@ahmadmoussawi/webdb 0.1.1 → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
- (function(m,Gt){typeof exports=="object"&&typeof module<"u"?Gt(exports):typeof define=="function"&&define.amd?define(["exports"],Gt):(m=typeof globalThis<"u"?globalThis:m||self,Gt(m.WebDB={}))})(this,function(m){"use strict";var pl=Object.defineProperty;var yl=(m,Gt,Cn)=>Gt in m?pl(m,Gt,{enumerable:!0,configurable:!0,writable:!0,value:Cn}):m[Gt]=Cn;var S=(m,Gt,Cn)=>yl(m,typeof Gt!="symbol"?Gt+"":Gt,Cn);const sa=[["TYPE",1],["FLAGS",1],["CELL_COUNT",2],["CONTENT_OFFSET",2],["NEXT_PAGE_ID",4],["FREE_BYTES",2],["CHECKSUM",4]],qt=16,io=0,ia=1,oa=2,ra=4,oo=6,aa=10,Re=12,ca=[["CHILD_PAGE_ID",4],["ROWID",8]],ro=12,la=0,ua=4,ao=291,co=145,te=64,Aa=[["MAGIC",6],["PAGE_SIZE",2],["FILE_FORMAT_VERSION",2],["MIN_READ_VERSION",2],["TOTAL_PAGES",4],["FREE_PAGE_HEAD",4],["SCHEMA_VERSION",4],["CHANGE_COUNTER",4],["PAGE_CHECKSUM",4],["NEXT_CATALOG_PAGE_ID",4],["NEXT_INDEX_CATALOG_PAGE_ID",4],["RESERVED",60]],fa=100,de=0,Ws=6,Vs=8,$s=10,ee=12,re=16,Ee=20,me=24,Ie=28,lo=32,uo=36,_a=40,ga=16,ha=8,ae=16,Ke=8,wn=100,Un=2148,da=3172,Ea=4,ma=3176,Ia=920,pe=56,ce=256,pa=[["TABLE_ID",2],["COLUMN_COUNT",2],["ROOT_PAGE_ID",4],["COL_CATALOG_PAGE_ID",4],["NAME",64],["FLAGS",4],["ROW_COUNT_ESTIMATE",4],["AUTO_INC_NEXT",8],["RESERVED",36]],De=128,ya=0,Ta=2,Ca=4,wa=8,Ua=12,Sa=76,Oa=80,Pa=84,Ba=92,Na=[["INDEX_ID",2],["TABLE_ID",2],["ROOT_PAGE_ID",4],["COLUMN_COUNT",1],["FLAGS",1],["COLUMN_INDICES",16],["COL_DIRECTIONS",8],["NAME",64],["RESERVED",30]],Fe=128,La=0,Ra=2,Da=4,Fa=8,ba=9,Qa=10,ka=26,va=34,Ga=98,Ma=[["PAGE_TYPE",1],["FLAGS",1],["COL_COUNT_IN_PAGE",2],["TABLE_ID",2],["START_COL_INDEX",2],["NEXT_COL_CATALOG_PAGE_ID",4],["PAGE_CHECKSUM",4]],Xs=16,Ha=0,Wa=1,Va=2,$a=4,Xa=6,Ya=8,Za=12,qa=[["TYPE",1],["FLAGS",1],["COL_OFFSET",2],["NAME",64],["RESERVED",4]],Ys=72,xa=0,ja=1,Ka=2,Ja=4,za=68,tc=4194304,be=1024,ec=1024,Qt=2048,ye=8,Ao=16384,fo=12288,Zs=65536,_o=32768,go=4096,ho=61312,Qe=16777216,nc=[["SLOT_TO_PAGE",4096],["PAGE_TO_SLOT",16384],["DIRTY_MASK",128],["VM_CONTEXT",12288],["RESULT_BUFFER",65536],["BYTECODE",32768],["PAGE_SCRATCHPAD",4096],["ALIGNMENT_PADDING",61312]],Zn=4194304,Ft=4198400,Eo=4214784,mo=4214912,Sn=4227200,Io=4292736,po=4325504,sc=4329600,yo=4390912,ic=21168128;function qs(t,e=Qe){const n=t*4096,s=t*4+7&-8;let i=16;for(;i<t*2;)i<<=1;const o=i*8,r=Math.ceil(t/8)+7&-8;if(t===be)return{slotsEndOffset:n,slotToPageOffset:Zn,pageToSlotOffset:Ft,pageToSlotBuckets:Qt,dirtyMaskOffset:Eo,vmContextOffset:mo,resultBufferOffset:Sn,bytecodeOffset:Io,pageScratchpadOffset:po,transientArenaOffset:yo};const a=n,l=a+s,c=l+o,u=c+r,h=u+fo,f=h+Zs,_=f+_o,g=_+go+ho;return{slotsEndOffset:n,slotToPageOffset:a,pageToSlotOffset:l,pageToSlotBuckets:i,dirtyMaskOffset:c,vmContextOffset:u,resultBufferOffset:h,bytecodeOffset:f,pageScratchpadOffset:_,transientArenaOffset:g}}const Te=4096,Je=4128,To=1,On=1463897158,qn=1,xn=2,jn=3,oc=[["MAGIC",6],["WAL_VERSION",2],["PAGE_SIZE",4],["CHECKPOINT_SEQ",4],["SALT1",4],["SALT2",4],["CHECKSUM",4],["RESERVED",4]],Kn=32,xs=0,js=6,Ks=8,Js=12,zs=16,ti=20,ei=24,Co=28,rc=[["MAGIC",4],["FRAME_TYPE",2],["FLAGS",2],["TX_ID",4],["PAGE_ID",4],["DB_SIZE_PAGES",4],["FRAME_SEQ",4],["CHECKSUM",4],["RESERVED",4]],ke=32,ni=0,si=4,ii=6,oi=8,ri=12,ai=16,ci=20,li=24,wo=28,Jn=1,Uo=1,ve=0,So=2,ui=5,zn=10,Pn=12,ts=13,ac=1280,cc=8,lc=64,uc=16,Ac=7,fc=32,Oo=1e4,kt=1e4;function Po(){return{pageId:0,rootPageId:0,slotIdx:0,cellIdx:0,rowOffset:0,btreeDepth:0,flags:0}}function Bo(){const t=Array.from({length:16},()=>Po());return{pc:0,status:O.RUNNING,fault_page_id:0,resultCount:0,resultOffset:0,arenaOffset:0,maxQueryMemory:Qe,rowsAffected:0,registers:new Array(64).fill(null),cursor:t[0],cursors:t,keyInfos:[],sorters:[],aggregators:[],table:null,tables:void 0,outputColumns:void 0,inSets:[]}}function No(t,e,n){t.pc=0,t.status=O.RUNNING,t.fault_page_id=0,t.resultCount=0,t.resultOffset=0,t.arenaOffset=0,t.maxQueryMemory=Qe,t.rowsAffected=0,t.registers.fill(null);for(let s=0;s<t.cursors.length;s++){const i=t.cursors[s];i.pageId=0,i.rootPageId=0,i.slotIdx=0,i.cellIdx=0,i.rowOffset=0,i.btreeDepth=0,i.flags=0}t.cursor=t.cursors[0],t.keyInfos=[],t.sorters=[],t.aggregators=[],t.table=e??null,t.tables=n,t.outputColumns=void 0,t.inSets=[]}var C=(t=>(t[t.NULL=0]="NULL",t[t.INT32=1]="INT32",t[t.INT64=2]="INT64",t[t.FLOAT64=3]="FLOAT64",t[t.TEXT=4]="TEXT",t[t.BLOB=5]="BLOB",t[t.UUID=6]="UUID",t[t.ULID=7]="ULID",t))(C||{}),z=(t=>(t[t.NONE=0]="NONE",t[t.PRIMARY_KEY=1]="PRIMARY_KEY",t[t.NOT_NULL=2]="NOT_NULL",t[t.INDEXED=4]="INDEXED",t[t.AUTO_INC=8]="AUTO_INC",t))(z||{}),Bn=(t=>(t[t.NONE=0]="NONE",t[t.ACTIVE=1]="ACTIVE",t[t.SYSTEM=2]="SYSTEM",t))(Bn||{}),mt=(t=>(t[t.NONE=0]="NONE",t[t.UNIQUE=1]="UNIQUE",t[t.PRIMARY=2]="PRIMARY",t[t.SPATIAL_VECTOR=4]="SPATIAL_VECTOR",t))(mt||{}),d=(t=>(t[t.OP_HALT=0]="OP_HALT",t[t.OP_OPEN_CURSOR=1]="OP_OPEN_CURSOR",t[t.OP_REWIND=2]="OP_REWIND",t[t.OP_NEXT_ROW=3]="OP_NEXT_ROW",t[t.OP_COLUMN_INT=4]="OP_COLUMN_INT",t[t.OP_COLUMN_FLOAT=5]="OP_COLUMN_FLOAT",t[t.OP_COLUMN_TEXT=6]="OP_COLUMN_TEXT",t[t.OP_COLUMN_BLOB=7]="OP_COLUMN_BLOB",t[t.OP_LAST=8]="OP_LAST",t[t.OP_PREV_ROW=9]="OP_PREV_ROW",t[t.OP_COLUMN_UUID=10]="OP_COLUMN_UUID",t[t.OP_COLUMN_ULID=11]="OP_COLUMN_ULID",t[t.OP_OPEN_INDEX=12]="OP_OPEN_INDEX",t[t.OP_INDEX_SEEK_EQ=13]="OP_INDEX_SEEK_EQ",t[t.OP_INDEX_SEEK_GE=14]="OP_INDEX_SEEK_GE",t[t.OP_INDEX_NEXT=15]="OP_INDEX_NEXT",t[t.OP_IS_NULL=16]="OP_IS_NULL",t[t.OP_IS_NOT_NULL=17]="OP_IS_NOT_NULL",t[t.OP_EQ=18]="OP_EQ",t[t.OP_NE=19]="OP_NE",t[t.OP_GT=20]="OP_GT",t[t.OP_GE=21]="OP_GE",t[t.OP_LT=22]="OP_LT",t[t.OP_LE=23]="OP_LE",t[t.OP_JUMP=24]="OP_JUMP",t[t.OP_STR_LIKE=25]="OP_STR_LIKE",t[t.OP_STR_NOT_LIKE=26]="OP_STR_NOT_LIKE",t[t.OP_STR_CONTAINS=27]="OP_STR_CONTAINS",t[t.OP_STR_STARTS_WITH=28]="OP_STR_STARTS_WITH",t[t.OP_STR_ENDS_WITH=29]="OP_STR_ENDS_WITH",t[t.OP_LOAD_BLOB=30]="OP_LOAD_BLOB",t[t.OP_IN=31]="OP_IN",t[t.OP_LOAD_INT=32]="OP_LOAD_INT",t[t.OP_LOAD_FLOAT=33]="OP_LOAD_FLOAT",t[t.OP_LOAD_TEXT=34]="OP_LOAD_TEXT",t[t.OP_LOAD_NULL=35]="OP_LOAD_NULL",t[t.OP_EMIT_ROW=36]="OP_EMIT_ROW",t[t.OP_RESULT_ROW=37]="OP_RESULT_ROW",t[t.OP_OFFSET=38]="OP_OFFSET",t[t.OP_LIMIT=39]="OP_LIMIT",t[t.OP_CALL_UDF=40]="OP_CALL_UDF",t[t.OP_STR_LOWER=41]="OP_STR_LOWER",t[t.OP_STR_UPPER=42]="OP_STR_UPPER",t[t.OP_STR_LENGTH=43]="OP_STR_LENGTH",t[t.OP_STR_SUBSTR=44]="OP_STR_SUBSTR",t[t.OP_STR_TRIM=45]="OP_STR_TRIM",t[t.OP_MATH_ABS=46]="OP_MATH_ABS",t[t.OP_MATH_ROUND=47]="OP_MATH_ROUND",t[t.OP_SORTER_OPEN=48]="OP_SORTER_OPEN",t[t.OP_SORTER_INSERT=49]="OP_SORTER_INSERT",t[t.OP_SORTER_SORT=50]="OP_SORTER_SORT",t[t.OP_SORTER_NEXT=51]="OP_SORTER_NEXT",t[t.OP_MATH_FLOOR=52]="OP_MATH_FLOOR",t[t.OP_MATH_CEIL=53]="OP_MATH_CEIL",t[t.OP_ADD=54]="OP_ADD",t[t.OP_SUB=55]="OP_SUB",t[t.OP_MUL=56]="OP_MUL",t[t.OP_DIV=57]="OP_DIV",t[t.OP_MOD=58]="OP_MOD",t[t.OP_ENTER_SUBQUERY=59]="OP_ENTER_SUBQUERY",t[t.OP_RETURN_SUBQUERY=60]="OP_RETURN_SUBQUERY",t[t.OP_STR_CONCAT=61]="OP_STR_CONCAT",t[t.OP_COALESCE=62]="OP_COALESCE",t[t.OP_COPY=63]="OP_COPY",t[t.OP_AGG_INIT=64]="OP_AGG_INIT",t[t.OP_AGG_STEP=65]="OP_AGG_STEP",t[t.OP_AGG_NEXT=66]="OP_AGG_NEXT",t[t.OP_AGG_FINAL=67]="OP_AGG_FINAL",t[t.OP_REG_IS_NULL=72]="OP_REG_IS_NULL",t[t.OP_REG_IS_NOT_NULL=73]="OP_REG_IS_NOT_NULL",t[t.OP_DELETE_ROW=80]="OP_DELETE_ROW",t[t.OP_UPDATE_FIELD=81]="OP_UPDATE_FIELD",t[t.OP_INSERT_ROW=82]="OP_INSERT_ROW",t))(d||{}),O=(t=>(t[t.RUNNING=0]="RUNNING",t[t.DONE=1]="DONE",t[t.PAGE_FAULT=2]="PAGE_FAULT",t[t.BUFFER_FULL=3]="BUFFER_FULL",t[t.ERROR=4]="ERROR",t[t.TIMEOUT=5]="TIMEOUT",t[t.ARENA_EXHAUSTED=6]="ARENA_EXHAUSTED",t[t.INVALID_BYTECODE=7]="INVALID_BYTECODE",t))(O||{});class Lo extends Error{constructor(e,n=2048){super(`Row size (${e} bytes) exceeds maximum limit of ${n} bytes`),this.name="RowSizeLimitExceededError"}}class es extends Error{constructor(e,n){super(`NOT NULL constraint failed: ${n?n+".":""}${e}`),this.name="NotNullConstraintError"}}class Ro extends Error{constructor(e,n=64){super(`Identifier "${e}" (${e.length} characters) exceeds maximum limit of ${n} characters`),this.name="IdentifierTooLongError"}}class ns extends Error{constructor(e,n){super(n?`Column "${e}" already exists on table "${n}"`:`Column "${e}" already exists`),this.name="ColumnAlreadyExistsError"}}class Ai extends Error{constructor(e){super(e),this.name="CannotDropColumnError"}}class le extends Error{constructor(e,n){super(n?`Column "${e}" not found on table "${n}"`:`Column "${e}" not found`),this.name="ColumnNotFoundError"}}class Nn extends Error{constructor(e){super(`Table not found: "${e}"`),this.name="TableNotFoundError"}}class ss extends Error{constructor(e){super(`Table already exists: "${e}"`),this.name="TableAlreadyExistsError"}}class Do extends Error{constructor(e){super(`Index not found: "${e}"`),this.name="IndexNotFoundError"}}class fi extends Error{constructor(e){super(`Index already exists: "${e}"`),this.name="IndexAlreadyExistsError"}}class ze extends Error{constructor(e){super(e),this.name="UniqueConstraintViolationError"}}class Ce extends Error{constructor(e,n,s){super(`Corrupted page detected (pageId: ${e}): stored checksum ${n}${s!==void 0?`, computed checksum ${s}`:""}`),this.pageId=e,this.storedChecksum=n,this.computedChecksum=s,this.name="CorruptPageError"}}class Ln extends Error{constructor(e,n=256){super(`Too many columns: ${e} exceeds maximum limit of ${n} columns`),this.name="TooManyColumnsError"}}class _i extends Error{constructor(e,n=16){super(`Too many tables: ${e} exceeds maximum limit of ${n} tables on Page 1`),this.name="TooManyTablesError"}}class Fo extends Error{constructor(e,n=8){super(`Too many indexes: ${e} exceeds maximum limit of ${n} indexes on Page 1`),this.name="TooManyIndexesError"}}class bo extends Error{constructor(e){super(e),this.name="UnsupportedFormatVersionError"}}class Rn extends Error{constructor(e){super(e),this.name="InvalidDatabaseError"}}class gi extends Error{constructor(e="Transient query arena exhausted"){super(e),this.name="QueryArenaExhaustedError"}}class is extends Error{constructor(e,n=16){super(`Too many cursors: ${e} exceeds maximum limit of ${n} cursors`),this.name="TooManyCursorsError"}}class nt extends Error{constructor(e,n=64){super(`Too many registers: ${e} exceeds maximum limit of ${n} registers`),this.name="TooManyRegistersError"}}class _c extends Error{constructor(e,n=7){super(`Subquery nesting depth ${e} exceeds maximum limit of ${n}`),this.name="SubqueryNestingTooDeepError"}}class Qo extends Error{constructor(e="Query execution exceeded maximum cycle limit (TIMEOUT)"){super(e),this.name="QueryTimeoutError"}}class ko extends Error{constructor(e="Malformed bytecode execution halted (INVALID_BYTECODE)"){super(e),this.name="InvalidBytecodeError"}}class vo extends Error{constructor(e,n=8){super(`Too many order by columns: ${e} exceeds maximum limit of ${n}`),this.name="TooManyOrderByColumnsError"}}class Go extends Error{constructor(e,n=8){super(`Too many group by columns: ${e} exceeds maximum limit of ${n}`),this.name="TooManyGroupByColumnsError"}}class hi extends Error{constructor(e){super(`Function "${e}" is neither a native built-in function nor a registered UDF`),this.name="UnknownFunctionError"}}class os extends Error{constructor(e){super(`Aggregate function "${e}" cannot be used in WHERE clause`),this.name="AggregateNotAllowedInWhereError"}}class rs extends Error{constructor(e="Corrupted WAL file header detected"){super(e),this.name="CorruptWalHeaderError"}}class Dn extends Error{constructor(e="Corrupted WAL frame detected"){super(e),this.name="CorruptWalFrameError"}}class Mo{constructor(){S(this,"name","memory");S(this,"isSynchronous",!0);S(this,"pages",new Map);S(this,"walHeader",null);S(this,"walFrames",[])}async readPage(e){const n=this.pages.get(e);return n?new Uint8Array(n):null}async writePage(e,n){const s=new Uint8Array(n.byteLength);s.set(n),this.pages.set(e,s)}async writePages(e){for(const{pageId:n,data:s}of e)await this.writePage(n,s)}async flush(){}async truncate(e){for(const n of Array.from(this.pages.keys()))n>e&&this.pages.delete(n)}snapshot(){const e=new Map;for(const[n,s]of this.pages.entries())e.set(n,new Uint8Array(s));return e}restoreSnapshot(e){this.pages.clear();for(const[n,s]of e.entries())this.pages.set(n,new Uint8Array(s))}async readWalHeader(){return this.walHeader?new Uint8Array(this.walHeader):null}async writeWalHeader(e){const n=new Uint8Array(e.byteLength);n.set(e),this.walHeader=n}async readWalFrame(e){const n=this.walFrames[e];return n?new Uint8Array(n):null}async readWalFrames(e,n){const s=n!==void 0?e+n:this.walFrames.length;return this.walFrames.slice(e,s).map(o=>new Uint8Array(o))}async appendWalFrames(e){for(const n of e){const s=new Uint8Array(n.byteLength);s.set(n),this.walFrames.push(s)}}async flushWal(){}async truncateWal(e){e===0?(this.walFrames=[],this.walHeader=null):this.walFrames.length=Math.min(this.walFrames.length,e)}async getWalFrameCount(){return this.walFrames.length}async close(){}}class Ho{constructor(e){S(this,"name","idb");S(this,"isSynchronous",!1);S(this,"dbName");S(this,"dbPromise",null);this.dbName=`webdb_${e}`}getDb(){return this.dbPromise||(this.dbPromise=new Promise((e,n)=>{const s=globalThis.indexedDB;if(!s){n(new Error("IndexedDB is not available in the current environment"));return}const i=s.open(this.dbName,1);i.onupgradeneeded=()=>{const o=i.result;o.objectStoreNames.contains("pages")||o.createObjectStore("pages"),o.objectStoreNames.contains("wal_frames")||o.createObjectStore("wal_frames"),o.objectStoreNames.contains("wal_meta")||o.createObjectStore("wal_meta")},i.onsuccess=()=>e(i.result),i.onerror=()=>n(i.error)})),this.dbPromise}async readPage(e){const n=await this.getDb();return new Promise((s,i)=>{const a=n.transaction("pages","readonly").objectStore("pages").get(e);a.onsuccess=()=>{const l=a.result;s(l?l instanceof Uint8Array?l:new Uint8Array(l):null)},a.onerror=()=>i(a.error)})}async writePage(e,n){const s=await this.getDb();return new Promise((i,o)=>{const r=s.transaction("pages","readwrite"),a=r.objectStore("pages"),l=new Uint8Array(n.byteLength);l.set(n),a.put(l,e),r.oncomplete=()=>i(),r.onerror=()=>o(r.error),r.onabort=()=>o(r.error)})}async writePages(e){if(e.length===0)return;const n=await this.getDb();return new Promise((s,i)=>{const o=n.transaction("pages","readwrite"),r=o.objectStore("pages");for(const{pageId:a,data:l}of e){const c=new Uint8Array(l.byteLength);c.set(l),r.put(c,a)}o.oncomplete=()=>s(),o.onerror=()=>i(o.error),o.onabort=()=>i(o.error)})}async flush(){}async truncate(e){const n=await this.getDb();return new Promise((s,i)=>{const r=n.transaction("pages","readwrite").objectStore("pages"),a=IDBKeyRange.lowerBound(e,!0),l=r.delete(a);l.onsuccess=()=>s(),l.onerror=()=>i(l.error)})}async readWalHeader(){const e=await this.getDb();return new Promise((n,s)=>{const r=e.transaction("wal_meta","readonly").objectStore("wal_meta").get("header");r.onsuccess=()=>{const a=r.result;n(a?a instanceof Uint8Array?a:new Uint8Array(a):null)},r.onerror=()=>s(r.error)})}async writeWalHeader(e){const n=await this.getDb();return new Promise((s,i)=>{const o=n.transaction("wal_meta","readwrite"),r=o.objectStore("wal_meta"),a=new Uint8Array(e.byteLength);a.set(e),r.put(a,"header"),o.oncomplete=()=>s(),o.onerror=()=>i(o.error),o.onabort=()=>i(o.error)})}async readWalFrame(e){const n=await this.getDb();return new Promise((s,i)=>{const a=n.transaction("wal_frames","readonly").objectStore("wal_frames").get(e);a.onsuccess=()=>{const l=a.result;s(l?l instanceof Uint8Array?l:new Uint8Array(l):null)},a.onerror=()=>i(a.error)})}async readWalFrames(e,n){const s=await this.getDb();return new Promise((i,o)=>{const a=s.transaction("wal_frames","readonly").objectStore("wal_frames"),l=[],c=n!==void 0?IDBKeyRange.bound(e,e+n-1):IDBKeyRange.lowerBound(e,!1),u=a.openCursor(c);u.onsuccess=()=>{const h=u.result;if(h){const f=h.value;l.push(f instanceof Uint8Array?f:new Uint8Array(f)),h.continue()}else i(l)},u.onerror=()=>o(u.error)})}async appendWalFrames(e){if(e.length===0)return;const n=await this.getDb();return new Promise((s,i)=>{const o=n.transaction("wal_frames","readwrite"),r=o.objectStore("wal_frames"),a=r.count();a.onsuccess=()=>{let l=a.result;for(const c of e){const u=new Uint8Array(c.byteLength);u.set(c),r.put(u,l++)}},o.oncomplete=()=>s(),o.onerror=()=>i(o.error),o.onabort=()=>i(o.error)})}async flushWal(){}async truncateWal(e){const n=await this.getDb();return new Promise((s,i)=>{const o=n.transaction(["wal_frames","wal_meta"],"readwrite"),r=o.objectStore("wal_frames"),a=o.objectStore("wal_meta");if(e===0)r.clear(),a.delete("header");else{const l=IDBKeyRange.lowerBound(e,!1);r.delete(l)}o.oncomplete=()=>s(),o.onerror=()=>i(o.error),o.onabort=()=>i(o.error)})}async getWalFrameCount(){const e=await this.getDb();return new Promise((n,s)=>{const r=e.transaction("wal_frames","readonly").objectStore("wal_frames").count();r.onsuccess=()=>n(r.result),r.onerror=()=>s(r.error)})}async close(){this.dbPromise&&((await this.dbPromise).close(),this.dbPromise=null)}}class Wo{constructor(e){S(this,"name","opfs");S(this,"isSynchronous");S(this,"dbName");S(this,"rootDir",null);S(this,"dbFileHandle",null);S(this,"walFileHandle",null);S(this,"dbSyncHandle",null);S(this,"walSyncHandle",null);this.dbName=e,this.isSynchronous=typeof globalThis.FileSystemSyncAccessHandle<"u"}async initHandles(){var e;if(!this.rootDir){if(!((e=navigator==null?void 0:navigator.storage)!=null&&e.getDirectory))throw new Error("OPFS (Origin Private File System) is not available in the current environment");if(this.rootDir=await navigator.storage.getDirectory(),this.dbFileHandle=await this.rootDir.getFileHandle(`${this.dbName}.db`,{create:!0}),this.walFileHandle=await this.rootDir.getFileHandle(`${this.dbName}.wal`,{create:!0}),this.isSynchronous)try{this.dbSyncHandle=await this.dbFileHandle.createSyncAccessHandle(),this.walSyncHandle=await this.walFileHandle.createSyncAccessHandle()}catch{}}}async readPage(e){await this.initHandles();const n=(e-1)*4096;if(this.dbSyncHandle){const r=this.dbSyncHandle.getSize();if(n+4096>r)return null;const a=new Uint8Array(4096);return this.dbSyncHandle.read(a,{at:n}),a}const s=await this.dbFileHandle.getFile();if(n+4096>s.size)return null;const o=await s.slice(n,n+4096).arrayBuffer();return new Uint8Array(o)}async writePage(e,n){await this.initHandles();const s=(e-1)*4096;if(this.dbSyncHandle){this.dbSyncHandle.write(n,{at:s});return}const i=await this.dbFileHandle.createWritable({keepExistingData:!0});await i.seek(s),await i.write(n),await i.close()}async writePages(e){for(const{pageId:n,data:s}of e)await this.writePage(n,s)}async flush(){this.dbSyncHandle&&this.dbSyncHandle.flush()}async truncate(e){await this.initHandles();const n=e*4096;if(this.dbSyncHandle){this.dbSyncHandle.truncate(n);return}const s=await this.dbFileHandle.createWritable({keepExistingData:!0});await s.truncate(n),await s.close()}async readWalHeader(){if(await this.initHandles(),this.walSyncHandle){if(this.walSyncHandle.getSize()<32)return null;const i=new Uint8Array(32);return this.walSyncHandle.read(i,{at:0}),i}const e=await this.walFileHandle.getFile();if(e.size<32)return null;const n=e.slice(0,32);return new Uint8Array(await n.arrayBuffer())}async writeWalHeader(e){if(await this.initHandles(),this.walSyncHandle){this.walSyncHandle.write(e,{at:0});return}const n=await this.walFileHandle.createWritable({keepExistingData:!0});await n.seek(0),await n.write(e),await n.close()}async readWalFrame(e){await this.initHandles();const n=32+e*4128;if(this.walSyncHandle){const r=this.walSyncHandle.getSize();if(n>=r)return null;const a=Math.min(4128,r-n),l=new Uint8Array(a);return this.walSyncHandle.read(l,{at:n}),l}const s=await this.walFileHandle.getFile();if(n>=s.size)return null;const i=Math.min(4128,s.size-n),o=s.slice(n,n+i);return new Uint8Array(await o.arrayBuffer())}async readWalFrames(e,n){const s=[];let i=e;const o=n!==void 0?e+n:1/0;for(;i<o;){const r=await this.readWalFrame(i);if(!r)break;s.push(r),i++}return s}async appendWalFrames(e){if(await this.initHandles(),this.walSyncHandle){let i=Math.max(32,this.walSyncHandle.getSize());for(const o of e)this.walSyncHandle.write(o,{at:i}),i+=o.byteLength;return}const n=await this.walFileHandle.getFile(),s=await this.walFileHandle.createWritable({keepExistingData:!0});await s.seek(Math.max(32,n.size));for(const i of e)await s.write(i);await s.close()}async flushWal(){this.walSyncHandle&&this.walSyncHandle.flush()}async truncateWal(e){await this.initHandles();const n=e===0?0:32+e*4128;if(this.walSyncHandle){this.walSyncHandle.truncate(n);return}const s=await this.walFileHandle.createWritable({keepExistingData:e>0});await s.truncate(n),await s.close()}async getWalFrameCount(){await this.initHandles();let e=0;return this.walSyncHandle?e=this.walSyncHandle.getSize():e=(await this.walFileHandle.getFile()).size,e<=32?0:Math.ceil((e-32)/4128)}async close(){this.dbSyncHandle&&(this.dbSyncHandle.close(),this.dbSyncHandle=null),this.walSyncHandle&&(this.walSyncHandle.close(),this.walSyncHandle=null),this.dbFileHandle=null,this.walFileHandle=null,this.rootDir=null}}const tn=new Uint32Array(256);for(let t=0;t<256;t++){let e=t;for(let n=0;n<8;n++)e=e&1?3988292384^e>>>1:e>>>1;tn[t]=e>>>0}function di(t,e=0,n=t.byteLength-e){let s=4294967295;const i=e+n;for(let o=e;o<i;o++)s=tn[(s^t[o])&255]^s>>>8;return(s^4294967295)>>>0}function Ge(t){let e=4294967295;for(let n=0;n<4096;n++){const s=n>=12&&n<=15?0:t[n];e=tn[(e^s)&255]^e>>>8}return(e^4294967295)>>>0}function Ei(t){let e=4294967295;for(let n=0;n<4096;n++){const s=n>=28&&n<=31?0:t[n];e=tn[(e^s)&255]^e>>>8}return(e^4294967295)>>>0}function as(t){let e=4294967295;for(let s=0;s<24;s++)e=tn[(e^t[s])&255]^e>>>8;const n=Math.min(t.byteLength,4128);for(let s=32;s<n;s++)e=tn[(e^t[s])&255]^e>>>8;return(e^4294967295)>>>0}function en(t,e,n,s,i){const o=t instanceof Uint8Array?t:new Uint8Array(t.buffer,t.byteOffset,t.byteLength),r=n instanceof Uint8Array?n:new Uint8Array(n.buffer,n.byteOffset,n.byteLength);o.set(r.subarray(s,s+i),e)}function ne(t,e,n,s){(t instanceof Uint8Array?t:new Uint8Array(t.buffer,t.byteOffset,t.byteLength)).fill(n&255,e,e+s)}function gc(t,e,n,s,i){const o=t instanceof Uint8Array?t:new Uint8Array(t.buffer,t.byteOffset,t.byteLength),r=n instanceof Uint8Array?n:new Uint8Array(n.buffer,n.byteOffset,n.byteLength);for(let a=0;a<i;a++){const l=o[e+a]-r[s+a];if(l!==0)return l}return 0}function cs(t){return t.length}function Vo(t,e){return t instanceof Uint8Array?t[e]:t.getUint8(e)}function hc(t,e,n){t instanceof Uint8Array?t[e]=n&255:t.setUint8(e,n&255)}function ls(t,e){return t.getUint16(e,!0)}function us(t,e,n){t.setUint16(e,n&65535,!0)}function pt(t,e){return t.getUint32(e,!0)}function yt(t,e,n){t.setUint32(e,n>>>0,!0)}function dc(t,e){return t.getInt32(e,!0)}function Ec(t,e,n){t.setInt32(e,n|0,!0)}function mc(t,e){return t.getFloat64(e,!0)}function Ic(t,e,n){t.setFloat64(e,n,!0)}function pc(t,e){return t.getBigUint64(e,!0)}function yc(t,e,n){t.setBigUint64(e,n,!0)}function Tc(t,e){return t.getBigInt64(e,!0)}function Cc(t,e,n){t.setBigInt64(e,n,!0)}function $o(t,e,n){return n!==void 0?t[e+(n>>3)]&1<<(n&7)?1:0:t[e>>3]&1<<(e&7)?1:0}function Xo(t,e,n){n!==void 0?t[e+(n>>3)]|=1<<(n&7):t[e>>3]|=1<<(e&7)}function Yo(t,e,n){n!==void 0?t[e+(n>>3)]&=~(1<<(n&7)):t[e>>3]&=~(1<<(e&7))}function Zo(t,e){if(!t)throw new Error(`Assertion failed: ${e}`)}class mi{constructor(e){S(this,"vfs");S(this,"buffer");S(this,"uint8");S(this,"view");S(this,"in_flight_flushes",new Map);S(this,"in_flight_reads",new Map);S(this,"coordinator",null);if(!e.vfs)throw new Error("Io requires a valid IVfsAdapter instance");if(!e.memory)throw new Error("Io requires a valid memory buffer or WebAssembly.Memory");this.vfs=e.vfs,this.buffer=e.memory instanceof WebAssembly.Memory?e.memory.buffer:e.memory,this.uint8=new Uint8Array(this.buffer),this.view=new DataView(this.buffer)}setTransactionCoordinator(e){this.coordinator=e}isInTransaction(){return this.coordinator?this.coordinator.isInTransaction():!1}stampSlotChecksum(e,n){const s=e*4096,i=this.uint8.subarray(s,s+4096);if(n===1){const o=Ei(i);yt(this.view,s+Ie,o)}else{const o=Ge(i);yt(this.view,s+Re,o)}}async readSlot(e,n){if(n<=0)throw new Error(`Invalid page ID: ${n}. Page IDs must be positive integers.`);if(this.coordinator&&this.coordinator.hasSpilledPage(n)){const r=e*4096,a=this.coordinator.getSpilledPage(n);this.uint8.set(a,r);return}const s=this.in_flight_flushes.get(n);s&&await s;const i=this.in_flight_reads.get(n);if(i){await i;return}const o=(async()=>{const r=await this.vfs.readPage(n),a=e*4096;if(r){if(r.byteLength!==4096)throw new Ce(n,`Unexpected page byte length: ${r.byteLength}, expected 4096`);const l=n===1?Ie:Re,c=pt(new DataView(r.buffer,r.byteOffset),l);if(c!==0){const u=n===1?Ei(r):Ge(r);if(u!==c)throw new Ce(n,c,u)}this.uint8.set(r,a)}else this.uint8.fill(0,a,a+4096)})();this.in_flight_reads.set(n,o);try{await o}finally{this.in_flight_reads.delete(n)}}async writeSlot(e,n){if(n<=0)throw new Error(`Invalid page ID: ${n}. Page IDs must be positive integers.`);const s=this.in_flight_flushes.get(n);if(s){await s;return}const i=e*4096,o=this.uint8.subarray(i,i+4096);this.stampSlotChecksum(e,n);const r=o.slice();this.coordinator&&this.coordinator.onDirectPageWrite(n,r);const a=this.vfs.writePage(n,r);this.in_flight_flushes.set(n,a);try{await a}finally{this.in_flight_flushes.delete(n)}}async spillOrWriteSlot(e,n){this.coordinator&&this.coordinator.isInTransaction()?await this.coordinator.spillUncommittedSlot(e,n):await this.writeSlot(e,n)}async resolvePageFault(e,n,s){if(s>0&&(this.coordinator&&this.coordinator.isInTransaction()?await this.coordinator.spillUncommittedSlot(e,s):await this.writeSlot(e,s)),this.coordinator&&this.coordinator.hasSpilledPage(n)){const i=e*4096,o=this.coordinator.getSpilledPage(n);this.uint8.set(o,i)}else await this.readSlot(e,n)}async flush(){await this.vfs.flush()}}const Ii=new Uint8Array([87,69,66,87,65,76]);function As(t={}){const e=new Uint8Array(Kn),n=new DataView(e.buffer,e.byteOffset,e.byteLength);e.set(Ii,xs),us(n,js,t.walVersion??To),yt(n,Ks,t.pageSize??Te),yt(n,Js,t.checkpointSeq??0);const s=t.salt1??Math.floor(Math.random()*4294967295)>>>0;yt(n,zs,s);const i=t.salt2??Math.floor(Math.random()*4294967295)>>>0;yt(n,ti,i);const o=t.checksum??di(e,0,24);return yt(n,ei,o),yt(n,Co,0),e}function fs(t,e=!0){if(t.byteLength<Kn)throw new rs(`Truncated WAL file header: expected at least ${Kn} bytes, received ${t.byteLength}`);for(let c=0;c<6;c++)if(t[xs+c]!==Ii[c])throw new rs('Invalid WAL file header magic identifier (expected "WEBWAL")');const n=new DataView(t.buffer,t.byteOffset,t.byteLength),s=ls(n,js),i=pt(n,Ks),o=pt(n,Js),r=pt(n,zs),a=pt(n,ti),l=pt(n,ei);if(e){const c=di(t,0,24);if(l!==c)throw new rs(`WAL file header CRC32 checksum mismatch: stored ${l}, computed ${c}`)}return{walVersion:s,pageSize:i,checkpointSeq:o,salt1:r,salt2:a,checksum:l}}function _s(t,e){const n=new Uint8Array(Je),s=new DataView(n.buffer,n.byteOffset,n.byteLength);yt(s,ni,t.magic??On),us(s,si,t.frameType),us(s,ii,t.flags??0),yt(s,oi,t.txId),yt(s,ri,t.pageId),yt(s,ai,t.dbSizePages??0),yt(s,ci,t.frameSeq),yt(s,wo,0),e&&n.set(e.subarray(0,Te),ke);const i=t.checksum??as(n);return yt(s,li,i),n}function pi(t){if(t.byteLength<ke)throw new Dn(`Truncated WAL frame header: expected at least ${ke} bytes, received ${t.byteLength}`);const e=new DataView(t.buffer,t.byteOffset,t.byteLength);return{magic:pt(e,ni),frameType:ls(e,si),flags:ls(e,ii),txId:pt(e,oi),pageId:pt(e,ri),dbSizePages:pt(e,ai),frameSeq:pt(e,ci),checksum:pt(e,li)}}function yi(t){if(t.byteLength<Je)return{valid:!1,reason:"truncated"};const e=pi(t);if(e.magic!==On)return{valid:!1,reason:"magic_mismatch",header:e};const n=as(t);return e.checksum!==n?{valid:!1,reason:"checksum_mismatch",header:e}:{valid:!0,header:e}}function wc(t,e=!0){if(t.byteLength<Je)throw new Dn(`Truncated WAL frame: expected ${Je} bytes, received ${t.byteLength}`);const n=pi(t);if(n.magic!==On)throw new Dn(`Invalid WAL frame magic: expected 0x${On.toString(16)}, got 0x${n.magic.toString(16)}`);if(e){const i=as(t);if(n.checksum!==i)throw new Dn(`WAL frame CRC32 checksum mismatch: stored ${n.checksum}, computed ${i}`)}const s=t.subarray(ke,Je);return{header:n,pageData:s}}const qo=new TextDecoder,xo="0123456789abcdef",Ti="0123456789ABCDEFGHJKMNPQRSTVWXYZ";function Uc(t){return t>=48&&t<=57?t-48:t>=97&&t<=102?t-97+10:t>=65&&t<=70?t-65+10:-1}function Ci(t){if(t>=48&&t<=57)return t-48;switch(t>=97&&t<=122&&(t=t-32),t){case 65:return 10;case 66:return 11;case 67:return 12;case 68:return 13;case 69:return 14;case 70:return 15;case 71:return 16;case 72:return 17;case 74:return 18;case 75:return 19;case 77:return 20;case 78:return 21;case 80:return 22;case 81:return 23;case 82:return 24;case 83:return 25;case 84:return 26;case 86:return 27;case 87:return 28;case 88:return 29;case 89:return 30;case 90:return 31;case 73:case 76:return 1;case 79:return 0;default:return-1}}function Sc(t,e,n){let s=0,i=-1;for(let o=0;o<cs(t);o++){const r=t.charCodeAt(o);if(r!==45){if(s>=32)return-1;const a=Uc(r);if(a<0)return-1;s%2===0?i=a:e[n+(s>>1)]=i<<4|a,s++}}return s!==32?-1:0}function Oc(t,e,n){let s=0;for(let i=0;i<16;i++){(i===4||i===6||i===8||i===10)&&(n[s++]=45);const o=t[e+i];n[s++]=xo.charCodeAt(o>>4&15),n[s++]=xo.charCodeAt(o&15)}n[s]=0}class nn{static encode(e,n,s=0){if(Sc(e,n,s)!==0)throw new Error(`Invalid UUID format: "${e}" (must be 36 characters with hyphens)`)}static decode(e,n=0){const s=new Uint8Array(37);return Oc(e,n,s),qo.decode(s.subarray(0,36))}}function Pc(t,e,n){if(cs(t)!==26)return-1;let s=0n;for(let r=0;r<10;r++){const a=Ci(t.charCodeAt(r));if(a<0)return-1;s=s<<5n|BigInt(a)}e[n+0]=Number(s>>40n&0xffn),e[n+1]=Number(s>>32n&0xffn),e[n+2]=Number(s>>24n&0xffn),e[n+3]=Number(s>>16n&0xffn),e[n+4]=Number(s>>8n&0xffn),e[n+5]=Number(s&0xffn);let i=0n;for(let r=10;r<18;r++){const a=Ci(t.charCodeAt(r));if(a<0)return-1;i=i<<5n|BigInt(a)}let o=0n;for(let r=18;r<26;r++){const a=Ci(t.charCodeAt(r));if(a<0)return-1;o=o<<5n|BigInt(a)}for(let r=0;r<5;r++)e[n+6+r]=Number(i>>BigInt((4-r)*8)&0xffn),e[n+11+r]=Number(o>>BigInt((4-r)*8)&0xffn);return 0}function Bc(t,e,n){let s=0n;for(let r=0;r<6;r++)s=s<<8n|BigInt(t[e+r]);for(let r=9;r>=0;r--)n[r]=Ti.charCodeAt(Number(s%32n)),s/=32n;let i=0n;for(let r=0;r<5;r++)i=i<<8n|BigInt(t[e+6+r]);let o=0n;for(let r=0;r<5;r++)o=o<<8n|BigInt(t[e+11+r]);for(let r=25;r>=18;r--)n[r]=Ti.charCodeAt(Number(o&31n)),o>>=5n;for(let r=17;r>=10;r--)n[r]=Ti.charCodeAt(Number(i&31n)),i>>=5n;n[26]=0}class sn{static encode(e,n,s=0){if(Pc(e,n,s)!==0)throw new Error(`Invalid ULID length: "${e}" (must be 26 Crockford Base32 characters)`)}static decode(e,n=0){const s=new Uint8Array(27);return Bc(e,n,s),qo.decode(s.subarray(0,26))}}const wi=new TextEncoder,gs=new TextDecoder;function Fn(t,e,n=ts,s=0){t.setUint8(e+0,n),t.setUint8(e+1,0),t.setUint16(e+2,0,!0),t.setUint16(e+4,4096,!0),t.setUint32(e+6,s,!0),t.setUint16(e+10,0,!0),t.setUint32(e+Re,0,!0)}function jo(t,e,n=0){t.setUint8(e+0,ve),t.setUint8(e+1,0),t.setUint16(e+2,0,!0),t.setUint16(e+4,0,!0),t.setUint32(e+6,n,!0),t.setUint16(e+10,0,!0),t.setUint32(e+Re,0,!0)}function Me(t,e){return t.getUint8(e+0)}function Nc(t,e,n){t.setUint8(e+0,n)}function lt(t,e){return t.getUint16(e+2,!0)}function He(t,e,n){t.setUint16(e+2,n,!0)}function We(t,e){return t.getUint16(e+4,!0)}function Ve(t,e,n){t.setUint16(e+4,n,!0)}function Ut(t,e){return t.getUint32(e+6,!0)}function hs(t,e,n){t.setUint32(e+6,n,!0)}function we(t,e){return t.getUint16(e+10,!0)}function $e(t,e,n){t.setUint16(e+10,n,!0)}function Lc(t,e){return t.getUint32(e+Re,!0)}function Rc(t,e,n){t.setUint32(e+Re,n,!0)}function ot(t,e,n){const s=e+qt+n*2;return t.getUint16(s,!0)}function on(t,e,n,s){const i=e+qt+n*2;t.setUint16(i,s,!0)}function ds(t,e){const n=lt(t,e),s=We(t,e),i=qt+n*2;return s-i}function Ko(t,e){return ds(t,e)+we(t,e)}function bn(t,e,n=0,s){const i=lt(t,e);if(i===0){Ve(t,e,4096),$e(t,e,0);return}let o=t,r=n;if(n===0||n===e||n+4096>t.byteLength){const l=new Uint8Array(4096);o=new DataView(l.buffer),r=0}en(o,r,t,e,qt);let a=4096;for(let l=0;l<i;l++){let c=0,u=t,h=0;if(s&&l===s.cell_idx)c=s.row_bytes.byteLength,u=s.row_bytes,h=0;else{const f=ot(t,e,l);Me(t,e)===zn?c=2+t.getUint16(e+f,!0)+8:c=Es(t,e+f),u=t,h=e+f}a=a-c,en(o,r+a,u,h,c),on(o,r,l,a)}Ve(o,r,a),$e(o,r,0),en(t,e,o,r,4096)}function Es(t,e){return t.getUint16(e+1,!0)}function rn(t,e,n,s){const i=lt(t,e),o=We(t,e),r=n.byteLength+2,a=qt+i*2,l=o-a,c=l+we(t,e);if(r>c)return-1;r>l&&bn(t,e,s);const u=We(t,e),h=lt(t,e),f=u-n.byteLength,_=t.byteOffset+e+f;return new Uint8Array(t.buffer).set(n,_),on(t,e,h,f),He(t,e,h+1),Ve(t,e,f),h}function Jo(t,e,n){const s=lt(t,e);if(n>=s)return;const i=ot(t,e,n),o=Es(t,e+i),r=e+qt,a=r+(n+1)*2,l=r+n*2,c=(s-1-n)*2;c>0&&en(t,l,t,a,c),He(t,e,s-1),$e(t,e,we(t,e)+o)}function Ui(t,e,n,s,i){const o=lt(t,e);if(n<0||n>=o)throw new Error(`Invalid cell index ${n} for update`);const r=ot(t,e,n),a=Es(t,e+r),l=s.byteLength,c=new Uint8Array(t.buffer);if(l<=a)return c.set(s,t.byteOffset+e+r),l<a&&$e(t,e,we(t,e)+(a-l)),!0;const u=Ko(t,e),h=l-a;if(u>=h){if(ds(t,e)<l)return bn(t,e,i,{cell_idx:n,row_bytes:s}),!0;$e(t,e,we(t,e)+a);const g=We(t,e)-l;return c.set(s,t.byteOffset+e+g),on(t,e,n,g),Ve(t,e,g),!0}return!1}function Dc(t){const e=Array.isArray(t)?t:t.columns,n=Math.ceil(e.length/8);let s=0,i=0;for(let o=0;o<e.length;o++){const r=e[o];r.type===C.INT32?s+=4:r.type===C.INT64||r.type===C.FLOAT64?s+=8:r.type===C.UUID||r.type===C.ULID?s+=16:(r.type===C.TEXT||r.type===C.BLOB)&&i++}return{null_bitmap_bytes:n,fixed_slice_size:s,var_col_count:i}}function ms(t,e){const n=Array.isArray(t)?t:t.columns,s=n.length;if(s>ce)throw new Ln(s,ce);const i=Math.ceil(s/8),o=new Uint8Array(i);for(let p=0;p<s;p++){const y=n[p],T=e[y.name];if(T==null){if(y.flags&z.NOT_NULL)throw new es(y.name);const L=p>>3,P=1<<(p&7);o[L]|=P}}let r=0;for(let p=0;p<s;p++){const y=n[p];if(!((o[p>>3]&1<<(p&7))!==0))switch(y.type){case C.INT32:r+=4;break;case C.INT64:case C.FLOAT64:r+=8;break;case C.UUID:case C.ULID:r+=16;break}}const a=[];for(let p=0;p<s;p++){const y=n[p];if(y.type===C.TEXT||y.type===C.BLOB)if((o[p>>3]&1<<(p&7))!==0)a.push({col_idx:p,col:y,payload:null});else{const B=e[y.name];let L;y.type===C.TEXT?L=wi.encode(String(B??"")):L=B instanceof Uint8Array?B:new Uint8Array(B),a.push({col_idx:p,col:y,payload:L})}}const l=a.length*4,c=3+i+r+l;let u=0;for(let p=0;p<a.length;p++){const y=a[p];y.payload&&(u+=y.payload.byteLength)}const h=c+u;if(h>2048)throw new Lo(h,2048);const f=new Uint8Array(h),_=new DataView(f.buffer);_.setUint8(0,1),_.setUint16(1,h,!0),f.set(o,3);let g=3+i;for(let p=0;p<s;p++){const y=n[p];if(!((o[p>>3]&1<<(p&7))!==0)){const B=e[y.name];switch(y.type){case C.INT32:_.setInt32(g,Number(B),!0),g+=4;break;case C.INT64:_.setBigInt64(g,BigInt(B),!0),g+=8;break;case C.FLOAT64:_.setFloat64(g,Number(B),!0),g+=8;break;case C.UUID:nn.encode(String(B),f,g),g+=16;break;case C.ULID:sn.encode(String(B),f,g),g+=16;break}}}let E=g,I=c;for(let p=0;p<a.length;p++){const y=a[p];y.payload===null?(_.setUint16(E,0,!0),_.setUint16(E+2,0,!0)):(_.setUint16(E,I,!0),_.setUint16(E+2,y.payload.byteLength,!0),f.set(y.payload,I),I+=y.payload.byteLength),E+=4}return f}function Xe(t,e,n){let s,i,o;if(t instanceof DataView){i=t,o=e;const g=n;s=Array.isArray(g)?g:g.columns}else s=Array.isArray(t)?t:t.columns,i=e,o=n;const r={},a=s.length,l=Math.ceil(a/8),c=new Uint8Array(i.buffer,i.byteOffset+o+3,l);let u=o+3+l,h=0;const f=u;for(let g=0;g<a;g++){const E=s[g];if(!((c[g>>3]&1<<(g&7))!==0))switch(E.type){case C.INT32:u+=4;break;case C.INT64:case C.FLOAT64:u+=8;break;case C.UUID:case C.ULID:u+=16;break}}const _=u;u=f;for(let g=0;g<a;g++){const E=s[g];if((c[g>>3]&1<<(g&7))!==0){r[E.name]=null,(E.type===C.TEXT||E.type===C.BLOB)&&h++;continue}switch(E.type){case C.INT32:r[E.name]=i.getInt32(u,!0),u+=4;break;case C.INT64:r[E.name]=i.getBigInt64(u,!0),u+=8;break;case C.FLOAT64:r[E.name]=i.getFloat64(u,!0),u+=8;break;case C.UUID:{const p=new Uint8Array(i.buffer,i.byteOffset+u,16);r[E.name]=nn.decode(p,0),u+=16;break}case C.ULID:{const p=new Uint8Array(i.buffer,i.byteOffset+u,16);r[E.name]=sn.decode(p,0),u+=16;break}case C.TEXT:{const p=_+h*4,y=i.getUint16(p,!0),T=i.getUint16(p+2,!0),B=i.byteOffset+o+y,L=new Uint8Array(i.buffer,B,T);r[E.name]=gs.decode(L),h++;break}case C.BLOB:{const p=_+h*4,y=i.getUint16(p,!0),T=i.getUint16(p+2,!0),B=i.byteOffset+o+y,L=new Uint8Array(T);L.set(new Uint8Array(i.buffer,B,T)),r[E.name]=L,h++;break}}}return r}function zo(t,e,n=0){Fn(t,e,ui,n)}function Is(t,e){return t.getUint32(e+6,!0)}function tr(t,e,n){t.setUint32(e+6,n,!0)}function er(t,e,n,s){const i=lt(t,e);if(i>=ao)return-1;const r=We(t,e)-ro,a=e+r;return t.setUint32(a,n,!0),t.setBigInt64(a+4,s,!0),on(t,e,i,r),He(t,e,i+1),Ve(t,e,r),i+1}function Fc(t,e,n){const s=lt(t,e);if(s===0)return Is(t,e);let i=0,o=s-1,r=-1;for(;i<=o;){const a=i+o>>1,l=ot(t,e,a),c=t.getBigInt64(e+l+4,!0);n<=c?(r=t.getUint32(e+l,!0),o=a-1):i=a+1}return r!==-1?r:Is(t,e)}function bc(t,e,n){const s=lt(t,e),i=co;if(s<=i)throw new Error(`Cannot split interior page with only ${s} cells`);const o=ot(t,e,i),r=t.getUint32(e+o,!0),a=t.getBigInt64(e+o+4,!0),l=Is(t,e);zo(t,n,l);for(let c=i+1;c<s;c++){const u=ot(t,e,c),h=t.getUint32(e+u,!0),f=t.getBigInt64(e+u+4,!0);er(t,n,h,f)}return tr(t,e,r),He(t,e,i),{median_rowid:a,promoted_child_page_id:r,right_child_page_id:l}}function ps(t,e,n=0){Fn(t,e,zn,n)}function ys(t,e,n,s,i,o){if(t!==s)return t-s;if(t===C.NULL)return n<o?-1:n>o?1:0;let r=0;if(t===C.INT32||t===C.INT64||t===C.FLOAT64){const a=typeof e=="bigint"?Number(e):e,l=typeof i=="bigint"?Number(i):i;r=a<l?-1:a>l?1:0}else if(t===C.TEXT||t===C.UUID||t===C.ULID){const a=String(e),l=String(i);r=a<l?-1:a>l?1:0}else if(t===C.BLOB){const a=e,l=i,c=Math.min(a.length,l.length);for(let u=0;u<c;u++)if(a[u]!==l[u]){r=a[u]<l[u]?-1:1;break}r===0&&(r=a.length-l.length)}return r!==0?r:n<o?-1:n>o?1:0}function Si(t,e,n,s){const i=new Uint8Array(t.buffer,t.byteOffset+e,n);return n===0?{cellType:C.NULL,cellVal:null}:s===C.TEXT?n===4&&(i[2]===0&&i[3]===0||i[2]===255&&i[3]===255)?{cellType:C.INT32,cellVal:new DataView(i.buffer,i.byteOffset).getInt32(0,!0)}:n===2&&i[0]<32&&i[1]<32?{cellType:C.BLOB,cellVal:i}:{cellType:C.TEXT,cellVal:gs.decode(i)}:n===2?{cellType:C.BLOB,cellVal:i}:n===4?{cellType:C.INT32,cellVal:new DataView(i.buffer,i.byteOffset).getInt32(0,!0)}:s===C.UUID&&n===16?{cellType:C.UUID,cellVal:nn.decode(i,0)}:s===C.ULID&&n===16?{cellType:C.ULID,cellVal:sn.decode(i,0)}:s===C.FLOAT64&&n===8?{cellType:C.FLOAT64,cellVal:new DataView(i.buffer,i.byteOffset).getFloat64(0,!0)}:s===C.INT64&&n===8?{cellType:C.INT64,cellVal:new DataView(i.buffer,i.byteOffset).getBigInt64(0,!0)}:s===C.BLOB?n===5||n===6?{cellType:C.TEXT,cellVal:gs.decode(i)}:{cellType:C.BLOB,cellVal:i}:{cellType:C.TEXT,cellVal:gs.decode(i)}}function Oi(t,e,n,s,i,o){let r;n===C.NULL||s===null||s===void 0?r=new Uint8Array(0):n===C.INT32?(r=new Uint8Array(4),new DataView(r.buffer).setInt32(0,Number(s),!0)):n===C.INT64?(r=new Uint8Array(8),new DataView(r.buffer).setBigInt64(0,BigInt(s),!0)):n===C.FLOAT64?(r=new Uint8Array(8),new DataView(r.buffer).setFloat64(0,Number(s),!0)):n===C.UUID?(r=new Uint8Array(16),nn.encode(String(s),r,0)):n===C.ULID?(r=new Uint8Array(16),sn.encode(String(s),r,0)):n===C.TEXT?r=wi.encode(String(s)):r=s instanceof Uint8Array?s:new Uint8Array(s);const a=2+r.byteLength+8,l=a+2,c=lt(t,e),u=ds(t,e),h=u+we(t,e);if(l>h)return-1;l>u&&bn(t,e,o);const _=We(t,e)-a,g=e+_,E=t.byteOffset+g;t.setUint16(g,r.byteLength,!0),new Uint8Array(t.buffer).set(r,E+2),t.setBigInt64(g+2+r.byteLength,i,!0);let I=0,p=c-1,y=c;for(;I<=p;){const U=I+p>>1,k=ot(t,e,U),R=t.getUint16(e+k,!0),A=t.getBigInt64(e+k+2+R,!0),{cellType:N,cellVal:v}=Si(t,e+k+2,R,n);ys(n,s,i,N,v,A)<0?(y=U,p=U-1):I=U+1}const T=new Uint8Array(t.buffer),L=t.byteOffset+e+qt,P=L+y*2,F=L+(y+1)*2,w=(c-y)*2;return w>0&&T.copyWithin(F,P,P+w),on(t,e,y,_),He(t,e,c+1),Ve(t,e,_),y}function nr(t,e,n){const s=lt(t,e);if(n<0||n>=s)return;const i=ot(t,e,n),r=2+t.getUint16(e+i,!0)+8,a=e+qt,l=a+(n+1)*2,c=a+n*2,u=(s-1-n)*2;u>0&&en(t,c,t,l,u),He(t,e,s-1),$e(t,e,we(t,e)+r)}function Qn(t,e,n,s,i){const o=lt(t,e);let r=0,a=o-1;for(;r<=a;){const l=r+a>>1,c=ot(t,e,l),u=t.getUint16(e+c,!0),h=t.getBigInt64(e+c+2+u,!0),{cellType:f,cellVal:_}=Si(t,e+c+2,u,n),E=ys(n,s,i!==void 0?i:h,f,_,h);if(E===0){if(i===void 0){let I=l;for(;I>0;){const p=I-1,y=ot(t,e,p),T=t.getUint16(e+y,!0),{cellType:B,cellVal:L}=Si(t,e+y+2,T,n);if(ys(n,s,0n,B,L,0n)===0)I=p;else break}return{found:!0,slot_idx:I}}return{found:!0,slot_idx:l}}else E<0?a=l-1:r=l+1}return{found:!1,slot_idx:r}}function sr(t,e){if(e==null)return new Uint8Array(0);if(t===C.INT32){const n=new Uint8Array(4);return new DataView(n.buffer).setInt32(0,Number(e),!0),n}if(t===C.INT64){const n=new Uint8Array(8);return new DataView(n.buffer).setBigInt64(0,BigInt(e),!0),n}if(t===C.FLOAT64){const n=new Uint8Array(8);return new DataView(n.buffer).setFloat64(0,Number(e),!0),n}if(t===C.UUID){const n=new Uint8Array(16);return nn.encode(String(e),n,0),n}if(t===C.ULID){const n=new Uint8Array(16);return sn.encode(String(e),n,0),n}return t===C.TEXT?wi.encode(String(e)):e instanceof Uint8Array?e:new Uint8Array(e)}function Ts(t,e,n,s){const i=[];let o=0;for(let l=0;l<n;l++){const c=t[e[l]],u=s[c.name],h=sr(c.type,u),f=new Uint8Array(3+h.byteLength);f[0]=c.type,f[1]=h.byteLength&255,f[2]=h.byteLength>>8&255,f.set(h,3),i.push(f),o+=f.byteLength}const r=new Uint8Array(o);let a=0;for(let l=0;l<i.length;l++){const c=i[l];r.set(c,a),a+=c.byteLength}return r}const Qc=2654435769;function kn(t,e){const n=Math.imul(t,Qc);return(n^n>>>16)>>>0&e}function ir(t,e,n,s){const i=n-1;let o=kn(s,i);for(let r=0;r<n;r++){const a=e+o*ye,l=t.getUint32(a,!0);if(l===0)return-1;if(l===s)return t.getUint32(a+4,!0);o=o+1&i}return-1}function or(t,e,n,s,i){const o=n-1;let r=kn(s,o);for(let a=0;a<n;a++){const l=e+r*ye,c=t.getUint32(l,!0);if(c===0||c===s){t.setUint32(l,s,!0),t.setUint32(l+4,i,!0);return}r=r+1&o}throw new Error(`BufferPool page table full: cannot insert page ${s}`)}function Pi(t,e,n,s){const i=n-1;let o=kn(s,i),r=!1;for(let c=0;c<n;c++){const u=e+o*ye,h=t.getUint32(u,!0);if(h===0)return!1;if(h===s){r=!0;break}o=o+1&i}if(!r)return!1;let a=o;for(;;){a=a+1&i;const c=e+a*ye,u=t.getUint32(c,!0);if(u===0)break;const h=kn(u,i);if((o-h&i)<(a-h&i)){const f=t.getUint32(c+4,!0),_=e+o*ye;t.setUint32(_,u,!0),t.setUint32(_+4,f,!0),o=a}}const l=e+o*ye;return t.setUint32(l,0,!0),t.setUint32(l+4,0,!0),!0}function kc(t){return t*4096}function an(t,e,n){return pt(t,e+n*4)}function Bi(t,e,n,s){yt(t,e+n*4,s)}function vt(t,e,n,s){return ir(t,e,n,s)}function rr(t,e,n,s,i,o){Zo(o>0,"page_id must be > 0");const r=an(t,e,i);return r>0&&r!==o&&Pi(t,n,s,r),Bi(t,e,i,o),or(t,n,s,o,i),0}function ar(t,e,n,s,i){const o=an(t,e,i);return o>0?(Pi(t,n,s,o),Bi(t,e,i,0),1):0}function cr(t,e,n){Xo(t,e,n)}function lr(t,e,n){Yo(t,e,n)}function Ni(t,e,n){return $o(t,e,n)===1}function Li(t,e){if(t[e]>=4294967295)throw new Error(`Pin count overflow on slot ${e}`);t[e]++}function Ri(t,e){e!==0&&t[e]>0&&t[e]--}function cn(t,e){return e===0||t[e]>0}function Di(t,e,n,s,i,o){const r=new DataView(t);for(let l=1;l<i;l++)if(pt(r,s+l*4)===0&&!cn(n,l))return{candidate_slot:l,next_clock_hand:o};let a=o;for(let l=0;l<i*2;l++){if(a=(a+1)%i,a===0||cn(n,a))continue;const c=new DataView(t,a*4096,4096);if(Me(c,0)!==Pn)if(e[a]===1)e[a]=0;else return{candidate_slot:a,next_clock_hand:a}}throw new Error("Cache deadlock: all slots are pinned")}function Fi(t,e,n,s,i,o,r,a){const l=new DataView(t);let c=-1,u=r;if(a>1&&a<=o&&an(l,s,a-1)===0&&!cn(n,a-1))c=a-1;else{const I=Di(t,e,n,s,o,r);c=I.candidate_slot,u=I.next_clock_hand}const h=an(l,s,c),f=Ni(new Uint8Array(t),i,c),_=new DataView(t,c*4096,4096),g=h>0&&Me(_,0)===ve,E=f&&!g&&h>0?h:0;return{candidate_slot:c,flush_page_id:E,next_clock_hand:u}}function Tt(t,e){return t.cursors&&t.cursors[e]?t.cursors[e]:t.cursor}function Mt(t,e){if(e<=0)return 0;if(t.byteLength>=Ft+Ao){const n=vt(t,Ft,Qt,e);if(n>=0)return n*4096}return(e-1)*4096}function ln(t,e){if(t==null||e===null||e===void 0)return{result:0,is_unknown:!0};if(typeof t=="boolean"||typeof e=="boolean"){const n=t?1:0,s=e?1:0;return n===s?{result:0,is_unknown:!1}:{result:n>s?1:-1,is_unknown:!1}}if(typeof t=="number"&&typeof e=="number")return t===e?{result:0,is_unknown:!1}:{result:t>e?1:-1,is_unknown:!1};if(typeof t=="bigint"||typeof e=="bigint"){const n=BigInt(t),s=BigInt(e);return n===s?{result:0,is_unknown:!1}:{result:n>s?1:-1,is_unknown:!1}}if(typeof t=="string"&&typeof e=="string")return t===e?{result:0,is_unknown:!1}:{result:t>e?1:-1,is_unknown:!1};if(t instanceof Uint8Array&&e instanceof Uint8Array){const n=Math.min(t.byteLength,e.byteLength);for(let s=0;s<n;s++)if(t[s]!==e[s])return{result:t[s]>e[s]?1:-1,is_unknown:!1};return t.byteLength===e.byteLength?{result:0,is_unknown:!1}:{result:t.byteLength>e.byteLength?1:-1,is_unknown:!1}}return t===e?{result:0,is_unknown:!1}:{result:t>e?1:-1,is_unknown:!1}}function ur(t){return t>=65&&t<=90?t+32:t}function vc(t,e,n,s){let i=0,o=0,r=-1,a=-1;for(;i<e;){const l=o<s?n.charCodeAt(o):0,c=t.charCodeAt(i);if(o<s&&(l===95||ur(l)===ur(c)))i++,o++;else if(o<s&&l===37)r=o++,a=i;else if(r!==-1)o=r+1,i=++a;else return 0}for(;o<s&&n.charCodeAt(o)===37;)o++;return o===s?1:0}function Ye(t,e){return vc(t,t.length,e,e.length)===1}function un(t,e,n){const s=n.numKeys;for(let i=0;i<s;i++){const o=t[i],r=e[i],a=n.directions[i]??0,l=n.nullOrders[i]??(a===1?1:0),c=o==null,u=r==null;if(c&&u)continue;if(c||u)return l===0?c?-1:1:c?1:-1;let h=0;if(typeof o=="number"&&typeof r=="number")h=o<r?-1:o>r?1:0;else if(typeof o=="bigint"||typeof r=="bigint"){const f=BigInt(o),_=BigInt(r);h=f<_?-1:f>_?1:0}else if(typeof o=="string"&&typeof r=="string")h=o<r?-1:o>r?1:0;else if(o instanceof Uint8Array&&r instanceof Uint8Array){const f=Math.min(o.byteLength,r.byteLength);for(let _=0;_<f;_++)if(o[_]!==r[_]){h=o[_]<r[_]?-1:1;break}h===0&&(h=o.byteLength<r.byteLength?-1:o.byteLength>r.byteLength?1:0)}else h=o<r?-1:o>r?1:0;if(h!==0)return a===1?-h:h}return 0}function Ar(t,e,n,s){const i=s.numKeys;for(let o=0;o<i;o++){const r=t[e+o],a=n[o],l=s.directions[o]??0,c=s.nullOrders[o]??(l===1?1:0),u=r==null,h=a==null;if(u&&h)continue;if(u||h)return c===0?u?-1:1:u?1:-1;let f=0;if(typeof r=="number"&&typeof a=="number")f=r<a?-1:r>a?1:0;else if(typeof r=="string"&&typeof a=="string")f=r<a?-1:r>a?1:0;else if(typeof r=="bigint"||typeof a=="bigint"){const _=BigInt(r),g=BigInt(a);f=_<g?-1:_>g?1:0}else if(r instanceof Uint8Array&&a instanceof Uint8Array){const _=Math.min(r.byteLength,a.byteLength);for(let g=0;g<_;g++)if(r[g]!==a[g]){f=r[g]<a[g]?-1:1;break}f===0&&(f=r.byteLength<a.byteLength?-1:r.byteLength>a.byteLength?1:0)}else f=r<a?-1:r>a?1:0;if(f!==0)return l===1?-f:f}return 0}function Cs(t){let e=2166136261;for(let n=0;n<t.length;n++){const s=t[n];if(s==null)e^=255,e=Math.imul(e,16777619);else if(typeof s=="number"){const i=new ArrayBuffer(8);new DataView(i).setFloat64(0,s,!0);const o=new Uint8Array(i);for(let r=0;r<8;r++)e^=o[r],e=Math.imul(e,16777619)}else if(typeof s=="string")for(let i=0;i<s.length;i++)e^=s.charCodeAt(i)&255,e=Math.imul(e,16777619);else if(typeof s=="bigint"){const i=Number(s);e^=i&255,e=Math.imul(e,16777619)}else if(s instanceof Uint8Array)for(let i=0;i<s.byteLength;i++)e^=s[i],e=Math.imul(e,16777619)}return e=e>>>0,e===0?1:e}function Gc(t,e){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++){const s=t[n],i=e[n];if(s==null){if(i!=null)return!1}else{if(i==null)return!1;if(s!==i)if(s instanceof Uint8Array&&i instanceof Uint8Array){if(s.byteLength!==i.byteLength)return!1;for(let o=0;o<s.byteLength;o++)if(s[o]!==i[o])return!1}else return!1}}return!0}function fr(t){const e=new Array(t);for(let n=0;n<t;n++)e[n]={hash:0,keys:[],count:0,sum:0,min_val:1/0,max_val:-1/0,has_val:!1};return e}function _r(t,e,n,s){let i=e;for(;;){let o=i;const r=2*i+1,a=2*i+2;if(r<n&&un(t[r].keys,t[o].keys,s)>0&&(o=r),a<n&&un(t[a].keys,t[o].keys,s)>0&&(o=a),o!==i){const l=t[i];t[i]=t[o],t[o]=l,i=o}else break}}function Mc(t){const e=t.keyInfo;t.entries.sort((n,s)=>un(n.keys,s.keys,e)),t.readIdx=e.offset??0}function gr(t,e,n){const s=new Uint8Array(t.buffer,t.byteOffset+e,n),i=new Uint8Array(n);return i.set(s),i}function Hc(t,e,n,s,i,o,r){if(r>0&&e.entries.length>=r){if(un(n,e.entries[0].keys,e.keyInfo)>=0)return O.RUNNING;const u=e.entries[0],h=i-u.rowLen;if(h>0&&t.arenaOffset+h>t.maxQueryMemory)return t.status=O.ARENA_EXHAUSTED,O.ARENA_EXHAUSTED;t.arenaOffset+=h;const f=gr(o,s,i);return u.keys=n,u.rowOffset=s,u.rowLen=i,u.rowData=f,_r(e.entries,0,r,e.keyInfo),O.RUNNING}const a=16+16*n.length+i;if(t.arenaOffset+a>t.maxQueryMemory)return t.status=O.ARENA_EXHAUSTED,O.ARENA_EXHAUSTED;t.arenaOffset+=a;const l=gr(o,s,i);if(e.entries.push({keys:n,rowOffset:s,rowLen:i,rowData:l}),r>0&&e.entries.length===r)for(let c=Math.floor(r/2)-1;c>=0;c--)_r(e.entries,c,r,e.keyInfo);return O.RUNNING}function Wc(t,e,n){var o,r;let s;const i={};if(t.outputColumns&&n===t.outputColumns.length){s=t.outputColumns;for(let a=0;a<n;a++)i[s[a].name]=t.registers[e+a]}else if(t.table&&n===t.table.columns.length){s=t.table.columns;for(let a=0;a<n;a++)i[s[a].name]=t.registers[e+a]}else{s=[];for(let a=0;a<n;a++){const l=t.registers[e+a],c=((r=(o=t.table)==null?void 0:o.columns[a])==null?void 0:r.name)??`col_${a}`;let u=C.TEXT;typeof l=="number"?u=Number.isInteger(l)?C.INT32:C.FLOAT64:typeof l=="bigint"?u=C.INT64:l instanceof Uint8Array&&(u=C.BLOB),s.push({name:c,type:u,flags:z.NONE,colOffset:0}),i[c]=l}}return ms(s,i)}function bi(t,e,n,s){const i=2+n.byteLength;if(t.resultOffset+i>Zs)return t.status=O.BUFFER_FULL,t.pc=s,O.BUFFER_FULL;const o=Sn+t.resultOffset;return e.setUint16(o,n.byteLength,!0),new Uint8Array(e.buffer,e.byteOffset+o+2,n.byteLength).set(n),t.resultOffset+=i,t.resultCount++,O.RUNNING}function Ze(t,e,n){return(t.getUint8(e+(n>>3))&1<<(n&7))!==0}function vn(t,e,n,s,i){let o=e+n;for(let r=0;r<i;r++)if(!Ze(t,e,r))switch(s[r].type){case C.INT32:o+=4;break;case C.INT64:case C.FLOAT64:o+=8;break;case C.UUID:case C.ULID:o+=16;break}return o}const hr=new TextDecoder;function Gn(t,e,n){var l,c;const s=new DataView(n.buffer,n.byteOffset,n.byteLength),i=n.byteLength,o=1e7;let r=0;const a=e.byteLength>=Zn+4&&e.getUint32(Zn,!0)>0;for(;t.pc<i;){if(++r>o)return t.status=O.TIMEOUT,O.TIMEOUT;const u=t.pc,h=n[t.pc];switch(t.pc+=1,h){case d.OP_HALT:return t.arenaOffset=0,t.status=O.DONE,O.DONE;case d.OP_OPEN_CURSOR:{const f=n[t.pc],_=s.getUint32(t.pc+1,!0);t.pc+=5;const g=Tt(t,f);if(g.pageId=_,g.cellIdx=0,g.rowOffset=0,a&&_>0){const E=vt(e,Ft,Qt,_);if(E<0)return t.fault_page_id=_,t.status=O.PAGE_FAULT,t.pc=u,O.PAGE_FAULT;g.slotIdx=E}break}case d.OP_REWIND:{const f=n[t.pc],_=s.getUint16(t.pc+1,!0);if(t.pc+=3,_>i)return t.status=O.INVALID_BYTECODE,O.INVALID_BYTECODE;const g=Tt(t,f);if(a&&g.pageId>0){const p=vt(e,Ft,Qt,g.pageId);if(p<0)return t.fault_page_id=g.pageId,t.status=O.PAGE_FAULT,t.pc=u,O.PAGE_FAULT;g.slotIdx=p}const E=Mt(e,g.pageId);if(lt(e,E)===0)t.pc=_;else{g.cellIdx=0;const p=ot(e,E,0);g.rowOffset=E+p}break}case d.OP_NEXT_ROW:{const f=n[t.pc],_=s.getUint16(t.pc+1,!0);if(t.pc+=3,_>i)return t.status=O.INVALID_BYTECODE,O.INVALID_BYTECODE;const g=Tt(t,f),E=Mt(e,g.pageId),I=lt(e,E),p=g.cellIdx+1;if(p<I){g.cellIdx=p;const y=ot(e,E,g.cellIdx);g.rowOffset=E+y}else{const y=Ut(e,E);if(y!==0){if(a){const L=vt(e,Ft,Qt,y);if(L<0)return t.fault_page_id=y,t.status=O.PAGE_FAULT,t.pc=u,O.PAGE_FAULT;g.slotIdx=L}g.pageId=y,g.cellIdx=0;const T=Mt(e,y);if(lt(e,T)>0){const L=ot(e,T,0);g.rowOffset=T+L}else t.pc=_}else t.pc=_}break}case d.OP_LAST:{const f=n[t.pc],_=s.getUint16(t.pc+1,!0);if(t.pc+=3,_>i)return t.status=O.INVALID_BYTECODE,O.INVALID_BYTECODE;const g=Tt(t,f),E=Mt(e,g.pageId),I=lt(e,E);if(I===0)t.pc=_;else{g.cellIdx=I-1;const p=ot(e,E,g.cellIdx);g.rowOffset=E+p}break}case d.OP_PREV_ROW:{const f=n[t.pc],_=s.getUint16(t.pc+1,!0);if(t.pc+=3,_>i)return t.status=O.INVALID_BYTECODE,O.INVALID_BYTECODE;const g=Tt(t,f),E=Mt(e,g.pageId);if(g.cellIdx>0){g.cellIdx--;const I=ot(e,E,g.cellIdx);g.rowOffset=E+I}else t.pc=_;break}case d.OP_COLUMN_INT:{const f=n[t.pc],_=n[t.pc+1],g=n[t.pc+2];t.pc+=3;const E=Tt(t,f),I=(t.tables&&t.tables[f])??t.table,p=I.columns[_],y=Math.ceil(I.columns.length/8),T=E.rowOffset+3;if(Ze(e,T,_)){t.registers[g]=null;break}const B=vn(e,T,y,I.columns,_);p.type===C.INT32?t.registers[g]=e.getInt32(B,!0):p.type===C.INT64&&(t.registers[g]=Number(e.getBigInt64(B,!0)));break}case d.OP_COLUMN_FLOAT:{const f=n[t.pc],_=n[t.pc+1],g=n[t.pc+2];t.pc+=3;const E=Tt(t,f),I=(t.tables&&t.tables[f])??t.table,p=Math.ceil(I.columns.length/8),y=E.rowOffset+3;if(Ze(e,y,_)){t.registers[g]=null;break}const T=vn(e,y,p,I.columns,_);t.registers[g]=e.getFloat64(T,!0);break}case d.OP_COLUMN_UUID:case d.OP_COLUMN_ULID:case d.OP_COLUMN_TEXT:{const f=n[t.pc],_=n[t.pc+1],g=n[t.pc+2];t.pc+=3;const E=Tt(t,f),I=(t.tables&&t.tables[f])??t.table,p=Math.ceil(I.columns.length/8),y=E.rowOffset+3;if(Ze(e,y,_)){t.registers[g]=null;break}if(I.columns[_].type===C.UUID||I.columns[_].type===C.ULID){const w=vn(e,y,p,I.columns,_),U=new Uint8Array(e.buffer,e.byteOffset+w,16);t.registers[g]=I.columns[_].type===C.UUID?nn.decode(U,0):sn.decode(U,0);break}const T=vn(e,y,p,I.columns,I.columns.length);let B=0;for(let w=0;w<_;w++){const U=I.columns[w];(U.type===C.TEXT||U.type===C.BLOB)&&B++}const L=T+B*4,P=e.getUint16(L,!0),F=e.getUint16(L+2,!0);if(F===0)t.registers[g]="";else{const w=new Uint8Array(e.buffer,E.rowOffset+P,F);t.registers[g]=hr.decode(w)}break}case d.OP_COLUMN_BLOB:{const f=n[t.pc],_=n[t.pc+1],g=n[t.pc+2];t.pc+=3;const E=Tt(t,f),I=(t.tables&&t.tables[f])??t.table,p=Math.ceil(I.columns.length/8),y=E.rowOffset+3;if(Ze(e,y,_)){t.registers[g]=null;break}const T=vn(e,y,p,I.columns,I.columns.length);let B=0;for(let U=0;U<_;U++){const k=I.columns[U];(k.type===C.TEXT||k.type===C.BLOB)&&B++}const L=T+B*4,P=e.getUint16(L,!0),F=e.getUint16(L+2,!0),w=new Uint8Array(F);w.set(new Uint8Array(e.buffer,E.rowOffset+P,F)),t.registers[g]=w;break}case d.OP_OPEN_INDEX:{const f=n[t.pc],_=s.getUint32(t.pc+1,!0);t.pc+=5;const g=Tt(t,f);if(g.pageId=_,g.rootPageId=_,g.cellIdx=0,g.rowOffset=0,a&&_>0){const E=vt(e,Ft,Qt,_);if(E<0)return t.fault_page_id=_,t.status=O.PAGE_FAULT,t.pc=u,O.PAGE_FAULT;g.slotIdx=E}break}case d.OP_INDEX_SEEK_EQ:{const f=n[t.pc],_=n[t.pc+1],g=n[t.pc+2],E=n[t.pc+3],I=s.getUint16(t.pc+4,!0);if(t.pc+=6,I>i)return t.status=O.INVALID_BYTECODE,O.INVALID_BYTECODE;const p=t.registers[g];if(p==null){t.pc=I;break}const y=Tt(t,f);let T=y.rootPageId||y.pageId,B=!1,L=0n;for(;T!==0;){if(a&&T>0){const w=vt(e,Ft,Qt,T);if(w<0)return t.fault_page_id=T,t.status=O.PAGE_FAULT,t.pc=u,O.PAGE_FAULT;y.slotIdx=w}const P=Mt(e,T),F=Qn(e,P,E,p);if(F.found){B=!0,y.pageId=T,y.cellIdx=F.slot_idx;const w=ot(e,P,F.slot_idx),U=e.getUint16(P+w,!0);L=e.getBigInt64(P+w+2+U,!0);break}T=Ut(e,P)}if(!B)t.pc=I;else{const P=Number(L>>16n),F=Number(L&0xffffn);if(a&&P>0&&vt(e,Ft,Qt,P)<0)return t.fault_page_id=P,t.status=O.PAGE_FAULT,t.pc=u,O.PAGE_FAULT;const w=Tt(t,_);w.pageId=P,w.cellIdx=F;const U=Mt(e,P),k=ot(e,U,F);w.rowOffset=U+k}break}case d.OP_INDEX_SEEK_GE:{const f=n[t.pc],_=n[t.pc+1],g=n[t.pc+2],E=n[t.pc+3],I=s.getUint16(t.pc+4,!0);if(t.pc+=6,I>i)return t.status=O.INVALID_BYTECODE,O.INVALID_BYTECODE;const p=t.registers[g];if(p==null){t.pc=I;break}const y=Tt(t,f);let T=y.rootPageId||y.pageId,B=!1,L=0n;for(;T!==0;){if(a&&T>0){const U=vt(e,Ft,Qt,T);if(U<0)return t.fault_page_id=T,t.status=O.PAGE_FAULT,t.pc=u,O.PAGE_FAULT;y.slotIdx=U}const P=Mt(e,T),F=lt(e,P),w=Qn(e,P,E,p);if(w.found||w.slot_idx<F){B=!0,y.pageId=T,y.cellIdx=w.slot_idx;const U=ot(e,P,w.slot_idx),k=e.getUint16(P+U,!0);L=e.getBigInt64(P+U+2+k,!0);break}T=Ut(e,P)}if(!B)t.pc=I;else{const P=Number(L>>16n),F=Number(L&0xffffn);if(a&&P>0&&vt(e,Ft,Qt,P)<0)return t.fault_page_id=P,t.status=O.PAGE_FAULT,t.pc=u,O.PAGE_FAULT;const w=Tt(t,_);w.pageId=P,w.cellIdx=F;const U=Mt(e,P),k=ot(e,U,F);w.rowOffset=U+k}break}case d.OP_INDEX_NEXT:{const f=n[t.pc],_=n[t.pc+1],g=s.getUint16(t.pc+2,!0);if(t.pc+=4,g>i)return t.status=O.INVALID_BYTECODE,O.INVALID_BYTECODE;const E=Tt(t,f);let I=E.pageId,p=Mt(e,I);const y=lt(e,p);let T=E.cellIdx+1;if(T>=y){if(I=Ut(e,p),I===0){t.pc=g;break}if(a&&I>0){const A=vt(e,Ft,Qt,I);if(A<0)return t.fault_page_id=I,t.status=O.PAGE_FAULT,t.pc=u,O.PAGE_FAULT;E.slotIdx=A}p=Mt(e,I),T=0,E.pageId=I,E.cellIdx=-1}const B=ot(e,p,T),L=e.getUint16(p+B,!0),P=e.getBigInt64(p+B+2+L,!0),F=Number(P>>16n),w=Number(P&0xffffn);if(a&&F>0&&vt(e,Ft,Qt,F)<0)return t.fault_page_id=F,t.status=O.PAGE_FAULT,t.pc=u,O.PAGE_FAULT;E.pageId=I,E.cellIdx=T;const U=Tt(t,_);U.pageId=F,U.cellIdx=w;const k=Mt(e,F),R=ot(e,k,w);U.rowOffset=k+R;break}case d.OP_IS_NULL:{const f=n[t.pc],_=n[t.pc+1],g=s.getUint16(t.pc+2,!0);if(t.pc+=4,g>i)return t.status=O.INVALID_BYTECODE,O.INVALID_BYTECODE;const I=Tt(t,f).rowOffset+3;Ze(e,I,_)&&(t.pc=g);break}case d.OP_IS_NOT_NULL:{const f=n[t.pc],_=n[t.pc+1],g=s.getUint16(t.pc+2,!0);if(t.pc+=4,g>i)return t.status=O.INVALID_BYTECODE,O.INVALID_BYTECODE;const I=Tt(t,f).rowOffset+3;Ze(e,I,_)||(t.pc=g);break}case d.OP_EQ:{const f=n[t.pc],_=n[t.pc+1],g=s.getUint16(t.pc+2,!0);if(t.pc+=4,g>i)return t.status=O.INVALID_BYTECODE,O.INVALID_BYTECODE;const E=ln(t.registers[f],t.registers[_]);!E.is_unknown&&E.result===0&&(t.pc=g);break}case d.OP_NE:{const f=n[t.pc],_=n[t.pc+1],g=s.getUint16(t.pc+2,!0);if(t.pc+=4,g>i)return t.status=O.INVALID_BYTECODE,O.INVALID_BYTECODE;const E=ln(t.registers[f],t.registers[_]);!E.is_unknown&&E.result!==0&&(t.pc=g);break}case d.OP_GT:{const f=n[t.pc],_=n[t.pc+1],g=s.getUint16(t.pc+2,!0);if(t.pc+=4,g>i)return t.status=O.INVALID_BYTECODE,O.INVALID_BYTECODE;const E=ln(t.registers[f],t.registers[_]);!E.is_unknown&&E.result>0&&(t.pc=g);break}case d.OP_GE:{const f=n[t.pc],_=n[t.pc+1],g=s.getUint16(t.pc+2,!0);if(t.pc+=4,g>i)return t.status=O.INVALID_BYTECODE,O.INVALID_BYTECODE;const E=ln(t.registers[f],t.registers[_]);!E.is_unknown&&E.result>=0&&(t.pc=g);break}case d.OP_LT:{const f=n[t.pc],_=n[t.pc+1],g=s.getUint16(t.pc+2,!0);if(t.pc+=4,g>i)return t.status=O.INVALID_BYTECODE,O.INVALID_BYTECODE;const E=ln(t.registers[f],t.registers[_]);!E.is_unknown&&E.result<0&&(t.pc=g);break}case d.OP_LE:{const f=n[t.pc],_=n[t.pc+1],g=s.getUint16(t.pc+2,!0);if(t.pc+=4,g>i)return t.status=O.INVALID_BYTECODE,O.INVALID_BYTECODE;const E=ln(t.registers[f],t.registers[_]);!E.is_unknown&&E.result<=0&&(t.pc=g);break}case d.OP_JUMP:{const f=s.getUint16(t.pc,!0);if(f>i)return t.status=O.INVALID_BYTECODE,O.INVALID_BYTECODE;t.pc=f;break}case d.OP_STR_LIKE:{const f=n[t.pc],_=n[t.pc+1],g=s.getUint16(t.pc+2,!0);if(t.pc+=4,g>i)return t.status=O.INVALID_BYTECODE,O.INVALID_BYTECODE;const E=t.registers[f],I=t.registers[_];if(E===null||I===null)break;Ye(String(E),String(I))&&(t.pc=g);break}case d.OP_STR_NOT_LIKE:{const f=n[t.pc],_=n[t.pc+1],g=s.getUint16(t.pc+2,!0);if(t.pc+=4,g>i)return t.status=O.INVALID_BYTECODE,O.INVALID_BYTECODE;const E=t.registers[f],I=t.registers[_];if(E===null||I===null)break;Ye(String(E),String(I))||(t.pc=g);break}case d.OP_STR_CONTAINS:{const f=n[t.pc],_=n[t.pc+1],g=s.getUint16(t.pc+2,!0);if(t.pc+=4,g>i)return t.status=O.INVALID_BYTECODE,O.INVALID_BYTECODE;const E=t.registers[f],I=t.registers[_];if(E===null||I===null)break;String(E).includes(String(I))&&(t.pc=g);break}case d.OP_STR_STARTS_WITH:{const f=n[t.pc],_=n[t.pc+1],g=s.getUint16(t.pc+2,!0);if(t.pc+=4,g>i)return t.status=O.INVALID_BYTECODE,O.INVALID_BYTECODE;const E=t.registers[f],I=t.registers[_];if(E===null||I===null)break;String(E).startsWith(String(I))&&(t.pc=g);break}case d.OP_STR_ENDS_WITH:{const f=n[t.pc],_=n[t.pc+1],g=s.getUint16(t.pc+2,!0);if(t.pc+=4,g>i)return t.status=O.INVALID_BYTECODE,O.INVALID_BYTECODE;const E=t.registers[f],I=t.registers[_];if(E===null||I===null)break;String(E).endsWith(String(I))&&(t.pc=g);break}case d.OP_IN:{const f=n[t.pc],_=s.getUint16(t.pc+1,!0),g=s.getUint16(t.pc+3,!0);if(t.pc+=5,g>i)return t.status=O.INVALID_BYTECODE,O.INVALID_BYTECODE;const E=t.registers[f];if(E==null)break;const I=(l=t.inSets)==null?void 0:l[_];I&&(I.has(E)||typeof E=="number"&&Number.isSafeInteger(E)&&I.has(BigInt(E))||typeof E=="bigint"&&I.has(Number(E)))&&(t.pc=g);break}case d.OP_LOAD_INT:{const f=n[t.pc],_=s.getInt32(t.pc+1,!0);t.pc+=5,t.registers[f]=_;break}case d.OP_LOAD_FLOAT:{const f=n[t.pc],_=s.getFloat64(t.pc+1,!0);t.pc+=9,t.registers[f]=_;break}case d.OP_LOAD_TEXT:{const f=n[t.pc],_=s.getUint16(t.pc+1,!0),g=new Uint8Array(n.buffer,n.byteOffset+t.pc+3,_);t.registers[f]=hr.decode(g),t.pc+=3+_;break}case d.OP_LOAD_BLOB:{const f=n[t.pc],_=s.getUint16(t.pc+1,!0),g=new Uint8Array(_);g.set(new Uint8Array(n.buffer,n.byteOffset+t.pc+3,_)),t.registers[f]=g,t.pc+=3+_;break}case d.OP_LOAD_NULL:{const f=n[t.pc];t.pc+=1,t.registers[f]=null;break}case d.OP_EMIT_ROW:{const f=n[t.pc];t.pc+=1;const _=Tt(t,f),g=e.getUint16(_.rowOffset+1,!0),E=new Uint8Array(e.buffer,e.byteOffset+_.rowOffset,g),I=bi(t,e,E,u);if(I!==O.RUNNING)return I;break}case d.OP_OFFSET:{const f=n[t.pc],_=s.getUint16(t.pc+1,!0);if(t.pc+=3,_>i)return t.status=O.INVALID_BYTECODE,O.INVALID_BYTECODE;const g=Number(t.registers[f]??0);g>0&&(t.registers[f]=g-1,t.pc=_);break}case d.OP_LIMIT:{const f=n[t.pc],_=s.getUint16(t.pc+1,!0);if(t.pc+=3,_>i)return t.status=O.INVALID_BYTECODE,O.INVALID_BYTECODE;const g=Number(t.registers[f]??0);g<=1?(t.registers[f]=0,t.pc=_):t.registers[f]=g-1;break}case d.OP_CALL_UDF:{const f=s.getUint16(t.pc,!0),_=n[t.pc+2],g=n[t.pc+3],E=n[t.pc+4];t.pc+=5;const I=(c=t.udfs)==null?void 0:c[f];if(!I)return t.status=O.INVALID_BYTECODE,O.INVALID_BYTECODE;const p=[];for(let y=0;y<g;y++)p.push(t.registers[_+y]);try{const y=I(...p);t.registers[E]=y!==void 0?y:null}catch{return t.status=O.ERROR,O.ERROR}break}case d.OP_STR_LOWER:{const f=n[t.pc],_=n[t.pc+1];t.pc+=2;const g=t.registers[f];t.registers[_]=g!==null?String(g).toLowerCase():null;break}case d.OP_STR_UPPER:{const f=n[t.pc],_=n[t.pc+1];t.pc+=2;const g=t.registers[f];t.registers[_]=g!==null?String(g).toUpperCase():null;break}case d.OP_STR_LENGTH:{const f=n[t.pc],_=n[t.pc+1];t.pc+=2;const g=t.registers[f];t.registers[_]=g!==null?String(g).length:null;break}case d.OP_STR_SUBSTR:{const f=n[t.pc],_=n[t.pc+1],g=n[t.pc+2],E=n[t.pc+3];t.pc+=4;const I=t.registers[f],p=t.registers[_],y=t.registers[g];if(I===null||p===null){t.registers[E]=null;break}const T=String(I),B=Math.max(0,Number(p)-1);if(y===null)t.registers[E]=T.slice(B);else{const L=Math.max(0,Number(y));t.registers[E]=T.slice(B,B+L)}break}case d.OP_STR_TRIM:{const f=n[t.pc],_=n[t.pc+1];t.pc+=2;const g=t.registers[f];t.registers[_]=g!=null?String(g).trim():null;break}case d.OP_MATH_ABS:{const f=n[t.pc],_=n[t.pc+1];t.pc+=2;const g=t.registers[f];t.registers[_]=g!=null?Math.abs(Number(g)):null;break}case d.OP_MATH_ROUND:{const f=n[t.pc],_=n[t.pc+1];t.pc+=2;const g=t.registers[f];t.registers[_]=g!=null?Math.round(Number(g)):null;break}case d.OP_RESULT_ROW:{const f=n[t.pc],_=n[t.pc+1];t.pc+=2;const g=Wc(t,f,_),E=bi(t,e,g,u);if(E!==O.RUNNING)return E;break}case d.OP_SORTER_OPEN:{const f=n[t.pc],_=n[t.pc+1];t.pc+=2;const g=t.keyInfos[_]??{numKeys:1,directions:[0],nullOrders:[0]},E=g.limit!==void 0&&g.limit>0?(g.offset??0)+g.limit:0,I=E>0&&E<=Oo?E:0;t.sorters[f]={keyInfo:g,entries:[],readIdx:0,isSorted:!1,maxK:I};break}case d.OP_SORTER_INSERT:{const f=n[t.pc],_=n[t.pc+1],g=n[t.pc+2],E=n[t.pc+3];t.pc+=4;const I=t.sorters[f];if(!I)return t.status=O.INVALID_BYTECODE,O.INVALID_BYTECODE;const p=I.maxK??0;if(p>0&&I.entries.length>=p){if(g===1){const P=t.registers[_],F=I.entries[0].keys[0],w=I.keyInfo.directions[0]??0;if(typeof P=="number"&&typeof F=="number"){if(w===0?P>=F:P<=F)break}else if(typeof P=="string"&&typeof F=="string"){if(w===0?P>=F:P<=F)break}else if(Ar(t.registers,_,I.entries[0].keys,I.keyInfo)>=0)break}else if(Ar(t.registers,_,I.entries[0].keys,I.keyInfo)>=0)break}const y=Tt(t,E),T=e.getUint16(y.rowOffset+1,!0),B=new Array(g);for(let P=0;P<g;P++)B[P]=t.registers[_+P];const L=Hc(t,I,B,y.rowOffset,T,e,p);if(L!==O.RUNNING)return L;break}case d.OP_SORTER_SORT:{const f=n[t.pc];t.pc+=1;const _=t.sorters[f];if(!_)return t.status=O.INVALID_BYTECODE,O.INVALID_BYTECODE;Mc(_),_.isSorted=!0;break}case d.OP_SORTER_NEXT:{const f=n[t.pc],_=s.getUint16(t.pc+1,!0);if(t.pc+=3,_>i)return t.status=O.INVALID_BYTECODE,O.INVALID_BYTECODE;const g=t.sorters[f];if(!g)return t.status=O.INVALID_BYTECODE,O.INVALID_BYTECODE;const E=g.keyInfo.limit!==void 0?(g.keyInfo.offset??0)+g.keyInfo.limit:g.entries.length;if(g.readIdx>=Math.min(g.entries.length,E))break;const I=g.entries[g.readIdx],p=I.rowData??new Uint8Array(e.buffer,e.byteOffset+I.rowOffset,I.rowLen),y=bi(t,e,p,u);if(y!==O.RUNNING)return y;g.readIdx++,t.pc=_;break}case d.OP_MATH_FLOOR:{const f=n[t.pc],_=n[t.pc+1];t.pc+=2;const g=t.registers[f];t.registers[_]=g!=null?Math.floor(Number(g)):null;break}case d.OP_MATH_CEIL:{const f=n[t.pc],_=n[t.pc+1];t.pc+=2;const g=t.registers[f];t.registers[_]=g!=null?Math.ceil(Number(g)):null;break}case d.OP_ADD:{const f=n[t.pc],_=n[t.pc+1],g=n[t.pc+2];t.pc+=3;const E=t.registers[f],I=t.registers[_];E==null||I===null||I===void 0?t.registers[g]=null:t.registers[g]=Number(E)+Number(I);break}case d.OP_SUB:{const f=n[t.pc],_=n[t.pc+1],g=n[t.pc+2];t.pc+=3;const E=t.registers[f],I=t.registers[_];E==null||I===null||I===void 0?t.registers[g]=null:t.registers[g]=Number(E)-Number(I);break}case d.OP_MUL:{const f=n[t.pc],_=n[t.pc+1],g=n[t.pc+2];t.pc+=3;const E=t.registers[f],I=t.registers[_];E==null||I===null||I===void 0?t.registers[g]=null:t.registers[g]=Number(E)*Number(I);break}case d.OP_DIV:{const f=n[t.pc],_=n[t.pc+1],g=n[t.pc+2];t.pc+=3;const E=t.registers[f],I=t.registers[_];if(E==null||I===null||I===void 0)t.registers[g]=null;else{const p=Number(I);t.registers[g]=p===0?null:Number(E)/p}break}case d.OP_MOD:{const f=n[t.pc],_=n[t.pc+1],g=n[t.pc+2];t.pc+=3;const E=t.registers[f],I=t.registers[_];if(E==null||I===null||I===void 0)t.registers[g]=null;else{const p=Number(I);t.registers[g]=p===0?null:Number(E)%p}break}case d.OP_STR_CONCAT:{const f=n[t.pc],_=n[t.pc+1],g=n[t.pc+2];t.pc+=3;let E="",I=!1;for(let p=0;p<_;p++){const y=t.registers[f+p];y!=null&&(I=!0,E+=String(y))}t.registers[g]=I?E:null;break}case d.OP_COALESCE:{const f=n[t.pc],_=n[t.pc+1],g=n[t.pc+2];t.pc+=3;let E=null;for(let I=0;I<_;I++){const p=t.registers[f+I];if(p!=null){E=p;break}}t.registers[g]=E;break}case d.OP_COPY:{const f=n[t.pc],_=n[t.pc+1];t.pc+=2,t.registers[_]=t.registers[f];break}case d.OP_AGG_INIT:{const f=n[t.pc],_=n[t.pc+1],g=n[t.pc+2],E=n[t.pc+3];if(t.pc+=4,E===0){if(t.arenaOffset+40960>t.maxQueryMemory)return t.status=O.ARENA_EXHAUSTED,O.ARENA_EXHAUSTED;t.arenaOffset+=40960;const y=fr(1024);if(g===0){const T=Cs([]),B=T%1024;y[B].hash=T,y[B].keys=[],y[B].count=0,y[B].sum=0,y[B].min_val=1/0,y[B].max_val=-1/0,y[B].has_val=!1}t.aggregators[f]={mode:0,startKeyReg:_,numKeys:g,capacity:1024,occupiedCount:g===0?1:0,readIdx:0,buckets:y}}else t.aggregators[f]={mode:1,startKeyReg:_,numKeys:g,capacity:1,occupiedCount:0,readIdx:0,buckets:[]};break}case d.OP_AGG_STEP:{const f=n[t.pc],_=n[t.pc+1],g=n[t.pc+2],E=n[t.pc+3],I=n[t.pc+4];t.pc+=5;const p=t.aggregators[f];if(!p)return t.status=O.INVALID_BYTECODE,O.INVALID_BYTECODE;const y=[];for(let B=0;B<g;B++)y.push(t.registers[_+B]);const T=E===255?null:t.registers[E];if(p.mode===0){const B=Cs(y),L=B%p.capacity;let P=null;for(let F=0;F<p.capacity;F++){const w=(L+F)%p.capacity,U=p.buckets[w];if(U.hash===0){U.hash=B,U.keys=y.slice(),U.count=0,U.sum=0,U.min_val=1/0,U.max_val=-1/0,U.has_val=!1,p.occupiedCount++,P=U;break}else if(U.hash===B&&Gc(U.keys,y)){P=U;break}}if(!P)return t.status=O.ARENA_EXHAUSTED,O.ARENA_EXHAUSTED;if(I===0)(E===255||T!=null)&&P.count++;else if(I===1||I===2)T!=null&&(P.sum+=Number(T),P.has_val=!0);else if(I===3){if(T!=null){const F=Number(T);(!P.has_val||F<P.min_val)&&(P.min_val=F),P.has_val=!0}}else if(I===4&&T!=null){const F=Number(T);(!P.has_val||F>P.max_val)&&(P.max_val=F),P.has_val=!0}if(p.occupiedCount>.7*p.capacity){const w=p.capacity*2,U=w*40;if(t.arenaOffset+U>t.maxQueryMemory)return t.status=O.ARENA_EXHAUSTED,O.ARENA_EXHAUSTED;t.arenaOffset+=U;const k=p.buckets,R=fr(w);for(let A=0;A<k.length;A++){const N=k[A];if(N.hash!==0){const v=N.hash%w;for(let X=0;X<w;X++){const x=(v+X)%w;if(R[x].hash===0){R[x]=N;break}}}}p.capacity=w,p.buckets=R}}break}case d.OP_AGG_NEXT:{const f=n[t.pc],_=n[t.pc+1],g=n[t.pc+2],E=s.getUint16(t.pc+3,!0);if(t.pc+=5,E>i)return t.status=O.INVALID_BYTECODE,O.INVALID_BYTECODE;const I=t.aggregators[f];if(!I)return t.status=O.INVALID_BYTECODE,O.INVALID_BYTECODE;for(;I.readIdx<I.buckets.length&&I.buckets[I.readIdx].hash===0;)I.readIdx++;if(I.readIdx>=I.buckets.length)break;const p=I.buckets[I.readIdx++];for(let y=0;y<p.keys.length;y++)t.registers[_+y]=p.keys[y];t.registers[g]=p.sum,t.registers[g+1]=p.count,t.registers[g+2]=p.has_val?p.min_val:null,t.registers[g+3]=p.has_val?p.max_val:null,t.pc=E;break}case d.OP_AGG_FINAL:{const f=n[t.pc],_=n[t.pc+1],g=n[t.pc+2],E=n[t.pc+3];t.pc+=4;const I=t.registers[f],p=Number(t.registers[_]??0);E===0?t.registers[g]=p:E===1?t.registers[g]=p>0?Number(I):null:E===2?t.registers[g]=p>0?Number(I)/p:null:(E===3||E===4)&&(t.registers[g]=t.registers[f]);break}case d.OP_REG_IS_NULL:{const f=n[t.pc],_=s.getUint16(t.pc+1,!0);if(t.pc+=3,_>i)return t.status=O.INVALID_BYTECODE,O.INVALID_BYTECODE;const g=t.registers[f];g==null&&(t.pc=_);break}case d.OP_REG_IS_NOT_NULL:{const f=n[t.pc],_=s.getUint16(t.pc+1,!0);if(t.pc+=3,_>i)return t.status=O.INVALID_BYTECODE,O.INVALID_BYTECODE;const g=t.registers[f];g!=null&&(t.pc=_);break}default:return t.status=O.INVALID_BYTECODE,O.INVALID_BYTECODE}}return t.status=O.DONE,O.DONE}const Vc=new TextDecoder,dr=new Uint8Array([87,69,66,68,66,0]),Er=new Uint32Array(256);let mr=0;function $c(){if(!mr){for(let t=0;t<256;t++){let e=t;for(let n=0;n<8;n++)e=e&1?3988292384^e>>>1:e>>>1;Er[t]=e>>>0}mr=1}}function Qi(t,e=0){$c();let n=4294967295;for(let s=0;s<4096;s++){const i=s>=28&&s<=31?0:t.getUint8(e+s);n=Er[(n^i)&255]^n>>>8}return(n^4294967295)>>>0}function Ir(t,e=0){ne(t,e,0,4096),t.setUint8(e+de+0,87),t.setUint8(e+de+1,69),t.setUint8(e+de+2,66),t.setUint8(e+de+3,68),t.setUint8(e+de+4,66),t.setUint8(e+de+5,0),t.setUint16(e+Ws,4096,!0),t.setUint16(e+Vs,Jn,!0),t.setUint16(e+$s,Uo,!0),t.setUint32(e+ee,1,!0),t.setUint32(e+re,0,!0),t.setUint32(e+Ee,1,!0),t.setUint32(e+me,0,!0),t.setUint32(e+Ie,0,!0),t.setUint32(e+lo,0,!0),t.setUint32(e+uo,0,!0);const n=Qi(t,e);t.setUint32(e+Ie,n,!0)}function Mn(t,e=!1){for(let u=0;u<dr.length;u++)if(t.getUint8(de+u)!==dr[u])throw new Rn("Invalid database file: magic bytes mismatch");const n=t.getUint16(Ws,!0),s=t.getUint16(Vs,!0),i=t.getUint16($s,!0),o=t.getUint32(ee,!0),r=t.getUint32(re,!0),a=t.getUint32(Ee,!0),l=t.getUint32(me,!0),c=t.getUint32(Ie,!0);if(i>Jn)throw new bo(`Database file format requires engine version >= ${i}, but running engine is version ${Jn}`);if(e&&c!==0){const u=Qi(t,0);if(u!==c)throw new Ce(1,c,u)}return{pageSize:n,fileFormatVersion:s,minReadVersion:i,totalPages:o,freePageHead:r,schemaVersion:a,changeCounter:l,storedChecksum:c}}function pr(t,e=0){return t.getUint32(e+ee,!0)}function Xc(t,e,n){n===void 0&&(n=e,e=0),t.setUint32(e+ee,n,!0)}function Yc(t,e=0){return t.getUint32(e+re,!0)}function Zc(t,e,n){n===void 0&&(n=e,e=0),t.setUint32(e+re,n,!0)}function yr(t,e=0){return t.getUint32(e+Ee,!0)}function qe(t,e=0){const n=yr(t,e)+1;return t.setUint32(e+Ee,n,!0),n}function Tr(t,e=0){return t.getUint32(e+me,!0)}function se(t,e=0){const n=Tr(t,e)+1;return t.setUint32(e+me,n,!0),n}function Ht(t,e=0){t.setUint32(e+Ie,0,!0);const n=Qi(t,e);return t.setUint32(e+Ie,n,!0),n}function ws(t,e,n,s){let i=0;for(;i<s&&i<cs(n);i++)t.setUint8(e+i,n.charCodeAt(i));for(;i<s;i++)t.setUint8(e+i,0)}function Us(t,e,n){const s=[];for(let i=0;i<n;i++){const o=t.getUint8(e+i);if(o===0)break;s.push(o)}return Vc.decode(new Uint8Array(s))}function Cr(t){switch(t.toUpperCase()){case"INT32":return C.INT32;case"INT64":return C.INT64;case"FLOAT64":return C.FLOAT64;case"TEXT":return C.TEXT;case"BLOB":return C.BLOB;case"UUID":return C.UUID;case"ULID":return C.ULID;default:throw new Error(`Unsupported column data type: "${t}"`)}}function xt(t,e){const n=wn+e*De,s=t.getUint16(n+0,!0);if(s===0)return null;const i=t.getUint16(n+2,!0),o=t.getUint32(n+4,!0),r=t.getUint32(n+8,!0),a=Us(t,n+12,te),l=t.getUint32(n+76,!0),c=t.getUint32(n+80,!0),u=t.getBigUint64(n+84,!0);return{tableId:s,columnCount:i,rootPageId:o,colCatalogPageId:r,name:a,flags:l,rowCountEstimate:c,autoIncNext:u}}function An(t,e,n){const s=wn+e*De;t.setUint16(s+0,n.tableId,!0),t.setUint16(s+2,n.columnCount,!0),t.setUint32(s+4,n.rootPageId,!0),t.setUint32(s+8,n.colCatalogPageId,!0),ws(t,s+12,n.name,te),t.setUint32(s+76,n.flags,!0),t.setUint32(s+80,n.rowCountEstimate,!0),t.setBigUint64(s+84,n.autoIncNext,!0),new Uint8Array(t.buffer,t.byteOffset).fill(0,s+92,s+De)}function qc(t,e){const n=Wt(t,e);return n!==-1?xt(t,n):null}function Wt(t,e){for(let n=0;n<ae;n++){const s=xt(t,n);if(s&&s.flags&Bn.ACTIVE&&s.name===e)return n}return-1}function ki(t,e=0){for(let n=0;n<ae;n++){const s=e+wn+n*De;if(t.getUint16(s,!0)===0)return n}return-1}function fn(t){const e=[];for(let n=0;n<ae;n++){const s=xt(t,n);s&&s.flags&Bn.ACTIVE&&e.push(s)}return e}function _n(t,e){const n=Un+e*Fe,s=t.getUint16(n+0,!0);if(s===0)return null;const i=t.getUint16(n+2,!0),o=t.getUint32(n+4,!0),r=t.getUint8(n+8),a=t.getUint8(n+9),l=[];for(let h=0;h<8;h++)l.push(t.getUint16(n+10+h*2,!0));const c=[];for(let h=0;h<8;h++)c.push(t.getUint8(n+26+h));const u=Us(t,n+34,te);return{indexId:s,tableId:i,rootPageId:o,columnCount:r,flags:a,columnIndices:l,colDirections:c,name:u}}function Ss(t,e,n){const s=Un+e*Fe;t.setUint16(s+0,n.indexId,!0),t.setUint16(s+2,n.tableId,!0),t.setUint32(s+4,n.rootPageId,!0),t.setUint8(s+8,n.columnCount),t.setUint8(s+9,n.flags);for(let o=0;o<8;o++)t.setUint16(s+10+o*2,n.columnIndices[o]??0,!0);for(let o=0;o<8;o++)t.setUint8(s+26+o,n.colDirections[o]??0);ws(t,s+34,n.name,te),new Uint8Array(t.buffer,t.byteOffset).fill(0,s+98,s+Fe)}const Os=8;function Ps(t,e=0){for(let n=0;n<Os;n++){const s=e+Un+n*Fe;if(t.getUint16(s+0,!0)===0)return n}return-1}function Bs(t,e){const n=e.toLowerCase();for(let s=0;s<Os;s++){const i=_n(t,s);if(i&&i.name.toLowerCase()===n)return{slotIdx:s,desc:i}}return null}function ue(t,e){const n=[];for(let s=0;s<Os;s++){const i=_n(t,s);i&&i.tableId===e&&n.push(i)}return n}function vi(t,e,n){if(n===void 0&&(n=e,e=0),n>=Os)return-1;const s=e+Un+n*Fe;return ne(t,s,0,Fe),0}function wr(t,e,n){if(n===void 0&&(n=e,e=0),n>=ae)return-1;const s=e+wn+n*De;return ne(t,s,0,De),0}function Ur(t,e,n,s,i=0){ne(t,e,0,4096),t.setUint8(e+0,Pn),t.setUint8(e+1,0),t.setUint16(e+2,0,!0),t.setUint16(e+4,n,!0),t.setUint16(e+6,s,!0),t.setUint32(e+8,i,!0),t.setUint32(e+12,0,!0)}function Ae(t,e){return{pageType:t.getUint8(e+0),flags:t.getUint8(e+1),colCountInPage:t.getUint16(e+2,!0),tableId:t.getUint16(e+4,!0),startColIndex:t.getUint16(e+6,!0),nextColCatalogPageId:t.getUint32(e+8,!0),pageChecksum:t.getUint32(e+12,!0)}}function xc(t,e,n,s,i,o){t.setUint8(e+0,Pn),t.setUint8(e+1,0),t.setUint16(e+2,n,!0),t.setUint16(e+4,s,!0),t.setUint16(e+6,i,!0),t.setUint32(e+8,o,!0)}function Gi(t,e,n,s){if(n<0||n>=pe)throw new Error(`Invalid catalog in-page slot ${n}`);const i=e+Xs+n*Ys;t.setUint8(i+0,s.type),t.setUint8(i+1,s.flags),t.setUint16(i+2,s.colOffset,!0),ws(t,i+4,s.name,te),t.setUint32(i+68,0,!0)}function Sr(t,e,n){const s=e+Xs+n*Ys,i=t.getUint8(s+0),o=t.getUint8(s+1),r=t.getUint16(s+2,!0),a=Us(t,s+4,te);return{type:i,flags:o,colOffset:r,name:a}}function Or(t){return{pageChainIdx:Math.floor(t/pe),colIdxInPage:t%pe}}function Pr(t,e,n,s){var T,B,L,P,F;if(s.length===0)throw new Error("Table must have at least one column");if(s.length>ce)throw new Ln(s.length,ce);if(Wt(t,n)!==-1)throw new ss(n);const i=ki(t);if(i===-1)throw new _i(ae,ae);const o=i+1,r=e.allocateNewPage(),a=e.getPageBytes(r),l=new DataView(a.buffer,a.byteOffset);l.setUint8(0,13),l.setUint8(1,0),l.setUint16(2,0,!0),l.setUint16(4,4096,!0),l.setUint32(6,0,!0),l.setUint16(10,0,!0),l.setUint32(12,0,!0),e.markPageDirty(r);const c=[];let u=0;for(let w=0;w<s.length;w++){const U=s[w],k=typeof U.type=="string"?Cr(U.type):U.type;let R=0;typeof U.flags=="number"?R=U.flags:((U.primaryKey||(T=U.flags)!=null&&T.primaryKey)&&(R|=z.PRIMARY_KEY),(U.notNull||(B=U.flags)!=null&&B.notNull)&&(R|=z.NOT_NULL),(U.indexed||(L=U.flags)!=null&&L.indexed)&&(R|=z.INDEXED),(U.autoInc||U.autoIncrement||(P=U.flags)!=null&&P.autoInc||(F=U.flags)!=null&&F.autoIncrement)&&(R|=z.AUTO_INC));const A=u;switch(k){case C.INT32:u+=4;break;case C.INT64:case C.FLOAT64:u+=8;break;case C.UUID:case C.ULID:u+=16;break}c.push({type:k,flags:R,colOffset:A,name:U.name})}const h=c.length,f=Math.ceil(h/pe),_=[];for(let w=0;w<f;w++)_.push(e.allocateNewPage());for(let w=0;w<f;w++){const U=_[w],k=w<f-1?_[w+1]:0,R=w*pe,A=Math.min(h-R,pe),N=e.getPageBytes(U),v=new DataView(N.buffer,N.byteOffset);Ur(v,0,o,R,k),v.setUint16(2,A,!0);for(let x=0;x<A;x++){const K=c[R+x];Gi(v,0,x,K)}const X=Ge(N);v.setUint32(12,X,!0),e.markPageDirty(U)}const g=_[0],E={tableId:o,columnCount:h,rootPageId:r,colCatalogPageId:g,name:n,flags:Bn.ACTIVE,rowCountEstimate:0,autoIncNext:1n};An(t,i,E);const I=[];for(let w=0;w<c.length;w++)c[w].flags&z.PRIMARY_KEY&&I.push(c[w]);if(I.length>0){const w=Ps(t);if(w!==-1){const U=e.allocateNewPage(),k=e.getPageBytes(U),R=new DataView(k.buffer,k.byteOffset);ps(R,0,0),e.markPageDirty(U);const A=[0,0,0,0,0,0,0,0],N=[0,0,0,0,0,0,0,0];for(let X=0;X<I.length&&X<8;X++){const x=I[X].name;let K=-1;for(let M=0;M<c.length;M++)if(c[M].name===x){K=M;break}A[X]=K}const v={indexId:w+1,tableId:o,rootPageId:U,columnCount:I.length,flags:mt.PRIMARY|mt.UNIQUE,columnIndices:A,colDirections:N,name:`pk_${n}`};Ss(t,w,v)}}qe(t),se(t),Ht(t);const p=ue(t,o),y=[];for(let w=0;w<I.length;w++)y.push(I[w].name);return{...E,columns:c,primaryKey:y.length>0?y:void 0,indexes:p.length>0?p:void 0}}function Mi(t,e,n){const s=Wt(t,n);if(s===-1)throw new Nn(n);const i=xt(t,s),o=[];let r=i.colCatalogPageId,a=0;for(;r!==0&&a<i.columnCount;){const u=e.getPageBytes(r),h=new DataView(u.buffer,u.byteOffset),f=Ae(h,0);for(let _=0;_<f.colCountInPage;_++){const g=Sr(h,0,_);o.push(g),a++}r=f.nextColCatalogPageId}const l=ue(t,i.tableId),c=[];for(let u=0;u<o.length;u++)o[u].flags&z.PRIMARY_KEY&&c.push(o[u].name);return{...i,columns:o,primaryKey:c.length>0?c:void 0,indexes:l.length>0?l:void 0}}function jc(t,e){const n=fn(t),s=[];for(let i=0;i<n.length;i++)s.push(Mi(t,e,n[i].name));return s}const Hi="AGFzbQEAAAABcBFgAX8Bf2ACf38AYAJ/fwF/YAN/f38AYAN/f38Bf2AEf39/fwF/YAAAYAV/f39/fwF/YAN/f34Bf2ACf34Bf2ABfwBgBH9/f38AYAV/f39/fwBgBX9+f35/AGAFf3x/fH8AYAd/f39/f39/AGAAAX8CDwEDZW52Bm1lbW9yeQIAAgNIRwYAAAQAAwQDAgQFBAACAwcFAQECAwEAAQABAAEAAQABAAECAwAAAQABAQgJAQIAAAoAAQAAAAAAAwAAAgILDAACBQ0ODwUQBggBfwFBgIAECwfYDUwPX19zdGFja19wb2ludGVyAwAHaGV4X3ZhbAABEGNyb2NrZm9yZF9kZWNvZGUAAgt1dWlkX2VuY29kZQADBnN0cmxlbgAEC3V1aWRfZGVjb2RlAAULdWxpZF9lbmNvZGUABgt1bGlkX2RlY29kZQAHD3BhZ2VfdGFibGVfaGFzaAAIDnBhZ2VfdGFibGVfZ2V0AAkOcGFnZV90YWJsZV9zZXQAChFwYWdlX3RhYmxlX2RlbGV0ZQALGGJ1Zl9wb29sX2dldF9zbG90X29mZnNldAAMGmJ1Zl9wb29sX3JlYWRfc2xvdF90b19wYWdlAA0bYnVmX3Bvb2xfd3JpdGVfc2xvdF90b19wYWdlAA4aYnVmX3Bvb2xfZ2V0X3Jlc2lkZW50X3Nsb3QACRRidWZfcG9vbF9hc3NpZ25fc2xvdAAPFmJ1Zl9wb29sX3VuYXNzaWduX3Nsb3QAEBNidWZfcG9vbF9tYXJrX2RpcnR5ABEUYnVmX3Bvb2xfY2xlYXJfZGlydHkAEhFidWZfcG9vbF9pc19kaXJ0eQATCXBhZ2VfaW5pdAAUDnBhZ2VfaW5pdF9mcmVlABUNcGFnZV9nZXRfdHlwZQAWDXBhZ2Vfc2V0X3R5cGUAFxNwYWdlX2dldF9jZWxsX2NvdW50ABgTcGFnZV9zZXRfY2VsbF9jb3VudAAZHHBhZ2VfZ2V0X2NlbGxfY29udGVudF9vZmZzZXQAGhxwYWdlX3NldF9jZWxsX2NvbnRlbnRfb2Zmc2V0ABsVcGFnZV9nZXRfbmV4dF9wYWdlX2lkABwVcGFnZV9zZXRfbmV4dF9wYWdlX2lkAB0TcGFnZV9nZXRfZnJlZV9ieXRlcwAeE3BhZ2Vfc2V0X2ZyZWVfYnl0ZXMAHxFwYWdlX2dldF9jaGVja3N1bQAgEXBhZ2Vfc2V0X2NoZWNrc3VtACEUcGFnZV9nZXRfY2VsbF9vZmZzZXQAIhRwYWdlX3NldF9jZWxsX29mZnNldAAjHnBhZ2VfZ2V0X2NvbnRpZ3VvdXNfZnJlZV9zcGFjZQAkGXBhZ2VfZ2V0X3RvdGFsX2ZyZWVfc3BhY2UAJQxwYWdlX2NvbXBhY3QAJhNwYWdlX2dldF9yb3dfbGVuZ3RoACcPcGFnZV9kZWxldGVfcm93ACgScGFnZV9pbml0X2ludGVyaW9yACkccGFnZV9nZXRfcmlnaHRfY2hpbGRfcGFnZV9pZAAcHHBhZ2Vfc2V0X3JpZ2h0X2NoaWxkX3BhZ2VfaWQAHRlwYWdlX2luc2VydF9pbnRlcmlvcl9jZWxsACobcGFnZV9iaW5hcnlfc2VhcmNoX2ludGVyaW9yACsUcGFnZV9pbml0X2luZGV4X2xlYWYALA1jb21wdXRlX2NyYzMyAC0VY29tcHV0ZV9wYWdlX2NoZWNrc3VtAC4WY29tcHV0ZV9wYWdlMV9jaGVja3N1bQAvEmNhdGFsb2dfaW5pdF9wYWdlMQAwF2NhdGFsb2dfZ2V0X3RvdGFsX3BhZ2VzACAXY2F0YWxvZ19zZXRfdG90YWxfcGFnZXMAIRpjYXRhbG9nX2dldF9mcmVlX3BhZ2VfaGVhZAAxGmNhdGFsb2dfc2V0X2ZyZWVfcGFnZV9oZWFkADIaY2F0YWxvZ19nZXRfc2NoZW1hX3ZlcnNpb24AMyBjYXRhbG9nX2luY3JlbWVudF9zY2hlbWFfdmVyc2lvbgA0GmNhdGFsb2dfZ2V0X2NoYW5nZV9jb3VudGVyADUgY2F0YWxvZ19pbmNyZW1lbnRfY2hhbmdlX2NvdW50ZXIANh1jYXRhbG9nX3VwZGF0ZV9wYWdlMV9jaGVja3N1bQA3GmNhdGFsb2dfd3JpdGVfZml4ZWRfc3RyaW5nADgcY2F0YWxvZ19maW5kX2ZyZWVfdGFibGVfc2xvdAA5HGNhdGFsb2dfZmluZF9mcmVlX2luZGV4X3Nsb3QAOh9jYXRhbG9nX2RlbGV0ZV9pbmRleF9kZXNjcmlwdG9yADsfY2F0YWxvZ19kZWxldGVfdGFibGVfZGVzY3JpcHRvcgA8EWNhdGFsb2dfaW5pdF9wYWdlAD0Z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IABBBmooAAALDAAgAEEGaiABNgAACwoAIABBCmovAAALDAAgAEEKaiABOwAACwoAIABBDGooAAALDAAgAEEMaiABNgAACxAAIAAgAUEBdGpBEGovAAALEgAgACABQQF0akEQaiACOwAACx4AIABBBGovAAAgAEECai8AAEEBdGtBEGtB//8DcQsnACAAQQpqLwAAIABBBGovAAAgAEECai8AAEEBdGtqQRBrQf//A3EL0AEBBn8gAEECai8AACIFRQRAIABBCmpBADsAACAAQQRqQYAgOwAADwsgAUEAIAAgAUcbQQAgAUGAYE8bIgIgACkACDcACCACIAApAAA3AAAgAkEQaiEDIABBEGohBEGAICEBA0AgASAAIAQvAABqIgdBAWovAAAiBmshASAGBEAgAiABQf//A3FqIAcgBvwKAAALIAMgATsAACAEQQJqIQQgA0ECaiEDIAVBAWsiBQ0ACyACQQpqQQA7AAAgAkEEaiABOwAAIAAgAkGAIPwKAAALCgAgAEEBai8AAAt0AQN/IABBAmovAAAiAiABSwRAIAAgACABQQF0akEQaiIDLwAAakEBai8AACEEAkAgAkEBayICIAFGDQAgAiABa0EBdCIBRQ0AIAMgA0ECaiAB/AoAAAsgAEECaiACOwAAIABBCmoiACAALwAAIARqOwAACws1ACAAQQU7AAAgAEEMakEANgAAIABBCmpBADsAACAAQQZqIAE2AAAgAEECakGAgICAATYAAAtsAQV/IABBAmoiBS8AACIDQaICTQR/IABBBGoiBi8AAEEMayIEIABqIgcgATYAACAHQQRqIAI3AAAgACADQQF0Qf7/A3FqQRBqIAQ7AAAgBiAEOwAAIAUgA0EBaiIAOwAAIABB//8DcQVBfwsLhwEBBn8CQCAAQQJqLwAAIgIEQCAAQRBqIQcgAkEBayEDQX8hAgNAIAMgBWoiBEEBdiEGAkAgACAHIARB/v8HcWovAABqIgRBBGo1AAAgAVkEQCAGQQFrIQMgBCgAACECDAELIAZBAWohBQsgAyAFTw0ACyACQX9HDQELIABBBmooAAAhAgsgAgs1ACAAQQo7AAAgAEEMakEANgAAIABBCmpBADsAACAAQQZqIAE2AAAgAEECakGAgICAATYAAAu6AgEEf0HAkQQtAABFBEADQCACQcyJBGogBEEIdiID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";let Hn=null;function Br(){if(!Hn){const t=globalThis.Buffer;if(typeof t<"u"&&typeof t.from=="function")Hn=new Uint8Array(t.from(Hi,"base64"));else{const e=atob(Hi),n=e.length;Hn=new Uint8Array(n);for(let s=0;s<n;s++)Hn[s]=e.charCodeAt(s)}}return Hn}function Nr(t,e){const n=e??Br(),s=new WebAssembly.Module(n),i=new WebAssembly.Instance(s,{env:{memory:t}}),o=i.exports,r=(l,c=0)=>l.byteOffset+c;return{instance:i,exports:o,memory:t,page_init:(l,c,u=ts,h=0)=>{o.page_init(r(l,c),u,h)},page_init_free:(l,c,u=0)=>{o.page_init_free(r(l,c),u)},page_get_type:(l,c)=>o.page_get_type(r(l,c)),page_set_type:(l,c,u)=>{o.page_set_type(r(l,c),u)},page_get_cell_count:(l,c)=>o.page_get_cell_count(r(l,c)),page_set_cell_count:(l,c,u)=>{o.page_set_cell_count(r(l,c),u)},page_get_cell_content_offset:(l,c)=>o.page_get_cell_content_offset(r(l,c)),page_set_cell_content_offset:(l,c,u)=>{o.page_set_cell_content_offset(r(l,c),u)},page_get_next_page_id:(l,c)=>o.page_get_next_page_id(r(l,c)),page_set_next_page_id:(l,c,u)=>{o.page_set_next_page_id(r(l,c),u)},page_get_free_bytes:(l,c)=>o.page_get_free_bytes(r(l,c)),page_set_free_bytes:(l,c,u)=>{o.page_set_free_bytes(r(l,c),u)},page_get_checksum:(l,c)=>o.page_get_checksum(r(l,c)),page_set_checksum:(l,c,u)=>{o.page_set_checksum(r(l,c),u)},page_get_cell_offset:(l,c,u)=>o.page_get_cell_offset(r(l,c),u),page_set_cell_offset:(l,c,u,h)=>{o.page_set_cell_offset(r(l,c),u,h)},page_get_contiguous_free_space:(l,c)=>o.page_get_contiguous_free_space(r(l,c)),page_get_total_free_space:(l,c)=>o.page_get_total_free_space(r(l,c)),page_compact:(l,c,u=0,h)=>{h?bn(l,c,u,h):o.page_compact(r(l,c),u,-1,0,0)},page_get_row_length:(l,c)=>o.page_get_row_length(r(l,c)),page_insert_row:(l,c,u,h=0)=>rn(l,c,u,h),page_delete_row:(l,c,u)=>{o.page_delete_row(r(l,c),u)},page_update_row:(l,c,u,h,f=0)=>Ui(l,c,u,h,f),page_table_hash:(l,c)=>o.page_table_hash(l,c),page_table_get:(l,c,u,h)=>o.page_table_get(r(l,c),u,h),page_table_set:(l,c,u,h,f)=>{if(o.page_table_set(r(l,c),u,h,f)<0)throw new Error(`BufferPool page table full: cannot insert page ${h}`)},page_table_delete:(l,c,u,h)=>o.page_table_delete(r(l,c),u,h)!==0,buf_pool_get_slot_offset:l=>o.buf_pool_get_slot_offset(l),buf_pool_read_slot_to_page:(l,c,u)=>o.buf_pool_read_slot_to_page(r(l,c),u),buf_pool_write_slot_to_page:(l,c,u,h)=>{o.buf_pool_write_slot_to_page(r(l,c),u,h)},buf_pool_get_resident_slot:(l,c,u,h)=>o.buf_pool_get_resident_slot(r(l,c),u,h),buf_pool_assign_slot:(l,c,u,h,f,_)=>{o.buf_pool_assign_slot(r(l,c),r(l,u),h,f,_)},buf_pool_unassign_slot:(l,c,u,h,f)=>{o.buf_pool_unassign_slot(r(l,c),r(l,u),h,f)},buf_pool_mark_dirty:(l,c,u)=>{o.buf_pool_mark_dirty(r(l,c),u)},buf_pool_clear_dirty:(l,c,u)=>{o.buf_pool_clear_dirty(r(l,c),u)},buf_pool_is_dirty:(l,c,u)=>o.buf_pool_is_dirty(r(l,c),u)!==0,buf_pool_pin_slot:(l,c)=>{Li(l,c)},buf_pool_unpin_slot:(l,c)=>{Ri(l,c)},buf_pool_is_pinned:(l,c)=>cn(l,c),buf_pool_find_victim:(l,c,u,h,f,_)=>Di(l,c,u,h,f,_),buf_pool_select_eviction_victim:(l,c,u,h,f,_,g,E)=>Fi(l,c,u,h,f,_,g,E),catalog_init_page1:l=>{o.catalog_init_page1(r(l))},catalog_read_page1_header:(l,c)=>Mn(l,c),catalog_get_total_pages:l=>o.catalog_get_total_pages(r(l)),catalog_set_total_pages:(l,c)=>{o.catalog_set_total_pages(r(l),c)},catalog_get_free_page_head:l=>o.catalog_get_free_page_head(r(l)),catalog_set_free_page_head:(l,c)=>{o.catalog_set_free_page_head(r(l),c)},catalog_get_schema_version:l=>o.catalog_get_schema_version(r(l)),catalog_increment_schema_version:l=>o.catalog_increment_schema_version(r(l)),catalog_get_change_counter:l=>o.catalog_get_change_counter(r(l)),catalog_increment_change_counter:l=>o.catalog_increment_change_counter(r(l)),catalog_update_page1_checksum:l=>o.catalog_update_page1_checksum(r(l)),sql_like_match:(l,c)=>Ye(l,c),fnv1a_32:l=>Cs(l),compare_sorter_keys:un,vm_step:Gn}}function Lr(t=be,e=Qe){const n=qs(t,e),s=n.transientArenaOffset+256*1024,i=Math.ceil(s/65536),o=Math.ceil((n.transientArenaOffset+e)/65536);return new WebAssembly.Memory({initial:i,maximum:Math.max(i,o)})}class Rr{constructor(e){S(this,"io");S(this,"wasmMemory");S(this,"buffer");S(this,"view");S(this,"uint8");S(this,"slotCount");S(this,"maxQueryMemory");S(this,"offsets");S(this,"slotsEndOffset");S(this,"slotToPageOffset");S(this,"pageToSlotOffset");S(this,"pageToSlotBuckets");S(this,"dirtyMaskOffset");S(this,"vmContextOffset");S(this,"resultBufferOffset");S(this,"bytecodeOffset");S(this,"pageScratchpadOffset");S(this,"transientArenaOffset");S(this,"pin_counts");S(this,"slot_dirty_generations");S(this,"ref_bits");S(this,"clock_hand",0);S(this,"arena_offset",0);S(this,"in_flight_acquires",new Map);S(this,"allocation_lock",Promise.resolve());var s,i,o;this.slotCount=e.slotCount??((s=e.pool)==null?void 0:s.slotCount)??be,this.maxQueryMemory=e.maxQueryMemory??((i=e.pool)==null?void 0:i.maxQueryMemory)??Qe;const n=e.memory??((o=e.pool)==null?void 0:o.wasmMemory);if(!n)throw new Error("BufferPoolDriver requires a valid WebAssembly.Memory (or pool with wasmMemory)");if(this.wasmMemory=n,this.buffer=this.wasmMemory.buffer,this.view=new DataView(this.buffer),this.uint8=new Uint8Array(this.buffer),this.offsets=qs(e.useDefaultLayoutOffsets?be:this.slotCount,this.maxQueryMemory),this.slotsEndOffset=this.offsets.slotsEndOffset,this.slotToPageOffset=this.offsets.slotToPageOffset,this.pageToSlotOffset=this.offsets.pageToSlotOffset,this.pageToSlotBuckets=this.offsets.pageToSlotBuckets,this.dirtyMaskOffset=this.offsets.dirtyMaskOffset,this.vmContextOffset=this.offsets.vmContextOffset,this.resultBufferOffset=this.offsets.resultBufferOffset,this.bytecodeOffset=this.offsets.bytecodeOffset,this.pageScratchpadOffset=this.offsets.pageScratchpadOffset,this.transientArenaOffset=this.offsets.transientArenaOffset,this.ref_bits=new Uint8Array(this.slotCount),this.pin_counts=new Uint32Array(this.slotCount),this.slot_dirty_generations=new Uint32Array(this.slotCount),e.io)this.io=e.io;else if(e.vfs)this.io=new mi({vfs:e.vfs,memory:this.wasmMemory});else throw new Error("BufferPoolDriver requires either an Io instance or IVfsAdapter");ne(this.uint8,this.slotToPageOffset,0,this.slotCount*4),ne(this.uint8,this.pageToSlotOffset,0,this.pageToSlotBuckets*ye),ne(this.uint8,this.dirtyMaskOffset,0,Math.ceil(this.slotCount/8)),this.assignSlot(0,1),this.pin_counts[0]=1}validate_slot_idx(e){if(!Number.isInteger(e)||e<0||e>=this.slotCount)throw new Error(`Invalid slot index: ${e}. Must be an integer between 0 and ${this.slotCount-1}`)}validate_page_id(e){if(!Number.isInteger(e)||e<=0)throw new Error(`Invalid page ID: ${e}. Page IDs must be positive integers.`)}async with_allocation_lock(e){const n=this.allocation_lock;let s;this.allocation_lock=new Promise(i=>{s=i}),await n;try{return await e()}finally{s()}}setTransactionCoordinator(e){this.io.setTransactionCoordinator(e)}getSlotOffset(e){return this.validate_slot_idx(e),e*4096}getPageBytesInSlot(e){return this.validate_slot_idx(e),this.uint8.subarray(e*4096,(e+1)*4096)}getSlotDataView(e){return this.validate_slot_idx(e),new DataView(this.buffer,e*4096,4096)}getResidentSlot(e){return this.validate_page_id(e),vt(this.view,this.pageToSlotOffset,this.pageToSlotBuckets,e)}getAssignedPage(e){return this.validate_slot_idx(e),an(this.view,this.slotToPageOffset,e)}assignSlot(e,n){if(this.validate_slot_idx(e),!Number.isInteger(n)||n<=0)throw new Error(`Invalid page ID: ${n}. Must be a positive integer >= 1`);if(e===0&&n!==1)throw new Error(`Cannot reassign slot 0: reserved permanently for page 1 (got page ${n})`);const s=this.getResidentSlot(n);if(s!==-1&&s!==e)throw new Error(`Cannot map page ${n} to slot ${e}: already resident in slot ${s}`);rr(this.view,this.slotToPageOffset,this.pageToSlotOffset,this.pageToSlotBuckets,e,n),this.ref_bits[e]=1}unassignSlot(e){if(this.validate_slot_idx(e),e===0)throw new Error("Cannot unassign slot 0: reserved permanently for page 1");ar(this.view,this.slotToPageOffset,this.pageToSlotOffset,this.pageToSlotBuckets,e),this.ref_bits[e]=0}markDirty(e){this.validate_slot_idx(e),cr(this.uint8,this.dirtyMaskOffset,e),this.slot_dirty_generations[e]++}clearDirty(e){this.validate_slot_idx(e),lr(this.uint8,this.dirtyMaskOffset,e)}isDirty(e){return this.validate_slot_idx(e),Ni(this.uint8,this.dirtyMaskOffset,e)}pinSlot(e){this.validate_slot_idx(e),Li(this.pin_counts,e)}unpinSlot(e){this.validate_slot_idx(e),Ri(this.pin_counts,e)}pinPage(e){this.validate_page_id(e);const n=this.getResidentSlot(e);if(n===-1)throw new Error(`Cannot pin page ${e}: page is not resident in buffer pool`);this.pinSlot(n)}unpinPage(e){if(this.validate_page_id(e),e===1)return;const n=this.getResidentSlot(e);n!==-1&&this.unpinSlot(n)}forceUnpinSlot(e){this.validate_slot_idx(e),e!==0&&(this.pin_counts[e]=0)}forceUnpinPage(e){if(this.validate_page_id(e),e<=1)return;const n=this.getResidentSlot(e);n!==-1&&this.forceUnpinSlot(n)}isSlotPinned(e){return this.validate_slot_idx(e),cn(this.pin_counts,e)}getPinCount(e){return this.validate_slot_idx(e),this.pin_counts[e]}getRefBit(e){return this.validate_slot_idx(e),this.ref_bits[e]}setRefBit(e,n){this.validate_slot_idx(e),this.ref_bits[e]=n?1:0}allocArena(e){const n=e+7&-8;if(this.arena_offset+n>this.maxQueryMemory)throw new gi;const s=this.transientArenaOffset+this.arena_offset;return this.arena_offset+=n,s}resetArena(){this.arena_offset>0&&(ne(this.uint8,this.transientArenaOffset,0,this.arena_offset),this.arena_offset=0)}getArenaOffset(){return this.arena_offset}async acquirePage(e,n=!1){this.validate_page_id(e);const s=this.getResidentSlot(e);if(s!==-1)return this.setRefBit(s,1),n&&this.pinSlot(s),s;const i=this.in_flight_acquires.get(e);if(i){const r=await i;return n&&this.pinSlot(r),r}const o=(async()=>{const{candidate_slot:r,flush_page_id:a,next_clock_hand:l}=Fi(this.buffer,this.ref_bits,this.pin_counts,this.slotToPageOffset,this.dirtyMaskOffset,this.slotCount,this.clock_hand,e);this.clock_hand=l,this.pinSlot(r);try{return await this.io.resolvePageFault(r,e,a),this.assignSlot(r,e),this.setRefBit(r,1),this.clearDirty(r),r}catch(c){throw r!==-1&&this.unpinSlot(r),c}})();this.in_flight_acquires.set(e,o);try{const r=await o;return n||this.unpinSlot(r),r}finally{this.in_flight_acquires.delete(e)}}acquireAndPinPage(e){return this.acquirePage(e,!0)}async flushSlot(e){this.validate_slot_idx(e);const n=this.getAssignedPage(e);if(n===0)return;if(e===0&&n!==1)throw new Error(`Corruption detected: slot 0 is assigned to page ${n} instead of page 1`);const s=this.slot_dirty_generations[e];await this.io.writeSlot(e,n),this.slot_dirty_generations[e]===s&&this.clearDirty(e)}async flushPage(e){this.validate_page_id(e);const n=this.getResidentSlot(e);n!==-1&&this.isDirty(n)&&await this.flushSlot(n)}async flushAllDirty(){for(let e=0;e<this.slotCount;e++)this.isDirty(e)&&await this.flushSlot(e);await this.io.flush()}async allocatePage(e=!1){return this.with_allocation_lock(async()=>{const n=this.getSlotDataView(0),s=pt(n,re),i=pt(n,ee);if(s>0){if(s<=1||i>0&&s>i)throw new Ce(s,`Corrupted free_page_head pointer ${s} (totalPages: ${i})`);const l=await this.acquirePage(s,e),c=this.getSlotDataView(l),u=Vo(c,io);if(u!==ve)throw new Ce(s,`Expected free page type 0x00, got 0x${u.toString(16)}`);const h=pt(c,oo);if(h===s||i>0&&h>i)throw new Ce(s,`Corrupted next_free_page_id pointer ${h} in free page ${s}`);return yt(n,re,h),this.markDirty(0),Fn(c,0),this.markDirty(l),s}const o=i+1;yt(n,ee,o),this.markDirty(0);const r=await this.acquirePage(o,e),a=this.getSlotDataView(r);return Fn(a,0),this.markDirty(r),o})}allocateAndPinPage(){return this.allocatePage(!0)}async freePage(e,n=!1){if(this.validate_page_id(e),e<=1)throw new Error(`Cannot free reserved database page ${e}`);return this.with_allocation_lock(async()=>{const s=this.getSlotDataView(0),i=pt(s,ee);if(i>0&&e>i)throw new Error(`Cannot free page ${e} beyond total pages ${i}`);const o=this.getResidentSlot(e);if(o!==-1){if(n)this.forceUnpinSlot(o);else if(this.isSlotPinned(o))throw new Error(`Cannot free pinned/active database page ${e}`)}const r=await this.acquirePage(e,!0);try{const a=this.getSlotDataView(r),l=Me(a,0);if(l===ve){if(this.unassignSlot(r),n)return;throw new Error(`Double-free detected: page ${e} is already marked free`)}if(!n&&l===Pn)throw new Error(`Cannot free system catalog page ${e}`);const c=pt(s,re);jo(a,0,c),ne(this.uint8,r*4096+qt,0,4096-qt),this.io.isInTransaction()?await this.io.spillOrWriteSlot(r,e):await this.flushSlot(r),this.unassignSlot(r),this.clearDirty(r),this.setRefBit(r,0),yt(s,re,e),this.markDirty(0)}finally{this.unpinSlot(r)}})}async stepVm(e,n){let s=Gn(e,this.view,n);for(;s===O.PAGE_FAULT;){const i=e.cursor.pageId;await this.acquirePage(i),e.status=O.RUNNING,s=Gn(e,this.view,n)}return s}}async function Wi(t){const e=await t.getWalFrameCount();if(e===0)return{frameCount:0,committedTxCount:0,abortedTxCount:0,replayedPageCount:0};const n=await t.readWalHeader();if(!n)return await t.truncateWal(0),{frameCount:0,committedTxCount:0,abortedTxCount:0,replayedPageCount:0};try{fs(n,!0)}catch{return await t.truncateWal(0),{frameCount:0,committedTxCount:0,abortedTxCount:0,replayedPageCount:0}}const s=await t.readWalFrames(0,e),i=new Map,o=new Set;let r=0;for(const u of s){const h=yi(u);if(!h.valid||!h.header)break;const{header:f}=h;if(f.frameSeq!==r+1)break;if(r++,i.has(f.txId)||i.set(f.txId,[]),f.frameType===xn)o.add(f.txId);else if(f.frameType===qn||f.frameType===jn){const _=new Uint8Array(u.buffer,u.byteOffset+ke,4096),g=new Uint8Array(4096);g.set(_),i.get(f.txId).push({pageId:f.pageId,data:g,frameType:f.frameType})}}const a=new Map;let l=0,c=0;for(const[u,h]of i.entries())if(o.has(u)){l++;for(const f of h)f.pageId>0&&a.set(f.pageId,f.data)}else c++;if(a.size>0){const u=[];for(const[h,f]of a.entries())u.push({pageId:h,data:f});u.sort((h,f)=>h.pageId-f.pageId),await t.writePages(u)}return await t.flush(),await t.truncateWal(0),{frameCount:r,committedTxCount:l,abortedTxCount:c,replayedPageCount:a.size}}class Dr{constructor(e,n){S(this,"activeLease",null);S(this,"inFlightNonTxCount",0);S(this,"queue",[]);S(this,"leaseWaiters",[]);S(this,"nextLeaseId",1);S(this,"nextTxId",1);S(this,"crossTabLockName");S(this,"onSyncCrossTab");S(this,"releaseWebLock",null);this.crossTabLockName=e,this.onSyncCrossTab=n}hasWebLocks(){var e;return!!this.crossTabLockName&&typeof navigator<"u"&&typeof((e=navigator==null?void 0:navigator.locks)==null?void 0:e.request)=="function"}async acquireWebLock(){!this.hasWebLocks()||this.releaseWebLock||await new Promise(e=>{navigator.locks.request(this.crossTabLockName,{mode:"exclusive"},()=>new Promise(n=>{this.releaseWebLock=n,e()})).catch(()=>{e()})})}releaseCurrentWebLock(){if(this.releaseWebLock){const e=this.releaseWebLock;this.releaseWebLock=null,e()}}get isLeased(){return this.activeLease!==null}get currentLease(){return this.activeLease}async enqueue(e,n){if(this.activeLease&&n===this.activeLease.leaseId)return e();if(this.activeLease||this.leaseWaiters.length>0||this.hasWebLocks()&&this.inFlightNonTxCount>0)return new Promise((s,i)=>{this.queue.push(async()=>{this.inFlightNonTxCount++;try{this.hasWebLocks()&&this.inFlightNonTxCount===1&&(await this.acquireWebLock(),this.onSyncCrossTab&&await this.onSyncCrossTab());const o=await e();s(o)}catch(o){i(o)}finally{this.inFlightNonTxCount--,this.inFlightNonTxCount===0&&!this.activeLease&&this.releaseCurrentWebLock(),this.drain()}})});this.inFlightNonTxCount++;try{return this.hasWebLocks()&&this.inFlightNonTxCount===1&&(await this.acquireWebLock(),this.onSyncCrossTab&&await this.onSyncCrossTab()),await e()}finally{this.inFlightNonTxCount--,this.inFlightNonTxCount===0&&!this.activeLease&&this.releaseCurrentWebLock(),this.drain()}}async acquireExclusiveLease(){if(!this.activeLease&&this.inFlightNonTxCount===0&&this.queue.length===0){const e={leaseId:this.nextLeaseId++,txId:this.nextTxId++,createdAt:Date.now()};return this.activeLease=e,await this.acquireWebLock(),e}return new Promise(e=>{this.leaseWaiters.push({resolve:async n=>{await this.acquireWebLock(),e(n)}}),this.drain()})}releaseExclusiveLease(e){!this.activeLease||this.activeLease.leaseId!==e||(this.activeLease=null,this.releaseCurrentWebLock(),this.drain())}drain(){if(!this.activeLease){if(this.leaseWaiters.length>0){if(this.inFlightNonTxCount===0){const e=this.leaseWaiters.shift(),n={leaseId:this.nextLeaseId++,txId:this.nextTxId++,createdAt:Date.now()};this.activeLease=n,e.resolve(n)}return}for(;this.queue.length>0&&!this.activeLease&&this.leaseWaiters.length===0&&(!this.hasWebLocks()||this.inFlightNonTxCount===0);){const e=this.queue.shift();e&&e()}}}}class Fr{constructor(e,n,s,i){S(this,"vfs");S(this,"pool");S(this,"io");S(this,"queue");S(this,"activeLease",null);S(this,"snapshotFrameCount",0);S(this,"snapshotWalFrameSeq",0);S(this,"slotSnapshots",new Map);S(this,"pinCountsSnapshot",null);S(this,"spilledPages",new Map);S(this,"committedWalPages",new Map);S(this,"walFrameSeq",0);S(this,"txCommitCount",0);S(this,"checkpointSeq",0);S(this,"instanceSalt",Math.floor(Math.random()*4294967295)>>>0||1);S(this,"expectedWalFrameCount",0);S(this,"lastDiskChangeCounter",0);S(this,"lastDiskSchemaVersion",0);S(this,"onCrossTabInvalidated");S(this,"idleTimer",null);S(this,"isClosed",!1);this.vfs=e,this.pool=n,this.io=s,this.queue=new Dr(i,()=>this.syncCrossTabState())}setOnCrossTabInvalidated(e){this.onCrossTabInvalidated=e}recordDiskPage1State(){const e=this.pool.getSlotDataView(0);this.lastDiskChangeCounter=e.getUint32(me,!0),this.lastDiskSchemaVersion=e.getUint32(Ee,!0)}async reloadFromDisk(e,n,s){this.pool.getPageBytesInSlot(0).set(e),this.pool.clearDirty(0),this.lastDiskChangeCounter=n,this.lastDiskSchemaVersion=s;for(let i=1;i<this.pool.slotCount;i++)this.pool.unassignSlot(i),this.pool.clearDirty(i),this.pool.pin_counts[i]=0;this.pool.pin_counts[0]=1,this.onCrossTabInvalidated&&await this.onCrossTabInvalidated()}async syncCrossTabState(e=!1){if(!e&&!this.queue.hasWebLocks())return;const n=await this.vfs.getWalFrameCount();let s=!1;if(n>0){const o=await this.vfs.readWalHeader();let r=0;if(o)try{r=fs(o,!0).salt1}catch{r=0}(r!==this.instanceSalt||n!==this.expectedWalFrameCount)&&(s=!0,await Wi(this.vfs),this.committedWalPages.clear(),this.walFrameSeq=0,this.txCommitCount=0,this.expectedWalFrameCount=0)}else this.expectedWalFrameCount>0&&(s=!0,this.committedWalPages.clear(),this.walFrameSeq=0,this.txCommitCount=0,this.expectedWalFrameCount=0);const i=await this.vfs.readPage(1);if(i){const o=new DataView(i.buffer,i.byteOffset,i.byteLength),r=o.getUint32(me,!0),a=o.getUint32(Ee,!0);(s||r!==this.lastDiskChangeCounter||a!==this.lastDiskSchemaVersion)&&await this.reloadFromDisk(i,r,a)}}get leaseQueue(){return this.queue}isInTransaction(){return this.activeLease!==null}getActiveLeaseId(){return this.activeLease?this.activeLease.leaseId:null}getActiveTxId(){return this.activeLease?this.activeLease.txId:null}hasSpilledPage(e){return this.spilledPages.has(e)||this.committedWalPages.has(e)}getSpilledPage(e){const n=this.spilledPages.get(e)??this.committedWalPages.get(e);return n?new Uint8Array(n):null}onDirectPageWrite(e,n){if(this.committedWalPages.has(e)&&this.committedWalPages.set(e,new Uint8Array(n)),e===1){const s=new DataView(n.buffer,n.byteOffset,n.byteLength);this.lastDiskChangeCounter=s.getUint32(me,!0),this.lastDiskSchemaVersion=s.getUint32(Ee,!0)}}async spillUncommittedSlot(e,n){if(!this.activeLease){await this.io.writeSlot(e,n);return}this.io.stampSlotChecksum(e,n);const s=this.pool.getPageBytesInSlot(e),i=new Uint8Array(Te);i.set(s),this.spilledPages.set(n,i);const o=this.pool.getSlotDataView(0).getUint32(ee,!0),r=_s({frameType:jn,flags:0,txId:this.activeLease.txId,pageId:n,dbSizePages:o,frameSeq:++this.walFrameSeq},i);await this.vfs.appendWalFrames([r]),this.expectedWalFrameCount=await this.vfs.getWalFrameCount()}async captureSavepoint(){const e=await this.vfs.getWalFrameCount(),n=new Map;for(let o=0;o<this.pool.slotCount;o++){const r=this.pool.getAssignedPage(o);if(r>0){const a=this.pool.isDirty(o),l=new Uint8Array(this.pool.getPageBytesInSlot(o));n.set(o,{pageId:r,dirty:a,data:l})}}const s=new Uint32Array(this.pool.pin_counts),i=new Map;for(const[o,r]of this.spilledPages.entries())i.set(o,new Uint8Array(r));return{frameCount:e,slotSnapshots:n,pinCounts:s,spilledPages:i,walFrameSeq:this.walFrameSeq}}async restoreSavepoint(e){for(let n=1;n<this.pool.slotCount;n++)this.pool.unassignSlot(n),this.pool.clearDirty(n);for(let n=0;n<this.pool.slotCount;n++){const s=e.slotSnapshots.get(n);s&&(this.pool.assignSlot(n,s.pageId),this.pool.getPageBytesInSlot(n).set(s.data),s.dirty?this.pool.markDirty(n):this.pool.clearDirty(n))}this.pool.pin_counts.set(e.pinCounts),this.spilledPages.clear();for(const[n,s]of e.spilledPages.entries())this.spilledPages.set(n,new Uint8Array(s));this.walFrameSeq=e.walFrameSeq,await this.vfs.truncateWal(e.frameCount),this.expectedWalFrameCount=e.frameCount}async begin(){const e=await this.queue.acquireExclusiveLease();this.activeLease=e,this.pauseIdleTimer();try{await this.syncCrossTabState();const n=await this.vfs.getWalFrameCount(),s=await this.vfs.readWalHeader();let i=!1;if(s&&n>0)try{i=fs(s,!0).salt1===this.instanceSalt}catch{i=!1}i||await this.vfs.writeWalHeader(As({checkpointSeq:this.checkpointSeq,salt1:this.instanceSalt})),this.spilledPages.clear();const o=await this.captureSavepoint();return this.snapshotFrameCount=o.frameCount,this.snapshotWalFrameSeq=o.walFrameSeq,this.slotSnapshots=o.slotSnapshots,this.pinCountsSnapshot=o.pinCounts,e}catch(n){throw this.activeLease=null,this.queue.releaseExclusiveLease(e.leaseId),n}}async commit(e){if(!this.activeLease||this.activeLease.leaseId!==e)return;const n=this.activeLease.txId,s=[],i=this.pool.getSlotDataView(0).getUint32(ee,!0);for(const[r,a]of this.spilledPages.entries())this.committedWalPages.set(r,a);for(let r=0;r<this.pool.slotCount;r++)if(this.pool.isDirty(r)){const a=this.pool.getAssignedPage(r);if(a>0){this.io.stampSlotChecksum(r,a);const l=this.pool.getPageBytesInSlot(r),c=new Uint8Array(Te);c.set(l),this.committedWalPages.set(a,c),this.pool.clearDirty(r),s.push(_s({frameType:qn,flags:0,txId:n,pageId:a,dbSizePages:i,frameSeq:++this.walFrameSeq},c))}}s.push(_s({frameType:xn,flags:0,txId:n,pageId:0,dbSizePages:i,frameSeq:++this.walFrameSeq})),await this.vfs.appendWalFrames(s),await this.vfs.flushWal();const o=await this.vfs.getWalFrameCount();this.expectedWalFrameCount=o,this.activeLease=null,this.spilledPages.clear(),this.slotSnapshots.clear(),this.pinCountsSnapshot=null,this.txCommitCount++,this.queue.releaseExclusiveLease(e),this.scheduleIdleTimer(),(o>=256||this.txCommitCount>=100)&&this.queue.enqueue(()=>this.executeCheckpoint())}async rollback(e){!this.activeLease||this.activeLease.leaseId!==e||(await this.restoreSavepoint({frameCount:this.snapshotFrameCount,slotSnapshots:this.slotSnapshots,pinCounts:this.pinCountsSnapshot??new Uint32Array(this.pool.pin_counts),spilledPages:new Map,walFrameSeq:this.snapshotWalFrameSeq}),this.activeLease=null,this.spilledPages.clear(),this.slotSnapshots.clear(),this.pinCountsSnapshot=null,this.queue.releaseExclusiveLease(e),this.scheduleIdleTimer())}async checkpoint(){return this.queue.enqueue(()=>this.executeCheckpoint())}async executeCheckpoint(){const e=await this.vfs.getWalFrameCount(),n=new Map;if(e>0){const r=await this.vfs.readWalFrames(0,e),a=new Map,l=new Set;for(const c of r){const u=yi(c);if(!u.valid||!u.header)break;const{frameType:h,txId:f,pageId:_}=u.header;if(a.has(f)||a.set(f,[]),h===xn)l.add(f);else if(h===qn||h===jn){const g=new Uint8Array(c.buffer,c.byteOffset+ke,Te),E=new Uint8Array(Te);E.set(g),a.get(f).push({pageId:_,data:E})}}for(const[c,u]of a.entries())if(l.has(c))for(const h of u)h.pageId>0&&n.set(h.pageId,h.data)}for(const[r,a]of this.committedWalPages.entries())n.set(r,a);const s=new Map;for(let r=0;r<this.pool.slotCount;r++)if(this.pool.isDirty(r)){const a=this.pool.getAssignedPage(r);if(a>0){this.io.stampSlotChecksum(r,a);const l=this.pool.getPageBytesInSlot(r),c=new Uint8Array(Te);c.set(l),s.set(a,{slotIdx:r,data:c})}}const i=new Set([...n.keys(),...s.keys()]),o=[];for(const r of i)if(s.has(r)){const{slotIdx:a,data:l}=s.get(r);o.push({pageId:r,data:l}),this.pool.clearDirty(a)}else o.push({pageId:r,data:n.get(r)});return o.length>0&&(o.sort((r,a)=>r.pageId-a.pageId),await this.vfs.writePages(o)),await this.vfs.flush(),await this.vfs.truncateWal(0),this.committedWalPages.clear(),this.checkpointSeq++,this.walFrameSeq=0,this.txCommitCount=0,this.expectedWalFrameCount=0,this.recordDiskPage1State(),await this.vfs.writeWalHeader(As({checkpointSeq:this.checkpointSeq,salt1:this.instanceSalt})),{pagesWritten:o.length}}async resetWalAfterImport(){this.spilledPages.clear(),this.committedWalPages.clear(),await this.vfs.truncateWal(0),this.checkpointSeq++,this.walFrameSeq=0,this.txCommitCount=0,this.expectedWalFrameCount=0,this.recordDiskPage1State(),await this.vfs.writeWalHeader(As({checkpointSeq:this.checkpointSeq,salt1:this.instanceSalt}))}scheduleIdleTimer(){this.isClosed||(this.pauseIdleTimer(),this.idleTimer=setTimeout(()=>{this.checkpoint().catch(()=>{})},5e3))}pauseIdleTimer(){this.idleTimer&&(clearTimeout(this.idleTimer),this.idleTimer=null)}async close(){this.isClosed=!0,this.pauseIdleTimer(),await this.checkpoint()}}const br=new Set(["count","sum","avg","min","max"]),Qr=new Set(["upper","lower","length","substr","trim","abs","round","floor","ceil","concat","coalesce"]);function Ue(t){return br.has(t.toLowerCase())}function kr(t){return Qr.has(t.toLowerCase())}function Kc(t){return Ue(t)||kr(t)}function xe(t,e){if(e==="where"){if(t.type==="fn"&&Ue(t.name))throw new os(t.name);if(t.type==="binary"&&(xe(t.left,e),xe(t.right,e)),t.type==="fn")for(const n of t.args)xe(n,e)}}function Jc(t){const e=[];let n=0;const s=t.length;for(;n<s;){const i=t[n];if(/\s/.test(i)){n++;continue}if(/[0-9]/.test(i)||i==="."&&n+1<s&&/[0-9]/.test(t[n+1])){const o=n;let r=!1;for(;n<s&&(/[0-9]/.test(t[n])||t[n]==="."&&!r);)t[n]==="."&&(r=!0),n++;e.push({type:"NUMBER",value:t.slice(o,n),pos:o});continue}if(i==="'"||i==='"'){const o=i,r=n;n++;let a="";for(;n<s&&t[n]!==o;)t[n]==="\\"&&n+1<s&&n++,a+=t[n],n++;n<s&&t[n]===o&&n++,e.push({type:"STRING",value:a,pos:r});continue}if(i==="("){e.push({type:"LPAREN",value:"(",pos:n++});continue}if(i===")"){e.push({type:"RPAREN",value:")",pos:n++});continue}if(i===","){e.push({type:"COMMA",value:",",pos:n++});continue}if(i==="<"){if(n+1<s&&t[n+1]==="="){e.push({type:"OP",value:"<=",pos:n}),n+=2;continue}if(n+1<s&&t[n+1]===">"){e.push({type:"OP",value:"!=",pos:n}),n+=2;continue}e.push({type:"OP",value:"<",pos:n++});continue}if(i===">"){if(n+1<s&&t[n+1]==="="){e.push({type:"OP",value:">=",pos:n}),n+=2;continue}e.push({type:"OP",value:">",pos:n++});continue}if(i==="="){if(n+1<s&&t[n+1]==="="){e.push({type:"OP",value:"=",pos:n}),n+=2;continue}e.push({type:"OP",value:"=",pos:n++});continue}if(i==="!"&&n+1<s&&t[n+1]==="="){e.push({type:"OP",value:"!=",pos:n}),n+=2;continue}if(i==="+"||i==="-"||i==="/"||i==="%"){e.push({type:"OP",value:i,pos:n++});continue}if(i==="*"){e.push({type:"STAR",value:"*",pos:n++});continue}if(/[a-zA-Z_]/.test(i)){const o=n;for(;n<s;)if(/[a-zA-Z0-9_]/.test(t[n]))n++;else if(t[n]==="."&&n+1<s&&/[a-zA-Z_]/.test(t[n+1]))n+=2;else break;const r=t.slice(o,n);e.push({type:"IDENT",value:r,pos:o});continue}n++}return e.push({type:"EOF",value:"",pos:s}),e}class zc{constructor(e){S(this,"tokens");S(this,"cursor",0);this.tokens=e}peek(){return this.tokens[this.cursor]??{type:"EOF",value:"",pos:0}}consume(){const e=this.peek();return this.cursor++,e}match(e,n){const s=this.peek();return s.type!==e||n!==void 0&&s.value.toLowerCase()!==n.toLowerCase()?!1:(this.cursor++,!0)}getPrecedence(e){if(e.type==="OP"||e.type==="STAR"){if(e.value==="="||e.value==="!="||e.value==="<"||e.value==="<="||e.value===">"||e.value===">=")return 5;if(e.value==="+"||e.value==="-")return 10;if(e.value==="*"||e.value==="/"||e.value==="%")return 20}return 0}parse(e=0){let n=this.parsePrimary();for(;;){const s=this.peek(),i=this.getPrecedence(s);if(i===0||i<=e)break;this.consume();const o=this.parse(i);n={type:"binary",op:s.value,left:n,right:o}}return n}parsePrimary(){const e=this.peek();if(e.type==="OP"&&e.value==="-"){this.consume();const n=this.parse(25);return n.type==="literal"&&typeof n.value=="number"?{type:"literal",value:-n.value}:{type:"binary",op:"-",left:{type:"literal",value:0},right:n}}if(this.match("NUMBER"))return{type:"literal",value:Number(e.value)};if(this.match("STRING"))return{type:"literal",value:e.value};if(this.match("LPAREN")){const n=this.parse(0);if(!this.match("RPAREN"))throw new Error("Unclosed parenthesis in expression");return n}if(this.match("STAR"))return{type:"col",name:"*"};if(e.type==="IDENT"){this.consume();const n=e.value,s=n.toLowerCase();if(s==="null"&&this.peek().type!=="LPAREN")return{type:"literal",value:null};if(s==="true"&&this.peek().type!=="LPAREN")return{type:"literal",value:!0};if(s==="false"&&this.peek().type!=="LPAREN")return{type:"literal",value:!1};if(this.match("LPAREN")){const i=[];if(!this.match("RPAREN")){for(;;)if(i.push(this.parse(0)),!this.match("COMMA")){if(this.match("RPAREN"))break;throw new Error(`Expected ',' or ')' in argument list of function ${n}`)}}return{type:"fn",name:s,args:i}}return{type:"col",name:n}}throw new Error(`Unexpected token "${e.value}" in expression at position ${e.pos}`)}}function ut(t){const e=t.trim();if(!e)throw new Error("Cannot parse empty expression");const n=Jc(e);return new zc(n).parse(0)}function tl(t){let e=0,n=null;const s=t.length;for(let i=0;i<s;i++){const o=t[i];if(n){o===n&&t[i-1]!=="\\"&&(n=null);continue}if(o==="'"||o==='"'){n=o;continue}if(o==="("){e++;continue}if(o===")"){e--;continue}if(e===0&&(o===" "||o===" ")&&i+4<s&&t.slice(i+1,i+3).toLowerCase()==="as"&&/\s/.test(t[i+3])){const r=t.slice(0,i).trim(),a=t.slice(i+4).trim();return{exprStr:r,explicitAlias:a}}}return{exprStr:t.trim()}}function jt(t){if(t.type==="col")return t.name.includes(".")?t.name.slice(t.name.lastIndexOf(".")+1):t.name;if(t.type==="fn"){if(t.args.length>0&&t.args[0].type==="col"&&t.args[0].name!=="*"){const e=t.args[0].name.includes(".")?t.args[0].name.slice(t.args[0].name.lastIndexOf(".")+1):t.args[0].name;return`${t.name}_${e}`}return t.name}return t.type==="binary"?"expr":"val"}function Ns(t){const{exprStr:e,explicitAlias:n}=tl(t),s=ut(e),i=n&&n.length>0?n:jt(s);return{expr:s,alias:i}}class st{constructor(e){S(this,"node");this.node=e}add(e){return new st({type:"binary",op:"+",left:this.node,right:Vt(e)})}sub(e){return new st({type:"binary",op:"-",left:this.node,right:Vt(e)})}mul(e){return new st({type:"binary",op:"*",left:this.node,right:Vt(e)})}div(e){return new st({type:"binary",op:"/",left:this.node,right:Vt(e)})}mod(e){return new st({type:"binary",op:"%",left:this.node,right:Vt(e)})}eq(e){return new st({type:"binary",op:"=",left:this.node,right:Vt(e)})}ne(e){return new st({type:"binary",op:"!=",left:this.node,right:Vt(e)})}lt(e){return new st({type:"binary",op:"<",left:this.node,right:Vt(e)})}lte(e){return new st({type:"binary",op:"<=",left:this.node,right:Vt(e)})}gt(e){return new st({type:"binary",op:">",left:this.node,right:Vt(e)})}gte(e){return new st({type:"binary",op:">=",left:this.node,right:Vt(e)})}as(e){return{expr:this.node,alias:e}}}function Vt(t){return t===null?{type:"literal",value:null}:typeof t=="boolean"?{type:"literal",value:t}:t instanceof st?t.node:typeof t=="number"?{type:"literal",value:t}:typeof t=="string"?{type:"literal",value:t}:t}function Vi(t){return new st({type:"col",name:t})}function vr(t){return new st(ut(t))}const el=vr;function Ot(t,e){return new st({type:"fn",name:t.toLowerCase(),args:e.map(n=>typeof n=="string"&&!n.startsWith("'")?Vi(n).node:Vt(n))})}const Gr=(t,...e)=>Ot(t,e),nl={upper:t=>Ot("upper",[t]),lower:t=>Ot("lower",[t]),length:t=>Ot("length",[t]),substr:(t,e,n)=>{const s=[t,e];return n!==void 0&&s.push(n),Ot("substr",s)},trim:t=>Ot("trim",[t]),abs:t=>Ot("abs",[t]),round:t=>Ot("round",[t]),floor:t=>Ot("floor",[t]),ceil:t=>Ot("ceil",[t]),count:t=>Ot("count",[t??Vi("*").node]),sum:t=>Ot("sum",[t]),avg:t=>Ot("avg",[t]),min:t=>Ot("min",[t]),max:t=>Ot("max",[t]),concat:(...t)=>Ot("concat",t),coalesce:(...t)=>Ot("coalesce",t)};for(const[t,e]of Object.entries(nl))Object.defineProperty(Gr,t,{value:e,writable:!0,enumerable:!0,configurable:!0});const sl=Gr;function fe(t,e,n){switch(t.type){case"literal":return t.value;case"col":return t.name==="*"?null:e[t.name]!==void 0?e[t.name]:null;case"binary":{const s=fe(t.left,e,n),i=fe(t.right,e,n);if(s===null||i===null||s===void 0||i===void 0)return null;if(t.op==="="||t.op==="!="||t.op==="<"||t.op==="<="||t.op===">"||t.op===">="){const a=typeof s=="string"&&typeof i=="string"?s<i?-1:s>i?1:0:Number(s)<Number(i)?-1:Number(s)>Number(i)?1:0;switch(t.op){case"=":return a===0?1:0;case"!=":return a!==0?1:0;case"<":return a<0?1:0;case"<=":return a<=0?1:0;case">":return a>0?1:0;case">=":return a>=0?1:0}}const o=Number(s),r=Number(i);switch(t.op){case"+":return o+r;case"-":return o-r;case"*":return o*r;case"/":return r===0?null:o/r;case"%":return r===0?null:o%r}return null}case"fn":{const s=t.name.toLowerCase();if(Ue(s)){if(e[s]!==void 0)return e[s];const o=t.args[0];if(o&&o.type==="col"){const r=`${s}_${o.name}`;if(e[r]!==void 0)return e[r]}return null}const i=t.args.map(o=>fe(o,e,n));switch(s){case"upper":return i[0]!==null&&i[0]!==void 0?String(i[0]).toUpperCase():null;case"lower":return i[0]!==null&&i[0]!==void 0?String(i[0]).toLowerCase():null;case"length":return i[0]!==null&&i[0]!==void 0?String(i[0]).length:null;case"trim":return i[0]!==null&&i[0]!==void 0?String(i[0]).trim():null;case"substr":{if(i[0]===null||i[0]===void 0)return null;const o=String(i[0]),r=Math.max(0,(Number(i[1])||1)-1),a=i[2]!==null&&i[2]!==void 0?Number(i[2]):void 0;return a!==void 0?o.substring(r,r+a):o.substring(r)}case"abs":return i[0]!==null&&i[0]!==void 0?Math.abs(Number(i[0])):null;case"round":return i[0]!==null&&i[0]!==void 0?Math.round(Number(i[0])):null;case"floor":return i[0]!==null&&i[0]!==void 0?Math.floor(Number(i[0])):null;case"ceil":return i[0]!==null&&i[0]!==void 0?Math.ceil(Number(i[0])):null;case"concat":return i.some(o=>o==null)?null:i.map(String).join("");case"coalesce":{for(const o of i)if(o!=null)return o;return null}case"starts_with":case"startswith":return i[0]!==null&&i[0]!==void 0&&i[1]!==null&&i[1]!==void 0?String(i[0]).startsWith(String(i[1]))?1:0:null;case"ends_with":case"endswith":return i[0]!==null&&i[0]!==void 0&&i[1]!==null&&i[1]!==void 0?String(i[0]).endsWith(String(i[1]))?1:0:null;case"contains":return i[0]!==null&&i[0]!==void 0&&i[1]!==null&&i[1]!==void 0?String(i[0]).includes(String(i[1]))?1:0:null;case"like":return i[0]!==null&&i[0]!==void 0&&i[1]!==null&&i[1]!==void 0?Ye(String(i[0]),String(i[1]))?1:0:null;default:{let o;if(typeof n=="function")o=n(s);else if(n instanceof Map){const r=n.get(s);o=typeof r=="function"?r:r==null?void 0:r.call}else if(n&&typeof n=="object"){const r=n[s];o=typeof r=="function"?r:r==null?void 0:r.call}if(o)return o(...i);throw new hi(s)}}}}}const gn=.5,Ls=.05,_e=.02;function Mr(t){const e=[];function n(i){if(i.colName&&e.push(i.colName),i.expr&&s(i.expr),i.children)for(const o of i.children)n(o);i.child&&n(i.child)}function s(i){if(i&&(i.type==="col"&&i.name&&e.push(i.name),i.left&&s(i.left),i.right&&s(i.right),i.args&&Array.isArray(i.args)))for(const o of i.args)s(o)}return n(t),e}function hn(t,e){const n=Mr(t),s=new Set;for(const i of n){const o=ft(i,e);o&&s.add(o.tableIdx)}return s}function $i(t,e){var s,i;const n=Math.max(1,e.rowCountEstimate||10);if(t.type==="cmp"){const o=t.op??"=";if(o==="="){const r=(s=t.colName)==null?void 0:s.toLowerCase(),a=e.columns.findIndex(l=>l.name.toLowerCase()===r);if(a!==-1&&e.indexes){for(const l of e.indexes)if(l.columnCount===1&&l.columnIndices[0]===a)return(l.flags&(mt.PRIMARY|mt.UNIQUE))!==0?1/n:Math.min(.2,5/n)}return .1}if(o==="<"||o==="<="||o===">"||o===">=")return .33;if(o==="!="||o==="<>")return .9;if(o==="like"||o==="contains"||o==="starts_with"||o==="ends_with")return .15}if(t.type==="in"){const o=Math.max(1,((i=t.values)==null?void 0:i.length)||1);return Math.min(1,o*.05)}return t.type==="null"?t.isNull?.05:.95:.2}function ge(t,e,n,s){var h;const i=Math.max(1,t.rowCountEstimate||10);let o=1;for(const f of e)o*=$i(f,t);const r=Math.max(1,Math.round(i*o)),a=n!==void 0&&n.length>0,l=a&&r>1?r*Math.log2(r)*_e:0,c=ks(t,e,e,n);if(c){const f=c.scanType==="point",_=c.scanType==="multi_point",g=c.satisfiesOrderBy===!0,E=g&&s!==void 0&&s>0?Math.min(s,r):r;let I=gn;return f?(I+=1*_e,{cost:I,rows:1,scanType:"IndexScan",indexName:c.index.name,isOrderSatisfied:!0,sortCostAvoided:a?l:void 0}):_?(I=(((h=c.inValues)==null?void 0:h.length)||1)*gn+E*_e,!g&&a&&(I+=l),{cost:I,rows:E,scanType:"IndexScan",indexName:c.index.name,isOrderSatisfied:g,sortCostAvoided:g?l:void 0}):(I+=E*Ls+E*_e,!g&&a&&(I+=l),{cost:I,rows:E,scanType:"IndexScan",indexName:c.index.name,isOrderSatisfied:g,sortCostAvoided:g?l:void 0})}let u=i*_e;return a&&(u+=l),{cost:u,rows:r,scanType:"TableScan",isOrderSatisfied:!1}}function Wn(t,e){if(!t.indexes||t.indexes.length===0)return null;const n=t.columns.findIndex(o=>o.name.toLowerCase()===e.toLowerCase());if(n===-1)return null;let s=null,i=999;for(const o of t.indexes)if(o.columnCount===1&&o.columnIndices[0]===n){const r=(o.flags&mt.PRIMARY)!==0,a=(o.flags&mt.UNIQUE)!==0,l=r?1:a?2:3;l<i&&(i=l,s={index:o,isUnique:r||a})}return s}function Rs(t,e){const n=e.length,s=[],i=Array.from({length:n},()=>new Set);if(!t.joinedTables)return{edges:s,dependencies:i};for(let o=0;o<t.joinedTables.length;o++){const r=t.joinedTables[o],a=o+1,l=ft(r.leftCol,e),c=ft(r.rightCol,e);if(l&&c&&(s.push({tableA:l.tableIdx,tableB:c.tableIdx,colA:l.col.name,colB:c.col.name,op:r.op,type:r.type,declaredRightTable:a}),r.type==="left")){const u=l.tableIdx===a?c.tableIdx:l.tableIdx;i[a].add(u)}}return{edges:s,dependencies:i}}function Vn(t,e){if(t.selectExprs&&t.selectExprs.length>0)return t.selectExprs;const n=new Set,s=new Set;for(const o of e)for(const r of o.columns)n.has(r.name.toLowerCase())&&s.add(r.name.toLowerCase()),n.add(r.name.toLowerCase());const i=[];for(const o of e)for(const r of o.columns){const a=s.has(r.name.toLowerCase())?`${o.name}.${r.name}`:r.name;i.push({expr:{type:"col",name:`${o.name}.${r.name}`},alias:a})}return i}function Ds(t,e,n,s){const i=t.length,o=[];for(let r=1;r<i;r++){const a=t[r],l=e[a],c=t.slice(0,r),u=n.find(E=>E.tableA===a&&c.includes(E.tableB)||E.tableB===a&&c.includes(E.tableA));let h,f,_="=",g="inner";if(u)_=u.op,g=u.type,u.tableA===a?(f=`${l.name}.${u.colA}`,h=`${e[u.tableB].name}.${u.colB}`):(f=`${l.name}.${u.colB}`,h=`${e[u.tableA].name}.${u.colA}`);else{const E=s==null?void 0:s.find(I=>I.table.name===l.name);h=E?E.leftCol:`${e[t[0]].name}.id`,f=E?E.rightCol:`${l.name}.id`,_=E?E.op:"=",g=E?E.type:"inner"}o.push({type:g,table:l,cursor:r,leftCol:h,op:_,rightCol:f})}return o}function Xi(t,e,n,s,i){if(!s||s.length===0)return!1;for(const o of s){if(o.direction==="desc")return!1;const r=o.colName;if(!r)return!1;let a=ft(r,n);if(!a&&i){const l=i.find(c=>c.alias===r);l&&l.expr.type==="col"&&(a=ft(l.expr.name,n))}if(!a||a.tableIdx!==e)return!1}return!0}function Yi(t,e){var n;if(t.type==="null")return 1;if(t.type==="cmp"){const s=t.op??"=";if(s==="like"||s==="not like")return(typeof t.value=="string"?t.value:"").startsWith("%")?25:15;let i=!1;if(e&&t.colName){const o=t.colName.toLowerCase(),r=o.includes(".")?o.slice(o.lastIndexOf(".")+1):o;for(const a of e){const l=a.columns.find(c=>c.name.toLowerCase()===r);if(l){i=l.type===1||l.type===2||l.type===3;break}}}else typeof t.value=="number"&&(i=!0);return s==="="||s==="=="?i?2:4:i?3:6}return t.type==="in"?(((n=t.values)==null?void 0:n.length)??0)<=3?5:10:t.type==="expr"?40:t.type==="and"||t.type==="or"?15:t.type==="not"?8:10}function Zi(t,e){if(!t||t.length===0)return{filters:[],isAlwaysFalse:!1,isAlwaysTrue:!0,metrics:{originalCount:0,optimizedCount:0,isAlwaysFalse:!1,isAlwaysTrue:!0,eliminatedFiltersCount:0,reordered:!1}};const n=t.length,s=[];for(const h of t)h.type==="and"&&Array.isArray(h.children)?s.push(...h.children):s.push(h);const i=new Map,o=[];for(const h of s)if(h.colName){const f=h.colName.toLowerCase();i.has(f)||i.set(f,[]),i.get(f).push(h)}else o.push(h);for(const[h,f]of i.entries()){const _=il(f);if(_)return{filters:[],isAlwaysFalse:!0,isAlwaysTrue:!1,metrics:{originalCount:n,optimizedCount:0,isAlwaysFalse:!0,isAlwaysTrue:!1,contradictionReason:`Contradiction on column "${h}": ${_}`,eliminatedFiltersCount:n,reordered:!1}}}const r=[];let a=0;for(const[,h]of i.entries()){const f=ol(h);a+=h.length-f.length,r.push(...f)}r.push(...o);const l=r.map(h=>qi(h)).join("|");r.sort((h,f)=>{const _=Yi(h,e),g=Yi(f,e);return _-g});const c=r.map(h=>qi(h)).join("|"),u=l!==c;return{filters:r,isAlwaysFalse:!1,isAlwaysTrue:r.length===0,metrics:{originalCount:n,optimizedCount:r.length,isAlwaysFalse:!1,isAlwaysTrue:r.length===0,eliminatedFiltersCount:a,reordered:u}}}function il(t){let e=!1,n=!1;const s=[];let i=null,o=null,r=null;for(const a of t){if(a.type==="null"&&(a.isNull===!0&&(e=!0),a.isNull===!1&&(n=!0)),a.type==="cmp"){const l=a.op??"=",c=a.value;l==="="&&c!==null&&c!==void 0&&s.push(c),typeof c=="number"&&(l===">"?(!i||c>i.val||c===i.val&&!i.strict)&&(i={val:c,strict:!0}):l===">="?(!i||c>i.val)&&(i={val:c,strict:!1}):l==="<"?(!o||c<o.val||c===o.val&&!o.strict)&&(o={val:c,strict:!0}):l==="<="&&(!o||c<o.val)&&(o={val:c,strict:!1}))}if(a.type==="in"&&!a.notIn){if(!a.values||a.values.length===0)return"Empty IN () list";const l=new Set(a.values);if(!r)r=l;else{const c=new Set([...r].filter(u=>l.has(u)));if(c.size===0)return"Mutually exclusive IN lists with no common values";r=c}}}if(e&&n)return"Conflicting IS NULL and IS NOT NULL";if(e&&(s.length>0||i||o))return"Conflicting IS NULL and literal comparison";if(s.length>1){const a=s[0];for(let l=1;l<s.length;l++)if(s[l]!==a)return`Conflicting equality values (${a} !== ${s[l]})`}if(s.length>0&&(i||o)){const a=s[0];if(typeof a=="number"){if(i&&(i.strict?a<=i.val:a<i.val))return`Equality value ${a} violates lower bound ${i.strict?">":">="} ${i.val}`;if(o&&(o.strict?a>=o.val:a>o.val))return`Equality value ${a} violates upper bound ${o.strict?"<":"<="} ${o.val}`}}if(s.length>0&&r){const a=s[0];if(!r.has(a))return`Equality value ${a} not present in IN list`}if(i&&o){if(i.val>o.val)return`Lower bound ${i.val} is greater than upper bound ${o.val}`;if(i.val===o.val&&(i.strict||o.strict))return`Strict range bounds empty at ${i.val}`}return null}function ol(t){const e=[],n=new Set;let s=!1,i;for(const a of t)if(a.type==="cmp"&&(a.op==="="||a.op===void 0)&&a.value!==null&&a.value!==void 0){s=!0,i=a.value;break}let o=null,r=null;for(const a of t)if(a.type==="cmp"&&typeof a.value=="number"){const l=a.op??"=",c=a.value;l===">"?(!o||c>o.val||c===o.val&&!o.strict)&&(o={val:c,strict:!0,filter:a}):l===">="?(!o||c>o.val)&&(o={val:c,strict:!1,filter:a}):l==="<"?(!r||c<r.val||c===r.val&&!r.strict)&&(r={val:c,strict:!0,filter:a}):l==="<="&&(!r||c<r.val)&&(r={val:c,strict:!1,filter:a})}for(const a of t){const l=qi(a);if(!n.has(l)&&!(a.type==="null"&&a.isNull===!1&&s)&&!(a.type==="in"&&!a.notIn&&s&&Array.isArray(a.values)&&a.values.includes(i))){if(a.type==="cmp"&&typeof a.value=="number"){const c=a.op??"=";if(c===">"||c===">="){if(o&&a!==o.filter)continue}else if((c==="<"||c==="<=")&&r&&a!==r.filter)continue}n.add(l),e.push(a)}}return e}function qi(t){return`${t.type}:${t.colName??""}:${t.isNull??""}:${t.op??""}:${String(t.value??"")}:${t.notIn??""}:${JSON.stringify(t.values??"")}`}function Hr(t,e){const n=[...t],s=r=>r.toLowerCase(),i=r=>{const a=r.lastIndexOf(".");return a>=0?r.slice(a+1).toLowerCase():r.toLowerCase()},o=r=>{const a=s(r),l=i(r);for(const c of t)if(c.type==="cmp"&&(c.op==="="||c.op==="=="||c.op===void 0)&&c.colName&&c.value!==null&&c.value!==void 0){const u=s(c.colName),h=i(c.colName);if(u===a||h===a||u===l)return c.value}};for(const r of e){if(r.type!=="inner"&&r.type!=="left"||r.op!=="="&&r.op!=="==")continue;const a=o(r.leftCol);if(a!==void 0&&n.push({type:"cmp",colName:r.rightCol,op:"=",value:a}),r.type==="inner"){const l=o(r.rightCol);l!==void 0&&n.push({type:"cmp",colName:r.leftCol,op:"=",value:l})}}return n}class Fs{constructor(e){S(this,"name","cost");S(this,"indexSeekCost");S(this,"indexNextCost");S(this,"rowEvalCost");this.indexSeekCost=(e==null?void 0:e.indexSeekCost)??gn,this.indexNextCost=(e==null?void 0:e.indexNextCost)??Ls,this.rowEvalCost=(e==null?void 0:e.rowEvalCost)??_e}optimize(e){var R,A;const n=[e.table,...((R=e.joinedTables)==null?void 0:R.map(N=>N.table))??[]],s=n.length,i=Zi(e.filters,n);if(i.isAlwaysFalse)return{plan:{...e,filters:[]},orderedTables:n,metrics:null,isAlwaysFalse:!0,whereMetrics:i.metrics};let o=i.filters,r=i.metrics;if(e.joinedTables&&e.joinedTables.length>0){const N=Hr(o,e.joinedTables);if(N.length>o.length){const v=Zi(N,n);if(v.isAlwaysFalse)return{plan:{...e,filters:[]},orderedTables:n,metrics:null,isAlwaysFalse:!0,whereMetrics:v.metrics};o=v.filters,r=v.metrics}}if(s<=1||!e.joinedTables||e.joinedTables.length===0){const N=new Map;N.set(0,o);const v=ge(e.table,o,e.orderBy,e.limit);return{plan:{...e,filters:o},orderedTables:[e.table],metrics:{totalCost:v.cost,estimatedRows:v.rows,joinOrder:[e.table.name],singleTableFilters:N,crossFilters:[],tableScanTypes:[v.scanType],tableIndexNames:[v.indexName],isOrderSatisfied:v.isOrderSatisfied,sortCostAvoided:v.sortCostAvoided},isAlwaysFalse:!1,isAlwaysTrue:r.isAlwaysTrue,whereMetrics:r,isOrderSatisfied:v.isOrderSatisfied,sortCostAvoided:v.sortCostAvoided}}const a=Kt(o),l=dn(a),c=new Map,u=[];for(let N=0;N<s;N++)c.set(N,[]);for(const N of l){const v=hn(N,n);if(v.size===1){const X=v.values().next().value;X!==void 0&&((A=c.get(X))==null||A.push(N))}else u.push(N)}if(s<=1||!e.joinedTables||e.joinedTables.length===0){const N=ge(n[0],c.get(0)??[]);return{plan:e,orderedTables:n,metrics:{totalCost:N.cost,estimatedRows:N.rows,joinOrder:[n[0].name],singleTableFilters:c,crossFilters:u,tableScanTypes:[N.scanType],tableIndexNames:[N.indexName]}}}const{edges:h,dependencies:f}=Rs(e,n),_=new Map;for(let N=0;N<s;N++)if(f[N].size===0){const v=Xi(n[N],N,n,e.orderBy,e.selectExprs),X=v?e.orderBy.map(M=>{const H=M.colName??"",zt=H.includes(".")?H.slice(H.lastIndexOf(".")+1):H;return{...M,colName:zt}}):void 0,x=ge(n[N],c.get(N)??[],X,v?e.limit:void 0),K=1<<N;_.set(K,{order:[N],cost:x.cost,rows:x.rows,scanTypes:[x.scanType],indexNames:[x.indexName],edgesUsed:[],isOrderSatisfied:x.isOrderSatisfied,sortCostAvoided:x.sortCostAvoided})}const g=1<<s;for(let N=2;N<=s;N++)for(let v=1;v<g;v++)if(rl(v)===N)for(let X=0;X<s;X++){if(!(v&1<<X))continue;const x=v^1<<X,K=_.get(x);if(!K)continue;let M=!0;for(const Pe of f[X])if(!(x&1<<Pe)){M=!1;break}if(!M)continue;const H=this.evaluateJoinStep(K.rows,n[X],X,h,K.order,c.get(X)??[]),zt=K.cost+H.stepCost,Et=_.get(v);let _t=!1,En=zt,mn=Et?Et.cost:0;const In=K.isOrderSatisfied===!0,je=(Et==null?void 0:Et.isOrderSatisfied)===!0;if(N===s&&e.orderBy&&e.orderBy.length>0&&(!In&&H.newRows>1&&(En+=H.newRows*Math.log2(H.newRows)*this.rowEvalCost),Et&&!je&&Et.rows>1&&(mn+=Et.rows*Math.log2(Et.rows)*this.rowEvalCost)),!Et)_t=!0;else if(In&&!je)_t=!0;else if(!In&&je)_t=!1;else{const Pe=K.scanTypes.filter(Be=>Be==="IndexScan").length+(H.scanType==="IndexScan"?1:0),Yn=Et.scanTypes.filter(Be=>Be==="IndexScan").length;if(Pe>Yn&&En<=mn*1.2)_t=!0;else if(Pe<Yn)_t=!1;else if(En<mn*.75)_t=!0;else if(mn<En*.75)_t=!1;else{const Be=K.order[0]===0,pn=Et.order[0]===0;if(Be&&!pn)_t=!0;else if(!Be&&pn)_t=!1;else{const ie=K.order.filter(yn=>yn>X).length,Ms=Et.order.filter((yn,Hs)=>yn>Hs).length;ie<Ms&&(_t=!0)}}}_t&&_.set(v,{order:[...K.order,X],cost:zt,rows:H.newRows,scanTypes:[...K.scanTypes,H.scanType],indexNames:[...K.indexNames,H.indexName],edgesUsed:[...K.edgesUsed,H.matchedEdge],isOrderSatisfied:K.isOrderSatisfied,sortCostAvoided:K.sortCostAvoided})}const E=(1<<s)-1,I=_.get(E);let p,y,T,B,L;I?(p=I.order,y=I.cost,T=I.rows,B=I.scanTypes,L=I.indexNames):(p=Array.from({length:s},(N,v)=>v),y=999999,T=100,B=Array.from({length:s},()=>"TableScan"),L=Array.from({length:s},()=>{}));const P=p.map(N=>n[N]),F=Ds(p,n,h,e.joinedTables),w=Vn(e,n),U=(I==null?void 0:I.isOrderSatisfied)===!0,k=U&&e.orderBy&&e.orderBy.length>0&&T>1?T*Math.log2(T)*this.rowEvalCost:void 0;return{plan:{...e,table:P[0],joinedTables:F,selectExprs:w,filters:o,isOrderSatisfied:U},orderedTables:P,metrics:{totalCost:y,estimatedRows:T,joinOrder:P.map(N=>N.name),singleTableFilters:c,crossFilters:u,tableScanTypes:B,tableIndexNames:L,isOrderSatisfied:U,sortCostAvoided:k},isAlwaysFalse:!1,isAlwaysTrue:r.isAlwaysTrue,whereMetrics:r,isOrderSatisfied:U,sortCostAvoided:k}}evaluateJoinStep(e,n,s,i,o,r){const a=Math.max(1,n.rowCountEstimate||10);let l=1;for(const _ of r)l*=$i(_,n);const c=[];for(const _ of i)if(_.tableA===s&&o.includes(_.tableB)){const g=Wn(n,_.colA);c.push({edge:_,nextCol:_.colA,outerCol:_.colB,idxMatch:g})}else if(_.tableB===s&&o.includes(_.tableA)){const g=Wn(n,_.colB);c.push({edge:_,nextCol:_.colB,outerCol:_.colA,idxMatch:g})}if(c.length===0){const _=e*(2+a*.1),g=Math.max(1,Math.round(e*a*l)),E={tableA:o[0],tableB:s,colA:"",colB:"",op:"=",type:"inner",declaredRightTable:s};return{stepCost:_,newRows:g,scanType:"TableScan",matchedEdge:E}}c.sort((_,g)=>{const E=_.idxMatch?_.idxMatch.isUnique?1:2:3,I=g.idxMatch?g.idxMatch.isUnique?1:2:3;return E-I});const u=c[0];if(u.idxMatch&&u.idxMatch.isUnique){const _=this.indexSeekCost+1*this.rowEvalCost,g=e*_,E=Math.max(1,Math.round(e*l));return{stepCost:g,newRows:E,scanType:"IndexScan",indexName:u.idxMatch.index.name,matchedEdge:u.edge}}if(u.idxMatch&&!u.idxMatch.isUnique){const _=Math.max(1,Math.min(10,Math.round(a/20))),g=this.indexSeekCost+_*this.indexNextCost,E=e*g,I=Math.max(1,Math.round(e*_*l));return{stepCost:E,newRows:I,scanType:"IndexScan",indexName:u.idxMatch.index.name,matchedEdge:u.edge}}const h=e*(2+a*.1),f=Math.max(1,Math.round(e*Math.max(1,Math.round(a*.1))*l));return{stepCost:h,newRows:f,scanType:"TableScan",matchedEdge:u.edge}}}function rl(t){let e=0,n=t;for(;n>0;)e+=n&1,n>>=1;return e}class Wr{constructor(){S(this,"name","heuristic")}optimize(e){var w,U,k;const n=[e.table,...((w=e.joinedTables)==null?void 0:w.map(R=>R.table))??[]],s=n.length,i=Kt(e.filters),o=dn(i),r=new Map,a=[];for(let R=0;R<s;R++)r.set(R,[]);for(const R of o){const A=hn(R,n);if(A.size===1){const N=A.values().next().value;N!==void 0&&((U=r.get(N))==null||U.push(R))}else a.push(R)}if(s<=1||!e.joinedTables||e.joinedTables.length===0){const R=ge(n[0],r.get(0)??[],e.orderBy,e.limit);return{plan:e,orderedTables:n,metrics:{totalCost:R.cost,estimatedRows:R.rows,joinOrder:[n[0].name],singleTableFilters:r,crossFilters:a,tableScanTypes:[R.scanType],tableIndexNames:[R.indexName],isOrderSatisfied:R.isOrderSatisfied,sortCostAvoided:R.sortCostAvoided},isOrderSatisfied:R.isOrderSatisfied,sortCostAvoided:R.sortCostAvoided}}const{edges:l,dependencies:c}=Rs(e,n),u=n.map((R,A)=>{const N=Xi(R,A,n,e.orderBy,e.selectExprs),v=N?e.orderBy.map(X=>{const x=X.colName??"",K=x.includes(".")?x.slice(x.lastIndexOf(".")+1):x;return{...X,colName:K}}):void 0;return ge(R,r.get(A)??[],v,N?e.limit:void 0)}),h=[];for(let R=0;R<s;R++)c[R].size===0&&h.push(R);h.sort((R,A)=>{const N=u[R].isOrderSatisfied?1:0,v=u[A].isOrderSatisfied?1:0;if(N!==v)return v-N;if(u[R].rows!==u[A].rows)return u[R].rows-u[A].rows;const X=u[R].scanType==="IndexScan"?1:0,x=u[A].scanType==="IndexScan"?1:0;return X!==x?x-X:R===0?-1:A===0?1:R-A});const f=h[0]??0,_=[f],g=[u[f].scanType],E=[u[f].indexName];let I=u[f].cost,p=u[f].rows;const y=new Set;for(let R=0;R<s;R++)R!==f&&y.add(R);for(;y.size>0;){const R=[];for(const N of y){let v=!0;for(const M of c[N])if(!_.includes(M)){v=!1;break}if(!v)continue;const X=n[N],x=Math.max(1,X.rowCountEstimate||10);let K=null;for(const M of l)if(M.tableA===N&&_.includes(M.tableB)){const H=Wn(X,M.colA);H&&(!K||H.isUnique)&&(K={isUnique:H.isUnique,indexName:H.index.name})}else if(M.tableB===N&&_.includes(M.tableA)){const H=Wn(X,M.colB);H&&(!K||H.isUnique)&&(K={isUnique:H.isUnique,indexName:H.index.name})}if(K)if(K.isUnique){const M=gn+1*_e;R.push({tableIdx:N,rank:1,stepCost:p*M,newRows:Math.max(1,p),scanType:"IndexScan",indexName:K.indexName})}else{const M=Math.max(1,Math.min(10,Math.round(x/20))),H=gn+M*Ls;R.push({tableIdx:N,rank:2,stepCost:p*H,newRows:Math.max(1,p*M),scanType:"IndexScan",indexName:K.indexName})}else R.push({tableIdx:N,rank:3,stepCost:p*(2+x*.1),newRows:Math.max(1,p*Math.max(1,Math.round(x*.1))),scanType:"TableScan"})}if(R.length===0){const N=y.values().next().value;if(N===void 0)break;_.push(N),g.push("TableScan"),E.push(void 0),y.delete(N);continue}R.sort((N,v)=>N.rank!==v.rank?N.rank-v.rank:Math.abs(N.stepCost-v.stepCost)>.05?N.stepCost-v.stepCost:N.tableIdx-v.tableIdx);const A=R[0];_.push(A.tableIdx),g.push(A.scanType),E.push(A.indexName),I+=A.stepCost,p=A.newRows,y.delete(A.tableIdx)}const T=_.map(R=>n[R]),B=Ds(_,n,l,e.joinedTables),L=Vn(e,n),P=((k=u[f])==null?void 0:k.isOrderSatisfied)===!0,F=P&&e.orderBy&&e.orderBy.length>0&&p>1?p*Math.log2(p)*_e:void 0;return{plan:{...e,table:T[0],joinedTables:B,selectExprs:L,isOrderSatisfied:P},orderedTables:T,metrics:{totalCost:I,estimatedRows:p,joinOrder:T.map(R=>R.name),singleTableFilters:r,crossFilters:a,tableScanTypes:g,tableIndexNames:E,isOrderSatisfied:P,sortCostAvoided:F},isOrderSatisfied:P,sortCostAvoided:F}}}class Vr{constructor(){S(this,"name","noop")}optimize(e){var g,E;const n=[e.table,...((g=e.joinedTables)==null?void 0:g.map(I=>I.table))??[]],s=n.length,i=Kt(e.filters),o=dn(i),r=new Map,a=[];for(let I=0;I<s;I++)r.set(I,[]);for(const I of o){const p=hn(I,n);if(p.size===1){const y=p.values().next().value;y!==void 0&&((E=r.get(y))==null||E.push(I))}else a.push(I)}const l=ge(n[0],r.get(0)??[]),c=[l.scanType],u=[l.indexName];let h=l.cost;const f=l.rows;if(e.joinedTables)for(let I=1;I<s;I++){const p=e.joinedTables[I-1],y=vs(p,n[I],I,n,I);y?(c.push("IndexScan"),u.push(y.index.name),h+=f*.55):(c.push("TableScan"),u.push(void 0),h+=f*(2+(n[I].rowCountEstimate||10)*.1))}const _=Vn(e,n);return{plan:{...e,selectExprs:_},orderedTables:n,metrics:{totalCost:h,estimatedRows:f,joinOrder:n.map(I=>I.name),singleTableFilters:r,crossFilters:a,tableScanTypes:c,tableIndexNames:u}}}}class al{constructor(e){S(this,"name","custom-order");S(this,"orderSpec");this.orderSpec=e}optimize(e){var L,P,F;const n=[e.table,...((L=e.joinedTables)==null?void 0:L.map(w=>w.table))??[]],s=n.length,i=e.joinedTables!==void 0&&e.joinedTables.length>0,o=Kt(e.filters),r=dn(o),a=new Map,l=[];for(let w=0;w<s;w++)a.set(w,[]);for(const w of r){const U=hn(w,n);if(U.size===1){const k=U.values().next().value;k!==void 0&&((P=a.get(k))==null||P.push(w))}else l.push(w)}if(!i||s<=1){const w=ge(n[0],a.get(0)??[]);return{plan:e,orderedTables:n,metrics:{totalCost:w.cost,estimatedRows:w.rows,joinOrder:[n[0].name],singleTableFilters:a,crossFilters:l,tableScanTypes:[w.scanType],tableIndexNames:[w.indexName]}}}const c=Array.from({length:s},(w,U)=>U);if(this.orderSpec){if(typeof this.orderSpec=="function"){const w=this.orderSpec;c.sort((U,k)=>w(n[U],n[k]))}else if(Array.isArray(this.orderSpec)){const w=this.orderSpec;c.sort((U,k)=>{const R=n[U].name,A=n[k].name,N=w.indexOf(R),v=w.indexOf(A),X=N===-1?9999:N,x=v===-1?9999:v;return X!==x?X-x:U-k})}}const{edges:u}=Rs(e,n),h=c.map(w=>n[w]),f=Ds(c,n,u,e.joinedTables),_=Vn(e,n),g={...e,table:h[0],joinedTables:f,selectExprs:_},E=new Map;for(let w=0;w<s;w++)E.set(w,[]);for(const w of r){const U=hn(w,h);if(U.size===1){const k=U.values().next().value;k!==void 0&&((F=E.get(k))==null||F.push(w))}}const I=ge(h[0],E.get(0)??[]),p=[I.scanType],y=[I.indexName];let T=I.cost;const B=I.rows;if(g.joinedTables)for(let w=1;w<s;w++){const U=g.joinedTables[w-1],k=vs(U,h[w],w,h,w);k?(p.push("IndexScan"),y.push(k.index.name),T+=B*.55):(p.push("TableScan"),y.push(void 0),T+=B*(2+(h[w].rowCountEstimate||10)*.1))}return{plan:g,orderedTables:h,metrics:{totalCost:T,estimatedRows:B,joinOrder:h.map(w=>w.name),singleTableFilters:E,crossFilters:l,tableScanTypes:p,tableIndexNames:y}}}}class $r{constructor(e){S(this,"name","custom");this.fn=e}optimize(e){return this.fn(e)}}const cl=$r,ll=Fs,ul=Fs,Al=Wr,fl=Vr,_l=new Fs;function xi(t){return t??_l}function gl(t,e){return xi(e).optimize(t)}function $n(t){if(!t)return d.OP_EQ;switch(String(t).trim().toLowerCase().replace(/\s+/g," ")){case"=":case"==":return d.OP_EQ;case"!=":case"<>":return d.OP_NE;case">":return d.OP_GT;case">=":return d.OP_GE;case"<":return d.OP_LT;case"<=":return d.OP_LE;case"like":return d.OP_STR_LIKE;case"not like":return d.OP_STR_NOT_LIKE;case"contains":return d.OP_STR_CONTAINS;case"starts_with":return d.OP_STR_STARTS_WITH;case"ends_with":return d.OP_STR_ENDS_WITH;default:return d.OP_EQ}}class bs{constructor(){S(this,"buffer",[]);S(this,"textEncoder",new TextEncoder)}emitUint8(e){const n=this.buffer.length;return this.buffer.push(e&255),n}emitUint16(e){const n=this.buffer.length;return this.buffer.push(e&255),this.buffer.push(e>>8&255),n}emitUint32(e){const n=this.buffer.length;return this.buffer.push(e&255),this.buffer.push(e>>8&255),this.buffer.push(e>>16&255),this.buffer.push(e>>24&255),n}emitInt32(e){return this.emitUint32(e)}emitFloat64(e){const n=this.buffer.length,s=new ArrayBuffer(8);new DataView(s).setFloat64(0,e,!0);const i=new Uint8Array(s);for(let o=0;o<8;o++)this.buffer.push(i[o]);return n}emitString(e){const n=this.textEncoder.encode(e),s=this.emitUint16(n.byteLength);for(let i=0;i<n.byteLength;i++)this.buffer.push(n[i]);return s}emitBytes(e){const n=this.emitUint16(e.byteLength);for(let s=0;s<e.byteLength;s++)this.buffer.push(e[s]);return n}patchUint16(e,n){this.buffer[e]=n&255,this.buffer[e+1]=n>>8&255}currentOffset(){return this.buffer.length}toByteArray(){return new Uint8Array(this.buffer)}}function Nt(t,e,n,s,i){i===C.INT32||i===C.INT64?(t.emitUint8(d.OP_COLUMN_INT),t.emitUint8(e),t.emitUint8(n),t.emitUint8(s)):i===C.FLOAT64?(t.emitUint8(d.OP_COLUMN_FLOAT),t.emitUint8(e),t.emitUint8(n),t.emitUint8(s)):i===C.TEXT?(t.emitUint8(d.OP_COLUMN_TEXT),t.emitUint8(e),t.emitUint8(n),t.emitUint8(s)):i===C.UUID?(t.emitUint8(d.OP_COLUMN_UUID),t.emitUint8(e),t.emitUint8(n),t.emitUint8(s)):i===C.ULID?(t.emitUint8(d.OP_COLUMN_ULID),t.emitUint8(e),t.emitUint8(n),t.emitUint8(s)):i===C.BLOB&&(t.emitUint8(d.OP_COLUMN_BLOB),t.emitUint8(e),t.emitUint8(n),t.emitUint8(s))}function Se(t){if(t.type==="in"){if(t.values&&t.values.length>kt)throw new RangeError(`WebDB: whereIn list exceeds maximum limit of ${kt} elements`);return{type:"in",colName:t.colName,expr:t.expr,values:t.values?Array.from(new Set(t.values)):[],notIn:!!t.notIn}}if(t.type==="cmp"){const e=t.op?String(t.op).trim().toLowerCase():"";if(e==="in"||e==="not in"){const n=Array.isArray(t.value)?t.value:[t.value];if(n.length>kt)throw new RangeError(`WebDB: whereIn list exceeds maximum limit of ${kt} elements`);return{type:"in",colName:t.colName,expr:t.expr,values:Array.from(new Set(n)),notIn:e==="not in"}}}if(t.type==="and")return{type:"and",children:t.children?t.children.map(Se):[]};if(t.type==="or")return{type:"or",children:t.children?t.children.map(Se):[]};if(t.type==="not"){const e=t.child;if(!e)return t;if(e.type==="not"&&e.child)return Se(e.child);if(e.type==="in")return{type:"in",colName:e.colName,expr:e.expr,values:e.values,notIn:!e.notIn};if(e.type==="and")return{type:"or",children:e.children?e.children.map(n=>Se({type:"not",child:n})):[]};if(e.type==="or")return{type:"and",children:e.children?e.children.map(n=>Se({type:"not",child:n})):[]};if(e.type==="null")return{type:"null",colName:e.colName,isNull:!e.isNull};if(e.type==="cmp"){const n=e.op?String(e.op).trim().toLowerCase():"";if(n==="in"||n==="not in")return Se({type:"in",colName:e.colName,expr:e.expr,values:Array.isArray(e.value)?e.value:[e.value],notIn:n==="in"});const s={"=":"!=","!=":"=",">":"<=",">=":"<","<":">=","<=":">",like:"not like","not like":"like"};return e.op&&s[e.op]?{type:"cmp",colName:e.colName,op:s[e.op],value:e.value}:{type:"and",children:[{type:"null",colName:e.colName,isNull:!1},{type:"not",child:e}]}}}return t}function Kt(t){if(!t||t.length===0)return null;const e=t.length===1?t[0]:{type:"and",children:t};return Se(e)}function Xr(t){const e=[],n=new Set;function s(i){if(i.type==="null"||i.type==="cmp"||i.type==="expr"||i.type==="in")n.has(i)||(n.add(i),e.push(i));else if(i.type==="and"||i.type==="or"){if(i.children)for(const o of i.children)s(o)}else i.type==="not"&&i.child&&s(i.child)}return s(t),e}function dn(t){if(!t)return[];const e=[];function n(s){if(s.type==="and"&&s.children)for(const i of s.children)n(i);else(s.type==="cmp"||s.type==="in"||s.type==="null")&&e.push(s)}return n(t),e}function ft(t,e){if(t.includes(".")){const n=t.split("."),s=n[0],i=n[1],o=e.findIndex(a=>a.name.toLowerCase()===s.toLowerCase());if(o===-1)return null;const r=e[o].columns.findIndex(a=>a.name.toLowerCase()===i.toLowerCase());return r===-1?null:{tableIdx:o,cursor:o,colIdx:r,col:e[o].columns[r],table:e[o]}}for(let n=0;n<e.length;n++){const s=e[n].columns.findIndex(i=>i.name.toLowerCase()===t.toLowerCase());if(s!==-1)return{tableIdx:n,cursor:n,colIdx:s,col:e[n].columns[s],table:e[n]}}return null}function ji(t,e,n,s,i,o,r,a){const l=r??[n];if(t.type==="expr"){const f=e*2,_=e*2+1;let g=50;const E=()=>{if(g>=64)throw new nt(g);return g++};q(t.expr,n,s,0,f,E,o,void 0,l),s.emitUint8(d.OP_LOAD_INT),s.emitUint8(_),s.emitInt32(1),s.emitUint8(d.OP_EQ),s.emitUint8(f),s.emitUint8(_),i.push(s.emitUint16(0));return}if(t.type==="null"){if(!t.colName)throw new Error("Filter leaf node missing colName");const f=ft(t.colName,l);if(!f)throw new Error(`Column "${t.colName}" not found in tables`);t.isNull?s.emitUint8(d.OP_IS_NULL):s.emitUint8(d.OP_IS_NOT_NULL),s.emitUint8(f.cursor),s.emitUint8(f.colIdx),i.push(s.emitUint16(0));return}if(t.type==="in"){if(!t.values||t.values.length===0){t.notIn&&(s.emitUint8(d.OP_JUMP),i.push(s.emitUint16(0)));return}const f=e*2;if(t.expr){let g=50;const E=()=>{if(g>=64)throw new nt(g);return g++};q(t.expr,n,s,0,f,E,o,void 0,l)}else{if(!t.colName)throw new Error("Filter IN leaf node missing colName");const g=ft(t.colName,l);if(g)Nt(s,g.cursor,g.colIdx,f,g.col.type);else try{const E=ut(t.colName);let I=50;q(E,n,s,0,f,()=>{if(I>=64)throw new nt(I);return I++},o,void 0,l)}catch{throw new Error(`Column "${t.colName}" not found in tables`)}}const _=(a==null?void 0:a.get(t))??0;if(!t.notIn)s.emitUint8(d.OP_IN),s.emitUint8(f),s.emitUint16(_),i.push(s.emitUint16(0));else{let g=-1;if(t.colName){const p=ft(t.colName,l);p&&(s.emitUint8(d.OP_IS_NULL),s.emitUint8(p.cursor),s.emitUint8(p.colIdx),g=s.emitUint16(0))}s.emitUint8(d.OP_IN),s.emitUint8(f),s.emitUint16(_);const E=s.emitUint16(0);s.emitUint8(d.OP_JUMP),i.push(s.emitUint16(0));const I=s.currentOffset();g!==-1&&s.patchUint16(g,I),s.patchUint16(E,I)}return}const c=e*2,u=e*2+1;if(t.expr){let f=50;const _=()=>{if(f>=64)throw new nt(f);return f++};q(t.expr,n,s,0,c,_,o,void 0,l)}else{if(!t.colName)throw new Error("Filter leaf node missing colName");const f=ft(t.colName,l);if(f)Nt(s,f.cursor,f.colIdx,c,f.col.type);else try{const _=ut(t.colName);let g=50;q(_,n,s,0,c,()=>{if(g>=64)throw new nt(g);return g++},o,void 0,l)}catch{throw new Error(`Column "${t.colName}" not found in tables`)}}const h=$n(t.op);s.emitUint8(h),s.emitUint8(c),s.emitUint8(u),i.push(s.emitUint16(0))}function Ki(t,e,n,s,i,o,r,a){const l=r??[n];if(t.type==="expr"){const _=e*2,g=e*2+1;let E=50;const I=()=>{if(E>=64)throw new nt(E);return E++};q(t.expr,n,s,0,_,I,o,void 0,l),s.emitUint8(d.OP_LOAD_INT),s.emitUint8(g),s.emitInt32(1),s.emitUint8(d.OP_EQ),s.emitUint8(_),s.emitUint8(g);const p=s.emitUint16(0);s.emitUint8(d.OP_JUMP),i.push(s.emitUint16(0)),s.patchUint16(p,s.currentOffset());return}if(t.type==="null"){if(!t.colName)throw new Error("Filter leaf node missing colName");const _=ft(t.colName,l);if(!_)throw new Error(`Column "${t.colName}" not found in tables`);t.isNull?s.emitUint8(d.OP_IS_NOT_NULL):s.emitUint8(d.OP_IS_NULL),s.emitUint8(_.cursor),s.emitUint8(_.colIdx),i.push(s.emitUint16(0));return}if(t.type==="in"){if(!t.values||t.values.length===0){t.notIn||(s.emitUint8(d.OP_JUMP),i.push(s.emitUint16(0)));return}const _=e*2;if(t.expr){let E=50;const I=()=>{if(E>=64)throw new nt(E);return E++};q(t.expr,n,s,0,_,I,o,void 0,l)}else{if(!t.colName)throw new Error("Filter IN leaf node missing colName");const E=ft(t.colName,l);if(E)Nt(s,E.cursor,E.colIdx,_,E.col.type);else try{const I=ut(t.colName);let p=50;q(I,n,s,0,_,()=>{if(p>=64)throw new nt(p);return p++},o,void 0,l)}catch{throw new Error(`Column "${t.colName}" not found in tables`)}}const g=(a==null?void 0:a.get(t))??0;if(t.notIn){if(t.colName){const E=ft(t.colName,l);E&&(s.emitUint8(d.OP_IS_NULL),s.emitUint8(E.cursor),s.emitUint8(E.colIdx),i.push(s.emitUint16(0)))}s.emitUint8(d.OP_IN),s.emitUint8(_),s.emitUint16(g),i.push(s.emitUint16(0))}else{if(t.colName){const p=ft(t.colName,l);p&&(s.emitUint8(d.OP_IS_NULL),s.emitUint8(p.cursor),s.emitUint8(p.colIdx),i.push(s.emitUint16(0)))}s.emitUint8(d.OP_IN),s.emitUint8(_),s.emitUint16(g);const E=s.emitUint16(0);s.emitUint8(d.OP_JUMP),i.push(s.emitUint16(0));const I=s.currentOffset();s.patchUint16(E,I)}return}const c=e*2,u=e*2+1;if(t.expr){let _=50;const g=()=>{if(_>=64)throw new nt(_);return _++};q(t.expr,n,s,0,c,g,o,void 0,l)}else{if(!t.colName)throw new Error("Filter leaf node missing colName");const _=ft(t.colName,l);if(_)Nt(s,_.cursor,_.colIdx,c,_.col.type);else try{const g=ut(t.colName);let E=50;q(g,n,s,0,c,()=>{if(E>=64)throw new nt(E);return E++},o,void 0,l)}catch{throw new Error(`Column "${t.colName}" not found in tables`)}}const h=$n(t.op);s.emitUint8(h),s.emitUint8(c),s.emitUint8(u);const f=s.emitUint16(0);s.emitUint8(d.OP_JUMP),i.push(s.emitUint16(0)),s.patchUint16(f,s.currentOffset())}function hl(t,e,n,s,i,o,r,a,l,c){r==="true"?Ki(t,e,n,s,o,a,l,c):r==="false"?ji(t,e,n,s,i,a,l,c):(ji(t,e,n,s,i,a,l,c),s.emitUint8(d.OP_JUMP),o.push(s.emitUint16(0)))}function Xn(t,e,n,s,i,o,r,a,l,c){if(t.type==="cmp"||t.type==="null"||t.type==="expr"||t.type==="in"){const u=s.get(t)??0;hl(t,u,n,e,i,o,r,a,l,c);return}if(t.type==="not"){if(!t.child)return;const u=t.child,h=s.get(u)??0;r==="true"?ji(u,h,n,e,o,a,l,c):r==="false"?Ki(u,h,n,e,i,a,l,c):(Ki(u,h,n,e,i,a,l,c),e.emitUint8(d.OP_JUMP),o.push(e.emitUint16(0)));return}if(t.type==="and"){const u=t.children??[];if(u.length===0){r==="false"&&(e.emitUint8(d.OP_JUMP),i.push(e.emitUint16(0)));return}for(let h=0;h<u.length;h++){const f=u[h];if(h===u.length-1)Xn(f,e,n,s,i,o,r,a,l,c);else{const g=[];Xn(f,e,n,s,g,o,"true",a,l,c);const E=e.currentOffset();for(const I of g)e.patchUint16(I,E)}}return}if(t.type==="or"){const u=t.children??[];if(u.length===0){r==="true"&&(e.emitUint8(d.OP_JUMP),o.push(e.emitUint16(0)));return}for(let h=0;h<u.length;h++){const f=u[h];if(h===u.length-1)Xn(f,e,n,s,i,o,r,a,l,c);else{const g=[];Xn(f,e,n,s,i,g,"false",a,l,c);const E=e.currentOffset();for(const I of g)e.patchUint16(I,E)}}return}}function dl(t,e,n,s,i,o,r){if(t.type==="cmp"){let a;const l=s(t.colName,t.expr);if(l!==void 0)a=l;else if(t.expr)a=i(),q(t.expr,e,n,-1,a,i,r,s);else if(t.colName){a=i();const _=ut(t.colName);q(_,e,n,-1,a,i,r,s)}else a=i(),n.emitUint8(d.OP_LOAD_NULL),n.emitUint8(a);const c=i(),u=t.value;u==null?(n.emitUint8(d.OP_LOAD_NULL),n.emitUint8(c)):typeof u=="number"?Number.isInteger(u)?(n.emitUint8(d.OP_LOAD_INT),n.emitUint8(c),n.emitInt32(u)):(n.emitUint8(d.OP_LOAD_FLOAT),n.emitUint8(c),n.emitFloat64(u)):typeof u=="string"?(n.emitUint8(d.OP_LOAD_TEXT),n.emitUint8(c),n.emitString(u)):typeof u=="boolean"?(n.emitUint8(d.OP_LOAD_INT),n.emitUint8(c),n.emitInt32(u?1:0)):typeof u=="bigint"&&(n.emitUint8(d.OP_LOAD_INT),n.emitUint8(c),n.emitInt32(Number(u)));const h=$n(t.op);n.emitUint8(h),n.emitUint8(a),n.emitUint8(c);const f=n.emitUint16(0);n.emitUint8(d.OP_JUMP),o.push(n.emitUint16(0)),n.patchUint16(f,n.currentOffset());return}if(t.type==="null"){let a;const l=s(t.colName,t.expr);if(l!==void 0)a=l;else if(t.expr)a=i(),q(t.expr,e,n,-1,a,i,r,s);else if(t.colName){a=i();const c=ut(t.colName);q(c,e,n,-1,a,i,r,s)}else a=i(),n.emitUint8(d.OP_LOAD_NULL),n.emitUint8(a);t.isNull?(n.emitUint8(d.OP_REG_IS_NOT_NULL),n.emitUint8(a),o.push(n.emitUint16(0))):(n.emitUint8(d.OP_REG_IS_NULL),n.emitUint8(a),o.push(n.emitUint16(0)));return}if(t.type==="expr"&&t.expr){const a=i();q(t.expr,e,n,-1,a,i,r,s);const l=i();n.emitUint8(d.OP_LOAD_INT),n.emitUint8(l),n.emitInt32(1),n.emitUint8(d.OP_EQ),n.emitUint8(a),n.emitUint8(l);const c=n.emitUint16(0);n.emitUint8(d.OP_JUMP),o.push(n.emitUint16(0)),n.patchUint16(c,n.currentOffset());return}}function Yr(t,e,n,s,i,o,r){if(t.type==="cmp"){let a;const l=s(t.colName,t.expr);if(l!==void 0)a=l;else if(t.expr)a=i(),q(t.expr,e,n,-1,a,i,r,s);else if(t.colName){a=i();const f=ut(t.colName);q(f,e,n,-1,a,i,r,s)}else a=i(),n.emitUint8(d.OP_LOAD_NULL),n.emitUint8(a);const c=i(),u=t.value;u==null?(n.emitUint8(d.OP_LOAD_NULL),n.emitUint8(c)):typeof u=="number"?Number.isInteger(u)?(n.emitUint8(d.OP_LOAD_INT),n.emitUint8(c),n.emitInt32(u)):(n.emitUint8(d.OP_LOAD_FLOAT),n.emitUint8(c),n.emitFloat64(u)):typeof u=="string"?(n.emitUint8(d.OP_LOAD_TEXT),n.emitUint8(c),n.emitString(u)):typeof u=="boolean"?(n.emitUint8(d.OP_LOAD_INT),n.emitUint8(c),n.emitInt32(u?1:0)):typeof u=="bigint"&&(n.emitUint8(d.OP_LOAD_INT),n.emitUint8(c),n.emitInt32(Number(u)));const h=$n(t.op);n.emitUint8(h),n.emitUint8(a),n.emitUint8(c),o.push(n.emitUint16(0));return}if(t.type==="null"){let a;const l=s(t.colName,t.expr);if(l!==void 0)a=l;else if(t.expr)a=i(),q(t.expr,e,n,-1,a,i,r,s);else if(t.colName){a=i();const c=ut(t.colName);q(c,e,n,-1,a,i,r,s)}else a=i(),n.emitUint8(d.OP_LOAD_NULL),n.emitUint8(a);t.isNull?(n.emitUint8(d.OP_REG_IS_NULL),n.emitUint8(a),o.push(n.emitUint16(0))):(n.emitUint8(d.OP_REG_IS_NOT_NULL),n.emitUint8(a),o.push(n.emitUint16(0)));return}if(t.type==="expr"&&t.expr){const a=i();q(t.expr,e,n,-1,a,i,r,s);const l=i();n.emitUint8(d.OP_LOAD_INT),n.emitUint8(l),n.emitInt32(1),n.emitUint8(d.OP_EQ),n.emitUint8(a),n.emitUint8(l),o.push(n.emitUint16(0));return}}function El(t,e,n,s,i,o,r,a,l){a==="true"?dl(t,e,n,s,i,r,l):a==="false"?Yr(t,e,n,s,i,o,l):(Yr(t,e,n,s,i,o,l),n.emitUint8(d.OP_JUMP),r.push(n.emitUint16(0)))}function Oe(t,e,n,s,i,o,r,a,l){if(t.type==="cmp"||t.type==="null"||t.type==="expr"){El(t,n,e,s,i,o,r,a,l);return}if(t.type==="not"){if(!t.child)return;const c=t.child;a==="true"?Oe(c,e,n,s,i,r,o,"false",l):a==="false"?Oe(c,e,n,s,i,o,r,"true",l):Oe(c,e,n,s,i,r,o,"none",l);return}if(t.type==="and"){const c=t.children??[];if(c.length===0){a==="false"&&(e.emitUint8(d.OP_JUMP),o.push(e.emitUint16(0)));return}for(let u=0;u<c.length;u++){const h=c[u];if(u===c.length-1)Oe(h,e,n,s,i,o,r,a,l);else{const _=[];Oe(h,e,n,s,i,_,r,"true",l);const g=e.currentOffset();for(const E of _)e.patchUint16(E,g)}}return}if(t.type==="or"){const c=t.children??[];if(c.length===0){a==="true"&&(e.emitUint8(d.OP_JUMP),r.push(e.emitUint16(0)));return}for(let u=0;u<c.length;u++){const h=c[u];if(u===c.length-1)Oe(h,e,n,s,i,o,r,a,l);else{const _=[];Oe(h,e,n,s,i,o,_,"false",l);const g=e.currentOffset();for(const E of _)e.patchUint16(E,g)}}return}}function ml(t,e,n,s,i,o,r){if(!t)return;const a=[];Oe(t,n,e,s,i,a,o,"true",r);const l=n.currentOffset();for(const c of a)n.patchUint16(c,l)}function Jt(t,e,n,s,i,o,r,a){if(!t)return;const l=[];Xn(t,n,e,s,l,i,"true",o,r,a);const c=n.currentOffset();for(const u of l)n.patchUint16(u,c)}function Zr(t,e,n,s){if(t.type==="literal")return typeof t.value=="number"?Number.isInteger(t.value)?C.INT32:C.FLOAT64:(typeof t.value=="string",C.TEXT);if(t.type==="col"){const i=s??[e],o=ft(t.name,i);return o?o.col.type:C.TEXT}if(t.type==="binary")return C.FLOAT64;if(t.type==="fn"){const i=t.name.toLowerCase();if(n&&n.has(i)){const o=n.get(i);if(o.returnType!==void 0)return o.returnType}if(["upper","lower","substr","trim","concat"].includes(i))return C.TEXT;if(["length","count","starts_with","startswith","ends_with","endswith","like","contains"].includes(i))return C.INT32;if(["abs","round","floor","ceil","sum","avg","min","max"].includes(i)){if(t.args.length>0&&t.args[0].type==="col"){const o=ft(t.args[0].name,s??[e]);if(o&&o.col.type===C.INT32&&i!=="avg")return C.INT32}return C.FLOAT64}return C.TEXT}return C.TEXT}function q(t,e,n,s,i,o,r,a,l){if(a){const c=t.type==="col"?t.name:void 0,u=a(c,t);if(u!==void 0){u!==i&&(n.emitUint8(d.OP_COPY),n.emitUint8(u),n.emitUint8(i));return}}if(t.type==="literal"){const c=t.value;c==null?(n.emitUint8(d.OP_LOAD_NULL),n.emitUint8(i)):typeof c=="number"?Number.isInteger(c)?(n.emitUint8(d.OP_LOAD_INT),n.emitUint8(i),n.emitInt32(c)):(n.emitUint8(d.OP_LOAD_FLOAT),n.emitUint8(i),n.emitFloat64(c)):typeof c=="string"?(n.emitUint8(d.OP_LOAD_TEXT),n.emitUint8(i),n.emitString(c)):typeof c=="boolean"&&(n.emitUint8(d.OP_LOAD_INT),n.emitUint8(i),n.emitInt32(c?1:0));return}if(t.type==="col"){if(s===-1)throw new Error(`Column "${t.name}" in HAVING clause must be an aggregate or grouping column`);const c=l??[e],u=ft(t.name,c);if(!u){if(t.name==="*"){n.emitUint8(d.OP_LOAD_NULL),n.emitUint8(i);return}throw new Error(`Column "${t.name}" does not exist in table "${e.name}"`)}Nt(n,u.cursor,u.colIdx,i,u.col.type);return}if(t.type==="binary"){const c=o(),u=o();q(t.left,e,n,s,c,o,r,a,l),q(t.right,e,n,s,u,o,r,a,l);let h=d.OP_ADD;if(t.op==="+")h=d.OP_ADD;else if(t.op==="-")h=d.OP_SUB;else if(t.op==="*")h=d.OP_MUL;else if(t.op==="/")h=d.OP_DIV;else if(t.op==="%")h=d.OP_MOD;else if(t.op==="="||t.op==="!="||t.op==="<"||t.op==="<="||t.op===">"||t.op===">="){let f=d.OP_EQ;t.op==="="?f=d.OP_EQ:t.op==="!="?f=d.OP_NE:t.op==="<"?f=d.OP_LT:t.op==="<="?f=d.OP_LE:t.op===">"?f=d.OP_GT:t.op===">="&&(f=d.OP_GE),n.emitUint8(f),n.emitUint8(c),n.emitUint8(u);const _=n.emitUint16(0);n.emitUint8(d.OP_LOAD_INT),n.emitUint8(i),n.emitInt32(0),n.emitUint8(d.OP_JUMP);const g=n.emitUint16(0);n.patchUint16(_,n.currentOffset()),n.emitUint8(d.OP_LOAD_INT),n.emitUint8(i),n.emitInt32(1),n.patchUint16(g,n.currentOffset());return}n.emitUint8(h),n.emitUint8(c),n.emitUint8(u),n.emitUint8(i);return}if(t.type==="fn"){const c=t.name.toLowerCase(),u={upper:d.OP_STR_UPPER,lower:d.OP_STR_LOWER,length:d.OP_STR_LENGTH,trim:d.OP_STR_TRIM,abs:d.OP_MATH_ABS,round:d.OP_MATH_ROUND,floor:d.OP_MATH_FLOOR,ceil:d.OP_MATH_CEIL};if(u[c]){const f=o(),_=t.args[0]??{type:"literal",value:null};q(_,e,n,s,f,o,r,a,l),n.emitUint8(u[c]),n.emitUint8(f),n.emitUint8(i);return}if(c==="substr"){const f=o(),_=o(),g=o();q(t.args[0],e,n,s,f,o,r,a,l),q(t.args[1]??{type:"literal",value:1},e,n,s,_,o,r,a,l),t.args[2]!==void 0?q(t.args[2],e,n,s,g,o,r,a,l):(n.emitUint8(d.OP_LOAD_NULL),n.emitUint8(g)),n.emitUint8(d.OP_STR_SUBSTR),n.emitUint8(f),n.emitUint8(_),n.emitUint8(g),n.emitUint8(i);return}const h={starts_with:d.OP_STR_STARTS_WITH,startswith:d.OP_STR_STARTS_WITH,ends_with:d.OP_STR_ENDS_WITH,endswith:d.OP_STR_ENDS_WITH,like:d.OP_STR_LIKE,contains:d.OP_STR_CONTAINS};if(h[c]){const f=o(),_=o();q(t.args[0]??{type:"literal",value:null},e,n,s,f,o,r,a,l),q(t.args[1]??{type:"literal",value:""},e,n,s,_,o,r,a,l),n.emitUint8(h[c]),n.emitUint8(f),n.emitUint8(_);const g=n.emitUint16(0);n.emitUint8(d.OP_LOAD_INT),n.emitUint8(i),n.emitInt32(0),n.emitUint8(d.OP_JUMP);const E=n.emitUint16(0);n.patchUint16(g,n.currentOffset()),n.emitUint8(d.OP_LOAD_INT),n.emitUint8(i),n.emitInt32(1),n.patchUint16(E,n.currentOffset());return}if(c==="concat"||c==="coalesce"){const f=t.args.length,_=o();for(let E=1;E<f;E++)o();for(let E=0;E<f;E++)q(t.args[E],e,n,s,_+E,o,r,a,l);const g=c==="concat"?d.OP_STR_CONCAT:d.OP_COALESCE;n.emitUint8(g),n.emitUint8(_),n.emitUint8(f),n.emitUint8(i);return}if(r&&r.has(c)){const f=r.get(c),_=t.args.length;let g=i;if(_>0){g=o();for(let E=1;E<_;E++)o();for(let E=0;E<_;E++)q(t.args[E],e,n,s,g+E,o,r,a,l)}n.emitUint8(d.OP_CALL_UDF),n.emitUint16(f),n.emitUint8(g),n.emitUint8(_),n.emitUint8(i);return}throw new hi(c)}}function Ji(t,e,n,s){n==null?(t.emitUint8(d.OP_LOAD_NULL),t.emitUint8(e)):typeof n=="number"?s===C.FLOAT64||!Number.isInteger(n)?(t.emitUint8(d.OP_LOAD_FLOAT),t.emitUint8(e),t.emitFloat64(n)):(t.emitUint8(d.OP_LOAD_INT),t.emitUint8(e),t.emitInt32(Math.floor(n))):typeof n=="bigint"?(t.emitUint8(d.OP_LOAD_INT),t.emitUint8(e),t.emitInt32(Number(n))):typeof n=="string"?(t.emitUint8(d.OP_LOAD_TEXT),t.emitUint8(e),t.emitString(n)):typeof n=="boolean"&&(t.emitUint8(d.OP_LOAD_INT),t.emitUint8(e),t.emitInt32(n?1:0))}function Qs(t){switch(t){case C.INT32:return-2147483648;case C.INT64:return-9223372036854775808n;case C.FLOAT64:return-1/0;case C.TEXT:case C.UUID:case C.ULID:return"";case C.BLOB:return new Uint8Array(0);default:return 0}}function zi(t,e,n,s){var a;if(!n||n.length===0)return!1;for(const l of n)if(l.direction==="desc")return!1;const i=t.columnIndices.map(l=>e.columns[l].name.toLowerCase());let o=0;if(s&&s.size>0)for(;o<i.length&&s.has(i[o]);)o++;let r=0;for(;o<i.length&&r<n.length;){const l=(a=n[r].colName)==null?void 0:a.toLowerCase();if(!l||l!==i[o])return!1;o++,r++}return r===n.length}function qr(t,e,n,s,i){if(!n||n.length===0)return!1;for(const o of n){if(o.direction==="desc")return!1;const r=o.colName;if(!r)return!1;if(s&&s.length>0){let a=ft(r,s);if(!a&&i){const l=i.find(c=>c.alias===r);l&&l.expr.type==="col"&&(a=ft(l.expr.name,s))}if(!a||a.tableIdx!==0)return!1}else{const a=r.includes(".")?r.slice(r.lastIndexOf(".")+1):r;if(!t.columns.some(c=>c.name.toLowerCase()===a.toLowerCase()))return!1}}return!0}function ks(t,e,n,s){if(!t.indexes||t.indexes.length===0)return null;const i=n??e,o=new Set;for(const a of e)a.type==="cmp"&&(a.op==="="||a.op===void 0)&&a.colName&&a.value!==void 0&&a.value!==null&&o.add(a.colName.toLowerCase());const r=a=>(s&&s.length>0&&(a.scanType==="point"&&a.index.flags&(mt.PRIMARY|mt.UNIQUE)||zi(a.index,t,s,o))&&(a.satisfiesOrderBy=!0),a);for(const a of t.indexes)if(a.flags&mt.PRIMARY&&a.columnCount===1){const l=t.columns[a.columnIndices[0]];for(let c=0;c<e.length;c++){const u=e[c];if(u.type==="cmp"&&(u.op==="="||u.op===void 0)&&u.colName===l.name&&u.value!==void 0&&u.value!==null)return r({index:a,scanType:"point",seekFilter:u,filterIndex:i.indexOf(u),keyType:l.type});if(u.type==="in"&&!u.notIn&&u.colName===l.name&&Array.isArray(u.values)&&u.values.length>0){const h=Array.from(new Set(u.values.filter(f=>f!=null)));return r({index:a,scanType:"multi_point",seekFilter:u,filterIndex:i.indexOf(u),keyType:l.type,inValues:h})}}}for(const a of t.indexes)if(a.flags&mt.UNIQUE&&a.columnCount===1){const l=t.columns[a.columnIndices[0]];for(let c=0;c<e.length;c++){const u=e[c];if(u.type==="cmp"&&(u.op==="="||u.op===void 0)&&u.colName===l.name&&u.value!==void 0&&u.value!==null)return r({index:a,scanType:"point",seekFilter:u,filterIndex:i.indexOf(u),keyType:l.type});if(u.type==="in"&&!u.notIn&&u.colName===l.name&&Array.isArray(u.values)&&u.values.length>0){const h=Array.from(new Set(u.values.filter(f=>f!=null)));return r({index:a,scanType:"multi_point",seekFilter:u,filterIndex:i.indexOf(u),keyType:l.type,inValues:h})}}}for(const a of t.indexes)if(a.columnCount>1){const l=[];let c=!0;for(let u=0;u<a.columnCount;u++){const h=t.columns[a.columnIndices[u]],f=e.find(_=>_.type==="cmp"&&(_.op==="="||_.op===void 0)&&_.colName===h.name&&_.value!==void 0&&_.value!==null);if(f)l.push(f);else{c=!1;break}}if(c){const u={};for(const f of l)u[f.colName]=f.value;const h=Ts(t.columns,a.columnIndices,a.columnCount,u);return r({index:a,scanType:"point",seekFilter:l[0],filterIndex:i.indexOf(l[0]),keyType:C.BLOB,compositeValue:h})}}for(const a of t.indexes)if(a.columnCount===1){const l=t.columns[a.columnIndices[0]];for(let c=0;c<e.length;c++){const u=e[c];if(u.type==="cmp"&&(u.op==="="||u.op===void 0)&&u.colName===l.name&&u.value!==void 0&&u.value!==null)return r({index:a,scanType:"range",seekFilter:u,filterIndex:i.indexOf(u),keyType:l.type})}}for(const a of t.indexes)if(a.columnCount===1){const l=t.columns[a.columnIndices[0]];for(let c=0;c<e.length;c++){const u=e[c];if(u.type==="cmp"&&(u.op===">="||u.op===">")&&u.colName===l.name&&u.value!==void 0&&u.value!==null)return r({index:a,scanType:"range",seekFilter:u,filterIndex:i.indexOf(u),keyType:l.type})}}if(s&&s.length>0){for(const a of t.indexes)if(zi(a,t,s,o))if(a.columnCount===1){const l=t.columns[a.columnIndices[0]];return{index:a,scanType:"range",seekFilter:void 0,filterIndex:-1,keyType:l.type,satisfiesOrderBy:!0}}else{const l={};for(let u=0;u<a.columnCount;u++){const h=t.columns[a.columnIndices[u]],f=e.find(_=>_.type==="cmp"&&(_.op==="="||_.op===void 0)&&_.colName===h.name&&_.value!==void 0&&_.value!==null);f?l[h.name]=f.value:l[h.name]=Qs(h.type)}const c=Ts(t.columns,a.columnIndices,a.columnCount,l);return{index:a,scanType:"range",seekFilter:void 0,filterIndex:-1,keyType:C.BLOB,compositeValue:c,satisfiesOrderBy:!0}}}return null}function vs(t,e,n,s,i){if(t.op!=="="||!e.indexes||e.indexes.length===0)return null;const o=ft(t.leftCol,s),r=ft(t.rightCol,s);if(!o||!r)return null;let a=null,l=null;if(o.tableIdx===n&&r.tableIdx<n?(a=o,l=r):r.tableIdx===n&&o.tableIdx<n&&(a=r,l=o),!a||!l)return null;let c=null,u=999;for(const f of e.indexes)if(f.columnCount===1&&f.columnIndices[0]===a.colIdx){const _=(f.flags&mt.PRIMARY)!==0,g=(f.flags&mt.UNIQUE)!==0,E=_?1:g?2:3;E<u&&(u=E,c=f)}if(!c)return null;const h=(c.flags&(mt.PRIMARY|mt.UNIQUE))!==0;return{index:c,isUnique:h,innerCol:a,outerCol:l,indexCursor:i}}function to(t,e){var Ms,yn,Hs,Kr,Jr,zr,ta,ea,na;const n=[t.table,...((Ms=t.joinedTables)==null?void 0:Ms.map(D=>D.table))??[]],i=xi((e==null?void 0:e.planner)??t.planner).optimize(t),o=i.orderedTables??n,r=i.whereMetrics,a=i.metrics;if(i.isAlwaysFalse){const D=new bs;D.emitUint8(d.OP_HALT);const G=D.toByteArray();return t.outputColumns&&(G.outputColumns=t.outputColumns),G.allTables=o,G.whereMetrics=r,G}const l=i.plan;l!==t&&Object.assign(t,l);const c=t.joinedTables!==void 0&&t.joinedTables.length>0,u=Kt(t.filters),h=u?Xr(u):[],f=dn(u),_=Array.from({length:o.length},()=>[]),g=new Set;if(c&&a)for(let D=0;D<o.length;D++){const G=n.indexOf(o[D]);if(G!==-1){const W=a.singleTableFilters.get(G)??[];if(D===0||t.joinedTables&&((yn=t.joinedTables[D-1])==null?void 0:yn.type)==="inner"){_[D]=W;for(const $ of W)g.add($)}}}const E=[];for(const D of f)g.has(D)||E.push(D);const I=Kt(E),p=c&&qr(o[0],t.joinedTables,t.orderBy,o,t.selectExprs),y=p?t.orderBy.map(D=>{const G=D.colName??"",W=G.includes(".")?G.slice(G.lastIndexOf(".")+1):G;return{...D,colName:W}}):void 0,T=c?ks(o[0],_[0],h,y):null,B=p&&!!(T!=null&&T.satisfiesOrderBy);let L=o.length,P=-1;T&&L<16&&(P=L++);const F=new Array(o.length).fill(null);if(c&&t.joinedTables)for(let D=1;D<o.length;D++){const G=t.joinedTables[D-1];if(L<16){const W=vs(G,o[D],D,o,L);W&&(F[D]=W,L++)}}const w=L;if(w>16)throw new is(w,16);for(const D of f)if(D.type==="in"&&!D.notIn&&(!D.values||D.values.length===0)){const G=new bs;G.emitUint8(d.OP_HALT);const W=G.toByteArray();return t.outputColumns&&(W.outputColumns=t.outputColumns),W}const U=[],k=new Map;for(const D of h)if(D.type==="in"){const G=U.length;k.set(D,G);const W=new Set;if(D.values)for(const $ of D.values)$!=null&&(W.add($),typeof $=="bigint"?W.add(Number($)):typeof $=="number"&&Number.isSafeInteger($)&&W.add(BigInt($)));U.push(W)}const R=new Map;for(let D=0;D<h.length;D++)R.set(h[D],D);if(h.length*2>=64)throw new nt(h.length*2);if(t.orderBy&&t.orderBy.length>8)throw new vo(t.orderBy.length);if(t.groupBy&&t.groupBy.length>8)throw new Go(t.groupBy.length);const A=new bs;if(t.limit!==void 0&&t.limit<=0)return A.emitUint8(d.OP_HALT),A.toByteArray();let N=h.length*2;const v=t.offset!==void 0&&t.offset>0,X=t.limit!==void 0&&t.limit>0,x=v?N++:-1,K=X?N++:-1;if(N>=64)throw new nt(N);const M=t.table;for(let D=0;D<h.length;D++){const G=h[D];if(G.type==="cmp"){const W=D*2+1,$=G.value;if($==null)A.emitUint8(d.OP_LOAD_NULL),A.emitUint8(W);else if(typeof $=="number"){const gt=G.colName?ft(G.colName,o):void 0;gt&&gt.col.type===C.FLOAT64?(A.emitUint8(d.OP_LOAD_FLOAT),A.emitUint8(W),A.emitFloat64($)):Number.isInteger($)?(A.emitUint8(d.OP_LOAD_INT),A.emitUint8(W),A.emitInt32(Math.floor($))):(A.emitUint8(d.OP_LOAD_FLOAT),A.emitUint8(W),A.emitFloat64($))}else typeof $=="bigint"?(A.emitUint8(d.OP_LOAD_INT),A.emitUint8(W),A.emitInt32(Number($))):typeof $=="string"?(A.emitUint8(d.OP_LOAD_TEXT),A.emitUint8(W),A.emitString($)):typeof $=="boolean"&&(A.emitUint8(d.OP_LOAD_INT),A.emitUint8(W),A.emitInt32($?1:0))}}if(v&&(A.emitUint8(d.OP_LOAD_INT),A.emitUint8(x),A.emitInt32(t.offset)),X&&(A.emitUint8(d.OP_LOAD_INT),A.emitUint8(K),A.emitInt32(t.limit)),t.aggregates&&t.aggregates.length>0||t.groupBy&&t.groupBy.length>0){const D=((Hs=t.groupBy)==null?void 0:Hs.length)??0,G=t.aggregates??[],W=G.length,$=[];for(const Q of t.groupBy??[]){const V=typeof Q=="string"?Q:Q.colName??(Q.expr?jt(Q.expr):"group_key"),Y=(Kr=t.selectExprs)==null?void 0:Kr.find(At=>{if(At.alias===V)return!0;if(typeof Q=="object"&&Q.expr)return JSON.stringify(At.expr)===JSON.stringify(Q.expr);if(typeof Q=="string"&&Q.includes("("))try{const Zt=ut(Q);return JSON.stringify(At.expr)===JSON.stringify(Zt)}catch{return!1}return!1}),Z=(Y==null?void 0:Y.alias)??V,j=M.columns.find(At=>At.name===V||At.name===Z);j?$.push({...j,name:Z}):$.push({name:Z,type:C.TEXT,flags:z.NONE,colOffset:0})}for(let Q=0;Q<G.length;Q++){const V=G[Q],Y=V.alias??(V.colName?`${V.func}_${V.colName}`:V.func),Z=V.func==="count"?C.INT32:C.FLOAT64;$.push({name:Y,type:Z,flags:z.NONE,colOffset:0})}const J=N,tt=J+D,it=tt+4,ht=it+4,et=ht+D,St=et+W;if(St>=64)throw new nt(St);A.emitUint8(d.OP_AGG_INIT),A.emitUint8(0),A.emitUint8(J),A.emitUint8(D),A.emitUint8(0),A.emitUint8(d.OP_OPEN_CURSOR),A.emitUint8(0),A.emitUint32(M.rootPageId),A.emitUint8(d.OP_REWIND),A.emitUint8(0);const Lt=A.emitUint16(0),rt=A.currentOffset(),Pt=[];if(Jt(u,M,A,R,Pt,t.udfNameMap,void 0,k),t.groupBy)for(let Q=0;Q<t.groupBy.length;Q++){const V=t.groupBy[Q],Y=J+Q;let Z=Math.max(St+4,40);const j=()=>{if(Z>=64)throw new nt(Z);return Z++};if(typeof V=="object"&&V.expr)q(V.expr,M,A,0,Y,j,t.udfNameMap);else{const At=typeof V=="string"?V:V.colName,Zt=(zr=(Jr=t.selectExprs)==null?void 0:Jr.find(It=>It.alias===At))==null?void 0:zr.expr;if(Zt)q(Zt,M,A,0,Y,j,t.udfNameMap);else{const It=M.columns.findIndex(Rt=>Rt.name===At);if(It!==-1){const Rt=M.columns[It];Nt(A,0,It,Y,Rt.type)}else try{const Rt=ut(At);q(Rt,M,A,0,Y,j,t.udfNameMap)}catch{throw new Error(`Grouping column "${At}" not found in table "${M.name}"`)}}}}W===0&&D>0&&(A.emitUint8(d.OP_AGG_STEP),A.emitUint8(0),A.emitUint8(J),A.emitUint8(D),A.emitUint8(255),A.emitUint8(0));const Xt=G.some(Q=>Q.func==="count"),bt=G.some(Q=>Q.func==="avg"),Ne=G.some(Q=>Q.func==="sum"),oe=G.some(Q=>Q.func==="min"),Bt=G.some(Q=>Q.func==="max");if(Xt||bt||Ne){const Q=G.find(Y=>Y.func==="count");let V=255;if(Q&&Q.colName&&Q.colName!=="*"){const Y=M.columns.findIndex(Z=>Z.name===Q.colName);if(Y!==-1){const Z=M.columns[Y];V=tt,Nt(A,0,Y,V,Z.type)}}A.emitUint8(d.OP_AGG_STEP),A.emitUint8(0),A.emitUint8(J),A.emitUint8(D),A.emitUint8(V),A.emitUint8(0)}if(Ne||bt){const Q=G.find(Y=>Y.func==="sum"||Y.func==="avg");let V=255;if(Q&&Q.colName&&Q.colName!=="*"){const Y=M.columns.findIndex(Z=>Z.name===Q.colName);if(Y!==-1){const Z=M.columns[Y];V=tt+1,Nt(A,0,Y,V,Z.type)}}A.emitUint8(d.OP_AGG_STEP),A.emitUint8(0),A.emitUint8(J),A.emitUint8(D),A.emitUint8(V),A.emitUint8(1)}if(oe){const Q=G.find(Y=>Y.func==="min");let V=255;if(Q&&Q.colName&&Q.colName!=="*"){const Y=M.columns.findIndex(Z=>Z.name===Q.colName);if(Y!==-1){const Z=M.columns[Y];V=tt+2,Nt(A,0,Y,V,Z.type)}}A.emitUint8(d.OP_AGG_STEP),A.emitUint8(0),A.emitUint8(J),A.emitUint8(D),A.emitUint8(V),A.emitUint8(3)}if(Bt){const Q=G.find(Y=>Y.func==="max");let V=255;if(Q&&Q.colName&&Q.colName!=="*"){const Y=M.columns.findIndex(Z=>Z.name===Q.colName);if(Y!==-1){const Z=M.columns[Y];V=tt+3,Nt(A,0,Y,V,Z.type)}}A.emitUint8(d.OP_AGG_STEP),A.emitUint8(0),A.emitUint8(J),A.emitUint8(D),A.emitUint8(V),A.emitUint8(4)}const he=A.currentOffset();for(const Q of Pt)A.patchUint16(Q,he);A.emitUint8(d.OP_NEXT_ROW),A.emitUint8(0);const b=A.emitUint16(0);A.emitUint8(d.OP_JUMP),A.emitUint16(rt);const dt=A.currentOffset();A.patchUint16(Lt,dt),A.patchUint16(b,dt);const at=A.currentOffset();A.emitUint8(d.OP_AGG_NEXT),A.emitUint8(0),A.emitUint8(ht),A.emitUint8(it);const Dt=A.emitUint16(0),wt=A.currentOffset();A.emitUint8(d.OP_HALT);const Yt=A.currentOffset();A.patchUint16(Dt,Yt);for(let Q=0;Q<G.length;Q++){const V=G[Q],Y=et+Q;let Z=it,j=0;V.func==="count"?(Z=it,j=0):V.func==="sum"?(Z=it,j=1):V.func==="avg"?(Z=it,j=2):V.func==="min"?(Z=it+2,j=3):V.func==="max"&&(Z=it+3,j=4),A.emitUint8(d.OP_AGG_FINAL),A.emitUint8(Z),A.emitUint8(it+1),A.emitUint8(Y),A.emitUint8(j)}const Tn=(Q,V)=>{var Y;for(let Z=0;Z<G.length;Z++){const j=G[Z],At=et+Z;if(Q&&(j.alias&&j.alias===Q||(j.colName?`${j.func}_${j.colName}`:j.func)===Q||`${j.func}(${j.colName??"*"})`===Q.replace(/\s+/g,"")||j.func===Q))return At;if(V&&V.type==="fn"){const Zt=V.name.toLowerCase();if(j.func===Zt)if(Zt==="count"){const It=V.args[0],Rt=It&&It.type==="col"?It.name:void 0;if(j.colName===void 0||j.colName==="*"||j.colName===Rt)return At}else{const It=V.args[0],Rt=It&&It.type==="col"?It.name:void 0;if(j.colName===Rt)return At}}}if(t.groupBy)for(let Z=0;Z<t.groupBy.length;Z++){const j=t.groupBy[Z],At=ht+Z,Zt=typeof j=="string"?j:j.colName,It=typeof j=="object"?j.expr:void 0;if(Q){if(Zt===Q||It&&jt(It)===Q)return At;const Rt=(Y=t.selectExprs)==null?void 0:Y.find(so=>so.alias===Q);if(Rt){if(Zt===Rt.alias||It&&JSON.stringify(It)===JSON.stringify(Rt.expr))return At;if(typeof j=="string"&&j.includes("("))try{const so=ut(j);if(JSON.stringify(so)===JSON.stringify(Rt.expr))return At}catch{}}}if(V){if(It&&JSON.stringify(It)===JSON.stringify(V)||V.type==="col"&&Zt===V.name)return At;if(typeof j=="string"&&j.includes("("))try{const Rt=ut(j);if(JSON.stringify(Rt)===JSON.stringify(V))return At}catch{}}}};if(t.having&&t.having.length>0){let Q=null;t.having.length===1?Q=t.having[0]:Q={type:"and",children:t.having};const V=[];let Y=Math.max(St+4,40);ml(Q,M,A,Tn,()=>{if(Y>=64)throw new nt(Y);return Y++},V,t.udfNameMap);for(const j of V)A.patchUint16(j,at)}v&&(A.emitUint8(d.OP_OFFSET),A.emitUint8(x),A.emitUint16(at)),A.emitUint8(d.OP_RESULT_ROW),A.emitUint8(ht),A.emitUint8(D+W),X&&(A.emitUint8(d.OP_LIMIT),A.emitUint8(K),A.emitUint16(wt)),A.emitUint8(d.OP_JUMP),A.emitUint16(at);const Le=A.toByteArray();return Le.outputColumns=$,Le.inSets=U,t.outputColumns=$,Le}const H=c?null:ks(M,f,h,t.orderBy);if(!c&&t.orderBy&&t.orderBy.length>0&&!(H!=null&&H.satisfiesOrderBy)){const D=t.orderBy.length,G=N,W=G+D;if(W>=64)throw new nt(W);const $={numKeys:D,directions:t.orderBy.map(rt=>rt.direction==="desc"?1:0),nullOrders:t.orderBy.map(rt=>rt.nullOrder==="nulls_last"?1:rt.nullOrder==="nulls_first"?0:rt.direction==="desc"?1:0),limit:t.limit,offset:t.offset};t.keyInfos=[$],A.emitUint8(d.OP_SORTER_OPEN),A.emitUint8(0),A.emitUint8(0),A.emitUint8(d.OP_OPEN_CURSOR),A.emitUint8(0),A.emitUint32(M.rootPageId),A.emitUint8(d.OP_REWIND),A.emitUint8(0);const gt=A.emitUint16(0),J=A.currentOffset(),tt=[];Jt(u,M,A,R,tt,t.udfNameMap,void 0,k);for(let rt=0;rt<D;rt++){const Pt=t.orderBy[rt],Xt=G+rt;let bt=50;const Ne=()=>{if(bt>=64)throw new nt(bt);return bt++};if(Pt.expr)q(Pt.expr,M,A,0,Xt,Ne,t.udfNameMap);else if(Pt.colName){const oe=Pt.colName,Bt=(ea=(ta=t.selectExprs)==null?void 0:ta.find(he=>he.alias===oe))==null?void 0:ea.expr;if(Bt)q(Bt,M,A,0,Xt,Ne,t.udfNameMap);else{const he=M.columns.findIndex(b=>b.name===oe);if(he!==-1){const b=M.columns[he];Nt(A,0,he,Xt,b.type)}else try{const b=ut(oe);q(b,M,A,0,Xt,Ne,t.udfNameMap)}catch{throw new Error(`Order by column "${oe}" not found in table "${M.name}"`)}}}}A.emitUint8(d.OP_SORTER_INSERT),A.emitUint8(0),A.emitUint8(G),A.emitUint8(D),A.emitUint8(0);const it=A.currentOffset();for(const rt of tt)A.patchUint16(rt,it);A.emitUint8(d.OP_NEXT_ROW),A.emitUint8(0);const ht=A.emitUint16(0);A.emitUint8(d.OP_JUMP),A.emitUint16(J);const et=A.currentOffset();A.patchUint16(gt,et),A.patchUint16(ht,et),A.emitUint8(d.OP_SORTER_SORT),A.emitUint8(0);const St=A.currentOffset();A.emitUint8(d.OP_SORTER_NEXT),A.emitUint8(0),A.emitUint16(St),A.emitUint8(d.OP_HALT);const Lt=A.toByteArray();return Lt.keyInfos=t.keyInfos,Lt.inSets=U,a&&(Lt.planMetrics=a,Lt.estimatedCost=a.totalCost,Lt.estimatedRows=a.estimatedRows,Lt.joinOrder=a.joinOrder),Lt}const zt=t.selectExprs!==void 0&&t.selectExprs.length>0&&!(t.selectExprs.length===1&&t.selectExprs[0].expr.type==="col"&&t.selectExprs[0].expr.name==="*");let Et=[];if(zt)Et=t.selectExprs;else if(c){const D=new Set,G=new Set;for(const W of o)for(const $ of W.columns)D.has($.name.toLowerCase())&&G.add($.name.toLowerCase()),D.add($.name.toLowerCase());for(const W of o)for(const $ of W.columns){const gt=G.has($.name.toLowerCase())?`${W.name}.${$.name}`:$.name;Et.push({expr:{type:"col",name:`${W.name}.${$.name}`},alias:gt})}}let _t=-1;if(zt||c){const D=Et.map(G=>({name:G.alias,type:Zr(G.expr,M,t.udfDefs,o),flags:z.NONE,colOffset:0}));if(t.outputColumns=D,_t=N,N+=Et.length,N>=64)throw new nt(N)}if(c){const D=o.length,G=new Array(D);for(let b=1;b<D;b++)t.joinedTables[b-1].type==="left"&&(G[b]=N++);const W=N++,$=N++,gt=N++;let J=-1;if(T&&P!==-1)if(T.compositeValue){if(J=N++,N>=64)throw new nt(N);A.emitUint8(d.OP_LOAD_BLOB),A.emitUint8(J),A.emitUint32(T.compositeValue.length),A.emitBytes(T.compositeValue)}else if(T.scanType==="multi_point"){if(J=N++,N>=64)throw new nt(N)}else if(T.filterIndex>=0)J=T.filterIndex*2+1;else{if(J=N++,N>=64)throw new nt(N);const b=Qs(T.keyType);Ji(A,J,b,T.keyType)}if(N>=64)throw new nt(N);for(let b=0;b<D;b++)A.emitUint8(d.OP_OPEN_CURSOR),A.emitUint8(b),A.emitUint32(o[b].rootPageId);T&&P!==-1&&(A.emitUint8(d.OP_OPEN_INDEX),A.emitUint8(P),A.emitUint32(T.index.rootPageId));for(let b=1;b<D;b++){const dt=F[b];dt&&(A.emitUint8(d.OP_OPEN_INDEX),A.emitUint8(dt.indexCursor),A.emitUint32(dt.index.rootPageId))}const tt=new Array(D),it=new Array(D),ht=Array.from({length:D},()=>[]),et=new Array(D),St=[];if(T&&P!==-1?T.scanType==="point"?(A.emitUint8(d.OP_INDEX_SEEK_EQ),A.emitUint8(P),A.emitUint8(0),A.emitUint8(J),A.emitUint8(T.keyType),tt[0]=A.emitUint16(0)):(A.emitUint8(d.OP_INDEX_SEEK_GE),A.emitUint8(P),A.emitUint8(0),A.emitUint8(J),A.emitUint8(T.keyType),tt[0]=A.emitUint16(0)):(A.emitUint8(d.OP_REWIND),A.emitUint8(0),tt[0]=A.emitUint16(0)),it[0]=A.currentOffset(),_[0]&&_[0].length>0){const b=Kt(_[0]);Jt(b,o[0],A,R,ht[0],t.udfNameMap,o,k)}for(let b=1;b<D;b++){const dt=t.joinedTables[b-1],at=F[b];if(dt.type==="left"&&(A.emitUint8(d.OP_LOAD_INT),A.emitUint8(G[b]),A.emitInt32(0)),at&&at.isUnique){if(Nt(A,at.outerCol.cursor,at.outerCol.colIdx,W,at.outerCol.col.type),A.emitUint8(d.OP_INDEX_SEEK_EQ),A.emitUint8(at.indexCursor),A.emitUint8(b),A.emitUint8(W),A.emitUint8(at.outerCol.col.type),tt[b]=A.emitUint16(0),it[b]=A.currentOffset(),dt.type==="inner"&&_[b]&&_[b].length>0){const Dt=Kt(_[b]);Jt(Dt,o[b],A,R,ht[b],t.udfNameMap,o,k)}dt.type==="left"&&(A.emitUint8(d.OP_LOAD_INT),A.emitUint8(G[b]),A.emitInt32(1))}else if(at&&!at.isUnique){Nt(A,at.outerCol.cursor,at.outerCol.colIdx,W,at.outerCol.col.type),A.emitUint8(d.OP_INDEX_SEEK_GE),A.emitUint8(at.indexCursor),A.emitUint8(b),A.emitUint8(W),A.emitUint8(at.outerCol.col.type),tt[b]=A.emitUint16(0),it[b]=A.currentOffset(),Nt(A,b,at.innerCol.colIdx,$,at.innerCol.col.type),A.emitUint8(d.OP_EQ),A.emitUint8(W),A.emitUint8($);const Dt=A.emitUint16(0);if(A.emitUint8(d.OP_JUMP),ht[b].push(A.emitUint16(0)),A.patchUint16(Dt,A.currentOffset()),dt.type==="inner"&&_[b]&&_[b].length>0){const wt=Kt(_[b]);Jt(wt,o[b],A,R,ht[b],t.udfNameMap,o,k)}dt.type==="left"&&(A.emitUint8(d.OP_LOAD_INT),A.emitUint8(G[b]),A.emitInt32(1))}else{A.emitUint8(d.OP_REWIND),A.emitUint8(b),tt[b]=A.emitUint16(0),it[b]=A.currentOffset();const Dt=ft(dt.leftCol,o);if(!Dt)throw new Error(`Join column "${dt.leftCol}" not found in tables`);const wt=ft(dt.rightCol,o);if(!wt)throw new Error(`Join column "${dt.rightCol}" not found in tables`);Nt(A,Dt.cursor,Dt.colIdx,W,Dt.col.type),Nt(A,wt.cursor,wt.colIdx,$,wt.col.type);let Yt;switch(dt.op){case"=":Yt=d.OP_EQ;break;case"!=":Yt=d.OP_NE;break;case">":Yt=d.OP_GT;break;case">=":Yt=d.OP_GE;break;case"<":Yt=d.OP_LT;break;case"<=":Yt=d.OP_LE;break;default:Yt=d.OP_EQ}A.emitUint8(Yt),A.emitUint8(W),A.emitUint8($);const Tn=A.emitUint16(0);if(A.emitUint8(d.OP_JUMP),ht[b].push(A.emitUint16(0)),A.patchUint16(Tn,A.currentOffset()),dt.type==="inner"&&_[b]&&_[b].length>0){const Le=Kt(_[b]);Jt(Le,o[b],A,R,ht[b],t.udfNameMap,o,k)}dt.type==="left"&&(A.emitUint8(d.OP_LOAD_INT),A.emitUint8(G[b]),A.emitInt32(1))}}Jt(I,M,A,R,ht[D-1],t.udfNameMap,o,k);const rt=!(t.orderBy!==void 0&&t.orderBy.length>0)||B;let Pt=-1;v&&rt&&(A.emitUint8(d.OP_OFFSET),A.emitUint8(x),Pt=A.emitUint16(0));let Xt=N;const bt=()=>{if(Xt>=64)throw new nt(Xt);return Xt++};for(let b=0;b<Et.length;b++)q(Et[b].expr,M,A,0,_t+b,bt,t.udfNameMap,void 0,o);A.emitUint8(d.OP_RESULT_ROW),A.emitUint8(_t),A.emitUint8(Et.length),X&&rt&&(A.emitUint8(d.OP_LIMIT),A.emitUint8(K),St.push(A.emitUint16(0)));for(let b=D-1;b>=1;b--){const dt=A.currentOffset();b===D-1&&Pt!==-1&&A.patchUint16(Pt,dt);for(const wt of ht[b])A.patchUint16(wt,dt);const at=F[b];if(at&&at.isUnique){const wt=A.currentOffset();A.patchUint16(tt[b],wt)}else if(at&&!at.isUnique){A.emitUint8(d.OP_INDEX_NEXT),A.emitUint8(at.indexCursor),A.emitUint8(b),et[b]=A.emitUint16(0),A.emitUint8(d.OP_JUMP),A.emitUint16(it[b]);const wt=A.currentOffset();A.patchUint16(tt[b],wt),A.patchUint16(et[b],wt)}else{A.emitUint8(d.OP_NEXT_ROW),A.emitUint8(b),et[b]=A.emitUint16(0),A.emitUint8(d.OP_JUMP),A.emitUint16(it[b]);const wt=A.currentOffset();A.patchUint16(tt[b],wt),A.patchUint16(et[b],wt)}if(t.joinedTables[b-1].type==="left"){A.emitUint8(d.OP_LOAD_INT),A.emitUint8(gt),A.emitInt32(0),A.emitUint8(d.OP_EQ),A.emitUint8(G[b]),A.emitUint8(gt);const wt=A.emitUint16(0);A.emitUint8(d.OP_JUMP);const Yt=A.emitUint16(0);A.patchUint16(wt,A.currentOffset());for(let Q=0;Q<Et.length;Q++){const V=Et[Q];let Y=-1;if(V.expr.type==="col"){const Z=ft(V.expr.name,o);Z&&(Y=Z.tableIdx)}Y>=b?(A.emitUint8(d.OP_LOAD_NULL),A.emitUint8(_t+Q)):q(V.expr,M,A,0,_t+Q,bt,t.udfNameMap,void 0,o)}const Tn=[];v&&rt&&(A.emitUint8(d.OP_OFFSET),A.emitUint8(x),Tn.push(A.emitUint16(0))),A.emitUint8(d.OP_RESULT_ROW),A.emitUint8(_t),A.emitUint8(Et.length),X&&rt&&(A.emitUint8(d.OP_LIMIT),A.emitUint8(K),St.push(A.emitUint16(0)));const Le=A.currentOffset();A.patchUint16(Yt,Le);for(const Q of Tn)A.patchUint16(Q,Le)}}const Ne=A.currentOffset();for(const b of ht[0])A.patchUint16(b,Ne);T&&P!==-1?T.scanType==="point"?(A.emitUint8(d.OP_JUMP),et[0]=A.emitUint16(0)):(A.emitUint8(d.OP_INDEX_NEXT),A.emitUint8(P),A.emitUint8(0),et[0]=A.emitUint16(0),A.emitUint8(d.OP_JUMP),A.emitUint16(it[0])):(A.emitUint8(d.OP_NEXT_ROW),A.emitUint8(0),et[0]=A.emitUint16(0),A.emitUint8(d.OP_JUMP),A.emitUint16(it[0]));const oe=A.currentOffset();A.patchUint16(tt[0],oe),A.patchUint16(et[0],oe);for(const b of St)A.patchUint16(b,oe);A.emitUint8(d.OP_HALT);const Bt=A.toByteArray();t.outputColumns&&(Bt.outputColumns=t.outputColumns);const he=(na=t.joinedTables)==null?void 0:na.map((b,dt)=>{const at=dt+1,Dt=F[at];return{tableIndex:at,tableName:b.table.name,scanType:Dt?"IndexScan":"TableScan",indexName:Dt?Dt.index.name:void 0}});return Bt.joinedTableScans=he,Bt.allTables=o,Bt.inSets=U,Bt.table0Scan=T,Bt.isOrderSatisfied=B,B&&(t.isOrderSatisfied=!0),a&&(Bt.planMetrics=a,Bt.estimatedCost=a.totalCost,Bt.estimatedRows=a.estimatedRows,Bt.joinOrder=a.joinOrder),r&&(Bt.whereMetrics=r),Bt}if(H){let D;if(H.compositeValue){if(D=N++,D>=64)throw new nt(D);A.emitUint8(d.OP_LOAD_BLOB),A.emitUint8(D),A.emitBytes(H.compositeValue)}else if(H.scanType==="multi_point"){if(D=N++,D>=64)throw new nt(D)}else if(H.filterIndex>=0)D=H.filterIndex*2+1;else{if(D=N++,D>=64)throw new nt(D);const G=Qs(H.keyType);Ji(A,D,G,H.keyType)}if(H.scanType==="point"){A.emitUint8(d.OP_OPEN_CURSOR),A.emitUint8(0),A.emitUint32(M.rootPageId),A.emitUint8(d.OP_OPEN_INDEX),A.emitUint8(1),A.emitUint32(H.index.rootPageId),A.emitUint8(d.OP_INDEX_SEEK_EQ),A.emitUint8(1),A.emitUint8(0),A.emitUint8(D),A.emitUint8(H.keyType);const G=A.emitUint16(0),W=[];Jt(u,M,A,R,W,t.udfNameMap,void 0,k);let $=-1;if(v&&(A.emitUint8(d.OP_OFFSET),A.emitUint8(x),$=A.emitUint16(0)),zt){let it=N;const ht=()=>{if(it>=64)throw new nt(it);return it++};for(let et=0;et<t.selectExprs.length;et++)q(t.selectExprs[et].expr,M,A,0,_t+et,ht,t.udfNameMap);A.emitUint8(d.OP_RESULT_ROW),A.emitUint8(_t),A.emitUint8(t.selectExprs.length)}else A.emitUint8(d.OP_EMIT_ROW),A.emitUint8(0);A.emitUint8(d.OP_JUMP);const gt=A.emitUint16(0),J=A.currentOffset();A.patchUint16(G,J),A.patchUint16(gt,J),$!==-1&&A.patchUint16($,J);for(const it of W)A.patchUint16(it,J);A.emitUint8(d.OP_HALT);const tt=A.toByteArray();return tt.indexScan=H,tt.inSets=U,t.outputColumns&&(tt.outputColumns=t.outputColumns),H!=null&&H.satisfiesOrderBy&&(tt.isOrderSatisfied=!0,t.isOrderSatisfied=!0),a&&(tt.planMetrics=a,tt.estimatedCost=a.totalCost,tt.estimatedRows=a.estimatedRows,tt.joinOrder=a.joinOrder),tt}else if(H.scanType==="multi_point"){const G=H.inValues?H.inValues.length:0;if(G===0){A.emitUint8(d.OP_HALT);const J=A.toByteArray();return J.indexScan=H,J.inSets=U,t.outputColumns&&(J.outputColumns=t.outputColumns),J}A.emitUint8(d.OP_OPEN_CURSOR),A.emitUint8(0),A.emitUint32(M.rootPageId),A.emitUint8(d.OP_OPEN_INDEX),A.emitUint8(1),A.emitUint32(H.index.rootPageId);const W=[];for(let J=0;J<G;J++){const tt=H.inValues[J];Ji(A,D,tt,H.keyType),A.emitUint8(d.OP_INDEX_SEEK_EQ),A.emitUint8(1),A.emitUint8(0),A.emitUint8(D),A.emitUint8(H.keyType);const it=A.emitUint16(0),ht=[];Jt(u,M,A,R,ht,t.udfNameMap,void 0,k);let et=-1;if(v&&(A.emitUint8(d.OP_OFFSET),A.emitUint8(x),et=A.emitUint16(0)),zt){let Pt=N;const Xt=()=>{if(Pt>=64)throw new nt(Pt);return Pt++};for(let bt=0;bt<t.selectExprs.length;bt++)q(t.selectExprs[bt].expr,M,A,0,_t+bt,Xt,t.udfNameMap);A.emitUint8(d.OP_RESULT_ROW),A.emitUint8(_t),A.emitUint8(t.selectExprs.length)}else A.emitUint8(d.OP_EMIT_ROW),A.emitUint8(0);X&&(A.emitUint8(d.OP_LIMIT),A.emitUint8(K),W.push(A.emitUint16(0)));const St=J===G-1;let Lt=-1;St||(A.emitUint8(d.OP_JUMP),Lt=A.emitUint16(0));const rt=A.currentOffset();A.patchUint16(it,rt);for(const Pt of ht)A.patchUint16(Pt,rt);et!==-1&&A.patchUint16(et,rt),Lt!==-1&&A.patchUint16(Lt,rt)}const $=A.currentOffset();for(const J of W)A.patchUint16(J,$);A.emitUint8(d.OP_HALT);const gt=A.toByteArray();return gt.indexScan=H,gt.inSets=U,t.outputColumns&&(gt.outputColumns=t.outputColumns),H!=null&&H.satisfiesOrderBy&&(gt.isOrderSatisfied=!0,t.isOrderSatisfied=!0),a&&(gt.planMetrics=a,gt.estimatedCost=a.totalCost,gt.estimatedRows=a.estimatedRows,gt.joinOrder=a.joinOrder),gt}else{A.emitUint8(d.OP_OPEN_CURSOR),A.emitUint8(0),A.emitUint32(M.rootPageId),A.emitUint8(d.OP_OPEN_INDEX),A.emitUint8(1),A.emitUint32(H.index.rootPageId),A.emitUint8(d.OP_INDEX_SEEK_GE),A.emitUint8(1),A.emitUint8(0),A.emitUint8(D),A.emitUint8(H.keyType);const G=A.emitUint16(0),W=A.currentOffset(),$=[];Jt(u,M,A,R,$,t.udfNameMap,void 0,k);let gt=-1;if(v&&(A.emitUint8(d.OP_OFFSET),A.emitUint8(x),gt=A.emitUint16(0)),zt){let St=N;const Lt=()=>{if(St>=64)throw new nt(St);return St++};for(let rt=0;rt<t.selectExprs.length;rt++)q(t.selectExprs[rt].expr,M,A,0,_t+rt,Lt,t.udfNameMap);A.emitUint8(d.OP_RESULT_ROW),A.emitUint8(_t),A.emitUint8(t.selectExprs.length)}else A.emitUint8(d.OP_EMIT_ROW),A.emitUint8(0);let J=-1;X&&(A.emitUint8(d.OP_LIMIT),A.emitUint8(K),J=A.emitUint16(0));const tt=A.currentOffset();gt!==-1&&A.patchUint16(gt,tt);for(const St of $)A.patchUint16(St,tt);A.emitUint8(d.OP_INDEX_NEXT),A.emitUint8(1),A.emitUint8(0);const it=A.emitUint16(0);A.emitUint8(d.OP_JUMP),A.emitUint16(W);const ht=A.currentOffset();A.patchUint16(G,ht),A.patchUint16(it,ht),J!==-1&&A.patchUint16(J,ht),A.emitUint8(d.OP_HALT);const et=A.toByteArray();return et.indexScan=H,et.inSets=U,t.outputColumns&&(et.outputColumns=t.outputColumns),H!=null&&H.satisfiesOrderBy&&(et.isOrderSatisfied=!0,t.isOrderSatisfied=!0),a&&(et.planMetrics=a,et.estimatedCost=a.totalCost,et.estimatedRows=a.estimatedRows,et.joinOrder=a.joinOrder),et}}A.emitUint8(d.OP_OPEN_CURSOR),A.emitUint8(0),A.emitUint32(M.rootPageId),A.emitUint8(d.OP_REWIND),A.emitUint8(0);const En=A.emitUint16(0),mn=A.currentOffset(),In=[];Jt(u,M,A,R,In,t.udfNameMap,void 0,k);let je=-1;if(v&&(A.emitUint8(d.OP_OFFSET),A.emitUint8(x),je=A.emitUint16(0)),zt){let D=N;const G=()=>{if(D>=64)throw new nt(D);return D++};for(let W=0;W<t.selectExprs.length;W++)q(t.selectExprs[W].expr,M,A,0,_t+W,G,t.udfNameMap);A.emitUint8(d.OP_RESULT_ROW),A.emitUint8(_t),A.emitUint8(t.selectExprs.length)}else A.emitUint8(d.OP_EMIT_ROW),A.emitUint8(0);let Pe=-1;X&&(A.emitUint8(d.OP_LIMIT),A.emitUint8(K),Pe=A.emitUint16(0));const Yn=A.currentOffset();je!==-1&&A.patchUint16(je,Yn);for(const D of In)A.patchUint16(D,Yn);A.emitUint8(d.OP_NEXT_ROW),A.emitUint8(0);const Be=A.emitUint16(0);A.emitUint8(d.OP_JUMP),A.emitUint16(mn);const pn=A.currentOffset();A.patchUint16(En,pn),A.patchUint16(Be,pn),Pe!==-1&&A.patchUint16(Pe,pn),A.emitUint8(d.OP_HALT);const ie=A.toByteArray();return ie.inSets=U,t.outputColumns&&(ie.outputColumns=t.outputColumns),r&&(ie.whereMetrics=r),a&&(ie.planMetrics=a,ie.estimatedCost=a.totalCost,ie.estimatedRows=a.estimatedRows,ie.joinOrder=a.joinOrder),ie}const Il=new TextDecoder;function xr(t,e){const n=[],s=new DataView(t.buffer,t.byteOffset,t.byteLength);let i=0;const o=a=>{var l;return(l=e==null?void 0:e.columns[a])!=null&&l.name?`'${e.columns[a].name}'`:`col_${a}`},r=a=>`0x${a.toString(16).padStart(4,"0")}`;for(;i<t.byteLength;){const a=i,l=t[i++];switch(l){case d.OP_HALT:n.push({addr:a,opcode:"OP_HALT",p1:"",p2:"",p3:"",comment:"Halt VM execution (STATUS_DONE)"});break;case d.OP_OPEN_CURSOR:{const c=t[i++],u=s.getUint32(i,!0);i+=4,n.push({addr:a,opcode:"OP_OPEN_CURSOR",p1:`c[${c}]`,p2:`page=${u}`,p3:"",comment:`Open cursor ${c} on root page ${u}${e?` ('${e.name}')`:""}`});break}case d.OP_OPEN_INDEX:{const c=t[i++],u=s.getUint32(i,!0);i+=4,n.push({addr:a,opcode:"OP_OPEN_INDEX",p1:`c[${c}]`,p2:`page=${u}`,p3:"",comment:`Open index cursor ${c} on root page ${u}`});break}case d.OP_INDEX_SEEK_EQ:{const c=t[i++],u=t[i++],h=t[i++],f=t[i++],_=s.getUint16(i,!0);i+=2,n.push({addr:a,opcode:"OP_INDEX_SEEK_EQ",p1:`idx=c[${c}], data=c[${u}]`,p2:`key=r[${h}], type=${f}`,p3:r(_),comment:`Seek exact key in index; position data cursor or jump to ${r(_)} if not found`});break}case d.OP_INDEX_SEEK_GE:{const c=t[i++],u=t[i++],h=t[i++],f=t[i++],_=s.getUint16(i,!0);i+=2,n.push({addr:a,opcode:"OP_INDEX_SEEK_GE",p1:`idx=c[${c}], data=c[${u}]`,p2:`key=r[${h}], type=${f}`,p3:r(_),comment:`Seek first entry >= key in index; position data cursor or jump to ${r(_)} if EOF`});break}case d.OP_INDEX_NEXT:{const c=t[i++],u=t[i++],h=s.getUint16(i,!0);i+=2,n.push({addr:a,opcode:"OP_INDEX_NEXT",p1:`idx=c[${c}], data=c[${u}]`,p2:r(h),p3:"",comment:`Advance index cursor to next entry; jump to ${r(h)} if EOF`});break}case d.OP_REWIND:{const c=t[i++],u=s.getUint16(i,!0);i+=2,n.push({addr:a,opcode:"OP_REWIND",p1:`c[${c}]`,p2:r(u),p3:"",comment:`Rewind cursor to first row; jump to ${r(u)} if empty`});break}case d.OP_NEXT_ROW:{const c=t[i++],u=s.getUint16(i,!0);i+=2,n.push({addr:a,opcode:"OP_NEXT_ROW",p1:`c[${c}]`,p2:r(u),p3:"",comment:`Advance cursor to next row; jump to ${r(u)} if EOF`});break}case d.OP_LAST:{const c=t[i++],u=s.getUint16(i,!0);i+=2,n.push({addr:a,opcode:"OP_LAST",p1:`c[${c}]`,p2:r(u),p3:"",comment:`Position cursor to last row; jump to ${r(u)} if empty`});break}case d.OP_PREV_ROW:{const c=t[i++],u=s.getUint16(i,!0);i+=2,n.push({addr:a,opcode:"OP_PREV_ROW",p1:`c[${c}]`,p2:r(u),p3:"",comment:`Advance cursor to previous row; jump to ${r(u)} if BOF`});break}case d.OP_COLUMN_INT:{const c=t[i++],u=t[i++],h=t[i++];n.push({addr:a,opcode:"OP_COLUMN_INT",p1:`c[${c}]`,p2:`${u} (${o(u)})`,p3:`r[${h}]`,comment:`Read ${o(u)} as INT into r[${h}]`});break}case d.OP_COLUMN_FLOAT:{const c=t[i++],u=t[i++],h=t[i++];n.push({addr:a,opcode:"OP_COLUMN_FLOAT",p1:`c[${c}]`,p2:`${u} (${o(u)})`,p3:`r[${h}]`,comment:`Read ${o(u)} as FLOAT into r[${h}]`});break}case d.OP_COLUMN_TEXT:{const c=t[i++],u=t[i++],h=t[i++];n.push({addr:a,opcode:"OP_COLUMN_TEXT",p1:`c[${c}]`,p2:`${u} (${o(u)})`,p3:`r[${h}]`,comment:`Read ${o(u)} as TEXT into r[${h}]`});break}case d.OP_COLUMN_BLOB:{const c=t[i++],u=t[i++],h=t[i++];n.push({addr:a,opcode:"OP_COLUMN_BLOB",p1:`c[${c}]`,p2:`${u} (${o(u)})`,p3:`r[${h}]`,comment:`Read ${o(u)} as BLOB into r[${h}]`});break}case d.OP_COLUMN_UUID:{const c=t[i++],u=t[i++],h=t[i++];n.push({addr:a,opcode:"OP_COLUMN_UUID",p1:`c[${c}]`,p2:`${u} (${o(u)})`,p3:`r[${h}]`,comment:`Read ${o(u)} as UUID into r[${h}]`});break}case d.OP_COLUMN_ULID:{const c=t[i++],u=t[i++],h=t[i++];n.push({addr:a,opcode:"OP_COLUMN_ULID",p1:`c[${c}]`,p2:`${u} (${o(u)})`,p3:`r[${h}]`,comment:`Read ${o(u)} as ULID into r[${h}]`});break}case d.OP_IS_NULL:{const c=t[i++],u=t[i++],h=s.getUint16(i,!0);i+=2,n.push({addr:a,opcode:"OP_IS_NULL",p1:`c[${c}]`,p2:`${u} (${o(u)})`,p3:r(h),comment:`If ${o(u)} IS NULL -> jump to ${r(h)}`});break}case d.OP_IS_NOT_NULL:{const c=t[i++],u=t[i++],h=s.getUint16(i,!0);i+=2,n.push({addr:a,opcode:"OP_IS_NOT_NULL",p1:`c[${c}]`,p2:`${u} (${o(u)})`,p3:r(h),comment:`If ${o(u)} IS NOT NULL -> jump to ${r(h)}`});break}case d.OP_EQ:case d.OP_NE:case d.OP_GT:case d.OP_GE:case d.OP_LT:case d.OP_LE:{const c={[d.OP_EQ]:"OP_EQ",[d.OP_NE]:"OP_NE",[d.OP_GT]:"OP_GT",[d.OP_GE]:"OP_GE",[d.OP_LT]:"OP_LT",[d.OP_LE]:"OP_LE"},u={[d.OP_EQ]:"==",[d.OP_NE]:"!=",[d.OP_GT]:">",[d.OP_GE]:">=",[d.OP_LT]:"<",[d.OP_LE]:"<="},h=t[i++],f=t[i++],_=s.getUint16(i,!0);i+=2,n.push({addr:a,opcode:c[l],p1:`r[${h}]`,p2:`r[${f}]`,p3:r(_),comment:`If r[${h}] ${u[l]} r[${f}] -> jump to ${r(_)}`});break}case d.OP_JUMP:{const c=s.getUint16(i,!0);i+=2,n.push({addr:a,opcode:"OP_JUMP",p1:r(c),p2:"",p3:"",comment:`Unconditional jump to ${r(c)}`});break}case d.OP_STR_LIKE:case d.OP_STR_NOT_LIKE:case d.OP_STR_CONTAINS:case d.OP_STR_STARTS_WITH:case d.OP_STR_ENDS_WITH:{const c={[d.OP_STR_LIKE]:"OP_STR_LIKE",[d.OP_STR_NOT_LIKE]:"OP_STR_NOT_LIKE",[d.OP_STR_CONTAINS]:"OP_STR_CONTAINS",[d.OP_STR_STARTS_WITH]:"OP_STR_STARTS_WITH",[d.OP_STR_ENDS_WITH]:"OP_STR_ENDS_WITH"},u={[d.OP_STR_LIKE]:"LIKE",[d.OP_STR_NOT_LIKE]:"NOT LIKE",[d.OP_STR_CONTAINS]:"CONTAINS",[d.OP_STR_STARTS_WITH]:"STARTS_WITH",[d.OP_STR_ENDS_WITH]:"ENDS_WITH"},h=t[i++],f=t[i++],_=s.getUint16(i,!0);i+=2,n.push({addr:a,opcode:c[l],p1:`r[${h}]`,p2:`r[${f}]`,p3:r(_),comment:`If r[${h}] ${u[l]} r[${f}] -> jump to ${r(_)}`});break}case d.OP_IN:{const c=t[i++],u=s.getUint16(i,!0);i+=2;const h=s.getUint16(i,!0);i+=2,n.push({addr:a,opcode:"OP_IN",p1:`r[${c}]`,p2:`set[${u}]`,p3:r(h),comment:`If r[${c}] IN set[${u}] -> jump to ${r(h)}`});break}case d.OP_LOAD_INT:{const c=t[i++],u=s.getInt32(i,!0);i+=4,n.push({addr:a,opcode:"OP_LOAD_INT",p1:`r[${c}]`,p2:`${u}`,p3:"",comment:`Load literal int ${u} into r[${c}]`});break}case d.OP_LOAD_FLOAT:{const c=t[i++],u=s.getFloat64(i,!0);i+=8,n.push({addr:a,opcode:"OP_LOAD_FLOAT",p1:`r[${c}]`,p2:`${u}`,p3:"",comment:`Load literal float ${u} into r[${c}]`});break}case d.OP_LOAD_TEXT:{const c=t[i++],u=s.getUint16(i,!0);i+=2;const h=new Uint8Array(t.buffer,t.byteOffset+i,u),f=Il.decode(h);i+=u,n.push({addr:a,opcode:"OP_LOAD_TEXT",p1:`r[${c}]`,p2:`"${f}"`,p3:"",comment:`Load literal text "${f}" into r[${c}]`});break}case d.OP_LOAD_BLOB:{const c=t[i++],u=s.getUint16(i,!0);i+=2+u,n.push({addr:a,opcode:"OP_LOAD_BLOB",p1:`r[${c}]`,p2:`len=${u}`,p3:"",comment:`Load literal BLOB (${u} bytes) into r[${c}]`});break}case d.OP_LOAD_NULL:{const c=t[i++];n.push({addr:a,opcode:"OP_LOAD_NULL",p1:`r[${c}]`,p2:"NULL",p3:"",comment:`Set r[${c}] to NULL`});break}case d.OP_EMIT_ROW:{const c=t[i++];n.push({addr:a,opcode:"OP_EMIT_ROW",p1:`c[${c}]`,p2:"",p3:"",comment:"Row passed all filters -> emit to Output Result Buffer"});break}case d.OP_RESULT_ROW:{const c=t[i++],u=t[i++];n.push({addr:a,opcode:"OP_RESULT_ROW",p1:`r[${c}]`,p2:`cols=${u}`,p3:"",comment:`Serialize registers r[${c}..${c+u-1}] to Result Buffer`});break}case d.OP_OFFSET:{const c=t[i++],u=s.getUint16(i,!0);i+=2,n.push({addr:a,opcode:"OP_OFFSET",p1:`r[${c}]`,p2:r(u),p3:"",comment:`If r[${c}] > 0 -> decrement and skip row to ${r(u)}`});break}case d.OP_LIMIT:{const c=t[i++],u=s.getUint16(i,!0);i+=2,n.push({addr:a,opcode:"OP_LIMIT",p1:`r[${c}]`,p2:r(u),p3:"",comment:`If r[${c}] <= 1 -> halt to ${r(u)}, else decrement`});break}case d.OP_CALL_UDF:{const c=s.getUint16(i,!0);i+=2;const u=t[i++],h=t[i++],f=t[i++];n.push({addr:a,opcode:"OP_CALL_UDF",p1:`udf#${c}`,p2:`r[${u}..${u+h-1}]`,p3:`r[${f}]`,comment:`Call UDF #${c} with ${h} args -> r[${f}]`});break}case d.OP_STR_LOWER:case d.OP_STR_UPPER:case d.OP_STR_LENGTH:case d.OP_STR_TRIM:case d.OP_MATH_ABS:case d.OP_MATH_ROUND:case d.OP_MATH_FLOOR:case d.OP_MATH_CEIL:{const c={[d.OP_STR_LOWER]:"OP_STR_LOWER",[d.OP_STR_UPPER]:"OP_STR_UPPER",[d.OP_STR_LENGTH]:"OP_STR_LENGTH",[d.OP_STR_TRIM]:"OP_STR_TRIM",[d.OP_MATH_ABS]:"OP_MATH_ABS",[d.OP_MATH_ROUND]:"OP_MATH_ROUND",[d.OP_MATH_FLOOR]:"OP_MATH_FLOOR",[d.OP_MATH_CEIL]:"OP_MATH_CEIL"},u=t[i++],h=t[i++];n.push({addr:a,opcode:c[l],p1:`r[${u}]`,p2:`r[${h}]`,p3:"",comment:`${c[l]}: r[${h}] = ${c[l].toLowerCase()}(r[${u}])`});break}case d.OP_STR_SUBSTR:{const c=t[i++],u=t[i++],h=t[i++],f=t[i++];n.push({addr:a,opcode:"OP_STR_SUBSTR",p1:`r[${c}]`,p2:`start=r[${u}], len=r[${h}]`,p3:`r[${f}]`,comment:`Extract substring from r[${c}] into r[${f}]`});break}case d.OP_ADD:case d.OP_SUB:case d.OP_MUL:case d.OP_DIV:case d.OP_MOD:{const c={[d.OP_ADD]:"OP_ADD",[d.OP_SUB]:"OP_SUB",[d.OP_MUL]:"OP_MUL",[d.OP_DIV]:"OP_DIV",[d.OP_MOD]:"OP_MOD"},u=t[i++],h=t[i++],f=t[i++];n.push({addr:a,opcode:c[l],p1:`r[${u}]`,p2:`r[${h}]`,p3:`r[${f}]`,comment:`${c[l]}: r[${f}] = r[${u}] ${c[l].replace("OP_","")} r[${h}]`});break}case d.OP_STR_CONCAT:case d.OP_COALESCE:{const c={[d.OP_STR_CONCAT]:"OP_STR_CONCAT",[d.OP_COALESCE]:"OP_COALESCE"},u=t[i++],h=t[i++],f=t[i++];n.push({addr:a,opcode:c[l],p1:`r[${u}..${u+h-1}]`,p2:`count=${h}`,p3:`r[${f}]`,comment:`${c[l]}: r[${f}]`});break}case d.OP_COPY:{const c=t[i++],u=t[i++];n.push({addr:a,opcode:"OP_COPY",p1:`r[${c}]`,p2:`r[${u}]`,p3:"",comment:`Copy r[${c}] to r[${u}]`});break}case d.OP_SORTER_OPEN:{const c=t[i++],u=t[i++];n.push({addr:a,opcode:"OP_SORTER_OPEN",p1:`s[${c}]`,p2:`keyInfo=${u}`,p3:"",comment:`Open sorter ${c} with keyInfo ${u}`});break}case d.OP_SORTER_INSERT:{const c=t[i++],u=t[i++],h=t[i++],f=t[i++];n.push({addr:a,opcode:"OP_SORTER_INSERT",p1:`s[${c}]`,p2:`r[${u}..+${h}]`,p3:`c[${f}]`,comment:`Insert row from cursor ${f} into sorter ${c}`});break}case d.OP_SORTER_SORT:{const c=t[i++];n.push({addr:a,opcode:"OP_SORTER_SORT",p1:`s[${c}]`,p2:"",p3:"",comment:`Sort entries in sorter ${c}`});break}case d.OP_SORTER_NEXT:{const c=t[i++],u=s.getUint16(i,!0);i+=2,n.push({addr:a,opcode:"OP_SORTER_NEXT",p1:`s[${c}]`,p2:r(u),p3:"",comment:`Emit next sorted row from sorter ${c}; jump to ${r(u)} while more rows`});break}case d.OP_AGG_INIT:{const c=t[i++],u=t[i++],h=t[i++],f=t[i++];n.push({addr:a,opcode:"OP_AGG_INIT",p1:`agg[${c}]`,p2:`keys=r[${u}..+${h}]`,p3:`mode=${f===0?"hash":"stream"}`,comment:`Initialize aggregator ${c} (${f===0?"hash table":"stream"})`});break}case d.OP_AGG_STEP:{const c=t[i++],u=t[i++],h=t[i++],f=t[i++],_=t[i++],g=["COUNT","SUM","AVG","MIN","MAX"];n.push({addr:a,opcode:"OP_AGG_STEP",p1:`agg[${c}]`,p2:`val=${f===255?"*":`r[${f}]`}`,p3:g[_]??`${_}`,comment:`Update accumulator ${g[_]??_} for group r[${u}..+${h}]`});break}case d.OP_AGG_NEXT:{const c=t[i++],u=t[i++],h=t[i++],f=s.getUint16(i,!0);i+=2,n.push({addr:a,opcode:"OP_AGG_NEXT",p1:`agg[${c}]`,p2:`out_keys=r[${u}], out_acc=r[${h}]`,p3:r(f),comment:`Iterate next group bucket; jump to ${r(f)}`});break}case d.OP_AGG_FINAL:{const c=t[i++],u=t[i++],h=t[i++],f=t[i++],_=["COUNT","SUM","AVG","MIN","MAX"];n.push({addr:a,opcode:"OP_AGG_FINAL",p1:`sum=r[${c}], cnt=r[${u}]`,p2:`r[${h}]`,p3:_[f]??`${f}`,comment:`Finalize ${_[f]??f} into r[${h}]`});break}case d.OP_REG_IS_NULL:{const c=t[i++],u=s.getUint16(i,!0);i+=2,n.push({addr:a,opcode:"OP_REG_IS_NULL",p1:`r[${c}]`,p2:r(u),p3:"",comment:`Jump to ${r(u)} if r[${c}] is NULL`});break}case d.OP_REG_IS_NOT_NULL:{const c=t[i++],u=s.getUint16(i,!0);i+=2,n.push({addr:a,opcode:"OP_REG_IS_NOT_NULL",p1:`r[${c}]`,p2:r(u),p3:"",comment:`Jump to ${r(u)} if r[${c}] is NOT NULL`});break}default:n.push({addr:a,opcode:`OP_UNKNOWN(0x${l.toString(16)})`,p1:"",p2:"",p3:"",comment:"Unknown opcode"});break}}return n}function jr(t){const e=(i,o)=>i.padEnd(o," "),n=i=>`0x${i.toString(16).padStart(4,"0")}`;let s=`${e("ADDR",8)} ${e("OPCODE",18)} ${e("P1",12)} ${e("P2",20)} ${e("P3",10)} COMMENT
1
+ (function(E,Ht){typeof exports=="object"&&typeof module<"u"?Ht(exports):typeof define=="function"&&define.amd?define(["exports"],Ht):(E=typeof globalThis<"u"?globalThis:E||self,Ht(E.WebDB={}))})(this,function(E){"use strict";var yc=Object.defineProperty;var Tc=(E,Ht,wn)=>Ht in E?yc(E,Ht,{enumerable:!0,configurable:!0,writable:!0,value:wn}):E[Ht]=wn;var U=(E,Ht,wn)=>Tc(E,typeof Ht!="symbol"?Ht+"":Ht,wn);const ra=[["TYPE",1],["FLAGS",1],["CELL_COUNT",2],["CONTENT_OFFSET",2],["NEXT_PAGE_ID",4],["FREE_BYTES",2],["CHECKSUM",4]],Kt=16,rr=0,oa=1,aa=2,la=4,or=6,ca=10,Re=12,ua=[["CHILD_PAGE_ID",4],["ROWID",8]],ar=12,fa=0,Aa=4,lr=291,cr=145,ne=64,ha=[["MAGIC",6],["PAGE_SIZE",2],["FILE_FORMAT_VERSION",2],["MIN_READ_VERSION",2],["TOTAL_PAGES",4],["FREE_PAGE_HEAD",4],["SCHEMA_VERSION",4],["CHANGE_COUNTER",4],["PAGE_CHECKSUM",4],["NEXT_CATALOG_PAGE_ID",4],["NEXT_INDEX_CATALOG_PAGE_ID",4],["RESERVED",60]],ga=100,Ee=0,Hs=6,Vs=8,$s=10,se=12,le=16,Ie=20,pe=24,ye=28,ur=32,fr=36,_a=40,da=16,ma=8,ce=16,Je=8,Sn=100,Un=2148,Ea=3172,Ia=4,pa=3176,ya=920,Te=56,ue=256,Ta=[["TABLE_ID",2],["COLUMN_COUNT",2],["ROOT_PAGE_ID",4],["COL_CATALOG_PAGE_ID",4],["NAME",64],["FLAGS",4],["ROW_COUNT_ESTIMATE",4],["AUTO_INC_NEXT",8],["RESERVED",36]],Fe=128,Ca=0,wa=2,Sa=4,Ua=8,Oa=12,Pa=76,Na=80,ba=84,Ba=92,La=[["INDEX_ID",2],["TABLE_ID",2],["ROOT_PAGE_ID",4],["COLUMN_COUNT",1],["FLAGS",1],["COLUMN_INDICES",16],["COL_DIRECTIONS",8],["NAME",64],["RESERVED",30]],De=128,Ra=0,Fa=2,Da=4,Qa=8,va=9,ka=10,Ma=26,Ga=34,qa=98,Wa=[["PAGE_TYPE",1],["FLAGS",1],["COL_COUNT_IN_PAGE",2],["TABLE_ID",2],["START_COL_INDEX",2],["NEXT_COL_CATALOG_PAGE_ID",4],["PAGE_CHECKSUM",4]],xs=16,Ha=0,Va=1,$a=2,xa=4,Xa=6,Ya=8,Za=12,ja=[["TYPE",1],["FLAGS",1],["COL_OFFSET",2],["NAME",64],["RESERVED",4]],Xs=72,Ka=0,Ja=1,za=2,tl=4,el=68,nl=4194304,Qe=1024,sl=1024,qt=2048,Ce=8,Ar=16384,hr=12288,Ys=65536,gr=32768,_r=4096,dr=61312,ve=16777216,il=[["SLOT_TO_PAGE",4096],["PAGE_TO_SLOT",16384],["DIRTY_MASK",128],["VM_CONTEXT",12288],["RESULT_BUFFER",65536],["BYTECODE",32768],["PAGE_SCRATCHPAD",4096],["ALIGNMENT_PADDING",61312]],Yn=4194304,Mt=4198400,mr=4214784,Er=4214912,On=4227200,Ir=4292736,pr=4325504,rl=4329600,yr=4390912,ol=21168128;function Zs(e,t=ve){const n=e*4096,s=e*4+7&-8;let i=16;for(;i<e*2;)i<<=1;const r=i*8,o=Math.ceil(e/8)+7&-8;if(e===Qe)return{slotsEndOffset:n,slotToPageOffset:Yn,pageToSlotOffset:Mt,pageToSlotBuckets:qt,dirtyMaskOffset:mr,vmContextOffset:Er,resultBufferOffset:On,bytecodeOffset:Ir,pageScratchpadOffset:pr,transientArenaOffset:yr};const a=n,c=a+s,l=c+r,u=l+o,_=u+hr,A=_+Ys,f=A+gr,g=f+_r+dr;return{slotsEndOffset:n,slotToPageOffset:a,pageToSlotOffset:c,pageToSlotBuckets:i,dirtyMaskOffset:l,vmContextOffset:u,resultBufferOffset:_,bytecodeOffset:A,pageScratchpadOffset:f,transientArenaOffset:g}}const we=4096,ze=4128,Tr=1,Pn=1463897158,Zn=1,jn=2,Kn=3,al=[["MAGIC",6],["WAL_VERSION",2],["PAGE_SIZE",4],["CHECKPOINT_SEQ",4],["SALT1",4],["SALT2",4],["CHECKSUM",4],["RESERVED",4]],Jn=32,js=0,Ks=6,Js=8,zs=12,ti=16,ei=20,ni=24,Cr=28,ll=[["MAGIC",4],["FRAME_TYPE",2],["FLAGS",2],["TX_ID",4],["PAGE_ID",4],["DB_SIZE_PAGES",4],["FRAME_SEQ",4],["CHECKSUM",4],["RESERVED",4]],ke=32,si=0,ii=4,ri=6,oi=8,ai=12,li=16,ci=20,ui=24,wr=28,zn=1,Sr=1,Me=0,Ur=2,fi=5,ts=10,Nn=12,es=13,cl=1280,ul=8,fl=64,Al=16,hl=7,gl=32,Or=1e4,Dt=1e4;function Pr(){return{pageId:0,rootPageId:0,slotIdx:0,cellIdx:0,rowOffset:0,btreeDepth:0,flags:0}}function Nr(){const e=Array.from({length:16},()=>Pr());return{pc:0,status:O.RUNNING,fault_page_id:0,resultCount:0,resultOffset:0,arenaOffset:0,maxQueryMemory:ve,rowsAffected:0,registers:new Array(64).fill(null),cursor:e[0],cursors:e,keyInfos:[],sorters:[],aggregators:[],table:null,tables:void 0,outputColumns:void 0,inSets:[]}}function br(e,t,n){e.pc=0,e.status=O.RUNNING,e.fault_page_id=0,e.resultCount=0,e.resultOffset=0,e.arenaOffset=0,e.maxQueryMemory=ve,e.rowsAffected=0,e.registers.fill(null);for(let s=0;s<e.cursors.length;s++){const i=e.cursors[s];i.pageId=0,i.rootPageId=0,i.slotIdx=0,i.cellIdx=0,i.rowOffset=0,i.btreeDepth=0,i.flags=0}e.cursor=e.cursors[0],e.keyInfos=[],e.sorters=[],e.aggregators=[],e.table=t??null,e.tables=n,e.outputColumns=void 0,e.inSets=[]}var C=(e=>(e[e.NULL=0]="NULL",e[e.INT32=1]="INT32",e[e.INT64=2]="INT64",e[e.FLOAT64=3]="FLOAT64",e[e.TEXT=4]="TEXT",e[e.BLOB=5]="BLOB",e[e.UUID=6]="UUID",e[e.ULID=7]="ULID",e))(C||{}),tt=(e=>(e[e.NONE=0]="NONE",e[e.PRIMARY_KEY=1]="PRIMARY_KEY",e[e.NOT_NULL=2]="NOT_NULL",e[e.INDEXED=4]="INDEXED",e[e.AUTO_INC=8]="AUTO_INC",e))(tt||{}),bn=(e=>(e[e.NONE=0]="NONE",e[e.ACTIVE=1]="ACTIVE",e[e.SYSTEM=2]="SYSTEM",e))(bn||{}),It=(e=>(e[e.NONE=0]="NONE",e[e.UNIQUE=1]="UNIQUE",e[e.PRIMARY=2]="PRIMARY",e[e.SPATIAL_VECTOR=4]="SPATIAL_VECTOR",e))(It||{}),m=(e=>(e[e.OP_HALT=0]="OP_HALT",e[e.OP_OPEN_CURSOR=1]="OP_OPEN_CURSOR",e[e.OP_REWIND=2]="OP_REWIND",e[e.OP_NEXT_ROW=3]="OP_NEXT_ROW",e[e.OP_COLUMN_INT=4]="OP_COLUMN_INT",e[e.OP_COLUMN_FLOAT=5]="OP_COLUMN_FLOAT",e[e.OP_COLUMN_TEXT=6]="OP_COLUMN_TEXT",e[e.OP_COLUMN_BLOB=7]="OP_COLUMN_BLOB",e[e.OP_LAST=8]="OP_LAST",e[e.OP_PREV_ROW=9]="OP_PREV_ROW",e[e.OP_COLUMN_UUID=10]="OP_COLUMN_UUID",e[e.OP_COLUMN_ULID=11]="OP_COLUMN_ULID",e[e.OP_OPEN_INDEX=12]="OP_OPEN_INDEX",e[e.OP_INDEX_SEEK_EQ=13]="OP_INDEX_SEEK_EQ",e[e.OP_INDEX_SEEK_GE=14]="OP_INDEX_SEEK_GE",e[e.OP_INDEX_NEXT=15]="OP_INDEX_NEXT",e[e.OP_IS_NULL=16]="OP_IS_NULL",e[e.OP_IS_NOT_NULL=17]="OP_IS_NOT_NULL",e[e.OP_EQ=18]="OP_EQ",e[e.OP_NE=19]="OP_NE",e[e.OP_GT=20]="OP_GT",e[e.OP_GE=21]="OP_GE",e[e.OP_LT=22]="OP_LT",e[e.OP_LE=23]="OP_LE",e[e.OP_JUMP=24]="OP_JUMP",e[e.OP_STR_LIKE=25]="OP_STR_LIKE",e[e.OP_STR_NOT_LIKE=26]="OP_STR_NOT_LIKE",e[e.OP_STR_CONTAINS=27]="OP_STR_CONTAINS",e[e.OP_STR_STARTS_WITH=28]="OP_STR_STARTS_WITH",e[e.OP_STR_ENDS_WITH=29]="OP_STR_ENDS_WITH",e[e.OP_LOAD_BLOB=30]="OP_LOAD_BLOB",e[e.OP_IN=31]="OP_IN",e[e.OP_LOAD_INT=32]="OP_LOAD_INT",e[e.OP_LOAD_FLOAT=33]="OP_LOAD_FLOAT",e[e.OP_LOAD_TEXT=34]="OP_LOAD_TEXT",e[e.OP_LOAD_NULL=35]="OP_LOAD_NULL",e[e.OP_EMIT_ROW=36]="OP_EMIT_ROW",e[e.OP_RESULT_ROW=37]="OP_RESULT_ROW",e[e.OP_OFFSET=38]="OP_OFFSET",e[e.OP_LIMIT=39]="OP_LIMIT",e[e.OP_CALL_UDF=40]="OP_CALL_UDF",e[e.OP_STR_LOWER=41]="OP_STR_LOWER",e[e.OP_STR_UPPER=42]="OP_STR_UPPER",e[e.OP_STR_LENGTH=43]="OP_STR_LENGTH",e[e.OP_STR_SUBSTR=44]="OP_STR_SUBSTR",e[e.OP_STR_TRIM=45]="OP_STR_TRIM",e[e.OP_MATH_ABS=46]="OP_MATH_ABS",e[e.OP_MATH_ROUND=47]="OP_MATH_ROUND",e[e.OP_SORTER_OPEN=48]="OP_SORTER_OPEN",e[e.OP_SORTER_INSERT=49]="OP_SORTER_INSERT",e[e.OP_SORTER_SORT=50]="OP_SORTER_SORT",e[e.OP_SORTER_NEXT=51]="OP_SORTER_NEXT",e[e.OP_MATH_FLOOR=52]="OP_MATH_FLOOR",e[e.OP_MATH_CEIL=53]="OP_MATH_CEIL",e[e.OP_ADD=54]="OP_ADD",e[e.OP_SUB=55]="OP_SUB",e[e.OP_MUL=56]="OP_MUL",e[e.OP_DIV=57]="OP_DIV",e[e.OP_MOD=58]="OP_MOD",e[e.OP_ENTER_SUBQUERY=59]="OP_ENTER_SUBQUERY",e[e.OP_RETURN_SUBQUERY=60]="OP_RETURN_SUBQUERY",e[e.OP_STR_CONCAT=61]="OP_STR_CONCAT",e[e.OP_COALESCE=62]="OP_COALESCE",e[e.OP_COPY=63]="OP_COPY",e[e.OP_AGG_INIT=64]="OP_AGG_INIT",e[e.OP_AGG_STEP=65]="OP_AGG_STEP",e[e.OP_AGG_NEXT=66]="OP_AGG_NEXT",e[e.OP_AGG_FINAL=67]="OP_AGG_FINAL",e[e.OP_REG_IS_NULL=72]="OP_REG_IS_NULL",e[e.OP_REG_IS_NOT_NULL=73]="OP_REG_IS_NOT_NULL",e[e.OP_DELETE_ROW=80]="OP_DELETE_ROW",e[e.OP_UPDATE_FIELD=81]="OP_UPDATE_FIELD",e[e.OP_INSERT_ROW=82]="OP_INSERT_ROW",e))(m||{}),O=(e=>(e[e.RUNNING=0]="RUNNING",e[e.DONE=1]="DONE",e[e.PAGE_FAULT=2]="PAGE_FAULT",e[e.BUFFER_FULL=3]="BUFFER_FULL",e[e.ERROR=4]="ERROR",e[e.TIMEOUT=5]="TIMEOUT",e[e.ARENA_EXHAUSTED=6]="ARENA_EXHAUSTED",e[e.INVALID_BYTECODE=7]="INVALID_BYTECODE",e))(O||{});class Br extends Error{constructor(t,n=2048){super(`Row size (${t} bytes) exceeds maximum limit of ${n} bytes`),this.name="RowSizeLimitExceededError"}}class ns extends Error{constructor(t,n){super(`NOT NULL constraint failed: ${n?n+".":""}${t}`),this.name="NotNullConstraintError"}}class Lr extends Error{constructor(t,n=64){super(`Identifier "${t}" (${t.length} characters) exceeds maximum limit of ${n} characters`),this.name="IdentifierTooLongError"}}class ss extends Error{constructor(t,n){super(n?`Column "${t}" already exists on table "${n}"`:`Column "${t}" already exists`),this.name="ColumnAlreadyExistsError"}}class Ai extends Error{constructor(t){super(t),this.name="CannotDropColumnError"}}class fe extends Error{constructor(t,n){super(n?`Column "${t}" not found on table "${n}"`:`Column "${t}" not found`),this.name="ColumnNotFoundError"}}class Bn extends Error{constructor(t){super(`Table not found: "${t}"`),this.name="TableNotFoundError"}}class is extends Error{constructor(t){super(`Table already exists: "${t}"`),this.name="TableAlreadyExistsError"}}class Rr extends Error{constructor(t){super(`Index not found: "${t}"`),this.name="IndexNotFoundError"}}class hi extends Error{constructor(t){super(`Index already exists: "${t}"`),this.name="IndexAlreadyExistsError"}}class tn extends Error{constructor(t){super(t),this.name="UniqueConstraintViolationError"}}class Se extends Error{constructor(t,n,s){super(`Corrupted page detected (pageId: ${t}): stored checksum ${n}${s!==void 0?`, computed checksum ${s}`:""}`),this.pageId=t,this.storedChecksum=n,this.computedChecksum=s,this.name="CorruptPageError"}}class Ln extends Error{constructor(t,n=256){super(`Too many columns: ${t} exceeds maximum limit of ${n} columns`),this.name="TooManyColumnsError"}}class gi extends Error{constructor(t,n=16){super(`Too many tables: ${t} exceeds maximum limit of ${n} tables on Page 1`),this.name="TooManyTablesError"}}class Fr extends Error{constructor(t,n=8){super(`Too many indexes: ${t} exceeds maximum limit of ${n} indexes on Page 1`),this.name="TooManyIndexesError"}}class Dr extends Error{constructor(t){super(t),this.name="UnsupportedFormatVersionError"}}class Rn extends Error{constructor(t){super(t),this.name="InvalidDatabaseError"}}class _i extends Error{constructor(t="Transient query arena exhausted"){super(t),this.name="QueryArenaExhaustedError"}}class rs extends Error{constructor(t,n=16){super(`Too many cursors: ${t} exceeds maximum limit of ${n} cursors`),this.name="TooManyCursorsError"}}class st extends Error{constructor(t,n=64){super(`Too many registers: ${t} exceeds maximum limit of ${n} registers`),this.name="TooManyRegistersError"}}class Qr extends Error{constructor(t,n=7){super(`Subquery nesting depth ${t} exceeds maximum limit of ${n}`),this.name="SubqueryNestingTooDeepError"}}class vr extends Error{constructor(t="Query execution exceeded maximum cycle limit (TIMEOUT)"){super(t),this.name="QueryTimeoutError"}}class kr extends Error{constructor(t="Malformed bytecode execution halted (INVALID_BYTECODE)"){super(t),this.name="InvalidBytecodeError"}}class Mr extends Error{constructor(t,n=8){super(`Too many order by columns: ${t} exceeds maximum limit of ${n}`),this.name="TooManyOrderByColumnsError"}}class Gr extends Error{constructor(t,n=8){super(`Too many group by columns: ${t} exceeds maximum limit of ${n}`),this.name="TooManyGroupByColumnsError"}}class di extends Error{constructor(t){super(`Function "${t}" is neither a native built-in function nor a registered UDF`),this.name="UnknownFunctionError"}}class os extends Error{constructor(t){super(`Aggregate function "${t}" cannot be used in WHERE clause`),this.name="AggregateNotAllowedInWhereError"}}class as extends Error{constructor(t="Corrupted WAL file header detected"){super(t),this.name="CorruptWalHeaderError"}}class Fn extends Error{constructor(t="Corrupted WAL frame detected"){super(t),this.name="CorruptWalFrameError"}}class qr{constructor(){U(this,"name","memory");U(this,"isSynchronous",!0);U(this,"pages",new Map);U(this,"walHeader",null);U(this,"walFrames",[])}async readPages(t){return t.map(n=>{const s=this.pages.get(n);return s?new Uint8Array(s):null})}async writePages(t){for(const{pageId:n,data:s}of t){const i=new Uint8Array(s.byteLength);i.set(s),this.pages.set(n,i)}}async flush(){}async truncate(t){for(const n of Array.from(this.pages.keys()))n>t&&this.pages.delete(n)}snapshot(){const t=new Map;for(const[n,s]of this.pages.entries())t.set(n,new Uint8Array(s));return t}restoreSnapshot(t){this.pages.clear();for(const[n,s]of t.entries())this.pages.set(n,new Uint8Array(s))}async readWalHeader(){return this.walHeader?new Uint8Array(this.walHeader):null}async writeWalHeader(t){const n=new Uint8Array(t.byteLength);n.set(t),this.walHeader=n}async readWalFrames(t,n){const s=n!==void 0?t+n:this.walFrames.length;return this.walFrames.slice(t,s).map(r=>new Uint8Array(r))}async appendWalFrames(t){for(const n of t){const s=new Uint8Array(n.byteLength);s.set(n),this.walFrames.push(s)}}async flushWal(){}async truncateWal(t){t===0?(this.walFrames=[],this.walHeader=null):this.walFrames.length=Math.min(this.walFrames.length,t)}async getWalFrameCount(){return this.walFrames.length}async close(){}}class Wr{constructor(t){U(this,"name","idb");U(this,"isSynchronous",!1);U(this,"dbName");U(this,"dbPromise",null);this.dbName=`webdb_${t}`}getDb(){return this.dbPromise||(this.dbPromise=new Promise((t,n)=>{const s=globalThis.indexedDB;if(!s){n(new Error("IndexedDB is not available in the current environment"));return}const i=s.open(this.dbName,1);i.onupgradeneeded=()=>{const r=i.result;r.objectStoreNames.contains("pages")||r.createObjectStore("pages"),r.objectStoreNames.contains("wal_frames")||r.createObjectStore("wal_frames"),r.objectStoreNames.contains("wal_meta")||r.createObjectStore("wal_meta")},i.onsuccess=()=>t(i.result),i.onerror=()=>n(i.error)})),this.dbPromise}async readPages(t){if(t.length===0)return[];const n=await this.getDb();return new Promise((s,i)=>{const r=n.transaction("pages","readonly"),o=r.objectStore("pages"),a=new Array(t.length).fill(null);for(let c=0;c<t.length;c++){const l=o.get(t[c]);l.onsuccess=()=>{const u=l.result;u&&(a[c]=u instanceof Uint8Array?u:new Uint8Array(u))}}r.oncomplete=()=>s(a),r.onerror=()=>i(r.error),r.onabort=()=>i(r.error)})}async writePages(t){if(t.length===0)return;const n=await this.getDb();return new Promise((s,i)=>{const r=n.transaction("pages","readwrite"),o=r.objectStore("pages");for(const{pageId:a,data:c}of t){const l=new Uint8Array(c.byteLength);l.set(c),o.put(l,a)}r.oncomplete=()=>s(),r.onerror=()=>i(r.error),r.onabort=()=>i(r.error)})}async flush(){}async truncate(t){const n=await this.getDb();return new Promise((s,i)=>{const o=n.transaction("pages","readwrite").objectStore("pages"),a=IDBKeyRange.lowerBound(t,!0),c=o.delete(a);c.onsuccess=()=>s(),c.onerror=()=>i(c.error)})}async readWalHeader(){const t=await this.getDb();return new Promise((n,s)=>{const o=t.transaction("wal_meta","readonly").objectStore("wal_meta").get("header");o.onsuccess=()=>{const a=o.result;n(a?a instanceof Uint8Array?a:new Uint8Array(a):null)},o.onerror=()=>s(o.error)})}async writeWalHeader(t){const n=await this.getDb();return new Promise((s,i)=>{const r=n.transaction("wal_meta","readwrite"),o=r.objectStore("wal_meta"),a=new Uint8Array(t.byteLength);a.set(t),o.put(a,"header"),r.oncomplete=()=>s(),r.onerror=()=>i(r.error),r.onabort=()=>i(r.error)})}async readWalFrames(t,n){const s=await this.getDb();return new Promise((i,r)=>{const a=s.transaction("wal_frames","readonly").objectStore("wal_frames"),c=[],l=n!==void 0?IDBKeyRange.bound(t,t+n-1):IDBKeyRange.lowerBound(t,!1),u=a.openCursor(l);u.onsuccess=()=>{const _=u.result;if(_){const A=_.value;c.push(A instanceof Uint8Array?A:new Uint8Array(A)),_.continue()}else i(c)},u.onerror=()=>r(u.error)})}async appendWalFrames(t){if(t.length===0)return;const n=await this.getDb();return new Promise((s,i)=>{const r=n.transaction("wal_frames","readwrite"),o=r.objectStore("wal_frames"),a=o.count();a.onsuccess=()=>{let c=a.result;for(const l of t){const u=new Uint8Array(l.byteLength);u.set(l),o.put(u,c++)}},r.oncomplete=()=>s(),r.onerror=()=>i(r.error),r.onabort=()=>i(r.error)})}async flushWal(){}async truncateWal(t){const n=await this.getDb();return new Promise((s,i)=>{const r=n.transaction(["wal_frames","wal_meta"],"readwrite"),o=r.objectStore("wal_frames"),a=r.objectStore("wal_meta");if(t===0)o.clear(),a.delete("header");else{const c=IDBKeyRange.lowerBound(t,!1);o.delete(c)}r.oncomplete=()=>s(),r.onerror=()=>i(r.error),r.onabort=()=>i(r.error)})}async getWalFrameCount(){const t=await this.getDb();return new Promise((n,s)=>{const o=t.transaction("wal_frames","readonly").objectStore("wal_frames").count();o.onsuccess=()=>n(o.result),o.onerror=()=>s(o.error)})}async close(){this.dbPromise&&((await this.dbPromise).close(),this.dbPromise=null)}}class Hr{constructor(t){U(this,"name","opfs");U(this,"isSynchronous");U(this,"dbName");U(this,"rootDir",null);U(this,"dbFileHandle",null);U(this,"walFileHandle",null);U(this,"dbSyncHandle",null);U(this,"walSyncHandle",null);this.dbName=t,this.isSynchronous=typeof globalThis.FileSystemSyncAccessHandle<"u"}async initHandles(){var t;if(!this.rootDir){if(!((t=navigator==null?void 0:navigator.storage)!=null&&t.getDirectory))throw new Error("OPFS (Origin Private File System) is not available in the current environment");if(this.rootDir=await navigator.storage.getDirectory(),this.dbFileHandle=await this.rootDir.getFileHandle(`${this.dbName}.db`,{create:!0}),this.walFileHandle=await this.rootDir.getFileHandle(`${this.dbName}.wal`,{create:!0}),this.isSynchronous)try{this.dbSyncHandle=await this.dbFileHandle.createSyncAccessHandle(),this.walSyncHandle=await this.walFileHandle.createSyncAccessHandle()}catch{}}}async readPages(t){if(t.length===0)return[];if(await this.initHandles(),this.dbSyncHandle){const i=this.dbSyncHandle.getSize();return t.map(r=>{const o=(r-1)*4096;if(o+4096>i)return null;const a=new Uint8Array(4096);return this.dbSyncHandle.read(a,{at:o}),a})}const n=await this.dbFileHandle.getFile(),s=[];for(const i of t){const r=(i-1)*4096;if(r+4096>n.size)s.push(null);else{const a=await n.slice(r,r+4096).arrayBuffer();s.push(new Uint8Array(a))}}return s}async writePages(t){if(t.length===0)return;if(await this.initHandles(),this.dbSyncHandle){for(const{pageId:s,data:i}of t){const r=(s-1)*4096;this.dbSyncHandle.write(i,{at:r})}return}const n=await this.dbFileHandle.createWritable({keepExistingData:!0});for(const{pageId:s,data:i}of t){const r=(s-1)*4096;await n.seek(r),await n.write(i)}await n.close()}async flush(){this.dbSyncHandle&&this.dbSyncHandle.flush()}async truncate(t){await this.initHandles();const n=t*4096;if(this.dbSyncHandle){this.dbSyncHandle.truncate(n);return}const s=await this.dbFileHandle.createWritable({keepExistingData:!0});await s.truncate(n),await s.close()}async readWalHeader(){if(await this.initHandles(),this.walSyncHandle){if(this.walSyncHandle.getSize()<32)return null;const i=new Uint8Array(32);return this.walSyncHandle.read(i,{at:0}),i}const t=await this.walFileHandle.getFile();if(t.size<32)return null;const n=t.slice(0,32);return new Uint8Array(await n.arrayBuffer())}async writeWalHeader(t){if(await this.initHandles(),this.walSyncHandle){this.walSyncHandle.write(t,{at:0});return}const n=await this.walFileHandle.createWritable({keepExistingData:!0});await n.seek(0),await n.write(t),await n.close()}async readWalFrames(t,n){await this.initHandles();const s=[];let i=t;const r=n!==void 0?t+n:1/0;if(this.walSyncHandle){const a=this.walSyncHandle.getSize();for(;i<r;){const c=32+i*4128;if(c>=a)break;const l=Math.min(4128,a-c),u=new Uint8Array(l);this.walSyncHandle.read(u,{at:c}),s.push(u),i++}return s}const o=await this.walFileHandle.getFile();for(;i<r;){const a=32+i*4128;if(a>=o.size)break;const c=Math.min(4128,o.size-a),l=o.slice(a,a+c);s.push(new Uint8Array(await l.arrayBuffer())),i++}return s}async appendWalFrames(t){if(await this.initHandles(),this.walSyncHandle){let i=Math.max(32,this.walSyncHandle.getSize());for(const r of t)this.walSyncHandle.write(r,{at:i}),i+=r.byteLength;return}const n=await this.walFileHandle.getFile(),s=await this.walFileHandle.createWritable({keepExistingData:!0});await s.seek(Math.max(32,n.size));for(const i of t)await s.write(i);await s.close()}async flushWal(){this.walSyncHandle&&this.walSyncHandle.flush()}async truncateWal(t){await this.initHandles();const n=t===0?0:32+t*4128;if(this.walSyncHandle){this.walSyncHandle.truncate(n);return}const s=await this.walFileHandle.createWritable({keepExistingData:t>0});await s.truncate(n),await s.close()}async getWalFrameCount(){await this.initHandles();let t=0;return this.walSyncHandle?t=this.walSyncHandle.getSize():t=(await this.walFileHandle.getFile()).size,t<=32?0:Math.ceil((t-32)/4128)}async close(){this.dbSyncHandle&&(this.dbSyncHandle.close(),this.dbSyncHandle=null),this.walSyncHandle&&(this.walSyncHandle.close(),this.walSyncHandle=null),this.dbFileHandle=null,this.walFileHandle=null,this.rootDir=null}}const en=new Uint32Array(256);for(let e=0;e<256;e++){let t=e;for(let n=0;n<8;n++)t=t&1?3988292384^t>>>1:t>>>1;en[e]=t>>>0}function mi(e,t=0,n=e.byteLength-t){let s=4294967295;const i=t+n;for(let r=t;r<i;r++)s=en[(s^e[r])&255]^s>>>8;return(s^4294967295)>>>0}function Ge(e){let t=4294967295;for(let n=0;n<4096;n++){const s=n>=12&&n<=15?0:e[n];t=en[(t^s)&255]^t>>>8}return(t^4294967295)>>>0}function Ei(e){let t=4294967295;for(let n=0;n<4096;n++){const s=n>=28&&n<=31?0:e[n];t=en[(t^s)&255]^t>>>8}return(t^4294967295)>>>0}function ls(e){let t=4294967295;for(let s=0;s<24;s++)t=en[(t^e[s])&255]^t>>>8;const n=Math.min(e.byteLength,4128);for(let s=32;s<n;s++)t=en[(t^e[s])&255]^t>>>8;return(t^4294967295)>>>0}function nn(e,t,n,s,i){const r=e instanceof Uint8Array?e:new Uint8Array(e.buffer,e.byteOffset,e.byteLength),o=n instanceof Uint8Array?n:new Uint8Array(n.buffer,n.byteOffset,n.byteLength);r.set(o.subarray(s,s+i),t)}function ie(e,t,n,s){(e instanceof Uint8Array?e:new Uint8Array(e.buffer,e.byteOffset,e.byteLength)).fill(n&255,t,t+s)}function _l(e,t,n,s,i){const r=e instanceof Uint8Array?e:new Uint8Array(e.buffer,e.byteOffset,e.byteLength),o=n instanceof Uint8Array?n:new Uint8Array(n.buffer,n.byteOffset,n.byteLength);for(let a=0;a<i;a++){const c=r[t+a]-o[s+a];if(c!==0)return c}return 0}function cs(e){return e.length}function Vr(e,t){return e instanceof Uint8Array?e[t]:e.getUint8(t)}function dl(e,t,n){e instanceof Uint8Array?e[t]=n&255:e.setUint8(t,n&255)}function us(e,t){return e.getUint16(t,!0)}function fs(e,t,n){e.setUint16(t,n&65535,!0)}function yt(e,t){return e.getUint32(t,!0)}function Tt(e,t,n){e.setUint32(t,n>>>0,!0)}function ml(e,t){return e.getInt32(t,!0)}function El(e,t,n){e.setInt32(t,n|0,!0)}function Il(e,t){return e.getFloat64(t,!0)}function pl(e,t,n){e.setFloat64(t,n,!0)}function yl(e,t){return e.getBigUint64(t,!0)}function Tl(e,t,n){e.setBigUint64(t,n,!0)}function Cl(e,t){return e.getBigInt64(t,!0)}function wl(e,t,n){e.setBigInt64(t,n,!0)}function $r(e,t,n){return n!==void 0?e[t+(n>>3)]&1<<(n&7)?1:0:e[t>>3]&1<<(t&7)?1:0}function xr(e,t,n){n!==void 0?e[t+(n>>3)]|=1<<(n&7):e[t>>3]|=1<<(t&7)}function Xr(e,t,n){n!==void 0?e[t+(n>>3)]&=~(1<<(n&7)):e[t>>3]&=~(1<<(t&7))}function Yr(e,t){if(!e)throw new Error(`Assertion failed: ${t}`)}class Ii{constructor(t){U(this,"vfs");U(this,"buffer");U(this,"uint8");U(this,"view");U(this,"in_flight_flushes",new Map);U(this,"in_flight_reads",new Map);U(this,"coordinator",null);if(!t.vfs)throw new Error("Io requires a valid IVfsAdapter instance");if(!t.memory)throw new Error("Io requires a valid memory buffer or WebAssembly.Memory");this.vfs=t.vfs,this.buffer=t.memory instanceof WebAssembly.Memory?t.memory.buffer:t.memory,this.uint8=new Uint8Array(this.buffer),this.view=new DataView(this.buffer)}setTransactionCoordinator(t){this.coordinator=t}isInTransaction(){return this.coordinator?this.coordinator.isInTransaction():!1}stampSlotChecksum(t,n){const s=t*4096,i=this.uint8.subarray(s,s+4096);if(n===1){const r=Ei(i);Tt(this.view,s+ye,r)}else{const r=Ge(i);Tt(this.view,s+Re,r)}}async readSlot(t,n){if(n<=0)throw new Error(`Invalid page ID: ${n}. Page IDs must be positive integers.`);if(this.coordinator&&this.coordinator.hasSpilledPage(n)){const o=t*4096,a=this.coordinator.getSpilledPage(n);this.uint8.set(a,o);return}const s=this.in_flight_flushes.get(n);s&&await s;const i=this.in_flight_reads.get(n);if(i){await i;return}const r=(async()=>{const[o]=await this.vfs.readPages([n]),a=t*4096;if(o){if(o.byteLength!==4096)throw new Se(n,`Unexpected page byte length: ${o.byteLength}, expected 4096`);const c=n===1?ye:Re,l=yt(new DataView(o.buffer,o.byteOffset),c);if(l!==0){const u=n===1?Ei(o):Ge(o);if(u!==l)throw new Se(n,l,u)}this.uint8.set(o,a)}else this.uint8.fill(0,a,a+4096)})();this.in_flight_reads.set(n,r);try{await r}finally{this.in_flight_reads.delete(n)}}async writeSlot(t,n){if(n<=0)throw new Error(`Invalid page ID: ${n}. Page IDs must be positive integers.`);const s=this.in_flight_flushes.get(n);if(s){await s;return}const i=t*4096,r=this.uint8.subarray(i,i+4096);this.stampSlotChecksum(t,n);const o=r.slice();this.coordinator&&this.coordinator.onDirectPageWrite(n,o);const a=this.vfs.writePages([{pageId:n,data:o}]);this.in_flight_flushes.set(n,a);try{await a}finally{this.in_flight_flushes.delete(n)}}async spillOrWriteSlot(t,n){this.coordinator&&this.coordinator.isInTransaction()?await this.coordinator.spillUncommittedSlot(t,n):await this.writeSlot(t,n)}async resolvePageFault(t,n,s){if(s>0&&(this.coordinator&&this.coordinator.isInTransaction()?await this.coordinator.spillUncommittedSlot(t,s):await this.writeSlot(t,s)),this.coordinator&&this.coordinator.hasSpilledPage(n)){const i=t*4096,r=this.coordinator.getSpilledPage(n);this.uint8.set(r,i)}else await this.readSlot(t,n)}async flush(){var t,n;await((n=(t=this.vfs).flush)==null?void 0:n.call(t))}}const pi=new Uint8Array([87,69,66,87,65,76]);function As(e={}){const t=new Uint8Array(Jn),n=new DataView(t.buffer,t.byteOffset,t.byteLength);t.set(pi,js),fs(n,Ks,e.walVersion??Tr),Tt(n,Js,e.pageSize??we),Tt(n,zs,e.checkpointSeq??0);const s=e.salt1??Math.floor(Math.random()*4294967295)>>>0;Tt(n,ti,s);const i=e.salt2??Math.floor(Math.random()*4294967295)>>>0;Tt(n,ei,i);const r=e.checksum??mi(t,0,24);return Tt(n,ni,r),Tt(n,Cr,0),t}function hs(e,t=!0){if(e.byteLength<Jn)throw new as(`Truncated WAL file header: expected at least ${Jn} bytes, received ${e.byteLength}`);for(let l=0;l<6;l++)if(e[js+l]!==pi[l])throw new as('Invalid WAL file header magic identifier (expected "WEBWAL")');const n=new DataView(e.buffer,e.byteOffset,e.byteLength),s=us(n,Ks),i=yt(n,Js),r=yt(n,zs),o=yt(n,ti),a=yt(n,ei),c=yt(n,ni);if(t){const l=mi(e,0,24);if(c!==l)throw new as(`WAL file header CRC32 checksum mismatch: stored ${c}, computed ${l}`)}return{walVersion:s,pageSize:i,checkpointSeq:r,salt1:o,salt2:a,checksum:c}}function gs(e,t){const n=new Uint8Array(ze),s=new DataView(n.buffer,n.byteOffset,n.byteLength);Tt(s,si,e.magic??Pn),fs(s,ii,e.frameType),fs(s,ri,e.flags??0),Tt(s,oi,e.txId),Tt(s,ai,e.pageId),Tt(s,li,e.dbSizePages??0),Tt(s,ci,e.frameSeq),Tt(s,wr,0),t&&n.set(t.subarray(0,we),ke);const i=e.checksum??ls(n);return Tt(s,ui,i),n}function yi(e){if(e.byteLength<ke)throw new Fn(`Truncated WAL frame header: expected at least ${ke} bytes, received ${e.byteLength}`);const t=new DataView(e.buffer,e.byteOffset,e.byteLength);return{magic:yt(t,si),frameType:us(t,ii),flags:us(t,ri),txId:yt(t,oi),pageId:yt(t,ai),dbSizePages:yt(t,li),frameSeq:yt(t,ci),checksum:yt(t,ui)}}function Ti(e){if(e.byteLength<ze)return{valid:!1,reason:"truncated"};const t=yi(e);if(t.magic!==Pn)return{valid:!1,reason:"magic_mismatch",header:t};const n=ls(e);return t.checksum!==n?{valid:!1,reason:"checksum_mismatch",header:t}:{valid:!0,header:t}}function Sl(e,t=!0){if(e.byteLength<ze)throw new Fn(`Truncated WAL frame: expected ${ze} bytes, received ${e.byteLength}`);const n=yi(e);if(n.magic!==Pn)throw new Fn(`Invalid WAL frame magic: expected 0x${Pn.toString(16)}, got 0x${n.magic.toString(16)}`);if(t){const i=ls(e);if(n.checksum!==i)throw new Fn(`WAL frame CRC32 checksum mismatch: stored ${n.checksum}, computed ${i}`)}const s=e.subarray(ke,ze);return{header:n,pageData:s}}const Zr=new TextDecoder,jr="0123456789abcdef",Ci="0123456789ABCDEFGHJKMNPQRSTVWXYZ";function Ul(e){return e>=48&&e<=57?e-48:e>=97&&e<=102?e-97+10:e>=65&&e<=70?e-65+10:-1}function wi(e){if(e>=48&&e<=57)return e-48;switch(e>=97&&e<=122&&(e=e-32),e){case 65:return 10;case 66:return 11;case 67:return 12;case 68:return 13;case 69:return 14;case 70:return 15;case 71:return 16;case 72:return 17;case 74:return 18;case 75:return 19;case 77:return 20;case 78:return 21;case 80:return 22;case 81:return 23;case 82:return 24;case 83:return 25;case 84:return 26;case 86:return 27;case 87:return 28;case 88:return 29;case 89:return 30;case 90:return 31;case 73:case 76:return 1;case 79:return 0;default:return-1}}function Ol(e,t,n){let s=0,i=-1;for(let r=0;r<cs(e);r++){const o=e.charCodeAt(r);if(o!==45){if(s>=32)return-1;const a=Ul(o);if(a<0)return-1;s%2===0?i=a:t[n+(s>>1)]=i<<4|a,s++}}return s!==32?-1:0}function Pl(e,t,n){let s=0;for(let i=0;i<16;i++){(i===4||i===6||i===8||i===10)&&(n[s++]=45);const r=e[t+i];n[s++]=jr.charCodeAt(r>>4&15),n[s++]=jr.charCodeAt(r&15)}n[s]=0}class sn{static encode(t,n,s=0){if(Ol(t,n,s)!==0)throw new Error(`Invalid UUID format: "${t}" (must be 36 characters with hyphens)`)}static decode(t,n=0){const s=new Uint8Array(37);return Pl(t,n,s),Zr.decode(s.subarray(0,36))}}function Nl(e,t,n){if(cs(e)!==26)return-1;let s=0n;for(let o=0;o<10;o++){const a=wi(e.charCodeAt(o));if(a<0)return-1;s=s<<5n|BigInt(a)}t[n+0]=Number(s>>40n&0xffn),t[n+1]=Number(s>>32n&0xffn),t[n+2]=Number(s>>24n&0xffn),t[n+3]=Number(s>>16n&0xffn),t[n+4]=Number(s>>8n&0xffn),t[n+5]=Number(s&0xffn);let i=0n;for(let o=10;o<18;o++){const a=wi(e.charCodeAt(o));if(a<0)return-1;i=i<<5n|BigInt(a)}let r=0n;for(let o=18;o<26;o++){const a=wi(e.charCodeAt(o));if(a<0)return-1;r=r<<5n|BigInt(a)}for(let o=0;o<5;o++)t[n+6+o]=Number(i>>BigInt((4-o)*8)&0xffn),t[n+11+o]=Number(r>>BigInt((4-o)*8)&0xffn);return 0}function bl(e,t,n){let s=0n;for(let o=0;o<6;o++)s=s<<8n|BigInt(e[t+o]);for(let o=9;o>=0;o--)n[o]=Ci.charCodeAt(Number(s%32n)),s/=32n;let i=0n;for(let o=0;o<5;o++)i=i<<8n|BigInt(e[t+6+o]);let r=0n;for(let o=0;o<5;o++)r=r<<8n|BigInt(e[t+11+o]);for(let o=25;o>=18;o--)n[o]=Ci.charCodeAt(Number(r&31n)),r>>=5n;for(let o=17;o>=10;o--)n[o]=Ci.charCodeAt(Number(i&31n)),i>>=5n;n[26]=0}class rn{static encode(t,n,s=0){if(Nl(t,n,s)!==0)throw new Error(`Invalid ULID length: "${t}" (must be 26 Crockford Base32 characters)`)}static decode(t,n=0){const s=new Uint8Array(27);return bl(t,n,s),Zr.decode(s.subarray(0,26))}}const Si=new TextEncoder,_s=new TextDecoder;function Dn(e,t,n=es,s=0){e.setUint8(t+0,n),e.setUint8(t+1,0),e.setUint16(t+2,0,!0),e.setUint16(t+4,4096,!0),e.setUint32(t+6,s,!0),e.setUint16(t+10,0,!0),e.setUint32(t+Re,0,!0)}function Kr(e,t,n=0){e.setUint8(t+0,Me),e.setUint8(t+1,0),e.setUint16(t+2,0,!0),e.setUint16(t+4,0,!0),e.setUint32(t+6,n,!0),e.setUint16(t+10,0,!0),e.setUint32(t+Re,0,!0)}function qe(e,t){return e.getUint8(t+0)}function Bl(e,t,n){e.setUint8(t+0,n)}function ut(e,t){return e.getUint16(t+2,!0)}function We(e,t,n){e.setUint16(t+2,n,!0)}function He(e,t){return e.getUint16(t+4,!0)}function Ve(e,t,n){e.setUint16(t+4,n,!0)}function Ut(e,t){return e.getUint32(t+6,!0)}function ds(e,t,n){e.setUint32(t+6,n,!0)}function Ue(e,t){return e.getUint16(t+10,!0)}function $e(e,t,n){e.setUint16(t+10,n,!0)}function Ll(e,t){return e.getUint32(t+Re,!0)}function Rl(e,t,n){e.setUint32(t+Re,n,!0)}function ot(e,t,n){const s=t+Kt+n*2;return e.getUint16(s,!0)}function on(e,t,n,s){const i=t+Kt+n*2;e.setUint16(i,s,!0)}function ms(e,t){const n=ut(e,t),s=He(e,t),i=Kt+n*2;return s-i}function Jr(e,t){return ms(e,t)+Ue(e,t)}function Qn(e,t,n=0,s){const i=ut(e,t);if(i===0){Ve(e,t,4096),$e(e,t,0);return}let r=e,o=n;if(n===0||n===t||n+4096>e.byteLength){const c=new Uint8Array(4096);r=new DataView(c.buffer),o=0}nn(r,o,e,t,Kt);let a=4096;for(let c=0;c<i;c++){let l=0,u=e,_=0;if(s&&c===s.cell_idx)l=s.row_bytes.byteLength,u=s.row_bytes,_=0;else{const A=ot(e,t,c);qe(e,t)===ts?l=2+e.getUint16(t+A,!0)+8:l=Es(e,t+A),u=e,_=t+A}a=a-l,nn(r,o+a,u,_,l),on(r,o,c,a)}Ve(r,o,a),$e(r,o,0),nn(e,t,r,o,4096)}function Es(e,t){return e.getUint16(t+1,!0)}function an(e,t,n,s){const i=ut(e,t),r=He(e,t),o=n.byteLength+2,a=Kt+i*2,c=r-a,l=c+Ue(e,t);if(o>l)return-1;o>c&&Qn(e,t,s);const u=He(e,t),_=ut(e,t),A=u-n.byteLength,f=e.byteOffset+t+A;return new Uint8Array(e.buffer).set(n,f),on(e,t,_,A),We(e,t,_+1),Ve(e,t,A),_}function zr(e,t,n){const s=ut(e,t);if(n>=s)return;const i=ot(e,t,n),r=Es(e,t+i),o=t+Kt,a=o+(n+1)*2,c=o+n*2,l=(s-1-n)*2;l>0&&nn(e,c,e,a,l),We(e,t,s-1),$e(e,t,Ue(e,t)+r)}function Ui(e,t,n,s,i){const r=ut(e,t);if(n<0||n>=r)throw new Error(`Invalid cell index ${n} for update`);const o=ot(e,t,n),a=Es(e,t+o),c=s.byteLength,l=new Uint8Array(e.buffer);if(c<=a)return l.set(s,e.byteOffset+t+o),c<a&&$e(e,t,Ue(e,t)+(a-c)),!0;const u=Jr(e,t),_=c-a;if(u>=_){if(ms(e,t)<c)return Qn(e,t,i,{cell_idx:n,row_bytes:s}),!0;$e(e,t,Ue(e,t)+a);const g=He(e,t)-c;return l.set(s,e.byteOffset+t+g),on(e,t,n,g),Ve(e,t,g),!0}return!1}function Fl(e){const t=Array.isArray(e)?e:e.columns,n=Math.ceil(t.length/8);let s=0,i=0;for(let r=0;r<t.length;r++){const o=t[r];o.type===C.INT32?s+=4:o.type===C.INT64||o.type===C.FLOAT64?s+=8:o.type===C.UUID||o.type===C.ULID?s+=16:(o.type===C.TEXT||o.type===C.BLOB)&&i++}return{null_bitmap_bytes:n,fixed_slice_size:s,var_col_count:i}}function Is(e,t){const n=Array.isArray(e)?e:e.columns,s=n.length;if(s>ue)throw new Ln(s,ue);const i=Math.ceil(s/8),r=new Uint8Array(i);for(let p=0;p<s;p++){const y=n[p],T=t[y.name];if(T==null){if(y.flags&tt.NOT_NULL)throw new ns(y.name);const B=p>>3,P=1<<(p&7);r[B]|=P}}let o=0;for(let p=0;p<s;p++){const y=n[p];if(!((r[p>>3]&1<<(p&7))!==0))switch(y.type){case C.INT32:o+=4;break;case C.INT64:case C.FLOAT64:o+=8;break;case C.UUID:case C.ULID:o+=16;break}}const a=[];for(let p=0;p<s;p++){const y=n[p];if(y.type===C.TEXT||y.type===C.BLOB)if((r[p>>3]&1<<(p&7))!==0)a.push({col_idx:p,col:y,payload:null});else{const N=t[y.name];let B;y.type===C.TEXT?B=Si.encode(String(N??"")):B=N instanceof Uint8Array?N:new Uint8Array(N),a.push({col_idx:p,col:y,payload:B})}}const c=a.length*4,l=3+i+o+c;let u=0;for(let p=0;p<a.length;p++){const y=a[p];y.payload&&(u+=y.payload.byteLength)}const _=l+u;if(_>2048)throw new Br(_,2048);const A=new Uint8Array(_),f=new DataView(A.buffer);f.setUint8(0,1),f.setUint16(1,_,!0),A.set(r,3);let g=3+i;for(let p=0;p<s;p++){const y=n[p];if(!((r[p>>3]&1<<(p&7))!==0)){const N=t[y.name];switch(y.type){case C.INT32:f.setInt32(g,Number(N),!0),g+=4;break;case C.INT64:f.setBigInt64(g,BigInt(N),!0),g+=8;break;case C.FLOAT64:f.setFloat64(g,Number(N),!0),g+=8;break;case C.UUID:sn.encode(String(N),A,g),g+=16;break;case C.ULID:rn.encode(String(N),A,g),g+=16;break}}}let d=g,I=l;for(let p=0;p<a.length;p++){const y=a[p];y.payload===null?(f.setUint16(d,0,!0),f.setUint16(d+2,0,!0)):(f.setUint16(d,I,!0),f.setUint16(d+2,y.payload.byteLength,!0),A.set(y.payload,I),I+=y.payload.byteLength),d+=4}return A}function xe(e,t,n){let s,i,r;if(e instanceof DataView){i=e,r=t;const g=n;s=Array.isArray(g)?g:g.columns}else s=Array.isArray(e)?e:e.columns,i=t,r=n;const o={},a=s.length,c=Math.ceil(a/8),l=new Uint8Array(i.buffer,i.byteOffset+r+3,c);let u=r+3+c,_=0;const A=u;for(let g=0;g<a;g++){const d=s[g];if(!((l[g>>3]&1<<(g&7))!==0))switch(d.type){case C.INT32:u+=4;break;case C.INT64:case C.FLOAT64:u+=8;break;case C.UUID:case C.ULID:u+=16;break}}const f=u;u=A;for(let g=0;g<a;g++){const d=s[g];if((l[g>>3]&1<<(g&7))!==0){o[d.name]=null,(d.type===C.TEXT||d.type===C.BLOB)&&_++;continue}switch(d.type){case C.INT32:o[d.name]=i.getInt32(u,!0),u+=4;break;case C.INT64:o[d.name]=i.getBigInt64(u,!0),u+=8;break;case C.FLOAT64:o[d.name]=i.getFloat64(u,!0),u+=8;break;case C.UUID:{const p=new Uint8Array(i.buffer,i.byteOffset+u,16);o[d.name]=sn.decode(p,0),u+=16;break}case C.ULID:{const p=new Uint8Array(i.buffer,i.byteOffset+u,16);o[d.name]=rn.decode(p,0),u+=16;break}case C.TEXT:{const p=f+_*4,y=i.getUint16(p,!0),T=i.getUint16(p+2,!0),N=i.byteOffset+r+y,B=new Uint8Array(i.buffer,N,T);o[d.name]=_s.decode(B),_++;break}case C.BLOB:{const p=f+_*4,y=i.getUint16(p,!0),T=i.getUint16(p+2,!0),N=i.byteOffset+r+y,B=new Uint8Array(T);B.set(new Uint8Array(i.buffer,N,T)),o[d.name]=B,_++;break}}}return o}function to(e,t,n=0){Dn(e,t,fi,n)}function ps(e,t){return e.getUint32(t+6,!0)}function eo(e,t,n){e.setUint32(t+6,n,!0)}function no(e,t,n,s){const i=ut(e,t);if(i>=lr)return-1;const o=He(e,t)-ar,a=t+o;return e.setUint32(a,n,!0),e.setBigInt64(a+4,s,!0),on(e,t,i,o),We(e,t,i+1),Ve(e,t,o),i+1}function Dl(e,t,n){const s=ut(e,t);if(s===0)return ps(e,t);let i=0,r=s-1,o=-1;for(;i<=r;){const a=i+r>>1,c=ot(e,t,a),l=e.getBigInt64(t+c+4,!0);n<=l?(o=e.getUint32(t+c,!0),r=a-1):i=a+1}return o!==-1?o:ps(e,t)}function Ql(e,t,n){const s=ut(e,t),i=cr;if(s<=i)throw new Error(`Cannot split interior page with only ${s} cells`);const r=ot(e,t,i),o=e.getUint32(t+r,!0),a=e.getBigInt64(t+r+4,!0),c=ps(e,t);to(e,n,c);for(let l=i+1;l<s;l++){const u=ot(e,t,l),_=e.getUint32(t+u,!0),A=e.getBigInt64(t+u+4,!0);no(e,n,_,A)}return eo(e,t,o),We(e,t,i),{median_rowid:a,promoted_child_page_id:o,right_child_page_id:c}}function ys(e,t,n=0){Dn(e,t,ts,n)}function Ts(e,t,n,s,i,r){if(e!==s)return e-s;if(e===C.NULL)return n<r?-1:n>r?1:0;let o=0;if(e===C.INT32||e===C.INT64||e===C.FLOAT64){const a=typeof t=="bigint"?Number(t):t,c=typeof i=="bigint"?Number(i):i;o=a<c?-1:a>c?1:0}else if(e===C.TEXT||e===C.UUID||e===C.ULID){const a=String(t),c=String(i);o=a<c?-1:a>c?1:0}else if(e===C.BLOB){const a=t,c=i,l=Math.min(a.length,c.length);for(let u=0;u<l;u++)if(a[u]!==c[u]){o=a[u]<c[u]?-1:1;break}o===0&&(o=a.length-c.length)}return o!==0?o:n<r?-1:n>r?1:0}function Oi(e,t,n,s){const i=new Uint8Array(e.buffer,e.byteOffset+t,n);return n===0?{cellType:C.NULL,cellVal:null}:s===C.TEXT?n===4&&(i[2]===0&&i[3]===0||i[2]===255&&i[3]===255)?{cellType:C.INT32,cellVal:new DataView(i.buffer,i.byteOffset).getInt32(0,!0)}:n===2&&i[0]<32&&i[1]<32?{cellType:C.BLOB,cellVal:i}:{cellType:C.TEXT,cellVal:_s.decode(i)}:n===2?{cellType:C.BLOB,cellVal:i}:n===4?{cellType:C.INT32,cellVal:new DataView(i.buffer,i.byteOffset).getInt32(0,!0)}:s===C.UUID&&n===16?{cellType:C.UUID,cellVal:sn.decode(i,0)}:s===C.ULID&&n===16?{cellType:C.ULID,cellVal:rn.decode(i,0)}:s===C.FLOAT64&&n===8?{cellType:C.FLOAT64,cellVal:new DataView(i.buffer,i.byteOffset).getFloat64(0,!0)}:s===C.INT64&&n===8?{cellType:C.INT64,cellVal:new DataView(i.buffer,i.byteOffset).getBigInt64(0,!0)}:s===C.BLOB?n===5||n===6?{cellType:C.TEXT,cellVal:_s.decode(i)}:{cellType:C.BLOB,cellVal:i}:{cellType:C.TEXT,cellVal:_s.decode(i)}}function Pi(e,t,n,s,i,r){let o;n===C.NULL||s===null||s===void 0?o=new Uint8Array(0):n===C.INT32?(o=new Uint8Array(4),new DataView(o.buffer).setInt32(0,Number(s),!0)):n===C.INT64?(o=new Uint8Array(8),new DataView(o.buffer).setBigInt64(0,BigInt(s),!0)):n===C.FLOAT64?(o=new Uint8Array(8),new DataView(o.buffer).setFloat64(0,Number(s),!0)):n===C.UUID?(o=new Uint8Array(16),sn.encode(String(s),o,0)):n===C.ULID?(o=new Uint8Array(16),rn.encode(String(s),o,0)):n===C.TEXT?o=Si.encode(String(s)):o=s instanceof Uint8Array?s:new Uint8Array(s);const a=2+o.byteLength+8,c=a+2,l=ut(e,t),u=ms(e,t),_=u+Ue(e,t);if(c>_)return-1;c>u&&Qn(e,t,r);const f=He(e,t)-a,g=t+f,d=e.byteOffset+g;e.setUint16(g,o.byteLength,!0),new Uint8Array(e.buffer).set(o,d+2),e.setBigInt64(g+2+o.byteLength,i,!0);let I=0,p=l-1,y=l;for(;I<=p;){const S=I+p>>1,v=ot(e,t,S),L=e.getUint16(t+v,!0),h=e.getBigInt64(t+v+2+L,!0),{cellType:b,cellVal:k}=Oi(e,t+v+2,L,n);Ts(n,s,i,b,k,h)<0?(y=S,p=S-1):I=S+1}const T=new Uint8Array(e.buffer),B=e.byteOffset+t+Kt,P=B+y*2,F=B+(y+1)*2,w=(l-y)*2;return w>0&&T.copyWithin(F,P,P+w),on(e,t,y,f),We(e,t,l+1),Ve(e,t,f),y}function so(e,t,n){const s=ut(e,t);if(n<0||n>=s)return;const i=ot(e,t,n),o=2+e.getUint16(t+i,!0)+8,a=t+Kt,c=a+(n+1)*2,l=a+n*2,u=(s-1-n)*2;u>0&&nn(e,l,e,c,u),We(e,t,s-1),$e(e,t,Ue(e,t)+o)}function vn(e,t,n,s,i){const r=ut(e,t);let o=0,a=r-1;for(;o<=a;){const c=o+a>>1,l=ot(e,t,c),u=e.getUint16(t+l,!0),_=e.getBigInt64(t+l+2+u,!0),{cellType:A,cellVal:f}=Oi(e,t+l+2,u,n),d=Ts(n,s,i!==void 0?i:_,A,f,_);if(d===0){if(i===void 0){let I=c;for(;I>0;){const p=I-1,y=ot(e,t,p),T=e.getUint16(t+y,!0),{cellType:N,cellVal:B}=Oi(e,t+y+2,T,n);if(Ts(n,s,0n,N,B,0n)===0)I=p;else break}return{found:!0,slot_idx:I}}return{found:!0,slot_idx:c}}else d<0?a=c-1:o=c+1}return{found:!1,slot_idx:o}}function io(e,t){if(t==null)return new Uint8Array(0);if(e===C.INT32){const n=new Uint8Array(4);return new DataView(n.buffer).setInt32(0,Number(t),!0),n}if(e===C.INT64){const n=new Uint8Array(8);return new DataView(n.buffer).setBigInt64(0,BigInt(t),!0),n}if(e===C.FLOAT64){const n=new Uint8Array(8);return new DataView(n.buffer).setFloat64(0,Number(t),!0),n}if(e===C.UUID){const n=new Uint8Array(16);return sn.encode(String(t),n,0),n}if(e===C.ULID){const n=new Uint8Array(16);return rn.encode(String(t),n,0),n}return e===C.TEXT?Si.encode(String(t)):t instanceof Uint8Array?t:new Uint8Array(t)}function Cs(e,t,n,s){const i=[];let r=0;for(let c=0;c<n;c++){const l=e[t[c]],u=s[l.name],_=io(l.type,u),A=new Uint8Array(3+_.byteLength);A[0]=l.type,A[1]=_.byteLength&255,A[2]=_.byteLength>>8&255,A.set(_,3),i.push(A),r+=A.byteLength}const o=new Uint8Array(r);let a=0;for(let c=0;c<i.length;c++){const l=i[c];o.set(l,a),a+=l.byteLength}return o}const vl=2654435769;function kn(e,t){const n=Math.imul(e,vl);return(n^n>>>16)>>>0&t}function ro(e,t,n,s){const i=n-1;let r=kn(s,i);for(let o=0;o<n;o++){const a=t+r*Ce,c=e.getUint32(a,!0);if(c===0)return-1;if(c===s)return e.getUint32(a+4,!0);r=r+1&i}return-1}function oo(e,t,n,s,i){const r=n-1;let o=kn(s,r);for(let a=0;a<n;a++){const c=t+o*Ce,l=e.getUint32(c,!0);if(l===0||l===s){e.setUint32(c,s,!0),e.setUint32(c+4,i,!0);return}o=o+1&r}throw new Error(`BufferPool page table full: cannot insert page ${s}`)}function Ni(e,t,n,s){const i=n-1;let r=kn(s,i),o=!1;for(let l=0;l<n;l++){const u=t+r*Ce,_=e.getUint32(u,!0);if(_===0)return!1;if(_===s){o=!0;break}r=r+1&i}if(!o)return!1;let a=r;for(;;){a=a+1&i;const l=t+a*Ce,u=e.getUint32(l,!0);if(u===0)break;const _=kn(u,i);if((r-_&i)<(a-_&i)){const A=e.getUint32(l+4,!0),f=t+r*Ce;e.setUint32(f,u,!0),e.setUint32(f+4,A,!0),r=a}}const c=t+r*Ce;return e.setUint32(c,0,!0),e.setUint32(c+4,0,!0),!0}function kl(e){return e*4096}function ln(e,t,n){return yt(e,t+n*4)}function bi(e,t,n,s){Tt(e,t+n*4,s)}function Wt(e,t,n,s){return ro(e,t,n,s)}function ao(e,t,n,s,i,r){Yr(r>0,"page_id must be > 0");const o=ln(e,t,i);return o>0&&o!==r&&Ni(e,n,s,o),bi(e,t,i,r),oo(e,n,s,r,i),0}function lo(e,t,n,s,i){const r=ln(e,t,i);return r>0?(Ni(e,n,s,r),bi(e,t,i,0),1):0}function co(e,t,n){xr(e,t,n)}function uo(e,t,n){Xr(e,t,n)}function Bi(e,t,n){return $r(e,t,n)===1}function Li(e,t){if(e[t]>=4294967295)throw new Error(`Pin count overflow on slot ${t}`);e[t]++}function Ri(e,t){t!==0&&e[t]>0&&e[t]--}function cn(e,t){return t===0||e[t]>0}function Fi(e,t,n,s,i,r){const o=new DataView(e);for(let c=1;c<i;c++)if(yt(o,s+c*4)===0&&!cn(n,c))return{candidate_slot:c,next_clock_hand:r};let a=r;for(let c=0;c<i*2;c++){if(a=(a+1)%i,a===0||cn(n,a))continue;const l=new DataView(e,a*4096,4096);if(qe(l,0)!==Nn)if(t[a]===1)t[a]=0;else return{candidate_slot:a,next_clock_hand:a}}throw new Error("Cache deadlock: all slots are pinned")}function Di(e,t,n,s,i,r,o,a){const c=new DataView(e);let l=-1,u=o;if(a>1&&a<=r&&ln(c,s,a-1)===0&&!cn(n,a-1))l=a-1;else{const I=Fi(e,t,n,s,r,o);l=I.candidate_slot,u=I.next_clock_hand}const _=ln(c,s,l),A=Bi(new Uint8Array(e),i,l),f=new DataView(e,l*4096,4096),g=_>0&&qe(f,0)===Me,d=A&&!g&&_>0?_:0;return{candidate_slot:l,flush_page_id:d,next_clock_hand:u}}function Ct(e,t){return e.cursors&&e.cursors[t]?e.cursors[t]:e.cursor}function Vt(e,t){if(t<=0)return 0;if(e.byteLength>=Mt+Ar){const n=Wt(e,Mt,qt,t);if(n>=0)return n*4096}return(t-1)*4096}function un(e,t){if(e==null||t===null||t===void 0)return{result:0,is_unknown:!0};if(typeof e=="boolean"||typeof t=="boolean"){const n=e?1:0,s=t?1:0;return n===s?{result:0,is_unknown:!1}:{result:n>s?1:-1,is_unknown:!1}}if(typeof e=="number"&&typeof t=="number")return e===t?{result:0,is_unknown:!1}:{result:e>t?1:-1,is_unknown:!1};if(typeof e=="bigint"||typeof t=="bigint"){const n=BigInt(e),s=BigInt(t);return n===s?{result:0,is_unknown:!1}:{result:n>s?1:-1,is_unknown:!1}}if(typeof e=="string"&&typeof t=="string")return e===t?{result:0,is_unknown:!1}:{result:e>t?1:-1,is_unknown:!1};if(e instanceof Uint8Array&&t instanceof Uint8Array){const n=Math.min(e.byteLength,t.byteLength);for(let s=0;s<n;s++)if(e[s]!==t[s])return{result:e[s]>t[s]?1:-1,is_unknown:!1};return e.byteLength===t.byteLength?{result:0,is_unknown:!1}:{result:e.byteLength>t.byteLength?1:-1,is_unknown:!1}}return e===t?{result:0,is_unknown:!1}:{result:e>t?1:-1,is_unknown:!1}}function fo(e){return e>=65&&e<=90?e+32:e}function Ml(e,t,n,s){let i=0,r=0,o=-1,a=-1;for(;i<t;){const c=r<s?n.charCodeAt(r):0,l=e.charCodeAt(i);if(r<s&&(c===95||fo(c)===fo(l)))i++,r++;else if(r<s&&c===37)o=r++,a=i;else if(o!==-1)r=o+1,i=++a;else return 0}for(;r<s&&n.charCodeAt(r)===37;)r++;return r===s?1:0}function Xe(e,t){return Ml(e,e.length,t,t.length)===1}function fn(e,t,n){const s=n.numKeys;for(let i=0;i<s;i++){const r=e[i],o=t[i],a=n.directions[i]??0,c=n.nullOrders[i]??(a===1?1:0),l=r==null,u=o==null;if(l&&u)continue;if(l||u)return c===0?l?-1:1:l?1:-1;let _=0;if(typeof r=="number"&&typeof o=="number")_=r<o?-1:r>o?1:0;else if(typeof r=="bigint"||typeof o=="bigint"){const A=BigInt(r),f=BigInt(o);_=A<f?-1:A>f?1:0}else if(typeof r=="string"&&typeof o=="string")_=r<o?-1:r>o?1:0;else if(r instanceof Uint8Array&&o instanceof Uint8Array){const A=Math.min(r.byteLength,o.byteLength);for(let f=0;f<A;f++)if(r[f]!==o[f]){_=r[f]<o[f]?-1:1;break}_===0&&(_=r.byteLength<o.byteLength?-1:r.byteLength>o.byteLength?1:0)}else _=r<o?-1:r>o?1:0;if(_!==0)return a===1?-_:_}return 0}function Ao(e,t,n,s){const i=s.numKeys;for(let r=0;r<i;r++){const o=e[t+r],a=n[r],c=s.directions[r]??0,l=s.nullOrders[r]??(c===1?1:0),u=o==null,_=a==null;if(u&&_)continue;if(u||_)return l===0?u?-1:1:u?1:-1;let A=0;if(typeof o=="number"&&typeof a=="number")A=o<a?-1:o>a?1:0;else if(typeof o=="string"&&typeof a=="string")A=o<a?-1:o>a?1:0;else if(typeof o=="bigint"||typeof a=="bigint"){const f=BigInt(o),g=BigInt(a);A=f<g?-1:f>g?1:0}else if(o instanceof Uint8Array&&a instanceof Uint8Array){const f=Math.min(o.byteLength,a.byteLength);for(let g=0;g<f;g++)if(o[g]!==a[g]){A=o[g]<a[g]?-1:1;break}A===0&&(A=o.byteLength<a.byteLength?-1:o.byteLength>a.byteLength?1:0)}else A=o<a?-1:o>a?1:0;if(A!==0)return c===1?-A:A}return 0}function ws(e){let t=2166136261;for(let n=0;n<e.length;n++){const s=e[n];if(s==null)t^=255,t=Math.imul(t,16777619);else if(typeof s=="number"){const i=new ArrayBuffer(8);new DataView(i).setFloat64(0,s,!0);const r=new Uint8Array(i);for(let o=0;o<8;o++)t^=r[o],t=Math.imul(t,16777619)}else if(typeof s=="string")for(let i=0;i<s.length;i++)t^=s.charCodeAt(i)&255,t=Math.imul(t,16777619);else if(typeof s=="bigint"){const i=Number(s);t^=i&255,t=Math.imul(t,16777619)}else if(s instanceof Uint8Array)for(let i=0;i<s.byteLength;i++)t^=s[i],t=Math.imul(t,16777619)}return t=t>>>0,t===0?1:t}function Gl(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++){const s=e[n],i=t[n];if(s==null){if(i!=null)return!1}else{if(i==null)return!1;if(s!==i)if(s instanceof Uint8Array&&i instanceof Uint8Array){if(s.byteLength!==i.byteLength)return!1;for(let r=0;r<s.byteLength;r++)if(s[r]!==i[r])return!1}else return!1}}return!0}function ho(e){const t=new Array(e);for(let n=0;n<e;n++)t[n]={hash:0,keys:[],count:0,sum:0,min_val:1/0,max_val:-1/0,has_val:!1};return t}function go(e,t,n,s){let i=t;for(;;){let r=i;const o=2*i+1,a=2*i+2;if(o<n&&fn(e[o].keys,e[r].keys,s)>0&&(r=o),a<n&&fn(e[a].keys,e[r].keys,s)>0&&(r=a),r!==i){const c=e[i];e[i]=e[r],e[r]=c,i=r}else break}}function ql(e){const t=e.keyInfo;e.entries.sort((n,s)=>fn(n.keys,s.keys,t)),e.readIdx=t.offset??0}function _o(e,t,n){const s=new Uint8Array(e.buffer,e.byteOffset+t,n),i=new Uint8Array(n);return i.set(s),i}function Wl(e,t,n,s,i,r,o){if(o>0&&t.entries.length>=o){if(fn(n,t.entries[0].keys,t.keyInfo)>=0)return O.RUNNING;const u=t.entries[0],_=i-u.rowLen;if(_>0&&e.arenaOffset+_>e.maxQueryMemory)return e.status=O.ARENA_EXHAUSTED,O.ARENA_EXHAUSTED;e.arenaOffset+=_;const A=_o(r,s,i);return u.keys=n,u.rowOffset=s,u.rowLen=i,u.rowData=A,go(t.entries,0,o,t.keyInfo),O.RUNNING}const a=16+16*n.length+i;if(e.arenaOffset+a>e.maxQueryMemory)return e.status=O.ARENA_EXHAUSTED,O.ARENA_EXHAUSTED;e.arenaOffset+=a;const c=_o(r,s,i);if(t.entries.push({keys:n,rowOffset:s,rowLen:i,rowData:c}),o>0&&t.entries.length===o)for(let l=Math.floor(o/2)-1;l>=0;l--)go(t.entries,l,o,t.keyInfo);return O.RUNNING}function Hl(e,t,n){var r,o;let s;const i={};if(e.outputColumns&&n===e.outputColumns.length){s=e.outputColumns;for(let a=0;a<n;a++)i[s[a].name]=e.registers[t+a]}else if(e.table&&n===e.table.columns.length){s=e.table.columns;for(let a=0;a<n;a++)i[s[a].name]=e.registers[t+a]}else{s=[];for(let a=0;a<n;a++){const c=e.registers[t+a],l=((o=(r=e.table)==null?void 0:r.columns[a])==null?void 0:o.name)??`col_${a}`;let u=C.TEXT;typeof c=="number"?u=Number.isInteger(c)?C.INT32:C.FLOAT64:typeof c=="bigint"?u=C.INT64:c instanceof Uint8Array&&(u=C.BLOB),s.push({name:l,type:u,flags:tt.NONE,colOffset:0}),i[l]=c}}return Is(s,i)}function Qi(e,t,n,s){const i=2+n.byteLength;if(e.resultOffset+i>Ys)return e.status=O.BUFFER_FULL,e.pc=s,O.BUFFER_FULL;const r=On+e.resultOffset;return t.setUint16(r,n.byteLength,!0),new Uint8Array(t.buffer,t.byteOffset+r+2,n.byteLength).set(n),e.resultOffset+=i,e.resultCount++,O.RUNNING}function Ye(e,t,n){return(e.getUint8(t+(n>>3))&1<<(n&7))!==0}function Mn(e,t,n,s,i){let r=t+n;for(let o=0;o<i;o++)if(!Ye(e,t,o))switch(s[o].type){case C.INT32:r+=4;break;case C.INT64:case C.FLOAT64:r+=8;break;case C.UUID:case C.ULID:r+=16;break}return r}const mo=new TextDecoder;function Gn(e,t,n){var c,l;const s=new DataView(n.buffer,n.byteOffset,n.byteLength),i=n.byteLength,r=1e7;let o=0;const a=t.byteLength>=Yn+4&&t.getUint32(Yn,!0)>0;for(;e.pc<i;){if(++o>r)return e.status=O.TIMEOUT,O.TIMEOUT;const u=e.pc,_=n[e.pc];switch(e.pc+=1,_){case m.OP_HALT:return e.arenaOffset=0,e.status=O.DONE,O.DONE;case m.OP_OPEN_CURSOR:{const A=n[e.pc],f=s.getUint32(e.pc+1,!0);e.pc+=5;const g=Ct(e,A);if(g.pageId=f,g.cellIdx=0,g.rowOffset=0,a&&f>0){const d=Wt(t,Mt,qt,f);if(d<0)return e.fault_page_id=f,e.status=O.PAGE_FAULT,e.pc=u,O.PAGE_FAULT;g.slotIdx=d}break}case m.OP_REWIND:{const A=n[e.pc],f=s.getUint16(e.pc+1,!0);if(e.pc+=3,f>i)return e.status=O.INVALID_BYTECODE,O.INVALID_BYTECODE;const g=Ct(e,A);if(a&&g.pageId>0){const p=Wt(t,Mt,qt,g.pageId);if(p<0)return e.fault_page_id=g.pageId,e.status=O.PAGE_FAULT,e.pc=u,O.PAGE_FAULT;g.slotIdx=p}const d=Vt(t,g.pageId);if(ut(t,d)===0)e.pc=f;else{g.cellIdx=0;const p=ot(t,d,0);g.rowOffset=d+p}break}case m.OP_NEXT_ROW:{const A=n[e.pc],f=s.getUint16(e.pc+1,!0);if(e.pc+=3,f>i)return e.status=O.INVALID_BYTECODE,O.INVALID_BYTECODE;const g=Ct(e,A),d=Vt(t,g.pageId),I=ut(t,d),p=g.cellIdx+1;if(p<I){g.cellIdx=p;const y=ot(t,d,g.cellIdx);g.rowOffset=d+y}else{const y=Ut(t,d);if(y!==0){if(a){const B=Wt(t,Mt,qt,y);if(B<0)return e.fault_page_id=y,e.status=O.PAGE_FAULT,e.pc=u,O.PAGE_FAULT;g.slotIdx=B}g.pageId=y,g.cellIdx=0;const T=Vt(t,y);if(ut(t,T)>0){const B=ot(t,T,0);g.rowOffset=T+B}else e.pc=f}else e.pc=f}break}case m.OP_LAST:{const A=n[e.pc],f=s.getUint16(e.pc+1,!0);if(e.pc+=3,f>i)return e.status=O.INVALID_BYTECODE,O.INVALID_BYTECODE;const g=Ct(e,A),d=Vt(t,g.pageId),I=ut(t,d);if(I===0)e.pc=f;else{g.cellIdx=I-1;const p=ot(t,d,g.cellIdx);g.rowOffset=d+p}break}case m.OP_PREV_ROW:{const A=n[e.pc],f=s.getUint16(e.pc+1,!0);if(e.pc+=3,f>i)return e.status=O.INVALID_BYTECODE,O.INVALID_BYTECODE;const g=Ct(e,A),d=Vt(t,g.pageId);if(g.cellIdx>0){g.cellIdx--;const I=ot(t,d,g.cellIdx);g.rowOffset=d+I}else e.pc=f;break}case m.OP_COLUMN_INT:{const A=n[e.pc],f=n[e.pc+1],g=n[e.pc+2];e.pc+=3;const d=Ct(e,A),I=(e.tables&&e.tables[A])??e.table,p=I.columns[f],y=Math.ceil(I.columns.length/8),T=d.rowOffset+3;if(Ye(t,T,f)){e.registers[g]=null;break}const N=Mn(t,T,y,I.columns,f);p.type===C.INT32?e.registers[g]=t.getInt32(N,!0):p.type===C.INT64&&(e.registers[g]=Number(t.getBigInt64(N,!0)));break}case m.OP_COLUMN_FLOAT:{const A=n[e.pc],f=n[e.pc+1],g=n[e.pc+2];e.pc+=3;const d=Ct(e,A),I=(e.tables&&e.tables[A])??e.table,p=Math.ceil(I.columns.length/8),y=d.rowOffset+3;if(Ye(t,y,f)){e.registers[g]=null;break}const T=Mn(t,y,p,I.columns,f);e.registers[g]=t.getFloat64(T,!0);break}case m.OP_COLUMN_UUID:case m.OP_COLUMN_ULID:case m.OP_COLUMN_TEXT:{const A=n[e.pc],f=n[e.pc+1],g=n[e.pc+2];e.pc+=3;const d=Ct(e,A),I=(e.tables&&e.tables[A])??e.table,p=Math.ceil(I.columns.length/8),y=d.rowOffset+3;if(Ye(t,y,f)){e.registers[g]=null;break}if(I.columns[f].type===C.UUID||I.columns[f].type===C.ULID){const w=Mn(t,y,p,I.columns,f),S=new Uint8Array(t.buffer,t.byteOffset+w,16);e.registers[g]=I.columns[f].type===C.UUID?sn.decode(S,0):rn.decode(S,0);break}const T=Mn(t,y,p,I.columns,I.columns.length);let N=0;for(let w=0;w<f;w++){const S=I.columns[w];(S.type===C.TEXT||S.type===C.BLOB)&&N++}const B=T+N*4,P=t.getUint16(B,!0),F=t.getUint16(B+2,!0);if(F===0)e.registers[g]="";else{const w=new Uint8Array(t.buffer,d.rowOffset+P,F);e.registers[g]=mo.decode(w)}break}case m.OP_COLUMN_BLOB:{const A=n[e.pc],f=n[e.pc+1],g=n[e.pc+2];e.pc+=3;const d=Ct(e,A),I=(e.tables&&e.tables[A])??e.table,p=Math.ceil(I.columns.length/8),y=d.rowOffset+3;if(Ye(t,y,f)){e.registers[g]=null;break}const T=Mn(t,y,p,I.columns,I.columns.length);let N=0;for(let S=0;S<f;S++){const v=I.columns[S];(v.type===C.TEXT||v.type===C.BLOB)&&N++}const B=T+N*4,P=t.getUint16(B,!0),F=t.getUint16(B+2,!0),w=new Uint8Array(F);w.set(new Uint8Array(t.buffer,d.rowOffset+P,F)),e.registers[g]=w;break}case m.OP_OPEN_INDEX:{const A=n[e.pc],f=s.getUint32(e.pc+1,!0);e.pc+=5;const g=Ct(e,A);if(g.pageId=f,g.rootPageId=f,g.cellIdx=0,g.rowOffset=0,a&&f>0){const d=Wt(t,Mt,qt,f);if(d<0)return e.fault_page_id=f,e.status=O.PAGE_FAULT,e.pc=u,O.PAGE_FAULT;g.slotIdx=d}break}case m.OP_INDEX_SEEK_EQ:{const A=n[e.pc],f=n[e.pc+1],g=n[e.pc+2],d=n[e.pc+3],I=s.getUint16(e.pc+4,!0);if(e.pc+=6,I>i)return e.status=O.INVALID_BYTECODE,O.INVALID_BYTECODE;const p=e.registers[g];if(p==null){e.pc=I;break}const y=Ct(e,A);let T=y.rootPageId||y.pageId,N=!1,B=0n;for(;T!==0;){if(a&&T>0){const w=Wt(t,Mt,qt,T);if(w<0)return e.fault_page_id=T,e.status=O.PAGE_FAULT,e.pc=u,O.PAGE_FAULT;y.slotIdx=w}const P=Vt(t,T),F=vn(t,P,d,p);if(F.found){N=!0,y.pageId=T,y.cellIdx=F.slot_idx;const w=ot(t,P,F.slot_idx),S=t.getUint16(P+w,!0);B=t.getBigInt64(P+w+2+S,!0);break}T=Ut(t,P)}if(!N)e.pc=I;else{const P=Number(B>>16n),F=Number(B&0xffffn);if(a&&P>0&&Wt(t,Mt,qt,P)<0)return e.fault_page_id=P,e.status=O.PAGE_FAULT,e.pc=u,O.PAGE_FAULT;const w=Ct(e,f);w.pageId=P,w.cellIdx=F;const S=Vt(t,P),v=ot(t,S,F);w.rowOffset=S+v}break}case m.OP_INDEX_SEEK_GE:{const A=n[e.pc],f=n[e.pc+1],g=n[e.pc+2],d=n[e.pc+3],I=s.getUint16(e.pc+4,!0);if(e.pc+=6,I>i)return e.status=O.INVALID_BYTECODE,O.INVALID_BYTECODE;const p=e.registers[g];if(p==null){e.pc=I;break}const y=Ct(e,A);let T=y.rootPageId||y.pageId,N=!1,B=0n;for(;T!==0;){if(a&&T>0){const S=Wt(t,Mt,qt,T);if(S<0)return e.fault_page_id=T,e.status=O.PAGE_FAULT,e.pc=u,O.PAGE_FAULT;y.slotIdx=S}const P=Vt(t,T),F=ut(t,P),w=vn(t,P,d,p);if(w.found||w.slot_idx<F){N=!0,y.pageId=T,y.cellIdx=w.slot_idx;const S=ot(t,P,w.slot_idx),v=t.getUint16(P+S,!0);B=t.getBigInt64(P+S+2+v,!0);break}T=Ut(t,P)}if(!N)e.pc=I;else{const P=Number(B>>16n),F=Number(B&0xffffn);if(a&&P>0&&Wt(t,Mt,qt,P)<0)return e.fault_page_id=P,e.status=O.PAGE_FAULT,e.pc=u,O.PAGE_FAULT;const w=Ct(e,f);w.pageId=P,w.cellIdx=F;const S=Vt(t,P),v=ot(t,S,F);w.rowOffset=S+v}break}case m.OP_INDEX_NEXT:{const A=n[e.pc],f=n[e.pc+1],g=s.getUint16(e.pc+2,!0);if(e.pc+=4,g>i)return e.status=O.INVALID_BYTECODE,O.INVALID_BYTECODE;const d=Ct(e,A);let I=d.pageId,p=Vt(t,I);const y=ut(t,p);let T=d.cellIdx+1;if(T>=y){if(I=Ut(t,p),I===0){e.pc=g;break}if(a&&I>0){const h=Wt(t,Mt,qt,I);if(h<0)return e.fault_page_id=I,e.status=O.PAGE_FAULT,e.pc=u,O.PAGE_FAULT;d.slotIdx=h}p=Vt(t,I),T=0,d.pageId=I,d.cellIdx=-1}const N=ot(t,p,T),B=t.getUint16(p+N,!0),P=t.getBigInt64(p+N+2+B,!0),F=Number(P>>16n),w=Number(P&0xffffn);if(a&&F>0&&Wt(t,Mt,qt,F)<0)return e.fault_page_id=F,e.status=O.PAGE_FAULT,e.pc=u,O.PAGE_FAULT;d.pageId=I,d.cellIdx=T;const S=Ct(e,f);S.pageId=F,S.cellIdx=w;const v=Vt(t,F),L=ot(t,v,w);S.rowOffset=v+L;break}case m.OP_IS_NULL:{const A=n[e.pc],f=n[e.pc+1],g=s.getUint16(e.pc+2,!0);if(e.pc+=4,g>i)return e.status=O.INVALID_BYTECODE,O.INVALID_BYTECODE;const I=Ct(e,A).rowOffset+3;Ye(t,I,f)&&(e.pc=g);break}case m.OP_IS_NOT_NULL:{const A=n[e.pc],f=n[e.pc+1],g=s.getUint16(e.pc+2,!0);if(e.pc+=4,g>i)return e.status=O.INVALID_BYTECODE,O.INVALID_BYTECODE;const I=Ct(e,A).rowOffset+3;Ye(t,I,f)||(e.pc=g);break}case m.OP_EQ:{const A=n[e.pc],f=n[e.pc+1],g=s.getUint16(e.pc+2,!0);if(e.pc+=4,g>i)return e.status=O.INVALID_BYTECODE,O.INVALID_BYTECODE;const d=un(e.registers[A],e.registers[f]);!d.is_unknown&&d.result===0&&(e.pc=g);break}case m.OP_NE:{const A=n[e.pc],f=n[e.pc+1],g=s.getUint16(e.pc+2,!0);if(e.pc+=4,g>i)return e.status=O.INVALID_BYTECODE,O.INVALID_BYTECODE;const d=un(e.registers[A],e.registers[f]);!d.is_unknown&&d.result!==0&&(e.pc=g);break}case m.OP_GT:{const A=n[e.pc],f=n[e.pc+1],g=s.getUint16(e.pc+2,!0);if(e.pc+=4,g>i)return e.status=O.INVALID_BYTECODE,O.INVALID_BYTECODE;const d=un(e.registers[A],e.registers[f]);!d.is_unknown&&d.result>0&&(e.pc=g);break}case m.OP_GE:{const A=n[e.pc],f=n[e.pc+1],g=s.getUint16(e.pc+2,!0);if(e.pc+=4,g>i)return e.status=O.INVALID_BYTECODE,O.INVALID_BYTECODE;const d=un(e.registers[A],e.registers[f]);!d.is_unknown&&d.result>=0&&(e.pc=g);break}case m.OP_LT:{const A=n[e.pc],f=n[e.pc+1],g=s.getUint16(e.pc+2,!0);if(e.pc+=4,g>i)return e.status=O.INVALID_BYTECODE,O.INVALID_BYTECODE;const d=un(e.registers[A],e.registers[f]);!d.is_unknown&&d.result<0&&(e.pc=g);break}case m.OP_LE:{const A=n[e.pc],f=n[e.pc+1],g=s.getUint16(e.pc+2,!0);if(e.pc+=4,g>i)return e.status=O.INVALID_BYTECODE,O.INVALID_BYTECODE;const d=un(e.registers[A],e.registers[f]);!d.is_unknown&&d.result<=0&&(e.pc=g);break}case m.OP_JUMP:{const A=s.getUint16(e.pc,!0);if(A>i)return e.status=O.INVALID_BYTECODE,O.INVALID_BYTECODE;e.pc=A;break}case m.OP_STR_LIKE:{const A=n[e.pc],f=n[e.pc+1],g=s.getUint16(e.pc+2,!0);if(e.pc+=4,g>i)return e.status=O.INVALID_BYTECODE,O.INVALID_BYTECODE;const d=e.registers[A],I=e.registers[f];if(d===null||I===null)break;Xe(String(d),String(I))&&(e.pc=g);break}case m.OP_STR_NOT_LIKE:{const A=n[e.pc],f=n[e.pc+1],g=s.getUint16(e.pc+2,!0);if(e.pc+=4,g>i)return e.status=O.INVALID_BYTECODE,O.INVALID_BYTECODE;const d=e.registers[A],I=e.registers[f];if(d===null||I===null)break;Xe(String(d),String(I))||(e.pc=g);break}case m.OP_STR_CONTAINS:{const A=n[e.pc],f=n[e.pc+1],g=s.getUint16(e.pc+2,!0);if(e.pc+=4,g>i)return e.status=O.INVALID_BYTECODE,O.INVALID_BYTECODE;const d=e.registers[A],I=e.registers[f];if(d===null||I===null)break;String(d).includes(String(I))&&(e.pc=g);break}case m.OP_STR_STARTS_WITH:{const A=n[e.pc],f=n[e.pc+1],g=s.getUint16(e.pc+2,!0);if(e.pc+=4,g>i)return e.status=O.INVALID_BYTECODE,O.INVALID_BYTECODE;const d=e.registers[A],I=e.registers[f];if(d===null||I===null)break;String(d).startsWith(String(I))&&(e.pc=g);break}case m.OP_STR_ENDS_WITH:{const A=n[e.pc],f=n[e.pc+1],g=s.getUint16(e.pc+2,!0);if(e.pc+=4,g>i)return e.status=O.INVALID_BYTECODE,O.INVALID_BYTECODE;const d=e.registers[A],I=e.registers[f];if(d===null||I===null)break;String(d).endsWith(String(I))&&(e.pc=g);break}case m.OP_IN:{const A=n[e.pc],f=s.getUint16(e.pc+1,!0),g=s.getUint16(e.pc+3,!0);if(e.pc+=5,g>i)return e.status=O.INVALID_BYTECODE,O.INVALID_BYTECODE;const d=e.registers[A];if(d==null)break;const I=(c=e.inSets)==null?void 0:c[f];I&&(I.has(d)||typeof d=="number"&&Number.isSafeInteger(d)&&I.has(BigInt(d))||typeof d=="bigint"&&I.has(Number(d)))&&(e.pc=g);break}case m.OP_LOAD_INT:{const A=n[e.pc],f=s.getInt32(e.pc+1,!0);e.pc+=5,e.registers[A]=f;break}case m.OP_LOAD_FLOAT:{const A=n[e.pc],f=s.getFloat64(e.pc+1,!0);e.pc+=9,e.registers[A]=f;break}case m.OP_LOAD_TEXT:{const A=n[e.pc],f=s.getUint16(e.pc+1,!0),g=new Uint8Array(n.buffer,n.byteOffset+e.pc+3,f);e.registers[A]=mo.decode(g),e.pc+=3+f;break}case m.OP_LOAD_BLOB:{const A=n[e.pc],f=s.getUint16(e.pc+1,!0),g=new Uint8Array(f);g.set(new Uint8Array(n.buffer,n.byteOffset+e.pc+3,f)),e.registers[A]=g,e.pc+=3+f;break}case m.OP_LOAD_NULL:{const A=n[e.pc];e.pc+=1,e.registers[A]=null;break}case m.OP_EMIT_ROW:{const A=n[e.pc];e.pc+=1;const f=Ct(e,A),g=t.getUint16(f.rowOffset+1,!0),d=new Uint8Array(t.buffer,t.byteOffset+f.rowOffset,g),I=Qi(e,t,d,u);if(I!==O.RUNNING)return I;break}case m.OP_OFFSET:{const A=n[e.pc],f=s.getUint16(e.pc+1,!0);if(e.pc+=3,f>i)return e.status=O.INVALID_BYTECODE,O.INVALID_BYTECODE;const g=Number(e.registers[A]??0);g>0&&(e.registers[A]=g-1,e.pc=f);break}case m.OP_LIMIT:{const A=n[e.pc],f=s.getUint16(e.pc+1,!0);if(e.pc+=3,f>i)return e.status=O.INVALID_BYTECODE,O.INVALID_BYTECODE;const g=Number(e.registers[A]??0);g<=1?(e.registers[A]=0,e.pc=f):e.registers[A]=g-1;break}case m.OP_CALL_UDF:{const A=s.getUint16(e.pc,!0),f=n[e.pc+2],g=n[e.pc+3],d=n[e.pc+4];e.pc+=5;const I=(l=e.udfs)==null?void 0:l[A];if(!I)return e.status=O.INVALID_BYTECODE,O.INVALID_BYTECODE;const p=[];for(let y=0;y<g;y++)p.push(e.registers[f+y]);try{const y=I(...p);e.registers[d]=y!==void 0?y:null}catch{return e.status=O.ERROR,O.ERROR}break}case m.OP_STR_LOWER:{const A=n[e.pc],f=n[e.pc+1];e.pc+=2;const g=e.registers[A];e.registers[f]=g!==null?String(g).toLowerCase():null;break}case m.OP_STR_UPPER:{const A=n[e.pc],f=n[e.pc+1];e.pc+=2;const g=e.registers[A];e.registers[f]=g!==null?String(g).toUpperCase():null;break}case m.OP_STR_LENGTH:{const A=n[e.pc],f=n[e.pc+1];e.pc+=2;const g=e.registers[A];e.registers[f]=g!==null?String(g).length:null;break}case m.OP_STR_SUBSTR:{const A=n[e.pc],f=n[e.pc+1],g=n[e.pc+2],d=n[e.pc+3];e.pc+=4;const I=e.registers[A],p=e.registers[f],y=e.registers[g];if(I===null||p===null){e.registers[d]=null;break}const T=String(I),N=Math.max(0,Number(p)-1);if(y===null)e.registers[d]=T.slice(N);else{const B=Math.max(0,Number(y));e.registers[d]=T.slice(N,N+B)}break}case m.OP_STR_TRIM:{const A=n[e.pc],f=n[e.pc+1];e.pc+=2;const g=e.registers[A];e.registers[f]=g!=null?String(g).trim():null;break}case m.OP_MATH_ABS:{const A=n[e.pc],f=n[e.pc+1];e.pc+=2;const g=e.registers[A];e.registers[f]=g!=null?Math.abs(Number(g)):null;break}case m.OP_MATH_ROUND:{const A=n[e.pc],f=n[e.pc+1];e.pc+=2;const g=e.registers[A];e.registers[f]=g!=null?Math.round(Number(g)):null;break}case m.OP_RESULT_ROW:{const A=n[e.pc],f=n[e.pc+1];e.pc+=2;const g=Hl(e,A,f),d=Qi(e,t,g,u);if(d!==O.RUNNING)return d;break}case m.OP_SORTER_OPEN:{const A=n[e.pc],f=n[e.pc+1];e.pc+=2;const g=e.keyInfos[f]??{numKeys:1,directions:[0],nullOrders:[0]},d=g.limit!==void 0&&g.limit>0?(g.offset??0)+g.limit:0,I=d>0&&d<=Or?d:0;e.sorters[A]={keyInfo:g,entries:[],readIdx:0,isSorted:!1,maxK:I};break}case m.OP_SORTER_INSERT:{const A=n[e.pc],f=n[e.pc+1],g=n[e.pc+2],d=n[e.pc+3];e.pc+=4;const I=e.sorters[A];if(!I)return e.status=O.INVALID_BYTECODE,O.INVALID_BYTECODE;const p=I.maxK??0;if(p>0&&I.entries.length>=p){if(g===1){const P=e.registers[f],F=I.entries[0].keys[0],w=I.keyInfo.directions[0]??0;if(typeof P=="number"&&typeof F=="number"){if(w===0?P>=F:P<=F)break}else if(typeof P=="string"&&typeof F=="string"){if(w===0?P>=F:P<=F)break}else if(Ao(e.registers,f,I.entries[0].keys,I.keyInfo)>=0)break}else if(Ao(e.registers,f,I.entries[0].keys,I.keyInfo)>=0)break}const y=Ct(e,d),T=t.getUint16(y.rowOffset+1,!0),N=new Array(g);for(let P=0;P<g;P++)N[P]=e.registers[f+P];const B=Wl(e,I,N,y.rowOffset,T,t,p);if(B!==O.RUNNING)return B;break}case m.OP_SORTER_SORT:{const A=n[e.pc];e.pc+=1;const f=e.sorters[A];if(!f)return e.status=O.INVALID_BYTECODE,O.INVALID_BYTECODE;ql(f),f.isSorted=!0;break}case m.OP_SORTER_NEXT:{const A=n[e.pc],f=s.getUint16(e.pc+1,!0);if(e.pc+=3,f>i)return e.status=O.INVALID_BYTECODE,O.INVALID_BYTECODE;const g=e.sorters[A];if(!g)return e.status=O.INVALID_BYTECODE,O.INVALID_BYTECODE;const d=g.keyInfo.limit!==void 0?(g.keyInfo.offset??0)+g.keyInfo.limit:g.entries.length;if(g.readIdx>=Math.min(g.entries.length,d))break;const I=g.entries[g.readIdx],p=I.rowData??new Uint8Array(t.buffer,t.byteOffset+I.rowOffset,I.rowLen),y=Qi(e,t,p,u);if(y!==O.RUNNING)return y;g.readIdx++,e.pc=f;break}case m.OP_MATH_FLOOR:{const A=n[e.pc],f=n[e.pc+1];e.pc+=2;const g=e.registers[A];e.registers[f]=g!=null?Math.floor(Number(g)):null;break}case m.OP_MATH_CEIL:{const A=n[e.pc],f=n[e.pc+1];e.pc+=2;const g=e.registers[A];e.registers[f]=g!=null?Math.ceil(Number(g)):null;break}case m.OP_ADD:{const A=n[e.pc],f=n[e.pc+1],g=n[e.pc+2];e.pc+=3;const d=e.registers[A],I=e.registers[f];d==null||I===null||I===void 0?e.registers[g]=null:e.registers[g]=Number(d)+Number(I);break}case m.OP_SUB:{const A=n[e.pc],f=n[e.pc+1],g=n[e.pc+2];e.pc+=3;const d=e.registers[A],I=e.registers[f];d==null||I===null||I===void 0?e.registers[g]=null:e.registers[g]=Number(d)-Number(I);break}case m.OP_MUL:{const A=n[e.pc],f=n[e.pc+1],g=n[e.pc+2];e.pc+=3;const d=e.registers[A],I=e.registers[f];d==null||I===null||I===void 0?e.registers[g]=null:e.registers[g]=Number(d)*Number(I);break}case m.OP_DIV:{const A=n[e.pc],f=n[e.pc+1],g=n[e.pc+2];e.pc+=3;const d=e.registers[A],I=e.registers[f];if(d==null||I===null||I===void 0)e.registers[g]=null;else{const p=Number(I);e.registers[g]=p===0?null:Number(d)/p}break}case m.OP_MOD:{const A=n[e.pc],f=n[e.pc+1],g=n[e.pc+2];e.pc+=3;const d=e.registers[A],I=e.registers[f];if(d==null||I===null||I===void 0)e.registers[g]=null;else{const p=Number(I);e.registers[g]=p===0?null:Number(d)%p}break}case m.OP_STR_CONCAT:{const A=n[e.pc],f=n[e.pc+1],g=n[e.pc+2];e.pc+=3;let d="",I=!1;for(let p=0;p<f;p++){const y=e.registers[A+p];y!=null&&(I=!0,d+=String(y))}e.registers[g]=I?d:null;break}case m.OP_COALESCE:{const A=n[e.pc],f=n[e.pc+1],g=n[e.pc+2];e.pc+=3;let d=null;for(let I=0;I<f;I++){const p=e.registers[A+I];if(p!=null){d=p;break}}e.registers[g]=d;break}case m.OP_COPY:{const A=n[e.pc],f=n[e.pc+1];e.pc+=2,e.registers[f]=e.registers[A];break}case m.OP_AGG_INIT:{const A=n[e.pc],f=n[e.pc+1],g=n[e.pc+2],d=n[e.pc+3];if(e.pc+=4,d===0){if(e.arenaOffset+40960>e.maxQueryMemory)return e.status=O.ARENA_EXHAUSTED,O.ARENA_EXHAUSTED;e.arenaOffset+=40960;const y=ho(1024);if(g===0){const T=ws([]),N=T%1024;y[N].hash=T,y[N].keys=[],y[N].count=0,y[N].sum=0,y[N].min_val=1/0,y[N].max_val=-1/0,y[N].has_val=!1}e.aggregators[A]={mode:0,startKeyReg:f,numKeys:g,capacity:1024,occupiedCount:g===0?1:0,readIdx:0,buckets:y}}else e.aggregators[A]={mode:1,startKeyReg:f,numKeys:g,capacity:1,occupiedCount:0,readIdx:0,buckets:[]};break}case m.OP_AGG_STEP:{const A=n[e.pc],f=n[e.pc+1],g=n[e.pc+2],d=n[e.pc+3],I=n[e.pc+4];e.pc+=5;const p=e.aggregators[A];if(!p)return e.status=O.INVALID_BYTECODE,O.INVALID_BYTECODE;const y=[];for(let N=0;N<g;N++)y.push(e.registers[f+N]);const T=d===255?null:e.registers[d];if(p.mode===0){const N=ws(y),B=N%p.capacity;let P=null;for(let F=0;F<p.capacity;F++){const w=(B+F)%p.capacity,S=p.buckets[w];if(S.hash===0){S.hash=N,S.keys=y.slice(),S.count=0,S.sum=0,S.min_val=1/0,S.max_val=-1/0,S.has_val=!1,p.occupiedCount++,P=S;break}else if(S.hash===N&&Gl(S.keys,y)){P=S;break}}if(!P)return e.status=O.ARENA_EXHAUSTED,O.ARENA_EXHAUSTED;if(I===0)(d===255||T!=null)&&P.count++;else if(I===1||I===2)T!=null&&(P.sum+=Number(T),P.has_val=!0);else if(I===3){if(T!=null){const F=Number(T);(!P.has_val||F<P.min_val)&&(P.min_val=F),P.has_val=!0}}else if(I===4&&T!=null){const F=Number(T);(!P.has_val||F>P.max_val)&&(P.max_val=F),P.has_val=!0}if(p.occupiedCount>.7*p.capacity){const w=p.capacity*2,S=w*40;if(e.arenaOffset+S>e.maxQueryMemory)return e.status=O.ARENA_EXHAUSTED,O.ARENA_EXHAUSTED;e.arenaOffset+=S;const v=p.buckets,L=ho(w);for(let h=0;h<v.length;h++){const b=v[h];if(b.hash!==0){const k=b.hash%w;for(let $=0;$<w;$++){const j=(k+$)%w;if(L[j].hash===0){L[j]=b;break}}}}p.capacity=w,p.buckets=L}}break}case m.OP_AGG_NEXT:{const A=n[e.pc],f=n[e.pc+1],g=n[e.pc+2],d=s.getUint16(e.pc+3,!0);if(e.pc+=5,d>i)return e.status=O.INVALID_BYTECODE,O.INVALID_BYTECODE;const I=e.aggregators[A];if(!I)return e.status=O.INVALID_BYTECODE,O.INVALID_BYTECODE;for(;I.readIdx<I.buckets.length&&I.buckets[I.readIdx].hash===0;)I.readIdx++;if(I.readIdx>=I.buckets.length)break;const p=I.buckets[I.readIdx++];for(let y=0;y<p.keys.length;y++)e.registers[f+y]=p.keys[y];e.registers[g]=p.sum,e.registers[g+1]=p.count,e.registers[g+2]=p.has_val?p.min_val:null,e.registers[g+3]=p.has_val?p.max_val:null,e.pc=d;break}case m.OP_AGG_FINAL:{const A=n[e.pc],f=n[e.pc+1],g=n[e.pc+2],d=n[e.pc+3];e.pc+=4;const I=e.registers[A],p=Number(e.registers[f]??0);d===0?e.registers[g]=p:d===1?e.registers[g]=p>0?Number(I):null:d===2?e.registers[g]=p>0?Number(I)/p:null:(d===3||d===4)&&(e.registers[g]=e.registers[A]);break}case m.OP_REG_IS_NULL:{const A=n[e.pc],f=s.getUint16(e.pc+1,!0);if(e.pc+=3,f>i)return e.status=O.INVALID_BYTECODE,O.INVALID_BYTECODE;const g=e.registers[A];g==null&&(e.pc=f);break}case m.OP_REG_IS_NOT_NULL:{const A=n[e.pc],f=s.getUint16(e.pc+1,!0);if(e.pc+=3,f>i)return e.status=O.INVALID_BYTECODE,O.INVALID_BYTECODE;const g=e.registers[A];g!=null&&(e.pc=f);break}default:return e.status=O.INVALID_BYTECODE,O.INVALID_BYTECODE}}return e.status=O.DONE,O.DONE}const Vl=new TextDecoder,Eo=new Uint8Array([87,69,66,68,66,0]),Io=new Uint32Array(256);let po=0;function $l(){if(!po){for(let e=0;e<256;e++){let t=e;for(let n=0;n<8;n++)t=t&1?3988292384^t>>>1:t>>>1;Io[e]=t>>>0}po=1}}function vi(e,t=0){$l();let n=4294967295;for(let s=0;s<4096;s++){const i=s>=28&&s<=31?0:e.getUint8(t+s);n=Io[(n^i)&255]^n>>>8}return(n^4294967295)>>>0}function yo(e,t=0){ie(e,t,0,4096),e.setUint8(t+Ee+0,87),e.setUint8(t+Ee+1,69),e.setUint8(t+Ee+2,66),e.setUint8(t+Ee+3,68),e.setUint8(t+Ee+4,66),e.setUint8(t+Ee+5,0),e.setUint16(t+Hs,4096,!0),e.setUint16(t+Vs,zn,!0),e.setUint16(t+$s,Sr,!0),e.setUint32(t+se,1,!0),e.setUint32(t+le,0,!0),e.setUint32(t+Ie,1,!0),e.setUint32(t+pe,0,!0),e.setUint32(t+ye,0,!0),e.setUint32(t+ur,0,!0),e.setUint32(t+fr,0,!0);const n=vi(e,t);e.setUint32(t+ye,n,!0)}function qn(e,t=!1){for(let u=0;u<Eo.length;u++)if(e.getUint8(Ee+u)!==Eo[u])throw new Rn("Invalid database file: magic bytes mismatch");const n=e.getUint16(Hs,!0),s=e.getUint16(Vs,!0),i=e.getUint16($s,!0),r=e.getUint32(se,!0),o=e.getUint32(le,!0),a=e.getUint32(Ie,!0),c=e.getUint32(pe,!0),l=e.getUint32(ye,!0);if(i>zn)throw new Dr(`Database file format requires engine version >= ${i}, but running engine is version ${zn}`);if(t&&l!==0){const u=vi(e,0);if(u!==l)throw new Se(1,l,u)}return{pageSize:n,fileFormatVersion:s,minReadVersion:i,totalPages:r,freePageHead:o,schemaVersion:a,changeCounter:c,storedChecksum:l}}function To(e,t=0){return e.getUint32(t+se,!0)}function xl(e,t,n){n===void 0&&(n=t,t=0),e.setUint32(t+se,n,!0)}function Xl(e,t=0){return e.getUint32(t+le,!0)}function Yl(e,t,n){n===void 0&&(n=t,t=0),e.setUint32(t+le,n,!0)}function Co(e,t=0){return e.getUint32(t+Ie,!0)}function Ze(e,t=0){const n=Co(e,t)+1;return e.setUint32(t+Ie,n,!0),n}function wo(e,t=0){return e.getUint32(t+pe,!0)}function re(e,t=0){const n=wo(e,t)+1;return e.setUint32(t+pe,n,!0),n}function $t(e,t=0){e.setUint32(t+ye,0,!0);const n=vi(e,t);return e.setUint32(t+ye,n,!0),n}function Ss(e,t,n,s){let i=0;for(;i<s&&i<cs(n);i++)e.setUint8(t+i,n.charCodeAt(i));for(;i<s;i++)e.setUint8(t+i,0)}function Us(e,t,n){const s=[];for(let i=0;i<n;i++){const r=e.getUint8(t+i);if(r===0)break;s.push(r)}return Vl.decode(new Uint8Array(s))}function So(e){switch(e.toUpperCase()){case"INT32":return C.INT32;case"INT64":return C.INT64;case"FLOAT64":return C.FLOAT64;case"TEXT":return C.TEXT;case"BLOB":return C.BLOB;case"UUID":return C.UUID;case"ULID":return C.ULID;default:throw new Error(`Unsupported column data type: "${e}"`)}}function Jt(e,t){const n=Sn+t*Fe,s=e.getUint16(n+0,!0);if(s===0)return null;const i=e.getUint16(n+2,!0),r=e.getUint32(n+4,!0),o=e.getUint32(n+8,!0),a=Us(e,n+12,ne),c=e.getUint32(n+76,!0),l=e.getUint32(n+80,!0),u=e.getBigUint64(n+84,!0);return{tableId:s,columnCount:i,rootPageId:r,colCatalogPageId:o,name:a,flags:c,rowCountEstimate:l,autoIncNext:u}}function An(e,t,n){const s=Sn+t*Fe;e.setUint16(s+0,n.tableId,!0),e.setUint16(s+2,n.columnCount,!0),e.setUint32(s+4,n.rootPageId,!0),e.setUint32(s+8,n.colCatalogPageId,!0),Ss(e,s+12,n.name,ne),e.setUint32(s+76,n.flags,!0),e.setUint32(s+80,n.rowCountEstimate,!0),e.setBigUint64(s+84,n.autoIncNext,!0),new Uint8Array(e.buffer,e.byteOffset).fill(0,s+92,s+Fe)}function Zl(e,t){const n=xt(e,t);return n!==-1?Jt(e,n):null}function xt(e,t){for(let n=0;n<ce;n++){const s=Jt(e,n);if(s&&s.flags&bn.ACTIVE&&s.name===t)return n}return-1}function ki(e,t=0){for(let n=0;n<ce;n++){const s=t+Sn+n*Fe;if(e.getUint16(s,!0)===0)return n}return-1}function hn(e){const t=[];for(let n=0;n<ce;n++){const s=Jt(e,n);s&&s.flags&bn.ACTIVE&&t.push(s)}return t}function gn(e,t){const n=Un+t*De,s=e.getUint16(n+0,!0);if(s===0)return null;const i=e.getUint16(n+2,!0),r=e.getUint32(n+4,!0),o=e.getUint8(n+8),a=e.getUint8(n+9),c=[];for(let _=0;_<8;_++)c.push(e.getUint16(n+10+_*2,!0));const l=[];for(let _=0;_<8;_++)l.push(e.getUint8(n+26+_));const u=Us(e,n+34,ne);return{indexId:s,tableId:i,rootPageId:r,columnCount:o,flags:a,columnIndices:c,colDirections:l,name:u}}function Os(e,t,n){const s=Un+t*De;e.setUint16(s+0,n.indexId,!0),e.setUint16(s+2,n.tableId,!0),e.setUint32(s+4,n.rootPageId,!0),e.setUint8(s+8,n.columnCount),e.setUint8(s+9,n.flags);for(let r=0;r<8;r++)e.setUint16(s+10+r*2,n.columnIndices[r]??0,!0);for(let r=0;r<8;r++)e.setUint8(s+26+r,n.colDirections[r]??0);Ss(e,s+34,n.name,ne),new Uint8Array(e.buffer,e.byteOffset).fill(0,s+98,s+De)}const Ps=8;function Ns(e,t=0){for(let n=0;n<Ps;n++){const s=t+Un+n*De;if(e.getUint16(s+0,!0)===0)return n}return-1}function bs(e,t){const n=t.toLowerCase();for(let s=0;s<Ps;s++){const i=gn(e,s);if(i&&i.name.toLowerCase()===n)return{slotIdx:s,desc:i}}return null}function Ae(e,t){const n=[];for(let s=0;s<Ps;s++){const i=gn(e,s);i&&i.tableId===t&&n.push(i)}return n}function Mi(e,t,n){if(n===void 0&&(n=t,t=0),n>=Ps)return-1;const s=t+Un+n*De;return ie(e,s,0,De),0}function Uo(e,t,n){if(n===void 0&&(n=t,t=0),n>=ce)return-1;const s=t+Sn+n*Fe;return ie(e,s,0,Fe),0}function Oo(e,t,n,s,i=0){ie(e,t,0,4096),e.setUint8(t+0,Nn),e.setUint8(t+1,0),e.setUint16(t+2,0,!0),e.setUint16(t+4,n,!0),e.setUint16(t+6,s,!0),e.setUint32(t+8,i,!0),e.setUint32(t+12,0,!0)}function he(e,t){return{pageType:e.getUint8(t+0),flags:e.getUint8(t+1),colCountInPage:e.getUint16(t+2,!0),tableId:e.getUint16(t+4,!0),startColIndex:e.getUint16(t+6,!0),nextColCatalogPageId:e.getUint32(t+8,!0),pageChecksum:e.getUint32(t+12,!0)}}function jl(e,t,n,s,i,r){e.setUint8(t+0,Nn),e.setUint8(t+1,0),e.setUint16(t+2,n,!0),e.setUint16(t+4,s,!0),e.setUint16(t+6,i,!0),e.setUint32(t+8,r,!0)}function Gi(e,t,n,s){if(n<0||n>=Te)throw new Error(`Invalid catalog in-page slot ${n}`);const i=t+xs+n*Xs;e.setUint8(i+0,s.type),e.setUint8(i+1,s.flags),e.setUint16(i+2,s.colOffset,!0),Ss(e,i+4,s.name,ne),e.setUint32(i+68,0,!0)}function Po(e,t,n){const s=t+xs+n*Xs,i=e.getUint8(s+0),r=e.getUint8(s+1),o=e.getUint16(s+2,!0),a=Us(e,s+4,ne);return{type:i,flags:r,colOffset:o,name:a}}function No(e){return{pageChainIdx:Math.floor(e/Te),colIdxInPage:e%Te}}function bo(e,t,n,s){var T,N,B,P,F;if(s.length===0)throw new Error("Table must have at least one column");if(s.length>ue)throw new Ln(s.length,ue);if(xt(e,n)!==-1)throw new is(n);const i=ki(e);if(i===-1)throw new gi(ce,ce);const r=i+1,o=t.allocateNewPage(),a=t.getPageBytes(o),c=new DataView(a.buffer,a.byteOffset);c.setUint8(0,13),c.setUint8(1,0),c.setUint16(2,0,!0),c.setUint16(4,4096,!0),c.setUint32(6,0,!0),c.setUint16(10,0,!0),c.setUint32(12,0,!0),t.markPageDirty(o);const l=[];let u=0;for(let w=0;w<s.length;w++){const S=s[w],v=typeof S.type=="string"?So(S.type):S.type;let L=0;typeof S.flags=="number"?L=S.flags:((S.primaryKey||(T=S.flags)!=null&&T.primaryKey)&&(L|=tt.PRIMARY_KEY),(S.notNull||(N=S.flags)!=null&&N.notNull)&&(L|=tt.NOT_NULL),(S.indexed||(B=S.flags)!=null&&B.indexed)&&(L|=tt.INDEXED),(S.autoInc||S.autoIncrement||(P=S.flags)!=null&&P.autoInc||(F=S.flags)!=null&&F.autoIncrement)&&(L|=tt.AUTO_INC));const h=u;switch(v){case C.INT32:u+=4;break;case C.INT64:case C.FLOAT64:u+=8;break;case C.UUID:case C.ULID:u+=16;break}l.push({type:v,flags:L,colOffset:h,name:S.name})}const _=l.length,A=Math.ceil(_/Te),f=[];for(let w=0;w<A;w++)f.push(t.allocateNewPage());for(let w=0;w<A;w++){const S=f[w],v=w<A-1?f[w+1]:0,L=w*Te,h=Math.min(_-L,Te),b=t.getPageBytes(S),k=new DataView(b.buffer,b.byteOffset);Oo(k,0,r,L,v),k.setUint16(2,h,!0);for(let j=0;j<h;j++){const J=l[L+j];Gi(k,0,j,J)}const $=Ge(b);k.setUint32(12,$,!0),t.markPageDirty(S)}const g=f[0],d={tableId:r,columnCount:_,rootPageId:o,colCatalogPageId:g,name:n,flags:bn.ACTIVE,rowCountEstimate:0,autoIncNext:1n};An(e,i,d);const I=[];for(let w=0;w<l.length;w++)l[w].flags&tt.PRIMARY_KEY&&I.push(l[w]);if(I.length>0){const w=Ns(e);if(w!==-1){const S=t.allocateNewPage(),v=t.getPageBytes(S),L=new DataView(v.buffer,v.byteOffset);ys(L,0,0),t.markPageDirty(S);const h=[0,0,0,0,0,0,0,0],b=[0,0,0,0,0,0,0,0];for(let $=0;$<I.length&&$<8;$++){const j=I[$].name;let J=-1;for(let G=0;G<l.length;G++)if(l[G].name===j){J=G;break}h[$]=J}const k={indexId:w+1,tableId:r,rootPageId:S,columnCount:I.length,flags:It.PRIMARY|It.UNIQUE,columnIndices:h,colDirections:b,name:`pk_${n}`};Os(e,w,k)}}Ze(e),re(e),$t(e);const p=Ae(e,r),y=[];for(let w=0;w<I.length;w++)y.push(I[w].name);return{...d,columns:l,primaryKey:y.length>0?y:void 0,indexes:p.length>0?p:void 0}}function qi(e,t,n){const s=xt(e,n);if(s===-1)throw new Bn(n);const i=Jt(e,s),r=[];let o=i.colCatalogPageId,a=0;for(;o!==0&&a<i.columnCount;){const u=t.getPageBytes(o),_=new DataView(u.buffer,u.byteOffset),A=he(_,0);for(let f=0;f<A.colCountInPage;f++){const g=Po(_,0,f);r.push(g),a++}o=A.nextColCatalogPageId}const c=Ae(e,i.tableId),l=[];for(let u=0;u<r.length;u++)r[u].flags&tt.PRIMARY_KEY&&l.push(r[u].name);return{...i,columns:r,primaryKey:l.length>0?l:void 0,indexes:c.length>0?c:void 0}}function Kl(e,t){const n=hn(e),s=[];for(let i=0;i<n.length;i++)s.push(qi(e,t,n[i].name));return s}const Wi="AGFzbQEAAAABcBFgAX8Bf2ACf38AYAJ/fwF/YAN/f38AYAN/f38Bf2AEf39/fwF/YAAAYAV/f39/fwF/YAN/f34Bf2ACf34Bf2ABfwBgBH9/f38AYAV/f39/fwBgBX9+f35/AGAFf3x/fH8AYAd/f39/f39/AGAAAX8CDwEDZW52Bm1lbW9yeQIAQwNIRwYAAAQAAwQDAgQFBAACAwcFAQECAwEAAQABAAEAAQABAAECAwAAAQABAQgJAQIAAAoAAQAAAAAAAwAAAgILDAACBQ0ODwUQBgkBfwFBgKCLAgsH2A1MD19fc3RhY2tfcG9pbnRlcgMAB2hleF92YWwAARBjcm9ja2ZvcmRfZGVjb2RlAAILdXVpZF9lbmNvZGUAAwZzdHJsZW4ABAt1dWlkX2RlY29kZQAFC3VsaWRfZW5jb2RlAAYLdWxpZF9kZWNvZGUABw9wYWdlX3RhYmxlX2hhc2gACA5wYWdlX3RhYmxlX2dldAAJDnBhZ2VfdGFibGVfc2V0AAoRcGFnZV90YWJsZV9kZWxldGUACxhidWZfcG9vbF9nZXRfc2xvdF9vZmZzZXQADBpidWZfcG9vbF9yZWFkX3Nsb3RfdG9fcGFnZQANG2J1Zl9wb29sX3dyaXRlX3Nsb3RfdG9fcGFnZQAOGmJ1Zl9wb29sX2dldF9yZXNpZGVudF9zbG90AAkUYnVmX3Bvb2xfYXNzaWduX3Nsb3QADxZidWZfcG9vbF91bmFzc2lnbl9zbG90ABATYnVmX3Bvb2xfbWFya19kaXJ0eQARFGJ1Zl9wb29sX2NsZWFyX2RpcnR5ABIRYnVmX3Bvb2xfaXNfZGlydHkAEwlwYWdlX2luaXQAFA5wYWdlX2luaXRfZnJlZQAVDXBhZ2VfZ2V0X3R5cGUAFg1wYWdlX3NldF90eXBlABcTcGFnZV9nZXRfY2VsbF9jb3VudAAYE3BhZ2Vfc2V0X2NlbGxfY291bnQAGRxwYWdlX2dldF9jZWxsX2NvbnRlbnRfb2Zmc2V0ABoccGFnZV9zZXRfY2VsbF9jb250ZW50X29mZnNldAAbFXBhZ2VfZ2V0X25leHRfcGFnZV9pZAAcFXBhZ2Vfc2V0X25leHRfcGFnZV9pZAAdE3BhZ2VfZ2V0X2ZyZWVfYnl0ZXMAHhNwYWdlX3NldF9mcmVlX2J5dGVzAB8RcGFnZV9nZXRfY2hlY2tzdW0AIBFwYWdlX3NldF9jaGVja3N1bQAhFHBhZ2VfZ2V0X2NlbGxfb2Zmc2V0ACIUcGFnZV9zZXRfY2VsbF9vZmZzZXQAIx5wYWdlX2dldF9jb250aWd1b3VzX2ZyZWVfc3BhY2UAJBlwYWdlX2dldF90b3RhbF9mcmVlX3NwYWNlACUMcGFnZV9jb21wYWN0ACYTcGFnZV9nZXRfcm93X2xlbmd0aAAnD3BhZ2VfZGVsZXRlX3JvdwAoEnBhZ2VfaW5pdF9pbnRlcmlvcgApHHBhZ2VfZ2V0X3JpZ2h0X2NoaWxkX3BhZ2VfaWQAHBxwYWdlX3NldF9yaWdodF9jaGlsZF9wYWdlX2lkAB0ZcGFnZV9pbnNlcnRfaW50ZXJpb3JfY2VsbAAqG3BhZ2VfYmluYXJ5X3NlYXJjaF9pbnRlcmlvcgArFHBhZ2VfaW5pdF9pbmRleF9sZWFmACwNY29tcHV0ZV9jcmMzMgAtFWNvbXB1dGVfcGFnZV9jaGVja3N1bQAuFmNvbXB1dGVfcGFnZTFfY2hlY2tzdW0ALxJjYXRhbG9nX2luaXRfcGFnZTEAMBdjYXRhbG9nX2dldF90b3RhbF9wYWdlcwAgF2NhdGFsb2dfc2V0X3RvdGFsX3BhZ2VzACEaY2F0YWxvZ19nZXRfZnJlZV9wYWdlX2hlYWQAMRpjYXRhbG9nX3NldF9mcmVlX3BhZ2VfaGVhZAAyGmNhdGFsb2dfZ2V0X3NjaGVtYV92ZXJzaW9uADMgY2F0YWxvZ19pbmNyZW1lbnRfc2NoZW1hX3ZlcnNpb24ANBpjYXRhbG9nX2dldF9jaGFuZ2VfY291bnRlcgA1IGNhdGFsb2dfaW5jcmVtZW50X2NoYW5nZV9jb3VudGVyADYdY2F0YWxvZ191cGRhdGVfcGFnZTFfY2hlY2tzdW0ANxpjYXRhbG9nX3dyaXRlX2ZpeGVkX3N0cmluZwA4HGNhdGFsb2dfZmluZF9mcmVlX3RhYmxlX3Nsb3QAORxjYXRhbG9nX2ZpbmRfZnJlZV9pbmRleF9zbG90ADofY2F0YWxvZ19kZWxldGVfaW5kZXhfZGVzY3JpcHRvcgA7H2NhdGFsb2dfZGVsZXRlX3RhYmxlX2Rlc2NyaXB0b3IAPBFjYXRhbG9nX2luaXRfcGFnZQA9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IAE7AAALCgAgAEEEai8AAAsMACAAQQRqIAE7AAALCgAgAEEGaigAAAsMACAAQQZqIAE2AAALCgAgAEEKai8AAAsMACAAQQpqIAE7AAALCgAgAEEMaigAAAsMACAAQQxqIAE2AAALEAAgACABQQF0akEQai8AAAsSACAAIAFBAXRqQRBqIAI7AAALHgAgAEEEai8AACAAQQJqLwAAQQF0a0EQa0H//wNxCycAIABBCmovAAAgAEEEai8AACAAQQJqLwAAQQF0a2pBEGtB//8DcQuBAgEHfyAAQQJqLwAAIgZFBEAgAEEKakEAOwAAIABBBGpBgCA7AAAPCyABQQAgACABRxtBACABQYBgTxsiAyAAKQAINwAIIAMgACkAADcAACADQRBqIQQgAEEBaiEIIABBEGohBUGAICEBA0AgBS8AACECIAECfyAALQAAQQpGBEAgACACaiIHLwAAQQpqDAELIAAgAmohByACIAhqLwAACyICayEBIAJB//8DcSICBEAgAyABQf//A3FqIAcgAvwKAAALIAQgATsAACAFQQJqIQUgBEECaiEEIAZBAWsiBg0ACyADQQpqQQA7AAAgA0EEaiABOwAAIAAgA0GAIPwKAAALCgAgAEEBai8AAAt0AQN/IABBAmovAAAiAiABSwRAIAAgACABQQF0akEQaiIDLwAAakEBai8AACEEAkAgAkEBayICIAFGDQAgAiABa0EBdCIBRQ0AIAMgA0ECaiAB/AoAAAsgAEECaiACOwAAIABBCmoiACAALwAAIARqOwAACws1ACAAQQU7AAAgAEEMakEANgAAIABBCmpBADsAACAAQQZqIAE2AAAgAEECakGAgICAATYAAAtsAQV/IABBAmoiBS8AACIDQaICTQR/IABBBGoiBi8AAEEMayIEIABqIgcgATYAACAHQQRqIAI3AAAgACADQQF0Qf7/A3FqQRBqIAQ7AAAgBiAEOwAAIAUgA0EBaiIAOwAAIABB//8DcQVBfwsLhwEBBn8CQCAAQQJqLwAAIgIEQCAAQRBqIQcgAkEBayEDQX8hAgNAIAMgBWoiBEEBdiEGAkAgACAHIARB/v8HcWovAABqIgRBBGo1AAAgAVkEQCAGQQFrIQMgBCgAACECDAELIAZBAWohBQsgAyAFTw0ACyACQX9HDQELIABBBmooAAAhAgsgAgs1ACAA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";let Wn=null;function Bo(){if(!Wn){const e=globalThis.Buffer;if(typeof e<"u"&&typeof e.from=="function")Wn=new Uint8Array(e.from(Wi,"base64"));else{const t=atob(Wi),n=t.length;Wn=new Uint8Array(n);for(let s=0;s<n;s++)Wn[s]=t.charCodeAt(s)}}return Wn}function Lo(e,t){const n=t??Bo(),s=new WebAssembly.Module(n),i=new WebAssembly.Instance(s,{env:{memory:e}}),r=i.exports;r.__stack_pointer&&typeof r.__stack_pointer=="object"&&"value"in r.__stack_pointer&&(r.__stack_pointer.value=4378624);const o=(c,l=0)=>c.byteOffset+l;return{instance:i,exports:r,memory:e,page_init:(c,l,u=es,_=0)=>{r.page_init(o(c,l),u,_)},page_init_free:(c,l,u=0)=>{r.page_init_free(o(c,l),u)},page_get_type:(c,l)=>r.page_get_type(o(c,l)),page_set_type:(c,l,u)=>{r.page_set_type(o(c,l),u)},page_get_cell_count:(c,l)=>r.page_get_cell_count(o(c,l)),page_set_cell_count:(c,l,u)=>{r.page_set_cell_count(o(c,l),u)},page_get_cell_content_offset:(c,l)=>r.page_get_cell_content_offset(o(c,l)),page_set_cell_content_offset:(c,l,u)=>{r.page_set_cell_content_offset(o(c,l),u)},page_get_next_page_id:(c,l)=>r.page_get_next_page_id(o(c,l)),page_set_next_page_id:(c,l,u)=>{r.page_set_next_page_id(o(c,l),u)},page_get_free_bytes:(c,l)=>r.page_get_free_bytes(o(c,l)),page_set_free_bytes:(c,l,u)=>{r.page_set_free_bytes(o(c,l),u)},page_get_checksum:(c,l)=>r.page_get_checksum(o(c,l)),page_set_checksum:(c,l,u)=>{r.page_set_checksum(o(c,l),u)},page_get_cell_offset:(c,l,u)=>r.page_get_cell_offset(o(c,l),u),page_set_cell_offset:(c,l,u,_)=>{r.page_set_cell_offset(o(c,l),u,_)},page_get_contiguous_free_space:(c,l)=>r.page_get_contiguous_free_space(o(c,l)),page_get_total_free_space:(c,l)=>r.page_get_total_free_space(o(c,l)),page_compact:(c,l,u=0,_)=>{_?Qn(c,l,u,_):r.page_compact(o(c,l),u,-1,0,0)},page_get_row_length:(c,l)=>r.page_get_row_length(o(c,l)),page_insert_row:(c,l,u,_=0)=>an(c,l,u,_),page_delete_row:(c,l,u)=>{r.page_delete_row(o(c,l),u)},page_update_row:(c,l,u,_,A=0)=>Ui(c,l,u,_,A),page_table_hash:(c,l)=>r.page_table_hash(c,l),page_table_get:(c,l,u,_)=>r.page_table_get(o(c,l),u,_),page_table_set:(c,l,u,_,A)=>{if(r.page_table_set(o(c,l),u,_,A)<0)throw new Error(`BufferPool page table full: cannot insert page ${_}`)},page_table_delete:(c,l,u,_)=>r.page_table_delete(o(c,l),u,_)!==0,buf_pool_get_slot_offset:c=>r.buf_pool_get_slot_offset(c),buf_pool_read_slot_to_page:(c,l,u)=>r.buf_pool_read_slot_to_page(o(c,l),u),buf_pool_write_slot_to_page:(c,l,u,_)=>{r.buf_pool_write_slot_to_page(o(c,l),u,_)},buf_pool_get_resident_slot:(c,l,u,_)=>r.buf_pool_get_resident_slot(o(c,l),u,_),buf_pool_assign_slot:(c,l,u,_,A,f)=>{r.buf_pool_assign_slot(o(c,l),o(c,u),_,A,f)},buf_pool_unassign_slot:(c,l,u,_,A)=>{r.buf_pool_unassign_slot(o(c,l),o(c,u),_,A)},buf_pool_mark_dirty:(c,l,u)=>{r.buf_pool_mark_dirty(o(c,l),u)},buf_pool_clear_dirty:(c,l,u)=>{r.buf_pool_clear_dirty(o(c,l),u)},buf_pool_is_dirty:(c,l,u)=>r.buf_pool_is_dirty(o(c,l),u)!==0,buf_pool_pin_slot:(c,l)=>{Li(c,l)},buf_pool_unpin_slot:(c,l)=>{Ri(c,l)},buf_pool_is_pinned:(c,l)=>cn(c,l),buf_pool_find_victim:(c,l,u,_,A,f)=>Fi(c,l,u,_,A,f),buf_pool_select_eviction_victim:(c,l,u,_,A,f,g,d)=>Di(c,l,u,_,A,f,g,d),catalog_init_page1:c=>{r.catalog_init_page1(o(c))},catalog_read_page1_header:(c,l)=>qn(c,l),catalog_get_total_pages:c=>r.catalog_get_total_pages(o(c)),catalog_set_total_pages:(c,l)=>{r.catalog_set_total_pages(o(c),l)},catalog_get_free_page_head:c=>r.catalog_get_free_page_head(o(c)),catalog_set_free_page_head:(c,l)=>{r.catalog_set_free_page_head(o(c),l)},catalog_get_schema_version:c=>r.catalog_get_schema_version(o(c)),catalog_increment_schema_version:c=>r.catalog_increment_schema_version(o(c)),catalog_get_change_counter:c=>r.catalog_get_change_counter(o(c)),catalog_increment_change_counter:c=>r.catalog_increment_change_counter(o(c)),catalog_update_page1_checksum:c=>r.catalog_update_page1_checksum(o(c)),sql_like_match:(c,l)=>Xe(c,l),fnv1a_32:c=>ws(c),compare_sorter_keys:fn,vm_step:Gn}}function Ro(e=Qe,t=ve){const n=Zs(e,t),s=n.transientArenaOffset+256*1024,i=Math.ceil(s/65536),r=Math.ceil((n.transientArenaOffset+t)/65536);return new WebAssembly.Memory({initial:i,maximum:Math.max(i,r)})}class Fo{constructor(t){U(this,"io");U(this,"wasmMemory");U(this,"buffer");U(this,"view");U(this,"uint8");U(this,"slotCount");U(this,"maxQueryMemory");U(this,"offsets");U(this,"slotsEndOffset");U(this,"slotToPageOffset");U(this,"pageToSlotOffset");U(this,"pageToSlotBuckets");U(this,"dirtyMaskOffset");U(this,"vmContextOffset");U(this,"resultBufferOffset");U(this,"bytecodeOffset");U(this,"pageScratchpadOffset");U(this,"transientArenaOffset");U(this,"pin_counts");U(this,"slot_dirty_generations");U(this,"ref_bits");U(this,"clock_hand",0);U(this,"arena_offset",0);U(this,"in_flight_acquires",new Map);U(this,"allocation_lock",Promise.resolve());var s,i,r;this.slotCount=t.slotCount??((s=t.pool)==null?void 0:s.slotCount)??Qe,this.maxQueryMemory=t.maxQueryMemory??((i=t.pool)==null?void 0:i.maxQueryMemory)??ve;const n=t.memory??((r=t.pool)==null?void 0:r.wasmMemory);if(!n)throw new Error("BufferPoolDriver requires a valid WebAssembly.Memory (or pool with wasmMemory)");if(this.wasmMemory=n,this.buffer=this.wasmMemory.buffer,this.view=new DataView(this.buffer),this.uint8=new Uint8Array(this.buffer),this.offsets=Zs(t.useDefaultLayoutOffsets?Qe:this.slotCount,this.maxQueryMemory),this.slotsEndOffset=this.offsets.slotsEndOffset,this.slotToPageOffset=this.offsets.slotToPageOffset,this.pageToSlotOffset=this.offsets.pageToSlotOffset,this.pageToSlotBuckets=this.offsets.pageToSlotBuckets,this.dirtyMaskOffset=this.offsets.dirtyMaskOffset,this.vmContextOffset=this.offsets.vmContextOffset,this.resultBufferOffset=this.offsets.resultBufferOffset,this.bytecodeOffset=this.offsets.bytecodeOffset,this.pageScratchpadOffset=this.offsets.pageScratchpadOffset,this.transientArenaOffset=this.offsets.transientArenaOffset,this.ref_bits=new Uint8Array(this.slotCount),this.pin_counts=new Uint32Array(this.slotCount),this.slot_dirty_generations=new Uint32Array(this.slotCount),t.io)this.io=t.io;else if(t.vfs)this.io=new Ii({vfs:t.vfs,memory:this.wasmMemory});else throw new Error("BufferPoolDriver requires either an Io instance or IVfsAdapter");ie(this.uint8,this.slotToPageOffset,0,this.slotCount*4),ie(this.uint8,this.pageToSlotOffset,0,this.pageToSlotBuckets*Ce),ie(this.uint8,this.dirtyMaskOffset,0,Math.ceil(this.slotCount/8)),this.assignSlot(0,1),this.pin_counts[0]=1}validate_slot_idx(t){if(!Number.isInteger(t)||t<0||t>=this.slotCount)throw new Error(`Invalid slot index: ${t}. Must be an integer between 0 and ${this.slotCount-1}`)}validate_page_id(t){if(!Number.isInteger(t)||t<=0)throw new Error(`Invalid page ID: ${t}. Page IDs must be positive integers.`)}async with_allocation_lock(t){const n=this.allocation_lock;let s;this.allocation_lock=new Promise(i=>{s=i}),await n;try{return await t()}finally{s()}}setTransactionCoordinator(t){this.io.setTransactionCoordinator(t)}getSlotOffset(t){return this.validate_slot_idx(t),t*4096}getPageBytesInSlot(t){return this.validate_slot_idx(t),this.uint8.subarray(t*4096,(t+1)*4096)}getSlotDataView(t){return this.validate_slot_idx(t),new DataView(this.buffer,t*4096,4096)}getResidentSlot(t){return this.validate_page_id(t),Wt(this.view,this.pageToSlotOffset,this.pageToSlotBuckets,t)}getAssignedPage(t){return this.validate_slot_idx(t),ln(this.view,this.slotToPageOffset,t)}assignSlot(t,n){if(this.validate_slot_idx(t),!Number.isInteger(n)||n<=0)throw new Error(`Invalid page ID: ${n}. Must be a positive integer >= 1`);if(t===0&&n!==1)throw new Error(`Cannot reassign slot 0: reserved permanently for page 1 (got page ${n})`);const s=this.getResidentSlot(n);if(s!==-1&&s!==t)throw new Error(`Cannot map page ${n} to slot ${t}: already resident in slot ${s}`);ao(this.view,this.slotToPageOffset,this.pageToSlotOffset,this.pageToSlotBuckets,t,n),this.ref_bits[t]=1}unassignSlot(t){if(this.validate_slot_idx(t),t===0)throw new Error("Cannot unassign slot 0: reserved permanently for page 1");lo(this.view,this.slotToPageOffset,this.pageToSlotOffset,this.pageToSlotBuckets,t),this.ref_bits[t]=0}markDirty(t){this.validate_slot_idx(t),co(this.uint8,this.dirtyMaskOffset,t),this.slot_dirty_generations[t]++}clearDirty(t){this.validate_slot_idx(t),uo(this.uint8,this.dirtyMaskOffset,t)}isDirty(t){return this.validate_slot_idx(t),Bi(this.uint8,this.dirtyMaskOffset,t)}pinSlot(t){this.validate_slot_idx(t),Li(this.pin_counts,t)}unpinSlot(t){this.validate_slot_idx(t),Ri(this.pin_counts,t)}pinPage(t){this.validate_page_id(t);const n=this.getResidentSlot(t);if(n===-1)throw new Error(`Cannot pin page ${t}: page is not resident in buffer pool`);this.pinSlot(n)}unpinPage(t){if(this.validate_page_id(t),t===1)return;const n=this.getResidentSlot(t);n!==-1&&this.unpinSlot(n)}forceUnpinSlot(t){this.validate_slot_idx(t),t!==0&&(this.pin_counts[t]=0)}forceUnpinPage(t){if(this.validate_page_id(t),t<=1)return;const n=this.getResidentSlot(t);n!==-1&&this.forceUnpinSlot(n)}isSlotPinned(t){return this.validate_slot_idx(t),cn(this.pin_counts,t)}getPinCount(t){return this.validate_slot_idx(t),this.pin_counts[t]}getRefBit(t){return this.validate_slot_idx(t),this.ref_bits[t]}setRefBit(t,n){this.validate_slot_idx(t),this.ref_bits[t]=n?1:0}allocArena(t){const n=t+7&-8;if(this.arena_offset+n>this.maxQueryMemory)throw new _i;const s=this.transientArenaOffset+this.arena_offset;return this.arena_offset+=n,s}resetArena(){this.arena_offset>0&&(ie(this.uint8,this.transientArenaOffset,0,this.arena_offset),this.arena_offset=0)}getArenaOffset(){return this.arena_offset}async acquirePage(t,n=!1){this.validate_page_id(t);const s=this.getResidentSlot(t);if(s!==-1)return this.setRefBit(s,1),n&&this.pinSlot(s),s;const i=this.in_flight_acquires.get(t);if(i){const o=await i;return n&&this.pinSlot(o),o}const r=(async()=>{const{candidate_slot:o,flush_page_id:a,next_clock_hand:c}=Di(this.buffer,this.ref_bits,this.pin_counts,this.slotToPageOffset,this.dirtyMaskOffset,this.slotCount,this.clock_hand,t);this.clock_hand=c,this.pinSlot(o);try{return await this.io.resolvePageFault(o,t,a),this.assignSlot(o,t),this.setRefBit(o,1),this.clearDirty(o),o}catch(l){throw o!==-1&&this.unpinSlot(o),l}})();this.in_flight_acquires.set(t,r);try{const o=await r;return n||this.unpinSlot(o),o}finally{this.in_flight_acquires.delete(t)}}acquireAndPinPage(t){return this.acquirePage(t,!0)}async flushSlot(t){this.validate_slot_idx(t);const n=this.getAssignedPage(t);if(n===0)return;if(t===0&&n!==1)throw new Error(`Corruption detected: slot 0 is assigned to page ${n} instead of page 1`);const s=this.slot_dirty_generations[t];await this.io.writeSlot(t,n),this.slot_dirty_generations[t]===s&&this.clearDirty(t)}async flushPage(t){this.validate_page_id(t);const n=this.getResidentSlot(t);n!==-1&&this.isDirty(n)&&await this.flushSlot(n)}async flushAllDirty(){for(let t=0;t<this.slotCount;t++)this.isDirty(t)&&await this.flushSlot(t);await this.io.flush()}async allocatePage(t=!1){return this.with_allocation_lock(async()=>{const n=this.getSlotDataView(0),s=yt(n,le),i=yt(n,se);if(s>0){if(s<=1||i>0&&s>i)throw new Se(s,`Corrupted free_page_head pointer ${s} (totalPages: ${i})`);const c=await this.acquirePage(s,t),l=this.getSlotDataView(c),u=Vr(l,rr);if(u!==Me)throw new Se(s,`Expected free page type 0x00, got 0x${u.toString(16)}`);const _=yt(l,or);if(_===s||i>0&&_>i)throw new Se(s,`Corrupted next_free_page_id pointer ${_} in free page ${s}`);return Tt(n,le,_),this.markDirty(0),Dn(l,0),this.markDirty(c),s}const r=i+1;Tt(n,se,r),this.markDirty(0);const o=await this.acquirePage(r,t),a=this.getSlotDataView(o);return Dn(a,0),this.markDirty(o),r})}allocateAndPinPage(){return this.allocatePage(!0)}async freePage(t,n=!1){if(this.validate_page_id(t),t<=1)throw new Error(`Cannot free reserved database page ${t}`);return this.with_allocation_lock(async()=>{const s=this.getSlotDataView(0),i=yt(s,se);if(i>0&&t>i)throw new Error(`Cannot free page ${t} beyond total pages ${i}`);const r=this.getResidentSlot(t);if(r!==-1){if(n)this.forceUnpinSlot(r);else if(this.isSlotPinned(r))throw new Error(`Cannot free pinned/active database page ${t}`)}const o=await this.acquirePage(t,!0);try{const a=this.getSlotDataView(o),c=qe(a,0);if(c===Me){if(this.unassignSlot(o),n)return;throw new Error(`Double-free detected: page ${t} is already marked free`)}if(!n&&c===Nn)throw new Error(`Cannot free system catalog page ${t}`);const l=yt(s,le);Kr(a,0,l),ie(this.uint8,o*4096+Kt,0,4096-Kt),this.io.isInTransaction()?await this.io.spillOrWriteSlot(o,t):await this.flushSlot(o),this.unassignSlot(o),this.clearDirty(o),this.setRefBit(o,0),Tt(s,le,t),this.markDirty(0)}finally{this.unpinSlot(o)}})}async stepVm(t,n){let s=Gn(t,this.view,n);for(;s===O.PAGE_FAULT;){const i=t.cursor.pageId;await this.acquirePage(i),t.status=O.RUNNING,s=Gn(t,this.view,n)}return s}}async function Hi(e){var u;const t=await e.getWalFrameCount();if(t===0)return{frameCount:0,committedTxCount:0,abortedTxCount:0,replayedPageCount:0};const n=await e.readWalHeader();if(!n)return await e.truncateWal(0),{frameCount:0,committedTxCount:0,abortedTxCount:0,replayedPageCount:0};try{hs(n,!0)}catch{return await e.truncateWal(0),{frameCount:0,committedTxCount:0,abortedTxCount:0,replayedPageCount:0}}const s=await e.readWalFrames(0,t),i=new Map,r=new Set;let o=0;for(const _ of s){const A=Ti(_);if(!A.valid||!A.header)break;const{header:f}=A;if(f.frameSeq!==o+1)break;if(o++,i.has(f.txId)||i.set(f.txId,[]),f.frameType===jn)r.add(f.txId);else if(f.frameType===Zn||f.frameType===Kn){const g=new Uint8Array(_.buffer,_.byteOffset+ke,4096),d=new Uint8Array(4096);d.set(g),i.get(f.txId).push({pageId:f.pageId,data:d,frameType:f.frameType})}}const a=new Map;let c=0,l=0;for(const[_,A]of i.entries())if(r.has(_)){c++;for(const f of A)f.pageId>0&&a.set(f.pageId,f.data)}else l++;if(a.size>0){const _=[];for(const[A,f]of a.entries())_.push({pageId:A,data:f});_.sort((A,f)=>A.pageId-f.pageId),await e.writePages(_)}return await((u=e.flush)==null?void 0:u.call(e)),await e.truncateWal(0),{frameCount:o,committedTxCount:c,abortedTxCount:l,replayedPageCount:a.size}}class Do{constructor(t,n){U(this,"activeLease",null);U(this,"inFlightNonTxCount",0);U(this,"queue",[]);U(this,"leaseWaiters",[]);U(this,"nextLeaseId",1);U(this,"nextTxId",1);U(this,"crossTabLockName");U(this,"onSyncCrossTab");U(this,"releaseWebLock",null);this.crossTabLockName=t,this.onSyncCrossTab=n}hasWebLocks(){var t;return!!this.crossTabLockName&&typeof navigator<"u"&&typeof((t=navigator==null?void 0:navigator.locks)==null?void 0:t.request)=="function"}async acquireWebLock(){!this.hasWebLocks()||this.releaseWebLock||await new Promise(t=>{navigator.locks.request(this.crossTabLockName,{mode:"exclusive"},()=>new Promise(n=>{this.releaseWebLock=n,t()})).catch(()=>{t()})})}releaseCurrentWebLock(){if(this.releaseWebLock){const t=this.releaseWebLock;this.releaseWebLock=null,t()}}get isLeased(){return this.activeLease!==null}get currentLease(){return this.activeLease}async enqueue(t,n){if(this.activeLease&&n===this.activeLease.leaseId)return t();if(this.activeLease||this.leaseWaiters.length>0||this.hasWebLocks()&&this.inFlightNonTxCount>0)return new Promise((s,i)=>{this.queue.push(async()=>{this.inFlightNonTxCount++;try{this.hasWebLocks()&&this.inFlightNonTxCount===1&&(await this.acquireWebLock(),this.onSyncCrossTab&&await this.onSyncCrossTab());const r=await t();s(r)}catch(r){i(r)}finally{this.inFlightNonTxCount--,this.inFlightNonTxCount===0&&!this.activeLease&&this.releaseCurrentWebLock(),this.drain()}})});this.inFlightNonTxCount++;try{return this.hasWebLocks()&&this.inFlightNonTxCount===1&&(await this.acquireWebLock(),this.onSyncCrossTab&&await this.onSyncCrossTab()),await t()}finally{this.inFlightNonTxCount--,this.inFlightNonTxCount===0&&!this.activeLease&&this.releaseCurrentWebLock(),this.drain()}}async acquireExclusiveLease(){if(!this.activeLease&&this.inFlightNonTxCount===0&&this.queue.length===0){const t={leaseId:this.nextLeaseId++,txId:this.nextTxId++,createdAt:Date.now()};return this.activeLease=t,await this.acquireWebLock(),t}return new Promise(t=>{this.leaseWaiters.push({resolve:async n=>{await this.acquireWebLock(),t(n)}}),this.drain()})}releaseExclusiveLease(t){!this.activeLease||this.activeLease.leaseId!==t||(this.activeLease=null,this.releaseCurrentWebLock(),this.drain())}drain(){if(!this.activeLease){if(this.leaseWaiters.length>0){if(this.inFlightNonTxCount===0){const t=this.leaseWaiters.shift(),n={leaseId:this.nextLeaseId++,txId:this.nextTxId++,createdAt:Date.now()};this.activeLease=n,t.resolve(n)}return}for(;this.queue.length>0&&!this.activeLease&&this.leaseWaiters.length===0&&(!this.hasWebLocks()||this.inFlightNonTxCount===0);){const t=this.queue.shift();t&&t()}}}}class Qo{constructor(t,n,s,i){U(this,"vfs");U(this,"pool");U(this,"io");U(this,"queue");U(this,"activeLease",null);U(this,"snapshotFrameCount",0);U(this,"snapshotWalFrameSeq",0);U(this,"slotSnapshots",new Map);U(this,"pinCountsSnapshot",null);U(this,"spilledPages",new Map);U(this,"committedWalPages",new Map);U(this,"walFrameSeq",0);U(this,"txCommitCount",0);U(this,"checkpointSeq",0);U(this,"instanceSalt",Math.floor(Math.random()*4294967295)>>>0||1);U(this,"expectedWalFrameCount",0);U(this,"lastDiskChangeCounter",0);U(this,"lastDiskSchemaVersion",0);U(this,"onCrossTabInvalidated");U(this,"idleTimer",null);U(this,"isClosed",!1);this.vfs=t,this.pool=n,this.io=s,this.queue=new Do(i,()=>this.syncCrossTabState())}setOnCrossTabInvalidated(t){this.onCrossTabInvalidated=t}recordDiskPage1State(){const t=this.pool.getSlotDataView(0);this.lastDiskChangeCounter=t.getUint32(pe,!0),this.lastDiskSchemaVersion=t.getUint32(Ie,!0)}async reloadFromDisk(t,n,s){this.pool.getPageBytesInSlot(0).set(t),this.pool.clearDirty(0),this.lastDiskChangeCounter=n,this.lastDiskSchemaVersion=s;for(let i=1;i<this.pool.slotCount;i++)this.pool.unassignSlot(i),this.pool.clearDirty(i),this.pool.pin_counts[i]=0;this.pool.pin_counts[0]=1,this.onCrossTabInvalidated&&await this.onCrossTabInvalidated()}async syncCrossTabState(t=!1){if(!t&&!this.queue.hasWebLocks())return;const n=await this.vfs.getWalFrameCount();let s=!1;if(n>0){const r=await this.vfs.readWalHeader();let o=0;if(r)try{o=hs(r,!0).salt1}catch{o=0}(o!==this.instanceSalt||n!==this.expectedWalFrameCount)&&(s=!0,await Hi(this.vfs),this.committedWalPages.clear(),this.walFrameSeq=0,this.txCommitCount=0,this.expectedWalFrameCount=0)}else this.expectedWalFrameCount>0&&(s=!0,this.committedWalPages.clear(),this.walFrameSeq=0,this.txCommitCount=0,this.expectedWalFrameCount=0);const[i]=await this.vfs.readPages([1]);if(i){const r=new DataView(i.buffer,i.byteOffset,i.byteLength),o=r.getUint32(pe,!0),a=r.getUint32(Ie,!0);(s||o!==this.lastDiskChangeCounter||a!==this.lastDiskSchemaVersion)&&await this.reloadFromDisk(i,o,a)}}get leaseQueue(){return this.queue}isInTransaction(){return this.activeLease!==null}getActiveLeaseId(){return this.activeLease?this.activeLease.leaseId:null}getActiveTxId(){return this.activeLease?this.activeLease.txId:null}hasSpilledPage(t){return this.spilledPages.has(t)||this.committedWalPages.has(t)}getSpilledPage(t){const n=this.spilledPages.get(t)??this.committedWalPages.get(t);return n?new Uint8Array(n):null}onDirectPageWrite(t,n){if(this.committedWalPages.has(t)&&this.committedWalPages.set(t,new Uint8Array(n)),t===1){const s=new DataView(n.buffer,n.byteOffset,n.byteLength);this.lastDiskChangeCounter=s.getUint32(pe,!0),this.lastDiskSchemaVersion=s.getUint32(Ie,!0)}}async spillUncommittedSlot(t,n){if(!this.activeLease){await this.io.writeSlot(t,n);return}this.io.stampSlotChecksum(t,n);const s=this.pool.getPageBytesInSlot(t),i=new Uint8Array(we);i.set(s),this.spilledPages.set(n,i);const r=this.pool.getSlotDataView(0).getUint32(se,!0),o=gs({frameType:Kn,flags:0,txId:this.activeLease.txId,pageId:n,dbSizePages:r,frameSeq:++this.walFrameSeq},i);await this.vfs.appendWalFrames([o]),this.expectedWalFrameCount=await this.vfs.getWalFrameCount()}async captureSavepoint(){const t=await this.vfs.getWalFrameCount(),n=new Map;for(let r=0;r<this.pool.slotCount;r++){const o=this.pool.getAssignedPage(r);if(o>0){const a=this.pool.isDirty(r),c=new Uint8Array(this.pool.getPageBytesInSlot(r));n.set(r,{pageId:o,dirty:a,data:c})}}const s=new Uint32Array(this.pool.pin_counts),i=new Map;for(const[r,o]of this.spilledPages.entries())i.set(r,new Uint8Array(o));return{frameCount:t,slotSnapshots:n,pinCounts:s,spilledPages:i,walFrameSeq:this.walFrameSeq}}async restoreSavepoint(t){for(let n=1;n<this.pool.slotCount;n++)this.pool.unassignSlot(n),this.pool.clearDirty(n);for(let n=0;n<this.pool.slotCount;n++){const s=t.slotSnapshots.get(n);s&&(this.pool.assignSlot(n,s.pageId),this.pool.getPageBytesInSlot(n).set(s.data),s.dirty?this.pool.markDirty(n):this.pool.clearDirty(n))}this.pool.pin_counts.set(t.pinCounts),this.spilledPages.clear();for(const[n,s]of t.spilledPages.entries())this.spilledPages.set(n,new Uint8Array(s));this.walFrameSeq=t.walFrameSeq,await this.vfs.truncateWal(t.frameCount),this.expectedWalFrameCount=t.frameCount}async begin(){const t=await this.queue.acquireExclusiveLease();this.activeLease=t,this.pauseIdleTimer();try{await this.syncCrossTabState();const n=await this.vfs.getWalFrameCount(),s=await this.vfs.readWalHeader();let i=!1;if(s&&n>0)try{i=hs(s,!0).salt1===this.instanceSalt}catch{i=!1}i||await this.vfs.writeWalHeader(As({checkpointSeq:this.checkpointSeq,salt1:this.instanceSalt})),this.spilledPages.clear();const r=await this.captureSavepoint();return this.snapshotFrameCount=r.frameCount,this.snapshotWalFrameSeq=r.walFrameSeq,this.slotSnapshots=r.slotSnapshots,this.pinCountsSnapshot=r.pinCounts,t}catch(n){throw this.activeLease=null,this.queue.releaseExclusiveLease(t.leaseId),n}}async commit(t){var o,a;if(!this.activeLease||this.activeLease.leaseId!==t)return;const n=this.activeLease.txId,s=[],i=this.pool.getSlotDataView(0).getUint32(se,!0);for(const[c,l]of this.spilledPages.entries())this.committedWalPages.set(c,l);for(let c=0;c<this.pool.slotCount;c++)if(this.pool.isDirty(c)){const l=this.pool.getAssignedPage(c);if(l>0){this.io.stampSlotChecksum(c,l);const u=this.pool.getPageBytesInSlot(c),_=new Uint8Array(we);_.set(u),this.committedWalPages.set(l,_),this.pool.clearDirty(c),s.push(gs({frameType:Zn,flags:0,txId:n,pageId:l,dbSizePages:i,frameSeq:++this.walFrameSeq},_))}}s.push(gs({frameType:jn,flags:0,txId:n,pageId:0,dbSizePages:i,frameSeq:++this.walFrameSeq})),await this.vfs.appendWalFrames(s),await((a=(o=this.vfs).flushWal)==null?void 0:a.call(o));const r=await this.vfs.getWalFrameCount();this.expectedWalFrameCount=r,this.activeLease=null,this.spilledPages.clear(),this.slotSnapshots.clear(),this.pinCountsSnapshot=null,this.txCommitCount++,this.queue.releaseExclusiveLease(t),this.scheduleIdleTimer(),(r>=256||this.txCommitCount>=100)&&this.queue.enqueue(()=>this.executeCheckpoint())}async rollback(t){!this.activeLease||this.activeLease.leaseId!==t||(await this.restoreSavepoint({frameCount:this.snapshotFrameCount,slotSnapshots:this.slotSnapshots,pinCounts:this.pinCountsSnapshot??new Uint32Array(this.pool.pin_counts),spilledPages:new Map,walFrameSeq:this.snapshotWalFrameSeq}),this.activeLease=null,this.spilledPages.clear(),this.slotSnapshots.clear(),this.pinCountsSnapshot=null,this.queue.releaseExclusiveLease(t),this.scheduleIdleTimer())}async checkpoint(){return this.queue.enqueue(()=>this.executeCheckpoint())}async executeCheckpoint(){var o,a;const t=await this.vfs.getWalFrameCount(),n=new Map;if(t>0){const c=await this.vfs.readWalFrames(0,t),l=new Map,u=new Set;for(const _ of c){const A=Ti(_);if(!A.valid||!A.header)break;const{frameType:f,txId:g,pageId:d}=A.header;if(l.has(g)||l.set(g,[]),f===jn)u.add(g);else if(f===Zn||f===Kn){const I=new Uint8Array(_.buffer,_.byteOffset+ke,we),p=new Uint8Array(we);p.set(I),l.get(g).push({pageId:d,data:p})}}for(const[_,A]of l.entries())if(u.has(_))for(const f of A)f.pageId>0&&n.set(f.pageId,f.data)}for(const[c,l]of this.committedWalPages.entries())n.set(c,l);const s=new Map;for(let c=0;c<this.pool.slotCount;c++)if(this.pool.isDirty(c)){const l=this.pool.getAssignedPage(c);if(l>0){this.io.stampSlotChecksum(c,l);const u=this.pool.getPageBytesInSlot(c),_=new Uint8Array(we);_.set(u),s.set(l,{slotIdx:c,data:_})}}const i=new Set([...n.keys(),...s.keys()]),r=[];for(const c of i)if(s.has(c)){const{slotIdx:l,data:u}=s.get(c);r.push({pageId:c,data:u}),this.pool.clearDirty(l)}else r.push({pageId:c,data:n.get(c)});return r.length>0&&(r.sort((c,l)=>c.pageId-l.pageId),await this.vfs.writePages(r)),await((a=(o=this.vfs).flush)==null?void 0:a.call(o)),await this.vfs.truncateWal(0),this.committedWalPages.clear(),this.checkpointSeq++,this.walFrameSeq=0,this.txCommitCount=0,this.expectedWalFrameCount=0,this.recordDiskPage1State(),await this.vfs.writeWalHeader(As({checkpointSeq:this.checkpointSeq,salt1:this.instanceSalt})),{pagesWritten:r.length}}async resetWalAfterImport(){this.spilledPages.clear(),this.committedWalPages.clear(),await this.vfs.truncateWal(0),this.checkpointSeq++,this.walFrameSeq=0,this.txCommitCount=0,this.expectedWalFrameCount=0,this.recordDiskPage1State(),await this.vfs.writeWalHeader(As({checkpointSeq:this.checkpointSeq,salt1:this.instanceSalt}))}scheduleIdleTimer(){this.isClosed||(this.pauseIdleTimer(),this.idleTimer=setTimeout(()=>{this.checkpoint().catch(()=>{})},5e3))}pauseIdleTimer(){this.idleTimer&&(clearTimeout(this.idleTimer),this.idleTimer=null)}async close(){this.isClosed=!0,this.pauseIdleTimer(),await this.checkpoint()}}const vo=new Set(["count","sum","avg","min","max"]),ko=new Set(["upper","lower","length","substr","trim","abs","round","floor","ceil","concat","coalesce"]);function ge(e){return vo.has(e.toLowerCase())}function Mo(e){return ko.has(e.toLowerCase())}function Jl(e){return ge(e)||Mo(e)}function je(e,t){if(t==="where"){if(e.type==="fn"&&ge(e.name))throw new os(e.name);if(e.type==="binary"&&(je(e.left,t),je(e.right,t)),e.type==="fn")for(const n of e.args)je(n,t)}}function zl(e){const t=[];let n=0;const s=e.length;for(;n<s;){const i=e[n];if(/\s/.test(i)){n++;continue}if(/[0-9]/.test(i)||i==="."&&n+1<s&&/[0-9]/.test(e[n+1])){const r=n;let o=!1;for(;n<s&&(/[0-9]/.test(e[n])||e[n]==="."&&!o);)e[n]==="."&&(o=!0),n++;t.push({type:"NUMBER",value:e.slice(r,n),pos:r});continue}if(i==="'"||i==='"'){const r=i,o=n;n++;let a="";for(;n<s&&e[n]!==r;)e[n]==="\\"&&n+1<s&&n++,a+=e[n],n++;n<s&&e[n]===r&&n++,t.push({type:"STRING",value:a,pos:o});continue}if(i==="("){t.push({type:"LPAREN",value:"(",pos:n++});continue}if(i===")"){t.push({type:"RPAREN",value:")",pos:n++});continue}if(i===","){t.push({type:"COMMA",value:",",pos:n++});continue}if(i==="<"){if(n+1<s&&e[n+1]==="="){t.push({type:"OP",value:"<=",pos:n}),n+=2;continue}if(n+1<s&&e[n+1]===">"){t.push({type:"OP",value:"!=",pos:n}),n+=2;continue}t.push({type:"OP",value:"<",pos:n++});continue}if(i===">"){if(n+1<s&&e[n+1]==="="){t.push({type:"OP",value:">=",pos:n}),n+=2;continue}t.push({type:"OP",value:">",pos:n++});continue}if(i==="="){if(n+1<s&&e[n+1]==="="){t.push({type:"OP",value:"=",pos:n}),n+=2;continue}t.push({type:"OP",value:"=",pos:n++});continue}if(i==="!"&&n+1<s&&e[n+1]==="="){t.push({type:"OP",value:"!=",pos:n}),n+=2;continue}if(i==="+"||i==="-"||i==="/"||i==="%"){t.push({type:"OP",value:i,pos:n++});continue}if(i==="*"){t.push({type:"STAR",value:"*",pos:n++});continue}if(/[a-zA-Z_]/.test(i)){const r=n;for(;n<s;)if(/[a-zA-Z0-9_]/.test(e[n]))n++;else if(e[n]==="."&&n+1<s&&/[a-zA-Z_]/.test(e[n+1]))n+=2;else break;const o=e.slice(r,n);t.push({type:"IDENT",value:o,pos:r});continue}n++}return t.push({type:"EOF",value:"",pos:s}),t}class tc{constructor(t){U(this,"tokens");U(this,"cursor",0);this.tokens=t}peek(){return this.tokens[this.cursor]??{type:"EOF",value:"",pos:0}}consume(){const t=this.peek();return this.cursor++,t}match(t,n){const s=this.peek();return s.type!==t||n!==void 0&&s.value.toLowerCase()!==n.toLowerCase()?!1:(this.cursor++,!0)}getPrecedence(t){if(t.type==="OP"||t.type==="STAR"){if(t.value==="="||t.value==="!="||t.value==="<"||t.value==="<="||t.value===">"||t.value===">=")return 5;if(t.value==="+"||t.value==="-")return 10;if(t.value==="*"||t.value==="/"||t.value==="%")return 20}return 0}parse(t=0){let n=this.parsePrimary();for(;;){const s=this.peek(),i=this.getPrecedence(s);if(i===0||i<=t)break;this.consume();const r=this.parse(i);n={type:"binary",op:s.value,left:n,right:r}}return n}parsePrimary(){const t=this.peek();if(t.type==="OP"&&t.value==="-"){this.consume();const n=this.parse(25);return n.type==="literal"&&typeof n.value=="number"?{type:"literal",value:-n.value}:{type:"binary",op:"-",left:{type:"literal",value:0},right:n}}if(this.match("NUMBER"))return{type:"literal",value:Number(t.value)};if(this.match("STRING"))return{type:"literal",value:t.value};if(this.match("LPAREN")){const n=this.parse(0);if(!this.match("RPAREN"))throw new Error("Unclosed parenthesis in expression");return n}if(this.match("STAR"))return{type:"col",name:"*"};if(t.type==="IDENT"){this.consume();const n=t.value,s=n.toLowerCase();if(s==="null"&&this.peek().type!=="LPAREN")return{type:"literal",value:null};if(s==="true"&&this.peek().type!=="LPAREN")return{type:"literal",value:!0};if(s==="false"&&this.peek().type!=="LPAREN")return{type:"literal",value:!1};if(this.match("LPAREN")){const i=[];if(!this.match("RPAREN")){for(;;)if(i.push(this.parse(0)),!this.match("COMMA")){if(this.match("RPAREN"))break;throw new Error(`Expected ',' or ')' in argument list of function ${n}`)}}return{type:"fn",name:s,args:i}}return{type:"col",name:n}}throw new Error(`Unexpected token "${t.value}" in expression at position ${t.pos}`)}}function ft(e){const t=e.trim();if(!t)throw new Error("Cannot parse empty expression");const n=zl(t);return new tc(n).parse(0)}function ec(e){let t=0,n=null;const s=e.length;for(let i=0;i<s;i++){const r=e[i];if(n){r===n&&e[i-1]!=="\\"&&(n=null);continue}if(r==="'"||r==='"'){n=r;continue}if(r==="("){t++;continue}if(r===")"){t--;continue}if(t===0&&(r===" "||r===" ")&&i+4<s&&e.slice(i+1,i+3).toLowerCase()==="as"&&/\s/.test(e[i+3])){const o=e.slice(0,i).trim(),a=e.slice(i+4).trim();return{exprStr:o,explicitAlias:a}}}return{exprStr:e.trim()}}function Qt(e){if(e.type==="col")return e.name.includes(".")?e.name.slice(e.name.lastIndexOf(".")+1):e.name;if(e.type==="fn"){if(e.args.length>0&&e.args[0].type==="col"&&e.args[0].name!=="*"){const t=e.args[0].name.includes(".")?e.args[0].name.slice(e.args[0].name.lastIndexOf(".")+1):e.args[0].name;return`${e.name}_${t}`}return e.name}return e.type==="binary"?"expr":"val"}function Bs(e){const{exprStr:t,explicitAlias:n}=ec(e),s=ft(t),i=n&&n.length>0?n:Qt(s);return{expr:s,alias:i}}class it{constructor(t){U(this,"node");this.node=t}add(t){return new it({type:"binary",op:"+",left:this.node,right:Xt(t)})}sub(t){return new it({type:"binary",op:"-",left:this.node,right:Xt(t)})}mul(t){return new it({type:"binary",op:"*",left:this.node,right:Xt(t)})}div(t){return new it({type:"binary",op:"/",left:this.node,right:Xt(t)})}mod(t){return new it({type:"binary",op:"%",left:this.node,right:Xt(t)})}eq(t){return new it({type:"binary",op:"=",left:this.node,right:Xt(t)})}ne(t){return new it({type:"binary",op:"!=",left:this.node,right:Xt(t)})}lt(t){return new it({type:"binary",op:"<",left:this.node,right:Xt(t)})}lte(t){return new it({type:"binary",op:"<=",left:this.node,right:Xt(t)})}gt(t){return new it({type:"binary",op:">",left:this.node,right:Xt(t)})}gte(t){return new it({type:"binary",op:">=",left:this.node,right:Xt(t)})}as(t){return{expr:this.node,alias:t}}}function Xt(e){return e===null?{type:"literal",value:null}:typeof e=="boolean"?{type:"literal",value:e}:e instanceof it?e.node:typeof e=="number"?{type:"literal",value:e}:typeof e=="string"?{type:"literal",value:e}:e}function Vi(e){return new it({type:"col",name:e})}function Go(e){return new it(ft(e))}const nc=Go;function Pt(e,t){return new it({type:"fn",name:e.toLowerCase(),args:t.map(n=>typeof n=="string"&&!n.startsWith("'")?Vi(n).node:Xt(n))})}const qo=(e,...t)=>Pt(e,t),sc={upper:e=>Pt("upper",[e]),lower:e=>Pt("lower",[e]),length:e=>Pt("length",[e]),substr:(e,t,n)=>{const s=[e,t];return n!==void 0&&s.push(n),Pt("substr",s)},trim:e=>Pt("trim",[e]),abs:e=>Pt("abs",[e]),round:e=>Pt("round",[e]),floor:e=>Pt("floor",[e]),ceil:e=>Pt("ceil",[e]),count:e=>Pt("count",[e??Vi("*").node]),sum:e=>Pt("sum",[e]),avg:e=>Pt("avg",[e]),min:e=>Pt("min",[e]),max:e=>Pt("max",[e]),concat:(...e)=>Pt("concat",e),coalesce:(...e)=>Pt("coalesce",e)};for(const[e,t]of Object.entries(sc))Object.defineProperty(qo,e,{value:t,writable:!0,enumerable:!0,configurable:!0});const ic=qo;function vt(e,t,n){switch(e.type){case"literal":return e.value;case"col":return e.name==="*"?null:t[e.name]!==void 0?t[e.name]:null;case"binary":{const s=vt(e.left,t,n),i=vt(e.right,t,n);if(s===null||i===null||s===void 0||i===void 0)return null;if(e.op==="="||e.op==="!="||e.op==="<"||e.op==="<="||e.op===">"||e.op===">="){const a=typeof s=="string"&&typeof i=="string"?s<i?-1:s>i?1:0:Number(s)<Number(i)?-1:Number(s)>Number(i)?1:0;switch(e.op){case"=":return a===0?1:0;case"!=":return a!==0?1:0;case"<":return a<0?1:0;case"<=":return a<=0?1:0;case">":return a>0?1:0;case">=":return a>=0?1:0}}const r=Number(s),o=Number(i);switch(e.op){case"+":return r+o;case"-":return r-o;case"*":return r*o;case"/":return o===0?null:r/o;case"%":return o===0?null:r%o}return null}case"fn":{const s=e.name.toLowerCase();if(ge(s)){if(t[s]!==void 0)return t[s];const r=e.args[0];if(r&&r.type==="col"){const o=`${s}_${r.name}`;if(t[o]!==void 0)return t[o]}return null}const i=e.args.map(r=>vt(r,t,n));switch(s){case"upper":return i[0]!==null&&i[0]!==void 0?String(i[0]).toUpperCase():null;case"lower":return i[0]!==null&&i[0]!==void 0?String(i[0]).toLowerCase():null;case"length":return i[0]!==null&&i[0]!==void 0?String(i[0]).length:null;case"trim":return i[0]!==null&&i[0]!==void 0?String(i[0]).trim():null;case"substr":{if(i[0]===null||i[0]===void 0)return null;const r=String(i[0]),o=Math.max(0,(Number(i[1])||1)-1),a=i[2]!==null&&i[2]!==void 0?Number(i[2]):void 0;return a!==void 0?r.substring(o,o+a):r.substring(o)}case"abs":return i[0]!==null&&i[0]!==void 0?Math.abs(Number(i[0])):null;case"round":return i[0]!==null&&i[0]!==void 0?Math.round(Number(i[0])):null;case"floor":return i[0]!==null&&i[0]!==void 0?Math.floor(Number(i[0])):null;case"ceil":return i[0]!==null&&i[0]!==void 0?Math.ceil(Number(i[0])):null;case"concat":return i.some(r=>r==null)?null:i.map(String).join("");case"coalesce":{for(const r of i)if(r!=null)return r;return null}case"starts_with":case"startswith":return i[0]!==null&&i[0]!==void 0&&i[1]!==null&&i[1]!==void 0?String(i[0]).startsWith(String(i[1]))?1:0:null;case"ends_with":case"endswith":return i[0]!==null&&i[0]!==void 0&&i[1]!==null&&i[1]!==void 0?String(i[0]).endsWith(String(i[1]))?1:0:null;case"contains":return i[0]!==null&&i[0]!==void 0&&i[1]!==null&&i[1]!==void 0?String(i[0]).includes(String(i[1]))?1:0:null;case"like":return i[0]!==null&&i[0]!==void 0&&i[1]!==null&&i[1]!==void 0?Xe(String(i[0]),String(i[1]))?1:0:null;default:{let r;if(typeof n=="function")r=n(s);else if(n instanceof Map){const o=n.get(s);r=typeof o=="function"?o:o==null?void 0:o.call}else if(n&&typeof n=="object"){const o=n[s];r=typeof o=="function"?o:o==null?void 0:o.call}if(r)return r(...i);throw new di(s)}}}}}const _n=.5,Ls=.05,_e=.02;function Wo(e){const t=[];function n(i){if(i.colName&&t.push(i.colName),i.expr&&s(i.expr),i.children)for(const r of i.children)n(r);i.child&&n(i.child)}function s(i){if(i&&(i.type==="col"&&i.name&&t.push(i.name),i.left&&s(i.left),i.right&&s(i.right),i.args&&Array.isArray(i.args)))for(const r of i.args)s(r)}return n(e),t}function dn(e,t){const n=Wo(e),s=new Set;for(const i of n){const r=ht(i,t);r&&s.add(r.tableIdx)}return s}function $i(e,t){var s,i;const n=Math.max(1,t.rowCountEstimate||10);if(e.type==="cmp"){const r=e.op??"=";if(r==="="){const o=(s=e.colName)==null?void 0:s.toLowerCase(),a=t.columns.findIndex(c=>c.name.toLowerCase()===o);if(a!==-1&&t.indexes){for(const c of t.indexes)if(c.columnCount===1&&c.columnIndices[0]===a)return(c.flags&(It.PRIMARY|It.UNIQUE))!==0?1/n:Math.min(.2,5/n)}return .1}if(r==="<"||r==="<="||r===">"||r===">=")return .33;if(r==="!="||r==="<>")return .9;if(r==="like"||r==="contains"||r==="starts_with"||r==="ends_with")return .15}if(e.type==="in"){const r=Math.max(1,((i=e.values)==null?void 0:i.length)||1);return Math.min(1,r*.05)}return e.type==="null"?e.isNull?.05:.95:.2}function de(e,t,n,s){var _;const i=Math.max(1,e.rowCountEstimate||10);let r=1;for(const A of t)r*=$i(A,e);const o=Math.max(1,Math.round(i*r)),a=n!==void 0&&n.length>0,c=a&&o>1?o*Math.log2(o)*_e:0,l=ks(e,t,t,n);if(l){const A=l.scanType==="point",f=l.scanType==="multi_point",g=l.satisfiesOrderBy===!0,d=g&&s!==void 0&&s>0?Math.min(s,o):o;let I=_n;return A?(I+=1*_e,{cost:I,rows:1,scanType:"IndexScan",indexName:l.index.name,isOrderSatisfied:!0,sortCostAvoided:a?c:void 0}):f?(I=(((_=l.inValues)==null?void 0:_.length)||1)*_n+d*_e,!g&&a&&(I+=c),{cost:I,rows:d,scanType:"IndexScan",indexName:l.index.name,isOrderSatisfied:g,sortCostAvoided:g?c:void 0}):(I+=d*Ls+d*_e,!g&&a&&(I+=c),{cost:I,rows:d,scanType:"IndexScan",indexName:l.index.name,isOrderSatisfied:g,sortCostAvoided:g?c:void 0})}let u=i*_e;return a&&(u+=c),{cost:u,rows:o,scanType:"TableScan",isOrderSatisfied:!1}}function Hn(e,t){if(!e.indexes||e.indexes.length===0)return null;const n=e.columns.findIndex(r=>r.name.toLowerCase()===t.toLowerCase());if(n===-1)return null;let s=null,i=999;for(const r of e.indexes)if(r.columnCount===1&&r.columnIndices[0]===n){const o=(r.flags&It.PRIMARY)!==0,a=(r.flags&It.UNIQUE)!==0,c=o?1:a?2:3;c<i&&(i=c,s={index:r,isUnique:o||a})}return s}function Rs(e,t){const n=t.length,s=[],i=Array.from({length:n},()=>new Set);if(!e.joinedTables)return{edges:s,dependencies:i};for(let r=0;r<e.joinedTables.length;r++){const o=e.joinedTables[r],a=r+1,c=ht(o.leftCol,t),l=ht(o.rightCol,t);if(c&&l&&(s.push({tableA:c.tableIdx,tableB:l.tableIdx,colA:c.col.name,colB:l.col.name,op:o.op,type:o.type,declaredRightTable:a}),o.type==="left")){const u=c.tableIdx===a?l.tableIdx:c.tableIdx;i[a].add(u)}}return{edges:s,dependencies:i}}function Vn(e,t){if(e.selectExprs&&e.selectExprs.length>0)return e.selectExprs;const n=new Set,s=new Set;for(const r of t)for(const o of r.columns)n.has(o.name.toLowerCase())&&s.add(o.name.toLowerCase()),n.add(o.name.toLowerCase());const i=[];for(const r of t)for(const o of r.columns){const a=s.has(o.name.toLowerCase())?`${r.name}.${o.name}`:o.name;i.push({expr:{type:"col",name:`${r.name}.${o.name}`},alias:a})}return i}function Fs(e,t,n,s){const i=e.length,r=[];for(let o=1;o<i;o++){const a=e[o],c=t[a],l=e.slice(0,o),u=n.find(d=>d.tableA===a&&l.includes(d.tableB)||d.tableB===a&&l.includes(d.tableA));let _,A,f="=",g="inner";if(u)f=u.op,g=u.type,u.tableA===a?(A=`${c.name}.${u.colA}`,_=`${t[u.tableB].name}.${u.colB}`):(A=`${c.name}.${u.colB}`,_=`${t[u.tableA].name}.${u.colA}`);else{const d=s==null?void 0:s.find(I=>I.table.name===c.name);_=d?d.leftCol:`${t[e[0]].name}.id`,A=d?d.rightCol:`${c.name}.id`,f=d?d.op:"=",g=d?d.type:"inner"}r.push({type:g,table:c,cursor:o,leftCol:_,op:f,rightCol:A})}return r}function xi(e,t,n,s,i){if(!s||s.length===0)return!1;for(const r of s){if(r.direction==="desc")return!1;const o=r.colName;if(!o)return!1;let a=ht(o,n);if(!a&&i){const c=i.find(l=>l.alias===o);c&&c.expr.type==="col"&&(a=ht(c.expr.name,n))}if(!a||a.tableIdx!==t)return!1}return!0}function Xi(e,t){var n;if(e.type==="null")return 1;if(e.type==="cmp"){const s=e.op??"=";if(s==="like"||s==="not like")return(typeof e.value=="string"?e.value:"").startsWith("%")?25:15;let i=!1;if(t&&e.colName){const r=e.colName.toLowerCase(),o=r.includes(".")?r.slice(r.lastIndexOf(".")+1):r;for(const a of t){const c=a.columns.find(l=>l.name.toLowerCase()===o);if(c){i=c.type===1||c.type===2||c.type===3;break}}}else typeof e.value=="number"&&(i=!0);return s==="="||s==="=="?i?2:4:i?3:6}return e.type==="in"?(((n=e.values)==null?void 0:n.length)??0)<=3?5:10:e.type==="expr"?40:e.type==="and"||e.type==="or"?15:e.type==="not"?8:10}function Yi(e,t){if(!e||e.length===0)return{filters:[],isAlwaysFalse:!1,isAlwaysTrue:!0,metrics:{originalCount:0,optimizedCount:0,isAlwaysFalse:!1,isAlwaysTrue:!0,eliminatedFiltersCount:0,reordered:!1}};const n=e.length,s=[];for(const _ of e)_.type==="and"&&Array.isArray(_.children)?s.push(..._.children):s.push(_);const i=new Map,r=[];for(const _ of s)if(_.colName){const A=_.colName.toLowerCase();i.has(A)||i.set(A,[]),i.get(A).push(_)}else r.push(_);for(const[_,A]of i.entries()){const f=rc(A);if(f)return{filters:[],isAlwaysFalse:!0,isAlwaysTrue:!1,metrics:{originalCount:n,optimizedCount:0,isAlwaysFalse:!0,isAlwaysTrue:!1,contradictionReason:`Contradiction on column "${_}": ${f}`,eliminatedFiltersCount:n,reordered:!1}}}const o=[];let a=0;for(const[,_]of i.entries()){const A=oc(_);a+=_.length-A.length,o.push(...A)}o.push(...r);const c=o.map(_=>Zi(_)).join("|");o.sort((_,A)=>{const f=Xi(_,t),g=Xi(A,t);return f-g});const l=o.map(_=>Zi(_)).join("|"),u=c!==l;return{filters:o,isAlwaysFalse:!1,isAlwaysTrue:o.length===0,metrics:{originalCount:n,optimizedCount:o.length,isAlwaysFalse:!1,isAlwaysTrue:o.length===0,eliminatedFiltersCount:a,reordered:u}}}function rc(e){let t=!1,n=!1;const s=[];let i=null,r=null,o=null;for(const a of e){if(a.type==="null"&&(a.isNull===!0&&(t=!0),a.isNull===!1&&(n=!0)),a.type==="cmp"){const c=a.op??"=",l=a.value;c==="="&&l!==null&&l!==void 0&&s.push(l),typeof l=="number"&&(c===">"?(!i||l>i.val||l===i.val&&!i.strict)&&(i={val:l,strict:!0}):c===">="?(!i||l>i.val)&&(i={val:l,strict:!1}):c==="<"?(!r||l<r.val||l===r.val&&!r.strict)&&(r={val:l,strict:!0}):c==="<="&&(!r||l<r.val)&&(r={val:l,strict:!1}))}if(a.type==="in"&&!a.notIn){if(!a.values||a.values.length===0)return"Empty IN () list";const c=new Set(a.values);if(!o)o=c;else{const l=new Set([...o].filter(u=>c.has(u)));if(l.size===0)return"Mutually exclusive IN lists with no common values";o=l}}}if(t&&n)return"Conflicting IS NULL and IS NOT NULL";if(t&&(s.length>0||i||r))return"Conflicting IS NULL and literal comparison";if(s.length>1){const a=s[0];for(let c=1;c<s.length;c++)if(s[c]!==a)return`Conflicting equality values (${a} !== ${s[c]})`}if(s.length>0&&(i||r)){const a=s[0];if(typeof a=="number"){if(i&&(i.strict?a<=i.val:a<i.val))return`Equality value ${a} violates lower bound ${i.strict?">":">="} ${i.val}`;if(r&&(r.strict?a>=r.val:a>r.val))return`Equality value ${a} violates upper bound ${r.strict?"<":"<="} ${r.val}`}}if(s.length>0&&o){const a=s[0];if(!o.has(a))return`Equality value ${a} not present in IN list`}if(i&&r){if(i.val>r.val)return`Lower bound ${i.val} is greater than upper bound ${r.val}`;if(i.val===r.val&&(i.strict||r.strict))return`Strict range bounds empty at ${i.val}`}return null}function oc(e){const t=[],n=new Set;let s=!1,i;for(const a of e)if(a.type==="cmp"&&(a.op==="="||a.op===void 0)&&a.value!==null&&a.value!==void 0){s=!0,i=a.value;break}let r=null,o=null;for(const a of e)if(a.type==="cmp"&&typeof a.value=="number"){const c=a.op??"=",l=a.value;c===">"?(!r||l>r.val||l===r.val&&!r.strict)&&(r={val:l,strict:!0,filter:a}):c===">="?(!r||l>r.val)&&(r={val:l,strict:!1,filter:a}):c==="<"?(!o||l<o.val||l===o.val&&!o.strict)&&(o={val:l,strict:!0,filter:a}):c==="<="&&(!o||l<o.val)&&(o={val:l,strict:!1,filter:a})}for(const a of e){const c=Zi(a);if(!n.has(c)&&!(a.type==="null"&&a.isNull===!1&&s)&&!(a.type==="in"&&!a.notIn&&s&&Array.isArray(a.values)&&a.values.includes(i))){if(a.type==="cmp"&&typeof a.value=="number"){const l=a.op??"=";if(l===">"||l===">="){if(r&&a!==r.filter)continue}else if((l==="<"||l==="<=")&&o&&a!==o.filter)continue}n.add(c),t.push(a)}}return t}function Zi(e){return`${e.type}:${e.colName??""}:${e.isNull??""}:${e.op??""}:${String(e.value??"")}:${e.notIn??""}:${JSON.stringify(e.values??"")}`}function Ho(e,t){const n=[...e],s=o=>o.toLowerCase(),i=o=>{const a=o.lastIndexOf(".");return a>=0?o.slice(a+1).toLowerCase():o.toLowerCase()},r=o=>{const a=s(o),c=i(o);for(const l of e)if(l.type==="cmp"&&(l.op==="="||l.op==="=="||l.op===void 0)&&l.colName&&l.value!==null&&l.value!==void 0){const u=s(l.colName),_=i(l.colName);if(u===a||_===a||u===c)return l.value}};for(const o of t){if(o.type!=="inner"&&o.type!=="left"||o.op!=="="&&o.op!=="==")continue;const a=r(o.leftCol);if(a!==void 0&&n.push({type:"cmp",colName:o.rightCol,op:"=",value:a}),o.type==="inner"){const c=r(o.rightCol);c!==void 0&&n.push({type:"cmp",colName:o.leftCol,op:"=",value:c})}}return n}class Ds{constructor(t){U(this,"name","cost");U(this,"indexSeekCost");U(this,"indexNextCost");U(this,"rowEvalCost");this.indexSeekCost=(t==null?void 0:t.indexSeekCost)??_n,this.indexNextCost=(t==null?void 0:t.indexNextCost)??Ls,this.rowEvalCost=(t==null?void 0:t.rowEvalCost)??_e}optimize(t){var L,h;const n=[t.table,...((L=t.joinedTables)==null?void 0:L.map(b=>b.table))??[]],s=n.length,i=Yi(t.filters,n);if(i.isAlwaysFalse)return{plan:{...t,filters:[]},orderedTables:n,metrics:null,isAlwaysFalse:!0,whereMetrics:i.metrics};let r=i.filters,o=i.metrics;if(t.joinedTables&&t.joinedTables.length>0){const b=Ho(r,t.joinedTables);if(b.length>r.length){const k=Yi(b,n);if(k.isAlwaysFalse)return{plan:{...t,filters:[]},orderedTables:n,metrics:null,isAlwaysFalse:!0,whereMetrics:k.metrics};r=k.filters,o=k.metrics}}if(s<=1||!t.joinedTables||t.joinedTables.length===0){const b=new Map;b.set(0,r);const k=de(t.table,r,t.orderBy,t.limit);return{plan:{...t,filters:r},orderedTables:[t.table],metrics:{totalCost:k.cost,estimatedRows:k.rows,joinOrder:[t.table.name],singleTableFilters:b,crossFilters:[],tableScanTypes:[k.scanType],tableIndexNames:[k.indexName],isOrderSatisfied:k.isOrderSatisfied,sortCostAvoided:k.sortCostAvoided},isAlwaysFalse:!1,isAlwaysTrue:o.isAlwaysTrue,whereMetrics:o,isOrderSatisfied:k.isOrderSatisfied,sortCostAvoided:k.sortCostAvoided}}const a=zt(r),c=mn(a),l=new Map,u=[];for(let b=0;b<s;b++)l.set(b,[]);for(const b of c){const k=dn(b,n);if(k.size===1){const $=k.values().next().value;$!==void 0&&((h=l.get($))==null||h.push(b))}else u.push(b)}if(s<=1||!t.joinedTables||t.joinedTables.length===0){const b=de(n[0],l.get(0)??[]);return{plan:t,orderedTables:n,metrics:{totalCost:b.cost,estimatedRows:b.rows,joinOrder:[n[0].name],singleTableFilters:l,crossFilters:u,tableScanTypes:[b.scanType],tableIndexNames:[b.indexName]}}}const{edges:_,dependencies:A}=Rs(t,n),f=new Map;for(let b=0;b<s;b++)if(A[b].size===0){const k=xi(n[b],b,n,t.orderBy,t.selectExprs),$=k?t.orderBy.map(G=>{const q=G.colName??"",ee=q.includes(".")?q.slice(q.lastIndexOf(".")+1):q;return{...G,colName:ee}}):void 0,j=de(n[b],l.get(b)??[],$,k?t.limit:void 0),J=1<<b;f.set(J,{order:[b],cost:j.cost,rows:j.rows,scanTypes:[j.scanType],indexNames:[j.indexName],edgesUsed:[],isOrderSatisfied:j.isOrderSatisfied,sortCostAvoided:j.sortCostAvoided})}const g=1<<s;for(let b=2;b<=s;b++)for(let k=1;k<g;k++)if(ac(k)===b)for(let $=0;$<s;$++){if(!(k&1<<$))continue;const j=k^1<<$,J=f.get(j);if(!J)continue;let G=!0;for(const Ne of A[$])if(!(j&1<<Ne)){G=!1;break}if(!G)continue;const q=this.evaluateJoinStep(J.rows,n[$],$,_,J.order,l.get($)??[]),ee=J.cost+q.stepCost,Et=f.get(k);let gt=!1,En=ee,In=Et?Et.cost:0;const pn=J.isOrderSatisfied===!0,Ke=(Et==null?void 0:Et.isOrderSatisfied)===!0;if(b===s&&t.orderBy&&t.orderBy.length>0&&(!pn&&q.newRows>1&&(En+=q.newRows*Math.log2(q.newRows)*this.rowEvalCost),Et&&!Ke&&Et.rows>1&&(In+=Et.rows*Math.log2(Et.rows)*this.rowEvalCost)),!Et)gt=!0;else if(pn&&!Ke)gt=!0;else if(!pn&&Ke)gt=!1;else{const Ne=J.scanTypes.filter(be=>be==="IndexScan").length+(q.scanType==="IndexScan"?1:0),Xn=Et.scanTypes.filter(be=>be==="IndexScan").length;if(Ne>Xn&&En<=In*1.2)gt=!0;else if(Ne<Xn)gt=!1;else if(En<In*.75)gt=!0;else if(In<En*.75)gt=!1;else{const be=J.order[0]===0,yn=Et.order[0]===0;if(be&&!yn)gt=!0;else if(!be&&yn)gt=!1;else{const oe=J.order.filter(Tn=>Tn>$).length,qs=Et.order.filter((Tn,Ws)=>Tn>Ws).length;oe<qs&&(gt=!0)}}}gt&&f.set(k,{order:[...J.order,$],cost:ee,rows:q.newRows,scanTypes:[...J.scanTypes,q.scanType],indexNames:[...J.indexNames,q.indexName],edgesUsed:[...J.edgesUsed,q.matchedEdge],isOrderSatisfied:J.isOrderSatisfied,sortCostAvoided:J.sortCostAvoided})}const d=(1<<s)-1,I=f.get(d);let p,y,T,N,B;I?(p=I.order,y=I.cost,T=I.rows,N=I.scanTypes,B=I.indexNames):(p=Array.from({length:s},(b,k)=>k),y=999999,T=100,N=Array.from({length:s},()=>"TableScan"),B=Array.from({length:s},()=>{}));const P=p.map(b=>n[b]),F=Fs(p,n,_,t.joinedTables),w=Vn(t,n),S=(I==null?void 0:I.isOrderSatisfied)===!0,v=S&&t.orderBy&&t.orderBy.length>0&&T>1?T*Math.log2(T)*this.rowEvalCost:void 0;return{plan:{...t,table:P[0],joinedTables:F,selectExprs:w,filters:r,isOrderSatisfied:S},orderedTables:P,metrics:{totalCost:y,estimatedRows:T,joinOrder:P.map(b=>b.name),singleTableFilters:l,crossFilters:u,tableScanTypes:N,tableIndexNames:B,isOrderSatisfied:S,sortCostAvoided:v},isAlwaysFalse:!1,isAlwaysTrue:o.isAlwaysTrue,whereMetrics:o,isOrderSatisfied:S,sortCostAvoided:v}}evaluateJoinStep(t,n,s,i,r,o){const a=Math.max(1,n.rowCountEstimate||10);let c=1;for(const f of o)c*=$i(f,n);const l=[];for(const f of i)if(f.tableA===s&&r.includes(f.tableB)){const g=Hn(n,f.colA);l.push({edge:f,nextCol:f.colA,outerCol:f.colB,idxMatch:g})}else if(f.tableB===s&&r.includes(f.tableA)){const g=Hn(n,f.colB);l.push({edge:f,nextCol:f.colB,outerCol:f.colA,idxMatch:g})}if(l.length===0){const f=t*(2+a*.1),g=Math.max(1,Math.round(t*a*c)),d={tableA:r[0],tableB:s,colA:"",colB:"",op:"=",type:"inner",declaredRightTable:s};return{stepCost:f,newRows:g,scanType:"TableScan",matchedEdge:d}}l.sort((f,g)=>{const d=f.idxMatch?f.idxMatch.isUnique?1:2:3,I=g.idxMatch?g.idxMatch.isUnique?1:2:3;return d-I});const u=l[0];if(u.idxMatch&&u.idxMatch.isUnique){const f=this.indexSeekCost+1*this.rowEvalCost,g=t*f,d=Math.max(1,Math.round(t*c));return{stepCost:g,newRows:d,scanType:"IndexScan",indexName:u.idxMatch.index.name,matchedEdge:u.edge}}if(u.idxMatch&&!u.idxMatch.isUnique){const f=Math.max(1,Math.min(10,Math.round(a/20))),g=this.indexSeekCost+f*this.indexNextCost,d=t*g,I=Math.max(1,Math.round(t*f*c));return{stepCost:d,newRows:I,scanType:"IndexScan",indexName:u.idxMatch.index.name,matchedEdge:u.edge}}const _=t*(2+a*.1),A=Math.max(1,Math.round(t*Math.max(1,Math.round(a*.1))*c));return{stepCost:_,newRows:A,scanType:"TableScan",matchedEdge:u.edge}}}function ac(e){let t=0,n=e;for(;n>0;)t+=n&1,n>>=1;return t}class Vo{constructor(){U(this,"name","heuristic")}optimize(t){var w,S,v;const n=[t.table,...((w=t.joinedTables)==null?void 0:w.map(L=>L.table))??[]],s=n.length,i=zt(t.filters),r=mn(i),o=new Map,a=[];for(let L=0;L<s;L++)o.set(L,[]);for(const L of r){const h=dn(L,n);if(h.size===1){const b=h.values().next().value;b!==void 0&&((S=o.get(b))==null||S.push(L))}else a.push(L)}if(s<=1||!t.joinedTables||t.joinedTables.length===0){const L=de(n[0],o.get(0)??[],t.orderBy,t.limit);return{plan:t,orderedTables:n,metrics:{totalCost:L.cost,estimatedRows:L.rows,joinOrder:[n[0].name],singleTableFilters:o,crossFilters:a,tableScanTypes:[L.scanType],tableIndexNames:[L.indexName],isOrderSatisfied:L.isOrderSatisfied,sortCostAvoided:L.sortCostAvoided},isOrderSatisfied:L.isOrderSatisfied,sortCostAvoided:L.sortCostAvoided}}const{edges:c,dependencies:l}=Rs(t,n),u=n.map((L,h)=>{const b=xi(L,h,n,t.orderBy,t.selectExprs),k=b?t.orderBy.map($=>{const j=$.colName??"",J=j.includes(".")?j.slice(j.lastIndexOf(".")+1):j;return{...$,colName:J}}):void 0;return de(L,o.get(h)??[],k,b?t.limit:void 0)}),_=[];for(let L=0;L<s;L++)l[L].size===0&&_.push(L);_.sort((L,h)=>{const b=u[L].isOrderSatisfied?1:0,k=u[h].isOrderSatisfied?1:0;if(b!==k)return k-b;if(u[L].rows!==u[h].rows)return u[L].rows-u[h].rows;const $=u[L].scanType==="IndexScan"?1:0,j=u[h].scanType==="IndexScan"?1:0;return $!==j?j-$:L===0?-1:h===0?1:L-h});const A=_[0]??0,f=[A],g=[u[A].scanType],d=[u[A].indexName];let I=u[A].cost,p=u[A].rows;const y=new Set;for(let L=0;L<s;L++)L!==A&&y.add(L);for(;y.size>0;){const L=[];for(const b of y){let k=!0;for(const G of l[b])if(!f.includes(G)){k=!1;break}if(!k)continue;const $=n[b],j=Math.max(1,$.rowCountEstimate||10);let J=null;for(const G of c)if(G.tableA===b&&f.includes(G.tableB)){const q=Hn($,G.colA);q&&(!J||q.isUnique)&&(J={isUnique:q.isUnique,indexName:q.index.name})}else if(G.tableB===b&&f.includes(G.tableA)){const q=Hn($,G.colB);q&&(!J||q.isUnique)&&(J={isUnique:q.isUnique,indexName:q.index.name})}if(J)if(J.isUnique){const G=_n+1*_e;L.push({tableIdx:b,rank:1,stepCost:p*G,newRows:Math.max(1,p),scanType:"IndexScan",indexName:J.indexName})}else{const G=Math.max(1,Math.min(10,Math.round(j/20))),q=_n+G*Ls;L.push({tableIdx:b,rank:2,stepCost:p*q,newRows:Math.max(1,p*G),scanType:"IndexScan",indexName:J.indexName})}else L.push({tableIdx:b,rank:3,stepCost:p*(2+j*.1),newRows:Math.max(1,p*Math.max(1,Math.round(j*.1))),scanType:"TableScan"})}if(L.length===0){const b=y.values().next().value;if(b===void 0)break;f.push(b),g.push("TableScan"),d.push(void 0),y.delete(b);continue}L.sort((b,k)=>b.rank!==k.rank?b.rank-k.rank:Math.abs(b.stepCost-k.stepCost)>.05?b.stepCost-k.stepCost:b.tableIdx-k.tableIdx);const h=L[0];f.push(h.tableIdx),g.push(h.scanType),d.push(h.indexName),I+=h.stepCost,p=h.newRows,y.delete(h.tableIdx)}const T=f.map(L=>n[L]),N=Fs(f,n,c,t.joinedTables),B=Vn(t,n),P=((v=u[A])==null?void 0:v.isOrderSatisfied)===!0,F=P&&t.orderBy&&t.orderBy.length>0&&p>1?p*Math.log2(p)*_e:void 0;return{plan:{...t,table:T[0],joinedTables:N,selectExprs:B,isOrderSatisfied:P},orderedTables:T,metrics:{totalCost:I,estimatedRows:p,joinOrder:T.map(L=>L.name),singleTableFilters:o,crossFilters:a,tableScanTypes:g,tableIndexNames:d,isOrderSatisfied:P,sortCostAvoided:F},isOrderSatisfied:P,sortCostAvoided:F}}}class $o{constructor(){U(this,"name","noop")}optimize(t){var g,d;const n=[t.table,...((g=t.joinedTables)==null?void 0:g.map(I=>I.table))??[]],s=n.length,i=zt(t.filters),r=mn(i),o=new Map,a=[];for(let I=0;I<s;I++)o.set(I,[]);for(const I of r){const p=dn(I,n);if(p.size===1){const y=p.values().next().value;y!==void 0&&((d=o.get(y))==null||d.push(I))}else a.push(I)}const c=de(n[0],o.get(0)??[]),l=[c.scanType],u=[c.indexName];let _=c.cost;const A=c.rows;if(t.joinedTables)for(let I=1;I<s;I++){const p=t.joinedTables[I-1],y=Ms(p,n[I],I,n,I);y?(l.push("IndexScan"),u.push(y.index.name),_+=A*.55):(l.push("TableScan"),u.push(void 0),_+=A*(2+(n[I].rowCountEstimate||10)*.1))}const f=Vn(t,n);return{plan:{...t,selectExprs:f},orderedTables:n,metrics:{totalCost:_,estimatedRows:A,joinOrder:n.map(I=>I.name),singleTableFilters:o,crossFilters:a,tableScanTypes:l,tableIndexNames:u}}}}class lc{constructor(t){U(this,"name","custom-order");U(this,"orderSpec");this.orderSpec=t}optimize(t){var B,P,F;const n=[t.table,...((B=t.joinedTables)==null?void 0:B.map(w=>w.table))??[]],s=n.length,i=t.joinedTables!==void 0&&t.joinedTables.length>0,r=zt(t.filters),o=mn(r),a=new Map,c=[];for(let w=0;w<s;w++)a.set(w,[]);for(const w of o){const S=dn(w,n);if(S.size===1){const v=S.values().next().value;v!==void 0&&((P=a.get(v))==null||P.push(w))}else c.push(w)}if(!i||s<=1){const w=de(n[0],a.get(0)??[]);return{plan:t,orderedTables:n,metrics:{totalCost:w.cost,estimatedRows:w.rows,joinOrder:[n[0].name],singleTableFilters:a,crossFilters:c,tableScanTypes:[w.scanType],tableIndexNames:[w.indexName]}}}const l=Array.from({length:s},(w,S)=>S);if(this.orderSpec){if(typeof this.orderSpec=="function"){const w=this.orderSpec;l.sort((S,v)=>w(n[S],n[v]))}else if(Array.isArray(this.orderSpec)){const w=this.orderSpec;l.sort((S,v)=>{const L=n[S].name,h=n[v].name,b=w.indexOf(L),k=w.indexOf(h),$=b===-1?9999:b,j=k===-1?9999:k;return $!==j?$-j:S-v})}}const{edges:u}=Rs(t,n),_=l.map(w=>n[w]),A=Fs(l,n,u,t.joinedTables),f=Vn(t,n),g={...t,table:_[0],joinedTables:A,selectExprs:f},d=new Map;for(let w=0;w<s;w++)d.set(w,[]);for(const w of o){const S=dn(w,_);if(S.size===1){const v=S.values().next().value;v!==void 0&&((F=d.get(v))==null||F.push(w))}}const I=de(_[0],d.get(0)??[]),p=[I.scanType],y=[I.indexName];let T=I.cost;const N=I.rows;if(g.joinedTables)for(let w=1;w<s;w++){const S=g.joinedTables[w-1],v=Ms(S,_[w],w,_,w);v?(p.push("IndexScan"),y.push(v.index.name),T+=N*.55):(p.push("TableScan"),y.push(void 0),T+=N*(2+(_[w].rowCountEstimate||10)*.1))}return{plan:g,orderedTables:_,metrics:{totalCost:T,estimatedRows:N,joinOrder:_.map(w=>w.name),singleTableFilters:d,crossFilters:c,tableScanTypes:p,tableIndexNames:y}}}}class xo{constructor(t){U(this,"name","custom");this.fn=t}optimize(t){return this.fn(t)}}const cc=xo,uc=Ds,fc=Ds,Ac=Vo,hc=$o,gc=new Ds;function ji(e){return e??gc}function _c(e,t){return ji(t).optimize(e)}function $n(e){if(!e)return m.OP_EQ;switch(String(e).trim().toLowerCase().replace(/\s+/g," ")){case"=":case"==":return m.OP_EQ;case"!=":case"<>":return m.OP_NE;case">":return m.OP_GT;case">=":return m.OP_GE;case"<":return m.OP_LT;case"<=":return m.OP_LE;case"like":return m.OP_STR_LIKE;case"not like":return m.OP_STR_NOT_LIKE;case"contains":return m.OP_STR_CONTAINS;case"starts_with":return m.OP_STR_STARTS_WITH;case"ends_with":return m.OP_STR_ENDS_WITH;default:return m.OP_EQ}}class Qs{constructor(){U(this,"buffer",[]);U(this,"textEncoder",new TextEncoder)}emitUint8(t){const n=this.buffer.length;return this.buffer.push(t&255),n}emitUint16(t){const n=this.buffer.length;return this.buffer.push(t&255),this.buffer.push(t>>8&255),n}emitUint32(t){const n=this.buffer.length;return this.buffer.push(t&255),this.buffer.push(t>>8&255),this.buffer.push(t>>16&255),this.buffer.push(t>>24&255),n}emitInt32(t){return this.emitUint32(t)}emitFloat64(t){const n=this.buffer.length,s=new ArrayBuffer(8);new DataView(s).setFloat64(0,t,!0);const i=new Uint8Array(s);for(let r=0;r<8;r++)this.buffer.push(i[r]);return n}emitString(t){const n=this.textEncoder.encode(t),s=this.emitUint16(n.byteLength);for(let i=0;i<n.byteLength;i++)this.buffer.push(n[i]);return s}emitBytes(t){const n=this.emitUint16(t.byteLength);for(let s=0;s<t.byteLength;s++)this.buffer.push(t[s]);return n}patchUint16(t,n){this.buffer[t]=n&255,this.buffer[t+1]=n>>8&255}currentOffset(){return this.buffer.length}toByteArray(){return new Uint8Array(this.buffer)}}function Bt(e,t,n,s,i){i===C.INT32||i===C.INT64?(e.emitUint8(m.OP_COLUMN_INT),e.emitUint8(t),e.emitUint8(n),e.emitUint8(s)):i===C.FLOAT64?(e.emitUint8(m.OP_COLUMN_FLOAT),e.emitUint8(t),e.emitUint8(n),e.emitUint8(s)):i===C.TEXT?(e.emitUint8(m.OP_COLUMN_TEXT),e.emitUint8(t),e.emitUint8(n),e.emitUint8(s)):i===C.UUID?(e.emitUint8(m.OP_COLUMN_UUID),e.emitUint8(t),e.emitUint8(n),e.emitUint8(s)):i===C.ULID?(e.emitUint8(m.OP_COLUMN_ULID),e.emitUint8(t),e.emitUint8(n),e.emitUint8(s)):i===C.BLOB&&(e.emitUint8(m.OP_COLUMN_BLOB),e.emitUint8(t),e.emitUint8(n),e.emitUint8(s))}function Oe(e){if(e.type==="in"){if(e.values&&e.values.length>Dt)throw new RangeError(`WebDB: whereIn list exceeds maximum limit of ${Dt} elements`);return{type:"in",colName:e.colName,expr:e.expr,values:e.values?Array.from(new Set(e.values)):[],notIn:!!e.notIn}}if(e.type==="cmp"){const t=e.op?String(e.op).trim().toLowerCase():"";if(t==="in"||t==="not in"){const n=Array.isArray(e.value)?e.value:[e.value];if(n.length>Dt)throw new RangeError(`WebDB: whereIn list exceeds maximum limit of ${Dt} elements`);return{type:"in",colName:e.colName,expr:e.expr,values:Array.from(new Set(n)),notIn:t==="not in"}}}if(e.type==="and")return{type:"and",children:e.children?e.children.map(Oe):[]};if(e.type==="or")return{type:"or",children:e.children?e.children.map(Oe):[]};if(e.type==="not"){const t=e.child;if(!t)return e;if(t.type==="not"&&t.child)return Oe(t.child);if(t.type==="in")return{type:"in",colName:t.colName,expr:t.expr,values:t.values,notIn:!t.notIn};if(t.type==="and")return{type:"or",children:t.children?t.children.map(n=>Oe({type:"not",child:n})):[]};if(t.type==="or")return{type:"and",children:t.children?t.children.map(n=>Oe({type:"not",child:n})):[]};if(t.type==="null")return{type:"null",colName:t.colName,expr:t.expr,isNull:!t.isNull};if(t.type==="cmp"){const n=t.op?String(t.op).trim().toLowerCase():"";if(n==="in"||n==="not in")return Oe({type:"in",colName:t.colName,expr:t.expr,values:Array.isArray(t.value)?t.value:[t.value],notIn:n==="in"});const s={"=":"!=","!=":"=",">":"<=",">=":"<","<":">=","<=":">",like:"not like","not like":"like"};return t.op&&s[t.op]?{type:"cmp",colName:t.colName,op:s[t.op],value:t.value}:{type:"and",children:[{type:"null",colName:t.colName,isNull:!1},{type:"not",child:t}]}}}return e}function zt(e){if(!e||e.length===0)return null;const t=e.length===1?e[0]:{type:"and",children:e};return Oe(t)}function Xo(e){const t=[],n=new Set;function s(i){if(i.type==="null"||i.type==="cmp"||i.type==="expr"||i.type==="in")n.has(i)||(n.add(i),t.push(i));else if(i.type==="and"||i.type==="or"){if(i.children)for(const r of i.children)s(r)}else i.type==="not"&&i.child&&s(i.child)}return s(e),t}function mn(e){if(!e)return[];const t=[];function n(s){if(s.type==="and"&&s.children)for(const i of s.children)n(i);else(s.type==="cmp"||s.type==="in"||s.type==="null")&&t.push(s)}return n(e),t}function ht(e,t){if(e.includes(".")){const n=e.split("."),s=n[0],i=n[1],r=t.findIndex(a=>a.name.toLowerCase()===s.toLowerCase());if(r===-1)return null;const o=t[r].columns.findIndex(a=>a.name.toLowerCase()===i.toLowerCase());return o===-1?null:{tableIdx:r,cursor:r,colIdx:o,col:t[r].columns[o],table:t[r]}}for(let n=0;n<t.length;n++){const s=t[n].columns.findIndex(i=>i.name.toLowerCase()===e.toLowerCase());if(s!==-1)return{tableIdx:n,cursor:n,colIdx:s,col:t[n].columns[s],table:t[n]}}return null}function Ki(e,t,n,s,i,r,o,a){const c=o??[n];if(e.type==="expr"){const A=t*2,f=t*2+1;let g=50;const d=()=>{if(g>=64)throw new st(g);return g++};Z(e.expr,n,s,0,A,d,r,void 0,c),s.emitUint8(m.OP_LOAD_INT),s.emitUint8(f),s.emitInt32(1),s.emitUint8(m.OP_EQ),s.emitUint8(A),s.emitUint8(f),i.push(s.emitUint16(0));return}if(e.type==="null"){if(e.expr){const f=t*2;let g=50;const d=()=>{if(g>=64)throw new st(g);return g++};Z(e.expr,n,s,0,f,d,r,void 0,c),e.isNull?s.emitUint8(m.OP_REG_IS_NULL):s.emitUint8(m.OP_REG_IS_NOT_NULL),s.emitUint8(f),i.push(s.emitUint16(0));return}if(!e.colName)throw new Error("Filter leaf node missing colName");const A=ht(e.colName,c);if(!A)throw new Error(`Column "${e.colName}" not found in tables`);e.isNull?s.emitUint8(m.OP_IS_NULL):s.emitUint8(m.OP_IS_NOT_NULL),s.emitUint8(A.cursor),s.emitUint8(A.colIdx),i.push(s.emitUint16(0));return}if(e.type==="in"){if(!e.values||e.values.length===0){e.notIn&&(s.emitUint8(m.OP_JUMP),i.push(s.emitUint16(0)));return}const A=t*2;if(e.expr){let g=50;const d=()=>{if(g>=64)throw new st(g);return g++};Z(e.expr,n,s,0,A,d,r,void 0,c)}else{if(!e.colName)throw new Error("Filter IN leaf node missing colName");const g=ht(e.colName,c);if(g)Bt(s,g.cursor,g.colIdx,A,g.col.type);else try{const d=ft(e.colName);let I=50;Z(d,n,s,0,A,()=>{if(I>=64)throw new st(I);return I++},r,void 0,c)}catch{throw new Error(`Column "${e.colName}" not found in tables`)}}const f=(a==null?void 0:a.get(e))??0;if(!e.notIn)s.emitUint8(m.OP_IN),s.emitUint8(A),s.emitUint16(f),i.push(s.emitUint16(0));else{let g=-1;if(e.colName){const p=ht(e.colName,c);p&&(s.emitUint8(m.OP_IS_NULL),s.emitUint8(p.cursor),s.emitUint8(p.colIdx),g=s.emitUint16(0))}s.emitUint8(m.OP_IN),s.emitUint8(A),s.emitUint16(f);const d=s.emitUint16(0);s.emitUint8(m.OP_JUMP),i.push(s.emitUint16(0));const I=s.currentOffset();g!==-1&&s.patchUint16(g,I),s.patchUint16(d,I)}return}const l=t*2,u=t*2+1;if(e.expr){let A=50;const f=()=>{if(A>=64)throw new st(A);return A++};Z(e.expr,n,s,0,l,f,r,void 0,c)}else{if(!e.colName)throw new Error("Filter leaf node missing colName");const A=ht(e.colName,c);if(A)Bt(s,A.cursor,A.colIdx,l,A.col.type);else try{const f=ft(e.colName);let g=50;Z(f,n,s,0,l,()=>{if(g>=64)throw new st(g);return g++},r,void 0,c)}catch{throw new Error(`Column "${e.colName}" not found in tables`)}}const _=$n(e.op);s.emitUint8(_),s.emitUint8(l),s.emitUint8(u),i.push(s.emitUint16(0))}function Ji(e,t,n,s,i,r,o,a){const c=o??[n];if(e.type==="expr"){const f=t*2,g=t*2+1;let d=50;const I=()=>{if(d>=64)throw new st(d);return d++};Z(e.expr,n,s,0,f,I,r,void 0,c),s.emitUint8(m.OP_LOAD_INT),s.emitUint8(g),s.emitInt32(1),s.emitUint8(m.OP_EQ),s.emitUint8(f),s.emitUint8(g);const p=s.emitUint16(0);s.emitUint8(m.OP_JUMP),i.push(s.emitUint16(0)),s.patchUint16(p,s.currentOffset());return}if(e.type==="null"){if(e.expr){const g=t*2;let d=50;const I=()=>{if(d>=64)throw new st(d);return d++};Z(e.expr,n,s,0,g,I,r,void 0,c),e.isNull?s.emitUint8(m.OP_REG_IS_NOT_NULL):s.emitUint8(m.OP_REG_IS_NULL),s.emitUint8(g),i.push(s.emitUint16(0));return}if(!e.colName)throw new Error("Filter leaf node missing colName");const f=ht(e.colName,c);if(!f)throw new Error(`Column "${e.colName}" not found in tables`);e.isNull?s.emitUint8(m.OP_IS_NOT_NULL):s.emitUint8(m.OP_IS_NULL),s.emitUint8(f.cursor),s.emitUint8(f.colIdx),i.push(s.emitUint16(0));return}if(e.type==="in"){if(!e.values||e.values.length===0){e.notIn||(s.emitUint8(m.OP_JUMP),i.push(s.emitUint16(0)));return}const f=t*2;if(e.expr){let d=50;const I=()=>{if(d>=64)throw new st(d);return d++};Z(e.expr,n,s,0,f,I,r,void 0,c)}else{if(!e.colName)throw new Error("Filter IN leaf node missing colName");const d=ht(e.colName,c);if(d)Bt(s,d.cursor,d.colIdx,f,d.col.type);else try{const I=ft(e.colName);let p=50;Z(I,n,s,0,f,()=>{if(p>=64)throw new st(p);return p++},r,void 0,c)}catch{throw new Error(`Column "${e.colName}" not found in tables`)}}const g=(a==null?void 0:a.get(e))??0;if(e.notIn){if(e.colName){const d=ht(e.colName,c);d&&(s.emitUint8(m.OP_IS_NULL),s.emitUint8(d.cursor),s.emitUint8(d.colIdx),i.push(s.emitUint16(0)))}s.emitUint8(m.OP_IN),s.emitUint8(f),s.emitUint16(g),i.push(s.emitUint16(0))}else{if(e.colName){const p=ht(e.colName,c);p&&(s.emitUint8(m.OP_IS_NULL),s.emitUint8(p.cursor),s.emitUint8(p.colIdx),i.push(s.emitUint16(0)))}s.emitUint8(m.OP_IN),s.emitUint8(f),s.emitUint16(g);const d=s.emitUint16(0);s.emitUint8(m.OP_JUMP),i.push(s.emitUint16(0));const I=s.currentOffset();s.patchUint16(d,I)}return}const l=t*2,u=t*2+1;if(e.expr){let f=50;const g=()=>{if(f>=64)throw new st(f);return f++};Z(e.expr,n,s,0,l,g,r,void 0,c)}else{if(!e.colName)throw new Error("Filter leaf node missing colName");const f=ht(e.colName,c);if(f)Bt(s,f.cursor,f.colIdx,l,f.col.type);else try{const g=ft(e.colName);let d=50;Z(g,n,s,0,l,()=>{if(d>=64)throw new st(d);return d++},r,void 0,c)}catch{throw new Error(`Column "${e.colName}" not found in tables`)}}const _=$n(e.op);s.emitUint8(_),s.emitUint8(l),s.emitUint8(u);const A=s.emitUint16(0);s.emitUint8(m.OP_JUMP),i.push(s.emitUint16(0)),s.patchUint16(A,s.currentOffset())}function dc(e,t,n,s,i,r,o,a,c,l){o==="true"?Ji(e,t,n,s,r,a,c,l):o==="false"?Ki(e,t,n,s,i,a,c,l):(Ki(e,t,n,s,i,a,c,l),s.emitUint8(m.OP_JUMP),r.push(s.emitUint16(0)))}function xn(e,t,n,s,i,r,o,a,c,l){if(e.type==="cmp"||e.type==="null"||e.type==="expr"||e.type==="in"){const u=s.get(e)??0;dc(e,u,n,t,i,r,o,a,c,l);return}if(e.type==="not"){if(!e.child)return;const u=e.child,_=s.get(u)??0;o==="true"?Ki(u,_,n,t,r,a,c,l):o==="false"?Ji(u,_,n,t,i,a,c,l):(Ji(u,_,n,t,i,a,c,l),t.emitUint8(m.OP_JUMP),r.push(t.emitUint16(0)));return}if(e.type==="and"){const u=e.children??[];if(u.length===0){o==="false"&&(t.emitUint8(m.OP_JUMP),i.push(t.emitUint16(0)));return}for(let _=0;_<u.length;_++){const A=u[_];if(_===u.length-1)xn(A,t,n,s,i,r,o,a,c,l);else{const g=[];xn(A,t,n,s,g,r,"true",a,c,l);const d=t.currentOffset();for(const I of g)t.patchUint16(I,d)}}return}if(e.type==="or"){const u=e.children??[];if(u.length===0){o==="true"&&(t.emitUint8(m.OP_JUMP),r.push(t.emitUint16(0)));return}for(let _=0;_<u.length;_++){const A=u[_];if(_===u.length-1)xn(A,t,n,s,i,r,o,a,c,l);else{const g=[];xn(A,t,n,s,i,g,"false",a,c,l);const d=t.currentOffset();for(const I of g)t.patchUint16(I,d)}}return}}function mc(e,t,n,s,i,r,o){if(e.type==="cmp"){let a;const c=s(e.colName,e.expr);if(c!==void 0)a=c;else if(e.expr)a=i(),Z(e.expr,t,n,-1,a,i,o,s);else if(e.colName){a=i();const f=ft(e.colName);Z(f,t,n,-1,a,i,o,s)}else a=i(),n.emitUint8(m.OP_LOAD_NULL),n.emitUint8(a);const l=i(),u=e.value;u==null?(n.emitUint8(m.OP_LOAD_NULL),n.emitUint8(l)):typeof u=="number"?Number.isInteger(u)?(n.emitUint8(m.OP_LOAD_INT),n.emitUint8(l),n.emitInt32(u)):(n.emitUint8(m.OP_LOAD_FLOAT),n.emitUint8(l),n.emitFloat64(u)):typeof u=="string"?(n.emitUint8(m.OP_LOAD_TEXT),n.emitUint8(l),n.emitString(u)):typeof u=="boolean"?(n.emitUint8(m.OP_LOAD_INT),n.emitUint8(l),n.emitInt32(u?1:0)):typeof u=="bigint"&&(n.emitUint8(m.OP_LOAD_INT),n.emitUint8(l),n.emitInt32(Number(u)));const _=$n(e.op);n.emitUint8(_),n.emitUint8(a),n.emitUint8(l);const A=n.emitUint16(0);n.emitUint8(m.OP_JUMP),r.push(n.emitUint16(0)),n.patchUint16(A,n.currentOffset());return}if(e.type==="null"){let a;const c=s(e.colName,e.expr);if(c!==void 0)a=c;else if(e.expr)a=i(),Z(e.expr,t,n,-1,a,i,o,s);else if(e.colName){a=i();const l=ft(e.colName);Z(l,t,n,-1,a,i,o,s)}else a=i(),n.emitUint8(m.OP_LOAD_NULL),n.emitUint8(a);e.isNull?(n.emitUint8(m.OP_REG_IS_NOT_NULL),n.emitUint8(a),r.push(n.emitUint16(0))):(n.emitUint8(m.OP_REG_IS_NULL),n.emitUint8(a),r.push(n.emitUint16(0)));return}if(e.type==="expr"&&e.expr){const a=i();Z(e.expr,t,n,-1,a,i,o,s);const c=i();n.emitUint8(m.OP_LOAD_INT),n.emitUint8(c),n.emitInt32(1),n.emitUint8(m.OP_EQ),n.emitUint8(a),n.emitUint8(c);const l=n.emitUint16(0);n.emitUint8(m.OP_JUMP),r.push(n.emitUint16(0)),n.patchUint16(l,n.currentOffset());return}}function Yo(e,t,n,s,i,r,o){if(e.type==="cmp"){let a;const c=s(e.colName,e.expr);if(c!==void 0)a=c;else if(e.expr)a=i(),Z(e.expr,t,n,-1,a,i,o,s);else if(e.colName){a=i();const A=ft(e.colName);Z(A,t,n,-1,a,i,o,s)}else a=i(),n.emitUint8(m.OP_LOAD_NULL),n.emitUint8(a);const l=i(),u=e.value;u==null?(n.emitUint8(m.OP_LOAD_NULL),n.emitUint8(l)):typeof u=="number"?Number.isInteger(u)?(n.emitUint8(m.OP_LOAD_INT),n.emitUint8(l),n.emitInt32(u)):(n.emitUint8(m.OP_LOAD_FLOAT),n.emitUint8(l),n.emitFloat64(u)):typeof u=="string"?(n.emitUint8(m.OP_LOAD_TEXT),n.emitUint8(l),n.emitString(u)):typeof u=="boolean"?(n.emitUint8(m.OP_LOAD_INT),n.emitUint8(l),n.emitInt32(u?1:0)):typeof u=="bigint"&&(n.emitUint8(m.OP_LOAD_INT),n.emitUint8(l),n.emitInt32(Number(u)));const _=$n(e.op);n.emitUint8(_),n.emitUint8(a),n.emitUint8(l),r.push(n.emitUint16(0));return}if(e.type==="null"){let a;const c=s(e.colName,e.expr);if(c!==void 0)a=c;else if(e.expr)a=i(),Z(e.expr,t,n,-1,a,i,o,s);else if(e.colName){a=i();const l=ft(e.colName);Z(l,t,n,-1,a,i,o,s)}else a=i(),n.emitUint8(m.OP_LOAD_NULL),n.emitUint8(a);e.isNull?(n.emitUint8(m.OP_REG_IS_NULL),n.emitUint8(a),r.push(n.emitUint16(0))):(n.emitUint8(m.OP_REG_IS_NOT_NULL),n.emitUint8(a),r.push(n.emitUint16(0)));return}if(e.type==="expr"&&e.expr){const a=i();Z(e.expr,t,n,-1,a,i,o,s);const c=i();n.emitUint8(m.OP_LOAD_INT),n.emitUint8(c),n.emitInt32(1),n.emitUint8(m.OP_EQ),n.emitUint8(a),n.emitUint8(c),r.push(n.emitUint16(0));return}}function Ec(e,t,n,s,i,r,o,a,c){a==="true"?mc(e,t,n,s,i,o,c):a==="false"?Yo(e,t,n,s,i,r,c):(Yo(e,t,n,s,i,r,c),n.emitUint8(m.OP_JUMP),o.push(n.emitUint16(0)))}function Pe(e,t,n,s,i,r,o,a,c){if(e.type==="cmp"||e.type==="null"||e.type==="expr"){Ec(e,n,t,s,i,r,o,a,c);return}if(e.type==="not"){if(!e.child)return;const l=e.child;a==="true"?Pe(l,t,n,s,i,o,r,"false",c):a==="false"?Pe(l,t,n,s,i,r,o,"true",c):Pe(l,t,n,s,i,o,r,"none",c);return}if(e.type==="and"){const l=e.children??[];if(l.length===0){a==="false"&&(t.emitUint8(m.OP_JUMP),r.push(t.emitUint16(0)));return}for(let u=0;u<l.length;u++){const _=l[u];if(u===l.length-1)Pe(_,t,n,s,i,r,o,a,c);else{const f=[];Pe(_,t,n,s,i,f,o,"true",c);const g=t.currentOffset();for(const d of f)t.patchUint16(d,g)}}return}if(e.type==="or"){const l=e.children??[];if(l.length===0){a==="true"&&(t.emitUint8(m.OP_JUMP),o.push(t.emitUint16(0)));return}for(let u=0;u<l.length;u++){const _=l[u];if(u===l.length-1)Pe(_,t,n,s,i,r,o,a,c);else{const f=[];Pe(_,t,n,s,i,r,f,"false",c);const g=t.currentOffset();for(const d of f)t.patchUint16(d,g)}}return}}function Ic(e,t,n,s,i,r,o){if(!e)return;const a=[];Pe(e,n,t,s,i,a,r,"true",o);const c=n.currentOffset();for(const l of a)n.patchUint16(l,c)}function te(e,t,n,s,i,r,o,a){if(!e)return;const c=[];xn(e,n,t,s,c,i,"true",r,o,a);const l=n.currentOffset();for(const u of c)n.patchUint16(u,l)}function Zo(e,t,n,s){if(e.type==="literal")return typeof e.value=="number"?Number.isInteger(e.value)?C.INT32:C.FLOAT64:(typeof e.value=="string",C.TEXT);if(e.type==="col"){const i=s??[t],r=ht(e.name,i);return r?r.col.type:C.TEXT}if(e.type==="binary")return C.FLOAT64;if(e.type==="fn"){const i=e.name.toLowerCase();if(n&&n.has(i)){const r=n.get(i);if(r.returnType!==void 0)return r.returnType}if(["upper","lower","substr","trim","concat"].includes(i))return C.TEXT;if(["length","count","starts_with","startswith","ends_with","endswith","like","contains"].includes(i))return C.INT32;if(["abs","round","floor","ceil","sum","avg","min","max"].includes(i)){if(e.args.length>0&&e.args[0].type==="col"){const r=ht(e.args[0].name,s??[t]);if(r&&r.col.type===C.INT32&&i!=="avg")return C.INT32}return C.FLOAT64}return C.TEXT}return C.TEXT}function Z(e,t,n,s,i,r,o,a,c){if(a){const l=e.type==="col"?e.name:void 0,u=a(l,e);if(u!==void 0){u!==i&&(n.emitUint8(m.OP_COPY),n.emitUint8(u),n.emitUint8(i));return}}if(e.type==="literal"){const l=e.value;l==null?(n.emitUint8(m.OP_LOAD_NULL),n.emitUint8(i)):typeof l=="number"?Number.isInteger(l)?(n.emitUint8(m.OP_LOAD_INT),n.emitUint8(i),n.emitInt32(l)):(n.emitUint8(m.OP_LOAD_FLOAT),n.emitUint8(i),n.emitFloat64(l)):typeof l=="string"?(n.emitUint8(m.OP_LOAD_TEXT),n.emitUint8(i),n.emitString(l)):typeof l=="boolean"&&(n.emitUint8(m.OP_LOAD_INT),n.emitUint8(i),n.emitInt32(l?1:0));return}if(e.type==="col"){if(s===-1)throw new Error(`Column "${e.name}" in HAVING clause must be an aggregate or grouping column`);const l=c??[t],u=ht(e.name,l);if(!u){if(e.name==="*"){n.emitUint8(m.OP_LOAD_NULL),n.emitUint8(i);return}throw new Error(`Column "${e.name}" does not exist in table "${t.name}"`)}Bt(n,u.cursor,u.colIdx,i,u.col.type);return}if(e.type==="binary"){const l=r(),u=r();Z(e.left,t,n,s,l,r,o,a,c),Z(e.right,t,n,s,u,r,o,a,c);let _=m.OP_ADD;if(e.op==="+")_=m.OP_ADD;else if(e.op==="-")_=m.OP_SUB;else if(e.op==="*")_=m.OP_MUL;else if(e.op==="/")_=m.OP_DIV;else if(e.op==="%")_=m.OP_MOD;else if(e.op==="="||e.op==="!="||e.op==="<"||e.op==="<="||e.op===">"||e.op===">="){let A=m.OP_EQ;e.op==="="?A=m.OP_EQ:e.op==="!="?A=m.OP_NE:e.op==="<"?A=m.OP_LT:e.op==="<="?A=m.OP_LE:e.op===">"?A=m.OP_GT:e.op===">="&&(A=m.OP_GE),n.emitUint8(A),n.emitUint8(l),n.emitUint8(u);const f=n.emitUint16(0);n.emitUint8(m.OP_LOAD_INT),n.emitUint8(i),n.emitInt32(0),n.emitUint8(m.OP_JUMP);const g=n.emitUint16(0);n.patchUint16(f,n.currentOffset()),n.emitUint8(m.OP_LOAD_INT),n.emitUint8(i),n.emitInt32(1),n.patchUint16(g,n.currentOffset());return}n.emitUint8(_),n.emitUint8(l),n.emitUint8(u),n.emitUint8(i);return}if(e.type==="fn"){const l=e.name.toLowerCase(),u={upper:m.OP_STR_UPPER,lower:m.OP_STR_LOWER,length:m.OP_STR_LENGTH,trim:m.OP_STR_TRIM,abs:m.OP_MATH_ABS,round:m.OP_MATH_ROUND,floor:m.OP_MATH_FLOOR,ceil:m.OP_MATH_CEIL};if(u[l]){const A=r(),f=e.args[0]??{type:"literal",value:null};Z(f,t,n,s,A,r,o,a,c),n.emitUint8(u[l]),n.emitUint8(A),n.emitUint8(i);return}if(l==="substr"){const A=r(),f=r(),g=r();Z(e.args[0],t,n,s,A,r,o,a,c),Z(e.args[1]??{type:"literal",value:1},t,n,s,f,r,o,a,c),e.args[2]!==void 0?Z(e.args[2],t,n,s,g,r,o,a,c):(n.emitUint8(m.OP_LOAD_NULL),n.emitUint8(g)),n.emitUint8(m.OP_STR_SUBSTR),n.emitUint8(A),n.emitUint8(f),n.emitUint8(g),n.emitUint8(i);return}const _={starts_with:m.OP_STR_STARTS_WITH,startswith:m.OP_STR_STARTS_WITH,ends_with:m.OP_STR_ENDS_WITH,endswith:m.OP_STR_ENDS_WITH,like:m.OP_STR_LIKE,contains:m.OP_STR_CONTAINS};if(_[l]){const A=r(),f=r();Z(e.args[0]??{type:"literal",value:null},t,n,s,A,r,o,a,c),Z(e.args[1]??{type:"literal",value:""},t,n,s,f,r,o,a,c),n.emitUint8(_[l]),n.emitUint8(A),n.emitUint8(f);const g=n.emitUint16(0);n.emitUint8(m.OP_LOAD_INT),n.emitUint8(i),n.emitInt32(0),n.emitUint8(m.OP_JUMP);const d=n.emitUint16(0);n.patchUint16(g,n.currentOffset()),n.emitUint8(m.OP_LOAD_INT),n.emitUint8(i),n.emitInt32(1),n.patchUint16(d,n.currentOffset());return}if(l==="concat"||l==="coalesce"){const A=e.args.length,f=r();for(let d=1;d<A;d++)r();for(let d=0;d<A;d++)Z(e.args[d],t,n,s,f+d,r,o,a,c);const g=l==="concat"?m.OP_STR_CONCAT:m.OP_COALESCE;n.emitUint8(g),n.emitUint8(f),n.emitUint8(A),n.emitUint8(i);return}if(o&&o.has(l)){const A=o.get(l),f=e.args.length;let g=i;if(f>0){g=r();for(let d=1;d<f;d++)r();for(let d=0;d<f;d++)Z(e.args[d],t,n,s,g+d,r,o,a,c)}n.emitUint8(m.OP_CALL_UDF),n.emitUint16(A),n.emitUint8(g),n.emitUint8(f),n.emitUint8(i);return}throw new di(l)}}function zi(e,t,n,s){n==null?(e.emitUint8(m.OP_LOAD_NULL),e.emitUint8(t)):typeof n=="number"?s===C.FLOAT64||!Number.isInteger(n)?(e.emitUint8(m.OP_LOAD_FLOAT),e.emitUint8(t),e.emitFloat64(n)):(e.emitUint8(m.OP_LOAD_INT),e.emitUint8(t),e.emitInt32(Math.floor(n))):typeof n=="bigint"?(e.emitUint8(m.OP_LOAD_INT),e.emitUint8(t),e.emitInt32(Number(n))):typeof n=="string"?(e.emitUint8(m.OP_LOAD_TEXT),e.emitUint8(t),e.emitString(n)):typeof n=="boolean"&&(e.emitUint8(m.OP_LOAD_INT),e.emitUint8(t),e.emitInt32(n?1:0))}function vs(e){switch(e){case C.INT32:return-2147483648;case C.INT64:return-9223372036854775808n;case C.FLOAT64:return-1/0;case C.TEXT:case C.UUID:case C.ULID:return"";case C.BLOB:return new Uint8Array(0);default:return 0}}function tr(e,t,n,s){var a;if(!n||n.length===0)return!1;for(const c of n)if(c.direction==="desc")return!1;const i=e.columnIndices.map(c=>t.columns[c].name.toLowerCase());let r=0;if(s&&s.size>0)for(;r<i.length&&s.has(i[r]);)r++;let o=0;for(;r<i.length&&o<n.length;){const c=(a=n[o].colName)==null?void 0:a.toLowerCase();if(!c||c!==i[r])return!1;r++,o++}return o===n.length}function jo(e,t,n,s,i){if(!n||n.length===0)return!1;for(const r of n){if(r.direction==="desc")return!1;const o=r.colName;if(!o)return!1;if(s&&s.length>0){let a=ht(o,s);if(!a&&i){const c=i.find(l=>l.alias===o);c&&c.expr.type==="col"&&(a=ht(c.expr.name,s))}if(!a||a.tableIdx!==0)return!1}else{const a=o.includes(".")?o.slice(o.lastIndexOf(".")+1):o;if(!e.columns.some(l=>l.name.toLowerCase()===a.toLowerCase()))return!1}}return!0}function ks(e,t,n,s){if(!e.indexes||e.indexes.length===0)return null;const i=n??t,r=new Set;for(const a of t)a.type==="cmp"&&(a.op==="="||a.op===void 0)&&a.colName&&a.value!==void 0&&a.value!==null&&r.add(a.colName.toLowerCase());const o=a=>{if(s&&s.length>0){if(a.scanType==="point"&&a.index.flags&(It.PRIMARY|It.UNIQUE))a.satisfiesOrderBy=!0;else if(tr(a.index,e,s,r)){if(a.scanType==="multi_point"&&a.inValues){const c=s[0].direction==="desc"?-1:1;a.inValues.sort((l,u)=>typeof l=="number"&&typeof u=="number"?(l-u)*c:String(l).localeCompare(String(u))*c)}a.satisfiesOrderBy=!0}}return a};for(const a of e.indexes)if(a.flags&It.PRIMARY&&a.columnCount===1){const c=e.columns[a.columnIndices[0]];for(let l=0;l<t.length;l++){const u=t[l];if(u.type==="cmp"&&(u.op==="="||u.op===void 0)&&u.colName===c.name&&u.value!==void 0&&u.value!==null)return o({index:a,scanType:"point",seekFilter:u,filterIndex:i.indexOf(u),keyType:c.type});if(u.type==="in"&&!u.notIn&&u.colName===c.name&&Array.isArray(u.values)&&u.values.length>0){const _=Array.from(new Set(u.values.filter(A=>A!=null)));return o({index:a,scanType:"multi_point",seekFilter:u,filterIndex:i.indexOf(u),keyType:c.type,inValues:_})}}}for(const a of e.indexes)if(a.flags&It.UNIQUE&&a.columnCount===1){const c=e.columns[a.columnIndices[0]];for(let l=0;l<t.length;l++){const u=t[l];if(u.type==="cmp"&&(u.op==="="||u.op===void 0)&&u.colName===c.name&&u.value!==void 0&&u.value!==null)return o({index:a,scanType:"point",seekFilter:u,filterIndex:i.indexOf(u),keyType:c.type});if(u.type==="in"&&!u.notIn&&u.colName===c.name&&Array.isArray(u.values)&&u.values.length>0){const _=Array.from(new Set(u.values.filter(A=>A!=null)));return o({index:a,scanType:"multi_point",seekFilter:u,filterIndex:i.indexOf(u),keyType:c.type,inValues:_})}}}for(const a of e.indexes)if(a.columnCount>1){const c=[];let l=!0;for(let u=0;u<a.columnCount;u++){const _=e.columns[a.columnIndices[u]],A=t.find(f=>f.type==="cmp"&&(f.op==="="||f.op===void 0)&&f.colName===_.name&&f.value!==void 0&&f.value!==null);if(A)c.push(A);else{l=!1;break}}if(l){const u={};for(const A of c)u[A.colName]=A.value;const _=Cs(e.columns,a.columnIndices,a.columnCount,u);return o({index:a,scanType:"point",seekFilter:c[0],filterIndex:i.indexOf(c[0]),keyType:C.BLOB,compositeValue:_})}}for(const a of e.indexes)if(a.columnCount===1){const c=e.columns[a.columnIndices[0]];for(let l=0;l<t.length;l++){const u=t[l];if(u.type==="cmp"&&(u.op==="="||u.op===void 0)&&u.colName===c.name&&u.value!==void 0&&u.value!==null)return o({index:a,scanType:"range",seekFilter:u,filterIndex:i.indexOf(u),keyType:c.type})}}for(const a of e.indexes)if(a.columnCount===1){const c=e.columns[a.columnIndices[0]];for(let l=0;l<t.length;l++){const u=t[l];if(u.type==="cmp"&&(u.op===">="||u.op===">")&&u.colName===c.name&&u.value!==void 0&&u.value!==null)return o({index:a,scanType:"range",seekFilter:u,filterIndex:i.indexOf(u),keyType:c.type})}}if(s&&s.length>0){for(const a of e.indexes)if(tr(a,e,s,r))if(a.columnCount===1){const c=e.columns[a.columnIndices[0]];return{index:a,scanType:"range",seekFilter:void 0,filterIndex:-1,keyType:c.type,satisfiesOrderBy:!0}}else{const c={};for(let u=0;u<a.columnCount;u++){const _=e.columns[a.columnIndices[u]],A=t.find(f=>f.type==="cmp"&&(f.op==="="||f.op===void 0)&&f.colName===_.name&&f.value!==void 0&&f.value!==null);A?c[_.name]=A.value:c[_.name]=vs(_.type)}const l=Cs(e.columns,a.columnIndices,a.columnCount,c);return{index:a,scanType:"range",seekFilter:void 0,filterIndex:-1,keyType:C.BLOB,compositeValue:l,satisfiesOrderBy:!0}}}return null}function Ms(e,t,n,s,i){if(e.op!=="="||!t.indexes||t.indexes.length===0)return null;const r=ht(e.leftCol,s),o=ht(e.rightCol,s);if(!r||!o)return null;let a=null,c=null;if(r.tableIdx===n&&o.tableIdx<n?(a=r,c=o):o.tableIdx===n&&r.tableIdx<n&&(a=o,c=r),!a||!c)return null;let l=null,u=999;for(const A of t.indexes)if(A.columnCount===1&&A.columnIndices[0]===a.colIdx){const f=(A.flags&It.PRIMARY)!==0,g=(A.flags&It.UNIQUE)!==0,d=f?1:g?2:3;d<u&&(u=d,l=A)}if(!l)return null;const _=(l.flags&(It.PRIMARY|It.UNIQUE))!==0;return{index:l,isUnique:_,innerCol:a,outerCol:c,indexCursor:i}}function er(e,t){var qs,Tn,Ws,zo,ta,ea,na,sa,ia;const n=[e.table,...((qs=e.joinedTables)==null?void 0:qs.map(R=>R.table))??[]],i=ji((t==null?void 0:t.planner)??e.planner).optimize(e),r=i.orderedTables??n,o=i.whereMetrics,a=i.metrics;if(i.isAlwaysFalse){const R=new Qs;R.emitUint8(m.OP_HALT);const M=R.toByteArray();return e.outputColumns&&(M.outputColumns=e.outputColumns),M.allTables=r,M.whereMetrics=o,M}const c=i.plan;c!==e&&Object.assign(e,c);const l=e.joinedTables!==void 0&&e.joinedTables.length>0,u=zt(e.filters),_=u?Xo(u):[],A=mn(u),f=Array.from({length:r.length},()=>[]),g=new Set;if(l&&a)for(let R=0;R<r.length;R++){const M=n.indexOf(r[R]);if(M!==-1){const W=a.singleTableFilters.get(M)??[];if(R===0||e.joinedTables&&((Tn=e.joinedTables[R-1])==null?void 0:Tn.type)==="inner"){f[R]=W;for(const V of W)g.add(V)}}}const d=[];for(const R of A)g.has(R)||d.push(R);const I=zt(d),p=l&&jo(r[0],e.joinedTables,e.orderBy,r,e.selectExprs),y=p?e.orderBy.map(R=>{const M=R.colName??"",W=M.includes(".")?M.slice(M.lastIndexOf(".")+1):M;return{...R,colName:W}}):void 0,T=l?ks(r[0],f[0],_,y):null,N=p&&!!(T!=null&&T.satisfiesOrderBy);let B=r.length,P=-1;T&&B<16&&(P=B++);const F=new Array(r.length).fill(null);if(l&&e.joinedTables)for(let R=1;R<r.length;R++){const M=e.joinedTables[R-1];if(B<16){const W=Ms(M,r[R],R,r,B);W&&(F[R]=W,B++)}}const w=B;if(w>16)throw new rs(w,16);for(const R of A)if(R.type==="in"&&!R.notIn&&(!R.values||R.values.length===0)){const M=new Qs;M.emitUint8(m.OP_HALT);const W=M.toByteArray();return e.outputColumns&&(W.outputColumns=e.outputColumns),W}const S=[],v=new Map;for(const R of _)if(R.type==="in"){const M=S.length;v.set(R,M);const W=new Set;if(R.values)for(const V of R.values)V!=null&&(W.add(V),typeof V=="bigint"?W.add(Number(V)):typeof V=="number"&&Number.isSafeInteger(V)&&W.add(BigInt(V)));S.push(W)}const L=new Map;for(let R=0;R<_.length;R++)L.set(_[R],R);if(_.length*2>=64)throw new st(_.length*2);if(e.orderBy&&e.orderBy.length>8)throw new Mr(e.orderBy.length);if(e.groupBy&&e.groupBy.length>8)throw new Gr(e.groupBy.length);const h=new Qs;if(e.limit!==void 0&&e.limit<=0)return h.emitUint8(m.OP_HALT),h.toByteArray();let b=_.length*2;const k=e.offset!==void 0&&e.offset>0,$=e.limit!==void 0&&e.limit>0,j=k?b++:-1,J=$?b++:-1;if(b>=64)throw new st(b);const G=e.table;for(let R=0;R<_.length;R++){const M=_[R];if(M.type==="cmp"){const W=R*2+1,V=M.value;if(V==null)h.emitUint8(m.OP_LOAD_NULL),h.emitUint8(W);else if(typeof V=="number"){const _t=M.colName?ht(M.colName,r):void 0;_t&&_t.col.type===C.FLOAT64?(h.emitUint8(m.OP_LOAD_FLOAT),h.emitUint8(W),h.emitFloat64(V)):Number.isInteger(V)?(h.emitUint8(m.OP_LOAD_INT),h.emitUint8(W),h.emitInt32(Math.floor(V))):(h.emitUint8(m.OP_LOAD_FLOAT),h.emitUint8(W),h.emitFloat64(V))}else typeof V=="bigint"?(h.emitUint8(m.OP_LOAD_INT),h.emitUint8(W),h.emitInt32(Number(V))):typeof V=="string"?(h.emitUint8(m.OP_LOAD_TEXT),h.emitUint8(W),h.emitString(V)):typeof V=="boolean"&&(h.emitUint8(m.OP_LOAD_INT),h.emitUint8(W),h.emitInt32(V?1:0))}}if(k&&(h.emitUint8(m.OP_LOAD_INT),h.emitUint8(j),h.emitInt32(e.offset)),$&&(h.emitUint8(m.OP_LOAD_INT),h.emitUint8(J),h.emitInt32(e.limit)),e.aggregates&&e.aggregates.length>0||e.groupBy&&e.groupBy.length>0){const R=((Ws=e.groupBy)==null?void 0:Ws.length)??0,M=e.aggregates??[],W=M.length,V=[];for(const Q of e.groupBy??[]){const H=typeof Q=="string"?Q:Q.colName??(Q.expr?Qt(Q.expr):"group_key"),X=(zo=e.selectExprs)==null?void 0:zo.find(At=>{if(At.alias===H)return!0;if(typeof Q=="object"&&Q.expr)return JSON.stringify(At.expr)===JSON.stringify(Q.expr);if(typeof Q=="string"&&Q.includes("("))try{const jt=ft(Q);return JSON.stringify(At.expr)===JSON.stringify(jt)}catch{return!1}return!1}),Y=(X==null?void 0:X.alias)??H,K=G.columns.find(At=>At.name===H||At.name===Y);K?V.push({...K,name:Y}):V.push({name:Y,type:C.TEXT,flags:tt.NONE,colOffset:0})}for(let Q=0;Q<M.length;Q++){const H=M[Q],X=H.alias??(H.colName?`${H.func}_${H.colName}`:H.func),Y=H.func==="count"?C.INT32:C.FLOAT64;V.push({name:X,type:Y,flags:tt.NONE,colOffset:0})}const z=b,et=z+R,rt=et+4,dt=rt+4,nt=dt+R,Ot=nt+W;if(Ot>=64)throw new st(Ot);h.emitUint8(m.OP_AGG_INIT),h.emitUint8(0),h.emitUint8(z),h.emitUint8(R),h.emitUint8(0),h.emitUint8(m.OP_OPEN_CURSOR),h.emitUint8(0),h.emitUint32(G.rootPageId),h.emitUint8(m.OP_REWIND),h.emitUint8(0);const Rt=h.emitUint16(0),at=h.currentOffset(),Nt=[];if(te(u,G,h,L,Nt,e.udfNameMap,void 0,v),e.groupBy)for(let Q=0;Q<e.groupBy.length;Q++){const H=e.groupBy[Q],X=z+Q;let Y=Math.max(Ot+4,40);const K=()=>{if(Y>=64)throw new st(Y);return Y++};if(typeof H=="object"&&H.expr)Z(H.expr,G,h,0,X,K,e.udfNameMap);else{const At=typeof H=="string"?H:H.colName,jt=(ea=(ta=e.selectExprs)==null?void 0:ta.find(pt=>pt.alias===At))==null?void 0:ea.expr;if(jt)Z(jt,G,h,0,X,K,e.udfNameMap);else{const pt=G.columns.findIndex(Ft=>Ft.name===At);if(pt!==-1){const Ft=G.columns[pt];Bt(h,0,pt,X,Ft.type)}else try{const Ft=ft(At);Z(Ft,G,h,0,X,K,e.udfNameMap)}catch{throw new Error(`Grouping column "${At}" not found in table "${G.name}"`)}}}}W===0&&R>0&&(h.emitUint8(m.OP_AGG_STEP),h.emitUint8(0),h.emitUint8(z),h.emitUint8(R),h.emitUint8(255),h.emitUint8(0));const Yt=M.some(Q=>Q.func==="count"),Gt=M.some(Q=>Q.func==="avg"),Be=M.some(Q=>Q.func==="sum"),ae=M.some(Q=>Q.func==="min"),bt=M.some(Q=>Q.func==="max");if(Yt||Gt||Be){const Q=M.find(X=>X.func==="count");let H=255;if(Q&&Q.colName&&Q.colName!=="*"){const X=G.columns.findIndex(Y=>Y.name===Q.colName);if(X!==-1){const Y=G.columns[X];H=et,Bt(h,0,X,H,Y.type)}}h.emitUint8(m.OP_AGG_STEP),h.emitUint8(0),h.emitUint8(z),h.emitUint8(R),h.emitUint8(H),h.emitUint8(0)}if(Be||Gt){const Q=M.find(X=>X.func==="sum"||X.func==="avg");let H=255;if(Q&&Q.colName&&Q.colName!=="*"){const X=G.columns.findIndex(Y=>Y.name===Q.colName);if(X!==-1){const Y=G.columns[X];H=et+1,Bt(h,0,X,H,Y.type)}}h.emitUint8(m.OP_AGG_STEP),h.emitUint8(0),h.emitUint8(z),h.emitUint8(R),h.emitUint8(H),h.emitUint8(1)}if(ae){const Q=M.find(X=>X.func==="min");let H=255;if(Q&&Q.colName&&Q.colName!=="*"){const X=G.columns.findIndex(Y=>Y.name===Q.colName);if(X!==-1){const Y=G.columns[X];H=et+2,Bt(h,0,X,H,Y.type)}}h.emitUint8(m.OP_AGG_STEP),h.emitUint8(0),h.emitUint8(z),h.emitUint8(R),h.emitUint8(H),h.emitUint8(3)}if(bt){const Q=M.find(X=>X.func==="max");let H=255;if(Q&&Q.colName&&Q.colName!=="*"){const X=G.columns.findIndex(Y=>Y.name===Q.colName);if(X!==-1){const Y=G.columns[X];H=et+3,Bt(h,0,X,H,Y.type)}}h.emitUint8(m.OP_AGG_STEP),h.emitUint8(0),h.emitUint8(z),h.emitUint8(R),h.emitUint8(H),h.emitUint8(4)}const me=h.currentOffset();for(const Q of Nt)h.patchUint16(Q,me);h.emitUint8(m.OP_NEXT_ROW),h.emitUint8(0);const D=h.emitUint16(0);h.emitUint8(m.OP_JUMP),h.emitUint16(at);const mt=h.currentOffset();h.patchUint16(Rt,mt),h.patchUint16(D,mt);const lt=h.currentOffset();h.emitUint8(m.OP_AGG_NEXT),h.emitUint8(0),h.emitUint8(dt),h.emitUint8(rt);const kt=h.emitUint16(0),St=h.currentOffset();h.emitUint8(m.OP_HALT);const Zt=h.currentOffset();h.patchUint16(kt,Zt);for(let Q=0;Q<M.length;Q++){const H=M[Q],X=nt+Q;let Y=rt,K=0;H.func==="count"?(Y=rt,K=0):H.func==="sum"?(Y=rt,K=1):H.func==="avg"?(Y=rt,K=2):H.func==="min"?(Y=rt+2,K=3):H.func==="max"&&(Y=rt+3,K=4),h.emitUint8(m.OP_AGG_FINAL),h.emitUint8(Y),h.emitUint8(rt+1),h.emitUint8(X),h.emitUint8(K)}const Cn=(Q,H)=>{var X;for(let Y=0;Y<M.length;Y++){const K=M[Y],At=nt+Y;if(Q&&(K.alias&&K.alias===Q||(K.colName?`${K.func}_${K.colName}`:K.func)===Q||`${K.func}(${K.colName??"*"})`===Q.replace(/\s+/g,"")||K.func===Q))return At;if(H&&H.type==="fn"){const jt=H.name.toLowerCase();if(K.func===jt)if(jt==="count"){const pt=H.args[0],Ft=pt&&pt.type==="col"?pt.name:void 0;if(K.colName===void 0||K.colName==="*"||K.colName===Ft)return At}else{const pt=H.args[0],Ft=pt&&pt.type==="col"?pt.name:void 0;if(K.colName===Ft)return At}}}if(e.groupBy)for(let Y=0;Y<e.groupBy.length;Y++){const K=e.groupBy[Y],At=dt+Y,jt=typeof K=="string"?K:K.colName,pt=typeof K=="object"?K.expr:void 0;if(Q){if(jt===Q||pt&&Qt(pt)===Q)return At;const Ft=(X=e.selectExprs)==null?void 0:X.find(ir=>ir.alias===Q);if(Ft){if(jt===Ft.alias||pt&&JSON.stringify(pt)===JSON.stringify(Ft.expr))return At;if(typeof K=="string"&&K.includes("("))try{const ir=ft(K);if(JSON.stringify(ir)===JSON.stringify(Ft.expr))return At}catch{}}}if(H){if(pt&&JSON.stringify(pt)===JSON.stringify(H)||H.type==="col"&&jt===H.name)return At;if(typeof K=="string"&&K.includes("("))try{const Ft=ft(K);if(JSON.stringify(Ft)===JSON.stringify(H))return At}catch{}}}};if(e.having&&e.having.length>0){let Q=null;e.having.length===1?Q=e.having[0]:Q={type:"and",children:e.having};const H=[];let X=Math.max(Ot+4,40);Ic(Q,G,h,Cn,()=>{if(X>=64)throw new st(X);return X++},H,e.udfNameMap);for(const K of H)h.patchUint16(K,lt)}k&&(h.emitUint8(m.OP_OFFSET),h.emitUint8(j),h.emitUint16(lt)),h.emitUint8(m.OP_RESULT_ROW),h.emitUint8(dt),h.emitUint8(R+W),$&&(h.emitUint8(m.OP_LIMIT),h.emitUint8(J),h.emitUint16(St)),h.emitUint8(m.OP_JUMP),h.emitUint16(lt);const Le=h.toByteArray();return Le.outputColumns=V,Le.inSets=S,e.outputColumns=V,Le}const q=l?null:ks(G,A,_,e.orderBy);if(!l&&e.orderBy&&e.orderBy.length>0&&!(q!=null&&q.satisfiesOrderBy)){const R=e.orderBy.length,M=b,W=M+R;if(W>=64)throw new st(W);const V={numKeys:R,directions:e.orderBy.map(at=>at.direction==="desc"?1:0),nullOrders:e.orderBy.map(at=>at.nullOrder==="nulls_last"?1:at.nullOrder==="nulls_first"?0:at.direction==="desc"?1:0),limit:e.limit,offset:e.offset};e.keyInfos=[V],h.emitUint8(m.OP_SORTER_OPEN),h.emitUint8(0),h.emitUint8(0),h.emitUint8(m.OP_OPEN_CURSOR),h.emitUint8(0),h.emitUint32(G.rootPageId),h.emitUint8(m.OP_REWIND),h.emitUint8(0);const _t=h.emitUint16(0),z=h.currentOffset(),et=[];te(u,G,h,L,et,e.udfNameMap,void 0,v);for(let at=0;at<R;at++){const Nt=e.orderBy[at],Yt=M+at;let Gt=50;const Be=()=>{if(Gt>=64)throw new st(Gt);return Gt++};if(Nt.expr)Z(Nt.expr,G,h,0,Yt,Be,e.udfNameMap);else if(Nt.colName){const ae=Nt.colName,bt=(sa=(na=e.selectExprs)==null?void 0:na.find(me=>me.alias===ae))==null?void 0:sa.expr;if(bt)Z(bt,G,h,0,Yt,Be,e.udfNameMap);else{const me=G.columns.findIndex(D=>D.name===ae);if(me!==-1){const D=G.columns[me];Bt(h,0,me,Yt,D.type)}else try{const D=ft(ae);Z(D,G,h,0,Yt,Be,e.udfNameMap)}catch{throw new Error(`Order by column "${ae}" not found in table "${G.name}"`)}}}}h.emitUint8(m.OP_SORTER_INSERT),h.emitUint8(0),h.emitUint8(M),h.emitUint8(R),h.emitUint8(0);const rt=h.currentOffset();for(const at of et)h.patchUint16(at,rt);h.emitUint8(m.OP_NEXT_ROW),h.emitUint8(0);const dt=h.emitUint16(0);h.emitUint8(m.OP_JUMP),h.emitUint16(z);const nt=h.currentOffset();h.patchUint16(_t,nt),h.patchUint16(dt,nt),h.emitUint8(m.OP_SORTER_SORT),h.emitUint8(0);const Ot=h.currentOffset();h.emitUint8(m.OP_SORTER_NEXT),h.emitUint8(0),h.emitUint16(Ot),h.emitUint8(m.OP_HALT);const Rt=h.toByteArray();return Rt.keyInfos=e.keyInfos,Rt.inSets=S,a&&(Rt.planMetrics=a,Rt.estimatedCost=a.totalCost,Rt.estimatedRows=a.estimatedRows,Rt.joinOrder=a.joinOrder),Rt}const ee=e.selectExprs!==void 0&&e.selectExprs.length>0&&!(e.selectExprs.length===1&&e.selectExprs[0].expr.type==="col"&&e.selectExprs[0].expr.name==="*");let Et=[];if(ee)Et=e.selectExprs;else if(l){const R=new Set,M=new Set;for(const W of r)for(const V of W.columns)R.has(V.name.toLowerCase())&&M.add(V.name.toLowerCase()),R.add(V.name.toLowerCase());for(const W of r)for(const V of W.columns){const _t=M.has(V.name.toLowerCase())?`${W.name}.${V.name}`:V.name;Et.push({expr:{type:"col",name:`${W.name}.${V.name}`},alias:_t})}}let gt=-1;if(ee||l){const R=Et.map(M=>({name:M.alias,type:Zo(M.expr,G,e.udfDefs,r),flags:tt.NONE,colOffset:0}));if(e.outputColumns=R,gt=b,b+=Et.length,b>=64)throw new st(b)}if(l){const R=r.length,M=new Array(R);for(let D=1;D<R;D++)e.joinedTables[D-1].type==="left"&&(M[D]=b++);const W=b++,V=b++,_t=b++;let z=-1;if(T&&P!==-1)if(T.compositeValue){if(z=b++,b>=64)throw new st(b);h.emitUint8(m.OP_LOAD_BLOB),h.emitUint8(z),h.emitUint32(T.compositeValue.length),h.emitBytes(T.compositeValue)}else if(T.scanType==="multi_point"){if(z=b++,b>=64)throw new st(b)}else if(T.filterIndex>=0)z=T.filterIndex*2+1;else{if(z=b++,b>=64)throw new st(b);const D=vs(T.keyType);zi(h,z,D,T.keyType)}if(b>=64)throw new st(b);for(let D=0;D<R;D++)h.emitUint8(m.OP_OPEN_CURSOR),h.emitUint8(D),h.emitUint32(r[D].rootPageId);T&&P!==-1&&(h.emitUint8(m.OP_OPEN_INDEX),h.emitUint8(P),h.emitUint32(T.index.rootPageId));for(let D=1;D<R;D++){const mt=F[D];mt&&(h.emitUint8(m.OP_OPEN_INDEX),h.emitUint8(mt.indexCursor),h.emitUint32(mt.index.rootPageId))}const et=new Array(R),rt=new Array(R),dt=Array.from({length:R},()=>[]),nt=new Array(R),Ot=[];if(T&&P!==-1?T.scanType==="point"?(h.emitUint8(m.OP_INDEX_SEEK_EQ),h.emitUint8(P),h.emitUint8(0),h.emitUint8(z),h.emitUint8(T.keyType),et[0]=h.emitUint16(0)):(h.emitUint8(m.OP_INDEX_SEEK_GE),h.emitUint8(P),h.emitUint8(0),h.emitUint8(z),h.emitUint8(T.keyType),et[0]=h.emitUint16(0)):(h.emitUint8(m.OP_REWIND),h.emitUint8(0),et[0]=h.emitUint16(0)),rt[0]=h.currentOffset(),f[0]&&f[0].length>0){const D=zt(f[0]);te(D,r[0],h,L,dt[0],e.udfNameMap,r,v)}for(let D=1;D<R;D++){const mt=e.joinedTables[D-1],lt=F[D];if(mt.type==="left"&&(h.emitUint8(m.OP_LOAD_INT),h.emitUint8(M[D]),h.emitInt32(0)),lt&&lt.isUnique){if(Bt(h,lt.outerCol.cursor,lt.outerCol.colIdx,W,lt.outerCol.col.type),h.emitUint8(m.OP_INDEX_SEEK_EQ),h.emitUint8(lt.indexCursor),h.emitUint8(D),h.emitUint8(W),h.emitUint8(lt.outerCol.col.type),et[D]=h.emitUint16(0),rt[D]=h.currentOffset(),mt.type==="inner"&&f[D]&&f[D].length>0){const kt=zt(f[D]);te(kt,r[D],h,L,dt[D],e.udfNameMap,r,v)}mt.type==="left"&&(h.emitUint8(m.OP_LOAD_INT),h.emitUint8(M[D]),h.emitInt32(1))}else if(lt&&!lt.isUnique){Bt(h,lt.outerCol.cursor,lt.outerCol.colIdx,W,lt.outerCol.col.type),h.emitUint8(m.OP_INDEX_SEEK_GE),h.emitUint8(lt.indexCursor),h.emitUint8(D),h.emitUint8(W),h.emitUint8(lt.outerCol.col.type),et[D]=h.emitUint16(0),rt[D]=h.currentOffset(),Bt(h,D,lt.innerCol.colIdx,V,lt.innerCol.col.type),h.emitUint8(m.OP_EQ),h.emitUint8(W),h.emitUint8(V);const kt=h.emitUint16(0);if(h.emitUint8(m.OP_JUMP),dt[D].push(h.emitUint16(0)),h.patchUint16(kt,h.currentOffset()),mt.type==="inner"&&f[D]&&f[D].length>0){const St=zt(f[D]);te(St,r[D],h,L,dt[D],e.udfNameMap,r,v)}mt.type==="left"&&(h.emitUint8(m.OP_LOAD_INT),h.emitUint8(M[D]),h.emitInt32(1))}else{h.emitUint8(m.OP_REWIND),h.emitUint8(D),et[D]=h.emitUint16(0),rt[D]=h.currentOffset();const kt=ht(mt.leftCol,r);if(!kt)throw new Error(`Join column "${mt.leftCol}" not found in tables`);const St=ht(mt.rightCol,r);if(!St)throw new Error(`Join column "${mt.rightCol}" not found in tables`);Bt(h,kt.cursor,kt.colIdx,W,kt.col.type),Bt(h,St.cursor,St.colIdx,V,St.col.type);let Zt;switch(mt.op){case"=":Zt=m.OP_EQ;break;case"!=":Zt=m.OP_NE;break;case">":Zt=m.OP_GT;break;case">=":Zt=m.OP_GE;break;case"<":Zt=m.OP_LT;break;case"<=":Zt=m.OP_LE;break;default:Zt=m.OP_EQ}h.emitUint8(Zt),h.emitUint8(W),h.emitUint8(V);const Cn=h.emitUint16(0);if(h.emitUint8(m.OP_JUMP),dt[D].push(h.emitUint16(0)),h.patchUint16(Cn,h.currentOffset()),mt.type==="inner"&&f[D]&&f[D].length>0){const Le=zt(f[D]);te(Le,r[D],h,L,dt[D],e.udfNameMap,r,v)}mt.type==="left"&&(h.emitUint8(m.OP_LOAD_INT),h.emitUint8(M[D]),h.emitInt32(1))}}te(I,G,h,L,dt[R-1],e.udfNameMap,r,v);const at=!(e.orderBy!==void 0&&e.orderBy.length>0)||N;let Nt=-1;k&&at&&(h.emitUint8(m.OP_OFFSET),h.emitUint8(j),Nt=h.emitUint16(0));let Yt=b;const Gt=()=>{if(Yt>=64)throw new st(Yt);return Yt++};for(let D=0;D<Et.length;D++)Z(Et[D].expr,G,h,0,gt+D,Gt,e.udfNameMap,void 0,r);h.emitUint8(m.OP_RESULT_ROW),h.emitUint8(gt),h.emitUint8(Et.length),$&&at&&(h.emitUint8(m.OP_LIMIT),h.emitUint8(J),Ot.push(h.emitUint16(0)));for(let D=R-1;D>=1;D--){const mt=h.currentOffset();D===R-1&&Nt!==-1&&h.patchUint16(Nt,mt);for(const St of dt[D])h.patchUint16(St,mt);const lt=F[D];if(lt&&lt.isUnique){const St=h.currentOffset();h.patchUint16(et[D],St)}else if(lt&&!lt.isUnique){h.emitUint8(m.OP_INDEX_NEXT),h.emitUint8(lt.indexCursor),h.emitUint8(D),nt[D]=h.emitUint16(0),h.emitUint8(m.OP_JUMP),h.emitUint16(rt[D]);const St=h.currentOffset();h.patchUint16(et[D],St),h.patchUint16(nt[D],St)}else{h.emitUint8(m.OP_NEXT_ROW),h.emitUint8(D),nt[D]=h.emitUint16(0),h.emitUint8(m.OP_JUMP),h.emitUint16(rt[D]);const St=h.currentOffset();h.patchUint16(et[D],St),h.patchUint16(nt[D],St)}if(e.joinedTables[D-1].type==="left"){h.emitUint8(m.OP_LOAD_INT),h.emitUint8(_t),h.emitInt32(0),h.emitUint8(m.OP_EQ),h.emitUint8(M[D]),h.emitUint8(_t);const St=h.emitUint16(0);h.emitUint8(m.OP_JUMP);const Zt=h.emitUint16(0);h.patchUint16(St,h.currentOffset());for(let Q=0;Q<Et.length;Q++){const H=Et[Q];let X=-1;if(H.expr.type==="col"){const Y=ht(H.expr.name,r);Y&&(X=Y.tableIdx)}X>=D?(h.emitUint8(m.OP_LOAD_NULL),h.emitUint8(gt+Q)):Z(H.expr,G,h,0,gt+Q,Gt,e.udfNameMap,void 0,r)}const Cn=[];k&&at&&(h.emitUint8(m.OP_OFFSET),h.emitUint8(j),Cn.push(h.emitUint16(0))),h.emitUint8(m.OP_RESULT_ROW),h.emitUint8(gt),h.emitUint8(Et.length),$&&at&&(h.emitUint8(m.OP_LIMIT),h.emitUint8(J),Ot.push(h.emitUint16(0)));const Le=h.currentOffset();h.patchUint16(Zt,Le);for(const Q of Cn)h.patchUint16(Q,Le)}}const Be=h.currentOffset();for(const D of dt[0])h.patchUint16(D,Be);T&&P!==-1?T.scanType==="point"?(h.emitUint8(m.OP_JUMP),nt[0]=h.emitUint16(0)):(h.emitUint8(m.OP_INDEX_NEXT),h.emitUint8(P),h.emitUint8(0),nt[0]=h.emitUint16(0),h.emitUint8(m.OP_JUMP),h.emitUint16(rt[0])):(h.emitUint8(m.OP_NEXT_ROW),h.emitUint8(0),nt[0]=h.emitUint16(0),h.emitUint8(m.OP_JUMP),h.emitUint16(rt[0]));const ae=h.currentOffset();h.patchUint16(et[0],ae),h.patchUint16(nt[0],ae);for(const D of Ot)h.patchUint16(D,ae);h.emitUint8(m.OP_HALT);const bt=h.toByteArray();e.outputColumns&&(bt.outputColumns=e.outputColumns);const me=(ia=e.joinedTables)==null?void 0:ia.map((D,mt)=>{const lt=mt+1,kt=F[lt];return{tableIndex:lt,tableName:D.table.name,scanType:kt?"IndexScan":"TableScan",indexName:kt?kt.index.name:void 0}});return bt.joinedTableScans=me,bt.allTables=r,bt.inSets=S,bt.table0Scan=T,bt.isOrderSatisfied=N,N&&(e.isOrderSatisfied=!0),a&&(bt.planMetrics=a,bt.estimatedCost=a.totalCost,bt.estimatedRows=a.estimatedRows,bt.joinOrder=a.joinOrder),o&&(bt.whereMetrics=o),bt}if(q){let R;if(q.compositeValue){if(R=b++,R>=64)throw new st(R);h.emitUint8(m.OP_LOAD_BLOB),h.emitUint8(R),h.emitBytes(q.compositeValue)}else if(q.scanType==="multi_point"){if(R=b++,R>=64)throw new st(R)}else if(q.filterIndex>=0)R=q.filterIndex*2+1;else{if(R=b++,R>=64)throw new st(R);const M=vs(q.keyType);zi(h,R,M,q.keyType)}if(q.scanType==="point"){h.emitUint8(m.OP_OPEN_CURSOR),h.emitUint8(0),h.emitUint32(G.rootPageId),h.emitUint8(m.OP_OPEN_INDEX),h.emitUint8(1),h.emitUint32(q.index.rootPageId),h.emitUint8(m.OP_INDEX_SEEK_EQ),h.emitUint8(1),h.emitUint8(0),h.emitUint8(R),h.emitUint8(q.keyType);const M=h.emitUint16(0),W=[];te(u,G,h,L,W,e.udfNameMap,void 0,v);let V=-1;if(k&&(h.emitUint8(m.OP_OFFSET),h.emitUint8(j),V=h.emitUint16(0)),ee){let rt=b;const dt=()=>{if(rt>=64)throw new st(rt);return rt++};for(let nt=0;nt<e.selectExprs.length;nt++)Z(e.selectExprs[nt].expr,G,h,0,gt+nt,dt,e.udfNameMap);h.emitUint8(m.OP_RESULT_ROW),h.emitUint8(gt),h.emitUint8(e.selectExprs.length)}else h.emitUint8(m.OP_EMIT_ROW),h.emitUint8(0);h.emitUint8(m.OP_JUMP);const _t=h.emitUint16(0),z=h.currentOffset();h.patchUint16(M,z),h.patchUint16(_t,z),V!==-1&&h.patchUint16(V,z);for(const rt of W)h.patchUint16(rt,z);h.emitUint8(m.OP_HALT);const et=h.toByteArray();return et.indexScan=q,et.inSets=S,e.outputColumns&&(et.outputColumns=e.outputColumns),q!=null&&q.satisfiesOrderBy&&(et.isOrderSatisfied=!0,e.isOrderSatisfied=!0),a&&(et.planMetrics=a,et.estimatedCost=a.totalCost,et.estimatedRows=a.estimatedRows,et.joinOrder=a.joinOrder),et}else if(q.scanType==="multi_point"){const M=q.inValues?q.inValues.length:0;if(M===0){h.emitUint8(m.OP_HALT);const z=h.toByteArray();return z.indexScan=q,z.inSets=S,e.outputColumns&&(z.outputColumns=e.outputColumns),z}h.emitUint8(m.OP_OPEN_CURSOR),h.emitUint8(0),h.emitUint32(G.rootPageId),h.emitUint8(m.OP_OPEN_INDEX),h.emitUint8(1),h.emitUint32(q.index.rootPageId);const W=[];for(let z=0;z<M;z++){const et=q.inValues[z];zi(h,R,et,q.keyType),h.emitUint8(m.OP_INDEX_SEEK_EQ),h.emitUint8(1),h.emitUint8(0),h.emitUint8(R),h.emitUint8(q.keyType);const rt=h.emitUint16(0),dt=[];te(u,G,h,L,dt,e.udfNameMap,void 0,v);let nt=-1;if(k&&(h.emitUint8(m.OP_OFFSET),h.emitUint8(j),nt=h.emitUint16(0)),ee){let Nt=b;const Yt=()=>{if(Nt>=64)throw new st(Nt);return Nt++};for(let Gt=0;Gt<e.selectExprs.length;Gt++)Z(e.selectExprs[Gt].expr,G,h,0,gt+Gt,Yt,e.udfNameMap);h.emitUint8(m.OP_RESULT_ROW),h.emitUint8(gt),h.emitUint8(e.selectExprs.length)}else h.emitUint8(m.OP_EMIT_ROW),h.emitUint8(0);$&&(h.emitUint8(m.OP_LIMIT),h.emitUint8(J),W.push(h.emitUint16(0)));const Ot=z===M-1;let Rt=-1;Ot||(h.emitUint8(m.OP_JUMP),Rt=h.emitUint16(0));const at=h.currentOffset();h.patchUint16(rt,at);for(const Nt of dt)h.patchUint16(Nt,at);nt!==-1&&h.patchUint16(nt,at),Rt!==-1&&h.patchUint16(Rt,at)}const V=h.currentOffset();for(const z of W)h.patchUint16(z,V);h.emitUint8(m.OP_HALT);const _t=h.toByteArray();return _t.indexScan=q,_t.inSets=S,e.outputColumns&&(_t.outputColumns=e.outputColumns),q!=null&&q.satisfiesOrderBy&&(_t.isOrderSatisfied=!0,e.isOrderSatisfied=!0),a&&(_t.planMetrics=a,_t.estimatedCost=a.totalCost,_t.estimatedRows=a.estimatedRows,_t.joinOrder=a.joinOrder),_t}else{h.emitUint8(m.OP_OPEN_CURSOR),h.emitUint8(0),h.emitUint32(G.rootPageId),h.emitUint8(m.OP_OPEN_INDEX),h.emitUint8(1),h.emitUint32(q.index.rootPageId),h.emitUint8(m.OP_INDEX_SEEK_GE),h.emitUint8(1),h.emitUint8(0),h.emitUint8(R),h.emitUint8(q.keyType);const M=h.emitUint16(0),W=h.currentOffset(),V=[];te(u,G,h,L,V,e.udfNameMap,void 0,v);let _t=-1;if(k&&(h.emitUint8(m.OP_OFFSET),h.emitUint8(j),_t=h.emitUint16(0)),ee){let Ot=b;const Rt=()=>{if(Ot>=64)throw new st(Ot);return Ot++};for(let at=0;at<e.selectExprs.length;at++)Z(e.selectExprs[at].expr,G,h,0,gt+at,Rt,e.udfNameMap);h.emitUint8(m.OP_RESULT_ROW),h.emitUint8(gt),h.emitUint8(e.selectExprs.length)}else h.emitUint8(m.OP_EMIT_ROW),h.emitUint8(0);let z=-1;$&&(h.emitUint8(m.OP_LIMIT),h.emitUint8(J),z=h.emitUint16(0));const et=h.currentOffset();_t!==-1&&h.patchUint16(_t,et);for(const Ot of V)h.patchUint16(Ot,et);h.emitUint8(m.OP_INDEX_NEXT),h.emitUint8(1),h.emitUint8(0);const rt=h.emitUint16(0);h.emitUint8(m.OP_JUMP),h.emitUint16(W);const dt=h.currentOffset();h.patchUint16(M,dt),h.patchUint16(rt,dt),z!==-1&&h.patchUint16(z,dt),h.emitUint8(m.OP_HALT);const nt=h.toByteArray();return nt.indexScan=q,nt.inSets=S,e.outputColumns&&(nt.outputColumns=e.outputColumns),q!=null&&q.satisfiesOrderBy&&(nt.isOrderSatisfied=!0,e.isOrderSatisfied=!0),a&&(nt.planMetrics=a,nt.estimatedCost=a.totalCost,nt.estimatedRows=a.estimatedRows,nt.joinOrder=a.joinOrder),nt}}h.emitUint8(m.OP_OPEN_CURSOR),h.emitUint8(0),h.emitUint32(G.rootPageId),h.emitUint8(m.OP_REWIND),h.emitUint8(0);const En=h.emitUint16(0),In=h.currentOffset(),pn=[];te(u,G,h,L,pn,e.udfNameMap,void 0,v);let Ke=-1;if(k&&(h.emitUint8(m.OP_OFFSET),h.emitUint8(j),Ke=h.emitUint16(0)),ee){let R=b;const M=()=>{if(R>=64)throw new st(R);return R++};for(let W=0;W<e.selectExprs.length;W++)Z(e.selectExprs[W].expr,G,h,0,gt+W,M,e.udfNameMap);h.emitUint8(m.OP_RESULT_ROW),h.emitUint8(gt),h.emitUint8(e.selectExprs.length)}else h.emitUint8(m.OP_EMIT_ROW),h.emitUint8(0);let Ne=-1;$&&(h.emitUint8(m.OP_LIMIT),h.emitUint8(J),Ne=h.emitUint16(0));const Xn=h.currentOffset();Ke!==-1&&h.patchUint16(Ke,Xn);for(const R of pn)h.patchUint16(R,Xn);h.emitUint8(m.OP_NEXT_ROW),h.emitUint8(0);const be=h.emitUint16(0);h.emitUint8(m.OP_JUMP),h.emitUint16(In);const yn=h.currentOffset();h.patchUint16(En,yn),h.patchUint16(be,yn),Ne!==-1&&h.patchUint16(Ne,yn),h.emitUint8(m.OP_HALT);const oe=h.toByteArray();return oe.inSets=S,e.outputColumns&&(oe.outputColumns=e.outputColumns),o&&(oe.whereMetrics=o),a&&(oe.planMetrics=a,oe.estimatedCost=a.totalCost,oe.estimatedRows=a.estimatedRows,oe.joinOrder=a.joinOrder),oe}const pc=new TextDecoder;function Ko(e,t){const n=[],s=new DataView(e.buffer,e.byteOffset,e.byteLength);let i=0;const r=a=>{var c;return(c=t==null?void 0:t.columns[a])!=null&&c.name?`'${t.columns[a].name}'`:`col_${a}`},o=a=>`0x${a.toString(16).padStart(4,"0")}`;for(;i<e.byteLength;){const a=i,c=e[i++];switch(c){case m.OP_HALT:n.push({addr:a,opcode:"OP_HALT",p1:"",p2:"",p3:"",comment:"Halt VM execution (STATUS_DONE)"});break;case m.OP_OPEN_CURSOR:{const l=e[i++],u=s.getUint32(i,!0);i+=4,n.push({addr:a,opcode:"OP_OPEN_CURSOR",p1:`c[${l}]`,p2:`page=${u}`,p3:"",comment:`Open cursor ${l} on root page ${u}${t?` ('${t.name}')`:""}`});break}case m.OP_OPEN_INDEX:{const l=e[i++],u=s.getUint32(i,!0);i+=4,n.push({addr:a,opcode:"OP_OPEN_INDEX",p1:`c[${l}]`,p2:`page=${u}`,p3:"",comment:`Open index cursor ${l} on root page ${u}`});break}case m.OP_INDEX_SEEK_EQ:{const l=e[i++],u=e[i++],_=e[i++],A=e[i++],f=s.getUint16(i,!0);i+=2,n.push({addr:a,opcode:"OP_INDEX_SEEK_EQ",p1:`idx=c[${l}], data=c[${u}]`,p2:`key=r[${_}], type=${A}`,p3:o(f),comment:`Seek exact key in index; position data cursor or jump to ${o(f)} if not found`});break}case m.OP_INDEX_SEEK_GE:{const l=e[i++],u=e[i++],_=e[i++],A=e[i++],f=s.getUint16(i,!0);i+=2,n.push({addr:a,opcode:"OP_INDEX_SEEK_GE",p1:`idx=c[${l}], data=c[${u}]`,p2:`key=r[${_}], type=${A}`,p3:o(f),comment:`Seek first entry >= key in index; position data cursor or jump to ${o(f)} if EOF`});break}case m.OP_INDEX_NEXT:{const l=e[i++],u=e[i++],_=s.getUint16(i,!0);i+=2,n.push({addr:a,opcode:"OP_INDEX_NEXT",p1:`idx=c[${l}], data=c[${u}]`,p2:o(_),p3:"",comment:`Advance index cursor to next entry; jump to ${o(_)} if EOF`});break}case m.OP_REWIND:{const l=e[i++],u=s.getUint16(i,!0);i+=2,n.push({addr:a,opcode:"OP_REWIND",p1:`c[${l}]`,p2:o(u),p3:"",comment:`Rewind cursor to first row; jump to ${o(u)} if empty`});break}case m.OP_NEXT_ROW:{const l=e[i++],u=s.getUint16(i,!0);i+=2,n.push({addr:a,opcode:"OP_NEXT_ROW",p1:`c[${l}]`,p2:o(u),p3:"",comment:`Advance cursor to next row; jump to ${o(u)} if EOF`});break}case m.OP_LAST:{const l=e[i++],u=s.getUint16(i,!0);i+=2,n.push({addr:a,opcode:"OP_LAST",p1:`c[${l}]`,p2:o(u),p3:"",comment:`Position cursor to last row; jump to ${o(u)} if empty`});break}case m.OP_PREV_ROW:{const l=e[i++],u=s.getUint16(i,!0);i+=2,n.push({addr:a,opcode:"OP_PREV_ROW",p1:`c[${l}]`,p2:o(u),p3:"",comment:`Advance cursor to previous row; jump to ${o(u)} if BOF`});break}case m.OP_COLUMN_INT:{const l=e[i++],u=e[i++],_=e[i++];n.push({addr:a,opcode:"OP_COLUMN_INT",p1:`c[${l}]`,p2:`${u} (${r(u)})`,p3:`r[${_}]`,comment:`Read ${r(u)} as INT into r[${_}]`});break}case m.OP_COLUMN_FLOAT:{const l=e[i++],u=e[i++],_=e[i++];n.push({addr:a,opcode:"OP_COLUMN_FLOAT",p1:`c[${l}]`,p2:`${u} (${r(u)})`,p3:`r[${_}]`,comment:`Read ${r(u)} as FLOAT into r[${_}]`});break}case m.OP_COLUMN_TEXT:{const l=e[i++],u=e[i++],_=e[i++];n.push({addr:a,opcode:"OP_COLUMN_TEXT",p1:`c[${l}]`,p2:`${u} (${r(u)})`,p3:`r[${_}]`,comment:`Read ${r(u)} as TEXT into r[${_}]`});break}case m.OP_COLUMN_BLOB:{const l=e[i++],u=e[i++],_=e[i++];n.push({addr:a,opcode:"OP_COLUMN_BLOB",p1:`c[${l}]`,p2:`${u} (${r(u)})`,p3:`r[${_}]`,comment:`Read ${r(u)} as BLOB into r[${_}]`});break}case m.OP_COLUMN_UUID:{const l=e[i++],u=e[i++],_=e[i++];n.push({addr:a,opcode:"OP_COLUMN_UUID",p1:`c[${l}]`,p2:`${u} (${r(u)})`,p3:`r[${_}]`,comment:`Read ${r(u)} as UUID into r[${_}]`});break}case m.OP_COLUMN_ULID:{const l=e[i++],u=e[i++],_=e[i++];n.push({addr:a,opcode:"OP_COLUMN_ULID",p1:`c[${l}]`,p2:`${u} (${r(u)})`,p3:`r[${_}]`,comment:`Read ${r(u)} as ULID into r[${_}]`});break}case m.OP_IS_NULL:{const l=e[i++],u=e[i++],_=s.getUint16(i,!0);i+=2,n.push({addr:a,opcode:"OP_IS_NULL",p1:`c[${l}]`,p2:`${u} (${r(u)})`,p3:o(_),comment:`If ${r(u)} IS NULL -> jump to ${o(_)}`});break}case m.OP_IS_NOT_NULL:{const l=e[i++],u=e[i++],_=s.getUint16(i,!0);i+=2,n.push({addr:a,opcode:"OP_IS_NOT_NULL",p1:`c[${l}]`,p2:`${u} (${r(u)})`,p3:o(_),comment:`If ${r(u)} IS NOT NULL -> jump to ${o(_)}`});break}case m.OP_EQ:case m.OP_NE:case m.OP_GT:case m.OP_GE:case m.OP_LT:case m.OP_LE:{const l={[m.OP_EQ]:"OP_EQ",[m.OP_NE]:"OP_NE",[m.OP_GT]:"OP_GT",[m.OP_GE]:"OP_GE",[m.OP_LT]:"OP_LT",[m.OP_LE]:"OP_LE"},u={[m.OP_EQ]:"==",[m.OP_NE]:"!=",[m.OP_GT]:">",[m.OP_GE]:">=",[m.OP_LT]:"<",[m.OP_LE]:"<="},_=e[i++],A=e[i++],f=s.getUint16(i,!0);i+=2,n.push({addr:a,opcode:l[c],p1:`r[${_}]`,p2:`r[${A}]`,p3:o(f),comment:`If r[${_}] ${u[c]} r[${A}] -> jump to ${o(f)}`});break}case m.OP_JUMP:{const l=s.getUint16(i,!0);i+=2,n.push({addr:a,opcode:"OP_JUMP",p1:o(l),p2:"",p3:"",comment:`Unconditional jump to ${o(l)}`});break}case m.OP_STR_LIKE:case m.OP_STR_NOT_LIKE:case m.OP_STR_CONTAINS:case m.OP_STR_STARTS_WITH:case m.OP_STR_ENDS_WITH:{const l={[m.OP_STR_LIKE]:"OP_STR_LIKE",[m.OP_STR_NOT_LIKE]:"OP_STR_NOT_LIKE",[m.OP_STR_CONTAINS]:"OP_STR_CONTAINS",[m.OP_STR_STARTS_WITH]:"OP_STR_STARTS_WITH",[m.OP_STR_ENDS_WITH]:"OP_STR_ENDS_WITH"},u={[m.OP_STR_LIKE]:"LIKE",[m.OP_STR_NOT_LIKE]:"NOT LIKE",[m.OP_STR_CONTAINS]:"CONTAINS",[m.OP_STR_STARTS_WITH]:"STARTS_WITH",[m.OP_STR_ENDS_WITH]:"ENDS_WITH"},_=e[i++],A=e[i++],f=s.getUint16(i,!0);i+=2,n.push({addr:a,opcode:l[c],p1:`r[${_}]`,p2:`r[${A}]`,p3:o(f),comment:`If r[${_}] ${u[c]} r[${A}] -> jump to ${o(f)}`});break}case m.OP_IN:{const l=e[i++],u=s.getUint16(i,!0);i+=2;const _=s.getUint16(i,!0);i+=2,n.push({addr:a,opcode:"OP_IN",p1:`r[${l}]`,p2:`set[${u}]`,p3:o(_),comment:`If r[${l}] IN set[${u}] -> jump to ${o(_)}`});break}case m.OP_LOAD_INT:{const l=e[i++],u=s.getInt32(i,!0);i+=4,n.push({addr:a,opcode:"OP_LOAD_INT",p1:`r[${l}]`,p2:`${u}`,p3:"",comment:`Load literal int ${u} into r[${l}]`});break}case m.OP_LOAD_FLOAT:{const l=e[i++],u=s.getFloat64(i,!0);i+=8,n.push({addr:a,opcode:"OP_LOAD_FLOAT",p1:`r[${l}]`,p2:`${u}`,p3:"",comment:`Load literal float ${u} into r[${l}]`});break}case m.OP_LOAD_TEXT:{const l=e[i++],u=s.getUint16(i,!0);i+=2;const _=new Uint8Array(e.buffer,e.byteOffset+i,u),A=pc.decode(_);i+=u,n.push({addr:a,opcode:"OP_LOAD_TEXT",p1:`r[${l}]`,p2:`"${A}"`,p3:"",comment:`Load literal text "${A}" into r[${l}]`});break}case m.OP_LOAD_BLOB:{const l=e[i++],u=s.getUint16(i,!0);i+=2+u,n.push({addr:a,opcode:"OP_LOAD_BLOB",p1:`r[${l}]`,p2:`len=${u}`,p3:"",comment:`Load literal BLOB (${u} bytes) into r[${l}]`});break}case m.OP_LOAD_NULL:{const l=e[i++];n.push({addr:a,opcode:"OP_LOAD_NULL",p1:`r[${l}]`,p2:"NULL",p3:"",comment:`Set r[${l}] to NULL`});break}case m.OP_EMIT_ROW:{const l=e[i++];n.push({addr:a,opcode:"OP_EMIT_ROW",p1:`c[${l}]`,p2:"",p3:"",comment:"Row passed all filters -> emit to Output Result Buffer"});break}case m.OP_RESULT_ROW:{const l=e[i++],u=e[i++];n.push({addr:a,opcode:"OP_RESULT_ROW",p1:`r[${l}]`,p2:`cols=${u}`,p3:"",comment:`Serialize registers r[${l}..${l+u-1}] to Result Buffer`});break}case m.OP_OFFSET:{const l=e[i++],u=s.getUint16(i,!0);i+=2,n.push({addr:a,opcode:"OP_OFFSET",p1:`r[${l}]`,p2:o(u),p3:"",comment:`If r[${l}] > 0 -> decrement and skip row to ${o(u)}`});break}case m.OP_LIMIT:{const l=e[i++],u=s.getUint16(i,!0);i+=2,n.push({addr:a,opcode:"OP_LIMIT",p1:`r[${l}]`,p2:o(u),p3:"",comment:`If r[${l}] <= 1 -> halt to ${o(u)}, else decrement`});break}case m.OP_CALL_UDF:{const l=s.getUint16(i,!0);i+=2;const u=e[i++],_=e[i++],A=e[i++];n.push({addr:a,opcode:"OP_CALL_UDF",p1:`udf#${l}`,p2:`r[${u}..${u+_-1}]`,p3:`r[${A}]`,comment:`Call UDF #${l} with ${_} args -> r[${A}]`});break}case m.OP_STR_LOWER:case m.OP_STR_UPPER:case m.OP_STR_LENGTH:case m.OP_STR_TRIM:case m.OP_MATH_ABS:case m.OP_MATH_ROUND:case m.OP_MATH_FLOOR:case m.OP_MATH_CEIL:{const l={[m.OP_STR_LOWER]:"OP_STR_LOWER",[m.OP_STR_UPPER]:"OP_STR_UPPER",[m.OP_STR_LENGTH]:"OP_STR_LENGTH",[m.OP_STR_TRIM]:"OP_STR_TRIM",[m.OP_MATH_ABS]:"OP_MATH_ABS",[m.OP_MATH_ROUND]:"OP_MATH_ROUND",[m.OP_MATH_FLOOR]:"OP_MATH_FLOOR",[m.OP_MATH_CEIL]:"OP_MATH_CEIL"},u=e[i++],_=e[i++];n.push({addr:a,opcode:l[c],p1:`r[${u}]`,p2:`r[${_}]`,p3:"",comment:`${l[c]}: r[${_}] = ${l[c].toLowerCase()}(r[${u}])`});break}case m.OP_STR_SUBSTR:{const l=e[i++],u=e[i++],_=e[i++],A=e[i++];n.push({addr:a,opcode:"OP_STR_SUBSTR",p1:`r[${l}]`,p2:`start=r[${u}], len=r[${_}]`,p3:`r[${A}]`,comment:`Extract substring from r[${l}] into r[${A}]`});break}case m.OP_ADD:case m.OP_SUB:case m.OP_MUL:case m.OP_DIV:case m.OP_MOD:{const l={[m.OP_ADD]:"OP_ADD",[m.OP_SUB]:"OP_SUB",[m.OP_MUL]:"OP_MUL",[m.OP_DIV]:"OP_DIV",[m.OP_MOD]:"OP_MOD"},u=e[i++],_=e[i++],A=e[i++];n.push({addr:a,opcode:l[c],p1:`r[${u}]`,p2:`r[${_}]`,p3:`r[${A}]`,comment:`${l[c]}: r[${A}] = r[${u}] ${l[c].replace("OP_","")} r[${_}]`});break}case m.OP_STR_CONCAT:case m.OP_COALESCE:{const l={[m.OP_STR_CONCAT]:"OP_STR_CONCAT",[m.OP_COALESCE]:"OP_COALESCE"},u=e[i++],_=e[i++],A=e[i++];n.push({addr:a,opcode:l[c],p1:`r[${u}..${u+_-1}]`,p2:`count=${_}`,p3:`r[${A}]`,comment:`${l[c]}: r[${A}]`});break}case m.OP_COPY:{const l=e[i++],u=e[i++];n.push({addr:a,opcode:"OP_COPY",p1:`r[${l}]`,p2:`r[${u}]`,p3:"",comment:`Copy r[${l}] to r[${u}]`});break}case m.OP_SORTER_OPEN:{const l=e[i++],u=e[i++];n.push({addr:a,opcode:"OP_SORTER_OPEN",p1:`s[${l}]`,p2:`keyInfo=${u}`,p3:"",comment:`Open sorter ${l} with keyInfo ${u}`});break}case m.OP_SORTER_INSERT:{const l=e[i++],u=e[i++],_=e[i++],A=e[i++];n.push({addr:a,opcode:"OP_SORTER_INSERT",p1:`s[${l}]`,p2:`r[${u}..+${_}]`,p3:`c[${A}]`,comment:`Insert row from cursor ${A} into sorter ${l}`});break}case m.OP_SORTER_SORT:{const l=e[i++];n.push({addr:a,opcode:"OP_SORTER_SORT",p1:`s[${l}]`,p2:"",p3:"",comment:`Sort entries in sorter ${l}`});break}case m.OP_SORTER_NEXT:{const l=e[i++],u=s.getUint16(i,!0);i+=2,n.push({addr:a,opcode:"OP_SORTER_NEXT",p1:`s[${l}]`,p2:o(u),p3:"",comment:`Emit next sorted row from sorter ${l}; jump to ${o(u)} while more rows`});break}case m.OP_AGG_INIT:{const l=e[i++],u=e[i++],_=e[i++],A=e[i++];n.push({addr:a,opcode:"OP_AGG_INIT",p1:`agg[${l}]`,p2:`keys=r[${u}..+${_}]`,p3:`mode=${A===0?"hash":"stream"}`,comment:`Initialize aggregator ${l} (${A===0?"hash table":"stream"})`});break}case m.OP_AGG_STEP:{const l=e[i++],u=e[i++],_=e[i++],A=e[i++],f=e[i++],g=["COUNT","SUM","AVG","MIN","MAX"];n.push({addr:a,opcode:"OP_AGG_STEP",p1:`agg[${l}]`,p2:`val=${A===255?"*":`r[${A}]`}`,p3:g[f]??`${f}`,comment:`Update accumulator ${g[f]??f} for group r[${u}..+${_}]`});break}case m.OP_AGG_NEXT:{const l=e[i++],u=e[i++],_=e[i++],A=s.getUint16(i,!0);i+=2,n.push({addr:a,opcode:"OP_AGG_NEXT",p1:`agg[${l}]`,p2:`out_keys=r[${u}], out_acc=r[${_}]`,p3:o(A),comment:`Iterate next group bucket; jump to ${o(A)}`});break}case m.OP_AGG_FINAL:{const l=e[i++],u=e[i++],_=e[i++],A=e[i++],f=["COUNT","SUM","AVG","MIN","MAX"];n.push({addr:a,opcode:"OP_AGG_FINAL",p1:`sum=r[${l}], cnt=r[${u}]`,p2:`r[${_}]`,p3:f[A]??`${A}`,comment:`Finalize ${f[A]??A} into r[${_}]`});break}case m.OP_REG_IS_NULL:{const l=e[i++],u=s.getUint16(i,!0);i+=2,n.push({addr:a,opcode:"OP_REG_IS_NULL",p1:`r[${l}]`,p2:o(u),p3:"",comment:`Jump to ${o(u)} if r[${l}] is NULL`});break}case m.OP_REG_IS_NOT_NULL:{const l=e[i++],u=s.getUint16(i,!0);i+=2,n.push({addr:a,opcode:"OP_REG_IS_NOT_NULL",p1:`r[${l}]`,p2:o(u),p3:"",comment:`Jump to ${o(u)} if r[${l}] is NOT NULL`});break}default:n.push({addr:a,opcode:`OP_UNKNOWN(0x${c.toString(16)})`,p1:"",p2:"",p3:"",comment:"Unknown opcode"});break}}return n}function Jo(e){const t=(i,r)=>i.padEnd(r," "),n=i=>`0x${i.toString(16).padStart(4,"0")}`;let s=`${t("ADDR",8)} ${t("OPCODE",18)} ${t("P1",12)} ${t("P2",20)} ${t("P3",10)} COMMENT
2
2
  `;s+="-".repeat(95)+`
3
- `;for(const i of t)s+=`${e(n(i.addr),8)} ${e(i.opcode,18)} ${e(i.p1,12)} ${e(i.p2,20)} ${e(i.p3,10)} ${i.comment}
4
- `;return s}function Ct(t){if(t instanceof st||typeof t=="object"&&t!==null&&"node"in t)return{expr:t.node};if(typeof t=="object"&&t!==null&&"type"in t)return{expr:t};if(typeof t=="string"){const e=t.trim();return e.includes("(")||e.includes("+")||e.includes("-")||e.includes("*")||e.includes("/")||e.includes("%")?{expr:ut(e),colName:e}:{colName:e}}return{}}function eo(t){const e=[];function n(s){if(s.type==="fn"){const i=s.name.toLowerCase();if(Ue(i)){const o=s.args[0],r=o&&o.type==="col"&&o.name!=="*"?o.name:void 0;e.push({func:i,colName:r})}for(const o of s.args)n(o)}else s.type==="binary"&&(n(s.left),n(s.right))}return n(t),e}function Gs(t){if(!t)return[];if(Array.isArray(t)){const e=[];for(const n of t)e.push(...Gs(n));return e}if(t instanceof st||typeof t=="object"&&t!==null&&"node"in t){const e=t.node;return[{alias:jt(e),expr:e,sourceCol:e.type==="col"&&e.name!=="*"?e.name:void 0,fn:e.type==="fn"?e.name:void 0}]}if(typeof t=="string"){const e=t.trim();if(!e)return[];const n=Ns(e);return[{alias:n.alias,expr:n.expr,sourceCol:n.expr.type==="col"&&n.expr.name!=="*"?n.expr.name:void 0,fn:n.expr.type==="fn"?n.expr.name:void 0}]}if(typeof t=="object"&&t!==null){if("expr"in t&&"alias"in t){const n=t.expr;return[{alias:t.alias,expr:n,sourceCol:n.type==="col"&&n.name!=="*"?n.name:void 0,fn:n.type==="fn"?n.name:void 0}]}if("col"in t&&"as"in t&&typeof t.col=="string"&&typeof t.as=="string"){const n=Ns(`${t.col} as ${t.as}`);return[{sourceCol:t.col==="*"?void 0:t.col,alias:t.as,expr:n.expr,fn:n.expr.type==="fn"?n.expr.name:void 0}]}const e=[];for(const[n,s]of Object.entries(t))if(typeof s=="string"){const i=Ns(`${n} as ${s}`);e.push({sourceCol:n==="*"?void 0:n,alias:s,expr:i.expr,fn:i.expr.type==="fn"?i.expr.name:void 0})}return e}return[]}function ct(t){if(typeof t=="string"){const e=t.trim();if(Ue(e))throw new os(e);if(e.includes("("))try{const n=ut(e);xe(n,"where")}catch(n){if(n instanceof os)throw n}}else t instanceof st||typeof t=="object"&&t!==null&&"node"in t?xe(t.node,"where"):typeof t=="object"&&t!==null&&"type"in t&&xe(t,"where")}class $t{constructor(e,n){S(this,"db");S(this,"tableName");S(this,"filters",[]);S(this,"selectFields",[]);S(this,"limitCount",null);S(this,"offsetCount",null);S(this,"sortCol",null);S(this,"sortDir","asc");S(this,"orderKeys",[]);S(this,"groupCols",[]);S(this,"groupKeys",[]);S(this,"aggExprs",[]);S(this,"havingFilters",[]);S(this,"joins",[]);S(this,"planner");this.db=e,this.tableName=n}withPlanner(e){return this.planner=e,this}join(e,n,s,i){const o=i!==void 0?s:"=",r=i!==void 0?i:s;return this.joins.push({type:"inner",table:e,leftCol:n,op:o,rightCol:r}),this}innerJoin(e,n,s,i){return this.join(e,n,s,i)}leftJoin(e,n,s,i){const o=i!==void 0?s:"=",r=i!==void 0?i:s;return this.joins.push({type:"left",table:e,leftCol:n,op:o,rightCol:r}),this}getJoins(){return this.joins}where(e,n,s){if(typeof e=="function"){const i=new $t(this.db,this.tableName);e(i);const o=i.getRootFilter();o&&this.filters.push(o)}else if(n===void 0&&s===void 0)if(typeof e=="string"){ct(e);const i=ut(e);this.filters.push({type:"expr",expr:i})}else e instanceof st||typeof e=="object"&&e!==null&&"node"in e?(ct(e),this.filters.push({type:"expr",expr:e.node})):typeof e=="object"&&e!==null&&"type"in e&&(ct(e),this.filters.push({type:"expr",expr:e}));else{if(ct(e),ct(s),typeof n=="string"&&n.trim().toLowerCase()==="in")return this.whereIn(e,s);if(typeof n=="string"&&n.trim().toLowerCase()==="not in")return this.whereNotIn(e,s);const i=Ct(e);this.filters.push({type:"cmp",colName:i.colName,expr:i.expr,op:n,value:s})}return this}orWhere(e,n,s){if(typeof e=="function"){const i=new $t(this.db,this.tableName);e(i);const o=i.getRootFilter();o&&this.addOrFilter(o)}else if(n===void 0&&s===void 0)if(typeof e=="string"){ct(e);const i=ut(e);this.addOrFilter({type:"expr",expr:i})}else e instanceof st||typeof e=="object"&&e!==null&&"node"in e?(ct(e),this.addOrFilter({type:"expr",expr:e.node})):typeof e=="object"&&e!==null&&"type"in e&&(ct(e),this.addOrFilter({type:"expr",expr:e}));else{if(ct(e),ct(s),typeof n=="string"&&n.trim().toLowerCase()==="in")return this.orWhereIn(e,s);if(typeof n=="string"&&n.trim().toLowerCase()==="not in")return this.orWhereNotIn(e,s);const i=Ct(e);this.addOrFilter({type:"cmp",colName:i.colName,expr:i.expr,op:n,value:s})}return this}whereNot(e,n,s){if(typeof e=="function"){const i=new $t(this.db,this.tableName);e(i);const o=i.getRootFilter();o&&this.filters.push({type:"not",child:o})}else if(n===void 0&&s===void 0)if(typeof e=="string"){ct(e);const i=ut(e);this.filters.push({type:"not",child:{type:"expr",expr:i}})}else e instanceof st||typeof e=="object"&&e!==null&&"node"in e?(ct(e),this.filters.push({type:"not",child:{type:"expr",expr:e.node}})):typeof e=="object"&&e!==null&&"type"in e&&(ct(e),this.filters.push({type:"not",child:{type:"expr",expr:e}}));else{ct(e),ct(s);const i=Ct(e);this.filters.push({type:"not",child:{type:"cmp",colName:i.colName,expr:i.expr,op:n,value:s}})}return this}orWhereNot(e,n,s){if(typeof e=="function"){const i=new $t(this.db,this.tableName);e(i);const o=i.getRootFilter();o&&this.addOrFilter({type:"not",child:o})}else if(n===void 0&&s===void 0)if(typeof e=="string"){ct(e);const i=ut(e);this.addOrFilter({type:"not",child:{type:"expr",expr:i}})}else e instanceof st||typeof e=="object"&&e!==null&&"node"in e?(ct(e),this.addOrFilter({type:"not",child:{type:"expr",expr:e.node}})):typeof e=="object"&&e!==null&&"type"in e&&(ct(e),this.addOrFilter({type:"not",child:{type:"expr",expr:e}}));else{ct(e),ct(s);const i=Ct(e);this.addOrFilter({type:"not",child:{type:"cmp",colName:i.colName,expr:i.expr,op:n,value:s}})}return this}whereRaw(e){return this.where(e)}orWhereRaw(e){return this.orWhere(e)}whereNull(e){return ct(e),this.filters.push({type:"null",colName:e,isNull:!0}),this}whereNotNull(e){return ct(e),this.filters.push({type:"null",colName:e,isNull:!1}),this}orWhereNull(e){return ct(e),this.addOrFilter({type:"null",colName:e,isNull:!0}),this}orWhereNotNull(e){return ct(e),this.addOrFilter({type:"null",colName:e,isNull:!1}),this}whereLike(e,n){return this.where(e,"like",n)}whereNotLike(e,n){return this.where(e,"not like",n)}whereStartsWith(e,n){return this.where(e,"starts_with",n)}whereEndsWith(e,n){return this.where(e,"ends_with",n)}whereContains(e,n){return this.where(e,"contains",n)}orWhereLike(e,n){return this.orWhere(e,"like",n)}orWhereNotLike(e,n){return this.orWhere(e,"not like",n)}orWhereStartsWith(e,n){return this.orWhere(e,"starts_with",n)}orWhereEndsWith(e,n){return this.orWhere(e,"ends_with",n)}orWhereContains(e,n){return this.orWhere(e,"contains",n)}whereIn(e,n){if(ct(e),!Array.isArray(n))throw new TypeError("WebDB: whereIn requires an array of values");if(n.length>kt)throw new RangeError(`WebDB: whereIn list exceeds maximum limit of ${kt} elements`);const s=Ct(e);return this.filters.push({type:"in",colName:s.colName,expr:s.expr,values:n,notIn:!1}),this}whereNotIn(e,n){if(ct(e),!Array.isArray(n))throw new TypeError("WebDB: whereNotIn requires an array of values");if(n.length>kt)throw new RangeError(`WebDB: whereNotIn list exceeds maximum limit of ${kt} elements`);const s=Ct(e);return this.filters.push({type:"in",colName:s.colName,expr:s.expr,values:n,notIn:!0}),this}orWhereIn(e,n){if(ct(e),!Array.isArray(n))throw new TypeError("WebDB: orWhereIn requires an array of values");if(n.length>kt)throw new RangeError(`WebDB: orWhereIn list exceeds maximum limit of ${kt} elements`);const s=Ct(e);return this.addOrFilter({type:"in",colName:s.colName,expr:s.expr,values:n,notIn:!1}),this}orWhereNotIn(e,n){if(ct(e),!Array.isArray(n))throw new TypeError("WebDB: orWhereNotIn requires an array of values");if(n.length>kt)throw new RangeError(`WebDB: orWhereNotIn list exceeds maximum limit of ${kt} elements`);const s=Ct(e);return this.addOrFilter({type:"in",colName:s.colName,expr:s.expr,values:n,notIn:!0}),this}getFilters(){return this.filters}getRootFilter(){return this.filters.length===0?null:this.filters.length===1?this.filters[0]:{type:"and",children:[...this.filters]}}addOrFilter(e){if(this.filters.length===0){this.filters.push(e);return}if(this.filters.length===1&&this.filters[0].type==="or"&&this.filters[0].children){this.filters[0].children.push(e);return}let n;this.filters.length===1?n=this.filters[0]:n={type:"and",children:[...this.filters]},this.filters=[{type:"or",children:[n,e]}]}limit(e){return this.limitCount=e,this}offset(e){return this.offsetCount=e,this}orderBy(e,n="asc",s){if(typeof e=="string"){this.sortCol=e,this.sortDir=n;const i=Ct(e);this.orderKeys.push({colName:i.colName??e,expr:i.expr,direction:n,nullOrder:s})}else if(e instanceof st||typeof e=="object"&&e!==null&&"node"in e)this.orderKeys.push({expr:e.node,direction:n,nullOrder:s});else if(typeof e=="object"&&e!==null&&"type"in e)this.orderKeys.push({expr:e,direction:n,nullOrder:s});else if(Array.isArray(e))for(const i of e)if(typeof i=="string"){const o=Ct(i);this.orderKeys.push({colName:o.colName??i,expr:o.expr,direction:"asc"})}else this.orderKeys.push(i);else this.orderKeys.push(e);return this}groupBy(...e){for(const n of e)if(Array.isArray(n))for(const s of n)this.addGroupByItem(s);else this.addGroupByItem(n);return this}addGroupByItem(e){if(e instanceof st||typeof e=="object"&&e!==null&&"node"in e)this.groupKeys.push({expr:e.node}),this.groupCols.push(jt(e.node));else if(typeof e=="object"&&e!==null&&"type"in e)this.groupKeys.push({expr:e}),this.groupCols.push(jt(e));else if(typeof e=="string"){const n=Ct(e);this.groupKeys.push({colName:n.colName??e,expr:n.expr}),this.groupCols.push(e)}}registerAggregatesFromFilter(e){const n=(s,i)=>{if(i){const o=eo(i);for(const r of o)this.aggExprs.some(l=>l.func===r.func&&(l.colName===r.colName||l.colName===void 0&&r.colName===void 0))||this.aggExprs.push(r)}else if(s&&s.includes("("))try{const o=ut(s),r=eo(o);for(const a of r)this.aggExprs.some(c=>c.func===a.func&&(c.colName===a.colName||c.colName===void 0&&a.colName===void 0))||this.aggExprs.push(a)}catch{}};if(e.type==="cmp")n(e.colName,e.expr);else if(e.type==="expr"&&e.expr)n(void 0,e.expr);else if(e.type==="null")n(e.colName,e.expr);else if(e.type==="not"&&e.child)this.registerAggregatesFromFilter(e.child);else if((e.type==="and"||e.type==="or")&&e.children)for(const s of e.children)this.registerAggregatesFromFilter(s)}having(e,n,s){if(typeof e=="function"){const i=new $t(this.db,this.tableName);e(i);const o=i.getRootHavingFilter();o&&(this.havingFilters.push(o),this.registerAggregatesFromFilter(o))}else if(n===void 0&&s===void 0){if(typeof e=="string"){const o={type:"expr",expr:ut(e)};this.havingFilters.push(o),this.registerAggregatesFromFilter(o)}else if(e instanceof st||typeof e=="object"&&e!==null&&"node"in e){const i={type:"expr",expr:e.node};this.havingFilters.push(i),this.registerAggregatesFromFilter(i)}else if(typeof e=="object"&&e!==null&&"type"in e){const i={type:"expr",expr:e};this.havingFilters.push(i),this.registerAggregatesFromFilter(i)}}else{const i=Ct(e),o={type:"cmp",colName:i.colName,expr:i.expr,op:n,value:s};this.havingFilters.push(o),this.registerAggregatesFromFilter(o)}return this}orHaving(e,n,s){if(typeof e=="function"){const i=new $t(this.db,this.tableName);e(i);const o=i.getRootHavingFilter();o&&(this.addHavingOrFilter(o),this.registerAggregatesFromFilter(o))}else if(n===void 0&&s===void 0){if(typeof e=="string"){const o={type:"expr",expr:ut(e)};this.addHavingOrFilter(o),this.registerAggregatesFromFilter(o)}else if(e instanceof st||typeof e=="object"&&e!==null&&"node"in e){const i={type:"expr",expr:e.node};this.addHavingOrFilter(i),this.registerAggregatesFromFilter(i)}else if(typeof e=="object"&&e!==null&&"type"in e){const i={type:"expr",expr:e};this.addHavingOrFilter(i),this.registerAggregatesFromFilter(i)}}else{const i=Ct(e),o={type:"cmp",colName:i.colName,expr:i.expr,op:n,value:s};this.addHavingOrFilter(o),this.registerAggregatesFromFilter(o)}return this}havingNot(e,n,s){if(typeof e=="function"){const i=new $t(this.db,this.tableName);e(i);const o=i.getRootHavingFilter();if(o){const r={type:"not",child:o};this.havingFilters.push(r),this.registerAggregatesFromFilter(r)}}else if(n===void 0&&s===void 0){if(typeof e=="string"){const o={type:"not",child:{type:"expr",expr:ut(e)}};this.havingFilters.push(o),this.registerAggregatesFromFilter(o)}else if(e instanceof st||typeof e=="object"&&e!==null&&"node"in e){const i={type:"not",child:{type:"expr",expr:e.node}};this.havingFilters.push(i),this.registerAggregatesFromFilter(i)}else if(typeof e=="object"&&e!==null&&"type"in e){const i={type:"not",child:{type:"expr",expr:e}};this.havingFilters.push(i),this.registerAggregatesFromFilter(i)}}else{const i=Ct(e),o={type:"not",child:{type:"cmp",colName:i.colName,expr:i.expr,op:n,value:s}};this.havingFilters.push(o),this.registerAggregatesFromFilter(o)}return this}orHavingNot(e,n,s){if(typeof e=="function"){const i=new $t(this.db,this.tableName);e(i);const o=i.getRootHavingFilter();if(o){const r={type:"not",child:o};this.addHavingOrFilter(r),this.registerAggregatesFromFilter(r)}}else if(n===void 0&&s===void 0){if(typeof e=="string"){const o={type:"not",child:{type:"expr",expr:ut(e)}};this.addHavingOrFilter(o),this.registerAggregatesFromFilter(o)}else if(e instanceof st||typeof e=="object"&&e!==null&&"node"in e){const i={type:"not",child:{type:"expr",expr:e.node}};this.addHavingOrFilter(i),this.registerAggregatesFromFilter(i)}else if(typeof e=="object"&&e!==null&&"type"in e){const i={type:"not",child:{type:"expr",expr:e}};this.addHavingOrFilter(i),this.registerAggregatesFromFilter(i)}}else{const i=Ct(e),o={type:"not",child:{type:"cmp",colName:i.colName,expr:i.expr,op:n,value:s}};this.addHavingOrFilter(o),this.registerAggregatesFromFilter(o)}return this}havingRaw(e){return this.having(e)}orHavingRaw(e){return this.orHaving(e)}havingNull(e){const n=Ct(e),s={type:"null",colName:n.colName,expr:n.expr,isNull:!0};return this.havingFilters.push(s),this.registerAggregatesFromFilter(s),this}havingNotNull(e){const n=Ct(e),s={type:"null",colName:n.colName,expr:n.expr,isNull:!1};return this.havingFilters.push(s),this.registerAggregatesFromFilter(s),this}orHavingNull(e){const n=Ct(e),s={type:"null",colName:n.colName,expr:n.expr,isNull:!0};return this.addHavingOrFilter(s),this.registerAggregatesFromFilter(s),this}orHavingNotNull(e){const n=Ct(e),s={type:"null",colName:n.colName,expr:n.expr,isNull:!1};return this.addHavingOrFilter(s),this.registerAggregatesFromFilter(s),this}getHavingFilters(){return this.havingFilters}getRootHavingFilter(){return this.havingFilters.length===0?null:this.havingFilters.length===1?this.havingFilters[0]:{type:"and",children:[...this.havingFilters]}}addHavingOrFilter(e){if(this.havingFilters.length===0){this.havingFilters.push(e);return}if(this.havingFilters.length===1&&this.havingFilters[0].type==="or"&&this.havingFilters[0].children){this.havingFilters[0].children.push(e);return}let n;this.havingFilters.length===1?n=this.havingFilters[0]:n={type:"and",children:[...this.havingFilters]},this.havingFilters=[{type:"or",children:[n,e]}]}aggregate(e){return this.aggExprs.push(...e),this}count(e,n){return this.aggExprs.push({func:"count",colName:e,alias:n}),this}sum(e,n){return this.aggExprs.push({func:"sum",colName:e,alias:n}),this}avg(e,n){return this.aggExprs.push({func:"avg",colName:e,alias:n}),this}min(e,n){return this.aggExprs.push({func:"min",colName:e,alias:n}),this}max(e,n){return this.aggExprs.push({func:"max",colName:e,alias:n}),this}select(e,...n){if(e===void 0)return this;const s=[];s.push(...Gs(e));for(const i of n)s.push(...Gs(i));this.selectFields.push(...s);for(const i of s)if(i.expr&&i.expr.type==="fn"){const o=i.expr.name.toLowerCase();if(Ue(o)&&!this.aggExprs.some(a=>a.alias===i.alias)){const a=i.expr.args[0],l=a&&a.type==="col"&&a.name!=="*"?a.name:void 0;this.aggExprs.push({func:o,colName:l,alias:i.alias})}}else if(typeof i.fn=="string"){const o=i.fn.toLowerCase();Ue(o)&&(this.aggExprs.some(a=>a.alias===i.alias)||this.aggExprs.push({func:o,colName:i.sourceCol==="*"?void 0:i.sourceCol,alias:i.alias}))}return this}getSelectFields(){return this.selectFields}projectRow(e){const n=Object.keys(e);if(this.selectFields.length>0&&n.length===this.selectFields.length&&this.selectFields.every(i=>i.alias in e))return e;const s={};for(const i of this.selectFields){const o=i.alias;if(e[o]!==void 0)s[o]=e[o];else if(i.expr&&e[jt(i.expr)]!==void 0)s[o]=e[jt(i.expr)];else if(i.sourceCol!==void 0&&e[i.sourceCol]!==void 0)s[o]=e[i.sourceCol];else if(i.expr){let r;typeof this.db.getUdf=="function"&&(r=a=>{var l,c;return(c=(l=this.db.getUdf(a))==null?void 0:l.def)==null?void 0:c.call}),s[o]=fe(i.expr,e,r)}else s[o]=null}return s}async explain(){const e=this.selectFields.map(n=>({expr:n.expr??{type:"col",name:n.sourceCol??n.alias},alias:n.alias}));return this.db.explainQuery(this.tableName,this.filters,{joins:this.joins.length>0?this.joins:void 0,orderBy:this.orderKeys.length>0?this.orderKeys:void 0,groupBy:this.groupKeys.length>0?this.groupKeys:this.groupCols.length>0?this.groupCols:void 0,aggregates:this.aggExprs.length>0?this.aggExprs:void 0,having:this.havingFilters.length>0?this.havingFilters:void 0,select:this.selectFields.length>0?this.selectFields:void 0,selectExprs:e.length>0?e:void 0,limit:this.limitCount!==null?this.limitCount:void 0,offset:this.offsetCount!==null?this.offsetCount:void 0,planner:this.planner})}getOrderKeyValue(e,n){const s=n.colName??(n.expr?jt(n.expr):void 0);if(!s)return;if(e[s]!==void 0)return e[s];const i=s.includes(".")?s.slice(s.lastIndexOf(".")+1):s;if(e[i]!==void 0)return e[i];if(this.selectFields.length>0){for(const o of this.selectFields)if((o.sourceCol===s||o.sourceCol===i||o.alias===s||o.alias===i)&&e[o.alias]!==void 0)return e[o.alias]}if(e[`__sort_${s}`]!==void 0)return e[`__sort_${s}`];if(e[`__sort_${i}`]!==void 0)return e[`__sort_${i}`]}sortAggregatedRows(e){return[...e].sort((n,s)=>{for(const i of this.orderKeys){const o=this.getOrderKeyValue(n,i),r=this.getOrderKeyValue(s,i);if(o===r)continue;if(o==null)return i.nullOrder==="nulls_first"?-1:1;if(r==null)return i.nullOrder==="nulls_first"?1:-1;const a=i.direction==="desc"?-1:1;return typeof o=="number"&&typeof r=="number"?(o-r)*a:String(o).localeCompare(String(r))*a}return 0})}async toArray(){const e=this.selectFields.map(l=>({expr:l.expr??{type:"col",name:l.sourceCol??l.alias},alias:l.alias})),n=this.joins.length>0,s=this.orderKeys.length>0,i=this.aggExprs.length>0||this.groupKeys.length>0||this.groupCols.length>0;if(n&&s&&e.length>0)for(const l of this.orderKeys){const c=l.colName;if(c){const u=c.includes(".")?c.slice(c.lastIndexOf(".")+1):c;this.selectFields.some(f=>f.alias===c||f.alias===u||f.sourceCol===c||f.sourceCol===u)||e.push({expr:{type:"col",name:c},alias:`__sort_${c}`})}}const o=await this.db.executeQuery(this.tableName,this.filters,{limit:n&&s&&i?null:this.limitCount,offset:n&&s&&i?null:this.offsetCount,sortCol:n?null:this.sortCol,sortDir:this.sortDir,orderBy:n&&i?void 0:s?this.orderKeys:void 0,joins:n?this.joins:void 0,groupBy:this.groupKeys.length>0?this.groupKeys:this.groupCols.length>0?this.groupCols:void 0,aggregates:this.aggExprs.length>0?this.aggExprs:void 0,having:this.havingFilters.length>0?this.havingFilters:void 0,select:this.selectFields.length>0?this.selectFields:void 0,selectExprs:e.length>0?e:void 0,planner:this.planner});let r=o;const a=o.isOrderSatisfied===!0;return(i||n)&&s&&!a&&(r=this.sortAggregatedRows(r),n&&(this.offsetCount!==null&&this.offsetCount>0&&(r=r.slice(this.offsetCount)),this.limitCount!==null&&this.limitCount>=0&&(r=r.slice(0,this.limitCount)))),this.selectFields.length>0&&(r=r.map(l=>this.projectRow(l))),r}async first(){const e=await this.limit(1).toArray();return e.length>0?e[0]:null}async update(e,n){if(!this.db.executeUpdate)throw new Error("Database executor does not support executeUpdate");return this.db.executeUpdate(this.tableName,this.filters,e,n)}async delete(e){if(!this.db.executeDelete)throw new Error("Database executor does not support executeDelete");return this.db.executeDelete(this.tableName,this.filters,e)}}class no{constructor(e,n,s,i,o="js",r,a,l){S(this,"vfs");S(this,"io");S(this,"driver");S(this,"coreMode");S(this,"wasmCore");S(this,"planner");S(this,"coordinator");S(this,"currentLeaseId",null);S(this,"vmCtx");S(this,"udfs",new Map);S(this,"nextUdfId",1);S(this,"tableMetaCache",new Map);S(this,"tableTailPages",new Map);S(this,"indexTailPages",new Map);S(this,"beforeCommitHooks",new Set);S(this,"commitHooks",new Set);S(this,"subscriptions",new Set);S(this,"activeTxChanges",[]);S(this,"activeTxOrigin","local");S(this,"activeTxMeta");S(this,"activeTxId",0);S(this,"nextAutoTxId",1e6);S(this,"isRunningBeforeCommit",!1);S(this,"broadcastChannel",null);S(this,"instanceId",Math.random().toString(36).slice(2)+Date.now().toString(36));if(this.vfs=e,this.io=n,this.driver=s,this.coordinator=i,this.coreMode=o,this.wasmCore=r,this.planner=a,this.vmCtx=Bo(),this.coordinator.setOnCrossTabInvalidated(async()=>{this.tableMetaCache.clear(),this.tableTailPages.clear(),this.indexTailPages.clear();const c=fn(this.driver.getSlotDataView(0));for(const u of c){let h=u.colCatalogPageId;for(;h!==0;){const f=await this.driver.acquireAndPinPage(h),_=this.driver.getSlotDataView(f);h=Ae(_,0).nextColCatalogPageId}}}),typeof BroadcastChannel<"u"&&l){const c=`webdb_sync_${e.name}_${l}`;this.broadcastChannel=new BroadcastChannel(c),this.broadcastChannel.onmessage=u=>{const h=u.data;if(!h||h.senderId===this.instanceId)return;const{tables:f,origin:_,meta:g,changeCounter:E,schemaVersion:I}=h;this.coordinator.leaseQueue.enqueue(async()=>{await this.coordinator.syncCrossTabState(!0),this.notifySubscriptions({tables:Array.isArray(f)?f:[],origin:_??"remote",meta:g,changeCounter:typeof E=="number"?E:this.getSyncState().changeCounter,schemaVersion:typeof I=="number"?I:this.getSyncState().schemaVersion,crossTab:!0})}).catch(()=>{})}}}get pool(){return this.driver}static async open(e){const n=e.storage||"memory";let s;e.vfs?s=e.vfs:n==="idb"?s=new Ho(e.name):n==="opfs"?s=new Wo(e.name):s=new Mo;const i=e.slotCount??be,o=e.maxQueryMemory??Qe,r=Lr(Math.max(i,be),o),a=new mi({vfs:s,memory:r}),l=new Rr({io:a,memory:r,slotCount:i,maxQueryMemory:o,useDefaultLayoutOffsets:!0}),c=e.name&&s.name!=="memory"?`webdb_lock_${s.name}_${e.name}`:void 0,u=new Fr(s,l,a,c);l.setTransactionCoordinator(u),await u.leaseQueue.enqueue(async()=>{await Wi(s);const g=await s.readPage(1);if(!g)Ir(l.getSlotDataView(0)),l.markDirty(0),await l.flushSlot(0);else{l.getPageBytesInSlot(0).set(g),l.clearDirty(0),Mn(l.getSlotDataView(0),!0);const E=fn(l.getSlotDataView(0));for(const I of E){let p=I.colCatalogPageId;for(;p!==0;){const y=await l.acquireAndPinPage(p),T=l.getSlotDataView(y);p=Ae(T,0).nextColCatalogPageId}}}u.recordDiskPage1State()});const h=e.core??"js";let f;h==="wasm"&&(f=Nr(r,e.wasmBinary?new Uint8Array(e.wasmBinary):void 0));const _=new no(s,a,l,u,h,f,e.planner,e.name);return e.initialData&&await _.importBinary(e.initialData),_}getPlanner(){return this.planner}setPlanner(e){return this.planner=e,this}validateIdentifier(e,n="Identifier"){if(!e||typeof e!="string"||e.length===0)throw new Error(`${n} cannot be empty`);if(e.length>te)throw new Ro(e,te)}async createTable(e,n){return this.coordinator.leaseQueue.enqueue(()=>this._createTableInternal(e,n),this.currentLeaseId??void 0)}async _createTableInternal(e,n){var g;if(this.validateIdentifier(e,"Table name"),n.length===0)throw new Error("Table must have at least one column");if(n.length>ce)throw new Ln(n.length,ce);const s=new Set;let i=!1;for(const E of n){if(this.validateIdentifier(E.name,"Column name"),s.has(E.name))throw new ns(E.name,e);s.add(E.name);const I=typeof E.flags=="number"?E.flags:0;(E.primaryKey||(g=E.flags)!=null&&g.primaryKey||I&z.PRIMARY_KEY)&&(i=!0)}const o=this.pool.getSlotDataView(0);if(Wt(o,e)!==-1)throw new ss(e);if(ki(o)===-1)throw new _i(ae,ae);const r=Math.ceil(n.length/pe),a=i&&Ps(o)!==-1?1:0,l=1+r+a,c=[];for(let E=0;E<l;E++)c.push(await this.driver.allocateAndPinPage());let u=0;const h={allocateNewPage:()=>{if(u<c.length)return c[u++];const I=o.getUint32(12,!0)+1;return o.setUint32(12,I,!0),this.pool.markDirty(0),I},getPageBytes:E=>{let I=this.pool.getResidentSlot(E);return I===-1&&(I=E<=this.pool.slotCount?E-1:1,this.pool.assignSlot(I,E)),this.pool.getPageBytesInSlot(I)},markPageDirty:E=>{const I=this.pool.getResidentSlot(E);I!==-1&&this.pool.markDirty(I)}};let f;try{f=Pr(o,h,e,n)}catch(E){for(const I of c)this.driver.forceUnpinPage(I),await this.driver.freePage(I,!0);throw E}this.driver.unpinPage(f.rootPageId);for(const E of f.indexes??[])E.rootPageId>1&&this.driver.unpinPage(E.rootPageId);let _=f.colCatalogPageId;for(;_!==0;){const E=await this.driver.acquirePage(_);this.pool.isSlotPinned(E)||this.pool.pinSlot(E),_=Ae(this.pool.getSlotDataView(E),0).nextColCatalogPageId}return this.coordinator.isInTransaction()||await this.driver.flushAllDirty(),this.tableMetaCache.delete(e.toLowerCase()),f}async getTable(e){return this.coordinator.leaseQueue.enqueue(()=>this._getTableInternal(e),this.currentLeaseId??void 0)}async _getTableInternal(e){const n=e.toLowerCase(),s=this.tableMetaCache.get(n);if(s)return s;const i=this.pool.getSlotDataView(0),o=Wt(i,e);if(o===-1)throw new Nn(e);let a=xt(i,o).colCatalogPageId;for(;a!==0;){await this.driver.acquirePage(a);const u=this.pool.getResidentSlot(a);a=Ae(this.pool.getSlotDataView(u),0).nextColCatalogPageId}const c=Mi(i,{getPageBytes:u=>{const h=this.pool.getResidentSlot(u);return h!==-1?this.pool.getPageBytesInSlot(h):new Uint8Array(4096)}},e);return this.tableMetaCache.set(n,c),c}async listTables(){return this.coordinator.leaseQueue.enqueue(async()=>{const e=this.pool.getSlotDataView(0),n=fn(e),s=[];for(const i of n)s.push(await this._getTableInternal(i.name));return s},this.currentLeaseId??void 0)}async freeTableTreePages(e){if(e<=1)return;const n=[],s=new Set,i=[e];for(;i.length>0;){const o=i.shift();if(o<=1||s.has(o))continue;s.add(o);const r=await this.driver.acquirePage(o),a=this.pool.getSlotDataView(r),l=Me(a,0);if(l===ve){this.driver.forceUnpinPage(o);continue}if(n.push(o),l===ui||l===So){const c=lt(a,0);for(let h=0;h<c;h++){const f=ot(a,0,h);if(f>0&&f+4<=4096){const _=a.getUint32(f,!0);_>1&&!s.has(_)&&i.push(_)}}const u=Ut(a,0);u>1&&!s.has(u)&&i.push(u)}else if(l===ts||l===zn){const c=Ut(a,0);c>1&&!s.has(c)&&i.push(c)}}for(const o of n)this.driver.forceUnpinPage(o),await this.driver.freePage(o,!0)}async dropTable(e){return this.coordinator.leaseQueue.enqueue(()=>this._dropTableInternal(e),this.currentLeaseId??void 0)}async _dropTableInternal(e){var r;this.tableMetaCache.delete(e.toLowerCase()),this.tableTailPages.delete(e);const n=this.pool.getSlotDataView(0),s=Wt(n,e);if(s===-1)throw new Nn(e);const i=xt(n,s);for(let a=0;a<Ke;a++){const l=_n(n,a);l&&(l.tableId===i.tableId||l.name.toLowerCase().startsWith(`idx_${e.toLowerCase()}_`)||l.name.toLowerCase()===`pk_${e.toLowerCase()}`)&&(l.rootPageId>1&&(await this.freeTableTreePages(l.rootPageId),this.indexTailPages.delete(l.rootPageId)),vi(n,a))}i.rootPageId>1&&await this.freeTableTreePages(i.rootPageId);let o=i.colCatalogPageId;for(;o>1;){const a=await this.driver.acquirePage(o),l=this.pool.getSlotDataView(a);if(Me(l,0)===ve){this.driver.forceUnpinPage(o);break}const h=Ae(l,0).nextColCatalogPageId;this.driver.forceUnpinPage(o),await this.driver.freePage(o,!0),o=h}wr(n,s),qe(n),se(n),Ht(n),this.pool.markDirty(0),this.coordinator.isInTransaction()||await this.driver.flushAllDirty(),((r=this.vmCtx.table)==null?void 0:r.name.toLowerCase())===e.toLowerCase()&&(this.vmCtx.table=null)}async renameTable(e,n){return this.coordinator.leaseQueue.enqueue(()=>this._renameTableInternal(e,n),this.currentLeaseId??void 0)}async _renameTableInternal(e,n){var c;this.validateIdentifier(n,"Table name");const s=this.pool.getSlotDataView(0),i=Wt(s,e);if(i===-1)throw new Nn(e);if(e===n)return this._getTableInternal(n);if(Wt(s,n)!==-1)throw new ss(n);const o=xt(s,i);o.name=n,An(s,i,o);const r=`pk_${e}`,a=`idx_${e}_`;for(let u=0;u<Ke;u++){const h=_n(s,u);if(h&&h.tableId===o.tableId){let f=null;h.name===r?f=`pk_${n}`:h.name.startsWith(a)&&(f=`idx_${n}_${h.name.slice(a.length)}`),f&&f.length<=te&&!Bs(s,f)&&(h.name=f,Ss(s,u,h))}}qe(s),se(s),Ht(s),this.pool.markDirty(0),this.tableMetaCache.delete(e.toLowerCase()),this.tableMetaCache.delete(n.toLowerCase());const l=this.tableTailPages.get(e);return l!==void 0&&(this.tableTailPages.delete(e),this.tableTailPages.set(n,l)),((c=this.vmCtx.table)==null?void 0:c.name.toLowerCase())===e.toLowerCase()&&(this.vmCtx.table=null),this.coordinator.isInTransaction()||await this.driver.flushAllDirty(),this._getTableInternal(n)}async renameColumn(e,n,s){return this.coordinator.leaseQueue.enqueue(()=>this._renameColumnInternal(e,n,s),this.currentLeaseId??void 0)}async _renameColumnInternal(e,n,s){var g;this.validateIdentifier(s,"Column name");const i=await this._getTableInternal(e),o=i.columns.findIndex(E=>E.name===n);if(o===-1)throw new le(n,e);if(n===s)return i;if(i.columns.some((E,I)=>I!==o&&E.name===s))throw new ns(s,e);const{pageChainIdx:r,colIdxInPage:a}=Or(o);let l=i.colCatalogPageId;for(let E=0;E<r;E++){const I=await this.driver.acquirePage(l);l=Ae(this.pool.getSlotDataView(I),0).nextColCatalogPageId}const c=await this.driver.acquirePage(l),u=this.pool.getSlotDataView(c),h={...i.columns[o],name:s};Gi(u,0,a,h);const f=Ge(this.pool.getPageBytesInSlot(c));u.setUint32(12,f,!0),this.pool.markDirty(c);const _=this.pool.getSlotDataView(0);return qe(_),se(_),Ht(_),this.pool.markDirty(0),this.tableMetaCache.delete(e.toLowerCase()),((g=this.vmCtx.table)==null?void 0:g.name.toLowerCase())===e.toLowerCase()&&(this.vmCtx.table=null),this.coordinator.isInTransaction()||await this.driver.flushAllDirty(),this._getTableInternal(e)}async addColumn(e,n,s){this.validateIdentifier(n.name,"Column name");const i=(s==null?void 0:s.defaultValue)!==void 0?s.defaultValue:n.defaultValue!==void 0?n.defaultValue:null;return this._executeTableRebuildAtomic(e,o=>{var h,f,_;if(o.columns.some(g=>g.name===n.name))throw new ns(n.name,e);if(o.columns.length+1>ce)throw new Ln(o.columns.length+1,ce);const r=typeof n.flags=="number"?n.flags:0,a=!!n.primaryKey||!!((h=n.flags)!=null&&h.primaryKey)||(r&z.PRIMARY_KEY)!==0,l=!!n.autoInc||!!((f=n.flags)!=null&&f.autoInc)||(r&z.AUTO_INC)!==0,c=!!n.indexed||!!((_=n.flags)!=null&&_.indexed)||(r&z.INDEXED)!==0;if(a&&o.columns.some(g=>(g.flags&z.PRIMARY_KEY)!==0))throw new Error(`Cannot add a PRIMARY KEY column "${n.name}" to table "${e}" because it already has a primary key`);return{newColumns:[...o.columns.map(g=>({name:g.name,type:g.type,flags:{primaryKey:(g.flags&z.PRIMARY_KEY)!==0,notNull:(g.flags&z.NOT_NULL)!==0,indexed:(g.flags&z.INDEXED)!==0,autoInc:(g.flags&z.AUTO_INC)!==0}})),n],transformRow:g=>{const E={...g};return(!l||i!==null)&&(E[n.name]=i),E},keepIndex:()=>!0,newAutoIndexCol:c&&!a?n.name:void 0}})}async dropColumn(e,n){return this.validateIdentifier(n,"Column name"),this._executeTableRebuildAtomic(e,s=>{const i=s.columns.findIndex(a=>a.name===n);if(i===-1)throw new le(n,e);if(s.columns.length<=1)throw new Ai(`Cannot drop column "${n}" from table "${e}": table must have at least one column`);if(s.columns[i].flags&z.PRIMARY_KEY)throw new Ai(`Cannot drop PRIMARY KEY column "${n}" from table "${e}"`);return{newColumns:s.columns.filter(a=>a.name!==n).map(a=>({name:a.name,type:a.type,flags:{primaryKey:(a.flags&z.PRIMARY_KEY)!==0,notNull:(a.flags&z.NOT_NULL)!==0,indexed:(a.flags&z.INDEXED)!==0,autoInc:(a.flags&z.AUTO_INC)!==0}})),transformRow:a=>{const l={...a};return delete l[n],l},keepIndex:a=>!a.includes(n)}})}async alterTable(e,n){switch(n.type){case"renameTable":return this.renameTable(e,n.newName);case"renameColumn":return this.renameColumn(e,n.from,n.to);case"addColumn":return this.addColumn(e,n.column,{defaultValue:n.defaultValue});case"dropColumn":return this.dropColumn(e,n.column);default:throw new Error(`Unsupported alterTable operation: ${n==null?void 0:n.type}`)}}async _executeTableRebuildAtomic(e,n){return this.coordinator.isInTransaction()?this.coordinator.leaseQueue.enqueue(async()=>{const s=await this.coordinator.captureSavepoint();try{return await this._rebuildTableSchemaInternal(e,n)}catch(i){throw this.tableMetaCache.clear(),this.tableTailPages.clear(),this.indexTailPages.clear(),await this.coordinator.restoreSavepoint(s),i}},this.currentLeaseId??void 0):this.transaction(s=>s._rebuildTableSchemaInternal(e,n))}async _rebuildTableSchemaInternal(e,n){const s=await this._getTableInternal(e),{newColumns:i,transformRow:o,keepIndex:r,newAutoIndexCol:a}=n(s),l=[];let c=s.rootPageId;for(;c!==0;){let E=await this.driver.acquirePage(c),I=this.pool.getSlotDataView(E);const p=lt(I,0),y=Ut(I,0);for(let T=0;T<p;T++){E=await this.driver.acquirePage(c),I=this.pool.getSlotDataView(E);const B=ot(I,0,T),L=Xe(s.columns,I,B);L&&l.push(o(L))}c=y}const u=s.autoIncNext,h=this.pool.getSlotDataView(0),f=ue(h,s.tableId),_=[];for(const E of f){if(E.flags&mt.PRIMARY)continue;const I=E.columnIndices.slice(0,E.columnCount).map(p=>{var y;return(y=s.columns[p])==null?void 0:y.name}).filter(p=>typeof p=="string");I.length===E.columnCount&&r(I)&&_.push({name:E.name,colNames:I,unique:(E.flags&mt.UNIQUE)!==0})}await this._dropTableInternal(e),await this._createTableInternal(e,i);for(const E of _)await this._createIndexInternal(e,E.colNames,{name:E.name,unique:E.unique});a&&!_.some(E=>E.colNames.length===1&&E.colNames[0]===a)&&await this._createIndexInternal(e,a),l.length>0&&await this._insertManyInternal(e,l,!1);const g=Wt(h,e);if(g!==-1){const E=xt(h,g);u>E.autoIncNext&&(E.autoIncNext=u,An(h,g,E),Ht(h),this.pool.markDirty(0))}return this.tableMetaCache.delete(e.toLowerCase()),this.coordinator.isInTransaction()||await this.driver.flushAllDirty(),this._getTableInternal(e)}async createIndex(e,n,s){return this.coordinator.leaseQueue.enqueue(()=>this._createIndexInternal(e,n,s),this.currentLeaseId??void 0)}async _createIndexInternal(e,n,s){const i=await this._getTableInternal(e),o=Array.isArray(n)?n:[n];if(o.length===0)throw new Error(`At least one column must be specified for createIndex on table "${e}"`);if(o.length>8)throw new Error(`Maximum 8 columns allowed per index (requested ${o.length})`);const r=[];for(const L of o){const P=i.columns.findIndex(F=>F.name===L);if(P===-1)throw new le(L,e);r.push(P)}const a=(s==null?void 0:s.name)??`idx_${e}_${o.join("_")}`,l=this.pool.getSlotDataView(0);if(Bs(l,a)!==null)throw new fi(a);const h=ue(l,i.tableId).find(L=>{if(L.columnCount!==r.length)return!1;for(let P=0;P<L.columnCount;P++)if(L.columnIndices[P]!==r[P])return!1;return!0});if(h)throw new fi(h.name||a);const f=Ps(l);if(f===-1)throw new Fo(Ke,Ke);const _=await this.driver.allocateAndPinPage(),g=this.pool.getResidentSlot(_),E=this.pool.getSlotDataView(g);ps(E,0,0),this.pool.markDirty(g),this.pool.unpinSlot(g);const I=!!(s!=null&&s.unique);let p=i.rootPageId;for(;p!==0;){let L=await this.driver.acquirePage(p),P=this.pool.getSlotDataView(L);const F=lt(P,0),w=Ut(P,0);for(let U=0;U<F;U++){L=await this.driver.acquirePage(p),P=this.pool.getSlotDataView(L);const k=ot(P,0,U),R=Xe(i.columns,P,k);if(R){const A=BigInt(p)<<16n|BigInt(U),{keyVal:N,keyType:v}=this.extractIndexKey(i.columns,{columnCount:r.length,columnIndices:r},R);if(N!=null){if(I&&await this.probeIndexUnique(_,v,N))throw await this.freeTableTreePages(_),this.indexTailPages.delete(_),new ze(`Duplicate key value violates unique constraint "${a}" on table "${e}"`);await this.insertIntoIndex(_,v,N,A)}}}p=w}const y=[0,0,0,0,0,0,0,0],T=[0,0,0,0,0,0,0,0];for(let L=0;L<r.length&&L<8;L++)y[L]=r[L];const B=I?mt.UNIQUE:0;Ss(l,f,{indexId:f+1,tableId:i.tableId,rootPageId:_,columnCount:r.length,flags:B,columnIndices:y,colDirections:T,name:a}),qe(l),se(l),Ht(l),this.pool.markDirty(0),this.tableMetaCache.delete(e.toLowerCase()),this.indexTailPages.delete(_),this.coordinator.isInTransaction()||await this.driver.flushAllDirty()}async dropIndex(e){return this.coordinator.leaseQueue.enqueue(()=>this._dropIndexInternal(e),this.currentLeaseId??void 0)}async _dropIndexInternal(e){const n=this.pool.getSlotDataView(0),s=Bs(n,e);if(!s)throw new Do(e);s.desc.rootPageId>1&&(await this.freeTableTreePages(s.desc.rootPageId),this.indexTailPages.delete(s.desc.rootPageId)),vi(n,s.slotIdx),qe(n),se(n),Ht(n),this.pool.markDirty(0),this.tableMetaCache.clear(),this.indexTailPages.clear(),this.coordinator.isInTransaction()||await this.driver.flushAllDirty()}async listIndexes(e){return this.coordinator.leaseQueue.enqueue(async()=>{const n=this.pool.getSlotDataView(0);if(e){const i=await this._getTableInternal(e);return ue(n,i.tableId)}const s=[];for(let i=0;i<Ke;i++){const o=_n(n,i);o&&s.push(o)}return s},this.currentLeaseId??void 0)}extractIndexKey(e,n,s){if(n.columnCount===1){const i=e[n.columnIndices[0]];return{keyVal:s[i.name],keyType:i.type}}return{keyVal:Ts(e,n.columnIndices,n.columnCount,s),keyType:C.BLOB}}async probeIndexUnique(e,n,s,i){let o=e;for(;o!==0;){const r=await this.driver.acquirePage(o),a=this.pool.getSlotDataView(r);if(lt(a,0)>0){const c=Qn(a,0,n,s);if(c.found){const u=ot(a,0,c.slot_idx),h=a.getUint16(u,!0),f=a.getBigInt64(u+2+h,!0);if(!i||!i.has(f))return!0}}o=Ut(a,0)}return!1}async deleteFromIndex(e,n,s,i){let o=e;for(;o!==0;){const r=await this.driver.acquirePage(o),a=this.pool.getSlotDataView(r);if(lt(a,0)>0){const c=Qn(a,0,n,s,i);if(c.found)return nr(a,0,c.slot_idx),this.pool.markDirty(r),!0}o=Ut(a,0)}return!1}async insertIntoIndex(e,n,s,i){let o=this.indexTailPages.get(e)??e,r=await this.driver.acquirePage(o),a=this.pool.getSlotDataView(r);for(;;){const c=Ut(a,0);if(c===0)break;o=c,r=await this.driver.acquirePage(o),a=this.pool.getSlotDataView(r)}this.indexTailPages.set(e,o);let l=Oi(a,0,n,s,i,this.pool.pageScratchpadOffset);if(l===-1){this.pool.pinSlot(r);try{const c=await this.driver.allocateAndPinPage(),u=this.pool.getResidentSlot(c);try{hs(a,0,c),this.pool.markDirty(r);const h=this.pool.getSlotDataView(u);if(ps(h,0,0),l=Oi(h,0,n,s,i,this.pool.pageScratchpadOffset),l===-1)throw new Error("Unexpected error: index entry does not fit in empty page");this.pool.markDirty(u),this.indexTailPages.set(e,c)}finally{this.pool.unpinSlot(u)}}finally{this.pool.unpinSlot(r)}}else this.pool.markDirty(r)}cloneRow(e){const n={};for(const[s,i]of Object.entries(e))n[s]=i instanceof Uint8Array?i.slice():i;return n}valuesEqual(e,n){if(e===n||e==null&&n==null)return!0;if(e instanceof Uint8Array&&n instanceof Uint8Array){if(e.byteLength!==n.byteLength)return!1;for(let s=0;s<e.byteLength;s++)if(e[s]!==n[s])return!1;return!0}return typeof e=="number"&&typeof n=="bigint"||typeof e=="bigint"&&typeof n=="number"?BigInt(e)===BigInt(n):typeof e=="boolean"&&typeof n=="number"||typeof e=="number"&&typeof n=="boolean"?Number(e)===Number(n):!1}extractPrimaryKey(e,n){const s=e.columns.filter(i=>(i.flags&z.PRIMARY_KEY)!==0);return s.length===1?n[s[0].name]??null:s.length>1?s.map(i=>n[i.name]??null):e.columns.length===1?n[e.columns[0].name]??null:e.columns.map(i=>n[i.name]??null)}serializePkKey(e){const n=s=>s==null?"null":s instanceof Uint8Array?`b:${Array.from(s).join(",")}`:`${typeof s}:${String(s)}`;return Array.isArray(e)?`[${e.map(n).join("|")}]`:e!==null&&typeof e=="object"&&!(e instanceof Uint8Array)?`{${Object.keys(e).sort().map(i=>`${i}:${n(e[i])}`).join("|")}}`:n(e)}buildChangeset(e,n,s,i){const{changeCounter:o,schemaVersion:r}=this.getSyncState(),a=Array.from(new Set(i.map(l=>l.table)));return{txId:e,origin:n,meta:s,changeCounter:o,schemaVersion:r,tables:a,changes:i,coalesced:()=>{const l=new Map;for(const c of i){const u=`${c.table.toLowerCase()}::${this.serializePkKey(c.pk)}`,h=l.get(u);if(!h){l.set(u,{table:c.table,op:c.op,pk:Array.isArray(c.pk)?[...c.pk]:c.pk,oldRow:c.oldRow?this.cloneRow(c.oldRow):void 0,newRow:c.newRow?this.cloneRow(c.newRow):void 0,changedColumns:c.changedColumns?[...c.changedColumns]:void 0});continue}if(h.op==="insert"&&c.op==="update")l.set(u,{table:c.table,op:"insert",pk:Array.isArray(c.pk)?[...c.pk]:c.pk,newRow:c.newRow?this.cloneRow(c.newRow):h.newRow});else if(h.op==="insert"&&c.op==="delete")l.delete(u);else if(h.op==="update"&&c.op==="update"){const f=h.oldRow,_=c.newRow?this.cloneRow(c.newRow):h.newRow,g=Object.keys(_).filter(E=>!this.valuesEqual(f[E],_[E]));l.set(u,{table:c.table,op:"update",pk:Array.isArray(c.pk)?[...c.pk]:c.pk,oldRow:f,newRow:_,changedColumns:g})}else if(h.op==="update"&&c.op==="delete")l.set(u,{table:c.table,op:"delete",pk:Array.isArray(h.pk)?[...h.pk]:h.pk,oldRow:h.oldRow});else if(h.op==="delete"&&c.op==="insert"){const f=h.oldRow,_=c.newRow?this.cloneRow(c.newRow):{},g=Object.keys(_).filter(E=>!this.valuesEqual(f[E],_[E]));l.set(u,{table:c.table,op:"update",pk:Array.isArray(c.pk)?[...c.pk]:c.pk,oldRow:f,newRow:_,changedColumns:g})}else l.set(u,{table:c.table,op:c.op,pk:Array.isArray(c.pk)?[...c.pk]:c.pk,oldRow:c.oldRow?this.cloneRow(c.oldRow):void 0,newRow:c.newRow?this.cloneRow(c.newRow):void 0,changedColumns:c.changedColumns?[...c.changedColumns]:void 0})}return Array.from(l.values())}}}notifySubscriptions(e){if(e.tables.length===0||this.subscriptions.size===0)return;const n=new Set(e.tables.map(s=>s.toLowerCase()));for(const s of this.subscriptions)if(s.tables==="*")s.callback(e);else for(const i of n)if(s.tables.has(i)){s.callback(e);break}}emitCommitAndSubscriptions(e){if(e.changes.length===0)return;for(const o of this.commitHooks)o(e);const n=e.tables,{changeCounter:s,schemaVersion:i}=e;if(this.notifySubscriptions({tables:n,origin:e.origin,meta:e.meta,changeCounter:s,schemaVersion:i,crossTab:!1,changeset:e}),this.broadcastChannel)try{this.broadcastChannel.postMessage({senderId:this.instanceId,tables:n,origin:e.origin,meta:e.meta,changeCounter:s,schemaVersion:i})}catch{}}onBeforeCommit(e){return this.beforeCommitHooks.add(e),()=>{this.beforeCommitHooks.delete(e)}}onCommit(e){return this.commitHooks.add(e),()=>{this.commitHooks.delete(e)}}subscribe(e,n){const s={tables:e==="*"?"*":new Set((Array.isArray(e)?e:[e]).map(i=>i.toLowerCase())),callback:n};return this.subscriptions.add(s),()=>{this.subscriptions.delete(s)}}getSyncState(){const e=this.pool.getSlotDataView(0),n=Mn(e,!1);return{changeCounter:n.changeCounter,schemaVersion:n.schemaVersion}}validateFilterColumns(e,n){const s=new Set(e.columns.map(r=>r.name)),i=r=>{if(r){if(r.type==="col"&&r.name!=="*"){if(!s.has(r.name))throw new le(r.name,e.name)}else if(r.type==="binary")i(r.left),i(r.right);else if(r.type==="fn"&&Array.isArray(r.args))for(const a of r.args)i(a)}},o=r=>{if(r.colName&&!s.has(r.colName))throw new le(r.colName,e.name);if(r.expr&&i(r.expr),r.child&&o(r.child),r.children)for(const a of r.children)o(a)};for(const r of n)o(r)}matchesFilter(e,n,s){switch(s.type){case"and":return(s.children??[]).every(i=>this.matchesFilter(e,n,i));case"or":return(s.children??[]).some(i=>this.matchesFilter(e,n,i));case"not":return s.child?!this.matchesFilter(e,n,s.child):!0;case"null":{const i=s.expr?fe(s.expr,n,r=>{var a;return(a=this.getUdf(r))==null?void 0:a.def.call}):n[s.colName],o=i==null;return s.isNull?o:!o}case"in":{const i=s.expr?fe(s.expr,n,a=>{var l;return(l=this.getUdf(a))==null?void 0:l.def.call}):n[s.colName];if(i==null)return!1;const r=(s.values??[]).some(a=>this.valuesEqual(i,a));return s.notIn?!r:r}case"expr":{if(!s.expr)return!0;const i=fe(s.expr,n,o=>{var r;return(r=this.getUdf(o))==null?void 0:r.def.call});return!!i&&i!==0}case"cmp":{const i=s.expr?fe(s.expr,n,a=>{var l;return(l=this.getUdf(a))==null?void 0:l.def.call}):n[s.colName],o=s.value;if(i==null||o===null||o===void 0)return!1;switch(String(s.op??"=").trim().toLowerCase().replace(/\s+/g," ")){case"=":case"==":return this.valuesEqual(i,o);case"!=":case"<>":return!this.valuesEqual(i,o);case"<":return typeof i=="string"&&typeof o=="string"?i<o:Number(i)<Number(o);case"<=":return typeof i=="string"&&typeof o=="string"?i<=o:Number(i)<=Number(o);case">":return typeof i=="string"&&typeof o=="string"?i>o:Number(i)>Number(o);case">=":return typeof i=="string"&&typeof o=="string"?i>=o:Number(i)>=Number(o);case"like":return Ye(String(i),String(o));case"not like":return!Ye(String(i),String(o));case"contains":return String(i).includes(String(o));case"starts_with":return String(i).startsWith(String(o));case"ends_with":return String(i).endsWith(String(o));default:return this.valuesEqual(i,o)}}default:return!0}}matchesFilters(e,n,s){for(const i of s)if(!this.matchesFilter(e,n,i))return!1;return!0}async deleteCellsOnDataPageAndShiftIndexes(e,n,s,i,o){if(i.length===0)return;const r=new Set(i);if(n.length>0){for(const u of i){const h=o[u];if(!h)continue;const f=BigInt(s)<<16n|BigInt(u);for(const _ of n){const{keyVal:g,keyType:E}=this.extractIndexKey(e.columns,_,h.row);g!=null&&await this.deleteFromIndex(_.rootPageId,E,g,f)}}let c=0;for(let u=0;u<o.length;u++)if(!r.has(u)){if(c!==u){const h=o[u].row,f=BigInt(s)<<16n|BigInt(u),_=BigInt(s)<<16n|BigInt(c);for(const g of n){const{keyVal:E,keyType:I}=this.extractIndexKey(e.columns,g,h);E!=null&&(await this.deleteFromIndex(g.rootPageId,I,E,f),await this.insertIntoIndex(g.rootPageId,I,E,_))}}c++}}const a=await this.driver.acquirePage(s),l=this.pool.getSlotDataView(a);for(let c=i.length-1;c>=0;c--)Jo(l,0,i[c]);this.pool.markDirty(a)}normalizeWhereOrPkFilters(e,n){if(n!==null&&typeof n=="object"&&!(n instanceof Uint8Array)){const i=[];for(const[o,r]of Object.entries(n))r!==void 0&&(r===null?i.push({type:"null",colName:o,isNull:!0}):i.push({type:"cmp",colName:o,op:"=",value:r}));return i}const s=e.columns.find(i=>(i.flags&z.PRIMARY_KEY)!==0);if(!s)throw new Error(`Table "${e.name}" does not have a primary key column for scalar lookup`);return[{type:"cmp",colName:s.name,op:"=",value:n}]}async insert(e,n,s){await this.insertMany(e,[n],s)}async insertMany(e,n,s){if(!(!n||n.length===0)){if(!this.coordinator.isInTransaction()&&this.beforeCommitHooks.size>0){await this.transaction(async i=>{await i._insertManyInternal(e,n,!0)},s);return}return this.coordinator.leaseQueue.enqueue(async()=>{const i=this.coordinator.isInTransaction(),o=await this._insertManyInternal(e,n,!0);if(!i&&o.length>0){const r=this.buildChangeset(this.nextAutoTxId++,(s==null?void 0:s.origin)??"local",s==null?void 0:s.meta,o);this.emitCommitAndSubscriptions(r)}},this.currentLeaseId??void 0)}}async _insertManyInternal(e,n,s=!0){if(!n||n.length===0)return[];const i=await this._getTableInternal(e),o=this.pool.getSlotDataView(0),r=ue(o,i.tableId),a=r.filter(p=>(p.flags&(mt.UNIQUE|mt.PRIMARY))!==0),l=i.columns.find(p=>(p.flags&z.AUTO_INC)!==0),c=new Map;for(const p of a)c.set(p.name,new Set);let u=i.autoIncNext;const h=[];for(let p=0;p<n.length;p++){const y=n[p];for(const P of i.columns)if(P.flags&z.PRIMARY_KEY&&!(P.flags&z.AUTO_INC)&&(y[P.name]===void 0||y[P.name]===null))throw new es(P.name,e);let T,B={};for(const P of i.columns)y[P.name]!==void 0?B[P.name]=y[P.name]:B[P.name]=null;l&&(y[l.name]===void 0||y[l.name]===null)&&(T=Number(u),u+=1n,B[l.name]=T);for(const P of a){const{keyVal:F,keyType:w}=this.extractIndexKey(i.columns,P,B);if(F!=null){const U=F instanceof Uint8Array?Array.from(F).join(","):F,k=c.get(P.name);if(k.has(U))throw new ze(`Duplicate key value violates unique constraint "${P.name}" on table "${e}"`);if(k.add(U),await this.probeIndexUnique(P.rootPageId,w,F))throw new ze(`Duplicate key value violates unique constraint "${P.name}" on table "${e}"`)}}const L=ms(i.columns,B);h.push({row:y,effectiveRow:B,rowBytes:L,assignedAutoInc:T})}i.autoIncNext=u;let f=this.tableTailPages.get(e)??i.rootPageId,_=await this.driver.acquirePage(f),g=this.pool.getSlotDataView(_);for(;;){const p=Ut(g,0);if(p===0)break;f=p,_=await this.driver.acquirePage(f),g=this.pool.getSlotDataView(_)}this.tableTailPages.set(e,f);const E=[];for(let p=0;p<h.length;p++){const{row:y,effectiveRow:T,rowBytes:B,assignedAutoInc:L}=h[p];l&&L!==void 0&&(y[l.name]=L),_=await this.driver.acquirePage(f),g=this.pool.getSlotDataView(_);let P=f,F=rn(g,0,B,this.pool.pageScratchpadOffset);if(F===-1){const U=_;this.pool.pinSlot(U);try{const k=await this.driver.allocateAndPinPage(),R=this.pool.getResidentSlot(k);try{hs(g,0,k),this.pool.markDirty(U);const A=this.pool.getSlotDataView(R);if(F=rn(A,0,B,this.pool.pageScratchpadOffset),F===-1)throw new Error("Unexpected error: row does not fit in empty page");this.pool.markDirty(R),f=k,P=k,_=R,g=A,this.tableTailPages.set(e,k)}finally{this.pool.unpinSlot(R)}}finally{this.pool.unpinSlot(U)}}else this.pool.markDirty(_);const w=BigInt(P)<<16n|BigInt(F);for(const U of r){const{keyVal:k,keyType:R}=this.extractIndexKey(i.columns,U,T);k!=null&&await this.insertIntoIndex(U.rootPageId,R,k,w)}if(s){const U={table:i.name,op:"insert",pk:this.extractPrimaryKey(i,T),newRow:this.cloneRow(T)};E.push(U),this.coordinator.isInTransaction()&&this.activeTxChanges.push(U)}}const I=Wt(o,e);if(I!==-1){const p=xt(o,I);p.rowCountEstimate+=n.length,l&&(p.autoIncNext=i.autoIncNext),An(o,I,p),se(o),Ht(o),this.pool.markDirty(0)}return this.coordinator.isInTransaction()||await this.driver.flushAllDirty(),E}async update(e,n,s,i){return!this.coordinator.isInTransaction()&&this.beforeCommitHooks.size>0?this.transaction(o=>o.update(e,n,s,i),i):this.coordinator.leaseQueue.enqueue(async()=>{const o=await this._getTableInternal(e),r=this.normalizeWhereOrPkFilters(o,n),a=this.coordinator.isInTransaction(),{count:l,changes:c}=await this._executeUpdateInternal(e,r,s);if(!a&&c.length>0){const u=this.buildChangeset(this.nextAutoTxId++,(i==null?void 0:i.origin)??"local",i==null?void 0:i.meta,c);this.emitCommitAndSubscriptions(u)}return l},this.currentLeaseId??void 0)}async executeUpdate(e,n,s,i){return!this.coordinator.isInTransaction()&&this.beforeCommitHooks.size>0?this.transaction(o=>o.executeUpdate(e,n,s,i),i):this.coordinator.leaseQueue.enqueue(async()=>{const o=this.coordinator.isInTransaction(),{count:r,changes:a}=await this._executeUpdateInternal(e,n,s);if(!o&&a.length>0){const l=this.buildChangeset(this.nextAutoTxId++,(i==null?void 0:i.origin)??"local",i==null?void 0:i.meta,a);this.emitCommitAndSubscriptions(l)}return r},this.currentLeaseId??void 0)}async _executeUpdateInternal(e,n,s){const i=await this._getTableInternal(e);this.validateFilterColumns(i,n);const o=new Map(i.columns.map(E=>[E.name,E]));for(const E of Object.keys(s))if(!o.has(E))throw new le(E,e);const r=this.pool.getSlotDataView(0),a=ue(r,i.tableId),l=a.filter(E=>(E.flags&(mt.UNIQUE|mt.PRIMARY))!==0),c=[],u=new Set;let h=0,f=i.rootPageId;for(;f!==0;){const E=await this.driver.acquirePage(f),I=this.pool.getSlotDataView(E),p=lt(I,0),y=Ut(I,0),T=[],B=[];for(let L=0;L<p;L++){const P=ot(I,0,L),F=Xe(i.columns,I,P);if(T.push({cellIdx:L,row:F}),this.matchesFilters(i,F,n)){const w={...F};for(const[R,A]of Object.entries(s))A!==void 0&&(w[R]=A);for(const R of i.columns)if(R.flags&z.PRIMARY_KEY&&(w[R.name]===null||w[R.name]===void 0))throw new es(R.name,e);const U=i.columns.map(R=>R.name).filter(R=>!this.valuesEqual(F[R],w[R])),k=ms(i.columns,w);B.push({cellIdx:L,oldRow:F,newRow:w,changedColumns:U,newRowBytes:k}),u.add(BigInt(f)<<16n|BigInt(L)),h++}}B.length>0&&c.push({pageId:f,allCells:T,matches:B}),f=y}if(h===0)return{count:0,changes:[]};for(const E of l){const I=new Set;for(const p of c)for(const y of p.matches){const{keyVal:T,keyType:B}=this.extractIndexKey(i.columns,E,y.newRow);if(T!=null){const L=T instanceof Uint8Array?Array.from(T).join(","):T;if(I.has(L))throw new ze(`Duplicate key value violates unique constraint "${E.name}" on table "${e}"`);if(I.add(L),await this.probeIndexUnique(E.rootPageId,B,T,u))throw new ze(`Duplicate key value violates unique constraint "${E.name}" on table "${e}"`)}}}const _=[],g=[];for(const E of c){const I=[];for(const p of E.matches){const y=await this.driver.acquirePage(E.pageId),T=this.pool.getSlotDataView(y);if(Ui(T,0,p.cellIdx,p.newRowBytes,this.pool.pageScratchpadOffset)){this.pool.markDirty(y),E.allCells[p.cellIdx].row=p.newRow;const L=BigInt(E.pageId)<<16n|BigInt(p.cellIdx);for(const F of a){const w=this.extractIndexKey(i.columns,F,p.oldRow),U=this.extractIndexKey(i.columns,F,p.newRow);this.valuesEqual(w.keyVal,U.keyVal)||(w.keyVal!==void 0&&w.keyVal!==null&&await this.deleteFromIndex(F.rootPageId,w.keyType,w.keyVal,L),U.keyVal!==void 0&&U.keyVal!==null&&await this.insertIntoIndex(F.rootPageId,U.keyType,U.keyVal,L))}const P={table:i.name,op:"update",pk:this.extractPrimaryKey(i,p.newRow),oldRow:this.cloneRow(p.oldRow),newRow:this.cloneRow(p.newRow),changedColumns:p.changedColumns};_.push(P),this.coordinator.isInTransaction()&&this.activeTxChanges.push(P)}else I.push(p.cellIdx),g.push(p)}I.length>0&&await this.deleteCellsOnDataPageAndShiftIndexes(i,a,E.pageId,I,E.allCells)}if(g.length>0){let E=this.tableTailPages.get(e)??i.rootPageId,I=await this.driver.acquirePage(E),p=this.pool.getSlotDataView(I);for(;;){const y=Ut(p,0);if(y===0)break;E=y,I=await this.driver.acquirePage(E),p=this.pool.getSlotDataView(I)}this.tableTailPages.set(e,E);for(const y of g){I=await this.driver.acquirePage(E),p=this.pool.getSlotDataView(I);let T=E,B=rn(p,0,y.newRowBytes,this.pool.pageScratchpadOffset);if(B===-1){const F=I;this.pool.pinSlot(F);try{const w=await this.driver.allocateAndPinPage(),U=this.pool.getResidentSlot(w);try{hs(p,0,w),this.pool.markDirty(F);const k=this.pool.getSlotDataView(U);B=rn(k,0,y.newRowBytes,this.pool.pageScratchpadOffset),this.pool.markDirty(U),E=w,T=w,this.tableTailPages.set(e,w)}finally{this.pool.unpinSlot(U)}}finally{this.pool.unpinSlot(F)}}else this.pool.markDirty(I);const L=BigInt(T)<<16n|BigInt(B);for(const F of a){const{keyVal:w,keyType:U}=this.extractIndexKey(i.columns,F,y.newRow);w!=null&&await this.insertIntoIndex(F.rootPageId,U,w,L)}const P={table:i.name,op:"update",pk:this.extractPrimaryKey(i,y.newRow),oldRow:this.cloneRow(y.oldRow),newRow:this.cloneRow(y.newRow),changedColumns:y.changedColumns};_.push(P),this.coordinator.isInTransaction()&&this.activeTxChanges.push(P)}}return se(r),Ht(r),this.pool.markDirty(0),this.coordinator.isInTransaction()||await this.driver.flushAllDirty(),{count:h,changes:_}}async delete(e,n,s){return!this.coordinator.isInTransaction()&&this.beforeCommitHooks.size>0?this.transaction(i=>i.delete(e,n,s),s):this.coordinator.leaseQueue.enqueue(async()=>{const i=await this._getTableInternal(e),o=this.normalizeWhereOrPkFilters(i,n),r=this.coordinator.isInTransaction(),{count:a,changes:l}=await this._executeDeleteInternal(e,o);if(!r&&l.length>0){const c=this.buildChangeset(this.nextAutoTxId++,(s==null?void 0:s.origin)??"local",s==null?void 0:s.meta,l);this.emitCommitAndSubscriptions(c)}return a},this.currentLeaseId??void 0)}async executeDelete(e,n,s){return!this.coordinator.isInTransaction()&&this.beforeCommitHooks.size>0?this.transaction(i=>i.executeDelete(e,n,s),s):this.coordinator.leaseQueue.enqueue(async()=>{const i=this.coordinator.isInTransaction(),{count:o,changes:r}=await this._executeDeleteInternal(e,n);if(!i&&r.length>0){const a=this.buildChangeset(this.nextAutoTxId++,(s==null?void 0:s.origin)??"local",s==null?void 0:s.meta,r);this.emitCommitAndSubscriptions(a)}return o},this.currentLeaseId??void 0)}async _executeDeleteInternal(e,n){const s=await this._getTableInternal(e);this.validateFilterColumns(s,n);const i=this.pool.getSlotDataView(0),o=ue(i,s.tableId),r=[];let a=0,l=s.rootPageId;for(;l!==0;){const u=await this.driver.acquirePage(l),h=this.pool.getSlotDataView(u),f=lt(h,0),_=Ut(h,0);if(f>0){const g=[],E=[];for(let I=0;I<f;I++){const p=ot(h,0,I),y=Xe(s.columns,h,p);if(g.push({cellIdx:I,row:y}),this.matchesFilters(s,y,n)){E.push(I);const T={table:s.name,op:"delete",pk:this.extractPrimaryKey(s,y),oldRow:this.cloneRow(y)};r.push(T),this.coordinator.isInTransaction()&&this.activeTxChanges.push(T)}}E.length>0&&(a+=E.length,await this.deleteCellsOnDataPageAndShiftIndexes(s,o,l,E,g))}l=_}if(a===0)return{count:0,changes:[]};const c=Wt(i,e);if(c!==-1){const u=xt(i,c);u.rowCountEstimate=Math.max(0,u.rowCountEstimate-a),An(i,c,u)}return se(i),Ht(i),this.pool.markDirty(0),this.coordinator.isInTransaction()||await this.driver.flushAllDirty(),{count:a,changes:r}}async upsert(e,n,s){const i=await this.upsertMany(e,[n],s);return i.inserted>0?"inserted":i.updated>0?"updated":"ignored"}async upsertMany(e,n,s){return!n||n.length===0?{inserted:0,updated:0,ignored:0}:!this.coordinator.isInTransaction()&&(this.beforeCommitHooks.size>0||n.length>1)?this.transaction(i=>i._upsertManyInLease(e,n,s),s):this.coordinator.leaseQueue.enqueue(async()=>{const i=this.coordinator.isInTransaction(),o=[],r=await this._upsertManyInLease(e,n,s,i?void 0:o);if(!i&&o.length>0){const a=this.buildChangeset(this.nextAutoTxId++,(s==null?void 0:s.origin)??"local",s==null?void 0:s.meta,o);this.emitCommitAndSubscriptions(a)}return r},this.currentLeaseId??void 0)}async _upsertManyInLease(e,n,s,i){const o=await this._getTableInternal(e),r=new Set(o.columns.map(f=>f.name));let a;if(s!=null&&s.conflictTarget){a=Array.isArray(s.conflictTarget)?s.conflictTarget:[s.conflictTarget];for(const f of a)if(!r.has(f))throw new le(f,e)}else if(a=o.columns.filter(f=>(f.flags&z.PRIMARY_KEY)!==0).map(f=>f.name),a.length===0)throw new Error(`Cannot upsert on table "${e}" without a primary key or explicit conflictTarget`);const l=(s==null?void 0:s.mode)??"merge";let c=0,u=0,h=0;for(const f of n){for(const I of Object.keys(f))if(!r.has(I))throw new le(I,e);const _=a.every(I=>f[I]!==void 0&&f[I]!==null);let g=null,E=[];if(_&&(E=a.map(I=>({type:"cmp",colName:I,op:"=",value:f[I]})),g=await this.findFirstMatchingRow(o,E)),g){if(l==="ignore"){h++;continue}if(s!=null&&s.where&&!s.where(this.cloneRow(g),this.cloneRow(f))){h++;continue}const I={};if(l==="replace")for(const y of o.columns)f[y.name]!==void 0?I[y.name]=f[y.name]:y.flags&z.PRIMARY_KEY?I[y.name]=g[y.name]:I[y.name]=null;else for(const[y,T]of Object.entries(f))T!==void 0&&(I[y]=T);const{changes:p}=await this._executeUpdateInternal(e,E,I);i&&i.push(...p),u++}else{const I=await this._insertManyInternal(e,[f],!0);i&&i.push(...I),c++}}return{inserted:c,updated:u,ignored:h}}async findFirstMatchingRow(e,n){let s=e.rootPageId;for(;s!==0;){const i=await this.driver.acquirePage(s),o=this.pool.getSlotDataView(i),r=lt(o,0),a=Ut(o,0);for(let l=0;l<r;l++){const c=ot(o,0,l),u=Xe(e.columns,o,c);if(this.matchesFilters(e,u,n))return u}s=a}return null}async transaction(e,n){const s=await this.coordinator.begin(),i=s.leaseId;this.activeTxChanges=[],this.activeTxOrigin=(n==null?void 0:n.origin)??"local",this.activeTxMeta=n==null?void 0:n.meta,this.activeTxId=s.txId;const o=new Proxy(this,{get:(r,a,l)=>{if(a==="currentLeaseId")return i;if(a==="transaction")return async(u,h)=>{const f=await this.coordinator.captureSavepoint(),_=this.activeTxChanges.length;try{return await u(o)}catch(g){throw this.activeTxChanges.length=_,this.tableMetaCache.clear(),this.tableTailPages.clear(),this.indexTailPages.clear(),await this.coordinator.restoreSavepoint(f),g}};if(a==="checkpoint")return()=>this.checkpoint();if(a==="from")return u=>{const h=new $t(o,u);return r.planner&&h.withPlanner(r.planner),h};const c=Reflect.get(r,a,l);return typeof c=="function"?c.bind(o):c}});try{const r=await e(o);if(this.activeTxChanges.length>0&&this.beforeCommitHooks.size>0&&!this.isRunningBeforeCommit){const h=this.buildChangeset(this.activeTxId,this.activeTxOrigin,this.activeTxMeta,[...this.activeTxChanges]);this.isRunningBeforeCommit=!0;try{for(const f of this.beforeCommitHooks)await f(h,o)}finally{this.isRunningBeforeCommit=!1}}const a=[...this.activeTxChanges],l=this.activeTxOrigin,c=this.activeTxMeta,u=this.activeTxId;if(this.activeTxChanges=[],this.activeTxOrigin="local",this.activeTxMeta=void 0,await this.coordinator.commit(i),a.length>0){const h=this.buildChangeset(u,l,c,a);this.emitCommitAndSubscriptions(h)}return r}catch(r){throw this.activeTxChanges=[],this.activeTxOrigin="local",this.activeTxMeta=void 0,this.isRunningBeforeCommit=!1,this.tableMetaCache.clear(),this.tableTailPages.clear(),this.indexTailPages.clear(),await this.coordinator.rollback(i),r}}registerFunction(e,n){const s=e.toLowerCase(),i=typeof n=="function"?{call:n}:{...n};if(!i.returnType)try{const r=i.call(1,1,1,1,1);typeof r=="number"?i.returnType=Number.isInteger(r)?C.INT32:C.FLOAT64:typeof r=="string"&&(i.returnType=C.TEXT)}catch{try{const r=i.call("","","","","");typeof r=="number"?i.returnType=Number.isInteger(r)?C.INT32:C.FLOAT64:typeof r=="string"&&(i.returnType=C.TEXT)}catch{}}let o=this.udfs.get(s);return o?o.def=i:(o={id:this.nextUdfId++,def:i},this.udfs.set(s,o)),this}getUdf(e){return this.udfs.get(e.toLowerCase())}getUdfMap(){const e=new Map;for(const[n,s]of this.udfs.entries())e.set(n,s.id);return e}getUdfDefs(){const e=new Map;for(const[n,s]of this.udfs.entries())e.set(n,s.def);return e}from(e){return new $t(this,e)}async explainQuery(e,n,s){return this.coordinator.leaseQueue.enqueue(()=>this._explainQueryInternal(e,n,s),this.currentLeaseId??void 0)}async _explainQueryInternal(e,n,s){var I,p,y;const i=await this._getTableInternal(e),o=[];if(s!=null&&s.joins&&s.joins.length>0){if(1+s.joins.length>16)throw new is(1+s.joins.length,16);for(let T=0;T<s.joins.length;T++){const B=s.joins[T],L=await this._getTableInternal(B.table);o.push({type:B.type,table:L,cursor:T+1,leftCol:B.leftCol,op:B.op,rightCol:B.rightCol})}}const r=to({table:i,joinedTables:o.length>0?o:void 0,filters:n,orderBy:s==null?void 0:s.orderBy,groupBy:s==null?void 0:s.groupBy,aggregates:s==null?void 0:s.aggregates,having:s==null?void 0:s.having,selectExprs:s==null?void 0:s.selectExprs,udfNameMap:this.getUdfMap(),udfDefs:this.getUdfDefs(),limit:s==null?void 0:s.limit,offset:s==null?void 0:s.offset,planner:(s==null?void 0:s.planner)??this.planner}),l=(r.allTables??(o.length>0?[i,...o.map(T=>T.table)]:[i]))[0],c=xr(r,l),u=jr(c),h=r.indexScan??r.table0Scan,f=h?"IndexScan":"TableScan",_=h?h.index.name:void 0,g=r.joinedTableScans,E=(I=s==null?void 0:s.joins)==null?void 0:I.map(T=>{const B=g==null?void 0:g.find(L=>L.tableName.toLowerCase()===T.table.toLowerCase());return B&&B.scanType==="IndexScan"?{...T,scanType:B.scanType,indexName:B.indexName}:T});return{plan:{table:l.name,rootPageId:l.rootPageId,scanType:f,indexName:_,filters:n,orderBy:s==null?void 0:s.orderBy,groupBy:s==null?void 0:s.groupBy,aggregates:s==null?void 0:s.aggregates,having:s==null?void 0:s.having,select:s==null?void 0:s.select,joins:E,limit:s==null?void 0:s.limit,offset:s==null?void 0:s.offset,estimatedCost:r.estimatedCost,estimatedRows:r.estimatedRows,joinOrder:r.joinOrder,isOrderSatisfied:r.isOrderSatisfied??((p=r.planMetrics)==null?void 0:p.isOrderSatisfied)??!1,sortCostAvoided:((y=r.planMetrics)==null?void 0:y.sortCostAvoided)??void 0},bytecodeSize:r.byteLength,instructions:c,assembly:u}}async executeQuery(e,n,s){return this.coordinator.leaseQueue.enqueue(()=>this._executeQueryInternal(e,n,s),this.currentLeaseId??void 0)}async _executeQueryInternal(e,n,s){var E;const i=await this._getTableInternal(e),o=[],r=[];if(s.joins&&s.joins.length>0){if(1+s.joins.length>16)throw new is(1+s.joins.length,16);for(let I=0;I<s.joins.length;I++){const p=s.joins[I],y=await this._getTableInternal(p.table);o.push(y),r.push({type:p.type,table:y,cursor:I+1,leftCol:p.leftCol,op:p.op,rightCol:p.rightCol})}}for(const I of[i,...o]){let p=I.rootPageId;for(;p!==0;){const y=await this.driver.acquirePage(p),T=this.pool.getSlotDataView(y);p=Ut(T,0)}for(const y of I.indexes??[]){let T=y.rootPageId;for(;T!==0;){const B=await this.driver.acquirePage(T),L=this.pool.getSlotDataView(B);T=Ut(L,0)}}}let a=s.orderBy;!a&&s.sortCol&&(a=[{colName:s.sortCol,direction:s.sortDir}]);const l={table:i,joinedTables:r.length>0?r:void 0,filters:n,orderBy:a,groupBy:s.groupBy,aggregates:s.aggregates,having:s.having,selectExprs:s.selectExprs,udfNameMap:this.getUdfMap(),udfDefs:this.getUdfDefs(),limit:s.limit!==null?s.limit:void 0,offset:s.offset!==null?s.offset:void 0,planner:s.planner??this.planner},c=to(l),u=c.allTables??[i,...o];No(this.vmCtx,u[0],u),c.inSets&&(this.vmCtx.inSets=c.inSets);const h=c.keyInfos??l.keyInfos;h&&(this.vmCtx.keyInfos=h);const f={};for(const I of this.udfs.values())f[I.id]=I.def.call;this.vmCtx.udfs=f;let _=c.outputColumns??l.outputColumns??i.columns;if(l.aggregates&&l.aggregates.length>0||l.groupBy&&l.groupBy.length>0)if(c.outputColumns)_=c.outputColumns;else{_=[];const I=l.groupBy??[];for(const p of I){const y=typeof p=="string"?p:p.colName??(p.expr?jt(p.expr):"group_key"),T=i.columns.find(B=>B.name===y);T?_.push(T):_.push({name:y,type:C.TEXT,flags:z.NONE,colOffset:0})}for(let p=0;p<(((E=l.aggregates)==null?void 0:E.length)??0);p++){const y=l.aggregates[p],T=y.alias??(y.colName?`${y.func}_${y.colName}`:y.func),B=y.func==="count"?C.INT32:C.FLOAT64;_.push({name:T,type:B,flags:z.NONE,colOffset:0})}}this.vmCtx.outputColumns=_;const g=[];for(;;){const I=Gn(this.vmCtx,this.pool.view,c);let p=0;for(let y=0;y<this.vmCtx.resultCount;y++){const T=this.pool.view.getUint16(Sn+p,!0),B=Sn+p+2,L=Xe(_,this.pool.view,B);g.push(L),p+=2+T}if(I===O.DONE)break;if(I===O.BUFFER_FULL)this.vmCtx.resultOffset=0,this.vmCtx.resultCount=0,this.vmCtx.status=O.RUNNING;else if(I===O.PAGE_FAULT){this.vmCtx.resultOffset=0,this.vmCtx.resultCount=0;const y=[],T=this.vmCtx.cursors??[this.vmCtx.cursor];for(const B of T)if(B&&B.pageId>1){const L=this.pool.getResidentSlot(B.pageId);L>0&&(this.pool.pinSlot(L),y.push(L))}try{await this.driver.acquirePage(this.vmCtx.fault_page_id)}finally{for(const B of y)this.pool.unpinSlot(B)}this.vmCtx.status=O.RUNNING}else throw I===O.ARENA_EXHAUSTED?(this.vmCtx.arenaOffset=0,new gi):I===O.TIMEOUT?new Qo:I===O.INVALID_BYTECODE?new ko:new Error(`VM execution error: status=${I}`)}return Object.defineProperty(g,"isOrderSatisfied",{value:c.isOrderSatisfied??!1,writable:!0,enumerable:!1,configurable:!0}),g}async checkpoint(){return this.coordinator.checkpoint()}async exportBinary(){return this.coordinator.leaseQueue.enqueue(async()=>{this.coordinator.isInTransaction()||(await this.coordinator.executeCheckpoint(),await this.driver.flushAllDirty());const e=this.pool.getSlotDataView(0),n=pr(e),s=new Uint8Array(n*4096);s.set(this.pool.getPageBytesInSlot(0),0);const i=new DataView(s.buffer,s.byteOffset,4096);Ht(i,0);for(let o=2;o<=n;o++){const r=(o-1)*4096,a=s.subarray(r,r+4096),l=this.pool.getResidentSlot(o);if(l!==-1)a.set(this.pool.getPageBytesInSlot(l));else if(this.coordinator.hasSpilledPage(o))a.set(this.coordinator.getSpilledPage(o));else{const u=await this.vfs.readPage(o);u&&a.set(u)}const c=Ge(a);new DataView(a.buffer,a.byteOffset,4096).setUint32(12,c,!0)}return s},this.currentLeaseId??void 0)}async importBinary(e){if(this.coordinator.isInTransaction())throw new Error("Cannot import binary database while a transaction is active");return this.coordinator.leaseQueue.enqueue(async()=>{const n=e instanceof Uint8Array?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e);if(n.byteLength<4096||n.byteLength%4096!==0)throw new Rn(`Invalid database binary size (${n.byteLength} bytes): must be a non-zero multiple of 4096 bytes`);const s=n.byteLength/4096,i=n.subarray(0,4096),o=new DataView(i.buffer,i.byteOffset,4096),r=Mn(o,!0);if(r.pageSize!==4096)throw new Rn(`Invalid database page size ${r.pageSize} (expected 4096)`);if(r.totalPages!==s)throw new Rn(`Database page count mismatch: header specifies ${r.totalPages} pages, but binary image contains ${s} pages`);for(let c=2;c<=s;c++){const u=(c-1)*4096,h=n.subarray(u,u+4096),_=new DataView(h.buffer,h.byteOffset,4096).getUint32(12,!0);if(_!==0){const g=Ge(h);if(g!==_)throw new Ce(c,_,g)}}const a=[];for(let c=1;c<=s;c++){const u=(c-1)*4096;a.push({pageId:c,data:n.subarray(u,u+4096).slice()})}for(let c=1;c<this.pool.slotCount;c++)this.pool.forceUnpinSlot(c),this.pool.unassignSlot(c),this.pool.clearDirty(c),this.pool.getPageBytesInSlot(c).fill(0);this.pool.getPageBytesInSlot(0).set(a[0].data),this.pool.clearDirty(0),await this.vfs.writePages(a),await this.vfs.flush(),await this.coordinator.resetWalAfterImport(),this.tableMetaCache.clear(),this.tableTailPages.clear(),this.indexTailPages.clear(),this.vmCtx.table=null;const l=fn(this.pool.getSlotDataView(0));for(const c of l){let u=c.colCatalogPageId;for(;u!==0;){const h=await this.driver.acquireAndPinPage(u),f=this.pool.getSlotDataView(h);u=Ae(f,0).nextColCatalogPageId}}})}async close(){this.broadcastChannel&&(this.broadcastChannel.close(),this.broadcastChannel=null),this.beforeCommitHooks.clear(),this.commitHooks.clear(),this.subscriptions.clear(),await this.coordinator.close(),await this.driver.flushAllDirty(),await this.vfs.close()}}m.ALIGNMENT_PADDING_OFFSET=sc,m.ALIGNMENT_PADDING_SIZE=ho,m.AggregateNotAllowedInWhereError=os,m.BUILTIN_AGGREGATES=br,m.BUILTIN_SCALARS=Qr,m.BYTECODE_OFFSET=Io,m.BYTECODE_SIZE=_o,m.BufferPoolDriver=Rr,m.BytecodeEmitter=bs,m.CATALOG_PAGE_HEADER_FIELDS=Ma,m.CATALOG_PAGE_HEADER_OFFSET_COL_COUNT_IN_PAGE=Va,m.CATALOG_PAGE_HEADER_OFFSET_FLAGS=Wa,m.CATALOG_PAGE_HEADER_OFFSET_NEXT_COL_CATALOG_PAGE_ID=Ya,m.CATALOG_PAGE_HEADER_OFFSET_PAGE_CHECKSUM=Za,m.CATALOG_PAGE_HEADER_OFFSET_PAGE_TYPE=Ha,m.CATALOG_PAGE_HEADER_OFFSET_START_COL_INDEX=Xa,m.CATALOG_PAGE_HEADER_OFFSET_TABLE_ID=$a,m.CATALOG_PAGE_HEADER_SIZE=Xs,m.COLUMN_META_FIELDS=qa,m.COLUMN_META_OFFSET_COL_OFFSET=Ka,m.COLUMN_META_OFFSET_FLAGS=ja,m.COLUMN_META_OFFSET_NAME=Ja,m.COLUMN_META_OFFSET_RESERVED=za,m.COLUMN_META_OFFSET_TYPE=xa,m.COLUMN_META_SIZE=Ys,m.COST_INDEX_NEXT=Ls,m.COST_INDEX_SEEK=gn,m.COST_ROW_EVAL=_e,m.CURRENT_ENGINE_VERSION=Jn,m.CURRENT_MIN_READ_VERSION=Uo,m.CannotDropColumnError=Ai,m.ColumnAlreadyExistsError=ns,m.ColumnFlag=z,m.ColumnNotFoundError=le,m.CorruptPageError=Ce,m.CorruptWalFrameError=Dn,m.CorruptWalHeaderError=rs,m.CostBasedPlanner=Fs,m.CostBasedQueryPlanner=ul,m.CustomOrderPlanner=al,m.CustomPlanner=$r,m.CustomQueryPlanner=cl,m.DEFAULT_BUFFER_POOL_REGIONS=nc,m.DEFAULT_CACHE_SIZE_BYTES=tc,m.DEFAULT_MAX_QUERY_MEMORY=Qe,m.DEFAULT_PAGE_SLOTS=ec,m.DEFAULT_PAGE_TO_SLOT_BUCKETS=Qt,m.DEFAULT_SLOT_COUNT=be,m.DIRTY_MASK_OFFSET=Eo,m.DataType=C,m.DefaultQueryPlanner=ll,m.ExclusiveLeaseQueue=Dr,m.ExpressionBuilder=st,m.FILE_HEADER_SIZE=fa,m.HEADER_OFFSET_CHANGE_COUNTER=me,m.HEADER_OFFSET_FILE_FORMAT_VERSION=Vs,m.HEADER_OFFSET_FREE_PAGE_HEAD=re,m.HEADER_OFFSET_MAGIC=de,m.HEADER_OFFSET_MIN_READ_VERSION=$s,m.HEADER_OFFSET_NEXT_CATALOG_PAGE_ID=lo,m.HEADER_OFFSET_NEXT_INDEX_CATALOG_PAGE_ID=uo,m.HEADER_OFFSET_PAGE_CHECKSUM=Ie,m.HEADER_OFFSET_PAGE_SIZE=Ws,m.HEADER_OFFSET_RESERVED=_a,m.HEADER_OFFSET_SCHEMA_VERSION=Ee,m.HEADER_OFFSET_TOTAL_PAGES=ee,m.HeuristicPlanner=Wr,m.HeuristicQueryPlanner=Al,m.INDEX_CATALOG_OFFSET=Un,m.INDEX_DESCRIPTOR_FIELDS=Na,m.INDEX_DESCRIPTOR_OFFSET_COLUMN_COUNT=Fa,m.INDEX_DESCRIPTOR_OFFSET_COLUMN_INDICES=Qa,m.INDEX_DESCRIPTOR_OFFSET_COL_DIRECTIONS=ka,m.INDEX_DESCRIPTOR_OFFSET_FLAGS=ba,m.INDEX_DESCRIPTOR_OFFSET_INDEX_ID=La,m.INDEX_DESCRIPTOR_OFFSET_NAME=va,m.INDEX_DESCRIPTOR_OFFSET_RESERVED=Ga,m.INDEX_DESCRIPTOR_OFFSET_ROOT_PAGE_ID=Da,m.INDEX_DESCRIPTOR_OFFSET_TABLE_ID=Ra,m.INDEX_DESCRIPTOR_SIZE=Fe,m.IdentifierTooLongError=Ro,m.IndexAlreadyExistsError=fi,m.IndexFlag=mt,m.IndexNotFoundError=Do,m.IndexedDbVfsAdapter=Ho,m.InvalidBytecodeError=ko,m.InvalidDatabaseError=Rn,m.Io=mi,m.MASTER_TABLE_OFFSET=wn,m.MAX_COLUMNS_PER_CATALOG_PAGE=pe,m.MAX_COLUMNS_PER_TABLE=ce,m.MAX_CURSORS_PER_FRAME=uc,m.MAX_INDEXES_PAGE1=Ke,m.MAX_INDEXES_SYSPAGE=ha,m.MAX_IN_LIST_SIZE=kt,m.MAX_NAME_LENGTH=te,m.MAX_REGISTERS_PER_FRAME=lc,m.MAX_ROW_SIZE=2048,m.MAX_SUBQUERY_DEPTH=Ac,m.MAX_TABLES_PAGE1=ae,m.MAX_TABLES_SYSPAGE=ga,m.MAX_TABLE_INTERIOR_CELLS=ao,m.MAX_TOPK_HEAP_LIMIT=Oo,m.MemoryVfsAdapter=Mo,m.NEXT_DESCRIPTOR_CATALOG_PAGE_OFFSET=da,m.NEXT_DESCRIPTOR_CATALOG_PAGE_SIZE=Ea,m.NoOpPlanner=Vr,m.NoOpQueryPlanner=fl,m.NotNullConstraintError=es,m.OpCode=d,m.OpfsVfsAdapter=Wo,m.PAGE_HEADER_OFFSET_CELL_COUNT=oa,m.PAGE_HEADER_OFFSET_CHECKSUM=Re,m.PAGE_HEADER_OFFSET_CONTENT_OFFSET=ra,m.PAGE_HEADER_OFFSET_FLAGS=ia,m.PAGE_HEADER_OFFSET_FREE_BYTES=aa,m.PAGE_HEADER_OFFSET_NEXT_PAGE_ID=oo,m.PAGE_HEADER_OFFSET_TYPE=io,m.PAGE_HEADER_SIZE=qt,m.PAGE_SCRATCHPAD_OFFSET=po,m.PAGE_SCRATCHPAD_SIZE=go,m.PAGE_SIZE=4096,m.PAGE_TO_SLOT_BUCKET_SIZE=ye,m.PAGE_TO_SLOT_OFFSET=Ft,m.PAGE_TO_SLOT_SIZE=Ao,m.PAGE_TYPE_CATALOG_PAGE=Pn,m.PAGE_TYPE_FREE=ve,m.PAGE_TYPE_INDEX_INTERIOR=So,m.PAGE_TYPE_INDEX_LEAF=zn,m.PAGE_TYPE_LEAF_DATA=ts,m.PAGE_TYPE_TABLE_INTERIOR=ui,m.QueryArenaExhaustedError=gi,m.QueryBuilder=$t,m.QueryTimeoutError=Qo,m.RESULT_BUFFER_OFFSET=Sn,m.RESULT_BUFFER_SIZE=Zs,m.RowSizeLimitExceededError=Lo,m.SLOTTED_PAGE_HEADER_FIELDS=sa,m.SLOT_TO_PAGE_OFFSET=Zn,m.SYSPAGE_FILE_HEADER_FIELDS=Aa,m.SYSPAGE_RESERVED_OFFSET=ma,m.SYSPAGE_RESERVED_SIZE=Ia,m.SubqueryNestingTooDeepError=_c,m.TABLE_DESCRIPTOR_FIELDS=pa,m.TABLE_DESCRIPTOR_OFFSET_AUTO_INC_NEXT=Pa,m.TABLE_DESCRIPTOR_OFFSET_COLUMN_COUNT=Ta,m.TABLE_DESCRIPTOR_OFFSET_COL_CATALOG_PAGE_ID=wa,m.TABLE_DESCRIPTOR_OFFSET_FLAGS=Sa,m.TABLE_DESCRIPTOR_OFFSET_NAME=Ua,m.TABLE_DESCRIPTOR_OFFSET_RESERVED=Ba,m.TABLE_DESCRIPTOR_OFFSET_ROOT_PAGE_ID=Ca,m.TABLE_DESCRIPTOR_OFFSET_ROW_COUNT_ESTIMATE=Oa,m.TABLE_DESCRIPTOR_OFFSET_TABLE_ID=ya,m.TABLE_DESCRIPTOR_SIZE=De,m.TABLE_INTERIOR_CELL_FIELDS=ca,m.TABLE_INTERIOR_CELL_OFFSET_CHILD_PAGE_ID=la,m.TABLE_INTERIOR_CELL_OFFSET_ROWID=ua,m.TABLE_INTERIOR_CELL_SIZE=ro,m.TABLE_INTERIOR_SPLIT_INDEX=co,m.TOTAL_MEMORY_BYTES=ic,m.TRANSIENT_ARENA_OFFSET=yo,m.TableAlreadyExistsError=ss,m.TableFlag=Bn,m.TableNotFoundError=Nn,m.TooManyColumnsError=Ln,m.TooManyCursorsError=is,m.TooManyGroupByColumnsError=Go,m.TooManyIndexesError=Fo,m.TooManyOrderByColumnsError=vo,m.TooManyRegistersError=nt,m.TooManyTablesError=_i,m.TransactionCoordinator=Fr,m.UniqueConstraintViolationError=ze,m.UnknownFunctionError=hi,m.UnsupportedFormatVersionError=bo,m.VM_CONTEXT_OFFSET=mo,m.VM_CONTEXT_SIZE=fo,m.VM_FRAME_COUNT=cc,m.VM_FRAME_SIZE=ac,m.VmStatus=O,m.WAL_CURRENT_VERSION=To,m.WAL_FILE_HEADER_FIELDS=oc,m.WAL_FILE_HEADER_SIZE=Kn,m.WAL_FRAME_HEADER_FIELDS=rc,m.WAL_FRAME_HEADER_SIZE=ke,m.WAL_FRAME_MAGIC=On,m.WAL_FRAME_OFFSET_CHECKSUM=li,m.WAL_FRAME_OFFSET_DB_SIZE_PAGES=ai,m.WAL_FRAME_OFFSET_FLAGS=ii,m.WAL_FRAME_OFFSET_FRAME_SEQ=ci,m.WAL_FRAME_OFFSET_FRAME_TYPE=si,m.WAL_FRAME_OFFSET_MAGIC=ni,m.WAL_FRAME_OFFSET_PAGE_ID=ri,m.WAL_FRAME_OFFSET_RESERVED=wo,m.WAL_FRAME_OFFSET_TX_ID=oi,m.WAL_FRAME_SIZE=Je,m.WAL_FRAME_TYPE_PAGE_DATA=qn,m.WAL_FRAME_TYPE_TX_COMMIT=xn,m.WAL_FRAME_TYPE_TX_UNCOMMITTED=jn,m.WAL_HEADER_OFFSET_CHECKPOINT_SEQ=Js,m.WAL_HEADER_OFFSET_CHECKSUM=ei,m.WAL_HEADER_OFFSET_MAGIC=xs,m.WAL_HEADER_OFFSET_PAGE_SIZE=Ks,m.WAL_HEADER_OFFSET_RESERVED=Co,m.WAL_HEADER_OFFSET_SALT1=zs,m.WAL_HEADER_OFFSET_SALT2=ti,m.WAL_HEADER_OFFSET_WAL_VERSION=js,m.WAL_HEADER_SIZE=fc,m.WAL_MAGIC_BYTES=Ii,m.WAL_PAGE_SIZE=Te,m.WEBDB_CORE_WASM_BASE64=Hi,m.WebDB=no,m.buf_pool_assign_slot=rr,m.buf_pool_clear_dirty=lr,m.buf_pool_find_victim=Di,m.buf_pool_get_resident_slot=vt,m.buf_pool_get_slot_offset=kc,m.buf_pool_is_dirty=Ni,m.buf_pool_is_pinned=cn,m.buf_pool_mark_dirty=cr,m.buf_pool_pin_slot=Li,m.buf_pool_read_slot_to_page=an,m.buf_pool_select_eviction_victim=Fi,m.buf_pool_unassign_slot=ar,m.buf_pool_unpin_slot=Ri,m.buf_pool_write_slot_to_page=Bi,m.buildJoinEdges=Rs,m.buildRootFilter=Kt,m.c_assert=Zo,m.canJoinPreserveOrder=qr,m.catalog_create_table=Pr,m.catalog_delete_index_descriptor=vi,m.catalog_delete_table_descriptor=wr,m.catalog_find_free_index_slot=Ps,m.catalog_find_free_table_slot=ki,m.catalog_find_index_by_name=Bs,m.catalog_find_table_by_name=qc,m.catalog_find_table_slot=Wt,m.catalog_get_change_counter=Tr,m.catalog_get_free_page_head=Yc,m.catalog_get_schema_version=yr,m.catalog_get_total_pages=pr,m.catalog_increment_change_counter=se,m.catalog_increment_schema_version=qe,m.catalog_init_page=Ur,m.catalog_init_page1=Ir,m.catalog_list_table_descriptors=fn,m.catalog_list_table_indexes=ue,m.catalog_load_all_tables=jc,m.catalog_load_table_meta=Mi,m.catalog_map_column_location=Or,m.catalog_parse_data_type=Cr,m.catalog_read_column_meta=Sr,m.catalog_read_fixed_string=Us,m.catalog_read_index_descriptor=_n,m.catalog_read_page1_header=Mn,m.catalog_read_page_header=Ae,m.catalog_read_table_descriptor=xt,m.catalog_set_free_page_head=Zc,m.catalog_set_total_pages=Xc,m.catalog_update_page1_checksum=Ht,m.catalog_write_column_meta=Gi,m.catalog_write_fixed_string=ws,m.catalog_write_index_descriptor=Ss,m.catalog_write_page_header=xc,m.catalog_write_table_descriptor=An,m.chooseIndexScan=ks,m.chooseJoinIndex=vs,m.clear_bit=Yo,m.col=Vi,m.collectLeafFilters=Xr,m.compare_sorter_keys=un,m.compileQuery=to,m.computeBufferPoolOffsets=qs,m.computePage1Checksum=Ei,m.computePageChecksum=Ge,m.computeWalFrameChecksum=as,m.crc32=di,m.createVmContext=Bo,m.createVmCursor=Po,m.createWasmCore=Nr,m.createWasmMemory=Lr,m.decodeWalFileHeader=fs,m.decodeWalFrame=wc,m.decodeWalFrameHeader=pi,m.deriveDefaultAlias=jt,m.disassembleBytecode=xr,m.doesTableSatisfyJoinOrderKeys=Xi,m.emitExpression=q,m.encodeWalFileHeader=As,m.encodeWalFrame=_s,m.estimateFilterSelectivity=$i,m.estimateWhereCost=Yi,m.evalExprNode=fe,m.exp=vr,m.extractAggregatesFromExpr=eo,m.extractFilterColumnNames=Mr,m.findIndexOnColumn=Wn,m.fn=sl,m.fnv1a_32=Cs,m.formatDisassembly=jr,m.getCmpOpcode=$n,m.getFilterReferencedTables=hn,m.getMinKeyValueForType=Qs,m.getSingleTableBaseCost=ge,m.getTopLevelConjunctionFilters=dn,m.getWebDbCoreWasmBytes=Br,m.get_bit=$o,m.inferExprType=Zr,m.inferTransitivePredicates=Hr,m.isAggregateFunction=Ue,m.isBuiltinFunction=Kc,m.isBuiltinScalarFunction=kr,m.isIndexAlignedWithOrderBy=zi,m.materializeOutputSelectExprs=Vn,m.memcmp=gc,m.memcpy=en,m.memset=ne,m.normalizeFilter=Se,m.normalizeSelectItem=Gs,m.optimizeQueryPlan=gl,m.optimizeWherePredicates=Zi,m.page_binary_search_index_leaf=Qn,m.page_binary_search_interior=Fc,m.page_compact=bn,m.page_compare_index_keys=ys,m.page_delete_index_leaf_cell=nr,m.page_delete_row=Jo,m.page_deserialize_row=Xe,m.page_get_cell_content_offset=We,m.page_get_cell_count=lt,m.page_get_cell_offset=ot,m.page_get_checksum=Lc,m.page_get_contiguous_free_space=ds,m.page_get_free_bytes=we,m.page_get_next_page_id=Ut,m.page_get_right_child_page_id=Is,m.page_get_row_length=Es,m.page_get_table_layout=Dc,m.page_get_total_free_space=Ko,m.page_get_type=Me,m.page_init=Fn,m.page_init_free=jo,m.page_init_index_leaf=ps,m.page_init_interior=zo,m.page_insert_index_leaf_cell=Oi,m.page_insert_interior_cell=er,m.page_insert_row=rn,m.page_serialize_row=ms,m.page_set_cell_content_offset=Ve,m.page_set_cell_count=He,m.page_set_cell_offset=on,m.page_set_checksum=Rc,m.page_set_free_bytes=$e,m.page_set_next_page_id=hs,m.page_set_right_child_page_id=tr,m.page_set_type=Nc,m.page_split_interior=bc,m.page_table_delete=Pi,m.page_table_get=ir,m.page_table_hash=kn,m.page_table_set=or,m.page_update_row=Ui,m.parseExpression=ut,m.parseFilterTarget=Ct,m.parseSelectExpr=Ns,m.read_f64=mc,m.read_i32=dc,m.read_i64=Tc,m.read_u16=ls,m.read_u32=pt,m.read_u64=pc,m.read_u8=Vo,m.reconstructJoinPlans=Ds,m.recoverFromWal=Wi,m.resetVmContext=No,m.resolveColumnAcrossTables=ft,m.resolveQueryPlanner=xi,m.serialize_composite_key=Ts,m.serialize_single_key=sr,m.set_bit=Xo,m.sql=el,m.sql_like_match=Ye,m.strlen=cs,m.validateClause=xe,m.validateWalFrame=yi,m.vm_step=Gn,m.write_f64=Ic,m.write_i32=Ec,m.write_i64=Cc,m.write_u16=us,m.write_u32=yt,m.write_u64=yc,m.write_u8=hc,Object.defineProperty(m,Symbol.toStringTag,{value:"Module"})});
3
+ `;for(const i of e)s+=`${t(n(i.addr),8)} ${t(i.opcode,18)} ${t(i.p1,12)} ${t(i.p2,20)} ${t(i.p3,10)} ${i.comment}
4
+ `;return s}function x(e){return e instanceof Lt||typeof e=="object"&&e!==null&&typeof e.toArray=="function"&&typeof e.where=="function"&&typeof e.select=="function"&&"filters"in e}function wt(e){if(e instanceof it||typeof e=="object"&&e!==null&&"node"in e)return{expr:e.node};if(typeof e=="object"&&e!==null&&"type"in e)return{expr:e};if(typeof e=="string"){const t=e.trim();return t.includes("(")||t.includes("+")||t.includes("-")||t.includes("*")||t.includes("/")||t.includes("%")?{expr:ft(t),colName:t}:{colName:t}}return{}}function nr(e){const t=[];function n(s){if(s.type==="fn"){const i=s.name.toLowerCase();if(ge(i)){const r=s.args[0],o=r&&r.type==="col"&&r.name!=="*"?r.name:void 0;t.push({func:i,colName:o})}for(const r of s.args)n(r)}else s.type==="binary"&&(n(s.left),n(s.right))}return n(e),t}function Gs(e){if(!e)return[];if(Array.isArray(e)){const t=[];for(const n of e)t.push(...Gs(n));return t}if(x(e)){const t=e.getSelectFields(),n=e.getAggregates();return[{alias:t.length>0?t[0].alias:n.length>0?n[0].alias??(n[0].colName?`${n[0].func}_${n[0].colName}`:n[0].func):"subquery",subquery:e}]}if(e instanceof it||typeof e=="object"&&e!==null&&"node"in e){const t=e.node;return[{alias:Qt(t),expr:t,sourceCol:t.type==="col"&&t.name!=="*"?t.name:void 0,fn:t.type==="fn"?t.name:void 0}]}if(typeof e=="string"){const t=e.trim();if(!t)return[];const n=Bs(t);return[{alias:n.alias,expr:n.expr,sourceCol:n.expr.type==="col"&&n.expr.name!=="*"?n.expr.name:void 0,fn:n.expr.type==="fn"?n.expr.name:void 0}]}if(typeof e=="object"&&e!==null){if("subquery"in e&&"as"in e&&x(e.subquery)&&typeof e.as=="string")return[{alias:e.as,subquery:e.subquery}];if("expr"in e&&"alias"in e){const n=e.expr;return[{alias:e.alias,expr:n,sourceCol:n.type==="col"&&n.name!=="*"?n.name:void 0,fn:n.type==="fn"?n.name:void 0}]}if("col"in e&&"as"in e&&typeof e.col=="string"&&typeof e.as=="string"){const n=Bs(`${e.col} as ${e.as}`);return[{sourceCol:e.col==="*"?void 0:e.col,alias:e.as,expr:n.expr,fn:n.expr.type==="fn"?n.expr.name:void 0}]}const t=[];for(const[n,s]of Object.entries(e))if(typeof s=="string"){const i=Bs(`${n} as ${s}`);t.push({sourceCol:n==="*"?void 0:n,alias:s,expr:i.expr,fn:i.expr.type==="fn"?i.expr.name:void 0})}else if(x(s))t.push({alias:n,subquery:s});else if(typeof s=="object"&&s!==null&&"subquery"in s&&x(s.subquery))t.push({alias:n,subquery:s.subquery});else if(s instanceof it||typeof s=="object"&&s!==null&&"node"in s){const i=s.node;t.push({alias:n,expr:i,sourceCol:i.type==="col"&&i.name!=="*"?i.name:void 0,fn:i.type==="fn"?i.name:void 0})}else if(typeof s=="object"&&s!==null&&"type"in s){const i=s;t.push({alias:n,expr:i,sourceCol:i.type==="col"&&i.name!=="*"?i.name:void 0,fn:i.type==="fn"?i.name:void 0})}return t}return[]}function ct(e){if(!x(e))if(typeof e=="string"){const t=e.trim();if(ge(t))throw new os(t);if(t.includes("("))try{const n=ft(t);je(n,"where")}catch(n){if(n instanceof os)throw n}}else e instanceof it||typeof e=="object"&&e!==null&&"node"in e?je(e.node,"where"):typeof e=="object"&&e!==null&&"type"in e&&je(e,"where")}class Lt{constructor(t,n){U(this,"db");U(this,"tableName");U(this,"sourceSubquery");U(this,"filters",[]);U(this,"selectFields",[]);U(this,"limitCount",null);U(this,"offsetCount",null);U(this,"sortCol",null);U(this,"sortDir","asc");U(this,"orderKeys",[]);U(this,"groupCols",[]);U(this,"groupKeys",[]);U(this,"aggExprs",[]);U(this,"havingFilters",[]);U(this,"joins",[]);U(this,"planner");this.db=t,x(n)?(this.sourceSubquery=n,this.tableName="__subquery__",this.assertSubqueryDepth()):this.tableName=n}withPlanner(t){return this.planner=t,this}as(t){return{subquery:this,as:t}}getTableName(){return this.tableName}getSourceSubquery(){return this.sourceSubquery}getAggregates(){return this.aggExprs}getFilterSubqueryDepth(t){let n=0;if(t.subquery&&x(t.subquery)&&(n=Math.max(n,1+t.subquery.getMaxSubqueryDepth())),t.value&&x(t.value)&&(n=Math.max(n,1+t.value.getMaxSubqueryDepth())),t.child&&(n=Math.max(n,this.getFilterSubqueryDepth(t.child))),t.children)for(const s of t.children)n=Math.max(n,this.getFilterSubqueryDepth(s));return n}getMaxSubqueryDepth(){let t=0;this.sourceSubquery&&(t=Math.max(t,1+this.sourceSubquery.getMaxSubqueryDepth()));for(const n of this.selectFields)n.subquery&&(t=Math.max(t,1+n.subquery.getMaxSubqueryDepth()));for(const n of this.filters)t=Math.max(t,this.getFilterSubqueryDepth(n));for(const n of this.havingFilters)t=Math.max(t,this.getFilterSubqueryDepth(n));return t}assertSubqueryDepth(){const t=this.getMaxSubqueryDepth();if(t>7)throw new Qr(t,7)}join(t,n,s,i){const r=i!==void 0?s:"=",o=i!==void 0?i:s;return this.joins.push({type:"inner",table:t,leftCol:n,op:r,rightCol:o}),this}innerJoin(t,n,s,i){return this.join(t,n,s,i)}leftJoin(t,n,s,i){const r=i!==void 0?s:"=",o=i!==void 0?i:s;return this.joins.push({type:"left",table:t,leftCol:n,op:r,rightCol:o}),this}getJoins(){return this.joins}where(t,n,s){if(typeof t=="function"){const i=new Lt(this.db,this.tableName);t(i);const r=i.getRootFilter();r&&(this.filters.push(r),this.assertSubqueryDepth())}else if(n===void 0&&s===void 0){if(typeof t=="string"){ct(t);const i=ft(t);this.filters.push({type:"expr",expr:i})}else if(t instanceof it||typeof t=="object"&&t!==null&&"node"in t)ct(t),this.filters.push({type:"expr",expr:t.node});else if(typeof t=="object"&&t!==null&&"type"in t)ct(t),this.filters.push({type:"expr",expr:t});else if(typeof t=="object"&&t!==null)for(const[i,r]of Object.entries(t))this.where(i,"=",r)}else{if(ct(t),ct(s),typeof n=="string"&&n.trim().toLowerCase()==="in")return this.whereIn(t,s);if(typeof n=="string"&&n.trim().toLowerCase()==="not in")return this.whereNotIn(t,s);const i=wt(t);x(s)?(this.filters.push({type:"cmp",colName:i.colName,expr:i.expr,op:n,value:s,subquery:s}),this.assertSubqueryDepth()):this.filters.push({type:"cmp",colName:i.colName,expr:i.expr,op:n,value:s})}return this}orWhere(t,n,s){if(typeof t=="function"){const i=new Lt(this.db,this.tableName);t(i);const r=i.getRootFilter();r&&(this.addOrFilter(r),this.assertSubqueryDepth())}else if(n===void 0&&s===void 0)if(typeof t=="string"){ct(t);const i=ft(t);this.addOrFilter({type:"expr",expr:i})}else t instanceof it||typeof t=="object"&&t!==null&&"node"in t?(ct(t),this.addOrFilter({type:"expr",expr:t.node})):typeof t=="object"&&t!==null&&"type"in t&&(ct(t),this.addOrFilter({type:"expr",expr:t}));else{if(ct(t),ct(s),typeof n=="string"&&n.trim().toLowerCase()==="in")return this.orWhereIn(t,s);if(typeof n=="string"&&n.trim().toLowerCase()==="not in")return this.orWhereNotIn(t,s);const i=wt(t);x(s)?(this.addOrFilter({type:"cmp",colName:i.colName,expr:i.expr,op:n,value:s,subquery:s}),this.assertSubqueryDepth()):this.addOrFilter({type:"cmp",colName:i.colName,expr:i.expr,op:n,value:s})}return this}whereNot(t,n,s){if(typeof t=="function"){const i=new Lt(this.db,this.tableName);t(i);const r=i.getRootFilter();r&&(this.filters.push({type:"not",child:r}),this.assertSubqueryDepth())}else if(n===void 0&&s===void 0)if(typeof t=="string"){ct(t);const i=ft(t);this.filters.push({type:"not",child:{type:"expr",expr:i}})}else t instanceof it||typeof t=="object"&&t!==null&&"node"in t?(ct(t),this.filters.push({type:"not",child:{type:"expr",expr:t.node}})):typeof t=="object"&&t!==null&&"type"in t&&(ct(t),this.filters.push({type:"not",child:{type:"expr",expr:t}}));else{if(ct(t),ct(s),typeof n=="string"&&n.trim().toLowerCase()==="in")return this.whereNotIn(t,s);if(typeof n=="string"&&n.trim().toLowerCase()==="not in")return this.whereIn(t,s);const i=wt(t);this.filters.push({type:"not",child:{type:"cmp",colName:i.colName,expr:i.expr,op:n,value:s,subquery:x(s)?s:void 0}}),x(s)&&this.assertSubqueryDepth()}return this}orWhereNot(t,n,s){if(typeof t=="function"){const i=new Lt(this.db,this.tableName);t(i);const r=i.getRootFilter();r&&(this.addOrFilter({type:"not",child:r}),this.assertSubqueryDepth())}else if(n===void 0&&s===void 0)if(typeof t=="string"){ct(t);const i=ft(t);this.addOrFilter({type:"not",child:{type:"expr",expr:i}})}else t instanceof it||typeof t=="object"&&t!==null&&"node"in t?(ct(t),this.addOrFilter({type:"not",child:{type:"expr",expr:t.node}})):typeof t=="object"&&t!==null&&"type"in t&&(ct(t),this.addOrFilter({type:"not",child:{type:"expr",expr:t}}));else{if(ct(t),ct(s),typeof n=="string"&&n.trim().toLowerCase()==="in")return this.orWhereNotIn(t,s);if(typeof n=="string"&&n.trim().toLowerCase()==="not in")return this.orWhereIn(t,s);const i=wt(t);this.addOrFilter({type:"not",child:{type:"cmp",colName:i.colName,expr:i.expr,op:n,value:s,subquery:x(s)?s:void 0}}),x(s)&&this.assertSubqueryDepth()}return this}whereRaw(t){return this.where(t)}orWhereRaw(t){return this.orWhere(t)}whereNull(t){return ct(t),this.filters.push({type:"null",colName:t,isNull:!0}),this}whereNotNull(t){return ct(t),this.filters.push({type:"null",colName:t,isNull:!1}),this}orWhereNull(t){return ct(t),this.addOrFilter({type:"null",colName:t,isNull:!0}),this}orWhereNotNull(t){return ct(t),this.addOrFilter({type:"null",colName:t,isNull:!1}),this}whereLike(t,n){return this.where(t,"like",n)}whereNotLike(t,n){return this.where(t,"not like",n)}whereStartsWith(t,n){return this.where(t,"starts_with",n)}whereEndsWith(t,n){return this.where(t,"ends_with",n)}whereContains(t,n){return this.where(t,"contains",n)}orWhereLike(t,n){return this.orWhere(t,"like",n)}orWhereNotLike(t,n){return this.orWhere(t,"not like",n)}orWhereStartsWith(t,n){return this.orWhere(t,"starts_with",n)}orWhereEndsWith(t,n){return this.orWhere(t,"ends_with",n)}orWhereContains(t,n){return this.orWhere(t,"contains",n)}whereIn(t,n){ct(t);const s=wt(t);if(x(n))return this.filters.push({type:"in",colName:s.colName,expr:s.expr,subquery:n,notIn:!1}),this.assertSubqueryDepth(),this;if(!Array.isArray(n))throw new TypeError("WebDB: whereIn requires an array of values");if(n.length>Dt)throw new RangeError(`WebDB: whereIn list exceeds maximum limit of ${Dt} elements`);return this.filters.push({type:"in",colName:s.colName,expr:s.expr,values:n,notIn:!1}),this}whereNotIn(t,n){ct(t);const s=wt(t);if(x(n))return this.filters.push({type:"in",colName:s.colName,expr:s.expr,subquery:n,notIn:!0}),this.assertSubqueryDepth(),this;if(!Array.isArray(n))throw new TypeError("WebDB: whereNotIn requires an array of values");if(n.length>Dt)throw new RangeError(`WebDB: whereNotIn list exceeds maximum limit of ${Dt} elements`);return this.filters.push({type:"in",colName:s.colName,expr:s.expr,values:n,notIn:!0}),this}orWhereIn(t,n){ct(t);const s=wt(t);if(x(n))return this.addOrFilter({type:"in",colName:s.colName,expr:s.expr,subquery:n,notIn:!1}),this.assertSubqueryDepth(),this;if(!Array.isArray(n))throw new TypeError("WebDB: orWhereIn requires an array of values");if(n.length>Dt)throw new RangeError(`WebDB: orWhereIn list exceeds maximum limit of ${Dt} elements`);return this.addOrFilter({type:"in",colName:s.colName,expr:s.expr,values:n,notIn:!1}),this}orWhereNotIn(t,n){ct(t);const s=wt(t);if(x(n))return this.addOrFilter({type:"in",colName:s.colName,expr:s.expr,subquery:n,notIn:!0}),this.assertSubqueryDepth(),this;if(!Array.isArray(n))throw new TypeError("WebDB: orWhereNotIn requires an array of values");if(n.length>Dt)throw new RangeError(`WebDB: orWhereNotIn list exceeds maximum limit of ${Dt} elements`);return this.addOrFilter({type:"in",colName:s.colName,expr:s.expr,values:n,notIn:!0}),this}whereExists(t){if(!x(t))throw new TypeError("WebDB: whereExists requires a QueryBuilder subquery");return this.filters.push({type:"exists",subquery:t,notExists:!1}),this.assertSubqueryDepth(),this}whereNotExists(t){if(!x(t))throw new TypeError("WebDB: whereNotExists requires a QueryBuilder subquery");return this.filters.push({type:"exists",subquery:t,notExists:!0}),this.assertSubqueryDepth(),this}orWhereExists(t){if(!x(t))throw new TypeError("WebDB: orWhereExists requires a QueryBuilder subquery");return this.addOrFilter({type:"exists",subquery:t,notExists:!1}),this.assertSubqueryDepth(),this}orWhereNotExists(t){if(!x(t))throw new TypeError("WebDB: orWhereNotExists requires a QueryBuilder subquery");return this.addOrFilter({type:"exists",subquery:t,notExists:!0}),this.assertSubqueryDepth(),this}getFilters(){return this.filters}getRootFilter(){return this.filters.length===0?null:this.filters.length===1?this.filters[0]:{type:"and",children:[...this.filters]}}addOrFilter(t){if(this.filters.length===0){this.filters.push(t);return}if(this.filters.length===1&&this.filters[0].type==="or"&&this.filters[0].children){this.filters[0].children.push(t);return}let n;this.filters.length===1?n=this.filters[0]:n={type:"and",children:[...this.filters]},this.filters=[{type:"or",children:[n,t]}]}limit(t){return this.limitCount=t,this}offset(t){return this.offsetCount=t,this}orderBy(t,n="asc",s){if(typeof t=="string"){this.sortCol=t,this.sortDir=n;const i=wt(t);this.orderKeys.push({colName:i.colName??t,expr:i.expr,direction:n,nullOrder:s})}else if(t instanceof it||typeof t=="object"&&t!==null&&"node"in t)this.orderKeys.push({expr:t.node,direction:n,nullOrder:s});else if(typeof t=="object"&&t!==null&&"type"in t)this.orderKeys.push({expr:t,direction:n,nullOrder:s});else if(Array.isArray(t))for(const i of t)if(typeof i=="string"){const r=wt(i);this.orderKeys.push({colName:r.colName??i,expr:r.expr,direction:"asc"})}else this.orderKeys.push(i);else this.orderKeys.push(t);return this}groupBy(...t){for(const n of t)if(Array.isArray(n))for(const s of n)this.addGroupByItem(s);else this.addGroupByItem(n);return this}addGroupByItem(t){if(t instanceof it||typeof t=="object"&&t!==null&&"node"in t)this.groupKeys.push({expr:t.node}),this.groupCols.push(Qt(t.node));else if(typeof t=="object"&&t!==null&&"type"in t)this.groupKeys.push({expr:t}),this.groupCols.push(Qt(t));else if(typeof t=="string"){const n=wt(t);this.groupKeys.push({colName:n.colName??t,expr:n.expr}),this.groupCols.push(t)}}registerAggregatesFromFilter(t){const n=(s,i)=>{if(i){const r=nr(i);for(const o of r)this.aggExprs.some(c=>c.func===o.func&&(c.colName===o.colName||c.colName===void 0&&o.colName===void 0))||this.aggExprs.push(o)}else if(s&&s.includes("("))try{const r=ft(s),o=nr(r);for(const a of o)this.aggExprs.some(l=>l.func===a.func&&(l.colName===a.colName||l.colName===void 0&&a.colName===void 0))||this.aggExprs.push(a)}catch{}};if(t.type==="cmp")n(t.colName,t.expr);else if(t.type==="expr"&&t.expr)n(void 0,t.expr);else if(t.type==="null")n(t.colName,t.expr);else if(t.type==="not"&&t.child)this.registerAggregatesFromFilter(t.child);else if((t.type==="and"||t.type==="or")&&t.children)for(const s of t.children)this.registerAggregatesFromFilter(s)}having(t,n,s){if(typeof t=="function"){const i=new Lt(this.db,this.tableName);t(i);const r=i.getRootHavingFilter();r&&(this.havingFilters.push(r),this.registerAggregatesFromFilter(r),this.assertSubqueryDepth())}else if(n===void 0&&s===void 0){if(typeof t=="string"){const r={type:"expr",expr:ft(t)};this.havingFilters.push(r),this.registerAggregatesFromFilter(r)}else if(t instanceof it||typeof t=="object"&&t!==null&&"node"in t){const i={type:"expr",expr:t.node};this.havingFilters.push(i),this.registerAggregatesFromFilter(i)}else if(typeof t=="object"&&t!==null&&"type"in t){const i={type:"expr",expr:t};this.havingFilters.push(i),this.registerAggregatesFromFilter(i)}}else{const i=wt(t);if(typeof n=="string"&&(n.trim().toLowerCase()==="in"||n.trim().toLowerCase()==="not in")){const o=n.trim().toLowerCase()==="not in",a=x(s)?{type:"in",colName:i.colName,expr:i.expr,subquery:s,notIn:o}:{type:"in",colName:i.colName,expr:i.expr,values:s,notIn:o};return this.havingFilters.push(a),this.registerAggregatesFromFilter(a),this.assertSubqueryDepth(),this}const r={type:"cmp",colName:i.colName,expr:i.expr,op:n,value:s,subquery:x(s)?s:void 0};this.havingFilters.push(r),this.registerAggregatesFromFilter(r),x(s)&&this.assertSubqueryDepth()}return this}orHaving(t,n,s){if(typeof t=="function"){const i=new Lt(this.db,this.tableName);t(i);const r=i.getRootHavingFilter();r&&(this.addHavingOrFilter(r),this.registerAggregatesFromFilter(r),this.assertSubqueryDepth())}else if(n===void 0&&s===void 0){if(typeof t=="string"){const r={type:"expr",expr:ft(t)};this.addHavingOrFilter(r),this.registerAggregatesFromFilter(r)}else if(t instanceof it||typeof t=="object"&&t!==null&&"node"in t){const i={type:"expr",expr:t.node};this.addHavingOrFilter(i),this.registerAggregatesFromFilter(i)}else if(typeof t=="object"&&t!==null&&"type"in t){const i={type:"expr",expr:t};this.addHavingOrFilter(i),this.registerAggregatesFromFilter(i)}}else{const i=wt(t),r={type:"cmp",colName:i.colName,expr:i.expr,op:n,value:s,subquery:x(s)?s:void 0};this.addHavingOrFilter(r),this.registerAggregatesFromFilter(r),x(s)&&this.assertSubqueryDepth()}return this}havingNot(t,n,s){if(typeof t=="function"){const i=new Lt(this.db,this.tableName);t(i);const r=i.getRootHavingFilter();if(r){const o={type:"not",child:r};this.havingFilters.push(o),this.registerAggregatesFromFilter(o),this.assertSubqueryDepth()}}else if(n===void 0&&s===void 0){if(typeof t=="string"){const r={type:"not",child:{type:"expr",expr:ft(t)}};this.havingFilters.push(r),this.registerAggregatesFromFilter(r)}else if(t instanceof it||typeof t=="object"&&t!==null&&"node"in t){const i={type:"not",child:{type:"expr",expr:t.node}};this.havingFilters.push(i),this.registerAggregatesFromFilter(i)}else if(typeof t=="object"&&t!==null&&"type"in t){const i={type:"not",child:{type:"expr",expr:t}};this.havingFilters.push(i),this.registerAggregatesFromFilter(i)}}else{const i=wt(t),r={type:"not",child:{type:"cmp",colName:i.colName,expr:i.expr,op:n,value:s,subquery:x(s)?s:void 0}};this.havingFilters.push(r),this.registerAggregatesFromFilter(r),x(s)&&this.assertSubqueryDepth()}return this}orHavingNot(t,n,s){if(typeof t=="function"){const i=new Lt(this.db,this.tableName);t(i);const r=i.getRootHavingFilter();if(r){const o={type:"not",child:r};this.addHavingOrFilter(o),this.registerAggregatesFromFilter(o),this.assertSubqueryDepth()}}else if(n===void 0&&s===void 0){if(typeof t=="string"){const r={type:"not",child:{type:"expr",expr:ft(t)}};this.addHavingOrFilter(r),this.registerAggregatesFromFilter(r)}else if(t instanceof it||typeof t=="object"&&t!==null&&"node"in t){const i={type:"not",child:{type:"expr",expr:t.node}};this.addHavingOrFilter(i),this.registerAggregatesFromFilter(i)}else if(typeof t=="object"&&t!==null&&"type"in t){const i={type:"not",child:{type:"expr",expr:t}};this.addHavingOrFilter(i),this.registerAggregatesFromFilter(i)}}else{const i=wt(t),r={type:"not",child:{type:"cmp",colName:i.colName,expr:i.expr,op:n,value:s,subquery:x(s)?s:void 0}};this.addHavingOrFilter(r),this.registerAggregatesFromFilter(r),x(s)&&this.assertSubqueryDepth()}return this}havingRaw(t){return this.having(t)}orHavingRaw(t){return this.orHaving(t)}havingNull(t){const n=wt(t),s={type:"null",colName:n.colName,expr:n.expr,isNull:!0};return this.havingFilters.push(s),this.registerAggregatesFromFilter(s),this}havingNotNull(t){const n=wt(t),s={type:"null",colName:n.colName,expr:n.expr,isNull:!1};return this.havingFilters.push(s),this.registerAggregatesFromFilter(s),this}orHavingNull(t){const n=wt(t),s={type:"null",colName:n.colName,expr:n.expr,isNull:!0};return this.addHavingOrFilter(s),this.registerAggregatesFromFilter(s),this}orHavingNotNull(t){const n=wt(t),s={type:"null",colName:n.colName,expr:n.expr,isNull:!1};return this.addHavingOrFilter(s),this.registerAggregatesFromFilter(s),this}getHavingFilters(){return this.havingFilters}getRootHavingFilter(){return this.havingFilters.length===0?null:this.havingFilters.length===1?this.havingFilters[0]:{type:"and",children:[...this.havingFilters]}}addHavingOrFilter(t){if(this.havingFilters.length===0){this.havingFilters.push(t);return}if(this.havingFilters.length===1&&this.havingFilters[0].type==="or"&&this.havingFilters[0].children){this.havingFilters[0].children.push(t);return}let n;this.havingFilters.length===1?n=this.havingFilters[0]:n={type:"and",children:[...this.havingFilters]},this.havingFilters=[{type:"or",children:[n,t]}]}aggregate(t){return this.aggExprs.push(...t),this}count(t,n){return this.aggExprs.push({func:"count",colName:t,alias:n}),this}sum(t,n){return this.aggExprs.push({func:"sum",colName:t,alias:n}),this}avg(t,n){return this.aggExprs.push({func:"avg",colName:t,alias:n}),this}min(t,n){return this.aggExprs.push({func:"min",colName:t,alias:n}),this}max(t,n){return this.aggExprs.push({func:"max",colName:t,alias:n}),this}select(t,...n){if(t===void 0)return this;const s=[];s.push(...Gs(t));for(const i of n)s.push(...Gs(i));this.selectFields.push(...s),this.assertSubqueryDepth();for(const i of s)if(i.expr&&i.expr.type==="fn"){const r=i.expr.name.toLowerCase();if(ge(r)&&!this.aggExprs.some(a=>a.alias===i.alias)){const a=i.expr.args[0],c=a&&a.type==="col"&&a.name!=="*"?a.name:void 0;this.aggExprs.push({func:r,colName:c,alias:i.alias})}}else if(typeof i.fn=="string"){const r=i.fn.toLowerCase();ge(r)&&(this.aggExprs.some(a=>a.alias===i.alias)||this.aggExprs.push({func:r,colName:i.sourceCol==="*"?void 0:i.sourceCol,alias:i.alias}))}return this}getSelectFields(){return this.selectFields}clone(t){const n=t??this.db,s=new Lt(n,this.sourceSubquery?this.sourceSubquery.clone(n):this.tableName),i=r=>({...r,values:r.values?[...r.values]:void 0,subquery:r.subquery&&x(r.subquery)?r.subquery.clone(n):r.subquery,value:x(r.value)?r.value.clone(n):r.value,child:r.child?i(r.child):void 0,children:r.children?r.children.map(i):void 0});return s.filters=this.filters.map(i),s.selectFields=this.selectFields.map(r=>({...r,args:r.args?[...r.args]:void 0,subquery:r.subquery?r.subquery.clone(n):void 0})),s.limitCount=this.limitCount,s.offsetCount=this.offsetCount,s.sortCol=this.sortCol,s.sortDir=this.sortDir,s.orderKeys=this.orderKeys.map(r=>({...r})),s.groupCols=[...this.groupCols],s.groupKeys=this.groupKeys.map(r=>({...r})),s.aggExprs=this.aggExprs.map(r=>({...r})),s.havingFilters=this.havingFilters.map(i),s.joins=this.joins.map(r=>({...r})),s.planner=this.planner,s}cloneExprNode(t){return t.type==="binary"?{...t,left:this.cloneExprNode(t.left),right:this.cloneExprNode(t.right)}:t.type==="fn"?{...t,args:t.args.map(n=>this.cloneExprNode(n))}:{...t}}substituteExpr(t,n){if(t.type==="col"){if(t.name==="*")return t;const s=t.name.includes(".")?t.name.slice(t.name.lastIndexOf(".")+1):t.name,i=n.get(t.name)??n.get(s);return i?this.cloneExprNode(i):{...t}}return t.type==="binary"?{...t,left:this.substituteExpr(t.left,n),right:this.substituteExpr(t.right,n)}:t.type==="fn"?{...t,args:t.args.map(s=>this.substituteExpr(s,n))}:{...t}}substituteColOrExpr(t,n,s){if(n){const i=this.substituteExpr(n,s);return i.type==="col"?{colName:i.name,expr:i}:{expr:i}}if(t){const i=t.includes(".")?t.slice(t.lastIndexOf(".")+1):t,r=s.get(t)??s.get(i);if(r){const o=this.cloneExprNode(r);return o.type==="col"?{colName:o.name}:{expr:o}}return{colName:t}}return{colName:t,expr:n}}substituteFilter(t,n){var i;if(t.type==="and"||t.type==="or")return{...t,children:(i=t.children)==null?void 0:i.map(r=>this.substituteFilter(r,n))};if(t.type==="not"&&t.child)return{...t,child:this.substituteFilter(t.child,n)};if(t.type==="exists")return{...t};const s=this.substituteColOrExpr(t.colName,t.expr,n);return{...t,colName:s.colName,expr:s.expr}}tryFlatten(){var r;if(!this.sourceSubquery)return null;const t=this.sourceSubquery.tryFlatten()??this.sourceSubquery.clone(this.db);if(t.sourceSubquery||t.groupKeys.length>0||t.groupCols.length>0||t.aggExprs.length>0||t.havingFilters.length>0||t.limitCount!==null||t.offsetCount!==null||t.joins.length>0||t.selectFields.some(o=>o.subquery)||this.joins.length>0)return null;const n=new Map;for(const o of t.selectFields){const a=o.expr??{type:"col",name:o.sourceCol??o.alias};n.set(o.alias,a)}for(const o of this.aggExprs)if(o.colName){const a=o.colName.includes(".")?o.colName.slice(o.colName.lastIndexOf(".")+1):o.colName,c=n.get(o.colName)??n.get(a);if(c&&c.type!=="col")return null}for(const o of this.groupKeys){const a=this.substituteColOrExpr(o.colName,o.expr,n);if(!a.colName&&a.expr&&a.expr.type!=="col")return null}const s=new Lt(this.db,t.tableName);s.planner=this.planner??t.planner,s.filters=[...t.filters.map(o=>({...o})),...this.filters.map(o=>this.substituteFilter(o,n))],this.selectFields.length>0?s.selectFields=this.selectFields.map(o=>{if(o.subquery)return{...o,subquery:o.subquery.clone(this.db)};const a=o.expr??{type:"col",name:o.sourceCol??o.alias},c=this.substituteExpr(a,n);return{alias:o.alias,expr:c,sourceCol:c.type==="col"&&c.name!=="*"?c.name:void 0,fn:c.type==="fn"?c.name:void 0}}):t.selectFields.length>0&&(s.selectFields=t.selectFields.map(o=>({...o})));const i=this.aggExprs.length>0||this.groupKeys.length>0||this.groupCols.length>0;return this.orderKeys.length>0?(s.orderKeys=this.orderKeys.map(o=>{const a=this.substituteColOrExpr(o.colName,o.expr,n);return{...o,colName:a.colName,expr:a.expr}}),(r=s.orderKeys[0])!=null&&r.colName&&(s.sortCol=s.orderKeys[0].colName,s.sortDir=s.orderKeys[0].direction)):!i&&t.orderKeys.length>0&&(s.orderKeys=t.orderKeys.map(o=>({...o})),s.sortCol=t.sortCol,s.sortDir=t.sortDir),s.groupKeys=this.groupKeys.map(o=>{const a=this.substituteColOrExpr(o.colName,o.expr,n);return{colName:a.colName,expr:a.expr}}),s.groupCols=this.groupCols.map(o=>{const a=n.get(o);return a&&a.type==="col"?a.name:o}),s.aggExprs=this.aggExprs.map(o=>{if(o.colName){const a=n.get(o.colName);if(a&&a.type==="col")return{...o,colName:a.name}}return{...o}}),s.havingFilters=this.havingFilters.map(o=>this.substituteFilter(o,n)),s.limitCount=this.limitCount,s.offsetCount=this.offsetCount,s}exprReferencesOuter(t,n){if(!t)return!1;if(t.type==="col"){if(t.name.includes(".")){const s=t.name.slice(0,t.name.indexOf("."));if(s==="outer"||!n.has(s))return!0}return!1}return t.type==="binary"?this.exprReferencesOuter(t.left,n)||this.exprReferencesOuter(t.right,n):t.type==="fn"?t.args.some(s=>this.exprReferencesOuter(s,n)):!1}filterIsCorrelatedWithOuter(t,n){var s;if(t.type==="and"||t.type==="or")return((s=t.children)==null?void 0:s.some(i=>this.filterIsCorrelatedWithOuter(i,n)))??!1;if(t.type==="not"&&t.child)return this.filterIsCorrelatedWithOuter(t.child,n);if(t.type==="cmp"&&(t.value instanceof it||typeof t.value=="object"&&t.value!==null&&!x(t.value)&&("node"in t.value||"type"in t.value)||t.subquery&&x(t.subquery)&&this.isSubqueryCorrelated(t.subquery))||(t.type==="in"||t.type==="exists")&&t.subquery&&x(t.subquery)&&this.isSubqueryCorrelated(t.subquery))return!0;if(t.colName&&t.colName.includes(".")){const i=t.colName.slice(0,t.colName.indexOf("."));if(i==="outer"||!n.has(i))return!0}return!!this.exprReferencesOuter(t.expr,n)}isSubqueryCorrelated(t){const n=new Set([t.tableName]);for(const s of t.joins)n.add(s.table);return!!(t.filters.some(s=>this.filterIsCorrelatedWithOuter(s,n))||t.havingFilters.some(s=>this.filterIsCorrelatedWithOuter(s,n))||t.sourceSubquery&&this.isSubqueryCorrelated(t.sourceSubquery)||t.selectFields.some(s=>s.subquery&&this.isSubqueryCorrelated(s.subquery)))}filterContainsCorrelatedSubquery(t){var s;if(t.type==="and"||t.type==="or")return((s=t.children)==null?void 0:s.some(i=>this.filterContainsCorrelatedSubquery(i)))??!1;if(t.type==="not"&&t.child)return this.filterContainsCorrelatedSubquery(t.child);const n=t.subquery&&x(t.subquery)?t.subquery:x(t.value)?t.value:void 0;return!!(n&&this.isSubqueryCorrelated(n))}getRowValue(t,n){if(n in t)return t[n];if(n.startsWith("outer.")){const s=n.slice(6);if(s in t)return t[s]}if(n.includes(".")){const s=n.slice(n.lastIndexOf(".")+1);if(s in t)return t[s]}}bindOuterRowToExpr(t,n,s,i=!1){if(t.type==="col"){if(i)return{type:"literal",value:this.getRowValue(n,t.name)??null};if(t.name.includes(".")){const r=t.name.slice(0,t.name.indexOf("."));if(r==="outer"||!s.has(r))return{type:"literal",value:this.getRowValue(n,t.name)??null}}return{...t}}return t.type==="binary"?{...t,left:this.bindOuterRowToExpr(t.left,n,s,i),right:this.bindOuterRowToExpr(t.right,n,s,i)}:t.type==="fn"?{...t,args:t.args.map(r=>this.bindOuterRowToExpr(r,n,s,i))}:{...t}}bindOuterRowToFilter(t,n,s){var r;if(t.type==="and"||t.type==="or")return{...t,children:(r=t.children)==null?void 0:r.map(o=>this.bindOuterRowToFilter(o,n,s))};if(t.type==="not"&&t.child)return{...t,child:this.bindOuterRowToFilter(t.child,n,s)};let i=t.expr?this.bindOuterRowToExpr(t.expr,n,s,!1):void 0;if(t.type==="cmp"&&(t.value instanceof it||typeof t.value=="object"&&t.value!==null&&!x(t.value)&&("node"in t.value||"type"in t.value))){const o="node"in t.value?t.value.node:t.value,a=this.bindOuterRowToExpr(o,n,s,!0);let c;typeof this.db.getUdf=="function"&&(c=u=>{var _,A;return(A=(_=this.db.getUdf(u))==null?void 0:_.def)==null?void 0:A.call});const l=vt(a,n,c);return l==null?{type:"in",values:[],notIn:!1}:{...t,expr:i,value:l}}return{...t,expr:i,subquery:t.subquery&&x(t.subquery)?this.bindOuterRowToSubquery(t.subquery,n):t.subquery}}bindOuterRowToSubquery(t,n){const s=t.clone(this.db),i=new Set([s.tableName]);for(const r of s.joins)i.add(r.table);return s.filters=s.filters.map(r=>this.bindOuterRowToFilter(r,n,i)),s.havingFilters=s.havingFilters.map(r=>this.bindOuterRowToFilter(r,n,i)),s.sourceSubquery&&(s.sourceSubquery=this.bindOuterRowToSubquery(s.sourceSubquery,n)),s}async evalScalarSubquery(t,n){const i=await(n&&this.isSubqueryCorrelated(t)?this.bindOuterRowToSubquery(t,n):t.clone(this.db)).first();if(!i)return null;const r=Object.keys(i);return r.length>0?i[r[0]]:null}async resolveUncorrelatedFilter(t){if(t.type==="and"||t.type==="or"){const n=[];for(const s of t.children??[])n.push(await this.resolveUncorrelatedFilter(s));return{...t,children:n}}if(t.type==="not"&&t.child)return{...t,child:await this.resolveUncorrelatedFilter(t.child)};if(t.type==="in"&&t.subquery&&x(t.subquery)&&!this.isSubqueryCorrelated(t.subquery)){const s=(await t.subquery.clone(this.db).toArray()).map(r=>{const o=Object.keys(r);return o.length>0?r[o[0]]:null});if(t.notIn&&s.some(r=>r==null))return{type:"in",colName:t.colName,expr:t.expr,values:[],notIn:!1};const i=s.filter(r=>r!=null);if(i.length>Dt)throw new RangeError(`WebDB: whereIn subquery result exceeds maximum limit of ${Dt} elements`);return{type:"in",colName:t.colName,expr:t.expr,values:i,notIn:t.notIn}}if(t.type==="exists"&&t.subquery&&x(t.subquery)&&!this.isSubqueryCorrelated(t.subquery)){const s=await t.subquery.clone(this.db).first()!==null,i=t.notExists?!s:s;return{type:"in",values:[],notIn:i}}if(t.type==="cmp"){const n=t.subquery&&x(t.subquery)?t.subquery:x(t.value)?t.value:void 0;if(n&&!this.isSubqueryCorrelated(n)){const s=await this.evalScalarSubquery(n);return s==null?{type:"in",colName:t.colName,expr:t.expr,values:[],notIn:!1}:{...t,value:s,subquery:void 0}}}return t}async resolveUncorrelatedFilters(t){const n=[];for(const s of t)n.push(await this.resolveUncorrelatedFilter(s));return n}evalFilterTargetValue(t,n,s){let i;if(typeof this.db.getUdf=="function"&&(i=r=>{var o,a;return(a=(o=this.db.getUdf(r))==null?void 0:o.def)==null?void 0:a.call}),n&&t[n]!==void 0)return t[n];if(s){const r=Qt(s);return t[r]!==void 0?t[r]:vt(s,t,i)}if(n)return this.getRowValue(t,n)}evalComparisonValues(t,n,s){if(t==null||s===null||s===void 0)return!1;const i=(n??"=").trim().toLowerCase();switch(i){case"=":return t===s;case"!=":case"<>":return t!==s;case"<":return t<s;case"<=":return t<=s;case">":return t>s;case">=":return t>=s;case"starts_with":return String(t).startsWith(String(s));case"ends_with":return String(t).endsWith(String(s));case"contains":return String(t).includes(String(s));case"like":case"not like":{const r=String(s).replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/%/g,".*").replace(/_/g,"."),a=new RegExp(`^${r}$`,"s").test(String(t));return i==="not like"?!a:a}default:return t===s}}async evalFilterOnRow(t,n){if(n.type==="and"){for(const s of n.children??[])if(!await this.evalFilterOnRow(t,s))return!1;return!0}if(n.type==="or"){for(const s of n.children??[])if(await this.evalFilterOnRow(t,s))return!0;return!1}if(n.type==="not"&&n.child){if(n.child.type==="cmp"||n.child.type==="in"){const s=this.evalFilterTargetValue(t,n.child.colName,n.child.expr);if(s==null)return!1}return!await this.evalFilterOnRow(t,n.child)}if(n.type==="null"){const s=this.evalFilterTargetValue(t,n.colName,n.expr),i=s==null;return n.isNull?i:!i}if(n.type==="expr"&&n.expr){let s;typeof this.db.getUdf=="function"&&(s=r=>{var o,a;return(a=(o=this.db.getUdf(r))==null?void 0:o.def)==null?void 0:a.call});const i=vt(n.expr,t,s);return!!(i&&i!==0)}if(n.type==="exists"){if(n.subquery&&x(n.subquery)){const r=await(this.isSubqueryCorrelated(n.subquery)?this.bindOuterRowToSubquery(n.subquery,t):n.subquery.clone(this.db)).first()!==null;return n.notExists?!r:r}return!!n.notExists}if(n.type==="in"){let s=n.values??[];if(n.subquery&&x(n.subquery)){const c=(await(this.isSubqueryCorrelated(n.subquery)?this.bindOuterRowToSubquery(n.subquery,t):n.subquery.clone(this.db)).toArray()).map(l=>{const u=Object.keys(l);return u.length>0?l[u[0]]:null});if(n.notIn&&c.some(l=>l==null))return!1;s=c.filter(l=>l!=null)}if(!n.colName&&!n.expr)return n.notIn?s.length===0:s.length>0;if(s.length===0)return!!n.notIn;const i=this.evalFilterTargetValue(t,n.colName,n.expr);if(i==null||n.notIn&&s.some(o=>o==null))return!1;const r=s.includes(i);return n.notIn?!r:r}if(n.type==="cmp"){const s=this.evalFilterTargetValue(t,n.colName,n.expr),i=n.subquery&&x(n.subquery)?n.subquery:x(n.value)?n.value:void 0,r=i?await this.evalScalarSubquery(i,t):n.value;return this.evalComparisonValues(s,n.op,r)}return!0}async evalFiltersOnRows(t,n){if(n.length===0)return t;const s=await this.resolveUncorrelatedFilters(n),i=[];for(const r of t){let o=!0;for(const a of s)if(!await this.evalFilterOnRow(r,a)){o=!1;break}o&&i.push(r)}return i}performInMemoryAggregation(t){const n=Math.max(this.groupKeys.length,this.groupCols.length),s=new Map;if(n===0)s.set("__global__",{keyRow:{},rows:t});else for(const a of t){const c=[],l={};for(let A=0;A<n;A++){const f=this.groupKeys[A],g=this.groupCols[A],d=this.evalFilterTargetValue(a,(f==null?void 0:f.colName)??g,f==null?void 0:f.expr);c.push(d);const I=(f==null?void 0:f.colName)??(f!=null&&f.expr?Qt(f.expr):g);I&&(l[I]=d,I.includes(".")&&(l[I.slice(I.lastIndexOf(".")+1)]=d)),g&&(l[g]=d)}const u=JSON.stringify(c);let _=s.get(u);_||(_={keyRow:l,rows:[]},s.set(u,_)),_.rows.push(a)}let i;typeof this.db.getUdf=="function"&&(i=a=>{var c,l;return(l=(c=this.db.getUdf(a))==null?void 0:c.def)==null?void 0:l.call});const r=(a,c,l,u)=>{const _=c.toLowerCase();if(_==="count"){if(!l&&(!u||u.type==="col"&&u.name==="*"))return a.length;let f=0;for(const g of a){const d=u?vt(u,g,i):this.getRowValue(g,l);d!=null&&f++}return f}const A=[];for(const f of a){const g=u?vt(u,f,i):l?this.getRowValue(f,l):null;g!=null&&A.push(g)}return A.length===0?null:_==="sum"?A.reduce((f,g)=>f+Number(g),0):_==="avg"?A.reduce((f,g)=>f+Number(g),0)/A.length:_==="min"?A.reduce((f,g)=>g<f?g:f,A[0]):_==="max"?A.reduce((f,g)=>g>f?g:f,A[0]):null},o=[];for(const{keyRow:a,rows:c}of s.values()){const l={...a};for(const u of this.aggExprs){const _=r(c,u.func,u.colName),A=u.alias??(u.colName?`${u.func}_${u.colName}`:u.func);l[A]=_,l[`${u.func}(${u.colName??"*"})`]=_,u.colName||(l[u.func]=_)}for(const u of this.selectFields)if(u.expr&&u.expr.type==="fn"&&ge(u.expr.name)){const _=u.expr.args[0],A=r(c,u.expr.name,_&&_.type==="col"&&_.name!=="*"?_.name:void 0,_);l[u.alias]=A,l[Qt(u.expr)]=A}o.push(l)}return o}async attachSelectSubqueries(t){const n=this.selectFields.filter(i=>i.subquery);if(n.length===0||t.length===0)return;const s=new Map;for(const i of n)if(i.subquery&&!this.isSubqueryCorrelated(i.subquery)){const r=await this.evalScalarSubquery(i.subquery);s.set(i,r)}for(const i of t)for(const r of n)s.has(r)?i[r.alias]=s.get(r):r.subquery&&(i[r.alias]=await this.evalScalarSubquery(r.subquery,i))}async executeMaterializedDerivedTable(){let t=await this.sourceSubquery.clone(this.db).toArray();for(const r of this.joins){const o=await new Lt(this.db,r.table).toArray(),a=[];for(const c of t){let l=!1;const u=this.getRowValue(c,r.leftCol);for(const _ of o){const A=this.getRowValue(_,r.rightCol);if(this.evalComparisonValues(u,r.op,A)){l=!0;const f={...c};for(const[g,d]of Object.entries(_))f[`${r.table}.${g}`]=d,g in f||(f[g]=d);a.push(f)}}!l&&r.type==="left"&&a.push({...c})}t=a}t=await this.evalFiltersOnRows(t,this.filters),(this.aggExprs.length>0||this.groupKeys.length>0||this.groupCols.length>0)&&(t=this.performInMemoryAggregation(t),this.havingFilters.length>0&&(t=await this.evalFiltersOnRows(t,this.havingFilters)));const s=this.selectFields.some(r=>r.subquery),i=s&&this.orderKeys.some(r=>this.selectFields.some(o=>o.subquery&&(o.alias===r.colName||o.alias===(r.expr?Qt(r.expr):void 0))));return i&&await this.attachSelectSubqueries(t),this.orderKeys.length>0&&(t=this.sortAggregatedRows(t)),this.offsetCount!==null&&this.offsetCount>0&&(t=t.slice(this.offsetCount)),this.limitCount!==null&&this.limitCount>=0&&(t=t.slice(0,this.limitCount)),s&&!i&&await this.attachSelectSubqueries(t),this.selectFields.length>0&&(t=t.map(r=>this.projectRow(r))),t}projectRow(t){const n=Object.keys(t);if(this.selectFields.length>0&&n.length===this.selectFields.length&&this.selectFields.every(i=>i.alias in t))return t;const s={};for(const i of this.selectFields){const r=i.alias;if(t[r]!==void 0)s[r]=t[r];else if(i.expr&&t[Qt(i.expr)]!==void 0)s[r]=t[Qt(i.expr)];else if(i.sourceCol!==void 0&&t[i.sourceCol]!==void 0)s[r]=t[i.sourceCol];else if(i.expr){let o;typeof this.db.getUdf=="function"&&(o=a=>{var c,l;return(l=(c=this.db.getUdf(a))==null?void 0:c.def)==null?void 0:l.call}),s[r]=vt(i.expr,t,o)}else s[r]=null}return s}async explain(){if(this.assertSubqueryDepth(),this.sourceSubquery){const r=this.tryFlatten();if(r)return r.explain();const o=await this.sourceSubquery.clone(this.db).explain(),a=await this.resolveUncorrelatedFilters(this.filters);return{plan:{...o.plan,filters:[...o.plan.filters,...a],orderBy:this.orderKeys.length>0?this.orderKeys:o.plan.orderBy,groupBy:this.groupKeys.length>0?this.groupKeys:this.groupCols.length>0?this.groupCols:o.plan.groupBy,aggregates:this.aggExprs.length>0?this.aggExprs:o.plan.aggregates,having:this.havingFilters.length>0?this.havingFilters:o.plan.having,select:this.selectFields.length>0?this.selectFields:o.plan.select,limit:this.limitCount!==null?this.limitCount:o.plan.limit,offset:this.offsetCount!==null?this.offsetCount:o.plan.offset},bytecodeSize:o.bytecodeSize,instructions:o.instructions,assembly:o.assembly}}const t=await this.resolveUncorrelatedFilters(this.filters.filter(r=>!this.filterContainsCorrelatedSubquery(r))),n=await this.resolveUncorrelatedFilters(this.havingFilters.filter(r=>!this.filterContainsCorrelatedSubquery(r))),s=this.selectFields.filter(r=>!r.subquery),i=s.map(r=>({expr:r.expr??{type:"col",name:r.sourceCol??r.alias},alias:r.alias}));return this.db.explainQuery(this.tableName,t,{joins:this.joins.length>0?this.joins:void 0,orderBy:this.orderKeys.length>0?this.orderKeys:void 0,groupBy:this.groupKeys.length>0?this.groupKeys:this.groupCols.length>0?this.groupCols:void 0,aggregates:this.aggExprs.length>0?this.aggExprs:void 0,having:n.length>0?n:void 0,select:s.length>0?s:void 0,selectExprs:i.length>0?i:void 0,limit:this.limitCount!==null?this.limitCount:void 0,offset:this.offsetCount!==null?this.offsetCount:void 0,planner:this.planner})}getOrderKeyValue(t,n){const s=n.colName??(n.expr?Qt(n.expr):void 0);if(!s)return;if(t[s]!==void 0)return t[s];const i=s.includes(".")?s.slice(s.lastIndexOf(".")+1):s;if(t[i]!==void 0)return t[i];if(this.selectFields.length>0){for(const r of this.selectFields)if((r.sourceCol===s||r.sourceCol===i||r.alias===s||r.alias===i)&&t[r.alias]!==void 0)return t[r.alias]}if(t[`__sort_${s}`]!==void 0)return t[`__sort_${s}`];if(t[`__sort_${i}`]!==void 0)return t[`__sort_${i}`];if(n.expr){let r;return typeof this.db.getUdf=="function"&&(r=o=>{var a,c;return(c=(a=this.db.getUdf(o))==null?void 0:a.def)==null?void 0:c.call}),vt(n.expr,t,r)}}sortAggregatedRows(t){return[...t].sort((n,s)=>{for(const i of this.orderKeys){const r=this.getOrderKeyValue(n,i),o=this.getOrderKeyValue(s,i);if(r===o)continue;if(r==null)return i.nullOrder==="nulls_first"?-1:1;if(o==null)return i.nullOrder==="nulls_first"?1:-1;const a=i.direction==="desc"?-1:1;return typeof r=="number"&&typeof o=="number"?(r-o)*a:String(r).localeCompare(String(o))*a}return 0})}async toArray(){if(this.assertSubqueryDepth(),this.sourceSubquery){const p=this.tryFlatten();return p?p.toArray():this.executeMaterializedDerivedTable()}const t=this.filters.some(p=>this.filterContainsCorrelatedSubquery(p)),n=this.havingFilters.some(p=>this.filterContainsCorrelatedSubquery(p)),s=this.selectFields.some(p=>p.subquery),i=this.selectFields.some(p=>p.subquery&&this.isSubqueryCorrelated(p.subquery)),r=await this.resolveUncorrelatedFilters(this.filters.filter(p=>!this.filterContainsCorrelatedSubquery(p))),o=this.filters.filter(p=>this.filterContainsCorrelatedSubquery(p)),a=this.joins.length>0,c=this.orderKeys.length>0,l=this.aggExprs.length>0||this.groupKeys.length>0||this.groupCols.length>0;if(t){let p=await this.db.executeQuery(this.tableName,r,{limit:null,offset:null,sortCol:null,sortDir:this.sortDir,joins:a?this.joins:void 0,planner:this.planner});return p=await this.evalFiltersOnRows(p,o),l&&(p=this.performInMemoryAggregation(p),this.havingFilters.length>0&&(p=await this.evalFiltersOnRows(p,this.havingFilters))),s&&await this.attachSelectSubqueries(p),c&&(p=this.sortAggregatedRows(p)),this.offsetCount!==null&&this.offsetCount>0&&(p=p.slice(this.offsetCount)),this.limitCount!==null&&this.limitCount>=0&&(p=p.slice(0,this.limitCount)),this.selectFields.length>0&&(p=p.map(y=>this.projectRow(y))),p}const u=await this.resolveUncorrelatedFilters(this.havingFilters.filter(p=>!this.filterContainsCorrelatedSubquery(p))),_=this.selectFields.filter(p=>!p.subquery),A=_.map(p=>({expr:p.expr??{type:"col",name:p.sourceCol??p.alias},alias:p.alias}));if(a&&c&&A.length>0)for(const p of this.orderKeys){const y=p.colName;if(y){const T=y.includes(".")?y.slice(y.lastIndexOf(".")+1):y;_.some(B=>B.alias===y||B.alias===T||B.sourceCol===y||B.sourceCol===T)||A.push({expr:{type:"col",name:y},alias:`__sort_${y}`})}}const f=!i||l,g=await this.db.executeQuery(this.tableName,r,{limit:a&&c&&l||n?null:this.limitCount,offset:a&&c&&l||n?null:this.offsetCount,sortCol:a?null:this.sortCol,sortDir:this.sortDir,orderBy:a&&l?void 0:c?this.orderKeys:void 0,joins:a?this.joins:void 0,groupBy:this.groupKeys.length>0?this.groupKeys:this.groupCols.length>0?this.groupCols:void 0,aggregates:this.aggExprs.length>0?this.aggExprs:void 0,having:u.length>0?u:void 0,select:f&&_.length>0?_:void 0,selectExprs:f&&A.length>0?A:void 0,planner:this.planner});let d=g;if(n){const p=this.havingFilters.filter(y=>this.filterContainsCorrelatedSubquery(y));d=await this.evalFiltersOnRows(d,p)}const I=g.isOrderSatisfied===!0;return(l||a)&&c&&!I?(d=this.sortAggregatedRows(d),(a||n)&&(this.offsetCount!==null&&this.offsetCount>0&&(d=d.slice(this.offsetCount)),this.limitCount!==null&&this.limitCount>=0&&(d=d.slice(0,this.limitCount)))):n&&(this.offsetCount!==null&&this.offsetCount>0&&(d=d.slice(this.offsetCount)),this.limitCount!==null&&this.limitCount>=0&&(d=d.slice(0,this.limitCount))),s&&await this.attachSelectSubqueries(d),this.selectFields.length>0&&(d=d.map(p=>this.projectRow(p))),d}async first(){const t=await this.limit(1).toArray();return t.length>0?t[0]:null}async update(t,n){if(!this.db.executeUpdate)throw new Error("Database executor does not support executeUpdate");this.assertSubqueryDepth();const s=await this.resolveUncorrelatedFilters(this.filters);return this.db.executeUpdate(this.tableName,s,t,n)}async delete(t){if(!this.db.executeDelete)throw new Error("Database executor does not support executeDelete");this.assertSubqueryDepth();const n=await this.resolveUncorrelatedFilters(this.filters);return this.db.executeDelete(this.tableName,n,t)}}class sr{constructor(t,n,s,i,r="js",o,a,c){U(this,"vfs");U(this,"io");U(this,"driver");U(this,"coreMode");U(this,"wasmCore");U(this,"planner");U(this,"coordinator");U(this,"currentLeaseId",null);U(this,"vmCtx");U(this,"udfs",new Map);U(this,"nextUdfId",1);U(this,"tableMetaCache",new Map);U(this,"tableTailPages",new Map);U(this,"indexTailPages",new Map);U(this,"beforeCommitHooks",new Set);U(this,"commitHooks",new Set);U(this,"subscriptions",new Set);U(this,"activeTxChanges",[]);U(this,"activeTxOrigin","local");U(this,"activeTxMeta");U(this,"activeTxId",0);U(this,"nextAutoTxId",1e6);U(this,"isRunningBeforeCommit",!1);U(this,"broadcastChannel",null);U(this,"instanceId",Math.random().toString(36).slice(2)+Date.now().toString(36));if(this.vfs=t,this.io=n,this.driver=s,this.coordinator=i,this.coreMode=r,this.wasmCore=o,this.planner=a,this.vmCtx=Nr(),this.coordinator.setOnCrossTabInvalidated(async()=>{this.tableMetaCache.clear(),this.tableTailPages.clear(),this.indexTailPages.clear();const l=hn(this.driver.getSlotDataView(0));for(const u of l){let _=u.colCatalogPageId;for(;_!==0;){const A=await this.driver.acquireAndPinPage(_),f=this.driver.getSlotDataView(A);_=he(f,0).nextColCatalogPageId}}}),typeof BroadcastChannel<"u"&&c){const l=`webdb_sync_${t.name}_${c}`;this.broadcastChannel=new BroadcastChannel(l),this.broadcastChannel.onmessage=u=>{const _=u.data;if(!_||_.senderId===this.instanceId)return;const{tables:A,origin:f,meta:g,changeCounter:d,schemaVersion:I}=_;this.coordinator.leaseQueue.enqueue(async()=>{await this.coordinator.syncCrossTabState(!0),this.notifySubscriptions({tables:Array.isArray(A)?A:[],origin:f??"remote",meta:g,changeCounter:typeof d=="number"?d:this.getSyncState().changeCounter,schemaVersion:typeof I=="number"?I:this.getSyncState().schemaVersion,crossTab:!0})}).catch(()=>{})}}}get pool(){return this.driver}static async open(t){const n=t.storage||"memory";let s;t.vfs?s=t.vfs:n==="idb"?s=new Wr(t.name):n==="opfs"?s=new Hr(t.name):s=new qr;const i=t.slotCount??Qe,r=t.maxQueryMemory??ve,o=Ro(Math.max(i,Qe),r),a=t.core??"js";let c;a==="wasm"&&(c=Lo(o,t.wasmBinary?new Uint8Array(t.wasmBinary):void 0));const l=new Ii({vfs:s,memory:o}),u=new Fo({io:l,memory:o,slotCount:i,maxQueryMemory:r,useDefaultLayoutOffsets:!0}),_=t.name&&s.name!=="memory"?`webdb_lock_${s.name}_${t.name}`:void 0,A=new Qo(s,u,l,_);u.setTransactionCoordinator(A),await A.leaseQueue.enqueue(async()=>{await Hi(s);const[g]=await s.readPages([1]);if(!g)yo(u.getSlotDataView(0)),u.markDirty(0),await u.flushSlot(0);else{u.getPageBytesInSlot(0).set(g),u.clearDirty(0),qn(u.getSlotDataView(0),!0);const d=hn(u.getSlotDataView(0));for(const I of d){let p=I.colCatalogPageId;for(;p!==0;){const y=await u.acquireAndPinPage(p),T=u.getSlotDataView(y);p=he(T,0).nextColCatalogPageId}}}A.recordDiskPage1State()});const f=new sr(s,l,u,A,a,c,t.planner,t.name);return t.initialData&&await f.importBinary(t.initialData),f}getPlanner(){return this.planner}setPlanner(t){return this.planner=t,this}validateIdentifier(t,n="Identifier"){if(!t||typeof t!="string"||t.length===0)throw new Error(`${n} cannot be empty`);if(t.length>ne)throw new Lr(t,ne)}async createTable(t,n){return this.coordinator.leaseQueue.enqueue(()=>this._createTableInternal(t,n),this.currentLeaseId??void 0)}async _createTableInternal(t,n){var g;if(this.validateIdentifier(t,"Table name"),n.length===0)throw new Error("Table must have at least one column");if(n.length>ue)throw new Ln(n.length,ue);const s=new Set;let i=!1;for(const d of n){if(this.validateIdentifier(d.name,"Column name"),s.has(d.name))throw new ss(d.name,t);s.add(d.name);const I=typeof d.flags=="number"?d.flags:0;(d.primaryKey||(g=d.flags)!=null&&g.primaryKey||I&tt.PRIMARY_KEY)&&(i=!0)}const r=this.pool.getSlotDataView(0);if(xt(r,t)!==-1)throw new is(t);if(ki(r)===-1)throw new gi(ce,ce);const o=Math.ceil(n.length/Te),a=i&&Ns(r)!==-1?1:0,c=1+o+a,l=[];for(let d=0;d<c;d++)l.push(await this.driver.allocateAndPinPage());let u=0;const _={allocateNewPage:()=>{if(u<l.length)return l[u++];const I=r.getUint32(12,!0)+1;return r.setUint32(12,I,!0),this.pool.markDirty(0),I},getPageBytes:d=>{let I=this.pool.getResidentSlot(d);return I===-1&&(I=d<=this.pool.slotCount?d-1:1,this.pool.assignSlot(I,d)),this.pool.getPageBytesInSlot(I)},markPageDirty:d=>{const I=this.pool.getResidentSlot(d);I!==-1&&this.pool.markDirty(I)}};let A;try{A=bo(r,_,t,n)}catch(d){for(const I of l)this.driver.forceUnpinPage(I),await this.driver.freePage(I,!0);throw d}this.driver.unpinPage(A.rootPageId);for(const d of A.indexes??[])d.rootPageId>1&&this.driver.unpinPage(d.rootPageId);let f=A.colCatalogPageId;for(;f!==0;){const d=await this.driver.acquirePage(f);this.pool.isSlotPinned(d)||this.pool.pinSlot(d),f=he(this.pool.getSlotDataView(d),0).nextColCatalogPageId}return this.coordinator.isInTransaction()||await this.driver.flushAllDirty(),this.tableMetaCache.delete(t.toLowerCase()),A}async getTable(t){return this.coordinator.leaseQueue.enqueue(()=>this._getTableInternal(t),this.currentLeaseId??void 0)}async _getTableInternal(t){const n=t.toLowerCase(),s=this.tableMetaCache.get(n);if(s)return s;const i=this.pool.getSlotDataView(0),r=xt(i,t);if(r===-1)throw new Bn(t);let a=Jt(i,r).colCatalogPageId;for(;a!==0;){await this.driver.acquirePage(a);const u=this.pool.getResidentSlot(a);a=he(this.pool.getSlotDataView(u),0).nextColCatalogPageId}const l=qi(i,{getPageBytes:u=>{const _=this.pool.getResidentSlot(u);return _!==-1?this.pool.getPageBytesInSlot(_):new Uint8Array(4096)}},t);return this.tableMetaCache.set(n,l),l}async listTables(){return this.coordinator.leaseQueue.enqueue(async()=>{const t=this.pool.getSlotDataView(0),n=hn(t),s=[];for(const i of n)s.push(await this._getTableInternal(i.name));return s},this.currentLeaseId??void 0)}async freeTableTreePages(t){if(t<=1)return;const n=[],s=new Set,i=[t];for(;i.length>0;){const r=i.shift();if(r<=1||s.has(r))continue;s.add(r);const o=await this.driver.acquirePage(r),a=this.pool.getSlotDataView(o),c=qe(a,0);if(c===Me){this.driver.forceUnpinPage(r);continue}if(n.push(r),c===fi||c===Ur){const l=ut(a,0);for(let _=0;_<l;_++){const A=ot(a,0,_);if(A>0&&A+4<=4096){const f=a.getUint32(A,!0);f>1&&!s.has(f)&&i.push(f)}}const u=Ut(a,0);u>1&&!s.has(u)&&i.push(u)}else if(c===es||c===ts){const l=Ut(a,0);l>1&&!s.has(l)&&i.push(l)}}for(const r of n)this.driver.forceUnpinPage(r),await this.driver.freePage(r,!0)}async dropTable(t){return this.coordinator.leaseQueue.enqueue(()=>this._dropTableInternal(t),this.currentLeaseId??void 0)}async _dropTableInternal(t){var o;this.tableMetaCache.delete(t.toLowerCase()),this.tableTailPages.delete(t);const n=this.pool.getSlotDataView(0),s=xt(n,t);if(s===-1)throw new Bn(t);const i=Jt(n,s);for(let a=0;a<Je;a++){const c=gn(n,a);c&&(c.tableId===i.tableId||c.name.toLowerCase().startsWith(`idx_${t.toLowerCase()}_`)||c.name.toLowerCase()===`pk_${t.toLowerCase()}`)&&(c.rootPageId>1&&(await this.freeTableTreePages(c.rootPageId),this.indexTailPages.delete(c.rootPageId)),Mi(n,a))}i.rootPageId>1&&await this.freeTableTreePages(i.rootPageId);let r=i.colCatalogPageId;for(;r>1;){const a=await this.driver.acquirePage(r),c=this.pool.getSlotDataView(a);if(qe(c,0)===Me){this.driver.forceUnpinPage(r);break}const _=he(c,0).nextColCatalogPageId;this.driver.forceUnpinPage(r),await this.driver.freePage(r,!0),r=_}Uo(n,s),Ze(n),re(n),$t(n),this.pool.markDirty(0),this.coordinator.isInTransaction()||await this.driver.flushAllDirty(),((o=this.vmCtx.table)==null?void 0:o.name.toLowerCase())===t.toLowerCase()&&(this.vmCtx.table=null)}async renameTable(t,n){return this.coordinator.leaseQueue.enqueue(()=>this._renameTableInternal(t,n),this.currentLeaseId??void 0)}async _renameTableInternal(t,n){var l;this.validateIdentifier(n,"Table name");const s=this.pool.getSlotDataView(0),i=xt(s,t);if(i===-1)throw new Bn(t);if(t===n)return this._getTableInternal(n);if(xt(s,n)!==-1)throw new is(n);const r=Jt(s,i);r.name=n,An(s,i,r);const o=`pk_${t}`,a=`idx_${t}_`;for(let u=0;u<Je;u++){const _=gn(s,u);if(_&&_.tableId===r.tableId){let A=null;_.name===o?A=`pk_${n}`:_.name.startsWith(a)&&(A=`idx_${n}_${_.name.slice(a.length)}`),A&&A.length<=ne&&!bs(s,A)&&(_.name=A,Os(s,u,_))}}Ze(s),re(s),$t(s),this.pool.markDirty(0),this.tableMetaCache.delete(t.toLowerCase()),this.tableMetaCache.delete(n.toLowerCase());const c=this.tableTailPages.get(t);return c!==void 0&&(this.tableTailPages.delete(t),this.tableTailPages.set(n,c)),((l=this.vmCtx.table)==null?void 0:l.name.toLowerCase())===t.toLowerCase()&&(this.vmCtx.table=null),this.coordinator.isInTransaction()||await this.driver.flushAllDirty(),this._getTableInternal(n)}async renameColumn(t,n,s){return this.coordinator.leaseQueue.enqueue(()=>this._renameColumnInternal(t,n,s),this.currentLeaseId??void 0)}async _renameColumnInternal(t,n,s){var g;this.validateIdentifier(s,"Column name");const i=await this._getTableInternal(t),r=i.columns.findIndex(d=>d.name===n);if(r===-1)throw new fe(n,t);if(n===s)return i;if(i.columns.some((d,I)=>I!==r&&d.name===s))throw new ss(s,t);const{pageChainIdx:o,colIdxInPage:a}=No(r);let c=i.colCatalogPageId;for(let d=0;d<o;d++){const I=await this.driver.acquirePage(c);c=he(this.pool.getSlotDataView(I),0).nextColCatalogPageId}const l=await this.driver.acquirePage(c),u=this.pool.getSlotDataView(l),_={...i.columns[r],name:s};Gi(u,0,a,_);const A=Ge(this.pool.getPageBytesInSlot(l));u.setUint32(12,A,!0),this.pool.markDirty(l);const f=this.pool.getSlotDataView(0);return Ze(f),re(f),$t(f),this.pool.markDirty(0),this.tableMetaCache.delete(t.toLowerCase()),((g=this.vmCtx.table)==null?void 0:g.name.toLowerCase())===t.toLowerCase()&&(this.vmCtx.table=null),this.coordinator.isInTransaction()||await this.driver.flushAllDirty(),this._getTableInternal(t)}async addColumn(t,n,s){this.validateIdentifier(n.name,"Column name");const i=(s==null?void 0:s.defaultValue)!==void 0?s.defaultValue:n.defaultValue!==void 0?n.defaultValue:null;return this._executeTableRebuildAtomic(t,r=>{var _,A,f;if(r.columns.some(g=>g.name===n.name))throw new ss(n.name,t);if(r.columns.length+1>ue)throw new Ln(r.columns.length+1,ue);const o=typeof n.flags=="number"?n.flags:0,a=!!n.primaryKey||!!((_=n.flags)!=null&&_.primaryKey)||(o&tt.PRIMARY_KEY)!==0,c=!!n.autoInc||!!((A=n.flags)!=null&&A.autoInc)||(o&tt.AUTO_INC)!==0,l=!!n.indexed||!!((f=n.flags)!=null&&f.indexed)||(o&tt.INDEXED)!==0;if(a&&r.columns.some(g=>(g.flags&tt.PRIMARY_KEY)!==0))throw new Error(`Cannot add a PRIMARY KEY column "${n.name}" to table "${t}" because it already has a primary key`);return{newColumns:[...r.columns.map(g=>({name:g.name,type:g.type,flags:{primaryKey:(g.flags&tt.PRIMARY_KEY)!==0,notNull:(g.flags&tt.NOT_NULL)!==0,indexed:(g.flags&tt.INDEXED)!==0,autoInc:(g.flags&tt.AUTO_INC)!==0}})),n],transformRow:g=>{const d={...g};return(!c||i!==null)&&(d[n.name]=i),d},keepIndex:()=>!0,newAutoIndexCol:l&&!a?n.name:void 0}})}async dropColumn(t,n){return this.validateIdentifier(n,"Column name"),this._executeTableRebuildAtomic(t,s=>{const i=s.columns.findIndex(a=>a.name===n);if(i===-1)throw new fe(n,t);if(s.columns.length<=1)throw new Ai(`Cannot drop column "${n}" from table "${t}": table must have at least one column`);if(s.columns[i].flags&tt.PRIMARY_KEY)throw new Ai(`Cannot drop PRIMARY KEY column "${n}" from table "${t}"`);return{newColumns:s.columns.filter(a=>a.name!==n).map(a=>({name:a.name,type:a.type,flags:{primaryKey:(a.flags&tt.PRIMARY_KEY)!==0,notNull:(a.flags&tt.NOT_NULL)!==0,indexed:(a.flags&tt.INDEXED)!==0,autoInc:(a.flags&tt.AUTO_INC)!==0}})),transformRow:a=>{const c={...a};return delete c[n],c},keepIndex:a=>!a.includes(n)}})}async alterTable(t,n){switch(n.type){case"renameTable":return this.renameTable(t,n.newName);case"renameColumn":return this.renameColumn(t,n.from,n.to);case"addColumn":return this.addColumn(t,n.column,{defaultValue:n.defaultValue});case"dropColumn":return this.dropColumn(t,n.column);default:throw new Error(`Unsupported alterTable operation: ${n==null?void 0:n.type}`)}}async _executeTableRebuildAtomic(t,n){return this.coordinator.isInTransaction()?this.coordinator.leaseQueue.enqueue(async()=>{const s=await this.coordinator.captureSavepoint();try{return await this._rebuildTableSchemaInternal(t,n)}catch(i){throw this.tableMetaCache.clear(),this.tableTailPages.clear(),this.indexTailPages.clear(),await this.coordinator.restoreSavepoint(s),i}},this.currentLeaseId??void 0):this.transaction(s=>s._rebuildTableSchemaInternal(t,n))}async _rebuildTableSchemaInternal(t,n){const s=await this._getTableInternal(t),{newColumns:i,transformRow:r,keepIndex:o,newAutoIndexCol:a}=n(s),c=[];let l=s.rootPageId;for(;l!==0;){let d=await this.driver.acquirePage(l),I=this.pool.getSlotDataView(d);const p=ut(I,0),y=Ut(I,0);for(let T=0;T<p;T++){d=await this.driver.acquirePage(l),I=this.pool.getSlotDataView(d);const N=ot(I,0,T),B=xe(s.columns,I,N);B&&c.push(r(B))}l=y}const u=s.autoIncNext,_=this.pool.getSlotDataView(0),A=Ae(_,s.tableId),f=[];for(const d of A){if(d.flags&It.PRIMARY)continue;const I=d.columnIndices.slice(0,d.columnCount).map(p=>{var y;return(y=s.columns[p])==null?void 0:y.name}).filter(p=>typeof p=="string");I.length===d.columnCount&&o(I)&&f.push({name:d.name,colNames:I,unique:(d.flags&It.UNIQUE)!==0})}await this._dropTableInternal(t),await this._createTableInternal(t,i);for(const d of f)await this._createIndexInternal(t,d.colNames,{name:d.name,unique:d.unique});a&&!f.some(d=>d.colNames.length===1&&d.colNames[0]===a)&&await this._createIndexInternal(t,a),c.length>0&&await this._insertManyInternal(t,c,!1);const g=xt(_,t);if(g!==-1){const d=Jt(_,g);u>d.autoIncNext&&(d.autoIncNext=u,An(_,g,d),$t(_),this.pool.markDirty(0))}return this.tableMetaCache.delete(t.toLowerCase()),this.coordinator.isInTransaction()||await this.driver.flushAllDirty(),this._getTableInternal(t)}async createIndex(t,n,s){return this.coordinator.leaseQueue.enqueue(()=>this._createIndexInternal(t,n,s),this.currentLeaseId??void 0)}async _createIndexInternal(t,n,s){const i=await this._getTableInternal(t),r=Array.isArray(n)?n:[n];if(r.length===0)throw new Error(`At least one column must be specified for createIndex on table "${t}"`);if(r.length>8)throw new Error(`Maximum 8 columns allowed per index (requested ${r.length})`);const o=[];for(const B of r){const P=i.columns.findIndex(F=>F.name===B);if(P===-1)throw new fe(B,t);o.push(P)}const a=(s==null?void 0:s.name)??`idx_${t}_${r.join("_")}`,c=this.pool.getSlotDataView(0);if(bs(c,a)!==null)throw new hi(a);const _=Ae(c,i.tableId).find(B=>{if(B.columnCount!==o.length)return!1;for(let P=0;P<B.columnCount;P++)if(B.columnIndices[P]!==o[P])return!1;return!0});if(_)throw new hi(_.name||a);const A=Ns(c);if(A===-1)throw new Fr(Je,Je);const f=await this.driver.allocateAndPinPage(),g=this.pool.getResidentSlot(f),d=this.pool.getSlotDataView(g);ys(d,0,0),this.pool.markDirty(g),this.pool.unpinSlot(g);const I=!!(s!=null&&s.unique);let p=i.rootPageId;for(;p!==0;){let B=await this.driver.acquirePage(p),P=this.pool.getSlotDataView(B);const F=ut(P,0),w=Ut(P,0);for(let S=0;S<F;S++){B=await this.driver.acquirePage(p),P=this.pool.getSlotDataView(B);const v=ot(P,0,S),L=xe(i.columns,P,v);if(L){const h=BigInt(p)<<16n|BigInt(S),{keyVal:b,keyType:k}=this.extractIndexKey(i.columns,{columnCount:o.length,columnIndices:o},L);if(b!=null){if(I&&await this.probeIndexUnique(f,k,b))throw await this.freeTableTreePages(f),this.indexTailPages.delete(f),new tn(`Duplicate key value violates unique constraint "${a}" on table "${t}"`);await this.insertIntoIndex(f,k,b,h)}}}p=w}const y=[0,0,0,0,0,0,0,0],T=[0,0,0,0,0,0,0,0];for(let B=0;B<o.length&&B<8;B++)y[B]=o[B];const N=I?It.UNIQUE:0;Os(c,A,{indexId:A+1,tableId:i.tableId,rootPageId:f,columnCount:o.length,flags:N,columnIndices:y,colDirections:T,name:a}),Ze(c),re(c),$t(c),this.pool.markDirty(0),this.tableMetaCache.delete(t.toLowerCase()),this.indexTailPages.delete(f),this.coordinator.isInTransaction()||await this.driver.flushAllDirty()}async dropIndex(t){return this.coordinator.leaseQueue.enqueue(()=>this._dropIndexInternal(t),this.currentLeaseId??void 0)}async _dropIndexInternal(t){const n=this.pool.getSlotDataView(0),s=bs(n,t);if(!s)throw new Rr(t);s.desc.rootPageId>1&&(await this.freeTableTreePages(s.desc.rootPageId),this.indexTailPages.delete(s.desc.rootPageId)),Mi(n,s.slotIdx),Ze(n),re(n),$t(n),this.pool.markDirty(0),this.tableMetaCache.clear(),this.indexTailPages.clear(),this.coordinator.isInTransaction()||await this.driver.flushAllDirty()}async listIndexes(t){return this.coordinator.leaseQueue.enqueue(async()=>{const n=this.pool.getSlotDataView(0);if(t){const i=await this._getTableInternal(t);return Ae(n,i.tableId)}const s=[];for(let i=0;i<Je;i++){const r=gn(n,i);r&&s.push(r)}return s},this.currentLeaseId??void 0)}extractIndexKey(t,n,s){if(n.columnCount===1){const i=t[n.columnIndices[0]];return{keyVal:s[i.name],keyType:i.type}}return{keyVal:Cs(t,n.columnIndices,n.columnCount,s),keyType:C.BLOB}}async probeIndexUnique(t,n,s,i){let r=t;for(;r!==0;){const o=await this.driver.acquirePage(r),a=this.pool.getSlotDataView(o);if(ut(a,0)>0){const l=vn(a,0,n,s);if(l.found){const u=ot(a,0,l.slot_idx),_=a.getUint16(u,!0),A=a.getBigInt64(u+2+_,!0);if(!i||!i.has(A))return!0}}r=Ut(a,0)}return!1}async deleteFromIndex(t,n,s,i){let r=t;for(;r!==0;){const o=await this.driver.acquirePage(r),a=this.pool.getSlotDataView(o);if(ut(a,0)>0){const l=vn(a,0,n,s,i);if(l.found)return so(a,0,l.slot_idx),this.pool.markDirty(o),!0}r=Ut(a,0)}return!1}async insertIntoIndex(t,n,s,i){let r=this.indexTailPages.get(t)??t,o=await this.driver.acquirePage(r),a=this.pool.getSlotDataView(o);for(;;){const l=Ut(a,0);if(l===0)break;r=l,o=await this.driver.acquirePage(r),a=this.pool.getSlotDataView(o)}this.indexTailPages.set(t,r);let c=Pi(a,0,n,s,i,this.pool.pageScratchpadOffset);if(c===-1){this.pool.pinSlot(o);try{const l=await this.driver.allocateAndPinPage(),u=this.pool.getResidentSlot(l);try{ds(a,0,l),this.pool.markDirty(o);const _=this.pool.getSlotDataView(u);if(ys(_,0,0),c=Pi(_,0,n,s,i,this.pool.pageScratchpadOffset),c===-1)throw new Error("Unexpected error: index entry does not fit in empty page");this.pool.markDirty(u),this.indexTailPages.set(t,l)}finally{this.pool.unpinSlot(u)}}finally{this.pool.unpinSlot(o)}}else this.pool.markDirty(o)}cloneRow(t){const n={};for(const[s,i]of Object.entries(t))n[s]=i instanceof Uint8Array?i.slice():i;return n}valuesEqual(t,n){if(t===n||t==null&&n==null)return!0;if(t instanceof Uint8Array&&n instanceof Uint8Array){if(t.byteLength!==n.byteLength)return!1;for(let s=0;s<t.byteLength;s++)if(t[s]!==n[s])return!1;return!0}return typeof t=="number"&&typeof n=="bigint"||typeof t=="bigint"&&typeof n=="number"?BigInt(t)===BigInt(n):typeof t=="boolean"&&typeof n=="number"||typeof t=="number"&&typeof n=="boolean"?Number(t)===Number(n):!1}extractPrimaryKey(t,n){const s=t.columns.filter(i=>(i.flags&tt.PRIMARY_KEY)!==0);return s.length===1?n[s[0].name]??null:s.length>1?s.map(i=>n[i.name]??null):t.columns.length===1?n[t.columns[0].name]??null:t.columns.map(i=>n[i.name]??null)}serializePkKey(t){const n=s=>s==null?"null":s instanceof Uint8Array?`b:${Array.from(s).join(",")}`:`${typeof s}:${String(s)}`;return Array.isArray(t)?`[${t.map(n).join("|")}]`:t!==null&&typeof t=="object"&&!(t instanceof Uint8Array)?`{${Object.keys(t).sort().map(i=>`${i}:${n(t[i])}`).join("|")}}`:n(t)}buildChangeset(t,n,s,i){const{changeCounter:r,schemaVersion:o}=this.getSyncState(),a=Array.from(new Set(i.map(c=>c.table)));return{txId:t,origin:n,meta:s,changeCounter:r,schemaVersion:o,tables:a,changes:i,coalesced:()=>{const c=new Map;for(const l of i){const u=`${l.table.toLowerCase()}::${this.serializePkKey(l.pk)}`,_=c.get(u);if(!_){c.set(u,{table:l.table,op:l.op,pk:Array.isArray(l.pk)?[...l.pk]:l.pk,oldRow:l.oldRow?this.cloneRow(l.oldRow):void 0,newRow:l.newRow?this.cloneRow(l.newRow):void 0,changedColumns:l.changedColumns?[...l.changedColumns]:void 0});continue}if(_.op==="insert"&&l.op==="update")c.set(u,{table:l.table,op:"insert",pk:Array.isArray(l.pk)?[...l.pk]:l.pk,newRow:l.newRow?this.cloneRow(l.newRow):_.newRow});else if(_.op==="insert"&&l.op==="delete")c.delete(u);else if(_.op==="update"&&l.op==="update"){const A=_.oldRow,f=l.newRow?this.cloneRow(l.newRow):_.newRow,g=Object.keys(f).filter(d=>!this.valuesEqual(A[d],f[d]));c.set(u,{table:l.table,op:"update",pk:Array.isArray(l.pk)?[...l.pk]:l.pk,oldRow:A,newRow:f,changedColumns:g})}else if(_.op==="update"&&l.op==="delete")c.set(u,{table:l.table,op:"delete",pk:Array.isArray(_.pk)?[..._.pk]:_.pk,oldRow:_.oldRow});else if(_.op==="delete"&&l.op==="insert"){const A=_.oldRow,f=l.newRow?this.cloneRow(l.newRow):{},g=Object.keys(f).filter(d=>!this.valuesEqual(A[d],f[d]));c.set(u,{table:l.table,op:"update",pk:Array.isArray(l.pk)?[...l.pk]:l.pk,oldRow:A,newRow:f,changedColumns:g})}else c.set(u,{table:l.table,op:l.op,pk:Array.isArray(l.pk)?[...l.pk]:l.pk,oldRow:l.oldRow?this.cloneRow(l.oldRow):void 0,newRow:l.newRow?this.cloneRow(l.newRow):void 0,changedColumns:l.changedColumns?[...l.changedColumns]:void 0})}return Array.from(c.values())}}}notifySubscriptions(t){if(t.tables.length===0||this.subscriptions.size===0)return;const n=new Set(t.tables.map(s=>s.toLowerCase()));for(const s of this.subscriptions)if(s.tables==="*")s.callback(t);else for(const i of n)if(s.tables.has(i)){s.callback(t);break}}emitCommitAndSubscriptions(t){if(t.changes.length===0)return;for(const r of this.commitHooks)r(t);const n=t.tables,{changeCounter:s,schemaVersion:i}=t;if(this.notifySubscriptions({tables:n,origin:t.origin,meta:t.meta,changeCounter:s,schemaVersion:i,crossTab:!1,changeset:t}),this.broadcastChannel)try{this.broadcastChannel.postMessage({senderId:this.instanceId,tables:n,origin:t.origin,meta:t.meta,changeCounter:s,schemaVersion:i})}catch{}}onBeforeCommit(t){return this.beforeCommitHooks.add(t),()=>{this.beforeCommitHooks.delete(t)}}onCommit(t){return this.commitHooks.add(t),()=>{this.commitHooks.delete(t)}}subscribe(t,n){const s={tables:t==="*"?"*":new Set((Array.isArray(t)?t:[t]).map(i=>i.toLowerCase())),callback:n};return this.subscriptions.add(s),()=>{this.subscriptions.delete(s)}}getSyncState(){const t=this.pool.getSlotDataView(0),n=qn(t,!1);return{changeCounter:n.changeCounter,schemaVersion:n.schemaVersion}}validateFilterColumns(t,n){const s=new Set(t.columns.map(o=>o.name)),i=o=>{if(o){if(o.type==="col"&&o.name!=="*"){if(!s.has(o.name))throw new fe(o.name,t.name)}else if(o.type==="binary")i(o.left),i(o.right);else if(o.type==="fn"&&Array.isArray(o.args))for(const a of o.args)i(a)}},r=o=>{if(o.colName&&!s.has(o.colName))throw new fe(o.colName,t.name);if(o.expr&&i(o.expr),o.child&&r(o.child),o.children)for(const a of o.children)r(a)};for(const o of n)r(o)}matchesFilter(t,n,s){switch(s.type){case"and":return(s.children??[]).every(i=>this.matchesFilter(t,n,i));case"or":return(s.children??[]).some(i=>this.matchesFilter(t,n,i));case"not":return s.child?!this.matchesFilter(t,n,s.child):!0;case"null":{const i=s.expr?vt(s.expr,n,o=>{var a;return(a=this.getUdf(o))==null?void 0:a.def.call}):n[s.colName],r=i==null;return s.isNull?r:!r}case"in":{const i=s.expr?vt(s.expr,n,a=>{var c;return(c=this.getUdf(a))==null?void 0:c.def.call}):n[s.colName];if(i==null)return!1;const o=(s.values??[]).some(a=>this.valuesEqual(i,a));return s.notIn?!o:o}case"expr":{if(!s.expr)return!0;const i=vt(s.expr,n,r=>{var o;return(o=this.getUdf(r))==null?void 0:o.def.call});return!!i&&i!==0}case"cmp":{const i=s.expr?vt(s.expr,n,a=>{var c;return(c=this.getUdf(a))==null?void 0:c.def.call}):n[s.colName],r=s.value;if(i==null||r===null||r===void 0)return!1;switch(String(s.op??"=").trim().toLowerCase().replace(/\s+/g," ")){case"=":case"==":return this.valuesEqual(i,r);case"!=":case"<>":return!this.valuesEqual(i,r);case"<":return typeof i=="string"&&typeof r=="string"?i<r:Number(i)<Number(r);case"<=":return typeof i=="string"&&typeof r=="string"?i<=r:Number(i)<=Number(r);case">":return typeof i=="string"&&typeof r=="string"?i>r:Number(i)>Number(r);case">=":return typeof i=="string"&&typeof r=="string"?i>=r:Number(i)>=Number(r);case"like":return Xe(String(i),String(r));case"not like":return!Xe(String(i),String(r));case"contains":return String(i).includes(String(r));case"starts_with":return String(i).startsWith(String(r));case"ends_with":return String(i).endsWith(String(r));default:return this.valuesEqual(i,r)}}default:return!0}}matchesFilters(t,n,s){for(const i of s)if(!this.matchesFilter(t,n,i))return!1;return!0}async deleteCellsOnDataPageAndShiftIndexes(t,n,s,i,r){if(i.length===0)return;const o=new Set(i);if(n.length>0){for(const u of i){const _=r[u];if(!_)continue;const A=BigInt(s)<<16n|BigInt(u);for(const f of n){const{keyVal:g,keyType:d}=this.extractIndexKey(t.columns,f,_.row);g!=null&&await this.deleteFromIndex(f.rootPageId,d,g,A)}}let l=0;for(let u=0;u<r.length;u++)if(!o.has(u)){if(l!==u){const _=r[u].row,A=BigInt(s)<<16n|BigInt(u),f=BigInt(s)<<16n|BigInt(l);for(const g of n){const{keyVal:d,keyType:I}=this.extractIndexKey(t.columns,g,_);d!=null&&(await this.deleteFromIndex(g.rootPageId,I,d,A),await this.insertIntoIndex(g.rootPageId,I,d,f))}}l++}}const a=await this.driver.acquirePage(s),c=this.pool.getSlotDataView(a);for(let l=i.length-1;l>=0;l--)zr(c,0,i[l]);this.pool.markDirty(a)}normalizeWhereOrPkFilters(t,n){if(n!==null&&typeof n=="object"&&!(n instanceof Uint8Array)){const i=[];for(const[r,o]of Object.entries(n))o!==void 0&&(o===null?i.push({type:"null",colName:r,isNull:!0}):i.push({type:"cmp",colName:r,op:"=",value:o}));return i}const s=t.columns.find(i=>(i.flags&tt.PRIMARY_KEY)!==0);if(!s)throw new Error(`Table "${t.name}" does not have a primary key column for scalar lookup`);return[{type:"cmp",colName:s.name,op:"=",value:n}]}async insert(t,n,s){await this.insertMany(t,[n],s)}async insertMany(t,n,s){if(!(!n||n.length===0)){if(!this.coordinator.isInTransaction()&&this.beforeCommitHooks.size>0){await this.transaction(async i=>{await i._insertManyInternal(t,n,!0)},s);return}return this.coordinator.leaseQueue.enqueue(async()=>{const i=this.coordinator.isInTransaction(),r=await this._insertManyInternal(t,n,!0);if(!i&&r.length>0){const o=this.buildChangeset(this.nextAutoTxId++,(s==null?void 0:s.origin)??"local",s==null?void 0:s.meta,r);this.emitCommitAndSubscriptions(o)}},this.currentLeaseId??void 0)}}async _insertManyInternal(t,n,s=!0){if(!n||n.length===0)return[];const i=await this._getTableInternal(t),r=this.pool.getSlotDataView(0),o=Ae(r,i.tableId),a=o.filter(p=>(p.flags&(It.UNIQUE|It.PRIMARY))!==0),c=i.columns.find(p=>(p.flags&tt.AUTO_INC)!==0),l=new Map;for(const p of a)l.set(p.name,new Set);let u=i.autoIncNext;const _=[];for(let p=0;p<n.length;p++){const y=n[p];for(const P of i.columns)if(P.flags&tt.PRIMARY_KEY&&!(P.flags&tt.AUTO_INC)&&(y[P.name]===void 0||y[P.name]===null))throw new ns(P.name,t);let T,N={};for(const P of i.columns)y[P.name]!==void 0?N[P.name]=y[P.name]:N[P.name]=null;c&&(y[c.name]===void 0||y[c.name]===null)&&(T=Number(u),u+=1n,N[c.name]=T);for(const P of a){const{keyVal:F,keyType:w}=this.extractIndexKey(i.columns,P,N);if(F!=null){const S=F instanceof Uint8Array?Array.from(F).join(","):F,v=l.get(P.name);if(v.has(S))throw new tn(`Duplicate key value violates unique constraint "${P.name}" on table "${t}"`);if(v.add(S),await this.probeIndexUnique(P.rootPageId,w,F))throw new tn(`Duplicate key value violates unique constraint "${P.name}" on table "${t}"`)}}const B=Is(i.columns,N);_.push({row:y,effectiveRow:N,rowBytes:B,assignedAutoInc:T})}i.autoIncNext=u;let A=this.tableTailPages.get(t)??i.rootPageId,f=await this.driver.acquirePage(A),g=this.pool.getSlotDataView(f);for(;;){const p=Ut(g,0);if(p===0)break;A=p,f=await this.driver.acquirePage(A),g=this.pool.getSlotDataView(f)}this.tableTailPages.set(t,A);const d=[];for(let p=0;p<_.length;p++){const{row:y,effectiveRow:T,rowBytes:N,assignedAutoInc:B}=_[p];c&&B!==void 0&&(y[c.name]=B),f=await this.driver.acquirePage(A),g=this.pool.getSlotDataView(f);let P=A,F=an(g,0,N,this.pool.pageScratchpadOffset);if(F===-1){const S=f;this.pool.pinSlot(S);try{const v=await this.driver.allocateAndPinPage(),L=this.pool.getResidentSlot(v);try{ds(g,0,v),this.pool.markDirty(S);const h=this.pool.getSlotDataView(L);if(F=an(h,0,N,this.pool.pageScratchpadOffset),F===-1)throw new Error("Unexpected error: row does not fit in empty page");this.pool.markDirty(L),A=v,P=v,f=L,g=h,this.tableTailPages.set(t,v)}finally{this.pool.unpinSlot(L)}}finally{this.pool.unpinSlot(S)}}else this.pool.markDirty(f);const w=BigInt(P)<<16n|BigInt(F);for(const S of o){const{keyVal:v,keyType:L}=this.extractIndexKey(i.columns,S,T);v!=null&&await this.insertIntoIndex(S.rootPageId,L,v,w)}if(s){const S={table:i.name,op:"insert",pk:this.extractPrimaryKey(i,T),newRow:this.cloneRow(T)};d.push(S),this.coordinator.isInTransaction()&&this.activeTxChanges.push(S)}}const I=xt(r,t);if(I!==-1){const p=Jt(r,I);p.rowCountEstimate+=n.length,c&&(p.autoIncNext=i.autoIncNext),An(r,I,p),re(r),$t(r),this.pool.markDirty(0)}return this.coordinator.isInTransaction()||await this.driver.flushAllDirty(),d}async update(t,n,s,i){return!this.coordinator.isInTransaction()&&this.beforeCommitHooks.size>0?this.transaction(r=>r.update(t,n,s,i),i):this.coordinator.leaseQueue.enqueue(async()=>{const r=await this._getTableInternal(t),o=this.normalizeWhereOrPkFilters(r,n),a=this.coordinator.isInTransaction(),{count:c,changes:l}=await this._executeUpdateInternal(t,o,s);if(!a&&l.length>0){const u=this.buildChangeset(this.nextAutoTxId++,(i==null?void 0:i.origin)??"local",i==null?void 0:i.meta,l);this.emitCommitAndSubscriptions(u)}return c},this.currentLeaseId??void 0)}async executeUpdate(t,n,s,i){return!this.coordinator.isInTransaction()&&this.beforeCommitHooks.size>0?this.transaction(r=>r.executeUpdate(t,n,s,i),i):this.coordinator.leaseQueue.enqueue(async()=>{const r=this.coordinator.isInTransaction(),{count:o,changes:a}=await this._executeUpdateInternal(t,n,s);if(!r&&a.length>0){const c=this.buildChangeset(this.nextAutoTxId++,(i==null?void 0:i.origin)??"local",i==null?void 0:i.meta,a);this.emitCommitAndSubscriptions(c)}return o},this.currentLeaseId??void 0)}async _executeUpdateInternal(t,n,s){const i=await this._getTableInternal(t);this.validateFilterColumns(i,n);const r=new Map(i.columns.map(d=>[d.name,d]));for(const d of Object.keys(s))if(!r.has(d))throw new fe(d,t);const o=this.pool.getSlotDataView(0),a=Ae(o,i.tableId),c=a.filter(d=>(d.flags&(It.UNIQUE|It.PRIMARY))!==0),l=[],u=new Set;let _=0,A=i.rootPageId;for(;A!==0;){const d=await this.driver.acquirePage(A),I=this.pool.getSlotDataView(d),p=ut(I,0),y=Ut(I,0),T=[],N=[];for(let B=0;B<p;B++){const P=ot(I,0,B),F=xe(i.columns,I,P);if(T.push({cellIdx:B,row:F}),this.matchesFilters(i,F,n)){const w={...F};for(const[L,h]of Object.entries(s))h!==void 0&&(w[L]=h);for(const L of i.columns)if(L.flags&tt.PRIMARY_KEY&&(w[L.name]===null||w[L.name]===void 0))throw new ns(L.name,t);const S=i.columns.map(L=>L.name).filter(L=>!this.valuesEqual(F[L],w[L])),v=Is(i.columns,w);N.push({cellIdx:B,oldRow:F,newRow:w,changedColumns:S,newRowBytes:v}),u.add(BigInt(A)<<16n|BigInt(B)),_++}}N.length>0&&l.push({pageId:A,allCells:T,matches:N}),A=y}if(_===0)return{count:0,changes:[]};for(const d of c){const I=new Set;for(const p of l)for(const y of p.matches){const{keyVal:T,keyType:N}=this.extractIndexKey(i.columns,d,y.newRow);if(T!=null){const B=T instanceof Uint8Array?Array.from(T).join(","):T;if(I.has(B))throw new tn(`Duplicate key value violates unique constraint "${d.name}" on table "${t}"`);if(I.add(B),await this.probeIndexUnique(d.rootPageId,N,T,u))throw new tn(`Duplicate key value violates unique constraint "${d.name}" on table "${t}"`)}}}const f=[],g=[];for(const d of l){const I=[];for(const p of d.matches){const y=await this.driver.acquirePage(d.pageId),T=this.pool.getSlotDataView(y);if(Ui(T,0,p.cellIdx,p.newRowBytes,this.pool.pageScratchpadOffset)){this.pool.markDirty(y),d.allCells[p.cellIdx].row=p.newRow;const B=BigInt(d.pageId)<<16n|BigInt(p.cellIdx);for(const F of a){const w=this.extractIndexKey(i.columns,F,p.oldRow),S=this.extractIndexKey(i.columns,F,p.newRow);this.valuesEqual(w.keyVal,S.keyVal)||(w.keyVal!==void 0&&w.keyVal!==null&&await this.deleteFromIndex(F.rootPageId,w.keyType,w.keyVal,B),S.keyVal!==void 0&&S.keyVal!==null&&await this.insertIntoIndex(F.rootPageId,S.keyType,S.keyVal,B))}const P={table:i.name,op:"update",pk:this.extractPrimaryKey(i,p.newRow),oldRow:this.cloneRow(p.oldRow),newRow:this.cloneRow(p.newRow),changedColumns:p.changedColumns};f.push(P),this.coordinator.isInTransaction()&&this.activeTxChanges.push(P)}else I.push(p.cellIdx),g.push(p)}I.length>0&&await this.deleteCellsOnDataPageAndShiftIndexes(i,a,d.pageId,I,d.allCells)}if(g.length>0){let d=this.tableTailPages.get(t)??i.rootPageId,I=await this.driver.acquirePage(d),p=this.pool.getSlotDataView(I);for(;;){const y=Ut(p,0);if(y===0)break;d=y,I=await this.driver.acquirePage(d),p=this.pool.getSlotDataView(I)}this.tableTailPages.set(t,d);for(const y of g){I=await this.driver.acquirePage(d),p=this.pool.getSlotDataView(I);let T=d,N=an(p,0,y.newRowBytes,this.pool.pageScratchpadOffset);if(N===-1){const F=I;this.pool.pinSlot(F);try{const w=await this.driver.allocateAndPinPage(),S=this.pool.getResidentSlot(w);try{ds(p,0,w),this.pool.markDirty(F);const v=this.pool.getSlotDataView(S);N=an(v,0,y.newRowBytes,this.pool.pageScratchpadOffset),this.pool.markDirty(S),d=w,T=w,this.tableTailPages.set(t,w)}finally{this.pool.unpinSlot(S)}}finally{this.pool.unpinSlot(F)}}else this.pool.markDirty(I);const B=BigInt(T)<<16n|BigInt(N);for(const F of a){const{keyVal:w,keyType:S}=this.extractIndexKey(i.columns,F,y.newRow);w!=null&&await this.insertIntoIndex(F.rootPageId,S,w,B)}const P={table:i.name,op:"update",pk:this.extractPrimaryKey(i,y.newRow),oldRow:this.cloneRow(y.oldRow),newRow:this.cloneRow(y.newRow),changedColumns:y.changedColumns};f.push(P),this.coordinator.isInTransaction()&&this.activeTxChanges.push(P)}}return re(o),$t(o),this.pool.markDirty(0),this.coordinator.isInTransaction()||await this.driver.flushAllDirty(),{count:_,changes:f}}async delete(t,n,s){return!this.coordinator.isInTransaction()&&this.beforeCommitHooks.size>0?this.transaction(i=>i.delete(t,n,s),s):this.coordinator.leaseQueue.enqueue(async()=>{const i=await this._getTableInternal(t),r=this.normalizeWhereOrPkFilters(i,n),o=this.coordinator.isInTransaction(),{count:a,changes:c}=await this._executeDeleteInternal(t,r);if(!o&&c.length>0){const l=this.buildChangeset(this.nextAutoTxId++,(s==null?void 0:s.origin)??"local",s==null?void 0:s.meta,c);this.emitCommitAndSubscriptions(l)}return a},this.currentLeaseId??void 0)}async executeDelete(t,n,s){return!this.coordinator.isInTransaction()&&this.beforeCommitHooks.size>0?this.transaction(i=>i.executeDelete(t,n,s),s):this.coordinator.leaseQueue.enqueue(async()=>{const i=this.coordinator.isInTransaction(),{count:r,changes:o}=await this._executeDeleteInternal(t,n);if(!i&&o.length>0){const a=this.buildChangeset(this.nextAutoTxId++,(s==null?void 0:s.origin)??"local",s==null?void 0:s.meta,o);this.emitCommitAndSubscriptions(a)}return r},this.currentLeaseId??void 0)}async _executeDeleteInternal(t,n){const s=await this._getTableInternal(t);this.validateFilterColumns(s,n);const i=this.pool.getSlotDataView(0),r=Ae(i,s.tableId),o=[];let a=0,c=s.rootPageId;for(;c!==0;){const u=await this.driver.acquirePage(c),_=this.pool.getSlotDataView(u),A=ut(_,0),f=Ut(_,0);if(A>0){const g=[],d=[];for(let I=0;I<A;I++){const p=ot(_,0,I),y=xe(s.columns,_,p);if(g.push({cellIdx:I,row:y}),this.matchesFilters(s,y,n)){d.push(I);const T={table:s.name,op:"delete",pk:this.extractPrimaryKey(s,y),oldRow:this.cloneRow(y)};o.push(T),this.coordinator.isInTransaction()&&this.activeTxChanges.push(T)}}d.length>0&&(a+=d.length,await this.deleteCellsOnDataPageAndShiftIndexes(s,r,c,d,g))}c=f}if(a===0)return{count:0,changes:[]};const l=xt(i,t);if(l!==-1){const u=Jt(i,l);u.rowCountEstimate=Math.max(0,u.rowCountEstimate-a),An(i,l,u)}return re(i),$t(i),this.pool.markDirty(0),this.coordinator.isInTransaction()||await this.driver.flushAllDirty(),{count:a,changes:o}}async upsert(t,n,s){const i=await this.upsertMany(t,[n],s);return i.inserted>0?"inserted":i.updated>0?"updated":"ignored"}async upsertMany(t,n,s){return!n||n.length===0?{inserted:0,updated:0,ignored:0}:!this.coordinator.isInTransaction()&&(this.beforeCommitHooks.size>0||n.length>1)?this.transaction(i=>i._upsertManyInLease(t,n,s),s):this.coordinator.leaseQueue.enqueue(async()=>{const i=this.coordinator.isInTransaction(),r=[],o=await this._upsertManyInLease(t,n,s,i?void 0:r);if(!i&&r.length>0){const a=this.buildChangeset(this.nextAutoTxId++,(s==null?void 0:s.origin)??"local",s==null?void 0:s.meta,r);this.emitCommitAndSubscriptions(a)}return o},this.currentLeaseId??void 0)}async _upsertManyInLease(t,n,s,i){const r=await this._getTableInternal(t),o=new Set(r.columns.map(A=>A.name));let a;if(s!=null&&s.conflictTarget){a=Array.isArray(s.conflictTarget)?s.conflictTarget:[s.conflictTarget];for(const A of a)if(!o.has(A))throw new fe(A,t)}else if(a=r.columns.filter(A=>(A.flags&tt.PRIMARY_KEY)!==0).map(A=>A.name),a.length===0)throw new Error(`Cannot upsert on table "${t}" without a primary key or explicit conflictTarget`);const c=(s==null?void 0:s.mode)??"merge";let l=0,u=0,_=0;for(const A of n){for(const I of Object.keys(A))if(!o.has(I))throw new fe(I,t);const f=a.every(I=>A[I]!==void 0&&A[I]!==null);let g=null,d=[];if(f&&(d=a.map(I=>({type:"cmp",colName:I,op:"=",value:A[I]})),g=await this.findFirstMatchingRow(r,d)),g){if(c==="ignore"){_++;continue}if(s!=null&&s.where&&!s.where(this.cloneRow(g),this.cloneRow(A))){_++;continue}const I={};if(c==="replace")for(const y of r.columns)A[y.name]!==void 0?I[y.name]=A[y.name]:y.flags&tt.PRIMARY_KEY?I[y.name]=g[y.name]:I[y.name]=null;else for(const[y,T]of Object.entries(A))T!==void 0&&(I[y]=T);const{changes:p}=await this._executeUpdateInternal(t,d,I);i&&i.push(...p),u++}else{const I=await this._insertManyInternal(t,[A],!0);i&&i.push(...I),l++}}return{inserted:l,updated:u,ignored:_}}async findFirstMatchingRow(t,n){let s=t.rootPageId;for(;s!==0;){const i=await this.driver.acquirePage(s),r=this.pool.getSlotDataView(i),o=ut(r,0),a=Ut(r,0);for(let c=0;c<o;c++){const l=ot(r,0,c),u=xe(t.columns,r,l);if(this.matchesFilters(t,u,n))return u}s=a}return null}async transaction(t,n){const s=await this.coordinator.begin(),i=s.leaseId;this.activeTxChanges=[],this.activeTxOrigin=(n==null?void 0:n.origin)??"local",this.activeTxMeta=n==null?void 0:n.meta,this.activeTxId=s.txId;const r=new Proxy(this,{get:(o,a,c)=>{if(a==="currentLeaseId")return i;if(a==="transaction")return async(u,_)=>{const A=await this.coordinator.captureSavepoint(),f=this.activeTxChanges.length;try{return await u(r)}catch(g){throw this.activeTxChanges.length=f,this.tableMetaCache.clear(),this.tableTailPages.clear(),this.indexTailPages.clear(),await this.coordinator.restoreSavepoint(A),g}};if(a==="checkpoint")return()=>this.checkpoint();if(a==="from")return u=>{const _=new Lt(r,u);return o.planner&&_.withPlanner(o.planner),_};const l=Reflect.get(o,a,c);return typeof l=="function"?l.bind(r):l}});try{const o=await t(r);if(this.activeTxChanges.length>0&&this.beforeCommitHooks.size>0&&!this.isRunningBeforeCommit){const _=this.buildChangeset(this.activeTxId,this.activeTxOrigin,this.activeTxMeta,[...this.activeTxChanges]);this.isRunningBeforeCommit=!0;try{for(const A of this.beforeCommitHooks)await A(_,r)}finally{this.isRunningBeforeCommit=!1}}const a=[...this.activeTxChanges],c=this.activeTxOrigin,l=this.activeTxMeta,u=this.activeTxId;if(this.activeTxChanges=[],this.activeTxOrigin="local",this.activeTxMeta=void 0,await this.coordinator.commit(i),a.length>0){const _=this.buildChangeset(u,c,l,a);this.emitCommitAndSubscriptions(_)}return o}catch(o){throw this.activeTxChanges=[],this.activeTxOrigin="local",this.activeTxMeta=void 0,this.isRunningBeforeCommit=!1,this.tableMetaCache.clear(),this.tableTailPages.clear(),this.indexTailPages.clear(),await this.coordinator.rollback(i),o}}registerFunction(t,n){const s=t.toLowerCase(),i=typeof n=="function"?{call:n}:{...n};if(!i.returnType)try{const o=i.call(1,1,1,1,1);typeof o=="number"?i.returnType=Number.isInteger(o)?C.INT32:C.FLOAT64:typeof o=="string"&&(i.returnType=C.TEXT)}catch{try{const o=i.call("","","","","");typeof o=="number"?i.returnType=Number.isInteger(o)?C.INT32:C.FLOAT64:typeof o=="string"&&(i.returnType=C.TEXT)}catch{}}let r=this.udfs.get(s);return r?r.def=i:(r={id:this.nextUdfId++,def:i},this.udfs.set(s,r)),this}getUdf(t){return this.udfs.get(t.toLowerCase())}getUdfMap(){const t=new Map;for(const[n,s]of this.udfs.entries())t.set(n,s.id);return t}getUdfDefs(){const t=new Map;for(const[n,s]of this.udfs.entries())t.set(n,s.def);return t}from(t){return new Lt(this,t)}async explainQuery(t,n,s){return this.coordinator.leaseQueue.enqueue(()=>this._explainQueryInternal(t,n,s),this.currentLeaseId??void 0)}async _explainQueryInternal(t,n,s){var I,p,y;const i=await this._getTableInternal(t),r=[];if(s!=null&&s.joins&&s.joins.length>0){if(1+s.joins.length>16)throw new rs(1+s.joins.length,16);for(let T=0;T<s.joins.length;T++){const N=s.joins[T],B=await this._getTableInternal(N.table);r.push({type:N.type,table:B,cursor:T+1,leftCol:N.leftCol,op:N.op,rightCol:N.rightCol})}}const o=er({table:i,joinedTables:r.length>0?r:void 0,filters:n,orderBy:s==null?void 0:s.orderBy,groupBy:s==null?void 0:s.groupBy,aggregates:s==null?void 0:s.aggregates,having:s==null?void 0:s.having,selectExprs:s==null?void 0:s.selectExprs,udfNameMap:this.getUdfMap(),udfDefs:this.getUdfDefs(),limit:s==null?void 0:s.limit,offset:s==null?void 0:s.offset,planner:(s==null?void 0:s.planner)??this.planner}),c=(o.allTables??(r.length>0?[i,...r.map(T=>T.table)]:[i]))[0],l=Ko(o,c),u=Jo(l),_=o.indexScan??o.table0Scan,A=_?"IndexScan":"TableScan",f=_?_.index.name:void 0,g=o.joinedTableScans,d=(I=s==null?void 0:s.joins)==null?void 0:I.map(T=>{const N=g==null?void 0:g.find(B=>B.tableName.toLowerCase()===T.table.toLowerCase());return N&&N.scanType==="IndexScan"?{...T,scanType:N.scanType,indexName:N.indexName}:T});return{plan:{table:c.name,rootPageId:c.rootPageId,scanType:A,indexName:f,filters:n,orderBy:s==null?void 0:s.orderBy,groupBy:s==null?void 0:s.groupBy,aggregates:s==null?void 0:s.aggregates,having:s==null?void 0:s.having,select:s==null?void 0:s.select,joins:d,limit:s==null?void 0:s.limit,offset:s==null?void 0:s.offset,estimatedCost:o.estimatedCost,estimatedRows:o.estimatedRows,joinOrder:o.joinOrder,isOrderSatisfied:o.isOrderSatisfied??((p=o.planMetrics)==null?void 0:p.isOrderSatisfied)??!1,sortCostAvoided:((y=o.planMetrics)==null?void 0:y.sortCostAvoided)??void 0},bytecodeSize:o.byteLength,instructions:l,assembly:u}}async executeQuery(t,n,s){return this.coordinator.leaseQueue.enqueue(()=>this._executeQueryInternal(t,n,s),this.currentLeaseId??void 0)}async _executeQueryInternal(t,n,s){var d;const i=await this._getTableInternal(t),r=[],o=[];if(s.joins&&s.joins.length>0){if(1+s.joins.length>16)throw new rs(1+s.joins.length,16);for(let I=0;I<s.joins.length;I++){const p=s.joins[I],y=await this._getTableInternal(p.table);r.push(y),o.push({type:p.type,table:y,cursor:I+1,leftCol:p.leftCol,op:p.op,rightCol:p.rightCol})}}for(const I of[i,...r]){let p=I.rootPageId;for(;p!==0;){const y=await this.driver.acquirePage(p),T=this.pool.getSlotDataView(y);p=Ut(T,0)}for(const y of I.indexes??[]){let T=y.rootPageId;for(;T!==0;){const N=await this.driver.acquirePage(T),B=this.pool.getSlotDataView(N);T=Ut(B,0)}}}let a=s.orderBy;!a&&s.sortCol&&(a=[{colName:s.sortCol,direction:s.sortDir}]);const c={table:i,joinedTables:o.length>0?o:void 0,filters:n,orderBy:a,groupBy:s.groupBy,aggregates:s.aggregates,having:s.having,selectExprs:s.selectExprs,udfNameMap:this.getUdfMap(),udfDefs:this.getUdfDefs(),limit:s.limit!==null?s.limit:void 0,offset:s.offset!==null?s.offset:void 0,planner:s.planner??this.planner},l=er(c),u=l.allTables??[i,...r];br(this.vmCtx,u[0],u),l.inSets&&(this.vmCtx.inSets=l.inSets);const _=l.keyInfos??c.keyInfos;_&&(this.vmCtx.keyInfos=_);const A={};for(const I of this.udfs.values())A[I.id]=I.def.call;this.vmCtx.udfs=A;let f=l.outputColumns??c.outputColumns??i.columns;if(c.aggregates&&c.aggregates.length>0||c.groupBy&&c.groupBy.length>0)if(l.outputColumns)f=l.outputColumns;else{f=[];const I=c.groupBy??[];for(const p of I){const y=typeof p=="string"?p:p.colName??(p.expr?Qt(p.expr):"group_key"),T=i.columns.find(N=>N.name===y);T?f.push(T):f.push({name:y,type:C.TEXT,flags:tt.NONE,colOffset:0})}for(let p=0;p<(((d=c.aggregates)==null?void 0:d.length)??0);p++){const y=c.aggregates[p],T=y.alias??(y.colName?`${y.func}_${y.colName}`:y.func),N=y.func==="count"?C.INT32:C.FLOAT64;f.push({name:T,type:N,flags:tt.NONE,colOffset:0})}}this.vmCtx.outputColumns=f;const g=[];for(;;){const I=Gn(this.vmCtx,this.pool.view,l);let p=0;for(let y=0;y<this.vmCtx.resultCount;y++){const T=this.pool.view.getUint16(On+p,!0),N=On+p+2,B=xe(f,this.pool.view,N);g.push(B),p+=2+T}if(I===O.DONE)break;if(I===O.BUFFER_FULL)this.vmCtx.resultOffset=0,this.vmCtx.resultCount=0,this.vmCtx.status=O.RUNNING;else if(I===O.PAGE_FAULT){this.vmCtx.resultOffset=0,this.vmCtx.resultCount=0;const y=[],T=this.vmCtx.cursors??[this.vmCtx.cursor];for(const N of T)if(N&&N.pageId>1){const B=this.pool.getResidentSlot(N.pageId);B>0&&(this.pool.pinSlot(B),y.push(B))}try{await this.driver.acquirePage(this.vmCtx.fault_page_id)}finally{for(const N of y)this.pool.unpinSlot(N)}this.vmCtx.status=O.RUNNING}else throw I===O.ARENA_EXHAUSTED?(this.vmCtx.arenaOffset=0,new _i):I===O.TIMEOUT?new vr:I===O.INVALID_BYTECODE?new kr:new Error(`VM execution error: status=${I}`)}return Object.defineProperty(g,"isOrderSatisfied",{value:l.isOrderSatisfied??!1,writable:!0,enumerable:!1,configurable:!0}),g}async checkpoint(){return this.coordinator.checkpoint()}async exportBinary(){return this.coordinator.leaseQueue.enqueue(async()=>{this.coordinator.isInTransaction()||(await this.coordinator.executeCheckpoint(),await this.driver.flushAllDirty());const t=this.pool.getSlotDataView(0),n=To(t),s=new Uint8Array(n*4096);s.set(this.pool.getPageBytesInSlot(0),0);const i=new DataView(s.buffer,s.byteOffset,4096);$t(i,0);const r=[];for(let c=2;c<=n;c++)this.pool.getResidentSlot(c)===-1&&!this.coordinator.hasSpilledPage(c)&&r.push(c);const o=r.length>0?await this.vfs.readPages(r):[],a=new Map;for(let c=0;c<r.length;c++)a.set(r[c],o[c]??null);for(let c=2;c<=n;c++){const l=(c-1)*4096,u=s.subarray(l,l+4096),_=this.pool.getResidentSlot(c);if(_!==-1)u.set(this.pool.getPageBytesInSlot(_));else if(this.coordinator.hasSpilledPage(c))u.set(this.coordinator.getSpilledPage(c));else{const f=a.get(c);f&&u.set(f)}const A=Ge(u);new DataView(u.buffer,u.byteOffset,4096).setUint32(12,A,!0)}return s},this.currentLeaseId??void 0)}async importBinary(t){if(this.coordinator.isInTransaction())throw new Error("Cannot import binary database while a transaction is active");return this.coordinator.leaseQueue.enqueue(async()=>{var l,u;const n=t instanceof Uint8Array?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):new Uint8Array(t);if(n.byteLength<4096||n.byteLength%4096!==0)throw new Rn(`Invalid database binary size (${n.byteLength} bytes): must be a non-zero multiple of 4096 bytes`);const s=n.byteLength/4096,i=n.subarray(0,4096),r=new DataView(i.buffer,i.byteOffset,4096),o=qn(r,!0);if(o.pageSize!==4096)throw new Rn(`Invalid database page size ${o.pageSize} (expected 4096)`);if(o.totalPages!==s)throw new Rn(`Database page count mismatch: header specifies ${o.totalPages} pages, but binary image contains ${s} pages`);for(let _=2;_<=s;_++){const A=(_-1)*4096,f=n.subarray(A,A+4096),d=new DataView(f.buffer,f.byteOffset,4096).getUint32(12,!0);if(d!==0){const I=Ge(f);if(I!==d)throw new Se(_,d,I)}}const a=[];for(let _=1;_<=s;_++){const A=(_-1)*4096;a.push({pageId:_,data:n.subarray(A,A+4096).slice()})}for(let _=1;_<this.pool.slotCount;_++)this.pool.forceUnpinSlot(_),this.pool.unassignSlot(_),this.pool.clearDirty(_),this.pool.getPageBytesInSlot(_).fill(0);this.pool.getPageBytesInSlot(0).set(a[0].data),this.pool.clearDirty(0),await this.vfs.writePages(a),await((u=(l=this.vfs).flush)==null?void 0:u.call(l)),await this.coordinator.resetWalAfterImport(),this.tableMetaCache.clear(),this.tableTailPages.clear(),this.indexTailPages.clear(),this.vmCtx.table=null;const c=hn(this.pool.getSlotDataView(0));for(const _ of c){let A=_.colCatalogPageId;for(;A!==0;){const f=await this.driver.acquireAndPinPage(A),g=this.pool.getSlotDataView(f);A=he(g,0).nextColCatalogPageId}}})}async close(){var t,n;this.broadcastChannel&&(this.broadcastChannel.close(),this.broadcastChannel=null),this.beforeCommitHooks.clear(),this.commitHooks.clear(),this.subscriptions.clear(),await this.coordinator.close(),await this.driver.flushAllDirty(),await((n=(t=this.vfs).close)==null?void 0:n.call(t))}}E.ALIGNMENT_PADDING_OFFSET=rl,E.ALIGNMENT_PADDING_SIZE=dr,E.AggregateNotAllowedInWhereError=os,E.BUILTIN_AGGREGATES=vo,E.BUILTIN_SCALARS=ko,E.BYTECODE_OFFSET=Ir,E.BYTECODE_SIZE=gr,E.BufferPoolDriver=Fo,E.BytecodeEmitter=Qs,E.CATALOG_PAGE_HEADER_FIELDS=Wa,E.CATALOG_PAGE_HEADER_OFFSET_COL_COUNT_IN_PAGE=$a,E.CATALOG_PAGE_HEADER_OFFSET_FLAGS=Va,E.CATALOG_PAGE_HEADER_OFFSET_NEXT_COL_CATALOG_PAGE_ID=Ya,E.CATALOG_PAGE_HEADER_OFFSET_PAGE_CHECKSUM=Za,E.CATALOG_PAGE_HEADER_OFFSET_PAGE_TYPE=Ha,E.CATALOG_PAGE_HEADER_OFFSET_START_COL_INDEX=Xa,E.CATALOG_PAGE_HEADER_OFFSET_TABLE_ID=xa,E.CATALOG_PAGE_HEADER_SIZE=xs,E.COLUMN_META_FIELDS=ja,E.COLUMN_META_OFFSET_COL_OFFSET=za,E.COLUMN_META_OFFSET_FLAGS=Ja,E.COLUMN_META_OFFSET_NAME=tl,E.COLUMN_META_OFFSET_RESERVED=el,E.COLUMN_META_OFFSET_TYPE=Ka,E.COLUMN_META_SIZE=Xs,E.COST_INDEX_NEXT=Ls,E.COST_INDEX_SEEK=_n,E.COST_ROW_EVAL=_e,E.CURRENT_ENGINE_VERSION=zn,E.CURRENT_MIN_READ_VERSION=Sr,E.CannotDropColumnError=Ai,E.ColumnAlreadyExistsError=ss,E.ColumnFlag=tt,E.ColumnNotFoundError=fe,E.CorruptPageError=Se,E.CorruptWalFrameError=Fn,E.CorruptWalHeaderError=as,E.CostBasedPlanner=Ds,E.CostBasedQueryPlanner=fc,E.CustomOrderPlanner=lc,E.CustomPlanner=xo,E.CustomQueryPlanner=cc,E.DEFAULT_BUFFER_POOL_REGIONS=il,E.DEFAULT_CACHE_SIZE_BYTES=nl,E.DEFAULT_MAX_QUERY_MEMORY=ve,E.DEFAULT_PAGE_SLOTS=sl,E.DEFAULT_PAGE_TO_SLOT_BUCKETS=qt,E.DEFAULT_SLOT_COUNT=Qe,E.DIRTY_MASK_OFFSET=mr,E.DataType=C,E.DefaultQueryPlanner=uc,E.ExclusiveLeaseQueue=Do,E.ExpressionBuilder=it,E.FILE_HEADER_SIZE=ga,E.HEADER_OFFSET_CHANGE_COUNTER=pe,E.HEADER_OFFSET_FILE_FORMAT_VERSION=Vs,E.HEADER_OFFSET_FREE_PAGE_HEAD=le,E.HEADER_OFFSET_MAGIC=Ee,E.HEADER_OFFSET_MIN_READ_VERSION=$s,E.HEADER_OFFSET_NEXT_CATALOG_PAGE_ID=ur,E.HEADER_OFFSET_NEXT_INDEX_CATALOG_PAGE_ID=fr,E.HEADER_OFFSET_PAGE_CHECKSUM=ye,E.HEADER_OFFSET_PAGE_SIZE=Hs,E.HEADER_OFFSET_RESERVED=_a,E.HEADER_OFFSET_SCHEMA_VERSION=Ie,E.HEADER_OFFSET_TOTAL_PAGES=se,E.HeuristicPlanner=Vo,E.HeuristicQueryPlanner=Ac,E.INDEX_CATALOG_OFFSET=Un,E.INDEX_DESCRIPTOR_FIELDS=La,E.INDEX_DESCRIPTOR_OFFSET_COLUMN_COUNT=Qa,E.INDEX_DESCRIPTOR_OFFSET_COLUMN_INDICES=ka,E.INDEX_DESCRIPTOR_OFFSET_COL_DIRECTIONS=Ma,E.INDEX_DESCRIPTOR_OFFSET_FLAGS=va,E.INDEX_DESCRIPTOR_OFFSET_INDEX_ID=Ra,E.INDEX_DESCRIPTOR_OFFSET_NAME=Ga,E.INDEX_DESCRIPTOR_OFFSET_RESERVED=qa,E.INDEX_DESCRIPTOR_OFFSET_ROOT_PAGE_ID=Da,E.INDEX_DESCRIPTOR_OFFSET_TABLE_ID=Fa,E.INDEX_DESCRIPTOR_SIZE=De,E.IdentifierTooLongError=Lr,E.IndexAlreadyExistsError=hi,E.IndexFlag=It,E.IndexNotFoundError=Rr,E.IndexedDbVfsAdapter=Wr,E.InvalidBytecodeError=kr,E.InvalidDatabaseError=Rn,E.Io=Ii,E.MASTER_TABLE_OFFSET=Sn,E.MAX_COLUMNS_PER_CATALOG_PAGE=Te,E.MAX_COLUMNS_PER_TABLE=ue,E.MAX_CURSORS_PER_FRAME=Al,E.MAX_INDEXES_PAGE1=Je,E.MAX_INDEXES_SYSPAGE=ma,E.MAX_IN_LIST_SIZE=Dt,E.MAX_NAME_LENGTH=ne,E.MAX_REGISTERS_PER_FRAME=fl,E.MAX_ROW_SIZE=2048,E.MAX_SUBQUERY_DEPTH=hl,E.MAX_TABLES_PAGE1=ce,E.MAX_TABLES_SYSPAGE=da,E.MAX_TABLE_INTERIOR_CELLS=lr,E.MAX_TOPK_HEAP_LIMIT=Or,E.MemoryVfsAdapter=qr,E.NEXT_DESCRIPTOR_CATALOG_PAGE_OFFSET=Ea,E.NEXT_DESCRIPTOR_CATALOG_PAGE_SIZE=Ia,E.NoOpPlanner=$o,E.NoOpQueryPlanner=hc,E.NotNullConstraintError=ns,E.OpCode=m,E.OpfsVfsAdapter=Hr,E.PAGE_HEADER_OFFSET_CELL_COUNT=aa,E.PAGE_HEADER_OFFSET_CHECKSUM=Re,E.PAGE_HEADER_OFFSET_CONTENT_OFFSET=la,E.PAGE_HEADER_OFFSET_FLAGS=oa,E.PAGE_HEADER_OFFSET_FREE_BYTES=ca,E.PAGE_HEADER_OFFSET_NEXT_PAGE_ID=or,E.PAGE_HEADER_OFFSET_TYPE=rr,E.PAGE_HEADER_SIZE=Kt,E.PAGE_SCRATCHPAD_OFFSET=pr,E.PAGE_SCRATCHPAD_SIZE=_r,E.PAGE_SIZE=4096,E.PAGE_TO_SLOT_BUCKET_SIZE=Ce,E.PAGE_TO_SLOT_OFFSET=Mt,E.PAGE_TO_SLOT_SIZE=Ar,E.PAGE_TYPE_CATALOG_PAGE=Nn,E.PAGE_TYPE_FREE=Me,E.PAGE_TYPE_INDEX_INTERIOR=Ur,E.PAGE_TYPE_INDEX_LEAF=ts,E.PAGE_TYPE_LEAF_DATA=es,E.PAGE_TYPE_TABLE_INTERIOR=fi,E.QueryArenaExhaustedError=_i,E.QueryBuilder=Lt,E.QueryTimeoutError=vr,E.RESULT_BUFFER_OFFSET=On,E.RESULT_BUFFER_SIZE=Ys,E.RowSizeLimitExceededError=Br,E.SLOTTED_PAGE_HEADER_FIELDS=ra,E.SLOT_TO_PAGE_OFFSET=Yn,E.SYSPAGE_FILE_HEADER_FIELDS=ha,E.SYSPAGE_RESERVED_OFFSET=pa,E.SYSPAGE_RESERVED_SIZE=ya,E.SubqueryNestingTooDeepError=Qr,E.TABLE_DESCRIPTOR_FIELDS=Ta,E.TABLE_DESCRIPTOR_OFFSET_AUTO_INC_NEXT=ba,E.TABLE_DESCRIPTOR_OFFSET_COLUMN_COUNT=wa,E.TABLE_DESCRIPTOR_OFFSET_COL_CATALOG_PAGE_ID=Ua,E.TABLE_DESCRIPTOR_OFFSET_FLAGS=Pa,E.TABLE_DESCRIPTOR_OFFSET_NAME=Oa,E.TABLE_DESCRIPTOR_OFFSET_RESERVED=Ba,E.TABLE_DESCRIPTOR_OFFSET_ROOT_PAGE_ID=Sa,E.TABLE_DESCRIPTOR_OFFSET_ROW_COUNT_ESTIMATE=Na,E.TABLE_DESCRIPTOR_OFFSET_TABLE_ID=Ca,E.TABLE_DESCRIPTOR_SIZE=Fe,E.TABLE_INTERIOR_CELL_FIELDS=ua,E.TABLE_INTERIOR_CELL_OFFSET_CHILD_PAGE_ID=fa,E.TABLE_INTERIOR_CELL_OFFSET_ROWID=Aa,E.TABLE_INTERIOR_CELL_SIZE=ar,E.TABLE_INTERIOR_SPLIT_INDEX=cr,E.TOTAL_MEMORY_BYTES=ol,E.TRANSIENT_ARENA_OFFSET=yr,E.TableAlreadyExistsError=is,E.TableFlag=bn,E.TableNotFoundError=Bn,E.TooManyColumnsError=Ln,E.TooManyCursorsError=rs,E.TooManyGroupByColumnsError=Gr,E.TooManyIndexesError=Fr,E.TooManyOrderByColumnsError=Mr,E.TooManyRegistersError=st,E.TooManyTablesError=gi,E.TransactionCoordinator=Qo,E.UniqueConstraintViolationError=tn,E.UnknownFunctionError=di,E.UnsupportedFormatVersionError=Dr,E.VM_CONTEXT_OFFSET=Er,E.VM_CONTEXT_SIZE=hr,E.VM_FRAME_COUNT=ul,E.VM_FRAME_SIZE=cl,E.VmStatus=O,E.WAL_CURRENT_VERSION=Tr,E.WAL_FILE_HEADER_FIELDS=al,E.WAL_FILE_HEADER_SIZE=Jn,E.WAL_FRAME_HEADER_FIELDS=ll,E.WAL_FRAME_HEADER_SIZE=ke,E.WAL_FRAME_MAGIC=Pn,E.WAL_FRAME_OFFSET_CHECKSUM=ui,E.WAL_FRAME_OFFSET_DB_SIZE_PAGES=li,E.WAL_FRAME_OFFSET_FLAGS=ri,E.WAL_FRAME_OFFSET_FRAME_SEQ=ci,E.WAL_FRAME_OFFSET_FRAME_TYPE=ii,E.WAL_FRAME_OFFSET_MAGIC=si,E.WAL_FRAME_OFFSET_PAGE_ID=ai,E.WAL_FRAME_OFFSET_RESERVED=wr,E.WAL_FRAME_OFFSET_TX_ID=oi,E.WAL_FRAME_SIZE=ze,E.WAL_FRAME_TYPE_PAGE_DATA=Zn,E.WAL_FRAME_TYPE_TX_COMMIT=jn,E.WAL_FRAME_TYPE_TX_UNCOMMITTED=Kn,E.WAL_HEADER_OFFSET_CHECKPOINT_SEQ=zs,E.WAL_HEADER_OFFSET_CHECKSUM=ni,E.WAL_HEADER_OFFSET_MAGIC=js,E.WAL_HEADER_OFFSET_PAGE_SIZE=Js,E.WAL_HEADER_OFFSET_RESERVED=Cr,E.WAL_HEADER_OFFSET_SALT1=ti,E.WAL_HEADER_OFFSET_SALT2=ei,E.WAL_HEADER_OFFSET_WAL_VERSION=Ks,E.WAL_HEADER_SIZE=gl,E.WAL_MAGIC_BYTES=pi,E.WAL_PAGE_SIZE=we,E.WEBDB_CORE_WASM_BASE64=Wi,E.WebDB=sr,E.buf_pool_assign_slot=ao,E.buf_pool_clear_dirty=uo,E.buf_pool_find_victim=Fi,E.buf_pool_get_resident_slot=Wt,E.buf_pool_get_slot_offset=kl,E.buf_pool_is_dirty=Bi,E.buf_pool_is_pinned=cn,E.buf_pool_mark_dirty=co,E.buf_pool_pin_slot=Li,E.buf_pool_read_slot_to_page=ln,E.buf_pool_select_eviction_victim=Di,E.buf_pool_unassign_slot=lo,E.buf_pool_unpin_slot=Ri,E.buf_pool_write_slot_to_page=bi,E.buildJoinEdges=Rs,E.buildRootFilter=zt,E.c_assert=Yr,E.canJoinPreserveOrder=jo,E.catalog_create_table=bo,E.catalog_delete_index_descriptor=Mi,E.catalog_delete_table_descriptor=Uo,E.catalog_find_free_index_slot=Ns,E.catalog_find_free_table_slot=ki,E.catalog_find_index_by_name=bs,E.catalog_find_table_by_name=Zl,E.catalog_find_table_slot=xt,E.catalog_get_change_counter=wo,E.catalog_get_free_page_head=Xl,E.catalog_get_schema_version=Co,E.catalog_get_total_pages=To,E.catalog_increment_change_counter=re,E.catalog_increment_schema_version=Ze,E.catalog_init_page=Oo,E.catalog_init_page1=yo,E.catalog_list_table_descriptors=hn,E.catalog_list_table_indexes=Ae,E.catalog_load_all_tables=Kl,E.catalog_load_table_meta=qi,E.catalog_map_column_location=No,E.catalog_parse_data_type=So,E.catalog_read_column_meta=Po,E.catalog_read_fixed_string=Us,E.catalog_read_index_descriptor=gn,E.catalog_read_page1_header=qn,E.catalog_read_page_header=he,E.catalog_read_table_descriptor=Jt,E.catalog_set_free_page_head=Yl,E.catalog_set_total_pages=xl,E.catalog_update_page1_checksum=$t,E.catalog_write_column_meta=Gi,E.catalog_write_fixed_string=Ss,E.catalog_write_index_descriptor=Os,E.catalog_write_page_header=jl,E.catalog_write_table_descriptor=An,E.chooseIndexScan=ks,E.chooseJoinIndex=Ms,E.clear_bit=Xr,E.col=Vi,E.collectLeafFilters=Xo,E.compare_sorter_keys=fn,E.compileQuery=er,E.computeBufferPoolOffsets=Zs,E.computePage1Checksum=Ei,E.computePageChecksum=Ge,E.computeWalFrameChecksum=ls,E.crc32=mi,E.createVmContext=Nr,E.createVmCursor=Pr,E.createWasmCore=Lo,E.createWasmMemory=Ro,E.decodeWalFileHeader=hs,E.decodeWalFrame=Sl,E.decodeWalFrameHeader=yi,E.deriveDefaultAlias=Qt,E.disassembleBytecode=Ko,E.doesTableSatisfyJoinOrderKeys=xi,E.emitExpression=Z,E.encodeWalFileHeader=As,E.encodeWalFrame=gs,E.estimateFilterSelectivity=$i,E.estimateWhereCost=Xi,E.evalExprNode=vt,E.exp=Go,E.extractAggregatesFromExpr=nr,E.extractFilterColumnNames=Wo,E.findIndexOnColumn=Hn,E.fn=ic,E.fnv1a_32=ws,E.formatDisassembly=Jo,E.getCmpOpcode=$n,E.getFilterReferencedTables=dn,E.getMinKeyValueForType=vs,E.getSingleTableBaseCost=de,E.getTopLevelConjunctionFilters=mn,E.getWebDbCoreWasmBytes=Bo,E.get_bit=$r,E.inferExprType=Zo,E.inferTransitivePredicates=Ho,E.isAggregateFunction=ge,E.isBuiltinFunction=Jl,E.isBuiltinScalarFunction=Mo,E.isIndexAlignedWithOrderBy=tr,E.isQueryBuilder=x,E.materializeOutputSelectExprs=Vn,E.memcmp=_l,E.memcpy=nn,E.memset=ie,E.normalizeFilter=Oe,E.normalizeSelectItem=Gs,E.optimizeQueryPlan=_c,E.optimizeWherePredicates=Yi,E.page_binary_search_index_leaf=vn,E.page_binary_search_interior=Dl,E.page_compact=Qn,E.page_compare_index_keys=Ts,E.page_delete_index_leaf_cell=so,E.page_delete_row=zr,E.page_deserialize_row=xe,E.page_get_cell_content_offset=He,E.page_get_cell_count=ut,E.page_get_cell_offset=ot,E.page_get_checksum=Ll,E.page_get_contiguous_free_space=ms,E.page_get_free_bytes=Ue,E.page_get_next_page_id=Ut,E.page_get_right_child_page_id=ps,E.page_get_row_length=Es,E.page_get_table_layout=Fl,E.page_get_total_free_space=Jr,E.page_get_type=qe,E.page_init=Dn,E.page_init_free=Kr,E.page_init_index_leaf=ys,E.page_init_interior=to,E.page_insert_index_leaf_cell=Pi,E.page_insert_interior_cell=no,E.page_insert_row=an,E.page_serialize_row=Is,E.page_set_cell_content_offset=Ve,E.page_set_cell_count=We,E.page_set_cell_offset=on,E.page_set_checksum=Rl,E.page_set_free_bytes=$e,E.page_set_next_page_id=ds,E.page_set_right_child_page_id=eo,E.page_set_type=Bl,E.page_split_interior=Ql,E.page_table_delete=Ni,E.page_table_get=ro,E.page_table_hash=kn,E.page_table_set=oo,E.page_update_row=Ui,E.parseExpression=ft,E.parseFilterTarget=wt,E.parseSelectExpr=Bs,E.read_f64=Il,E.read_i32=ml,E.read_i64=Cl,E.read_u16=us,E.read_u32=yt,E.read_u64=yl,E.read_u8=Vr,E.reconstructJoinPlans=Fs,E.recoverFromWal=Hi,E.resetVmContext=br,E.resolveColumnAcrossTables=ht,E.resolveQueryPlanner=ji,E.serialize_composite_key=Cs,E.serialize_single_key=io,E.set_bit=xr,E.sql=nc,E.sql_like_match=Xe,E.strlen=cs,E.validateClause=je,E.validateWalFrame=Ti,E.vm_step=Gn,E.write_f64=pl,E.write_i32=El,E.write_i64=wl,E.write_u16=fs,E.write_u32=Tt,E.write_u64=Tl,E.write_u8=dl,Object.defineProperty(E,Symbol.toStringTag,{value:"Module"})});
5
5
  //# sourceMappingURL=webdb.umd.cjs.map