@uwdata/mosaic-core 0.3.5 → 0.4.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.
@@ -12294,6 +12294,7 @@ function jsType(type) {
12294
12294
  case "TIMESTAMPTZ":
12295
12295
  case "TIMESTAMP WITH TIME ZONE":
12296
12296
  case "TIME":
12297
+ case "TIMESTAMP_NS":
12297
12298
  return "date";
12298
12299
  case "BOOLEAN":
12299
12300
  return "boolean";
@@ -12585,7 +12586,7 @@ function getIndexColumns(client) {
12585
12586
  const dims = [];
12586
12587
  let count2;
12587
12588
  for (const { as, expr: { aggregate } } of q2.select()) {
12588
- switch (aggregate?.toUpperCase()) {
12589
+ switch (aggregate?.toUpperCase?.()) {
12589
12590
  case "COUNT":
12590
12591
  case "SUM":
12591
12592
  aggr.push({ [as]: sql`SUM("${as}")::DOUBLE` });
@@ -7,4 +7,4 @@ ${t}`),new Function("x",`${t}
7
7
  return true;`)}function yd(r){return typeof r!="bigint"?oe(r):`${oe(r)}n`}var So=(r,t)=>(Math.ceil(r)*t+63&-64||64)/t,gd=(r,t=0)=>r.length>=t?r.subarray(0,t):Lr(new r.constructor(t),r,0),Ye=class{constructor(t,e=1){this.buffer=t,this.stride=e,this.BYTES_PER_ELEMENT=t.BYTES_PER_ELEMENT,this.ArrayType=t.constructor,this._resize(this.length=Math.ceil(t.length/e))}get byteLength(){return Math.ceil(this.length*this.stride)*this.BYTES_PER_ELEMENT}get reservedLength(){return this.buffer.length/this.stride}get reservedByteLength(){return this.buffer.byteLength}set(t,e){return this}append(t){return this.set(this.length,t)}reserve(t){if(t>0){this.length+=t;let e=this.stride,i=this.length*e,n=this.buffer.length;i>=n&&this._resize(n===0?So(i*1,this.BYTES_PER_ELEMENT):So(i*2,this.BYTES_PER_ELEMENT))}return this}flush(t=this.length){t=So(t*this.stride,this.BYTES_PER_ELEMENT);let e=gd(this.buffer,t);return this.clear(),e}clear(){return this.length=0,this._resize(0),this}_resize(t){return this.buffer=Lr(new this.ArrayType(t),this.buffer)}};Ye.prototype.offset=0;var Fe=class extends Ye{last(){return this.get(this.length-1)}get(t){return this.buffer[t]}set(t,e){return this.reserve(t-this.length+1),this.buffer[t*this.stride]=e,this}},qr=class extends Fe{constructor(t=new Uint8Array(0)){super(t,1/8),this.numValid=0}get numInvalid(){return this.length-this.numValid}get(t){return this.buffer[t>>3]>>t%8&1}set(t,e){let{buffer:i}=this.reserve(t-this.length+1),n=t>>3,s=t%8,o=i[n]>>s&1;return e?o===0&&(i[n]|=1<<s,++this.numValid):o===1&&(i[n]&=~(1<<s),--this.numValid),this}clear(){return this.numValid=0,super.clear()}},Gr=class extends Fe{constructor(t=new Int32Array(1)){super(t,1)}append(t){return this.set(this.length-1,t)}set(t,e){let i=this.length-1,n=this.reserve(t-i+1).buffer;return i<t++&&n.fill(n[i],i,t),n[t]=n[t-1]+e,this}flush(t=this.length-1){return t>this.length&&this.set(t-1,0),super.flush(t+1)}};var K=class{static throughNode(t){throw new Error('"throughNode" not available in this environment')}static throughDOM(t){throw new Error('"throughDOM" not available in this environment')}constructor({type:t,nullValues:e}){this.length=0,this.finished=!1,this.type=t,this.children=[],this.nullValues=e,this.stride=Bt(t),this._nulls=new qr,e&&e.length>0&&(this._isValid=Sc(e))}toVector(){return new L([this.flush()])}get ArrayType(){return this.type.ArrayType}get nullCount(){return this._nulls.numInvalid}get numChildren(){return this.children.length}get byteLength(){let t=0,{_offsets:e,_values:i,_nulls:n,_typeIds:s,children:o}=this;return e&&(t+=e.byteLength),i&&(t+=i.byteLength),n&&(t+=n.byteLength),s&&(t+=s.byteLength),o.reduce((a,c)=>a+c.byteLength,t)}get reservedLength(){return this._nulls.reservedLength}get reservedByteLength(){let t=0;return this._offsets&&(t+=this._offsets.reservedByteLength),this._values&&(t+=this._values.reservedByteLength),this._nulls&&(t+=this._nulls.reservedByteLength),this._typeIds&&(t+=this._typeIds.reservedByteLength),this.children.reduce((e,i)=>e+i.reservedByteLength,t)}get valueOffsets(){return this._offsets?this._offsets.buffer:null}get values(){return this._values?this._values.buffer:null}get nullBitmap(){return this._nulls?this._nulls.buffer:null}get typeIds(){return this._typeIds?this._typeIds.buffer:null}append(t){return this.set(this.length,t)}isValid(t){return this._isValid(t)}set(t,e){return this.setValid(t,this.isValid(e))&&this.setValue(t,e),this}setValue(t,e){this._setValue(this,t,e)}setValid(t,e){return this.length=this._nulls.set(t,+e).length,e}addChild(t,e=`${this.numChildren}`){throw new Error(`Cannot append children to non-nested type "${this.type}"`)}getChildAt(t){return this.children[t]||null}flush(){let t,e,i,n,{type:s,length:o,nullCount:a,_typeIds:c,_offsets:l,_values:d,_nulls:h}=this;(e=c?.flush(o))?n=l?.flush(o):(n=l?.flush(o))?t=d?.flush(l.last()):t=d?.flush(o),a>0&&(i=h?.flush(o));let f=this.children.map(g=>g.flush());return this.clear(),x({type:s,length:o,nullCount:a,children:f,child:f[0],data:t,typeIds:e,nullBitmap:i,valueOffsets:n})}finish(){this.finished=!0;for(let t of this.children)t.finish();return this}clear(){var t,e,i,n;this.length=0,(t=this._nulls)===null||t===void 0||t.clear(),(e=this._values)===null||e===void 0||e.clear(),(i=this._offsets)===null||i===void 0||i.clear(),(n=this._typeIds)===null||n===void 0||n.clear();for(let s of this.children)s.clear();return this}};K.prototype.length=1;K.prototype.stride=1;K.prototype.children=null;K.prototype.finished=!1;K.prototype.nullValues=null;K.prototype._isValid=()=>!0;var ct=class extends K{constructor(t){super(t),this._values=new Fe(new this.ArrayType(0),this.stride)}setValue(t,e){let i=this._values;return i.reserve(t-i.length+1),super.setValue(t,e)}},ue=class extends K{constructor(t){super(t),this._pendingLength=0,this._offsets=new Gr}setValue(t,e){let i=this._pending||(this._pending=new Map),n=i.get(t);n&&(this._pendingLength-=n.length),this._pendingLength+=e instanceof ce?e[Ut].length:e.length,i.set(t,e)}setValid(t,e){return super.setValid(t,e)?!0:((this._pending||(this._pending=new Map)).set(t,void 0),!1)}clear(){return this._pendingLength=0,this._pending=void 0,super.clear()}flush(){return this._flush(),super.flush()}finish(){return this._flush(),super.finish()}_flush(){let t=this._pending,e=this._pendingLength;return this._pendingLength=0,this._pending=void 0,t&&t.size>0&&this._flushPending(t,e),this}};var pr=class{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}offset(){return this.bb.readInt64(this.bb_pos)}metaDataLength(){return this.bb.readInt32(this.bb_pos+8)}bodyLength(){return this.bb.readInt64(this.bb_pos+16)}static sizeOf(){return 24}static createBlock(t,e,i,n){return t.prep(8,24),t.writeInt64(BigInt(n??0)),t.pad(4),t.writeInt32(i),t.writeInt64(BigInt(e??0)),t.offset()}};var de=new Int32Array(2),Yn=new Float32Array(de.buffer),Hn=new Float64Array(de.buffer),Wr=new Uint16Array(new Uint8Array([1,0]).buffer)[0]===1;var yi;(function(r){r[r.UTF8_BYTES=1]="UTF8_BYTES",r[r.UTF16_STRING=2]="UTF16_STRING"})(yi||(yi={}));var Ft=class r{constructor(t){this.bytes_=t,this.position_=0,this.text_decoder_=new TextDecoder}static allocate(t){return new r(new Uint8Array(t))}clear(){this.position_=0}bytes(){return this.bytes_}position(){return this.position_}setPosition(t){this.position_=t}capacity(){return this.bytes_.length}readInt8(t){return this.readUint8(t)<<24>>24}readUint8(t){return this.bytes_[t]}readInt16(t){return this.readUint16(t)<<16>>16}readUint16(t){return this.bytes_[t]|this.bytes_[t+1]<<8}readInt32(t){return this.bytes_[t]|this.bytes_[t+1]<<8|this.bytes_[t+2]<<16|this.bytes_[t+3]<<24}readUint32(t){return this.readInt32(t)>>>0}readInt64(t){return BigInt.asIntN(64,BigInt(this.readUint32(t))+(BigInt(this.readUint32(t+4))<<BigInt(32)))}readUint64(t){return BigInt.asUintN(64,BigInt(this.readUint32(t))+(BigInt(this.readUint32(t+4))<<BigInt(32)))}readFloat32(t){return de[0]=this.readInt32(t),Yn[0]}readFloat64(t){return de[Wr?0:1]=this.readInt32(t),de[Wr?1:0]=this.readInt32(t+4),Hn[0]}writeInt8(t,e){this.bytes_[t]=e}writeUint8(t,e){this.bytes_[t]=e}writeInt16(t,e){this.bytes_[t]=e,this.bytes_[t+1]=e>>8}writeUint16(t,e){this.bytes_[t]=e,this.bytes_[t+1]=e>>8}writeInt32(t,e){this.bytes_[t]=e,this.bytes_[t+1]=e>>8,this.bytes_[t+2]=e>>16,this.bytes_[t+3]=e>>24}writeUint32(t,e){this.bytes_[t]=e,this.bytes_[t+1]=e>>8,this.bytes_[t+2]=e>>16,this.bytes_[t+3]=e>>24}writeInt64(t,e){this.writeInt32(t,Number(BigInt.asIntN(32,e))),this.writeInt32(t+4,Number(BigInt.asIntN(32,e>>BigInt(32))))}writeUint64(t,e){this.writeUint32(t,Number(BigInt.asUintN(32,e))),this.writeUint32(t+4,Number(BigInt.asUintN(32,e>>BigInt(32))))}writeFloat32(t,e){Yn[0]=e,this.writeInt32(t,de[0])}writeFloat64(t,e){Hn[0]=e,this.writeInt32(t,de[Wr?0:1]),this.writeInt32(t+4,de[Wr?1:0])}getBufferIdentifier(){if(this.bytes_.length<this.position_+4+4)throw new Error("FlatBuffers: ByteBuffer is too short to contain an identifier.");let t="";for(let e=0;e<4;e++)t+=String.fromCharCode(this.readInt8(this.position_+4+e));return t}__offset(t,e){let i=t-this.readInt32(t);return e<this.readInt16(i)?this.readInt16(i+e):0}__union(t,e){return t.bb_pos=e+this.readInt32(e),t.bb=this,t}__string(t,e){t+=this.readInt32(t);let i=this.readInt32(t);t+=4;let n=this.bytes_.subarray(t,t+i);return e===yi.UTF8_BYTES?n:this.text_decoder_.decode(n)}__union_with_string(t,e){return typeof t=="string"?this.__string(e):this.__union(t,e)}__indirect(t){return t+this.readInt32(t)}__vector(t){return t+this.readInt32(t)+4}__vector_len(t){return this.readInt32(t+this.readInt32(t))}__has_identifier(t){if(t.length!=4)throw new Error("FlatBuffers: file identifier must be length "+4);for(let e=0;e<4;e++)if(t.charCodeAt(e)!=this.readInt8(this.position()+4+e))return!1;return!0}createScalarList(t,e){let i=[];for(let n=0;n<e;++n){let s=t(n);s!==null&&i.push(s)}return i}createObjList(t,e){let i=[];for(let n=0;n<e;++n){let s=t(n);s!==null&&i.push(s.unpack())}return i}};var mr=class r{constructor(t){this.minalign=1,this.vtable=null,this.vtable_in_use=0,this.isNested=!1,this.object_start=0,this.vtables=[],this.vector_num_elems=0,this.force_defaults=!1,this.string_maps=null,this.text_encoder=new TextEncoder;let e;t?e=t:e=1024,this.bb=Ft.allocate(e),this.space=e}clear(){this.bb.clear(),this.space=this.bb.capacity(),this.minalign=1,this.vtable=null,this.vtable_in_use=0,this.isNested=!1,this.object_start=0,this.vtables=[],this.vector_num_elems=0,this.force_defaults=!1,this.string_maps=null}forceDefaults(t){this.force_defaults=t}dataBuffer(){return this.bb}asUint8Array(){return this.bb.bytes().subarray(this.bb.position(),this.bb.position()+this.offset())}prep(t,e){t>this.minalign&&(this.minalign=t);let i=~(this.bb.capacity()-this.space+e)+1&t-1;for(;this.space<i+t+e;){let n=this.bb.capacity();this.bb=r.growByteBuffer(this.bb),this.space+=this.bb.capacity()-n}this.pad(i)}pad(t){for(let e=0;e<t;e++)this.bb.writeInt8(--this.space,0)}writeInt8(t){this.bb.writeInt8(this.space-=1,t)}writeInt16(t){this.bb.writeInt16(this.space-=2,t)}writeInt32(t){this.bb.writeInt32(this.space-=4,t)}writeInt64(t){this.bb.writeInt64(this.space-=8,t)}writeFloat32(t){this.bb.writeFloat32(this.space-=4,t)}writeFloat64(t){this.bb.writeFloat64(this.space-=8,t)}addInt8(t){this.prep(1,0),this.writeInt8(t)}addInt16(t){this.prep(2,0),this.writeInt16(t)}addInt32(t){this.prep(4,0),this.writeInt32(t)}addInt64(t){this.prep(8,0),this.writeInt64(t)}addFloat32(t){this.prep(4,0),this.writeFloat32(t)}addFloat64(t){this.prep(8,0),this.writeFloat64(t)}addFieldInt8(t,e,i){(this.force_defaults||e!=i)&&(this.addInt8(e),this.slot(t))}addFieldInt16(t,e,i){(this.force_defaults||e!=i)&&(this.addInt16(e),this.slot(t))}addFieldInt32(t,e,i){(this.force_defaults||e!=i)&&(this.addInt32(e),this.slot(t))}addFieldInt64(t,e,i){(this.force_defaults||e!==i)&&(this.addInt64(e),this.slot(t))}addFieldFloat32(t,e,i){(this.force_defaults||e!=i)&&(this.addFloat32(e),this.slot(t))}addFieldFloat64(t,e,i){(this.force_defaults||e!=i)&&(this.addFloat64(e),this.slot(t))}addFieldOffset(t,e,i){(this.force_defaults||e!=i)&&(this.addOffset(e),this.slot(t))}addFieldStruct(t,e,i){e!=i&&(this.nested(e),this.slot(t))}nested(t){if(t!=this.offset())throw new TypeError("FlatBuffers: struct must be serialized inline.")}notNested(){if(this.isNested)throw new TypeError("FlatBuffers: object serialization must not be nested.")}slot(t){this.vtable!==null&&(this.vtable[t]=this.offset())}offset(){return this.bb.capacity()-this.space}static growByteBuffer(t){let e=t.capacity();if(e&3221225472)throw new Error("FlatBuffers: cannot grow buffer beyond 2 gigabytes.");let i=e<<1,n=Ft.allocate(i);return n.setPosition(i-e),n.bytes().set(t.bytes(),i-e),n}addOffset(t){this.prep(4,0),this.writeInt32(this.offset()-t+4)}startObject(t){this.notNested(),this.vtable==null&&(this.vtable=[]),this.vtable_in_use=t;for(let e=0;e<t;e++)this.vtable[e]=0;this.isNested=!0,this.object_start=this.offset()}endObject(){if(this.vtable==null||!this.isNested)throw new Error("FlatBuffers: endObject called without startObject");this.addInt32(0);let t=this.offset(),e=this.vtable_in_use-1;for(;e>=0&&this.vtable[e]==0;e--);let i=e+1;for(;e>=0;e--)this.addInt16(this.vtable[e]!=0?t-this.vtable[e]:0);let n=2;this.addInt16(t-this.object_start);let s=(i+n)*2;this.addInt16(s);let o=0,a=this.space;t:for(e=0;e<this.vtables.length;e++){let c=this.bb.capacity()-this.vtables[e];if(s==this.bb.readInt16(c)){for(let l=2;l<s;l+=2)if(this.bb.readInt16(a+l)!=this.bb.readInt16(c+l))continue t;o=this.vtables[e];break}}return o?(this.space=this.bb.capacity()-t,this.bb.writeInt32(this.space,o-t)):(this.vtables.push(this.offset()),this.bb.writeInt32(this.bb.capacity()-t,this.offset()-t)),this.isNested=!1,t}finish(t,e,i){let n=i?4:0;if(e){let s=e;if(this.prep(this.minalign,8+n),s.length!=4)throw new TypeError("FlatBuffers: file identifier must be length "+4);for(let o=3;o>=0;o--)this.writeInt8(s.charCodeAt(o))}this.prep(this.minalign,4+n),this.addOffset(t),n&&this.addInt32(this.bb.capacity()-this.space),this.bb.setPosition(this.space)}finishSizePrefixed(t,e){this.finish(t,e,!0)}requiredField(t,e){let i=this.bb.capacity()-t,n=i-this.bb.readInt32(i);if(!(e<this.bb.readInt16(n)&&this.bb.readInt16(n+e)!=0))throw new TypeError("FlatBuffers: field "+e+" must be set")}startVector(t,e,i){this.notNested(),this.vector_num_elems=e,this.prep(4,t*e),this.prep(i,t*e)}endVector(){return this.writeInt32(this.vector_num_elems),this.offset()}createSharedString(t){if(!t)return 0;if(this.string_maps||(this.string_maps=new Map),this.string_maps.has(t))return this.string_maps.get(t);let e=this.createString(t);return this.string_maps.set(t,e),e}createString(t){if(t==null)return 0;let e;t instanceof Uint8Array?e=t:e=this.text_encoder.encode(t),this.addInt8(0),this.startVector(1,e.length,1),this.bb.setPosition(this.space-=e.length);for(let i=0,n=this.space,s=this.bb.bytes();i<e.length;i++)s[n++]=e[i];return this.endVector()}createObjectOffset(t){return t===null?0:typeof t=="string"?this.createString(t):t.pack(this)}createObjectOffsetList(t){let e=[];for(let i=0;i<t.length;++i){let n=t[i];if(n!==null)e.push(this.createObjectOffset(n));else throw new TypeError("FlatBuffers: Argument for createObjectOffsetList cannot contain null.")}return e}createStructOffsetList(t,e){return e(this,t.length),this.createObjectOffsetList(t.slice().reverse()),this.endVector()}};var st=class r{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsKeyValue(t,e){return(e||new r).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsKeyValue(t,e){return t.setPosition(t.position()+4),(e||new r).__init(t.readInt32(t.position())+t.position(),t)}key(t){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__string(this.bb_pos+e,t):null}value(t){let e=this.bb.__offset(this.bb_pos,6);return e?this.bb.__string(this.bb_pos+e,t):null}static startKeyValue(t){t.startObject(2)}static addKey(t,e){t.addFieldOffset(0,e,0)}static addValue(t,e){t.addFieldOffset(1,e,0)}static endKeyValue(t){return t.endObject()}static createKeyValue(t,e,i){return r.startKeyValue(t),r.addKey(t,e),r.addValue(t,i),r.endKeyValue(t)}};var He;(function(r){r[r.V1=0]="V1",r[r.V2=1]="V2",r[r.V3=2]="V3",r[r.V4=3]="V4",r[r.V5=4]="V5"})(He||(He={}));var Ke;(function(r){r[r.Little=0]="Little",r[r.Big=1]="Big"})(Ke||(Ke={}));var gi;(function(r){r[r.DenseArray=0]="DenseArray"})(gi||(gi={}));var Zt=class r{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsInt(t,e){return(e||new r).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsInt(t,e){return t.setPosition(t.position()+4),(e||new r).__init(t.readInt32(t.position())+t.position(),t)}bitWidth(){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.readInt32(this.bb_pos+t):0}isSigned(){let t=this.bb.__offset(this.bb_pos,6);return t?!!this.bb.readInt8(this.bb_pos+t):!1}static startInt(t){t.startObject(2)}static addBitWidth(t,e){t.addFieldInt32(0,e,0)}static addIsSigned(t,e){t.addFieldInt8(1,+e,0)}static endInt(t){return t.endObject()}static createInt(t,e,i){return r.startInt(t),r.addBitWidth(t,e),r.addIsSigned(t,i),r.endInt(t)}};var he=class r{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsDictionaryEncoding(t,e){return(e||new r).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsDictionaryEncoding(t,e){return t.setPosition(t.position()+4),(e||new r).__init(t.readInt32(t.position())+t.position(),t)}id(){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.readInt64(this.bb_pos+t):BigInt("0")}indexType(t){let e=this.bb.__offset(this.bb_pos,6);return e?(t||new Zt).__init(this.bb.__indirect(this.bb_pos+e),this.bb):null}isOrdered(){let t=this.bb.__offset(this.bb_pos,8);return t?!!this.bb.readInt8(this.bb_pos+t):!1}dictionaryKind(){let t=this.bb.__offset(this.bb_pos,10);return t?this.bb.readInt16(this.bb_pos+t):gi.DenseArray}static startDictionaryEncoding(t){t.startObject(4)}static addId(t,e){t.addFieldInt64(0,e,BigInt("0"))}static addIndexType(t,e){t.addFieldOffset(1,e,0)}static addIsOrdered(t,e){t.addFieldInt8(2,+e,0)}static addDictionaryKind(t,e){t.addFieldInt16(3,e,gi.DenseArray)}static endDictionaryEncoding(t){return t.endObject()}};var bi=class r{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsBinary(t,e){return(e||new r).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsBinary(t,e){return t.setPosition(t.position()+4),(e||new r).__init(t.readInt32(t.position())+t.position(),t)}static startBinary(t){t.startObject(0)}static endBinary(t){return t.endObject()}static createBinary(t){return r.startBinary(t),r.endBinary(t)}};var _i=class r{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsBool(t,e){return(e||new r).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsBool(t,e){return t.setPosition(t.position()+4),(e||new r).__init(t.readInt32(t.position())+t.position(),t)}static startBool(t){t.startObject(0)}static endBool(t){return t.endObject()}static createBool(t){return r.startBool(t),r.endBool(t)}};var wi;(function(r){r[r.DAY=0]="DAY",r[r.MILLISECOND=1]="MILLISECOND"})(wi||(wi={}));var Qe=class r{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsDate(t,e){return(e||new r).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsDate(t,e){return t.setPosition(t.position()+4),(e||new r).__init(t.readInt32(t.position())+t.position(),t)}unit(){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.readInt16(this.bb_pos+t):wi.MILLISECOND}static startDate(t){t.startObject(1)}static addUnit(t,e){t.addFieldInt16(0,e,wi.MILLISECOND)}static endDate(t){return t.endObject()}static createDate(t,e){return r.startDate(t),r.addUnit(t,e),r.endDate(t)}};var fe=class r{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsDecimal(t,e){return(e||new r).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsDecimal(t,e){return t.setPosition(t.position()+4),(e||new r).__init(t.readInt32(t.position())+t.position(),t)}precision(){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.readInt32(this.bb_pos+t):0}scale(){let t=this.bb.__offset(this.bb_pos,6);return t?this.bb.readInt32(this.bb_pos+t):0}bitWidth(){let t=this.bb.__offset(this.bb_pos,8);return t?this.bb.readInt32(this.bb_pos+t):128}static startDecimal(t){t.startObject(3)}static addPrecision(t,e){t.addFieldInt32(0,e,0)}static addScale(t,e){t.addFieldInt32(1,e,0)}static addBitWidth(t,e){t.addFieldInt32(2,e,128)}static endDecimal(t){return t.endObject()}static createDecimal(t,e,i,n){return r.startDecimal(t),r.addPrecision(t,e),r.addScale(t,i),r.addBitWidth(t,n),r.endDecimal(t)}};var Je;(function(r){r[r.SECOND=0]="SECOND",r[r.MILLISECOND=1]="MILLISECOND",r[r.MICROSECOND=2]="MICROSECOND",r[r.NANOSECOND=3]="NANOSECOND"})(Je||(Je={}));var Xe=class r{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsFixedSizeBinary(t,e){return(e||new r).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsFixedSizeBinary(t,e){return t.setPosition(t.position()+4),(e||new r).__init(t.readInt32(t.position())+t.position(),t)}byteWidth(){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.readInt32(this.bb_pos+t):0}static startFixedSizeBinary(t){t.startObject(1)}static addByteWidth(t,e){t.addFieldInt32(0,e,0)}static endFixedSizeBinary(t){return t.endObject()}static createFixedSizeBinary(t,e){return r.startFixedSizeBinary(t),r.addByteWidth(t,e),r.endFixedSizeBinary(t)}};var Ze=class r{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsFixedSizeList(t,e){return(e||new r).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsFixedSizeList(t,e){return t.setPosition(t.position()+4),(e||new r).__init(t.readInt32(t.position())+t.position(),t)}listSize(){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.readInt32(this.bb_pos+t):0}static startFixedSizeList(t){t.startObject(1)}static addListSize(t,e){t.addFieldInt32(0,e,0)}static endFixedSizeList(t){return t.endObject()}static createFixedSizeList(t,e){return r.startFixedSizeList(t),r.addListSize(t,e),r.endFixedSizeList(t)}};var Ii;(function(r){r[r.HALF=0]="HALF",r[r.SINGLE=1]="SINGLE",r[r.DOUBLE=2]="DOUBLE"})(Ii||(Ii={}));var tr=class r{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsFloatingPoint(t,e){return(e||new r).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsFloatingPoint(t,e){return t.setPosition(t.position()+4),(e||new r).__init(t.readInt32(t.position())+t.position(),t)}precision(){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.readInt16(this.bb_pos+t):Ii.HALF}static startFloatingPoint(t){t.startObject(1)}static addPrecision(t,e){t.addFieldInt16(0,e,Ii.HALF)}static endFloatingPoint(t){return t.endObject()}static createFloatingPoint(t,e){return r.startFloatingPoint(t),r.addPrecision(t,e),r.endFloatingPoint(t)}};var vi;(function(r){r[r.YEAR_MONTH=0]="YEAR_MONTH",r[r.DAY_TIME=1]="DAY_TIME",r[r.MONTH_DAY_NANO=2]="MONTH_DAY_NANO"})(vi||(vi={}));var er=class r{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsInterval(t,e){return(e||new r).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsInterval(t,e){return t.setPosition(t.position()+4),(e||new r).__init(t.readInt32(t.position())+t.position(),t)}unit(){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.readInt16(this.bb_pos+t):vi.YEAR_MONTH}static startInterval(t){t.startObject(1)}static addUnit(t,e){t.addFieldInt16(0,e,vi.YEAR_MONTH)}static endInterval(t){return t.endObject()}static createInterval(t,e){return r.startInterval(t),r.addUnit(t,e),r.endInterval(t)}};var Si=class r{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsList(t,e){return(e||new r).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsList(t,e){return t.setPosition(t.position()+4),(e||new r).__init(t.readInt32(t.position())+t.position(),t)}static startList(t){t.startObject(0)}static endList(t){return t.endObject()}static createList(t){return r.startList(t),r.endList(t)}};var rr=class r{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsMap(t,e){return(e||new r).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsMap(t,e){return t.setPosition(t.position()+4),(e||new r).__init(t.readInt32(t.position())+t.position(),t)}keysSorted(){let t=this.bb.__offset(this.bb_pos,4);return t?!!this.bb.readInt8(this.bb_pos+t):!1}static startMap(t){t.startObject(1)}static addKeysSorted(t,e){t.addFieldInt8(0,+e,0)}static endMap(t){return t.endObject()}static createMap(t,e){return r.startMap(t),r.addKeysSorted(t,e),r.endMap(t)}};var Ti=class r{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsNull(t,e){return(e||new r).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsNull(t,e){return t.setPosition(t.position()+4),(e||new r).__init(t.readInt32(t.position())+t.position(),t)}static startNull(t){t.startObject(0)}static endNull(t){return t.endObject()}static createNull(t){return r.startNull(t),r.endNull(t)}};var Ei=class r{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsStruct_(t,e){return(e||new r).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsStruct_(t,e){return t.setPosition(t.position()+4),(e||new r).__init(t.readInt32(t.position())+t.position(),t)}static startStruct_(t){t.startObject(0)}static endStruct_(t){return t.endObject()}static createStruct_(t){return r.startStruct_(t),r.endStruct_(t)}};var Re=class r{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsTime(t,e){return(e||new r).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsTime(t,e){return t.setPosition(t.position()+4),(e||new r).__init(t.readInt32(t.position())+t.position(),t)}unit(){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.readInt16(this.bb_pos+t):Je.MILLISECOND}bitWidth(){let t=this.bb.__offset(this.bb_pos,6);return t?this.bb.readInt32(this.bb_pos+t):32}static startTime(t){t.startObject(2)}static addUnit(t,e){t.addFieldInt16(0,e,Je.MILLISECOND)}static addBitWidth(t,e){t.addFieldInt32(1,e,32)}static endTime(t){return t.endObject()}static createTime(t,e,i){return r.startTime(t),r.addUnit(t,e),r.addBitWidth(t,i),r.endTime(t)}};var De=class r{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsTimestamp(t,e){return(e||new r).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsTimestamp(t,e){return t.setPosition(t.position()+4),(e||new r).__init(t.readInt32(t.position())+t.position(),t)}unit(){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.readInt16(this.bb_pos+t):Je.SECOND}timezone(t){let e=this.bb.__offset(this.bb_pos,6);return e?this.bb.__string(this.bb_pos+e,t):null}static startTimestamp(t){t.startObject(2)}static addUnit(t,e){t.addFieldInt16(0,e,Je.SECOND)}static addTimezone(t,e){t.addFieldOffset(1,e,0)}static endTimestamp(t){return t.endObject()}static createTimestamp(t,e,i){return r.startTimestamp(t),r.addUnit(t,e),r.addTimezone(t,i),r.endTimestamp(t)}};var xi;(function(r){r[r.Sparse=0]="Sparse",r[r.Dense=1]="Dense"})(xi||(xi={}));var te=class r{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsUnion(t,e){return(e||new r).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsUnion(t,e){return t.setPosition(t.position()+4),(e||new r).__init(t.readInt32(t.position())+t.position(),t)}mode(){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.readInt16(this.bb_pos+t):xi.Sparse}typeIds(t){let e=this.bb.__offset(this.bb_pos,6);return e?this.bb.readInt32(this.bb.__vector(this.bb_pos+e)+t*4):0}typeIdsLength(){let t=this.bb.__offset(this.bb_pos,6);return t?this.bb.__vector_len(this.bb_pos+t):0}typeIdsArray(){let t=this.bb.__offset(this.bb_pos,6);return t?new Int32Array(this.bb.bytes().buffer,this.bb.bytes().byteOffset+this.bb.__vector(this.bb_pos+t),this.bb.__vector_len(this.bb_pos+t)):null}static startUnion(t){t.startObject(2)}static addMode(t,e){t.addFieldInt16(0,e,xi.Sparse)}static addTypeIds(t,e){t.addFieldOffset(1,e,0)}static createTypeIdsVector(t,e){t.startVector(4,e.length,4);for(let i=e.length-1;i>=0;i--)t.addInt32(e[i]);return t.endVector()}static startTypeIdsVector(t,e){t.startVector(4,e,4)}static endUnion(t){return t.endObject()}static createUnion(t,e,i){return r.startUnion(t),r.addMode(t,e),r.addTypeIds(t,i),r.endUnion(t)}};var Ai=class r{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsUtf8(t,e){return(e||new r).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsUtf8(t,e){return t.setPosition(t.position()+4),(e||new r).__init(t.readInt32(t.position())+t.position(),t)}static startUtf8(t){t.startObject(0)}static endUtf8(t){return t.endObject()}static createUtf8(t){return r.startUtf8(t),r.endUtf8(t)}};var Q;(function(r){r[r.NONE=0]="NONE",r[r.Null=1]="Null",r[r.Int=2]="Int",r[r.FloatingPoint=3]="FloatingPoint",r[r.Binary=4]="Binary",r[r.Utf8=5]="Utf8",r[r.Bool=6]="Bool",r[r.Decimal=7]="Decimal",r[r.Date=8]="Date",r[r.Time=9]="Time",r[r.Timestamp=10]="Timestamp",r[r.Interval=11]="Interval",r[r.List=12]="List",r[r.Struct_=13]="Struct_",r[r.Union=14]="Union",r[r.FixedSizeBinary=15]="FixedSizeBinary",r[r.FixedSizeList=16]="FixedSizeList",r[r.Map=17]="Map",r[r.Duration=18]="Duration",r[r.LargeBinary=19]="LargeBinary",r[r.LargeUtf8=20]="LargeUtf8",r[r.LargeList=21]="LargeList",r[r.RunEndEncoded=22]="RunEndEncoded"})(Q||(Q={}));var pt=class r{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsField(t,e){return(e||new r).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsField(t,e){return t.setPosition(t.position()+4),(e||new r).__init(t.readInt32(t.position())+t.position(),t)}name(t){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__string(this.bb_pos+e,t):null}nullable(){let t=this.bb.__offset(this.bb_pos,6);return t?!!this.bb.readInt8(this.bb_pos+t):!1}typeType(){let t=this.bb.__offset(this.bb_pos,8);return t?this.bb.readUint8(this.bb_pos+t):Q.NONE}type(t){let e=this.bb.__offset(this.bb_pos,10);return e?this.bb.__union(t,this.bb_pos+e):null}dictionary(t){let e=this.bb.__offset(this.bb_pos,12);return e?(t||new he).__init(this.bb.__indirect(this.bb_pos+e),this.bb):null}children(t,e){let i=this.bb.__offset(this.bb_pos,14);return i?(e||new r).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+i)+t*4),this.bb):null}childrenLength(){let t=this.bb.__offset(this.bb_pos,14);return t?this.bb.__vector_len(this.bb_pos+t):0}customMetadata(t,e){let i=this.bb.__offset(this.bb_pos,16);return i?(e||new st).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+i)+t*4),this.bb):null}customMetadataLength(){let t=this.bb.__offset(this.bb_pos,16);return t?this.bb.__vector_len(this.bb_pos+t):0}static startField(t){t.startObject(7)}static addName(t,e){t.addFieldOffset(0,e,0)}static addNullable(t,e){t.addFieldInt8(1,+e,0)}static addTypeType(t,e){t.addFieldInt8(2,e,Q.NONE)}static addType(t,e){t.addFieldOffset(3,e,0)}static addDictionary(t,e){t.addFieldOffset(4,e,0)}static addChildren(t,e){t.addFieldOffset(5,e,0)}static createChildrenVector(t,e){t.startVector(4,e.length,4);for(let i=e.length-1;i>=0;i--)t.addOffset(e[i]);return t.endVector()}static startChildrenVector(t,e){t.startVector(4,e,4)}static addCustomMetadata(t,e){t.addFieldOffset(6,e,0)}static createCustomMetadataVector(t,e){t.startVector(4,e.length,4);for(let i=e.length-1;i>=0;i--)t.addOffset(e[i]);return t.endVector()}static startCustomMetadataVector(t,e){t.startVector(4,e,4)}static endField(t){return t.endObject()}};var wt=class r{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsSchema(t,e){return(e||new r).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsSchema(t,e){return t.setPosition(t.position()+4),(e||new r).__init(t.readInt32(t.position())+t.position(),t)}endianness(){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.readInt16(this.bb_pos+t):Ke.Little}fields(t,e){let i=this.bb.__offset(this.bb_pos,6);return i?(e||new pt).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+i)+t*4),this.bb):null}fieldsLength(){let t=this.bb.__offset(this.bb_pos,6);return t?this.bb.__vector_len(this.bb_pos+t):0}customMetadata(t,e){let i=this.bb.__offset(this.bb_pos,8);return i?(e||new st).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+i)+t*4),this.bb):null}customMetadataLength(){let t=this.bb.__offset(this.bb_pos,8);return t?this.bb.__vector_len(this.bb_pos+t):0}features(t){let e=this.bb.__offset(this.bb_pos,10);return e?this.bb.readInt64(this.bb.__vector(this.bb_pos+e)+t*8):BigInt(0)}featuresLength(){let t=this.bb.__offset(this.bb_pos,10);return t?this.bb.__vector_len(this.bb_pos+t):0}static startSchema(t){t.startObject(4)}static addEndianness(t,e){t.addFieldInt16(0,e,Ke.Little)}static addFields(t,e){t.addFieldOffset(1,e,0)}static createFieldsVector(t,e){t.startVector(4,e.length,4);for(let i=e.length-1;i>=0;i--)t.addOffset(e[i]);return t.endVector()}static startFieldsVector(t,e){t.startVector(4,e,4)}static addCustomMetadata(t,e){t.addFieldOffset(2,e,0)}static createCustomMetadataVector(t,e){t.startVector(4,e.length,4);for(let i=e.length-1;i>=0;i--)t.addOffset(e[i]);return t.endVector()}static startCustomMetadataVector(t,e){t.startVector(4,e,4)}static addFeatures(t,e){t.addFieldOffset(3,e,0)}static createFeaturesVector(t,e){t.startVector(8,e.length,8);for(let i=e.length-1;i>=0;i--)t.addInt64(e[i]);return t.endVector()}static startFeaturesVector(t,e){t.startVector(8,e,8)}static endSchema(t){return t.endObject()}static finishSchemaBuffer(t,e){t.finish(e)}static finishSizePrefixedSchemaBuffer(t,e){t.finish(e,void 0,!0)}static createSchema(t,e,i,n,s){return r.startSchema(t),r.addEndianness(t,e),r.addFields(t,i),r.addCustomMetadata(t,n),r.addFeatures(t,s),r.endSchema(t)}};var Rt=class r{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsFooter(t,e){return(e||new r).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsFooter(t,e){return t.setPosition(t.position()+4),(e||new r).__init(t.readInt32(t.position())+t.position(),t)}version(){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.readInt16(this.bb_pos+t):He.V1}schema(t){let e=this.bb.__offset(this.bb_pos,6);return e?(t||new wt).__init(this.bb.__indirect(this.bb_pos+e),this.bb):null}dictionaries(t,e){let i=this.bb.__offset(this.bb_pos,8);return i?(e||new pr).__init(this.bb.__vector(this.bb_pos+i)+t*24,this.bb):null}dictionariesLength(){let t=this.bb.__offset(this.bb_pos,8);return t?this.bb.__vector_len(this.bb_pos+t):0}recordBatches(t,e){let i=this.bb.__offset(this.bb_pos,10);return i?(e||new pr).__init(this.bb.__vector(this.bb_pos+i)+t*24,this.bb):null}recordBatchesLength(){let t=this.bb.__offset(this.bb_pos,10);return t?this.bb.__vector_len(this.bb_pos+t):0}customMetadata(t,e){let i=this.bb.__offset(this.bb_pos,12);return i?(e||new st).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+i)+t*4),this.bb):null}customMetadataLength(){let t=this.bb.__offset(this.bb_pos,12);return t?this.bb.__vector_len(this.bb_pos+t):0}static startFooter(t){t.startObject(5)}static addVersion(t,e){t.addFieldInt16(0,e,He.V1)}static addSchema(t,e){t.addFieldOffset(1,e,0)}static addDictionaries(t,e){t.addFieldOffset(2,e,0)}static startDictionariesVector(t,e){t.startVector(24,e,8)}static addRecordBatches(t,e){t.addFieldOffset(3,e,0)}static startRecordBatchesVector(t,e){t.startVector(24,e,8)}static addCustomMetadata(t,e){t.addFieldOffset(4,e,0)}static createCustomMetadataVector(t,e){t.startVector(4,e.length,4);for(let i=e.length-1;i>=0;i--)t.addOffset(e[i]);return t.endVector()}static startCustomMetadataVector(t,e){t.startVector(4,e,4)}static endFooter(t){return t.endObject()}static finishFooterBuffer(t,e){t.finish(e)}static finishSizePrefixedFooterBuffer(t,e){t.finish(e,void 0,!0)}};var j=class r{constructor(t=[],e,i){this.fields=t||[],this.metadata=e||new Map,i||(i=To(t)),this.dictionaries=i}get[Symbol.toStringTag](){return"Schema"}get names(){return this.fields.map(t=>t.name)}toString(){return`Schema<{ ${this.fields.map((t,e)=>`${e}: ${t}`).join(", ")} }>`}select(t){let e=new Set(t),i=this.fields.filter(n=>e.has(n.name));return new r(i,this.metadata)}selectAt(t){let e=t.map(i=>this.fields[i]).filter(Boolean);return new r(e,this.metadata)}assign(...t){let e=t[0]instanceof r?t[0]:Array.isArray(t[0])?new r(t[0]):new r(t),i=[...this.fields],n=Qn(Qn(new Map,this.metadata),e.metadata),s=e.fields.filter(a=>{let c=i.findIndex(l=>l.name===a.name);return~c?(i[c]=a.clone({metadata:Qn(Qn(new Map,i[c].metadata),a.metadata)}))&&!1:!0}),o=To(s,new Map);return new r([...i,...s],n,new Map([...this.dictionaries,...o]))}};j.prototype.fields=null;j.prototype.metadata=null;j.prototype.dictionaries=null;var R=class r{static new(...t){let[e,i,n,s]=t;return t[0]&&typeof t[0]=="object"&&({name:e}=t[0],i===void 0&&(i=t[0].type),n===void 0&&(n=t[0].nullable),s===void 0&&(s=t[0].metadata)),new r(`${e}`,i,n,s)}constructor(t,e,i=!1,n){this.name=t,this.type=e,this.nullable=i,this.metadata=n||new Map}get typeId(){return this.type.typeId}get[Symbol.toStringTag](){return"Field"}toString(){return`${this.name}: ${this.type}`}clone(...t){let[e,i,n,s]=t;return!t[0]||typeof t[0]!="object"?[e=this.name,i=this.type,n=this.nullable,s=this.metadata]=t:{name:e=this.name,type:i=this.type,nullable:n=this.nullable,metadata:s=this.metadata}=t[0],r.new(e,i,n,s)}};R.prototype.type=null;R.prototype.name=null;R.prototype.nullable=null;R.prototype.metadata=null;function Qn(r,t){return new Map([...r||new Map,...t||new Map])}function To(r,t=new Map){for(let e=-1,i=r.length;++e<i;){let s=r[e].type;if(y.isDictionary(s)){if(!t.has(s.id))t.set(s.id,s.dictionary);else if(t.get(s.id)!==s.dictionary)throw new Error("Cannot create Schema containing two different dictionaries with the same Id")}s.children&&s.children.length>0&&To(s.children,t)}return t}var bd=mr,_d=Ft,Le=class{static decode(t){t=new _d(S(t));let e=Rt.getRootAsFooter(t),i=j.decode(e.schema());return new Eo(i,e)}static encode(t){let e=new bd,i=j.encode(e,t.schema);Rt.startRecordBatchesVector(e,t.numRecordBatches);for(let o of[...t.recordBatches()].slice().reverse())Me.encode(e,o);let n=e.endVector();Rt.startDictionariesVector(e,t.numDictionaries);for(let o of[...t.dictionaryBatches()].slice().reverse())Me.encode(e,o);let s=e.endVector();return Rt.startFooter(e),Rt.addSchema(e,i),Rt.addVersion(e,at.V4),Rt.addRecordBatches(e,n),Rt.addDictionaries(e,s),Rt.finishFooterBuffer(e,Rt.endFooter(e)),e.asUint8Array()}get numRecordBatches(){return this._recordBatches.length}get numDictionaries(){return this._dictionaryBatches.length}constructor(t,e=at.V4,i,n){this.schema=t,this.version=e,i&&(this._recordBatches=i),n&&(this._dictionaryBatches=n)}*recordBatches(){for(let t,e=-1,i=this.numRecordBatches;++e<i;)(t=this.getRecordBatch(e))&&(yield t)}*dictionaryBatches(){for(let t,e=-1,i=this.numDictionaries;++e<i;)(t=this.getDictionaryBatch(e))&&(yield t)}getRecordBatch(t){return t>=0&&t<this.numRecordBatches&&this._recordBatches[t]||null}getDictionaryBatch(t){return t>=0&&t<this.numDictionaries&&this._dictionaryBatches[t]||null}};var Eo=class extends Le{get numRecordBatches(){return this._footer.recordBatchesLength()}get numDictionaries(){return this._footer.dictionariesLength()}constructor(t,e){super(t,e.version()),this._footer=e}getRecordBatch(t){if(t>=0&&t<this.numRecordBatches){let e=this._footer.recordBatches(t);if(e)return Me.decode(e)}return null}getDictionaryBatch(t){if(t>=0&&t<this.numDictionaries){let e=this._footer.dictionaries(t);if(e)return Me.decode(e)}return null}},Me=class r{static decode(t){return new r(t.metaDataLength(),t.bodyLength(),t.offset())}static encode(t,e){let{metaDataLength:i}=e,n=BigInt(e.offset),s=BigInt(e.bodyLength);return pr.createBlock(t,n,i,s)}constructor(t,e,i){this.metaDataLength=t,this.offset=bt(i),this.bodyLength=bt(e)}};var Y=Object.freeze({done:!0,value:void 0}),Oi=class{constructor(t){this._json=t}get schema(){return this._json.schema}get batches(){return this._json.batches||[]}get dictionaries(){return this._json.dictionaries||[]}},yr=class{tee(){return this._getDOMStream().tee()}pipe(t,e){return this._getNodeStream().pipe(t,e)}pipeTo(t,e){return this._getDOMStream().pipeTo(t,e)}pipeThrough(t,e){return this._getDOMStream().pipeThrough(t,e)}_getDOMStream(){return this._DOMStream||(this._DOMStream=this.toDOMStream())}_getNodeStream(){return this._nodeStream||(this._nodeStream=this.toNodeStream())}},Jn=class extends yr{constructor(){super(),this._values=[],this.resolvers=[],this._closedPromise=new Promise(t=>this._closedPromiseResolve=t)}get closed(){return this._closedPromise}cancel(t){return p(this,void 0,void 0,function*(){yield this.return(t)})}write(t){this._ensureOpen()&&(this.resolvers.length<=0?this._values.push(t):this.resolvers.shift().resolve({done:!1,value:t}))}abort(t){this._closedPromiseResolve&&(this.resolvers.length<=0?this._error={error:t}:this.resolvers.shift().reject({done:!0,value:t}))}close(){if(this._closedPromiseResolve){let{resolvers:t}=this;for(;t.length>0;)t.shift().resolve(Y);this._closedPromiseResolve(),this._closedPromiseResolve=void 0}}[Symbol.asyncIterator](){return this}toDOMStream(t){return ut.toDOMStream(this._closedPromiseResolve||this._error?this:this._values,t)}toNodeStream(t){return ut.toNodeStream(this._closedPromiseResolve||this._error?this:this._values,t)}throw(t){return p(this,void 0,void 0,function*(){return yield this.abort(t),Y})}return(t){return p(this,void 0,void 0,function*(){return yield this.close(),Y})}read(t){return p(this,void 0,void 0,function*(){return(yield this.next(t,"read")).value})}peek(t){return p(this,void 0,void 0,function*(){return(yield this.next(t,"peek")).value})}next(...t){return this._values.length>0?Promise.resolve({done:!1,value:this._values.shift()}):this._error?Promise.reject({done:!0,value:this._error.error}):this._closedPromiseResolve?new Promise((e,i)=>{this.resolvers.push({resolve:e,reject:i})}):Promise.resolve(Y)}_ensureOpen(){if(this._closedPromiseResolve)return!0;throw new Error("AsyncQueue is closed")}};var pe=class extends Jn{write(t){if((t=S(t)).byteLength>0)return super.write(t)}toString(t=!1){return t?oi(this.toUint8Array(!0)):this.toUint8Array(!1).then(oi)}toUint8Array(t=!1){return t?At(this._values)[0]:p(this,void 0,void 0,function*(){var e,i,n,s;let o=[],a=0;try{for(var c=!0,l=zt(this),d;d=yield l.next(),e=d.done,!e;c=!0){s=d.value,c=!1;let h=s;o.push(h),a+=h.byteLength}}catch(h){i={error:h}}finally{try{!c&&!e&&(n=l.return)&&(yield n.call(l))}finally{if(i)throw i.error}}return At(o,a)[0]})}},me=class{constructor(t){t&&(this.source=new xo(ut.fromIterable(t)))}[Symbol.iterator](){return this}next(t){return this.source.next(t)}throw(t){return this.source.throw(t)}return(t){return this.source.return(t)}peek(t){return this.source.peek(t)}read(t){return this.source.read(t)}},kt=class r{constructor(t){t instanceof r?this.source=t.source:t instanceof pe?this.source=new Ue(ut.fromAsyncIterable(t)):fn(t)?this.source=new Ue(ut.fromNodeStream(t)):ai(t)?this.source=new Ue(ut.fromDOMStream(t)):dn(t)?this.source=new Ue(ut.fromDOMStream(t.body)):$t(t)?this.source=new Ue(ut.fromIterable(t)):xt(t)?this.source=new Ue(ut.fromAsyncIterable(t)):Lt(t)&&(this.source=new Ue(ut.fromAsyncIterable(t)))}[Symbol.asyncIterator](){return this}next(t){return this.source.next(t)}throw(t){return this.source.throw(t)}return(t){return this.source.return(t)}get closed(){return this.source.closed}cancel(t){return this.source.cancel(t)}peek(t){return this.source.peek(t)}read(t){return this.source.read(t)}},xo=class{constructor(t){this.source=t}cancel(t){this.return(t)}peek(t){return this.next(t,"peek").value}read(t){return this.next(t,"read").value}next(t,e="read"){return this.source.next({cmd:e,size:t})}throw(t){return Object.create(this.source.throw&&this.source.throw(t)||Y)}return(t){return Object.create(this.source.return&&this.source.return(t)||Y)}},Ue=class{constructor(t){this.source=t,this._closedPromise=new Promise(e=>this._closedPromiseResolve=e)}cancel(t){return p(this,void 0,void 0,function*(){yield this.return(t)})}get closed(){return this._closedPromise}read(t){return p(this,void 0,void 0,function*(){return(yield this.next(t,"read")).value})}peek(t){return p(this,void 0,void 0,function*(){return(yield this.next(t,"peek")).value})}next(t,e="read"){return p(this,void 0,void 0,function*(){return yield this.source.next({cmd:e,size:t})})}throw(t){return p(this,void 0,void 0,function*(){let e=this.source.throw&&(yield this.source.throw(t))||Y;return this._closedPromiseResolve&&this._closedPromiseResolve(),this._closedPromiseResolve=void 0,Object.create(e)})}return(t){return p(this,void 0,void 0,function*(){let e=this.source.return&&(yield this.source.return(t))||Y;return this._closedPromiseResolve&&this._closedPromiseResolve(),this._closedPromiseResolve=void 0,Object.create(e)})}};var Bi=class extends me{constructor(t,e){super(),this.position=0,this.buffer=S(t),this.size=e===void 0?this.buffer.byteLength:e}readInt32(t){let{buffer:e,byteOffset:i}=this.readAt(t,4);return new DataView(e,i).getInt32(0,!0)}seek(t){return this.position=Math.min(t,this.size),t<this.size}read(t){let{buffer:e,size:i,position:n}=this;return e&&n<i?(typeof t!="number"&&(t=Number.POSITIVE_INFINITY),this.position=Math.min(i,n+Math.min(i-n,t)),e.subarray(n,this.position)):null}readAt(t,e){let i=this.buffer,n=Math.min(this.size,t+e);return i?i.subarray(t,n):new Uint8Array(e)}close(){this.buffer&&(this.buffer=null)}throw(t){return this.close(),{done:!0,value:t}}return(t){return this.close(),{done:!0,value:t}}},ir=class extends kt{constructor(t,e){super(),this.position=0,this._handle=t,typeof e=="number"?this.size=e:this._pending=p(this,void 0,void 0,function*(){this.size=(yield t.stat()).size,delete this._pending})}readInt32(t){return p(this,void 0,void 0,function*(){let{buffer:e,byteOffset:i}=yield this.readAt(t,4);return new DataView(e,i).getInt32(0,!0)})}seek(t){return p(this,void 0,void 0,function*(){return this._pending&&(yield this._pending),this.position=Math.min(t,this.size),t<this.size})}read(t){return p(this,void 0,void 0,function*(){this._pending&&(yield this._pending);let{_handle:e,size:i,position:n}=this;if(e&&n<i){typeof t!="number"&&(t=Number.POSITIVE_INFINITY);let s=n,o=0,a=0,c=Math.min(i,s+Math.min(i-s,t)),l=new Uint8Array(Math.max(0,(this.position=c)-s));for(;(s+=a)<c&&(o+=a)<l.byteLength;)({bytesRead:a}=yield e.read(l,o,l.byteLength-o,s));return l}return null})}readAt(t,e){return p(this,void 0,void 0,function*(){this._pending&&(yield this._pending);let{_handle:i,size:n}=this;if(i&&t+e<n){let s=Math.min(n,t+e),o=new Uint8Array(s-t);return(yield i.read(o,0,e,t)).buffer}return new Uint8Array(e)})}close(){return p(this,void 0,void 0,function*(){let t=this._handle;this._handle=null,t&&(yield t.close())})}throw(t){return p(this,void 0,void 0,function*(){return yield this.close(),{done:!0,value:t}})}return(t){return p(this,void 0,void 0,function*(){return yield this.close(),{done:!0,value:t}})}};var Oo={};Rr(Oo,{BaseInt64:()=>Ni,Int128:()=>Fi,Int64:()=>Ce,Uint64:()=>X});function Yr(r){return r<0&&(r=4294967295+r+1),`0x${r.toString(16)}`}var Hr=8,Ao=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8],Ni=class{constructor(t){this.buffer=t}high(){return this.buffer[1]}low(){return this.buffer[0]}_times(t){let e=new Uint32Array([this.buffer[1]>>>16,this.buffer[1]&65535,this.buffer[0]>>>16,this.buffer[0]&65535]),i=new Uint32Array([t.buffer[1]>>>16,t.buffer[1]&65535,t.buffer[0]>>>16,t.buffer[0]&65535]),n=e[3]*i[3];this.buffer[0]=n&65535;let s=n>>>16;return n=e[2]*i[3],s+=n,n=e[3]*i[2]>>>0,s+=n,this.buffer[0]+=s<<16,this.buffer[1]=s>>>0<n?65536:0,this.buffer[1]+=s>>>16,this.buffer[1]+=e[1]*i[3]+e[2]*i[2]+e[3]*i[1],this.buffer[1]+=e[0]*i[3]+e[1]*i[2]+e[2]*i[1]+e[3]*i[0]<<16,this}_plus(t){let e=this.buffer[0]+t.buffer[0]>>>0;this.buffer[1]+=t.buffer[1],e<this.buffer[0]>>>0&&++this.buffer[1],this.buffer[0]=e}lessThan(t){return this.buffer[1]<t.buffer[1]||this.buffer[1]===t.buffer[1]&&this.buffer[0]<t.buffer[0]}equals(t){return this.buffer[1]===t.buffer[1]&&this.buffer[0]==t.buffer[0]}greaterThan(t){return t.lessThan(this)}hex(){return`${Yr(this.buffer[1])} ${Yr(this.buffer[0])}`}},X=class r extends Ni{times(t){return this._times(t),this}plus(t){return this._plus(t),this}static from(t,e=new Uint32Array(2)){return r.fromString(typeof t=="string"?t:t.toString(),e)}static fromNumber(t,e=new Uint32Array(2)){return r.fromString(t.toString(),e)}static fromString(t,e=new Uint32Array(2)){let i=t.length,n=new r(e);for(let s=0;s<i;){let o=Hr<i-s?Hr:i-s,a=new r(new Uint32Array([Number.parseInt(t.slice(s,s+o),10),0])),c=new r(new Uint32Array([Ao[o],0]));n.times(c),n.plus(a),s+=o}return n}static convertArray(t){let e=new Uint32Array(t.length*2);for(let i=-1,n=t.length;++i<n;)r.from(t[i],new Uint32Array(e.buffer,e.byteOffset+2*i*4,2));return e}static multiply(t,e){return new r(new Uint32Array(t.buffer)).times(e)}static add(t,e){return new r(new Uint32Array(t.buffer)).plus(e)}},Ce=class r extends Ni{negate(){return this.buffer[0]=~this.buffer[0]+1,this.buffer[1]=~this.buffer[1],this.buffer[0]==0&&++this.buffer[1],this}times(t){return this._times(t),this}plus(t){return this._plus(t),this}lessThan(t){let e=this.buffer[1]<<0,i=t.buffer[1]<<0;return e<i||e===i&&this.buffer[0]<t.buffer[0]}static from(t,e=new Uint32Array(2)){return r.fromString(typeof t=="string"?t:t.toString(),e)}static fromNumber(t,e=new Uint32Array(2)){return r.fromString(t.toString(),e)}static fromString(t,e=new Uint32Array(2)){let i=t.startsWith("-"),n=t.length,s=new r(e);for(let o=i?1:0;o<n;){let a=Hr<n-o?Hr:n-o,c=new r(new Uint32Array([Number.parseInt(t.slice(o,o+a),10),0])),l=new r(new Uint32Array([Ao[a],0]));s.times(l),s.plus(c),o+=a}return i?s.negate():s}static convertArray(t){let e=new Uint32Array(t.length*2);for(let i=-1,n=t.length;++i<n;)r.from(t[i],new Uint32Array(e.buffer,e.byteOffset+2*i*4,2));return e}static multiply(t,e){return new r(new Uint32Array(t.buffer)).times(e)}static add(t,e){return new r(new Uint32Array(t.buffer)).plus(e)}},Fi=class r{constructor(t){this.buffer=t}high(){return new Ce(new Uint32Array(this.buffer.buffer,this.buffer.byteOffset+8,2))}low(){return new Ce(new Uint32Array(this.buffer.buffer,this.buffer.byteOffset,2))}negate(){return this.buffer[0]=~this.buffer[0]+1,this.buffer[1]=~this.buffer[1],this.buffer[2]=~this.buffer[2],this.buffer[3]=~this.buffer[3],this.buffer[0]==0&&++this.buffer[1],this.buffer[1]==0&&++this.buffer[2],this.buffer[2]==0&&++this.buffer[3],this}times(t){let e=new X(new Uint32Array([this.buffer[3],0])),i=new X(new Uint32Array([this.buffer[2],0])),n=new X(new Uint32Array([this.buffer[1],0])),s=new X(new Uint32Array([this.buffer[0],0])),o=new X(new Uint32Array([t.buffer[3],0])),a=new X(new Uint32Array([t.buffer[2],0])),c=new X(new Uint32Array([t.buffer[1],0])),l=new X(new Uint32Array([t.buffer[0],0])),d=X.multiply(s,l);this.buffer[0]=d.low();let h=new X(new Uint32Array([d.high(),0]));return d=X.multiply(n,l),h.plus(d),d=X.multiply(s,c),h.plus(d),this.buffer[1]=h.low(),this.buffer[3]=h.lessThan(d)?1:0,this.buffer[2]=h.high(),new X(new Uint32Array(this.buffer.buffer,this.buffer.byteOffset+8,2)).plus(X.multiply(i,l)).plus(X.multiply(n,c)).plus(X.multiply(s,a)),this.buffer[3]+=X.multiply(e,l).plus(X.multiply(i,c)).plus(X.multiply(n,a)).plus(X.multiply(s,o)).low(),this}plus(t){let e=new Uint32Array(4);return e[3]=this.buffer[3]+t.buffer[3]>>>0,e[2]=this.buffer[2]+t.buffer[2]>>>0,e[1]=this.buffer[1]+t.buffer[1]>>>0,e[0]=this.buffer[0]+t.buffer[0]>>>0,e[0]<this.buffer[0]>>>0&&++e[1],e[1]<this.buffer[1]>>>0&&++e[2],e[2]<this.buffer[2]>>>0&&++e[3],this.buffer[3]=e[3],this.buffer[2]=e[2],this.buffer[1]=e[1],this.buffer[0]=e[0],this}hex(){return`${Yr(this.buffer[3])} ${Yr(this.buffer[2])} ${Yr(this.buffer[1])} ${Yr(this.buffer[0])}`}static multiply(t,e){return new r(new Uint32Array(t.buffer)).times(e)}static add(t,e){return new r(new Uint32Array(t.buffer)).plus(e)}static from(t,e=new Uint32Array(4)){return r.fromString(typeof t=="string"?t:t.toString(),e)}static fromNumber(t,e=new Uint32Array(4)){return r.fromString(t.toString(),e)}static fromString(t,e=new Uint32Array(4)){let i=t.startsWith("-"),n=t.length,s=new r(e);for(let o=i?1:0;o<n;){let a=Hr<n-o?Hr:n-o,c=new r(new Uint32Array([Number.parseInt(t.slice(o,o+a),10),0,0,0])),l=new r(new Uint32Array([Ao[a],0,0,0]));s.times(l),s.plus(c),o+=a}return i?s.negate():s}static convertArray(t){let e=new Uint32Array(t.length*4);for(let i=-1,n=t.length;++i<n;)r.from(t[i],new Uint32Array(e.buffer,e.byteOffset+4*4*i,4));return e}};var Ri=class extends b{constructor(t,e,i,n){super(),this.nodesIndex=-1,this.buffersIndex=-1,this.bytes=t,this.nodes=e,this.buffers=i,this.dictionaries=n}visit(t){return super.visit(t instanceof R?t.type:t)}visitNull(t,{length:e}=this.nextFieldNode()){return x({type:t,length:e})}visitBool(t,{length:e,nullCount:i}=this.nextFieldNode()){return x({type:t,length:e,nullCount:i,nullBitmap:this.readNullBitmap(t,i),data:this.readData(t)})}visitInt(t,{length:e,nullCount:i}=this.nextFieldNode()){return x({type:t,length:e,nullCount:i,nullBitmap:this.readNullBitmap(t,i),data:this.readData(t)})}visitFloat(t,{length:e,nullCount:i}=this.nextFieldNode()){return x({type:t,length:e,nullCount:i,nullBitmap:this.readNullBitmap(t,i),data:this.readData(t)})}visitUtf8(t,{length:e,nullCount:i}=this.nextFieldNode()){return x({type:t,length:e,nullCount:i,nullBitmap:this.readNullBitmap(t,i),valueOffsets:this.readOffsets(t),data:this.readData(t)})}visitBinary(t,{length:e,nullCount:i}=this.nextFieldNode()){return x({type:t,length:e,nullCount:i,nullBitmap:this.readNullBitmap(t,i),valueOffsets:this.readOffsets(t),data:this.readData(t)})}visitFixedSizeBinary(t,{length:e,nullCount:i}=this.nextFieldNode()){return x({type:t,length:e,nullCount:i,nullBitmap:this.readNullBitmap(t,i),data:this.readData(t)})}visitDate(t,{length:e,nullCount:i}=this.nextFieldNode()){return x({type:t,length:e,nullCount:i,nullBitmap:this.readNullBitmap(t,i),data:this.readData(t)})}visitTimestamp(t,{length:e,nullCount:i}=this.nextFieldNode()){return x({type:t,length:e,nullCount:i,nullBitmap:this.readNullBitmap(t,i),data:this.readData(t)})}visitTime(t,{length:e,nullCount:i}=this.nextFieldNode()){return x({type:t,length:e,nullCount:i,nullBitmap:this.readNullBitmap(t,i),data:this.readData(t)})}visitDecimal(t,{length:e,nullCount:i}=this.nextFieldNode()){return x({type:t,length:e,nullCount:i,nullBitmap:this.readNullBitmap(t,i),data:this.readData(t)})}visitList(t,{length:e,nullCount:i}=this.nextFieldNode()){return x({type:t,length:e,nullCount:i,nullBitmap:this.readNullBitmap(t,i),valueOffsets:this.readOffsets(t),child:this.visit(t.children[0])})}visitStruct(t,{length:e,nullCount:i}=this.nextFieldNode()){return x({type:t,length:e,nullCount:i,nullBitmap:this.readNullBitmap(t,i),children:this.visitMany(t.children)})}visitUnion(t){return t.mode===J.Sparse?this.visitSparseUnion(t):this.visitDenseUnion(t)}visitDenseUnion(t,{length:e,nullCount:i}=this.nextFieldNode()){return x({type:t,length:e,nullCount:i,nullBitmap:this.readNullBitmap(t,i),typeIds:this.readTypeIds(t),valueOffsets:this.readOffsets(t),children:this.visitMany(t.children)})}visitSparseUnion(t,{length:e,nullCount:i}=this.nextFieldNode()){return x({type:t,length:e,nullCount:i,nullBitmap:this.readNullBitmap(t,i),typeIds:this.readTypeIds(t),children:this.visitMany(t.children)})}visitDictionary(t,{length:e,nullCount:i}=this.nextFieldNode()){return x({type:t,length:e,nullCount:i,nullBitmap:this.readNullBitmap(t,i),data:this.readData(t.indices),dictionary:this.readDictionary(t)})}visitInterval(t,{length:e,nullCount:i}=this.nextFieldNode()){return x({type:t,length:e,nullCount:i,nullBitmap:this.readNullBitmap(t,i),data:this.readData(t)})}visitFixedSizeList(t,{length:e,nullCount:i}=this.nextFieldNode()){return x({type:t,length:e,nullCount:i,nullBitmap:this.readNullBitmap(t,i),child:this.visit(t.children[0])})}visitMap(t,{length:e,nullCount:i}=this.nextFieldNode()){return x({type:t,length:e,nullCount:i,nullBitmap:this.readNullBitmap(t,i),valueOffsets:this.readOffsets(t),child:this.visit(t.children[0])})}nextFieldNode(){return this.nodes[++this.nodesIndex]}nextBufferRange(){return this.buffers[++this.buffersIndex]}readNullBitmap(t,e,i=this.nextBufferRange()){return e>0&&this.readData(t,i)||new Uint8Array(0)}readOffsets(t,e){return this.readData(t,e)}readTypeIds(t,e){return this.readData(t,e)}readData(t,{length:e,offset:i}=this.nextBufferRange()){return this.bytes.subarray(i,i+e)}readDictionary(t){return this.dictionaries.get(t.id)}},Xn=class extends Ri{constructor(t,e,i,n){super(new Uint8Array(0),e,i,n),this.sources=t}readNullBitmap(t,e,{offset:i}=this.nextBufferRange()){return e<=0?new Uint8Array(0):hr(this.sources[i])}readOffsets(t,{offset:e}=this.nextBufferRange()){return N(Uint8Array,N(Int32Array,this.sources[e]))}readTypeIds(t,{offset:e}=this.nextBufferRange()){return N(Uint8Array,N(t.ArrayType,this.sources[e]))}readData(t,{offset:e}=this.nextBufferRange()){let{sources:i}=this;return y.isTimestamp(t)?N(Uint8Array,Ce.convertArray(i[e])):(y.isInt(t)||y.isTime(t))&&t.bitWidth===64?N(Uint8Array,Ce.convertArray(i[e])):y.isDate(t)&&t.unit===dt.MILLISECOND?N(Uint8Array,Ce.convertArray(i[e])):y.isDecimal(t)?N(Uint8Array,Fi.convertArray(i[e])):y.isBinary(t)||y.isFixedSizeBinary(t)?wd(i[e]):y.isBool(t)?hr(i[e]):y.isUtf8(t)?ze(i[e].join("")):N(Uint8Array,N(t.ArrayType,i[e].map(n=>+n)))}};function wd(r){let t=r.join(""),e=new Uint8Array(t.length/2);for(let i=0;i<t.length;i+=2)e[i>>1]=Number.parseInt(t.slice(i,i+2),16);return e}var Kr=class extends ue{constructor(t){super(t),this._values=new Ye(new Uint8Array(0))}get byteLength(){let t=this._pendingLength+this.length*4;return this._offsets&&(t+=this._offsets.byteLength),this._values&&(t+=this._values.byteLength),this._nulls&&(t+=this._nulls.byteLength),t}setValue(t,e){return super.setValue(t,S(e))}_flushPending(t,e){let i=this._offsets,n=this._values.reserve(e).buffer,s=0;for(let[o,a]of t)if(a===void 0)i.set(o,0);else{let c=a.length;n.set(a,s),i.set(o,c),s+=c}}};var Zn=class extends K{constructor(t){super(t),this._values=new qr}setValue(t,e){this._values.set(t,+e)}};var gr=class extends ct{};gr.prototype._setValue=ao;var Di=class extends gr{};Di.prototype._setValue=xn;var Li=class extends gr{};Li.prototype._setValue=An;var Mi=class extends ct{};Mi.prototype._setValue=uo;var ts=class extends K{constructor({type:t,nullValues:e,dictionaryHashFunction:i}){super({type:new Ot(t.dictionary,t.indices,t.id,t.isOrdered)}),this._nulls=null,this._dictionaryOffset=0,this._keysToIndices=Object.create(null),this.indices=br({type:this.type.indices,nullValues:e}),this.dictionary=br({type:this.type.dictionary,nullValues:null}),typeof i=="function"&&(this.valueToKey=i)}get values(){return this.indices.values}get nullCount(){return this.indices.nullCount}get nullBitmap(){return this.indices.nullBitmap}get byteLength(){return this.indices.byteLength+this.dictionary.byteLength}get reservedLength(){return this.indices.reservedLength+this.dictionary.reservedLength}get reservedByteLength(){return this.indices.reservedByteLength+this.dictionary.reservedByteLength}isValid(t){return this.indices.isValid(t)}setValid(t,e){let i=this.indices;return e=i.setValid(t,e),this.length=i.length,e}setValue(t,e){let i=this._keysToIndices,n=this.valueToKey(e),s=i[n];return s===void 0&&(i[n]=s=this._dictionaryOffset+this.dictionary.append(e).length-1),this.indices.setValue(t,s)}flush(){let t=this.type,e=this._dictionary,i=this.dictionary.toVector(),n=this.indices.flush().clone(t);return n.dictionary=e?e.concat(i):i,this.finished||(this._dictionaryOffset+=i.length),this._dictionary=n.dictionary,this.clear(),n}finish(){return this.indices.finish(),this.dictionary.finish(),this._dictionaryOffset=0,this._keysToIndices=Object.create(null),super.finish()}clear(){return this.indices.clear(),this.dictionary.clear(),super.clear()}valueToKey(t){return typeof t=="string"?t:`${t}`}};var Ui=class extends ct{};Ui.prototype._setValue=oo;var es=class extends K{setValue(t,e){let[i]=this.children,n=t*this.stride;for(let s=-1,o=e.length;++s<o;)i.set(n+s,e[s])}addChild(t,e="0"){if(this.numChildren>0)throw new Error("FixedSizeListBuilder can only have one child.");let i=this.children.push(t);return this.type=new Kt(this.type.listSize,new R(e,t.type,!0)),i}};var _r=class extends ct{setValue(t,e){this._values.set(t,e)}},rs=class extends _r{setValue(t,e){super.setValue(t,di(e))}},is=class extends _r{},ns=class extends _r{};var wr=class extends ct{};wr.prototype._setValue=ho;var Ci=class extends wr{};Ci.prototype._setValue=Un;var ki=class extends wr{};ki.prototype._setValue=Cn;var Pt=class extends ct{setValue(t,e){this._values.set(t,e)}},ss=class extends Pt{},os=class extends Pt{},as=class extends Pt{},cs=class extends Pt{},ls=class extends Pt{},us=class extends Pt{},ds=class extends Pt{},hs=class extends Pt{};var fs=class extends ue{constructor(t){super(t),this._offsets=new Gr}addChild(t,e="0"){if(this.numChildren>0)throw new Error("ListBuilder can only have one child.");return this.children[this.numChildren]=t,this.type=new Yt(new R(e,t.type,!0)),this.numChildren-1}_flushPending(t){let e=this._offsets,[i]=this.children;for(let[n,s]of t)if(typeof s>"u")e.set(n,0);else{let o=s,a=o.length,c=e.set(n,a).buffer[n];for(let l=-1;++l<a;)i.set(c+l,o[l])}}};var ps=class extends ue{set(t,e){return super.set(t,e)}setValue(t,e){let i=e instanceof Map?e:new Map(Object.entries(e)),n=this._pending||(this._pending=new Map),s=n.get(t);s&&(this._pendingLength-=s.size),this._pendingLength+=i.size,n.set(t,i)}addChild(t,e=`${this.numChildren}`){if(this.numChildren>0)throw new Error("ListBuilder can only have one child.");return this.children[this.numChildren]=t,this.type=new Qt(new R(e,t.type,!0),this.type.keysSorted),this.numChildren-1}_flushPending(t){let e=this._offsets,[i]=this.children;for(let[n,s]of t)if(s===void 0)e.set(n,0);else{let{[n]:o,[n+1]:a}=e.set(n,s.size).buffer;for(let c of s.entries())if(i.set(o,c),++o>=a)break}}};var ms=class extends K{setValue(t,e){}setValid(t,e){return this.length=Math.max(t+1,this.length),e}};var ys=class extends K{setValue(t,e){let{children:i,type:n}=this;switch(Array.isArray(e)||e.constructor){case!0:return n.children.forEach((s,o)=>i[o].set(t,e[o]));case Map:return n.children.forEach((s,o)=>i[o].set(t,e.get(s.name)));default:return n.children.forEach((s,o)=>i[o].set(t,e[s.name]))}}setValid(t,e){return super.setValid(t,e)||this.children.forEach(i=>i.setValid(t,e)),e}addChild(t,e=`${this.numChildren}`){let i=this.children.push(t);return this.type=new W([...this.type.children,new R(e,t.type,!0)]),i}};var ke=class extends ct{};ke.prototype._setValue=co;var Pi=class extends ke{};Pi.prototype._setValue=On;var Vi=class extends ke{};Vi.prototype._setValue=Bn;var ji=class extends ke{};ji.prototype._setValue=Nn;var zi=class extends ke{};zi.prototype._setValue=Fn;var Pe=class extends ct{};Pe.prototype._setValue=lo;var $i=class extends Pe{};$i.prototype._setValue=Rn;var qi=class extends Pe{};qi.prototype._setValue=Dn;var Gi=class extends Pe{};Gi.prototype._setValue=Ln;var Wi=class extends Pe{};Wi.prototype._setValue=Mn;var Qr=class extends K{constructor(t){super(t),this._typeIds=new Fe(new Int8Array(0),1),typeof t.valueToChildTypeId=="function"&&(this._valueToChildTypeId=t.valueToChildTypeId)}get typeIdToChildIndex(){return this.type.typeIdToChildIndex}append(t,e){return this.set(this.length,t,e)}set(t,e,i){return i===void 0&&(i=this._valueToChildTypeId(this,e,t)),this.setValid(t,this.isValid(e))&&this.setValue(t,e,i),this}setValue(t,e,i){this._typeIds.set(t,i);let n=this.type.typeIdToChildIndex[i],s=this.children[n];s?.set(t,e)}addChild(t,e=`${this.children.length}`){let i=this.children.push(t),{type:{children:n,mode:s,typeIds:o}}=this,a=[...n,new R(e,t.type)];return this.type=new Ht(s,[...o,i],a),i}_valueToChildTypeId(t,e,i){throw new Error("Cannot map UnionBuilder value to child typeId. Pass the `childTypeId` as the second argument to unionBuilder.append(), or supply a `valueToChildTypeId` function as part of the UnionBuilder constructor options.")}},gs=class extends Qr{},bs=class extends Qr{constructor(t){super(t),this._offsets=new Fe(new Int32Array(0))}setValue(t,e,i){let n=this._typeIds.set(t,i).buffer[t],s=this.getChildAt(this.type.typeIdToChildIndex[n]),o=this._offsets.set(t,s.length).buffer[t];s?.set(o,e)}};var Yi=class extends ue{constructor(t){super(t),this._values=new Ye(new Uint8Array(0))}get byteLength(){let t=this._pendingLength+this.length*4;return this._offsets&&(t+=this._offsets.byteLength),this._values&&(t+=this._values.byteLength),this._nulls&&(t+=this._nulls.byteLength),t}setValue(t,e){return super.setValue(t,ze(e))}_flushPending(t,e){}};Yi.prototype._flushPending=Kr.prototype._flushPending;var Bo=class extends b{visitNull(){return ms}visitBool(){return Zn}visitInt(){return Pt}visitInt8(){return ss}visitInt16(){return os}visitInt32(){return as}visitInt64(){return cs}visitUint8(){return ls}visitUint16(){return us}visitUint32(){return ds}visitUint64(){return hs}visitFloat(){return _r}visitFloat16(){return rs}visitFloat32(){return is}visitFloat64(){return ns}visitUtf8(){return Yi}visitBinary(){return Kr}visitFixedSizeBinary(){return Ui}visitDate(){return gr}visitDateDay(){return Di}visitDateMillisecond(){return Li}visitTimestamp(){return ke}visitTimestampSecond(){return Pi}visitTimestampMillisecond(){return Vi}visitTimestampMicrosecond(){return ji}visitTimestampNanosecond(){return zi}visitTime(){return Pe}visitTimeSecond(){return $i}visitTimeMillisecond(){return qi}visitTimeMicrosecond(){return Gi}visitTimeNanosecond(){return Wi}visitDecimal(){return Mi}visitList(){return fs}visitStruct(){return ys}visitUnion(){return Qr}visitDenseUnion(){return bs}visitSparseUnion(){return gs}visitDictionary(){return ts}visitInterval(){return wr}visitIntervalDayTime(){return Ci}visitIntervalYearMonth(){return ki}visitFixedSizeList(){return es}visitMap(){return ps}},Tc=new Bo;var v=class extends b{compareSchemas(t,e){return t===e||e instanceof t.constructor&&this.compareManyFields(t.fields,e.fields)}compareManyFields(t,e){return t===e||Array.isArray(t)&&Array.isArray(e)&&t.length===e.length&&t.every((i,n)=>this.compareFields(i,e[n]))}compareFields(t,e){return t===e||e instanceof t.constructor&&t.name===e.name&&t.nullable===e.nullable&&this.visit(t.type,e.type)}};function It(r,t){return t instanceof r.constructor}function Hi(r,t){return r===t||It(r,t)}function Ve(r,t){return r===t||It(r,t)&&r.bitWidth===t.bitWidth&&r.isSigned===t.isSigned}function _s(r,t){return r===t||It(r,t)&&r.precision===t.precision}function Id(r,t){return r===t||It(r,t)&&r.byteWidth===t.byteWidth}function No(r,t){return r===t||It(r,t)&&r.unit===t.unit}function Ki(r,t){return r===t||It(r,t)&&r.unit===t.unit&&r.timezone===t.timezone}function Qi(r,t){return r===t||It(r,t)&&r.unit===t.unit&&r.bitWidth===t.bitWidth}function vd(r,t){return r===t||It(r,t)&&r.children.length===t.children.length&&ye.compareManyFields(r.children,t.children)}function Sd(r,t){return r===t||It(r,t)&&r.children.length===t.children.length&&ye.compareManyFields(r.children,t.children)}function Fo(r,t){return r===t||It(r,t)&&r.mode===t.mode&&r.typeIds.every((e,i)=>e===t.typeIds[i])&&ye.compareManyFields(r.children,t.children)}function Td(r,t){return r===t||It(r,t)&&r.id===t.id&&r.isOrdered===t.isOrdered&&ye.visit(r.indices,t.indices)&&ye.visit(r.dictionary,t.dictionary)}function Ro(r,t){return r===t||It(r,t)&&r.unit===t.unit}function Ed(r,t){return r===t||It(r,t)&&r.listSize===t.listSize&&r.children.length===t.children.length&&ye.compareManyFields(r.children,t.children)}function xd(r,t){return r===t||It(r,t)&&r.keysSorted===t.keysSorted&&r.children.length===t.children.length&&ye.compareManyFields(r.children,t.children)}v.prototype.visitNull=Hi;v.prototype.visitBool=Hi;v.prototype.visitInt=Ve;v.prototype.visitInt8=Ve;v.prototype.visitInt16=Ve;v.prototype.visitInt32=Ve;v.prototype.visitInt64=Ve;v.prototype.visitUint8=Ve;v.prototype.visitUint16=Ve;v.prototype.visitUint32=Ve;v.prototype.visitUint64=Ve;v.prototype.visitFloat=_s;v.prototype.visitFloat16=_s;v.prototype.visitFloat32=_s;v.prototype.visitFloat64=_s;v.prototype.visitUtf8=Hi;v.prototype.visitBinary=Hi;v.prototype.visitFixedSizeBinary=Id;v.prototype.visitDate=No;v.prototype.visitDateDay=No;v.prototype.visitDateMillisecond=No;v.prototype.visitTimestamp=Ki;v.prototype.visitTimestampSecond=Ki;v.prototype.visitTimestampMillisecond=Ki;v.prototype.visitTimestampMicrosecond=Ki;v.prototype.visitTimestampNanosecond=Ki;v.prototype.visitTime=Qi;v.prototype.visitTimeSecond=Qi;v.prototype.visitTimeMillisecond=Qi;v.prototype.visitTimeMicrosecond=Qi;v.prototype.visitTimeNanosecond=Qi;v.prototype.visitDecimal=Hi;v.prototype.visitList=vd;v.prototype.visitStruct=Sd;v.prototype.visitUnion=Fo;v.prototype.visitDenseUnion=Fo;v.prototype.visitSparseUnion=Fo;v.prototype.visitDictionary=Td;v.prototype.visitInterval=Ro;v.prototype.visitIntervalDayTime=Ro;v.prototype.visitIntervalYearMonth=Ro;v.prototype.visitFixedSizeList=Ed;v.prototype.visitMap=xd;var ye=new v;function Ir(r,t){return ye.compareSchemas(r,t)}function Ec(r,t){return ye.compareFields(r,t)}function xc(r,t){return ye.visit(r,t)}function br(r){let t=r.type,e=new(Tc.getVisitFn(t)())(r);if(t.children&&t.children.length>0){let i=r.children||[],n={nullValues:r.nullValues},s=Array.isArray(i)?(o,a)=>i[a]||n:({name:o})=>i[o]||n;for(let[o,a]of t.children.entries()){let{type:c}=a,l=s(a,o);e.children.push(br(Object.assign(Object.assign({},l),{type:c})))}}return e}function ws(r,t){return Ad(r,t.map(e=>e.data.concat()))}function Ad(r,t){let e=[...r.fields],i=[],n={numBatches:t.reduce((h,f)=>Math.max(h,f.length),0)},s=0,o=0,a=-1,c=t.length,l,d=[];for(;n.numBatches-- >0;){for(o=Number.POSITIVE_INFINITY,a=-1;++a<c;)d[a]=l=t[a].shift(),o=Math.min(o,l?l.length:o);Number.isFinite(o)&&(d=Od(e,o,d,t,n),o>0&&(i[s++]=x({type:new W(e),length:o,nullCount:0,children:d.slice()})))}return[r=r.assign(e),i.map(h=>new Z(r,h))]}function Od(r,t,e,i,n){var s;let o=(t+63&-64)>>3;for(let a=-1,c=i.length;++a<c;){let l=e[a],d=l?.length;if(d>=t)d===t?e[a]=l:(e[a]=l.slice(0,t),n.numBatches=Math.max(n.numBatches,i[a].unshift(l.slice(t,d-t))));else{let h=r[a];r[a]=h.clone({nullable:!0}),e[a]=(s=l?._changeLengthAndBackfillNullBitmap(t))!==null&&s!==void 0?s:x({type:h.type,length:t,nullCount:t,nullBitmap:new Uint8Array(o)})}}return e}var Ac,lt=class r{constructor(...t){var e,i;if(t.length===0)return this.batches=[],this.schema=new j([]),this._offsets=[0],this;let n,s;t[0]instanceof j&&(n=t.shift()),t.at(-1)instanceof Uint32Array&&(s=t.pop());let o=c=>{if(c){if(c instanceof Z)return[c];if(c instanceof r)return c.batches;if(c instanceof $){if(c.type instanceof W)return[new Z(new j(c.type.children),c)]}else{if(Array.isArray(c))return c.flatMap(l=>o(l));if(typeof c[Symbol.iterator]=="function")return[...c].flatMap(l=>o(l));if(typeof c=="object"){let l=Object.keys(c),d=l.map(g=>new L([c[g]])),h=new j(l.map((g,M)=>new R(String(g),d[M].type))),[,f]=ws(h,d);return f.length===0?[new Z(c)]:f}}}return[]},a=t.flatMap(c=>o(c));if(n=(i=n??((e=a[0])===null||e===void 0?void 0:e.schema))!==null&&i!==void 0?i:new j([]),!(n instanceof j))throw new TypeError("Table constructor expects a [Schema, RecordBatch[]] pair.");for(let c of a){if(!(c instanceof Z))throw new TypeError("Table constructor expects a [Schema, RecordBatch[]] pair.");if(!Ir(n,c.schema))throw new TypeError("Table and inner RecordBatch schemas must be equivalent.")}this.schema=n,this.batches=a,this._offsets=s??zn(this.data)}get data(){return this.batches.map(({data:t})=>t)}get numCols(){return this.schema.fields.length}get numRows(){return this.data.reduce((t,e)=>t+e.length,0)}get nullCount(){return this._nullCount===-1&&(this._nullCount=jn(this.data)),this._nullCount}isValid(t){return!1}get(t){return null}set(t,e){}indexOf(t,e){return-1}getByteLength(t){return 0}[Symbol.iterator](){return this.batches.length>0?$r.visit(new L(this.data)):new Array(0)[Symbol.iterator]()}toArray(){return[...this]}toString(){return`[
8
8
  ${this.toArray().join(`,
9
9
  `)}
10
- ]`}concat(...t){let e=this.schema,i=this.data.concat(t.flatMap(({data:n})=>n));return new r(e,i.map(n=>new Z(e,n)))}slice(t,e){let i=this.schema;[t,e]=hi({length:this.numRows},t,e);let n=$n(this.data,this._offsets,t,e);return new r(i,n.map(s=>new Z(i,s)))}getChild(t){return this.getChildAt(this.schema.fields.findIndex(e=>e.name===t))}getChildAt(t){if(t>-1&&t<this.schema.fields.length){let e=this.data.map(i=>i.children[t]);if(e.length===0){let{type:i}=this.schema.fields[t],n=x({type:i,length:0,nullCount:0});e.push(n._changeLengthAndBackfillNullBitmap(this.numRows))}return new L(e)}return null}setChild(t,e){var i;return this.setChildAt((i=this.schema.fields)===null||i===void 0?void 0:i.findIndex(n=>n.name===t),e)}setChildAt(t,e){let i=this.schema,n=[...this.batches];if(t>-1&&t<this.numCols){e||(e=new L([x({type:new gt,length:this.numRows})]));let s=i.fields.slice(),o=s[t].clone({type:e.type}),a=this.schema.fields.map((c,l)=>this.getChildAt(l));[s[t],a[t]]=[o,e],[i,n]=ws(i,a)}return new r(i,n)}select(t){let e=this.schema.fields.reduce((i,n,s)=>i.set(n.name,s),new Map);return this.selectAt(t.map(i=>e.get(i)).filter(i=>i>-1))}selectAt(t){let e=this.schema.selectAt(t),i=this.batches.map(n=>n.selectAt(t));return new r(e,i)}assign(t){let e=this.schema.fields,[i,n]=t.schema.fields.reduce((a,c,l)=>{let[d,h]=a,f=e.findIndex(g=>g.name===c.name);return~f?h[f]=l:d.push(l),a},[[],[]]),s=this.schema.assign(t.schema),o=[...e.map((a,c)=>[c,n[c]]).map(([a,c])=>c===void 0?this.getChildAt(a):t.getChildAt(c)),...i.map(a=>t.getChildAt(a))].filter(Boolean);return new r(...ws(s,o))}};Ac=Symbol.toStringTag;lt[Ac]=(r=>(r.schema=null,r.batches=[],r._offsets=new Uint32Array([0]),r._nullCount=-1,r[Symbol.isConcatSpreadable]=!0,r.isValid=We(mi),r.get=We(it.getVisitFn(u.Struct)),r.set=qn(ht.getVisitFn(u.Struct)),r.indexOf=Gn(fr.getVisitFn(u.Struct)),r.getByteLength=We(Nt.getVisitFn(u.Struct)),"Table"))(lt.prototype);var Bc,Z=class r{constructor(...t){switch(t.length){case 2:{if([this.schema]=t,!(this.schema instanceof j))throw new TypeError("RecordBatch constructor expects a [Schema, Data] pair.");if([,this.data=x({nullCount:0,type:new W(this.schema.fields),children:this.schema.fields.map(e=>x({type:e.type,nullCount:0}))})]=t,!(this.data instanceof $))throw new TypeError("RecordBatch constructor expects a [Schema, Data] pair.");[this.schema,this.data]=Oc(this.schema,this.data.children);break}case 1:{let[e]=t,{fields:i,children:n,length:s}=Object.keys(e).reduce((c,l,d)=>(c.children[d]=e[l],c.length=Math.max(c.length,e[l].length),c.fields[d]=R.new({name:l,type:e[l].type,nullable:!0}),c),{length:0,fields:new Array,children:new Array}),o=new j(i),a=x({type:new W(i),length:s,children:n,nullCount:0});[this.schema,this.data]=Oc(o,a.children,s);break}default:throw new TypeError("RecordBatch constructor expects an Object mapping names to child Data, or a [Schema, Data] pair.")}}get dictionaries(){return this._dictionaries||(this._dictionaries=Nc(this.schema.fields,this.data.children))}get numCols(){return this.schema.fields.length}get numRows(){return this.data.length}get nullCount(){return this.data.nullCount}isValid(t){return this.data.getValid(t)}get(t){return it.visit(this.data,t)}set(t,e){return ht.visit(this.data,t,e)}indexOf(t,e){return fr.visit(this.data,t,e)}getByteLength(t){return Nt.visit(this.data,t)}[Symbol.iterator](){return $r.visit(new L([this.data]))}toArray(){return[...this]}concat(...t){return new lt(this.schema,[this,...t])}slice(t,e){let[i]=new L([this.data]).slice(t,e).data;return new r(this.schema,i)}getChild(t){var e;return this.getChildAt((e=this.schema.fields)===null||e===void 0?void 0:e.findIndex(i=>i.name===t))}getChildAt(t){return t>-1&&t<this.schema.fields.length?new L([this.data.children[t]]):null}setChild(t,e){var i;return this.setChildAt((i=this.schema.fields)===null||i===void 0?void 0:i.findIndex(n=>n.name===t),e)}setChildAt(t,e){let i=this.schema,n=this.data;if(t>-1&&t<this.numCols){e||(e=new L([x({type:new gt,length:this.numRows})]));let s=i.fields.slice(),o=n.children.slice(),a=s[t].clone({type:e.type});[s[t],o[t]]=[a,e.data[0]],i=new j(s,new Map(this.schema.metadata)),n=x({type:new W(s),children:o})}return new r(i,n)}select(t){let e=this.schema.select(t),i=new W(e.fields),n=[];for(let s of t){let o=this.schema.fields.findIndex(a=>a.name===s);~o&&(n[o]=this.data.children[o])}return new r(e,x({type:i,length:this.numRows,children:n}))}selectAt(t){let e=this.schema.selectAt(t),i=t.map(s=>this.data.children[s]).filter(Boolean),n=x({type:new W(e.fields),length:this.numRows,children:i});return new r(e,n)}};Bc=Symbol.toStringTag;Z[Bc]=(r=>(r._nullCount=-1,r[Symbol.isConcatSpreadable]=!0,"RecordBatch"))(Z.prototype);function Oc(r,t,e=t.reduce((i,n)=>Math.max(i,n.length),0)){var i;let n=[...r.fields],s=[...t],o=(e+63&-64)>>3;for(let[a,c]of r.fields.entries()){let l=t[a];(!l||l.length!==e)&&(n[a]=c.clone({nullable:!0}),s[a]=(i=l?._changeLengthAndBackfillNullBitmap(e))!==null&&i!==void 0?i:x({type:c.type,length:e,nullCount:e,nullBitmap:new Uint8Array(o)}))}return[r.assign(n),x({type:new W(n),length:e,children:s})]}function Nc(r,t,e=new Map){for(let i=-1,n=r.length;++i<n;){let o=r[i].type,a=t[i];if(y.isDictionary(o)){if(!e.has(o.id))a.dictionary&&e.set(o.id,a.dictionary);else if(e.get(o.id)!==a.dictionary)throw new Error("Cannot create Schema containing two different dictionaries with the same Id")}o.children&&o.children.length>0&&Nc(o.children,a.children,e)}return e}var vr=class extends Z{constructor(t){let e=t.fields.map(n=>x({type:n.type})),i=x({type:new W(t.fields),nullCount:0,children:e});super(t,i)}};var Ji;(function(r){r[r.BUFFER=0]="BUFFER"})(Ji||(Ji={}));var Xi;(function(r){r[r.LZ4_FRAME=0]="LZ4_FRAME",r[r.ZSTD=1]="ZSTD"})(Xi||(Xi={}));var Is=class r{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsBodyCompression(t,e){return(e||new r).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsBodyCompression(t,e){return t.setPosition(t.position()+4),(e||new r).__init(t.readInt32(t.position())+t.position(),t)}codec(){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.readInt8(this.bb_pos+t):Xi.LZ4_FRAME}method(){let t=this.bb.__offset(this.bb_pos,6);return t?this.bb.readInt8(this.bb_pos+t):Ji.BUFFER}static startBodyCompression(t){t.startObject(2)}static addCodec(t,e){t.addFieldInt8(0,e,Xi.LZ4_FRAME)}static addMethod(t,e){t.addFieldInt8(1,e,Ji.BUFFER)}static endBodyCompression(t){return t.endObject()}static createBodyCompression(t,e,i){return r.startBodyCompression(t),r.addCodec(t,e),r.addMethod(t,i),r.endBodyCompression(t)}};var Jr=class{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}offset(){return this.bb.readInt64(this.bb_pos)}length(){return this.bb.readInt64(this.bb_pos+8)}static sizeOf(){return 16}static createBuffer(t,e,i){return t.prep(8,16),t.writeInt64(BigInt(i??0)),t.writeInt64(BigInt(e??0)),t.offset()}};var Xr=class{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}length(){return this.bb.readInt64(this.bb_pos)}nullCount(){return this.bb.readInt64(this.bb_pos+8)}static sizeOf(){return 16}static createFieldNode(t,e,i){return t.prep(8,16),t.writeInt64(BigInt(i??0)),t.writeInt64(BigInt(e??0)),t.offset()}};var Dt=class r{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsRecordBatch(t,e){return(e||new r).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsRecordBatch(t,e){return t.setPosition(t.position()+4),(e||new r).__init(t.readInt32(t.position())+t.position(),t)}length(){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.readInt64(this.bb_pos+t):BigInt("0")}nodes(t,e){let i=this.bb.__offset(this.bb_pos,6);return i?(e||new Xr).__init(this.bb.__vector(this.bb_pos+i)+t*16,this.bb):null}nodesLength(){let t=this.bb.__offset(this.bb_pos,6);return t?this.bb.__vector_len(this.bb_pos+t):0}buffers(t,e){let i=this.bb.__offset(this.bb_pos,8);return i?(e||new Jr).__init(this.bb.__vector(this.bb_pos+i)+t*16,this.bb):null}buffersLength(){let t=this.bb.__offset(this.bb_pos,8);return t?this.bb.__vector_len(this.bb_pos+t):0}compression(t){let e=this.bb.__offset(this.bb_pos,10);return e?(t||new Is).__init(this.bb.__indirect(this.bb_pos+e),this.bb):null}static startRecordBatch(t){t.startObject(4)}static addLength(t,e){t.addFieldInt64(0,e,BigInt("0"))}static addNodes(t,e){t.addFieldOffset(1,e,0)}static startNodesVector(t,e){t.startVector(16,e,8)}static addBuffers(t,e){t.addFieldOffset(2,e,0)}static startBuffersVector(t,e){t.startVector(16,e,8)}static addCompression(t,e){t.addFieldOffset(3,e,0)}static endRecordBatch(t){return t.endObject()}};var je=class r{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsDictionaryBatch(t,e){return(e||new r).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsDictionaryBatch(t,e){return t.setPosition(t.position()+4),(e||new r).__init(t.readInt32(t.position())+t.position(),t)}id(){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.readInt64(this.bb_pos+t):BigInt("0")}data(t){let e=this.bb.__offset(this.bb_pos,6);return e?(t||new Dt).__init(this.bb.__indirect(this.bb_pos+e),this.bb):null}isDelta(){let t=this.bb.__offset(this.bb_pos,8);return t?!!this.bb.readInt8(this.bb_pos+t):!1}static startDictionaryBatch(t){t.startObject(3)}static addId(t,e){t.addFieldInt64(0,e,BigInt("0"))}static addData(t,e){t.addFieldOffset(1,e,0)}static addIsDelta(t,e){t.addFieldInt8(2,+e,0)}static endDictionaryBatch(t){return t.endObject()}};var Zr;(function(r){r[r.NONE=0]="NONE",r[r.Schema=1]="Schema",r[r.DictionaryBatch=2]="DictionaryBatch",r[r.RecordBatch=3]="RecordBatch",r[r.Tensor=4]="Tensor",r[r.SparseTensor=5]="SparseTensor"})(Zr||(Zr={}));var ee=class r{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsMessage(t,e){return(e||new r).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsMessage(t,e){return t.setPosition(t.position()+4),(e||new r).__init(t.readInt32(t.position())+t.position(),t)}version(){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.readInt16(this.bb_pos+t):He.V1}headerType(){let t=this.bb.__offset(this.bb_pos,6);return t?this.bb.readUint8(this.bb_pos+t):Zr.NONE}header(t){let e=this.bb.__offset(this.bb_pos,8);return e?this.bb.__union(t,this.bb_pos+e):null}bodyLength(){let t=this.bb.__offset(this.bb_pos,10);return t?this.bb.readInt64(this.bb_pos+t):BigInt("0")}customMetadata(t,e){let i=this.bb.__offset(this.bb_pos,12);return i?(e||new st).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+i)+t*4),this.bb):null}customMetadataLength(){let t=this.bb.__offset(this.bb_pos,12);return t?this.bb.__vector_len(this.bb_pos+t):0}static startMessage(t){t.startObject(5)}static addVersion(t,e){t.addFieldInt16(0,e,He.V1)}static addHeaderType(t,e){t.addFieldInt8(1,e,Zr.NONE)}static addHeader(t,e){t.addFieldOffset(2,e,0)}static addBodyLength(t,e){t.addFieldInt64(3,e,BigInt("0"))}static addCustomMetadata(t,e){t.addFieldOffset(4,e,0)}static createCustomMetadataVector(t,e){t.startVector(4,e.length,4);for(let i=e.length-1;i>=0;i--)t.addOffset(e[i]);return t.endVector()}static startCustomMetadataVector(t,e){t.startVector(4,e,4)}static endMessage(t){return t.endObject()}static finishMessageBuffer(t,e){t.finish(e)}static finishSizePrefixedMessageBuffer(t,e){t.finish(e,void 0,!0)}static createMessage(t,e,i,n,s,o){return r.startMessage(t),r.addVersion(t,e),r.addHeaderType(t,i),r.addHeader(t,n),r.addBodyLength(t,s),r.addCustomMetadata(t,o),r.endMessage(t)}};var Do=class extends b{visit(t,e){return t==null||e==null?void 0:super.visit(t,e)}visitNull(t,e){return Ti.startNull(e),Ti.endNull(e)}visitInt(t,e){return Zt.startInt(e),Zt.addBitWidth(e,t.bitWidth),Zt.addIsSigned(e,t.isSigned),Zt.endInt(e)}visitFloat(t,e){return tr.startFloatingPoint(e),tr.addPrecision(e,t.precision),tr.endFloatingPoint(e)}visitBinary(t,e){return bi.startBinary(e),bi.endBinary(e)}visitBool(t,e){return _i.startBool(e),_i.endBool(e)}visitUtf8(t,e){return Ai.startUtf8(e),Ai.endUtf8(e)}visitDecimal(t,e){return fe.startDecimal(e),fe.addScale(e,t.scale),fe.addPrecision(e,t.precision),fe.addBitWidth(e,t.bitWidth),fe.endDecimal(e)}visitDate(t,e){return Qe.startDate(e),Qe.addUnit(e,t.unit),Qe.endDate(e)}visitTime(t,e){return Re.startTime(e),Re.addUnit(e,t.unit),Re.addBitWidth(e,t.bitWidth),Re.endTime(e)}visitTimestamp(t,e){let i=t.timezone&&e.createString(t.timezone)||void 0;return De.startTimestamp(e),De.addUnit(e,t.unit),i!==void 0&&De.addTimezone(e,i),De.endTimestamp(e)}visitInterval(t,e){return er.startInterval(e),er.addUnit(e,t.unit),er.endInterval(e)}visitList(t,e){return Si.startList(e),Si.endList(e)}visitStruct(t,e){return Ei.startStruct_(e),Ei.endStruct_(e)}visitUnion(t,e){te.startTypeIdsVector(e,t.typeIds.length);let i=te.createTypeIdsVector(e,t.typeIds);return te.startUnion(e),te.addMode(e,t.mode),te.addTypeIds(e,i),te.endUnion(e)}visitDictionary(t,e){let i=this.visit(t.indices,e);return he.startDictionaryEncoding(e),he.addId(e,BigInt(t.id)),he.addIsOrdered(e,t.isOrdered),i!==void 0&&he.addIndexType(e,i),he.endDictionaryEncoding(e)}visitFixedSizeBinary(t,e){return Xe.startFixedSizeBinary(e),Xe.addByteWidth(e,t.byteWidth),Xe.endFixedSizeBinary(e)}visitFixedSizeList(t,e){return Ze.startFixedSizeList(e),Ze.addListSize(e,t.listSize),Ze.endFixedSizeList(e)}visitMap(t,e){return rr.startMap(e),rr.addKeysSorted(e,t.keysSorted),rr.endMap(e)}},vs=new Do;function Lc(r,t=new Map){return new j(Nd(r,t),Ss(r.customMetadata),t)}function Lo(r){return new ft(r.count,Uc(r.columns),Cc(r.columns))}function Mc(r){return new St(Lo(r.data),r.id,r.isDelta)}function Nd(r,t){return(r.fields||[]).filter(Boolean).map(e=>R.fromJSON(e,t))}function Fc(r,t){return(r.children||[]).filter(Boolean).map(e=>R.fromJSON(e,t))}function Uc(r){return(r||[]).reduce((t,e)=>[...t,new re(e.count,Fd(e.VALIDITY)),...Uc(e.children)],[])}function Cc(r,t=[]){for(let e=-1,i=(r||[]).length;++e<i;){let n=r[e];n.VALIDITY&&t.push(new vt(t.length,n.VALIDITY.length)),n.TYPE&&t.push(new vt(t.length,n.TYPE.length)),n.OFFSET&&t.push(new vt(t.length,n.OFFSET.length)),n.DATA&&t.push(new vt(t.length,n.DATA.length)),t=Cc(n.children,t)}return t}function Fd(r){return(r||[]).reduce((t,e)=>t+ +(e===0),0)}function kc(r,t){let e,i,n,s,o,a;return!t||!(s=r.dictionary)?(o=Dc(r,Fc(r,t)),n=new R(r.name,o,r.nullable,Ss(r.customMetadata))):t.has(e=s.id)?(i=(i=s.indexType)?Rc(i):new ae,a=new Ot(t.get(e),i,e,s.isOrdered),n=new R(r.name,a,r.nullable,Ss(r.customMetadata))):(i=(i=s.indexType)?Rc(i):new ae,t.set(e,o=Dc(r,Fc(r,t))),a=new Ot(o,i,e,s.isOrdered),n=new R(r.name,a,r.nullable,Ss(r.customMetadata))),n||null}function Ss(r){return new Map(Object.entries(r||{}))}function Rc(r){return new tt(r.isSigned,r.bitWidth)}function Dc(r,t){let e=r.type.name;switch(e){case"NONE":return new gt;case"null":return new gt;case"binary":return new ve;case"utf8":return new Se;case"bool":return new Te;case"list":return new Yt((t||[])[0]);case"struct":return new W(t||[]);case"struct_":return new W(t||[])}switch(e){case"int":{let i=r.type;return new tt(i.isSigned,i.bitWidth)}case"floatingpoint":{let i=r.type;return new _t(H[i.precision])}case"decimal":{let i=r.type;return new Ee(i.scale,i.precision,i.bitWidth)}case"date":{let i=r.type;return new xe(dt[i.unit])}case"time":{let i=r.type;return new Wt(D[i.unit],i.bitWidth)}case"timestamp":{let i=r.type;return new Ae(D[i.unit],i.timezone)}case"interval":{let i=r.type;return new Oe(yt[i.unit])}case"union":{let i=r.type;return new Ht(J[i.mode],i.typeIds||[],t||[])}case"fixedsizebinary":{let i=r.type;return new Be(i.byteWidth)}case"fixedsizelist":{let i=r.type;return new Kt(i.listSize,(t||[])[0])}case"map":{let i=r.type;return new Qt((t||[])[0],i.keysSorted)}}throw new Error(`Unrecognized type: "${e}"`)}var Rd=mr,Dd=Ft,Tt=class r{static fromJSON(t,e){let i=new r(0,at.V4,e);return i._createHeader=Ld(t,e),i}static decode(t){t=new Dd(S(t));let e=ee.getRootAsMessage(t),i=e.bodyLength(),n=e.version(),s=e.headerType(),o=new r(i,n,s);return o._createHeader=Md(e,s),o}static encode(t){let e=new Rd,i=-1;return t.isSchema()?i=j.encode(e,t.header()):t.isRecordBatch()?i=ft.encode(e,t.header()):t.isDictionaryBatch()&&(i=St.encode(e,t.header())),ee.startMessage(e),ee.addVersion(e,at.V4),ee.addHeader(e,i),ee.addHeaderType(e,t.headerType),ee.addBodyLength(e,BigInt(t.bodyLength)),ee.finishMessageBuffer(e,ee.endMessage(e)),e.asUint8Array()}static from(t,e=0){if(t instanceof j)return new r(0,at.V4,k.Schema,t);if(t instanceof ft)return new r(e,at.V4,k.RecordBatch,t);if(t instanceof St)return new r(e,at.V4,k.DictionaryBatch,t);throw new Error(`Unrecognized Message header: ${t}`)}get type(){return this.headerType}get version(){return this._version}get headerType(){return this._headerType}get bodyLength(){return this._bodyLength}header(){return this._createHeader()}isSchema(){return this.headerType===k.Schema}isRecordBatch(){return this.headerType===k.RecordBatch}isDictionaryBatch(){return this.headerType===k.DictionaryBatch}constructor(t,e,i,n){this._version=e,this._headerType=i,this.body=new Uint8Array(0),n&&(this._createHeader=()=>n),this._bodyLength=bt(t)}},ft=class{get nodes(){return this._nodes}get length(){return this._length}get buffers(){return this._buffers}constructor(t,e,i){this._nodes=e,this._buffers=i,this._length=bt(t)}},St=class{get id(){return this._id}get data(){return this._data}get isDelta(){return this._isDelta}get length(){return this.data.length}get nodes(){return this.data.nodes}get buffers(){return this.data.buffers}constructor(t,e,i=!1){this._data=t,this._isDelta=i,this._id=bt(e)}},vt=class{constructor(t,e){this.offset=bt(t),this.length=bt(e)}},re=class{constructor(t,e){this.length=bt(t),this.nullCount=bt(e)}};function Ld(r,t){return()=>{switch(t){case k.Schema:return j.fromJSON(r);case k.RecordBatch:return ft.fromJSON(r);case k.DictionaryBatch:return St.fromJSON(r)}throw new Error(`Unrecognized Message type: { name: ${k[t]}, type: ${t} }`)}}function Md(r,t){return()=>{switch(t){case k.Schema:return j.decode(r.header(new wt));case k.RecordBatch:return ft.decode(r.header(new Dt),r.version());case k.DictionaryBatch:return St.decode(r.header(new je),r.version())}throw new Error(`Unrecognized Message type: { name: ${k[t]}, type: ${t} }`)}}R.encode=Wd;R.decode=qd;R.fromJSON=kc;j.encode=Gd;j.decode=Ud;j.fromJSON=Lc;ft.encode=Yd;ft.decode=Cd;ft.fromJSON=Lo;St.encode=Hd;St.decode=kd;St.fromJSON=Mc;re.encode=Kd;re.decode=Vd;vt.encode=Qd;vt.decode=Pd;function Ud(r,t=new Map){let e=$d(r,t);return new j(e,Ts(r),t)}function Cd(r,t=at.V4){if(r.compression()!==null)throw new Error("Record batch compression not implemented");return new ft(r.length(),jd(r),zd(r,t))}function kd(r,t=at.V4){return new St(ft.decode(r.data(),t),r.id(),r.isDelta())}function Pd(r){return new vt(r.offset(),r.length())}function Vd(r){return new re(r.length(),r.nullCount())}function jd(r){let t=[];for(let e,i=-1,n=-1,s=r.nodesLength();++i<s;)(e=r.nodes(i))&&(t[++n]=re.decode(e));return t}function zd(r,t){let e=[];for(let i,n=-1,s=-1,o=r.buffersLength();++n<o;)(i=r.buffers(n))&&(t<at.V4&&(i.bb_pos+=8*(n+1)),e[++s]=vt.decode(i));return e}function $d(r,t){let e=[];for(let i,n=-1,s=-1,o=r.fieldsLength();++n<o;)(i=r.fields(n))&&(e[++s]=R.decode(i,t));return e}function Pc(r,t){let e=[];for(let i,n=-1,s=-1,o=r.childrenLength();++n<o;)(i=r.children(n))&&(e[++s]=R.decode(i,t));return e}function qd(r,t){let e,i,n,s,o,a;return!t||!(a=r.dictionary())?(n=jc(r,Pc(r,t)),i=new R(r.name(),n,r.nullable(),Ts(r))):t.has(e=bt(a.id()))?(s=(s=a.indexType())?Vc(s):new ae,o=new Ot(t.get(e),s,e,a.isOrdered()),i=new R(r.name(),o,r.nullable(),Ts(r))):(s=(s=a.indexType())?Vc(s):new ae,t.set(e,n=jc(r,Pc(r,t))),o=new Ot(n,s,e,a.isOrdered()),i=new R(r.name(),o,r.nullable(),Ts(r))),i||null}function Ts(r){let t=new Map;if(r)for(let e,i,n=-1,s=Math.trunc(r.customMetadataLength());++n<s;)(e=r.customMetadata(n))&&(i=e.key())!=null&&t.set(i,e.value());return t}function Vc(r){return new tt(r.isSigned(),r.bitWidth())}function jc(r,t){let e=r.typeType();switch(e){case Q.NONE:return new gt;case Q.Null:return new gt;case Q.Binary:return new ve;case Q.Utf8:return new Se;case Q.Bool:return new Te;case Q.List:return new Yt((t||[])[0]);case Q.Struct_:return new W(t||[])}switch(e){case Q.Int:{let i=r.type(new Zt);return new tt(i.isSigned(),i.bitWidth())}case Q.FloatingPoint:{let i=r.type(new tr);return new _t(i.precision())}case Q.Decimal:{let i=r.type(new fe);return new Ee(i.scale(),i.precision(),i.bitWidth())}case Q.Date:{let i=r.type(new Qe);return new xe(i.unit())}case Q.Time:{let i=r.type(new Re);return new Wt(i.unit(),i.bitWidth())}case Q.Timestamp:{let i=r.type(new De);return new Ae(i.unit(),i.timezone())}case Q.Interval:{let i=r.type(new er);return new Oe(i.unit())}case Q.Union:{let i=r.type(new te);return new Ht(i.mode(),i.typeIdsArray()||[],t||[])}case Q.FixedSizeBinary:{let i=r.type(new Xe);return new Be(i.byteWidth())}case Q.FixedSizeList:{let i=r.type(new Ze);return new Kt(i.listSize(),(t||[])[0])}case Q.Map:{let i=r.type(new rr);return new Qt((t||[])[0],i.keysSorted())}}throw new Error(`Unrecognized type: "${Q[e]}" (${e})`)}function Gd(r,t){let e=t.fields.map(s=>R.encode(r,s));wt.startFieldsVector(r,e.length);let i=wt.createFieldsVector(r,e),n=t.metadata&&t.metadata.size>0?wt.createCustomMetadataVector(r,[...t.metadata].map(([s,o])=>{let a=r.createString(`${s}`),c=r.createString(`${o}`);return st.startKeyValue(r),st.addKey(r,a),st.addValue(r,c),st.endKeyValue(r)})):-1;return wt.startSchema(r),wt.addFields(r,i),wt.addEndianness(r,Jd?Ke.Little:Ke.Big),n!==-1&&wt.addCustomMetadata(r,n),wt.endSchema(r)}function Wd(r,t){let e=-1,i=-1,n=-1,s=t.type,o=t.typeId;y.isDictionary(s)?(o=s.dictionary.typeId,n=vs.visit(s,r),i=vs.visit(s.dictionary,r)):i=vs.visit(s,r);let a=(s.children||[]).map(d=>R.encode(r,d)),c=pt.createChildrenVector(r,a),l=t.metadata&&t.metadata.size>0?pt.createCustomMetadataVector(r,[...t.metadata].map(([d,h])=>{let f=r.createString(`${d}`),g=r.createString(`${h}`);return st.startKeyValue(r),st.addKey(r,f),st.addValue(r,g),st.endKeyValue(r)})):-1;return t.name&&(e=r.createString(t.name)),pt.startField(r),pt.addType(r,i),pt.addTypeType(r,o),pt.addChildren(r,c),pt.addNullable(r,!!t.nullable),e!==-1&&pt.addName(r,e),n!==-1&&pt.addDictionary(r,n),l!==-1&&pt.addCustomMetadata(r,l),pt.endField(r)}function Yd(r,t){let e=t.nodes||[],i=t.buffers||[];Dt.startNodesVector(r,e.length);for(let o of e.slice().reverse())re.encode(r,o);let n=r.endVector();Dt.startBuffersVector(r,i.length);for(let o of i.slice().reverse())vt.encode(r,o);let s=r.endVector();return Dt.startRecordBatch(r),Dt.addLength(r,BigInt(t.length)),Dt.addNodes(r,n),Dt.addBuffers(r,s),Dt.endRecordBatch(r)}function Hd(r,t){let e=ft.encode(r,t.data);return je.startDictionaryBatch(r),je.addId(r,BigInt(t.id)),je.addIsDelta(r,t.isDelta),je.addData(r,e),je.endDictionaryBatch(r)}function Kd(r,t){return Xr.createFieldNode(r,BigInt(t.length),BigInt(t.nullCount))}function Qd(r,t){return Jr.createBuffer(r,BigInt(t.offset),BigInt(t.length))}var Jd=(()=>{let r=new ArrayBuffer(2);return new DataView(r).setInt16(0,256,!0),new Int16Array(r)[0]===256})();var Uo=r=>`Expected ${k[r]} Message in stream, but was null or length 0.`,Co=r=>`Header pointer of flatbuffer-encoded ${k[r]} Message is null or length 0.`,zc=(r,t)=>`Expected to read ${r} metadata bytes, but only read ${t}.`,$c=(r,t)=>`Expected to read ${r} bytes for message body, but only read ${t}.`,ti=class{constructor(t){this.source=t instanceof me?t:new me(t)}[Symbol.iterator](){return this}next(){let t;return(t=this.readMetadataLength()).done?Y:t.value===-1&&(t=this.readMetadataLength()).done?Y:(t=this.readMetadata(t.value)).done?Y:t}throw(t){return this.source.throw(t)}return(t){return this.source.return(t)}readMessage(t){let e;if((e=this.next()).done)return null;if(t!=null&&e.value.headerType!==t)throw new Error(Uo(t));return e.value}readMessageBody(t){if(t<=0)return new Uint8Array(0);let e=S(this.source.read(t));if(e.byteLength<t)throw new Error($c(t,e.byteLength));return e.byteOffset%8===0&&e.byteOffset+e.byteLength<=e.buffer.byteLength?e:e.slice()}readSchema(t=!1){let e=k.Schema,i=this.readMessage(e),n=i?.header();if(t&&!n)throw new Error(Co(e));return n}readMetadataLength(){let t=this.source.read(Es),e=t&&new Ft(t),i=e?.readInt32(0)||0;return{done:i===0,value:i}}readMetadata(t){let e=this.source.read(t);if(!e)return Y;if(e.byteLength<t)throw new Error(zc(t,e.byteLength));return{done:!1,value:Tt.decode(e)}}},Zi=class{constructor(t,e){this.source=t instanceof kt?t:un(t)?new ir(t,e):new kt(t)}[Symbol.asyncIterator](){return this}next(){return p(this,void 0,void 0,function*(){let t;return(t=yield this.readMetadataLength()).done?Y:t.value===-1&&(t=yield this.readMetadataLength()).done?Y:(t=yield this.readMetadata(t.value)).done?Y:t})}throw(t){return p(this,void 0,void 0,function*(){return yield this.source.throw(t)})}return(t){return p(this,void 0,void 0,function*(){return yield this.source.return(t)})}readMessage(t){return p(this,void 0,void 0,function*(){let e;if((e=yield this.next()).done)return null;if(t!=null&&e.value.headerType!==t)throw new Error(Uo(t));return e.value})}readMessageBody(t){return p(this,void 0,void 0,function*(){if(t<=0)return new Uint8Array(0);let e=S(yield this.source.read(t));if(e.byteLength<t)throw new Error($c(t,e.byteLength));return e.byteOffset%8===0&&e.byteOffset+e.byteLength<=e.buffer.byteLength?e:e.slice()})}readSchema(t=!1){return p(this,void 0,void 0,function*(){let e=k.Schema,i=yield this.readMessage(e),n=i?.header();if(t&&!n)throw new Error(Co(e));return n})}readMetadataLength(){return p(this,void 0,void 0,function*(){let t=yield this.source.read(Es),e=t&&new Ft(t),i=e?.readInt32(0)||0;return{done:i===0,value:i}})}readMetadata(t){return p(this,void 0,void 0,function*(){let e=yield this.source.read(t);if(!e)return Y;if(e.byteLength<t)throw new Error(zc(t,e.byteLength));return{done:!1,value:Tt.decode(e)}})}},tn=class extends ti{constructor(t){super(new Uint8Array(0)),this._schema=!1,this._body=[],this._batchIndex=0,this._dictionaryIndex=0,this._json=t instanceof Oi?t:new Oi(t)}next(){let{_json:t}=this;if(!this._schema)return this._schema=!0,{done:!1,value:Tt.fromJSON(t.schema,k.Schema)};if(this._dictionaryIndex<t.dictionaries.length){let e=t.dictionaries[this._dictionaryIndex++];return this._body=e.data.columns,{done:!1,value:Tt.fromJSON(e,k.DictionaryBatch)}}if(this._batchIndex<t.batches.length){let e=t.batches[this._batchIndex++];return this._body=e.columns,{done:!1,value:Tt.fromJSON(e,k.RecordBatch)}}return this._body=[],Y}readMessageBody(t){return e(this._body);function e(i){return(i||[]).reduce((n,s)=>[...n,...s.VALIDITY&&[s.VALIDITY]||[],...s.TYPE&&[s.TYPE]||[],...s.OFFSET&&[s.OFFSET]||[],...s.DATA&&[s.DATA]||[],...e(s.children)],[])}}readMessage(t){let e;if((e=this.next()).done)return null;if(t!=null&&e.value.headerType!==t)throw new Error(Uo(t));return e.value}readSchema(){let t=k.Schema,e=this.readMessage(t),i=e?.header();if(!e||!i)throw new Error(Co(t));return i}},Es=4,Mo="ARROW1",ei=new Uint8Array(Mo.length);for(let r=0;r<Mo.length;r+=1)ei[r]=Mo.codePointAt(r);function xs(r,t=0){for(let e=-1,i=ei.length;++e<i;)if(ei[e]!==r[t+e])return!1;return!0}var ri=ei.length,ko=ri+Es,qc=ri*2+Es;var ot=class r extends yr{constructor(t){super(),this._impl=t}get closed(){return this._impl.closed}get schema(){return this._impl.schema}get autoDestroy(){return this._impl.autoDestroy}get dictionaries(){return this._impl.dictionaries}get numDictionaries(){return this._impl.numDictionaries}get numRecordBatches(){return this._impl.numRecordBatches}get footer(){return this._impl.isFile()?this._impl.footer:null}isSync(){return this._impl.isSync()}isAsync(){return this._impl.isAsync()}isFile(){return this._impl.isFile()}isStream(){return this._impl.isStream()}next(){return this._impl.next()}throw(t){return this._impl.throw(t)}return(t){return this._impl.return(t)}cancel(){return this._impl.cancel()}reset(t){return this._impl.reset(t),this._DOMStream=void 0,this._nodeStream=void 0,this}open(t){let e=this._impl.open(t);return xt(e)?e.then(()=>this):this}readRecordBatch(t){return this._impl.isFile()?this._impl.readRecordBatch(t):null}[Symbol.iterator](){return this._impl[Symbol.iterator]()}[Symbol.asyncIterator](){return this._impl[Symbol.asyncIterator]()}toDOMStream(){return ut.toDOMStream(this.isSync()?{[Symbol.iterator]:()=>this}:{[Symbol.asyncIterator]:()=>this})}toNodeStream(){return ut.toNodeStream(this.isSync()?{[Symbol.iterator]:()=>this}:{[Symbol.asyncIterator]:()=>this},{objectMode:!0})}static throughNode(t){throw new Error('"throughNode" not available in this environment')}static throughDOM(t,e){throw new Error('"throughDOM" not available in this environment')}static from(t){return t instanceof r?t:cn(t)?Zd(t):un(t)?rh(t):xt(t)?p(this,void 0,void 0,function*(){return yield r.from(yield t)}):dn(t)||ai(t)||fn(t)||Lt(t)?eh(new kt(t)):th(new me(t))}static readAll(t){return t instanceof r?t.isSync()?Gc(t):Wc(t):cn(t)||ArrayBuffer.isView(t)||$t(t)||ln(t)?Gc(t):Wc(t)}},ge=class extends ot{constructor(t){super(t),this._impl=t}readAll(){return[...this]}[Symbol.iterator](){return this._impl[Symbol.iterator]()}[Symbol.asyncIterator](){return Et(this,arguments,function*(){yield E(yield*Dr(zt(this[Symbol.iterator]())))})}},nr=class extends ot{constructor(t){super(t),this._impl=t}readAll(){var t,e,i,n;return p(this,void 0,void 0,function*(){let s=new Array;try{for(var o=!0,a=zt(this),c;c=yield a.next(),t=c.done,!t;o=!0){n=c.value,o=!1;let l=n;s.push(l)}}catch(l){e={error:l}}finally{try{!o&&!t&&(i=a.return)&&(yield i.call(a))}finally{if(e)throw e.error}}return s})}[Symbol.iterator](){throw new Error("AsyncRecordBatchStreamReader is not Iterable")}[Symbol.asyncIterator](){return this._impl[Symbol.asyncIterator]()}},sr=class extends ge{constructor(t){super(t),this._impl=t}},en=class extends nr{constructor(t){super(t),this._impl=t}},As=class{get numDictionaries(){return this._dictionaryIndex}get numRecordBatches(){return this._recordBatchIndex}constructor(t=new Map){this.closed=!1,this.autoDestroy=!0,this._dictionaryIndex=0,this._recordBatchIndex=0,this.dictionaries=t}isSync(){return!1}isAsync(){return!1}isFile(){return!1}isStream(){return!1}reset(t){return this._dictionaryIndex=0,this._recordBatchIndex=0,this.schema=t,this.dictionaries=new Map,this}_loadRecordBatch(t,e){let i=this._loadVectors(t,e,this.schema.fields),n=x({type:new W(this.schema.fields),length:t.length,children:i});return new Z(this.schema,n)}_loadDictionaryBatch(t,e){let{id:i,isDelta:n}=t,{dictionaries:s,schema:o}=this,a=s.get(i);if(n||!a){let c=o.dictionaries.get(i),l=this._loadVectors(t.data,e,[c]);return(a&&n?a.concat(new L(l)):new L(l)).memoize()}return a.memoize()}_loadVectors(t,e,i){return new Ri(e,t.nodes,t.buffers,this.dictionaries).visitMany(i)}},ii=class extends As{constructor(t,e){super(e),this._reader=cn(t)?new tn(this._handle=t):new ti(this._handle=t)}isSync(){return!0}isStream(){return!0}[Symbol.iterator](){return this}cancel(){!this.closed&&(this.closed=!0)&&(this.reset()._reader.return(),this._reader=null,this.dictionaries=null)}open(t){return this.closed||(this.autoDestroy=Yc(this,t),this.schema||(this.schema=this._reader.readSchema())||this.cancel()),this}throw(t){return!this.closed&&this.autoDestroy&&(this.closed=!0)?this.reset()._reader.throw(t):Y}return(t){return!this.closed&&this.autoDestroy&&(this.closed=!0)?this.reset()._reader.return(t):Y}next(){if(this.closed)return Y;let t,{_reader:e}=this;for(;t=this._readNextMessageAndValidate();)if(t.isSchema())this.reset(t.header());else if(t.isRecordBatch()){this._recordBatchIndex++;let i=t.header(),n=e.readMessageBody(t.bodyLength);return{done:!1,value:this._loadRecordBatch(i,n)}}else if(t.isDictionaryBatch()){this._dictionaryIndex++;let i=t.header(),n=e.readMessageBody(t.bodyLength),s=this._loadDictionaryBatch(i,n);this.dictionaries.set(i.id,s)}return this.schema&&this._recordBatchIndex===0?(this._recordBatchIndex++,{done:!1,value:new vr(this.schema)}):this.return()}_readNextMessageAndValidate(t){return this._reader.readMessage(t)}},ni=class extends As{constructor(t,e){super(e),this._reader=new Zi(this._handle=t)}isAsync(){return!0}isStream(){return!0}[Symbol.asyncIterator](){return this}cancel(){return p(this,void 0,void 0,function*(){!this.closed&&(this.closed=!0)&&(yield this.reset()._reader.return(),this._reader=null,this.dictionaries=null)})}open(t){return p(this,void 0,void 0,function*(){return this.closed||(this.autoDestroy=Yc(this,t),this.schema||(this.schema=yield this._reader.readSchema())||(yield this.cancel())),this})}throw(t){return p(this,void 0,void 0,function*(){return!this.closed&&this.autoDestroy&&(this.closed=!0)?yield this.reset()._reader.throw(t):Y})}return(t){return p(this,void 0,void 0,function*(){return!this.closed&&this.autoDestroy&&(this.closed=!0)?yield this.reset()._reader.return(t):Y})}next(){return p(this,void 0,void 0,function*(){if(this.closed)return Y;let t,{_reader:e}=this;for(;t=yield this._readNextMessageAndValidate();)if(t.isSchema())yield this.reset(t.header());else if(t.isRecordBatch()){this._recordBatchIndex++;let i=t.header(),n=yield e.readMessageBody(t.bodyLength);return{done:!1,value:this._loadRecordBatch(i,n)}}else if(t.isDictionaryBatch()){this._dictionaryIndex++;let i=t.header(),n=yield e.readMessageBody(t.bodyLength),s=this._loadDictionaryBatch(i,n);this.dictionaries.set(i.id,s)}return this.schema&&this._recordBatchIndex===0?(this._recordBatchIndex++,{done:!1,value:new vr(this.schema)}):yield this.return()})}_readNextMessageAndValidate(t){return p(this,void 0,void 0,function*(){return yield this._reader.readMessage(t)})}},Os=class extends ii{get footer(){return this._footer}get numDictionaries(){return this._footer?this._footer.numDictionaries:0}get numRecordBatches(){return this._footer?this._footer.numRecordBatches:0}constructor(t,e){super(t instanceof Bi?t:new Bi(t),e)}isSync(){return!0}isFile(){return!0}open(t){if(!this.closed&&!this._footer){this.schema=(this._footer=this._readFooter()).schema;for(let e of this._footer.dictionaryBatches())e&&this._readDictionaryBatch(this._dictionaryIndex++)}return super.open(t)}readRecordBatch(t){var e;if(this.closed)return null;this._footer||this.open();let i=(e=this._footer)===null||e===void 0?void 0:e.getRecordBatch(t);if(i&&this._handle.seek(i.offset)){let n=this._reader.readMessage(k.RecordBatch);if(n?.isRecordBatch()){let s=n.header(),o=this._reader.readMessageBody(n.bodyLength);return this._loadRecordBatch(s,o)}}return null}_readDictionaryBatch(t){var e;let i=(e=this._footer)===null||e===void 0?void 0:e.getDictionaryBatch(t);if(i&&this._handle.seek(i.offset)){let n=this._reader.readMessage(k.DictionaryBatch);if(n?.isDictionaryBatch()){let s=n.header(),o=this._reader.readMessageBody(n.bodyLength),a=this._loadDictionaryBatch(s,o);this.dictionaries.set(s.id,a)}}}_readFooter(){let{_handle:t}=this,e=t.size-ko,i=t.readInt32(e),n=t.readAt(e-i,i);return Le.decode(n)}_readNextMessageAndValidate(t){var e;if(this._footer||this.open(),this._footer&&this._recordBatchIndex<this.numRecordBatches){let i=(e=this._footer)===null||e===void 0?void 0:e.getRecordBatch(this._recordBatchIndex);if(i&&this._handle.seek(i.offset))return this._reader.readMessage(t)}return null}},Po=class extends ni{get footer(){return this._footer}get numDictionaries(){return this._footer?this._footer.numDictionaries:0}get numRecordBatches(){return this._footer?this._footer.numRecordBatches:0}constructor(t,...e){let i=typeof e[0]!="number"?e.shift():void 0,n=e[0]instanceof Map?e.shift():void 0;super(t instanceof ir?t:new ir(t,i),n)}isFile(){return!0}isAsync(){return!0}open(t){let e=Object.create(null,{open:{get:()=>super.open}});return p(this,void 0,void 0,function*(){if(!this.closed&&!this._footer){this.schema=(this._footer=yield this._readFooter()).schema;for(let i of this._footer.dictionaryBatches())i&&(yield this._readDictionaryBatch(this._dictionaryIndex++))}return yield e.open.call(this,t)})}readRecordBatch(t){var e;return p(this,void 0,void 0,function*(){if(this.closed)return null;this._footer||(yield this.open());let i=(e=this._footer)===null||e===void 0?void 0:e.getRecordBatch(t);if(i&&(yield this._handle.seek(i.offset))){let n=yield this._reader.readMessage(k.RecordBatch);if(n?.isRecordBatch()){let s=n.header(),o=yield this._reader.readMessageBody(n.bodyLength);return this._loadRecordBatch(s,o)}}return null})}_readDictionaryBatch(t){var e;return p(this,void 0,void 0,function*(){let i=(e=this._footer)===null||e===void 0?void 0:e.getDictionaryBatch(t);if(i&&(yield this._handle.seek(i.offset))){let n=yield this._reader.readMessage(k.DictionaryBatch);if(n?.isDictionaryBatch()){let s=n.header(),o=yield this._reader.readMessageBody(n.bodyLength),a=this._loadDictionaryBatch(s,o);this.dictionaries.set(s.id,a)}}})}_readFooter(){return p(this,void 0,void 0,function*(){let{_handle:t}=this;t._pending&&(yield t._pending);let e=t.size-ko,i=yield t.readInt32(e),n=yield t.readAt(e-i,i);return Le.decode(n)})}_readNextMessageAndValidate(t){return p(this,void 0,void 0,function*(){if(this._footer||(yield this.open()),this._footer&&this._recordBatchIndex<this.numRecordBatches){let e=this._footer.getRecordBatch(this._recordBatchIndex);if(e&&(yield this._handle.seek(e.offset)))return yield this._reader.readMessage(t)}return null})}},Vo=class extends ii{constructor(t,e){super(t,e)}_loadVectors(t,e,i){return new Xn(e,t.nodes,t.buffers,this.dictionaries).visitMany(i)}};function Yc(r,t){return t&&typeof t.autoDestroy=="boolean"?t.autoDestroy:r.autoDestroy}function*Gc(r){let t=ot.from(r);try{if(!t.open({autoDestroy:!1}).closed)do yield t;while(!t.reset().open().closed)}finally{t.cancel()}}function Wc(r){return Et(this,arguments,function*(){let e=yield E(ot.from(r));try{if(!(yield E(e.open({autoDestroy:!1}))).closed)do yield yield E(e);while(!(yield E(e.reset().open())).closed)}finally{yield E(e.cancel())}})}function Zd(r){return new ge(new Vo(r))}function th(r){let t=r.peek(ri+7&-8);return t&&t.byteLength>=4?xs(t)?new sr(new Os(r.read())):new ge(new ii(r)):new ge(new ii(function*(){}()))}function eh(r){return p(this,void 0,void 0,function*(){let t=yield r.peek(ri+7&-8);return t&&t.byteLength>=4?xs(t)?new sr(new Os(yield r.read())):new nr(new ni(r)):new nr(new ni(function(){return Et(this,arguments,function*(){})}()))})}function rh(r){return p(this,void 0,void 0,function*(){let{size:t}=yield r.stat(),e=new ir(r,t);return t>=qc&&xs(yield e.readAt(0,ri+7&-8))?new en(new Po(e)):new nr(new ni(e))})}var et=class r extends b{static assemble(...t){let e=n=>n.flatMap(s=>Array.isArray(s)?e(s):s instanceof Z?s.data.children:s.data),i=new r;return i.visitMany(e(t)),i}constructor(){super(),this._byteLength=0,this._nodes=[],this._buffers=[],this._bufferRegions=[]}visit(t){if(t instanceof L)return this.visitMany(t.data),this;let{type:e}=t;if(!y.isDictionary(e)){let{length:i,nullCount:n}=t;if(i>2147483647)throw new RangeError("Cannot write arrays larger than 2^31 - 1 in length");y.isNull(e)||ie.call(this,n<=0?new Uint8Array(0):zr(t.offset,i,t.nullBitmap)),this.nodes.push(new re(i,n))}return super.visit(t)}visitNull(t){return this}visitDictionary(t){return this.visit(t.clone(t.type.indices))}get nodes(){return this._nodes}get buffers(){return this._buffers}get byteLength(){return this._byteLength}get bufferRegions(){return this._bufferRegions}};function ie(r){let t=r.byteLength+7&-8;return this.buffers.push(r),this.bufferRegions.push(new vt(this._byteLength,t)),this._byteLength+=t,this}function ih(r){let{type:t,length:e,typeIds:i,valueOffsets:n}=r;if(ie.call(this,i),t.mode===J.Sparse)return jo.call(this,r);if(t.mode===J.Dense){if(r.offset<=0)return ie.call(this,n),jo.call(this,r);{let s=i.reduce((d,h)=>Math.max(d,h),i[0]),o=new Int32Array(s+1),a=new Int32Array(s+1).fill(-1),c=new Int32Array(e),l=ci(-n[0],e,n);for(let d,h,f=-1;++f<e;)(h=a[d=i[f]])===-1&&(h=a[d]=l[d]),c[f]=l[f]-h,++o[d];ie.call(this,c);for(let d,h=-1,f=t.children.length;++h<f;)if(d=r.children[h]){let g=t.typeIds[h],M=Math.min(e,o[g]);this.visit(d.slice(a[g],M))}}}return this}function nh(r){let t;return r.nullCount>=r.length?ie.call(this,new Uint8Array(0)):(t=r.values)instanceof Uint8Array?ie.call(this,zr(r.offset,r.length,t)):ie.call(this,hr(r.values))}function or(r){return ie.call(this,r.values.subarray(0,r.length*r.stride))}function Hc(r){let{length:t,values:e,valueOffsets:i}=r,n=i[0],s=i[t],o=Math.min(s-n,e.byteLength-n);return ie.call(this,ci(-i[0],t,i)),ie.call(this,e.subarray(n,n+o)),this}function zo(r){let{length:t,valueOffsets:e}=r;return e&&ie.call(this,ci(e[0],t,e)),this.visit(r.children[0])}function jo(r){return this.visitMany(r.type.children.map((t,e)=>r.children[e]).filter(Boolean))[0]}et.prototype.visitBool=nh;et.prototype.visitInt=or;et.prototype.visitFloat=or;et.prototype.visitUtf8=Hc;et.prototype.visitBinary=Hc;et.prototype.visitFixedSizeBinary=or;et.prototype.visitDate=or;et.prototype.visitTimestamp=or;et.prototype.visitTime=or;et.prototype.visitDecimal=or;et.prototype.visitList=zo;et.prototype.visitStruct=jo;et.prototype.visitUnion=ih;et.prototype.visitInterval=or;et.prototype.visitFixedSizeList=zo;et.prototype.visitMap=zo;var Sr=class extends yr{static throughNode(t){throw new Error('"throughNode" not available in this environment')}static throughDOM(t,e){throw new Error('"throughDOM" not available in this environment')}constructor(t){super(),this._position=0,this._started=!1,this._sink=new pe,this._schema=null,this._dictionaryBlocks=[],this._recordBatchBlocks=[],this._dictionaryDeltaOffsets=new Map,mt(t)||(t={autoDestroy:!0,writeLegacyIpcFormat:!1}),this._autoDestroy=typeof t.autoDestroy=="boolean"?t.autoDestroy:!0,this._writeLegacyIpcFormat=typeof t.writeLegacyIpcFormat=="boolean"?t.writeLegacyIpcFormat:!1}toString(t=!1){return this._sink.toString(t)}toUint8Array(t=!1){return this._sink.toUint8Array(t)}writeAll(t){return xt(t)?t.then(e=>this.writeAll(e)):Lt(t)?qo(this,t):$o(this,t)}get closed(){return this._sink.closed}[Symbol.asyncIterator](){return this._sink[Symbol.asyncIterator]()}toDOMStream(t){return this._sink.toDOMStream(t)}toNodeStream(t){return this._sink.toNodeStream(t)}close(){return this.reset()._sink.close()}abort(t){return this.reset()._sink.abort(t)}finish(){return this._autoDestroy?this.close():this.reset(this._sink,this._schema),this}reset(t=this._sink,e=null){return t===this._sink||t instanceof pe?this._sink=t:(this._sink=new pe,t&&ba(t)?this.toDOMStream({type:"bytes"}).pipeTo(t):t&&_a(t)&&this.toNodeStream({objectMode:!1}).pipe(t)),this._started&&this._schema&&this._writeFooter(this._schema),this._started=!1,this._dictionaryBlocks=[],this._recordBatchBlocks=[],this._dictionaryDeltaOffsets=new Map,(!e||!Ir(e,this._schema))&&(e==null?(this._position=0,this._schema=null):(this._started=!0,this._schema=e,this._writeSchema(e))),this}write(t){let e=null;if(this._sink){if(t==null)return this.finish()&&void 0;if(t instanceof lt&&!(e=t.schema))return this.finish()&&void 0;if(t instanceof Z&&!(e=t.schema))return this.finish()&&void 0}else throw new Error("RecordBatchWriter is closed");if(e&&!Ir(e,this._schema)){if(this._started&&this._autoDestroy)return this.close();this.reset(this._sink,e)}t instanceof Z?t instanceof vr||this._writeRecordBatch(t):t instanceof lt?this.writeAll(t.batches):$t(t)&&this.writeAll(t)}_writeMessage(t,e=8){let i=e-1,n=Tt.encode(t),s=n.byteLength,o=this._writeLegacyIpcFormat?4:8,a=s+o+i&~i,c=a-s-o;return t.headerType===k.RecordBatch?this._recordBatchBlocks.push(new Me(a,t.bodyLength,this._position)):t.headerType===k.DictionaryBatch&&this._dictionaryBlocks.push(new Me(a,t.bodyLength,this._position)),this._writeLegacyIpcFormat||this._write(Int32Array.of(-1)),this._write(Int32Array.of(a-o)),s>0&&this._write(n),this._writePadding(c)}_write(t){if(this._started){let e=S(t);e&&e.byteLength>0&&(this._sink.write(e),this._position+=e.byteLength)}return this}_writeSchema(t){return this._writeMessage(Tt.from(t))}_writeFooter(t){return this._writeLegacyIpcFormat?this._write(Int32Array.of(0)):this._write(Int32Array.of(-1,0))}_writeMagic(){return this._write(ei)}_writePadding(t){return t>0?this._write(new Uint8Array(t)):this}_writeRecordBatch(t){let{byteLength:e,nodes:i,bufferRegions:n,buffers:s}=et.assemble(t),o=new ft(t.numRows,i,n),a=Tt.from(o,e);return this._writeDictionaries(t)._writeMessage(a)._writeBodyBuffers(s)}_writeDictionaryBatch(t,e,i=!1){this._dictionaryDeltaOffsets.set(e,t.length+(this._dictionaryDeltaOffsets.get(e)||0));let{byteLength:n,nodes:s,bufferRegions:o,buffers:a}=et.assemble(new L([t])),c=new ft(t.length,s,o),l=new St(c,e,i),d=Tt.from(l,n);return this._writeMessage(d)._writeBodyBuffers(a)}_writeBodyBuffers(t){let e,i,n;for(let s=-1,o=t.length;++s<o;)(e=t[s])&&(i=e.byteLength)>0&&(this._write(e),(n=(i+7&-8)-i)>0&&this._writePadding(n));return this}_writeDictionaries(t){for(let[e,i]of t.dictionaries){let n=this._dictionaryDeltaOffsets.get(e)||0;if(n===0||(i=i?.slice(n)).length>0)for(let s of i.data)this._writeDictionaryBatch(s,e,n>0),n+=s.length}return this}},Tr=class r extends Sr{static writeAll(t,e){let i=new r(e);return xt(t)?t.then(n=>i.writeAll(n)):Lt(t)?qo(i,t):$o(i,t)}},Er=class r extends Sr{static writeAll(t){let e=new r;return xt(t)?t.then(i=>e.writeAll(i)):Lt(t)?qo(e,t):$o(e,t)}constructor(){super(),this._autoDestroy=!0}_writeSchema(t){return this._writeMagic()._writePadding(2)}_writeFooter(t){let e=Le.encode(new Le(t,at.V4,this._recordBatchBlocks,this._dictionaryBlocks));return super._writeFooter(t)._write(e)._write(Int32Array.of(e.byteLength))._writeMagic()}};function $o(r,t){let e=t;t instanceof lt&&(e=t.batches,r.reset(void 0,t.schema));for(let i of e)r.write(i);return r.finish()}function qo(r,t){var e,i,n,s,o,a,c;return p(this,void 0,void 0,function*(){try{for(e=!0,i=zt(t);n=yield i.next(),s=n.done,!s;e=!0){c=n.value,e=!1;let l=c;r.write(l)}}catch(l){o={error:l}}finally{try{!e&&!s&&(a=i.return)&&(yield a.call(i))}finally{if(o)throw o.error}}return r.finish()})}function Kc(r,t){if(Lt(r))return oh(r,t);if($t(r))return sh(r,t);throw new Error("toDOMStream() must be called with an Iterable or AsyncIterable")}function sh(r,t){let e=null,i=t?.type==="bytes"||!1,n=t?.highWaterMark||Math.pow(2,24);return new ReadableStream(Object.assign(Object.assign({},t),{start(o){s(o,e||(e=r[Symbol.iterator]()))},pull(o){e?s(o,e):o.close()},cancel(){(e?.return&&e.return()||!0)&&(e=null)}}),Object.assign({highWaterMark:i?n:void 0},t));function s(o,a){let c,l=null,d=o.desiredSize||null;for(;!(l=a.next(i?d:null)).done;)if(ArrayBuffer.isView(l.value)&&(c=S(l.value))&&(d!=null&&i&&(d=d-c.byteLength+1),l.value=c),o.enqueue(l.value),d!=null&&--d<=0)return;o.close()}}function oh(r,t){let e=null,i=t?.type==="bytes"||!1,n=t?.highWaterMark||Math.pow(2,24);return new ReadableStream(Object.assign(Object.assign({},t),{start(o){return p(this,void 0,void 0,function*(){yield s(o,e||(e=r[Symbol.asyncIterator]()))})},pull(o){return p(this,void 0,void 0,function*(){e?yield s(o,e):o.close()})},cancel(){return p(this,void 0,void 0,function*(){(e?.return&&(yield e.return())||!0)&&(e=null)})}}),Object.assign({highWaterMark:i?n:void 0},t));function s(o,a){return p(this,void 0,void 0,function*(){let c,l=null,d=o.desiredSize||null;for(;!(l=yield a.next(i?d:null)).done;)if(ArrayBuffer.isView(l.value)&&(c=S(l.value))&&(d!=null&&i&&(d=d-c.byteLength+1),l.value=c),o.enqueue(l.value),d!=null&&--d<=0)return;o.close()})}}function Xc(r){return new Go(r)}var Go=class{constructor(t){this._numChunks=0,this._finished=!1,this._bufferedSize=0;let{["readableStrategy"]:e,["writableStrategy"]:i,["queueingStrategy"]:n="count"}=t,s=ya(t,["readableStrategy","writableStrategy","queueingStrategy"]);this._controller=null,this._builder=br(s),this._getSize=n!=="bytes"?Qc:Jc;let{["highWaterMark"]:o=n==="bytes"?Math.pow(2,14):1e3}=Object.assign({},e),{["highWaterMark"]:a=n==="bytes"?Math.pow(2,14):1e3}=Object.assign({},i);this.readable=new ReadableStream({cancel:()=>{this._builder.clear()},pull:c=>{this._maybeFlush(this._builder,this._controller=c)},start:c=>{this._maybeFlush(this._builder,this._controller=c)}},{highWaterMark:o,size:n!=="bytes"?Qc:Jc}),this.writable=new WritableStream({abort:()=>{this._builder.clear()},write:()=>{this._maybeFlush(this._builder,this._controller)},close:()=>{this._maybeFlush(this._builder.finish(),this._controller)}},{highWaterMark:a,size:c=>this._writeValueAndReturnChunkSize(c)})}_writeValueAndReturnChunkSize(t){let e=this._bufferedSize;return this._bufferedSize=this._getSize(this._builder.append(t)),this._bufferedSize-e}_maybeFlush(t,e){e!=null&&(this._bufferedSize>=e.desiredSize&&++this._numChunks&&this._enqueue(e,t.toVector()),t.finished&&((t.length>0||this._numChunks===0)&&++this._numChunks&&this._enqueue(e,t.toVector()),!this._finished&&(this._finished=!0)&&this._enqueue(e,null)))}_enqueue(t,e){this._bufferedSize=0,this._controller=null,e==null?t.close():t.enqueue(e)}},Qc=r=>{var t;return(t=r?.length)!==null&&t!==void 0?t:0},Jc=r=>{var t;return(t=r?.byteLength)!==null&&t!==void 0?t:0};function Bs(r,t){let e=new pe,i=null,n=new ReadableStream({cancel(){return p(this,void 0,void 0,function*(){yield e.close()})},start(a){return p(this,void 0,void 0,function*(){yield o(a,i||(i=yield s()))})},pull(a){return p(this,void 0,void 0,function*(){i?yield o(a,i):a.close()})}});return{writable:new WritableStream(e,Object.assign({highWaterMark:Math.pow(2,14)},r)),readable:n};function s(){return p(this,void 0,void 0,function*(){return yield(yield ot.from(e)).open(t)})}function o(a,c){return p(this,void 0,void 0,function*(){let l=a.desiredSize,d=null;for(;!(d=yield c.next()).done;)if(a.enqueue(d.value),l!=null&&--l<=0)return;a.close()})}}function Ns(r,t){let e=new this(r),i=new kt(e),n=new ReadableStream({cancel(){return p(this,void 0,void 0,function*(){yield i.cancel()})},pull(o){return p(this,void 0,void 0,function*(){yield s(o)})},start(o){return p(this,void 0,void 0,function*(){yield s(o)})}},Object.assign({highWaterMark:Math.pow(2,14)},t));return{writable:new WritableStream(e,r),readable:n};function s(o){return p(this,void 0,void 0,function*(){let a=null,c=o.desiredSize;for(;a=yield i.read(c||null);)if(o.enqueue(a),c!=null&&(c-=a.byteLength)<=0)return;o.close()})}}function xr(r){let t=ot.from(r);return xt(t)?t.then(e=>xr(e)):t.isAsync()?t.readAll().then(e=>new lt(e)):new lt(t.readAll())}function Fs(r,t="stream"){return(t==="stream"?Tr:Er).writeAll(r).toUint8Array(!0)}var lh=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},ro),Oo),_o),io),Xs),bo),{compareSchemas:Ir,compareFields:Ec,compareTypes:xc});ut.toDOMStream=Kc;K.throughDOM=Xc;ot.throughDOM=Bs;sr.throughDOM=Bs;ge.throughDOM=Bs;Sr.throughDOM=Ns;Er.throughDOM=Ns;Tr.throughDOM=Ns;function Wo(r="ws://localhost:3000/"){let t=[],e=!1,i=null,n,s={open(){e=!0,c()},close(){for(e=!1,i=null,n=null;t.length;)t.shift().reject("Socket closed")},error(l){if(i){let{reject:d}=i;i=null,c(),d(l)}else console.error("WebSocket error: ",l)},message({data:l}){if(i){let{query:d,resolve:h,reject:f}=i;if(i=null,c(),typeof l=="string"){let g=JSON.parse(l);g.error?f(g.error):h(g)}else if(d.type==="exec")h();else if(d.type==="arrow")h(xr(l.arrayBuffer()));else throw new Error(`Unexpected socket data: ${l}`)}else console.log("WebSocket message: ",l)}};function o(){n=new WebSocket(r);for(let l in s)n.addEventListener(l,s[l])}function a(l,d,h){n==null&&o(),t.push({query:l,resolve:d,reject:h}),e&&!i&&c()}function c(){t.length&&(i=t.shift(),n.send(JSON.stringify(i.query)))}return{get connected(){return e},query(l){return new Promise((d,h)=>a(l,d,h))}}}var Vt=class{constructor(t,e){t&&(this.table=String(t)),e&&(this.column=e)}get columns(){return this.column?[this.column]:[]}toString(){let{table:t,column:e}=this;if(e){let i=e.startsWith("*")?e:`"${e}"`;return`${t?`${tl(t)}.`:""}${i}`}else return t?tl(t):"NULL"}};function tl(r){return r.split(".").map(e=>`"${e}"`).join(".")}function el(r,t){return r instanceof Vt&&r.column===t}function z(r){return typeof r=="string"?il(r):r}function Ar(r){return typeof r=="string"?rl(r):r}function rl(r){return new Vt(r)}function il(r,t){return arguments.length===1&&(t=r,r=null),new Vt(r,t)}function ar(r){switch(typeof r){case"boolean":return r?"TRUE":"FALSE";case"string":return`'${r}'`;case"number":return Number.isFinite(r)?String(r):"NULL";default:if(r==null)return"NULL";if(r instanceof Date){let t=+r;if(Number.isNaN(t))return"NULL";let e=r.getUTCFullYear(),i=r.getUTCMonth(),n=r.getUTCDate();return t===Date.UTC(e,i,n)?`MAKE_DATE(${e}, ${i+1}, ${n})`:`EPOCH_MS(${t})`}else return r instanceof RegExp?`'${r.source}'`:String(r)}}var Or=r=>typeof r?.addEventListener=="function";function Rs(r){return r instanceof cr}var cr=class{constructor(t,e,i){this._expr=Array.isArray(t)?t:[t],this._deps=e||[],this.annotate(i);let n=this._expr.filter(s=>Or(s));n.length>0?(this._params=Array.from(new Set(n)),this._params.forEach(s=>{s.addEventListener("value",()=>uh(this,this.map?.get("value")))})):this.addEventListener=void 0}get value(){return this}get columns(){let{_params:t,_deps:e}=this;if(t){let i=new Set(t.flatMap(n=>{let s=n.value?.columns;return Array.isArray(s)?s:[]}));if(i.size){let n=new Set(e);return i.forEach(s=>n.add(s)),Array.from(n)}}return e}get column(){return this._deps.length?this._deps[0]:this.columns[0]}annotate(...t){return Object.assign(this,...t)}toString(){return this._expr.map(t=>Or(t)&&!Rs(t)?ar(t.value):t).join("")}addEventListener(t,e){let i=this.map||(this.map=new Map);(i.get(t)||(i.set(t,new Set),i.get(t))).add(e)}};function uh(r,t){if(t?.size)return Promise.allSettled(Array.from(t,e=>e(r)))}function Yo(r,t){let e=[r[0]],i=new Set,n=t.length;for(let s=0,o=0;s<n;){let a=t[s];Or(a)?e[++o]=a:(Array.isArray(a?.columns)&&a.columns.forEach(l=>i.add(l)),e[o]+=typeof a=="string"?a:ar(a));let c=r[++s];Or(e[o])?e[++o]=c:e[o]+=c}return{spans:e,cols:Array.from(i)}}function U(r,...t){let{spans:e,cols:i}=Yo(r,t);return new cr(e,i)}function rn(r){r(this.op,this),this.children?.forEach(t=>t.visit(r))}function nl(r,t){let e=t.filter(n=>n!=null).map(z),i=e.map((n,s)=>s?` ${r} `:"");return e.length===1?i.push(""):e.length>1&&(i[0]="(",i.push(")")),U(i,...e).annotate({op:r,children:e,visit:rn})}var Ho=(...r)=>nl("AND",r.flat()),Ko=(...r)=>nl("OR",r.flat()),dh=r=>t=>U`(${r} ${z(t)})`.annotate({op:r,a:t,visit:rn}),hh=dh("NOT"),sl=r=>t=>U`(${z(t)} ${r})`.annotate({op:r,a:t,visit:rn}),Qo=sl("IS NULL"),fh=sl("IS NOT NULL"),lr=r=>(t,e)=>U`(${z(t)} ${r} ${z(e)})`.annotate({op:r,a:t,b:e,visit:rn}),ph=lr("="),mh=lr("<>"),yh=lr("<"),gh=lr(">"),bh=lr("<="),_h=lr(">="),wh=lr("IS DISTINCT FROM"),Ih=lr("IS NOT DISTINCT FROM");function vh(r,t,e,i){t=z(t);let n=r.startsWith("NOT ")?"NOT ":"";return(e?i?U`${n}(${e[0]} <= ${t} AND ${t} < ${e[1]})`:U`(${t} ${r} ${e[0]} AND ${e[1]})`:U``).annotate({op:r,visit:rn,field:t,range:e})}var Ds=(r,t,e)=>vh("BETWEEN",r,t,e);function Br(r,t){return Array.from({length:r},()=>t)}function jt(r,t){return(...e)=>{let i=e.map(z),n=t?`::${t}`:"";return(i.length?U([`${r}(`,...Br(i.length-1,", "),`)${n}`],...i):U`${r}()${n}`).annotate({func:r,args:i})}}var Sh=jt("REGEXP_MATCHES"),Th=jt("CONTAINS"),Eh=jt("PREFIX"),xh=jt("SUFFIX"),Ah=jt("LOWER"),Oh=jt("UPPER"),Bh=jt("LENGTH"),Nh=jt("ISNAN"),Fh=jt("ISFINITE"),Rh=jt("ISINF");var nn=class r extends cr{constructor(t,e,i,n,s="",o="",a=""){let c;if(n&&!(s||o||a))c=n?U`${e} OVER "${n}"`:U`${e} OVER ()`;else{let f=s&&o?" ":"",g=(s||o)&&a?" ":"";c=U`${e} OVER (${n?`"${n}" `:""}${s}${f}${o}${g}${a})`}i&&(c=U`(${c})::${i}`);let{_expr:d,_deps:h}=c;super(d,h,{window:t,func:e,type:i,name:n,group:s,order:o,frame:a})}get basis(){return this.column}get label(){let{func:t}=this;return t.label??t.toString()}over(t){let{window:e,func:i,type:n,group:s,order:o,frame:a}=this;return new r(e,i,n,t,s,o,a)}partitionby(...t){let e=t.flat().filter(d=>d).map(z),i=U(["PARTITION BY ",Br(e.length-1,", "),""],...e),{window:n,func:s,type:o,name:a,order:c,frame:l}=this;return new r(n,s,o,a,i,c,l)}orderby(...t){let e=t.flat().filter(d=>d).map(z),i=U(["ORDER BY ",Br(e.length-1,", "),""],...e),{window:n,func:s,type:o,name:a,group:c,frame:l}=this;return new r(n,s,o,a,c,i,l)}rows(t){let e=ol("ROWS",t),{window:i,func:n,type:s,name:o,group:a,order:c}=this;return new r(i,n,s,o,a,c,e)}range(t){let e=ol("RANGE",t),{window:i,func:n,type:s,name:o,group:a,order:c}=this;return new r(i,n,s,o,a,c,e)}};function ol(r,t){if(Or(t)){let e=U`${t}`;return e.toString=()=>`${r} ${al(t.value)}`,e}return`${r} ${al(t)}`}function al(r){let[t,e]=r,i=t===0?"CURRENT ROW":Number.isFinite(t)?`${Math.abs(t)} PRECEDING`:"UNBOUNDED PRECEDING",n=e===0?"CURRENT ROW":Number.isFinite(e)?`${Math.abs(e)} FOLLOWING`:"UNBOUNDED FOLLOWING";return`BETWEEN ${i} AND ${n}`}function ne(r,t){return(...e)=>{let i=jt(r)(...e);return new nn(r,i,t)}}var Dh=ne("ROW_NUMBER","INTEGER"),Lh=ne("RANK","INTEGER"),Mh=ne("DENSE_RANK","INTEGER"),Uh=ne("PERCENT_RANK"),Ch=ne("CUME_DIST"),kh=ne("NTILE"),Ph=ne("LAG"),Vh=ne("LEAD"),jh=ne("FIRST_VALUE"),zh=ne("LAST_VALUE"),$h=ne("NTH_VALUE");var Jo=class r extends cr{constructor(t,e,i,n,s){e=(e||[]).map(z);let{strings:o,exprs:a}=qh(t,e,i,n,s),{spans:c,cols:l}=Yo(o,a);super(c,l,{aggregate:t,args:e,type:i,isDistinct:n,filter:s})}get basis(){return this.column}get label(){let{aggregate:t,args:e,isDistinct:i}=this,n=i?"DISTINCT"+(e.length?" ":""):"",s=e.length?`(${n}${e.map(Gh).join(", ")})`:"";return`${t.toLowerCase()}${s}`}distinct(){let{aggregate:t,args:e,type:i,filter:n}=this;return new r(t,e,i,!0,n)}where(t){let{aggregate:e,args:i,type:n,isDistinct:s}=this;return new r(e,i,n,s,t)}window(){let{aggregate:t,args:e,type:i,isDistinct:n}=this,s=new r(t,e,null,n);return new nn(t,s,i)}partitionby(...t){return this.window().partitionby(...t)}orderby(...t){return this.window().orderby(...t)}rows(t,e){return this.window().rows(t,e)}range(t,e){return this.window().range(t,e)}};function qh(r,t,e,i,n){let s=`)${e?`::${e}`:""}`,o=[`${r}(${i?"DISTINCT ":""}`],a=[];return t.length?(o=o.concat([...Br(t.length-1,", "),`${s}${n?" FILTER (WHERE ":""}`,...n?[")"]:[]]),a=[...t,...n?[n]:[]]):o[0]+="*"+s,{exprs:a,strings:o}}function Gh(r){let t=ar(r);return t&&t.startsWith('"')&&t.endsWith('"')?t.slice(1,-1):t}function C(r,t){return(...e)=>new Jo(r,e,t)}var sn=C("COUNT","INTEGER"),Wh=C("AVG"),Yh=C("AVG"),Hh=C("MAD"),Xo=C("MAX"),Zo=C("MIN"),Kh=C("SUM","DOUBLE"),Qh=C("PRODUCT"),Jh=C("MEDIAN"),Xh=C("QUANTILE"),Zh=C("MODE"),tf=C("VARIANCE"),ef=C("STDDEV"),rf=C("SKEWNESS"),nf=C("KURTOSIS"),sf=C("ENTROPY"),of=C("VAR_POP"),af=C("STDDEV_POP"),cf=C("CORR"),lf=C("COVAR_POP"),uf=C("REGR_INTERCEPT"),df=C("REGR_SLOPE"),hf=C("REGR_COUNT"),ff=C("REGR_R2"),pf=C("REGR_SYY"),mf=C("REGR_SXX"),yf=C("REGR_SXY"),gf=C("REGR_AVGX"),bf=C("REGR_AVGY"),_f=C("FIRST"),wf=C("LAST"),If=C("ARG_MIN"),vf=C("ARG_MAX"),Sf=C("STRING_AGG"),Tf=C("ARRAY_AGG");var ta=r=>{let t=z(r);return U`(1000 * (epoch(${t}) - second(${t})) + millisecond(${t}))::DOUBLE`};var be=class r{static select(...t){return new r().select(...t)}static from(...t){return new r().from(...t)}static with(...t){return new r().with(...t)}static union(...t){return new Nr("UNION",t.flat())}static unionAll(...t){return new Nr("UNION ALL",t.flat())}static intersect(...t){return new Nr("INTERSECT",t.flat())}static except(...t){return new Nr("EXCEPT",t.flat())}constructor(){this.query={with:[],select:[],from:[],where:[],groupby:[],having:[],window:[],qualify:[],orderby:[]}}clone(){let t=new r;return t.query={...this.query},t}with(...t){let{query:e}=this;if(t.length===0)return e.with;{let i=[],n=(s,o)=>{let a=o.clone();a.cteFor=this,i.push({as:s,query:a})};return t.flat().forEach(s=>{if(s!=null)if(s.as&&s.query)n(s.as,s.query);else for(let o in s)n(o,s[o])}),e.with=e.with.concat(i),this}}select(...t){let{query:e}=this;if(t.length===0)return e.select;{let i=[];for(let n of t.flat())if(n!=null)if(typeof n=="string")i.push({as:n,expr:z(n)});else if(n instanceof Vt)i.push({as:n.column,expr:n});else if(Array.isArray(n))i.push({as:n[0],expr:n[1]});else for(let s in n)i.push({as:Ls(s),expr:z(n[s])});return e.select=e.select.concat(i),this}}$select(...t){return this.query.select=[],this.select(...t)}distinct(t=!0){return this.query.distinct=!!t,this}from(...t){let{query:e}=this;if(t.length===0)return e.from;{let i=[];return t.flat().forEach(n=>{if(n!=null)if(typeof n=="string")i.push({as:n,from:Ar(n)});else if(n instanceof Vt)i.push({as:n.table,from:n});else if(Ms(n)||Rs(n))i.push({from:n});else if(Array.isArray(n))i.push({as:Ls(n[0]),from:Ar(n[1])});else for(let s in n)i.push({as:Ls(s),from:Ar(n[s])})}),e.from=e.from.concat(i),this}}$from(...t){return this.query.from=[],this.from(...t)}sample(t,e){let{query:i}=this;if(arguments.length===0)return i.sample;{let n=t;return typeof t=="number"&&(n=t>0&&t<1?{perc:100*t,method:e}:{rows:Math.round(t),method:e}),i.sample=n,this}}where(...t){let{query:e}=this;return t.length===0?e.where:(e.where=e.where.concat(t.flat().filter(i=>i)),this)}$where(...t){return this.query.where=[],this.where(...t)}groupby(...t){let{query:e}=this;return t.length===0?e.groupby:(e.groupby=e.groupby.concat(t.flat().filter(i=>i).map(z)),this)}$groupby(...t){return this.query.groupby=[],this.groupby(...t)}having(...t){let{query:e}=this;return t.length===0?e.having:(e.having=e.having.concat(t.flat().filter(i=>i)),this)}window(...t){let{query:e}=this;if(t.length===0)return e.window;{let i=[];return t.flat().forEach(n=>{if(n!=null)for(let s in n)i.push({as:Ls(s),expr:n[s]})}),e.window=e.window.concat(i),this}}qualify(...t){let{query:e}=this;return t.length===0?e.qualify:(e.qualify=e.qualify.concat(t.flat().filter(i=>i)),this)}orderby(...t){let{query:e}=this;return t.length===0?e.orderby:(e.orderby=e.orderby.concat(t.flat().filter(i=>i).map(z)),this)}limit(t){let{query:e}=this;return arguments.length===0?e.limit:(e.limit=Number.isFinite(t)?t:void 0,this)}offset(t){let{query:e}=this;return arguments.length===0?e.offset:(e.offset=Number.isFinite(t)?t:void 0,this)}get subqueries(){let{query:t,cteFor:e}=this,n=(e?.query||t).with?.reduce((o,{as:a,query:c})=>(o[a]=c,o),{}),s=[];return t.from.forEach(({from:o})=>{if(Ms(o))s.push(o);else if(n[o.table]){let a=n[o.table];s.push(a)}}),s}toString(){let{select:t,distinct:e,from:i,sample:n,where:s,groupby:o,having:a,window:c,qualify:l,orderby:d,limit:h,offset:f,with:g}=this.query,M=[];if(g.length){let G=g.map(({as:V,query:rt})=>`"${V}" AS (${rt})`);M.push(`WITH ${G.join(", ")}`)}let we=t.map(({as:G,expr:V})=>el(V,G)&&!V.table?`${V}`:`${V} AS "${G}"`);if(M.push(`SELECT${e?" DISTINCT":""} ${we.join(", ")}`),i.length){let G=i.map(({as:V,from:rt})=>{let Ie=Ms(rt)?`(${rt})`:`${rt}`;return!V||V===rt.table?Ie:`${Ie} AS "${V}"`});M.push(`FROM ${G.join(", ")}`)}if(s.length){let G=s.map(String).filter(V=>V).join(" AND ");G&&M.push(`WHERE ${G}`)}if(n){let{rows:G,perc:V,method:rt,seed:Ie}=n,on=G?`${G} ROWS`:`${V} PERCENT`,an=rt?` (${rt}${Ie!=null?`, ${Ie}`:""})`:"";M.push(`USING SAMPLE ${on}${an}`)}if(o.length&&M.push(`GROUP BY ${o.join(", ")}`),a.length){let G=a.map(String).filter(V=>V).join(" AND ");G&&M.push(`HAVING ${G}`)}if(c.length){let G=c.map(({as:V,expr:rt})=>`"${V}" AS (${rt})`);M.push(`WINDOW ${G.join(", ")}`)}if(l.length){let G=l.map(String).filter(V=>V).join(" AND ");G&&M.push(`QUALIFY ${G}`)}return d.length&&M.push(`ORDER BY ${d.join(", ")}`),Number.isFinite(h)&&M.push(`LIMIT ${h}`),Number.isFinite(f)&&M.push(`OFFSET ${f}`),M.join(" ")}},Nr=class r{constructor(t,e){this.op=t,this.queries=e.map(i=>i.clone()),this.query={orderby:[]}}clone(){let t=new r(this.op,this.queries);return t.query={...this.query},t}orderby(...t){let{query:e}=this;return t.length===0?e.orderby:(e.orderby=e.orderby.concat(t.flat().filter(i=>i).map(z)),this)}limit(t){let{query:e}=this;return arguments.length===0?e.limit:(e.limit=Number.isFinite(t)?t:void 0,this)}offset(t){let{query:e}=this;return arguments.length===0?e.offset:(e.offset=Number.isFinite(t)?t:void 0,this)}get subqueries(){let{queries:t,cteFor:e}=this;return e&&t.forEach(i=>i.cteFor=e),t}toString(){let{op:t,queries:e,query:{orderby:i,limit:n,offset:s}}=this,o=[e.join(` ${t} `)];return i.length&&o.push(`ORDER BY ${i.join(", ")}`),Number.isFinite(n)&&o.push(`LIMIT ${n}`),Number.isFinite(s)&&o.push(`OFFSET ${s}`),o.join(" ")}};function Ms(r){return r instanceof be||r instanceof Nr}function Ls(r){return Ef(r)?r.slice(1,-1):r}function Ef(r){return r[0]==='"'&&r[r.length-1]==='"'}function Us(r,t,{replace:e=!1,temp:i=!0,view:n=!1}={}){return"CREATE"+(e?" OR REPLACE ":" ")+(i?"TEMP ":"")+(n?"VIEW":"TABLE")+(e?" ":" IF NOT EXISTS ")+r+" AS "+t}function cl(r){switch(r){case"BIGINT":case"HUGEINT":case"INTEGER":case"SMALLINT":case"TINYINT":case"UBIGINT":case"UINTEGER":case"USMALLINT":case"UTINYINT":case"DOUBLE":case"FLOAT":case"REAL":case"DECIMAL":return"number";case"DATE":case"TIMESTAMP":case"TIMESTAMPTZ":case"TIMESTAMP WITH TIME ZONE":case"TIME":return"date";case"BOOLEAN":return"boolean";case"VARCHAR":case"UUID":return"string";case"LIST":return"array";case"BLOB":case"STRUCT":case"MAP":return"object";default:throw new Error(`Unsupported type: ${r}`)}}var xf="count",Af="nulls",Of="max",Bf="min",Nf="distinct";var Ff={[xf]:sn,[Nf]:r=>sn(r).distinct(),[Of]:Xo,[Bf]:Zo,[Af]:r=>sn().where(Qo(r))};function ll({table:r,column:t},e){return be.from(r).select(e.map(i=>[i,Ff[i](t)]))}var ul=()=>Object.create(null),Cs=class{constructor(t){this.mc=t,this.clear()}clear(){this.tables=ul()}tableInfo(t){let e=this.tables;if(e[t])return e[t];let i=Rf(this.mc,t).catch(n=>{throw e[t]=null,n});return e[t]=i}async fieldInfo({table:t,column:e,stats:i}){let s=(await this.tableInfo(t))[e];if(s==null)return;if(!i?.length)return s;let o=await this.mc.query(ll(s,i),{persist:!0}),a={...s,...Array.from(o)[0]};for(let c in a){let l=a[c];typeof l=="bigint"&&(a[c]=Number(l))}return a}async queryFields(t){let e=await Df(this,t);return(await Promise.all(e.map(n=>this.fieldInfo(n)))).filter(n=>n)}};async function Rf(r,t){let e=await r.query(`DESCRIBE ${Ar(t)}`,{type:"json",cache:!1}),i=ul();for(let n of e)i[n.column_name]={table:t,column:n.column_name,sqlType:n.column_type,type:cl(n.column_type),nullable:n.null==="YES"};return i}async function Df(r,t){return t.length===1&&t[0].column==="*"?Object.values(await r.tableInfo(t[0].table)):t}function hl(r){let t=2166136261;for(let e=0,i=r.length;e<i;++e){let n=r.charCodeAt(e),s=n&65280;s&&(t=dl(t^s>>8)),t=dl(t^n&255)}return Lf(t)}function dl(r){return r+(r<<1)+(r<<4)+(r<<7)+(r<<8)+(r<<24)}function Lf(r){return r+=r<<13,r^=r>>>7,r+=r<<3,r^=r>>>17,r+=r<<5,r&4294967295}var ml=r=>r,ks=class{constructor(t,{selection:e,temp:i=!0}){this.mc=t,this.selection=e,this.temp=i,this.reset()}reset(){this.enabled=!1,this.clients=null,this.indices=null,this.activeView=null}clear(){this.indices&&(this.mc.cancel(Array.from(this.indices.values(),t=>t.result)),this.indices=null)}index(t,e){if(this.clients!==t){let l=Array.from(t,pl),d=l[0]?.from;this.enabled=l.every(h=>h&&h.from===d),this.clients=t,this.activeView=null,this.clear()}if(!this.enabled)return!1;e=e||this.selection.active;let{source:i}=e;if(i&&i===this.activeView?.source)return!0;if(this.clear(),!i)return!1;let n=this.activeView=Mf(e);if(!n)return!1;this.mc.logger().warn("DATA CUBE INDEX CONSTRUCTION");let s=this.selection.remove(i),o=this.indices=new Map,{mc:a,temp:c}=this;for(let l of t){if(s.skip(l,e))continue;let d=pl(l),h=l.query(s.predicate(l)).select({...n.columns,...d.count}).groupby(Object.keys(n.columns)),[f]=h.subqueries;if(f){let rt=Object.values(n.columns).map(Ie=>Ie.columns[0]);kf(f,rt)}let g=h.orderby();h.query.orderby=[];let M=h.toString(),G=`cube_index_${(hl(M)>>>0).toString(16)}`,V=a.exec(Us(G,M,{temp:c}));o.set(l,{table:G,result:V,order:g,...d})}}async update(){let{clients:t,selection:e,activeView:i}=this,n=i.predicate(e.active.predicate);return Promise.all(Array.from(t).map(s=>this.updateClient(s,n)))}async updateClient(t,e){let i=this.indices.get(t);if(!i)return;e||(e=this.activeView.predicate(this.selection.active.predicate));let{table:n,dims:s,aggr:o,order:a=[]}=i,c=be.select(s,o).from(n).groupby(s).where(e).orderby(a);return this.mc.updateClient(t,c)}};function Mf(r){let{source:t,schema:e}=r,i=r.predicate?.columns;if(!e||!i)return null;let{type:n,scales:s,pixelSize:o=1}=e,a;if(n==="interval"&&s){let c=s.map(l=>Uf(l,o));if(c.some(l=>l==null))return null;c.length===1?(a=l=>l?Ds("active0",l.range.map(c[0])):[],i={active0:c[0](r.predicate.field)}):(a=l=>l?Ho(l.children.map(({range:d},h)=>Ds(`active${h}`,d.map(c[h])))):[],i=Object.fromEntries(r.predicate.children.map((l,d)=>[`active${d}`,c[d](l.field)])))}else if(n==="point")a=ml,i=Object.fromEntries(i.map(c=>[c.toString(),c]));else return null;return{source:t,columns:i,predicate:a}}function Uf(r,t){let{type:e,domain:i,range:n}=r,s,o;switch(e){case"linear":s=ml,o=z;break;case"log":s=Math.log,o=a=>U`LN(${z(a)})`;break;case"symlog":s=a=>Math.sign(a)*Math.log1p(Math.abs(a)),o=a=>(a=z(a),U`SIGN(${a}) * LN(1 + ABS(${a}))`);break;case"sqrt":s=Math.sqrt,o=a=>U`SQRT(${z(a)})`;break;case"utc":case"time":s=a=>+a,o=a=>a instanceof Date?+a:ta(z(a));break}return s?Cf(i,n,t,s,o):null}function Cf(r,t,e,i,n){let s=i(Math.min(r[0],r[1])),o=i(Math.max(r[0],r[1])),a=Math.abs(i(t[1])-i(t[0]))/(o-s)/e,c=e===1?"":`${e}::INTEGER * `;return l=>U`${c}FLOOR(${a}::DOUBLE * (${n(l)} - ${s}::DOUBLE))::INTEGER`}var fl={from:NaN};function pl(r){if(!r.filterIndexable)return fl;let t=r.query(),e=ea(t);if(!e||!t.groupby)return fl;let i=new Set(t.groupby().map(a=>a.column)),n=[],s=[],o;for(let{as:a,expr:{aggregate:c}}of t.select())switch(c?.toUpperCase()){case"COUNT":case"SUM":n.push({[a]:U`SUM("${a}")::DOUBLE`});break;case"AVG":o="_count_",n.push({[a]:U`(SUM("${a}" * ${o}) / SUM(${o}))::DOUBLE`});break;case"MAX":n.push({[a]:U`MAX("${a}")`});break;case"MIN":n.push({[a]:U`MIN("${a}")`});break;default:if(i.has(a))s.push(a);else return null}return{aggr:n,dims:s,count:o?{[o]:U`COUNT(*)`}:{},from:e}}function ea(r){let t=r.subqueries;if(r.select){let i=r.from();if(!i.length)return;if(t.length===0)return i[0].from.table}let e=ea(t[0]);for(let i=1;i<t.length;++i){let n=ea(t[i]);if(n!==void 0&&n!==e)return NaN}return e}function kf(r,t){let e=new Set,i=n=>{e.has(n)||(e.add(n),n.select&&n.from().length&&n.select(t),n.subqueries.forEach(i))};i(r)}var Ps=class{constructor(t,e,i=!0){this.mc=t,this.selection=e,this.clients=new Set,this.indexer=i?new ks(this.mc,{...i,selection:e}):null;let{value:n,activate:s}=this.handlers={value:()=>this.update(),activate:o=>this.indexer?.index(this.clients,o)};e.addEventListener("value",n),e.addEventListener("activate",s)}finalize(){let{value:t,activate:e}=this.handlers;this.selection.removeEventListener("value",t),this.selection.removeEventListener("activate",e)}reset(){this.indexer?.reset()}add(t){return(this.clients=new Set(this.clients)).add(t),this}remove(t){return this.clients.has(t)&&(this.clients=new Set(this.clients)).delete(t),this}update(){let{mc:t,indexer:e,clients:i,selection:n}=this;return e?.index(i)?e.update():Pf(t,i,n)}};function Pf(r,t,e){return Promise.all(Array.from(t).map(i=>{let n=e.predicate(i);if(n!=null)return r.updateClient(i,i.query(n))}))}function Vs(){let r,t,e=new Promise((i,n)=>{r=i,t=n});return e.fulfill=i=>(r(i),e),e.reject=i=>(t(i),e),e}function yl(r,t,e){let i=[],n=0;function s(){let o=Vf(i,t);i=[],n=0;for(let a of o)zf(a,r,e),Gf(a,t)}return{add(o,a){o.request.type==="arrow"?(n=n||requestAnimationFrame(()=>s()),i.push({entry:o,priority:a,index:i.length})):r(o,a)}}}function Vf(r,t){let e=[],i=new Map;for(let n of r){let{entry:{request:s}}=n,o=jf(s.query,t);if(!i.has(o)){let a=[];e.push(a),i.set(o,a)}i.get(o).push(n)}return e}function jf(r,t){let e=`${r}`;if(r instanceof be&&!t.get(e)){if(r.orderby().length||r.where().length||r.qualify().length||r.having().length)return e;let i=r.clone().$select("*"),n=r.groupby();if(n.length){let s={};r.select().forEach(({as:o,expr:a})=>s[o]=a),i.$groupby(n.map(o=>o instanceof Vt&&s[o.column]||o))}return`${i}`}else return e}function zf(r,t,e){if($f(r))t({request:{type:"arrow",cache:!1,record:!1,query:qf(r,e)},result:r.result=Vs()});else for(let{entry:i,priority:n}of r)t(i,n)}function $f(r){if(r.length>1){let t=`${r[0].entry.request.query}`;for(let e=1;e<r.length;++e)if(t!==`${r[e].entry.request.query}`)return!0}return!1}function qf(r,t){let e=r.maps=[],i=new Map;for(let o of r){let{query:a}=o.entry.request,c=[];e.push(c);for(let{as:l,expr:d}of a.select()){let h=`${d}`;i.has(h)||i.set(h,[`col${i.size}`,d]);let[f]=i.get(h);c.push([f,l])}t(`${a}`)}let n=r[0].entry.request.query.clone(),s=n.groupby();if(s.length){let o={};r.maps[0].forEach(([a,c])=>o[c]=a),n.$groupby(s.map(a=>a instanceof Vt&&o[a.column]||a))}return n.$select(Array.from(i.values()))}async function Gf(r,t){let{maps:e,result:i}=r;if(!e)return;let n;try{n=await i}catch(s){for(let{entry:o}of r)o.result.reject(s);return}r.forEach(({entry:s},o)=>{let{request:a,result:c}=s,l=Wf(n,e[o]);a.cache&&t.set(String(a.query),l),c.fulfill(l)})}function Wf(r,t){if(t){let e={};for(let[i,n]of t)e[n]=r.getChild(i);return new r.constructor(e)}else return r}var Yf=typeof requestIdleCallback<"u"?requestIdleCallback:setTimeout,gl=()=>({get:()=>{},set:(r,t)=>t,clear:()=>{}});function bl({max:r=1e3,ttl:t=3*60*60*1e3}={}){let e=new Map;function i(){let n=performance.now()-t,s=null,o=1/0;for(let[a,c]of e){let{last:l}=c;l<o&&(s=a,o=l),n>l&&e.delete(a)}s&&e.delete(s)}return{get(n){let s=e.get(n);if(s)return s.last=performance.now(),s.value},set(n,s){return e.set(n,{last:performance.now(),value:s}),e.size>r&&Yf(i),s},clear(){e=new Map}}}function _l(r){let t=Array.from({length:r},()=>({head:null,tail:null}));return{isEmpty(){return t.every(e=>!e.head)},insert(e,i){let n=t[i];if(!n)throw new Error(`Invalid queue priority rank: ${i}`);let s={item:e,next:null};n.head===null?n.head=n.tail=s:n.tail=n.tail.next=s},remove(e){for(let i of t){let{head:n,tail:s}=i;for(let o=null,a=n;a;o=a,a=a.next)e(a.item)&&(a===n?n=a.next:o.next=a.next,a===s&&(s=o||n));i.head=n,i.tail=s}},next(){for(let e of t){let{head:i}=e;if(i!==null)return e.head=i.next,e.tail===i&&(e.tail=null),i.item}}}}var _e={High:0,Normal:1,Low:2};function wl(){let r=_l(3),t,e,i,n=[],s=null,o;function a(){if(s||r.isEmpty())return;let{request:h,result:f}=r.next();s=d(h,f),s.finally(()=>{s=null,a()})}function c(h,f=_e.Normal){r.insert(h,f),a()}function l(h){n.length&&h&&n.forEach(f=>f.add(h))}async function d(h,f){try{let{query:g,type:M,cache:we=!1,record:G=!0,options:V}=h,rt=g?`${g}`:null;if(G&&l(rt),we){let an=e.get(rt);if(an){i.debug("Cache"),f.fulfill(an);return}}let Ie=performance.now(),on=await t.query({type:M,sql:rt,...V});we&&e.set(rt,on),i.debug(`Request: ${(performance.now()-Ie).toFixed(1)}`),f.fulfill(on)}catch(g){f.reject(g)}}return{cache(h){return h!==void 0?e=h===!0?bl():h||gl():e},logger(h){return h?i=h:i},connector(h){return h?t=h:t},consolidate(h){h&&!o?o=yl(c,e,l):!h&&o&&(o=null)},request(h,f=_e.Normal){let g=Vs(),M={request:h,result:g};return o?o.add(M,f):c(M,f),g},cancel(h){let f=new Set(h);r.remove(({result:g})=>f.has(g))},clear(){r.remove(({result:h})=>(h.reject("Cleared"),!0))},record(){let h=[],f={add(g){h.push(g)},reset(){h=[]},snapshot(){return h.slice()},stop(){return n=n.filter(g=>g!==f),h}};return n.push(f),f}}}function Il(){return{debug(){},info(){},log(){},warn(){},error(){}}}var js;function ra(r){return r?js=r:js==null&&(js=new zs),js}var zs=class{constructor(t=Wo(),e={}){this.catalog=new Cs(this),this.manager=e.manager||wl(),this.logger(e.logger||console),this.configure(e),this.databaseConnector(t),this.clear()}logger(t){return arguments.length&&(this._logger=t||Il(),this.manager.logger(this._logger)),this._logger}configure({cache:t=!0,consolidate:e=!0,indexes:i=!0}){this.manager.cache(t),this.manager.consolidate(e),this.indexes=i}clear({clients:t=!0,cache:e=!0,catalog:i=!1}={}){this.manager.clear(),t&&(this.clients?.forEach(n=>this.disconnect(n)),this.filterGroups?.forEach(n=>n.finalize()),this.clients=new Set,this.filterGroups=new Map),e&&this.manager.cache().clear(),i&&this.catalog.clear()}databaseConnector(t){return this.manager.connector(t)}cancel(t){this.manager.cancel(t)}exec(t,{priority:e=_e.Normal}={}){return this.manager.request({type:"exec",query:t},e)}query(t,{type:e="arrow",cache:i=!0,priority:n=_e.Normal,...s}={}){return this.manager.request({type:e,query:t,cache:i,options:s},n)}prefetch(t,e={}){return this.query(t,{...e,cache:!0,priority:_e.Low})}createBundle(t,e,i=_e.Low){let n={name:t,queries:e};return this.manager.request({type:"create-bundle",options:n},i)}loadBundle(t,e=_e.High){let i={name:t};return this.manager.request({type:"load-bundle",options:i},e)}updateClient(t,e,i=_e.Normal){return t.queryPending(),this.query(e,{priority:i}).then(n=>t.queryResult(n).update(),n=>{t.queryError(n),this._logger.error(n)})}requestQuery(t,e){return this.filterGroups.get(t.filterBy)?.reset(),e?this.updateClient(t,e):t.update()}async connect(t){let{catalog:e,clients:i,filterGroups:n,indexes:s}=this;if(i.has(t))throw new Error("Client already connected.");i.add(t);let o=t.fields();o?.length&&t.fieldInfo(await e.queryFields(o));let a=t.filterBy;if(a)if(n.has(a))n.get(a).add(t);else{let c=new Ps(this,a,s);n.set(a,c.add(t))}t.requestQuery()}disconnect(t){let{clients:e,filterGroups:i}=this;e.has(t)&&(e.delete(t),i.get(t.filterBy)?.remove(t))}};var vl={};function ia(r,t=!1){let e,i,n=vl;function s(l){e=r(l).then(()=>{if(i){let{value:d}=i;i=null,s(d)}else e=null})}function o(l){i={event:l}}function a(l){e?o(l):s(l)}function c(l){n!==l&&requestAnimationFrame(()=>{let d=n;n=vl,a(d)}),n=l}return t?c:a}var na=class{constructor(t){this._filterBy=t,this._requestUpdate=ia(()=>this.requestQuery(),!0)}get filterBy(){return this._filterBy}get filterIndexable(){return!0}fields(){return null}fieldInfo(){return this}query(){return null}queryPending(){return this}queryResult(){return this}queryError(t){return console.error(t),this}requestQuery(t){let e=t||this.query(this.filterBy?.predicate(this));return ra().requestQuery(this,e)}requestUpdate(){this._requestUpdate()}update(){return this}};var $s=class{constructor(){this._callbacks=new Map}addEventListener(t,e){this._callbacks.has(t)||this._callbacks.set(t,{callbacks:new Set,pending:null,queue:new sa}),this._callbacks.get(t).callbacks.add(e)}removeEventListener(t,e){let i=this._callbacks.get(t);i&&i.callbacks.delete(e)}willEmit(t,e){return e}emitQueueFilter(){return null}cancel(t){this._callbacks.get(t)?.queue.clear()}emit(t,e){let i=this._callbacks.get(t)||{};if(i.pending)i.queue.enqueue(e,this.emitQueueFilter(t,e));else{let n=this.willEmit(t,e),{callbacks:s,queue:o}=i;if(s?.size){let a=Promise.allSettled(Array.from(s,c=>c(n))).then(()=>{i.pending=null,o.isEmpty()||this.emit(t,o.dequeue())});i.pending=a}}}},sa=class{constructor(){this.clear()}clear(){this.next=null}isEmpty(){return!this.next}enqueue(t,e){let i={value:t};if(e&&this.next){let n=this;for(;n.next;)e(n.next.value)?n=n.next:n.next=n.next.next;n.next=i}else this.next=i}dequeue(){let{next:t}=this;return this.next=t?.next,t?.value}};function oa(r,t){return r===t?!1:r instanceof Date&&t instanceof Date?+r!=+t:Array.isArray(r)&&Array.isArray(t)?Hf(r,t):!0}function Hf(r,t){if(r.length!==t.length)return!0;for(let e=0;e<r.length;++e)if(r[e]!==t[e])return!0;return!1}function qs(r){return r instanceof si}var si=class r extends $s{constructor(t){super(),this._value=t}static value(t){return new r(t)}static array(t){if(t.some(e=>qs(e))){let e=new r,i=()=>e.update(t.map(n=>qs(n)?n.value:n));return i(),t.forEach(n=>qs(n)?n.addEventListener("value",i):0),e}return new r(t)}get value(){return this._value}update(t,{force:e}={}){return oa(this._value,t)||e?this.emit("value",t):this.cancel("value"),this}willEmit(t,e){return t==="value"&&(this._value=e),e}};function Kf(r){return r instanceof Gs}var Gs=class r extends si{static intersect({cross:t=!1}={}){return new r(new Fr({cross:t}))}static union({cross:t=!1}={}){return new r(new Fr({cross:t,union:!0}))}static single({cross:t=!1}={}){return new r(new Fr({cross:t,single:!0}))}static crossfilter(){return new r(new Fr({cross:!0}))}constructor(t=new Fr){super([]),this._resolved=this._value,this._resolver=t}clone(){let t=new r(this._resolver);return t._value=t._resolved=this._value,t}remove(t){let e=this.clone();return e._value=e._resolved=e._resolver.resolve(this._resolved,{source:t}),e._value.active={source:t},e}get active(){return this.clauses.active}get value(){return this.active?.value}get clauses(){return super.value}get single(){return this._resolver.single}activate(t){this.emit("activate",t)}update(t){return this._resolved=this._resolver.resolve(this._resolved,t,!0),this._resolved.active=t,super.update(this._resolved)}willEmit(t,e){return t==="value"?(this._value=e,this.value):e}emitQueueFilter(t,e){return t==="value"?this._resolver.queueFilter(e):null}skip(t,e){return this._resolver.skip(t,e)}predicate(t,e=!1){let{clauses:i}=this,n=e?null:i.active;return this._resolver.predicate(i,n,t)}},Fr=class{constructor({union:t,cross:e,single:i}={}){this.union=!!t,this.cross=!!e,this.single=!!i}resolve(t,e,i=!1){let{source:n,predicate:s}=e,o=t.filter(c=>n!==c.source),a=this.single?[]:o;return this.single&&i&&o.forEach(c=>c.source?.reset?.()),s&&a.push(e),a}skip(t,e){return this.cross&&e?.clients?.has(t)}predicate(t,e,i){let{union:n}=this;if(this.skip(i,e))return;let s=t.filter(o=>!this.skip(i,o)).map(o=>o.predicate);return n&&s.length>1?Ko(s):s}queueFilter(t){if(this.cross){let e=t.active?.source;return i=>i.active?.source!==e}}};function Qf(r="http://localhost:3000/"){return{async query(t){let e=fetch(r,{method:"POST",mode:"cors",cache:"no-cache",credentials:"omit",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});return t.type==="exec"?e:t.type==="arrow"?xr(e):(await e).json()}}}var Jf=Object.create,Sl=Object.defineProperty,Xf=Object.getOwnPropertyDescriptor,Zf=Object.getOwnPropertyNames,tp=Object.getPrototypeOf,ep=Object.prototype.hasOwnProperty,rp=(r,t)=>()=>(t||r((t={exports:{}}).exports,t),t.exports),ip=(r,t,e,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Zf(t))!ep.call(r,n)&&n!==e&&Sl(r,n,{get:()=>t[n],enumerable:!(i=Xf(t,n))||i.enumerable});return r},np=(r,t,e)=>(e=r!=null?Jf(tp(r)):{},ip(t||!r||!r.__esModule?Sl(e,"default",{value:r,enumerable:!0}):e,r)),sp=rp((r,t)=>{t.exports=Worker}),op=(r=>(r[r.UNDEFINED=0]="UNDEFINED",r[r.AUTOMATIC=1]="AUTOMATIC",r[r.READ_ONLY=2]="READ_ONLY",r[r.READ_WRITE=3]="READ_WRITE",r))(op||{}),ap=(r=>(r[r.IDENTIFIER=0]="IDENTIFIER",r[r.NUMERIC_CONSTANT=1]="NUMERIC_CONSTANT",r[r.STRING_CONSTANT=2]="STRING_CONSTANT",r[r.OPERATOR=3]="OPERATOR",r[r.KEYWORD=4]="KEYWORD",r[r.COMMENT=5]="COMMENT",r))(ap||{}),cp=(r=>(r[r.NONE=0]="NONE",r[r.DEBUG=1]="DEBUG",r[r.INFO=2]="INFO",r[r.WARNING=3]="WARNING",r[r.ERROR=4]="ERROR",r))(cp||{}),lp=(r=>(r[r.NONE=0]="NONE",r[r.CONNECT=1]="CONNECT",r[r.DISCONNECT=2]="DISCONNECT",r[r.OPEN=3]="OPEN",r[r.QUERY=4]="QUERY",r[r.INSTANTIATE=5]="INSTANTIATE",r))(lp||{}),up=(r=>(r[r.NONE=0]="NONE",r[r.OK=1]="OK",r[r.ERROR=2]="ERROR",r[r.START=3]="START",r[r.RUN=4]="RUN",r[r.CAPTURE=5]="CAPTURE",r))(up||{}),dp=(r=>(r[r.NONE=0]="NONE",r[r.WEB_WORKER=1]="WEB_WORKER",r[r.NODE_WORKER=2]="NODE_WORKER",r[r.BINDINGS=3]="BINDINGS",r[r.ASYNC_DUCKDB=4]="ASYNC_DUCKDB",r))(dp||{}),Tl=class{log(r){}},El=class{constructor(r=2){this.level=r}log(r){r.level>=this.level&&console.log(r)}};var hp=(r=>(r[r.SUCCESS=0]="SUCCESS",r))(hp||{}),fp=class{constructor(r,t){this._bindings=r,this._conn=t}get bindings(){return this._bindings}async close(){return this._bindings.disconnect(this._conn)}useUnsafe(r){return r(this._bindings,this._conn)}async query(r){this._bindings.logger.log({timestamp:new Date,level:2,origin:4,topic:4,event:4,value:r});let t=await this._bindings.runQuery(this._conn,r),e=ot.from(t);return console.assert(e.isSync(),"Reader is not sync"),console.assert(e.isFile(),"Reader is not file"),new lt(e)}async send(r){this._bindings.logger.log({timestamp:new Date,level:2,origin:4,topic:4,event:4,value:r});let t=await this._bindings.startPendingQuery(this._conn,r);for(;t==null;)t=await this._bindings.pollPendingQuery(this._conn);let e=new xl(this._bindings,this._conn,t),i=await ot.from(e);return console.assert(i.isAsync()),console.assert(i.isStream()),i}async cancelSent(){return await this._bindings.cancelPendingQuery(this._conn)}async getTableNames(r){return await this._bindings.getTableNames(this._conn,r)}async prepare(r){let t=await this._bindings.createPrepared(this._conn,r);return new pp(this._bindings,this._conn,t)}async insertArrowTable(r,t){let e=Fs(r,"stream");await this.insertArrowFromIPCStream(e,t)}async insertArrowFromIPCStream(r,t){await this._bindings.insertArrowFromIPCStream(this._conn,r,t)}async insertCSVFromPath(r,t){await this._bindings.insertCSVFromPath(this._conn,r,t)}async insertJSONFromPath(r,t){await this._bindings.insertJSONFromPath(this._conn,r,t)}},xl=class{constructor(r,t,e){this.db=r,this.conn=t,this.header=e,this._first=!0,this._depleted=!1,this._inFlight=null}async next(){if(this._first)return this._first=!1,{done:!1,value:this.header};if(this._depleted)return{done:!0,value:null};let r;return this._inFlight!=null?(r=await this._inFlight,this._inFlight=null):r=await this.db.fetchQueryResults(this.conn),this._depleted=r.length==0,this._depleted||(this._inFlight=this.db.fetchQueryResults(this.conn)),{done:this._depleted,value:r}}[Symbol.asyncIterator](){return this}},pp=class{constructor(r,t,e){this.bindings=r,this.connectionId=t,this.statementId=e}async close(){await this.bindings.closePrepared(this.connectionId,this.statementId)}async query(...r){let t=await this.bindings.runPrepared(this.connectionId,this.statementId,r),e=ot.from(t);return console.assert(e.isSync()),console.assert(e.isFile()),new lt(e)}async send(...r){let t=await this.bindings.sendPrepared(this.connectionId,this.statementId,r),e=new xl(this.bindings,this.connectionId,t),i=await ot.from(e);return console.assert(i.isAsync()),console.assert(i.isStream()),i}},mp=(r=>(r.CANCEL_PENDING_QUERY="CANCEL_PENDING_QUERY",r.CLOSE_PREPARED="CLOSE_PREPARED",r.COLLECT_FILE_STATISTICS="COLLECT_FILE_STATISTICS",r.CONNECT="CONNECT",r.COPY_FILE_TO_BUFFER="COPY_FILE_TO_BUFFER",r.COPY_FILE_TO_PATH="COPY_FILE_TO_PATH",r.CREATE_PREPARED="CREATE_PREPARED",r.DISCONNECT="DISCONNECT",r.DROP_FILE="DROP_FILE",r.DROP_FILES="DROP_FILES",r.EXPORT_FILE_STATISTICS="EXPORT_FILE_STATISTICS",r.FETCH_QUERY_RESULTS="FETCH_QUERY_RESULTS",r.FLUSH_FILES="FLUSH_FILES",r.GET_FEATURE_FLAGS="GET_FEATURE_FLAGS",r.GET_TABLE_NAMES="GET_TABLE_NAMES",r.GET_VERSION="GET_VERSION",r.GLOB_FILE_INFOS="GLOB_FILE_INFOS",r.INSERT_ARROW_FROM_IPC_STREAM="INSERT_ARROW_FROM_IPC_STREAM",r.INSERT_CSV_FROM_PATH="IMPORT_CSV_FROM_PATH",r.INSERT_JSON_FROM_PATH="IMPORT_JSON_FROM_PATH",r.INSTANTIATE="INSTANTIATE",r.OPEN="OPEN",r.PING="PING",r.POLL_PENDING_QUERY="POLL_PENDING_QUERY",r.REGISTER_FILE_BUFFER="REGISTER_FILE_BUFFER",r.REGISTER_FILE_HANDLE="REGISTER_FILE_HANDLE",r.REGISTER_FILE_URL="REGISTER_FILE_URL",r.RESET="RESET",r.RUN_PREPARED="RUN_PREPARED",r.RUN_QUERY="RUN_QUERY",r.SEND_PREPARED="SEND_PREPARED",r.START_PENDING_QUERY="START_PENDING_QUERY",r.TOKENIZE="TOKENIZE",r))(mp||{}),yp=(r=>(r.CONNECTION_INFO="CONNECTION_INFO",r.ERROR="ERROR",r.FEATURE_FLAGS="FEATURE_FLAGS",r.FILE_BUFFER="FILE_BUFFER",r.FILE_INFOS="FILE_INFOS",r.FILE_SIZE="FILE_SIZE",r.FILE_STATISTICS="FILE_STATISTICS",r.INSTANTIATE_PROGRESS="INSTANTIATE_PROGRESS",r.LOG="LOG",r.OK="OK",r.PREPARED_STATEMENT_ID="PREPARED_STATEMENT_ID",r.QUERY_PLAN="QUERY_PLAN",r.QUERY_RESULT="QUERY_RESULT",r.QUERY_RESULT_CHUNK="QUERY_RESULT_CHUNK",r.QUERY_RESULT_HEADER="QUERY_RESULT_HEADER",r.QUERY_RESULT_HEADER_OR_NULL="QUERY_RESULT_HEADER_OR_NULL",r.REGISTERED_FILE="REGISTERED_FILE",r.SCRIPT_TOKENS="SCRIPT_TOKENS",r.SUCCESS="SUCCESS",r.TABLE_NAMES="TABLE_NAMES",r.VERSION_STRING="VERSION_STRING",r))(yp||{}),P=class{constructor(r,t){this.promiseResolver=()=>{},this.promiseRejecter=()=>{},this.type=r,this.data=t,this.promise=new Promise((e,i)=>{this.promiseResolver=e,this.promiseRejecter=i})}};function Ws(r){switch(r.typeId){case u.Binary:return{sqlType:"binary"};case u.Bool:return{sqlType:"bool"};case u.Date:return{sqlType:"date"};case u.DateDay:return{sqlType:"date32[d]"};case u.DateMillisecond:return{sqlType:"date64[ms]"};case u.Decimal:{let t=r;return{sqlType:"decimal",precision:t.precision,scale:t.scale}}case u.Float:return{sqlType:"float"};case u.Float16:return{sqlType:"float16"};case u.Float32:return{sqlType:"float32"};case u.Float64:return{sqlType:"float64"};case u.Int:return{sqlType:"int32"};case u.Int16:return{sqlType:"int16"};case u.Int32:return{sqlType:"int32"};case u.Int64:return{sqlType:"int64"};case u.Uint16:return{sqlType:"uint16"};case u.Uint32:return{sqlType:"uint32"};case u.Uint64:return{sqlType:"uint64"};case u.Uint8:return{sqlType:"uint8"};case u.IntervalDayTime:return{sqlType:"interval[dt]"};case u.IntervalYearMonth:return{sqlType:"interval[m]"};case u.List:return{sqlType:"list",valueType:Ws(r.valueType)};case u.FixedSizeBinary:return{sqlType:"fixedsizebinary",byteWidth:r.byteWidth};case u.Null:return{sqlType:"null"};case u.Utf8:return{sqlType:"utf8"};case u.Struct:return{sqlType:"struct",fields:r.children.map(t=>ha(t.name,t.type))};case u.Map:{let t=r;return{sqlType:"map",keyType:Ws(t.keyType),valueType:Ws(t.valueType)}}case u.Time:return{sqlType:"time[s]"};case u.TimeMicrosecond:return{sqlType:"time[us]"};case u.TimeMillisecond:return{sqlType:"time[ms]"};case u.TimeNanosecond:return{sqlType:"time[ns]"};case u.TimeSecond:return{sqlType:"time[s]"};case u.Timestamp:return{sqlType:"timestamp",timezone:r.timezone||void 0};case u.TimestampSecond:return{sqlType:"timestamp[s]",timezone:r.timezone||void 0};case u.TimestampMicrosecond:return{sqlType:"timestamp[us]",timezone:r.timezone||void 0};case u.TimestampNanosecond:return{sqlType:"timestamp[ns]",timezone:r.timezone||void 0};case u.TimestampMillisecond:return{sqlType:"timestamp[ms]",timezone:r.timezone||void 0}}throw new Error("unsupported arrow type: ".concat(r.toString()))}function ha(r,t){let e=Ws(t);return e.name=r,e}var gp=new TextEncoder,Al=class{constructor(r,t=null){this._onInstantiationProgress=[],this._worker=null,this._workerShutdownPromise=null,this._workerShutdownResolver=()=>{},this._nextMessageId=0,this._pendingRequests=new Map,this._logger=r,this._onMessageHandler=this.onMessage.bind(this),this._onErrorHandler=this.onError.bind(this),this._onCloseHandler=this.onClose.bind(this),t!=null&&this.attach(t)}get logger(){return this._logger}attach(r){this._worker=r,this._worker.addEventListener("message",this._onMessageHandler),this._worker.addEventListener("error",this._onErrorHandler),this._worker.addEventListener("close",this._onCloseHandler),this._workerShutdownPromise=new Promise((t,e)=>{this._workerShutdownResolver=t})}detach(){this._worker&&(this._worker.removeEventListener("message",this._onMessageHandler),this._worker.removeEventListener("error",this._onErrorHandler),this._worker.removeEventListener("close",this._onCloseHandler),this._worker=null,this._workerShutdownResolver(null),this._workerShutdownPromise=null,this._workerShutdownResolver=()=>{})}async terminate(){this._worker&&(this._worker.terminate(),this._worker=null,this._workerShutdownPromise=null,this._workerShutdownResolver=()=>{})}async postTask(r,t=[]){if(!this._worker){console.error("cannot send a message since the worker is not set!");return}let e=this._nextMessageId++;return this._pendingRequests.set(e,r),this._worker.postMessage({messageId:e,type:r.type,data:r.data},t),await r.promise}onMessage(r){var t;let e=r.data;switch(e.type){case"LOG":{this._logger.log(e.data);return}case"INSTANTIATE_PROGRESS":{for(let n of this._onInstantiationProgress)n(e.data);return}}let i=this._pendingRequests.get(e.requestId);if(!i){console.warn("unassociated response: [".concat(e.requestId,", ").concat(e.type.toString(),"]"));return}if(this._pendingRequests.delete(e.requestId),e.type=="ERROR"){let n=new Error(e.data.message);n.name=e.data.name,(t=Object.getOwnPropertyDescriptor(n,"stack"))!=null&&t.writable&&(n.stack=e.data.stack),i.promiseRejecter(n);return}switch(i.type){case"CLOSE_PREPARED":case"COLLECT_FILE_STATISTICS":case"COPY_FILE_TO_PATH":case"DISCONNECT":case"DROP_FILE":case"DROP_FILES":case"FLUSH_FILES":case"INSERT_ARROW_FROM_IPC_STREAM":case"IMPORT_CSV_FROM_PATH":case"IMPORT_JSON_FROM_PATH":case"OPEN":case"PING":case"REGISTER_FILE_BUFFER":case"REGISTER_FILE_HANDLE":case"REGISTER_FILE_URL":case"RESET":if(e.type=="OK"){i.promiseResolver(e.data);return}break;case"INSTANTIATE":if(this._onInstantiationProgress=[],e.type=="OK"){i.promiseResolver(e.data);return}break;case"GLOB_FILE_INFOS":if(e.type=="FILE_INFOS"){i.promiseResolver(e.data);return}break;case"GET_VERSION":if(e.type=="VERSION_STRING"){i.promiseResolver(e.data);return}break;case"GET_FEATURE_FLAGS":if(e.type=="FEATURE_FLAGS"){i.promiseResolver(e.data);return}break;case"GET_TABLE_NAMES":if(e.type=="TABLE_NAMES"){i.promiseResolver(e.data);return}break;case"TOKENIZE":if(e.type=="SCRIPT_TOKENS"){i.promiseResolver(e.data);return}break;case"COPY_FILE_TO_BUFFER":if(e.type=="FILE_BUFFER"){i.promiseResolver(e.data);return}break;case"EXPORT_FILE_STATISTICS":if(e.type=="FILE_STATISTICS"){i.promiseResolver(e.data);return}break;case"CONNECT":if(e.type=="CONNECTION_INFO"){i.promiseResolver(e.data);return}break;case"RUN_PREPARED":case"RUN_QUERY":if(e.type=="QUERY_RESULT"){i.promiseResolver(e.data);return}break;case"SEND_PREPARED":if(e.type=="QUERY_RESULT_HEADER"){i.promiseResolver(e.data);return}break;case"START_PENDING_QUERY":if(e.type=="QUERY_RESULT_HEADER_OR_NULL"){i.promiseResolver(e.data);return}break;case"POLL_PENDING_QUERY":if(e.type=="QUERY_RESULT_HEADER_OR_NULL"){i.promiseResolver(e.data);return}break;case"CANCEL_PENDING_QUERY":if(this._onInstantiationProgress=[],e.type=="SUCCESS"){i.promiseResolver(e.data);return}break;case"FETCH_QUERY_RESULTS":if(e.type=="QUERY_RESULT_CHUNK"){i.promiseResolver(e.data);return}break;case"CREATE_PREPARED":if(e.type=="PREPARED_STATEMENT_ID"){i.promiseResolver(e.data);return}break}i.promiseRejecter(new Error("unexpected response type: ".concat(e.type.toString())))}onError(r){console.error(r),console.error("error in duckdb worker: ".concat(r.message)),this._pendingRequests.clear()}onClose(){if(this._workerShutdownResolver(null),this._pendingRequests.size!=0){console.warn("worker terminated with ".concat(this._pendingRequests.size," pending requests"));return}this._pendingRequests.clear()}async reset(){let r=new P("RESET",null);return await this.postTask(r)}async ping(){let r=new P("PING",null);await this.postTask(r)}async dropFile(r){let t=new P("DROP_FILE",r);return await this.postTask(t)}async dropFiles(){let r=new P("DROP_FILES",null);return await this.postTask(r)}async flushFiles(){let r=new P("FLUSH_FILES",null);return await this.postTask(r)}async instantiate(r,t=null,e=i=>{}){this._onInstantiationProgress.push(e);let i=new P("INSTANTIATE",[r,t]);return await this.postTask(i)}async getVersion(){let r=new P("GET_VERSION",null);return await this.postTask(r)}async getFeatureFlags(){let r=new P("GET_FEATURE_FLAGS",null);return await this.postTask(r)}async open(r){let t=new P("OPEN",r);await this.postTask(t)}async tokenize(r){let t=new P("TOKENIZE",r);return await this.postTask(t)}async connectInternal(){let r=new P("CONNECT",null);return await this.postTask(r)}async connect(){let r=await this.connectInternal();return new fp(this,r)}async disconnect(r){let t=new P("DISCONNECT",r);await this.postTask(t)}async runQuery(r,t){let e=new P("RUN_QUERY",[r,t]);return await this.postTask(e)}async startPendingQuery(r,t){let e=new P("START_PENDING_QUERY",[r,t]);return await this.postTask(e)}async pollPendingQuery(r){let t=new P("POLL_PENDING_QUERY",r);return await this.postTask(t)}async cancelPendingQuery(r){let t=new P("CANCEL_PENDING_QUERY",r);return await this.postTask(t)}async fetchQueryResults(r){let t=new P("FETCH_QUERY_RESULTS",r);return await this.postTask(t)}async getTableNames(r,t){let e=new P("GET_TABLE_NAMES",[r,t]);return await this.postTask(e)}async createPrepared(r,t){let e=new P("CREATE_PREPARED",[r,t]);return await this.postTask(e)}async closePrepared(r,t){let e=new P("CLOSE_PREPARED",[r,t]);await this.postTask(e)}async runPrepared(r,t,e){let i=new P("RUN_PREPARED",[r,t,e]);return await this.postTask(i)}async sendPrepared(r,t,e){let i=new P("SEND_PREPARED",[r,t,e]);return await this.postTask(i)}async globFiles(r){let t=new P("GLOB_FILE_INFOS",r);return await this.postTask(t)}async registerFileText(r,t){let e=gp.encode(t);await this.registerFileBuffer(r,e)}async registerFileURL(r,t,e,i){t===void 0&&(t=r);let n=new P("REGISTER_FILE_URL",[r,t,e,i]);await this.postTask(n)}async registerEmptyFileBuffer(r){let t=new P("REGISTER_FILE_BUFFER",[r,new Uint8Array]);await this.postTask(t)}async registerFileBuffer(r,t){let e=new P("REGISTER_FILE_BUFFER",[r,t]);await this.postTask(e,[t.buffer])}async registerFileHandle(r,t,e,i){let n=new P("REGISTER_FILE_HANDLE",[r,t,e,i]);await this.postTask(n,[])}async collectFileStatistics(r,t){let e=new P("COLLECT_FILE_STATISTICS",[r,t]);await this.postTask(e,[])}async exportFileStatistics(r){let t=new P("EXPORT_FILE_STATISTICS",r);return await this.postTask(t,[])}async copyFileToBuffer(r){let t=new P("COPY_FILE_TO_BUFFER",r);return await this.postTask(t)}async copyFileToPath(r,t){let e=new P("COPY_FILE_TO_PATH",[r,t]);await this.postTask(e)}async insertArrowFromIPCStream(r,t,e){if(t.length==0)return;let i=new P("INSERT_ARROW_FROM_IPC_STREAM",[r,t,e]);await this.postTask(i,[t.buffer])}async insertCSVFromPath(r,t,e){if(e.columns!==void 0){let n=[];for(let s in e.columns){let o=e.columns[s];n.push(ha(s,o))}e.columnsFlat=n,delete e.columns}let i=new P("IMPORT_CSV_FROM_PATH",[r,t,e]);await this.postTask(i)}async insertJSONFromPath(r,t,e){if(e.columns!==void 0){let n=[];for(let s in e.columns){let o=e.columns[s];n.push(ha(s,o))}e.columnsFlat=n,delete e.columns}let i=new P("IMPORT_JSON_FROM_PATH",[r,t,e]);await this.postTask(i)}};var bp=async()=>WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,3,1,0,1,10,14,1,12,0,65,0,65,0,65,0,252,10,0,0,11])),_p=async()=>WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,8,1,6,0,6,64,25,11,11])),wp=async()=>WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,10,1,8,0,65,0,253,15,253,98,11])),Ip=()=>(async r=>{try{return typeof MessageChannel<"u"&&new MessageChannel().port1.postMessage(new SharedArrayBuffer(1)),WebAssembly.validate(r)}catch{return!1}})(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11])),fa={name:"@duckdb/duckdb-wasm",version:"1.28.0",description:"DuckDB powered by WebAssembly",license:"MIT",repository:{type:"git",url:"https://github.com/duckdb/duckdb-wasm.git"},keywords:["sql","duckdb","relational","database","data","query","wasm","analytics","olap","arrow","parquet","json","csv"],dependencies:{"apache-arrow":"^13.0.0"},devDependencies:{"@types/emscripten":"^1.39.8","@types/jasmine":"^4.3.1","@typescript-eslint/eslint-plugin":"^6.5.0","@typescript-eslint/parser":"^6.7.3",esbuild:"^0.19.5",eslint:"^8.50.0","eslint-plugin-jasmine":"^4.1.3","eslint-plugin-react":"^7.33.2","fast-glob":"^3.3.1",jasmine:"^5.1.0","jasmine-core":"^5.1.1","jasmine-spec-reporter":"^7.0.0","js-sha256":"^0.9.0",karma:"^6.4.2","karma-chrome-launcher":"^3.2.0","karma-coverage":"^2.2.1","karma-firefox-launcher":"^2.1.2","karma-jasmine":"^5.1.0","karma-jasmine-html-reporter":"^2.1.0","karma-sourcemap-loader":"^0.4.0","karma-spec-reporter":"^0.0.36","make-dir":"^4.0.0",nyc:"^15.1.0",prettier:"^3.0.2",puppeteer:"^21.1.1",rimraf:"^5.0.5",s3rver:"^3.7.1",typedoc:"^0.25.2",typescript:"^5.2.2","wasm-feature-detect":"^1.5.1","web-worker":"^1.2.0"},scripts:{"build:debug":"node bundle.mjs debug && tsc --emitDeclarationOnly","build:release":"node bundle.mjs release && tsc --emitDeclarationOnly",docs:"typedoc",report:"node ./coverage.mjs","test:node":"node --enable-source-maps ../../node_modules/jasmine/bin/jasmine ./dist/tests-node.cjs","test:node:debug":"node --inspect-brk --enable-source-maps ../../node_modules/jasmine/bin/jasmine ./dist/tests-node.cjs","test:node:coverage":"nyc -r json --report-dir ./coverage/node node ../../node_modules/jasmine/bin/jasmine ./dist/tests-node.cjs","test:firefox":"karma start ./karma/tests-firefox.cjs","test:chrome":"karma start ./karma/tests-chrome.cjs","test:chrome:eh":"karma start ./karma/tests-chrome-eh.cjs","test:chrome:coverage":"karma start ./karma/tests-chrome-coverage.cjs","test:browser":"karma start ./karma/tests-all.cjs","test:browser:debug":"karma start ./karma/tests-debug.cjs",test:"npm run test:chrome && npm run test:node","test:coverage":"npm run test:chrome:coverage && npm run test:node:coverage && npm run report",lint:"eslint src test"},files:["dist","!dist/types/test"],main:"dist/duckdb-browser.cjs",module:"dist/duckdb-browser.mjs",types:"dist/duckdb-browser.d.ts",jsdelivr:"dist/duckdb-browser.cjs",unpkg:"dist/duckdb-browser.mjs",sideEffects:!1,browser:{fs:!1,path:!1,perf_hooks:!1,os:!1,worker_threads:!1},exports:{"./dist/duckdb-mvp.wasm":"./dist/duckdb-mvp.wasm","./dist/duckdb-eh.wasm":"./dist/duckdb-eh.wasm","./dist/duckdb-coi.wasm":"./dist/duckdb-coi.wasm","./dist/duckdb-browser":"./dist/duckdb-browser.mjs","./dist/duckdb-browser.cjs":"./dist/duckdb-browser.cjs","./dist/duckdb-browser.mjs":"./dist/duckdb-browser.mjs","./dist/duckdb-browser-blocking":"./dist/duckdb-browser-blocking.mjs","./dist/duckdb-browser-blocking.mjs":"./dist/duckdb-browser-blocking.mjs","./dist/duckdb-browser-blocking.cjs":"./dist/duckdb-browser-blocking.cjs","./dist/duckdb-browser-coi.pthread.worker.js":"./dist/duckdb-browser-coi.pthread.worker.js","./dist/duckdb-browser-coi.worker.js":"./dist/duckdb-browser-coi.worker.js","./dist/duckdb-browser-eh.worker.js":"./dist/duckdb-browser-eh.worker.js","./dist/duckdb-browser-mvp.worker.js":"./dist/duckdb-browser-mvp.worker.js","./dist/duckdb-node":"./dist/duckdb-node.cjs","./dist/duckdb-node.cjs":"./dist/duckdb-node.cjs","./dist/duckdb-node-blocking":"./dist/duckdb-node-blocking.cjs","./dist/duckdb-node-blocking.cjs":"./dist/duckdb-node-blocking.cjs","./dist/duckdb-node-eh.worker.cjs":"./dist/duckdb-node-eh.worker.cjs","./dist/duckdb-node-mvp.worker.cjs":"./dist/duckdb-node-mvp.worker.cjs","./blocking":{browser:{types:"./dist/duckdb-browser-blocking.d.ts",import:"./dist/duckdb-browser-blocking.mjs",require:"./dist/duckdb-browser-blocking.cjs"},node:{types:"./dist/duckdb-node-blocking.d.ts",require:"./dist/duckdb-node-blocking.cjs",import:"./dist/duckdb-node-blocking.cjs"},types:"./dist/duckdb-browser-blocking.d.ts",import:"./dist/duckdb-browser-blocking.mjs",require:"./dist/duckdb-browser-blocking.cjs"},".":{browser:{types:"./dist/duckdb-browser.d.ts",import:"./dist/duckdb-browser.mjs",require:"./dist/duckdb-browser.cjs"},node:{types:"./dist/duckdb-node.d.ts",import:"./dist/duckdb-node.cjs",require:"./dist/duckdb-node.cjs"},types:"./dist/duckdb-browser.d.ts",import:"./dist/duckdb-browser.mjs",require:"./dist/duckdb-browser.cjs"}}},vp=fa.name,Sp=fa.version,pa=fa.version.split("."),$T=pa[0],qT=pa[1],GT=pa[2],Tp=()=>typeof navigator>"u";function Ol(){let r="https://cdn.jsdelivr.net/npm/".concat(vp,"@").concat(Sp,"/dist/");return{mvp:{mainModule:"".concat(r,"duckdb-mvp.wasm"),mainWorker:"".concat(r,"duckdb-browser-mvp.worker.js")},eh:{mainModule:"".concat(r,"duckdb-eh.wasm"),mainWorker:"".concat(r,"duckdb-browser-eh.worker.js")}}}var aa=null,ca=null,la=null,ua=null,da=null;async function Ep(){return aa==null&&(aa=typeof BigInt64Array<"u"),ca==null&&(ca=await _p()),la==null&&(la=await Ip()),ua==null&&(ua=await wp()),da==null&&(da=await bp()),{bigInt64Array:aa,crossOriginIsolated:Tp()||globalThis.crossOriginIsolated||!1,wasmExceptions:ca,wasmSIMD:ua,wasmThreads:la,wasmBulkMemory:da}}async function Bl(r){let t=await Ep();if(t.wasmExceptions){if(t.wasmSIMD&&t.wasmThreads&&t.crossOriginIsolated&&r.coi)return{mainModule:r.coi.mainModule,mainWorker:r.coi.mainWorker,pthreadWorker:r.coi.pthreadWorker};if(r.eh)return{mainModule:r.eh.mainModule,mainWorker:r.eh.mainWorker,pthreadWorker:null}}return{mainModule:r.mvp.mainModule,mainWorker:r.mvp.mainWorker,pthreadWorker:null}}var WT=np(sp());function xp(){let r=new TextDecoder;return t=>(typeof SharedArrayBuffer<"u"&&t.buffer instanceof SharedArrayBuffer&&(t=new Uint8Array(t)),r.decode(t))}var YT=xp(),Ap=(r=>(r[r.BUFFER=0]="BUFFER",r[r.NODE_FS=1]="NODE_FS",r[r.BROWSER_FILEREADER=2]="BROWSER_FILEREADER",r[r.BROWSER_FSACCESS=3]="BROWSER_FSACCESS",r[r.HTTP=4]="HTTP",r[r.S3=5]="S3",r))(Ap||{});async function Bp(r){let t=await Np(r),e=await t.connect();return{db:t,con:e,query:async i=>{let{type:n,sql:s}=i,o=await e.query(s);return n==="exec"?void 0:n==="arrow"?o:Array.from(o)}}}async function Np({log:r=!1}={}){let t=Ol(),e=await Bl(t),i=URL.createObjectURL(new Blob([`importScripts("${e.mainWorker}");`],{type:"text/javascript"})),n=new Worker(i),s=r?new El:new Tl,o=new Al(s,n);return await o.instantiate(e.mainModule,e.pthreadWorker),URL.revokeObjectURL(i),o}function Fp(){let r=new Set,t,e=new Promise(i=>t=i);return{pending(i){r.add(i)},ready(i){return r.delete(i),r.size===0},resolve(){e=new Promise(i=>{t(),t=i})},get promise(){return e}}}export{zs as Coordinator,na as MosaicClient,si as Param,_e as Priority,Gs as Selection,ra as coordinator,oa as distinct,qs as isParam,Kf as isSelection,Qf as restConnector,Wo as socketConnector,Fp as synchronizer,ia as throttle,Bp as wasmConnector};
10
+ ]`}concat(...t){let e=this.schema,i=this.data.concat(t.flatMap(({data:n})=>n));return new r(e,i.map(n=>new Z(e,n)))}slice(t,e){let i=this.schema;[t,e]=hi({length:this.numRows},t,e);let n=$n(this.data,this._offsets,t,e);return new r(i,n.map(s=>new Z(i,s)))}getChild(t){return this.getChildAt(this.schema.fields.findIndex(e=>e.name===t))}getChildAt(t){if(t>-1&&t<this.schema.fields.length){let e=this.data.map(i=>i.children[t]);if(e.length===0){let{type:i}=this.schema.fields[t],n=x({type:i,length:0,nullCount:0});e.push(n._changeLengthAndBackfillNullBitmap(this.numRows))}return new L(e)}return null}setChild(t,e){var i;return this.setChildAt((i=this.schema.fields)===null||i===void 0?void 0:i.findIndex(n=>n.name===t),e)}setChildAt(t,e){let i=this.schema,n=[...this.batches];if(t>-1&&t<this.numCols){e||(e=new L([x({type:new gt,length:this.numRows})]));let s=i.fields.slice(),o=s[t].clone({type:e.type}),a=this.schema.fields.map((c,l)=>this.getChildAt(l));[s[t],a[t]]=[o,e],[i,n]=ws(i,a)}return new r(i,n)}select(t){let e=this.schema.fields.reduce((i,n,s)=>i.set(n.name,s),new Map);return this.selectAt(t.map(i=>e.get(i)).filter(i=>i>-1))}selectAt(t){let e=this.schema.selectAt(t),i=this.batches.map(n=>n.selectAt(t));return new r(e,i)}assign(t){let e=this.schema.fields,[i,n]=t.schema.fields.reduce((a,c,l)=>{let[d,h]=a,f=e.findIndex(g=>g.name===c.name);return~f?h[f]=l:d.push(l),a},[[],[]]),s=this.schema.assign(t.schema),o=[...e.map((a,c)=>[c,n[c]]).map(([a,c])=>c===void 0?this.getChildAt(a):t.getChildAt(c)),...i.map(a=>t.getChildAt(a))].filter(Boolean);return new r(...ws(s,o))}};Ac=Symbol.toStringTag;lt[Ac]=(r=>(r.schema=null,r.batches=[],r._offsets=new Uint32Array([0]),r._nullCount=-1,r[Symbol.isConcatSpreadable]=!0,r.isValid=We(mi),r.get=We(it.getVisitFn(u.Struct)),r.set=qn(ht.getVisitFn(u.Struct)),r.indexOf=Gn(fr.getVisitFn(u.Struct)),r.getByteLength=We(Nt.getVisitFn(u.Struct)),"Table"))(lt.prototype);var Bc,Z=class r{constructor(...t){switch(t.length){case 2:{if([this.schema]=t,!(this.schema instanceof j))throw new TypeError("RecordBatch constructor expects a [Schema, Data] pair.");if([,this.data=x({nullCount:0,type:new W(this.schema.fields),children:this.schema.fields.map(e=>x({type:e.type,nullCount:0}))})]=t,!(this.data instanceof $))throw new TypeError("RecordBatch constructor expects a [Schema, Data] pair.");[this.schema,this.data]=Oc(this.schema,this.data.children);break}case 1:{let[e]=t,{fields:i,children:n,length:s}=Object.keys(e).reduce((c,l,d)=>(c.children[d]=e[l],c.length=Math.max(c.length,e[l].length),c.fields[d]=R.new({name:l,type:e[l].type,nullable:!0}),c),{length:0,fields:new Array,children:new Array}),o=new j(i),a=x({type:new W(i),length:s,children:n,nullCount:0});[this.schema,this.data]=Oc(o,a.children,s);break}default:throw new TypeError("RecordBatch constructor expects an Object mapping names to child Data, or a [Schema, Data] pair.")}}get dictionaries(){return this._dictionaries||(this._dictionaries=Nc(this.schema.fields,this.data.children))}get numCols(){return this.schema.fields.length}get numRows(){return this.data.length}get nullCount(){return this.data.nullCount}isValid(t){return this.data.getValid(t)}get(t){return it.visit(this.data,t)}set(t,e){return ht.visit(this.data,t,e)}indexOf(t,e){return fr.visit(this.data,t,e)}getByteLength(t){return Nt.visit(this.data,t)}[Symbol.iterator](){return $r.visit(new L([this.data]))}toArray(){return[...this]}concat(...t){return new lt(this.schema,[this,...t])}slice(t,e){let[i]=new L([this.data]).slice(t,e).data;return new r(this.schema,i)}getChild(t){var e;return this.getChildAt((e=this.schema.fields)===null||e===void 0?void 0:e.findIndex(i=>i.name===t))}getChildAt(t){return t>-1&&t<this.schema.fields.length?new L([this.data.children[t]]):null}setChild(t,e){var i;return this.setChildAt((i=this.schema.fields)===null||i===void 0?void 0:i.findIndex(n=>n.name===t),e)}setChildAt(t,e){let i=this.schema,n=this.data;if(t>-1&&t<this.numCols){e||(e=new L([x({type:new gt,length:this.numRows})]));let s=i.fields.slice(),o=n.children.slice(),a=s[t].clone({type:e.type});[s[t],o[t]]=[a,e.data[0]],i=new j(s,new Map(this.schema.metadata)),n=x({type:new W(s),children:o})}return new r(i,n)}select(t){let e=this.schema.select(t),i=new W(e.fields),n=[];for(let s of t){let o=this.schema.fields.findIndex(a=>a.name===s);~o&&(n[o]=this.data.children[o])}return new r(e,x({type:i,length:this.numRows,children:n}))}selectAt(t){let e=this.schema.selectAt(t),i=t.map(s=>this.data.children[s]).filter(Boolean),n=x({type:new W(e.fields),length:this.numRows,children:i});return new r(e,n)}};Bc=Symbol.toStringTag;Z[Bc]=(r=>(r._nullCount=-1,r[Symbol.isConcatSpreadable]=!0,"RecordBatch"))(Z.prototype);function Oc(r,t,e=t.reduce((i,n)=>Math.max(i,n.length),0)){var i;let n=[...r.fields],s=[...t],o=(e+63&-64)>>3;for(let[a,c]of r.fields.entries()){let l=t[a];(!l||l.length!==e)&&(n[a]=c.clone({nullable:!0}),s[a]=(i=l?._changeLengthAndBackfillNullBitmap(e))!==null&&i!==void 0?i:x({type:c.type,length:e,nullCount:e,nullBitmap:new Uint8Array(o)}))}return[r.assign(n),x({type:new W(n),length:e,children:s})]}function Nc(r,t,e=new Map){for(let i=-1,n=r.length;++i<n;){let o=r[i].type,a=t[i];if(y.isDictionary(o)){if(!e.has(o.id))a.dictionary&&e.set(o.id,a.dictionary);else if(e.get(o.id)!==a.dictionary)throw new Error("Cannot create Schema containing two different dictionaries with the same Id")}o.children&&o.children.length>0&&Nc(o.children,a.children,e)}return e}var vr=class extends Z{constructor(t){let e=t.fields.map(n=>x({type:n.type})),i=x({type:new W(t.fields),nullCount:0,children:e});super(t,i)}};var Ji;(function(r){r[r.BUFFER=0]="BUFFER"})(Ji||(Ji={}));var Xi;(function(r){r[r.LZ4_FRAME=0]="LZ4_FRAME",r[r.ZSTD=1]="ZSTD"})(Xi||(Xi={}));var Is=class r{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsBodyCompression(t,e){return(e||new r).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsBodyCompression(t,e){return t.setPosition(t.position()+4),(e||new r).__init(t.readInt32(t.position())+t.position(),t)}codec(){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.readInt8(this.bb_pos+t):Xi.LZ4_FRAME}method(){let t=this.bb.__offset(this.bb_pos,6);return t?this.bb.readInt8(this.bb_pos+t):Ji.BUFFER}static startBodyCompression(t){t.startObject(2)}static addCodec(t,e){t.addFieldInt8(0,e,Xi.LZ4_FRAME)}static addMethod(t,e){t.addFieldInt8(1,e,Ji.BUFFER)}static endBodyCompression(t){return t.endObject()}static createBodyCompression(t,e,i){return r.startBodyCompression(t),r.addCodec(t,e),r.addMethod(t,i),r.endBodyCompression(t)}};var Jr=class{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}offset(){return this.bb.readInt64(this.bb_pos)}length(){return this.bb.readInt64(this.bb_pos+8)}static sizeOf(){return 16}static createBuffer(t,e,i){return t.prep(8,16),t.writeInt64(BigInt(i??0)),t.writeInt64(BigInt(e??0)),t.offset()}};var Xr=class{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}length(){return this.bb.readInt64(this.bb_pos)}nullCount(){return this.bb.readInt64(this.bb_pos+8)}static sizeOf(){return 16}static createFieldNode(t,e,i){return t.prep(8,16),t.writeInt64(BigInt(i??0)),t.writeInt64(BigInt(e??0)),t.offset()}};var Dt=class r{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsRecordBatch(t,e){return(e||new r).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsRecordBatch(t,e){return t.setPosition(t.position()+4),(e||new r).__init(t.readInt32(t.position())+t.position(),t)}length(){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.readInt64(this.bb_pos+t):BigInt("0")}nodes(t,e){let i=this.bb.__offset(this.bb_pos,6);return i?(e||new Xr).__init(this.bb.__vector(this.bb_pos+i)+t*16,this.bb):null}nodesLength(){let t=this.bb.__offset(this.bb_pos,6);return t?this.bb.__vector_len(this.bb_pos+t):0}buffers(t,e){let i=this.bb.__offset(this.bb_pos,8);return i?(e||new Jr).__init(this.bb.__vector(this.bb_pos+i)+t*16,this.bb):null}buffersLength(){let t=this.bb.__offset(this.bb_pos,8);return t?this.bb.__vector_len(this.bb_pos+t):0}compression(t){let e=this.bb.__offset(this.bb_pos,10);return e?(t||new Is).__init(this.bb.__indirect(this.bb_pos+e),this.bb):null}static startRecordBatch(t){t.startObject(4)}static addLength(t,e){t.addFieldInt64(0,e,BigInt("0"))}static addNodes(t,e){t.addFieldOffset(1,e,0)}static startNodesVector(t,e){t.startVector(16,e,8)}static addBuffers(t,e){t.addFieldOffset(2,e,0)}static startBuffersVector(t,e){t.startVector(16,e,8)}static addCompression(t,e){t.addFieldOffset(3,e,0)}static endRecordBatch(t){return t.endObject()}};var je=class r{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsDictionaryBatch(t,e){return(e||new r).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsDictionaryBatch(t,e){return t.setPosition(t.position()+4),(e||new r).__init(t.readInt32(t.position())+t.position(),t)}id(){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.readInt64(this.bb_pos+t):BigInt("0")}data(t){let e=this.bb.__offset(this.bb_pos,6);return e?(t||new Dt).__init(this.bb.__indirect(this.bb_pos+e),this.bb):null}isDelta(){let t=this.bb.__offset(this.bb_pos,8);return t?!!this.bb.readInt8(this.bb_pos+t):!1}static startDictionaryBatch(t){t.startObject(3)}static addId(t,e){t.addFieldInt64(0,e,BigInt("0"))}static addData(t,e){t.addFieldOffset(1,e,0)}static addIsDelta(t,e){t.addFieldInt8(2,+e,0)}static endDictionaryBatch(t){return t.endObject()}};var Zr;(function(r){r[r.NONE=0]="NONE",r[r.Schema=1]="Schema",r[r.DictionaryBatch=2]="DictionaryBatch",r[r.RecordBatch=3]="RecordBatch",r[r.Tensor=4]="Tensor",r[r.SparseTensor=5]="SparseTensor"})(Zr||(Zr={}));var ee=class r{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsMessage(t,e){return(e||new r).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsMessage(t,e){return t.setPosition(t.position()+4),(e||new r).__init(t.readInt32(t.position())+t.position(),t)}version(){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.readInt16(this.bb_pos+t):He.V1}headerType(){let t=this.bb.__offset(this.bb_pos,6);return t?this.bb.readUint8(this.bb_pos+t):Zr.NONE}header(t){let e=this.bb.__offset(this.bb_pos,8);return e?this.bb.__union(t,this.bb_pos+e):null}bodyLength(){let t=this.bb.__offset(this.bb_pos,10);return t?this.bb.readInt64(this.bb_pos+t):BigInt("0")}customMetadata(t,e){let i=this.bb.__offset(this.bb_pos,12);return i?(e||new st).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+i)+t*4),this.bb):null}customMetadataLength(){let t=this.bb.__offset(this.bb_pos,12);return t?this.bb.__vector_len(this.bb_pos+t):0}static startMessage(t){t.startObject(5)}static addVersion(t,e){t.addFieldInt16(0,e,He.V1)}static addHeaderType(t,e){t.addFieldInt8(1,e,Zr.NONE)}static addHeader(t,e){t.addFieldOffset(2,e,0)}static addBodyLength(t,e){t.addFieldInt64(3,e,BigInt("0"))}static addCustomMetadata(t,e){t.addFieldOffset(4,e,0)}static createCustomMetadataVector(t,e){t.startVector(4,e.length,4);for(let i=e.length-1;i>=0;i--)t.addOffset(e[i]);return t.endVector()}static startCustomMetadataVector(t,e){t.startVector(4,e,4)}static endMessage(t){return t.endObject()}static finishMessageBuffer(t,e){t.finish(e)}static finishSizePrefixedMessageBuffer(t,e){t.finish(e,void 0,!0)}static createMessage(t,e,i,n,s,o){return r.startMessage(t),r.addVersion(t,e),r.addHeaderType(t,i),r.addHeader(t,n),r.addBodyLength(t,s),r.addCustomMetadata(t,o),r.endMessage(t)}};var Do=class extends b{visit(t,e){return t==null||e==null?void 0:super.visit(t,e)}visitNull(t,e){return Ti.startNull(e),Ti.endNull(e)}visitInt(t,e){return Zt.startInt(e),Zt.addBitWidth(e,t.bitWidth),Zt.addIsSigned(e,t.isSigned),Zt.endInt(e)}visitFloat(t,e){return tr.startFloatingPoint(e),tr.addPrecision(e,t.precision),tr.endFloatingPoint(e)}visitBinary(t,e){return bi.startBinary(e),bi.endBinary(e)}visitBool(t,e){return _i.startBool(e),_i.endBool(e)}visitUtf8(t,e){return Ai.startUtf8(e),Ai.endUtf8(e)}visitDecimal(t,e){return fe.startDecimal(e),fe.addScale(e,t.scale),fe.addPrecision(e,t.precision),fe.addBitWidth(e,t.bitWidth),fe.endDecimal(e)}visitDate(t,e){return Qe.startDate(e),Qe.addUnit(e,t.unit),Qe.endDate(e)}visitTime(t,e){return Re.startTime(e),Re.addUnit(e,t.unit),Re.addBitWidth(e,t.bitWidth),Re.endTime(e)}visitTimestamp(t,e){let i=t.timezone&&e.createString(t.timezone)||void 0;return De.startTimestamp(e),De.addUnit(e,t.unit),i!==void 0&&De.addTimezone(e,i),De.endTimestamp(e)}visitInterval(t,e){return er.startInterval(e),er.addUnit(e,t.unit),er.endInterval(e)}visitList(t,e){return Si.startList(e),Si.endList(e)}visitStruct(t,e){return Ei.startStruct_(e),Ei.endStruct_(e)}visitUnion(t,e){te.startTypeIdsVector(e,t.typeIds.length);let i=te.createTypeIdsVector(e,t.typeIds);return te.startUnion(e),te.addMode(e,t.mode),te.addTypeIds(e,i),te.endUnion(e)}visitDictionary(t,e){let i=this.visit(t.indices,e);return he.startDictionaryEncoding(e),he.addId(e,BigInt(t.id)),he.addIsOrdered(e,t.isOrdered),i!==void 0&&he.addIndexType(e,i),he.endDictionaryEncoding(e)}visitFixedSizeBinary(t,e){return Xe.startFixedSizeBinary(e),Xe.addByteWidth(e,t.byteWidth),Xe.endFixedSizeBinary(e)}visitFixedSizeList(t,e){return Ze.startFixedSizeList(e),Ze.addListSize(e,t.listSize),Ze.endFixedSizeList(e)}visitMap(t,e){return rr.startMap(e),rr.addKeysSorted(e,t.keysSorted),rr.endMap(e)}},vs=new Do;function Lc(r,t=new Map){return new j(Nd(r,t),Ss(r.customMetadata),t)}function Lo(r){return new ft(r.count,Uc(r.columns),Cc(r.columns))}function Mc(r){return new St(Lo(r.data),r.id,r.isDelta)}function Nd(r,t){return(r.fields||[]).filter(Boolean).map(e=>R.fromJSON(e,t))}function Fc(r,t){return(r.children||[]).filter(Boolean).map(e=>R.fromJSON(e,t))}function Uc(r){return(r||[]).reduce((t,e)=>[...t,new re(e.count,Fd(e.VALIDITY)),...Uc(e.children)],[])}function Cc(r,t=[]){for(let e=-1,i=(r||[]).length;++e<i;){let n=r[e];n.VALIDITY&&t.push(new vt(t.length,n.VALIDITY.length)),n.TYPE&&t.push(new vt(t.length,n.TYPE.length)),n.OFFSET&&t.push(new vt(t.length,n.OFFSET.length)),n.DATA&&t.push(new vt(t.length,n.DATA.length)),t=Cc(n.children,t)}return t}function Fd(r){return(r||[]).reduce((t,e)=>t+ +(e===0),0)}function kc(r,t){let e,i,n,s,o,a;return!t||!(s=r.dictionary)?(o=Dc(r,Fc(r,t)),n=new R(r.name,o,r.nullable,Ss(r.customMetadata))):t.has(e=s.id)?(i=(i=s.indexType)?Rc(i):new ae,a=new Ot(t.get(e),i,e,s.isOrdered),n=new R(r.name,a,r.nullable,Ss(r.customMetadata))):(i=(i=s.indexType)?Rc(i):new ae,t.set(e,o=Dc(r,Fc(r,t))),a=new Ot(o,i,e,s.isOrdered),n=new R(r.name,a,r.nullable,Ss(r.customMetadata))),n||null}function Ss(r){return new Map(Object.entries(r||{}))}function Rc(r){return new tt(r.isSigned,r.bitWidth)}function Dc(r,t){let e=r.type.name;switch(e){case"NONE":return new gt;case"null":return new gt;case"binary":return new ve;case"utf8":return new Se;case"bool":return new Te;case"list":return new Yt((t||[])[0]);case"struct":return new W(t||[]);case"struct_":return new W(t||[])}switch(e){case"int":{let i=r.type;return new tt(i.isSigned,i.bitWidth)}case"floatingpoint":{let i=r.type;return new _t(H[i.precision])}case"decimal":{let i=r.type;return new Ee(i.scale,i.precision,i.bitWidth)}case"date":{let i=r.type;return new xe(dt[i.unit])}case"time":{let i=r.type;return new Wt(D[i.unit],i.bitWidth)}case"timestamp":{let i=r.type;return new Ae(D[i.unit],i.timezone)}case"interval":{let i=r.type;return new Oe(yt[i.unit])}case"union":{let i=r.type;return new Ht(J[i.mode],i.typeIds||[],t||[])}case"fixedsizebinary":{let i=r.type;return new Be(i.byteWidth)}case"fixedsizelist":{let i=r.type;return new Kt(i.listSize,(t||[])[0])}case"map":{let i=r.type;return new Qt((t||[])[0],i.keysSorted)}}throw new Error(`Unrecognized type: "${e}"`)}var Rd=mr,Dd=Ft,Tt=class r{static fromJSON(t,e){let i=new r(0,at.V4,e);return i._createHeader=Ld(t,e),i}static decode(t){t=new Dd(S(t));let e=ee.getRootAsMessage(t),i=e.bodyLength(),n=e.version(),s=e.headerType(),o=new r(i,n,s);return o._createHeader=Md(e,s),o}static encode(t){let e=new Rd,i=-1;return t.isSchema()?i=j.encode(e,t.header()):t.isRecordBatch()?i=ft.encode(e,t.header()):t.isDictionaryBatch()&&(i=St.encode(e,t.header())),ee.startMessage(e),ee.addVersion(e,at.V4),ee.addHeader(e,i),ee.addHeaderType(e,t.headerType),ee.addBodyLength(e,BigInt(t.bodyLength)),ee.finishMessageBuffer(e,ee.endMessage(e)),e.asUint8Array()}static from(t,e=0){if(t instanceof j)return new r(0,at.V4,k.Schema,t);if(t instanceof ft)return new r(e,at.V4,k.RecordBatch,t);if(t instanceof St)return new r(e,at.V4,k.DictionaryBatch,t);throw new Error(`Unrecognized Message header: ${t}`)}get type(){return this.headerType}get version(){return this._version}get headerType(){return this._headerType}get bodyLength(){return this._bodyLength}header(){return this._createHeader()}isSchema(){return this.headerType===k.Schema}isRecordBatch(){return this.headerType===k.RecordBatch}isDictionaryBatch(){return this.headerType===k.DictionaryBatch}constructor(t,e,i,n){this._version=e,this._headerType=i,this.body=new Uint8Array(0),n&&(this._createHeader=()=>n),this._bodyLength=bt(t)}},ft=class{get nodes(){return this._nodes}get length(){return this._length}get buffers(){return this._buffers}constructor(t,e,i){this._nodes=e,this._buffers=i,this._length=bt(t)}},St=class{get id(){return this._id}get data(){return this._data}get isDelta(){return this._isDelta}get length(){return this.data.length}get nodes(){return this.data.nodes}get buffers(){return this.data.buffers}constructor(t,e,i=!1){this._data=t,this._isDelta=i,this._id=bt(e)}},vt=class{constructor(t,e){this.offset=bt(t),this.length=bt(e)}},re=class{constructor(t,e){this.length=bt(t),this.nullCount=bt(e)}};function Ld(r,t){return()=>{switch(t){case k.Schema:return j.fromJSON(r);case k.RecordBatch:return ft.fromJSON(r);case k.DictionaryBatch:return St.fromJSON(r)}throw new Error(`Unrecognized Message type: { name: ${k[t]}, type: ${t} }`)}}function Md(r,t){return()=>{switch(t){case k.Schema:return j.decode(r.header(new wt));case k.RecordBatch:return ft.decode(r.header(new Dt),r.version());case k.DictionaryBatch:return St.decode(r.header(new je),r.version())}throw new Error(`Unrecognized Message type: { name: ${k[t]}, type: ${t} }`)}}R.encode=Wd;R.decode=qd;R.fromJSON=kc;j.encode=Gd;j.decode=Ud;j.fromJSON=Lc;ft.encode=Yd;ft.decode=Cd;ft.fromJSON=Lo;St.encode=Hd;St.decode=kd;St.fromJSON=Mc;re.encode=Kd;re.decode=Vd;vt.encode=Qd;vt.decode=Pd;function Ud(r,t=new Map){let e=$d(r,t);return new j(e,Ts(r),t)}function Cd(r,t=at.V4){if(r.compression()!==null)throw new Error("Record batch compression not implemented");return new ft(r.length(),jd(r),zd(r,t))}function kd(r,t=at.V4){return new St(ft.decode(r.data(),t),r.id(),r.isDelta())}function Pd(r){return new vt(r.offset(),r.length())}function Vd(r){return new re(r.length(),r.nullCount())}function jd(r){let t=[];for(let e,i=-1,n=-1,s=r.nodesLength();++i<s;)(e=r.nodes(i))&&(t[++n]=re.decode(e));return t}function zd(r,t){let e=[];for(let i,n=-1,s=-1,o=r.buffersLength();++n<o;)(i=r.buffers(n))&&(t<at.V4&&(i.bb_pos+=8*(n+1)),e[++s]=vt.decode(i));return e}function $d(r,t){let e=[];for(let i,n=-1,s=-1,o=r.fieldsLength();++n<o;)(i=r.fields(n))&&(e[++s]=R.decode(i,t));return e}function Pc(r,t){let e=[];for(let i,n=-1,s=-1,o=r.childrenLength();++n<o;)(i=r.children(n))&&(e[++s]=R.decode(i,t));return e}function qd(r,t){let e,i,n,s,o,a;return!t||!(a=r.dictionary())?(n=jc(r,Pc(r,t)),i=new R(r.name(),n,r.nullable(),Ts(r))):t.has(e=bt(a.id()))?(s=(s=a.indexType())?Vc(s):new ae,o=new Ot(t.get(e),s,e,a.isOrdered()),i=new R(r.name(),o,r.nullable(),Ts(r))):(s=(s=a.indexType())?Vc(s):new ae,t.set(e,n=jc(r,Pc(r,t))),o=new Ot(n,s,e,a.isOrdered()),i=new R(r.name(),o,r.nullable(),Ts(r))),i||null}function Ts(r){let t=new Map;if(r)for(let e,i,n=-1,s=Math.trunc(r.customMetadataLength());++n<s;)(e=r.customMetadata(n))&&(i=e.key())!=null&&t.set(i,e.value());return t}function Vc(r){return new tt(r.isSigned(),r.bitWidth())}function jc(r,t){let e=r.typeType();switch(e){case Q.NONE:return new gt;case Q.Null:return new gt;case Q.Binary:return new ve;case Q.Utf8:return new Se;case Q.Bool:return new Te;case Q.List:return new Yt((t||[])[0]);case Q.Struct_:return new W(t||[])}switch(e){case Q.Int:{let i=r.type(new Zt);return new tt(i.isSigned(),i.bitWidth())}case Q.FloatingPoint:{let i=r.type(new tr);return new _t(i.precision())}case Q.Decimal:{let i=r.type(new fe);return new Ee(i.scale(),i.precision(),i.bitWidth())}case Q.Date:{let i=r.type(new Qe);return new xe(i.unit())}case Q.Time:{let i=r.type(new Re);return new Wt(i.unit(),i.bitWidth())}case Q.Timestamp:{let i=r.type(new De);return new Ae(i.unit(),i.timezone())}case Q.Interval:{let i=r.type(new er);return new Oe(i.unit())}case Q.Union:{let i=r.type(new te);return new Ht(i.mode(),i.typeIdsArray()||[],t||[])}case Q.FixedSizeBinary:{let i=r.type(new Xe);return new Be(i.byteWidth())}case Q.FixedSizeList:{let i=r.type(new Ze);return new Kt(i.listSize(),(t||[])[0])}case Q.Map:{let i=r.type(new rr);return new Qt((t||[])[0],i.keysSorted())}}throw new Error(`Unrecognized type: "${Q[e]}" (${e})`)}function Gd(r,t){let e=t.fields.map(s=>R.encode(r,s));wt.startFieldsVector(r,e.length);let i=wt.createFieldsVector(r,e),n=t.metadata&&t.metadata.size>0?wt.createCustomMetadataVector(r,[...t.metadata].map(([s,o])=>{let a=r.createString(`${s}`),c=r.createString(`${o}`);return st.startKeyValue(r),st.addKey(r,a),st.addValue(r,c),st.endKeyValue(r)})):-1;return wt.startSchema(r),wt.addFields(r,i),wt.addEndianness(r,Jd?Ke.Little:Ke.Big),n!==-1&&wt.addCustomMetadata(r,n),wt.endSchema(r)}function Wd(r,t){let e=-1,i=-1,n=-1,s=t.type,o=t.typeId;y.isDictionary(s)?(o=s.dictionary.typeId,n=vs.visit(s,r),i=vs.visit(s.dictionary,r)):i=vs.visit(s,r);let a=(s.children||[]).map(d=>R.encode(r,d)),c=pt.createChildrenVector(r,a),l=t.metadata&&t.metadata.size>0?pt.createCustomMetadataVector(r,[...t.metadata].map(([d,h])=>{let f=r.createString(`${d}`),g=r.createString(`${h}`);return st.startKeyValue(r),st.addKey(r,f),st.addValue(r,g),st.endKeyValue(r)})):-1;return t.name&&(e=r.createString(t.name)),pt.startField(r),pt.addType(r,i),pt.addTypeType(r,o),pt.addChildren(r,c),pt.addNullable(r,!!t.nullable),e!==-1&&pt.addName(r,e),n!==-1&&pt.addDictionary(r,n),l!==-1&&pt.addCustomMetadata(r,l),pt.endField(r)}function Yd(r,t){let e=t.nodes||[],i=t.buffers||[];Dt.startNodesVector(r,e.length);for(let o of e.slice().reverse())re.encode(r,o);let n=r.endVector();Dt.startBuffersVector(r,i.length);for(let o of i.slice().reverse())vt.encode(r,o);let s=r.endVector();return Dt.startRecordBatch(r),Dt.addLength(r,BigInt(t.length)),Dt.addNodes(r,n),Dt.addBuffers(r,s),Dt.endRecordBatch(r)}function Hd(r,t){let e=ft.encode(r,t.data);return je.startDictionaryBatch(r),je.addId(r,BigInt(t.id)),je.addIsDelta(r,t.isDelta),je.addData(r,e),je.endDictionaryBatch(r)}function Kd(r,t){return Xr.createFieldNode(r,BigInt(t.length),BigInt(t.nullCount))}function Qd(r,t){return Jr.createBuffer(r,BigInt(t.offset),BigInt(t.length))}var Jd=(()=>{let r=new ArrayBuffer(2);return new DataView(r).setInt16(0,256,!0),new Int16Array(r)[0]===256})();var Uo=r=>`Expected ${k[r]} Message in stream, but was null or length 0.`,Co=r=>`Header pointer of flatbuffer-encoded ${k[r]} Message is null or length 0.`,zc=(r,t)=>`Expected to read ${r} metadata bytes, but only read ${t}.`,$c=(r,t)=>`Expected to read ${r} bytes for message body, but only read ${t}.`,ti=class{constructor(t){this.source=t instanceof me?t:new me(t)}[Symbol.iterator](){return this}next(){let t;return(t=this.readMetadataLength()).done?Y:t.value===-1&&(t=this.readMetadataLength()).done?Y:(t=this.readMetadata(t.value)).done?Y:t}throw(t){return this.source.throw(t)}return(t){return this.source.return(t)}readMessage(t){let e;if((e=this.next()).done)return null;if(t!=null&&e.value.headerType!==t)throw new Error(Uo(t));return e.value}readMessageBody(t){if(t<=0)return new Uint8Array(0);let e=S(this.source.read(t));if(e.byteLength<t)throw new Error($c(t,e.byteLength));return e.byteOffset%8===0&&e.byteOffset+e.byteLength<=e.buffer.byteLength?e:e.slice()}readSchema(t=!1){let e=k.Schema,i=this.readMessage(e),n=i?.header();if(t&&!n)throw new Error(Co(e));return n}readMetadataLength(){let t=this.source.read(Es),e=t&&new Ft(t),i=e?.readInt32(0)||0;return{done:i===0,value:i}}readMetadata(t){let e=this.source.read(t);if(!e)return Y;if(e.byteLength<t)throw new Error(zc(t,e.byteLength));return{done:!1,value:Tt.decode(e)}}},Zi=class{constructor(t,e){this.source=t instanceof kt?t:un(t)?new ir(t,e):new kt(t)}[Symbol.asyncIterator](){return this}next(){return p(this,void 0,void 0,function*(){let t;return(t=yield this.readMetadataLength()).done?Y:t.value===-1&&(t=yield this.readMetadataLength()).done?Y:(t=yield this.readMetadata(t.value)).done?Y:t})}throw(t){return p(this,void 0,void 0,function*(){return yield this.source.throw(t)})}return(t){return p(this,void 0,void 0,function*(){return yield this.source.return(t)})}readMessage(t){return p(this,void 0,void 0,function*(){let e;if((e=yield this.next()).done)return null;if(t!=null&&e.value.headerType!==t)throw new Error(Uo(t));return e.value})}readMessageBody(t){return p(this,void 0,void 0,function*(){if(t<=0)return new Uint8Array(0);let e=S(yield this.source.read(t));if(e.byteLength<t)throw new Error($c(t,e.byteLength));return e.byteOffset%8===0&&e.byteOffset+e.byteLength<=e.buffer.byteLength?e:e.slice()})}readSchema(t=!1){return p(this,void 0,void 0,function*(){let e=k.Schema,i=yield this.readMessage(e),n=i?.header();if(t&&!n)throw new Error(Co(e));return n})}readMetadataLength(){return p(this,void 0,void 0,function*(){let t=yield this.source.read(Es),e=t&&new Ft(t),i=e?.readInt32(0)||0;return{done:i===0,value:i}})}readMetadata(t){return p(this,void 0,void 0,function*(){let e=yield this.source.read(t);if(!e)return Y;if(e.byteLength<t)throw new Error(zc(t,e.byteLength));return{done:!1,value:Tt.decode(e)}})}},tn=class extends ti{constructor(t){super(new Uint8Array(0)),this._schema=!1,this._body=[],this._batchIndex=0,this._dictionaryIndex=0,this._json=t instanceof Oi?t:new Oi(t)}next(){let{_json:t}=this;if(!this._schema)return this._schema=!0,{done:!1,value:Tt.fromJSON(t.schema,k.Schema)};if(this._dictionaryIndex<t.dictionaries.length){let e=t.dictionaries[this._dictionaryIndex++];return this._body=e.data.columns,{done:!1,value:Tt.fromJSON(e,k.DictionaryBatch)}}if(this._batchIndex<t.batches.length){let e=t.batches[this._batchIndex++];return this._body=e.columns,{done:!1,value:Tt.fromJSON(e,k.RecordBatch)}}return this._body=[],Y}readMessageBody(t){return e(this._body);function e(i){return(i||[]).reduce((n,s)=>[...n,...s.VALIDITY&&[s.VALIDITY]||[],...s.TYPE&&[s.TYPE]||[],...s.OFFSET&&[s.OFFSET]||[],...s.DATA&&[s.DATA]||[],...e(s.children)],[])}}readMessage(t){let e;if((e=this.next()).done)return null;if(t!=null&&e.value.headerType!==t)throw new Error(Uo(t));return e.value}readSchema(){let t=k.Schema,e=this.readMessage(t),i=e?.header();if(!e||!i)throw new Error(Co(t));return i}},Es=4,Mo="ARROW1",ei=new Uint8Array(Mo.length);for(let r=0;r<Mo.length;r+=1)ei[r]=Mo.codePointAt(r);function xs(r,t=0){for(let e=-1,i=ei.length;++e<i;)if(ei[e]!==r[t+e])return!1;return!0}var ri=ei.length,ko=ri+Es,qc=ri*2+Es;var ot=class r extends yr{constructor(t){super(),this._impl=t}get closed(){return this._impl.closed}get schema(){return this._impl.schema}get autoDestroy(){return this._impl.autoDestroy}get dictionaries(){return this._impl.dictionaries}get numDictionaries(){return this._impl.numDictionaries}get numRecordBatches(){return this._impl.numRecordBatches}get footer(){return this._impl.isFile()?this._impl.footer:null}isSync(){return this._impl.isSync()}isAsync(){return this._impl.isAsync()}isFile(){return this._impl.isFile()}isStream(){return this._impl.isStream()}next(){return this._impl.next()}throw(t){return this._impl.throw(t)}return(t){return this._impl.return(t)}cancel(){return this._impl.cancel()}reset(t){return this._impl.reset(t),this._DOMStream=void 0,this._nodeStream=void 0,this}open(t){let e=this._impl.open(t);return xt(e)?e.then(()=>this):this}readRecordBatch(t){return this._impl.isFile()?this._impl.readRecordBatch(t):null}[Symbol.iterator](){return this._impl[Symbol.iterator]()}[Symbol.asyncIterator](){return this._impl[Symbol.asyncIterator]()}toDOMStream(){return ut.toDOMStream(this.isSync()?{[Symbol.iterator]:()=>this}:{[Symbol.asyncIterator]:()=>this})}toNodeStream(){return ut.toNodeStream(this.isSync()?{[Symbol.iterator]:()=>this}:{[Symbol.asyncIterator]:()=>this},{objectMode:!0})}static throughNode(t){throw new Error('"throughNode" not available in this environment')}static throughDOM(t,e){throw new Error('"throughDOM" not available in this environment')}static from(t){return t instanceof r?t:cn(t)?Zd(t):un(t)?rh(t):xt(t)?p(this,void 0,void 0,function*(){return yield r.from(yield t)}):dn(t)||ai(t)||fn(t)||Lt(t)?eh(new kt(t)):th(new me(t))}static readAll(t){return t instanceof r?t.isSync()?Gc(t):Wc(t):cn(t)||ArrayBuffer.isView(t)||$t(t)||ln(t)?Gc(t):Wc(t)}},ge=class extends ot{constructor(t){super(t),this._impl=t}readAll(){return[...this]}[Symbol.iterator](){return this._impl[Symbol.iterator]()}[Symbol.asyncIterator](){return Et(this,arguments,function*(){yield E(yield*Dr(zt(this[Symbol.iterator]())))})}},nr=class extends ot{constructor(t){super(t),this._impl=t}readAll(){var t,e,i,n;return p(this,void 0,void 0,function*(){let s=new Array;try{for(var o=!0,a=zt(this),c;c=yield a.next(),t=c.done,!t;o=!0){n=c.value,o=!1;let l=n;s.push(l)}}catch(l){e={error:l}}finally{try{!o&&!t&&(i=a.return)&&(yield i.call(a))}finally{if(e)throw e.error}}return s})}[Symbol.iterator](){throw new Error("AsyncRecordBatchStreamReader is not Iterable")}[Symbol.asyncIterator](){return this._impl[Symbol.asyncIterator]()}},sr=class extends ge{constructor(t){super(t),this._impl=t}},en=class extends nr{constructor(t){super(t),this._impl=t}},As=class{get numDictionaries(){return this._dictionaryIndex}get numRecordBatches(){return this._recordBatchIndex}constructor(t=new Map){this.closed=!1,this.autoDestroy=!0,this._dictionaryIndex=0,this._recordBatchIndex=0,this.dictionaries=t}isSync(){return!1}isAsync(){return!1}isFile(){return!1}isStream(){return!1}reset(t){return this._dictionaryIndex=0,this._recordBatchIndex=0,this.schema=t,this.dictionaries=new Map,this}_loadRecordBatch(t,e){let i=this._loadVectors(t,e,this.schema.fields),n=x({type:new W(this.schema.fields),length:t.length,children:i});return new Z(this.schema,n)}_loadDictionaryBatch(t,e){let{id:i,isDelta:n}=t,{dictionaries:s,schema:o}=this,a=s.get(i);if(n||!a){let c=o.dictionaries.get(i),l=this._loadVectors(t.data,e,[c]);return(a&&n?a.concat(new L(l)):new L(l)).memoize()}return a.memoize()}_loadVectors(t,e,i){return new Ri(e,t.nodes,t.buffers,this.dictionaries).visitMany(i)}},ii=class extends As{constructor(t,e){super(e),this._reader=cn(t)?new tn(this._handle=t):new ti(this._handle=t)}isSync(){return!0}isStream(){return!0}[Symbol.iterator](){return this}cancel(){!this.closed&&(this.closed=!0)&&(this.reset()._reader.return(),this._reader=null,this.dictionaries=null)}open(t){return this.closed||(this.autoDestroy=Yc(this,t),this.schema||(this.schema=this._reader.readSchema())||this.cancel()),this}throw(t){return!this.closed&&this.autoDestroy&&(this.closed=!0)?this.reset()._reader.throw(t):Y}return(t){return!this.closed&&this.autoDestroy&&(this.closed=!0)?this.reset()._reader.return(t):Y}next(){if(this.closed)return Y;let t,{_reader:e}=this;for(;t=this._readNextMessageAndValidate();)if(t.isSchema())this.reset(t.header());else if(t.isRecordBatch()){this._recordBatchIndex++;let i=t.header(),n=e.readMessageBody(t.bodyLength);return{done:!1,value:this._loadRecordBatch(i,n)}}else if(t.isDictionaryBatch()){this._dictionaryIndex++;let i=t.header(),n=e.readMessageBody(t.bodyLength),s=this._loadDictionaryBatch(i,n);this.dictionaries.set(i.id,s)}return this.schema&&this._recordBatchIndex===0?(this._recordBatchIndex++,{done:!1,value:new vr(this.schema)}):this.return()}_readNextMessageAndValidate(t){return this._reader.readMessage(t)}},ni=class extends As{constructor(t,e){super(e),this._reader=new Zi(this._handle=t)}isAsync(){return!0}isStream(){return!0}[Symbol.asyncIterator](){return this}cancel(){return p(this,void 0,void 0,function*(){!this.closed&&(this.closed=!0)&&(yield this.reset()._reader.return(),this._reader=null,this.dictionaries=null)})}open(t){return p(this,void 0,void 0,function*(){return this.closed||(this.autoDestroy=Yc(this,t),this.schema||(this.schema=yield this._reader.readSchema())||(yield this.cancel())),this})}throw(t){return p(this,void 0,void 0,function*(){return!this.closed&&this.autoDestroy&&(this.closed=!0)?yield this.reset()._reader.throw(t):Y})}return(t){return p(this,void 0,void 0,function*(){return!this.closed&&this.autoDestroy&&(this.closed=!0)?yield this.reset()._reader.return(t):Y})}next(){return p(this,void 0,void 0,function*(){if(this.closed)return Y;let t,{_reader:e}=this;for(;t=yield this._readNextMessageAndValidate();)if(t.isSchema())yield this.reset(t.header());else if(t.isRecordBatch()){this._recordBatchIndex++;let i=t.header(),n=yield e.readMessageBody(t.bodyLength);return{done:!1,value:this._loadRecordBatch(i,n)}}else if(t.isDictionaryBatch()){this._dictionaryIndex++;let i=t.header(),n=yield e.readMessageBody(t.bodyLength),s=this._loadDictionaryBatch(i,n);this.dictionaries.set(i.id,s)}return this.schema&&this._recordBatchIndex===0?(this._recordBatchIndex++,{done:!1,value:new vr(this.schema)}):yield this.return()})}_readNextMessageAndValidate(t){return p(this,void 0,void 0,function*(){return yield this._reader.readMessage(t)})}},Os=class extends ii{get footer(){return this._footer}get numDictionaries(){return this._footer?this._footer.numDictionaries:0}get numRecordBatches(){return this._footer?this._footer.numRecordBatches:0}constructor(t,e){super(t instanceof Bi?t:new Bi(t),e)}isSync(){return!0}isFile(){return!0}open(t){if(!this.closed&&!this._footer){this.schema=(this._footer=this._readFooter()).schema;for(let e of this._footer.dictionaryBatches())e&&this._readDictionaryBatch(this._dictionaryIndex++)}return super.open(t)}readRecordBatch(t){var e;if(this.closed)return null;this._footer||this.open();let i=(e=this._footer)===null||e===void 0?void 0:e.getRecordBatch(t);if(i&&this._handle.seek(i.offset)){let n=this._reader.readMessage(k.RecordBatch);if(n?.isRecordBatch()){let s=n.header(),o=this._reader.readMessageBody(n.bodyLength);return this._loadRecordBatch(s,o)}}return null}_readDictionaryBatch(t){var e;let i=(e=this._footer)===null||e===void 0?void 0:e.getDictionaryBatch(t);if(i&&this._handle.seek(i.offset)){let n=this._reader.readMessage(k.DictionaryBatch);if(n?.isDictionaryBatch()){let s=n.header(),o=this._reader.readMessageBody(n.bodyLength),a=this._loadDictionaryBatch(s,o);this.dictionaries.set(s.id,a)}}}_readFooter(){let{_handle:t}=this,e=t.size-ko,i=t.readInt32(e),n=t.readAt(e-i,i);return Le.decode(n)}_readNextMessageAndValidate(t){var e;if(this._footer||this.open(),this._footer&&this._recordBatchIndex<this.numRecordBatches){let i=(e=this._footer)===null||e===void 0?void 0:e.getRecordBatch(this._recordBatchIndex);if(i&&this._handle.seek(i.offset))return this._reader.readMessage(t)}return null}},Po=class extends ni{get footer(){return this._footer}get numDictionaries(){return this._footer?this._footer.numDictionaries:0}get numRecordBatches(){return this._footer?this._footer.numRecordBatches:0}constructor(t,...e){let i=typeof e[0]!="number"?e.shift():void 0,n=e[0]instanceof Map?e.shift():void 0;super(t instanceof ir?t:new ir(t,i),n)}isFile(){return!0}isAsync(){return!0}open(t){let e=Object.create(null,{open:{get:()=>super.open}});return p(this,void 0,void 0,function*(){if(!this.closed&&!this._footer){this.schema=(this._footer=yield this._readFooter()).schema;for(let i of this._footer.dictionaryBatches())i&&(yield this._readDictionaryBatch(this._dictionaryIndex++))}return yield e.open.call(this,t)})}readRecordBatch(t){var e;return p(this,void 0,void 0,function*(){if(this.closed)return null;this._footer||(yield this.open());let i=(e=this._footer)===null||e===void 0?void 0:e.getRecordBatch(t);if(i&&(yield this._handle.seek(i.offset))){let n=yield this._reader.readMessage(k.RecordBatch);if(n?.isRecordBatch()){let s=n.header(),o=yield this._reader.readMessageBody(n.bodyLength);return this._loadRecordBatch(s,o)}}return null})}_readDictionaryBatch(t){var e;return p(this,void 0,void 0,function*(){let i=(e=this._footer)===null||e===void 0?void 0:e.getDictionaryBatch(t);if(i&&(yield this._handle.seek(i.offset))){let n=yield this._reader.readMessage(k.DictionaryBatch);if(n?.isDictionaryBatch()){let s=n.header(),o=yield this._reader.readMessageBody(n.bodyLength),a=this._loadDictionaryBatch(s,o);this.dictionaries.set(s.id,a)}}})}_readFooter(){return p(this,void 0,void 0,function*(){let{_handle:t}=this;t._pending&&(yield t._pending);let e=t.size-ko,i=yield t.readInt32(e),n=yield t.readAt(e-i,i);return Le.decode(n)})}_readNextMessageAndValidate(t){return p(this,void 0,void 0,function*(){if(this._footer||(yield this.open()),this._footer&&this._recordBatchIndex<this.numRecordBatches){let e=this._footer.getRecordBatch(this._recordBatchIndex);if(e&&(yield this._handle.seek(e.offset)))return yield this._reader.readMessage(t)}return null})}},Vo=class extends ii{constructor(t,e){super(t,e)}_loadVectors(t,e,i){return new Xn(e,t.nodes,t.buffers,this.dictionaries).visitMany(i)}};function Yc(r,t){return t&&typeof t.autoDestroy=="boolean"?t.autoDestroy:r.autoDestroy}function*Gc(r){let t=ot.from(r);try{if(!t.open({autoDestroy:!1}).closed)do yield t;while(!t.reset().open().closed)}finally{t.cancel()}}function Wc(r){return Et(this,arguments,function*(){let e=yield E(ot.from(r));try{if(!(yield E(e.open({autoDestroy:!1}))).closed)do yield yield E(e);while(!(yield E(e.reset().open())).closed)}finally{yield E(e.cancel())}})}function Zd(r){return new ge(new Vo(r))}function th(r){let t=r.peek(ri+7&-8);return t&&t.byteLength>=4?xs(t)?new sr(new Os(r.read())):new ge(new ii(r)):new ge(new ii(function*(){}()))}function eh(r){return p(this,void 0,void 0,function*(){let t=yield r.peek(ri+7&-8);return t&&t.byteLength>=4?xs(t)?new sr(new Os(yield r.read())):new nr(new ni(r)):new nr(new ni(function(){return Et(this,arguments,function*(){})}()))})}function rh(r){return p(this,void 0,void 0,function*(){let{size:t}=yield r.stat(),e=new ir(r,t);return t>=qc&&xs(yield e.readAt(0,ri+7&-8))?new en(new Po(e)):new nr(new ni(e))})}var et=class r extends b{static assemble(...t){let e=n=>n.flatMap(s=>Array.isArray(s)?e(s):s instanceof Z?s.data.children:s.data),i=new r;return i.visitMany(e(t)),i}constructor(){super(),this._byteLength=0,this._nodes=[],this._buffers=[],this._bufferRegions=[]}visit(t){if(t instanceof L)return this.visitMany(t.data),this;let{type:e}=t;if(!y.isDictionary(e)){let{length:i,nullCount:n}=t;if(i>2147483647)throw new RangeError("Cannot write arrays larger than 2^31 - 1 in length");y.isNull(e)||ie.call(this,n<=0?new Uint8Array(0):zr(t.offset,i,t.nullBitmap)),this.nodes.push(new re(i,n))}return super.visit(t)}visitNull(t){return this}visitDictionary(t){return this.visit(t.clone(t.type.indices))}get nodes(){return this._nodes}get buffers(){return this._buffers}get byteLength(){return this._byteLength}get bufferRegions(){return this._bufferRegions}};function ie(r){let t=r.byteLength+7&-8;return this.buffers.push(r),this.bufferRegions.push(new vt(this._byteLength,t)),this._byteLength+=t,this}function ih(r){let{type:t,length:e,typeIds:i,valueOffsets:n}=r;if(ie.call(this,i),t.mode===J.Sparse)return jo.call(this,r);if(t.mode===J.Dense){if(r.offset<=0)return ie.call(this,n),jo.call(this,r);{let s=i.reduce((d,h)=>Math.max(d,h),i[0]),o=new Int32Array(s+1),a=new Int32Array(s+1).fill(-1),c=new Int32Array(e),l=ci(-n[0],e,n);for(let d,h,f=-1;++f<e;)(h=a[d=i[f]])===-1&&(h=a[d]=l[d]),c[f]=l[f]-h,++o[d];ie.call(this,c);for(let d,h=-1,f=t.children.length;++h<f;)if(d=r.children[h]){let g=t.typeIds[h],M=Math.min(e,o[g]);this.visit(d.slice(a[g],M))}}}return this}function nh(r){let t;return r.nullCount>=r.length?ie.call(this,new Uint8Array(0)):(t=r.values)instanceof Uint8Array?ie.call(this,zr(r.offset,r.length,t)):ie.call(this,hr(r.values))}function or(r){return ie.call(this,r.values.subarray(0,r.length*r.stride))}function Hc(r){let{length:t,values:e,valueOffsets:i}=r,n=i[0],s=i[t],o=Math.min(s-n,e.byteLength-n);return ie.call(this,ci(-i[0],t,i)),ie.call(this,e.subarray(n,n+o)),this}function zo(r){let{length:t,valueOffsets:e}=r;return e&&ie.call(this,ci(e[0],t,e)),this.visit(r.children[0])}function jo(r){return this.visitMany(r.type.children.map((t,e)=>r.children[e]).filter(Boolean))[0]}et.prototype.visitBool=nh;et.prototype.visitInt=or;et.prototype.visitFloat=or;et.prototype.visitUtf8=Hc;et.prototype.visitBinary=Hc;et.prototype.visitFixedSizeBinary=or;et.prototype.visitDate=or;et.prototype.visitTimestamp=or;et.prototype.visitTime=or;et.prototype.visitDecimal=or;et.prototype.visitList=zo;et.prototype.visitStruct=jo;et.prototype.visitUnion=ih;et.prototype.visitInterval=or;et.prototype.visitFixedSizeList=zo;et.prototype.visitMap=zo;var Sr=class extends yr{static throughNode(t){throw new Error('"throughNode" not available in this environment')}static throughDOM(t,e){throw new Error('"throughDOM" not available in this environment')}constructor(t){super(),this._position=0,this._started=!1,this._sink=new pe,this._schema=null,this._dictionaryBlocks=[],this._recordBatchBlocks=[],this._dictionaryDeltaOffsets=new Map,mt(t)||(t={autoDestroy:!0,writeLegacyIpcFormat:!1}),this._autoDestroy=typeof t.autoDestroy=="boolean"?t.autoDestroy:!0,this._writeLegacyIpcFormat=typeof t.writeLegacyIpcFormat=="boolean"?t.writeLegacyIpcFormat:!1}toString(t=!1){return this._sink.toString(t)}toUint8Array(t=!1){return this._sink.toUint8Array(t)}writeAll(t){return xt(t)?t.then(e=>this.writeAll(e)):Lt(t)?qo(this,t):$o(this,t)}get closed(){return this._sink.closed}[Symbol.asyncIterator](){return this._sink[Symbol.asyncIterator]()}toDOMStream(t){return this._sink.toDOMStream(t)}toNodeStream(t){return this._sink.toNodeStream(t)}close(){return this.reset()._sink.close()}abort(t){return this.reset()._sink.abort(t)}finish(){return this._autoDestroy?this.close():this.reset(this._sink,this._schema),this}reset(t=this._sink,e=null){return t===this._sink||t instanceof pe?this._sink=t:(this._sink=new pe,t&&ba(t)?this.toDOMStream({type:"bytes"}).pipeTo(t):t&&_a(t)&&this.toNodeStream({objectMode:!1}).pipe(t)),this._started&&this._schema&&this._writeFooter(this._schema),this._started=!1,this._dictionaryBlocks=[],this._recordBatchBlocks=[],this._dictionaryDeltaOffsets=new Map,(!e||!Ir(e,this._schema))&&(e==null?(this._position=0,this._schema=null):(this._started=!0,this._schema=e,this._writeSchema(e))),this}write(t){let e=null;if(this._sink){if(t==null)return this.finish()&&void 0;if(t instanceof lt&&!(e=t.schema))return this.finish()&&void 0;if(t instanceof Z&&!(e=t.schema))return this.finish()&&void 0}else throw new Error("RecordBatchWriter is closed");if(e&&!Ir(e,this._schema)){if(this._started&&this._autoDestroy)return this.close();this.reset(this._sink,e)}t instanceof Z?t instanceof vr||this._writeRecordBatch(t):t instanceof lt?this.writeAll(t.batches):$t(t)&&this.writeAll(t)}_writeMessage(t,e=8){let i=e-1,n=Tt.encode(t),s=n.byteLength,o=this._writeLegacyIpcFormat?4:8,a=s+o+i&~i,c=a-s-o;return t.headerType===k.RecordBatch?this._recordBatchBlocks.push(new Me(a,t.bodyLength,this._position)):t.headerType===k.DictionaryBatch&&this._dictionaryBlocks.push(new Me(a,t.bodyLength,this._position)),this._writeLegacyIpcFormat||this._write(Int32Array.of(-1)),this._write(Int32Array.of(a-o)),s>0&&this._write(n),this._writePadding(c)}_write(t){if(this._started){let e=S(t);e&&e.byteLength>0&&(this._sink.write(e),this._position+=e.byteLength)}return this}_writeSchema(t){return this._writeMessage(Tt.from(t))}_writeFooter(t){return this._writeLegacyIpcFormat?this._write(Int32Array.of(0)):this._write(Int32Array.of(-1,0))}_writeMagic(){return this._write(ei)}_writePadding(t){return t>0?this._write(new Uint8Array(t)):this}_writeRecordBatch(t){let{byteLength:e,nodes:i,bufferRegions:n,buffers:s}=et.assemble(t),o=new ft(t.numRows,i,n),a=Tt.from(o,e);return this._writeDictionaries(t)._writeMessage(a)._writeBodyBuffers(s)}_writeDictionaryBatch(t,e,i=!1){this._dictionaryDeltaOffsets.set(e,t.length+(this._dictionaryDeltaOffsets.get(e)||0));let{byteLength:n,nodes:s,bufferRegions:o,buffers:a}=et.assemble(new L([t])),c=new ft(t.length,s,o),l=new St(c,e,i),d=Tt.from(l,n);return this._writeMessage(d)._writeBodyBuffers(a)}_writeBodyBuffers(t){let e,i,n;for(let s=-1,o=t.length;++s<o;)(e=t[s])&&(i=e.byteLength)>0&&(this._write(e),(n=(i+7&-8)-i)>0&&this._writePadding(n));return this}_writeDictionaries(t){for(let[e,i]of t.dictionaries){let n=this._dictionaryDeltaOffsets.get(e)||0;if(n===0||(i=i?.slice(n)).length>0)for(let s of i.data)this._writeDictionaryBatch(s,e,n>0),n+=s.length}return this}},Tr=class r extends Sr{static writeAll(t,e){let i=new r(e);return xt(t)?t.then(n=>i.writeAll(n)):Lt(t)?qo(i,t):$o(i,t)}},Er=class r extends Sr{static writeAll(t){let e=new r;return xt(t)?t.then(i=>e.writeAll(i)):Lt(t)?qo(e,t):$o(e,t)}constructor(){super(),this._autoDestroy=!0}_writeSchema(t){return this._writeMagic()._writePadding(2)}_writeFooter(t){let e=Le.encode(new Le(t,at.V4,this._recordBatchBlocks,this._dictionaryBlocks));return super._writeFooter(t)._write(e)._write(Int32Array.of(e.byteLength))._writeMagic()}};function $o(r,t){let e=t;t instanceof lt&&(e=t.batches,r.reset(void 0,t.schema));for(let i of e)r.write(i);return r.finish()}function qo(r,t){var e,i,n,s,o,a,c;return p(this,void 0,void 0,function*(){try{for(e=!0,i=zt(t);n=yield i.next(),s=n.done,!s;e=!0){c=n.value,e=!1;let l=c;r.write(l)}}catch(l){o={error:l}}finally{try{!e&&!s&&(a=i.return)&&(yield a.call(i))}finally{if(o)throw o.error}}return r.finish()})}function Kc(r,t){if(Lt(r))return oh(r,t);if($t(r))return sh(r,t);throw new Error("toDOMStream() must be called with an Iterable or AsyncIterable")}function sh(r,t){let e=null,i=t?.type==="bytes"||!1,n=t?.highWaterMark||Math.pow(2,24);return new ReadableStream(Object.assign(Object.assign({},t),{start(o){s(o,e||(e=r[Symbol.iterator]()))},pull(o){e?s(o,e):o.close()},cancel(){(e?.return&&e.return()||!0)&&(e=null)}}),Object.assign({highWaterMark:i?n:void 0},t));function s(o,a){let c,l=null,d=o.desiredSize||null;for(;!(l=a.next(i?d:null)).done;)if(ArrayBuffer.isView(l.value)&&(c=S(l.value))&&(d!=null&&i&&(d=d-c.byteLength+1),l.value=c),o.enqueue(l.value),d!=null&&--d<=0)return;o.close()}}function oh(r,t){let e=null,i=t?.type==="bytes"||!1,n=t?.highWaterMark||Math.pow(2,24);return new ReadableStream(Object.assign(Object.assign({},t),{start(o){return p(this,void 0,void 0,function*(){yield s(o,e||(e=r[Symbol.asyncIterator]()))})},pull(o){return p(this,void 0,void 0,function*(){e?yield s(o,e):o.close()})},cancel(){return p(this,void 0,void 0,function*(){(e?.return&&(yield e.return())||!0)&&(e=null)})}}),Object.assign({highWaterMark:i?n:void 0},t));function s(o,a){return p(this,void 0,void 0,function*(){let c,l=null,d=o.desiredSize||null;for(;!(l=yield a.next(i?d:null)).done;)if(ArrayBuffer.isView(l.value)&&(c=S(l.value))&&(d!=null&&i&&(d=d-c.byteLength+1),l.value=c),o.enqueue(l.value),d!=null&&--d<=0)return;o.close()})}}function Xc(r){return new Go(r)}var Go=class{constructor(t){this._numChunks=0,this._finished=!1,this._bufferedSize=0;let{["readableStrategy"]:e,["writableStrategy"]:i,["queueingStrategy"]:n="count"}=t,s=ya(t,["readableStrategy","writableStrategy","queueingStrategy"]);this._controller=null,this._builder=br(s),this._getSize=n!=="bytes"?Qc:Jc;let{["highWaterMark"]:o=n==="bytes"?Math.pow(2,14):1e3}=Object.assign({},e),{["highWaterMark"]:a=n==="bytes"?Math.pow(2,14):1e3}=Object.assign({},i);this.readable=new ReadableStream({cancel:()=>{this._builder.clear()},pull:c=>{this._maybeFlush(this._builder,this._controller=c)},start:c=>{this._maybeFlush(this._builder,this._controller=c)}},{highWaterMark:o,size:n!=="bytes"?Qc:Jc}),this.writable=new WritableStream({abort:()=>{this._builder.clear()},write:()=>{this._maybeFlush(this._builder,this._controller)},close:()=>{this._maybeFlush(this._builder.finish(),this._controller)}},{highWaterMark:a,size:c=>this._writeValueAndReturnChunkSize(c)})}_writeValueAndReturnChunkSize(t){let e=this._bufferedSize;return this._bufferedSize=this._getSize(this._builder.append(t)),this._bufferedSize-e}_maybeFlush(t,e){e!=null&&(this._bufferedSize>=e.desiredSize&&++this._numChunks&&this._enqueue(e,t.toVector()),t.finished&&((t.length>0||this._numChunks===0)&&++this._numChunks&&this._enqueue(e,t.toVector()),!this._finished&&(this._finished=!0)&&this._enqueue(e,null)))}_enqueue(t,e){this._bufferedSize=0,this._controller=null,e==null?t.close():t.enqueue(e)}},Qc=r=>{var t;return(t=r?.length)!==null&&t!==void 0?t:0},Jc=r=>{var t;return(t=r?.byteLength)!==null&&t!==void 0?t:0};function Bs(r,t){let e=new pe,i=null,n=new ReadableStream({cancel(){return p(this,void 0,void 0,function*(){yield e.close()})},start(a){return p(this,void 0,void 0,function*(){yield o(a,i||(i=yield s()))})},pull(a){return p(this,void 0,void 0,function*(){i?yield o(a,i):a.close()})}});return{writable:new WritableStream(e,Object.assign({highWaterMark:Math.pow(2,14)},r)),readable:n};function s(){return p(this,void 0,void 0,function*(){return yield(yield ot.from(e)).open(t)})}function o(a,c){return p(this,void 0,void 0,function*(){let l=a.desiredSize,d=null;for(;!(d=yield c.next()).done;)if(a.enqueue(d.value),l!=null&&--l<=0)return;a.close()})}}function Ns(r,t){let e=new this(r),i=new kt(e),n=new ReadableStream({cancel(){return p(this,void 0,void 0,function*(){yield i.cancel()})},pull(o){return p(this,void 0,void 0,function*(){yield s(o)})},start(o){return p(this,void 0,void 0,function*(){yield s(o)})}},Object.assign({highWaterMark:Math.pow(2,14)},t));return{writable:new WritableStream(e,r),readable:n};function s(o){return p(this,void 0,void 0,function*(){let a=null,c=o.desiredSize;for(;a=yield i.read(c||null);)if(o.enqueue(a),c!=null&&(c-=a.byteLength)<=0)return;o.close()})}}function xr(r){let t=ot.from(r);return xt(t)?t.then(e=>xr(e)):t.isAsync()?t.readAll().then(e=>new lt(e)):new lt(t.readAll())}function Fs(r,t="stream"){return(t==="stream"?Tr:Er).writeAll(r).toUint8Array(!0)}var lh=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},ro),Oo),_o),io),Xs),bo),{compareSchemas:Ir,compareFields:Ec,compareTypes:xc});ut.toDOMStream=Kc;K.throughDOM=Xc;ot.throughDOM=Bs;sr.throughDOM=Bs;ge.throughDOM=Bs;Sr.throughDOM=Ns;Er.throughDOM=Ns;Tr.throughDOM=Ns;function Wo(r="ws://localhost:3000/"){let t=[],e=!1,i=null,n,s={open(){e=!0,c()},close(){for(e=!1,i=null,n=null;t.length;)t.shift().reject("Socket closed")},error(l){if(i){let{reject:d}=i;i=null,c(),d(l)}else console.error("WebSocket error: ",l)},message({data:l}){if(i){let{query:d,resolve:h,reject:f}=i;if(i=null,c(),typeof l=="string"){let g=JSON.parse(l);g.error?f(g.error):h(g)}else if(d.type==="exec")h();else if(d.type==="arrow")h(xr(l.arrayBuffer()));else throw new Error(`Unexpected socket data: ${l}`)}else console.log("WebSocket message: ",l)}};function o(){n=new WebSocket(r);for(let l in s)n.addEventListener(l,s[l])}function a(l,d,h){n==null&&o(),t.push({query:l,resolve:d,reject:h}),e&&!i&&c()}function c(){t.length&&(i=t.shift(),n.send(JSON.stringify(i.query)))}return{get connected(){return e},query(l){return new Promise((d,h)=>a(l,d,h))}}}var Vt=class{constructor(t,e){t&&(this.table=String(t)),e&&(this.column=e)}get columns(){return this.column?[this.column]:[]}toString(){let{table:t,column:e}=this;if(e){let i=e.startsWith("*")?e:`"${e}"`;return`${t?`${tl(t)}.`:""}${i}`}else return t?tl(t):"NULL"}};function tl(r){return r.split(".").map(e=>`"${e}"`).join(".")}function el(r,t){return r instanceof Vt&&r.column===t}function z(r){return typeof r=="string"?il(r):r}function Ar(r){return typeof r=="string"?rl(r):r}function rl(r){return new Vt(r)}function il(r,t){return arguments.length===1&&(t=r,r=null),new Vt(r,t)}function ar(r){switch(typeof r){case"boolean":return r?"TRUE":"FALSE";case"string":return`'${r}'`;case"number":return Number.isFinite(r)?String(r):"NULL";default:if(r==null)return"NULL";if(r instanceof Date){let t=+r;if(Number.isNaN(t))return"NULL";let e=r.getUTCFullYear(),i=r.getUTCMonth(),n=r.getUTCDate();return t===Date.UTC(e,i,n)?`MAKE_DATE(${e}, ${i+1}, ${n})`:`EPOCH_MS(${t})`}else return r instanceof RegExp?`'${r.source}'`:String(r)}}var Or=r=>typeof r?.addEventListener=="function";function Rs(r){return r instanceof cr}var cr=class{constructor(t,e,i){this._expr=Array.isArray(t)?t:[t],this._deps=e||[],this.annotate(i);let n=this._expr.filter(s=>Or(s));n.length>0?(this._params=Array.from(new Set(n)),this._params.forEach(s=>{s.addEventListener("value",()=>uh(this,this.map?.get("value")))})):this.addEventListener=void 0}get value(){return this}get columns(){let{_params:t,_deps:e}=this;if(t){let i=new Set(t.flatMap(n=>{let s=n.value?.columns;return Array.isArray(s)?s:[]}));if(i.size){let n=new Set(e);return i.forEach(s=>n.add(s)),Array.from(n)}}return e}get column(){return this._deps.length?this._deps[0]:this.columns[0]}annotate(...t){return Object.assign(this,...t)}toString(){return this._expr.map(t=>Or(t)&&!Rs(t)?ar(t.value):t).join("")}addEventListener(t,e){let i=this.map||(this.map=new Map);(i.get(t)||(i.set(t,new Set),i.get(t))).add(e)}};function uh(r,t){if(t?.size)return Promise.allSettled(Array.from(t,e=>e(r)))}function Yo(r,t){let e=[r[0]],i=new Set,n=t.length;for(let s=0,o=0;s<n;){let a=t[s];Or(a)?e[++o]=a:(Array.isArray(a?.columns)&&a.columns.forEach(l=>i.add(l)),e[o]+=typeof a=="string"?a:ar(a));let c=r[++s];Or(e[o])?e[++o]=c:e[o]+=c}return{spans:e,cols:Array.from(i)}}function U(r,...t){let{spans:e,cols:i}=Yo(r,t);return new cr(e,i)}function rn(r){r(this.op,this),this.children?.forEach(t=>t.visit(r))}function nl(r,t){let e=t.filter(n=>n!=null).map(z),i=e.map((n,s)=>s?` ${r} `:"");return e.length===1?i.push(""):e.length>1&&(i[0]="(",i.push(")")),U(i,...e).annotate({op:r,children:e,visit:rn})}var Ho=(...r)=>nl("AND",r.flat()),Ko=(...r)=>nl("OR",r.flat()),dh=r=>t=>U`(${r} ${z(t)})`.annotate({op:r,a:t,visit:rn}),hh=dh("NOT"),sl=r=>t=>U`(${z(t)} ${r})`.annotate({op:r,a:t,visit:rn}),Qo=sl("IS NULL"),fh=sl("IS NOT NULL"),lr=r=>(t,e)=>U`(${z(t)} ${r} ${z(e)})`.annotate({op:r,a:t,b:e,visit:rn}),ph=lr("="),mh=lr("<>"),yh=lr("<"),gh=lr(">"),bh=lr("<="),_h=lr(">="),wh=lr("IS DISTINCT FROM"),Ih=lr("IS NOT DISTINCT FROM");function vh(r,t,e,i){t=z(t);let n=r.startsWith("NOT ")?"NOT ":"";return(e?i?U`${n}(${e[0]} <= ${t} AND ${t} < ${e[1]})`:U`(${t} ${r} ${e[0]} AND ${e[1]})`:U``).annotate({op:r,visit:rn,field:t,range:e})}var Ds=(r,t,e)=>vh("BETWEEN",r,t,e);function Br(r,t){return Array.from({length:r},()=>t)}function jt(r,t){return(...e)=>{let i=e.map(z),n=t?`::${t}`:"";return(i.length?U([`${r}(`,...Br(i.length-1,", "),`)${n}`],...i):U`${r}()${n}`).annotate({func:r,args:i})}}var Sh=jt("REGEXP_MATCHES"),Th=jt("CONTAINS"),Eh=jt("PREFIX"),xh=jt("SUFFIX"),Ah=jt("LOWER"),Oh=jt("UPPER"),Bh=jt("LENGTH"),Nh=jt("ISNAN"),Fh=jt("ISFINITE"),Rh=jt("ISINF");var nn=class r extends cr{constructor(t,e,i,n,s="",o="",a=""){let c;if(n&&!(s||o||a))c=n?U`${e} OVER "${n}"`:U`${e} OVER ()`;else{let f=s&&o?" ":"",g=(s||o)&&a?" ":"";c=U`${e} OVER (${n?`"${n}" `:""}${s}${f}${o}${g}${a})`}i&&(c=U`(${c})::${i}`);let{_expr:d,_deps:h}=c;super(d,h,{window:t,func:e,type:i,name:n,group:s,order:o,frame:a})}get basis(){return this.column}get label(){let{func:t}=this;return t.label??t.toString()}over(t){let{window:e,func:i,type:n,group:s,order:o,frame:a}=this;return new r(e,i,n,t,s,o,a)}partitionby(...t){let e=t.flat().filter(d=>d).map(z),i=U(["PARTITION BY ",Br(e.length-1,", "),""],...e),{window:n,func:s,type:o,name:a,order:c,frame:l}=this;return new r(n,s,o,a,i,c,l)}orderby(...t){let e=t.flat().filter(d=>d).map(z),i=U(["ORDER BY ",Br(e.length-1,", "),""],...e),{window:n,func:s,type:o,name:a,group:c,frame:l}=this;return new r(n,s,o,a,c,i,l)}rows(t){let e=ol("ROWS",t),{window:i,func:n,type:s,name:o,group:a,order:c}=this;return new r(i,n,s,o,a,c,e)}range(t){let e=ol("RANGE",t),{window:i,func:n,type:s,name:o,group:a,order:c}=this;return new r(i,n,s,o,a,c,e)}};function ol(r,t){if(Or(t)){let e=U`${t}`;return e.toString=()=>`${r} ${al(t.value)}`,e}return`${r} ${al(t)}`}function al(r){let[t,e]=r,i=t===0?"CURRENT ROW":Number.isFinite(t)?`${Math.abs(t)} PRECEDING`:"UNBOUNDED PRECEDING",n=e===0?"CURRENT ROW":Number.isFinite(e)?`${Math.abs(e)} FOLLOWING`:"UNBOUNDED FOLLOWING";return`BETWEEN ${i} AND ${n}`}function ne(r,t){return(...e)=>{let i=jt(r)(...e);return new nn(r,i,t)}}var Dh=ne("ROW_NUMBER","INTEGER"),Lh=ne("RANK","INTEGER"),Mh=ne("DENSE_RANK","INTEGER"),Uh=ne("PERCENT_RANK"),Ch=ne("CUME_DIST"),kh=ne("NTILE"),Ph=ne("LAG"),Vh=ne("LEAD"),jh=ne("FIRST_VALUE"),zh=ne("LAST_VALUE"),$h=ne("NTH_VALUE");var Jo=class r extends cr{constructor(t,e,i,n,s){e=(e||[]).map(z);let{strings:o,exprs:a}=qh(t,e,i,n,s),{spans:c,cols:l}=Yo(o,a);super(c,l,{aggregate:t,args:e,type:i,isDistinct:n,filter:s})}get basis(){return this.column}get label(){let{aggregate:t,args:e,isDistinct:i}=this,n=i?"DISTINCT"+(e.length?" ":""):"",s=e.length?`(${n}${e.map(Gh).join(", ")})`:"";return`${t.toLowerCase()}${s}`}distinct(){let{aggregate:t,args:e,type:i,filter:n}=this;return new r(t,e,i,!0,n)}where(t){let{aggregate:e,args:i,type:n,isDistinct:s}=this;return new r(e,i,n,s,t)}window(){let{aggregate:t,args:e,type:i,isDistinct:n}=this,s=new r(t,e,null,n);return new nn(t,s,i)}partitionby(...t){return this.window().partitionby(...t)}orderby(...t){return this.window().orderby(...t)}rows(t,e){return this.window().rows(t,e)}range(t,e){return this.window().range(t,e)}};function qh(r,t,e,i,n){let s=`)${e?`::${e}`:""}`,o=[`${r}(${i?"DISTINCT ":""}`],a=[];return t.length?(o=o.concat([...Br(t.length-1,", "),`${s}${n?" FILTER (WHERE ":""}`,...n?[")"]:[]]),a=[...t,...n?[n]:[]]):o[0]+="*"+s,{exprs:a,strings:o}}function Gh(r){let t=ar(r);return t&&t.startsWith('"')&&t.endsWith('"')?t.slice(1,-1):t}function C(r,t){return(...e)=>new Jo(r,e,t)}var sn=C("COUNT","INTEGER"),Wh=C("AVG"),Yh=C("AVG"),Hh=C("MAD"),Xo=C("MAX"),Zo=C("MIN"),Kh=C("SUM","DOUBLE"),Qh=C("PRODUCT"),Jh=C("MEDIAN"),Xh=C("QUANTILE"),Zh=C("MODE"),tf=C("VARIANCE"),ef=C("STDDEV"),rf=C("SKEWNESS"),nf=C("KURTOSIS"),sf=C("ENTROPY"),of=C("VAR_POP"),af=C("STDDEV_POP"),cf=C("CORR"),lf=C("COVAR_POP"),uf=C("REGR_INTERCEPT"),df=C("REGR_SLOPE"),hf=C("REGR_COUNT"),ff=C("REGR_R2"),pf=C("REGR_SYY"),mf=C("REGR_SXX"),yf=C("REGR_SXY"),gf=C("REGR_AVGX"),bf=C("REGR_AVGY"),_f=C("FIRST"),wf=C("LAST"),If=C("ARG_MIN"),vf=C("ARG_MAX"),Sf=C("STRING_AGG"),Tf=C("ARRAY_AGG");var ta=r=>{let t=z(r);return U`(1000 * (epoch(${t}) - second(${t})) + millisecond(${t}))::DOUBLE`};var be=class r{static select(...t){return new r().select(...t)}static from(...t){return new r().from(...t)}static with(...t){return new r().with(...t)}static union(...t){return new Nr("UNION",t.flat())}static unionAll(...t){return new Nr("UNION ALL",t.flat())}static intersect(...t){return new Nr("INTERSECT",t.flat())}static except(...t){return new Nr("EXCEPT",t.flat())}constructor(){this.query={with:[],select:[],from:[],where:[],groupby:[],having:[],window:[],qualify:[],orderby:[]}}clone(){let t=new r;return t.query={...this.query},t}with(...t){let{query:e}=this;if(t.length===0)return e.with;{let i=[],n=(s,o)=>{let a=o.clone();a.cteFor=this,i.push({as:s,query:a})};return t.flat().forEach(s=>{if(s!=null)if(s.as&&s.query)n(s.as,s.query);else for(let o in s)n(o,s[o])}),e.with=e.with.concat(i),this}}select(...t){let{query:e}=this;if(t.length===0)return e.select;{let i=[];for(let n of t.flat())if(n!=null)if(typeof n=="string")i.push({as:n,expr:z(n)});else if(n instanceof Vt)i.push({as:n.column,expr:n});else if(Array.isArray(n))i.push({as:n[0],expr:n[1]});else for(let s in n)i.push({as:Ls(s),expr:z(n[s])});return e.select=e.select.concat(i),this}}$select(...t){return this.query.select=[],this.select(...t)}distinct(t=!0){return this.query.distinct=!!t,this}from(...t){let{query:e}=this;if(t.length===0)return e.from;{let i=[];return t.flat().forEach(n=>{if(n!=null)if(typeof n=="string")i.push({as:n,from:Ar(n)});else if(n instanceof Vt)i.push({as:n.table,from:n});else if(Ms(n)||Rs(n))i.push({from:n});else if(Array.isArray(n))i.push({as:Ls(n[0]),from:Ar(n[1])});else for(let s in n)i.push({as:Ls(s),from:Ar(n[s])})}),e.from=e.from.concat(i),this}}$from(...t){return this.query.from=[],this.from(...t)}sample(t,e){let{query:i}=this;if(arguments.length===0)return i.sample;{let n=t;return typeof t=="number"&&(n=t>0&&t<1?{perc:100*t,method:e}:{rows:Math.round(t),method:e}),i.sample=n,this}}where(...t){let{query:e}=this;return t.length===0?e.where:(e.where=e.where.concat(t.flat().filter(i=>i)),this)}$where(...t){return this.query.where=[],this.where(...t)}groupby(...t){let{query:e}=this;return t.length===0?e.groupby:(e.groupby=e.groupby.concat(t.flat().filter(i=>i).map(z)),this)}$groupby(...t){return this.query.groupby=[],this.groupby(...t)}having(...t){let{query:e}=this;return t.length===0?e.having:(e.having=e.having.concat(t.flat().filter(i=>i)),this)}window(...t){let{query:e}=this;if(t.length===0)return e.window;{let i=[];return t.flat().forEach(n=>{if(n!=null)for(let s in n)i.push({as:Ls(s),expr:n[s]})}),e.window=e.window.concat(i),this}}qualify(...t){let{query:e}=this;return t.length===0?e.qualify:(e.qualify=e.qualify.concat(t.flat().filter(i=>i)),this)}orderby(...t){let{query:e}=this;return t.length===0?e.orderby:(e.orderby=e.orderby.concat(t.flat().filter(i=>i).map(z)),this)}limit(t){let{query:e}=this;return arguments.length===0?e.limit:(e.limit=Number.isFinite(t)?t:void 0,this)}offset(t){let{query:e}=this;return arguments.length===0?e.offset:(e.offset=Number.isFinite(t)?t:void 0,this)}get subqueries(){let{query:t,cteFor:e}=this,n=(e?.query||t).with?.reduce((o,{as:a,query:c})=>(o[a]=c,o),{}),s=[];return t.from.forEach(({from:o})=>{if(Ms(o))s.push(o);else if(n[o.table]){let a=n[o.table];s.push(a)}}),s}toString(){let{select:t,distinct:e,from:i,sample:n,where:s,groupby:o,having:a,window:c,qualify:l,orderby:d,limit:h,offset:f,with:g}=this.query,M=[];if(g.length){let G=g.map(({as:V,query:rt})=>`"${V}" AS (${rt})`);M.push(`WITH ${G.join(", ")}`)}let we=t.map(({as:G,expr:V})=>el(V,G)&&!V.table?`${V}`:`${V} AS "${G}"`);if(M.push(`SELECT${e?" DISTINCT":""} ${we.join(", ")}`),i.length){let G=i.map(({as:V,from:rt})=>{let Ie=Ms(rt)?`(${rt})`:`${rt}`;return!V||V===rt.table?Ie:`${Ie} AS "${V}"`});M.push(`FROM ${G.join(", ")}`)}if(s.length){let G=s.map(String).filter(V=>V).join(" AND ");G&&M.push(`WHERE ${G}`)}if(n){let{rows:G,perc:V,method:rt,seed:Ie}=n,on=G?`${G} ROWS`:`${V} PERCENT`,an=rt?` (${rt}${Ie!=null?`, ${Ie}`:""})`:"";M.push(`USING SAMPLE ${on}${an}`)}if(o.length&&M.push(`GROUP BY ${o.join(", ")}`),a.length){let G=a.map(String).filter(V=>V).join(" AND ");G&&M.push(`HAVING ${G}`)}if(c.length){let G=c.map(({as:V,expr:rt})=>`"${V}" AS (${rt})`);M.push(`WINDOW ${G.join(", ")}`)}if(l.length){let G=l.map(String).filter(V=>V).join(" AND ");G&&M.push(`QUALIFY ${G}`)}return d.length&&M.push(`ORDER BY ${d.join(", ")}`),Number.isFinite(h)&&M.push(`LIMIT ${h}`),Number.isFinite(f)&&M.push(`OFFSET ${f}`),M.join(" ")}},Nr=class r{constructor(t,e){this.op=t,this.queries=e.map(i=>i.clone()),this.query={orderby:[]}}clone(){let t=new r(this.op,this.queries);return t.query={...this.query},t}orderby(...t){let{query:e}=this;return t.length===0?e.orderby:(e.orderby=e.orderby.concat(t.flat().filter(i=>i).map(z)),this)}limit(t){let{query:e}=this;return arguments.length===0?e.limit:(e.limit=Number.isFinite(t)?t:void 0,this)}offset(t){let{query:e}=this;return arguments.length===0?e.offset:(e.offset=Number.isFinite(t)?t:void 0,this)}get subqueries(){let{queries:t,cteFor:e}=this;return e&&t.forEach(i=>i.cteFor=e),t}toString(){let{op:t,queries:e,query:{orderby:i,limit:n,offset:s}}=this,o=[e.join(` ${t} `)];return i.length&&o.push(`ORDER BY ${i.join(", ")}`),Number.isFinite(n)&&o.push(`LIMIT ${n}`),Number.isFinite(s)&&o.push(`OFFSET ${s}`),o.join(" ")}};function Ms(r){return r instanceof be||r instanceof Nr}function Ls(r){return Ef(r)?r.slice(1,-1):r}function Ef(r){return r[0]==='"'&&r[r.length-1]==='"'}function Us(r,t,{replace:e=!1,temp:i=!0,view:n=!1}={}){return"CREATE"+(e?" OR REPLACE ":" ")+(i?"TEMP ":"")+(n?"VIEW":"TABLE")+(e?" ":" IF NOT EXISTS ")+r+" AS "+t}function cl(r){switch(r){case"BIGINT":case"HUGEINT":case"INTEGER":case"SMALLINT":case"TINYINT":case"UBIGINT":case"UINTEGER":case"USMALLINT":case"UTINYINT":case"DOUBLE":case"FLOAT":case"REAL":case"DECIMAL":return"number";case"DATE":case"TIMESTAMP":case"TIMESTAMPTZ":case"TIMESTAMP WITH TIME ZONE":case"TIME":case"TIMESTAMP_NS":return"date";case"BOOLEAN":return"boolean";case"VARCHAR":case"UUID":return"string";case"LIST":return"array";case"BLOB":case"STRUCT":case"MAP":return"object";default:throw new Error(`Unsupported type: ${r}`)}}var xf="count",Af="nulls",Of="max",Bf="min",Nf="distinct";var Ff={[xf]:sn,[Nf]:r=>sn(r).distinct(),[Of]:Xo,[Bf]:Zo,[Af]:r=>sn().where(Qo(r))};function ll({table:r,column:t},e){return be.from(r).select(e.map(i=>[i,Ff[i](t)]))}var ul=()=>Object.create(null),Cs=class{constructor(t){this.mc=t,this.clear()}clear(){this.tables=ul()}tableInfo(t){let e=this.tables;if(e[t])return e[t];let i=Rf(this.mc,t).catch(n=>{throw e[t]=null,n});return e[t]=i}async fieldInfo({table:t,column:e,stats:i}){let s=(await this.tableInfo(t))[e];if(s==null)return;if(!i?.length)return s;let o=await this.mc.query(ll(s,i),{persist:!0}),a={...s,...Array.from(o)[0]};for(let c in a){let l=a[c];typeof l=="bigint"&&(a[c]=Number(l))}return a}async queryFields(t){let e=await Df(this,t);return(await Promise.all(e.map(n=>this.fieldInfo(n)))).filter(n=>n)}};async function Rf(r,t){let e=await r.query(`DESCRIBE ${Ar(t)}`,{type:"json",cache:!1}),i=ul();for(let n of e)i[n.column_name]={table:t,column:n.column_name,sqlType:n.column_type,type:cl(n.column_type),nullable:n.null==="YES"};return i}async function Df(r,t){return t.length===1&&t[0].column==="*"?Object.values(await r.tableInfo(t[0].table)):t}function hl(r){let t=2166136261;for(let e=0,i=r.length;e<i;++e){let n=r.charCodeAt(e),s=n&65280;s&&(t=dl(t^s>>8)),t=dl(t^n&255)}return Lf(t)}function dl(r){return r+(r<<1)+(r<<4)+(r<<7)+(r<<8)+(r<<24)}function Lf(r){return r+=r<<13,r^=r>>>7,r+=r<<3,r^=r>>>17,r+=r<<5,r&4294967295}var ml=r=>r,ks=class{constructor(t,{selection:e,temp:i=!0}){this.mc=t,this.selection=e,this.temp=i,this.reset()}reset(){this.enabled=!1,this.clients=null,this.indices=null,this.activeView=null}clear(){this.indices&&(this.mc.cancel(Array.from(this.indices.values(),t=>t.result)),this.indices=null)}index(t,e){if(this.clients!==t){let l=Array.from(t,pl),d=l[0]?.from;this.enabled=l.every(h=>h&&h.from===d),this.clients=t,this.activeView=null,this.clear()}if(!this.enabled)return!1;e=e||this.selection.active;let{source:i}=e;if(i&&i===this.activeView?.source)return!0;if(this.clear(),!i)return!1;let n=this.activeView=Mf(e);if(!n)return!1;this.mc.logger().warn("DATA CUBE INDEX CONSTRUCTION");let s=this.selection.remove(i),o=this.indices=new Map,{mc:a,temp:c}=this;for(let l of t){if(s.skip(l,e))continue;let d=pl(l),h=l.query(s.predicate(l)).select({...n.columns,...d.count}).groupby(Object.keys(n.columns)),[f]=h.subqueries;if(f){let rt=Object.values(n.columns).map(Ie=>Ie.columns[0]);kf(f,rt)}let g=h.orderby();h.query.orderby=[];let M=h.toString(),G=`cube_index_${(hl(M)>>>0).toString(16)}`,V=a.exec(Us(G,M,{temp:c}));o.set(l,{table:G,result:V,order:g,...d})}}async update(){let{clients:t,selection:e,activeView:i}=this,n=i.predicate(e.active.predicate);return Promise.all(Array.from(t).map(s=>this.updateClient(s,n)))}async updateClient(t,e){let i=this.indices.get(t);if(!i)return;e||(e=this.activeView.predicate(this.selection.active.predicate));let{table:n,dims:s,aggr:o,order:a=[]}=i,c=be.select(s,o).from(n).groupby(s).where(e).orderby(a);return this.mc.updateClient(t,c)}};function Mf(r){let{source:t,schema:e}=r,i=r.predicate?.columns;if(!e||!i)return null;let{type:n,scales:s,pixelSize:o=1}=e,a;if(n==="interval"&&s){let c=s.map(l=>Uf(l,o));if(c.some(l=>l==null))return null;c.length===1?(a=l=>l?Ds("active0",l.range.map(c[0])):[],i={active0:c[0](r.predicate.field)}):(a=l=>l?Ho(l.children.map(({range:d},h)=>Ds(`active${h}`,d.map(c[h])))):[],i=Object.fromEntries(r.predicate.children.map((l,d)=>[`active${d}`,c[d](l.field)])))}else if(n==="point")a=ml,i=Object.fromEntries(i.map(c=>[c.toString(),c]));else return null;return{source:t,columns:i,predicate:a}}function Uf(r,t){let{type:e,domain:i,range:n}=r,s,o;switch(e){case"linear":s=ml,o=z;break;case"log":s=Math.log,o=a=>U`LN(${z(a)})`;break;case"symlog":s=a=>Math.sign(a)*Math.log1p(Math.abs(a)),o=a=>(a=z(a),U`SIGN(${a}) * LN(1 + ABS(${a}))`);break;case"sqrt":s=Math.sqrt,o=a=>U`SQRT(${z(a)})`;break;case"utc":case"time":s=a=>+a,o=a=>a instanceof Date?+a:ta(z(a));break}return s?Cf(i,n,t,s,o):null}function Cf(r,t,e,i,n){let s=i(Math.min(r[0],r[1])),o=i(Math.max(r[0],r[1])),a=Math.abs(i(t[1])-i(t[0]))/(o-s)/e,c=e===1?"":`${e}::INTEGER * `;return l=>U`${c}FLOOR(${a}::DOUBLE * (${n(l)} - ${s}::DOUBLE))::INTEGER`}var fl={from:NaN};function pl(r){if(!r.filterIndexable)return fl;let t=r.query(),e=ea(t);if(!e||!t.groupby)return fl;let i=new Set(t.groupby().map(a=>a.column)),n=[],s=[],o;for(let{as:a,expr:{aggregate:c}}of t.select())switch(c?.toUpperCase?.()){case"COUNT":case"SUM":n.push({[a]:U`SUM("${a}")::DOUBLE`});break;case"AVG":o="_count_",n.push({[a]:U`(SUM("${a}" * ${o}) / SUM(${o}))::DOUBLE`});break;case"MAX":n.push({[a]:U`MAX("${a}")`});break;case"MIN":n.push({[a]:U`MIN("${a}")`});break;default:if(i.has(a))s.push(a);else return null}return{aggr:n,dims:s,count:o?{[o]:U`COUNT(*)`}:{},from:e}}function ea(r){let t=r.subqueries;if(r.select){let i=r.from();if(!i.length)return;if(t.length===0)return i[0].from.table}let e=ea(t[0]);for(let i=1;i<t.length;++i){let n=ea(t[i]);if(n!==void 0&&n!==e)return NaN}return e}function kf(r,t){let e=new Set,i=n=>{e.has(n)||(e.add(n),n.select&&n.from().length&&n.select(t),n.subqueries.forEach(i))};i(r)}var Ps=class{constructor(t,e,i=!0){this.mc=t,this.selection=e,this.clients=new Set,this.indexer=i?new ks(this.mc,{...i,selection:e}):null;let{value:n,activate:s}=this.handlers={value:()=>this.update(),activate:o=>this.indexer?.index(this.clients,o)};e.addEventListener("value",n),e.addEventListener("activate",s)}finalize(){let{value:t,activate:e}=this.handlers;this.selection.removeEventListener("value",t),this.selection.removeEventListener("activate",e)}reset(){this.indexer?.reset()}add(t){return(this.clients=new Set(this.clients)).add(t),this}remove(t){return this.clients.has(t)&&(this.clients=new Set(this.clients)).delete(t),this}update(){let{mc:t,indexer:e,clients:i,selection:n}=this;return e?.index(i)?e.update():Pf(t,i,n)}};function Pf(r,t,e){return Promise.all(Array.from(t).map(i=>{let n=e.predicate(i);if(n!=null)return r.updateClient(i,i.query(n))}))}function Vs(){let r,t,e=new Promise((i,n)=>{r=i,t=n});return e.fulfill=i=>(r(i),e),e.reject=i=>(t(i),e),e}function yl(r,t,e){let i=[],n=0;function s(){let o=Vf(i,t);i=[],n=0;for(let a of o)zf(a,r,e),Gf(a,t)}return{add(o,a){o.request.type==="arrow"?(n=n||requestAnimationFrame(()=>s()),i.push({entry:o,priority:a,index:i.length})):r(o,a)}}}function Vf(r,t){let e=[],i=new Map;for(let n of r){let{entry:{request:s}}=n,o=jf(s.query,t);if(!i.has(o)){let a=[];e.push(a),i.set(o,a)}i.get(o).push(n)}return e}function jf(r,t){let e=`${r}`;if(r instanceof be&&!t.get(e)){if(r.orderby().length||r.where().length||r.qualify().length||r.having().length)return e;let i=r.clone().$select("*"),n=r.groupby();if(n.length){let s={};r.select().forEach(({as:o,expr:a})=>s[o]=a),i.$groupby(n.map(o=>o instanceof Vt&&s[o.column]||o))}return`${i}`}else return e}function zf(r,t,e){if($f(r))t({request:{type:"arrow",cache:!1,record:!1,query:qf(r,e)},result:r.result=Vs()});else for(let{entry:i,priority:n}of r)t(i,n)}function $f(r){if(r.length>1){let t=`${r[0].entry.request.query}`;for(let e=1;e<r.length;++e)if(t!==`${r[e].entry.request.query}`)return!0}return!1}function qf(r,t){let e=r.maps=[],i=new Map;for(let o of r){let{query:a}=o.entry.request,c=[];e.push(c);for(let{as:l,expr:d}of a.select()){let h=`${d}`;i.has(h)||i.set(h,[`col${i.size}`,d]);let[f]=i.get(h);c.push([f,l])}t(`${a}`)}let n=r[0].entry.request.query.clone(),s=n.groupby();if(s.length){let o={};r.maps[0].forEach(([a,c])=>o[c]=a),n.$groupby(s.map(a=>a instanceof Vt&&o[a.column]||a))}return n.$select(Array.from(i.values()))}async function Gf(r,t){let{maps:e,result:i}=r;if(!e)return;let n;try{n=await i}catch(s){for(let{entry:o}of r)o.result.reject(s);return}r.forEach(({entry:s},o)=>{let{request:a,result:c}=s,l=Wf(n,e[o]);a.cache&&t.set(String(a.query),l),c.fulfill(l)})}function Wf(r,t){if(t){let e={};for(let[i,n]of t)e[n]=r.getChild(i);return new r.constructor(e)}else return r}var Yf=typeof requestIdleCallback<"u"?requestIdleCallback:setTimeout,gl=()=>({get:()=>{},set:(r,t)=>t,clear:()=>{}});function bl({max:r=1e3,ttl:t=3*60*60*1e3}={}){let e=new Map;function i(){let n=performance.now()-t,s=null,o=1/0;for(let[a,c]of e){let{last:l}=c;l<o&&(s=a,o=l),n>l&&e.delete(a)}s&&e.delete(s)}return{get(n){let s=e.get(n);if(s)return s.last=performance.now(),s.value},set(n,s){return e.set(n,{last:performance.now(),value:s}),e.size>r&&Yf(i),s},clear(){e=new Map}}}function _l(r){let t=Array.from({length:r},()=>({head:null,tail:null}));return{isEmpty(){return t.every(e=>!e.head)},insert(e,i){let n=t[i];if(!n)throw new Error(`Invalid queue priority rank: ${i}`);let s={item:e,next:null};n.head===null?n.head=n.tail=s:n.tail=n.tail.next=s},remove(e){for(let i of t){let{head:n,tail:s}=i;for(let o=null,a=n;a;o=a,a=a.next)e(a.item)&&(a===n?n=a.next:o.next=a.next,a===s&&(s=o||n));i.head=n,i.tail=s}},next(){for(let e of t){let{head:i}=e;if(i!==null)return e.head=i.next,e.tail===i&&(e.tail=null),i.item}}}}var _e={High:0,Normal:1,Low:2};function wl(){let r=_l(3),t,e,i,n=[],s=null,o;function a(){if(s||r.isEmpty())return;let{request:h,result:f}=r.next();s=d(h,f),s.finally(()=>{s=null,a()})}function c(h,f=_e.Normal){r.insert(h,f),a()}function l(h){n.length&&h&&n.forEach(f=>f.add(h))}async function d(h,f){try{let{query:g,type:M,cache:we=!1,record:G=!0,options:V}=h,rt=g?`${g}`:null;if(G&&l(rt),we){let an=e.get(rt);if(an){i.debug("Cache"),f.fulfill(an);return}}let Ie=performance.now(),on=await t.query({type:M,sql:rt,...V});we&&e.set(rt,on),i.debug(`Request: ${(performance.now()-Ie).toFixed(1)}`),f.fulfill(on)}catch(g){f.reject(g)}}return{cache(h){return h!==void 0?e=h===!0?bl():h||gl():e},logger(h){return h?i=h:i},connector(h){return h?t=h:t},consolidate(h){h&&!o?o=yl(c,e,l):!h&&o&&(o=null)},request(h,f=_e.Normal){let g=Vs(),M={request:h,result:g};return o?o.add(M,f):c(M,f),g},cancel(h){let f=new Set(h);r.remove(({result:g})=>f.has(g))},clear(){r.remove(({result:h})=>(h.reject("Cleared"),!0))},record(){let h=[],f={add(g){h.push(g)},reset(){h=[]},snapshot(){return h.slice()},stop(){return n=n.filter(g=>g!==f),h}};return n.push(f),f}}}function Il(){return{debug(){},info(){},log(){},warn(){},error(){}}}var js;function ra(r){return r?js=r:js==null&&(js=new zs),js}var zs=class{constructor(t=Wo(),e={}){this.catalog=new Cs(this),this.manager=e.manager||wl(),this.logger(e.logger||console),this.configure(e),this.databaseConnector(t),this.clear()}logger(t){return arguments.length&&(this._logger=t||Il(),this.manager.logger(this._logger)),this._logger}configure({cache:t=!0,consolidate:e=!0,indexes:i=!0}){this.manager.cache(t),this.manager.consolidate(e),this.indexes=i}clear({clients:t=!0,cache:e=!0,catalog:i=!1}={}){this.manager.clear(),t&&(this.clients?.forEach(n=>this.disconnect(n)),this.filterGroups?.forEach(n=>n.finalize()),this.clients=new Set,this.filterGroups=new Map),e&&this.manager.cache().clear(),i&&this.catalog.clear()}databaseConnector(t){return this.manager.connector(t)}cancel(t){this.manager.cancel(t)}exec(t,{priority:e=_e.Normal}={}){return this.manager.request({type:"exec",query:t},e)}query(t,{type:e="arrow",cache:i=!0,priority:n=_e.Normal,...s}={}){return this.manager.request({type:e,query:t,cache:i,options:s},n)}prefetch(t,e={}){return this.query(t,{...e,cache:!0,priority:_e.Low})}createBundle(t,e,i=_e.Low){let n={name:t,queries:e};return this.manager.request({type:"create-bundle",options:n},i)}loadBundle(t,e=_e.High){let i={name:t};return this.manager.request({type:"load-bundle",options:i},e)}updateClient(t,e,i=_e.Normal){return t.queryPending(),this.query(e,{priority:i}).then(n=>t.queryResult(n).update(),n=>{t.queryError(n),this._logger.error(n)})}requestQuery(t,e){return this.filterGroups.get(t.filterBy)?.reset(),e?this.updateClient(t,e):t.update()}async connect(t){let{catalog:e,clients:i,filterGroups:n,indexes:s}=this;if(i.has(t))throw new Error("Client already connected.");i.add(t);let o=t.fields();o?.length&&t.fieldInfo(await e.queryFields(o));let a=t.filterBy;if(a)if(n.has(a))n.get(a).add(t);else{let c=new Ps(this,a,s);n.set(a,c.add(t))}t.requestQuery()}disconnect(t){let{clients:e,filterGroups:i}=this;e.has(t)&&(e.delete(t),i.get(t.filterBy)?.remove(t))}};var vl={};function ia(r,t=!1){let e,i,n=vl;function s(l){e=r(l).then(()=>{if(i){let{value:d}=i;i=null,s(d)}else e=null})}function o(l){i={event:l}}function a(l){e?o(l):s(l)}function c(l){n!==l&&requestAnimationFrame(()=>{let d=n;n=vl,a(d)}),n=l}return t?c:a}var na=class{constructor(t){this._filterBy=t,this._requestUpdate=ia(()=>this.requestQuery(),!0)}get filterBy(){return this._filterBy}get filterIndexable(){return!0}fields(){return null}fieldInfo(){return this}query(){return null}queryPending(){return this}queryResult(){return this}queryError(t){return console.error(t),this}requestQuery(t){let e=t||this.query(this.filterBy?.predicate(this));return ra().requestQuery(this,e)}requestUpdate(){this._requestUpdate()}update(){return this}};var $s=class{constructor(){this._callbacks=new Map}addEventListener(t,e){this._callbacks.has(t)||this._callbacks.set(t,{callbacks:new Set,pending:null,queue:new sa}),this._callbacks.get(t).callbacks.add(e)}removeEventListener(t,e){let i=this._callbacks.get(t);i&&i.callbacks.delete(e)}willEmit(t,e){return e}emitQueueFilter(){return null}cancel(t){this._callbacks.get(t)?.queue.clear()}emit(t,e){let i=this._callbacks.get(t)||{};if(i.pending)i.queue.enqueue(e,this.emitQueueFilter(t,e));else{let n=this.willEmit(t,e),{callbacks:s,queue:o}=i;if(s?.size){let a=Promise.allSettled(Array.from(s,c=>c(n))).then(()=>{i.pending=null,o.isEmpty()||this.emit(t,o.dequeue())});i.pending=a}}}},sa=class{constructor(){this.clear()}clear(){this.next=null}isEmpty(){return!this.next}enqueue(t,e){let i={value:t};if(e&&this.next){let n=this;for(;n.next;)e(n.next.value)?n=n.next:n.next=n.next.next;n.next=i}else this.next=i}dequeue(){let{next:t}=this;return this.next=t?.next,t?.value}};function oa(r,t){return r===t?!1:r instanceof Date&&t instanceof Date?+r!=+t:Array.isArray(r)&&Array.isArray(t)?Hf(r,t):!0}function Hf(r,t){if(r.length!==t.length)return!0;for(let e=0;e<r.length;++e)if(r[e]!==t[e])return!0;return!1}function qs(r){return r instanceof si}var si=class r extends $s{constructor(t){super(),this._value=t}static value(t){return new r(t)}static array(t){if(t.some(e=>qs(e))){let e=new r,i=()=>e.update(t.map(n=>qs(n)?n.value:n));return i(),t.forEach(n=>qs(n)?n.addEventListener("value",i):0),e}return new r(t)}get value(){return this._value}update(t,{force:e}={}){return oa(this._value,t)||e?this.emit("value",t):this.cancel("value"),this}willEmit(t,e){return t==="value"&&(this._value=e),e}};function Kf(r){return r instanceof Gs}var Gs=class r extends si{static intersect({cross:t=!1}={}){return new r(new Fr({cross:t}))}static union({cross:t=!1}={}){return new r(new Fr({cross:t,union:!0}))}static single({cross:t=!1}={}){return new r(new Fr({cross:t,single:!0}))}static crossfilter(){return new r(new Fr({cross:!0}))}constructor(t=new Fr){super([]),this._resolved=this._value,this._resolver=t}clone(){let t=new r(this._resolver);return t._value=t._resolved=this._value,t}remove(t){let e=this.clone();return e._value=e._resolved=e._resolver.resolve(this._resolved,{source:t}),e._value.active={source:t},e}get active(){return this.clauses.active}get value(){return this.active?.value}get clauses(){return super.value}get single(){return this._resolver.single}activate(t){this.emit("activate",t)}update(t){return this._resolved=this._resolver.resolve(this._resolved,t,!0),this._resolved.active=t,super.update(this._resolved)}willEmit(t,e){return t==="value"?(this._value=e,this.value):e}emitQueueFilter(t,e){return t==="value"?this._resolver.queueFilter(e):null}skip(t,e){return this._resolver.skip(t,e)}predicate(t,e=!1){let{clauses:i}=this,n=e?null:i.active;return this._resolver.predicate(i,n,t)}},Fr=class{constructor({union:t,cross:e,single:i}={}){this.union=!!t,this.cross=!!e,this.single=!!i}resolve(t,e,i=!1){let{source:n,predicate:s}=e,o=t.filter(c=>n!==c.source),a=this.single?[]:o;return this.single&&i&&o.forEach(c=>c.source?.reset?.()),s&&a.push(e),a}skip(t,e){return this.cross&&e?.clients?.has(t)}predicate(t,e,i){let{union:n}=this;if(this.skip(i,e))return;let s=t.filter(o=>!this.skip(i,o)).map(o=>o.predicate);return n&&s.length>1?Ko(s):s}queueFilter(t){if(this.cross){let e=t.active?.source;return i=>i.active?.source!==e}}};function Qf(r="http://localhost:3000/"){return{async query(t){let e=fetch(r,{method:"POST",mode:"cors",cache:"no-cache",credentials:"omit",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});return t.type==="exec"?e:t.type==="arrow"?xr(e):(await e).json()}}}var Jf=Object.create,Sl=Object.defineProperty,Xf=Object.getOwnPropertyDescriptor,Zf=Object.getOwnPropertyNames,tp=Object.getPrototypeOf,ep=Object.prototype.hasOwnProperty,rp=(r,t)=>()=>(t||r((t={exports:{}}).exports,t),t.exports),ip=(r,t,e,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Zf(t))!ep.call(r,n)&&n!==e&&Sl(r,n,{get:()=>t[n],enumerable:!(i=Xf(t,n))||i.enumerable});return r},np=(r,t,e)=>(e=r!=null?Jf(tp(r)):{},ip(t||!r||!r.__esModule?Sl(e,"default",{value:r,enumerable:!0}):e,r)),sp=rp((r,t)=>{t.exports=Worker}),op=(r=>(r[r.UNDEFINED=0]="UNDEFINED",r[r.AUTOMATIC=1]="AUTOMATIC",r[r.READ_ONLY=2]="READ_ONLY",r[r.READ_WRITE=3]="READ_WRITE",r))(op||{}),ap=(r=>(r[r.IDENTIFIER=0]="IDENTIFIER",r[r.NUMERIC_CONSTANT=1]="NUMERIC_CONSTANT",r[r.STRING_CONSTANT=2]="STRING_CONSTANT",r[r.OPERATOR=3]="OPERATOR",r[r.KEYWORD=4]="KEYWORD",r[r.COMMENT=5]="COMMENT",r))(ap||{}),cp=(r=>(r[r.NONE=0]="NONE",r[r.DEBUG=1]="DEBUG",r[r.INFO=2]="INFO",r[r.WARNING=3]="WARNING",r[r.ERROR=4]="ERROR",r))(cp||{}),lp=(r=>(r[r.NONE=0]="NONE",r[r.CONNECT=1]="CONNECT",r[r.DISCONNECT=2]="DISCONNECT",r[r.OPEN=3]="OPEN",r[r.QUERY=4]="QUERY",r[r.INSTANTIATE=5]="INSTANTIATE",r))(lp||{}),up=(r=>(r[r.NONE=0]="NONE",r[r.OK=1]="OK",r[r.ERROR=2]="ERROR",r[r.START=3]="START",r[r.RUN=4]="RUN",r[r.CAPTURE=5]="CAPTURE",r))(up||{}),dp=(r=>(r[r.NONE=0]="NONE",r[r.WEB_WORKER=1]="WEB_WORKER",r[r.NODE_WORKER=2]="NODE_WORKER",r[r.BINDINGS=3]="BINDINGS",r[r.ASYNC_DUCKDB=4]="ASYNC_DUCKDB",r))(dp||{}),Tl=class{log(r){}},El=class{constructor(r=2){this.level=r}log(r){r.level>=this.level&&console.log(r)}};var hp=(r=>(r[r.SUCCESS=0]="SUCCESS",r))(hp||{}),fp=class{constructor(r,t){this._bindings=r,this._conn=t}get bindings(){return this._bindings}async close(){return this._bindings.disconnect(this._conn)}useUnsafe(r){return r(this._bindings,this._conn)}async query(r){this._bindings.logger.log({timestamp:new Date,level:2,origin:4,topic:4,event:4,value:r});let t=await this._bindings.runQuery(this._conn,r),e=ot.from(t);return console.assert(e.isSync(),"Reader is not sync"),console.assert(e.isFile(),"Reader is not file"),new lt(e)}async send(r){this._bindings.logger.log({timestamp:new Date,level:2,origin:4,topic:4,event:4,value:r});let t=await this._bindings.startPendingQuery(this._conn,r);for(;t==null;)t=await this._bindings.pollPendingQuery(this._conn);let e=new xl(this._bindings,this._conn,t),i=await ot.from(e);return console.assert(i.isAsync()),console.assert(i.isStream()),i}async cancelSent(){return await this._bindings.cancelPendingQuery(this._conn)}async getTableNames(r){return await this._bindings.getTableNames(this._conn,r)}async prepare(r){let t=await this._bindings.createPrepared(this._conn,r);return new pp(this._bindings,this._conn,t)}async insertArrowTable(r,t){let e=Fs(r,"stream");await this.insertArrowFromIPCStream(e,t)}async insertArrowFromIPCStream(r,t){await this._bindings.insertArrowFromIPCStream(this._conn,r,t)}async insertCSVFromPath(r,t){await this._bindings.insertCSVFromPath(this._conn,r,t)}async insertJSONFromPath(r,t){await this._bindings.insertJSONFromPath(this._conn,r,t)}},xl=class{constructor(r,t,e){this.db=r,this.conn=t,this.header=e,this._first=!0,this._depleted=!1,this._inFlight=null}async next(){if(this._first)return this._first=!1,{done:!1,value:this.header};if(this._depleted)return{done:!0,value:null};let r;return this._inFlight!=null?(r=await this._inFlight,this._inFlight=null):r=await this.db.fetchQueryResults(this.conn),this._depleted=r.length==0,this._depleted||(this._inFlight=this.db.fetchQueryResults(this.conn)),{done:this._depleted,value:r}}[Symbol.asyncIterator](){return this}},pp=class{constructor(r,t,e){this.bindings=r,this.connectionId=t,this.statementId=e}async close(){await this.bindings.closePrepared(this.connectionId,this.statementId)}async query(...r){let t=await this.bindings.runPrepared(this.connectionId,this.statementId,r),e=ot.from(t);return console.assert(e.isSync()),console.assert(e.isFile()),new lt(e)}async send(...r){let t=await this.bindings.sendPrepared(this.connectionId,this.statementId,r),e=new xl(this.bindings,this.connectionId,t),i=await ot.from(e);return console.assert(i.isAsync()),console.assert(i.isStream()),i}},mp=(r=>(r.CANCEL_PENDING_QUERY="CANCEL_PENDING_QUERY",r.CLOSE_PREPARED="CLOSE_PREPARED",r.COLLECT_FILE_STATISTICS="COLLECT_FILE_STATISTICS",r.CONNECT="CONNECT",r.COPY_FILE_TO_BUFFER="COPY_FILE_TO_BUFFER",r.COPY_FILE_TO_PATH="COPY_FILE_TO_PATH",r.CREATE_PREPARED="CREATE_PREPARED",r.DISCONNECT="DISCONNECT",r.DROP_FILE="DROP_FILE",r.DROP_FILES="DROP_FILES",r.EXPORT_FILE_STATISTICS="EXPORT_FILE_STATISTICS",r.FETCH_QUERY_RESULTS="FETCH_QUERY_RESULTS",r.FLUSH_FILES="FLUSH_FILES",r.GET_FEATURE_FLAGS="GET_FEATURE_FLAGS",r.GET_TABLE_NAMES="GET_TABLE_NAMES",r.GET_VERSION="GET_VERSION",r.GLOB_FILE_INFOS="GLOB_FILE_INFOS",r.INSERT_ARROW_FROM_IPC_STREAM="INSERT_ARROW_FROM_IPC_STREAM",r.INSERT_CSV_FROM_PATH="IMPORT_CSV_FROM_PATH",r.INSERT_JSON_FROM_PATH="IMPORT_JSON_FROM_PATH",r.INSTANTIATE="INSTANTIATE",r.OPEN="OPEN",r.PING="PING",r.POLL_PENDING_QUERY="POLL_PENDING_QUERY",r.REGISTER_FILE_BUFFER="REGISTER_FILE_BUFFER",r.REGISTER_FILE_HANDLE="REGISTER_FILE_HANDLE",r.REGISTER_FILE_URL="REGISTER_FILE_URL",r.RESET="RESET",r.RUN_PREPARED="RUN_PREPARED",r.RUN_QUERY="RUN_QUERY",r.SEND_PREPARED="SEND_PREPARED",r.START_PENDING_QUERY="START_PENDING_QUERY",r.TOKENIZE="TOKENIZE",r))(mp||{}),yp=(r=>(r.CONNECTION_INFO="CONNECTION_INFO",r.ERROR="ERROR",r.FEATURE_FLAGS="FEATURE_FLAGS",r.FILE_BUFFER="FILE_BUFFER",r.FILE_INFOS="FILE_INFOS",r.FILE_SIZE="FILE_SIZE",r.FILE_STATISTICS="FILE_STATISTICS",r.INSTANTIATE_PROGRESS="INSTANTIATE_PROGRESS",r.LOG="LOG",r.OK="OK",r.PREPARED_STATEMENT_ID="PREPARED_STATEMENT_ID",r.QUERY_PLAN="QUERY_PLAN",r.QUERY_RESULT="QUERY_RESULT",r.QUERY_RESULT_CHUNK="QUERY_RESULT_CHUNK",r.QUERY_RESULT_HEADER="QUERY_RESULT_HEADER",r.QUERY_RESULT_HEADER_OR_NULL="QUERY_RESULT_HEADER_OR_NULL",r.REGISTERED_FILE="REGISTERED_FILE",r.SCRIPT_TOKENS="SCRIPT_TOKENS",r.SUCCESS="SUCCESS",r.TABLE_NAMES="TABLE_NAMES",r.VERSION_STRING="VERSION_STRING",r))(yp||{}),P=class{constructor(r,t){this.promiseResolver=()=>{},this.promiseRejecter=()=>{},this.type=r,this.data=t,this.promise=new Promise((e,i)=>{this.promiseResolver=e,this.promiseRejecter=i})}};function Ws(r){switch(r.typeId){case u.Binary:return{sqlType:"binary"};case u.Bool:return{sqlType:"bool"};case u.Date:return{sqlType:"date"};case u.DateDay:return{sqlType:"date32[d]"};case u.DateMillisecond:return{sqlType:"date64[ms]"};case u.Decimal:{let t=r;return{sqlType:"decimal",precision:t.precision,scale:t.scale}}case u.Float:return{sqlType:"float"};case u.Float16:return{sqlType:"float16"};case u.Float32:return{sqlType:"float32"};case u.Float64:return{sqlType:"float64"};case u.Int:return{sqlType:"int32"};case u.Int16:return{sqlType:"int16"};case u.Int32:return{sqlType:"int32"};case u.Int64:return{sqlType:"int64"};case u.Uint16:return{sqlType:"uint16"};case u.Uint32:return{sqlType:"uint32"};case u.Uint64:return{sqlType:"uint64"};case u.Uint8:return{sqlType:"uint8"};case u.IntervalDayTime:return{sqlType:"interval[dt]"};case u.IntervalYearMonth:return{sqlType:"interval[m]"};case u.List:return{sqlType:"list",valueType:Ws(r.valueType)};case u.FixedSizeBinary:return{sqlType:"fixedsizebinary",byteWidth:r.byteWidth};case u.Null:return{sqlType:"null"};case u.Utf8:return{sqlType:"utf8"};case u.Struct:return{sqlType:"struct",fields:r.children.map(t=>ha(t.name,t.type))};case u.Map:{let t=r;return{sqlType:"map",keyType:Ws(t.keyType),valueType:Ws(t.valueType)}}case u.Time:return{sqlType:"time[s]"};case u.TimeMicrosecond:return{sqlType:"time[us]"};case u.TimeMillisecond:return{sqlType:"time[ms]"};case u.TimeNanosecond:return{sqlType:"time[ns]"};case u.TimeSecond:return{sqlType:"time[s]"};case u.Timestamp:return{sqlType:"timestamp",timezone:r.timezone||void 0};case u.TimestampSecond:return{sqlType:"timestamp[s]",timezone:r.timezone||void 0};case u.TimestampMicrosecond:return{sqlType:"timestamp[us]",timezone:r.timezone||void 0};case u.TimestampNanosecond:return{sqlType:"timestamp[ns]",timezone:r.timezone||void 0};case u.TimestampMillisecond:return{sqlType:"timestamp[ms]",timezone:r.timezone||void 0}}throw new Error("unsupported arrow type: ".concat(r.toString()))}function ha(r,t){let e=Ws(t);return e.name=r,e}var gp=new TextEncoder,Al=class{constructor(r,t=null){this._onInstantiationProgress=[],this._worker=null,this._workerShutdownPromise=null,this._workerShutdownResolver=()=>{},this._nextMessageId=0,this._pendingRequests=new Map,this._logger=r,this._onMessageHandler=this.onMessage.bind(this),this._onErrorHandler=this.onError.bind(this),this._onCloseHandler=this.onClose.bind(this),t!=null&&this.attach(t)}get logger(){return this._logger}attach(r){this._worker=r,this._worker.addEventListener("message",this._onMessageHandler),this._worker.addEventListener("error",this._onErrorHandler),this._worker.addEventListener("close",this._onCloseHandler),this._workerShutdownPromise=new Promise((t,e)=>{this._workerShutdownResolver=t})}detach(){this._worker&&(this._worker.removeEventListener("message",this._onMessageHandler),this._worker.removeEventListener("error",this._onErrorHandler),this._worker.removeEventListener("close",this._onCloseHandler),this._worker=null,this._workerShutdownResolver(null),this._workerShutdownPromise=null,this._workerShutdownResolver=()=>{})}async terminate(){this._worker&&(this._worker.terminate(),this._worker=null,this._workerShutdownPromise=null,this._workerShutdownResolver=()=>{})}async postTask(r,t=[]){if(!this._worker){console.error("cannot send a message since the worker is not set!");return}let e=this._nextMessageId++;return this._pendingRequests.set(e,r),this._worker.postMessage({messageId:e,type:r.type,data:r.data},t),await r.promise}onMessage(r){var t;let e=r.data;switch(e.type){case"LOG":{this._logger.log(e.data);return}case"INSTANTIATE_PROGRESS":{for(let n of this._onInstantiationProgress)n(e.data);return}}let i=this._pendingRequests.get(e.requestId);if(!i){console.warn("unassociated response: [".concat(e.requestId,", ").concat(e.type.toString(),"]"));return}if(this._pendingRequests.delete(e.requestId),e.type=="ERROR"){let n=new Error(e.data.message);n.name=e.data.name,(t=Object.getOwnPropertyDescriptor(n,"stack"))!=null&&t.writable&&(n.stack=e.data.stack),i.promiseRejecter(n);return}switch(i.type){case"CLOSE_PREPARED":case"COLLECT_FILE_STATISTICS":case"COPY_FILE_TO_PATH":case"DISCONNECT":case"DROP_FILE":case"DROP_FILES":case"FLUSH_FILES":case"INSERT_ARROW_FROM_IPC_STREAM":case"IMPORT_CSV_FROM_PATH":case"IMPORT_JSON_FROM_PATH":case"OPEN":case"PING":case"REGISTER_FILE_BUFFER":case"REGISTER_FILE_HANDLE":case"REGISTER_FILE_URL":case"RESET":if(e.type=="OK"){i.promiseResolver(e.data);return}break;case"INSTANTIATE":if(this._onInstantiationProgress=[],e.type=="OK"){i.promiseResolver(e.data);return}break;case"GLOB_FILE_INFOS":if(e.type=="FILE_INFOS"){i.promiseResolver(e.data);return}break;case"GET_VERSION":if(e.type=="VERSION_STRING"){i.promiseResolver(e.data);return}break;case"GET_FEATURE_FLAGS":if(e.type=="FEATURE_FLAGS"){i.promiseResolver(e.data);return}break;case"GET_TABLE_NAMES":if(e.type=="TABLE_NAMES"){i.promiseResolver(e.data);return}break;case"TOKENIZE":if(e.type=="SCRIPT_TOKENS"){i.promiseResolver(e.data);return}break;case"COPY_FILE_TO_BUFFER":if(e.type=="FILE_BUFFER"){i.promiseResolver(e.data);return}break;case"EXPORT_FILE_STATISTICS":if(e.type=="FILE_STATISTICS"){i.promiseResolver(e.data);return}break;case"CONNECT":if(e.type=="CONNECTION_INFO"){i.promiseResolver(e.data);return}break;case"RUN_PREPARED":case"RUN_QUERY":if(e.type=="QUERY_RESULT"){i.promiseResolver(e.data);return}break;case"SEND_PREPARED":if(e.type=="QUERY_RESULT_HEADER"){i.promiseResolver(e.data);return}break;case"START_PENDING_QUERY":if(e.type=="QUERY_RESULT_HEADER_OR_NULL"){i.promiseResolver(e.data);return}break;case"POLL_PENDING_QUERY":if(e.type=="QUERY_RESULT_HEADER_OR_NULL"){i.promiseResolver(e.data);return}break;case"CANCEL_PENDING_QUERY":if(this._onInstantiationProgress=[],e.type=="SUCCESS"){i.promiseResolver(e.data);return}break;case"FETCH_QUERY_RESULTS":if(e.type=="QUERY_RESULT_CHUNK"){i.promiseResolver(e.data);return}break;case"CREATE_PREPARED":if(e.type=="PREPARED_STATEMENT_ID"){i.promiseResolver(e.data);return}break}i.promiseRejecter(new Error("unexpected response type: ".concat(e.type.toString())))}onError(r){console.error(r),console.error("error in duckdb worker: ".concat(r.message)),this._pendingRequests.clear()}onClose(){if(this._workerShutdownResolver(null),this._pendingRequests.size!=0){console.warn("worker terminated with ".concat(this._pendingRequests.size," pending requests"));return}this._pendingRequests.clear()}async reset(){let r=new P("RESET",null);return await this.postTask(r)}async ping(){let r=new P("PING",null);await this.postTask(r)}async dropFile(r){let t=new P("DROP_FILE",r);return await this.postTask(t)}async dropFiles(){let r=new P("DROP_FILES",null);return await this.postTask(r)}async flushFiles(){let r=new P("FLUSH_FILES",null);return await this.postTask(r)}async instantiate(r,t=null,e=i=>{}){this._onInstantiationProgress.push(e);let i=new P("INSTANTIATE",[r,t]);return await this.postTask(i)}async getVersion(){let r=new P("GET_VERSION",null);return await this.postTask(r)}async getFeatureFlags(){let r=new P("GET_FEATURE_FLAGS",null);return await this.postTask(r)}async open(r){let t=new P("OPEN",r);await this.postTask(t)}async tokenize(r){let t=new P("TOKENIZE",r);return await this.postTask(t)}async connectInternal(){let r=new P("CONNECT",null);return await this.postTask(r)}async connect(){let r=await this.connectInternal();return new fp(this,r)}async disconnect(r){let t=new P("DISCONNECT",r);await this.postTask(t)}async runQuery(r,t){let e=new P("RUN_QUERY",[r,t]);return await this.postTask(e)}async startPendingQuery(r,t){let e=new P("START_PENDING_QUERY",[r,t]);return await this.postTask(e)}async pollPendingQuery(r){let t=new P("POLL_PENDING_QUERY",r);return await this.postTask(t)}async cancelPendingQuery(r){let t=new P("CANCEL_PENDING_QUERY",r);return await this.postTask(t)}async fetchQueryResults(r){let t=new P("FETCH_QUERY_RESULTS",r);return await this.postTask(t)}async getTableNames(r,t){let e=new P("GET_TABLE_NAMES",[r,t]);return await this.postTask(e)}async createPrepared(r,t){let e=new P("CREATE_PREPARED",[r,t]);return await this.postTask(e)}async closePrepared(r,t){let e=new P("CLOSE_PREPARED",[r,t]);await this.postTask(e)}async runPrepared(r,t,e){let i=new P("RUN_PREPARED",[r,t,e]);return await this.postTask(i)}async sendPrepared(r,t,e){let i=new P("SEND_PREPARED",[r,t,e]);return await this.postTask(i)}async globFiles(r){let t=new P("GLOB_FILE_INFOS",r);return await this.postTask(t)}async registerFileText(r,t){let e=gp.encode(t);await this.registerFileBuffer(r,e)}async registerFileURL(r,t,e,i){t===void 0&&(t=r);let n=new P("REGISTER_FILE_URL",[r,t,e,i]);await this.postTask(n)}async registerEmptyFileBuffer(r){let t=new P("REGISTER_FILE_BUFFER",[r,new Uint8Array]);await this.postTask(t)}async registerFileBuffer(r,t){let e=new P("REGISTER_FILE_BUFFER",[r,t]);await this.postTask(e,[t.buffer])}async registerFileHandle(r,t,e,i){let n=new P("REGISTER_FILE_HANDLE",[r,t,e,i]);await this.postTask(n,[])}async collectFileStatistics(r,t){let e=new P("COLLECT_FILE_STATISTICS",[r,t]);await this.postTask(e,[])}async exportFileStatistics(r){let t=new P("EXPORT_FILE_STATISTICS",r);return await this.postTask(t,[])}async copyFileToBuffer(r){let t=new P("COPY_FILE_TO_BUFFER",r);return await this.postTask(t)}async copyFileToPath(r,t){let e=new P("COPY_FILE_TO_PATH",[r,t]);await this.postTask(e)}async insertArrowFromIPCStream(r,t,e){if(t.length==0)return;let i=new P("INSERT_ARROW_FROM_IPC_STREAM",[r,t,e]);await this.postTask(i,[t.buffer])}async insertCSVFromPath(r,t,e){if(e.columns!==void 0){let n=[];for(let s in e.columns){let o=e.columns[s];n.push(ha(s,o))}e.columnsFlat=n,delete e.columns}let i=new P("IMPORT_CSV_FROM_PATH",[r,t,e]);await this.postTask(i)}async insertJSONFromPath(r,t,e){if(e.columns!==void 0){let n=[];for(let s in e.columns){let o=e.columns[s];n.push(ha(s,o))}e.columnsFlat=n,delete e.columns}let i=new P("IMPORT_JSON_FROM_PATH",[r,t,e]);await this.postTask(i)}};var bp=async()=>WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,3,1,0,1,10,14,1,12,0,65,0,65,0,65,0,252,10,0,0,11])),_p=async()=>WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,8,1,6,0,6,64,25,11,11])),wp=async()=>WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,10,1,8,0,65,0,253,15,253,98,11])),Ip=()=>(async r=>{try{return typeof MessageChannel<"u"&&new MessageChannel().port1.postMessage(new SharedArrayBuffer(1)),WebAssembly.validate(r)}catch{return!1}})(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11])),fa={name:"@duckdb/duckdb-wasm",version:"1.28.0",description:"DuckDB powered by WebAssembly",license:"MIT",repository:{type:"git",url:"https://github.com/duckdb/duckdb-wasm.git"},keywords:["sql","duckdb","relational","database","data","query","wasm","analytics","olap","arrow","parquet","json","csv"],dependencies:{"apache-arrow":"^13.0.0"},devDependencies:{"@types/emscripten":"^1.39.8","@types/jasmine":"^4.3.1","@typescript-eslint/eslint-plugin":"^6.5.0","@typescript-eslint/parser":"^6.7.3",esbuild:"^0.19.5",eslint:"^8.50.0","eslint-plugin-jasmine":"^4.1.3","eslint-plugin-react":"^7.33.2","fast-glob":"^3.3.1",jasmine:"^5.1.0","jasmine-core":"^5.1.1","jasmine-spec-reporter":"^7.0.0","js-sha256":"^0.9.0",karma:"^6.4.2","karma-chrome-launcher":"^3.2.0","karma-coverage":"^2.2.1","karma-firefox-launcher":"^2.1.2","karma-jasmine":"^5.1.0","karma-jasmine-html-reporter":"^2.1.0","karma-sourcemap-loader":"^0.4.0","karma-spec-reporter":"^0.0.36","make-dir":"^4.0.0",nyc:"^15.1.0",prettier:"^3.0.2",puppeteer:"^21.1.1",rimraf:"^5.0.5",s3rver:"^3.7.1",typedoc:"^0.25.2",typescript:"^5.2.2","wasm-feature-detect":"^1.5.1","web-worker":"^1.2.0"},scripts:{"build:debug":"node bundle.mjs debug && tsc --emitDeclarationOnly","build:release":"node bundle.mjs release && tsc --emitDeclarationOnly",docs:"typedoc",report:"node ./coverage.mjs","test:node":"node --enable-source-maps ../../node_modules/jasmine/bin/jasmine ./dist/tests-node.cjs","test:node:debug":"node --inspect-brk --enable-source-maps ../../node_modules/jasmine/bin/jasmine ./dist/tests-node.cjs","test:node:coverage":"nyc -r json --report-dir ./coverage/node node ../../node_modules/jasmine/bin/jasmine ./dist/tests-node.cjs","test:firefox":"karma start ./karma/tests-firefox.cjs","test:chrome":"karma start ./karma/tests-chrome.cjs","test:chrome:eh":"karma start ./karma/tests-chrome-eh.cjs","test:chrome:coverage":"karma start ./karma/tests-chrome-coverage.cjs","test:browser":"karma start ./karma/tests-all.cjs","test:browser:debug":"karma start ./karma/tests-debug.cjs",test:"npm run test:chrome && npm run test:node","test:coverage":"npm run test:chrome:coverage && npm run test:node:coverage && npm run report",lint:"eslint src test"},files:["dist","!dist/types/test"],main:"dist/duckdb-browser.cjs",module:"dist/duckdb-browser.mjs",types:"dist/duckdb-browser.d.ts",jsdelivr:"dist/duckdb-browser.cjs",unpkg:"dist/duckdb-browser.mjs",sideEffects:!1,browser:{fs:!1,path:!1,perf_hooks:!1,os:!1,worker_threads:!1},exports:{"./dist/duckdb-mvp.wasm":"./dist/duckdb-mvp.wasm","./dist/duckdb-eh.wasm":"./dist/duckdb-eh.wasm","./dist/duckdb-coi.wasm":"./dist/duckdb-coi.wasm","./dist/duckdb-browser":"./dist/duckdb-browser.mjs","./dist/duckdb-browser.cjs":"./dist/duckdb-browser.cjs","./dist/duckdb-browser.mjs":"./dist/duckdb-browser.mjs","./dist/duckdb-browser-blocking":"./dist/duckdb-browser-blocking.mjs","./dist/duckdb-browser-blocking.mjs":"./dist/duckdb-browser-blocking.mjs","./dist/duckdb-browser-blocking.cjs":"./dist/duckdb-browser-blocking.cjs","./dist/duckdb-browser-coi.pthread.worker.js":"./dist/duckdb-browser-coi.pthread.worker.js","./dist/duckdb-browser-coi.worker.js":"./dist/duckdb-browser-coi.worker.js","./dist/duckdb-browser-eh.worker.js":"./dist/duckdb-browser-eh.worker.js","./dist/duckdb-browser-mvp.worker.js":"./dist/duckdb-browser-mvp.worker.js","./dist/duckdb-node":"./dist/duckdb-node.cjs","./dist/duckdb-node.cjs":"./dist/duckdb-node.cjs","./dist/duckdb-node-blocking":"./dist/duckdb-node-blocking.cjs","./dist/duckdb-node-blocking.cjs":"./dist/duckdb-node-blocking.cjs","./dist/duckdb-node-eh.worker.cjs":"./dist/duckdb-node-eh.worker.cjs","./dist/duckdb-node-mvp.worker.cjs":"./dist/duckdb-node-mvp.worker.cjs","./blocking":{browser:{types:"./dist/duckdb-browser-blocking.d.ts",import:"./dist/duckdb-browser-blocking.mjs",require:"./dist/duckdb-browser-blocking.cjs"},node:{types:"./dist/duckdb-node-blocking.d.ts",require:"./dist/duckdb-node-blocking.cjs",import:"./dist/duckdb-node-blocking.cjs"},types:"./dist/duckdb-browser-blocking.d.ts",import:"./dist/duckdb-browser-blocking.mjs",require:"./dist/duckdb-browser-blocking.cjs"},".":{browser:{types:"./dist/duckdb-browser.d.ts",import:"./dist/duckdb-browser.mjs",require:"./dist/duckdb-browser.cjs"},node:{types:"./dist/duckdb-node.d.ts",import:"./dist/duckdb-node.cjs",require:"./dist/duckdb-node.cjs"},types:"./dist/duckdb-browser.d.ts",import:"./dist/duckdb-browser.mjs",require:"./dist/duckdb-browser.cjs"}}},vp=fa.name,Sp=fa.version,pa=fa.version.split("."),$T=pa[0],qT=pa[1],GT=pa[2],Tp=()=>typeof navigator>"u";function Ol(){let r="https://cdn.jsdelivr.net/npm/".concat(vp,"@").concat(Sp,"/dist/");return{mvp:{mainModule:"".concat(r,"duckdb-mvp.wasm"),mainWorker:"".concat(r,"duckdb-browser-mvp.worker.js")},eh:{mainModule:"".concat(r,"duckdb-eh.wasm"),mainWorker:"".concat(r,"duckdb-browser-eh.worker.js")}}}var aa=null,ca=null,la=null,ua=null,da=null;async function Ep(){return aa==null&&(aa=typeof BigInt64Array<"u"),ca==null&&(ca=await _p()),la==null&&(la=await Ip()),ua==null&&(ua=await wp()),da==null&&(da=await bp()),{bigInt64Array:aa,crossOriginIsolated:Tp()||globalThis.crossOriginIsolated||!1,wasmExceptions:ca,wasmSIMD:ua,wasmThreads:la,wasmBulkMemory:da}}async function Bl(r){let t=await Ep();if(t.wasmExceptions){if(t.wasmSIMD&&t.wasmThreads&&t.crossOriginIsolated&&r.coi)return{mainModule:r.coi.mainModule,mainWorker:r.coi.mainWorker,pthreadWorker:r.coi.pthreadWorker};if(r.eh)return{mainModule:r.eh.mainModule,mainWorker:r.eh.mainWorker,pthreadWorker:null}}return{mainModule:r.mvp.mainModule,mainWorker:r.mvp.mainWorker,pthreadWorker:null}}var WT=np(sp());function xp(){let r=new TextDecoder;return t=>(typeof SharedArrayBuffer<"u"&&t.buffer instanceof SharedArrayBuffer&&(t=new Uint8Array(t)),r.decode(t))}var YT=xp(),Ap=(r=>(r[r.BUFFER=0]="BUFFER",r[r.NODE_FS=1]="NODE_FS",r[r.BROWSER_FILEREADER=2]="BROWSER_FILEREADER",r[r.BROWSER_FSACCESS=3]="BROWSER_FSACCESS",r[r.HTTP=4]="HTTP",r[r.S3=5]="S3",r))(Ap||{});async function Bp(r){let t=await Np(r),e=await t.connect();return{db:t,con:e,query:async i=>{let{type:n,sql:s}=i,o=await e.query(s);return n==="exec"?void 0:n==="arrow"?o:Array.from(o)}}}async function Np({log:r=!1}={}){let t=Ol(),e=await Bl(t),i=URL.createObjectURL(new Blob([`importScripts("${e.mainWorker}");`],{type:"text/javascript"})),n=new Worker(i),s=r?new El:new Tl,o=new Al(s,n);return await o.instantiate(e.mainModule,e.pthreadWorker),URL.revokeObjectURL(i),o}function Fp(){let r=new Set,t,e=new Promise(i=>t=i);return{pending(i){r.add(i)},ready(i){return r.delete(i),r.size===0},resolve(){e=new Promise(i=>{t(),t=i})},get promise(){return e}}}export{zs as Coordinator,na as MosaicClient,si as Param,_e as Priority,Gs as Selection,ra as coordinator,oa as distinct,qs as isParam,Kf as isSelection,Qf as restConnector,Wo as socketConnector,Fp as synchronizer,ia as throttle,Bp as wasmConnector};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@uwdata/mosaic-core",
3
- "version": "0.3.5",
3
+ "version": "0.4.0",
4
4
  "description": "Scalable and extensible linked data views.",
5
5
  "keywords": [
6
6
  "mosaic",
@@ -29,8 +29,8 @@
29
29
  },
30
30
  "dependencies": {
31
31
  "@duckdb/duckdb-wasm": "^1.28.0",
32
- "@uwdata/mosaic-sql": "^0.3.5",
32
+ "@uwdata/mosaic-sql": "^0.4.0",
33
33
  "apache-arrow": "^13.0.0"
34
34
  },
35
- "gitHead": "7cc66d26c687a28036b3c7102045f2196572847b"
35
+ "gitHead": "4114465543a21b25d6d14647db7d95af875d2519"
36
36
  }
@@ -211,7 +211,7 @@ function getIndexColumns(client) {
211
211
  let count;
212
212
 
213
213
  for (const { as, expr: { aggregate } } of q.select()) {
214
- switch (aggregate?.toUpperCase()) {
214
+ switch (aggregate?.toUpperCase?.()) {
215
215
  case 'COUNT':
216
216
  case 'SUM':
217
217
  aggr.push({ [as]: sql`SUM("${as}")::DOUBLE` });
@@ -19,6 +19,7 @@ export function jsType(type) {
19
19
  case 'TIMESTAMPTZ':
20
20
  case 'TIMESTAMP WITH TIME ZONE':
21
21
  case 'TIME':
22
+ case 'TIMESTAMP_NS':
22
23
  return 'date';
23
24
  case 'BOOLEAN':
24
25
  return 'boolean';