@ahmadmoussawi/webdb 0.1.3 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/README.md +50 -6
  2. package/dist/angular.cjs +2 -0
  3. package/dist/angular.cjs.map +1 -0
  4. package/dist/angular.d.ts +92 -0
  5. package/dist/angular.js +108 -0
  6. package/dist/angular.js.map +1 -0
  7. package/dist/core/index.d.ts +1 -1
  8. package/dist/core/index.d.ts.map +1 -1
  9. package/dist/core/js/catalog.c.d.ts +88 -27
  10. package/dist/core/js/catalog.c.d.ts.map +1 -1
  11. package/dist/core/wasm/embedded_wasm.d.ts +1 -1
  12. package/dist/core/wasm/embedded_wasm.d.ts.map +1 -1
  13. package/dist/core/wasm/wasm_core.d.ts.map +1 -1
  14. package/dist/host/api/index.d.ts +1 -0
  15. package/dist/host/api/index.d.ts.map +1 -1
  16. package/dist/host/api/live_query.d.ts +71 -0
  17. package/dist/host/api/live_query.d.ts.map +1 -0
  18. package/dist/host/api/query_builder.d.ts +20 -0
  19. package/dist/host/api/query_builder.d.ts.map +1 -1
  20. package/dist/host/api/webdb.d.ts +8 -0
  21. package/dist/host/api/webdb.d.ts.map +1 -1
  22. package/dist/host/driver/buffer_pool_driver.d.ts.map +1 -1
  23. package/dist/host/storage/idb.d.ts +1 -3
  24. package/dist/host/storage/idb.d.ts.map +1 -1
  25. package/dist/host/storage/io.d.ts.map +1 -1
  26. package/dist/host/storage/memory.d.ts +1 -3
  27. package/dist/host/storage/memory.d.ts.map +1 -1
  28. package/dist/host/storage/opfs.d.ts +1 -3
  29. package/dist/host/storage/opfs.d.ts.map +1 -1
  30. package/dist/host/storage/vfs.d.ts +12 -16
  31. package/dist/host/storage/vfs.d.ts.map +1 -1
  32. package/dist/react.cjs +2 -0
  33. package/dist/react.cjs.map +1 -0
  34. package/dist/react.d.ts +52 -0
  35. package/dist/react.js +66 -0
  36. package/dist/react.js.map +1 -0
  37. package/dist/types/index.d.ts +4 -0
  38. package/dist/types/index.d.ts.map +1 -1
  39. package/dist/vue.cjs +2 -0
  40. package/dist/vue.cjs.map +1 -0
  41. package/dist/vue.d.ts +100 -0
  42. package/dist/vue.js +80 -0
  43. package/dist/vue.js.map +1 -0
  44. package/dist/webdb.js +5701 -5143
  45. package/dist/webdb.js.map +1 -1
  46. package/dist/webdb.umd.cjs +2 -2
  47. package/dist/webdb.umd.cjs.map +1 -1
  48. package/package.json +37 -2
@@ -1,5 +1,5 @@
1
- (function(E,qt){typeof exports=="object"&&typeof module<"u"?qt(exports):typeof define=="function"&&define.amd?define(["exports"],qt):(E=typeof globalThis<"u"?globalThis:E||self,qt(E.WebDB={}))})(this,function(E){"use strict";var yc=Object.defineProperty;var Tc=(E,qt,wn)=>qt in E?yc(E,qt,{enumerable:!0,configurable:!0,writable:!0,value:wn}):E[qt]=wn;var U=(E,qt,wn)=>Tc(E,typeof qt!="symbol"?qt+"":qt,wn);const ra=[["TYPE",1],["FLAGS",1],["CELL_COUNT",2],["CONTENT_OFFSET",2],["NEXT_PAGE_ID",4],["FREE_BYTES",2],["CHECKSUM",4]],Kt=16,rr=0,oa=1,aa=2,la=4,or=6,ca=10,De=12,ua=[["CHILD_PAGE_ID",4],["ROWID",8]],ar=12,fa=0,Aa=4,lr=291,cr=145,ne=64,ha=[["MAGIC",6],["PAGE_SIZE",2],["FILE_FORMAT_VERSION",2],["MIN_READ_VERSION",2],["TOTAL_PAGES",4],["FREE_PAGE_HEAD",4],["SCHEMA_VERSION",4],["CHANGE_COUNTER",4],["PAGE_CHECKSUM",4],["NEXT_CATALOG_PAGE_ID",4],["NEXT_INDEX_CATALOG_PAGE_ID",4],["RESERVED",60]],ga=100,Ee=0,qs=6,Vs=8,$s=10,se=12,le=16,Ie=20,pe=24,ye=28,ur=32,fr=36,_a=40,da=16,ma=8,ce=16,Je=8,Sn=100,Un=2148,Ea=3172,Ia=4,pa=3176,ya=920,Te=56,ue=256,Ta=[["TABLE_ID",2],["COLUMN_COUNT",2],["ROOT_PAGE_ID",4],["COL_CATALOG_PAGE_ID",4],["NAME",64],["FLAGS",4],["ROW_COUNT_ESTIMATE",4],["AUTO_INC_NEXT",8],["RESERVED",36]],Re=128,Ca=0,wa=2,Sa=4,Ua=8,Oa=12,Pa=76,Na=80,Ba=84,ba=92,La=[["INDEX_ID",2],["TABLE_ID",2],["ROOT_PAGE_ID",4],["COLUMN_COUNT",1],["FLAGS",1],["COLUMN_INDICES",16],["COL_DIRECTIONS",8],["NAME",64],["RESERVED",30]],Fe=128,Da=0,Ra=2,Fa=4,Qa=8,va=9,ka=10,Ga=26,Ma=34,Wa=98,Ha=[["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,qa=0,Va=1,$a=2,xa=4,Xa=6,Ya=8,Za=12,ja=[["TYPE",1],["FLAGS",1],["COL_OFFSET",2],["NAME",64],["RESERVED",4]],Xs=72,Ka=0,Ja=1,za=2,tl=4,el=68,nl=4194304,Qe=1024,sl=1024,Wt=2048,Ce=8,Ar=16384,hr=12288,Ys=65536,gr=32768,_r=4096,dr=61312,ve=16777216,il=[["SLOT_TO_PAGE",4096],["PAGE_TO_SLOT",16384],["DIRTY_MASK",128],["VM_CONTEXT",12288],["RESULT_BUFFER",65536],["BYTECODE",32768],["PAGE_SCRATCHPAD",4096],["ALIGNMENT_PADDING",61312]],Yn=4194304,Gt=4198400,mr=4214784,Er=4214912,On=4227200,Ir=4292736,pr=4325504,rl=4329600,yr=4390912,ol=21168128;function Zs(e,t=ve){const n=e*4096,s=e*4+7&-8;let i=16;for(;i<e*2;)i<<=1;const r=i*8,o=Math.ceil(e/8)+7&-8;if(e===Qe)return{slotsEndOffset:n,slotToPageOffset:Yn,pageToSlotOffset:Gt,pageToSlotBuckets:Wt,dirtyMaskOffset:mr,vmContextOffset:Er,resultBufferOffset:On,bytecodeOffset:Ir,pageScratchpadOffset:pr,transientArenaOffset:yr};const a=n,c=a+s,l=c+r,u=l+o,_=u+hr,f=_+Ys,h=f+gr,g=h+_r+dr;return{slotsEndOffset:n,slotToPageOffset:a,pageToSlotOffset:c,pageToSlotBuckets:i,dirtyMaskOffset:l,vmContextOffset:u,resultBufferOffset:_,bytecodeOffset:f,pageScratchpadOffset:h,transientArenaOffset:g}}const we=4096,ze=4128,Tr=1,Pn=1463897158,Zn=1,jn=2,Kn=3,al=[["MAGIC",6],["WAL_VERSION",2],["PAGE_SIZE",4],["CHECKPOINT_SEQ",4],["SALT1",4],["SALT2",4],["CHECKSUM",4],["RESERVED",4]],Jn=32,js=0,Ks=6,Js=8,zs=12,ti=16,ei=20,ni=24,Cr=28,ll=[["MAGIC",4],["FRAME_TYPE",2],["FLAGS",2],["TX_ID",4],["PAGE_ID",4],["DB_SIZE_PAGES",4],["FRAME_SEQ",4],["CHECKSUM",4],["RESERVED",4]],ke=32,si=0,ii=4,ri=6,oi=8,ai=12,li=16,ci=20,ui=24,wr=28,zn=1,Sr=1,Ge=0,Ur=2,fi=5,ts=10,Nn=12,es=13,cl=1280,ul=8,fl=64,Al=16,hl=7,gl=32,Or=1e4,Ft=1e4;function Pr(){return{pageId:0,rootPageId:0,slotIdx:0,cellIdx:0,rowOffset:0,btreeDepth:0,flags:0}}function Nr(){const e=Array.from({length:16},()=>Pr());return{pc:0,status:O.RUNNING,fault_page_id:0,resultCount:0,resultOffset:0,arenaOffset:0,maxQueryMemory:ve,rowsAffected:0,registers:new Array(64).fill(null),cursor:e[0],cursors:e,keyInfos:[],sorters:[],aggregators:[],table:null,tables:void 0,outputColumns:void 0,inSets:[]}}function Br(e,t,n){e.pc=0,e.status=O.RUNNING,e.fault_page_id=0,e.resultCount=0,e.resultOffset=0,e.arenaOffset=0,e.maxQueryMemory=ve,e.rowsAffected=0,e.registers.fill(null);for(let s=0;s<e.cursors.length;s++){const i=e.cursors[s];i.pageId=0,i.rootPageId=0,i.slotIdx=0,i.cellIdx=0,i.rowOffset=0,i.btreeDepth=0,i.flags=0}e.cursor=e.cursors[0],e.keyInfos=[],e.sorters=[],e.aggregators=[],e.table=t??null,e.tables=n,e.outputColumns=void 0,e.inSets=[]}var C=(e=>(e[e.NULL=0]="NULL",e[e.INT32=1]="INT32",e[e.INT64=2]="INT64",e[e.FLOAT64=3]="FLOAT64",e[e.TEXT=4]="TEXT",e[e.BLOB=5]="BLOB",e[e.UUID=6]="UUID",e[e.ULID=7]="ULID",e))(C||{}),tt=(e=>(e[e.NONE=0]="NONE",e[e.PRIMARY_KEY=1]="PRIMARY_KEY",e[e.NOT_NULL=2]="NOT_NULL",e[e.INDEXED=4]="INDEXED",e[e.AUTO_INC=8]="AUTO_INC",e))(tt||{}),Bn=(e=>(e[e.NONE=0]="NONE",e[e.ACTIVE=1]="ACTIVE",e[e.SYSTEM=2]="SYSTEM",e))(Bn||{}),It=(e=>(e[e.NONE=0]="NONE",e[e.UNIQUE=1]="UNIQUE",e[e.PRIMARY=2]="PRIMARY",e[e.SPATIAL_VECTOR=4]="SPATIAL_VECTOR",e))(It||{}),m=(e=>(e[e.OP_HALT=0]="OP_HALT",e[e.OP_OPEN_CURSOR=1]="OP_OPEN_CURSOR",e[e.OP_REWIND=2]="OP_REWIND",e[e.OP_NEXT_ROW=3]="OP_NEXT_ROW",e[e.OP_COLUMN_INT=4]="OP_COLUMN_INT",e[e.OP_COLUMN_FLOAT=5]="OP_COLUMN_FLOAT",e[e.OP_COLUMN_TEXT=6]="OP_COLUMN_TEXT",e[e.OP_COLUMN_BLOB=7]="OP_COLUMN_BLOB",e[e.OP_LAST=8]="OP_LAST",e[e.OP_PREV_ROW=9]="OP_PREV_ROW",e[e.OP_COLUMN_UUID=10]="OP_COLUMN_UUID",e[e.OP_COLUMN_ULID=11]="OP_COLUMN_ULID",e[e.OP_OPEN_INDEX=12]="OP_OPEN_INDEX",e[e.OP_INDEX_SEEK_EQ=13]="OP_INDEX_SEEK_EQ",e[e.OP_INDEX_SEEK_GE=14]="OP_INDEX_SEEK_GE",e[e.OP_INDEX_NEXT=15]="OP_INDEX_NEXT",e[e.OP_IS_NULL=16]="OP_IS_NULL",e[e.OP_IS_NOT_NULL=17]="OP_IS_NOT_NULL",e[e.OP_EQ=18]="OP_EQ",e[e.OP_NE=19]="OP_NE",e[e.OP_GT=20]="OP_GT",e[e.OP_GE=21]="OP_GE",e[e.OP_LT=22]="OP_LT",e[e.OP_LE=23]="OP_LE",e[e.OP_JUMP=24]="OP_JUMP",e[e.OP_STR_LIKE=25]="OP_STR_LIKE",e[e.OP_STR_NOT_LIKE=26]="OP_STR_NOT_LIKE",e[e.OP_STR_CONTAINS=27]="OP_STR_CONTAINS",e[e.OP_STR_STARTS_WITH=28]="OP_STR_STARTS_WITH",e[e.OP_STR_ENDS_WITH=29]="OP_STR_ENDS_WITH",e[e.OP_LOAD_BLOB=30]="OP_LOAD_BLOB",e[e.OP_IN=31]="OP_IN",e[e.OP_LOAD_INT=32]="OP_LOAD_INT",e[e.OP_LOAD_FLOAT=33]="OP_LOAD_FLOAT",e[e.OP_LOAD_TEXT=34]="OP_LOAD_TEXT",e[e.OP_LOAD_NULL=35]="OP_LOAD_NULL",e[e.OP_EMIT_ROW=36]="OP_EMIT_ROW",e[e.OP_RESULT_ROW=37]="OP_RESULT_ROW",e[e.OP_OFFSET=38]="OP_OFFSET",e[e.OP_LIMIT=39]="OP_LIMIT",e[e.OP_CALL_UDF=40]="OP_CALL_UDF",e[e.OP_STR_LOWER=41]="OP_STR_LOWER",e[e.OP_STR_UPPER=42]="OP_STR_UPPER",e[e.OP_STR_LENGTH=43]="OP_STR_LENGTH",e[e.OP_STR_SUBSTR=44]="OP_STR_SUBSTR",e[e.OP_STR_TRIM=45]="OP_STR_TRIM",e[e.OP_MATH_ABS=46]="OP_MATH_ABS",e[e.OP_MATH_ROUND=47]="OP_MATH_ROUND",e[e.OP_SORTER_OPEN=48]="OP_SORTER_OPEN",e[e.OP_SORTER_INSERT=49]="OP_SORTER_INSERT",e[e.OP_SORTER_SORT=50]="OP_SORTER_SORT",e[e.OP_SORTER_NEXT=51]="OP_SORTER_NEXT",e[e.OP_MATH_FLOOR=52]="OP_MATH_FLOOR",e[e.OP_MATH_CEIL=53]="OP_MATH_CEIL",e[e.OP_ADD=54]="OP_ADD",e[e.OP_SUB=55]="OP_SUB",e[e.OP_MUL=56]="OP_MUL",e[e.OP_DIV=57]="OP_DIV",e[e.OP_MOD=58]="OP_MOD",e[e.OP_ENTER_SUBQUERY=59]="OP_ENTER_SUBQUERY",e[e.OP_RETURN_SUBQUERY=60]="OP_RETURN_SUBQUERY",e[e.OP_STR_CONCAT=61]="OP_STR_CONCAT",e[e.OP_COALESCE=62]="OP_COALESCE",e[e.OP_COPY=63]="OP_COPY",e[e.OP_AGG_INIT=64]="OP_AGG_INIT",e[e.OP_AGG_STEP=65]="OP_AGG_STEP",e[e.OP_AGG_NEXT=66]="OP_AGG_NEXT",e[e.OP_AGG_FINAL=67]="OP_AGG_FINAL",e[e.OP_REG_IS_NULL=72]="OP_REG_IS_NULL",e[e.OP_REG_IS_NOT_NULL=73]="OP_REG_IS_NOT_NULL",e[e.OP_DELETE_ROW=80]="OP_DELETE_ROW",e[e.OP_UPDATE_FIELD=81]="OP_UPDATE_FIELD",e[e.OP_INSERT_ROW=82]="OP_INSERT_ROW",e))(m||{}),O=(e=>(e[e.RUNNING=0]="RUNNING",e[e.DONE=1]="DONE",e[e.PAGE_FAULT=2]="PAGE_FAULT",e[e.BUFFER_FULL=3]="BUFFER_FULL",e[e.ERROR=4]="ERROR",e[e.TIMEOUT=5]="TIMEOUT",e[e.ARENA_EXHAUSTED=6]="ARENA_EXHAUSTED",e[e.INVALID_BYTECODE=7]="INVALID_BYTECODE",e))(O||{});class br extends Error{constructor(t,n=2048){super(`Row size (${t} bytes) exceeds maximum limit of ${n} bytes`),this.name="RowSizeLimitExceededError"}}class ns extends Error{constructor(t,n){super(`NOT NULL constraint failed: ${n?n+".":""}${t}`),this.name="NotNullConstraintError"}}class Lr extends Error{constructor(t,n=64){super(`Identifier "${t}" (${t.length} characters) exceeds maximum limit of ${n} characters`),this.name="IdentifierTooLongError"}}class ss extends Error{constructor(t,n){super(n?`Column "${t}" already exists on table "${n}"`:`Column "${t}" already exists`),this.name="ColumnAlreadyExistsError"}}class Ai extends Error{constructor(t){super(t),this.name="CannotDropColumnError"}}class fe extends Error{constructor(t,n){super(n?`Column "${t}" not found on table "${n}"`:`Column "${t}" not found`),this.name="ColumnNotFoundError"}}class bn extends Error{constructor(t){super(`Table not found: "${t}"`),this.name="TableNotFoundError"}}class is extends Error{constructor(t){super(`Table already exists: "${t}"`),this.name="TableAlreadyExistsError"}}class Dr extends Error{constructor(t){super(`Index not found: "${t}"`),this.name="IndexNotFoundError"}}class hi extends Error{constructor(t){super(`Index already exists: "${t}"`),this.name="IndexAlreadyExistsError"}}class tn extends Error{constructor(t){super(t),this.name="UniqueConstraintViolationError"}}class Se extends Error{constructor(t,n,s){super(`Corrupted page detected (pageId: ${t}): stored checksum ${n}${s!==void 0?`, computed checksum ${s}`:""}`),this.pageId=t,this.storedChecksum=n,this.computedChecksum=s,this.name="CorruptPageError"}}class Ln extends Error{constructor(t,n=256){super(`Too many columns: ${t} exceeds maximum limit of ${n} columns`),this.name="TooManyColumnsError"}}class gi extends Error{constructor(t,n=16){super(`Too many tables: ${t} exceeds maximum limit of ${n} tables on Page 1`),this.name="TooManyTablesError"}}class Rr extends Error{constructor(t,n=8){super(`Too many indexes: ${t} exceeds maximum limit of ${n} indexes on Page 1`),this.name="TooManyIndexesError"}}class Fr extends Error{constructor(t){super(t),this.name="UnsupportedFormatVersionError"}}class Dn extends Error{constructor(t){super(t),this.name="InvalidDatabaseError"}}class _i extends Error{constructor(t="Transient query arena exhausted"){super(t),this.name="QueryArenaExhaustedError"}}class rs extends Error{constructor(t,n=16){super(`Too many cursors: ${t} exceeds maximum limit of ${n} cursors`),this.name="TooManyCursorsError"}}class st extends Error{constructor(t,n=64){super(`Too many registers: ${t} exceeds maximum limit of ${n} registers`),this.name="TooManyRegistersError"}}class Qr extends Error{constructor(t,n=7){super(`Subquery nesting depth ${t} exceeds maximum limit of ${n}`),this.name="SubqueryNestingTooDeepError"}}class vr extends Error{constructor(t="Query execution exceeded maximum cycle limit (TIMEOUT)"){super(t),this.name="QueryTimeoutError"}}class kr extends Error{constructor(t="Malformed bytecode execution halted (INVALID_BYTECODE)"){super(t),this.name="InvalidBytecodeError"}}class Gr extends Error{constructor(t,n=8){super(`Too many order by columns: ${t} exceeds maximum limit of ${n}`),this.name="TooManyOrderByColumnsError"}}class Mr extends Error{constructor(t,n=8){super(`Too many group by columns: ${t} exceeds maximum limit of ${n}`),this.name="TooManyGroupByColumnsError"}}class di extends Error{constructor(t){super(`Function "${t}" is neither a native built-in function nor a registered UDF`),this.name="UnknownFunctionError"}}class os extends Error{constructor(t){super(`Aggregate function "${t}" cannot be used in WHERE clause`),this.name="AggregateNotAllowedInWhereError"}}class as extends Error{constructor(t="Corrupted WAL file header detected"){super(t),this.name="CorruptWalHeaderError"}}class Rn extends Error{constructor(t="Corrupted WAL frame detected"){super(t),this.name="CorruptWalFrameError"}}class Wr{constructor(){U(this,"name","memory");U(this,"isSynchronous",!0);U(this,"pages",new Map);U(this,"walHeader",null);U(this,"walFrames",[])}async readPage(t){const n=this.pages.get(t);return n?new Uint8Array(n):null}async writePage(t,n){const s=new Uint8Array(n.byteLength);s.set(n),this.pages.set(t,s)}async writePages(t){for(const{pageId:n,data:s}of t)await this.writePage(n,s)}async flush(){}async truncate(t){for(const n of Array.from(this.pages.keys()))n>t&&this.pages.delete(n)}snapshot(){const t=new Map;for(const[n,s]of this.pages.entries())t.set(n,new Uint8Array(s));return t}restoreSnapshot(t){this.pages.clear();for(const[n,s]of t.entries())this.pages.set(n,new Uint8Array(s))}async readWalHeader(){return this.walHeader?new Uint8Array(this.walHeader):null}async writeWalHeader(t){const n=new Uint8Array(t.byteLength);n.set(t),this.walHeader=n}async readWalFrame(t){const n=this.walFrames[t];return n?new Uint8Array(n):null}async readWalFrames(t,n){const s=n!==void 0?t+n:this.walFrames.length;return this.walFrames.slice(t,s).map(r=>new Uint8Array(r))}async appendWalFrames(t){for(const n of t){const s=new Uint8Array(n.byteLength);s.set(n),this.walFrames.push(s)}}async flushWal(){}async truncateWal(t){t===0?(this.walFrames=[],this.walHeader=null):this.walFrames.length=Math.min(this.walFrames.length,t)}async getWalFrameCount(){return this.walFrames.length}async close(){}}class Hr{constructor(t){U(this,"name","idb");U(this,"isSynchronous",!1);U(this,"dbName");U(this,"dbPromise",null);this.dbName=`webdb_${t}`}getDb(){return this.dbPromise||(this.dbPromise=new Promise((t,n)=>{const s=globalThis.indexedDB;if(!s){n(new Error("IndexedDB is not available in the current environment"));return}const i=s.open(this.dbName,1);i.onupgradeneeded=()=>{const r=i.result;r.objectStoreNames.contains("pages")||r.createObjectStore("pages"),r.objectStoreNames.contains("wal_frames")||r.createObjectStore("wal_frames"),r.objectStoreNames.contains("wal_meta")||r.createObjectStore("wal_meta")},i.onsuccess=()=>t(i.result),i.onerror=()=>n(i.error)})),this.dbPromise}async readPage(t){const n=await this.getDb();return new Promise((s,i)=>{const a=n.transaction("pages","readonly").objectStore("pages").get(t);a.onsuccess=()=>{const c=a.result;s(c?c instanceof Uint8Array?c:new Uint8Array(c):null)},a.onerror=()=>i(a.error)})}async writePage(t,n){const s=await this.getDb();return new Promise((i,r)=>{const o=s.transaction("pages","readwrite"),a=o.objectStore("pages"),c=new Uint8Array(n.byteLength);c.set(n),a.put(c,t),o.oncomplete=()=>i(),o.onerror=()=>r(o.error),o.onabort=()=>r(o.error)})}async writePages(t){if(t.length===0)return;const n=await this.getDb();return new Promise((s,i)=>{const r=n.transaction("pages","readwrite"),o=r.objectStore("pages");for(const{pageId:a,data:c}of t){const l=new Uint8Array(c.byteLength);l.set(c),o.put(l,a)}r.oncomplete=()=>s(),r.onerror=()=>i(r.error),r.onabort=()=>i(r.error)})}async flush(){}async truncate(t){const n=await this.getDb();return new Promise((s,i)=>{const o=n.transaction("pages","readwrite").objectStore("pages"),a=IDBKeyRange.lowerBound(t,!0),c=o.delete(a);c.onsuccess=()=>s(),c.onerror=()=>i(c.error)})}async readWalHeader(){const t=await this.getDb();return new Promise((n,s)=>{const o=t.transaction("wal_meta","readonly").objectStore("wal_meta").get("header");o.onsuccess=()=>{const a=o.result;n(a?a instanceof Uint8Array?a:new Uint8Array(a):null)},o.onerror=()=>s(o.error)})}async writeWalHeader(t){const n=await this.getDb();return new Promise((s,i)=>{const r=n.transaction("wal_meta","readwrite"),o=r.objectStore("wal_meta"),a=new Uint8Array(t.byteLength);a.set(t),o.put(a,"header"),r.oncomplete=()=>s(),r.onerror=()=>i(r.error),r.onabort=()=>i(r.error)})}async readWalFrame(t){const n=await this.getDb();return new Promise((s,i)=>{const a=n.transaction("wal_frames","readonly").objectStore("wal_frames").get(t);a.onsuccess=()=>{const c=a.result;s(c?c instanceof Uint8Array?c:new Uint8Array(c):null)},a.onerror=()=>i(a.error)})}async readWalFrames(t,n){const s=await this.getDb();return new Promise((i,r)=>{const a=s.transaction("wal_frames","readonly").objectStore("wal_frames"),c=[],l=n!==void 0?IDBKeyRange.bound(t,t+n-1):IDBKeyRange.lowerBound(t,!1),u=a.openCursor(l);u.onsuccess=()=>{const _=u.result;if(_){const f=_.value;c.push(f instanceof Uint8Array?f:new Uint8Array(f)),_.continue()}else i(c)},u.onerror=()=>r(u.error)})}async appendWalFrames(t){if(t.length===0)return;const n=await this.getDb();return new Promise((s,i)=>{const r=n.transaction("wal_frames","readwrite"),o=r.objectStore("wal_frames"),a=o.count();a.onsuccess=()=>{let c=a.result;for(const l of t){const u=new Uint8Array(l.byteLength);u.set(l),o.put(u,c++)}},r.oncomplete=()=>s(),r.onerror=()=>i(r.error),r.onabort=()=>i(r.error)})}async flushWal(){}async truncateWal(t){const n=await this.getDb();return new Promise((s,i)=>{const r=n.transaction(["wal_frames","wal_meta"],"readwrite"),o=r.objectStore("wal_frames"),a=r.objectStore("wal_meta");if(t===0)o.clear(),a.delete("header");else{const c=IDBKeyRange.lowerBound(t,!1);o.delete(c)}r.oncomplete=()=>s(),r.onerror=()=>i(r.error),r.onabort=()=>i(r.error)})}async getWalFrameCount(){const t=await this.getDb();return new Promise((n,s)=>{const o=t.transaction("wal_frames","readonly").objectStore("wal_frames").count();o.onsuccess=()=>n(o.result),o.onerror=()=>s(o.error)})}async close(){this.dbPromise&&((await this.dbPromise).close(),this.dbPromise=null)}}class qr{constructor(t){U(this,"name","opfs");U(this,"isSynchronous");U(this,"dbName");U(this,"rootDir",null);U(this,"dbFileHandle",null);U(this,"walFileHandle",null);U(this,"dbSyncHandle",null);U(this,"walSyncHandle",null);this.dbName=t,this.isSynchronous=typeof globalThis.FileSystemSyncAccessHandle<"u"}async initHandles(){var t;if(!this.rootDir){if(!((t=navigator==null?void 0:navigator.storage)!=null&&t.getDirectory))throw new Error("OPFS (Origin Private File System) is not available in the current environment");if(this.rootDir=await navigator.storage.getDirectory(),this.dbFileHandle=await this.rootDir.getFileHandle(`${this.dbName}.db`,{create:!0}),this.walFileHandle=await this.rootDir.getFileHandle(`${this.dbName}.wal`,{create:!0}),this.isSynchronous)try{this.dbSyncHandle=await this.dbFileHandle.createSyncAccessHandle(),this.walSyncHandle=await this.walFileHandle.createSyncAccessHandle()}catch{}}}async readPage(t){await this.initHandles();const n=(t-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(t,n){await this.initHandles();const s=(t-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(t){for(const{pageId:n,data:s}of t)await this.writePage(n,s)}async flush(){this.dbSyncHandle&&this.dbSyncHandle.flush()}async truncate(t){await this.initHandles();const n=t*4096;if(this.dbSyncHandle){this.dbSyncHandle.truncate(n);return}const s=await this.dbFileHandle.createWritable({keepExistingData:!0});await s.truncate(n),await s.close()}async readWalHeader(){if(await this.initHandles(),this.walSyncHandle){if(this.walSyncHandle.getSize()<32)return null;const i=new Uint8Array(32);return this.walSyncHandle.read(i,{at:0}),i}const t=await this.walFileHandle.getFile();if(t.size<32)return null;const n=t.slice(0,32);return new Uint8Array(await n.arrayBuffer())}async writeWalHeader(t){if(await this.initHandles(),this.walSyncHandle){this.walSyncHandle.write(t,{at:0});return}const n=await this.walFileHandle.createWritable({keepExistingData:!0});await n.seek(0),await n.write(t),await n.close()}async readWalFrame(t){await this.initHandles();const n=32+t*4128;if(this.walSyncHandle){const o=this.walSyncHandle.getSize();if(n>=o)return null;const a=Math.min(4128,o-n),c=new Uint8Array(a);return this.walSyncHandle.read(c,{at:n}),c}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(t,n){const s=[];let i=t;const r=n!==void 0?t+n:1/0;for(;i<r;){const o=await this.readWalFrame(i);if(!o)break;s.push(o),i++}return s}async appendWalFrames(t){if(await this.initHandles(),this.walSyncHandle){let i=Math.max(32,this.walSyncHandle.getSize());for(const r of t)this.walSyncHandle.write(r,{at:i}),i+=r.byteLength;return}const n=await this.walFileHandle.getFile(),s=await this.walFileHandle.createWritable({keepExistingData:!0});await s.seek(Math.max(32,n.size));for(const i of t)await s.write(i);await s.close()}async flushWal(){this.walSyncHandle&&this.walSyncHandle.flush()}async truncateWal(t){await this.initHandles();const n=t===0?0:32+t*4128;if(this.walSyncHandle){this.walSyncHandle.truncate(n);return}const s=await this.walFileHandle.createWritable({keepExistingData:t>0});await s.truncate(n),await s.close()}async getWalFrameCount(){await this.initHandles();let t=0;return this.walSyncHandle?t=this.walSyncHandle.getSize():t=(await this.walFileHandle.getFile()).size,t<=32?0:Math.ceil((t-32)/4128)}async close(){this.dbSyncHandle&&(this.dbSyncHandle.close(),this.dbSyncHandle=null),this.walSyncHandle&&(this.walSyncHandle.close(),this.walSyncHandle=null),this.dbFileHandle=null,this.walFileHandle=null,this.rootDir=null}}const en=new Uint32Array(256);for(let e=0;e<256;e++){let t=e;for(let n=0;n<8;n++)t=t&1?3988292384^t>>>1:t>>>1;en[e]=t>>>0}function mi(e,t=0,n=e.byteLength-t){let s=4294967295;const i=t+n;for(let r=t;r<i;r++)s=en[(s^e[r])&255]^s>>>8;return(s^4294967295)>>>0}function Me(e){let t=4294967295;for(let n=0;n<4096;n++){const s=n>=12&&n<=15?0:e[n];t=en[(t^s)&255]^t>>>8}return(t^4294967295)>>>0}function Ei(e){let t=4294967295;for(let n=0;n<4096;n++){const s=n>=28&&n<=31?0:e[n];t=en[(t^s)&255]^t>>>8}return(t^4294967295)>>>0}function ls(e){let t=4294967295;for(let s=0;s<24;s++)t=en[(t^e[s])&255]^t>>>8;const n=Math.min(e.byteLength,4128);for(let s=32;s<n;s++)t=en[(t^e[s])&255]^t>>>8;return(t^4294967295)>>>0}function nn(e,t,n,s,i){const r=e instanceof Uint8Array?e:new Uint8Array(e.buffer,e.byteOffset,e.byteLength),o=n instanceof Uint8Array?n:new Uint8Array(n.buffer,n.byteOffset,n.byteLength);r.set(o.subarray(s,s+i),t)}function ie(e,t,n,s){(e instanceof Uint8Array?e:new Uint8Array(e.buffer,e.byteOffset,e.byteLength)).fill(n&255,t,t+s)}function _l(e,t,n,s,i){const r=e instanceof Uint8Array?e:new Uint8Array(e.buffer,e.byteOffset,e.byteLength),o=n instanceof Uint8Array?n:new Uint8Array(n.buffer,n.byteOffset,n.byteLength);for(let a=0;a<i;a++){const c=r[t+a]-o[s+a];if(c!==0)return c}return 0}function cs(e){return e.length}function Vr(e,t){return e instanceof Uint8Array?e[t]:e.getUint8(t)}function dl(e,t,n){e instanceof Uint8Array?e[t]=n&255:e.setUint8(t,n&255)}function us(e,t){return e.getUint16(t,!0)}function fs(e,t,n){e.setUint16(t,n&65535,!0)}function yt(e,t){return e.getUint32(t,!0)}function Tt(e,t,n){e.setUint32(t,n>>>0,!0)}function ml(e,t){return e.getInt32(t,!0)}function El(e,t,n){e.setInt32(t,n|0,!0)}function Il(e,t){return e.getFloat64(t,!0)}function pl(e,t,n){e.setFloat64(t,n,!0)}function yl(e,t){return e.getBigUint64(t,!0)}function Tl(e,t,n){e.setBigUint64(t,n,!0)}function Cl(e,t){return e.getBigInt64(t,!0)}function wl(e,t,n){e.setBigInt64(t,n,!0)}function $r(e,t,n){return n!==void 0?e[t+(n>>3)]&1<<(n&7)?1:0:e[t>>3]&1<<(t&7)?1:0}function xr(e,t,n){n!==void 0?e[t+(n>>3)]|=1<<(n&7):e[t>>3]|=1<<(t&7)}function Xr(e,t,n){n!==void 0?e[t+(n>>3)]&=~(1<<(n&7)):e[t>>3]&=~(1<<(t&7))}function Yr(e,t){if(!e)throw new Error(`Assertion failed: ${t}`)}class Ii{constructor(t){U(this,"vfs");U(this,"buffer");U(this,"uint8");U(this,"view");U(this,"in_flight_flushes",new Map);U(this,"in_flight_reads",new Map);U(this,"coordinator",null);if(!t.vfs)throw new Error("Io requires a valid IVfsAdapter instance");if(!t.memory)throw new Error("Io requires a valid memory buffer or WebAssembly.Memory");this.vfs=t.vfs,this.buffer=t.memory instanceof WebAssembly.Memory?t.memory.buffer:t.memory,this.uint8=new Uint8Array(this.buffer),this.view=new DataView(this.buffer)}setTransactionCoordinator(t){this.coordinator=t}isInTransaction(){return this.coordinator?this.coordinator.isInTransaction():!1}stampSlotChecksum(t,n){const s=t*4096,i=this.uint8.subarray(s,s+4096);if(n===1){const r=Ei(i);Tt(this.view,s+ye,r)}else{const r=Me(i);Tt(this.view,s+De,r)}}async readSlot(t,n){if(n<=0)throw new Error(`Invalid page ID: ${n}. Page IDs must be positive integers.`);if(this.coordinator&&this.coordinator.hasSpilledPage(n)){const o=t*4096,a=this.coordinator.getSpilledPage(n);this.uint8.set(a,o);return}const s=this.in_flight_flushes.get(n);s&&await s;const i=this.in_flight_reads.get(n);if(i){await i;return}const r=(async()=>{const o=await this.vfs.readPage(n),a=t*4096;if(o){if(o.byteLength!==4096)throw new Se(n,`Unexpected page byte length: ${o.byteLength}, expected 4096`);const c=n===1?ye:De,l=yt(new DataView(o.buffer,o.byteOffset),c);if(l!==0){const u=n===1?Ei(o):Me(o);if(u!==l)throw new Se(n,l,u)}this.uint8.set(o,a)}else this.uint8.fill(0,a,a+4096)})();this.in_flight_reads.set(n,r);try{await r}finally{this.in_flight_reads.delete(n)}}async writeSlot(t,n){if(n<=0)throw new Error(`Invalid page ID: ${n}. Page IDs must be positive integers.`);const s=this.in_flight_flushes.get(n);if(s){await s;return}const i=t*4096,r=this.uint8.subarray(i,i+4096);this.stampSlotChecksum(t,n);const o=r.slice();this.coordinator&&this.coordinator.onDirectPageWrite(n,o);const a=this.vfs.writePage(n,o);this.in_flight_flushes.set(n,a);try{await a}finally{this.in_flight_flushes.delete(n)}}async spillOrWriteSlot(t,n){this.coordinator&&this.coordinator.isInTransaction()?await this.coordinator.spillUncommittedSlot(t,n):await this.writeSlot(t,n)}async resolvePageFault(t,n,s){if(s>0&&(this.coordinator&&this.coordinator.isInTransaction()?await this.coordinator.spillUncommittedSlot(t,s):await this.writeSlot(t,s)),this.coordinator&&this.coordinator.hasSpilledPage(n)){const i=t*4096,r=this.coordinator.getSpilledPage(n);this.uint8.set(r,i)}else await this.readSlot(t,n)}async flush(){await this.vfs.flush()}}const pi=new Uint8Array([87,69,66,87,65,76]);function As(e={}){const t=new Uint8Array(Jn),n=new DataView(t.buffer,t.byteOffset,t.byteLength);t.set(pi,js),fs(n,Ks,e.walVersion??Tr),Tt(n,Js,e.pageSize??we),Tt(n,zs,e.checkpointSeq??0);const s=e.salt1??Math.floor(Math.random()*4294967295)>>>0;Tt(n,ti,s);const i=e.salt2??Math.floor(Math.random()*4294967295)>>>0;Tt(n,ei,i);const r=e.checksum??mi(t,0,24);return Tt(n,ni,r),Tt(n,Cr,0),t}function hs(e,t=!0){if(e.byteLength<Jn)throw new as(`Truncated WAL file header: expected at least ${Jn} bytes, received ${e.byteLength}`);for(let l=0;l<6;l++)if(e[js+l]!==pi[l])throw new as('Invalid WAL file header magic identifier (expected "WEBWAL")');const n=new DataView(e.buffer,e.byteOffset,e.byteLength),s=us(n,Ks),i=yt(n,Js),r=yt(n,zs),o=yt(n,ti),a=yt(n,ei),c=yt(n,ni);if(t){const l=mi(e,0,24);if(c!==l)throw new as(`WAL file header CRC32 checksum mismatch: stored ${c}, computed ${l}`)}return{walVersion:s,pageSize:i,checkpointSeq:r,salt1:o,salt2:a,checksum:c}}function gs(e,t){const n=new Uint8Array(ze),s=new DataView(n.buffer,n.byteOffset,n.byteLength);Tt(s,si,e.magic??Pn),fs(s,ii,e.frameType),fs(s,ri,e.flags??0),Tt(s,oi,e.txId),Tt(s,ai,e.pageId),Tt(s,li,e.dbSizePages??0),Tt(s,ci,e.frameSeq),Tt(s,wr,0),t&&n.set(t.subarray(0,we),ke);const i=e.checksum??ls(n);return Tt(s,ui,i),n}function yi(e){if(e.byteLength<ke)throw new Rn(`Truncated WAL frame header: expected at least ${ke} bytes, received ${e.byteLength}`);const t=new DataView(e.buffer,e.byteOffset,e.byteLength);return{magic:yt(t,si),frameType:us(t,ii),flags:us(t,ri),txId:yt(t,oi),pageId:yt(t,ai),dbSizePages:yt(t,li),frameSeq:yt(t,ci),checksum:yt(t,ui)}}function Ti(e){if(e.byteLength<ze)return{valid:!1,reason:"truncated"};const t=yi(e);if(t.magic!==Pn)return{valid:!1,reason:"magic_mismatch",header:t};const n=ls(e);return t.checksum!==n?{valid:!1,reason:"checksum_mismatch",header:t}:{valid:!0,header:t}}function Sl(e,t=!0){if(e.byteLength<ze)throw new Rn(`Truncated WAL frame: expected ${ze} bytes, received ${e.byteLength}`);const n=yi(e);if(n.magic!==Pn)throw new Rn(`Invalid WAL frame magic: expected 0x${Pn.toString(16)}, got 0x${n.magic.toString(16)}`);if(t){const i=ls(e);if(n.checksum!==i)throw new Rn(`WAL frame CRC32 checksum mismatch: stored ${n.checksum}, computed ${i}`)}const s=e.subarray(ke,ze);return{header:n,pageData:s}}const Zr=new TextDecoder,jr="0123456789abcdef",Ci="0123456789ABCDEFGHJKMNPQRSTVWXYZ";function Ul(e){return e>=48&&e<=57?e-48:e>=97&&e<=102?e-97+10:e>=65&&e<=70?e-65+10:-1}function wi(e){if(e>=48&&e<=57)return e-48;switch(e>=97&&e<=122&&(e=e-32),e){case 65:return 10;case 66:return 11;case 67:return 12;case 68:return 13;case 69:return 14;case 70:return 15;case 71:return 16;case 72:return 17;case 74:return 18;case 75:return 19;case 77:return 20;case 78:return 21;case 80:return 22;case 81:return 23;case 82:return 24;case 83:return 25;case 84:return 26;case 86:return 27;case 87:return 28;case 88:return 29;case 89:return 30;case 90:return 31;case 73:case 76:return 1;case 79:return 0;default:return-1}}function Ol(e,t,n){let s=0,i=-1;for(let r=0;r<cs(e);r++){const o=e.charCodeAt(r);if(o!==45){if(s>=32)return-1;const a=Ul(o);if(a<0)return-1;s%2===0?i=a:t[n+(s>>1)]=i<<4|a,s++}}return s!==32?-1:0}function Pl(e,t,n){let s=0;for(let i=0;i<16;i++){(i===4||i===6||i===8||i===10)&&(n[s++]=45);const r=e[t+i];n[s++]=jr.charCodeAt(r>>4&15),n[s++]=jr.charCodeAt(r&15)}n[s]=0}class sn{static encode(t,n,s=0){if(Ol(t,n,s)!==0)throw new Error(`Invalid UUID format: "${t}" (must be 36 characters with hyphens)`)}static decode(t,n=0){const s=new Uint8Array(37);return Pl(t,n,s),Zr.decode(s.subarray(0,36))}}function Nl(e,t,n){if(cs(e)!==26)return-1;let s=0n;for(let o=0;o<10;o++){const a=wi(e.charCodeAt(o));if(a<0)return-1;s=s<<5n|BigInt(a)}t[n+0]=Number(s>>40n&0xffn),t[n+1]=Number(s>>32n&0xffn),t[n+2]=Number(s>>24n&0xffn),t[n+3]=Number(s>>16n&0xffn),t[n+4]=Number(s>>8n&0xffn),t[n+5]=Number(s&0xffn);let i=0n;for(let o=10;o<18;o++){const a=wi(e.charCodeAt(o));if(a<0)return-1;i=i<<5n|BigInt(a)}let r=0n;for(let o=18;o<26;o++){const a=wi(e.charCodeAt(o));if(a<0)return-1;r=r<<5n|BigInt(a)}for(let o=0;o<5;o++)t[n+6+o]=Number(i>>BigInt((4-o)*8)&0xffn),t[n+11+o]=Number(r>>BigInt((4-o)*8)&0xffn);return 0}function Bl(e,t,n){let s=0n;for(let o=0;o<6;o++)s=s<<8n|BigInt(e[t+o]);for(let o=9;o>=0;o--)n[o]=Ci.charCodeAt(Number(s%32n)),s/=32n;let i=0n;for(let o=0;o<5;o++)i=i<<8n|BigInt(e[t+6+o]);let r=0n;for(let o=0;o<5;o++)r=r<<8n|BigInt(e[t+11+o]);for(let o=25;o>=18;o--)n[o]=Ci.charCodeAt(Number(r&31n)),r>>=5n;for(let o=17;o>=10;o--)n[o]=Ci.charCodeAt(Number(i&31n)),i>>=5n;n[26]=0}class rn{static encode(t,n,s=0){if(Nl(t,n,s)!==0)throw new Error(`Invalid ULID length: "${t}" (must be 26 Crockford Base32 characters)`)}static decode(t,n=0){const s=new Uint8Array(27);return Bl(t,n,s),Zr.decode(s.subarray(0,26))}}const Si=new TextEncoder,_s=new TextDecoder;function Fn(e,t,n=es,s=0){e.setUint8(t+0,n),e.setUint8(t+1,0),e.setUint16(t+2,0,!0),e.setUint16(t+4,4096,!0),e.setUint32(t+6,s,!0),e.setUint16(t+10,0,!0),e.setUint32(t+De,0,!0)}function Kr(e,t,n=0){e.setUint8(t+0,Ge),e.setUint8(t+1,0),e.setUint16(t+2,0,!0),e.setUint16(t+4,0,!0),e.setUint32(t+6,n,!0),e.setUint16(t+10,0,!0),e.setUint32(t+De,0,!0)}function We(e,t){return e.getUint8(t+0)}function bl(e,t,n){e.setUint8(t+0,n)}function ut(e,t){return e.getUint16(t+2,!0)}function He(e,t,n){e.setUint16(t+2,n,!0)}function qe(e,t){return e.getUint16(t+4,!0)}function Ve(e,t,n){e.setUint16(t+4,n,!0)}function Ut(e,t){return e.getUint32(t+6,!0)}function ds(e,t,n){e.setUint32(t+6,n,!0)}function Ue(e,t){return e.getUint16(t+10,!0)}function $e(e,t,n){e.setUint16(t+10,n,!0)}function Ll(e,t){return e.getUint32(t+De,!0)}function Dl(e,t,n){e.setUint32(t+De,n,!0)}function ot(e,t,n){const s=t+Kt+n*2;return e.getUint16(s,!0)}function on(e,t,n,s){const i=t+Kt+n*2;e.setUint16(i,s,!0)}function ms(e,t){const n=ut(e,t),s=qe(e,t),i=Kt+n*2;return s-i}function Jr(e,t){return ms(e,t)+Ue(e,t)}function Qn(e,t,n=0,s){const i=ut(e,t);if(i===0){Ve(e,t,4096),$e(e,t,0);return}let r=e,o=n;if(n===0||n===t||n+4096>e.byteLength){const c=new Uint8Array(4096);r=new DataView(c.buffer),o=0}nn(r,o,e,t,Kt);let a=4096;for(let c=0;c<i;c++){let l=0,u=e,_=0;if(s&&c===s.cell_idx)l=s.row_bytes.byteLength,u=s.row_bytes,_=0;else{const f=ot(e,t,c);We(e,t)===ts?l=2+e.getUint16(t+f,!0)+8:l=Es(e,t+f),u=e,_=t+f}a=a-l,nn(r,o+a,u,_,l),on(r,o,c,a)}Ve(r,o,a),$e(r,o,0),nn(e,t,r,o,4096)}function Es(e,t){return e.getUint16(t+1,!0)}function an(e,t,n,s){const i=ut(e,t),r=qe(e,t),o=n.byteLength+2,a=Kt+i*2,c=r-a,l=c+Ue(e,t);if(o>l)return-1;o>c&&Qn(e,t,s);const u=qe(e,t),_=ut(e,t),f=u-n.byteLength,h=e.byteOffset+t+f;return new Uint8Array(e.buffer).set(n,h),on(e,t,_,f),He(e,t,_+1),Ve(e,t,f),_}function zr(e,t,n){const s=ut(e,t);if(n>=s)return;const i=ot(e,t,n),r=Es(e,t+i),o=t+Kt,a=o+(n+1)*2,c=o+n*2,l=(s-1-n)*2;l>0&&nn(e,c,e,a,l),He(e,t,s-1),$e(e,t,Ue(e,t)+r)}function Ui(e,t,n,s,i){const r=ut(e,t);if(n<0||n>=r)throw new Error(`Invalid cell index ${n} for update`);const o=ot(e,t,n),a=Es(e,t+o),c=s.byteLength,l=new Uint8Array(e.buffer);if(c<=a)return l.set(s,e.byteOffset+t+o),c<a&&$e(e,t,Ue(e,t)+(a-c)),!0;const u=Jr(e,t),_=c-a;if(u>=_){if(ms(e,t)<c)return Qn(e,t,i,{cell_idx:n,row_bytes:s}),!0;$e(e,t,Ue(e,t)+a);const g=qe(e,t)-c;return l.set(s,e.byteOffset+t+g),on(e,t,n,g),Ve(e,t,g),!0}return!1}function Rl(e){const t=Array.isArray(e)?e:e.columns,n=Math.ceil(t.length/8);let s=0,i=0;for(let r=0;r<t.length;r++){const o=t[r];o.type===C.INT32?s+=4:o.type===C.INT64||o.type===C.FLOAT64?s+=8:o.type===C.UUID||o.type===C.ULID?s+=16:(o.type===C.TEXT||o.type===C.BLOB)&&i++}return{null_bitmap_bytes:n,fixed_slice_size:s,var_col_count:i}}function Is(e,t){const n=Array.isArray(e)?e:e.columns,s=n.length;if(s>ue)throw new Ln(s,ue);const i=Math.ceil(s/8),r=new Uint8Array(i);for(let p=0;p<s;p++){const y=n[p],T=t[y.name];if(T==null){if(y.flags&tt.NOT_NULL)throw new ns(y.name);const b=p>>3,P=1<<(p&7);r[b]|=P}}let o=0;for(let p=0;p<s;p++){const y=n[p];if(!((r[p>>3]&1<<(p&7))!==0))switch(y.type){case C.INT32:o+=4;break;case C.INT64:case C.FLOAT64:o+=8;break;case C.UUID:case C.ULID:o+=16;break}}const a=[];for(let p=0;p<s;p++){const y=n[p];if(y.type===C.TEXT||y.type===C.BLOB)if((r[p>>3]&1<<(p&7))!==0)a.push({col_idx:p,col:y,payload:null});else{const N=t[y.name];let b;y.type===C.TEXT?b=Si.encode(String(N??"")):b=N instanceof Uint8Array?N:new Uint8Array(N),a.push({col_idx:p,col:y,payload:b})}}const c=a.length*4,l=3+i+o+c;let u=0;for(let p=0;p<a.length;p++){const y=a[p];y.payload&&(u+=y.payload.byteLength)}const _=l+u;if(_>2048)throw new br(_,2048);const f=new Uint8Array(_),h=new DataView(f.buffer);h.setUint8(0,1),h.setUint16(1,_,!0),f.set(r,3);let g=3+i;for(let p=0;p<s;p++){const y=n[p];if(!((r[p>>3]&1<<(p&7))!==0)){const N=t[y.name];switch(y.type){case C.INT32:h.setInt32(g,Number(N),!0),g+=4;break;case C.INT64:h.setBigInt64(g,BigInt(N),!0),g+=8;break;case C.FLOAT64:h.setFloat64(g,Number(N),!0),g+=8;break;case C.UUID:sn.encode(String(N),f,g),g+=16;break;case C.ULID:rn.encode(String(N),f,g),g+=16;break}}}let d=g,I=l;for(let p=0;p<a.length;p++){const y=a[p];y.payload===null?(h.setUint16(d,0,!0),h.setUint16(d+2,0,!0)):(h.setUint16(d,I,!0),h.setUint16(d+2,y.payload.byteLength,!0),f.set(y.payload,I),I+=y.payload.byteLength),d+=4}return f}function xe(e,t,n){let s,i,r;if(e instanceof DataView){i=e,r=t;const g=n;s=Array.isArray(g)?g:g.columns}else s=Array.isArray(e)?e:e.columns,i=t,r=n;const o={},a=s.length,c=Math.ceil(a/8),l=new Uint8Array(i.buffer,i.byteOffset+r+3,c);let u=r+3+c,_=0;const f=u;for(let g=0;g<a;g++){const d=s[g];if(!((l[g>>3]&1<<(g&7))!==0))switch(d.type){case C.INT32:u+=4;break;case C.INT64:case C.FLOAT64:u+=8;break;case C.UUID:case C.ULID:u+=16;break}}const h=u;u=f;for(let g=0;g<a;g++){const d=s[g];if((l[g>>3]&1<<(g&7))!==0){o[d.name]=null,(d.type===C.TEXT||d.type===C.BLOB)&&_++;continue}switch(d.type){case C.INT32:o[d.name]=i.getInt32(u,!0),u+=4;break;case C.INT64:o[d.name]=i.getBigInt64(u,!0),u+=8;break;case C.FLOAT64:o[d.name]=i.getFloat64(u,!0),u+=8;break;case C.UUID:{const p=new Uint8Array(i.buffer,i.byteOffset+u,16);o[d.name]=sn.decode(p,0),u+=16;break}case C.ULID:{const p=new Uint8Array(i.buffer,i.byteOffset+u,16);o[d.name]=rn.decode(p,0),u+=16;break}case C.TEXT:{const p=h+_*4,y=i.getUint16(p,!0),T=i.getUint16(p+2,!0),N=i.byteOffset+r+y,b=new Uint8Array(i.buffer,N,T);o[d.name]=_s.decode(b),_++;break}case C.BLOB:{const p=h+_*4,y=i.getUint16(p,!0),T=i.getUint16(p+2,!0),N=i.byteOffset+r+y,b=new Uint8Array(T);b.set(new Uint8Array(i.buffer,N,T)),o[d.name]=b,_++;break}}}return o}function to(e,t,n=0){Fn(e,t,fi,n)}function ps(e,t){return e.getUint32(t+6,!0)}function eo(e,t,n){e.setUint32(t+6,n,!0)}function no(e,t,n,s){const i=ut(e,t);if(i>=lr)return-1;const o=qe(e,t)-ar,a=t+o;return e.setUint32(a,n,!0),e.setBigInt64(a+4,s,!0),on(e,t,i,o),He(e,t,i+1),Ve(e,t,o),i+1}function Fl(e,t,n){const s=ut(e,t);if(s===0)return ps(e,t);let i=0,r=s-1,o=-1;for(;i<=r;){const a=i+r>>1,c=ot(e,t,a),l=e.getBigInt64(t+c+4,!0);n<=l?(o=e.getUint32(t+c,!0),r=a-1):i=a+1}return o!==-1?o:ps(e,t)}function Ql(e,t,n){const s=ut(e,t),i=cr;if(s<=i)throw new Error(`Cannot split interior page with only ${s} cells`);const r=ot(e,t,i),o=e.getUint32(t+r,!0),a=e.getBigInt64(t+r+4,!0),c=ps(e,t);to(e,n,c);for(let l=i+1;l<s;l++){const u=ot(e,t,l),_=e.getUint32(t+u,!0),f=e.getBigInt64(t+u+4,!0);no(e,n,_,f)}return eo(e,t,o),He(e,t,i),{median_rowid:a,promoted_child_page_id:o,right_child_page_id:c}}function ys(e,t,n=0){Fn(e,t,ts,n)}function Ts(e,t,n,s,i,r){if(e!==s)return e-s;if(e===C.NULL)return n<r?-1:n>r?1:0;let o=0;if(e===C.INT32||e===C.INT64||e===C.FLOAT64){const a=typeof t=="bigint"?Number(t):t,c=typeof i=="bigint"?Number(i):i;o=a<c?-1:a>c?1:0}else if(e===C.TEXT||e===C.UUID||e===C.ULID){const a=String(t),c=String(i);o=a<c?-1:a>c?1:0}else if(e===C.BLOB){const a=t,c=i,l=Math.min(a.length,c.length);for(let u=0;u<l;u++)if(a[u]!==c[u]){o=a[u]<c[u]?-1:1;break}o===0&&(o=a.length-c.length)}return o!==0?o:n<r?-1:n>r?1:0}function Oi(e,t,n,s){const i=new Uint8Array(e.buffer,e.byteOffset+t,n);return n===0?{cellType:C.NULL,cellVal:null}:s===C.TEXT?n===4&&(i[2]===0&&i[3]===0||i[2]===255&&i[3]===255)?{cellType:C.INT32,cellVal:new DataView(i.buffer,i.byteOffset).getInt32(0,!0)}:n===2&&i[0]<32&&i[1]<32?{cellType:C.BLOB,cellVal:i}:{cellType:C.TEXT,cellVal:_s.decode(i)}:n===2?{cellType:C.BLOB,cellVal:i}:n===4?{cellType:C.INT32,cellVal:new DataView(i.buffer,i.byteOffset).getInt32(0,!0)}:s===C.UUID&&n===16?{cellType:C.UUID,cellVal:sn.decode(i,0)}:s===C.ULID&&n===16?{cellType:C.ULID,cellVal:rn.decode(i,0)}:s===C.FLOAT64&&n===8?{cellType:C.FLOAT64,cellVal:new DataView(i.buffer,i.byteOffset).getFloat64(0,!0)}:s===C.INT64&&n===8?{cellType:C.INT64,cellVal:new DataView(i.buffer,i.byteOffset).getBigInt64(0,!0)}:s===C.BLOB?n===5||n===6?{cellType:C.TEXT,cellVal:_s.decode(i)}:{cellType:C.BLOB,cellVal:i}:{cellType:C.TEXT,cellVal:_s.decode(i)}}function Pi(e,t,n,s,i,r){let o;n===C.NULL||s===null||s===void 0?o=new Uint8Array(0):n===C.INT32?(o=new Uint8Array(4),new DataView(o.buffer).setInt32(0,Number(s),!0)):n===C.INT64?(o=new Uint8Array(8),new DataView(o.buffer).setBigInt64(0,BigInt(s),!0)):n===C.FLOAT64?(o=new Uint8Array(8),new DataView(o.buffer).setFloat64(0,Number(s),!0)):n===C.UUID?(o=new Uint8Array(16),sn.encode(String(s),o,0)):n===C.ULID?(o=new Uint8Array(16),rn.encode(String(s),o,0)):n===C.TEXT?o=Si.encode(String(s)):o=s instanceof Uint8Array?s:new Uint8Array(s);const a=2+o.byteLength+8,c=a+2,l=ut(e,t),u=ms(e,t),_=u+Ue(e,t);if(c>_)return-1;c>u&&Qn(e,t,r);const h=qe(e,t)-a,g=t+h,d=e.byteOffset+g;e.setUint16(g,o.byteLength,!0),new Uint8Array(e.buffer).set(o,d+2),e.setBigInt64(g+2+o.byteLength,i,!0);let I=0,p=l-1,y=l;for(;I<=p;){const S=I+p>>1,v=ot(e,t,S),L=e.getUint16(t+v,!0),A=e.getBigInt64(t+v+2+L,!0),{cellType:B,cellVal:k}=Oi(e,t+v+2,L,n);Ts(n,s,i,B,k,A)<0?(y=S,p=S-1):I=S+1}const T=new Uint8Array(e.buffer),b=e.byteOffset+t+Kt,P=b+y*2,R=b+(y+1)*2,w=(l-y)*2;return w>0&&T.copyWithin(R,P,P+w),on(e,t,y,h),He(e,t,l+1),Ve(e,t,h),y}function so(e,t,n){const s=ut(e,t);if(n<0||n>=s)return;const i=ot(e,t,n),o=2+e.getUint16(t+i,!0)+8,a=t+Kt,c=a+(n+1)*2,l=a+n*2,u=(s-1-n)*2;u>0&&nn(e,l,e,c,u),He(e,t,s-1),$e(e,t,Ue(e,t)+o)}function vn(e,t,n,s,i){const r=ut(e,t);let o=0,a=r-1;for(;o<=a;){const c=o+a>>1,l=ot(e,t,c),u=e.getUint16(t+l,!0),_=e.getBigInt64(t+l+2+u,!0),{cellType:f,cellVal:h}=Oi(e,t+l+2,u,n),d=Ts(n,s,i!==void 0?i:_,f,h,_);if(d===0){if(i===void 0){let I=c;for(;I>0;){const p=I-1,y=ot(e,t,p),T=e.getUint16(t+y,!0),{cellType:N,cellVal:b}=Oi(e,t+y+2,T,n);if(Ts(n,s,0n,N,b,0n)===0)I=p;else break}return{found:!0,slot_idx:I}}return{found:!0,slot_idx:c}}else d<0?a=c-1:o=c+1}return{found:!1,slot_idx:o}}function io(e,t){if(t==null)return new Uint8Array(0);if(e===C.INT32){const n=new Uint8Array(4);return new DataView(n.buffer).setInt32(0,Number(t),!0),n}if(e===C.INT64){const n=new Uint8Array(8);return new DataView(n.buffer).setBigInt64(0,BigInt(t),!0),n}if(e===C.FLOAT64){const n=new Uint8Array(8);return new DataView(n.buffer).setFloat64(0,Number(t),!0),n}if(e===C.UUID){const n=new Uint8Array(16);return sn.encode(String(t),n,0),n}if(e===C.ULID){const n=new Uint8Array(16);return rn.encode(String(t),n,0),n}return e===C.TEXT?Si.encode(String(t)):t instanceof Uint8Array?t:new Uint8Array(t)}function Cs(e,t,n,s){const i=[];let r=0;for(let c=0;c<n;c++){const l=e[t[c]],u=s[l.name],_=io(l.type,u),f=new Uint8Array(3+_.byteLength);f[0]=l.type,f[1]=_.byteLength&255,f[2]=_.byteLength>>8&255,f.set(_,3),i.push(f),r+=f.byteLength}const o=new Uint8Array(r);let a=0;for(let c=0;c<i.length;c++){const l=i[c];o.set(l,a),a+=l.byteLength}return o}const vl=2654435769;function kn(e,t){const n=Math.imul(e,vl);return(n^n>>>16)>>>0&t}function ro(e,t,n,s){const i=n-1;let r=kn(s,i);for(let o=0;o<n;o++){const a=t+r*Ce,c=e.getUint32(a,!0);if(c===0)return-1;if(c===s)return e.getUint32(a+4,!0);r=r+1&i}return-1}function oo(e,t,n,s,i){const r=n-1;let o=kn(s,r);for(let a=0;a<n;a++){const c=t+o*Ce,l=e.getUint32(c,!0);if(l===0||l===s){e.setUint32(c,s,!0),e.setUint32(c+4,i,!0);return}o=o+1&r}throw new Error(`BufferPool page table full: cannot insert page ${s}`)}function Ni(e,t,n,s){const i=n-1;let r=kn(s,i),o=!1;for(let l=0;l<n;l++){const u=t+r*Ce,_=e.getUint32(u,!0);if(_===0)return!1;if(_===s){o=!0;break}r=r+1&i}if(!o)return!1;let a=r;for(;;){a=a+1&i;const l=t+a*Ce,u=e.getUint32(l,!0);if(u===0)break;const _=kn(u,i);if((r-_&i)<(a-_&i)){const f=e.getUint32(l+4,!0),h=t+r*Ce;e.setUint32(h,u,!0),e.setUint32(h+4,f,!0),r=a}}const c=t+r*Ce;return e.setUint32(c,0,!0),e.setUint32(c+4,0,!0),!0}function kl(e){return e*4096}function ln(e,t,n){return yt(e,t+n*4)}function Bi(e,t,n,s){Tt(e,t+n*4,s)}function Ht(e,t,n,s){return ro(e,t,n,s)}function ao(e,t,n,s,i,r){Yr(r>0,"page_id must be > 0");const o=ln(e,t,i);return o>0&&o!==r&&Ni(e,n,s,o),Bi(e,t,i,r),oo(e,n,s,r,i),0}function lo(e,t,n,s,i){const r=ln(e,t,i);return r>0?(Ni(e,n,s,r),Bi(e,t,i,0),1):0}function co(e,t,n){xr(e,t,n)}function uo(e,t,n){Xr(e,t,n)}function bi(e,t,n){return $r(e,t,n)===1}function Li(e,t){if(e[t]>=4294967295)throw new Error(`Pin count overflow on slot ${t}`);e[t]++}function Di(e,t){t!==0&&e[t]>0&&e[t]--}function cn(e,t){return t===0||e[t]>0}function Ri(e,t,n,s,i,r){const o=new DataView(e);for(let c=1;c<i;c++)if(yt(o,s+c*4)===0&&!cn(n,c))return{candidate_slot:c,next_clock_hand:r};let a=r;for(let c=0;c<i*2;c++){if(a=(a+1)%i,a===0||cn(n,a))continue;const l=new DataView(e,a*4096,4096);if(We(l,0)!==Nn)if(t[a]===1)t[a]=0;else return{candidate_slot:a,next_clock_hand:a}}throw new Error("Cache deadlock: all slots are pinned")}function Fi(e,t,n,s,i,r,o,a){const c=new DataView(e);let l=-1,u=o;if(a>1&&a<=r&&ln(c,s,a-1)===0&&!cn(n,a-1))l=a-1;else{const I=Ri(e,t,n,s,r,o);l=I.candidate_slot,u=I.next_clock_hand}const _=ln(c,s,l),f=bi(new Uint8Array(e),i,l),h=new DataView(e,l*4096,4096),g=_>0&&We(h,0)===Ge,d=f&&!g&&_>0?_:0;return{candidate_slot:l,flush_page_id:d,next_clock_hand:u}}function Ct(e,t){return e.cursors&&e.cursors[t]?e.cursors[t]:e.cursor}function Vt(e,t){if(t<=0)return 0;if(e.byteLength>=Gt+Ar){const n=Ht(e,Gt,Wt,t);if(n>=0)return n*4096}return(t-1)*4096}function un(e,t){if(e==null||t===null||t===void 0)return{result:0,is_unknown:!0};if(typeof e=="boolean"||typeof t=="boolean"){const n=e?1:0,s=t?1:0;return n===s?{result:0,is_unknown:!1}:{result:n>s?1:-1,is_unknown:!1}}if(typeof e=="number"&&typeof t=="number")return e===t?{result:0,is_unknown:!1}:{result:e>t?1:-1,is_unknown:!1};if(typeof e=="bigint"||typeof t=="bigint"){const n=BigInt(e),s=BigInt(t);return n===s?{result:0,is_unknown:!1}:{result:n>s?1:-1,is_unknown:!1}}if(typeof e=="string"&&typeof t=="string")return e===t?{result:0,is_unknown:!1}:{result:e>t?1:-1,is_unknown:!1};if(e instanceof Uint8Array&&t instanceof Uint8Array){const n=Math.min(e.byteLength,t.byteLength);for(let s=0;s<n;s++)if(e[s]!==t[s])return{result:e[s]>t[s]?1:-1,is_unknown:!1};return e.byteLength===t.byteLength?{result:0,is_unknown:!1}:{result:e.byteLength>t.byteLength?1:-1,is_unknown:!1}}return e===t?{result:0,is_unknown:!1}:{result:e>t?1:-1,is_unknown:!1}}function fo(e){return e>=65&&e<=90?e+32:e}function Gl(e,t,n,s){let i=0,r=0,o=-1,a=-1;for(;i<t;){const c=r<s?n.charCodeAt(r):0,l=e.charCodeAt(i);if(r<s&&(c===95||fo(c)===fo(l)))i++,r++;else if(r<s&&c===37)o=r++,a=i;else if(o!==-1)r=o+1,i=++a;else return 0}for(;r<s&&n.charCodeAt(r)===37;)r++;return r===s?1:0}function Xe(e,t){return Gl(e,e.length,t,t.length)===1}function fn(e,t,n){const s=n.numKeys;for(let i=0;i<s;i++){const r=e[i],o=t[i],a=n.directions[i]??0,c=n.nullOrders[i]??(a===1?1:0),l=r==null,u=o==null;if(l&&u)continue;if(l||u)return c===0?l?-1:1:l?1:-1;let _=0;if(typeof r=="number"&&typeof o=="number")_=r<o?-1:r>o?1:0;else if(typeof r=="bigint"||typeof o=="bigint"){const f=BigInt(r),h=BigInt(o);_=f<h?-1:f>h?1:0}else if(typeof r=="string"&&typeof o=="string")_=r<o?-1:r>o?1:0;else if(r instanceof Uint8Array&&o instanceof Uint8Array){const f=Math.min(r.byteLength,o.byteLength);for(let h=0;h<f;h++)if(r[h]!==o[h]){_=r[h]<o[h]?-1:1;break}_===0&&(_=r.byteLength<o.byteLength?-1:r.byteLength>o.byteLength?1:0)}else _=r<o?-1:r>o?1:0;if(_!==0)return a===1?-_:_}return 0}function Ao(e,t,n,s){const i=s.numKeys;for(let r=0;r<i;r++){const o=e[t+r],a=n[r],c=s.directions[r]??0,l=s.nullOrders[r]??(c===1?1:0),u=o==null,_=a==null;if(u&&_)continue;if(u||_)return l===0?u?-1:1:u?1:-1;let 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 h=BigInt(o),g=BigInt(a);f=h<g?-1:h>g?1:0}else if(o instanceof Uint8Array&&a instanceof Uint8Array){const h=Math.min(o.byteLength,a.byteLength);for(let g=0;g<h;g++)if(o[g]!==a[g]){f=o[g]<a[g]?-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 c===1?-f:f}return 0}function ws(e){let t=2166136261;for(let n=0;n<e.length;n++){const s=e[n];if(s==null)t^=255,t=Math.imul(t,16777619);else if(typeof s=="number"){const i=new ArrayBuffer(8);new DataView(i).setFloat64(0,s,!0);const r=new Uint8Array(i);for(let o=0;o<8;o++)t^=r[o],t=Math.imul(t,16777619)}else if(typeof s=="string")for(let i=0;i<s.length;i++)t^=s.charCodeAt(i)&255,t=Math.imul(t,16777619);else if(typeof s=="bigint"){const i=Number(s);t^=i&255,t=Math.imul(t,16777619)}else if(s instanceof Uint8Array)for(let i=0;i<s.byteLength;i++)t^=s[i],t=Math.imul(t,16777619)}return t=t>>>0,t===0?1:t}function Ml(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++){const s=e[n],i=t[n];if(s==null){if(i!=null)return!1}else{if(i==null)return!1;if(s!==i)if(s instanceof Uint8Array&&i instanceof Uint8Array){if(s.byteLength!==i.byteLength)return!1;for(let r=0;r<s.byteLength;r++)if(s[r]!==i[r])return!1}else return!1}}return!0}function ho(e){const t=new Array(e);for(let n=0;n<e;n++)t[n]={hash:0,keys:[],count:0,sum:0,min_val:1/0,max_val:-1/0,has_val:!1};return t}function go(e,t,n,s){let i=t;for(;;){let r=i;const o=2*i+1,a=2*i+2;if(o<n&&fn(e[o].keys,e[r].keys,s)>0&&(r=o),a<n&&fn(e[a].keys,e[r].keys,s)>0&&(r=a),r!==i){const c=e[i];e[i]=e[r],e[r]=c,i=r}else break}}function Wl(e){const t=e.keyInfo;e.entries.sort((n,s)=>fn(n.keys,s.keys,t)),e.readIdx=t.offset??0}function _o(e,t,n){const s=new Uint8Array(e.buffer,e.byteOffset+t,n),i=new Uint8Array(n);return i.set(s),i}function Hl(e,t,n,s,i,r,o){if(o>0&&t.entries.length>=o){if(fn(n,t.entries[0].keys,t.keyInfo)>=0)return O.RUNNING;const u=t.entries[0],_=i-u.rowLen;if(_>0&&e.arenaOffset+_>e.maxQueryMemory)return e.status=O.ARENA_EXHAUSTED,O.ARENA_EXHAUSTED;e.arenaOffset+=_;const f=_o(r,s,i);return u.keys=n,u.rowOffset=s,u.rowLen=i,u.rowData=f,go(t.entries,0,o,t.keyInfo),O.RUNNING}const a=16+16*n.length+i;if(e.arenaOffset+a>e.maxQueryMemory)return e.status=O.ARENA_EXHAUSTED,O.ARENA_EXHAUSTED;e.arenaOffset+=a;const c=_o(r,s,i);if(t.entries.push({keys:n,rowOffset:s,rowLen:i,rowData:c}),o>0&&t.entries.length===o)for(let l=Math.floor(o/2)-1;l>=0;l--)go(t.entries,l,o,t.keyInfo);return O.RUNNING}function ql(e,t,n){var r,o;let s;const i={};if(e.outputColumns&&n===e.outputColumns.length){s=e.outputColumns;for(let a=0;a<n;a++)i[s[a].name]=e.registers[t+a]}else if(e.table&&n===e.table.columns.length){s=e.table.columns;for(let a=0;a<n;a++)i[s[a].name]=e.registers[t+a]}else{s=[];for(let a=0;a<n;a++){const c=e.registers[t+a],l=((o=(r=e.table)==null?void 0:r.columns[a])==null?void 0:o.name)??`col_${a}`;let u=C.TEXT;typeof c=="number"?u=Number.isInteger(c)?C.INT32:C.FLOAT64:typeof c=="bigint"?u=C.INT64:c instanceof Uint8Array&&(u=C.BLOB),s.push({name:l,type:u,flags:tt.NONE,colOffset:0}),i[l]=c}}return Is(s,i)}function Qi(e,t,n,s){const i=2+n.byteLength;if(e.resultOffset+i>Ys)return e.status=O.BUFFER_FULL,e.pc=s,O.BUFFER_FULL;const r=On+e.resultOffset;return t.setUint16(r,n.byteLength,!0),new Uint8Array(t.buffer,t.byteOffset+r+2,n.byteLength).set(n),e.resultOffset+=i,e.resultCount++,O.RUNNING}function Ye(e,t,n){return(e.getUint8(t+(n>>3))&1<<(n&7))!==0}function Gn(e,t,n,s,i){let r=t+n;for(let o=0;o<i;o++)if(!Ye(e,t,o))switch(s[o].type){case C.INT32:r+=4;break;case C.INT64:case C.FLOAT64:r+=8;break;case C.UUID:case C.ULID:r+=16;break}return r}const mo=new TextDecoder;function Mn(e,t,n){var c,l;const s=new DataView(n.buffer,n.byteOffset,n.byteLength),i=n.byteLength,r=1e7;let o=0;const a=t.byteLength>=Yn+4&&t.getUint32(Yn,!0)>0;for(;e.pc<i;){if(++o>r)return e.status=O.TIMEOUT,O.TIMEOUT;const u=e.pc,_=n[e.pc];switch(e.pc+=1,_){case m.OP_HALT:return e.arenaOffset=0,e.status=O.DONE,O.DONE;case m.OP_OPEN_CURSOR:{const f=n[e.pc],h=s.getUint32(e.pc+1,!0);e.pc+=5;const g=Ct(e,f);if(g.pageId=h,g.cellIdx=0,g.rowOffset=0,a&&h>0){const d=Ht(t,Gt,Wt,h);if(d<0)return e.fault_page_id=h,e.status=O.PAGE_FAULT,e.pc=u,O.PAGE_FAULT;g.slotIdx=d}break}case m.OP_REWIND:{const f=n[e.pc],h=s.getUint16(e.pc+1,!0);if(e.pc+=3,h>i)return e.status=O.INVALID_BYTECODE,O.INVALID_BYTECODE;const g=Ct(e,f);if(a&&g.pageId>0){const p=Ht(t,Gt,Wt,g.pageId);if(p<0)return e.fault_page_id=g.pageId,e.status=O.PAGE_FAULT,e.pc=u,O.PAGE_FAULT;g.slotIdx=p}const d=Vt(t,g.pageId);if(ut(t,d)===0)e.pc=h;else{g.cellIdx=0;const p=ot(t,d,0);g.rowOffset=d+p}break}case m.OP_NEXT_ROW:{const f=n[e.pc],h=s.getUint16(e.pc+1,!0);if(e.pc+=3,h>i)return e.status=O.INVALID_BYTECODE,O.INVALID_BYTECODE;const g=Ct(e,f),d=Vt(t,g.pageId),I=ut(t,d),p=g.cellIdx+1;if(p<I){g.cellIdx=p;const y=ot(t,d,g.cellIdx);g.rowOffset=d+y}else{const y=Ut(t,d);if(y!==0){if(a){const b=Ht(t,Gt,Wt,y);if(b<0)return e.fault_page_id=y,e.status=O.PAGE_FAULT,e.pc=u,O.PAGE_FAULT;g.slotIdx=b}g.pageId=y,g.cellIdx=0;const T=Vt(t,y);if(ut(t,T)>0){const b=ot(t,T,0);g.rowOffset=T+b}else e.pc=h}else e.pc=h}break}case m.OP_LAST:{const f=n[e.pc],h=s.getUint16(e.pc+1,!0);if(e.pc+=3,h>i)return e.status=O.INVALID_BYTECODE,O.INVALID_BYTECODE;const g=Ct(e,f),d=Vt(t,g.pageId),I=ut(t,d);if(I===0)e.pc=h;else{g.cellIdx=I-1;const p=ot(t,d,g.cellIdx);g.rowOffset=d+p}break}case m.OP_PREV_ROW:{const f=n[e.pc],h=s.getUint16(e.pc+1,!0);if(e.pc+=3,h>i)return e.status=O.INVALID_BYTECODE,O.INVALID_BYTECODE;const g=Ct(e,f),d=Vt(t,g.pageId);if(g.cellIdx>0){g.cellIdx--;const I=ot(t,d,g.cellIdx);g.rowOffset=d+I}else e.pc=h;break}case m.OP_COLUMN_INT:{const f=n[e.pc],h=n[e.pc+1],g=n[e.pc+2];e.pc+=3;const d=Ct(e,f),I=(e.tables&&e.tables[f])??e.table,p=I.columns[h],y=Math.ceil(I.columns.length/8),T=d.rowOffset+3;if(Ye(t,T,h)){e.registers[g]=null;break}const N=Gn(t,T,y,I.columns,h);p.type===C.INT32?e.registers[g]=t.getInt32(N,!0):p.type===C.INT64&&(e.registers[g]=Number(t.getBigInt64(N,!0)));break}case m.OP_COLUMN_FLOAT:{const f=n[e.pc],h=n[e.pc+1],g=n[e.pc+2];e.pc+=3;const d=Ct(e,f),I=(e.tables&&e.tables[f])??e.table,p=Math.ceil(I.columns.length/8),y=d.rowOffset+3;if(Ye(t,y,h)){e.registers[g]=null;break}const T=Gn(t,y,p,I.columns,h);e.registers[g]=t.getFloat64(T,!0);break}case m.OP_COLUMN_UUID:case m.OP_COLUMN_ULID:case m.OP_COLUMN_TEXT:{const f=n[e.pc],h=n[e.pc+1],g=n[e.pc+2];e.pc+=3;const d=Ct(e,f),I=(e.tables&&e.tables[f])??e.table,p=Math.ceil(I.columns.length/8),y=d.rowOffset+3;if(Ye(t,y,h)){e.registers[g]=null;break}if(I.columns[h].type===C.UUID||I.columns[h].type===C.ULID){const w=Gn(t,y,p,I.columns,h),S=new Uint8Array(t.buffer,t.byteOffset+w,16);e.registers[g]=I.columns[h].type===C.UUID?sn.decode(S,0):rn.decode(S,0);break}const T=Gn(t,y,p,I.columns,I.columns.length);let N=0;for(let w=0;w<h;w++){const S=I.columns[w];(S.type===C.TEXT||S.type===C.BLOB)&&N++}const b=T+N*4,P=t.getUint16(b,!0),R=t.getUint16(b+2,!0);if(R===0)e.registers[g]="";else{const w=new Uint8Array(t.buffer,d.rowOffset+P,R);e.registers[g]=mo.decode(w)}break}case m.OP_COLUMN_BLOB:{const f=n[e.pc],h=n[e.pc+1],g=n[e.pc+2];e.pc+=3;const d=Ct(e,f),I=(e.tables&&e.tables[f])??e.table,p=Math.ceil(I.columns.length/8),y=d.rowOffset+3;if(Ye(t,y,h)){e.registers[g]=null;break}const T=Gn(t,y,p,I.columns,I.columns.length);let N=0;for(let S=0;S<h;S++){const v=I.columns[S];(v.type===C.TEXT||v.type===C.BLOB)&&N++}const b=T+N*4,P=t.getUint16(b,!0),R=t.getUint16(b+2,!0),w=new Uint8Array(R);w.set(new Uint8Array(t.buffer,d.rowOffset+P,R)),e.registers[g]=w;break}case m.OP_OPEN_INDEX:{const f=n[e.pc],h=s.getUint32(e.pc+1,!0);e.pc+=5;const g=Ct(e,f);if(g.pageId=h,g.rootPageId=h,g.cellIdx=0,g.rowOffset=0,a&&h>0){const d=Ht(t,Gt,Wt,h);if(d<0)return e.fault_page_id=h,e.status=O.PAGE_FAULT,e.pc=u,O.PAGE_FAULT;g.slotIdx=d}break}case m.OP_INDEX_SEEK_EQ:{const f=n[e.pc],h=n[e.pc+1],g=n[e.pc+2],d=n[e.pc+3],I=s.getUint16(e.pc+4,!0);if(e.pc+=6,I>i)return e.status=O.INVALID_BYTECODE,O.INVALID_BYTECODE;const p=e.registers[g];if(p==null){e.pc=I;break}const y=Ct(e,f);let T=y.rootPageId||y.pageId,N=!1,b=0n;for(;T!==0;){if(a&&T>0){const w=Ht(t,Gt,Wt,T);if(w<0)return e.fault_page_id=T,e.status=O.PAGE_FAULT,e.pc=u,O.PAGE_FAULT;y.slotIdx=w}const P=Vt(t,T),R=vn(t,P,d,p);if(R.found){N=!0,y.pageId=T,y.cellIdx=R.slot_idx;const w=ot(t,P,R.slot_idx),S=t.getUint16(P+w,!0);b=t.getBigInt64(P+w+2+S,!0);break}T=Ut(t,P)}if(!N)e.pc=I;else{const P=Number(b>>16n),R=Number(b&0xffffn);if(a&&P>0&&Ht(t,Gt,Wt,P)<0)return e.fault_page_id=P,e.status=O.PAGE_FAULT,e.pc=u,O.PAGE_FAULT;const w=Ct(e,h);w.pageId=P,w.cellIdx=R;const S=Vt(t,P),v=ot(t,S,R);w.rowOffset=S+v}break}case m.OP_INDEX_SEEK_GE:{const f=n[e.pc],h=n[e.pc+1],g=n[e.pc+2],d=n[e.pc+3],I=s.getUint16(e.pc+4,!0);if(e.pc+=6,I>i)return e.status=O.INVALID_BYTECODE,O.INVALID_BYTECODE;const p=e.registers[g];if(p==null){e.pc=I;break}const y=Ct(e,f);let T=y.rootPageId||y.pageId,N=!1,b=0n;for(;T!==0;){if(a&&T>0){const S=Ht(t,Gt,Wt,T);if(S<0)return e.fault_page_id=T,e.status=O.PAGE_FAULT,e.pc=u,O.PAGE_FAULT;y.slotIdx=S}const P=Vt(t,T),R=ut(t,P),w=vn(t,P,d,p);if(w.found||w.slot_idx<R){N=!0,y.pageId=T,y.cellIdx=w.slot_idx;const S=ot(t,P,w.slot_idx),v=t.getUint16(P+S,!0);b=t.getBigInt64(P+S+2+v,!0);break}T=Ut(t,P)}if(!N)e.pc=I;else{const P=Number(b>>16n),R=Number(b&0xffffn);if(a&&P>0&&Ht(t,Gt,Wt,P)<0)return e.fault_page_id=P,e.status=O.PAGE_FAULT,e.pc=u,O.PAGE_FAULT;const w=Ct(e,h);w.pageId=P,w.cellIdx=R;const S=Vt(t,P),v=ot(t,S,R);w.rowOffset=S+v}break}case m.OP_INDEX_NEXT:{const f=n[e.pc],h=n[e.pc+1],g=s.getUint16(e.pc+2,!0);if(e.pc+=4,g>i)return e.status=O.INVALID_BYTECODE,O.INVALID_BYTECODE;const d=Ct(e,f);let I=d.pageId,p=Vt(t,I);const y=ut(t,p);let T=d.cellIdx+1;if(T>=y){if(I=Ut(t,p),I===0){e.pc=g;break}if(a&&I>0){const A=Ht(t,Gt,Wt,I);if(A<0)return e.fault_page_id=I,e.status=O.PAGE_FAULT,e.pc=u,O.PAGE_FAULT;d.slotIdx=A}p=Vt(t,I),T=0,d.pageId=I,d.cellIdx=-1}const N=ot(t,p,T),b=t.getUint16(p+N,!0),P=t.getBigInt64(p+N+2+b,!0),R=Number(P>>16n),w=Number(P&0xffffn);if(a&&R>0&&Ht(t,Gt,Wt,R)<0)return e.fault_page_id=R,e.status=O.PAGE_FAULT,e.pc=u,O.PAGE_FAULT;d.pageId=I,d.cellIdx=T;const S=Ct(e,h);S.pageId=R,S.cellIdx=w;const v=Vt(t,R),L=ot(t,v,w);S.rowOffset=v+L;break}case m.OP_IS_NULL:{const f=n[e.pc],h=n[e.pc+1],g=s.getUint16(e.pc+2,!0);if(e.pc+=4,g>i)return e.status=O.INVALID_BYTECODE,O.INVALID_BYTECODE;const I=Ct(e,f).rowOffset+3;Ye(t,I,h)&&(e.pc=g);break}case m.OP_IS_NOT_NULL:{const f=n[e.pc],h=n[e.pc+1],g=s.getUint16(e.pc+2,!0);if(e.pc+=4,g>i)return e.status=O.INVALID_BYTECODE,O.INVALID_BYTECODE;const I=Ct(e,f).rowOffset+3;Ye(t,I,h)||(e.pc=g);break}case m.OP_EQ:{const f=n[e.pc],h=n[e.pc+1],g=s.getUint16(e.pc+2,!0);if(e.pc+=4,g>i)return e.status=O.INVALID_BYTECODE,O.INVALID_BYTECODE;const d=un(e.registers[f],e.registers[h]);!d.is_unknown&&d.result===0&&(e.pc=g);break}case m.OP_NE:{const f=n[e.pc],h=n[e.pc+1],g=s.getUint16(e.pc+2,!0);if(e.pc+=4,g>i)return e.status=O.INVALID_BYTECODE,O.INVALID_BYTECODE;const d=un(e.registers[f],e.registers[h]);!d.is_unknown&&d.result!==0&&(e.pc=g);break}case m.OP_GT:{const f=n[e.pc],h=n[e.pc+1],g=s.getUint16(e.pc+2,!0);if(e.pc+=4,g>i)return e.status=O.INVALID_BYTECODE,O.INVALID_BYTECODE;const d=un(e.registers[f],e.registers[h]);!d.is_unknown&&d.result>0&&(e.pc=g);break}case m.OP_GE:{const f=n[e.pc],h=n[e.pc+1],g=s.getUint16(e.pc+2,!0);if(e.pc+=4,g>i)return e.status=O.INVALID_BYTECODE,O.INVALID_BYTECODE;const d=un(e.registers[f],e.registers[h]);!d.is_unknown&&d.result>=0&&(e.pc=g);break}case m.OP_LT:{const f=n[e.pc],h=n[e.pc+1],g=s.getUint16(e.pc+2,!0);if(e.pc+=4,g>i)return e.status=O.INVALID_BYTECODE,O.INVALID_BYTECODE;const d=un(e.registers[f],e.registers[h]);!d.is_unknown&&d.result<0&&(e.pc=g);break}case m.OP_LE:{const f=n[e.pc],h=n[e.pc+1],g=s.getUint16(e.pc+2,!0);if(e.pc+=4,g>i)return e.status=O.INVALID_BYTECODE,O.INVALID_BYTECODE;const d=un(e.registers[f],e.registers[h]);!d.is_unknown&&d.result<=0&&(e.pc=g);break}case m.OP_JUMP:{const f=s.getUint16(e.pc,!0);if(f>i)return e.status=O.INVALID_BYTECODE,O.INVALID_BYTECODE;e.pc=f;break}case m.OP_STR_LIKE:{const f=n[e.pc],h=n[e.pc+1],g=s.getUint16(e.pc+2,!0);if(e.pc+=4,g>i)return e.status=O.INVALID_BYTECODE,O.INVALID_BYTECODE;const d=e.registers[f],I=e.registers[h];if(d===null||I===null)break;Xe(String(d),String(I))&&(e.pc=g);break}case m.OP_STR_NOT_LIKE:{const f=n[e.pc],h=n[e.pc+1],g=s.getUint16(e.pc+2,!0);if(e.pc+=4,g>i)return e.status=O.INVALID_BYTECODE,O.INVALID_BYTECODE;const d=e.registers[f],I=e.registers[h];if(d===null||I===null)break;Xe(String(d),String(I))||(e.pc=g);break}case m.OP_STR_CONTAINS:{const f=n[e.pc],h=n[e.pc+1],g=s.getUint16(e.pc+2,!0);if(e.pc+=4,g>i)return e.status=O.INVALID_BYTECODE,O.INVALID_BYTECODE;const d=e.registers[f],I=e.registers[h];if(d===null||I===null)break;String(d).includes(String(I))&&(e.pc=g);break}case m.OP_STR_STARTS_WITH:{const f=n[e.pc],h=n[e.pc+1],g=s.getUint16(e.pc+2,!0);if(e.pc+=4,g>i)return e.status=O.INVALID_BYTECODE,O.INVALID_BYTECODE;const d=e.registers[f],I=e.registers[h];if(d===null||I===null)break;String(d).startsWith(String(I))&&(e.pc=g);break}case m.OP_STR_ENDS_WITH:{const f=n[e.pc],h=n[e.pc+1],g=s.getUint16(e.pc+2,!0);if(e.pc+=4,g>i)return e.status=O.INVALID_BYTECODE,O.INVALID_BYTECODE;const d=e.registers[f],I=e.registers[h];if(d===null||I===null)break;String(d).endsWith(String(I))&&(e.pc=g);break}case m.OP_IN:{const f=n[e.pc],h=s.getUint16(e.pc+1,!0),g=s.getUint16(e.pc+3,!0);if(e.pc+=5,g>i)return e.status=O.INVALID_BYTECODE,O.INVALID_BYTECODE;const d=e.registers[f];if(d==null)break;const I=(c=e.inSets)==null?void 0:c[h];I&&(I.has(d)||typeof d=="number"&&Number.isSafeInteger(d)&&I.has(BigInt(d))||typeof d=="bigint"&&I.has(Number(d)))&&(e.pc=g);break}case m.OP_LOAD_INT:{const f=n[e.pc],h=s.getInt32(e.pc+1,!0);e.pc+=5,e.registers[f]=h;break}case m.OP_LOAD_FLOAT:{const f=n[e.pc],h=s.getFloat64(e.pc+1,!0);e.pc+=9,e.registers[f]=h;break}case m.OP_LOAD_TEXT:{const f=n[e.pc],h=s.getUint16(e.pc+1,!0),g=new Uint8Array(n.buffer,n.byteOffset+e.pc+3,h);e.registers[f]=mo.decode(g),e.pc+=3+h;break}case m.OP_LOAD_BLOB:{const f=n[e.pc],h=s.getUint16(e.pc+1,!0),g=new Uint8Array(h);g.set(new Uint8Array(n.buffer,n.byteOffset+e.pc+3,h)),e.registers[f]=g,e.pc+=3+h;break}case m.OP_LOAD_NULL:{const f=n[e.pc];e.pc+=1,e.registers[f]=null;break}case m.OP_EMIT_ROW:{const f=n[e.pc];e.pc+=1;const h=Ct(e,f),g=t.getUint16(h.rowOffset+1,!0),d=new Uint8Array(t.buffer,t.byteOffset+h.rowOffset,g),I=Qi(e,t,d,u);if(I!==O.RUNNING)return I;break}case m.OP_OFFSET:{const f=n[e.pc],h=s.getUint16(e.pc+1,!0);if(e.pc+=3,h>i)return e.status=O.INVALID_BYTECODE,O.INVALID_BYTECODE;const g=Number(e.registers[f]??0);g>0&&(e.registers[f]=g-1,e.pc=h);break}case m.OP_LIMIT:{const f=n[e.pc],h=s.getUint16(e.pc+1,!0);if(e.pc+=3,h>i)return e.status=O.INVALID_BYTECODE,O.INVALID_BYTECODE;const g=Number(e.registers[f]??0);g<=1?(e.registers[f]=0,e.pc=h):e.registers[f]=g-1;break}case m.OP_CALL_UDF:{const f=s.getUint16(e.pc,!0),h=n[e.pc+2],g=n[e.pc+3],d=n[e.pc+4];e.pc+=5;const I=(l=e.udfs)==null?void 0:l[f];if(!I)return e.status=O.INVALID_BYTECODE,O.INVALID_BYTECODE;const p=[];for(let y=0;y<g;y++)p.push(e.registers[h+y]);try{const y=I(...p);e.registers[d]=y!==void 0?y:null}catch{return e.status=O.ERROR,O.ERROR}break}case m.OP_STR_LOWER:{const f=n[e.pc],h=n[e.pc+1];e.pc+=2;const g=e.registers[f];e.registers[h]=g!==null?String(g).toLowerCase():null;break}case m.OP_STR_UPPER:{const f=n[e.pc],h=n[e.pc+1];e.pc+=2;const g=e.registers[f];e.registers[h]=g!==null?String(g).toUpperCase():null;break}case m.OP_STR_LENGTH:{const f=n[e.pc],h=n[e.pc+1];e.pc+=2;const g=e.registers[f];e.registers[h]=g!==null?String(g).length:null;break}case m.OP_STR_SUBSTR:{const f=n[e.pc],h=n[e.pc+1],g=n[e.pc+2],d=n[e.pc+3];e.pc+=4;const I=e.registers[f],p=e.registers[h],y=e.registers[g];if(I===null||p===null){e.registers[d]=null;break}const T=String(I),N=Math.max(0,Number(p)-1);if(y===null)e.registers[d]=T.slice(N);else{const b=Math.max(0,Number(y));e.registers[d]=T.slice(N,N+b)}break}case m.OP_STR_TRIM:{const f=n[e.pc],h=n[e.pc+1];e.pc+=2;const g=e.registers[f];e.registers[h]=g!=null?String(g).trim():null;break}case m.OP_MATH_ABS:{const f=n[e.pc],h=n[e.pc+1];e.pc+=2;const g=e.registers[f];e.registers[h]=g!=null?Math.abs(Number(g)):null;break}case m.OP_MATH_ROUND:{const f=n[e.pc],h=n[e.pc+1];e.pc+=2;const g=e.registers[f];e.registers[h]=g!=null?Math.round(Number(g)):null;break}case m.OP_RESULT_ROW:{const f=n[e.pc],h=n[e.pc+1];e.pc+=2;const g=ql(e,f,h),d=Qi(e,t,g,u);if(d!==O.RUNNING)return d;break}case m.OP_SORTER_OPEN:{const f=n[e.pc],h=n[e.pc+1];e.pc+=2;const g=e.keyInfos[h]??{numKeys:1,directions:[0],nullOrders:[0]},d=g.limit!==void 0&&g.limit>0?(g.offset??0)+g.limit:0,I=d>0&&d<=Or?d:0;e.sorters[f]={keyInfo:g,entries:[],readIdx:0,isSorted:!1,maxK:I};break}case m.OP_SORTER_INSERT:{const f=n[e.pc],h=n[e.pc+1],g=n[e.pc+2],d=n[e.pc+3];e.pc+=4;const I=e.sorters[f];if(!I)return e.status=O.INVALID_BYTECODE,O.INVALID_BYTECODE;const p=I.maxK??0;if(p>0&&I.entries.length>=p){if(g===1){const P=e.registers[h],R=I.entries[0].keys[0],w=I.keyInfo.directions[0]??0;if(typeof P=="number"&&typeof R=="number"){if(w===0?P>=R:P<=R)break}else if(typeof P=="string"&&typeof R=="string"){if(w===0?P>=R:P<=R)break}else if(Ao(e.registers,h,I.entries[0].keys,I.keyInfo)>=0)break}else if(Ao(e.registers,h,I.entries[0].keys,I.keyInfo)>=0)break}const y=Ct(e,d),T=t.getUint16(y.rowOffset+1,!0),N=new Array(g);for(let P=0;P<g;P++)N[P]=e.registers[h+P];const b=Hl(e,I,N,y.rowOffset,T,t,p);if(b!==O.RUNNING)return b;break}case m.OP_SORTER_SORT:{const f=n[e.pc];e.pc+=1;const h=e.sorters[f];if(!h)return e.status=O.INVALID_BYTECODE,O.INVALID_BYTECODE;Wl(h),h.isSorted=!0;break}case m.OP_SORTER_NEXT:{const f=n[e.pc],h=s.getUint16(e.pc+1,!0);if(e.pc+=3,h>i)return e.status=O.INVALID_BYTECODE,O.INVALID_BYTECODE;const g=e.sorters[f];if(!g)return e.status=O.INVALID_BYTECODE,O.INVALID_BYTECODE;const d=g.keyInfo.limit!==void 0?(g.keyInfo.offset??0)+g.keyInfo.limit:g.entries.length;if(g.readIdx>=Math.min(g.entries.length,d))break;const I=g.entries[g.readIdx],p=I.rowData??new Uint8Array(t.buffer,t.byteOffset+I.rowOffset,I.rowLen),y=Qi(e,t,p,u);if(y!==O.RUNNING)return y;g.readIdx++,e.pc=h;break}case m.OP_MATH_FLOOR:{const f=n[e.pc],h=n[e.pc+1];e.pc+=2;const g=e.registers[f];e.registers[h]=g!=null?Math.floor(Number(g)):null;break}case m.OP_MATH_CEIL:{const f=n[e.pc],h=n[e.pc+1];e.pc+=2;const g=e.registers[f];e.registers[h]=g!=null?Math.ceil(Number(g)):null;break}case m.OP_ADD:{const f=n[e.pc],h=n[e.pc+1],g=n[e.pc+2];e.pc+=3;const d=e.registers[f],I=e.registers[h];d==null||I===null||I===void 0?e.registers[g]=null:e.registers[g]=Number(d)+Number(I);break}case m.OP_SUB:{const f=n[e.pc],h=n[e.pc+1],g=n[e.pc+2];e.pc+=3;const d=e.registers[f],I=e.registers[h];d==null||I===null||I===void 0?e.registers[g]=null:e.registers[g]=Number(d)-Number(I);break}case m.OP_MUL:{const f=n[e.pc],h=n[e.pc+1],g=n[e.pc+2];e.pc+=3;const d=e.registers[f],I=e.registers[h];d==null||I===null||I===void 0?e.registers[g]=null:e.registers[g]=Number(d)*Number(I);break}case m.OP_DIV:{const f=n[e.pc],h=n[e.pc+1],g=n[e.pc+2];e.pc+=3;const d=e.registers[f],I=e.registers[h];if(d==null||I===null||I===void 0)e.registers[g]=null;else{const p=Number(I);e.registers[g]=p===0?null:Number(d)/p}break}case m.OP_MOD:{const f=n[e.pc],h=n[e.pc+1],g=n[e.pc+2];e.pc+=3;const d=e.registers[f],I=e.registers[h];if(d==null||I===null||I===void 0)e.registers[g]=null;else{const p=Number(I);e.registers[g]=p===0?null:Number(d)%p}break}case m.OP_STR_CONCAT:{const f=n[e.pc],h=n[e.pc+1],g=n[e.pc+2];e.pc+=3;let d="",I=!1;for(let p=0;p<h;p++){const y=e.registers[f+p];y!=null&&(I=!0,d+=String(y))}e.registers[g]=I?d:null;break}case m.OP_COALESCE:{const f=n[e.pc],h=n[e.pc+1],g=n[e.pc+2];e.pc+=3;let d=null;for(let I=0;I<h;I++){const p=e.registers[f+I];if(p!=null){d=p;break}}e.registers[g]=d;break}case m.OP_COPY:{const f=n[e.pc],h=n[e.pc+1];e.pc+=2,e.registers[h]=e.registers[f];break}case m.OP_AGG_INIT:{const f=n[e.pc],h=n[e.pc+1],g=n[e.pc+2],d=n[e.pc+3];if(e.pc+=4,d===0){if(e.arenaOffset+40960>e.maxQueryMemory)return e.status=O.ARENA_EXHAUSTED,O.ARENA_EXHAUSTED;e.arenaOffset+=40960;const y=ho(1024);if(g===0){const T=ws([]),N=T%1024;y[N].hash=T,y[N].keys=[],y[N].count=0,y[N].sum=0,y[N].min_val=1/0,y[N].max_val=-1/0,y[N].has_val=!1}e.aggregators[f]={mode:0,startKeyReg:h,numKeys:g,capacity:1024,occupiedCount:g===0?1:0,readIdx:0,buckets:y}}else e.aggregators[f]={mode:1,startKeyReg:h,numKeys:g,capacity:1,occupiedCount:0,readIdx:0,buckets:[]};break}case m.OP_AGG_STEP:{const f=n[e.pc],h=n[e.pc+1],g=n[e.pc+2],d=n[e.pc+3],I=n[e.pc+4];e.pc+=5;const p=e.aggregators[f];if(!p)return e.status=O.INVALID_BYTECODE,O.INVALID_BYTECODE;const y=[];for(let N=0;N<g;N++)y.push(e.registers[h+N]);const T=d===255?null:e.registers[d];if(p.mode===0){const N=ws(y),b=N%p.capacity;let P=null;for(let R=0;R<p.capacity;R++){const w=(b+R)%p.capacity,S=p.buckets[w];if(S.hash===0){S.hash=N,S.keys=y.slice(),S.count=0,S.sum=0,S.min_val=1/0,S.max_val=-1/0,S.has_val=!1,p.occupiedCount++,P=S;break}else if(S.hash===N&&Ml(S.keys,y)){P=S;break}}if(!P)return e.status=O.ARENA_EXHAUSTED,O.ARENA_EXHAUSTED;if(I===0)(d===255||T!=null)&&P.count++;else if(I===1||I===2)T!=null&&(P.sum+=Number(T),P.has_val=!0);else if(I===3){if(T!=null){const R=Number(T);(!P.has_val||R<P.min_val)&&(P.min_val=R),P.has_val=!0}}else if(I===4&&T!=null){const R=Number(T);(!P.has_val||R>P.max_val)&&(P.max_val=R),P.has_val=!0}if(p.occupiedCount>.7*p.capacity){const w=p.capacity*2,S=w*40;if(e.arenaOffset+S>e.maxQueryMemory)return e.status=O.ARENA_EXHAUSTED,O.ARENA_EXHAUSTED;e.arenaOffset+=S;const v=p.buckets,L=ho(w);for(let A=0;A<v.length;A++){const B=v[A];if(B.hash!==0){const k=B.hash%w;for(let $=0;$<w;$++){const j=(k+$)%w;if(L[j].hash===0){L[j]=B;break}}}}p.capacity=w,p.buckets=L}}break}case m.OP_AGG_NEXT:{const f=n[e.pc],h=n[e.pc+1],g=n[e.pc+2],d=s.getUint16(e.pc+3,!0);if(e.pc+=5,d>i)return e.status=O.INVALID_BYTECODE,O.INVALID_BYTECODE;const I=e.aggregators[f];if(!I)return e.status=O.INVALID_BYTECODE,O.INVALID_BYTECODE;for(;I.readIdx<I.buckets.length&&I.buckets[I.readIdx].hash===0;)I.readIdx++;if(I.readIdx>=I.buckets.length)break;const p=I.buckets[I.readIdx++];for(let y=0;y<p.keys.length;y++)e.registers[h+y]=p.keys[y];e.registers[g]=p.sum,e.registers[g+1]=p.count,e.registers[g+2]=p.has_val?p.min_val:null,e.registers[g+3]=p.has_val?p.max_val:null,e.pc=d;break}case m.OP_AGG_FINAL:{const f=n[e.pc],h=n[e.pc+1],g=n[e.pc+2],d=n[e.pc+3];e.pc+=4;const I=e.registers[f],p=Number(e.registers[h]??0);d===0?e.registers[g]=p:d===1?e.registers[g]=p>0?Number(I):null:d===2?e.registers[g]=p>0?Number(I)/p:null:(d===3||d===4)&&(e.registers[g]=e.registers[f]);break}case m.OP_REG_IS_NULL:{const f=n[e.pc],h=s.getUint16(e.pc+1,!0);if(e.pc+=3,h>i)return e.status=O.INVALID_BYTECODE,O.INVALID_BYTECODE;const g=e.registers[f];g==null&&(e.pc=h);break}case m.OP_REG_IS_NOT_NULL:{const f=n[e.pc],h=s.getUint16(e.pc+1,!0);if(e.pc+=3,h>i)return e.status=O.INVALID_BYTECODE,O.INVALID_BYTECODE;const g=e.registers[f];g!=null&&(e.pc=h);break}default:return e.status=O.INVALID_BYTECODE,O.INVALID_BYTECODE}}return e.status=O.DONE,O.DONE}const Vl=new TextDecoder,Eo=new Uint8Array([87,69,66,68,66,0]),Io=new Uint32Array(256);let po=0;function $l(){if(!po){for(let e=0;e<256;e++){let t=e;for(let n=0;n<8;n++)t=t&1?3988292384^t>>>1:t>>>1;Io[e]=t>>>0}po=1}}function vi(e,t=0){$l();let n=4294967295;for(let s=0;s<4096;s++){const i=s>=28&&s<=31?0:e.getUint8(t+s);n=Io[(n^i)&255]^n>>>8}return(n^4294967295)>>>0}function yo(e,t=0){ie(e,t,0,4096),e.setUint8(t+Ee+0,87),e.setUint8(t+Ee+1,69),e.setUint8(t+Ee+2,66),e.setUint8(t+Ee+3,68),e.setUint8(t+Ee+4,66),e.setUint8(t+Ee+5,0),e.setUint16(t+qs,4096,!0),e.setUint16(t+Vs,zn,!0),e.setUint16(t+$s,Sr,!0),e.setUint32(t+se,1,!0),e.setUint32(t+le,0,!0),e.setUint32(t+Ie,1,!0),e.setUint32(t+pe,0,!0),e.setUint32(t+ye,0,!0),e.setUint32(t+ur,0,!0),e.setUint32(t+fr,0,!0);const n=vi(e,t);e.setUint32(t+ye,n,!0)}function Wn(e,t=!1){for(let u=0;u<Eo.length;u++)if(e.getUint8(Ee+u)!==Eo[u])throw new Dn("Invalid database file: magic bytes mismatch");const n=e.getUint16(qs,!0),s=e.getUint16(Vs,!0),i=e.getUint16($s,!0),r=e.getUint32(se,!0),o=e.getUint32(le,!0),a=e.getUint32(Ie,!0),c=e.getUint32(pe,!0),l=e.getUint32(ye,!0);if(i>zn)throw new Fr(`Database file format requires engine version >= ${i}, but running engine is version ${zn}`);if(t&&l!==0){const u=vi(e,0);if(u!==l)throw new Se(1,l,u)}return{pageSize:n,fileFormatVersion:s,minReadVersion:i,totalPages:r,freePageHead:o,schemaVersion:a,changeCounter:c,storedChecksum:l}}function To(e,t=0){return e.getUint32(t+se,!0)}function xl(e,t,n){n===void 0&&(n=t,t=0),e.setUint32(t+se,n,!0)}function Xl(e,t=0){return e.getUint32(t+le,!0)}function Yl(e,t,n){n===void 0&&(n=t,t=0),e.setUint32(t+le,n,!0)}function Co(e,t=0){return e.getUint32(t+Ie,!0)}function Ze(e,t=0){const n=Co(e,t)+1;return e.setUint32(t+Ie,n,!0),n}function wo(e,t=0){return e.getUint32(t+pe,!0)}function re(e,t=0){const n=wo(e,t)+1;return e.setUint32(t+pe,n,!0),n}function $t(e,t=0){e.setUint32(t+ye,0,!0);const n=vi(e,t);return e.setUint32(t+ye,n,!0),n}function Ss(e,t,n,s){let i=0;for(;i<s&&i<cs(n);i++)e.setUint8(t+i,n.charCodeAt(i));for(;i<s;i++)e.setUint8(t+i,0)}function Us(e,t,n){const s=[];for(let i=0;i<n;i++){const r=e.getUint8(t+i);if(r===0)break;s.push(r)}return Vl.decode(new Uint8Array(s))}function So(e){switch(e.toUpperCase()){case"INT32":return C.INT32;case"INT64":return C.INT64;case"FLOAT64":return C.FLOAT64;case"TEXT":return C.TEXT;case"BLOB":return C.BLOB;case"UUID":return C.UUID;case"ULID":return C.ULID;default:throw new Error(`Unsupported column data type: "${e}"`)}}function Jt(e,t){const n=Sn+t*Re,s=e.getUint16(n+0,!0);if(s===0)return null;const i=e.getUint16(n+2,!0),r=e.getUint32(n+4,!0),o=e.getUint32(n+8,!0),a=Us(e,n+12,ne),c=e.getUint32(n+76,!0),l=e.getUint32(n+80,!0),u=e.getBigUint64(n+84,!0);return{tableId:s,columnCount:i,rootPageId:r,colCatalogPageId:o,name:a,flags:c,rowCountEstimate:l,autoIncNext:u}}function An(e,t,n){const s=Sn+t*Re;e.setUint16(s+0,n.tableId,!0),e.setUint16(s+2,n.columnCount,!0),e.setUint32(s+4,n.rootPageId,!0),e.setUint32(s+8,n.colCatalogPageId,!0),Ss(e,s+12,n.name,ne),e.setUint32(s+76,n.flags,!0),e.setUint32(s+80,n.rowCountEstimate,!0),e.setBigUint64(s+84,n.autoIncNext,!0),new Uint8Array(e.buffer,e.byteOffset).fill(0,s+92,s+Re)}function Zl(e,t){const n=xt(e,t);return n!==-1?Jt(e,n):null}function xt(e,t){for(let n=0;n<ce;n++){const s=Jt(e,n);if(s&&s.flags&Bn.ACTIVE&&s.name===t)return n}return-1}function ki(e,t=0){for(let n=0;n<ce;n++){const s=t+Sn+n*Re;if(e.getUint16(s,!0)===0)return n}return-1}function hn(e){const t=[];for(let n=0;n<ce;n++){const s=Jt(e,n);s&&s.flags&Bn.ACTIVE&&t.push(s)}return t}function gn(e,t){const n=Un+t*Fe,s=e.getUint16(n+0,!0);if(s===0)return null;const i=e.getUint16(n+2,!0),r=e.getUint32(n+4,!0),o=e.getUint8(n+8),a=e.getUint8(n+9),c=[];for(let _=0;_<8;_++)c.push(e.getUint16(n+10+_*2,!0));const l=[];for(let _=0;_<8;_++)l.push(e.getUint8(n+26+_));const u=Us(e,n+34,ne);return{indexId:s,tableId:i,rootPageId:r,columnCount:o,flags:a,columnIndices:c,colDirections:l,name:u}}function Os(e,t,n){const s=Un+t*Fe;e.setUint16(s+0,n.indexId,!0),e.setUint16(s+2,n.tableId,!0),e.setUint32(s+4,n.rootPageId,!0),e.setUint8(s+8,n.columnCount),e.setUint8(s+9,n.flags);for(let r=0;r<8;r++)e.setUint16(s+10+r*2,n.columnIndices[r]??0,!0);for(let r=0;r<8;r++)e.setUint8(s+26+r,n.colDirections[r]??0);Ss(e,s+34,n.name,ne),new Uint8Array(e.buffer,e.byteOffset).fill(0,s+98,s+Fe)}const Ps=8;function Ns(e,t=0){for(let n=0;n<Ps;n++){const s=t+Un+n*Fe;if(e.getUint16(s+0,!0)===0)return n}return-1}function Bs(e,t){const n=t.toLowerCase();for(let s=0;s<Ps;s++){const i=gn(e,s);if(i&&i.name.toLowerCase()===n)return{slotIdx:s,desc:i}}return null}function Ae(e,t){const n=[];for(let s=0;s<Ps;s++){const i=gn(e,s);i&&i.tableId===t&&n.push(i)}return n}function Gi(e,t,n){if(n===void 0&&(n=t,t=0),n>=Ps)return-1;const s=t+Un+n*Fe;return ie(e,s,0,Fe),0}function Uo(e,t,n){if(n===void 0&&(n=t,t=0),n>=ce)return-1;const s=t+Sn+n*Re;return ie(e,s,0,Re),0}function Oo(e,t,n,s,i=0){ie(e,t,0,4096),e.setUint8(t+0,Nn),e.setUint8(t+1,0),e.setUint16(t+2,0,!0),e.setUint16(t+4,n,!0),e.setUint16(t+6,s,!0),e.setUint32(t+8,i,!0),e.setUint32(t+12,0,!0)}function he(e,t){return{pageType:e.getUint8(t+0),flags:e.getUint8(t+1),colCountInPage:e.getUint16(t+2,!0),tableId:e.getUint16(t+4,!0),startColIndex:e.getUint16(t+6,!0),nextColCatalogPageId:e.getUint32(t+8,!0),pageChecksum:e.getUint32(t+12,!0)}}function jl(e,t,n,s,i,r){e.setUint8(t+0,Nn),e.setUint8(t+1,0),e.setUint16(t+2,n,!0),e.setUint16(t+4,s,!0),e.setUint16(t+6,i,!0),e.setUint32(t+8,r,!0)}function Mi(e,t,n,s){if(n<0||n>=Te)throw new Error(`Invalid catalog in-page slot ${n}`);const i=t+xs+n*Xs;e.setUint8(i+0,s.type),e.setUint8(i+1,s.flags),e.setUint16(i+2,s.colOffset,!0),Ss(e,i+4,s.name,ne),e.setUint32(i+68,0,!0)}function Po(e,t,n){const s=t+xs+n*Xs,i=e.getUint8(s+0),r=e.getUint8(s+1),o=e.getUint16(s+2,!0),a=Us(e,s+4,ne);return{type:i,flags:r,colOffset:o,name:a}}function No(e){return{pageChainIdx:Math.floor(e/Te),colIdxInPage:e%Te}}function Bo(e,t,n,s){var T,N,b,P,R;if(s.length===0)throw new Error("Table must have at least one column");if(s.length>ue)throw new Ln(s.length,ue);if(xt(e,n)!==-1)throw new is(n);const i=ki(e);if(i===-1)throw new gi(ce,ce);const r=i+1,o=t.allocateNewPage(),a=t.getPageBytes(o),c=new DataView(a.buffer,a.byteOffset);c.setUint8(0,13),c.setUint8(1,0),c.setUint16(2,0,!0),c.setUint16(4,4096,!0),c.setUint32(6,0,!0),c.setUint16(10,0,!0),c.setUint32(12,0,!0),t.markPageDirty(o);const l=[];let u=0;for(let w=0;w<s.length;w++){const S=s[w],v=typeof S.type=="string"?So(S.type):S.type;let L=0;typeof S.flags=="number"?L=S.flags:((S.primaryKey||(T=S.flags)!=null&&T.primaryKey)&&(L|=tt.PRIMARY_KEY),(S.notNull||(N=S.flags)!=null&&N.notNull)&&(L|=tt.NOT_NULL),(S.indexed||(b=S.flags)!=null&&b.indexed)&&(L|=tt.INDEXED),(S.autoInc||S.autoIncrement||(P=S.flags)!=null&&P.autoInc||(R=S.flags)!=null&&R.autoIncrement)&&(L|=tt.AUTO_INC));const A=u;switch(v){case C.INT32:u+=4;break;case C.INT64:case C.FLOAT64:u+=8;break;case C.UUID:case C.ULID:u+=16;break}l.push({type:v,flags:L,colOffset:A,name:S.name})}const _=l.length,f=Math.ceil(_/Te),h=[];for(let w=0;w<f;w++)h.push(t.allocateNewPage());for(let w=0;w<f;w++){const S=h[w],v=w<f-1?h[w+1]:0,L=w*Te,A=Math.min(_-L,Te),B=t.getPageBytes(S),k=new DataView(B.buffer,B.byteOffset);Oo(k,0,r,L,v),k.setUint16(2,A,!0);for(let j=0;j<A;j++){const J=l[L+j];Mi(k,0,j,J)}const $=Me(B);k.setUint32(12,$,!0),t.markPageDirty(S)}const g=h[0],d={tableId:r,columnCount:_,rootPageId:o,colCatalogPageId:g,name:n,flags:Bn.ACTIVE,rowCountEstimate:0,autoIncNext:1n};An(e,i,d);const I=[];for(let w=0;w<l.length;w++)l[w].flags&tt.PRIMARY_KEY&&I.push(l[w]);if(I.length>0){const w=Ns(e);if(w!==-1){const S=t.allocateNewPage(),v=t.getPageBytes(S),L=new DataView(v.buffer,v.byteOffset);ys(L,0,0),t.markPageDirty(S);const A=[0,0,0,0,0,0,0,0],B=[0,0,0,0,0,0,0,0];for(let $=0;$<I.length&&$<8;$++){const j=I[$].name;let J=-1;for(let M=0;M<l.length;M++)if(l[M].name===j){J=M;break}A[$]=J}const k={indexId:w+1,tableId:r,rootPageId:S,columnCount:I.length,flags:It.PRIMARY|It.UNIQUE,columnIndices:A,colDirections:B,name:`pk_${n}`};Os(e,w,k)}}Ze(e),re(e),$t(e);const p=Ae(e,r),y=[];for(let w=0;w<I.length;w++)y.push(I[w].name);return{...d,columns:l,primaryKey:y.length>0?y:void 0,indexes:p.length>0?p:void 0}}function Wi(e,t,n){const s=xt(e,n);if(s===-1)throw new bn(n);const i=Jt(e,s),r=[];let o=i.colCatalogPageId,a=0;for(;o!==0&&a<i.columnCount;){const u=t.getPageBytes(o),_=new DataView(u.buffer,u.byteOffset),f=he(_,0);for(let h=0;h<f.colCountInPage;h++){const g=Po(_,0,h);r.push(g),a++}o=f.nextColCatalogPageId}const c=Ae(e,i.tableId),l=[];for(let u=0;u<r.length;u++)r[u].flags&tt.PRIMARY_KEY&&l.push(r[u].name);return{...i,columns:r,primaryKey:l.length>0?l:void 0,indexes:c.length>0?c:void 0}}function Kl(e,t){const n=hn(e),s=[];for(let i=0;i<n.length;i++)s.push(Wi(e,t,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 bo(){if(!Hn){const e=globalThis.Buffer;if(typeof e<"u"&&typeof e.from=="function")Hn=new Uint8Array(e.from(Hi,"base64"));else{const t=atob(Hi),n=t.length;Hn=new Uint8Array(n);for(let s=0;s<n;s++)Hn[s]=t.charCodeAt(s)}}return Hn}function Lo(e,t){const n=t??bo(),s=new WebAssembly.Module(n),i=new WebAssembly.Instance(s,{env:{memory:e}}),r=i.exports,o=(c,l=0)=>c.byteOffset+l;return{instance:i,exports:r,memory:e,page_init:(c,l,u=es,_=0)=>{r.page_init(o(c,l),u,_)},page_init_free:(c,l,u=0)=>{r.page_init_free(o(c,l),u)},page_get_type:(c,l)=>r.page_get_type(o(c,l)),page_set_type:(c,l,u)=>{r.page_set_type(o(c,l),u)},page_get_cell_count:(c,l)=>r.page_get_cell_count(o(c,l)),page_set_cell_count:(c,l,u)=>{r.page_set_cell_count(o(c,l),u)},page_get_cell_content_offset:(c,l)=>r.page_get_cell_content_offset(o(c,l)),page_set_cell_content_offset:(c,l,u)=>{r.page_set_cell_content_offset(o(c,l),u)},page_get_next_page_id:(c,l)=>r.page_get_next_page_id(o(c,l)),page_set_next_page_id:(c,l,u)=>{r.page_set_next_page_id(o(c,l),u)},page_get_free_bytes:(c,l)=>r.page_get_free_bytes(o(c,l)),page_set_free_bytes:(c,l,u)=>{r.page_set_free_bytes(o(c,l),u)},page_get_checksum:(c,l)=>r.page_get_checksum(o(c,l)),page_set_checksum:(c,l,u)=>{r.page_set_checksum(o(c,l),u)},page_get_cell_offset:(c,l,u)=>r.page_get_cell_offset(o(c,l),u),page_set_cell_offset:(c,l,u,_)=>{r.page_set_cell_offset(o(c,l),u,_)},page_get_contiguous_free_space:(c,l)=>r.page_get_contiguous_free_space(o(c,l)),page_get_total_free_space:(c,l)=>r.page_get_total_free_space(o(c,l)),page_compact:(c,l,u=0,_)=>{_?Qn(c,l,u,_):r.page_compact(o(c,l),u,-1,0,0)},page_get_row_length:(c,l)=>r.page_get_row_length(o(c,l)),page_insert_row:(c,l,u,_=0)=>an(c,l,u,_),page_delete_row:(c,l,u)=>{r.page_delete_row(o(c,l),u)},page_update_row:(c,l,u,_,f=0)=>Ui(c,l,u,_,f),page_table_hash:(c,l)=>r.page_table_hash(c,l),page_table_get:(c,l,u,_)=>r.page_table_get(o(c,l),u,_),page_table_set:(c,l,u,_,f)=>{if(r.page_table_set(o(c,l),u,_,f)<0)throw new Error(`BufferPool page table full: cannot insert page ${_}`)},page_table_delete:(c,l,u,_)=>r.page_table_delete(o(c,l),u,_)!==0,buf_pool_get_slot_offset:c=>r.buf_pool_get_slot_offset(c),buf_pool_read_slot_to_page:(c,l,u)=>r.buf_pool_read_slot_to_page(o(c,l),u),buf_pool_write_slot_to_page:(c,l,u,_)=>{r.buf_pool_write_slot_to_page(o(c,l),u,_)},buf_pool_get_resident_slot:(c,l,u,_)=>r.buf_pool_get_resident_slot(o(c,l),u,_),buf_pool_assign_slot:(c,l,u,_,f,h)=>{r.buf_pool_assign_slot(o(c,l),o(c,u),_,f,h)},buf_pool_unassign_slot:(c,l,u,_,f)=>{r.buf_pool_unassign_slot(o(c,l),o(c,u),_,f)},buf_pool_mark_dirty:(c,l,u)=>{r.buf_pool_mark_dirty(o(c,l),u)},buf_pool_clear_dirty:(c,l,u)=>{r.buf_pool_clear_dirty(o(c,l),u)},buf_pool_is_dirty:(c,l,u)=>r.buf_pool_is_dirty(o(c,l),u)!==0,buf_pool_pin_slot:(c,l)=>{Li(c,l)},buf_pool_unpin_slot:(c,l)=>{Di(c,l)},buf_pool_is_pinned:(c,l)=>cn(c,l),buf_pool_find_victim:(c,l,u,_,f,h)=>Ri(c,l,u,_,f,h),buf_pool_select_eviction_victim:(c,l,u,_,f,h,g,d)=>Fi(c,l,u,_,f,h,g,d),catalog_init_page1:c=>{r.catalog_init_page1(o(c))},catalog_read_page1_header:(c,l)=>Wn(c,l),catalog_get_total_pages:c=>r.catalog_get_total_pages(o(c)),catalog_set_total_pages:(c,l)=>{r.catalog_set_total_pages(o(c),l)},catalog_get_free_page_head:c=>r.catalog_get_free_page_head(o(c)),catalog_set_free_page_head:(c,l)=>{r.catalog_set_free_page_head(o(c),l)},catalog_get_schema_version:c=>r.catalog_get_schema_version(o(c)),catalog_increment_schema_version:c=>r.catalog_increment_schema_version(o(c)),catalog_get_change_counter:c=>r.catalog_get_change_counter(o(c)),catalog_increment_change_counter:c=>r.catalog_increment_change_counter(o(c)),catalog_update_page1_checksum:c=>r.catalog_update_page1_checksum(o(c)),sql_like_match:(c,l)=>Xe(c,l),fnv1a_32:c=>ws(c),compare_sorter_keys:fn,vm_step:Mn}}function Do(e=Qe,t=ve){const n=Zs(e,t),s=n.transientArenaOffset+256*1024,i=Math.ceil(s/65536),r=Math.ceil((n.transientArenaOffset+t)/65536);return new WebAssembly.Memory({initial:i,maximum:Math.max(i,r)})}class Ro{constructor(t){U(this,"io");U(this,"wasmMemory");U(this,"buffer");U(this,"view");U(this,"uint8");U(this,"slotCount");U(this,"maxQueryMemory");U(this,"offsets");U(this,"slotsEndOffset");U(this,"slotToPageOffset");U(this,"pageToSlotOffset");U(this,"pageToSlotBuckets");U(this,"dirtyMaskOffset");U(this,"vmContextOffset");U(this,"resultBufferOffset");U(this,"bytecodeOffset");U(this,"pageScratchpadOffset");U(this,"transientArenaOffset");U(this,"pin_counts");U(this,"slot_dirty_generations");U(this,"ref_bits");U(this,"clock_hand",0);U(this,"arena_offset",0);U(this,"in_flight_acquires",new Map);U(this,"allocation_lock",Promise.resolve());var s,i,r;this.slotCount=t.slotCount??((s=t.pool)==null?void 0:s.slotCount)??Qe,this.maxQueryMemory=t.maxQueryMemory??((i=t.pool)==null?void 0:i.maxQueryMemory)??ve;const n=t.memory??((r=t.pool)==null?void 0:r.wasmMemory);if(!n)throw new Error("BufferPoolDriver requires a valid WebAssembly.Memory (or pool with wasmMemory)");if(this.wasmMemory=n,this.buffer=this.wasmMemory.buffer,this.view=new DataView(this.buffer),this.uint8=new Uint8Array(this.buffer),this.offsets=Zs(t.useDefaultLayoutOffsets?Qe:this.slotCount,this.maxQueryMemory),this.slotsEndOffset=this.offsets.slotsEndOffset,this.slotToPageOffset=this.offsets.slotToPageOffset,this.pageToSlotOffset=this.offsets.pageToSlotOffset,this.pageToSlotBuckets=this.offsets.pageToSlotBuckets,this.dirtyMaskOffset=this.offsets.dirtyMaskOffset,this.vmContextOffset=this.offsets.vmContextOffset,this.resultBufferOffset=this.offsets.resultBufferOffset,this.bytecodeOffset=this.offsets.bytecodeOffset,this.pageScratchpadOffset=this.offsets.pageScratchpadOffset,this.transientArenaOffset=this.offsets.transientArenaOffset,this.ref_bits=new Uint8Array(this.slotCount),this.pin_counts=new Uint32Array(this.slotCount),this.slot_dirty_generations=new Uint32Array(this.slotCount),t.io)this.io=t.io;else if(t.vfs)this.io=new Ii({vfs:t.vfs,memory:this.wasmMemory});else throw new Error("BufferPoolDriver requires either an Io instance or IVfsAdapter");ie(this.uint8,this.slotToPageOffset,0,this.slotCount*4),ie(this.uint8,this.pageToSlotOffset,0,this.pageToSlotBuckets*Ce),ie(this.uint8,this.dirtyMaskOffset,0,Math.ceil(this.slotCount/8)),this.assignSlot(0,1),this.pin_counts[0]=1}validate_slot_idx(t){if(!Number.isInteger(t)||t<0||t>=this.slotCount)throw new Error(`Invalid slot index: ${t}. Must be an integer between 0 and ${this.slotCount-1}`)}validate_page_id(t){if(!Number.isInteger(t)||t<=0)throw new Error(`Invalid page ID: ${t}. Page IDs must be positive integers.`)}async with_allocation_lock(t){const n=this.allocation_lock;let s;this.allocation_lock=new Promise(i=>{s=i}),await n;try{return await t()}finally{s()}}setTransactionCoordinator(t){this.io.setTransactionCoordinator(t)}getSlotOffset(t){return this.validate_slot_idx(t),t*4096}getPageBytesInSlot(t){return this.validate_slot_idx(t),this.uint8.subarray(t*4096,(t+1)*4096)}getSlotDataView(t){return this.validate_slot_idx(t),new DataView(this.buffer,t*4096,4096)}getResidentSlot(t){return this.validate_page_id(t),Ht(this.view,this.pageToSlotOffset,this.pageToSlotBuckets,t)}getAssignedPage(t){return this.validate_slot_idx(t),ln(this.view,this.slotToPageOffset,t)}assignSlot(t,n){if(this.validate_slot_idx(t),!Number.isInteger(n)||n<=0)throw new Error(`Invalid page ID: ${n}. Must be a positive integer >= 1`);if(t===0&&n!==1)throw new Error(`Cannot reassign slot 0: reserved permanently for page 1 (got page ${n})`);const s=this.getResidentSlot(n);if(s!==-1&&s!==t)throw new Error(`Cannot map page ${n} to slot ${t}: already resident in slot ${s}`);ao(this.view,this.slotToPageOffset,this.pageToSlotOffset,this.pageToSlotBuckets,t,n),this.ref_bits[t]=1}unassignSlot(t){if(this.validate_slot_idx(t),t===0)throw new Error("Cannot unassign slot 0: reserved permanently for page 1");lo(this.view,this.slotToPageOffset,this.pageToSlotOffset,this.pageToSlotBuckets,t),this.ref_bits[t]=0}markDirty(t){this.validate_slot_idx(t),co(this.uint8,this.dirtyMaskOffset,t),this.slot_dirty_generations[t]++}clearDirty(t){this.validate_slot_idx(t),uo(this.uint8,this.dirtyMaskOffset,t)}isDirty(t){return this.validate_slot_idx(t),bi(this.uint8,this.dirtyMaskOffset,t)}pinSlot(t){this.validate_slot_idx(t),Li(this.pin_counts,t)}unpinSlot(t){this.validate_slot_idx(t),Di(this.pin_counts,t)}pinPage(t){this.validate_page_id(t);const n=this.getResidentSlot(t);if(n===-1)throw new Error(`Cannot pin page ${t}: page is not resident in buffer pool`);this.pinSlot(n)}unpinPage(t){if(this.validate_page_id(t),t===1)return;const n=this.getResidentSlot(t);n!==-1&&this.unpinSlot(n)}forceUnpinSlot(t){this.validate_slot_idx(t),t!==0&&(this.pin_counts[t]=0)}forceUnpinPage(t){if(this.validate_page_id(t),t<=1)return;const n=this.getResidentSlot(t);n!==-1&&this.forceUnpinSlot(n)}isSlotPinned(t){return this.validate_slot_idx(t),cn(this.pin_counts,t)}getPinCount(t){return this.validate_slot_idx(t),this.pin_counts[t]}getRefBit(t){return this.validate_slot_idx(t),this.ref_bits[t]}setRefBit(t,n){this.validate_slot_idx(t),this.ref_bits[t]=n?1:0}allocArena(t){const n=t+7&-8;if(this.arena_offset+n>this.maxQueryMemory)throw new _i;const s=this.transientArenaOffset+this.arena_offset;return this.arena_offset+=n,s}resetArena(){this.arena_offset>0&&(ie(this.uint8,this.transientArenaOffset,0,this.arena_offset),this.arena_offset=0)}getArenaOffset(){return this.arena_offset}async acquirePage(t,n=!1){this.validate_page_id(t);const s=this.getResidentSlot(t);if(s!==-1)return this.setRefBit(s,1),n&&this.pinSlot(s),s;const i=this.in_flight_acquires.get(t);if(i){const o=await i;return n&&this.pinSlot(o),o}const r=(async()=>{const{candidate_slot:o,flush_page_id:a,next_clock_hand:c}=Fi(this.buffer,this.ref_bits,this.pin_counts,this.slotToPageOffset,this.dirtyMaskOffset,this.slotCount,this.clock_hand,t);this.clock_hand=c,this.pinSlot(o);try{return await this.io.resolvePageFault(o,t,a),this.assignSlot(o,t),this.setRefBit(o,1),this.clearDirty(o),o}catch(l){throw o!==-1&&this.unpinSlot(o),l}})();this.in_flight_acquires.set(t,r);try{const o=await r;return n||this.unpinSlot(o),o}finally{this.in_flight_acquires.delete(t)}}acquireAndPinPage(t){return this.acquirePage(t,!0)}async flushSlot(t){this.validate_slot_idx(t);const n=this.getAssignedPage(t);if(n===0)return;if(t===0&&n!==1)throw new Error(`Corruption detected: slot 0 is assigned to page ${n} instead of page 1`);const s=this.slot_dirty_generations[t];await this.io.writeSlot(t,n),this.slot_dirty_generations[t]===s&&this.clearDirty(t)}async flushPage(t){this.validate_page_id(t);const n=this.getResidentSlot(t);n!==-1&&this.isDirty(n)&&await this.flushSlot(n)}async flushAllDirty(){for(let t=0;t<this.slotCount;t++)this.isDirty(t)&&await this.flushSlot(t);await this.io.flush()}async allocatePage(t=!1){return this.with_allocation_lock(async()=>{const n=this.getSlotDataView(0),s=yt(n,le),i=yt(n,se);if(s>0){if(s<=1||i>0&&s>i)throw new Se(s,`Corrupted free_page_head pointer ${s} (totalPages: ${i})`);const c=await this.acquirePage(s,t),l=this.getSlotDataView(c),u=Vr(l,rr);if(u!==Ge)throw new Se(s,`Expected free page type 0x00, got 0x${u.toString(16)}`);const _=yt(l,or);if(_===s||i>0&&_>i)throw new Se(s,`Corrupted next_free_page_id pointer ${_} in free page ${s}`);return Tt(n,le,_),this.markDirty(0),Fn(l,0),this.markDirty(c),s}const r=i+1;Tt(n,se,r),this.markDirty(0);const o=await this.acquirePage(r,t),a=this.getSlotDataView(o);return Fn(a,0),this.markDirty(o),r})}allocateAndPinPage(){return this.allocatePage(!0)}async freePage(t,n=!1){if(this.validate_page_id(t),t<=1)throw new Error(`Cannot free reserved database page ${t}`);return this.with_allocation_lock(async()=>{const s=this.getSlotDataView(0),i=yt(s,se);if(i>0&&t>i)throw new Error(`Cannot free page ${t} beyond total pages ${i}`);const r=this.getResidentSlot(t);if(r!==-1){if(n)this.forceUnpinSlot(r);else if(this.isSlotPinned(r))throw new Error(`Cannot free pinned/active database page ${t}`)}const o=await this.acquirePage(t,!0);try{const a=this.getSlotDataView(o),c=We(a,0);if(c===Ge){if(this.unassignSlot(o),n)return;throw new Error(`Double-free detected: page ${t} is already marked free`)}if(!n&&c===Nn)throw new Error(`Cannot free system catalog page ${t}`);const l=yt(s,le);Kr(a,0,l),ie(this.uint8,o*4096+Kt,0,4096-Kt),this.io.isInTransaction()?await this.io.spillOrWriteSlot(o,t):await this.flushSlot(o),this.unassignSlot(o),this.clearDirty(o),this.setRefBit(o,0),Tt(s,le,t),this.markDirty(0)}finally{this.unpinSlot(o)}})}async stepVm(t,n){let s=Mn(t,this.view,n);for(;s===O.PAGE_FAULT;){const i=t.cursor.pageId;await this.acquirePage(i),t.status=O.RUNNING,s=Mn(t,this.view,n)}return s}}async function qi(e){const t=await e.getWalFrameCount();if(t===0)return{frameCount:0,committedTxCount:0,abortedTxCount:0,replayedPageCount:0};const n=await e.readWalHeader();if(!n)return await e.truncateWal(0),{frameCount:0,committedTxCount:0,abortedTxCount:0,replayedPageCount:0};try{hs(n,!0)}catch{return await e.truncateWal(0),{frameCount:0,committedTxCount:0,abortedTxCount:0,replayedPageCount:0}}const s=await e.readWalFrames(0,t),i=new Map,r=new Set;let o=0;for(const u of s){const _=Ti(u);if(!_.valid||!_.header)break;const{header:f}=_;if(f.frameSeq!==o+1)break;if(o++,i.has(f.txId)||i.set(f.txId,[]),f.frameType===jn)r.add(f.txId);else if(f.frameType===Zn||f.frameType===Kn){const h=new Uint8Array(u.buffer,u.byteOffset+ke,4096),g=new Uint8Array(4096);g.set(h),i.get(f.txId).push({pageId:f.pageId,data:g,frameType:f.frameType})}}const a=new Map;let c=0,l=0;for(const[u,_]of i.entries())if(r.has(u)){c++;for(const f of _)f.pageId>0&&a.set(f.pageId,f.data)}else l++;if(a.size>0){const u=[];for(const[_,f]of a.entries())u.push({pageId:_,data:f});u.sort((_,f)=>_.pageId-f.pageId),await e.writePages(u)}return await e.flush(),await e.truncateWal(0),{frameCount:o,committedTxCount:c,abortedTxCount:l,replayedPageCount:a.size}}class Fo{constructor(t,n){U(this,"activeLease",null);U(this,"inFlightNonTxCount",0);U(this,"queue",[]);U(this,"leaseWaiters",[]);U(this,"nextLeaseId",1);U(this,"nextTxId",1);U(this,"crossTabLockName");U(this,"onSyncCrossTab");U(this,"releaseWebLock",null);this.crossTabLockName=t,this.onSyncCrossTab=n}hasWebLocks(){var t;return!!this.crossTabLockName&&typeof navigator<"u"&&typeof((t=navigator==null?void 0:navigator.locks)==null?void 0:t.request)=="function"}async acquireWebLock(){!this.hasWebLocks()||this.releaseWebLock||await new Promise(t=>{navigator.locks.request(this.crossTabLockName,{mode:"exclusive"},()=>new Promise(n=>{this.releaseWebLock=n,t()})).catch(()=>{t()})})}releaseCurrentWebLock(){if(this.releaseWebLock){const t=this.releaseWebLock;this.releaseWebLock=null,t()}}get isLeased(){return this.activeLease!==null}get currentLease(){return this.activeLease}async enqueue(t,n){if(this.activeLease&&n===this.activeLease.leaseId)return t();if(this.activeLease||this.leaseWaiters.length>0||this.hasWebLocks()&&this.inFlightNonTxCount>0)return new Promise((s,i)=>{this.queue.push(async()=>{this.inFlightNonTxCount++;try{this.hasWebLocks()&&this.inFlightNonTxCount===1&&(await this.acquireWebLock(),this.onSyncCrossTab&&await this.onSyncCrossTab());const r=await t();s(r)}catch(r){i(r)}finally{this.inFlightNonTxCount--,this.inFlightNonTxCount===0&&!this.activeLease&&this.releaseCurrentWebLock(),this.drain()}})});this.inFlightNonTxCount++;try{return this.hasWebLocks()&&this.inFlightNonTxCount===1&&(await this.acquireWebLock(),this.onSyncCrossTab&&await this.onSyncCrossTab()),await t()}finally{this.inFlightNonTxCount--,this.inFlightNonTxCount===0&&!this.activeLease&&this.releaseCurrentWebLock(),this.drain()}}async acquireExclusiveLease(){if(!this.activeLease&&this.inFlightNonTxCount===0&&this.queue.length===0){const t={leaseId:this.nextLeaseId++,txId:this.nextTxId++,createdAt:Date.now()};return this.activeLease=t,await this.acquireWebLock(),t}return new Promise(t=>{this.leaseWaiters.push({resolve:async n=>{await this.acquireWebLock(),t(n)}}),this.drain()})}releaseExclusiveLease(t){!this.activeLease||this.activeLease.leaseId!==t||(this.activeLease=null,this.releaseCurrentWebLock(),this.drain())}drain(){if(!this.activeLease){if(this.leaseWaiters.length>0){if(this.inFlightNonTxCount===0){const t=this.leaseWaiters.shift(),n={leaseId:this.nextLeaseId++,txId:this.nextTxId++,createdAt:Date.now()};this.activeLease=n,t.resolve(n)}return}for(;this.queue.length>0&&!this.activeLease&&this.leaseWaiters.length===0&&(!this.hasWebLocks()||this.inFlightNonTxCount===0);){const t=this.queue.shift();t&&t()}}}}class Qo{constructor(t,n,s,i){U(this,"vfs");U(this,"pool");U(this,"io");U(this,"queue");U(this,"activeLease",null);U(this,"snapshotFrameCount",0);U(this,"snapshotWalFrameSeq",0);U(this,"slotSnapshots",new Map);U(this,"pinCountsSnapshot",null);U(this,"spilledPages",new Map);U(this,"committedWalPages",new Map);U(this,"walFrameSeq",0);U(this,"txCommitCount",0);U(this,"checkpointSeq",0);U(this,"instanceSalt",Math.floor(Math.random()*4294967295)>>>0||1);U(this,"expectedWalFrameCount",0);U(this,"lastDiskChangeCounter",0);U(this,"lastDiskSchemaVersion",0);U(this,"onCrossTabInvalidated");U(this,"idleTimer",null);U(this,"isClosed",!1);this.vfs=t,this.pool=n,this.io=s,this.queue=new Fo(i,()=>this.syncCrossTabState())}setOnCrossTabInvalidated(t){this.onCrossTabInvalidated=t}recordDiskPage1State(){const t=this.pool.getSlotDataView(0);this.lastDiskChangeCounter=t.getUint32(pe,!0),this.lastDiskSchemaVersion=t.getUint32(Ie,!0)}async reloadFromDisk(t,n,s){this.pool.getPageBytesInSlot(0).set(t),this.pool.clearDirty(0),this.lastDiskChangeCounter=n,this.lastDiskSchemaVersion=s;for(let i=1;i<this.pool.slotCount;i++)this.pool.unassignSlot(i),this.pool.clearDirty(i),this.pool.pin_counts[i]=0;this.pool.pin_counts[0]=1,this.onCrossTabInvalidated&&await this.onCrossTabInvalidated()}async syncCrossTabState(t=!1){if(!t&&!this.queue.hasWebLocks())return;const n=await this.vfs.getWalFrameCount();let s=!1;if(n>0){const r=await this.vfs.readWalHeader();let o=0;if(r)try{o=hs(r,!0).salt1}catch{o=0}(o!==this.instanceSalt||n!==this.expectedWalFrameCount)&&(s=!0,await qi(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 r=new DataView(i.buffer,i.byteOffset,i.byteLength),o=r.getUint32(pe,!0),a=r.getUint32(Ie,!0);(s||o!==this.lastDiskChangeCounter||a!==this.lastDiskSchemaVersion)&&await this.reloadFromDisk(i,o,a)}}get leaseQueue(){return this.queue}isInTransaction(){return this.activeLease!==null}getActiveLeaseId(){return this.activeLease?this.activeLease.leaseId:null}getActiveTxId(){return this.activeLease?this.activeLease.txId:null}hasSpilledPage(t){return this.spilledPages.has(t)||this.committedWalPages.has(t)}getSpilledPage(t){const n=this.spilledPages.get(t)??this.committedWalPages.get(t);return n?new Uint8Array(n):null}onDirectPageWrite(t,n){if(this.committedWalPages.has(t)&&this.committedWalPages.set(t,new Uint8Array(n)),t===1){const s=new DataView(n.buffer,n.byteOffset,n.byteLength);this.lastDiskChangeCounter=s.getUint32(pe,!0),this.lastDiskSchemaVersion=s.getUint32(Ie,!0)}}async spillUncommittedSlot(t,n){if(!this.activeLease){await this.io.writeSlot(t,n);return}this.io.stampSlotChecksum(t,n);const s=this.pool.getPageBytesInSlot(t),i=new Uint8Array(we);i.set(s),this.spilledPages.set(n,i);const r=this.pool.getSlotDataView(0).getUint32(se,!0),o=gs({frameType:Kn,flags:0,txId:this.activeLease.txId,pageId:n,dbSizePages:r,frameSeq:++this.walFrameSeq},i);await this.vfs.appendWalFrames([o]),this.expectedWalFrameCount=await this.vfs.getWalFrameCount()}async captureSavepoint(){const t=await this.vfs.getWalFrameCount(),n=new Map;for(let r=0;r<this.pool.slotCount;r++){const o=this.pool.getAssignedPage(r);if(o>0){const a=this.pool.isDirty(r),c=new Uint8Array(this.pool.getPageBytesInSlot(r));n.set(r,{pageId:o,dirty:a,data:c})}}const s=new Uint32Array(this.pool.pin_counts),i=new Map;for(const[r,o]of this.spilledPages.entries())i.set(r,new Uint8Array(o));return{frameCount:t,slotSnapshots:n,pinCounts:s,spilledPages:i,walFrameSeq:this.walFrameSeq}}async restoreSavepoint(t){for(let n=1;n<this.pool.slotCount;n++)this.pool.unassignSlot(n),this.pool.clearDirty(n);for(let n=0;n<this.pool.slotCount;n++){const s=t.slotSnapshots.get(n);s&&(this.pool.assignSlot(n,s.pageId),this.pool.getPageBytesInSlot(n).set(s.data),s.dirty?this.pool.markDirty(n):this.pool.clearDirty(n))}this.pool.pin_counts.set(t.pinCounts),this.spilledPages.clear();for(const[n,s]of t.spilledPages.entries())this.spilledPages.set(n,new Uint8Array(s));this.walFrameSeq=t.walFrameSeq,await this.vfs.truncateWal(t.frameCount),this.expectedWalFrameCount=t.frameCount}async begin(){const t=await this.queue.acquireExclusiveLease();this.activeLease=t,this.pauseIdleTimer();try{await this.syncCrossTabState();const n=await this.vfs.getWalFrameCount(),s=await this.vfs.readWalHeader();let i=!1;if(s&&n>0)try{i=hs(s,!0).salt1===this.instanceSalt}catch{i=!1}i||await this.vfs.writeWalHeader(As({checkpointSeq:this.checkpointSeq,salt1:this.instanceSalt})),this.spilledPages.clear();const r=await this.captureSavepoint();return this.snapshotFrameCount=r.frameCount,this.snapshotWalFrameSeq=r.walFrameSeq,this.slotSnapshots=r.slotSnapshots,this.pinCountsSnapshot=r.pinCounts,t}catch(n){throw this.activeLease=null,this.queue.releaseExclusiveLease(t.leaseId),n}}async commit(t){if(!this.activeLease||this.activeLease.leaseId!==t)return;const n=this.activeLease.txId,s=[],i=this.pool.getSlotDataView(0).getUint32(se,!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 c=this.pool.getPageBytesInSlot(o),l=new Uint8Array(we);l.set(c),this.committedWalPages.set(a,l),this.pool.clearDirty(o),s.push(gs({frameType:Zn,flags:0,txId:n,pageId:a,dbSizePages:i,frameSeq:++this.walFrameSeq},l))}}s.push(gs({frameType:jn,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(t),this.scheduleIdleTimer(),(r>=256||this.txCommitCount>=100)&&this.queue.enqueue(()=>this.executeCheckpoint())}async rollback(t){!this.activeLease||this.activeLease.leaseId!==t||(await this.restoreSavepoint({frameCount:this.snapshotFrameCount,slotSnapshots:this.slotSnapshots,pinCounts:this.pinCountsSnapshot??new Uint32Array(this.pool.pin_counts),spilledPages:new Map,walFrameSeq:this.snapshotWalFrameSeq}),this.activeLease=null,this.spilledPages.clear(),this.slotSnapshots.clear(),this.pinCountsSnapshot=null,this.queue.releaseExclusiveLease(t),this.scheduleIdleTimer())}async checkpoint(){return this.queue.enqueue(()=>this.executeCheckpoint())}async executeCheckpoint(){const t=await this.vfs.getWalFrameCount(),n=new Map;if(t>0){const o=await this.vfs.readWalFrames(0,t),a=new Map,c=new Set;for(const l of o){const u=Ti(l);if(!u.valid||!u.header)break;const{frameType:_,txId:f,pageId:h}=u.header;if(a.has(f)||a.set(f,[]),_===jn)c.add(f);else if(_===Zn||_===Kn){const g=new Uint8Array(l.buffer,l.byteOffset+ke,we),d=new Uint8Array(we);d.set(g),a.get(f).push({pageId:h,data:d})}}for(const[l,u]of a.entries())if(c.has(l))for(const _ of u)_.pageId>0&&n.set(_.pageId,_.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 c=this.pool.getPageBytesInSlot(o),l=new Uint8Array(we);l.set(c),s.set(a,{slotIdx:o,data:l})}}const i=new Set([...n.keys(),...s.keys()]),r=[];for(const o of i)if(s.has(o)){const{slotIdx:a,data:c}=s.get(o);r.push({pageId:o,data:c}),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(As({checkpointSeq:this.checkpointSeq,salt1:this.instanceSalt})),{pagesWritten:r.length}}async resetWalAfterImport(){this.spilledPages.clear(),this.committedWalPages.clear(),await this.vfs.truncateWal(0),this.checkpointSeq++,this.walFrameSeq=0,this.txCommitCount=0,this.expectedWalFrameCount=0,this.recordDiskPage1State(),await this.vfs.writeWalHeader(As({checkpointSeq:this.checkpointSeq,salt1:this.instanceSalt}))}scheduleIdleTimer(){this.isClosed||(this.pauseIdleTimer(),this.idleTimer=setTimeout(()=>{this.checkpoint().catch(()=>{})},5e3))}pauseIdleTimer(){this.idleTimer&&(clearTimeout(this.idleTimer),this.idleTimer=null)}async close(){this.isClosed=!0,this.pauseIdleTimer(),await this.checkpoint()}}const vo=new Set(["count","sum","avg","min","max"]),ko=new Set(["upper","lower","length","substr","trim","abs","round","floor","ceil","concat","coalesce"]);function ge(e){return vo.has(e.toLowerCase())}function Go(e){return ko.has(e.toLowerCase())}function Jl(e){return ge(e)||Go(e)}function je(e,t){if(t==="where"){if(e.type==="fn"&&ge(e.name))throw new os(e.name);if(e.type==="binary"&&(je(e.left,t),je(e.right,t)),e.type==="fn")for(const n of e.args)je(n,t)}}function zl(e){const t=[];let n=0;const s=e.length;for(;n<s;){const i=e[n];if(/\s/.test(i)){n++;continue}if(/[0-9]/.test(i)||i==="."&&n+1<s&&/[0-9]/.test(e[n+1])){const r=n;let o=!1;for(;n<s&&(/[0-9]/.test(e[n])||e[n]==="."&&!o);)e[n]==="."&&(o=!0),n++;t.push({type:"NUMBER",value:e.slice(r,n),pos:r});continue}if(i==="'"||i==='"'){const r=i,o=n;n++;let a="";for(;n<s&&e[n]!==r;)e[n]==="\\"&&n+1<s&&n++,a+=e[n],n++;n<s&&e[n]===r&&n++,t.push({type:"STRING",value:a,pos:o});continue}if(i==="("){t.push({type:"LPAREN",value:"(",pos:n++});continue}if(i===")"){t.push({type:"RPAREN",value:")",pos:n++});continue}if(i===","){t.push({type:"COMMA",value:",",pos:n++});continue}if(i==="<"){if(n+1<s&&e[n+1]==="="){t.push({type:"OP",value:"<=",pos:n}),n+=2;continue}if(n+1<s&&e[n+1]===">"){t.push({type:"OP",value:"!=",pos:n}),n+=2;continue}t.push({type:"OP",value:"<",pos:n++});continue}if(i===">"){if(n+1<s&&e[n+1]==="="){t.push({type:"OP",value:">=",pos:n}),n+=2;continue}t.push({type:"OP",value:">",pos:n++});continue}if(i==="="){if(n+1<s&&e[n+1]==="="){t.push({type:"OP",value:"=",pos:n}),n+=2;continue}t.push({type:"OP",value:"=",pos:n++});continue}if(i==="!"&&n+1<s&&e[n+1]==="="){t.push({type:"OP",value:"!=",pos:n}),n+=2;continue}if(i==="+"||i==="-"||i==="/"||i==="%"){t.push({type:"OP",value:i,pos:n++});continue}if(i==="*"){t.push({type:"STAR",value:"*",pos:n++});continue}if(/[a-zA-Z_]/.test(i)){const r=n;for(;n<s;)if(/[a-zA-Z0-9_]/.test(e[n]))n++;else if(e[n]==="."&&n+1<s&&/[a-zA-Z_]/.test(e[n+1]))n+=2;else break;const o=e.slice(r,n);t.push({type:"IDENT",value:o,pos:r});continue}n++}return t.push({type:"EOF",value:"",pos:s}),t}class tc{constructor(t){U(this,"tokens");U(this,"cursor",0);this.tokens=t}peek(){return this.tokens[this.cursor]??{type:"EOF",value:"",pos:0}}consume(){const t=this.peek();return this.cursor++,t}match(t,n){const s=this.peek();return s.type!==t||n!==void 0&&s.value.toLowerCase()!==n.toLowerCase()?!1:(this.cursor++,!0)}getPrecedence(t){if(t.type==="OP"||t.type==="STAR"){if(t.value==="="||t.value==="!="||t.value==="<"||t.value==="<="||t.value===">"||t.value===">=")return 5;if(t.value==="+"||t.value==="-")return 10;if(t.value==="*"||t.value==="/"||t.value==="%")return 20}return 0}parse(t=0){let n=this.parsePrimary();for(;;){const s=this.peek(),i=this.getPrecedence(s);if(i===0||i<=t)break;this.consume();const r=this.parse(i);n={type:"binary",op:s.value,left:n,right:r}}return n}parsePrimary(){const t=this.peek();if(t.type==="OP"&&t.value==="-"){this.consume();const n=this.parse(25);return n.type==="literal"&&typeof n.value=="number"?{type:"literal",value:-n.value}:{type:"binary",op:"-",left:{type:"literal",value:0},right:n}}if(this.match("NUMBER"))return{type:"literal",value:Number(t.value)};if(this.match("STRING"))return{type:"literal",value:t.value};if(this.match("LPAREN")){const n=this.parse(0);if(!this.match("RPAREN"))throw new Error("Unclosed parenthesis in expression");return n}if(this.match("STAR"))return{type:"col",name:"*"};if(t.type==="IDENT"){this.consume();const n=t.value,s=n.toLowerCase();if(s==="null"&&this.peek().type!=="LPAREN")return{type:"literal",value:null};if(s==="true"&&this.peek().type!=="LPAREN")return{type:"literal",value:!0};if(s==="false"&&this.peek().type!=="LPAREN")return{type:"literal",value:!1};if(this.match("LPAREN")){const i=[];if(!this.match("RPAREN")){for(;;)if(i.push(this.parse(0)),!this.match("COMMA")){if(this.match("RPAREN"))break;throw new Error(`Expected ',' or ')' in argument list of function ${n}`)}}return{type:"fn",name:s,args:i}}return{type:"col",name:n}}throw new Error(`Unexpected token "${t.value}" in expression at position ${t.pos}`)}}function ft(e){const t=e.trim();if(!t)throw new Error("Cannot parse empty expression");const n=zl(t);return new tc(n).parse(0)}function ec(e){let t=0,n=null;const s=e.length;for(let i=0;i<s;i++){const r=e[i];if(n){r===n&&e[i-1]!=="\\"&&(n=null);continue}if(r==="'"||r==='"'){n=r;continue}if(r==="("){t++;continue}if(r===")"){t--;continue}if(t===0&&(r===" "||r===" ")&&i+4<s&&e.slice(i+1,i+3).toLowerCase()==="as"&&/\s/.test(e[i+3])){const o=e.slice(0,i).trim(),a=e.slice(i+4).trim();return{exprStr:o,explicitAlias:a}}}return{exprStr:e.trim()}}function Qt(e){if(e.type==="col")return e.name.includes(".")?e.name.slice(e.name.lastIndexOf(".")+1):e.name;if(e.type==="fn"){if(e.args.length>0&&e.args[0].type==="col"&&e.args[0].name!=="*"){const t=e.args[0].name.includes(".")?e.args[0].name.slice(e.args[0].name.lastIndexOf(".")+1):e.args[0].name;return`${e.name}_${t}`}return e.name}return e.type==="binary"?"expr":"val"}function bs(e){const{exprStr:t,explicitAlias:n}=ec(e),s=ft(t),i=n&&n.length>0?n:Qt(s);return{expr:s,alias:i}}class it{constructor(t){U(this,"node");this.node=t}add(t){return new it({type:"binary",op:"+",left:this.node,right:Xt(t)})}sub(t){return new it({type:"binary",op:"-",left:this.node,right:Xt(t)})}mul(t){return new it({type:"binary",op:"*",left:this.node,right:Xt(t)})}div(t){return new it({type:"binary",op:"/",left:this.node,right:Xt(t)})}mod(t){return new it({type:"binary",op:"%",left:this.node,right:Xt(t)})}eq(t){return new it({type:"binary",op:"=",left:this.node,right:Xt(t)})}ne(t){return new it({type:"binary",op:"!=",left:this.node,right:Xt(t)})}lt(t){return new it({type:"binary",op:"<",left:this.node,right:Xt(t)})}lte(t){return new it({type:"binary",op:"<=",left:this.node,right:Xt(t)})}gt(t){return new it({type:"binary",op:">",left:this.node,right:Xt(t)})}gte(t){return new it({type:"binary",op:">=",left:this.node,right:Xt(t)})}as(t){return{expr:this.node,alias:t}}}function Xt(e){return e===null?{type:"literal",value:null}:typeof e=="boolean"?{type:"literal",value:e}:e instanceof it?e.node:typeof e=="number"?{type:"literal",value:e}:typeof e=="string"?{type:"literal",value:e}:e}function Vi(e){return new it({type:"col",name:e})}function Mo(e){return new it(ft(e))}const nc=Mo;function Pt(e,t){return new it({type:"fn",name:e.toLowerCase(),args:t.map(n=>typeof n=="string"&&!n.startsWith("'")?Vi(n).node:Xt(n))})}const Wo=(e,...t)=>Pt(e,t),sc={upper:e=>Pt("upper",[e]),lower:e=>Pt("lower",[e]),length:e=>Pt("length",[e]),substr:(e,t,n)=>{const s=[e,t];return n!==void 0&&s.push(n),Pt("substr",s)},trim:e=>Pt("trim",[e]),abs:e=>Pt("abs",[e]),round:e=>Pt("round",[e]),floor:e=>Pt("floor",[e]),ceil:e=>Pt("ceil",[e]),count:e=>Pt("count",[e??Vi("*").node]),sum:e=>Pt("sum",[e]),avg:e=>Pt("avg",[e]),min:e=>Pt("min",[e]),max:e=>Pt("max",[e]),concat:(...e)=>Pt("concat",e),coalesce:(...e)=>Pt("coalesce",e)};for(const[e,t]of Object.entries(sc))Object.defineProperty(Wo,e,{value:t,writable:!0,enumerable:!0,configurable:!0});const ic=Wo;function vt(e,t,n){switch(e.type){case"literal":return e.value;case"col":return e.name==="*"?null:t[e.name]!==void 0?t[e.name]:null;case"binary":{const s=vt(e.left,t,n),i=vt(e.right,t,n);if(s===null||i===null||s===void 0||i===void 0)return null;if(e.op==="="||e.op==="!="||e.op==="<"||e.op==="<="||e.op===">"||e.op===">="){const a=typeof s=="string"&&typeof i=="string"?s<i?-1:s>i?1:0:Number(s)<Number(i)?-1:Number(s)>Number(i)?1:0;switch(e.op){case"=":return a===0?1:0;case"!=":return a!==0?1:0;case"<":return a<0?1:0;case"<=":return a<=0?1:0;case">":return a>0?1:0;case">=":return a>=0?1:0}}const r=Number(s),o=Number(i);switch(e.op){case"+":return r+o;case"-":return r-o;case"*":return r*o;case"/":return o===0?null:r/o;case"%":return o===0?null:r%o}return null}case"fn":{const s=e.name.toLowerCase();if(ge(s)){if(t[s]!==void 0)return t[s];const r=e.args[0];if(r&&r.type==="col"){const o=`${s}_${r.name}`;if(t[o]!==void 0)return t[o]}return null}const i=e.args.map(r=>vt(r,t,n));switch(s){case"upper":return i[0]!==null&&i[0]!==void 0?String(i[0]).toUpperCase():null;case"lower":return i[0]!==null&&i[0]!==void 0?String(i[0]).toLowerCase():null;case"length":return i[0]!==null&&i[0]!==void 0?String(i[0]).length:null;case"trim":return i[0]!==null&&i[0]!==void 0?String(i[0]).trim():null;case"substr":{if(i[0]===null||i[0]===void 0)return null;const r=String(i[0]),o=Math.max(0,(Number(i[1])||1)-1),a=i[2]!==null&&i[2]!==void 0?Number(i[2]):void 0;return a!==void 0?r.substring(o,o+a):r.substring(o)}case"abs":return i[0]!==null&&i[0]!==void 0?Math.abs(Number(i[0])):null;case"round":return i[0]!==null&&i[0]!==void 0?Math.round(Number(i[0])):null;case"floor":return i[0]!==null&&i[0]!==void 0?Math.floor(Number(i[0])):null;case"ceil":return i[0]!==null&&i[0]!==void 0?Math.ceil(Number(i[0])):null;case"concat":return i.some(r=>r==null)?null:i.map(String).join("");case"coalesce":{for(const r of i)if(r!=null)return r;return null}case"starts_with":case"startswith":return i[0]!==null&&i[0]!==void 0&&i[1]!==null&&i[1]!==void 0?String(i[0]).startsWith(String(i[1]))?1:0:null;case"ends_with":case"endswith":return i[0]!==null&&i[0]!==void 0&&i[1]!==null&&i[1]!==void 0?String(i[0]).endsWith(String(i[1]))?1:0:null;case"contains":return i[0]!==null&&i[0]!==void 0&&i[1]!==null&&i[1]!==void 0?String(i[0]).includes(String(i[1]))?1:0:null;case"like":return i[0]!==null&&i[0]!==void 0&&i[1]!==null&&i[1]!==void 0?Xe(String(i[0]),String(i[1]))?1:0:null;default:{let r;if(typeof n=="function")r=n(s);else if(n instanceof Map){const o=n.get(s);r=typeof o=="function"?o:o==null?void 0:o.call}else if(n&&typeof n=="object"){const o=n[s];r=typeof o=="function"?o:o==null?void 0:o.call}if(r)return r(...i);throw new di(s)}}}}}const _n=.5,Ls=.05,_e=.02;function Ho(e){const t=[];function n(i){if(i.colName&&t.push(i.colName),i.expr&&s(i.expr),i.children)for(const r of i.children)n(r);i.child&&n(i.child)}function s(i){if(i&&(i.type==="col"&&i.name&&t.push(i.name),i.left&&s(i.left),i.right&&s(i.right),i.args&&Array.isArray(i.args)))for(const r of i.args)s(r)}return n(e),t}function dn(e,t){const n=Ho(e),s=new Set;for(const i of n){const r=ht(i,t);r&&s.add(r.tableIdx)}return s}function $i(e,t){var s,i;const n=Math.max(1,t.rowCountEstimate||10);if(e.type==="cmp"){const r=e.op??"=";if(r==="="){const o=(s=e.colName)==null?void 0:s.toLowerCase(),a=t.columns.findIndex(c=>c.name.toLowerCase()===o);if(a!==-1&&t.indexes){for(const c of t.indexes)if(c.columnCount===1&&c.columnIndices[0]===a)return(c.flags&(It.PRIMARY|It.UNIQUE))!==0?1/n:Math.min(.2,5/n)}return .1}if(r==="<"||r==="<="||r===">"||r===">=")return .33;if(r==="!="||r==="<>")return .9;if(r==="like"||r==="contains"||r==="starts_with"||r==="ends_with")return .15}if(e.type==="in"){const r=Math.max(1,((i=e.values)==null?void 0:i.length)||1);return Math.min(1,r*.05)}return e.type==="null"?e.isNull?.05:.95:.2}function de(e,t,n,s){var _;const i=Math.max(1,e.rowCountEstimate||10);let r=1;for(const f of t)r*=$i(f,e);const o=Math.max(1,Math.round(i*r)),a=n!==void 0&&n.length>0,c=a&&o>1?o*Math.log2(o)*_e:0,l=ks(e,t,t,n);if(l){const f=l.scanType==="point",h=l.scanType==="multi_point",g=l.satisfiesOrderBy===!0,d=g&&s!==void 0&&s>0?Math.min(s,o):o;let I=_n;return f?(I+=1*_e,{cost:I,rows:1,scanType:"IndexScan",indexName:l.index.name,isOrderSatisfied:!0,sortCostAvoided:a?c:void 0}):h?(I=(((_=l.inValues)==null?void 0:_.length)||1)*_n+d*_e,!g&&a&&(I+=c),{cost:I,rows:d,scanType:"IndexScan",indexName:l.index.name,isOrderSatisfied:g,sortCostAvoided:g?c:void 0}):(I+=d*Ls+d*_e,!g&&a&&(I+=c),{cost:I,rows:d,scanType:"IndexScan",indexName:l.index.name,isOrderSatisfied:g,sortCostAvoided:g?c:void 0})}let u=i*_e;return a&&(u+=c),{cost:u,rows:o,scanType:"TableScan",isOrderSatisfied:!1}}function qn(e,t){if(!e.indexes||e.indexes.length===0)return null;const n=e.columns.findIndex(r=>r.name.toLowerCase()===t.toLowerCase());if(n===-1)return null;let s=null,i=999;for(const r of e.indexes)if(r.columnCount===1&&r.columnIndices[0]===n){const o=(r.flags&It.PRIMARY)!==0,a=(r.flags&It.UNIQUE)!==0,c=o?1:a?2:3;c<i&&(i=c,s={index:r,isUnique:o||a})}return s}function Ds(e,t){const n=t.length,s=[],i=Array.from({length:n},()=>new Set);if(!e.joinedTables)return{edges:s,dependencies:i};for(let r=0;r<e.joinedTables.length;r++){const o=e.joinedTables[r],a=r+1,c=ht(o.leftCol,t),l=ht(o.rightCol,t);if(c&&l&&(s.push({tableA:c.tableIdx,tableB:l.tableIdx,colA:c.col.name,colB:l.col.name,op:o.op,type:o.type,declaredRightTable:a}),o.type==="left")){const u=c.tableIdx===a?l.tableIdx:c.tableIdx;i[a].add(u)}}return{edges:s,dependencies:i}}function Vn(e,t){if(e.selectExprs&&e.selectExprs.length>0)return e.selectExprs;const n=new Set,s=new Set;for(const r of t)for(const o of r.columns)n.has(o.name.toLowerCase())&&s.add(o.name.toLowerCase()),n.add(o.name.toLowerCase());const i=[];for(const r of t)for(const o of r.columns){const a=s.has(o.name.toLowerCase())?`${r.name}.${o.name}`:o.name;i.push({expr:{type:"col",name:`${r.name}.${o.name}`},alias:a})}return i}function Rs(e,t,n,s){const i=e.length,r=[];for(let o=1;o<i;o++){const a=e[o],c=t[a],l=e.slice(0,o),u=n.find(d=>d.tableA===a&&l.includes(d.tableB)||d.tableB===a&&l.includes(d.tableA));let _,f,h="=",g="inner";if(u)h=u.op,g=u.type,u.tableA===a?(f=`${c.name}.${u.colA}`,_=`${t[u.tableB].name}.${u.colB}`):(f=`${c.name}.${u.colB}`,_=`${t[u.tableA].name}.${u.colA}`);else{const d=s==null?void 0:s.find(I=>I.table.name===c.name);_=d?d.leftCol:`${t[e[0]].name}.id`,f=d?d.rightCol:`${c.name}.id`,h=d?d.op:"=",g=d?d.type:"inner"}r.push({type:g,table:c,cursor:o,leftCol:_,op:h,rightCol:f})}return r}function xi(e,t,n,s,i){if(!s||s.length===0)return!1;for(const r of s){if(r.direction==="desc")return!1;const o=r.colName;if(!o)return!1;let a=ht(o,n);if(!a&&i){const c=i.find(l=>l.alias===o);c&&c.expr.type==="col"&&(a=ht(c.expr.name,n))}if(!a||a.tableIdx!==t)return!1}return!0}function Xi(e,t){var n;if(e.type==="null")return 1;if(e.type==="cmp"){const s=e.op??"=";if(s==="like"||s==="not like")return(typeof e.value=="string"?e.value:"").startsWith("%")?25:15;let i=!1;if(t&&e.colName){const r=e.colName.toLowerCase(),o=r.includes(".")?r.slice(r.lastIndexOf(".")+1):r;for(const a of t){const c=a.columns.find(l=>l.name.toLowerCase()===o);if(c){i=c.type===1||c.type===2||c.type===3;break}}}else typeof e.value=="number"&&(i=!0);return s==="="||s==="=="?i?2:4:i?3:6}return e.type==="in"?(((n=e.values)==null?void 0:n.length)??0)<=3?5:10:e.type==="expr"?40:e.type==="and"||e.type==="or"?15:e.type==="not"?8:10}function Yi(e,t){if(!e||e.length===0)return{filters:[],isAlwaysFalse:!1,isAlwaysTrue:!0,metrics:{originalCount:0,optimizedCount:0,isAlwaysFalse:!1,isAlwaysTrue:!0,eliminatedFiltersCount:0,reordered:!1}};const n=e.length,s=[];for(const _ of e)_.type==="and"&&Array.isArray(_.children)?s.push(..._.children):s.push(_);const i=new Map,r=[];for(const _ of s)if(_.colName){const f=_.colName.toLowerCase();i.has(f)||i.set(f,[]),i.get(f).push(_)}else r.push(_);for(const[_,f]of i.entries()){const h=rc(f);if(h)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 o=[];let a=0;for(const[,_]of i.entries()){const f=oc(_);a+=_.length-f.length,o.push(...f)}o.push(...r);const c=o.map(_=>Zi(_)).join("|");o.sort((_,f)=>{const h=Xi(_,t),g=Xi(f,t);return h-g});const l=o.map(_=>Zi(_)).join("|"),u=c!==l;return{filters:o,isAlwaysFalse:!1,isAlwaysTrue:o.length===0,metrics:{originalCount:n,optimizedCount:o.length,isAlwaysFalse:!1,isAlwaysTrue:o.length===0,eliminatedFiltersCount:a,reordered:u}}}function rc(e){let t=!1,n=!1;const s=[];let i=null,r=null,o=null;for(const a of e){if(a.type==="null"&&(a.isNull===!0&&(t=!0),a.isNull===!1&&(n=!0)),a.type==="cmp"){const c=a.op??"=",l=a.value;c==="="&&l!==null&&l!==void 0&&s.push(l),typeof l=="number"&&(c===">"?(!i||l>i.val||l===i.val&&!i.strict)&&(i={val:l,strict:!0}):c===">="?(!i||l>i.val)&&(i={val:l,strict:!1}):c==="<"?(!r||l<r.val||l===r.val&&!r.strict)&&(r={val:l,strict:!0}):c==="<="&&(!r||l<r.val)&&(r={val:l,strict:!1}))}if(a.type==="in"&&!a.notIn){if(!a.values||a.values.length===0)return"Empty IN () list";const c=new Set(a.values);if(!o)o=c;else{const l=new Set([...o].filter(u=>c.has(u)));if(l.size===0)return"Mutually exclusive IN lists with no common values";o=l}}}if(t&&n)return"Conflicting IS NULL and IS NOT NULL";if(t&&(s.length>0||i||r))return"Conflicting IS NULL and literal comparison";if(s.length>1){const a=s[0];for(let c=1;c<s.length;c++)if(s[c]!==a)return`Conflicting equality values (${a} !== ${s[c]})`}if(s.length>0&&(i||r)){const a=s[0];if(typeof a=="number"){if(i&&(i.strict?a<=i.val:a<i.val))return`Equality value ${a} violates lower bound ${i.strict?">":">="} ${i.val}`;if(r&&(r.strict?a>=r.val:a>r.val))return`Equality value ${a} violates upper bound ${r.strict?"<":"<="} ${r.val}`}}if(s.length>0&&o){const a=s[0];if(!o.has(a))return`Equality value ${a} not present in IN list`}if(i&&r){if(i.val>r.val)return`Lower bound ${i.val} is greater than upper bound ${r.val}`;if(i.val===r.val&&(i.strict||r.strict))return`Strict range bounds empty at ${i.val}`}return null}function oc(e){const t=[],n=new Set;let s=!1,i;for(const a of e)if(a.type==="cmp"&&(a.op==="="||a.op===void 0)&&a.value!==null&&a.value!==void 0){s=!0,i=a.value;break}let r=null,o=null;for(const a of e)if(a.type==="cmp"&&typeof a.value=="number"){const c=a.op??"=",l=a.value;c===">"?(!r||l>r.val||l===r.val&&!r.strict)&&(r={val:l,strict:!0,filter:a}):c===">="?(!r||l>r.val)&&(r={val:l,strict:!1,filter:a}):c==="<"?(!o||l<o.val||l===o.val&&!o.strict)&&(o={val:l,strict:!0,filter:a}):c==="<="&&(!o||l<o.val)&&(o={val:l,strict:!1,filter:a})}for(const a of e){const c=Zi(a);if(!n.has(c)&&!(a.type==="null"&&a.isNull===!1&&s)&&!(a.type==="in"&&!a.notIn&&s&&Array.isArray(a.values)&&a.values.includes(i))){if(a.type==="cmp"&&typeof a.value=="number"){const l=a.op??"=";if(l===">"||l===">="){if(r&&a!==r.filter)continue}else if((l==="<"||l==="<=")&&o&&a!==o.filter)continue}n.add(c),t.push(a)}}return t}function Zi(e){return`${e.type}:${e.colName??""}:${e.isNull??""}:${e.op??""}:${String(e.value??"")}:${e.notIn??""}:${JSON.stringify(e.values??"")}`}function qo(e,t){const n=[...e],s=o=>o.toLowerCase(),i=o=>{const a=o.lastIndexOf(".");return a>=0?o.slice(a+1).toLowerCase():o.toLowerCase()},r=o=>{const a=s(o),c=i(o);for(const l of e)if(l.type==="cmp"&&(l.op==="="||l.op==="=="||l.op===void 0)&&l.colName&&l.value!==null&&l.value!==void 0){const u=s(l.colName),_=i(l.colName);if(u===a||_===a||u===c)return l.value}};for(const o of t){if(o.type!=="inner"&&o.type!=="left"||o.op!=="="&&o.op!=="==")continue;const a=r(o.leftCol);if(a!==void 0&&n.push({type:"cmp",colName:o.rightCol,op:"=",value:a}),o.type==="inner"){const c=r(o.rightCol);c!==void 0&&n.push({type:"cmp",colName:o.leftCol,op:"=",value:c})}}return n}class Fs{constructor(t){U(this,"name","cost");U(this,"indexSeekCost");U(this,"indexNextCost");U(this,"rowEvalCost");this.indexSeekCost=(t==null?void 0:t.indexSeekCost)??_n,this.indexNextCost=(t==null?void 0:t.indexNextCost)??Ls,this.rowEvalCost=(t==null?void 0:t.rowEvalCost)??_e}optimize(t){var L,A;const n=[t.table,...((L=t.joinedTables)==null?void 0:L.map(B=>B.table))??[]],s=n.length,i=Yi(t.filters,n);if(i.isAlwaysFalse)return{plan:{...t,filters:[]},orderedTables:n,metrics:null,isAlwaysFalse:!0,whereMetrics:i.metrics};let r=i.filters,o=i.metrics;if(t.joinedTables&&t.joinedTables.length>0){const B=qo(r,t.joinedTables);if(B.length>r.length){const k=Yi(B,n);if(k.isAlwaysFalse)return{plan:{...t,filters:[]},orderedTables:n,metrics:null,isAlwaysFalse:!0,whereMetrics:k.metrics};r=k.filters,o=k.metrics}}if(s<=1||!t.joinedTables||t.joinedTables.length===0){const B=new Map;B.set(0,r);const k=de(t.table,r,t.orderBy,t.limit);return{plan:{...t,filters:r},orderedTables:[t.table],metrics:{totalCost:k.cost,estimatedRows:k.rows,joinOrder:[t.table.name],singleTableFilters:B,crossFilters:[],tableScanTypes:[k.scanType],tableIndexNames:[k.indexName],isOrderSatisfied:k.isOrderSatisfied,sortCostAvoided:k.sortCostAvoided},isAlwaysFalse:!1,isAlwaysTrue:o.isAlwaysTrue,whereMetrics:o,isOrderSatisfied:k.isOrderSatisfied,sortCostAvoided:k.sortCostAvoided}}const a=zt(r),c=mn(a),l=new Map,u=[];for(let B=0;B<s;B++)l.set(B,[]);for(const B of c){const k=dn(B,n);if(k.size===1){const $=k.values().next().value;$!==void 0&&((A=l.get($))==null||A.push(B))}else u.push(B)}if(s<=1||!t.joinedTables||t.joinedTables.length===0){const B=de(n[0],l.get(0)??[]);return{plan:t,orderedTables:n,metrics:{totalCost:B.cost,estimatedRows:B.rows,joinOrder:[n[0].name],singleTableFilters:l,crossFilters:u,tableScanTypes:[B.scanType],tableIndexNames:[B.indexName]}}}const{edges:_,dependencies:f}=Ds(t,n),h=new Map;for(let B=0;B<s;B++)if(f[B].size===0){const k=xi(n[B],B,n,t.orderBy,t.selectExprs),$=k?t.orderBy.map(M=>{const W=M.colName??"",ee=W.includes(".")?W.slice(W.lastIndexOf(".")+1):W;return{...M,colName:ee}}):void 0,j=de(n[B],l.get(B)??[],$,k?t.limit:void 0),J=1<<B;h.set(J,{order:[B],cost:j.cost,rows:j.rows,scanTypes:[j.scanType],indexNames:[j.indexName],edgesUsed:[],isOrderSatisfied:j.isOrderSatisfied,sortCostAvoided:j.sortCostAvoided})}const g=1<<s;for(let B=2;B<=s;B++)for(let k=1;k<g;k++)if(ac(k)===B)for(let $=0;$<s;$++){if(!(k&1<<$))continue;const j=k^1<<$,J=h.get(j);if(!J)continue;let M=!0;for(const Ne of f[$])if(!(j&1<<Ne)){M=!1;break}if(!M)continue;const W=this.evaluateJoinStep(J.rows,n[$],$,_,J.order,l.get($)??[]),ee=J.cost+W.stepCost,Et=h.get(k);let gt=!1,En=ee,In=Et?Et.cost:0;const pn=J.isOrderSatisfied===!0,Ke=(Et==null?void 0:Et.isOrderSatisfied)===!0;if(B===s&&t.orderBy&&t.orderBy.length>0&&(!pn&&W.newRows>1&&(En+=W.newRows*Math.log2(W.newRows)*this.rowEvalCost),Et&&!Ke&&Et.rows>1&&(In+=Et.rows*Math.log2(Et.rows)*this.rowEvalCost)),!Et)gt=!0;else if(pn&&!Ke)gt=!0;else if(!pn&&Ke)gt=!1;else{const Ne=J.scanTypes.filter(Be=>Be==="IndexScan").length+(W.scanType==="IndexScan"?1:0),Xn=Et.scanTypes.filter(Be=>Be==="IndexScan").length;if(Ne>Xn&&En<=In*1.2)gt=!0;else if(Ne<Xn)gt=!1;else if(En<In*.75)gt=!0;else if(In<En*.75)gt=!1;else{const Be=J.order[0]===0,yn=Et.order[0]===0;if(Be&&!yn)gt=!0;else if(!Be&&yn)gt=!1;else{const oe=J.order.filter(Tn=>Tn>$).length,Ws=Et.order.filter((Tn,Hs)=>Tn>Hs).length;oe<Ws&&(gt=!0)}}}gt&&h.set(k,{order:[...J.order,$],cost:ee,rows:W.newRows,scanTypes:[...J.scanTypes,W.scanType],indexNames:[...J.indexNames,W.indexName],edgesUsed:[...J.edgesUsed,W.matchedEdge],isOrderSatisfied:J.isOrderSatisfied,sortCostAvoided:J.sortCostAvoided})}const d=(1<<s)-1,I=h.get(d);let p,y,T,N,b;I?(p=I.order,y=I.cost,T=I.rows,N=I.scanTypes,b=I.indexNames):(p=Array.from({length:s},(B,k)=>k),y=999999,T=100,N=Array.from({length:s},()=>"TableScan"),b=Array.from({length:s},()=>{}));const P=p.map(B=>n[B]),R=Rs(p,n,_,t.joinedTables),w=Vn(t,n),S=(I==null?void 0:I.isOrderSatisfied)===!0,v=S&&t.orderBy&&t.orderBy.length>0&&T>1?T*Math.log2(T)*this.rowEvalCost:void 0;return{plan:{...t,table:P[0],joinedTables:R,selectExprs:w,filters:r,isOrderSatisfied:S},orderedTables:P,metrics:{totalCost:y,estimatedRows:T,joinOrder:P.map(B=>B.name),singleTableFilters:l,crossFilters:u,tableScanTypes:N,tableIndexNames:b,isOrderSatisfied:S,sortCostAvoided:v},isAlwaysFalse:!1,isAlwaysTrue:o.isAlwaysTrue,whereMetrics:o,isOrderSatisfied:S,sortCostAvoided:v}}evaluateJoinStep(t,n,s,i,r,o){const a=Math.max(1,n.rowCountEstimate||10);let c=1;for(const h of o)c*=$i(h,n);const l=[];for(const h of i)if(h.tableA===s&&r.includes(h.tableB)){const g=qn(n,h.colA);l.push({edge:h,nextCol:h.colA,outerCol:h.colB,idxMatch:g})}else if(h.tableB===s&&r.includes(h.tableA)){const g=qn(n,h.colB);l.push({edge:h,nextCol:h.colB,outerCol:h.colA,idxMatch:g})}if(l.length===0){const h=t*(2+a*.1),g=Math.max(1,Math.round(t*a*c)),d={tableA:r[0],tableB:s,colA:"",colB:"",op:"=",type:"inner",declaredRightTable:s};return{stepCost:h,newRows:g,scanType:"TableScan",matchedEdge:d}}l.sort((h,g)=>{const d=h.idxMatch?h.idxMatch.isUnique?1:2:3,I=g.idxMatch?g.idxMatch.isUnique?1:2:3;return d-I});const u=l[0];if(u.idxMatch&&u.idxMatch.isUnique){const h=this.indexSeekCost+1*this.rowEvalCost,g=t*h,d=Math.max(1,Math.round(t*c));return{stepCost:g,newRows:d,scanType:"IndexScan",indexName:u.idxMatch.index.name,matchedEdge:u.edge}}if(u.idxMatch&&!u.idxMatch.isUnique){const h=Math.max(1,Math.min(10,Math.round(a/20))),g=this.indexSeekCost+h*this.indexNextCost,d=t*g,I=Math.max(1,Math.round(t*h*c));return{stepCost:d,newRows:I,scanType:"IndexScan",indexName:u.idxMatch.index.name,matchedEdge:u.edge}}const _=t*(2+a*.1),f=Math.max(1,Math.round(t*Math.max(1,Math.round(a*.1))*c));return{stepCost:_,newRows:f,scanType:"TableScan",matchedEdge:u.edge}}}function ac(e){let t=0,n=e;for(;n>0;)t+=n&1,n>>=1;return t}class Vo{constructor(){U(this,"name","heuristic")}optimize(t){var w,S,v;const n=[t.table,...((w=t.joinedTables)==null?void 0:w.map(L=>L.table))??[]],s=n.length,i=zt(t.filters),r=mn(i),o=new Map,a=[];for(let L=0;L<s;L++)o.set(L,[]);for(const L of r){const A=dn(L,n);if(A.size===1){const B=A.values().next().value;B!==void 0&&((S=o.get(B))==null||S.push(L))}else a.push(L)}if(s<=1||!t.joinedTables||t.joinedTables.length===0){const L=de(n[0],o.get(0)??[],t.orderBy,t.limit);return{plan:t,orderedTables:n,metrics:{totalCost:L.cost,estimatedRows:L.rows,joinOrder:[n[0].name],singleTableFilters:o,crossFilters:a,tableScanTypes:[L.scanType],tableIndexNames:[L.indexName],isOrderSatisfied:L.isOrderSatisfied,sortCostAvoided:L.sortCostAvoided},isOrderSatisfied:L.isOrderSatisfied,sortCostAvoided:L.sortCostAvoided}}const{edges:c,dependencies:l}=Ds(t,n),u=n.map((L,A)=>{const B=xi(L,A,n,t.orderBy,t.selectExprs),k=B?t.orderBy.map($=>{const j=$.colName??"",J=j.includes(".")?j.slice(j.lastIndexOf(".")+1):j;return{...$,colName:J}}):void 0;return de(L,o.get(A)??[],k,B?t.limit:void 0)}),_=[];for(let L=0;L<s;L++)l[L].size===0&&_.push(L);_.sort((L,A)=>{const B=u[L].isOrderSatisfied?1:0,k=u[A].isOrderSatisfied?1:0;if(B!==k)return k-B;if(u[L].rows!==u[A].rows)return u[L].rows-u[A].rows;const $=u[L].scanType==="IndexScan"?1:0,j=u[A].scanType==="IndexScan"?1:0;return $!==j?j-$:L===0?-1:A===0?1:L-A});const f=_[0]??0,h=[f],g=[u[f].scanType],d=[u[f].indexName];let I=u[f].cost,p=u[f].rows;const y=new Set;for(let L=0;L<s;L++)L!==f&&y.add(L);for(;y.size>0;){const L=[];for(const B of y){let k=!0;for(const M of l[B])if(!h.includes(M)){k=!1;break}if(!k)continue;const $=n[B],j=Math.max(1,$.rowCountEstimate||10);let J=null;for(const M of c)if(M.tableA===B&&h.includes(M.tableB)){const W=qn($,M.colA);W&&(!J||W.isUnique)&&(J={isUnique:W.isUnique,indexName:W.index.name})}else if(M.tableB===B&&h.includes(M.tableA)){const W=qn($,M.colB);W&&(!J||W.isUnique)&&(J={isUnique:W.isUnique,indexName:W.index.name})}if(J)if(J.isUnique){const M=_n+1*_e;L.push({tableIdx:B,rank:1,stepCost:p*M,newRows:Math.max(1,p),scanType:"IndexScan",indexName:J.indexName})}else{const M=Math.max(1,Math.min(10,Math.round(j/20))),W=_n+M*Ls;L.push({tableIdx:B,rank:2,stepCost:p*W,newRows:Math.max(1,p*M),scanType:"IndexScan",indexName:J.indexName})}else L.push({tableIdx:B,rank:3,stepCost:p*(2+j*.1),newRows:Math.max(1,p*Math.max(1,Math.round(j*.1))),scanType:"TableScan"})}if(L.length===0){const B=y.values().next().value;if(B===void 0)break;h.push(B),g.push("TableScan"),d.push(void 0),y.delete(B);continue}L.sort((B,k)=>B.rank!==k.rank?B.rank-k.rank:Math.abs(B.stepCost-k.stepCost)>.05?B.stepCost-k.stepCost:B.tableIdx-k.tableIdx);const A=L[0];h.push(A.tableIdx),g.push(A.scanType),d.push(A.indexName),I+=A.stepCost,p=A.newRows,y.delete(A.tableIdx)}const T=h.map(L=>n[L]),N=Rs(h,n,c,t.joinedTables),b=Vn(t,n),P=((v=u[f])==null?void 0:v.isOrderSatisfied)===!0,R=P&&t.orderBy&&t.orderBy.length>0&&p>1?p*Math.log2(p)*_e:void 0;return{plan:{...t,table:T[0],joinedTables:N,selectExprs:b,isOrderSatisfied:P},orderedTables:T,metrics:{totalCost:I,estimatedRows:p,joinOrder:T.map(L=>L.name),singleTableFilters:o,crossFilters:a,tableScanTypes:g,tableIndexNames:d,isOrderSatisfied:P,sortCostAvoided:R},isOrderSatisfied:P,sortCostAvoided:R}}}class $o{constructor(){U(this,"name","noop")}optimize(t){var g,d;const n=[t.table,...((g=t.joinedTables)==null?void 0:g.map(I=>I.table))??[]],s=n.length,i=zt(t.filters),r=mn(i),o=new Map,a=[];for(let I=0;I<s;I++)o.set(I,[]);for(const I of r){const p=dn(I,n);if(p.size===1){const y=p.values().next().value;y!==void 0&&((d=o.get(y))==null||d.push(I))}else a.push(I)}const c=de(n[0],o.get(0)??[]),l=[c.scanType],u=[c.indexName];let _=c.cost;const f=c.rows;if(t.joinedTables)for(let I=1;I<s;I++){const p=t.joinedTables[I-1],y=Gs(p,n[I],I,n,I);y?(l.push("IndexScan"),u.push(y.index.name),_+=f*.55):(l.push("TableScan"),u.push(void 0),_+=f*(2+(n[I].rowCountEstimate||10)*.1))}const h=Vn(t,n);return{plan:{...t,selectExprs:h},orderedTables:n,metrics:{totalCost:_,estimatedRows:f,joinOrder:n.map(I=>I.name),singleTableFilters:o,crossFilters:a,tableScanTypes:l,tableIndexNames:u}}}}class lc{constructor(t){U(this,"name","custom-order");U(this,"orderSpec");this.orderSpec=t}optimize(t){var b,P,R;const n=[t.table,...((b=t.joinedTables)==null?void 0:b.map(w=>w.table))??[]],s=n.length,i=t.joinedTables!==void 0&&t.joinedTables.length>0,r=zt(t.filters),o=mn(r),a=new Map,c=[];for(let w=0;w<s;w++)a.set(w,[]);for(const w of o){const S=dn(w,n);if(S.size===1){const v=S.values().next().value;v!==void 0&&((P=a.get(v))==null||P.push(w))}else c.push(w)}if(!i||s<=1){const w=de(n[0],a.get(0)??[]);return{plan:t,orderedTables:n,metrics:{totalCost:w.cost,estimatedRows:w.rows,joinOrder:[n[0].name],singleTableFilters:a,crossFilters:c,tableScanTypes:[w.scanType],tableIndexNames:[w.indexName]}}}const l=Array.from({length:s},(w,S)=>S);if(this.orderSpec){if(typeof this.orderSpec=="function"){const w=this.orderSpec;l.sort((S,v)=>w(n[S],n[v]))}else if(Array.isArray(this.orderSpec)){const w=this.orderSpec;l.sort((S,v)=>{const L=n[S].name,A=n[v].name,B=w.indexOf(L),k=w.indexOf(A),$=B===-1?9999:B,j=k===-1?9999:k;return $!==j?$-j:S-v})}}const{edges:u}=Ds(t,n),_=l.map(w=>n[w]),f=Rs(l,n,u,t.joinedTables),h=Vn(t,n),g={...t,table:_[0],joinedTables:f,selectExprs:h},d=new Map;for(let w=0;w<s;w++)d.set(w,[]);for(const w of o){const S=dn(w,_);if(S.size===1){const v=S.values().next().value;v!==void 0&&((R=d.get(v))==null||R.push(w))}}const I=de(_[0],d.get(0)??[]),p=[I.scanType],y=[I.indexName];let T=I.cost;const N=I.rows;if(g.joinedTables)for(let w=1;w<s;w++){const S=g.joinedTables[w-1],v=Gs(S,_[w],w,_,w);v?(p.push("IndexScan"),y.push(v.index.name),T+=N*.55):(p.push("TableScan"),y.push(void 0),T+=N*(2+(_[w].rowCountEstimate||10)*.1))}return{plan:g,orderedTables:_,metrics:{totalCost:T,estimatedRows:N,joinOrder:_.map(w=>w.name),singleTableFilters:d,crossFilters:c,tableScanTypes:p,tableIndexNames:y}}}}class xo{constructor(t){U(this,"name","custom");this.fn=t}optimize(t){return this.fn(t)}}const cc=xo,uc=Fs,fc=Fs,Ac=Vo,hc=$o,gc=new Fs;function ji(e){return e??gc}function _c(e,t){return ji(t).optimize(e)}function $n(e){if(!e)return m.OP_EQ;switch(String(e).trim().toLowerCase().replace(/\s+/g," ")){case"=":case"==":return m.OP_EQ;case"!=":case"<>":return m.OP_NE;case">":return m.OP_GT;case">=":return m.OP_GE;case"<":return m.OP_LT;case"<=":return m.OP_LE;case"like":return m.OP_STR_LIKE;case"not like":return m.OP_STR_NOT_LIKE;case"contains":return m.OP_STR_CONTAINS;case"starts_with":return m.OP_STR_STARTS_WITH;case"ends_with":return m.OP_STR_ENDS_WITH;default:return m.OP_EQ}}class Qs{constructor(){U(this,"buffer",[]);U(this,"textEncoder",new TextEncoder)}emitUint8(t){const n=this.buffer.length;return this.buffer.push(t&255),n}emitUint16(t){const n=this.buffer.length;return this.buffer.push(t&255),this.buffer.push(t>>8&255),n}emitUint32(t){const n=this.buffer.length;return this.buffer.push(t&255),this.buffer.push(t>>8&255),this.buffer.push(t>>16&255),this.buffer.push(t>>24&255),n}emitInt32(t){return this.emitUint32(t)}emitFloat64(t){const n=this.buffer.length,s=new ArrayBuffer(8);new DataView(s).setFloat64(0,t,!0);const i=new Uint8Array(s);for(let r=0;r<8;r++)this.buffer.push(i[r]);return n}emitString(t){const n=this.textEncoder.encode(t),s=this.emitUint16(n.byteLength);for(let i=0;i<n.byteLength;i++)this.buffer.push(n[i]);return s}emitBytes(t){const n=this.emitUint16(t.byteLength);for(let s=0;s<t.byteLength;s++)this.buffer.push(t[s]);return n}patchUint16(t,n){this.buffer[t]=n&255,this.buffer[t+1]=n>>8&255}currentOffset(){return this.buffer.length}toByteArray(){return new Uint8Array(this.buffer)}}function bt(e,t,n,s,i){i===C.INT32||i===C.INT64?(e.emitUint8(m.OP_COLUMN_INT),e.emitUint8(t),e.emitUint8(n),e.emitUint8(s)):i===C.FLOAT64?(e.emitUint8(m.OP_COLUMN_FLOAT),e.emitUint8(t),e.emitUint8(n),e.emitUint8(s)):i===C.TEXT?(e.emitUint8(m.OP_COLUMN_TEXT),e.emitUint8(t),e.emitUint8(n),e.emitUint8(s)):i===C.UUID?(e.emitUint8(m.OP_COLUMN_UUID),e.emitUint8(t),e.emitUint8(n),e.emitUint8(s)):i===C.ULID?(e.emitUint8(m.OP_COLUMN_ULID),e.emitUint8(t),e.emitUint8(n),e.emitUint8(s)):i===C.BLOB&&(e.emitUint8(m.OP_COLUMN_BLOB),e.emitUint8(t),e.emitUint8(n),e.emitUint8(s))}function Oe(e){if(e.type==="in"){if(e.values&&e.values.length>Ft)throw new RangeError(`WebDB: whereIn list exceeds maximum limit of ${Ft} elements`);return{type:"in",colName:e.colName,expr:e.expr,values:e.values?Array.from(new Set(e.values)):[],notIn:!!e.notIn}}if(e.type==="cmp"){const t=e.op?String(e.op).trim().toLowerCase():"";if(t==="in"||t==="not in"){const n=Array.isArray(e.value)?e.value:[e.value];if(n.length>Ft)throw new RangeError(`WebDB: whereIn list exceeds maximum limit of ${Ft} elements`);return{type:"in",colName:e.colName,expr:e.expr,values:Array.from(new Set(n)),notIn:t==="not in"}}}if(e.type==="and")return{type:"and",children:e.children?e.children.map(Oe):[]};if(e.type==="or")return{type:"or",children:e.children?e.children.map(Oe):[]};if(e.type==="not"){const t=e.child;if(!t)return e;if(t.type==="not"&&t.child)return Oe(t.child);if(t.type==="in")return{type:"in",colName:t.colName,expr:t.expr,values:t.values,notIn:!t.notIn};if(t.type==="and")return{type:"or",children:t.children?t.children.map(n=>Oe({type:"not",child:n})):[]};if(t.type==="or")return{type:"and",children:t.children?t.children.map(n=>Oe({type:"not",child:n})):[]};if(t.type==="null")return{type:"null",colName:t.colName,expr:t.expr,isNull:!t.isNull};if(t.type==="cmp"){const n=t.op?String(t.op).trim().toLowerCase():"";if(n==="in"||n==="not in")return Oe({type:"in",colName:t.colName,expr:t.expr,values:Array.isArray(t.value)?t.value:[t.value],notIn:n==="in"});const s={"=":"!=","!=":"=",">":"<=",">=":"<","<":">=","<=":">",like:"not like","not like":"like"};return t.op&&s[t.op]?{type:"cmp",colName:t.colName,op:s[t.op],value:t.value}:{type:"and",children:[{type:"null",colName:t.colName,isNull:!1},{type:"not",child:t}]}}}return e}function zt(e){if(!e||e.length===0)return null;const t=e.length===1?e[0]:{type:"and",children:e};return Oe(t)}function Xo(e){const t=[],n=new Set;function s(i){if(i.type==="null"||i.type==="cmp"||i.type==="expr"||i.type==="in")n.has(i)||(n.add(i),t.push(i));else if(i.type==="and"||i.type==="or"){if(i.children)for(const r of i.children)s(r)}else i.type==="not"&&i.child&&s(i.child)}return s(e),t}function mn(e){if(!e)return[];const t=[];function n(s){if(s.type==="and"&&s.children)for(const i of s.children)n(i);else(s.type==="cmp"||s.type==="in"||s.type==="null")&&t.push(s)}return n(e),t}function ht(e,t){if(e.includes(".")){const n=e.split("."),s=n[0],i=n[1],r=t.findIndex(a=>a.name.toLowerCase()===s.toLowerCase());if(r===-1)return null;const o=t[r].columns.findIndex(a=>a.name.toLowerCase()===i.toLowerCase());return o===-1?null:{tableIdx:r,cursor:r,colIdx:o,col:t[r].columns[o],table:t[r]}}for(let n=0;n<t.length;n++){const s=t[n].columns.findIndex(i=>i.name.toLowerCase()===e.toLowerCase());if(s!==-1)return{tableIdx:n,cursor:n,colIdx:s,col:t[n].columns[s],table:t[n]}}return null}function Ki(e,t,n,s,i,r,o,a){const c=o??[n];if(e.type==="expr"){const f=t*2,h=t*2+1;let g=50;const d=()=>{if(g>=64)throw new st(g);return g++};Z(e.expr,n,s,0,f,d,r,void 0,c),s.emitUint8(m.OP_LOAD_INT),s.emitUint8(h),s.emitInt32(1),s.emitUint8(m.OP_EQ),s.emitUint8(f),s.emitUint8(h),i.push(s.emitUint16(0));return}if(e.type==="null"){if(e.expr){const h=t*2;let g=50;const d=()=>{if(g>=64)throw new st(g);return g++};Z(e.expr,n,s,0,h,d,r,void 0,c),e.isNull?s.emitUint8(m.OP_REG_IS_NULL):s.emitUint8(m.OP_REG_IS_NOT_NULL),s.emitUint8(h),i.push(s.emitUint16(0));return}if(!e.colName)throw new Error("Filter leaf node missing colName");const f=ht(e.colName,c);if(!f)throw new Error(`Column "${e.colName}" not found in tables`);e.isNull?s.emitUint8(m.OP_IS_NULL):s.emitUint8(m.OP_IS_NOT_NULL),s.emitUint8(f.cursor),s.emitUint8(f.colIdx),i.push(s.emitUint16(0));return}if(e.type==="in"){if(!e.values||e.values.length===0){e.notIn&&(s.emitUint8(m.OP_JUMP),i.push(s.emitUint16(0)));return}const f=t*2;if(e.expr){let g=50;const d=()=>{if(g>=64)throw new st(g);return g++};Z(e.expr,n,s,0,f,d,r,void 0,c)}else{if(!e.colName)throw new Error("Filter IN leaf node missing colName");const g=ht(e.colName,c);if(g)bt(s,g.cursor,g.colIdx,f,g.col.type);else try{const d=ft(e.colName);let I=50;Z(d,n,s,0,f,()=>{if(I>=64)throw new st(I);return I++},r,void 0,c)}catch{throw new Error(`Column "${e.colName}" not found in tables`)}}const h=(a==null?void 0:a.get(e))??0;if(!e.notIn)s.emitUint8(m.OP_IN),s.emitUint8(f),s.emitUint16(h),i.push(s.emitUint16(0));else{let g=-1;if(e.colName){const p=ht(e.colName,c);p&&(s.emitUint8(m.OP_IS_NULL),s.emitUint8(p.cursor),s.emitUint8(p.colIdx),g=s.emitUint16(0))}s.emitUint8(m.OP_IN),s.emitUint8(f),s.emitUint16(h);const d=s.emitUint16(0);s.emitUint8(m.OP_JUMP),i.push(s.emitUint16(0));const I=s.currentOffset();g!==-1&&s.patchUint16(g,I),s.patchUint16(d,I)}return}const l=t*2,u=t*2+1;if(e.expr){let f=50;const h=()=>{if(f>=64)throw new st(f);return f++};Z(e.expr,n,s,0,l,h,r,void 0,c)}else{if(!e.colName)throw new Error("Filter leaf node missing colName");const f=ht(e.colName,c);if(f)bt(s,f.cursor,f.colIdx,l,f.col.type);else try{const h=ft(e.colName);let g=50;Z(h,n,s,0,l,()=>{if(g>=64)throw new st(g);return g++},r,void 0,c)}catch{throw new Error(`Column "${e.colName}" not found in tables`)}}const _=$n(e.op);s.emitUint8(_),s.emitUint8(l),s.emitUint8(u),i.push(s.emitUint16(0))}function Ji(e,t,n,s,i,r,o,a){const c=o??[n];if(e.type==="expr"){const h=t*2,g=t*2+1;let d=50;const I=()=>{if(d>=64)throw new st(d);return d++};Z(e.expr,n,s,0,h,I,r,void 0,c),s.emitUint8(m.OP_LOAD_INT),s.emitUint8(g),s.emitInt32(1),s.emitUint8(m.OP_EQ),s.emitUint8(h),s.emitUint8(g);const p=s.emitUint16(0);s.emitUint8(m.OP_JUMP),i.push(s.emitUint16(0)),s.patchUint16(p,s.currentOffset());return}if(e.type==="null"){if(e.expr){const g=t*2;let d=50;const I=()=>{if(d>=64)throw new st(d);return d++};Z(e.expr,n,s,0,g,I,r,void 0,c),e.isNull?s.emitUint8(m.OP_REG_IS_NOT_NULL):s.emitUint8(m.OP_REG_IS_NULL),s.emitUint8(g),i.push(s.emitUint16(0));return}if(!e.colName)throw new Error("Filter leaf node missing colName");const h=ht(e.colName,c);if(!h)throw new Error(`Column "${e.colName}" not found in tables`);e.isNull?s.emitUint8(m.OP_IS_NOT_NULL):s.emitUint8(m.OP_IS_NULL),s.emitUint8(h.cursor),s.emitUint8(h.colIdx),i.push(s.emitUint16(0));return}if(e.type==="in"){if(!e.values||e.values.length===0){e.notIn||(s.emitUint8(m.OP_JUMP),i.push(s.emitUint16(0)));return}const h=t*2;if(e.expr){let d=50;const I=()=>{if(d>=64)throw new st(d);return d++};Z(e.expr,n,s,0,h,I,r,void 0,c)}else{if(!e.colName)throw new Error("Filter IN leaf node missing colName");const d=ht(e.colName,c);if(d)bt(s,d.cursor,d.colIdx,h,d.col.type);else try{const I=ft(e.colName);let p=50;Z(I,n,s,0,h,()=>{if(p>=64)throw new st(p);return p++},r,void 0,c)}catch{throw new Error(`Column "${e.colName}" not found in tables`)}}const g=(a==null?void 0:a.get(e))??0;if(e.notIn){if(e.colName){const d=ht(e.colName,c);d&&(s.emitUint8(m.OP_IS_NULL),s.emitUint8(d.cursor),s.emitUint8(d.colIdx),i.push(s.emitUint16(0)))}s.emitUint8(m.OP_IN),s.emitUint8(h),s.emitUint16(g),i.push(s.emitUint16(0))}else{if(e.colName){const p=ht(e.colName,c);p&&(s.emitUint8(m.OP_IS_NULL),s.emitUint8(p.cursor),s.emitUint8(p.colIdx),i.push(s.emitUint16(0)))}s.emitUint8(m.OP_IN),s.emitUint8(h),s.emitUint16(g);const d=s.emitUint16(0);s.emitUint8(m.OP_JUMP),i.push(s.emitUint16(0));const I=s.currentOffset();s.patchUint16(d,I)}return}const l=t*2,u=t*2+1;if(e.expr){let h=50;const g=()=>{if(h>=64)throw new st(h);return h++};Z(e.expr,n,s,0,l,g,r,void 0,c)}else{if(!e.colName)throw new Error("Filter leaf node missing colName");const h=ht(e.colName,c);if(h)bt(s,h.cursor,h.colIdx,l,h.col.type);else try{const g=ft(e.colName);let d=50;Z(g,n,s,0,l,()=>{if(d>=64)throw new st(d);return d++},r,void 0,c)}catch{throw new Error(`Column "${e.colName}" not found in tables`)}}const _=$n(e.op);s.emitUint8(_),s.emitUint8(l),s.emitUint8(u);const f=s.emitUint16(0);s.emitUint8(m.OP_JUMP),i.push(s.emitUint16(0)),s.patchUint16(f,s.currentOffset())}function dc(e,t,n,s,i,r,o,a,c,l){o==="true"?Ji(e,t,n,s,r,a,c,l):o==="false"?Ki(e,t,n,s,i,a,c,l):(Ki(e,t,n,s,i,a,c,l),s.emitUint8(m.OP_JUMP),r.push(s.emitUint16(0)))}function xn(e,t,n,s,i,r,o,a,c,l){if(e.type==="cmp"||e.type==="null"||e.type==="expr"||e.type==="in"){const u=s.get(e)??0;dc(e,u,n,t,i,r,o,a,c,l);return}if(e.type==="not"){if(!e.child)return;const u=e.child,_=s.get(u)??0;o==="true"?Ki(u,_,n,t,r,a,c,l):o==="false"?Ji(u,_,n,t,i,a,c,l):(Ji(u,_,n,t,i,a,c,l),t.emitUint8(m.OP_JUMP),r.push(t.emitUint16(0)));return}if(e.type==="and"){const u=e.children??[];if(u.length===0){o==="false"&&(t.emitUint8(m.OP_JUMP),i.push(t.emitUint16(0)));return}for(let _=0;_<u.length;_++){const f=u[_];if(_===u.length-1)xn(f,t,n,s,i,r,o,a,c,l);else{const g=[];xn(f,t,n,s,g,r,"true",a,c,l);const d=t.currentOffset();for(const I of g)t.patchUint16(I,d)}}return}if(e.type==="or"){const u=e.children??[];if(u.length===0){o==="true"&&(t.emitUint8(m.OP_JUMP),r.push(t.emitUint16(0)));return}for(let _=0;_<u.length;_++){const f=u[_];if(_===u.length-1)xn(f,t,n,s,i,r,o,a,c,l);else{const g=[];xn(f,t,n,s,i,g,"false",a,c,l);const d=t.currentOffset();for(const I of g)t.patchUint16(I,d)}}return}}function mc(e,t,n,s,i,r,o){if(e.type==="cmp"){let a;const c=s(e.colName,e.expr);if(c!==void 0)a=c;else if(e.expr)a=i(),Z(e.expr,t,n,-1,a,i,o,s);else if(e.colName){a=i();const h=ft(e.colName);Z(h,t,n,-1,a,i,o,s)}else a=i(),n.emitUint8(m.OP_LOAD_NULL),n.emitUint8(a);const l=i(),u=e.value;u==null?(n.emitUint8(m.OP_LOAD_NULL),n.emitUint8(l)):typeof u=="number"?Number.isInteger(u)?(n.emitUint8(m.OP_LOAD_INT),n.emitUint8(l),n.emitInt32(u)):(n.emitUint8(m.OP_LOAD_FLOAT),n.emitUint8(l),n.emitFloat64(u)):typeof u=="string"?(n.emitUint8(m.OP_LOAD_TEXT),n.emitUint8(l),n.emitString(u)):typeof u=="boolean"?(n.emitUint8(m.OP_LOAD_INT),n.emitUint8(l),n.emitInt32(u?1:0)):typeof u=="bigint"&&(n.emitUint8(m.OP_LOAD_INT),n.emitUint8(l),n.emitInt32(Number(u)));const _=$n(e.op);n.emitUint8(_),n.emitUint8(a),n.emitUint8(l);const f=n.emitUint16(0);n.emitUint8(m.OP_JUMP),r.push(n.emitUint16(0)),n.patchUint16(f,n.currentOffset());return}if(e.type==="null"){let a;const c=s(e.colName,e.expr);if(c!==void 0)a=c;else if(e.expr)a=i(),Z(e.expr,t,n,-1,a,i,o,s);else if(e.colName){a=i();const l=ft(e.colName);Z(l,t,n,-1,a,i,o,s)}else a=i(),n.emitUint8(m.OP_LOAD_NULL),n.emitUint8(a);e.isNull?(n.emitUint8(m.OP_REG_IS_NOT_NULL),n.emitUint8(a),r.push(n.emitUint16(0))):(n.emitUint8(m.OP_REG_IS_NULL),n.emitUint8(a),r.push(n.emitUint16(0)));return}if(e.type==="expr"&&e.expr){const a=i();Z(e.expr,t,n,-1,a,i,o,s);const c=i();n.emitUint8(m.OP_LOAD_INT),n.emitUint8(c),n.emitInt32(1),n.emitUint8(m.OP_EQ),n.emitUint8(a),n.emitUint8(c);const l=n.emitUint16(0);n.emitUint8(m.OP_JUMP),r.push(n.emitUint16(0)),n.patchUint16(l,n.currentOffset());return}}function Yo(e,t,n,s,i,r,o){if(e.type==="cmp"){let a;const c=s(e.colName,e.expr);if(c!==void 0)a=c;else if(e.expr)a=i(),Z(e.expr,t,n,-1,a,i,o,s);else if(e.colName){a=i();const f=ft(e.colName);Z(f,t,n,-1,a,i,o,s)}else a=i(),n.emitUint8(m.OP_LOAD_NULL),n.emitUint8(a);const l=i(),u=e.value;u==null?(n.emitUint8(m.OP_LOAD_NULL),n.emitUint8(l)):typeof u=="number"?Number.isInteger(u)?(n.emitUint8(m.OP_LOAD_INT),n.emitUint8(l),n.emitInt32(u)):(n.emitUint8(m.OP_LOAD_FLOAT),n.emitUint8(l),n.emitFloat64(u)):typeof u=="string"?(n.emitUint8(m.OP_LOAD_TEXT),n.emitUint8(l),n.emitString(u)):typeof u=="boolean"?(n.emitUint8(m.OP_LOAD_INT),n.emitUint8(l),n.emitInt32(u?1:0)):typeof u=="bigint"&&(n.emitUint8(m.OP_LOAD_INT),n.emitUint8(l),n.emitInt32(Number(u)));const _=$n(e.op);n.emitUint8(_),n.emitUint8(a),n.emitUint8(l),r.push(n.emitUint16(0));return}if(e.type==="null"){let a;const c=s(e.colName,e.expr);if(c!==void 0)a=c;else if(e.expr)a=i(),Z(e.expr,t,n,-1,a,i,o,s);else if(e.colName){a=i();const l=ft(e.colName);Z(l,t,n,-1,a,i,o,s)}else a=i(),n.emitUint8(m.OP_LOAD_NULL),n.emitUint8(a);e.isNull?(n.emitUint8(m.OP_REG_IS_NULL),n.emitUint8(a),r.push(n.emitUint16(0))):(n.emitUint8(m.OP_REG_IS_NOT_NULL),n.emitUint8(a),r.push(n.emitUint16(0)));return}if(e.type==="expr"&&e.expr){const a=i();Z(e.expr,t,n,-1,a,i,o,s);const c=i();n.emitUint8(m.OP_LOAD_INT),n.emitUint8(c),n.emitInt32(1),n.emitUint8(m.OP_EQ),n.emitUint8(a),n.emitUint8(c),r.push(n.emitUint16(0));return}}function Ec(e,t,n,s,i,r,o,a,c){a==="true"?mc(e,t,n,s,i,o,c):a==="false"?Yo(e,t,n,s,i,r,c):(Yo(e,t,n,s,i,r,c),n.emitUint8(m.OP_JUMP),o.push(n.emitUint16(0)))}function Pe(e,t,n,s,i,r,o,a,c){if(e.type==="cmp"||e.type==="null"||e.type==="expr"){Ec(e,n,t,s,i,r,o,a,c);return}if(e.type==="not"){if(!e.child)return;const l=e.child;a==="true"?Pe(l,t,n,s,i,o,r,"false",c):a==="false"?Pe(l,t,n,s,i,r,o,"true",c):Pe(l,t,n,s,i,o,r,"none",c);return}if(e.type==="and"){const l=e.children??[];if(l.length===0){a==="false"&&(t.emitUint8(m.OP_JUMP),r.push(t.emitUint16(0)));return}for(let u=0;u<l.length;u++){const _=l[u];if(u===l.length-1)Pe(_,t,n,s,i,r,o,a,c);else{const h=[];Pe(_,t,n,s,i,h,o,"true",c);const g=t.currentOffset();for(const d of h)t.patchUint16(d,g)}}return}if(e.type==="or"){const l=e.children??[];if(l.length===0){a==="true"&&(t.emitUint8(m.OP_JUMP),o.push(t.emitUint16(0)));return}for(let u=0;u<l.length;u++){const _=l[u];if(u===l.length-1)Pe(_,t,n,s,i,r,o,a,c);else{const h=[];Pe(_,t,n,s,i,r,h,"false",c);const g=t.currentOffset();for(const d of h)t.patchUint16(d,g)}}return}}function Ic(e,t,n,s,i,r,o){if(!e)return;const a=[];Pe(e,n,t,s,i,a,r,"true",o);const c=n.currentOffset();for(const l of a)n.patchUint16(l,c)}function te(e,t,n,s,i,r,o,a){if(!e)return;const c=[];xn(e,n,t,s,c,i,"true",r,o,a);const l=n.currentOffset();for(const u of c)n.patchUint16(u,l)}function Zo(e,t,n,s){if(e.type==="literal")return typeof e.value=="number"?Number.isInteger(e.value)?C.INT32:C.FLOAT64:(typeof e.value=="string",C.TEXT);if(e.type==="col"){const i=s??[t],r=ht(e.name,i);return r?r.col.type:C.TEXT}if(e.type==="binary")return C.FLOAT64;if(e.type==="fn"){const i=e.name.toLowerCase();if(n&&n.has(i)){const r=n.get(i);if(r.returnType!==void 0)return r.returnType}if(["upper","lower","substr","trim","concat"].includes(i))return C.TEXT;if(["length","count","starts_with","startswith","ends_with","endswith","like","contains"].includes(i))return C.INT32;if(["abs","round","floor","ceil","sum","avg","min","max"].includes(i)){if(e.args.length>0&&e.args[0].type==="col"){const r=ht(e.args[0].name,s??[t]);if(r&&r.col.type===C.INT32&&i!=="avg")return C.INT32}return C.FLOAT64}return C.TEXT}return C.TEXT}function Z(e,t,n,s,i,r,o,a,c){if(a){const l=e.type==="col"?e.name:void 0,u=a(l,e);if(u!==void 0){u!==i&&(n.emitUint8(m.OP_COPY),n.emitUint8(u),n.emitUint8(i));return}}if(e.type==="literal"){const l=e.value;l==null?(n.emitUint8(m.OP_LOAD_NULL),n.emitUint8(i)):typeof l=="number"?Number.isInteger(l)?(n.emitUint8(m.OP_LOAD_INT),n.emitUint8(i),n.emitInt32(l)):(n.emitUint8(m.OP_LOAD_FLOAT),n.emitUint8(i),n.emitFloat64(l)):typeof l=="string"?(n.emitUint8(m.OP_LOAD_TEXT),n.emitUint8(i),n.emitString(l)):typeof l=="boolean"&&(n.emitUint8(m.OP_LOAD_INT),n.emitUint8(i),n.emitInt32(l?1:0));return}if(e.type==="col"){if(s===-1)throw new Error(`Column "${e.name}" in HAVING clause must be an aggregate or grouping column`);const l=c??[t],u=ht(e.name,l);if(!u){if(e.name==="*"){n.emitUint8(m.OP_LOAD_NULL),n.emitUint8(i);return}throw new Error(`Column "${e.name}" does not exist in table "${t.name}"`)}bt(n,u.cursor,u.colIdx,i,u.col.type);return}if(e.type==="binary"){const l=r(),u=r();Z(e.left,t,n,s,l,r,o,a,c),Z(e.right,t,n,s,u,r,o,a,c);let _=m.OP_ADD;if(e.op==="+")_=m.OP_ADD;else if(e.op==="-")_=m.OP_SUB;else if(e.op==="*")_=m.OP_MUL;else if(e.op==="/")_=m.OP_DIV;else if(e.op==="%")_=m.OP_MOD;else if(e.op==="="||e.op==="!="||e.op==="<"||e.op==="<="||e.op===">"||e.op===">="){let f=m.OP_EQ;e.op==="="?f=m.OP_EQ:e.op==="!="?f=m.OP_NE:e.op==="<"?f=m.OP_LT:e.op==="<="?f=m.OP_LE:e.op===">"?f=m.OP_GT:e.op===">="&&(f=m.OP_GE),n.emitUint8(f),n.emitUint8(l),n.emitUint8(u);const h=n.emitUint16(0);n.emitUint8(m.OP_LOAD_INT),n.emitUint8(i),n.emitInt32(0),n.emitUint8(m.OP_JUMP);const g=n.emitUint16(0);n.patchUint16(h,n.currentOffset()),n.emitUint8(m.OP_LOAD_INT),n.emitUint8(i),n.emitInt32(1),n.patchUint16(g,n.currentOffset());return}n.emitUint8(_),n.emitUint8(l),n.emitUint8(u),n.emitUint8(i);return}if(e.type==="fn"){const l=e.name.toLowerCase(),u={upper:m.OP_STR_UPPER,lower:m.OP_STR_LOWER,length:m.OP_STR_LENGTH,trim:m.OP_STR_TRIM,abs:m.OP_MATH_ABS,round:m.OP_MATH_ROUND,floor:m.OP_MATH_FLOOR,ceil:m.OP_MATH_CEIL};if(u[l]){const f=r(),h=e.args[0]??{type:"literal",value:null};Z(h,t,n,s,f,r,o,a,c),n.emitUint8(u[l]),n.emitUint8(f),n.emitUint8(i);return}if(l==="substr"){const f=r(),h=r(),g=r();Z(e.args[0],t,n,s,f,r,o,a,c),Z(e.args[1]??{type:"literal",value:1},t,n,s,h,r,o,a,c),e.args[2]!==void 0?Z(e.args[2],t,n,s,g,r,o,a,c):(n.emitUint8(m.OP_LOAD_NULL),n.emitUint8(g)),n.emitUint8(m.OP_STR_SUBSTR),n.emitUint8(f),n.emitUint8(h),n.emitUint8(g),n.emitUint8(i);return}const _={starts_with:m.OP_STR_STARTS_WITH,startswith:m.OP_STR_STARTS_WITH,ends_with:m.OP_STR_ENDS_WITH,endswith:m.OP_STR_ENDS_WITH,like:m.OP_STR_LIKE,contains:m.OP_STR_CONTAINS};if(_[l]){const f=r(),h=r();Z(e.args[0]??{type:"literal",value:null},t,n,s,f,r,o,a,c),Z(e.args[1]??{type:"literal",value:""},t,n,s,h,r,o,a,c),n.emitUint8(_[l]),n.emitUint8(f),n.emitUint8(h);const g=n.emitUint16(0);n.emitUint8(m.OP_LOAD_INT),n.emitUint8(i),n.emitInt32(0),n.emitUint8(m.OP_JUMP);const d=n.emitUint16(0);n.patchUint16(g,n.currentOffset()),n.emitUint8(m.OP_LOAD_INT),n.emitUint8(i),n.emitInt32(1),n.patchUint16(d,n.currentOffset());return}if(l==="concat"||l==="coalesce"){const f=e.args.length,h=r();for(let d=1;d<f;d++)r();for(let d=0;d<f;d++)Z(e.args[d],t,n,s,h+d,r,o,a,c);const g=l==="concat"?m.OP_STR_CONCAT:m.OP_COALESCE;n.emitUint8(g),n.emitUint8(h),n.emitUint8(f),n.emitUint8(i);return}if(o&&o.has(l)){const f=o.get(l),h=e.args.length;let g=i;if(h>0){g=r();for(let d=1;d<h;d++)r();for(let d=0;d<h;d++)Z(e.args[d],t,n,s,g+d,r,o,a,c)}n.emitUint8(m.OP_CALL_UDF),n.emitUint16(f),n.emitUint8(g),n.emitUint8(h),n.emitUint8(i);return}throw new di(l)}}function zi(e,t,n,s){n==null?(e.emitUint8(m.OP_LOAD_NULL),e.emitUint8(t)):typeof n=="number"?s===C.FLOAT64||!Number.isInteger(n)?(e.emitUint8(m.OP_LOAD_FLOAT),e.emitUint8(t),e.emitFloat64(n)):(e.emitUint8(m.OP_LOAD_INT),e.emitUint8(t),e.emitInt32(Math.floor(n))):typeof n=="bigint"?(e.emitUint8(m.OP_LOAD_INT),e.emitUint8(t),e.emitInt32(Number(n))):typeof n=="string"?(e.emitUint8(m.OP_LOAD_TEXT),e.emitUint8(t),e.emitString(n)):typeof n=="boolean"&&(e.emitUint8(m.OP_LOAD_INT),e.emitUint8(t),e.emitInt32(n?1:0))}function vs(e){switch(e){case C.INT32:return-2147483648;case C.INT64:return-9223372036854775808n;case C.FLOAT64:return-1/0;case C.TEXT:case C.UUID:case C.ULID:return"";case C.BLOB:return new Uint8Array(0);default:return 0}}function tr(e,t,n,s){var a;if(!n||n.length===0)return!1;for(const c of n)if(c.direction==="desc")return!1;const i=e.columnIndices.map(c=>t.columns[c].name.toLowerCase());let r=0;if(s&&s.size>0)for(;r<i.length&&s.has(i[r]);)r++;let o=0;for(;r<i.length&&o<n.length;){const c=(a=n[o].colName)==null?void 0:a.toLowerCase();if(!c||c!==i[r])return!1;r++,o++}return o===n.length}function jo(e,t,n,s,i){if(!n||n.length===0)return!1;for(const r of n){if(r.direction==="desc")return!1;const o=r.colName;if(!o)return!1;if(s&&s.length>0){let a=ht(o,s);if(!a&&i){const c=i.find(l=>l.alias===o);c&&c.expr.type==="col"&&(a=ht(c.expr.name,s))}if(!a||a.tableIdx!==0)return!1}else{const a=o.includes(".")?o.slice(o.lastIndexOf(".")+1):o;if(!e.columns.some(l=>l.name.toLowerCase()===a.toLowerCase()))return!1}}return!0}function ks(e,t,n,s){if(!e.indexes||e.indexes.length===0)return null;const i=n??t,r=new Set;for(const a of t)a.type==="cmp"&&(a.op==="="||a.op===void 0)&&a.colName&&a.value!==void 0&&a.value!==null&&r.add(a.colName.toLowerCase());const o=a=>{if(s&&s.length>0){if(a.scanType==="point"&&a.index.flags&(It.PRIMARY|It.UNIQUE))a.satisfiesOrderBy=!0;else if(tr(a.index,e,s,r)){if(a.scanType==="multi_point"&&a.inValues){const c=s[0].direction==="desc"?-1:1;a.inValues.sort((l,u)=>typeof l=="number"&&typeof u=="number"?(l-u)*c:String(l).localeCompare(String(u))*c)}a.satisfiesOrderBy=!0}}return a};for(const a of e.indexes)if(a.flags&It.PRIMARY&&a.columnCount===1){const c=e.columns[a.columnIndices[0]];for(let l=0;l<t.length;l++){const u=t[l];if(u.type==="cmp"&&(u.op==="="||u.op===void 0)&&u.colName===c.name&&u.value!==void 0&&u.value!==null)return o({index:a,scanType:"point",seekFilter:u,filterIndex:i.indexOf(u),keyType:c.type});if(u.type==="in"&&!u.notIn&&u.colName===c.name&&Array.isArray(u.values)&&u.values.length>0){const _=Array.from(new Set(u.values.filter(f=>f!=null)));return o({index:a,scanType:"multi_point",seekFilter:u,filterIndex:i.indexOf(u),keyType:c.type,inValues:_})}}}for(const a of e.indexes)if(a.flags&It.UNIQUE&&a.columnCount===1){const c=e.columns[a.columnIndices[0]];for(let l=0;l<t.length;l++){const u=t[l];if(u.type==="cmp"&&(u.op==="="||u.op===void 0)&&u.colName===c.name&&u.value!==void 0&&u.value!==null)return o({index:a,scanType:"point",seekFilter:u,filterIndex:i.indexOf(u),keyType:c.type});if(u.type==="in"&&!u.notIn&&u.colName===c.name&&Array.isArray(u.values)&&u.values.length>0){const _=Array.from(new Set(u.values.filter(f=>f!=null)));return o({index:a,scanType:"multi_point",seekFilter:u,filterIndex:i.indexOf(u),keyType:c.type,inValues:_})}}}for(const a of e.indexes)if(a.columnCount>1){const c=[];let l=!0;for(let u=0;u<a.columnCount;u++){const _=e.columns[a.columnIndices[u]],f=t.find(h=>h.type==="cmp"&&(h.op==="="||h.op===void 0)&&h.colName===_.name&&h.value!==void 0&&h.value!==null);if(f)c.push(f);else{l=!1;break}}if(l){const u={};for(const f of c)u[f.colName]=f.value;const _=Cs(e.columns,a.columnIndices,a.columnCount,u);return o({index:a,scanType:"point",seekFilter:c[0],filterIndex:i.indexOf(c[0]),keyType:C.BLOB,compositeValue:_})}}for(const a of e.indexes)if(a.columnCount===1){const c=e.columns[a.columnIndices[0]];for(let l=0;l<t.length;l++){const u=t[l];if(u.type==="cmp"&&(u.op==="="||u.op===void 0)&&u.colName===c.name&&u.value!==void 0&&u.value!==null)return o({index:a,scanType:"range",seekFilter:u,filterIndex:i.indexOf(u),keyType:c.type})}}for(const a of e.indexes)if(a.columnCount===1){const c=e.columns[a.columnIndices[0]];for(let l=0;l<t.length;l++){const u=t[l];if(u.type==="cmp"&&(u.op===">="||u.op===">")&&u.colName===c.name&&u.value!==void 0&&u.value!==null)return o({index:a,scanType:"range",seekFilter:u,filterIndex:i.indexOf(u),keyType:c.type})}}if(s&&s.length>0){for(const a of e.indexes)if(tr(a,e,s,r))if(a.columnCount===1){const c=e.columns[a.columnIndices[0]];return{index:a,scanType:"range",seekFilter:void 0,filterIndex:-1,keyType:c.type,satisfiesOrderBy:!0}}else{const c={};for(let u=0;u<a.columnCount;u++){const _=e.columns[a.columnIndices[u]],f=t.find(h=>h.type==="cmp"&&(h.op==="="||h.op===void 0)&&h.colName===_.name&&h.value!==void 0&&h.value!==null);f?c[_.name]=f.value:c[_.name]=vs(_.type)}const l=Cs(e.columns,a.columnIndices,a.columnCount,c);return{index:a,scanType:"range",seekFilter:void 0,filterIndex:-1,keyType:C.BLOB,compositeValue:l,satisfiesOrderBy:!0}}}return null}function Gs(e,t,n,s,i){if(e.op!=="="||!t.indexes||t.indexes.length===0)return null;const r=ht(e.leftCol,s),o=ht(e.rightCol,s);if(!r||!o)return null;let a=null,c=null;if(r.tableIdx===n&&o.tableIdx<n?(a=r,c=o):o.tableIdx===n&&r.tableIdx<n&&(a=o,c=r),!a||!c)return null;let l=null,u=999;for(const f of t.indexes)if(f.columnCount===1&&f.columnIndices[0]===a.colIdx){const h=(f.flags&It.PRIMARY)!==0,g=(f.flags&It.UNIQUE)!==0,d=h?1:g?2:3;d<u&&(u=d,l=f)}if(!l)return null;const _=(l.flags&(It.PRIMARY|It.UNIQUE))!==0;return{index:l,isUnique:_,innerCol:a,outerCol:c,indexCursor:i}}function er(e,t){var Ws,Tn,Hs,zo,ta,ea,na,sa,ia;const n=[e.table,...((Ws=e.joinedTables)==null?void 0:Ws.map(D=>D.table))??[]],i=ji((t==null?void 0:t.planner)??e.planner).optimize(e),r=i.orderedTables??n,o=i.whereMetrics,a=i.metrics;if(i.isAlwaysFalse){const D=new Qs;D.emitUint8(m.OP_HALT);const G=D.toByteArray();return e.outputColumns&&(G.outputColumns=e.outputColumns),G.allTables=r,G.whereMetrics=o,G}const c=i.plan;c!==e&&Object.assign(e,c);const l=e.joinedTables!==void 0&&e.joinedTables.length>0,u=zt(e.filters),_=u?Xo(u):[],f=mn(u),h=Array.from({length:r.length},()=>[]),g=new Set;if(l&&a)for(let D=0;D<r.length;D++){const G=n.indexOf(r[D]);if(G!==-1){const H=a.singleTableFilters.get(G)??[];if(D===0||e.joinedTables&&((Tn=e.joinedTables[D-1])==null?void 0:Tn.type)==="inner"){h[D]=H;for(const V of H)g.add(V)}}}const d=[];for(const D of f)g.has(D)||d.push(D);const I=zt(d),p=l&&jo(r[0],e.joinedTables,e.orderBy,r,e.selectExprs),y=p?e.orderBy.map(D=>{const G=D.colName??"",H=G.includes(".")?G.slice(G.lastIndexOf(".")+1):G;return{...D,colName:H}}):void 0,T=l?ks(r[0],h[0],_,y):null,N=p&&!!(T!=null&&T.satisfiesOrderBy);let b=r.length,P=-1;T&&b<16&&(P=b++);const R=new Array(r.length).fill(null);if(l&&e.joinedTables)for(let D=1;D<r.length;D++){const G=e.joinedTables[D-1];if(b<16){const H=Gs(G,r[D],D,r,b);H&&(R[D]=H,b++)}}const w=b;if(w>16)throw new rs(w,16);for(const D of f)if(D.type==="in"&&!D.notIn&&(!D.values||D.values.length===0)){const G=new Qs;G.emitUint8(m.OP_HALT);const H=G.toByteArray();return e.outputColumns&&(H.outputColumns=e.outputColumns),H}const S=[],v=new Map;for(const D of _)if(D.type==="in"){const G=S.length;v.set(D,G);const H=new Set;if(D.values)for(const V of D.values)V!=null&&(H.add(V),typeof V=="bigint"?H.add(Number(V)):typeof V=="number"&&Number.isSafeInteger(V)&&H.add(BigInt(V)));S.push(H)}const L=new Map;for(let D=0;D<_.length;D++)L.set(_[D],D);if(_.length*2>=64)throw new st(_.length*2);if(e.orderBy&&e.orderBy.length>8)throw new Gr(e.orderBy.length);if(e.groupBy&&e.groupBy.length>8)throw new Mr(e.groupBy.length);const A=new Qs;if(e.limit!==void 0&&e.limit<=0)return A.emitUint8(m.OP_HALT),A.toByteArray();let B=_.length*2;const k=e.offset!==void 0&&e.offset>0,$=e.limit!==void 0&&e.limit>0,j=k?B++:-1,J=$?B++:-1;if(B>=64)throw new st(B);const M=e.table;for(let D=0;D<_.length;D++){const G=_[D];if(G.type==="cmp"){const H=D*2+1,V=G.value;if(V==null)A.emitUint8(m.OP_LOAD_NULL),A.emitUint8(H);else if(typeof V=="number"){const _t=G.colName?ht(G.colName,r):void 0;_t&&_t.col.type===C.FLOAT64?(A.emitUint8(m.OP_LOAD_FLOAT),A.emitUint8(H),A.emitFloat64(V)):Number.isInteger(V)?(A.emitUint8(m.OP_LOAD_INT),A.emitUint8(H),A.emitInt32(Math.floor(V))):(A.emitUint8(m.OP_LOAD_FLOAT),A.emitUint8(H),A.emitFloat64(V))}else typeof V=="bigint"?(A.emitUint8(m.OP_LOAD_INT),A.emitUint8(H),A.emitInt32(Number(V))):typeof V=="string"?(A.emitUint8(m.OP_LOAD_TEXT),A.emitUint8(H),A.emitString(V)):typeof V=="boolean"&&(A.emitUint8(m.OP_LOAD_INT),A.emitUint8(H),A.emitInt32(V?1:0))}}if(k&&(A.emitUint8(m.OP_LOAD_INT),A.emitUint8(j),A.emitInt32(e.offset)),$&&(A.emitUint8(m.OP_LOAD_INT),A.emitUint8(J),A.emitInt32(e.limit)),e.aggregates&&e.aggregates.length>0||e.groupBy&&e.groupBy.length>0){const D=((Hs=e.groupBy)==null?void 0:Hs.length)??0,G=e.aggregates??[],H=G.length,V=[];for(const Q of e.groupBy??[]){const q=typeof Q=="string"?Q:Q.colName??(Q.expr?Qt(Q.expr):"group_key"),X=(zo=e.selectExprs)==null?void 0:zo.find(At=>{if(At.alias===q)return!0;if(typeof Q=="object"&&Q.expr)return JSON.stringify(At.expr)===JSON.stringify(Q.expr);if(typeof Q=="string"&&Q.includes("("))try{const jt=ft(Q);return JSON.stringify(At.expr)===JSON.stringify(jt)}catch{return!1}return!1}),Y=(X==null?void 0:X.alias)??q,K=M.columns.find(At=>At.name===q||At.name===Y);K?V.push({...K,name:Y}):V.push({name:Y,type:C.TEXT,flags:tt.NONE,colOffset:0})}for(let Q=0;Q<G.length;Q++){const q=G[Q],X=q.alias??(q.colName?`${q.func}_${q.colName}`:q.func),Y=q.func==="count"?C.INT32:C.FLOAT64;V.push({name:X,type:Y,flags:tt.NONE,colOffset:0})}const z=B,et=z+D,rt=et+4,dt=rt+4,nt=dt+D,Ot=nt+H;if(Ot>=64)throw new st(Ot);A.emitUint8(m.OP_AGG_INIT),A.emitUint8(0),A.emitUint8(z),A.emitUint8(D),A.emitUint8(0),A.emitUint8(m.OP_OPEN_CURSOR),A.emitUint8(0),A.emitUint32(M.rootPageId),A.emitUint8(m.OP_REWIND),A.emitUint8(0);const Dt=A.emitUint16(0),at=A.currentOffset(),Nt=[];if(te(u,M,A,L,Nt,e.udfNameMap,void 0,v),e.groupBy)for(let Q=0;Q<e.groupBy.length;Q++){const q=e.groupBy[Q],X=z+Q;let Y=Math.max(Ot+4,40);const K=()=>{if(Y>=64)throw new st(Y);return Y++};if(typeof q=="object"&&q.expr)Z(q.expr,M,A,0,X,K,e.udfNameMap);else{const At=typeof q=="string"?q:q.colName,jt=(ea=(ta=e.selectExprs)==null?void 0:ta.find(pt=>pt.alias===At))==null?void 0:ea.expr;if(jt)Z(jt,M,A,0,X,K,e.udfNameMap);else{const pt=M.columns.findIndex(Rt=>Rt.name===At);if(pt!==-1){const Rt=M.columns[pt];bt(A,0,pt,X,Rt.type)}else try{const Rt=ft(At);Z(Rt,M,A,0,X,K,e.udfNameMap)}catch{throw new Error(`Grouping column "${At}" not found in table "${M.name}"`)}}}}H===0&&D>0&&(A.emitUint8(m.OP_AGG_STEP),A.emitUint8(0),A.emitUint8(z),A.emitUint8(D),A.emitUint8(255),A.emitUint8(0));const Yt=G.some(Q=>Q.func==="count"),Mt=G.some(Q=>Q.func==="avg"),be=G.some(Q=>Q.func==="sum"),ae=G.some(Q=>Q.func==="min"),Bt=G.some(Q=>Q.func==="max");if(Yt||Mt||be){const Q=G.find(X=>X.func==="count");let q=255;if(Q&&Q.colName&&Q.colName!=="*"){const X=M.columns.findIndex(Y=>Y.name===Q.colName);if(X!==-1){const Y=M.columns[X];q=et,bt(A,0,X,q,Y.type)}}A.emitUint8(m.OP_AGG_STEP),A.emitUint8(0),A.emitUint8(z),A.emitUint8(D),A.emitUint8(q),A.emitUint8(0)}if(be||Mt){const Q=G.find(X=>X.func==="sum"||X.func==="avg");let q=255;if(Q&&Q.colName&&Q.colName!=="*"){const X=M.columns.findIndex(Y=>Y.name===Q.colName);if(X!==-1){const Y=M.columns[X];q=et+1,bt(A,0,X,q,Y.type)}}A.emitUint8(m.OP_AGG_STEP),A.emitUint8(0),A.emitUint8(z),A.emitUint8(D),A.emitUint8(q),A.emitUint8(1)}if(ae){const Q=G.find(X=>X.func==="min");let q=255;if(Q&&Q.colName&&Q.colName!=="*"){const X=M.columns.findIndex(Y=>Y.name===Q.colName);if(X!==-1){const Y=M.columns[X];q=et+2,bt(A,0,X,q,Y.type)}}A.emitUint8(m.OP_AGG_STEP),A.emitUint8(0),A.emitUint8(z),A.emitUint8(D),A.emitUint8(q),A.emitUint8(3)}if(Bt){const Q=G.find(X=>X.func==="max");let q=255;if(Q&&Q.colName&&Q.colName!=="*"){const X=M.columns.findIndex(Y=>Y.name===Q.colName);if(X!==-1){const Y=M.columns[X];q=et+3,bt(A,0,X,q,Y.type)}}A.emitUint8(m.OP_AGG_STEP),A.emitUint8(0),A.emitUint8(z),A.emitUint8(D),A.emitUint8(q),A.emitUint8(4)}const me=A.currentOffset();for(const Q of Nt)A.patchUint16(Q,me);A.emitUint8(m.OP_NEXT_ROW),A.emitUint8(0);const F=A.emitUint16(0);A.emitUint8(m.OP_JUMP),A.emitUint16(at);const mt=A.currentOffset();A.patchUint16(Dt,mt),A.patchUint16(F,mt);const lt=A.currentOffset();A.emitUint8(m.OP_AGG_NEXT),A.emitUint8(0),A.emitUint8(dt),A.emitUint8(rt);const kt=A.emitUint16(0),St=A.currentOffset();A.emitUint8(m.OP_HALT);const Zt=A.currentOffset();A.patchUint16(kt,Zt);for(let Q=0;Q<G.length;Q++){const q=G[Q],X=nt+Q;let Y=rt,K=0;q.func==="count"?(Y=rt,K=0):q.func==="sum"?(Y=rt,K=1):q.func==="avg"?(Y=rt,K=2):q.func==="min"?(Y=rt+2,K=3):q.func==="max"&&(Y=rt+3,K=4),A.emitUint8(m.OP_AGG_FINAL),A.emitUint8(Y),A.emitUint8(rt+1),A.emitUint8(X),A.emitUint8(K)}const Cn=(Q,q)=>{var X;for(let Y=0;Y<G.length;Y++){const K=G[Y],At=nt+Y;if(Q&&(K.alias&&K.alias===Q||(K.colName?`${K.func}_${K.colName}`:K.func)===Q||`${K.func}(${K.colName??"*"})`===Q.replace(/\s+/g,"")||K.func===Q))return At;if(q&&q.type==="fn"){const jt=q.name.toLowerCase();if(K.func===jt)if(jt==="count"){const pt=q.args[0],Rt=pt&&pt.type==="col"?pt.name:void 0;if(K.colName===void 0||K.colName==="*"||K.colName===Rt)return At}else{const pt=q.args[0],Rt=pt&&pt.type==="col"?pt.name:void 0;if(K.colName===Rt)return At}}}if(e.groupBy)for(let Y=0;Y<e.groupBy.length;Y++){const K=e.groupBy[Y],At=dt+Y,jt=typeof K=="string"?K:K.colName,pt=typeof K=="object"?K.expr:void 0;if(Q){if(jt===Q||pt&&Qt(pt)===Q)return At;const Rt=(X=e.selectExprs)==null?void 0:X.find(ir=>ir.alias===Q);if(Rt){if(jt===Rt.alias||pt&&JSON.stringify(pt)===JSON.stringify(Rt.expr))return At;if(typeof K=="string"&&K.includes("("))try{const ir=ft(K);if(JSON.stringify(ir)===JSON.stringify(Rt.expr))return At}catch{}}}if(q){if(pt&&JSON.stringify(pt)===JSON.stringify(q)||q.type==="col"&&jt===q.name)return At;if(typeof K=="string"&&K.includes("("))try{const Rt=ft(K);if(JSON.stringify(Rt)===JSON.stringify(q))return At}catch{}}}};if(e.having&&e.having.length>0){let Q=null;e.having.length===1?Q=e.having[0]:Q={type:"and",children:e.having};const q=[];let X=Math.max(Ot+4,40);Ic(Q,M,A,Cn,()=>{if(X>=64)throw new st(X);return X++},q,e.udfNameMap);for(const K of q)A.patchUint16(K,lt)}k&&(A.emitUint8(m.OP_OFFSET),A.emitUint8(j),A.emitUint16(lt)),A.emitUint8(m.OP_RESULT_ROW),A.emitUint8(dt),A.emitUint8(D+H),$&&(A.emitUint8(m.OP_LIMIT),A.emitUint8(J),A.emitUint16(St)),A.emitUint8(m.OP_JUMP),A.emitUint16(lt);const Le=A.toByteArray();return Le.outputColumns=V,Le.inSets=S,e.outputColumns=V,Le}const W=l?null:ks(M,f,_,e.orderBy);if(!l&&e.orderBy&&e.orderBy.length>0&&!(W!=null&&W.satisfiesOrderBy)){const D=e.orderBy.length,G=B,H=G+D;if(H>=64)throw new st(H);const V={numKeys:D,directions:e.orderBy.map(at=>at.direction==="desc"?1:0),nullOrders:e.orderBy.map(at=>at.nullOrder==="nulls_last"?1:at.nullOrder==="nulls_first"?0:at.direction==="desc"?1:0),limit:e.limit,offset:e.offset};e.keyInfos=[V],A.emitUint8(m.OP_SORTER_OPEN),A.emitUint8(0),A.emitUint8(0),A.emitUint8(m.OP_OPEN_CURSOR),A.emitUint8(0),A.emitUint32(M.rootPageId),A.emitUint8(m.OP_REWIND),A.emitUint8(0);const _t=A.emitUint16(0),z=A.currentOffset(),et=[];te(u,M,A,L,et,e.udfNameMap,void 0,v);for(let at=0;at<D;at++){const Nt=e.orderBy[at],Yt=G+at;let Mt=50;const be=()=>{if(Mt>=64)throw new st(Mt);return Mt++};if(Nt.expr)Z(Nt.expr,M,A,0,Yt,be,e.udfNameMap);else if(Nt.colName){const ae=Nt.colName,Bt=(sa=(na=e.selectExprs)==null?void 0:na.find(me=>me.alias===ae))==null?void 0:sa.expr;if(Bt)Z(Bt,M,A,0,Yt,be,e.udfNameMap);else{const me=M.columns.findIndex(F=>F.name===ae);if(me!==-1){const F=M.columns[me];bt(A,0,me,Yt,F.type)}else try{const F=ft(ae);Z(F,M,A,0,Yt,be,e.udfNameMap)}catch{throw new Error(`Order by column "${ae}" not found in table "${M.name}"`)}}}}A.emitUint8(m.OP_SORTER_INSERT),A.emitUint8(0),A.emitUint8(G),A.emitUint8(D),A.emitUint8(0);const rt=A.currentOffset();for(const at of et)A.patchUint16(at,rt);A.emitUint8(m.OP_NEXT_ROW),A.emitUint8(0);const dt=A.emitUint16(0);A.emitUint8(m.OP_JUMP),A.emitUint16(z);const nt=A.currentOffset();A.patchUint16(_t,nt),A.patchUint16(dt,nt),A.emitUint8(m.OP_SORTER_SORT),A.emitUint8(0);const Ot=A.currentOffset();A.emitUint8(m.OP_SORTER_NEXT),A.emitUint8(0),A.emitUint16(Ot),A.emitUint8(m.OP_HALT);const Dt=A.toByteArray();return Dt.keyInfos=e.keyInfos,Dt.inSets=S,a&&(Dt.planMetrics=a,Dt.estimatedCost=a.totalCost,Dt.estimatedRows=a.estimatedRows,Dt.joinOrder=a.joinOrder),Dt}const ee=e.selectExprs!==void 0&&e.selectExprs.length>0&&!(e.selectExprs.length===1&&e.selectExprs[0].expr.type==="col"&&e.selectExprs[0].expr.name==="*");let Et=[];if(ee)Et=e.selectExprs;else if(l){const D=new Set,G=new Set;for(const H of r)for(const V of H.columns)D.has(V.name.toLowerCase())&&G.add(V.name.toLowerCase()),D.add(V.name.toLowerCase());for(const H of r)for(const V of H.columns){const _t=G.has(V.name.toLowerCase())?`${H.name}.${V.name}`:V.name;Et.push({expr:{type:"col",name:`${H.name}.${V.name}`},alias:_t})}}let gt=-1;if(ee||l){const D=Et.map(G=>({name:G.alias,type:Zo(G.expr,M,e.udfDefs,r),flags:tt.NONE,colOffset:0}));if(e.outputColumns=D,gt=B,B+=Et.length,B>=64)throw new st(B)}if(l){const D=r.length,G=new Array(D);for(let F=1;F<D;F++)e.joinedTables[F-1].type==="left"&&(G[F]=B++);const H=B++,V=B++,_t=B++;let z=-1;if(T&&P!==-1)if(T.compositeValue){if(z=B++,B>=64)throw new st(B);A.emitUint8(m.OP_LOAD_BLOB),A.emitUint8(z),A.emitUint32(T.compositeValue.length),A.emitBytes(T.compositeValue)}else if(T.scanType==="multi_point"){if(z=B++,B>=64)throw new st(B)}else if(T.filterIndex>=0)z=T.filterIndex*2+1;else{if(z=B++,B>=64)throw new st(B);const F=vs(T.keyType);zi(A,z,F,T.keyType)}if(B>=64)throw new st(B);for(let F=0;F<D;F++)A.emitUint8(m.OP_OPEN_CURSOR),A.emitUint8(F),A.emitUint32(r[F].rootPageId);T&&P!==-1&&(A.emitUint8(m.OP_OPEN_INDEX),A.emitUint8(P),A.emitUint32(T.index.rootPageId));for(let F=1;F<D;F++){const mt=R[F];mt&&(A.emitUint8(m.OP_OPEN_INDEX),A.emitUint8(mt.indexCursor),A.emitUint32(mt.index.rootPageId))}const et=new Array(D),rt=new Array(D),dt=Array.from({length:D},()=>[]),nt=new Array(D),Ot=[];if(T&&P!==-1?T.scanType==="point"?(A.emitUint8(m.OP_INDEX_SEEK_EQ),A.emitUint8(P),A.emitUint8(0),A.emitUint8(z),A.emitUint8(T.keyType),et[0]=A.emitUint16(0)):(A.emitUint8(m.OP_INDEX_SEEK_GE),A.emitUint8(P),A.emitUint8(0),A.emitUint8(z),A.emitUint8(T.keyType),et[0]=A.emitUint16(0)):(A.emitUint8(m.OP_REWIND),A.emitUint8(0),et[0]=A.emitUint16(0)),rt[0]=A.currentOffset(),h[0]&&h[0].length>0){const F=zt(h[0]);te(F,r[0],A,L,dt[0],e.udfNameMap,r,v)}for(let F=1;F<D;F++){const mt=e.joinedTables[F-1],lt=R[F];if(mt.type==="left"&&(A.emitUint8(m.OP_LOAD_INT),A.emitUint8(G[F]),A.emitInt32(0)),lt&&lt.isUnique){if(bt(A,lt.outerCol.cursor,lt.outerCol.colIdx,H,lt.outerCol.col.type),A.emitUint8(m.OP_INDEX_SEEK_EQ),A.emitUint8(lt.indexCursor),A.emitUint8(F),A.emitUint8(H),A.emitUint8(lt.outerCol.col.type),et[F]=A.emitUint16(0),rt[F]=A.currentOffset(),mt.type==="inner"&&h[F]&&h[F].length>0){const kt=zt(h[F]);te(kt,r[F],A,L,dt[F],e.udfNameMap,r,v)}mt.type==="left"&&(A.emitUint8(m.OP_LOAD_INT),A.emitUint8(G[F]),A.emitInt32(1))}else if(lt&&!lt.isUnique){bt(A,lt.outerCol.cursor,lt.outerCol.colIdx,H,lt.outerCol.col.type),A.emitUint8(m.OP_INDEX_SEEK_GE),A.emitUint8(lt.indexCursor),A.emitUint8(F),A.emitUint8(H),A.emitUint8(lt.outerCol.col.type),et[F]=A.emitUint16(0),rt[F]=A.currentOffset(),bt(A,F,lt.innerCol.colIdx,V,lt.innerCol.col.type),A.emitUint8(m.OP_EQ),A.emitUint8(H),A.emitUint8(V);const kt=A.emitUint16(0);if(A.emitUint8(m.OP_JUMP),dt[F].push(A.emitUint16(0)),A.patchUint16(kt,A.currentOffset()),mt.type==="inner"&&h[F]&&h[F].length>0){const St=zt(h[F]);te(St,r[F],A,L,dt[F],e.udfNameMap,r,v)}mt.type==="left"&&(A.emitUint8(m.OP_LOAD_INT),A.emitUint8(G[F]),A.emitInt32(1))}else{A.emitUint8(m.OP_REWIND),A.emitUint8(F),et[F]=A.emitUint16(0),rt[F]=A.currentOffset();const kt=ht(mt.leftCol,r);if(!kt)throw new Error(`Join column "${mt.leftCol}" not found in tables`);const St=ht(mt.rightCol,r);if(!St)throw new Error(`Join column "${mt.rightCol}" not found in tables`);bt(A,kt.cursor,kt.colIdx,H,kt.col.type),bt(A,St.cursor,St.colIdx,V,St.col.type);let Zt;switch(mt.op){case"=":Zt=m.OP_EQ;break;case"!=":Zt=m.OP_NE;break;case">":Zt=m.OP_GT;break;case">=":Zt=m.OP_GE;break;case"<":Zt=m.OP_LT;break;case"<=":Zt=m.OP_LE;break;default:Zt=m.OP_EQ}A.emitUint8(Zt),A.emitUint8(H),A.emitUint8(V);const Cn=A.emitUint16(0);if(A.emitUint8(m.OP_JUMP),dt[F].push(A.emitUint16(0)),A.patchUint16(Cn,A.currentOffset()),mt.type==="inner"&&h[F]&&h[F].length>0){const Le=zt(h[F]);te(Le,r[F],A,L,dt[F],e.udfNameMap,r,v)}mt.type==="left"&&(A.emitUint8(m.OP_LOAD_INT),A.emitUint8(G[F]),A.emitInt32(1))}}te(I,M,A,L,dt[D-1],e.udfNameMap,r,v);const at=!(e.orderBy!==void 0&&e.orderBy.length>0)||N;let Nt=-1;k&&at&&(A.emitUint8(m.OP_OFFSET),A.emitUint8(j),Nt=A.emitUint16(0));let Yt=B;const Mt=()=>{if(Yt>=64)throw new st(Yt);return Yt++};for(let F=0;F<Et.length;F++)Z(Et[F].expr,M,A,0,gt+F,Mt,e.udfNameMap,void 0,r);A.emitUint8(m.OP_RESULT_ROW),A.emitUint8(gt),A.emitUint8(Et.length),$&&at&&(A.emitUint8(m.OP_LIMIT),A.emitUint8(J),Ot.push(A.emitUint16(0)));for(let F=D-1;F>=1;F--){const mt=A.currentOffset();F===D-1&&Nt!==-1&&A.patchUint16(Nt,mt);for(const St of dt[F])A.patchUint16(St,mt);const lt=R[F];if(lt&&lt.isUnique){const St=A.currentOffset();A.patchUint16(et[F],St)}else if(lt&&!lt.isUnique){A.emitUint8(m.OP_INDEX_NEXT),A.emitUint8(lt.indexCursor),A.emitUint8(F),nt[F]=A.emitUint16(0),A.emitUint8(m.OP_JUMP),A.emitUint16(rt[F]);const St=A.currentOffset();A.patchUint16(et[F],St),A.patchUint16(nt[F],St)}else{A.emitUint8(m.OP_NEXT_ROW),A.emitUint8(F),nt[F]=A.emitUint16(0),A.emitUint8(m.OP_JUMP),A.emitUint16(rt[F]);const St=A.currentOffset();A.patchUint16(et[F],St),A.patchUint16(nt[F],St)}if(e.joinedTables[F-1].type==="left"){A.emitUint8(m.OP_LOAD_INT),A.emitUint8(_t),A.emitInt32(0),A.emitUint8(m.OP_EQ),A.emitUint8(G[F]),A.emitUint8(_t);const St=A.emitUint16(0);A.emitUint8(m.OP_JUMP);const Zt=A.emitUint16(0);A.patchUint16(St,A.currentOffset());for(let Q=0;Q<Et.length;Q++){const q=Et[Q];let X=-1;if(q.expr.type==="col"){const Y=ht(q.expr.name,r);Y&&(X=Y.tableIdx)}X>=F?(A.emitUint8(m.OP_LOAD_NULL),A.emitUint8(gt+Q)):Z(q.expr,M,A,0,gt+Q,Mt,e.udfNameMap,void 0,r)}const Cn=[];k&&at&&(A.emitUint8(m.OP_OFFSET),A.emitUint8(j),Cn.push(A.emitUint16(0))),A.emitUint8(m.OP_RESULT_ROW),A.emitUint8(gt),A.emitUint8(Et.length),$&&at&&(A.emitUint8(m.OP_LIMIT),A.emitUint8(J),Ot.push(A.emitUint16(0)));const Le=A.currentOffset();A.patchUint16(Zt,Le);for(const Q of Cn)A.patchUint16(Q,Le)}}const be=A.currentOffset();for(const F of dt[0])A.patchUint16(F,be);T&&P!==-1?T.scanType==="point"?(A.emitUint8(m.OP_JUMP),nt[0]=A.emitUint16(0)):(A.emitUint8(m.OP_INDEX_NEXT),A.emitUint8(P),A.emitUint8(0),nt[0]=A.emitUint16(0),A.emitUint8(m.OP_JUMP),A.emitUint16(rt[0])):(A.emitUint8(m.OP_NEXT_ROW),A.emitUint8(0),nt[0]=A.emitUint16(0),A.emitUint8(m.OP_JUMP),A.emitUint16(rt[0]));const ae=A.currentOffset();A.patchUint16(et[0],ae),A.patchUint16(nt[0],ae);for(const F of Ot)A.patchUint16(F,ae);A.emitUint8(m.OP_HALT);const Bt=A.toByteArray();e.outputColumns&&(Bt.outputColumns=e.outputColumns);const me=(ia=e.joinedTables)==null?void 0:ia.map((F,mt)=>{const lt=mt+1,kt=R[lt];return{tableIndex:lt,tableName:F.table.name,scanType:kt?"IndexScan":"TableScan",indexName:kt?kt.index.name:void 0}});return Bt.joinedTableScans=me,Bt.allTables=r,Bt.inSets=S,Bt.table0Scan=T,Bt.isOrderSatisfied=N,N&&(e.isOrderSatisfied=!0),a&&(Bt.planMetrics=a,Bt.estimatedCost=a.totalCost,Bt.estimatedRows=a.estimatedRows,Bt.joinOrder=a.joinOrder),o&&(Bt.whereMetrics=o),Bt}if(W){let D;if(W.compositeValue){if(D=B++,D>=64)throw new st(D);A.emitUint8(m.OP_LOAD_BLOB),A.emitUint8(D),A.emitBytes(W.compositeValue)}else if(W.scanType==="multi_point"){if(D=B++,D>=64)throw new st(D)}else if(W.filterIndex>=0)D=W.filterIndex*2+1;else{if(D=B++,D>=64)throw new st(D);const G=vs(W.keyType);zi(A,D,G,W.keyType)}if(W.scanType==="point"){A.emitUint8(m.OP_OPEN_CURSOR),A.emitUint8(0),A.emitUint32(M.rootPageId),A.emitUint8(m.OP_OPEN_INDEX),A.emitUint8(1),A.emitUint32(W.index.rootPageId),A.emitUint8(m.OP_INDEX_SEEK_EQ),A.emitUint8(1),A.emitUint8(0),A.emitUint8(D),A.emitUint8(W.keyType);const G=A.emitUint16(0),H=[];te(u,M,A,L,H,e.udfNameMap,void 0,v);let V=-1;if(k&&(A.emitUint8(m.OP_OFFSET),A.emitUint8(j),V=A.emitUint16(0)),ee){let rt=B;const dt=()=>{if(rt>=64)throw new st(rt);return rt++};for(let nt=0;nt<e.selectExprs.length;nt++)Z(e.selectExprs[nt].expr,M,A,0,gt+nt,dt,e.udfNameMap);A.emitUint8(m.OP_RESULT_ROW),A.emitUint8(gt),A.emitUint8(e.selectExprs.length)}else A.emitUint8(m.OP_EMIT_ROW),A.emitUint8(0);A.emitUint8(m.OP_JUMP);const _t=A.emitUint16(0),z=A.currentOffset();A.patchUint16(G,z),A.patchUint16(_t,z),V!==-1&&A.patchUint16(V,z);for(const rt of H)A.patchUint16(rt,z);A.emitUint8(m.OP_HALT);const et=A.toByteArray();return et.indexScan=W,et.inSets=S,e.outputColumns&&(et.outputColumns=e.outputColumns),W!=null&&W.satisfiesOrderBy&&(et.isOrderSatisfied=!0,e.isOrderSatisfied=!0),a&&(et.planMetrics=a,et.estimatedCost=a.totalCost,et.estimatedRows=a.estimatedRows,et.joinOrder=a.joinOrder),et}else if(W.scanType==="multi_point"){const G=W.inValues?W.inValues.length:0;if(G===0){A.emitUint8(m.OP_HALT);const z=A.toByteArray();return z.indexScan=W,z.inSets=S,e.outputColumns&&(z.outputColumns=e.outputColumns),z}A.emitUint8(m.OP_OPEN_CURSOR),A.emitUint8(0),A.emitUint32(M.rootPageId),A.emitUint8(m.OP_OPEN_INDEX),A.emitUint8(1),A.emitUint32(W.index.rootPageId);const H=[];for(let z=0;z<G;z++){const et=W.inValues[z];zi(A,D,et,W.keyType),A.emitUint8(m.OP_INDEX_SEEK_EQ),A.emitUint8(1),A.emitUint8(0),A.emitUint8(D),A.emitUint8(W.keyType);const rt=A.emitUint16(0),dt=[];te(u,M,A,L,dt,e.udfNameMap,void 0,v);let nt=-1;if(k&&(A.emitUint8(m.OP_OFFSET),A.emitUint8(j),nt=A.emitUint16(0)),ee){let Nt=B;const Yt=()=>{if(Nt>=64)throw new st(Nt);return Nt++};for(let Mt=0;Mt<e.selectExprs.length;Mt++)Z(e.selectExprs[Mt].expr,M,A,0,gt+Mt,Yt,e.udfNameMap);A.emitUint8(m.OP_RESULT_ROW),A.emitUint8(gt),A.emitUint8(e.selectExprs.length)}else A.emitUint8(m.OP_EMIT_ROW),A.emitUint8(0);$&&(A.emitUint8(m.OP_LIMIT),A.emitUint8(J),H.push(A.emitUint16(0)));const Ot=z===G-1;let Dt=-1;Ot||(A.emitUint8(m.OP_JUMP),Dt=A.emitUint16(0));const at=A.currentOffset();A.patchUint16(rt,at);for(const Nt of dt)A.patchUint16(Nt,at);nt!==-1&&A.patchUint16(nt,at),Dt!==-1&&A.patchUint16(Dt,at)}const V=A.currentOffset();for(const z of H)A.patchUint16(z,V);A.emitUint8(m.OP_HALT);const _t=A.toByteArray();return _t.indexScan=W,_t.inSets=S,e.outputColumns&&(_t.outputColumns=e.outputColumns),W!=null&&W.satisfiesOrderBy&&(_t.isOrderSatisfied=!0,e.isOrderSatisfied=!0),a&&(_t.planMetrics=a,_t.estimatedCost=a.totalCost,_t.estimatedRows=a.estimatedRows,_t.joinOrder=a.joinOrder),_t}else{A.emitUint8(m.OP_OPEN_CURSOR),A.emitUint8(0),A.emitUint32(M.rootPageId),A.emitUint8(m.OP_OPEN_INDEX),A.emitUint8(1),A.emitUint32(W.index.rootPageId),A.emitUint8(m.OP_INDEX_SEEK_GE),A.emitUint8(1),A.emitUint8(0),A.emitUint8(D),A.emitUint8(W.keyType);const G=A.emitUint16(0),H=A.currentOffset(),V=[];te(u,M,A,L,V,e.udfNameMap,void 0,v);let _t=-1;if(k&&(A.emitUint8(m.OP_OFFSET),A.emitUint8(j),_t=A.emitUint16(0)),ee){let Ot=B;const Dt=()=>{if(Ot>=64)throw new st(Ot);return Ot++};for(let at=0;at<e.selectExprs.length;at++)Z(e.selectExprs[at].expr,M,A,0,gt+at,Dt,e.udfNameMap);A.emitUint8(m.OP_RESULT_ROW),A.emitUint8(gt),A.emitUint8(e.selectExprs.length)}else A.emitUint8(m.OP_EMIT_ROW),A.emitUint8(0);let z=-1;$&&(A.emitUint8(m.OP_LIMIT),A.emitUint8(J),z=A.emitUint16(0));const et=A.currentOffset();_t!==-1&&A.patchUint16(_t,et);for(const Ot of V)A.patchUint16(Ot,et);A.emitUint8(m.OP_INDEX_NEXT),A.emitUint8(1),A.emitUint8(0);const rt=A.emitUint16(0);A.emitUint8(m.OP_JUMP),A.emitUint16(H);const dt=A.currentOffset();A.patchUint16(G,dt),A.patchUint16(rt,dt),z!==-1&&A.patchUint16(z,dt),A.emitUint8(m.OP_HALT);const nt=A.toByteArray();return nt.indexScan=W,nt.inSets=S,e.outputColumns&&(nt.outputColumns=e.outputColumns),W!=null&&W.satisfiesOrderBy&&(nt.isOrderSatisfied=!0,e.isOrderSatisfied=!0),a&&(nt.planMetrics=a,nt.estimatedCost=a.totalCost,nt.estimatedRows=a.estimatedRows,nt.joinOrder=a.joinOrder),nt}}A.emitUint8(m.OP_OPEN_CURSOR),A.emitUint8(0),A.emitUint32(M.rootPageId),A.emitUint8(m.OP_REWIND),A.emitUint8(0);const En=A.emitUint16(0),In=A.currentOffset(),pn=[];te(u,M,A,L,pn,e.udfNameMap,void 0,v);let Ke=-1;if(k&&(A.emitUint8(m.OP_OFFSET),A.emitUint8(j),Ke=A.emitUint16(0)),ee){let D=B;const G=()=>{if(D>=64)throw new st(D);return D++};for(let H=0;H<e.selectExprs.length;H++)Z(e.selectExprs[H].expr,M,A,0,gt+H,G,e.udfNameMap);A.emitUint8(m.OP_RESULT_ROW),A.emitUint8(gt),A.emitUint8(e.selectExprs.length)}else A.emitUint8(m.OP_EMIT_ROW),A.emitUint8(0);let Ne=-1;$&&(A.emitUint8(m.OP_LIMIT),A.emitUint8(J),Ne=A.emitUint16(0));const Xn=A.currentOffset();Ke!==-1&&A.patchUint16(Ke,Xn);for(const D of pn)A.patchUint16(D,Xn);A.emitUint8(m.OP_NEXT_ROW),A.emitUint8(0);const Be=A.emitUint16(0);A.emitUint8(m.OP_JUMP),A.emitUint16(In);const yn=A.currentOffset();A.patchUint16(En,yn),A.patchUint16(Be,yn),Ne!==-1&&A.patchUint16(Ne,yn),A.emitUint8(m.OP_HALT);const oe=A.toByteArray();return oe.inSets=S,e.outputColumns&&(oe.outputColumns=e.outputColumns),o&&(oe.whereMetrics=o),a&&(oe.planMetrics=a,oe.estimatedCost=a.totalCost,oe.estimatedRows=a.estimatedRows,oe.joinOrder=a.joinOrder),oe}const pc=new TextDecoder;function Ko(e,t){const n=[],s=new DataView(e.buffer,e.byteOffset,e.byteLength);let i=0;const r=a=>{var c;return(c=t==null?void 0:t.columns[a])!=null&&c.name?`'${t.columns[a].name}'`:`col_${a}`},o=a=>`0x${a.toString(16).padStart(4,"0")}`;for(;i<e.byteLength;){const a=i,c=e[i++];switch(c){case m.OP_HALT:n.push({addr:a,opcode:"OP_HALT",p1:"",p2:"",p3:"",comment:"Halt VM execution (STATUS_DONE)"});break;case m.OP_OPEN_CURSOR:{const l=e[i++],u=s.getUint32(i,!0);i+=4,n.push({addr:a,opcode:"OP_OPEN_CURSOR",p1:`c[${l}]`,p2:`page=${u}`,p3:"",comment:`Open cursor ${l} on root page ${u}${t?` ('${t.name}')`:""}`});break}case m.OP_OPEN_INDEX:{const l=e[i++],u=s.getUint32(i,!0);i+=4,n.push({addr:a,opcode:"OP_OPEN_INDEX",p1:`c[${l}]`,p2:`page=${u}`,p3:"",comment:`Open index cursor ${l} on root page ${u}`});break}case m.OP_INDEX_SEEK_EQ:{const l=e[i++],u=e[i++],_=e[i++],f=e[i++],h=s.getUint16(i,!0);i+=2,n.push({addr:a,opcode:"OP_INDEX_SEEK_EQ",p1:`idx=c[${l}], data=c[${u}]`,p2:`key=r[${_}], type=${f}`,p3:o(h),comment:`Seek exact key in index; position data cursor or jump to ${o(h)} if not found`});break}case m.OP_INDEX_SEEK_GE:{const l=e[i++],u=e[i++],_=e[i++],f=e[i++],h=s.getUint16(i,!0);i+=2,n.push({addr:a,opcode:"OP_INDEX_SEEK_GE",p1:`idx=c[${l}], data=c[${u}]`,p2:`key=r[${_}], type=${f}`,p3:o(h),comment:`Seek first entry >= key in index; position data cursor or jump to ${o(h)} if EOF`});break}case m.OP_INDEX_NEXT:{const l=e[i++],u=e[i++],_=s.getUint16(i,!0);i+=2,n.push({addr:a,opcode:"OP_INDEX_NEXT",p1:`idx=c[${l}], data=c[${u}]`,p2:o(_),p3:"",comment:`Advance index cursor to next entry; jump to ${o(_)} if EOF`});break}case m.OP_REWIND:{const l=e[i++],u=s.getUint16(i,!0);i+=2,n.push({addr:a,opcode:"OP_REWIND",p1:`c[${l}]`,p2:o(u),p3:"",comment:`Rewind cursor to first row; jump to ${o(u)} if empty`});break}case m.OP_NEXT_ROW:{const l=e[i++],u=s.getUint16(i,!0);i+=2,n.push({addr:a,opcode:"OP_NEXT_ROW",p1:`c[${l}]`,p2:o(u),p3:"",comment:`Advance cursor to next row; jump to ${o(u)} if EOF`});break}case m.OP_LAST:{const l=e[i++],u=s.getUint16(i,!0);i+=2,n.push({addr:a,opcode:"OP_LAST",p1:`c[${l}]`,p2:o(u),p3:"",comment:`Position cursor to last row; jump to ${o(u)} if empty`});break}case m.OP_PREV_ROW:{const l=e[i++],u=s.getUint16(i,!0);i+=2,n.push({addr:a,opcode:"OP_PREV_ROW",p1:`c[${l}]`,p2:o(u),p3:"",comment:`Advance cursor to previous row; jump to ${o(u)} if BOF`});break}case m.OP_COLUMN_INT:{const l=e[i++],u=e[i++],_=e[i++];n.push({addr:a,opcode:"OP_COLUMN_INT",p1:`c[${l}]`,p2:`${u} (${r(u)})`,p3:`r[${_}]`,comment:`Read ${r(u)} as INT into r[${_}]`});break}case m.OP_COLUMN_FLOAT:{const l=e[i++],u=e[i++],_=e[i++];n.push({addr:a,opcode:"OP_COLUMN_FLOAT",p1:`c[${l}]`,p2:`${u} (${r(u)})`,p3:`r[${_}]`,comment:`Read ${r(u)} as FLOAT into r[${_}]`});break}case m.OP_COLUMN_TEXT:{const l=e[i++],u=e[i++],_=e[i++];n.push({addr:a,opcode:"OP_COLUMN_TEXT",p1:`c[${l}]`,p2:`${u} (${r(u)})`,p3:`r[${_}]`,comment:`Read ${r(u)} as TEXT into r[${_}]`});break}case m.OP_COLUMN_BLOB:{const l=e[i++],u=e[i++],_=e[i++];n.push({addr:a,opcode:"OP_COLUMN_BLOB",p1:`c[${l}]`,p2:`${u} (${r(u)})`,p3:`r[${_}]`,comment:`Read ${r(u)} as BLOB into r[${_}]`});break}case m.OP_COLUMN_UUID:{const l=e[i++],u=e[i++],_=e[i++];n.push({addr:a,opcode:"OP_COLUMN_UUID",p1:`c[${l}]`,p2:`${u} (${r(u)})`,p3:`r[${_}]`,comment:`Read ${r(u)} as UUID into r[${_}]`});break}case m.OP_COLUMN_ULID:{const l=e[i++],u=e[i++],_=e[i++];n.push({addr:a,opcode:"OP_COLUMN_ULID",p1:`c[${l}]`,p2:`${u} (${r(u)})`,p3:`r[${_}]`,comment:`Read ${r(u)} as ULID into r[${_}]`});break}case m.OP_IS_NULL:{const l=e[i++],u=e[i++],_=s.getUint16(i,!0);i+=2,n.push({addr:a,opcode:"OP_IS_NULL",p1:`c[${l}]`,p2:`${u} (${r(u)})`,p3:o(_),comment:`If ${r(u)} IS NULL -> jump to ${o(_)}`});break}case m.OP_IS_NOT_NULL:{const l=e[i++],u=e[i++],_=s.getUint16(i,!0);i+=2,n.push({addr:a,opcode:"OP_IS_NOT_NULL",p1:`c[${l}]`,p2:`${u} (${r(u)})`,p3:o(_),comment:`If ${r(u)} IS NOT NULL -> jump to ${o(_)}`});break}case m.OP_EQ:case m.OP_NE:case m.OP_GT:case m.OP_GE:case m.OP_LT:case m.OP_LE:{const l={[m.OP_EQ]:"OP_EQ",[m.OP_NE]:"OP_NE",[m.OP_GT]:"OP_GT",[m.OP_GE]:"OP_GE",[m.OP_LT]:"OP_LT",[m.OP_LE]:"OP_LE"},u={[m.OP_EQ]:"==",[m.OP_NE]:"!=",[m.OP_GT]:">",[m.OP_GE]:">=",[m.OP_LT]:"<",[m.OP_LE]:"<="},_=e[i++],f=e[i++],h=s.getUint16(i,!0);i+=2,n.push({addr:a,opcode:l[c],p1:`r[${_}]`,p2:`r[${f}]`,p3:o(h),comment:`If r[${_}] ${u[c]} r[${f}] -> jump to ${o(h)}`});break}case m.OP_JUMP:{const l=s.getUint16(i,!0);i+=2,n.push({addr:a,opcode:"OP_JUMP",p1:o(l),p2:"",p3:"",comment:`Unconditional jump to ${o(l)}`});break}case m.OP_STR_LIKE:case m.OP_STR_NOT_LIKE:case m.OP_STR_CONTAINS:case m.OP_STR_STARTS_WITH:case m.OP_STR_ENDS_WITH:{const l={[m.OP_STR_LIKE]:"OP_STR_LIKE",[m.OP_STR_NOT_LIKE]:"OP_STR_NOT_LIKE",[m.OP_STR_CONTAINS]:"OP_STR_CONTAINS",[m.OP_STR_STARTS_WITH]:"OP_STR_STARTS_WITH",[m.OP_STR_ENDS_WITH]:"OP_STR_ENDS_WITH"},u={[m.OP_STR_LIKE]:"LIKE",[m.OP_STR_NOT_LIKE]:"NOT LIKE",[m.OP_STR_CONTAINS]:"CONTAINS",[m.OP_STR_STARTS_WITH]:"STARTS_WITH",[m.OP_STR_ENDS_WITH]:"ENDS_WITH"},_=e[i++],f=e[i++],h=s.getUint16(i,!0);i+=2,n.push({addr:a,opcode:l[c],p1:`r[${_}]`,p2:`r[${f}]`,p3:o(h),comment:`If r[${_}] ${u[c]} r[${f}] -> jump to ${o(h)}`});break}case m.OP_IN:{const l=e[i++],u=s.getUint16(i,!0);i+=2;const _=s.getUint16(i,!0);i+=2,n.push({addr:a,opcode:"OP_IN",p1:`r[${l}]`,p2:`set[${u}]`,p3:o(_),comment:`If r[${l}] IN set[${u}] -> jump to ${o(_)}`});break}case m.OP_LOAD_INT:{const l=e[i++],u=s.getInt32(i,!0);i+=4,n.push({addr:a,opcode:"OP_LOAD_INT",p1:`r[${l}]`,p2:`${u}`,p3:"",comment:`Load literal int ${u} into r[${l}]`});break}case m.OP_LOAD_FLOAT:{const l=e[i++],u=s.getFloat64(i,!0);i+=8,n.push({addr:a,opcode:"OP_LOAD_FLOAT",p1:`r[${l}]`,p2:`${u}`,p3:"",comment:`Load literal float ${u} into r[${l}]`});break}case m.OP_LOAD_TEXT:{const l=e[i++],u=s.getUint16(i,!0);i+=2;const _=new Uint8Array(e.buffer,e.byteOffset+i,u),f=pc.decode(_);i+=u,n.push({addr:a,opcode:"OP_LOAD_TEXT",p1:`r[${l}]`,p2:`"${f}"`,p3:"",comment:`Load literal text "${f}" into r[${l}]`});break}case m.OP_LOAD_BLOB:{const l=e[i++],u=s.getUint16(i,!0);i+=2+u,n.push({addr:a,opcode:"OP_LOAD_BLOB",p1:`r[${l}]`,p2:`len=${u}`,p3:"",comment:`Load literal BLOB (${u} bytes) into r[${l}]`});break}case m.OP_LOAD_NULL:{const l=e[i++];n.push({addr:a,opcode:"OP_LOAD_NULL",p1:`r[${l}]`,p2:"NULL",p3:"",comment:`Set r[${l}] to NULL`});break}case m.OP_EMIT_ROW:{const l=e[i++];n.push({addr:a,opcode:"OP_EMIT_ROW",p1:`c[${l}]`,p2:"",p3:"",comment:"Row passed all filters -> emit to Output Result Buffer"});break}case m.OP_RESULT_ROW:{const l=e[i++],u=e[i++];n.push({addr:a,opcode:"OP_RESULT_ROW",p1:`r[${l}]`,p2:`cols=${u}`,p3:"",comment:`Serialize registers r[${l}..${l+u-1}] to Result Buffer`});break}case m.OP_OFFSET:{const l=e[i++],u=s.getUint16(i,!0);i+=2,n.push({addr:a,opcode:"OP_OFFSET",p1:`r[${l}]`,p2:o(u),p3:"",comment:`If r[${l}] > 0 -> decrement and skip row to ${o(u)}`});break}case m.OP_LIMIT:{const l=e[i++],u=s.getUint16(i,!0);i+=2,n.push({addr:a,opcode:"OP_LIMIT",p1:`r[${l}]`,p2:o(u),p3:"",comment:`If r[${l}] <= 1 -> halt to ${o(u)}, else decrement`});break}case m.OP_CALL_UDF:{const l=s.getUint16(i,!0);i+=2;const u=e[i++],_=e[i++],f=e[i++];n.push({addr:a,opcode:"OP_CALL_UDF",p1:`udf#${l}`,p2:`r[${u}..${u+_-1}]`,p3:`r[${f}]`,comment:`Call UDF #${l} with ${_} args -> r[${f}]`});break}case m.OP_STR_LOWER:case m.OP_STR_UPPER:case m.OP_STR_LENGTH:case m.OP_STR_TRIM:case m.OP_MATH_ABS:case m.OP_MATH_ROUND:case m.OP_MATH_FLOOR:case m.OP_MATH_CEIL:{const l={[m.OP_STR_LOWER]:"OP_STR_LOWER",[m.OP_STR_UPPER]:"OP_STR_UPPER",[m.OP_STR_LENGTH]:"OP_STR_LENGTH",[m.OP_STR_TRIM]:"OP_STR_TRIM",[m.OP_MATH_ABS]:"OP_MATH_ABS",[m.OP_MATH_ROUND]:"OP_MATH_ROUND",[m.OP_MATH_FLOOR]:"OP_MATH_FLOOR",[m.OP_MATH_CEIL]:"OP_MATH_CEIL"},u=e[i++],_=e[i++];n.push({addr:a,opcode:l[c],p1:`r[${u}]`,p2:`r[${_}]`,p3:"",comment:`${l[c]}: r[${_}] = ${l[c].toLowerCase()}(r[${u}])`});break}case m.OP_STR_SUBSTR:{const l=e[i++],u=e[i++],_=e[i++],f=e[i++];n.push({addr:a,opcode:"OP_STR_SUBSTR",p1:`r[${l}]`,p2:`start=r[${u}], len=r[${_}]`,p3:`r[${f}]`,comment:`Extract substring from r[${l}] into r[${f}]`});break}case m.OP_ADD:case m.OP_SUB:case m.OP_MUL:case m.OP_DIV:case m.OP_MOD:{const l={[m.OP_ADD]:"OP_ADD",[m.OP_SUB]:"OP_SUB",[m.OP_MUL]:"OP_MUL",[m.OP_DIV]:"OP_DIV",[m.OP_MOD]:"OP_MOD"},u=e[i++],_=e[i++],f=e[i++];n.push({addr:a,opcode:l[c],p1:`r[${u}]`,p2:`r[${_}]`,p3:`r[${f}]`,comment:`${l[c]}: r[${f}] = r[${u}] ${l[c].replace("OP_","")} r[${_}]`});break}case m.OP_STR_CONCAT:case m.OP_COALESCE:{const l={[m.OP_STR_CONCAT]:"OP_STR_CONCAT",[m.OP_COALESCE]:"OP_COALESCE"},u=e[i++],_=e[i++],f=e[i++];n.push({addr:a,opcode:l[c],p1:`r[${u}..${u+_-1}]`,p2:`count=${_}`,p3:`r[${f}]`,comment:`${l[c]}: r[${f}]`});break}case m.OP_COPY:{const l=e[i++],u=e[i++];n.push({addr:a,opcode:"OP_COPY",p1:`r[${l}]`,p2:`r[${u}]`,p3:"",comment:`Copy r[${l}] to r[${u}]`});break}case m.OP_SORTER_OPEN:{const l=e[i++],u=e[i++];n.push({addr:a,opcode:"OP_SORTER_OPEN",p1:`s[${l}]`,p2:`keyInfo=${u}`,p3:"",comment:`Open sorter ${l} with keyInfo ${u}`});break}case m.OP_SORTER_INSERT:{const l=e[i++],u=e[i++],_=e[i++],f=e[i++];n.push({addr:a,opcode:"OP_SORTER_INSERT",p1:`s[${l}]`,p2:`r[${u}..+${_}]`,p3:`c[${f}]`,comment:`Insert row from cursor ${f} into sorter ${l}`});break}case m.OP_SORTER_SORT:{const l=e[i++];n.push({addr:a,opcode:"OP_SORTER_SORT",p1:`s[${l}]`,p2:"",p3:"",comment:`Sort entries in sorter ${l}`});break}case m.OP_SORTER_NEXT:{const l=e[i++],u=s.getUint16(i,!0);i+=2,n.push({addr:a,opcode:"OP_SORTER_NEXT",p1:`s[${l}]`,p2:o(u),p3:"",comment:`Emit next sorted row from sorter ${l}; jump to ${o(u)} while more rows`});break}case m.OP_AGG_INIT:{const l=e[i++],u=e[i++],_=e[i++],f=e[i++];n.push({addr:a,opcode:"OP_AGG_INIT",p1:`agg[${l}]`,p2:`keys=r[${u}..+${_}]`,p3:`mode=${f===0?"hash":"stream"}`,comment:`Initialize aggregator ${l} (${f===0?"hash table":"stream"})`});break}case m.OP_AGG_STEP:{const l=e[i++],u=e[i++],_=e[i++],f=e[i++],h=e[i++],g=["COUNT","SUM","AVG","MIN","MAX"];n.push({addr:a,opcode:"OP_AGG_STEP",p1:`agg[${l}]`,p2:`val=${f===255?"*":`r[${f}]`}`,p3:g[h]??`${h}`,comment:`Update accumulator ${g[h]??h} for group r[${u}..+${_}]`});break}case m.OP_AGG_NEXT:{const l=e[i++],u=e[i++],_=e[i++],f=s.getUint16(i,!0);i+=2,n.push({addr:a,opcode:"OP_AGG_NEXT",p1:`agg[${l}]`,p2:`out_keys=r[${u}], out_acc=r[${_}]`,p3:o(f),comment:`Iterate next group bucket; jump to ${o(f)}`});break}case m.OP_AGG_FINAL:{const l=e[i++],u=e[i++],_=e[i++],f=e[i++],h=["COUNT","SUM","AVG","MIN","MAX"];n.push({addr:a,opcode:"OP_AGG_FINAL",p1:`sum=r[${l}], cnt=r[${u}]`,p2:`r[${_}]`,p3:h[f]??`${f}`,comment:`Finalize ${h[f]??f} into r[${_}]`});break}case m.OP_REG_IS_NULL:{const l=e[i++],u=s.getUint16(i,!0);i+=2,n.push({addr:a,opcode:"OP_REG_IS_NULL",p1:`r[${l}]`,p2:o(u),p3:"",comment:`Jump to ${o(u)} if r[${l}] is NULL`});break}case m.OP_REG_IS_NOT_NULL:{const l=e[i++],u=s.getUint16(i,!0);i+=2,n.push({addr:a,opcode:"OP_REG_IS_NOT_NULL",p1:`r[${l}]`,p2:o(u),p3:"",comment:`Jump to ${o(u)} if r[${l}] is NOT NULL`});break}default:n.push({addr:a,opcode:`OP_UNKNOWN(0x${c.toString(16)})`,p1:"",p2:"",p3:"",comment:"Unknown opcode"});break}}return n}function Jo(e){const t=(i,r)=>i.padEnd(r," "),n=i=>`0x${i.toString(16).padStart(4,"0")}`;let s=`${t("ADDR",8)} ${t("OPCODE",18)} ${t("P1",12)} ${t("P2",20)} ${t("P3",10)} COMMENT
1
+ (function(E,$t){typeof exports=="object"&&typeof module<"u"?$t(exports):typeof define=="function"&&define.amd?define(["exports"],$t):(E=typeof globalThis<"u"?globalThis:E||self,$t(E.WebDB={}))})(this,function(E){"use strict";var kc=Object.defineProperty;var Mc=(E,$t,Rn)=>$t in E?kc(E,$t,{enumerable:!0,configurable:!0,writable:!0,value:Rn}):E[$t]=Rn;var N=(E,$t,Rn)=>Mc(E,typeof $t!="symbol"?$t+"":$t,Rn);const pa=[["TYPE",1],["FLAGS",1],["CELL_COUNT",2],["CONTENT_OFFSET",2],["NEXT_PAGE_ID",4],["FREE_BYTES",2],["CHECKSUM",4]],te=16,Er=0,ya=1,Ta=2,Ca=4,Ir=6,wa=10,Me=12,Sa=[["CHILD_PAGE_ID",4],["ROWID",8]],pr=12,Ua=0,Oa=4,yr=291,Tr=145,ie=64,Pa=[["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]],ba=100,Ie=0,ei=6,ni=8,si=10,re=12,fe=16,pe=20,ye=24,Te=28,Ge=32,qe=36,Na=40,La=16,Ba=8,ee=16,ii=8,ns=100,ss=2148,Ra=3172,Fa=4,Da=3176,Qa=920,Ce=56,Ae=256,va=[["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]],we=128,ka=0,Ma=2,Ga=4,qa=8,Wa=12,Ha=76,Va=80,$a=84,xa=92,Xa=[["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]],Se=128,Ya=0,Za=2,ja=4,Ka=8,Ja=9,za=10,tl=26,el=34,nl=98,sl=[["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]],Fn=16,il=0,rl=1,ol=2,al=4,ll=6,cl=8,ul=12,fl=[["TYPE",1],["FLAGS",1],["COL_OFFSET",2],["NAME",64],["RESERVED",4]],ri=72,Al=0,hl=1,gl=2,dl=4,_l=68,ml=4194304,We=1024,El=1024,Ht=2048,Ue=8,Cr=16384,wr=12288,oi=65536,Sr=32768,Ur=4096,Or=61312,He=16777216,Il=[["SLOT_TO_PAGE",4096],["PAGE_TO_SLOT",16384],["DIRTY_MASK",128],["VM_CONTEXT",12288],["RESULT_BUFFER",65536],["BYTECODE",32768],["PAGE_SCRATCHPAD",4096],["ALIGNMENT_PADDING",61312]],is=4194304,Gt=4198400,Pr=4214784,br=4214912,Dn=4227200,Nr=4292736,Lr=4325504,pl=4329600,Br=4390912,yl=21168128;function ai(e,t=He){const n=e*4096,s=e*4+7&-8;let i=16;for(;i<e*2;)i<<=1;const r=i*8,o=Math.ceil(e/8)+7&-8;if(e===We)return{slotsEndOffset:n,slotToPageOffset:is,pageToSlotOffset:Gt,pageToSlotBuckets:Ht,dirtyMaskOffset:Pr,vmContextOffset:br,resultBufferOffset:Dn,bytecodeOffset:Nr,pageScratchpadOffset:Lr,transientArenaOffset:Br};const a=n,c=a+s,l=c+r,u=l+o,d=u+wr,h=d+oi,f=h+Sr,g=f+Ur+Or;return{slotsEndOffset:n,slotToPageOffset:a,pageToSlotOffset:c,pageToSlotBuckets:i,dirtyMaskOffset:l,vmContextOffset:u,resultBufferOffset:d,bytecodeOffset:h,pageScratchpadOffset:f,transientArenaOffset:g}}const Oe=4096,an=4128,Rr=1,Qn=1463897158,rs=1,os=2,as=3,Tl=[["MAGIC",6],["WAL_VERSION",2],["PAGE_SIZE",4],["CHECKPOINT_SEQ",4],["SALT1",4],["SALT2",4],["CHECKSUM",4],["RESERVED",4]],ls=32,li=0,ci=6,ui=8,fi=12,Ai=16,hi=20,gi=24,Fr=28,Cl=[["MAGIC",4],["FRAME_TYPE",2],["FLAGS",2],["TX_ID",4],["PAGE_ID",4],["DB_SIZE_PAGES",4],["FRAME_SEQ",4],["CHECKSUM",4],["RESERVED",4]],Ve=32,di=0,_i=4,mi=6,Ei=8,Ii=12,pi=16,yi=20,Ti=24,Dr=28,cs=1,Qr=1,$e=0,vr=2,Ci=5,us=10,vn=12,fs=13,wl=1280,Sl=8,Ul=64,Ol=16,Pl=7,bl=32,kr=1e4,Qt=1e4;function Mr(){return{pageId:0,rootPageId:0,slotIdx:0,cellIdx:0,rowOffset:0,btreeDepth:0,flags:0}}function Gr(){const e=Array.from({length:16},()=>Mr());return{pc:0,status:L.RUNNING,fault_page_id:0,resultCount:0,resultOffset:0,arenaOffset:0,maxQueryMemory:He,rowsAffected:0,registers:new Array(64).fill(null),cursor:e[0],cursors:e,keyInfos:[],sorters:[],aggregators:[],table:null,tables:void 0,outputColumns:void 0,inSets:[]}}function qr(e,t,n){e.pc=0,e.status=L.RUNNING,e.fault_page_id=0,e.resultCount=0,e.resultOffset=0,e.arenaOffset=0,e.maxQueryMemory=He,e.rowsAffected=0,e.registers.fill(null);for(let s=0;s<e.cursors.length;s++){const i=e.cursors[s];i.pageId=0,i.rootPageId=0,i.slotIdx=0,i.cellIdx=0,i.rowOffset=0,i.btreeDepth=0,i.flags=0}e.cursor=e.cursors[0],e.keyInfos=[],e.sorters=[],e.aggregators=[],e.table=t??null,e.tables=n,e.outputColumns=void 0,e.inSets=[]}var S=(e=>(e[e.NULL=0]="NULL",e[e.INT32=1]="INT32",e[e.INT64=2]="INT64",e[e.FLOAT64=3]="FLOAT64",e[e.TEXT=4]="TEXT",e[e.BLOB=5]="BLOB",e[e.UUID=6]="UUID",e[e.ULID=7]="ULID",e))(S||{}),tt=(e=>(e[e.NONE=0]="NONE",e[e.PRIMARY_KEY=1]="PRIMARY_KEY",e[e.NOT_NULL=2]="NOT_NULL",e[e.INDEXED=4]="INDEXED",e[e.AUTO_INC=8]="AUTO_INC",e))(tt||{}),xe=(e=>(e[e.NONE=0]="NONE",e[e.ACTIVE=1]="ACTIVE",e[e.SYSTEM=2]="SYSTEM",e))(xe||{}),rt=(e=>(e[e.NONE=0]="NONE",e[e.UNIQUE=1]="UNIQUE",e[e.PRIMARY=2]="PRIMARY",e[e.SPATIAL_VECTOR=4]="SPATIAL_VECTOR",e))(rt||{}),m=(e=>(e[e.OP_HALT=0]="OP_HALT",e[e.OP_OPEN_CURSOR=1]="OP_OPEN_CURSOR",e[e.OP_REWIND=2]="OP_REWIND",e[e.OP_NEXT_ROW=3]="OP_NEXT_ROW",e[e.OP_COLUMN_INT=4]="OP_COLUMN_INT",e[e.OP_COLUMN_FLOAT=5]="OP_COLUMN_FLOAT",e[e.OP_COLUMN_TEXT=6]="OP_COLUMN_TEXT",e[e.OP_COLUMN_BLOB=7]="OP_COLUMN_BLOB",e[e.OP_LAST=8]="OP_LAST",e[e.OP_PREV_ROW=9]="OP_PREV_ROW",e[e.OP_COLUMN_UUID=10]="OP_COLUMN_UUID",e[e.OP_COLUMN_ULID=11]="OP_COLUMN_ULID",e[e.OP_OPEN_INDEX=12]="OP_OPEN_INDEX",e[e.OP_INDEX_SEEK_EQ=13]="OP_INDEX_SEEK_EQ",e[e.OP_INDEX_SEEK_GE=14]="OP_INDEX_SEEK_GE",e[e.OP_INDEX_NEXT=15]="OP_INDEX_NEXT",e[e.OP_IS_NULL=16]="OP_IS_NULL",e[e.OP_IS_NOT_NULL=17]="OP_IS_NOT_NULL",e[e.OP_EQ=18]="OP_EQ",e[e.OP_NE=19]="OP_NE",e[e.OP_GT=20]="OP_GT",e[e.OP_GE=21]="OP_GE",e[e.OP_LT=22]="OP_LT",e[e.OP_LE=23]="OP_LE",e[e.OP_JUMP=24]="OP_JUMP",e[e.OP_STR_LIKE=25]="OP_STR_LIKE",e[e.OP_STR_NOT_LIKE=26]="OP_STR_NOT_LIKE",e[e.OP_STR_CONTAINS=27]="OP_STR_CONTAINS",e[e.OP_STR_STARTS_WITH=28]="OP_STR_STARTS_WITH",e[e.OP_STR_ENDS_WITH=29]="OP_STR_ENDS_WITH",e[e.OP_LOAD_BLOB=30]="OP_LOAD_BLOB",e[e.OP_IN=31]="OP_IN",e[e.OP_LOAD_INT=32]="OP_LOAD_INT",e[e.OP_LOAD_FLOAT=33]="OP_LOAD_FLOAT",e[e.OP_LOAD_TEXT=34]="OP_LOAD_TEXT",e[e.OP_LOAD_NULL=35]="OP_LOAD_NULL",e[e.OP_EMIT_ROW=36]="OP_EMIT_ROW",e[e.OP_RESULT_ROW=37]="OP_RESULT_ROW",e[e.OP_OFFSET=38]="OP_OFFSET",e[e.OP_LIMIT=39]="OP_LIMIT",e[e.OP_CALL_UDF=40]="OP_CALL_UDF",e[e.OP_STR_LOWER=41]="OP_STR_LOWER",e[e.OP_STR_UPPER=42]="OP_STR_UPPER",e[e.OP_STR_LENGTH=43]="OP_STR_LENGTH",e[e.OP_STR_SUBSTR=44]="OP_STR_SUBSTR",e[e.OP_STR_TRIM=45]="OP_STR_TRIM",e[e.OP_MATH_ABS=46]="OP_MATH_ABS",e[e.OP_MATH_ROUND=47]="OP_MATH_ROUND",e[e.OP_SORTER_OPEN=48]="OP_SORTER_OPEN",e[e.OP_SORTER_INSERT=49]="OP_SORTER_INSERT",e[e.OP_SORTER_SORT=50]="OP_SORTER_SORT",e[e.OP_SORTER_NEXT=51]="OP_SORTER_NEXT",e[e.OP_MATH_FLOOR=52]="OP_MATH_FLOOR",e[e.OP_MATH_CEIL=53]="OP_MATH_CEIL",e[e.OP_ADD=54]="OP_ADD",e[e.OP_SUB=55]="OP_SUB",e[e.OP_MUL=56]="OP_MUL",e[e.OP_DIV=57]="OP_DIV",e[e.OP_MOD=58]="OP_MOD",e[e.OP_ENTER_SUBQUERY=59]="OP_ENTER_SUBQUERY",e[e.OP_RETURN_SUBQUERY=60]="OP_RETURN_SUBQUERY",e[e.OP_STR_CONCAT=61]="OP_STR_CONCAT",e[e.OP_COALESCE=62]="OP_COALESCE",e[e.OP_COPY=63]="OP_COPY",e[e.OP_AGG_INIT=64]="OP_AGG_INIT",e[e.OP_AGG_STEP=65]="OP_AGG_STEP",e[e.OP_AGG_NEXT=66]="OP_AGG_NEXT",e[e.OP_AGG_FINAL=67]="OP_AGG_FINAL",e[e.OP_REG_IS_NULL=72]="OP_REG_IS_NULL",e[e.OP_REG_IS_NOT_NULL=73]="OP_REG_IS_NOT_NULL",e[e.OP_DELETE_ROW=80]="OP_DELETE_ROW",e[e.OP_UPDATE_FIELD=81]="OP_UPDATE_FIELD",e[e.OP_INSERT_ROW=82]="OP_INSERT_ROW",e))(m||{}),L=(e=>(e[e.RUNNING=0]="RUNNING",e[e.DONE=1]="DONE",e[e.PAGE_FAULT=2]="PAGE_FAULT",e[e.BUFFER_FULL=3]="BUFFER_FULL",e[e.ERROR=4]="ERROR",e[e.TIMEOUT=5]="TIMEOUT",e[e.ARENA_EXHAUSTED=6]="ARENA_EXHAUSTED",e[e.INVALID_BYTECODE=7]="INVALID_BYTECODE",e))(L||{});class Wr extends Error{constructor(t,n=2048){super(`Row size (${t} bytes) exceeds maximum limit of ${n} bytes`),this.name="RowSizeLimitExceededError"}}class As extends Error{constructor(t,n){super(`NOT NULL constraint failed: ${n?n+".":""}${t}`),this.name="NotNullConstraintError"}}class Hr extends Error{constructor(t,n=64){super(`Identifier "${t}" (${t.length} characters) exceeds maximum limit of ${n} characters`),this.name="IdentifierTooLongError"}}class hs extends Error{constructor(t,n){super(n?`Column "${t}" already exists on table "${n}"`:`Column "${t}" already exists`),this.name="ColumnAlreadyExistsError"}}class wi extends Error{constructor(t){super(t),this.name="CannotDropColumnError"}}class he extends Error{constructor(t,n){super(n?`Column "${t}" not found on table "${n}"`:`Column "${t}" not found`),this.name="ColumnNotFoundError"}}class kn extends Error{constructor(t){super(`Table not found: "${t}"`),this.name="TableNotFoundError"}}class gs extends Error{constructor(t){super(`Table already exists: "${t}"`),this.name="TableAlreadyExistsError"}}class Vr extends Error{constructor(t){super(`Index not found: "${t}"`),this.name="IndexNotFoundError"}}class Si extends Error{constructor(t){super(`Index already exists: "${t}"`),this.name="IndexAlreadyExistsError"}}class ln extends Error{constructor(t){super(t),this.name="UniqueConstraintViolationError"}}class Pe extends Error{constructor(t,n,s){super(`Corrupted page detected (pageId: ${t}): stored checksum ${n}${s!==void 0?`, computed checksum ${s}`:""}`),this.pageId=t,this.storedChecksum=n,this.computedChecksum=s,this.name="CorruptPageError"}}class Mn extends Error{constructor(t,n=256){super(`Too many columns: ${t} exceeds maximum limit of ${n} columns`),this.name="TooManyColumnsError"}}class Ui extends Error{constructor(t,n=16){super(`Too many tables: ${t} exceeds maximum limit of ${n} tables on Page 1`),this.name="TooManyTablesError"}}class $r extends Error{constructor(t,n=8){super(`Too many indexes: ${t} exceeds maximum limit of ${n} indexes on Page 1`),this.name="TooManyIndexesError"}}class xr extends Error{constructor(t){super(t),this.name="UnsupportedFormatVersionError"}}class Gn extends Error{constructor(t){super(t),this.name="InvalidDatabaseError"}}class Oi extends Error{constructor(t="Transient query arena exhausted"){super(t),this.name="QueryArenaExhaustedError"}}class ds extends Error{constructor(t,n=16){super(`Too many cursors: ${t} exceeds maximum limit of ${n} cursors`),this.name="TooManyCursorsError"}}class st extends Error{constructor(t,n=64){super(`Too many registers: ${t} exceeds maximum limit of ${n} registers`),this.name="TooManyRegistersError"}}class Xr extends Error{constructor(t,n=7){super(`Subquery nesting depth ${t} exceeds maximum limit of ${n}`),this.name="SubqueryNestingTooDeepError"}}class Yr extends Error{constructor(t="Query execution exceeded maximum cycle limit (TIMEOUT)"){super(t),this.name="QueryTimeoutError"}}class Zr extends Error{constructor(t="Malformed bytecode execution halted (INVALID_BYTECODE)"){super(t),this.name="InvalidBytecodeError"}}class jr extends Error{constructor(t,n=8){super(`Too many order by columns: ${t} exceeds maximum limit of ${n}`),this.name="TooManyOrderByColumnsError"}}class Kr extends Error{constructor(t,n=8){super(`Too many group by columns: ${t} exceeds maximum limit of ${n}`),this.name="TooManyGroupByColumnsError"}}class Pi extends Error{constructor(t){super(`Function "${t}" is neither a native built-in function nor a registered UDF`),this.name="UnknownFunctionError"}}class _s extends Error{constructor(t){super(`Aggregate function "${t}" cannot be used in WHERE clause`),this.name="AggregateNotAllowedInWhereError"}}class ms extends Error{constructor(t="Corrupted WAL file header detected"){super(t),this.name="CorruptWalHeaderError"}}class qn extends Error{constructor(t="Corrupted WAL frame detected"){super(t),this.name="CorruptWalFrameError"}}class Jr{constructor(){N(this,"name","memory");N(this,"isSynchronous",!0);N(this,"pages",new Map);N(this,"walHeader",null);N(this,"walFrames",[])}async readPages(t){return t.map(n=>{const s=this.pages.get(n);return s?new Uint8Array(s):null})}async writePages(t){for(const{pageId:n,data:s}of t){const i=new Uint8Array(s.byteLength);i.set(s),this.pages.set(n,i)}}async flush(){}async truncate(t){for(const n of Array.from(this.pages.keys()))n>t&&this.pages.delete(n)}snapshot(){const t=new Map;for(const[n,s]of this.pages.entries())t.set(n,new Uint8Array(s));return t}restoreSnapshot(t){this.pages.clear();for(const[n,s]of t.entries())this.pages.set(n,new Uint8Array(s))}async readWalHeader(){return this.walHeader?new Uint8Array(this.walHeader):null}async writeWalHeader(t){const n=new Uint8Array(t.byteLength);n.set(t),this.walHeader=n}async readWalFrames(t,n){const s=n!==void 0?t+n:this.walFrames.length;return this.walFrames.slice(t,s).map(r=>new Uint8Array(r))}async appendWalFrames(t){for(const n of t){const s=new Uint8Array(n.byteLength);s.set(n),this.walFrames.push(s)}}async flushWal(){}async truncateWal(t){t===0?(this.walFrames=[],this.walHeader=null):this.walFrames.length=Math.min(this.walFrames.length,t)}async getWalFrameCount(){return this.walFrames.length}async close(){}}class zr{constructor(t){N(this,"name","idb");N(this,"isSynchronous",!1);N(this,"dbName");N(this,"dbPromise",null);this.dbName=`webdb_${t}`}getDb(){return this.dbPromise||(this.dbPromise=new Promise((t,n)=>{const s=globalThis.indexedDB;if(!s){n(new Error("IndexedDB is not available in the current environment"));return}const i=s.open(this.dbName,1);i.onupgradeneeded=()=>{const r=i.result;r.objectStoreNames.contains("pages")||r.createObjectStore("pages"),r.objectStoreNames.contains("wal_frames")||r.createObjectStore("wal_frames"),r.objectStoreNames.contains("wal_meta")||r.createObjectStore("wal_meta")},i.onsuccess=()=>t(i.result),i.onerror=()=>n(i.error)})),this.dbPromise}async readPages(t){if(t.length===0)return[];const n=await this.getDb();return new Promise((s,i)=>{const r=n.transaction("pages","readonly"),o=r.objectStore("pages"),a=new Array(t.length).fill(null);for(let c=0;c<t.length;c++){const l=o.get(t[c]);l.onsuccess=()=>{const u=l.result;u&&(a[c]=u instanceof Uint8Array?u:new Uint8Array(u))}}r.oncomplete=()=>s(a),r.onerror=()=>i(r.error),r.onabort=()=>i(r.error)})}async writePages(t){if(t.length===0)return;const n=await this.getDb();return new Promise((s,i)=>{const r=n.transaction("pages","readwrite"),o=r.objectStore("pages");for(const{pageId:a,data:c}of t){const l=new Uint8Array(c.byteLength);l.set(c),o.put(l,a)}r.oncomplete=()=>s(),r.onerror=()=>i(r.error),r.onabort=()=>i(r.error)})}async flush(){}async truncate(t){const n=await this.getDb();return new Promise((s,i)=>{const o=n.transaction("pages","readwrite").objectStore("pages"),a=IDBKeyRange.lowerBound(t,!0),c=o.delete(a);c.onsuccess=()=>s(),c.onerror=()=>i(c.error)})}async readWalHeader(){const t=await this.getDb();return new Promise((n,s)=>{const o=t.transaction("wal_meta","readonly").objectStore("wal_meta").get("header");o.onsuccess=()=>{const a=o.result;n(a?a instanceof Uint8Array?a:new Uint8Array(a):null)},o.onerror=()=>s(o.error)})}async writeWalHeader(t){const n=await this.getDb();return new Promise((s,i)=>{const r=n.transaction("wal_meta","readwrite"),o=r.objectStore("wal_meta"),a=new Uint8Array(t.byteLength);a.set(t),o.put(a,"header"),r.oncomplete=()=>s(),r.onerror=()=>i(r.error),r.onabort=()=>i(r.error)})}async readWalFrames(t,n){const s=await this.getDb();return new Promise((i,r)=>{const a=s.transaction("wal_frames","readonly").objectStore("wal_frames"),c=[],l=n!==void 0?IDBKeyRange.bound(t,t+n-1):IDBKeyRange.lowerBound(t,!1),u=a.openCursor(l);u.onsuccess=()=>{const d=u.result;if(d){const h=d.value;c.push(h instanceof Uint8Array?h:new Uint8Array(h)),d.continue()}else i(c)},u.onerror=()=>r(u.error)})}async appendWalFrames(t){if(t.length===0)return;const n=await this.getDb();return new Promise((s,i)=>{const r=n.transaction("wal_frames","readwrite"),o=r.objectStore("wal_frames"),a=o.count();a.onsuccess=()=>{let c=a.result;for(const l of t){const u=new Uint8Array(l.byteLength);u.set(l),o.put(u,c++)}},r.oncomplete=()=>s(),r.onerror=()=>i(r.error),r.onabort=()=>i(r.error)})}async flushWal(){}async truncateWal(t){const n=await this.getDb();return new Promise((s,i)=>{const r=n.transaction(["wal_frames","wal_meta"],"readwrite"),o=r.objectStore("wal_frames"),a=r.objectStore("wal_meta");if(t===0)o.clear(),a.delete("header");else{const c=IDBKeyRange.lowerBound(t,!1);o.delete(c)}r.oncomplete=()=>s(),r.onerror=()=>i(r.error),r.onabort=()=>i(r.error)})}async getWalFrameCount(){const t=await this.getDb();return new Promise((n,s)=>{const o=t.transaction("wal_frames","readonly").objectStore("wal_frames").count();o.onsuccess=()=>n(o.result),o.onerror=()=>s(o.error)})}async close(){this.dbPromise&&((await this.dbPromise).close(),this.dbPromise=null)}}class to{constructor(t){N(this,"name","opfs");N(this,"isSynchronous");N(this,"dbName");N(this,"rootDir",null);N(this,"dbFileHandle",null);N(this,"walFileHandle",null);N(this,"dbSyncHandle",null);N(this,"walSyncHandle",null);this.dbName=t,this.isSynchronous=typeof globalThis.FileSystemSyncAccessHandle<"u"}async initHandles(){var t;if(!this.rootDir){if(!((t=navigator==null?void 0:navigator.storage)!=null&&t.getDirectory))throw new Error("OPFS (Origin Private File System) is not available in the current environment");if(this.rootDir=await navigator.storage.getDirectory(),this.dbFileHandle=await this.rootDir.getFileHandle(`${this.dbName}.db`,{create:!0}),this.walFileHandle=await this.rootDir.getFileHandle(`${this.dbName}.wal`,{create:!0}),this.isSynchronous)try{this.dbSyncHandle=await this.dbFileHandle.createSyncAccessHandle(),this.walSyncHandle=await this.walFileHandle.createSyncAccessHandle()}catch{}}}async readPages(t){if(t.length===0)return[];if(await this.initHandles(),this.dbSyncHandle){const i=this.dbSyncHandle.getSize();return t.map(r=>{const o=(r-1)*4096;if(o+4096>i)return null;const a=new Uint8Array(4096);return this.dbSyncHandle.read(a,{at:o}),a})}const n=await this.dbFileHandle.getFile(),s=[];for(const i of t){const r=(i-1)*4096;if(r+4096>n.size)s.push(null);else{const a=await n.slice(r,r+4096).arrayBuffer();s.push(new Uint8Array(a))}}return s}async writePages(t){if(t.length===0)return;if(await this.initHandles(),this.dbSyncHandle){for(const{pageId:s,data:i}of t){const r=(s-1)*4096;this.dbSyncHandle.write(i,{at:r})}return}const n=await this.dbFileHandle.createWritable({keepExistingData:!0});for(const{pageId:s,data:i}of t){const r=(s-1)*4096;await n.seek(r),await n.write(i)}await n.close()}async flush(){this.dbSyncHandle&&this.dbSyncHandle.flush()}async truncate(t){await this.initHandles();const n=t*4096;if(this.dbSyncHandle){this.dbSyncHandle.truncate(n);return}const s=await this.dbFileHandle.createWritable({keepExistingData:!0});await s.truncate(n),await s.close()}async readWalHeader(){if(await this.initHandles(),this.walSyncHandle){if(this.walSyncHandle.getSize()<32)return null;const i=new Uint8Array(32);return this.walSyncHandle.read(i,{at:0}),i}const t=await this.walFileHandle.getFile();if(t.size<32)return null;const n=t.slice(0,32);return new Uint8Array(await n.arrayBuffer())}async writeWalHeader(t){if(await this.initHandles(),this.walSyncHandle){this.walSyncHandle.write(t,{at:0});return}const n=await this.walFileHandle.createWritable({keepExistingData:!0});await n.seek(0),await n.write(t),await n.close()}async readWalFrames(t,n){await this.initHandles();const s=[];let i=t;const r=n!==void 0?t+n:1/0;if(this.walSyncHandle){const a=this.walSyncHandle.getSize();for(;i<r;){const c=32+i*4128;if(c>=a)break;const l=Math.min(4128,a-c),u=new Uint8Array(l);this.walSyncHandle.read(u,{at:c}),s.push(u),i++}return s}const o=await this.walFileHandle.getFile();for(;i<r;){const a=32+i*4128;if(a>=o.size)break;const c=Math.min(4128,o.size-a),l=o.slice(a,a+c);s.push(new Uint8Array(await l.arrayBuffer())),i++}return s}async appendWalFrames(t){if(await this.initHandles(),this.walSyncHandle){let i=Math.max(32,this.walSyncHandle.getSize());for(const r of t)this.walSyncHandle.write(r,{at:i}),i+=r.byteLength;return}const n=await this.walFileHandle.getFile(),s=await this.walFileHandle.createWritable({keepExistingData:!0});await s.seek(Math.max(32,n.size));for(const i of t)await s.write(i);await s.close()}async flushWal(){this.walSyncHandle&&this.walSyncHandle.flush()}async truncateWal(t){await this.initHandles();const n=t===0?0:32+t*4128;if(this.walSyncHandle){this.walSyncHandle.truncate(n);return}const s=await this.walFileHandle.createWritable({keepExistingData:t>0});await s.truncate(n),await s.close()}async getWalFrameCount(){await this.initHandles();let t=0;return this.walSyncHandle?t=this.walSyncHandle.getSize():t=(await this.walFileHandle.getFile()).size,t<=32?0:Math.ceil((t-32)/4128)}async close(){this.dbSyncHandle&&(this.dbSyncHandle.close(),this.dbSyncHandle=null),this.walSyncHandle&&(this.walSyncHandle.close(),this.walSyncHandle=null),this.dbFileHandle=null,this.walFileHandle=null,this.rootDir=null}}const cn=new Uint32Array(256);for(let e=0;e<256;e++){let t=e;for(let n=0;n<8;n++)t=t&1?3988292384^t>>>1:t>>>1;cn[e]=t>>>0}function bi(e,t=0,n=e.byteLength-t){let s=4294967295;const i=t+n;for(let r=t;r<i;r++)s=cn[(s^e[r])&255]^s>>>8;return(s^4294967295)>>>0}function be(e){let t=4294967295;for(let n=0;n<4096;n++){const s=n>=12&&n<=15?0:e[n];t=cn[(t^s)&255]^t>>>8}return(t^4294967295)>>>0}function Ni(e){let t=4294967295;for(let n=0;n<4096;n++){const s=n>=28&&n<=31?0:e[n];t=cn[(t^s)&255]^t>>>8}return(t^4294967295)>>>0}function Es(e){let t=4294967295;for(let s=0;s<24;s++)t=cn[(t^e[s])&255]^t>>>8;const n=Math.min(e.byteLength,4128);for(let s=32;s<n;s++)t=cn[(t^e[s])&255]^t>>>8;return(t^4294967295)>>>0}function un(e,t,n,s,i){const r=e instanceof Uint8Array?e:new Uint8Array(e.buffer,e.byteOffset,e.byteLength),o=n instanceof Uint8Array?n:new Uint8Array(n.buffer,n.byteOffset,n.byteLength);r.set(o.subarray(s,s+i),t)}function xt(e,t,n,s){(e instanceof Uint8Array?e:new Uint8Array(e.buffer,e.byteOffset,e.byteLength)).fill(n&255,t,t+s)}function Nl(e,t,n,s,i){const r=e instanceof Uint8Array?e:new Uint8Array(e.buffer,e.byteOffset,e.byteLength),o=n instanceof Uint8Array?n:new Uint8Array(n.buffer,n.byteOffset,n.byteLength);for(let a=0;a<i;a++){const c=r[t+a]-o[s+a];if(c!==0)return c}return 0}function Is(e){return e.length}function eo(e,t){return e instanceof Uint8Array?e[t]:e.getUint8(t)}function Ll(e,t,n){e instanceof Uint8Array?e[t]=n&255:e.setUint8(t,n&255)}function ps(e,t){return e.getUint16(t,!0)}function ys(e,t,n){e.setUint16(t,n&65535,!0)}function yt(e,t){return e.getUint32(t,!0)}function Tt(e,t,n){e.setUint32(t,n>>>0,!0)}function Bl(e,t){return e.getInt32(t,!0)}function Rl(e,t,n){e.setInt32(t,n|0,!0)}function Fl(e,t){return e.getFloat64(t,!0)}function Dl(e,t,n){e.setFloat64(t,n,!0)}function Ql(e,t){return e.getBigUint64(t,!0)}function vl(e,t,n){e.setBigUint64(t,n,!0)}function kl(e,t){return e.getBigInt64(t,!0)}function Ml(e,t,n){e.setBigInt64(t,n,!0)}function no(e,t,n){return n!==void 0?e[t+(n>>3)]&1<<(n&7)?1:0:e[t>>3]&1<<(t&7)?1:0}function so(e,t,n){n!==void 0?e[t+(n>>3)]|=1<<(n&7):e[t>>3]|=1<<(t&7)}function io(e,t,n){n!==void 0?e[t+(n>>3)]&=~(1<<(n&7)):e[t>>3]&=~(1<<(t&7))}function ro(e,t){if(!e)throw new Error(`Assertion failed: ${t}`)}class Li{constructor(t){N(this,"vfs");N(this,"buffer");N(this,"uint8");N(this,"view");N(this,"in_flight_flushes",new Map);N(this,"in_flight_reads",new Map);N(this,"coordinator",null);if(!t.vfs)throw new Error("Io requires a valid IVfsAdapter instance");if(!t.memory)throw new Error("Io requires a valid memory buffer or WebAssembly.Memory");this.vfs=t.vfs,this.buffer=t.memory instanceof WebAssembly.Memory?t.memory.buffer:t.memory,this.uint8=new Uint8Array(this.buffer),this.view=new DataView(this.buffer)}setTransactionCoordinator(t){this.coordinator=t}isInTransaction(){return this.coordinator?this.coordinator.isInTransaction():!1}stampSlotChecksum(t,n){const s=t*4096,i=this.uint8.subarray(s,s+4096);if(n===1){const r=Ni(i);Tt(this.view,s+Te,r)}else{const r=be(i);Tt(this.view,s+Me,r)}}async readSlot(t,n){if(n<=0)throw new Error(`Invalid page ID: ${n}. Page IDs must be positive integers.`);if(this.coordinator&&this.coordinator.hasSpilledPage(n)){const o=t*4096,a=this.coordinator.getSpilledPage(n);this.uint8.set(a,o);return}const s=this.in_flight_flushes.get(n);s&&await s;const i=this.in_flight_reads.get(n);if(i){await i;return}const r=(async()=>{const[o]=await this.vfs.readPages([n]),a=t*4096;if(o){if(o.byteLength!==4096)throw new Pe(n,`Unexpected page byte length: ${o.byteLength}, expected 4096`);const c=n===1?Te:Me,l=yt(new DataView(o.buffer,o.byteOffset),c);if(l!==0){const u=n===1?Ni(o):be(o);if(u!==l)throw new Pe(n,l,u)}this.uint8.set(o,a)}else this.uint8.fill(0,a,a+4096)})();this.in_flight_reads.set(n,r);try{await r}finally{this.in_flight_reads.delete(n)}}async writeSlot(t,n){if(n<=0)throw new Error(`Invalid page ID: ${n}. Page IDs must be positive integers.`);const s=this.in_flight_flushes.get(n);if(s){await s;return}const i=t*4096,r=this.uint8.subarray(i,i+4096);this.stampSlotChecksum(t,n);const o=r.slice();this.coordinator&&this.coordinator.onDirectPageWrite(n,o);const a=this.vfs.writePages([{pageId:n,data:o}]);this.in_flight_flushes.set(n,a);try{await a}finally{this.in_flight_flushes.delete(n)}}async spillOrWriteSlot(t,n){this.coordinator&&this.coordinator.isInTransaction()?await this.coordinator.spillUncommittedSlot(t,n):await this.writeSlot(t,n)}async resolvePageFault(t,n,s){if(s>0&&(this.coordinator&&this.coordinator.isInTransaction()?await this.coordinator.spillUncommittedSlot(t,s):await this.writeSlot(t,s)),this.coordinator&&this.coordinator.hasSpilledPage(n)){const i=t*4096,r=this.coordinator.getSpilledPage(n);this.uint8.set(r,i)}else await this.readSlot(t,n)}async flush(){var t,n;await((n=(t=this.vfs).flush)==null?void 0:n.call(t))}}const Bi=new Uint8Array([87,69,66,87,65,76]);function Ts(e={}){const t=new Uint8Array(ls),n=new DataView(t.buffer,t.byteOffset,t.byteLength);t.set(Bi,li),ys(n,ci,e.walVersion??Rr),Tt(n,ui,e.pageSize??Oe),Tt(n,fi,e.checkpointSeq??0);const s=e.salt1??Math.floor(Math.random()*4294967295)>>>0;Tt(n,Ai,s);const i=e.salt2??Math.floor(Math.random()*4294967295)>>>0;Tt(n,hi,i);const r=e.checksum??bi(t,0,24);return Tt(n,gi,r),Tt(n,Fr,0),t}function Cs(e,t=!0){if(e.byteLength<ls)throw new ms(`Truncated WAL file header: expected at least ${ls} bytes, received ${e.byteLength}`);for(let l=0;l<6;l++)if(e[li+l]!==Bi[l])throw new ms('Invalid WAL file header magic identifier (expected "WEBWAL")');const n=new DataView(e.buffer,e.byteOffset,e.byteLength),s=ps(n,ci),i=yt(n,ui),r=yt(n,fi),o=yt(n,Ai),a=yt(n,hi),c=yt(n,gi);if(t){const l=bi(e,0,24);if(c!==l)throw new ms(`WAL file header CRC32 checksum mismatch: stored ${c}, computed ${l}`)}return{walVersion:s,pageSize:i,checkpointSeq:r,salt1:o,salt2:a,checksum:c}}function ws(e,t){const n=new Uint8Array(an),s=new DataView(n.buffer,n.byteOffset,n.byteLength);Tt(s,di,e.magic??Qn),ys(s,_i,e.frameType),ys(s,mi,e.flags??0),Tt(s,Ei,e.txId),Tt(s,Ii,e.pageId),Tt(s,pi,e.dbSizePages??0),Tt(s,yi,e.frameSeq),Tt(s,Dr,0),t&&n.set(t.subarray(0,Oe),Ve);const i=e.checksum??Es(n);return Tt(s,Ti,i),n}function Ri(e){if(e.byteLength<Ve)throw new qn(`Truncated WAL frame header: expected at least ${Ve} bytes, received ${e.byteLength}`);const t=new DataView(e.buffer,e.byteOffset,e.byteLength);return{magic:yt(t,di),frameType:ps(t,_i),flags:ps(t,mi),txId:yt(t,Ei),pageId:yt(t,Ii),dbSizePages:yt(t,pi),frameSeq:yt(t,yi),checksum:yt(t,Ti)}}function Fi(e){if(e.byteLength<an)return{valid:!1,reason:"truncated"};const t=Ri(e);if(t.magic!==Qn)return{valid:!1,reason:"magic_mismatch",header:t};const n=Es(e);return t.checksum!==n?{valid:!1,reason:"checksum_mismatch",header:t}:{valid:!0,header:t}}function Gl(e,t=!0){if(e.byteLength<an)throw new qn(`Truncated WAL frame: expected ${an} bytes, received ${e.byteLength}`);const n=Ri(e);if(n.magic!==Qn)throw new qn(`Invalid WAL frame magic: expected 0x${Qn.toString(16)}, got 0x${n.magic.toString(16)}`);if(t){const i=Es(e);if(n.checksum!==i)throw new qn(`WAL frame CRC32 checksum mismatch: stored ${n.checksum}, computed ${i}`)}const s=e.subarray(Ve,an);return{header:n,pageData:s}}const oo=new TextDecoder,ao="0123456789abcdef",Di="0123456789ABCDEFGHJKMNPQRSTVWXYZ";function ql(e){return e>=48&&e<=57?e-48:e>=97&&e<=102?e-97+10:e>=65&&e<=70?e-65+10:-1}function Qi(e){if(e>=48&&e<=57)return e-48;switch(e>=97&&e<=122&&(e=e-32),e){case 65:return 10;case 66:return 11;case 67:return 12;case 68:return 13;case 69:return 14;case 70:return 15;case 71:return 16;case 72:return 17;case 74:return 18;case 75:return 19;case 77:return 20;case 78:return 21;case 80:return 22;case 81:return 23;case 82:return 24;case 83:return 25;case 84:return 26;case 86:return 27;case 87:return 28;case 88:return 29;case 89:return 30;case 90:return 31;case 73:case 76:return 1;case 79:return 0;default:return-1}}function Wl(e,t,n){let s=0,i=-1;for(let r=0;r<Is(e);r++){const o=e.charCodeAt(r);if(o!==45){if(s>=32)return-1;const a=ql(o);if(a<0)return-1;s%2===0?i=a:t[n+(s>>1)]=i<<4|a,s++}}return s!==32?-1:0}function Hl(e,t,n){let s=0;for(let i=0;i<16;i++){(i===4||i===6||i===8||i===10)&&(n[s++]=45);const r=e[t+i];n[s++]=ao.charCodeAt(r>>4&15),n[s++]=ao.charCodeAt(r&15)}n[s]=0}class fn{static encode(t,n,s=0){if(Wl(t,n,s)!==0)throw new Error(`Invalid UUID format: "${t}" (must be 36 characters with hyphens)`)}static decode(t,n=0){const s=new Uint8Array(37);return Hl(t,n,s),oo.decode(s.subarray(0,36))}}function Vl(e,t,n){if(Is(e)!==26)return-1;let s=0n;for(let o=0;o<10;o++){const a=Qi(e.charCodeAt(o));if(a<0)return-1;s=s<<5n|BigInt(a)}t[n+0]=Number(s>>40n&0xffn),t[n+1]=Number(s>>32n&0xffn),t[n+2]=Number(s>>24n&0xffn),t[n+3]=Number(s>>16n&0xffn),t[n+4]=Number(s>>8n&0xffn),t[n+5]=Number(s&0xffn);let i=0n;for(let o=10;o<18;o++){const a=Qi(e.charCodeAt(o));if(a<0)return-1;i=i<<5n|BigInt(a)}let r=0n;for(let o=18;o<26;o++){const a=Qi(e.charCodeAt(o));if(a<0)return-1;r=r<<5n|BigInt(a)}for(let o=0;o<5;o++)t[n+6+o]=Number(i>>BigInt((4-o)*8)&0xffn),t[n+11+o]=Number(r>>BigInt((4-o)*8)&0xffn);return 0}function $l(e,t,n){let s=0n;for(let o=0;o<6;o++)s=s<<8n|BigInt(e[t+o]);for(let o=9;o>=0;o--)n[o]=Di.charCodeAt(Number(s%32n)),s/=32n;let i=0n;for(let o=0;o<5;o++)i=i<<8n|BigInt(e[t+6+o]);let r=0n;for(let o=0;o<5;o++)r=r<<8n|BigInt(e[t+11+o]);for(let o=25;o>=18;o--)n[o]=Di.charCodeAt(Number(r&31n)),r>>=5n;for(let o=17;o>=10;o--)n[o]=Di.charCodeAt(Number(i&31n)),i>>=5n;n[26]=0}class An{static encode(t,n,s=0){if(Vl(t,n,s)!==0)throw new Error(`Invalid ULID length: "${t}" (must be 26 Crockford Base32 characters)`)}static decode(t,n=0){const s=new Uint8Array(27);return $l(t,n,s),oo.decode(s.subarray(0,26))}}const vi=new TextEncoder,Ss=new TextDecoder;function Wn(e,t,n=fs,s=0){e.setUint8(t+0,n),e.setUint8(t+1,0),e.setUint16(t+2,0,!0),e.setUint16(t+4,4096,!0),e.setUint32(t+6,s,!0),e.setUint16(t+10,0,!0),e.setUint32(t+Me,0,!0)}function lo(e,t,n=0){e.setUint8(t+0,$e),e.setUint8(t+1,0),e.setUint16(t+2,0,!0),e.setUint16(t+4,0,!0),e.setUint32(t+6,n,!0),e.setUint16(t+10,0,!0),e.setUint32(t+Me,0,!0)}function Xe(e,t){return e.getUint8(t+0)}function xl(e,t,n){e.setUint8(t+0,n)}function ft(e,t){return e.getUint16(t+2,!0)}function Ye(e,t,n){e.setUint16(t+2,n,!0)}function Ze(e,t){return e.getUint16(t+4,!0)}function je(e,t,n){e.setUint16(t+4,n,!0)}function Ut(e,t){return e.getUint32(t+6,!0)}function Us(e,t,n){e.setUint32(t+6,n,!0)}function Ne(e,t){return e.getUint16(t+10,!0)}function Ke(e,t,n){e.setUint16(t+10,n,!0)}function Xl(e,t){return e.getUint32(t+Me,!0)}function Yl(e,t,n){e.setUint32(t+Me,n,!0)}function at(e,t,n){const s=t+te+n*2;return e.getUint16(s,!0)}function hn(e,t,n,s){const i=t+te+n*2;e.setUint16(i,s,!0)}function Os(e,t){const n=ft(e,t),s=Ze(e,t),i=te+n*2;return s-i}function co(e,t){return Os(e,t)+Ne(e,t)}function Hn(e,t,n=0,s){const i=ft(e,t);if(i===0){je(e,t,4096),Ke(e,t,0);return}let r=e,o=n;if(n===0||n===t||n+4096>e.byteLength){const c=new Uint8Array(4096);r=new DataView(c.buffer),o=0}un(r,o,e,t,te);let a=4096;for(let c=0;c<i;c++){let l=0,u=e,d=0;if(s&&c===s.cell_idx)l=s.row_bytes.byteLength,u=s.row_bytes,d=0;else{const h=at(e,t,c);Xe(e,t)===us?l=2+e.getUint16(t+h,!0)+8:l=Ps(e,t+h),u=e,d=t+h}a=a-l,un(r,o+a,u,d,l),hn(r,o,c,a)}je(r,o,a),Ke(r,o,0),un(e,t,r,o,4096)}function Ps(e,t){return e.getUint16(t+1,!0)}function gn(e,t,n,s){const i=ft(e,t),r=Ze(e,t),o=n.byteLength+2,a=te+i*2,c=r-a,l=c+Ne(e,t);if(o>l)return-1;o>c&&Hn(e,t,s);const u=Ze(e,t),d=ft(e,t),h=u-n.byteLength,f=e.byteOffset+t+h;return new Uint8Array(e.buffer).set(n,f),hn(e,t,d,h),Ye(e,t,d+1),je(e,t,h),d}function uo(e,t,n){const s=ft(e,t);if(n>=s)return;const i=at(e,t,n),r=Ps(e,t+i),o=t+te,a=o+(n+1)*2,c=o+n*2,l=(s-1-n)*2;l>0&&un(e,c,e,a,l),Ye(e,t,s-1),Ke(e,t,Ne(e,t)+r)}function ki(e,t,n,s,i){const r=ft(e,t);if(n<0||n>=r)throw new Error(`Invalid cell index ${n} for update`);const o=at(e,t,n),a=Ps(e,t+o),c=s.byteLength,l=new Uint8Array(e.buffer);if(c<=a)return l.set(s,e.byteOffset+t+o),c<a&&Ke(e,t,Ne(e,t)+(a-c)),!0;const u=co(e,t),d=c-a;if(u>=d){if(Os(e,t)<c)return Hn(e,t,i,{cell_idx:n,row_bytes:s}),!0;Ke(e,t,Ne(e,t)+a);const g=Ze(e,t)-c;return l.set(s,e.byteOffset+t+g),hn(e,t,n,g),je(e,t,g),!0}return!1}function Zl(e){const t=Array.isArray(e)?e:e.columns,n=Math.ceil(t.length/8);let s=0,i=0;for(let r=0;r<t.length;r++){const o=t[r];o.type===S.INT32?s+=4:o.type===S.INT64||o.type===S.FLOAT64?s+=8:o.type===S.UUID||o.type===S.ULID?s+=16:(o.type===S.TEXT||o.type===S.BLOB)&&i++}return{null_bitmap_bytes:n,fixed_slice_size:s,var_col_count:i}}function bs(e,t){const n=Array.isArray(e)?e:e.columns,s=n.length;if(s>Ae)throw new Mn(s,Ae);const i=Math.ceil(s/8),r=new Uint8Array(i);for(let p=0;p<s;p++){const y=n[p],T=t[y.name];if(T==null){if(y.flags&tt.NOT_NULL)throw new As(y.name);const w=p>>3,C=1<<(p&7);r[w]|=C}}let o=0;for(let p=0;p<s;p++){const y=n[p];if(!((r[p>>3]&1<<(p&7))!==0))switch(y.type){case S.INT32:o+=4;break;case S.INT64:case S.FLOAT64:o+=8;break;case S.UUID:case S.ULID:o+=16;break}}const a=[];for(let p=0;p<s;p++){const y=n[p];if(y.type===S.TEXT||y.type===S.BLOB)if((r[p>>3]&1<<(p&7))!==0)a.push({col_idx:p,col:y,payload:null});else{const O=t[y.name];let w;y.type===S.TEXT?w=vi.encode(String(O??"")):w=O instanceof Uint8Array?O:new Uint8Array(O),a.push({col_idx:p,col:y,payload:w})}}const c=a.length*4,l=3+i+o+c;let u=0;for(let p=0;p<a.length;p++){const y=a[p];y.payload&&(u+=y.payload.byteLength)}const d=l+u;if(d>2048)throw new Wr(d,2048);const h=new Uint8Array(d),f=new DataView(h.buffer);f.setUint8(0,1),f.setUint16(1,d,!0),h.set(r,3);let g=3+i;for(let p=0;p<s;p++){const y=n[p];if(!((r[p>>3]&1<<(p&7))!==0)){const O=t[y.name];switch(y.type){case S.INT32:f.setInt32(g,Number(O),!0),g+=4;break;case S.INT64:f.setBigInt64(g,BigInt(O),!0),g+=8;break;case S.FLOAT64:f.setFloat64(g,Number(O),!0),g+=8;break;case S.UUID:fn.encode(String(O),h,g),g+=16;break;case S.ULID:An.encode(String(O),h,g),g+=16;break}}}let _=g,I=l;for(let p=0;p<a.length;p++){const y=a[p];y.payload===null?(f.setUint16(_,0,!0),f.setUint16(_+2,0,!0)):(f.setUint16(_,I,!0),f.setUint16(_+2,y.payload.byteLength,!0),h.set(y.payload,I),I+=y.payload.byteLength),_+=4}return h}function Je(e,t,n){let s,i,r;if(e instanceof DataView){i=e,r=t;const g=n;s=Array.isArray(g)?g:g.columns}else s=Array.isArray(e)?e:e.columns,i=t,r=n;const o={},a=s.length,c=Math.ceil(a/8),l=new Uint8Array(i.buffer,i.byteOffset+r+3,c);let u=r+3+c,d=0;const h=u;for(let g=0;g<a;g++){const _=s[g];if(!((l[g>>3]&1<<(g&7))!==0))switch(_.type){case S.INT32:u+=4;break;case S.INT64:case S.FLOAT64:u+=8;break;case S.UUID:case S.ULID:u+=16;break}}const f=u;u=h;for(let g=0;g<a;g++){const _=s[g];if((l[g>>3]&1<<(g&7))!==0){o[_.name]=null,(_.type===S.TEXT||_.type===S.BLOB)&&d++;continue}switch(_.type){case S.INT32:o[_.name]=i.getInt32(u,!0),u+=4;break;case S.INT64:o[_.name]=i.getBigInt64(u,!0),u+=8;break;case S.FLOAT64:o[_.name]=i.getFloat64(u,!0),u+=8;break;case S.UUID:{const p=new Uint8Array(i.buffer,i.byteOffset+u,16);o[_.name]=fn.decode(p,0),u+=16;break}case S.ULID:{const p=new Uint8Array(i.buffer,i.byteOffset+u,16);o[_.name]=An.decode(p,0),u+=16;break}case S.TEXT:{const p=f+d*4,y=i.getUint16(p,!0),T=i.getUint16(p+2,!0),O=i.byteOffset+r+y,w=new Uint8Array(i.buffer,O,T);o[_.name]=Ss.decode(w),d++;break}case S.BLOB:{const p=f+d*4,y=i.getUint16(p,!0),T=i.getUint16(p+2,!0),O=i.byteOffset+r+y,w=new Uint8Array(T);w.set(new Uint8Array(i.buffer,O,T)),o[_.name]=w,d++;break}}}return o}function fo(e,t,n=0){Wn(e,t,Ci,n)}function Ns(e,t){return e.getUint32(t+6,!0)}function Ao(e,t,n){e.setUint32(t+6,n,!0)}function ho(e,t,n,s){const i=ft(e,t);if(i>=yr)return-1;const o=Ze(e,t)-pr,a=t+o;return e.setUint32(a,n,!0),e.setBigInt64(a+4,s,!0),hn(e,t,i,o),Ye(e,t,i+1),je(e,t,o),i+1}function jl(e,t,n){const s=ft(e,t);if(s===0)return Ns(e,t);let i=0,r=s-1,o=-1;for(;i<=r;){const a=i+r>>1,c=at(e,t,a),l=e.getBigInt64(t+c+4,!0);n<=l?(o=e.getUint32(t+c,!0),r=a-1):i=a+1}return o!==-1?o:Ns(e,t)}function Kl(e,t,n){const s=ft(e,t),i=Tr;if(s<=i)throw new Error(`Cannot split interior page with only ${s} cells`);const r=at(e,t,i),o=e.getUint32(t+r,!0),a=e.getBigInt64(t+r+4,!0),c=Ns(e,t);fo(e,n,c);for(let l=i+1;l<s;l++){const u=at(e,t,l),d=e.getUint32(t+u,!0),h=e.getBigInt64(t+u+4,!0);ho(e,n,d,h)}return Ao(e,t,o),Ye(e,t,i),{median_rowid:a,promoted_child_page_id:o,right_child_page_id:c}}function Ls(e,t,n=0){Wn(e,t,us,n)}function Bs(e,t,n,s,i,r){if(e!==s)return e-s;if(e===S.NULL)return n<r?-1:n>r?1:0;let o=0;if(e===S.INT32||e===S.INT64||e===S.FLOAT64){const a=typeof t=="bigint"?Number(t):t,c=typeof i=="bigint"?Number(i):i;o=a<c?-1:a>c?1:0}else if(e===S.TEXT||e===S.UUID||e===S.ULID){const a=String(t),c=String(i);o=a<c?-1:a>c?1:0}else if(e===S.BLOB){const a=t,c=i,l=Math.min(a.length,c.length);for(let u=0;u<l;u++)if(a[u]!==c[u]){o=a[u]<c[u]?-1:1;break}o===0&&(o=a.length-c.length)}return o!==0?o:n<r?-1:n>r?1:0}function Mi(e,t,n,s){const i=new Uint8Array(e.buffer,e.byteOffset+t,n);return n===0?{cellType:S.NULL,cellVal:null}:s===S.TEXT?n===4&&(i[2]===0&&i[3]===0||i[2]===255&&i[3]===255)?{cellType:S.INT32,cellVal:new DataView(i.buffer,i.byteOffset).getInt32(0,!0)}:n===2&&i[0]<32&&i[1]<32?{cellType:S.BLOB,cellVal:i}:{cellType:S.TEXT,cellVal:Ss.decode(i)}:n===2?{cellType:S.BLOB,cellVal:i}:n===4?{cellType:S.INT32,cellVal:new DataView(i.buffer,i.byteOffset).getInt32(0,!0)}:s===S.UUID&&n===16?{cellType:S.UUID,cellVal:fn.decode(i,0)}:s===S.ULID&&n===16?{cellType:S.ULID,cellVal:An.decode(i,0)}:s===S.FLOAT64&&n===8?{cellType:S.FLOAT64,cellVal:new DataView(i.buffer,i.byteOffset).getFloat64(0,!0)}:s===S.INT64&&n===8?{cellType:S.INT64,cellVal:new DataView(i.buffer,i.byteOffset).getBigInt64(0,!0)}:s===S.BLOB?n===5||n===6?{cellType:S.TEXT,cellVal:Ss.decode(i)}:{cellType:S.BLOB,cellVal:i}:{cellType:S.TEXT,cellVal:Ss.decode(i)}}function Gi(e,t,n,s,i,r){let o;n===S.NULL||s===null||s===void 0?o=new Uint8Array(0):n===S.INT32?(o=new Uint8Array(4),new DataView(o.buffer).setInt32(0,Number(s),!0)):n===S.INT64?(o=new Uint8Array(8),new DataView(o.buffer).setBigInt64(0,BigInt(s),!0)):n===S.FLOAT64?(o=new Uint8Array(8),new DataView(o.buffer).setFloat64(0,Number(s),!0)):n===S.UUID?(o=new Uint8Array(16),fn.encode(String(s),o,0)):n===S.ULID?(o=new Uint8Array(16),An.encode(String(s),o,0)):n===S.TEXT?o=vi.encode(String(s)):o=s instanceof Uint8Array?s:new Uint8Array(s);const a=2+o.byteLength+8,c=a+2,l=ft(e,t),u=Os(e,t),d=u+Ne(e,t);if(c>d)return-1;c>u&&Hn(e,t,r);const f=Ze(e,t)-a,g=t+f,_=e.byteOffset+g;e.setUint16(g,o.byteLength,!0),new Uint8Array(e.buffer).set(o,_+2),e.setBigInt64(g+2+o.byteLength,i,!0);let I=0,p=l-1,y=l;for(;I<=p;){const U=I+p>>1,Q=at(e,t,U),R=e.getUint16(t+Q,!0),A=e.getBigInt64(t+Q+2+R,!0),{cellType:b,cellVal:k}=Mi(e,t+Q+2,R,n);Bs(n,s,i,b,k,A)<0?(y=U,p=U-1):I=U+1}const T=new Uint8Array(e.buffer),w=e.byteOffset+t+te,C=w+y*2,B=w+(y+1)*2,P=(l-y)*2;return P>0&&T.copyWithin(B,C,C+P),hn(e,t,y,f),Ye(e,t,l+1),je(e,t,f),y}function go(e,t,n){const s=ft(e,t);if(n<0||n>=s)return;const i=at(e,t,n),o=2+e.getUint16(t+i,!0)+8,a=t+te,c=a+(n+1)*2,l=a+n*2,u=(s-1-n)*2;u>0&&un(e,l,e,c,u),Ye(e,t,s-1),Ke(e,t,Ne(e,t)+o)}function Vn(e,t,n,s,i){const r=ft(e,t);let o=0,a=r-1;for(;o<=a;){const c=o+a>>1,l=at(e,t,c),u=e.getUint16(t+l,!0),d=e.getBigInt64(t+l+2+u,!0),{cellType:h,cellVal:f}=Mi(e,t+l+2,u,n),_=Bs(n,s,i!==void 0?i:d,h,f,d);if(_===0){if(i===void 0){let I=c;for(;I>0;){const p=I-1,y=at(e,t,p),T=e.getUint16(t+y,!0),{cellType:O,cellVal:w}=Mi(e,t+y+2,T,n);if(Bs(n,s,0n,O,w,0n)===0)I=p;else break}return{found:!0,slot_idx:I}}return{found:!0,slot_idx:c}}else _<0?a=c-1:o=c+1}return{found:!1,slot_idx:o}}function _o(e,t){if(t==null)return new Uint8Array(0);if(e===S.INT32){const n=new Uint8Array(4);return new DataView(n.buffer).setInt32(0,Number(t),!0),n}if(e===S.INT64){const n=new Uint8Array(8);return new DataView(n.buffer).setBigInt64(0,BigInt(t),!0),n}if(e===S.FLOAT64){const n=new Uint8Array(8);return new DataView(n.buffer).setFloat64(0,Number(t),!0),n}if(e===S.UUID){const n=new Uint8Array(16);return fn.encode(String(t),n,0),n}if(e===S.ULID){const n=new Uint8Array(16);return An.encode(String(t),n,0),n}return e===S.TEXT?vi.encode(String(t)):t instanceof Uint8Array?t:new Uint8Array(t)}function Rs(e,t,n,s){const i=[];let r=0;for(let c=0;c<n;c++){const l=e[t[c]],u=s[l.name],d=_o(l.type,u),h=new Uint8Array(3+d.byteLength);h[0]=l.type,h[1]=d.byteLength&255,h[2]=d.byteLength>>8&255,h.set(d,3),i.push(h),r+=h.byteLength}const o=new Uint8Array(r);let a=0;for(let c=0;c<i.length;c++){const l=i[c];o.set(l,a),a+=l.byteLength}return o}const Jl=2654435769;function $n(e,t){const n=Math.imul(e,Jl);return(n^n>>>16)>>>0&t}function mo(e,t,n,s){const i=n-1;let r=$n(s,i);for(let o=0;o<n;o++){const a=t+r*Ue,c=e.getUint32(a,!0);if(c===0)return-1;if(c===s)return e.getUint32(a+4,!0);r=r+1&i}return-1}function Eo(e,t,n,s,i){const r=n-1;let o=$n(s,r);for(let a=0;a<n;a++){const c=t+o*Ue,l=e.getUint32(c,!0);if(l===0||l===s){e.setUint32(c,s,!0),e.setUint32(c+4,i,!0);return}o=o+1&r}throw new Error(`BufferPool page table full: cannot insert page ${s}`)}function qi(e,t,n,s){const i=n-1;let r=$n(s,i),o=!1;for(let l=0;l<n;l++){const u=t+r*Ue,d=e.getUint32(u,!0);if(d===0)return!1;if(d===s){o=!0;break}r=r+1&i}if(!o)return!1;let a=r;for(;;){a=a+1&i;const l=t+a*Ue,u=e.getUint32(l,!0);if(u===0)break;const d=$n(u,i);if((r-d&i)<(a-d&i)){const h=e.getUint32(l+4,!0),f=t+r*Ue;e.setUint32(f,u,!0),e.setUint32(f+4,h,!0),r=a}}const c=t+r*Ue;return e.setUint32(c,0,!0),e.setUint32(c+4,0,!0),!0}function zl(e){return e*4096}function dn(e,t,n){return yt(e,t+n*4)}function Wi(e,t,n,s){Tt(e,t+n*4,s)}function Vt(e,t,n,s){return mo(e,t,n,s)}function Io(e,t,n,s,i,r){ro(r>0,"page_id must be > 0");const o=dn(e,t,i);return o>0&&o!==r&&qi(e,n,s,o),Wi(e,t,i,r),Eo(e,n,s,r,i),0}function po(e,t,n,s,i){const r=dn(e,t,i);return r>0?(qi(e,n,s,r),Wi(e,t,i,0),1):0}function yo(e,t,n){so(e,t,n)}function To(e,t,n){io(e,t,n)}function Hi(e,t,n){return no(e,t,n)===1}function Vi(e,t){if(e[t]>=4294967295)throw new Error(`Pin count overflow on slot ${t}`);e[t]++}function $i(e,t){t!==0&&e[t]>0&&e[t]--}function _n(e,t){return t===0||e[t]>0}function xi(e,t,n,s,i,r){const o=new DataView(e);for(let c=1;c<i;c++)if(yt(o,s+c*4)===0&&!_n(n,c))return{candidate_slot:c,next_clock_hand:r};let a=r;for(let c=0;c<i*2;c++){if(a=(a+1)%i,a===0||_n(n,a))continue;const l=new DataView(e,a*4096,4096);if(Xe(l,0)!==vn)if(t[a]===1)t[a]=0;else return{candidate_slot:a,next_clock_hand:a}}throw new Error("Cache deadlock: all slots are pinned")}function Xi(e,t,n,s,i,r,o,a){const c=new DataView(e);let l=-1,u=o;if(a>1&&a<=r&&dn(c,s,a-1)===0&&!_n(n,a-1))l=a-1;else{const I=xi(e,t,n,s,r,o);l=I.candidate_slot,u=I.next_clock_hand}const d=dn(c,s,l),h=Hi(new Uint8Array(e),i,l),f=new DataView(e,l*4096,4096),g=d>0&&Xe(f,0)===$e,_=h&&!g&&d>0?d:0;return{candidate_slot:l,flush_page_id:_,next_clock_hand:u}}function Ct(e,t){return e.cursors&&e.cursors[t]?e.cursors[t]:e.cursor}function Xt(e,t){if(t<=0)return 0;if(e.byteLength>=Gt+Cr){const n=Vt(e,Gt,Ht,t);if(n>=0)return n*4096}return(t-1)*4096}function mn(e,t){if(e==null||t===null||t===void 0)return{result:0,is_unknown:!0};if(typeof e=="boolean"||typeof t=="boolean"){const n=e?1:0,s=t?1:0;return n===s?{result:0,is_unknown:!1}:{result:n>s?1:-1,is_unknown:!1}}if(typeof e=="number"&&typeof t=="number")return e===t?{result:0,is_unknown:!1}:{result:e>t?1:-1,is_unknown:!1};if(typeof e=="bigint"||typeof t=="bigint"){const n=BigInt(e),s=BigInt(t);return n===s?{result:0,is_unknown:!1}:{result:n>s?1:-1,is_unknown:!1}}if(typeof e=="string"&&typeof t=="string")return e===t?{result:0,is_unknown:!1}:{result:e>t?1:-1,is_unknown:!1};if(e instanceof Uint8Array&&t instanceof Uint8Array){const n=Math.min(e.byteLength,t.byteLength);for(let s=0;s<n;s++)if(e[s]!==t[s])return{result:e[s]>t[s]?1:-1,is_unknown:!1};return e.byteLength===t.byteLength?{result:0,is_unknown:!1}:{result:e.byteLength>t.byteLength?1:-1,is_unknown:!1}}return e===t?{result:0,is_unknown:!1}:{result:e>t?1:-1,is_unknown:!1}}function Co(e){return e>=65&&e<=90?e+32:e}function tc(e,t,n,s){let i=0,r=0,o=-1,a=-1;for(;i<t;){const c=r<s?n.charCodeAt(r):0,l=e.charCodeAt(i);if(r<s&&(c===95||Co(c)===Co(l)))i++,r++;else if(r<s&&c===37)o=r++,a=i;else if(o!==-1)r=o+1,i=++a;else return 0}for(;r<s&&n.charCodeAt(r)===37;)r++;return r===s?1:0}function ze(e,t){return tc(e,e.length,t,t.length)===1}function En(e,t,n){const s=n.numKeys;for(let i=0;i<s;i++){const r=e[i],o=t[i],a=n.directions[i]??0,c=n.nullOrders[i]??(a===1?1:0),l=r==null,u=o==null;if(l&&u)continue;if(l||u)return c===0?l?-1:1:l?1:-1;let d=0;if(typeof r=="number"&&typeof o=="number")d=r<o?-1:r>o?1:0;else if(typeof r=="bigint"||typeof o=="bigint"){const h=BigInt(r),f=BigInt(o);d=h<f?-1:h>f?1:0}else if(typeof r=="string"&&typeof o=="string")d=r<o?-1:r>o?1:0;else if(r instanceof Uint8Array&&o instanceof Uint8Array){const h=Math.min(r.byteLength,o.byteLength);for(let f=0;f<h;f++)if(r[f]!==o[f]){d=r[f]<o[f]?-1:1;break}d===0&&(d=r.byteLength<o.byteLength?-1:r.byteLength>o.byteLength?1:0)}else d=r<o?-1:r>o?1:0;if(d!==0)return a===1?-d:d}return 0}function wo(e,t,n,s){const i=s.numKeys;for(let r=0;r<i;r++){const o=e[t+r],a=n[r],c=s.directions[r]??0,l=s.nullOrders[r]??(c===1?1:0),u=o==null,d=a==null;if(u&&d)continue;if(u||d)return l===0?u?-1:1:u?1:-1;let h=0;if(typeof o=="number"&&typeof a=="number")h=o<a?-1:o>a?1:0;else if(typeof o=="string"&&typeof a=="string")h=o<a?-1:o>a?1:0;else if(typeof o=="bigint"||typeof a=="bigint"){const f=BigInt(o),g=BigInt(a);h=f<g?-1:f>g?1:0}else if(o instanceof Uint8Array&&a instanceof Uint8Array){const f=Math.min(o.byteLength,a.byteLength);for(let g=0;g<f;g++)if(o[g]!==a[g]){h=o[g]<a[g]?-1:1;break}h===0&&(h=o.byteLength<a.byteLength?-1:o.byteLength>a.byteLength?1:0)}else h=o<a?-1:o>a?1:0;if(h!==0)return c===1?-h:h}return 0}function Fs(e){let t=2166136261;for(let n=0;n<e.length;n++){const s=e[n];if(s==null)t^=255,t=Math.imul(t,16777619);else if(typeof s=="number"){const i=new ArrayBuffer(8);new DataView(i).setFloat64(0,s,!0);const r=new Uint8Array(i);for(let o=0;o<8;o++)t^=r[o],t=Math.imul(t,16777619)}else if(typeof s=="string")for(let i=0;i<s.length;i++)t^=s.charCodeAt(i)&255,t=Math.imul(t,16777619);else if(typeof s=="bigint"){const i=Number(s);t^=i&255,t=Math.imul(t,16777619)}else if(s instanceof Uint8Array)for(let i=0;i<s.byteLength;i++)t^=s[i],t=Math.imul(t,16777619)}return t=t>>>0,t===0?1:t}function ec(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++){const s=e[n],i=t[n];if(s==null){if(i!=null)return!1}else{if(i==null)return!1;if(s!==i)if(s instanceof Uint8Array&&i instanceof Uint8Array){if(s.byteLength!==i.byteLength)return!1;for(let r=0;r<s.byteLength;r++)if(s[r]!==i[r])return!1}else return!1}}return!0}function So(e){const t=new Array(e);for(let n=0;n<e;n++)t[n]={hash:0,keys:[],count:0,sum:0,min_val:1/0,max_val:-1/0,has_val:!1};return t}function Uo(e,t,n,s){let i=t;for(;;){let r=i;const o=2*i+1,a=2*i+2;if(o<n&&En(e[o].keys,e[r].keys,s)>0&&(r=o),a<n&&En(e[a].keys,e[r].keys,s)>0&&(r=a),r!==i){const c=e[i];e[i]=e[r],e[r]=c,i=r}else break}}function nc(e){const t=e.keyInfo;e.entries.sort((n,s)=>En(n.keys,s.keys,t)),e.readIdx=t.offset??0}function Oo(e,t,n){const s=new Uint8Array(e.buffer,e.byteOffset+t,n),i=new Uint8Array(n);return i.set(s),i}function sc(e,t,n,s,i,r,o){if(o>0&&t.entries.length>=o){if(En(n,t.entries[0].keys,t.keyInfo)>=0)return L.RUNNING;const u=t.entries[0],d=i-u.rowLen;if(d>0&&e.arenaOffset+d>e.maxQueryMemory)return e.status=L.ARENA_EXHAUSTED,L.ARENA_EXHAUSTED;e.arenaOffset+=d;const h=Oo(r,s,i);return u.keys=n,u.rowOffset=s,u.rowLen=i,u.rowData=h,Uo(t.entries,0,o,t.keyInfo),L.RUNNING}const a=16+16*n.length+i;if(e.arenaOffset+a>e.maxQueryMemory)return e.status=L.ARENA_EXHAUSTED,L.ARENA_EXHAUSTED;e.arenaOffset+=a;const c=Oo(r,s,i);if(t.entries.push({keys:n,rowOffset:s,rowLen:i,rowData:c}),o>0&&t.entries.length===o)for(let l=Math.floor(o/2)-1;l>=0;l--)Uo(t.entries,l,o,t.keyInfo);return L.RUNNING}function ic(e,t,n){var r,o;let s;const i={};if(e.outputColumns&&n===e.outputColumns.length){s=e.outputColumns;for(let a=0;a<n;a++)i[s[a].name]=e.registers[t+a]}else if(e.table&&n===e.table.columns.length){s=e.table.columns;for(let a=0;a<n;a++)i[s[a].name]=e.registers[t+a]}else{s=[];for(let a=0;a<n;a++){const c=e.registers[t+a],l=((o=(r=e.table)==null?void 0:r.columns[a])==null?void 0:o.name)??`col_${a}`;let u=S.TEXT;typeof c=="number"?u=Number.isInteger(c)?S.INT32:S.FLOAT64:typeof c=="bigint"?u=S.INT64:c instanceof Uint8Array&&(u=S.BLOB),s.push({name:l,type:u,flags:tt.NONE,colOffset:0}),i[l]=c}}return bs(s,i)}function Yi(e,t,n,s){const i=2+n.byteLength;if(e.resultOffset+i>oi)return e.status=L.BUFFER_FULL,e.pc=s,L.BUFFER_FULL;const r=Dn+e.resultOffset;return t.setUint16(r,n.byteLength,!0),new Uint8Array(t.buffer,t.byteOffset+r+2,n.byteLength).set(n),e.resultOffset+=i,e.resultCount++,L.RUNNING}function tn(e,t,n){return(e.getUint8(t+(n>>3))&1<<(n&7))!==0}function xn(e,t,n,s,i){let r=t+n;for(let o=0;o<i;o++)if(!tn(e,t,o))switch(s[o].type){case S.INT32:r+=4;break;case S.INT64:case S.FLOAT64:r+=8;break;case S.UUID:case S.ULID:r+=16;break}return r}const Po=new TextDecoder;function Xn(e,t,n){var c,l;const s=new DataView(n.buffer,n.byteOffset,n.byteLength),i=n.byteLength,r=1e7;let o=0;const a=t.byteLength>=is+4&&t.getUint32(is,!0)>0;for(;e.pc<i;){if(++o>r)return e.status=L.TIMEOUT,L.TIMEOUT;const u=e.pc,d=n[e.pc];switch(e.pc+=1,d){case m.OP_HALT:return e.arenaOffset=0,e.status=L.DONE,L.DONE;case m.OP_OPEN_CURSOR:{const h=n[e.pc],f=s.getUint32(e.pc+1,!0);e.pc+=5;const g=Ct(e,h);if(g.pageId=f,g.cellIdx=0,g.rowOffset=0,a&&f>0){const _=Vt(t,Gt,Ht,f);if(_<0)return e.fault_page_id=f,e.status=L.PAGE_FAULT,e.pc=u,L.PAGE_FAULT;g.slotIdx=_}break}case m.OP_REWIND:{const h=n[e.pc],f=s.getUint16(e.pc+1,!0);if(e.pc+=3,f>i)return e.status=L.INVALID_BYTECODE,L.INVALID_BYTECODE;const g=Ct(e,h);if(a&&g.pageId>0){const p=Vt(t,Gt,Ht,g.pageId);if(p<0)return e.fault_page_id=g.pageId,e.status=L.PAGE_FAULT,e.pc=u,L.PAGE_FAULT;g.slotIdx=p}const _=Xt(t,g.pageId);if(ft(t,_)===0)e.pc=f;else{g.cellIdx=0;const p=at(t,_,0);g.rowOffset=_+p}break}case m.OP_NEXT_ROW:{const h=n[e.pc],f=s.getUint16(e.pc+1,!0);if(e.pc+=3,f>i)return e.status=L.INVALID_BYTECODE,L.INVALID_BYTECODE;const g=Ct(e,h),_=Xt(t,g.pageId),I=ft(t,_),p=g.cellIdx+1;if(p<I){g.cellIdx=p;const y=at(t,_,g.cellIdx);g.rowOffset=_+y}else{const y=Ut(t,_);if(y!==0){if(a){const w=Vt(t,Gt,Ht,y);if(w<0)return e.fault_page_id=y,e.status=L.PAGE_FAULT,e.pc=u,L.PAGE_FAULT;g.slotIdx=w}g.pageId=y,g.cellIdx=0;const T=Xt(t,y);if(ft(t,T)>0){const w=at(t,T,0);g.rowOffset=T+w}else e.pc=f}else e.pc=f}break}case m.OP_LAST:{const h=n[e.pc],f=s.getUint16(e.pc+1,!0);if(e.pc+=3,f>i)return e.status=L.INVALID_BYTECODE,L.INVALID_BYTECODE;const g=Ct(e,h),_=Xt(t,g.pageId),I=ft(t,_);if(I===0)e.pc=f;else{g.cellIdx=I-1;const p=at(t,_,g.cellIdx);g.rowOffset=_+p}break}case m.OP_PREV_ROW:{const h=n[e.pc],f=s.getUint16(e.pc+1,!0);if(e.pc+=3,f>i)return e.status=L.INVALID_BYTECODE,L.INVALID_BYTECODE;const g=Ct(e,h),_=Xt(t,g.pageId);if(g.cellIdx>0){g.cellIdx--;const I=at(t,_,g.cellIdx);g.rowOffset=_+I}else e.pc=f;break}case m.OP_COLUMN_INT:{const h=n[e.pc],f=n[e.pc+1],g=n[e.pc+2];e.pc+=3;const _=Ct(e,h),I=(e.tables&&e.tables[h])??e.table,p=I.columns[f],y=Math.ceil(I.columns.length/8),T=_.rowOffset+3;if(tn(t,T,f)){e.registers[g]=null;break}const O=xn(t,T,y,I.columns,f);p.type===S.INT32?e.registers[g]=t.getInt32(O,!0):p.type===S.INT64&&(e.registers[g]=Number(t.getBigInt64(O,!0)));break}case m.OP_COLUMN_FLOAT:{const h=n[e.pc],f=n[e.pc+1],g=n[e.pc+2];e.pc+=3;const _=Ct(e,h),I=(e.tables&&e.tables[h])??e.table,p=Math.ceil(I.columns.length/8),y=_.rowOffset+3;if(tn(t,y,f)){e.registers[g]=null;break}const T=xn(t,y,p,I.columns,f);e.registers[g]=t.getFloat64(T,!0);break}case m.OP_COLUMN_UUID:case m.OP_COLUMN_ULID:case m.OP_COLUMN_TEXT:{const h=n[e.pc],f=n[e.pc+1],g=n[e.pc+2];e.pc+=3;const _=Ct(e,h),I=(e.tables&&e.tables[h])??e.table,p=Math.ceil(I.columns.length/8),y=_.rowOffset+3;if(tn(t,y,f)){e.registers[g]=null;break}if(I.columns[f].type===S.UUID||I.columns[f].type===S.ULID){const P=xn(t,y,p,I.columns,f),U=new Uint8Array(t.buffer,t.byteOffset+P,16);e.registers[g]=I.columns[f].type===S.UUID?fn.decode(U,0):An.decode(U,0);break}const T=xn(t,y,p,I.columns,I.columns.length);let O=0;for(let P=0;P<f;P++){const U=I.columns[P];(U.type===S.TEXT||U.type===S.BLOB)&&O++}const w=T+O*4,C=t.getUint16(w,!0),B=t.getUint16(w+2,!0);if(B===0)e.registers[g]="";else{const P=new Uint8Array(t.buffer,_.rowOffset+C,B);e.registers[g]=Po.decode(P)}break}case m.OP_COLUMN_BLOB:{const h=n[e.pc],f=n[e.pc+1],g=n[e.pc+2];e.pc+=3;const _=Ct(e,h),I=(e.tables&&e.tables[h])??e.table,p=Math.ceil(I.columns.length/8),y=_.rowOffset+3;if(tn(t,y,f)){e.registers[g]=null;break}const T=xn(t,y,p,I.columns,I.columns.length);let O=0;for(let U=0;U<f;U++){const Q=I.columns[U];(Q.type===S.TEXT||Q.type===S.BLOB)&&O++}const w=T+O*4,C=t.getUint16(w,!0),B=t.getUint16(w+2,!0),P=new Uint8Array(B);P.set(new Uint8Array(t.buffer,_.rowOffset+C,B)),e.registers[g]=P;break}case m.OP_OPEN_INDEX:{const h=n[e.pc],f=s.getUint32(e.pc+1,!0);e.pc+=5;const g=Ct(e,h);if(g.pageId=f,g.rootPageId=f,g.cellIdx=0,g.rowOffset=0,a&&f>0){const _=Vt(t,Gt,Ht,f);if(_<0)return e.fault_page_id=f,e.status=L.PAGE_FAULT,e.pc=u,L.PAGE_FAULT;g.slotIdx=_}break}case m.OP_INDEX_SEEK_EQ:{const h=n[e.pc],f=n[e.pc+1],g=n[e.pc+2],_=n[e.pc+3],I=s.getUint16(e.pc+4,!0);if(e.pc+=6,I>i)return e.status=L.INVALID_BYTECODE,L.INVALID_BYTECODE;const p=e.registers[g];if(p==null){e.pc=I;break}const y=Ct(e,h);let T=y.rootPageId||y.pageId,O=!1,w=0n;for(;T!==0;){if(a&&T>0){const P=Vt(t,Gt,Ht,T);if(P<0)return e.fault_page_id=T,e.status=L.PAGE_FAULT,e.pc=u,L.PAGE_FAULT;y.slotIdx=P}const C=Xt(t,T),B=Vn(t,C,_,p);if(B.found){O=!0,y.pageId=T,y.cellIdx=B.slot_idx;const P=at(t,C,B.slot_idx),U=t.getUint16(C+P,!0);w=t.getBigInt64(C+P+2+U,!0);break}T=Ut(t,C)}if(!O)e.pc=I;else{const C=Number(w>>16n),B=Number(w&0xffffn);if(a&&C>0&&Vt(t,Gt,Ht,C)<0)return e.fault_page_id=C,e.status=L.PAGE_FAULT,e.pc=u,L.PAGE_FAULT;const P=Ct(e,f);P.pageId=C,P.cellIdx=B;const U=Xt(t,C),Q=at(t,U,B);P.rowOffset=U+Q}break}case m.OP_INDEX_SEEK_GE:{const h=n[e.pc],f=n[e.pc+1],g=n[e.pc+2],_=n[e.pc+3],I=s.getUint16(e.pc+4,!0);if(e.pc+=6,I>i)return e.status=L.INVALID_BYTECODE,L.INVALID_BYTECODE;const p=e.registers[g];if(p==null){e.pc=I;break}const y=Ct(e,h);let T=y.rootPageId||y.pageId,O=!1,w=0n;for(;T!==0;){if(a&&T>0){const U=Vt(t,Gt,Ht,T);if(U<0)return e.fault_page_id=T,e.status=L.PAGE_FAULT,e.pc=u,L.PAGE_FAULT;y.slotIdx=U}const C=Xt(t,T),B=ft(t,C),P=Vn(t,C,_,p);if(P.found||P.slot_idx<B){O=!0,y.pageId=T,y.cellIdx=P.slot_idx;const U=at(t,C,P.slot_idx),Q=t.getUint16(C+U,!0);w=t.getBigInt64(C+U+2+Q,!0);break}T=Ut(t,C)}if(!O)e.pc=I;else{const C=Number(w>>16n),B=Number(w&0xffffn);if(a&&C>0&&Vt(t,Gt,Ht,C)<0)return e.fault_page_id=C,e.status=L.PAGE_FAULT,e.pc=u,L.PAGE_FAULT;const P=Ct(e,f);P.pageId=C,P.cellIdx=B;const U=Xt(t,C),Q=at(t,U,B);P.rowOffset=U+Q}break}case m.OP_INDEX_NEXT:{const h=n[e.pc],f=n[e.pc+1],g=s.getUint16(e.pc+2,!0);if(e.pc+=4,g>i)return e.status=L.INVALID_BYTECODE,L.INVALID_BYTECODE;const _=Ct(e,h);let I=_.pageId,p=Xt(t,I);const y=ft(t,p);let T=_.cellIdx+1;if(T>=y){if(I=Ut(t,p),I===0){e.pc=g;break}if(a&&I>0){const A=Vt(t,Gt,Ht,I);if(A<0)return e.fault_page_id=I,e.status=L.PAGE_FAULT,e.pc=u,L.PAGE_FAULT;_.slotIdx=A}p=Xt(t,I),T=0,_.pageId=I,_.cellIdx=-1}const O=at(t,p,T),w=t.getUint16(p+O,!0),C=t.getBigInt64(p+O+2+w,!0),B=Number(C>>16n),P=Number(C&0xffffn);if(a&&B>0&&Vt(t,Gt,Ht,B)<0)return e.fault_page_id=B,e.status=L.PAGE_FAULT,e.pc=u,L.PAGE_FAULT;_.pageId=I,_.cellIdx=T;const U=Ct(e,f);U.pageId=B,U.cellIdx=P;const Q=Xt(t,B),R=at(t,Q,P);U.rowOffset=Q+R;break}case m.OP_IS_NULL:{const h=n[e.pc],f=n[e.pc+1],g=s.getUint16(e.pc+2,!0);if(e.pc+=4,g>i)return e.status=L.INVALID_BYTECODE,L.INVALID_BYTECODE;const I=Ct(e,h).rowOffset+3;tn(t,I,f)&&(e.pc=g);break}case m.OP_IS_NOT_NULL:{const h=n[e.pc],f=n[e.pc+1],g=s.getUint16(e.pc+2,!0);if(e.pc+=4,g>i)return e.status=L.INVALID_BYTECODE,L.INVALID_BYTECODE;const I=Ct(e,h).rowOffset+3;tn(t,I,f)||(e.pc=g);break}case m.OP_EQ:{const h=n[e.pc],f=n[e.pc+1],g=s.getUint16(e.pc+2,!0);if(e.pc+=4,g>i)return e.status=L.INVALID_BYTECODE,L.INVALID_BYTECODE;const _=mn(e.registers[h],e.registers[f]);!_.is_unknown&&_.result===0&&(e.pc=g);break}case m.OP_NE:{const h=n[e.pc],f=n[e.pc+1],g=s.getUint16(e.pc+2,!0);if(e.pc+=4,g>i)return e.status=L.INVALID_BYTECODE,L.INVALID_BYTECODE;const _=mn(e.registers[h],e.registers[f]);!_.is_unknown&&_.result!==0&&(e.pc=g);break}case m.OP_GT:{const h=n[e.pc],f=n[e.pc+1],g=s.getUint16(e.pc+2,!0);if(e.pc+=4,g>i)return e.status=L.INVALID_BYTECODE,L.INVALID_BYTECODE;const _=mn(e.registers[h],e.registers[f]);!_.is_unknown&&_.result>0&&(e.pc=g);break}case m.OP_GE:{const h=n[e.pc],f=n[e.pc+1],g=s.getUint16(e.pc+2,!0);if(e.pc+=4,g>i)return e.status=L.INVALID_BYTECODE,L.INVALID_BYTECODE;const _=mn(e.registers[h],e.registers[f]);!_.is_unknown&&_.result>=0&&(e.pc=g);break}case m.OP_LT:{const h=n[e.pc],f=n[e.pc+1],g=s.getUint16(e.pc+2,!0);if(e.pc+=4,g>i)return e.status=L.INVALID_BYTECODE,L.INVALID_BYTECODE;const _=mn(e.registers[h],e.registers[f]);!_.is_unknown&&_.result<0&&(e.pc=g);break}case m.OP_LE:{const h=n[e.pc],f=n[e.pc+1],g=s.getUint16(e.pc+2,!0);if(e.pc+=4,g>i)return e.status=L.INVALID_BYTECODE,L.INVALID_BYTECODE;const _=mn(e.registers[h],e.registers[f]);!_.is_unknown&&_.result<=0&&(e.pc=g);break}case m.OP_JUMP:{const h=s.getUint16(e.pc,!0);if(h>i)return e.status=L.INVALID_BYTECODE,L.INVALID_BYTECODE;e.pc=h;break}case m.OP_STR_LIKE:{const h=n[e.pc],f=n[e.pc+1],g=s.getUint16(e.pc+2,!0);if(e.pc+=4,g>i)return e.status=L.INVALID_BYTECODE,L.INVALID_BYTECODE;const _=e.registers[h],I=e.registers[f];if(_===null||I===null)break;ze(String(_),String(I))&&(e.pc=g);break}case m.OP_STR_NOT_LIKE:{const h=n[e.pc],f=n[e.pc+1],g=s.getUint16(e.pc+2,!0);if(e.pc+=4,g>i)return e.status=L.INVALID_BYTECODE,L.INVALID_BYTECODE;const _=e.registers[h],I=e.registers[f];if(_===null||I===null)break;ze(String(_),String(I))||(e.pc=g);break}case m.OP_STR_CONTAINS:{const h=n[e.pc],f=n[e.pc+1],g=s.getUint16(e.pc+2,!0);if(e.pc+=4,g>i)return e.status=L.INVALID_BYTECODE,L.INVALID_BYTECODE;const _=e.registers[h],I=e.registers[f];if(_===null||I===null)break;String(_).includes(String(I))&&(e.pc=g);break}case m.OP_STR_STARTS_WITH:{const h=n[e.pc],f=n[e.pc+1],g=s.getUint16(e.pc+2,!0);if(e.pc+=4,g>i)return e.status=L.INVALID_BYTECODE,L.INVALID_BYTECODE;const _=e.registers[h],I=e.registers[f];if(_===null||I===null)break;String(_).startsWith(String(I))&&(e.pc=g);break}case m.OP_STR_ENDS_WITH:{const h=n[e.pc],f=n[e.pc+1],g=s.getUint16(e.pc+2,!0);if(e.pc+=4,g>i)return e.status=L.INVALID_BYTECODE,L.INVALID_BYTECODE;const _=e.registers[h],I=e.registers[f];if(_===null||I===null)break;String(_).endsWith(String(I))&&(e.pc=g);break}case m.OP_IN:{const h=n[e.pc],f=s.getUint16(e.pc+1,!0),g=s.getUint16(e.pc+3,!0);if(e.pc+=5,g>i)return e.status=L.INVALID_BYTECODE,L.INVALID_BYTECODE;const _=e.registers[h];if(_==null)break;const I=(c=e.inSets)==null?void 0:c[f];I&&(I.has(_)||typeof _=="number"&&Number.isSafeInteger(_)&&I.has(BigInt(_))||typeof _=="bigint"&&I.has(Number(_)))&&(e.pc=g);break}case m.OP_LOAD_INT:{const h=n[e.pc],f=s.getInt32(e.pc+1,!0);e.pc+=5,e.registers[h]=f;break}case m.OP_LOAD_FLOAT:{const h=n[e.pc],f=s.getFloat64(e.pc+1,!0);e.pc+=9,e.registers[h]=f;break}case m.OP_LOAD_TEXT:{const h=n[e.pc],f=s.getUint16(e.pc+1,!0),g=new Uint8Array(n.buffer,n.byteOffset+e.pc+3,f);e.registers[h]=Po.decode(g),e.pc+=3+f;break}case m.OP_LOAD_BLOB:{const h=n[e.pc],f=s.getUint16(e.pc+1,!0),g=new Uint8Array(f);g.set(new Uint8Array(n.buffer,n.byteOffset+e.pc+3,f)),e.registers[h]=g,e.pc+=3+f;break}case m.OP_LOAD_NULL:{const h=n[e.pc];e.pc+=1,e.registers[h]=null;break}case m.OP_EMIT_ROW:{const h=n[e.pc];e.pc+=1;const f=Ct(e,h),g=t.getUint16(f.rowOffset+1,!0),_=new Uint8Array(t.buffer,t.byteOffset+f.rowOffset,g),I=Yi(e,t,_,u);if(I!==L.RUNNING)return I;break}case m.OP_OFFSET:{const h=n[e.pc],f=s.getUint16(e.pc+1,!0);if(e.pc+=3,f>i)return e.status=L.INVALID_BYTECODE,L.INVALID_BYTECODE;const g=Number(e.registers[h]??0);g>0&&(e.registers[h]=g-1,e.pc=f);break}case m.OP_LIMIT:{const h=n[e.pc],f=s.getUint16(e.pc+1,!0);if(e.pc+=3,f>i)return e.status=L.INVALID_BYTECODE,L.INVALID_BYTECODE;const g=Number(e.registers[h]??0);g<=1?(e.registers[h]=0,e.pc=f):e.registers[h]=g-1;break}case m.OP_CALL_UDF:{const h=s.getUint16(e.pc,!0),f=n[e.pc+2],g=n[e.pc+3],_=n[e.pc+4];e.pc+=5;const I=(l=e.udfs)==null?void 0:l[h];if(!I)return e.status=L.INVALID_BYTECODE,L.INVALID_BYTECODE;const p=[];for(let y=0;y<g;y++)p.push(e.registers[f+y]);try{const y=I(...p);e.registers[_]=y!==void 0?y:null}catch{return e.status=L.ERROR,L.ERROR}break}case m.OP_STR_LOWER:{const h=n[e.pc],f=n[e.pc+1];e.pc+=2;const g=e.registers[h];e.registers[f]=g!==null?String(g).toLowerCase():null;break}case m.OP_STR_UPPER:{const h=n[e.pc],f=n[e.pc+1];e.pc+=2;const g=e.registers[h];e.registers[f]=g!==null?String(g).toUpperCase():null;break}case m.OP_STR_LENGTH:{const h=n[e.pc],f=n[e.pc+1];e.pc+=2;const g=e.registers[h];e.registers[f]=g!==null?String(g).length:null;break}case m.OP_STR_SUBSTR:{const h=n[e.pc],f=n[e.pc+1],g=n[e.pc+2],_=n[e.pc+3];e.pc+=4;const I=e.registers[h],p=e.registers[f],y=e.registers[g];if(I===null||p===null){e.registers[_]=null;break}const T=String(I),O=Math.max(0,Number(p)-1);if(y===null)e.registers[_]=T.slice(O);else{const w=Math.max(0,Number(y));e.registers[_]=T.slice(O,O+w)}break}case m.OP_STR_TRIM:{const h=n[e.pc],f=n[e.pc+1];e.pc+=2;const g=e.registers[h];e.registers[f]=g!=null?String(g).trim():null;break}case m.OP_MATH_ABS:{const h=n[e.pc],f=n[e.pc+1];e.pc+=2;const g=e.registers[h];e.registers[f]=g!=null?Math.abs(Number(g)):null;break}case m.OP_MATH_ROUND:{const h=n[e.pc],f=n[e.pc+1];e.pc+=2;const g=e.registers[h];e.registers[f]=g!=null?Math.round(Number(g)):null;break}case m.OP_RESULT_ROW:{const h=n[e.pc],f=n[e.pc+1];e.pc+=2;const g=ic(e,h,f),_=Yi(e,t,g,u);if(_!==L.RUNNING)return _;break}case m.OP_SORTER_OPEN:{const h=n[e.pc],f=n[e.pc+1];e.pc+=2;const g=e.keyInfos[f]??{numKeys:1,directions:[0],nullOrders:[0]},_=g.limit!==void 0&&g.limit>0?(g.offset??0)+g.limit:0,I=_>0&&_<=kr?_:0;e.sorters[h]={keyInfo:g,entries:[],readIdx:0,isSorted:!1,maxK:I};break}case m.OP_SORTER_INSERT:{const h=n[e.pc],f=n[e.pc+1],g=n[e.pc+2],_=n[e.pc+3];e.pc+=4;const I=e.sorters[h];if(!I)return e.status=L.INVALID_BYTECODE,L.INVALID_BYTECODE;const p=I.maxK??0;if(p>0&&I.entries.length>=p){if(g===1){const C=e.registers[f],B=I.entries[0].keys[0],P=I.keyInfo.directions[0]??0;if(typeof C=="number"&&typeof B=="number"){if(P===0?C>=B:C<=B)break}else if(typeof C=="string"&&typeof B=="string"){if(P===0?C>=B:C<=B)break}else if(wo(e.registers,f,I.entries[0].keys,I.keyInfo)>=0)break}else if(wo(e.registers,f,I.entries[0].keys,I.keyInfo)>=0)break}const y=Ct(e,_),T=t.getUint16(y.rowOffset+1,!0),O=new Array(g);for(let C=0;C<g;C++)O[C]=e.registers[f+C];const w=sc(e,I,O,y.rowOffset,T,t,p);if(w!==L.RUNNING)return w;break}case m.OP_SORTER_SORT:{const h=n[e.pc];e.pc+=1;const f=e.sorters[h];if(!f)return e.status=L.INVALID_BYTECODE,L.INVALID_BYTECODE;nc(f),f.isSorted=!0;break}case m.OP_SORTER_NEXT:{const h=n[e.pc],f=s.getUint16(e.pc+1,!0);if(e.pc+=3,f>i)return e.status=L.INVALID_BYTECODE,L.INVALID_BYTECODE;const g=e.sorters[h];if(!g)return e.status=L.INVALID_BYTECODE,L.INVALID_BYTECODE;const _=g.keyInfo.limit!==void 0?(g.keyInfo.offset??0)+g.keyInfo.limit:g.entries.length;if(g.readIdx>=Math.min(g.entries.length,_))break;const I=g.entries[g.readIdx],p=I.rowData??new Uint8Array(t.buffer,t.byteOffset+I.rowOffset,I.rowLen),y=Yi(e,t,p,u);if(y!==L.RUNNING)return y;g.readIdx++,e.pc=f;break}case m.OP_MATH_FLOOR:{const h=n[e.pc],f=n[e.pc+1];e.pc+=2;const g=e.registers[h];e.registers[f]=g!=null?Math.floor(Number(g)):null;break}case m.OP_MATH_CEIL:{const h=n[e.pc],f=n[e.pc+1];e.pc+=2;const g=e.registers[h];e.registers[f]=g!=null?Math.ceil(Number(g)):null;break}case m.OP_ADD:{const h=n[e.pc],f=n[e.pc+1],g=n[e.pc+2];e.pc+=3;const _=e.registers[h],I=e.registers[f];_==null||I===null||I===void 0?e.registers[g]=null:e.registers[g]=Number(_)+Number(I);break}case m.OP_SUB:{const h=n[e.pc],f=n[e.pc+1],g=n[e.pc+2];e.pc+=3;const _=e.registers[h],I=e.registers[f];_==null||I===null||I===void 0?e.registers[g]=null:e.registers[g]=Number(_)-Number(I);break}case m.OP_MUL:{const h=n[e.pc],f=n[e.pc+1],g=n[e.pc+2];e.pc+=3;const _=e.registers[h],I=e.registers[f];_==null||I===null||I===void 0?e.registers[g]=null:e.registers[g]=Number(_)*Number(I);break}case m.OP_DIV:{const h=n[e.pc],f=n[e.pc+1],g=n[e.pc+2];e.pc+=3;const _=e.registers[h],I=e.registers[f];if(_==null||I===null||I===void 0)e.registers[g]=null;else{const p=Number(I);e.registers[g]=p===0?null:Number(_)/p}break}case m.OP_MOD:{const h=n[e.pc],f=n[e.pc+1],g=n[e.pc+2];e.pc+=3;const _=e.registers[h],I=e.registers[f];if(_==null||I===null||I===void 0)e.registers[g]=null;else{const p=Number(I);e.registers[g]=p===0?null:Number(_)%p}break}case m.OP_STR_CONCAT:{const h=n[e.pc],f=n[e.pc+1],g=n[e.pc+2];e.pc+=3;let _="",I=!1;for(let p=0;p<f;p++){const y=e.registers[h+p];y!=null&&(I=!0,_+=String(y))}e.registers[g]=I?_:null;break}case m.OP_COALESCE:{const h=n[e.pc],f=n[e.pc+1],g=n[e.pc+2];e.pc+=3;let _=null;for(let I=0;I<f;I++){const p=e.registers[h+I];if(p!=null){_=p;break}}e.registers[g]=_;break}case m.OP_COPY:{const h=n[e.pc],f=n[e.pc+1];e.pc+=2,e.registers[f]=e.registers[h];break}case m.OP_AGG_INIT:{const h=n[e.pc],f=n[e.pc+1],g=n[e.pc+2],_=n[e.pc+3];if(e.pc+=4,_===0){if(e.arenaOffset+40960>e.maxQueryMemory)return e.status=L.ARENA_EXHAUSTED,L.ARENA_EXHAUSTED;e.arenaOffset+=40960;const y=So(1024);if(g===0){const T=Fs([]),O=T%1024;y[O].hash=T,y[O].keys=[],y[O].count=0,y[O].sum=0,y[O].min_val=1/0,y[O].max_val=-1/0,y[O].has_val=!1}e.aggregators[h]={mode:0,startKeyReg:f,numKeys:g,capacity:1024,occupiedCount:g===0?1:0,readIdx:0,buckets:y}}else e.aggregators[h]={mode:1,startKeyReg:f,numKeys:g,capacity:1,occupiedCount:0,readIdx:0,buckets:[]};break}case m.OP_AGG_STEP:{const h=n[e.pc],f=n[e.pc+1],g=n[e.pc+2],_=n[e.pc+3],I=n[e.pc+4];e.pc+=5;const p=e.aggregators[h];if(!p)return e.status=L.INVALID_BYTECODE,L.INVALID_BYTECODE;const y=[];for(let O=0;O<g;O++)y.push(e.registers[f+O]);const T=_===255?null:e.registers[_];if(p.mode===0){const O=Fs(y),w=O%p.capacity;let C=null;for(let B=0;B<p.capacity;B++){const P=(w+B)%p.capacity,U=p.buckets[P];if(U.hash===0){U.hash=O,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++,C=U;break}else if(U.hash===O&&ec(U.keys,y)){C=U;break}}if(!C)return e.status=L.ARENA_EXHAUSTED,L.ARENA_EXHAUSTED;if(I===0)(_===255||T!=null)&&C.count++;else if(I===1||I===2)T!=null&&(C.sum+=Number(T),C.has_val=!0);else if(I===3){if(T!=null){const B=Number(T);(!C.has_val||B<C.min_val)&&(C.min_val=B),C.has_val=!0}}else if(I===4&&T!=null){const B=Number(T);(!C.has_val||B>C.max_val)&&(C.max_val=B),C.has_val=!0}if(p.occupiedCount>.7*p.capacity){const P=p.capacity*2,U=P*40;if(e.arenaOffset+U>e.maxQueryMemory)return e.status=L.ARENA_EXHAUSTED,L.ARENA_EXHAUSTED;e.arenaOffset+=U;const Q=p.buckets,R=So(P);for(let A=0;A<Q.length;A++){const b=Q[A];if(b.hash!==0){const k=b.hash%P;for(let V=0;V<P;V++){const j=(k+V)%P;if(R[j].hash===0){R[j]=b;break}}}}p.capacity=P,p.buckets=R}}break}case m.OP_AGG_NEXT:{const h=n[e.pc],f=n[e.pc+1],g=n[e.pc+2],_=s.getUint16(e.pc+3,!0);if(e.pc+=5,_>i)return e.status=L.INVALID_BYTECODE,L.INVALID_BYTECODE;const I=e.aggregators[h];if(!I)return e.status=L.INVALID_BYTECODE,L.INVALID_BYTECODE;for(;I.readIdx<I.buckets.length&&I.buckets[I.readIdx].hash===0;)I.readIdx++;if(I.readIdx>=I.buckets.length)break;const p=I.buckets[I.readIdx++];for(let y=0;y<p.keys.length;y++)e.registers[f+y]=p.keys[y];e.registers[g]=p.sum,e.registers[g+1]=p.count,e.registers[g+2]=p.has_val?p.min_val:null,e.registers[g+3]=p.has_val?p.max_val:null,e.pc=_;break}case m.OP_AGG_FINAL:{const h=n[e.pc],f=n[e.pc+1],g=n[e.pc+2],_=n[e.pc+3];e.pc+=4;const I=e.registers[h],p=Number(e.registers[f]??0);_===0?e.registers[g]=p:_===1?e.registers[g]=p>0?Number(I):null:_===2?e.registers[g]=p>0?Number(I)/p:null:(_===3||_===4)&&(e.registers[g]=e.registers[h]);break}case m.OP_REG_IS_NULL:{const h=n[e.pc],f=s.getUint16(e.pc+1,!0);if(e.pc+=3,f>i)return e.status=L.INVALID_BYTECODE,L.INVALID_BYTECODE;const g=e.registers[h];g==null&&(e.pc=f);break}case m.OP_REG_IS_NOT_NULL:{const h=n[e.pc],f=s.getUint16(e.pc+1,!0);if(e.pc+=3,f>i)return e.status=L.INVALID_BYTECODE,L.INVALID_BYTECODE;const g=e.registers[h];g!=null&&(e.pc=f);break}default:return e.status=L.INVALID_BYTECODE,L.INVALID_BYTECODE}}return e.status=L.DONE,L.DONE}const rc=new TextDecoder,bo=new Uint8Array([87,69,66,68,66,0]),No=new Uint32Array(256);let Lo=0;function oc(){if(!Lo){for(let e=0;e<256;e++){let t=e;for(let n=0;n<8;n++)t=t&1?3988292384^t>>>1:t>>>1;No[e]=t>>>0}Lo=1}}function Zi(e,t=0){oc();let n=4294967295;for(let s=0;s<4096;s++){const i=s>=28&&s<=31?0:e.getUint8(t+s);n=No[(n^i)&255]^n>>>8}return(n^4294967295)>>>0}function Bo(e,t=0){xt(e,t,0,4096),e.setUint8(t+Ie+0,87),e.setUint8(t+Ie+1,69),e.setUint8(t+Ie+2,66),e.setUint8(t+Ie+3,68),e.setUint8(t+Ie+4,66),e.setUint8(t+Ie+5,0),e.setUint16(t+ei,4096,!0),e.setUint16(t+ni,cs,!0),e.setUint16(t+si,Qr,!0),e.setUint32(t+re,1,!0),e.setUint32(t+fe,0,!0),e.setUint32(t+pe,1,!0),e.setUint32(t+ye,0,!0),e.setUint32(t+Te,0,!0),e.setUint32(t+Ge,0,!0),e.setUint32(t+qe,0,!0);const n=Zi(e,t);e.setUint32(t+Te,n,!0)}function Yn(e,t=!1){for(let u=0;u<bo.length;u++)if(e.getUint8(Ie+u)!==bo[u])throw new Gn("Invalid database file: magic bytes mismatch");const n=e.getUint16(ei,!0),s=e.getUint16(ni,!0),i=e.getUint16(si,!0),r=e.getUint32(re,!0),o=e.getUint32(fe,!0),a=e.getUint32(pe,!0),c=e.getUint32(ye,!0),l=e.getUint32(Te,!0);if(i>cs)throw new xr(`Database file format requires engine version >= ${i}, but running engine is version ${cs}`);if(t&&l!==0){const u=Zi(e,0);if(u!==l)throw new Pe(1,l,u)}return{pageSize:n,fileFormatVersion:s,minReadVersion:i,totalPages:r,freePageHead:o,schemaVersion:a,changeCounter:c,storedChecksum:l}}function Ro(e,t=0){return e.getUint32(t+re,!0)}function ac(e,t,n){n===void 0&&(n=t,t=0),e.setUint32(t+re,n,!0)}function lc(e,t=0){return e.getUint32(t+fe,!0)}function cc(e,t,n){n===void 0&&(n=t,t=0),e.setUint32(t+fe,n,!0)}function Fo(e,t=0){return e.getUint32(t+pe,!0)}function en(e,t=0){const n=Fo(e,t)+1;return e.setUint32(t+pe,n,!0),n}function Do(e,t=0){return e.getUint32(t+ye,!0)}function oe(e,t=0){const n=Do(e,t)+1;return e.setUint32(t+ye,n,!0),n}function Yt(e,t=0){e.setUint32(t+Te,0,!0);const n=Zi(e,t);return e.setUint32(t+Te,n,!0),n}function Ds(e,t,n,s){let i=0;for(;i<s&&i<Is(n);i++)e.setUint8(t+i,n.charCodeAt(i));for(;i<s;i++)e.setUint8(t+i,0)}function Qs(e,t,n){const s=[];for(let i=0;i<n;i++){const r=e.getUint8(t+i);if(r===0)break;s.push(r)}return rc.decode(new Uint8Array(s))}function Qo(e){switch(e.toUpperCase()){case"INT32":return S.INT32;case"INT64":return S.INT64;case"FLOAT64":return S.FLOAT64;case"TEXT":return S.TEXT;case"BLOB":return S.BLOB;case"UUID":return S.UUID;case"ULID":return S.ULID;default:throw new Error(`Unsupported column data type: "${e}"`)}}const nn=31,uc=1,fc=2;function ae(e,t,n){var i;if(t<=1)return e;if(n){const r=n.getPageBytes(t);if(r&&r.byteLength>=4096)return new DataView(r.buffer,r.byteOffset,4096)}const s=(i=e.buffer)==null?void 0:i.__webdbPool;if(s&&typeof s.getResidentSlot=="function"){const r=s.getResidentSlot(t);if(r!==-1)return s.getSlotDataView(r)}return e.buffer.byteLength>=t*4096?new DataView(e.buffer,(t-1)*4096,4096):null}function Le(e,t,n,s){var a;const i=new Uint8Array(n.buffer,n.byteOffset,4096),r=be(i);n.setUint32(12,r,!0),s!=null&&s.markPageDirty&&s.markPageDirty(t);const o=(a=e.buffer)==null?void 0:a.__webdbPool;if(o&&typeof o.getResidentSlot=="function"){const c=o.getResidentSlot(t);c!==-1&&o.markDirty(c)}}function In(e,t){let n=ee,s=e.getUint32(Ge,!0);for(;s!==0;){const i=ae(e,s,t);if(!i)break;n+=nn,s=i.getUint32(8,!0)}return n}function vs(e,t,n){if(t<0)return null;if(t<ee)return{view:e,offset:ns+t*we,pageId:1};const s=t-ee,i=Math.floor(s/nn),r=s%nn;let o=e.getUint32(Ge,!0);for(let c=0;c<i;c++){if(o===0)return null;const l=ae(e,o,n);if(!l)return null;o=l.getUint32(8,!0)}if(o===0)return null;const a=ae(e,o,n);return a?{view:a,offset:Fn+r*we,pageId:o}:null}function vo(e,t,n){const s=In(e,n),i=ae(e,t,n);if(!i)return-1;Gs(i,0,0,s,0),i.setUint8(1,uc),Le(e,t,i,n);const r=e.getUint32(Ge,!0);if(r===0)e.setUint32(Ge,t,!0);else{let o=r;for(;o!==0;){const a=ae(e,o,n);if(!a)break;const c=a.getUint32(8,!0);if(c===0){a.setUint32(8,t,!0),Le(e,o,a,n);break}o=c}}return s}function qt(e,t,n){const s=vs(e,t,n);if(!s)return null;const{view:i,offset:r}=s,o=i.getUint16(r+0,!0);if(o===0)return null;const a=i.getUint16(r+2,!0),c=i.getUint32(r+4,!0),l=i.getUint32(r+8,!0),u=Qs(i,r+12,ie),d=i.getUint32(r+76,!0),h=i.getUint32(r+80,!0),f=i.getBigUint64(r+84,!0),g=i.getUint32(r+92,!0),_=i.getUint8(r+96),I=i.getUint8(r+97),p=[];for(let y=0;y<8;y++)p.push(i.getUint16(r+98+y*2,!0));return{tableId:o,columnCount:a,rootPageId:c,colCatalogPageId:l,name:u,flags:d,rowCountEstimate:h,autoIncNext:f,pkRootPageId:g>0?g:void 0,pkColumnCount:g>0?_:void 0,pkFlags:g>0?I:void 0,pkColumnIndices:g>0?p:void 0}}function sn(e,t,n,s){var l;const i=vs(e,t,s);if(!i)throw new Error(`Invalid table descriptor slot ${t}`);const{view:r,offset:o,pageId:a}=i;if(r.setUint16(o+0,n.tableId,!0),r.setUint16(o+2,n.columnCount,!0),r.setUint32(o+4,n.rootPageId,!0),r.setUint32(o+8,n.colCatalogPageId,!0),Ds(r,o+12,n.name,ie),r.setUint32(o+76,n.flags,!0),r.setUint32(o+80,n.rowCountEstimate,!0),r.setBigUint64(o+84,n.autoIncNext,!0),new Uint8Array(r.buffer,r.byteOffset).fill(0,o+92,o+we),n.pkRootPageId&&n.pkRootPageId>0){r.setUint32(o+92,n.pkRootPageId,!0),r.setUint8(o+96,n.pkColumnCount??1),r.setUint8(o+97,n.pkFlags??rt.PRIMARY|rt.UNIQUE);for(let u=0;u<8;u++)r.setUint16(o+98+u*2,((l=n.pkColumnIndices)==null?void 0:l[u])??0,!0)}a>1&&Le(e,a,r,s)}function ji(e){return e.pkRootPageId&&e.pkRootPageId>0&&e.pkColumnCount&&e.pkColumnCount>0&&(e.pkFlags??rt.PRIMARY|rt.UNIQUE)&rt.PRIMARY?{indexId:32768+e.tableId,tableId:e.tableId,rootPageId:e.pkRootPageId,columnCount:e.pkColumnCount,flags:e.pkFlags??rt.PRIMARY|rt.UNIQUE,columnIndices:e.pkColumnIndices?[...e.pkColumnIndices]:[0,0,0,0,0,0,0,0],colDirections:[0,0,0,0,0,0,0,0],name:`pk_${e.name}`}:null}function Ac(e,t,n){const s=Zt(e,t,n);return s!==-1?qt(e,s,n):null}function Zt(e,t,n){const s=In(e,n);for(let i=0;i<s;i++){const r=qt(e,i,n);if(r&&r.flags&xe.ACTIVE&&r.name===t)return i}return-1}function Ki(e,t=0,n){for(let s=0;s<ee;s++){const i=t+ns+s*we;if(e.getUint16(i,!0)===0)return s}if(t===0){const s=In(e,n);for(let i=ee;i<s;i++){const r=vs(e,i,n);if(r&&r.view.getUint16(r.offset,!0)===0)return i}}return-1}function pn(e,t){const n=[],s=In(e,t);for(let i=0;i<s;i++){const r=qt(e,i,t);r&&r.flags&xe.ACTIVE&&n.push(r)}return n}function Be(e,t){let n=Tn,s=e.getUint32(qe,!0);for(;s!==0;){const i=ae(e,s,t);if(!i)break;n+=nn,s=i.getUint32(8,!0)}return n}function ks(e,t,n){if(t<0)return null;if(t<Tn)return{view:e,offset:ss+t*Se,pageId:1};const s=t-Tn,i=Math.floor(s/nn),r=s%nn;let o=e.getUint32(qe,!0);for(let c=0;c<i;c++){if(o===0)return null;const l=ae(e,o,n);if(!l)return null;o=l.getUint32(8,!0)}if(o===0)return null;const a=ae(e,o,n);return a?{view:a,offset:Fn+r*Se,pageId:o}:null}function ko(e,t,n){const s=Be(e,n),i=ae(e,t,n);if(!i)return-1;Gs(i,0,0,s,0),i.setUint8(1,fc),Le(e,t,i,n);const r=e.getUint32(qe,!0);if(r===0)e.setUint32(qe,t,!0);else{let o=r;for(;o!==0;){const a=ae(e,o,n);if(!a)break;const c=a.getUint32(8,!0);if(c===0){a.setUint32(8,t,!0),Le(e,o,a,n);break}o=c}}return s}function yn(e,t,n){const s=ks(e,t,n);if(!s)return null;const{view:i,offset:r}=s,o=i.getUint16(r+0,!0);if(o===0)return null;const a=i.getUint16(r+2,!0),c=i.getUint32(r+4,!0),l=i.getUint8(r+8),u=i.getUint8(r+9),d=[];for(let g=0;g<8;g++)d.push(i.getUint16(r+10+g*2,!0));const h=[];for(let g=0;g<8;g++)h.push(i.getUint8(r+26+g));const f=Qs(i,r+34,ie);return{indexId:o,tableId:a,rootPageId:c,columnCount:l,flags:u,columnIndices:d,colDirections:h,name:f}}function Ji(e,t,n,s){const i=ks(e,t,s);if(!i)throw new Error(`Invalid index descriptor slot ${t}`);const{view:r,offset:o,pageId:a}=i;r.setUint16(o+0,n.indexId,!0),r.setUint16(o+2,n.tableId,!0),r.setUint32(o+4,n.rootPageId,!0),r.setUint8(o+8,n.columnCount),r.setUint8(o+9,n.flags);for(let l=0;l<8;l++)r.setUint16(o+10+l*2,n.columnIndices[l]??0,!0);for(let l=0;l<8;l++)r.setUint8(o+26+l,n.colDirections[l]??0);Ds(r,o+34,n.name,ie),new Uint8Array(r.buffer,r.byteOffset).fill(0,o+98,o+Se),a>1&&Le(e,a,r,s)}const Tn=8;function Mo(e,t=0,n){for(let s=0;s<Tn;s++){const i=t+ss+s*Se;if(e.getUint16(i+0,!0)===0)return s}if(t===0){const s=Be(e,n);for(let i=Tn;i<s;i++){const r=ks(e,i,n);if(r&&r.view.getUint16(r.offset,!0)===0)return i}}return-1}function Ms(e,t,n){const s=t.toLowerCase(),i=Be(e,n);for(let o=0;o<i;o++){const a=yn(e,o,n);if(a&&a.name.toLowerCase()===s)return{slotIdx:o,desc:a}}const r=In(e,n);for(let o=0;o<r;o++){const a=qt(e,o,n);if(a&&a.flags&xe.ACTIVE){const c=ji(a);if(c&&c.name.toLowerCase()===s)return{slotIdx:-(o+1),desc:c}}}return null}function le(e,t,n){const s=[];let i=!1;const r=t-1;let o=r>=0?qt(e,r,n):null;if((!o||o.tableId!==t)&&(o=pn(e,n).find(l=>l.tableId===t)??null),o&&o.flags&xe.ACTIVE){const c=ji(o);c&&(s.push(c),i=!0)}const a=Be(e,n);for(let c=0;c<a;c++){const l=yn(e,c,n);if(l&&l.tableId===t){if(i&&l.flags&rt.PRIMARY)continue;s.push(l)}}return s}function Go(e,t){const n=[],s=pn(e,t),i=new Set;for(const o of s){i.add(o.tableId);const a=le(e,o.tableId,t);for(const c of a)n.push(c)}const r=Be(e,t);for(let o=0;o<r;o++){const a=yn(e,o,t);a&&!i.has(a.tableId)&&n.push(a)}return n}function zi(e,t,n){if(n===void 0&&(n=t,t=0),n<Tn){const s=t+ss+n*Se;return xt(e,s,0,Se),0}if(t===0){const s=ks(e,n);return s?(xt(s.view,s.offset,0,Se),s.pageId>1&&Le(e,s.pageId,s.view),0):-1}return-1}function qo(e,t,n){if(n===void 0&&(n=t,t=0),n<ee){const s=t+ns+n*we;return xt(e,s,0,we),0}if(t===0){const s=vs(e,n);return s?(xt(s.view,s.offset,0,we),s.pageId>1&&Le(e,s.pageId,s.view),0):-1}return-1}function Gs(e,t,n,s,i=0){xt(e,t,0,4096),e.setUint8(t+0,vn),e.setUint8(t+1,0),e.setUint16(t+2,0,!0),e.setUint16(t+4,n,!0),e.setUint16(t+6,s,!0),e.setUint32(t+8,i,!0),e.setUint32(t+12,0,!0)}function ge(e,t){return{pageType:e.getUint8(t+0),flags:e.getUint8(t+1),colCountInPage:e.getUint16(t+2,!0),tableId:e.getUint16(t+4,!0),startColIndex:e.getUint16(t+6,!0),nextColCatalogPageId:e.getUint32(t+8,!0),pageChecksum:e.getUint32(t+12,!0)}}function hc(e,t,n,s,i,r){e.setUint8(t+0,vn),e.setUint8(t+1,0),e.setUint16(t+2,n,!0),e.setUint16(t+4,s,!0),e.setUint16(t+6,i,!0),e.setUint32(t+8,r,!0)}function tr(e,t,n,s){if(n<0||n>=Ce)throw new Error(`Invalid catalog in-page slot ${n}`);const i=t+Fn+n*ri;e.setUint8(i+0,s.type),e.setUint8(i+1,s.flags),e.setUint16(i+2,s.colOffset,!0),Ds(e,i+4,s.name,ie),e.setUint32(i+68,0,!0)}function Wo(e,t,n){const s=t+Fn+n*ri,i=e.getUint8(s+0),r=e.getUint8(s+1),o=e.getUint16(s+2,!0),a=Qs(e,s+4,ie);return{type:i,flags:r,colOffset:o,name:a}}function Ho(e){return{pageChainIdx:Math.floor(e/Ce),colIdxInPage:e%Ce}}function Vo(e,t,n,s){var B,P,U,Q,R;if(s.length===0)throw new Error("Table must have at least one column");if(s.length>Ae)throw new Mn(s.length,Ae);if(Zt(e,n,t)!==-1)throw new gs(n);let i=Ki(e,0,t);if(i===-1){const A=t.allocateNewPage();if(!A||A<=1)throw new Ui(ee+1,ee);if(i=vo(e,A,t),i===-1)throw new Ui(ee+1,ee)}const r=i+1,o=t.allocateNewPage(),a=t.getPageBytes(o),c=new DataView(a.buffer,a.byteOffset);c.setUint8(0,13),c.setUint8(1,0),c.setUint16(2,0,!0),c.setUint16(4,4096,!0),c.setUint32(6,0,!0),c.setUint16(10,0,!0),c.setUint32(12,0,!0),t.markPageDirty(o);const l=[];let u=0;for(let A=0;A<s.length;A++){const b=s[A],k=typeof b.type=="string"?Qo(b.type):b.type;let V=0;typeof b.flags=="number"?V=b.flags:((b.primaryKey||(B=b.flags)!=null&&B.primaryKey)&&(V|=tt.PRIMARY_KEY),(b.notNull||(P=b.flags)!=null&&P.notNull)&&(V|=tt.NOT_NULL),(b.indexed||(U=b.flags)!=null&&U.indexed)&&(V|=tt.INDEXED),(b.autoInc||b.autoIncrement||(Q=b.flags)!=null&&Q.autoInc||(R=b.flags)!=null&&R.autoIncrement)&&(V|=tt.AUTO_INC));const j=u;switch(k){case S.INT32:u+=4;break;case S.INT64:case S.FLOAT64:u+=8;break;case S.UUID:case S.ULID:u+=16;break}l.push({type:k,flags:V,colOffset:j,name:b.name})}const d=l.length,h=Math.ceil(d/Ce),f=[];for(let A=0;A<h;A++)f.push(t.allocateNewPage());for(let A=0;A<h;A++){const b=f[A],k=A<h-1?f[A+1]:0,V=A*Ce,j=Math.min(d-V,Ce),K=t.getPageBytes(b),G=new DataView(K.buffer,K.byteOffset);Gs(G,0,r,V,k),G.setUint16(2,j,!0);for(let Rt=0;Rt<j;Rt++){const dt=l[V+Rt];tr(G,0,Rt,dt)}const q=be(K);G.setUint32(12,q,!0),t.markPageDirty(b)}const g=f[0],_=[];for(let A=0;A<l.length;A++)l[A].flags&tt.PRIMARY_KEY&&_.push(l[A]);let I=0,p=0,y=0;const T=[0,0,0,0,0,0,0,0];if(_.length>0){I=t.allocateNewPage();const A=t.getPageBytes(I),b=new DataView(A.buffer,A.byteOffset);Ls(b,0,0),t.markPageDirty(I),p=Math.min(_.length,8),y=rt.PRIMARY|rt.UNIQUE;for(let k=0;k<p;k++){const V=_[k].name;let j=0;for(let K=0;K<l.length;K++)if(l[K].name===V){j=K;break}T[k]=j}}const O={tableId:r,columnCount:d,rootPageId:o,colCatalogPageId:g,name:n,flags:xe.ACTIVE,rowCountEstimate:0,autoIncNext:1n,pkRootPageId:I>0?I:void 0,pkColumnCount:I>0?p:void 0,pkFlags:I>0?y:void 0,pkColumnIndices:I>0?T:void 0};sn(e,i,O,t),en(e),oe(e),Yt(e);const w=le(e,r,t),C=[];for(let A=0;A<_.length;A++)C.push(_[A].name);return{...O,columns:l,primaryKey:C.length>0?C:void 0,indexes:w.length>0?w:void 0}}function er(e,t,n){const s=Zt(e,n,t);if(s===-1)throw new kn(n);const i=qt(e,s,t),r=[];let o=i.colCatalogPageId,a=0;for(;o!==0&&a<i.columnCount;){const u=t.getPageBytes(o),d=new DataView(u.buffer,u.byteOffset),h=ge(d,0);for(let f=0;f<h.colCountInPage;f++){const g=Wo(d,0,f);r.push(g),a++}o=h.nextColCatalogPageId}const c=le(e,i.tableId,t),l=[];for(let u=0;u<r.length;u++)r[u].flags&tt.PRIMARY_KEY&&l.push(r[u].name);return{...i,columns:r,primaryKey:l.length>0?l:void 0,indexes:c.length>0?c:void 0}}function gc(e,t){const n=pn(e,t),s=[];for(let i=0;i<n.length;i++)s.push(er(e,t,n[i].name));return s}const nr="AGFzbQEAAAABcBFgAX8Bf2ACf38AYAJ/fwF/YAN/f38AYAN/f38Bf2AEf39/fwF/YAAAYAV/f39/fwF/YAN/f34Bf2ACf34Bf2ABfwBgBH9/f38AYAV/f39/fwBgBX9+f35/AGAFf3x/fH8AYAd/f39/f39/AGAAAX8CDwEDZW52Bm1lbW9yeQIAQwNIRwYAAAQAAwQDAgQFBAACAwcFAQECAwEAAQABAAEAAQABAAECAwAAAQABAQgJAQIAAAoAAQAAAAAAAwAAAgILDAACBQ0ODwUQBgkBfwFBgKCLAgsH2A1MD19fc3RhY2tfcG9pbnRlcgMAB2hleF92YWwAARBjcm9ja2ZvcmRfZGVjb2RlAAILdXVpZF9lbmNvZGUAAwZzdHJsZW4ABAt1dWlkX2RlY29kZQAFC3VsaWRfZW5jb2RlAAYLdWxpZF9kZWNvZGUABw9wYWdlX3RhYmxlX2hhc2gACA5wYWdlX3RhYmxlX2dldAAJDnBhZ2VfdGFibGVfc2V0AAoRcGFnZV90YWJsZV9kZWxldGUACxhidWZfcG9vbF9nZXRfc2xvdF9vZmZzZXQADBpidWZfcG9vbF9yZWFkX3Nsb3RfdG9fcGFnZQANG2J1Zl9wb29sX3dyaXRlX3Nsb3RfdG9fcGFnZQAOGmJ1Zl9wb29sX2dldF9yZXNpZGVudF9zbG90AAkUYnVmX3Bvb2xfYXNzaWduX3Nsb3QADxZidWZfcG9vbF91bmFzc2lnbl9zbG90ABATYnVmX3Bvb2xfbWFya19kaXJ0eQARFGJ1Zl9wb29sX2NsZWFyX2RpcnR5ABIRYnVmX3Bvb2xfaXNfZGlydHkAEwlwYWdlX2luaXQAFA5wYWdlX2luaXRfZnJlZQAVDXBhZ2VfZ2V0X3R5cGUAFg1wYWdlX3NldF90eXBlABcTcGFnZV9nZXRfY2VsbF9jb3VudAAYE3BhZ2Vfc2V0X2NlbGxfY291bnQAGRxwYWdlX2dldF9jZWxsX2NvbnRlbnRfb2Zmc2V0ABoccGFnZV9zZXRfY2VsbF9jb250ZW50X29mZnNldAAbFXBhZ2VfZ2V0X25leHRfcGFnZV9pZAAcFXBhZ2Vfc2V0X25leHRfcGFnZV9pZAAdE3BhZ2VfZ2V0X2ZyZWVfYnl0ZXMAHhNwYWdlX3NldF9mcmVlX2J5dGVzAB8RcGFnZV9nZXRfY2hlY2tzdW0AIBFwYWdlX3NldF9jaGVja3N1bQAhFHBhZ2VfZ2V0X2NlbGxfb2Zmc2V0ACIUcGFnZV9zZXRfY2VsbF9vZmZzZXQAIx5wYWdlX2dldF9jb250aWd1b3VzX2ZyZWVfc3BhY2UAJBlwYWdlX2dldF90b3RhbF9mcmVlX3NwYWNlACUMcGFnZV9jb21wYWN0ACYTcGFnZV9nZXRfcm93X2xlbmd0aAAnD3BhZ2VfZGVsZXRlX3JvdwAoEnBhZ2VfaW5pdF9pbnRlcmlvcgApHHBhZ2VfZ2V0X3JpZ2h0X2NoaWxkX3BhZ2VfaWQAHBxwYWdlX3NldF9yaWdodF9jaGlsZF9wYWdlX2lkAB0ZcGFnZV9pbnNlcnRfaW50ZXJpb3JfY2VsbAAqG3BhZ2VfYmluYXJ5X3NlYXJjaF9pbnRlcmlvcgArFHBhZ2VfaW5pdF9pbmRleF9sZWFmACwNY29tcHV0ZV9jcmMzMgAtFWNvbXB1dGVfcGFnZV9jaGVja3N1bQAuFmNvbXB1dGVfcGFnZTFfY2hlY2tzdW0ALxJjYXRhbG9nX2luaXRfcGFnZTEAMBdjYXRhbG9nX2dldF90b3RhbF9wYWdlcwAgF2NhdGFsb2dfc2V0X3RvdGFsX3BhZ2VzACEaY2F0YWxvZ19nZXRfZnJlZV9wYWdlX2hlYWQAMRpjYXRhbG9nX3NldF9mcmVlX3BhZ2VfaGVhZAAyGmNhdGFsb2dfZ2V0X3NjaGVtYV92ZXJzaW9uADMgY2F0YWxvZ19pbmNyZW1lbnRfc2NoZW1hX3ZlcnNpb24ANBpjYXRhbG9nX2dldF9jaGFuZ2VfY291bnRlcgA1IGNhdGFsb2dfaW5jcmVtZW50X2NoYW5nZV9jb3VudGVyADYdY2F0YWxvZ191cGRhdGVfcGFnZTFfY2hlY2tzdW0ANxpjYXRhbG9nX3dyaXRlX2ZpeGVkX3N0cmluZwA4HGNhdGFsb2dfZmluZF9mcmVlX3RhYmxlX3Nsb3QAORxjYXRhbG9nX2ZpbmRfZnJlZV9pbmRleF9zbG90ADofY2F0YWxvZ19kZWxldGVfaW5kZXhfZGVzY3JpcHRvcgA7H2NhdGFsb2dfZGVsZXRlX3RhYmxlX2Rlc2NyaXB0b3IAPBFjYXRhbG9nX2luaXRfcGFnZQA9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IAE7AAALCgAgAEEEai8AAAsMACAAQQRqIAE7AAALCgAgAEEGaigAAAsMACAAQQZqIAE2AAALCgAgAEEKai8AAAsMACAAQQpqIAE7AAALCgAgAEEMaigAAAsMACAAQQxqIAE2AAALEAAgACABQQF0akEQai8AAAsSACAAIAFBAXRqQRBqIAI7AAALHgAgAEEEai8AACAAQQJqLwAAQQF0a0EQa0H//wNxCycAIABBCmovAAAgAEEEai8AACAAQQJqLwAAQQF0a2pBEGtB//8DcQuBAgEHfyAAQQJqLwAAIgZFBEAgAEEKakEAOwAAIABBBGpBgCA7AAAPCyABQQAgACABRxtBACABQYBgTxsiAyAAKQAINwAIIAMgACkAADcAACADQRBqIQQgAEEBaiEIIABBEGohBUGAICEBA0AgBS8AACECIAECfyAALQAAQQpGBEAgACACaiIHLwAAQQpqDAELIAAgAmohByACIAhqLwAACyICayEBIAJB//8DcSICBEAgAyABQf//A3FqIAcgAvwKAAALIAQgATsAACAFQQJqIQUgBEECaiEEIAZBAWsiBg0ACyADQQpqQQA7AAAgA0EEaiABOwAAIAAgA0GAIPwKAAALCgAgAEEBai8AAAt0AQN/IABBAmovAAAiAiABSwRAIAAgACABQQF0akEQaiIDLwAAakEBai8AACEEAkAgAkEBayICIAFGDQAgAiABa0EBdCIBRQ0AIAMgA0ECaiAB/AoAAAsgAEECaiACOwAAIABBCmoiACAALwAAIARqOwAACws1ACAAQQU7AAAgAEEMakEANgAAIABBCmpBADsAACAAQQZqIAE2AAAgAEECakGAgICAATYAAAtsAQV/IABBAmoiBS8AACIDQaICTQR/IABBBGoiBi8AAEEMayIEIABqIgcgATYAACAHQQRqIAI3AAAgACADQQF0Qf7/A3FqQRBqIAQ7AAAgBiAEOwAAIAUgA0EBaiIAOwAAIABB//8DcQVBfwsLhwEBBn8CQCAAQQJqLwAAIgIEQCAAQRBqIQcgAkEBayEDQX8hAgNAIAMgBWoiBEEBdiEGAkAgACAHIARB/v8HcWovAABqIgRBBGo1AAAgAVkEQCAGQQFrIQMgBCgAACECDAELIAZBAWohBQsgAyAFTw0ACyACQX9HDQELIABBBmooAAAhAgsgAgs1ACAA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";let Zn=null;function $o(){if(!Zn){const e=globalThis.Buffer;if(typeof e<"u"&&typeof e.from=="function")Zn=new Uint8Array(e.from(nr,"base64"));else{const t=atob(nr),n=t.length;Zn=new Uint8Array(n);for(let s=0;s<n;s++)Zn[s]=t.charCodeAt(s)}}return Zn}function xo(e,t){const n=t??$o(),s=new WebAssembly.Module(n),i=new WebAssembly.Instance(s,{env:{memory:e}}),r=i.exports;r.__stack_pointer&&typeof r.__stack_pointer=="object"&&"value"in r.__stack_pointer&&(r.__stack_pointer.value=4378624);const o=(c,l=0)=>c.byteOffset+l;return{instance:i,exports:r,memory:e,page_init:(c,l,u=fs,d=0)=>{r.page_init(o(c,l),u,d)},page_init_free:(c,l,u=0)=>{r.page_init_free(o(c,l),u)},page_get_type:(c,l)=>r.page_get_type(o(c,l)),page_set_type:(c,l,u)=>{r.page_set_type(o(c,l),u)},page_get_cell_count:(c,l)=>r.page_get_cell_count(o(c,l)),page_set_cell_count:(c,l,u)=>{r.page_set_cell_count(o(c,l),u)},page_get_cell_content_offset:(c,l)=>r.page_get_cell_content_offset(o(c,l)),page_set_cell_content_offset:(c,l,u)=>{r.page_set_cell_content_offset(o(c,l),u)},page_get_next_page_id:(c,l)=>r.page_get_next_page_id(o(c,l)),page_set_next_page_id:(c,l,u)=>{r.page_set_next_page_id(o(c,l),u)},page_get_free_bytes:(c,l)=>r.page_get_free_bytes(o(c,l)),page_set_free_bytes:(c,l,u)=>{r.page_set_free_bytes(o(c,l),u)},page_get_checksum:(c,l)=>r.page_get_checksum(o(c,l)),page_set_checksum:(c,l,u)=>{r.page_set_checksum(o(c,l),u)},page_get_cell_offset:(c,l,u)=>r.page_get_cell_offset(o(c,l),u),page_set_cell_offset:(c,l,u,d)=>{r.page_set_cell_offset(o(c,l),u,d)},page_get_contiguous_free_space:(c,l)=>r.page_get_contiguous_free_space(o(c,l)),page_get_total_free_space:(c,l)=>r.page_get_total_free_space(o(c,l)),page_compact:(c,l,u=0,d)=>{d?Hn(c,l,u,d):r.page_compact(o(c,l),u,-1,0,0)},page_get_row_length:(c,l)=>r.page_get_row_length(o(c,l)),page_insert_row:(c,l,u,d=0)=>gn(c,l,u,d),page_delete_row:(c,l,u)=>{r.page_delete_row(o(c,l),u)},page_update_row:(c,l,u,d,h=0)=>ki(c,l,u,d,h),page_table_hash:(c,l)=>r.page_table_hash(c,l),page_table_get:(c,l,u,d)=>r.page_table_get(o(c,l),u,d),page_table_set:(c,l,u,d,h)=>{if(r.page_table_set(o(c,l),u,d,h)<0)throw new Error(`BufferPool page table full: cannot insert page ${d}`)},page_table_delete:(c,l,u,d)=>r.page_table_delete(o(c,l),u,d)!==0,buf_pool_get_slot_offset:c=>r.buf_pool_get_slot_offset(c),buf_pool_read_slot_to_page:(c,l,u)=>r.buf_pool_read_slot_to_page(o(c,l),u),buf_pool_write_slot_to_page:(c,l,u,d)=>{r.buf_pool_write_slot_to_page(o(c,l),u,d)},buf_pool_get_resident_slot:(c,l,u,d)=>r.buf_pool_get_resident_slot(o(c,l),u,d),buf_pool_assign_slot:(c,l,u,d,h,f)=>{r.buf_pool_assign_slot(o(c,l),o(c,u),d,h,f)},buf_pool_unassign_slot:(c,l,u,d,h)=>{r.buf_pool_unassign_slot(o(c,l),o(c,u),d,h)},buf_pool_mark_dirty:(c,l,u)=>{r.buf_pool_mark_dirty(o(c,l),u)},buf_pool_clear_dirty:(c,l,u)=>{r.buf_pool_clear_dirty(o(c,l),u)},buf_pool_is_dirty:(c,l,u)=>r.buf_pool_is_dirty(o(c,l),u)!==0,buf_pool_pin_slot:(c,l)=>{Vi(c,l)},buf_pool_unpin_slot:(c,l)=>{$i(c,l)},buf_pool_is_pinned:(c,l)=>_n(c,l),buf_pool_find_victim:(c,l,u,d,h,f)=>xi(c,l,u,d,h,f),buf_pool_select_eviction_victim:(c,l,u,d,h,f,g,_)=>Xi(c,l,u,d,h,f,g,_),catalog_init_page1:c=>{r.catalog_init_page1(o(c))},catalog_read_page1_header:(c,l)=>Yn(c,l),catalog_get_total_pages:c=>r.catalog_get_total_pages(o(c)),catalog_set_total_pages:(c,l)=>{r.catalog_set_total_pages(o(c),l)},catalog_get_free_page_head:c=>r.catalog_get_free_page_head(o(c)),catalog_set_free_page_head:(c,l)=>{r.catalog_set_free_page_head(o(c),l)},catalog_get_schema_version:c=>r.catalog_get_schema_version(o(c)),catalog_increment_schema_version:c=>r.catalog_increment_schema_version(o(c)),catalog_get_change_counter:c=>r.catalog_get_change_counter(o(c)),catalog_increment_change_counter:c=>r.catalog_increment_change_counter(o(c)),catalog_update_page1_checksum:c=>r.catalog_update_page1_checksum(o(c)),sql_like_match:(c,l)=>ze(c,l),fnv1a_32:c=>Fs(c),compare_sorter_keys:En,vm_step:Xn}}function Xo(e=We,t=He){const n=ai(e,t),s=n.transientArenaOffset+256*1024,i=Math.ceil(s/65536),r=Math.ceil((n.transientArenaOffset+t)/65536);return new WebAssembly.Memory({initial:i,maximum:Math.max(i,r)})}class Yo{constructor(t){N(this,"io");N(this,"wasmMemory");N(this,"buffer");N(this,"view");N(this,"uint8");N(this,"slotCount");N(this,"maxQueryMemory");N(this,"offsets");N(this,"slotsEndOffset");N(this,"slotToPageOffset");N(this,"pageToSlotOffset");N(this,"pageToSlotBuckets");N(this,"dirtyMaskOffset");N(this,"vmContextOffset");N(this,"resultBufferOffset");N(this,"bytecodeOffset");N(this,"pageScratchpadOffset");N(this,"transientArenaOffset");N(this,"pin_counts");N(this,"slot_dirty_generations");N(this,"ref_bits");N(this,"clock_hand",0);N(this,"arena_offset",0);N(this,"in_flight_acquires",new Map);N(this,"allocation_lock",Promise.resolve());var s,i,r;this.slotCount=t.slotCount??((s=t.pool)==null?void 0:s.slotCount)??We,this.maxQueryMemory=t.maxQueryMemory??((i=t.pool)==null?void 0:i.maxQueryMemory)??He;const n=t.memory??((r=t.pool)==null?void 0:r.wasmMemory);if(!n)throw new Error("BufferPoolDriver requires a valid WebAssembly.Memory (or pool with wasmMemory)");if(this.wasmMemory=n,this.buffer=this.wasmMemory.buffer,this.buffer.__webdbPool=this,this.view=new DataView(this.buffer),this.uint8=new Uint8Array(this.buffer),this.offsets=ai(t.useDefaultLayoutOffsets?We:this.slotCount,this.maxQueryMemory),this.slotsEndOffset=this.offsets.slotsEndOffset,this.slotToPageOffset=this.offsets.slotToPageOffset,this.pageToSlotOffset=this.offsets.pageToSlotOffset,this.pageToSlotBuckets=this.offsets.pageToSlotBuckets,this.dirtyMaskOffset=this.offsets.dirtyMaskOffset,this.vmContextOffset=this.offsets.vmContextOffset,this.resultBufferOffset=this.offsets.resultBufferOffset,this.bytecodeOffset=this.offsets.bytecodeOffset,this.pageScratchpadOffset=this.offsets.pageScratchpadOffset,this.transientArenaOffset=this.offsets.transientArenaOffset,this.ref_bits=new Uint8Array(this.slotCount),this.pin_counts=new Uint32Array(this.slotCount),this.slot_dirty_generations=new Uint32Array(this.slotCount),t.io)this.io=t.io;else if(t.vfs)this.io=new Li({vfs:t.vfs,memory:this.wasmMemory});else throw new Error("BufferPoolDriver requires either an Io instance or IVfsAdapter");xt(this.uint8,this.slotToPageOffset,0,this.slotCount*4),xt(this.uint8,this.pageToSlotOffset,0,this.pageToSlotBuckets*Ue),xt(this.uint8,this.dirtyMaskOffset,0,Math.ceil(this.slotCount/8)),this.assignSlot(0,1),this.pin_counts[0]=1}validate_slot_idx(t){if(!Number.isInteger(t)||t<0||t>=this.slotCount)throw new Error(`Invalid slot index: ${t}. Must be an integer between 0 and ${this.slotCount-1}`)}validate_page_id(t){if(!Number.isInteger(t)||t<=0)throw new Error(`Invalid page ID: ${t}. Page IDs must be positive integers.`)}async with_allocation_lock(t){const n=this.allocation_lock;let s;this.allocation_lock=new Promise(i=>{s=i}),await n;try{return await t()}finally{s()}}setTransactionCoordinator(t){this.io.setTransactionCoordinator(t)}getSlotOffset(t){return this.validate_slot_idx(t),t*4096}getPageBytesInSlot(t){return this.validate_slot_idx(t),this.uint8.subarray(t*4096,(t+1)*4096)}getSlotDataView(t){return this.validate_slot_idx(t),new DataView(this.buffer,t*4096,4096)}getResidentSlot(t){return this.validate_page_id(t),Vt(this.view,this.pageToSlotOffset,this.pageToSlotBuckets,t)}getAssignedPage(t){return this.validate_slot_idx(t),dn(this.view,this.slotToPageOffset,t)}assignSlot(t,n){if(this.validate_slot_idx(t),!Number.isInteger(n)||n<=0)throw new Error(`Invalid page ID: ${n}. Must be a positive integer >= 1`);if(t===0&&n!==1)throw new Error(`Cannot reassign slot 0: reserved permanently for page 1 (got page ${n})`);const s=this.getResidentSlot(n);if(s!==-1&&s!==t)throw new Error(`Cannot map page ${n} to slot ${t}: already resident in slot ${s}`);Io(this.view,this.slotToPageOffset,this.pageToSlotOffset,this.pageToSlotBuckets,t,n),this.ref_bits[t]=1}unassignSlot(t){if(this.validate_slot_idx(t),t===0)throw new Error("Cannot unassign slot 0: reserved permanently for page 1");po(this.view,this.slotToPageOffset,this.pageToSlotOffset,this.pageToSlotBuckets,t),this.ref_bits[t]=0}markDirty(t){this.validate_slot_idx(t),yo(this.uint8,this.dirtyMaskOffset,t),this.slot_dirty_generations[t]++}clearDirty(t){this.validate_slot_idx(t),To(this.uint8,this.dirtyMaskOffset,t)}isDirty(t){return this.validate_slot_idx(t),Hi(this.uint8,this.dirtyMaskOffset,t)}pinSlot(t){this.validate_slot_idx(t),Vi(this.pin_counts,t)}unpinSlot(t){this.validate_slot_idx(t),$i(this.pin_counts,t)}pinPage(t){this.validate_page_id(t);const n=this.getResidentSlot(t);if(n===-1)throw new Error(`Cannot pin page ${t}: page is not resident in buffer pool`);this.pinSlot(n)}unpinPage(t){if(this.validate_page_id(t),t===1)return;const n=this.getResidentSlot(t);n!==-1&&this.unpinSlot(n)}forceUnpinSlot(t){this.validate_slot_idx(t),t!==0&&(this.pin_counts[t]=0)}forceUnpinPage(t){if(this.validate_page_id(t),t<=1)return;const n=this.getResidentSlot(t);n!==-1&&this.forceUnpinSlot(n)}isSlotPinned(t){return this.validate_slot_idx(t),_n(this.pin_counts,t)}getPinCount(t){return this.validate_slot_idx(t),this.pin_counts[t]}getRefBit(t){return this.validate_slot_idx(t),this.ref_bits[t]}setRefBit(t,n){this.validate_slot_idx(t),this.ref_bits[t]=n?1:0}allocArena(t){const n=t+7&-8;if(this.arena_offset+n>this.maxQueryMemory)throw new Oi;const s=this.transientArenaOffset+this.arena_offset;return this.arena_offset+=n,s}resetArena(){this.arena_offset>0&&(xt(this.uint8,this.transientArenaOffset,0,this.arena_offset),this.arena_offset=0)}getArenaOffset(){return this.arena_offset}async acquirePage(t,n=!1){this.validate_page_id(t);const s=this.getResidentSlot(t);if(s!==-1)return this.setRefBit(s,1),n&&this.pinSlot(s),s;const i=this.in_flight_acquires.get(t);if(i){const o=await i;return n&&this.pinSlot(o),o}const r=(async()=>{const{candidate_slot:o,flush_page_id:a,next_clock_hand:c}=Xi(this.buffer,this.ref_bits,this.pin_counts,this.slotToPageOffset,this.dirtyMaskOffset,this.slotCount,this.clock_hand,t);this.clock_hand=c,this.pinSlot(o);try{return await this.io.resolvePageFault(o,t,a),this.assignSlot(o,t),this.setRefBit(o,1),this.clearDirty(o),o}catch(l){throw o!==-1&&this.unpinSlot(o),l}})();this.in_flight_acquires.set(t,r);try{const o=await r;return n||this.unpinSlot(o),o}finally{this.in_flight_acquires.delete(t)}}acquireAndPinPage(t){return this.acquirePage(t,!0)}async flushSlot(t){this.validate_slot_idx(t);const n=this.getAssignedPage(t);if(n===0)return;if(t===0&&n!==1)throw new Error(`Corruption detected: slot 0 is assigned to page ${n} instead of page 1`);const s=this.slot_dirty_generations[t];await this.io.writeSlot(t,n),this.slot_dirty_generations[t]===s&&this.clearDirty(t)}async flushPage(t){this.validate_page_id(t);const n=this.getResidentSlot(t);n!==-1&&this.isDirty(n)&&await this.flushSlot(n)}async flushAllDirty(){for(let t=0;t<this.slotCount;t++)this.isDirty(t)&&await this.flushSlot(t);await this.io.flush()}async allocatePage(t=!1){return this.with_allocation_lock(async()=>{const n=this.getSlotDataView(0),s=yt(n,fe),i=yt(n,re);if(s>0){if(s<=1||i>0&&s>i)throw new Pe(s,`Corrupted free_page_head pointer ${s} (totalPages: ${i})`);const c=await this.acquirePage(s,t),l=this.getSlotDataView(c),u=eo(l,Er);if(u!==$e)throw new Pe(s,`Expected free page type 0x00, got 0x${u.toString(16)}`);const d=yt(l,Ir);if(d===s||i>0&&d>i)throw new Pe(s,`Corrupted next_free_page_id pointer ${d} in free page ${s}`);return Tt(n,fe,d),this.markDirty(0),Wn(l,0),this.markDirty(c),s}const r=i+1;Tt(n,re,r),this.markDirty(0);const o=await this.acquirePage(r,t),a=this.getSlotDataView(o);return Wn(a,0),this.markDirty(o),r})}allocateAndPinPage(){return this.allocatePage(!0)}async freePage(t,n=!1){if(this.validate_page_id(t),t<=1)throw new Error(`Cannot free reserved database page ${t}`);return this.with_allocation_lock(async()=>{const s=this.getSlotDataView(0),i=yt(s,re);if(i>0&&t>i)throw new Error(`Cannot free page ${t} beyond total pages ${i}`);const r=this.getResidentSlot(t);if(r!==-1){if(n)this.forceUnpinSlot(r);else if(this.isSlotPinned(r))throw new Error(`Cannot free pinned/active database page ${t}`)}const o=await this.acquirePage(t,!0);try{const a=this.getSlotDataView(o),c=Xe(a,0);if(c===$e){if(this.unassignSlot(o),n)return;throw new Error(`Double-free detected: page ${t} is already marked free`)}if(!n&&c===vn)throw new Error(`Cannot free system catalog page ${t}`);const l=yt(s,fe);lo(a,0,l),xt(this.uint8,o*4096+te,0,4096-te),this.io.isInTransaction()?await this.io.spillOrWriteSlot(o,t):await this.flushSlot(o),this.unassignSlot(o),this.clearDirty(o),this.setRefBit(o,0),Tt(s,fe,t),this.markDirty(0)}finally{this.unpinSlot(o)}})}async stepVm(t,n){let s=Xn(t,this.view,n);for(;s===L.PAGE_FAULT;){const i=t.cursor.pageId;await this.acquirePage(i),t.status=L.RUNNING,s=Xn(t,this.view,n)}return s}}async function sr(e){var u;const t=await e.getWalFrameCount();if(t===0)return{frameCount:0,committedTxCount:0,abortedTxCount:0,replayedPageCount:0};const n=await e.readWalHeader();if(!n)return await e.truncateWal(0),{frameCount:0,committedTxCount:0,abortedTxCount:0,replayedPageCount:0};try{Cs(n,!0)}catch{return await e.truncateWal(0),{frameCount:0,committedTxCount:0,abortedTxCount:0,replayedPageCount:0}}const s=await e.readWalFrames(0,t),i=new Map,r=new Set;let o=0;for(const d of s){const h=Fi(d);if(!h.valid||!h.header)break;const{header:f}=h;if(f.frameSeq!==o+1)break;if(o++,i.has(f.txId)||i.set(f.txId,[]),f.frameType===os)r.add(f.txId);else if(f.frameType===rs||f.frameType===as){const g=new Uint8Array(d.buffer,d.byteOffset+Ve,4096),_=new Uint8Array(4096);_.set(g),i.get(f.txId).push({pageId:f.pageId,data:_,frameType:f.frameType})}}const a=new Map;let c=0,l=0;for(const[d,h]of i.entries())if(r.has(d)){c++;for(const f of h)f.pageId>0&&a.set(f.pageId,f.data)}else l++;if(a.size>0){const d=[];for(const[h,f]of a.entries())d.push({pageId:h,data:f});d.sort((h,f)=>h.pageId-f.pageId),await e.writePages(d)}return await((u=e.flush)==null?void 0:u.call(e)),await e.truncateWal(0),{frameCount:o,committedTxCount:c,abortedTxCount:l,replayedPageCount:a.size}}class Zo{constructor(t,n){N(this,"activeLease",null);N(this,"inFlightNonTxCount",0);N(this,"queue",[]);N(this,"leaseWaiters",[]);N(this,"nextLeaseId",1);N(this,"nextTxId",1);N(this,"crossTabLockName");N(this,"onSyncCrossTab");N(this,"releaseWebLock",null);this.crossTabLockName=t,this.onSyncCrossTab=n}hasWebLocks(){var t;return!!this.crossTabLockName&&typeof navigator<"u"&&typeof((t=navigator==null?void 0:navigator.locks)==null?void 0:t.request)=="function"}async acquireWebLock(){!this.hasWebLocks()||this.releaseWebLock||await new Promise(t=>{navigator.locks.request(this.crossTabLockName,{mode:"exclusive"},()=>new Promise(n=>{this.releaseWebLock=n,t()})).catch(()=>{t()})})}releaseCurrentWebLock(){if(this.releaseWebLock){const t=this.releaseWebLock;this.releaseWebLock=null,t()}}get isLeased(){return this.activeLease!==null}get currentLease(){return this.activeLease}async enqueue(t,n){if(this.activeLease&&n===this.activeLease.leaseId)return t();if(this.activeLease||this.leaseWaiters.length>0||this.hasWebLocks()&&this.inFlightNonTxCount>0)return new Promise((s,i)=>{this.queue.push(async()=>{this.inFlightNonTxCount++;try{this.hasWebLocks()&&this.inFlightNonTxCount===1&&(await this.acquireWebLock(),this.onSyncCrossTab&&await this.onSyncCrossTab());const r=await t();s(r)}catch(r){i(r)}finally{this.inFlightNonTxCount--,this.inFlightNonTxCount===0&&!this.activeLease&&this.releaseCurrentWebLock(),this.drain()}})});this.inFlightNonTxCount++;try{return this.hasWebLocks()&&this.inFlightNonTxCount===1&&(await this.acquireWebLock(),this.onSyncCrossTab&&await this.onSyncCrossTab()),await t()}finally{this.inFlightNonTxCount--,this.inFlightNonTxCount===0&&!this.activeLease&&this.releaseCurrentWebLock(),this.drain()}}async acquireExclusiveLease(){if(!this.activeLease&&this.inFlightNonTxCount===0&&this.queue.length===0){const t={leaseId:this.nextLeaseId++,txId:this.nextTxId++,createdAt:Date.now()};return this.activeLease=t,await this.acquireWebLock(),t}return new Promise(t=>{this.leaseWaiters.push({resolve:async n=>{await this.acquireWebLock(),t(n)}}),this.drain()})}releaseExclusiveLease(t){!this.activeLease||this.activeLease.leaseId!==t||(this.activeLease=null,this.releaseCurrentWebLock(),this.drain())}drain(){if(!this.activeLease){if(this.leaseWaiters.length>0){if(this.inFlightNonTxCount===0){const t=this.leaseWaiters.shift(),n={leaseId:this.nextLeaseId++,txId:this.nextTxId++,createdAt:Date.now()};this.activeLease=n,t.resolve(n)}return}for(;this.queue.length>0&&!this.activeLease&&this.leaseWaiters.length===0&&(!this.hasWebLocks()||this.inFlightNonTxCount===0);){const t=this.queue.shift();t&&t()}}}}class jo{constructor(t,n,s,i){N(this,"vfs");N(this,"pool");N(this,"io");N(this,"queue");N(this,"activeLease",null);N(this,"snapshotFrameCount",0);N(this,"snapshotWalFrameSeq",0);N(this,"slotSnapshots",new Map);N(this,"pinCountsSnapshot",null);N(this,"spilledPages",new Map);N(this,"committedWalPages",new Map);N(this,"walFrameSeq",0);N(this,"txCommitCount",0);N(this,"checkpointSeq",0);N(this,"instanceSalt",Math.floor(Math.random()*4294967295)>>>0||1);N(this,"expectedWalFrameCount",0);N(this,"lastDiskChangeCounter",0);N(this,"lastDiskSchemaVersion",0);N(this,"onCrossTabInvalidated");N(this,"idleTimer",null);N(this,"isClosed",!1);this.vfs=t,this.pool=n,this.io=s,this.queue=new Zo(i,()=>this.syncCrossTabState())}setOnCrossTabInvalidated(t){this.onCrossTabInvalidated=t}recordDiskPage1State(){const t=this.pool.getSlotDataView(0);this.lastDiskChangeCounter=t.getUint32(ye,!0),this.lastDiskSchemaVersion=t.getUint32(pe,!0)}async reloadFromDisk(t,n,s){this.pool.getPageBytesInSlot(0).set(t),this.pool.clearDirty(0),this.lastDiskChangeCounter=n,this.lastDiskSchemaVersion=s;for(let i=1;i<this.pool.slotCount;i++)this.pool.unassignSlot(i),this.pool.clearDirty(i),this.pool.pin_counts[i]=0;this.pool.pin_counts[0]=1,this.onCrossTabInvalidated&&await this.onCrossTabInvalidated()}async syncCrossTabState(t=!1){if(!t&&!this.queue.hasWebLocks())return;const n=await this.vfs.getWalFrameCount();let s=!1;if(n>0){const r=await this.vfs.readWalHeader();let o=0;if(r)try{o=Cs(r,!0).salt1}catch{o=0}(o!==this.instanceSalt||n!==this.expectedWalFrameCount)&&(s=!0,await sr(this.vfs),this.committedWalPages.clear(),this.walFrameSeq=0,this.txCommitCount=0,this.expectedWalFrameCount=0)}else this.expectedWalFrameCount>0&&(s=!0,this.committedWalPages.clear(),this.walFrameSeq=0,this.txCommitCount=0,this.expectedWalFrameCount=0);const[i]=await this.vfs.readPages([1]);if(i){const r=new DataView(i.buffer,i.byteOffset,i.byteLength),o=r.getUint32(ye,!0),a=r.getUint32(pe,!0);(s||o!==this.lastDiskChangeCounter||a!==this.lastDiskSchemaVersion)&&await this.reloadFromDisk(i,o,a)}}get leaseQueue(){return this.queue}isInTransaction(){return this.activeLease!==null}getActiveLeaseId(){return this.activeLease?this.activeLease.leaseId:null}getActiveTxId(){return this.activeLease?this.activeLease.txId:null}hasSpilledPage(t){return this.spilledPages.has(t)||this.committedWalPages.has(t)}getSpilledPage(t){const n=this.spilledPages.get(t)??this.committedWalPages.get(t);return n?new Uint8Array(n):null}onDirectPageWrite(t,n){if(this.committedWalPages.has(t)&&this.committedWalPages.set(t,new Uint8Array(n)),t===1){const s=new DataView(n.buffer,n.byteOffset,n.byteLength);this.lastDiskChangeCounter=s.getUint32(ye,!0),this.lastDiskSchemaVersion=s.getUint32(pe,!0)}}async spillUncommittedSlot(t,n){if(!this.activeLease){await this.io.writeSlot(t,n);return}this.io.stampSlotChecksum(t,n);const s=this.pool.getPageBytesInSlot(t),i=new Uint8Array(Oe);i.set(s),this.spilledPages.set(n,i);const r=this.pool.getSlotDataView(0).getUint32(re,!0),o=ws({frameType:as,flags:0,txId:this.activeLease.txId,pageId:n,dbSizePages:r,frameSeq:++this.walFrameSeq},i);await this.vfs.appendWalFrames([o]),this.expectedWalFrameCount=await this.vfs.getWalFrameCount()}async captureSavepoint(){const t=await this.vfs.getWalFrameCount(),n=new Map;for(let r=0;r<this.pool.slotCount;r++){const o=this.pool.getAssignedPage(r);if(o>0){const a=this.pool.isDirty(r),c=new Uint8Array(this.pool.getPageBytesInSlot(r));n.set(r,{pageId:o,dirty:a,data:c})}}const s=new Uint32Array(this.pool.pin_counts),i=new Map;for(const[r,o]of this.spilledPages.entries())i.set(r,new Uint8Array(o));return{frameCount:t,slotSnapshots:n,pinCounts:s,spilledPages:i,walFrameSeq:this.walFrameSeq}}async restoreSavepoint(t){for(let n=1;n<this.pool.slotCount;n++)this.pool.unassignSlot(n),this.pool.clearDirty(n);for(let n=0;n<this.pool.slotCount;n++){const s=t.slotSnapshots.get(n);s&&(this.pool.assignSlot(n,s.pageId),this.pool.getPageBytesInSlot(n).set(s.data),s.dirty?this.pool.markDirty(n):this.pool.clearDirty(n))}this.pool.pin_counts.set(t.pinCounts),this.spilledPages.clear();for(const[n,s]of t.spilledPages.entries())this.spilledPages.set(n,new Uint8Array(s));this.walFrameSeq=t.walFrameSeq,await this.vfs.truncateWal(t.frameCount),this.expectedWalFrameCount=t.frameCount}async begin(){const t=await this.queue.acquireExclusiveLease();this.activeLease=t,this.pauseIdleTimer();try{await this.syncCrossTabState();const n=await this.vfs.getWalFrameCount(),s=await this.vfs.readWalHeader();let i=!1;if(s&&n>0)try{i=Cs(s,!0).salt1===this.instanceSalt}catch{i=!1}i||await this.vfs.writeWalHeader(Ts({checkpointSeq:this.checkpointSeq,salt1:this.instanceSalt})),this.spilledPages.clear();const r=await this.captureSavepoint();return this.snapshotFrameCount=r.frameCount,this.snapshotWalFrameSeq=r.walFrameSeq,this.slotSnapshots=r.slotSnapshots,this.pinCountsSnapshot=r.pinCounts,t}catch(n){throw this.activeLease=null,this.queue.releaseExclusiveLease(t.leaseId),n}}async commit(t){var o,a;if(!this.activeLease||this.activeLease.leaseId!==t)return;const n=this.activeLease.txId,s=[],i=this.pool.getSlotDataView(0).getUint32(re,!0);for(const[c,l]of this.spilledPages.entries())this.committedWalPages.set(c,l);for(let c=0;c<this.pool.slotCount;c++)if(this.pool.isDirty(c)){const l=this.pool.getAssignedPage(c);if(l>0){this.io.stampSlotChecksum(c,l);const u=this.pool.getPageBytesInSlot(c),d=new Uint8Array(Oe);d.set(u),this.committedWalPages.set(l,d),this.pool.clearDirty(c),s.push(ws({frameType:rs,flags:0,txId:n,pageId:l,dbSizePages:i,frameSeq:++this.walFrameSeq},d))}}s.push(ws({frameType:os,flags:0,txId:n,pageId:0,dbSizePages:i,frameSeq:++this.walFrameSeq})),await this.vfs.appendWalFrames(s),await((a=(o=this.vfs).flushWal)==null?void 0:a.call(o));const r=await this.vfs.getWalFrameCount();this.expectedWalFrameCount=r,this.activeLease=null,this.spilledPages.clear(),this.slotSnapshots.clear(),this.pinCountsSnapshot=null,this.txCommitCount++,this.queue.releaseExclusiveLease(t),this.scheduleIdleTimer(),(r>=256||this.txCommitCount>=100)&&this.queue.enqueue(()=>this.executeCheckpoint())}async rollback(t){!this.activeLease||this.activeLease.leaseId!==t||(await this.restoreSavepoint({frameCount:this.snapshotFrameCount,slotSnapshots:this.slotSnapshots,pinCounts:this.pinCountsSnapshot??new Uint32Array(this.pool.pin_counts),spilledPages:new Map,walFrameSeq:this.snapshotWalFrameSeq}),this.activeLease=null,this.spilledPages.clear(),this.slotSnapshots.clear(),this.pinCountsSnapshot=null,this.queue.releaseExclusiveLease(t),this.scheduleIdleTimer())}async checkpoint(){return this.queue.enqueue(()=>this.executeCheckpoint())}async executeCheckpoint(){var o,a;const t=await this.vfs.getWalFrameCount(),n=new Map;if(t>0){const c=await this.vfs.readWalFrames(0,t),l=new Map,u=new Set;for(const d of c){const h=Fi(d);if(!h.valid||!h.header)break;const{frameType:f,txId:g,pageId:_}=h.header;if(l.has(g)||l.set(g,[]),f===os)u.add(g);else if(f===rs||f===as){const I=new Uint8Array(d.buffer,d.byteOffset+Ve,Oe),p=new Uint8Array(Oe);p.set(I),l.get(g).push({pageId:_,data:p})}}for(const[d,h]of l.entries())if(u.has(d))for(const f of h)f.pageId>0&&n.set(f.pageId,f.data)}for(const[c,l]of this.committedWalPages.entries())n.set(c,l);const s=new Map;for(let c=0;c<this.pool.slotCount;c++)if(this.pool.isDirty(c)){const l=this.pool.getAssignedPage(c);if(l>0){this.io.stampSlotChecksum(c,l);const u=this.pool.getPageBytesInSlot(c),d=new Uint8Array(Oe);d.set(u),s.set(l,{slotIdx:c,data:d})}}const i=new Set([...n.keys(),...s.keys()]),r=[];for(const c of i)if(s.has(c)){const{slotIdx:l,data:u}=s.get(c);r.push({pageId:c,data:u}),this.pool.clearDirty(l)}else r.push({pageId:c,data:n.get(c)});return r.length>0&&(r.sort((c,l)=>c.pageId-l.pageId),await this.vfs.writePages(r)),await((a=(o=this.vfs).flush)==null?void 0:a.call(o)),await this.vfs.truncateWal(0),this.committedWalPages.clear(),this.checkpointSeq++,this.walFrameSeq=0,this.txCommitCount=0,this.expectedWalFrameCount=0,this.recordDiskPage1State(),await this.vfs.writeWalHeader(Ts({checkpointSeq:this.checkpointSeq,salt1:this.instanceSalt})),{pagesWritten:r.length}}async resetWalAfterImport(){this.spilledPages.clear(),this.committedWalPages.clear(),await this.vfs.truncateWal(0),this.checkpointSeq++,this.walFrameSeq=0,this.txCommitCount=0,this.expectedWalFrameCount=0,this.recordDiskPage1State(),await this.vfs.writeWalHeader(Ts({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 Ko=new Set(["count","sum","avg","min","max"]),Jo=new Set(["upper","lower","length","substr","trim","abs","round","floor","ceil","concat","coalesce"]);function de(e){return Ko.has(e.toLowerCase())}function zo(e){return Jo.has(e.toLowerCase())}function dc(e){return de(e)||zo(e)}function rn(e,t){if(t==="where"){if(e.type==="fn"&&de(e.name))throw new _s(e.name);if(e.type==="binary"&&(rn(e.left,t),rn(e.right,t)),e.type==="fn")for(const n of e.args)rn(n,t)}}function _c(e){const t=[];let n=0;const s=e.length;for(;n<s;){const i=e[n];if(/\s/.test(i)){n++;continue}if(/[0-9]/.test(i)||i==="."&&n+1<s&&/[0-9]/.test(e[n+1])){const r=n;let o=!1;for(;n<s&&(/[0-9]/.test(e[n])||e[n]==="."&&!o);)e[n]==="."&&(o=!0),n++;t.push({type:"NUMBER",value:e.slice(r,n),pos:r});continue}if(i==="'"||i==='"'){const r=i,o=n;n++;let a="";for(;n<s&&e[n]!==r;)e[n]==="\\"&&n+1<s&&n++,a+=e[n],n++;n<s&&e[n]===r&&n++,t.push({type:"STRING",value:a,pos:o});continue}if(i==="("){t.push({type:"LPAREN",value:"(",pos:n++});continue}if(i===")"){t.push({type:"RPAREN",value:")",pos:n++});continue}if(i===","){t.push({type:"COMMA",value:",",pos:n++});continue}if(i==="<"){if(n+1<s&&e[n+1]==="="){t.push({type:"OP",value:"<=",pos:n}),n+=2;continue}if(n+1<s&&e[n+1]===">"){t.push({type:"OP",value:"!=",pos:n}),n+=2;continue}t.push({type:"OP",value:"<",pos:n++});continue}if(i===">"){if(n+1<s&&e[n+1]==="="){t.push({type:"OP",value:">=",pos:n}),n+=2;continue}t.push({type:"OP",value:">",pos:n++});continue}if(i==="="){if(n+1<s&&e[n+1]==="="){t.push({type:"OP",value:"=",pos:n}),n+=2;continue}t.push({type:"OP",value:"=",pos:n++});continue}if(i==="!"&&n+1<s&&e[n+1]==="="){t.push({type:"OP",value:"!=",pos:n}),n+=2;continue}if(i==="+"||i==="-"||i==="/"||i==="%"){t.push({type:"OP",value:i,pos:n++});continue}if(i==="*"){t.push({type:"STAR",value:"*",pos:n++});continue}if(/[a-zA-Z_]/.test(i)){const r=n;for(;n<s;)if(/[a-zA-Z0-9_]/.test(e[n]))n++;else if(e[n]==="."&&n+1<s&&/[a-zA-Z_]/.test(e[n+1]))n+=2;else break;const o=e.slice(r,n);t.push({type:"IDENT",value:o,pos:r});continue}n++}return t.push({type:"EOF",value:"",pos:s}),t}class mc{constructor(t){N(this,"tokens");N(this,"cursor",0);this.tokens=t}peek(){return this.tokens[this.cursor]??{type:"EOF",value:"",pos:0}}consume(){const t=this.peek();return this.cursor++,t}match(t,n){const s=this.peek();return s.type!==t||n!==void 0&&s.value.toLowerCase()!==n.toLowerCase()?!1:(this.cursor++,!0)}getPrecedence(t){if(t.type==="OP"||t.type==="STAR"){if(t.value==="="||t.value==="!="||t.value==="<"||t.value==="<="||t.value===">"||t.value===">=")return 5;if(t.value==="+"||t.value==="-")return 10;if(t.value==="*"||t.value==="/"||t.value==="%")return 20}return 0}parse(t=0){let n=this.parsePrimary();for(;;){const s=this.peek(),i=this.getPrecedence(s);if(i===0||i<=t)break;this.consume();const r=this.parse(i);n={type:"binary",op:s.value,left:n,right:r}}return n}parsePrimary(){const t=this.peek();if(t.type==="OP"&&t.value==="-"){this.consume();const n=this.parse(25);return n.type==="literal"&&typeof n.value=="number"?{type:"literal",value:-n.value}:{type:"binary",op:"-",left:{type:"literal",value:0},right:n}}if(this.match("NUMBER"))return{type:"literal",value:Number(t.value)};if(this.match("STRING"))return{type:"literal",value:t.value};if(this.match("LPAREN")){const n=this.parse(0);if(!this.match("RPAREN"))throw new Error("Unclosed parenthesis in expression");return n}if(this.match("STAR"))return{type:"col",name:"*"};if(t.type==="IDENT"){this.consume();const n=t.value,s=n.toLowerCase();if(s==="null"&&this.peek().type!=="LPAREN")return{type:"literal",value:null};if(s==="true"&&this.peek().type!=="LPAREN")return{type:"literal",value:!0};if(s==="false"&&this.peek().type!=="LPAREN")return{type:"literal",value:!1};if(this.match("LPAREN")){const i=[];if(!this.match("RPAREN")){for(;;)if(i.push(this.parse(0)),!this.match("COMMA")){if(this.match("RPAREN"))break;throw new Error(`Expected ',' or ')' in argument list of function ${n}`)}}return{type:"fn",name:s,args:i}}return{type:"col",name:n}}throw new Error(`Unexpected token "${t.value}" in expression at position ${t.pos}`)}}function At(e){const t=e.trim();if(!t)throw new Error("Cannot parse empty expression");const n=_c(t);return new mc(n).parse(0)}function Ec(e){let t=0,n=null;const s=e.length;for(let i=0;i<s;i++){const r=e[i];if(n){r===n&&e[i-1]!=="\\"&&(n=null);continue}if(r==="'"||r==='"'){n=r;continue}if(r==="("){t++;continue}if(r===")"){t--;continue}if(t===0&&(r===" "||r===" ")&&i+4<s&&e.slice(i+1,i+3).toLowerCase()==="as"&&/\s/.test(e[i+3])){const o=e.slice(0,i).trim(),a=e.slice(i+4).trim();return{exprStr:o,explicitAlias:a}}}return{exprStr:e.trim()}}function vt(e){if(e.type==="col")return e.name.includes(".")?e.name.slice(e.name.lastIndexOf(".")+1):e.name;if(e.type==="fn"){if(e.args.length>0&&e.args[0].type==="col"&&e.args[0].name!=="*"){const t=e.args[0].name.includes(".")?e.args[0].name.slice(e.args[0].name.lastIndexOf(".")+1):e.args[0].name;return`${e.name}_${t}`}return e.name}return e.type==="binary"?"expr":"val"}function qs(e){const{exprStr:t,explicitAlias:n}=Ec(e),s=At(t),i=n&&n.length>0?n:vt(s);return{expr:s,alias:i}}class it{constructor(t){N(this,"node");this.node=t}add(t){return new it({type:"binary",op:"+",left:this.node,right:jt(t)})}sub(t){return new it({type:"binary",op:"-",left:this.node,right:jt(t)})}mul(t){return new it({type:"binary",op:"*",left:this.node,right:jt(t)})}div(t){return new it({type:"binary",op:"/",left:this.node,right:jt(t)})}mod(t){return new it({type:"binary",op:"%",left:this.node,right:jt(t)})}eq(t){return new it({type:"binary",op:"=",left:this.node,right:jt(t)})}ne(t){return new it({type:"binary",op:"!=",left:this.node,right:jt(t)})}lt(t){return new it({type:"binary",op:"<",left:this.node,right:jt(t)})}lte(t){return new it({type:"binary",op:"<=",left:this.node,right:jt(t)})}gt(t){return new it({type:"binary",op:">",left:this.node,right:jt(t)})}gte(t){return new it({type:"binary",op:">=",left:this.node,right:jt(t)})}as(t){return{expr:this.node,alias:t}}}function jt(e){return e===null?{type:"literal",value:null}:typeof e=="boolean"?{type:"literal",value:e}:e instanceof it?e.node:typeof e=="number"?{type:"literal",value:e}:typeof e=="string"?{type:"literal",value:e}:e}function ir(e){return new it({type:"col",name:e})}function ta(e){return new it(At(e))}const Ic=ta;function Pt(e,t){return new it({type:"fn",name:e.toLowerCase(),args:t.map(n=>typeof n=="string"&&!n.startsWith("'")?ir(n).node:jt(n))})}const ea=(e,...t)=>Pt(e,t),pc={upper:e=>Pt("upper",[e]),lower:e=>Pt("lower",[e]),length:e=>Pt("length",[e]),substr:(e,t,n)=>{const s=[e,t];return n!==void 0&&s.push(n),Pt("substr",s)},trim:e=>Pt("trim",[e]),abs:e=>Pt("abs",[e]),round:e=>Pt("round",[e]),floor:e=>Pt("floor",[e]),ceil:e=>Pt("ceil",[e]),count:e=>Pt("count",[e??ir("*").node]),sum:e=>Pt("sum",[e]),avg:e=>Pt("avg",[e]),min:e=>Pt("min",[e]),max:e=>Pt("max",[e]),concat:(...e)=>Pt("concat",e),coalesce:(...e)=>Pt("coalesce",e)};for(const[e,t]of Object.entries(pc))Object.defineProperty(ea,e,{value:t,writable:!0,enumerable:!0,configurable:!0});const yc=ea;function kt(e,t,n){switch(e.type){case"literal":return e.value;case"col":return e.name==="*"?null:t[e.name]!==void 0?t[e.name]:null;case"binary":{const s=kt(e.left,t,n),i=kt(e.right,t,n);if(s===null||i===null||s===void 0||i===void 0)return null;if(e.op==="="||e.op==="!="||e.op==="<"||e.op==="<="||e.op===">"||e.op===">="){const a=typeof s=="string"&&typeof i=="string"?s<i?-1:s>i?1:0:Number(s)<Number(i)?-1:Number(s)>Number(i)?1:0;switch(e.op){case"=":return a===0?1:0;case"!=":return a!==0?1:0;case"<":return a<0?1:0;case"<=":return a<=0?1:0;case">":return a>0?1:0;case">=":return a>=0?1:0}}const r=Number(s),o=Number(i);switch(e.op){case"+":return r+o;case"-":return r-o;case"*":return r*o;case"/":return o===0?null:r/o;case"%":return o===0?null:r%o}return null}case"fn":{const s=e.name.toLowerCase();if(de(s)){if(t[s]!==void 0)return t[s];const r=e.args[0];if(r&&r.type==="col"){const o=`${s}_${r.name}`;if(t[o]!==void 0)return t[o]}return null}const i=e.args.map(r=>kt(r,t,n));switch(s){case"upper":return i[0]!==null&&i[0]!==void 0?String(i[0]).toUpperCase():null;case"lower":return i[0]!==null&&i[0]!==void 0?String(i[0]).toLowerCase():null;case"length":return i[0]!==null&&i[0]!==void 0?String(i[0]).length:null;case"trim":return i[0]!==null&&i[0]!==void 0?String(i[0]).trim():null;case"substr":{if(i[0]===null||i[0]===void 0)return null;const r=String(i[0]),o=Math.max(0,(Number(i[1])||1)-1),a=i[2]!==null&&i[2]!==void 0?Number(i[2]):void 0;return a!==void 0?r.substring(o,o+a):r.substring(o)}case"abs":return i[0]!==null&&i[0]!==void 0?Math.abs(Number(i[0])):null;case"round":return i[0]!==null&&i[0]!==void 0?Math.round(Number(i[0])):null;case"floor":return i[0]!==null&&i[0]!==void 0?Math.floor(Number(i[0])):null;case"ceil":return i[0]!==null&&i[0]!==void 0?Math.ceil(Number(i[0])):null;case"concat":return i.some(r=>r==null)?null:i.map(String).join("");case"coalesce":{for(const r of i)if(r!=null)return r;return null}case"starts_with":case"startswith":return i[0]!==null&&i[0]!==void 0&&i[1]!==null&&i[1]!==void 0?String(i[0]).startsWith(String(i[1]))?1:0:null;case"ends_with":case"endswith":return i[0]!==null&&i[0]!==void 0&&i[1]!==null&&i[1]!==void 0?String(i[0]).endsWith(String(i[1]))?1:0:null;case"contains":return i[0]!==null&&i[0]!==void 0&&i[1]!==null&&i[1]!==void 0?String(i[0]).includes(String(i[1]))?1:0:null;case"like":return i[0]!==null&&i[0]!==void 0&&i[1]!==null&&i[1]!==void 0?ze(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 Pi(s)}}}}}const Cn=.5,Ws=.05,_e=.02;function na(e){const t=[];function n(i){if(i.colName&&t.push(i.colName),i.expr&&s(i.expr),i.children)for(const r of i.children)n(r);i.child&&n(i.child)}function s(i){if(i&&(i.type==="col"&&i.name&&t.push(i.name),i.left&&s(i.left),i.right&&s(i.right),i.args&&Array.isArray(i.args)))for(const r of i.args)s(r)}return n(e),t}function wn(e,t){const n=na(e),s=new Set;for(const i of n){const r=gt(i,t);r&&s.add(r.tableIdx)}return s}function rr(e,t){var s,i;const n=Math.max(1,t.rowCountEstimate||10);if(e.type==="cmp"){const r=e.op??"=";if(r==="="){const o=(s=e.colName)==null?void 0:s.toLowerCase(),a=t.columns.findIndex(c=>c.name.toLowerCase()===o);if(a!==-1&&t.indexes){for(const c of t.indexes)if(c.columnCount===1&&c.columnIndices[0]===a)return(c.flags&(rt.PRIMARY|rt.UNIQUE))!==0?1/n:Math.min(.2,5/n)}return .1}if(r==="<"||r==="<="||r===">"||r===">=")return .33;if(r==="!="||r==="<>")return .9;if(r==="like"||r==="contains"||r==="starts_with"||r==="ends_with")return .15}if(e.type==="in"){const r=Math.max(1,((i=e.values)==null?void 0:i.length)||1);return Math.min(1,r*.05)}return e.type==="null"?e.isNull?.05:.95:.2}function me(e,t,n,s){var d;const i=Math.max(1,e.rowCountEstimate||10);let r=1;for(const h of t)r*=rr(h,e);const o=Math.max(1,Math.round(i*r)),a=n!==void 0&&n.length>0,c=a&&o>1?o*Math.log2(o)*_e:0,l=Ys(e,t,t,n);if(l){const h=l.scanType==="point",f=l.scanType==="multi_point",g=l.satisfiesOrderBy===!0,_=g&&s!==void 0&&s>0?Math.min(s,o):o;let I=Cn;return h?(I+=1*_e,{cost:I,rows:1,scanType:"IndexScan",indexName:l.index.name,isOrderSatisfied:!0,sortCostAvoided:a?c:void 0}):f?(I=(((d=l.inValues)==null?void 0:d.length)||1)*Cn+_*_e,!g&&a&&(I+=c),{cost:I,rows:_,scanType:"IndexScan",indexName:l.index.name,isOrderSatisfied:g,sortCostAvoided:g?c:void 0}):(I+=_*Ws+_*_e,!g&&a&&(I+=c),{cost:I,rows:_,scanType:"IndexScan",indexName:l.index.name,isOrderSatisfied:g,sortCostAvoided:g?c:void 0})}let u=i*_e;return a&&(u+=c),{cost:u,rows:o,scanType:"TableScan",isOrderSatisfied:!1}}function jn(e,t){if(!e.indexes||e.indexes.length===0)return null;const n=e.columns.findIndex(r=>r.name.toLowerCase()===t.toLowerCase());if(n===-1)return null;let s=null,i=999;for(const r of e.indexes)if(r.columnCount===1&&r.columnIndices[0]===n){const o=(r.flags&rt.PRIMARY)!==0,a=(r.flags&rt.UNIQUE)!==0,c=o?1:a?2:3;c<i&&(i=c,s={index:r,isUnique:o||a})}return s}function Hs(e,t){const n=t.length,s=[],i=Array.from({length:n},()=>new Set);if(!e.joinedTables)return{edges:s,dependencies:i};for(let r=0;r<e.joinedTables.length;r++){const o=e.joinedTables[r],a=r+1,c=gt(o.leftCol,t),l=gt(o.rightCol,t);if(c&&l&&(s.push({tableA:c.tableIdx,tableB:l.tableIdx,colA:c.col.name,colB:l.col.name,op:o.op,type:o.type,declaredRightTable:a}),o.type==="left")){const u=c.tableIdx===a?l.tableIdx:c.tableIdx;i[a].add(u)}}return{edges:s,dependencies:i}}function Kn(e,t){if(e.selectExprs&&e.selectExprs.length>0)return e.selectExprs;const n=new Set,s=new Set;for(const r of t)for(const o of r.columns)n.has(o.name.toLowerCase())&&s.add(o.name.toLowerCase()),n.add(o.name.toLowerCase());const i=[];for(const r of t)for(const o of r.columns){const a=s.has(o.name.toLowerCase())?`${r.name}.${o.name}`:o.name;i.push({expr:{type:"col",name:`${r.name}.${o.name}`},alias:a})}return i}function Vs(e,t,n,s){const i=e.length,r=[];for(let o=1;o<i;o++){const a=e[o],c=t[a],l=e.slice(0,o),u=n.find(_=>_.tableA===a&&l.includes(_.tableB)||_.tableB===a&&l.includes(_.tableA));let d,h,f="=",g="inner";if(u)f=u.op,g=u.type,u.tableA===a?(h=`${c.name}.${u.colA}`,d=`${t[u.tableB].name}.${u.colB}`):(h=`${c.name}.${u.colB}`,d=`${t[u.tableA].name}.${u.colA}`);else{const _=s==null?void 0:s.find(I=>I.table.name===c.name);d=_?_.leftCol:`${t[e[0]].name}.id`,h=_?_.rightCol:`${c.name}.id`,f=_?_.op:"=",g=_?_.type:"inner"}r.push({type:g,table:c,cursor:o,leftCol:d,op:f,rightCol:h})}return r}function or(e,t,n,s,i){if(!s||s.length===0)return!1;for(const r of s){if(r.direction==="desc")return!1;const o=r.colName;if(!o)return!1;let a=gt(o,n);if(!a&&i){const c=i.find(l=>l.alias===o);c&&c.expr.type==="col"&&(a=gt(c.expr.name,n))}if(!a||a.tableIdx!==t)return!1}return!0}function ar(e,t){var n;if(e.type==="null")return 1;if(e.type==="cmp"){const s=e.op??"=";if(s==="like"||s==="not like")return(typeof e.value=="string"?e.value:"").startsWith("%")?25:15;let i=!1;if(t&&e.colName){const r=e.colName.toLowerCase(),o=r.includes(".")?r.slice(r.lastIndexOf(".")+1):r;for(const a of t){const c=a.columns.find(l=>l.name.toLowerCase()===o);if(c){i=c.type===1||c.type===2||c.type===3;break}}}else typeof e.value=="number"&&(i=!0);return s==="="||s==="=="?i?2:4:i?3:6}return e.type==="in"?(((n=e.values)==null?void 0:n.length)??0)<=3?5:10:e.type==="expr"?40:e.type==="and"||e.type==="or"?15:e.type==="not"?8:10}function lr(e,t){if(!e||e.length===0)return{filters:[],isAlwaysFalse:!1,isAlwaysTrue:!0,metrics:{originalCount:0,optimizedCount:0,isAlwaysFalse:!1,isAlwaysTrue:!0,eliminatedFiltersCount:0,reordered:!1}};const n=e.length,s=[];for(const d of e)d.type==="and"&&Array.isArray(d.children)?s.push(...d.children):s.push(d);const i=new Map,r=[];for(const d of s)if(d.colName){const h=d.colName.toLowerCase();i.has(h)||i.set(h,[]),i.get(h).push(d)}else r.push(d);for(const[d,h]of i.entries()){const f=Tc(h);if(f)return{filters:[],isAlwaysFalse:!0,isAlwaysTrue:!1,metrics:{originalCount:n,optimizedCount:0,isAlwaysFalse:!0,isAlwaysTrue:!1,contradictionReason:`Contradiction on column "${d}": ${f}`,eliminatedFiltersCount:n,reordered:!1}}}const o=[];let a=0;for(const[,d]of i.entries()){const h=Cc(d);a+=d.length-h.length,o.push(...h)}o.push(...r);const c=o.map(d=>cr(d)).join("|");o.sort((d,h)=>{const f=ar(d,t),g=ar(h,t);return f-g});const l=o.map(d=>cr(d)).join("|"),u=c!==l;return{filters:o,isAlwaysFalse:!1,isAlwaysTrue:o.length===0,metrics:{originalCount:n,optimizedCount:o.length,isAlwaysFalse:!1,isAlwaysTrue:o.length===0,eliminatedFiltersCount:a,reordered:u}}}function Tc(e){let t=!1,n=!1;const s=[];let i=null,r=null,o=null;for(const a of e){if(a.type==="null"&&(a.isNull===!0&&(t=!0),a.isNull===!1&&(n=!0)),a.type==="cmp"){const c=a.op??"=",l=a.value;c==="="&&l!==null&&l!==void 0&&s.push(l),typeof l=="number"&&(c===">"?(!i||l>i.val||l===i.val&&!i.strict)&&(i={val:l,strict:!0}):c===">="?(!i||l>i.val)&&(i={val:l,strict:!1}):c==="<"?(!r||l<r.val||l===r.val&&!r.strict)&&(r={val:l,strict:!0}):c==="<="&&(!r||l<r.val)&&(r={val:l,strict:!1}))}if(a.type==="in"&&!a.notIn){if(!a.values||a.values.length===0)return"Empty IN () list";const c=new Set(a.values);if(!o)o=c;else{const l=new Set([...o].filter(u=>c.has(u)));if(l.size===0)return"Mutually exclusive IN lists with no common values";o=l}}}if(t&&n)return"Conflicting IS NULL and IS NOT NULL";if(t&&(s.length>0||i||r))return"Conflicting IS NULL and literal comparison";if(s.length>1){const a=s[0];for(let c=1;c<s.length;c++)if(s[c]!==a)return`Conflicting equality values (${a} !== ${s[c]})`}if(s.length>0&&(i||r)){const a=s[0];if(typeof a=="number"){if(i&&(i.strict?a<=i.val:a<i.val))return`Equality value ${a} violates lower bound ${i.strict?">":">="} ${i.val}`;if(r&&(r.strict?a>=r.val:a>r.val))return`Equality value ${a} violates upper bound ${r.strict?"<":"<="} ${r.val}`}}if(s.length>0&&o){const a=s[0];if(!o.has(a))return`Equality value ${a} not present in IN list`}if(i&&r){if(i.val>r.val)return`Lower bound ${i.val} is greater than upper bound ${r.val}`;if(i.val===r.val&&(i.strict||r.strict))return`Strict range bounds empty at ${i.val}`}return null}function Cc(e){const t=[],n=new Set;let s=!1,i;for(const a of e)if(a.type==="cmp"&&(a.op==="="||a.op===void 0)&&a.value!==null&&a.value!==void 0){s=!0,i=a.value;break}let r=null,o=null;for(const a of e)if(a.type==="cmp"&&typeof a.value=="number"){const c=a.op??"=",l=a.value;c===">"?(!r||l>r.val||l===r.val&&!r.strict)&&(r={val:l,strict:!0,filter:a}):c===">="?(!r||l>r.val)&&(r={val:l,strict:!1,filter:a}):c==="<"?(!o||l<o.val||l===o.val&&!o.strict)&&(o={val:l,strict:!0,filter:a}):c==="<="&&(!o||l<o.val)&&(o={val:l,strict:!1,filter:a})}for(const a of e){const c=cr(a);if(!n.has(c)&&!(a.type==="null"&&a.isNull===!1&&s)&&!(a.type==="in"&&!a.notIn&&s&&Array.isArray(a.values)&&a.values.includes(i))){if(a.type==="cmp"&&typeof a.value=="number"){const l=a.op??"=";if(l===">"||l===">="){if(r&&a!==r.filter)continue}else if((l==="<"||l==="<=")&&o&&a!==o.filter)continue}n.add(c),t.push(a)}}return t}function cr(e){return`${e.type}:${e.colName??""}:${e.isNull??""}:${e.op??""}:${String(e.value??"")}:${e.notIn??""}:${JSON.stringify(e.values??"")}`}function sa(e,t){const n=[...e],s=o=>o.toLowerCase(),i=o=>{const a=o.lastIndexOf(".");return a>=0?o.slice(a+1).toLowerCase():o.toLowerCase()},r=o=>{const a=s(o),c=i(o);for(const l of e)if(l.type==="cmp"&&(l.op==="="||l.op==="=="||l.op===void 0)&&l.colName&&l.value!==null&&l.value!==void 0){const u=s(l.colName),d=i(l.colName);if(u===a||d===a||u===c)return l.value}};for(const o of t){if(o.type!=="inner"&&o.type!=="left"||o.op!=="="&&o.op!=="==")continue;const a=r(o.leftCol);if(a!==void 0&&n.push({type:"cmp",colName:o.rightCol,op:"=",value:a}),o.type==="inner"){const c=r(o.rightCol);c!==void 0&&n.push({type:"cmp",colName:o.leftCol,op:"=",value:c})}}return n}class $s{constructor(t){N(this,"name","cost");N(this,"indexSeekCost");N(this,"indexNextCost");N(this,"rowEvalCost");this.indexSeekCost=(t==null?void 0:t.indexSeekCost)??Cn,this.indexNextCost=(t==null?void 0:t.indexNextCost)??Ws,this.rowEvalCost=(t==null?void 0:t.rowEvalCost)??_e}optimize(t){var R,A;const n=[t.table,...((R=t.joinedTables)==null?void 0:R.map(b=>b.table))??[]],s=n.length,i=lr(t.filters,n);if(i.isAlwaysFalse)return{plan:{...t,filters:[]},orderedTables:n,metrics:null,isAlwaysFalse:!0,whereMetrics:i.metrics};let r=i.filters,o=i.metrics;if(t.joinedTables&&t.joinedTables.length>0){const b=sa(r,t.joinedTables);if(b.length>r.length){const k=lr(b,n);if(k.isAlwaysFalse)return{plan:{...t,filters:[]},orderedTables:n,metrics:null,isAlwaysFalse:!0,whereMetrics:k.metrics};r=k.filters,o=k.metrics}}if(s<=1||!t.joinedTables||t.joinedTables.length===0){const b=new Map;b.set(0,r);const k=me(t.table,r,t.orderBy,t.limit);return{plan:{...t,filters:r},orderedTables:[t.table],metrics:{totalCost:k.cost,estimatedRows:k.rows,joinOrder:[t.table.name],singleTableFilters:b,crossFilters:[],tableScanTypes:[k.scanType],tableIndexNames:[k.indexName],isOrderSatisfied:k.isOrderSatisfied,sortCostAvoided:k.sortCostAvoided},isAlwaysFalse:!1,isAlwaysTrue:o.isAlwaysTrue,whereMetrics:o,isOrderSatisfied:k.isOrderSatisfied,sortCostAvoided:k.sortCostAvoided}}const a=ne(r),c=Sn(a),l=new Map,u=[];for(let b=0;b<s;b++)l.set(b,[]);for(const b of c){const k=wn(b,n);if(k.size===1){const V=k.values().next().value;V!==void 0&&((A=l.get(V))==null||A.push(b))}else u.push(b)}if(s<=1||!t.joinedTables||t.joinedTables.length===0){const b=me(n[0],l.get(0)??[]);return{plan:t,orderedTables:n,metrics:{totalCost:b.cost,estimatedRows:b.rows,joinOrder:[n[0].name],singleTableFilters:l,crossFilters:u,tableScanTypes:[b.scanType],tableIndexNames:[b.indexName]}}}const{edges:d,dependencies:h}=Hs(t,n),f=new Map;for(let b=0;b<s;b++)if(h[b].size===0){const k=or(n[b],b,n,t.orderBy,t.selectExprs),V=k?t.orderBy.map(G=>{const q=G.colName??"",Rt=q.includes(".")?q.slice(q.lastIndexOf(".")+1):q;return{...G,colName:Rt}}):void 0,j=me(n[b],l.get(b)??[],V,k?t.limit:void 0),K=1<<b;f.set(K,{order:[b],cost:j.cost,rows:j.rows,scanTypes:[j.scanType],indexNames:[j.indexName],edgesUsed:[],isOrderSatisfied:j.isOrderSatisfied,sortCostAvoided:j.sortCostAvoided})}const g=1<<s;for(let b=2;b<=s;b++)for(let k=1;k<g;k++)if(wc(k)===b)for(let V=0;V<s;V++){if(!(k&1<<V))continue;const j=k^1<<V,K=f.get(j);if(!K)continue;let G=!0;for(const De of h[V])if(!(j&1<<De)){G=!1;break}if(!G)continue;const q=this.evaluateJoinStep(K.rows,n[V],V,d,K.order,l.get(V)??[]),Rt=K.cost+q.stepCost,dt=f.get(k);let _t=!1,On=Rt,Pn=dt?dt.cost:0;const bn=K.isOrderSatisfied===!0,on=(dt==null?void 0:dt.isOrderSatisfied)===!0;if(b===s&&t.orderBy&&t.orderBy.length>0&&(!bn&&q.newRows>1&&(On+=q.newRows*Math.log2(q.newRows)*this.rowEvalCost),dt&&!on&&dt.rows>1&&(Pn+=dt.rows*Math.log2(dt.rows)*this.rowEvalCost)),!dt)_t=!0;else if(bn&&!on)_t=!0;else if(!bn&&on)_t=!1;else{const De=K.scanTypes.filter(Qe=>Qe==="IndexScan").length+(q.scanType==="IndexScan"?1:0),es=dt.scanTypes.filter(Qe=>Qe==="IndexScan").length;if(De>es&&On<=Pn*1.2)_t=!0;else if(De<es)_t=!1;else if(On<Pn*.75)_t=!0;else if(Pn<On*.75)_t=!1;else{const Qe=K.order[0]===0,Nn=dt.order[0]===0;if(Qe&&!Nn)_t=!0;else if(!Qe&&Nn)_t=!1;else{const ce=K.order.filter(Ln=>Ln>V).length,zs=dt.order.filter((Ln,ti)=>Ln>ti).length;ce<zs&&(_t=!0)}}}_t&&f.set(k,{order:[...K.order,V],cost:Rt,rows:q.newRows,scanTypes:[...K.scanTypes,q.scanType],indexNames:[...K.indexNames,q.indexName],edgesUsed:[...K.edgesUsed,q.matchedEdge],isOrderSatisfied:K.isOrderSatisfied,sortCostAvoided:K.sortCostAvoided})}const _=(1<<s)-1,I=f.get(_);let p,y,T,O,w;I?(p=I.order,y=I.cost,T=I.rows,O=I.scanTypes,w=I.indexNames):(p=Array.from({length:s},(b,k)=>k),y=999999,T=100,O=Array.from({length:s},()=>"TableScan"),w=Array.from({length:s},()=>{}));const C=p.map(b=>n[b]),B=Vs(p,n,d,t.joinedTables),P=Kn(t,n),U=(I==null?void 0:I.isOrderSatisfied)===!0,Q=U&&t.orderBy&&t.orderBy.length>0&&T>1?T*Math.log2(T)*this.rowEvalCost:void 0;return{plan:{...t,table:C[0],joinedTables:B,selectExprs:P,filters:r,isOrderSatisfied:U},orderedTables:C,metrics:{totalCost:y,estimatedRows:T,joinOrder:C.map(b=>b.name),singleTableFilters:l,crossFilters:u,tableScanTypes:O,tableIndexNames:w,isOrderSatisfied:U,sortCostAvoided:Q},isAlwaysFalse:!1,isAlwaysTrue:o.isAlwaysTrue,whereMetrics:o,isOrderSatisfied:U,sortCostAvoided:Q}}evaluateJoinStep(t,n,s,i,r,o){const a=Math.max(1,n.rowCountEstimate||10);let c=1;for(const f of o)c*=rr(f,n);const l=[];for(const f of i)if(f.tableA===s&&r.includes(f.tableB)){const g=jn(n,f.colA);l.push({edge:f,nextCol:f.colA,outerCol:f.colB,idxMatch:g})}else if(f.tableB===s&&r.includes(f.tableA)){const g=jn(n,f.colB);l.push({edge:f,nextCol:f.colB,outerCol:f.colA,idxMatch:g})}if(l.length===0){const f=t*(2+a*.1),g=Math.max(1,Math.round(t*a*c)),_={tableA:r[0],tableB:s,colA:"",colB:"",op:"=",type:"inner",declaredRightTable:s};return{stepCost:f,newRows:g,scanType:"TableScan",matchedEdge:_}}l.sort((f,g)=>{const _=f.idxMatch?f.idxMatch.isUnique?1:2:3,I=g.idxMatch?g.idxMatch.isUnique?1:2:3;return _-I});const u=l[0];if(u.idxMatch&&u.idxMatch.isUnique){const f=this.indexSeekCost+1*this.rowEvalCost,g=t*f,_=Math.max(1,Math.round(t*c));return{stepCost:g,newRows:_,scanType:"IndexScan",indexName:u.idxMatch.index.name,matchedEdge:u.edge}}if(u.idxMatch&&!u.idxMatch.isUnique){const f=Math.max(1,Math.min(10,Math.round(a/20))),g=this.indexSeekCost+f*this.indexNextCost,_=t*g,I=Math.max(1,Math.round(t*f*c));return{stepCost:_,newRows:I,scanType:"IndexScan",indexName:u.idxMatch.index.name,matchedEdge:u.edge}}const d=t*(2+a*.1),h=Math.max(1,Math.round(t*Math.max(1,Math.round(a*.1))*c));return{stepCost:d,newRows:h,scanType:"TableScan",matchedEdge:u.edge}}}function wc(e){let t=0,n=e;for(;n>0;)t+=n&1,n>>=1;return t}class ia{constructor(){N(this,"name","heuristic")}optimize(t){var P,U,Q;const n=[t.table,...((P=t.joinedTables)==null?void 0:P.map(R=>R.table))??[]],s=n.length,i=ne(t.filters),r=Sn(i),o=new Map,a=[];for(let R=0;R<s;R++)o.set(R,[]);for(const R of r){const A=wn(R,n);if(A.size===1){const b=A.values().next().value;b!==void 0&&((U=o.get(b))==null||U.push(R))}else a.push(R)}if(s<=1||!t.joinedTables||t.joinedTables.length===0){const R=me(n[0],o.get(0)??[],t.orderBy,t.limit);return{plan:t,orderedTables:n,metrics:{totalCost:R.cost,estimatedRows:R.rows,joinOrder:[n[0].name],singleTableFilters:o,crossFilters:a,tableScanTypes:[R.scanType],tableIndexNames:[R.indexName],isOrderSatisfied:R.isOrderSatisfied,sortCostAvoided:R.sortCostAvoided},isOrderSatisfied:R.isOrderSatisfied,sortCostAvoided:R.sortCostAvoided}}const{edges:c,dependencies:l}=Hs(t,n),u=n.map((R,A)=>{const b=or(R,A,n,t.orderBy,t.selectExprs),k=b?t.orderBy.map(V=>{const j=V.colName??"",K=j.includes(".")?j.slice(j.lastIndexOf(".")+1):j;return{...V,colName:K}}):void 0;return me(R,o.get(A)??[],k,b?t.limit:void 0)}),d=[];for(let R=0;R<s;R++)l[R].size===0&&d.push(R);d.sort((R,A)=>{const b=u[R].isOrderSatisfied?1:0,k=u[A].isOrderSatisfied?1:0;if(b!==k)return k-b;if(u[R].rows!==u[A].rows)return u[R].rows-u[A].rows;const V=u[R].scanType==="IndexScan"?1:0,j=u[A].scanType==="IndexScan"?1:0;return V!==j?j-V:R===0?-1:A===0?1:R-A});const h=d[0]??0,f=[h],g=[u[h].scanType],_=[u[h].indexName];let I=u[h].cost,p=u[h].rows;const y=new Set;for(let R=0;R<s;R++)R!==h&&y.add(R);for(;y.size>0;){const R=[];for(const b of y){let k=!0;for(const G of l[b])if(!f.includes(G)){k=!1;break}if(!k)continue;const V=n[b],j=Math.max(1,V.rowCountEstimate||10);let K=null;for(const G of c)if(G.tableA===b&&f.includes(G.tableB)){const q=jn(V,G.colA);q&&(!K||q.isUnique)&&(K={isUnique:q.isUnique,indexName:q.index.name})}else if(G.tableB===b&&f.includes(G.tableA)){const q=jn(V,G.colB);q&&(!K||q.isUnique)&&(K={isUnique:q.isUnique,indexName:q.index.name})}if(K)if(K.isUnique){const G=Cn+1*_e;R.push({tableIdx:b,rank:1,stepCost:p*G,newRows:Math.max(1,p),scanType:"IndexScan",indexName:K.indexName})}else{const G=Math.max(1,Math.min(10,Math.round(j/20))),q=Cn+G*Ws;R.push({tableIdx:b,rank:2,stepCost:p*q,newRows:Math.max(1,p*G),scanType:"IndexScan",indexName:K.indexName})}else R.push({tableIdx:b,rank:3,stepCost:p*(2+j*.1),newRows:Math.max(1,p*Math.max(1,Math.round(j*.1))),scanType:"TableScan"})}if(R.length===0){const b=y.values().next().value;if(b===void 0)break;f.push(b),g.push("TableScan"),_.push(void 0),y.delete(b);continue}R.sort((b,k)=>b.rank!==k.rank?b.rank-k.rank:Math.abs(b.stepCost-k.stepCost)>.05?b.stepCost-k.stepCost:b.tableIdx-k.tableIdx);const A=R[0];f.push(A.tableIdx),g.push(A.scanType),_.push(A.indexName),I+=A.stepCost,p=A.newRows,y.delete(A.tableIdx)}const T=f.map(R=>n[R]),O=Vs(f,n,c,t.joinedTables),w=Kn(t,n),C=((Q=u[h])==null?void 0:Q.isOrderSatisfied)===!0,B=C&&t.orderBy&&t.orderBy.length>0&&p>1?p*Math.log2(p)*_e:void 0;return{plan:{...t,table:T[0],joinedTables:O,selectExprs:w,isOrderSatisfied:C},orderedTables:T,metrics:{totalCost:I,estimatedRows:p,joinOrder:T.map(R=>R.name),singleTableFilters:o,crossFilters:a,tableScanTypes:g,tableIndexNames:_,isOrderSatisfied:C,sortCostAvoided:B},isOrderSatisfied:C,sortCostAvoided:B}}}class ra{constructor(){N(this,"name","noop")}optimize(t){var g,_;const n=[t.table,...((g=t.joinedTables)==null?void 0:g.map(I=>I.table))??[]],s=n.length,i=ne(t.filters),r=Sn(i),o=new Map,a=[];for(let I=0;I<s;I++)o.set(I,[]);for(const I of r){const p=wn(I,n);if(p.size===1){const y=p.values().next().value;y!==void 0&&((_=o.get(y))==null||_.push(I))}else a.push(I)}const c=me(n[0],o.get(0)??[]),l=[c.scanType],u=[c.indexName];let d=c.cost;const h=c.rows;if(t.joinedTables)for(let I=1;I<s;I++){const p=t.joinedTables[I-1],y=Zs(p,n[I],I,n,I);y?(l.push("IndexScan"),u.push(y.index.name),d+=h*.55):(l.push("TableScan"),u.push(void 0),d+=h*(2+(n[I].rowCountEstimate||10)*.1))}const f=Kn(t,n);return{plan:{...t,selectExprs:f},orderedTables:n,metrics:{totalCost:d,estimatedRows:h,joinOrder:n.map(I=>I.name),singleTableFilters:o,crossFilters:a,tableScanTypes:l,tableIndexNames:u}}}}class Sc{constructor(t){N(this,"name","custom-order");N(this,"orderSpec");this.orderSpec=t}optimize(t){var w,C,B;const n=[t.table,...((w=t.joinedTables)==null?void 0:w.map(P=>P.table))??[]],s=n.length,i=t.joinedTables!==void 0&&t.joinedTables.length>0,r=ne(t.filters),o=Sn(r),a=new Map,c=[];for(let P=0;P<s;P++)a.set(P,[]);for(const P of o){const U=wn(P,n);if(U.size===1){const Q=U.values().next().value;Q!==void 0&&((C=a.get(Q))==null||C.push(P))}else c.push(P)}if(!i||s<=1){const P=me(n[0],a.get(0)??[]);return{plan:t,orderedTables:n,metrics:{totalCost:P.cost,estimatedRows:P.rows,joinOrder:[n[0].name],singleTableFilters:a,crossFilters:c,tableScanTypes:[P.scanType],tableIndexNames:[P.indexName]}}}const l=Array.from({length:s},(P,U)=>U);if(this.orderSpec){if(typeof this.orderSpec=="function"){const P=this.orderSpec;l.sort((U,Q)=>P(n[U],n[Q]))}else if(Array.isArray(this.orderSpec)){const P=this.orderSpec;l.sort((U,Q)=>{const R=n[U].name,A=n[Q].name,b=P.indexOf(R),k=P.indexOf(A),V=b===-1?9999:b,j=k===-1?9999:k;return V!==j?V-j:U-Q})}}const{edges:u}=Hs(t,n),d=l.map(P=>n[P]),h=Vs(l,n,u,t.joinedTables),f=Kn(t,n),g={...t,table:d[0],joinedTables:h,selectExprs:f},_=new Map;for(let P=0;P<s;P++)_.set(P,[]);for(const P of o){const U=wn(P,d);if(U.size===1){const Q=U.values().next().value;Q!==void 0&&((B=_.get(Q))==null||B.push(P))}}const I=me(d[0],_.get(0)??[]),p=[I.scanType],y=[I.indexName];let T=I.cost;const O=I.rows;if(g.joinedTables)for(let P=1;P<s;P++){const U=g.joinedTables[P-1],Q=Zs(U,d[P],P,d,P);Q?(p.push("IndexScan"),y.push(Q.index.name),T+=O*.55):(p.push("TableScan"),y.push(void 0),T+=O*(2+(d[P].rowCountEstimate||10)*.1))}return{plan:g,orderedTables:d,metrics:{totalCost:T,estimatedRows:O,joinOrder:d.map(P=>P.name),singleTableFilters:_,crossFilters:c,tableScanTypes:p,tableIndexNames:y}}}}class oa{constructor(t){N(this,"name","custom");this.fn=t}optimize(t){return this.fn(t)}}const Uc=oa,Oc=$s,Pc=$s,bc=ia,Nc=ra,Lc=new $s;function ur(e){return e??Lc}function Bc(e,t){return ur(t).optimize(e)}function Jn(e){if(!e)return m.OP_EQ;switch(String(e).trim().toLowerCase().replace(/\s+/g," ")){case"=":case"==":return m.OP_EQ;case"!=":case"<>":return m.OP_NE;case">":return m.OP_GT;case">=":return m.OP_GE;case"<":return m.OP_LT;case"<=":return m.OP_LE;case"like":return m.OP_STR_LIKE;case"not like":return m.OP_STR_NOT_LIKE;case"contains":return m.OP_STR_CONTAINS;case"starts_with":return m.OP_STR_STARTS_WITH;case"ends_with":return m.OP_STR_ENDS_WITH;default:return m.OP_EQ}}class xs{constructor(){N(this,"buffer",[]);N(this,"textEncoder",new TextEncoder)}emitUint8(t){const n=this.buffer.length;return this.buffer.push(t&255),n}emitUint16(t){const n=this.buffer.length;return this.buffer.push(t&255),this.buffer.push(t>>8&255),n}emitUint32(t){const n=this.buffer.length;return this.buffer.push(t&255),this.buffer.push(t>>8&255),this.buffer.push(t>>16&255),this.buffer.push(t>>24&255),n}emitInt32(t){return this.emitUint32(t)}emitFloat64(t){const n=this.buffer.length,s=new ArrayBuffer(8);new DataView(s).setFloat64(0,t,!0);const i=new Uint8Array(s);for(let r=0;r<8;r++)this.buffer.push(i[r]);return n}emitString(t){const n=this.textEncoder.encode(t),s=this.emitUint16(n.byteLength);for(let i=0;i<n.byteLength;i++)this.buffer.push(n[i]);return s}emitBytes(t){const n=this.emitUint16(t.byteLength);for(let s=0;s<t.byteLength;s++)this.buffer.push(t[s]);return n}patchUint16(t,n){this.buffer[t]=n&255,this.buffer[t+1]=n>>8&255}currentOffset(){return this.buffer.length}toByteArray(){return new Uint8Array(this.buffer)}}function Lt(e,t,n,s,i){i===S.INT32||i===S.INT64?(e.emitUint8(m.OP_COLUMN_INT),e.emitUint8(t),e.emitUint8(n),e.emitUint8(s)):i===S.FLOAT64?(e.emitUint8(m.OP_COLUMN_FLOAT),e.emitUint8(t),e.emitUint8(n),e.emitUint8(s)):i===S.TEXT?(e.emitUint8(m.OP_COLUMN_TEXT),e.emitUint8(t),e.emitUint8(n),e.emitUint8(s)):i===S.UUID?(e.emitUint8(m.OP_COLUMN_UUID),e.emitUint8(t),e.emitUint8(n),e.emitUint8(s)):i===S.ULID?(e.emitUint8(m.OP_COLUMN_ULID),e.emitUint8(t),e.emitUint8(n),e.emitUint8(s)):i===S.BLOB&&(e.emitUint8(m.OP_COLUMN_BLOB),e.emitUint8(t),e.emitUint8(n),e.emitUint8(s))}function Re(e){if(e.type==="in"){if(e.values&&e.values.length>Qt)throw new RangeError(`WebDB: whereIn list exceeds maximum limit of ${Qt} elements`);return{type:"in",colName:e.colName,expr:e.expr,values:e.values?Array.from(new Set(e.values)):[],notIn:!!e.notIn}}if(e.type==="cmp"){const t=e.op?String(e.op).trim().toLowerCase():"";if(t==="in"||t==="not in"){const n=Array.isArray(e.value)?e.value:[e.value];if(n.length>Qt)throw new RangeError(`WebDB: whereIn list exceeds maximum limit of ${Qt} elements`);return{type:"in",colName:e.colName,expr:e.expr,values:Array.from(new Set(n)),notIn:t==="not in"}}}if(e.type==="and")return{type:"and",children:e.children?e.children.map(Re):[]};if(e.type==="or")return{type:"or",children:e.children?e.children.map(Re):[]};if(e.type==="not"){const t=e.child;if(!t)return e;if(t.type==="not"&&t.child)return Re(t.child);if(t.type==="in")return{type:"in",colName:t.colName,expr:t.expr,values:t.values,notIn:!t.notIn};if(t.type==="and")return{type:"or",children:t.children?t.children.map(n=>Re({type:"not",child:n})):[]};if(t.type==="or")return{type:"and",children:t.children?t.children.map(n=>Re({type:"not",child:n})):[]};if(t.type==="null")return{type:"null",colName:t.colName,expr:t.expr,isNull:!t.isNull};if(t.type==="cmp"){const n=t.op?String(t.op).trim().toLowerCase():"";if(n==="in"||n==="not in")return Re({type:"in",colName:t.colName,expr:t.expr,values:Array.isArray(t.value)?t.value:[t.value],notIn:n==="in"});const s={"=":"!=","!=":"=",">":"<=",">=":"<","<":">=","<=":">",like:"not like","not like":"like"};return t.op&&s[t.op]?{type:"cmp",colName:t.colName,op:s[t.op],value:t.value}:{type:"and",children:[{type:"null",colName:t.colName,isNull:!1},{type:"not",child:t}]}}}return e}function ne(e){if(!e||e.length===0)return null;const t=e.length===1?e[0]:{type:"and",children:e};return Re(t)}function aa(e){const t=[],n=new Set;function s(i){if(i.type==="null"||i.type==="cmp"||i.type==="expr"||i.type==="in")n.has(i)||(n.add(i),t.push(i));else if(i.type==="and"||i.type==="or"){if(i.children)for(const r of i.children)s(r)}else i.type==="not"&&i.child&&s(i.child)}return s(e),t}function Sn(e){if(!e)return[];const t=[];function n(s){if(s.type==="and"&&s.children)for(const i of s.children)n(i);else(s.type==="cmp"||s.type==="in"||s.type==="null")&&t.push(s)}return n(e),t}function gt(e,t){if(e.includes(".")){const n=e.split("."),s=n[0],i=n[1],r=t.findIndex(a=>a.name.toLowerCase()===s.toLowerCase());if(r===-1)return null;const o=t[r].columns.findIndex(a=>a.name.toLowerCase()===i.toLowerCase());return o===-1?null:{tableIdx:r,cursor:r,colIdx:o,col:t[r].columns[o],table:t[r]}}for(let n=0;n<t.length;n++){const s=t[n].columns.findIndex(i=>i.name.toLowerCase()===e.toLowerCase());if(s!==-1)return{tableIdx:n,cursor:n,colIdx:s,col:t[n].columns[s],table:t[n]}}return null}function fr(e,t,n,s,i,r,o,a){const c=o??[n];if(e.type==="expr"){const h=t*2,f=t*2+1;let g=50;const _=()=>{if(g>=64)throw new st(g);return g++};Z(e.expr,n,s,0,h,_,r,void 0,c),s.emitUint8(m.OP_LOAD_INT),s.emitUint8(f),s.emitInt32(1),s.emitUint8(m.OP_EQ),s.emitUint8(h),s.emitUint8(f),i.push(s.emitUint16(0));return}if(e.type==="null"){if(e.expr){const f=t*2;let g=50;const _=()=>{if(g>=64)throw new st(g);return g++};Z(e.expr,n,s,0,f,_,r,void 0,c),e.isNull?s.emitUint8(m.OP_REG_IS_NULL):s.emitUint8(m.OP_REG_IS_NOT_NULL),s.emitUint8(f),i.push(s.emitUint16(0));return}if(!e.colName)throw new Error("Filter leaf node missing colName");const h=gt(e.colName,c);if(!h)throw new Error(`Column "${e.colName}" not found in tables`);e.isNull?s.emitUint8(m.OP_IS_NULL):s.emitUint8(m.OP_IS_NOT_NULL),s.emitUint8(h.cursor),s.emitUint8(h.colIdx),i.push(s.emitUint16(0));return}if(e.type==="in"){if(!e.values||e.values.length===0){e.notIn&&(s.emitUint8(m.OP_JUMP),i.push(s.emitUint16(0)));return}const h=t*2;if(e.expr){let g=50;const _=()=>{if(g>=64)throw new st(g);return g++};Z(e.expr,n,s,0,h,_,r,void 0,c)}else{if(!e.colName)throw new Error("Filter IN leaf node missing colName");const g=gt(e.colName,c);if(g)Lt(s,g.cursor,g.colIdx,h,g.col.type);else try{const _=At(e.colName);let I=50;Z(_,n,s,0,h,()=>{if(I>=64)throw new st(I);return I++},r,void 0,c)}catch{throw new Error(`Column "${e.colName}" not found in tables`)}}const f=(a==null?void 0:a.get(e))??0;if(!e.notIn)s.emitUint8(m.OP_IN),s.emitUint8(h),s.emitUint16(f),i.push(s.emitUint16(0));else{let g=-1;if(e.colName){const p=gt(e.colName,c);p&&(s.emitUint8(m.OP_IS_NULL),s.emitUint8(p.cursor),s.emitUint8(p.colIdx),g=s.emitUint16(0))}s.emitUint8(m.OP_IN),s.emitUint8(h),s.emitUint16(f);const _=s.emitUint16(0);s.emitUint8(m.OP_JUMP),i.push(s.emitUint16(0));const I=s.currentOffset();g!==-1&&s.patchUint16(g,I),s.patchUint16(_,I)}return}const l=t*2,u=t*2+1;if(e.expr){let h=50;const f=()=>{if(h>=64)throw new st(h);return h++};Z(e.expr,n,s,0,l,f,r,void 0,c)}else{if(!e.colName)throw new Error("Filter leaf node missing colName");const h=gt(e.colName,c);if(h)Lt(s,h.cursor,h.colIdx,l,h.col.type);else try{const f=At(e.colName);let g=50;Z(f,n,s,0,l,()=>{if(g>=64)throw new st(g);return g++},r,void 0,c)}catch{throw new Error(`Column "${e.colName}" not found in tables`)}}const d=Jn(e.op);s.emitUint8(d),s.emitUint8(l),s.emitUint8(u),i.push(s.emitUint16(0))}function Ar(e,t,n,s,i,r,o,a){const c=o??[n];if(e.type==="expr"){const f=t*2,g=t*2+1;let _=50;const I=()=>{if(_>=64)throw new st(_);return _++};Z(e.expr,n,s,0,f,I,r,void 0,c),s.emitUint8(m.OP_LOAD_INT),s.emitUint8(g),s.emitInt32(1),s.emitUint8(m.OP_EQ),s.emitUint8(f),s.emitUint8(g);const p=s.emitUint16(0);s.emitUint8(m.OP_JUMP),i.push(s.emitUint16(0)),s.patchUint16(p,s.currentOffset());return}if(e.type==="null"){if(e.expr){const g=t*2;let _=50;const I=()=>{if(_>=64)throw new st(_);return _++};Z(e.expr,n,s,0,g,I,r,void 0,c),e.isNull?s.emitUint8(m.OP_REG_IS_NOT_NULL):s.emitUint8(m.OP_REG_IS_NULL),s.emitUint8(g),i.push(s.emitUint16(0));return}if(!e.colName)throw new Error("Filter leaf node missing colName");const f=gt(e.colName,c);if(!f)throw new Error(`Column "${e.colName}" not found in tables`);e.isNull?s.emitUint8(m.OP_IS_NOT_NULL):s.emitUint8(m.OP_IS_NULL),s.emitUint8(f.cursor),s.emitUint8(f.colIdx),i.push(s.emitUint16(0));return}if(e.type==="in"){if(!e.values||e.values.length===0){e.notIn||(s.emitUint8(m.OP_JUMP),i.push(s.emitUint16(0)));return}const f=t*2;if(e.expr){let _=50;const I=()=>{if(_>=64)throw new st(_);return _++};Z(e.expr,n,s,0,f,I,r,void 0,c)}else{if(!e.colName)throw new Error("Filter IN leaf node missing colName");const _=gt(e.colName,c);if(_)Lt(s,_.cursor,_.colIdx,f,_.col.type);else try{const I=At(e.colName);let p=50;Z(I,n,s,0,f,()=>{if(p>=64)throw new st(p);return p++},r,void 0,c)}catch{throw new Error(`Column "${e.colName}" not found in tables`)}}const g=(a==null?void 0:a.get(e))??0;if(e.notIn){if(e.colName){const _=gt(e.colName,c);_&&(s.emitUint8(m.OP_IS_NULL),s.emitUint8(_.cursor),s.emitUint8(_.colIdx),i.push(s.emitUint16(0)))}s.emitUint8(m.OP_IN),s.emitUint8(f),s.emitUint16(g),i.push(s.emitUint16(0))}else{if(e.colName){const p=gt(e.colName,c);p&&(s.emitUint8(m.OP_IS_NULL),s.emitUint8(p.cursor),s.emitUint8(p.colIdx),i.push(s.emitUint16(0)))}s.emitUint8(m.OP_IN),s.emitUint8(f),s.emitUint16(g);const _=s.emitUint16(0);s.emitUint8(m.OP_JUMP),i.push(s.emitUint16(0));const I=s.currentOffset();s.patchUint16(_,I)}return}const l=t*2,u=t*2+1;if(e.expr){let f=50;const g=()=>{if(f>=64)throw new st(f);return f++};Z(e.expr,n,s,0,l,g,r,void 0,c)}else{if(!e.colName)throw new Error("Filter leaf node missing colName");const f=gt(e.colName,c);if(f)Lt(s,f.cursor,f.colIdx,l,f.col.type);else try{const g=At(e.colName);let _=50;Z(g,n,s,0,l,()=>{if(_>=64)throw new st(_);return _++},r,void 0,c)}catch{throw new Error(`Column "${e.colName}" not found in tables`)}}const d=Jn(e.op);s.emitUint8(d),s.emitUint8(l),s.emitUint8(u);const h=s.emitUint16(0);s.emitUint8(m.OP_JUMP),i.push(s.emitUint16(0)),s.patchUint16(h,s.currentOffset())}function Rc(e,t,n,s,i,r,o,a,c,l){o==="true"?Ar(e,t,n,s,r,a,c,l):o==="false"?fr(e,t,n,s,i,a,c,l):(fr(e,t,n,s,i,a,c,l),s.emitUint8(m.OP_JUMP),r.push(s.emitUint16(0)))}function zn(e,t,n,s,i,r,o,a,c,l){if(e.type==="cmp"||e.type==="null"||e.type==="expr"||e.type==="in"){const u=s.get(e)??0;Rc(e,u,n,t,i,r,o,a,c,l);return}if(e.type==="not"){if(!e.child)return;const u=e.child,d=s.get(u)??0;o==="true"?fr(u,d,n,t,r,a,c,l):o==="false"?Ar(u,d,n,t,i,a,c,l):(Ar(u,d,n,t,i,a,c,l),t.emitUint8(m.OP_JUMP),r.push(t.emitUint16(0)));return}if(e.type==="and"){const u=e.children??[];if(u.length===0){o==="false"&&(t.emitUint8(m.OP_JUMP),i.push(t.emitUint16(0)));return}for(let d=0;d<u.length;d++){const h=u[d];if(d===u.length-1)zn(h,t,n,s,i,r,o,a,c,l);else{const g=[];zn(h,t,n,s,g,r,"true",a,c,l);const _=t.currentOffset();for(const I of g)t.patchUint16(I,_)}}return}if(e.type==="or"){const u=e.children??[];if(u.length===0){o==="true"&&(t.emitUint8(m.OP_JUMP),r.push(t.emitUint16(0)));return}for(let d=0;d<u.length;d++){const h=u[d];if(d===u.length-1)zn(h,t,n,s,i,r,o,a,c,l);else{const g=[];zn(h,t,n,s,i,g,"false",a,c,l);const _=t.currentOffset();for(const I of g)t.patchUint16(I,_)}}return}}function Fc(e,t,n,s,i,r,o){if(e.type==="cmp"){let a;const c=s(e.colName,e.expr);if(c!==void 0)a=c;else if(e.expr)a=i(),Z(e.expr,t,n,-1,a,i,o,s);else if(e.colName){a=i();const f=At(e.colName);Z(f,t,n,-1,a,i,o,s)}else a=i(),n.emitUint8(m.OP_LOAD_NULL),n.emitUint8(a);const l=i(),u=e.value;u==null?(n.emitUint8(m.OP_LOAD_NULL),n.emitUint8(l)):typeof u=="number"?Number.isInteger(u)?(n.emitUint8(m.OP_LOAD_INT),n.emitUint8(l),n.emitInt32(u)):(n.emitUint8(m.OP_LOAD_FLOAT),n.emitUint8(l),n.emitFloat64(u)):typeof u=="string"?(n.emitUint8(m.OP_LOAD_TEXT),n.emitUint8(l),n.emitString(u)):typeof u=="boolean"?(n.emitUint8(m.OP_LOAD_INT),n.emitUint8(l),n.emitInt32(u?1:0)):typeof u=="bigint"&&(n.emitUint8(m.OP_LOAD_INT),n.emitUint8(l),n.emitInt32(Number(u)));const d=Jn(e.op);n.emitUint8(d),n.emitUint8(a),n.emitUint8(l);const h=n.emitUint16(0);n.emitUint8(m.OP_JUMP),r.push(n.emitUint16(0)),n.patchUint16(h,n.currentOffset());return}if(e.type==="null"){let a;const c=s(e.colName,e.expr);if(c!==void 0)a=c;else if(e.expr)a=i(),Z(e.expr,t,n,-1,a,i,o,s);else if(e.colName){a=i();const l=At(e.colName);Z(l,t,n,-1,a,i,o,s)}else a=i(),n.emitUint8(m.OP_LOAD_NULL),n.emitUint8(a);e.isNull?(n.emitUint8(m.OP_REG_IS_NOT_NULL),n.emitUint8(a),r.push(n.emitUint16(0))):(n.emitUint8(m.OP_REG_IS_NULL),n.emitUint8(a),r.push(n.emitUint16(0)));return}if(e.type==="expr"&&e.expr){const a=i();Z(e.expr,t,n,-1,a,i,o,s);const c=i();n.emitUint8(m.OP_LOAD_INT),n.emitUint8(c),n.emitInt32(1),n.emitUint8(m.OP_EQ),n.emitUint8(a),n.emitUint8(c);const l=n.emitUint16(0);n.emitUint8(m.OP_JUMP),r.push(n.emitUint16(0)),n.patchUint16(l,n.currentOffset());return}}function la(e,t,n,s,i,r,o){if(e.type==="cmp"){let a;const c=s(e.colName,e.expr);if(c!==void 0)a=c;else if(e.expr)a=i(),Z(e.expr,t,n,-1,a,i,o,s);else if(e.colName){a=i();const h=At(e.colName);Z(h,t,n,-1,a,i,o,s)}else a=i(),n.emitUint8(m.OP_LOAD_NULL),n.emitUint8(a);const l=i(),u=e.value;u==null?(n.emitUint8(m.OP_LOAD_NULL),n.emitUint8(l)):typeof u=="number"?Number.isInteger(u)?(n.emitUint8(m.OP_LOAD_INT),n.emitUint8(l),n.emitInt32(u)):(n.emitUint8(m.OP_LOAD_FLOAT),n.emitUint8(l),n.emitFloat64(u)):typeof u=="string"?(n.emitUint8(m.OP_LOAD_TEXT),n.emitUint8(l),n.emitString(u)):typeof u=="boolean"?(n.emitUint8(m.OP_LOAD_INT),n.emitUint8(l),n.emitInt32(u?1:0)):typeof u=="bigint"&&(n.emitUint8(m.OP_LOAD_INT),n.emitUint8(l),n.emitInt32(Number(u)));const d=Jn(e.op);n.emitUint8(d),n.emitUint8(a),n.emitUint8(l),r.push(n.emitUint16(0));return}if(e.type==="null"){let a;const c=s(e.colName,e.expr);if(c!==void 0)a=c;else if(e.expr)a=i(),Z(e.expr,t,n,-1,a,i,o,s);else if(e.colName){a=i();const l=At(e.colName);Z(l,t,n,-1,a,i,o,s)}else a=i(),n.emitUint8(m.OP_LOAD_NULL),n.emitUint8(a);e.isNull?(n.emitUint8(m.OP_REG_IS_NULL),n.emitUint8(a),r.push(n.emitUint16(0))):(n.emitUint8(m.OP_REG_IS_NOT_NULL),n.emitUint8(a),r.push(n.emitUint16(0)));return}if(e.type==="expr"&&e.expr){const a=i();Z(e.expr,t,n,-1,a,i,o,s);const c=i();n.emitUint8(m.OP_LOAD_INT),n.emitUint8(c),n.emitInt32(1),n.emitUint8(m.OP_EQ),n.emitUint8(a),n.emitUint8(c),r.push(n.emitUint16(0));return}}function Dc(e,t,n,s,i,r,o,a,c){a==="true"?Fc(e,t,n,s,i,o,c):a==="false"?la(e,t,n,s,i,r,c):(la(e,t,n,s,i,r,c),n.emitUint8(m.OP_JUMP),o.push(n.emitUint16(0)))}function Fe(e,t,n,s,i,r,o,a,c){if(e.type==="cmp"||e.type==="null"||e.type==="expr"){Dc(e,n,t,s,i,r,o,a,c);return}if(e.type==="not"){if(!e.child)return;const l=e.child;a==="true"?Fe(l,t,n,s,i,o,r,"false",c):a==="false"?Fe(l,t,n,s,i,r,o,"true",c):Fe(l,t,n,s,i,o,r,"none",c);return}if(e.type==="and"){const l=e.children??[];if(l.length===0){a==="false"&&(t.emitUint8(m.OP_JUMP),r.push(t.emitUint16(0)));return}for(let u=0;u<l.length;u++){const d=l[u];if(u===l.length-1)Fe(d,t,n,s,i,r,o,a,c);else{const f=[];Fe(d,t,n,s,i,f,o,"true",c);const g=t.currentOffset();for(const _ of f)t.patchUint16(_,g)}}return}if(e.type==="or"){const l=e.children??[];if(l.length===0){a==="true"&&(t.emitUint8(m.OP_JUMP),o.push(t.emitUint16(0)));return}for(let u=0;u<l.length;u++){const d=l[u];if(u===l.length-1)Fe(d,t,n,s,i,r,o,a,c);else{const f=[];Fe(d,t,n,s,i,r,f,"false",c);const g=t.currentOffset();for(const _ of f)t.patchUint16(_,g)}}return}}function Qc(e,t,n,s,i,r,o){if(!e)return;const a=[];Fe(e,n,t,s,i,a,r,"true",o);const c=n.currentOffset();for(const l of a)n.patchUint16(l,c)}function se(e,t,n,s,i,r,o,a){if(!e)return;const c=[];zn(e,n,t,s,c,i,"true",r,o,a);const l=n.currentOffset();for(const u of c)n.patchUint16(u,l)}function ca(e,t,n,s){if(e.type==="literal")return typeof e.value=="number"?Number.isInteger(e.value)?S.INT32:S.FLOAT64:(typeof e.value=="string",S.TEXT);if(e.type==="col"){const i=s??[t],r=gt(e.name,i);return r?r.col.type:S.TEXT}if(e.type==="binary")return S.FLOAT64;if(e.type==="fn"){const i=e.name.toLowerCase();if(n&&n.has(i)){const r=n.get(i);if(r.returnType!==void 0)return r.returnType}if(["upper","lower","substr","trim","concat"].includes(i))return S.TEXT;if(["length","count","starts_with","startswith","ends_with","endswith","like","contains"].includes(i))return S.INT32;if(["abs","round","floor","ceil","sum","avg","min","max"].includes(i)){if(e.args.length>0&&e.args[0].type==="col"){const r=gt(e.args[0].name,s??[t]);if(r&&r.col.type===S.INT32&&i!=="avg")return S.INT32}return S.FLOAT64}return S.TEXT}return S.TEXT}function Z(e,t,n,s,i,r,o,a,c){if(a){const l=e.type==="col"?e.name:void 0,u=a(l,e);if(u!==void 0){u!==i&&(n.emitUint8(m.OP_COPY),n.emitUint8(u),n.emitUint8(i));return}}if(e.type==="literal"){const l=e.value;l==null?(n.emitUint8(m.OP_LOAD_NULL),n.emitUint8(i)):typeof l=="number"?Number.isInteger(l)?(n.emitUint8(m.OP_LOAD_INT),n.emitUint8(i),n.emitInt32(l)):(n.emitUint8(m.OP_LOAD_FLOAT),n.emitUint8(i),n.emitFloat64(l)):typeof l=="string"?(n.emitUint8(m.OP_LOAD_TEXT),n.emitUint8(i),n.emitString(l)):typeof l=="boolean"&&(n.emitUint8(m.OP_LOAD_INT),n.emitUint8(i),n.emitInt32(l?1:0));return}if(e.type==="col"){if(s===-1)throw new Error(`Column "${e.name}" in HAVING clause must be an aggregate or grouping column`);const l=c??[t],u=gt(e.name,l);if(!u){if(e.name==="*"){n.emitUint8(m.OP_LOAD_NULL),n.emitUint8(i);return}throw new Error(`Column "${e.name}" does not exist in table "${t.name}"`)}Lt(n,u.cursor,u.colIdx,i,u.col.type);return}if(e.type==="binary"){const l=r(),u=r();Z(e.left,t,n,s,l,r,o,a,c),Z(e.right,t,n,s,u,r,o,a,c);let d=m.OP_ADD;if(e.op==="+")d=m.OP_ADD;else if(e.op==="-")d=m.OP_SUB;else if(e.op==="*")d=m.OP_MUL;else if(e.op==="/")d=m.OP_DIV;else if(e.op==="%")d=m.OP_MOD;else if(e.op==="="||e.op==="!="||e.op==="<"||e.op==="<="||e.op===">"||e.op===">="){let h=m.OP_EQ;e.op==="="?h=m.OP_EQ:e.op==="!="?h=m.OP_NE:e.op==="<"?h=m.OP_LT:e.op==="<="?h=m.OP_LE:e.op===">"?h=m.OP_GT:e.op===">="&&(h=m.OP_GE),n.emitUint8(h),n.emitUint8(l),n.emitUint8(u);const f=n.emitUint16(0);n.emitUint8(m.OP_LOAD_INT),n.emitUint8(i),n.emitInt32(0),n.emitUint8(m.OP_JUMP);const g=n.emitUint16(0);n.patchUint16(f,n.currentOffset()),n.emitUint8(m.OP_LOAD_INT),n.emitUint8(i),n.emitInt32(1),n.patchUint16(g,n.currentOffset());return}n.emitUint8(d),n.emitUint8(l),n.emitUint8(u),n.emitUint8(i);return}if(e.type==="fn"){const l=e.name.toLowerCase(),u={upper:m.OP_STR_UPPER,lower:m.OP_STR_LOWER,length:m.OP_STR_LENGTH,trim:m.OP_STR_TRIM,abs:m.OP_MATH_ABS,round:m.OP_MATH_ROUND,floor:m.OP_MATH_FLOOR,ceil:m.OP_MATH_CEIL};if(u[l]){const h=r(),f=e.args[0]??{type:"literal",value:null};Z(f,t,n,s,h,r,o,a,c),n.emitUint8(u[l]),n.emitUint8(h),n.emitUint8(i);return}if(l==="substr"){const h=r(),f=r(),g=r();Z(e.args[0],t,n,s,h,r,o,a,c),Z(e.args[1]??{type:"literal",value:1},t,n,s,f,r,o,a,c),e.args[2]!==void 0?Z(e.args[2],t,n,s,g,r,o,a,c):(n.emitUint8(m.OP_LOAD_NULL),n.emitUint8(g)),n.emitUint8(m.OP_STR_SUBSTR),n.emitUint8(h),n.emitUint8(f),n.emitUint8(g),n.emitUint8(i);return}const d={starts_with:m.OP_STR_STARTS_WITH,startswith:m.OP_STR_STARTS_WITH,ends_with:m.OP_STR_ENDS_WITH,endswith:m.OP_STR_ENDS_WITH,like:m.OP_STR_LIKE,contains:m.OP_STR_CONTAINS};if(d[l]){const h=r(),f=r();Z(e.args[0]??{type:"literal",value:null},t,n,s,h,r,o,a,c),Z(e.args[1]??{type:"literal",value:""},t,n,s,f,r,o,a,c),n.emitUint8(d[l]),n.emitUint8(h),n.emitUint8(f);const g=n.emitUint16(0);n.emitUint8(m.OP_LOAD_INT),n.emitUint8(i),n.emitInt32(0),n.emitUint8(m.OP_JUMP);const _=n.emitUint16(0);n.patchUint16(g,n.currentOffset()),n.emitUint8(m.OP_LOAD_INT),n.emitUint8(i),n.emitInt32(1),n.patchUint16(_,n.currentOffset());return}if(l==="concat"||l==="coalesce"){const h=e.args.length,f=r();for(let _=1;_<h;_++)r();for(let _=0;_<h;_++)Z(e.args[_],t,n,s,f+_,r,o,a,c);const g=l==="concat"?m.OP_STR_CONCAT:m.OP_COALESCE;n.emitUint8(g),n.emitUint8(f),n.emitUint8(h),n.emitUint8(i);return}if(o&&o.has(l)){const h=o.get(l),f=e.args.length;let g=i;if(f>0){g=r();for(let _=1;_<f;_++)r();for(let _=0;_<f;_++)Z(e.args[_],t,n,s,g+_,r,o,a,c)}n.emitUint8(m.OP_CALL_UDF),n.emitUint16(h),n.emitUint8(g),n.emitUint8(f),n.emitUint8(i);return}throw new Pi(l)}}function hr(e,t,n,s){n==null?(e.emitUint8(m.OP_LOAD_NULL),e.emitUint8(t)):typeof n=="number"?s===S.FLOAT64||!Number.isInteger(n)?(e.emitUint8(m.OP_LOAD_FLOAT),e.emitUint8(t),e.emitFloat64(n)):(e.emitUint8(m.OP_LOAD_INT),e.emitUint8(t),e.emitInt32(Math.floor(n))):typeof n=="bigint"?(e.emitUint8(m.OP_LOAD_INT),e.emitUint8(t),e.emitInt32(Number(n))):typeof n=="string"?(e.emitUint8(m.OP_LOAD_TEXT),e.emitUint8(t),e.emitString(n)):typeof n=="boolean"&&(e.emitUint8(m.OP_LOAD_INT),e.emitUint8(t),e.emitInt32(n?1:0))}function Xs(e){switch(e){case S.INT32:return-2147483648;case S.INT64:return-9223372036854775808n;case S.FLOAT64:return-1/0;case S.TEXT:case S.UUID:case S.ULID:return"";case S.BLOB:return new Uint8Array(0);default:return 0}}function gr(e,t,n,s){var a;if(!n||n.length===0)return!1;for(const c of n)if(c.direction==="desc")return!1;const i=e.columnIndices.map(c=>t.columns[c].name.toLowerCase());let r=0;if(s&&s.size>0)for(;r<i.length&&s.has(i[r]);)r++;let o=0;for(;r<i.length&&o<n.length;){const c=(a=n[o].colName)==null?void 0:a.toLowerCase();if(!c||c!==i[r])return!1;r++,o++}return o===n.length}function ua(e,t,n,s,i){if(!n||n.length===0)return!1;for(const r of n){if(r.direction==="desc")return!1;const o=r.colName;if(!o)return!1;if(s&&s.length>0){let a=gt(o,s);if(!a&&i){const c=i.find(l=>l.alias===o);c&&c.expr.type==="col"&&(a=gt(c.expr.name,s))}if(!a||a.tableIdx!==0)return!1}else{const a=o.includes(".")?o.slice(o.lastIndexOf(".")+1):o;if(!e.columns.some(l=>l.name.toLowerCase()===a.toLowerCase()))return!1}}return!0}function Ys(e,t,n,s){if(!e.indexes||e.indexes.length===0)return null;const i=n??t,r=new Set;for(const a of t)a.type==="cmp"&&(a.op==="="||a.op===void 0)&&a.colName&&a.value!==void 0&&a.value!==null&&r.add(a.colName.toLowerCase());const o=a=>{if(s&&s.length>0){if(a.scanType==="point"&&a.index.flags&(rt.PRIMARY|rt.UNIQUE))a.satisfiesOrderBy=!0;else if(gr(a.index,e,s,r)){if(a.scanType==="multi_point"&&a.inValues){const c=s[0].direction==="desc"?-1:1;a.inValues.sort((l,u)=>typeof l=="number"&&typeof u=="number"?(l-u)*c:String(l).localeCompare(String(u))*c)}a.satisfiesOrderBy=!0}}return a};for(const a of e.indexes)if(a.flags&rt.PRIMARY&&a.columnCount===1){const c=e.columns[a.columnIndices[0]];for(let l=0;l<t.length;l++){const u=t[l];if(u.type==="cmp"&&(u.op==="="||u.op===void 0)&&u.colName===c.name&&u.value!==void 0&&u.value!==null)return o({index:a,scanType:"point",seekFilter:u,filterIndex:i.indexOf(u),keyType:c.type});if(u.type==="in"&&!u.notIn&&u.colName===c.name&&Array.isArray(u.values)&&u.values.length>0){const d=Array.from(new Set(u.values.filter(h=>h!=null)));return o({index:a,scanType:"multi_point",seekFilter:u,filterIndex:i.indexOf(u),keyType:c.type,inValues:d})}}}for(const a of e.indexes)if(a.flags&rt.UNIQUE&&a.columnCount===1){const c=e.columns[a.columnIndices[0]];for(let l=0;l<t.length;l++){const u=t[l];if(u.type==="cmp"&&(u.op==="="||u.op===void 0)&&u.colName===c.name&&u.value!==void 0&&u.value!==null)return o({index:a,scanType:"point",seekFilter:u,filterIndex:i.indexOf(u),keyType:c.type});if(u.type==="in"&&!u.notIn&&u.colName===c.name&&Array.isArray(u.values)&&u.values.length>0){const d=Array.from(new Set(u.values.filter(h=>h!=null)));return o({index:a,scanType:"multi_point",seekFilter:u,filterIndex:i.indexOf(u),keyType:c.type,inValues:d})}}}for(const a of e.indexes)if(a.columnCount>1){const c=[];let l=!0;for(let u=0;u<a.columnCount;u++){const d=e.columns[a.columnIndices[u]],h=t.find(f=>f.type==="cmp"&&(f.op==="="||f.op===void 0)&&f.colName===d.name&&f.value!==void 0&&f.value!==null);if(h)c.push(h);else{l=!1;break}}if(l){const u={};for(const h of c)u[h.colName]=h.value;const d=Rs(e.columns,a.columnIndices,a.columnCount,u);return o({index:a,scanType:"point",seekFilter:c[0],filterIndex:i.indexOf(c[0]),keyType:S.BLOB,compositeValue:d})}}for(const a of e.indexes)if(a.columnCount===1){const c=e.columns[a.columnIndices[0]];for(let l=0;l<t.length;l++){const u=t[l];if(u.type==="cmp"&&(u.op==="="||u.op===void 0)&&u.colName===c.name&&u.value!==void 0&&u.value!==null)return o({index:a,scanType:"range",seekFilter:u,filterIndex:i.indexOf(u),keyType:c.type})}}for(const a of e.indexes)if(a.columnCount===1){const c=e.columns[a.columnIndices[0]];for(let l=0;l<t.length;l++){const u=t[l];if(u.type==="cmp"&&(u.op===">="||u.op===">")&&u.colName===c.name&&u.value!==void 0&&u.value!==null)return o({index:a,scanType:"range",seekFilter:u,filterIndex:i.indexOf(u),keyType:c.type})}}if(s&&s.length>0){for(const a of e.indexes)if(gr(a,e,s,r))if(a.columnCount===1){const c=e.columns[a.columnIndices[0]];return{index:a,scanType:"range",seekFilter:void 0,filterIndex:-1,keyType:c.type,satisfiesOrderBy:!0}}else{const c={};for(let u=0;u<a.columnCount;u++){const d=e.columns[a.columnIndices[u]],h=t.find(f=>f.type==="cmp"&&(f.op==="="||f.op===void 0)&&f.colName===d.name&&f.value!==void 0&&f.value!==null);h?c[d.name]=h.value:c[d.name]=Xs(d.type)}const l=Rs(e.columns,a.columnIndices,a.columnCount,c);return{index:a,scanType:"range",seekFilter:void 0,filterIndex:-1,keyType:S.BLOB,compositeValue:l,satisfiesOrderBy:!0}}}return null}function Zs(e,t,n,s,i){if(e.op!=="="||!t.indexes||t.indexes.length===0)return null;const r=gt(e.leftCol,s),o=gt(e.rightCol,s);if(!r||!o)return null;let a=null,c=null;if(r.tableIdx===n&&o.tableIdx<n?(a=r,c=o):o.tableIdx===n&&r.tableIdx<n&&(a=o,c=r),!a||!c)return null;let l=null,u=999;for(const h of t.indexes)if(h.columnCount===1&&h.columnIndices[0]===a.colIdx){const f=(h.flags&rt.PRIMARY)!==0,g=(h.flags&rt.UNIQUE)!==0,_=f?1:g?2:3;_<u&&(u=_,l=h)}if(!l)return null;const d=(l.flags&(rt.PRIMARY|rt.UNIQUE))!==0;return{index:l,isUnique:d,innerCol:a,outerCol:c,indexCursor:i}}function dr(e,t){var zs,Ln,ti,ga,da,_a,ma,Ea,Ia;const n=[e.table,...((zs=e.joinedTables)==null?void 0:zs.map(F=>F.table))??[]],i=ur((t==null?void 0:t.planner)??e.planner).optimize(e),r=i.orderedTables??n,o=i.whereMetrics,a=i.metrics;if(i.isAlwaysFalse){const F=new xs;F.emitUint8(m.OP_HALT);const M=F.toByteArray();return e.outputColumns&&(M.outputColumns=e.outputColumns),M.allTables=r,M.whereMetrics=o,M}const c=i.plan;c!==e&&Object.assign(e,c);const l=e.joinedTables!==void 0&&e.joinedTables.length>0,u=ne(e.filters),d=u?aa(u):[],h=Sn(u),f=Array.from({length:r.length},()=>[]),g=new Set;if(l&&a)for(let F=0;F<r.length;F++){const M=n.indexOf(r[F]);if(M!==-1){const W=a.singleTableFilters.get(M)??[];if(F===0||e.joinedTables&&((Ln=e.joinedTables[F-1])==null?void 0:Ln.type)==="inner"){f[F]=W;for(const $ of W)g.add($)}}}const _=[];for(const F of h)g.has(F)||_.push(F);const I=ne(_),p=l&&ua(r[0],e.joinedTables,e.orderBy,r,e.selectExprs),y=p?e.orderBy.map(F=>{const M=F.colName??"",W=M.includes(".")?M.slice(M.lastIndexOf(".")+1):M;return{...F,colName:W}}):void 0,T=l?Ys(r[0],f[0],d,y):null,O=p&&!!(T!=null&&T.satisfiesOrderBy);let w=r.length,C=-1;T&&w<16&&(C=w++);const B=new Array(r.length).fill(null);if(l&&e.joinedTables)for(let F=1;F<r.length;F++){const M=e.joinedTables[F-1];if(w<16){const W=Zs(M,r[F],F,r,w);W&&(B[F]=W,w++)}}const P=w;if(P>16)throw new ds(P,16);for(const F of h)if(F.type==="in"&&!F.notIn&&(!F.values||F.values.length===0)){const M=new xs;M.emitUint8(m.OP_HALT);const W=M.toByteArray();return e.outputColumns&&(W.outputColumns=e.outputColumns),W}const U=[],Q=new Map;for(const F of d)if(F.type==="in"){const M=U.length;Q.set(F,M);const W=new Set;if(F.values)for(const $ of F.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 F=0;F<d.length;F++)R.set(d[F],F);if(d.length*2>=64)throw new st(d.length*2);if(e.orderBy&&e.orderBy.length>8)throw new jr(e.orderBy.length);if(e.groupBy&&e.groupBy.length>8)throw new Kr(e.groupBy.length);const A=new xs;if(e.limit!==void 0&&e.limit<=0)return A.emitUint8(m.OP_HALT),A.toByteArray();let b=d.length*2;const k=e.offset!==void 0&&e.offset>0,V=e.limit!==void 0&&e.limit>0,j=k?b++:-1,K=V?b++:-1;if(b>=64)throw new st(b);const G=e.table;for(let F=0;F<d.length;F++){const M=d[F];if(M.type==="cmp"){const W=F*2+1,$=M.value;if($==null)A.emitUint8(m.OP_LOAD_NULL),A.emitUint8(W);else if(typeof $=="number"){const mt=M.colName?gt(M.colName,r):void 0;mt&&mt.col.type===S.FLOAT64?(A.emitUint8(m.OP_LOAD_FLOAT),A.emitUint8(W),A.emitFloat64($)):Number.isInteger($)?(A.emitUint8(m.OP_LOAD_INT),A.emitUint8(W),A.emitInt32(Math.floor($))):(A.emitUint8(m.OP_LOAD_FLOAT),A.emitUint8(W),A.emitFloat64($))}else typeof $=="bigint"?(A.emitUint8(m.OP_LOAD_INT),A.emitUint8(W),A.emitInt32(Number($))):typeof $=="string"?(A.emitUint8(m.OP_LOAD_TEXT),A.emitUint8(W),A.emitString($)):typeof $=="boolean"&&(A.emitUint8(m.OP_LOAD_INT),A.emitUint8(W),A.emitInt32($?1:0))}}if(k&&(A.emitUint8(m.OP_LOAD_INT),A.emitUint8(j),A.emitInt32(e.offset)),V&&(A.emitUint8(m.OP_LOAD_INT),A.emitUint8(K),A.emitInt32(e.limit)),e.aggregates&&e.aggregates.length>0||e.groupBy&&e.groupBy.length>0){const F=((ti=e.groupBy)==null?void 0:ti.length)??0,M=e.aggregates??[],W=M.length,$=[];for(const v of e.groupBy??[]){const H=typeof v=="string"?v:v.colName??(v.expr?vt(v.expr):"group_key"),X=(ga=e.selectExprs)==null?void 0:ga.find(ht=>{if(ht.alias===H)return!0;if(typeof v=="object"&&v.expr)return JSON.stringify(ht.expr)===JSON.stringify(v.expr);if(typeof v=="string"&&v.includes("("))try{const zt=At(v);return JSON.stringify(ht.expr)===JSON.stringify(zt)}catch{return!1}return!1}),Y=(X==null?void 0:X.alias)??H,J=G.columns.find(ht=>ht.name===H||ht.name===Y);J?$.push({...J,name:Y}):$.push({name:Y,type:S.TEXT,flags:tt.NONE,colOffset:0})}for(let v=0;v<M.length;v++){const H=M[v],X=H.alias??(H.colName?`${H.func}_${H.colName}`:H.func),Y=H.func==="count"?S.INT32:S.FLOAT64;$.push({name:X,type:Y,flags:tt.NONE,colOffset:0})}const z=b,et=z+F,ot=et+4,Et=ot+4,nt=Et+F,Ot=nt+W;if(Ot>=64)throw new st(Ot);A.emitUint8(m.OP_AGG_INIT),A.emitUint8(0),A.emitUint8(z),A.emitUint8(F),A.emitUint8(0),A.emitUint8(m.OP_OPEN_CURSOR),A.emitUint8(0),A.emitUint32(G.rootPageId),A.emitUint8(m.OP_REWIND),A.emitUint8(0);const Ft=A.emitUint16(0),lt=A.currentOffset(),bt=[];if(se(u,G,A,R,bt,e.udfNameMap,void 0,Q),e.groupBy)for(let v=0;v<e.groupBy.length;v++){const H=e.groupBy[v],X=z+v;let Y=Math.max(Ot+4,40);const J=()=>{if(Y>=64)throw new st(Y);return Y++};if(typeof H=="object"&&H.expr)Z(H.expr,G,A,0,X,J,e.udfNameMap);else{const ht=typeof H=="string"?H:H.colName,zt=(_a=(da=e.selectExprs)==null?void 0:da.find(pt=>pt.alias===ht))==null?void 0:_a.expr;if(zt)Z(zt,G,A,0,X,J,e.udfNameMap);else{const pt=G.columns.findIndex(Dt=>Dt.name===ht);if(pt!==-1){const Dt=G.columns[pt];Lt(A,0,pt,X,Dt.type)}else try{const Dt=At(ht);Z(Dt,G,A,0,X,J,e.udfNameMap)}catch{throw new Error(`Grouping column "${ht}" not found in table "${G.name}"`)}}}}W===0&&F>0&&(A.emitUint8(m.OP_AGG_STEP),A.emitUint8(0),A.emitUint8(z),A.emitUint8(F),A.emitUint8(255),A.emitUint8(0));const Kt=M.some(v=>v.func==="count"),Wt=M.some(v=>v.func==="avg"),ve=M.some(v=>v.func==="sum"),ue=M.some(v=>v.func==="min"),Nt=M.some(v=>v.func==="max");if(Kt||Wt||ve){const v=M.find(X=>X.func==="count");let H=255;if(v&&v.colName&&v.colName!=="*"){const X=G.columns.findIndex(Y=>Y.name===v.colName);if(X!==-1){const Y=G.columns[X];H=et,Lt(A,0,X,H,Y.type)}}A.emitUint8(m.OP_AGG_STEP),A.emitUint8(0),A.emitUint8(z),A.emitUint8(F),A.emitUint8(H),A.emitUint8(0)}if(ve||Wt){const v=M.find(X=>X.func==="sum"||X.func==="avg");let H=255;if(v&&v.colName&&v.colName!=="*"){const X=G.columns.findIndex(Y=>Y.name===v.colName);if(X!==-1){const Y=G.columns[X];H=et+1,Lt(A,0,X,H,Y.type)}}A.emitUint8(m.OP_AGG_STEP),A.emitUint8(0),A.emitUint8(z),A.emitUint8(F),A.emitUint8(H),A.emitUint8(1)}if(ue){const v=M.find(X=>X.func==="min");let H=255;if(v&&v.colName&&v.colName!=="*"){const X=G.columns.findIndex(Y=>Y.name===v.colName);if(X!==-1){const Y=G.columns[X];H=et+2,Lt(A,0,X,H,Y.type)}}A.emitUint8(m.OP_AGG_STEP),A.emitUint8(0),A.emitUint8(z),A.emitUint8(F),A.emitUint8(H),A.emitUint8(3)}if(Nt){const v=M.find(X=>X.func==="max");let H=255;if(v&&v.colName&&v.colName!=="*"){const X=G.columns.findIndex(Y=>Y.name===v.colName);if(X!==-1){const Y=G.columns[X];H=et+3,Lt(A,0,X,H,Y.type)}}A.emitUint8(m.OP_AGG_STEP),A.emitUint8(0),A.emitUint8(z),A.emitUint8(F),A.emitUint8(H),A.emitUint8(4)}const Ee=A.currentOffset();for(const v of bt)A.patchUint16(v,Ee);A.emitUint8(m.OP_NEXT_ROW),A.emitUint8(0);const D=A.emitUint16(0);A.emitUint8(m.OP_JUMP),A.emitUint16(lt);const It=A.currentOffset();A.patchUint16(Ft,It),A.patchUint16(D,It);const ct=A.currentOffset();A.emitUint8(m.OP_AGG_NEXT),A.emitUint8(0),A.emitUint8(Et),A.emitUint8(ot);const Mt=A.emitUint16(0),St=A.currentOffset();A.emitUint8(m.OP_HALT);const Jt=A.currentOffset();A.patchUint16(Mt,Jt);for(let v=0;v<M.length;v++){const H=M[v],X=nt+v;let Y=ot,J=0;H.func==="count"?(Y=ot,J=0):H.func==="sum"?(Y=ot,J=1):H.func==="avg"?(Y=ot,J=2):H.func==="min"?(Y=ot+2,J=3):H.func==="max"&&(Y=ot+3,J=4),A.emitUint8(m.OP_AGG_FINAL),A.emitUint8(Y),A.emitUint8(ot+1),A.emitUint8(X),A.emitUint8(J)}const Bn=(v,H)=>{var X;for(let Y=0;Y<M.length;Y++){const J=M[Y],ht=nt+Y;if(v&&(J.alias&&J.alias===v||(J.colName?`${J.func}_${J.colName}`:J.func)===v||`${J.func}(${J.colName??"*"})`===v.replace(/\s+/g,"")||J.func===v))return ht;if(H&&H.type==="fn"){const zt=H.name.toLowerCase();if(J.func===zt)if(zt==="count"){const pt=H.args[0],Dt=pt&&pt.type==="col"?pt.name:void 0;if(J.colName===void 0||J.colName==="*"||J.colName===Dt)return ht}else{const pt=H.args[0],Dt=pt&&pt.type==="col"?pt.name:void 0;if(J.colName===Dt)return ht}}}if(e.groupBy)for(let Y=0;Y<e.groupBy.length;Y++){const J=e.groupBy[Y],ht=Et+Y,zt=typeof J=="string"?J:J.colName,pt=typeof J=="object"?J.expr:void 0;if(v){if(zt===v||pt&&vt(pt)===v)return ht;const Dt=(X=e.selectExprs)==null?void 0:X.find(mr=>mr.alias===v);if(Dt){if(zt===Dt.alias||pt&&JSON.stringify(pt)===JSON.stringify(Dt.expr))return ht;if(typeof J=="string"&&J.includes("("))try{const mr=At(J);if(JSON.stringify(mr)===JSON.stringify(Dt.expr))return ht}catch{}}}if(H){if(pt&&JSON.stringify(pt)===JSON.stringify(H)||H.type==="col"&&zt===H.name)return ht;if(typeof J=="string"&&J.includes("("))try{const Dt=At(J);if(JSON.stringify(Dt)===JSON.stringify(H))return ht}catch{}}}};if(e.having&&e.having.length>0){let v=null;e.having.length===1?v=e.having[0]:v={type:"and",children:e.having};const H=[];let X=Math.max(Ot+4,40);Qc(v,G,A,Bn,()=>{if(X>=64)throw new st(X);return X++},H,e.udfNameMap);for(const J of H)A.patchUint16(J,ct)}k&&(A.emitUint8(m.OP_OFFSET),A.emitUint8(j),A.emitUint16(ct)),A.emitUint8(m.OP_RESULT_ROW),A.emitUint8(Et),A.emitUint8(F+W),V&&(A.emitUint8(m.OP_LIMIT),A.emitUint8(K),A.emitUint16(St)),A.emitUint8(m.OP_JUMP),A.emitUint16(ct);const ke=A.toByteArray();return ke.outputColumns=$,ke.inSets=U,e.outputColumns=$,ke}const q=l?null:Ys(G,h,d,e.orderBy);if(!l&&e.orderBy&&e.orderBy.length>0&&!(q!=null&&q.satisfiesOrderBy)){const F=e.orderBy.length,M=b,W=M+F;if(W>=64)throw new st(W);const $={numKeys:F,directions:e.orderBy.map(lt=>lt.direction==="desc"?1:0),nullOrders:e.orderBy.map(lt=>lt.nullOrder==="nulls_last"?1:lt.nullOrder==="nulls_first"?0:lt.direction==="desc"?1:0),limit:e.limit,offset:e.offset};e.keyInfos=[$],A.emitUint8(m.OP_SORTER_OPEN),A.emitUint8(0),A.emitUint8(0),A.emitUint8(m.OP_OPEN_CURSOR),A.emitUint8(0),A.emitUint32(G.rootPageId),A.emitUint8(m.OP_REWIND),A.emitUint8(0);const mt=A.emitUint16(0),z=A.currentOffset(),et=[];se(u,G,A,R,et,e.udfNameMap,void 0,Q);for(let lt=0;lt<F;lt++){const bt=e.orderBy[lt],Kt=M+lt;let Wt=50;const ve=()=>{if(Wt>=64)throw new st(Wt);return Wt++};if(bt.expr)Z(bt.expr,G,A,0,Kt,ve,e.udfNameMap);else if(bt.colName){const ue=bt.colName,Nt=(Ea=(ma=e.selectExprs)==null?void 0:ma.find(Ee=>Ee.alias===ue))==null?void 0:Ea.expr;if(Nt)Z(Nt,G,A,0,Kt,ve,e.udfNameMap);else{const Ee=G.columns.findIndex(D=>D.name===ue);if(Ee!==-1){const D=G.columns[Ee];Lt(A,0,Ee,Kt,D.type)}else try{const D=At(ue);Z(D,G,A,0,Kt,ve,e.udfNameMap)}catch{throw new Error(`Order by column "${ue}" not found in table "${G.name}"`)}}}}A.emitUint8(m.OP_SORTER_INSERT),A.emitUint8(0),A.emitUint8(M),A.emitUint8(F),A.emitUint8(0);const ot=A.currentOffset();for(const lt of et)A.patchUint16(lt,ot);A.emitUint8(m.OP_NEXT_ROW),A.emitUint8(0);const Et=A.emitUint16(0);A.emitUint8(m.OP_JUMP),A.emitUint16(z);const nt=A.currentOffset();A.patchUint16(mt,nt),A.patchUint16(Et,nt),A.emitUint8(m.OP_SORTER_SORT),A.emitUint8(0);const Ot=A.currentOffset();A.emitUint8(m.OP_SORTER_NEXT),A.emitUint8(0),A.emitUint16(Ot),A.emitUint8(m.OP_HALT);const Ft=A.toByteArray();return Ft.keyInfos=e.keyInfos,Ft.inSets=U,a&&(Ft.planMetrics=a,Ft.estimatedCost=a.totalCost,Ft.estimatedRows=a.estimatedRows,Ft.joinOrder=a.joinOrder),Ft}const Rt=e.selectExprs!==void 0&&e.selectExprs.length>0&&!(e.selectExprs.length===1&&e.selectExprs[0].expr.type==="col"&&e.selectExprs[0].expr.name==="*");let dt=[];if(Rt)dt=e.selectExprs;else if(l){const F=new Set,M=new Set;for(const W of r)for(const $ of W.columns)F.has($.name.toLowerCase())&&M.add($.name.toLowerCase()),F.add($.name.toLowerCase());for(const W of r)for(const $ of W.columns){const mt=M.has($.name.toLowerCase())?`${W.name}.${$.name}`:$.name;dt.push({expr:{type:"col",name:`${W.name}.${$.name}`},alias:mt})}}let _t=-1;if(Rt||l){const F=dt.map(M=>({name:M.alias,type:ca(M.expr,G,e.udfDefs,r),flags:tt.NONE,colOffset:0}));if(e.outputColumns=F,_t=b,b+=dt.length,b>=64)throw new st(b)}if(l){const F=r.length,M=new Array(F);for(let D=1;D<F;D++)e.joinedTables[D-1].type==="left"&&(M[D]=b++);const W=b++,$=b++,mt=b++;let z=-1;if(T&&C!==-1)if(T.compositeValue){if(z=b++,b>=64)throw new st(b);A.emitUint8(m.OP_LOAD_BLOB),A.emitUint8(z),A.emitUint32(T.compositeValue.length),A.emitBytes(T.compositeValue)}else if(T.scanType==="multi_point"){if(z=b++,b>=64)throw new st(b)}else if(T.filterIndex>=0)z=T.filterIndex*2+1;else{if(z=b++,b>=64)throw new st(b);const D=Xs(T.keyType);hr(A,z,D,T.keyType)}if(b>=64)throw new st(b);for(let D=0;D<F;D++)A.emitUint8(m.OP_OPEN_CURSOR),A.emitUint8(D),A.emitUint32(r[D].rootPageId);T&&C!==-1&&(A.emitUint8(m.OP_OPEN_INDEX),A.emitUint8(C),A.emitUint32(T.index.rootPageId));for(let D=1;D<F;D++){const It=B[D];It&&(A.emitUint8(m.OP_OPEN_INDEX),A.emitUint8(It.indexCursor),A.emitUint32(It.index.rootPageId))}const et=new Array(F),ot=new Array(F),Et=Array.from({length:F},()=>[]),nt=new Array(F),Ot=[];if(T&&C!==-1?T.scanType==="point"?(A.emitUint8(m.OP_INDEX_SEEK_EQ),A.emitUint8(C),A.emitUint8(0),A.emitUint8(z),A.emitUint8(T.keyType),et[0]=A.emitUint16(0)):(A.emitUint8(m.OP_INDEX_SEEK_GE),A.emitUint8(C),A.emitUint8(0),A.emitUint8(z),A.emitUint8(T.keyType),et[0]=A.emitUint16(0)):(A.emitUint8(m.OP_REWIND),A.emitUint8(0),et[0]=A.emitUint16(0)),ot[0]=A.currentOffset(),f[0]&&f[0].length>0){const D=ne(f[0]);se(D,r[0],A,R,Et[0],e.udfNameMap,r,Q)}for(let D=1;D<F;D++){const It=e.joinedTables[D-1],ct=B[D];if(It.type==="left"&&(A.emitUint8(m.OP_LOAD_INT),A.emitUint8(M[D]),A.emitInt32(0)),ct&&ct.isUnique){if(Lt(A,ct.outerCol.cursor,ct.outerCol.colIdx,W,ct.outerCol.col.type),A.emitUint8(m.OP_INDEX_SEEK_EQ),A.emitUint8(ct.indexCursor),A.emitUint8(D),A.emitUint8(W),A.emitUint8(ct.outerCol.col.type),et[D]=A.emitUint16(0),ot[D]=A.currentOffset(),It.type==="inner"&&f[D]&&f[D].length>0){const Mt=ne(f[D]);se(Mt,r[D],A,R,Et[D],e.udfNameMap,r,Q)}It.type==="left"&&(A.emitUint8(m.OP_LOAD_INT),A.emitUint8(M[D]),A.emitInt32(1))}else if(ct&&!ct.isUnique){Lt(A,ct.outerCol.cursor,ct.outerCol.colIdx,W,ct.outerCol.col.type),A.emitUint8(m.OP_INDEX_SEEK_GE),A.emitUint8(ct.indexCursor),A.emitUint8(D),A.emitUint8(W),A.emitUint8(ct.outerCol.col.type),et[D]=A.emitUint16(0),ot[D]=A.currentOffset(),Lt(A,D,ct.innerCol.colIdx,$,ct.innerCol.col.type),A.emitUint8(m.OP_EQ),A.emitUint8(W),A.emitUint8($);const Mt=A.emitUint16(0);if(A.emitUint8(m.OP_JUMP),Et[D].push(A.emitUint16(0)),A.patchUint16(Mt,A.currentOffset()),It.type==="inner"&&f[D]&&f[D].length>0){const St=ne(f[D]);se(St,r[D],A,R,Et[D],e.udfNameMap,r,Q)}It.type==="left"&&(A.emitUint8(m.OP_LOAD_INT),A.emitUint8(M[D]),A.emitInt32(1))}else{A.emitUint8(m.OP_REWIND),A.emitUint8(D),et[D]=A.emitUint16(0),ot[D]=A.currentOffset();const Mt=gt(It.leftCol,r);if(!Mt)throw new Error(`Join column "${It.leftCol}" not found in tables`);const St=gt(It.rightCol,r);if(!St)throw new Error(`Join column "${It.rightCol}" not found in tables`);Lt(A,Mt.cursor,Mt.colIdx,W,Mt.col.type),Lt(A,St.cursor,St.colIdx,$,St.col.type);let Jt;switch(It.op){case"=":Jt=m.OP_EQ;break;case"!=":Jt=m.OP_NE;break;case">":Jt=m.OP_GT;break;case">=":Jt=m.OP_GE;break;case"<":Jt=m.OP_LT;break;case"<=":Jt=m.OP_LE;break;default:Jt=m.OP_EQ}A.emitUint8(Jt),A.emitUint8(W),A.emitUint8($);const Bn=A.emitUint16(0);if(A.emitUint8(m.OP_JUMP),Et[D].push(A.emitUint16(0)),A.patchUint16(Bn,A.currentOffset()),It.type==="inner"&&f[D]&&f[D].length>0){const ke=ne(f[D]);se(ke,r[D],A,R,Et[D],e.udfNameMap,r,Q)}It.type==="left"&&(A.emitUint8(m.OP_LOAD_INT),A.emitUint8(M[D]),A.emitInt32(1))}}se(I,G,A,R,Et[F-1],e.udfNameMap,r,Q);const lt=!(e.orderBy!==void 0&&e.orderBy.length>0)||O;let bt=-1;k&&lt&&(A.emitUint8(m.OP_OFFSET),A.emitUint8(j),bt=A.emitUint16(0));let Kt=b;const Wt=()=>{if(Kt>=64)throw new st(Kt);return Kt++};for(let D=0;D<dt.length;D++)Z(dt[D].expr,G,A,0,_t+D,Wt,e.udfNameMap,void 0,r);A.emitUint8(m.OP_RESULT_ROW),A.emitUint8(_t),A.emitUint8(dt.length),V&&lt&&(A.emitUint8(m.OP_LIMIT),A.emitUint8(K),Ot.push(A.emitUint16(0)));for(let D=F-1;D>=1;D--){const It=A.currentOffset();D===F-1&&bt!==-1&&A.patchUint16(bt,It);for(const St of Et[D])A.patchUint16(St,It);const ct=B[D];if(ct&&ct.isUnique){const St=A.currentOffset();A.patchUint16(et[D],St)}else if(ct&&!ct.isUnique){A.emitUint8(m.OP_INDEX_NEXT),A.emitUint8(ct.indexCursor),A.emitUint8(D),nt[D]=A.emitUint16(0),A.emitUint8(m.OP_JUMP),A.emitUint16(ot[D]);const St=A.currentOffset();A.patchUint16(et[D],St),A.patchUint16(nt[D],St)}else{A.emitUint8(m.OP_NEXT_ROW),A.emitUint8(D),nt[D]=A.emitUint16(0),A.emitUint8(m.OP_JUMP),A.emitUint16(ot[D]);const St=A.currentOffset();A.patchUint16(et[D],St),A.patchUint16(nt[D],St)}if(e.joinedTables[D-1].type==="left"){A.emitUint8(m.OP_LOAD_INT),A.emitUint8(mt),A.emitInt32(0),A.emitUint8(m.OP_EQ),A.emitUint8(M[D]),A.emitUint8(mt);const St=A.emitUint16(0);A.emitUint8(m.OP_JUMP);const Jt=A.emitUint16(0);A.patchUint16(St,A.currentOffset());for(let v=0;v<dt.length;v++){const H=dt[v];let X=-1;if(H.expr.type==="col"){const Y=gt(H.expr.name,r);Y&&(X=Y.tableIdx)}X>=D?(A.emitUint8(m.OP_LOAD_NULL),A.emitUint8(_t+v)):Z(H.expr,G,A,0,_t+v,Wt,e.udfNameMap,void 0,r)}const Bn=[];k&&lt&&(A.emitUint8(m.OP_OFFSET),A.emitUint8(j),Bn.push(A.emitUint16(0))),A.emitUint8(m.OP_RESULT_ROW),A.emitUint8(_t),A.emitUint8(dt.length),V&&lt&&(A.emitUint8(m.OP_LIMIT),A.emitUint8(K),Ot.push(A.emitUint16(0)));const ke=A.currentOffset();A.patchUint16(Jt,ke);for(const v of Bn)A.patchUint16(v,ke)}}const ve=A.currentOffset();for(const D of Et[0])A.patchUint16(D,ve);T&&C!==-1?T.scanType==="point"?(A.emitUint8(m.OP_JUMP),nt[0]=A.emitUint16(0)):(A.emitUint8(m.OP_INDEX_NEXT),A.emitUint8(C),A.emitUint8(0),nt[0]=A.emitUint16(0),A.emitUint8(m.OP_JUMP),A.emitUint16(ot[0])):(A.emitUint8(m.OP_NEXT_ROW),A.emitUint8(0),nt[0]=A.emitUint16(0),A.emitUint8(m.OP_JUMP),A.emitUint16(ot[0]));const ue=A.currentOffset();A.patchUint16(et[0],ue),A.patchUint16(nt[0],ue);for(const D of Ot)A.patchUint16(D,ue);A.emitUint8(m.OP_HALT);const Nt=A.toByteArray();e.outputColumns&&(Nt.outputColumns=e.outputColumns);const Ee=(Ia=e.joinedTables)==null?void 0:Ia.map((D,It)=>{const ct=It+1,Mt=B[ct];return{tableIndex:ct,tableName:D.table.name,scanType:Mt?"IndexScan":"TableScan",indexName:Mt?Mt.index.name:void 0}});return Nt.joinedTableScans=Ee,Nt.allTables=r,Nt.inSets=U,Nt.table0Scan=T,Nt.isOrderSatisfied=O,O&&(e.isOrderSatisfied=!0),a&&(Nt.planMetrics=a,Nt.estimatedCost=a.totalCost,Nt.estimatedRows=a.estimatedRows,Nt.joinOrder=a.joinOrder),o&&(Nt.whereMetrics=o),Nt}if(q){let F;if(q.compositeValue){if(F=b++,F>=64)throw new st(F);A.emitUint8(m.OP_LOAD_BLOB),A.emitUint8(F),A.emitBytes(q.compositeValue)}else if(q.scanType==="multi_point"){if(F=b++,F>=64)throw new st(F)}else if(q.filterIndex>=0)F=q.filterIndex*2+1;else{if(F=b++,F>=64)throw new st(F);const M=Xs(q.keyType);hr(A,F,M,q.keyType)}if(q.scanType==="point"){A.emitUint8(m.OP_OPEN_CURSOR),A.emitUint8(0),A.emitUint32(G.rootPageId),A.emitUint8(m.OP_OPEN_INDEX),A.emitUint8(1),A.emitUint32(q.index.rootPageId),A.emitUint8(m.OP_INDEX_SEEK_EQ),A.emitUint8(1),A.emitUint8(0),A.emitUint8(F),A.emitUint8(q.keyType);const M=A.emitUint16(0),W=[];se(u,G,A,R,W,e.udfNameMap,void 0,Q);let $=-1;if(k&&(A.emitUint8(m.OP_OFFSET),A.emitUint8(j),$=A.emitUint16(0)),Rt){let ot=b;const Et=()=>{if(ot>=64)throw new st(ot);return ot++};for(let nt=0;nt<e.selectExprs.length;nt++)Z(e.selectExprs[nt].expr,G,A,0,_t+nt,Et,e.udfNameMap);A.emitUint8(m.OP_RESULT_ROW),A.emitUint8(_t),A.emitUint8(e.selectExprs.length)}else A.emitUint8(m.OP_EMIT_ROW),A.emitUint8(0);A.emitUint8(m.OP_JUMP);const mt=A.emitUint16(0),z=A.currentOffset();A.patchUint16(M,z),A.patchUint16(mt,z),$!==-1&&A.patchUint16($,z);for(const ot of W)A.patchUint16(ot,z);A.emitUint8(m.OP_HALT);const et=A.toByteArray();return et.indexScan=q,et.inSets=U,e.outputColumns&&(et.outputColumns=e.outputColumns),q!=null&&q.satisfiesOrderBy&&(et.isOrderSatisfied=!0,e.isOrderSatisfied=!0),a&&(et.planMetrics=a,et.estimatedCost=a.totalCost,et.estimatedRows=a.estimatedRows,et.joinOrder=a.joinOrder),et}else if(q.scanType==="multi_point"){const M=q.inValues?q.inValues.length:0;if(M===0){A.emitUint8(m.OP_HALT);const z=A.toByteArray();return z.indexScan=q,z.inSets=U,e.outputColumns&&(z.outputColumns=e.outputColumns),z}A.emitUint8(m.OP_OPEN_CURSOR),A.emitUint8(0),A.emitUint32(G.rootPageId),A.emitUint8(m.OP_OPEN_INDEX),A.emitUint8(1),A.emitUint32(q.index.rootPageId);const W=[];for(let z=0;z<M;z++){const et=q.inValues[z];hr(A,F,et,q.keyType),A.emitUint8(m.OP_INDEX_SEEK_EQ),A.emitUint8(1),A.emitUint8(0),A.emitUint8(F),A.emitUint8(q.keyType);const ot=A.emitUint16(0),Et=[];se(u,G,A,R,Et,e.udfNameMap,void 0,Q);let nt=-1;if(k&&(A.emitUint8(m.OP_OFFSET),A.emitUint8(j),nt=A.emitUint16(0)),Rt){let bt=b;const Kt=()=>{if(bt>=64)throw new st(bt);return bt++};for(let Wt=0;Wt<e.selectExprs.length;Wt++)Z(e.selectExprs[Wt].expr,G,A,0,_t+Wt,Kt,e.udfNameMap);A.emitUint8(m.OP_RESULT_ROW),A.emitUint8(_t),A.emitUint8(e.selectExprs.length)}else A.emitUint8(m.OP_EMIT_ROW),A.emitUint8(0);V&&(A.emitUint8(m.OP_LIMIT),A.emitUint8(K),W.push(A.emitUint16(0)));const Ot=z===M-1;let Ft=-1;Ot||(A.emitUint8(m.OP_JUMP),Ft=A.emitUint16(0));const lt=A.currentOffset();A.patchUint16(ot,lt);for(const bt of Et)A.patchUint16(bt,lt);nt!==-1&&A.patchUint16(nt,lt),Ft!==-1&&A.patchUint16(Ft,lt)}const $=A.currentOffset();for(const z of W)A.patchUint16(z,$);A.emitUint8(m.OP_HALT);const mt=A.toByteArray();return mt.indexScan=q,mt.inSets=U,e.outputColumns&&(mt.outputColumns=e.outputColumns),q!=null&&q.satisfiesOrderBy&&(mt.isOrderSatisfied=!0,e.isOrderSatisfied=!0),a&&(mt.planMetrics=a,mt.estimatedCost=a.totalCost,mt.estimatedRows=a.estimatedRows,mt.joinOrder=a.joinOrder),mt}else{A.emitUint8(m.OP_OPEN_CURSOR),A.emitUint8(0),A.emitUint32(G.rootPageId),A.emitUint8(m.OP_OPEN_INDEX),A.emitUint8(1),A.emitUint32(q.index.rootPageId),A.emitUint8(m.OP_INDEX_SEEK_GE),A.emitUint8(1),A.emitUint8(0),A.emitUint8(F),A.emitUint8(q.keyType);const M=A.emitUint16(0),W=A.currentOffset(),$=[];se(u,G,A,R,$,e.udfNameMap,void 0,Q);let mt=-1;if(k&&(A.emitUint8(m.OP_OFFSET),A.emitUint8(j),mt=A.emitUint16(0)),Rt){let Ot=b;const Ft=()=>{if(Ot>=64)throw new st(Ot);return Ot++};for(let lt=0;lt<e.selectExprs.length;lt++)Z(e.selectExprs[lt].expr,G,A,0,_t+lt,Ft,e.udfNameMap);A.emitUint8(m.OP_RESULT_ROW),A.emitUint8(_t),A.emitUint8(e.selectExprs.length)}else A.emitUint8(m.OP_EMIT_ROW),A.emitUint8(0);let z=-1;V&&(A.emitUint8(m.OP_LIMIT),A.emitUint8(K),z=A.emitUint16(0));const et=A.currentOffset();mt!==-1&&A.patchUint16(mt,et);for(const Ot of $)A.patchUint16(Ot,et);A.emitUint8(m.OP_INDEX_NEXT),A.emitUint8(1),A.emitUint8(0);const ot=A.emitUint16(0);A.emitUint8(m.OP_JUMP),A.emitUint16(W);const Et=A.currentOffset();A.patchUint16(M,Et),A.patchUint16(ot,Et),z!==-1&&A.patchUint16(z,Et),A.emitUint8(m.OP_HALT);const nt=A.toByteArray();return nt.indexScan=q,nt.inSets=U,e.outputColumns&&(nt.outputColumns=e.outputColumns),q!=null&&q.satisfiesOrderBy&&(nt.isOrderSatisfied=!0,e.isOrderSatisfied=!0),a&&(nt.planMetrics=a,nt.estimatedCost=a.totalCost,nt.estimatedRows=a.estimatedRows,nt.joinOrder=a.joinOrder),nt}}A.emitUint8(m.OP_OPEN_CURSOR),A.emitUint8(0),A.emitUint32(G.rootPageId),A.emitUint8(m.OP_REWIND),A.emitUint8(0);const On=A.emitUint16(0),Pn=A.currentOffset(),bn=[];se(u,G,A,R,bn,e.udfNameMap,void 0,Q);let on=-1;if(k&&(A.emitUint8(m.OP_OFFSET),A.emitUint8(j),on=A.emitUint16(0)),Rt){let F=b;const M=()=>{if(F>=64)throw new st(F);return F++};for(let W=0;W<e.selectExprs.length;W++)Z(e.selectExprs[W].expr,G,A,0,_t+W,M,e.udfNameMap);A.emitUint8(m.OP_RESULT_ROW),A.emitUint8(_t),A.emitUint8(e.selectExprs.length)}else A.emitUint8(m.OP_EMIT_ROW),A.emitUint8(0);let De=-1;V&&(A.emitUint8(m.OP_LIMIT),A.emitUint8(K),De=A.emitUint16(0));const es=A.currentOffset();on!==-1&&A.patchUint16(on,es);for(const F of bn)A.patchUint16(F,es);A.emitUint8(m.OP_NEXT_ROW),A.emitUint8(0);const Qe=A.emitUint16(0);A.emitUint8(m.OP_JUMP),A.emitUint16(Pn);const Nn=A.currentOffset();A.patchUint16(On,Nn),A.patchUint16(Qe,Nn),De!==-1&&A.patchUint16(De,Nn),A.emitUint8(m.OP_HALT);const ce=A.toByteArray();return ce.inSets=U,e.outputColumns&&(ce.outputColumns=e.outputColumns),o&&(ce.whereMetrics=o),a&&(ce.planMetrics=a,ce.estimatedCost=a.totalCost,ce.estimatedRows=a.estimatedRows,ce.joinOrder=a.joinOrder),ce}const vc=new TextDecoder;function fa(e,t){const n=[],s=new DataView(e.buffer,e.byteOffset,e.byteLength);let i=0;const r=a=>{var c;return(c=t==null?void 0:t.columns[a])!=null&&c.name?`'${t.columns[a].name}'`:`col_${a}`},o=a=>`0x${a.toString(16).padStart(4,"0")}`;for(;i<e.byteLength;){const a=i,c=e[i++];switch(c){case m.OP_HALT:n.push({addr:a,opcode:"OP_HALT",p1:"",p2:"",p3:"",comment:"Halt VM execution (STATUS_DONE)"});break;case m.OP_OPEN_CURSOR:{const l=e[i++],u=s.getUint32(i,!0);i+=4,n.push({addr:a,opcode:"OP_OPEN_CURSOR",p1:`c[${l}]`,p2:`page=${u}`,p3:"",comment:`Open cursor ${l} on root page ${u}${t?` ('${t.name}')`:""}`});break}case m.OP_OPEN_INDEX:{const l=e[i++],u=s.getUint32(i,!0);i+=4,n.push({addr:a,opcode:"OP_OPEN_INDEX",p1:`c[${l}]`,p2:`page=${u}`,p3:"",comment:`Open index cursor ${l} on root page ${u}`});break}case m.OP_INDEX_SEEK_EQ:{const l=e[i++],u=e[i++],d=e[i++],h=e[i++],f=s.getUint16(i,!0);i+=2,n.push({addr:a,opcode:"OP_INDEX_SEEK_EQ",p1:`idx=c[${l}], data=c[${u}]`,p2:`key=r[${d}], type=${h}`,p3:o(f),comment:`Seek exact key in index; position data cursor or jump to ${o(f)} if not found`});break}case m.OP_INDEX_SEEK_GE:{const l=e[i++],u=e[i++],d=e[i++],h=e[i++],f=s.getUint16(i,!0);i+=2,n.push({addr:a,opcode:"OP_INDEX_SEEK_GE",p1:`idx=c[${l}], data=c[${u}]`,p2:`key=r[${d}], type=${h}`,p3:o(f),comment:`Seek first entry >= key in index; position data cursor or jump to ${o(f)} if EOF`});break}case m.OP_INDEX_NEXT:{const l=e[i++],u=e[i++],d=s.getUint16(i,!0);i+=2,n.push({addr:a,opcode:"OP_INDEX_NEXT",p1:`idx=c[${l}], data=c[${u}]`,p2:o(d),p3:"",comment:`Advance index cursor to next entry; jump to ${o(d)} if EOF`});break}case m.OP_REWIND:{const l=e[i++],u=s.getUint16(i,!0);i+=2,n.push({addr:a,opcode:"OP_REWIND",p1:`c[${l}]`,p2:o(u),p3:"",comment:`Rewind cursor to first row; jump to ${o(u)} if empty`});break}case m.OP_NEXT_ROW:{const l=e[i++],u=s.getUint16(i,!0);i+=2,n.push({addr:a,opcode:"OP_NEXT_ROW",p1:`c[${l}]`,p2:o(u),p3:"",comment:`Advance cursor to next row; jump to ${o(u)} if EOF`});break}case m.OP_LAST:{const l=e[i++],u=s.getUint16(i,!0);i+=2,n.push({addr:a,opcode:"OP_LAST",p1:`c[${l}]`,p2:o(u),p3:"",comment:`Position cursor to last row; jump to ${o(u)} if empty`});break}case m.OP_PREV_ROW:{const l=e[i++],u=s.getUint16(i,!0);i+=2,n.push({addr:a,opcode:"OP_PREV_ROW",p1:`c[${l}]`,p2:o(u),p3:"",comment:`Advance cursor to previous row; jump to ${o(u)} if BOF`});break}case m.OP_COLUMN_INT:{const l=e[i++],u=e[i++],d=e[i++];n.push({addr:a,opcode:"OP_COLUMN_INT",p1:`c[${l}]`,p2:`${u} (${r(u)})`,p3:`r[${d}]`,comment:`Read ${r(u)} as INT into r[${d}]`});break}case m.OP_COLUMN_FLOAT:{const l=e[i++],u=e[i++],d=e[i++];n.push({addr:a,opcode:"OP_COLUMN_FLOAT",p1:`c[${l}]`,p2:`${u} (${r(u)})`,p3:`r[${d}]`,comment:`Read ${r(u)} as FLOAT into r[${d}]`});break}case m.OP_COLUMN_TEXT:{const l=e[i++],u=e[i++],d=e[i++];n.push({addr:a,opcode:"OP_COLUMN_TEXT",p1:`c[${l}]`,p2:`${u} (${r(u)})`,p3:`r[${d}]`,comment:`Read ${r(u)} as TEXT into r[${d}]`});break}case m.OP_COLUMN_BLOB:{const l=e[i++],u=e[i++],d=e[i++];n.push({addr:a,opcode:"OP_COLUMN_BLOB",p1:`c[${l}]`,p2:`${u} (${r(u)})`,p3:`r[${d}]`,comment:`Read ${r(u)} as BLOB into r[${d}]`});break}case m.OP_COLUMN_UUID:{const l=e[i++],u=e[i++],d=e[i++];n.push({addr:a,opcode:"OP_COLUMN_UUID",p1:`c[${l}]`,p2:`${u} (${r(u)})`,p3:`r[${d}]`,comment:`Read ${r(u)} as UUID into r[${d}]`});break}case m.OP_COLUMN_ULID:{const l=e[i++],u=e[i++],d=e[i++];n.push({addr:a,opcode:"OP_COLUMN_ULID",p1:`c[${l}]`,p2:`${u} (${r(u)})`,p3:`r[${d}]`,comment:`Read ${r(u)} as ULID into r[${d}]`});break}case m.OP_IS_NULL:{const l=e[i++],u=e[i++],d=s.getUint16(i,!0);i+=2,n.push({addr:a,opcode:"OP_IS_NULL",p1:`c[${l}]`,p2:`${u} (${r(u)})`,p3:o(d),comment:`If ${r(u)} IS NULL -> jump to ${o(d)}`});break}case m.OP_IS_NOT_NULL:{const l=e[i++],u=e[i++],d=s.getUint16(i,!0);i+=2,n.push({addr:a,opcode:"OP_IS_NOT_NULL",p1:`c[${l}]`,p2:`${u} (${r(u)})`,p3:o(d),comment:`If ${r(u)} IS NOT NULL -> jump to ${o(d)}`});break}case m.OP_EQ:case m.OP_NE:case m.OP_GT:case m.OP_GE:case m.OP_LT:case m.OP_LE:{const l={[m.OP_EQ]:"OP_EQ",[m.OP_NE]:"OP_NE",[m.OP_GT]:"OP_GT",[m.OP_GE]:"OP_GE",[m.OP_LT]:"OP_LT",[m.OP_LE]:"OP_LE"},u={[m.OP_EQ]:"==",[m.OP_NE]:"!=",[m.OP_GT]:">",[m.OP_GE]:">=",[m.OP_LT]:"<",[m.OP_LE]:"<="},d=e[i++],h=e[i++],f=s.getUint16(i,!0);i+=2,n.push({addr:a,opcode:l[c],p1:`r[${d}]`,p2:`r[${h}]`,p3:o(f),comment:`If r[${d}] ${u[c]} r[${h}] -> jump to ${o(f)}`});break}case m.OP_JUMP:{const l=s.getUint16(i,!0);i+=2,n.push({addr:a,opcode:"OP_JUMP",p1:o(l),p2:"",p3:"",comment:`Unconditional jump to ${o(l)}`});break}case m.OP_STR_LIKE:case m.OP_STR_NOT_LIKE:case m.OP_STR_CONTAINS:case m.OP_STR_STARTS_WITH:case m.OP_STR_ENDS_WITH:{const l={[m.OP_STR_LIKE]:"OP_STR_LIKE",[m.OP_STR_NOT_LIKE]:"OP_STR_NOT_LIKE",[m.OP_STR_CONTAINS]:"OP_STR_CONTAINS",[m.OP_STR_STARTS_WITH]:"OP_STR_STARTS_WITH",[m.OP_STR_ENDS_WITH]:"OP_STR_ENDS_WITH"},u={[m.OP_STR_LIKE]:"LIKE",[m.OP_STR_NOT_LIKE]:"NOT LIKE",[m.OP_STR_CONTAINS]:"CONTAINS",[m.OP_STR_STARTS_WITH]:"STARTS_WITH",[m.OP_STR_ENDS_WITH]:"ENDS_WITH"},d=e[i++],h=e[i++],f=s.getUint16(i,!0);i+=2,n.push({addr:a,opcode:l[c],p1:`r[${d}]`,p2:`r[${h}]`,p3:o(f),comment:`If r[${d}] ${u[c]} r[${h}] -> jump to ${o(f)}`});break}case m.OP_IN:{const l=e[i++],u=s.getUint16(i,!0);i+=2;const d=s.getUint16(i,!0);i+=2,n.push({addr:a,opcode:"OP_IN",p1:`r[${l}]`,p2:`set[${u}]`,p3:o(d),comment:`If r[${l}] IN set[${u}] -> jump to ${o(d)}`});break}case m.OP_LOAD_INT:{const l=e[i++],u=s.getInt32(i,!0);i+=4,n.push({addr:a,opcode:"OP_LOAD_INT",p1:`r[${l}]`,p2:`${u}`,p3:"",comment:`Load literal int ${u} into r[${l}]`});break}case m.OP_LOAD_FLOAT:{const l=e[i++],u=s.getFloat64(i,!0);i+=8,n.push({addr:a,opcode:"OP_LOAD_FLOAT",p1:`r[${l}]`,p2:`${u}`,p3:"",comment:`Load literal float ${u} into r[${l}]`});break}case m.OP_LOAD_TEXT:{const l=e[i++],u=s.getUint16(i,!0);i+=2;const d=new Uint8Array(e.buffer,e.byteOffset+i,u),h=vc.decode(d);i+=u,n.push({addr:a,opcode:"OP_LOAD_TEXT",p1:`r[${l}]`,p2:`"${h}"`,p3:"",comment:`Load literal text "${h}" into r[${l}]`});break}case m.OP_LOAD_BLOB:{const l=e[i++],u=s.getUint16(i,!0);i+=2+u,n.push({addr:a,opcode:"OP_LOAD_BLOB",p1:`r[${l}]`,p2:`len=${u}`,p3:"",comment:`Load literal BLOB (${u} bytes) into r[${l}]`});break}case m.OP_LOAD_NULL:{const l=e[i++];n.push({addr:a,opcode:"OP_LOAD_NULL",p1:`r[${l}]`,p2:"NULL",p3:"",comment:`Set r[${l}] to NULL`});break}case m.OP_EMIT_ROW:{const l=e[i++];n.push({addr:a,opcode:"OP_EMIT_ROW",p1:`c[${l}]`,p2:"",p3:"",comment:"Row passed all filters -> emit to Output Result Buffer"});break}case m.OP_RESULT_ROW:{const l=e[i++],u=e[i++];n.push({addr:a,opcode:"OP_RESULT_ROW",p1:`r[${l}]`,p2:`cols=${u}`,p3:"",comment:`Serialize registers r[${l}..${l+u-1}] to Result Buffer`});break}case m.OP_OFFSET:{const l=e[i++],u=s.getUint16(i,!0);i+=2,n.push({addr:a,opcode:"OP_OFFSET",p1:`r[${l}]`,p2:o(u),p3:"",comment:`If r[${l}] > 0 -> decrement and skip row to ${o(u)}`});break}case m.OP_LIMIT:{const l=e[i++],u=s.getUint16(i,!0);i+=2,n.push({addr:a,opcode:"OP_LIMIT",p1:`r[${l}]`,p2:o(u),p3:"",comment:`If r[${l}] <= 1 -> halt to ${o(u)}, else decrement`});break}case m.OP_CALL_UDF:{const l=s.getUint16(i,!0);i+=2;const u=e[i++],d=e[i++],h=e[i++];n.push({addr:a,opcode:"OP_CALL_UDF",p1:`udf#${l}`,p2:`r[${u}..${u+d-1}]`,p3:`r[${h}]`,comment:`Call UDF #${l} with ${d} args -> r[${h}]`});break}case m.OP_STR_LOWER:case m.OP_STR_UPPER:case m.OP_STR_LENGTH:case m.OP_STR_TRIM:case m.OP_MATH_ABS:case m.OP_MATH_ROUND:case m.OP_MATH_FLOOR:case m.OP_MATH_CEIL:{const l={[m.OP_STR_LOWER]:"OP_STR_LOWER",[m.OP_STR_UPPER]:"OP_STR_UPPER",[m.OP_STR_LENGTH]:"OP_STR_LENGTH",[m.OP_STR_TRIM]:"OP_STR_TRIM",[m.OP_MATH_ABS]:"OP_MATH_ABS",[m.OP_MATH_ROUND]:"OP_MATH_ROUND",[m.OP_MATH_FLOOR]:"OP_MATH_FLOOR",[m.OP_MATH_CEIL]:"OP_MATH_CEIL"},u=e[i++],d=e[i++];n.push({addr:a,opcode:l[c],p1:`r[${u}]`,p2:`r[${d}]`,p3:"",comment:`${l[c]}: r[${d}] = ${l[c].toLowerCase()}(r[${u}])`});break}case m.OP_STR_SUBSTR:{const l=e[i++],u=e[i++],d=e[i++],h=e[i++];n.push({addr:a,opcode:"OP_STR_SUBSTR",p1:`r[${l}]`,p2:`start=r[${u}], len=r[${d}]`,p3:`r[${h}]`,comment:`Extract substring from r[${l}] into r[${h}]`});break}case m.OP_ADD:case m.OP_SUB:case m.OP_MUL:case m.OP_DIV:case m.OP_MOD:{const l={[m.OP_ADD]:"OP_ADD",[m.OP_SUB]:"OP_SUB",[m.OP_MUL]:"OP_MUL",[m.OP_DIV]:"OP_DIV",[m.OP_MOD]:"OP_MOD"},u=e[i++],d=e[i++],h=e[i++];n.push({addr:a,opcode:l[c],p1:`r[${u}]`,p2:`r[${d}]`,p3:`r[${h}]`,comment:`${l[c]}: r[${h}] = r[${u}] ${l[c].replace("OP_","")} r[${d}]`});break}case m.OP_STR_CONCAT:case m.OP_COALESCE:{const l={[m.OP_STR_CONCAT]:"OP_STR_CONCAT",[m.OP_COALESCE]:"OP_COALESCE"},u=e[i++],d=e[i++],h=e[i++];n.push({addr:a,opcode:l[c],p1:`r[${u}..${u+d-1}]`,p2:`count=${d}`,p3:`r[${h}]`,comment:`${l[c]}: r[${h}]`});break}case m.OP_COPY:{const l=e[i++],u=e[i++];n.push({addr:a,opcode:"OP_COPY",p1:`r[${l}]`,p2:`r[${u}]`,p3:"",comment:`Copy r[${l}] to r[${u}]`});break}case m.OP_SORTER_OPEN:{const l=e[i++],u=e[i++];n.push({addr:a,opcode:"OP_SORTER_OPEN",p1:`s[${l}]`,p2:`keyInfo=${u}`,p3:"",comment:`Open sorter ${l} with keyInfo ${u}`});break}case m.OP_SORTER_INSERT:{const l=e[i++],u=e[i++],d=e[i++],h=e[i++];n.push({addr:a,opcode:"OP_SORTER_INSERT",p1:`s[${l}]`,p2:`r[${u}..+${d}]`,p3:`c[${h}]`,comment:`Insert row from cursor ${h} into sorter ${l}`});break}case m.OP_SORTER_SORT:{const l=e[i++];n.push({addr:a,opcode:"OP_SORTER_SORT",p1:`s[${l}]`,p2:"",p3:"",comment:`Sort entries in sorter ${l}`});break}case m.OP_SORTER_NEXT:{const l=e[i++],u=s.getUint16(i,!0);i+=2,n.push({addr:a,opcode:"OP_SORTER_NEXT",p1:`s[${l}]`,p2:o(u),p3:"",comment:`Emit next sorted row from sorter ${l}; jump to ${o(u)} while more rows`});break}case m.OP_AGG_INIT:{const l=e[i++],u=e[i++],d=e[i++],h=e[i++];n.push({addr:a,opcode:"OP_AGG_INIT",p1:`agg[${l}]`,p2:`keys=r[${u}..+${d}]`,p3:`mode=${h===0?"hash":"stream"}`,comment:`Initialize aggregator ${l} (${h===0?"hash table":"stream"})`});break}case m.OP_AGG_STEP:{const l=e[i++],u=e[i++],d=e[i++],h=e[i++],f=e[i++],g=["COUNT","SUM","AVG","MIN","MAX"];n.push({addr:a,opcode:"OP_AGG_STEP",p1:`agg[${l}]`,p2:`val=${h===255?"*":`r[${h}]`}`,p3:g[f]??`${f}`,comment:`Update accumulator ${g[f]??f} for group r[${u}..+${d}]`});break}case m.OP_AGG_NEXT:{const l=e[i++],u=e[i++],d=e[i++],h=s.getUint16(i,!0);i+=2,n.push({addr:a,opcode:"OP_AGG_NEXT",p1:`agg[${l}]`,p2:`out_keys=r[${u}], out_acc=r[${d}]`,p3:o(h),comment:`Iterate next group bucket; jump to ${o(h)}`});break}case m.OP_AGG_FINAL:{const l=e[i++],u=e[i++],d=e[i++],h=e[i++],f=["COUNT","SUM","AVG","MIN","MAX"];n.push({addr:a,opcode:"OP_AGG_FINAL",p1:`sum=r[${l}], cnt=r[${u}]`,p2:`r[${d}]`,p3:f[h]??`${h}`,comment:`Finalize ${f[h]??h} into r[${d}]`});break}case m.OP_REG_IS_NULL:{const l=e[i++],u=s.getUint16(i,!0);i+=2,n.push({addr:a,opcode:"OP_REG_IS_NULL",p1:`r[${l}]`,p2:o(u),p3:"",comment:`Jump to ${o(u)} if r[${l}] is NULL`});break}case m.OP_REG_IS_NOT_NULL:{const l=e[i++],u=s.getUint16(i,!0);i+=2,n.push({addr:a,opcode:"OP_REG_IS_NOT_NULL",p1:`r[${l}]`,p2:o(u),p3:"",comment:`Jump to ${o(u)} if r[${l}] is NOT NULL`});break}default:n.push({addr:a,opcode:`OP_UNKNOWN(0x${c.toString(16)})`,p1:"",p2:"",p3:"",comment:"Unknown opcode"});break}}return n}function Aa(e){const t=(i,r)=>i.padEnd(r," "),n=i=>`0x${i.toString(16).padStart(4,"0")}`;let s=`${t("ADDR",8)} ${t("OPCODE",18)} ${t("P1",12)} ${t("P2",20)} ${t("P3",10)} COMMENT
2
2
  `;s+="-".repeat(95)+`
3
3
  `;for(const i of e)s+=`${t(n(i.addr),8)} ${t(i.opcode,18)} ${t(i.p1,12)} ${t(i.p2,20)} ${t(i.p3,10)} ${i.comment}
4
- `;return s}function x(e){return e instanceof Lt||typeof e=="object"&&e!==null&&typeof e.toArray=="function"&&typeof e.where=="function"&&typeof e.select=="function"&&"filters"in e}function wt(e){if(e instanceof it||typeof e=="object"&&e!==null&&"node"in e)return{expr:e.node};if(typeof e=="object"&&e!==null&&"type"in e)return{expr:e};if(typeof e=="string"){const t=e.trim();return t.includes("(")||t.includes("+")||t.includes("-")||t.includes("*")||t.includes("/")||t.includes("%")?{expr:ft(t),colName:t}:{colName:t}}return{}}function nr(e){const t=[];function n(s){if(s.type==="fn"){const i=s.name.toLowerCase();if(ge(i)){const r=s.args[0],o=r&&r.type==="col"&&r.name!=="*"?r.name:void 0;t.push({func:i,colName:o})}for(const r of s.args)n(r)}else s.type==="binary"&&(n(s.left),n(s.right))}return n(e),t}function Ms(e){if(!e)return[];if(Array.isArray(e)){const t=[];for(const n of e)t.push(...Ms(n));return t}if(x(e)){const t=e.getSelectFields(),n=e.getAggregates();return[{alias:t.length>0?t[0].alias:n.length>0?n[0].alias??(n[0].colName?`${n[0].func}_${n[0].colName}`:n[0].func):"subquery",subquery:e}]}if(e instanceof it||typeof e=="object"&&e!==null&&"node"in e){const t=e.node;return[{alias:Qt(t),expr:t,sourceCol:t.type==="col"&&t.name!=="*"?t.name:void 0,fn:t.type==="fn"?t.name:void 0}]}if(typeof e=="string"){const t=e.trim();if(!t)return[];const n=bs(t);return[{alias:n.alias,expr:n.expr,sourceCol:n.expr.type==="col"&&n.expr.name!=="*"?n.expr.name:void 0,fn:n.expr.type==="fn"?n.expr.name:void 0}]}if(typeof e=="object"&&e!==null){if("subquery"in e&&"as"in e&&x(e.subquery)&&typeof e.as=="string")return[{alias:e.as,subquery:e.subquery}];if("expr"in e&&"alias"in e){const n=e.expr;return[{alias:e.alias,expr:n,sourceCol:n.type==="col"&&n.name!=="*"?n.name:void 0,fn:n.type==="fn"?n.name:void 0}]}if("col"in e&&"as"in e&&typeof e.col=="string"&&typeof e.as=="string"){const n=bs(`${e.col} as ${e.as}`);return[{sourceCol:e.col==="*"?void 0:e.col,alias:e.as,expr:n.expr,fn:n.expr.type==="fn"?n.expr.name:void 0}]}const t=[];for(const[n,s]of Object.entries(e))if(typeof s=="string"){const i=bs(`${n} as ${s}`);t.push({sourceCol:n==="*"?void 0:n,alias:s,expr:i.expr,fn:i.expr.type==="fn"?i.expr.name:void 0})}else if(x(s))t.push({alias:n,subquery:s});else if(typeof s=="object"&&s!==null&&"subquery"in s&&x(s.subquery))t.push({alias:n,subquery:s.subquery});else if(s instanceof it||typeof s=="object"&&s!==null&&"node"in s){const i=s.node;t.push({alias:n,expr:i,sourceCol:i.type==="col"&&i.name!=="*"?i.name:void 0,fn:i.type==="fn"?i.name:void 0})}else if(typeof s=="object"&&s!==null&&"type"in s){const i=s;t.push({alias:n,expr:i,sourceCol:i.type==="col"&&i.name!=="*"?i.name:void 0,fn:i.type==="fn"?i.name:void 0})}return t}return[]}function ct(e){if(!x(e))if(typeof e=="string"){const t=e.trim();if(ge(t))throw new os(t);if(t.includes("("))try{const n=ft(t);je(n,"where")}catch(n){if(n instanceof os)throw n}}else e instanceof it||typeof e=="object"&&e!==null&&"node"in e?je(e.node,"where"):typeof e=="object"&&e!==null&&"type"in e&&je(e,"where")}class Lt{constructor(t,n){U(this,"db");U(this,"tableName");U(this,"sourceSubquery");U(this,"filters",[]);U(this,"selectFields",[]);U(this,"limitCount",null);U(this,"offsetCount",null);U(this,"sortCol",null);U(this,"sortDir","asc");U(this,"orderKeys",[]);U(this,"groupCols",[]);U(this,"groupKeys",[]);U(this,"aggExprs",[]);U(this,"havingFilters",[]);U(this,"joins",[]);U(this,"planner");this.db=t,x(n)?(this.sourceSubquery=n,this.tableName="__subquery__",this.assertSubqueryDepth()):this.tableName=n}withPlanner(t){return this.planner=t,this}as(t){return{subquery:this,as:t}}getTableName(){return this.tableName}getSourceSubquery(){return this.sourceSubquery}getAggregates(){return this.aggExprs}getFilterSubqueryDepth(t){let n=0;if(t.subquery&&x(t.subquery)&&(n=Math.max(n,1+t.subquery.getMaxSubqueryDepth())),t.value&&x(t.value)&&(n=Math.max(n,1+t.value.getMaxSubqueryDepth())),t.child&&(n=Math.max(n,this.getFilterSubqueryDepth(t.child))),t.children)for(const s of t.children)n=Math.max(n,this.getFilterSubqueryDepth(s));return n}getMaxSubqueryDepth(){let t=0;this.sourceSubquery&&(t=Math.max(t,1+this.sourceSubquery.getMaxSubqueryDepth()));for(const n of this.selectFields)n.subquery&&(t=Math.max(t,1+n.subquery.getMaxSubqueryDepth()));for(const n of this.filters)t=Math.max(t,this.getFilterSubqueryDepth(n));for(const n of this.havingFilters)t=Math.max(t,this.getFilterSubqueryDepth(n));return t}assertSubqueryDepth(){const t=this.getMaxSubqueryDepth();if(t>7)throw new Qr(t,7)}join(t,n,s,i){const r=i!==void 0?s:"=",o=i!==void 0?i:s;return this.joins.push({type:"inner",table:t,leftCol:n,op:r,rightCol:o}),this}innerJoin(t,n,s,i){return this.join(t,n,s,i)}leftJoin(t,n,s,i){const r=i!==void 0?s:"=",o=i!==void 0?i:s;return this.joins.push({type:"left",table:t,leftCol:n,op:r,rightCol:o}),this}getJoins(){return this.joins}where(t,n,s){if(typeof t=="function"){const i=new Lt(this.db,this.tableName);t(i);const r=i.getRootFilter();r&&(this.filters.push(r),this.assertSubqueryDepth())}else if(n===void 0&&s===void 0){if(typeof t=="string"){ct(t);const i=ft(t);this.filters.push({type:"expr",expr:i})}else if(t instanceof it||typeof t=="object"&&t!==null&&"node"in t)ct(t),this.filters.push({type:"expr",expr:t.node});else if(typeof t=="object"&&t!==null&&"type"in t)ct(t),this.filters.push({type:"expr",expr:t});else if(typeof t=="object"&&t!==null)for(const[i,r]of Object.entries(t))this.where(i,"=",r)}else{if(ct(t),ct(s),typeof n=="string"&&n.trim().toLowerCase()==="in")return this.whereIn(t,s);if(typeof n=="string"&&n.trim().toLowerCase()==="not in")return this.whereNotIn(t,s);const i=wt(t);x(s)?(this.filters.push({type:"cmp",colName:i.colName,expr:i.expr,op:n,value:s,subquery:s}),this.assertSubqueryDepth()):this.filters.push({type:"cmp",colName:i.colName,expr:i.expr,op:n,value:s})}return this}orWhere(t,n,s){if(typeof t=="function"){const i=new Lt(this.db,this.tableName);t(i);const r=i.getRootFilter();r&&(this.addOrFilter(r),this.assertSubqueryDepth())}else if(n===void 0&&s===void 0)if(typeof t=="string"){ct(t);const i=ft(t);this.addOrFilter({type:"expr",expr:i})}else t instanceof it||typeof t=="object"&&t!==null&&"node"in t?(ct(t),this.addOrFilter({type:"expr",expr:t.node})):typeof t=="object"&&t!==null&&"type"in t&&(ct(t),this.addOrFilter({type:"expr",expr:t}));else{if(ct(t),ct(s),typeof n=="string"&&n.trim().toLowerCase()==="in")return this.orWhereIn(t,s);if(typeof n=="string"&&n.trim().toLowerCase()==="not in")return this.orWhereNotIn(t,s);const i=wt(t);x(s)?(this.addOrFilter({type:"cmp",colName:i.colName,expr:i.expr,op:n,value:s,subquery:s}),this.assertSubqueryDepth()):this.addOrFilter({type:"cmp",colName:i.colName,expr:i.expr,op:n,value:s})}return this}whereNot(t,n,s){if(typeof t=="function"){const i=new Lt(this.db,this.tableName);t(i);const r=i.getRootFilter();r&&(this.filters.push({type:"not",child:r}),this.assertSubqueryDepth())}else if(n===void 0&&s===void 0)if(typeof t=="string"){ct(t);const i=ft(t);this.filters.push({type:"not",child:{type:"expr",expr:i}})}else t instanceof it||typeof t=="object"&&t!==null&&"node"in t?(ct(t),this.filters.push({type:"not",child:{type:"expr",expr:t.node}})):typeof t=="object"&&t!==null&&"type"in t&&(ct(t),this.filters.push({type:"not",child:{type:"expr",expr:t}}));else{if(ct(t),ct(s),typeof n=="string"&&n.trim().toLowerCase()==="in")return this.whereNotIn(t,s);if(typeof n=="string"&&n.trim().toLowerCase()==="not in")return this.whereIn(t,s);const i=wt(t);this.filters.push({type:"not",child:{type:"cmp",colName:i.colName,expr:i.expr,op:n,value:s,subquery:x(s)?s:void 0}}),x(s)&&this.assertSubqueryDepth()}return this}orWhereNot(t,n,s){if(typeof t=="function"){const i=new Lt(this.db,this.tableName);t(i);const r=i.getRootFilter();r&&(this.addOrFilter({type:"not",child:r}),this.assertSubqueryDepth())}else if(n===void 0&&s===void 0)if(typeof t=="string"){ct(t);const i=ft(t);this.addOrFilter({type:"not",child:{type:"expr",expr:i}})}else t instanceof it||typeof t=="object"&&t!==null&&"node"in t?(ct(t),this.addOrFilter({type:"not",child:{type:"expr",expr:t.node}})):typeof t=="object"&&t!==null&&"type"in t&&(ct(t),this.addOrFilter({type:"not",child:{type:"expr",expr:t}}));else{if(ct(t),ct(s),typeof n=="string"&&n.trim().toLowerCase()==="in")return this.orWhereNotIn(t,s);if(typeof n=="string"&&n.trim().toLowerCase()==="not in")return this.orWhereIn(t,s);const i=wt(t);this.addOrFilter({type:"not",child:{type:"cmp",colName:i.colName,expr:i.expr,op:n,value:s,subquery:x(s)?s:void 0}}),x(s)&&this.assertSubqueryDepth()}return this}whereRaw(t){return this.where(t)}orWhereRaw(t){return this.orWhere(t)}whereNull(t){return ct(t),this.filters.push({type:"null",colName:t,isNull:!0}),this}whereNotNull(t){return ct(t),this.filters.push({type:"null",colName:t,isNull:!1}),this}orWhereNull(t){return ct(t),this.addOrFilter({type:"null",colName:t,isNull:!0}),this}orWhereNotNull(t){return ct(t),this.addOrFilter({type:"null",colName:t,isNull:!1}),this}whereLike(t,n){return this.where(t,"like",n)}whereNotLike(t,n){return this.where(t,"not like",n)}whereStartsWith(t,n){return this.where(t,"starts_with",n)}whereEndsWith(t,n){return this.where(t,"ends_with",n)}whereContains(t,n){return this.where(t,"contains",n)}orWhereLike(t,n){return this.orWhere(t,"like",n)}orWhereNotLike(t,n){return this.orWhere(t,"not like",n)}orWhereStartsWith(t,n){return this.orWhere(t,"starts_with",n)}orWhereEndsWith(t,n){return this.orWhere(t,"ends_with",n)}orWhereContains(t,n){return this.orWhere(t,"contains",n)}whereIn(t,n){ct(t);const s=wt(t);if(x(n))return this.filters.push({type:"in",colName:s.colName,expr:s.expr,subquery:n,notIn:!1}),this.assertSubqueryDepth(),this;if(!Array.isArray(n))throw new TypeError("WebDB: whereIn requires an array of values");if(n.length>Ft)throw new RangeError(`WebDB: whereIn list exceeds maximum limit of ${Ft} elements`);return this.filters.push({type:"in",colName:s.colName,expr:s.expr,values:n,notIn:!1}),this}whereNotIn(t,n){ct(t);const s=wt(t);if(x(n))return this.filters.push({type:"in",colName:s.colName,expr:s.expr,subquery:n,notIn:!0}),this.assertSubqueryDepth(),this;if(!Array.isArray(n))throw new TypeError("WebDB: whereNotIn requires an array of values");if(n.length>Ft)throw new RangeError(`WebDB: whereNotIn list exceeds maximum limit of ${Ft} elements`);return this.filters.push({type:"in",colName:s.colName,expr:s.expr,values:n,notIn:!0}),this}orWhereIn(t,n){ct(t);const s=wt(t);if(x(n))return this.addOrFilter({type:"in",colName:s.colName,expr:s.expr,subquery:n,notIn:!1}),this.assertSubqueryDepth(),this;if(!Array.isArray(n))throw new TypeError("WebDB: orWhereIn requires an array of values");if(n.length>Ft)throw new RangeError(`WebDB: orWhereIn list exceeds maximum limit of ${Ft} elements`);return this.addOrFilter({type:"in",colName:s.colName,expr:s.expr,values:n,notIn:!1}),this}orWhereNotIn(t,n){ct(t);const s=wt(t);if(x(n))return this.addOrFilter({type:"in",colName:s.colName,expr:s.expr,subquery:n,notIn:!0}),this.assertSubqueryDepth(),this;if(!Array.isArray(n))throw new TypeError("WebDB: orWhereNotIn requires an array of values");if(n.length>Ft)throw new RangeError(`WebDB: orWhereNotIn list exceeds maximum limit of ${Ft} elements`);return this.addOrFilter({type:"in",colName:s.colName,expr:s.expr,values:n,notIn:!0}),this}whereExists(t){if(!x(t))throw new TypeError("WebDB: whereExists requires a QueryBuilder subquery");return this.filters.push({type:"exists",subquery:t,notExists:!1}),this.assertSubqueryDepth(),this}whereNotExists(t){if(!x(t))throw new TypeError("WebDB: whereNotExists requires a QueryBuilder subquery");return this.filters.push({type:"exists",subquery:t,notExists:!0}),this.assertSubqueryDepth(),this}orWhereExists(t){if(!x(t))throw new TypeError("WebDB: orWhereExists requires a QueryBuilder subquery");return this.addOrFilter({type:"exists",subquery:t,notExists:!1}),this.assertSubqueryDepth(),this}orWhereNotExists(t){if(!x(t))throw new TypeError("WebDB: orWhereNotExists requires a QueryBuilder subquery");return this.addOrFilter({type:"exists",subquery:t,notExists:!0}),this.assertSubqueryDepth(),this}getFilters(){return this.filters}getRootFilter(){return this.filters.length===0?null:this.filters.length===1?this.filters[0]:{type:"and",children:[...this.filters]}}addOrFilter(t){if(this.filters.length===0){this.filters.push(t);return}if(this.filters.length===1&&this.filters[0].type==="or"&&this.filters[0].children){this.filters[0].children.push(t);return}let n;this.filters.length===1?n=this.filters[0]:n={type:"and",children:[...this.filters]},this.filters=[{type:"or",children:[n,t]}]}limit(t){return this.limitCount=t,this}offset(t){return this.offsetCount=t,this}orderBy(t,n="asc",s){if(typeof t=="string"){this.sortCol=t,this.sortDir=n;const i=wt(t);this.orderKeys.push({colName:i.colName??t,expr:i.expr,direction:n,nullOrder:s})}else if(t instanceof it||typeof t=="object"&&t!==null&&"node"in t)this.orderKeys.push({expr:t.node,direction:n,nullOrder:s});else if(typeof t=="object"&&t!==null&&"type"in t)this.orderKeys.push({expr:t,direction:n,nullOrder:s});else if(Array.isArray(t))for(const i of t)if(typeof i=="string"){const r=wt(i);this.orderKeys.push({colName:r.colName??i,expr:r.expr,direction:"asc"})}else this.orderKeys.push(i);else this.orderKeys.push(t);return this}groupBy(...t){for(const n of t)if(Array.isArray(n))for(const s of n)this.addGroupByItem(s);else this.addGroupByItem(n);return this}addGroupByItem(t){if(t instanceof it||typeof t=="object"&&t!==null&&"node"in t)this.groupKeys.push({expr:t.node}),this.groupCols.push(Qt(t.node));else if(typeof t=="object"&&t!==null&&"type"in t)this.groupKeys.push({expr:t}),this.groupCols.push(Qt(t));else if(typeof t=="string"){const n=wt(t);this.groupKeys.push({colName:n.colName??t,expr:n.expr}),this.groupCols.push(t)}}registerAggregatesFromFilter(t){const n=(s,i)=>{if(i){const r=nr(i);for(const o of r)this.aggExprs.some(c=>c.func===o.func&&(c.colName===o.colName||c.colName===void 0&&o.colName===void 0))||this.aggExprs.push(o)}else if(s&&s.includes("("))try{const r=ft(s),o=nr(r);for(const a of o)this.aggExprs.some(l=>l.func===a.func&&(l.colName===a.colName||l.colName===void 0&&a.colName===void 0))||this.aggExprs.push(a)}catch{}};if(t.type==="cmp")n(t.colName,t.expr);else if(t.type==="expr"&&t.expr)n(void 0,t.expr);else if(t.type==="null")n(t.colName,t.expr);else if(t.type==="not"&&t.child)this.registerAggregatesFromFilter(t.child);else if((t.type==="and"||t.type==="or")&&t.children)for(const s of t.children)this.registerAggregatesFromFilter(s)}having(t,n,s){if(typeof t=="function"){const i=new Lt(this.db,this.tableName);t(i);const r=i.getRootHavingFilter();r&&(this.havingFilters.push(r),this.registerAggregatesFromFilter(r),this.assertSubqueryDepth())}else if(n===void 0&&s===void 0){if(typeof t=="string"){const r={type:"expr",expr:ft(t)};this.havingFilters.push(r),this.registerAggregatesFromFilter(r)}else if(t instanceof it||typeof t=="object"&&t!==null&&"node"in t){const i={type:"expr",expr:t.node};this.havingFilters.push(i),this.registerAggregatesFromFilter(i)}else if(typeof t=="object"&&t!==null&&"type"in t){const i={type:"expr",expr:t};this.havingFilters.push(i),this.registerAggregatesFromFilter(i)}}else{const i=wt(t);if(typeof n=="string"&&(n.trim().toLowerCase()==="in"||n.trim().toLowerCase()==="not in")){const o=n.trim().toLowerCase()==="not in",a=x(s)?{type:"in",colName:i.colName,expr:i.expr,subquery:s,notIn:o}:{type:"in",colName:i.colName,expr:i.expr,values:s,notIn:o};return this.havingFilters.push(a),this.registerAggregatesFromFilter(a),this.assertSubqueryDepth(),this}const r={type:"cmp",colName:i.colName,expr:i.expr,op:n,value:s,subquery:x(s)?s:void 0};this.havingFilters.push(r),this.registerAggregatesFromFilter(r),x(s)&&this.assertSubqueryDepth()}return this}orHaving(t,n,s){if(typeof t=="function"){const i=new Lt(this.db,this.tableName);t(i);const r=i.getRootHavingFilter();r&&(this.addHavingOrFilter(r),this.registerAggregatesFromFilter(r),this.assertSubqueryDepth())}else if(n===void 0&&s===void 0){if(typeof t=="string"){const r={type:"expr",expr:ft(t)};this.addHavingOrFilter(r),this.registerAggregatesFromFilter(r)}else if(t instanceof it||typeof t=="object"&&t!==null&&"node"in t){const i={type:"expr",expr:t.node};this.addHavingOrFilter(i),this.registerAggregatesFromFilter(i)}else if(typeof t=="object"&&t!==null&&"type"in t){const i={type:"expr",expr:t};this.addHavingOrFilter(i),this.registerAggregatesFromFilter(i)}}else{const i=wt(t),r={type:"cmp",colName:i.colName,expr:i.expr,op:n,value:s,subquery:x(s)?s:void 0};this.addHavingOrFilter(r),this.registerAggregatesFromFilter(r),x(s)&&this.assertSubqueryDepth()}return this}havingNot(t,n,s){if(typeof t=="function"){const i=new Lt(this.db,this.tableName);t(i);const r=i.getRootHavingFilter();if(r){const o={type:"not",child:r};this.havingFilters.push(o),this.registerAggregatesFromFilter(o),this.assertSubqueryDepth()}}else if(n===void 0&&s===void 0){if(typeof t=="string"){const r={type:"not",child:{type:"expr",expr:ft(t)}};this.havingFilters.push(r),this.registerAggregatesFromFilter(r)}else if(t instanceof it||typeof t=="object"&&t!==null&&"node"in t){const i={type:"not",child:{type:"expr",expr:t.node}};this.havingFilters.push(i),this.registerAggregatesFromFilter(i)}else if(typeof t=="object"&&t!==null&&"type"in t){const i={type:"not",child:{type:"expr",expr:t}};this.havingFilters.push(i),this.registerAggregatesFromFilter(i)}}else{const i=wt(t),r={type:"not",child:{type:"cmp",colName:i.colName,expr:i.expr,op:n,value:s,subquery:x(s)?s:void 0}};this.havingFilters.push(r),this.registerAggregatesFromFilter(r),x(s)&&this.assertSubqueryDepth()}return this}orHavingNot(t,n,s){if(typeof t=="function"){const i=new Lt(this.db,this.tableName);t(i);const r=i.getRootHavingFilter();if(r){const o={type:"not",child:r};this.addHavingOrFilter(o),this.registerAggregatesFromFilter(o),this.assertSubqueryDepth()}}else if(n===void 0&&s===void 0){if(typeof t=="string"){const r={type:"not",child:{type:"expr",expr:ft(t)}};this.addHavingOrFilter(r),this.registerAggregatesFromFilter(r)}else if(t instanceof it||typeof t=="object"&&t!==null&&"node"in t){const i={type:"not",child:{type:"expr",expr:t.node}};this.addHavingOrFilter(i),this.registerAggregatesFromFilter(i)}else if(typeof t=="object"&&t!==null&&"type"in t){const i={type:"not",child:{type:"expr",expr:t}};this.addHavingOrFilter(i),this.registerAggregatesFromFilter(i)}}else{const i=wt(t),r={type:"not",child:{type:"cmp",colName:i.colName,expr:i.expr,op:n,value:s,subquery:x(s)?s:void 0}};this.addHavingOrFilter(r),this.registerAggregatesFromFilter(r),x(s)&&this.assertSubqueryDepth()}return this}havingRaw(t){return this.having(t)}orHavingRaw(t){return this.orHaving(t)}havingNull(t){const n=wt(t),s={type:"null",colName:n.colName,expr:n.expr,isNull:!0};return this.havingFilters.push(s),this.registerAggregatesFromFilter(s),this}havingNotNull(t){const n=wt(t),s={type:"null",colName:n.colName,expr:n.expr,isNull:!1};return this.havingFilters.push(s),this.registerAggregatesFromFilter(s),this}orHavingNull(t){const n=wt(t),s={type:"null",colName:n.colName,expr:n.expr,isNull:!0};return this.addHavingOrFilter(s),this.registerAggregatesFromFilter(s),this}orHavingNotNull(t){const n=wt(t),s={type:"null",colName:n.colName,expr:n.expr,isNull:!1};return this.addHavingOrFilter(s),this.registerAggregatesFromFilter(s),this}getHavingFilters(){return this.havingFilters}getRootHavingFilter(){return this.havingFilters.length===0?null:this.havingFilters.length===1?this.havingFilters[0]:{type:"and",children:[...this.havingFilters]}}addHavingOrFilter(t){if(this.havingFilters.length===0){this.havingFilters.push(t);return}if(this.havingFilters.length===1&&this.havingFilters[0].type==="or"&&this.havingFilters[0].children){this.havingFilters[0].children.push(t);return}let n;this.havingFilters.length===1?n=this.havingFilters[0]:n={type:"and",children:[...this.havingFilters]},this.havingFilters=[{type:"or",children:[n,t]}]}aggregate(t){return this.aggExprs.push(...t),this}count(t,n){return this.aggExprs.push({func:"count",colName:t,alias:n}),this}sum(t,n){return this.aggExprs.push({func:"sum",colName:t,alias:n}),this}avg(t,n){return this.aggExprs.push({func:"avg",colName:t,alias:n}),this}min(t,n){return this.aggExprs.push({func:"min",colName:t,alias:n}),this}max(t,n){return this.aggExprs.push({func:"max",colName:t,alias:n}),this}select(t,...n){if(t===void 0)return this;const s=[];s.push(...Ms(t));for(const i of n)s.push(...Ms(i));this.selectFields.push(...s),this.assertSubqueryDepth();for(const i of s)if(i.expr&&i.expr.type==="fn"){const r=i.expr.name.toLowerCase();if(ge(r)&&!this.aggExprs.some(a=>a.alias===i.alias)){const a=i.expr.args[0],c=a&&a.type==="col"&&a.name!=="*"?a.name:void 0;this.aggExprs.push({func:r,colName:c,alias:i.alias})}}else if(typeof i.fn=="string"){const r=i.fn.toLowerCase();ge(r)&&(this.aggExprs.some(a=>a.alias===i.alias)||this.aggExprs.push({func:r,colName:i.sourceCol==="*"?void 0:i.sourceCol,alias:i.alias}))}return this}getSelectFields(){return this.selectFields}clone(t){const n=t??this.db,s=new Lt(n,this.sourceSubquery?this.sourceSubquery.clone(n):this.tableName),i=r=>({...r,values:r.values?[...r.values]:void 0,subquery:r.subquery&&x(r.subquery)?r.subquery.clone(n):r.subquery,value:x(r.value)?r.value.clone(n):r.value,child:r.child?i(r.child):void 0,children:r.children?r.children.map(i):void 0});return s.filters=this.filters.map(i),s.selectFields=this.selectFields.map(r=>({...r,args:r.args?[...r.args]:void 0,subquery:r.subquery?r.subquery.clone(n):void 0})),s.limitCount=this.limitCount,s.offsetCount=this.offsetCount,s.sortCol=this.sortCol,s.sortDir=this.sortDir,s.orderKeys=this.orderKeys.map(r=>({...r})),s.groupCols=[...this.groupCols],s.groupKeys=this.groupKeys.map(r=>({...r})),s.aggExprs=this.aggExprs.map(r=>({...r})),s.havingFilters=this.havingFilters.map(i),s.joins=this.joins.map(r=>({...r})),s.planner=this.planner,s}cloneExprNode(t){return t.type==="binary"?{...t,left:this.cloneExprNode(t.left),right:this.cloneExprNode(t.right)}:t.type==="fn"?{...t,args:t.args.map(n=>this.cloneExprNode(n))}:{...t}}substituteExpr(t,n){if(t.type==="col"){if(t.name==="*")return t;const s=t.name.includes(".")?t.name.slice(t.name.lastIndexOf(".")+1):t.name,i=n.get(t.name)??n.get(s);return i?this.cloneExprNode(i):{...t}}return t.type==="binary"?{...t,left:this.substituteExpr(t.left,n),right:this.substituteExpr(t.right,n)}:t.type==="fn"?{...t,args:t.args.map(s=>this.substituteExpr(s,n))}:{...t}}substituteColOrExpr(t,n,s){if(n){const i=this.substituteExpr(n,s);return i.type==="col"?{colName:i.name,expr:i}:{expr:i}}if(t){const i=t.includes(".")?t.slice(t.lastIndexOf(".")+1):t,r=s.get(t)??s.get(i);if(r){const o=this.cloneExprNode(r);return o.type==="col"?{colName:o.name}:{expr:o}}return{colName:t}}return{colName:t,expr:n}}substituteFilter(t,n){var i;if(t.type==="and"||t.type==="or")return{...t,children:(i=t.children)==null?void 0:i.map(r=>this.substituteFilter(r,n))};if(t.type==="not"&&t.child)return{...t,child:this.substituteFilter(t.child,n)};if(t.type==="exists")return{...t};const s=this.substituteColOrExpr(t.colName,t.expr,n);return{...t,colName:s.colName,expr:s.expr}}tryFlatten(){var r;if(!this.sourceSubquery)return null;const t=this.sourceSubquery.tryFlatten()??this.sourceSubquery.clone(this.db);if(t.sourceSubquery||t.groupKeys.length>0||t.groupCols.length>0||t.aggExprs.length>0||t.havingFilters.length>0||t.limitCount!==null||t.offsetCount!==null||t.joins.length>0||t.selectFields.some(o=>o.subquery)||this.joins.length>0)return null;const n=new Map;for(const o of t.selectFields){const a=o.expr??{type:"col",name:o.sourceCol??o.alias};n.set(o.alias,a)}for(const o of this.aggExprs)if(o.colName){const a=o.colName.includes(".")?o.colName.slice(o.colName.lastIndexOf(".")+1):o.colName,c=n.get(o.colName)??n.get(a);if(c&&c.type!=="col")return null}for(const o of this.groupKeys){const a=this.substituteColOrExpr(o.colName,o.expr,n);if(!a.colName&&a.expr&&a.expr.type!=="col")return null}const s=new Lt(this.db,t.tableName);s.planner=this.planner??t.planner,s.filters=[...t.filters.map(o=>({...o})),...this.filters.map(o=>this.substituteFilter(o,n))],this.selectFields.length>0?s.selectFields=this.selectFields.map(o=>{if(o.subquery)return{...o,subquery:o.subquery.clone(this.db)};const a=o.expr??{type:"col",name:o.sourceCol??o.alias},c=this.substituteExpr(a,n);return{alias:o.alias,expr:c,sourceCol:c.type==="col"&&c.name!=="*"?c.name:void 0,fn:c.type==="fn"?c.name:void 0}}):t.selectFields.length>0&&(s.selectFields=t.selectFields.map(o=>({...o})));const i=this.aggExprs.length>0||this.groupKeys.length>0||this.groupCols.length>0;return this.orderKeys.length>0?(s.orderKeys=this.orderKeys.map(o=>{const a=this.substituteColOrExpr(o.colName,o.expr,n);return{...o,colName:a.colName,expr:a.expr}}),(r=s.orderKeys[0])!=null&&r.colName&&(s.sortCol=s.orderKeys[0].colName,s.sortDir=s.orderKeys[0].direction)):!i&&t.orderKeys.length>0&&(s.orderKeys=t.orderKeys.map(o=>({...o})),s.sortCol=t.sortCol,s.sortDir=t.sortDir),s.groupKeys=this.groupKeys.map(o=>{const a=this.substituteColOrExpr(o.colName,o.expr,n);return{colName:a.colName,expr:a.expr}}),s.groupCols=this.groupCols.map(o=>{const a=n.get(o);return a&&a.type==="col"?a.name:o}),s.aggExprs=this.aggExprs.map(o=>{if(o.colName){const a=n.get(o.colName);if(a&&a.type==="col")return{...o,colName:a.name}}return{...o}}),s.havingFilters=this.havingFilters.map(o=>this.substituteFilter(o,n)),s.limitCount=this.limitCount,s.offsetCount=this.offsetCount,s}exprReferencesOuter(t,n){if(!t)return!1;if(t.type==="col"){if(t.name.includes(".")){const s=t.name.slice(0,t.name.indexOf("."));if(s==="outer"||!n.has(s))return!0}return!1}return t.type==="binary"?this.exprReferencesOuter(t.left,n)||this.exprReferencesOuter(t.right,n):t.type==="fn"?t.args.some(s=>this.exprReferencesOuter(s,n)):!1}filterIsCorrelatedWithOuter(t,n){var s;if(t.type==="and"||t.type==="or")return((s=t.children)==null?void 0:s.some(i=>this.filterIsCorrelatedWithOuter(i,n)))??!1;if(t.type==="not"&&t.child)return this.filterIsCorrelatedWithOuter(t.child,n);if(t.type==="cmp"&&(t.value instanceof it||typeof t.value=="object"&&t.value!==null&&!x(t.value)&&("node"in t.value||"type"in t.value)||t.subquery&&x(t.subquery)&&this.isSubqueryCorrelated(t.subquery))||(t.type==="in"||t.type==="exists")&&t.subquery&&x(t.subquery)&&this.isSubqueryCorrelated(t.subquery))return!0;if(t.colName&&t.colName.includes(".")){const i=t.colName.slice(0,t.colName.indexOf("."));if(i==="outer"||!n.has(i))return!0}return!!this.exprReferencesOuter(t.expr,n)}isSubqueryCorrelated(t){const n=new Set([t.tableName]);for(const s of t.joins)n.add(s.table);return!!(t.filters.some(s=>this.filterIsCorrelatedWithOuter(s,n))||t.havingFilters.some(s=>this.filterIsCorrelatedWithOuter(s,n))||t.sourceSubquery&&this.isSubqueryCorrelated(t.sourceSubquery)||t.selectFields.some(s=>s.subquery&&this.isSubqueryCorrelated(s.subquery)))}filterContainsCorrelatedSubquery(t){var s;if(t.type==="and"||t.type==="or")return((s=t.children)==null?void 0:s.some(i=>this.filterContainsCorrelatedSubquery(i)))??!1;if(t.type==="not"&&t.child)return this.filterContainsCorrelatedSubquery(t.child);const n=t.subquery&&x(t.subquery)?t.subquery:x(t.value)?t.value:void 0;return!!(n&&this.isSubqueryCorrelated(n))}getRowValue(t,n){if(n in t)return t[n];if(n.startsWith("outer.")){const s=n.slice(6);if(s in t)return t[s]}if(n.includes(".")){const s=n.slice(n.lastIndexOf(".")+1);if(s in t)return t[s]}}bindOuterRowToExpr(t,n,s,i=!1){if(t.type==="col"){if(i)return{type:"literal",value:this.getRowValue(n,t.name)??null};if(t.name.includes(".")){const r=t.name.slice(0,t.name.indexOf("."));if(r==="outer"||!s.has(r))return{type:"literal",value:this.getRowValue(n,t.name)??null}}return{...t}}return t.type==="binary"?{...t,left:this.bindOuterRowToExpr(t.left,n,s,i),right:this.bindOuterRowToExpr(t.right,n,s,i)}:t.type==="fn"?{...t,args:t.args.map(r=>this.bindOuterRowToExpr(r,n,s,i))}:{...t}}bindOuterRowToFilter(t,n,s){var r;if(t.type==="and"||t.type==="or")return{...t,children:(r=t.children)==null?void 0:r.map(o=>this.bindOuterRowToFilter(o,n,s))};if(t.type==="not"&&t.child)return{...t,child:this.bindOuterRowToFilter(t.child,n,s)};let i=t.expr?this.bindOuterRowToExpr(t.expr,n,s,!1):void 0;if(t.type==="cmp"&&(t.value instanceof it||typeof t.value=="object"&&t.value!==null&&!x(t.value)&&("node"in t.value||"type"in t.value))){const o="node"in t.value?t.value.node:t.value,a=this.bindOuterRowToExpr(o,n,s,!0);let c;typeof this.db.getUdf=="function"&&(c=u=>{var _,f;return(f=(_=this.db.getUdf(u))==null?void 0:_.def)==null?void 0:f.call});const l=vt(a,n,c);return l==null?{type:"in",values:[],notIn:!1}:{...t,expr:i,value:l}}return{...t,expr:i,subquery:t.subquery&&x(t.subquery)?this.bindOuterRowToSubquery(t.subquery,n):t.subquery}}bindOuterRowToSubquery(t,n){const s=t.clone(this.db),i=new Set([s.tableName]);for(const r of s.joins)i.add(r.table);return s.filters=s.filters.map(r=>this.bindOuterRowToFilter(r,n,i)),s.havingFilters=s.havingFilters.map(r=>this.bindOuterRowToFilter(r,n,i)),s.sourceSubquery&&(s.sourceSubquery=this.bindOuterRowToSubquery(s.sourceSubquery,n)),s}async evalScalarSubquery(t,n){const i=await(n&&this.isSubqueryCorrelated(t)?this.bindOuterRowToSubquery(t,n):t.clone(this.db)).first();if(!i)return null;const r=Object.keys(i);return r.length>0?i[r[0]]:null}async resolveUncorrelatedFilter(t){if(t.type==="and"||t.type==="or"){const n=[];for(const s of t.children??[])n.push(await this.resolveUncorrelatedFilter(s));return{...t,children:n}}if(t.type==="not"&&t.child)return{...t,child:await this.resolveUncorrelatedFilter(t.child)};if(t.type==="in"&&t.subquery&&x(t.subquery)&&!this.isSubqueryCorrelated(t.subquery)){const s=(await t.subquery.clone(this.db).toArray()).map(r=>{const o=Object.keys(r);return o.length>0?r[o[0]]:null});if(t.notIn&&s.some(r=>r==null))return{type:"in",colName:t.colName,expr:t.expr,values:[],notIn:!1};const i=s.filter(r=>r!=null);if(i.length>Ft)throw new RangeError(`WebDB: whereIn subquery result exceeds maximum limit of ${Ft} elements`);return{type:"in",colName:t.colName,expr:t.expr,values:i,notIn:t.notIn}}if(t.type==="exists"&&t.subquery&&x(t.subquery)&&!this.isSubqueryCorrelated(t.subquery)){const s=await t.subquery.clone(this.db).first()!==null,i=t.notExists?!s:s;return{type:"in",values:[],notIn:i}}if(t.type==="cmp"){const n=t.subquery&&x(t.subquery)?t.subquery:x(t.value)?t.value:void 0;if(n&&!this.isSubqueryCorrelated(n)){const s=await this.evalScalarSubquery(n);return s==null?{type:"in",colName:t.colName,expr:t.expr,values:[],notIn:!1}:{...t,value:s,subquery:void 0}}}return t}async resolveUncorrelatedFilters(t){const n=[];for(const s of t)n.push(await this.resolveUncorrelatedFilter(s));return n}evalFilterTargetValue(t,n,s){let i;if(typeof this.db.getUdf=="function"&&(i=r=>{var o,a;return(a=(o=this.db.getUdf(r))==null?void 0:o.def)==null?void 0:a.call}),n&&t[n]!==void 0)return t[n];if(s){const r=Qt(s);return t[r]!==void 0?t[r]:vt(s,t,i)}if(n)return this.getRowValue(t,n)}evalComparisonValues(t,n,s){if(t==null||s===null||s===void 0)return!1;const i=(n??"=").trim().toLowerCase();switch(i){case"=":return t===s;case"!=":case"<>":return t!==s;case"<":return t<s;case"<=":return t<=s;case">":return t>s;case">=":return t>=s;case"starts_with":return String(t).startsWith(String(s));case"ends_with":return String(t).endsWith(String(s));case"contains":return String(t).includes(String(s));case"like":case"not like":{const r=String(s).replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/%/g,".*").replace(/_/g,"."),a=new RegExp(`^${r}$`,"s").test(String(t));return i==="not like"?!a:a}default:return t===s}}async evalFilterOnRow(t,n){if(n.type==="and"){for(const s of n.children??[])if(!await this.evalFilterOnRow(t,s))return!1;return!0}if(n.type==="or"){for(const s of n.children??[])if(await this.evalFilterOnRow(t,s))return!0;return!1}if(n.type==="not"&&n.child){if(n.child.type==="cmp"||n.child.type==="in"){const s=this.evalFilterTargetValue(t,n.child.colName,n.child.expr);if(s==null)return!1}return!await this.evalFilterOnRow(t,n.child)}if(n.type==="null"){const s=this.evalFilterTargetValue(t,n.colName,n.expr),i=s==null;return n.isNull?i:!i}if(n.type==="expr"&&n.expr){let s;typeof this.db.getUdf=="function"&&(s=r=>{var o,a;return(a=(o=this.db.getUdf(r))==null?void 0:o.def)==null?void 0:a.call});const i=vt(n.expr,t,s);return!!(i&&i!==0)}if(n.type==="exists"){if(n.subquery&&x(n.subquery)){const r=await(this.isSubqueryCorrelated(n.subquery)?this.bindOuterRowToSubquery(n.subquery,t):n.subquery.clone(this.db)).first()!==null;return n.notExists?!r:r}return!!n.notExists}if(n.type==="in"){let s=n.values??[];if(n.subquery&&x(n.subquery)){const c=(await(this.isSubqueryCorrelated(n.subquery)?this.bindOuterRowToSubquery(n.subquery,t):n.subquery.clone(this.db)).toArray()).map(l=>{const u=Object.keys(l);return u.length>0?l[u[0]]:null});if(n.notIn&&c.some(l=>l==null))return!1;s=c.filter(l=>l!=null)}if(!n.colName&&!n.expr)return n.notIn?s.length===0:s.length>0;if(s.length===0)return!!n.notIn;const i=this.evalFilterTargetValue(t,n.colName,n.expr);if(i==null||n.notIn&&s.some(o=>o==null))return!1;const r=s.includes(i);return n.notIn?!r:r}if(n.type==="cmp"){const s=this.evalFilterTargetValue(t,n.colName,n.expr),i=n.subquery&&x(n.subquery)?n.subquery:x(n.value)?n.value:void 0,r=i?await this.evalScalarSubquery(i,t):n.value;return this.evalComparisonValues(s,n.op,r)}return!0}async evalFiltersOnRows(t,n){if(n.length===0)return t;const s=await this.resolveUncorrelatedFilters(n),i=[];for(const r of t){let o=!0;for(const a of s)if(!await this.evalFilterOnRow(r,a)){o=!1;break}o&&i.push(r)}return i}performInMemoryAggregation(t){const n=Math.max(this.groupKeys.length,this.groupCols.length),s=new Map;if(n===0)s.set("__global__",{keyRow:{},rows:t});else for(const a of t){const c=[],l={};for(let f=0;f<n;f++){const h=this.groupKeys[f],g=this.groupCols[f],d=this.evalFilterTargetValue(a,(h==null?void 0:h.colName)??g,h==null?void 0:h.expr);c.push(d);const I=(h==null?void 0:h.colName)??(h!=null&&h.expr?Qt(h.expr):g);I&&(l[I]=d,I.includes(".")&&(l[I.slice(I.lastIndexOf(".")+1)]=d)),g&&(l[g]=d)}const u=JSON.stringify(c);let _=s.get(u);_||(_={keyRow:l,rows:[]},s.set(u,_)),_.rows.push(a)}let i;typeof this.db.getUdf=="function"&&(i=a=>{var c,l;return(l=(c=this.db.getUdf(a))==null?void 0:c.def)==null?void 0:l.call});const r=(a,c,l,u)=>{const _=c.toLowerCase();if(_==="count"){if(!l&&(!u||u.type==="col"&&u.name==="*"))return a.length;let h=0;for(const g of a){const d=u?vt(u,g,i):this.getRowValue(g,l);d!=null&&h++}return h}const f=[];for(const h of a){const g=u?vt(u,h,i):l?this.getRowValue(h,l):null;g!=null&&f.push(g)}return f.length===0?null:_==="sum"?f.reduce((h,g)=>h+Number(g),0):_==="avg"?f.reduce((h,g)=>h+Number(g),0)/f.length:_==="min"?f.reduce((h,g)=>g<h?g:h,f[0]):_==="max"?f.reduce((h,g)=>g>h?g:h,f[0]):null},o=[];for(const{keyRow:a,rows:c}of s.values()){const l={...a};for(const u of this.aggExprs){const _=r(c,u.func,u.colName),f=u.alias??(u.colName?`${u.func}_${u.colName}`:u.func);l[f]=_,l[`${u.func}(${u.colName??"*"})`]=_,u.colName||(l[u.func]=_)}for(const u of this.selectFields)if(u.expr&&u.expr.type==="fn"&&ge(u.expr.name)){const _=u.expr.args[0],f=r(c,u.expr.name,_&&_.type==="col"&&_.name!=="*"?_.name:void 0,_);l[u.alias]=f,l[Qt(u.expr)]=f}o.push(l)}return o}async attachSelectSubqueries(t){const n=this.selectFields.filter(i=>i.subquery);if(n.length===0||t.length===0)return;const s=new Map;for(const i of n)if(i.subquery&&!this.isSubqueryCorrelated(i.subquery)){const r=await this.evalScalarSubquery(i.subquery);s.set(i,r)}for(const i of t)for(const r of n)s.has(r)?i[r.alias]=s.get(r):r.subquery&&(i[r.alias]=await this.evalScalarSubquery(r.subquery,i))}async executeMaterializedDerivedTable(){let t=await this.sourceSubquery.clone(this.db).toArray();for(const r of this.joins){const o=await new Lt(this.db,r.table).toArray(),a=[];for(const c of t){let l=!1;const u=this.getRowValue(c,r.leftCol);for(const _ of o){const f=this.getRowValue(_,r.rightCol);if(this.evalComparisonValues(u,r.op,f)){l=!0;const h={...c};for(const[g,d]of Object.entries(_))h[`${r.table}.${g}`]=d,g in h||(h[g]=d);a.push(h)}}!l&&r.type==="left"&&a.push({...c})}t=a}t=await this.evalFiltersOnRows(t,this.filters),(this.aggExprs.length>0||this.groupKeys.length>0||this.groupCols.length>0)&&(t=this.performInMemoryAggregation(t),this.havingFilters.length>0&&(t=await this.evalFiltersOnRows(t,this.havingFilters)));const s=this.selectFields.some(r=>r.subquery),i=s&&this.orderKeys.some(r=>this.selectFields.some(o=>o.subquery&&(o.alias===r.colName||o.alias===(r.expr?Qt(r.expr):void 0))));return i&&await this.attachSelectSubqueries(t),this.orderKeys.length>0&&(t=this.sortAggregatedRows(t)),this.offsetCount!==null&&this.offsetCount>0&&(t=t.slice(this.offsetCount)),this.limitCount!==null&&this.limitCount>=0&&(t=t.slice(0,this.limitCount)),s&&!i&&await this.attachSelectSubqueries(t),this.selectFields.length>0&&(t=t.map(r=>this.projectRow(r))),t}projectRow(t){const n=Object.keys(t);if(this.selectFields.length>0&&n.length===this.selectFields.length&&this.selectFields.every(i=>i.alias in t))return t;const s={};for(const i of this.selectFields){const r=i.alias;if(t[r]!==void 0)s[r]=t[r];else if(i.expr&&t[Qt(i.expr)]!==void 0)s[r]=t[Qt(i.expr)];else if(i.sourceCol!==void 0&&t[i.sourceCol]!==void 0)s[r]=t[i.sourceCol];else if(i.expr){let o;typeof this.db.getUdf=="function"&&(o=a=>{var c,l;return(l=(c=this.db.getUdf(a))==null?void 0:c.def)==null?void 0:l.call}),s[r]=vt(i.expr,t,o)}else s[r]=null}return s}async explain(){if(this.assertSubqueryDepth(),this.sourceSubquery){const r=this.tryFlatten();if(r)return r.explain();const o=await this.sourceSubquery.clone(this.db).explain(),a=await this.resolveUncorrelatedFilters(this.filters);return{plan:{...o.plan,filters:[...o.plan.filters,...a],orderBy:this.orderKeys.length>0?this.orderKeys:o.plan.orderBy,groupBy:this.groupKeys.length>0?this.groupKeys:this.groupCols.length>0?this.groupCols:o.plan.groupBy,aggregates:this.aggExprs.length>0?this.aggExprs:o.plan.aggregates,having:this.havingFilters.length>0?this.havingFilters:o.plan.having,select:this.selectFields.length>0?this.selectFields:o.plan.select,limit:this.limitCount!==null?this.limitCount:o.plan.limit,offset:this.offsetCount!==null?this.offsetCount:o.plan.offset},bytecodeSize:o.bytecodeSize,instructions:o.instructions,assembly:o.assembly}}const t=await this.resolveUncorrelatedFilters(this.filters.filter(r=>!this.filterContainsCorrelatedSubquery(r))),n=await this.resolveUncorrelatedFilters(this.havingFilters.filter(r=>!this.filterContainsCorrelatedSubquery(r))),s=this.selectFields.filter(r=>!r.subquery),i=s.map(r=>({expr:r.expr??{type:"col",name:r.sourceCol??r.alias},alias:r.alias}));return this.db.explainQuery(this.tableName,t,{joins:this.joins.length>0?this.joins:void 0,orderBy:this.orderKeys.length>0?this.orderKeys:void 0,groupBy:this.groupKeys.length>0?this.groupKeys:this.groupCols.length>0?this.groupCols:void 0,aggregates:this.aggExprs.length>0?this.aggExprs:void 0,having:n.length>0?n:void 0,select:s.length>0?s:void 0,selectExprs:i.length>0?i:void 0,limit:this.limitCount!==null?this.limitCount:void 0,offset:this.offsetCount!==null?this.offsetCount:void 0,planner:this.planner})}getOrderKeyValue(t,n){const s=n.colName??(n.expr?Qt(n.expr):void 0);if(!s)return;if(t[s]!==void 0)return t[s];const i=s.includes(".")?s.slice(s.lastIndexOf(".")+1):s;if(t[i]!==void 0)return t[i];if(this.selectFields.length>0){for(const r of this.selectFields)if((r.sourceCol===s||r.sourceCol===i||r.alias===s||r.alias===i)&&t[r.alias]!==void 0)return t[r.alias]}if(t[`__sort_${s}`]!==void 0)return t[`__sort_${s}`];if(t[`__sort_${i}`]!==void 0)return t[`__sort_${i}`];if(n.expr){let r;return typeof this.db.getUdf=="function"&&(r=o=>{var a,c;return(c=(a=this.db.getUdf(o))==null?void 0:a.def)==null?void 0:c.call}),vt(n.expr,t,r)}}sortAggregatedRows(t){return[...t].sort((n,s)=>{for(const i of this.orderKeys){const r=this.getOrderKeyValue(n,i),o=this.getOrderKeyValue(s,i);if(r===o)continue;if(r==null)return i.nullOrder==="nulls_first"?-1:1;if(o==null)return i.nullOrder==="nulls_first"?1:-1;const a=i.direction==="desc"?-1:1;return typeof r=="number"&&typeof o=="number"?(r-o)*a:String(r).localeCompare(String(o))*a}return 0})}async toArray(){if(this.assertSubqueryDepth(),this.sourceSubquery){const p=this.tryFlatten();return p?p.toArray():this.executeMaterializedDerivedTable()}const t=this.filters.some(p=>this.filterContainsCorrelatedSubquery(p)),n=this.havingFilters.some(p=>this.filterContainsCorrelatedSubquery(p)),s=this.selectFields.some(p=>p.subquery),i=this.selectFields.some(p=>p.subquery&&this.isSubqueryCorrelated(p.subquery)),r=await this.resolveUncorrelatedFilters(this.filters.filter(p=>!this.filterContainsCorrelatedSubquery(p))),o=this.filters.filter(p=>this.filterContainsCorrelatedSubquery(p)),a=this.joins.length>0,c=this.orderKeys.length>0,l=this.aggExprs.length>0||this.groupKeys.length>0||this.groupCols.length>0;if(t){let p=await this.db.executeQuery(this.tableName,r,{limit:null,offset:null,sortCol:null,sortDir:this.sortDir,joins:a?this.joins:void 0,planner:this.planner});return p=await this.evalFiltersOnRows(p,o),l&&(p=this.performInMemoryAggregation(p),this.havingFilters.length>0&&(p=await this.evalFiltersOnRows(p,this.havingFilters))),s&&await this.attachSelectSubqueries(p),c&&(p=this.sortAggregatedRows(p)),this.offsetCount!==null&&this.offsetCount>0&&(p=p.slice(this.offsetCount)),this.limitCount!==null&&this.limitCount>=0&&(p=p.slice(0,this.limitCount)),this.selectFields.length>0&&(p=p.map(y=>this.projectRow(y))),p}const u=await this.resolveUncorrelatedFilters(this.havingFilters.filter(p=>!this.filterContainsCorrelatedSubquery(p))),_=this.selectFields.filter(p=>!p.subquery),f=_.map(p=>({expr:p.expr??{type:"col",name:p.sourceCol??p.alias},alias:p.alias}));if(a&&c&&f.length>0)for(const p of this.orderKeys){const y=p.colName;if(y){const T=y.includes(".")?y.slice(y.lastIndexOf(".")+1):y;_.some(b=>b.alias===y||b.alias===T||b.sourceCol===y||b.sourceCol===T)||f.push({expr:{type:"col",name:y},alias:`__sort_${y}`})}}const h=!i||l,g=await this.db.executeQuery(this.tableName,r,{limit:a&&c&&l||n?null:this.limitCount,offset:a&&c&&l||n?null:this.offsetCount,sortCol:a?null:this.sortCol,sortDir:this.sortDir,orderBy:a&&l?void 0:c?this.orderKeys:void 0,joins:a?this.joins:void 0,groupBy:this.groupKeys.length>0?this.groupKeys:this.groupCols.length>0?this.groupCols:void 0,aggregates:this.aggExprs.length>0?this.aggExprs:void 0,having:u.length>0?u:void 0,select:h&&_.length>0?_:void 0,selectExprs:h&&f.length>0?f:void 0,planner:this.planner});let d=g;if(n){const p=this.havingFilters.filter(y=>this.filterContainsCorrelatedSubquery(y));d=await this.evalFiltersOnRows(d,p)}const I=g.isOrderSatisfied===!0;return(l||a)&&c&&!I?(d=this.sortAggregatedRows(d),(a||n)&&(this.offsetCount!==null&&this.offsetCount>0&&(d=d.slice(this.offsetCount)),this.limitCount!==null&&this.limitCount>=0&&(d=d.slice(0,this.limitCount)))):n&&(this.offsetCount!==null&&this.offsetCount>0&&(d=d.slice(this.offsetCount)),this.limitCount!==null&&this.limitCount>=0&&(d=d.slice(0,this.limitCount))),s&&await this.attachSelectSubqueries(d),this.selectFields.length>0&&(d=d.map(p=>this.projectRow(p))),d}async first(){const t=await this.limit(1).toArray();return t.length>0?t[0]:null}async update(t,n){if(!this.db.executeUpdate)throw new Error("Database executor does not support executeUpdate");this.assertSubqueryDepth();const s=await this.resolveUncorrelatedFilters(this.filters);return this.db.executeUpdate(this.tableName,s,t,n)}async delete(t){if(!this.db.executeDelete)throw new Error("Database executor does not support executeDelete");this.assertSubqueryDepth();const n=await this.resolveUncorrelatedFilters(this.filters);return this.db.executeDelete(this.tableName,n,t)}}class sr{constructor(t,n,s,i,r="js",o,a,c){U(this,"vfs");U(this,"io");U(this,"driver");U(this,"coreMode");U(this,"wasmCore");U(this,"planner");U(this,"coordinator");U(this,"currentLeaseId",null);U(this,"vmCtx");U(this,"udfs",new Map);U(this,"nextUdfId",1);U(this,"tableMetaCache",new Map);U(this,"tableTailPages",new Map);U(this,"indexTailPages",new Map);U(this,"beforeCommitHooks",new Set);U(this,"commitHooks",new Set);U(this,"subscriptions",new Set);U(this,"activeTxChanges",[]);U(this,"activeTxOrigin","local");U(this,"activeTxMeta");U(this,"activeTxId",0);U(this,"nextAutoTxId",1e6);U(this,"isRunningBeforeCommit",!1);U(this,"broadcastChannel",null);U(this,"instanceId",Math.random().toString(36).slice(2)+Date.now().toString(36));if(this.vfs=t,this.io=n,this.driver=s,this.coordinator=i,this.coreMode=r,this.wasmCore=o,this.planner=a,this.vmCtx=Nr(),this.coordinator.setOnCrossTabInvalidated(async()=>{this.tableMetaCache.clear(),this.tableTailPages.clear(),this.indexTailPages.clear();const l=hn(this.driver.getSlotDataView(0));for(const u of l){let _=u.colCatalogPageId;for(;_!==0;){const f=await this.driver.acquireAndPinPage(_),h=this.driver.getSlotDataView(f);_=he(h,0).nextColCatalogPageId}}}),typeof BroadcastChannel<"u"&&c){const l=`webdb_sync_${t.name}_${c}`;this.broadcastChannel=new BroadcastChannel(l),this.broadcastChannel.onmessage=u=>{const _=u.data;if(!_||_.senderId===this.instanceId)return;const{tables:f,origin:h,meta:g,changeCounter:d,schemaVersion:I}=_;this.coordinator.leaseQueue.enqueue(async()=>{await this.coordinator.syncCrossTabState(!0),this.notifySubscriptions({tables:Array.isArray(f)?f:[],origin:h??"remote",meta:g,changeCounter:typeof d=="number"?d:this.getSyncState().changeCounter,schemaVersion:typeof I=="number"?I:this.getSyncState().schemaVersion,crossTab:!0})}).catch(()=>{})}}}get pool(){return this.driver}static async open(t){const n=t.storage||"memory";let s;t.vfs?s=t.vfs:n==="idb"?s=new Hr(t.name):n==="opfs"?s=new qr(t.name):s=new Wr;const i=t.slotCount??Qe,r=t.maxQueryMemory??ve,o=Do(Math.max(i,Qe),r),a=new Ii({vfs:s,memory:o}),c=new Ro({io:a,memory:o,slotCount:i,maxQueryMemory:r,useDefaultLayoutOffsets:!0}),l=t.name&&s.name!=="memory"?`webdb_lock_${s.name}_${t.name}`:void 0,u=new Qo(s,c,a,l);c.setTransactionCoordinator(u),await u.leaseQueue.enqueue(async()=>{await qi(s);const g=await s.readPage(1);if(!g)yo(c.getSlotDataView(0)),c.markDirty(0),await c.flushSlot(0);else{c.getPageBytesInSlot(0).set(g),c.clearDirty(0),Wn(c.getSlotDataView(0),!0);const d=hn(c.getSlotDataView(0));for(const I of d){let p=I.colCatalogPageId;for(;p!==0;){const y=await c.acquireAndPinPage(p),T=c.getSlotDataView(y);p=he(T,0).nextColCatalogPageId}}}u.recordDiskPage1State()});const _=t.core??"js";let f;_==="wasm"&&(f=Lo(o,t.wasmBinary?new Uint8Array(t.wasmBinary):void 0));const h=new sr(s,a,c,u,_,f,t.planner,t.name);return t.initialData&&await h.importBinary(t.initialData),h}getPlanner(){return this.planner}setPlanner(t){return this.planner=t,this}validateIdentifier(t,n="Identifier"){if(!t||typeof t!="string"||t.length===0)throw new Error(`${n} cannot be empty`);if(t.length>ne)throw new Lr(t,ne)}async createTable(t,n){return this.coordinator.leaseQueue.enqueue(()=>this._createTableInternal(t,n),this.currentLeaseId??void 0)}async _createTableInternal(t,n){var g;if(this.validateIdentifier(t,"Table name"),n.length===0)throw new Error("Table must have at least one column");if(n.length>ue)throw new Ln(n.length,ue);const s=new Set;let i=!1;for(const d of n){if(this.validateIdentifier(d.name,"Column name"),s.has(d.name))throw new ss(d.name,t);s.add(d.name);const I=typeof d.flags=="number"?d.flags:0;(d.primaryKey||(g=d.flags)!=null&&g.primaryKey||I&tt.PRIMARY_KEY)&&(i=!0)}const r=this.pool.getSlotDataView(0);if(xt(r,t)!==-1)throw new is(t);if(ki(r)===-1)throw new gi(ce,ce);const o=Math.ceil(n.length/Te),a=i&&Ns(r)!==-1?1:0,c=1+o+a,l=[];for(let d=0;d<c;d++)l.push(await this.driver.allocateAndPinPage());let u=0;const _={allocateNewPage:()=>{if(u<l.length)return l[u++];const I=r.getUint32(12,!0)+1;return r.setUint32(12,I,!0),this.pool.markDirty(0),I},getPageBytes:d=>{let I=this.pool.getResidentSlot(d);return I===-1&&(I=d<=this.pool.slotCount?d-1:1,this.pool.assignSlot(I,d)),this.pool.getPageBytesInSlot(I)},markPageDirty:d=>{const I=this.pool.getResidentSlot(d);I!==-1&&this.pool.markDirty(I)}};let f;try{f=Bo(r,_,t,n)}catch(d){for(const I of l)this.driver.forceUnpinPage(I),await this.driver.freePage(I,!0);throw d}this.driver.unpinPage(f.rootPageId);for(const d of f.indexes??[])d.rootPageId>1&&this.driver.unpinPage(d.rootPageId);let h=f.colCatalogPageId;for(;h!==0;){const d=await this.driver.acquirePage(h);this.pool.isSlotPinned(d)||this.pool.pinSlot(d),h=he(this.pool.getSlotDataView(d),0).nextColCatalogPageId}return this.coordinator.isInTransaction()||await this.driver.flushAllDirty(),this.tableMetaCache.delete(t.toLowerCase()),f}async getTable(t){return this.coordinator.leaseQueue.enqueue(()=>this._getTableInternal(t),this.currentLeaseId??void 0)}async _getTableInternal(t){const n=t.toLowerCase(),s=this.tableMetaCache.get(n);if(s)return s;const i=this.pool.getSlotDataView(0),r=xt(i,t);if(r===-1)throw new bn(t);let a=Jt(i,r).colCatalogPageId;for(;a!==0;){await this.driver.acquirePage(a);const u=this.pool.getResidentSlot(a);a=he(this.pool.getSlotDataView(u),0).nextColCatalogPageId}const l=Wi(i,{getPageBytes:u=>{const _=this.pool.getResidentSlot(u);return _!==-1?this.pool.getPageBytesInSlot(_):new Uint8Array(4096)}},t);return this.tableMetaCache.set(n,l),l}async listTables(){return this.coordinator.leaseQueue.enqueue(async()=>{const t=this.pool.getSlotDataView(0),n=hn(t),s=[];for(const i of n)s.push(await this._getTableInternal(i.name));return s},this.currentLeaseId??void 0)}async freeTableTreePages(t){if(t<=1)return;const n=[],s=new Set,i=[t];for(;i.length>0;){const r=i.shift();if(r<=1||s.has(r))continue;s.add(r);const o=await this.driver.acquirePage(r),a=this.pool.getSlotDataView(o),c=We(a,0);if(c===Ge){this.driver.forceUnpinPage(r);continue}if(n.push(r),c===fi||c===Ur){const l=ut(a,0);for(let _=0;_<l;_++){const f=ot(a,0,_);if(f>0&&f+4<=4096){const h=a.getUint32(f,!0);h>1&&!s.has(h)&&i.push(h)}}const u=Ut(a,0);u>1&&!s.has(u)&&i.push(u)}else if(c===es||c===ts){const l=Ut(a,0);l>1&&!s.has(l)&&i.push(l)}}for(const r of n)this.driver.forceUnpinPage(r),await this.driver.freePage(r,!0)}async dropTable(t){return this.coordinator.leaseQueue.enqueue(()=>this._dropTableInternal(t),this.currentLeaseId??void 0)}async _dropTableInternal(t){var o;this.tableMetaCache.delete(t.toLowerCase()),this.tableTailPages.delete(t);const n=this.pool.getSlotDataView(0),s=xt(n,t);if(s===-1)throw new bn(t);const i=Jt(n,s);for(let a=0;a<Je;a++){const c=gn(n,a);c&&(c.tableId===i.tableId||c.name.toLowerCase().startsWith(`idx_${t.toLowerCase()}_`)||c.name.toLowerCase()===`pk_${t.toLowerCase()}`)&&(c.rootPageId>1&&(await this.freeTableTreePages(c.rootPageId),this.indexTailPages.delete(c.rootPageId)),Gi(n,a))}i.rootPageId>1&&await this.freeTableTreePages(i.rootPageId);let r=i.colCatalogPageId;for(;r>1;){const a=await this.driver.acquirePage(r),c=this.pool.getSlotDataView(a);if(We(c,0)===Ge){this.driver.forceUnpinPage(r);break}const _=he(c,0).nextColCatalogPageId;this.driver.forceUnpinPage(r),await this.driver.freePage(r,!0),r=_}Uo(n,s),Ze(n),re(n),$t(n),this.pool.markDirty(0),this.coordinator.isInTransaction()||await this.driver.flushAllDirty(),((o=this.vmCtx.table)==null?void 0:o.name.toLowerCase())===t.toLowerCase()&&(this.vmCtx.table=null)}async renameTable(t,n){return this.coordinator.leaseQueue.enqueue(()=>this._renameTableInternal(t,n),this.currentLeaseId??void 0)}async _renameTableInternal(t,n){var l;this.validateIdentifier(n,"Table name");const s=this.pool.getSlotDataView(0),i=xt(s,t);if(i===-1)throw new bn(t);if(t===n)return this._getTableInternal(n);if(xt(s,n)!==-1)throw new is(n);const r=Jt(s,i);r.name=n,An(s,i,r);const o=`pk_${t}`,a=`idx_${t}_`;for(let u=0;u<Je;u++){const _=gn(s,u);if(_&&_.tableId===r.tableId){let f=null;_.name===o?f=`pk_${n}`:_.name.startsWith(a)&&(f=`idx_${n}_${_.name.slice(a.length)}`),f&&f.length<=ne&&!Bs(s,f)&&(_.name=f,Os(s,u,_))}}Ze(s),re(s),$t(s),this.pool.markDirty(0),this.tableMetaCache.delete(t.toLowerCase()),this.tableMetaCache.delete(n.toLowerCase());const c=this.tableTailPages.get(t);return c!==void 0&&(this.tableTailPages.delete(t),this.tableTailPages.set(n,c)),((l=this.vmCtx.table)==null?void 0:l.name.toLowerCase())===t.toLowerCase()&&(this.vmCtx.table=null),this.coordinator.isInTransaction()||await this.driver.flushAllDirty(),this._getTableInternal(n)}async renameColumn(t,n,s){return this.coordinator.leaseQueue.enqueue(()=>this._renameColumnInternal(t,n,s),this.currentLeaseId??void 0)}async _renameColumnInternal(t,n,s){var g;this.validateIdentifier(s,"Column name");const i=await this._getTableInternal(t),r=i.columns.findIndex(d=>d.name===n);if(r===-1)throw new fe(n,t);if(n===s)return i;if(i.columns.some((d,I)=>I!==r&&d.name===s))throw new ss(s,t);const{pageChainIdx:o,colIdxInPage:a}=No(r);let c=i.colCatalogPageId;for(let d=0;d<o;d++){const I=await this.driver.acquirePage(c);c=he(this.pool.getSlotDataView(I),0).nextColCatalogPageId}const l=await this.driver.acquirePage(c),u=this.pool.getSlotDataView(l),_={...i.columns[r],name:s};Mi(u,0,a,_);const f=Me(this.pool.getPageBytesInSlot(l));u.setUint32(12,f,!0),this.pool.markDirty(l);const h=this.pool.getSlotDataView(0);return Ze(h),re(h),$t(h),this.pool.markDirty(0),this.tableMetaCache.delete(t.toLowerCase()),((g=this.vmCtx.table)==null?void 0:g.name.toLowerCase())===t.toLowerCase()&&(this.vmCtx.table=null),this.coordinator.isInTransaction()||await this.driver.flushAllDirty(),this._getTableInternal(t)}async addColumn(t,n,s){this.validateIdentifier(n.name,"Column name");const i=(s==null?void 0:s.defaultValue)!==void 0?s.defaultValue:n.defaultValue!==void 0?n.defaultValue:null;return this._executeTableRebuildAtomic(t,r=>{var _,f,h;if(r.columns.some(g=>g.name===n.name))throw new ss(n.name,t);if(r.columns.length+1>ue)throw new Ln(r.columns.length+1,ue);const o=typeof n.flags=="number"?n.flags:0,a=!!n.primaryKey||!!((_=n.flags)!=null&&_.primaryKey)||(o&tt.PRIMARY_KEY)!==0,c=!!n.autoInc||!!((f=n.flags)!=null&&f.autoInc)||(o&tt.AUTO_INC)!==0,l=!!n.indexed||!!((h=n.flags)!=null&&h.indexed)||(o&tt.INDEXED)!==0;if(a&&r.columns.some(g=>(g.flags&tt.PRIMARY_KEY)!==0))throw new Error(`Cannot add a PRIMARY KEY column "${n.name}" to table "${t}" because it already has a primary key`);return{newColumns:[...r.columns.map(g=>({name:g.name,type:g.type,flags:{primaryKey:(g.flags&tt.PRIMARY_KEY)!==0,notNull:(g.flags&tt.NOT_NULL)!==0,indexed:(g.flags&tt.INDEXED)!==0,autoInc:(g.flags&tt.AUTO_INC)!==0}})),n],transformRow:g=>{const d={...g};return(!c||i!==null)&&(d[n.name]=i),d},keepIndex:()=>!0,newAutoIndexCol:l&&!a?n.name:void 0}})}async dropColumn(t,n){return this.validateIdentifier(n,"Column name"),this._executeTableRebuildAtomic(t,s=>{const i=s.columns.findIndex(a=>a.name===n);if(i===-1)throw new fe(n,t);if(s.columns.length<=1)throw new Ai(`Cannot drop column "${n}" from table "${t}": table must have at least one column`);if(s.columns[i].flags&tt.PRIMARY_KEY)throw new Ai(`Cannot drop PRIMARY KEY column "${n}" from table "${t}"`);return{newColumns:s.columns.filter(a=>a.name!==n).map(a=>({name:a.name,type:a.type,flags:{primaryKey:(a.flags&tt.PRIMARY_KEY)!==0,notNull:(a.flags&tt.NOT_NULL)!==0,indexed:(a.flags&tt.INDEXED)!==0,autoInc:(a.flags&tt.AUTO_INC)!==0}})),transformRow:a=>{const c={...a};return delete c[n],c},keepIndex:a=>!a.includes(n)}})}async alterTable(t,n){switch(n.type){case"renameTable":return this.renameTable(t,n.newName);case"renameColumn":return this.renameColumn(t,n.from,n.to);case"addColumn":return this.addColumn(t,n.column,{defaultValue:n.defaultValue});case"dropColumn":return this.dropColumn(t,n.column);default:throw new Error(`Unsupported alterTable operation: ${n==null?void 0:n.type}`)}}async _executeTableRebuildAtomic(t,n){return this.coordinator.isInTransaction()?this.coordinator.leaseQueue.enqueue(async()=>{const s=await this.coordinator.captureSavepoint();try{return await this._rebuildTableSchemaInternal(t,n)}catch(i){throw this.tableMetaCache.clear(),this.tableTailPages.clear(),this.indexTailPages.clear(),await this.coordinator.restoreSavepoint(s),i}},this.currentLeaseId??void 0):this.transaction(s=>s._rebuildTableSchemaInternal(t,n))}async _rebuildTableSchemaInternal(t,n){const s=await this._getTableInternal(t),{newColumns:i,transformRow:r,keepIndex:o,newAutoIndexCol:a}=n(s),c=[];let l=s.rootPageId;for(;l!==0;){let d=await this.driver.acquirePage(l),I=this.pool.getSlotDataView(d);const p=ut(I,0),y=Ut(I,0);for(let T=0;T<p;T++){d=await this.driver.acquirePage(l),I=this.pool.getSlotDataView(d);const N=ot(I,0,T),b=xe(s.columns,I,N);b&&c.push(r(b))}l=y}const u=s.autoIncNext,_=this.pool.getSlotDataView(0),f=Ae(_,s.tableId),h=[];for(const d of f){if(d.flags&It.PRIMARY)continue;const I=d.columnIndices.slice(0,d.columnCount).map(p=>{var y;return(y=s.columns[p])==null?void 0:y.name}).filter(p=>typeof p=="string");I.length===d.columnCount&&o(I)&&h.push({name:d.name,colNames:I,unique:(d.flags&It.UNIQUE)!==0})}await this._dropTableInternal(t),await this._createTableInternal(t,i);for(const d of h)await this._createIndexInternal(t,d.colNames,{name:d.name,unique:d.unique});a&&!h.some(d=>d.colNames.length===1&&d.colNames[0]===a)&&await this._createIndexInternal(t,a),c.length>0&&await this._insertManyInternal(t,c,!1);const g=xt(_,t);if(g!==-1){const d=Jt(_,g);u>d.autoIncNext&&(d.autoIncNext=u,An(_,g,d),$t(_),this.pool.markDirty(0))}return this.tableMetaCache.delete(t.toLowerCase()),this.coordinator.isInTransaction()||await this.driver.flushAllDirty(),this._getTableInternal(t)}async createIndex(t,n,s){return this.coordinator.leaseQueue.enqueue(()=>this._createIndexInternal(t,n,s),this.currentLeaseId??void 0)}async _createIndexInternal(t,n,s){const i=await this._getTableInternal(t),r=Array.isArray(n)?n:[n];if(r.length===0)throw new Error(`At least one column must be specified for createIndex on table "${t}"`);if(r.length>8)throw new Error(`Maximum 8 columns allowed per index (requested ${r.length})`);const o=[];for(const b of r){const P=i.columns.findIndex(R=>R.name===b);if(P===-1)throw new fe(b,t);o.push(P)}const a=(s==null?void 0:s.name)??`idx_${t}_${r.join("_")}`,c=this.pool.getSlotDataView(0);if(Bs(c,a)!==null)throw new hi(a);const _=Ae(c,i.tableId).find(b=>{if(b.columnCount!==o.length)return!1;for(let P=0;P<b.columnCount;P++)if(b.columnIndices[P]!==o[P])return!1;return!0});if(_)throw new hi(_.name||a);const f=Ns(c);if(f===-1)throw new Rr(Je,Je);const h=await this.driver.allocateAndPinPage(),g=this.pool.getResidentSlot(h),d=this.pool.getSlotDataView(g);ys(d,0,0),this.pool.markDirty(g),this.pool.unpinSlot(g);const I=!!(s!=null&&s.unique);let p=i.rootPageId;for(;p!==0;){let b=await this.driver.acquirePage(p),P=this.pool.getSlotDataView(b);const R=ut(P,0),w=Ut(P,0);for(let S=0;S<R;S++){b=await this.driver.acquirePage(p),P=this.pool.getSlotDataView(b);const v=ot(P,0,S),L=xe(i.columns,P,v);if(L){const A=BigInt(p)<<16n|BigInt(S),{keyVal:B,keyType:k}=this.extractIndexKey(i.columns,{columnCount:o.length,columnIndices:o},L);if(B!=null){if(I&&await this.probeIndexUnique(h,k,B))throw await this.freeTableTreePages(h),this.indexTailPages.delete(h),new tn(`Duplicate key value violates unique constraint "${a}" on table "${t}"`);await this.insertIntoIndex(h,k,B,A)}}}p=w}const y=[0,0,0,0,0,0,0,0],T=[0,0,0,0,0,0,0,0];for(let b=0;b<o.length&&b<8;b++)y[b]=o[b];const N=I?It.UNIQUE:0;Os(c,f,{indexId:f+1,tableId:i.tableId,rootPageId:h,columnCount:o.length,flags:N,columnIndices:y,colDirections:T,name:a}),Ze(c),re(c),$t(c),this.pool.markDirty(0),this.tableMetaCache.delete(t.toLowerCase()),this.indexTailPages.delete(h),this.coordinator.isInTransaction()||await this.driver.flushAllDirty()}async dropIndex(t){return this.coordinator.leaseQueue.enqueue(()=>this._dropIndexInternal(t),this.currentLeaseId??void 0)}async _dropIndexInternal(t){const n=this.pool.getSlotDataView(0),s=Bs(n,t);if(!s)throw new Dr(t);s.desc.rootPageId>1&&(await this.freeTableTreePages(s.desc.rootPageId),this.indexTailPages.delete(s.desc.rootPageId)),Gi(n,s.slotIdx),Ze(n),re(n),$t(n),this.pool.markDirty(0),this.tableMetaCache.clear(),this.indexTailPages.clear(),this.coordinator.isInTransaction()||await this.driver.flushAllDirty()}async listIndexes(t){return this.coordinator.leaseQueue.enqueue(async()=>{const n=this.pool.getSlotDataView(0);if(t){const i=await this._getTableInternal(t);return Ae(n,i.tableId)}const s=[];for(let i=0;i<Je;i++){const r=gn(n,i);r&&s.push(r)}return s},this.currentLeaseId??void 0)}extractIndexKey(t,n,s){if(n.columnCount===1){const i=t[n.columnIndices[0]];return{keyVal:s[i.name],keyType:i.type}}return{keyVal:Cs(t,n.columnIndices,n.columnCount,s),keyType:C.BLOB}}async probeIndexUnique(t,n,s,i){let r=t;for(;r!==0;){const o=await this.driver.acquirePage(r),a=this.pool.getSlotDataView(o);if(ut(a,0)>0){const l=vn(a,0,n,s);if(l.found){const u=ot(a,0,l.slot_idx),_=a.getUint16(u,!0),f=a.getBigInt64(u+2+_,!0);if(!i||!i.has(f))return!0}}r=Ut(a,0)}return!1}async deleteFromIndex(t,n,s,i){let r=t;for(;r!==0;){const o=await this.driver.acquirePage(r),a=this.pool.getSlotDataView(o);if(ut(a,0)>0){const l=vn(a,0,n,s,i);if(l.found)return so(a,0,l.slot_idx),this.pool.markDirty(o),!0}r=Ut(a,0)}return!1}async insertIntoIndex(t,n,s,i){let r=this.indexTailPages.get(t)??t,o=await this.driver.acquirePage(r),a=this.pool.getSlotDataView(o);for(;;){const l=Ut(a,0);if(l===0)break;r=l,o=await this.driver.acquirePage(r),a=this.pool.getSlotDataView(o)}this.indexTailPages.set(t,r);let c=Pi(a,0,n,s,i,this.pool.pageScratchpadOffset);if(c===-1){this.pool.pinSlot(o);try{const l=await this.driver.allocateAndPinPage(),u=this.pool.getResidentSlot(l);try{ds(a,0,l),this.pool.markDirty(o);const _=this.pool.getSlotDataView(u);if(ys(_,0,0),c=Pi(_,0,n,s,i,this.pool.pageScratchpadOffset),c===-1)throw new Error("Unexpected error: index entry does not fit in empty page");this.pool.markDirty(u),this.indexTailPages.set(t,l)}finally{this.pool.unpinSlot(u)}}finally{this.pool.unpinSlot(o)}}else this.pool.markDirty(o)}cloneRow(t){const n={};for(const[s,i]of Object.entries(t))n[s]=i instanceof Uint8Array?i.slice():i;return n}valuesEqual(t,n){if(t===n||t==null&&n==null)return!0;if(t instanceof Uint8Array&&n instanceof Uint8Array){if(t.byteLength!==n.byteLength)return!1;for(let s=0;s<t.byteLength;s++)if(t[s]!==n[s])return!1;return!0}return typeof t=="number"&&typeof n=="bigint"||typeof t=="bigint"&&typeof n=="number"?BigInt(t)===BigInt(n):typeof t=="boolean"&&typeof n=="number"||typeof t=="number"&&typeof n=="boolean"?Number(t)===Number(n):!1}extractPrimaryKey(t,n){const s=t.columns.filter(i=>(i.flags&tt.PRIMARY_KEY)!==0);return s.length===1?n[s[0].name]??null:s.length>1?s.map(i=>n[i.name]??null):t.columns.length===1?n[t.columns[0].name]??null:t.columns.map(i=>n[i.name]??null)}serializePkKey(t){const n=s=>s==null?"null":s instanceof Uint8Array?`b:${Array.from(s).join(",")}`:`${typeof s}:${String(s)}`;return Array.isArray(t)?`[${t.map(n).join("|")}]`:t!==null&&typeof t=="object"&&!(t instanceof Uint8Array)?`{${Object.keys(t).sort().map(i=>`${i}:${n(t[i])}`).join("|")}}`:n(t)}buildChangeset(t,n,s,i){const{changeCounter:r,schemaVersion:o}=this.getSyncState(),a=Array.from(new Set(i.map(c=>c.table)));return{txId:t,origin:n,meta:s,changeCounter:r,schemaVersion:o,tables:a,changes:i,coalesced:()=>{const c=new Map;for(const l of i){const u=`${l.table.toLowerCase()}::${this.serializePkKey(l.pk)}`,_=c.get(u);if(!_){c.set(u,{table:l.table,op:l.op,pk:Array.isArray(l.pk)?[...l.pk]:l.pk,oldRow:l.oldRow?this.cloneRow(l.oldRow):void 0,newRow:l.newRow?this.cloneRow(l.newRow):void 0,changedColumns:l.changedColumns?[...l.changedColumns]:void 0});continue}if(_.op==="insert"&&l.op==="update")c.set(u,{table:l.table,op:"insert",pk:Array.isArray(l.pk)?[...l.pk]:l.pk,newRow:l.newRow?this.cloneRow(l.newRow):_.newRow});else if(_.op==="insert"&&l.op==="delete")c.delete(u);else if(_.op==="update"&&l.op==="update"){const f=_.oldRow,h=l.newRow?this.cloneRow(l.newRow):_.newRow,g=Object.keys(h).filter(d=>!this.valuesEqual(f[d],h[d]));c.set(u,{table:l.table,op:"update",pk:Array.isArray(l.pk)?[...l.pk]:l.pk,oldRow:f,newRow:h,changedColumns:g})}else if(_.op==="update"&&l.op==="delete")c.set(u,{table:l.table,op:"delete",pk:Array.isArray(_.pk)?[..._.pk]:_.pk,oldRow:_.oldRow});else if(_.op==="delete"&&l.op==="insert"){const f=_.oldRow,h=l.newRow?this.cloneRow(l.newRow):{},g=Object.keys(h).filter(d=>!this.valuesEqual(f[d],h[d]));c.set(u,{table:l.table,op:"update",pk:Array.isArray(l.pk)?[...l.pk]:l.pk,oldRow:f,newRow:h,changedColumns:g})}else c.set(u,{table:l.table,op:l.op,pk:Array.isArray(l.pk)?[...l.pk]:l.pk,oldRow:l.oldRow?this.cloneRow(l.oldRow):void 0,newRow:l.newRow?this.cloneRow(l.newRow):void 0,changedColumns:l.changedColumns?[...l.changedColumns]:void 0})}return Array.from(c.values())}}}notifySubscriptions(t){if(t.tables.length===0||this.subscriptions.size===0)return;const n=new Set(t.tables.map(s=>s.toLowerCase()));for(const s of this.subscriptions)if(s.tables==="*")s.callback(t);else for(const i of n)if(s.tables.has(i)){s.callback(t);break}}emitCommitAndSubscriptions(t){if(t.changes.length===0)return;for(const r of this.commitHooks)r(t);const n=t.tables,{changeCounter:s,schemaVersion:i}=t;if(this.notifySubscriptions({tables:n,origin:t.origin,meta:t.meta,changeCounter:s,schemaVersion:i,crossTab:!1,changeset:t}),this.broadcastChannel)try{this.broadcastChannel.postMessage({senderId:this.instanceId,tables:n,origin:t.origin,meta:t.meta,changeCounter:s,schemaVersion:i})}catch{}}onBeforeCommit(t){return this.beforeCommitHooks.add(t),()=>{this.beforeCommitHooks.delete(t)}}onCommit(t){return this.commitHooks.add(t),()=>{this.commitHooks.delete(t)}}subscribe(t,n){const s={tables:t==="*"?"*":new Set((Array.isArray(t)?t:[t]).map(i=>i.toLowerCase())),callback:n};return this.subscriptions.add(s),()=>{this.subscriptions.delete(s)}}getSyncState(){const t=this.pool.getSlotDataView(0),n=Wn(t,!1);return{changeCounter:n.changeCounter,schemaVersion:n.schemaVersion}}validateFilterColumns(t,n){const s=new Set(t.columns.map(o=>o.name)),i=o=>{if(o){if(o.type==="col"&&o.name!=="*"){if(!s.has(o.name))throw new fe(o.name,t.name)}else if(o.type==="binary")i(o.left),i(o.right);else if(o.type==="fn"&&Array.isArray(o.args))for(const a of o.args)i(a)}},r=o=>{if(o.colName&&!s.has(o.colName))throw new fe(o.colName,t.name);if(o.expr&&i(o.expr),o.child&&r(o.child),o.children)for(const a of o.children)r(a)};for(const o of n)r(o)}matchesFilter(t,n,s){switch(s.type){case"and":return(s.children??[]).every(i=>this.matchesFilter(t,n,i));case"or":return(s.children??[]).some(i=>this.matchesFilter(t,n,i));case"not":return s.child?!this.matchesFilter(t,n,s.child):!0;case"null":{const i=s.expr?vt(s.expr,n,o=>{var a;return(a=this.getUdf(o))==null?void 0:a.def.call}):n[s.colName],r=i==null;return s.isNull?r:!r}case"in":{const i=s.expr?vt(s.expr,n,a=>{var c;return(c=this.getUdf(a))==null?void 0:c.def.call}):n[s.colName];if(i==null)return!1;const o=(s.values??[]).some(a=>this.valuesEqual(i,a));return s.notIn?!o:o}case"expr":{if(!s.expr)return!0;const i=vt(s.expr,n,r=>{var o;return(o=this.getUdf(r))==null?void 0:o.def.call});return!!i&&i!==0}case"cmp":{const i=s.expr?vt(s.expr,n,a=>{var c;return(c=this.getUdf(a))==null?void 0:c.def.call}):n[s.colName],r=s.value;if(i==null||r===null||r===void 0)return!1;switch(String(s.op??"=").trim().toLowerCase().replace(/\s+/g," ")){case"=":case"==":return this.valuesEqual(i,r);case"!=":case"<>":return!this.valuesEqual(i,r);case"<":return typeof i=="string"&&typeof r=="string"?i<r:Number(i)<Number(r);case"<=":return typeof i=="string"&&typeof r=="string"?i<=r:Number(i)<=Number(r);case">":return typeof i=="string"&&typeof r=="string"?i>r:Number(i)>Number(r);case">=":return typeof i=="string"&&typeof r=="string"?i>=r:Number(i)>=Number(r);case"like":return Xe(String(i),String(r));case"not like":return!Xe(String(i),String(r));case"contains":return String(i).includes(String(r));case"starts_with":return String(i).startsWith(String(r));case"ends_with":return String(i).endsWith(String(r));default:return this.valuesEqual(i,r)}}default:return!0}}matchesFilters(t,n,s){for(const i of s)if(!this.matchesFilter(t,n,i))return!1;return!0}async deleteCellsOnDataPageAndShiftIndexes(t,n,s,i,r){if(i.length===0)return;const o=new Set(i);if(n.length>0){for(const u of i){const _=r[u];if(!_)continue;const f=BigInt(s)<<16n|BigInt(u);for(const h of n){const{keyVal:g,keyType:d}=this.extractIndexKey(t.columns,h,_.row);g!=null&&await this.deleteFromIndex(h.rootPageId,d,g,f)}}let l=0;for(let u=0;u<r.length;u++)if(!o.has(u)){if(l!==u){const _=r[u].row,f=BigInt(s)<<16n|BigInt(u),h=BigInt(s)<<16n|BigInt(l);for(const g of n){const{keyVal:d,keyType:I}=this.extractIndexKey(t.columns,g,_);d!=null&&(await this.deleteFromIndex(g.rootPageId,I,d,f),await this.insertIntoIndex(g.rootPageId,I,d,h))}}l++}}const a=await this.driver.acquirePage(s),c=this.pool.getSlotDataView(a);for(let l=i.length-1;l>=0;l--)zr(c,0,i[l]);this.pool.markDirty(a)}normalizeWhereOrPkFilters(t,n){if(n!==null&&typeof n=="object"&&!(n instanceof Uint8Array)){const i=[];for(const[r,o]of Object.entries(n))o!==void 0&&(o===null?i.push({type:"null",colName:r,isNull:!0}):i.push({type:"cmp",colName:r,op:"=",value:o}));return i}const s=t.columns.find(i=>(i.flags&tt.PRIMARY_KEY)!==0);if(!s)throw new Error(`Table "${t.name}" does not have a primary key column for scalar lookup`);return[{type:"cmp",colName:s.name,op:"=",value:n}]}async insert(t,n,s){await this.insertMany(t,[n],s)}async insertMany(t,n,s){if(!(!n||n.length===0)){if(!this.coordinator.isInTransaction()&&this.beforeCommitHooks.size>0){await this.transaction(async i=>{await i._insertManyInternal(t,n,!0)},s);return}return this.coordinator.leaseQueue.enqueue(async()=>{const i=this.coordinator.isInTransaction(),r=await this._insertManyInternal(t,n,!0);if(!i&&r.length>0){const o=this.buildChangeset(this.nextAutoTxId++,(s==null?void 0:s.origin)??"local",s==null?void 0:s.meta,r);this.emitCommitAndSubscriptions(o)}},this.currentLeaseId??void 0)}}async _insertManyInternal(t,n,s=!0){if(!n||n.length===0)return[];const i=await this._getTableInternal(t),r=this.pool.getSlotDataView(0),o=Ae(r,i.tableId),a=o.filter(p=>(p.flags&(It.UNIQUE|It.PRIMARY))!==0),c=i.columns.find(p=>(p.flags&tt.AUTO_INC)!==0),l=new Map;for(const p of a)l.set(p.name,new Set);let u=i.autoIncNext;const _=[];for(let p=0;p<n.length;p++){const y=n[p];for(const P of i.columns)if(P.flags&tt.PRIMARY_KEY&&!(P.flags&tt.AUTO_INC)&&(y[P.name]===void 0||y[P.name]===null))throw new ns(P.name,t);let T,N={};for(const P of i.columns)y[P.name]!==void 0?N[P.name]=y[P.name]:N[P.name]=null;c&&(y[c.name]===void 0||y[c.name]===null)&&(T=Number(u),u+=1n,N[c.name]=T);for(const P of a){const{keyVal:R,keyType:w}=this.extractIndexKey(i.columns,P,N);if(R!=null){const S=R instanceof Uint8Array?Array.from(R).join(","):R,v=l.get(P.name);if(v.has(S))throw new tn(`Duplicate key value violates unique constraint "${P.name}" on table "${t}"`);if(v.add(S),await this.probeIndexUnique(P.rootPageId,w,R))throw new tn(`Duplicate key value violates unique constraint "${P.name}" on table "${t}"`)}}const b=Is(i.columns,N);_.push({row:y,effectiveRow:N,rowBytes:b,assignedAutoInc:T})}i.autoIncNext=u;let f=this.tableTailPages.get(t)??i.rootPageId,h=await this.driver.acquirePage(f),g=this.pool.getSlotDataView(h);for(;;){const p=Ut(g,0);if(p===0)break;f=p,h=await this.driver.acquirePage(f),g=this.pool.getSlotDataView(h)}this.tableTailPages.set(t,f);const d=[];for(let p=0;p<_.length;p++){const{row:y,effectiveRow:T,rowBytes:N,assignedAutoInc:b}=_[p];c&&b!==void 0&&(y[c.name]=b),h=await this.driver.acquirePage(f),g=this.pool.getSlotDataView(h);let P=f,R=an(g,0,N,this.pool.pageScratchpadOffset);if(R===-1){const S=h;this.pool.pinSlot(S);try{const v=await this.driver.allocateAndPinPage(),L=this.pool.getResidentSlot(v);try{ds(g,0,v),this.pool.markDirty(S);const A=this.pool.getSlotDataView(L);if(R=an(A,0,N,this.pool.pageScratchpadOffset),R===-1)throw new Error("Unexpected error: row does not fit in empty page");this.pool.markDirty(L),f=v,P=v,h=L,g=A,this.tableTailPages.set(t,v)}finally{this.pool.unpinSlot(L)}}finally{this.pool.unpinSlot(S)}}else this.pool.markDirty(h);const w=BigInt(P)<<16n|BigInt(R);for(const S of o){const{keyVal:v,keyType:L}=this.extractIndexKey(i.columns,S,T);v!=null&&await this.insertIntoIndex(S.rootPageId,L,v,w)}if(s){const S={table:i.name,op:"insert",pk:this.extractPrimaryKey(i,T),newRow:this.cloneRow(T)};d.push(S),this.coordinator.isInTransaction()&&this.activeTxChanges.push(S)}}const I=xt(r,t);if(I!==-1){const p=Jt(r,I);p.rowCountEstimate+=n.length,c&&(p.autoIncNext=i.autoIncNext),An(r,I,p),re(r),$t(r),this.pool.markDirty(0)}return this.coordinator.isInTransaction()||await this.driver.flushAllDirty(),d}async update(t,n,s,i){return!this.coordinator.isInTransaction()&&this.beforeCommitHooks.size>0?this.transaction(r=>r.update(t,n,s,i),i):this.coordinator.leaseQueue.enqueue(async()=>{const r=await this._getTableInternal(t),o=this.normalizeWhereOrPkFilters(r,n),a=this.coordinator.isInTransaction(),{count:c,changes:l}=await this._executeUpdateInternal(t,o,s);if(!a&&l.length>0){const u=this.buildChangeset(this.nextAutoTxId++,(i==null?void 0:i.origin)??"local",i==null?void 0:i.meta,l);this.emitCommitAndSubscriptions(u)}return c},this.currentLeaseId??void 0)}async executeUpdate(t,n,s,i){return!this.coordinator.isInTransaction()&&this.beforeCommitHooks.size>0?this.transaction(r=>r.executeUpdate(t,n,s,i),i):this.coordinator.leaseQueue.enqueue(async()=>{const r=this.coordinator.isInTransaction(),{count:o,changes:a}=await this._executeUpdateInternal(t,n,s);if(!r&&a.length>0){const c=this.buildChangeset(this.nextAutoTxId++,(i==null?void 0:i.origin)??"local",i==null?void 0:i.meta,a);this.emitCommitAndSubscriptions(c)}return o},this.currentLeaseId??void 0)}async _executeUpdateInternal(t,n,s){const i=await this._getTableInternal(t);this.validateFilterColumns(i,n);const r=new Map(i.columns.map(d=>[d.name,d]));for(const d of Object.keys(s))if(!r.has(d))throw new fe(d,t);const o=this.pool.getSlotDataView(0),a=Ae(o,i.tableId),c=a.filter(d=>(d.flags&(It.UNIQUE|It.PRIMARY))!==0),l=[],u=new Set;let _=0,f=i.rootPageId;for(;f!==0;){const d=await this.driver.acquirePage(f),I=this.pool.getSlotDataView(d),p=ut(I,0),y=Ut(I,0),T=[],N=[];for(let b=0;b<p;b++){const P=ot(I,0,b),R=xe(i.columns,I,P);if(T.push({cellIdx:b,row:R}),this.matchesFilters(i,R,n)){const w={...R};for(const[L,A]of Object.entries(s))A!==void 0&&(w[L]=A);for(const L of i.columns)if(L.flags&tt.PRIMARY_KEY&&(w[L.name]===null||w[L.name]===void 0))throw new ns(L.name,t);const S=i.columns.map(L=>L.name).filter(L=>!this.valuesEqual(R[L],w[L])),v=Is(i.columns,w);N.push({cellIdx:b,oldRow:R,newRow:w,changedColumns:S,newRowBytes:v}),u.add(BigInt(f)<<16n|BigInt(b)),_++}}N.length>0&&l.push({pageId:f,allCells:T,matches:N}),f=y}if(_===0)return{count:0,changes:[]};for(const d of c){const I=new Set;for(const p of l)for(const y of p.matches){const{keyVal:T,keyType:N}=this.extractIndexKey(i.columns,d,y.newRow);if(T!=null){const b=T instanceof Uint8Array?Array.from(T).join(","):T;if(I.has(b))throw new tn(`Duplicate key value violates unique constraint "${d.name}" on table "${t}"`);if(I.add(b),await this.probeIndexUnique(d.rootPageId,N,T,u))throw new tn(`Duplicate key value violates unique constraint "${d.name}" on table "${t}"`)}}}const h=[],g=[];for(const d of l){const I=[];for(const p of d.matches){const y=await this.driver.acquirePage(d.pageId),T=this.pool.getSlotDataView(y);if(Ui(T,0,p.cellIdx,p.newRowBytes,this.pool.pageScratchpadOffset)){this.pool.markDirty(y),d.allCells[p.cellIdx].row=p.newRow;const b=BigInt(d.pageId)<<16n|BigInt(p.cellIdx);for(const R of a){const w=this.extractIndexKey(i.columns,R,p.oldRow),S=this.extractIndexKey(i.columns,R,p.newRow);this.valuesEqual(w.keyVal,S.keyVal)||(w.keyVal!==void 0&&w.keyVal!==null&&await this.deleteFromIndex(R.rootPageId,w.keyType,w.keyVal,b),S.keyVal!==void 0&&S.keyVal!==null&&await this.insertIntoIndex(R.rootPageId,S.keyType,S.keyVal,b))}const P={table:i.name,op:"update",pk:this.extractPrimaryKey(i,p.newRow),oldRow:this.cloneRow(p.oldRow),newRow:this.cloneRow(p.newRow),changedColumns:p.changedColumns};h.push(P),this.coordinator.isInTransaction()&&this.activeTxChanges.push(P)}else I.push(p.cellIdx),g.push(p)}I.length>0&&await this.deleteCellsOnDataPageAndShiftIndexes(i,a,d.pageId,I,d.allCells)}if(g.length>0){let d=this.tableTailPages.get(t)??i.rootPageId,I=await this.driver.acquirePage(d),p=this.pool.getSlotDataView(I);for(;;){const y=Ut(p,0);if(y===0)break;d=y,I=await this.driver.acquirePage(d),p=this.pool.getSlotDataView(I)}this.tableTailPages.set(t,d);for(const y of g){I=await this.driver.acquirePage(d),p=this.pool.getSlotDataView(I);let T=d,N=an(p,0,y.newRowBytes,this.pool.pageScratchpadOffset);if(N===-1){const R=I;this.pool.pinSlot(R);try{const w=await this.driver.allocateAndPinPage(),S=this.pool.getResidentSlot(w);try{ds(p,0,w),this.pool.markDirty(R);const v=this.pool.getSlotDataView(S);N=an(v,0,y.newRowBytes,this.pool.pageScratchpadOffset),this.pool.markDirty(S),d=w,T=w,this.tableTailPages.set(t,w)}finally{this.pool.unpinSlot(S)}}finally{this.pool.unpinSlot(R)}}else this.pool.markDirty(I);const b=BigInt(T)<<16n|BigInt(N);for(const R of a){const{keyVal:w,keyType:S}=this.extractIndexKey(i.columns,R,y.newRow);w!=null&&await this.insertIntoIndex(R.rootPageId,S,w,b)}const P={table:i.name,op:"update",pk:this.extractPrimaryKey(i,y.newRow),oldRow:this.cloneRow(y.oldRow),newRow:this.cloneRow(y.newRow),changedColumns:y.changedColumns};h.push(P),this.coordinator.isInTransaction()&&this.activeTxChanges.push(P)}}return re(o),$t(o),this.pool.markDirty(0),this.coordinator.isInTransaction()||await this.driver.flushAllDirty(),{count:_,changes:h}}async delete(t,n,s){return!this.coordinator.isInTransaction()&&this.beforeCommitHooks.size>0?this.transaction(i=>i.delete(t,n,s),s):this.coordinator.leaseQueue.enqueue(async()=>{const i=await this._getTableInternal(t),r=this.normalizeWhereOrPkFilters(i,n),o=this.coordinator.isInTransaction(),{count:a,changes:c}=await this._executeDeleteInternal(t,r);if(!o&&c.length>0){const l=this.buildChangeset(this.nextAutoTxId++,(s==null?void 0:s.origin)??"local",s==null?void 0:s.meta,c);this.emitCommitAndSubscriptions(l)}return a},this.currentLeaseId??void 0)}async executeDelete(t,n,s){return!this.coordinator.isInTransaction()&&this.beforeCommitHooks.size>0?this.transaction(i=>i.executeDelete(t,n,s),s):this.coordinator.leaseQueue.enqueue(async()=>{const i=this.coordinator.isInTransaction(),{count:r,changes:o}=await this._executeDeleteInternal(t,n);if(!i&&o.length>0){const a=this.buildChangeset(this.nextAutoTxId++,(s==null?void 0:s.origin)??"local",s==null?void 0:s.meta,o);this.emitCommitAndSubscriptions(a)}return r},this.currentLeaseId??void 0)}async _executeDeleteInternal(t,n){const s=await this._getTableInternal(t);this.validateFilterColumns(s,n);const i=this.pool.getSlotDataView(0),r=Ae(i,s.tableId),o=[];let a=0,c=s.rootPageId;for(;c!==0;){const u=await this.driver.acquirePage(c),_=this.pool.getSlotDataView(u),f=ut(_,0),h=Ut(_,0);if(f>0){const g=[],d=[];for(let I=0;I<f;I++){const p=ot(_,0,I),y=xe(s.columns,_,p);if(g.push({cellIdx:I,row:y}),this.matchesFilters(s,y,n)){d.push(I);const T={table:s.name,op:"delete",pk:this.extractPrimaryKey(s,y),oldRow:this.cloneRow(y)};o.push(T),this.coordinator.isInTransaction()&&this.activeTxChanges.push(T)}}d.length>0&&(a+=d.length,await this.deleteCellsOnDataPageAndShiftIndexes(s,r,c,d,g))}c=h}if(a===0)return{count:0,changes:[]};const l=xt(i,t);if(l!==-1){const u=Jt(i,l);u.rowCountEstimate=Math.max(0,u.rowCountEstimate-a),An(i,l,u)}return re(i),$t(i),this.pool.markDirty(0),this.coordinator.isInTransaction()||await this.driver.flushAllDirty(),{count:a,changes:o}}async upsert(t,n,s){const i=await this.upsertMany(t,[n],s);return i.inserted>0?"inserted":i.updated>0?"updated":"ignored"}async upsertMany(t,n,s){return!n||n.length===0?{inserted:0,updated:0,ignored:0}:!this.coordinator.isInTransaction()&&(this.beforeCommitHooks.size>0||n.length>1)?this.transaction(i=>i._upsertManyInLease(t,n,s),s):this.coordinator.leaseQueue.enqueue(async()=>{const i=this.coordinator.isInTransaction(),r=[],o=await this._upsertManyInLease(t,n,s,i?void 0:r);if(!i&&r.length>0){const a=this.buildChangeset(this.nextAutoTxId++,(s==null?void 0:s.origin)??"local",s==null?void 0:s.meta,r);this.emitCommitAndSubscriptions(a)}return o},this.currentLeaseId??void 0)}async _upsertManyInLease(t,n,s,i){const r=await this._getTableInternal(t),o=new Set(r.columns.map(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(!o.has(f))throw new fe(f,t)}else if(a=r.columns.filter(f=>(f.flags&tt.PRIMARY_KEY)!==0).map(f=>f.name),a.length===0)throw new Error(`Cannot upsert on table "${t}" without a primary key or explicit conflictTarget`);const c=(s==null?void 0:s.mode)??"merge";let l=0,u=0,_=0;for(const f of n){for(const I of Object.keys(f))if(!o.has(I))throw new fe(I,t);const h=a.every(I=>f[I]!==void 0&&f[I]!==null);let g=null,d=[];if(h&&(d=a.map(I=>({type:"cmp",colName:I,op:"=",value:f[I]})),g=await this.findFirstMatchingRow(r,d)),g){if(c==="ignore"){_++;continue}if(s!=null&&s.where&&!s.where(this.cloneRow(g),this.cloneRow(f))){_++;continue}const I={};if(c==="replace")for(const y of r.columns)f[y.name]!==void 0?I[y.name]=f[y.name]:y.flags&tt.PRIMARY_KEY?I[y.name]=g[y.name]:I[y.name]=null;else for(const[y,T]of Object.entries(f))T!==void 0&&(I[y]=T);const{changes:p}=await this._executeUpdateInternal(t,d,I);i&&i.push(...p),u++}else{const I=await this._insertManyInternal(t,[f],!0);i&&i.push(...I),l++}}return{inserted:l,updated:u,ignored:_}}async findFirstMatchingRow(t,n){let s=t.rootPageId;for(;s!==0;){const i=await this.driver.acquirePage(s),r=this.pool.getSlotDataView(i),o=ut(r,0),a=Ut(r,0);for(let c=0;c<o;c++){const l=ot(r,0,c),u=xe(t.columns,r,l);if(this.matchesFilters(t,u,n))return u}s=a}return null}async transaction(t,n){const s=await this.coordinator.begin(),i=s.leaseId;this.activeTxChanges=[],this.activeTxOrigin=(n==null?void 0:n.origin)??"local",this.activeTxMeta=n==null?void 0:n.meta,this.activeTxId=s.txId;const r=new Proxy(this,{get:(o,a,c)=>{if(a==="currentLeaseId")return i;if(a==="transaction")return async(u,_)=>{const f=await this.coordinator.captureSavepoint(),h=this.activeTxChanges.length;try{return await u(r)}catch(g){throw this.activeTxChanges.length=h,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 _=new Lt(r,u);return o.planner&&_.withPlanner(o.planner),_};const l=Reflect.get(o,a,c);return typeof l=="function"?l.bind(r):l}});try{const o=await t(r);if(this.activeTxChanges.length>0&&this.beforeCommitHooks.size>0&&!this.isRunningBeforeCommit){const _=this.buildChangeset(this.activeTxId,this.activeTxOrigin,this.activeTxMeta,[...this.activeTxChanges]);this.isRunningBeforeCommit=!0;try{for(const f of this.beforeCommitHooks)await f(_,r)}finally{this.isRunningBeforeCommit=!1}}const a=[...this.activeTxChanges],c=this.activeTxOrigin,l=this.activeTxMeta,u=this.activeTxId;if(this.activeTxChanges=[],this.activeTxOrigin="local",this.activeTxMeta=void 0,await this.coordinator.commit(i),a.length>0){const _=this.buildChangeset(u,c,l,a);this.emitCommitAndSubscriptions(_)}return o}catch(o){throw this.activeTxChanges=[],this.activeTxOrigin="local",this.activeTxMeta=void 0,this.isRunningBeforeCommit=!1,this.tableMetaCache.clear(),this.tableTailPages.clear(),this.indexTailPages.clear(),await this.coordinator.rollback(i),o}}registerFunction(t,n){const s=t.toLowerCase(),i=typeof n=="function"?{call:n}:{...n};if(!i.returnType)try{const o=i.call(1,1,1,1,1);typeof o=="number"?i.returnType=Number.isInteger(o)?C.INT32:C.FLOAT64:typeof o=="string"&&(i.returnType=C.TEXT)}catch{try{const o=i.call("","","","","");typeof o=="number"?i.returnType=Number.isInteger(o)?C.INT32:C.FLOAT64:typeof o=="string"&&(i.returnType=C.TEXT)}catch{}}let r=this.udfs.get(s);return r?r.def=i:(r={id:this.nextUdfId++,def:i},this.udfs.set(s,r)),this}getUdf(t){return this.udfs.get(t.toLowerCase())}getUdfMap(){const t=new Map;for(const[n,s]of this.udfs.entries())t.set(n,s.id);return t}getUdfDefs(){const t=new Map;for(const[n,s]of this.udfs.entries())t.set(n,s.def);return t}from(t){return new Lt(this,t)}async explainQuery(t,n,s){return this.coordinator.leaseQueue.enqueue(()=>this._explainQueryInternal(t,n,s),this.currentLeaseId??void 0)}async _explainQueryInternal(t,n,s){var I,p,y;const i=await this._getTableInternal(t),r=[];if(s!=null&&s.joins&&s.joins.length>0){if(1+s.joins.length>16)throw new rs(1+s.joins.length,16);for(let T=0;T<s.joins.length;T++){const N=s.joins[T],b=await this._getTableInternal(N.table);r.push({type:N.type,table:b,cursor:T+1,leftCol:N.leftCol,op:N.op,rightCol:N.rightCol})}}const o=er({table:i,joinedTables:r.length>0?r:void 0,filters:n,orderBy:s==null?void 0:s.orderBy,groupBy:s==null?void 0:s.groupBy,aggregates:s==null?void 0:s.aggregates,having:s==null?void 0:s.having,selectExprs:s==null?void 0:s.selectExprs,udfNameMap:this.getUdfMap(),udfDefs:this.getUdfDefs(),limit:s==null?void 0:s.limit,offset:s==null?void 0:s.offset,planner:(s==null?void 0:s.planner)??this.planner}),c=(o.allTables??(r.length>0?[i,...r.map(T=>T.table)]:[i]))[0],l=Ko(o,c),u=Jo(l),_=o.indexScan??o.table0Scan,f=_?"IndexScan":"TableScan",h=_?_.index.name:void 0,g=o.joinedTableScans,d=(I=s==null?void 0:s.joins)==null?void 0:I.map(T=>{const N=g==null?void 0:g.find(b=>b.tableName.toLowerCase()===T.table.toLowerCase());return N&&N.scanType==="IndexScan"?{...T,scanType:N.scanType,indexName:N.indexName}:T});return{plan:{table:c.name,rootPageId:c.rootPageId,scanType:f,indexName:h,filters:n,orderBy:s==null?void 0:s.orderBy,groupBy:s==null?void 0:s.groupBy,aggregates:s==null?void 0:s.aggregates,having:s==null?void 0:s.having,select:s==null?void 0:s.select,joins:d,limit:s==null?void 0:s.limit,offset:s==null?void 0:s.offset,estimatedCost:o.estimatedCost,estimatedRows:o.estimatedRows,joinOrder:o.joinOrder,isOrderSatisfied:o.isOrderSatisfied??((p=o.planMetrics)==null?void 0:p.isOrderSatisfied)??!1,sortCostAvoided:((y=o.planMetrics)==null?void 0:y.sortCostAvoided)??void 0},bytecodeSize:o.byteLength,instructions:l,assembly:u}}async executeQuery(t,n,s){return this.coordinator.leaseQueue.enqueue(()=>this._executeQueryInternal(t,n,s),this.currentLeaseId??void 0)}async _executeQueryInternal(t,n,s){var d;const i=await this._getTableInternal(t),r=[],o=[];if(s.joins&&s.joins.length>0){if(1+s.joins.length>16)throw new rs(1+s.joins.length,16);for(let I=0;I<s.joins.length;I++){const p=s.joins[I],y=await this._getTableInternal(p.table);r.push(y),o.push({type:p.type,table:y,cursor:I+1,leftCol:p.leftCol,op:p.op,rightCol:p.rightCol})}}for(const I of[i,...r]){let p=I.rootPageId;for(;p!==0;){const y=await this.driver.acquirePage(p),T=this.pool.getSlotDataView(y);p=Ut(T,0)}for(const y of I.indexes??[]){let T=y.rootPageId;for(;T!==0;){const N=await this.driver.acquirePage(T),b=this.pool.getSlotDataView(N);T=Ut(b,0)}}}let a=s.orderBy;!a&&s.sortCol&&(a=[{colName:s.sortCol,direction:s.sortDir}]);const c={table:i,joinedTables:o.length>0?o:void 0,filters:n,orderBy:a,groupBy:s.groupBy,aggregates:s.aggregates,having:s.having,selectExprs:s.selectExprs,udfNameMap:this.getUdfMap(),udfDefs:this.getUdfDefs(),limit:s.limit!==null?s.limit:void 0,offset:s.offset!==null?s.offset:void 0,planner:s.planner??this.planner},l=er(c),u=l.allTables??[i,...r];Br(this.vmCtx,u[0],u),l.inSets&&(this.vmCtx.inSets=l.inSets);const _=l.keyInfos??c.keyInfos;_&&(this.vmCtx.keyInfos=_);const f={};for(const I of this.udfs.values())f[I.id]=I.def.call;this.vmCtx.udfs=f;let h=l.outputColumns??c.outputColumns??i.columns;if(c.aggregates&&c.aggregates.length>0||c.groupBy&&c.groupBy.length>0)if(l.outputColumns)h=l.outputColumns;else{h=[];const I=c.groupBy??[];for(const p of I){const y=typeof p=="string"?p:p.colName??(p.expr?Qt(p.expr):"group_key"),T=i.columns.find(N=>N.name===y);T?h.push(T):h.push({name:y,type:C.TEXT,flags:tt.NONE,colOffset:0})}for(let p=0;p<(((d=c.aggregates)==null?void 0:d.length)??0);p++){const y=c.aggregates[p],T=y.alias??(y.colName?`${y.func}_${y.colName}`:y.func),N=y.func==="count"?C.INT32:C.FLOAT64;h.push({name:T,type:N,flags:tt.NONE,colOffset:0})}}this.vmCtx.outputColumns=h;const g=[];for(;;){const I=Mn(this.vmCtx,this.pool.view,l);let p=0;for(let y=0;y<this.vmCtx.resultCount;y++){const T=this.pool.view.getUint16(On+p,!0),N=On+p+2,b=xe(h,this.pool.view,N);g.push(b),p+=2+T}if(I===O.DONE)break;if(I===O.BUFFER_FULL)this.vmCtx.resultOffset=0,this.vmCtx.resultCount=0,this.vmCtx.status=O.RUNNING;else if(I===O.PAGE_FAULT){this.vmCtx.resultOffset=0,this.vmCtx.resultCount=0;const y=[],T=this.vmCtx.cursors??[this.vmCtx.cursor];for(const N of T)if(N&&N.pageId>1){const b=this.pool.getResidentSlot(N.pageId);b>0&&(this.pool.pinSlot(b),y.push(b))}try{await this.driver.acquirePage(this.vmCtx.fault_page_id)}finally{for(const N of y)this.pool.unpinSlot(N)}this.vmCtx.status=O.RUNNING}else throw I===O.ARENA_EXHAUSTED?(this.vmCtx.arenaOffset=0,new _i):I===O.TIMEOUT?new vr:I===O.INVALID_BYTECODE?new kr:new Error(`VM execution error: status=${I}`)}return Object.defineProperty(g,"isOrderSatisfied",{value:l.isOrderSatisfied??!1,writable:!0,enumerable:!1,configurable:!0}),g}async checkpoint(){return this.coordinator.checkpoint()}async exportBinary(){return this.coordinator.leaseQueue.enqueue(async()=>{this.coordinator.isInTransaction()||(await this.coordinator.executeCheckpoint(),await this.driver.flushAllDirty());const t=this.pool.getSlotDataView(0),n=To(t),s=new Uint8Array(n*4096);s.set(this.pool.getPageBytesInSlot(0),0);const i=new DataView(s.buffer,s.byteOffset,4096);$t(i,0);for(let r=2;r<=n;r++){const o=(r-1)*4096,a=s.subarray(o,o+4096),c=this.pool.getResidentSlot(r);if(c!==-1)a.set(this.pool.getPageBytesInSlot(c));else if(this.coordinator.hasSpilledPage(r))a.set(this.coordinator.getSpilledPage(r));else{const u=await this.vfs.readPage(r);u&&a.set(u)}const l=Me(a);new DataView(a.buffer,a.byteOffset,4096).setUint32(12,l,!0)}return s},this.currentLeaseId??void 0)}async importBinary(t){if(this.coordinator.isInTransaction())throw new Error("Cannot import binary database while a transaction is active");return this.coordinator.leaseQueue.enqueue(async()=>{const n=t instanceof Uint8Array?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):new Uint8Array(t);if(n.byteLength<4096||n.byteLength%4096!==0)throw new Dn(`Invalid database binary size (${n.byteLength} bytes): must be a non-zero multiple of 4096 bytes`);const s=n.byteLength/4096,i=n.subarray(0,4096),r=new DataView(i.buffer,i.byteOffset,4096),o=Wn(r,!0);if(o.pageSize!==4096)throw new Dn(`Invalid database page size ${o.pageSize} (expected 4096)`);if(o.totalPages!==s)throw new Dn(`Database page count mismatch: header specifies ${o.totalPages} pages, but binary image contains ${s} pages`);for(let l=2;l<=s;l++){const u=(l-1)*4096,_=n.subarray(u,u+4096),h=new DataView(_.buffer,_.byteOffset,4096).getUint32(12,!0);if(h!==0){const g=Me(_);if(g!==h)throw new Se(l,h,g)}}const a=[];for(let l=1;l<=s;l++){const u=(l-1)*4096;a.push({pageId:l,data:n.subarray(u,u+4096).slice()})}for(let l=1;l<this.pool.slotCount;l++)this.pool.forceUnpinSlot(l),this.pool.unassignSlot(l),this.pool.clearDirty(l),this.pool.getPageBytesInSlot(l).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 c=hn(this.pool.getSlotDataView(0));for(const l of c){let u=l.colCatalogPageId;for(;u!==0;){const _=await this.driver.acquireAndPinPage(u),f=this.pool.getSlotDataView(_);u=he(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()}}E.ALIGNMENT_PADDING_OFFSET=rl,E.ALIGNMENT_PADDING_SIZE=dr,E.AggregateNotAllowedInWhereError=os,E.BUILTIN_AGGREGATES=vo,E.BUILTIN_SCALARS=ko,E.BYTECODE_OFFSET=Ir,E.BYTECODE_SIZE=gr,E.BufferPoolDriver=Ro,E.BytecodeEmitter=Qs,E.CATALOG_PAGE_HEADER_FIELDS=Ha,E.CATALOG_PAGE_HEADER_OFFSET_COL_COUNT_IN_PAGE=$a,E.CATALOG_PAGE_HEADER_OFFSET_FLAGS=Va,E.CATALOG_PAGE_HEADER_OFFSET_NEXT_COL_CATALOG_PAGE_ID=Ya,E.CATALOG_PAGE_HEADER_OFFSET_PAGE_CHECKSUM=Za,E.CATALOG_PAGE_HEADER_OFFSET_PAGE_TYPE=qa,E.CATALOG_PAGE_HEADER_OFFSET_START_COL_INDEX=Xa,E.CATALOG_PAGE_HEADER_OFFSET_TABLE_ID=xa,E.CATALOG_PAGE_HEADER_SIZE=xs,E.COLUMN_META_FIELDS=ja,E.COLUMN_META_OFFSET_COL_OFFSET=za,E.COLUMN_META_OFFSET_FLAGS=Ja,E.COLUMN_META_OFFSET_NAME=tl,E.COLUMN_META_OFFSET_RESERVED=el,E.COLUMN_META_OFFSET_TYPE=Ka,E.COLUMN_META_SIZE=Xs,E.COST_INDEX_NEXT=Ls,E.COST_INDEX_SEEK=_n,E.COST_ROW_EVAL=_e,E.CURRENT_ENGINE_VERSION=zn,E.CURRENT_MIN_READ_VERSION=Sr,E.CannotDropColumnError=Ai,E.ColumnAlreadyExistsError=ss,E.ColumnFlag=tt,E.ColumnNotFoundError=fe,E.CorruptPageError=Se,E.CorruptWalFrameError=Rn,E.CorruptWalHeaderError=as,E.CostBasedPlanner=Fs,E.CostBasedQueryPlanner=fc,E.CustomOrderPlanner=lc,E.CustomPlanner=xo,E.CustomQueryPlanner=cc,E.DEFAULT_BUFFER_POOL_REGIONS=il,E.DEFAULT_CACHE_SIZE_BYTES=nl,E.DEFAULT_MAX_QUERY_MEMORY=ve,E.DEFAULT_PAGE_SLOTS=sl,E.DEFAULT_PAGE_TO_SLOT_BUCKETS=Wt,E.DEFAULT_SLOT_COUNT=Qe,E.DIRTY_MASK_OFFSET=mr,E.DataType=C,E.DefaultQueryPlanner=uc,E.ExclusiveLeaseQueue=Fo,E.ExpressionBuilder=it,E.FILE_HEADER_SIZE=ga,E.HEADER_OFFSET_CHANGE_COUNTER=pe,E.HEADER_OFFSET_FILE_FORMAT_VERSION=Vs,E.HEADER_OFFSET_FREE_PAGE_HEAD=le,E.HEADER_OFFSET_MAGIC=Ee,E.HEADER_OFFSET_MIN_READ_VERSION=$s,E.HEADER_OFFSET_NEXT_CATALOG_PAGE_ID=ur,E.HEADER_OFFSET_NEXT_INDEX_CATALOG_PAGE_ID=fr,E.HEADER_OFFSET_PAGE_CHECKSUM=ye,E.HEADER_OFFSET_PAGE_SIZE=qs,E.HEADER_OFFSET_RESERVED=_a,E.HEADER_OFFSET_SCHEMA_VERSION=Ie,E.HEADER_OFFSET_TOTAL_PAGES=se,E.HeuristicPlanner=Vo,E.HeuristicQueryPlanner=Ac,E.INDEX_CATALOG_OFFSET=Un,E.INDEX_DESCRIPTOR_FIELDS=La,E.INDEX_DESCRIPTOR_OFFSET_COLUMN_COUNT=Qa,E.INDEX_DESCRIPTOR_OFFSET_COLUMN_INDICES=ka,E.INDEX_DESCRIPTOR_OFFSET_COL_DIRECTIONS=Ga,E.INDEX_DESCRIPTOR_OFFSET_FLAGS=va,E.INDEX_DESCRIPTOR_OFFSET_INDEX_ID=Da,E.INDEX_DESCRIPTOR_OFFSET_NAME=Ma,E.INDEX_DESCRIPTOR_OFFSET_RESERVED=Wa,E.INDEX_DESCRIPTOR_OFFSET_ROOT_PAGE_ID=Fa,E.INDEX_DESCRIPTOR_OFFSET_TABLE_ID=Ra,E.INDEX_DESCRIPTOR_SIZE=Fe,E.IdentifierTooLongError=Lr,E.IndexAlreadyExistsError=hi,E.IndexFlag=It,E.IndexNotFoundError=Dr,E.IndexedDbVfsAdapter=Hr,E.InvalidBytecodeError=kr,E.InvalidDatabaseError=Dn,E.Io=Ii,E.MASTER_TABLE_OFFSET=Sn,E.MAX_COLUMNS_PER_CATALOG_PAGE=Te,E.MAX_COLUMNS_PER_TABLE=ue,E.MAX_CURSORS_PER_FRAME=Al,E.MAX_INDEXES_PAGE1=Je,E.MAX_INDEXES_SYSPAGE=ma,E.MAX_IN_LIST_SIZE=Ft,E.MAX_NAME_LENGTH=ne,E.MAX_REGISTERS_PER_FRAME=fl,E.MAX_ROW_SIZE=2048,E.MAX_SUBQUERY_DEPTH=hl,E.MAX_TABLES_PAGE1=ce,E.MAX_TABLES_SYSPAGE=da,E.MAX_TABLE_INTERIOR_CELLS=lr,E.MAX_TOPK_HEAP_LIMIT=Or,E.MemoryVfsAdapter=Wr,E.NEXT_DESCRIPTOR_CATALOG_PAGE_OFFSET=Ea,E.NEXT_DESCRIPTOR_CATALOG_PAGE_SIZE=Ia,E.NoOpPlanner=$o,E.NoOpQueryPlanner=hc,E.NotNullConstraintError=ns,E.OpCode=m,E.OpfsVfsAdapter=qr,E.PAGE_HEADER_OFFSET_CELL_COUNT=aa,E.PAGE_HEADER_OFFSET_CHECKSUM=De,E.PAGE_HEADER_OFFSET_CONTENT_OFFSET=la,E.PAGE_HEADER_OFFSET_FLAGS=oa,E.PAGE_HEADER_OFFSET_FREE_BYTES=ca,E.PAGE_HEADER_OFFSET_NEXT_PAGE_ID=or,E.PAGE_HEADER_OFFSET_TYPE=rr,E.PAGE_HEADER_SIZE=Kt,E.PAGE_SCRATCHPAD_OFFSET=pr,E.PAGE_SCRATCHPAD_SIZE=_r,E.PAGE_SIZE=4096,E.PAGE_TO_SLOT_BUCKET_SIZE=Ce,E.PAGE_TO_SLOT_OFFSET=Gt,E.PAGE_TO_SLOT_SIZE=Ar,E.PAGE_TYPE_CATALOG_PAGE=Nn,E.PAGE_TYPE_FREE=Ge,E.PAGE_TYPE_INDEX_INTERIOR=Ur,E.PAGE_TYPE_INDEX_LEAF=ts,E.PAGE_TYPE_LEAF_DATA=es,E.PAGE_TYPE_TABLE_INTERIOR=fi,E.QueryArenaExhaustedError=_i,E.QueryBuilder=Lt,E.QueryTimeoutError=vr,E.RESULT_BUFFER_OFFSET=On,E.RESULT_BUFFER_SIZE=Ys,E.RowSizeLimitExceededError=br,E.SLOTTED_PAGE_HEADER_FIELDS=ra,E.SLOT_TO_PAGE_OFFSET=Yn,E.SYSPAGE_FILE_HEADER_FIELDS=ha,E.SYSPAGE_RESERVED_OFFSET=pa,E.SYSPAGE_RESERVED_SIZE=ya,E.SubqueryNestingTooDeepError=Qr,E.TABLE_DESCRIPTOR_FIELDS=Ta,E.TABLE_DESCRIPTOR_OFFSET_AUTO_INC_NEXT=Ba,E.TABLE_DESCRIPTOR_OFFSET_COLUMN_COUNT=wa,E.TABLE_DESCRIPTOR_OFFSET_COL_CATALOG_PAGE_ID=Ua,E.TABLE_DESCRIPTOR_OFFSET_FLAGS=Pa,E.TABLE_DESCRIPTOR_OFFSET_NAME=Oa,E.TABLE_DESCRIPTOR_OFFSET_RESERVED=ba,E.TABLE_DESCRIPTOR_OFFSET_ROOT_PAGE_ID=Sa,E.TABLE_DESCRIPTOR_OFFSET_ROW_COUNT_ESTIMATE=Na,E.TABLE_DESCRIPTOR_OFFSET_TABLE_ID=Ca,E.TABLE_DESCRIPTOR_SIZE=Re,E.TABLE_INTERIOR_CELL_FIELDS=ua,E.TABLE_INTERIOR_CELL_OFFSET_CHILD_PAGE_ID=fa,E.TABLE_INTERIOR_CELL_OFFSET_ROWID=Aa,E.TABLE_INTERIOR_CELL_SIZE=ar,E.TABLE_INTERIOR_SPLIT_INDEX=cr,E.TOTAL_MEMORY_BYTES=ol,E.TRANSIENT_ARENA_OFFSET=yr,E.TableAlreadyExistsError=is,E.TableFlag=Bn,E.TableNotFoundError=bn,E.TooManyColumnsError=Ln,E.TooManyCursorsError=rs,E.TooManyGroupByColumnsError=Mr,E.TooManyIndexesError=Rr,E.TooManyOrderByColumnsError=Gr,E.TooManyRegistersError=st,E.TooManyTablesError=gi,E.TransactionCoordinator=Qo,E.UniqueConstraintViolationError=tn,E.UnknownFunctionError=di,E.UnsupportedFormatVersionError=Fr,E.VM_CONTEXT_OFFSET=Er,E.VM_CONTEXT_SIZE=hr,E.VM_FRAME_COUNT=ul,E.VM_FRAME_SIZE=cl,E.VmStatus=O,E.WAL_CURRENT_VERSION=Tr,E.WAL_FILE_HEADER_FIELDS=al,E.WAL_FILE_HEADER_SIZE=Jn,E.WAL_FRAME_HEADER_FIELDS=ll,E.WAL_FRAME_HEADER_SIZE=ke,E.WAL_FRAME_MAGIC=Pn,E.WAL_FRAME_OFFSET_CHECKSUM=ui,E.WAL_FRAME_OFFSET_DB_SIZE_PAGES=li,E.WAL_FRAME_OFFSET_FLAGS=ri,E.WAL_FRAME_OFFSET_FRAME_SEQ=ci,E.WAL_FRAME_OFFSET_FRAME_TYPE=ii,E.WAL_FRAME_OFFSET_MAGIC=si,E.WAL_FRAME_OFFSET_PAGE_ID=ai,E.WAL_FRAME_OFFSET_RESERVED=wr,E.WAL_FRAME_OFFSET_TX_ID=oi,E.WAL_FRAME_SIZE=ze,E.WAL_FRAME_TYPE_PAGE_DATA=Zn,E.WAL_FRAME_TYPE_TX_COMMIT=jn,E.WAL_FRAME_TYPE_TX_UNCOMMITTED=Kn,E.WAL_HEADER_OFFSET_CHECKPOINT_SEQ=zs,E.WAL_HEADER_OFFSET_CHECKSUM=ni,E.WAL_HEADER_OFFSET_MAGIC=js,E.WAL_HEADER_OFFSET_PAGE_SIZE=Js,E.WAL_HEADER_OFFSET_RESERVED=Cr,E.WAL_HEADER_OFFSET_SALT1=ti,E.WAL_HEADER_OFFSET_SALT2=ei,E.WAL_HEADER_OFFSET_WAL_VERSION=Ks,E.WAL_HEADER_SIZE=gl,E.WAL_MAGIC_BYTES=pi,E.WAL_PAGE_SIZE=we,E.WEBDB_CORE_WASM_BASE64=Hi,E.WebDB=sr,E.buf_pool_assign_slot=ao,E.buf_pool_clear_dirty=uo,E.buf_pool_find_victim=Ri,E.buf_pool_get_resident_slot=Ht,E.buf_pool_get_slot_offset=kl,E.buf_pool_is_dirty=bi,E.buf_pool_is_pinned=cn,E.buf_pool_mark_dirty=co,E.buf_pool_pin_slot=Li,E.buf_pool_read_slot_to_page=ln,E.buf_pool_select_eviction_victim=Fi,E.buf_pool_unassign_slot=lo,E.buf_pool_unpin_slot=Di,E.buf_pool_write_slot_to_page=Bi,E.buildJoinEdges=Ds,E.buildRootFilter=zt,E.c_assert=Yr,E.canJoinPreserveOrder=jo,E.catalog_create_table=Bo,E.catalog_delete_index_descriptor=Gi,E.catalog_delete_table_descriptor=Uo,E.catalog_find_free_index_slot=Ns,E.catalog_find_free_table_slot=ki,E.catalog_find_index_by_name=Bs,E.catalog_find_table_by_name=Zl,E.catalog_find_table_slot=xt,E.catalog_get_change_counter=wo,E.catalog_get_free_page_head=Xl,E.catalog_get_schema_version=Co,E.catalog_get_total_pages=To,E.catalog_increment_change_counter=re,E.catalog_increment_schema_version=Ze,E.catalog_init_page=Oo,E.catalog_init_page1=yo,E.catalog_list_table_descriptors=hn,E.catalog_list_table_indexes=Ae,E.catalog_load_all_tables=Kl,E.catalog_load_table_meta=Wi,E.catalog_map_column_location=No,E.catalog_parse_data_type=So,E.catalog_read_column_meta=Po,E.catalog_read_fixed_string=Us,E.catalog_read_index_descriptor=gn,E.catalog_read_page1_header=Wn,E.catalog_read_page_header=he,E.catalog_read_table_descriptor=Jt,E.catalog_set_free_page_head=Yl,E.catalog_set_total_pages=xl,E.catalog_update_page1_checksum=$t,E.catalog_write_column_meta=Mi,E.catalog_write_fixed_string=Ss,E.catalog_write_index_descriptor=Os,E.catalog_write_page_header=jl,E.catalog_write_table_descriptor=An,E.chooseIndexScan=ks,E.chooseJoinIndex=Gs,E.clear_bit=Xr,E.col=Vi,E.collectLeafFilters=Xo,E.compare_sorter_keys=fn,E.compileQuery=er,E.computeBufferPoolOffsets=Zs,E.computePage1Checksum=Ei,E.computePageChecksum=Me,E.computeWalFrameChecksum=ls,E.crc32=mi,E.createVmContext=Nr,E.createVmCursor=Pr,E.createWasmCore=Lo,E.createWasmMemory=Do,E.decodeWalFileHeader=hs,E.decodeWalFrame=Sl,E.decodeWalFrameHeader=yi,E.deriveDefaultAlias=Qt,E.disassembleBytecode=Ko,E.doesTableSatisfyJoinOrderKeys=xi,E.emitExpression=Z,E.encodeWalFileHeader=As,E.encodeWalFrame=gs,E.estimateFilterSelectivity=$i,E.estimateWhereCost=Xi,E.evalExprNode=vt,E.exp=Mo,E.extractAggregatesFromExpr=nr,E.extractFilterColumnNames=Ho,E.findIndexOnColumn=qn,E.fn=ic,E.fnv1a_32=ws,E.formatDisassembly=Jo,E.getCmpOpcode=$n,E.getFilterReferencedTables=dn,E.getMinKeyValueForType=vs,E.getSingleTableBaseCost=de,E.getTopLevelConjunctionFilters=mn,E.getWebDbCoreWasmBytes=bo,E.get_bit=$r,E.inferExprType=Zo,E.inferTransitivePredicates=qo,E.isAggregateFunction=ge,E.isBuiltinFunction=Jl,E.isBuiltinScalarFunction=Go,E.isIndexAlignedWithOrderBy=tr,E.isQueryBuilder=x,E.materializeOutputSelectExprs=Vn,E.memcmp=_l,E.memcpy=nn,E.memset=ie,E.normalizeFilter=Oe,E.normalizeSelectItem=Ms,E.optimizeQueryPlan=_c,E.optimizeWherePredicates=Yi,E.page_binary_search_index_leaf=vn,E.page_binary_search_interior=Fl,E.page_compact=Qn,E.page_compare_index_keys=Ts,E.page_delete_index_leaf_cell=so,E.page_delete_row=zr,E.page_deserialize_row=xe,E.page_get_cell_content_offset=qe,E.page_get_cell_count=ut,E.page_get_cell_offset=ot,E.page_get_checksum=Ll,E.page_get_contiguous_free_space=ms,E.page_get_free_bytes=Ue,E.page_get_next_page_id=Ut,E.page_get_right_child_page_id=ps,E.page_get_row_length=Es,E.page_get_table_layout=Rl,E.page_get_total_free_space=Jr,E.page_get_type=We,E.page_init=Fn,E.page_init_free=Kr,E.page_init_index_leaf=ys,E.page_init_interior=to,E.page_insert_index_leaf_cell=Pi,E.page_insert_interior_cell=no,E.page_insert_row=an,E.page_serialize_row=Is,E.page_set_cell_content_offset=Ve,E.page_set_cell_count=He,E.page_set_cell_offset=on,E.page_set_checksum=Dl,E.page_set_free_bytes=$e,E.page_set_next_page_id=ds,E.page_set_right_child_page_id=eo,E.page_set_type=bl,E.page_split_interior=Ql,E.page_table_delete=Ni,E.page_table_get=ro,E.page_table_hash=kn,E.page_table_set=oo,E.page_update_row=Ui,E.parseExpression=ft,E.parseFilterTarget=wt,E.parseSelectExpr=bs,E.read_f64=Il,E.read_i32=ml,E.read_i64=Cl,E.read_u16=us,E.read_u32=yt,E.read_u64=yl,E.read_u8=Vr,E.reconstructJoinPlans=Rs,E.recoverFromWal=qi,E.resetVmContext=Br,E.resolveColumnAcrossTables=ht,E.resolveQueryPlanner=ji,E.serialize_composite_key=Cs,E.serialize_single_key=io,E.set_bit=xr,E.sql=nc,E.sql_like_match=Xe,E.strlen=cs,E.validateClause=je,E.validateWalFrame=Ti,E.vm_step=Mn,E.write_f64=pl,E.write_i32=El,E.write_i64=wl,E.write_u16=fs,E.write_u32=Tt,E.write_u64=Tl,E.write_u8=dl,Object.defineProperty(E,Symbol.toStringTag,{value:"Module"})});
4
+ `;return s}const ts=new Set;function js(e,t){if(ts.size===0||!e)return;const n=Array.isArray(t)?t:[t];for(const s of ts)s.record(e,n)}function ha(e,t={}){let n={data:t.initialData,isLoading:!0,error:null,lastUpdated:null,lastEvent:null};const s=new Set;let i=[],r="",o=0,a=!1,c=!1,l=null,u;const d=()=>{if(!a)for(const p of s)try{p(n)}catch{}},h=()=>{for(const p of i)try{p()}catch{}i=[],r=""},f=p=>{if(!a){if(u=p,t.debounceMs&&t.debounceMs>0){l!==null&&clearTimeout(l),l=setTimeout(()=>{l=null;const y=u;u=void 0,_(y)},t.debounceMs);return}c||(c=!0,queueMicrotask(()=>{if(c=!1,a)return;const y=u;u=void 0,_(y)}))}},g=p=>{if(a)return;if(t.db&&typeof t.db.subscribe=="function"){if(p.has(t.db)||p.set(t.db,new Set),t.tables){const w=p.get(t.db);if(t.tables==="*")w.add("*");else{const C=Array.isArray(t.tables)?t.tables:[t.tables];for(const B of C)w.add(B.toLowerCase())}}}else if(t.tables&&p.size>0)for(const[,w]of p)if(t.tables==="*")w.add("*");else{const C=Array.isArray(t.tables)?t.tables:[t.tables];for(const B of C)w.add(B.toLowerCase())}const y=[];let T=0;for(const[,w]of p){const C=w.has("*")?["*"]:Array.from(w).sort();y.push(`${T++}:${C.join(",")}`)}const O=y.join("|");if(!(O===r&&i.length>0)){h(),r=O;for(const[w,C]of p){if(!w||typeof w.subscribe!="function")continue;const B=C.has("*")||C.size===0?"*":Array.from(C),P=w.subscribe(B,U=>{f(U)});i.push(P)}}},_=async p=>{if(a)return n.data;const y=++o,T=new Map,O={record(w,C){if(!w||typeof w.subscribe!="function")return;let B=T.get(w);B||(B=new Set,T.set(w,B));for(const P of C)P&&P!=="__subquery__"&&B.add(P.toLowerCase())}};ts.add(O);try{const w=e();let C;if(x(w)){const B=w;O.record(B.getDb(),B.getReferencedTables()),C=await B.toArray()}else{const B=await w;if(x(B)){const P=B;O.record(P.getDb(),P.getReferencedTables()),C=await P.toArray()}else C=B}return ts.delete(O),a||y!==o?n.data:(g(T),n={data:C,isLoading:!1,error:null,lastUpdated:Date.now(),lastEvent:p??n.lastEvent},d(),C)}catch(w){if(ts.delete(O),a||y!==o)return n.data;(T.size>0||t.db)&&g(T);const C=w instanceof Error?w:new Error(String(w));if(n={...n,isLoading:!1,error:C},t.onError)try{t.onError(C)}catch{}return d(),n.data}};t.autoStart!==!1&&_();const I={getState(){return n},subscribe(p){return a?()=>{}:(s.add(p),p(n),()=>{s.delete(p)})},onData(p){return I.subscribe(y=>{!y.isLoading&&!y.error&&y.data!==void 0&&p(y.data,y)})},refresh(){return _()},destroy(){a||(a=!0,o++,l!==null&&(clearTimeout(l),l=null),h(),s.clear())},[Symbol.asyncIterator](){const p=[];let y=null,T=null,O=null,w=!1;const C=U=>{if(!w)if(y){const Q=y;y=null,T=null,Q({value:U,done:!1})}else p.push({value:U})},B=U=>{if(!w)if(T){const Q=T;y=null,T=null,Q(U)}else p.push({error:U})};O=I.subscribe(U=>{U.isLoading||(U.error?B(U.error):U.data!==void 0&&C(U.data))});const P=()=>{if(!w&&(w=!0,O&&(O(),O=null),I.destroy(),y)){const U=y;y=null,T=null,U({value:void 0,done:!0})}};return{next(){if(p.length>0){const U=p.shift();return U.error?Promise.reject(U.error):U.done?Promise.resolve({value:void 0,done:!0}):Promise.resolve({value:U.value,done:!1})}return w||a?Promise.resolve({value:void 0,done:!0}):new Promise((U,Q)=>{y=U,T=Q})},return(){return P(),Promise.resolve({value:void 0,done:!0})},throw(U){return P(),Promise.reject(U)},[Symbol.asyncIterator](){return this}}}};return I}function Ks(e,t,n){const s=typeof t=="function",r=ha(e,s?n:t);return s&&r.onData(t),r}function x(e){return e instanceof Bt||typeof e=="object"&&e!==null&&typeof e.toArray=="function"&&typeof e.where=="function"&&typeof e.select=="function"&&"filters"in e}function wt(e){if(e instanceof it||typeof e=="object"&&e!==null&&"node"in e)return{expr:e.node};if(typeof e=="object"&&e!==null&&"type"in e)return{expr:e};if(typeof e=="string"){const t=e.trim();return t.includes("(")||t.includes("+")||t.includes("-")||t.includes("*")||t.includes("/")||t.includes("%")?{expr:At(t),colName:t}:{colName:t}}return{}}function _r(e){const t=[];function n(s){if(s.type==="fn"){const i=s.name.toLowerCase();if(de(i)){const r=s.args[0],o=r&&r.type==="col"&&r.name!=="*"?r.name:void 0;t.push({func:i,colName:o})}for(const r of s.args)n(r)}else s.type==="binary"&&(n(s.left),n(s.right))}return n(e),t}function Js(e){if(!e)return[];if(Array.isArray(e)){const t=[];for(const n of e)t.push(...Js(n));return t}if(x(e)){const t=e.getSelectFields(),n=e.getAggregates();return[{alias:t.length>0?t[0].alias:n.length>0?n[0].alias??(n[0].colName?`${n[0].func}_${n[0].colName}`:n[0].func):"subquery",subquery:e}]}if(e instanceof it||typeof e=="object"&&e!==null&&"node"in e){const t=e.node;return[{alias:vt(t),expr:t,sourceCol:t.type==="col"&&t.name!=="*"?t.name:void 0,fn:t.type==="fn"?t.name:void 0}]}if(typeof e=="string"){const t=e.trim();if(!t)return[];const n=qs(t);return[{alias:n.alias,expr:n.expr,sourceCol:n.expr.type==="col"&&n.expr.name!=="*"?n.expr.name:void 0,fn:n.expr.type==="fn"?n.expr.name:void 0}]}if(typeof e=="object"&&e!==null){if("subquery"in e&&"as"in e&&x(e.subquery)&&typeof e.as=="string")return[{alias:e.as,subquery:e.subquery}];if("expr"in e&&"alias"in e){const n=e.expr;return[{alias:e.alias,expr:n,sourceCol:n.type==="col"&&n.name!=="*"?n.name:void 0,fn:n.type==="fn"?n.name:void 0}]}if("col"in e&&"as"in e&&typeof e.col=="string"&&typeof e.as=="string"){const n=qs(`${e.col} as ${e.as}`);return[{sourceCol:e.col==="*"?void 0:e.col,alias:e.as,expr:n.expr,fn:n.expr.type==="fn"?n.expr.name:void 0}]}const t=[];for(const[n,s]of Object.entries(e))if(typeof s=="string"){const i=qs(`${n} as ${s}`);t.push({sourceCol:n==="*"?void 0:n,alias:s,expr:i.expr,fn:i.expr.type==="fn"?i.expr.name:void 0})}else if(x(s))t.push({alias:n,subquery:s});else if(typeof s=="object"&&s!==null&&"subquery"in s&&x(s.subquery))t.push({alias:n,subquery:s.subquery});else if(s instanceof it||typeof s=="object"&&s!==null&&"node"in s){const i=s.node;t.push({alias:n,expr:i,sourceCol:i.type==="col"&&i.name!=="*"?i.name:void 0,fn:i.type==="fn"?i.name:void 0})}else if(typeof s=="object"&&s!==null&&"type"in s){const i=s;t.push({alias:n,expr:i,sourceCol:i.type==="col"&&i.name!=="*"?i.name:void 0,fn:i.type==="fn"?i.name:void 0})}return t}return[]}function ut(e){if(!x(e))if(typeof e=="string"){const t=e.trim();if(de(t))throw new _s(t);if(t.includes("("))try{const n=At(t);rn(n,"where")}catch(n){if(n instanceof _s)throw n}}else e instanceof it||typeof e=="object"&&e!==null&&"node"in e?rn(e.node,"where"):typeof e=="object"&&e!==null&&"type"in e&&rn(e,"where")}class Bt{constructor(t,n){N(this,"db");N(this,"tableName");N(this,"sourceSubquery");N(this,"filters",[]);N(this,"selectFields",[]);N(this,"limitCount",null);N(this,"offsetCount",null);N(this,"sortCol",null);N(this,"sortDir","asc");N(this,"orderKeys",[]);N(this,"groupCols",[]);N(this,"groupKeys",[]);N(this,"aggExprs",[]);N(this,"havingFilters",[]);N(this,"joins",[]);N(this,"planner");this.db=t,x(n)?(this.sourceSubquery=n,this.tableName="__subquery__",this.assertSubqueryDepth(),js(this.db,n.getReferencedTables())):(this.tableName=n,js(this.db,n))}withPlanner(t){return this.planner=t,this}as(t){return{subquery:this,as:t}}getDb(){return this.db}getTableName(){return this.tableName}getReferencedTables(){const t=new Set,n=s=>{if(!s)return;s.tableName&&s.tableName!=="__subquery__"&&t.add(s.tableName),s.sourceSubquery&&n(s.sourceSubquery);for(const r of s.joins)r.table&&t.add(r.table);for(const r of s.selectFields)r.subquery&&x(r.subquery)&&n(r.subquery);const i=r=>{if(r&&(r.subquery&&x(r.subquery)&&n(r.subquery),r.value&&x(r.value)&&n(r.value),r.child&&i(r.child),r.children))for(const o of r.children)i(o)};for(const r of s.filters)i(r);for(const r of s.havingFilters)i(r)};return n(this),Array.from(t)}getSourceSubquery(){return this.sourceSubquery}getAggregates(){return this.aggExprs}getFilterSubqueryDepth(t){let n=0;if(t.subquery&&x(t.subquery)&&(n=Math.max(n,1+t.subquery.getMaxSubqueryDepth())),t.value&&x(t.value)&&(n=Math.max(n,1+t.value.getMaxSubqueryDepth())),t.child&&(n=Math.max(n,this.getFilterSubqueryDepth(t.child))),t.children)for(const s of t.children)n=Math.max(n,this.getFilterSubqueryDepth(s));return n}getMaxSubqueryDepth(){let t=0;this.sourceSubquery&&(t=Math.max(t,1+this.sourceSubquery.getMaxSubqueryDepth()));for(const n of this.selectFields)n.subquery&&(t=Math.max(t,1+n.subquery.getMaxSubqueryDepth()));for(const n of this.filters)t=Math.max(t,this.getFilterSubqueryDepth(n));for(const n of this.havingFilters)t=Math.max(t,this.getFilterSubqueryDepth(n));return t}assertSubqueryDepth(){const t=this.getMaxSubqueryDepth();if(t>7)throw new Xr(t,7)}join(t,n,s,i){const r=i!==void 0?s:"=",o=i!==void 0?i:s;return this.joins.push({type:"inner",table:t,leftCol:n,op:r,rightCol:o}),this}innerJoin(t,n,s,i){return this.join(t,n,s,i)}leftJoin(t,n,s,i){const r=i!==void 0?s:"=",o=i!==void 0?i:s;return this.joins.push({type:"left",table:t,leftCol:n,op:r,rightCol:o}),this}getJoins(){return this.joins}where(t,n,s){if(typeof t=="function"){const i=new Bt(this.db,this.tableName);t(i);const r=i.getRootFilter();r&&(this.filters.push(r),this.assertSubqueryDepth())}else if(n===void 0&&s===void 0){if(typeof t=="string"){ut(t);const i=At(t);this.filters.push({type:"expr",expr:i})}else if(t instanceof it||typeof t=="object"&&t!==null&&"node"in t)ut(t),this.filters.push({type:"expr",expr:t.node});else if(typeof t=="object"&&t!==null&&"type"in t)ut(t),this.filters.push({type:"expr",expr:t});else if(typeof t=="object"&&t!==null)for(const[i,r]of Object.entries(t))this.where(i,"=",r)}else{if(ut(t),ut(s),typeof n=="string"&&n.trim().toLowerCase()==="in")return this.whereIn(t,s);if(typeof n=="string"&&n.trim().toLowerCase()==="not in")return this.whereNotIn(t,s);const i=wt(t);x(s)?(this.filters.push({type:"cmp",colName:i.colName,expr:i.expr,op:n,value:s,subquery:s}),this.assertSubqueryDepth()):this.filters.push({type:"cmp",colName:i.colName,expr:i.expr,op:n,value:s})}return this}orWhere(t,n,s){if(typeof t=="function"){const i=new Bt(this.db,this.tableName);t(i);const r=i.getRootFilter();r&&(this.addOrFilter(r),this.assertSubqueryDepth())}else if(n===void 0&&s===void 0)if(typeof t=="string"){ut(t);const i=At(t);this.addOrFilter({type:"expr",expr:i})}else t instanceof it||typeof t=="object"&&t!==null&&"node"in t?(ut(t),this.addOrFilter({type:"expr",expr:t.node})):typeof t=="object"&&t!==null&&"type"in t&&(ut(t),this.addOrFilter({type:"expr",expr:t}));else{if(ut(t),ut(s),typeof n=="string"&&n.trim().toLowerCase()==="in")return this.orWhereIn(t,s);if(typeof n=="string"&&n.trim().toLowerCase()==="not in")return this.orWhereNotIn(t,s);const i=wt(t);x(s)?(this.addOrFilter({type:"cmp",colName:i.colName,expr:i.expr,op:n,value:s,subquery:s}),this.assertSubqueryDepth()):this.addOrFilter({type:"cmp",colName:i.colName,expr:i.expr,op:n,value:s})}return this}whereNot(t,n,s){if(typeof t=="function"){const i=new Bt(this.db,this.tableName);t(i);const r=i.getRootFilter();r&&(this.filters.push({type:"not",child:r}),this.assertSubqueryDepth())}else if(n===void 0&&s===void 0)if(typeof t=="string"){ut(t);const i=At(t);this.filters.push({type:"not",child:{type:"expr",expr:i}})}else t instanceof it||typeof t=="object"&&t!==null&&"node"in t?(ut(t),this.filters.push({type:"not",child:{type:"expr",expr:t.node}})):typeof t=="object"&&t!==null&&"type"in t&&(ut(t),this.filters.push({type:"not",child:{type:"expr",expr:t}}));else{if(ut(t),ut(s),typeof n=="string"&&n.trim().toLowerCase()==="in")return this.whereNotIn(t,s);if(typeof n=="string"&&n.trim().toLowerCase()==="not in")return this.whereIn(t,s);const i=wt(t);this.filters.push({type:"not",child:{type:"cmp",colName:i.colName,expr:i.expr,op:n,value:s,subquery:x(s)?s:void 0}}),x(s)&&this.assertSubqueryDepth()}return this}orWhereNot(t,n,s){if(typeof t=="function"){const i=new Bt(this.db,this.tableName);t(i);const r=i.getRootFilter();r&&(this.addOrFilter({type:"not",child:r}),this.assertSubqueryDepth())}else if(n===void 0&&s===void 0)if(typeof t=="string"){ut(t);const i=At(t);this.addOrFilter({type:"not",child:{type:"expr",expr:i}})}else t instanceof it||typeof t=="object"&&t!==null&&"node"in t?(ut(t),this.addOrFilter({type:"not",child:{type:"expr",expr:t.node}})):typeof t=="object"&&t!==null&&"type"in t&&(ut(t),this.addOrFilter({type:"not",child:{type:"expr",expr:t}}));else{if(ut(t),ut(s),typeof n=="string"&&n.trim().toLowerCase()==="in")return this.orWhereNotIn(t,s);if(typeof n=="string"&&n.trim().toLowerCase()==="not in")return this.orWhereIn(t,s);const i=wt(t);this.addOrFilter({type:"not",child:{type:"cmp",colName:i.colName,expr:i.expr,op:n,value:s,subquery:x(s)?s:void 0}}),x(s)&&this.assertSubqueryDepth()}return this}whereRaw(t){return this.where(t)}orWhereRaw(t){return this.orWhere(t)}whereNull(t){return ut(t),this.filters.push({type:"null",colName:t,isNull:!0}),this}whereNotNull(t){return ut(t),this.filters.push({type:"null",colName:t,isNull:!1}),this}orWhereNull(t){return ut(t),this.addOrFilter({type:"null",colName:t,isNull:!0}),this}orWhereNotNull(t){return ut(t),this.addOrFilter({type:"null",colName:t,isNull:!1}),this}whereLike(t,n){return this.where(t,"like",n)}whereNotLike(t,n){return this.where(t,"not like",n)}whereStartsWith(t,n){return this.where(t,"starts_with",n)}whereEndsWith(t,n){return this.where(t,"ends_with",n)}whereContains(t,n){return this.where(t,"contains",n)}orWhereLike(t,n){return this.orWhere(t,"like",n)}orWhereNotLike(t,n){return this.orWhere(t,"not like",n)}orWhereStartsWith(t,n){return this.orWhere(t,"starts_with",n)}orWhereEndsWith(t,n){return this.orWhere(t,"ends_with",n)}orWhereContains(t,n){return this.orWhere(t,"contains",n)}whereIn(t,n){ut(t);const s=wt(t);if(x(n))return this.filters.push({type:"in",colName:s.colName,expr:s.expr,subquery:n,notIn:!1}),this.assertSubqueryDepth(),this;if(!Array.isArray(n))throw new TypeError("WebDB: whereIn requires an array of values");if(n.length>Qt)throw new RangeError(`WebDB: whereIn list exceeds maximum limit of ${Qt} elements`);return this.filters.push({type:"in",colName:s.colName,expr:s.expr,values:n,notIn:!1}),this}whereNotIn(t,n){ut(t);const s=wt(t);if(x(n))return this.filters.push({type:"in",colName:s.colName,expr:s.expr,subquery:n,notIn:!0}),this.assertSubqueryDepth(),this;if(!Array.isArray(n))throw new TypeError("WebDB: whereNotIn requires an array of values");if(n.length>Qt)throw new RangeError(`WebDB: whereNotIn list exceeds maximum limit of ${Qt} elements`);return this.filters.push({type:"in",colName:s.colName,expr:s.expr,values:n,notIn:!0}),this}orWhereIn(t,n){ut(t);const s=wt(t);if(x(n))return this.addOrFilter({type:"in",colName:s.colName,expr:s.expr,subquery:n,notIn:!1}),this.assertSubqueryDepth(),this;if(!Array.isArray(n))throw new TypeError("WebDB: orWhereIn requires an array of values");if(n.length>Qt)throw new RangeError(`WebDB: orWhereIn list exceeds maximum limit of ${Qt} elements`);return this.addOrFilter({type:"in",colName:s.colName,expr:s.expr,values:n,notIn:!1}),this}orWhereNotIn(t,n){ut(t);const s=wt(t);if(x(n))return this.addOrFilter({type:"in",colName:s.colName,expr:s.expr,subquery:n,notIn:!0}),this.assertSubqueryDepth(),this;if(!Array.isArray(n))throw new TypeError("WebDB: orWhereNotIn requires an array of values");if(n.length>Qt)throw new RangeError(`WebDB: orWhereNotIn list exceeds maximum limit of ${Qt} elements`);return this.addOrFilter({type:"in",colName:s.colName,expr:s.expr,values:n,notIn:!0}),this}whereExists(t){if(!x(t))throw new TypeError("WebDB: whereExists requires a QueryBuilder subquery");return this.filters.push({type:"exists",subquery:t,notExists:!1}),this.assertSubqueryDepth(),this}whereNotExists(t){if(!x(t))throw new TypeError("WebDB: whereNotExists requires a QueryBuilder subquery");return this.filters.push({type:"exists",subquery:t,notExists:!0}),this.assertSubqueryDepth(),this}orWhereExists(t){if(!x(t))throw new TypeError("WebDB: orWhereExists requires a QueryBuilder subquery");return this.addOrFilter({type:"exists",subquery:t,notExists:!1}),this.assertSubqueryDepth(),this}orWhereNotExists(t){if(!x(t))throw new TypeError("WebDB: orWhereNotExists requires a QueryBuilder subquery");return this.addOrFilter({type:"exists",subquery:t,notExists:!0}),this.assertSubqueryDepth(),this}getFilters(){return this.filters}getRootFilter(){return this.filters.length===0?null:this.filters.length===1?this.filters[0]:{type:"and",children:[...this.filters]}}addOrFilter(t){if(this.filters.length===0){this.filters.push(t);return}if(this.filters.length===1&&this.filters[0].type==="or"&&this.filters[0].children){this.filters[0].children.push(t);return}let n;this.filters.length===1?n=this.filters[0]:n={type:"and",children:[...this.filters]},this.filters=[{type:"or",children:[n,t]}]}limit(t){return this.limitCount=t,this}offset(t){return this.offsetCount=t,this}orderBy(t,n="asc",s){if(typeof t=="string"){this.sortCol=t,this.sortDir=n;const i=wt(t);this.orderKeys.push({colName:i.colName??t,expr:i.expr,direction:n,nullOrder:s})}else if(t instanceof it||typeof t=="object"&&t!==null&&"node"in t)this.orderKeys.push({expr:t.node,direction:n,nullOrder:s});else if(typeof t=="object"&&t!==null&&"type"in t)this.orderKeys.push({expr:t,direction:n,nullOrder:s});else if(Array.isArray(t))for(const i of t)if(typeof i=="string"){const r=wt(i);this.orderKeys.push({colName:r.colName??i,expr:r.expr,direction:"asc"})}else this.orderKeys.push(i);else this.orderKeys.push(t);return this}groupBy(...t){for(const n of t)if(Array.isArray(n))for(const s of n)this.addGroupByItem(s);else this.addGroupByItem(n);return this}addGroupByItem(t){if(t instanceof it||typeof t=="object"&&t!==null&&"node"in t)this.groupKeys.push({expr:t.node}),this.groupCols.push(vt(t.node));else if(typeof t=="object"&&t!==null&&"type"in t)this.groupKeys.push({expr:t}),this.groupCols.push(vt(t));else if(typeof t=="string"){const n=wt(t);this.groupKeys.push({colName:n.colName??t,expr:n.expr}),this.groupCols.push(t)}}registerAggregatesFromFilter(t){const n=(s,i)=>{if(i){const r=_r(i);for(const o of r)this.aggExprs.some(c=>c.func===o.func&&(c.colName===o.colName||c.colName===void 0&&o.colName===void 0))||this.aggExprs.push(o)}else if(s&&s.includes("("))try{const r=At(s),o=_r(r);for(const a of o)this.aggExprs.some(l=>l.func===a.func&&(l.colName===a.colName||l.colName===void 0&&a.colName===void 0))||this.aggExprs.push(a)}catch{}};if(t.type==="cmp")n(t.colName,t.expr);else if(t.type==="expr"&&t.expr)n(void 0,t.expr);else if(t.type==="null")n(t.colName,t.expr);else if(t.type==="not"&&t.child)this.registerAggregatesFromFilter(t.child);else if((t.type==="and"||t.type==="or")&&t.children)for(const s of t.children)this.registerAggregatesFromFilter(s)}having(t,n,s){if(typeof t=="function"){const i=new Bt(this.db,this.tableName);t(i);const r=i.getRootHavingFilter();r&&(this.havingFilters.push(r),this.registerAggregatesFromFilter(r),this.assertSubqueryDepth())}else if(n===void 0&&s===void 0){if(typeof t=="string"){const r={type:"expr",expr:At(t)};this.havingFilters.push(r),this.registerAggregatesFromFilter(r)}else if(t instanceof it||typeof t=="object"&&t!==null&&"node"in t){const i={type:"expr",expr:t.node};this.havingFilters.push(i),this.registerAggregatesFromFilter(i)}else if(typeof t=="object"&&t!==null&&"type"in t){const i={type:"expr",expr:t};this.havingFilters.push(i),this.registerAggregatesFromFilter(i)}}else{const i=wt(t);if(typeof n=="string"&&(n.trim().toLowerCase()==="in"||n.trim().toLowerCase()==="not in")){const o=n.trim().toLowerCase()==="not in",a=x(s)?{type:"in",colName:i.colName,expr:i.expr,subquery:s,notIn:o}:{type:"in",colName:i.colName,expr:i.expr,values:s,notIn:o};return this.havingFilters.push(a),this.registerAggregatesFromFilter(a),this.assertSubqueryDepth(),this}const r={type:"cmp",colName:i.colName,expr:i.expr,op:n,value:s,subquery:x(s)?s:void 0};this.havingFilters.push(r),this.registerAggregatesFromFilter(r),x(s)&&this.assertSubqueryDepth()}return this}orHaving(t,n,s){if(typeof t=="function"){const i=new Bt(this.db,this.tableName);t(i);const r=i.getRootHavingFilter();r&&(this.addHavingOrFilter(r),this.registerAggregatesFromFilter(r),this.assertSubqueryDepth())}else if(n===void 0&&s===void 0){if(typeof t=="string"){const r={type:"expr",expr:At(t)};this.addHavingOrFilter(r),this.registerAggregatesFromFilter(r)}else if(t instanceof it||typeof t=="object"&&t!==null&&"node"in t){const i={type:"expr",expr:t.node};this.addHavingOrFilter(i),this.registerAggregatesFromFilter(i)}else if(typeof t=="object"&&t!==null&&"type"in t){const i={type:"expr",expr:t};this.addHavingOrFilter(i),this.registerAggregatesFromFilter(i)}}else{const i=wt(t),r={type:"cmp",colName:i.colName,expr:i.expr,op:n,value:s,subquery:x(s)?s:void 0};this.addHavingOrFilter(r),this.registerAggregatesFromFilter(r),x(s)&&this.assertSubqueryDepth()}return this}havingNot(t,n,s){if(typeof t=="function"){const i=new Bt(this.db,this.tableName);t(i);const r=i.getRootHavingFilter();if(r){const o={type:"not",child:r};this.havingFilters.push(o),this.registerAggregatesFromFilter(o),this.assertSubqueryDepth()}}else if(n===void 0&&s===void 0){if(typeof t=="string"){const r={type:"not",child:{type:"expr",expr:At(t)}};this.havingFilters.push(r),this.registerAggregatesFromFilter(r)}else if(t instanceof it||typeof t=="object"&&t!==null&&"node"in t){const i={type:"not",child:{type:"expr",expr:t.node}};this.havingFilters.push(i),this.registerAggregatesFromFilter(i)}else if(typeof t=="object"&&t!==null&&"type"in t){const i={type:"not",child:{type:"expr",expr:t}};this.havingFilters.push(i),this.registerAggregatesFromFilter(i)}}else{const i=wt(t),r={type:"not",child:{type:"cmp",colName:i.colName,expr:i.expr,op:n,value:s,subquery:x(s)?s:void 0}};this.havingFilters.push(r),this.registerAggregatesFromFilter(r),x(s)&&this.assertSubqueryDepth()}return this}orHavingNot(t,n,s){if(typeof t=="function"){const i=new Bt(this.db,this.tableName);t(i);const r=i.getRootHavingFilter();if(r){const o={type:"not",child:r};this.addHavingOrFilter(o),this.registerAggregatesFromFilter(o),this.assertSubqueryDepth()}}else if(n===void 0&&s===void 0){if(typeof t=="string"){const r={type:"not",child:{type:"expr",expr:At(t)}};this.addHavingOrFilter(r),this.registerAggregatesFromFilter(r)}else if(t instanceof it||typeof t=="object"&&t!==null&&"node"in t){const i={type:"not",child:{type:"expr",expr:t.node}};this.addHavingOrFilter(i),this.registerAggregatesFromFilter(i)}else if(typeof t=="object"&&t!==null&&"type"in t){const i={type:"not",child:{type:"expr",expr:t}};this.addHavingOrFilter(i),this.registerAggregatesFromFilter(i)}}else{const i=wt(t),r={type:"not",child:{type:"cmp",colName:i.colName,expr:i.expr,op:n,value:s,subquery:x(s)?s:void 0}};this.addHavingOrFilter(r),this.registerAggregatesFromFilter(r),x(s)&&this.assertSubqueryDepth()}return this}havingRaw(t){return this.having(t)}orHavingRaw(t){return this.orHaving(t)}havingNull(t){const n=wt(t),s={type:"null",colName:n.colName,expr:n.expr,isNull:!0};return this.havingFilters.push(s),this.registerAggregatesFromFilter(s),this}havingNotNull(t){const n=wt(t),s={type:"null",colName:n.colName,expr:n.expr,isNull:!1};return this.havingFilters.push(s),this.registerAggregatesFromFilter(s),this}orHavingNull(t){const n=wt(t),s={type:"null",colName:n.colName,expr:n.expr,isNull:!0};return this.addHavingOrFilter(s),this.registerAggregatesFromFilter(s),this}orHavingNotNull(t){const n=wt(t),s={type:"null",colName:n.colName,expr:n.expr,isNull:!1};return this.addHavingOrFilter(s),this.registerAggregatesFromFilter(s),this}getHavingFilters(){return this.havingFilters}getRootHavingFilter(){return this.havingFilters.length===0?null:this.havingFilters.length===1?this.havingFilters[0]:{type:"and",children:[...this.havingFilters]}}addHavingOrFilter(t){if(this.havingFilters.length===0){this.havingFilters.push(t);return}if(this.havingFilters.length===1&&this.havingFilters[0].type==="or"&&this.havingFilters[0].children){this.havingFilters[0].children.push(t);return}let n;this.havingFilters.length===1?n=this.havingFilters[0]:n={type:"and",children:[...this.havingFilters]},this.havingFilters=[{type:"or",children:[n,t]}]}aggregate(t){return this.aggExprs.push(...t),this}count(t,n){return this.aggExprs.push({func:"count",colName:t,alias:n}),this}sum(t,n){return this.aggExprs.push({func:"sum",colName:t,alias:n}),this}avg(t,n){return this.aggExprs.push({func:"avg",colName:t,alias:n}),this}min(t,n){return this.aggExprs.push({func:"min",colName:t,alias:n}),this}max(t,n){return this.aggExprs.push({func:"max",colName:t,alias:n}),this}select(t,...n){if(t===void 0)return this;const s=[];s.push(...Js(t));for(const i of n)s.push(...Js(i));this.selectFields.push(...s),this.assertSubqueryDepth();for(const i of s)if(i.expr&&i.expr.type==="fn"){const r=i.expr.name.toLowerCase();if(de(r)&&!this.aggExprs.some(a=>a.alias===i.alias)){const a=i.expr.args[0],c=a&&a.type==="col"&&a.name!=="*"?a.name:void 0;this.aggExprs.push({func:r,colName:c,alias:i.alias})}}else if(typeof i.fn=="string"){const r=i.fn.toLowerCase();de(r)&&(this.aggExprs.some(a=>a.alias===i.alias)||this.aggExprs.push({func:r,colName:i.sourceCol==="*"?void 0:i.sourceCol,alias:i.alias}))}return this}getSelectFields(){return this.selectFields}clone(t){const n=t??this.db,s=new Bt(n,this.sourceSubquery?this.sourceSubquery.clone(n):this.tableName),i=r=>({...r,values:r.values?[...r.values]:void 0,subquery:r.subquery&&x(r.subquery)?r.subquery.clone(n):r.subquery,value:x(r.value)?r.value.clone(n):r.value,child:r.child?i(r.child):void 0,children:r.children?r.children.map(i):void 0});return s.filters=this.filters.map(i),s.selectFields=this.selectFields.map(r=>({...r,args:r.args?[...r.args]:void 0,subquery:r.subquery?r.subquery.clone(n):void 0})),s.limitCount=this.limitCount,s.offsetCount=this.offsetCount,s.sortCol=this.sortCol,s.sortDir=this.sortDir,s.orderKeys=this.orderKeys.map(r=>({...r})),s.groupCols=[...this.groupCols],s.groupKeys=this.groupKeys.map(r=>({...r})),s.aggExprs=this.aggExprs.map(r=>({...r})),s.havingFilters=this.havingFilters.map(i),s.joins=this.joins.map(r=>({...r})),s.planner=this.planner,s}cloneExprNode(t){return t.type==="binary"?{...t,left:this.cloneExprNode(t.left),right:this.cloneExprNode(t.right)}:t.type==="fn"?{...t,args:t.args.map(n=>this.cloneExprNode(n))}:{...t}}substituteExpr(t,n){if(t.type==="col"){if(t.name==="*")return t;const s=t.name.includes(".")?t.name.slice(t.name.lastIndexOf(".")+1):t.name,i=n.get(t.name)??n.get(s);return i?this.cloneExprNode(i):{...t}}return t.type==="binary"?{...t,left:this.substituteExpr(t.left,n),right:this.substituteExpr(t.right,n)}:t.type==="fn"?{...t,args:t.args.map(s=>this.substituteExpr(s,n))}:{...t}}substituteColOrExpr(t,n,s){if(n){const i=this.substituteExpr(n,s);return i.type==="col"?{colName:i.name,expr:i}:{expr:i}}if(t){const i=t.includes(".")?t.slice(t.lastIndexOf(".")+1):t,r=s.get(t)??s.get(i);if(r){const o=this.cloneExprNode(r);return o.type==="col"?{colName:o.name}:{expr:o}}return{colName:t}}return{colName:t,expr:n}}substituteFilter(t,n){var i;if(t.type==="and"||t.type==="or")return{...t,children:(i=t.children)==null?void 0:i.map(r=>this.substituteFilter(r,n))};if(t.type==="not"&&t.child)return{...t,child:this.substituteFilter(t.child,n)};if(t.type==="exists")return{...t};const s=this.substituteColOrExpr(t.colName,t.expr,n);return{...t,colName:s.colName,expr:s.expr}}tryFlatten(){var r;if(!this.sourceSubquery)return null;const t=this.sourceSubquery.tryFlatten()??this.sourceSubquery.clone(this.db);if(t.sourceSubquery||t.groupKeys.length>0||t.groupCols.length>0||t.aggExprs.length>0||t.havingFilters.length>0||t.limitCount!==null||t.offsetCount!==null||t.joins.length>0||t.selectFields.some(o=>o.subquery)||this.joins.length>0)return null;const n=new Map;for(const o of t.selectFields){const a=o.expr??{type:"col",name:o.sourceCol??o.alias};n.set(o.alias,a)}for(const o of this.aggExprs)if(o.colName){const a=o.colName.includes(".")?o.colName.slice(o.colName.lastIndexOf(".")+1):o.colName,c=n.get(o.colName)??n.get(a);if(c&&c.type!=="col")return null}for(const o of this.groupKeys){const a=this.substituteColOrExpr(o.colName,o.expr,n);if(!a.colName&&a.expr&&a.expr.type!=="col")return null}const s=new Bt(this.db,t.tableName);s.planner=this.planner??t.planner,s.filters=[...t.filters.map(o=>({...o})),...this.filters.map(o=>this.substituteFilter(o,n))],this.selectFields.length>0?s.selectFields=this.selectFields.map(o=>{if(o.subquery)return{...o,subquery:o.subquery.clone(this.db)};const a=o.expr??{type:"col",name:o.sourceCol??o.alias},c=this.substituteExpr(a,n);return{alias:o.alias,expr:c,sourceCol:c.type==="col"&&c.name!=="*"?c.name:void 0,fn:c.type==="fn"?c.name:void 0}}):t.selectFields.length>0&&(s.selectFields=t.selectFields.map(o=>({...o})));const i=this.aggExprs.length>0||this.groupKeys.length>0||this.groupCols.length>0;return this.orderKeys.length>0?(s.orderKeys=this.orderKeys.map(o=>{const a=this.substituteColOrExpr(o.colName,o.expr,n);return{...o,colName:a.colName,expr:a.expr}}),(r=s.orderKeys[0])!=null&&r.colName&&(s.sortCol=s.orderKeys[0].colName,s.sortDir=s.orderKeys[0].direction??"asc")):!i&&t.orderKeys.length>0&&(s.orderKeys=t.orderKeys.map(o=>({...o})),s.sortCol=t.sortCol,s.sortDir=t.sortDir),s.groupKeys=this.groupKeys.map(o=>{const a=this.substituteColOrExpr(o.colName,o.expr,n);return{colName:a.colName,expr:a.expr}}),s.groupCols=this.groupCols.map(o=>{const a=n.get(o);return a&&a.type==="col"?a.name:o}),s.aggExprs=this.aggExprs.map(o=>{if(o.colName){const a=n.get(o.colName);if(a&&a.type==="col")return{...o,colName:a.name}}return{...o}}),s.havingFilters=this.havingFilters.map(o=>this.substituteFilter(o,n)),s.limitCount=this.limitCount,s.offsetCount=this.offsetCount,s}exprReferencesOuter(t,n){if(!t)return!1;if(t.type==="col"){if(t.name.includes(".")){const s=t.name.slice(0,t.name.indexOf("."));if(s==="outer"||!n.has(s))return!0}return!1}return t.type==="binary"?this.exprReferencesOuter(t.left,n)||this.exprReferencesOuter(t.right,n):t.type==="fn"?t.args.some(s=>this.exprReferencesOuter(s,n)):!1}filterIsCorrelatedWithOuter(t,n){var s;if(t.type==="and"||t.type==="or")return((s=t.children)==null?void 0:s.some(i=>this.filterIsCorrelatedWithOuter(i,n)))??!1;if(t.type==="not"&&t.child)return this.filterIsCorrelatedWithOuter(t.child,n);if(t.type==="cmp"&&(t.value instanceof it||typeof t.value=="object"&&t.value!==null&&!x(t.value)&&("node"in t.value||"type"in t.value)||t.subquery&&x(t.subquery)&&this.isSubqueryCorrelated(t.subquery))||(t.type==="in"||t.type==="exists")&&t.subquery&&x(t.subquery)&&this.isSubqueryCorrelated(t.subquery))return!0;if(t.colName&&t.colName.includes(".")){const i=t.colName.slice(0,t.colName.indexOf("."));if(i==="outer"||!n.has(i))return!0}return!!this.exprReferencesOuter(t.expr,n)}isSubqueryCorrelated(t){const n=new Set([t.tableName]);for(const s of t.joins)n.add(s.table);return!!(t.filters.some(s=>this.filterIsCorrelatedWithOuter(s,n))||t.havingFilters.some(s=>this.filterIsCorrelatedWithOuter(s,n))||t.sourceSubquery&&this.isSubqueryCorrelated(t.sourceSubquery)||t.selectFields.some(s=>s.subquery&&this.isSubqueryCorrelated(s.subquery)))}filterContainsCorrelatedSubquery(t){var s;if(t.type==="and"||t.type==="or")return((s=t.children)==null?void 0:s.some(i=>this.filterContainsCorrelatedSubquery(i)))??!1;if(t.type==="not"&&t.child)return this.filterContainsCorrelatedSubquery(t.child);const n=t.subquery&&x(t.subquery)?t.subquery:x(t.value)?t.value:void 0;return!!(n&&this.isSubqueryCorrelated(n))}getRowValue(t,n){if(n in t)return t[n];if(n.startsWith("outer.")){const s=n.slice(6);if(s in t)return t[s]}if(n.includes(".")){const s=n.slice(n.lastIndexOf(".")+1);if(s in t)return t[s]}}bindOuterRowToExpr(t,n,s,i=!1){if(t.type==="col"){if(i)return{type:"literal",value:this.getRowValue(n,t.name)??null};if(t.name.includes(".")){const r=t.name.slice(0,t.name.indexOf("."));if(r==="outer"||!s.has(r))return{type:"literal",value:this.getRowValue(n,t.name)??null}}return{...t}}return t.type==="binary"?{...t,left:this.bindOuterRowToExpr(t.left,n,s,i),right:this.bindOuterRowToExpr(t.right,n,s,i)}:t.type==="fn"?{...t,args:t.args.map(r=>this.bindOuterRowToExpr(r,n,s,i))}:{...t}}bindOuterRowToFilter(t,n,s){var r;if(t.type==="and"||t.type==="or")return{...t,children:(r=t.children)==null?void 0:r.map(o=>this.bindOuterRowToFilter(o,n,s))};if(t.type==="not"&&t.child)return{...t,child:this.bindOuterRowToFilter(t.child,n,s)};let i=t.expr?this.bindOuterRowToExpr(t.expr,n,s,!1):void 0;if(t.type==="cmp"&&(t.value instanceof it||typeof t.value=="object"&&t.value!==null&&!x(t.value)&&("node"in t.value||"type"in t.value))){const o="node"in t.value?t.value.node:t.value,a=this.bindOuterRowToExpr(o,n,s,!0);let c;typeof this.db.getUdf=="function"&&(c=u=>{var d,h;return(h=(d=this.db.getUdf(u))==null?void 0:d.def)==null?void 0:h.call});const l=kt(a,n,c);return l==null?{type:"in",values:[],notIn:!1}:{...t,expr:i,value:l}}return{...t,expr:i,subquery:t.subquery&&x(t.subquery)?this.bindOuterRowToSubquery(t.subquery,n):t.subquery}}bindOuterRowToSubquery(t,n){const s=t.clone(this.db),i=new Set([s.tableName]);for(const r of s.joins)i.add(r.table);return s.filters=s.filters.map(r=>this.bindOuterRowToFilter(r,n,i)),s.havingFilters=s.havingFilters.map(r=>this.bindOuterRowToFilter(r,n,i)),s.sourceSubquery&&(s.sourceSubquery=this.bindOuterRowToSubquery(s.sourceSubquery,n)),s}async evalScalarSubquery(t,n){const i=await(n&&this.isSubqueryCorrelated(t)?this.bindOuterRowToSubquery(t,n):t.clone(this.db)).first();if(!i)return null;const r=Object.keys(i);return r.length>0?i[r[0]]:null}async resolveUncorrelatedFilter(t){if(t.type==="and"||t.type==="or"){const n=[];for(const s of t.children??[])n.push(await this.resolveUncorrelatedFilter(s));return{...t,children:n}}if(t.type==="not"&&t.child)return{...t,child:await this.resolveUncorrelatedFilter(t.child)};if(t.type==="in"&&t.subquery&&x(t.subquery)&&!this.isSubqueryCorrelated(t.subquery)){const s=(await t.subquery.clone(this.db).toArray()).map(r=>{const o=Object.keys(r);return o.length>0?r[o[0]]:null});if(t.notIn&&s.some(r=>r==null))return{type:"in",colName:t.colName,expr:t.expr,values:[],notIn:!1};const i=s.filter(r=>r!=null);if(i.length>Qt)throw new RangeError(`WebDB: whereIn subquery result exceeds maximum limit of ${Qt} elements`);return{type:"in",colName:t.colName,expr:t.expr,values:i,notIn:t.notIn}}if(t.type==="exists"&&t.subquery&&x(t.subquery)&&!this.isSubqueryCorrelated(t.subquery)){const s=await t.subquery.clone(this.db).first()!==null,i=t.notExists?!s:s;return{type:"in",values:[],notIn:i}}if(t.type==="cmp"){const n=t.subquery&&x(t.subquery)?t.subquery:x(t.value)?t.value:void 0;if(n&&!this.isSubqueryCorrelated(n)){const s=await this.evalScalarSubquery(n);return s==null?{type:"in",colName:t.colName,expr:t.expr,values:[],notIn:!1}:{...t,value:s,subquery:void 0}}}return t}async resolveUncorrelatedFilters(t){const n=[];for(const s of t)n.push(await this.resolveUncorrelatedFilter(s));return n}evalFilterTargetValue(t,n,s){let i;if(typeof this.db.getUdf=="function"&&(i=r=>{var o,a;return(a=(o=this.db.getUdf(r))==null?void 0:o.def)==null?void 0:a.call}),n&&t[n]!==void 0)return t[n];if(s){const r=vt(s);return t[r]!==void 0?t[r]:kt(s,t,i)}if(n)return this.getRowValue(t,n)}evalComparisonValues(t,n,s){if(t==null||s===null||s===void 0)return!1;const i=(n??"=").trim().toLowerCase();switch(i){case"=":return t===s;case"!=":case"<>":return t!==s;case"<":return t<s;case"<=":return t<=s;case">":return t>s;case">=":return t>=s;case"starts_with":return String(t).startsWith(String(s));case"ends_with":return String(t).endsWith(String(s));case"contains":return String(t).includes(String(s));case"like":case"not like":{const r=String(s).replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/%/g,".*").replace(/_/g,"."),a=new RegExp(`^${r}$`,"s").test(String(t));return i==="not like"?!a:a}default:return t===s}}async evalFilterOnRow(t,n){if(n.type==="and"){for(const s of n.children??[])if(!await this.evalFilterOnRow(t,s))return!1;return!0}if(n.type==="or"){for(const s of n.children??[])if(await this.evalFilterOnRow(t,s))return!0;return!1}if(n.type==="not"&&n.child){if(n.child.type==="cmp"||n.child.type==="in"){const s=this.evalFilterTargetValue(t,n.child.colName,n.child.expr);if(s==null)return!1}return!await this.evalFilterOnRow(t,n.child)}if(n.type==="null"){const s=this.evalFilterTargetValue(t,n.colName,n.expr),i=s==null;return n.isNull?i:!i}if(n.type==="expr"&&n.expr){let s;typeof this.db.getUdf=="function"&&(s=r=>{var o,a;return(a=(o=this.db.getUdf(r))==null?void 0:o.def)==null?void 0:a.call});const i=kt(n.expr,t,s);return!!(i&&i!==0)}if(n.type==="exists"){if(n.subquery&&x(n.subquery)){const r=await(this.isSubqueryCorrelated(n.subquery)?this.bindOuterRowToSubquery(n.subquery,t):n.subquery.clone(this.db)).first()!==null;return n.notExists?!r:r}return!!n.notExists}if(n.type==="in"){let s=n.values??[];if(n.subquery&&x(n.subquery)){const c=(await(this.isSubqueryCorrelated(n.subquery)?this.bindOuterRowToSubquery(n.subquery,t):n.subquery.clone(this.db)).toArray()).map(l=>{const u=Object.keys(l);return u.length>0?l[u[0]]:null});if(n.notIn&&c.some(l=>l==null))return!1;s=c.filter(l=>l!=null)}if(!n.colName&&!n.expr)return n.notIn?s.length===0:s.length>0;if(s.length===0)return!!n.notIn;const i=this.evalFilterTargetValue(t,n.colName,n.expr);if(i==null||n.notIn&&s.some(o=>o==null))return!1;const r=s.includes(i);return n.notIn?!r:r}if(n.type==="cmp"){const s=this.evalFilterTargetValue(t,n.colName,n.expr),i=n.subquery&&x(n.subquery)?n.subquery:x(n.value)?n.value:void 0,r=i?await this.evalScalarSubquery(i,t):n.value;return this.evalComparisonValues(s,n.op,r)}return!0}async evalFiltersOnRows(t,n){if(n.length===0)return t;const s=await this.resolveUncorrelatedFilters(n),i=[];for(const r of t){let o=!0;for(const a of s)if(!await this.evalFilterOnRow(r,a)){o=!1;break}o&&i.push(r)}return i}performInMemoryAggregation(t){const n=Math.max(this.groupKeys.length,this.groupCols.length),s=new Map;if(n===0)s.set("__global__",{keyRow:{},rows:t});else for(const a of t){const c=[],l={};for(let h=0;h<n;h++){const f=this.groupKeys[h],g=this.groupCols[h],_=this.evalFilterTargetValue(a,(f==null?void 0:f.colName)??g,f==null?void 0:f.expr);c.push(_);const I=(f==null?void 0:f.colName)??(f!=null&&f.expr?vt(f.expr):g);I&&(l[I]=_,I.includes(".")&&(l[I.slice(I.lastIndexOf(".")+1)]=_)),g&&(l[g]=_)}const u=JSON.stringify(c);let d=s.get(u);d||(d={keyRow:l,rows:[]},s.set(u,d)),d.rows.push(a)}let i;typeof this.db.getUdf=="function"&&(i=a=>{var c,l;return(l=(c=this.db.getUdf(a))==null?void 0:c.def)==null?void 0:l.call});const r=(a,c,l,u)=>{const d=c.toLowerCase();if(d==="count"){if(!l&&(!u||u.type==="col"&&u.name==="*"))return a.length;let f=0;for(const g of a){const _=u?kt(u,g,i):this.getRowValue(g,l);_!=null&&f++}return f}const h=[];for(const f of a){const g=u?kt(u,f,i):l?this.getRowValue(f,l):null;g!=null&&h.push(g)}return h.length===0?null:d==="sum"?h.reduce((f,g)=>f+Number(g),0):d==="avg"?h.reduce((f,g)=>f+Number(g),0)/h.length:d==="min"?h.reduce((f,g)=>g<f?g:f,h[0]):d==="max"?h.reduce((f,g)=>g>f?g:f,h[0]):null},o=[];for(const{keyRow:a,rows:c}of s.values()){const l={...a};for(const u of this.aggExprs){const d=r(c,u.func,u.colName),h=u.alias??(u.colName?`${u.func}_${u.colName}`:u.func);l[h]=d,l[`${u.func}(${u.colName??"*"})`]=d,u.colName||(l[u.func]=d)}for(const u of this.selectFields)if(u.expr&&u.expr.type==="fn"&&de(u.expr.name)){const d=u.expr.args[0],h=r(c,u.expr.name,d&&d.type==="col"&&d.name!=="*"?d.name:void 0,d);l[u.alias]=h,l[vt(u.expr)]=h}o.push(l)}return o}async attachSelectSubqueries(t){const n=this.selectFields.filter(i=>i.subquery);if(n.length===0||t.length===0)return;const s=new Map;for(const i of n)if(i.subquery&&!this.isSubqueryCorrelated(i.subquery)){const r=await this.evalScalarSubquery(i.subquery);s.set(i,r)}for(const i of t)for(const r of n)s.has(r)?i[r.alias]=s.get(r):r.subquery&&(i[r.alias]=await this.evalScalarSubquery(r.subquery,i))}async executeMaterializedDerivedTable(){let t=await this.sourceSubquery.clone(this.db).toArray();for(const r of this.joins){const o=await new Bt(this.db,r.table).toArray(),a=[];for(const c of t){let l=!1;const u=this.getRowValue(c,r.leftCol);for(const d of o){const h=this.getRowValue(d,r.rightCol);if(this.evalComparisonValues(u,r.op,h)){l=!0;const f={...c};for(const[g,_]of Object.entries(d))f[`${r.table}.${g}`]=_,g in f||(f[g]=_);a.push(f)}}!l&&r.type==="left"&&a.push({...c})}t=a}t=await this.evalFiltersOnRows(t,this.filters),(this.aggExprs.length>0||this.groupKeys.length>0||this.groupCols.length>0)&&(t=this.performInMemoryAggregation(t),this.havingFilters.length>0&&(t=await this.evalFiltersOnRows(t,this.havingFilters)));const s=this.selectFields.some(r=>r.subquery),i=s&&this.orderKeys.some(r=>this.selectFields.some(o=>o.subquery&&(o.alias===r.colName||o.alias===(r.expr?vt(r.expr):void 0))));return i&&await this.attachSelectSubqueries(t),this.orderKeys.length>0&&(t=this.sortAggregatedRows(t)),this.offsetCount!==null&&this.offsetCount>0&&(t=t.slice(this.offsetCount)),this.limitCount!==null&&this.limitCount>=0&&(t=t.slice(0,this.limitCount)),s&&!i&&await this.attachSelectSubqueries(t),this.selectFields.length>0&&(t=t.map(r=>this.projectRow(r))),t}projectRow(t){const n=Object.keys(t);if(this.selectFields.length>0&&n.length===this.selectFields.length&&this.selectFields.every(i=>i.alias in t))return t;const s={};for(const i of this.selectFields){const r=i.alias;if(t[r]!==void 0)s[r]=t[r];else if(i.expr&&t[vt(i.expr)]!==void 0)s[r]=t[vt(i.expr)];else if(i.sourceCol!==void 0&&t[i.sourceCol]!==void 0)s[r]=t[i.sourceCol];else if(i.expr){let o;typeof this.db.getUdf=="function"&&(o=a=>{var c,l;return(l=(c=this.db.getUdf(a))==null?void 0:c.def)==null?void 0:l.call}),s[r]=kt(i.expr,t,o)}else s[r]=null}return s}async explain(){if(this.assertSubqueryDepth(),this.sourceSubquery){const r=this.tryFlatten();if(r)return r.explain();const o=await this.sourceSubquery.clone(this.db).explain(),a=await this.resolveUncorrelatedFilters(this.filters);return{plan:{...o.plan,filters:[...o.plan.filters,...a],orderBy:this.orderKeys.length>0?this.orderKeys:o.plan.orderBy,groupBy:this.groupKeys.length>0?this.groupKeys:this.groupCols.length>0?this.groupCols:o.plan.groupBy,aggregates:this.aggExprs.length>0?this.aggExprs:o.plan.aggregates,having:this.havingFilters.length>0?this.havingFilters:o.plan.having,select:this.selectFields.length>0?this.selectFields:o.plan.select,limit:this.limitCount!==null?this.limitCount:o.plan.limit,offset:this.offsetCount!==null?this.offsetCount:o.plan.offset},bytecodeSize:o.bytecodeSize,instructions:o.instructions,assembly:o.assembly}}const t=await this.resolveUncorrelatedFilters(this.filters.filter(r=>!this.filterContainsCorrelatedSubquery(r))),n=await this.resolveUncorrelatedFilters(this.havingFilters.filter(r=>!this.filterContainsCorrelatedSubquery(r))),s=this.selectFields.filter(r=>!r.subquery),i=s.map(r=>({expr:r.expr??{type:"col",name:r.sourceCol??r.alias},alias:r.alias}));return this.db.explainQuery(this.tableName,t,{joins:this.joins.length>0?this.joins:void 0,orderBy:this.orderKeys.length>0?this.orderKeys:void 0,groupBy:this.groupKeys.length>0?this.groupKeys:this.groupCols.length>0?this.groupCols:void 0,aggregates:this.aggExprs.length>0?this.aggExprs:void 0,having:n.length>0?n:void 0,select:s.length>0?s:void 0,selectExprs:i.length>0?i:void 0,limit:this.limitCount!==null?this.limitCount:void 0,offset:this.offsetCount!==null?this.offsetCount:void 0,planner:this.planner})}getOrderKeyValue(t,n){const s=n.colName??(n.expr?vt(n.expr):void 0);if(!s)return;if(t[s]!==void 0)return t[s];const i=s.includes(".")?s.slice(s.lastIndexOf(".")+1):s;if(t[i]!==void 0)return t[i];if(this.selectFields.length>0){for(const r of this.selectFields)if((r.sourceCol===s||r.sourceCol===i||r.alias===s||r.alias===i)&&t[r.alias]!==void 0)return t[r.alias]}if(t[`__sort_${s}`]!==void 0)return t[`__sort_${s}`];if(t[`__sort_${i}`]!==void 0)return t[`__sort_${i}`];if(n.expr){let r;return typeof this.db.getUdf=="function"&&(r=o=>{var a,c;return(c=(a=this.db.getUdf(o))==null?void 0:a.def)==null?void 0:c.call}),kt(n.expr,t,r)}}sortAggregatedRows(t){return[...t].sort((n,s)=>{for(const i of this.orderKeys){const r=this.getOrderKeyValue(n,i),o=this.getOrderKeyValue(s,i);if(r===o)continue;if(r==null)return i.nullOrder==="nulls_first"?-1:1;if(o==null)return i.nullOrder==="nulls_first"?1:-1;const a=i.direction==="desc"?-1:1;return typeof r=="number"&&typeof o=="number"?(r-o)*a:String(r).localeCompare(String(o))*a}return 0})}async toArray(){if(this.assertSubqueryDepth(),js(this.db,this.getReferencedTables()),this.sourceSubquery){const p=this.tryFlatten();return p?p.toArray():this.executeMaterializedDerivedTable()}const t=this.filters.some(p=>this.filterContainsCorrelatedSubquery(p)),n=this.havingFilters.some(p=>this.filterContainsCorrelatedSubquery(p)),s=this.selectFields.some(p=>p.subquery),i=this.selectFields.some(p=>p.subquery&&this.isSubqueryCorrelated(p.subquery)),r=await this.resolveUncorrelatedFilters(this.filters.filter(p=>!this.filterContainsCorrelatedSubquery(p))),o=this.filters.filter(p=>this.filterContainsCorrelatedSubquery(p)),a=this.joins.length>0,c=this.orderKeys.length>0,l=this.aggExprs.length>0||this.groupKeys.length>0||this.groupCols.length>0;if(t){let p=await this.db.executeQuery(this.tableName,r,{limit:null,offset:null,sortCol:null,sortDir:this.sortDir,joins:a?this.joins:void 0,planner:this.planner});return p=await this.evalFiltersOnRows(p,o),l&&(p=this.performInMemoryAggregation(p),this.havingFilters.length>0&&(p=await this.evalFiltersOnRows(p,this.havingFilters))),s&&await this.attachSelectSubqueries(p),c&&(p=this.sortAggregatedRows(p)),this.offsetCount!==null&&this.offsetCount>0&&(p=p.slice(this.offsetCount)),this.limitCount!==null&&this.limitCount>=0&&(p=p.slice(0,this.limitCount)),this.selectFields.length>0&&(p=p.map(y=>this.projectRow(y))),p}const u=await this.resolveUncorrelatedFilters(this.havingFilters.filter(p=>!this.filterContainsCorrelatedSubquery(p))),d=this.selectFields.filter(p=>!p.subquery),h=d.map(p=>({expr:p.expr??{type:"col",name:p.sourceCol??p.alias},alias:p.alias}));if(a&&c&&h.length>0)for(const p of this.orderKeys){const y=p.colName;if(y){const T=y.includes(".")?y.slice(y.lastIndexOf(".")+1):y;d.some(w=>w.alias===y||w.alias===T||w.sourceCol===y||w.sourceCol===T)||h.push({expr:{type:"col",name:y},alias:`__sort_${y}`})}}const f=!i||l,g=await this.db.executeQuery(this.tableName,r,{limit:a&&c&&l||n?null:this.limitCount,offset:a&&c&&l||n?null:this.offsetCount,sortCol:a?null:this.sortCol,sortDir:this.sortDir,orderBy:a&&l?void 0:c?this.orderKeys:void 0,joins:a?this.joins:void 0,groupBy:this.groupKeys.length>0?this.groupKeys:this.groupCols.length>0?this.groupCols:void 0,aggregates:this.aggExprs.length>0?this.aggExprs:void 0,having:u.length>0?u:void 0,select:f&&d.length>0?d:void 0,selectExprs:f&&h.length>0?h:void 0,planner:this.planner});let _=g;if(n){const p=this.havingFilters.filter(y=>this.filterContainsCorrelatedSubquery(y));_=await this.evalFiltersOnRows(_,p)}const I=g.isOrderSatisfied===!0;return(l||a)&&c&&!I?(_=this.sortAggregatedRows(_),(a||n)&&(this.offsetCount!==null&&this.offsetCount>0&&(_=_.slice(this.offsetCount)),this.limitCount!==null&&this.limitCount>=0&&(_=_.slice(0,this.limitCount)))):n&&(this.offsetCount!==null&&this.offsetCount>0&&(_=_.slice(this.offsetCount)),this.limitCount!==null&&this.limitCount>=0&&(_=_.slice(0,this.limitCount))),s&&await this.attachSelectSubqueries(_),this.selectFields.length>0&&(_=_.map(p=>this.projectRow(p))),_}async first(){const t=await this.limit(1).toArray();return t.length>0?t[0]:null}live(t,n){return Ks(()=>this.clone(this.db).toArray(),t,n)}async update(t,n){if(!this.db.executeUpdate)throw new Error("Database executor does not support executeUpdate");this.assertSubqueryDepth();const s=await this.resolveUncorrelatedFilters(this.filters);return this.db.executeUpdate(this.tableName,s,t,n)}async delete(t){if(!this.db.executeDelete)throw new Error("Database executor does not support executeDelete");this.assertSubqueryDepth();const n=await this.resolveUncorrelatedFilters(this.filters);return this.db.executeDelete(this.tableName,n,t)}}class Un{constructor(t,n,s,i,r="js",o,a,c){N(this,"vfs");N(this,"io");N(this,"driver");N(this,"coreMode");N(this,"wasmCore");N(this,"planner");N(this,"coordinator");N(this,"currentLeaseId",null);N(this,"vmCtx");N(this,"udfs",new Map);N(this,"nextUdfId",1);N(this,"tableMetaCache",new Map);N(this,"tableTailPages",new Map);N(this,"indexTailPages",new Map);N(this,"beforeCommitHooks",new Set);N(this,"commitHooks",new Set);N(this,"subscriptions",new Set);N(this,"activeTxChanges",[]);N(this,"activeTxOrigin","local");N(this,"activeTxMeta");N(this,"activeTxId",0);N(this,"nextAutoTxId",1e6);N(this,"isRunningBeforeCommit",!1);N(this,"broadcastChannel",null);N(this,"instanceId",Math.random().toString(36).slice(2)+Date.now().toString(36));if(this.vfs=t,this.io=n,this.driver=s,this.coordinator=i,this.coreMode=r,this.wasmCore=o,this.planner=a,this.vmCtx=Gr(),this.coordinator.setOnCrossTabInvalidated(async()=>{this.tableMetaCache.clear(),this.tableTailPages.clear(),this.indexTailPages.clear(),await Un.pinAllCatalogPages(this.driver)}),typeof BroadcastChannel<"u"&&c){const l=`webdb_sync_${t.name}_${c}`;this.broadcastChannel=new BroadcastChannel(l),this.broadcastChannel.onmessage=u=>{const d=u.data;if(!d||d.senderId===this.instanceId)return;const{tables:h,origin:f,meta:g,changeCounter:_,schemaVersion:I}=d;this.coordinator.leaseQueue.enqueue(async()=>{await this.coordinator.syncCrossTabState(!0),this.notifySubscriptions({tables:Array.isArray(h)?h:[],origin:f??"remote",meta:g,changeCounter:typeof _=="number"?_:this.getSyncState().changeCounter,schemaVersion:typeof I=="number"?I:this.getSyncState().schemaVersion,crossTab:!0})}).catch(()=>{})}}}get pool(){return this.driver}static async open(t){const n=t.storage||"memory";let s;t.vfs?s=t.vfs:n==="idb"?s=new zr(t.name):n==="opfs"?s=new to(t.name):s=new Jr;const i=t.slotCount??We,r=t.maxQueryMemory??He,o=Xo(Math.max(i,We),r),a=t.core??"js";let c;a==="wasm"&&(c=xo(o,t.wasmBinary?new Uint8Array(t.wasmBinary):void 0));const l=new Li({vfs:s,memory:o}),u=new Yo({io:l,memory:o,slotCount:i,maxQueryMemory:r,useDefaultLayoutOffsets:!0}),d=t.name&&s.name!=="memory"?`webdb_lock_${s.name}_${t.name}`:void 0,h=new jo(s,u,l,d);u.setTransactionCoordinator(h),await h.leaseQueue.enqueue(async()=>{await sr(s);const[g]=await s.readPages([1]);g?(u.getPageBytesInSlot(0).set(g),u.clearDirty(0),Yn(u.getSlotDataView(0),!0),await Un.pinAllCatalogPages(u)):(Bo(u.getSlotDataView(0)),u.markDirty(0),await u.flushSlot(0)),h.recordDiskPage1State()});const f=new Un(s,l,u,h,a,c,t.planner,t.name);return t.initialData&&await f.importBinary(t.initialData),f}static async pinAllCatalogPages(t){const n=t.getSlotDataView(0);let s=n.getUint32(Ge,!0);for(;s!==0;){const o=await t.acquireAndPinPage(s),a=t.getSlotDataView(o);s=ge(a,0).nextColCatalogPageId}let i=n.getUint32(qe,!0);for(;i!==0;){const o=await t.acquireAndPinPage(i),a=t.getSlotDataView(o);i=ge(a,0).nextColCatalogPageId}const r=pn(n);for(const o of r){let a=o.colCatalogPageId;for(;a!==0;){const c=await t.acquireAndPinPage(a),l=t.getSlotDataView(c);a=ge(l,0).nextColCatalogPageId}}}getPlanner(){return this.planner}setPlanner(t){return this.planner=t,this}validateIdentifier(t,n="Identifier"){if(!t||typeof t!="string"||t.length===0)throw new Error(`${n} cannot be empty`);if(t.length>ie)throw new Hr(t,ie)}async createTable(t,n){return this.coordinator.leaseQueue.enqueue(()=>this._createTableInternal(t,n),this.currentLeaseId??void 0)}async _createTableInternal(t,n){var _;if(this.validateIdentifier(t,"Table name"),n.length===0)throw new Error("Table must have at least one column");if(n.length>Ae)throw new Mn(n.length,Ae);const s=new Set;let i=!1;for(const I of n){if(this.validateIdentifier(I.name,"Column name"),s.has(I.name))throw new hs(I.name,t);s.add(I.name);const p=typeof I.flags=="number"?I.flags:0;(I.primaryKey||(_=I.flags)!=null&&_.primaryKey||p&tt.PRIMARY_KEY)&&(i=!0)}const r=this.pool.getSlotDataView(0);if(Zt(r,t)!==-1)throw new gs(t);const o=Ki(r)===-1?1:0,a=Math.ceil(n.length/Ce),c=i?1:0,l=1+a+c+o,u=[];for(let I=0;I<l;I++)u.push(await this.driver.allocateAndPinPage());let d=0;const h={allocateNewPage:()=>{if(d<u.length)return u[d++];const p=r.getUint32(12,!0)+1;return r.setUint32(12,p,!0),this.pool.markDirty(0),p},getPageBytes:I=>{let p=this.pool.getResidentSlot(I);return p===-1&&(p=I<=this.pool.slotCount?I-1:1,this.pool.assignSlot(p,I)),this.pool.getPageBytesInSlot(p)},markPageDirty:I=>{const p=this.pool.getResidentSlot(I);p!==-1&&this.pool.markDirty(p)}};let f;try{f=Vo(r,h,t,n)}catch(I){for(const p of u)this.driver.forceUnpinPage(p),await this.driver.freePage(p,!0);throw I}this.driver.unpinPage(f.rootPageId);for(const I of f.indexes??[])I.rootPageId>1&&this.driver.unpinPage(I.rootPageId);let g=f.colCatalogPageId;for(;g!==0;){const I=await this.driver.acquirePage(g);this.pool.isSlotPinned(I)||this.pool.pinSlot(I),g=ge(this.pool.getSlotDataView(I),0).nextColCatalogPageId}return this.coordinator.isInTransaction()||await this.driver.flushAllDirty(),this.tableMetaCache.delete(t.toLowerCase()),f}async getTable(t){return this.coordinator.leaseQueue.enqueue(()=>this._getTableInternal(t),this.currentLeaseId??void 0)}async _getTableInternal(t){const n=t.toLowerCase(),s=this.tableMetaCache.get(n);if(s)return s;const i=this.pool.getSlotDataView(0),r=Zt(i,t);if(r===-1)throw new kn(t);let a=qt(i,r).colCatalogPageId;for(;a!==0;){await this.driver.acquirePage(a);const u=this.pool.getResidentSlot(a);a=ge(this.pool.getSlotDataView(u),0).nextColCatalogPageId}const l=er(i,{getPageBytes:u=>{const d=this.pool.getResidentSlot(u);return d!==-1?this.pool.getPageBytesInSlot(d):new Uint8Array(4096)}},t);return this.tableMetaCache.set(n,l),l}async listTables(){return this.coordinator.leaseQueue.enqueue(async()=>{const t=this.pool.getSlotDataView(0),n=pn(t),s=[];for(const i of n)s.push(await this._getTableInternal(i.name));return s},this.currentLeaseId??void 0)}async freeTableTreePages(t){if(t<=1)return;const n=[],s=new Set,i=[t];for(;i.length>0;){const r=i.shift();if(r<=1||s.has(r))continue;s.add(r);const o=await this.driver.acquirePage(r),a=this.pool.getSlotDataView(o),c=Xe(a,0);if(c===$e){this.driver.forceUnpinPage(r);continue}if(n.push(r),c===Ci||c===vr){const l=ft(a,0);for(let d=0;d<l;d++){const h=at(a,0,d);if(h>0&&h+4<=4096){const f=a.getUint32(h,!0);f>1&&!s.has(f)&&i.push(f)}}const u=Ut(a,0);u>1&&!s.has(u)&&i.push(u)}else if(c===fs||c===us){const l=Ut(a,0);l>1&&!s.has(l)&&i.push(l)}}for(const r of n)this.driver.forceUnpinPage(r),await this.driver.freePage(r,!0)}async dropTable(t){return this.coordinator.leaseQueue.enqueue(()=>this._dropTableInternal(t),this.currentLeaseId??void 0)}async _dropTableInternal(t){var a;this.tableMetaCache.delete(t.toLowerCase()),this.tableTailPages.delete(t);const n=this.pool.getSlotDataView(0),s=Zt(n,t);if(s===-1)throw new kn(t);const i=qt(n,s);i.pkRootPageId&&i.pkRootPageId>1&&(await this.freeTableTreePages(i.pkRootPageId),this.indexTailPages.delete(i.pkRootPageId));const r=Be(n);for(let c=0;c<r;c++){const l=yn(n,c);l&&(l.tableId===i.tableId||l.name.toLowerCase().startsWith(`idx_${t.toLowerCase()}_`)||l.name.toLowerCase()===`pk_${t.toLowerCase()}`)&&(l.rootPageId>1&&l.rootPageId!==i.pkRootPageId&&(await this.freeTableTreePages(l.rootPageId),this.indexTailPages.delete(l.rootPageId)),zi(n,c))}i.rootPageId>1&&await this.freeTableTreePages(i.rootPageId);let o=i.colCatalogPageId;for(;o>1;){const c=await this.driver.acquirePage(o),l=this.pool.getSlotDataView(c);if(Xe(l,0)===$e){this.driver.forceUnpinPage(o);break}const h=ge(l,0).nextColCatalogPageId;this.driver.forceUnpinPage(o),await this.driver.freePage(o,!0),o=h}qo(n,s),en(n),oe(n),Yt(n),this.pool.markDirty(0),this.coordinator.isInTransaction()||await this.driver.flushAllDirty(),((a=this.vmCtx.table)==null?void 0:a.name.toLowerCase())===t.toLowerCase()&&(this.vmCtx.table=null)}async renameTable(t,n){return this.coordinator.leaseQueue.enqueue(()=>this._renameTableInternal(t,n),this.currentLeaseId??void 0)}async _renameTableInternal(t,n){var u;this.validateIdentifier(n,"Table name");const s=this.pool.getSlotDataView(0),i=Zt(s,t);if(i===-1)throw new kn(t);if(t===n)return this._getTableInternal(n);if(Zt(s,n)!==-1)throw new gs(n);const r=qt(s,i);r.name=n,sn(s,i,r);const o=`pk_${t}`,a=`idx_${t}_`,c=Be(s);for(let d=0;d<c;d++){const h=yn(s,d);if(h&&h.tableId===r.tableId){let f=null;h.name===o?f=`pk_${n}`:h.name.startsWith(a)&&(f=`idx_${n}_${h.name.slice(a.length)}`),f&&f.length<=ie&&!Ms(s,f)&&(h.name=f,Ji(s,d,h))}}en(s),oe(s),Yt(s),this.pool.markDirty(0),this.tableMetaCache.delete(t.toLowerCase()),this.tableMetaCache.delete(n.toLowerCase());const l=this.tableTailPages.get(t);return l!==void 0&&(this.tableTailPages.delete(t),this.tableTailPages.set(n,l)),((u=this.vmCtx.table)==null?void 0:u.name.toLowerCase())===t.toLowerCase()&&(this.vmCtx.table=null),this.coordinator.isInTransaction()||await this.driver.flushAllDirty(),this._getTableInternal(n)}async renameColumn(t,n,s){return this.coordinator.leaseQueue.enqueue(()=>this._renameColumnInternal(t,n,s),this.currentLeaseId??void 0)}async _renameColumnInternal(t,n,s){var g;this.validateIdentifier(s,"Column name");const i=await this._getTableInternal(t),r=i.columns.findIndex(_=>_.name===n);if(r===-1)throw new he(n,t);if(n===s)return i;if(i.columns.some((_,I)=>I!==r&&_.name===s))throw new hs(s,t);const{pageChainIdx:o,colIdxInPage:a}=Ho(r);let c=i.colCatalogPageId;for(let _=0;_<o;_++){const I=await this.driver.acquirePage(c);c=ge(this.pool.getSlotDataView(I),0).nextColCatalogPageId}const l=await this.driver.acquirePage(c),u=this.pool.getSlotDataView(l),d={...i.columns[r],name:s};tr(u,0,a,d);const h=be(this.pool.getPageBytesInSlot(l));u.setUint32(12,h,!0),this.pool.markDirty(l);const f=this.pool.getSlotDataView(0);return en(f),oe(f),Yt(f),this.pool.markDirty(0),this.tableMetaCache.delete(t.toLowerCase()),((g=this.vmCtx.table)==null?void 0:g.name.toLowerCase())===t.toLowerCase()&&(this.vmCtx.table=null),this.coordinator.isInTransaction()||await this.driver.flushAllDirty(),this._getTableInternal(t)}async addColumn(t,n,s){this.validateIdentifier(n.name,"Column name");const i=(s==null?void 0:s.defaultValue)!==void 0?s.defaultValue:n.defaultValue!==void 0?n.defaultValue:null;return this._executeTableRebuildAtomic(t,r=>{var d,h,f;if(r.columns.some(g=>g.name===n.name))throw new hs(n.name,t);if(r.columns.length+1>Ae)throw new Mn(r.columns.length+1,Ae);const o=typeof n.flags=="number"?n.flags:0,a=!!n.primaryKey||!!((d=n.flags)!=null&&d.primaryKey)||(o&tt.PRIMARY_KEY)!==0,c=!!n.autoInc||!!((h=n.flags)!=null&&h.autoInc)||(o&tt.AUTO_INC)!==0,l=!!n.indexed||!!((f=n.flags)!=null&&f.indexed)||(o&tt.INDEXED)!==0;if(a&&r.columns.some(g=>(g.flags&tt.PRIMARY_KEY)!==0))throw new Error(`Cannot add a PRIMARY KEY column "${n.name}" to table "${t}" because it already has a primary key`);return{newColumns:[...r.columns.map(g=>({name:g.name,type:g.type,flags:{primaryKey:(g.flags&tt.PRIMARY_KEY)!==0,notNull:(g.flags&tt.NOT_NULL)!==0,indexed:(g.flags&tt.INDEXED)!==0,autoInc:(g.flags&tt.AUTO_INC)!==0}})),n],transformRow:g=>{const _={...g};return(!c||i!==null)&&(_[n.name]=i),_},keepIndex:()=>!0,newAutoIndexCol:l&&!a?n.name:void 0}})}async dropColumn(t,n){return this.validateIdentifier(n,"Column name"),this._executeTableRebuildAtomic(t,s=>{const i=s.columns.findIndex(a=>a.name===n);if(i===-1)throw new he(n,t);if(s.columns.length<=1)throw new wi(`Cannot drop column "${n}" from table "${t}": table must have at least one column`);if(s.columns[i].flags&tt.PRIMARY_KEY)throw new wi(`Cannot drop PRIMARY KEY column "${n}" from table "${t}"`);return{newColumns:s.columns.filter(a=>a.name!==n).map(a=>({name:a.name,type:a.type,flags:{primaryKey:(a.flags&tt.PRIMARY_KEY)!==0,notNull:(a.flags&tt.NOT_NULL)!==0,indexed:(a.flags&tt.INDEXED)!==0,autoInc:(a.flags&tt.AUTO_INC)!==0}})),transformRow:a=>{const c={...a};return delete c[n],c},keepIndex:a=>!a.includes(n)}})}async alterTable(t,n){switch(n.type){case"renameTable":return this.renameTable(t,n.newName);case"renameColumn":return this.renameColumn(t,n.from,n.to);case"addColumn":return this.addColumn(t,n.column,{defaultValue:n.defaultValue});case"dropColumn":return this.dropColumn(t,n.column);default:throw new Error(`Unsupported alterTable operation: ${n==null?void 0:n.type}`)}}async _executeTableRebuildAtomic(t,n){return this.coordinator.isInTransaction()?this.coordinator.leaseQueue.enqueue(async()=>{const s=await this.coordinator.captureSavepoint();try{return await this._rebuildTableSchemaInternal(t,n)}catch(i){throw this.tableMetaCache.clear(),this.tableTailPages.clear(),this.indexTailPages.clear(),await this.coordinator.restoreSavepoint(s),i}},this.currentLeaseId??void 0):this.transaction(s=>s._rebuildTableSchemaInternal(t,n))}async _rebuildTableSchemaInternal(t,n){const s=await this._getTableInternal(t),{newColumns:i,transformRow:r,keepIndex:o,newAutoIndexCol:a}=n(s),c=[];let l=s.rootPageId;for(;l!==0;){let _=await this.driver.acquirePage(l),I=this.pool.getSlotDataView(_);const p=ft(I,0),y=Ut(I,0);for(let T=0;T<p;T++){_=await this.driver.acquirePage(l),I=this.pool.getSlotDataView(_);const O=at(I,0,T),w=Je(s.columns,I,O);w&&c.push(r(w))}l=y}const u=s.autoIncNext,d=this.pool.getSlotDataView(0),h=le(d,s.tableId),f=[];for(const _ of h){if(_.flags&rt.PRIMARY)continue;const I=_.columnIndices.slice(0,_.columnCount).map(p=>{var y;return(y=s.columns[p])==null?void 0:y.name}).filter(p=>typeof p=="string");I.length===_.columnCount&&o(I)&&f.push({name:_.name,colNames:I,unique:(_.flags&rt.UNIQUE)!==0})}await this._dropTableInternal(t),await this._createTableInternal(t,i);for(const _ of f)await this._createIndexInternal(t,_.colNames,{name:_.name,unique:_.unique});a&&!f.some(_=>_.colNames.length===1&&_.colNames[0]===a)&&await this._createIndexInternal(t,a),c.length>0&&await this._insertManyInternal(t,c,!1);const g=Zt(d,t);if(g!==-1){const _=qt(d,g);u>_.autoIncNext&&(_.autoIncNext=u,sn(d,g,_),Yt(d),this.pool.markDirty(0))}return this.tableMetaCache.delete(t.toLowerCase()),this.coordinator.isInTransaction()||await this.driver.flushAllDirty(),this._getTableInternal(t)}async createIndex(t,n,s){return this.coordinator.leaseQueue.enqueue(()=>this._createIndexInternal(t,n,s),this.currentLeaseId??void 0)}async _createIndexInternal(t,n,s){const i=await this._getTableInternal(t),r=Array.isArray(n)?n:[n];if(r.length===0)throw new Error(`At least one column must be specified for createIndex on table "${t}"`);if(r.length>8)throw new Error(`Maximum 8 columns allowed per index (requested ${r.length})`);const o=[];for(const w of r){const C=i.columns.findIndex(B=>B.name===w);if(C===-1)throw new he(w,t);o.push(C)}const a=(s==null?void 0:s.name)??`idx_${t}_${r.join("_")}`,c=this.pool.getSlotDataView(0);if(Ms(c,a)!==null)throw new Si(a);const d=le(c,i.tableId).find(w=>{if(w.columnCount!==o.length)return!1;for(let C=0;C<w.columnCount;C++)if(w.columnIndices[C]!==o[C])return!1;return!0});if(d)throw new Si(d.name||a);const h=await this.driver.allocateAndPinPage(),f=this.pool.getResidentSlot(h),g=this.pool.getSlotDataView(f);Ls(g,0,0),this.pool.markDirty(f),this.pool.unpinSlot(f);const _=!!(s!=null&&s.unique);let I=i.rootPageId;for(;I!==0;){let w=await this.driver.acquirePage(I),C=this.pool.getSlotDataView(w);const B=ft(C,0),P=Ut(C,0);for(let U=0;U<B;U++){w=await this.driver.acquirePage(I),C=this.pool.getSlotDataView(w);const Q=at(C,0,U),R=Je(i.columns,C,Q);if(R){const A=BigInt(I)<<16n|BigInt(U),{keyVal:b,keyType:k}=this.extractIndexKey(i.columns,{columnCount:o.length,columnIndices:o},R);if(b!=null){if(_&&await this.probeIndexUnique(h,k,b))throw await this.freeTableTreePages(h),this.indexTailPages.delete(h),new ln(`Duplicate key value violates unique constraint "${a}" on table "${t}"`);await this.insertIntoIndex(h,k,b,A)}}}I=P}let p=Mo(c);if(p===-1){const w=await this.driver.allocateAndPinPage();if(p=ko(c,w),p===-1)throw new $r(ii+1,ii);this.pool.markDirty(0)}const y=[0,0,0,0,0,0,0,0],T=[0,0,0,0,0,0,0,0];for(let w=0;w<o.length&&w<8;w++)y[w]=o[w];const O=_?rt.UNIQUE:0;Ji(c,p,{indexId:p+1,tableId:i.tableId,rootPageId:h,columnCount:o.length,flags:O,columnIndices:y,colDirections:T,name:a}),en(c),oe(c),Yt(c),this.pool.markDirty(0),this.tableMetaCache.delete(t.toLowerCase()),this.indexTailPages.delete(h),this.coordinator.isInTransaction()||await this.driver.flushAllDirty()}async dropIndex(t){return this.coordinator.leaseQueue.enqueue(()=>this._dropIndexInternal(t),this.currentLeaseId??void 0)}async _dropIndexInternal(t){const n=this.pool.getSlotDataView(0),s=Ms(n,t);if(!s)throw new Vr(t);if(s.desc.rootPageId>1&&(await this.freeTableTreePages(s.desc.rootPageId),this.indexTailPages.delete(s.desc.rootPageId)),s.slotIdx>=0)zi(n,s.slotIdx);else{const i=-s.slotIdx-1,r=qt(n,i);r&&(r.pkRootPageId=void 0,r.pkColumnCount=void 0,r.pkFlags=void 0,r.pkColumnIndices=void 0,sn(n,i,r))}en(n),oe(n),Yt(n),this.pool.markDirty(0),this.tableMetaCache.clear(),this.indexTailPages.clear(),this.coordinator.isInTransaction()||await this.driver.flushAllDirty()}async listIndexes(t){return this.coordinator.leaseQueue.enqueue(async()=>{const n=this.pool.getSlotDataView(0);if(t){const s=await this._getTableInternal(t);return le(n,s.tableId)}return Go(n)},this.currentLeaseId??void 0)}extractIndexKey(t,n,s){if(n.columnCount===1){const i=t[n.columnIndices[0]];return{keyVal:s[i.name],keyType:i.type}}return{keyVal:Rs(t,n.columnIndices,n.columnCount,s),keyType:S.BLOB}}async probeIndexUnique(t,n,s,i){let r=t;for(;r!==0;){const o=await this.driver.acquirePage(r),a=this.pool.getSlotDataView(o);if(ft(a,0)>0){const l=Vn(a,0,n,s);if(l.found){const u=at(a,0,l.slot_idx),d=a.getUint16(u,!0),h=a.getBigInt64(u+2+d,!0);if(!i||!i.has(h))return!0}}r=Ut(a,0)}return!1}async deleteFromIndex(t,n,s,i){let r=t;for(;r!==0;){const o=await this.driver.acquirePage(r),a=this.pool.getSlotDataView(o);if(ft(a,0)>0){const l=Vn(a,0,n,s,i);if(l.found)return go(a,0,l.slot_idx),this.pool.markDirty(o),!0}r=Ut(a,0)}return!1}async insertIntoIndex(t,n,s,i){let r=this.indexTailPages.get(t)??t,o=await this.driver.acquirePage(r),a=this.pool.getSlotDataView(o);for(;;){const l=Ut(a,0);if(l===0)break;r=l,o=await this.driver.acquirePage(r),a=this.pool.getSlotDataView(o)}this.indexTailPages.set(t,r);let c=Gi(a,0,n,s,i,this.pool.pageScratchpadOffset);if(c===-1){this.pool.pinSlot(o);try{const l=await this.driver.allocateAndPinPage(),u=this.pool.getResidentSlot(l);try{Us(a,0,l),this.pool.markDirty(o);const d=this.pool.getSlotDataView(u);if(Ls(d,0,0),c=Gi(d,0,n,s,i,this.pool.pageScratchpadOffset),c===-1)throw new Error("Unexpected error: index entry does not fit in empty page");this.pool.markDirty(u),this.indexTailPages.set(t,l)}finally{this.pool.unpinSlot(u)}}finally{this.pool.unpinSlot(o)}}else this.pool.markDirty(o)}cloneRow(t){const n={};for(const[s,i]of Object.entries(t))n[s]=i instanceof Uint8Array?i.slice():i;return n}valuesEqual(t,n){if(t===n||t==null&&n==null)return!0;if(t instanceof Uint8Array&&n instanceof Uint8Array){if(t.byteLength!==n.byteLength)return!1;for(let s=0;s<t.byteLength;s++)if(t[s]!==n[s])return!1;return!0}return typeof t=="number"&&typeof n=="bigint"||typeof t=="bigint"&&typeof n=="number"?BigInt(t)===BigInt(n):typeof t=="boolean"&&typeof n=="number"||typeof t=="number"&&typeof n=="boolean"?Number(t)===Number(n):!1}extractPrimaryKey(t,n){const s=t.columns.filter(i=>(i.flags&tt.PRIMARY_KEY)!==0);return s.length===1?n[s[0].name]??null:s.length>1?s.map(i=>n[i.name]??null):t.columns.length===1?n[t.columns[0].name]??null:t.columns.map(i=>n[i.name]??null)}serializePkKey(t){const n=s=>s==null?"null":s instanceof Uint8Array?`b:${Array.from(s).join(",")}`:`${typeof s}:${String(s)}`;return Array.isArray(t)?`[${t.map(n).join("|")}]`:t!==null&&typeof t=="object"&&!(t instanceof Uint8Array)?`{${Object.keys(t).sort().map(i=>`${i}:${n(t[i])}`).join("|")}}`:n(t)}buildChangeset(t,n,s,i){const{changeCounter:r,schemaVersion:o}=this.getSyncState(),a=Array.from(new Set(i.map(c=>c.table)));return{txId:t,origin:n,meta:s,changeCounter:r,schemaVersion:o,tables:a,changes:i,coalesced:()=>{const c=new Map;for(const l of i){const u=`${l.table.toLowerCase()}::${this.serializePkKey(l.pk)}`,d=c.get(u);if(!d){c.set(u,{table:l.table,op:l.op,pk:Array.isArray(l.pk)?[...l.pk]:l.pk,oldRow:l.oldRow?this.cloneRow(l.oldRow):void 0,newRow:l.newRow?this.cloneRow(l.newRow):void 0,changedColumns:l.changedColumns?[...l.changedColumns]:void 0});continue}if(d.op==="insert"&&l.op==="update")c.set(u,{table:l.table,op:"insert",pk:Array.isArray(l.pk)?[...l.pk]:l.pk,newRow:l.newRow?this.cloneRow(l.newRow):d.newRow});else if(d.op==="insert"&&l.op==="delete")c.delete(u);else if(d.op==="update"&&l.op==="update"){const h=d.oldRow,f=l.newRow?this.cloneRow(l.newRow):d.newRow,g=Object.keys(f).filter(_=>!this.valuesEqual(h[_],f[_]));c.set(u,{table:l.table,op:"update",pk:Array.isArray(l.pk)?[...l.pk]:l.pk,oldRow:h,newRow:f,changedColumns:g})}else if(d.op==="update"&&l.op==="delete")c.set(u,{table:l.table,op:"delete",pk:Array.isArray(d.pk)?[...d.pk]:d.pk,oldRow:d.oldRow});else if(d.op==="delete"&&l.op==="insert"){const h=d.oldRow,f=l.newRow?this.cloneRow(l.newRow):{},g=Object.keys(f).filter(_=>!this.valuesEqual(h[_],f[_]));c.set(u,{table:l.table,op:"update",pk:Array.isArray(l.pk)?[...l.pk]:l.pk,oldRow:h,newRow:f,changedColumns:g})}else c.set(u,{table:l.table,op:l.op,pk:Array.isArray(l.pk)?[...l.pk]:l.pk,oldRow:l.oldRow?this.cloneRow(l.oldRow):void 0,newRow:l.newRow?this.cloneRow(l.newRow):void 0,changedColumns:l.changedColumns?[...l.changedColumns]:void 0})}return Array.from(c.values())}}}notifySubscriptions(t){if(t.tables.length===0||this.subscriptions.size===0)return;const n=new Set(t.tables.map(s=>s.toLowerCase()));for(const s of this.subscriptions)if(s.tables==="*")s.callback(t);else for(const i of n)if(s.tables.has(i)){s.callback(t);break}}emitCommitAndSubscriptions(t){if(t.changes.length===0)return;for(const r of this.commitHooks)r(t);const n=t.tables,{changeCounter:s,schemaVersion:i}=t;if(this.notifySubscriptions({tables:n,origin:t.origin,meta:t.meta,changeCounter:s,schemaVersion:i,crossTab:!1,changeset:t}),this.broadcastChannel)try{this.broadcastChannel.postMessage({senderId:this.instanceId,tables:n,origin:t.origin,meta:t.meta,changeCounter:s,schemaVersion:i})}catch{}}onBeforeCommit(t){return this.beforeCommitHooks.add(t),()=>{this.beforeCommitHooks.delete(t)}}onCommit(t){return this.commitHooks.add(t),()=>{this.commitHooks.delete(t)}}subscribe(t,n){const s={tables:t==="*"?"*":new Set((Array.isArray(t)?t:[t]).map(i=>i.toLowerCase())),callback:n};return this.subscriptions.add(s),()=>{this.subscriptions.delete(s)}}liveQuery(t,n,s){const i=typeof n=="function",r={db:this,...i?s:n};return i?Ks(t,n,r):Ks(t,r)}getSyncState(){const t=this.pool.getSlotDataView(0),n=Yn(t,!1);return{changeCounter:n.changeCounter,schemaVersion:n.schemaVersion}}validateFilterColumns(t,n){const s=new Set(t.columns.map(o=>o.name)),i=o=>{if(o){if(o.type==="col"&&o.name!=="*"){if(!s.has(o.name))throw new he(o.name,t.name)}else if(o.type==="binary")i(o.left),i(o.right);else if(o.type==="fn"&&Array.isArray(o.args))for(const a of o.args)i(a)}},r=o=>{if(o.colName&&!s.has(o.colName))throw new he(o.colName,t.name);if(o.expr&&i(o.expr),o.child&&r(o.child),o.children)for(const a of o.children)r(a)};for(const o of n)r(o)}matchesFilter(t,n,s){switch(s.type){case"and":return(s.children??[]).every(i=>this.matchesFilter(t,n,i));case"or":return(s.children??[]).some(i=>this.matchesFilter(t,n,i));case"not":return s.child?!this.matchesFilter(t,n,s.child):!0;case"null":{const i=s.expr?kt(s.expr,n,o=>{var a;return(a=this.getUdf(o))==null?void 0:a.def.call}):n[s.colName],r=i==null;return s.isNull?r:!r}case"in":{const i=s.expr?kt(s.expr,n,a=>{var c;return(c=this.getUdf(a))==null?void 0:c.def.call}):n[s.colName];if(i==null)return!1;const o=(s.values??[]).some(a=>this.valuesEqual(i,a));return s.notIn?!o:o}case"expr":{if(!s.expr)return!0;const i=kt(s.expr,n,r=>{var o;return(o=this.getUdf(r))==null?void 0:o.def.call});return!!i&&i!==0}case"cmp":{const i=s.expr?kt(s.expr,n,a=>{var c;return(c=this.getUdf(a))==null?void 0:c.def.call}):n[s.colName],r=s.value;if(i==null||r===null||r===void 0)return!1;switch(String(s.op??"=").trim().toLowerCase().replace(/\s+/g," ")){case"=":case"==":return this.valuesEqual(i,r);case"!=":case"<>":return!this.valuesEqual(i,r);case"<":return typeof i=="string"&&typeof r=="string"?i<r:Number(i)<Number(r);case"<=":return typeof i=="string"&&typeof r=="string"?i<=r:Number(i)<=Number(r);case">":return typeof i=="string"&&typeof r=="string"?i>r:Number(i)>Number(r);case">=":return typeof i=="string"&&typeof r=="string"?i>=r:Number(i)>=Number(r);case"like":return ze(String(i),String(r));case"not like":return!ze(String(i),String(r));case"contains":return String(i).includes(String(r));case"starts_with":return String(i).startsWith(String(r));case"ends_with":return String(i).endsWith(String(r));default:return this.valuesEqual(i,r)}}default:return!0}}matchesFilters(t,n,s){for(const i of s)if(!this.matchesFilter(t,n,i))return!1;return!0}async deleteCellsOnDataPageAndShiftIndexes(t,n,s,i,r){if(i.length===0)return;const o=new Set(i);if(n.length>0){for(const u of i){const d=r[u];if(!d)continue;const h=BigInt(s)<<16n|BigInt(u);for(const f of n){const{keyVal:g,keyType:_}=this.extractIndexKey(t.columns,f,d.row);g!=null&&await this.deleteFromIndex(f.rootPageId,_,g,h)}}let l=0;for(let u=0;u<r.length;u++)if(!o.has(u)){if(l!==u){const d=r[u].row,h=BigInt(s)<<16n|BigInt(u),f=BigInt(s)<<16n|BigInt(l);for(const g of n){const{keyVal:_,keyType:I}=this.extractIndexKey(t.columns,g,d);_!=null&&(await this.deleteFromIndex(g.rootPageId,I,_,h),await this.insertIntoIndex(g.rootPageId,I,_,f))}}l++}}const a=await this.driver.acquirePage(s),c=this.pool.getSlotDataView(a);for(let l=i.length-1;l>=0;l--)uo(c,0,i[l]);this.pool.markDirty(a)}normalizeWhereOrPkFilters(t,n){if(n!==null&&typeof n=="object"&&!(n instanceof Uint8Array)){const i=[];for(const[r,o]of Object.entries(n))o!==void 0&&(o===null?i.push({type:"null",colName:r,isNull:!0}):i.push({type:"cmp",colName:r,op:"=",value:o}));return i}const s=t.columns.find(i=>(i.flags&tt.PRIMARY_KEY)!==0);if(!s)throw new Error(`Table "${t.name}" does not have a primary key column for scalar lookup`);return[{type:"cmp",colName:s.name,op:"=",value:n}]}async insert(t,n,s){await this.insertMany(t,[n],s)}async insertMany(t,n,s){if(!(!n||n.length===0)){if(!this.coordinator.isInTransaction()&&this.beforeCommitHooks.size>0){await this.transaction(async i=>{await i._insertManyInternal(t,n,!0)},s);return}return this.coordinator.leaseQueue.enqueue(async()=>{const i=this.coordinator.isInTransaction(),r=await this._insertManyInternal(t,n,!0);if(!i&&r.length>0){const o=this.buildChangeset(this.nextAutoTxId++,(s==null?void 0:s.origin)??"local",s==null?void 0:s.meta,r);this.emitCommitAndSubscriptions(o)}},this.currentLeaseId??void 0)}}async _insertManyInternal(t,n,s=!0){if(!n||n.length===0)return[];const i=await this._getTableInternal(t),r=this.pool.getSlotDataView(0),o=le(r,i.tableId),a=o.filter(p=>(p.flags&(rt.UNIQUE|rt.PRIMARY))!==0),c=i.columns.find(p=>(p.flags&tt.AUTO_INC)!==0),l=new Map;for(const p of a)l.set(p.name,new Set);let u=i.autoIncNext;const d=[];for(let p=0;p<n.length;p++){const y=n[p];for(const C of i.columns)if(C.flags&tt.PRIMARY_KEY&&!(C.flags&tt.AUTO_INC)&&(y[C.name]===void 0||y[C.name]===null))throw new As(C.name,t);let T;const O={};for(const C of i.columns)y[C.name]!==void 0?O[C.name]=y[C.name]:O[C.name]=null;c&&(y[c.name]===void 0||y[c.name]===null)&&(T=Number(u),u+=1n,O[c.name]=T);for(const C of a){const{keyVal:B,keyType:P}=this.extractIndexKey(i.columns,C,O);if(B!=null){const U=B instanceof Uint8Array?Array.from(B).join(","):B,Q=l.get(C.name);if(Q.has(U))throw new ln(`Duplicate key value violates unique constraint "${C.name}" on table "${t}"`);if(Q.add(U),await this.probeIndexUnique(C.rootPageId,P,B))throw new ln(`Duplicate key value violates unique constraint "${C.name}" on table "${t}"`)}}const w=bs(i.columns,O);d.push({row:y,effectiveRow:O,rowBytes:w,assignedAutoInc:T})}i.autoIncNext=u;let h=this.tableTailPages.get(t)??i.rootPageId,f=await this.driver.acquirePage(h),g=this.pool.getSlotDataView(f);for(;;){const p=Ut(g,0);if(p===0)break;h=p,f=await this.driver.acquirePage(h),g=this.pool.getSlotDataView(f)}this.tableTailPages.set(t,h);const _=[];for(let p=0;p<d.length;p++){const{row:y,effectiveRow:T,rowBytes:O,assignedAutoInc:w}=d[p];c&&w!==void 0&&(y[c.name]=w),f=await this.driver.acquirePage(h),g=this.pool.getSlotDataView(f);let C=h,B=gn(g,0,O,this.pool.pageScratchpadOffset);if(B===-1){const U=f;this.pool.pinSlot(U);try{const Q=await this.driver.allocateAndPinPage(),R=this.pool.getResidentSlot(Q);try{Us(g,0,Q),this.pool.markDirty(U);const A=this.pool.getSlotDataView(R);if(B=gn(A,0,O,this.pool.pageScratchpadOffset),B===-1)throw new Error("Unexpected error: row does not fit in empty page");this.pool.markDirty(R),h=Q,C=Q,f=R,g=A,this.tableTailPages.set(t,Q)}finally{this.pool.unpinSlot(R)}}finally{this.pool.unpinSlot(U)}}else this.pool.markDirty(f);const P=BigInt(C)<<16n|BigInt(B);for(const U of o){const{keyVal:Q,keyType:R}=this.extractIndexKey(i.columns,U,T);Q!=null&&await this.insertIntoIndex(U.rootPageId,R,Q,P)}if(s){const U={table:i.name,op:"insert",pk:this.extractPrimaryKey(i,T),newRow:this.cloneRow(T)};_.push(U),this.coordinator.isInTransaction()&&this.activeTxChanges.push(U)}}const I=Zt(r,t);if(I!==-1){const p=qt(r,I);p.rowCountEstimate+=n.length,c&&(p.autoIncNext=i.autoIncNext),sn(r,I,p),oe(r),Yt(r),this.pool.markDirty(0)}return this.coordinator.isInTransaction()||await this.driver.flushAllDirty(),_}async update(t,n,s,i){return!this.coordinator.isInTransaction()&&this.beforeCommitHooks.size>0?this.transaction(r=>r.update(t,n,s,i),i):this.coordinator.leaseQueue.enqueue(async()=>{const r=await this._getTableInternal(t),o=this.normalizeWhereOrPkFilters(r,n),a=this.coordinator.isInTransaction(),{count:c,changes:l}=await this._executeUpdateInternal(t,o,s);if(!a&&l.length>0){const u=this.buildChangeset(this.nextAutoTxId++,(i==null?void 0:i.origin)??"local",i==null?void 0:i.meta,l);this.emitCommitAndSubscriptions(u)}return c},this.currentLeaseId??void 0)}async executeUpdate(t,n,s,i){return!this.coordinator.isInTransaction()&&this.beforeCommitHooks.size>0?this.transaction(r=>r.executeUpdate(t,n,s,i),i):this.coordinator.leaseQueue.enqueue(async()=>{const r=this.coordinator.isInTransaction(),{count:o,changes:a}=await this._executeUpdateInternal(t,n,s);if(!r&&a.length>0){const c=this.buildChangeset(this.nextAutoTxId++,(i==null?void 0:i.origin)??"local",i==null?void 0:i.meta,a);this.emitCommitAndSubscriptions(c)}return o},this.currentLeaseId??void 0)}async _executeUpdateInternal(t,n,s){const i=await this._getTableInternal(t);this.validateFilterColumns(i,n);const r=new Map(i.columns.map(_=>[_.name,_]));for(const _ of Object.keys(s))if(!r.has(_))throw new he(_,t);const o=this.pool.getSlotDataView(0),a=le(o,i.tableId),c=a.filter(_=>(_.flags&(rt.UNIQUE|rt.PRIMARY))!==0),l=[],u=new Set;let d=0,h=i.rootPageId;for(;h!==0;){const _=await this.driver.acquirePage(h),I=this.pool.getSlotDataView(_),p=ft(I,0),y=Ut(I,0),T=[],O=[];for(let w=0;w<p;w++){const C=at(I,0,w),B=Je(i.columns,I,C);if(T.push({cellIdx:w,row:B}),this.matchesFilters(i,B,n)){const P={...B};for(const[R,A]of Object.entries(s))A!==void 0&&(P[R]=A);for(const R of i.columns)if(R.flags&tt.PRIMARY_KEY&&(P[R.name]===null||P[R.name]===void 0))throw new As(R.name,t);const U=i.columns.map(R=>R.name).filter(R=>!this.valuesEqual(B[R],P[R])),Q=bs(i.columns,P);O.push({cellIdx:w,oldRow:B,newRow:P,changedColumns:U,newRowBytes:Q}),u.add(BigInt(h)<<16n|BigInt(w)),d++}}O.length>0&&l.push({pageId:h,allCells:T,matches:O}),h=y}if(d===0)return{count:0,changes:[]};for(const _ of c){const I=new Set;for(const p of l)for(const y of p.matches){const{keyVal:T,keyType:O}=this.extractIndexKey(i.columns,_,y.newRow);if(T!=null){const w=T instanceof Uint8Array?Array.from(T).join(","):T;if(I.has(w))throw new ln(`Duplicate key value violates unique constraint "${_.name}" on table "${t}"`);if(I.add(w),await this.probeIndexUnique(_.rootPageId,O,T,u))throw new ln(`Duplicate key value violates unique constraint "${_.name}" on table "${t}"`)}}}const f=[],g=[];for(const _ of l){const I=[];for(const p of _.matches){const y=await this.driver.acquirePage(_.pageId),T=this.pool.getSlotDataView(y);if(ki(T,0,p.cellIdx,p.newRowBytes,this.pool.pageScratchpadOffset)){this.pool.markDirty(y),_.allCells[p.cellIdx].row=p.newRow;const w=BigInt(_.pageId)<<16n|BigInt(p.cellIdx);for(const B of a){const P=this.extractIndexKey(i.columns,B,p.oldRow),U=this.extractIndexKey(i.columns,B,p.newRow);this.valuesEqual(P.keyVal,U.keyVal)||(P.keyVal!==void 0&&P.keyVal!==null&&await this.deleteFromIndex(B.rootPageId,P.keyType,P.keyVal,w),U.keyVal!==void 0&&U.keyVal!==null&&await this.insertIntoIndex(B.rootPageId,U.keyType,U.keyVal,w))}const C={table:i.name,op:"update",pk:this.extractPrimaryKey(i,p.newRow),oldRow:this.cloneRow(p.oldRow),newRow:this.cloneRow(p.newRow),changedColumns:p.changedColumns};f.push(C),this.coordinator.isInTransaction()&&this.activeTxChanges.push(C)}else I.push(p.cellIdx),g.push(p)}I.length>0&&await this.deleteCellsOnDataPageAndShiftIndexes(i,a,_.pageId,I,_.allCells)}if(g.length>0){let _=this.tableTailPages.get(t)??i.rootPageId,I=await this.driver.acquirePage(_),p=this.pool.getSlotDataView(I);for(;;){const y=Ut(p,0);if(y===0)break;_=y,I=await this.driver.acquirePage(_),p=this.pool.getSlotDataView(I)}this.tableTailPages.set(t,_);for(const y of g){I=await this.driver.acquirePage(_),p=this.pool.getSlotDataView(I);let T=_,O=gn(p,0,y.newRowBytes,this.pool.pageScratchpadOffset);if(O===-1){const B=I;this.pool.pinSlot(B);try{const P=await this.driver.allocateAndPinPage(),U=this.pool.getResidentSlot(P);try{Us(p,0,P),this.pool.markDirty(B);const Q=this.pool.getSlotDataView(U);O=gn(Q,0,y.newRowBytes,this.pool.pageScratchpadOffset),this.pool.markDirty(U),_=P,T=P,this.tableTailPages.set(t,P)}finally{this.pool.unpinSlot(U)}}finally{this.pool.unpinSlot(B)}}else this.pool.markDirty(I);const w=BigInt(T)<<16n|BigInt(O);for(const B of a){const{keyVal:P,keyType:U}=this.extractIndexKey(i.columns,B,y.newRow);P!=null&&await this.insertIntoIndex(B.rootPageId,U,P,w)}const C={table:i.name,op:"update",pk:this.extractPrimaryKey(i,y.newRow),oldRow:this.cloneRow(y.oldRow),newRow:this.cloneRow(y.newRow),changedColumns:y.changedColumns};f.push(C),this.coordinator.isInTransaction()&&this.activeTxChanges.push(C)}}return oe(o),Yt(o),this.pool.markDirty(0),this.coordinator.isInTransaction()||await this.driver.flushAllDirty(),{count:d,changes:f}}async delete(t,n,s){return!this.coordinator.isInTransaction()&&this.beforeCommitHooks.size>0?this.transaction(i=>i.delete(t,n,s),s):this.coordinator.leaseQueue.enqueue(async()=>{const i=await this._getTableInternal(t),r=this.normalizeWhereOrPkFilters(i,n),o=this.coordinator.isInTransaction(),{count:a,changes:c}=await this._executeDeleteInternal(t,r);if(!o&&c.length>0){const l=this.buildChangeset(this.nextAutoTxId++,(s==null?void 0:s.origin)??"local",s==null?void 0:s.meta,c);this.emitCommitAndSubscriptions(l)}return a},this.currentLeaseId??void 0)}async executeDelete(t,n,s){return!this.coordinator.isInTransaction()&&this.beforeCommitHooks.size>0?this.transaction(i=>i.executeDelete(t,n,s),s):this.coordinator.leaseQueue.enqueue(async()=>{const i=this.coordinator.isInTransaction(),{count:r,changes:o}=await this._executeDeleteInternal(t,n);if(!i&&o.length>0){const a=this.buildChangeset(this.nextAutoTxId++,(s==null?void 0:s.origin)??"local",s==null?void 0:s.meta,o);this.emitCommitAndSubscriptions(a)}return r},this.currentLeaseId??void 0)}async _executeDeleteInternal(t,n){const s=await this._getTableInternal(t);this.validateFilterColumns(s,n);const i=this.pool.getSlotDataView(0),r=le(i,s.tableId),o=[];let a=0,c=s.rootPageId;for(;c!==0;){const u=await this.driver.acquirePage(c),d=this.pool.getSlotDataView(u),h=ft(d,0),f=Ut(d,0);if(h>0){const g=[],_=[];for(let I=0;I<h;I++){const p=at(d,0,I),y=Je(s.columns,d,p);if(g.push({cellIdx:I,row:y}),this.matchesFilters(s,y,n)){_.push(I);const T={table:s.name,op:"delete",pk:this.extractPrimaryKey(s,y),oldRow:this.cloneRow(y)};o.push(T),this.coordinator.isInTransaction()&&this.activeTxChanges.push(T)}}_.length>0&&(a+=_.length,await this.deleteCellsOnDataPageAndShiftIndexes(s,r,c,_,g))}c=f}if(a===0)return{count:0,changes:[]};const l=Zt(i,t);if(l!==-1){const u=qt(i,l);u.rowCountEstimate=Math.max(0,u.rowCountEstimate-a),sn(i,l,u)}return oe(i),Yt(i),this.pool.markDirty(0),this.coordinator.isInTransaction()||await this.driver.flushAllDirty(),{count:a,changes:o}}async upsert(t,n,s){const i=await this.upsertMany(t,[n],s);return i.inserted>0?"inserted":i.updated>0?"updated":"ignored"}async upsertMany(t,n,s){return!n||n.length===0?{inserted:0,updated:0,ignored:0}:!this.coordinator.isInTransaction()&&(this.beforeCommitHooks.size>0||n.length>1)?this.transaction(i=>i._upsertManyInLease(t,n,s),s):this.coordinator.leaseQueue.enqueue(async()=>{const i=this.coordinator.isInTransaction(),r=[],o=await this._upsertManyInLease(t,n,s,i?void 0:r);if(!i&&r.length>0){const a=this.buildChangeset(this.nextAutoTxId++,(s==null?void 0:s.origin)??"local",s==null?void 0:s.meta,r);this.emitCommitAndSubscriptions(a)}return o},this.currentLeaseId??void 0)}async _upsertManyInLease(t,n,s,i){const r=await this._getTableInternal(t),o=new Set(r.columns.map(h=>h.name));let a;if(s!=null&&s.conflictTarget){a=Array.isArray(s.conflictTarget)?s.conflictTarget:[s.conflictTarget];for(const h of a)if(!o.has(h))throw new he(h,t)}else if(a=r.columns.filter(h=>(h.flags&tt.PRIMARY_KEY)!==0).map(h=>h.name),a.length===0)throw new Error(`Cannot upsert on table "${t}" without a primary key or explicit conflictTarget`);const c=(s==null?void 0:s.mode)??"merge";let l=0,u=0,d=0;for(const h of n){for(const I of Object.keys(h))if(!o.has(I))throw new he(I,t);const f=a.every(I=>h[I]!==void 0&&h[I]!==null);let g=null,_=[];if(f&&(_=a.map(I=>({type:"cmp",colName:I,op:"=",value:h[I]})),g=await this.findFirstMatchingRow(r,_)),g){if(c==="ignore"){d++;continue}if(s!=null&&s.where&&!s.where(this.cloneRow(g),this.cloneRow(h))){d++;continue}const I={};if(c==="replace")for(const y of r.columns)h[y.name]!==void 0?I[y.name]=h[y.name]:y.flags&tt.PRIMARY_KEY?I[y.name]=g[y.name]:I[y.name]=null;else for(const[y,T]of Object.entries(h))T!==void 0&&(I[y]=T);const{changes:p}=await this._executeUpdateInternal(t,_,I);i&&i.push(...p),u++}else{const I=await this._insertManyInternal(t,[h],!0);i&&i.push(...I),l++}}return{inserted:l,updated:u,ignored:d}}async findFirstMatchingRow(t,n){let s=t.rootPageId;for(;s!==0;){const i=await this.driver.acquirePage(s),r=this.pool.getSlotDataView(i),o=ft(r,0),a=Ut(r,0);for(let c=0;c<o;c++){const l=at(r,0,c),u=Je(t.columns,r,l);if(this.matchesFilters(t,u,n))return u}s=a}return null}async transaction(t,n){const s=await this.coordinator.begin(),i=s.leaseId;this.activeTxChanges=[],this.activeTxOrigin=(n==null?void 0:n.origin)??"local",this.activeTxMeta=n==null?void 0:n.meta,this.activeTxId=s.txId;const r=new Proxy(this,{get:(o,a,c)=>{if(a==="currentLeaseId")return i;if(a==="transaction")return async(u,d)=>{const h=await this.coordinator.captureSavepoint(),f=this.activeTxChanges.length;try{return await u(r)}catch(g){throw this.activeTxChanges.length=f,this.tableMetaCache.clear(),this.tableTailPages.clear(),this.indexTailPages.clear(),await this.coordinator.restoreSavepoint(h),g}};if(a==="checkpoint")return()=>this.checkpoint();if(a==="from")return u=>{const d=new Bt(r,u);return o.planner&&d.withPlanner(o.planner),d};const l=Reflect.get(o,a,c);return typeof l=="function"?l.bind(r):l}});try{const o=await t(r);if(this.activeTxChanges.length>0&&this.beforeCommitHooks.size>0&&!this.isRunningBeforeCommit){const d=this.buildChangeset(this.activeTxId,this.activeTxOrigin,this.activeTxMeta,[...this.activeTxChanges]);this.isRunningBeforeCommit=!0;try{for(const h of this.beforeCommitHooks)await h(d,r)}finally{this.isRunningBeforeCommit=!1}}const a=[...this.activeTxChanges],c=this.activeTxOrigin,l=this.activeTxMeta,u=this.activeTxId;if(this.activeTxChanges=[],this.activeTxOrigin="local",this.activeTxMeta=void 0,await this.coordinator.commit(i),a.length>0){const d=this.buildChangeset(u,c,l,a);this.emitCommitAndSubscriptions(d)}return o}catch(o){throw this.activeTxChanges=[],this.activeTxOrigin="local",this.activeTxMeta=void 0,this.isRunningBeforeCommit=!1,this.tableMetaCache.clear(),this.tableTailPages.clear(),this.indexTailPages.clear(),await this.coordinator.rollback(i),o}}registerFunction(t,n){const s=t.toLowerCase(),i=typeof n=="function"?{call:n}:{...n};if(!i.returnType)try{const o=i.call(1,1,1,1,1);typeof o=="number"?i.returnType=Number.isInteger(o)?S.INT32:S.FLOAT64:typeof o=="string"&&(i.returnType=S.TEXT)}catch{try{const o=i.call("","","","","");typeof o=="number"?i.returnType=Number.isInteger(o)?S.INT32:S.FLOAT64:typeof o=="string"&&(i.returnType=S.TEXT)}catch{}}let r=this.udfs.get(s);return r?r.def=i:(r={id:this.nextUdfId++,def:i},this.udfs.set(s,r)),this}getUdf(t){return this.udfs.get(t.toLowerCase())}getUdfMap(){const t=new Map;for(const[n,s]of this.udfs.entries())t.set(n,s.id);return t}getUdfDefs(){const t=new Map;for(const[n,s]of this.udfs.entries())t.set(n,s.def);return t}from(t){return new Bt(this,t)}async explainQuery(t,n,s){return this.coordinator.leaseQueue.enqueue(()=>this._explainQueryInternal(t,n,s),this.currentLeaseId??void 0)}async _explainQueryInternal(t,n,s){var I,p,y;const i=await this._getTableInternal(t),r=[];if(s!=null&&s.joins&&s.joins.length>0){if(1+s.joins.length>16)throw new ds(1+s.joins.length,16);for(let T=0;T<s.joins.length;T++){const O=s.joins[T],w=await this._getTableInternal(O.table);r.push({type:O.type,table:w,cursor:T+1,leftCol:O.leftCol,op:O.op,rightCol:O.rightCol})}}const o=dr({table:i,joinedTables:r.length>0?r:void 0,filters:n,orderBy:s==null?void 0:s.orderBy,groupBy:s==null?void 0:s.groupBy,aggregates:s==null?void 0:s.aggregates,having:s==null?void 0:s.having,selectExprs:s==null?void 0:s.selectExprs,udfNameMap:this.getUdfMap(),udfDefs:this.getUdfDefs(),limit:s==null?void 0:s.limit,offset:s==null?void 0:s.offset,planner:(s==null?void 0:s.planner)??this.planner}),c=(o.allTables??(r.length>0?[i,...r.map(T=>T.table)]:[i]))[0],l=fa(o,c),u=Aa(l),d=o.indexScan??o.table0Scan,h=d?"IndexScan":"TableScan",f=d?d.index.name:void 0,g=o.joinedTableScans,_=(I=s==null?void 0:s.joins)==null?void 0:I.map(T=>{const O=g==null?void 0:g.find(w=>w.tableName.toLowerCase()===T.table.toLowerCase());return O&&O.scanType==="IndexScan"?{...T,scanType:O.scanType,indexName:O.indexName}:T});return{plan:{table:c.name,rootPageId:c.rootPageId,scanType:h,indexName:f,filters:n,orderBy:s==null?void 0:s.orderBy,groupBy:s==null?void 0:s.groupBy,aggregates:s==null?void 0:s.aggregates,having:s==null?void 0:s.having,select:s==null?void 0:s.select,joins:_,limit:s==null?void 0:s.limit,offset:s==null?void 0:s.offset,estimatedCost:o.estimatedCost,estimatedRows:o.estimatedRows,joinOrder:o.joinOrder,isOrderSatisfied:o.isOrderSatisfied??((p=o.planMetrics)==null?void 0:p.isOrderSatisfied)??!1,sortCostAvoided:((y=o.planMetrics)==null?void 0:y.sortCostAvoided)??void 0},bytecodeSize:o.byteLength,instructions:l,assembly:u}}async executeQuery(t,n,s){return this.coordinator.leaseQueue.enqueue(()=>this._executeQueryInternal(t,n,s),this.currentLeaseId??void 0)}async _executeQueryInternal(t,n,s){var _;const i=await this._getTableInternal(t),r=[],o=[];if(s.joins&&s.joins.length>0){if(1+s.joins.length>16)throw new ds(1+s.joins.length,16);for(let I=0;I<s.joins.length;I++){const p=s.joins[I],y=await this._getTableInternal(p.table);r.push(y),o.push({type:p.type,table:y,cursor:I+1,leftCol:p.leftCol,op:p.op,rightCol:p.rightCol})}}for(const I of[i,...r]){let p=I.rootPageId;for(;p!==0;){const y=await this.driver.acquirePage(p),T=this.pool.getSlotDataView(y);p=Ut(T,0)}for(const y of I.indexes??[]){let T=y.rootPageId;for(;T!==0;){const O=await this.driver.acquirePage(T),w=this.pool.getSlotDataView(O);T=Ut(w,0)}}}let a=s.orderBy;!a&&s.sortCol&&(a=[{colName:s.sortCol,direction:s.sortDir}]);const c={table:i,joinedTables:o.length>0?o:void 0,filters:n,orderBy:a,groupBy:s.groupBy,aggregates:s.aggregates,having:s.having,selectExprs:s.selectExprs,udfNameMap:this.getUdfMap(),udfDefs:this.getUdfDefs(),limit:s.limit!==null?s.limit:void 0,offset:s.offset!==null?s.offset:void 0,planner:s.planner??this.planner},l=dr(c),u=l.allTables??[i,...r];qr(this.vmCtx,u[0],u),l.inSets&&(this.vmCtx.inSets=l.inSets);const d=l.keyInfos??c.keyInfos;d&&(this.vmCtx.keyInfos=d);const h={};for(const I of this.udfs.values())h[I.id]=I.def.call;this.vmCtx.udfs=h;let f=l.outputColumns??c.outputColumns??i.columns;if(c.aggregates&&c.aggregates.length>0||c.groupBy&&c.groupBy.length>0)if(l.outputColumns)f=l.outputColumns;else{f=[];const I=c.groupBy??[];for(const p of I){const y=typeof p=="string"?p:p.colName??(p.expr?vt(p.expr):"group_key"),T=i.columns.find(O=>O.name===y);T?f.push(T):f.push({name:y,type:S.TEXT,flags:tt.NONE,colOffset:0})}for(let p=0;p<(((_=c.aggregates)==null?void 0:_.length)??0);p++){const y=c.aggregates[p],T=y.alias??(y.colName?`${y.func}_${y.colName}`:y.func),O=y.func==="count"?S.INT32:S.FLOAT64;f.push({name:T,type:O,flags:tt.NONE,colOffset:0})}}this.vmCtx.outputColumns=f;const g=[];for(;;){const I=Xn(this.vmCtx,this.pool.view,l);let p=0;for(let y=0;y<this.vmCtx.resultCount;y++){const T=this.pool.view.getUint16(Dn+p,!0),O=Dn+p+2,w=Je(f,this.pool.view,O);g.push(w),p+=2+T}if(I===L.DONE)break;if(I===L.BUFFER_FULL)this.vmCtx.resultOffset=0,this.vmCtx.resultCount=0,this.vmCtx.status=L.RUNNING;else if(I===L.PAGE_FAULT){this.vmCtx.resultOffset=0,this.vmCtx.resultCount=0;const y=[],T=this.vmCtx.cursors??[this.vmCtx.cursor];for(const O of T)if(O&&O.pageId>1){const w=this.pool.getResidentSlot(O.pageId);w>0&&(this.pool.pinSlot(w),y.push(w))}try{await this.driver.acquirePage(this.vmCtx.fault_page_id)}finally{for(const O of y)this.pool.unpinSlot(O)}this.vmCtx.status=L.RUNNING}else throw I===L.ARENA_EXHAUSTED?(this.vmCtx.arenaOffset=0,new Oi):I===L.TIMEOUT?new Yr:I===L.INVALID_BYTECODE?new Zr:new Error(`VM execution error: status=${I}`)}return Object.defineProperty(g,"isOrderSatisfied",{value:l.isOrderSatisfied??!1,writable:!0,enumerable:!1,configurable:!0}),g}async checkpoint(){return this.coordinator.checkpoint()}async exportBinary(){return this.coordinator.leaseQueue.enqueue(async()=>{this.coordinator.isInTransaction()||(await this.coordinator.executeCheckpoint(),await this.driver.flushAllDirty());const t=this.pool.getSlotDataView(0),n=Ro(t),s=new Uint8Array(n*4096);s.set(this.pool.getPageBytesInSlot(0),0);const i=new DataView(s.buffer,s.byteOffset,4096);Yt(i,0);const r=[];for(let c=2;c<=n;c++)this.pool.getResidentSlot(c)===-1&&!this.coordinator.hasSpilledPage(c)&&r.push(c);const o=r.length>0?await this.vfs.readPages(r):[],a=new Map;for(let c=0;c<r.length;c++)a.set(r[c],o[c]??null);for(let c=2;c<=n;c++){const l=(c-1)*4096,u=s.subarray(l,l+4096),d=this.pool.getResidentSlot(c);if(d!==-1)u.set(this.pool.getPageBytesInSlot(d));else if(this.coordinator.hasSpilledPage(c))u.set(this.coordinator.getSpilledPage(c));else{const f=a.get(c);f&&u.set(f)}const h=be(u);new DataView(u.buffer,u.byteOffset,4096).setUint32(12,h,!0)}return s},this.currentLeaseId??void 0)}async importBinary(t){if(this.coordinator.isInTransaction())throw new Error("Cannot import binary database while a transaction is active");return this.coordinator.leaseQueue.enqueue(async()=>{var c,l;const n=t instanceof Uint8Array?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):new Uint8Array(t);if(n.byteLength<4096||n.byteLength%4096!==0)throw new Gn(`Invalid database binary size (${n.byteLength} bytes): must be a non-zero multiple of 4096 bytes`);const s=n.byteLength/4096,i=n.subarray(0,4096),r=new DataView(i.buffer,i.byteOffset,4096),o=Yn(r,!0);if(o.pageSize!==4096)throw new Gn(`Invalid database page size ${o.pageSize} (expected 4096)`);if(o.totalPages!==s)throw new Gn(`Database page count mismatch: header specifies ${o.totalPages} pages, but binary image contains ${s} pages`);for(let u=2;u<=s;u++){const d=(u-1)*4096,h=n.subarray(d,d+4096),g=new DataView(h.buffer,h.byteOffset,4096).getUint32(12,!0);if(g!==0){const _=be(h);if(_!==g)throw new Pe(u,g,_)}}const a=[];for(let u=1;u<=s;u++){const d=(u-1)*4096;a.push({pageId:u,data:n.subarray(d,d+4096).slice()})}for(let u=1;u<this.pool.slotCount;u++)this.pool.forceUnpinSlot(u),this.pool.unassignSlot(u),this.pool.clearDirty(u),this.pool.getPageBytesInSlot(u).fill(0);this.pool.getPageBytesInSlot(0).set(a[0].data),this.pool.clearDirty(0),await this.vfs.writePages(a),await((l=(c=this.vfs).flush)==null?void 0:l.call(c)),await this.coordinator.resetWalAfterImport(),this.tableMetaCache.clear(),this.tableTailPages.clear(),this.indexTailPages.clear(),this.vmCtx.table=null,await Un.pinAllCatalogPages(this.driver)})}async close(){var t,n;this.broadcastChannel&&(this.broadcastChannel.close(),this.broadcastChannel=null),this.beforeCommitHooks.clear(),this.commitHooks.clear(),this.subscriptions.clear(),await this.coordinator.close(),await this.driver.flushAllDirty(),await((n=(t=this.vfs).close)==null?void 0:n.call(t))}}E.ALIGNMENT_PADDING_OFFSET=pl,E.ALIGNMENT_PADDING_SIZE=Or,E.AggregateNotAllowedInWhereError=_s,E.BUILTIN_AGGREGATES=Ko,E.BUILTIN_SCALARS=Jo,E.BYTECODE_OFFSET=Nr,E.BYTECODE_SIZE=Sr,E.BufferPoolDriver=Yo,E.BytecodeEmitter=xs,E.CATALOG_PAGE_HEADER_FIELDS=sl,E.CATALOG_PAGE_HEADER_OFFSET_COL_COUNT_IN_PAGE=ol,E.CATALOG_PAGE_HEADER_OFFSET_FLAGS=rl,E.CATALOG_PAGE_HEADER_OFFSET_NEXT_COL_CATALOG_PAGE_ID=cl,E.CATALOG_PAGE_HEADER_OFFSET_PAGE_CHECKSUM=ul,E.CATALOG_PAGE_HEADER_OFFSET_PAGE_TYPE=il,E.CATALOG_PAGE_HEADER_OFFSET_START_COL_INDEX=ll,E.CATALOG_PAGE_HEADER_OFFSET_TABLE_ID=al,E.CATALOG_PAGE_HEADER_SIZE=Fn,E.COLUMN_META_FIELDS=fl,E.COLUMN_META_OFFSET_COL_OFFSET=gl,E.COLUMN_META_OFFSET_FLAGS=hl,E.COLUMN_META_OFFSET_NAME=dl,E.COLUMN_META_OFFSET_RESERVED=_l,E.COLUMN_META_OFFSET_TYPE=Al,E.COLUMN_META_SIZE=ri,E.COST_INDEX_NEXT=Ws,E.COST_INDEX_SEEK=Cn,E.COST_ROW_EVAL=_e,E.CURRENT_ENGINE_VERSION=cs,E.CURRENT_MIN_READ_VERSION=Qr,E.CannotDropColumnError=wi,E.ColumnAlreadyExistsError=hs,E.ColumnFlag=tt,E.ColumnNotFoundError=he,E.CorruptPageError=Pe,E.CorruptWalFrameError=qn,E.CorruptWalHeaderError=ms,E.CostBasedPlanner=$s,E.CostBasedQueryPlanner=Pc,E.CustomOrderPlanner=Sc,E.CustomPlanner=oa,E.CustomQueryPlanner=Uc,E.DEFAULT_BUFFER_POOL_REGIONS=Il,E.DEFAULT_CACHE_SIZE_BYTES=ml,E.DEFAULT_MAX_QUERY_MEMORY=He,E.DEFAULT_PAGE_SLOTS=El,E.DEFAULT_PAGE_TO_SLOT_BUCKETS=Ht,E.DEFAULT_SLOT_COUNT=We,E.DIRTY_MASK_OFFSET=Pr,E.DataType=S,E.DefaultQueryPlanner=Oc,E.ExclusiveLeaseQueue=Zo,E.ExpressionBuilder=it,E.FILE_HEADER_SIZE=ba,E.HEADER_OFFSET_CHANGE_COUNTER=ye,E.HEADER_OFFSET_FILE_FORMAT_VERSION=ni,E.HEADER_OFFSET_FREE_PAGE_HEAD=fe,E.HEADER_OFFSET_MAGIC=Ie,E.HEADER_OFFSET_MIN_READ_VERSION=si,E.HEADER_OFFSET_NEXT_CATALOG_PAGE_ID=Ge,E.HEADER_OFFSET_NEXT_INDEX_CATALOG_PAGE_ID=qe,E.HEADER_OFFSET_PAGE_CHECKSUM=Te,E.HEADER_OFFSET_PAGE_SIZE=ei,E.HEADER_OFFSET_RESERVED=Na,E.HEADER_OFFSET_SCHEMA_VERSION=pe,E.HEADER_OFFSET_TOTAL_PAGES=re,E.HeuristicPlanner=ia,E.HeuristicQueryPlanner=bc,E.INDEX_CATALOG_OFFSET=ss,E.INDEX_DESCRIPTOR_FIELDS=Xa,E.INDEX_DESCRIPTOR_OFFSET_COLUMN_COUNT=Ka,E.INDEX_DESCRIPTOR_OFFSET_COLUMN_INDICES=za,E.INDEX_DESCRIPTOR_OFFSET_COL_DIRECTIONS=tl,E.INDEX_DESCRIPTOR_OFFSET_FLAGS=Ja,E.INDEX_DESCRIPTOR_OFFSET_INDEX_ID=Ya,E.INDEX_DESCRIPTOR_OFFSET_NAME=el,E.INDEX_DESCRIPTOR_OFFSET_RESERVED=nl,E.INDEX_DESCRIPTOR_OFFSET_ROOT_PAGE_ID=ja,E.INDEX_DESCRIPTOR_OFFSET_TABLE_ID=Za,E.INDEX_DESCRIPTOR_SIZE=Se,E.IdentifierTooLongError=Hr,E.IndexAlreadyExistsError=Si,E.IndexFlag=rt,E.IndexNotFoundError=Vr,E.IndexedDbVfsAdapter=zr,E.InvalidBytecodeError=Zr,E.InvalidDatabaseError=Gn,E.Io=Li,E.MASTER_TABLE_OFFSET=ns,E.MAX_COLUMNS_PER_CATALOG_PAGE=Ce,E.MAX_COLUMNS_PER_TABLE=Ae,E.MAX_CURSORS_PER_FRAME=Ol,E.MAX_DESCRIPTORS_PER_OVERFLOW_PAGE=nn,E.MAX_INDEXES_PAGE1=ii,E.MAX_INDEXES_SYSPAGE=Ba,E.MAX_IN_LIST_SIZE=Qt,E.MAX_NAME_LENGTH=ie,E.MAX_REGISTERS_PER_FRAME=Ul,E.MAX_ROW_SIZE=2048,E.MAX_SUBQUERY_DEPTH=Pl,E.MAX_TABLES_PAGE1=ee,E.MAX_TABLES_SYSPAGE=La,E.MAX_TABLE_INTERIOR_CELLS=yr,E.MAX_TOPK_HEAP_LIMIT=kr,E.MemoryVfsAdapter=Jr,E.NEXT_DESCRIPTOR_CATALOG_PAGE_OFFSET=Ra,E.NEXT_DESCRIPTOR_CATALOG_PAGE_SIZE=Fa,E.NoOpPlanner=ra,E.NoOpQueryPlanner=Nc,E.NotNullConstraintError=As,E.OpCode=m,E.OpfsVfsAdapter=to,E.PAGE_HEADER_OFFSET_CELL_COUNT=Ta,E.PAGE_HEADER_OFFSET_CHECKSUM=Me,E.PAGE_HEADER_OFFSET_CONTENT_OFFSET=Ca,E.PAGE_HEADER_OFFSET_FLAGS=ya,E.PAGE_HEADER_OFFSET_FREE_BYTES=wa,E.PAGE_HEADER_OFFSET_NEXT_PAGE_ID=Ir,E.PAGE_HEADER_OFFSET_TYPE=Er,E.PAGE_HEADER_SIZE=te,E.PAGE_SCRATCHPAD_OFFSET=Lr,E.PAGE_SCRATCHPAD_SIZE=Ur,E.PAGE_SIZE=4096,E.PAGE_TO_SLOT_BUCKET_SIZE=Ue,E.PAGE_TO_SLOT_OFFSET=Gt,E.PAGE_TO_SLOT_SIZE=Cr,E.PAGE_TYPE_CATALOG_PAGE=vn,E.PAGE_TYPE_FREE=$e,E.PAGE_TYPE_INDEX_INTERIOR=vr,E.PAGE_TYPE_INDEX_LEAF=us,E.PAGE_TYPE_LEAF_DATA=fs,E.PAGE_TYPE_TABLE_INTERIOR=Ci,E.QueryArenaExhaustedError=Oi,E.QueryBuilder=Bt,E.QueryTimeoutError=Yr,E.RESULT_BUFFER_OFFSET=Dn,E.RESULT_BUFFER_SIZE=oi,E.RowSizeLimitExceededError=Wr,E.SLOTTED_PAGE_HEADER_FIELDS=pa,E.SLOT_TO_PAGE_OFFSET=is,E.SYSPAGE_FILE_HEADER_FIELDS=Pa,E.SYSPAGE_RESERVED_OFFSET=Da,E.SYSPAGE_RESERVED_SIZE=Qa,E.SubqueryNestingTooDeepError=Xr,E.TABLE_DESCRIPTOR_FIELDS=va,E.TABLE_DESCRIPTOR_OFFSET_AUTO_INC_NEXT=$a,E.TABLE_DESCRIPTOR_OFFSET_COLUMN_COUNT=Ma,E.TABLE_DESCRIPTOR_OFFSET_COL_CATALOG_PAGE_ID=qa,E.TABLE_DESCRIPTOR_OFFSET_FLAGS=Ha,E.TABLE_DESCRIPTOR_OFFSET_NAME=Wa,E.TABLE_DESCRIPTOR_OFFSET_RESERVED=xa,E.TABLE_DESCRIPTOR_OFFSET_ROOT_PAGE_ID=Ga,E.TABLE_DESCRIPTOR_OFFSET_ROW_COUNT_ESTIMATE=Va,E.TABLE_DESCRIPTOR_OFFSET_TABLE_ID=ka,E.TABLE_DESCRIPTOR_SIZE=we,E.TABLE_INTERIOR_CELL_FIELDS=Sa,E.TABLE_INTERIOR_CELL_OFFSET_CHILD_PAGE_ID=Ua,E.TABLE_INTERIOR_CELL_OFFSET_ROWID=Oa,E.TABLE_INTERIOR_CELL_SIZE=pr,E.TABLE_INTERIOR_SPLIT_INDEX=Tr,E.TOTAL_MEMORY_BYTES=yl,E.TRANSIENT_ARENA_OFFSET=Br,E.TableAlreadyExistsError=gs,E.TableFlag=xe,E.TableNotFoundError=kn,E.TooManyColumnsError=Mn,E.TooManyCursorsError=ds,E.TooManyGroupByColumnsError=Kr,E.TooManyIndexesError=$r,E.TooManyOrderByColumnsError=jr,E.TooManyRegistersError=st,E.TooManyTablesError=Ui,E.TransactionCoordinator=jo,E.UniqueConstraintViolationError=ln,E.UnknownFunctionError=Pi,E.UnsupportedFormatVersionError=xr,E.VM_CONTEXT_OFFSET=br,E.VM_CONTEXT_SIZE=wr,E.VM_FRAME_COUNT=Sl,E.VM_FRAME_SIZE=wl,E.VmStatus=L,E.WAL_CURRENT_VERSION=Rr,E.WAL_FILE_HEADER_FIELDS=Tl,E.WAL_FILE_HEADER_SIZE=ls,E.WAL_FRAME_HEADER_FIELDS=Cl,E.WAL_FRAME_HEADER_SIZE=Ve,E.WAL_FRAME_MAGIC=Qn,E.WAL_FRAME_OFFSET_CHECKSUM=Ti,E.WAL_FRAME_OFFSET_DB_SIZE_PAGES=pi,E.WAL_FRAME_OFFSET_FLAGS=mi,E.WAL_FRAME_OFFSET_FRAME_SEQ=yi,E.WAL_FRAME_OFFSET_FRAME_TYPE=_i,E.WAL_FRAME_OFFSET_MAGIC=di,E.WAL_FRAME_OFFSET_PAGE_ID=Ii,E.WAL_FRAME_OFFSET_RESERVED=Dr,E.WAL_FRAME_OFFSET_TX_ID=Ei,E.WAL_FRAME_SIZE=an,E.WAL_FRAME_TYPE_PAGE_DATA=rs,E.WAL_FRAME_TYPE_TX_COMMIT=os,E.WAL_FRAME_TYPE_TX_UNCOMMITTED=as,E.WAL_HEADER_OFFSET_CHECKPOINT_SEQ=fi,E.WAL_HEADER_OFFSET_CHECKSUM=gi,E.WAL_HEADER_OFFSET_MAGIC=li,E.WAL_HEADER_OFFSET_PAGE_SIZE=ui,E.WAL_HEADER_OFFSET_RESERVED=Fr,E.WAL_HEADER_OFFSET_SALT1=Ai,E.WAL_HEADER_OFFSET_SALT2=hi,E.WAL_HEADER_OFFSET_WAL_VERSION=ci,E.WAL_HEADER_SIZE=bl,E.WAL_MAGIC_BYTES=Bi,E.WAL_PAGE_SIZE=Oe,E.WEBDB_CORE_WASM_BASE64=nr,E.WebDB=Un,E.buf_pool_assign_slot=Io,E.buf_pool_clear_dirty=To,E.buf_pool_find_victim=xi,E.buf_pool_get_resident_slot=Vt,E.buf_pool_get_slot_offset=zl,E.buf_pool_is_dirty=Hi,E.buf_pool_is_pinned=_n,E.buf_pool_mark_dirty=yo,E.buf_pool_pin_slot=Vi,E.buf_pool_read_slot_to_page=dn,E.buf_pool_select_eviction_victim=Xi,E.buf_pool_unassign_slot=po,E.buf_pool_unpin_slot=$i,E.buf_pool_write_slot_to_page=Wi,E.buildJoinEdges=Hs,E.buildRootFilter=ne,E.c_assert=ro,E.canJoinPreserveOrder=ua,E.catalog_append_index_overflow_page=ko,E.catalog_append_table_overflow_page=vo,E.catalog_create_table=Vo,E.catalog_delete_index_descriptor=zi,E.catalog_delete_table_descriptor=qo,E.catalog_find_free_index_slot=Mo,E.catalog_find_free_table_slot=Ki,E.catalog_find_index_by_name=Ms,E.catalog_find_table_by_name=Ac,E.catalog_find_table_slot=Zt,E.catalog_get_change_counter=Do,E.catalog_get_free_page_head=lc,E.catalog_get_index_slot_capacity=Be,E.catalog_get_schema_version=Fo,E.catalog_get_table_pk_index=ji,E.catalog_get_table_slot_capacity=In,E.catalog_get_total_pages=Ro,E.catalog_increment_change_counter=oe,E.catalog_increment_schema_version=en,E.catalog_init_page=Gs,E.catalog_init_page1=Bo,E.catalog_list_all_indexes=Go,E.catalog_list_table_descriptors=pn,E.catalog_list_table_indexes=le,E.catalog_load_all_tables=gc,E.catalog_load_table_meta=er,E.catalog_map_column_location=Ho,E.catalog_parse_data_type=Qo,E.catalog_read_column_meta=Wo,E.catalog_read_fixed_string=Qs,E.catalog_read_index_descriptor=yn,E.catalog_read_page1_header=Yn,E.catalog_read_page_header=ge,E.catalog_read_table_descriptor=qt,E.catalog_set_free_page_head=cc,E.catalog_set_total_pages=ac,E.catalog_update_page1_checksum=Yt,E.catalog_write_column_meta=tr,E.catalog_write_fixed_string=Ds,E.catalog_write_index_descriptor=Ji,E.catalog_write_page_header=hc,E.catalog_write_table_descriptor=sn,E.chooseIndexScan=Ys,E.chooseJoinIndex=Zs,E.clear_bit=io,E.col=ir,E.collectLeafFilters=aa,E.compare_sorter_keys=En,E.compileQuery=dr,E.computeBufferPoolOffsets=ai,E.computePage1Checksum=Ni,E.computePageChecksum=be,E.computeWalFrameChecksum=Es,E.crc32=bi,E.createLiveQuery=ha,E.createVmContext=Gr,E.createVmCursor=Mr,E.createWasmCore=xo,E.createWasmMemory=Xo,E.decodeWalFileHeader=Cs,E.decodeWalFrame=Gl,E.decodeWalFrameHeader=Ri,E.deriveDefaultAlias=vt,E.disassembleBytecode=fa,E.doesTableSatisfyJoinOrderKeys=or,E.emitExpression=Z,E.encodeWalFileHeader=Ts,E.encodeWalFrame=ws,E.estimateFilterSelectivity=rr,E.estimateWhereCost=ar,E.evalExprNode=kt,E.exp=ta,E.extractAggregatesFromExpr=_r,E.extractFilterColumnNames=na,E.findIndexOnColumn=jn,E.fn=yc,E.fnv1a_32=Fs,E.formatDisassembly=Aa,E.getCmpOpcode=Jn,E.getFilterReferencedTables=wn,E.getMinKeyValueForType=Xs,E.getSingleTableBaseCost=me,E.getTopLevelConjunctionFilters=Sn,E.getWebDbCoreWasmBytes=$o,E.get_bit=no,E.inferExprType=ca,E.inferTransitivePredicates=sa,E.isAggregateFunction=de,E.isBuiltinFunction=dc,E.isBuiltinScalarFunction=zo,E.isIndexAlignedWithOrderBy=gr,E.isQueryBuilder=x,E.liveQuery=Ks,E.materializeOutputSelectExprs=Kn,E.memcmp=Nl,E.memcpy=un,E.memset=xt,E.normalizeFilter=Re,E.normalizeSelectItem=Js,E.notifyLiveQueryTableRead=js,E.optimizeQueryPlan=Bc,E.optimizeWherePredicates=lr,E.page_binary_search_index_leaf=Vn,E.page_binary_search_interior=jl,E.page_compact=Hn,E.page_compare_index_keys=Bs,E.page_delete_index_leaf_cell=go,E.page_delete_row=uo,E.page_deserialize_row=Je,E.page_get_cell_content_offset=Ze,E.page_get_cell_count=ft,E.page_get_cell_offset=at,E.page_get_checksum=Xl,E.page_get_contiguous_free_space=Os,E.page_get_free_bytes=Ne,E.page_get_next_page_id=Ut,E.page_get_right_child_page_id=Ns,E.page_get_row_length=Ps,E.page_get_table_layout=Zl,E.page_get_total_free_space=co,E.page_get_type=Xe,E.page_init=Wn,E.page_init_free=lo,E.page_init_index_leaf=Ls,E.page_init_interior=fo,E.page_insert_index_leaf_cell=Gi,E.page_insert_interior_cell=ho,E.page_insert_row=gn,E.page_serialize_row=bs,E.page_set_cell_content_offset=je,E.page_set_cell_count=Ye,E.page_set_cell_offset=hn,E.page_set_checksum=Yl,E.page_set_free_bytes=Ke,E.page_set_next_page_id=Us,E.page_set_right_child_page_id=Ao,E.page_set_type=xl,E.page_split_interior=Kl,E.page_table_delete=qi,E.page_table_get=mo,E.page_table_hash=$n,E.page_table_set=Eo,E.page_update_row=ki,E.parseExpression=At,E.parseFilterTarget=wt,E.parseSelectExpr=qs,E.read_f64=Fl,E.read_i32=Bl,E.read_i64=kl,E.read_u16=ps,E.read_u32=yt,E.read_u64=Ql,E.read_u8=eo,E.reconstructJoinPlans=Vs,E.recoverFromWal=sr,E.resetVmContext=qr,E.resolveColumnAcrossTables=gt,E.resolveQueryPlanner=ur,E.serialize_composite_key=Rs,E.serialize_single_key=_o,E.set_bit=so,E.sql=Ic,E.sql_like_match=ze,E.strlen=Is,E.validateClause=rn,E.validateWalFrame=Fi,E.vm_step=Xn,E.write_f64=Dl,E.write_i32=Rl,E.write_i64=Ml,E.write_u16=ys,E.write_u32=Tt,E.write_u64=vl,E.write_u8=Ll,Object.defineProperty(E,Symbol.toStringTag,{value:"Module"})});
5
5
  //# sourceMappingURL=webdb.umd.cjs.map