@ahmadmoussawi/webdb 0.1.0-alpha.0 → 0.1.1
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.
- package/dist/core/index.d.ts +1 -1
- package/dist/core/index.d.ts.map +1 -1
- package/dist/core/js/catalog.c.d.ts.map +1 -1
- package/dist/core/js/page.c.d.ts +4 -0
- package/dist/core/js/page.c.d.ts.map +1 -1
- package/dist/host/api/query_builder.d.ts +5 -1
- package/dist/host/api/query_builder.d.ts.map +1 -1
- package/dist/host/api/webdb.d.ts +74 -4
- package/dist/host/api/webdb.d.ts.map +1 -1
- package/dist/host/compiler/expr_parser.d.ts.map +1 -1
- package/dist/host/driver/transaction_coordinator.d.ts +5 -2
- package/dist/host/driver/transaction_coordinator.d.ts.map +1 -1
- package/dist/types/index.d.ts +70 -1
- package/dist/types/index.d.ts.map +1 -1
- package/dist/webdb.js +6143 -4852
- package/dist/webdb.js.map +1 -1
- package/dist/webdb.umd.cjs +2 -2
- package/dist/webdb.umd.cjs.map +1 -1
- package/package.json +1 -1
package/dist/webdb.umd.cjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
(function(h,vt){typeof exports=="object"&&typeof module<"u"?vt(exports):typeof define=="function"&&define.amd?define(["exports"],vt):(h=typeof globalThis<"u"?globalThis:h||self,vt(h.WebDB={}))})(this,function(h){"use strict";var dl=Object.defineProperty;var El=(h,vt,ln)=>vt in h?dl(h,vt,{enumerable:!0,configurable:!0,writable:!0,value:ln}):h[vt]=ln;var S=(h,vt,ln)=>El(h,typeof vt!="symbol"?vt+"":vt,ln);const Jo=[["TYPE",1],["FLAGS",1],["CELL_COUNT",2],["CONTENT_OFFSET",2],["NEXT_PAGE_ID",4],["FREE_BYTES",2],["CHECKSUM",4]],Jt=16,ji=0,Ko=1,zo=2,xo=4,Ji=6,ta=10,Ie=12,ea=[["CHILD_PAGE_ID",4],["ROWID",8]],Ki=12,na=0,sa=4,zi=291,xi=145,pe=64,ia=[["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]],ra=100,re=0,Ss=6,Ns=8,Bs=10,Kt=12,ee=16,oe=20,ae=24,ce=28,tr=32,er=36,oa=40,aa=16,ca=8,Te=16,un=8,An=100,fn=2148,la=3172,ua=4,Aa=3176,fa=920,ye=56,_n=256,_a=[["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]],Ue=128,ga=0,ha=2,da=4,Ea=8,ma=12,Ia=76,pa=80,Ta=84,ya=92,Ua=[["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]],Ce=128,Ca=0,Oa=2,Sa=4,Na=8,Ba=9,Pa=10,wa=26,La=34,Fa=98,Da=[["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]],Ps=16,Ra=0,Qa=1,ba=2,ka=4,Ga=6,va=8,Ma=12,Wa=[["TYPE",1],["FLAGS",1],["COL_OFFSET",2],["NAME",64],["RESERVED",4]],ws=72,Ha=0,Va=1,Xa=2,$a=4,Ya=68,Za=4194304,Oe=1024,qa=1024,Qt=2048,le=8,nr=16384,sr=12288,Ls=65536,ir=32768,rr=4096,or=61312,Se=16777216,ja=[["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]],bn=4194304,Dt=4198400,ar=4214784,cr=4214912,gn=4227200,lr=4292736,ur=4325504,Ja=4329600,Ar=4390912,Ka=21168128;function Fs(t,e=Se){const n=t*4096,s=t*4+7&-8;let i=16;for(;i<t*2;)i<<=1;const r=i*8,o=Math.ceil(t/8)+7&-8;if(t===Oe)return{slotsEndOffset:n,slotToPageOffset:bn,pageToSlotOffset:Dt,pageToSlotBuckets:Qt,dirtyMaskOffset:ar,vmContextOffset:cr,resultBufferOffset:gn,bytecodeOffset:lr,pageScratchpadOffset:ur,transientArenaOffset:Ar};const a=n,l=a+s,c=l+r,u=c+o,E=u+sr,f=E+Ls,_=f+ir,d=_+rr+or;return{slotsEndOffset:n,slotToPageOffset:a,pageToSlotOffset:l,pageToSlotBuckets:i,dirtyMaskOffset:c,vmContextOffset:u,resultBufferOffset:E,bytecodeOffset:f,pageScratchpadOffset:_,transientArenaOffset:d}}const ue=4096,Ge=4128,fr=1,hn=1463897158,kn=1,Gn=2,vn=3,za=[["MAGIC",6],["WAL_VERSION",2],["PAGE_SIZE",4],["CHECKPOINT_SEQ",4],["SALT1",4],["SALT2",4],["CHECKSUM",4],["RESERVED",4]],Mn=32,Ds=0,Rs=6,Qs=8,bs=12,ks=16,Gs=20,vs=24,_r=28,xa=[["MAGIC",4],["FRAME_TYPE",2],["FLAGS",2],["TX_ID",4],["PAGE_ID",4],["DB_SIZE_PAGES",4],["FRAME_SEQ",4],["CHECKSUM",4],["RESERVED",4]],Ne=32,Ms=0,Ws=4,Hs=6,Vs=8,Xs=12,$s=16,Ys=20,Zs=24,gr=28,Wn=1,hr=1,Be=0,dr=2,qs=5,js=10,dn=12,Hn=13,tc=1280,ec=8,nc=64,sc=16,ic=7,rc=32,Er=1e4,bt=1e4;function mr(){return{pageId:0,rootPageId:0,slotIdx:0,cellIdx:0,rowOffset:0,btreeDepth:0,flags:0}}function Ir(){const t=Array.from({length:16},()=>mr());return{pc:0,status:C.RUNNING,fault_page_id:0,resultCount:0,resultOffset:0,arenaOffset:0,maxQueryMemory:Se,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 pr(t,e,n){t.pc=0,t.status=C.RUNNING,t.fault_page_id=0,t.resultCount=0,t.resultOffset=0,t.arenaOffset=0,t.maxQueryMemory=Se,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 y=(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))(y||{}),Ct=(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))(Ct||{}),En=(t=>(t[t.NONE=0]="NONE",t[t.ACTIVE=1]="ACTIVE",t[t.SYSTEM=2]="SYSTEM",t))(En||{}),Ut=(t=>(t[t.NONE=0]="NONE",t[t.UNIQUE=1]="UNIQUE",t[t.PRIMARY=2]="PRIMARY",t[t.SPATIAL_VECTOR=4]="SPATIAL_VECTOR",t))(Ut||{}),g=(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))(g||{}),C=(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))(C||{});class Tr extends Error{constructor(e,n=2048){super(`Row size (${e} bytes) exceeds maximum limit of ${n} bytes`),this.name="RowSizeLimitExceededError"}}class Js extends Error{constructor(e,n){super(`NOT NULL constraint failed: ${n?n+".":""}${e}`),this.name="NotNullConstraintError"}}class yr extends Error{constructor(e,n){super(n?`Column "${e}" not found on table "${n}"`:`Column "${e}" not found`),this.name="ColumnNotFoundError"}}class Vn extends Error{constructor(e){super(`Table not found: "${e}"`),this.name="TableNotFoundError"}}class Ur extends Error{constructor(e){super(`Table already exists: "${e}"`),this.name="TableAlreadyExistsError"}}class Cr extends Error{constructor(e){super(`Index not found: "${e}"`),this.name="IndexNotFoundError"}}class Ks extends Error{constructor(e){super(`Index already exists: "${e}"`),this.name="IndexAlreadyExistsError"}}class Xn extends Error{constructor(e){super(e),this.name="UniqueConstraintViolationError"}}class Pe 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 zs extends Error{constructor(e,n=256){super(`Too many columns: ${e} exceeds maximum limit of ${n} columns`),this.name="TooManyColumnsError"}}class Or extends Error{constructor(e,n=16){super(`Too many tables: ${e} exceeds maximum limit of ${n} tables on Page 1`),this.name="TooManyTablesError"}}class Sr extends Error{constructor(e,n=8){super(`Too many indexes: ${e} exceeds maximum limit of ${n} indexes on Page 1`),this.name="TooManyIndexesError"}}class Nr extends Error{constructor(e){super(e),this.name="UnsupportedFormatVersionError"}}class Br extends Error{constructor(e){super(e),this.name="InvalidDatabaseError"}}class xs extends Error{constructor(e="Transient query arena exhausted"){super(e),this.name="QueryArenaExhaustedError"}}class $n extends Error{constructor(e,n=16){super(`Too many cursors: ${e} exceeds maximum limit of ${n} cursors`),this.name="TooManyCursorsError"}}class et extends Error{constructor(e,n=64){super(`Too many registers: ${e} exceeds maximum limit of ${n} registers`),this.name="TooManyRegistersError"}}class oc extends Error{constructor(e,n=7){super(`Subquery nesting depth ${e} exceeds maximum limit of ${n}`),this.name="SubqueryNestingTooDeepError"}}class Pr extends Error{constructor(e="Query execution exceeded maximum cycle limit (TIMEOUT)"){super(e),this.name="QueryTimeoutError"}}class wr extends Error{constructor(e="Malformed bytecode execution halted (INVALID_BYTECODE)"){super(e),this.name="InvalidBytecodeError"}}class Lr extends Error{constructor(e,n=8){super(`Too many order by columns: ${e} exceeds maximum limit of ${n}`),this.name="TooManyOrderByColumnsError"}}class Fr extends Error{constructor(e,n=8){super(`Too many group by columns: ${e} exceeds maximum limit of ${n}`),this.name="TooManyGroupByColumnsError"}}class ti extends Error{constructor(e){super(`Function "${e}" is neither a native built-in function nor a registered UDF`),this.name="UnknownFunctionError"}}class Yn extends Error{constructor(e){super(`Aggregate function "${e}" cannot be used in WHERE clause`),this.name="AggregateNotAllowedInWhereError"}}class Zn extends Error{constructor(e="Corrupted WAL file header detected"){super(e),this.name="CorruptWalHeaderError"}}class mn extends Error{constructor(e="Corrupted WAL frame detected"){super(e),this.name="CorruptWalFrameError"}}class Dr{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(r=>new Uint8Array(r))}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 Rr{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 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=()=>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,r)=>{const o=s.transaction("pages","readwrite"),a=o.objectStore("pages"),l=new Uint8Array(n.byteLength);l.set(n),a.put(l,e),o.oncomplete=()=>i(),o.onerror=()=>r(o.error),o.onabort=()=>r(o.error)})}async writePages(e){if(e.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:l}of e){const c=new Uint8Array(l.byteLength);c.set(l),o.put(c,a)}r.oncomplete=()=>s(),r.onerror=()=>i(r.error),r.onabort=()=>i(r.error)})}async flush(){}async truncate(e){const n=await this.getDb();return new Promise((s,i)=>{const o=n.transaction("pages","readwrite").objectStore("pages"),a=IDBKeyRange.lowerBound(e,!0),l=o.delete(a);l.onsuccess=()=>s(),l.onerror=()=>i(l.error)})}async readWalHeader(){const e=await this.getDb();return new Promise((n,s)=>{const o=e.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(e){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(e.byteLength);a.set(e),o.put(a,"header"),r.oncomplete=()=>s(),r.onerror=()=>i(r.error),r.onabort=()=>i(r.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,r)=>{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 E=u.result;if(E){const f=E.value;l.push(f instanceof Uint8Array?f:new Uint8Array(f)),E.continue()}else i(l)},u.onerror=()=>r(u.error)})}async appendWalFrames(e){if(e.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 l=a.result;for(const c of e){const u=new Uint8Array(c.byteLength);u.set(c),o.put(u,l++)}},r.oncomplete=()=>s(),r.onerror=()=>i(r.error),r.onabort=()=>i(r.error)})}async flushWal(){}async truncateWal(e){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(e===0)o.clear(),a.delete("header");else{const l=IDBKeyRange.lowerBound(e,!1);o.delete(l)}r.oncomplete=()=>s(),r.onerror=()=>i(r.error),r.onabort=()=>i(r.error)})}async getWalFrameCount(){const e=await this.getDb();return new Promise((n,s)=>{const o=e.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 Qr{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 o=this.dbSyncHandle.getSize();if(n+4096>o)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 r=await s.slice(n,n+4096).arrayBuffer();return new Uint8Array(r)}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 o=this.walSyncHandle.getSize();if(n>=o)return null;const a=Math.min(4128,o-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),r=s.slice(n,n+i);return new Uint8Array(await r.arrayBuffer())}async readWalFrames(e,n){const s=[];let i=e;const r=n!==void 0?e+n:1/0;for(;i<r;){const o=await this.readWalFrame(i);if(!o)break;s.push(o),i++}return s}async appendWalFrames(e){if(await this.initHandles(),this.walSyncHandle){let i=Math.max(32,this.walSyncHandle.getSize());for(const r of e)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 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 ve=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;ve[t]=e>>>0}function ei(t,e=0,n=t.byteLength-e){let s=4294967295;const i=e+n;for(let r=e;r<i;r++)s=ve[(s^t[r])&255]^s>>>8;return(s^4294967295)>>>0}function qn(t){let e=4294967295;for(let n=0;n<4096;n++){const s=n>=12&&n<=15?0:t[n];e=ve[(e^s)&255]^e>>>8}return(e^4294967295)>>>0}function ni(t){let e=4294967295;for(let n=0;n<4096;n++){const s=n>=28&&n<=31?0:t[n];e=ve[(e^s)&255]^e>>>8}return(e^4294967295)>>>0}function jn(t){let e=4294967295;for(let s=0;s<24;s++)e=ve[(e^t[s])&255]^e>>>8;const n=Math.min(t.byteLength,4128);for(let s=32;s<n;s++)e=ve[(e^t[s])&255]^e>>>8;return(e^4294967295)>>>0}function In(t,e,n,s,i){const r=t instanceof Uint8Array?t:new Uint8Array(t.buffer,t.byteOffset,t.byteLength),o=n instanceof Uint8Array?n:new Uint8Array(n.buffer,n.byteOffset,n.byteLength);r.set(o.subarray(s,s+i),e)}function zt(t,e,n,s){(t instanceof Uint8Array?t:new Uint8Array(t.buffer,t.byteOffset,t.byteLength)).fill(n&255,e,e+s)}function ac(t,e,n,s,i){const r=t instanceof Uint8Array?t:new Uint8Array(t.buffer,t.byteOffset,t.byteLength),o=n instanceof Uint8Array?n:new Uint8Array(n.buffer,n.byteOffset,n.byteLength);for(let a=0;a<i;a++){const l=r[e+a]-o[s+a];if(l!==0)return l}return 0}function Jn(t){return t.length}function br(t,e){return t instanceof Uint8Array?t[e]:t.getUint8(e)}function cc(t,e,n){t instanceof Uint8Array?t[e]=n&255:t.setUint8(e,n&255)}function Kn(t,e){return t.getUint16(e,!0)}function zn(t,e,n){t.setUint16(e,n&65535,!0)}function mt(t,e){return t.getUint32(e,!0)}function It(t,e,n){t.setUint32(e,n>>>0,!0)}function lc(t,e){return t.getInt32(e,!0)}function uc(t,e,n){t.setInt32(e,n|0,!0)}function Ac(t,e){return t.getFloat64(e,!0)}function fc(t,e,n){t.setFloat64(e,n,!0)}function _c(t,e){return t.getBigUint64(e,!0)}function gc(t,e,n){t.setBigUint64(e,n,!0)}function hc(t,e){return t.getBigInt64(e,!0)}function dc(t,e,n){t.setBigInt64(e,n,!0)}function kr(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 Gr(t,e,n){n!==void 0?t[e+(n>>3)]|=1<<(n&7):t[e>>3]|=1<<(e&7)}function vr(t,e,n){n!==void 0?t[e+(n>>3)]&=~(1<<(n&7)):t[e>>3]&=~(1<<(e&7))}function Mr(t,e){if(!t)throw new Error(`Assertion failed: ${e}`)}class si{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 r=ni(i);It(this.view,s+ce,r)}else{const r=qn(i);It(this.view,s+Ie,r)}}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 o=e*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.readPage(n),a=e*4096;if(o){if(o.byteLength!==4096)throw new Pe(n,`Unexpected page byte length: ${o.byteLength}, expected 4096`);const l=n===1?ce:Ie,c=mt(new DataView(o.buffer,o.byteOffset),l);if(c!==0){const u=n===1?ni(o):qn(o);if(u!==c)throw new Pe(n,c,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(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,r=this.uint8.subarray(i,i+4096);this.stampSlotChecksum(e,n);const o=r.slice();this.coordinator&&this.coordinator.onDirectPageWrite(n,o);const a=this.vfs.writePage(n,o);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,r=this.coordinator.getSpilledPage(n);this.uint8.set(r,i)}else await this.readSlot(e,n)}async flush(){await this.vfs.flush()}}const ii=new Uint8Array([87,69,66,87,65,76]);function ri(t={}){const e=new Uint8Array(Mn),n=new DataView(e.buffer,e.byteOffset,e.byteLength);e.set(ii,Ds),zn(n,Rs,t.walVersion??fr),It(n,Qs,t.pageSize??ue),It(n,bs,t.checkpointSeq??0);const s=t.salt1??Math.floor(Math.random()*4294967295)>>>0;It(n,ks,s);const i=t.salt2??Math.floor(Math.random()*4294967295)>>>0;It(n,Gs,i);const r=t.checksum??ei(e,0,24);return It(n,vs,r),It(n,_r,0),e}function xn(t,e=!0){if(t.byteLength<Mn)throw new Zn(`Truncated WAL file header: expected at least ${Mn} bytes, received ${t.byteLength}`);for(let c=0;c<6;c++)if(t[Ds+c]!==ii[c])throw new Zn('Invalid WAL file header magic identifier (expected "WEBWAL")');const n=new DataView(t.buffer,t.byteOffset,t.byteLength),s=Kn(n,Rs),i=mt(n,Qs),r=mt(n,bs),o=mt(n,ks),a=mt(n,Gs),l=mt(n,vs);if(e){const c=ei(t,0,24);if(l!==c)throw new Zn(`WAL file header CRC32 checksum mismatch: stored ${l}, computed ${c}`)}return{walVersion:s,pageSize:i,checkpointSeq:r,salt1:o,salt2:a,checksum:l}}function ts(t,e){const n=new Uint8Array(Ge),s=new DataView(n.buffer,n.byteOffset,n.byteLength);It(s,Ms,t.magic??hn),zn(s,Ws,t.frameType),zn(s,Hs,t.flags??0),It(s,Vs,t.txId),It(s,Xs,t.pageId),It(s,$s,t.dbSizePages??0),It(s,Ys,t.frameSeq),It(s,gr,0),e&&n.set(e.subarray(0,ue),Ne);const i=t.checksum??jn(n);return It(s,Zs,i),n}function oi(t){if(t.byteLength<Ne)throw new mn(`Truncated WAL frame header: expected at least ${Ne} bytes, received ${t.byteLength}`);const e=new DataView(t.buffer,t.byteOffset,t.byteLength);return{magic:mt(e,Ms),frameType:Kn(e,Ws),flags:Kn(e,Hs),txId:mt(e,Vs),pageId:mt(e,Xs),dbSizePages:mt(e,$s),frameSeq:mt(e,Ys),checksum:mt(e,Zs)}}function ai(t){if(t.byteLength<Ge)return{valid:!1,reason:"truncated"};const e=oi(t);if(e.magic!==hn)return{valid:!1,reason:"magic_mismatch",header:e};const n=jn(t);return e.checksum!==n?{valid:!1,reason:"checksum_mismatch",header:e}:{valid:!0,header:e}}function Ec(t,e=!0){if(t.byteLength<Ge)throw new mn(`Truncated WAL frame: expected ${Ge} bytes, received ${t.byteLength}`);const n=oi(t);if(n.magic!==hn)throw new mn(`Invalid WAL frame magic: expected 0x${hn.toString(16)}, got 0x${n.magic.toString(16)}`);if(e){const i=jn(t);if(n.checksum!==i)throw new mn(`WAL frame CRC32 checksum mismatch: stored ${n.checksum}, computed ${i}`)}const s=t.subarray(Ne,Ge);return{header:n,pageData:s}}const Wr=new TextDecoder,Hr="0123456789abcdef",ci="0123456789ABCDEFGHJKMNPQRSTVWXYZ";function mc(t){return t>=48&&t<=57?t-48:t>=97&&t<=102?t-97+10:t>=65&&t<=70?t-65+10:-1}function li(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 Ic(t,e,n){let s=0,i=-1;for(let r=0;r<Jn(t);r++){const o=t.charCodeAt(r);if(o!==45){if(s>=32)return-1;const a=mc(o);if(a<0)return-1;s%2===0?i=a:e[n+(s>>1)]=i<<4|a,s++}}return s!==32?-1:0}function pc(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 r=t[e+i];n[s++]=Hr.charCodeAt(r>>4&15),n[s++]=Hr.charCodeAt(r&15)}n[s]=0}class Me{static encode(e,n,s=0){if(Ic(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 pc(e,n,s),Wr.decode(s.subarray(0,36))}}function Tc(t,e,n){if(Jn(t)!==26)return-1;let s=0n;for(let o=0;o<10;o++){const a=li(t.charCodeAt(o));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 o=10;o<18;o++){const a=li(t.charCodeAt(o));if(a<0)return-1;i=i<<5n|BigInt(a)}let r=0n;for(let o=18;o<26;o++){const a=li(t.charCodeAt(o));if(a<0)return-1;r=r<<5n|BigInt(a)}for(let o=0;o<5;o++)e[n+6+o]=Number(i>>BigInt((4-o)*8)&0xffn),e[n+11+o]=Number(r>>BigInt((4-o)*8)&0xffn);return 0}function yc(t,e,n){let s=0n;for(let o=0;o<6;o++)s=s<<8n|BigInt(t[e+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(t[e+6+o]);let r=0n;for(let o=0;o<5;o++)r=r<<8n|BigInt(t[e+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 We{static encode(e,n,s=0){if(Tc(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 yc(e,n,s),Wr.decode(s.subarray(0,26))}}const ui=new TextEncoder,es=new TextDecoder;function pn(t,e,n=Hn,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+Ie,0,!0)}function Vr(t,e,n=0){t.setUint8(e+0,Be),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+Ie,0,!0)}function He(t,e){return t.getUint8(e+0)}function Uc(t,e,n){t.setUint8(e+0,n)}function dt(t,e){return t.getUint16(e+2,!0)}function Ve(t,e,n){t.setUint16(e+2,n,!0)}function we(t,e){return t.getUint16(e+4,!0)}function Le(t,e,n){t.setUint16(e+4,n,!0)}function kt(t,e){return t.getUint32(e+6,!0)}function Ai(t,e,n){t.setUint32(e+6,n,!0)}function Fe(t,e){return t.getUint16(e+10,!0)}function Xe(t,e,n){t.setUint16(e+10,n,!0)}function Cc(t,e){return t.getUint32(e+Ie,!0)}function Oc(t,e,n){t.setUint32(e+Ie,n,!0)}function ht(t,e,n){const s=e+Jt+n*2;return t.getUint16(s,!0)}function $e(t,e,n,s){const i=e+Jt+n*2;t.setUint16(i,s,!0)}function ns(t,e){const n=dt(t,e),s=we(t,e),i=Jt+n*2;return s-i}function Xr(t,e){return ns(t,e)+Fe(t,e)}function Tn(t,e,n=0,s){const i=dt(t,e);if(i===0){Le(t,e,4096),Xe(t,e,0);return}let r=t,o=n;if(n===0||n===e||n+4096>t.byteLength){const l=new Uint8Array(4096);r=new DataView(l.buffer),o=0}In(r,o,t,e,Jt);let a=4096;for(let l=0;l<i;l++){let c=0,u=t,E=0;if(s&&l===s.cell_idx)c=s.row_bytes.byteLength,u=s.row_bytes,E=0;else{const f=ht(t,e,l);c=ss(t,e+f),u=t,E=e+f}a=a-c,In(r,o+a,u,E,c),$e(r,o,l,a)}Le(r,o,a),Xe(r,o,0),In(t,e,r,o,4096)}function ss(t,e){return t.getUint16(e+1,!0)}function is(t,e,n,s){const i=dt(t,e),r=we(t,e),o=n.byteLength+2,a=Jt+i*2,l=r-a,c=l+Fe(t,e);if(o>c)return-1;o>l&&Tn(t,e,s);const u=we(t,e),E=dt(t,e),f=u-n.byteLength,_=t.byteOffset+e+f;return new Uint8Array(t.buffer).set(n,_),$e(t,e,E,f),Ve(t,e,E+1),Le(t,e,f),E}function Sc(t,e,n){const s=dt(t,e);if(n>=s)return;const i=ht(t,e,n),r=ss(t,e+i),o=e+Jt,a=o+(n+1)*2,l=o+n*2,c=(s-1-n)*2;c>0&&In(t,l,t,a,c),Ve(t,e,s-1),Xe(t,e,Fe(t,e)+r)}function $r(t,e,n,s,i){const r=dt(t,e);if(n<0||n>=r)throw new Error(`Invalid cell index ${n} for update`);const o=ht(t,e,n),a=ss(t,e+o),l=s.byteLength,c=new Uint8Array(t.buffer);if(l<=a)return c.set(s,t.byteOffset+e+o),l<a&&Xe(t,e,Fe(t,e)+(a-l)),!0;const u=Xr(t,e),E=l-a;if(u>=E){if(ns(t,e)<l)return Tn(t,e,i,{cell_idx:n,row_bytes:s}),!0;Xe(t,e,Fe(t,e)+a);const d=we(t,e)-l;return c.set(s,t.byteOffset+e+d),$e(t,e,n,d),Le(t,e,d),!0}return!1}function Nc(t){const e=Array.isArray(t)?t:t.columns,n=Math.ceil(e.length/8);let s=0,i=0;for(let r=0;r<e.length;r++){const o=e[r];o.type===y.INT32?s+=4:o.type===y.INT64||o.type===y.FLOAT64?s+=8:o.type===y.UUID||o.type===y.ULID?s+=16:(o.type===y.TEXT||o.type===y.BLOB)&&i++}return{null_bitmap_bytes:n,fixed_slice_size:s,var_col_count:i}}function fi(t,e){const n=Array.isArray(t)?t:t.columns,s=n.length;if(s>_n)throw new zs(s,_n);const i=Math.ceil(s/8),r=new Uint8Array(i);for(let p=0;p<s;p++){const T=n[p],U=e[T.name];if(U==null){if(T.flags&Ct.NOT_NULL)throw new Js(T.name);const F=p>>3,P=1<<(p&7);r[F]|=P}}let o=0;for(let p=0;p<s;p++){const T=n[p];if(!((r[p>>3]&1<<(p&7))!==0))switch(T.type){case y.INT32:o+=4;break;case y.INT64:case y.FLOAT64:o+=8;break;case y.UUID:case y.ULID:o+=16;break}}const a=[];for(let p=0;p<s;p++){const T=n[p];if(T.type===y.TEXT||T.type===y.BLOB)if((r[p>>3]&1<<(p&7))!==0)a.push({col_idx:p,col:T,payload:null});else{const B=e[T.name];let F;T.type===y.TEXT?F=ui.encode(String(B??"")):F=B instanceof Uint8Array?B:new Uint8Array(B),a.push({col_idx:p,col:T,payload:F})}}const l=a.length*4,c=3+i+o+l;let u=0;for(let p=0;p<a.length;p++){const T=a[p];T.payload&&(u+=T.payload.byteLength)}const E=c+u;if(E>2048)throw new Tr(E,2048);const f=new Uint8Array(E),_=new DataView(f.buffer);_.setUint8(0,1),_.setUint16(1,E,!0),f.set(r,3);let d=3+i;for(let p=0;p<s;p++){const T=n[p];if(!((r[p>>3]&1<<(p&7))!==0)){const B=e[T.name];switch(T.type){case y.INT32:_.setInt32(d,Number(B),!0),d+=4;break;case y.INT64:_.setBigInt64(d,BigInt(B),!0),d+=8;break;case y.FLOAT64:_.setFloat64(d,Number(B),!0),d+=8;break;case y.UUID:Me.encode(String(B),f,d),d+=16;break;case y.ULID:We.encode(String(B),f,d),d+=16;break}}}let m=d,I=c;for(let p=0;p<a.length;p++){const T=a[p];T.payload===null?(_.setUint16(m,0,!0),_.setUint16(m+2,0,!0)):(_.setUint16(m,I,!0),_.setUint16(m+2,T.payload.byteLength,!0),f.set(T.payload,I),I+=T.payload.byteLength),m+=4}return f}function _i(t,e,n){let s,i,r;if(t instanceof DataView){i=t,r=e;const d=n;s=Array.isArray(d)?d:d.columns}else s=Array.isArray(t)?t:t.columns,i=e,r=n;const o={},a=s.length,l=Math.ceil(a/8),c=new Uint8Array(i.buffer,i.byteOffset+r+3,l);let u=r+3+l,E=0;const f=u;for(let d=0;d<a;d++){const m=s[d];if(!((c[d>>3]&1<<(d&7))!==0))switch(m.type){case y.INT32:u+=4;break;case y.INT64:case y.FLOAT64:u+=8;break;case y.UUID:case y.ULID:u+=16;break}}const _=u;u=f;for(let d=0;d<a;d++){const m=s[d];if((c[d>>3]&1<<(d&7))!==0){o[m.name]=null,(m.type===y.TEXT||m.type===y.BLOB)&&E++;continue}switch(m.type){case y.INT32:o[m.name]=i.getInt32(u,!0),u+=4;break;case y.INT64:o[m.name]=i.getBigInt64(u,!0),u+=8;break;case y.FLOAT64:o[m.name]=i.getFloat64(u,!0),u+=8;break;case y.UUID:{const p=new Uint8Array(i.buffer,i.byteOffset+u,16);o[m.name]=Me.decode(p,0),u+=16;break}case y.ULID:{const p=new Uint8Array(i.buffer,i.byteOffset+u,16);o[m.name]=We.decode(p,0),u+=16;break}case y.TEXT:{const p=_+E*4,T=i.getUint16(p,!0),U=i.getUint16(p+2,!0),B=i.byteOffset+r+T,F=new Uint8Array(i.buffer,B,U);o[m.name]=es.decode(F),E++;break}case y.BLOB:{const p=_+E*4,T=i.getUint16(p,!0),U=i.getUint16(p+2,!0),B=i.byteOffset+r+T,F=new Uint8Array(U);F.set(new Uint8Array(i.buffer,B,U)),o[m.name]=F,E++;break}}}return o}function Yr(t,e,n=0){pn(t,e,qs,n)}function rs(t,e){return t.getUint32(e+6,!0)}function Zr(t,e,n){t.setUint32(e+6,n,!0)}function qr(t,e,n,s){const i=dt(t,e);if(i>=zi)return-1;const o=we(t,e)-Ki,a=e+o;return t.setUint32(a,n,!0),t.setBigInt64(a+4,s,!0),$e(t,e,i,o),Ve(t,e,i+1),Le(t,e,o),i+1}function Bc(t,e,n){const s=dt(t,e);if(s===0)return rs(t,e);let i=0,r=s-1,o=-1;for(;i<=r;){const a=i+r>>1,l=ht(t,e,a),c=t.getBigInt64(e+l+4,!0);n<=c?(o=t.getUint32(e+l,!0),r=a-1):i=a+1}return o!==-1?o:rs(t,e)}function Pc(t,e,n){const s=dt(t,e),i=xi;if(s<=i)throw new Error(`Cannot split interior page with only ${s} cells`);const r=ht(t,e,i),o=t.getUint32(e+r,!0),a=t.getBigInt64(e+r+4,!0),l=rs(t,e);Yr(t,n,l);for(let c=i+1;c<s;c++){const u=ht(t,e,c),E=t.getUint32(e+u,!0),f=t.getBigInt64(e+u+4,!0);qr(t,n,E,f)}return Zr(t,e,o),Ve(t,e,i),{median_rowid:a,promoted_child_page_id:o,right_child_page_id:l}}function os(t,e,n=0){pn(t,e,js,n)}function as(t,e,n,s,i,r){if(t!==s)return t-s;if(t===y.NULL)return n<r?-1:n>r?1:0;let o=0;if(t===y.INT32||t===y.INT64||t===y.FLOAT64){const a=typeof e=="bigint"?Number(e):e,l=typeof i=="bigint"?Number(i):i;o=a<l?-1:a>l?1:0}else if(t===y.TEXT||t===y.UUID||t===y.ULID){const a=String(e),l=String(i);o=a<l?-1:a>l?1:0}else if(t===y.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]){o=a[u]<l[u]?-1:1;break}o===0&&(o=a.length-l.length)}return o!==0?o:n<r?-1:n>r?1:0}function gi(t,e,n,s){const i=new Uint8Array(t.buffer,t.byteOffset+e,n);return n===0?{cellType:y.NULL,cellVal:null}:s===y.TEXT?n===4&&(i[2]===0&&i[3]===0||i[2]===255&&i[3]===255)?{cellType:y.INT32,cellVal:new DataView(i.buffer,i.byteOffset).getInt32(0,!0)}:n===2&&i[0]<32&&i[1]<32?{cellType:y.BLOB,cellVal:i}:{cellType:y.TEXT,cellVal:es.decode(i)}:n===2?{cellType:y.BLOB,cellVal:i}:n===4?{cellType:y.INT32,cellVal:new DataView(i.buffer,i.byteOffset).getInt32(0,!0)}:s===y.UUID&&n===16?{cellType:y.UUID,cellVal:Me.decode(i,0)}:s===y.ULID&&n===16?{cellType:y.ULID,cellVal:We.decode(i,0)}:s===y.FLOAT64&&n===8?{cellType:y.FLOAT64,cellVal:new DataView(i.buffer,i.byteOffset).getFloat64(0,!0)}:s===y.INT64&&n===8?{cellType:y.INT64,cellVal:new DataView(i.buffer,i.byteOffset).getBigInt64(0,!0)}:s===y.BLOB?n===5||n===6?{cellType:y.TEXT,cellVal:es.decode(i)}:{cellType:y.BLOB,cellVal:i}:{cellType:y.TEXT,cellVal:es.decode(i)}}function hi(t,e,n,s,i,r){let o;n===y.NULL||s===null||s===void 0?o=new Uint8Array(0):n===y.INT32?(o=new Uint8Array(4),new DataView(o.buffer).setInt32(0,Number(s),!0)):n===y.INT64?(o=new Uint8Array(8),new DataView(o.buffer).setBigInt64(0,BigInt(s),!0)):n===y.FLOAT64?(o=new Uint8Array(8),new DataView(o.buffer).setFloat64(0,Number(s),!0)):n===y.UUID?(o=new Uint8Array(16),Me.encode(String(s),o,0)):n===y.ULID?(o=new Uint8Array(16),We.encode(String(s),o,0)):n===y.TEXT?o=ui.encode(String(s)):o=s instanceof Uint8Array?s:new Uint8Array(s);const a=2+o.byteLength+8,l=a+2,c=dt(t,e),u=ns(t,e),E=u+Fe(t,e);if(l>E)return-1;l>u&&Tn(t,e,r);const _=we(t,e)-a,d=e+_,m=t.byteOffset+d;t.setUint16(d,o.byteLength,!0),new Uint8Array(t.buffer).set(o,m+2),t.setBigInt64(d+2+o.byteLength,i,!0);let I=0,p=c-1,T=c;for(;I<=p;){const D=I+p>>1,v=ht(t,e,D),Q=t.getUint16(e+v,!0),A=t.getBigInt64(e+v+2+Q,!0),{cellType:N,cellVal:k}=gi(t,e+v+2,Q,n);as(n,s,i,N,k,A)<0?(T=D,p=D-1):I=D+1}const U=new Uint8Array(t.buffer),F=t.byteOffset+e+Jt,P=F+T*2,w=F+(T+1)*2,O=(c-T)*2;return O>0&&U.copyWithin(w,P,P+O),$e(t,e,T,_),Ve(t,e,c+1),Le(t,e,_),T}function cs(t,e,n,s,i){const r=dt(t,e);let o=0,a=r-1;for(;o<=a;){const l=o+a>>1,c=ht(t,e,l),u=t.getUint16(e+c,!0),E=t.getBigInt64(e+c+2+u,!0),{cellType:f,cellVal:_}=gi(t,e+c+2,u,n),m=as(n,s,i!==void 0?i:E,f,_,E);if(m===0){if(i===void 0){let I=l;for(;I>0;){const p=I-1,T=ht(t,e,p),U=t.getUint16(e+T,!0),{cellType:B,cellVal:F}=gi(t,e+T+2,U,n);if(as(n,s,0n,B,F,0n)===0)I=p;else break}return{found:!0,slot_idx:I}}return{found:!0,slot_idx:l}}else m<0?a=l-1:o=l+1}return{found:!1,slot_idx:o}}function jr(t,e){if(e==null)return new Uint8Array(0);if(t===y.INT32){const n=new Uint8Array(4);return new DataView(n.buffer).setInt32(0,Number(e),!0),n}if(t===y.INT64){const n=new Uint8Array(8);return new DataView(n.buffer).setBigInt64(0,BigInt(e),!0),n}if(t===y.FLOAT64){const n=new Uint8Array(8);return new DataView(n.buffer).setFloat64(0,Number(e),!0),n}if(t===y.UUID){const n=new Uint8Array(16);return Me.encode(String(e),n,0),n}if(t===y.ULID){const n=new Uint8Array(16);return We.encode(String(e),n,0),n}return t===y.TEXT?ui.encode(String(e)):e instanceof Uint8Array?e:new Uint8Array(e)}function ls(t,e,n,s){const i=[];let r=0;for(let l=0;l<n;l++){const c=t[e[l]],u=s[c.name],E=jr(c.type,u),f=new Uint8Array(3+E.byteLength);f[0]=c.type,f[1]=E.byteLength&255,f[2]=E.byteLength>>8&255,f.set(E,3),i.push(f),r+=f.byteLength}const o=new Uint8Array(r);let a=0;for(let l=0;l<i.length;l++){const c=i[l];o.set(c,a),a+=c.byteLength}return o}const wc=2654435769;function yn(t,e){const n=Math.imul(t,wc);return(n^n>>>16)>>>0&e}function Jr(t,e,n,s){const i=n-1;let r=yn(s,i);for(let o=0;o<n;o++){const a=e+r*le,l=t.getUint32(a,!0);if(l===0)return-1;if(l===s)return t.getUint32(a+4,!0);r=r+1&i}return-1}function Kr(t,e,n,s,i){const r=n-1;let o=yn(s,r);for(let a=0;a<n;a++){const l=e+o*le,c=t.getUint32(l,!0);if(c===0||c===s){t.setUint32(l,s,!0),t.setUint32(l+4,i,!0);return}o=o+1&r}throw new Error(`BufferPool page table full: cannot insert page ${s}`)}function di(t,e,n,s){const i=n-1;let r=yn(s,i),o=!1;for(let c=0;c<n;c++){const u=e+r*le,E=t.getUint32(u,!0);if(E===0)return!1;if(E===s){o=!0;break}r=r+1&i}if(!o)return!1;let a=r;for(;;){a=a+1&i;const c=e+a*le,u=t.getUint32(c,!0);if(u===0)break;const E=yn(u,i);if((r-E&i)<(a-E&i)){const f=t.getUint32(c+4,!0),_=e+r*le;t.setUint32(_,u,!0),t.setUint32(_+4,f,!0),r=a}}const l=e+r*le;return t.setUint32(l,0,!0),t.setUint32(l+4,0,!0),!0}function Lc(t){return t*4096}function Ye(t,e,n){return mt(t,e+n*4)}function Ei(t,e,n,s){It(t,e+n*4,s)}function Gt(t,e,n,s){return Jr(t,e,n,s)}function zr(t,e,n,s,i,r){Mr(r>0,"page_id must be > 0");const o=Ye(t,e,i);return o>0&&o!==r&&di(t,n,s,o),Ei(t,e,i,r),Kr(t,n,s,r,i),0}function xr(t,e,n,s,i){const r=Ye(t,e,i);return r>0?(di(t,n,s,r),Ei(t,e,i,0),1):0}function to(t,e,n){Gr(t,e,n)}function eo(t,e,n){vr(t,e,n)}function mi(t,e,n){return kr(t,e,n)===1}function Ii(t,e){if(t[e]>=4294967295)throw new Error(`Pin count overflow on slot ${e}`);t[e]++}function pi(t,e){e!==0&&t[e]>0&&t[e]--}function Ze(t,e){return e===0||t[e]>0}function Ti(t,e,n,s,i,r){const o=new DataView(t);for(let l=1;l<i;l++)if(mt(o,s+l*4)===0&&!Ze(n,l))return{candidate_slot:l,next_clock_hand:r};let a=r;for(let l=0;l<i*2;l++){if(a=(a+1)%i,a===0||Ze(n,a))continue;const c=new DataView(t,a*4096,4096);if(He(c,0)!==dn)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 yi(t,e,n,s,i,r,o,a){const l=new DataView(t);let c=-1,u=o;if(a>1&&a<=r&&Ye(l,s,a-1)===0&&!Ze(n,a-1))c=a-1;else{const I=Ti(t,e,n,s,r,o);c=I.candidate_slot,u=I.next_clock_hand}const E=Ye(l,s,c),f=mi(new Uint8Array(t),i,c),_=new DataView(t,c*4096,4096),d=E>0&&He(_,0)===Be,m=f&&!d&&E>0?E:0;return{candidate_slot:c,flush_page_id:m,next_clock_hand:u}}function pt(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>=Dt+nr){const n=Gt(t,Dt,Qt,e);if(n>=0)return n*4096}return(e-1)*4096}function qe(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 no(t){return t>=65&&t<=90?t+32:t}function Fc(t,e,n,s){let i=0,r=0,o=-1,a=-1;for(;i<e;){const l=r<s?n.charCodeAt(r):0,c=t.charCodeAt(i);if(r<s&&(l===95||no(l)===no(c)))i++,r++;else if(r<s&&l===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 Un(t,e){return Fc(t,t.length,e,e.length)===1}function je(t,e,n){const s=n.numKeys;for(let i=0;i<s;i++){const r=t[i],o=e[i],a=n.directions[i]??0,l=n.nullOrders[i]??(a===1?1:0),c=r==null,u=o==null;if(c&&u)continue;if(c||u)return l===0?c?-1:1:c?1:-1;let E=0;if(typeof r=="number"&&typeof o=="number")E=r<o?-1:r>o?1:0;else if(typeof r=="bigint"||typeof o=="bigint"){const f=BigInt(r),_=BigInt(o);E=f<_?-1:f>_?1:0}else if(typeof r=="string"&&typeof o=="string")E=r<o?-1:r>o?1:0;else if(r instanceof Uint8Array&&o instanceof Uint8Array){const f=Math.min(r.byteLength,o.byteLength);for(let _=0;_<f;_++)if(r[_]!==o[_]){E=r[_]<o[_]?-1:1;break}E===0&&(E=r.byteLength<o.byteLength?-1:r.byteLength>o.byteLength?1:0)}else E=r<o?-1:r>o?1:0;if(E!==0)return a===1?-E:E}return 0}function so(t,e,n,s){const i=s.numKeys;for(let r=0;r<i;r++){const o=t[e+r],a=n[r],l=s.directions[r]??0,c=s.nullOrders[r]??(l===1?1:0),u=o==null,E=a==null;if(u&&E)continue;if(u||E)return c===0?u?-1:1:u?1:-1;let f=0;if(typeof o=="number"&&typeof a=="number")f=o<a?-1:o>a?1:0;else if(typeof o=="string"&&typeof a=="string")f=o<a?-1:o>a?1:0;else if(typeof o=="bigint"||typeof a=="bigint"){const _=BigInt(o),d=BigInt(a);f=_<d?-1:_>d?1:0}else if(o instanceof Uint8Array&&a instanceof Uint8Array){const _=Math.min(o.byteLength,a.byteLength);for(let d=0;d<_;d++)if(o[d]!==a[d]){f=o[d]<a[d]?-1:1;break}f===0&&(f=o.byteLength<a.byteLength?-1:o.byteLength>a.byteLength?1:0)}else f=o<a?-1:o>a?1:0;if(f!==0)return l===1?-f:f}return 0}function us(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 r=new Uint8Array(i);for(let o=0;o<8;o++)e^=r[o],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 Dc(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 r=0;r<s.byteLength;r++)if(s[r]!==i[r])return!1}else return!1}}return!0}function io(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 ro(t,e,n,s){let i=e;for(;;){let r=i;const o=2*i+1,a=2*i+2;if(o<n&&je(t[o].keys,t[r].keys,s)>0&&(r=o),a<n&&je(t[a].keys,t[r].keys,s)>0&&(r=a),r!==i){const l=t[i];t[i]=t[r],t[r]=l,i=r}else break}}function Rc(t){const e=t.keyInfo;t.entries.sort((n,s)=>je(n.keys,s.keys,e)),t.readIdx=e.offset??0}function oo(t,e,n){const s=new Uint8Array(t.buffer,t.byteOffset+e,n),i=new Uint8Array(n);return i.set(s),i}function Qc(t,e,n,s,i,r,o){if(o>0&&e.entries.length>=o){if(je(n,e.entries[0].keys,e.keyInfo)>=0)return C.RUNNING;const u=e.entries[0],E=i-u.rowLen;if(E>0&&t.arenaOffset+E>t.maxQueryMemory)return t.status=C.ARENA_EXHAUSTED,C.ARENA_EXHAUSTED;t.arenaOffset+=E;const f=oo(r,s,i);return u.keys=n,u.rowOffset=s,u.rowLen=i,u.rowData=f,ro(e.entries,0,o,e.keyInfo),C.RUNNING}const a=16+16*n.length+i;if(t.arenaOffset+a>t.maxQueryMemory)return t.status=C.ARENA_EXHAUSTED,C.ARENA_EXHAUSTED;t.arenaOffset+=a;const l=oo(r,s,i);if(e.entries.push({keys:n,rowOffset:s,rowLen:i,rowData:l}),o>0&&e.entries.length===o)for(let c=Math.floor(o/2)-1;c>=0;c--)ro(e.entries,c,o,e.keyInfo);return C.RUNNING}function bc(t,e,n){var r,o;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=((o=(r=t.table)==null?void 0:r.columns[a])==null?void 0:o.name)??`col_${a}`;let u=y.TEXT;typeof l=="number"?u=Number.isInteger(l)?y.INT32:y.FLOAT64:typeof l=="bigint"?u=y.INT64:l instanceof Uint8Array&&(u=y.BLOB),s.push({name:c,type:u,flags:Ct.NONE,colOffset:0}),i[c]=l}}return fi(s,i)}function Ui(t,e,n,s){const i=2+n.byteLength;if(t.resultOffset+i>Ls)return t.status=C.BUFFER_FULL,t.pc=s,C.BUFFER_FULL;const r=gn+t.resultOffset;return e.setUint16(r,n.byteLength,!0),new Uint8Array(e.buffer,e.byteOffset+r+2,n.byteLength).set(n),t.resultOffset+=i,t.resultCount++,C.RUNNING}function De(t,e,n){return(t.getUint8(e+(n>>3))&1<<(n&7))!==0}function Cn(t,e,n,s,i){let r=e+n;for(let o=0;o<i;o++)if(!De(t,e,o))switch(s[o].type){case y.INT32:r+=4;break;case y.INT64:case y.FLOAT64:r+=8;break;case y.UUID:case y.ULID:r+=16;break}return r}const ao=new TextDecoder;function On(t,e,n){var l,c;const s=new DataView(n.buffer,n.byteOffset,n.byteLength),i=n.byteLength,r=1e7;let o=0;const a=e.byteLength>=bn+4&&e.getUint32(bn,!0)>0;for(;t.pc<i;){if(++o>r)return t.status=C.TIMEOUT,C.TIMEOUT;const u=t.pc,E=n[t.pc];switch(t.pc+=1,E){case g.OP_HALT:return t.arenaOffset=0,t.status=C.DONE,C.DONE;case g.OP_OPEN_CURSOR:{const f=n[t.pc],_=s.getUint32(t.pc+1,!0);t.pc+=5;const d=pt(t,f);if(d.pageId=_,d.cellIdx=0,d.rowOffset=0,a&&_>0){const m=Gt(e,Dt,Qt,_);if(m<0)return t.fault_page_id=_,t.status=C.PAGE_FAULT,t.pc=u,C.PAGE_FAULT;d.slotIdx=m}break}case g.OP_REWIND:{const f=n[t.pc],_=s.getUint16(t.pc+1,!0);if(t.pc+=3,_>i)return t.status=C.INVALID_BYTECODE,C.INVALID_BYTECODE;const d=pt(t,f);if(a&&d.pageId>0){const p=Gt(e,Dt,Qt,d.pageId);if(p<0)return t.fault_page_id=d.pageId,t.status=C.PAGE_FAULT,t.pc=u,C.PAGE_FAULT;d.slotIdx=p}const m=Mt(e,d.pageId);if(dt(e,m)===0)t.pc=_;else{d.cellIdx=0;const p=ht(e,m,0);d.rowOffset=m+p}break}case g.OP_NEXT_ROW:{const f=n[t.pc],_=s.getUint16(t.pc+1,!0);if(t.pc+=3,_>i)return t.status=C.INVALID_BYTECODE,C.INVALID_BYTECODE;const d=pt(t,f),m=Mt(e,d.pageId),I=dt(e,m),p=d.cellIdx+1;if(p<I){d.cellIdx=p;const T=ht(e,m,d.cellIdx);d.rowOffset=m+T}else{const T=kt(e,m);if(T!==0){if(a){const F=Gt(e,Dt,Qt,T);if(F<0)return t.fault_page_id=T,t.status=C.PAGE_FAULT,t.pc=u,C.PAGE_FAULT;d.slotIdx=F}d.pageId=T,d.cellIdx=0;const U=Mt(e,T);if(dt(e,U)>0){const F=ht(e,U,0);d.rowOffset=U+F}else t.pc=_}else t.pc=_}break}case g.OP_LAST:{const f=n[t.pc],_=s.getUint16(t.pc+1,!0);if(t.pc+=3,_>i)return t.status=C.INVALID_BYTECODE,C.INVALID_BYTECODE;const d=pt(t,f),m=Mt(e,d.pageId),I=dt(e,m);if(I===0)t.pc=_;else{d.cellIdx=I-1;const p=ht(e,m,d.cellIdx);d.rowOffset=m+p}break}case g.OP_PREV_ROW:{const f=n[t.pc],_=s.getUint16(t.pc+1,!0);if(t.pc+=3,_>i)return t.status=C.INVALID_BYTECODE,C.INVALID_BYTECODE;const d=pt(t,f),m=Mt(e,d.pageId);if(d.cellIdx>0){d.cellIdx--;const I=ht(e,m,d.cellIdx);d.rowOffset=m+I}else t.pc=_;break}case g.OP_COLUMN_INT:{const f=n[t.pc],_=n[t.pc+1],d=n[t.pc+2];t.pc+=3;const m=pt(t,f),I=(t.tables&&t.tables[f])??t.table,p=I.columns[_],T=Math.ceil(I.columns.length/8),U=m.rowOffset+3;if(De(e,U,_)){t.registers[d]=null;break}const B=Cn(e,U,T,I.columns,_);p.type===y.INT32?t.registers[d]=e.getInt32(B,!0):p.type===y.INT64&&(t.registers[d]=Number(e.getBigInt64(B,!0)));break}case g.OP_COLUMN_FLOAT:{const f=n[t.pc],_=n[t.pc+1],d=n[t.pc+2];t.pc+=3;const m=pt(t,f),I=(t.tables&&t.tables[f])??t.table,p=Math.ceil(I.columns.length/8),T=m.rowOffset+3;if(De(e,T,_)){t.registers[d]=null;break}const U=Cn(e,T,p,I.columns,_);t.registers[d]=e.getFloat64(U,!0);break}case g.OP_COLUMN_UUID:case g.OP_COLUMN_ULID:case g.OP_COLUMN_TEXT:{const f=n[t.pc],_=n[t.pc+1],d=n[t.pc+2];t.pc+=3;const m=pt(t,f),I=(t.tables&&t.tables[f])??t.table,p=Math.ceil(I.columns.length/8),T=m.rowOffset+3;if(De(e,T,_)){t.registers[d]=null;break}if(I.columns[_].type===y.UUID||I.columns[_].type===y.ULID){const O=Cn(e,T,p,I.columns,_),D=new Uint8Array(e.buffer,e.byteOffset+O,16);t.registers[d]=I.columns[_].type===y.UUID?Me.decode(D,0):We.decode(D,0);break}const U=Cn(e,T,p,I.columns,I.columns.length);let B=0;for(let O=0;O<_;O++){const D=I.columns[O];(D.type===y.TEXT||D.type===y.BLOB)&&B++}const F=U+B*4,P=e.getUint16(F,!0),w=e.getUint16(F+2,!0);if(w===0)t.registers[d]="";else{const O=new Uint8Array(e.buffer,m.rowOffset+P,w);t.registers[d]=ao.decode(O)}break}case g.OP_COLUMN_BLOB:{const f=n[t.pc],_=n[t.pc+1],d=n[t.pc+2];t.pc+=3;const m=pt(t,f),I=(t.tables&&t.tables[f])??t.table,p=Math.ceil(I.columns.length/8),T=m.rowOffset+3;if(De(e,T,_)){t.registers[d]=null;break}const U=Cn(e,T,p,I.columns,I.columns.length);let B=0;for(let D=0;D<_;D++){const v=I.columns[D];(v.type===y.TEXT||v.type===y.BLOB)&&B++}const F=U+B*4,P=e.getUint16(F,!0),w=e.getUint16(F+2,!0),O=new Uint8Array(w);O.set(new Uint8Array(e.buffer,m.rowOffset+P,w)),t.registers[d]=O;break}case g.OP_OPEN_INDEX:{const f=n[t.pc],_=s.getUint32(t.pc+1,!0);t.pc+=5;const d=pt(t,f);if(d.pageId=_,d.rootPageId=_,d.cellIdx=0,d.rowOffset=0,a&&_>0){const m=Gt(e,Dt,Qt,_);if(m<0)return t.fault_page_id=_,t.status=C.PAGE_FAULT,t.pc=u,C.PAGE_FAULT;d.slotIdx=m}break}case g.OP_INDEX_SEEK_EQ:{const f=n[t.pc],_=n[t.pc+1],d=n[t.pc+2],m=n[t.pc+3],I=s.getUint16(t.pc+4,!0);if(t.pc+=6,I>i)return t.status=C.INVALID_BYTECODE,C.INVALID_BYTECODE;const p=t.registers[d];if(p==null){t.pc=I;break}const T=pt(t,f);let U=T.rootPageId||T.pageId,B=!1,F=0n;for(;U!==0;){if(a&&U>0){const O=Gt(e,Dt,Qt,U);if(O<0)return t.fault_page_id=U,t.status=C.PAGE_FAULT,t.pc=u,C.PAGE_FAULT;T.slotIdx=O}const P=Mt(e,U),w=cs(e,P,m,p);if(w.found){B=!0,T.pageId=U,T.cellIdx=w.slot_idx;const O=ht(e,P,w.slot_idx),D=e.getUint16(P+O,!0);F=e.getBigInt64(P+O+2+D,!0);break}U=kt(e,P)}if(!B)t.pc=I;else{const P=Number(F>>16n),w=Number(F&0xffffn);if(a&&P>0&&Gt(e,Dt,Qt,P)<0)return t.fault_page_id=P,t.status=C.PAGE_FAULT,t.pc=u,C.PAGE_FAULT;const O=pt(t,_);O.pageId=P,O.cellIdx=w;const D=Mt(e,P),v=ht(e,D,w);O.rowOffset=D+v}break}case g.OP_INDEX_SEEK_GE:{const f=n[t.pc],_=n[t.pc+1],d=n[t.pc+2],m=n[t.pc+3],I=s.getUint16(t.pc+4,!0);if(t.pc+=6,I>i)return t.status=C.INVALID_BYTECODE,C.INVALID_BYTECODE;const p=t.registers[d];if(p==null){t.pc=I;break}const T=pt(t,f);let U=T.rootPageId||T.pageId,B=!1,F=0n;for(;U!==0;){if(a&&U>0){const D=Gt(e,Dt,Qt,U);if(D<0)return t.fault_page_id=U,t.status=C.PAGE_FAULT,t.pc=u,C.PAGE_FAULT;T.slotIdx=D}const P=Mt(e,U),w=dt(e,P),O=cs(e,P,m,p);if(O.found||O.slot_idx<w){B=!0,T.pageId=U,T.cellIdx=O.slot_idx;const D=ht(e,P,O.slot_idx),v=e.getUint16(P+D,!0);F=e.getBigInt64(P+D+2+v,!0);break}U=kt(e,P)}if(!B)t.pc=I;else{const P=Number(F>>16n),w=Number(F&0xffffn);if(a&&P>0&&Gt(e,Dt,Qt,P)<0)return t.fault_page_id=P,t.status=C.PAGE_FAULT,t.pc=u,C.PAGE_FAULT;const O=pt(t,_);O.pageId=P,O.cellIdx=w;const D=Mt(e,P),v=ht(e,D,w);O.rowOffset=D+v}break}case g.OP_INDEX_NEXT:{const f=n[t.pc],_=n[t.pc+1],d=s.getUint16(t.pc+2,!0);if(t.pc+=4,d>i)return t.status=C.INVALID_BYTECODE,C.INVALID_BYTECODE;const m=pt(t,f);let I=m.pageId,p=Mt(e,I);const T=dt(e,p);let U=m.cellIdx+1;if(U>=T){if(I=kt(e,p),I===0){t.pc=d;break}if(a&&I>0){const A=Gt(e,Dt,Qt,I);if(A<0)return t.fault_page_id=I,t.status=C.PAGE_FAULT,t.pc=u,C.PAGE_FAULT;m.slotIdx=A}p=Mt(e,I),U=0,m.pageId=I,m.cellIdx=-1}const B=ht(e,p,U),F=e.getUint16(p+B,!0),P=e.getBigInt64(p+B+2+F,!0),w=Number(P>>16n),O=Number(P&0xffffn);if(a&&w>0&&Gt(e,Dt,Qt,w)<0)return t.fault_page_id=w,t.status=C.PAGE_FAULT,t.pc=u,C.PAGE_FAULT;m.pageId=I,m.cellIdx=U;const D=pt(t,_);D.pageId=w,D.cellIdx=O;const v=Mt(e,w),Q=ht(e,v,O);D.rowOffset=v+Q;break}case g.OP_IS_NULL:{const f=n[t.pc],_=n[t.pc+1],d=s.getUint16(t.pc+2,!0);if(t.pc+=4,d>i)return t.status=C.INVALID_BYTECODE,C.INVALID_BYTECODE;const I=pt(t,f).rowOffset+3;De(e,I,_)&&(t.pc=d);break}case g.OP_IS_NOT_NULL:{const f=n[t.pc],_=n[t.pc+1],d=s.getUint16(t.pc+2,!0);if(t.pc+=4,d>i)return t.status=C.INVALID_BYTECODE,C.INVALID_BYTECODE;const I=pt(t,f).rowOffset+3;De(e,I,_)||(t.pc=d);break}case g.OP_EQ:{const f=n[t.pc],_=n[t.pc+1],d=s.getUint16(t.pc+2,!0);if(t.pc+=4,d>i)return t.status=C.INVALID_BYTECODE,C.INVALID_BYTECODE;const m=qe(t.registers[f],t.registers[_]);!m.is_unknown&&m.result===0&&(t.pc=d);break}case g.OP_NE:{const f=n[t.pc],_=n[t.pc+1],d=s.getUint16(t.pc+2,!0);if(t.pc+=4,d>i)return t.status=C.INVALID_BYTECODE,C.INVALID_BYTECODE;const m=qe(t.registers[f],t.registers[_]);!m.is_unknown&&m.result!==0&&(t.pc=d);break}case g.OP_GT:{const f=n[t.pc],_=n[t.pc+1],d=s.getUint16(t.pc+2,!0);if(t.pc+=4,d>i)return t.status=C.INVALID_BYTECODE,C.INVALID_BYTECODE;const m=qe(t.registers[f],t.registers[_]);!m.is_unknown&&m.result>0&&(t.pc=d);break}case g.OP_GE:{const f=n[t.pc],_=n[t.pc+1],d=s.getUint16(t.pc+2,!0);if(t.pc+=4,d>i)return t.status=C.INVALID_BYTECODE,C.INVALID_BYTECODE;const m=qe(t.registers[f],t.registers[_]);!m.is_unknown&&m.result>=0&&(t.pc=d);break}case g.OP_LT:{const f=n[t.pc],_=n[t.pc+1],d=s.getUint16(t.pc+2,!0);if(t.pc+=4,d>i)return t.status=C.INVALID_BYTECODE,C.INVALID_BYTECODE;const m=qe(t.registers[f],t.registers[_]);!m.is_unknown&&m.result<0&&(t.pc=d);break}case g.OP_LE:{const f=n[t.pc],_=n[t.pc+1],d=s.getUint16(t.pc+2,!0);if(t.pc+=4,d>i)return t.status=C.INVALID_BYTECODE,C.INVALID_BYTECODE;const m=qe(t.registers[f],t.registers[_]);!m.is_unknown&&m.result<=0&&(t.pc=d);break}case g.OP_JUMP:{const f=s.getUint16(t.pc,!0);if(f>i)return t.status=C.INVALID_BYTECODE,C.INVALID_BYTECODE;t.pc=f;break}case g.OP_STR_LIKE:{const f=n[t.pc],_=n[t.pc+1],d=s.getUint16(t.pc+2,!0);if(t.pc+=4,d>i)return t.status=C.INVALID_BYTECODE,C.INVALID_BYTECODE;const m=t.registers[f],I=t.registers[_];if(m===null||I===null)break;Un(String(m),String(I))&&(t.pc=d);break}case g.OP_STR_NOT_LIKE:{const f=n[t.pc],_=n[t.pc+1],d=s.getUint16(t.pc+2,!0);if(t.pc+=4,d>i)return t.status=C.INVALID_BYTECODE,C.INVALID_BYTECODE;const m=t.registers[f],I=t.registers[_];if(m===null||I===null)break;Un(String(m),String(I))||(t.pc=d);break}case g.OP_STR_CONTAINS:{const f=n[t.pc],_=n[t.pc+1],d=s.getUint16(t.pc+2,!0);if(t.pc+=4,d>i)return t.status=C.INVALID_BYTECODE,C.INVALID_BYTECODE;const m=t.registers[f],I=t.registers[_];if(m===null||I===null)break;String(m).includes(String(I))&&(t.pc=d);break}case g.OP_STR_STARTS_WITH:{const f=n[t.pc],_=n[t.pc+1],d=s.getUint16(t.pc+2,!0);if(t.pc+=4,d>i)return t.status=C.INVALID_BYTECODE,C.INVALID_BYTECODE;const m=t.registers[f],I=t.registers[_];if(m===null||I===null)break;String(m).startsWith(String(I))&&(t.pc=d);break}case g.OP_STR_ENDS_WITH:{const f=n[t.pc],_=n[t.pc+1],d=s.getUint16(t.pc+2,!0);if(t.pc+=4,d>i)return t.status=C.INVALID_BYTECODE,C.INVALID_BYTECODE;const m=t.registers[f],I=t.registers[_];if(m===null||I===null)break;String(m).endsWith(String(I))&&(t.pc=d);break}case g.OP_IN:{const f=n[t.pc],_=s.getUint16(t.pc+1,!0),d=s.getUint16(t.pc+3,!0);if(t.pc+=5,d>i)return t.status=C.INVALID_BYTECODE,C.INVALID_BYTECODE;const m=t.registers[f];if(m==null)break;const I=(l=t.inSets)==null?void 0:l[_];I&&(I.has(m)||typeof m=="number"&&Number.isSafeInteger(m)&&I.has(BigInt(m))||typeof m=="bigint"&&I.has(Number(m)))&&(t.pc=d);break}case g.OP_LOAD_INT:{const f=n[t.pc],_=s.getInt32(t.pc+1,!0);t.pc+=5,t.registers[f]=_;break}case g.OP_LOAD_FLOAT:{const f=n[t.pc],_=s.getFloat64(t.pc+1,!0);t.pc+=9,t.registers[f]=_;break}case g.OP_LOAD_TEXT:{const f=n[t.pc],_=s.getUint16(t.pc+1,!0),d=new Uint8Array(n.buffer,n.byteOffset+t.pc+3,_);t.registers[f]=ao.decode(d),t.pc+=3+_;break}case g.OP_LOAD_BLOB:{const f=n[t.pc],_=s.getUint16(t.pc+1,!0),d=new Uint8Array(_);d.set(new Uint8Array(n.buffer,n.byteOffset+t.pc+3,_)),t.registers[f]=d,t.pc+=3+_;break}case g.OP_LOAD_NULL:{const f=n[t.pc];t.pc+=1,t.registers[f]=null;break}case g.OP_EMIT_ROW:{const f=n[t.pc];t.pc+=1;const _=pt(t,f),d=e.getUint16(_.rowOffset+1,!0),m=new Uint8Array(e.buffer,e.byteOffset+_.rowOffset,d),I=Ui(t,e,m,u);if(I!==C.RUNNING)return I;break}case g.OP_OFFSET:{const f=n[t.pc],_=s.getUint16(t.pc+1,!0);if(t.pc+=3,_>i)return t.status=C.INVALID_BYTECODE,C.INVALID_BYTECODE;const d=Number(t.registers[f]??0);d>0&&(t.registers[f]=d-1,t.pc=_);break}case g.OP_LIMIT:{const f=n[t.pc],_=s.getUint16(t.pc+1,!0);if(t.pc+=3,_>i)return t.status=C.INVALID_BYTECODE,C.INVALID_BYTECODE;const d=Number(t.registers[f]??0);d<=1?(t.registers[f]=0,t.pc=_):t.registers[f]=d-1;break}case g.OP_CALL_UDF:{const f=s.getUint16(t.pc,!0),_=n[t.pc+2],d=n[t.pc+3],m=n[t.pc+4];t.pc+=5;const I=(c=t.udfs)==null?void 0:c[f];if(!I)return t.status=C.INVALID_BYTECODE,C.INVALID_BYTECODE;const p=[];for(let T=0;T<d;T++)p.push(t.registers[_+T]);try{const T=I(...p);t.registers[m]=T!==void 0?T:null}catch{return t.status=C.ERROR,C.ERROR}break}case g.OP_STR_LOWER:{const f=n[t.pc],_=n[t.pc+1];t.pc+=2;const d=t.registers[f];t.registers[_]=d!==null?String(d).toLowerCase():null;break}case g.OP_STR_UPPER:{const f=n[t.pc],_=n[t.pc+1];t.pc+=2;const d=t.registers[f];t.registers[_]=d!==null?String(d).toUpperCase():null;break}case g.OP_STR_LENGTH:{const f=n[t.pc],_=n[t.pc+1];t.pc+=2;const d=t.registers[f];t.registers[_]=d!==null?String(d).length:null;break}case g.OP_STR_SUBSTR:{const f=n[t.pc],_=n[t.pc+1],d=n[t.pc+2],m=n[t.pc+3];t.pc+=4;const I=t.registers[f],p=t.registers[_],T=t.registers[d];if(I===null||p===null){t.registers[m]=null;break}const U=String(I),B=Math.max(0,Number(p)-1);if(T===null)t.registers[m]=U.slice(B);else{const F=Math.max(0,Number(T));t.registers[m]=U.slice(B,B+F)}break}case g.OP_STR_TRIM:{const f=n[t.pc],_=n[t.pc+1];t.pc+=2;const d=t.registers[f];t.registers[_]=d!=null?String(d).trim():null;break}case g.OP_MATH_ABS:{const f=n[t.pc],_=n[t.pc+1];t.pc+=2;const d=t.registers[f];t.registers[_]=d!=null?Math.abs(Number(d)):null;break}case g.OP_MATH_ROUND:{const f=n[t.pc],_=n[t.pc+1];t.pc+=2;const d=t.registers[f];t.registers[_]=d!=null?Math.round(Number(d)):null;break}case g.OP_RESULT_ROW:{const f=n[t.pc],_=n[t.pc+1];t.pc+=2;const d=bc(t,f,_),m=Ui(t,e,d,u);if(m!==C.RUNNING)return m;break}case g.OP_SORTER_OPEN:{const f=n[t.pc],_=n[t.pc+1];t.pc+=2;const d=t.keyInfos[_]??{numKeys:1,directions:[0],nullOrders:[0]},m=d.limit!==void 0&&d.limit>0?(d.offset??0)+d.limit:0,I=m>0&&m<=Er?m:0;t.sorters[f]={keyInfo:d,entries:[],readIdx:0,isSorted:!1,maxK:I};break}case g.OP_SORTER_INSERT:{const f=n[t.pc],_=n[t.pc+1],d=n[t.pc+2],m=n[t.pc+3];t.pc+=4;const I=t.sorters[f];if(!I)return t.status=C.INVALID_BYTECODE,C.INVALID_BYTECODE;const p=I.maxK??0;if(p>0&&I.entries.length>=p){if(d===1){const P=t.registers[_],w=I.entries[0].keys[0],O=I.keyInfo.directions[0]??0;if(typeof P=="number"&&typeof w=="number"){if(O===0?P>=w:P<=w)break}else if(typeof P=="string"&&typeof w=="string"){if(O===0?P>=w:P<=w)break}else if(so(t.registers,_,I.entries[0].keys,I.keyInfo)>=0)break}else if(so(t.registers,_,I.entries[0].keys,I.keyInfo)>=0)break}const T=pt(t,m),U=e.getUint16(T.rowOffset+1,!0),B=new Array(d);for(let P=0;P<d;P++)B[P]=t.registers[_+P];const F=Qc(t,I,B,T.rowOffset,U,e,p);if(F!==C.RUNNING)return F;break}case g.OP_SORTER_SORT:{const f=n[t.pc];t.pc+=1;const _=t.sorters[f];if(!_)return t.status=C.INVALID_BYTECODE,C.INVALID_BYTECODE;Rc(_),_.isSorted=!0;break}case g.OP_SORTER_NEXT:{const f=n[t.pc],_=s.getUint16(t.pc+1,!0);if(t.pc+=3,_>i)return t.status=C.INVALID_BYTECODE,C.INVALID_BYTECODE;const d=t.sorters[f];if(!d)return t.status=C.INVALID_BYTECODE,C.INVALID_BYTECODE;const m=d.keyInfo.limit!==void 0?(d.keyInfo.offset??0)+d.keyInfo.limit:d.entries.length;if(d.readIdx>=Math.min(d.entries.length,m))break;const I=d.entries[d.readIdx],p=I.rowData??new Uint8Array(e.buffer,e.byteOffset+I.rowOffset,I.rowLen),T=Ui(t,e,p,u);if(T!==C.RUNNING)return T;d.readIdx++,t.pc=_;break}case g.OP_MATH_FLOOR:{const f=n[t.pc],_=n[t.pc+1];t.pc+=2;const d=t.registers[f];t.registers[_]=d!=null?Math.floor(Number(d)):null;break}case g.OP_MATH_CEIL:{const f=n[t.pc],_=n[t.pc+1];t.pc+=2;const d=t.registers[f];t.registers[_]=d!=null?Math.ceil(Number(d)):null;break}case g.OP_ADD:{const f=n[t.pc],_=n[t.pc+1],d=n[t.pc+2];t.pc+=3;const m=t.registers[f],I=t.registers[_];m==null||I===null||I===void 0?t.registers[d]=null:t.registers[d]=Number(m)+Number(I);break}case g.OP_SUB:{const f=n[t.pc],_=n[t.pc+1],d=n[t.pc+2];t.pc+=3;const m=t.registers[f],I=t.registers[_];m==null||I===null||I===void 0?t.registers[d]=null:t.registers[d]=Number(m)-Number(I);break}case g.OP_MUL:{const f=n[t.pc],_=n[t.pc+1],d=n[t.pc+2];t.pc+=3;const m=t.registers[f],I=t.registers[_];m==null||I===null||I===void 0?t.registers[d]=null:t.registers[d]=Number(m)*Number(I);break}case g.OP_DIV:{const f=n[t.pc],_=n[t.pc+1],d=n[t.pc+2];t.pc+=3;const m=t.registers[f],I=t.registers[_];if(m==null||I===null||I===void 0)t.registers[d]=null;else{const p=Number(I);t.registers[d]=p===0?null:Number(m)/p}break}case g.OP_MOD:{const f=n[t.pc],_=n[t.pc+1],d=n[t.pc+2];t.pc+=3;const m=t.registers[f],I=t.registers[_];if(m==null||I===null||I===void 0)t.registers[d]=null;else{const p=Number(I);t.registers[d]=p===0?null:Number(m)%p}break}case g.OP_STR_CONCAT:{const f=n[t.pc],_=n[t.pc+1],d=n[t.pc+2];t.pc+=3;let m="",I=!1;for(let p=0;p<_;p++){const T=t.registers[f+p];T!=null&&(I=!0,m+=String(T))}t.registers[d]=I?m:null;break}case g.OP_COALESCE:{const f=n[t.pc],_=n[t.pc+1],d=n[t.pc+2];t.pc+=3;let m=null;for(let I=0;I<_;I++){const p=t.registers[f+I];if(p!=null){m=p;break}}t.registers[d]=m;break}case g.OP_COPY:{const f=n[t.pc],_=n[t.pc+1];t.pc+=2,t.registers[_]=t.registers[f];break}case g.OP_AGG_INIT:{const f=n[t.pc],_=n[t.pc+1],d=n[t.pc+2],m=n[t.pc+3];if(t.pc+=4,m===0){if(t.arenaOffset+40960>t.maxQueryMemory)return t.status=C.ARENA_EXHAUSTED,C.ARENA_EXHAUSTED;t.arenaOffset+=40960;const T=io(1024);if(d===0){const U=us([]),B=U%1024;T[B].hash=U,T[B].keys=[],T[B].count=0,T[B].sum=0,T[B].min_val=1/0,T[B].max_val=-1/0,T[B].has_val=!1}t.aggregators[f]={mode:0,startKeyReg:_,numKeys:d,capacity:1024,occupiedCount:d===0?1:0,readIdx:0,buckets:T}}else t.aggregators[f]={mode:1,startKeyReg:_,numKeys:d,capacity:1,occupiedCount:0,readIdx:0,buckets:[]};break}case g.OP_AGG_STEP:{const f=n[t.pc],_=n[t.pc+1],d=n[t.pc+2],m=n[t.pc+3],I=n[t.pc+4];t.pc+=5;const p=t.aggregators[f];if(!p)return t.status=C.INVALID_BYTECODE,C.INVALID_BYTECODE;const T=[];for(let B=0;B<d;B++)T.push(t.registers[_+B]);const U=m===255?null:t.registers[m];if(p.mode===0){const B=us(T),F=B%p.capacity;let P=null;for(let w=0;w<p.capacity;w++){const O=(F+w)%p.capacity,D=p.buckets[O];if(D.hash===0){D.hash=B,D.keys=T.slice(),D.count=0,D.sum=0,D.min_val=1/0,D.max_val=-1/0,D.has_val=!1,p.occupiedCount++,P=D;break}else if(D.hash===B&&Dc(D.keys,T)){P=D;break}}if(!P)return t.status=C.ARENA_EXHAUSTED,C.ARENA_EXHAUSTED;if(I===0)(m===255||U!=null)&&P.count++;else if(I===1||I===2)U!=null&&(P.sum+=Number(U),P.has_val=!0);else if(I===3){if(U!=null){const w=Number(U);(!P.has_val||w<P.min_val)&&(P.min_val=w),P.has_val=!0}}else if(I===4&&U!=null){const w=Number(U);(!P.has_val||w>P.max_val)&&(P.max_val=w),P.has_val=!0}if(p.occupiedCount>.7*p.capacity){const O=p.capacity*2,D=O*40;if(t.arenaOffset+D>t.maxQueryMemory)return t.status=C.ARENA_EXHAUSTED,C.ARENA_EXHAUSTED;t.arenaOffset+=D;const v=p.buckets,Q=io(O);for(let A=0;A<v.length;A++){const N=v[A];if(N.hash!==0){const k=N.hash%O;for(let $=0;$<O;$++){const J=(k+$)%O;if(Q[J].hash===0){Q[J]=N;break}}}}p.capacity=O,p.buckets=Q}}break}case g.OP_AGG_NEXT:{const f=n[t.pc],_=n[t.pc+1],d=n[t.pc+2],m=s.getUint16(t.pc+3,!0);if(t.pc+=5,m>i)return t.status=C.INVALID_BYTECODE,C.INVALID_BYTECODE;const I=t.aggregators[f];if(!I)return t.status=C.INVALID_BYTECODE,C.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 T=0;T<p.keys.length;T++)t.registers[_+T]=p.keys[T];t.registers[d]=p.sum,t.registers[d+1]=p.count,t.registers[d+2]=p.has_val?p.min_val:null,t.registers[d+3]=p.has_val?p.max_val:null,t.pc=m;break}case g.OP_AGG_FINAL:{const f=n[t.pc],_=n[t.pc+1],d=n[t.pc+2],m=n[t.pc+3];t.pc+=4;const I=t.registers[f],p=Number(t.registers[_]??0);m===0?t.registers[d]=p:m===1?t.registers[d]=p>0?Number(I):null:m===2?t.registers[d]=p>0?Number(I)/p:null:(m===3||m===4)&&(t.registers[d]=t.registers[f]);break}case g.OP_REG_IS_NULL:{const f=n[t.pc],_=s.getUint16(t.pc+1,!0);if(t.pc+=3,_>i)return t.status=C.INVALID_BYTECODE,C.INVALID_BYTECODE;const d=t.registers[f];d==null&&(t.pc=_);break}case g.OP_REG_IS_NOT_NULL:{const f=n[t.pc],_=s.getUint16(t.pc+1,!0);if(t.pc+=3,_>i)return t.status=C.INVALID_BYTECODE,C.INVALID_BYTECODE;const d=t.registers[f];d!=null&&(t.pc=_);break}default:return t.status=C.INVALID_BYTECODE,C.INVALID_BYTECODE}}return t.status=C.DONE,C.DONE}const kc=new TextDecoder,co=new Uint8Array([87,69,66,68,66,0]),lo=new Uint32Array(256);let uo=0;function Gc(){if(!uo){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;lo[t]=e>>>0}uo=1}}function Ci(t,e=0){Gc();let n=4294967295;for(let s=0;s<4096;s++){const i=s>=28&&s<=31?0:t.getUint8(e+s);n=lo[(n^i)&255]^n>>>8}return(n^4294967295)>>>0}function Ao(t,e=0){zt(t,e,0,4096),t.setUint8(e+re+0,87),t.setUint8(e+re+1,69),t.setUint8(e+re+2,66),t.setUint8(e+re+3,68),t.setUint8(e+re+4,66),t.setUint8(e+re+5,0),t.setUint16(e+Ss,4096,!0),t.setUint16(e+Ns,Wn,!0),t.setUint16(e+Bs,hr,!0),t.setUint32(e+Kt,1,!0),t.setUint32(e+ee,0,!0),t.setUint32(e+oe,1,!0),t.setUint32(e+ae,0,!0),t.setUint32(e+ce,0,!0),t.setUint32(e+tr,0,!0),t.setUint32(e+er,0,!0);const n=Ci(t,e);t.setUint32(e+ce,n,!0)}function Oi(t,e=!1){for(let u=0;u<co.length;u++)if(t.getUint8(re+u)!==co[u])throw new Br("Invalid database file: magic bytes mismatch");const n=t.getUint16(Ss,!0),s=t.getUint16(Ns,!0),i=t.getUint16(Bs,!0),r=t.getUint32(Kt,!0),o=t.getUint32(ee,!0),a=t.getUint32(oe,!0),l=t.getUint32(ae,!0),c=t.getUint32(ce,!0);if(i>Wn)throw new Nr(`Database file format requires engine version >= ${i}, but running engine is version ${Wn}`);if(e&&c!==0){const u=Ci(t,0);if(u!==c)throw new Pe(1,c,u)}return{pageSize:n,fileFormatVersion:s,minReadVersion:i,totalPages:r,freePageHead:o,schemaVersion:a,changeCounter:l,storedChecksum:c}}function vc(t,e=0){return t.getUint32(e+Kt,!0)}function Mc(t,e,n){n===void 0&&(n=e,e=0),t.setUint32(e+Kt,n,!0)}function Wc(t,e=0){return t.getUint32(e+ee,!0)}function Hc(t,e,n){n===void 0&&(n=e,e=0),t.setUint32(e+ee,n,!0)}function fo(t,e=0){return t.getUint32(e+oe,!0)}function Sn(t,e=0){const n=fo(t,e)+1;return t.setUint32(e+oe,n,!0),n}function _o(t,e=0){return t.getUint32(e+ae,!0)}function Je(t,e=0){const n=_o(t,e)+1;return t.setUint32(e+ae,n,!0),n}function Ke(t,e=0){t.setUint32(e+ce,0,!0);const n=Ci(t,e);return t.setUint32(e+ce,n,!0),n}function As(t,e,n,s){let i=0;for(;i<s&&i<Jn(n);i++)t.setUint8(e+i,n.charCodeAt(i));for(;i<s;i++)t.setUint8(e+i,0)}function fs(t,e,n){const s=[];for(let i=0;i<n;i++){const r=t.getUint8(e+i);if(r===0)break;s.push(r)}return kc.decode(new Uint8Array(s))}function go(t){switch(t.toUpperCase()){case"INT32":return y.INT32;case"INT64":return y.INT64;case"FLOAT64":return y.FLOAT64;case"TEXT":return y.TEXT;case"BLOB":return y.BLOB;case"UUID":return y.UUID;case"ULID":return y.ULID;default:throw new Error(`Unsupported column data type: "${t}"`)}}function Ae(t,e){const n=An+e*Ue,s=t.getUint16(n+0,!0);if(s===0)return null;const i=t.getUint16(n+2,!0),r=t.getUint32(n+4,!0),o=t.getUint32(n+8,!0),a=fs(t,n+12,pe),l=t.getUint32(n+76,!0),c=t.getUint32(n+80,!0),u=t.getBigUint64(n+84,!0);return{tableId:s,columnCount:i,rootPageId:r,colCatalogPageId:o,name:a,flags:l,rowCountEstimate:c,autoIncNext:u}}function Si(t,e,n){const s=An+e*Ue;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),As(t,s+12,n.name,pe),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+Ue)}function Vc(t,e){const n=Re(t,e);return n!==-1?Ae(t,n):null}function Re(t,e){for(let n=0;n<Te;n++){const s=Ae(t,n);if(s&&s.flags&En.ACTIVE&&s.name===e)return n}return-1}function ho(t,e=0){for(let n=0;n<Te;n++){const s=e+An+n*Ue;if(t.getUint16(s,!0)===0)return n}return-1}function Nn(t){const e=[];for(let n=0;n<Te;n++){const s=Ae(t,n);s&&s.flags&En.ACTIVE&&e.push(s)}return e}function Bn(t,e){const n=fn+e*Ce,s=t.getUint16(n+0,!0);if(s===0)return null;const i=t.getUint16(n+2,!0),r=t.getUint32(n+4,!0),o=t.getUint8(n+8),a=t.getUint8(n+9),l=[];for(let E=0;E<8;E++)l.push(t.getUint16(n+10+E*2,!0));const c=[];for(let E=0;E<8;E++)c.push(t.getUint8(n+26+E));const u=fs(t,n+34,pe);return{indexId:s,tableId:i,rootPageId:r,columnCount:o,flags:a,columnIndices:l,colDirections:c,name:u}}function Ni(t,e,n){const s=fn+e*Ce;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 r=0;r<8;r++)t.setUint16(s+10+r*2,n.columnIndices[r]??0,!0);for(let r=0;r<8;r++)t.setUint8(s+26+r,n.colDirections[r]??0);As(t,s+34,n.name,pe),new Uint8Array(t.buffer,t.byteOffset).fill(0,s+98,s+Ce)}const _s=8;function Bi(t,e=0){for(let n=0;n<_s;n++){const s=e+fn+n*Ce;if(t.getUint16(s+0,!0)===0)return n}return-1}function Pi(t,e){const n=e.toLowerCase();for(let s=0;s<_s;s++){const i=Bn(t,s);if(i&&i.name.toLowerCase()===n)return{slotIdx:s,desc:i}}return null}function ze(t,e){const n=[];for(let s=0;s<_s;s++){const i=Bn(t,s);i&&i.tableId===e&&n.push(i)}return n}function wi(t,e,n){if(n===void 0&&(n=e,e=0),n>=_s)return-1;const s=e+fn+n*Ce;return zt(t,s,0,Ce),0}function Eo(t,e,n){if(n===void 0&&(n=e,e=0),n>=Te)return-1;const s=e+An+n*Ue;return zt(t,s,0,Ue),0}function mo(t,e,n,s,i=0){zt(t,e,0,4096),t.setUint8(e+0,dn),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 Qe(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,r){t.setUint8(e+0,dn),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,r,!0)}function Io(t,e,n,s){if(n<0||n>=ye)throw new Error(`Invalid catalog in-page slot ${n}`);const i=e+Ps+n*ws;t.setUint8(i+0,s.type),t.setUint8(i+1,s.flags),t.setUint16(i+2,s.colOffset,!0),As(t,i+4,s.name,pe),t.setUint32(i+68,0,!0)}function po(t,e,n){const s=e+Ps+n*ws,i=t.getUint8(s+0),r=t.getUint8(s+1),o=t.getUint16(s+2,!0),a=fs(t,s+4,pe);return{type:i,flags:r,colOffset:o,name:a}}function $c(t){return{pageChainIdx:Math.floor(t/ye),colIdxInPage:t%ye}}function To(t,e,n,s){var U,B,F,P;if(s.length===0)throw new Error("Table must have at least one column");if(s.length>_n)throw new zs(s.length,_n);if(Re(t,n)!==-1)throw new Ur(n);const i=ho(t);if(i===-1)throw new Or(Te,Te);const r=i+1,o=e.allocateNewPage(),a=e.getPageBytes(o),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(o);const c=[];let u=0;for(let w=0;w<s.length;w++){const O=s[w],D=typeof O.type=="string"?go(O.type):O.type;let v=0;typeof O.flags=="number"?v=O.flags:((O.primaryKey||(U=O.flags)!=null&&U.primaryKey)&&(v|=Ct.PRIMARY_KEY),(O.notNull||(B=O.flags)!=null&&B.notNull)&&(v|=Ct.NOT_NULL),(O.indexed||(F=O.flags)!=null&&F.indexed)&&(v|=Ct.INDEXED),(O.autoInc||(P=O.flags)!=null&&P.autoInc)&&(v|=Ct.AUTO_INC));const Q=u;switch(D){case y.INT32:u+=4;break;case y.INT64:case y.FLOAT64:u+=8;break;case y.UUID:case y.ULID:u+=16;break}c.push({type:D,flags:v,colOffset:Q,name:O.name})}const E=c.length,f=Math.ceil(E/ye),_=[];for(let w=0;w<f;w++)_.push(e.allocateNewPage());for(let w=0;w<f;w++){const O=_[w],D=w<f-1?_[w+1]:0,v=w*ye,Q=Math.min(E-v,ye),A=e.getPageBytes(O),N=new DataView(A.buffer,A.byteOffset);mo(N,0,r,v,D),N.setUint16(2,Q,!0);for(let $=0;$<Q;$++){const J=c[v+$];Io(N,0,$,J)}const k=qn(A);N.setUint32(12,k,!0),e.markPageDirty(O)}const d=_[0],m={tableId:r,columnCount:E,rootPageId:o,colCatalogPageId:d,name:n,flags:En.ACTIVE,rowCountEstimate:0,autoIncNext:1n};Si(t,i,m);const I=[];for(let w=0;w<c.length;w++)c[w].flags&Ct.PRIMARY_KEY&&I.push(c[w]);if(I.length>0){const w=Bi(t);if(w!==-1){const O=e.allocateNewPage(),D=e.getPageBytes(O),v=new DataView(D.buffer,D.byteOffset);os(v,0,0),e.markPageDirty(O);const Q=[0,0,0,0,0,0,0,0],A=[0,0,0,0,0,0,0,0];for(let k=0;k<I.length&&k<8;k++){const $=I[k].name;let J=-1;for(let K=0;K<c.length;K++)if(c[K].name===$){J=K;break}Q[k]=J}const N={indexId:w+1,tableId:r,rootPageId:O,columnCount:I.length,flags:Ut.PRIMARY|Ut.UNIQUE,columnIndices:Q,colDirections:A,name:`pk_${n}`};Ni(t,w,N)}}Sn(t),Je(t),Ke(t);const p=ze(t,r),T=[];for(let w=0;w<I.length;w++)T.push(I[w].name);return{...m,columns:c,primaryKey:T.length>0?T:void 0,indexes:p.length>0?p:void 0}}function Li(t,e,n){const s=Re(t,n);if(s===-1)throw new Vn(n);const i=Ae(t,s),r=[];let o=i.colCatalogPageId,a=0;for(;o!==0&&a<i.columnCount;){const u=e.getPageBytes(o),E=new DataView(u.buffer,u.byteOffset),f=Qe(E,0);for(let _=0;_<f.colCountInPage;_++){const d=po(E,0,_);r.push(d),a++}o=f.nextColCatalogPageId}const l=ze(t,i.tableId),c=[];for(let u=0;u<r.length;u++)r[u].flags&Ct.PRIMARY_KEY&&c.push(r[u].name);return{...i,columns:r,primaryKey:c.length>0?c:void 0,indexes:l.length>0?l:void 0}}function Yc(t,e){const n=Nn(t),s=[];for(let i=0;i<n.length;i++)s.push(Li(t,e,n[i].name));return s}const Fi="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 Pn=null;function yo(){if(!Pn){const t=globalThis.Buffer;if(typeof t<"u"&&typeof t.from=="function")Pn=new Uint8Array(t.from(Fi,"base64"));else{const e=atob(Fi),n=e.length;Pn=new Uint8Array(n);for(let s=0;s<n;s++)Pn[s]=e.charCodeAt(s)}}return Pn}function Uo(t,e){const n=e??yo(),s=new WebAssembly.Module(n),i=new WebAssembly.Instance(s,{env:{memory:t}}),r=i.exports,o=(l,c=0)=>l.byteOffset+c;return{instance:i,exports:r,memory:t,page_init:(l,c,u=Hn,E=0)=>{r.page_init(o(l,c),u,E)},page_init_free:(l,c,u=0)=>{r.page_init_free(o(l,c),u)},page_get_type:(l,c)=>r.page_get_type(o(l,c)),page_set_type:(l,c,u)=>{r.page_set_type(o(l,c),u)},page_get_cell_count:(l,c)=>r.page_get_cell_count(o(l,c)),page_set_cell_count:(l,c,u)=>{r.page_set_cell_count(o(l,c),u)},page_get_cell_content_offset:(l,c)=>r.page_get_cell_content_offset(o(l,c)),page_set_cell_content_offset:(l,c,u)=>{r.page_set_cell_content_offset(o(l,c),u)},page_get_next_page_id:(l,c)=>r.page_get_next_page_id(o(l,c)),page_set_next_page_id:(l,c,u)=>{r.page_set_next_page_id(o(l,c),u)},page_get_free_bytes:(l,c)=>r.page_get_free_bytes(o(l,c)),page_set_free_bytes:(l,c,u)=>{r.page_set_free_bytes(o(l,c),u)},page_get_checksum:(l,c)=>r.page_get_checksum(o(l,c)),page_set_checksum:(l,c,u)=>{r.page_set_checksum(o(l,c),u)},page_get_cell_offset:(l,c,u)=>r.page_get_cell_offset(o(l,c),u),page_set_cell_offset:(l,c,u,E)=>{r.page_set_cell_offset(o(l,c),u,E)},page_get_contiguous_free_space:(l,c)=>r.page_get_contiguous_free_space(o(l,c)),page_get_total_free_space:(l,c)=>r.page_get_total_free_space(o(l,c)),page_compact:(l,c,u=0,E)=>{E?Tn(l,c,u,E):r.page_compact(o(l,c),u,-1,0,0)},page_get_row_length:(l,c)=>r.page_get_row_length(o(l,c)),page_insert_row:(l,c,u,E=0)=>is(l,c,u,E),page_delete_row:(l,c,u)=>{r.page_delete_row(o(l,c),u)},page_update_row:(l,c,u,E,f=0)=>$r(l,c,u,E,f),page_table_hash:(l,c)=>r.page_table_hash(l,c),page_table_get:(l,c,u,E)=>r.page_table_get(o(l,c),u,E),page_table_set:(l,c,u,E,f)=>{if(r.page_table_set(o(l,c),u,E,f)<0)throw new Error(`BufferPool page table full: cannot insert page ${E}`)},page_table_delete:(l,c,u,E)=>r.page_table_delete(o(l,c),u,E)!==0,buf_pool_get_slot_offset:l=>r.buf_pool_get_slot_offset(l),buf_pool_read_slot_to_page:(l,c,u)=>r.buf_pool_read_slot_to_page(o(l,c),u),buf_pool_write_slot_to_page:(l,c,u,E)=>{r.buf_pool_write_slot_to_page(o(l,c),u,E)},buf_pool_get_resident_slot:(l,c,u,E)=>r.buf_pool_get_resident_slot(o(l,c),u,E),buf_pool_assign_slot:(l,c,u,E,f,_)=>{r.buf_pool_assign_slot(o(l,c),o(l,u),E,f,_)},buf_pool_unassign_slot:(l,c,u,E,f)=>{r.buf_pool_unassign_slot(o(l,c),o(l,u),E,f)},buf_pool_mark_dirty:(l,c,u)=>{r.buf_pool_mark_dirty(o(l,c),u)},buf_pool_clear_dirty:(l,c,u)=>{r.buf_pool_clear_dirty(o(l,c),u)},buf_pool_is_dirty:(l,c,u)=>r.buf_pool_is_dirty(o(l,c),u)!==0,buf_pool_pin_slot:(l,c)=>{Ii(l,c)},buf_pool_unpin_slot:(l,c)=>{pi(l,c)},buf_pool_is_pinned:(l,c)=>Ze(l,c),buf_pool_find_victim:(l,c,u,E,f,_)=>Ti(l,c,u,E,f,_),buf_pool_select_eviction_victim:(l,c,u,E,f,_,d,m)=>yi(l,c,u,E,f,_,d,m),catalog_init_page1:l=>{r.catalog_init_page1(o(l))},catalog_read_page1_header:(l,c)=>Oi(l,c),catalog_get_total_pages:l=>r.catalog_get_total_pages(o(l)),catalog_set_total_pages:(l,c)=>{r.catalog_set_total_pages(o(l),c)},catalog_get_free_page_head:l=>r.catalog_get_free_page_head(o(l)),catalog_set_free_page_head:(l,c)=>{r.catalog_set_free_page_head(o(l),c)},catalog_get_schema_version:l=>r.catalog_get_schema_version(o(l)),catalog_increment_schema_version:l=>r.catalog_increment_schema_version(o(l)),catalog_get_change_counter:l=>r.catalog_get_change_counter(o(l)),catalog_increment_change_counter:l=>r.catalog_increment_change_counter(o(l)),catalog_update_page1_checksum:l=>r.catalog_update_page1_checksum(o(l)),sql_like_match:(l,c)=>Un(l,c),fnv1a_32:l=>us(l),compare_sorter_keys:je,vm_step:On}}function Co(t=Oe,e=Se){const n=Fs(t,e),s=n.transientArenaOffset+256*1024,i=Math.ceil(s/65536),r=Math.ceil((n.transientArenaOffset+e)/65536);return new WebAssembly.Memory({initial:i,maximum:Math.max(i,r)})}class Oo{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,r;this.slotCount=e.slotCount??((s=e.pool)==null?void 0:s.slotCount)??Oe,this.maxQueryMemory=e.maxQueryMemory??((i=e.pool)==null?void 0:i.maxQueryMemory)??Se;const n=e.memory??((r=e.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=Fs(e.useDefaultLayoutOffsets?Oe: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 si({vfs:e.vfs,memory:this.wasmMemory});else throw new Error("BufferPoolDriver requires either an Io instance or IVfsAdapter");zt(this.uint8,this.slotToPageOffset,0,this.slotCount*4),zt(this.uint8,this.pageToSlotOffset,0,this.pageToSlotBuckets*le),zt(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),Gt(this.view,this.pageToSlotOffset,this.pageToSlotBuckets,e)}getAssignedPage(e){return this.validate_slot_idx(e),Ye(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}`);zr(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");xr(this.view,this.slotToPageOffset,this.pageToSlotOffset,this.pageToSlotBuckets,e),this.ref_bits[e]=0}markDirty(e){this.validate_slot_idx(e),to(this.uint8,this.dirtyMaskOffset,e),this.slot_dirty_generations[e]++}clearDirty(e){this.validate_slot_idx(e),eo(this.uint8,this.dirtyMaskOffset,e)}isDirty(e){return this.validate_slot_idx(e),mi(this.uint8,this.dirtyMaskOffset,e)}pinSlot(e){this.validate_slot_idx(e),Ii(this.pin_counts,e)}unpinSlot(e){this.validate_slot_idx(e),pi(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),Ze(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 xs;const s=this.transientArenaOffset+this.arena_offset;return this.arena_offset+=n,s}resetArena(){this.arena_offset>0&&(zt(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 o=await i;return n&&this.pinSlot(o),o}const r=(async()=>{const{candidate_slot:o,flush_page_id:a,next_clock_hand:l}=yi(this.buffer,this.ref_bits,this.pin_counts,this.slotToPageOffset,this.dirtyMaskOffset,this.slotCount,this.clock_hand,e);this.clock_hand=l,this.pinSlot(o);try{return await this.io.resolvePageFault(o,e,a),this.assignSlot(o,e),this.setRefBit(o,1),this.clearDirty(o),o}catch(c){throw o!==-1&&this.unpinSlot(o),c}})();this.in_flight_acquires.set(e,r);try{const o=await r;return n||this.unpinSlot(o),o}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=mt(n,ee),i=mt(n,Kt);if(s>0){if(s<=1||i>0&&s>i)throw new Pe(s,`Corrupted free_page_head pointer ${s} (totalPages: ${i})`);const l=await this.acquirePage(s,e),c=this.getSlotDataView(l),u=br(c,ji);if(u!==Be)throw new Pe(s,`Expected free page type 0x00, got 0x${u.toString(16)}`);const E=mt(c,Ji);if(E===s||i>0&&E>i)throw new Pe(s,`Corrupted next_free_page_id pointer ${E} in free page ${s}`);return It(n,ee,E),this.markDirty(0),pn(c,0),this.markDirty(l),s}const r=i+1;It(n,Kt,r),this.markDirty(0);const o=await this.acquirePage(r,e),a=this.getSlotDataView(o);return pn(a,0),this.markDirty(o),r})}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=mt(s,Kt);if(i>0&&e>i)throw new Error(`Cannot free page ${e} beyond total pages ${i}`);const r=this.getResidentSlot(e);if(r!==-1){if(n)this.forceUnpinSlot(r);else if(this.isSlotPinned(r))throw new Error(`Cannot free pinned/active database page ${e}`)}const o=await this.acquirePage(e,!0);try{const a=this.getSlotDataView(o),l=He(a,0);if(l===Be){if(this.unassignSlot(o),n)return;throw new Error(`Double-free detected: page ${e} is already marked free`)}if(!n&&l===dn)throw new Error(`Cannot free system catalog page ${e}`);const c=mt(s,ee);Vr(a,0,c),zt(this.uint8,o*4096+Jt,0,4096-Jt),this.io.isInTransaction()?await this.io.spillOrWriteSlot(o,e):await this.flushSlot(o),this.unassignSlot(o),this.clearDirty(o),this.setRefBit(o,0),It(s,ee,e),this.markDirty(0)}finally{this.unpinSlot(o)}})}async stepVm(e,n){let s=On(e,this.view,n);for(;s===C.PAGE_FAULT;){const i=e.cursor.pageId;await this.acquirePage(i),e.status=C.RUNNING,s=On(e,this.view,n)}return s}}async function Di(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{xn(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,r=new Set;let o=0;for(const u of s){const E=ai(u);if(!E.valid||!E.header)break;const{header:f}=E;if(f.frameSeq!==o+1)break;if(o++,i.has(f.txId)||i.set(f.txId,[]),f.frameType===Gn)r.add(f.txId);else if(f.frameType===kn||f.frameType===vn){const _=new Uint8Array(u.buffer,u.byteOffset+Ne,4096),d=new Uint8Array(4096);d.set(_),i.get(f.txId).push({pageId:f.pageId,data:d,frameType:f.frameType})}}const a=new Map;let l=0,c=0;for(const[u,E]of i.entries())if(r.has(u)){l++;for(const f of E)f.pageId>0&&a.set(f.pageId,f.data)}else c++;if(a.size>0){const u=[];for(const[E,f]of a.entries())u.push({pageId:E,data:f});u.sort((E,f)=>E.pageId-f.pageId),await t.writePages(u)}return await t.flush(),await t.truncateWal(0),{frameCount:o,committedTxCount:l,abortedTxCount:c,replayedPageCount:a.size}}class So{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 r=await e();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 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 No{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 So(i,()=>this.syncCrossTabState())}setOnCrossTabInvalidated(e){this.onCrossTabInvalidated=e}recordDiskPage1State(){const e=this.pool.getSlotDataView(0);this.lastDiskChangeCounter=e.getUint32(ae,!0),this.lastDiskSchemaVersion=e.getUint32(oe,!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(){if(!this.queue.hasWebLocks())return;const e=await this.vfs.getWalFrameCount();let n=!1;if(e>0){const i=await this.vfs.readWalHeader();let r=0;if(i)try{r=xn(i,!0).salt1}catch{r=0}(r!==this.instanceSalt||e!==this.expectedWalFrameCount)&&(n=!0,await Di(this.vfs),this.committedWalPages.clear(),this.walFrameSeq=0,this.txCommitCount=0,this.expectedWalFrameCount=0)}else this.expectedWalFrameCount>0&&(n=!0,this.committedWalPages.clear(),this.walFrameSeq=0,this.txCommitCount=0,this.expectedWalFrameCount=0);const s=await this.vfs.readPage(1);if(s){const i=new DataView(s.buffer,s.byteOffset,s.byteLength),r=i.getUint32(ae,!0),o=i.getUint32(oe,!0);(n||r!==this.lastDiskChangeCounter||o!==this.lastDiskSchemaVersion)&&await this.reloadFromDisk(s,r,o)}}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(ae,!0),this.lastDiskSchemaVersion=s.getUint32(oe,!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(ue);i.set(s),this.spilledPages.set(n,i);const r=this.pool.getSlotDataView(0).getUint32(Kt,!0),o=ts({frameType:vn,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 e=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),l=new Uint8Array(this.pool.getPageBytesInSlot(r));n.set(r,{pageId:o,dirty:a,data:l})}}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: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=xn(s,!0).salt1===this.instanceSalt}catch{i=!1}i||await this.vfs.writeWalHeader(ri({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,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(Kt,!0);for(const[o,a]of this.spilledPages.entries())this.committedWalPages.set(o,a);for(let o=0;o<this.pool.slotCount;o++)if(this.pool.isDirty(o)){const a=this.pool.getAssignedPage(o);if(a>0){this.io.stampSlotChecksum(o,a);const l=this.pool.getPageBytesInSlot(o),c=new Uint8Array(ue);c.set(l),this.committedWalPages.set(a,c),this.pool.clearDirty(o),s.push(ts({frameType:kn,flags:0,txId:n,pageId:a,dbSizePages:i,frameSeq:++this.walFrameSeq},c))}}s.push(ts({frameType:Gn,flags:0,txId:n,pageId:0,dbSizePages:i,frameSeq:++this.walFrameSeq})),await this.vfs.appendWalFrames(s),await this.vfs.flushWal();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(e),this.scheduleIdleTimer(),(r>=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 o=await this.vfs.readWalFrames(0,e),a=new Map,l=new Set;for(const c of o){const u=ai(c);if(!u.valid||!u.header)break;const{frameType:E,txId:f,pageId:_}=u.header;if(a.has(f)||a.set(f,[]),E===Gn)l.add(f);else if(E===kn||E===vn){const d=new Uint8Array(c.buffer,c.byteOffset+Ne,ue),m=new Uint8Array(ue);m.set(d),a.get(f).push({pageId:_,data:m})}}for(const[c,u]of a.entries())if(l.has(c))for(const E of u)E.pageId>0&&n.set(E.pageId,E.data)}for(const[o,a]of this.committedWalPages.entries())n.set(o,a);const s=new Map;for(let o=0;o<this.pool.slotCount;o++)if(this.pool.isDirty(o)){const a=this.pool.getAssignedPage(o);if(a>0){this.io.stampSlotChecksum(o,a);const l=this.pool.getPageBytesInSlot(o),c=new Uint8Array(ue);c.set(l),s.set(a,{slotIdx:o,data:c})}}const i=new Set([...n.keys(),...s.keys()]),r=[];for(const o of i)if(s.has(o)){const{slotIdx:a,data:l}=s.get(o);r.push({pageId:o,data:l}),this.pool.clearDirty(a)}else r.push({pageId:o,data:n.get(o)});return r.length>0&&(r.sort((o,a)=>o.pageId-a.pageId),await this.vfs.writePages(r)),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(ri({checkpointSeq:this.checkpointSeq,salt1:this.instanceSalt})),{pagesWritten:r.length}}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 Bo=new Set(["count","sum","avg","min","max"]),Po=new Set(["upper","lower","length","substr","trim","abs","round","floor","ceil","concat","coalesce"]);function fe(t){return Bo.has(t.toLowerCase())}function wo(t){return Po.has(t.toLowerCase())}function Zc(t){return fe(t)||wo(t)}function be(t,e){if(e==="where"){if(t.type==="fn"&&fe(t.name))throw new Yn(t.name);if(t.type==="binary"&&(be(t.left,e),be(t.right,e)),t.type==="fn")for(const n of t.args)be(n,e)}}function qc(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 r=n;let o=!1;for(;n<s&&(/[0-9]/.test(t[n])||t[n]==="."&&!o);)t[n]==="."&&(o=!0),n++;e.push({type:"NUMBER",value:t.slice(r,n),pos:r});continue}if(i==="'"||i==='"'){const r=i,o=n;n++;let a="";for(;n<s&&t[n]!==r;)t[n]==="\\"&&n+1<s&&n++,a+=t[n],n++;n<s&&t[n]===r&&n++,e.push({type:"STRING",value:a,pos:o});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 r=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 o=t.slice(r,n);e.push({type:"IDENT",value:o,pos:r});continue}n++}return e.push({type:"EOF",value:"",pos:s}),e}class jc{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 r=this.parse(i);n={type:"binary",op:s.value,left:n,right:r}}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 at(t){const e=t.trim();if(!e)throw new Error("Cannot parse empty expression");const n=qc(e);return new jc(n).parse(0)}function Jc(t){let e=0,n=null;const s=t.length;for(let i=0;i<s;i++){const r=t[i];if(n){r===n&&t[i-1]!=="\\"&&(n=null);continue}if(r==="'"||r==='"'){n=r;continue}if(r==="("){e++;continue}if(r===")"){e--;continue}if(e===0&&(r===" "||r===" ")&&i+4<s&&t.slice(i+1,i+3).toLowerCase()==="as"&&/\s/.test(t[i+3])){const o=t.slice(0,i).trim(),a=t.slice(i+4).trim();return{exprStr:o,explicitAlias:a}}}return{exprStr:t.trim()}}function Yt(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 gs(t){const{exprStr:e,explicitAlias:n}=Jc(t),s=at(e),i=n&&n.length>0?n:Yt(s);return{expr:s,alias:i}}class nt{constructor(e){S(this,"node");this.node=e}add(e){return new nt({type:"binary",op:"+",left:this.node,right:Wt(e)})}sub(e){return new nt({type:"binary",op:"-",left:this.node,right:Wt(e)})}mul(e){return new nt({type:"binary",op:"*",left:this.node,right:Wt(e)})}div(e){return new nt({type:"binary",op:"/",left:this.node,right:Wt(e)})}mod(e){return new nt({type:"binary",op:"%",left:this.node,right:Wt(e)})}eq(e){return new nt({type:"binary",op:"=",left:this.node,right:Wt(e)})}ne(e){return new nt({type:"binary",op:"!=",left:this.node,right:Wt(e)})}lt(e){return new nt({type:"binary",op:"<",left:this.node,right:Wt(e)})}lte(e){return new nt({type:"binary",op:"<=",left:this.node,right:Wt(e)})}gt(e){return new nt({type:"binary",op:">",left:this.node,right:Wt(e)})}gte(e){return new nt({type:"binary",op:">=",left:this.node,right:Wt(e)})}as(e){return{expr:this.node,alias:e}}}function Wt(t){return t===null?{type:"literal",value:null}:typeof t=="boolean"?{type:"literal",value:t}:t instanceof nt?t.node:typeof t=="number"?{type:"literal",value:t}:typeof t=="string"?{type:"literal",value:t}:t}function Ri(t){return new nt({type:"col",name:t})}function Lo(t){return new nt(at(t))}const Kc=Lo;function St(t,e){return new nt({type:"fn",name:t.toLowerCase(),args:e.map(n=>typeof n=="string"&&!n.startsWith("'")?Ri(n).node:Wt(n))})}const Fo=(t,...e)=>St(t,e),zc={upper:t=>St("upper",[t]),lower:t=>St("lower",[t]),length:t=>St("length",[t]),substr:(t,e,n)=>{const s=[t,e];return n!==void 0&&s.push(n),St("substr",s)},trim:t=>St("trim",[t]),abs:t=>St("abs",[t]),round:t=>St("round",[t]),floor:t=>St("floor",[t]),ceil:t=>St("ceil",[t]),count:t=>St("count",[t??Ri("*").node]),sum:t=>St("sum",[t]),avg:t=>St("avg",[t]),min:t=>St("min",[t]),max:t=>St("max",[t]),concat:(...t)=>St("concat",t),coalesce:(...t)=>St("coalesce",t)};for(const[t,e]of Object.entries(zc))Object.defineProperty(Fo,t,{value:e,writable:!0,enumerable:!0,configurable:!0});const xc=Fo;function wn(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=wn(t.left,e,n),i=wn(t.right,e,n);if(s===null||i===null||s===void 0||i===void 0)return null;const r=Number(s),o=Number(i);switch(t.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=t.name.toLowerCase();if(fe(s)){if(e[s]!==void 0)return e[s];const r=t.args[0];if(r&&r.type==="col"){const o=`${s}_${r.name}`;if(e[o]!==void 0)return e[o]}return null}const i=t.args.map(r=>wn(r,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 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?Un(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 ti(s)}}}}}const xe=.5,hs=.05,ne=.02;function Do(t){const e=[];function n(i){if(i.colName&&e.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&&e.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(t),e}function tn(t,e){const n=Do(t),s=new Set;for(const i of n){const r=lt(i,e);r&&s.add(r.tableIdx)}return s}function Qi(t,e){var s,i;const n=Math.max(1,e.rowCountEstimate||10);if(t.type==="cmp"){const r=t.op??"=";if(r==="="){const o=(s=t.colName)==null?void 0:s.toLowerCase(),a=e.columns.findIndex(l=>l.name.toLowerCase()===o);if(a!==-1&&e.indexes){for(const l of e.indexes)if(l.columnCount===1&&l.columnIndices[0]===a)return(l.flags&(Ut.PRIMARY|Ut.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(t.type==="in"){const r=Math.max(1,((i=t.values)==null?void 0:i.length)||1);return Math.min(1,r*.05)}return t.type==="null"?t.isNull?.05:.95:.2}function se(t,e,n,s){var E;const i=Math.max(1,t.rowCountEstimate||10);let r=1;for(const f of e)r*=Qi(f,t);const o=Math.max(1,Math.round(i*r)),a=n!==void 0&&n.length>0,l=a&&o>1?o*Math.log2(o)*ne:0,c=Ts(t,e,e,n);if(c){const f=c.scanType==="point",_=c.scanType==="multi_point",d=c.satisfiesOrderBy===!0,m=d&&s!==void 0&&s>0?Math.min(s,o):o;let I=xe;return f?(I+=1*ne,{cost:I,rows:1,scanType:"IndexScan",indexName:c.index.name,isOrderSatisfied:!0,sortCostAvoided:a?l:void 0}):_?(I=(((E=c.inValues)==null?void 0:E.length)||1)*xe+m*ne,!d&&a&&(I+=l),{cost:I,rows:m,scanType:"IndexScan",indexName:c.index.name,isOrderSatisfied:d,sortCostAvoided:d?l:void 0}):(I+=m*hs+m*ne,!d&&a&&(I+=l),{cost:I,rows:m,scanType:"IndexScan",indexName:c.index.name,isOrderSatisfied:d,sortCostAvoided:d?l:void 0})}let u=i*ne;return a&&(u+=l),{cost:u,rows:o,scanType:"TableScan",isOrderSatisfied:!1}}function Ln(t,e){if(!t.indexes||t.indexes.length===0)return null;const n=t.columns.findIndex(r=>r.name.toLowerCase()===e.toLowerCase());if(n===-1)return null;let s=null,i=999;for(const r of t.indexes)if(r.columnCount===1&&r.columnIndices[0]===n){const o=(r.flags&Ut.PRIMARY)!==0,a=(r.flags&Ut.UNIQUE)!==0,l=o?1:a?2:3;l<i&&(i=l,s={index:r,isUnique:o||a})}return s}function ds(t,e){const n=e.length,s=[],i=Array.from({length:n},()=>new Set);if(!t.joinedTables)return{edges:s,dependencies:i};for(let r=0;r<t.joinedTables.length;r++){const o=t.joinedTables[r],a=r+1,l=lt(o.leftCol,e),c=lt(o.rightCol,e);if(l&&c&&(s.push({tableA:l.tableIdx,tableB:c.tableIdx,colA:l.col.name,colB:c.col.name,op:o.op,type:o.type,declaredRightTable:a}),o.type==="left")){const u=l.tableIdx===a?c.tableIdx:l.tableIdx;i[a].add(u)}}return{edges:s,dependencies:i}}function Fn(t,e){if(t.selectExprs&&t.selectExprs.length>0)return t.selectExprs;const n=new Set,s=new Set;for(const r of e)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 e)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 Es(t,e,n,s){const i=t.length,r=[];for(let o=1;o<i;o++){const a=t[o],l=e[a],c=t.slice(0,o),u=n.find(m=>m.tableA===a&&c.includes(m.tableB)||m.tableB===a&&c.includes(m.tableA));let E,f,_="=",d="inner";if(u)_=u.op,d=u.type,u.tableA===a?(f=`${l.name}.${u.colA}`,E=`${e[u.tableB].name}.${u.colB}`):(f=`${l.name}.${u.colB}`,E=`${e[u.tableA].name}.${u.colA}`);else{const m=s==null?void 0:s.find(I=>I.table.name===l.name);E=m?m.leftCol:`${e[t[0]].name}.id`,f=m?m.rightCol:`${l.name}.id`,_=m?m.op:"=",d=m?m.type:"inner"}r.push({type:d,table:l,cursor:o,leftCol:E,op:_,rightCol:f})}return r}function bi(t,e,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=lt(o,n);if(!a&&i){const l=i.find(c=>c.alias===o);l&&l.expr.type==="col"&&(a=lt(l.expr.name,n))}if(!a||a.tableIdx!==e)return!1}return!0}function ki(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 r=t.colName.toLowerCase(),o=r.includes(".")?r.slice(r.lastIndexOf(".")+1):r;for(const a of e){const l=a.columns.find(c=>c.name.toLowerCase()===o);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 Gi(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 E of t)E.type==="and"&&Array.isArray(E.children)?s.push(...E.children):s.push(E);const i=new Map,r=[];for(const E of s)if(E.colName){const f=E.colName.toLowerCase();i.has(f)||i.set(f,[]),i.get(f).push(E)}else r.push(E);for(const[E,f]of i.entries()){const _=tl(f);if(_)return{filters:[],isAlwaysFalse:!0,isAlwaysTrue:!1,metrics:{originalCount:n,optimizedCount:0,isAlwaysFalse:!0,isAlwaysTrue:!1,contradictionReason:`Contradiction on column "${E}": ${_}`,eliminatedFiltersCount:n,reordered:!1}}}const o=[];let a=0;for(const[,E]of i.entries()){const f=el(E);a+=E.length-f.length,o.push(...f)}o.push(...r);const l=o.map(E=>vi(E)).join("|");o.sort((E,f)=>{const _=ki(E,e),d=ki(f,e);return _-d});const c=o.map(E=>vi(E)).join("|"),u=l!==c;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 tl(t){let e=!1,n=!1;const s=[];let i=null,r=null,o=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==="<"?(!r||c<r.val||c===r.val&&!r.strict)&&(r={val:c,strict:!0}):l==="<="&&(!r||c<r.val)&&(r={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(!o)o=l;else{const c=new Set([...o].filter(u=>l.has(u)));if(c.size===0)return"Mutually exclusive IN lists with no common values";o=c}}}if(e&&n)return"Conflicting IS NULL and IS NOT NULL";if(e&&(s.length>0||i||r))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||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 el(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 r=null,o=null;for(const a of t)if(a.type==="cmp"&&typeof a.value=="number"){const l=a.op??"=",c=a.value;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}):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})}for(const a of t){const l=vi(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(r&&a!==r.filter)continue}else if((c==="<"||c==="<=")&&o&&a!==o.filter)continue}n.add(l),e.push(a)}}return e}function vi(t){return`${t.type}:${t.colName??""}:${t.isNull??""}:${t.op??""}:${String(t.value??"")}:${t.notIn??""}:${JSON.stringify(t.values??"")}`}function Ro(t,e){const n=[...t],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),l=i(o);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),E=i(c.colName);if(u===a||E===a||u===l)return c.value}};for(const o of e){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 l=r(o.rightCol);l!==void 0&&n.push({type:"cmp",colName:o.leftCol,op:"=",value:l})}}return n}class ms{constructor(e){S(this,"name","cost");S(this,"indexSeekCost");S(this,"indexNextCost");S(this,"rowEvalCost");this.indexSeekCost=(e==null?void 0:e.indexSeekCost)??xe,this.indexNextCost=(e==null?void 0:e.indexNextCost)??hs,this.rowEvalCost=(e==null?void 0:e.rowEvalCost)??ne}optimize(e){var Q,A;const n=[e.table,...((Q=e.joinedTables)==null?void 0:Q.map(N=>N.table))??[]],s=n.length,i=Gi(e.filters,n);if(i.isAlwaysFalse)return{plan:{...e,filters:[]},orderedTables:n,metrics:null,isAlwaysFalse:!0,whereMetrics:i.metrics};let r=i.filters,o=i.metrics;if(e.joinedTables&&e.joinedTables.length>0){const N=Ro(r,e.joinedTables);if(N.length>r.length){const k=Gi(N,n);if(k.isAlwaysFalse)return{plan:{...e,filters:[]},orderedTables:n,metrics:null,isAlwaysFalse:!0,whereMetrics:k.metrics};r=k.filters,o=k.metrics}}if(s<=1||!e.joinedTables||e.joinedTables.length===0){const N=new Map;N.set(0,r);const k=se(e.table,r,e.orderBy,e.limit);return{plan:{...e,filters:r},orderedTables:[e.table],metrics:{totalCost:k.cost,estimatedRows:k.rows,joinOrder:[e.table.name],singleTableFilters:N,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),l=en(a),c=new Map,u=[];for(let N=0;N<s;N++)c.set(N,[]);for(const N of l){const k=tn(N,n);if(k.size===1){const $=k.values().next().value;$!==void 0&&((A=c.get($))==null||A.push(N))}else u.push(N)}if(s<=1||!e.joinedTables||e.joinedTables.length===0){const N=se(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:E,dependencies:f}=ds(e,n),_=new Map;for(let N=0;N<s;N++)if(f[N].size===0){const k=bi(n[N],N,n,e.orderBy,e.selectExprs),$=k?e.orderBy.map(M=>{const W=M.colName??"",jt=W.includes(".")?W.slice(W.lastIndexOf(".")+1):W;return{...M,colName:jt}}):void 0,J=se(n[N],c.get(N)??[],$,k?e.limit:void 0),K=1<<N;_.set(K,{order:[N],cost:J.cost,rows:J.rows,scanTypes:[J.scanType],indexNames:[J.indexName],edgesUsed:[],isOrderSatisfied:J.isOrderSatisfied,sortCostAvoided:J.sortCostAvoided})}const d=1<<s;for(let N=2;N<=s;N++)for(let k=1;k<d;k++)if(nl(k)===N)for(let $=0;$<s;$++){if(!(k&1<<$))continue;const J=k^1<<$,K=_.get(J);if(!K)continue;let M=!0;for(const he of f[$])if(!(J&1<<he)){M=!1;break}if(!M)continue;const W=this.evaluateJoinStep(K.rows,n[$],$,E,K.order,c.get($)??[]),jt=K.cost+W.stepCost,gt=_.get(k);let ut=!1,nn=jt,sn=gt?gt.cost:0;const rn=K.isOrderSatisfied===!0,ke=(gt==null?void 0:gt.isOrderSatisfied)===!0;if(N===s&&e.orderBy&&e.orderBy.length>0&&(!rn&&W.newRows>1&&(nn+=W.newRows*Math.log2(W.newRows)*this.rowEvalCost),gt&&!ke&>.rows>1&&(sn+=gt.rows*Math.log2(gt.rows)*this.rowEvalCost)),!gt)ut=!0;else if(rn&&!ke)ut=!0;else if(!rn&&ke)ut=!1;else{const he=K.scanTypes.filter(de=>de==="IndexScan").length+(W.scanType==="IndexScan"?1:0),Qn=gt.scanTypes.filter(de=>de==="IndexScan").length;if(he>Qn&&nn<=sn*1.2)ut=!0;else if(he<Qn)ut=!1;else if(nn<sn*.75)ut=!0;else if(sn<nn*.75)ut=!1;else{const de=K.order[0]===0,on=gt.order[0]===0;if(de&&!on)ut=!0;else if(!de&&on)ut=!1;else{const xt=K.order.filter(an=>an>$).length,Cs=gt.order.filter((an,Os)=>an>Os).length;xt<Cs&&(ut=!0)}}}ut&&_.set(k,{order:[...K.order,$],cost:jt,rows:W.newRows,scanTypes:[...K.scanTypes,W.scanType],indexNames:[...K.indexNames,W.indexName],edgesUsed:[...K.edgesUsed,W.matchedEdge],isOrderSatisfied:K.isOrderSatisfied,sortCostAvoided:K.sortCostAvoided})}const m=(1<<s)-1,I=_.get(m);let p,T,U,B,F;I?(p=I.order,T=I.cost,U=I.rows,B=I.scanTypes,F=I.indexNames):(p=Array.from({length:s},(N,k)=>k),T=999999,U=100,B=Array.from({length:s},()=>"TableScan"),F=Array.from({length:s},()=>{}));const P=p.map(N=>n[N]),w=Es(p,n,E,e.joinedTables),O=Fn(e,n),D=(I==null?void 0:I.isOrderSatisfied)===!0,v=D&&e.orderBy&&e.orderBy.length>0&&U>1?U*Math.log2(U)*this.rowEvalCost:void 0;return{plan:{...e,table:P[0],joinedTables:w,selectExprs:O,filters:r,isOrderSatisfied:D},orderedTables:P,metrics:{totalCost:T,estimatedRows:U,joinOrder:P.map(N=>N.name),singleTableFilters:c,crossFilters:u,tableScanTypes:B,tableIndexNames:F,isOrderSatisfied:D,sortCostAvoided:v},isAlwaysFalse:!1,isAlwaysTrue:o.isAlwaysTrue,whereMetrics:o,isOrderSatisfied:D,sortCostAvoided:v}}evaluateJoinStep(e,n,s,i,r,o){const a=Math.max(1,n.rowCountEstimate||10);let l=1;for(const _ of o)l*=Qi(_,n);const c=[];for(const _ of i)if(_.tableA===s&&r.includes(_.tableB)){const d=Ln(n,_.colA);c.push({edge:_,nextCol:_.colA,outerCol:_.colB,idxMatch:d})}else if(_.tableB===s&&r.includes(_.tableA)){const d=Ln(n,_.colB);c.push({edge:_,nextCol:_.colB,outerCol:_.colA,idxMatch:d})}if(c.length===0){const _=e*(2+a*.1),d=Math.max(1,Math.round(e*a*l)),m={tableA:r[0],tableB:s,colA:"",colB:"",op:"=",type:"inner",declaredRightTable:s};return{stepCost:_,newRows:d,scanType:"TableScan",matchedEdge:m}}c.sort((_,d)=>{const m=_.idxMatch?_.idxMatch.isUnique?1:2:3,I=d.idxMatch?d.idxMatch.isUnique?1:2:3;return m-I});const u=c[0];if(u.idxMatch&&u.idxMatch.isUnique){const _=this.indexSeekCost+1*this.rowEvalCost,d=e*_,m=Math.max(1,Math.round(e*l));return{stepCost:d,newRows:m,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))),d=this.indexSeekCost+_*this.indexNextCost,m=e*d,I=Math.max(1,Math.round(e*_*l));return{stepCost:m,newRows:I,scanType:"IndexScan",indexName:u.idxMatch.index.name,matchedEdge:u.edge}}const E=e*(2+a*.1),f=Math.max(1,Math.round(e*Math.max(1,Math.round(a*.1))*l));return{stepCost:E,newRows:f,scanType:"TableScan",matchedEdge:u.edge}}}function nl(t){let e=0,n=t;for(;n>0;)e+=n&1,n>>=1;return e}class Qo{constructor(){S(this,"name","heuristic")}optimize(e){var O,D,v;const n=[e.table,...((O=e.joinedTables)==null?void 0:O.map(Q=>Q.table))??[]],s=n.length,i=Zt(e.filters),r=en(i),o=new Map,a=[];for(let Q=0;Q<s;Q++)o.set(Q,[]);for(const Q of r){const A=tn(Q,n);if(A.size===1){const N=A.values().next().value;N!==void 0&&((D=o.get(N))==null||D.push(Q))}else a.push(Q)}if(s<=1||!e.joinedTables||e.joinedTables.length===0){const Q=se(n[0],o.get(0)??[],e.orderBy,e.limit);return{plan:e,orderedTables:n,metrics:{totalCost:Q.cost,estimatedRows:Q.rows,joinOrder:[n[0].name],singleTableFilters:o,crossFilters:a,tableScanTypes:[Q.scanType],tableIndexNames:[Q.indexName],isOrderSatisfied:Q.isOrderSatisfied,sortCostAvoided:Q.sortCostAvoided},isOrderSatisfied:Q.isOrderSatisfied,sortCostAvoided:Q.sortCostAvoided}}const{edges:l,dependencies:c}=ds(e,n),u=n.map((Q,A)=>{const N=bi(Q,A,n,e.orderBy,e.selectExprs),k=N?e.orderBy.map($=>{const J=$.colName??"",K=J.includes(".")?J.slice(J.lastIndexOf(".")+1):J;return{...$,colName:K}}):void 0;return se(Q,o.get(A)??[],k,N?e.limit:void 0)}),E=[];for(let Q=0;Q<s;Q++)c[Q].size===0&&E.push(Q);E.sort((Q,A)=>{const N=u[Q].isOrderSatisfied?1:0,k=u[A].isOrderSatisfied?1:0;if(N!==k)return k-N;if(u[Q].rows!==u[A].rows)return u[Q].rows-u[A].rows;const $=u[Q].scanType==="IndexScan"?1:0,J=u[A].scanType==="IndexScan"?1:0;return $!==J?J-$:Q===0?-1:A===0?1:Q-A});const f=E[0]??0,_=[f],d=[u[f].scanType],m=[u[f].indexName];let I=u[f].cost,p=u[f].rows;const T=new Set;for(let Q=0;Q<s;Q++)Q!==f&&T.add(Q);for(;T.size>0;){const Q=[];for(const N of T){let k=!0;for(const M of c[N])if(!_.includes(M)){k=!1;break}if(!k)continue;const $=n[N],J=Math.max(1,$.rowCountEstimate||10);let K=null;for(const M of l)if(M.tableA===N&&_.includes(M.tableB)){const W=Ln($,M.colA);W&&(!K||W.isUnique)&&(K={isUnique:W.isUnique,indexName:W.index.name})}else if(M.tableB===N&&_.includes(M.tableA)){const W=Ln($,M.colB);W&&(!K||W.isUnique)&&(K={isUnique:W.isUnique,indexName:W.index.name})}if(K)if(K.isUnique){const M=xe+1*ne;Q.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(J/20))),W=xe+M*hs;Q.push({tableIdx:N,rank:2,stepCost:p*W,newRows:Math.max(1,p*M),scanType:"IndexScan",indexName:K.indexName})}else Q.push({tableIdx:N,rank:3,stepCost:p*(2+J*.1),newRows:Math.max(1,p*Math.max(1,Math.round(J*.1))),scanType:"TableScan"})}if(Q.length===0){const N=T.values().next().value;if(N===void 0)break;_.push(N),d.push("TableScan"),m.push(void 0),T.delete(N);continue}Q.sort((N,k)=>N.rank!==k.rank?N.rank-k.rank:Math.abs(N.stepCost-k.stepCost)>.05?N.stepCost-k.stepCost:N.tableIdx-k.tableIdx);const A=Q[0];_.push(A.tableIdx),d.push(A.scanType),m.push(A.indexName),I+=A.stepCost,p=A.newRows,T.delete(A.tableIdx)}const U=_.map(Q=>n[Q]),B=Es(_,n,l,e.joinedTables),F=Fn(e,n),P=((v=u[f])==null?void 0:v.isOrderSatisfied)===!0,w=P&&e.orderBy&&e.orderBy.length>0&&p>1?p*Math.log2(p)*ne:void 0;return{plan:{...e,table:U[0],joinedTables:B,selectExprs:F,isOrderSatisfied:P},orderedTables:U,metrics:{totalCost:I,estimatedRows:p,joinOrder:U.map(Q=>Q.name),singleTableFilters:o,crossFilters:a,tableScanTypes:d,tableIndexNames:m,isOrderSatisfied:P,sortCostAvoided:w},isOrderSatisfied:P,sortCostAvoided:w}}}class bo{constructor(){S(this,"name","noop")}optimize(e){var d,m;const n=[e.table,...((d=e.joinedTables)==null?void 0:d.map(I=>I.table))??[]],s=n.length,i=Zt(e.filters),r=en(i),o=new Map,a=[];for(let I=0;I<s;I++)o.set(I,[]);for(const I of r){const p=tn(I,n);if(p.size===1){const T=p.values().next().value;T!==void 0&&((m=o.get(T))==null||m.push(I))}else a.push(I)}const l=se(n[0],o.get(0)??[]),c=[l.scanType],u=[l.indexName];let E=l.cost;const f=l.rows;if(e.joinedTables)for(let I=1;I<s;I++){const p=e.joinedTables[I-1],T=ys(p,n[I],I,n,I);T?(c.push("IndexScan"),u.push(T.index.name),E+=f*.55):(c.push("TableScan"),u.push(void 0),E+=f*(2+(n[I].rowCountEstimate||10)*.1))}const _=Fn(e,n);return{plan:{...e,selectExprs:_},orderedTables:n,metrics:{totalCost:E,estimatedRows:f,joinOrder:n.map(I=>I.name),singleTableFilters:o,crossFilters:a,tableScanTypes:c,tableIndexNames:u}}}}class sl{constructor(e){S(this,"name","custom-order");S(this,"orderSpec");this.orderSpec=e}optimize(e){var F,P,w;const n=[e.table,...((F=e.joinedTables)==null?void 0:F.map(O=>O.table))??[]],s=n.length,i=e.joinedTables!==void 0&&e.joinedTables.length>0,r=Zt(e.filters),o=en(r),a=new Map,l=[];for(let O=0;O<s;O++)a.set(O,[]);for(const O of o){const D=tn(O,n);if(D.size===1){const v=D.values().next().value;v!==void 0&&((P=a.get(v))==null||P.push(O))}else l.push(O)}if(!i||s<=1){const O=se(n[0],a.get(0)??[]);return{plan:e,orderedTables:n,metrics:{totalCost:O.cost,estimatedRows:O.rows,joinOrder:[n[0].name],singleTableFilters:a,crossFilters:l,tableScanTypes:[O.scanType],tableIndexNames:[O.indexName]}}}const c=Array.from({length:s},(O,D)=>D);if(this.orderSpec){if(typeof this.orderSpec=="function"){const O=this.orderSpec;c.sort((D,v)=>O(n[D],n[v]))}else if(Array.isArray(this.orderSpec)){const O=this.orderSpec;c.sort((D,v)=>{const Q=n[D].name,A=n[v].name,N=O.indexOf(Q),k=O.indexOf(A),$=N===-1?9999:N,J=k===-1?9999:k;return $!==J?$-J:D-v})}}const{edges:u}=ds(e,n),E=c.map(O=>n[O]),f=Es(c,n,u,e.joinedTables),_=Fn(e,n),d={...e,table:E[0],joinedTables:f,selectExprs:_},m=new Map;for(let O=0;O<s;O++)m.set(O,[]);for(const O of o){const D=tn(O,E);if(D.size===1){const v=D.values().next().value;v!==void 0&&((w=m.get(v))==null||w.push(O))}}const I=se(E[0],m.get(0)??[]),p=[I.scanType],T=[I.indexName];let U=I.cost;const B=I.rows;if(d.joinedTables)for(let O=1;O<s;O++){const D=d.joinedTables[O-1],v=ys(D,E[O],O,E,O);v?(p.push("IndexScan"),T.push(v.index.name),U+=B*.55):(p.push("TableScan"),T.push(void 0),U+=B*(2+(E[O].rowCountEstimate||10)*.1))}return{plan:d,orderedTables:E,metrics:{totalCost:U,estimatedRows:B,joinOrder:E.map(O=>O.name),singleTableFilters:m,crossFilters:l,tableScanTypes:p,tableIndexNames:T}}}}class ko{constructor(e){S(this,"name","custom");this.fn=e}optimize(e){return this.fn(e)}}const il=ko,rl=ms,ol=ms,al=Qo,cl=bo,ll=new ms;function Mi(t){return t??ll}function ul(t,e){return Mi(e).optimize(t)}function Dn(t){if(!t)return g.OP_EQ;switch(String(t).trim().toLowerCase().replace(/\s+/g," ")){case"=":case"==":return g.OP_EQ;case"!=":case"<>":return g.OP_NE;case">":return g.OP_GT;case">=":return g.OP_GE;case"<":return g.OP_LT;case"<=":return g.OP_LE;case"like":return g.OP_STR_LIKE;case"not like":return g.OP_STR_NOT_LIKE;case"contains":return g.OP_STR_CONTAINS;case"starts_with":return g.OP_STR_STARTS_WITH;case"ends_with":return g.OP_STR_ENDS_WITH;default:return g.OP_EQ}}class Is{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 r=0;r<8;r++)this.buffer.push(i[r]);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 Pt(t,e,n,s,i){i===y.INT32||i===y.INT64?(t.emitUint8(g.OP_COLUMN_INT),t.emitUint8(e),t.emitUint8(n),t.emitUint8(s)):i===y.FLOAT64?(t.emitUint8(g.OP_COLUMN_FLOAT),t.emitUint8(e),t.emitUint8(n),t.emitUint8(s)):i===y.TEXT?(t.emitUint8(g.OP_COLUMN_TEXT),t.emitUint8(e),t.emitUint8(n),t.emitUint8(s)):i===y.UUID?(t.emitUint8(g.OP_COLUMN_UUID),t.emitUint8(e),t.emitUint8(n),t.emitUint8(s)):i===y.ULID?(t.emitUint8(g.OP_COLUMN_ULID),t.emitUint8(e),t.emitUint8(n),t.emitUint8(s)):i===y.BLOB&&(t.emitUint8(g.OP_COLUMN_BLOB),t.emitUint8(e),t.emitUint8(n),t.emitUint8(s))}function _e(t){if(t.type==="in"){if(t.values&&t.values.length>bt)throw new RangeError(`WebDB: whereIn list exceeds maximum limit of ${bt} 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>bt)throw new RangeError(`WebDB: whereIn list exceeds maximum limit of ${bt} 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(_e):[]};if(t.type==="or")return{type:"or",children:t.children?t.children.map(_e):[]};if(t.type==="not"){const e=t.child;if(!e)return t;if(e.type==="not"&&e.child)return _e(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=>_e({type:"not",child:n})):[]};if(e.type==="or")return{type:"and",children:e.children?e.children.map(n=>_e({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 _e({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 Zt(t){if(!t||t.length===0)return null;const e=t.length===1?t[0]:{type:"and",children:t};return _e(e)}function Go(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 r of i.children)s(r)}else i.type==="not"&&i.child&&s(i.child)}return s(t),e}function en(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 lt(t,e){if(t.includes(".")){const n=t.split("."),s=n[0],i=n[1],r=e.findIndex(a=>a.name.toLowerCase()===s.toLowerCase());if(r===-1)return null;const o=e[r].columns.findIndex(a=>a.name.toLowerCase()===i.toLowerCase());return o===-1?null:{tableIdx:r,cursor:r,colIdx:o,col:e[r].columns[o],table:e[r]}}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 Wi(t,e,n,s,i,r,o,a){const l=o??[n];if(t.type==="expr"){const f=e*2,_=e*2+1;let d=50;const m=()=>{if(d>=64)throw new et(d);return d++};q(t.expr,n,s,0,f,m,r,void 0,l),s.emitUint8(g.OP_LOAD_INT),s.emitUint8(_),s.emitInt32(1),s.emitUint8(g.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=lt(t.colName,l);if(!f)throw new Error(`Column "${t.colName}" not found in tables`);t.isNull?s.emitUint8(g.OP_IS_NULL):s.emitUint8(g.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(g.OP_JUMP),i.push(s.emitUint16(0)));return}const f=e*2;if(t.expr){let d=50;const m=()=>{if(d>=64)throw new et(d);return d++};q(t.expr,n,s,0,f,m,r,void 0,l)}else{if(!t.colName)throw new Error("Filter IN leaf node missing colName");const d=lt(t.colName,l);if(d)Pt(s,d.cursor,d.colIdx,f,d.col.type);else try{const m=at(t.colName);let I=50;q(m,n,s,0,f,()=>{if(I>=64)throw new et(I);return I++},r,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(g.OP_IN),s.emitUint8(f),s.emitUint16(_),i.push(s.emitUint16(0));else{let d=-1;if(t.colName){const p=lt(t.colName,l);p&&(s.emitUint8(g.OP_IS_NULL),s.emitUint8(p.cursor),s.emitUint8(p.colIdx),d=s.emitUint16(0))}s.emitUint8(g.OP_IN),s.emitUint8(f),s.emitUint16(_);const m=s.emitUint16(0);s.emitUint8(g.OP_JUMP),i.push(s.emitUint16(0));const I=s.currentOffset();d!==-1&&s.patchUint16(d,I),s.patchUint16(m,I)}return}const c=e*2,u=e*2+1;if(t.expr){let f=50;const _=()=>{if(f>=64)throw new et(f);return f++};q(t.expr,n,s,0,c,_,r,void 0,l)}else{if(!t.colName)throw new Error("Filter leaf node missing colName");const f=lt(t.colName,l);if(f)Pt(s,f.cursor,f.colIdx,c,f.col.type);else try{const _=at(t.colName);let d=50;q(_,n,s,0,c,()=>{if(d>=64)throw new et(d);return d++},r,void 0,l)}catch{throw new Error(`Column "${t.colName}" not found in tables`)}}const E=Dn(t.op);s.emitUint8(E),s.emitUint8(c),s.emitUint8(u),i.push(s.emitUint16(0))}function Hi(t,e,n,s,i,r,o,a){const l=o??[n];if(t.type==="expr"){const _=e*2,d=e*2+1;let m=50;const I=()=>{if(m>=64)throw new et(m);return m++};q(t.expr,n,s,0,_,I,r,void 0,l),s.emitUint8(g.OP_LOAD_INT),s.emitUint8(d),s.emitInt32(1),s.emitUint8(g.OP_EQ),s.emitUint8(_),s.emitUint8(d);const p=s.emitUint16(0);s.emitUint8(g.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 _=lt(t.colName,l);if(!_)throw new Error(`Column "${t.colName}" not found in tables`);t.isNull?s.emitUint8(g.OP_IS_NOT_NULL):s.emitUint8(g.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(g.OP_JUMP),i.push(s.emitUint16(0)));return}const _=e*2;if(t.expr){let m=50;const I=()=>{if(m>=64)throw new et(m);return m++};q(t.expr,n,s,0,_,I,r,void 0,l)}else{if(!t.colName)throw new Error("Filter IN leaf node missing colName");const m=lt(t.colName,l);if(m)Pt(s,m.cursor,m.colIdx,_,m.col.type);else try{const I=at(t.colName);let p=50;q(I,n,s,0,_,()=>{if(p>=64)throw new et(p);return p++},r,void 0,l)}catch{throw new Error(`Column "${t.colName}" not found in tables`)}}const d=(a==null?void 0:a.get(t))??0;if(t.notIn){if(t.colName){const m=lt(t.colName,l);m&&(s.emitUint8(g.OP_IS_NULL),s.emitUint8(m.cursor),s.emitUint8(m.colIdx),i.push(s.emitUint16(0)))}s.emitUint8(g.OP_IN),s.emitUint8(_),s.emitUint16(d),i.push(s.emitUint16(0))}else{if(t.colName){const p=lt(t.colName,l);p&&(s.emitUint8(g.OP_IS_NULL),s.emitUint8(p.cursor),s.emitUint8(p.colIdx),i.push(s.emitUint16(0)))}s.emitUint8(g.OP_IN),s.emitUint8(_),s.emitUint16(d);const m=s.emitUint16(0);s.emitUint8(g.OP_JUMP),i.push(s.emitUint16(0));const I=s.currentOffset();s.patchUint16(m,I)}return}const c=e*2,u=e*2+1;if(t.expr){let _=50;const d=()=>{if(_>=64)throw new et(_);return _++};q(t.expr,n,s,0,c,d,r,void 0,l)}else{if(!t.colName)throw new Error("Filter leaf node missing colName");const _=lt(t.colName,l);if(_)Pt(s,_.cursor,_.colIdx,c,_.col.type);else try{const d=at(t.colName);let m=50;q(d,n,s,0,c,()=>{if(m>=64)throw new et(m);return m++},r,void 0,l)}catch{throw new Error(`Column "${t.colName}" not found in tables`)}}const E=Dn(t.op);s.emitUint8(E),s.emitUint8(c),s.emitUint8(u);const f=s.emitUint16(0);s.emitUint8(g.OP_JUMP),i.push(s.emitUint16(0)),s.patchUint16(f,s.currentOffset())}function Al(t,e,n,s,i,r,o,a,l,c){o==="true"?Hi(t,e,n,s,r,a,l,c):o==="false"?Wi(t,e,n,s,i,a,l,c):(Wi(t,e,n,s,i,a,l,c),s.emitUint8(g.OP_JUMP),r.push(s.emitUint16(0)))}function Rn(t,e,n,s,i,r,o,a,l,c){if(t.type==="cmp"||t.type==="null"||t.type==="expr"||t.type==="in"){const u=s.get(t)??0;Al(t,u,n,e,i,r,o,a,l,c);return}if(t.type==="not"){if(!t.child)return;const u=t.child,E=s.get(u)??0;o==="true"?Wi(u,E,n,e,r,a,l,c):o==="false"?Hi(u,E,n,e,i,a,l,c):(Hi(u,E,n,e,i,a,l,c),e.emitUint8(g.OP_JUMP),r.push(e.emitUint16(0)));return}if(t.type==="and"){const u=t.children??[];if(u.length===0){o==="false"&&(e.emitUint8(g.OP_JUMP),i.push(e.emitUint16(0)));return}for(let E=0;E<u.length;E++){const f=u[E];if(E===u.length-1)Rn(f,e,n,s,i,r,o,a,l,c);else{const d=[];Rn(f,e,n,s,d,r,"true",a,l,c);const m=e.currentOffset();for(const I of d)e.patchUint16(I,m)}}return}if(t.type==="or"){const u=t.children??[];if(u.length===0){o==="true"&&(e.emitUint8(g.OP_JUMP),r.push(e.emitUint16(0)));return}for(let E=0;E<u.length;E++){const f=u[E];if(E===u.length-1)Rn(f,e,n,s,i,r,o,a,l,c);else{const d=[];Rn(f,e,n,s,i,d,"false",a,l,c);const m=e.currentOffset();for(const I of d)e.patchUint16(I,m)}}return}}function fl(t,e,n,s,i,r,o){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,o,s);else if(t.colName){a=i();const _=at(t.colName);q(_,e,n,-1,a,i,o,s)}else a=i(),n.emitUint8(g.OP_LOAD_NULL),n.emitUint8(a);const c=i(),u=t.value;u==null?(n.emitUint8(g.OP_LOAD_NULL),n.emitUint8(c)):typeof u=="number"?Number.isInteger(u)?(n.emitUint8(g.OP_LOAD_INT),n.emitUint8(c),n.emitInt32(u)):(n.emitUint8(g.OP_LOAD_FLOAT),n.emitUint8(c),n.emitFloat64(u)):typeof u=="string"?(n.emitUint8(g.OP_LOAD_TEXT),n.emitUint8(c),n.emitString(u)):typeof u=="boolean"?(n.emitUint8(g.OP_LOAD_INT),n.emitUint8(c),n.emitInt32(u?1:0)):typeof u=="bigint"&&(n.emitUint8(g.OP_LOAD_INT),n.emitUint8(c),n.emitInt32(Number(u)));const E=Dn(t.op);n.emitUint8(E),n.emitUint8(a),n.emitUint8(c);const f=n.emitUint16(0);n.emitUint8(g.OP_JUMP),r.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,o,s);else if(t.colName){a=i();const c=at(t.colName);q(c,e,n,-1,a,i,o,s)}else a=i(),n.emitUint8(g.OP_LOAD_NULL),n.emitUint8(a);t.isNull?(n.emitUint8(g.OP_REG_IS_NOT_NULL),n.emitUint8(a),r.push(n.emitUint16(0))):(n.emitUint8(g.OP_REG_IS_NULL),n.emitUint8(a),r.push(n.emitUint16(0)));return}if(t.type==="expr"&&t.expr){const a=i();q(t.expr,e,n,-1,a,i,o,s);const l=i();n.emitUint8(g.OP_LOAD_INT),n.emitUint8(l),n.emitInt32(1),n.emitUint8(g.OP_EQ),n.emitUint8(a),n.emitUint8(l);const c=n.emitUint16(0);n.emitUint8(g.OP_JUMP),r.push(n.emitUint16(0)),n.patchUint16(c,n.currentOffset());return}}function vo(t,e,n,s,i,r,o){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,o,s);else if(t.colName){a=i();const f=at(t.colName);q(f,e,n,-1,a,i,o,s)}else a=i(),n.emitUint8(g.OP_LOAD_NULL),n.emitUint8(a);const c=i(),u=t.value;u==null?(n.emitUint8(g.OP_LOAD_NULL),n.emitUint8(c)):typeof u=="number"?Number.isInteger(u)?(n.emitUint8(g.OP_LOAD_INT),n.emitUint8(c),n.emitInt32(u)):(n.emitUint8(g.OP_LOAD_FLOAT),n.emitUint8(c),n.emitFloat64(u)):typeof u=="string"?(n.emitUint8(g.OP_LOAD_TEXT),n.emitUint8(c),n.emitString(u)):typeof u=="boolean"?(n.emitUint8(g.OP_LOAD_INT),n.emitUint8(c),n.emitInt32(u?1:0)):typeof u=="bigint"&&(n.emitUint8(g.OP_LOAD_INT),n.emitUint8(c),n.emitInt32(Number(u)));const E=Dn(t.op);n.emitUint8(E),n.emitUint8(a),n.emitUint8(c),r.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,o,s);else if(t.colName){a=i();const c=at(t.colName);q(c,e,n,-1,a,i,o,s)}else a=i(),n.emitUint8(g.OP_LOAD_NULL),n.emitUint8(a);t.isNull?(n.emitUint8(g.OP_REG_IS_NULL),n.emitUint8(a),r.push(n.emitUint16(0))):(n.emitUint8(g.OP_REG_IS_NOT_NULL),n.emitUint8(a),r.push(n.emitUint16(0)));return}if(t.type==="expr"&&t.expr){const a=i();q(t.expr,e,n,-1,a,i,o,s);const l=i();n.emitUint8(g.OP_LOAD_INT),n.emitUint8(l),n.emitInt32(1),n.emitUint8(g.OP_EQ),n.emitUint8(a),n.emitUint8(l),r.push(n.emitUint16(0));return}}function _l(t,e,n,s,i,r,o,a,l){a==="true"?fl(t,e,n,s,i,o,l):a==="false"?vo(t,e,n,s,i,r,l):(vo(t,e,n,s,i,r,l),n.emitUint8(g.OP_JUMP),o.push(n.emitUint16(0)))}function ge(t,e,n,s,i,r,o,a,l){if(t.type==="cmp"||t.type==="null"||t.type==="expr"){_l(t,n,e,s,i,r,o,a,l);return}if(t.type==="not"){if(!t.child)return;const c=t.child;a==="true"?ge(c,e,n,s,i,o,r,"false",l):a==="false"?ge(c,e,n,s,i,r,o,"true",l):ge(c,e,n,s,i,o,r,"none",l);return}if(t.type==="and"){const c=t.children??[];if(c.length===0){a==="false"&&(e.emitUint8(g.OP_JUMP),r.push(e.emitUint16(0)));return}for(let u=0;u<c.length;u++){const E=c[u];if(u===c.length-1)ge(E,e,n,s,i,r,o,a,l);else{const _=[];ge(E,e,n,s,i,_,o,"true",l);const d=e.currentOffset();for(const m of _)e.patchUint16(m,d)}}return}if(t.type==="or"){const c=t.children??[];if(c.length===0){a==="true"&&(e.emitUint8(g.OP_JUMP),o.push(e.emitUint16(0)));return}for(let u=0;u<c.length;u++){const E=c[u];if(u===c.length-1)ge(E,e,n,s,i,r,o,a,l);else{const _=[];ge(E,e,n,s,i,r,_,"false",l);const d=e.currentOffset();for(const m of _)e.patchUint16(m,d)}}return}}function gl(t,e,n,s,i,r,o){if(!t)return;const a=[];ge(t,n,e,s,i,a,r,"true",o);const l=n.currentOffset();for(const c of a)n.patchUint16(c,l)}function qt(t,e,n,s,i,r,o,a){if(!t)return;const l=[];Rn(t,n,e,s,l,i,"true",r,o,a);const c=n.currentOffset();for(const u of l)n.patchUint16(u,c)}function Mo(t,e,n,s){if(t.type==="literal")return typeof t.value=="number"?Number.isInteger(t.value)?y.INT32:y.FLOAT64:(typeof t.value=="string",y.TEXT);if(t.type==="col"){const i=s??[e],r=lt(t.name,i);return r?r.col.type:y.TEXT}if(t.type==="binary")return y.FLOAT64;if(t.type==="fn"){const i=t.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 y.TEXT;if(["length","count","starts_with","startswith","ends_with","endswith","like","contains"].includes(i))return y.INT32;if(["abs","round","floor","ceil","sum","avg","min","max"].includes(i)){if(t.args.length>0&&t.args[0].type==="col"){const r=lt(t.args[0].name,s??[e]);if(r&&r.col.type===y.INT32&&i!=="avg")return y.INT32}return y.FLOAT64}return y.TEXT}return y.TEXT}function q(t,e,n,s,i,r,o,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(g.OP_COPY),n.emitUint8(u),n.emitUint8(i));return}}if(t.type==="literal"){const c=t.value;c==null?(n.emitUint8(g.OP_LOAD_NULL),n.emitUint8(i)):typeof c=="number"?Number.isInteger(c)?(n.emitUint8(g.OP_LOAD_INT),n.emitUint8(i),n.emitInt32(c)):(n.emitUint8(g.OP_LOAD_FLOAT),n.emitUint8(i),n.emitFloat64(c)):typeof c=="string"?(n.emitUint8(g.OP_LOAD_TEXT),n.emitUint8(i),n.emitString(c)):typeof c=="boolean"&&(n.emitUint8(g.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=lt(t.name,c);if(!u){if(t.name==="*"){n.emitUint8(g.OP_LOAD_NULL),n.emitUint8(i);return}throw new Error(`Column "${t.name}" does not exist in table "${e.name}"`)}Pt(n,u.cursor,u.colIdx,i,u.col.type);return}if(t.type==="binary"){const c=r(),u=r();q(t.left,e,n,s,c,r,o,a,l),q(t.right,e,n,s,u,r,o,a,l);let E=g.OP_ADD;if(t.op==="+")E=g.OP_ADD;else if(t.op==="-")E=g.OP_SUB;else if(t.op==="*")E=g.OP_MUL;else if(t.op==="/")E=g.OP_DIV;else if(t.op==="%")E=g.OP_MOD;else if(t.op==="="||t.op==="!="||t.op==="<"||t.op==="<="||t.op===">"||t.op===">="){let f=g.OP_EQ;t.op==="="?f=g.OP_EQ:t.op==="!="?f=g.OP_NE:t.op==="<"?f=g.OP_LT:t.op==="<="?f=g.OP_LE:t.op===">"?f=g.OP_GT:t.op===">="&&(f=g.OP_GE),n.emitUint8(f),n.emitUint8(c),n.emitUint8(u);const _=n.emitUint16(0);n.emitUint8(g.OP_LOAD_INT),n.emitUint8(i),n.emitInt32(0),n.emitUint8(g.OP_JUMP);const d=n.emitUint16(0);n.patchUint16(_,n.currentOffset()),n.emitUint8(g.OP_LOAD_INT),n.emitUint8(i),n.emitInt32(1),n.patchUint16(d,n.currentOffset());return}n.emitUint8(E),n.emitUint8(c),n.emitUint8(u),n.emitUint8(i);return}if(t.type==="fn"){const c=t.name.toLowerCase(),u={upper:g.OP_STR_UPPER,lower:g.OP_STR_LOWER,length:g.OP_STR_LENGTH,trim:g.OP_STR_TRIM,abs:g.OP_MATH_ABS,round:g.OP_MATH_ROUND,floor:g.OP_MATH_FLOOR,ceil:g.OP_MATH_CEIL};if(u[c]){const f=r(),_=t.args[0]??{type:"literal",value:null};q(_,e,n,s,f,r,o,a,l),n.emitUint8(u[c]),n.emitUint8(f),n.emitUint8(i);return}if(c==="substr"){const f=r(),_=r(),d=r();q(t.args[0],e,n,s,f,r,o,a,l),q(t.args[1]??{type:"literal",value:1},e,n,s,_,r,o,a,l),t.args[2]!==void 0?q(t.args[2],e,n,s,d,r,o,a,l):(n.emitUint8(g.OP_LOAD_NULL),n.emitUint8(d)),n.emitUint8(g.OP_STR_SUBSTR),n.emitUint8(f),n.emitUint8(_),n.emitUint8(d),n.emitUint8(i);return}const E={starts_with:g.OP_STR_STARTS_WITH,startswith:g.OP_STR_STARTS_WITH,ends_with:g.OP_STR_ENDS_WITH,endswith:g.OP_STR_ENDS_WITH,like:g.OP_STR_LIKE,contains:g.OP_STR_CONTAINS};if(E[c]){const f=r(),_=r();q(t.args[0]??{type:"literal",value:null},e,n,s,f,r,o,a,l),q(t.args[1]??{type:"literal",value:""},e,n,s,_,r,o,a,l),n.emitUint8(E[c]),n.emitUint8(f),n.emitUint8(_);const d=n.emitUint16(0);n.emitUint8(g.OP_LOAD_INT),n.emitUint8(i),n.emitInt32(0),n.emitUint8(g.OP_JUMP);const m=n.emitUint16(0);n.patchUint16(d,n.currentOffset()),n.emitUint8(g.OP_LOAD_INT),n.emitUint8(i),n.emitInt32(1),n.patchUint16(m,n.currentOffset());return}if(c==="concat"||c==="coalesce"){const f=t.args.length,_=r();for(let m=1;m<f;m++)r();for(let m=0;m<f;m++)q(t.args[m],e,n,s,_+m,r,o,a,l);const d=c==="concat"?g.OP_STR_CONCAT:g.OP_COALESCE;n.emitUint8(d),n.emitUint8(_),n.emitUint8(f),n.emitUint8(i);return}if(o&&o.has(c)){const f=o.get(c),_=t.args.length;let d=i;if(_>0){d=r();for(let m=1;m<_;m++)r();for(let m=0;m<_;m++)q(t.args[m],e,n,s,d+m,r,o,a,l)}n.emitUint8(g.OP_CALL_UDF),n.emitUint16(f),n.emitUint8(d),n.emitUint8(_),n.emitUint8(i);return}throw new ti(c)}}function Vi(t,e,n,s){n==null?(t.emitUint8(g.OP_LOAD_NULL),t.emitUint8(e)):typeof n=="number"?s===y.FLOAT64||!Number.isInteger(n)?(t.emitUint8(g.OP_LOAD_FLOAT),t.emitUint8(e),t.emitFloat64(n)):(t.emitUint8(g.OP_LOAD_INT),t.emitUint8(e),t.emitInt32(Math.floor(n))):typeof n=="bigint"?(t.emitUint8(g.OP_LOAD_INT),t.emitUint8(e),t.emitInt32(Number(n))):typeof n=="string"?(t.emitUint8(g.OP_LOAD_TEXT),t.emitUint8(e),t.emitString(n)):typeof n=="boolean"&&(t.emitUint8(g.OP_LOAD_INT),t.emitUint8(e),t.emitInt32(n?1:0))}function ps(t){switch(t){case y.INT32:return-2147483648;case y.INT64:return-9223372036854775808n;case y.FLOAT64:return-1/0;case y.TEXT:case y.UUID:case y.ULID:return"";case y.BLOB:return new Uint8Array(0);default:return 0}}function Xi(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 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 l=(a=n[o].colName)==null?void 0:a.toLowerCase();if(!l||l!==i[r])return!1;r++,o++}return o===n.length}function Wo(t,e,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=lt(o,s);if(!a&&i){const l=i.find(c=>c.alias===o);l&&l.expr.type==="col"&&(a=lt(l.expr.name,s))}if(!a||a.tableIdx!==0)return!1}else{const a=o.includes(".")?o.slice(o.lastIndexOf(".")+1):o;if(!t.columns.some(c=>c.name.toLowerCase()===a.toLowerCase()))return!1}}return!0}function Ts(t,e,n,s){if(!t.indexes||t.indexes.length===0)return null;const i=n??e,r=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&&r.add(a.colName.toLowerCase());const o=a=>(s&&s.length>0&&(a.scanType==="point"&&a.index.flags&(Ut.PRIMARY|Ut.UNIQUE)||Xi(a.index,t,s,r))&&(a.satisfiesOrderBy=!0),a);for(const a of t.indexes)if(a.flags&Ut.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 o({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 E=Array.from(new Set(u.values.filter(f=>f!=null)));return o({index:a,scanType:"multi_point",seekFilter:u,filterIndex:i.indexOf(u),keyType:l.type,inValues:E})}}}for(const a of t.indexes)if(a.flags&Ut.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 o({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 E=Array.from(new Set(u.values.filter(f=>f!=null)));return o({index:a,scanType:"multi_point",seekFilter:u,filterIndex:i.indexOf(u),keyType:l.type,inValues:E})}}}for(const a of t.indexes)if(a.columnCount>1){const l=[];let c=!0;for(let u=0;u<a.columnCount;u++){const E=t.columns[a.columnIndices[u]],f=e.find(_=>_.type==="cmp"&&(_.op==="="||_.op===void 0)&&_.colName===E.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 E=ls(t.columns,a.columnIndices,a.columnCount,u);return o({index:a,scanType:"point",seekFilter:l[0],filterIndex:i.indexOf(l[0]),keyType:y.BLOB,compositeValue:E})}}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 o({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 o({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(Xi(a,t,s,r))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 E=t.columns[a.columnIndices[u]],f=e.find(_=>_.type==="cmp"&&(_.op==="="||_.op===void 0)&&_.colName===E.name&&_.value!==void 0&&_.value!==null);f?l[E.name]=f.value:l[E.name]=ps(E.type)}const c=ls(t.columns,a.columnIndices,a.columnCount,l);return{index:a,scanType:"range",seekFilter:void 0,filterIndex:-1,keyType:y.BLOB,compositeValue:c,satisfiesOrderBy:!0}}}return null}function ys(t,e,n,s,i){if(t.op!=="="||!e.indexes||e.indexes.length===0)return null;const r=lt(t.leftCol,s),o=lt(t.rightCol,s);if(!r||!o)return null;let a=null,l=null;if(r.tableIdx===n&&o.tableIdx<n?(a=r,l=o):o.tableIdx===n&&r.tableIdx<n&&(a=o,l=r),!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&Ut.PRIMARY)!==0,d=(f.flags&Ut.UNIQUE)!==0,m=_?1:d?2:3;m<u&&(u=m,c=f)}if(!c)return null;const E=(c.flags&(Ut.PRIMARY|Ut.UNIQUE))!==0;return{index:c,isUnique:E,innerCol:a,outerCol:l,indexCursor:i}}function $i(t,e){var Cs,an,Os,Xo,$o,Yo,Zo,qo,jo;const n=[t.table,...((Cs=t.joinedTables)==null?void 0:Cs.map(L=>L.table))??[]],i=Mi((e==null?void 0:e.planner)??t.planner).optimize(t),r=i.orderedTables??n,o=i.whereMetrics,a=i.metrics;if(i.isAlwaysFalse){const L=new Is;L.emitUint8(g.OP_HALT);const G=L.toByteArray();return t.outputColumns&&(G.outputColumns=t.outputColumns),G.allTables=r,G.whereMetrics=o,G}const l=i.plan;l!==t&&Object.assign(t,l);const c=t.joinedTables!==void 0&&t.joinedTables.length>0,u=Zt(t.filters),E=u?Go(u):[],f=en(u),_=Array.from({length:r.length},()=>[]),d=new Set;if(c&&a)for(let L=0;L<r.length;L++){const G=n.indexOf(r[L]);if(G!==-1){const H=a.singleTableFilters.get(G)??[];if(L===0||t.joinedTables&&((an=t.joinedTables[L-1])==null?void 0:an.type)==="inner"){_[L]=H;for(const X of H)d.add(X)}}}const m=[];for(const L of f)d.has(L)||m.push(L);const I=Zt(m),p=c&&Wo(r[0],t.joinedTables,t.orderBy,r,t.selectExprs),T=p?t.orderBy.map(L=>{const G=L.colName??"",H=G.includes(".")?G.slice(G.lastIndexOf(".")+1):G;return{...L,colName:H}}):void 0,U=c?Ts(r[0],_[0],E,T):null,B=p&&!!(U!=null&&U.satisfiesOrderBy);let F=r.length,P=-1;U&&F<16&&(P=F++);const w=new Array(r.length).fill(null);if(c&&t.joinedTables)for(let L=1;L<r.length;L++){const G=t.joinedTables[L-1];if(F<16){const H=ys(G,r[L],L,r,F);H&&(w[L]=H,F++)}}const O=F;if(O>16)throw new $n(O,16);for(const L of f)if(L.type==="in"&&!L.notIn&&(!L.values||L.values.length===0)){const G=new Is;G.emitUint8(g.OP_HALT);const H=G.toByteArray();return t.outputColumns&&(H.outputColumns=t.outputColumns),H}const D=[],v=new Map;for(const L of E)if(L.type==="in"){const G=D.length;v.set(L,G);const H=new Set;if(L.values)for(const X of L.values)X!=null&&(H.add(X),typeof X=="bigint"?H.add(Number(X)):typeof X=="number"&&Number.isSafeInteger(X)&&H.add(BigInt(X)));D.push(H)}const Q=new Map;for(let L=0;L<E.length;L++)Q.set(E[L],L);if(E.length*2>=64)throw new et(E.length*2);if(t.orderBy&&t.orderBy.length>8)throw new Lr(t.orderBy.length);if(t.groupBy&&t.groupBy.length>8)throw new Fr(t.groupBy.length);const A=new Is;if(t.limit!==void 0&&t.limit<=0)return A.emitUint8(g.OP_HALT),A.toByteArray();let N=E.length*2;const k=t.offset!==void 0&&t.offset>0,$=t.limit!==void 0&&t.limit>0,J=k?N++:-1,K=$?N++:-1;if(N>=64)throw new et(N);const M=t.table;for(let L=0;L<E.length;L++){const G=E[L];if(G.type==="cmp"){const H=L*2+1,X=G.value;if(X==null)A.emitUint8(g.OP_LOAD_NULL),A.emitUint8(H);else if(typeof X=="number"){const At=G.colName?lt(G.colName,r):void 0;At&&At.col.type===y.FLOAT64?(A.emitUint8(g.OP_LOAD_FLOAT),A.emitUint8(H),A.emitFloat64(X)):Number.isInteger(X)?(A.emitUint8(g.OP_LOAD_INT),A.emitUint8(H),A.emitInt32(Math.floor(X))):(A.emitUint8(g.OP_LOAD_FLOAT),A.emitUint8(H),A.emitFloat64(X))}else typeof X=="bigint"?(A.emitUint8(g.OP_LOAD_INT),A.emitUint8(H),A.emitInt32(Number(X))):typeof X=="string"?(A.emitUint8(g.OP_LOAD_TEXT),A.emitUint8(H),A.emitString(X)):typeof X=="boolean"&&(A.emitUint8(g.OP_LOAD_INT),A.emitUint8(H),A.emitInt32(X?1:0))}}if(k&&(A.emitUint8(g.OP_LOAD_INT),A.emitUint8(J),A.emitInt32(t.offset)),$&&(A.emitUint8(g.OP_LOAD_INT),A.emitUint8(K),A.emitInt32(t.limit)),t.aggregates&&t.aggregates.length>0||t.groupBy&&t.groupBy.length>0){const L=((Os=t.groupBy)==null?void 0:Os.length)??0,G=t.aggregates??[],H=G.length,X=[];for(const b of t.groupBy??[]){const V=typeof b=="string"?b:b.colName??(b.expr?Yt(b.expr):"group_key"),Y=(Xo=t.selectExprs)==null?void 0:Xo.find(ct=>{if(ct.alias===V)return!0;if(typeof b=="object"&&b.expr)return JSON.stringify(ct.expr)===JSON.stringify(b.expr);if(typeof b=="string"&&b.includes("("))try{const $t=at(b);return JSON.stringify(ct.expr)===JSON.stringify($t)}catch{return!1}return!1}),Z=(Y==null?void 0:Y.alias)??V,j=M.columns.find(ct=>ct.name===V||ct.name===Z);j?X.push({...j,name:Z}):X.push({name:Z,type:y.TEXT,flags:Ct.NONE,colOffset:0})}for(let b=0;b<G.length;b++){const V=G[b],Y=V.alias??(V.colName?`${V.func}_${V.colName}`:V.func),Z=V.func==="count"?y.INT32:y.FLOAT64;X.push({name:Y,type:Z,flags:Ct.NONE,colOffset:0})}const z=N,x=z+L,st=x+4,ft=st+4,tt=ft+L,Ot=tt+H;if(Ot>=64)throw new et(Ot);A.emitUint8(g.OP_AGG_INIT),A.emitUint8(0),A.emitUint8(z),A.emitUint8(L),A.emitUint8(0),A.emitUint8(g.OP_OPEN_CURSOR),A.emitUint8(0),A.emitUint32(M.rootPageId),A.emitUint8(g.OP_REWIND),A.emitUint8(0);const wt=A.emitUint16(0),it=A.currentOffset(),Nt=[];if(qt(u,M,A,Q,Nt,t.udfNameMap,void 0,v),t.groupBy)for(let b=0;b<t.groupBy.length;b++){const V=t.groupBy[b],Y=z+b;let Z=Math.max(Ot+4,40);const j=()=>{if(Z>=64)throw new et(Z);return Z++};if(typeof V=="object"&&V.expr)q(V.expr,M,A,0,Y,j,t.udfNameMap);else{const ct=typeof V=="string"?V:V.colName,$t=(Yo=($o=t.selectExprs)==null?void 0:$o.find(Et=>Et.alias===ct))==null?void 0:Yo.expr;if($t)q($t,M,A,0,Y,j,t.udfNameMap);else{const Et=M.columns.findIndex(Lt=>Lt.name===ct);if(Et!==-1){const Lt=M.columns[Et];Pt(A,0,Et,Y,Lt.type)}else try{const Lt=at(ct);q(Lt,M,A,0,Y,j,t.udfNameMap)}catch{throw new Error(`Grouping column "${ct}" not found in table "${M.name}"`)}}}}H===0&&L>0&&(A.emitUint8(g.OP_AGG_STEP),A.emitUint8(0),A.emitUint8(z),A.emitUint8(L),A.emitUint8(255),A.emitUint8(0));const Vt=G.some(b=>b.func==="count"),Rt=G.some(b=>b.func==="avg"),Ee=G.some(b=>b.func==="sum"),te=G.some(b=>b.func==="min"),Bt=G.some(b=>b.func==="max");if(Vt||Rt||Ee){const b=G.find(Y=>Y.func==="count");let V=255;if(b&&b.colName&&b.colName!=="*"){const Y=M.columns.findIndex(Z=>Z.name===b.colName);if(Y!==-1){const Z=M.columns[Y];V=x,Pt(A,0,Y,V,Z.type)}}A.emitUint8(g.OP_AGG_STEP),A.emitUint8(0),A.emitUint8(z),A.emitUint8(L),A.emitUint8(V),A.emitUint8(0)}if(Ee||Rt){const b=G.find(Y=>Y.func==="sum"||Y.func==="avg");let V=255;if(b&&b.colName&&b.colName!=="*"){const Y=M.columns.findIndex(Z=>Z.name===b.colName);if(Y!==-1){const Z=M.columns[Y];V=x+1,Pt(A,0,Y,V,Z.type)}}A.emitUint8(g.OP_AGG_STEP),A.emitUint8(0),A.emitUint8(z),A.emitUint8(L),A.emitUint8(V),A.emitUint8(1)}if(te){const b=G.find(Y=>Y.func==="min");let V=255;if(b&&b.colName&&b.colName!=="*"){const Y=M.columns.findIndex(Z=>Z.name===b.colName);if(Y!==-1){const Z=M.columns[Y];V=x+2,Pt(A,0,Y,V,Z.type)}}A.emitUint8(g.OP_AGG_STEP),A.emitUint8(0),A.emitUint8(z),A.emitUint8(L),A.emitUint8(V),A.emitUint8(3)}if(Bt){const b=G.find(Y=>Y.func==="max");let V=255;if(b&&b.colName&&b.colName!=="*"){const Y=M.columns.findIndex(Z=>Z.name===b.colName);if(Y!==-1){const Z=M.columns[Y];V=x+3,Pt(A,0,Y,V,Z.type)}}A.emitUint8(g.OP_AGG_STEP),A.emitUint8(0),A.emitUint8(z),A.emitUint8(L),A.emitUint8(V),A.emitUint8(4)}const ie=A.currentOffset();for(const b of Nt)A.patchUint16(b,ie);A.emitUint8(g.OP_NEXT_ROW),A.emitUint8(0);const R=A.emitUint16(0);A.emitUint8(g.OP_JUMP),A.emitUint16(it);const _t=A.currentOffset();A.patchUint16(wt,_t),A.patchUint16(R,_t);const rt=A.currentOffset();A.emitUint8(g.OP_AGG_NEXT),A.emitUint8(0),A.emitUint8(ft),A.emitUint8(st);const Ft=A.emitUint16(0),yt=A.currentOffset();A.emitUint8(g.OP_HALT);const Xt=A.currentOffset();A.patchUint16(Ft,Xt);for(let b=0;b<G.length;b++){const V=G[b],Y=tt+b;let Z=st,j=0;V.func==="count"?(Z=st,j=0):V.func==="sum"?(Z=st,j=1):V.func==="avg"?(Z=st,j=2):V.func==="min"?(Z=st+2,j=3):V.func==="max"&&(Z=st+3,j=4),A.emitUint8(g.OP_AGG_FINAL),A.emitUint8(Z),A.emitUint8(st+1),A.emitUint8(Y),A.emitUint8(j)}const cn=(b,V)=>{var Y;for(let Z=0;Z<G.length;Z++){const j=G[Z],ct=tt+Z;if(b&&(j.alias&&j.alias===b||(j.colName?`${j.func}_${j.colName}`:j.func)===b||`${j.func}(${j.colName??"*"})`===b.replace(/\s+/g,"")||j.func===b))return ct;if(V&&V.type==="fn"){const $t=V.name.toLowerCase();if(j.func===$t)if($t==="count"){const Et=V.args[0],Lt=Et&&Et.type==="col"?Et.name:void 0;if(j.colName===void 0||j.colName==="*"||j.colName===Lt)return ct}else{const Et=V.args[0],Lt=Et&&Et.type==="col"?Et.name:void 0;if(j.colName===Lt)return ct}}}if(t.groupBy)for(let Z=0;Z<t.groupBy.length;Z++){const j=t.groupBy[Z],ct=ft+Z,$t=typeof j=="string"?j:j.colName,Et=typeof j=="object"?j.expr:void 0;if(b){if($t===b||Et&&Yt(Et)===b)return ct;const Lt=(Y=t.selectExprs)==null?void 0:Y.find(qi=>qi.alias===b);if(Lt){if($t===Lt.alias||Et&&JSON.stringify(Et)===JSON.stringify(Lt.expr))return ct;if(typeof j=="string"&&j.includes("("))try{const qi=at(j);if(JSON.stringify(qi)===JSON.stringify(Lt.expr))return ct}catch{}}}if(V){if(Et&&JSON.stringify(Et)===JSON.stringify(V)||V.type==="col"&&$t===V.name)return ct;if(typeof j=="string"&&j.includes("("))try{const Lt=at(j);if(JSON.stringify(Lt)===JSON.stringify(V))return ct}catch{}}}};if(t.having&&t.having.length>0){let b=null;t.having.length===1?b=t.having[0]:b={type:"and",children:t.having};const V=[];let Y=Math.max(Ot+4,40);gl(b,M,A,cn,()=>{if(Y>=64)throw new et(Y);return Y++},V,t.udfNameMap);for(const j of V)A.patchUint16(j,rt)}k&&(A.emitUint8(g.OP_OFFSET),A.emitUint8(J),A.emitUint16(rt)),A.emitUint8(g.OP_RESULT_ROW),A.emitUint8(ft),A.emitUint8(L+H),$&&(A.emitUint8(g.OP_LIMIT),A.emitUint8(K),A.emitUint16(yt)),A.emitUint8(g.OP_JUMP),A.emitUint16(rt);const me=A.toByteArray();return me.outputColumns=X,me.inSets=D,t.outputColumns=X,me}const W=c?null:Ts(M,f,E,t.orderBy);if(!c&&t.orderBy&&t.orderBy.length>0&&!(W!=null&&W.satisfiesOrderBy)){const L=t.orderBy.length,G=N,H=G+L;if(H>=64)throw new et(H);const X={numKeys:L,directions:t.orderBy.map(it=>it.direction==="desc"?1:0),nullOrders:t.orderBy.map(it=>it.nullOrder==="nulls_last"?1:it.nullOrder==="nulls_first"?0:it.direction==="desc"?1:0),limit:t.limit,offset:t.offset};t.keyInfos=[X],A.emitUint8(g.OP_SORTER_OPEN),A.emitUint8(0),A.emitUint8(0),A.emitUint8(g.OP_OPEN_CURSOR),A.emitUint8(0),A.emitUint32(M.rootPageId),A.emitUint8(g.OP_REWIND),A.emitUint8(0);const At=A.emitUint16(0),z=A.currentOffset(),x=[];qt(u,M,A,Q,x,t.udfNameMap,void 0,v);for(let it=0;it<L;it++){const Nt=t.orderBy[it],Vt=G+it;let Rt=50;const Ee=()=>{if(Rt>=64)throw new et(Rt);return Rt++};if(Nt.expr)q(Nt.expr,M,A,0,Vt,Ee,t.udfNameMap);else if(Nt.colName){const te=Nt.colName,Bt=(qo=(Zo=t.selectExprs)==null?void 0:Zo.find(ie=>ie.alias===te))==null?void 0:qo.expr;if(Bt)q(Bt,M,A,0,Vt,Ee,t.udfNameMap);else{const ie=M.columns.findIndex(R=>R.name===te);if(ie!==-1){const R=M.columns[ie];Pt(A,0,ie,Vt,R.type)}else try{const R=at(te);q(R,M,A,0,Vt,Ee,t.udfNameMap)}catch{throw new Error(`Order by column "${te}" not found in table "${M.name}"`)}}}}A.emitUint8(g.OP_SORTER_INSERT),A.emitUint8(0),A.emitUint8(G),A.emitUint8(L),A.emitUint8(0);const st=A.currentOffset();for(const it of x)A.patchUint16(it,st);A.emitUint8(g.OP_NEXT_ROW),A.emitUint8(0);const ft=A.emitUint16(0);A.emitUint8(g.OP_JUMP),A.emitUint16(z);const tt=A.currentOffset();A.patchUint16(At,tt),A.patchUint16(ft,tt),A.emitUint8(g.OP_SORTER_SORT),A.emitUint8(0);const Ot=A.currentOffset();A.emitUint8(g.OP_SORTER_NEXT),A.emitUint8(0),A.emitUint16(Ot),A.emitUint8(g.OP_HALT);const wt=A.toByteArray();return wt.keyInfos=t.keyInfos,wt.inSets=D,a&&(wt.planMetrics=a,wt.estimatedCost=a.totalCost,wt.estimatedRows=a.estimatedRows,wt.joinOrder=a.joinOrder),wt}const jt=t.selectExprs!==void 0&&t.selectExprs.length>0&&!(t.selectExprs.length===1&&t.selectExprs[0].expr.type==="col"&&t.selectExprs[0].expr.name==="*");let gt=[];if(jt)gt=t.selectExprs;else if(c){const L=new Set,G=new Set;for(const H of r)for(const X of H.columns)L.has(X.name.toLowerCase())&&G.add(X.name.toLowerCase()),L.add(X.name.toLowerCase());for(const H of r)for(const X of H.columns){const At=G.has(X.name.toLowerCase())?`${H.name}.${X.name}`:X.name;gt.push({expr:{type:"col",name:`${H.name}.${X.name}`},alias:At})}}let ut=-1;if(jt||c){const L=gt.map(G=>({name:G.alias,type:Mo(G.expr,M,t.udfDefs,r),flags:Ct.NONE,colOffset:0}));if(t.outputColumns=L,ut=N,N+=gt.length,N>=64)throw new et(N)}if(c){const L=r.length,G=new Array(L);for(let R=1;R<L;R++)t.joinedTables[R-1].type==="left"&&(G[R]=N++);const H=N++,X=N++,At=N++;let z=-1;if(U&&P!==-1)if(U.compositeValue){if(z=N++,N>=64)throw new et(N);A.emitUint8(g.OP_LOAD_BLOB),A.emitUint8(z),A.emitUint32(U.compositeValue.length),A.emitBytes(U.compositeValue)}else if(U.scanType==="multi_point"){if(z=N++,N>=64)throw new et(N)}else if(U.filterIndex>=0)z=U.filterIndex*2+1;else{if(z=N++,N>=64)throw new et(N);const R=ps(U.keyType);Vi(A,z,R,U.keyType)}if(N>=64)throw new et(N);for(let R=0;R<L;R++)A.emitUint8(g.OP_OPEN_CURSOR),A.emitUint8(R),A.emitUint32(r[R].rootPageId);U&&P!==-1&&(A.emitUint8(g.OP_OPEN_INDEX),A.emitUint8(P),A.emitUint32(U.index.rootPageId));for(let R=1;R<L;R++){const _t=w[R];_t&&(A.emitUint8(g.OP_OPEN_INDEX),A.emitUint8(_t.indexCursor),A.emitUint32(_t.index.rootPageId))}const x=new Array(L),st=new Array(L),ft=Array.from({length:L},()=>[]),tt=new Array(L),Ot=[];if(U&&P!==-1?U.scanType==="point"?(A.emitUint8(g.OP_INDEX_SEEK_EQ),A.emitUint8(P),A.emitUint8(0),A.emitUint8(z),A.emitUint8(U.keyType),x[0]=A.emitUint16(0)):(A.emitUint8(g.OP_INDEX_SEEK_GE),A.emitUint8(P),A.emitUint8(0),A.emitUint8(z),A.emitUint8(U.keyType),x[0]=A.emitUint16(0)):(A.emitUint8(g.OP_REWIND),A.emitUint8(0),x[0]=A.emitUint16(0)),st[0]=A.currentOffset(),_[0]&&_[0].length>0){const R=Zt(_[0]);qt(R,r[0],A,Q,ft[0],t.udfNameMap,r,v)}for(let R=1;R<L;R++){const _t=t.joinedTables[R-1],rt=w[R];if(_t.type==="left"&&(A.emitUint8(g.OP_LOAD_INT),A.emitUint8(G[R]),A.emitInt32(0)),rt&&rt.isUnique){if(Pt(A,rt.outerCol.cursor,rt.outerCol.colIdx,H,rt.outerCol.col.type),A.emitUint8(g.OP_INDEX_SEEK_EQ),A.emitUint8(rt.indexCursor),A.emitUint8(R),A.emitUint8(H),A.emitUint8(rt.outerCol.col.type),x[R]=A.emitUint16(0),st[R]=A.currentOffset(),_t.type==="inner"&&_[R]&&_[R].length>0){const Ft=Zt(_[R]);qt(Ft,r[R],A,Q,ft[R],t.udfNameMap,r,v)}_t.type==="left"&&(A.emitUint8(g.OP_LOAD_INT),A.emitUint8(G[R]),A.emitInt32(1))}else if(rt&&!rt.isUnique){Pt(A,rt.outerCol.cursor,rt.outerCol.colIdx,H,rt.outerCol.col.type),A.emitUint8(g.OP_INDEX_SEEK_GE),A.emitUint8(rt.indexCursor),A.emitUint8(R),A.emitUint8(H),A.emitUint8(rt.outerCol.col.type),x[R]=A.emitUint16(0),st[R]=A.currentOffset(),Pt(A,R,rt.innerCol.colIdx,X,rt.innerCol.col.type),A.emitUint8(g.OP_EQ),A.emitUint8(H),A.emitUint8(X);const Ft=A.emitUint16(0);if(A.emitUint8(g.OP_JUMP),ft[R].push(A.emitUint16(0)),A.patchUint16(Ft,A.currentOffset()),_t.type==="inner"&&_[R]&&_[R].length>0){const yt=Zt(_[R]);qt(yt,r[R],A,Q,ft[R],t.udfNameMap,r,v)}_t.type==="left"&&(A.emitUint8(g.OP_LOAD_INT),A.emitUint8(G[R]),A.emitInt32(1))}else{A.emitUint8(g.OP_REWIND),A.emitUint8(R),x[R]=A.emitUint16(0),st[R]=A.currentOffset();const Ft=lt(_t.leftCol,r);if(!Ft)throw new Error(`Join column "${_t.leftCol}" not found in tables`);const yt=lt(_t.rightCol,r);if(!yt)throw new Error(`Join column "${_t.rightCol}" not found in tables`);Pt(A,Ft.cursor,Ft.colIdx,H,Ft.col.type),Pt(A,yt.cursor,yt.colIdx,X,yt.col.type);let Xt;switch(_t.op){case"=":Xt=g.OP_EQ;break;case"!=":Xt=g.OP_NE;break;case">":Xt=g.OP_GT;break;case">=":Xt=g.OP_GE;break;case"<":Xt=g.OP_LT;break;case"<=":Xt=g.OP_LE;break;default:Xt=g.OP_EQ}A.emitUint8(Xt),A.emitUint8(H),A.emitUint8(X);const cn=A.emitUint16(0);if(A.emitUint8(g.OP_JUMP),ft[R].push(A.emitUint16(0)),A.patchUint16(cn,A.currentOffset()),_t.type==="inner"&&_[R]&&_[R].length>0){const me=Zt(_[R]);qt(me,r[R],A,Q,ft[R],t.udfNameMap,r,v)}_t.type==="left"&&(A.emitUint8(g.OP_LOAD_INT),A.emitUint8(G[R]),A.emitInt32(1))}}qt(I,M,A,Q,ft[L-1],t.udfNameMap,r,v);const it=!(t.orderBy!==void 0&&t.orderBy.length>0)||B;let Nt=-1;k&&it&&(A.emitUint8(g.OP_OFFSET),A.emitUint8(J),Nt=A.emitUint16(0));let Vt=N;const Rt=()=>{if(Vt>=64)throw new et(Vt);return Vt++};for(let R=0;R<gt.length;R++)q(gt[R].expr,M,A,0,ut+R,Rt,t.udfNameMap,void 0,r);A.emitUint8(g.OP_RESULT_ROW),A.emitUint8(ut),A.emitUint8(gt.length),$&&it&&(A.emitUint8(g.OP_LIMIT),A.emitUint8(K),Ot.push(A.emitUint16(0)));for(let R=L-1;R>=1;R--){const _t=A.currentOffset();R===L-1&&Nt!==-1&&A.patchUint16(Nt,_t);for(const yt of ft[R])A.patchUint16(yt,_t);const rt=w[R];if(rt&&rt.isUnique){const yt=A.currentOffset();A.patchUint16(x[R],yt)}else if(rt&&!rt.isUnique){A.emitUint8(g.OP_INDEX_NEXT),A.emitUint8(rt.indexCursor),A.emitUint8(R),tt[R]=A.emitUint16(0),A.emitUint8(g.OP_JUMP),A.emitUint16(st[R]);const yt=A.currentOffset();A.patchUint16(x[R],yt),A.patchUint16(tt[R],yt)}else{A.emitUint8(g.OP_NEXT_ROW),A.emitUint8(R),tt[R]=A.emitUint16(0),A.emitUint8(g.OP_JUMP),A.emitUint16(st[R]);const yt=A.currentOffset();A.patchUint16(x[R],yt),A.patchUint16(tt[R],yt)}if(t.joinedTables[R-1].type==="left"){A.emitUint8(g.OP_LOAD_INT),A.emitUint8(At),A.emitInt32(0),A.emitUint8(g.OP_EQ),A.emitUint8(G[R]),A.emitUint8(At);const yt=A.emitUint16(0);A.emitUint8(g.OP_JUMP);const Xt=A.emitUint16(0);A.patchUint16(yt,A.currentOffset());for(let b=0;b<gt.length;b++){const V=gt[b];let Y=-1;if(V.expr.type==="col"){const Z=lt(V.expr.name,r);Z&&(Y=Z.tableIdx)}Y>=R?(A.emitUint8(g.OP_LOAD_NULL),A.emitUint8(ut+b)):q(V.expr,M,A,0,ut+b,Rt,t.udfNameMap,void 0,r)}const cn=[];k&&it&&(A.emitUint8(g.OP_OFFSET),A.emitUint8(J),cn.push(A.emitUint16(0))),A.emitUint8(g.OP_RESULT_ROW),A.emitUint8(ut),A.emitUint8(gt.length),$&&it&&(A.emitUint8(g.OP_LIMIT),A.emitUint8(K),Ot.push(A.emitUint16(0)));const me=A.currentOffset();A.patchUint16(Xt,me);for(const b of cn)A.patchUint16(b,me)}}const Ee=A.currentOffset();for(const R of ft[0])A.patchUint16(R,Ee);U&&P!==-1?U.scanType==="point"?(A.emitUint8(g.OP_JUMP),tt[0]=A.emitUint16(0)):(A.emitUint8(g.OP_INDEX_NEXT),A.emitUint8(P),A.emitUint8(0),tt[0]=A.emitUint16(0),A.emitUint8(g.OP_JUMP),A.emitUint16(st[0])):(A.emitUint8(g.OP_NEXT_ROW),A.emitUint8(0),tt[0]=A.emitUint16(0),A.emitUint8(g.OP_JUMP),A.emitUint16(st[0]));const te=A.currentOffset();A.patchUint16(x[0],te),A.patchUint16(tt[0],te);for(const R of Ot)A.patchUint16(R,te);A.emitUint8(g.OP_HALT);const Bt=A.toByteArray();t.outputColumns&&(Bt.outputColumns=t.outputColumns);const ie=(jo=t.joinedTables)==null?void 0:jo.map((R,_t)=>{const rt=_t+1,Ft=w[rt];return{tableIndex:rt,tableName:R.table.name,scanType:Ft?"IndexScan":"TableScan",indexName:Ft?Ft.index.name:void 0}});return Bt.joinedTableScans=ie,Bt.allTables=r,Bt.inSets=D,Bt.table0Scan=U,Bt.isOrderSatisfied=B,B&&(t.isOrderSatisfied=!0),a&&(Bt.planMetrics=a,Bt.estimatedCost=a.totalCost,Bt.estimatedRows=a.estimatedRows,Bt.joinOrder=a.joinOrder),o&&(Bt.whereMetrics=o),Bt}if(W){let L;if(W.compositeValue){if(L=N++,L>=64)throw new et(L);A.emitUint8(g.OP_LOAD_BLOB),A.emitUint8(L),A.emitBytes(W.compositeValue)}else if(W.scanType==="multi_point"){if(L=N++,L>=64)throw new et(L)}else if(W.filterIndex>=0)L=W.filterIndex*2+1;else{if(L=N++,L>=64)throw new et(L);const G=ps(W.keyType);Vi(A,L,G,W.keyType)}if(W.scanType==="point"){A.emitUint8(g.OP_OPEN_CURSOR),A.emitUint8(0),A.emitUint32(M.rootPageId),A.emitUint8(g.OP_OPEN_INDEX),A.emitUint8(1),A.emitUint32(W.index.rootPageId),A.emitUint8(g.OP_INDEX_SEEK_EQ),A.emitUint8(1),A.emitUint8(0),A.emitUint8(L),A.emitUint8(W.keyType);const G=A.emitUint16(0),H=[];qt(u,M,A,Q,H,t.udfNameMap,void 0,v);let X=-1;if(k&&(A.emitUint8(g.OP_OFFSET),A.emitUint8(J),X=A.emitUint16(0)),jt){let st=N;const ft=()=>{if(st>=64)throw new et(st);return st++};for(let tt=0;tt<t.selectExprs.length;tt++)q(t.selectExprs[tt].expr,M,A,0,ut+tt,ft,t.udfNameMap);A.emitUint8(g.OP_RESULT_ROW),A.emitUint8(ut),A.emitUint8(t.selectExprs.length)}else A.emitUint8(g.OP_EMIT_ROW),A.emitUint8(0);A.emitUint8(g.OP_JUMP);const At=A.emitUint16(0),z=A.currentOffset();A.patchUint16(G,z),A.patchUint16(At,z),X!==-1&&A.patchUint16(X,z);for(const st of H)A.patchUint16(st,z);A.emitUint8(g.OP_HALT);const x=A.toByteArray();return x.indexScan=W,x.inSets=D,t.outputColumns&&(x.outputColumns=t.outputColumns),W!=null&&W.satisfiesOrderBy&&(x.isOrderSatisfied=!0,t.isOrderSatisfied=!0),a&&(x.planMetrics=a,x.estimatedCost=a.totalCost,x.estimatedRows=a.estimatedRows,x.joinOrder=a.joinOrder),x}else if(W.scanType==="multi_point"){const G=W.inValues?W.inValues.length:0;if(G===0){A.emitUint8(g.OP_HALT);const z=A.toByteArray();return z.indexScan=W,z.inSets=D,t.outputColumns&&(z.outputColumns=t.outputColumns),z}A.emitUint8(g.OP_OPEN_CURSOR),A.emitUint8(0),A.emitUint32(M.rootPageId),A.emitUint8(g.OP_OPEN_INDEX),A.emitUint8(1),A.emitUint32(W.index.rootPageId);const H=[];for(let z=0;z<G;z++){const x=W.inValues[z];Vi(A,L,x,W.keyType),A.emitUint8(g.OP_INDEX_SEEK_EQ),A.emitUint8(1),A.emitUint8(0),A.emitUint8(L),A.emitUint8(W.keyType);const st=A.emitUint16(0),ft=[];qt(u,M,A,Q,ft,t.udfNameMap,void 0,v);let tt=-1;if(k&&(A.emitUint8(g.OP_OFFSET),A.emitUint8(J),tt=A.emitUint16(0)),jt){let Nt=N;const Vt=()=>{if(Nt>=64)throw new et(Nt);return Nt++};for(let Rt=0;Rt<t.selectExprs.length;Rt++)q(t.selectExprs[Rt].expr,M,A,0,ut+Rt,Vt,t.udfNameMap);A.emitUint8(g.OP_RESULT_ROW),A.emitUint8(ut),A.emitUint8(t.selectExprs.length)}else A.emitUint8(g.OP_EMIT_ROW),A.emitUint8(0);$&&(A.emitUint8(g.OP_LIMIT),A.emitUint8(K),H.push(A.emitUint16(0)));const Ot=z===G-1;let wt=-1;Ot||(A.emitUint8(g.OP_JUMP),wt=A.emitUint16(0));const it=A.currentOffset();A.patchUint16(st,it);for(const Nt of ft)A.patchUint16(Nt,it);tt!==-1&&A.patchUint16(tt,it),wt!==-1&&A.patchUint16(wt,it)}const X=A.currentOffset();for(const z of H)A.patchUint16(z,X);A.emitUint8(g.OP_HALT);const At=A.toByteArray();return At.indexScan=W,At.inSets=D,t.outputColumns&&(At.outputColumns=t.outputColumns),W!=null&&W.satisfiesOrderBy&&(At.isOrderSatisfied=!0,t.isOrderSatisfied=!0),a&&(At.planMetrics=a,At.estimatedCost=a.totalCost,At.estimatedRows=a.estimatedRows,At.joinOrder=a.joinOrder),At}else{A.emitUint8(g.OP_OPEN_CURSOR),A.emitUint8(0),A.emitUint32(M.rootPageId),A.emitUint8(g.OP_OPEN_INDEX),A.emitUint8(1),A.emitUint32(W.index.rootPageId),A.emitUint8(g.OP_INDEX_SEEK_GE),A.emitUint8(1),A.emitUint8(0),A.emitUint8(L),A.emitUint8(W.keyType);const G=A.emitUint16(0),H=A.currentOffset(),X=[];qt(u,M,A,Q,X,t.udfNameMap,void 0,v);let At=-1;if(k&&(A.emitUint8(g.OP_OFFSET),A.emitUint8(J),At=A.emitUint16(0)),jt){let Ot=N;const wt=()=>{if(Ot>=64)throw new et(Ot);return Ot++};for(let it=0;it<t.selectExprs.length;it++)q(t.selectExprs[it].expr,M,A,0,ut+it,wt,t.udfNameMap);A.emitUint8(g.OP_RESULT_ROW),A.emitUint8(ut),A.emitUint8(t.selectExprs.length)}else A.emitUint8(g.OP_EMIT_ROW),A.emitUint8(0);let z=-1;$&&(A.emitUint8(g.OP_LIMIT),A.emitUint8(K),z=A.emitUint16(0));const x=A.currentOffset();At!==-1&&A.patchUint16(At,x);for(const Ot of X)A.patchUint16(Ot,x);A.emitUint8(g.OP_INDEX_NEXT),A.emitUint8(1),A.emitUint8(0);const st=A.emitUint16(0);A.emitUint8(g.OP_JUMP),A.emitUint16(H);const ft=A.currentOffset();A.patchUint16(G,ft),A.patchUint16(st,ft),z!==-1&&A.patchUint16(z,ft),A.emitUint8(g.OP_HALT);const tt=A.toByteArray();return tt.indexScan=W,tt.inSets=D,t.outputColumns&&(tt.outputColumns=t.outputColumns),W!=null&&W.satisfiesOrderBy&&(tt.isOrderSatisfied=!0,t.isOrderSatisfied=!0),a&&(tt.planMetrics=a,tt.estimatedCost=a.totalCost,tt.estimatedRows=a.estimatedRows,tt.joinOrder=a.joinOrder),tt}}A.emitUint8(g.OP_OPEN_CURSOR),A.emitUint8(0),A.emitUint32(M.rootPageId),A.emitUint8(g.OP_REWIND),A.emitUint8(0);const nn=A.emitUint16(0),sn=A.currentOffset(),rn=[];qt(u,M,A,Q,rn,t.udfNameMap,void 0,v);let ke=-1;if(k&&(A.emitUint8(g.OP_OFFSET),A.emitUint8(J),ke=A.emitUint16(0)),jt){let L=N;const G=()=>{if(L>=64)throw new et(L);return L++};for(let H=0;H<t.selectExprs.length;H++)q(t.selectExprs[H].expr,M,A,0,ut+H,G,t.udfNameMap);A.emitUint8(g.OP_RESULT_ROW),A.emitUint8(ut),A.emitUint8(t.selectExprs.length)}else A.emitUint8(g.OP_EMIT_ROW),A.emitUint8(0);let he=-1;$&&(A.emitUint8(g.OP_LIMIT),A.emitUint8(K),he=A.emitUint16(0));const Qn=A.currentOffset();ke!==-1&&A.patchUint16(ke,Qn);for(const L of rn)A.patchUint16(L,Qn);A.emitUint8(g.OP_NEXT_ROW),A.emitUint8(0);const de=A.emitUint16(0);A.emitUint8(g.OP_JUMP),A.emitUint16(sn);const on=A.currentOffset();A.patchUint16(nn,on),A.patchUint16(de,on),he!==-1&&A.patchUint16(he,on),A.emitUint8(g.OP_HALT);const xt=A.toByteArray();return xt.inSets=D,t.outputColumns&&(xt.outputColumns=t.outputColumns),o&&(xt.whereMetrics=o),a&&(xt.planMetrics=a,xt.estimatedCost=a.totalCost,xt.estimatedRows=a.estimatedRows,xt.joinOrder=a.joinOrder),xt}const hl=new TextDecoder;function Ho(t,e){const n=[],s=new DataView(t.buffer,t.byteOffset,t.byteLength);let i=0;const r=a=>{var l;return(l=e==null?void 0:e.columns[a])!=null&&l.name?`'${e.columns[a].name}'`:`col_${a}`},o=a=>`0x${a.toString(16).padStart(4,"0")}`;for(;i<t.byteLength;){const a=i,l=t[i++];switch(l){case g.OP_HALT:n.push({addr:a,opcode:"OP_HALT",p1:"",p2:"",p3:"",comment:"Halt VM execution (STATUS_DONE)"});break;case g.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 g.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 g.OP_INDEX_SEEK_EQ:{const c=t[i++],u=t[i++],E=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[${E}], type=${f}`,p3:o(_),comment:`Seek exact key in index; position data cursor or jump to ${o(_)} if not found`});break}case g.OP_INDEX_SEEK_GE:{const c=t[i++],u=t[i++],E=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[${E}], type=${f}`,p3:o(_),comment:`Seek first entry >= key in index; position data cursor or jump to ${o(_)} if EOF`});break}case g.OP_INDEX_NEXT:{const c=t[i++],u=t[i++],E=s.getUint16(i,!0);i+=2,n.push({addr:a,opcode:"OP_INDEX_NEXT",p1:`idx=c[${c}], data=c[${u}]`,p2:o(E),p3:"",comment:`Advance index cursor to next entry; jump to ${o(E)} if EOF`});break}case g.OP_REWIND:{const c=t[i++],u=s.getUint16(i,!0);i+=2,n.push({addr:a,opcode:"OP_REWIND",p1:`c[${c}]`,p2:o(u),p3:"",comment:`Rewind cursor to first row; jump to ${o(u)} if empty`});break}case g.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:o(u),p3:"",comment:`Advance cursor to next row; jump to ${o(u)} if EOF`});break}case g.OP_LAST:{const c=t[i++],u=s.getUint16(i,!0);i+=2,n.push({addr:a,opcode:"OP_LAST",p1:`c[${c}]`,p2:o(u),p3:"",comment:`Position cursor to last row; jump to ${o(u)} if empty`});break}case g.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:o(u),p3:"",comment:`Advance cursor to previous row; jump to ${o(u)} if BOF`});break}case g.OP_COLUMN_INT:{const c=t[i++],u=t[i++],E=t[i++];n.push({addr:a,opcode:"OP_COLUMN_INT",p1:`c[${c}]`,p2:`${u} (${r(u)})`,p3:`r[${E}]`,comment:`Read ${r(u)} as INT into r[${E}]`});break}case g.OP_COLUMN_FLOAT:{const c=t[i++],u=t[i++],E=t[i++];n.push({addr:a,opcode:"OP_COLUMN_FLOAT",p1:`c[${c}]`,p2:`${u} (${r(u)})`,p3:`r[${E}]`,comment:`Read ${r(u)} as FLOAT into r[${E}]`});break}case g.OP_COLUMN_TEXT:{const c=t[i++],u=t[i++],E=t[i++];n.push({addr:a,opcode:"OP_COLUMN_TEXT",p1:`c[${c}]`,p2:`${u} (${r(u)})`,p3:`r[${E}]`,comment:`Read ${r(u)} as TEXT into r[${E}]`});break}case g.OP_COLUMN_BLOB:{const c=t[i++],u=t[i++],E=t[i++];n.push({addr:a,opcode:"OP_COLUMN_BLOB",p1:`c[${c}]`,p2:`${u} (${r(u)})`,p3:`r[${E}]`,comment:`Read ${r(u)} as BLOB into r[${E}]`});break}case g.OP_COLUMN_UUID:{const c=t[i++],u=t[i++],E=t[i++];n.push({addr:a,opcode:"OP_COLUMN_UUID",p1:`c[${c}]`,p2:`${u} (${r(u)})`,p3:`r[${E}]`,comment:`Read ${r(u)} as UUID into r[${E}]`});break}case g.OP_COLUMN_ULID:{const c=t[i++],u=t[i++],E=t[i++];n.push({addr:a,opcode:"OP_COLUMN_ULID",p1:`c[${c}]`,p2:`${u} (${r(u)})`,p3:`r[${E}]`,comment:`Read ${r(u)} as ULID into r[${E}]`});break}case g.OP_IS_NULL:{const c=t[i++],u=t[i++],E=s.getUint16(i,!0);i+=2,n.push({addr:a,opcode:"OP_IS_NULL",p1:`c[${c}]`,p2:`${u} (${r(u)})`,p3:o(E),comment:`If ${r(u)} IS NULL -> jump to ${o(E)}`});break}case g.OP_IS_NOT_NULL:{const c=t[i++],u=t[i++],E=s.getUint16(i,!0);i+=2,n.push({addr:a,opcode:"OP_IS_NOT_NULL",p1:`c[${c}]`,p2:`${u} (${r(u)})`,p3:o(E),comment:`If ${r(u)} IS NOT NULL -> jump to ${o(E)}`});break}case g.OP_EQ:case g.OP_NE:case g.OP_GT:case g.OP_GE:case g.OP_LT:case g.OP_LE:{const c={[g.OP_EQ]:"OP_EQ",[g.OP_NE]:"OP_NE",[g.OP_GT]:"OP_GT",[g.OP_GE]:"OP_GE",[g.OP_LT]:"OP_LT",[g.OP_LE]:"OP_LE"},u={[g.OP_EQ]:"==",[g.OP_NE]:"!=",[g.OP_GT]:">",[g.OP_GE]:">=",[g.OP_LT]:"<",[g.OP_LE]:"<="},E=t[i++],f=t[i++],_=s.getUint16(i,!0);i+=2,n.push({addr:a,opcode:c[l],p1:`r[${E}]`,p2:`r[${f}]`,p3:o(_),comment:`If r[${E}] ${u[l]} r[${f}] -> jump to ${o(_)}`});break}case g.OP_JUMP:{const c=s.getUint16(i,!0);i+=2,n.push({addr:a,opcode:"OP_JUMP",p1:o(c),p2:"",p3:"",comment:`Unconditional jump to ${o(c)}`});break}case g.OP_STR_LIKE:case g.OP_STR_NOT_LIKE:case g.OP_STR_CONTAINS:case g.OP_STR_STARTS_WITH:case g.OP_STR_ENDS_WITH:{const c={[g.OP_STR_LIKE]:"OP_STR_LIKE",[g.OP_STR_NOT_LIKE]:"OP_STR_NOT_LIKE",[g.OP_STR_CONTAINS]:"OP_STR_CONTAINS",[g.OP_STR_STARTS_WITH]:"OP_STR_STARTS_WITH",[g.OP_STR_ENDS_WITH]:"OP_STR_ENDS_WITH"},u={[g.OP_STR_LIKE]:"LIKE",[g.OP_STR_NOT_LIKE]:"NOT LIKE",[g.OP_STR_CONTAINS]:"CONTAINS",[g.OP_STR_STARTS_WITH]:"STARTS_WITH",[g.OP_STR_ENDS_WITH]:"ENDS_WITH"},E=t[i++],f=t[i++],_=s.getUint16(i,!0);i+=2,n.push({addr:a,opcode:c[l],p1:`r[${E}]`,p2:`r[${f}]`,p3:o(_),comment:`If r[${E}] ${u[l]} r[${f}] -> jump to ${o(_)}`});break}case g.OP_IN:{const c=t[i++],u=s.getUint16(i,!0);i+=2;const E=s.getUint16(i,!0);i+=2,n.push({addr:a,opcode:"OP_IN",p1:`r[${c}]`,p2:`set[${u}]`,p3:o(E),comment:`If r[${c}] IN set[${u}] -> jump to ${o(E)}`});break}case g.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 g.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 g.OP_LOAD_TEXT:{const c=t[i++],u=s.getUint16(i,!0);i+=2;const E=new Uint8Array(t.buffer,t.byteOffset+i,u),f=hl.decode(E);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 g.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 g.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 g.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 g.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 g.OP_OFFSET:{const c=t[i++],u=s.getUint16(i,!0);i+=2,n.push({addr:a,opcode:"OP_OFFSET",p1:`r[${c}]`,p2:o(u),p3:"",comment:`If r[${c}] > 0 -> decrement and skip row to ${o(u)}`});break}case g.OP_LIMIT:{const c=t[i++],u=s.getUint16(i,!0);i+=2,n.push({addr:a,opcode:"OP_LIMIT",p1:`r[${c}]`,p2:o(u),p3:"",comment:`If r[${c}] <= 1 -> halt to ${o(u)}, else decrement`});break}case g.OP_CALL_UDF:{const c=s.getUint16(i,!0);i+=2;const u=t[i++],E=t[i++],f=t[i++];n.push({addr:a,opcode:"OP_CALL_UDF",p1:`udf#${c}`,p2:`r[${u}..${u+E-1}]`,p3:`r[${f}]`,comment:`Call UDF #${c} with ${E} args -> r[${f}]`});break}case g.OP_STR_LOWER:case g.OP_STR_UPPER:case g.OP_STR_LENGTH:case g.OP_STR_TRIM:case g.OP_MATH_ABS:case g.OP_MATH_ROUND:case g.OP_MATH_FLOOR:case g.OP_MATH_CEIL:{const c={[g.OP_STR_LOWER]:"OP_STR_LOWER",[g.OP_STR_UPPER]:"OP_STR_UPPER",[g.OP_STR_LENGTH]:"OP_STR_LENGTH",[g.OP_STR_TRIM]:"OP_STR_TRIM",[g.OP_MATH_ABS]:"OP_MATH_ABS",[g.OP_MATH_ROUND]:"OP_MATH_ROUND",[g.OP_MATH_FLOOR]:"OP_MATH_FLOOR",[g.OP_MATH_CEIL]:"OP_MATH_CEIL"},u=t[i++],E=t[i++];n.push({addr:a,opcode:c[l],p1:`r[${u}]`,p2:`r[${E}]`,p3:"",comment:`${c[l]}: r[${E}] = ${c[l].toLowerCase()}(r[${u}])`});break}case g.OP_STR_SUBSTR:{const c=t[i++],u=t[i++],E=t[i++],f=t[i++];n.push({addr:a,opcode:"OP_STR_SUBSTR",p1:`r[${c}]`,p2:`start=r[${u}], len=r[${E}]`,p3:`r[${f}]`,comment:`Extract substring from r[${c}] into r[${f}]`});break}case g.OP_ADD:case g.OP_SUB:case g.OP_MUL:case g.OP_DIV:case g.OP_MOD:{const c={[g.OP_ADD]:"OP_ADD",[g.OP_SUB]:"OP_SUB",[g.OP_MUL]:"OP_MUL",[g.OP_DIV]:"OP_DIV",[g.OP_MOD]:"OP_MOD"},u=t[i++],E=t[i++],f=t[i++];n.push({addr:a,opcode:c[l],p1:`r[${u}]`,p2:`r[${E}]`,p3:`r[${f}]`,comment:`${c[l]}: r[${f}] = r[${u}] ${c[l].replace("OP_","")} r[${E}]`});break}case g.OP_STR_CONCAT:case g.OP_COALESCE:{const c={[g.OP_STR_CONCAT]:"OP_STR_CONCAT",[g.OP_COALESCE]:"OP_COALESCE"},u=t[i++],E=t[i++],f=t[i++];n.push({addr:a,opcode:c[l],p1:`r[${u}..${u+E-1}]`,p2:`count=${E}`,p3:`r[${f}]`,comment:`${c[l]}: r[${f}]`});break}case g.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 g.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 g.OP_SORTER_INSERT:{const c=t[i++],u=t[i++],E=t[i++],f=t[i++];n.push({addr:a,opcode:"OP_SORTER_INSERT",p1:`s[${c}]`,p2:`r[${u}..+${E}]`,p3:`c[${f}]`,comment:`Insert row from cursor ${f} into sorter ${c}`});break}case g.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 g.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:o(u),p3:"",comment:`Emit next sorted row from sorter ${c}; jump to ${o(u)} while more rows`});break}case g.OP_AGG_INIT:{const c=t[i++],u=t[i++],E=t[i++],f=t[i++];n.push({addr:a,opcode:"OP_AGG_INIT",p1:`agg[${c}]`,p2:`keys=r[${u}..+${E}]`,p3:`mode=${f===0?"hash":"stream"}`,comment:`Initialize aggregator ${c} (${f===0?"hash table":"stream"})`});break}case g.OP_AGG_STEP:{const c=t[i++],u=t[i++],E=t[i++],f=t[i++],_=t[i++],d=["COUNT","SUM","AVG","MIN","MAX"];n.push({addr:a,opcode:"OP_AGG_STEP",p1:`agg[${c}]`,p2:`val=${f===255?"*":`r[${f}]`}`,p3:d[_]??`${_}`,comment:`Update accumulator ${d[_]??_} for group r[${u}..+${E}]`});break}case g.OP_AGG_NEXT:{const c=t[i++],u=t[i++],E=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[${E}]`,p3:o(f),comment:`Iterate next group bucket; jump to ${o(f)}`});break}case g.OP_AGG_FINAL:{const c=t[i++],u=t[i++],E=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[${E}]`,p3:_[f]??`${f}`,comment:`Finalize ${_[f]??f} into r[${E}]`});break}case g.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:o(u),p3:"",comment:`Jump to ${o(u)} if r[${c}] is NULL`});break}case g.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:o(u),p3:"",comment:`Jump to ${o(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 Vo(t){const e=(i,r)=>i.padEnd(r," "),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(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&>.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
|
|
2
2
|
`;s+="-".repeat(95)+`
|
|
3
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 Tt(t){if(t instanceof nt||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:at(e),colName:e}:{colName:e}}return{}}function Yi(t){const e=[];function n(s){if(s.type==="fn"){const i=s.name.toLowerCase();if(fe(i)){const r=s.args[0],o=r&&r.type==="col"&&r.name!=="*"?r.name:void 0;e.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(t),e}function Us(t){if(!t)return[];if(Array.isArray(t)){const e=[];for(const n of t)e.push(...Us(n));return e}if(t instanceof nt||typeof t=="object"&&t!==null&&"node"in t){const e=t.node;return[{alias:Yt(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=gs(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=gs(`${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=gs(`${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 ot(t){if(typeof t=="string"){const e=t.trim();if(fe(e))throw new Yn(e);if(e.includes("("))try{const n=at(e);be(n,"where")}catch(n){if(n instanceof Yn)throw n}}else t instanceof nt||typeof t=="object"&&t!==null&&"node"in t?be(t.node,"where"):typeof t=="object"&&t!==null&&"type"in t&&be(t,"where")}class Ht{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 r=i!==void 0?s:"=",o=i!==void 0?i:s;return this.joins.push({type:"inner",table:e,leftCol:n,op:r,rightCol:o}),this}innerJoin(e,n,s,i){return this.join(e,n,s,i)}leftJoin(e,n,s,i){const r=i!==void 0?s:"=",o=i!==void 0?i:s;return this.joins.push({type:"left",table:e,leftCol:n,op:r,rightCol:o}),this}getJoins(){return this.joins}where(e,n,s){if(typeof e=="function"){const i=new Ht(this.db,this.tableName);e(i);const r=i.getRootFilter();r&&this.filters.push(r)}else if(n===void 0&&s===void 0)if(typeof e=="string"){ot(e);const i=at(e);this.filters.push({type:"expr",expr:i})}else e instanceof nt||typeof e=="object"&&e!==null&&"node"in e?(ot(e),this.filters.push({type:"expr",expr:e.node})):typeof e=="object"&&e!==null&&"type"in e&&(ot(e),this.filters.push({type:"expr",expr:e}));else{if(ot(e),ot(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=Tt(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 Ht(this.db,this.tableName);e(i);const r=i.getRootFilter();r&&this.addOrFilter(r)}else if(n===void 0&&s===void 0)if(typeof e=="string"){ot(e);const i=at(e);this.addOrFilter({type:"expr",expr:i})}else e instanceof nt||typeof e=="object"&&e!==null&&"node"in e?(ot(e),this.addOrFilter({type:"expr",expr:e.node})):typeof e=="object"&&e!==null&&"type"in e&&(ot(e),this.addOrFilter({type:"expr",expr:e}));else{if(ot(e),ot(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=Tt(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 Ht(this.db,this.tableName);e(i);const r=i.getRootFilter();r&&this.filters.push({type:"not",child:r})}else if(n===void 0&&s===void 0)if(typeof e=="string"){ot(e);const i=at(e);this.filters.push({type:"not",child:{type:"expr",expr:i}})}else e instanceof nt||typeof e=="object"&&e!==null&&"node"in e?(ot(e),this.filters.push({type:"not",child:{type:"expr",expr:e.node}})):typeof e=="object"&&e!==null&&"type"in e&&(ot(e),this.filters.push({type:"not",child:{type:"expr",expr:e}}));else{ot(e),ot(s);const i=Tt(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 Ht(this.db,this.tableName);e(i);const r=i.getRootFilter();r&&this.addOrFilter({type:"not",child:r})}else if(n===void 0&&s===void 0)if(typeof e=="string"){ot(e);const i=at(e);this.addOrFilter({type:"not",child:{type:"expr",expr:i}})}else e instanceof nt||typeof e=="object"&&e!==null&&"node"in e?(ot(e),this.addOrFilter({type:"not",child:{type:"expr",expr:e.node}})):typeof e=="object"&&e!==null&&"type"in e&&(ot(e),this.addOrFilter({type:"not",child:{type:"expr",expr:e}}));else{ot(e),ot(s);const i=Tt(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 ot(e),this.filters.push({type:"null",colName:e,isNull:!0}),this}whereNotNull(e){return ot(e),this.filters.push({type:"null",colName:e,isNull:!1}),this}orWhereNull(e){return ot(e),this.addOrFilter({type:"null",colName:e,isNull:!0}),this}orWhereNotNull(e){return ot(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(ot(e),!Array.isArray(n))throw new TypeError("WebDB: whereIn requires an array of values");if(n.length>bt)throw new RangeError(`WebDB: whereIn list exceeds maximum limit of ${bt} elements`);const s=Tt(e);return this.filters.push({type:"in",colName:s.colName,expr:s.expr,values:n,notIn:!1}),this}whereNotIn(e,n){if(ot(e),!Array.isArray(n))throw new TypeError("WebDB: whereNotIn requires an array of values");if(n.length>bt)throw new RangeError(`WebDB: whereNotIn list exceeds maximum limit of ${bt} elements`);const s=Tt(e);return this.filters.push({type:"in",colName:s.colName,expr:s.expr,values:n,notIn:!0}),this}orWhereIn(e,n){if(ot(e),!Array.isArray(n))throw new TypeError("WebDB: orWhereIn requires an array of values");if(n.length>bt)throw new RangeError(`WebDB: orWhereIn list exceeds maximum limit of ${bt} elements`);const s=Tt(e);return this.addOrFilter({type:"in",colName:s.colName,expr:s.expr,values:n,notIn:!1}),this}orWhereNotIn(e,n){if(ot(e),!Array.isArray(n))throw new TypeError("WebDB: orWhereNotIn requires an array of values");if(n.length>bt)throw new RangeError(`WebDB: orWhereNotIn list exceeds maximum limit of ${bt} elements`);const s=Tt(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=Tt(e);this.orderKeys.push({colName:i.colName??e,expr:i.expr,direction:n,nullOrder:s})}else if(e instanceof nt||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 r=Tt(i);this.orderKeys.push({colName:r.colName??i,expr:r.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 nt||typeof e=="object"&&e!==null&&"node"in e)this.groupKeys.push({expr:e.node}),this.groupCols.push(Yt(e.node));else if(typeof e=="object"&&e!==null&&"type"in e)this.groupKeys.push({expr:e}),this.groupCols.push(Yt(e));else if(typeof e=="string"){const n=Tt(e);this.groupKeys.push({colName:n.colName??e,expr:n.expr}),this.groupCols.push(e)}}registerAggregatesFromFilter(e){const n=(s,i)=>{if(i){const r=Yi(i);for(const o of r)this.aggExprs.some(l=>l.func===o.func&&(l.colName===o.colName||l.colName===void 0&&o.colName===void 0))||this.aggExprs.push(o)}else if(s&&s.includes("("))try{const r=at(s),o=Yi(r);for(const a of o)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 Ht(this.db,this.tableName);e(i);const r=i.getRootHavingFilter();r&&(this.havingFilters.push(r),this.registerAggregatesFromFilter(r))}else if(n===void 0&&s===void 0){if(typeof e=="string"){const r={type:"expr",expr:at(e)};this.havingFilters.push(r),this.registerAggregatesFromFilter(r)}else if(e instanceof nt||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=Tt(e),r={type:"cmp",colName:i.colName,expr:i.expr,op:n,value:s};this.havingFilters.push(r),this.registerAggregatesFromFilter(r)}return this}orHaving(e,n,s){if(typeof e=="function"){const i=new Ht(this.db,this.tableName);e(i);const r=i.getRootHavingFilter();r&&(this.addHavingOrFilter(r),this.registerAggregatesFromFilter(r))}else if(n===void 0&&s===void 0){if(typeof e=="string"){const r={type:"expr",expr:at(e)};this.addHavingOrFilter(r),this.registerAggregatesFromFilter(r)}else if(e instanceof nt||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=Tt(e),r={type:"cmp",colName:i.colName,expr:i.expr,op:n,value:s};this.addHavingOrFilter(r),this.registerAggregatesFromFilter(r)}return this}havingNot(e,n,s){if(typeof e=="function"){const i=new Ht(this.db,this.tableName);e(i);const r=i.getRootHavingFilter();if(r){const o={type:"not",child:r};this.havingFilters.push(o),this.registerAggregatesFromFilter(o)}}else if(n===void 0&&s===void 0){if(typeof e=="string"){const r={type:"not",child:{type:"expr",expr:at(e)}};this.havingFilters.push(r),this.registerAggregatesFromFilter(r)}else if(e instanceof nt||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=Tt(e),r={type:"not",child:{type:"cmp",colName:i.colName,expr:i.expr,op:n,value:s}};this.havingFilters.push(r),this.registerAggregatesFromFilter(r)}return this}orHavingNot(e,n,s){if(typeof e=="function"){const i=new Ht(this.db,this.tableName);e(i);const r=i.getRootHavingFilter();if(r){const o={type:"not",child:r};this.addHavingOrFilter(o),this.registerAggregatesFromFilter(o)}}else if(n===void 0&&s===void 0){if(typeof e=="string"){const r={type:"not",child:{type:"expr",expr:at(e)}};this.addHavingOrFilter(r),this.registerAggregatesFromFilter(r)}else if(e instanceof nt||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=Tt(e),r={type:"not",child:{type:"cmp",colName:i.colName,expr:i.expr,op:n,value:s}};this.addHavingOrFilter(r),this.registerAggregatesFromFilter(r)}return this}havingRaw(e){return this.having(e)}orHavingRaw(e){return this.orHaving(e)}havingNull(e){const n=Tt(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=Tt(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=Tt(e),s={type:"null",colName:n.colName,expr:n.expr,isNull:!0};return this.addHavingOrFilter(s),this.registerAggregatesFromFilter(s),this}orHavingNotNull(e){const n=Tt(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(...Us(e));for(const i of n)s.push(...Us(i));this.selectFields.push(...s);for(const i of s)if(i.expr&&i.expr.type==="fn"){const r=i.expr.name.toLowerCase();if(fe(r)&&!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:r,colName:l,alias:i.alias})}}else if(typeof i.fn=="string"){const r=i.fn.toLowerCase();fe(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}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 r=i.alias;if(e[r]!==void 0)s[r]=e[r];else if(i.expr&&e[Yt(i.expr)]!==void 0)s[r]=e[Yt(i.expr)];else if(i.sourceCol!==void 0&&e[i.sourceCol]!==void 0)s[r]=e[i.sourceCol];else if(i.expr){let o;typeof this.db.getUdf=="function"&&(o=a=>{var l,c;return(c=(l=this.db.getUdf(a))==null?void 0:l.def)==null?void 0:c.call}),s[r]=wn(i.expr,e,o)}else s[r]=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?Yt(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 r of this.selectFields)if((r.sourceCol===s||r.sourceCol===i||r.alias===s||r.alias===i)&&e[r.alias]!==void 0)return e[r.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 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(){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 r=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 o=r;const a=r.isOrderSatisfied===!0;return(i||n)&&s&&!a&&(o=this.sortAggregatedRows(o),n&&(this.offsetCount!==null&&this.offsetCount>0&&(o=o.slice(this.offsetCount)),this.limitCount!==null&&this.limitCount>=0&&(o=o.slice(0,this.limitCount)))),this.selectFields.length>0&&(o=o.map(l=>this.projectRow(l))),o}async first(){const e=await this.limit(1).toArray();return e.length>0?e[0]:null}}class Zi{constructor(e,n,s,i,r="js",o,a){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);this.vfs=e,this.io=n,this.driver=s,this.coordinator=i,this.coreMode=r,this.wasmCore=o,this.planner=a,this.vmCtx=Ir(),this.coordinator.setOnCrossTabInvalidated(async()=>{this.tableMetaCache.clear(),this.tableTailPages.clear(),this.indexTailPages.clear();const l=Nn(this.driver.getSlotDataView(0));for(const c of l){let u=c.colCatalogPageId;for(;u!==0;){const E=await this.driver.acquireAndPinPage(u),f=this.driver.getSlotDataView(E);u=Qe(f,0).nextColCatalogPageId}}})}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 Rr(e.name):n==="opfs"?s=new Qr(e.name):s=new Dr;const i=e.slotCount??Oe,r=e.maxQueryMemory??Se,o=Co(Math.max(i,Oe),r),a=new si({vfs:s,memory:o}),l=new Oo({io:a,memory:o,slotCount:i,maxQueryMemory:r,useDefaultLayoutOffsets:!0}),c=e.name&&s.name!=="memory"?`webdb_lock_${s.name}_${e.name}`:void 0,u=new No(s,l,a,c);l.setTransactionCoordinator(u),await u.leaseQueue.enqueue(async()=>{await Di(s);const _=await s.readPage(1);if(!_)Ao(l.getSlotDataView(0)),l.markDirty(0),await l.flushSlot(0);else{l.getPageBytesInSlot(0).set(_),l.clearDirty(0),Oi(l.getSlotDataView(0),!0);const d=Nn(l.getSlotDataView(0));for(const m of d){let I=m.colCatalogPageId;for(;I!==0;){const p=await l.acquireAndPinPage(I),T=l.getSlotDataView(p);I=Qe(T,0).nextColCatalogPageId}}}u.recordDiskPage1State()});const E=e.core??"js";let f;return E==="wasm"&&(f=Uo(o,e.wasmBinary?new Uint8Array(e.wasmBinary):void 0)),new Zi(s,a,l,u,E,f,e.planner)}getPlanner(){return this.planner}setPlanner(e){return this.planner=e,this}async createTable(e,n){return this.coordinator.leaseQueue.enqueue(()=>this._createTableInternal(e,n),this.currentLeaseId??void 0)}async _createTableInternal(e,n){const s=this.pool.getSlotDataView(0),r=To(s,{allocateNewPage:()=>{const l=s.getUint32(12,!0)+1;return s.setUint32(12,l,!0),this.pool.markDirty(0),l},getPageBytes:a=>{let l=this.pool.getResidentSlot(a);return l===-1&&(l=a<=this.pool.slotCount?a-1:1,this.pool.assignSlot(l,a)),this.pool.getPageBytesInSlot(l)},markPageDirty:a=>{const l=this.pool.getResidentSlot(a);l!==-1&&this.pool.markDirty(l)}},e,n);let o=r.colCatalogPageId;for(;o!==0;){const a=await this.driver.acquireAndPinPage(o);o=Qe(this.pool.getSlotDataView(a),0).nextColCatalogPageId}return this.coordinator.isInTransaction()||await this.driver.flushAllDirty(),this.tableMetaCache.delete(e.toLowerCase()),r}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),r=Re(i,e);if(r===-1)throw new Vn(e);let a=Ae(i,r).colCatalogPageId;for(;a!==0;){await this.driver.acquirePage(a);const u=this.pool.getResidentSlot(a);a=Qe(this.pool.getSlotDataView(u),0).nextColCatalogPageId}const c=Li(i,{getPageBytes:u=>{const E=this.pool.getResidentSlot(u);return E!==-1?this.pool.getPageBytesInSlot(E):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=Nn(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 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),l=He(a,0);if(l===Be){this.driver.forceUnpinPage(r);continue}if(n.push(r),l===qs||l===dr){const c=dt(a,0);for(let E=0;E<c;E++){const f=ht(a,0,E);if(f>0&&f+4<=4096){const _=a.getUint32(f,!0);_>1&&!s.has(_)&&i.push(_)}}const u=kt(a,0);u>1&&!s.has(u)&&i.push(u)}else if(l===Hn||l===js){const c=kt(a,0);c>1&&!s.has(c)&&i.push(c)}}for(const r of n)this.driver.forceUnpinPage(r),await this.driver.freePage(r,!0)}async dropTable(e){return this.coordinator.leaseQueue.enqueue(()=>this._dropTableInternal(e),this.currentLeaseId??void 0)}async _dropTableInternal(e){var o;this.tableMetaCache.delete(e.toLowerCase()),this.tableTailPages.delete(e);const n=this.pool.getSlotDataView(0),s=Re(n,e);if(s===-1)throw new Vn(e);const i=Ae(n,s);for(let a=0;a<un;a++){const l=Bn(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)),wi(n,a))}i.rootPageId>1&&await this.freeTableTreePages(i.rootPageId);let r=i.colCatalogPageId;for(;r>1;){const a=await this.driver.acquirePage(r),l=this.pool.getSlotDataView(a);if(He(l,0)===Be){this.driver.forceUnpinPage(r);break}const E=Qe(l,0).nextColCatalogPageId;this.driver.forceUnpinPage(r),await this.driver.freePage(r,!0),r=E}Eo(n,s),Sn(n),Je(n),Ke(n),this.pool.markDirty(0),this.coordinator.isInTransaction()||await this.driver.flushAllDirty(),((o=this.vmCtx.table)==null?void 0:o.name.toLowerCase())===e.toLowerCase()&&(this.vmCtx.table=null)}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),r=Array.isArray(n)?n:[n];if(r.length===0)throw new Error(`At least one column must be specified for createIndex on table "${e}"`);if(r.length>8)throw new Error(`Maximum 8 columns allowed per index (requested ${r.length})`);const o=[];for(const F of r){const P=i.columns.findIndex(w=>w.name===F);if(P===-1)throw new yr(F,e);o.push(P)}const a=(s==null?void 0:s.name)??`idx_${e}_${r.join("_")}`,l=this.pool.getSlotDataView(0);if(Pi(l,a)!==null)throw new Ks(a);const E=ze(l,i.tableId).find(F=>{if(F.columnCount!==o.length)return!1;for(let P=0;P<F.columnCount;P++)if(F.columnIndices[P]!==o[P])return!1;return!0});if(E)throw new Ks(E.name||a);const f=Bi(l);if(f===-1)throw new Sr(un,un);const _=await this.driver.allocateAndPinPage(),d=this.pool.getResidentSlot(_),m=this.pool.getSlotDataView(d);os(m,0,0),this.pool.markDirty(d),this.pool.unpinSlot(d);const I=!!(s!=null&&s.unique);let p=i.rootPageId;for(;p!==0;){let F=await this.driver.acquirePage(p),P=this.pool.getSlotDataView(F);const w=dt(P,0),O=kt(P,0);for(let D=0;D<w;D++){F=await this.driver.acquirePage(p),P=this.pool.getSlotDataView(F);const v=ht(P,0,D),Q=_i(i.columns,P,v);if(Q){const A=BigInt(p)<<16n|BigInt(D),{keyVal:N,keyType:k}=this.extractIndexKey(i.columns,{columnCount:o.length,columnIndices:o},Q);if(N!=null){if(I&&await this.probeIndexUnique(_,k,N))throw await this.freeTableTreePages(_),this.indexTailPages.delete(_),new Xn(`Duplicate key value violates unique constraint "${a}" on table "${e}"`);await this.insertIntoIndex(_,k,N,A)}}}p=O}const T=[0,0,0,0,0,0,0,0],U=[0,0,0,0,0,0,0,0];for(let F=0;F<o.length&&F<8;F++)T[F]=o[F];const B=I?Ut.UNIQUE:0;Ni(l,f,{indexId:f+1,tableId:i.tableId,rootPageId:_,columnCount:o.length,flags:B,columnIndices:T,colDirections:U,name:a}),Sn(l),Je(l),Ke(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=Pi(n,e);if(!s)throw new Cr(e);s.desc.rootPageId>1&&(await this.freeTableTreePages(s.desc.rootPageId),this.indexTailPages.delete(s.desc.rootPageId)),wi(n,s.slotIdx),Sn(n),Je(n),Ke(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 ze(n,i.tableId)}const s=[];for(let i=0;i<un;i++){const r=Bn(n,i);r&&s.push(r)}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:ls(e,n.columnIndices,n.columnCount,s),keyType:y.BLOB}}async probeIndexUnique(e,n,s){let i=e;for(;i!==0;){const r=await this.driver.acquirePage(i),o=this.pool.getSlotDataView(r);if(dt(o,0)>0&&cs(o,0,n,s).found)return!0;i=kt(o,0)}return!1}async insertIntoIndex(e,n,s,i){let r=this.indexTailPages.get(e)??e,o=await this.driver.acquirePage(r),a=this.pool.getSlotDataView(o);for(;;){const c=kt(a,0);if(c===0)break;r=c,o=await this.driver.acquirePage(r),a=this.pool.getSlotDataView(o)}this.indexTailPages.set(e,r);let l=hi(a,0,n,s,i,this.pool.pageScratchpadOffset);if(l===-1){this.pool.pinSlot(o);try{const c=await this.driver.allocateAndPinPage(),u=this.pool.getResidentSlot(c);try{Ai(a,0,c),this.pool.markDirty(o);const E=this.pool.getSlotDataView(u);if(os(E,0,0),l=hi(E,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(o)}}else this.pool.markDirty(o)}async insert(e,n){await this.insertMany(e,[n])}async insertMany(e,n){return this.coordinator.leaseQueue.enqueue(()=>this._insertManyInternal(e,n),this.currentLeaseId??void 0)}async _insertManyInternal(e,n){if(!n||n.length===0)return;const s=await this._getTableInternal(e),i=this.pool.getSlotDataView(0),r=ze(i,s.tableId),o=r.filter(m=>(m.flags&(Ut.UNIQUE|Ut.PRIMARY))!==0),a=s.columns.find(m=>(m.flags&Ct.AUTO_INC)!==0),l=new Map;for(const m of o)l.set(m.name,new Set);let c=s.autoIncNext;const u=[];for(let m=0;m<n.length;m++){const I=n[m];for(const B of s.columns)if(B.flags&Ct.PRIMARY_KEY&&!(B.flags&Ct.AUTO_INC)&&(I[B.name]===void 0||I[B.name]===null))throw new Js(B.name,e);let p,T=I;a&&(I[a.name]===void 0||I[a.name]===null)&&(p=Number(c),c+=1n,T={...I,[a.name]:p});for(const B of o){const{keyVal:F,keyType:P}=this.extractIndexKey(s.columns,B,T);if(F!=null){const w=F instanceof Uint8Array?Array.from(F).join(","):F,O=l.get(B.name);if(O.has(w))throw new Xn(`Duplicate key value violates unique constraint "${B.name}" on table "${e}"`);if(O.add(w),await this.probeIndexUnique(B.rootPageId,P,F))throw new Xn(`Duplicate key value violates unique constraint "${B.name}" on table "${e}"`)}}const U=fi(s.columns,T);u.push({row:I,rowBytes:U,assignedAutoInc:p})}s.autoIncNext=c;let E=this.tableTailPages.get(e)??s.rootPageId,f=await this.driver.acquirePage(E),_=this.pool.getSlotDataView(f);for(;;){const m=kt(_,0);if(m===0)break;E=m,f=await this.driver.acquirePage(E),_=this.pool.getSlotDataView(f)}this.tableTailPages.set(e,E);for(let m=0;m<u.length;m++){const{row:I,rowBytes:p,assignedAutoInc:T}=u[m];a&&T!==void 0&&(I[a.name]=T),f=await this.driver.acquirePage(E),_=this.pool.getSlotDataView(f);let U=E,B=is(_,0,p,this.pool.pageScratchpadOffset);if(B===-1){const P=f;this.pool.pinSlot(P);try{const w=await this.driver.allocateAndPinPage(),O=this.pool.getResidentSlot(w);try{Ai(_,0,w),this.pool.markDirty(P);const D=this.pool.getSlotDataView(O);if(B=is(D,0,p,this.pool.pageScratchpadOffset),B===-1)throw new Error("Unexpected error: row does not fit in empty page");this.pool.markDirty(O),E=w,U=w,f=O,_=D,this.tableTailPages.set(e,w)}finally{this.pool.unpinSlot(O)}}finally{this.pool.unpinSlot(P)}}else this.pool.markDirty(f);const F=BigInt(U)<<16n|BigInt(B);for(const P of r){const{keyVal:w,keyType:O}=this.extractIndexKey(s.columns,P,I);w!=null&&await this.insertIntoIndex(P.rootPageId,O,w,F)}}const d=Re(i,e);if(d!==-1){const m=Ae(i,d);m.rowCountEstimate+=n.length,a&&(m.autoIncNext=s.autoIncNext),Si(i,d,m),Je(i),Ke(i),this.pool.markDirty(0)}this.coordinator.isInTransaction()||await this.driver.flushAllDirty()}async transaction(e){const s=(await this.coordinator.begin()).leaseId,i=new Proxy(this,{get:(r,o,a)=>{if(o==="currentLeaseId")return s;if(o==="transaction")return async c=>{const u=await this.coordinator.captureSavepoint();try{return await c(i)}catch(E){throw this.tableMetaCache.clear(),this.tableTailPages.clear(),this.indexTailPages.clear(),await this.coordinator.restoreSavepoint(u),E}};if(o==="checkpoint")return()=>this.checkpoint();if(o==="from")return c=>{const u=new Ht(i,c);return r.planner&&u.withPlanner(r.planner),u};const l=Reflect.get(r,o,a);return typeof l=="function"?l.bind(i):l}});try{const r=await e(i);return await this.coordinator.commit(s),r}catch(r){throw this.tableMetaCache.clear(),this.tableTailPages.clear(),this.indexTailPages.clear(),await this.coordinator.rollback(s),r}}registerFunction(e,n){const s=e.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)?y.INT32:y.FLOAT64:typeof o=="string"&&(i.returnType=y.TEXT)}catch{try{const o=i.call("","","","","");typeof o=="number"?i.returnType=Number.isInteger(o)?y.INT32:y.FLOAT64:typeof o=="string"&&(i.returnType=y.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(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 Ht(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,T;const i=await this._getTableInternal(e),r=[];if(s!=null&&s.joins&&s.joins.length>0){if(1+s.joins.length>16)throw new $n(1+s.joins.length,16);for(let U=0;U<s.joins.length;U++){const B=s.joins[U],F=await this._getTableInternal(B.table);r.push({type:B.type,table:F,cursor:U+1,leftCol:B.leftCol,op:B.op,rightCol:B.rightCol})}}const o=$i({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}),l=(o.allTables??(r.length>0?[i,...r.map(U=>U.table)]:[i]))[0],c=Ho(o,l),u=Vo(c),E=o.indexScan??o.table0Scan,f=E?"IndexScan":"TableScan",_=E?E.index.name:void 0,d=o.joinedTableScans,m=(I=s==null?void 0:s.joins)==null?void 0:I.map(U=>{const B=d==null?void 0:d.find(F=>F.tableName.toLowerCase()===U.table.toLowerCase());return B&&B.scanType==="IndexScan"?{...U,scanType:B.scanType,indexName:B.indexName}:U});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:m,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:((T=o.planMetrics)==null?void 0:T.sortCostAvoided)??void 0},bytecodeSize:o.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 m;const i=await this._getTableInternal(e),r=[],o=[];if(s.joins&&s.joins.length>0){if(1+s.joins.length>16)throw new $n(1+s.joins.length,16);for(let I=0;I<s.joins.length;I++){const p=s.joins[I],T=await this._getTableInternal(p.table);r.push(T),o.push({type:p.type,table:T,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 T=await this.driver.acquirePage(p),U=this.pool.getSlotDataView(T);p=kt(U,0)}for(const T of I.indexes??[]){let U=T.rootPageId;for(;U!==0;){const B=await this.driver.acquirePage(U),F=this.pool.getSlotDataView(B);U=kt(F,0)}}}let a=s.orderBy;!a&&s.sortCol&&(a=[{colName:s.sortCol,direction:s.sortDir}]);const l={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},c=$i(l),u=c.allTables??[i,...r];pr(this.vmCtx,u[0],u),c.inSets&&(this.vmCtx.inSets=c.inSets);const E=c.keyInfos??l.keyInfos;E&&(this.vmCtx.keyInfos=E);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 T=typeof p=="string"?p:p.colName??(p.expr?Yt(p.expr):"group_key"),U=i.columns.find(B=>B.name===T);U?_.push(U):_.push({name:T,type:y.TEXT,flags:Ct.NONE,colOffset:0})}for(let p=0;p<(((m=l.aggregates)==null?void 0:m.length)??0);p++){const T=l.aggregates[p],U=T.alias??(T.colName?`${T.func}_${T.colName}`:T.func),B=T.func==="count"?y.INT32:y.FLOAT64;_.push({name:U,type:B,flags:Ct.NONE,colOffset:0})}}this.vmCtx.outputColumns=_;const d=[];for(;;){const I=On(this.vmCtx,this.pool.view,c);let p=0;for(let T=0;T<this.vmCtx.resultCount;T++){const U=this.pool.view.getUint16(gn+p,!0),B=gn+p+2,F=_i(_,this.pool.view,B);d.push(F),p+=2+U}if(I===C.DONE)break;if(I===C.BUFFER_FULL)this.vmCtx.resultOffset=0,this.vmCtx.resultCount=0,this.vmCtx.status=C.RUNNING;else if(I===C.PAGE_FAULT){this.vmCtx.resultOffset=0,this.vmCtx.resultCount=0;const T=[],U=this.vmCtx.cursors??[this.vmCtx.cursor];for(const B of U)if(B&&B.pageId>1){const F=this.pool.getResidentSlot(B.pageId);F>0&&(this.pool.pinSlot(F),T.push(F))}try{await this.driver.acquirePage(this.vmCtx.fault_page_id)}finally{for(const B of T)this.pool.unpinSlot(B)}this.vmCtx.status=C.RUNNING}else throw I===C.ARENA_EXHAUSTED?(this.vmCtx.arenaOffset=0,new xs):I===C.TIMEOUT?new Pr:I===C.INVALID_BYTECODE?new wr:new Error(`VM execution error: status=${I}`)}return Object.defineProperty(d,"isOrderSatisfied",{value:c.isOrderSatisfied??!1,writable:!0,enumerable:!1,configurable:!0}),d}async checkpoint(){return this.coordinator.checkpoint()}async close(){await this.coordinator.close(),await this.driver.flushAllDirty(),await this.vfs.close()}}h.ALIGNMENT_PADDING_OFFSET=Ja,h.ALIGNMENT_PADDING_SIZE=or,h.AggregateNotAllowedInWhereError=Yn,h.BUILTIN_AGGREGATES=Bo,h.BUILTIN_SCALARS=Po,h.BYTECODE_OFFSET=lr,h.BYTECODE_SIZE=ir,h.BufferPoolDriver=Oo,h.BytecodeEmitter=Is,h.CATALOG_PAGE_HEADER_FIELDS=Da,h.CATALOG_PAGE_HEADER_OFFSET_COL_COUNT_IN_PAGE=ba,h.CATALOG_PAGE_HEADER_OFFSET_FLAGS=Qa,h.CATALOG_PAGE_HEADER_OFFSET_NEXT_COL_CATALOG_PAGE_ID=va,h.CATALOG_PAGE_HEADER_OFFSET_PAGE_CHECKSUM=Ma,h.CATALOG_PAGE_HEADER_OFFSET_PAGE_TYPE=Ra,h.CATALOG_PAGE_HEADER_OFFSET_START_COL_INDEX=Ga,h.CATALOG_PAGE_HEADER_OFFSET_TABLE_ID=ka,h.CATALOG_PAGE_HEADER_SIZE=Ps,h.COLUMN_META_FIELDS=Wa,h.COLUMN_META_OFFSET_COL_OFFSET=Xa,h.COLUMN_META_OFFSET_FLAGS=Va,h.COLUMN_META_OFFSET_NAME=$a,h.COLUMN_META_OFFSET_RESERVED=Ya,h.COLUMN_META_OFFSET_TYPE=Ha,h.COLUMN_META_SIZE=ws,h.COST_INDEX_NEXT=hs,h.COST_INDEX_SEEK=xe,h.COST_ROW_EVAL=ne,h.CURRENT_ENGINE_VERSION=Wn,h.CURRENT_MIN_READ_VERSION=hr,h.ColumnFlag=Ct,h.ColumnNotFoundError=yr,h.CorruptPageError=Pe,h.CorruptWalFrameError=mn,h.CorruptWalHeaderError=Zn,h.CostBasedPlanner=ms,h.CostBasedQueryPlanner=ol,h.CustomOrderPlanner=sl,h.CustomPlanner=ko,h.CustomQueryPlanner=il,h.DEFAULT_BUFFER_POOL_REGIONS=ja,h.DEFAULT_CACHE_SIZE_BYTES=Za,h.DEFAULT_MAX_QUERY_MEMORY=Se,h.DEFAULT_PAGE_SLOTS=qa,h.DEFAULT_PAGE_TO_SLOT_BUCKETS=Qt,h.DEFAULT_SLOT_COUNT=Oe,h.DIRTY_MASK_OFFSET=ar,h.DataType=y,h.DefaultQueryPlanner=rl,h.ExclusiveLeaseQueue=So,h.ExpressionBuilder=nt,h.FILE_HEADER_SIZE=ra,h.HEADER_OFFSET_CHANGE_COUNTER=ae,h.HEADER_OFFSET_FILE_FORMAT_VERSION=Ns,h.HEADER_OFFSET_FREE_PAGE_HEAD=ee,h.HEADER_OFFSET_MAGIC=re,h.HEADER_OFFSET_MIN_READ_VERSION=Bs,h.HEADER_OFFSET_NEXT_CATALOG_PAGE_ID=tr,h.HEADER_OFFSET_NEXT_INDEX_CATALOG_PAGE_ID=er,h.HEADER_OFFSET_PAGE_CHECKSUM=ce,h.HEADER_OFFSET_PAGE_SIZE=Ss,h.HEADER_OFFSET_RESERVED=oa,h.HEADER_OFFSET_SCHEMA_VERSION=oe,h.HEADER_OFFSET_TOTAL_PAGES=Kt,h.HeuristicPlanner=Qo,h.HeuristicQueryPlanner=al,h.INDEX_CATALOG_OFFSET=fn,h.INDEX_DESCRIPTOR_FIELDS=Ua,h.INDEX_DESCRIPTOR_OFFSET_COLUMN_COUNT=Na,h.INDEX_DESCRIPTOR_OFFSET_COLUMN_INDICES=Pa,h.INDEX_DESCRIPTOR_OFFSET_COL_DIRECTIONS=wa,h.INDEX_DESCRIPTOR_OFFSET_FLAGS=Ba,h.INDEX_DESCRIPTOR_OFFSET_INDEX_ID=Ca,h.INDEX_DESCRIPTOR_OFFSET_NAME=La,h.INDEX_DESCRIPTOR_OFFSET_RESERVED=Fa,h.INDEX_DESCRIPTOR_OFFSET_ROOT_PAGE_ID=Sa,h.INDEX_DESCRIPTOR_OFFSET_TABLE_ID=Oa,h.INDEX_DESCRIPTOR_SIZE=Ce,h.IndexAlreadyExistsError=Ks,h.IndexFlag=Ut,h.IndexNotFoundError=Cr,h.IndexedDbVfsAdapter=Rr,h.InvalidBytecodeError=wr,h.InvalidDatabaseError=Br,h.Io=si,h.MASTER_TABLE_OFFSET=An,h.MAX_COLUMNS_PER_CATALOG_PAGE=ye,h.MAX_COLUMNS_PER_TABLE=_n,h.MAX_CURSORS_PER_FRAME=sc,h.MAX_INDEXES_PAGE1=un,h.MAX_INDEXES_SYSPAGE=ca,h.MAX_IN_LIST_SIZE=bt,h.MAX_NAME_LENGTH=pe,h.MAX_REGISTERS_PER_FRAME=nc,h.MAX_ROW_SIZE=2048,h.MAX_SUBQUERY_DEPTH=ic,h.MAX_TABLES_PAGE1=Te,h.MAX_TABLES_SYSPAGE=aa,h.MAX_TABLE_INTERIOR_CELLS=zi,h.MAX_TOPK_HEAP_LIMIT=Er,h.MemoryVfsAdapter=Dr,h.NEXT_DESCRIPTOR_CATALOG_PAGE_OFFSET=la,h.NEXT_DESCRIPTOR_CATALOG_PAGE_SIZE=ua,h.NoOpPlanner=bo,h.NoOpQueryPlanner=cl,h.NotNullConstraintError=Js,h.OpCode=g,h.OpfsVfsAdapter=Qr,h.PAGE_HEADER_OFFSET_CELL_COUNT=zo,h.PAGE_HEADER_OFFSET_CHECKSUM=Ie,h.PAGE_HEADER_OFFSET_CONTENT_OFFSET=xo,h.PAGE_HEADER_OFFSET_FLAGS=Ko,h.PAGE_HEADER_OFFSET_FREE_BYTES=ta,h.PAGE_HEADER_OFFSET_NEXT_PAGE_ID=Ji,h.PAGE_HEADER_OFFSET_TYPE=ji,h.PAGE_HEADER_SIZE=Jt,h.PAGE_SCRATCHPAD_OFFSET=ur,h.PAGE_SCRATCHPAD_SIZE=rr,h.PAGE_SIZE=4096,h.PAGE_TO_SLOT_BUCKET_SIZE=le,h.PAGE_TO_SLOT_OFFSET=Dt,h.PAGE_TO_SLOT_SIZE=nr,h.PAGE_TYPE_CATALOG_PAGE=dn,h.PAGE_TYPE_FREE=Be,h.PAGE_TYPE_INDEX_INTERIOR=dr,h.PAGE_TYPE_INDEX_LEAF=js,h.PAGE_TYPE_LEAF_DATA=Hn,h.PAGE_TYPE_TABLE_INTERIOR=qs,h.QueryArenaExhaustedError=xs,h.QueryBuilder=Ht,h.QueryTimeoutError=Pr,h.RESULT_BUFFER_OFFSET=gn,h.RESULT_BUFFER_SIZE=Ls,h.RowSizeLimitExceededError=Tr,h.SLOTTED_PAGE_HEADER_FIELDS=Jo,h.SLOT_TO_PAGE_OFFSET=bn,h.SYSPAGE_FILE_HEADER_FIELDS=ia,h.SYSPAGE_RESERVED_OFFSET=Aa,h.SYSPAGE_RESERVED_SIZE=fa,h.SubqueryNestingTooDeepError=oc,h.TABLE_DESCRIPTOR_FIELDS=_a,h.TABLE_DESCRIPTOR_OFFSET_AUTO_INC_NEXT=Ta,h.TABLE_DESCRIPTOR_OFFSET_COLUMN_COUNT=ha,h.TABLE_DESCRIPTOR_OFFSET_COL_CATALOG_PAGE_ID=Ea,h.TABLE_DESCRIPTOR_OFFSET_FLAGS=Ia,h.TABLE_DESCRIPTOR_OFFSET_NAME=ma,h.TABLE_DESCRIPTOR_OFFSET_RESERVED=ya,h.TABLE_DESCRIPTOR_OFFSET_ROOT_PAGE_ID=da,h.TABLE_DESCRIPTOR_OFFSET_ROW_COUNT_ESTIMATE=pa,h.TABLE_DESCRIPTOR_OFFSET_TABLE_ID=ga,h.TABLE_DESCRIPTOR_SIZE=Ue,h.TABLE_INTERIOR_CELL_FIELDS=ea,h.TABLE_INTERIOR_CELL_OFFSET_CHILD_PAGE_ID=na,h.TABLE_INTERIOR_CELL_OFFSET_ROWID=sa,h.TABLE_INTERIOR_CELL_SIZE=Ki,h.TABLE_INTERIOR_SPLIT_INDEX=xi,h.TOTAL_MEMORY_BYTES=Ka,h.TRANSIENT_ARENA_OFFSET=Ar,h.TableAlreadyExistsError=Ur,h.TableFlag=En,h.TableNotFoundError=Vn,h.TooManyColumnsError=zs,h.TooManyCursorsError=$n,h.TooManyGroupByColumnsError=Fr,h.TooManyIndexesError=Sr,h.TooManyOrderByColumnsError=Lr,h.TooManyRegistersError=et,h.TooManyTablesError=Or,h.TransactionCoordinator=No,h.UniqueConstraintViolationError=Xn,h.UnknownFunctionError=ti,h.UnsupportedFormatVersionError=Nr,h.VM_CONTEXT_OFFSET=cr,h.VM_CONTEXT_SIZE=sr,h.VM_FRAME_COUNT=ec,h.VM_FRAME_SIZE=tc,h.VmStatus=C,h.WAL_CURRENT_VERSION=fr,h.WAL_FILE_HEADER_FIELDS=za,h.WAL_FILE_HEADER_SIZE=Mn,h.WAL_FRAME_HEADER_FIELDS=xa,h.WAL_FRAME_HEADER_SIZE=Ne,h.WAL_FRAME_MAGIC=hn,h.WAL_FRAME_OFFSET_CHECKSUM=Zs,h.WAL_FRAME_OFFSET_DB_SIZE_PAGES=$s,h.WAL_FRAME_OFFSET_FLAGS=Hs,h.WAL_FRAME_OFFSET_FRAME_SEQ=Ys,h.WAL_FRAME_OFFSET_FRAME_TYPE=Ws,h.WAL_FRAME_OFFSET_MAGIC=Ms,h.WAL_FRAME_OFFSET_PAGE_ID=Xs,h.WAL_FRAME_OFFSET_RESERVED=gr,h.WAL_FRAME_OFFSET_TX_ID=Vs,h.WAL_FRAME_SIZE=Ge,h.WAL_FRAME_TYPE_PAGE_DATA=kn,h.WAL_FRAME_TYPE_TX_COMMIT=Gn,h.WAL_FRAME_TYPE_TX_UNCOMMITTED=vn,h.WAL_HEADER_OFFSET_CHECKPOINT_SEQ=bs,h.WAL_HEADER_OFFSET_CHECKSUM=vs,h.WAL_HEADER_OFFSET_MAGIC=Ds,h.WAL_HEADER_OFFSET_PAGE_SIZE=Qs,h.WAL_HEADER_OFFSET_RESERVED=_r,h.WAL_HEADER_OFFSET_SALT1=ks,h.WAL_HEADER_OFFSET_SALT2=Gs,h.WAL_HEADER_OFFSET_WAL_VERSION=Rs,h.WAL_HEADER_SIZE=rc,h.WAL_MAGIC_BYTES=ii,h.WAL_PAGE_SIZE=ue,h.WEBDB_CORE_WASM_BASE64=Fi,h.WebDB=Zi,h.buf_pool_assign_slot=zr,h.buf_pool_clear_dirty=eo,h.buf_pool_find_victim=Ti,h.buf_pool_get_resident_slot=Gt,h.buf_pool_get_slot_offset=Lc,h.buf_pool_is_dirty=mi,h.buf_pool_is_pinned=Ze,h.buf_pool_mark_dirty=to,h.buf_pool_pin_slot=Ii,h.buf_pool_read_slot_to_page=Ye,h.buf_pool_select_eviction_victim=yi,h.buf_pool_unassign_slot=xr,h.buf_pool_unpin_slot=pi,h.buf_pool_write_slot_to_page=Ei,h.buildJoinEdges=ds,h.buildRootFilter=Zt,h.c_assert=Mr,h.canJoinPreserveOrder=Wo,h.catalog_create_table=To,h.catalog_delete_index_descriptor=wi,h.catalog_delete_table_descriptor=Eo,h.catalog_find_free_index_slot=Bi,h.catalog_find_free_table_slot=ho,h.catalog_find_index_by_name=Pi,h.catalog_find_table_by_name=Vc,h.catalog_find_table_slot=Re,h.catalog_get_change_counter=_o,h.catalog_get_free_page_head=Wc,h.catalog_get_schema_version=fo,h.catalog_get_total_pages=vc,h.catalog_increment_change_counter=Je,h.catalog_increment_schema_version=Sn,h.catalog_init_page=mo,h.catalog_init_page1=Ao,h.catalog_list_table_descriptors=Nn,h.catalog_list_table_indexes=ze,h.catalog_load_all_tables=Yc,h.catalog_load_table_meta=Li,h.catalog_map_column_location=$c,h.catalog_parse_data_type=go,h.catalog_read_column_meta=po,h.catalog_read_fixed_string=fs,h.catalog_read_index_descriptor=Bn,h.catalog_read_page1_header=Oi,h.catalog_read_page_header=Qe,h.catalog_read_table_descriptor=Ae,h.catalog_set_free_page_head=Hc,h.catalog_set_total_pages=Mc,h.catalog_update_page1_checksum=Ke,h.catalog_write_column_meta=Io,h.catalog_write_fixed_string=As,h.catalog_write_index_descriptor=Ni,h.catalog_write_page_header=Xc,h.catalog_write_table_descriptor=Si,h.chooseIndexScan=Ts,h.chooseJoinIndex=ys,h.clear_bit=vr,h.col=Ri,h.collectLeafFilters=Go,h.compare_sorter_keys=je,h.compileQuery=$i,h.computeBufferPoolOffsets=Fs,h.computePage1Checksum=ni,h.computePageChecksum=qn,h.computeWalFrameChecksum=jn,h.crc32=ei,h.createVmContext=Ir,h.createVmCursor=mr,h.createWasmCore=Uo,h.createWasmMemory=Co,h.decodeWalFileHeader=xn,h.decodeWalFrame=Ec,h.decodeWalFrameHeader=oi,h.deriveDefaultAlias=Yt,h.disassembleBytecode=Ho,h.doesTableSatisfyJoinOrderKeys=bi,h.emitExpression=q,h.encodeWalFileHeader=ri,h.encodeWalFrame=ts,h.estimateFilterSelectivity=Qi,h.estimateWhereCost=ki,h.evalExprNode=wn,h.exp=Lo,h.extractAggregatesFromExpr=Yi,h.extractFilterColumnNames=Do,h.findIndexOnColumn=Ln,h.fn=xc,h.fnv1a_32=us,h.formatDisassembly=Vo,h.getCmpOpcode=Dn,h.getFilterReferencedTables=tn,h.getMinKeyValueForType=ps,h.getSingleTableBaseCost=se,h.getTopLevelConjunctionFilters=en,h.getWebDbCoreWasmBytes=yo,h.get_bit=kr,h.inferExprType=Mo,h.inferTransitivePredicates=Ro,h.isAggregateFunction=fe,h.isBuiltinFunction=Zc,h.isBuiltinScalarFunction=wo,h.isIndexAlignedWithOrderBy=Xi,h.materializeOutputSelectExprs=Fn,h.memcmp=ac,h.memcpy=In,h.memset=zt,h.normalizeFilter=_e,h.normalizeSelectItem=Us,h.optimizeQueryPlan=ul,h.optimizeWherePredicates=Gi,h.page_binary_search_index_leaf=cs,h.page_binary_search_interior=Bc,h.page_compact=Tn,h.page_compare_index_keys=as,h.page_delete_row=Sc,h.page_deserialize_row=_i,h.page_get_cell_content_offset=we,h.page_get_cell_count=dt,h.page_get_cell_offset=ht,h.page_get_checksum=Cc,h.page_get_contiguous_free_space=ns,h.page_get_free_bytes=Fe,h.page_get_next_page_id=kt,h.page_get_right_child_page_id=rs,h.page_get_row_length=ss,h.page_get_table_layout=Nc,h.page_get_total_free_space=Xr,h.page_get_type=He,h.page_init=pn,h.page_init_free=Vr,h.page_init_index_leaf=os,h.page_init_interior=Yr,h.page_insert_index_leaf_cell=hi,h.page_insert_interior_cell=qr,h.page_insert_row=is,h.page_serialize_row=fi,h.page_set_cell_content_offset=Le,h.page_set_cell_count=Ve,h.page_set_cell_offset=$e,h.page_set_checksum=Oc,h.page_set_free_bytes=Xe,h.page_set_next_page_id=Ai,h.page_set_right_child_page_id=Zr,h.page_set_type=Uc,h.page_split_interior=Pc,h.page_table_delete=di,h.page_table_get=Jr,h.page_table_hash=yn,h.page_table_set=Kr,h.page_update_row=$r,h.parseExpression=at,h.parseFilterTarget=Tt,h.parseSelectExpr=gs,h.read_f64=Ac,h.read_i32=lc,h.read_i64=hc,h.read_u16=Kn,h.read_u32=mt,h.read_u64=_c,h.read_u8=br,h.reconstructJoinPlans=Es,h.recoverFromWal=Di,h.resetVmContext=pr,h.resolveColumnAcrossTables=lt,h.resolveQueryPlanner=Mi,h.serialize_composite_key=ls,h.serialize_single_key=jr,h.set_bit=Gr,h.sql=Kc,h.sql_like_match=Un,h.strlen=Jn,h.validateClause=be,h.validateWalFrame=ai,h.vm_step=On,h.write_f64=fc,h.write_i32=uc,h.write_i64=dc,h.write_u16=zn,h.write_u32=It,h.write_u64=gc,h.write_u8=cc,Object.defineProperty(h,Symbol.toStringTag,{value:"Module"})});
|
|
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"})});
|
|
5
5
|
//# sourceMappingURL=webdb.umd.cjs.map
|