Big News: Socket raises $60M Series C at a $1B valuation to secure software supply chains for AI-driven development.Announcement →
Sign In

@clockworklabs/spacetimedb-sdk

Package Overview
Dependencies
Maintainers
4
Versions
44
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@clockworklabs/spacetimedb-sdk - npm Package Compare versions

Comparing version
1.2.0
to
1.2.1
+1
-1
dist/min/index.js

@@ -1,1 +0,1 @@

var e=class{#e;#t=0;constructor(e){this.#e=new DataView(e.buffer),this.#t=e.byteOffset}get offset(){return this.#t}readUInt8Array(){const e=this.readU32(),t=new Uint8Array(this.#e.buffer,this.#t,e);return this.#t+=e,t}readBool(){const e=this.#e.getUint8(this.#t);return this.#t+=1,0!==e}readByte(){const e=this.#e.getUint8(this.#t);return this.#t+=1,e}readBytes(e){const t=new DataView(this.#e.buffer,this.#t,e);return this.#t+=e,new Uint8Array(t.buffer)}readI8(){const e=this.#e.getInt8(this.#t);return this.#t+=1,e}readU8(){const e=this.#e.getUint8(this.#t);return this.#t+=1,e}readI16(){const e=this.#e.getInt16(this.#t,!0);return this.#t+=2,e}readU16(){const e=this.#e.getUint16(this.#t,!0);return this.#t+=2,e}readI32(){const e=this.#e.getInt32(this.#t,!0);return this.#t+=4,e}readU32(){const e=this.#e.getUint32(this.#t,!0);return this.#t+=4,e}readI64(){const e=this.#e.getBigInt64(this.#t,!0);return this.#t+=8,e}readU64(){const e=this.#e.getBigUint64(this.#t,!0);return this.#t+=8,e}readU128(){const e=this.#e.getBigUint64(this.#t,!0),t=this.#e.getBigUint64(this.#t+8,!0);return this.#t+=16,(t<<BigInt(64))+e}readI128(){const e=this.#e.getBigUint64(this.#t,!0),t=this.#e.getBigInt64(this.#t+8,!0);return this.#t+=16,(t<<BigInt(64))+e}readU256(){const e=this.#e.getBigUint64(this.#t,!0),t=this.#e.getBigUint64(this.#t+8,!0),r=this.#e.getBigUint64(this.#t+16,!0),i=this.#e.getBigUint64(this.#t+24,!0);return this.#t+=32,(i<<BigInt(192))+(r<<BigInt(128))+(t<<BigInt(64))+e}readI256(){const e=this.#e.getBigUint64(this.#t,!0),t=this.#e.getBigUint64(this.#t+8,!0),r=this.#e.getBigUint64(this.#t+16,!0),i=this.#e.getBigInt64(this.#t+24,!0);return this.#t+=32,(i<<BigInt(192))+(r<<BigInt(128))+(t<<BigInt(64))+e}readF32(){const e=this.#e.getFloat32(this.#t,!0);return this.#t+=4,e}readF64(){const e=this.#e.getFloat64(this.#t,!0);return this.#t+=8,e}readString(){const e=this.readU32(),t=new Uint8Array(this.#e.buffer,this.#t,e),r=new TextDecoder("utf-8").decode(t);return this.#t+=e,r}},t=class{#e;#r;#t=0;constructor(e){this.#e=new Uint8Array(e),this.#r=new DataView(this.#e.buffer)}#i(e){const t=this.#t+e+1;if(t<=this.#e.length)return;let r=2*this.#e.length;r<t&&(r=t);const i=new Uint8Array(r);i.set(this.#e),this.#e=i,this.#r=new DataView(this.#e.buffer)}getBuffer(){return this.#e.slice(0,this.#t)}writeUInt8Array(e){const t=e.length;this.#i(4+t),this.writeU32(t),this.#e.set(e,this.#t),this.#t+=e.length}writeBool(e){this.#i(1),this.#r.setUint8(this.#t,e?1:0),this.#t+=1}writeByte(e){this.#i(1),this.#r.setUint8(this.#t,e),this.#t+=1}writeI8(e){this.#i(1),this.#r.setInt8(this.#t,e),this.#t+=1}writeU8(e){this.#i(1),this.#r.setUint8(this.#t,e),this.#t+=1}writeI16(e){this.#i(2),this.#r.setInt16(this.#t,e,!0),this.#t+=2}writeU16(e){this.#i(2),this.#r.setUint16(this.#t,e,!0),this.#t+=2}writeI32(e){this.#i(4),this.#r.setInt32(this.#t,e,!0),this.#t+=4}writeU32(e){this.#i(4),this.#r.setUint32(this.#t,e,!0),this.#t+=4}writeI64(e){this.#i(8),this.#r.setBigInt64(this.#t,e,!0),this.#t+=8}writeU64(e){this.#i(8),this.#r.setBigUint64(this.#t,e,!0),this.#t+=8}writeU128(e){this.#i(16);const t=e&BigInt("0xFFFFFFFFFFFFFFFF"),r=e>>BigInt(64);this.#r.setBigUint64(this.#t,t,!0),this.#r.setBigUint64(this.#t+8,r,!0),this.#t+=16}writeI128(e){this.#i(16);const t=e&BigInt("0xFFFFFFFFFFFFFFFF"),r=e>>BigInt(64);this.#r.setBigInt64(this.#t,t,!0),this.#r.setBigInt64(this.#t+8,r,!0),this.#t+=16}writeU256(e){this.#i(32);const t=BigInt("0xFFFFFFFFFFFFFFFF"),r=e&t,i=e>>BigInt(64)&t,s=e>>BigInt(128)&t,n=e>>BigInt(192);this.#r.setBigUint64(this.#t+0,r,!0),this.#r.setBigUint64(this.#t+8,i,!0),this.#r.setBigUint64(this.#t+16,s,!0),this.#r.setBigUint64(this.#t+24,n,!0),this.#t+=32}writeI256(e){this.#i(32);const t=BigInt("0xFFFFFFFFFFFFFFFF"),r=e&t,i=e>>BigInt(64)&t,s=e>>BigInt(128)&t,n=e>>BigInt(192);this.#r.setBigUint64(this.#t+0,r,!0),this.#r.setBigUint64(this.#t+8,i,!0),this.#r.setBigUint64(this.#t+16,s,!0),this.#r.setBigInt64(this.#t+24,n,!0),this.#t+=32}writeF32(e){this.#i(4),this.#r.setFloat32(this.#t,e,!0),this.#t+=4}writeF64(e){this.#i(8),this.#r.setFloat64(this.#t,e,!0),this.#t+=8}writeString(e){const t=(new TextEncoder).encode(e);this.writeU32(t.length),this.#i(t.length),this.#e.set(t,this.#t),this.#t+=t.length}};function r(e,t){if(e===t)return!0;if("object"!=typeof e||null===e||"object"!=typeof t||null===t)return!1;const i=Object.keys(e),s=Object.keys(t);if(i.length!==s.length)return!1;for(let n of i)if(!s.includes(n)||!r(e[n],t[n]))return!1;return!0}function i(e){return Array.prototype.map.call(e.reverse(),(e=>("00"+e.toString(16)).slice(-2))).join("")}function s(e){e.startsWith("0x")&&(e=e.slice(2));let t=e.match(/.{1,2}/g)||[],r=Uint8Array.from(t.map((e=>parseInt(e,16))));return 32!=r.length?new Uint8Array(0):r.reverse()}function n(t){return function(t){if(16!=t.length)throw new Error(`Uint8Array is not 16 bytes long: ${t}`);return new e(t).readU128()}(s(t))}function a(t){return function(t){if(32!=t.length)throw new Error(`Uint8Array is not 32 bytes long: [${t}]`);return new e(t).readU256()}(s(t))}function c(e){let r=new t(16);return r.writeU128(e),r.getBuffer()}function o(e){let r=new t(32);return r.writeU256(e),r.getBuffer()}var p,u,l=class e{data;get __connection_id__(){return this.data}constructor(e){this.data=e}isZero(){return this.data===BigInt(0)}static nullIfZero(e){return e.isZero()?null:e}static random(){let t=BigInt(0);for(let e=0;e<16;e++)t=t<<BigInt(8)|BigInt(Math.floor(255*Math.random()));return new e(t)}isEqual(e){return this.data==e.data}toHexString(){return i(c(this.data))}toUint8Array(){return c(this.data)}static fromString(t){return new e(n(t))}static fromStringOrNull(t){let r=e.fromString(t);return r.isZero()?null:r}},y=class e{__time_duration_micros__;static MICROS_PER_MILLIS=1000n;get micros(){return this.__time_duration_micros__}get millis(){return Number(this.micros/e.MICROS_PER_MILLIS)}constructor(e){this.__time_duration_micros__=e}static fromMillis(t){return new e(BigInt(t)*e.MICROS_PER_MILLIS)}},d=class e{__timestamp_micros_since_unix_epoch__;static MICROS_PER_MILLIS=1000n;get microsSinceUnixEpoch(){return this.__timestamp_micros_since_unix_epoch__}constructor(e){this.__timestamp_micros_since_unix_epoch__=e}static UNIX_EPOCH=new e(0n);static now(){return e.fromDate(new Date)}static fromDate(t){const r=t.getTime(),i=BigInt(r)*e.MICROS_PER_MILLIS;return new e(i)}toDate(){const t=this.__timestamp_micros_since_unix_epoch__/e.MICROS_PER_MILLIS;if(t>BigInt(Number.MAX_SAFE_INTEGER)||t<BigInt(Number.MIN_SAFE_INTEGER))throw new RangeError("Timestamp is outside of the representable range of JS's Date");return new Date(Number(t))}},h=class e{data;get __identity__(){return this.data}constructor(e){this.data="string"==typeof e?a(e):e}isEqual(e){return this.toHexString()===e.toHexString()}toHexString(){return i(o(this.data))}toUint8Array(){return o(this.data)}static fromString(t){return new e(t)}};(u=p||(p={})).getAlgebraicType=function(){return U.createSumType([new b("Interval",U.createU64Type()),new b("Time",U.createU64Type())])},u.serialize=function(e){switch(e.tag){case"Interval":return{Interval:e.value};case"Time":return{Time:e.value};default:throw"unreachable"}},u.Interval=e=>({tag:"Interval",value:e}),u.Time=e=>({tag:"Time",value:e}),u.fromValue=function(e){let t=e.asSumValue();switch(t.tag){case 0:return{tag:"Interval",value:t.value.asBigInt()};case 1:return{tag:"Time",value:t.value.asBigInt()};default:throw"unreachable"}};var f,g,T=p,b=class{name;algebraicType;constructor(e,t){this.name=e,this.algebraicType=t}},w=class{variants;constructor(e){this.variants=e}serialize=(e,t)=>{if(2==this.variants.length&&"some"===this.variants[0].name&&"none"===this.variants[1].name)null!=t?(e.writeByte(0),this.variants[0].algebraicType.serialize(e,t)):e.writeByte(1);else{let r=t.tag;const i=this.variants.findIndex((e=>e.name===r));if(i<0)throw`Can't serialize a sum type, couldn't find ${t.tag} tag`;e.writeU8(i),this.variants[i].algebraicType.serialize(e,t.value)}};deserialize=e=>{let t=e.readU8();if(2==this.variants.length&&"some"===this.variants[0].name&&"none"===this.variants[1].name){if(0===t)return this.variants[0].algebraicType.deserialize(e);if(1===t)return;throw`Can't deserialize an option type, couldn't find ${t} tag`}{let r=this.variants[t],i=r.algebraicType.deserialize(e);return{tag:r.name,value:i}}}},m=class{name;algebraicType;constructor(e,t){this.name=e,this.algebraicType=t}},S=class{elements;constructor(e){this.elements=e}isEmpty(){return 0===this.elements.length}serialize=(e,t)=>{for(let r of this.elements)r.algebraicType.serialize(e,t[r.name])};deserialize=e=>{let t={};if(1===this.elements.length){if("__time_duration_micros__"===this.elements[0].name)return new y(e.readI64());if("__timestamp_micros_since_unix_epoch__"===this.elements[0].name)return new d(e.readI64());if("__identity__"===this.elements[0].name)return new h(e.readU256());if("__connection_id__"===this.elements[0].name)return new l(e.readU128())}for(let r of this.elements)t[r.name]=r.algebraicType.deserialize(e);return t}},I=class{keyType;valueType;constructor(e,t){this.keyType=e,this.valueType=t}},U=class e{type;type_;#s(e,t){this.type_=t,this.type=void 0===t?ke.None:e}get product(){if(this.type!==ke.ProductType)throw"product type was requested, but the type is not ProductType";return this.type_}set product(e){this.#s(ke.ProductType,e)}get sum(){if(this.type!==ke.SumType)throw"sum type was requested, but the type is not SumType";return this.type_}set sum(e){this.#s(ke.SumType,e)}get array(){if(this.type!==ke.ArrayType)throw"array type was requested, but the type is not ArrayType";return this.type_}set array(e){this.#s(ke.ArrayType,e)}get map(){if(this.type!==ke.MapType)throw"map type was requested, but the type is not MapType";return this.type_}set map(e){this.#s(ke.MapType,e)}static#n(t,r){let i=new e;return i.#s(t,r),i}static createProductType(e){return this.#n(ke.ProductType,new S(e))}static createSumType(e){return this.#n(ke.SumType,new w(e))}static createArrayType(e){return this.#n(ke.ArrayType,e)}static createMapType(e,t){return this.#n(ke.MapType,new I(e,t))}static createBoolType(){return this.#n(ke.Bool,null)}static createI8Type(){return this.#n(ke.I8,null)}static createU8Type(){return this.#n(ke.U8,null)}static createI16Type(){return this.#n(ke.I16,null)}static createU16Type(){return this.#n(ke.U16,null)}static createI32Type(){return this.#n(ke.I32,null)}static createU32Type(){return this.#n(ke.U32,null)}static createI64Type(){return this.#n(ke.I64,null)}static createU64Type(){return this.#n(ke.U64,null)}static createI128Type(){return this.#n(ke.I128,null)}static createU128Type(){return this.#n(ke.U128,null)}static createI256Type(){return this.#n(ke.I256,null)}static createU256Type(){return this.#n(ke.U256,null)}static createF32Type(){return this.#n(ke.F32,null)}static createF64Type(){return this.#n(ke.F64,null)}static createStringType(){return this.#n(ke.String,null)}static createBytesType(){return this.createArrayType(this.createU8Type())}static createOptionType(e){return this.createSumType([new b("some",e),new b("none",this.createProductType([]))])}static createIdentityType(){return this.createProductType([new m("__identity__",this.createU256Type())])}static createConnectionIdType(){return this.createProductType([new m("__connection_id__",this.createU128Type())])}static createScheduleAtType(){return T.getAlgebraicType()}static createTimestampType(){return this.createProductType([new m("__timestamp_micros_since_unix_epoch__",this.createI64Type())])}static createTimeDurationType(){return this.createProductType([new m("__time_duration_micros__",this.createI64Type())])}isProductType(){return this.type===ke.ProductType}isSumType(){return this.type===ke.SumType}isArrayType(){return this.type===ke.ArrayType}isMapType(){return this.type===ke.MapType}#a(){return this.isArrayType()&&this.array.type==ke.U8}#c(e){return this.isProductType()&&1===this.product.elements.length&&(this.product.elements[0].algebraicType.type==ke.U128||this.product.elements[0].algebraicType.type==ke.U256)&&this.product.elements[0].name===e}#o(e){return this.isProductType()&&1===this.product.elements.length&&this.product.elements[0].algebraicType.type===ke.I64&&this.product.elements[0].name===e}isIdentity(){return this.#c("__identity__")}isConnectionId(){return this.#c("__connection_id__")}isScheduleAt(){return this.isSumType()&&2===this.sum.variants.length&&"Interval"===this.sum.variants[0].name&&this.sum.variants[0].algebraicType.type===ke.U64&&"Time"===this.sum.variants[1].name&&this.sum.variants[1].algebraicType.type===ke.U64}isTimestamp(){return this.#o("__timestamp_micros_since_unix_epoch__")}isTimeDuration(){return this.#o("__time_duration_micros__")}serialize(e,t){switch(this.type){case ke.ProductType:this.product.serialize(e,t);break;case ke.SumType:this.sum.serialize(e,t);break;case ke.ArrayType:if(this.#a())e.writeUInt8Array(t);else{const r=this.array;e.writeU32(t.length);for(let i of t)r.serialize(e,i)}break;case ke.MapType:throw new Error("not implemented");case ke.Bool:e.writeBool(t);break;case ke.I8:e.writeI8(t);break;case ke.U8:e.writeU8(t);break;case ke.I16:e.writeI16(t);break;case ke.U16:e.writeU16(t);break;case ke.I32:e.writeI32(t);break;case ke.U32:e.writeU32(t);break;case ke.I64:e.writeI64(t);break;case ke.U64:e.writeU64(t);break;case ke.I128:e.writeI128(t);break;case ke.U128:e.writeU128(t);break;case ke.I256:e.writeI256(t);break;case ke.U256:e.writeU256(t);break;case ke.F32:e.writeF32(t);break;case ke.F64:e.writeF64(t);break;case ke.String:e.writeString(t);break;default:throw new Error(`not implemented, ${this.type}`)}}deserialize(e){switch(this.type){case ke.ProductType:return this.product.deserialize(e);case ke.SumType:return this.sum.deserialize(e);case ke.ArrayType:if(this.#a())return e.readUInt8Array();{const t=this.array,r=e.readU32();let i=[];for(let s=0;s<r;s++)i.push(t.deserialize(e));return i}case ke.MapType:throw new Error("not implemented");case ke.Bool:return e.readBool();case ke.I8:return e.readI8();case ke.U8:return e.readU8();case ke.I16:return e.readI16();case ke.U16:return e.readU16();case ke.I32:return e.readI32();case ke.U32:return e.readU32();case ke.I64:return e.readI64();case ke.U64:return e.readU64();case ke.I128:return e.readI128();case ke.U128:return e.readU128();case ke.U256:return e.readU256();case ke.F32:return e.readF32();case ke.F64:return e.readF64();case ke.String:return e.readString();default:throw new Error(`not implemented, ${this.type}`)}}};f=U||(U={}),(g=f.Type||(f.Type={})).SumType="SumType",g.ProductType="ProductType",g.ArrayType="ArrayType",g.MapType="MapType",g.Bool="Bool",g.I8="I8",g.U8="U8",g.I16="I16",g.U16="U16",g.I32="I32",g.U32="U32",g.I64="I64",g.U64="U64",g.I128="I128",g.U128="U128",g.I256="I256",g.U256="U256",g.F32="F32",g.F64="F64",g.String="String",g.None="None";var A,v,z,_,B,F,M,E,k,x,C,O,q,P,R,D,N,L,$,W,H,Q,V,j,G,Z,K,J,X,Y,ee,te,re,ie,se,ne,ae,ce,oe,pe,ue,le,ye,de,he,fe,ge,Te,be,we,me,Se,Ie,Ue,Ae,ve,ze,_e,Be,Fe,Me,Ee,ke=U.Type,xe=class{tag;value;constructor(e,t){this.tag=e,this.value=t}static deserialize(e,t){return t.readSum(e)}},Ce=class{elements;constructor(e){this.elements=e}static deserialize(e,t){return t.readProduct(e)}},Oe=class{value;constructor(e){if(void 0===e)throw"value is undefined";this.value=e}callMethod(e){return this[e]()}static deserialize(e,t){switch(e.type){case U.Type.ProductType:return new this(Ce.deserialize(e.product,t));case U.Type.SumType:return new this(xe.deserialize(e.sum,t));case U.Type.ArrayType:let r=e.array;return r.type===U.Type.U8?new this(t.readUInt8Array()):new this(t.readArray(r));case U.Type.MapType:let i=e.map;return new this(t.readMap(i.keyType,i.valueType));case U.Type.Bool:return new this(t.readBool());case U.Type.I8:return new this(t.readI8());case U.Type.U8:return new this(t.readU8());case U.Type.I16:return new this(t.readI16());case U.Type.U16:return new this(t.readU16());case U.Type.I32:return new this(t.readI32());case U.Type.U32:return new this(t.readU32());case U.Type.I64:return new this(t.readI64());case U.Type.U64:return new this(t.readU64());case U.Type.I128:return new this(t.readI128());case U.Type.U128:return new this(t.readU128());case U.Type.String:return new this(t.readString());default:throw new Error(`not implemented, ${e.type}`)}}asProductValue(){return this.value}asField(e){return this.asProductValue().elements[e]}asSumValue(){return this.value}asArray(){return this.value}asMap(){return this.value}asString(){return this.value}asBoolean(){return this.value}asNumber(){return this.value}asBytes(){return this.value}asBigInt(){return this.value}asIdentity(){return new h(this.asField(0).asBigInt())}asConnectionId(){return new l(this.asField(0).asBigInt())}asScheduleAt(){return p.fromValue(this)}};(v=A||(A={})).FixedSize=e=>({tag:"FixedSize",value:e}),v.RowOffsets=e=>({tag:"RowOffsets",value:e}),v.getTypeScriptAlgebraicType=function(){return U.createSumType([new b("FixedSize",U.createU16Type()),new b("RowOffsets",U.createArrayType(U.createU64Type()))])},v.serialize=function(e,t){v.getTypeScriptAlgebraicType().serialize(e,t)},v.deserialize=function(e){return v.getTypeScriptAlgebraicType().deserialize(e)},(_=z||(z={})).getTypeScriptAlgebraicType=function(){return U.createProductType([new m("sizeHint",A.getTypeScriptAlgebraicType()),new m("rowsData",U.createArrayType(U.createU8Type()))])},_.serialize=function(e,t){_.getTypeScriptAlgebraicType().serialize(e,t)},_.deserialize=function(e){return _.getTypeScriptAlgebraicType().deserialize(e)},(F=B||(B={})).getTypeScriptAlgebraicType=function(){return U.createProductType([new m("reducer",U.createStringType()),new m("args",U.createArrayType(U.createU8Type())),new m("requestId",U.createU32Type()),new m("flags",U.createU8Type())])},F.serialize=function(e,t){F.getTypeScriptAlgebraicType().serialize(e,t)},F.deserialize=function(e){return F.getTypeScriptAlgebraicType().deserialize(e)},(E=M||(M={})).getTypeScriptAlgebraicType=function(){return U.createProductType([new m("queryStrings",U.createArrayType(U.createStringType())),new m("requestId",U.createU32Type())])},E.serialize=function(e,t){E.getTypeScriptAlgebraicType().serialize(e,t)},E.deserialize=function(e){return E.getTypeScriptAlgebraicType().deserialize(e)},(x=k||(k={})).getTypeScriptAlgebraicType=function(){return U.createProductType([new m("messageId",U.createArrayType(U.createU8Type())),new m("queryString",U.createStringType())])},x.serialize=function(e,t){x.getTypeScriptAlgebraicType().serialize(e,t)},x.deserialize=function(e){return x.getTypeScriptAlgebraicType().deserialize(e)},(O=C||(C={})).getTypeScriptAlgebraicType=function(){return U.createProductType([new m("id",U.createU32Type())])},O.serialize=function(e,t){O.getTypeScriptAlgebraicType().serialize(e,t)},O.deserialize=function(e){return O.getTypeScriptAlgebraicType().deserialize(e)},(P=q||(q={})).getTypeScriptAlgebraicType=function(){return U.createProductType([new m("query",U.createStringType()),new m("requestId",U.createU32Type()),new m("queryId",C.getTypeScriptAlgebraicType())])},P.serialize=function(e,t){P.getTypeScriptAlgebraicType().serialize(e,t)},P.deserialize=function(e){return P.getTypeScriptAlgebraicType().deserialize(e)},(D=R||(R={})).getTypeScriptAlgebraicType=function(){return U.createProductType([new m("queryStrings",U.createArrayType(U.createStringType())),new m("requestId",U.createU32Type()),new m("queryId",C.getTypeScriptAlgebraicType())])},D.serialize=function(e,t){D.getTypeScriptAlgebraicType().serialize(e,t)},D.deserialize=function(e){return D.getTypeScriptAlgebraicType().deserialize(e)},(L=N||(N={})).getTypeScriptAlgebraicType=function(){return U.createProductType([new m("requestId",U.createU32Type()),new m("queryId",C.getTypeScriptAlgebraicType())])},L.serialize=function(e,t){L.getTypeScriptAlgebraicType().serialize(e,t)},L.deserialize=function(e){return L.getTypeScriptAlgebraicType().deserialize(e)},(W=$||($={})).getTypeScriptAlgebraicType=function(){return U.createProductType([new m("requestId",U.createU32Type()),new m("queryId",C.getTypeScriptAlgebraicType())])},W.serialize=function(e,t){W.getTypeScriptAlgebraicType().serialize(e,t)},W.deserialize=function(e){return W.getTypeScriptAlgebraicType().deserialize(e)},(Q=H||(H={})).CallReducer=e=>({tag:"CallReducer",value:e}),Q.Subscribe=e=>({tag:"Subscribe",value:e}),Q.OneOffQuery=e=>({tag:"OneOffQuery",value:e}),Q.SubscribeSingle=e=>({tag:"SubscribeSingle",value:e}),Q.SubscribeMulti=e=>({tag:"SubscribeMulti",value:e}),Q.Unsubscribe=e=>({tag:"Unsubscribe",value:e}),Q.UnsubscribeMulti=e=>({tag:"UnsubscribeMulti",value:e}),Q.getTypeScriptAlgebraicType=function(){return U.createSumType([new b("CallReducer",B.getTypeScriptAlgebraicType()),new b("Subscribe",M.getTypeScriptAlgebraicType()),new b("OneOffQuery",k.getTypeScriptAlgebraicType()),new b("SubscribeSingle",q.getTypeScriptAlgebraicType()),new b("SubscribeMulti",R.getTypeScriptAlgebraicType()),new b("Unsubscribe",N.getTypeScriptAlgebraicType()),new b("UnsubscribeMulti",$.getTypeScriptAlgebraicType())])},Q.serialize=function(e,t){Q.getTypeScriptAlgebraicType().serialize(e,t)},Q.deserialize=function(e){return Q.getTypeScriptAlgebraicType().deserialize(e)},(j=V||(V={})).getTypeScriptAlgebraicType=function(){return U.createProductType([new m("deletes",z.getTypeScriptAlgebraicType()),new m("inserts",z.getTypeScriptAlgebraicType())])},j.serialize=function(e,t){j.getTypeScriptAlgebraicType().serialize(e,t)},j.deserialize=function(e){return j.getTypeScriptAlgebraicType().deserialize(e)},(Z=G||(G={})).Uncompressed=e=>({tag:"Uncompressed",value:e}),Z.Brotli=e=>({tag:"Brotli",value:e}),Z.Gzip=e=>({tag:"Gzip",value:e}),Z.getTypeScriptAlgebraicType=function(){return U.createSumType([new b("Uncompressed",V.getTypeScriptAlgebraicType()),new b("Brotli",U.createArrayType(U.createU8Type())),new b("Gzip",U.createArrayType(U.createU8Type()))])},Z.serialize=function(e,t){Z.getTypeScriptAlgebraicType().serialize(e,t)},Z.deserialize=function(e){return Z.getTypeScriptAlgebraicType().deserialize(e)},(J=K||(K={})).getTypeScriptAlgebraicType=function(){return U.createProductType([new m("tableId",U.createU32Type()),new m("tableName",U.createStringType()),new m("numRows",U.createU64Type()),new m("updates",U.createArrayType(G.getTypeScriptAlgebraicType()))])},J.serialize=function(e,t){J.getTypeScriptAlgebraicType().serialize(e,t)},J.deserialize=function(e){return J.getTypeScriptAlgebraicType().deserialize(e)},(Y=X||(X={})).getTypeScriptAlgebraicType=function(){return U.createProductType([new m("tables",U.createArrayType(K.getTypeScriptAlgebraicType()))])},Y.serialize=function(e,t){Y.getTypeScriptAlgebraicType().serialize(e,t)},Y.deserialize=function(e){return Y.getTypeScriptAlgebraicType().deserialize(e)},(te=ee||(ee={})).getTypeScriptAlgebraicType=function(){return U.createProductType([new m("quanta",U.createU128Type())])},te.serialize=function(e,t){te.getTypeScriptAlgebraicType().serialize(e,t)},te.deserialize=function(e){return te.getTypeScriptAlgebraicType().deserialize(e)},(ie=re||(re={})).getTypeScriptAlgebraicType=function(){return U.createProductType([new m("identity",U.createIdentityType()),new m("token",U.createStringType()),new m("connectionId",U.createConnectionIdType())])},ie.serialize=function(e,t){ie.getTypeScriptAlgebraicType().serialize(e,t)},ie.deserialize=function(e){return ie.getTypeScriptAlgebraicType().deserialize(e)},(ne=se||(se={})).getTypeScriptAlgebraicType=function(){return U.createProductType([new m("databaseUpdate",X.getTypeScriptAlgebraicType()),new m("requestId",U.createU32Type()),new m("totalHostExecutionDuration",U.createTimeDurationType())])},ne.serialize=function(e,t){ne.getTypeScriptAlgebraicType().serialize(e,t)},ne.deserialize=function(e){return ne.getTypeScriptAlgebraicType().deserialize(e)},(ce=ae||(ae={})).getTypeScriptAlgebraicType=function(){return U.createProductType([new m("tableName",U.createStringType()),new m("rows",z.getTypeScriptAlgebraicType())])},ce.serialize=function(e,t){ce.getTypeScriptAlgebraicType().serialize(e,t)},ce.deserialize=function(e){return ce.getTypeScriptAlgebraicType().deserialize(e)},(pe=oe||(oe={})).getTypeScriptAlgebraicType=function(){return U.createProductType([new m("messageId",U.createArrayType(U.createU8Type())),new m("error",U.createOptionType(U.createStringType())),new m("tables",U.createArrayType(ae.getTypeScriptAlgebraicType())),new m("totalHostExecutionDuration",U.createTimeDurationType())])},pe.serialize=function(e,t){pe.getTypeScriptAlgebraicType().serialize(e,t)},pe.deserialize=function(e){return pe.getTypeScriptAlgebraicType().deserialize(e)},(le=ue||(ue={})).getTypeScriptAlgebraicType=function(){return U.createProductType([new m("reducerName",U.createStringType()),new m("reducerId",U.createU32Type()),new m("args",U.createArrayType(U.createU8Type())),new m("requestId",U.createU32Type())])},le.serialize=function(e,t){le.getTypeScriptAlgebraicType().serialize(e,t)},le.deserialize=function(e){return le.getTypeScriptAlgebraicType().deserialize(e)},(de=ye||(ye={})).Committed=e=>({tag:"Committed",value:e}),de.Failed=e=>({tag:"Failed",value:e}),de.OutOfEnergy={tag:"OutOfEnergy"},de.getTypeScriptAlgebraicType=function(){return U.createSumType([new b("Committed",X.getTypeScriptAlgebraicType()),new b("Failed",U.createStringType()),new b("OutOfEnergy",U.createProductType([]))])},de.serialize=function(e,t){de.getTypeScriptAlgebraicType().serialize(e,t)},de.deserialize=function(e){return de.getTypeScriptAlgebraicType().deserialize(e)},(fe=he||(he={})).getTypeScriptAlgebraicType=function(){return U.createProductType([new m("status",ye.getTypeScriptAlgebraicType()),new m("timestamp",U.createTimestampType()),new m("callerIdentity",U.createIdentityType()),new m("callerConnectionId",U.createConnectionIdType()),new m("reducerCall",ue.getTypeScriptAlgebraicType()),new m("energyQuantaUsed",ee.getTypeScriptAlgebraicType()),new m("totalHostExecutionDuration",U.createTimeDurationType())])},fe.serialize=function(e,t){fe.getTypeScriptAlgebraicType().serialize(e,t)},fe.deserialize=function(e){return fe.getTypeScriptAlgebraicType().deserialize(e)},(Te=ge||(ge={})).getTypeScriptAlgebraicType=function(){return U.createProductType([new m("requestId",U.createU32Type()),new m("update",X.getTypeScriptAlgebraicType())])},Te.serialize=function(e,t){Te.getTypeScriptAlgebraicType().serialize(e,t)},Te.deserialize=function(e){return Te.getTypeScriptAlgebraicType().deserialize(e)},(we=be||(be={})).getTypeScriptAlgebraicType=function(){return U.createProductType([new m("tableId",U.createU32Type()),new m("tableName",U.createStringType()),new m("tableRows",K.getTypeScriptAlgebraicType())])},we.serialize=function(e,t){we.getTypeScriptAlgebraicType().serialize(e,t)},we.deserialize=function(e){return we.getTypeScriptAlgebraicType().deserialize(e)},(Se=me||(me={})).getTypeScriptAlgebraicType=function(){return U.createProductType([new m("requestId",U.createU32Type()),new m("totalHostExecutionDurationMicros",U.createU64Type()),new m("queryId",C.getTypeScriptAlgebraicType()),new m("rows",be.getTypeScriptAlgebraicType())])},Se.serialize=function(e,t){Se.getTypeScriptAlgebraicType().serialize(e,t)},Se.deserialize=function(e){return Se.getTypeScriptAlgebraicType().deserialize(e)},(Ue=Ie||(Ie={})).getTypeScriptAlgebraicType=function(){return U.createProductType([new m("requestId",U.createU32Type()),new m("totalHostExecutionDurationMicros",U.createU64Type()),new m("queryId",C.getTypeScriptAlgebraicType()),new m("rows",be.getTypeScriptAlgebraicType())])},Ue.serialize=function(e,t){Ue.getTypeScriptAlgebraicType().serialize(e,t)},Ue.deserialize=function(e){return Ue.getTypeScriptAlgebraicType().deserialize(e)},(ve=Ae||(Ae={})).getTypeScriptAlgebraicType=function(){return U.createProductType([new m("totalHostExecutionDurationMicros",U.createU64Type()),new m("requestId",U.createOptionType(U.createU32Type())),new m("queryId",U.createOptionType(U.createU32Type())),new m("tableId",U.createOptionType(U.createU32Type())),new m("error",U.createStringType())])},ve.serialize=function(e,t){ve.getTypeScriptAlgebraicType().serialize(e,t)},ve.deserialize=function(e){return ve.getTypeScriptAlgebraicType().deserialize(e)},(_e=ze||(ze={})).getTypeScriptAlgebraicType=function(){return U.createProductType([new m("requestId",U.createU32Type()),new m("totalHostExecutionDurationMicros",U.createU64Type()),new m("queryId",C.getTypeScriptAlgebraicType()),new m("update",X.getTypeScriptAlgebraicType())])},_e.serialize=function(e,t){_e.getTypeScriptAlgebraicType().serialize(e,t)},_e.deserialize=function(e){return _e.getTypeScriptAlgebraicType().deserialize(e)},(Fe=Be||(Be={})).getTypeScriptAlgebraicType=function(){return U.createProductType([new m("requestId",U.createU32Type()),new m("totalHostExecutionDurationMicros",U.createU64Type()),new m("queryId",C.getTypeScriptAlgebraicType()),new m("update",X.getTypeScriptAlgebraicType())])},Fe.serialize=function(e,t){Fe.getTypeScriptAlgebraicType().serialize(e,t)},Fe.deserialize=function(e){return Fe.getTypeScriptAlgebraicType().deserialize(e)},(Ee=Me||(Me={})).InitialSubscription=e=>({tag:"InitialSubscription",value:e}),Ee.TransactionUpdate=e=>({tag:"TransactionUpdate",value:e}),Ee.TransactionUpdateLight=e=>({tag:"TransactionUpdateLight",value:e}),Ee.IdentityToken=e=>({tag:"IdentityToken",value:e}),Ee.OneOffQueryResponse=e=>({tag:"OneOffQueryResponse",value:e}),Ee.SubscribeApplied=e=>({tag:"SubscribeApplied",value:e}),Ee.UnsubscribeApplied=e=>({tag:"UnsubscribeApplied",value:e}),Ee.SubscriptionError=e=>({tag:"SubscriptionError",value:e}),Ee.SubscribeMultiApplied=e=>({tag:"SubscribeMultiApplied",value:e}),Ee.UnsubscribeMultiApplied=e=>({tag:"UnsubscribeMultiApplied",value:e}),Ee.getTypeScriptAlgebraicType=function(){return U.createSumType([new b("InitialSubscription",se.getTypeScriptAlgebraicType()),new b("TransactionUpdate",he.getTypeScriptAlgebraicType()),new b("TransactionUpdateLight",ge.getTypeScriptAlgebraicType()),new b("IdentityToken",re.getTypeScriptAlgebraicType()),new b("OneOffQueryResponse",oe.getTypeScriptAlgebraicType()),new b("SubscribeApplied",me.getTypeScriptAlgebraicType()),new b("UnsubscribeApplied",Ie.getTypeScriptAlgebraicType()),new b("SubscriptionError",Ae.getTypeScriptAlgebraicType()),new b("SubscribeMultiApplied",ze.getTypeScriptAlgebraicType()),new b("UnsubscribeMultiApplied",Be.getTypeScriptAlgebraicType())])},Ee.serialize=function(e,t){Ee.getTypeScriptAlgebraicType().serialize(e,t)},Ee.deserialize=function(e){return Ee.getTypeScriptAlgebraicType().deserialize(e)};var qe=class{#p=new Map;on(e,t){let r=this.#p.get(e);r||(r=new Set,this.#p.set(e,r)),r.add(t)}off(e,t){let r=this.#p.get(e);r&&r.delete(t)}emit(e,...t){let r=this.#p.get(e);if(r)for(let e of r)e(...t)}},Pe=class{#u=[];#l(e,t){return e&&"object"==typeof e&&"isEqual"in e?e.isEqual(t):e===t}set(e,t){const r=this.#u.findIndex((({key:t})=>this.#l(t,e)));r>-1?this.#u[r].value=t:this.#u.push({key:e,value:t})}get(e){const t=this.#u.find((({key:t})=>this.#l(t,e)));return t?t.value:void 0}delete(e){const t=this.#u.findIndex((({key:t})=>this.#l(t,e)));return t>-1&&(this.#u.splice(t,1),!0)}has(e){return this.#u.some((({key:t})=>this.#l(t,e)))}values(){return this.#u.map((e=>e.value))}entries(){return this.#u}[Symbol.iterator](){let e=0;const t=this.#u;return{next:()=>e<t.length?{value:t[e++],done:!1}:{value:null,done:!0}}}},Re={component:"đŸ“Ļ",info:"â„šī¸",warn:"âš ī¸",error:"❌",debug:"🐛"},De={component:"color: #fff; background-color: #8D6FDD; padding: 2px 5px; border-radius: 3px;",info:"color: #fff; background-color: #007bff; padding: 2px 5px; border-radius: 3px;",warn:"color: #fff; background-color: #ffc107; padding: 2px 5px; border-radius: 3px;",error:"color: #fff; background-color: #dc3545; padding: 2px 5px; border-radius: 3px;",debug:"color: #fff; background-color: #28a745; padding: 2px 5px; border-radius: 3px;"},Ne={component:"color: #8D6FDD;",info:"color: #007bff;",warn:"color: #ffc107;",error:"color: #dc3545;",debug:"color: #28a745;"},Le=(e,t)=>{console.log(`%c${Re[e]} ${e.toUpperCase()}%c ${t}`,De[e],Ne[e])},$e=class{rows;tableTypeInfo;emitter;constructor(e){this.tableTypeInfo=e,this.rows=new Map,this.emitter=new qe}count(){return this.rows.size}iter(){return Array.from(this.rows.values()).map((([e])=>e))}applyOperations=(e,t)=>{const r=[];if(void 0!==this.tableTypeInfo.primaryKey){const i=this.tableTypeInfo.primaryKey,s=new Pe,n=new Pe;for(const t of e)if("insert"===t.type){const[e,r]=s.get(t.row[i])||[t,0];s.set(t.row[i],[t,r+1])}else{const[e,r]=n.get(t.row[i])||[t,0];n.set(t.row[i],[t,r+1])}for(const{key:e,value:[i,a]}of s){const s=n.get(e);if(s){const[c,o]=s,p=a-o,u=this.update(t,i,c,p);u&&r.push(u),n.delete(e)}else{const e=this.insert(t,i,a);e&&r.push(e)}}for(const[e,i]of n.values()){const s=this.delete(t,e,i);s&&r.push(s)}}else for(const i of e)if("insert"===i.type){const e=this.insert(t,i);e&&r.push(e)}else{const e=this.delete(t,i);e&&r.push(e)}return r};update=(e,t,r,i=0)=>{const[s,n]=this.rows.get(r.rowId)||[r.row,0],a=Math.max(1,n+i);return this.rows.delete(r.rowId),this.rows.set(t.rowId,[t.row,a]),0===n?(Le("error","Updating a row that was not present in the cache"),{type:"insert",table:this.tableTypeInfo.tableName,cb:()=>{this.emitter.emit("insert",e,t.row)}}):(n+i<=0&&Le("error","Negative reference count for row"),{type:"update",table:this.tableTypeInfo.tableName,cb:()=>{this.emitter.emit("update",e,s,t.row)}})};insert=(e,t,r=1)=>{const[i,s]=this.rows.get(t.rowId)||[t.row,0];if(this.rows.set(t.rowId,[t.row,s+r]),0===s)return{type:"insert",table:this.tableTypeInfo.tableName,cb:()=>{this.emitter.emit("insert",e,t.row)}}};delete=(e,t,r=1)=>{const[i,s]=this.rows.get(t.rowId)||[t.row,0];if(0!==s)return s<=r?(this.rows.delete(t.rowId),{type:"delete",table:this.tableTypeInfo.tableName,cb:()=>{this.emitter.emit("delete",e,t.row)}}):void this.rows.set(t.rowId,[t.row,s-r]);Le("warn","Deleting a row that was not present in the cache")};onInsert=e=>{this.emitter.on("insert",e)};onDelete=e=>{this.emitter.on("delete",e)};onUpdate=e=>{this.emitter.on("update",e)};removeOnInsert=e=>{this.emitter.off("insert",e)};removeOnDelete=e=>{this.emitter.off("delete",e)};removeOnUpdate=e=>{this.emitter.off("update",e)}},We=class{tables;constructor(){this.tables=new Map}getTable(e){const t=this.tables.get(e);if(!t)throw console.error("The table has not been registered for this client. Please register the table before using it. If you have registered global tables using the SpacetimeDBClient.registerTables() or `registerTable()` method, please make sure that is executed first!"),new Error(`Table ${e} does not exist`);return t}getOrCreateTable(e){let t;return this.tables.has(e.tableName)?t=this.tables.get(e.tableName):(t=new $e(e),this.tables.set(e.tableName,t)),t}};async function He(e,t,r=131072){let i=0;const s=new ReadableStream({pull(t){if(i<e.length){const s=e.subarray(i,Math.min(i+r,e.length));t.enqueue(s),i+=r}else t.close()}}),n=new DecompressionStream(t),a=s.pipeThrough(n).getReader(),c=[];let o,p=0;for(;!(o=await a.read()).done;)c.push(o.value),p+=o.value.length;const u=new Uint8Array(p);let l=0;for(const e of c)u.set(e,l),l+=e.length;return u}var Qe=class e{onclose;onopen;onmessage;onerror;#y;async#d(e){const t=new Uint8Array(e.data);let r;if(0===t[0])r=t.slice(1);else{if(1===t[0])throw new Error("Brotli Compression not supported. Please use gzip or none compression in withCompression method on DbConnection.");if(2!==t[0])throw new Error("Unexpected Compression Algorithm. Please use `gzip` or `none`");r=await He(t.slice(1),"gzip")}this.onmessage?.({data:r})}#h(e){this.onopen?.(e)}#f(e){this.onerror?.(e)}send(e){this.#y.send(e)}close(){this.#y.close()}constructor(e){this.onmessage=void 0,this.onopen=void 0,this.onmessage=void 0,this.onerror=void 0,e.onmessage=this.#d.bind(this),e.onerror=this.#f.bind(this),e.onclose=this.#f.bind(this),e.onopen=this.#h.bind(this),e.binaryType="arraybuffer",this.#y=e}static async createWebSocketFn({url:t,nameOrAddress:r,wsProtocol:i,authToken:s,compression:n,lightMode:a}){const c=new Headers;let o;if(o="false"===import.meta.env.BROWSER?"WebSocket"in globalThis?WebSocket:(await import("undici")).WebSocket:WebSocket,s){c.set("Authorization",`Bearer ${s}`);const e=new URL("v1/identity/websocket-token",t);e.protocol="wss:"===t.protocol?"https:":"http:";const r=await fetch(e,{method:"POST",headers:c});if(!r.ok)return Promise.reject(new Error(`Failed to verify token: ${r.statusText}`));{const{token:e}=await r.json();t.searchParams.set("token",e)}}const p=new URL(`v1/database/${r}/subscribe`,t);p.searchParams.set("compression","gzip"===n?"Gzip":"None"),a&&p.searchParams.set("light","true");const u=new o(p,i);return new e(u)}},Ve=class{constructor(e,t){this.remoteModule=e,this.dbConnectionConstructor=t,this.#g=Qe.createWebSocketFn}#T;#b;#w;#m;#S=new qe;#I="gzip";#U=!1;#g;withUri(e){return this.#T=new URL(e),this}withModuleName(e){return this.#b=e,this}withToken(e){return this.#m=e,this}withWSFn(e){return this.#g=e,this}withCompression(e){return this.#I=e,this}withLightMode(e){return this.#U=e,this}onConnect(e){return this.#S.on("connect",e),this}onConnectError(e){return this.#S.on("connectError",e),this}onDisconnect(e){return this.#S.on("disconnect",e),this}build(){if(!this.#T)throw new Error("URI is required to connect to SpacetimeDB");if(!this.#b)throw new Error("Database name or address is required to connect to SpacetimeDB");return this.dbConnectionConstructor(new Je({uri:this.#T,nameOrAddress:this.#b,identity:this.#w,token:this.#m,emitter:this.#S,compression:this.#I,lightMode:this.#U,createWSFn:this.#g,remoteModule:this.remoteModule}))}},je=class{constructor(e){this.db=e}#A=void 0;#v=void 0;onApplied(e){return this.#A=e,this}onError(e){return this.#v=e,this}subscribe(e){const t=Array.isArray(e)?e:[e];if(0===t.length)throw new Error("Subscriptions must have at least one query");return new Ze(this.db,t,this.#A,this.#v)}subscribeToAllTables(){this.subscribe("SELECT * FROM *")}},Ge=class{subscriptions=new Map},Ze=class{constructor(e,t,r,i){this.db=e,this.#S.on("applied",(e=>{this.#z=!0,r&&r(e)})),this.#S.on("error",((e,t)=>{this.#z=!1,this.#_=!0,i&&i(e,t)})),this.#B=this.db.registerSubscription(this,this.#S,t)}#B;#F=!1;#_=!1;#z=!1;#S=new qe;unsubscribe(){if(this.#F)throw new Error("Unsubscribe has already been called");this.#F=!0,this.db.unregisterSubscription(this.#B),this.#S.on("end",(e=>{this.#_=!0,this.#z=!1}))}unsubscribeThen(e){if(this.#_)throw new Error("Subscription has already ended");if(this.#F)throw new Error("Unsubscribe has already been called");this.#F=!0,this.db.unregisterSubscription(this.#B),this.#S.on("end",(t=>{this.#_=!0,this.#z=!1,e(t)}))}isEnded(){return this.#_}isActive(){return this.#z}};function Ke(e){switch(e){case"FullUpdate":return 0;case"NoSuccessNotify":return 1}}var Je=class{isActive=!1;identity=void 0;token=void 0;db;reducers;setReducerFlags;connectionId=l.random();#B=0;#S;#M=new qe;#A;#E;#k=Promise.resolve();#x=new Ge;clientCache;ws;wsPromise;constructor({uri:e,nameOrAddress:t,identity:r,token:i,emitter:s,remoteModule:n,createWSFn:a,compression:c,lightMode:o}){Le("info","Connecting to SpacetimeDB WS...");let p=new URL(e);/^wss?:/.test(e.protocol)||(p.protocol="ws:"),this.identity=r,this.token=i,this.#E=n,this.#S=s;let u=this.connectionId.toHexString();p.searchParams.set("connection_id",u),this.clientCache=new We,this.db=this.#E.dbViewConstructor(this),this.setReducerFlags=this.#E.setReducerFlagsConstructor(),this.reducers=this.#E.reducersConstructor(this,this.setReducerFlags),this.wsPromise=a({url:p,nameOrAddress:t,wsProtocol:"v1.bsatn.spacetimedb",authToken:i,compression:c,lightMode:o}).then((e=>(this.ws=e,this.ws.onclose=()=>{this.#S.emit("disconnect",this)},this.ws.onerror=e=>{this.#S.emit("connectError",this,e)},this.ws.onopen=this.#h.bind(this),this.ws.onmessage=this.#d.bind(this),e))).catch((e=>{Le("error","Error connecting to SpacetimeDB WS"),this.#S.emit("connectError",this,e)}))}#C=()=>{const e=this.#B;return this.#B+=1,e};subscriptionBuilder=()=>new je(this);registerSubscription(e,t,r){const i=this.#C();return this.#x.subscriptions.set(i,{handle:e,emitter:t}),this.#O(H.SubscribeMulti({queryStrings:r,queryId:{id:i},requestId:0})),i}unregisterSubscription(e){this.#O(H.UnsubscribeMulti({queryId:{id:e},requestId:0}))}async#q(t){const r=(t,r,i)=>{const s=i.rowsData,n=new e(s),a=[],c=this.#E.tables[r].rowType;for(;n.offset<s.length+s.byteOffset;){const e=c.deserialize(n),r=JSON.stringify(e,((e,t)=>"bigint"==typeof t?t.toString():t));a.push({type:t,rowId:r,row:e})}return a},i=async t=>{const i=t.tableName;let s=[];for(const n of t.updates){let t;if("Gzip"===n.tag){const r=await He(n.value,"gzip");t=V.deserialize(new e(r))}else{if("Brotli"===n.tag)throw new Error("Brotli compression not supported. Please use gzip or none compression in withCompression method on DbConnection.");t=n.value}s=s.concat(r("insert",i,t.inserts)),s=s.concat(r("delete",i,t.deletes))}return{tableName:i,operations:s}},s=async e=>{const t=[];for(const r of e.tables)t.push(await i(r));return t};switch(t.tag){case"InitialSubscription":{const e=t.value.databaseUpdate;return{tag:"InitialSubscription",tableUpdates:await s(e)}}case"TransactionUpdateLight":{const e=t.value.update;return{tag:"TransactionUpdateLight",tableUpdates:await s(e)}}case"TransactionUpdate":{const e=t.value,r=e.callerIdentity,i=l.nullIfZero(e.callerConnectionId),n=e.reducerCall.reducerName,a=e.reducerCall.args,c=e.energyQuantaUsed;let o,p,u="";switch(e.status.tag){case"Committed":o=await s(e.status.value);break;case"Failed":o=[],u=e.status.value;break;case"OutOfEnergy":o=[]}if("<none>"===n){let e=u;return void console.error(`Received an error from the database: ${e}`)}""!==n&&(p={reducerName:n,args:a});return{tag:"TransactionUpdate",tableUpdates:o,identity:r,connectionId:i,reducerInfo:p,status:e.status,energyConsumed:c.quanta,message:u,timestamp:e.timestamp}}case"IdentityToken":return{tag:"IdentityToken",identity:t.value.identity,token:t.value.token,connectionId:t.value.connectionId};case"OneOffQueryResponse":throw new Error(`TypeScript SDK never sends one-off queries, but got OneOffQueryResponse ${t}`);case"SubscribeMultiApplied":{const e=await s(t.value.update);return{tag:"SubscribeApplied",queryId:t.value.queryId.id,tableUpdates:e}}case"UnsubscribeMultiApplied":{const e=await s(t.value.update);return{tag:"UnsubscribeApplied",queryId:t.value.queryId.id,tableUpdates:e}}case"SubscriptionError":return{tag:"SubscriptionError",queryId:t.value.queryId,error:t.value.error}}}#O(e){this.wsPromise.then((r=>{if(r){const i=new t(1024);H.serialize(i,e);const s=i.getBuffer();r.send(s)}}))}#h(){this.isActive=!0}#P(e,t){const r=[];for(let i of e){const e=i.tableName,s=this.#E.tables[e],n=this.clientCache.getOrCreateTable(s);r.push(...n.applyOperations(i.operations,t))}return r}async#R(t){const r=function(t,r){const i=new e(r);return t.deserialize(i)}(Me,t),i=await this.#q(r);if(i)switch(i.tag){case"InitialSubscription":{let e={tag:"SubscribeApplied"};const t=this.#E.eventContextConstructor(this,e),{event:r,...s}=t,n=this.#P(i.tableUpdates,t);this.#S&&this.#A?.(s);for(const e of n)e.cb();break}case"TransactionUpdateLight":{let e={tag:"UnknownTransaction"};const t=this.#E.eventContextConstructor(this,e),r=this.#P(i.tableUpdates,t);for(const e of r)e.cb();break}case"TransactionUpdate":{let t,r,s=i.reducerInfo,n=!1;if(s){r=this.#E.reducers[s.reducerName];try{const i=new e(s.args);t=r.argsType.deserialize(i)}catch{console.debug("Failed to deserialize reducer arguments"),n=!0}}else n=!0;if(n){const e={tag:"UnknownTransaction"},t=this.#E.eventContextConstructor(this,e),r=this.#P(i.tableUpdates,t);for(const e of r)e.cb();return}const a={callerIdentity:i.identity,status:i.status,callerConnectionId:i.connectionId,timestamp:i.timestamp,energyConsumed:i.energyConsumed,reducer:{name:s.reducerName,args:t}},c={tag:"Reducer",value:a},o=this.#E.eventContextConstructor(this,c),p={...o,event:a},u=this.#P(i.tableUpdates,o),l=[];r.argsType.product.elements.forEach(((e,r)=>{l.push(t[e.name])})),this.#M.emit(s.reducerName,p,...l);for(const e of u)e.cb();break}case"IdentityToken":this.identity=i.identity,!this.token&&i.token&&(this.token=i.token),this.connectionId=i.connectionId,this.#S.emit("connect",this,this.identity,this.token);break;case"SubscribeApplied":{const e=this.#x.subscriptions.get(i.queryId);if(void 0===e){Le("error",`Received SubscribeApplied for unknown queryId ${i.queryId}.`);break}const t={tag:"SubscribeApplied"},r=this.#E.eventContextConstructor(this,t),{event:s,...n}=r,a=this.#P(i.tableUpdates,r);e?.emitter.emit("applied",n);for(const e of a)e.cb();break}case"UnsubscribeApplied":{const e=this.#x.subscriptions.get(i.queryId);if(void 0===e){Le("error",`Received UnsubscribeApplied for unknown queryId ${i.queryId}.`);break}const t={tag:"UnsubscribeApplied"},r=this.#E.eventContextConstructor(this,t),{event:s,...n}=r,a=this.#P(i.tableUpdates,r);e?.emitter.emit("end",n),this.#x.subscriptions.delete(i.queryId);for(const e of a)e.cb();break}case"SubscriptionError":{const e=Error(i.error),t={tag:"Error",value:e},r={...this.#E.eventContextConstructor(this,t),event:e};void 0!==i.queryId?(this.#x.subscriptions.get(i.queryId)?.emitter.emit("error",r,e),this.#x.subscriptions.delete(i.queryId)):(console.error("Received an error message without a queryId: ",e),this.#x.subscriptions.forEach((({emitter:t})=>{t.emit("error",r,e)})))}}}#d(e){this.#k=this.#k.then((()=>this.#R(e.data)))}callReducer(e,t,r){const i=H.CallReducer({reducer:e,args:t,requestId:0,flags:Ke(r)});this.#O(i)}disconnect(){this.wsPromise.then((e=>{e&&e.close()}))}#D(e,t){this.#S.on(e,t)}#N(e,t){this.#S.off(e,t)}#L(e){this.#S.on("connect",e)}#$(e){this.#S.on("disconnect",e)}#W(e){this.#S.on("connectError",e)}#H(e){this.#S.off("connect",e)}#Q(e){this.#S.off("disconnect",e)}#V(e){this.#S.off("connectError",e)}onReducer(e,t){this.#M.on(e,t)}offReducer(e,t){this.#M.off(e,t)}};export{U as AlgebraicType,Oe as AlgebraicValue,e as BinaryReader,t as BinaryWriter,We as ClientCache,l as ConnectionId,Ve as DbConnectionBuilder,Je as DbConnectionImpl,h as Identity,S as ProductType,m as ProductTypeElement,Ce as ProductValue,p as ScheduleAt,je as SubscriptionBuilderImpl,w as SumType,b as SumTypeVariant,$e as TableCache,y as TimeDuration,d as Timestamp,r as deepEqual};//# sourceMappingURL=index.js.map
var e=class{#e;#t=0;constructor(e){this.#e=new DataView(e.buffer),this.#t=e.byteOffset}get offset(){return this.#t}readUInt8Array(){const e=this.readU32(),t=new Uint8Array(this.#e.buffer,this.#t,e);return this.#t+=e,t}readBool(){const e=this.#e.getUint8(this.#t);return this.#t+=1,0!==e}readByte(){const e=this.#e.getUint8(this.#t);return this.#t+=1,e}readBytes(e){const t=new DataView(this.#e.buffer,this.#t,e);return this.#t+=e,new Uint8Array(t.buffer)}readI8(){const e=this.#e.getInt8(this.#t);return this.#t+=1,e}readU8(){const e=this.#e.getUint8(this.#t);return this.#t+=1,e}readI16(){const e=this.#e.getInt16(this.#t,!0);return this.#t+=2,e}readU16(){const e=this.#e.getUint16(this.#t,!0);return this.#t+=2,e}readI32(){const e=this.#e.getInt32(this.#t,!0);return this.#t+=4,e}readU32(){const e=this.#e.getUint32(this.#t,!0);return this.#t+=4,e}readI64(){const e=this.#e.getBigInt64(this.#t,!0);return this.#t+=8,e}readU64(){const e=this.#e.getBigUint64(this.#t,!0);return this.#t+=8,e}readU128(){const e=this.#e.getBigUint64(this.#t,!0),t=this.#e.getBigUint64(this.#t+8,!0);return this.#t+=16,(t<<BigInt(64))+e}readI128(){const e=this.#e.getBigUint64(this.#t,!0),t=this.#e.getBigInt64(this.#t+8,!0);return this.#t+=16,(t<<BigInt(64))+e}readU256(){const e=this.#e.getBigUint64(this.#t,!0),t=this.#e.getBigUint64(this.#t+8,!0),r=this.#e.getBigUint64(this.#t+16,!0),i=this.#e.getBigUint64(this.#t+24,!0);return this.#t+=32,(i<<BigInt(192))+(r<<BigInt(128))+(t<<BigInt(64))+e}readI256(){const e=this.#e.getBigUint64(this.#t,!0),t=this.#e.getBigUint64(this.#t+8,!0),r=this.#e.getBigUint64(this.#t+16,!0),i=this.#e.getBigInt64(this.#t+24,!0);return this.#t+=32,(i<<BigInt(192))+(r<<BigInt(128))+(t<<BigInt(64))+e}readF32(){const e=this.#e.getFloat32(this.#t,!0);return this.#t+=4,e}readF64(){const e=this.#e.getFloat64(this.#t,!0);return this.#t+=8,e}readString(){const e=this.readU32(),t=new Uint8Array(this.#e.buffer,this.#t,e),r=new TextDecoder("utf-8").decode(t);return this.#t+=e,r}},t=class{#e;#r;#t=0;constructor(e){this.#e=new Uint8Array(e),this.#r=new DataView(this.#e.buffer)}#i(e){const t=this.#t+e+1;if(t<=this.#e.length)return;let r=2*this.#e.length;r<t&&(r=t);const i=new Uint8Array(r);i.set(this.#e),this.#e=i,this.#r=new DataView(this.#e.buffer)}getBuffer(){return this.#e.slice(0,this.#t)}writeUInt8Array(e){const t=e.length;this.#i(4+t),this.writeU32(t),this.#e.set(e,this.#t),this.#t+=e.length}writeBool(e){this.#i(1),this.#r.setUint8(this.#t,e?1:0),this.#t+=1}writeByte(e){this.#i(1),this.#r.setUint8(this.#t,e),this.#t+=1}writeI8(e){this.#i(1),this.#r.setInt8(this.#t,e),this.#t+=1}writeU8(e){this.#i(1),this.#r.setUint8(this.#t,e),this.#t+=1}writeI16(e){this.#i(2),this.#r.setInt16(this.#t,e,!0),this.#t+=2}writeU16(e){this.#i(2),this.#r.setUint16(this.#t,e,!0),this.#t+=2}writeI32(e){this.#i(4),this.#r.setInt32(this.#t,e,!0),this.#t+=4}writeU32(e){this.#i(4),this.#r.setUint32(this.#t,e,!0),this.#t+=4}writeI64(e){this.#i(8),this.#r.setBigInt64(this.#t,e,!0),this.#t+=8}writeU64(e){this.#i(8),this.#r.setBigUint64(this.#t,e,!0),this.#t+=8}writeU128(e){this.#i(16);const t=e&BigInt("0xFFFFFFFFFFFFFFFF"),r=e>>BigInt(64);this.#r.setBigUint64(this.#t,t,!0),this.#r.setBigUint64(this.#t+8,r,!0),this.#t+=16}writeI128(e){this.#i(16);const t=e&BigInt("0xFFFFFFFFFFFFFFFF"),r=e>>BigInt(64);this.#r.setBigInt64(this.#t,t,!0),this.#r.setBigInt64(this.#t+8,r,!0),this.#t+=16}writeU256(e){this.#i(32);const t=BigInt("0xFFFFFFFFFFFFFFFF"),r=e&t,i=e>>BigInt(64)&t,s=e>>BigInt(128)&t,n=e>>BigInt(192);this.#r.setBigUint64(this.#t+0,r,!0),this.#r.setBigUint64(this.#t+8,i,!0),this.#r.setBigUint64(this.#t+16,s,!0),this.#r.setBigUint64(this.#t+24,n,!0),this.#t+=32}writeI256(e){this.#i(32);const t=BigInt("0xFFFFFFFFFFFFFFFF"),r=e&t,i=e>>BigInt(64)&t,s=e>>BigInt(128)&t,n=e>>BigInt(192);this.#r.setBigUint64(this.#t+0,r,!0),this.#r.setBigUint64(this.#t+8,i,!0),this.#r.setBigUint64(this.#t+16,s,!0),this.#r.setBigInt64(this.#t+24,n,!0),this.#t+=32}writeF32(e){this.#i(4),this.#r.setFloat32(this.#t,e,!0),this.#t+=4}writeF64(e){this.#i(8),this.#r.setFloat64(this.#t,e,!0),this.#t+=8}writeString(e){const t=(new TextEncoder).encode(e);this.writeU32(t.length),this.#i(t.length),this.#e.set(t,this.#t),this.#t+=t.length}};function r(e,t){if(e===t)return!0;if("object"!=typeof e||null===e||"object"!=typeof t||null===t)return!1;const i=Object.keys(e),s=Object.keys(t);if(i.length!==s.length)return!1;for(let n of i)if(!s.includes(n)||!r(e[n],t[n]))return!1;return!0}function i(e){return Array.prototype.map.call(e.reverse(),(e=>("00"+e.toString(16)).slice(-2))).join("")}function s(e){e.startsWith("0x")&&(e=e.slice(2));let t=e.match(/.{1,2}/g)||[],r=Uint8Array.from(t.map((e=>parseInt(e,16))));return 32!=r.length?new Uint8Array(0):r.reverse()}function n(t){return function(t){if(16!=t.length)throw new Error(`Uint8Array is not 16 bytes long: ${t}`);return new e(t).readU128()}(s(t))}function a(t){return function(t){if(32!=t.length)throw new Error(`Uint8Array is not 32 bytes long: [${t}]`);return new e(t).readU256()}(s(t))}function c(e){let r=new t(16);return r.writeU128(e),r.getBuffer()}function o(e){let r=new t(32);return r.writeU256(e),r.getBuffer()}var p,u,l=class e{data;get __connection_id__(){return this.data}constructor(e){this.data=e}isZero(){return this.data===BigInt(0)}static nullIfZero(e){return e.isZero()?null:e}static random(){let t=BigInt(0);for(let e=0;e<16;e++)t=t<<BigInt(8)|BigInt(Math.floor(255*Math.random()));return new e(t)}isEqual(e){return this.data==e.data}toHexString(){return i(c(this.data))}toUint8Array(){return c(this.data)}static fromString(t){return new e(n(t))}static fromStringOrNull(t){let r=e.fromString(t);return r.isZero()?null:r}},y=class e{__time_duration_micros__;static MICROS_PER_MILLIS=1000n;get micros(){return this.__time_duration_micros__}get millis(){return Number(this.micros/e.MICROS_PER_MILLIS)}constructor(e){this.__time_duration_micros__=e}static fromMillis(t){return new e(BigInt(t)*e.MICROS_PER_MILLIS)}},d=class e{__timestamp_micros_since_unix_epoch__;static MICROS_PER_MILLIS=1000n;get microsSinceUnixEpoch(){return this.__timestamp_micros_since_unix_epoch__}constructor(e){this.__timestamp_micros_since_unix_epoch__=e}static UNIX_EPOCH=new e(0n);static now(){return e.fromDate(new Date)}static fromDate(t){const r=t.getTime(),i=BigInt(r)*e.MICROS_PER_MILLIS;return new e(i)}toDate(){const t=this.__timestamp_micros_since_unix_epoch__/e.MICROS_PER_MILLIS;if(t>BigInt(Number.MAX_SAFE_INTEGER)||t<BigInt(Number.MIN_SAFE_INTEGER))throw new RangeError("Timestamp is outside of the representable range of JS's Date");return new Date(Number(t))}},h=class e{data;get __identity__(){return this.data}constructor(e){this.data="string"==typeof e?a(e):e}isEqual(e){return this.toHexString()===e.toHexString()}toHexString(){return i(o(this.data))}toUint8Array(){return o(this.data)}static fromString(t){return new e(t)}};(u=p||(p={})).getAlgebraicType=function(){return U.createSumType([new b("Interval",U.createU64Type()),new b("Time",U.createU64Type())])},u.serialize=function(e){switch(e.tag){case"Interval":return{Interval:e.value};case"Time":return{Time:e.value};default:throw"unreachable"}},u.Interval=e=>({tag:"Interval",value:e}),u.Time=e=>({tag:"Time",value:e}),u.fromValue=function(e){let t=e.asSumValue();switch(t.tag){case 0:return{tag:"Interval",value:t.value.asBigInt()};case 1:return{tag:"Time",value:t.value.asBigInt()};default:throw"unreachable"}};var f,g,T=p,b=class{name;algebraicType;constructor(e,t){this.name=e,this.algebraicType=t}},w=class{variants;constructor(e){this.variants=e}serialize=(e,t)=>{if(2==this.variants.length&&"some"===this.variants[0].name&&"none"===this.variants[1].name)null!=t?(e.writeByte(0),this.variants[0].algebraicType.serialize(e,t)):e.writeByte(1);else{let r=t.tag;const i=this.variants.findIndex((e=>e.name===r));if(i<0)throw`Can't serialize a sum type, couldn't find ${t.tag} tag`;e.writeU8(i),this.variants[i].algebraicType.serialize(e,t.value)}};deserialize=e=>{let t=e.readU8();if(2==this.variants.length&&"some"===this.variants[0].name&&"none"===this.variants[1].name){if(0===t)return this.variants[0].algebraicType.deserialize(e);if(1===t)return;throw`Can't deserialize an option type, couldn't find ${t} tag`}{let r=this.variants[t],i=r.algebraicType.deserialize(e);return{tag:r.name,value:i}}}},m=class{name;algebraicType;constructor(e,t){this.name=e,this.algebraicType=t}},S=class{elements;constructor(e){this.elements=e}isEmpty(){return 0===this.elements.length}serialize=(e,t)=>{for(let r of this.elements)r.algebraicType.serialize(e,t[r.name])};deserialize=e=>{let t={};if(1===this.elements.length){if("__time_duration_micros__"===this.elements[0].name)return new y(e.readI64());if("__timestamp_micros_since_unix_epoch__"===this.elements[0].name)return new d(e.readI64());if("__identity__"===this.elements[0].name)return new h(e.readU256());if("__connection_id__"===this.elements[0].name)return new l(e.readU128())}for(let r of this.elements)t[r.name]=r.algebraicType.deserialize(e);return t}},I=class{keyType;valueType;constructor(e,t){this.keyType=e,this.valueType=t}},U=class e{type;type_;#s(e,t){this.type_=t,this.type=void 0===t?ke.None:e}get product(){if(this.type!==ke.ProductType)throw"product type was requested, but the type is not ProductType";return this.type_}set product(e){this.#s(ke.ProductType,e)}get sum(){if(this.type!==ke.SumType)throw"sum type was requested, but the type is not SumType";return this.type_}set sum(e){this.#s(ke.SumType,e)}get array(){if(this.type!==ke.ArrayType)throw"array type was requested, but the type is not ArrayType";return this.type_}set array(e){this.#s(ke.ArrayType,e)}get map(){if(this.type!==ke.MapType)throw"map type was requested, but the type is not MapType";return this.type_}set map(e){this.#s(ke.MapType,e)}static#n(t,r){let i=new e;return i.#s(t,r),i}static createProductType(e){return this.#n(ke.ProductType,new S(e))}static createSumType(e){return this.#n(ke.SumType,new w(e))}static createArrayType(e){return this.#n(ke.ArrayType,e)}static createMapType(e,t){return this.#n(ke.MapType,new I(e,t))}static createBoolType(){return this.#n(ke.Bool,null)}static createI8Type(){return this.#n(ke.I8,null)}static createU8Type(){return this.#n(ke.U8,null)}static createI16Type(){return this.#n(ke.I16,null)}static createU16Type(){return this.#n(ke.U16,null)}static createI32Type(){return this.#n(ke.I32,null)}static createU32Type(){return this.#n(ke.U32,null)}static createI64Type(){return this.#n(ke.I64,null)}static createU64Type(){return this.#n(ke.U64,null)}static createI128Type(){return this.#n(ke.I128,null)}static createU128Type(){return this.#n(ke.U128,null)}static createI256Type(){return this.#n(ke.I256,null)}static createU256Type(){return this.#n(ke.U256,null)}static createF32Type(){return this.#n(ke.F32,null)}static createF64Type(){return this.#n(ke.F64,null)}static createStringType(){return this.#n(ke.String,null)}static createBytesType(){return this.createArrayType(this.createU8Type())}static createOptionType(e){return this.createSumType([new b("some",e),new b("none",this.createProductType([]))])}static createIdentityType(){return this.createProductType([new m("__identity__",this.createU256Type())])}static createConnectionIdType(){return this.createProductType([new m("__connection_id__",this.createU128Type())])}static createScheduleAtType(){return T.getAlgebraicType()}static createTimestampType(){return this.createProductType([new m("__timestamp_micros_since_unix_epoch__",this.createI64Type())])}static createTimeDurationType(){return this.createProductType([new m("__time_duration_micros__",this.createI64Type())])}isProductType(){return this.type===ke.ProductType}isSumType(){return this.type===ke.SumType}isArrayType(){return this.type===ke.ArrayType}isMapType(){return this.type===ke.MapType}#a(){return this.isArrayType()&&this.array.type==ke.U8}#c(e){return this.isProductType()&&1===this.product.elements.length&&(this.product.elements[0].algebraicType.type==ke.U128||this.product.elements[0].algebraicType.type==ke.U256)&&this.product.elements[0].name===e}#o(e){return this.isProductType()&&1===this.product.elements.length&&this.product.elements[0].algebraicType.type===ke.I64&&this.product.elements[0].name===e}isIdentity(){return this.#c("__identity__")}isConnectionId(){return this.#c("__connection_id__")}isScheduleAt(){return this.isSumType()&&2===this.sum.variants.length&&"Interval"===this.sum.variants[0].name&&this.sum.variants[0].algebraicType.type===ke.U64&&"Time"===this.sum.variants[1].name&&this.sum.variants[1].algebraicType.type===ke.U64}isTimestamp(){return this.#o("__timestamp_micros_since_unix_epoch__")}isTimeDuration(){return this.#o("__time_duration_micros__")}serialize(e,t){switch(this.type){case ke.ProductType:this.product.serialize(e,t);break;case ke.SumType:this.sum.serialize(e,t);break;case ke.ArrayType:if(this.#a())e.writeUInt8Array(t);else{const r=this.array;e.writeU32(t.length);for(let i of t)r.serialize(e,i)}break;case ke.MapType:throw new Error("not implemented");case ke.Bool:e.writeBool(t);break;case ke.I8:e.writeI8(t);break;case ke.U8:e.writeU8(t);break;case ke.I16:e.writeI16(t);break;case ke.U16:e.writeU16(t);break;case ke.I32:e.writeI32(t);break;case ke.U32:e.writeU32(t);break;case ke.I64:e.writeI64(t);break;case ke.U64:e.writeU64(t);break;case ke.I128:e.writeI128(t);break;case ke.U128:e.writeU128(t);break;case ke.I256:e.writeI256(t);break;case ke.U256:e.writeU256(t);break;case ke.F32:e.writeF32(t);break;case ke.F64:e.writeF64(t);break;case ke.String:e.writeString(t);break;default:throw new Error(`not implemented, ${this.type}`)}}deserialize(e){switch(this.type){case ke.ProductType:return this.product.deserialize(e);case ke.SumType:return this.sum.deserialize(e);case ke.ArrayType:if(this.#a())return e.readUInt8Array();{const t=this.array,r=e.readU32();let i=[];for(let s=0;s<r;s++)i.push(t.deserialize(e));return i}case ke.MapType:throw new Error("not implemented");case ke.Bool:return e.readBool();case ke.I8:return e.readI8();case ke.U8:return e.readU8();case ke.I16:return e.readI16();case ke.U16:return e.readU16();case ke.I32:return e.readI32();case ke.U32:return e.readU32();case ke.I64:return e.readI64();case ke.U64:return e.readU64();case ke.I128:return e.readI128();case ke.U128:return e.readU128();case ke.U256:return e.readU256();case ke.F32:return e.readF32();case ke.F64:return e.readF64();case ke.String:return e.readString();default:throw new Error(`not implemented, ${this.type}`)}}};f=U||(U={}),(g=f.Type||(f.Type={})).SumType="SumType",g.ProductType="ProductType",g.ArrayType="ArrayType",g.MapType="MapType",g.Bool="Bool",g.I8="I8",g.U8="U8",g.I16="I16",g.U16="U16",g.I32="I32",g.U32="U32",g.I64="I64",g.U64="U64",g.I128="I128",g.U128="U128",g.I256="I256",g.U256="U256",g.F32="F32",g.F64="F64",g.String="String",g.None="None";var A,v,z,_,B,F,M,E,k,x,C,O,q,P,R,D,N,L,$,W,H,Q,V,j,G,Z,K,J,X,Y,ee,te,re,ie,se,ne,ae,ce,oe,pe,ue,le,ye,de,he,fe,ge,Te,be,we,me,Se,Ie,Ue,Ae,ve,ze,_e,Be,Fe,Me,Ee,ke=U.Type,xe=class{tag;value;constructor(e,t){this.tag=e,this.value=t}static deserialize(e,t){return t.readSum(e)}},Ce=class{elements;constructor(e){this.elements=e}static deserialize(e,t){return t.readProduct(e)}},Oe=class{value;constructor(e){if(void 0===e)throw"value is undefined";this.value=e}callMethod(e){return this[e]()}static deserialize(e,t){switch(e.type){case U.Type.ProductType:return new this(Ce.deserialize(e.product,t));case U.Type.SumType:return new this(xe.deserialize(e.sum,t));case U.Type.ArrayType:let r=e.array;return r.type===U.Type.U8?new this(t.readUInt8Array()):new this(t.readArray(r));case U.Type.MapType:let i=e.map;return new this(t.readMap(i.keyType,i.valueType));case U.Type.Bool:return new this(t.readBool());case U.Type.I8:return new this(t.readI8());case U.Type.U8:return new this(t.readU8());case U.Type.I16:return new this(t.readI16());case U.Type.U16:return new this(t.readU16());case U.Type.I32:return new this(t.readI32());case U.Type.U32:return new this(t.readU32());case U.Type.I64:return new this(t.readI64());case U.Type.U64:return new this(t.readU64());case U.Type.I128:return new this(t.readI128());case U.Type.U128:return new this(t.readU128());case U.Type.String:return new this(t.readString());default:throw new Error(`not implemented, ${e.type}`)}}asProductValue(){return this.value}asField(e){return this.asProductValue().elements[e]}asSumValue(){return this.value}asArray(){return this.value}asMap(){return this.value}asString(){return this.value}asBoolean(){return this.value}asNumber(){return this.value}asBytes(){return this.value}asBigInt(){return this.value}asIdentity(){return new h(this.asField(0).asBigInt())}asConnectionId(){return new l(this.asField(0).asBigInt())}asScheduleAt(){return p.fromValue(this)}};(v=A||(A={})).FixedSize=e=>({tag:"FixedSize",value:e}),v.RowOffsets=e=>({tag:"RowOffsets",value:e}),v.getTypeScriptAlgebraicType=function(){return U.createSumType([new b("FixedSize",U.createU16Type()),new b("RowOffsets",U.createArrayType(U.createU64Type()))])},v.serialize=function(e,t){v.getTypeScriptAlgebraicType().serialize(e,t)},v.deserialize=function(e){return v.getTypeScriptAlgebraicType().deserialize(e)},(_=z||(z={})).getTypeScriptAlgebraicType=function(){return U.createProductType([new m("sizeHint",A.getTypeScriptAlgebraicType()),new m("rowsData",U.createArrayType(U.createU8Type()))])},_.serialize=function(e,t){_.getTypeScriptAlgebraicType().serialize(e,t)},_.deserialize=function(e){return _.getTypeScriptAlgebraicType().deserialize(e)},(F=B||(B={})).getTypeScriptAlgebraicType=function(){return U.createProductType([new m("reducer",U.createStringType()),new m("args",U.createArrayType(U.createU8Type())),new m("requestId",U.createU32Type()),new m("flags",U.createU8Type())])},F.serialize=function(e,t){F.getTypeScriptAlgebraicType().serialize(e,t)},F.deserialize=function(e){return F.getTypeScriptAlgebraicType().deserialize(e)},(E=M||(M={})).getTypeScriptAlgebraicType=function(){return U.createProductType([new m("queryStrings",U.createArrayType(U.createStringType())),new m("requestId",U.createU32Type())])},E.serialize=function(e,t){E.getTypeScriptAlgebraicType().serialize(e,t)},E.deserialize=function(e){return E.getTypeScriptAlgebraicType().deserialize(e)},(x=k||(k={})).getTypeScriptAlgebraicType=function(){return U.createProductType([new m("messageId",U.createArrayType(U.createU8Type())),new m("queryString",U.createStringType())])},x.serialize=function(e,t){x.getTypeScriptAlgebraicType().serialize(e,t)},x.deserialize=function(e){return x.getTypeScriptAlgebraicType().deserialize(e)},(O=C||(C={})).getTypeScriptAlgebraicType=function(){return U.createProductType([new m("id",U.createU32Type())])},O.serialize=function(e,t){O.getTypeScriptAlgebraicType().serialize(e,t)},O.deserialize=function(e){return O.getTypeScriptAlgebraicType().deserialize(e)},(P=q||(q={})).getTypeScriptAlgebraicType=function(){return U.createProductType([new m("query",U.createStringType()),new m("requestId",U.createU32Type()),new m("queryId",C.getTypeScriptAlgebraicType())])},P.serialize=function(e,t){P.getTypeScriptAlgebraicType().serialize(e,t)},P.deserialize=function(e){return P.getTypeScriptAlgebraicType().deserialize(e)},(D=R||(R={})).getTypeScriptAlgebraicType=function(){return U.createProductType([new m("queryStrings",U.createArrayType(U.createStringType())),new m("requestId",U.createU32Type()),new m("queryId",C.getTypeScriptAlgebraicType())])},D.serialize=function(e,t){D.getTypeScriptAlgebraicType().serialize(e,t)},D.deserialize=function(e){return D.getTypeScriptAlgebraicType().deserialize(e)},(L=N||(N={})).getTypeScriptAlgebraicType=function(){return U.createProductType([new m("requestId",U.createU32Type()),new m("queryId",C.getTypeScriptAlgebraicType())])},L.serialize=function(e,t){L.getTypeScriptAlgebraicType().serialize(e,t)},L.deserialize=function(e){return L.getTypeScriptAlgebraicType().deserialize(e)},(W=$||($={})).getTypeScriptAlgebraicType=function(){return U.createProductType([new m("requestId",U.createU32Type()),new m("queryId",C.getTypeScriptAlgebraicType())])},W.serialize=function(e,t){W.getTypeScriptAlgebraicType().serialize(e,t)},W.deserialize=function(e){return W.getTypeScriptAlgebraicType().deserialize(e)},(Q=H||(H={})).CallReducer=e=>({tag:"CallReducer",value:e}),Q.Subscribe=e=>({tag:"Subscribe",value:e}),Q.OneOffQuery=e=>({tag:"OneOffQuery",value:e}),Q.SubscribeSingle=e=>({tag:"SubscribeSingle",value:e}),Q.SubscribeMulti=e=>({tag:"SubscribeMulti",value:e}),Q.Unsubscribe=e=>({tag:"Unsubscribe",value:e}),Q.UnsubscribeMulti=e=>({tag:"UnsubscribeMulti",value:e}),Q.getTypeScriptAlgebraicType=function(){return U.createSumType([new b("CallReducer",B.getTypeScriptAlgebraicType()),new b("Subscribe",M.getTypeScriptAlgebraicType()),new b("OneOffQuery",k.getTypeScriptAlgebraicType()),new b("SubscribeSingle",q.getTypeScriptAlgebraicType()),new b("SubscribeMulti",R.getTypeScriptAlgebraicType()),new b("Unsubscribe",N.getTypeScriptAlgebraicType()),new b("UnsubscribeMulti",$.getTypeScriptAlgebraicType())])},Q.serialize=function(e,t){Q.getTypeScriptAlgebraicType().serialize(e,t)},Q.deserialize=function(e){return Q.getTypeScriptAlgebraicType().deserialize(e)},(j=V||(V={})).getTypeScriptAlgebraicType=function(){return U.createProductType([new m("deletes",z.getTypeScriptAlgebraicType()),new m("inserts",z.getTypeScriptAlgebraicType())])},j.serialize=function(e,t){j.getTypeScriptAlgebraicType().serialize(e,t)},j.deserialize=function(e){return j.getTypeScriptAlgebraicType().deserialize(e)},(Z=G||(G={})).Uncompressed=e=>({tag:"Uncompressed",value:e}),Z.Brotli=e=>({tag:"Brotli",value:e}),Z.Gzip=e=>({tag:"Gzip",value:e}),Z.getTypeScriptAlgebraicType=function(){return U.createSumType([new b("Uncompressed",V.getTypeScriptAlgebraicType()),new b("Brotli",U.createArrayType(U.createU8Type())),new b("Gzip",U.createArrayType(U.createU8Type()))])},Z.serialize=function(e,t){Z.getTypeScriptAlgebraicType().serialize(e,t)},Z.deserialize=function(e){return Z.getTypeScriptAlgebraicType().deserialize(e)},(J=K||(K={})).getTypeScriptAlgebraicType=function(){return U.createProductType([new m("tableId",U.createU32Type()),new m("tableName",U.createStringType()),new m("numRows",U.createU64Type()),new m("updates",U.createArrayType(G.getTypeScriptAlgebraicType()))])},J.serialize=function(e,t){J.getTypeScriptAlgebraicType().serialize(e,t)},J.deserialize=function(e){return J.getTypeScriptAlgebraicType().deserialize(e)},(Y=X||(X={})).getTypeScriptAlgebraicType=function(){return U.createProductType([new m("tables",U.createArrayType(K.getTypeScriptAlgebraicType()))])},Y.serialize=function(e,t){Y.getTypeScriptAlgebraicType().serialize(e,t)},Y.deserialize=function(e){return Y.getTypeScriptAlgebraicType().deserialize(e)},(te=ee||(ee={})).getTypeScriptAlgebraicType=function(){return U.createProductType([new m("quanta",U.createU128Type())])},te.serialize=function(e,t){te.getTypeScriptAlgebraicType().serialize(e,t)},te.deserialize=function(e){return te.getTypeScriptAlgebraicType().deserialize(e)},(ie=re||(re={})).getTypeScriptAlgebraicType=function(){return U.createProductType([new m("identity",U.createIdentityType()),new m("token",U.createStringType()),new m("connectionId",U.createConnectionIdType())])},ie.serialize=function(e,t){ie.getTypeScriptAlgebraicType().serialize(e,t)},ie.deserialize=function(e){return ie.getTypeScriptAlgebraicType().deserialize(e)},(ne=se||(se={})).getTypeScriptAlgebraicType=function(){return U.createProductType([new m("databaseUpdate",X.getTypeScriptAlgebraicType()),new m("requestId",U.createU32Type()),new m("totalHostExecutionDuration",U.createTimeDurationType())])},ne.serialize=function(e,t){ne.getTypeScriptAlgebraicType().serialize(e,t)},ne.deserialize=function(e){return ne.getTypeScriptAlgebraicType().deserialize(e)},(ce=ae||(ae={})).getTypeScriptAlgebraicType=function(){return U.createProductType([new m("tableName",U.createStringType()),new m("rows",z.getTypeScriptAlgebraicType())])},ce.serialize=function(e,t){ce.getTypeScriptAlgebraicType().serialize(e,t)},ce.deserialize=function(e){return ce.getTypeScriptAlgebraicType().deserialize(e)},(pe=oe||(oe={})).getTypeScriptAlgebraicType=function(){return U.createProductType([new m("messageId",U.createArrayType(U.createU8Type())),new m("error",U.createOptionType(U.createStringType())),new m("tables",U.createArrayType(ae.getTypeScriptAlgebraicType())),new m("totalHostExecutionDuration",U.createTimeDurationType())])},pe.serialize=function(e,t){pe.getTypeScriptAlgebraicType().serialize(e,t)},pe.deserialize=function(e){return pe.getTypeScriptAlgebraicType().deserialize(e)},(le=ue||(ue={})).getTypeScriptAlgebraicType=function(){return U.createProductType([new m("reducerName",U.createStringType()),new m("reducerId",U.createU32Type()),new m("args",U.createArrayType(U.createU8Type())),new m("requestId",U.createU32Type())])},le.serialize=function(e,t){le.getTypeScriptAlgebraicType().serialize(e,t)},le.deserialize=function(e){return le.getTypeScriptAlgebraicType().deserialize(e)},(de=ye||(ye={})).Committed=e=>({tag:"Committed",value:e}),de.Failed=e=>({tag:"Failed",value:e}),de.OutOfEnergy={tag:"OutOfEnergy"},de.getTypeScriptAlgebraicType=function(){return U.createSumType([new b("Committed",X.getTypeScriptAlgebraicType()),new b("Failed",U.createStringType()),new b("OutOfEnergy",U.createProductType([]))])},de.serialize=function(e,t){de.getTypeScriptAlgebraicType().serialize(e,t)},de.deserialize=function(e){return de.getTypeScriptAlgebraicType().deserialize(e)},(fe=he||(he={})).getTypeScriptAlgebraicType=function(){return U.createProductType([new m("status",ye.getTypeScriptAlgebraicType()),new m("timestamp",U.createTimestampType()),new m("callerIdentity",U.createIdentityType()),new m("callerConnectionId",U.createConnectionIdType()),new m("reducerCall",ue.getTypeScriptAlgebraicType()),new m("energyQuantaUsed",ee.getTypeScriptAlgebraicType()),new m("totalHostExecutionDuration",U.createTimeDurationType())])},fe.serialize=function(e,t){fe.getTypeScriptAlgebraicType().serialize(e,t)},fe.deserialize=function(e){return fe.getTypeScriptAlgebraicType().deserialize(e)},(Te=ge||(ge={})).getTypeScriptAlgebraicType=function(){return U.createProductType([new m("requestId",U.createU32Type()),new m("update",X.getTypeScriptAlgebraicType())])},Te.serialize=function(e,t){Te.getTypeScriptAlgebraicType().serialize(e,t)},Te.deserialize=function(e){return Te.getTypeScriptAlgebraicType().deserialize(e)},(we=be||(be={})).getTypeScriptAlgebraicType=function(){return U.createProductType([new m("tableId",U.createU32Type()),new m("tableName",U.createStringType()),new m("tableRows",K.getTypeScriptAlgebraicType())])},we.serialize=function(e,t){we.getTypeScriptAlgebraicType().serialize(e,t)},we.deserialize=function(e){return we.getTypeScriptAlgebraicType().deserialize(e)},(Se=me||(me={})).getTypeScriptAlgebraicType=function(){return U.createProductType([new m("requestId",U.createU32Type()),new m("totalHostExecutionDurationMicros",U.createU64Type()),new m("queryId",C.getTypeScriptAlgebraicType()),new m("rows",be.getTypeScriptAlgebraicType())])},Se.serialize=function(e,t){Se.getTypeScriptAlgebraicType().serialize(e,t)},Se.deserialize=function(e){return Se.getTypeScriptAlgebraicType().deserialize(e)},(Ue=Ie||(Ie={})).getTypeScriptAlgebraicType=function(){return U.createProductType([new m("requestId",U.createU32Type()),new m("totalHostExecutionDurationMicros",U.createU64Type()),new m("queryId",C.getTypeScriptAlgebraicType()),new m("rows",be.getTypeScriptAlgebraicType())])},Ue.serialize=function(e,t){Ue.getTypeScriptAlgebraicType().serialize(e,t)},Ue.deserialize=function(e){return Ue.getTypeScriptAlgebraicType().deserialize(e)},(ve=Ae||(Ae={})).getTypeScriptAlgebraicType=function(){return U.createProductType([new m("totalHostExecutionDurationMicros",U.createU64Type()),new m("requestId",U.createOptionType(U.createU32Type())),new m("queryId",U.createOptionType(U.createU32Type())),new m("tableId",U.createOptionType(U.createU32Type())),new m("error",U.createStringType())])},ve.serialize=function(e,t){ve.getTypeScriptAlgebraicType().serialize(e,t)},ve.deserialize=function(e){return ve.getTypeScriptAlgebraicType().deserialize(e)},(_e=ze||(ze={})).getTypeScriptAlgebraicType=function(){return U.createProductType([new m("requestId",U.createU32Type()),new m("totalHostExecutionDurationMicros",U.createU64Type()),new m("queryId",C.getTypeScriptAlgebraicType()),new m("update",X.getTypeScriptAlgebraicType())])},_e.serialize=function(e,t){_e.getTypeScriptAlgebraicType().serialize(e,t)},_e.deserialize=function(e){return _e.getTypeScriptAlgebraicType().deserialize(e)},(Fe=Be||(Be={})).getTypeScriptAlgebraicType=function(){return U.createProductType([new m("requestId",U.createU32Type()),new m("totalHostExecutionDurationMicros",U.createU64Type()),new m("queryId",C.getTypeScriptAlgebraicType()),new m("update",X.getTypeScriptAlgebraicType())])},Fe.serialize=function(e,t){Fe.getTypeScriptAlgebraicType().serialize(e,t)},Fe.deserialize=function(e){return Fe.getTypeScriptAlgebraicType().deserialize(e)},(Ee=Me||(Me={})).InitialSubscription=e=>({tag:"InitialSubscription",value:e}),Ee.TransactionUpdate=e=>({tag:"TransactionUpdate",value:e}),Ee.TransactionUpdateLight=e=>({tag:"TransactionUpdateLight",value:e}),Ee.IdentityToken=e=>({tag:"IdentityToken",value:e}),Ee.OneOffQueryResponse=e=>({tag:"OneOffQueryResponse",value:e}),Ee.SubscribeApplied=e=>({tag:"SubscribeApplied",value:e}),Ee.UnsubscribeApplied=e=>({tag:"UnsubscribeApplied",value:e}),Ee.SubscriptionError=e=>({tag:"SubscriptionError",value:e}),Ee.SubscribeMultiApplied=e=>({tag:"SubscribeMultiApplied",value:e}),Ee.UnsubscribeMultiApplied=e=>({tag:"UnsubscribeMultiApplied",value:e}),Ee.getTypeScriptAlgebraicType=function(){return U.createSumType([new b("InitialSubscription",se.getTypeScriptAlgebraicType()),new b("TransactionUpdate",he.getTypeScriptAlgebraicType()),new b("TransactionUpdateLight",ge.getTypeScriptAlgebraicType()),new b("IdentityToken",re.getTypeScriptAlgebraicType()),new b("OneOffQueryResponse",oe.getTypeScriptAlgebraicType()),new b("SubscribeApplied",me.getTypeScriptAlgebraicType()),new b("UnsubscribeApplied",Ie.getTypeScriptAlgebraicType()),new b("SubscriptionError",Ae.getTypeScriptAlgebraicType()),new b("SubscribeMultiApplied",ze.getTypeScriptAlgebraicType()),new b("UnsubscribeMultiApplied",Be.getTypeScriptAlgebraicType())])},Ee.serialize=function(e,t){Ee.getTypeScriptAlgebraicType().serialize(e,t)},Ee.deserialize=function(e){return Ee.getTypeScriptAlgebraicType().deserialize(e)};var qe=class{#p=new Map;on(e,t){let r=this.#p.get(e);r||(r=new Set,this.#p.set(e,r)),r.add(t)}off(e,t){let r=this.#p.get(e);r&&r.delete(t)}emit(e,...t){let r=this.#p.get(e);if(r)for(let e of r)e(...t)}},Pe=class{#u=[];#l(e,t){return e&&"object"==typeof e&&"isEqual"in e?e.isEqual(t):e===t}set(e,t){const r=this.#u.findIndex((({key:t})=>this.#l(t,e)));r>-1?this.#u[r].value=t:this.#u.push({key:e,value:t})}get(e){const t=this.#u.find((({key:t})=>this.#l(t,e)));return t?t.value:void 0}delete(e){const t=this.#u.findIndex((({key:t})=>this.#l(t,e)));return t>-1&&(this.#u.splice(t,1),!0)}has(e){return this.#u.some((({key:t})=>this.#l(t,e)))}values(){return this.#u.map((e=>e.value))}entries(){return this.#u}[Symbol.iterator](){let e=0;const t=this.#u;return{next:()=>e<t.length?{value:t[e++],done:!1}:{value:null,done:!0}}}},Re={component:"đŸ“Ļ",info:"â„šī¸",warn:"âš ī¸",error:"❌",debug:"🐛"},De={component:"color: #fff; background-color: #8D6FDD; padding: 2px 5px; border-radius: 3px;",info:"color: #fff; background-color: #007bff; padding: 2px 5px; border-radius: 3px;",warn:"color: #fff; background-color: #ffc107; padding: 2px 5px; border-radius: 3px;",error:"color: #fff; background-color: #dc3545; padding: 2px 5px; border-radius: 3px;",debug:"color: #fff; background-color: #28a745; padding: 2px 5px; border-radius: 3px;"},Ne={component:"color: #8D6FDD;",info:"color: #007bff;",warn:"color: #ffc107;",error:"color: #dc3545;",debug:"color: #28a745;"},Le=(e,t)=>{console.log(`%c${Re[e]} ${e.toUpperCase()}%c ${t}`,De[e],Ne[e])},$e=class{rows;tableTypeInfo;emitter;constructor(e){this.tableTypeInfo=e,this.rows=new Map,this.emitter=new qe}count(){return this.rows.size}iter(){return Array.from(this.rows.values()).map((([e])=>e))}applyOperations=(e,t)=>{const r=[];if(void 0!==this.tableTypeInfo.primaryKey){const i=this.tableTypeInfo.primaryKey,s=new Pe,n=new Pe;for(const t of e)if("insert"===t.type){const[e,r]=s.get(t.row[i])||[t,0];s.set(t.row[i],[t,r+1])}else{const[e,r]=n.get(t.row[i])||[t,0];n.set(t.row[i],[t,r+1])}for(const{key:e,value:[i,a]}of s){const s=n.get(e);if(s){const[c,o]=s,p=a-o,u=this.update(t,i,c,p);u&&r.push(u),n.delete(e)}else{const e=this.insert(t,i,a);e&&r.push(e)}}for(const[e,i]of n.values()){const s=this.delete(t,e,i);s&&r.push(s)}}else for(const i of e)if("insert"===i.type){const e=this.insert(t,i);e&&r.push(e)}else{const e=this.delete(t,i);e&&r.push(e)}return r};update=(e,t,r,i=0)=>{const[s,n]=this.rows.get(r.rowId)||[r.row,0],a=Math.max(1,n+i);return this.rows.delete(r.rowId),this.rows.set(t.rowId,[t.row,a]),0===n?(Le("error","Updating a row that was not present in the cache"),{type:"insert",table:this.tableTypeInfo.tableName,cb:()=>{this.emitter.emit("insert",e,t.row)}}):(n+i<=0&&Le("error","Negative reference count for row"),{type:"update",table:this.tableTypeInfo.tableName,cb:()=>{this.emitter.emit("update",e,s,t.row)}})};insert=(e,t,r=1)=>{const[i,s]=this.rows.get(t.rowId)||[t.row,0];if(this.rows.set(t.rowId,[t.row,s+r]),0===s)return{type:"insert",table:this.tableTypeInfo.tableName,cb:()=>{this.emitter.emit("insert",e,t.row)}}};delete=(e,t,r=1)=>{const[i,s]=this.rows.get(t.rowId)||[t.row,0];if(0!==s)return s<=r?(this.rows.delete(t.rowId),{type:"delete",table:this.tableTypeInfo.tableName,cb:()=>{this.emitter.emit("delete",e,t.row)}}):void this.rows.set(t.rowId,[t.row,s-r]);Le("warn","Deleting a row that was not present in the cache")};onInsert=e=>{this.emitter.on("insert",e)};onDelete=e=>{this.emitter.on("delete",e)};onUpdate=e=>{this.emitter.on("update",e)};removeOnInsert=e=>{this.emitter.off("insert",e)};removeOnDelete=e=>{this.emitter.off("delete",e)};removeOnUpdate=e=>{this.emitter.off("update",e)}},We=class{tables;constructor(){this.tables=new Map}getTable(e){const t=this.tables.get(e);if(!t)throw console.error("The table has not been registered for this client. Please register the table before using it. If you have registered global tables using the SpacetimeDBClient.registerTables() or `registerTable()` method, please make sure that is executed first!"),new Error(`Table ${e} does not exist`);return t}getOrCreateTable(e){let t;return this.tables.has(e.tableName)?t=this.tables.get(e.tableName):(t=new $e(e),this.tables.set(e.tableName,t)),t}};async function He(e,t,r=131072){let i=0;const s=new ReadableStream({pull(t){if(i<e.length){const s=e.subarray(i,Math.min(i+r,e.length));t.enqueue(s),i+=r}else t.close()}}),n=new DecompressionStream(t),a=s.pipeThrough(n).getReader(),c=[];let o,p=0;for(;!(o=await a.read()).done;)c.push(o.value),p+=o.value.length;const u=new Uint8Array(p);let l=0;for(const e of c)u.set(e,l),l+=e.length;return u}var Qe=class e{onclose;onopen;onmessage;onerror;#y;async#d(e){const t=new Uint8Array(e.data);let r;if(0===t[0])r=t.slice(1);else{if(1===t[0])throw new Error("Brotli Compression not supported. Please use gzip or none compression in withCompression method on DbConnection.");if(2!==t[0])throw new Error("Unexpected Compression Algorithm. Please use `gzip` or `none`");r=await He(t.slice(1),"gzip")}this.onmessage?.({data:r})}#h(e){this.onopen?.(e)}#f(e){this.onerror?.(e)}send(e){this.#y.send(e)}close(){this.#y.close()}constructor(e){this.onmessage=void 0,this.onopen=void 0,this.onmessage=void 0,this.onerror=void 0,e.onmessage=this.#d.bind(this),e.onerror=this.#f.bind(this),e.onclose=this.#f.bind(this),e.onopen=this.#h.bind(this),e.binaryType="arraybuffer",this.#y=e}static async createWebSocketFn({url:t,nameOrAddress:r,wsProtocol:i,authToken:s,compression:n,lightMode:a}){const c=new Headers;let o,p;if(o="false"===import.meta.env.BROWSER?"WebSocket"in globalThis?WebSocket:(await import("undici")).WebSocket:WebSocket,s){c.set("Authorization",`Bearer ${s}`);const e=new URL("v1/identity/websocket-token",t);e.protocol="wss:"===t.protocol?"https:":"http:";const r=await fetch(e,{method:"POST",headers:c});if(!r.ok)return Promise.reject(new Error(`Failed to verify token: ${r.statusText}`));{const{token:e}=await r.json();p=e}}const u=new URL(`v1/database/${r}/subscribe`,t);p&&u.searchParams.set("token",p),u.searchParams.set("compression","gzip"===n?"Gzip":"None"),a&&u.searchParams.set("light","true");const l=new o(u,i);return new e(l)}},Ve=class{constructor(e,t){this.remoteModule=e,this.dbConnectionConstructor=t,this.#g=Qe.createWebSocketFn}#T;#b;#w;#m;#S=new qe;#I="gzip";#U=!1;#g;withUri(e){return this.#T=new URL(e),this}withModuleName(e){return this.#b=e,this}withToken(e){return this.#m=e,this}withWSFn(e){return this.#g=e,this}withCompression(e){return this.#I=e,this}withLightMode(e){return this.#U=e,this}onConnect(e){return this.#S.on("connect",e),this}onConnectError(e){return this.#S.on("connectError",e),this}onDisconnect(e){return this.#S.on("disconnect",e),this}build(){if(!this.#T)throw new Error("URI is required to connect to SpacetimeDB");if(!this.#b)throw new Error("Database name or address is required to connect to SpacetimeDB");return this.dbConnectionConstructor(new Je({uri:this.#T,nameOrAddress:this.#b,identity:this.#w,token:this.#m,emitter:this.#S,compression:this.#I,lightMode:this.#U,createWSFn:this.#g,remoteModule:this.remoteModule}))}},je=class{constructor(e){this.db=e}#A=void 0;#v=void 0;onApplied(e){return this.#A=e,this}onError(e){return this.#v=e,this}subscribe(e){const t=Array.isArray(e)?e:[e];if(0===t.length)throw new Error("Subscriptions must have at least one query");return new Ze(this.db,t,this.#A,this.#v)}subscribeToAllTables(){this.subscribe("SELECT * FROM *")}},Ge=class{subscriptions=new Map},Ze=class{constructor(e,t,r,i){this.db=e,this.#S.on("applied",(e=>{this.#z=!0,r&&r(e)})),this.#S.on("error",((e,t)=>{this.#z=!1,this.#_=!0,i&&i(e,t)})),this.#B=this.db.registerSubscription(this,this.#S,t)}#B;#F=!1;#_=!1;#z=!1;#S=new qe;unsubscribe(){if(this.#F)throw new Error("Unsubscribe has already been called");this.#F=!0,this.db.unregisterSubscription(this.#B),this.#S.on("end",(e=>{this.#_=!0,this.#z=!1}))}unsubscribeThen(e){if(this.#_)throw new Error("Subscription has already ended");if(this.#F)throw new Error("Unsubscribe has already been called");this.#F=!0,this.db.unregisterSubscription(this.#B),this.#S.on("end",(t=>{this.#_=!0,this.#z=!1,e(t)}))}isEnded(){return this.#_}isActive(){return this.#z}};function Ke(e){switch(e){case"FullUpdate":return 0;case"NoSuccessNotify":return 1}}var Je=class{isActive=!1;identity=void 0;token=void 0;db;reducers;setReducerFlags;connectionId=l.random();#B=0;#S;#M=new qe;#A;#E;#k=Promise.resolve();#x=new Ge;clientCache;ws;wsPromise;constructor({uri:e,nameOrAddress:t,identity:r,token:i,emitter:s,remoteModule:n,createWSFn:a,compression:c,lightMode:o}){Le("info","Connecting to SpacetimeDB WS...");let p=new URL(e);/^wss?:/.test(e.protocol)||(p.protocol="https:"===p.protocol?"wss:":"ws:"),this.identity=r,this.token=i,this.#E=n,this.#S=s;let u=this.connectionId.toHexString();p.searchParams.set("connection_id",u),this.clientCache=new We,this.db=this.#E.dbViewConstructor(this),this.setReducerFlags=this.#E.setReducerFlagsConstructor(),this.reducers=this.#E.reducersConstructor(this,this.setReducerFlags),this.wsPromise=a({url:p,nameOrAddress:t,wsProtocol:"v1.bsatn.spacetimedb",authToken:i,compression:c,lightMode:o}).then((e=>(this.ws=e,this.ws.onclose=()=>{this.#S.emit("disconnect",this)},this.ws.onerror=e=>{this.#S.emit("connectError",this,e)},this.ws.onopen=this.#h.bind(this),this.ws.onmessage=this.#d.bind(this),e))).catch((e=>{Le("error","Error connecting to SpacetimeDB WS"),this.#S.emit("connectError",this,e)}))}#C=()=>{const e=this.#B;return this.#B+=1,e};subscriptionBuilder=()=>new je(this);registerSubscription(e,t,r){const i=this.#C();return this.#x.subscriptions.set(i,{handle:e,emitter:t}),this.#O(H.SubscribeMulti({queryStrings:r,queryId:{id:i},requestId:0})),i}unregisterSubscription(e){this.#O(H.UnsubscribeMulti({queryId:{id:e},requestId:0}))}async#q(t){const r=(t,r,i)=>{const s=i.rowsData,n=new e(s),a=[],c=this.#E.tables[r].rowType;for(;n.offset<s.length+s.byteOffset;){const e=c.deserialize(n),r=JSON.stringify(e,((e,t)=>"bigint"==typeof t?t.toString():t));a.push({type:t,rowId:r,row:e})}return a},i=async t=>{const i=t.tableName;let s=[];for(const n of t.updates){let t;if("Gzip"===n.tag){const r=await He(n.value,"gzip");t=V.deserialize(new e(r))}else{if("Brotli"===n.tag)throw new Error("Brotli compression not supported. Please use gzip or none compression in withCompression method on DbConnection.");t=n.value}s=s.concat(r("insert",i,t.inserts)),s=s.concat(r("delete",i,t.deletes))}return{tableName:i,operations:s}},s=async e=>{const t=[];for(const r of e.tables)t.push(await i(r));return t};switch(t.tag){case"InitialSubscription":{const e=t.value.databaseUpdate;return{tag:"InitialSubscription",tableUpdates:await s(e)}}case"TransactionUpdateLight":{const e=t.value.update;return{tag:"TransactionUpdateLight",tableUpdates:await s(e)}}case"TransactionUpdate":{const e=t.value,r=e.callerIdentity,i=l.nullIfZero(e.callerConnectionId),n=e.reducerCall.reducerName,a=e.reducerCall.args,c=e.energyQuantaUsed;let o,p,u="";switch(e.status.tag){case"Committed":o=await s(e.status.value);break;case"Failed":o=[],u=e.status.value;break;case"OutOfEnergy":o=[]}if("<none>"===n){let e=u;return void console.error(`Received an error from the database: ${e}`)}""!==n&&(p={reducerName:n,args:a});return{tag:"TransactionUpdate",tableUpdates:o,identity:r,connectionId:i,reducerInfo:p,status:e.status,energyConsumed:c.quanta,message:u,timestamp:e.timestamp}}case"IdentityToken":return{tag:"IdentityToken",identity:t.value.identity,token:t.value.token,connectionId:t.value.connectionId};case"OneOffQueryResponse":throw new Error(`TypeScript SDK never sends one-off queries, but got OneOffQueryResponse ${t}`);case"SubscribeMultiApplied":{const e=await s(t.value.update);return{tag:"SubscribeApplied",queryId:t.value.queryId.id,tableUpdates:e}}case"UnsubscribeMultiApplied":{const e=await s(t.value.update);return{tag:"UnsubscribeApplied",queryId:t.value.queryId.id,tableUpdates:e}}case"SubscriptionError":return{tag:"SubscriptionError",queryId:t.value.queryId,error:t.value.error}}}#O(e){this.wsPromise.then((r=>{if(r){const i=new t(1024);H.serialize(i,e);const s=i.getBuffer();r.send(s)}}))}#h(){this.isActive=!0}#P(e,t){const r=[];for(let i of e){const e=i.tableName,s=this.#E.tables[e],n=this.clientCache.getOrCreateTable(s);r.push(...n.applyOperations(i.operations,t))}return r}async#R(t){const r=function(t,r){const i=new e(r);return t.deserialize(i)}(Me,t),i=await this.#q(r);if(i)switch(i.tag){case"InitialSubscription":{let e={tag:"SubscribeApplied"};const t=this.#E.eventContextConstructor(this,e),{event:r,...s}=t,n=this.#P(i.tableUpdates,t);this.#S&&this.#A?.(s);for(const e of n)e.cb();break}case"TransactionUpdateLight":{let e={tag:"UnknownTransaction"};const t=this.#E.eventContextConstructor(this,e),r=this.#P(i.tableUpdates,t);for(const e of r)e.cb();break}case"TransactionUpdate":{let t,r,s=i.reducerInfo,n=!1;if(s){r=this.#E.reducers[s.reducerName];try{const i=new e(s.args);t=r.argsType.deserialize(i)}catch{console.debug("Failed to deserialize reducer arguments"),n=!0}}else n=!0;if(n){const e={tag:"UnknownTransaction"},t=this.#E.eventContextConstructor(this,e),r=this.#P(i.tableUpdates,t);for(const e of r)e.cb();return}const a={callerIdentity:i.identity,status:i.status,callerConnectionId:i.connectionId,timestamp:i.timestamp,energyConsumed:i.energyConsumed,reducer:{name:s.reducerName,args:t}},c={tag:"Reducer",value:a},o=this.#E.eventContextConstructor(this,c),p={...o,event:a},u=this.#P(i.tableUpdates,o),l=[];r.argsType.product.elements.forEach(((e,r)=>{l.push(t[e.name])})),this.#M.emit(s.reducerName,p,...l);for(const e of u)e.cb();break}case"IdentityToken":this.identity=i.identity,!this.token&&i.token&&(this.token=i.token),this.connectionId=i.connectionId,this.#S.emit("connect",this,this.identity,this.token);break;case"SubscribeApplied":{const e=this.#x.subscriptions.get(i.queryId);if(void 0===e){Le("error",`Received SubscribeApplied for unknown queryId ${i.queryId}.`);break}const t={tag:"SubscribeApplied"},r=this.#E.eventContextConstructor(this,t),{event:s,...n}=r,a=this.#P(i.tableUpdates,r);e?.emitter.emit("applied",n);for(const e of a)e.cb();break}case"UnsubscribeApplied":{const e=this.#x.subscriptions.get(i.queryId);if(void 0===e){Le("error",`Received UnsubscribeApplied for unknown queryId ${i.queryId}.`);break}const t={tag:"UnsubscribeApplied"},r=this.#E.eventContextConstructor(this,t),{event:s,...n}=r,a=this.#P(i.tableUpdates,r);e?.emitter.emit("end",n),this.#x.subscriptions.delete(i.queryId);for(const e of a)e.cb();break}case"SubscriptionError":{const e=Error(i.error),t={tag:"Error",value:e},r={...this.#E.eventContextConstructor(this,t),event:e};void 0!==i.queryId?(this.#x.subscriptions.get(i.queryId)?.emitter.emit("error",r,e),this.#x.subscriptions.delete(i.queryId)):(console.error("Received an error message without a queryId: ",e),this.#x.subscriptions.forEach((({emitter:t})=>{t.emit("error",r,e)})))}}}#d(e){this.#k=this.#k.then((()=>this.#R(e.data)))}callReducer(e,t,r){const i=H.CallReducer({reducer:e,args:t,requestId:0,flags:Ke(r)});this.#O(i)}disconnect(){this.wsPromise.then((e=>{e&&e.close()}))}#D(e,t){this.#S.on(e,t)}#N(e,t){this.#S.off(e,t)}#L(e){this.#S.on("connect",e)}#$(e){this.#S.on("disconnect",e)}#W(e){this.#S.on("connectError",e)}#H(e){this.#S.off("connect",e)}#Q(e){this.#S.off("disconnect",e)}#V(e){this.#S.off("connectError",e)}onReducer(e,t){this.#M.on(e,t)}offReducer(e,t){this.#M.off(e,t)}};export{U as AlgebraicType,Oe as AlgebraicValue,e as BinaryReader,t as BinaryWriter,We as ClientCache,l as ConnectionId,Ve as DbConnectionBuilder,Je as DbConnectionImpl,h as Identity,S as ProductType,m as ProductTypeElement,Ce as ProductValue,p as ScheduleAt,je as SubscriptionBuilderImpl,w as SumType,b as SumTypeVariant,$e as TableCache,y as TimeDuration,d as Timestamp,r as deepEqual};//# sourceMappingURL=index.js.map
{
"name": "@clockworklabs/spacetimedb-sdk",
"version": "1.2.0",
"version": "1.2.1",
"description": "SDK for SpacetimeDB",

@@ -5,0 +5,0 @@ "author": {

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display