@tensorix/metahub 0.5.1 → 0.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/db-worker.js CHANGED
@@ -1,4 +1,4 @@
1
- var De=(e,t,r)=>()=>{if(e)try{t=e(e=0)}catch(n){r=[n]}if(r)throw r[0];return t};var Pc=`
1
+ var De=(e,t,r)=>()=>{if(e)try{t=e(e=0)}catch(n){r=[n]}if(r)throw r[0];return t};var qc=`
2
2
  CREATE TABLE IF NOT EXISTS meta (
3
3
  key TEXT PRIMARY KEY,
4
4
  value TEXT
@@ -308,7 +308,23 @@ CREATE TABLE IF NOT EXISTS blob_policy (
308
308
  redundancy TEXT, -- 'all' | 'any'
309
309
  __deleted INTEGER NOT NULL DEFAULT 0
310
310
  );
311
- `,Cc=`
311
+
312
+ -- Synced device roster (system tier, see tables.ts): one row per node id, written
313
+ -- by the device itself on open (describeSelf) and by anyone who renames it.
314
+ -- Replicates so every device shows the same name and icon for a peer — the only
315
+ -- record a purely bucket-joined device leaves besides its oplog stream. Each
316
+ -- column is its own LWW register, so a rename and a platform refresh never
317
+ -- clobber each other. meta.node_label survives as a node-local read fallback.
318
+ CREATE TABLE IF NOT EXISTS nodes (
319
+ id TEXT PRIMARY KEY, -- node_id
320
+ label TEXT, -- shared display name; any device may set it
321
+ platform TEXT, -- macos | windows | linux | ios | android | web
322
+ form TEXT, -- laptop | desktop | phone | server | browser
323
+ app TEXT, -- cli | server | desktop | web
324
+ first_seen INTEGER, -- epoch ms of the device's first self-description
325
+ __deleted INTEGER NOT NULL DEFAULT 0
326
+ );
327
+ `,Lc=`
312
328
  CREATE VIRTUAL TABLE IF NOT EXISTS search_fts USING fts5(
313
329
  kind UNINDEXED,
314
330
  id UNINDEXED,
@@ -316,35 +332,35 @@ CREATE VIRTUAL TABLE IF NOT EXISTS search_fts USING fts5(
316
332
  title,
317
333
  body
318
334
  );
319
- `;function bt(e=6){let t=crypto.getRandomValues(new Uint8Array(e)),r="";for(let n of t)r+="0123456789abcdefghijklmnopqrstuvwxyz".charAt(n%36);return r}function Fi(e,t="item"){return e.normalize("NFKD").replace(/[^\x20-\x7E]/g,"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,32).replace(/-+$/g,"")||t}function Ot(e,t,r=e){return`${e}_${Fi(t,r)}-${bt()}`}function nn(e){let t=e.indexOf("_");if(t<=0)return null;let r=e.slice(0,t);return Nm.has(r)?r:null}var Nm;var wt=De(()=>{Nm=new Set(["db","prop","rec","doc","blk","site","sf","chan"])});function We(e){let t=e.query("SELECT value FROM meta WHERE key = 'node_id'").get();if(t)return t.value;let r=bt(8);return e.query("INSERT INTO meta (key, value) VALUES ('node_id', ?)").run(r),r}function on(e){return e.query("SELECT value FROM meta WHERE key = 'node_label'").get()?.value??null}function Nc(e,t){if(t==null||t.trim()===""){e.query("DELETE FROM meta WHERE key = 'node_label'").run();return}e.query("INSERT INTO meta (key, value) VALUES ('node_label', ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(t.trim())}function qc(e){let t=We(e),r=e.query("SELECT node_id, label FROM peers WHERE node_id IS NOT NULL AND node_id <> '' GROUP BY node_id").all();return[{node_id:t,label:on(e),self:!0},...r.filter((n)=>n.node_id!==t).map((n)=>({...n,self:!1}))]}var Gt=De(()=>{wt()});function Mi(e,t){if(t<=65535)return{millis:e,counter:t};return{millis:e+Math.floor(t/65536),counter:t%65536}}function Bi(e){let{millis:t,counter:r}=Mi(e.millis,e.counter);return`${String(t).padStart(15,"0")}-${r.toString(16).padStart(4,"0")}-${e.node}`}function Ui(e){let t=e.indexOf("-"),r=e.indexOf("-",t+1);return{millis:Number(e.slice(0,t)),counter:parseInt(e.slice(t+1,r),16),node:e.slice(r+1)}}function Lc(e,t){let r=e.query("SELECT value FROM meta WHERE key = 'hlc'").get();return r?Ui(r.value):{millis:0,counter:0,node:t}}function $c(e,t){e.query("INSERT INTO meta (key, value) VALUES ('hlc', ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(Bi(t))}function zc(e,t,r=Date.now()){let n=Lc(e,t),o=Math.max(n.millis,r),s=o===n.millis?n.counter+1:0,a={...Mi(o,s),node:t};return $c(e,a),Bi(a)}function Fc(e,t,r,n=Date.now()){let o=Lc(e,t),s=Ui(r);if(!Number.isFinite(s.millis)||!Number.isFinite(s.counter))return;let a=Math.max(o.millis,s.millis,n),u;if(a===o.millis&&a===s.millis)u=Math.max(o.counter,s.counter)+1;else if(a===o.millis)u=o.counter+1;else if(a===s.millis)u=s.counter+1;else u=0;$c(e,{...Mi(a,u),node:t})}function sn(e){if(!e)return[];let t=e.replace(/\r\n?/g,`
335
+ `;function yt(e=6){let t=crypto.getRandomValues(new Uint8Array(e)),r="";for(let n of t)r+="0123456789abcdefghijklmnopqrstuvwxyz".charAt(n%36);return r}function Mi(e,t="item"){return e.normalize("NFKD").replace(/[^\x20-\x7E]/g,"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,32).replace(/-+$/g,"")||t}function Ot(e,t,r=e){return`${e}_${Mi(t,r)}-${yt()}`}function nn(e){let t=e.indexOf("_");if(t<=0)return null;let r=e.slice(0,t);return Um.has(r)?r:null}var Um;var bt=De(()=>{Um=new Set(["db","prop","rec","doc","blk","site","sf","chan"])});function je(e){let t=e.query("SELECT value FROM meta WHERE key = 'node_id'").get();if(t)return t.value;let r=yt(8);return e.query("INSERT INTO meta (key, value) VALUES ('node_id', ?)").run(r),r}function Cn(e,t){let r=e.query(`SELECT ${$c} FROM nodes WHERE id = ? AND __deleted = 0`).get(t);return r?Fc(r):null}function jm(e){return e.query(`SELECT ${$c} FROM nodes WHERE __deleted = 0`).all().map(Fc)}function zc(e){return e.query("SELECT value FROM meta WHERE key = 'node_label'").get()?.value??null}function Hm(e,t){if(t==null){e.query("DELETE FROM meta WHERE key = 'node_label'").run();return}e.query("INSERT INTO meta (key, value) VALUES ('node_label', ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(t)}function Bi(e,t){let r=Cn(e,t)?.label;if(r)return r;let n=e.query("SELECT label FROM peers WHERE node_id = ? AND label IS NOT NULL AND label <> '' LIMIT 1").get(t);if(n?.label)return n.label;return t===je(e)?zc(e):null}function Mc(e){return Bi(e,je(e))}function Bc(e,t,r){let n=r??je(e),o=t==null||t.trim()===""?null:t.trim(),s=Cn(e,n);if(n===je(e))Hm(e,o);if(s&&s.label===o)return;if(!s&&o==null)return;Kt("node",()=>{be(e,"nodes",n,"label",o)})}function Uc(e,t={}){let r=je(e),n=Cn(e,r),o={};if(t.platform!==void 0&&(n?.platform??null)!==t.platform)o.platform=t.platform;if(t.form!==void 0&&(n?.form??null)!==t.form)o.form=t.form;if(t.app!==void 0&&(n?.app??null)!==t.app)o.app=t.app;if(n?.first_seen==null)o.first_seen=t.now??Date.now();if(!n?.label){let s=zc(e)??t.defaultLabel??null;if(s)o.label=s}if(Object.keys(o).length>0)Kt("node",()=>{for(let[s,a]of Object.entries(o))be(e,"nodes",r,s,a)});return Cn(e,r)}function Ui(e){let t=je(e),r=new Set([t]);for(let s of jm(e))r.add(s.node_id);let n=e.query("SELECT node_id FROM peers WHERE node_id IS NOT NULL AND node_id <> '' GROUP BY node_id").all();for(let s of n)r.add(s.node_id);let o=[...r].map((s)=>{let a=Cn(e,s);return{node_id:s,label:Bi(e,s),self:s===t,platform:a?.platform??null,form:a?.form??null,app:a?.app??null}});return o.sort((s,a)=>Number(a.self)-Number(s.self)),o}var $c="id, label, platform, form, app, first_seen",Fc=(e)=>({node_id:e.id,label:e.label,platform:e.platform??null,form:e.form??null,app:e.app??null,first_seen:e.first_seen});var Gt=De(()=>{bt();dt()});function ji(e,t){if(t<=65535)return{millis:e,counter:t};return{millis:e+Math.floor(t/65536),counter:t%65536}}function Hi(e){let{millis:t,counter:r}=ji(e.millis,e.counter);return`${String(t).padStart(15,"0")}-${r.toString(16).padStart(4,"0")}-${e.node}`}function Wi(e){let t=e.indexOf("-"),r=e.indexOf("-",t+1);return{millis:Number(e.slice(0,t)),counter:parseInt(e.slice(t+1,r),16),node:e.slice(r+1)}}function jc(e,t){let r=e.query("SELECT value FROM meta WHERE key = 'hlc'").get();return r?Wi(r.value):{millis:0,counter:0,node:t}}function Hc(e,t){e.query("INSERT INTO meta (key, value) VALUES ('hlc', ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(Hi(t))}function Wc(e,t,r=Date.now()){let n=jc(e,t),o=Math.max(n.millis,r),s=o===n.millis?n.counter+1:0,a={...ji(o,s),node:t};return Hc(e,a),Hi(a)}function Zc(e,t,r,n=Date.now()){let o=jc(e,t),s=Wi(r);if(!Number.isFinite(s.millis)||!Number.isFinite(s.counter))return;let a=Math.max(o.millis,s.millis,n),u;if(a===o.millis&&a===s.millis)u=Math.max(o.counter,s.counter)+1;else if(a===o.millis)u=o.counter+1;else if(a===s.millis)u=s.counter+1;else u=0;Hc(e,{...ji(a,u),node:t})}function on(e){if(!e)return[];let t=e.replace(/\r\n?/g,`
320
336
  `).split(`
321
337
  `),r=[],n=[],o=null,s=0,a=()=>{if(n.length)r.push({text:n.join(`
322
- `),blankAfter:0}),n=[]},u=()=>{if(a(),r.length)r[r.length-1].blankAfter++};for(let _ of t){if(o){n.push(_);let x=_.match(/^\s*(`{3,}|~{3,})\s*$/);if(x&&x[1][0]===o&&x[1].length>=s)a(),o=null,s=0;continue}let m=_.match(/^\s*(`{3,}|~{3,})/);if(m)a(),o=m[1][0],s=m[1].length,n.push(_);else if(_.trim()==="")u();else n.push(_)}a();for(let _=0;_<r.length-1;_++)r[_].blankAfter=Math.max(0,r[_].blankAfter-1);return r}function Cr(e){let t=e.filter((n)=>!!n.text&&n.text.length>0),r=[];return t.forEach((n,o)=>{r.push(...n.text.split(`
338
+ `),blankAfter:0}),n=[]},u=()=>{if(a(),r.length)r[r.length-1].blankAfter++};for(let _ of t){if(o){n.push(_);let x=_.match(/^\s*(`{3,}|~{3,})\s*$/);if(x&&x[1][0]===o&&x[1].length>=s)a(),o=null,s=0;continue}let m=_.match(/^\s*(`{3,}|~{3,})/);if(m)a(),o=m[1][0],s=m[1].length,n.push(_);else if(_.trim()==="")u();else n.push(_)}a();for(let _=0;_<r.length-1;_++)r[_].blankAfter=Math.max(0,r[_].blankAfter-1);return r}function Nr(e){let t=e.filter((n)=>!!n.text&&n.text.length>0),r=[];return t.forEach((n,o)=>{r.push(...n.text.split(`
323
339
  `));let s=Math.max(0,n.blankAfter??0);if(o<t.length-1)r.push("");for(let a=0;a<s;a++)r.push("")}),r.join(`
324
- `)}function Mc(e,t){let r=qm(e,t),n=new Set(r.map((u)=>u[0])),o=new Map(r.map((u)=>[u[1],u[0]])),s=t.map((u,_)=>o.has(_)?{keep:o.get(_)}:{insert:u}),a=[];for(let u=0;u<e.length;u++)if(!n.has(u))a.push(u);return{items:s,deleted:a}}function qm(e,t){let r=e.length,n=t.length,o=Array.from({length:r+1},()=>Array(n+1).fill(0));for(let _=r-1;_>=0;_--)for(let m=n-1;m>=0;m--)o[_][m]=e[_]===t[m]?o[_+1][m+1]+1:Math.max(o[_+1][m],o[_][m+1]);let s=[],a=0,u=0;while(a<r&&u<n)if(e[a]===t[u])s.push([a,u]),a++,u++;else if(o[a+1][u]>=o[a][u+1])a++;else u++;return s}function Lm(e){return Math.max(0,Math.trunc(Number.isFinite(e)?e:Date.now()))}function qn(e=Date.now()){let t=Math.max(0,Lm(e)-2678400000);return String(t).padStart(15,"0")+"-"}function bo(e,t=Date.now()){return e.dataset==="intent_receipts"&&e.hlc<qn(t)}function ji(e,t=Date.now()){return e.filter((r)=>!bo(r,t))}function cn(e,t=Date.now()){return e.query("DELETE FROM crdt_changes WHERE dataset = 'intent_receipts' AND hlc < ?").run(qn(t)).changes}var an="intent_receipts";function yr(e,t){if(wo!==null)return t();wo=(Bc?Bc+"/":"")+(e?e+":":"")+bt(8);try{return t()}finally{wo=null}}function Fe(e,t=null){return(...r)=>yr(t,()=>e(...r))}function Uc(e,t,r){if(r!==null)return JSON.parse(r);return Fm.has(`${e}:${t}`)?0:null}function jc(e){if(e===null||e===void 0)return null;if(typeof e==="boolean")return e?1:0;if(typeof e==="number")return e;if(typeof e==="string")return e;return JSON.stringify(e)}function vo(e,t,r){e.query(`INSERT OR IGNORE INTO ${t} (id) VALUES (?)`).run(r)}function Mm(e,t){return e.query("SELECT 1 AS x FROM doc_blocks WHERE doc_id = ? LIMIT 1").get(t)!=null}function Bm(e,t){let r=e.query("SELECT text, blank_after FROM doc_blocks WHERE doc_id = ? AND __deleted = 0 ORDER BY order_key, id").all(t);vo(e,"documents",t),e.query("UPDATE documents SET body = ? WHERE id = ?").run(Cr(r.map((n)=>({text:n.text,blankAfter:n.blank_after??0}))),t)}function Um(e,t,r,n,o){if(Ln.has(t))return;if(t==="records"){if(Hi.has(n)){vo(e,"records",r);let u=Uc("records",n,o);e.query(`UPDATE records SET "${n}" = ? WHERE id = ?`).run(jc(u),r)}else if(vo(e,"records",r),o===null)e.query(`UPDATE records SET data = json_remove(data, '$."' || ? || '"') WHERE id = ?`).run(n,r);else e.query(`UPDATE records SET data = json_set(coalesce(data, '{}'), '$."' || ? || '"', json(?)) WHERE id = ?`).run(n,o,r);return}let s=zm[t];if(!s||!s.cols.has(n))return;if(t==="documents"&&n==="body"&&Mm(e,r))return;vo(e,s.table,r);let a=Uc(t,n,o);if(e.query(`UPDATE ${s.table} SET "${n}" = ? WHERE id = ?`).run(jc(a),r),t==="doc_blocks"){let u=e.query("SELECT doc_id FROM doc_blocks WHERE id = ?").get(r);if(u?.doc_id)Bm(e,u.doc_id)}}function So(e,t){let r=e.query("INSERT OR IGNORE INTO crdt_changes (hlc, node_id, dataset, row_id, col, value, txn) VALUES (?, ?, ?, ?, ?, ?, ?)").run(t.hlc,t.node_id,t.dataset,t.row_id,t.col,t.value,t.txn??null).changes>0;if(e.query("SELECT MAX(hlc) AS h FROM crdt_changes WHERE dataset = ? AND row_id = ? AND col = ?").get(t.dataset,t.row_id,t.col).h!==t.hlc)return{inserted:r,winner:!1};try{Um(e,t.dataset,t.row_id,t.col,t.value)}catch(o){if(r)e.query("DELETE FROM crdt_changes WHERE dataset = ? AND row_id = ? AND col = ? AND hlc = ?").run(t.dataset,t.row_id,t.col,t.hlc);throw o}return{inserted:r,winner:!0}}function we(e,t,r,n,o){let s=$m??We(e),a={hlc:zc(e,s),node_id:s,dataset:t,row_id:r,col:n,value:o===void 0?null:JSON.stringify(o),txn:wo};return So(e,a),a}function er(e,t,r={}){let n=r.now??Date.now();cn(e,n);let o=We(e),s=0,a=0;if(e.transaction((_)=>{for(let m of _){if(bo(m,n))continue;Fc(e,o,m.hlc);try{if(So(e,m).inserted)s++}catch(x){a++,console.error(`[ingest] skipped a change that failed to apply (dataset=${m.dataset} col=${m.col} row=${m.row_id}): ${x.message}`)}}})(t),a)console.error(`[ingest] ${a} change(s) skipped this batch (see above)`);return s}function br(e,t,r={}){let n=r.excludeDatasets??[],o=["rowid > ?"],s=[t];if(n.length)o.push(`dataset NOT IN (${n.map(()=>"?").join(", ")})`),s.push(...n);if(r.onlyNode!=null)o.push("node_id = ?"),s.push(r.onlyNode);o.push("(dataset != ? OR hlc >= ?)"),s.push(an,qn(r.now??Date.now()));let a=o.join(" AND "),u=r.limit!=null&&r.limit>0?` LIMIT ${Math.floor(r.limit)}`:"",_=e.query(`SELECT rowid AS seq, ${It} FROM crdt_changes WHERE ${a} ORDER BY rowid${u}`).all(...s),m=r.limit==null||r.limit<=0||_.length<r.limit,x;if(m){let D=e.query("SELECT MAX(rowid) AS m FROM crdt_changes").get();x=Math.max(t,D.m??t)}else x=_[_.length-1].seq;return{changes:_.map(({seq:D,...j})=>j),cursor:x}}var Eo,It,wo=null,Bc=null,Hc,$m=null,zm,Hi,Ln,Fm;var dt=De(()=>{Gt();wt();Eo=["hlc","node_id","dataset","row_id","col","value","txn"],It=Eo.join(", "),Hc=/^[a-z0-9_-]{1,16}$/;zm={databases:{table:"databases",cols:new Set(["name","icon","meta","created_hlc","__deleted"])},properties:{table:"properties",cols:new Set(["database_id","name","type","config","position","__deleted"])},documents:{table:"documents",cols:new Set(["title","body","database_id","parent_id","created_hlc","order_key","__deleted"])},doc_blocks:{table:"doc_blocks",cols:new Set(["doc_id","text","order_key","blank_after","__deleted"])},sites:{table:"sites",cols:new Set(["name","title","created_hlc","visibility","spa","public_grants","__deleted"])},site_channels:{table:"site_channels",cols:new Set(["site_id","audience","hosting","controller_node_id","target_ref","canonical_url","policy_json","desired_state","created_hlc","__deleted"])},site_files:{table:"site_files",cols:new Set(["site_id","path","content_type","encoding","content","created_hlc","__deleted"])},blob_policy:{table:"blob_policy",cols:new Set(["full_nodes","redundancy","__deleted"])}},Hi=new Set(["database_id","created_hlc","order_key","__deleted"]),Ln=new Set([an]),Fm=new Set(["records:__deleted","databases:__deleted","properties:__deleted","documents:__deleted","doc_blocks:__deleted","doc_blocks:blank_after","sites:__deleted","sites:spa","site_channels:__deleted","site_files:__deleted","blob_policy:__deleted"])});function ln(e){return e instanceof Z?e.code:void 0}var Z;var Ye=De(()=>{Z=class Z extends Error{code;constructor(e,t){super(t);this.code=e;this.name="MhError"}}});function Wc(e){return e.replace(/[^a-zA-Z0-9_]/g,"_")}function Zc(e){return e.replace(/'/g,"''")}function Gc(e,t){return`idx_rec_${Wc(e)}_${Wc(t)}`}function jm(e,t,r){return e.query("SELECT 1 AS ok FROM sqlite_master WHERE type = 'index' AND name = ?").get(Gc(t,r))!=null}function Wi(e,t,r){let n=Gc(t,r);e.exec(`CREATE INDEX IF NOT EXISTS "${n}" ON records (data ->> '${Zc(r)}', created_hlc) WHERE database_id = '${Zc(t)}' AND __deleted = 0`)}function Zi(e,t,r){if(jm(e,t,r.id))return;if(r.type!=="relation"&&r.type!=="doc"){if(e.query("SELECT COUNT(*) AS c FROM records WHERE database_id = ? AND __deleted = 0").get(t).c<2000)return}Wi(e,t,r.id)}function Gi(e,t){if(e==="select"||e==="multi_select"){let r=t?.options;if(!Array.isArray(r)||r.length===0||!r.every((n)=>typeof n==="string"))throw new Z("invalid_input",`${e} requires config.options: string[]`)}if(e==="relation"){if(typeof t?.database!=="string")throw new Z("invalid_input","relation requires config.database (target database id)")}}function Wm(e,t){return(e.query("SELECT MAX(position) AS m FROM properties WHERE database_id = ? AND __deleted = 0").get(t).m??0)+1}function wr(e,t){let r=e.query(`SELECT ${Vc} FROM properties WHERE id = ? AND __deleted = 0`).get(t);if(!r)return null;return{...r,config:r.config?JSON.parse(r.config):null}}function Nt(e,t){return e.query(`SELECT ${Vc} FROM properties WHERE database_id = ? AND __deleted = 0 ORDER BY position`).all(t).map((n)=>({...n,config:n.config?JSON.parse(n.config):null}))}function Jc(e,t,r){let n=wr(e,t);if(!n)throw new Z("not_found",`no such property: ${t}`);if(!Number.isFinite(r))throw new Z("invalid_input","width must be a finite number");let o=Math.max(80,Math.min(2000,Math.round(r)));return Ki(e,t,{config:{...n.config??{},width:o}})}function Xc(e,t){let r=wr(e,t);if(!r)throw new Z("not_found",`no such property: ${t}`);if(r.type!=="select"&&r.type!=="multi_select")throw new Z("invalid_input",`${r.type} property has no options`);return{prop:r,options:r.config?.options??[]}}var Kc,Hm,Vc,xo,Ki,Qc,Yc,el;var Nr=De(()=>{wt();dt();qr();Ye();Kc=new Set(["text","number","checkbox","select","multi_select","date","relation","doc","url"]),Hm=["id","database_id","name","type","config","position"],Vc=Hm.join(", ");xo=Fe(function(t,r,n){if(!Pt(t,r))throw new Z("not_found",`no such database: ${r}`);if(!Kc.has(n.type))throw new Z("invalid_input",`unknown property type: ${n.type}`);Gi(n.type,n.config);let o=n.indexed?{...n.config??{},indexed:!0}:n.config??null,s=Ot("prop",n.name);if(we(t,"properties",s,"database_id",r),we(t,"properties",s,"name",n.name),we(t,"properties",s,"type",n.type),we(t,"properties",s,"config",o),we(t,"properties",s,"position",n.position??Wm(t,r)),n.type==="relation"||n.type==="doc"||n.indexed===!0)Wi(t,r,s);return wr(t,s)});Ki=Fe(function(t,r,n){let o=wr(t,r);if(!o)throw new Z("not_found",`no such property: ${r}`);let s=n.type!==void 0&&n.type!==o.type;if(n.type!==void 0&&!Kc.has(n.type))throw new Z("invalid_input",`unknown property type: ${n.type}`);let a=n.type??o.type,u;if(n.config!==void 0){let _={...o.config??{}};for(let[m,x]of Object.entries(n.config))if(x===null)delete _[m];else _[m]=x;u=_,Gi(a,u)}else if(s)Gi(n.type,o.config??void 0);if(n.name!==void 0)we(t,"properties",r,"name",n.name);if(n.type!==void 0)we(t,"properties",r,"type",n.type);if(u!==void 0)we(t,"properties",r,"config",u);if(n.position!==void 0)we(t,"properties",r,"position",n.position);if(s){let _=t.query("SELECT id FROM records WHERE database_id = ? AND __deleted = 0 AND data ->> ? IS NOT NULL").all(o.database_id,r);for(let m of _)we(t,"records",m.id,r,null)}return wr(t,r)});Qc=Fe(function(t,r,n,o){let{prop:s,options:a}=Xc(t,r);if(o=o.trim(),!o)throw new Z("invalid_input","option name must not be empty");if(!a.includes(n))throw new Z("not_found",`no such option: ${n}`);if(o===n)return{property:s,renamed:0};if(a.includes(o))throw new Z("conflict",`option already exists: ${o}`);we(t,"properties",r,"config",{...s.config??{},options:a.map((_)=>_===n?o:_)});let u=0;if(s.type==="select"){let _=t.query("SELECT id FROM records WHERE database_id = ? AND __deleted = 0 AND data ->> ? = ?").all(s.database_id,r,n);for(let m of _)we(t,"records",m.id,r,o);u=_.length}else{let _=t.query("SELECT id, data ->> ? AS v FROM records WHERE database_id = ? AND __deleted = 0 AND data ->> ? IS NOT NULL").all(r,s.database_id,r);for(let m of _){let x=JSON.parse(m.v);if(!Array.isArray(x)||!x.includes(n))continue;we(t,"records",m.id,r,[...new Set(x.map((D)=>D===n?o:D))]),u++}}return{property:wr(t,r),renamed:u}}),Yc=Fe(function(t,r,n){let{prop:o,options:s}=Xc(t,r);if(!s.includes(n))throw new Z("not_found",`no such option: ${n}`);if(s.length===1)throw new Z("invalid_input","cannot remove the last option; delete the property instead");we(t,"properties",r,"config",{...o.config??{},options:s.filter((u)=>u!==n)});let a=0;if(o.type==="select"){let u=t.query("SELECT id FROM records WHERE database_id = ? AND __deleted = 0 AND data ->> ? = ?").all(o.database_id,r,n);for(let _ of u)we(t,"records",_.id,r,null);a=u.length}else{let u=t.query("SELECT id, data ->> ? AS v FROM records WHERE database_id = ? AND __deleted = 0 AND data ->> ? IS NOT NULL").all(r,o.database_id,r);for(let _ of u){let m=JSON.parse(_.v);if(!Array.isArray(m)||!m.includes(n))continue;we(t,"records",_.id,r,m.filter((x)=>x!==n)),a++}}return{property:wr(t,r),cleared:a}}),el=Fe(function(t,r){let n=wr(t,r);if(!n)return!1;we(t,"properties",r,"__deleted",1);let o=t.query("SELECT id FROM records WHERE database_id = ? AND __deleted = 0 AND data ->> ? IS NOT NULL").all(n.database_id,r);for(let s of o)we(t,"records",s.id,r,void 0);return!0})});function nl(e){if(!e)return null;return{...e,meta:e.meta===null?null:JSON.parse(e.meta)}}function Pt(e,t){return nl(e.query(`SELECT ${rl} FROM databases WHERE id = ? AND __deleted = 0`).get(t))}function sl(e){return e.query(`SELECT ${rl} FROM databases WHERE __deleted = 0 ORDER BY created_hlc`).all().map((r)=>nl(r))}function tl(e,t,r,n){return e.query(`SELECT id FROM ${t} WHERE ${r} = ? AND __deleted = 0`).all(n).map((o)=>o.id)}var Zm,rl,Vi,ol,il,al;var qr=De(()=>{wt();dt();Ye();Nr();Lr();Zm=["id","name","icon","meta","created_hlc"],rl=Zm.join(", ");Vi=Fe(function(t,r){let n=Ot("db",r.name),o=we(t,"databases",n,"name",r.name);if(we(t,"databases",n,"created_hlc",o.hlc),r.icon!==void 0)we(t,"databases",n,"icon",r.icon);return Pt(t,n)}),ol=Fe(function(t,r,n){if(!Pt(t,r))throw new Z("not_found",`no such database: ${r}`);if(n.name!==void 0)we(t,"databases",r,"name",n.name);if(n.icon!==void 0)we(t,"databases",r,"icon",n.icon);if(n.meta!==void 0){if(n.meta!==null&&(typeof n.meta!=="object"||Array.isArray(n.meta)))throw new Z("invalid_input","meta must be a JSON object or null");we(t,"databases",r,"meta",n.meta)}return Pt(t,r)}),il=Fe(function(t,r,n={}){let o=Pt(t,r);if(!o)throw new Z("not_found",`no such database: ${r}`);let s=Vi(t,{name:n.name??o.name,icon:n.icon??o.icon??void 0});if(o.meta!==null){let{collapsed:x,...D}=o.meta;if(Object.keys(D).length)we(t,"databases",s.id,"meta",D)}let a=new Map,u=new Set;for(let x of Nt(t,r)){let D=x.type==="relation"&&x.config?.database===r,j=D?{...x.config,database:s.id}:x.config??void 0,Y=xo(t,s.id,{name:x.name,type:x.type,config:j,position:x.position});if(a.set(x.id,Y.id),D)u.add(Y.id)}let _=un(t,r),m=new Map;for(let x of _){let D={};for(let[j,Y]of Object.entries(x.cells)){let _e=a.get(j);if(!_e)continue;if(u.has(_e)&&Array.isArray(Y)&&Y.length>0)continue;D[_e]=Y}m.set(x.id,To(t,s.id,D).id)}for(let x of _){let D={};for(let[j,Y]of Object.entries(x.cells)){let _e=a.get(j);if(_e&&u.has(_e)&&Array.isArray(Y)&&Y.length>0)D[_e]=Y.map((de)=>m.get(String(de))??de)}if(Object.keys(D).length)ko(t,m.get(x.id),D)}return Pt(t,s.id)});al=Fe(function(t,r){if(!Pt(t,r))return!1;we(t,"databases",r,"__deleted",1);let n=(o)=>{for(let s of tl(t,o,"database_id",r))we(t,o,s,"__deleted",1)};n("properties"),n("records");for(let o of tl(t,"documents","database_id",r))we(t,"documents",o,"database_id",null);return t.query("DELETE FROM meta WHERE key = 'current_db' AND value = ?").run(r),!0})});function Vm(e){return e!==null&&e!=="blk"}function ll(e,t){return e.query("SELECT id FROM properties WHERE database_id = ? AND type = 'text' AND __deleted = 0 ORDER BY position LIMIT 1").get(t)?.id??null}function Jm(e,t,r,n){let o=Gm[t],s=o.nameCol;if(t==="rec"&&n){let j=ll(e,n);if(j)s=`data ->> '${j.replace(/'/g,"''")}'`}let a=s??"''",u=[],_=[];u.push("(id >= ? AND id < ?)"),_.push(r,r+cl);let m=`${t}_${r}`;if(u.push("(id >= ? AND id < ?)"),_.push(m,m+cl),s)u.push(`lower(${s}) = lower(?)`),_.push(r);let x=`SELECT id, ${a} AS label FROM ${o.table} WHERE __deleted = 0 AND (${u.join(" OR ")})`;if(o.scoped&&n)x+=" AND database_id = ?",_.push(n);return e.query(x).all(..._).map((j)=>({kind:t,id:j.id,label:j.label??""}))}function Ji(e,t,r={}){let n=r.kind?[r.kind]:Vm(nn(t))?[nn(t)]:Km,o=[],s=new Set;for(let a of n)for(let u of Jm(e,a,t,r.databaseId)){if(s.has(u.id))continue;s.add(u.id),o.push(u)}return o}var Gm,Km,cl="{";var Xi=De(()=>{wt();Ye();Gm={db:{table:"databases",nameCol:"name",scoped:!1,noun:"database"},prop:{table:"properties",nameCol:"name",scoped:!0,noun:"property"},rec:{table:"records",nameCol:null,scoped:!0,noun:"record"},doc:{table:"documents",nameCol:"title",scoped:!0,noun:"document"}},Km=["db","prop","rec","doc"]});function Qi(e,t){if(t!==null&&e>=t)throw Error(`fracdex: ${e} >= ${t}`);if(e.endsWith("0")||t!==null&&t.endsWith("0"))throw Error(`fracdex: trailing zero in ${e}/${t}`);if(t!==null){let s=0;while((e[s]??"0")===t[s])s++;if(s>0)return t.slice(0,s)+Qi(e.slice(s),t.slice(s))}let n=e===""?0:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".indexOf(e[0]),o=t===null?62:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".indexOf(t[0]);if(o-n>1)return"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"[Math.round(0.5*(n+o))];if(t!==null&&t.length>1)return t.slice(0,1);return"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"[n]+Qi(e.slice(1),null)}function Mt(e,t){return Qi(e??"",t)}function lr(e,t,r){if(r<=0)return[];if(r===1)return[Mt(e,t)];if(t===null){let s=Mt(e,null),a=[s];for(let u=1;u<r;u++)s=Mt(s,null),a.push(s);return a}if(e===null){let s=Mt(null,t),a=[s];for(let u=1;u<r;u++)s=Mt(null,s),a.unshift(s);return a}let n=Math.floor(r/2),o=Mt(e,t);return[...lr(e,o,n),o,...lr(o,t,r-n-1)]}function ul(e){return typeof e==="string"||typeof e==="number"||typeof e==="boolean"}function Xm(e){return typeof e==="boolean"?e?1:0:e}function Qm(e,t,r){let n=t.config?.database;if(!n)return r;let o=Ji(e,r,{kind:"rec",databaseId:n}),s=o.find((a)=>a.id===r);if(s)return s.id;if(o.length===1)return o[0].id;if(o.length===0){if(nn(r)==="rec")return r;throw new Z("not_found",`${t.name}: no such record in target database: ${r}`)}throw new Z("ambiguous",`${t.name}: ambiguous relation "${r}" (${o.length} matches); use a full id`)}function Ym(e,t,r){let n=Ji(e,r,{kind:"doc"}),o=n.find((s)=>s.id===r);if(o)return o.id;if(n.length===1)return n[0].id;if(n.length===0){if(nn(r)==="doc")return r;throw new Z("not_found",`${t.name}: no such document: ${r}`)}throw new Z("ambiguous",`${t.name}: ambiguous document "${r}" (${n.length} matches); use a full id`)}function es(e,t,r){switch(t.type){case"text":case"url":case"date":{if(r===null)return null;if(typeof r!=="string")throw new Z("invalid_input",`${t.name} expects a string`);return r}case"number":{if(r===null)return null;let n=typeof r==="number"?r:Number(r);if(!Number.isFinite(n))throw new Z("invalid_input",`${t.name} expects a number`);return n}case"checkbox":{if(typeof r==="boolean")return r;if(r==="true"||r===1)return!0;if(r==="false"||r===0||r===null)return!1;throw new Z("invalid_input",`${t.name} expects a boolean`)}case"select":{if(r===null)return null;let n=String(r);if(!t.config?.options?.includes(n))throw new Z("invalid_input",`${t.name}: '${n}' is not an allowed option`);return n}case"multi_select":{let n=r===null?[]:Array.isArray(r)?r:[r],o=t.config?.options??[];for(let s of n)if(!o.includes(String(s)))throw new Z("invalid_input",`${t.name}: '${s}' is not an allowed option`);return n.map(String)}case"relation":return(r===null?[]:Array.isArray(r)?r:[r]).map((o)=>Qm(e,t,String(o)));case"doc":return(r===null?[]:Array.isArray(r)?r:[r]).map((o)=>Ym(e,t,String(o)))}}function ey(e){let t=new Map;for(let r of e){let n=r.name.toLowerCase(),o=t.get(n);if(o)o.push(r);else t.set(n,[r])}return t}function ts(e,t){let r=new Map(e.map((s)=>[s.id,s])),n=ey(e),o=[];for(let[s,a]of Object.entries(t)){let u=r.get(s);if(!u){let _=n.get(s.toLowerCase())??[];if(_.length>1)throw new Z("ambiguous",`property name "${s}" matches ${_.length} properties; use a property id`);u=_[0]}if(!u)throw new Z("not_found",`unknown property: ${s}`);o.push({prop:u,value:a})}return o}function pl(e,t,r){return ts(Nt(e,t),r).map(({prop:n,value:o})=>({prop:n,value:es(e,n,o)}))}function _l(e,t){let r=JSON.parse(e.data||"{}"),n=new Map(t.map((a)=>[a.id,a])),o={},s={};for(let[a,u]of Object.entries(r)){let _=n.get(a);if(!_)continue;o[_.name]=u,s[_.id]=u}return{id:e.id,database_id:e.database_id,values:o,cells:s}}function ty(e,t){let r=e.find((n)=>n.prop.type==="text"&&typeof n.value==="string"&&n.value);return Ot("rec",r?String(r.value):"",t)}function dl(e,t){return e.query("SELECT 1 AS ok FROM sqlite_master WHERE type = 'table' AND name = ?").get(t)!=null}function ry(e){return dl(e,"meta")&&dl(e,"crdt_changes")}function ny(e,t,r,n){if(n)we(e,"records",t,"order_key",r);else e.query("UPDATE records SET order_key = ? WHERE id = ?").run(r,t)}function gl(e,t){return e.query(`SELECT order_key FROM records
340
+ `)}function Gc(e,t){let r=Wm(e,t),n=new Set(r.map((u)=>u[0])),o=new Map(r.map((u)=>[u[1],u[0]])),s=t.map((u,_)=>o.has(_)?{keep:o.get(_)}:{insert:u}),a=[];for(let u=0;u<e.length;u++)if(!n.has(u))a.push(u);return{items:s,deleted:a}}function Wm(e,t){let r=e.length,n=t.length,o=Array.from({length:r+1},()=>Array(n+1).fill(0));for(let _=r-1;_>=0;_--)for(let m=n-1;m>=0;m--)o[_][m]=e[_]===t[m]?o[_+1][m+1]+1:Math.max(o[_+1][m],o[_][m+1]);let s=[],a=0,u=0;while(a<r&&u<n)if(e[a]===t[u])s.push([a,u]),a++,u++;else if(o[a+1][u]>=o[a][u+1])a++;else u++;return s}function Zm(e){return Math.max(0,Math.trunc(Number.isFinite(e)?e:Date.now()))}function qn(e=Date.now()){let t=Math.max(0,Zm(e)-2678400000);return String(t).padStart(15,"0")+"-"}function yo(e,t=Date.now()){return e.dataset==="intent_receipts"&&e.hlc<qn(t)}function Zi(e,t=Date.now()){return e.filter((r)=>!yo(r,t))}function an(e,t=Date.now()){return e.query("DELETE FROM crdt_changes WHERE dataset = 'intent_receipts' AND hlc < ?").run(qn(t)).changes}var sn="intent_receipts";function Kt(e,t){if(bo!==null)return t();bo=(Kc?Kc+"/":"")+(e?e+":":"")+yt(8);try{return t()}finally{bo=null}}function ze(e,t=null){return(...r)=>Kt(t,()=>e(...r))}function Vc(e,t,r){if(r!==null)return JSON.parse(r);return Vm.has(`${e}:${t}`)?0:null}function Jc(e){if(e===null||e===void 0)return null;if(typeof e==="boolean")return e?1:0;if(typeof e==="number")return e;if(typeof e==="string")return e;return JSON.stringify(e)}function wo(e,t,r){e.query(`INSERT OR IGNORE INTO ${t} (id) VALUES (?)`).run(r)}function Jm(e,t){return e.query("SELECT 1 AS x FROM doc_blocks WHERE doc_id = ? LIMIT 1").get(t)!=null}function Xm(e,t){let r=e.query("SELECT text, blank_after FROM doc_blocks WHERE doc_id = ? AND __deleted = 0 ORDER BY order_key, id").all(t);wo(e,"documents",t),e.query("UPDATE documents SET body = ? WHERE id = ?").run(Nr(r.map((n)=>({text:n.text,blankAfter:n.blank_after??0}))),t)}function Qm(e,t,r,n,o){if(Eo.has(t))return;if(t==="records"){if(Gi.has(n)){wo(e,"records",r);let u=Vc("records",n,o);e.query(`UPDATE records SET "${n}" = ? WHERE id = ?`).run(Jc(u),r)}else if(wo(e,"records",r),o===null)e.query(`UPDATE records SET data = json_remove(data, '$."' || ? || '"') WHERE id = ?`).run(n,r);else e.query(`UPDATE records SET data = json_set(coalesce(data, '{}'), '$."' || ? || '"', json(?)) WHERE id = ?`).run(n,o,r);return}let s=Km[t];if(!s||!s.cols.has(n))return;if(t==="documents"&&n==="body"&&Jm(e,r))return;wo(e,s.table,r);let a=Vc(t,n,o);if(e.query(`UPDATE ${s.table} SET "${n}" = ? WHERE id = ?`).run(Jc(a),r),t==="doc_blocks"){let u=e.query("SELECT doc_id FROM doc_blocks WHERE id = ?").get(r);if(u?.doc_id)Xm(e,u.doc_id)}}function So(e,t){let r=e.query("INSERT OR IGNORE INTO crdt_changes (hlc, node_id, dataset, row_id, col, value, txn) VALUES (?, ?, ?, ?, ?, ?, ?)").run(t.hlc,t.node_id,t.dataset,t.row_id,t.col,t.value,t.txn??null).changes>0;if(e.query("SELECT MAX(hlc) AS h FROM crdt_changes WHERE dataset = ? AND row_id = ? AND col = ?").get(t.dataset,t.row_id,t.col).h!==t.hlc)return{inserted:r,winner:!1};try{Qm(e,t.dataset,t.row_id,t.col,t.value)}catch(o){if(r)e.query("DELETE FROM crdt_changes WHERE dataset = ? AND row_id = ? AND col = ? AND hlc = ?").run(t.dataset,t.row_id,t.col,t.hlc);throw o}return{inserted:r,winner:!0}}function be(e,t,r,n,o){let s=Gm??je(e),a={hlc:Wc(e,s),node_id:s,dataset:t,row_id:r,col:n,value:o===void 0?null:JSON.stringify(o),txn:bo};return So(e,a),a}function rr(e,t,r={}){let n=r.now??Date.now();an(e,n);let o=je(e),s=0,a=0;if(e.transaction((_)=>{for(let m of _){if(yo(m,n))continue;Zc(e,o,m.hlc);try{if(So(e,m).inserted)s++}catch(x){a++,console.error(`[ingest] skipped a change that failed to apply (dataset=${m.dataset} col=${m.col} row=${m.row_id}): ${x.message}`)}}})(t),a)console.error(`[ingest] ${a} change(s) skipped this batch (see above)`);return s}function br(e,t,r={}){let n=r.excludeDatasets??[],o=["rowid > ?"],s=[t];if(n.length)o.push(`dataset NOT IN (${n.map(()=>"?").join(", ")})`),s.push(...n);if(r.onlyNode!=null)o.push("node_id = ?"),s.push(r.onlyNode);o.push("(dataset != ? OR hlc >= ?)"),s.push(sn,qn(r.now??Date.now()));let a=o.join(" AND "),u=r.limit!=null&&r.limit>0?` LIMIT ${Math.floor(r.limit)}`:"",_=e.query(`SELECT rowid AS seq, ${It} FROM crdt_changes WHERE ${a} ORDER BY rowid${u}`).all(...s),m=r.limit==null||r.limit<=0||_.length<r.limit,x;if(m){let D=e.query("SELECT MAX(rowid) AS m FROM crdt_changes").get();x=Math.max(t,D.m??t)}else x=_[_.length-1].seq;return{changes:_.map(({seq:D,...j})=>j),cursor:x}}var vo,It,bo=null,Kc=null,Xc,Gm=null,Km,Gi,Eo,Vm;var dt=De(()=>{Gt();bt();vo=["hlc","node_id","dataset","row_id","col","value","txn"],It=vo.join(", "),Xc=/^[a-z0-9_-]{1,16}$/;Km={databases:{table:"databases",cols:new Set(["name","icon","meta","created_hlc","__deleted"])},properties:{table:"properties",cols:new Set(["database_id","name","type","config","position","__deleted"])},documents:{table:"documents",cols:new Set(["title","body","database_id","parent_id","created_hlc","order_key","__deleted"])},doc_blocks:{table:"doc_blocks",cols:new Set(["doc_id","text","order_key","blank_after","__deleted"])},sites:{table:"sites",cols:new Set(["name","title","created_hlc","visibility","spa","public_grants","__deleted"])},site_channels:{table:"site_channels",cols:new Set(["site_id","audience","hosting","controller_node_id","target_ref","canonical_url","policy_json","desired_state","created_hlc","__deleted"])},site_files:{table:"site_files",cols:new Set(["site_id","path","content_type","encoding","content","created_hlc","__deleted"])},blob_policy:{table:"blob_policy",cols:new Set(["full_nodes","redundancy","__deleted"])},nodes:{table:"nodes",cols:new Set(["label","platform","form","app","first_seen","__deleted"])}},Gi=new Set(["database_id","created_hlc","order_key","__deleted"]),Eo=new Set([sn]),Vm=new Set(["records:__deleted","databases:__deleted","properties:__deleted","documents:__deleted","doc_blocks:__deleted","doc_blocks:blank_after","sites:__deleted","sites:spa","site_channels:__deleted","site_files:__deleted","blob_policy:__deleted","nodes:__deleted"])});function cn(e){return e instanceof Z?e.code:void 0}var Z;var Ye=De(()=>{Z=class Z extends Error{code;constructor(e,t){super(t);this.code=e;this.name="MhError"}}});function Qc(e){return e.replace(/[^a-zA-Z0-9_]/g,"_")}function Yc(e){return e.replace(/'/g,"''")}function el(e,t){return`idx_rec_${Qc(e)}_${Qc(t)}`}function Ym(e,t,r){return e.query("SELECT 1 AS ok FROM sqlite_master WHERE type = 'index' AND name = ?").get(el(t,r))!=null}function Ki(e,t,r){let n=el(t,r);e.exec(`CREATE INDEX IF NOT EXISTS "${n}" ON records (data ->> '${Yc(r)}', created_hlc) WHERE database_id = '${Yc(t)}' AND __deleted = 0`)}function Vi(e,t,r){if(Ym(e,t,r.id))return;if(r.type!=="relation"&&r.type!=="doc"){if(e.query("SELECT COUNT(*) AS c FROM records WHERE database_id = ? AND __deleted = 0").get(t).c<2000)return}Ki(e,t,r.id)}function Ji(e,t){if(e==="select"||e==="multi_select"){let r=t?.options;if(!Array.isArray(r)||r.length===0||!r.every((n)=>typeof n==="string"))throw new Z("invalid_input",`${e} requires config.options: string[]`)}if(e==="relation"){if(typeof t?.database!=="string")throw new Z("invalid_input","relation requires config.database (target database id)")}}function ty(e,t){return(e.query("SELECT MAX(position) AS m FROM properties WHERE database_id = ? AND __deleted = 0").get(t).m??0)+1}function wr(e,t){let r=e.query(`SELECT ${rl} FROM properties WHERE id = ? AND __deleted = 0`).get(t);if(!r)return null;return{...r,config:r.config?JSON.parse(r.config):null}}function Ct(e,t){return e.query(`SELECT ${rl} FROM properties WHERE database_id = ? AND __deleted = 0 ORDER BY position`).all(t).map((n)=>({...n,config:n.config?JSON.parse(n.config):null}))}function nl(e,t,r){let n=wr(e,t);if(!n)throw new Z("not_found",`no such property: ${t}`);if(!Number.isFinite(r))throw new Z("invalid_input","width must be a finite number");let o=Math.max(80,Math.min(2000,Math.round(r)));return Xi(e,t,{config:{...n.config??{},width:o}})}function ol(e,t){let r=wr(e,t);if(!r)throw new Z("not_found",`no such property: ${t}`);if(r.type!=="select"&&r.type!=="multi_select")throw new Z("invalid_input",`${r.type} property has no options`);return{prop:r,options:r.config?.options??[]}}var tl,ey,rl,xo,Xi,il,sl,al;var Cr=De(()=>{bt();dt();qr();Ye();tl=new Set(["text","number","checkbox","select","multi_select","date","relation","doc","url"]),ey=["id","database_id","name","type","config","position"],rl=ey.join(", ");xo=ze(function(t,r,n){if(!Pt(t,r))throw new Z("not_found",`no such database: ${r}`);if(!tl.has(n.type))throw new Z("invalid_input",`unknown property type: ${n.type}`);Ji(n.type,n.config);let o=n.indexed?{...n.config??{},indexed:!0}:n.config??null,s=Ot("prop",n.name);if(be(t,"properties",s,"database_id",r),be(t,"properties",s,"name",n.name),be(t,"properties",s,"type",n.type),be(t,"properties",s,"config",o),be(t,"properties",s,"position",n.position??ty(t,r)),n.type==="relation"||n.type==="doc"||n.indexed===!0)Ki(t,r,s);return wr(t,s)});Xi=ze(function(t,r,n){let o=wr(t,r);if(!o)throw new Z("not_found",`no such property: ${r}`);let s=n.type!==void 0&&n.type!==o.type;if(n.type!==void 0&&!tl.has(n.type))throw new Z("invalid_input",`unknown property type: ${n.type}`);let a=n.type??o.type,u;if(n.config!==void 0){let _={...o.config??{}};for(let[m,x]of Object.entries(n.config))if(x===null)delete _[m];else _[m]=x;u=_,Ji(a,u)}else if(s)Ji(n.type,o.config??void 0);if(n.name!==void 0)be(t,"properties",r,"name",n.name);if(n.type!==void 0)be(t,"properties",r,"type",n.type);if(u!==void 0)be(t,"properties",r,"config",u);if(n.position!==void 0)be(t,"properties",r,"position",n.position);if(s){let _=t.query("SELECT id FROM records WHERE database_id = ? AND __deleted = 0 AND data ->> ? IS NOT NULL").all(o.database_id,r);for(let m of _)be(t,"records",m.id,r,null)}return wr(t,r)});il=ze(function(t,r,n,o){let{prop:s,options:a}=ol(t,r);if(o=o.trim(),!o)throw new Z("invalid_input","option name must not be empty");if(!a.includes(n))throw new Z("not_found",`no such option: ${n}`);if(o===n)return{property:s,renamed:0};if(a.includes(o))throw new Z("conflict",`option already exists: ${o}`);be(t,"properties",r,"config",{...s.config??{},options:a.map((_)=>_===n?o:_)});let u=0;if(s.type==="select"){let _=t.query("SELECT id FROM records WHERE database_id = ? AND __deleted = 0 AND data ->> ? = ?").all(s.database_id,r,n);for(let m of _)be(t,"records",m.id,r,o);u=_.length}else{let _=t.query("SELECT id, data ->> ? AS v FROM records WHERE database_id = ? AND __deleted = 0 AND data ->> ? IS NOT NULL").all(r,s.database_id,r);for(let m of _){let x=JSON.parse(m.v);if(!Array.isArray(x)||!x.includes(n))continue;be(t,"records",m.id,r,[...new Set(x.map((D)=>D===n?o:D))]),u++}}return{property:wr(t,r),renamed:u}}),sl=ze(function(t,r,n){let{prop:o,options:s}=ol(t,r);if(!s.includes(n))throw new Z("not_found",`no such option: ${n}`);if(s.length===1)throw new Z("invalid_input","cannot remove the last option; delete the property instead");be(t,"properties",r,"config",{...o.config??{},options:s.filter((u)=>u!==n)});let a=0;if(o.type==="select"){let u=t.query("SELECT id FROM records WHERE database_id = ? AND __deleted = 0 AND data ->> ? = ?").all(o.database_id,r,n);for(let _ of u)be(t,"records",_.id,r,null);a=u.length}else{let u=t.query("SELECT id, data ->> ? AS v FROM records WHERE database_id = ? AND __deleted = 0 AND data ->> ? IS NOT NULL").all(r,o.database_id,r);for(let _ of u){let m=JSON.parse(_.v);if(!Array.isArray(m)||!m.includes(n))continue;be(t,"records",_.id,r,m.filter((x)=>x!==n)),a++}}return{property:wr(t,r),cleared:a}}),al=ze(function(t,r){let n=wr(t,r);if(!n)return!1;be(t,"properties",r,"__deleted",1);let o=t.query("SELECT id FROM records WHERE database_id = ? AND __deleted = 0 AND data ->> ? IS NOT NULL").all(n.database_id,r);for(let s of o)be(t,"records",s.id,r,void 0);return!0})});function ul(e){if(!e)return null;return{...e,meta:e.meta===null?null:JSON.parse(e.meta)}}function Pt(e,t){return ul(e.query(`SELECT ${ll} FROM databases WHERE id = ? AND __deleted = 0`).get(t))}function pl(e){return e.query(`SELECT ${ll} FROM databases WHERE __deleted = 0 ORDER BY created_hlc`).all().map((r)=>ul(r))}function cl(e,t,r,n){return e.query(`SELECT id FROM ${t} WHERE ${r} = ? AND __deleted = 0`).all(n).map((o)=>o.id)}var ry,ll,Qi,dl,fl,_l;var qr=De(()=>{bt();dt();Ye();Cr();Lr();ry=["id","name","icon","meta","created_hlc"],ll=ry.join(", ");Qi=ze(function(t,r){let n=Ot("db",r.name),o=be(t,"databases",n,"name",r.name);if(be(t,"databases",n,"created_hlc",o.hlc),r.icon!==void 0)be(t,"databases",n,"icon",r.icon);return Pt(t,n)}),dl=ze(function(t,r,n){if(!Pt(t,r))throw new Z("not_found",`no such database: ${r}`);if(n.name!==void 0)be(t,"databases",r,"name",n.name);if(n.icon!==void 0)be(t,"databases",r,"icon",n.icon);if(n.meta!==void 0){if(n.meta!==null&&(typeof n.meta!=="object"||Array.isArray(n.meta)))throw new Z("invalid_input","meta must be a JSON object or null");be(t,"databases",r,"meta",n.meta)}return Pt(t,r)}),fl=ze(function(t,r,n={}){let o=Pt(t,r);if(!o)throw new Z("not_found",`no such database: ${r}`);let s=Qi(t,{name:n.name??o.name,icon:n.icon??o.icon??void 0});if(o.meta!==null){let{collapsed:x,...D}=o.meta;if(Object.keys(D).length)be(t,"databases",s.id,"meta",D)}let a=new Map,u=new Set;for(let x of Ct(t,r)){let D=x.type==="relation"&&x.config?.database===r,j=D?{...x.config,database:s.id}:x.config??void 0,Y=xo(t,s.id,{name:x.name,type:x.type,config:j,position:x.position});if(a.set(x.id,Y.id),D)u.add(Y.id)}let _=ln(t,r),m=new Map;for(let x of _){let D={};for(let[j,Y]of Object.entries(x.cells)){let _e=a.get(j);if(!_e)continue;if(u.has(_e)&&Array.isArray(Y)&&Y.length>0)continue;D[_e]=Y}m.set(x.id,To(t,s.id,D).id)}for(let x of _){let D={};for(let[j,Y]of Object.entries(x.cells)){let _e=a.get(j);if(_e&&u.has(_e)&&Array.isArray(Y)&&Y.length>0)D[_e]=Y.map((de)=>m.get(String(de))??de)}if(Object.keys(D).length)ko(t,m.get(x.id),D)}return Pt(t,s.id)});_l=ze(function(t,r){if(!Pt(t,r))return!1;be(t,"databases",r,"__deleted",1);let n=(o)=>{for(let s of cl(t,o,"database_id",r))be(t,o,s,"__deleted",1)};n("properties"),n("records");for(let o of cl(t,"documents","database_id",r))be(t,"documents",o,"database_id",null);return t.query("DELETE FROM meta WHERE key = 'current_db' AND value = ?").run(r),!0})});function iy(e){return e!==null&&e!=="blk"}function hl(e,t){return e.query("SELECT id FROM properties WHERE database_id = ? AND type = 'text' AND __deleted = 0 ORDER BY position LIMIT 1").get(t)?.id??null}function sy(e,t,r,n){let o=ny[t],s=o.nameCol;if(t==="rec"&&n){let j=hl(e,n);if(j)s=`data ->> '${j.replace(/'/g,"''")}'`}let a=s??"''",u=[],_=[];u.push("(id >= ? AND id < ?)"),_.push(r,r+gl);let m=`${t}_${r}`;if(u.push("(id >= ? AND id < ?)"),_.push(m,m+gl),s)u.push(`lower(${s}) = lower(?)`),_.push(r);let x=`SELECT id, ${a} AS label FROM ${o.table} WHERE __deleted = 0 AND (${u.join(" OR ")})`;if(o.scoped&&n)x+=" AND database_id = ?",_.push(n);return e.query(x).all(..._).map((j)=>({kind:t,id:j.id,label:j.label??""}))}function Yi(e,t,r={}){let n=r.kind?[r.kind]:iy(nn(t))?[nn(t)]:oy,o=[],s=new Set;for(let a of n)for(let u of sy(e,a,t,r.databaseId)){if(s.has(u.id))continue;s.add(u.id),o.push(u)}return o}var ny,oy,gl="{";var es=De(()=>{bt();Ye();ny={db:{table:"databases",nameCol:"name",scoped:!1,noun:"database"},prop:{table:"properties",nameCol:"name",scoped:!0,noun:"property"},rec:{table:"records",nameCol:null,scoped:!0,noun:"record"},doc:{table:"documents",nameCol:"title",scoped:!0,noun:"document"}},oy=["db","prop","rec","doc"]});function ts(e,t){if(t!==null&&e>=t)throw Error(`fracdex: ${e} >= ${t}`);if(e.endsWith("0")||t!==null&&t.endsWith("0"))throw Error(`fracdex: trailing zero in ${e}/${t}`);if(t!==null){let s=0;while((e[s]??"0")===t[s])s++;if(s>0)return t.slice(0,s)+ts(e.slice(s),t.slice(s))}let n=e===""?0:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".indexOf(e[0]),o=t===null?62:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".indexOf(t[0]);if(o-n>1)return"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"[Math.round(0.5*(n+o))];if(t!==null&&t.length>1)return t.slice(0,1);return"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"[n]+ts(e.slice(1),null)}function Bt(e,t){return ts(e??"",t)}function dr(e,t,r){if(r<=0)return[];if(r===1)return[Bt(e,t)];if(t===null){let s=Bt(e,null),a=[s];for(let u=1;u<r;u++)s=Bt(s,null),a.push(s);return a}if(e===null){let s=Bt(null,t),a=[s];for(let u=1;u<r;u++)s=Bt(null,s),a.unshift(s);return a}let n=Math.floor(r/2),o=Bt(e,t);return[...dr(e,o,n),o,...dr(o,t,r-n-1)]}function ml(e){return typeof e==="string"||typeof e==="number"||typeof e==="boolean"}function ay(e){return typeof e==="boolean"?e?1:0:e}function cy(e,t,r){let n=t.config?.database;if(!n)return r;let o=Yi(e,r,{kind:"rec",databaseId:n}),s=o.find((a)=>a.id===r);if(s)return s.id;if(o.length===1)return o[0].id;if(o.length===0){if(nn(r)==="rec")return r;throw new Z("not_found",`${t.name}: no such record in target database: ${r}`)}throw new Z("ambiguous",`${t.name}: ambiguous relation "${r}" (${o.length} matches); use a full id`)}function ly(e,t,r){let n=Yi(e,r,{kind:"doc"}),o=n.find((s)=>s.id===r);if(o)return o.id;if(n.length===1)return n[0].id;if(n.length===0){if(nn(r)==="doc")return r;throw new Z("not_found",`${t.name}: no such document: ${r}`)}throw new Z("ambiguous",`${t.name}: ambiguous document "${r}" (${n.length} matches); use a full id`)}function ns(e,t,r){switch(t.type){case"text":case"url":case"date":{if(r===null)return null;if(typeof r!=="string")throw new Z("invalid_input",`${t.name} expects a string`);return r}case"number":{if(r===null)return null;let n=typeof r==="number"?r:Number(r);if(!Number.isFinite(n))throw new Z("invalid_input",`${t.name} expects a number`);return n}case"checkbox":{if(typeof r==="boolean")return r;if(r==="true"||r===1)return!0;if(r==="false"||r===0||r===null)return!1;throw new Z("invalid_input",`${t.name} expects a boolean`)}case"select":{if(r===null)return null;let n=String(r);if(!t.config?.options?.includes(n))throw new Z("invalid_input",`${t.name}: '${n}' is not an allowed option`);return n}case"multi_select":{let n=r===null?[]:Array.isArray(r)?r:[r],o=t.config?.options??[];for(let s of n)if(!o.includes(String(s)))throw new Z("invalid_input",`${t.name}: '${s}' is not an allowed option`);return n.map(String)}case"relation":return(r===null?[]:Array.isArray(r)?r:[r]).map((o)=>cy(e,t,String(o)));case"doc":return(r===null?[]:Array.isArray(r)?r:[r]).map((o)=>ly(e,t,String(o)))}}function uy(e){let t=new Map;for(let r of e){let n=r.name.toLowerCase(),o=t.get(n);if(o)o.push(r);else t.set(n,[r])}return t}function os(e,t){let r=new Map(e.map((s)=>[s.id,s])),n=uy(e),o=[];for(let[s,a]of Object.entries(t)){let u=r.get(s);if(!u){let _=n.get(s.toLowerCase())??[];if(_.length>1)throw new Z("ambiguous",`property name "${s}" matches ${_.length} properties; use a property id`);u=_[0]}if(!u)throw new Z("not_found",`unknown property: ${s}`);o.push({prop:u,value:a})}return o}function wl(e,t,r){return os(Ct(e,t),r).map(({prop:n,value:o})=>({prop:n,value:ns(e,n,o)}))}function vl(e,t){let r=JSON.parse(e.data||"{}"),n=new Map(t.map((a)=>[a.id,a])),o={},s={};for(let[a,u]of Object.entries(r)){let _=n.get(a);if(!_)continue;o[_.name]=u,s[_.id]=u}return{id:e.id,database_id:e.database_id,values:o,cells:s}}function dy(e,t){let r=e.find((n)=>n.prop.type==="text"&&typeof n.value==="string"&&n.value);return Ot("rec",r?String(r.value):"",t)}function yl(e,t){return e.query("SELECT 1 AS ok FROM sqlite_master WHERE type = 'table' AND name = ?").get(t)!=null}function fy(e){return yl(e,"meta")&&yl(e,"crdt_changes")}function py(e,t,r,n){if(n)be(e,"records",t,"order_key",r);else e.query("UPDATE records SET order_key = ? WHERE id = ?").run(r,t)}function El(e,t){return e.query(`SELECT order_key FROM records
325
341
  WHERE database_id = ? AND __deleted = 0 AND order_key IS NOT NULL
326
- ORDER BY order_key DESC, id DESC LIMIT 1`).get(t)?.order_key??null}function Yi(e,t){return e.query(`SELECT id, database_id, created_hlc, order_key FROM records
342
+ ORDER BY order_key DESC, id DESC LIMIT 1`).get(t)?.order_key??null}function rs(e,t){return e.query(`SELECT id, database_id, created_hlc, order_key FROM records
327
343
  WHERE database_id = ? AND __deleted = 0
328
- ORDER BY order_key IS NULL, order_key, created_hlc, id`).all(t)}function oy(e,t){let r=Yi(e,t),n=lr(null,null,r.length);r.forEach((o,s)=>{if(o.order_key!==n[s])we(e,"records",o.id,"order_key",n[s])})}function vr(e,t){let r=e.query("SELECT id, database_id, data FROM records WHERE id = ? AND __deleted = 0").get(t);if(!r)return null;return _l(r,Nt(e,r.database_id))}function fl(e){return e.replace(/'/g,"''")}function un(e,t,r={}){let n=Nt(e,t),o=r.filter&&Object.keys(r.filter).length?ts(n,r.filter).map(({prop:ge,value:Le})=>({prop:ge,value:es(e,ge,Le)})):[],s=o.filter((ge)=>ul(ge.value)),a=o.filter((ge)=>!ul(ge.value)),u,_=!1;if(r.sort){let ge=r.sort;if(ge.startsWith("-"))_=!0,ge=ge.slice(1);if(ge!=="created"&&ge!=="created_hlc"){let Le=n.find((Ze)=>Ze.id===ge);if(!Le){let Ze=n.filter(($e)=>$e.name.toLowerCase()===ge.toLowerCase());if(Ze.length>1)throw new Z("ambiguous",`sort field "${ge}" matches ${Ze.length} properties; use a property id`);Le=Ze[0]}if(!Le)throw new Z("not_found",`unknown sort field: ${ge}`);u=Le}}for(let ge of s)Zi(e,t,ge.prop);if(u)Zi(e,t,u);let m=["database_id = ?","__deleted = 0"],x=[t];for(let ge of s)m.push(`data ->> '${fl(ge.prop.id)}' = ?`),x.push(Xm(ge.value));let D=r.sort==null,j=u?`data ->> '${fl(u.id)}'`:"created_hlc",Y=`SELECT id, database_id, data FROM records WHERE ${m.join(" AND ")} `+(D?"ORDER BY order_key IS NULL, order_key, id":`ORDER BY ${j} ${_?"DESC":"ASC"}, id`);if(r.limit!=null&&a.length===0)Y+=" LIMIT ?",x.push(r.limit);let de=e.query(Y).all(...x).map((ge)=>_l(ge,n));if(a.length){if(de=de.filter((ge)=>a.every((Le)=>JSON.stringify(ge.cells[Le.prop.id]??null)===JSON.stringify(Le.value))),r.limit!=null)de=de.slice(0,r.limit)}return de}var Ro,rs,To,hl,ns,ko,ml;var Lr=De(()=>{wt();dt();qr();Nr();Xi();Ye();Ro=Fe(function(t,r){let n=ry(t),o=r?[{database_id:r}]:t.query(`SELECT DISTINCT database_id FROM records
344
+ ORDER BY order_key IS NULL, order_key, created_hlc, id`).all(t)}function _y(e,t){let r=rs(e,t),n=dr(null,null,r.length);r.forEach((o,s)=>{if(o.order_key!==n[s])be(e,"records",o.id,"order_key",n[s])})}function vr(e,t){let r=e.query("SELECT id, database_id, data FROM records WHERE id = ? AND __deleted = 0").get(t);if(!r)return null;return vl(r,Ct(e,r.database_id))}function bl(e){return e.replace(/'/g,"''")}function ln(e,t,r={}){let n=Ct(e,t),o=r.filter&&Object.keys(r.filter).length?os(n,r.filter).map(({prop:ge,value:Le})=>({prop:ge,value:ns(e,ge,Le)})):[],s=o.filter((ge)=>ml(ge.value)),a=o.filter((ge)=>!ml(ge.value)),u,_=!1;if(r.sort){let ge=r.sort;if(ge.startsWith("-"))_=!0,ge=ge.slice(1);if(ge!=="created"&&ge!=="created_hlc"){let Le=n.find((Ze)=>Ze.id===ge);if(!Le){let Ze=n.filter(($e)=>$e.name.toLowerCase()===ge.toLowerCase());if(Ze.length>1)throw new Z("ambiguous",`sort field "${ge}" matches ${Ze.length} properties; use a property id`);Le=Ze[0]}if(!Le)throw new Z("not_found",`unknown sort field: ${ge}`);u=Le}}for(let ge of s)Vi(e,t,ge.prop);if(u)Vi(e,t,u);let m=["database_id = ?","__deleted = 0"],x=[t];for(let ge of s)m.push(`data ->> '${bl(ge.prop.id)}' = ?`),x.push(ay(ge.value));let D=r.sort==null,j=u?`data ->> '${bl(u.id)}'`:"created_hlc",Y=`SELECT id, database_id, data FROM records WHERE ${m.join(" AND ")} `+(D?"ORDER BY order_key IS NULL, order_key, id":`ORDER BY ${j} ${_?"DESC":"ASC"}, id`);if(r.limit!=null&&a.length===0)Y+=" LIMIT ?",x.push(r.limit);let de=e.query(Y).all(...x).map((ge)=>vl(ge,n));if(a.length){if(de=de.filter((ge)=>a.every((Le)=>JSON.stringify(ge.cells[Le.prop.id]??null)===JSON.stringify(Le.value))),r.limit!=null)de=de.slice(0,r.limit)}return de}var Ro,is,To,Sl,ss,ko,xl;var Lr=De(()=>{bt();dt();qr();Cr();es();Ye();Ro=ze(function(t,r){let n=fy(t),o=r?[{database_id:r}]:t.query(`SELECT DISTINCT database_id FROM records
329
345
  WHERE database_id IS NOT NULL AND __deleted = 0 AND order_key IS NULL`).all();for(let s of o){let a=t.query(`SELECT id FROM records
330
346
  WHERE database_id = ? AND __deleted = 0 AND order_key IS NULL
331
- ORDER BY created_hlc, id`).all(s.database_id);if(!a.length)continue;let u=gl(t,s.database_id),_=lr(u,null,a.length);a.forEach((m,x)=>ny(t,m.id,_[x],n))}}),rs=Fe(function(t,r,n){let o=ty(n,Fi(r.name,"rec")),s=Mt(gl(t,r.id),null),a=we(t,"records",o,"database_id",r.id);we(t,"records",o,"created_hlc",a.hlc),we(t,"records",o,"order_key",s);for(let{prop:u,value:_}of n)we(t,"records",o,u.id,_);return vr(t,o)}),To=Fe(function(t,r,n){let o=Pt(t,r);if(!o)throw new Z("not_found",`no such database: ${r}`);return rs(t,o,pl(t,o.id,n))});hl=Fe(function(t,r,n,o){if(o!=="before"&&o!=="after")throw new Z("invalid_input",`unknown move position: ${o}`);let s=t.query("SELECT id, database_id FROM records WHERE id = ? AND __deleted = 0").get(r);if(!s)throw new Z("not_found",`no such record: ${r}`);let a=t.query("SELECT id, database_id FROM records WHERE id = ? AND __deleted = 0").get(n);if(!a)throw new Z("not_found",`no such record: ${n}`);if(s.database_id!==a.database_id)throw new Z("invalid_input","cannot move a record across databases");if(r===n)return vr(t,r);Ro(t,s.database_id);let u=Yi(t,s.database_id).filter((D)=>D.id!==r),_=u.findIndex((D)=>D.id===n);if(_<0)throw new Z("not_found",`no such target record: ${n}`);let m=o==="before"?u[_-1]?.order_key??null:u[_].order_key,x=o==="before"?u[_].order_key:u[_+1]?.order_key??null;if(m!==null&&x!==null&&m>=x)oy(t,s.database_id),u=Yi(t,s.database_id).filter((D)=>D.id!==r),_=u.findIndex((D)=>D.id===n),m=o==="before"?u[_-1]?.order_key??null:u[_].order_key,x=o==="before"?u[_].order_key:u[_+1]?.order_key??null;return we(t,"records",r,"order_key",Mt(m,x)),vr(t,r)}),ns=Fe(function(t,r,n){let o=t.query("SELECT id, database_id, data FROM records WHERE id = ? AND __deleted = 0").get(r);if(!o)throw new Z("not_found",`no such record: ${r}`);let s=JSON.parse(o.data||"{}");for(let{prop:a,value:u}of n){let _=Object.hasOwn(s,a.id);if(!(u===void 0?!_:_&&JSON.stringify(u)===JSON.stringify(s[a.id])))we(t,"records",r,a.id,u)}return vr(t,r)}),ko=Fe(function(t,r,n){let o=t.query("SELECT id, database_id FROM records WHERE id = ? AND __deleted = 0").get(r);if(!o)throw new Z("not_found",`no such record: ${r}`);return ns(t,r,pl(t,o.database_id,n))}),ml=Fe(function(t,r){if(!t.query("SELECT id FROM records WHERE id = ? AND __deleted = 0").get(r))return!1;return we(t,"records",r,"__deleted",1),!0})});function dn(e,t){return e.query("SELECT id, text, order_key, blank_after FROM doc_blocks WHERE doc_id = ? AND __deleted = 0 ORDER BY order_key, id").all(t)}function ly(e){return Ot("blk",e.split(`
332
- `,1)[0]??"")}function uy(e,t,r){let n=ly(r.text);if(we(e,"doc_blocks",n,"doc_id",t),we(e,"doc_blocks",n,"order_key",r.order_key),r.blankAfter)we(e,"doc_blocks",n,"blank_after",r.blankAfter);we(e,"doc_blocks",n,"text",r.text)}function fn(e,t,r,n,o){let s=lr(n,o,r.length);r.forEach((a,u)=>uy(e,t,{text:a.text,order_key:s[u],blankAfter:a.blankAfter}))}function pn(e,t){if(e.query("SELECT 1 AS x FROM doc_blocks WHERE doc_id = ? LIMIT 1").get(t))return;let r=e.query("SELECT body FROM documents WHERE id = ?").get(t),n=sn(r?.body??"");if(n.length)fn(e,t,n,null,null)}function os(e,t,r){let n=dn(e,t),o=sn(r),s=Mc(n.map((_)=>_.text),o.map((_)=>_.text));for(let _ of s.deleted)we(e,"doc_blocks",n[_].id,"__deleted",1);let{items:a}=s,u=0;while(u<a.length){let _=a[u];if("keep"in _){let j=n[_.keep],Y=o[u].blankAfter;if((j.blank_after??0)!==Y)we(e,"doc_blocks",j.id,"blank_after",Y);u++;continue}let m=u;while(m<a.length&&"insert"in a[m])m++;let x=u>0?n[a[u-1].keep].order_key:null,D=m<a.length?n[a[m].keep].order_key:null;fn(e,t,o.slice(u,m),x,D),u=m}}function Tt(e,t){return e.query(`SELECT MAX(hlc) AS h FROM crdt_changes
347
+ ORDER BY created_hlc, id`).all(s.database_id);if(!a.length)continue;let u=El(t,s.database_id),_=dr(u,null,a.length);a.forEach((m,x)=>py(t,m.id,_[x],n))}}),is=ze(function(t,r,n){let o=dy(n,Mi(r.name,"rec")),s=Bt(El(t,r.id),null),a=be(t,"records",o,"database_id",r.id);be(t,"records",o,"created_hlc",a.hlc),be(t,"records",o,"order_key",s);for(let{prop:u,value:_}of n)be(t,"records",o,u.id,_);return vr(t,o)}),To=ze(function(t,r,n){let o=Pt(t,r);if(!o)throw new Z("not_found",`no such database: ${r}`);return is(t,o,wl(t,o.id,n))});Sl=ze(function(t,r,n,o){if(o!=="before"&&o!=="after")throw new Z("invalid_input",`unknown move position: ${o}`);let s=t.query("SELECT id, database_id FROM records WHERE id = ? AND __deleted = 0").get(r);if(!s)throw new Z("not_found",`no such record: ${r}`);let a=t.query("SELECT id, database_id FROM records WHERE id = ? AND __deleted = 0").get(n);if(!a)throw new Z("not_found",`no such record: ${n}`);if(s.database_id!==a.database_id)throw new Z("invalid_input","cannot move a record across databases");if(r===n)return vr(t,r);Ro(t,s.database_id);let u=rs(t,s.database_id).filter((D)=>D.id!==r),_=u.findIndex((D)=>D.id===n);if(_<0)throw new Z("not_found",`no such target record: ${n}`);let m=o==="before"?u[_-1]?.order_key??null:u[_].order_key,x=o==="before"?u[_].order_key:u[_+1]?.order_key??null;if(m!==null&&x!==null&&m>=x)_y(t,s.database_id),u=rs(t,s.database_id).filter((D)=>D.id!==r),_=u.findIndex((D)=>D.id===n),m=o==="before"?u[_-1]?.order_key??null:u[_].order_key,x=o==="before"?u[_].order_key:u[_+1]?.order_key??null;return be(t,"records",r,"order_key",Bt(m,x)),vr(t,r)}),ss=ze(function(t,r,n){let o=t.query("SELECT id, database_id, data FROM records WHERE id = ? AND __deleted = 0").get(r);if(!o)throw new Z("not_found",`no such record: ${r}`);let s=JSON.parse(o.data||"{}");for(let{prop:a,value:u}of n){let _=Object.hasOwn(s,a.id);if(!(u===void 0?!_:_&&JSON.stringify(u)===JSON.stringify(s[a.id])))be(t,"records",r,a.id,u)}return vr(t,r)}),ko=ze(function(t,r,n){let o=t.query("SELECT id, database_id FROM records WHERE id = ? AND __deleted = 0").get(r);if(!o)throw new Z("not_found",`no such record: ${r}`);return ss(t,r,wl(t,o.database_id,n))}),xl=ze(function(t,r){if(!t.query("SELECT id FROM records WHERE id = ? AND __deleted = 0").get(r))return!1;return be(t,"records",r,"__deleted",1),!0})});function un(e,t){return e.query("SELECT id, text, order_key, blank_after FROM doc_blocks WHERE doc_id = ? AND __deleted = 0 ORDER BY order_key, id").all(t)}function by(e){return Ot("blk",e.split(`
348
+ `,1)[0]??"")}function wy(e,t,r){let n=by(r.text);if(be(e,"doc_blocks",n,"doc_id",t),be(e,"doc_blocks",n,"order_key",r.order_key),r.blankAfter)be(e,"doc_blocks",n,"blank_after",r.blankAfter);be(e,"doc_blocks",n,"text",r.text)}function dn(e,t,r,n,o){let s=dr(n,o,r.length);r.forEach((a,u)=>wy(e,t,{text:a.text,order_key:s[u],blankAfter:a.blankAfter}))}function fn(e,t){if(e.query("SELECT 1 AS x FROM doc_blocks WHERE doc_id = ? LIMIT 1").get(t))return;let r=e.query("SELECT body FROM documents WHERE id = ?").get(t),n=on(r?.body??"");if(n.length)dn(e,t,n,null,null)}function as(e,t,r){let n=un(e,t),o=on(r),s=Gc(n.map((_)=>_.text),o.map((_)=>_.text));for(let _ of s.deleted)be(e,"doc_blocks",n[_].id,"__deleted",1);let{items:a}=s,u=0;while(u<a.length){let _=a[u];if("keep"in _){let j=n[_.keep],Y=o[u].blankAfter;if((j.blank_after??0)!==Y)be(e,"doc_blocks",j.id,"blank_after",Y);u++;continue}let m=u;while(m<a.length&&"insert"in a[m])m++;let x=u>0?n[a[u-1].keep].order_key:null,D=m<a.length?n[a[m].keep].order_key:null;dn(e,t,o.slice(u,m),x,D),u=m}}function Tt(e,t){return e.query(`SELECT MAX(hlc) AS h FROM crdt_changes
333
349
  WHERE (dataset = 'documents' AND row_id = ?)
334
- OR (dataset = 'doc_blocks' AND row_id IN (SELECT id FROM doc_blocks WHERE doc_id = ?))`).get(t,t).h??""}function nt(e,t){return e.query(`SELECT ${sy} FROM documents WHERE id = ? AND __deleted = 0`).get(t)}function wl(e,t={}){let r=`SELECT ${cy} FROM documents WHERE __deleted = 0`;if(t.parent_id!==void 0)return e.query(`${r} AND parent_id = ? ${Ao}`).all(t.parent_id);if(t.database_id)return e.query(`${r} AND database_id = ? ${Ao}`).all(t.database_id);return e.query(`${r} ${Ao}`).all()}function ss(e){return e===null?{clause:"parent_id IS NULL",args:[]}:{clause:"parent_id = ?",args:[e]}}function dy(e){return yl(e,"meta")&&yl(e,"crdt_changes")}function yl(e,t){return e.query("SELECT 1 AS ok FROM sqlite_master WHERE type = 'table' AND name = ?").get(t)!=null}function vl(e,t,r){let n=ss(t),o=r?" AND id <> ?":"";return e.query(`SELECT order_key FROM documents WHERE ${n.clause}${o}
350
+ OR (dataset = 'doc_blocks' AND row_id IN (SELECT id FROM doc_blocks WHERE doc_id = ?))`).get(t,t).h??""}function nt(e,t){return e.query(`SELECT ${hy} FROM documents WHERE id = ? AND __deleted = 0`).get(t)}function Rl(e,t={}){let r=`SELECT ${yy} FROM documents WHERE __deleted = 0`;if(t.parent_id!==void 0)return e.query(`${r} AND parent_id = ? ${Ao}`).all(t.parent_id);if(t.database_id)return e.query(`${r} AND database_id = ? ${Ao}`).all(t.database_id);return e.query(`${r} ${Ao}`).all()}function ls(e){return e===null?{clause:"parent_id IS NULL",args:[]}:{clause:"parent_id = ?",args:[e]}}function vy(e){return Tl(e,"meta")&&Tl(e,"crdt_changes")}function Tl(e,t){return e.query("SELECT 1 AS ok FROM sqlite_master WHERE type = 'table' AND name = ?").get(t)!=null}function Al(e,t,r){let n=ls(t),o=r?" AND id <> ?":"";return e.query(`SELECT order_key FROM documents WHERE ${n.clause}${o}
335
351
  AND __deleted = 0 AND order_key IS NOT NULL
336
- ORDER BY order_key DESC, id DESC LIMIT 1`).get(...n.args,...r?[r]:[])?.order_key??null}function El(e,t){let r=ss(t);return e.query(`SELECT id, order_key FROM documents WHERE ${r.clause} AND __deleted = 0 ${Ao}`).all(...r.args)}function fy(e,t){let r=El(e,t),n=lr(null,null,r.length);r.forEach((o,s)=>{if(o.order_key!==n[s])we(e,"documents",o.id,"order_key",n[s])})}function Sl(e,t){let r=dy(e),n=ss(t),o=e.query(`SELECT id FROM documents WHERE ${n.clause} AND __deleted = 0 AND order_key IS NULL
337
- ORDER BY created_hlc, id`).all(...n.args);if(!o.length)return;let s=lr(vl(e,t),null,o.length);o.forEach((a,u)=>{if(r)we(e,"documents",a.id,"order_key",s[u]);else e.query("UPDATE documents SET order_key = ? WHERE id = ?").run(s[u],a.id)})}function Do(e,t,r,n){let o=r;while(o){if(o===t)throw new Z("invalid_input",`cannot set parent_id: would create a cycle (${t})`);o=nt(e,o)?.parent_id??null}let s=nt(e,t);if(s&&(s.parent_id??null)!==r)we(e,"documents",t,"parent_id",r);let a;if(!n)a=Mt(vl(e,r,t),null);else{Sl(e,r);let u=()=>{let x=El(e,r).filter((j)=>j.id!==t),D=x.findIndex((j)=>j.id===n.targetId);if(D<0)throw new Z("not_found",`no such target document: ${n.targetId}`);return n.where==="before"?[x[D-1]?.order_key??null,x[D].order_key]:[x[D].order_key,x[D+1]?.order_key??null]},[_,m]=u();if(_!==null&&m!==null&&_>=m)fy(e,r),[_,m]=u();a=Mt(_,m)}we(e,"documents",t,"order_key",a)}function bl(e,t,r,n){return e.query(`SELECT id FROM ${t} WHERE ${r} = ? AND __deleted = 0`).all(n).map((o)=>o.id)}function Rl(e,t){if(t==="")return 0;let r=0,n=e.indexOf(t);while(n!==-1)r++,n=e.indexOf(t,n+t.length);return r}var iy,sy,ay,cy,is,Ao="ORDER BY order_key IS NULL, order_key, created_hlc, id",xl,as,Tl,Oo,dS,fS,pS,_S,kl;var _n=De(()=>{wt();dt();Ye();iy=["id","title","body","database_id","parent_id","created_hlc","order_key"],sy=iy.join(", "),ay=["id","title","database_id","parent_id","created_hlc","order_key"],cy=ay.join(", ");is=Fe(function(t,r){let n=Ot("doc",r.title),o=we(t,"documents",n,"title",r.title);if(we(t,"documents",n,"created_hlc",o.hlc),r.database_id!==void 0)we(t,"documents",n,"database_id",r.database_id);if(r.parent_id!==void 0)we(t,"documents",n,"parent_id",r.parent_id);if(Do(t,n,r.parent_id??null),r.body!==void 0){let s=sn(r.body);if(s.length)fn(t,n,s,null,null)}return nt(t,n)});xl=Fe(function(t){let r=t.query("SELECT DISTINCT parent_id FROM documents WHERE __deleted = 0 AND order_key IS NULL").all();for(let n of r)Sl(t,n.parent_id)});as=Fe(function(t,r,n,o){let s=nt(t,r);if(!s)throw new Z("not_found",`no such document: ${r}`);if(r===n)return s;let a=nt(t,n);if(!a)throw new Z("not_found",`no such target document: ${n}`);if(o==="into")Do(t,r,n);else Do(t,r,a.parent_id,{targetId:n,where:o});return nt(t,r)}),Tl=Fe(function(t,r,n={}){let o=nt(t,r);if(!o)throw new Z("not_found",`no such document: ${r}`);pn(t,r);let s=dn(t,r),a=n.parentId!==void 0?n.parentId:o.parent_id,u=is(t,{title:n.title??o.title,database_id:o.database_id??void 0,parent_id:a??void 0});if(s.length)fn(t,u.id,s.map((_)=>({text:_.text,blankAfter:_.blank_after})),null,null);if(a===o.parent_id)as(t,u.id,o.id,"after");return nt(t,u.id)}),Oo=Fe(function(t,r,n,o={}){let s=nt(t,r);if(!s)throw new Z("not_found",`no such document: ${r}`);if(o.ifMatch!==void 0&&Tt(t,r)!==o.ifMatch)throw new Z("stale",`stale: document changed since ${o.ifMatch}; re-read first`);if(n.title!==void 0&&n.title!==(s.title??""))we(t,"documents",r,"title",n.title);if(n.database_id!==void 0&&n.database_id!==(s.database_id??null))we(t,"documents",r,"database_id",n.database_id);if(n.parent_id!==void 0){let a=n.parent_id??null;if((nt(t,r).parent_id??null)!==a)Do(t,r,a)}if(n.body!==void 0)pn(t,r),os(t,r,n.body);return nt(t,r)}),dS=Fe(function(t,r,n){if(!nt(t,r))throw new Z("not_found",`no such document: ${r}`);if(n.ifMatch!==void 0&&Tt(t,r)!==n.ifMatch)throw new Z("stale",`stale: document changed since ${n.ifMatch}; re-read first`);if(n.old==="")throw new Z("invalid_input","--old must not be empty");pn(t,r);let o=dn(t,r),s=Cr(o.map((_)=>({text:_.text,blankAfter:_.blank_after}))),a=Rl(s,n.old);if(a===0)throw new Z("invalid_input","anchor not found: no match for --old");if(a>1&&!n.replaceAll)throw new Z("ambiguous",`${a} matches for --old; add surrounding context or use --replace-all`);if(!n.old.includes(`
352
+ ORDER BY order_key DESC, id DESC LIMIT 1`).get(...n.args,...r?[r]:[])?.order_key??null}function Dl(e,t){let r=ls(t);return e.query(`SELECT id, order_key FROM documents WHERE ${r.clause} AND __deleted = 0 ${Ao}`).all(...r.args)}function Ey(e,t){let r=Dl(e,t),n=dr(null,null,r.length);r.forEach((o,s)=>{if(o.order_key!==n[s])be(e,"documents",o.id,"order_key",n[s])})}function Ol(e,t){let r=vy(e),n=ls(t),o=e.query(`SELECT id FROM documents WHERE ${n.clause} AND __deleted = 0 AND order_key IS NULL
353
+ ORDER BY created_hlc, id`).all(...n.args);if(!o.length)return;let s=dr(Al(e,t),null,o.length);o.forEach((a,u)=>{if(r)be(e,"documents",a.id,"order_key",s[u]);else e.query("UPDATE documents SET order_key = ? WHERE id = ?").run(s[u],a.id)})}function Do(e,t,r,n){let o=r;while(o){if(o===t)throw new Z("invalid_input",`cannot set parent_id: would create a cycle (${t})`);o=nt(e,o)?.parent_id??null}let s=nt(e,t);if(s&&(s.parent_id??null)!==r)be(e,"documents",t,"parent_id",r);let a;if(!n)a=Bt(Al(e,r,t),null);else{Ol(e,r);let u=()=>{let x=Dl(e,r).filter((j)=>j.id!==t),D=x.findIndex((j)=>j.id===n.targetId);if(D<0)throw new Z("not_found",`no such target document: ${n.targetId}`);return n.where==="before"?[x[D-1]?.order_key??null,x[D].order_key]:[x[D].order_key,x[D+1]?.order_key??null]},[_,m]=u();if(_!==null&&m!==null&&_>=m)Ey(e,r),[_,m]=u();a=Bt(_,m)}be(e,"documents",t,"order_key",a)}function kl(e,t,r,n){return e.query(`SELECT id FROM ${t} WHERE ${r} = ? AND __deleted = 0`).all(n).map((o)=>o.id)}function Cl(e,t){if(t==="")return 0;let r=0,n=e.indexOf(t);while(n!==-1)r++,n=e.indexOf(t,n+t.length);return r}var gy,hy,my,yy,cs,Ao="ORDER BY order_key IS NULL, order_key, created_hlc, id",Il,us,Pl,Oo,kS,RS,AS,DS,Nl;var pn=De(()=>{bt();dt();Ye();gy=["id","title","body","database_id","parent_id","created_hlc","order_key"],hy=gy.join(", "),my=["id","title","database_id","parent_id","created_hlc","order_key"],yy=my.join(", ");cs=ze(function(t,r){let n=Ot("doc",r.title),o=be(t,"documents",n,"title",r.title);if(be(t,"documents",n,"created_hlc",o.hlc),r.database_id!==void 0)be(t,"documents",n,"database_id",r.database_id);if(r.parent_id!==void 0)be(t,"documents",n,"parent_id",r.parent_id);if(Do(t,n,r.parent_id??null),r.body!==void 0){let s=on(r.body);if(s.length)dn(t,n,s,null,null)}return nt(t,n)});Il=ze(function(t){let r=t.query("SELECT DISTINCT parent_id FROM documents WHERE __deleted = 0 AND order_key IS NULL").all();for(let n of r)Ol(t,n.parent_id)});us=ze(function(t,r,n,o){let s=nt(t,r);if(!s)throw new Z("not_found",`no such document: ${r}`);if(r===n)return s;let a=nt(t,n);if(!a)throw new Z("not_found",`no such target document: ${n}`);if(o==="into")Do(t,r,n);else Do(t,r,a.parent_id,{targetId:n,where:o});return nt(t,r)}),Pl=ze(function(t,r,n={}){let o=nt(t,r);if(!o)throw new Z("not_found",`no such document: ${r}`);fn(t,r);let s=un(t,r),a=n.parentId!==void 0?n.parentId:o.parent_id,u=cs(t,{title:n.title??o.title,database_id:o.database_id??void 0,parent_id:a??void 0});if(s.length)dn(t,u.id,s.map((_)=>({text:_.text,blankAfter:_.blank_after})),null,null);if(a===o.parent_id)us(t,u.id,o.id,"after");return nt(t,u.id)}),Oo=ze(function(t,r,n,o={}){let s=nt(t,r);if(!s)throw new Z("not_found",`no such document: ${r}`);if(o.ifMatch!==void 0&&Tt(t,r)!==o.ifMatch)throw new Z("stale",`stale: document changed since ${o.ifMatch}; re-read first`);if(n.title!==void 0&&n.title!==(s.title??""))be(t,"documents",r,"title",n.title);if(n.database_id!==void 0&&n.database_id!==(s.database_id??null))be(t,"documents",r,"database_id",n.database_id);if(n.parent_id!==void 0){let a=n.parent_id??null;if((nt(t,r).parent_id??null)!==a)Do(t,r,a)}if(n.body!==void 0)fn(t,r),as(t,r,n.body);return nt(t,r)}),kS=ze(function(t,r,n){if(!nt(t,r))throw new Z("not_found",`no such document: ${r}`);if(n.ifMatch!==void 0&&Tt(t,r)!==n.ifMatch)throw new Z("stale",`stale: document changed since ${n.ifMatch}; re-read first`);if(n.old==="")throw new Z("invalid_input","--old must not be empty");fn(t,r);let o=un(t,r),s=Nr(o.map((_)=>({text:_.text,blankAfter:_.blank_after}))),a=Cl(s,n.old);if(a===0)throw new Z("invalid_input","anchor not found: no match for --old");if(a>1&&!n.replaceAll)throw new Z("ambiguous",`${a} matches for --old; add surrounding context or use --replace-all`);if(!n.old.includes(`
338
354
 
339
355
  `)){let _=o.filter((x)=>x.text.includes(n.old)),m=_.map((x)=>n.replaceAll?x.text.replaceAll(n.old,()=>n.new):x.text.replace(n.old,()=>n.new));if(m.every((x)=>x.length>0&&!x.includes(`
340
356
 
341
- `))){let x=n.replaceAll?_:_.slice(0,1),D=!1;return x.forEach((j,Y)=>{if(m[Y]!==j.text)we(t,"doc_blocks",j.id,"text",m[Y]),D=!0}),{id:r,changed:D,replaced:n.replaceAll?a:1,version:Tt(t,r)}}}let u=n.replaceAll?s.replaceAll(n.old,()=>n.new):s.replace(n.old,()=>n.new);return os(t,r,u),{id:r,changed:u!==s,replaced:n.replaceAll?a:1,version:Tt(t,r)}}),fS=Fe(function(t,r,n){if(!nt(t,r))throw new Z("not_found",`no such document: ${r}`);if(n.edits.length===0)throw new Z("invalid_input","no edits given");if(n.ifMatch!==void 0&&Tt(t,r)!==n.ifMatch)throw new Z("stale",`stale: document changed since ${n.ifMatch}; re-read first`);pn(t,r);let o=Cr(dn(t,r).map((u)=>({text:u.text,blankAfter:u.blank_after}))),s=o,a=0;if(n.edits.forEach((u,_)=>{if(u.old==="")throw new Z("invalid_input",`edit[${_}]: old must not be empty`);let m=Rl(s,u.old);if(m===0)throw new Z("invalid_input",`edit[${_}]: anchor not found: no match for old`);if(m>1&&!u.replaceAll)throw new Z("ambiguous",`edit[${_}]: ${m} matches for old; add surrounding context or set replaceAll`);let x=u.new??"";s=u.replaceAll?s.replaceAll(u.old,()=>x):s.replace(u.old,()=>x),a+=u.replaceAll?m:1}),s!==o)os(t,r,s);return{id:r,changed:s!==o,replaced:a,version:Tt(t,r)}}),pS=Fe(function(t,r,n){if(!nt(t,r))throw new Z("not_found",`no such document: ${r}`);pn(t,r);let o=sn(n);if(o.length){let s=dn(t,r),a=s.length?s[s.length-1].order_key:null;fn(t,r,o,a,null)}return{id:r,changed:o.length>0,replaced:o.length,version:Tt(t,r)}}),_S=Fe(function(t,r,n){if(!nt(t,r))throw new Z("not_found",`no such document: ${r}`);pn(t,r);let o=sn(n);if(o.length){let s=dn(t,r),a=s.length?s[0].order_key:null;fn(t,r,o,null,a)}return{id:r,changed:o.length>0,replaced:o.length,version:Tt(t,r)}}),kl=Fe(function(t,r){if(!nt(t,r))return!1;we(t,"documents",r,"__deleted",1);for(let n of bl(t,"doc_blocks","doc_id",r))we(t,"doc_blocks",n,"__deleted",1);for(let n of bl(t,"documents","parent_id",r))we(t,"documents",n,"parent_id",null);return!0})});function Al(e){Io=e}function Dl(e,t){return Io?Io(e,t):Promise.resolve(null)}function Ol(){return Io!==null}function $n(e){let t=e.query("SELECT full_nodes, redundancy FROM blob_policy WHERE id = ? AND __deleted = 0").get(cs),r=[];if(t?.full_nodes)try{let o=JSON.parse(t.full_nodes);if(Array.isArray(o))r=o.filter((s)=>typeof s==="string")}catch{}let n=t?.redundancy==="any"?"any":"all";return{fullNodes:r,redundancy:n}}function py(e){e.query("UPDATE blob_cache SET anchored = 0").run(),e.query("DELETE FROM meta WHERE key = ?").run(_y)}function hy(e){if(!e)return[];let t=[];for(let r of e.matchAll(gy))t.push(r[1]);return t}function Pl(e){let t=new Set,r=e.query("SELECT content FROM site_files WHERE encoding = 'blob' AND __deleted = 0").all();for(let o of r)if(o.content)t.add(o.content);let n=e.query("SELECT text FROM doc_blocks WHERE __deleted = 0 AND text LIKE '%/blob/%'").all();for(let o of n)for(let s of hy(o.text))t.add(s);return t}function Cl(e){return e.query("SELECT hash, size FROM blob_cache WHERE pending = 1").all()}function Nl(e,t){return e.query("SELECT content_type FROM blob_cache WHERE hash = ?").get(t)?.content_type??null}var cs="default",Io=null,Il=(e,t)=>{yr(null,()=>{let r=new Set,n=t.filter((s)=>s&&!r.has(s)&&r.add(s)!=null);if(we(e,"blob_policy",cs,"full_nodes",n),$n(e).redundancy==null)we(e,"blob_policy",cs,"redundancy","all")}),py(e)},_y="blob_verified_at",gy;var zn=De(()=>{dt();Gt();gy=/\/blob\/([0-9a-f]{16,64})/g});function ql(e){try{let t=new URL(e),r=t.port&&t.port!==my[t.protocol]?`:${t.port}`:"";return t.hostname+r}catch{return e.trim().replace(/^[a-z]+:\/\//i,"").replace(/\/.*$/,"").replace(/:(80|443)$/,"")}}function gn(e,t,r){let n=r?.trim()||"metahub";return`s3://${ql(e)}/${t}/${n}`}var my;var Fn=De(()=>{my={"https:":"443","http:":"80"}});function yy(e){e.exec(Pc);try{e.exec(Cc)}catch{}}function $l(e){return e.query("SELECT 1 AS ok FROM sqlite_master WHERE name = 'search_fts'").get()!=null}function ht(e,t,r){return e.query(`PRAGMA table_info(${t})`).all().some((o)=>o.name===r)}function $r(e,t){return e.query("SELECT 1 AS ok FROM sqlite_master WHERE type = 'table' AND name = ?").get(t)!=null}function by(e){if(!ht(e,"records","data"))e.exec("ALTER TABLE records ADD COLUMN data TEXT NOT NULL DEFAULT '{}'");if(!ht(e,"records","order_key"))e.exec("ALTER TABLE records ADD COLUMN order_key TEXT");if(!$r(e,"record_values"))return;e.transaction(()=>{e.exec(`
357
+ `))){let x=n.replaceAll?_:_.slice(0,1),D=!1;return x.forEach((j,Y)=>{if(m[Y]!==j.text)be(t,"doc_blocks",j.id,"text",m[Y]),D=!0}),{id:r,changed:D,replaced:n.replaceAll?a:1,version:Tt(t,r)}}}let u=n.replaceAll?s.replaceAll(n.old,()=>n.new):s.replace(n.old,()=>n.new);return as(t,r,u),{id:r,changed:u!==s,replaced:n.replaceAll?a:1,version:Tt(t,r)}}),RS=ze(function(t,r,n){if(!nt(t,r))throw new Z("not_found",`no such document: ${r}`);if(n.edits.length===0)throw new Z("invalid_input","no edits given");if(n.ifMatch!==void 0&&Tt(t,r)!==n.ifMatch)throw new Z("stale",`stale: document changed since ${n.ifMatch}; re-read first`);fn(t,r);let o=Nr(un(t,r).map((u)=>({text:u.text,blankAfter:u.blank_after}))),s=o,a=0;if(n.edits.forEach((u,_)=>{if(u.old==="")throw new Z("invalid_input",`edit[${_}]: old must not be empty`);let m=Cl(s,u.old);if(m===0)throw new Z("invalid_input",`edit[${_}]: anchor not found: no match for old`);if(m>1&&!u.replaceAll)throw new Z("ambiguous",`edit[${_}]: ${m} matches for old; add surrounding context or set replaceAll`);let x=u.new??"";s=u.replaceAll?s.replaceAll(u.old,()=>x):s.replace(u.old,()=>x),a+=u.replaceAll?m:1}),s!==o)as(t,r,s);return{id:r,changed:s!==o,replaced:a,version:Tt(t,r)}}),AS=ze(function(t,r,n){if(!nt(t,r))throw new Z("not_found",`no such document: ${r}`);fn(t,r);let o=on(n);if(o.length){let s=un(t,r),a=s.length?s[s.length-1].order_key:null;dn(t,r,o,a,null)}return{id:r,changed:o.length>0,replaced:o.length,version:Tt(t,r)}}),DS=ze(function(t,r,n){if(!nt(t,r))throw new Z("not_found",`no such document: ${r}`);fn(t,r);let o=on(n);if(o.length){let s=un(t,r),a=s.length?s[0].order_key:null;dn(t,r,o,null,a)}return{id:r,changed:o.length>0,replaced:o.length,version:Tt(t,r)}}),Nl=ze(function(t,r){if(!nt(t,r))return!1;be(t,"documents",r,"__deleted",1);for(let n of kl(t,"doc_blocks","doc_id",r))be(t,"doc_blocks",n,"__deleted",1);for(let n of kl(t,"documents","parent_id",r))be(t,"documents",n,"parent_id",null);return!0})});function ql(e){Io=e}function Ll(e,t){return Io?Io(e,t):Promise.resolve(null)}function $l(){return Io!==null}function Ln(e){let t=e.query("SELECT full_nodes, redundancy FROM blob_policy WHERE id = ? AND __deleted = 0").get(ds),r=[];if(t?.full_nodes)try{let o=JSON.parse(t.full_nodes);if(Array.isArray(o))r=o.filter((s)=>typeof s==="string")}catch{}let n=t?.redundancy==="any"?"any":"all";return{fullNodes:r,redundancy:n}}function Sy(e){e.query("UPDATE blob_cache SET anchored = 0").run(),e.query("DELETE FROM meta WHERE key = ?").run(xy)}function ky(e){if(!e)return[];let t=[];for(let r of e.matchAll(Ty))t.push(r[1]);return t}function zl(e){let t=new Set,r=e.query("SELECT content FROM site_files WHERE encoding = 'blob' AND __deleted = 0").all();for(let o of r)if(o.content)t.add(o.content);let n=e.query("SELECT text FROM doc_blocks WHERE __deleted = 0 AND text LIKE '%/blob/%'").all();for(let o of n)for(let s of ky(o.text))t.add(s);return t}function Ml(e){return e.query("SELECT hash, size FROM blob_cache WHERE pending = 1").all()}function Bl(e,t){return e.query("SELECT content_type FROM blob_cache WHERE hash = ?").get(t)?.content_type??null}var ds="default",Io=null,Fl=(e,t)=>{Kt(null,()=>{let r=new Set,n=t.filter((s)=>s&&!r.has(s)&&r.add(s)!=null);if(be(e,"blob_policy",ds,"full_nodes",n),Ln(e).redundancy==null)be(e,"blob_policy",ds,"redundancy","all")}),Sy(e)},xy="blob_verified_at",Ty;var $n=De(()=>{dt();Gt();Ty=/\/blob\/([0-9a-f]{16,64})/g});function Ul(e){try{let t=new URL(e),r=t.port&&t.port!==Ry[t.protocol]?`:${t.port}`:"";return t.hostname+r}catch{return e.trim().replace(/^[a-z]+:\/\//i,"").replace(/\/.*$/,"").replace(/:(80|443)$/,"")}}function _n(e,t,r){let n=r?.trim()||"metahub";return`s3://${Ul(e)}/${t}/${n}`}var Ry;var Fn=De(()=>{Ry={"https:":"443","http:":"80"}});function Ay(e){e.exec(qc);try{e.exec(Lc)}catch{}}function jl(e){return e.query("SELECT 1 AS ok FROM sqlite_master WHERE name = 'search_fts'").get()!=null}function gt(e,t,r){return e.query(`PRAGMA table_info(${t})`).all().some((o)=>o.name===r)}function $r(e,t){return e.query("SELECT 1 AS ok FROM sqlite_master WHERE type = 'table' AND name = ?").get(t)!=null}function Dy(e){if(!gt(e,"records","data"))e.exec("ALTER TABLE records ADD COLUMN data TEXT NOT NULL DEFAULT '{}'");if(!gt(e,"records","order_key"))e.exec("ALTER TABLE records ADD COLUMN order_key TEXT");if(!$r(e,"record_values"))return;e.transaction(()=>{e.exec(`
342
358
  UPDATE records SET data = coalesce((
343
359
  SELECT json_group_object(rv.property_id, json(rv.value))
344
360
  FROM record_values rv WHERE rv.record_id = records.id
345
361
  ), '{}')
346
362
  WHERE id IN (SELECT DISTINCT record_id FROM record_values);
347
- `),e.exec("DROP TABLE record_values"),Ro(e)})(),Ro(e)}function wy(e){if(!ht(e,"shares","served_base"))e.exec("ALTER TABLE shares ADD COLUMN served_base TEXT");if(!ht(e,"shares","grants"))e.exec("ALTER TABLE shares ADD COLUMN grants TEXT");if(!ht(e,"shares","request_id"))e.exec("ALTER TABLE shares ADD COLUMN request_id TEXT");e.exec("CREATE UNIQUE INDEX IF NOT EXISTS idx_shares_request_id ON shares(request_id) WHERE request_id IS NOT NULL")}function vy(e){let t=[["token","TEXT"],["label","TEXT"],["node_id","TEXT"],["enabled","INTEGER NOT NULL DEFAULT 1"],["last_sync_at","INTEGER"],["last_success_at","INTEGER"],["last_status","TEXT"],["last_error","TEXT"],["kind","TEXT NOT NULL DEFAULT 'http'"],["config","TEXT"]];for(let[r,n]of t)if(!ht(e,"peers",r))e.exec(`ALTER TABLE peers ADD COLUMN ${r} ${n}`);e.exec("UPDATE peers SET last_success_at = last_sync_at WHERE last_success_at IS NULL AND last_status = 'ok' AND last_sync_at IS NOT NULL")}function Ey(e){if(!ht(e,"doc_blocks","blank_after"))e.exec("ALTER TABLE doc_blocks ADD COLUMN blank_after INTEGER NOT NULL DEFAULT 0")}function Sy(e){if(!ht(e,"blob_cache","pinned"))e.exec("ALTER TABLE blob_cache ADD COLUMN pinned INTEGER NOT NULL DEFAULT 0");if(!ht(e,"blob_cache","pending"))e.exec("ALTER TABLE blob_cache ADD COLUMN pending INTEGER NOT NULL DEFAULT 1");if(!ht(e,"blob_cache","anchored"))e.exec("ALTER TABLE blob_cache ADD COLUMN anchored INTEGER NOT NULL DEFAULT 0");e.exec("DROP TABLE IF EXISTS blob_presence")}function xy(e){if(!ht(e,"documents","order_key"))e.exec("ALTER TABLE documents ADD COLUMN order_key TEXT");xl(e)}function Ty(e){if(!ht(e,"crdt_changes","txn"))e.exec("ALTER TABLE crdt_changes ADD COLUMN txn TEXT");e.exec("CREATE INDEX IF NOT EXISTS idx_changes_txn ON crdt_changes(txn) WHERE txn IS NOT NULL"),e.exec("CREATE INDEX IF NOT EXISTS idx_changes_intent_receipt_hlc ON crdt_changes(hlc) WHERE dataset = 'intent_receipts'")}function ky(e){if(ht(e,"crdt_changes","seq"))return;e.transaction(()=>{if(e.exec(`
363
+ `),e.exec("DROP TABLE record_values"),Ro(e)})(),Ro(e)}function Oy(e){if(!gt(e,"shares","served_base"))e.exec("ALTER TABLE shares ADD COLUMN served_base TEXT");if(!gt(e,"shares","grants"))e.exec("ALTER TABLE shares ADD COLUMN grants TEXT");if(!gt(e,"shares","request_id"))e.exec("ALTER TABLE shares ADD COLUMN request_id TEXT");e.exec("CREATE UNIQUE INDEX IF NOT EXISTS idx_shares_request_id ON shares(request_id) WHERE request_id IS NOT NULL")}function Iy(e){let t=[["token","TEXT"],["label","TEXT"],["node_id","TEXT"],["enabled","INTEGER NOT NULL DEFAULT 1"],["last_sync_at","INTEGER"],["last_success_at","INTEGER"],["last_status","TEXT"],["last_error","TEXT"],["kind","TEXT NOT NULL DEFAULT 'http'"],["config","TEXT"]];for(let[r,n]of t)if(!gt(e,"peers",r))e.exec(`ALTER TABLE peers ADD COLUMN ${r} ${n}`);e.exec("UPDATE peers SET last_success_at = last_sync_at WHERE last_success_at IS NULL AND last_status = 'ok' AND last_sync_at IS NOT NULL")}function Py(e){if(!gt(e,"doc_blocks","blank_after"))e.exec("ALTER TABLE doc_blocks ADD COLUMN blank_after INTEGER NOT NULL DEFAULT 0")}function Ny(e){if(!gt(e,"blob_cache","pinned"))e.exec("ALTER TABLE blob_cache ADD COLUMN pinned INTEGER NOT NULL DEFAULT 0");if(!gt(e,"blob_cache","pending"))e.exec("ALTER TABLE blob_cache ADD COLUMN pending INTEGER NOT NULL DEFAULT 1");if(!gt(e,"blob_cache","anchored"))e.exec("ALTER TABLE blob_cache ADD COLUMN anchored INTEGER NOT NULL DEFAULT 0");e.exec("DROP TABLE IF EXISTS blob_presence")}function Cy(e){if(!gt(e,"documents","order_key"))e.exec("ALTER TABLE documents ADD COLUMN order_key TEXT");Il(e)}function qy(e){if(!gt(e,"crdt_changes","txn"))e.exec("ALTER TABLE crdt_changes ADD COLUMN txn TEXT");e.exec("CREATE INDEX IF NOT EXISTS idx_changes_txn ON crdt_changes(txn) WHERE txn IS NOT NULL"),e.exec("CREATE INDEX IF NOT EXISTS idx_changes_intent_receipt_hlc ON crdt_changes(hlc) WHERE dataset = 'intent_receipts'")}function Ly(e){if(gt(e,"crdt_changes","seq"))return;e.transaction(()=>{if(e.exec(`
348
364
  DROP TABLE IF EXISTS crdt_changes_new;
349
365
  CREATE TABLE crdt_changes_new (
350
366
  seq INTEGER PRIMARY KEY AUTOINCREMENT,
@@ -369,7 +385,7 @@ CREATE VIRTUAL TABLE IF NOT EXISTS search_fts USING fts5(
369
385
  WHERE dataset = 'intent_receipts';
370
386
  CREATE INDEX IF NOT EXISTS idx_changes_docref ON crdt_changes(value)
371
387
  WHERE dataset = 'doc_blocks' AND col = 'doc_id';
372
- `),$r(e,"peers"))e.exec("UPDATE peers SET push_cursor = 0, pull_cursor = 0")})()}function Ry(e){if(!$r(e,"peers"))return;let t=e.query("SELECT url, config FROM peers WHERE kind = 's3' AND config IS NOT NULL").all();if(t.length===0)return;let r=[],n=new Set;for(let a of t){let u;try{u=JSON.parse(a.config)}catch{continue}if(!u.endpoint||!u.bucket||!u.prefix)continue;let _=gn(u.endpoint,u.bucket,u.prefix);if(_===a.url){n.add(_);continue}if(n.has(_)||e.query("SELECT 1 FROM peers WHERE url = ?").get(_)||$r(e,"storage_cursors")&&e.query("SELECT 1 FROM storage_cursors WHERE peer_url = ?").get(_))continue;n.add(_),r.push({oldUrl:a.url,newUrl:_})}if(r.length===0)return;let o=new Map(r.map(({oldUrl:a,newUrl:u})=>[a,u]));e.transaction(()=>{for(let{oldUrl:a,newUrl:u}of r){if($r(e,"storage_cursors"))e.query("UPDATE storage_cursors SET peer_url = ? WHERE peer_url = ?").run(u,a);e.query("UPDATE peers SET url = ? WHERE url = ?").run(u,a)}if($r(e,"blob_policy")){let a=$n(e).fullNodes;if(a.some((u)=>o.has(u)))Il(e,a.map((u)=>o.get(u)??u))}})()}function Ay(e){if(ht(e,"databases","meta"))return;e.exec("ALTER TABLE databases ADD COLUMN meta TEXT"),e.exec(`
388
+ `),$r(e,"peers"))e.exec("UPDATE peers SET push_cursor = 0, pull_cursor = 0")})()}function $y(e){if(!$r(e,"peers"))return;let t=e.query("SELECT url, config FROM peers WHERE kind = 's3' AND config IS NOT NULL").all();if(t.length===0)return;let r=[],n=new Set;for(let a of t){let u;try{u=JSON.parse(a.config)}catch{continue}if(!u.endpoint||!u.bucket||!u.prefix)continue;let _=_n(u.endpoint,u.bucket,u.prefix);if(_===a.url){n.add(_);continue}if(n.has(_)||e.query("SELECT 1 FROM peers WHERE url = ?").get(_)||$r(e,"storage_cursors")&&e.query("SELECT 1 FROM storage_cursors WHERE peer_url = ?").get(_))continue;n.add(_),r.push({oldUrl:a.url,newUrl:_})}if(r.length===0)return;let o=new Map(r.map(({oldUrl:a,newUrl:u})=>[a,u]));e.transaction(()=>{for(let{oldUrl:a,newUrl:u}of r){if($r(e,"storage_cursors"))e.query("UPDATE storage_cursors SET peer_url = ? WHERE peer_url = ?").run(u,a);e.query("UPDATE peers SET url = ? WHERE url = ?").run(u,a)}if($r(e,"blob_policy")){let a=Ln(e).fullNodes;if(a.some((u)=>o.has(u)))Fl(e,a.map((u)=>o.get(u)??u))}})()}function Fy(e){if(gt(e,"databases","meta"))return;e.exec("ALTER TABLE databases ADD COLUMN meta TEXT"),e.exec(`
373
389
  UPDATE databases SET meta = (
374
390
  SELECT c.value FROM crdt_changes c
375
391
  WHERE c.dataset = 'databases' AND c.col = 'meta' AND c.row_id = databases.id
@@ -378,7 +394,7 @@ CREATE VIRTUAL TABLE IF NOT EXISTS search_fts USING fts5(
378
394
  WHERE id IN (
379
395
  SELECT DISTINCT row_id FROM crdt_changes WHERE dataset = 'databases' AND col = 'meta'
380
396
  )
381
- `)}function Dy(e){let t=(r,n)=>{e.exec(`
397
+ `)}function zy(e){let t=(r,n)=>{e.exec(`
382
398
  UPDATE sites SET ${r} = COALESCE((
383
399
  SELECT json_extract(c.value, '$') FROM crdt_changes c
384
400
  WHERE c.dataset = 'sites' AND c.col = '${r}' AND c.row_id = sites.id
@@ -387,10 +403,10 @@ CREATE VIRTUAL TABLE IF NOT EXISTS search_fts USING fts5(
387
403
  WHERE id IN (
388
404
  SELECT DISTINCT row_id FROM crdt_changes WHERE dataset = 'sites' AND col = '${r}'
389
405
  )
390
- `)};if(!ht(e,"sites","visibility"))e.exec("ALTER TABLE sites ADD COLUMN visibility TEXT"),t("visibility","NULL");if(!ht(e,"sites","spa"))e.exec("ALTER TABLE sites ADD COLUMN spa INTEGER NOT NULL DEFAULT 0"),t("spa","0");if(!ht(e,"sites","public_grants"))e.exec("ALTER TABLE sites ADD COLUMN public_grants TEXT"),t("public_grants","NULL")}function Oy(e){if(!$r(e,"site_channels"))return;let t=e.query("SELECT value FROM meta WHERE key = ?").get(Ll),r=t?Number(t.value):0,n=e.query(`SELECT seq, ${It} FROM crdt_changes
391
- WHERE dataset = 'site_channels' AND seq > ? ORDER BY seq`).all(r);if(n.length===0)return;e.transaction((o)=>{for(let s of o)So(e,s);e.query("INSERT INTO meta (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(Ll,String(o[o.length-1].seq))})(n)}function ls(e){yy(e),Ty(e),Ay(e),ky(e),by(e),vy(e),Ry(e),Ey(e),xy(e),Sy(e),wy(e),Dy(e),Oy(e)}var Ll="site_channels_replay_seq";var Po=De(()=>{Lr();_n();zn();Fn();dt()});function ce(e,t,r){function n(u,_){if(!u._zod)Object.defineProperty(u,"_zod",{value:{def:_,constr:a,traits:new Set},enumerable:!1});if(u._zod.traits.has(e))return;u._zod.traits.add(e),t(u,_);let m=a.prototype,x=Object.keys(m);for(let D=0;D<x.length;D++){let j=x[D];if(!(j in u))u[j]=m[j].bind(u)}}let o=r?.Parent??Object;class s extends o{}Object.defineProperty(s,"name",{value:e});function a(u){var _;let m=r?.Parent?new s:this;n(m,u),(_=m._zod).deferred??(_.deferred=[]);for(let x of m._zod.deferred)x();return m}return Object.defineProperty(a,"init",{value:n}),Object.defineProperty(a,Symbol.hasInstance,{value:(u)=>{if(r?.Parent&&u instanceof r.Parent)return!0;return u?._zod?.traits?.has(e)}}),Object.defineProperty(a,"name",{value:e}),a}function Kt(e){if(e)Object.assign(hn,e);return hn}var zl,RS,ur,Mn,hn;var zr=De(()=>{RS=Symbol("zod_brand");ur=class ur extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}};Mn=class Mn extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`);this.name="ZodEncodeError"}};(zl=globalThis).__zod_globalConfig??(zl.__zod_globalConfig={});hn=globalThis.__zod_globalConfig});function No(e){let t=Object.values(e).filter((n)=>typeof n==="number");return Object.entries(e).filter(([n,o])=>t.indexOf(+n)===-1).map(([n,o])=>o)}function ds(e,t="|"){return e.map((r)=>gs(r)).join(t)}function Un(e,t){if(typeof t==="bigint")return t.toString();return t}function qo(e){return{get value(){{let r=e();return Object.defineProperty(this,"value",{value:r}),r}throw Error("cached value already set")}}}function Lo(e){return e===null||e===void 0}function $o(e){let t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function Ml(e,t){let r=e/t,n=Math.round(r),o=Number.EPSILON*Math.max(Math.abs(r),1);if(Math.abs(r-n)<o)return 0;return r-n}function Ve(e,t,r){let n=void 0;Object.defineProperty(e,t,{get(){if(n===Fl)return;if(n===void 0)n=Fl,n=r();return n},set(o){Object.defineProperty(e,t,{value:o})},configurable:!0})}function Fr(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function Er(...e){let t={};for(let r of e){let n=Object.getOwnPropertyDescriptors(r);Object.assign(t,n)}return Object.defineProperties({},t)}function fs(e){return JSON.stringify(e)}function Bl(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}function Bn(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function mn(e){if(Bn(e)===!1)return!1;let t=e.constructor;if(t===void 0)return!0;if(typeof t!=="function")return!0;let r=t.prototype;if(Bn(r)===!1)return!1;if(Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)return!1;return!0}function _s(e){if(mn(e))return{...e};if(Array.isArray(e))return[...e];if(e instanceof Map)return new Map(e);if(e instanceof Set)return new Set(e);return e}function Sr(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function tr(e,t,r){let n=new e._zod.constr(t??e._zod.def);if(!t||r?.parent)n._zod.parent=e;return n}function Ce(e){let t=e;if(!t)return{};if(typeof t==="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}if(delete t.message,typeof t.error==="string")return{...t,error:()=>t.error};return t}function gs(e){if(typeof e==="bigint")return e.toString()+"n";if(typeof e==="string")return`"${e}"`;return`${e}`}function Hl(e){return Object.keys(e).filter((t)=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}function Iy(e,t){let r=e._zod.def,n=r.checks;if(n&&n.length>0)throw Error(".pick() cannot be used on object schemas containing refinements");let s=Er(e._zod.def,{get shape(){let a={};for(let u in t){if(!(u in r.shape))throw Error(`Unrecognized key: "${u}"`);if(!t[u])continue;a[u]=r.shape[u]}return Fr(this,"shape",a),a},checks:[]});return tr(e,s)}function Py(e,t){let r=e._zod.def,n=r.checks;if(n&&n.length>0)throw Error(".omit() cannot be used on object schemas containing refinements");let s=Er(e._zod.def,{get shape(){let a={...e._zod.def.shape};for(let u in t){if(!(u in r.shape))throw Error(`Unrecognized key: "${u}"`);if(!t[u])continue;delete a[u]}return Fr(this,"shape",a),a},checks:[]});return tr(e,s)}function Cy(e,t){if(!mn(t))throw Error("Invalid input to extend: expected a plain object");let r=e._zod.def.checks;if(r&&r.length>0){let s=e._zod.def.shape;for(let a in t)if(Object.getOwnPropertyDescriptor(s,a)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let o=Er(e._zod.def,{get shape(){let s={...e._zod.def.shape,...t};return Fr(this,"shape",s),s}});return tr(e,o)}function Ny(e,t){if(!mn(t))throw Error("Invalid input to safeExtend: expected a plain object");let r=Er(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return Fr(this,"shape",n),n}});return tr(e,r)}function qy(e,t){if(e._zod.def.checks?.length)throw Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let r=Er(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t._zod.def.shape};return Fr(this,"shape",n),n},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return tr(e,r)}function Ly(e,t,r){let o=t._zod.def.checks;if(o&&o.length>0)throw Error(".partial() cannot be used on object schemas containing refinements");let a=Er(t._zod.def,{get shape(){let u=t._zod.def.shape,_={...u};if(r)for(let m in r){if(!(m in u))throw Error(`Unrecognized key: "${m}"`);if(!r[m])continue;_[m]=e?new e({type:"optional",innerType:u[m]}):u[m]}else for(let m in u)_[m]=e?new e({type:"optional",innerType:u[m]}):u[m];return Fr(this,"shape",_),_},checks:[]});return tr(t,a)}function $y(e,t,r){let n=Er(t._zod.def,{get shape(){let o=t._zod.def.shape,s={...o};if(r)for(let a in r){if(!(a in s))throw Error(`Unrecognized key: "${a}"`);if(!r[a])continue;s[a]=new e({type:"nonoptional",innerType:o[a]})}else for(let a in o)s[a]=new e({type:"nonoptional",innerType:o[a]});return Fr(this,"shape",s),s}});return tr(t,n)}function Mr(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function Zl(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue===!1)return!0;return!1}function zo(e,t){return t.map((r)=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(e),r})}function Co(e){return typeof e==="string"?e:e?.message}function dr(e,t,r){let n=e.message?e.message:Co(e.inst?._zod.def?.error?.(e))??Co(t?.error?.(e))??Co(r.customError?.(e))??Co(r.localeError?.(e))??"Invalid input",{inst:o,continue:s,input:a,...u}=e;if(u.path??(u.path=[]),u.message=n,t?.reportInput)u.input=a;return u}function Fo(e){if(Array.isArray(e))return"array";if(typeof e==="string")return"string";return"unknown"}function Gl(e){let t=typeof e;switch(t){case"number":return Number.isNaN(e)?"nan":"number";case"object":{if(e===null)return"null";if(Array.isArray(e))return"array";let r=e;if(r&&Object.getPrototypeOf(r)!==Object.prototype&&"constructor"in r&&r.constructor)return r.constructor.name}}return t}function Br(...e){let[t,r,n]=e;if(typeof t==="string")return{message:t,code:"custom",input:r,inst:n};return{...t}}var Fl,ps,Ul,jl,Wl;var Vt=De(()=>{zr();Fl=Symbol("evaluating");ps="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};Ul=qo(()=>{if(hn.jitless)return!1;if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(e){return!1}});jl=new Set(["string","number","symbol"]);Wl={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-340282346638528860000000000000000000000,340282346638528860000000000000000000000],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]}});function Vl(e,t=(r)=>r.message){let r={},n=[];for(let o of e.issues)if(o.path.length>0)r[o.path[0]]=r[o.path[0]]||[],r[o.path[0]].push(t(o));else n.push(t(o));return{formErrors:n,fieldErrors:r}}function Jl(e,t=(r)=>r.message){let r={_errors:[]},n=(o,s=[])=>{for(let a of o.issues)if(a.code==="invalid_union"&&a.errors.length)a.errors.map((u)=>n({issues:u},[...s,...a.path]));else if(a.code==="invalid_key")n({issues:a.issues},[...s,...a.path]);else if(a.code==="invalid_element")n({issues:a.issues},[...s,...a.path]);else{let u=[...s,...a.path];if(u.length===0)r._errors.push(t(a));else{let _=r,m=0;while(m<u.length){let x=u[m];if(m!==u.length-1)_[x]=_[x]||{_errors:[]};else _[x]=_[x]||{_errors:[]},_[x]._errors.push(t(a));_=_[x],m++}}}};return n(e),r}var Kl=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,Un,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Mo,hs;var ms=De(()=>{zr();Vt();Mo=ce("$ZodError",Kl),hs=ce("$ZodError",Kl,{Parent:Error})});var Bo=(e)=>(t,r,n,o)=>{let s=n?{...n,async:!1}:{async:!1},a=t._zod.run({value:r,issues:[]},s);if(a instanceof Promise)throw new ur;if(a.issues.length){let u=new(o?.Err??e)(a.issues.map((_)=>dr(_,s,Kt())));throw ps(u,o?.callee),u}return a.value},Uo=(e)=>async(t,r,n,o)=>{let s=n?{...n,async:!0}:{async:!0},a=t._zod.run({value:r,issues:[]},s);if(a instanceof Promise)a=await a;if(a.issues.length){let u=new(o?.Err??e)(a.issues.map((_)=>dr(_,s,Kt())));throw ps(u,o?.callee),u}return a.value},jn=(e)=>(t,r,n)=>{let o=n?{...n,async:!1}:{async:!1},s=t._zod.run({value:r,issues:[]},o);if(s instanceof Promise)throw new ur;return s.issues.length?{success:!1,error:new(e??Mo)(s.issues.map((a)=>dr(a,o,Kt())))}:{success:!0,data:s.value}},Xl,Hn=(e)=>async(t,r,n)=>{let o=n?{...n,async:!0}:{async:!0},s=t._zod.run({value:r,issues:[]},o);if(s instanceof Promise)s=await s;return s.issues.length?{success:!1,error:new e(s.issues.map((a)=>dr(a,o,Kt())))}:{success:!0,data:s.value}},Ql,Yl=(e)=>(t,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return Bo(e)(t,r,o)},eu=(e)=>(t,r,n)=>Bo(e)(t,r,n),tu=(e)=>async(t,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return Uo(e)(t,r,o)},ru=(e)=>async(t,r,n)=>Uo(e)(t,r,n),nu=(e)=>(t,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return jn(e)(t,r,o)},ou=(e)=>(t,r,n)=>jn(e)(t,r,n),iu=(e)=>async(t,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return Hn(e)(t,r,o)},su=(e)=>async(t,r,n)=>Hn(e)(t,r,n);var ys=De(()=>{zr();ms();Vt();Xl=jn(hs),Ql=Hn(hs)});function hu(){return new RegExp(Fy,"u")}function ku(e){return typeof e.precision==="number"?e.precision===-1?"(?:[01]\\d|2[0-3]):[0-5]\\d":e.precision===0?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d":`(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{${e.precision}}`:"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function Ru(e){return new RegExp(`^${ku(e)}$`)}function Au(e){let t=ku({precision:e.precision}),r=["Z"];if(e.local)r.push("");if(e.offset)r.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let n=`${t}(?:${r.join("|")})`;return new RegExp(`^${xu}T(?:${n})$`)}var au,cu,lu,uu,du,fu,pu,_u,bs=(e)=>{if(!e)return/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)},gu,Fy="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",mu,yu,bu,wu,vu,ws,Eu,Su,xu="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",Tu,Du=(e)=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},Ou,Iu,Pu,Cu,Nu;var Ho=De(()=>{au=/^[cC][0-9a-z]{6,}$/,cu=/^[0-9a-z]+$/,lu=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,uu=/^[0-9a-vA-V]{20}$/,du=/^[A-Za-z0-9]{27}$/,fu=/^[a-zA-Z0-9_-]{21}$/,pu=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,_u=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,gu=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;mu=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,yu=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,bu=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,wu=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,vu=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,ws=/^[A-Za-z0-9_-]*$/,Eu=/^https?$/,Su=/^\+[1-9]\d{6,14}$/,Tu=new RegExp(`^${xu}$`);Ou=/^-?\d+$/,Iu=/^-?\d+(?:\.\d+)?$/,Pu=/^(?:true|false)$/i,Cu=/^[^A-Z]*$/,Nu=/^[^a-z]*$/});var mt,qu,vs,Es,Lu,$u,zu,Fu,Mu,Wn,Bu,Uu,ju,Hu,Wu,Zu,Gu;var Wo=De(()=>{zr();Ho();Vt();mt=ce("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),qu={number:"number",bigint:"bigint",object:"date"},vs=ce("$ZodCheckLessThan",(e,t)=>{mt.init(e,t);let r=qu[typeof t.value];e._zod.onattach.push((n)=>{let o=n._zod.bag,s=(t.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;if(t.value<s)if(t.inclusive)o.maximum=t.value;else o.exclusiveMaximum=t.value}),e._zod.check=(n)=>{if(t.inclusive?n.value<=t.value:n.value<t.value)return;n.issues.push({origin:r,code:"too_big",maximum:typeof t.value==="object"?t.value.getTime():t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Es=ce("$ZodCheckGreaterThan",(e,t)=>{mt.init(e,t);let r=qu[typeof t.value];e._zod.onattach.push((n)=>{let o=n._zod.bag,s=(t.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if(t.value>s)if(t.inclusive)o.minimum=t.value;else o.exclusiveMinimum=t.value}),e._zod.check=(n)=>{if(t.inclusive?n.value>=t.value:n.value>t.value)return;n.issues.push({origin:r,code:"too_small",minimum:typeof t.value==="object"?t.value.getTime():t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Lu=ce("$ZodCheckMultipleOf",(e,t)=>{mt.init(e,t),e._zod.onattach.push((r)=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=(r)=>{if(typeof r.value!==typeof t.value)throw Error("Cannot mix number and bigint in multiple_of check.");if(typeof r.value==="bigint"?r.value%t.value===BigInt(0):Ml(r.value,t.value)===0)return;r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}}),$u=ce("$ZodCheckNumberFormat",(e,t)=>{mt.init(e,t),t.format=t.format||"float64";let r=t.format?.includes("int"),n=r?"int":"number",[o,s]=Wl[t.format];e._zod.onattach.push((a)=>{let u=a._zod.bag;if(u.format=t.format,u.minimum=o,u.maximum=s,r)u.pattern=Ou}),e._zod.check=(a)=>{let u=a.value;if(r){if(!Number.isInteger(u)){a.issues.push({expected:n,format:t.format,code:"invalid_type",continue:!1,input:u,inst:e});return}if(!Number.isSafeInteger(u)){if(u>0)a.issues.push({input:u,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,inclusive:!0,continue:!t.abort});else a.issues.push({input:u,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,inclusive:!0,continue:!t.abort});return}}if(u<o)a.issues.push({origin:"number",input:u,code:"too_small",minimum:o,inclusive:!0,inst:e,continue:!t.abort});if(u>s)a.issues.push({origin:"number",input:u,code:"too_big",maximum:s,inclusive:!0,inst:e,continue:!t.abort})}}),zu=ce("$ZodCheckMaxLength",(e,t)=>{var r;mt.init(e,t),(r=e._zod.def).when??(r.when=(n)=>{let o=n.value;return!Lo(o)&&o.length!==void 0}),e._zod.onattach.push((n)=>{let o=n._zod.bag.maximum??Number.POSITIVE_INFINITY;if(t.maximum<o)n._zod.bag.maximum=t.maximum}),e._zod.check=(n)=>{let o=n.value;if(o.length<=t.maximum)return;let a=Fo(o);n.issues.push({origin:a,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),Fu=ce("$ZodCheckMinLength",(e,t)=>{var r;mt.init(e,t),(r=e._zod.def).when??(r.when=(n)=>{let o=n.value;return!Lo(o)&&o.length!==void 0}),e._zod.onattach.push((n)=>{let o=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(t.minimum>o)n._zod.bag.minimum=t.minimum}),e._zod.check=(n)=>{let o=n.value;if(o.length>=t.minimum)return;let a=Fo(o);n.issues.push({origin:a,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),Mu=ce("$ZodCheckLengthEquals",(e,t)=>{var r;mt.init(e,t),(r=e._zod.def).when??(r.when=(n)=>{let o=n.value;return!Lo(o)&&o.length!==void 0}),e._zod.onattach.push((n)=>{let o=n._zod.bag;o.minimum=t.length,o.maximum=t.length,o.length=t.length}),e._zod.check=(n)=>{let o=n.value,s=o.length;if(s===t.length)return;let a=Fo(o),u=s>t.length;n.issues.push({origin:a,...u?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),Wn=ce("$ZodCheckStringFormat",(e,t)=>{var r,n;if(mt.init(e,t),e._zod.onattach.push((o)=>{let s=o._zod.bag;if(s.format=t.format,t.pattern)s.patterns??(s.patterns=new Set),s.patterns.add(t.pattern)}),t.pattern)(r=e._zod).check??(r.check=(o)=>{if(t.pattern.lastIndex=0,t.pattern.test(o.value))return;o.issues.push({origin:"string",code:"invalid_format",format:t.format,input:o.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})});else(n=e._zod).check??(n.check=()=>{})}),Bu=ce("$ZodCheckRegex",(e,t)=>{Wn.init(e,t),e._zod.check=(r)=>{if(t.pattern.lastIndex=0,t.pattern.test(r.value))return;r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),Uu=ce("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=Cu),Wn.init(e,t)}),ju=ce("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=Nu),Wn.init(e,t)}),Hu=ce("$ZodCheckIncludes",(e,t)=>{mt.init(e,t);let r=Sr(t.includes),n=new RegExp(typeof t.position==="number"?`^.{${t.position}}${r}`:r);t.pattern=n,e._zod.onattach.push((o)=>{let s=o._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(n)}),e._zod.check=(o)=>{if(o.value.includes(t.includes,t.position))return;o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:o.value,inst:e,continue:!t.abort})}}),Wu=ce("$ZodCheckStartsWith",(e,t)=>{mt.init(e,t);let r=new RegExp(`^${Sr(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.onattach.push((n)=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),e._zod.check=(n)=>{if(n.value.startsWith(t.prefix))return;n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),Zu=ce("$ZodCheckEndsWith",(e,t)=>{mt.init(e,t);let r=new RegExp(`.*${Sr(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.onattach.push((n)=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),e._zod.check=(n)=>{if(n.value.endsWith(t.suffix))return;n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}}),Gu=ce("$ZodCheckOverwrite",(e,t)=>{mt.init(e,t),e._zod.check=(r)=>{r.value=t.tx(r.value)}})});class Ss{constructor(e=[]){if(this.content=[],this.indent=0,this)this.args=e}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e==="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let r=e.split(`
406
+ `)};if(!gt(e,"sites","visibility"))e.exec("ALTER TABLE sites ADD COLUMN visibility TEXT"),t("visibility","NULL");if(!gt(e,"sites","spa"))e.exec("ALTER TABLE sites ADD COLUMN spa INTEGER NOT NULL DEFAULT 0"),t("spa","0");if(!gt(e,"sites","public_grants"))e.exec("ALTER TABLE sites ADD COLUMN public_grants TEXT"),t("public_grants","NULL")}function Hl(e,t){if(!$r(e,t))return;let r=`${t}_replay_seq`,n=e.query("SELECT value FROM meta WHERE key = ?").get(r),o=n?Number(n.value):0,s=e.query(`SELECT seq, ${It} FROM crdt_changes
407
+ WHERE dataset = ? AND seq > ? ORDER BY seq`).all(t,o);if(s.length===0)return;e.transaction((a)=>{for(let u of a)So(e,u);e.query("INSERT INTO meta (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(r,String(a[a.length-1].seq))})(s)}function My(e){Hl(e,"site_channels")}function By(e){Hl(e,"nodes")}function fs(e){Ay(e),qy(e),Fy(e),Ly(e),Dy(e),Iy(e),$y(e),Py(e),Cy(e),Ny(e),Oy(e),zy(e),My(e),By(e)}var Po=De(()=>{Lr();pn();$n();Fn();dt()});function ce(e,t,r){function n(u,_){if(!u._zod)Object.defineProperty(u,"_zod",{value:{def:_,constr:a,traits:new Set},enumerable:!1});if(u._zod.traits.has(e))return;u._zod.traits.add(e),t(u,_);let m=a.prototype,x=Object.keys(m);for(let D=0;D<x.length;D++){let j=x[D];if(!(j in u))u[j]=m[j].bind(u)}}let o=r?.Parent??Object;class s extends o{}Object.defineProperty(s,"name",{value:e});function a(u){var _;let m=r?.Parent?new s:this;n(m,u),(_=m._zod).deferred??(_.deferred=[]);for(let x of m._zod.deferred)x();return m}return Object.defineProperty(a,"init",{value:n}),Object.defineProperty(a,Symbol.hasInstance,{value:(u)=>{if(r?.Parent&&u instanceof r.Parent)return!0;return u?._zod?.traits?.has(e)}}),Object.defineProperty(a,"name",{value:e}),a}function Vt(e){if(e)Object.assign(gn,e);return gn}var Wl,US,fr,zn,gn;var Fr=De(()=>{US=Symbol("zod_brand");fr=class fr extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}};zn=class zn extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`);this.name="ZodEncodeError"}};(Wl=globalThis).__zod_globalConfig??(Wl.__zod_globalConfig={});gn=globalThis.__zod_globalConfig});function Co(e){let t=Object.values(e).filter((n)=>typeof n==="number");return Object.entries(e).filter(([n,o])=>t.indexOf(+n)===-1).map(([n,o])=>o)}function _s(e,t="|"){return e.map((r)=>ys(r)).join(t)}function Bn(e,t){if(typeof t==="bigint")return t.toString();return t}function qo(e){return{get value(){{let r=e();return Object.defineProperty(this,"value",{value:r}),r}throw Error("cached value already set")}}}function Lo(e){return e===null||e===void 0}function $o(e){let t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function Gl(e,t){let r=e/t,n=Math.round(r),o=Number.EPSILON*Math.max(Math.abs(r),1);if(Math.abs(r-n)<o)return 0;return r-n}function Ve(e,t,r){let n=void 0;Object.defineProperty(e,t,{get(){if(n===Zl)return;if(n===void 0)n=Zl,n=r();return n},set(o){Object.defineProperty(e,t,{value:o})},configurable:!0})}function zr(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function Er(...e){let t={};for(let r of e){let n=Object.getOwnPropertyDescriptors(r);Object.assign(t,n)}return Object.defineProperties({},t)}function gs(e){return JSON.stringify(e)}function Kl(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}function Mn(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function hn(e){if(Mn(e)===!1)return!1;let t=e.constructor;if(t===void 0)return!0;if(typeof t!=="function")return!0;let r=t.prototype;if(Mn(r)===!1)return!1;if(Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)return!1;return!0}function ms(e){if(hn(e))return{...e};if(Array.isArray(e))return[...e];if(e instanceof Map)return new Map(e);if(e instanceof Set)return new Set(e);return e}function Sr(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function nr(e,t,r){let n=new e._zod.constr(t??e._zod.def);if(!t||r?.parent)n._zod.parent=e;return n}function Ne(e){let t=e;if(!t)return{};if(typeof t==="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}if(delete t.message,typeof t.error==="string")return{...t,error:()=>t.error};return t}function ys(e){if(typeof e==="bigint")return e.toString()+"n";if(typeof e==="string")return`"${e}"`;return`${e}`}function Xl(e){return Object.keys(e).filter((t)=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}function Uy(e,t){let r=e._zod.def,n=r.checks;if(n&&n.length>0)throw Error(".pick() cannot be used on object schemas containing refinements");let s=Er(e._zod.def,{get shape(){let a={};for(let u in t){if(!(u in r.shape))throw Error(`Unrecognized key: "${u}"`);if(!t[u])continue;a[u]=r.shape[u]}return zr(this,"shape",a),a},checks:[]});return nr(e,s)}function jy(e,t){let r=e._zod.def,n=r.checks;if(n&&n.length>0)throw Error(".omit() cannot be used on object schemas containing refinements");let s=Er(e._zod.def,{get shape(){let a={...e._zod.def.shape};for(let u in t){if(!(u in r.shape))throw Error(`Unrecognized key: "${u}"`);if(!t[u])continue;delete a[u]}return zr(this,"shape",a),a},checks:[]});return nr(e,s)}function Hy(e,t){if(!hn(t))throw Error("Invalid input to extend: expected a plain object");let r=e._zod.def.checks;if(r&&r.length>0){let s=e._zod.def.shape;for(let a in t)if(Object.getOwnPropertyDescriptor(s,a)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let o=Er(e._zod.def,{get shape(){let s={...e._zod.def.shape,...t};return zr(this,"shape",s),s}});return nr(e,o)}function Wy(e,t){if(!hn(t))throw Error("Invalid input to safeExtend: expected a plain object");let r=Er(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return zr(this,"shape",n),n}});return nr(e,r)}function Zy(e,t){if(e._zod.def.checks?.length)throw Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let r=Er(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t._zod.def.shape};return zr(this,"shape",n),n},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return nr(e,r)}function Gy(e,t,r){let o=t._zod.def.checks;if(o&&o.length>0)throw Error(".partial() cannot be used on object schemas containing refinements");let a=Er(t._zod.def,{get shape(){let u=t._zod.def.shape,_={...u};if(r)for(let m in r){if(!(m in u))throw Error(`Unrecognized key: "${m}"`);if(!r[m])continue;_[m]=e?new e({type:"optional",innerType:u[m]}):u[m]}else for(let m in u)_[m]=e?new e({type:"optional",innerType:u[m]}):u[m];return zr(this,"shape",_),_},checks:[]});return nr(t,a)}function Ky(e,t,r){let n=Er(t._zod.def,{get shape(){let o=t._zod.def.shape,s={...o};if(r)for(let a in r){if(!(a in s))throw Error(`Unrecognized key: "${a}"`);if(!r[a])continue;s[a]=new e({type:"nonoptional",innerType:o[a]})}else for(let a in o)s[a]=new e({type:"nonoptional",innerType:o[a]});return zr(this,"shape",s),s}});return nr(t,n)}function Mr(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function Yl(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue===!1)return!0;return!1}function Fo(e,t){return t.map((r)=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(e),r})}function No(e){return typeof e==="string"?e:e?.message}function pr(e,t,r){let n=e.message?e.message:No(e.inst?._zod.def?.error?.(e))??No(t?.error?.(e))??No(r.customError?.(e))??No(r.localeError?.(e))??"Invalid input",{inst:o,continue:s,input:a,...u}=e;if(u.path??(u.path=[]),u.message=n,t?.reportInput)u.input=a;return u}function zo(e){if(Array.isArray(e))return"array";if(typeof e==="string")return"string";return"unknown"}function eu(e){let t=typeof e;switch(t){case"number":return Number.isNaN(e)?"nan":"number";case"object":{if(e===null)return"null";if(Array.isArray(e))return"array";let r=e;if(r&&Object.getPrototypeOf(r)!==Object.prototype&&"constructor"in r&&r.constructor)return r.constructor.name}}return t}function Br(...e){let[t,r,n]=e;if(typeof t==="string")return{message:t,code:"custom",input:r,inst:n};return{...t}}var Zl,hs,Vl,Jl,Ql;var Jt=De(()=>{Fr();Zl=Symbol("evaluating");hs="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};Vl=qo(()=>{if(gn.jitless)return!1;if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(e){return!1}});Jl=new Set(["string","number","symbol"]);Ql={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-340282346638528860000000000000000000000,340282346638528860000000000000000000000],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]}});function ru(e,t=(r)=>r.message){let r={},n=[];for(let o of e.issues)if(o.path.length>0)r[o.path[0]]=r[o.path[0]]||[],r[o.path[0]].push(t(o));else n.push(t(o));return{formErrors:n,fieldErrors:r}}function nu(e,t=(r)=>r.message){let r={_errors:[]},n=(o,s=[])=>{for(let a of o.issues)if(a.code==="invalid_union"&&a.errors.length)a.errors.map((u)=>n({issues:u},[...s,...a.path]));else if(a.code==="invalid_key")n({issues:a.issues},[...s,...a.path]);else if(a.code==="invalid_element")n({issues:a.issues},[...s,...a.path]);else{let u=[...s,...a.path];if(u.length===0)r._errors.push(t(a));else{let _=r,m=0;while(m<u.length){let x=u[m];if(m!==u.length-1)_[x]=_[x]||{_errors:[]};else _[x]=_[x]||{_errors:[]},_[x]._errors.push(t(a));_=_[x],m++}}}};return n(e),r}var tu=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,Bn,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Mo,bs;var ws=De(()=>{Fr();Jt();Mo=ce("$ZodError",tu),bs=ce("$ZodError",tu,{Parent:Error})});var Bo=(e)=>(t,r,n,o)=>{let s=n?{...n,async:!1}:{async:!1},a=t._zod.run({value:r,issues:[]},s);if(a instanceof Promise)throw new fr;if(a.issues.length){let u=new(o?.Err??e)(a.issues.map((_)=>pr(_,s,Vt())));throw hs(u,o?.callee),u}return a.value},Uo=(e)=>async(t,r,n,o)=>{let s=n?{...n,async:!0}:{async:!0},a=t._zod.run({value:r,issues:[]},s);if(a instanceof Promise)a=await a;if(a.issues.length){let u=new(o?.Err??e)(a.issues.map((_)=>pr(_,s,Vt())));throw hs(u,o?.callee),u}return a.value},Un=(e)=>(t,r,n)=>{let o=n?{...n,async:!1}:{async:!1},s=t._zod.run({value:r,issues:[]},o);if(s instanceof Promise)throw new fr;return s.issues.length?{success:!1,error:new(e??Mo)(s.issues.map((a)=>pr(a,o,Vt())))}:{success:!0,data:s.value}},ou,jn=(e)=>async(t,r,n)=>{let o=n?{...n,async:!0}:{async:!0},s=t._zod.run({value:r,issues:[]},o);if(s instanceof Promise)s=await s;return s.issues.length?{success:!1,error:new e(s.issues.map((a)=>pr(a,o,Vt())))}:{success:!0,data:s.value}},iu,su=(e)=>(t,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return Bo(e)(t,r,o)},au=(e)=>(t,r,n)=>Bo(e)(t,r,n),cu=(e)=>async(t,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return Uo(e)(t,r,o)},lu=(e)=>async(t,r,n)=>Uo(e)(t,r,n),uu=(e)=>(t,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return Un(e)(t,r,o)},du=(e)=>(t,r,n)=>Un(e)(t,r,n),fu=(e)=>async(t,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return jn(e)(t,r,o)},pu=(e)=>async(t,r,n)=>jn(e)(t,r,n);var vs=De(()=>{Fr();ws();Jt();ou=Un(bs),iu=jn(bs)});function Su(){return new RegExp(Jy,"u")}function Nu(e){return typeof e.precision==="number"?e.precision===-1?"(?:[01]\\d|2[0-3]):[0-5]\\d":e.precision===0?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d":`(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{${e.precision}}`:"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function Cu(e){return new RegExp(`^${Nu(e)}$`)}function qu(e){let t=Nu({precision:e.precision}),r=["Z"];if(e.local)r.push("");if(e.offset)r.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let n=`${t}(?:${r.join("|")})`;return new RegExp(`^${Iu}T(?:${n})$`)}var _u,gu,hu,mu,yu,bu,wu,vu,Es=(e)=>{if(!e)return/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)},Eu,Jy="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",xu,Tu,ku,Ru,Au,Ss,Du,Ou,Iu="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",Pu,Lu=(e)=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},$u,Fu,zu,Mu,Bu;var Ho=De(()=>{_u=/^[cC][0-9a-z]{6,}$/,gu=/^[0-9a-z]+$/,hu=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,mu=/^[0-9a-vA-V]{20}$/,yu=/^[A-Za-z0-9]{27}$/,bu=/^[a-zA-Z0-9_-]{21}$/,wu=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,vu=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,Eu=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;xu=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Tu=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,ku=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,Ru=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Au=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Ss=/^[A-Za-z0-9_-]*$/,Du=/^https?$/,Ou=/^\+[1-9]\d{6,14}$/,Pu=new RegExp(`^${Iu}$`);$u=/^-?\d+$/,Fu=/^-?\d+(?:\.\d+)?$/,zu=/^(?:true|false)$/i,Mu=/^[^A-Z]*$/,Bu=/^[^a-z]*$/});var ht,Uu,xs,Ts,ju,Hu,Wu,Zu,Gu,Hn,Ku,Vu,Ju,Xu,Qu,Yu,ed;var Wo=De(()=>{Fr();Ho();Jt();ht=ce("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),Uu={number:"number",bigint:"bigint",object:"date"},xs=ce("$ZodCheckLessThan",(e,t)=>{ht.init(e,t);let r=Uu[typeof t.value];e._zod.onattach.push((n)=>{let o=n._zod.bag,s=(t.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;if(t.value<s)if(t.inclusive)o.maximum=t.value;else o.exclusiveMaximum=t.value}),e._zod.check=(n)=>{if(t.inclusive?n.value<=t.value:n.value<t.value)return;n.issues.push({origin:r,code:"too_big",maximum:typeof t.value==="object"?t.value.getTime():t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Ts=ce("$ZodCheckGreaterThan",(e,t)=>{ht.init(e,t);let r=Uu[typeof t.value];e._zod.onattach.push((n)=>{let o=n._zod.bag,s=(t.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if(t.value>s)if(t.inclusive)o.minimum=t.value;else o.exclusiveMinimum=t.value}),e._zod.check=(n)=>{if(t.inclusive?n.value>=t.value:n.value>t.value)return;n.issues.push({origin:r,code:"too_small",minimum:typeof t.value==="object"?t.value.getTime():t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),ju=ce("$ZodCheckMultipleOf",(e,t)=>{ht.init(e,t),e._zod.onattach.push((r)=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=(r)=>{if(typeof r.value!==typeof t.value)throw Error("Cannot mix number and bigint in multiple_of check.");if(typeof r.value==="bigint"?r.value%t.value===BigInt(0):Gl(r.value,t.value)===0)return;r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}}),Hu=ce("$ZodCheckNumberFormat",(e,t)=>{ht.init(e,t),t.format=t.format||"float64";let r=t.format?.includes("int"),n=r?"int":"number",[o,s]=Ql[t.format];e._zod.onattach.push((a)=>{let u=a._zod.bag;if(u.format=t.format,u.minimum=o,u.maximum=s,r)u.pattern=$u}),e._zod.check=(a)=>{let u=a.value;if(r){if(!Number.isInteger(u)){a.issues.push({expected:n,format:t.format,code:"invalid_type",continue:!1,input:u,inst:e});return}if(!Number.isSafeInteger(u)){if(u>0)a.issues.push({input:u,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,inclusive:!0,continue:!t.abort});else a.issues.push({input:u,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,inclusive:!0,continue:!t.abort});return}}if(u<o)a.issues.push({origin:"number",input:u,code:"too_small",minimum:o,inclusive:!0,inst:e,continue:!t.abort});if(u>s)a.issues.push({origin:"number",input:u,code:"too_big",maximum:s,inclusive:!0,inst:e,continue:!t.abort})}}),Wu=ce("$ZodCheckMaxLength",(e,t)=>{var r;ht.init(e,t),(r=e._zod.def).when??(r.when=(n)=>{let o=n.value;return!Lo(o)&&o.length!==void 0}),e._zod.onattach.push((n)=>{let o=n._zod.bag.maximum??Number.POSITIVE_INFINITY;if(t.maximum<o)n._zod.bag.maximum=t.maximum}),e._zod.check=(n)=>{let o=n.value;if(o.length<=t.maximum)return;let a=zo(o);n.issues.push({origin:a,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),Zu=ce("$ZodCheckMinLength",(e,t)=>{var r;ht.init(e,t),(r=e._zod.def).when??(r.when=(n)=>{let o=n.value;return!Lo(o)&&o.length!==void 0}),e._zod.onattach.push((n)=>{let o=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(t.minimum>o)n._zod.bag.minimum=t.minimum}),e._zod.check=(n)=>{let o=n.value;if(o.length>=t.minimum)return;let a=zo(o);n.issues.push({origin:a,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),Gu=ce("$ZodCheckLengthEquals",(e,t)=>{var r;ht.init(e,t),(r=e._zod.def).when??(r.when=(n)=>{let o=n.value;return!Lo(o)&&o.length!==void 0}),e._zod.onattach.push((n)=>{let o=n._zod.bag;o.minimum=t.length,o.maximum=t.length,o.length=t.length}),e._zod.check=(n)=>{let o=n.value,s=o.length;if(s===t.length)return;let a=zo(o),u=s>t.length;n.issues.push({origin:a,...u?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),Hn=ce("$ZodCheckStringFormat",(e,t)=>{var r,n;if(ht.init(e,t),e._zod.onattach.push((o)=>{let s=o._zod.bag;if(s.format=t.format,t.pattern)s.patterns??(s.patterns=new Set),s.patterns.add(t.pattern)}),t.pattern)(r=e._zod).check??(r.check=(o)=>{if(t.pattern.lastIndex=0,t.pattern.test(o.value))return;o.issues.push({origin:"string",code:"invalid_format",format:t.format,input:o.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})});else(n=e._zod).check??(n.check=()=>{})}),Ku=ce("$ZodCheckRegex",(e,t)=>{Hn.init(e,t),e._zod.check=(r)=>{if(t.pattern.lastIndex=0,t.pattern.test(r.value))return;r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),Vu=ce("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=Mu),Hn.init(e,t)}),Ju=ce("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=Bu),Hn.init(e,t)}),Xu=ce("$ZodCheckIncludes",(e,t)=>{ht.init(e,t);let r=Sr(t.includes),n=new RegExp(typeof t.position==="number"?`^.{${t.position}}${r}`:r);t.pattern=n,e._zod.onattach.push((o)=>{let s=o._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(n)}),e._zod.check=(o)=>{if(o.value.includes(t.includes,t.position))return;o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:o.value,inst:e,continue:!t.abort})}}),Qu=ce("$ZodCheckStartsWith",(e,t)=>{ht.init(e,t);let r=new RegExp(`^${Sr(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.onattach.push((n)=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),e._zod.check=(n)=>{if(n.value.startsWith(t.prefix))return;n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),Yu=ce("$ZodCheckEndsWith",(e,t)=>{ht.init(e,t);let r=new RegExp(`.*${Sr(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.onattach.push((n)=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),e._zod.check=(n)=>{if(n.value.endsWith(t.suffix))return;n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}}),ed=ce("$ZodCheckOverwrite",(e,t)=>{ht.init(e,t),e._zod.check=(r)=>{r.value=t.tx(r.value)}})});class ks{constructor(e=[]){if(this.content=[],this.indent=0,this)this.args=e}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e==="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let r=e.split(`
392
408
  `).filter((s)=>s),n=Math.min(...r.map((s)=>s.length-s.trimStart().length)),o=r.map((s)=>s.slice(n)).map((s)=>" ".repeat(this.indent*2)+s);for(let s of o)this.content.push(s)}compile(){let e=Function,t=this?.args,n=[...(this?.content??[""]).map((o)=>` ${o}`)];return new e(...t,n.join(`
393
- `))}}var Vu;var xs=De(()=>{Vu={major:4,minor:4,patch:3}});function Sd(e){if(e==="")return!0;if(/\s/.test(e))return!1;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}function My(e){if(!ws.test(e))return!1;let t=e.replace(/[-_]/g,(n)=>n==="-"?"+":"/"),r=t.padEnd(Math.ceil(t.length/4)*4,"=");return Sd(r)}function By(e,t=null){try{let r=e.split(".");if(r.length!==3)return!1;let[n]=r;if(!n)return!1;let o=JSON.parse(atob(n));if("typ"in o&&o?.typ!=="JWT")return!1;if(!o.alg)return!1;if(t&&(!("alg"in o)||o.alg!==t))return!1;return!0}catch{return!1}}function Ju(e,t,r){if(e.issues.length)t.issues.push(...zo(r,e.issues));t.value[r]=e.value}function Go(e,t,r,n,o,s){let a=r in n;if(e.issues.length){if(o&&s&&!a)return;t.issues.push(...zo(r,e.issues))}if(!a&&!o){if(!e.issues.length)t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[r]});return}if(e.value===void 0){if(a)t.value[r]=void 0}else t.value[r]=e.value}function Cd(e){let t=Object.keys(e.shape);for(let n of t)if(!e.shape?.[n]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${n}": expected a Zod schema`);let r=Hl(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(r)}}function Nd(e,t,r,n,o,s){let a=[],u=o.keySet,_=o.catchall._zod,m=_.def.type,x=_.optin==="optional",D=_.optout==="optional";for(let j in t){if(j==="__proto__")continue;if(u.has(j))continue;if(m==="never"){a.push(j);continue}let Y=_.run({value:t[j],issues:[]},n);if(Y instanceof Promise)e.push(Y.then((_e)=>Go(_e,r,j,t,x,D)));else Go(Y,r,j,t,x,D)}if(a.length)r.issues.push({code:"unrecognized_keys",keys:a,input:t,inst:s});if(!e.length)return r;return Promise.all(e).then(()=>r)}function Xu(e,t,r,n){for(let s of e)if(s.issues.length===0)return t.value=s.value,t;let o=e.filter((s)=>!Mr(s));if(o.length===1)return t.value=o[0].value,o[0];return t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map((s)=>s.issues.map((a)=>dr(a,n,Kt())))}),t}function Ts(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e===+t)return{valid:!0,data:e};if(mn(e)&&mn(t)){let r=Object.keys(t),n=Object.keys(e).filter((s)=>r.indexOf(s)!==-1),o={...e,...t};for(let s of n){let a=Ts(e[s],t[s]);if(!a.valid)return{valid:!1,mergeErrorPath:[s,...a.mergeErrorPath]};o[s]=a.data}return{valid:!0,data:o}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let n=0;n<e.length;n++){let o=e[n],s=t[n],a=Ts(o,s);if(!a.valid)return{valid:!1,mergeErrorPath:[n,...a.mergeErrorPath]};r.push(a.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function Qu(e,t,r){let n=new Map,o;for(let u of t.issues)if(u.code==="unrecognized_keys"){o??(o=u);for(let _ of u.keys){if(!n.has(_))n.set(_,{});n.get(_).l=!0}}else e.issues.push(u);for(let u of r.issues)if(u.code==="unrecognized_keys")for(let _ of u.keys){if(!n.has(_))n.set(_,{});n.get(_).r=!0}else e.issues.push(u);let s=[...n].filter(([,u])=>u.l&&u.r).map(([u])=>u);if(s.length&&o)e.issues.push({...o,keys:s});if(Mr(e))return e;let a=Ts(t.value,r.value);if(!a.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(a.mergeErrorPath)}`);return e.value=a.data,e}function Yu(e,t){if(t===void 0&&(e.issues.length||e.fallback))return{issues:[],value:void 0};return e}function ed(e,t){if(e.value===void 0)e.value=t.defaultValue;return e}function td(e,t){if(!e.issues.length&&e.value===void 0)e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t});return e}function Zo(e,t,r){if(e.issues.length)return e.aborted=!0,e;return t._zod.run({value:e.value,issues:e.issues,fallback:e.fallback},r)}function rd(e){return e.value=Object.freeze(e.value),e}function nd(e,t,r,n){if(!e){let o={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};if(n._zod.def.params)o.params=n._zod.def.params;t.issues.push(Br(o))}}var it,Ko,rt,od,id,sd,ad,cd,ld,ud,dd,fd,pd,_d,gd,hd,md,yd,bd,wd,vd,Ed,xd,Td,kd,Rd,ks,Ad,Dd,Od,Id,Pd,Uy,qd,Ld,$d,zd,Fd,Md,Rs,Bd,Ud,jd,Hd,Wd,Zd,Gd,Kd,Vd;var Jd=De(()=>{Wo();zr();ys();Ho();Vt();xs();Vt();it=ce("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Vu;let n=[...e._zod.def.checks??[]];if(e._zod.traits.has("$ZodCheck"))n.unshift(e);for(let o of n)for(let s of o._zod.onattach)s(e);if(n.length===0)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let o=(a,u,_)=>{let m=Mr(a),x;for(let D of u){if(D._zod.def.when){if(Zl(a))continue;if(!D._zod.def.when(a))continue}else if(m)continue;let j=a.issues.length,Y=D._zod.check(a);if(Y instanceof Promise&&_?.async===!1)throw new ur;if(x||Y instanceof Promise)x=(x??Promise.resolve()).then(async()=>{if(await Y,a.issues.length===j)return;if(!m)m=Mr(a,j)});else{if(a.issues.length===j)continue;if(!m)m=Mr(a,j)}}if(x)return x.then(()=>a);return a},s=(a,u,_)=>{if(Mr(a))return a.aborted=!0,a;let m=o(u,n,_);if(m instanceof Promise){if(_.async===!1)throw new ur;return m.then((x)=>e._zod.parse(x,_))}return e._zod.parse(m,_)};e._zod.run=(a,u)=>{if(u.skipChecks)return e._zod.parse(a,u);if(u.direction==="backward"){let m=e._zod.parse({value:a.value,issues:[]},{...u,skipChecks:!0});if(m instanceof Promise)return m.then((x)=>s(x,a,u));return s(m,a,u)}let _=e._zod.parse(a,u);if(_ instanceof Promise){if(u.async===!1)throw new ur;return _.then((m)=>o(m,n,u))}return o(_,n,u)}}Ve(e,"~standard",()=>({validate:(o)=>{try{let s=Xl(e,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch(s){return Ql(e,o).then((a)=>a.success?{value:a.data}:{issues:a.error?.issues})}},vendor:"zod",version:1}))}),Ko=ce("$ZodString",(e,t)=>{it.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??Du(e._zod.bag),e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=String(r.value)}catch(o){}if(typeof r.value==="string")return r;return r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}}),rt=ce("$ZodStringFormat",(e,t)=>{Wn.init(e,t),Ko.init(e,t)}),od=ce("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=_u),rt.init(e,t)}),id=ce("$ZodUUID",(e,t)=>{if(t.version){let n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(n===void 0)throw Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=bs(n))}else t.pattern??(t.pattern=bs());rt.init(e,t)}),sd=ce("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=gu),rt.init(e,t)}),ad=ce("$ZodURL",(e,t)=>{rt.init(e,t),e._zod.check=(r)=>{try{let n=r.value.trim();if(!t.normalize&&t.protocol?.source===Eu.source){if(!/^https?:\/\//i.test(n)){r.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:r.value,inst:e,continue:!t.abort});return}}let o=new URL(n);if(t.hostname){if(t.hostname.lastIndex=0,!t.hostname.test(o.hostname))r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:r.value,inst:e,continue:!t.abort})}if(t.protocol){if(t.protocol.lastIndex=0,!t.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol))r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:r.value,inst:e,continue:!t.abort})}if(t.normalize)r.value=o.href;else r.value=n;return}catch(n){r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort})}}}),cd=ce("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=hu()),rt.init(e,t)}),ld=ce("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=fu),rt.init(e,t)}),ud=ce("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=au),rt.init(e,t)}),dd=ce("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=cu),rt.init(e,t)}),fd=ce("$ZodULID",(e,t)=>{t.pattern??(t.pattern=lu),rt.init(e,t)}),pd=ce("$ZodXID",(e,t)=>{t.pattern??(t.pattern=uu),rt.init(e,t)}),_d=ce("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=du),rt.init(e,t)}),gd=ce("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=Au(t)),rt.init(e,t)}),hd=ce("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=Tu),rt.init(e,t)}),md=ce("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=Ru(t)),rt.init(e,t)}),yd=ce("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=pu),rt.init(e,t)}),bd=ce("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=mu),rt.init(e,t),e._zod.bag.format="ipv4"}),wd=ce("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=yu),rt.init(e,t),e._zod.bag.format="ipv6",e._zod.check=(r)=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:e,continue:!t.abort})}}}),vd=ce("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=bu),rt.init(e,t)}),Ed=ce("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=wu),rt.init(e,t),e._zod.check=(r)=>{let n=r.value.split("/");try{if(n.length!==2)throw Error();let[o,s]=n;if(!s)throw Error();let a=Number(s);if(`${a}`!==s)throw Error();if(a<0||a>128)throw Error();new URL(`http://[${o}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:e,continue:!t.abort})}}});xd=ce("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=vu),rt.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=(r)=>{if(Sd(r.value))return;r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}});Td=ce("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=ws),rt.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=(r)=>{if(My(r.value))return;r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),kd=ce("$ZodE164",(e,t)=>{t.pattern??(t.pattern=Su),rt.init(e,t)});Rd=ce("$ZodJWT",(e,t)=>{rt.init(e,t),e._zod.check=(r)=>{if(By(r.value,t.alg))return;r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}}),ks=ce("$ZodNumber",(e,t)=>{it.init(e,t),e._zod.pattern=e._zod.bag.pattern??Iu,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=Number(r.value)}catch(a){}let o=r.value;if(typeof o==="number"&&!Number.isNaN(o)&&Number.isFinite(o))return r;let s=typeof o==="number"?Number.isNaN(o)?"NaN":!Number.isFinite(o)?"Infinity":void 0:void 0;return r.issues.push({expected:"number",code:"invalid_type",input:o,inst:e,...s?{received:s}:{}}),r}}),Ad=ce("$ZodNumberFormat",(e,t)=>{$u.init(e,t),ks.init(e,t)}),Dd=ce("$ZodBoolean",(e,t)=>{it.init(e,t),e._zod.pattern=Pu,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=Boolean(r.value)}catch(s){}let o=r.value;if(typeof o==="boolean")return r;return r.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:e}),r}}),Od=ce("$ZodUnknown",(e,t)=>{it.init(e,t),e._zod.parse=(r)=>r}),Id=ce("$ZodNever",(e,t)=>{it.init(e,t),e._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:e}),r)});Pd=ce("$ZodArray",(e,t)=>{it.init(e,t),e._zod.parse=(r,n)=>{let o=r.value;if(!Array.isArray(o))return r.issues.push({expected:"array",code:"invalid_type",input:o,inst:e}),r;r.value=Array(o.length);let s=[];for(let a=0;a<o.length;a++){let u=o[a],_=t.element._zod.run({value:u,issues:[]},n);if(_ instanceof Promise)s.push(_.then((m)=>Ju(m,r,a)));else Ju(_,r,a)}if(s.length)return Promise.all(s).then(()=>r);return r}});Uy=ce("$ZodObject",(e,t)=>{if(it.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){let u=t.shape;Object.defineProperty(t,"shape",{get:()=>{let _={...u};return Object.defineProperty(t,"shape",{value:_}),_}})}let n=qo(()=>Cd(t));Ve(e._zod,"propValues",()=>{let u=t.shape,_={};for(let m in u){let x=u[m]._zod;if(x.values){_[m]??(_[m]=new Set);for(let D of x.values)_[m].add(D)}}return _});let o=Bn,s=t.catchall,a;e._zod.parse=(u,_)=>{a??(a=n.value);let m=u.value;if(!o(m))return u.issues.push({expected:"object",code:"invalid_type",input:m,inst:e}),u;u.value={};let x=[],D=a.shape;for(let j of a.keys){let Y=D[j],_e=Y._zod.optin==="optional",de=Y._zod.optout==="optional",ge=Y._zod.run({value:m[j],issues:[]},_);if(ge instanceof Promise)x.push(ge.then((Le)=>Go(Le,u,j,m,_e,de)));else Go(ge,u,j,m,_e,de)}if(!s)return x.length?Promise.all(x).then(()=>u):u;return Nd(x,m,u,_,n.value,e)}}),qd=ce("$ZodObjectJIT",(e,t)=>{Uy.init(e,t);let r=e._zod.parse,n=qo(()=>Cd(t)),o=(j)=>{let Y=new Ss(["shape","payload","ctx"]),_e=n.value,de=($e)=>{let Ue=fs($e);return`shape[${Ue}]._zod.run({ value: input[${Ue}], issues: [] }, ctx)`};Y.write("const input = payload.value;");let ge=Object.create(null),Le=0;for(let $e of _e.keys)ge[$e]=`key_${Le++}`;Y.write("const newResult = {};");for(let $e of _e.keys){let Ue=ge[$e],tt=fs($e),Rr=j[$e],Lt=Rr?._zod?.optin==="optional",Dn=Rr?._zod?.optout==="optional";if(Y.write(`const ${Ue} = ${de($e)};`),Lt&&Dn)Y.write(`
409
+ `))}}var rd;var Rs=De(()=>{rd={major:4,minor:4,patch:3}});function Od(e){if(e==="")return!0;if(/\s/.test(e))return!1;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}function Xy(e){if(!Ss.test(e))return!1;let t=e.replace(/[-_]/g,(n)=>n==="-"?"+":"/"),r=t.padEnd(Math.ceil(t.length/4)*4,"=");return Od(r)}function Qy(e,t=null){try{let r=e.split(".");if(r.length!==3)return!1;let[n]=r;if(!n)return!1;let o=JSON.parse(atob(n));if("typ"in o&&o?.typ!=="JWT")return!1;if(!o.alg)return!1;if(t&&(!("alg"in o)||o.alg!==t))return!1;return!0}catch{return!1}}function nd(e,t,r){if(e.issues.length)t.issues.push(...Fo(r,e.issues));t.value[r]=e.value}function Go(e,t,r,n,o,s){let a=r in n;if(e.issues.length){if(o&&s&&!a)return;t.issues.push(...Fo(r,e.issues))}if(!a&&!o){if(!e.issues.length)t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[r]});return}if(e.value===void 0){if(a)t.value[r]=void 0}else t.value[r]=e.value}function Md(e){let t=Object.keys(e.shape);for(let n of t)if(!e.shape?.[n]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${n}": expected a Zod schema`);let r=Xl(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(r)}}function Bd(e,t,r,n,o,s){let a=[],u=o.keySet,_=o.catchall._zod,m=_.def.type,x=_.optin==="optional",D=_.optout==="optional";for(let j in t){if(j==="__proto__")continue;if(u.has(j))continue;if(m==="never"){a.push(j);continue}let Y=_.run({value:t[j],issues:[]},n);if(Y instanceof Promise)e.push(Y.then((_e)=>Go(_e,r,j,t,x,D)));else Go(Y,r,j,t,x,D)}if(a.length)r.issues.push({code:"unrecognized_keys",keys:a,input:t,inst:s});if(!e.length)return r;return Promise.all(e).then(()=>r)}function od(e,t,r,n){for(let s of e)if(s.issues.length===0)return t.value=s.value,t;let o=e.filter((s)=>!Mr(s));if(o.length===1)return t.value=o[0].value,o[0];return t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map((s)=>s.issues.map((a)=>pr(a,n,Vt())))}),t}function As(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e===+t)return{valid:!0,data:e};if(hn(e)&&hn(t)){let r=Object.keys(t),n=Object.keys(e).filter((s)=>r.indexOf(s)!==-1),o={...e,...t};for(let s of n){let a=As(e[s],t[s]);if(!a.valid)return{valid:!1,mergeErrorPath:[s,...a.mergeErrorPath]};o[s]=a.data}return{valid:!0,data:o}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let n=0;n<e.length;n++){let o=e[n],s=t[n],a=As(o,s);if(!a.valid)return{valid:!1,mergeErrorPath:[n,...a.mergeErrorPath]};r.push(a.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function id(e,t,r){let n=new Map,o;for(let u of t.issues)if(u.code==="unrecognized_keys"){o??(o=u);for(let _ of u.keys){if(!n.has(_))n.set(_,{});n.get(_).l=!0}}else e.issues.push(u);for(let u of r.issues)if(u.code==="unrecognized_keys")for(let _ of u.keys){if(!n.has(_))n.set(_,{});n.get(_).r=!0}else e.issues.push(u);let s=[...n].filter(([,u])=>u.l&&u.r).map(([u])=>u);if(s.length&&o)e.issues.push({...o,keys:s});if(Mr(e))return e;let a=As(t.value,r.value);if(!a.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(a.mergeErrorPath)}`);return e.value=a.data,e}function sd(e,t){if(t===void 0&&(e.issues.length||e.fallback))return{issues:[],value:void 0};return e}function ad(e,t){if(e.value===void 0)e.value=t.defaultValue;return e}function cd(e,t){if(!e.issues.length&&e.value===void 0)e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t});return e}function Zo(e,t,r){if(e.issues.length)return e.aborted=!0,e;return t._zod.run({value:e.value,issues:e.issues,fallback:e.fallback},r)}function ld(e){return e.value=Object.freeze(e.value),e}function ud(e,t,r,n){if(!e){let o={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};if(n._zod.def.params)o.params=n._zod.def.params;t.issues.push(Br(o))}}var it,Ko,rt,dd,fd,pd,_d,gd,hd,md,yd,bd,wd,vd,Ed,Sd,xd,Td,kd,Rd,Ad,Dd,Id,Pd,Nd,Cd,Ds,qd,Ld,$d,Fd,zd,Yy,Ud,jd,Hd,Wd,Zd,Gd,Os,Kd,Vd,Jd,Xd,Qd,Yd,ef,tf,rf;var nf=De(()=>{Wo();Fr();vs();Ho();Jt();Rs();Jt();it=ce("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=rd;let n=[...e._zod.def.checks??[]];if(e._zod.traits.has("$ZodCheck"))n.unshift(e);for(let o of n)for(let s of o._zod.onattach)s(e);if(n.length===0)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let o=(a,u,_)=>{let m=Mr(a),x;for(let D of u){if(D._zod.def.when){if(Yl(a))continue;if(!D._zod.def.when(a))continue}else if(m)continue;let j=a.issues.length,Y=D._zod.check(a);if(Y instanceof Promise&&_?.async===!1)throw new fr;if(x||Y instanceof Promise)x=(x??Promise.resolve()).then(async()=>{if(await Y,a.issues.length===j)return;if(!m)m=Mr(a,j)});else{if(a.issues.length===j)continue;if(!m)m=Mr(a,j)}}if(x)return x.then(()=>a);return a},s=(a,u,_)=>{if(Mr(a))return a.aborted=!0,a;let m=o(u,n,_);if(m instanceof Promise){if(_.async===!1)throw new fr;return m.then((x)=>e._zod.parse(x,_))}return e._zod.parse(m,_)};e._zod.run=(a,u)=>{if(u.skipChecks)return e._zod.parse(a,u);if(u.direction==="backward"){let m=e._zod.parse({value:a.value,issues:[]},{...u,skipChecks:!0});if(m instanceof Promise)return m.then((x)=>s(x,a,u));return s(m,a,u)}let _=e._zod.parse(a,u);if(_ instanceof Promise){if(u.async===!1)throw new fr;return _.then((m)=>o(m,n,u))}return o(_,n,u)}}Ve(e,"~standard",()=>({validate:(o)=>{try{let s=ou(e,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch(s){return iu(e,o).then((a)=>a.success?{value:a.data}:{issues:a.error?.issues})}},vendor:"zod",version:1}))}),Ko=ce("$ZodString",(e,t)=>{it.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??Lu(e._zod.bag),e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=String(r.value)}catch(o){}if(typeof r.value==="string")return r;return r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}}),rt=ce("$ZodStringFormat",(e,t)=>{Hn.init(e,t),Ko.init(e,t)}),dd=ce("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=vu),rt.init(e,t)}),fd=ce("$ZodUUID",(e,t)=>{if(t.version){let n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(n===void 0)throw Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=Es(n))}else t.pattern??(t.pattern=Es());rt.init(e,t)}),pd=ce("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=Eu),rt.init(e,t)}),_d=ce("$ZodURL",(e,t)=>{rt.init(e,t),e._zod.check=(r)=>{try{let n=r.value.trim();if(!t.normalize&&t.protocol?.source===Du.source){if(!/^https?:\/\//i.test(n)){r.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:r.value,inst:e,continue:!t.abort});return}}let o=new URL(n);if(t.hostname){if(t.hostname.lastIndex=0,!t.hostname.test(o.hostname))r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:r.value,inst:e,continue:!t.abort})}if(t.protocol){if(t.protocol.lastIndex=0,!t.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol))r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:r.value,inst:e,continue:!t.abort})}if(t.normalize)r.value=o.href;else r.value=n;return}catch(n){r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort})}}}),gd=ce("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=Su()),rt.init(e,t)}),hd=ce("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=bu),rt.init(e,t)}),md=ce("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=_u),rt.init(e,t)}),yd=ce("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=gu),rt.init(e,t)}),bd=ce("$ZodULID",(e,t)=>{t.pattern??(t.pattern=hu),rt.init(e,t)}),wd=ce("$ZodXID",(e,t)=>{t.pattern??(t.pattern=mu),rt.init(e,t)}),vd=ce("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=yu),rt.init(e,t)}),Ed=ce("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=qu(t)),rt.init(e,t)}),Sd=ce("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=Pu),rt.init(e,t)}),xd=ce("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=Cu(t)),rt.init(e,t)}),Td=ce("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=wu),rt.init(e,t)}),kd=ce("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=xu),rt.init(e,t),e._zod.bag.format="ipv4"}),Rd=ce("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=Tu),rt.init(e,t),e._zod.bag.format="ipv6",e._zod.check=(r)=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:e,continue:!t.abort})}}}),Ad=ce("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=ku),rt.init(e,t)}),Dd=ce("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=Ru),rt.init(e,t),e._zod.check=(r)=>{let n=r.value.split("/");try{if(n.length!==2)throw Error();let[o,s]=n;if(!s)throw Error();let a=Number(s);if(`${a}`!==s)throw Error();if(a<0||a>128)throw Error();new URL(`http://[${o}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:e,continue:!t.abort})}}});Id=ce("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=Au),rt.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=(r)=>{if(Od(r.value))return;r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}});Pd=ce("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=Ss),rt.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=(r)=>{if(Xy(r.value))return;r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),Nd=ce("$ZodE164",(e,t)=>{t.pattern??(t.pattern=Ou),rt.init(e,t)});Cd=ce("$ZodJWT",(e,t)=>{rt.init(e,t),e._zod.check=(r)=>{if(Qy(r.value,t.alg))return;r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}}),Ds=ce("$ZodNumber",(e,t)=>{it.init(e,t),e._zod.pattern=e._zod.bag.pattern??Fu,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=Number(r.value)}catch(a){}let o=r.value;if(typeof o==="number"&&!Number.isNaN(o)&&Number.isFinite(o))return r;let s=typeof o==="number"?Number.isNaN(o)?"NaN":!Number.isFinite(o)?"Infinity":void 0:void 0;return r.issues.push({expected:"number",code:"invalid_type",input:o,inst:e,...s?{received:s}:{}}),r}}),qd=ce("$ZodNumberFormat",(e,t)=>{Hu.init(e,t),Ds.init(e,t)}),Ld=ce("$ZodBoolean",(e,t)=>{it.init(e,t),e._zod.pattern=zu,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=Boolean(r.value)}catch(s){}let o=r.value;if(typeof o==="boolean")return r;return r.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:e}),r}}),$d=ce("$ZodUnknown",(e,t)=>{it.init(e,t),e._zod.parse=(r)=>r}),Fd=ce("$ZodNever",(e,t)=>{it.init(e,t),e._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:e}),r)});zd=ce("$ZodArray",(e,t)=>{it.init(e,t),e._zod.parse=(r,n)=>{let o=r.value;if(!Array.isArray(o))return r.issues.push({expected:"array",code:"invalid_type",input:o,inst:e}),r;r.value=Array(o.length);let s=[];for(let a=0;a<o.length;a++){let u=o[a],_=t.element._zod.run({value:u,issues:[]},n);if(_ instanceof Promise)s.push(_.then((m)=>nd(m,r,a)));else nd(_,r,a)}if(s.length)return Promise.all(s).then(()=>r);return r}});Yy=ce("$ZodObject",(e,t)=>{if(it.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){let u=t.shape;Object.defineProperty(t,"shape",{get:()=>{let _={...u};return Object.defineProperty(t,"shape",{value:_}),_}})}let n=qo(()=>Md(t));Ve(e._zod,"propValues",()=>{let u=t.shape,_={};for(let m in u){let x=u[m]._zod;if(x.values){_[m]??(_[m]=new Set);for(let D of x.values)_[m].add(D)}}return _});let o=Mn,s=t.catchall,a;e._zod.parse=(u,_)=>{a??(a=n.value);let m=u.value;if(!o(m))return u.issues.push({expected:"object",code:"invalid_type",input:m,inst:e}),u;u.value={};let x=[],D=a.shape;for(let j of a.keys){let Y=D[j],_e=Y._zod.optin==="optional",de=Y._zod.optout==="optional",ge=Y._zod.run({value:m[j],issues:[]},_);if(ge instanceof Promise)x.push(ge.then((Le)=>Go(Le,u,j,m,_e,de)));else Go(ge,u,j,m,_e,de)}if(!s)return x.length?Promise.all(x).then(()=>u):u;return Bd(x,m,u,_,n.value,e)}}),Ud=ce("$ZodObjectJIT",(e,t)=>{Yy.init(e,t);let r=e._zod.parse,n=qo(()=>Md(t)),o=(j)=>{let Y=new ks(["shape","payload","ctx"]),_e=n.value,de=($e)=>{let Ue=gs($e);return`shape[${Ue}]._zod.run({ value: input[${Ue}], issues: [] }, ctx)`};Y.write("const input = payload.value;");let ge=Object.create(null),Le=0;for(let $e of _e.keys)ge[$e]=`key_${Le++}`;Y.write("const newResult = {};");for(let $e of _e.keys){let Ue=ge[$e],tt=gs($e),Rr=j[$e],$t=Rr?._zod?.optin==="optional",An=Rr?._zod?.optout==="optional";if(Y.write(`const ${Ue} = ${de($e)};`),$t&&An)Y.write(`
394
410
  if (${Ue}.issues.length) {
395
411
  if (${tt} in input) {
396
412
  payload.issues = payload.issues.concat(${Ue}.issues.map(iss => ({
@@ -408,7 +424,7 @@ CREATE VIRTUAL TABLE IF NOT EXISTS search_fts USING fts5(
408
424
  newResult[${tt}] = ${Ue}.value;
409
425
  }
410
426
 
411
- `);else if(!Lt)Y.write(`
427
+ `);else if(!$t)Y.write(`
412
428
  const ${Ue}_present = ${tt} in input;
413
429
  if (${Ue}.issues.length) {
414
430
  payload.issues = payload.issues.concat(${Ue}.issues.map(iss => ({
@@ -449,94 +465,94 @@ CREATE VIRTUAL TABLE IF NOT EXISTS search_fts USING fts5(
449
465
  newResult[${tt}] = ${Ue}.value;
450
466
  }
451
467
 
452
- `)}Y.write("payload.value = newResult;"),Y.write("return payload;");let Ze=Y.compile();return($e,Ue)=>Ze(j,$e,Ue)},s,a=Bn,u=!hn.jitless,m=u&&Ul.value,x=t.catchall,D;e._zod.parse=(j,Y)=>{D??(D=n.value);let _e=j.value;if(!a(_e))return j.issues.push({expected:"object",code:"invalid_type",input:_e,inst:e}),j;if(u&&m&&Y?.async===!1&&Y.jitless!==!0){if(!s)s=o(t.shape);if(j=s(j,Y),!x)return j;return Nd([],_e,j,Y,D,e)}return r(j,Y)}});Ld=ce("$ZodUnion",(e,t)=>{it.init(e,t),Ve(e._zod,"optin",()=>t.options.some((n)=>n._zod.optin==="optional")?"optional":void 0),Ve(e._zod,"optout",()=>t.options.some((n)=>n._zod.optout==="optional")?"optional":void 0),Ve(e._zod,"values",()=>{if(t.options.every((n)=>n._zod.values))return new Set(t.options.flatMap((n)=>Array.from(n._zod.values)));return}),Ve(e._zod,"pattern",()=>{if(t.options.every((n)=>n._zod.pattern)){let n=t.options.map((o)=>o._zod.pattern);return new RegExp(`^(${n.map((o)=>$o(o.source)).join("|")})$`)}return});let r=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(n,o)=>{if(r)return r(n,o);let s=!1,a=[];for(let u of t.options){let _=u._zod.run({value:n.value,issues:[]},o);if(_ instanceof Promise)a.push(_),s=!0;else{if(_.issues.length===0)return _;a.push(_)}}if(!s)return Xu(a,n,e,o);return Promise.all(a).then((u)=>Xu(u,n,e,o))}}),$d=ce("$ZodIntersection",(e,t)=>{it.init(e,t),e._zod.parse=(r,n)=>{let o=r.value,s=t.left._zod.run({value:o,issues:[]},n),a=t.right._zod.run({value:o,issues:[]},n);if(s instanceof Promise||a instanceof Promise)return Promise.all([s,a]).then(([_,m])=>Qu(r,_,m));return Qu(r,s,a)}});zd=ce("$ZodEnum",(e,t)=>{it.init(e,t);let r=No(t.entries),n=new Set(r);e._zod.values=n,e._zod.pattern=new RegExp(`^(${r.filter((o)=>jl.has(typeof o)).map((o)=>typeof o==="string"?Sr(o):o.toString()).join("|")})$`),e._zod.parse=(o,s)=>{let a=o.value;if(n.has(a))return o;return o.issues.push({code:"invalid_value",values:r,input:a,inst:e}),o}}),Fd=ce("$ZodLiteral",(e,t)=>{if(it.init(e,t),t.values.length===0)throw Error("Cannot create literal schema with no valid values");let r=new Set(t.values);e._zod.values=r,e._zod.pattern=new RegExp(`^(${t.values.map((n)=>typeof n==="string"?Sr(n):n?Sr(n.toString()):String(n)).join("|")})$`),e._zod.parse=(n,o)=>{let s=n.value;if(r.has(s))return n;return n.issues.push({code:"invalid_value",values:t.values,input:s,inst:e}),n}}),Md=ce("$ZodTransform",(e,t)=>{it.init(e,t),e._zod.optin="optional",e._zod.parse=(r,n)=>{if(n.direction==="backward")throw new Mn(e.constructor.name);let o=t.transform(r.value,r);if(n.async)return(o instanceof Promise?o:Promise.resolve(o)).then((a)=>(r.value=a,r.fallback=!0,r));if(o instanceof Promise)throw new ur;return r.value=o,r.fallback=!0,r}});Rs=ce("$ZodOptional",(e,t)=>{it.init(e,t),e._zod.optin="optional",e._zod.optout="optional",Ve(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),Ve(e._zod,"pattern",()=>{let r=t.innerType._zod.pattern;return r?new RegExp(`^(${$o(r.source)})?$`):void 0}),e._zod.parse=(r,n)=>{if(t.innerType._zod.optin==="optional"){let o=r.value,s=t.innerType._zod.run(r,n);if(s instanceof Promise)return s.then((a)=>Yu(a,o));return Yu(s,o)}if(r.value===void 0)return r;return t.innerType._zod.run(r,n)}}),Bd=ce("$ZodExactOptional",(e,t)=>{Rs.init(e,t),Ve(e._zod,"values",()=>t.innerType._zod.values),Ve(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(r,n)=>t.innerType._zod.run(r,n)}),Ud=ce("$ZodNullable",(e,t)=>{it.init(e,t),Ve(e._zod,"optin",()=>t.innerType._zod.optin),Ve(e._zod,"optout",()=>t.innerType._zod.optout),Ve(e._zod,"pattern",()=>{let r=t.innerType._zod.pattern;return r?new RegExp(`^(${$o(r.source)}|null)$`):void 0}),Ve(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(r,n)=>{if(r.value===null)return r;return t.innerType._zod.run(r,n)}}),jd=ce("$ZodDefault",(e,t)=>{it.init(e,t),e._zod.optin="optional",Ve(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>{if(n.direction==="backward")return t.innerType._zod.run(r,n);if(r.value===void 0)return r.value=t.defaultValue,r;let o=t.innerType._zod.run(r,n);if(o instanceof Promise)return o.then((s)=>ed(s,t));return ed(o,t)}});Hd=ce("$ZodPrefault",(e,t)=>{it.init(e,t),e._zod.optin="optional",Ve(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>{if(n.direction==="backward")return t.innerType._zod.run(r,n);if(r.value===void 0)r.value=t.defaultValue;return t.innerType._zod.run(r,n)}}),Wd=ce("$ZodNonOptional",(e,t)=>{it.init(e,t),Ve(e._zod,"values",()=>{let r=t.innerType._zod.values;return r?new Set([...r].filter((n)=>n!==void 0)):void 0}),e._zod.parse=(r,n)=>{let o=t.innerType._zod.run(r,n);if(o instanceof Promise)return o.then((s)=>td(s,e));return td(o,e)}});Zd=ce("$ZodCatch",(e,t)=>{it.init(e,t),e._zod.optin="optional",Ve(e._zod,"optout",()=>t.innerType._zod.optout),Ve(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>{if(n.direction==="backward")return t.innerType._zod.run(r,n);let o=t.innerType._zod.run(r,n);if(o instanceof Promise)return o.then((s)=>{if(r.value=s.value,s.issues.length)r.value=t.catchValue({...r,error:{issues:s.issues.map((a)=>dr(a,n,Kt()))},input:r.value}),r.issues=[],r.fallback=!0;return r});if(r.value=o.value,o.issues.length)r.value=t.catchValue({...r,error:{issues:o.issues.map((s)=>dr(s,n,Kt()))},input:r.value}),r.issues=[],r.fallback=!0;return r}}),Gd=ce("$ZodPipe",(e,t)=>{it.init(e,t),Ve(e._zod,"values",()=>t.in._zod.values),Ve(e._zod,"optin",()=>t.in._zod.optin),Ve(e._zod,"optout",()=>t.out._zod.optout),Ve(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(r,n)=>{if(n.direction==="backward"){let s=t.out._zod.run(r,n);if(s instanceof Promise)return s.then((a)=>Zo(a,t.in,n));return Zo(s,t.in,n)}let o=t.in._zod.run(r,n);if(o instanceof Promise)return o.then((s)=>Zo(s,t.out,n));return Zo(o,t.out,n)}});Kd=ce("$ZodReadonly",(e,t)=>{it.init(e,t),Ve(e._zod,"propValues",()=>t.innerType._zod.propValues),Ve(e._zod,"values",()=>t.innerType._zod.values),Ve(e._zod,"optin",()=>t.innerType?._zod?.optin),Ve(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(r,n)=>{if(n.direction==="backward")return t.innerType._zod.run(r,n);let o=t.innerType._zod.run(r,n);if(o instanceof Promise)return o.then(rd);return rd(o)}});Vd=ce("$ZodCustom",(e,t)=>{mt.init(e,t),it.init(e,t),e._zod.parse=(r,n)=>r,e._zod.check=(r)=>{let n=r.value,o=t.fn(n);if(o instanceof Promise)return o.then((s)=>nd(s,r,n,e));nd(o,r,n,e);return}})});function As(){return{localeError:jy()}}var jy=()=>{let e={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"},map:{unit:"entries",verb:"to have"}};function t(o){return e[o]??null}let r={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"},n={nan:"NaN"};return(o)=>{switch(o.code){case"invalid_type":{let s=n[o.expected]??o.expected,a=Gl(o.input),u=n[a]??a;return`Invalid input: expected ${s}, received ${u}`}case"invalid_value":if(o.values.length===1)return`Invalid input: expected ${gs(o.values[0])}`;return`Invalid option: expected one of ${ds(o.values,"|")}`;case"too_big":{let s=o.inclusive?"<=":"<",a=t(o.origin);if(a)return`Too big: expected ${o.origin??"value"} to have ${s}${o.maximum.toString()} ${a.unit??"elements"}`;return`Too big: expected ${o.origin??"value"} to be ${s}${o.maximum.toString()}`}case"too_small":{let s=o.inclusive?">=":">",a=t(o.origin);if(a)return`Too small: expected ${o.origin} to have ${s}${o.minimum.toString()} ${a.unit}`;return`Too small: expected ${o.origin} to be ${s}${o.minimum.toString()}`}case"invalid_format":{let s=o;if(s.format==="starts_with")return`Invalid string: must start with "${s.prefix}"`;if(s.format==="ends_with")return`Invalid string: must end with "${s.suffix}"`;if(s.format==="includes")return`Invalid string: must include "${s.includes}"`;if(s.format==="regex")return`Invalid string: must match pattern ${s.pattern}`;return`Invalid ${r[s.format]??o.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${o.divisor}`;case"unrecognized_keys":return`Unrecognized key${o.keys.length>1?"s":""}: ${ds(o.keys,", ")}`;case"invalid_key":return`Invalid key in ${o.origin}`;case"invalid_union":if(o.options&&Array.isArray(o.options)&&o.options.length>0)return`Invalid discriminator value. Expected ${o.options.map((a)=>`'${a}'`).join(" | ")}`;return"Invalid input";case"invalid_element":return`Invalid value in ${o.origin}`;default:return"Invalid input"}}};var Xd=De(()=>{Vt()});var Ds=()=>{};class ef{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){let r=t[0];if(this._map.set(e,r),r&&typeof r==="object"&&"id"in r)this._idmap.set(r.id,e);return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let t=this._map.get(e);if(t&&typeof t==="object"&&"id"in t)this._idmap.delete(t.id);return this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let r={...this.get(t)??{}};delete r.id;let n={...r,...this._map.get(e)};return Object.keys(n).length?n:void 0}return this._map.get(e)}has(e){return this._map.has(e)}}function Hy(){return new ef}var Yd,VS,JS,Ur;var Os=De(()=>{VS=Symbol("ZodOutput"),JS=Symbol("ZodInput");(Yd=globalThis).__zod_globalRegistry??(Yd.__zod_globalRegistry=Hy());Ur=globalThis.__zod_globalRegistry});function tf(e,t){return new e({type:"string",...Ce(t)})}function rf(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...Ce(t)})}function Is(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...Ce(t)})}function nf(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...Ce(t)})}function of(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...Ce(t)})}function sf(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...Ce(t)})}function af(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...Ce(t)})}function cf(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...Ce(t)})}function lf(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...Ce(t)})}function uf(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...Ce(t)})}function df(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...Ce(t)})}function ff(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...Ce(t)})}function pf(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...Ce(t)})}function _f(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...Ce(t)})}function gf(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...Ce(t)})}function hf(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...Ce(t)})}function mf(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...Ce(t)})}function yf(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...Ce(t)})}function bf(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...Ce(t)})}function wf(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...Ce(t)})}function vf(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...Ce(t)})}function Ef(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...Ce(t)})}function Sf(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...Ce(t)})}function xf(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...Ce(t)})}function Tf(e,t){return new e({type:"string",format:"date",check:"string_format",...Ce(t)})}function kf(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...Ce(t)})}function Rf(e,t){return new e({type:"string",format:"duration",check:"string_format",...Ce(t)})}function Af(e,t){return new e({type:"number",checks:[],...Ce(t)})}function Df(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...Ce(t)})}function Of(e,t){return new e({type:"boolean",...Ce(t)})}function If(e){return new e({type:"unknown"})}function Pf(e,t){return new e({type:"never",...Ce(t)})}function Vo(e,t){return new vs({check:"less_than",...Ce(t),value:e,inclusive:!1})}function Zn(e,t){return new vs({check:"less_than",...Ce(t),value:e,inclusive:!0})}function Jo(e,t){return new Es({check:"greater_than",...Ce(t),value:e,inclusive:!1})}function Gn(e,t){return new Es({check:"greater_than",...Ce(t),value:e,inclusive:!0})}function Xo(e,t){return new Lu({check:"multiple_of",...Ce(t),value:e})}function Qo(e,t){return new zu({check:"max_length",...Ce(t),maximum:e})}function yn(e,t){return new Fu({check:"min_length",...Ce(t),minimum:e})}function Yo(e,t){return new Mu({check:"length_equals",...Ce(t),length:e})}function Ps(e,t){return new Bu({check:"string_format",format:"regex",...Ce(t),pattern:e})}function Cs(e){return new Uu({check:"string_format",format:"lowercase",...Ce(e)})}function Ns(e){return new ju({check:"string_format",format:"uppercase",...Ce(e)})}function qs(e,t){return new Hu({check:"string_format",format:"includes",...Ce(t),includes:e})}function Ls(e,t){return new Wu({check:"string_format",format:"starts_with",...Ce(t),prefix:e})}function $s(e,t){return new Zu({check:"string_format",format:"ends_with",...Ce(t),suffix:e})}function xr(e){return new Gu({check:"overwrite",tx:e})}function zs(e){return xr((t)=>t.normalize(e))}function Fs(){return xr((e)=>e.trim())}function Ms(){return xr((e)=>e.toLowerCase())}function Bs(){return xr((e)=>e.toUpperCase())}function Us(){return xr((e)=>Bl(e))}function Cf(e,t,r){return new e({type:"array",element:t,...Ce(r)})}function Nf(e,t,r){return new e({type:"custom",check:"custom",fn:t,...Ce(r)})}function qf(e,t){let r=Wy((n)=>(n.addIssue=(o)=>{if(typeof o==="string")n.issues.push(Br(o,n.value,r._zod.def));else{let s=o;if(s.fatal)s.continue=!1;s.code??(s.code="custom"),s.input??(s.input=n.value),s.inst??(s.inst=r),s.continue??(s.continue=!r._zod.def.abort),n.issues.push(Br(s))}},e(n.value,n)),t);return r}function Wy(e,t){let r=new mt({check:"custom",...Ce(t)});return r._zod.check=e,r}var Lf=De(()=>{Wo();Vt()});function js(e){let t=e?.target??"draft-2020-12";if(t==="draft-4")t="draft-04";if(t==="draft-7")t="draft-07";return{processors:e.processors??{},metadataRegistry:e?.metadata??Ur,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,cycles:e?.cycles??"ref",reused:e?.reused??"inline",external:e?.external??void 0}}function _t(e,t,r={path:[],schemaPath:[]}){var n;let o=e._zod.def,s=t.seen.get(e);if(s){if(s.count++,r.schemaPath.includes(e))s.cycle=r.path;return s.schema}let a={schema:{},count:1,cycle:void 0,path:r.path};t.seen.set(e,a);let u=e._zod.toJSONSchema?.();if(u)a.schema=u;else{let x={...r,schemaPath:[...r.schemaPath,e],path:r.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,a.schema,x);else{let j=a.schema,Y=t.processors[o.type];if(!Y)throw Error(`[toJSONSchema]: Non-representable type encountered: ${o.type}`);Y(e,t,j,x)}let D=e._zod.parent;if(D){if(!a.ref)a.ref=D;_t(D,t,x),t.seen.get(D).isParent=!0}}let _=t.metadataRegistry.get(e);if(_)Object.assign(a.schema,_);if(t.io==="input"&&kt(e))delete a.schema.examples,delete a.schema.default;if(t.io==="input"&&"_prefault"in a.schema)(n=a.schema).default??(n.default=a.schema._prefault);return delete a.schema._prefault,t.seen.get(e).schema}function Hs(e,t){let r=e.seen.get(t);if(!r)throw Error("Unprocessed schema. This is a bug in Zod.");let n=new Map;for(let a of e.seen.entries()){let u=e.metadataRegistry.get(a[0])?.id;if(u){let _=n.get(u);if(_&&_!==a[0])throw Error(`Duplicate schema id "${u}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);n.set(u,a[0])}}let o=(a)=>{let u=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){let D=e.external.registry.get(a[0])?.id,j=e.external.uri??((_e)=>_e);if(D)return{ref:j(D)};let Y=a[1].defId??a[1].schema.id??`schema${e.counter++}`;return a[1].defId=Y,{defId:Y,ref:`${j("__shared")}#/${u}/${Y}`}}if(a[1]===r)return{ref:"#"};let m=`${"#"}/${u}/`,x=a[1].schema.id??`__schema${e.counter++}`;return{defId:x,ref:m+x}},s=(a)=>{if(a[1].schema.$ref)return;let u=a[1],{ref:_,defId:m}=o(a);if(u.def={...u.schema},m)u.defId=m;let x=u.schema;for(let D in x)delete x[D];x.$ref=_};if(e.cycles==="throw")for(let a of e.seen.entries()){let u=a[1];if(u.cycle)throw Error(`Cycle detected: #/${u.cycle?.join("/")}/<root>
468
+ `)}Y.write("payload.value = newResult;"),Y.write("return payload;");let Ze=Y.compile();return($e,Ue)=>Ze(j,$e,Ue)},s,a=Mn,u=!gn.jitless,m=u&&Vl.value,x=t.catchall,D;e._zod.parse=(j,Y)=>{D??(D=n.value);let _e=j.value;if(!a(_e))return j.issues.push({expected:"object",code:"invalid_type",input:_e,inst:e}),j;if(u&&m&&Y?.async===!1&&Y.jitless!==!0){if(!s)s=o(t.shape);if(j=s(j,Y),!x)return j;return Bd([],_e,j,Y,D,e)}return r(j,Y)}});jd=ce("$ZodUnion",(e,t)=>{it.init(e,t),Ve(e._zod,"optin",()=>t.options.some((n)=>n._zod.optin==="optional")?"optional":void 0),Ve(e._zod,"optout",()=>t.options.some((n)=>n._zod.optout==="optional")?"optional":void 0),Ve(e._zod,"values",()=>{if(t.options.every((n)=>n._zod.values))return new Set(t.options.flatMap((n)=>Array.from(n._zod.values)));return}),Ve(e._zod,"pattern",()=>{if(t.options.every((n)=>n._zod.pattern)){let n=t.options.map((o)=>o._zod.pattern);return new RegExp(`^(${n.map((o)=>$o(o.source)).join("|")})$`)}return});let r=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(n,o)=>{if(r)return r(n,o);let s=!1,a=[];for(let u of t.options){let _=u._zod.run({value:n.value,issues:[]},o);if(_ instanceof Promise)a.push(_),s=!0;else{if(_.issues.length===0)return _;a.push(_)}}if(!s)return od(a,n,e,o);return Promise.all(a).then((u)=>od(u,n,e,o))}}),Hd=ce("$ZodIntersection",(e,t)=>{it.init(e,t),e._zod.parse=(r,n)=>{let o=r.value,s=t.left._zod.run({value:o,issues:[]},n),a=t.right._zod.run({value:o,issues:[]},n);if(s instanceof Promise||a instanceof Promise)return Promise.all([s,a]).then(([_,m])=>id(r,_,m));return id(r,s,a)}});Wd=ce("$ZodEnum",(e,t)=>{it.init(e,t);let r=Co(t.entries),n=new Set(r);e._zod.values=n,e._zod.pattern=new RegExp(`^(${r.filter((o)=>Jl.has(typeof o)).map((o)=>typeof o==="string"?Sr(o):o.toString()).join("|")})$`),e._zod.parse=(o,s)=>{let a=o.value;if(n.has(a))return o;return o.issues.push({code:"invalid_value",values:r,input:a,inst:e}),o}}),Zd=ce("$ZodLiteral",(e,t)=>{if(it.init(e,t),t.values.length===0)throw Error("Cannot create literal schema with no valid values");let r=new Set(t.values);e._zod.values=r,e._zod.pattern=new RegExp(`^(${t.values.map((n)=>typeof n==="string"?Sr(n):n?Sr(n.toString()):String(n)).join("|")})$`),e._zod.parse=(n,o)=>{let s=n.value;if(r.has(s))return n;return n.issues.push({code:"invalid_value",values:t.values,input:s,inst:e}),n}}),Gd=ce("$ZodTransform",(e,t)=>{it.init(e,t),e._zod.optin="optional",e._zod.parse=(r,n)=>{if(n.direction==="backward")throw new zn(e.constructor.name);let o=t.transform(r.value,r);if(n.async)return(o instanceof Promise?o:Promise.resolve(o)).then((a)=>(r.value=a,r.fallback=!0,r));if(o instanceof Promise)throw new fr;return r.value=o,r.fallback=!0,r}});Os=ce("$ZodOptional",(e,t)=>{it.init(e,t),e._zod.optin="optional",e._zod.optout="optional",Ve(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),Ve(e._zod,"pattern",()=>{let r=t.innerType._zod.pattern;return r?new RegExp(`^(${$o(r.source)})?$`):void 0}),e._zod.parse=(r,n)=>{if(t.innerType._zod.optin==="optional"){let o=r.value,s=t.innerType._zod.run(r,n);if(s instanceof Promise)return s.then((a)=>sd(a,o));return sd(s,o)}if(r.value===void 0)return r;return t.innerType._zod.run(r,n)}}),Kd=ce("$ZodExactOptional",(e,t)=>{Os.init(e,t),Ve(e._zod,"values",()=>t.innerType._zod.values),Ve(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(r,n)=>t.innerType._zod.run(r,n)}),Vd=ce("$ZodNullable",(e,t)=>{it.init(e,t),Ve(e._zod,"optin",()=>t.innerType._zod.optin),Ve(e._zod,"optout",()=>t.innerType._zod.optout),Ve(e._zod,"pattern",()=>{let r=t.innerType._zod.pattern;return r?new RegExp(`^(${$o(r.source)}|null)$`):void 0}),Ve(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(r,n)=>{if(r.value===null)return r;return t.innerType._zod.run(r,n)}}),Jd=ce("$ZodDefault",(e,t)=>{it.init(e,t),e._zod.optin="optional",Ve(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>{if(n.direction==="backward")return t.innerType._zod.run(r,n);if(r.value===void 0)return r.value=t.defaultValue,r;let o=t.innerType._zod.run(r,n);if(o instanceof Promise)return o.then((s)=>ad(s,t));return ad(o,t)}});Xd=ce("$ZodPrefault",(e,t)=>{it.init(e,t),e._zod.optin="optional",Ve(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>{if(n.direction==="backward")return t.innerType._zod.run(r,n);if(r.value===void 0)r.value=t.defaultValue;return t.innerType._zod.run(r,n)}}),Qd=ce("$ZodNonOptional",(e,t)=>{it.init(e,t),Ve(e._zod,"values",()=>{let r=t.innerType._zod.values;return r?new Set([...r].filter((n)=>n!==void 0)):void 0}),e._zod.parse=(r,n)=>{let o=t.innerType._zod.run(r,n);if(o instanceof Promise)return o.then((s)=>cd(s,e));return cd(o,e)}});Yd=ce("$ZodCatch",(e,t)=>{it.init(e,t),e._zod.optin="optional",Ve(e._zod,"optout",()=>t.innerType._zod.optout),Ve(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>{if(n.direction==="backward")return t.innerType._zod.run(r,n);let o=t.innerType._zod.run(r,n);if(o instanceof Promise)return o.then((s)=>{if(r.value=s.value,s.issues.length)r.value=t.catchValue({...r,error:{issues:s.issues.map((a)=>pr(a,n,Vt()))},input:r.value}),r.issues=[],r.fallback=!0;return r});if(r.value=o.value,o.issues.length)r.value=t.catchValue({...r,error:{issues:o.issues.map((s)=>pr(s,n,Vt()))},input:r.value}),r.issues=[],r.fallback=!0;return r}}),ef=ce("$ZodPipe",(e,t)=>{it.init(e,t),Ve(e._zod,"values",()=>t.in._zod.values),Ve(e._zod,"optin",()=>t.in._zod.optin),Ve(e._zod,"optout",()=>t.out._zod.optout),Ve(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(r,n)=>{if(n.direction==="backward"){let s=t.out._zod.run(r,n);if(s instanceof Promise)return s.then((a)=>Zo(a,t.in,n));return Zo(s,t.in,n)}let o=t.in._zod.run(r,n);if(o instanceof Promise)return o.then((s)=>Zo(s,t.out,n));return Zo(o,t.out,n)}});tf=ce("$ZodReadonly",(e,t)=>{it.init(e,t),Ve(e._zod,"propValues",()=>t.innerType._zod.propValues),Ve(e._zod,"values",()=>t.innerType._zod.values),Ve(e._zod,"optin",()=>t.innerType?._zod?.optin),Ve(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(r,n)=>{if(n.direction==="backward")return t.innerType._zod.run(r,n);let o=t.innerType._zod.run(r,n);if(o instanceof Promise)return o.then(ld);return ld(o)}});rf=ce("$ZodCustom",(e,t)=>{ht.init(e,t),it.init(e,t),e._zod.parse=(r,n)=>r,e._zod.check=(r)=>{let n=r.value,o=t.fn(n);if(o instanceof Promise)return o.then((s)=>ud(s,r,n,e));ud(o,r,n,e);return}})});function Is(){return{localeError:eb()}}var eb=()=>{let e={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"},map:{unit:"entries",verb:"to have"}};function t(o){return e[o]??null}let r={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"},n={nan:"NaN"};return(o)=>{switch(o.code){case"invalid_type":{let s=n[o.expected]??o.expected,a=eu(o.input),u=n[a]??a;return`Invalid input: expected ${s}, received ${u}`}case"invalid_value":if(o.values.length===1)return`Invalid input: expected ${ys(o.values[0])}`;return`Invalid option: expected one of ${_s(o.values,"|")}`;case"too_big":{let s=o.inclusive?"<=":"<",a=t(o.origin);if(a)return`Too big: expected ${o.origin??"value"} to have ${s}${o.maximum.toString()} ${a.unit??"elements"}`;return`Too big: expected ${o.origin??"value"} to be ${s}${o.maximum.toString()}`}case"too_small":{let s=o.inclusive?">=":">",a=t(o.origin);if(a)return`Too small: expected ${o.origin} to have ${s}${o.minimum.toString()} ${a.unit}`;return`Too small: expected ${o.origin} to be ${s}${o.minimum.toString()}`}case"invalid_format":{let s=o;if(s.format==="starts_with")return`Invalid string: must start with "${s.prefix}"`;if(s.format==="ends_with")return`Invalid string: must end with "${s.suffix}"`;if(s.format==="includes")return`Invalid string: must include "${s.includes}"`;if(s.format==="regex")return`Invalid string: must match pattern ${s.pattern}`;return`Invalid ${r[s.format]??o.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${o.divisor}`;case"unrecognized_keys":return`Unrecognized key${o.keys.length>1?"s":""}: ${_s(o.keys,", ")}`;case"invalid_key":return`Invalid key in ${o.origin}`;case"invalid_union":if(o.options&&Array.isArray(o.options)&&o.options.length>0)return`Invalid discriminator value. Expected ${o.options.map((a)=>`'${a}'`).join(" | ")}`;return"Invalid input";case"invalid_element":return`Invalid value in ${o.origin}`;default:return"Invalid input"}}};var of=De(()=>{Jt()});var Ps=()=>{};class cf{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){let r=t[0];if(this._map.set(e,r),r&&typeof r==="object"&&"id"in r)this._idmap.set(r.id,e);return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let t=this._map.get(e);if(t&&typeof t==="object"&&"id"in t)this._idmap.delete(t.id);return this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let r={...this.get(t)??{}};delete r.id;let n={...r,...this._map.get(e)};return Object.keys(n).length?n:void 0}return this._map.get(e)}has(e){return this._map.has(e)}}function tb(){return new cf}var af,ux,dx,Ur;var Ns=De(()=>{ux=Symbol("ZodOutput"),dx=Symbol("ZodInput");(af=globalThis).__zod_globalRegistry??(af.__zod_globalRegistry=tb());Ur=globalThis.__zod_globalRegistry});function lf(e,t){return new e({type:"string",...Ne(t)})}function uf(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...Ne(t)})}function Cs(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...Ne(t)})}function df(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...Ne(t)})}function ff(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...Ne(t)})}function pf(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...Ne(t)})}function _f(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...Ne(t)})}function gf(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...Ne(t)})}function hf(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...Ne(t)})}function mf(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...Ne(t)})}function yf(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...Ne(t)})}function bf(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...Ne(t)})}function wf(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...Ne(t)})}function vf(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...Ne(t)})}function Ef(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...Ne(t)})}function Sf(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...Ne(t)})}function xf(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...Ne(t)})}function Tf(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...Ne(t)})}function kf(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...Ne(t)})}function Rf(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...Ne(t)})}function Af(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...Ne(t)})}function Df(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...Ne(t)})}function Of(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...Ne(t)})}function If(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...Ne(t)})}function Pf(e,t){return new e({type:"string",format:"date",check:"string_format",...Ne(t)})}function Nf(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...Ne(t)})}function Cf(e,t){return new e({type:"string",format:"duration",check:"string_format",...Ne(t)})}function qf(e,t){return new e({type:"number",checks:[],...Ne(t)})}function Lf(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...Ne(t)})}function $f(e,t){return new e({type:"boolean",...Ne(t)})}function Ff(e){return new e({type:"unknown"})}function zf(e,t){return new e({type:"never",...Ne(t)})}function Vo(e,t){return new xs({check:"less_than",...Ne(t),value:e,inclusive:!1})}function Wn(e,t){return new xs({check:"less_than",...Ne(t),value:e,inclusive:!0})}function Jo(e,t){return new Ts({check:"greater_than",...Ne(t),value:e,inclusive:!1})}function Zn(e,t){return new Ts({check:"greater_than",...Ne(t),value:e,inclusive:!0})}function Xo(e,t){return new ju({check:"multiple_of",...Ne(t),value:e})}function Qo(e,t){return new Wu({check:"max_length",...Ne(t),maximum:e})}function mn(e,t){return new Zu({check:"min_length",...Ne(t),minimum:e})}function Yo(e,t){return new Gu({check:"length_equals",...Ne(t),length:e})}function qs(e,t){return new Ku({check:"string_format",format:"regex",...Ne(t),pattern:e})}function Ls(e){return new Vu({check:"string_format",format:"lowercase",...Ne(e)})}function $s(e){return new Ju({check:"string_format",format:"uppercase",...Ne(e)})}function Fs(e,t){return new Xu({check:"string_format",format:"includes",...Ne(t),includes:e})}function zs(e,t){return new Qu({check:"string_format",format:"starts_with",...Ne(t),prefix:e})}function Ms(e,t){return new Yu({check:"string_format",format:"ends_with",...Ne(t),suffix:e})}function xr(e){return new ed({check:"overwrite",tx:e})}function Bs(e){return xr((t)=>t.normalize(e))}function Us(){return xr((e)=>e.trim())}function js(){return xr((e)=>e.toLowerCase())}function Hs(){return xr((e)=>e.toUpperCase())}function Ws(){return xr((e)=>Kl(e))}function Mf(e,t,r){return new e({type:"array",element:t,...Ne(r)})}function Bf(e,t,r){return new e({type:"custom",check:"custom",fn:t,...Ne(r)})}function Uf(e,t){let r=rb((n)=>(n.addIssue=(o)=>{if(typeof o==="string")n.issues.push(Br(o,n.value,r._zod.def));else{let s=o;if(s.fatal)s.continue=!1;s.code??(s.code="custom"),s.input??(s.input=n.value),s.inst??(s.inst=r),s.continue??(s.continue=!r._zod.def.abort),n.issues.push(Br(s))}},e(n.value,n)),t);return r}function rb(e,t){let r=new ht({check:"custom",...Ne(t)});return r._zod.check=e,r}var jf=De(()=>{Wo();Jt()});function Zs(e){let t=e?.target??"draft-2020-12";if(t==="draft-4")t="draft-04";if(t==="draft-7")t="draft-07";return{processors:e.processors??{},metadataRegistry:e?.metadata??Ur,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,cycles:e?.cycles??"ref",reused:e?.reused??"inline",external:e?.external??void 0}}function _t(e,t,r={path:[],schemaPath:[]}){var n;let o=e._zod.def,s=t.seen.get(e);if(s){if(s.count++,r.schemaPath.includes(e))s.cycle=r.path;return s.schema}let a={schema:{},count:1,cycle:void 0,path:r.path};t.seen.set(e,a);let u=e._zod.toJSONSchema?.();if(u)a.schema=u;else{let x={...r,schemaPath:[...r.schemaPath,e],path:r.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,a.schema,x);else{let j=a.schema,Y=t.processors[o.type];if(!Y)throw Error(`[toJSONSchema]: Non-representable type encountered: ${o.type}`);Y(e,t,j,x)}let D=e._zod.parent;if(D){if(!a.ref)a.ref=D;_t(D,t,x),t.seen.get(D).isParent=!0}}let _=t.metadataRegistry.get(e);if(_)Object.assign(a.schema,_);if(t.io==="input"&&kt(e))delete a.schema.examples,delete a.schema.default;if(t.io==="input"&&"_prefault"in a.schema)(n=a.schema).default??(n.default=a.schema._prefault);return delete a.schema._prefault,t.seen.get(e).schema}function Gs(e,t){let r=e.seen.get(t);if(!r)throw Error("Unprocessed schema. This is a bug in Zod.");let n=new Map;for(let a of e.seen.entries()){let u=e.metadataRegistry.get(a[0])?.id;if(u){let _=n.get(u);if(_&&_!==a[0])throw Error(`Duplicate schema id "${u}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);n.set(u,a[0])}}let o=(a)=>{let u=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){let D=e.external.registry.get(a[0])?.id,j=e.external.uri??((_e)=>_e);if(D)return{ref:j(D)};let Y=a[1].defId??a[1].schema.id??`schema${e.counter++}`;return a[1].defId=Y,{defId:Y,ref:`${j("__shared")}#/${u}/${Y}`}}if(a[1]===r)return{ref:"#"};let m=`${"#"}/${u}/`,x=a[1].schema.id??`__schema${e.counter++}`;return{defId:x,ref:m+x}},s=(a)=>{if(a[1].schema.$ref)return;let u=a[1],{ref:_,defId:m}=o(a);if(u.def={...u.schema},m)u.defId=m;let x=u.schema;for(let D in x)delete x[D];x.$ref=_};if(e.cycles==="throw")for(let a of e.seen.entries()){let u=a[1];if(u.cycle)throw Error(`Cycle detected: #/${u.cycle?.join("/")}/<root>
453
469
 
454
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let a of e.seen.entries()){let u=a[1];if(t===a[0]){s(a);continue}if(e.external){let m=e.external.registry.get(a[0])?.id;if(t!==a[0]&&m){s(a);continue}}if(e.metadataRegistry.get(a[0])?.id){s(a);continue}if(u.cycle){s(a);continue}if(u.count>1){if(e.reused==="ref"){s(a);continue}}}}function Ws(e,t){let r=e.seen.get(t);if(!r)throw Error("Unprocessed schema. This is a bug in Zod.");let n=(u)=>{let _=e.seen.get(u);if(_.ref===null)return;let m=_.def??_.schema,x={...m},D=_.ref;if(_.ref=null,D){n(D);let Y=e.seen.get(D),_e=Y.schema;if(_e.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"))m.allOf=m.allOf??[],m.allOf.push(_e);else Object.assign(m,_e);if(Object.assign(m,x),u._zod.parent===D)for(let ge in m){if(ge==="$ref"||ge==="allOf")continue;if(!(ge in x))delete m[ge]}if(_e.$ref&&Y.def)for(let ge in m){if(ge==="$ref"||ge==="allOf")continue;if(ge in Y.def&&JSON.stringify(m[ge])===JSON.stringify(Y.def[ge]))delete m[ge]}}let j=u._zod.parent;if(j&&j!==D){n(j);let Y=e.seen.get(j);if(Y?.schema.$ref){if(m.$ref=Y.schema.$ref,Y.def)for(let _e in m){if(_e==="$ref"||_e==="allOf")continue;if(_e in Y.def&&JSON.stringify(m[_e])===JSON.stringify(Y.def[_e]))delete m[_e]}}}e.override({zodSchema:u,jsonSchema:m,path:_.path??[]})};for(let u of[...e.seen.entries()].reverse())n(u[0]);let o={};if(e.target==="draft-2020-12")o.$schema="https://json-schema.org/draft/2020-12/schema";else if(e.target==="draft-07")o.$schema="http://json-schema.org/draft-07/schema#";else if(e.target==="draft-04")o.$schema="http://json-schema.org/draft-04/schema#";else if(e.target==="openapi-3.0");if(e.external?.uri){let u=e.external.registry.get(t)?.id;if(!u)throw Error("Schema is missing an `id` property");o.$id=e.external.uri(u)}Object.assign(o,r.def??r.schema);let s=e.metadataRegistry.get(t)?.id;if(s!==void 0&&o.id===s)delete o.id;let a=e.external?.defs??{};for(let u of e.seen.entries()){let _=u[1];if(_.def&&_.defId){if(_.def.id===_.defId)delete _.def.id;a[_.defId]=_.def}}if(e.external);else if(Object.keys(a).length>0)if(e.target==="draft-2020-12")o.$defs=a;else o.definitions=a;try{let u=JSON.parse(JSON.stringify(o));return Object.defineProperty(u,"~standard",{value:{...t["~standard"],jsonSchema:{input:Kn(t,"input",e.processors),output:Kn(t,"output",e.processors)}},enumerable:!1,writable:!1}),u}catch(u){throw Error("Error converting schema to JSON.")}}function kt(e,t){let r=t??{seen:new Set};if(r.seen.has(e))return!1;r.seen.add(e);let n=e._zod.def;if(n.type==="transform")return!0;if(n.type==="array")return kt(n.element,r);if(n.type==="set")return kt(n.valueType,r);if(n.type==="lazy")return kt(n.getter(),r);if(n.type==="promise"||n.type==="optional"||n.type==="nonoptional"||n.type==="nullable"||n.type==="readonly"||n.type==="default"||n.type==="prefault")return kt(n.innerType,r);if(n.type==="intersection")return kt(n.left,r)||kt(n.right,r);if(n.type==="record"||n.type==="map")return kt(n.keyType,r)||kt(n.valueType,r);if(n.type==="pipe"){if(e._zod.traits.has("$ZodCodec"))return!0;return kt(n.in,r)||kt(n.out,r)}if(n.type==="object"){for(let o in n.shape)if(kt(n.shape[o],r))return!0;return!1}if(n.type==="union"){for(let o of n.options)if(kt(o,r))return!0;return!1}if(n.type==="tuple"){for(let o of n.items)if(kt(o,r))return!0;if(n.rest&&kt(n.rest,r))return!0;return!1}return!1}var $f=(e,t={})=>(r)=>{let n=js({...r,processors:t});return _t(e,n),Hs(n,e),Ws(n,e)},Kn=(e,t,r={})=>(n)=>{let{libraryOptions:o,target:s}=n??{},a=js({...o??{},target:s,io:t,processors:r});return _t(e,a),Hs(a,e),Ws(a,e)};var ei=De(()=>{Os()});var Zy,zf=(e,t,r,n)=>{let o=r;o.type="string";let{minimum:s,maximum:a,format:u,patterns:_,contentEncoding:m}=e._zod.bag;if(typeof s==="number")o.minLength=s;if(typeof a==="number")o.maxLength=a;if(u){if(o.format=Zy[u]??u,o.format==="")delete o.format;if(u==="time")delete o.format}if(m)o.contentEncoding=m;if(_&&_.size>0){let x=[..._];if(x.length===1)o.pattern=x[0].source;else if(x.length>1)o.allOf=[...x.map((D)=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:D.source}))]}},Ff=(e,t,r,n)=>{let o=r,{minimum:s,maximum:a,format:u,multipleOf:_,exclusiveMaximum:m,exclusiveMinimum:x}=e._zod.bag;if(typeof u==="string"&&u.includes("int"))o.type="integer";else o.type="number";let D=typeof x==="number"&&x>=(s??Number.NEGATIVE_INFINITY),j=typeof m==="number"&&m<=(a??Number.POSITIVE_INFINITY),Y=t.target==="draft-04"||t.target==="openapi-3.0";if(D)if(Y)o.minimum=x,o.exclusiveMinimum=!0;else o.exclusiveMinimum=x;else if(typeof s==="number")o.minimum=s;if(j)if(Y)o.maximum=m,o.exclusiveMaximum=!0;else o.exclusiveMaximum=m;else if(typeof a==="number")o.maximum=a;if(typeof _==="number")o.multipleOf=_},Mf=(e,t,r,n)=>{r.type="boolean"},Bf=(e,t,r,n)=>{r.not={}},Uf=(e,t,r,n)=>{},jf=(e,t,r,n)=>{let o=e._zod.def,s=No(o.entries);if(s.every((a)=>typeof a==="number"))r.type="number";if(s.every((a)=>typeof a==="string"))r.type="string";r.enum=s},Hf=(e,t,r,n)=>{let o=e._zod.def,s=[];for(let a of o.values)if(a===void 0){if(t.unrepresentable==="throw")throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof a==="bigint")if(t.unrepresentable==="throw")throw Error("BigInt literals cannot be represented in JSON Schema");else s.push(Number(a));else s.push(a);if(s.length===0);else if(s.length===1){let a=s[0];if(r.type=a===null?"null":typeof a,t.target==="draft-04"||t.target==="openapi-3.0")r.enum=[a];else r.const=a}else{if(s.every((a)=>typeof a==="number"))r.type="number";if(s.every((a)=>typeof a==="string"))r.type="string";if(s.every((a)=>typeof a==="boolean"))r.type="boolean";if(s.every((a)=>a===null))r.type="null";r.enum=s}},Wf=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw Error("Custom types cannot be represented in JSON Schema")},Zf=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw Error("Transforms cannot be represented in JSON Schema")},Gf=(e,t,r,n)=>{let o=r,s=e._zod.def,{minimum:a,maximum:u}=e._zod.bag;if(typeof a==="number")o.minItems=a;if(typeof u==="number")o.maxItems=u;o.type="array",o.items=_t(s.element,t,{...n,path:[...n.path,"items"]})},Kf=(e,t,r,n)=>{let o=r,s=e._zod.def;o.type="object",o.properties={};let a=s.shape;for(let m in a)o.properties[m]=_t(a[m],t,{...n,path:[...n.path,"properties",m]});let u=new Set(Object.keys(a)),_=new Set([...u].filter((m)=>{let x=s.shape[m]._zod;if(t.io==="input")return x.optin===void 0;else return x.optout===void 0}));if(_.size>0)o.required=Array.from(_);if(s.catchall?._zod.def.type==="never")o.additionalProperties=!1;else if(!s.catchall){if(t.io==="output")o.additionalProperties=!1}else if(s.catchall)o.additionalProperties=_t(s.catchall,t,{...n,path:[...n.path,"additionalProperties"]})},Vf=(e,t,r,n)=>{let o=e._zod.def,s=o.inclusive===!1,a=o.options.map((u,_)=>_t(u,t,{...n,path:[...n.path,s?"oneOf":"anyOf",_]}));if(s)r.oneOf=a;else r.anyOf=a},Jf=(e,t,r,n)=>{let o=e._zod.def,s=_t(o.left,t,{...n,path:[...n.path,"allOf",0]}),a=_t(o.right,t,{...n,path:[...n.path,"allOf",1]}),u=(m)=>("allOf"in m)&&Object.keys(m).length===1,_=[...u(s)?s.allOf:[s],...u(a)?a.allOf:[a]];r.allOf=_},Xf=(e,t,r,n)=>{let o=e._zod.def,s=_t(o.innerType,t,n),a=t.seen.get(e);if(t.target==="openapi-3.0")a.ref=o.innerType,r.nullable=!0;else r.anyOf=[s,{type:"null"}]},Qf=(e,t,r,n)=>{let o=e._zod.def;_t(o.innerType,t,n);let s=t.seen.get(e);s.ref=o.innerType},Yf=(e,t,r,n)=>{let o=e._zod.def;_t(o.innerType,t,n);let s=t.seen.get(e);s.ref=o.innerType,r.default=JSON.parse(JSON.stringify(o.defaultValue))},ep=(e,t,r,n)=>{let o=e._zod.def;_t(o.innerType,t,n);let s=t.seen.get(e);if(s.ref=o.innerType,t.io==="input")r._prefault=JSON.parse(JSON.stringify(o.defaultValue))},tp=(e,t,r,n)=>{let o=e._zod.def;_t(o.innerType,t,n);let s=t.seen.get(e);s.ref=o.innerType;let a;try{a=o.catchValue(void 0)}catch{throw Error("Dynamic catch values are not supported in JSON Schema")}r.default=a},rp=(e,t,r,n)=>{let o=e._zod.def,s=o.in._zod.traits.has("$ZodTransform"),a=t.io==="input"?s?o.out:o.in:o.out;_t(a,t,n);let u=t.seen.get(e);u.ref=a},np=(e,t,r,n)=>{let o=e._zod.def;_t(o.innerType,t,n);let s=t.seen.get(e);s.ref=o.innerType,r.readOnly=!0},Zs=(e,t,r,n)=>{let o=e._zod.def;_t(o.innerType,t,n);let s=t.seen.get(e);s.ref=o.innerType};var op=De(()=>{ei();Vt();Zy={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""}});var ip=()=>{};var rr=De(()=>{Vt();Ho();Ds();ip();zr();ys();ms();Jd();Wo();xs();Os();Lf();ei()});var Gs=De(()=>{rr()});function sp(e){return xf(Yy,e)}function ap(e){return Tf(eb,e)}function cp(e){return kf(tb,e)}function lp(e){return Rf(rb,e)}var Yy,eb,tb,rb;var Ks=De(()=>{rr();Vs();Yy=ce("ZodISODateTime",(e,t)=>{gd.init(e,t),ot.init(e,t)});eb=ce("ZodISODate",(e,t)=>{hd.init(e,t),ot.init(e,t)});tb=ce("ZodISOTime",(e,t)=>{md.init(e,t),ot.init(e,t)});rb=ce("ZodISODuration",(e,t)=>{yd.init(e,t),ot.init(e,t)})});var ob=(e,t)=>{Mo.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:(r)=>Jl(e,r)},flatten:{value:(r)=>Vl(e,r)},addIssue:{value:(r)=>{e.issues.push(r),e.message=JSON.stringify(e.issues,Un,2)}},addIssues:{value:(r)=>{e.issues.push(...r),e.message=JSON.stringify(e.issues,Un,2)}},isEmpty:{get(){return e.issues.length===0}}})},qt;var Js=De(()=>{rr();rr();Vt();qt=ce("ZodError",ob,{Parent:Error})});var dp,fp,pp,_p,gp,hp,mp,yp,bp,wp,vp,Ep;var Xs=De(()=>{rr();Js();dp=Bo(qt),fp=Uo(qt),pp=jn(qt),_p=Hn(qt),gp=Yl(qt),hp=eu(qt),mp=tu(qt),yp=ru(qt),bp=nu(qt),wp=ou(qt),vp=iu(qt),Ep=su(qt)});function Jn(e,t,r){let n=Object.getPrototypeOf(e),o=Sp.get(n);if(!o)o=new Set,Sp.set(n,o);if(o.has(t))return;o.add(t);for(let s in r){let a=r[s];Object.defineProperty(n,s,{configurable:!0,enumerable:!1,get(){let u=a.bind(this);return Object.defineProperty(this,s,{configurable:!0,writable:!0,enumerable:!0,value:u}),u},set(u){Object.defineProperty(this,s,{configurable:!0,writable:!0,enumerable:!0,value:u})}})}}function at(e){return tf(sb,e)}function ri(e){return Af(Ip,e)}function Tp(e){return Df(xb,e)}function kb(e){return Of(Tb,e)}function kp(){return If(Rb)}function Db(e){return Pf(Ab,e)}function Xn(e,t){return Cf(Ob,e,t)}function jr(e,t){let r={type:"object",shape:e??{},...Ce(t)};return new Ib(r)}function Cb(e,t){return new Pb({type:"union",options:e,...Ce(t)})}function qb(e,t){return new Nb({type:"intersection",left:e,right:t})}function ni(e,t){let r=Array.isArray(e)?Object.fromEntries(e.map((n)=>[n,n])):e;return new Qs({type:"enum",entries:r,...Ce(t)})}function $b(e,t){return new Lb({type:"literal",values:Array.isArray(e)?e:[e],...Ce(t)})}function Fb(e){return new zb({type:"transform",transform:e})}function Rp(e){return new Pp({type:"optional",innerType:e})}function Bb(e){return new Mb({type:"optional",innerType:e})}function Ap(e){return new Ub({type:"nullable",innerType:e})}function Hb(e,t){return new jb({type:"default",innerType:e,get defaultValue(){return typeof t==="function"?t():_s(t)}})}function Zb(e,t){return new Wb({type:"prefault",innerType:e,get defaultValue(){return typeof t==="function"?t():_s(t)}})}function Gb(e,t){return new Cp({type:"nonoptional",innerType:e,...Ce(t)})}function Vb(e,t){return new Kb({type:"catch",innerType:e,catchValue:typeof t==="function"?t:()=>t})}function Dp(e,t){return new Jb({type:"pipe",in:e,out:t})}function Qb(e){return new Xb({type:"readonly",innerType:e})}function ew(e,t={}){return Nf(Yb,e,t)}function tw(e,t){return qf(e,t)}var Sp,st,Op,sb,ot,ab,xp,ti,cb,lb,ub,db,fb,pb,_b,gb,hb,mb,yb,bb,wb,vb,Eb,Sb,Ip,xb,Tb,Rb,Ab,Ob,Ib,Pb,Nb,Qs,Lb,zb,Pp,Mb,Ub,jb,Wb,Cp,Kb,Jb,Xb,Yb;var Vs=De(()=>{rr();rr();op();ei();Gs();Ks();Xs();Sp=new WeakMap;st=ce("ZodType",(e,t)=>(it.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:Kn(e,"input"),output:Kn(e,"output")}}),e.toJSONSchema=$f(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(r,n)=>dp(e,r,n,{callee:e.parse}),e.safeParse=(r,n)=>pp(e,r,n),e.parseAsync=async(r,n)=>fp(e,r,n,{callee:e.parseAsync}),e.safeParseAsync=async(r,n)=>_p(e,r,n),e.spa=e.safeParseAsync,e.encode=(r,n)=>gp(e,r,n),e.decode=(r,n)=>hp(e,r,n),e.encodeAsync=async(r,n)=>mp(e,r,n),e.decodeAsync=async(r,n)=>yp(e,r,n),e.safeEncode=(r,n)=>bp(e,r,n),e.safeDecode=(r,n)=>wp(e,r,n),e.safeEncodeAsync=async(r,n)=>vp(e,r,n),e.safeDecodeAsync=async(r,n)=>Ep(e,r,n),Jn(e,"ZodType",{check(...r){let n=this.def;return this.clone(Er(n,{checks:[...n.checks??[],...r.map((o)=>typeof o==="function"?{_zod:{check:o,def:{check:"custom"},onattach:[]}}:o)]}),{parent:!0})},with(...r){return this.check(...r)},clone(r,n){return tr(this,r,n)},brand(){return this},register(r,n){return r.add(this,n),this},refine(r,n){return this.check(ew(r,n))},superRefine(r,n){return this.check(tw(r,n))},overwrite(r){return this.check(xr(r))},optional(){return Rp(this)},exactOptional(){return Bb(this)},nullable(){return Ap(this)},nullish(){return Rp(Ap(this))},nonoptional(r){return Gb(this,r)},array(){return Xn(this)},or(r){return Cb([this,r])},and(r){return qb(this,r)},transform(r){return Dp(this,Fb(r))},default(r){return Hb(this,r)},prefault(r){return Zb(this,r)},catch(r){return Vb(this,r)},pipe(r){return Dp(this,r)},readonly(){return Qb(this)},describe(r){let n=this.clone();return Ur.add(n,{description:r}),n},meta(...r){if(r.length===0)return Ur.get(this);let n=this.clone();return Ur.add(n,r[0]),n},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(r){return r(this)}}),Object.defineProperty(e,"description",{get(){return Ur.get(e)?.description},configurable:!0}),e)),Op=ce("_ZodString",(e,t)=>{Ko.init(e,t),st.init(e,t),e._zod.processJSONSchema=(n,o,s)=>zf(e,n,o,s);let r=e._zod.bag;e.format=r.format??null,e.minLength=r.minimum??null,e.maxLength=r.maximum??null,Jn(e,"_ZodString",{regex(...n){return this.check(Ps(...n))},includes(...n){return this.check(qs(...n))},startsWith(...n){return this.check(Ls(...n))},endsWith(...n){return this.check($s(...n))},min(...n){return this.check(yn(...n))},max(...n){return this.check(Qo(...n))},length(...n){return this.check(Yo(...n))},nonempty(...n){return this.check(yn(1,...n))},lowercase(n){return this.check(Cs(n))},uppercase(n){return this.check(Ns(n))},trim(){return this.check(Fs())},normalize(...n){return this.check(zs(...n))},toLowerCase(){return this.check(Ms())},toUpperCase(){return this.check(Bs())},slugify(){return this.check(Us())}})}),sb=ce("ZodString",(e,t)=>{Ko.init(e,t),Op.init(e,t),e.email=(r)=>e.check(rf(ab,r)),e.url=(r)=>e.check(cf(cb,r)),e.jwt=(r)=>e.check(Sf(Sb,r)),e.emoji=(r)=>e.check(lf(lb,r)),e.guid=(r)=>e.check(Is(xp,r)),e.uuid=(r)=>e.check(nf(ti,r)),e.uuidv4=(r)=>e.check(of(ti,r)),e.uuidv6=(r)=>e.check(sf(ti,r)),e.uuidv7=(r)=>e.check(af(ti,r)),e.nanoid=(r)=>e.check(uf(ub,r)),e.guid=(r)=>e.check(Is(xp,r)),e.cuid=(r)=>e.check(df(db,r)),e.cuid2=(r)=>e.check(ff(fb,r)),e.ulid=(r)=>e.check(pf(pb,r)),e.base64=(r)=>e.check(wf(wb,r)),e.base64url=(r)=>e.check(vf(vb,r)),e.xid=(r)=>e.check(_f(_b,r)),e.ksuid=(r)=>e.check(gf(gb,r)),e.ipv4=(r)=>e.check(hf(hb,r)),e.ipv6=(r)=>e.check(mf(mb,r)),e.cidrv4=(r)=>e.check(yf(yb,r)),e.cidrv6=(r)=>e.check(bf(bb,r)),e.e164=(r)=>e.check(Ef(Eb,r)),e.datetime=(r)=>e.check(sp(r)),e.date=(r)=>e.check(ap(r)),e.time=(r)=>e.check(cp(r)),e.duration=(r)=>e.check(lp(r))});ot=ce("ZodStringFormat",(e,t)=>{rt.init(e,t),Op.init(e,t)}),ab=ce("ZodEmail",(e,t)=>{sd.init(e,t),ot.init(e,t)}),xp=ce("ZodGUID",(e,t)=>{od.init(e,t),ot.init(e,t)}),ti=ce("ZodUUID",(e,t)=>{id.init(e,t),ot.init(e,t)}),cb=ce("ZodURL",(e,t)=>{ad.init(e,t),ot.init(e,t)}),lb=ce("ZodEmoji",(e,t)=>{cd.init(e,t),ot.init(e,t)}),ub=ce("ZodNanoID",(e,t)=>{ld.init(e,t),ot.init(e,t)}),db=ce("ZodCUID",(e,t)=>{ud.init(e,t),ot.init(e,t)}),fb=ce("ZodCUID2",(e,t)=>{dd.init(e,t),ot.init(e,t)}),pb=ce("ZodULID",(e,t)=>{fd.init(e,t),ot.init(e,t)}),_b=ce("ZodXID",(e,t)=>{pd.init(e,t),ot.init(e,t)}),gb=ce("ZodKSUID",(e,t)=>{_d.init(e,t),ot.init(e,t)}),hb=ce("ZodIPv4",(e,t)=>{bd.init(e,t),ot.init(e,t)}),mb=ce("ZodIPv6",(e,t)=>{wd.init(e,t),ot.init(e,t)}),yb=ce("ZodCIDRv4",(e,t)=>{vd.init(e,t),ot.init(e,t)}),bb=ce("ZodCIDRv6",(e,t)=>{Ed.init(e,t),ot.init(e,t)}),wb=ce("ZodBase64",(e,t)=>{xd.init(e,t),ot.init(e,t)}),vb=ce("ZodBase64URL",(e,t)=>{Td.init(e,t),ot.init(e,t)}),Eb=ce("ZodE164",(e,t)=>{kd.init(e,t),ot.init(e,t)}),Sb=ce("ZodJWT",(e,t)=>{Rd.init(e,t),ot.init(e,t)}),Ip=ce("ZodNumber",(e,t)=>{ks.init(e,t),st.init(e,t),e._zod.processJSONSchema=(n,o,s)=>Ff(e,n,o,s),Jn(e,"ZodNumber",{gt(n,o){return this.check(Jo(n,o))},gte(n,o){return this.check(Gn(n,o))},min(n,o){return this.check(Gn(n,o))},lt(n,o){return this.check(Vo(n,o))},lte(n,o){return this.check(Zn(n,o))},max(n,o){return this.check(Zn(n,o))},int(n){return this.check(Tp(n))},safe(n){return this.check(Tp(n))},positive(n){return this.check(Jo(0,n))},nonnegative(n){return this.check(Gn(0,n))},negative(n){return this.check(Vo(0,n))},nonpositive(n){return this.check(Zn(0,n))},multipleOf(n,o){return this.check(Xo(n,o))},step(n,o){return this.check(Xo(n,o))},finite(){return this}});let r=e._zod.bag;e.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??0.5),e.isFinite=!0,e.format=r.format??null});xb=ce("ZodNumberFormat",(e,t)=>{Ad.init(e,t),Ip.init(e,t)});Tb=ce("ZodBoolean",(e,t)=>{Dd.init(e,t),st.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Mf(e,r,n,o)});Rb=ce("ZodUnknown",(e,t)=>{Od.init(e,t),st.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Uf(e,r,n,o)});Ab=ce("ZodNever",(e,t)=>{Id.init(e,t),st.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Bf(e,r,n,o)});Ob=ce("ZodArray",(e,t)=>{Pd.init(e,t),st.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Gf(e,r,n,o),e.element=t.element,Jn(e,"ZodArray",{min(r,n){return this.check(yn(r,n))},nonempty(r){return this.check(yn(1,r))},max(r,n){return this.check(Qo(r,n))},length(r,n){return this.check(Yo(r,n))},unwrap(){return this.element}})});Ib=ce("ZodObject",(e,t)=>{qd.init(e,t),st.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Kf(e,r,n,o),Ve(e,"shape",()=>t.shape),Jn(e,"ZodObject",{keyof(){return ni(Object.keys(this._zod.def.shape))},catchall(r){return this.clone({...this._zod.def,catchall:r})},passthrough(){return this.clone({...this._zod.def,catchall:kp()})},loose(){return this.clone({...this._zod.def,catchall:kp()})},strict(){return this.clone({...this._zod.def,catchall:Db()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(r){return Cy(this,r)},safeExtend(r){return Ny(this,r)},merge(r){return qy(this,r)},pick(r){return Iy(this,r)},omit(r){return Py(this,r)},partial(...r){return Ly(Pp,this,r[0])},required(...r){return $y(Cp,this,r[0])}})});Pb=ce("ZodUnion",(e,t)=>{Ld.init(e,t),st.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Vf(e,r,n,o),e.options=t.options});Nb=ce("ZodIntersection",(e,t)=>{$d.init(e,t),st.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Jf(e,r,n,o)});Qs=ce("ZodEnum",(e,t)=>{zd.init(e,t),st.init(e,t),e._zod.processJSONSchema=(n,o,s)=>jf(e,n,o,s),e.enum=t.entries,e.options=Object.values(t.entries);let r=new Set(Object.keys(t.entries));e.extract=(n,o)=>{let s={};for(let a of n)if(r.has(a))s[a]=t.entries[a];else throw Error(`Key ${a} not found in enum`);return new Qs({...t,checks:[],...Ce(o),entries:s})},e.exclude=(n,o)=>{let s={...t.entries};for(let a of n)if(r.has(a))delete s[a];else throw Error(`Key ${a} not found in enum`);return new Qs({...t,checks:[],...Ce(o),entries:s})}});Lb=ce("ZodLiteral",(e,t)=>{Fd.init(e,t),st.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Hf(e,r,n,o),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});zb=ce("ZodTransform",(e,t)=>{Md.init(e,t),st.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Zf(e,r,n,o),e._zod.parse=(r,n)=>{if(n.direction==="backward")throw new Mn(e.constructor.name);r.addIssue=(s)=>{if(typeof s==="string")r.issues.push(Br(s,r.value,t));else{let a=s;if(a.fatal)a.continue=!1;a.code??(a.code="custom"),a.input??(a.input=r.value),a.inst??(a.inst=e),r.issues.push(Br(a))}};let o=t.transform(r.value,r);if(o instanceof Promise)return o.then((s)=>(r.value=s,r.fallback=!0,r));return r.value=o,r.fallback=!0,r}});Pp=ce("ZodOptional",(e,t)=>{Rs.init(e,t),st.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Zs(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});Mb=ce("ZodExactOptional",(e,t)=>{Bd.init(e,t),st.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Zs(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});Ub=ce("ZodNullable",(e,t)=>{Ud.init(e,t),st.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Xf(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});jb=ce("ZodDefault",(e,t)=>{jd.init(e,t),st.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Yf(e,r,n,o),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});Wb=ce("ZodPrefault",(e,t)=>{Hd.init(e,t),st.init(e,t),e._zod.processJSONSchema=(r,n,o)=>ep(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});Cp=ce("ZodNonOptional",(e,t)=>{Wd.init(e,t),st.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Qf(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});Kb=ce("ZodCatch",(e,t)=>{Zd.init(e,t),st.init(e,t),e._zod.processJSONSchema=(r,n,o)=>tp(e,r,n,o),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});Jb=ce("ZodPipe",(e,t)=>{Gd.init(e,t),st.init(e,t),e._zod.processJSONSchema=(r,n,o)=>rp(e,r,n,o),e.in=t.in,e.out=t.out});Xb=ce("ZodReadonly",(e,t)=>{Kd.init(e,t),st.init(e,t),e._zod.processJSONSchema=(r,n,o)=>np(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});Yb=ce("ZodCustom",(e,t)=>{Vd.init(e,t),st.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Wf(e,r,n,o)})});var Np;var qp=De(()=>{(function(e){})(Np||(Np={}))});var Lp=()=>{};var ea=De(()=>{rr();rr();Xd();Ds();Ks();Lp();Vs();Gs();Js();Xs();qp();Kt(As())});var ta=De(()=>{ea();ea()});var $p,XT,QT,zp,YT,ek,Fp="/sync",Mp="/health",Bp="/api/pair";var oi=De(()=>{ta();$p=jr({hlc:at().describe("Hybrid Logical Clock timestamp"),node_id:at().describe("Origin node that produced the change"),dataset:at().describe("CRDT dataset, e.g. databases / records / documents"),row_id:at().describe("Row identifier within the dataset"),col:at().describe("Column / property identifier"),value:at().nullable().describe("JSON-encoded field value, or null"),txn:at().nullable().optional().describe("Change-group id (one logical mutation)")}),XT=jr({node_id:at().describe("Calling client's node id"),since:ri().describe("Server cursor the client last pulled"),changes:Xn($p).describe("Client's changes to push"),limit:ri().optional().describe("Max changes to return (pagination for hydration)"),exclude_datasets:Xn(at()).optional().describe("Datasets to omit from the pull (partial replica)")}),QT=jr({node_id:at().describe("Server's node id"),changes:Xn($p).describe("Server changes after `since`"),cursor:ri().describe("New server cursor for the client to store")}),zp=jr({ok:kb(),node:at().describe("Server's node id"),capabilities:Xn(at()).optional().describe("Optional protocol features supported by this server"),version:at().optional().describe("Core version, for mixed-version workspace warnings")}),YT=jr({code:at().describe("One-time pairing code minted by this server"),node_id:at().describe("Calling device's node id"),grant:at().describe("Durable credential the caller issues to us"),self_url:at().optional().describe("Caller's reachable server URL (for mutual sync)")}),ek=jr({node_id:at().describe("This server's node id"),grant:at().describe("Durable credential we issue to the caller")})});function nw(e,t){return e.query("SELECT pull_cursor, push_cursor, token FROM peers WHERE url = ?").get(t)??{pull_cursor:0,push_cursor:0,token:null}}function ow(e,t,r){e.query("INSERT INTO peers (url, pull_cursor, push_cursor) VALUES (?, ?, ?) ON CONFLICT(url) DO UPDATE SET pull_cursor = excluded.pull_cursor, push_cursor = excluded.push_cursor").run(t,r.pull_cursor,r.push_cursor)}function iw(e,t,r){if(r.length===0)return t;let n=new Set(r.map(Up)),o=e.query("SELECT rowid AS seq, hlc, node_id, dataset, row_id, col FROM crdt_changes WHERE rowid > ? ORDER BY rowid").all(t),s=t;for(let a of o){if(!n.has(Up(a)))break;s=a.seq}return s}async function ii(e,t,r={}){let n=typeof r==="string"?{token:r}:r,o=We(e),s=nw(e,t),a=n.token??s.token??void 0,u=br(e,s.push_cursor),_={"content-type":"application/json"};if(a)_.authorization=`Bearer ${a}`;let m=await fetch(new URL(Fp,t),{method:"POST",headers:_,body:JSON.stringify({node_id:o,since:s.pull_cursor,changes:u.changes,...n.pullLimit!=null?{limit:n.pullLimit}:{},...n.excludeDatasets?.length?{exclude_datasets:n.excludeDatasets}:{}}),signal:AbortSignal.timeout(n.timeoutMs??30000)});if(!m.ok)throw new Z(m.status===401||m.status===403?"auth":"network",`sync failed: ${m.status} ${await m.text()}`);let x=await m.json(),D=x.changes??[],j=er(e,D);return ow(e,t,{pull_cursor:x.cursor,push_cursor:iw(e,u.cursor,D)}),{pushed:u.changes.length,pulled:j,received:D.length}}var Up=(e)=>`${e.hlc}\x00${e.node_id}\x00${e.dataset}\x00${e.row_id}\x00${e.col}`;var ra=De(()=>{Gt();dt();oi();Ye()});async function Hp(e,t,r,n,o=Date.now()){let s=`${t}\x00${r}`;if(o-(jp.get(s)??0)>=1e5){let m={node:r,priority:n,expiresAt:o+300000};await e.put(aw(t,r),new TextEncoder().encode(JSON.stringify(m)),{contentType:"application/json"}),jp.set(s,o)}let a=null,u=[];for(let m of await e.list(sw(t))){if(!m.key.endsWith(".lease"))continue;let x=await e.get(m.key);if(!x)continue;let D;try{D=JSON.parse(new TextDecoder().decode(x))}catch{continue}if(!D.node||D.expiresAt<=o){if(D.expiresAt<=o-300000)u.push(m.key);continue}if(!a||D.priority>a.priority||D.priority===a.priority&&D.node<a.node)a=D}let _=a?a.node===r:!0;if(_)for(let m of u)await e.del(m);return _}var sw=(e)=>`${e}/publisher/`,aw=(e,t)=>`${e}/publisher/${t}.lease`,jp;var Wp=De(()=>{jp=new Map});function Jt(e){let t=new Uint8Array(e.byteLength);return t.set(e),t.buffer}function nr(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return btoa(t)}function Xt(e){let t=atob(e),r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t.charCodeAt(n);return r}function na(){return crypto.getRandomValues(new Uint8Array(lw))}async function Gp(e,t){let r=await crypto.subtle.importKey("raw",Jt(new TextEncoder().encode(e)),"PBKDF2",!1,["deriveKey"]);return crypto.subtle.deriveKey({name:"PBKDF2",salt:Jt(t),iterations:Zp,hash:"SHA-256"},r,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async function Kp(e,t){let r=crypto.getRandomValues(new Uint8Array(cw)),n=await Gp(t,r),o=crypto.getRandomValues(new Uint8Array(bn)),s=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:Jt(o)},n,Jt(e))),a=new Uint8Array(o.length+s.length);return a.set(o,0),a.set(s,o.length),{v:1,kdf:"PBKDF2-SHA256",iter:Zp,salt:nr(r),wrap:"AES-GCM",wrapped_key:nr(a)}}async function oa(e,t){if(e.v!==1||e.kdf!=="PBKDF2-SHA256"||e.wrap!=="AES-GCM")throw new Z("invalid_input","unsupported key envelope format");let r=Xt(e.salt),n=await Gp(t,r),o=Xt(e.wrapped_key),s=o.subarray(0,bn),a=o.subarray(bn);try{let u=await crypto.subtle.decrypt({name:"AES-GCM",iv:Jt(s)},n,Jt(a));return new Uint8Array(u)}catch{throw new Z("auth","wrong passphrase — could not unwrap the master key")}}async function Vp(e){return crypto.subtle.importKey("raw",Jt(e),{name:"AES-GCM"},!1,["encrypt","decrypt"])}async function pr(e,t){let r=await Vp(e),n=crypto.getRandomValues(new Uint8Array(bn)),o=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:Jt(n)},r,Jt(t))),s=new Uint8Array(n.length+o.length);return s.set(n,0),s.set(o,n.length),s}async function Hr(e,t){let r=await Vp(e),n=t.subarray(0,bn),o=t.subarray(bn);try{let s=await crypto.subtle.decrypt({name:"AES-GCM",iv:Jt(n)},r,Jt(o));return new Uint8Array(s)}catch{throw new Z("auth","could not decrypt — wrong master key or corrupt data")}}var Zp=600000,cw=16,bn=12,lw=32;var Qn=De(()=>{Ye()});function Yp(e){if(e.virtualHostedStyle!=null)return e.virtualHostedStyle;try{return new URL(e.endpoint).hostname.startsWith(`${e.bucket}.`)}catch{return!1}}function e_(e){ia=e}function Bt(e){if(!ia)throw new Z("network","no S3 storage client is registered for this runtime");return ia(e)}function eo(e){let t=(e||"").replace(/^\/+|\/+$/g,"");return t?`${t}/spaces/default`:"spaces/default"}function la(e){let t=new Uint8Array(e.byteLength);return t.set(e),t.buffer}async function r_(e){let t=new Response(la(e)).body.pipeThrough(new CompressionStream("gzip"));return new Uint8Array(await new Response(t).arrayBuffer())}async function n_(e){let t=new Response(la(e)).body.pipeThrough(new DecompressionStream("gzip"));return new Uint8Array(await new Response(t).arrayBuffer())}function yw(e){return e.map((t)=>JSON.stringify(t)).join(`
455
- `)}async function o_(e,t){let r=await r_(new TextEncoder().encode(yw(e)));return t?pr(t,r):r}async function i_(e,t){let r=t?await Hr(t,e):e,n=new TextDecoder().decode(await n_(r));if(!n)return[];return n.split(`
456
- `).filter((o)=>o.length>0).map((o)=>JSON.parse(o))}function si(e){if(!e.encrypt)return null;if(!e.masterKey)throw new Z("invalid_input","encrypted bucket but master key missing — refusing to read/write plaintext");return Xt(e.masterKey)}async function a_(e,t,r){let n=Bt(e),o=s_(eo(e.prefix),t),s=si(e),a=s?await pr(s,r):r;try{return await n.put(o,a,{ifNoneMatch:!0,contentType:"application/octet-stream"}),!0}catch(u){if(ln(u)==="conflict")return!1;throw u}}async function ua(e,t){let n=await Bt(e).get(s_(eo(e.prefix),t));if(!n)return null;let o=si(e);return o?Hr(o,n):n}async function bw(e){let t=await crypto.subtle.digest("SHA-256",la(new TextEncoder().encode(e)));return[...new Uint8Array(t)].map((r)=>r.toString(16).padStart(2,"0")).join("").slice(0,16)}function ww(e,t){return e.query("SELECT push_cursor FROM peers WHERE url = ?").get(t)?.push_cursor??0}function Xp(e,t,r){e.query("UPDATE peers SET push_cursor = ? WHERE url = ?").run(r,t)}function da(e,t,r){return e.query("SELECT last_key FROM storage_cursors WHERE peer_url = ? AND node_id = ?").get(t,r)?.last_key??null}function fa(e,t,r,n){e.query("INSERT INTO storage_cursors (peer_url, node_id, last_key) VALUES (?, ?, ?) ON CONFLICT(peer_url, node_id) DO UPDATE SET last_key = excluded.last_key").run(t,r,n)}function vw(e,t){let r=da(e,t,t_);return new Set(r?r.split(`
457
- `).filter(Boolean):[])}function Ew(e,t,r){fa(e,t,t_,[...r].join(`
458
- `))}function Sw(e,t=Date.now()){let r=e.query(`SELECT ${It} FROM crdt_changes c
470
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let a of e.seen.entries()){let u=a[1];if(t===a[0]){s(a);continue}if(e.external){let m=e.external.registry.get(a[0])?.id;if(t!==a[0]&&m){s(a);continue}}if(e.metadataRegistry.get(a[0])?.id){s(a);continue}if(u.cycle){s(a);continue}if(u.count>1){if(e.reused==="ref"){s(a);continue}}}}function Ks(e,t){let r=e.seen.get(t);if(!r)throw Error("Unprocessed schema. This is a bug in Zod.");let n=(u)=>{let _=e.seen.get(u);if(_.ref===null)return;let m=_.def??_.schema,x={...m},D=_.ref;if(_.ref=null,D){n(D);let Y=e.seen.get(D),_e=Y.schema;if(_e.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"))m.allOf=m.allOf??[],m.allOf.push(_e);else Object.assign(m,_e);if(Object.assign(m,x),u._zod.parent===D)for(let ge in m){if(ge==="$ref"||ge==="allOf")continue;if(!(ge in x))delete m[ge]}if(_e.$ref&&Y.def)for(let ge in m){if(ge==="$ref"||ge==="allOf")continue;if(ge in Y.def&&JSON.stringify(m[ge])===JSON.stringify(Y.def[ge]))delete m[ge]}}let j=u._zod.parent;if(j&&j!==D){n(j);let Y=e.seen.get(j);if(Y?.schema.$ref){if(m.$ref=Y.schema.$ref,Y.def)for(let _e in m){if(_e==="$ref"||_e==="allOf")continue;if(_e in Y.def&&JSON.stringify(m[_e])===JSON.stringify(Y.def[_e]))delete m[_e]}}}e.override({zodSchema:u,jsonSchema:m,path:_.path??[]})};for(let u of[...e.seen.entries()].reverse())n(u[0]);let o={};if(e.target==="draft-2020-12")o.$schema="https://json-schema.org/draft/2020-12/schema";else if(e.target==="draft-07")o.$schema="http://json-schema.org/draft-07/schema#";else if(e.target==="draft-04")o.$schema="http://json-schema.org/draft-04/schema#";else if(e.target==="openapi-3.0");if(e.external?.uri){let u=e.external.registry.get(t)?.id;if(!u)throw Error("Schema is missing an `id` property");o.$id=e.external.uri(u)}Object.assign(o,r.def??r.schema);let s=e.metadataRegistry.get(t)?.id;if(s!==void 0&&o.id===s)delete o.id;let a=e.external?.defs??{};for(let u of e.seen.entries()){let _=u[1];if(_.def&&_.defId){if(_.def.id===_.defId)delete _.def.id;a[_.defId]=_.def}}if(e.external);else if(Object.keys(a).length>0)if(e.target==="draft-2020-12")o.$defs=a;else o.definitions=a;try{let u=JSON.parse(JSON.stringify(o));return Object.defineProperty(u,"~standard",{value:{...t["~standard"],jsonSchema:{input:Gn(t,"input",e.processors),output:Gn(t,"output",e.processors)}},enumerable:!1,writable:!1}),u}catch(u){throw Error("Error converting schema to JSON.")}}function kt(e,t){let r=t??{seen:new Set};if(r.seen.has(e))return!1;r.seen.add(e);let n=e._zod.def;if(n.type==="transform")return!0;if(n.type==="array")return kt(n.element,r);if(n.type==="set")return kt(n.valueType,r);if(n.type==="lazy")return kt(n.getter(),r);if(n.type==="promise"||n.type==="optional"||n.type==="nonoptional"||n.type==="nullable"||n.type==="readonly"||n.type==="default"||n.type==="prefault")return kt(n.innerType,r);if(n.type==="intersection")return kt(n.left,r)||kt(n.right,r);if(n.type==="record"||n.type==="map")return kt(n.keyType,r)||kt(n.valueType,r);if(n.type==="pipe"){if(e._zod.traits.has("$ZodCodec"))return!0;return kt(n.in,r)||kt(n.out,r)}if(n.type==="object"){for(let o in n.shape)if(kt(n.shape[o],r))return!0;return!1}if(n.type==="union"){for(let o of n.options)if(kt(o,r))return!0;return!1}if(n.type==="tuple"){for(let o of n.items)if(kt(o,r))return!0;if(n.rest&&kt(n.rest,r))return!0;return!1}return!1}var Hf=(e,t={})=>(r)=>{let n=Zs({...r,processors:t});return _t(e,n),Gs(n,e),Ks(n,e)},Gn=(e,t,r={})=>(n)=>{let{libraryOptions:o,target:s}=n??{},a=Zs({...o??{},target:s,io:t,processors:r});return _t(e,a),Gs(a,e),Ks(a,e)};var ei=De(()=>{Ns()});var nb,Wf=(e,t,r,n)=>{let o=r;o.type="string";let{minimum:s,maximum:a,format:u,patterns:_,contentEncoding:m}=e._zod.bag;if(typeof s==="number")o.minLength=s;if(typeof a==="number")o.maxLength=a;if(u){if(o.format=nb[u]??u,o.format==="")delete o.format;if(u==="time")delete o.format}if(m)o.contentEncoding=m;if(_&&_.size>0){let x=[..._];if(x.length===1)o.pattern=x[0].source;else if(x.length>1)o.allOf=[...x.map((D)=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:D.source}))]}},Zf=(e,t,r,n)=>{let o=r,{minimum:s,maximum:a,format:u,multipleOf:_,exclusiveMaximum:m,exclusiveMinimum:x}=e._zod.bag;if(typeof u==="string"&&u.includes("int"))o.type="integer";else o.type="number";let D=typeof x==="number"&&x>=(s??Number.NEGATIVE_INFINITY),j=typeof m==="number"&&m<=(a??Number.POSITIVE_INFINITY),Y=t.target==="draft-04"||t.target==="openapi-3.0";if(D)if(Y)o.minimum=x,o.exclusiveMinimum=!0;else o.exclusiveMinimum=x;else if(typeof s==="number")o.minimum=s;if(j)if(Y)o.maximum=m,o.exclusiveMaximum=!0;else o.exclusiveMaximum=m;else if(typeof a==="number")o.maximum=a;if(typeof _==="number")o.multipleOf=_},Gf=(e,t,r,n)=>{r.type="boolean"},Kf=(e,t,r,n)=>{r.not={}},Vf=(e,t,r,n)=>{},Jf=(e,t,r,n)=>{let o=e._zod.def,s=Co(o.entries);if(s.every((a)=>typeof a==="number"))r.type="number";if(s.every((a)=>typeof a==="string"))r.type="string";r.enum=s},Xf=(e,t,r,n)=>{let o=e._zod.def,s=[];for(let a of o.values)if(a===void 0){if(t.unrepresentable==="throw")throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof a==="bigint")if(t.unrepresentable==="throw")throw Error("BigInt literals cannot be represented in JSON Schema");else s.push(Number(a));else s.push(a);if(s.length===0);else if(s.length===1){let a=s[0];if(r.type=a===null?"null":typeof a,t.target==="draft-04"||t.target==="openapi-3.0")r.enum=[a];else r.const=a}else{if(s.every((a)=>typeof a==="number"))r.type="number";if(s.every((a)=>typeof a==="string"))r.type="string";if(s.every((a)=>typeof a==="boolean"))r.type="boolean";if(s.every((a)=>a===null))r.type="null";r.enum=s}},Qf=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw Error("Custom types cannot be represented in JSON Schema")},Yf=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw Error("Transforms cannot be represented in JSON Schema")},ep=(e,t,r,n)=>{let o=r,s=e._zod.def,{minimum:a,maximum:u}=e._zod.bag;if(typeof a==="number")o.minItems=a;if(typeof u==="number")o.maxItems=u;o.type="array",o.items=_t(s.element,t,{...n,path:[...n.path,"items"]})},tp=(e,t,r,n)=>{let o=r,s=e._zod.def;o.type="object",o.properties={};let a=s.shape;for(let m in a)o.properties[m]=_t(a[m],t,{...n,path:[...n.path,"properties",m]});let u=new Set(Object.keys(a)),_=new Set([...u].filter((m)=>{let x=s.shape[m]._zod;if(t.io==="input")return x.optin===void 0;else return x.optout===void 0}));if(_.size>0)o.required=Array.from(_);if(s.catchall?._zod.def.type==="never")o.additionalProperties=!1;else if(!s.catchall){if(t.io==="output")o.additionalProperties=!1}else if(s.catchall)o.additionalProperties=_t(s.catchall,t,{...n,path:[...n.path,"additionalProperties"]})},rp=(e,t,r,n)=>{let o=e._zod.def,s=o.inclusive===!1,a=o.options.map((u,_)=>_t(u,t,{...n,path:[...n.path,s?"oneOf":"anyOf",_]}));if(s)r.oneOf=a;else r.anyOf=a},np=(e,t,r,n)=>{let o=e._zod.def,s=_t(o.left,t,{...n,path:[...n.path,"allOf",0]}),a=_t(o.right,t,{...n,path:[...n.path,"allOf",1]}),u=(m)=>("allOf"in m)&&Object.keys(m).length===1,_=[...u(s)?s.allOf:[s],...u(a)?a.allOf:[a]];r.allOf=_},op=(e,t,r,n)=>{let o=e._zod.def,s=_t(o.innerType,t,n),a=t.seen.get(e);if(t.target==="openapi-3.0")a.ref=o.innerType,r.nullable=!0;else r.anyOf=[s,{type:"null"}]},ip=(e,t,r,n)=>{let o=e._zod.def;_t(o.innerType,t,n);let s=t.seen.get(e);s.ref=o.innerType},sp=(e,t,r,n)=>{let o=e._zod.def;_t(o.innerType,t,n);let s=t.seen.get(e);s.ref=o.innerType,r.default=JSON.parse(JSON.stringify(o.defaultValue))},ap=(e,t,r,n)=>{let o=e._zod.def;_t(o.innerType,t,n);let s=t.seen.get(e);if(s.ref=o.innerType,t.io==="input")r._prefault=JSON.parse(JSON.stringify(o.defaultValue))},cp=(e,t,r,n)=>{let o=e._zod.def;_t(o.innerType,t,n);let s=t.seen.get(e);s.ref=o.innerType;let a;try{a=o.catchValue(void 0)}catch{throw Error("Dynamic catch values are not supported in JSON Schema")}r.default=a},lp=(e,t,r,n)=>{let o=e._zod.def,s=o.in._zod.traits.has("$ZodTransform"),a=t.io==="input"?s?o.out:o.in:o.out;_t(a,t,n);let u=t.seen.get(e);u.ref=a},up=(e,t,r,n)=>{let o=e._zod.def;_t(o.innerType,t,n);let s=t.seen.get(e);s.ref=o.innerType,r.readOnly=!0},Vs=(e,t,r,n)=>{let o=e._zod.def;_t(o.innerType,t,n);let s=t.seen.get(e);s.ref=o.innerType};var dp=De(()=>{ei();Jt();nb={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""}});var fp=()=>{};var or=De(()=>{Jt();Ho();Ps();fp();Fr();vs();ws();nf();Wo();Rs();Ns();jf();ei()});var Js=De(()=>{or()});function pp(e){return If(ub,e)}function _p(e){return Pf(db,e)}function gp(e){return Nf(fb,e)}function hp(e){return Cf(pb,e)}var ub,db,fb,pb;var Xs=De(()=>{or();Qs();ub=ce("ZodISODateTime",(e,t)=>{Ed.init(e,t),ot.init(e,t)});db=ce("ZodISODate",(e,t)=>{Sd.init(e,t),ot.init(e,t)});fb=ce("ZodISOTime",(e,t)=>{xd.init(e,t),ot.init(e,t)});pb=ce("ZodISODuration",(e,t)=>{Td.init(e,t),ot.init(e,t)})});var gb=(e,t)=>{Mo.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:(r)=>nu(e,r)},flatten:{value:(r)=>ru(e,r)},addIssue:{value:(r)=>{e.issues.push(r),e.message=JSON.stringify(e.issues,Bn,2)}},addIssues:{value:(r)=>{e.issues.push(...r),e.message=JSON.stringify(e.issues,Bn,2)}},isEmpty:{get(){return e.issues.length===0}}})},qt;var Ys=De(()=>{or();or();Jt();qt=ce("ZodError",gb,{Parent:Error})});var yp,bp,wp,vp,Ep,Sp,xp,Tp,kp,Rp,Ap,Dp;var ea=De(()=>{or();Ys();yp=Bo(qt),bp=Uo(qt),wp=Un(qt),vp=jn(qt),Ep=su(qt),Sp=au(qt),xp=cu(qt),Tp=lu(qt),kp=uu(qt),Rp=du(qt),Ap=fu(qt),Dp=pu(qt)});function Vn(e,t,r){let n=Object.getPrototypeOf(e),o=Op.get(n);if(!o)o=new Set,Op.set(n,o);if(o.has(t))return;o.add(t);for(let s in r){let a=r[s];Object.defineProperty(n,s,{configurable:!0,enumerable:!1,get(){let u=a.bind(this);return Object.defineProperty(this,s,{configurable:!0,writable:!0,enumerable:!0,value:u}),u},set(u){Object.defineProperty(this,s,{configurable:!0,writable:!0,enumerable:!0,value:u})}})}}function at(e){return lf(mb,e)}function ri(e){return qf(Fp,e)}function Pp(e){return Lf(qb,e)}function $b(e){return $f(Lb,e)}function Np(){return Ff(Fb)}function Mb(e){return zf(zb,e)}function Jn(e,t){return Mf(Bb,e,t)}function jr(e,t){let r={type:"object",shape:e??{},...Ne(t)};return new Ub(r)}function Hb(e,t){return new jb({type:"union",options:e,...Ne(t)})}function Zb(e,t){return new Wb({type:"intersection",left:e,right:t})}function ni(e,t){let r=Array.isArray(e)?Object.fromEntries(e.map((n)=>[n,n])):e;return new ta({type:"enum",entries:r,...Ne(t)})}function Kb(e,t){return new Gb({type:"literal",values:Array.isArray(e)?e:[e],...Ne(t)})}function Jb(e){return new Vb({type:"transform",transform:e})}function Cp(e){return new zp({type:"optional",innerType:e})}function Qb(e){return new Xb({type:"optional",innerType:e})}function qp(e){return new Yb({type:"nullable",innerType:e})}function tw(e,t){return new ew({type:"default",innerType:e,get defaultValue(){return typeof t==="function"?t():ms(t)}})}function nw(e,t){return new rw({type:"prefault",innerType:e,get defaultValue(){return typeof t==="function"?t():ms(t)}})}function ow(e,t){return new Mp({type:"nonoptional",innerType:e,...Ne(t)})}function sw(e,t){return new iw({type:"catch",innerType:e,catchValue:typeof t==="function"?t:()=>t})}function Lp(e,t){return new aw({type:"pipe",in:e,out:t})}function lw(e){return new cw({type:"readonly",innerType:e})}function dw(e,t={}){return Bf(uw,e,t)}function fw(e,t){return Uf(e,t)}var Op,st,$p,mb,ot,yb,Ip,ti,bb,wb,vb,Eb,Sb,xb,Tb,kb,Rb,Ab,Db,Ob,Ib,Pb,Nb,Cb,Fp,qb,Lb,Fb,zb,Bb,Ub,jb,Wb,ta,Gb,Vb,zp,Xb,Yb,ew,rw,Mp,iw,aw,cw,uw;var Qs=De(()=>{or();or();dp();ei();Js();Xs();ea();Op=new WeakMap;st=ce("ZodType",(e,t)=>(it.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:Gn(e,"input"),output:Gn(e,"output")}}),e.toJSONSchema=Hf(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(r,n)=>yp(e,r,n,{callee:e.parse}),e.safeParse=(r,n)=>wp(e,r,n),e.parseAsync=async(r,n)=>bp(e,r,n,{callee:e.parseAsync}),e.safeParseAsync=async(r,n)=>vp(e,r,n),e.spa=e.safeParseAsync,e.encode=(r,n)=>Ep(e,r,n),e.decode=(r,n)=>Sp(e,r,n),e.encodeAsync=async(r,n)=>xp(e,r,n),e.decodeAsync=async(r,n)=>Tp(e,r,n),e.safeEncode=(r,n)=>kp(e,r,n),e.safeDecode=(r,n)=>Rp(e,r,n),e.safeEncodeAsync=async(r,n)=>Ap(e,r,n),e.safeDecodeAsync=async(r,n)=>Dp(e,r,n),Vn(e,"ZodType",{check(...r){let n=this.def;return this.clone(Er(n,{checks:[...n.checks??[],...r.map((o)=>typeof o==="function"?{_zod:{check:o,def:{check:"custom"},onattach:[]}}:o)]}),{parent:!0})},with(...r){return this.check(...r)},clone(r,n){return nr(this,r,n)},brand(){return this},register(r,n){return r.add(this,n),this},refine(r,n){return this.check(dw(r,n))},superRefine(r,n){return this.check(fw(r,n))},overwrite(r){return this.check(xr(r))},optional(){return Cp(this)},exactOptional(){return Qb(this)},nullable(){return qp(this)},nullish(){return Cp(qp(this))},nonoptional(r){return ow(this,r)},array(){return Jn(this)},or(r){return Hb([this,r])},and(r){return Zb(this,r)},transform(r){return Lp(this,Jb(r))},default(r){return tw(this,r)},prefault(r){return nw(this,r)},catch(r){return sw(this,r)},pipe(r){return Lp(this,r)},readonly(){return lw(this)},describe(r){let n=this.clone();return Ur.add(n,{description:r}),n},meta(...r){if(r.length===0)return Ur.get(this);let n=this.clone();return Ur.add(n,r[0]),n},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(r){return r(this)}}),Object.defineProperty(e,"description",{get(){return Ur.get(e)?.description},configurable:!0}),e)),$p=ce("_ZodString",(e,t)=>{Ko.init(e,t),st.init(e,t),e._zod.processJSONSchema=(n,o,s)=>Wf(e,n,o,s);let r=e._zod.bag;e.format=r.format??null,e.minLength=r.minimum??null,e.maxLength=r.maximum??null,Vn(e,"_ZodString",{regex(...n){return this.check(qs(...n))},includes(...n){return this.check(Fs(...n))},startsWith(...n){return this.check(zs(...n))},endsWith(...n){return this.check(Ms(...n))},min(...n){return this.check(mn(...n))},max(...n){return this.check(Qo(...n))},length(...n){return this.check(Yo(...n))},nonempty(...n){return this.check(mn(1,...n))},lowercase(n){return this.check(Ls(n))},uppercase(n){return this.check($s(n))},trim(){return this.check(Us())},normalize(...n){return this.check(Bs(...n))},toLowerCase(){return this.check(js())},toUpperCase(){return this.check(Hs())},slugify(){return this.check(Ws())}})}),mb=ce("ZodString",(e,t)=>{Ko.init(e,t),$p.init(e,t),e.email=(r)=>e.check(uf(yb,r)),e.url=(r)=>e.check(gf(bb,r)),e.jwt=(r)=>e.check(Of(Cb,r)),e.emoji=(r)=>e.check(hf(wb,r)),e.guid=(r)=>e.check(Cs(Ip,r)),e.uuid=(r)=>e.check(df(ti,r)),e.uuidv4=(r)=>e.check(ff(ti,r)),e.uuidv6=(r)=>e.check(pf(ti,r)),e.uuidv7=(r)=>e.check(_f(ti,r)),e.nanoid=(r)=>e.check(mf(vb,r)),e.guid=(r)=>e.check(Cs(Ip,r)),e.cuid=(r)=>e.check(yf(Eb,r)),e.cuid2=(r)=>e.check(bf(Sb,r)),e.ulid=(r)=>e.check(wf(xb,r)),e.base64=(r)=>e.check(Rf(Ib,r)),e.base64url=(r)=>e.check(Af(Pb,r)),e.xid=(r)=>e.check(vf(Tb,r)),e.ksuid=(r)=>e.check(Ef(kb,r)),e.ipv4=(r)=>e.check(Sf(Rb,r)),e.ipv6=(r)=>e.check(xf(Ab,r)),e.cidrv4=(r)=>e.check(Tf(Db,r)),e.cidrv6=(r)=>e.check(kf(Ob,r)),e.e164=(r)=>e.check(Df(Nb,r)),e.datetime=(r)=>e.check(pp(r)),e.date=(r)=>e.check(_p(r)),e.time=(r)=>e.check(gp(r)),e.duration=(r)=>e.check(hp(r))});ot=ce("ZodStringFormat",(e,t)=>{rt.init(e,t),$p.init(e,t)}),yb=ce("ZodEmail",(e,t)=>{pd.init(e,t),ot.init(e,t)}),Ip=ce("ZodGUID",(e,t)=>{dd.init(e,t),ot.init(e,t)}),ti=ce("ZodUUID",(e,t)=>{fd.init(e,t),ot.init(e,t)}),bb=ce("ZodURL",(e,t)=>{_d.init(e,t),ot.init(e,t)}),wb=ce("ZodEmoji",(e,t)=>{gd.init(e,t),ot.init(e,t)}),vb=ce("ZodNanoID",(e,t)=>{hd.init(e,t),ot.init(e,t)}),Eb=ce("ZodCUID",(e,t)=>{md.init(e,t),ot.init(e,t)}),Sb=ce("ZodCUID2",(e,t)=>{yd.init(e,t),ot.init(e,t)}),xb=ce("ZodULID",(e,t)=>{bd.init(e,t),ot.init(e,t)}),Tb=ce("ZodXID",(e,t)=>{wd.init(e,t),ot.init(e,t)}),kb=ce("ZodKSUID",(e,t)=>{vd.init(e,t),ot.init(e,t)}),Rb=ce("ZodIPv4",(e,t)=>{kd.init(e,t),ot.init(e,t)}),Ab=ce("ZodIPv6",(e,t)=>{Rd.init(e,t),ot.init(e,t)}),Db=ce("ZodCIDRv4",(e,t)=>{Ad.init(e,t),ot.init(e,t)}),Ob=ce("ZodCIDRv6",(e,t)=>{Dd.init(e,t),ot.init(e,t)}),Ib=ce("ZodBase64",(e,t)=>{Id.init(e,t),ot.init(e,t)}),Pb=ce("ZodBase64URL",(e,t)=>{Pd.init(e,t),ot.init(e,t)}),Nb=ce("ZodE164",(e,t)=>{Nd.init(e,t),ot.init(e,t)}),Cb=ce("ZodJWT",(e,t)=>{Cd.init(e,t),ot.init(e,t)}),Fp=ce("ZodNumber",(e,t)=>{Ds.init(e,t),st.init(e,t),e._zod.processJSONSchema=(n,o,s)=>Zf(e,n,o,s),Vn(e,"ZodNumber",{gt(n,o){return this.check(Jo(n,o))},gte(n,o){return this.check(Zn(n,o))},min(n,o){return this.check(Zn(n,o))},lt(n,o){return this.check(Vo(n,o))},lte(n,o){return this.check(Wn(n,o))},max(n,o){return this.check(Wn(n,o))},int(n){return this.check(Pp(n))},safe(n){return this.check(Pp(n))},positive(n){return this.check(Jo(0,n))},nonnegative(n){return this.check(Zn(0,n))},negative(n){return this.check(Vo(0,n))},nonpositive(n){return this.check(Wn(0,n))},multipleOf(n,o){return this.check(Xo(n,o))},step(n,o){return this.check(Xo(n,o))},finite(){return this}});let r=e._zod.bag;e.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??0.5),e.isFinite=!0,e.format=r.format??null});qb=ce("ZodNumberFormat",(e,t)=>{qd.init(e,t),Fp.init(e,t)});Lb=ce("ZodBoolean",(e,t)=>{Ld.init(e,t),st.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Gf(e,r,n,o)});Fb=ce("ZodUnknown",(e,t)=>{$d.init(e,t),st.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Vf(e,r,n,o)});zb=ce("ZodNever",(e,t)=>{Fd.init(e,t),st.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Kf(e,r,n,o)});Bb=ce("ZodArray",(e,t)=>{zd.init(e,t),st.init(e,t),e._zod.processJSONSchema=(r,n,o)=>ep(e,r,n,o),e.element=t.element,Vn(e,"ZodArray",{min(r,n){return this.check(mn(r,n))},nonempty(r){return this.check(mn(1,r))},max(r,n){return this.check(Qo(r,n))},length(r,n){return this.check(Yo(r,n))},unwrap(){return this.element}})});Ub=ce("ZodObject",(e,t)=>{Ud.init(e,t),st.init(e,t),e._zod.processJSONSchema=(r,n,o)=>tp(e,r,n,o),Ve(e,"shape",()=>t.shape),Vn(e,"ZodObject",{keyof(){return ni(Object.keys(this._zod.def.shape))},catchall(r){return this.clone({...this._zod.def,catchall:r})},passthrough(){return this.clone({...this._zod.def,catchall:Np()})},loose(){return this.clone({...this._zod.def,catchall:Np()})},strict(){return this.clone({...this._zod.def,catchall:Mb()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(r){return Hy(this,r)},safeExtend(r){return Wy(this,r)},merge(r){return Zy(this,r)},pick(r){return Uy(this,r)},omit(r){return jy(this,r)},partial(...r){return Gy(zp,this,r[0])},required(...r){return Ky(Mp,this,r[0])}})});jb=ce("ZodUnion",(e,t)=>{jd.init(e,t),st.init(e,t),e._zod.processJSONSchema=(r,n,o)=>rp(e,r,n,o),e.options=t.options});Wb=ce("ZodIntersection",(e,t)=>{Hd.init(e,t),st.init(e,t),e._zod.processJSONSchema=(r,n,o)=>np(e,r,n,o)});ta=ce("ZodEnum",(e,t)=>{Wd.init(e,t),st.init(e,t),e._zod.processJSONSchema=(n,o,s)=>Jf(e,n,o,s),e.enum=t.entries,e.options=Object.values(t.entries);let r=new Set(Object.keys(t.entries));e.extract=(n,o)=>{let s={};for(let a of n)if(r.has(a))s[a]=t.entries[a];else throw Error(`Key ${a} not found in enum`);return new ta({...t,checks:[],...Ne(o),entries:s})},e.exclude=(n,o)=>{let s={...t.entries};for(let a of n)if(r.has(a))delete s[a];else throw Error(`Key ${a} not found in enum`);return new ta({...t,checks:[],...Ne(o),entries:s})}});Gb=ce("ZodLiteral",(e,t)=>{Zd.init(e,t),st.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Xf(e,r,n,o),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});Vb=ce("ZodTransform",(e,t)=>{Gd.init(e,t),st.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Yf(e,r,n,o),e._zod.parse=(r,n)=>{if(n.direction==="backward")throw new zn(e.constructor.name);r.addIssue=(s)=>{if(typeof s==="string")r.issues.push(Br(s,r.value,t));else{let a=s;if(a.fatal)a.continue=!1;a.code??(a.code="custom"),a.input??(a.input=r.value),a.inst??(a.inst=e),r.issues.push(Br(a))}};let o=t.transform(r.value,r);if(o instanceof Promise)return o.then((s)=>(r.value=s,r.fallback=!0,r));return r.value=o,r.fallback=!0,r}});zp=ce("ZodOptional",(e,t)=>{Os.init(e,t),st.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Vs(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});Xb=ce("ZodExactOptional",(e,t)=>{Kd.init(e,t),st.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Vs(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});Yb=ce("ZodNullable",(e,t)=>{Vd.init(e,t),st.init(e,t),e._zod.processJSONSchema=(r,n,o)=>op(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});ew=ce("ZodDefault",(e,t)=>{Jd.init(e,t),st.init(e,t),e._zod.processJSONSchema=(r,n,o)=>sp(e,r,n,o),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});rw=ce("ZodPrefault",(e,t)=>{Xd.init(e,t),st.init(e,t),e._zod.processJSONSchema=(r,n,o)=>ap(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});Mp=ce("ZodNonOptional",(e,t)=>{Qd.init(e,t),st.init(e,t),e._zod.processJSONSchema=(r,n,o)=>ip(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});iw=ce("ZodCatch",(e,t)=>{Yd.init(e,t),st.init(e,t),e._zod.processJSONSchema=(r,n,o)=>cp(e,r,n,o),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});aw=ce("ZodPipe",(e,t)=>{ef.init(e,t),st.init(e,t),e._zod.processJSONSchema=(r,n,o)=>lp(e,r,n,o),e.in=t.in,e.out=t.out});cw=ce("ZodReadonly",(e,t)=>{tf.init(e,t),st.init(e,t),e._zod.processJSONSchema=(r,n,o)=>up(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});uw=ce("ZodCustom",(e,t)=>{rf.init(e,t),st.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Qf(e,r,n,o)})});var Bp;var Up=De(()=>{(function(e){})(Bp||(Bp={}))});var jp=()=>{};var na=De(()=>{or();or();of();Ps();Xs();jp();Qs();Js();Ys();ea();Up();Vt(Is())});var oa=De(()=>{na();na()});var Hp,fk,pk,Wp,_k,gk,Zp="/sync",Gp="/health",Kp="/api/pair";var oi=De(()=>{oa();Hp=jr({hlc:at().describe("Hybrid Logical Clock timestamp"),node_id:at().describe("Origin node that produced the change"),dataset:at().describe("CRDT dataset, e.g. databases / records / documents"),row_id:at().describe("Row identifier within the dataset"),col:at().describe("Column / property identifier"),value:at().nullable().describe("JSON-encoded field value, or null"),txn:at().nullable().optional().describe("Change-group id (one logical mutation)")}),fk=jr({node_id:at().describe("Calling client's node id"),since:ri().describe("Server cursor the client last pulled"),changes:Jn(Hp).describe("Client's changes to push"),limit:ri().optional().describe("Max changes to return (pagination for hydration)"),exclude_datasets:Jn(at()).optional().describe("Datasets to omit from the pull (partial replica)")}),pk=jr({node_id:at().describe("Server's node id"),changes:Jn(Hp).describe("Server changes after `since`"),cursor:ri().describe("New server cursor for the client to store")}),Wp=jr({ok:$b(),node:at().describe("Server's node id"),capabilities:Jn(at()).optional().describe("Optional protocol features supported by this server"),version:at().optional().describe("Core version, for mixed-version workspace warnings")}),_k=jr({code:at().describe("One-time pairing code minted by this server"),node_id:at().describe("Calling device's node id"),grant:at().describe("Durable credential the caller issues to us"),self_url:at().optional().describe("Caller's reachable server URL (for mutual sync)")}),gk=jr({node_id:at().describe("This server's node id"),grant:at().describe("Durable credential we issue to the caller")})});function _w(e,t){return e.query("SELECT pull_cursor, push_cursor, token FROM peers WHERE url = ?").get(t)??{pull_cursor:0,push_cursor:0,token:null}}function gw(e,t,r){e.query("INSERT INTO peers (url, pull_cursor, push_cursor) VALUES (?, ?, ?) ON CONFLICT(url) DO UPDATE SET pull_cursor = excluded.pull_cursor, push_cursor = excluded.push_cursor").run(t,r.pull_cursor,r.push_cursor)}function hw(e,t,r){if(r.length===0)return t;let n=new Set(r.map(Vp)),o=e.query("SELECT rowid AS seq, hlc, node_id, dataset, row_id, col FROM crdt_changes WHERE rowid > ? ORDER BY rowid").all(t),s=t;for(let a of o){if(!n.has(Vp(a)))break;s=a.seq}return s}async function ii(e,t,r={}){let n=typeof r==="string"?{token:r}:r,o=je(e),s=_w(e,t),a=n.token??s.token??void 0,u=br(e,s.push_cursor),_={"content-type":"application/json"};if(a)_.authorization=`Bearer ${a}`;let m=await fetch(new URL(Zp,t),{method:"POST",headers:_,body:JSON.stringify({node_id:o,since:s.pull_cursor,changes:u.changes,...n.pullLimit!=null?{limit:n.pullLimit}:{},...n.excludeDatasets?.length?{exclude_datasets:n.excludeDatasets}:{}}),signal:AbortSignal.timeout(n.timeoutMs??30000)});if(!m.ok)throw new Z(m.status===401||m.status===403?"auth":"network",`sync failed: ${m.status} ${await m.text()}`);let x=await m.json(),D=x.changes??[],j=rr(e,D);return gw(e,t,{pull_cursor:x.cursor,push_cursor:hw(e,u.cursor,D)}),{pushed:u.changes.length,pulled:j,received:D.length}}var Vp=(e)=>`${e.hlc}\x00${e.node_id}\x00${e.dataset}\x00${e.row_id}\x00${e.col}`;var ia=De(()=>{Gt();dt();oi();Ye()});async function Xp(e,t,r,n,o=Date.now()){let s=`${t}\x00${r}`;if(o-(Jp.get(s)??0)>=1e5){let m={node:r,priority:n,expiresAt:o+300000};await e.put(yw(t,r),new TextEncoder().encode(JSON.stringify(m)),{contentType:"application/json"}),Jp.set(s,o)}let a=null,u=[];for(let m of await e.list(mw(t))){if(!m.key.endsWith(".lease"))continue;let x=await e.get(m.key);if(!x)continue;let D;try{D=JSON.parse(new TextDecoder().decode(x))}catch{continue}if(!D.node||D.expiresAt<=o){if(D.expiresAt<=o-300000)u.push(m.key);continue}if(!a||D.priority>a.priority||D.priority===a.priority&&D.node<a.node)a=D}let _=a?a.node===r:!0;if(_)for(let m of u)await e.del(m);return _}var mw=(e)=>`${e}/publisher/`,yw=(e,t)=>`${e}/publisher/${t}.lease`,Jp;var Qp=De(()=>{Jp=new Map});function Xt(e){let t=new Uint8Array(e.byteLength);return t.set(e),t.buffer}function ir(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return btoa(t)}function Qt(e){let t=atob(e),r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t.charCodeAt(n);return r}function sa(){return crypto.getRandomValues(new Uint8Array(ww))}async function e_(e,t){let r=await crypto.subtle.importKey("raw",Xt(new TextEncoder().encode(e)),"PBKDF2",!1,["deriveKey"]);return crypto.subtle.deriveKey({name:"PBKDF2",salt:Xt(t),iterations:Yp,hash:"SHA-256"},r,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async function t_(e,t){let r=crypto.getRandomValues(new Uint8Array(bw)),n=await e_(t,r),o=crypto.getRandomValues(new Uint8Array(yn)),s=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:Xt(o)},n,Xt(e))),a=new Uint8Array(o.length+s.length);return a.set(o,0),a.set(s,o.length),{v:1,kdf:"PBKDF2-SHA256",iter:Yp,salt:ir(r),wrap:"AES-GCM",wrapped_key:ir(a)}}async function aa(e,t){if(e.v!==1||e.kdf!=="PBKDF2-SHA256"||e.wrap!=="AES-GCM")throw new Z("invalid_input","unsupported key envelope format");let r=Qt(e.salt),n=await e_(t,r),o=Qt(e.wrapped_key),s=o.subarray(0,yn),a=o.subarray(yn);try{let u=await crypto.subtle.decrypt({name:"AES-GCM",iv:Xt(s)},n,Xt(a));return new Uint8Array(u)}catch{throw new Z("auth","wrong passphrase — could not unwrap the master key")}}async function r_(e){return crypto.subtle.importKey("raw",Xt(e),{name:"AES-GCM"},!1,["encrypt","decrypt"])}async function gr(e,t){let r=await r_(e),n=crypto.getRandomValues(new Uint8Array(yn)),o=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:Xt(n)},r,Xt(t))),s=new Uint8Array(n.length+o.length);return s.set(n,0),s.set(o,n.length),s}async function Hr(e,t){let r=await r_(e),n=t.subarray(0,yn),o=t.subarray(yn);try{let s=await crypto.subtle.decrypt({name:"AES-GCM",iv:Xt(n)},r,Xt(o));return new Uint8Array(s)}catch{throw new Z("auth","could not decrypt — wrong master key or corrupt data")}}var Yp=600000,bw=16,yn=12,ww=32;var Xn=De(()=>{Ye()});function s_(e){if(e.virtualHostedStyle!=null)return e.virtualHostedStyle;try{return new URL(e.endpoint).hostname.startsWith(`${e.bucket}.`)}catch{return!1}}function a_(e){ca=e}function Ut(e){if(!ca)throw new Z("network","no S3 storage client is registered for this runtime");return ca(e)}function Yn(e){let t=(e||"").replace(/^\/+|\/+$/g,"");return t?`${t}/spaces/default`:"spaces/default"}function fa(e){let t=new Uint8Array(e.byteLength);return t.set(e),t.buffer}async function l_(e){let t=new Response(fa(e)).body.pipeThrough(new CompressionStream("gzip"));return new Uint8Array(await new Response(t).arrayBuffer())}async function u_(e){let t=new Response(fa(e)).body.pipeThrough(new DecompressionStream("gzip"));return new Uint8Array(await new Response(t).arrayBuffer())}function Dw(e){return e.map((t)=>JSON.stringify(t)).join(`
471
+ `)}async function d_(e,t){let r=await l_(new TextEncoder().encode(Dw(e)));return t?gr(t,r):r}async function f_(e,t){let r=t?await Hr(t,e):e,n=new TextDecoder().decode(await u_(r));if(!n)return[];return n.split(`
472
+ `).filter((o)=>o.length>0).map((o)=>JSON.parse(o))}function si(e){if(!e.encrypt)return null;if(!e.masterKey)throw new Z("invalid_input","encrypted bucket but master key missing — refusing to read/write plaintext");return Qt(e.masterKey)}async function __(e,t,r){let n=Ut(e),o=p_(Yn(e.prefix),t),s=si(e),a=s?await gr(s,r):r;try{return await n.put(o,a,{ifNoneMatch:!0,contentType:"application/octet-stream"}),!0}catch(u){if(cn(u)==="conflict")return!1;throw u}}async function pa(e,t){let n=await Ut(e).get(p_(Yn(e.prefix),t));if(!n)return null;let o=si(e);return o?Hr(o,n):n}async function Ow(e){let t=await crypto.subtle.digest("SHA-256",fa(new TextEncoder().encode(e)));return[...new Uint8Array(t)].map((r)=>r.toString(16).padStart(2,"0")).join("").slice(0,16)}function Iw(e,t){return e.query("SELECT push_cursor FROM peers WHERE url = ?").get(t)?.push_cursor??0}function o_(e,t,r){e.query("UPDATE peers SET push_cursor = ? WHERE url = ?").run(r,t)}function _a(e,t,r){return e.query("SELECT last_key FROM storage_cursors WHERE peer_url = ? AND node_id = ?").get(t,r)?.last_key??null}function ga(e,t,r,n){e.query("INSERT INTO storage_cursors (peer_url, node_id, last_key) VALUES (?, ?, ?) ON CONFLICT(peer_url, node_id) DO UPDATE SET last_key = excluded.last_key").run(t,r,n)}function Pw(e,t){let r=_a(e,t,c_);return new Set(r?r.split(`
473
+ `).filter(Boolean):[])}function Nw(e,t,r){ga(e,t,c_,[...r].join(`
474
+ `))}function Cw(e,t=Date.now()){let r=e.query(`SELECT ${It} FROM crdt_changes c
459
475
  WHERE NOT EXISTS (
460
476
  SELECT 1 FROM crdt_changes k
461
477
  WHERE k.dataset = c.dataset AND k.row_id = c.row_id AND k.col = c.col AND k.hlc > c.hlc
462
- )`).all();return ji(r,t)}function xw(e){let t={};for(let r of e)if(!t[r.node_id]||r.hlc>t[r.node_id])t[r.node_id]=r.hlc;return t}function Tw(e){let t=e.query("SELECT node_id, MAX(hlc) AS h FROM crdt_changes GROUP BY node_id").all(),r={};for(let n of t)r[n.node_id]=n.h;return r}function kw(e,t){for(let r in t)if(!e[r]||e[r]<t[r])return!1;return!0}async function Rw(e,t){let r=await r_(new TextEncoder().encode(JSON.stringify(e)));return t?pr(t,r):r}async function Aw(e,t){try{let r=t?await Hr(t,e):e;return JSON.parse(new TextDecoder().decode(await n_(r)))}catch{return null}}function Dw(e,t){let r=new Set;for(let n of e){let o=n.key.slice(t.length),s=o.indexOf("/");if(s>0)r.add(o.slice(0,s))}return[...r]}async function Ow(e,t){let r=gw(t);return Dw(await e.list(r,void 0,"/"),r)}async function pa(e,t,r){if(!t.encrypt)return null;let n=eo(t.prefix),o=mw(n),s=async(m)=>nr(await oa(JSON.parse(new TextDecoder().decode(m)),r)),a=await e.get(o);if(a)return s(a);let u=na(),_=await Kp(u,r);try{return await e.put(o,new TextEncoder().encode(JSON.stringify(_)),{contentType:"application/json",ifNoneMatch:!0}),nr(u)}catch(m){if(ln(m)==="conflict"){let x=await e.get(o);if(x)return s(x)}throw m}}async function Qp(e,t,r,n=dw){let o=Date.now();cn(e,o);let s=si(r),a=eo(r.prefix),u=We(e),_=(await t.list(aa(a,u))).map((de)=>de.key).filter((de)=>de.endsWith(".seg")).sort(),m=_.length?_[_.length-1]:null,x=Sw(e,o);if(x.length===0)return null;let D=x.reduce((de,ge)=>ge.hlc>de?ge.hlc:de,""),j=await bw(x.map((de)=>JSON.stringify(de)).sort().join(`
463
- `)),Y=`${Yn(a)}${D}${sa}${j}.snap`;await t.put(Y,await o_(x,s),{contentType:"application/octet-stream"}),await t.put(ca(Y),await Rw({frontier:xw(x),ownNode:u,ownSegHigh:m},s),{contentType:"application/octet-stream"});for(let de of await t.list(Yn(a))){if(!de.key.endsWith(".snap"))continue;if(de.key.slice(Yn(a).length).split(sa)[0]<D)await t.del(de.key),await t.del(ca(de.key))}let _e=_.slice(0,Math.max(0,_.length-n));for(let de of _e)await t.del(de);return{key:Y,changes:x.length}}function c_(e){return parseInt(e.slice(0,15),10)}function Iw(e){return Date.now()-c_(e.hlc)}function Pw(e,t){let r=Yn(t),n=null;for(let o of e){let s=o.slice(r.length).split(sa)[0];if(n===null||s>n)n=s}return n}async function l_(e,t,r,n,o={}){cn(e);let s=We(e),a=si(n),u=eo(n.prefix),_=ww(e,t),m=br(e,_,{onlyNode:s}),x=0,D=!1;if(m.changes.length===0)Xp(e,t,m.cursor);else{let de=o.minPushChanges??1,ge=o.maxPushAgeMs??0;if(o.forcePush||m.changes.length>=de||Iw(m.changes[0])>=ge){let Ze=hw(u,s,m.cursor);await r.put(Jp(u,s),new TextEncoder().encode(Ze),{contentType:"text/plain"}),await r.put(Ze,await o_(m.changes,a),{contentType:"application/octet-stream"}),Xp(e,t,m.cursor),x=m.changes.length}else D=!0}let j=[],Y=0;if(o.pull??!0){j=(await r.list(Yn(u))).map((de)=>de.key).filter((de)=>de.endsWith(".snap")),Y+=await Cw(e,t,j,r,a);for(let de of await Ow(r,u)){if(de===s)continue;let ge=da(e,t,de),Le=await r.get(Jp(u,de));if(Le){let $e=new TextDecoder().decode(Le);if(ge&&$e<=ge)continue}let Ze=(await r.list(aa(u,de),ge??void 0)).filter(($e)=>$e.key.endsWith(".seg"));for(let $e of Ze){let Ue=await r.get($e.key);if(!Ue)continue;let tt=await i_(Ue,a);Y+=er(e,tt),fa(e,t,de,$e.key)}}}let _e=!1;if(o.publish){let de=e.query("SELECT COUNT(*) AS n FROM crdt_changes").get().n;if(de>0){let ge=Pw(j,u),Le=o.snapshotMinDelta??fw,Ze=o.snapshotDeltaRatio??pw,$e=o.snapshotMaxIntervalMs??_w,Ue=ge===null?de:e.query("SELECT COUNT(*) AS n FROM crdt_changes WHERE hlc > ?").get(ge).n;if((ge===null||Ue>=Math.max(Le,de*Ze)||Ue>0&&Date.now()-c_(ge)>=$e)&&await Hp(r,u,s,o.priority??0))await Qp(e,r,n,o.snapshotRetainSegments),_e=!0}}if(o.publish&&!_e&&x>0){let de=o.snapshotEverySegments??200;if((await r.list(aa(u,s))).filter((Le)=>Le.key.endsWith(".seg")).length>=de)await Qp(e,r,n,o.snapshotRetainSegments)}return{pushed:x,pulled:Y,pendingPush:D}}async function Cw(e,t,r,n,o){if(r.length===0)return 0;let s=vw(e,t),a=Tw(e),u=0;for(let m of[...r].sort().reverse()){if(s.has(m))continue;let x=await n.get(ca(m)),D=x?await Aw(x,o):null;if(D&&kw(a,D.frontier)){s.add(m);continue}let j=await n.get(m);if(!j)continue;let Y=await i_(j,o);u+=er(e,Y),s.add(m);for(let _e of Y)if(!a[_e.node_id]||_e.hlc>a[_e.node_id])a[_e.node_id]=_e.hlc;if(D?.ownSegHigh){let _e=da(e,t,D.ownNode);if(!_e||_e<D.ownSegHigh)fa(e,t,D.ownNode,D.ownSegHigh)}}let _=new Set(r);return Ew(e,t,[...s].filter((m)=>_.has(m))),u}var ia=null,t_="__snapshot__",uw=16,sa="~",dw=40,fw=200,pw=0.5,_w=1800000,gw=(e)=>`${e}/oplog/`,aa=(e,t)=>`${e}/oplog/${t}/`,Jp=(e,t)=>`${e}/oplog/${t}/HEAD`,hw=(e,t,r)=>`${e}/oplog/${t}/${String(r).padStart(uw,"0")}.seg`,Yn=(e)=>`${e}/snapshot/`,mw=(e)=>`${e}/keys/main.json`,s_=(e,t)=>`${e}/blobs/${t}`,ca=(e)=>`${e}.vc`;var wn=De(()=>{Gt();dt();Wp();Ye();Qn()});var Nw=32,qw=3,yk;var u_=De(()=>{Ye();yk=(Nw+qw)*8/5});var d_=De(()=>{Ye()});function Lw(e){let t=e.query("SELECT value FROM meta WHERE key = ?").get("site_publish_rollbacks");if(!t?.value)return[];try{let r=JSON.parse(t.value);if(!Array.isArray(r))return[];return r.filter((n)=>!!n&&typeof n.siteId==="string"&&typeof n.peerUrl==="string"&&typeof n.targetUrl==="string"&&Number.isFinite(n.requiredSeq)&&Number.isFinite(n.createdAt)&&typeof n.lastError==="string")}catch{return[]}}function $w(e,t){if(t.length===0){e.query("DELETE FROM meta WHERE key = ?").run("site_publish_rollbacks");return}e.query("INSERT INTO meta (key,value) VALUES (?,?) ON CONFLICT(key) DO UPDATE SET value=excluded.value").run("site_publish_rollbacks",JSON.stringify(t))}function f_(e,t){let r=e.query("SELECT push_cursor,last_status FROM peers WHERE url = ?").get(t);if(!r||r.last_status!=="ok")return 0;let n=Lw(e),o=n.filter((s)=>s.peerUrl!==t||s.requiredSeq>r.push_cursor);return $w(e,o),n.length-o.length}var __;var p_=De(()=>{__={name:"@tensorix/metahub",version:"0.5.1",description:"Metahub core library and CLI",license:"AGPL-3.0-only",type:"module",main:"./dist/index.js",module:"./dist/index.js",types:"./dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./package.json":"./package.json"},bin:{metahub:"./dist/cli.js",mh:"./dist/cli.js"},files:["dist","README.md","README.zh-CN.md","LICENSE"],scripts:{dev:"bun --hot src/cli/index.ts",build:"bun run scripts/build.ts","build:shell":"bun run scripts/build-shell.ts","build:share-viewer":"bun run scripts/build-share-viewer.ts","build:binaries":"bun run scripts/compile-binaries.ts","build:binaries:host":"HOST_ONLY=1 bun run scripts/compile-binaries.ts",prepublishOnly:"bun run build",test:"bun test",release:"bun run scripts/tag-release.ts"},dependencies:{"@clack/prompts":"^1.5.0","@codemirror/commands":"6.10.4","@codemirror/state":"6.7.0","@codemirror/view":"6.43.4","@joplin/turndown-plugin-gfm":"^1.0.67","@sqlite.org/sqlite-wasm":"^3.53.0-build1",aws4fetch:"^1.0.20",citty:"^0.1.6","highlight.js":"^11.11.1",jsqr:"^1.4.0",preact:"^10.29.2","qrcode-generator":"^2.0.4",turndown:"^7.2.4",zod:"^4.4.3"},devDependencies:{"@happy-dom/global-registrator":"^20.10.2","@prettier/plugin-php":"^0.25.0","@types/bun":"latest","@types/turndown":"^5.0.6","@wasm-fmt/clang-format":"^22.1.8","@wasm-fmt/gofmt":"^0.7.3","@wasm-fmt/lua_fmt":"^0.3.3","@wasm-fmt/ruff_fmt":"^0.15.20","@wasm-fmt/taplo_fmt":"^0.2.5","mvdan-sh":"^0.10.1",prettier:"^3.6","sql-formatter":"^15",typescript:"^5"}}});function _a(){return{v:1,tables:[]}}function Mw(e){return typeof e==="string"&&ga.includes(e)}function g_(e){let t=new Map;for(let n of e){let o=t.get(n.db)??new Set;for(let s of n.ops)o.add(s);t.set(n.db,o)}let r=[];for(let[n,o]of t){let s=ga.filter((a)=>o.has(a));if(s.length)r.push({db:n,ops:s})}return r.sort((n,o)=>n.db<o.db?-1:n.db>o.db?1:0),{v:1,tables:r}}function _r(e){if(!e)return _a();let t;try{t=JSON.parse(e)}catch{return _a()}try{return to(t)}catch{return _a()}}function to(e){if(typeof e!=="object"||e===null||Array.isArray(e))throw new Z("invalid_input","grants must be an object {v:1, tables:[...]}");let t=e;if(t.v!==1)throw new Z("invalid_input","grants version must be 1");if(!Array.isArray(t.tables))throw new Z("invalid_input","grants.tables must be an array");let r=[];for(let n of t.tables){if(typeof n!=="object"||n===null)throw new Z("invalid_input","each grant table must be an object {db, ops}");let{db:o,ops:s}=n;if(typeof o!=="string"||!o)throw new Z("invalid_input","grant table `db` must be a database id");if(!Array.isArray(s)||!s.every(Mw))throw new Z("invalid_input",`grant ops must be a subset of ${ga.join("|")} (delete is never grantable)`);r.push({db:o,ops:s})}return g_(r)}function ai(e){return JSON.stringify(g_(e.tables))}function h_(e){return e.tables.some((t)=>t.ops.some((r)=>r!=="read"))}var ga;var Wr=De(()=>{Ye();qr();Nr();Lr();dt();ga=["read","create","update"]});function ha(e,t){let r=t.permission??"view";if(!Bw.has(t.kind))throw new Z("invalid_input",`unknown share kind: ${t.kind}`);if(r!=="view"&&r!=="edit")throw new Z("invalid_input",`unknown share permission: ${r}`);let n=t.requestId?.trim()||null;if(n&&!/^[A-Za-z0-9_-]{16,80}$/.test(n))throw new Z("invalid_input","share request id is invalid");if(n){let _=y_(e,n);if(_){if(_.kind!==t.kind||_.target_id!==t.target_id)throw new Z("conflict","share request id was already used for another target");return _}}let o=null;if(t.grants!=null){let _;try{_=JSON.parse(t.grants)}catch{throw new Z("invalid_input","grants must be a JSON GrantSet")}o=ai(to(_))}let s=bt(12);while(or(e,s))s=bt(12);let u=r==="edit"||h_(_r(o))?"g"+bt(8):null;return e.query(`INSERT INTO shares (${ro}) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(s,t.kind,t.target_id,r,"server",t.pwSalt??null,t.pwHash??null,t.expiresAt??null,u,t.servedBase??null,null,null,null,null,Date.now(),n,o),or(e,s)}function y_(e,t){return e.query(`SELECT ${ro} FROM shares WHERE request_id = ?`).get(t)??null}function or(e,t){return e.query(`SELECT ${ro} FROM shares WHERE slug = ?`).get(t)??null}function ma(e){return e.query(`SELECT ${ro} FROM shares ORDER BY created_at DESC`).all()}function ya(e,t){return e.query(`SELECT ${ro} FROM shares WHERE target_id = ? ORDER BY created_at DESC`).all(t)}function Qt(e,t){return e.query("DELETE FROM shares WHERE slug = ?").run(t).changes>0}function m_(e){let t=new Uint8Array(e.byteLength);return t.set(e),t.buffer}async function Ww(e,t){let r=await crypto.subtle.importKey("raw",m_(new TextEncoder().encode(e)),"PBKDF2",!1,["deriveBits"]),n=await crypto.subtle.deriveBits({name:"PBKDF2",salt:m_(t),iterations:Uw,hash:"SHA-256"},r,Hw);return new Uint8Array(n)}async function ba(e){let t=crypto.getRandomValues(new Uint8Array(jw)),r=await Ww(e,t);return{salt:nr(t),hash:nr(r)}}var Bw,ro="slug, kind, target_id, permission, transport, pw_salt, pw_hash, expires_at, guest_node_id, served_base, s3_peer_url, s3_object_prefix, s3_presign_exp, s3_key_b64, created_at, request_id, grants",Uw=600000,jw=16,Hw=256;var vn=De(()=>{Ye();wt();Qn();Wr();Bw=new Set(["doc","database","site"])});function wa(e){let t=Zw;for(let r=0;r<e.length;r++)t^=BigInt(e.charCodeAt(r)),t=t*Gw&Kw;return t.toString(16).padStart(16,"0")}var Zw=0xcbf29ce484222325n,Gw=0x100000001b3n,Kw=0xffffffffffffffffn;function va(e){let t=[],r=[];if(e.grantedDbIds.length>0){let n=e.grantedDbIds.map(()=>"?").join(", ");t.push(`SELECT 'databases' AS dataset, id AS row_id FROM databases WHERE id IN (${n})`),r.push(...e.grantedDbIds),t.push(`SELECT 'properties', id FROM properties WHERE database_id IN (${n})`),r.push(...e.grantedDbIds),t.push(`SELECT 'records', id FROM records WHERE database_id IN (${n})`),r.push(...e.grantedDbIds)}if(e.siteId)t.push("SELECT 'sites', id FROM sites WHERE id = ?"),r.push(e.siteId),t.push("SELECT 'site_files', id FROM site_files WHERE site_id = ?"),r.push(e.siteId);if(t.length===0)t.push("SELECT '' AS dataset, '' AS row_id WHERE 0");return{sql:t.join(" UNION ALL "),params:r}}function v_(e,t){let r=va(t);return e.query(`SELECT dataset, row_id FROM (${r.sql}) ORDER BY dataset, row_id`).all(...r.params)}function Ea(e,t,r){switch(r.dataset){case"databases":return t.grantedDbIds.includes(r.row_id)&&e.query("SELECT 1 FROM databases WHERE id = ?").get(r.row_id)!=null;case"properties":case"records":{let n=e.query(`SELECT database_id FROM ${r.dataset} WHERE id = ?`).get(r.row_id);return n?.database_id!=null&&t.grantedDbIds.includes(n.database_id)}case"sites":return t.siteId===r.row_id&&e.query("SELECT 1 FROM sites WHERE id = ?").get(r.row_id)!=null;case"site_files":{if(!t.siteId)return!1;return e.query("SELECT site_id FROM site_files WHERE id = ?").get(r.row_id)?.site_id===t.siteId}default:return!1}}function E_(e,t,r){let n=va(r),o=e.query(`WITH m(dataset, row_id) AS (${n.sql})
478
+ )`).all();return Zi(r,t)}function qw(e){let t={};for(let r of e)if(!t[r.node_id]||r.hlc>t[r.node_id])t[r.node_id]=r.hlc;return t}function Lw(e){let t=e.query("SELECT node_id, MAX(hlc) AS h FROM crdt_changes GROUP BY node_id").all(),r={};for(let n of t)r[n.node_id]=n.h;return r}function $w(e,t){for(let r in t)if(!e[r]||e[r]<t[r])return!1;return!0}async function Fw(e,t){let r=await l_(new TextEncoder().encode(JSON.stringify(e)));return t?gr(t,r):r}async function zw(e,t){try{let r=t?await Hr(t,e):e;return JSON.parse(new TextDecoder().decode(await u_(r)))}catch{return null}}function Mw(e,t){let r=new Set;for(let n of e){let o=n.key.slice(t.length),s=o.indexOf("/");if(s>0)r.add(o.slice(0,s))}return[...r]}async function Bw(e,t){let r=kw(t);return Mw(await e.list(r,void 0,"/"),r)}async function ha(e,t,r){if(!t.encrypt)return null;let n=Yn(t.prefix),o=Aw(n),s=async(m)=>ir(await aa(JSON.parse(new TextDecoder().decode(m)),r)),a=await e.get(o);if(a)return s(a);let u=sa(),_=await t_(u,r);try{return await e.put(o,new TextEncoder().encode(JSON.stringify(_)),{contentType:"application/json",ifNoneMatch:!0}),ir(u)}catch(m){if(cn(m)==="conflict"){let x=await e.get(o);if(x)return s(x)}throw m}}async function i_(e,t,r,n=Ew){let o=Date.now();an(e,o);let s=si(r),a=Yn(r.prefix),u=je(e),_=(await t.list(ua(a,u))).map((de)=>de.key).filter((de)=>de.endsWith(".seg")).sort(),m=_.length?_[_.length-1]:null,x=Cw(e,o);if(x.length===0)return null;let D=x.reduce((de,ge)=>ge.hlc>de?ge.hlc:de,""),j=await Ow(x.map((de)=>JSON.stringify(de)).sort().join(`
479
+ `)),Y=`${Qn(a)}${D}${la}${j}.snap`;await t.put(Y,await d_(x,s),{contentType:"application/octet-stream"}),await t.put(da(Y),await Fw({frontier:qw(x),ownNode:u,ownSegHigh:m},s),{contentType:"application/octet-stream"});for(let de of await t.list(Qn(a))){if(!de.key.endsWith(".snap"))continue;if(de.key.slice(Qn(a).length).split(la)[0]<D)await t.del(de.key),await t.del(da(de.key))}let _e=_.slice(0,Math.max(0,_.length-n));for(let de of _e)await t.del(de);return{key:Y,changes:x.length}}function g_(e){return parseInt(e.slice(0,15),10)}function Uw(e){return Date.now()-g_(e.hlc)}function jw(e,t){let r=Qn(t),n=null;for(let o of e){let s=o.slice(r.length).split(la)[0];if(n===null||s>n)n=s}return n}async function h_(e,t,r,n,o={}){an(e);let s=je(e),a=si(n),u=Yn(n.prefix),_=Iw(e,t),m=br(e,_,{onlyNode:s}),x=0,D=!1;if(m.changes.length===0)o_(e,t,m.cursor);else{let de=o.minPushChanges??1,ge=o.maxPushAgeMs??0;if(o.forcePush||m.changes.length>=de||Uw(m.changes[0])>=ge){let Ze=Rw(u,s,m.cursor);await r.put(n_(u,s),new TextEncoder().encode(Ze),{contentType:"text/plain"}),await r.put(Ze,await d_(m.changes,a),{contentType:"application/octet-stream"}),o_(e,t,m.cursor),x=m.changes.length}else D=!0}let j=[],Y=0;if(o.pull??!0){j=(await r.list(Qn(u))).map((de)=>de.key).filter((de)=>de.endsWith(".snap")),Y+=await Hw(e,t,j,r,a);for(let de of await Bw(r,u)){if(de===s)continue;let ge=_a(e,t,de),Le=await r.get(n_(u,de));if(Le){let $e=new TextDecoder().decode(Le);if(ge&&$e<=ge)continue}let Ze=(await r.list(ua(u,de),ge??void 0)).filter(($e)=>$e.key.endsWith(".seg"));for(let $e of Ze){let Ue=await r.get($e.key);if(!Ue)continue;let tt=await f_(Ue,a);Y+=rr(e,tt),ga(e,t,de,$e.key)}}}let _e=!1;if(o.publish){let de=e.query("SELECT COUNT(*) AS n FROM crdt_changes").get().n;if(de>0){let ge=jw(j,u),Le=o.snapshotMinDelta??Sw,Ze=o.snapshotDeltaRatio??xw,$e=o.snapshotMaxIntervalMs??Tw,Ue=ge===null?de:e.query("SELECT COUNT(*) AS n FROM crdt_changes WHERE hlc > ?").get(ge).n;if((ge===null||Ue>=Math.max(Le,de*Ze)||Ue>0&&Date.now()-g_(ge)>=$e)&&await Xp(r,u,s,o.priority??0))await i_(e,r,n,o.snapshotRetainSegments),_e=!0}}if(o.publish&&!_e&&x>0){let de=o.snapshotEverySegments??200;if((await r.list(ua(u,s))).filter((Le)=>Le.key.endsWith(".seg")).length>=de)await i_(e,r,n,o.snapshotRetainSegments)}return{pushed:x,pulled:Y,pendingPush:D}}async function Hw(e,t,r,n,o){if(r.length===0)return 0;let s=Pw(e,t),a=Lw(e),u=0;for(let m of[...r].sort().reverse()){if(s.has(m))continue;let x=await n.get(da(m)),D=x?await zw(x,o):null;if(D&&$w(a,D.frontier)){s.add(m);continue}let j=await n.get(m);if(!j)continue;let Y=await f_(j,o);u+=rr(e,Y),s.add(m);for(let _e of Y)if(!a[_e.node_id]||_e.hlc>a[_e.node_id])a[_e.node_id]=_e.hlc;if(D?.ownSegHigh){let _e=_a(e,t,D.ownNode);if(!_e||_e<D.ownSegHigh)ga(e,t,D.ownNode,D.ownSegHigh)}}let _=new Set(r);return Nw(e,t,[...s].filter((m)=>_.has(m))),u}var ca=null,c_="__snapshot__",vw=16,la="~",Ew=40,Sw=200,xw=0.5,Tw=1800000,kw=(e)=>`${e}/oplog/`,ua=(e,t)=>`${e}/oplog/${t}/`,n_=(e,t)=>`${e}/oplog/${t}/HEAD`,Rw=(e,t,r)=>`${e}/oplog/${t}/${String(r).padStart(vw,"0")}.seg`,Qn=(e)=>`${e}/snapshot/`,Aw=(e)=>`${e}/keys/main.json`,p_=(e,t)=>`${e}/blobs/${t}`,da=(e)=>`${e}.vc`;var bn=De(()=>{Gt();dt();Qp();Ye();Xn()});var Ww=32,Zw=3,Nk;var m_=De(()=>{Ye();Nk=(Ww+Zw)*8/5});var y_=De(()=>{Ye()});function Gw(e){let t=e.query("SELECT value FROM meta WHERE key = ?").get("site_publish_rollbacks");if(!t?.value)return[];try{let r=JSON.parse(t.value);if(!Array.isArray(r))return[];return r.filter((n)=>!!n&&typeof n.siteId==="string"&&typeof n.peerUrl==="string"&&typeof n.targetUrl==="string"&&Number.isFinite(n.requiredSeq)&&Number.isFinite(n.createdAt)&&typeof n.lastError==="string")}catch{return[]}}function Kw(e,t){if(t.length===0){e.query("DELETE FROM meta WHERE key = ?").run("site_publish_rollbacks");return}e.query("INSERT INTO meta (key,value) VALUES (?,?) ON CONFLICT(key) DO UPDATE SET value=excluded.value").run("site_publish_rollbacks",JSON.stringify(t))}function b_(e,t){let r=e.query("SELECT push_cursor,last_status FROM peers WHERE url = ?").get(t);if(!r||r.last_status!=="ok")return 0;let n=Gw(e),o=n.filter((s)=>s.peerUrl!==t||s.requiredSeq>r.push_cursor);return Kw(e,o),n.length-o.length}var v_;var w_=De(()=>{v_={name:"@tensorix/metahub",version:"0.5.2",description:"Metahub core library and CLI",license:"AGPL-3.0-only",type:"module",main:"./dist/index.js",module:"./dist/index.js",types:"./dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./package.json":"./package.json"},bin:{metahub:"./dist/cli.js",mh:"./dist/cli.js"},files:["dist","README.md","README.zh-CN.md","LICENSE"],scripts:{dev:"bun --hot src/cli/index.ts",build:"bun run scripts/build.ts","build:shell":"bun run scripts/build-shell.ts","build:share-viewer":"bun run scripts/build-share-viewer.ts","build:binaries":"bun run scripts/compile-binaries.ts","build:binaries:host":"HOST_ONLY=1 bun run scripts/compile-binaries.ts",prepublishOnly:"bun run build",test:"bun test",release:"bun run scripts/tag-release.ts"},dependencies:{"@clack/prompts":"^1.5.0","@codemirror/commands":"6.10.4","@codemirror/state":"6.7.0","@codemirror/view":"6.43.4","@joplin/turndown-plugin-gfm":"^1.0.67","@sqlite.org/sqlite-wasm":"^3.53.0-build1",aws4fetch:"^1.0.20",citty:"^0.1.6","highlight.js":"^11.11.1",jsqr:"^1.4.0",preact:"^10.29.2","qrcode-generator":"^2.0.4",turndown:"^7.2.4",zod:"^4.4.3"},devDependencies:{"@happy-dom/global-registrator":"^20.10.2","@prettier/plugin-php":"^0.25.0","@types/bun":"latest","@types/turndown":"^5.0.6","@wasm-fmt/clang-format":"^22.1.8","@wasm-fmt/gofmt":"^0.7.3","@wasm-fmt/lua_fmt":"^0.3.3","@wasm-fmt/ruff_fmt":"^0.15.20","@wasm-fmt/taplo_fmt":"^0.2.5","mvdan-sh":"^0.10.1",prettier:"^3.6","sql-formatter":"^15",typescript:"^5"}}});function ma(){return{v:1,tables:[]}}function Xw(e){return typeof e==="string"&&ya.includes(e)}function E_(e){let t=new Map;for(let n of e){let o=t.get(n.db)??new Set;for(let s of n.ops)o.add(s);t.set(n.db,o)}let r=[];for(let[n,o]of t){let s=ya.filter((a)=>o.has(a));if(s.length)r.push({db:n,ops:s})}return r.sort((n,o)=>n.db<o.db?-1:n.db>o.db?1:0),{v:1,tables:r}}function hr(e){if(!e)return ma();let t;try{t=JSON.parse(e)}catch{return ma()}try{return eo(t)}catch{return ma()}}function eo(e){if(typeof e!=="object"||e===null||Array.isArray(e))throw new Z("invalid_input","grants must be an object {v:1, tables:[...]}");let t=e;if(t.v!==1)throw new Z("invalid_input","grants version must be 1");if(!Array.isArray(t.tables))throw new Z("invalid_input","grants.tables must be an array");let r=[];for(let n of t.tables){if(typeof n!=="object"||n===null)throw new Z("invalid_input","each grant table must be an object {db, ops}");let{db:o,ops:s}=n;if(typeof o!=="string"||!o)throw new Z("invalid_input","grant table `db` must be a database id");if(!Array.isArray(s)||!s.every(Xw))throw new Z("invalid_input",`grant ops must be a subset of ${ya.join("|")} (delete is never grantable)`);r.push({db:o,ops:s})}return E_(r)}function ai(e){return JSON.stringify(E_(e.tables))}function S_(e){return e.tables.some((t)=>t.ops.some((r)=>r!=="read"))}var ya;var Wr=De(()=>{Ye();qr();Cr();Lr();dt();ya=["read","create","update"]});function ba(e,t){let r=t.permission??"view";if(!Qw.has(t.kind))throw new Z("invalid_input",`unknown share kind: ${t.kind}`);if(r!=="view"&&r!=="edit")throw new Z("invalid_input",`unknown share permission: ${r}`);let n=t.requestId?.trim()||null;if(n&&!/^[A-Za-z0-9_-]{16,80}$/.test(n))throw new Z("invalid_input","share request id is invalid");if(n){let _=T_(e,n);if(_){if(_.kind!==t.kind||_.target_id!==t.target_id)throw new Z("conflict","share request id was already used for another target");return _}}let o=null;if(t.grants!=null){let _;try{_=JSON.parse(t.grants)}catch{throw new Z("invalid_input","grants must be a JSON GrantSet")}o=ai(eo(_))}let s=yt(12);while(sr(e,s))s=yt(12);let u=r==="edit"||S_(hr(o))?"g"+yt(8):null;return e.query(`INSERT INTO shares (${to}) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(s,t.kind,t.target_id,r,"server",t.pwSalt??null,t.pwHash??null,t.expiresAt??null,u,t.servedBase??null,null,null,null,null,Date.now(),n,o),sr(e,s)}function T_(e,t){return e.query(`SELECT ${to} FROM shares WHERE request_id = ?`).get(t)??null}function sr(e,t){return e.query(`SELECT ${to} FROM shares WHERE slug = ?`).get(t)??null}function wa(e){return e.query(`SELECT ${to} FROM shares ORDER BY created_at DESC`).all()}function va(e,t){return e.query(`SELECT ${to} FROM shares WHERE target_id = ? ORDER BY created_at DESC`).all(t)}function Yt(e,t){return e.query("DELETE FROM shares WHERE slug = ?").run(t).changes>0}function x_(e){let t=new Uint8Array(e.byteLength);return t.set(e),t.buffer}async function rv(e,t){let r=await crypto.subtle.importKey("raw",x_(new TextEncoder().encode(e)),"PBKDF2",!1,["deriveBits"]),n=await crypto.subtle.deriveBits({name:"PBKDF2",salt:x_(t),iterations:Yw,hash:"SHA-256"},r,tv);return new Uint8Array(n)}async function Ea(e){let t=crypto.getRandomValues(new Uint8Array(ev)),r=await rv(e,t);return{salt:ir(t),hash:ir(r)}}var Qw,to="slug, kind, target_id, permission, transport, pw_salt, pw_hash, expires_at, guest_node_id, served_base, s3_peer_url, s3_object_prefix, s3_presign_exp, s3_key_b64, created_at, request_id, grants",Yw=600000,ev=16,tv=256;var wn=De(()=>{Ye();bt();Xn();Wr();Qw=new Set(["doc","database","site"])});function Sa(e){let t=nv;for(let r=0;r<e.length;r++)t^=BigInt(e.charCodeAt(r)),t=t*ov&iv;return t.toString(16).padStart(16,"0")}var nv=0xcbf29ce484222325n,ov=0x100000001b3n,iv=0xffffffffffffffffn;function xa(e){let t=[],r=[];if(e.grantedDbIds.length>0){let n=e.grantedDbIds.map(()=>"?").join(", ");t.push(`SELECT 'databases' AS dataset, id AS row_id FROM databases WHERE id IN (${n})`),r.push(...e.grantedDbIds),t.push(`SELECT 'properties', id FROM properties WHERE database_id IN (${n})`),r.push(...e.grantedDbIds),t.push(`SELECT 'records', id FROM records WHERE database_id IN (${n})`),r.push(...e.grantedDbIds)}if(e.siteId)t.push("SELECT 'sites', id FROM sites WHERE id = ?"),r.push(e.siteId),t.push("SELECT 'site_files', id FROM site_files WHERE site_id = ?"),r.push(e.siteId);if(t.length===0)t.push("SELECT '' AS dataset, '' AS row_id WHERE 0");return{sql:t.join(" UNION ALL "),params:r}}function A_(e,t){let r=xa(t);return e.query(`SELECT dataset, row_id FROM (${r.sql}) ORDER BY dataset, row_id`).all(...r.params)}function Ta(e,t,r){switch(r.dataset){case"databases":return t.grantedDbIds.includes(r.row_id)&&e.query("SELECT 1 FROM databases WHERE id = ?").get(r.row_id)!=null;case"properties":case"records":{let n=e.query(`SELECT database_id FROM ${r.dataset} WHERE id = ?`).get(r.row_id);return n?.database_id!=null&&t.grantedDbIds.includes(n.database_id)}case"sites":return t.siteId===r.row_id&&e.query("SELECT 1 FROM sites WHERE id = ?").get(r.row_id)!=null;case"site_files":{if(!t.siteId)return!1;return e.query("SELECT site_id FROM site_files WHERE id = ?").get(r.row_id)?.site_id===t.siteId}default:return!1}}function D_(e,t,r){let n=xa(r),o=e.query(`WITH m(dataset, row_id) AS (${n.sql})
464
480
  SELECT dataset, row_id FROM m
465
481
  EXCEPT SELECT dataset, row_id FROM room_rows WHERE peer_key = ?`).all(...n.params,t),s=e.query(`WITH m(dataset, row_id) AS (${n.sql})
466
482
  SELECT dataset, row_id FROM room_rows WHERE peer_key = ?
467
- EXCEPT SELECT dataset, row_id FROM m`).all(...n.params,t);return{entered:o,left:s}}function ci(e,t,r){let n=e.query("DELETE FROM room_rows WHERE peer_key = ? AND dataset = ? AND row_id = ?");for(let s of r.left)n.run(t,s.dataset,s.row_id);let o=e.query("INSERT OR IGNORE INTO room_rows (peer_key, dataset, row_id) VALUES (?, ?, ?)");for(let s of r.entered)o.run(t,s.dataset,s.row_id)}function S_(e,t,r){e.query("DELETE FROM room_rows WHERE peer_key = ?").run(t),ci(e,t,{entered:r,left:[]})}function x_(e,t,r,n={}){let o=["c.seq > ?"],s=[r,t];if(n.excludeGuestBase!=null)o.push("NOT (c.node_id = ? OR c.node_id LIKE ? || '-%')"),s.push(n.excludeGuestBase,n.excludeGuestBase);let a=n.limit!=null&&n.limit>0?` LIMIT ${Math.floor(n.limit)}`:"",u=e.query(`SELECT c.seq AS seq, ${w_} FROM crdt_changes c
483
+ EXCEPT SELECT dataset, row_id FROM m`).all(...n.params,t);return{entered:o,left:s}}function ci(e,t,r){let n=e.query("DELETE FROM room_rows WHERE peer_key = ? AND dataset = ? AND row_id = ?");for(let s of r.left)n.run(t,s.dataset,s.row_id);let o=e.query("INSERT OR IGNORE INTO room_rows (peer_key, dataset, row_id) VALUES (?, ?, ?)");for(let s of r.entered)o.run(t,s.dataset,s.row_id)}function O_(e,t,r){e.query("DELETE FROM room_rows WHERE peer_key = ?").run(t),ci(e,t,{entered:r,left:[]})}function I_(e,t,r,n={}){let o=["c.seq > ?"],s=[r,t];if(n.excludeGuestBase!=null)o.push("NOT (c.node_id = ? OR c.node_id LIKE ? || '-%')"),s.push(n.excludeGuestBase,n.excludeGuestBase);let a=n.limit!=null&&n.limit>0?` LIMIT ${Math.floor(n.limit)}`:"",u=e.query(`SELECT c.seq AS seq, ${R_} FROM crdt_changes c
468
484
  JOIN room_rows r ON r.peer_key = ? AND r.dataset = c.dataset AND r.row_id = c.row_id
469
- WHERE ${o.join(" AND ")} ORDER BY c.seq${a}`).all(...s),_=n.limit==null||n.limit<=0||u.length<n.limit,m;if(_){let x=e.query("SELECT MAX(seq) AS m FROM crdt_changes").get();m=Math.max(t,x.m??t)}else m=u[u.length-1].seq;return{changes:u.map(({seq:x,...D})=>D),cursor:m}}function Sa(e,t,r){return e.query(`SELECT ${It} FROM crdt_changes c
485
+ WHERE ${o.join(" AND ")} ORDER BY c.seq${a}`).all(...s),_=n.limit==null||n.limit<=0||u.length<n.limit,m;if(_){let x=e.query("SELECT MAX(seq) AS m FROM crdt_changes").get();m=Math.max(t,x.m??t)}else m=u[u.length-1].seq;return{changes:u.map(({seq:x,...D})=>D),cursor:m}}function ka(e,t,r){return e.query(`SELECT ${It} FROM crdt_changes c
470
486
  WHERE c.dataset = ? AND c.row_id = ? AND NOT EXISTS (
471
487
  SELECT 1 FROM crdt_changes k
472
488
  WHERE k.dataset = c.dataset AND k.row_id = c.row_id AND k.col = c.col AND k.hlc > c.hlc
473
- )`).all(t,r)}function li(e,t){let r=va(t);return e.query(`WITH m(dataset, row_id) AS (${r.sql})
474
- SELECT ${w_} FROM crdt_changes c
489
+ )`).all(t,r)}function li(e,t){let r=xa(t);return e.query(`WITH m(dataset, row_id) AS (${r.sql})
490
+ SELECT ${R_} FROM crdt_changes c
475
491
  JOIN m ON m.dataset = c.dataset AND m.row_id = c.row_id
476
492
  WHERE NOT EXISTS (
477
493
  SELECT 1 FROM crdt_changes k
478
494
  WHERE k.dataset = c.dataset AND k.row_id = c.row_id AND k.col = c.col AND k.hlc > c.hlc
479
- )`).all(...r.params)}function ui(e){let t=e.map((r)=>`${r.dataset}\x00${r.row_id}\x00${r.col}\x00${r.hlc}`).sort();return wa(t.map((r)=>r+"\x1E").join(""))}var b_,w_;var xa=De(()=>{dt();b_=["databases","properties","records","sites","site_files"],w_=Eo.map((e)=>"c."+e).join(", ")});var T_=De(()=>{Wr();vn()});var k_=De(()=>{Ye();Lr();dt();wt();Wr()});var di=1,fi=1048576,bR;var Ta=De(()=>{Ye();dt();Po();wt();T_();k_();xa();bR=Object.fromEntries(b_.map((e)=>[e,e]))});function Vw(e,t){e.query("INSERT INTO peers (url, kind, enabled, pull_cursor, push_cursor) VALUES (?, 'room', 1, 0, 0) ON CONFLICT(url) DO NOTHING").run(t)}function no(e,t){let r=e.query("SELECT pull_cursor, push_cursor FROM peers WHERE url = ?").get(t);return{pull:r?.pull_cursor??0,push:r?.push_cursor??0}}function ka(e,t,r){e.query("UPDATE peers SET pull_cursor = ?, push_cursor = ? WHERE url = ?").run(r.pull,r.push,t)}function A_(e,t){for(let r of e)if(r.node_id!==t&&!r.node_id.startsWith(t+"-"))throw new Z("auth",`room returned an op authored by ${JSON.stringify(r.node_id)} — refusing to ingest`)}function D_(e,t,r){let n=new Set,o=[];for(let s of r){let a=`${s.dataset} ${s.row_id}`;if(n.has(a))continue;n.add(a);let u={dataset:s.dataset,row_id:s.row_id};if(Ea(e,t.scope,u))o.push(u)}return o}function Jw(e,t,r){return e.transaction(()=>{let{push:o}=no(e,t.peerKey),s=E_(e,t.peerKey,t.scope),a=x_(e,o,t.peerKey,{limit:r,excludeGuestBase:t.guestBase}),u=[...a.changes],_=[];for(let m of s.entered){if(u.length>=r&&_.length>0)break;if(u.push(...Sa(e,m.dataset,m.row_id)),_.push(m),u.length>=r)break}return{diff:s,shipped:_,changes:u,pushCursor:a.cursor,pendingBaselines:_.length<s.entered.length,incrementFull:a.changes.length>=r}})()}async function O_(e,t,r,n={}){let o=n.limit??500;Vw(e,t.peerKey);let s=no(e,t.peerKey).pull,a=Jw(e,t,o),u={protocol:di,mh_version:n.mhVersion,node_id:We(e),since:s,changes:a.changes,evict:a.diff.left,digest:n.digest?ui(li(e,t.scope)):void 0},_=await r(u);if(_.protocol!==di)throw new Z("conflict",`room answered protocol ${_.protocol} — upgrade required`);if(_.share_state==="expired")return{pushed:0,pulled:0,evicted:0,pending:!1,healed:!1,needBlobs:[],shareState:"expired"};A_(_.changes,t.guestBase);let m=er(e,_.changes);if(e.transaction(()=>{ci(e,t.peerKey,{entered:[...a.shipped,...D_(e,t,_.changes)],left:a.diff.left}),ka(e,t.peerKey,{pull:_.cursor,push:a.pushCursor})})(),_.need_baseline.length>0)await Xw(e,t,r,_.need_baseline);let x=!1;if(n.digest&&_.digest!==void 0){if(ui(li(e,t.scope))!==_.digest)await Qw(e,t,r),x=!0}return{pushed:a.changes.length,pulled:m,evicted:a.diff.left.length,pending:a.pendingBaselines||a.incrementFull||_.more===!0,healed:x,needBlobs:_.need_blobs??[],shareState:"active"}}async function Xw(e,t,r,n){let o=[],s=[],a=[];for(let _ of n)if(Ea(e,t.scope,_))o.push(...Sa(e,_.dataset,_.row_id)),a.push(_);else s.push(_);let u=await I_(e,t,r,o,s);if(u.share_state==="expired")return;e.transaction(()=>{ci(e,t.peerKey,{entered:[...a,...D_(e,t,u.changes)],left:s});let _=no(e,t.peerKey);ka(e,t.peerKey,{pull:u.cursor,push:_.push})})()}async function Qw(e,t,r){let n=v_(e,t.scope),o=li(e,t.scope),s=await I_(e,t,r,o,[],n);if(s.share_state==="expired")return;e.transaction(()=>{S_(e,t.peerKey,n);let a=no(e,t.peerKey);ka(e,t.peerKey,{pull:s.cursor,push:a.push})})()}async function I_(e,t,r,n,o,s){let a=await r({protocol:di,node_id:We(e),since:no(e,t.peerKey).pull,changes:n,evict:o,members:s});if(a.share_state==="expired")return a;return A_(a.changes,t.guestBase),er(e,a.changes),a}var R_=16;var P_=De(()=>{Ye();Gt();dt();xa();Ta()});function Zr(e){return`${e.base.replace(/\/+$/,"")}/r/${e.slug}/`}function N_(e){C_=e}function Ra(e){return`room://${e}`}function sr(e,t,r,n){let o={...t,lifecycle:r,...n?{cleanupError:n}:{cleanupError:void 0}};return Aa(e,{url:Ra(t.slug),config:o,label:`room ${t.slug}`}),o}function _i(e,t){return`${e.base.replace(/\/+$/,"")}/r/${encodeURIComponent(e.slug)}/${t}`}function gi(e,t=!0){return{authorization:`Bearer ${e.ownerSecret}`,...t?{"content-type":"application/json"}:{}}}async function q_(e,t){try{return await fetch(_i(e,"owner/provision"),{method:"POST",headers:gi(e),body:JSON.stringify({slug:t.slug,guestBase:e.guestBase,grants:t.grants,pwHash:t.pw_hash,pwSalt:t.pw_salt,expiresAt:t.expires_at}),signal:AbortSignal.timeout(30000)})}catch(r){throw new Z("network",`edge worker unreachable: ${r.message}`)}}function L_(e){if(e.status===401)return new Z("auth","edge worker refused the owner secret");if(e.status===404)return new Z("not_found","the deployed edge worker has no room support — run `mh edge deploy` to upgrade it");return new Z("network",`room provisioning failed: HTTP ${e.status}`)}function Yw(e){return async(t)=>{let r;try{r=await fetch(_i(e,"owner/sync"),{method:"POST",headers:gi(e),body:JSON.stringify(t),signal:AbortSignal.timeout(30000)})}catch(n){throw new Z("network",`room ${e.slug} unreachable: ${n.message}`)}if(r.status===409)throw new Z("conflict","room protocol outdated — run `mh edge deploy`");if(r.status===401)throw new Z("auth",`room ${e.slug} refused the owner secret`);if(r.status===404)throw new Z("not_found",`room ${e.slug} is not provisioned — re-create the share with --room`);if(!r.ok)throw new Z("network",`room sync failed: HTTP ${r.status}`);return await r.json()}}async function hi(e,t,r={}){if(!t.config)throw new Z("invalid_input",`room peer ${t.url} has no config`);let n=JSON.parse(t.config);if(n.lifecycle==="cleanup_pending"){if(!await ir(n).catch(()=>!1))throw new Z("network",n.cleanupError||`room ${n.slug} cleanup is still pending`);return vt(e,t.url),Qt(e,n.slug),pi.delete(t.url),{pushed:0,pulled:0,pendingPush:!1}}let o=or(e,n.slug);if(!o){if(await ir(n).catch(()=>!1))return vt(e,t.url),{pushed:0,pulled:0,pendingPush:!1};throw n=sr(e,n,"cleanup_pending","share row is gone but remote room destruction is unconfirmed"),new Z("network",n.cleanupError)}if(n.lifecycle==="provisioning"){let Y;try{Y=await q_(n,o)}catch(ge){if(await ir(n).catch(()=>!1))vt(e,t.url),Qt(e,o.slug);else sr(e,n,"cleanup_pending",ge.message);throw ge}if(!Y.ok){let ge=L_(Y);if(Y.status===401||Y.status===404||await ir(n).catch(()=>!1))vt(e,t.url),Qt(e,o.slug);else sr(e,n,"cleanup_pending",ge.message);throw ge}let _e=sr(e,n,"active"),de=Et(e,t.url);try{return await hi(e,de,r)}catch(ge){if(await ir(_e).catch(()=>!1))vt(e,t.url),Qt(e,o.slug);else sr(e,_e,"cleanup_pending",ge.message);throw ge}}let s={grantedDbIds:_r(o.grants).tables.map((Y)=>Y.db),siteId:o.kind==="site"?o.target_id:null},a=n.guestBase??o.guest_node_id;if(!a)throw new Z("invalid_input",`room peer ${t.url} has no guest base id — revoke and re-create the share with --room`);let u=pi.get(t.url)??{rounds:0,lastGrants:o.grants},_=Yw(n),m=0,x=0,D=[],j=!1;for(let Y=0;Y<ev;Y++){u.rounds++;let _e=u.rounds%R_===0||u.lastGrants!==o.grants;u.lastGrants=o.grants,pi.set(t.url,u);let de=await O_(e,{peerKey:t.url,scope:s,guestBase:a},_,{digest:_e});if(de.shareState==="expired")return await ir(n).catch(()=>{return}),vt(e,t.url),{pushed:m,pulled:x,pendingPush:!1};if(m+=de.pushed,x+=de.pulled,D=de.needBlobs,j=de.pending,!de.pending)break}if(D.length>0)await tv(e,n,D,r.resolveBlob);return{pushed:m,pulled:x,pendingPush:j}}async function tv(e,t,r,n){let o=n??C_;if(!o)return 0;let s=0;for(let a of r){if(!/^[0-9a-f]{16,64}$/.test(a))continue;let u=await o(e,a).catch(()=>null);if(!u)continue;let _=Math.max(1,Math.ceil(u.byteLength/fi)),m=!0;for(let x=0;x<_&&m;x++){let D=u.subarray(x*fi,(x+1)*fi),j=new Uint8Array(D.byteLength);j.set(D),m=!!(await fetch(`${_i(t,`owner/blob/${a}`)}?idx=${x}&total=${_}`,{method:"POST",headers:{...gi(t,!1),"content-type":"application/octet-stream"},body:j.buffer,signal:AbortSignal.timeout(30000)}).catch(()=>null))?.ok}if(m)s++}return s}async function $_(e,t,r,n){let o={base:r.endpoint.replace(/\/+$/,""),slug:t.slug,ownerSecret:r.token,guestBase:t.guest_node_id??"g"+bt(8),lifecycle:"provisioning"},s=Ra(t.slug);Aa(e,{url:s,config:o,label:`room ${t.slug}`});let a;try{a=await q_(o,t)}catch(m){let x=m.message;if(await ir(o).catch(()=>!1))vt(e,s);else sr(e,o,"cleanup_pending",x);throw m}if(!a.ok){let m=L_(a);if(a.status===401||a.status===404)throw vt(e,s),m;let x=m.message;if(await ir(o).catch(()=>!1))vt(e,s);else sr(e,o,"cleanup_pending",x);throw m}let u=sr(e,o,"active"),_=Et(e,s);try{await hi(e,_,{resolveBlob:n})}catch(m){let x=m.message;if(await ir(u).catch(()=>!1))vt(e,s);else sr(e,u,"cleanup_pending",x);throw m}return{url:Zr(u),peerKey:s}}async function ir(e){let t=await fetch(_i(e,"owner/destroy"),{method:"POST",headers:gi(e),signal:AbortSignal.timeout(30000)});return t.ok||t.status===404}async function oo(e,t){let r=Et(e,Ra(t));if(!r||r.kind!=="room"||!r.config)return"absent";let n=JSON.parse(r.config),o=sr(e,n,"cleanup_pending","remote room destruction is unconfirmed");if(!await ir(o).catch(()=>!1))return"cleanup_pending";return vt(e,r.url),pi.delete(r.url),"destroyed"}var C_,pi,ev=50;var mi=De(()=>{Ye();wt();vn();Wr();io();P_();Ta();pi=new Map});function iv(e){let t=e.slice(e.lastIndexOf(".")+1).toLowerCase();return ov[t]??"application/octet-stream"}function Ia(e){let t=e.trim().toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^-+|-+$/g,"");if(!t)throw new Z("invalid_input",`invalid site name: ${JSON.stringify(e)}`);return t}function Pa(e){let t=[];for(let r of e.split("/")){if(r===""||r===".")continue;if(r==="..")t.pop();else t.push(r)}return t.join("/")}function M_(e){return e.visibility==="public"}function Yt(e,t){return e.query(`SELECT ${Oa} FROM sites WHERE id = ? AND __deleted = 0`).get(t)}function B_(e,t){let r=e.query("SELECT __deleted AS d FROM sites WHERE id = ?").get(t);if(!r)return"absent";return r.d?"tombstoned":"live"}function Ca(e,t){let r;try{r=Ia(t)}catch{return null}return e.query(`SELECT ${Oa} FROM sites WHERE name = ? AND __deleted = 0 ORDER BY created_hlc DESC LIMIT 1`).get(r)}function U_(e){return e.query(`SELECT ${Oa} FROM sites WHERE __deleted = 0 ORDER BY created_hlc`).all()}function Gr(e,t){let n=(t.startsWith("site_")?Yt(e,t):null)??Ca(e,t);if(!n)throw new Z("not_found",`no such site: ${t}`);return n}function Da(e,t,r){return e.query("SELECT content_type, encoding, content FROM site_files WHERE site_id = ? AND path = ? AND __deleted = 0 ORDER BY created_hlc LIMIT 1").get(t,r)}function j_(e,t,r,n={}){let o=r===""||r.endsWith("/")?`${r}index.html`:r,s=Pa(o);if(s){let u=Da(e,t,s);if(u)return{row:u,status:200}}if(n.spa){let u=r.split("/").pop()??"";if(!/\.[a-z0-9]+$/i.test(u)){let _=Da(e,t,"index.html");if(_)return{row:_,status:200}}}let a=Da(e,t,"404.html");if(a)return{row:a,status:404};return null}function H_(e,t){return e.query(`SELECT id, site_id, path, content_type, encoding,
495
+ )`).all(...r.params)}function ui(e){let t=e.map((r)=>`${r.dataset}\x00${r.row_id}\x00${r.col}\x00${r.hlc}`).sort();return Sa(t.map((r)=>r+"\x1E").join(""))}var k_,R_;var Ra=De(()=>{dt();k_=["databases","properties","records","sites","site_files"],R_=vo.map((e)=>"c."+e).join(", ")});var P_=De(()=>{Wr();wn()});var N_=De(()=>{Ye();Lr();dt();bt();Wr()});var di=1,fi=1048576,CR;var Aa=De(()=>{Ye();dt();Po();bt();P_();N_();Ra();CR=Object.fromEntries(k_.map((e)=>[e,e]))});function sv(e,t){e.query("INSERT INTO peers (url, kind, enabled, pull_cursor, push_cursor) VALUES (?, 'room', 1, 0, 0) ON CONFLICT(url) DO NOTHING").run(t)}function ro(e,t){let r=e.query("SELECT pull_cursor, push_cursor FROM peers WHERE url = ?").get(t);return{pull:r?.pull_cursor??0,push:r?.push_cursor??0}}function Da(e,t,r){e.query("UPDATE peers SET pull_cursor = ?, push_cursor = ? WHERE url = ?").run(r.pull,r.push,t)}function q_(e,t){for(let r of e)if(r.node_id!==t&&!r.node_id.startsWith(t+"-"))throw new Z("auth",`room returned an op authored by ${JSON.stringify(r.node_id)} — refusing to ingest`)}function L_(e,t,r){let n=new Set,o=[];for(let s of r){let a=`${s.dataset} ${s.row_id}`;if(n.has(a))continue;n.add(a);let u={dataset:s.dataset,row_id:s.row_id};if(Ta(e,t.scope,u))o.push(u)}return o}function av(e,t,r){return e.transaction(()=>{let{push:o}=ro(e,t.peerKey),s=D_(e,t.peerKey,t.scope),a=I_(e,o,t.peerKey,{limit:r,excludeGuestBase:t.guestBase}),u=[...a.changes],_=[];for(let m of s.entered){if(u.length>=r&&_.length>0)break;if(u.push(...ka(e,m.dataset,m.row_id)),_.push(m),u.length>=r)break}return{diff:s,shipped:_,changes:u,pushCursor:a.cursor,pendingBaselines:_.length<s.entered.length,incrementFull:a.changes.length>=r}})()}async function $_(e,t,r,n={}){let o=n.limit??500;sv(e,t.peerKey);let s=ro(e,t.peerKey).pull,a=av(e,t,o),u={protocol:di,mh_version:n.mhVersion,node_id:je(e),since:s,changes:a.changes,evict:a.diff.left,digest:n.digest?ui(li(e,t.scope)):void 0},_=await r(u);if(_.protocol!==di)throw new Z("conflict",`room answered protocol ${_.protocol} — upgrade required`);if(_.share_state==="expired")return{pushed:0,pulled:0,evicted:0,pending:!1,healed:!1,needBlobs:[],shareState:"expired"};q_(_.changes,t.guestBase);let m=rr(e,_.changes);if(e.transaction(()=>{ci(e,t.peerKey,{entered:[...a.shipped,...L_(e,t,_.changes)],left:a.diff.left}),Da(e,t.peerKey,{pull:_.cursor,push:a.pushCursor})})(),_.need_baseline.length>0)await cv(e,t,r,_.need_baseline);let x=!1;if(n.digest&&_.digest!==void 0){if(ui(li(e,t.scope))!==_.digest)await lv(e,t,r),x=!0}return{pushed:a.changes.length,pulled:m,evicted:a.diff.left.length,pending:a.pendingBaselines||a.incrementFull||_.more===!0,healed:x,needBlobs:_.need_blobs??[],shareState:"active"}}async function cv(e,t,r,n){let o=[],s=[],a=[];for(let _ of n)if(Ta(e,t.scope,_))o.push(...ka(e,_.dataset,_.row_id)),a.push(_);else s.push(_);let u=await F_(e,t,r,o,s);if(u.share_state==="expired")return;e.transaction(()=>{ci(e,t.peerKey,{entered:[...a,...L_(e,t,u.changes)],left:s});let _=ro(e,t.peerKey);Da(e,t.peerKey,{pull:u.cursor,push:_.push})})()}async function lv(e,t,r){let n=A_(e,t.scope),o=li(e,t.scope),s=await F_(e,t,r,o,[],n);if(s.share_state==="expired")return;e.transaction(()=>{O_(e,t.peerKey,n);let a=ro(e,t.peerKey);Da(e,t.peerKey,{pull:s.cursor,push:a.push})})()}async function F_(e,t,r,n,o,s){let a=await r({protocol:di,node_id:je(e),since:ro(e,t.peerKey).pull,changes:n,evict:o,members:s});if(a.share_state==="expired")return a;return q_(a.changes,t.guestBase),rr(e,a.changes),a}var C_=16;var z_=De(()=>{Ye();Gt();dt();Ra();Aa()});function Zr(e){return`${e.base.replace(/\/+$/,"")}/r/${e.slug}/`}function B_(e){M_=e}function Oa(e){return`room://${e}`}function cr(e,t,r,n){let o={...t,lifecycle:r,...n?{cleanupError:n}:{cleanupError:void 0}};return Ia(e,{url:Oa(t.slug),config:o,label:`room ${t.slug}`}),o}function _i(e,t){return`${e.base.replace(/\/+$/,"")}/r/${encodeURIComponent(e.slug)}/${t}`}function gi(e,t=!0){return{authorization:`Bearer ${e.ownerSecret}`,...t?{"content-type":"application/json"}:{}}}async function U_(e,t){try{return await fetch(_i(e,"owner/provision"),{method:"POST",headers:gi(e),body:JSON.stringify({slug:t.slug,guestBase:e.guestBase,grants:t.grants,pwHash:t.pw_hash,pwSalt:t.pw_salt,expiresAt:t.expires_at}),signal:AbortSignal.timeout(30000)})}catch(r){throw new Z("network",`edge worker unreachable: ${r.message}`)}}function j_(e){if(e.status===401)return new Z("auth","edge worker refused the owner secret");if(e.status===404)return new Z("not_found","the deployed edge worker has no room support — run `mh edge deploy` to upgrade it");return new Z("network",`room provisioning failed: HTTP ${e.status}`)}function uv(e){return async(t)=>{let r;try{r=await fetch(_i(e,"owner/sync"),{method:"POST",headers:gi(e),body:JSON.stringify(t),signal:AbortSignal.timeout(30000)})}catch(n){throw new Z("network",`room ${e.slug} unreachable: ${n.message}`)}if(r.status===409)throw new Z("conflict","room protocol outdated — run `mh edge deploy`");if(r.status===401)throw new Z("auth",`room ${e.slug} refused the owner secret`);if(r.status===404)throw new Z("not_found",`room ${e.slug} is not provisioned — re-create the share with --room`);if(!r.ok)throw new Z("network",`room sync failed: HTTP ${r.status}`);return await r.json()}}async function hi(e,t,r={}){if(!t.config)throw new Z("invalid_input",`room peer ${t.url} has no config`);let n=JSON.parse(t.config);if(n.lifecycle==="cleanup_pending"){if(!await ar(n).catch(()=>!1))throw new Z("network",n.cleanupError||`room ${n.slug} cleanup is still pending`);return wt(e,t.url),Yt(e,n.slug),pi.delete(t.url),{pushed:0,pulled:0,pendingPush:!1}}let o=sr(e,n.slug);if(!o){if(await ar(n).catch(()=>!1))return wt(e,t.url),{pushed:0,pulled:0,pendingPush:!1};throw n=cr(e,n,"cleanup_pending","share row is gone but remote room destruction is unconfirmed"),new Z("network",n.cleanupError)}if(n.lifecycle==="provisioning"){let Y;try{Y=await U_(n,o)}catch(ge){if(await ar(n).catch(()=>!1))wt(e,t.url),Yt(e,o.slug);else cr(e,n,"cleanup_pending",ge.message);throw ge}if(!Y.ok){let ge=j_(Y);if(Y.status===401||Y.status===404||await ar(n).catch(()=>!1))wt(e,t.url),Yt(e,o.slug);else cr(e,n,"cleanup_pending",ge.message);throw ge}let _e=cr(e,n,"active"),de=vt(e,t.url);try{return await hi(e,de,r)}catch(ge){if(await ar(_e).catch(()=>!1))wt(e,t.url),Yt(e,o.slug);else cr(e,_e,"cleanup_pending",ge.message);throw ge}}let s={grantedDbIds:hr(o.grants).tables.map((Y)=>Y.db),siteId:o.kind==="site"?o.target_id:null},a=n.guestBase??o.guest_node_id;if(!a)throw new Z("invalid_input",`room peer ${t.url} has no guest base id — revoke and re-create the share with --room`);let u=pi.get(t.url)??{rounds:0,lastGrants:o.grants},_=uv(n),m=0,x=0,D=[],j=!1;for(let Y=0;Y<dv;Y++){u.rounds++;let _e=u.rounds%C_===0||u.lastGrants!==o.grants;u.lastGrants=o.grants,pi.set(t.url,u);let de=await $_(e,{peerKey:t.url,scope:s,guestBase:a},_,{digest:_e});if(de.shareState==="expired")return await ar(n).catch(()=>{return}),wt(e,t.url),{pushed:m,pulled:x,pendingPush:!1};if(m+=de.pushed,x+=de.pulled,D=de.needBlobs,j=de.pending,!de.pending)break}if(D.length>0)await fv(e,n,D,r.resolveBlob);return{pushed:m,pulled:x,pendingPush:j}}async function fv(e,t,r,n){let o=n??M_;if(!o)return 0;let s=0;for(let a of r){if(!/^[0-9a-f]{16,64}$/.test(a))continue;let u=await o(e,a).catch(()=>null);if(!u)continue;let _=Math.max(1,Math.ceil(u.byteLength/fi)),m=!0;for(let x=0;x<_&&m;x++){let D=u.subarray(x*fi,(x+1)*fi),j=new Uint8Array(D.byteLength);j.set(D),m=!!(await fetch(`${_i(t,`owner/blob/${a}`)}?idx=${x}&total=${_}`,{method:"POST",headers:{...gi(t,!1),"content-type":"application/octet-stream"},body:j.buffer,signal:AbortSignal.timeout(30000)}).catch(()=>null))?.ok}if(m)s++}return s}async function H_(e,t,r,n){let o={base:r.endpoint.replace(/\/+$/,""),slug:t.slug,ownerSecret:r.token,guestBase:t.guest_node_id??"g"+yt(8),lifecycle:"provisioning"},s=Oa(t.slug);Ia(e,{url:s,config:o,label:`room ${t.slug}`});let a;try{a=await U_(o,t)}catch(m){let x=m.message;if(await ar(o).catch(()=>!1))wt(e,s);else cr(e,o,"cleanup_pending",x);throw m}if(!a.ok){let m=j_(a);if(a.status===401||a.status===404)throw wt(e,s),m;let x=m.message;if(await ar(o).catch(()=>!1))wt(e,s);else cr(e,o,"cleanup_pending",x);throw m}let u=cr(e,o,"active"),_=vt(e,s);try{await hi(e,_,{resolveBlob:n})}catch(m){let x=m.message;if(await ar(u).catch(()=>!1))wt(e,s);else cr(e,u,"cleanup_pending",x);throw m}return{url:Zr(u),peerKey:s}}async function ar(e){let t=await fetch(_i(e,"owner/destroy"),{method:"POST",headers:gi(e),signal:AbortSignal.timeout(30000)});return t.ok||t.status===404}async function no(e,t){let r=vt(e,Oa(t));if(!r||r.kind!=="room"||!r.config)return"absent";let n=JSON.parse(r.config),o=cr(e,n,"cleanup_pending","remote room destruction is unconfirmed");if(!await ar(o).catch(()=>!1))return"cleanup_pending";return wt(e,r.url),pi.delete(r.url),"destroyed"}var M_,pi,dv=50;var mi=De(()=>{Ye();bt();wn();Wr();oo();z_();Aa();pi=new Map});function hv(e){let t=e.slice(e.lastIndexOf(".")+1).toLowerCase();return gv[t]??"application/octet-stream"}function Ca(e){let t=e.trim().toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^-+|-+$/g,"");if(!t)throw new Z("invalid_input",`invalid site name: ${JSON.stringify(e)}`);return t}function qa(e){let t=[];for(let r of e.split("/")){if(r===""||r===".")continue;if(r==="..")t.pop();else t.push(r)}return t.join("/")}function G_(e){return e.visibility==="public"}function er(e,t){return e.query(`SELECT ${Na} FROM sites WHERE id = ? AND __deleted = 0`).get(t)}function K_(e,t){let r=e.query("SELECT __deleted AS d FROM sites WHERE id = ?").get(t);if(!r)return"absent";return r.d?"tombstoned":"live"}function La(e,t){let r;try{r=Ca(t)}catch{return null}return e.query(`SELECT ${Na} FROM sites WHERE name = ? AND __deleted = 0 ORDER BY created_hlc DESC LIMIT 1`).get(r)}function V_(e){return e.query(`SELECT ${Na} FROM sites WHERE __deleted = 0 ORDER BY created_hlc`).all()}function Gr(e,t){let n=(t.startsWith("site_")?er(e,t):null)??La(e,t);if(!n)throw new Z("not_found",`no such site: ${t}`);return n}function Pa(e,t,r){return e.query("SELECT content_type, encoding, content FROM site_files WHERE site_id = ? AND path = ? AND __deleted = 0 ORDER BY created_hlc LIMIT 1").get(t,r)}function J_(e,t,r,n={}){let o=r===""||r.endsWith("/")?`${r}index.html`:r,s=qa(o);if(s){let u=Pa(e,t,s);if(u)return{row:u,status:200}}if(n.spa){let u=r.split("/").pop()??"";if(!/\.[a-z0-9]+$/i.test(u)){let _=Pa(e,t,"index.html");if(_)return{row:_,status:200}}}let a=Pa(e,t,"404.html");if(a)return{row:a,status:404};return null}function X_(e,t){return e.query(`SELECT id, site_id, path, content_type, encoding,
480
496
  CASE encoding
481
497
  WHEN 'utf8' THEN LENGTH(CAST(content AS BLOB))
482
498
  WHEN 'base64' THEN (LENGTH(content) / 4) * 3
483
499
  ELSE (SELECT size FROM blob_cache WHERE hash = content)
484
500
  END AS size
485
- FROM site_files WHERE site_id = ? AND __deleted = 0 ORDER BY path`).all(t)}function W_(e,t){let r=t.content??"";if(t.encoding==="utf8")return new TextEncoder().encode(r).byteLength;if(t.encoding==="base64")return Math.floor(r.length/4)*3;return e.query("SELECT size FROM blob_cache WHERE hash = ?").get(r)?.size??null}function av(e){let t=e.toLowerCase();return t.startsWith("text/")||t.startsWith("application/json")||t.startsWith("application/manifest+json")||t.startsWith("application/xml")||t.startsWith("application/javascript")||t.startsWith("image/svg+xml")}function z_(e){if(typeof e==="string")return new TextEncoder().encode(e);return e instanceof Uint8Array?e:new Uint8Array(e)}function cv(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return btoa(t)}function Z_(e){if(e!=="public"&&e!=="private")throw new Z("invalid_input",`visibility must be "public" or "private", got ${JSON.stringify(e)}`)}function J_(e,t,r){return e.query("SELECT id FROM site_files WHERE site_id = ? AND path = ? ORDER BY created_hlc LIMIT 1").get(t,r)?.id??null}function lv(e,t,r,n,o,s){let a=e.query(`SELECT ${F_} FROM site_files WHERE site_id = ? AND path = ? AND __deleted = 0 ORDER BY created_hlc LIMIT 1`).get(t,r);if(!a)return null;return a.content_type===n&&a.encoding===o&&a.content===s?a:null}function uv(e,t,r,n,o,s){let a=lv(e,t,r,n,o,s);if(a)return{...a,changed:!1};let u=J_(e,t,r),_=u??Ot("sf",r);return yr(null,()=>{if(!u){let x=we(e,"site_files",_,"site_id",t);we(e,"site_files",_,"path",r),we(e,"site_files",_,"created_hlc",x.hlc)}we(e,"site_files",_,"content_type",n),we(e,"site_files",_,"encoding",o),we(e,"site_files",_,"content",s),we(e,"site_files",_,"__deleted",0)}),{...e.query(`SELECT ${F_} FROM site_files WHERE id = ?`).get(_),changed:!0}}function X_(e,t,r,n){let o=Pa(r);if(!o)throw new Z("invalid_input",`invalid file path: ${JSON.stringify(r)}`);let s=n.contentType??iv(o),a,u;if(av(s))a="utf8",u=typeof n.data==="string"?n.data:new TextDecoder().decode(z_(n.data));else{let _=z_(n.data);if(_.byteLength>sv)throw new Z("invalid_input","binary too large for inline storage (needs a server-backed blob)");a="base64",u=cv(_)}return uv(e,t,o,s,a,u)}function Y_(e){let t=e.query("SELECT site_id, COUNT(*) AS n FROM site_files WHERE __deleted = 0 GROUP BY site_id").all();return new Map(t.map((r)=>[r.site_id,r.n]))}function eg(e,t){return e.query("SELECT COUNT(*) AS n FROM site_files WHERE site_id = ? AND __deleted = 0").get(t).n}var rv,Oa,nv,F_,ov,sv=262144,G_,yi,K_,V_,Q_;var En=De(()=>{Ye();dt();wt();Wr();rv=["id","name","title","created_hlc","visibility","spa","public_grants"],Oa=rv.join(", "),nv=["id","site_id","path","content_type","encoding","content"],F_=nv.join(", "),ov={html:"text/html; charset=utf-8",htm:"text/html; charset=utf-8",css:"text/css; charset=utf-8",js:"text/javascript; charset=utf-8",mjs:"text/javascript; charset=utf-8",json:"application/json; charset=utf-8",svg:"image/svg+xml",txt:"text/plain; charset=utf-8",md:"text/markdown; charset=utf-8",xml:"application/xml; charset=utf-8",webmanifest:"application/manifest+json",ico:"image/x-icon",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",avif:"image/avif",woff:"font/woff",woff2:"font/woff2",ttf:"font/ttf",otf:"font/otf",pdf:"application/pdf",wasm:"application/wasm",mp4:"video/mp4",m4v:"video/mp4",webm:"video/webm",ogv:"video/ogg",mov:"video/quicktime",mkv:"video/x-matroska",mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",oga:"audio/ogg",m4a:"audio/mp4",aac:"audio/aac",flac:"audio/flac",opus:"audio/opus",weba:"audio/webm",csv:"text/csv; charset=utf-8",zip:"application/zip",gz:"application/gzip",tar:"application/x-tar",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",xls:"application/vnd.ms-excel",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",ppt:"application/vnd.ms-powerpoint",pptx:"application/vnd.openxmlformats-officedocument.presentationml.presentation"};G_=Fe(function(t,r){let n=Ia(r.name);if(Ca(t,n))throw new Z("conflict",`site name already exists: ${n}`);if(r.visibility!==void 0)Z_(r.visibility);let o=Ot("site",n),s=we(t,"sites",o,"name",n);if(we(t,"sites",o,"created_hlc",s.hlc),r.title!==void 0)we(t,"sites",o,"title",r.title);if(r.visibility!==void 0)we(t,"sites",o,"visibility",r.visibility);return Yt(t,o)}),yi=Fe(function(t,r,n){if(!Yt(t,r))throw new Z("not_found",`no such site: ${r}`);if(n.visibility!==void 0)Z_(n.visibility);if(n.name!==void 0){let o=Ia(n.name),s=Ca(t,o);if(s&&s.id!==r)throw new Z("conflict",`site name already exists: ${o}`);we(t,"sites",r,"name",o)}if(n.title!==void 0)we(t,"sites",r,"title",n.title);if(n.visibility!==void 0)we(t,"sites",r,"visibility",n.visibility);if(n.spa!==void 0)we(t,"sites",r,"spa",n.spa?1:0);return Yt(t,r)}),K_=Fe(function(t,r,n){if(!Yt(t,r))throw new Z("not_found",`no such site: ${r}`);let o=n==null?null:ai(to(n));return we(t,"sites",r,"public_grants",o),Yt(t,r)}),V_=Fe(function(t,r){if(!Yt(t,r))return!1;let n=t.query("SELECT id FROM site_files WHERE site_id = ? AND __deleted = 0").all(r);for(let o of n)we(t,"site_files",o.id,"__deleted",1);return we(t,"sites",r,"__deleted",1),!0});Q_=Fe(function(t,r,n){let o=J_(t,r,Pa(n));if(!o)return!1;let s=t.query("SELECT __deleted AS d FROM site_files WHERE id = ?").get(o);if(!s||s.d)return!1;return we(t,"site_files",o,"__deleted",1),!0})});function Na(e){return(e.audience==="public"||e.audience==="link")&&(e.hosting==="device"||e.hosting==="edge")&&(e.desired_state==="active"||e.desired_state==="revoked")}function Ut(e,t){return(t?e.query(`SELECT ${so} FROM site_channels
486
- WHERE site_id = ? AND __deleted = 0 ORDER BY created_hlc, id`).all(t):e.query(`SELECT ${so} FROM site_channels
487
- WHERE __deleted = 0 ORDER BY created_hlc, id`).all()).filter(Na)}function Sn(e,t){let r=e.query(`SELECT ${so} FROM site_channels WHERE id = ? AND __deleted = 0`).get(t);return r&&Na(r)?r:null}function fv(e,t){let r=Ut(e,t).filter((n)=>n.audience==="public"&&n.desired_state==="active");for(let n of r)gr(e,n.id,"revoked");return r.length}function tg(e,t,r){let n=Ut(e,t).filter((o)=>o.audience==="public"&&o.desired_state==="active");for(let o of n)ao(e,{id:o.id,siteId:o.site_id,audience:"public",hosting:o.hosting,controllerNodeId:o.controller_node_id,targetRef:o.target_ref,canonicalUrl:o.canonical_url,policy:r,desiredState:"active"});return n.length}function pv(e){if(e==null)return null;try{return JSON.parse(e)}catch{return null}}function _v(e,t,r){let n=Ut(e,t).filter((s)=>s.audience==="public"&&s.hosting==="device"&&s.desired_state==="active"&&s.canonical_url!=null),o=0;for(let s of n){let a;try{let u=new URL(s.canonical_url);u.pathname=`/sites/${encodeURIComponent(r)}/`,u.search="",u.hash="",a=u.toString()}catch{continue}ao(e,{id:s.id,siteId:s.site_id,audience:"public",hosting:"device",controllerNodeId:s.controller_node_id,targetRef:s.target_ref,canonicalUrl:a,policy:pv(s.policy_json),desiredState:"active"}),o++}return o}function rg(e,t,r,n){return e.transaction(()=>yr("site.update",()=>{let o=yi(e,t,{...r,visibility:r.visibility==="public"?"private":r.visibility});if(r.visibility==="private")fv(e,t);if(r.visibility==="public")n?.recordPublic?.(o);if(r.name!==void 0)_v(e,t,o.name);return Yt(e,t)}))()}function ng(e,t){return e.transaction(()=>yr("site.delete",()=>{if(!V_(e,t))return!1;return gv(e,t),!0}))()}function gv(e,t){let r=Ut(e,t).filter((n)=>n.desired_state==="active");for(let n of r)gr(e,n.id,"revoked");return r.length}function Rt(e,t){return e.query(`INSERT INTO site_channel_observations
501
+ FROM site_files WHERE site_id = ? AND __deleted = 0 ORDER BY path`).all(t)}function Q_(e,t){let r=t.content??"";if(t.encoding==="utf8")return new TextEncoder().encode(r).byteLength;if(t.encoding==="base64")return Math.floor(r.length/4)*3;return e.query("SELECT size FROM blob_cache WHERE hash = ?").get(r)?.size??null}function yv(e){let t=e.toLowerCase();return t.startsWith("text/")||t.startsWith("application/json")||t.startsWith("application/manifest+json")||t.startsWith("application/xml")||t.startsWith("application/javascript")||t.startsWith("image/svg+xml")}function W_(e){if(typeof e==="string")return new TextEncoder().encode(e);return e instanceof Uint8Array?e:new Uint8Array(e)}function bv(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return btoa(t)}function Y_(e){if(e!=="public"&&e!=="private")throw new Z("invalid_input",`visibility must be "public" or "private", got ${JSON.stringify(e)}`)}function ng(e,t,r){return e.query("SELECT id FROM site_files WHERE site_id = ? AND path = ? ORDER BY created_hlc LIMIT 1").get(t,r)?.id??null}function wv(e,t,r,n,o,s){let a=e.query(`SELECT ${Z_} FROM site_files WHERE site_id = ? AND path = ? AND __deleted = 0 ORDER BY created_hlc LIMIT 1`).get(t,r);if(!a)return null;return a.content_type===n&&a.encoding===o&&a.content===s?a:null}function vv(e,t,r,n,o,s){let a=wv(e,t,r,n,o,s);if(a)return{...a,changed:!1};let u=ng(e,t,r),_=u??Ot("sf",r);return Kt(null,()=>{if(!u){let x=be(e,"site_files",_,"site_id",t);be(e,"site_files",_,"path",r),be(e,"site_files",_,"created_hlc",x.hlc)}be(e,"site_files",_,"content_type",n),be(e,"site_files",_,"encoding",o),be(e,"site_files",_,"content",s),be(e,"site_files",_,"__deleted",0)}),{...e.query(`SELECT ${Z_} FROM site_files WHERE id = ?`).get(_),changed:!0}}function og(e,t,r,n){let o=qa(r);if(!o)throw new Z("invalid_input",`invalid file path: ${JSON.stringify(r)}`);let s=n.contentType??hv(o),a,u;if(yv(s))a="utf8",u=typeof n.data==="string"?n.data:new TextDecoder().decode(W_(n.data));else{let _=W_(n.data);if(_.byteLength>mv)throw new Z("invalid_input","binary too large for inline storage (needs a server-backed blob)");a="base64",u=bv(_)}return vv(e,t,o,s,a,u)}function sg(e){let t=e.query("SELECT site_id, COUNT(*) AS n FROM site_files WHERE __deleted = 0 GROUP BY site_id").all();return new Map(t.map((r)=>[r.site_id,r.n]))}function ag(e,t){return e.query("SELECT COUNT(*) AS n FROM site_files WHERE site_id = ? AND __deleted = 0").get(t).n}var pv,Na,_v,Z_,gv,mv=262144,eg,yi,tg,rg,ig;var vn=De(()=>{Ye();dt();bt();Wr();pv=["id","name","title","created_hlc","visibility","spa","public_grants"],Na=pv.join(", "),_v=["id","site_id","path","content_type","encoding","content"],Z_=_v.join(", "),gv={html:"text/html; charset=utf-8",htm:"text/html; charset=utf-8",css:"text/css; charset=utf-8",js:"text/javascript; charset=utf-8",mjs:"text/javascript; charset=utf-8",json:"application/json; charset=utf-8",svg:"image/svg+xml",txt:"text/plain; charset=utf-8",md:"text/markdown; charset=utf-8",xml:"application/xml; charset=utf-8",webmanifest:"application/manifest+json",ico:"image/x-icon",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",avif:"image/avif",woff:"font/woff",woff2:"font/woff2",ttf:"font/ttf",otf:"font/otf",pdf:"application/pdf",wasm:"application/wasm",mp4:"video/mp4",m4v:"video/mp4",webm:"video/webm",ogv:"video/ogg",mov:"video/quicktime",mkv:"video/x-matroska",mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",oga:"audio/ogg",m4a:"audio/mp4",aac:"audio/aac",flac:"audio/flac",opus:"audio/opus",weba:"audio/webm",csv:"text/csv; charset=utf-8",zip:"application/zip",gz:"application/gzip",tar:"application/x-tar",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",xls:"application/vnd.ms-excel",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",ppt:"application/vnd.ms-powerpoint",pptx:"application/vnd.openxmlformats-officedocument.presentationml.presentation"};eg=ze(function(t,r){let n=Ca(r.name);if(La(t,n))throw new Z("conflict",`site name already exists: ${n}`);if(r.visibility!==void 0)Y_(r.visibility);let o=Ot("site",n),s=be(t,"sites",o,"name",n);if(be(t,"sites",o,"created_hlc",s.hlc),r.title!==void 0)be(t,"sites",o,"title",r.title);if(r.visibility!==void 0)be(t,"sites",o,"visibility",r.visibility);return er(t,o)}),yi=ze(function(t,r,n){if(!er(t,r))throw new Z("not_found",`no such site: ${r}`);if(n.visibility!==void 0)Y_(n.visibility);if(n.name!==void 0){let o=Ca(n.name),s=La(t,o);if(s&&s.id!==r)throw new Z("conflict",`site name already exists: ${o}`);be(t,"sites",r,"name",o)}if(n.title!==void 0)be(t,"sites",r,"title",n.title);if(n.visibility!==void 0)be(t,"sites",r,"visibility",n.visibility);if(n.spa!==void 0)be(t,"sites",r,"spa",n.spa?1:0);return er(t,r)}),tg=ze(function(t,r,n){if(!er(t,r))throw new Z("not_found",`no such site: ${r}`);let o=n==null?null:ai(eo(n));return be(t,"sites",r,"public_grants",o),er(t,r)}),rg=ze(function(t,r){if(!er(t,r))return!1;let n=t.query("SELECT id FROM site_files WHERE site_id = ? AND __deleted = 0").all(r);for(let o of n)be(t,"site_files",o.id,"__deleted",1);return be(t,"sites",r,"__deleted",1),!0});ig=ze(function(t,r,n){let o=ng(t,r,qa(n));if(!o)return!1;let s=t.query("SELECT __deleted AS d FROM site_files WHERE id = ?").get(o);if(!s||s.d)return!1;return be(t,"site_files",o,"__deleted",1),!0})});function $a(e){return(e.audience==="public"||e.audience==="link")&&(e.hosting==="device"||e.hosting==="edge")&&(e.desired_state==="active"||e.desired_state==="revoked")}function jt(e,t){return(t?e.query(`SELECT ${io} FROM site_channels
502
+ WHERE site_id = ? AND __deleted = 0 ORDER BY created_hlc, id`).all(t):e.query(`SELECT ${io} FROM site_channels
503
+ WHERE __deleted = 0 ORDER BY created_hlc, id`).all()).filter($a)}function En(e,t){let r=e.query(`SELECT ${io} FROM site_channels WHERE id = ? AND __deleted = 0`).get(t);return r&&$a(r)?r:null}function Sv(e,t){let r=jt(e,t).filter((n)=>n.audience==="public"&&n.desired_state==="active");for(let n of r)mr(e,n.id,"revoked");return r.length}function cg(e,t,r){let n=jt(e,t).filter((o)=>o.audience==="public"&&o.desired_state==="active");for(let o of n)so(e,{id:o.id,siteId:o.site_id,audience:"public",hosting:o.hosting,controllerNodeId:o.controller_node_id,targetRef:o.target_ref,canonicalUrl:o.canonical_url,policy:r,desiredState:"active"});return n.length}function xv(e){if(e==null)return null;try{return JSON.parse(e)}catch{return null}}function Tv(e,t,r){let n=jt(e,t).filter((s)=>s.audience==="public"&&s.hosting==="device"&&s.desired_state==="active"&&s.canonical_url!=null),o=0;for(let s of n){let a;try{let u=new URL(s.canonical_url);u.pathname=`/sites/${encodeURIComponent(r)}/`,u.search="",u.hash="",a=u.toString()}catch{continue}so(e,{id:s.id,siteId:s.site_id,audience:"public",hosting:"device",controllerNodeId:s.controller_node_id,targetRef:s.target_ref,canonicalUrl:a,policy:xv(s.policy_json),desiredState:"active"}),o++}return o}function lg(e,t,r,n){return e.transaction(()=>Kt("site.update",()=>{let o=yi(e,t,{...r,visibility:r.visibility==="public"?"private":r.visibility});if(r.visibility==="private")Sv(e,t);if(r.visibility==="public")n?.recordPublic?.(o);if(r.name!==void 0)Tv(e,t,o.name);return er(e,t)}))()}function ug(e,t){return e.transaction(()=>Kt("site.delete",()=>{if(!rg(e,t))return!1;return kv(e,t),!0}))()}function kv(e,t){let r=jt(e,t).filter((n)=>n.desired_state==="active");for(let n of r)mr(e,n.id,"revoked");return r.length}function Rt(e,t){return e.query(`INSERT INTO site_channel_observations
488
504
  (channel_id,status,last_verified_at,last_error)
489
505
  VALUES (?,?,?,?)
490
506
  ON CONFLICT(channel_id) DO UPDATE SET
491
507
  status=excluded.status,
492
508
  last_verified_at=excluded.last_verified_at,
493
- last_error=excluded.last_error`).run(t.channelId,t.status,t.lastVerifiedAt??null,t.lastError??null),{channelId:t.channelId,status:t.status,lastVerifiedAt:t.lastVerifiedAt??null,lastError:t.lastError??null}}function og(e,t){e.query("DELETE FROM site_channel_observations WHERE channel_id = ?").run(t)}function bi(e,t){let r=e.query(`SELECT channel_id,status,last_verified_at,last_error
494
- FROM site_channel_observations WHERE channel_id = ?`).get(t);return r?{channelId:r.channel_id,status:r.status,lastVerifiedAt:r.last_verified_at,lastError:r.last_error}:null}function qa(e,t){let r=We(e);return Ut(e,t).map((n)=>{let o=bi(e,n.id),s;if(n.desired_state==="active")s=o?.status??"unverified";else if(n.hosting==="device"&&n.target_ref===r)s="revoked";else if(o?.status==="revoked"||o?.status==="cleanup_pending"||o?.status==="rollback_pending"||o?.status==="error")s=o.status;else s=n.controller_node_id===r?"cleanup_pending":"waiting_controller";return{id:n.id,siteId:n.site_id,audience:n.audience,hosting:n.hosting,controllerNodeId:n.controller_node_id,targetRef:n.target_ref,canonicalUrl:n.canonical_url,policyJson:n.policy_json,desiredState:n.desired_state,status:s,lastVerifiedAt:o?.lastVerifiedAt??null,lastError:o?.lastError??null}})}function ig(e,t){let r=e.query(`SELECT ${so} FROM site_channels
495
- WHERE site_id = ? AND audience = 'public' AND __deleted = 0 ORDER BY created_hlc, id`).all(t.id);if(r.length===0){let a=M_(t);return{serving:a,configured:a,anomaly:null}}let n=r.filter(Na),o=n.filter((a)=>a.desired_state==="active"),s=We(e);return{serving:o.some((a)=>a.hosting==="device"&&a.target_ref===s),configured:o.length>0,anomaly:r.length>n.length?"malformed_public_channel":null}}var dv,so,ao,gr;var co=De(()=>{dt();Ye();wt();Gt();En();dv=["id","site_id","audience","hosting","controller_node_id","target_ref","canonical_url","policy_json","desired_state","created_hlc","__deleted"],so=dv.join(", ");ao=Fe(function(t,r){if(!Yt(t,r.siteId))throw new Z("not_found",`no such site: ${r.siteId}`);let n=r.controllerNodeId??We(t),o=r.id?Sn(t,r.id):t.query(`SELECT ${so} FROM site_channels
509
+ last_error=excluded.last_error`).run(t.channelId,t.status,t.lastVerifiedAt??null,t.lastError??null),{channelId:t.channelId,status:t.status,lastVerifiedAt:t.lastVerifiedAt??null,lastError:t.lastError??null}}function dg(e,t){e.query("DELETE FROM site_channel_observations WHERE channel_id = ?").run(t)}function bi(e,t){let r=e.query(`SELECT channel_id,status,last_verified_at,last_error
510
+ FROM site_channel_observations WHERE channel_id = ?`).get(t);return r?{channelId:r.channel_id,status:r.status,lastVerifiedAt:r.last_verified_at,lastError:r.last_error}:null}function Fa(e,t){let r=je(e);return jt(e,t).map((n)=>{let o=bi(e,n.id),s;if(n.desired_state==="active")s=o?.status??"unverified";else if(n.hosting==="device"&&n.target_ref===r)s="revoked";else if(o?.status==="revoked"||o?.status==="cleanup_pending"||o?.status==="rollback_pending"||o?.status==="error")s=o.status;else s=n.controller_node_id===r?"cleanup_pending":"waiting_controller";return{id:n.id,siteId:n.site_id,audience:n.audience,hosting:n.hosting,controllerNodeId:n.controller_node_id,targetRef:n.target_ref,canonicalUrl:n.canonical_url,policyJson:n.policy_json,desiredState:n.desired_state,status:s,lastVerifiedAt:o?.lastVerifiedAt??null,lastError:o?.lastError??null}})}function fg(e,t){let r=e.query(`SELECT ${io} FROM site_channels
511
+ WHERE site_id = ? AND audience = 'public' AND __deleted = 0 ORDER BY created_hlc, id`).all(t.id);if(r.length===0){let a=G_(t);return{serving:a,configured:a,anomaly:null}}let n=r.filter($a),o=n.filter((a)=>a.desired_state==="active"),s=je(e);return{serving:o.some((a)=>a.hosting==="device"&&a.target_ref===s),configured:o.length>0,anomaly:r.length>n.length?"malformed_public_channel":null}}var Ev,io,so,mr;var ao=De(()=>{dt();Ye();bt();Gt();vn();Ev=["id","site_id","audience","hosting","controller_node_id","target_ref","canonical_url","policy_json","desired_state","created_hlc","__deleted"],io=Ev.join(", ");so=ze(function(t,r){if(!er(t,r.siteId))throw new Z("not_found",`no such site: ${r.siteId}`);let n=r.controllerNodeId??je(t),o=r.id?En(t,r.id):t.query(`SELECT ${io} FROM site_channels
496
512
  WHERE site_id = ? AND audience = ? AND hosting = ? AND target_ref = ?
497
513
  AND __deleted = 0
498
- ORDER BY created_hlc LIMIT 1`).get(r.siteId,r.audience,r.hosting,r.targetRef),s=o?.id??Ot("chan",`${r.audience}-${r.hosting}-${r.siteId}`,"channel"),a={audience:r.audience,hosting:r.hosting,controller_node_id:n,target_ref:r.targetRef,canonical_url:r.canonicalUrl??null,policy_json:r.policy==null?null:JSON.stringify(r.policy),desired_state:r.desiredState??"active"};return t.transaction(()=>{if(!o){let u=we(t,"site_channels",s,"site_id",r.siteId);we(t,"site_channels",s,"created_hlc",u.hlc)}for(let[u,_]of Object.entries(a)){if(o&&o[u]===_)continue;we(t,"site_channels",s,u,_)}})(),Sn(t,s)}),gr=Fe(function(t,r,n){if(!Sn(t,r))throw new Z("not_found",`no such site channel: ${r}`);return we(t,"site_channels",r,"desired_state",n),Sn(t,r)})});async function xn(e){try{return await hv(e),null}catch(t){let r=t instanceof Error?t.message:String(t);return console.error(`site channel reconcile failed: ${r}`),r}}async function hv(e){let t=We(e),r=Ut(e),n=new Set;for(let s of r){if(s.desired_state!=="active")continue;if(B_(e,s.site_id)==="tombstoned"){gr(e,s.id,"revoked"),n.add(s.id);continue}if(s.audience!=="link"||s.controller_node_id!==t)continue;if(!or(e,s.target_ref))Rt(e,{channelId:s.id,status:"error",lastError:`${sg}: 本机缺少该链接的凭据记录`});else if(bi(e,s.id)?.lastError?.startsWith(sg))og(e,s.id)}let o=r.map((s)=>n.has(s.id)?Sn(e,s.id)??s:s).filter((s)=>s.controller_node_id===t&&s.desired_state==="revoked"&&s.audience==="link"&&!(s.hosting==="edge"&&bi(e,s.id)?.status==="revoked"));for(let s of o){let a=or(e,s.target_ref);try{if(s.hosting==="edge"){await Promise.resolve().then(() => mi());let _=await oo(e,s.target_ref);if(_==="cleanup_pending"){Rt(e,{channelId:s.id,status:"cleanup_pending",lastError:"Edge 尚未确认销毁 Room"});continue}if(_==="absent"){Rt(e,{channelId:s.id,status:"cleanup_pending",lastError:"Edge Room 记录缺失,销毁未确认"});continue}}else if(!a){Rt(e,{channelId:s.id,status:"revoked",lastVerifiedAt:Date.now()});continue}if(a)Qt(e,a.slug);Rt(e,{channelId:s.id,status:"revoked",lastVerifiedAt:Date.now()})}catch(u){Rt(e,{channelId:s.id,status:"cleanup_pending",lastError:u instanceof Error?u.message:String(u)})}}}var sg="controller_state_missing";var La=De(()=>{Gt();co();vn();En()});function jt(e){return e.query(`SELECT ${lg} FROM peers ORDER BY url`).all()}function Et(e,t){return e.query(`SELECT ${lg} FROM peers WHERE url = ?`).get(t)??null}function ug(e,t){e.query(`INSERT INTO peers (url, token, label, node_id, enabled, pull_cursor, push_cursor)
514
+ ORDER BY created_hlc LIMIT 1`).get(r.siteId,r.audience,r.hosting,r.targetRef),s=o?.id??Ot("chan",`${r.audience}-${r.hosting}-${r.siteId}`,"channel"),a={audience:r.audience,hosting:r.hosting,controller_node_id:n,target_ref:r.targetRef,canonical_url:r.canonicalUrl??null,policy_json:r.policy==null?null:JSON.stringify(r.policy),desired_state:r.desiredState??"active"};return t.transaction(()=>{if(!o){let u=be(t,"site_channels",s,"site_id",r.siteId);be(t,"site_channels",s,"created_hlc",u.hlc)}for(let[u,_]of Object.entries(a)){if(o&&o[u]===_)continue;be(t,"site_channels",s,u,_)}})(),En(t,s)}),mr=ze(function(t,r,n){if(!En(t,r))throw new Z("not_found",`no such site channel: ${r}`);return be(t,"site_channels",r,"desired_state",n),En(t,r)})});async function Sn(e){try{return await Rv(e),null}catch(t){let r=t instanceof Error?t.message:String(t);return console.error(`site channel reconcile failed: ${r}`),r}}async function Rv(e){let t=je(e),r=jt(e),n=new Set;for(let s of r){if(s.desired_state!=="active")continue;if(K_(e,s.site_id)==="tombstoned"){mr(e,s.id,"revoked"),n.add(s.id);continue}if(s.audience!=="link"||s.controller_node_id!==t)continue;if(!sr(e,s.target_ref))Rt(e,{channelId:s.id,status:"error",lastError:`${pg}: 本机缺少该链接的凭据记录`});else if(bi(e,s.id)?.lastError?.startsWith(pg))dg(e,s.id)}let o=r.map((s)=>n.has(s.id)?En(e,s.id)??s:s).filter((s)=>s.controller_node_id===t&&s.desired_state==="revoked"&&s.audience==="link"&&!(s.hosting==="edge"&&bi(e,s.id)?.status==="revoked"));for(let s of o){let a=sr(e,s.target_ref);try{if(s.hosting==="edge"){await Promise.resolve().then(() => mi());let _=await no(e,s.target_ref);if(_==="cleanup_pending"){Rt(e,{channelId:s.id,status:"cleanup_pending",lastError:"Edge 尚未确认销毁 Room"});continue}if(_==="absent"){Rt(e,{channelId:s.id,status:"cleanup_pending",lastError:"Edge Room 记录缺失,销毁未确认"});continue}}else if(!a){Rt(e,{channelId:s.id,status:"revoked",lastVerifiedAt:Date.now()});continue}if(a)Yt(e,a.slug);Rt(e,{channelId:s.id,status:"revoked",lastVerifiedAt:Date.now()})}catch(u){Rt(e,{channelId:s.id,status:"cleanup_pending",lastError:u instanceof Error?u.message:String(u)})}}}var pg="controller_state_missing";var za=De(()=>{Gt();ao();wn();vn()});function Ht(e){return e.query(`SELECT ${hg} FROM peers ORDER BY url`).all()}function vt(e,t){return e.query(`SELECT ${hg} FROM peers WHERE url = ?`).get(t)??null}function mg(e,t){e.query(`INSERT INTO peers (url, token, label, node_id, enabled, pull_cursor, push_cursor)
499
515
  VALUES (?, ?, ?, ?, 1, 0, 0)
500
516
  ON CONFLICT(url) DO UPDATE SET
501
517
  token = coalesce(excluded.token, peers.token),
502
518
  label = coalesce(excluded.label, peers.label),
503
519
  node_id = coalesce(excluded.node_id, peers.node_id),
504
- enabled = 1`).run(t.url,t.token??null,t.label??null,t.node_id??null)}function dg(e,t){e.query(`INSERT INTO peers (url, kind, config, label, enabled, pull_cursor, push_cursor)
520
+ enabled = 1`).run(t.url,t.token??null,t.label??null,t.node_id??null)}function yg(e,t){e.query(`INSERT INTO peers (url, kind, config, label, enabled, pull_cursor, push_cursor)
505
521
  VALUES (?, 's3', ?, ?, 1, 0, 0)
506
522
  ON CONFLICT(url) DO UPDATE SET
507
523
  kind = 's3',
508
524
  config = excluded.config,
509
525
  label = coalesce(excluded.label, peers.label),
510
- enabled = 1`).run(t.url,JSON.stringify(t.config),t.label??null)}function Aa(e,t){e.query(`INSERT INTO peers (url, kind, config, label, enabled, pull_cursor, push_cursor)
526
+ enabled = 1`).run(t.url,JSON.stringify(t.config),t.label??null)}function Ia(e,t){e.query(`INSERT INTO peers (url, kind, config, label, enabled, pull_cursor, push_cursor)
511
527
  VALUES (?, 'room', ?, ?, 1, 0, 0)
512
528
  ON CONFLICT(url) DO UPDATE SET
513
529
  kind = 'room',
514
530
  config = excluded.config,
515
531
  label = coalesce(excluded.label, peers.label),
516
- enabled = 1`).run(t.url,JSON.stringify(t.config),t.label??null)}function vt(e,t){return e.transaction(()=>{let n=e.query("DELETE FROM peers WHERE url = ?").run(t).changes>0;return e.query("DELETE FROM peer_grants WHERE peer_url = ?").run(t),e.query("DELETE FROM storage_cursors WHERE peer_url = ?").run(t),e.query("DELETE FROM room_rows WHERE peer_key = ?").run(t),n})()}function cg(e,t,r,n){let o=Date.now();if(r==="ok"){e.query("UPDATE peers SET last_sync_at = ?, last_success_at = ?, last_status = ?, last_error = ? WHERE url = ?").run(o,o,r,n??null,t);return}e.query("UPDATE peers SET last_sync_at = ?, last_status = ?, last_error = ? WHERE url = ?").run(o,r,n??null,t)}async function $a(e,t,r){let n=ag.get(e);if(!n)n=new Map,ag.set(e,n);let o=n.get(t);if(o)return o;let s=bv(e,t,r).finally(()=>{if(n.get(t)===s)n.delete(t)});return n.set(t,s),s}function mv(e,t){if(!t)return null;if(t.capabilities&&!t.capabilities.includes("site_channels"))return"对端未升级(不支持站点渠道):站点发布/分享的变更在它升级前不会生效";if(t.version&&t.version!==e)return`对端运行 core ${t.version},本机为 ${e};混合版本工作区的新功能可能不生效`;return null}async function yv(e){try{let t=await fetch(new URL(Mp,e),{signal:AbortSignal.timeout(5000)});if(!t.ok)return null;let r=zp.safeParse(await t.json());return r.success?r.data:null}catch{return null}}async function bv(e,t,r){try{let n=Et(e,t),o;if(n?.kind==="s3"){if(!n.config)throw Error(`storage peer ${t} has no config`);let _=JSON.parse(n.config),m={...r?.storage,publish:r?.storage?.publish??_.publish,priority:r?.storage?.priority??_.priority};o=await l_(e,t,Bt(_),_,m)}else if(n?.kind==="room"){await Promise.resolve().then(() => mi());o=await hi(e,n)}else o=await ii(e,t,{timeoutMs:r?.timeoutMs});cg(e,t,"ok",null);let s=[];try{if(n?.kind!=="s3"&&n?.kind!=="room")f_(e,t)}catch(_){s.push(`site rollback bookkeeping failed: ${_.message}`)}if(n?.kind!=="s3"&&n?.kind!=="room"){let _=mv(__.version,await yv(t));if(_)s.push(`${t}: ${_}`)}await Promise.resolve().then(() => La());let u=await xn(e);if(u)s.push(`site channel reconcile failed: ${u}`);return{url:t,ok:!0,pushed:o.pushed,pulled:o.pulled,pendingPush:o.pendingPush,...s.length?{warnings:s}:{}}}catch(n){let o=n.message;return cg(e,t,"error",o),{url:t,ok:!1,error:o}}}var lg="url, pull_cursor, push_cursor, token, label, node_id, enabled, last_sync_at, last_success_at, last_status, last_error, kind, config",ag;var io=De(()=>{Ye();ra();Fn();wn();u_();d_();Qn();oi();p_();Fn();ag=new WeakMap});class Ba{constructor({accessKeyId:e,secretAccessKey:t,sessionToken:r,service:n,region:o,cache:s,retries:a,initRetryMs:u}){if(e==null)throw TypeError("accessKeyId is a required option");if(t==null)throw TypeError("secretAccessKey is a required option");this.accessKeyId=e,this.secretAccessKey=t,this.sessionToken=r,this.service=n,this.region=o,this.cache=s||new Map,this.retries=a!=null?a:10,this.initRetryMs=u||50}async sign(e,t){if(e instanceof Request){let{method:o,url:s,headers:a,body:u}=e;if(t=Object.assign({method:o,url:s,headers:a},t),t.body==null&&a.has("Content-Type"))t.body=u!=null&&a.has("X-Amz-Content-Sha256")?u:await e.clone().arrayBuffer();e=s}let r=new bg(Object.assign({url:e.toString()},t,this,t&&t.aws)),n=Object.assign({},t,await r.sign());delete n.aws;try{return new Request(n.url.toString(),n)}catch(o){if(o instanceof TypeError)return new Request(n.url.toString(),Object.assign({duplex:"half"},n));throw o}}async fetch(e,t){for(let r=0;r<=this.retries;r++){let n=fetch(await this.sign(e,t));if(r===this.retries)return n;let o=await n;if(o.status<500&&o.status!==429)return o;await new Promise((s)=>setTimeout(s,Math.random()*this.initRetryMs*Math.pow(2,r)))}throw Error("An unknown error occurred, ensure retries is not negative")}}class bg{constructor({method:e,url:t,headers:r,body:n,accessKeyId:o,secretAccessKey:s,sessionToken:a,service:u,region:_,cache:m,datetime:x,signQuery:D,appendSessionToken:j,allHeaders:Y,singleEncode:_e}){if(t==null)throw TypeError("url is a required option");if(o==null)throw TypeError("accessKeyId is a required option");if(s==null)throw TypeError("secretAccessKey is a required option");this.method=e||(n?"POST":"GET"),this.url=new URL(t),this.headers=new Headers(r||{}),this.body=n,this.accessKeyId=o,this.secretAccessKey=s,this.sessionToken=a;let de,ge;if(!u||!_)[de,ge]=Sv(this.url,this.headers);if(this.service=u||de||"",this.region=_||ge||"us-east-1",this.cache=m||new Map,this.datetime=x||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=D,this.appendSessionToken=j||this.service==="iotdevicegateway",this.headers.delete("Host"),this.service==="s3"&&!this.signQuery&&!this.headers.has("X-Amz-Content-Sha256"))this.headers.set("X-Amz-Content-Sha256","UNSIGNED-PAYLOAD");let Le=this.signQuery?this.url.searchParams:this.headers;if(Le.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken)Le.set("X-Amz-Security-Token",this.sessionToken);if(this.signableHeaders=["host",...this.headers.keys()].filter(($e)=>Y||!Ev.has($e)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map(($e)=>$e+":"+($e==="host"?this.url.host:(this.headers.get($e)||"").replace(/\s+/g," "))).join(`
517
- `),this.credentialString=[this.datetime.slice(0,8),this.region,this.service,"aws4_request"].join("/"),this.signQuery){if(this.service==="s3"&&!Le.has("X-Amz-Expires"))Le.set("X-Amz-Expires","86400");Le.set("X-Amz-Algorithm","AWS4-HMAC-SHA256"),Le.set("X-Amz-Credential",this.accessKeyId+"/"+this.credentialString),Le.set("X-Amz-SignedHeaders",this.signedHeaders)}if(this.service==="s3")try{this.encodedPath=decodeURIComponent(this.url.pathname.replace(/\+/g," "))}catch($e){this.encodedPath=this.url.pathname}else this.encodedPath=this.url.pathname.replace(/\/+/g,"/");if(!_e)this.encodedPath=encodeURIComponent(this.encodedPath).replace(/%2F/g,"/");this.encodedPath=yg(this.encodedPath);let Ze=new Set;this.encodedSearch=[...this.url.searchParams].filter(([$e])=>{if(!$e)return!1;if(this.service==="s3"){if(Ze.has($e))return!1;Ze.add($e)}return!0}).map(($e)=>$e.map((Ue)=>yg(encodeURIComponent(Ue)))).sort(([$e,Ue],[tt,Rr])=>$e<tt?-1:$e>tt?1:Ue<Rr?-1:Ue>Rr?1:0).map(($e)=>$e.join("=")).join("&")}async sign(){if(this.signQuery){if(this.url.searchParams.set("X-Amz-Signature",await this.signature()),this.sessionToken&&this.appendSessionToken)this.url.searchParams.set("X-Amz-Security-Token",this.sessionToken)}else this.headers.set("Authorization",await this.authHeader());return{method:this.method,url:this.url,headers:this.headers,body:this.body}}async authHeader(){return["AWS4-HMAC-SHA256 Credential="+this.accessKeyId+"/"+this.credentialString,"SignedHeaders="+this.signedHeaders,"Signature="+await this.signature()].join(", ")}async signature(){let e=this.datetime.slice(0,8),t=[this.secretAccessKey,e,this.region,this.service].join(),r=this.cache.get(t);if(!r){let n=await lo("AWS4"+this.secretAccessKey,e),o=await lo(n,this.region),s=await lo(o,this.service);r=await lo(s,"aws4_request"),this.cache.set(t,r)}return Fa(await lo(r,await this.stringToSign()))}async stringToSign(){return["AWS4-HMAC-SHA256",this.datetime,this.credentialString,Fa(await hg(await this.canonicalString()))].join(`
532
+ enabled = 1`).run(t.url,JSON.stringify(t.config),t.label??null)}function wt(e,t){return e.transaction(()=>{let n=e.query("DELETE FROM peers WHERE url = ?").run(t).changes>0;return e.query("DELETE FROM peer_grants WHERE peer_url = ?").run(t),e.query("DELETE FROM storage_cursors WHERE peer_url = ?").run(t),e.query("DELETE FROM room_rows WHERE peer_key = ?").run(t),n})()}function gg(e,t,r,n){let o=Date.now();if(r==="ok"){e.query("UPDATE peers SET last_sync_at = ?, last_success_at = ?, last_status = ?, last_error = ? WHERE url = ?").run(o,o,r,n??null,t);return}e.query("UPDATE peers SET last_sync_at = ?, last_status = ?, last_error = ? WHERE url = ?").run(o,r,n??null,t)}async function Ma(e,t,r){let n=_g.get(e);if(!n)n=new Map,_g.set(e,n);let o=n.get(t);if(o)return o;let s=Ov(e,t,r).finally(()=>{if(n.get(t)===s)n.delete(t)});return n.set(t,s),s}function Av(e,t){if(!t)return null;if(t.capabilities&&!t.capabilities.includes("site_channels"))return"对端未升级(不支持站点渠道):站点发布/分享的变更在它升级前不会生效";if(t.version&&t.version!==e)return`对端运行 core ${t.version},本机为 ${e};混合版本工作区的新功能可能不生效`;return null}async function Dv(e){try{let t=await fetch(new URL(Gp,e),{signal:AbortSignal.timeout(5000)});if(!t.ok)return null;let r=Wp.safeParse(await t.json());return r.success?r.data:null}catch{return null}}async function Ov(e,t,r){try{let n=vt(e,t),o;if(n?.kind==="s3"){if(!n.config)throw Error(`storage peer ${t} has no config`);let _=JSON.parse(n.config),m={...r?.storage,publish:r?.storage?.publish??_.publish,priority:r?.storage?.priority??_.priority};o=await h_(e,t,Ut(_),_,m)}else if(n?.kind==="room"){await Promise.resolve().then(() => mi());o=await hi(e,n)}else o=await ii(e,t,{timeoutMs:r?.timeoutMs});gg(e,t,"ok",null);let s=[];try{if(n?.kind!=="s3"&&n?.kind!=="room")b_(e,t)}catch(_){s.push(`site rollback bookkeeping failed: ${_.message}`)}if(n?.kind!=="s3"&&n?.kind!=="room"){let _=Av(v_.version,await Dv(t));if(_)s.push(`${t}: ${_}`)}await Promise.resolve().then(() => za());let u=await Sn(e);if(u)s.push(`site channel reconcile failed: ${u}`);return{url:t,ok:!0,pushed:o.pushed,pulled:o.pulled,pendingPush:o.pendingPush,...s.length?{warnings:s}:{}}}catch(n){let o=n.message;return gg(e,t,"error",o),{url:t,ok:!1,error:o}}}var hg="url, pull_cursor, push_cursor, token, label, node_id, enabled, last_sync_at, last_success_at, last_status, last_error, kind, config",_g;var oo=De(()=>{Ye();ia();Fn();bn();m_();y_();Xn();oi();w_();Fn();_g=new WeakMap});class Ha{constructor({accessKeyId:e,secretAccessKey:t,sessionToken:r,service:n,region:o,cache:s,retries:a,initRetryMs:u}){if(e==null)throw TypeError("accessKeyId is a required option");if(t==null)throw TypeError("secretAccessKey is a required option");this.accessKeyId=e,this.secretAccessKey=t,this.sessionToken=r,this.service=n,this.region=o,this.cache=s||new Map,this.retries=a!=null?a:10,this.initRetryMs=u||50}async sign(e,t){if(e instanceof Request){let{method:o,url:s,headers:a,body:u}=e;if(t=Object.assign({method:o,url:s,headers:a},t),t.body==null&&a.has("Content-Type"))t.body=u!=null&&a.has("X-Amz-Content-Sha256")?u:await e.clone().arrayBuffer();e=s}let r=new kg(Object.assign({url:e.toString()},t,this,t&&t.aws)),n=Object.assign({},t,await r.sign());delete n.aws;try{return new Request(n.url.toString(),n)}catch(o){if(o instanceof TypeError)return new Request(n.url.toString(),Object.assign({duplex:"half"},n));throw o}}async fetch(e,t){for(let r=0;r<=this.retries;r++){let n=fetch(await this.sign(e,t));if(r===this.retries)return n;let o=await n;if(o.status<500&&o.status!==429)return o;await new Promise((s)=>setTimeout(s,Math.random()*this.initRetryMs*Math.pow(2,r)))}throw Error("An unknown error occurred, ensure retries is not negative")}}class kg{constructor({method:e,url:t,headers:r,body:n,accessKeyId:o,secretAccessKey:s,sessionToken:a,service:u,region:_,cache:m,datetime:x,signQuery:D,appendSessionToken:j,allHeaders:Y,singleEncode:_e}){if(t==null)throw TypeError("url is a required option");if(o==null)throw TypeError("accessKeyId is a required option");if(s==null)throw TypeError("secretAccessKey is a required option");this.method=e||(n?"POST":"GET"),this.url=new URL(t),this.headers=new Headers(r||{}),this.body=n,this.accessKeyId=o,this.secretAccessKey=s,this.sessionToken=a;let de,ge;if(!u||!_)[de,ge]=Cv(this.url,this.headers);if(this.service=u||de||"",this.region=_||ge||"us-east-1",this.cache=m||new Map,this.datetime=x||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=D,this.appendSessionToken=j||this.service==="iotdevicegateway",this.headers.delete("Host"),this.service==="s3"&&!this.signQuery&&!this.headers.has("X-Amz-Content-Sha256"))this.headers.set("X-Amz-Content-Sha256","UNSIGNED-PAYLOAD");let Le=this.signQuery?this.url.searchParams:this.headers;if(Le.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken)Le.set("X-Amz-Security-Token",this.sessionToken);if(this.signableHeaders=["host",...this.headers.keys()].filter(($e)=>Y||!Nv.has($e)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map(($e)=>$e+":"+($e==="host"?this.url.host:(this.headers.get($e)||"").replace(/\s+/g," "))).join(`
533
+ `),this.credentialString=[this.datetime.slice(0,8),this.region,this.service,"aws4_request"].join("/"),this.signQuery){if(this.service==="s3"&&!Le.has("X-Amz-Expires"))Le.set("X-Amz-Expires","86400");Le.set("X-Amz-Algorithm","AWS4-HMAC-SHA256"),Le.set("X-Amz-Credential",this.accessKeyId+"/"+this.credentialString),Le.set("X-Amz-SignedHeaders",this.signedHeaders)}if(this.service==="s3")try{this.encodedPath=decodeURIComponent(this.url.pathname.replace(/\+/g," "))}catch($e){this.encodedPath=this.url.pathname}else this.encodedPath=this.url.pathname.replace(/\/+/g,"/");if(!_e)this.encodedPath=encodeURIComponent(this.encodedPath).replace(/%2F/g,"/");this.encodedPath=Tg(this.encodedPath);let Ze=new Set;this.encodedSearch=[...this.url.searchParams].filter(([$e])=>{if(!$e)return!1;if(this.service==="s3"){if(Ze.has($e))return!1;Ze.add($e)}return!0}).map(($e)=>$e.map((Ue)=>Tg(encodeURIComponent(Ue)))).sort(([$e,Ue],[tt,Rr])=>$e<tt?-1:$e>tt?1:Ue<Rr?-1:Ue>Rr?1:0).map(($e)=>$e.join("=")).join("&")}async sign(){if(this.signQuery){if(this.url.searchParams.set("X-Amz-Signature",await this.signature()),this.sessionToken&&this.appendSessionToken)this.url.searchParams.set("X-Amz-Security-Token",this.sessionToken)}else this.headers.set("Authorization",await this.authHeader());return{method:this.method,url:this.url,headers:this.headers,body:this.body}}async authHeader(){return["AWS4-HMAC-SHA256 Credential="+this.accessKeyId+"/"+this.credentialString,"SignedHeaders="+this.signedHeaders,"Signature="+await this.signature()].join(", ")}async signature(){let e=this.datetime.slice(0,8),t=[this.secretAccessKey,e,this.region,this.service].join(),r=this.cache.get(t);if(!r){let n=await co("AWS4"+this.secretAccessKey,e),o=await co(n,this.region),s=await co(o,this.service);r=await co(s,"aws4_request"),this.cache.set(t,r)}return Ua(await co(r,await this.stringToSign()))}async stringToSign(){return["AWS4-HMAC-SHA256",this.datetime,this.credentialString,Ua(await Sg(await this.canonicalString()))].join(`
518
534
  `)}async canonicalString(){return[this.method.toUpperCase(),this.encodedPath,this.encodedSearch,this.canonicalHeaders+`
519
535
  `,this.signedHeaders,await this.hexBodyHash()].join(`
520
- `)}async hexBodyHash(){let e=this.headers.get("X-Amz-Content-Sha256")||(this.service==="s3"&&this.signQuery?"UNSIGNED-PAYLOAD":null);if(e==null){if(this.body&&typeof this.body!=="string"&&!("byteLength"in this.body))throw Error("body must be a string, ArrayBuffer or ArrayBufferView, unless you include the X-Amz-Content-Sha256 header");e=Fa(await hg(this.body||""))}return e}}async function lo(e,t){let r=await crypto.subtle.importKey("raw",typeof e==="string"?Ma.encode(e):e,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return crypto.subtle.sign("HMAC",r,Ma.encode(t))}async function hg(e){return crypto.subtle.digest("SHA-256",typeof e==="string"?Ma.encode(e):e)}function Fa(e){let t=new Uint8Array(e),r="";for(let n=0;n<t.length;n++){let o=t[n];r+=mg[o>>>4&15],r+=mg[o&15]}return r}function yg(e){return e.replace(/[!'()*]/g,(t)=>"%"+t.charCodeAt(0).toString(16).toUpperCase())}function Sv(e,t){let{hostname:r,pathname:n}=e;if(r.endsWith(".on.aws")){let u=r.match(/^[^.]{1,63}\.lambda-url\.([^.]{1,63})\.on\.aws$/);return u!=null?["lambda",u[1]||""]:["",""]}if(r.endsWith(".r2.cloudflarestorage.com"))return["s3","auto"];if(r.endsWith(".backblazeb2.com")){let u=r.match(/^(?:[^.]{1,63}\.)?s3\.([^.]{1,63})\.backblazeb2\.com$/);return u!=null?["s3",u[1]||""]:["",""]}let o=r.replace("dualstack.","").match(/([^.]{1,63})\.(?:([^.]{0,63})\.)?amazonaws\.com(?:\.cn)?$/),s=o&&o[1]||"",a=o&&o[2];if(a==="us-gov")a="us-gov-west-1";else if(a==="s3"||a==="s3-accelerate")a="us-east-1",s="s3";else if(s==="iot")if(r.startsWith("iot."))s="execute-api";else if(r.startsWith("data.jobs.iot."))s="iot-jobs-data";else s=n==="/mqtt"?"iotdevicegateway":"iotdata";else if(s==="autoscaling"){let u=(t.get("X-Amz-Target")||"").split(".")[0];if(u==="AnyScaleFrontendService")s="application-autoscaling";else if(u==="AnyScaleScalingPlannerFrontendService")s="autoscaling-plans"}else if(a==null&&s.startsWith("s3-"))a=s.slice(3).replace(/^fips-|^external-1/,""),s="s3";else if(s.endsWith("-fips"))s=s.slice(0,-5);else if(a&&/-\d$/.test(s)&&!/-\d$/.test(a))[s,a]=[a,s];return[vv[s]||s,a||""]}var Ma,vv,Ev,mg;var wg=De(()=>{Ma=new TextEncoder,vv={appstream2:"appstream",cloudhsmv2:"cloudhsm",email:"ses",marketplace:"aws-marketplace",mobile:"AWSMobileHubService",pinpoint:"mobiletargeting",queue:"sqs","git-codecommit":"codecommit","mturk-requester-sandbox":"mturk-requester","personalize-runtime":"personalize"},Ev=new Set(["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"]);mg=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"]});function Ua(e){return new Ba({accessKeyId:e.accessKeyId,secretAccessKey:e.secretAccessKey,region:e.region||"auto",service:"s3"})}function ja(e){let t=new URL(e.endpoint).origin;return Yp(e)?t:`${t}/${e.bucket}`}function Ha(e,t){return`${ja(e)}/${t.split("/").map(encodeURIComponent).join("/")}`}async function uo(e,t,r){let n=Ua(e),o=new URL(Ha(e,t));return o.searchParams.set("X-Amz-Expires",String(Math.min(Math.max(1,Math.floor(r)),Tn))),(await n.sign(o.toString(),{method:"GET",aws:{signQuery:!0}})).url}var Tn=604800;var wi=De(()=>{wg();wn()});function Wv(e,t){let r=e.query("SELECT value FROM meta WHERE key = ?").get(t);return r?r.value:null}function rc(e,t,r){if(r===null){e.query("DELETE FROM meta WHERE key = ?").run(t);return}e.query("INSERT INTO meta (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(t,r)}function Ti(e){let t=Wv(e,"edge_config");if(!t)return null;try{let r=JSON.parse(t);if(!r||typeof r.endpoint!=="string"||typeof r.token!=="string")return null;if(r.cf&&"apiToken"in r.cf)delete r.cf.apiToken,rc(e,"edge_config",JSON.stringify(r));if(!Array.isArray(r.capabilities))r.capabilities=r.cf?["inbox","room"]:["inbox"],rc(e,"edge_config",JSON.stringify(r));return r}catch{return null}}function nc(e,t){if(t?.cf&&"apiToken"in t.cf)throw Error("Cloudflare API token must not be persisted");let r=t?{...t,capabilities:t.capabilities??(t.cf?["inbox","room"]:["inbox"])}:null;rc(e,"edge_config",r?JSON.stringify(r):null)}function fo(e){return e.capabilities??(e.cf?["inbox","room"]:["inbox"])}var Tr="3";function po(e){let t=(e||"").replace(/^\/+|\/+$/g,"");return t?`${t}/shares`:"shares"}function Xg(e){let t=new Set,r=/\/blob\/([0-9a-f]{16,64})/g,n;while(n=r.exec(e))t.add(n[1].toLowerCase());return[...t]}function eh(e,t){let r=new TextEncoder().encode(JSON.stringify(t));return e.encrypt&&e.masterKey?pr(Xt(e.masterKey),r):Promise.resolve(r)}async function ic(e,t){let n=await Bt(e).get(oc(po(e.prefix),t)).catch(()=>null);if(!n)return null;try{let o=e.encrypt&&e.masterKey?await Hr(Xt(e.masterKey),n):n;return JSON.parse(new TextDecoder().decode(o))}catch{return null}}async function Gv(e,t){let r=Bt(t.config),n=po(t.config.prefix),o={v:1,kind:t.kind,title:""},s=[];if(t.kind==="doc"){let m=nt(e,t.targetId);if(!m)throw new Z("not_found",`no such document: ${t.targetId}`);o.title=m.title,o.body=m.body??"",s=Xg(o.body)}else{let m=Pt(e,t.targetId);if(!m)throw new Z("not_found",`no such database: ${t.targetId}`);o.title=m.name;let x=Nt(e,t.targetId).sort((j,Y)=>j.position-Y.position);o.properties=x.map((j)=>({id:j.id,name:j.name,type:j.type}));let D=un(e,t.targetId);o.records=D.map((j)=>({cells:j.cells})),s=Xg(JSON.stringify(D.map((j)=>j.cells)))}let a=[],u={};if(s.length>0&&!Ol())throw new Z("network","no blob-bytes resolver is registered for this runtime");for(let m of s){let x=await Dl(e,m);if(!x)continue;let D=Yg(n,t.slug,m);await r.put(D,await pr(t.shareKey,x),{contentType:"application/octet-stream"}),a.push(D),u[m]={url:await uo(t.config,D,t.expiresSec),ct:Nl(e,m)??"application/octet-stream"}}if(Object.keys(u).length)o.blobs=u;let _=Qg(n,t.slug);return await r.put(_,await pr(t.shareKey,new TextEncoder().encode(JSON.stringify(o))),{contentType:"application/octet-stream"}),a.push(_),{manifestUrl:await uo(t.config,_,t.expiresSec),objects:a,title:o.title}}async function th(e,t,r,n=Tn){let o=await ic(t,r);if(!o)throw new Z("not_found",`no such bucket share: ${r}`);let s=Xt(o.key),a=oh(n),{manifestUrl:u,objects:_,title:m}=await Gv(e,{slug:r,kind:o.kind,targetId:o.target_id,config:t,shareKey:s,expiresSec:a}),x=Date.now()+a*1000,D={...o,title:m,presign_exp:x,objects:_,content_updated_at:Date.now()};return await Bt(t).put(oc(po(t.prefix),r),await eh(t,D),{contentType:"application/octet-stream"}),{manifestUrl:u,presignExp:x,keyB64:o.has_password?void 0:o.key,saltB64:o.salt,title:m}}async function Kv(e,t){if(!e.blobs)return e;let r={};for(let[n,o]of Object.entries(e.blobs))r[n]={...o,url:await t(n)};return{...e,blobs:r}}async function rh(e,t,r=Tn){let n=await ic(e,t);if(!n)throw new Z("not_found",`no such bucket share: ${t}`);let o=Bt(e),s=po(e.prefix),a=Xt(n.key),u=oh(r),_=Qg(s,t),m=await o.get(_).catch(()=>null);if(!m)throw new Z("not_found",`bucket share ${t} has no manifest`);let x=JSON.parse(new TextDecoder().decode(await Hr(a,m))),D=await Kv(x,(Y)=>uo(e,Yg(s,t,Y),u));await o.put(_,await pr(a,new TextEncoder().encode(JSON.stringify(D))),{contentType:"application/octet-stream"});let j=Date.now()+u*1000;return await o.put(oc(s,t),await eh(e,{...n,presign_exp:j}),{contentType:"application/octet-stream"}),{manifestUrl:await uo(e,_,u),presignExp:j,keyB64:n.has_password?void 0:n.key,saltB64:n.salt,title:n.title}}async function nh(e){let t=Bt(e),r=po(e.prefix),o=(await t.list(`${r}/`,void 0,"/").catch(()=>[])).map((a)=>a.key.slice(`${r}/`.length).replace(/\/$/,"")).filter((a)=>a&&!a.includes("/")),s=[];for(let a of o){let u=await ic(e,a);if(u)s.push(u)}return s}function oh(e){return Math.min(Math.max(60,Math.floor(e)),Tn)}var oc=(e,t)=>`${e}/${t}/meta.json`,Qg=(e,t)=>`${e}/${t}/manifest.bin`,Yg=(e,t,r)=>`${e}/${t}/blobs/${r}`;var ih=De(()=>{Ye();_n();qr();Nr();Lr();zn();wn();wi();Qn()});function Jv(e,t){if(t)return t.replace(/\/+$/,"");return(e.query("SELECT value FROM meta WHERE key='cfg_share_viewer_url'").get()?.value||Vv).replace(/\/+$/,"")}function Xv(e,t,r,n){let o=`m=${encodeURIComponent(t)}&`+(r?`k=${r}`:`s=${n}`);return`${e}/#${o}`}async function sh(e,t,r,n){for(let o of jt(e).filter((s)=>s.kind==="s3"&&s.config)){let s=JSON.parse(o.config),u=(await nh(s).catch(()=>[])).find((x)=>x.slug===t);if(!u)continue;let _=Jv(e,r),m=n?.refreshContent?await th(e,s,t):await rh(s,t);return{slug:t,kind:u.kind,permission:"view",transport:"s3",hosting:"s3",url:Xv(_,m.manifestUrl,m.keyB64,m.saltB64),expiresAt:m.presignExp,source:`桶 ${o.label??o.url}`}}throw new Z("not_found",`no such object-storage share: ${t}`)}var Vv="https://share.mh.tensorix.org",ID;var ah=De(()=>{ta();Ye();wt();Xi();En();_n();qr();io();vn();ih();wi();co();ID=jr({slug:at().min(1).max(128),kind:ni(["doc","database","site"]),permission:ni(["view","edit"]),transport:$b("server"),hosting:ni(["server","room"]),url:at().url(),expiresAt:ri().nullable(),source:at()})});globalThis.sqlite3Worker1Promiser=function e(t=e.defaultConfig){if(arguments.length===1&&typeof arguments[0]==="function"){let D=t;t=Object.assign(Object.create(null),e.defaultConfig),t.onready=D}else t=Object.assign(Object.create(null),e.defaultConfig,t);let r=Object.create(null),n=function(){},o=t.onerror||n,s=t.debug||n,a=t.generateMessageId?void 0:Object.create(null),u=t.generateMessageId||function(D){return D.type+"#"+(a[D.type]=(a[D.type]||0)+1)},_=(...D)=>{throw Error(D.join(" "))};if(!t.worker)t.worker=e.defaultConfig.worker;if(typeof t.worker==="function")t.worker=t.worker();let m,x;return t.worker.onmessage=function(D){D=D.data,s("worker1.onmessage",D);let j=r[D.messageId];if(!j){if(D&&D.type==="sqlite3-api"&&D.result==="worker1-ready"){if(t.onready)t.onready(x);return}if(j=r[D.type],j&&j.onrow){j.onrow(D);return}if(t.onunhandled)t.onunhandled(arguments[0]);else o("sqlite3Worker1Promiser() unhandled worker message:",D);return}switch(delete r[D.messageId],D.type){case"error":j.reject(D);return;case"open":if(!m)m=D.dbId;break;case"close":if(D.dbId===m)m=void 0;break;default:break}try{j.resolve(D)}catch(Y){j.reject(Y)}},x=function(){let D;if(arguments.length===1)D=arguments[0];else if(arguments.length===2)D=Object.create(null),D.type=arguments[0],D.args=arguments[1],D.dbId=D.args.dbId;else _("Invalid arguments for sqlite3Worker1Promiser()-created factory.");if(!D.dbId&&D.type!=="open")D.dbId=m;D.messageId=u(D),D.departureTime=performance.now();let j=Object.create(null);j.message=D;let Y;if(D.type==="exec"&&D.args){if(typeof D.args.callback==="function")Y=D.messageId+":row",j.onrow=D.args.callback,D.args.callback=Y,r[Y]=j;else if(typeof D.args.callback==="string")_("exec callback may not be a string when using the Promise interface.")}let _e=new Promise(function(de,ge){j.resolve=de,j.reject=ge,r[D.messageId]=j,s("Posting",D.type,"message to Worker dbId="+(m||"default")+":",D),t.worker.postMessage(D)});if(Y)_e=_e.finally(()=>delete r[Y]);return _e}};globalThis.sqlite3Worker1Promiser.defaultConfig={worker:function(){return new Worker(new URL("sqlite3-worker1.mjs",import.meta.url),{type:"module"})},onerror:(...e)=>console.error("sqlite3Worker1Promiser():",...e)};globalThis.sqlite3Worker1Promiser.v2=function e(t=e.defaultConfig){let r;if(typeof t=="function")r=t,t={};else if(typeof t?.onready==="function")r=t.onready,delete t.onready;let n=Object.create(null);t=Object.assign(t||Object.create(null),{onready:async function(s){try{if(r)await r(s);n.resolve(s)}catch(a){n.reject(a)}}});let o=new Promise(function(s,a){n.resolve=s,n.reject=a});try{this.original(t)}catch(s){n.reject(s)}return o}.bind({original:sqlite3Worker1Promiser});globalThis.sqlite3Worker1Promiser.v2.defaultConfig=globalThis.sqlite3Worker1Promiser.defaultConfig;var pE=sqlite3Worker1Promiser.v2;delete globalThis.sqlite3Worker1Promiser;async function Li(e={}){var t,r=e,n=!!globalThis.window,o=!!globalThis.WorkerGlobalScope;globalThis.process?.versions?.node&&globalThis.process?.type;var s="./this.program",a=import.meta.url,u="";function _(i){if(r.locateFile)return r.locateFile(i,u);return u+i}var m,x;if(n||o){try{u=new URL(".",a).href}catch{}if(o)x=(i)=>{var l=new XMLHttpRequest;return l.open("GET",i,!1),l.responseType="arraybuffer",l.send(null),new Uint8Array(l.response)};m=async(i)=>{var l=await fetch(i,{credentials:"same-origin"});if(l.ok)return l.arrayBuffer();throw Error(l.status+" : "+l.url)}}var D=console.log.bind(console),j=console.error.bind(console),Y,_e=!1,de,ge,Le=!1;function Ze(){var i=cr.buffer;$t=new Int8Array(i),On=new Int16Array(i),Ar=new Uint8Array(i),xh=new Uint16Array(i),Je=new Int32Array(i),et=new Uint32Array(i),Eh=new Float32Array(i),Sh=new Float64Array(i),St=new BigInt64Array(i),Th=new BigUint64Array(i)}function $e(){if(r.wasmMemory)cr=r.wasmMemory;else{var i=r.INITIAL_MEMORY||8388608;cr=new WebAssembly.Memory({initial:i/65536,maximum:32768})}Ze()}function Ue(){if(r.preRun){if(typeof r.preRun=="function")r.preRun=[r.preRun];while(r.preRun.length)Rh(r.preRun.shift())}uc(fc)}function tt(){if(Le=!0,!r.noFSInit&&!y.initialized)y.init();mr.init(),tn.__wasm_call_ctors(),y.ignorePermissions=!1}function Rr(){if(r.postRun){if(typeof r.postRun=="function")r.postRun=[r.postRun];while(r.postRun.length)kh(r.postRun.shift())}uc(dc)}function Lt(i){r.onAbort?.(i),i=`Aborted(${i})`,j(i),_e=!0,i+=". Build with -sASSERTIONS for more info.";var l=new WebAssembly.RuntimeError(i);throw ge?.(l),l}var Dn;function gh(){if(r.locateFile)return _("sqlite3.wasm");return new URL("sqlite3.wasm",import.meta.url).href}function hh(i){if(i==Dn&&Y)return new Uint8Array(Y);if(x)return x(i);throw"both async and sync fetching of the wasm failed"}async function mh(i){if(!Y)try{var l=await m(i);return new Uint8Array(l)}catch{}return hh(i)}async function yh(i,l){try{var h=await mh(i);return await WebAssembly.instantiate(h,l)}catch(f){j(`failed to asynchronously prepare wasm: ${f}`),Lt(f)}}async function bh(i,l,h){if(!i)try{var f=fetch(l,{credentials:"same-origin"});return await WebAssembly.instantiateStreaming(f,h)}catch(c){j(`wasm streaming compile failed: ${c}`),j("falling back to ArrayBuffer instantiation")}return yh(l,h)}function wh(){return{env:Rc,wasi_snapshot_preview1:Rc}}async function vh(){function i(f,c){return tn=f.exports,Im(tn),tn}function l(f){return i(f.instance)}var h=wh();if(r.instantiateWasm)return new Promise((f,c)=>{r.instantiateWasm(h,(d,p)=>{f(i(d,p))})});return Dn??=gh(),l(await bh(Y,Dn,h))}var On,Je,St,$t,Eh,Sh,xh,et,Th,Ar,uc=(i)=>{while(i.length>0)i.shift()(r)},dc=[],kh=(i)=>dc.push(i),fc=[],Rh=(i)=>fc.push(i),cr,Xe={isAbs:(i)=>i.charAt(0)==="/",splitPath:(i)=>/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/.exec(i).slice(1),normalizeArray:(i,l)=>{var h=0;for(var f=i.length-1;f>=0;f--){var c=i[f];if(c===".")i.splice(f,1);else if(c==="..")i.splice(f,1),h++;else if(h)i.splice(f,1),h--}if(l)for(;h;h--)i.unshift("..");return i},normalize:(i)=>{var l=Xe.isAbs(i),h=i.slice(-1)==="/";if(i=Xe.normalizeArray(i.split("/").filter((f)=>!!f),!l).join("/"),!i&&!l)i=".";if(i&&h)i+="/";return(l?"/":"")+i},dirname:(i)=>{var l=Xe.splitPath(i),h=l[0],f=l[1];if(!h&&!f)return".";if(f)f=f.slice(0,-1);return h+f},basename:(i)=>i&&i.match(/([^\/]+|\/)\/*$/)[1],join:(...i)=>Xe.normalize(i.join("/")),join2:(i,l)=>Xe.normalize(i+"/"+l)},Ah=()=>(i)=>(crypto.getRandomValues(i),0),pc=(i)=>(pc=Ah())(i),Qr={resolve:(...i)=>{var l="",h=!1;for(var f=i.length-1;f>=-1&&!h;f--){var c=f>=0?i[f]:y.cwd();if(typeof c!="string")throw TypeError("Arguments to path.resolve must be strings");else if(!c)return"";l=c+"/"+l,h=Xe.isAbs(c)}return l=Xe.normalizeArray(l.split("/").filter((d)=>!!d),!h).join("/"),(h?"/":"")+l||"."},relative:(i,l)=>{i=Qr.resolve(i).slice(1),l=Qr.resolve(l).slice(1);function h(I){var V=0;for(;V<I.length;V++)if(I[V]!=="")break;var M=I.length-1;for(;M>=0;M--)if(I[M]!=="")break;if(V>M)return[];return I.slice(V,M-V+1)}var f=h(i.split("/")),c=h(l.split("/")),d=Math.min(f.length,c.length),p=d;for(var E=0;E<d;E++)if(f[E]!==c[E]){p=E;break}var b=[];for(var E=p;E<f.length;E++)b.push("..");return b=b.concat(c.slice(p)),b.join("/")}},_c=new TextDecoder,gc=(i,l,h,f)=>{var c=l+h;if(f)return c;while(i[l]&&!(l>=c))++l;return l},In=(i,l=0,h,f)=>{var c=gc(i,l,h,f);return _c.decode(i.buffer?i.subarray(l,c):new Uint8Array(i.slice(l,c)))},Ii=[],go=(i)=>{var l=0;for(var h=0;h<i.length;++h){var f=i.charCodeAt(h);if(f<=127)l++;else if(f<=2047)l+=2;else if(f>=55296&&f<=57343)l+=4,++h;else l+=3}return l},hc=(i,l,h,f)=>{if(!(f>0))return 0;var c=h,d=h+f-1;for(var p=0;p<i.length;++p){var E=i.codePointAt(p);if(E<=127){if(h>=d)break;l[h++]=E}else if(E<=2047){if(h+1>=d)break;l[h++]=192|E>>6,l[h++]=128|E&63}else if(E<=65535){if(h+2>=d)break;l[h++]=224|E>>12,l[h++]=128|E>>6&63,l[h++]=128|E&63}else{if(h+3>=d)break;l[h++]=240|E>>18,l[h++]=128|E>>12&63,l[h++]=128|E>>6&63,l[h++]=128|E&63,p++}}return l[h]=0,h-c},Pi=(i,l,h)=>{var f=h>0?h:go(i)+1,c=Array(f),d=hc(i,c,0,c.length);if(l)c.length=d;return c},Dh=()=>{if(!Ii.length){var i=null;if(globalThis.window?.prompt){if(i=window.prompt("Input: "),i!==null)i+=`
521
- `}if(!i)return null;Ii=Pi(i,!0)}return Ii.shift()},mr={ttys:[],init(){},shutdown(){},register(i,l){mr.ttys[i]={input:[],output:[],ops:l},y.registerDevice(i,mr.stream_ops)},stream_ops:{open(i){var l=mr.ttys[i.node.rdev];if(!l)throw new y.ErrnoError(43);i.tty=l,i.seekable=!1},close(i){i.tty.ops.fsync(i.tty)},fsync(i){i.tty.ops.fsync(i.tty)},read(i,l,h,f,c){if(!i.tty||!i.tty.ops.get_char)throw new y.ErrnoError(60);var d=0;for(var p=0;p<f;p++){var E;try{E=i.tty.ops.get_char(i.tty)}catch(b){throw new y.ErrnoError(29)}if(E===void 0&&d===0)throw new y.ErrnoError(6);if(E===null||E===void 0)break;d++,l[h+p]=E}if(d)i.node.atime=Date.now();return d},write(i,l,h,f,c){if(!i.tty||!i.tty.ops.put_char)throw new y.ErrnoError(60);try{for(var d=0;d<f;d++)i.tty.ops.put_char(i.tty,l[h+d])}catch(p){throw new y.ErrnoError(29)}if(f)i.node.mtime=i.node.ctime=Date.now();return d}},default_tty_ops:{get_char(i){return Dh()},put_char(i,l){if(l===null||l===10)D(In(i.output)),i.output=[];else if(l!=0)i.output.push(l)},fsync(i){if(i.output?.length>0)D(In(i.output)),i.output=[]},ioctl_tcgets(i){return{c_iflag:25856,c_oflag:5,c_cflag:191,c_lflag:35387,c_cc:[3,28,127,21,4,0,1,0,17,19,26,0,18,15,23,22,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]}},ioctl_tcsets(i,l,h){return 0},ioctl_tiocgwinsz(i){return[24,80]}},default_tty1_ops:{put_char(i,l){if(l===null||l===10)j(In(i.output)),i.output=[];else if(l!=0)i.output.push(l)},fsync(i){if(i.output?.length>0)j(In(i.output)),i.output=[]}}},Oh=(i,l)=>Ar.fill(0,i,i+l),mc=(i,l)=>Math.ceil(i/l)*l,yc=(i)=>{i=mc(i,65536);var l=kc(65536,i);if(l)Oh(l,i);return l},ze={ops_table:null,mount(i){return ze.createNode(null,"/",16895,0)},createNode(i,l,h,f){if(y.isBlkdev(h)||y.isFIFO(h))throw new y.ErrnoError(63);ze.ops_table||={dir:{node:{getattr:ze.node_ops.getattr,setattr:ze.node_ops.setattr,lookup:ze.node_ops.lookup,mknod:ze.node_ops.mknod,rename:ze.node_ops.rename,unlink:ze.node_ops.unlink,rmdir:ze.node_ops.rmdir,readdir:ze.node_ops.readdir,symlink:ze.node_ops.symlink},stream:{llseek:ze.stream_ops.llseek}},file:{node:{getattr:ze.node_ops.getattr,setattr:ze.node_ops.setattr},stream:{llseek:ze.stream_ops.llseek,read:ze.stream_ops.read,write:ze.stream_ops.write,mmap:ze.stream_ops.mmap,msync:ze.stream_ops.msync}},link:{node:{getattr:ze.node_ops.getattr,setattr:ze.node_ops.setattr,readlink:ze.node_ops.readlink},stream:{}},chrdev:{node:{getattr:ze.node_ops.getattr,setattr:ze.node_ops.setattr},stream:y.chrdev_stream_ops}};var c=y.createNode(i,l,h,f);if(y.isDir(c.mode))c.node_ops=ze.ops_table.dir.node,c.stream_ops=ze.ops_table.dir.stream,c.contents={};else if(y.isFile(c.mode))c.node_ops=ze.ops_table.file.node,c.stream_ops=ze.ops_table.file.stream,c.usedBytes=0,c.contents=ze.emptyFileContents??=new Uint8Array(0);else if(y.isLink(c.mode))c.node_ops=ze.ops_table.link.node,c.stream_ops=ze.ops_table.link.stream;else if(y.isChrdev(c.mode))c.node_ops=ze.ops_table.chrdev.node,c.stream_ops=ze.ops_table.chrdev.stream;if(c.atime=c.mtime=c.ctime=Date.now(),i)i.contents[l]=c,i.atime=i.mtime=i.ctime=c.atime;return c},getFileDataAsTypedArray(i){return i.contents.subarray(0,i.usedBytes)},expandFileStorage(i,l){var h=i.contents.length;if(h>=l)return;if(l=Math.max(l,h*(h<1048576?2:1.125)>>>0),h)l=Math.max(l,256);var f=ze.getFileDataAsTypedArray(i);i.contents=new Uint8Array(l),i.contents.set(f)},resizeFileStorage(i,l){if(i.usedBytes==l)return;var h=i.contents;i.contents=new Uint8Array(l),i.contents.set(h.subarray(0,Math.min(l,i.usedBytes))),i.usedBytes=l},node_ops:{getattr(i){var l={};if(l.dev=y.isChrdev(i.mode)?i.id:1,l.ino=i.id,l.mode=i.mode,l.nlink=1,l.uid=0,l.gid=0,l.rdev=i.rdev,y.isDir(i.mode))l.size=4096;else if(y.isFile(i.mode))l.size=i.usedBytes;else if(y.isLink(i.mode))l.size=i.link.length;else l.size=0;return l.atime=new Date(i.atime),l.mtime=new Date(i.mtime),l.ctime=new Date(i.ctime),l.blksize=4096,l.blocks=Math.ceil(l.size/l.blksize),l},setattr(i,l){for(let h of["mode","atime","mtime","ctime"])if(l[h]!=null)i[h]=l[h];if(l.size!==void 0)ze.resizeFileStorage(i,l.size)},lookup(i,l){if(!ze.doesNotExistError)ze.doesNotExistError=new y.ErrnoError(44),ze.doesNotExistError.stack="<generic error, no stack>";throw ze.doesNotExistError},mknod(i,l,h,f){return ze.createNode(i,l,h,f)},rename(i,l,h){var f;try{f=y.lookupNode(l,h)}catch(d){}if(f){if(y.isDir(i.mode))for(var c in f.contents)throw new y.ErrnoError(55);y.hashRemoveNode(f)}delete i.parent.contents[i.name],l.contents[h]=i,i.name=h,l.ctime=l.mtime=i.parent.ctime=i.parent.mtime=Date.now()},unlink(i,l){delete i.contents[l],i.ctime=i.mtime=Date.now()},rmdir(i,l){for(var h in y.lookupNode(i,l).contents)throw new y.ErrnoError(55);delete i.contents[l],i.ctime=i.mtime=Date.now()},readdir(i){return[".","..",...Object.keys(i.contents)]},symlink(i,l,h){var f=ze.createNode(i,l,41471,0);return f.link=h,f},readlink(i){if(!y.isLink(i.mode))throw new y.ErrnoError(28);return i.link}},stream_ops:{read(i,l,h,f,c){var d=i.node.contents;if(c>=i.node.usedBytes)return 0;var p=Math.min(i.node.usedBytes-c,f);return l.set(d.subarray(c,c+p),h),p},write(i,l,h,f,c,d){if(l.buffer===$t.buffer)d=!1;if(!f)return 0;var p=i.node;if(p.mtime=p.ctime=Date.now(),d)p.contents=l.subarray(h,h+f),p.usedBytes=f;else if(p.usedBytes===0&&c===0)p.contents=l.slice(h,h+f),p.usedBytes=f;else ze.expandFileStorage(p,c+f),p.contents.set(l.subarray(h,h+f),c),p.usedBytes=Math.max(p.usedBytes,c+f);return f},llseek(i,l,h){var f=l;if(h===1)f+=i.position;else if(h===2){if(y.isFile(i.node.mode))f+=i.node.usedBytes}if(f<0)throw new y.ErrnoError(28);return f},mmap(i,l,h,f,c){if(!y.isFile(i.node.mode))throw new y.ErrnoError(43);var d,p,E=i.node.contents;if(!(c&2)&&E.buffer===$t.buffer)p=!1,d=E.byteOffset;else{if(p=!0,d=yc(l),!d)throw new y.ErrnoError(48);if(E){if(h>0||h+l<E.length)if(E.subarray)E=E.subarray(h,h+l);else E=Array.prototype.slice.call(E,h,h+l);$t.set(E,d)}}return{ptr:d,allocated:p}},msync(i,l,h,f,c){return ze.stream_ops.write(i,l,0,f,h,!1),0}}},Ih=(i)=>{if(typeof i!="string")return i;var l={r:0,"r+":2,w:577,"w+":578,a:1089,"a+":1090}[i];if(typeof l>"u")throw Error(`Unknown file open mode: ${i}`);return l},bc=(i)=>{if(typeof i=="string")i=Pi(i,!0);if(!i.subarray)i=new Uint8Array(i);return i},Ci=(i,l)=>{var h=0;if(i)h|=365;if(l)h|=146;return h},Ph=async(i)=>{var l=await m(i);return new Uint8Array(l)},Ch=(...i)=>y.createDataFile(...i),Nh=(i)=>i,Dr=0,Pn=null,qh=(i)=>{if(Dr--,r.monitorRunDependencies?.(Dr),Dr==0){if(Pn){var l=Pn;Pn=null,l()}}},Lh=(i)=>{Dr++,r.monitorRunDependencies?.(Dr)},wc=[],$h=async(i,l)=>{if(typeof Browser<"u")Browser.init();for(var h of wc)if(h.canHandle(l))return h.handle(i,l);return i},vc=async(i,l,h,f,c,d,p,E)=>{var b=l?Qr.resolve(Xe.join2(i,l)):i,I=Nh(`cp ${b}`);Lh(I);try{var V=h;if(typeof h=="string")V=await Ph(h);if(V=await $h(V,b),E?.(),!d)Ch(i,l,V,f,c,p)}finally{qh(I)}},zh=(i,l,h,f,c,d,p,E,b,I)=>{vc(i,l,h,f,c,E,b,I).then(d).catch(p)},y={root:null,mounts:[],devices:{},streams:[],nextInode:1,nameTable:null,currentPath:"/",initialized:!1,ignorePermissions:!0,filesystems:null,syncFSRequests:0,ErrnoError:class{name="ErrnoError";constructor(i){this.errno=i}},FSStream:class{shared={};get object(){return this.node}set object(i){this.node=i}get isRead(){return(this.flags&2097155)!==1}get isWrite(){return(this.flags&2097155)!==0}get isAppend(){return this.flags&1024}get flags(){return this.shared.flags}set flags(i){this.shared.flags=i}get position(){return this.shared.position}set position(i){this.shared.position=i}},FSNode:class{node_ops={};stream_ops={};readMode=365;writeMode=146;mounted=null;constructor(i,l,h,f){if(!i)i=this;this.parent=i,this.mount=i.mount,this.id=y.nextInode++,this.name=l,this.mode=h,this.rdev=f,this.atime=this.mtime=this.ctime=Date.now()}get read(){return(this.mode&this.readMode)===this.readMode}set read(i){i?this.mode|=this.readMode:this.mode&=~this.readMode}get write(){return(this.mode&this.writeMode)===this.writeMode}set write(i){i?this.mode|=this.writeMode:this.mode&=~this.writeMode}get isFolder(){return y.isDir(this.mode)}get isDevice(){return y.isChrdev(this.mode)}},lookupPath(i,l={}){if(!i)throw new y.ErrnoError(44);if(l.follow_mount??=!0,!Xe.isAbs(i))i=y.cwd()+"/"+i;e:for(var h=0;h<40;h++){var f=i.split("/").filter((I)=>!!I),c=y.root,d="/";for(var p=0;p<f.length;p++){var E=p===f.length-1;if(E&&l.parent)break;if(f[p]===".")continue;if(f[p]===".."){if(d=Xe.dirname(d),y.isRoot(c)){i=d+"/"+f.slice(p+1).join("/"),h--;continue e}else c=c.parent;continue}d=Xe.join2(d,f[p]);try{c=y.lookupNode(c,f[p])}catch(I){if(I?.errno===44&&E&&l.noent_okay)return{path:d};throw I}if(y.isMountpoint(c)&&(!E||l.follow_mount))c=c.mounted.root;if(y.isLink(c.mode)&&(!E||l.follow)){if(!c.node_ops.readlink)throw new y.ErrnoError(52);var b=c.node_ops.readlink(c);if(!Xe.isAbs(b))b=Xe.dirname(d)+"/"+b;i=b+"/"+f.slice(p+1).join("/");continue e}}return{path:d,node:c}}throw new y.ErrnoError(32)},getPath(i){var l;while(!0){if(y.isRoot(i)){var h=i.mount.mountpoint;if(!l)return h;return h[h.length-1]!=="/"?`${h}/${l}`:h+l}l=l?`${i.name}/${l}`:i.name,i=i.parent}},hashName(i,l){var h=0;for(var f=0;f<l.length;f++)h=(h<<5)-h+l.charCodeAt(f)|0;return(i+h>>>0)%y.nameTable.length},hashAddNode(i){var l=y.hashName(i.parent.id,i.name);i.name_next=y.nameTable[l],y.nameTable[l]=i},hashRemoveNode(i){var l=y.hashName(i.parent.id,i.name);if(y.nameTable[l]===i)y.nameTable[l]=i.name_next;else{var h=y.nameTable[l];while(h){if(h.name_next===i){h.name_next=i.name_next;break}h=h.name_next}}},lookupNode(i,l){var h=y.mayLookup(i);if(h)throw new y.ErrnoError(h);var f=y.hashName(i.id,l);for(var c=y.nameTable[f];c;c=c.name_next){var d=c.name;if(c.parent.id===i.id&&d===l)return c}return y.lookup(i,l)},createNode(i,l,h,f){var c=new y.FSNode(i,l,h,f);return y.hashAddNode(c),c},destroyNode(i){y.hashRemoveNode(i)},isRoot(i){return i===i.parent},isMountpoint(i){return!!i.mounted},isFile(i){return(i&61440)===32768},isDir(i){return(i&61440)===16384},isLink(i){return(i&61440)===40960},isChrdev(i){return(i&61440)===8192},isBlkdev(i){return(i&61440)===24576},isFIFO(i){return(i&61440)===4096},isSocket(i){return(i&49152)===49152},flagsToPermissionString(i){var l=["r","w","rw"][i&3];if(i&512)l+="w";return l},nodePermissions(i,l){if(y.ignorePermissions)return 0;if(l.includes("r")&&!(i.mode&292))return 2;if(l.includes("w")&&!(i.mode&146))return 2;if(l.includes("x")&&!(i.mode&73))return 2;return 0},mayLookup(i){if(!y.isDir(i.mode))return 54;var l=y.nodePermissions(i,"x");if(l)return l;if(!i.node_ops.lookup)return 2;return 0},mayCreate(i,l){if(!y.isDir(i.mode))return 54;try{return y.lookupNode(i,l),20}catch(h){}return y.nodePermissions(i,"wx")},mayDelete(i,l,h){var f;try{f=y.lookupNode(i,l)}catch(d){return d.errno}var c=y.nodePermissions(i,"wx");if(c)return c;if(h){if(!y.isDir(f.mode))return 54;if(y.isRoot(f)||y.getPath(f)===y.cwd())return 10}else if(y.isDir(f.mode))return 31;return 0},mayOpen(i,l){if(!i)return 44;if(y.isLink(i.mode))return 32;var h=y.flagsToPermissionString(l);if(y.isDir(i.mode)){if(h!=="r"||l&576)return 31}return y.nodePermissions(i,h)},checkOpExists(i,l){if(!i)throw new y.ErrnoError(l);return i},MAX_OPEN_FDS:4096,nextfd(){for(var i=0;i<=y.MAX_OPEN_FDS;i++)if(!y.streams[i])return i;throw new y.ErrnoError(33)},getStreamChecked(i){var l=y.getStream(i);if(!l)throw new y.ErrnoError(8);return l},getStream:(i)=>y.streams[i],createStream(i,l=-1){if(i=Object.assign(new y.FSStream,i),l==-1)l=y.nextfd();return i.fd=l,y.streams[l]=i,i},closeStream(i){y.streams[i]=null},dupStream(i,l=-1){var h=y.createStream(i,l);return h.stream_ops?.dup?.(h),h},doSetAttr(i,l,h){var f=i?.stream_ops.setattr,c=f?i:l;f??=l.node_ops.setattr,y.checkOpExists(f,63),f(c,h)},chrdev_stream_ops:{open(i){i.stream_ops=y.getDevice(i.node.rdev).stream_ops,i.stream_ops.open?.(i)},llseek(){throw new y.ErrnoError(70)}},major:(i)=>i>>8,minor:(i)=>i&255,makedev:(i,l)=>i<<8|l,registerDevice(i,l){y.devices[i]={stream_ops:l}},getDevice:(i)=>y.devices[i],getMounts(i){var l=[],h=[i];while(h.length){var f=h.pop();l.push(f),h.push(...f.mounts)}return l},syncfs(i,l){if(typeof i=="function")l=i,i=!1;if(y.syncFSRequests++,y.syncFSRequests>1)j(`warning: ${y.syncFSRequests} FS.syncfs operations in flight at once, probably just doing extra work`);var h=y.getMounts(y.root.mount),f=0;function c(E){return y.syncFSRequests--,l(E)}function d(E){if(E){if(!d.errored)return d.errored=!0,c(E);return}if(++f>=h.length)c(null)}for(var p of h)if(p.type.syncfs)p.type.syncfs(p,i,d);else d(null)},mount(i,l,h){var f=h==="/",c=!h,d;if(f&&y.root)throw new y.ErrnoError(10);else if(!f&&!c){var p=y.lookupPath(h,{follow_mount:!1});if(h=p.path,d=p.node,y.isMountpoint(d))throw new y.ErrnoError(10);if(!y.isDir(d.mode))throw new y.ErrnoError(54)}var E={type:i,opts:l,mountpoint:h,mounts:[]},b=i.mount(E);if(b.mount=E,E.root=b,f)y.root=b;else if(d){if(d.mounted=E,d.mount)d.mount.mounts.push(E)}return b},unmount(i){var l=y.lookupPath(i,{follow_mount:!1});if(!y.isMountpoint(l.node))throw new y.ErrnoError(28);var h=l.node,f=h.mounted,c=y.getMounts(f);for(var[d,p]of Object.entries(y.nameTable))while(p){var E=p.name_next;if(c.includes(p.mount))y.destroyNode(p);p=E}h.mounted=null;var b=h.mount.mounts.indexOf(f);h.mount.mounts.splice(b,1)},lookup(i,l){return i.node_ops.lookup(i,l)},mknod(i,l,h){var f=y.lookupPath(i,{parent:!0}).node,c=Xe.basename(i);if(!c)throw new y.ErrnoError(28);if(c==="."||c==="..")throw new y.ErrnoError(20);var d=y.mayCreate(f,c);if(d)throw new y.ErrnoError(d);if(!f.node_ops.mknod)throw new y.ErrnoError(63);return f.node_ops.mknod(f,c,l,h)},statfs(i){return y.statfsNode(y.lookupPath(i,{follow:!0}).node)},statfsStream(i){return y.statfsNode(i.node)},statfsNode(i){var l={bsize:4096,frsize:4096,blocks:1e6,bfree:500000,bavail:500000,files:y.nextInode,ffree:y.nextInode-1,fsid:42,flags:2,namelen:255};if(i.node_ops.statfs)Object.assign(l,i.node_ops.statfs(i.mount.opts.root));return l},create(i,l=438){return l&=4095,l|=32768,y.mknod(i,l,0)},mkdir(i,l=511){return l&=1023,l|=16384,y.mknod(i,l,0)},mkdirTree(i,l){var h=i.split("/"),f="";for(var c of h){if(!c)continue;if(f||Xe.isAbs(i))f+="/";f+=c;try{y.mkdir(f,l)}catch(d){if(d.errno!=20)throw d}}},mkdev(i,l,h){if(typeof h>"u")h=l,l=438;return l|=8192,y.mknod(i,l,h)},symlink(i,l){if(!Qr.resolve(i))throw new y.ErrnoError(44);var h=y.lookupPath(l,{parent:!0}).node;if(!h)throw new y.ErrnoError(44);var f=Xe.basename(l),c=y.mayCreate(h,f);if(c)throw new y.ErrnoError(c);if(!h.node_ops.symlink)throw new y.ErrnoError(63);return h.node_ops.symlink(h,f,i)},rename(i,l){var h=Xe.dirname(i),f=Xe.dirname(l),c=Xe.basename(i),d=Xe.basename(l),p=y.lookupPath(i,{parent:!0}),E=p.node,b;if(p=y.lookupPath(l,{parent:!0}),b=p.node,!E||!b)throw new y.ErrnoError(44);if(E.mount!==b.mount)throw new y.ErrnoError(75);var I=y.lookupNode(E,c),V=Qr.relative(i,f);if(V.charAt(0)!==".")throw new y.ErrnoError(28);if(V=Qr.relative(l,h),V.charAt(0)!==".")throw new y.ErrnoError(55);var M;try{M=y.lookupNode(b,d)}catch(H){}if(I===M)return;var N=y.isDir(I.mode),q=y.mayDelete(E,c,N);if(q)throw new y.ErrnoError(q);if(q=M?y.mayDelete(b,d,N):y.mayCreate(b,d),q)throw new y.ErrnoError(q);if(!E.node_ops.rename)throw new y.ErrnoError(63);if(y.isMountpoint(I)||M&&y.isMountpoint(M))throw new y.ErrnoError(10);if(b!==E){if(q=y.nodePermissions(E,"w"),q)throw new y.ErrnoError(q)}y.hashRemoveNode(I);try{E.node_ops.rename(I,b,d),I.parent=b}catch(H){throw H}finally{y.hashAddNode(I)}},rmdir(i){var l=y.lookupPath(i,{parent:!0}).node,h=Xe.basename(i),f=y.lookupNode(l,h),c=y.mayDelete(l,h,!0);if(c)throw new y.ErrnoError(c);if(!l.node_ops.rmdir)throw new y.ErrnoError(63);if(y.isMountpoint(f))throw new y.ErrnoError(10);l.node_ops.rmdir(l,h),y.destroyNode(f)},readdir(i){var l=y.lookupPath(i,{follow:!0}).node;return y.checkOpExists(l.node_ops.readdir,54)(l)},unlink(i){var l=y.lookupPath(i,{parent:!0}).node;if(!l)throw new y.ErrnoError(44);var h=Xe.basename(i),f=y.lookupNode(l,h),c=y.mayDelete(l,h,!1);if(c)throw new y.ErrnoError(c);if(!l.node_ops.unlink)throw new y.ErrnoError(63);if(y.isMountpoint(f))throw new y.ErrnoError(10);l.node_ops.unlink(l,h),y.destroyNode(f)},readlink(i){var l=y.lookupPath(i).node;if(!l)throw new y.ErrnoError(44);if(!l.node_ops.readlink)throw new y.ErrnoError(28);return l.node_ops.readlink(l)},stat(i,l){var h=y.lookupPath(i,{follow:!l}).node;return y.checkOpExists(h.node_ops.getattr,63)(h)},fstat(i){var l=y.getStreamChecked(i),h=l.node,f=l.stream_ops.getattr,c=f?l:h;return f??=h.node_ops.getattr,y.checkOpExists(f,63),f(c)},lstat(i){return y.stat(i,!0)},doChmod(i,l,h,f){y.doSetAttr(i,l,{mode:h&4095|l.mode&-4096,ctime:Date.now(),dontFollow:f})},chmod(i,l,h){var f;if(typeof i=="string")f=y.lookupPath(i,{follow:!h}).node;else f=i;y.doChmod(null,f,l,h)},lchmod(i,l){y.chmod(i,l,!0)},fchmod(i,l){var h=y.getStreamChecked(i);y.doChmod(h,h.node,l,!1)},doChown(i,l,h){y.doSetAttr(i,l,{timestamp:Date.now(),dontFollow:h})},chown(i,l,h,f){var c;if(typeof i=="string")c=y.lookupPath(i,{follow:!f}).node;else c=i;y.doChown(null,c,f)},lchown(i,l,h){y.chown(i,l,h,!0)},fchown(i,l,h){var f=y.getStreamChecked(i);y.doChown(f,f.node,!1)},doTruncate(i,l,h){if(y.isDir(l.mode))throw new y.ErrnoError(31);if(!y.isFile(l.mode))throw new y.ErrnoError(28);var f=y.nodePermissions(l,"w");if(f)throw new y.ErrnoError(f);y.doSetAttr(i,l,{size:h,timestamp:Date.now()})},truncate(i,l){if(l<0)throw new y.ErrnoError(28);var h;if(typeof i=="string")h=y.lookupPath(i,{follow:!0}).node;else h=i;y.doTruncate(null,h,l)},ftruncate(i,l){var h=y.getStreamChecked(i);if(l<0||(h.flags&2097155)===0)throw new y.ErrnoError(28);y.doTruncate(h,h.node,l)},utime(i,l,h){var f=y.lookupPath(i,{follow:!0}).node;y.checkOpExists(f.node_ops.setattr,63)(f,{atime:l,mtime:h})},open(i,l,h=438){if(i==="")throw new y.ErrnoError(44);if(l=Ih(l),l&64)h=h&4095|32768;else h=0;var f,c;if(typeof i=="object")f=i;else{c=i.endsWith("/");var d=y.lookupPath(i,{follow:!(l&131072),noent_okay:!0});f=d.node,i=d.path}var p=!1;if(l&64)if(f){if(l&128)throw new y.ErrnoError(20)}else if(c)throw new y.ErrnoError(31);else f=y.mknod(i,h|511,0),p=!0;if(!f)throw new y.ErrnoError(44);if(y.isChrdev(f.mode))l&=-513;if(l&65536&&!y.isDir(f.mode))throw new y.ErrnoError(54);if(!p){var E=y.mayOpen(f,l);if(E)throw new y.ErrnoError(E)}if(l&512&&!p)y.truncate(f,0);l&=-131713;var b=y.createStream({node:f,path:y.getPath(f),flags:l,seekable:!0,position:0,stream_ops:f.stream_ops,ungotten:[],error:!1});if(b.stream_ops.open)b.stream_ops.open(b);if(p)y.chmod(f,h&511);return b},close(i){if(y.isClosed(i))throw new y.ErrnoError(8);if(i.getdents)i.getdents=null;try{if(i.stream_ops.close)i.stream_ops.close(i)}catch(l){throw l}finally{y.closeStream(i.fd)}i.fd=null},isClosed(i){return i.fd===null},llseek(i,l,h){if(y.isClosed(i))throw new y.ErrnoError(8);if(!i.seekable||!i.stream_ops.llseek)throw new y.ErrnoError(70);if(h!=0&&h!=1&&h!=2)throw new y.ErrnoError(28);return i.position=i.stream_ops.llseek(i,l,h),i.ungotten=[],i.position},read(i,l,h,f,c){if(f<0||c<0)throw new y.ErrnoError(28);if(y.isClosed(i))throw new y.ErrnoError(8);if((i.flags&2097155)===1)throw new y.ErrnoError(8);if(y.isDir(i.node.mode))throw new y.ErrnoError(31);if(!i.stream_ops.read)throw new y.ErrnoError(28);var d=typeof c<"u";if(!d)c=i.position;else if(!i.seekable)throw new y.ErrnoError(70);var p=i.stream_ops.read(i,l,h,f,c);if(!d)i.position+=p;return p},write(i,l,h,f,c,d){if(f<0||c<0)throw new y.ErrnoError(28);if(y.isClosed(i))throw new y.ErrnoError(8);if((i.flags&2097155)===0)throw new y.ErrnoError(8);if(y.isDir(i.node.mode))throw new y.ErrnoError(31);if(!i.stream_ops.write)throw new y.ErrnoError(28);if(i.seekable&&i.flags&1024)y.llseek(i,0,2);var p=typeof c<"u";if(!p)c=i.position;else if(!i.seekable)throw new y.ErrnoError(70);var E=i.stream_ops.write(i,l,h,f,c,d);if(!p)i.position+=E;return E},mmap(i,l,h,f,c){if((f&2)!==0&&(c&2)===0&&(i.flags&2097155)!==2)throw new y.ErrnoError(2);if((i.flags&2097155)===1)throw new y.ErrnoError(2);if(!i.stream_ops.mmap)throw new y.ErrnoError(43);if(!l)throw new y.ErrnoError(28);return i.stream_ops.mmap(i,l,h,f,c)},msync(i,l,h,f,c){if(!i.stream_ops.msync)return 0;return i.stream_ops.msync(i,l,h,f,c)},ioctl(i,l,h){if(!i.stream_ops.ioctl)throw new y.ErrnoError(59);return i.stream_ops.ioctl(i,l,h)},readFile(i,l={}){if(l.flags=l.flags||0,l.encoding=l.encoding||"binary",l.encoding!=="utf8"&&l.encoding!=="binary")Lt(`Invalid encoding type "${l.encoding}"`);var h=y.open(i,l.flags),f=y.stat(i).size,c=new Uint8Array(f);if(y.read(h,c,0,f,0),l.encoding==="utf8")c=In(c);return y.close(h),c},writeFile(i,l,h={}){h.flags=h.flags||577;var f=y.open(i,h.flags,h.mode);l=bc(l),y.write(f,l,0,l.byteLength,void 0,h.canOwn),y.close(f)},cwd:()=>y.currentPath,chdir(i){var l=y.lookupPath(i,{follow:!0});if(l.node===null)throw new y.ErrnoError(44);if(!y.isDir(l.node.mode))throw new y.ErrnoError(54);var h=y.nodePermissions(l.node,"x");if(h)throw new y.ErrnoError(h);y.currentPath=l.path},createDefaultDirectories(){y.mkdir("/tmp"),y.mkdir("/home"),y.mkdir("/home/web_user")},createDefaultDevices(){y.mkdir("/dev"),y.registerDevice(y.makedev(1,3),{read:()=>0,write:(f,c,d,p,E)=>p,llseek:()=>0}),y.mkdev("/dev/null",y.makedev(1,3)),mr.register(y.makedev(5,0),mr.default_tty_ops),mr.register(y.makedev(6,0),mr.default_tty1_ops),y.mkdev("/dev/tty",y.makedev(5,0)),y.mkdev("/dev/tty1",y.makedev(6,0));var i=new Uint8Array(1024),l=0,h=()=>{if(l===0)pc(i),l=i.byteLength;return i[--l]};y.createDevice("/dev","random",h),y.createDevice("/dev","urandom",h),y.mkdir("/dev/shm"),y.mkdir("/dev/shm/tmp")},createSpecialDirectories(){y.mkdir("/proc");var i=y.mkdir("/proc/self");y.mkdir("/proc/self/fd"),y.mount({mount(){var l=y.createNode(i,"fd",16895,73);return l.stream_ops={llseek:ze.stream_ops.llseek},l.node_ops={lookup(h,f){var c=+f,d=y.getStreamChecked(c),p={parent:null,mount:{mountpoint:"fake"},node_ops:{readlink:()=>d.path},id:c+1};return p.parent=p,p},readdir(){return Array.from(y.streams.entries()).filter(([h,f])=>f).map(([h,f])=>h.toString())}},l}},{},"/proc/self/fd")},createStandardStreams(i,l,h){if(i)y.createDevice("/dev","stdin",i);else y.symlink("/dev/tty","/dev/stdin");if(l)y.createDevice("/dev","stdout",null,l);else y.symlink("/dev/tty","/dev/stdout");if(h)y.createDevice("/dev","stderr",null,h);else y.symlink("/dev/tty1","/dev/stderr");y.open("/dev/stdin",0),y.open("/dev/stdout",1),y.open("/dev/stderr",1)},staticInit(){y.nameTable=Array(4096),y.mount(ze,{},"/"),y.createDefaultDirectories(),y.createDefaultDevices(),y.createSpecialDirectories(),y.filesystems={MEMFS:ze}},init(i,l,h){y.initialized=!0,i??=r.stdin,l??=r.stdout,h??=r.stderr,y.createStandardStreams(i,l,h)},quit(){y.initialized=!1;for(var i of y.streams)if(i)y.close(i)},findObject(i,l){var h=y.analyzePath(i,l);if(!h.exists)return null;return h.object},analyzePath(i,l){try{var h=y.lookupPath(i,{follow:!l});i=h.path}catch(c){}var f={isRoot:!1,exists:!1,error:0,name:null,path:null,object:null,parentExists:!1,parentPath:null,parentObject:null};try{var h=y.lookupPath(i,{parent:!0});f.parentExists=!0,f.parentPath=h.path,f.parentObject=h.node,f.name=Xe.basename(i),h=y.lookupPath(i,{follow:!l}),f.exists=!0,f.path=h.path,f.object=h.node,f.name=h.node.name,f.isRoot=h.path==="/"}catch(c){f.error=c.errno}return f},createPath(i,l,h,f){i=typeof i=="string"?i:y.getPath(i);var c=l.split("/").reverse();while(c.length){var d=c.pop();if(!d)continue;var p=Xe.join2(i,d);try{y.mkdir(p)}catch(E){if(E.errno!=20)throw E}i=p}return p},createFile(i,l,h,f,c){var d=Xe.join2(typeof i=="string"?i:y.getPath(i),l),p=Ci(f,c);return y.create(d,p)},createDataFile(i,l,h,f,c,d){var p=l;if(i)i=typeof i=="string"?i:y.getPath(i),p=l?Xe.join2(i,l):i;var E=Ci(f,c),b=y.create(p,E);if(h){h=bc(h),y.chmod(b,E|146);var I=y.open(b,577);y.write(I,h,0,h.length,0,d),y.close(I),y.chmod(b,E)}},createDevice(i,l,h,f){var c=Xe.join2(typeof i=="string"?i:y.getPath(i),l),d=Ci(!!h,!!f);y.createDevice.major??=64;var p=y.makedev(y.createDevice.major++,0);return y.registerDevice(p,{open(E){E.seekable=!1},close(E){if(f?.buffer?.length)f(10)},read(E,b,I,V,M){var N=0;for(var q=0;q<V;q++){var H;try{H=h()}catch(G){throw new y.ErrnoError(29)}if(H===void 0&&N===0)throw new y.ErrnoError(6);if(H===null||H===void 0)break;N++,b[I+q]=H}if(N)E.node.atime=Date.now();return N},write(E,b,I,V,M){for(var N=0;N<V;N++)try{f(b[I+N])}catch(q){throw new y.ErrnoError(29)}if(V)E.node.mtime=E.node.ctime=Date.now();return N}}),y.mkdev(c,d,p)},forceLoadFile(i){if(i.isDevice||i.isFolder||i.link||i.contents)return!0;if(globalThis.XMLHttpRequest)Lt("Lazy loading should have been performed (contents set) in createLazyFile, but it was not. Lazy loading only works in web workers. Use --embed-file or --preload-file in emcc on the main thread.");else try{i.contents=x(i.url)}catch(l){throw new y.ErrnoError(29)}},createLazyFile(i,l,h,f,c){class d{lengthKnown=!1;chunks=[];get(V){if(V>this.length-1||V<0)return;var M=V%this.chunkSize,N=V/this.chunkSize|0;return this.getter(N)[M]}setDataGetter(V){this.getter=V}cacheLength(){var V=new XMLHttpRequest;if(V.open("HEAD",h,!1),V.send(null),!(V.status>=200&&V.status<300||V.status===304))Lt("Couldn't load "+h+". Status: "+V.status);var M=Number(V.getResponseHeader("Content-length")),N,q=(N=V.getResponseHeader("Accept-Ranges"))&&N==="bytes",H=(N=V.getResponseHeader("Content-Encoding"))&&N==="gzip",G=1048576;if(!q)G=M;var le=(R,X)=>{if(R>X)Lt("invalid range ("+R+", "+X+") or no bytes requested!");if(X>M-1)Lt("only "+M+" bytes available! programmer error!");var ee=new XMLHttpRequest;if(ee.open("GET",h,!1),M!==G)ee.setRequestHeader("Range","bytes="+R+"-"+X);if(ee.responseType="arraybuffer",ee.overrideMimeType)ee.overrideMimeType("text/plain; charset=x-user-defined");if(ee.send(null),!(ee.status>=200&&ee.status<300||ee.status===304))Lt("Couldn't load "+h+". Status: "+ee.status);if(ee.response!==void 0)return new Uint8Array(ee.response||[]);return Pi(ee.responseText||"",!0)},O=this;if(O.setDataGetter((R)=>{var X=R*G,ee=(R+1)*G-1;if(ee=Math.min(ee,M-1),typeof O.chunks[R]>"u")O.chunks[R]=le(X,ee);if(typeof O.chunks[R]>"u")Lt("doXHR failed!");return O.chunks[R]}),H||!M)G=M=1,M=this.getter(0).length,G=M,D("LazyFiles on gzip forces download of the whole file when length is accessed");this._length=M,this._chunkSize=G,this.lengthKnown=!0}get length(){if(!this.lengthKnown)this.cacheLength();return this._length}get chunkSize(){if(!this.lengthKnown)this.cacheLength();return this._chunkSize}}if(globalThis.XMLHttpRequest){if(!o)Lt("Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc");var p={isDevice:!1,contents:new d}}else var p={isDevice:!1,url:h};var E=y.createFile(i,l,p,f,c);if(p.contents)E.contents=p.contents;else if(p.url)E.contents=null,E.url=p.url;Object.defineProperties(E,{usedBytes:{get:function(){return this.contents.length}}});var b={};for(let[V,M]of Object.entries(E.stream_ops))b[V]=(...N)=>(y.forceLoadFile(E),M(...N));function I(V,M,N,q,H){var G=V.node.contents;if(H>=G.length)return 0;var le=Math.min(G.length-H,q);if(G.slice)for(var O=0;O<le;O++)M[N+O]=G[H+O];else for(var O=0;O<le;O++)M[N+O]=G.get(H+O);return le}return b.read=(V,M,N,q,H)=>(y.forceLoadFile(E),I(V,M,N,q,H)),b.mmap=(V,M,N,q,H)=>{y.forceLoadFile(E);var G=yc(M);if(!G)throw new y.ErrnoError(48);return I(V,$t,G,M,N),{ptr:G,allocated:!0}},E.stream_ops=b,E}},Fh=(i,l,h)=>{if(!i)return"";var f=gc(Ar,i,l,h);return _c.decode(Ar.subarray(i,f))},Be={calculateAt(i,l,h){if(Xe.isAbs(l))return l;var f;if(i===-100)f=y.cwd();else f=Be.getStreamFromFD(i).path;if(l.length==0){if(!h)throw new y.ErrnoError(44);return f}return f+"/"+l},writeStat(i,l){et[i>>2]=l.dev,et[i+4>>2]=l.mode,et[i+8>>2]=l.nlink,et[i+12>>2]=l.uid,et[i+16>>2]=l.gid,et[i+20>>2]=l.rdev,St[i+24>>3]=BigInt(l.size),Je[i+32>>2]=4096,Je[i+36>>2]=l.blocks;var h=l.atime.getTime(),f=l.mtime.getTime(),c=l.ctime.getTime();return St[i+40>>3]=BigInt(Math.floor(h/1000)),et[i+48>>2]=h%1000*1000*1000,St[i+56>>3]=BigInt(Math.floor(f/1000)),et[i+64>>2]=f%1000*1000*1000,St[i+72>>3]=BigInt(Math.floor(c/1000)),et[i+80>>2]=c%1000*1000*1000,St[i+88>>3]=BigInt(l.ino),0},writeStatFs(i,l){et[i+4>>2]=l.bsize,et[i+60>>2]=l.bsize,St[i+8>>3]=BigInt(l.blocks),St[i+16>>3]=BigInt(l.bfree),St[i+24>>3]=BigInt(l.bavail),St[i+32>>3]=BigInt(l.files),St[i+40>>3]=BigInt(l.ffree),et[i+48>>2]=l.fsid,et[i+64>>2]=l.flags,et[i+56>>2]=l.namelen},doMsync(i,l,h,f,c){if(!y.isFile(l.node.mode))throw new y.ErrnoError(43);if(f&2)return 0;var d=Ar.slice(i,i+h);y.msync(l,d,c,h,f)},getStreamFromFD(i){return y.getStreamChecked(i)},varargs:void 0,getStr(i){return Fh(i)}};function Mh(i,l){try{return i=Be.getStr(i),y.chmod(i,l),0}catch(h){if(typeof y>"u"||h.name!=="ErrnoError")throw h;return-h.errno}}function Bh(i,l,h,f){try{if(l=Be.getStr(l),l=Be.calculateAt(i,l),h&-8)return-28;var c=y.lookupPath(l,{follow:!0}).node;if(!c)return-44;var d="";if(h&4)d+="r";if(h&2)d+="w";if(h&1)d+="x";if(d&&y.nodePermissions(c,d))return-2;return 0}catch(p){if(typeof y>"u"||p.name!=="ErrnoError")throw p;return-p.errno}}function Uh(i,l){try{return y.fchmod(i,l),0}catch(h){if(typeof y>"u"||h.name!=="ErrnoError")throw h;return-h.errno}}function jh(i,l,h){try{return y.fchown(i,l,h),0}catch(f){if(typeof y>"u"||f.name!=="ErrnoError")throw f;return-f.errno}}var ho=()=>{var i=Je[+Be.varargs>>2];return Be.varargs+=4,i},Yr=ho;function Hh(i,l,h){Be.varargs=h;try{var f=Be.getStreamFromFD(i);switch(l){case 0:var c=ho();if(c<0)return-28;while(y.streams[c])c++;return y.dupStream(f,c).fd;case 1:case 2:return 0;case 3:return f.flags;case 4:var c=ho();return f.flags|=c,0;case 12:var c=Yr(),d=0;return On[c+d>>1]=2,0;case 13:case 14:return 0}return-28}catch(p){if(typeof y>"u"||p.name!=="ErrnoError")throw p;return-p.errno}}function Wh(i,l){try{return Be.writeStat(l,y.fstat(i))}catch(h){if(typeof y>"u"||h.name!=="ErrnoError")throw h;return-h.errno}}var Zh=9007199254740992,Gh=-9007199254740992,en=(i)=>i<Gh||i>Zh?NaN:Number(i);function Kh(i,l){l=en(l);try{if(isNaN(l))return-61;return y.ftruncate(i,l),0}catch(h){if(typeof y>"u"||h.name!=="ErrnoError")throw h;return-h.errno}}var Or=(i,l,h)=>hc(i,Ar,l,h);function Vh(i,l){try{if(l===0)return-28;var h=y.cwd(),f=go(h)+1;if(l<f)return-68;return Or(h,i,l),f}catch(c){if(typeof y>"u"||c.name!=="ErrnoError")throw c;return-c.errno}}function Jh(i,l,h){Be.varargs=h;try{var f=Be.getStreamFromFD(i);switch(l){case 21509:if(!f.tty)return-59;return 0;case 21505:if(!f.tty)return-59;if(f.tty.ops.ioctl_tcgets){var c=f.tty.ops.ioctl_tcgets(f),M=Yr();Je[M>>2]=c.c_iflag||0,Je[M+4>>2]=c.c_oflag||0,Je[M+8>>2]=c.c_cflag||0,Je[M+12>>2]=c.c_lflag||0;for(var d=0;d<32;d++)$t[M+d+17]=c.c_cc[d]||0;return 0}return 0;case 21510:case 21511:case 21512:if(!f.tty)return-59;return 0;case 21506:case 21507:case 21508:if(!f.tty)return-59;if(f.tty.ops.ioctl_tcsets){var M=Yr(),p=Je[M>>2],E=Je[M+4>>2],b=Je[M+8>>2],I=Je[M+12>>2],V=[];for(var d=0;d<32;d++)V.push($t[M+d+17]);return f.tty.ops.ioctl_tcsets(f.tty,l,{c_iflag:p,c_oflag:E,c_cflag:b,c_lflag:I,c_cc:V})}return 0;case 21519:if(!f.tty)return-59;var M=Yr();return Je[M>>2]=0,0;case 21520:if(!f.tty)return-59;return-28;case 21537:case 21531:var M=Yr();return y.ioctl(f,l,M);case 21523:if(!f.tty)return-59;if(f.tty.ops.ioctl_tiocgwinsz){var N=f.tty.ops.ioctl_tiocgwinsz(f.tty),M=Yr();On[M>>1]=N[0],On[M+2>>1]=N[1]}return 0;case 21524:if(!f.tty)return-59;return 0;case 21515:if(!f.tty)return-59;return 0;default:return-28}}catch(q){if(typeof y>"u"||q.name!=="ErrnoError")throw q;return-q.errno}}function Xh(i,l){try{return i=Be.getStr(i),Be.writeStat(l,y.lstat(i))}catch(h){if(typeof y>"u"||h.name!=="ErrnoError")throw h;return-h.errno}}function Qh(i,l,h){try{return l=Be.getStr(l),l=Be.calculateAt(i,l),y.mkdir(l,h,0),0}catch(f){if(typeof y>"u"||f.name!=="ErrnoError")throw f;return-f.errno}}function Yh(i,l,h,f){try{l=Be.getStr(l);var c=f&256,d=f&4096;return f=f&-6401,l=Be.calculateAt(i,l,d),Be.writeStat(h,c?y.lstat(l):y.stat(l))}catch(p){if(typeof y>"u"||p.name!=="ErrnoError")throw p;return-p.errno}}function em(i,l,h,f){Be.varargs=f;try{l=Be.getStr(l),l=Be.calculateAt(i,l);var c=f?ho():0;return y.open(l,h,c).fd}catch(d){if(typeof y>"u"||d.name!=="ErrnoError")throw d;return-d.errno}}function tm(i,l,h,f){try{if(l=Be.getStr(l),l=Be.calculateAt(i,l),f<=0)return-28;var c=y.readlink(l),d=Math.min(f,go(c)),p=$t[h+d];return Or(c,h,f+1),$t[h+d]=p,d}catch(E){if(typeof y>"u"||E.name!=="ErrnoError")throw E;return-E.errno}}function rm(i){try{return i=Be.getStr(i),y.rmdir(i),0}catch(l){if(typeof y>"u"||l.name!=="ErrnoError")throw l;return-l.errno}}function nm(i,l){try{return i=Be.getStr(i),Be.writeStat(l,y.stat(i))}catch(h){if(typeof y>"u"||h.name!=="ErrnoError")throw h;return-h.errno}}function om(i,l,h){try{if(l=Be.getStr(l),l=Be.calculateAt(i,l),!h)y.unlink(l);else if(h===512)y.rmdir(l);else return-28;return 0}catch(f){if(typeof y>"u"||f.name!=="ErrnoError")throw f;return-f.errno}}var Ec=(i)=>et[i>>2]+Je[i+4>>2]*4294967296;function im(i,l,h,f){try{l=Be.getStr(l),l=Be.calculateAt(i,l,!0);var c=Date.now(),d,p;if(!h)d=c,p=c;else{var E=Ec(h),b=Je[h+8>>2];if(b==1073741823)d=c;else if(b==1073741822)d=null;else d=E*1000+b/1e6;if(h+=16,E=Ec(h),b=Je[h+8>>2],b==1073741823)p=c;else if(b==1073741822)p=null;else p=E*1000+b/1e6}if((p??d)!==null)y.utime(l,d,p);return 0}catch(I){if(typeof y>"u"||I.name!=="ErrnoError")throw I;return-I.errno}}var sm=(i)=>i%4===0&&(i%100!==0||i%400===0),am=[0,31,60,91,121,152,182,213,244,274,305,335],cm=[0,31,59,90,120,151,181,212,243,273,304,334],lm=(i)=>(sm(i.getFullYear())?am:cm)[i.getMonth()]+i.getDate()-1;function um(i,l){i=en(i);var h=new Date(i*1000);Je[l>>2]=h.getSeconds(),Je[l+4>>2]=h.getMinutes(),Je[l+8>>2]=h.getHours(),Je[l+12>>2]=h.getDate(),Je[l+16>>2]=h.getMonth(),Je[l+20>>2]=h.getFullYear()-1900,Je[l+24>>2]=h.getDay();var f=lm(h)|0;Je[l+28>>2]=f,Je[l+36>>2]=-(h.getTimezoneOffset()*60);var c=new Date(h.getFullYear(),0,1),d=new Date(h.getFullYear(),6,1).getTimezoneOffset(),p=c.getTimezoneOffset(),E=(d!=p&&h.getTimezoneOffset()==Math.min(p,d))|0;Je[l+32>>2]=E}function dm(i,l,h,f,c,d,p){c=en(c);try{var E=Be.getStreamFromFD(f),b=y.mmap(E,i,c,l,h),I=b.ptr;return Je[d>>2]=b.allocated,et[p>>2]=I,0}catch(V){if(typeof y>"u"||V.name!=="ErrnoError")throw V;return-V.errno}}function fm(i,l,h,f,c,d){d=en(d);try{var p=Be.getStreamFromFD(c);if(h&2)Be.doMsync(i,p,l,f,d)}catch(E){if(typeof y>"u"||E.name!=="ErrnoError")throw E;return-E.errno}}var pm=(i,l,h,f)=>{var c=new Date().getFullYear(),d=new Date(c,0,1),p=new Date(c,6,1),E=d.getTimezoneOffset(),b=p.getTimezoneOffset(),I=Math.max(E,b);et[i>>2]=I*60,Je[l>>2]=Number(E!=b);var V=(q)=>{var H=q>=0?"-":"+",G=Math.abs(q);return`UTC${H}${String(Math.floor(G/60)).padStart(2,"0")}${String(G%60).padStart(2,"0")}`},M=V(E),N=V(b);if(b<E)Or(M,h,17),Or(N,f,17);else Or(M,f,17),Or(N,h,17)},Sc=()=>performance.now(),xc=()=>Date.now(),_m=1,gm=(i)=>i>=0&&i<=3;function hm(i,l,h){if(l=en(l),!gm(i))return 28;var f;if(i===0)f=xc();else if(_m)f=Sc();else return 52;var c=Math.round(f*1000*1000);return St[h>>3]=BigInt(c),0}var Tc=()=>2147483648,mm=()=>Tc(),ym=(i)=>{var l=(i-cr.buffer.byteLength+65535)/65536|0;try{return cr.grow(l),Ze(),1}catch(h){}},bm=(i)=>{var l=Ar.length;i>>>=0;var h=Tc();if(i>h)return!1;for(var f=1;f<=4;f*=2){var c=l*(1+0.2/f);if(c=Math.min(c,i+100663296),ym(Math.min(h,mc(Math.max(i,c),65536))))return!0}return!1},Ni={},wm=()=>s||"./this.program",Cn=()=>{if(!Cn.strings){var i={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(globalThis.navigator?.language??"C").replace("-","_")+".UTF-8",_:wm()};for(var l in Ni)if(Ni[l]===void 0)delete i[l];else i[l]=Ni[l];var h=[];for(var l in i)h.push(`${l}=${i[l]}`);Cn.strings=h}return Cn.strings},vm=(i,l)=>{var h=0,f=0;for(var c of Cn()){var d=l+h;et[i+f>>2]=d,h+=Or(c,d,1/0)+1,f+=4}return 0},Em=(i,l)=>{var h=Cn();et[i>>2]=h.length;var f=0;for(var c of h)f+=go(c)+1;return et[l>>2]=f,0};function Sm(i){try{var l=Be.getStreamFromFD(i);return y.close(l),0}catch(h){if(typeof y>"u"||h.name!=="ErrnoError")throw h;return h.errno}}function xm(i,l){try{var h=0,f=0,c=0,d=Be.getStreamFromFD(i),p=d.tty?2:y.isDir(d.mode)?3:y.isLink(d.mode)?7:4;return $t[l]=p,On[l+2>>1]=c,St[l+8>>3]=BigInt(h),St[l+16>>3]=BigInt(f),0}catch(E){if(typeof y>"u"||E.name!=="ErrnoError")throw E;return E.errno}}var Tm=(i,l,h,f)=>{var c=0;for(var d=0;d<h;d++){var p=et[l>>2],E=et[l+4>>2];l+=8;var b=y.read(i,$t,p,E,f);if(b<0)return-1;if(c+=b,b<E)break;if(typeof f<"u")f+=b}return c};function km(i,l,h,f){try{var c=Tm(Be.getStreamFromFD(i),l,h);return et[f>>2]=c,0}catch(d){if(typeof y>"u"||d.name!=="ErrnoError")throw d;return d.errno}}function Rm(i,l,h,f){l=en(l);try{if(isNaN(l))return 61;var c=Be.getStreamFromFD(i);if(y.llseek(c,l,h),St[f>>3]=BigInt(c.position),c.getdents&&l===0&&h===0)c.getdents=null;return 0}catch(d){if(typeof y>"u"||d.name!=="ErrnoError")throw d;return d.errno}}function Am(i){try{var l=Be.getStreamFromFD(i);return l.stream_ops?.fsync?.(l)}catch(h){if(typeof y>"u"||h.name!=="ErrnoError")throw h;return h.errno}}var Dm=(i,l,h,f)=>{var c=0;for(var d=0;d<h;d++){var p=et[l>>2],E=et[l+4>>2];l+=8;var b=y.write(i,$t,p,E,f);if(b<0)return-1;if(c+=b,b<E)break;if(typeof f<"u")f+=b}return c};function Om(i,l,h,f){try{var c=Dm(Be.getStreamFromFD(i),l,h);return et[f>>2]=c,0}catch(d){if(typeof y>"u"||d.name!=="ErrnoError")throw d;return d.errno}}if(y.createPreloadedFile=zh,y.preloadFile=vc,y.staticInit(),$e(),r.noExitRuntime)r.noExitRuntime;if(r.preloadPlugins)wc=r.preloadPlugins;if(r.print)D=r.print;if(r.printErr)j=r.printErr;if(r.wasmBinary)Y=r.wasmBinary;if(r.arguments)r.arguments;if(r.thisProgram)s=r.thisProgram;if(r.preInit){if(typeof r.preInit=="function")r.preInit=[r.preInit];while(r.preInit.length>0)r.preInit.shift()()}r.wasmMemory=cr;var kc;function Im(i){r._sqlite3_status64=i.sqlite3_status64,r._sqlite3_status=i.sqlite3_status,r._sqlite3_db_status64=i.sqlite3_db_status64,r._sqlite3_msize=i.sqlite3_msize,r._sqlite3_db_status=i.sqlite3_db_status,r._sqlite3_vfs_find=i.sqlite3_vfs_find,r._sqlite3_initialize=i.sqlite3_initialize,r._sqlite3_malloc=i.sqlite3_malloc,r._sqlite3_free=i.sqlite3_free,r._sqlite3_vfs_register=i.sqlite3_vfs_register,r._sqlite3_vfs_unregister=i.sqlite3_vfs_unregister,r._sqlite3_malloc64=i.sqlite3_malloc64,r._sqlite3_realloc=i.sqlite3_realloc,r._sqlite3_realloc64=i.sqlite3_realloc64,r._sqlite3_value_text=i.sqlite3_value_text,r._sqlite3_randomness=i.sqlite3_randomness,r._sqlite3_stricmp=i.sqlite3_stricmp,r._sqlite3_strnicmp=i.sqlite3_strnicmp,r._sqlite3_uri_parameter=i.sqlite3_uri_parameter,r._sqlite3_uri_boolean=i.sqlite3_uri_boolean,r._sqlite3_serialize=i.sqlite3_serialize,r._sqlite3_prepare_v2=i.sqlite3_prepare_v2,r._sqlite3_step=i.sqlite3_step,r._sqlite3_column_int64=i.sqlite3_column_int64,r._sqlite3_reset=i.sqlite3_reset,r._sqlite3_exec=i.sqlite3_exec,r._sqlite3_column_int=i.sqlite3_column_int,r._sqlite3_finalize=i.sqlite3_finalize,r._sqlite3_file_control=i.sqlite3_file_control,r._sqlite3_column_name=i.sqlite3_column_name,r._sqlite3_column_text=i.sqlite3_column_text,r._sqlite3_column_type=i.sqlite3_column_type,r._sqlite3_errmsg=i.sqlite3_errmsg,r._sqlite3_deserialize=i.sqlite3_deserialize,r._sqlite3_clear_bindings=i.sqlite3_clear_bindings,r._sqlite3_value_blob=i.sqlite3_value_blob,r._sqlite3_value_bytes=i.sqlite3_value_bytes,r._sqlite3_value_double=i.sqlite3_value_double,r._sqlite3_value_int=i.sqlite3_value_int,r._sqlite3_value_int64=i.sqlite3_value_int64,r._sqlite3_value_subtype=i.sqlite3_value_subtype,r._sqlite3_value_pointer=i.sqlite3_value_pointer,r._sqlite3_value_type=i.sqlite3_value_type,r._sqlite3_value_nochange=i.sqlite3_value_nochange,r._sqlite3_value_frombind=i.sqlite3_value_frombind,r._sqlite3_value_dup=i.sqlite3_value_dup,r._sqlite3_value_free=i.sqlite3_value_free,r._sqlite3_result_blob=i.sqlite3_result_blob,r._sqlite3_result_error_toobig=i.sqlite3_result_error_toobig,r._sqlite3_result_error_nomem=i.sqlite3_result_error_nomem,r._sqlite3_result_double=i.sqlite3_result_double,r._sqlite3_result_error=i.sqlite3_result_error,r._sqlite3_result_int=i.sqlite3_result_int,r._sqlite3_result_int64=i.sqlite3_result_int64,r._sqlite3_result_null=i.sqlite3_result_null,r._sqlite3_result_pointer=i.sqlite3_result_pointer,r._sqlite3_result_subtype=i.sqlite3_result_subtype,r._sqlite3_result_text=i.sqlite3_result_text,r._sqlite3_result_zeroblob=i.sqlite3_result_zeroblob,r._sqlite3_result_zeroblob64=i.sqlite3_result_zeroblob64,r._sqlite3_result_error_code=i.sqlite3_result_error_code,r._sqlite3_user_data=i.sqlite3_user_data,r._sqlite3_context_db_handle=i.sqlite3_context_db_handle,r._sqlite3_vtab_nochange=i.sqlite3_vtab_nochange,r._sqlite3_vtab_in_first=i.sqlite3_vtab_in_first,r._sqlite3_vtab_in_next=i.sqlite3_vtab_in_next,r._sqlite3_aggregate_context=i.sqlite3_aggregate_context,r._sqlite3_get_auxdata=i.sqlite3_get_auxdata,r._sqlite3_set_auxdata=i.sqlite3_set_auxdata,r._sqlite3_column_count=i.sqlite3_column_count,r._sqlite3_data_count=i.sqlite3_data_count,r._sqlite3_column_blob=i.sqlite3_column_blob,r._sqlite3_column_bytes=i.sqlite3_column_bytes,r._sqlite3_column_double=i.sqlite3_column_double,r._sqlite3_column_value=i.sqlite3_column_value,r._sqlite3_column_decltype=i.sqlite3_column_decltype,r._sqlite3_column_database_name=i.sqlite3_column_database_name,r._sqlite3_column_table_name=i.sqlite3_column_table_name,r._sqlite3_column_origin_name=i.sqlite3_column_origin_name,r._sqlite3_bind_blob=i.sqlite3_bind_blob,r._sqlite3_bind_double=i.sqlite3_bind_double,r._sqlite3_bind_int=i.sqlite3_bind_int,r._sqlite3_bind_int64=i.sqlite3_bind_int64,r._sqlite3_bind_null=i.sqlite3_bind_null,r._sqlite3_bind_pointer=i.sqlite3_bind_pointer,r._sqlite3_bind_text=i.sqlite3_bind_text,r._sqlite3_bind_zeroblob=i.sqlite3_bind_zeroblob,r._sqlite3_bind_parameter_count=i.sqlite3_bind_parameter_count,r._sqlite3_bind_parameter_name=i.sqlite3_bind_parameter_name,r._sqlite3_bind_parameter_index=i.sqlite3_bind_parameter_index,r._sqlite3_db_handle=i.sqlite3_db_handle,r._sqlite3_stmt_readonly=i.sqlite3_stmt_readonly,r._sqlite3_stmt_isexplain=i.sqlite3_stmt_isexplain,r._sqlite3_stmt_explain=i.sqlite3_stmt_explain,r._sqlite3_stmt_busy=i.sqlite3_stmt_busy,r._sqlite3_next_stmt=i.sqlite3_next_stmt,r._sqlite3_stmt_status=i.sqlite3_stmt_status,r._sqlite3_sql=i.sqlite3_sql,r._sqlite3_expanded_sql=i.sqlite3_expanded_sql,r._sqlite3_preupdate_old=i.sqlite3_preupdate_old,r._sqlite3_preupdate_count=i.sqlite3_preupdate_count,r._sqlite3_preupdate_depth=i.sqlite3_preupdate_depth,r._sqlite3_preupdate_blobwrite=i.sqlite3_preupdate_blobwrite,r._sqlite3_preupdate_new=i.sqlite3_preupdate_new,r._sqlite3_value_numeric_type=i.sqlite3_value_numeric_type,r._sqlite3_set_authorizer=i.sqlite3_set_authorizer,r._sqlite3_strglob=i.sqlite3_strglob,r._sqlite3_strlike=i.sqlite3_strlike,r._sqlite3_auto_extension=i.sqlite3_auto_extension,r._sqlite3_cancel_auto_extension=i.sqlite3_cancel_auto_extension,r._sqlite3_reset_auto_extension=i.sqlite3_reset_auto_extension,r._sqlite3_prepare_v3=i.sqlite3_prepare_v3,r._sqlite3_create_module=i.sqlite3_create_module,r._sqlite3_create_module_v2=i.sqlite3_create_module_v2,r._sqlite3_drop_modules=i.sqlite3_drop_modules,r._sqlite3_declare_vtab=i.sqlite3_declare_vtab,r._sqlite3_vtab_on_conflict=i.sqlite3_vtab_on_conflict,r._sqlite3_vtab_collation=i.sqlite3_vtab_collation,r._sqlite3_vtab_in=i.sqlite3_vtab_in,r._sqlite3_vtab_rhs_value=i.sqlite3_vtab_rhs_value,r._sqlite3_vtab_distinct=i.sqlite3_vtab_distinct,r._sqlite3_keyword_name=i.sqlite3_keyword_name,r._sqlite3_keyword_count=i.sqlite3_keyword_count,r._sqlite3_keyword_check=i.sqlite3_keyword_check,r._sqlite3_complete=i.sqlite3_complete,r._sqlite3_libversion=i.sqlite3_libversion,r._sqlite3_libversion_number=i.sqlite3_libversion_number,r._sqlite3_shutdown=i.sqlite3_shutdown,r._sqlite3_last_insert_rowid=i.sqlite3_last_insert_rowid,r._sqlite3_set_last_insert_rowid=i.sqlite3_set_last_insert_rowid,r._sqlite3_changes64=i.sqlite3_changes64,r._sqlite3_changes=i.sqlite3_changes,r._sqlite3_total_changes64=i.sqlite3_total_changes64,r._sqlite3_total_changes=i.sqlite3_total_changes,r._sqlite3_txn_state=i.sqlite3_txn_state,r._sqlite3_close_v2=i.sqlite3_close_v2,r._sqlite3_busy_handler=i.sqlite3_busy_handler,r._sqlite3_progress_handler=i.sqlite3_progress_handler,r._sqlite3_busy_timeout=i.sqlite3_busy_timeout,r._sqlite3_interrupt=i.sqlite3_interrupt,r._sqlite3_is_interrupted=i.sqlite3_is_interrupted,r._sqlite3_create_function=i.sqlite3_create_function,r._sqlite3_create_function_v2=i.sqlite3_create_function_v2,r._sqlite3_create_window_function=i.sqlite3_create_window_function,r._sqlite3_overload_function=i.sqlite3_overload_function,r._sqlite3_trace_v2=i.sqlite3_trace_v2,r._sqlite3_commit_hook=i.sqlite3_commit_hook,r._sqlite3_update_hook=i.sqlite3_update_hook,r._sqlite3_rollback_hook=i.sqlite3_rollback_hook,r._sqlite3_preupdate_hook=i.sqlite3_preupdate_hook,r._sqlite3_set_errmsg=i.sqlite3_set_errmsg,r._sqlite3_error_offset=i.sqlite3_error_offset,r._sqlite3_errcode=i.sqlite3_errcode,r._sqlite3_extended_errcode=i.sqlite3_extended_errcode,r._sqlite3_errstr=i.sqlite3_errstr,r._sqlite3_limit=i.sqlite3_limit,r._sqlite3_open=i.sqlite3_open,r._sqlite3_open_v2=i.sqlite3_open_v2,r._sqlite3_create_collation=i.sqlite3_create_collation,r._sqlite3_create_collation_v2=i.sqlite3_create_collation_v2,r._sqlite3_collation_needed=i.sqlite3_collation_needed,r._sqlite3_get_autocommit=i.sqlite3_get_autocommit,r._sqlite3_table_column_metadata=i.sqlite3_table_column_metadata,r._sqlite3_extended_result_codes=i.sqlite3_extended_result_codes,r._sqlite3_uri_key=i.sqlite3_uri_key,r._sqlite3_uri_int64=i.sqlite3_uri_int64,r._sqlite3_db_name=i.sqlite3_db_name,r._sqlite3_db_filename=i.sqlite3_db_filename,r._sqlite3_db_readonly=i.sqlite3_db_readonly,r._sqlite3_compileoption_used=i.sqlite3_compileoption_used,r._sqlite3_compileoption_get=i.sqlite3_compileoption_get,r._sqlite3session_diff=i.sqlite3session_diff,r._sqlite3session_attach=i.sqlite3session_attach,r._sqlite3session_create=i.sqlite3session_create,r._sqlite3session_delete=i.sqlite3session_delete,r._sqlite3session_table_filter=i.sqlite3session_table_filter,r._sqlite3session_changeset=i.sqlite3session_changeset,r._sqlite3session_changeset_strm=i.sqlite3session_changeset_strm,r._sqlite3session_patchset_strm=i.sqlite3session_patchset_strm,r._sqlite3session_patchset=i.sqlite3session_patchset,r._sqlite3session_enable=i.sqlite3session_enable,r._sqlite3session_indirect=i.sqlite3session_indirect,r._sqlite3session_isempty=i.sqlite3session_isempty,r._sqlite3session_memory_used=i.sqlite3session_memory_used,r._sqlite3session_object_config=i.sqlite3session_object_config,r._sqlite3session_changeset_size=i.sqlite3session_changeset_size,r._sqlite3changeset_start=i.sqlite3changeset_start,r._sqlite3changeset_start_v2=i.sqlite3changeset_start_v2,r._sqlite3changeset_start_strm=i.sqlite3changeset_start_strm,r._sqlite3changeset_start_v2_strm=i.sqlite3changeset_start_v2_strm,r._sqlite3changeset_next=i.sqlite3changeset_next,r._sqlite3changeset_op=i.sqlite3changeset_op,r._sqlite3changeset_pk=i.sqlite3changeset_pk,r._sqlite3changeset_old=i.sqlite3changeset_old,r._sqlite3changeset_new=i.sqlite3changeset_new,r._sqlite3changeset_conflict=i.sqlite3changeset_conflict,r._sqlite3changeset_fk_conflicts=i.sqlite3changeset_fk_conflicts,r._sqlite3changeset_finalize=i.sqlite3changeset_finalize,r._sqlite3changeset_invert=i.sqlite3changeset_invert,r._sqlite3changeset_invert_strm=i.sqlite3changeset_invert_strm,r._sqlite3changeset_apply_v2=i.sqlite3changeset_apply_v2,r._sqlite3changeset_apply_v3=i.sqlite3changeset_apply_v3,r._sqlite3changeset_apply=i.sqlite3changeset_apply,r._sqlite3changeset_apply_v3_strm=i.sqlite3changeset_apply_v3_strm,r._sqlite3changeset_apply_v2_strm=i.sqlite3changeset_apply_v2_strm,r._sqlite3changeset_apply_strm=i.sqlite3changeset_apply_strm,r._sqlite3changegroup_new=i.sqlite3changegroup_new,r._sqlite3changegroup_add=i.sqlite3changegroup_add,r._sqlite3changegroup_output=i.sqlite3changegroup_output,r._sqlite3changegroup_add_strm=i.sqlite3changegroup_add_strm,r._sqlite3changegroup_output_strm=i.sqlite3changegroup_output_strm,r._sqlite3changegroup_delete=i.sqlite3changegroup_delete,r._sqlite3changeset_concat=i.sqlite3changeset_concat,r._sqlite3changeset_concat_strm=i.sqlite3changeset_concat_strm,r._sqlite3session_config=i.sqlite3session_config,r._sqlite3_sourceid=i.sqlite3_sourceid,r._sqlite3__wasm_pstack_ptr=i.sqlite3__wasm_pstack_ptr,r._sqlite3__wasm_pstack_restore=i.sqlite3__wasm_pstack_restore,r._sqlite3__wasm_pstack_alloc=i.sqlite3__wasm_pstack_alloc,r._sqlite3__wasm_pstack_remaining=i.sqlite3__wasm_pstack_remaining,r._sqlite3__wasm_pstack_quota=i.sqlite3__wasm_pstack_quota,r._sqlite3__wasm_test_struct=i.sqlite3__wasm_test_struct,r._sqlite3__wasm_enum_json=i.sqlite3__wasm_enum_json,r._sqlite3__wasm_vfs_unlink=i.sqlite3__wasm_vfs_unlink,r._sqlite3__wasm_db_vfs=i.sqlite3__wasm_db_vfs,r._sqlite3__wasm_db_reset=i.sqlite3__wasm_db_reset,r._sqlite3__wasm_db_export_chunked=i.sqlite3__wasm_db_export_chunked,r._sqlite3__wasm_db_serialize=i.sqlite3__wasm_db_serialize,r._sqlite3__wasm_vfs_create_file=i.sqlite3__wasm_vfs_create_file,r._sqlite3__wasm_posix_create_file=i.sqlite3__wasm_posix_create_file,r._sqlite3__wasm_kvvfsMakeKey=i.sqlite3__wasm_kvvfsMakeKey,r._sqlite3__wasm_kvvfs_methods=i.sqlite3__wasm_kvvfs_methods,r._sqlite3__wasm_vtab_config=i.sqlite3__wasm_vtab_config,r._sqlite3__wasm_db_config_ip=i.sqlite3__wasm_db_config_ip,r._sqlite3__wasm_db_config_pii=i.sqlite3__wasm_db_config_pii,r._sqlite3__wasm_db_config_s=i.sqlite3__wasm_db_config_s,r._sqlite3__wasm_config_i=i.sqlite3__wasm_config_i,r._sqlite3__wasm_config_ii=i.sqlite3__wasm_config_ii,r._sqlite3__wasm_config_j=i.sqlite3__wasm_config_j,r._sqlite3__wasm_qfmt_token=i.sqlite3__wasm_qfmt_token,r._sqlite3__wasm_kvvfs_decode=i.sqlite3__wasm_kvvfs_decode,r._sqlite3__wasm_kvvfs_encode=i.sqlite3__wasm_kvvfs_encode,r._sqlite3__wasm_init_wasmfs=i.sqlite3__wasm_init_wasmfs,r._sqlite3__wasm_test_intptr=i.sqlite3__wasm_test_intptr,r._sqlite3__wasm_test_voidptr=i.sqlite3__wasm_test_voidptr,r._sqlite3__wasm_test_int64_max=i.sqlite3__wasm_test_int64_max,r._sqlite3__wasm_test_int64_min=i.sqlite3__wasm_test_int64_min,r._sqlite3__wasm_test_int64_times2=i.sqlite3__wasm_test_int64_times2,r._sqlite3__wasm_test_int64_minmax=i.sqlite3__wasm_test_int64_minmax,r._sqlite3__wasm_test_int64ptr=i.sqlite3__wasm_test_int64ptr,r._sqlite3__wasm_test_stack_overflow=i.sqlite3__wasm_test_stack_overflow,r._sqlite3__wasm_test_str_hello=i.sqlite3__wasm_test_str_hello,r._sqlite3__wasm_SQLTester_strglob=i.sqlite3__wasm_SQLTester_strglob,r._malloc=i.malloc,r._free=i.free,r._realloc=i.realloc,kc=i.emscripten_builtin_memalign,i._emscripten_stack_restore,i._emscripten_stack_alloc,i.emscripten_stack_get_current,i.__indirect_function_table}var Rc={__syscall_chmod:Mh,__syscall_faccessat:Bh,__syscall_fchmod:Uh,__syscall_fchown32:jh,__syscall_fcntl64:Hh,__syscall_fstat64:Wh,__syscall_ftruncate64:Kh,__syscall_getcwd:Vh,__syscall_ioctl:Jh,__syscall_lstat64:Xh,__syscall_mkdirat:Qh,__syscall_newfstatat:Yh,__syscall_openat:em,__syscall_readlinkat:tm,__syscall_rmdir:rm,__syscall_stat64:nm,__syscall_unlinkat:om,__syscall_utimensat:im,_localtime_js:um,_mmap_js:dm,_munmap_js:fm,_tzset_js:pm,clock_time_get:hm,emscripten_date_now:xc,emscripten_get_heap_max:mm,emscripten_get_now:Sc,emscripten_resize_heap:bm,environ_get:vm,environ_sizes_get:Em,fd_close:Sm,fd_fdstat_get:xm,fd_read:km,fd_seek:Rm,fd_sync:Am,fd_write:Om,memory:cr};function qi(){if(Dr>0){Pn=qi;return}if(Ue(),Dr>0){Pn=qi;return}function i(){if(r.calledRun=!0,_e)return;tt(),de?.(r),r.onRuntimeInitialized?.(),Rr()}if(r.setStatus)r.setStatus("Running..."),setTimeout(()=>{setTimeout(()=>r.setStatus(""),1),i()},1);else i()}var tn=await vh();if(qi(),r.runSQLite3PostLoadInit=async function(i,l,h){delete l.runSQLite3PostLoadInit,globalThis.sqlite3ApiBootstrap=async function f(c=globalThis.sqlite3ApiConfig||f.defaultConfig){if(f.sqlite3)return(f.sqlite3.config||console).warn("sqlite3ApiBootstrap() called multiple times.","Config and external initializers are ignored on calls after the first."),f.sqlite3;let d=(...S)=>Object.assign(Object.create(null),...S),p=d({exports:void 0,memory:void 0,bigIntEnabled:!!globalThis.BigInt64Array,debug:console.debug.bind(console),warn:console.warn.bind(console),error:console.error.bind(console),log:console.log.bind(console),wasmfsOpfsDir:"/opfs",useStdAlloc:!1},c);Object.assign(p,{allocExportName:p.useStdAlloc?"malloc":"sqlite3_malloc",deallocExportName:p.useStdAlloc?"free":"sqlite3_free",reallocExportName:p.useStdAlloc?"realloc":"sqlite3_realloc"}),["exports","memory","functionTable","wasmfsOpfsDir"].forEach((S)=>{if(typeof p[S]==="function")p[S]=p[S]()});let E=d(),b=d(),I=(S)=>E.sqlite3_js_rc_str&&E.sqlite3_js_rc_str(S)||"Unknown result code #"+S,V=(S)=>typeof S==="number"&&S===(S|0)&&S<=2147483647&&S>=-2147483648;class M extends Error{constructor(...S){let P;if(S.length)if(V(S[0]))if(P=S[0],S.length===1)super(I(S[0]));else{let K=I(P);if(typeof S[1]==="object")super(K,S[1]);else{S[0]=K+":";super(S.join(" "))}}else if(S.length===2&&typeof S[1]==="object")super(...S);else super(S.join(" "));this.resultCode=P||E.SQLITE_ERROR,this.name="SQLite3Error"}}M.toss=(...S)=>{throw new M(...S)};let N=M.toss;if(p.wasmfsOpfsDir&&!/^\/[^/]+$/.test(p.wasmfsOpfsDir))N("config.wasmfsOpfsDir must be falsy or in the form '/dir-name'.");let q=function S(P){if(!S._max)S._max=BigInt("0x7fffffffffffffff"),S._min=~S._max;return P>=S._min&&P<=S._max},H=(S)=>S>=-2147483647n-1n&&S<=2147483647n,G=function S(P){if(!S._min)S._min=Number.MIN_SAFE_INTEGER,S._max=Number.MAX_SAFE_INTEGER;return P>=S._min&&P<=S._max},le=(S)=>S&&S.constructor&&V(S.constructor.BYTES_PER_ELEMENT)?S:!1,O=(S)=>S&&(S instanceof Uint8Array||S instanceof Int8Array||S instanceof ArrayBuffer),R=(S)=>S&&(S instanceof Uint8Array||S instanceof Int8Array||S instanceof ArrayBuffer),X=(S)=>O(S)||N("Value is not of a supported TypedArray type."),ee=function(S){if(R(S))return b.typedArrayToString(S instanceof ArrayBuffer?new Uint8Array(S):S,0,S.length);else if(Array.isArray(S))return S.join("");else if(b.isPtr(S))S=b.cstrToJs(S);return S};class U extends Error{constructor(...S){if(S.length===2&&typeof S[1]==="object")super(...S);else if(S.length)super(S.join(" "));else super("Allocation failed.");this.resultCode=E.SQLITE_NOMEM,this.name="WasmAllocError"}}U.toss=(...S)=>{throw new U(...S)},Object.assign(E,{sqlite3_bind_blob:void 0,sqlite3_bind_text:void 0,sqlite3_create_function_v2:(S,P,K,oe,W,he,be,me,ve)=>{},sqlite3_create_function:(S,P,K,oe,W,he,be,me)=>{},sqlite3_create_window_function:(S,P,K,oe,W,he,be,me,ve,z)=>{},sqlite3_prepare_v3:(S,P,K,oe,W,he)=>{},sqlite3_prepare_v2:(S,P,K,oe,W)=>{},sqlite3_exec:(S,P,K,oe,W)=>{},sqlite3_randomness:(S,P)=>{}});let J={affirmBindableTypedArray:X,flexibleString:ee,bigIntFits32:H,bigIntFits64:q,bigIntFitsDouble:G,isBindableTypedArray:O,isInt32:V,isSQLableTypedArray:R,isTypedArray:le,isUIThread:()=>globalThis.window===globalThis&&!!globalThis.document,toss:function(...S){throw Error(S.join(" "))},toss3:N,typedArrayPart:b.typedArrayPart,nu:d,assert:function(S,P){if(!S)J.toss("Assertion failed:",P)},affirmDbHeader:function(S){if(S instanceof ArrayBuffer)S=new Uint8Array(S);let P="SQLite format 3";if(15>S.byteLength)N("Input does not contain an SQLite3 database header.");for(let K=0;K<15;++K)if(P.charCodeAt(K)!==S[K])N("Input does not contain an SQLite3 database header.")},affirmIsDb:function(S){if(S instanceof ArrayBuffer)S=new Uint8Array(S);let P=S.byteLength;if(P<512||P%512!==0)N("Byte array size",P,"is invalid for an SQLite3 db.");J.affirmDbHeader(S)}};Object.assign(b,{exports:p.exports||N("Missing API config.exports (WASM module exports)."),memory:p.memory||p.exports.memory||N("API config object requires a WebAssembly.Memory object","in either config.exports.memory (exported)","or config.memory (imported)."),pointerSize:typeof p.exports.sqlite3_libversion()==="number"?4:8,bigIntEnabled:!!p.bigIntEnabled,functionTable:p.functionTable,alloc:void 0,realloc:void 0,dealloc:void 0}),b.allocFromTypedArray=function(S){if(S instanceof ArrayBuffer)S=new Uint8Array(S);X(S);let P=b.alloc(S.byteLength||1);return b.heapForSize(S.constructor).set(S.byteLength?S:[0],Number(P)),P};{let{allocExportName:S,deallocExportName:P,reallocExportName:K}=p;for(let oe of[S,P,K])if(!(b.exports[oe]instanceof Function))N("Missing required exports[",oe,"] function.");b.alloc=function oe(W){return oe.impl(W)||U.toss("Failed to allocate",W," bytes.")},b.alloc.impl=b.exports[S],b.realloc=function oe(W,he){let be=oe.impl(b.ptr.coerce(W),he);return he?be||U.toss("Failed to reallocate",he," bytes."):b.ptr.null},b.realloc.impl=b.exports[K],b.dealloc=function oe(W){oe.impl(b.ptr.coerce(W))},b.dealloc.impl=b.exports[P]}b.compileOptionUsed=function S(P){if(!arguments.length){if(S._result)return S._result;else if(!S._opt)S._rx=/^([^=]+)=(.+)/,S._rxInt=/^-?\d+$/,S._opt=function(be,me){let ve=S._rx.exec(be);me[0]=ve?ve[1]:be,me[1]=ve?S._rxInt.test(ve[2])?+ve[2]:ve[2]:!0};let K=d(),oe=[0,0],W=0,he;while(he=E.sqlite3_compileoption_get(W++))S._opt(he,oe),K[oe[0]]=oe[1];return S._result=K}else if(Array.isArray(P)){let K=d();return P.forEach((oe)=>{K[oe]=E.sqlite3_compileoption_used(oe)}),K}else if(typeof P==="object")return Object.keys(P).forEach((K)=>{P[K]=E.sqlite3_compileoption_used(K)}),P;return typeof P==="string"?!!E.sqlite3_compileoption_used(P):!1},b.pstack=d({restore:b.exports.sqlite3__wasm_pstack_restore,alloc:function(S){if(typeof S==="string"&&!(S=b.sizeofIR(S)))U.toss("Invalid value for pstack.alloc(",arguments[0],")");return b.exports.sqlite3__wasm_pstack_alloc(S)||U.toss("Could not allocate",S,"bytes from the pstack.")},allocChunks:function(S,P){if(typeof P==="string"&&!(P=b.sizeofIR(P)))U.toss("Invalid size value for allocChunks(",arguments[1],")");let K=b.pstack.alloc(S*P),oe=[K],W=1,he=P;for(;W<S;++W,he+=P)oe.push(b.ptr.add(K,he));return oe},allocPtr:(S=1,P=!0)=>S===1?b.pstack.alloc(P?8:b.ptr.size):b.pstack.allocChunks(S,P?8:b.ptr.size),call:function(S){let P=b.pstack.pointer;try{return S(pe)}finally{b.pstack.restore(P)}}}),Object.defineProperties(b.pstack,{pointer:{configurable:!1,iterable:!0,writeable:!1,get:b.exports.sqlite3__wasm_pstack_ptr},quota:{configurable:!1,iterable:!0,writeable:!1,get:b.exports.sqlite3__wasm_pstack_quota},remaining:{configurable:!1,iterable:!0,writeable:!1,get:b.exports.sqlite3__wasm_pstack_remaining}}),E.sqlite3_randomness=(...S)=>{if(S.length===1&&J.isTypedArray(S[0])&&S[0].BYTES_PER_ELEMENT===1){let P=S[0];if(P.byteLength===0)return b.exports.sqlite3_randomness(0,b.ptr.null),P;let K=b.pstack.pointer;try{let oe=P.byteLength,W=0,he=b.exports.sqlite3_randomness,be=b.heap8u(),me=oe<512?oe:512,ve=b.pstack.alloc(me);do{let z=oe>me?me:oe;he(z,ve),P.set(b.typedArrayPart(be,ve,b.ptr.add(ve,z)),W),oe-=z,W+=z}while(oe>0)}catch(oe){p.error("Highly unexpected (and ignored!) exception in sqlite3_randomness():",oe)}finally{b.pstack.restore(K)}return P}b.exports.sqlite3_randomness(...S)},E.sqlite3_wasmfs_opfs_dir=function(){if(this.dir!==void 0)return this.dir;let S=p.wasmfsOpfsDir;if(!S||!globalThis.FileSystemHandle||!globalThis.FileSystemDirectoryHandle||!globalThis.FileSystemFileHandle||!b.exports.sqlite3__wasm_init_wasmfs)return this.dir="";try{if(S&&b.xCallWrapped("sqlite3__wasm_init_wasmfs","i32",["string"],S)===0)return this.dir=S;else return this.dir=""}catch(P){return this.dir=""}}.bind(d()),E.sqlite3_wasmfs_filename_is_persistent=function(S){let P=E.sqlite3_wasmfs_opfs_dir();return P&&S?S.startsWith(P+"/"):!1},E.sqlite3_js_db_uses_vfs=function(S,P,K=0){try{let oe=E.sqlite3_vfs_find(P);if(!oe)return!1;else if(!S)return oe===E.sqlite3_vfs_find(0)?oe:!1;else return oe===E.sqlite3_js_db_vfs(S,K)?oe:!1}catch(oe){return!1}},E.sqlite3_js_vfs_list=function(){let S=[],P=E.sqlite3_vfs_find(b.ptr.null);while(P){let K=new E.sqlite3_vfs(P);S.push(b.cstrToJs(K.$zName)),P=K.$pNext,K.dispose()}return S},E.sqlite3_js_db_export=function(S,P=0){if(S=b.xWrap.testConvertArg("sqlite3*",S),!S)N("Invalid sqlite3* argument.");if(!b.bigIntEnabled)N("BigInt support is not enabled.");let K=b.scopedAllocPush(),oe;try{let W=b.scopedAlloc(8+b.ptr.size),he=b.ptr.add(W,8),be=P?b.isPtr(P)?P:b.scopedAllocCString(""+P):b.ptr.null,me=b.exports.sqlite3__wasm_db_serialize(S,be,he,W,0);if(me)N("Database serialization failed with code",pe.capi.sqlite3_js_rc_str(me));oe=b.peekPtr(he);let ve=b.peek(W,"i64");return me=ve?b.heap8u().slice(Number(oe),Number(oe)+Number(ve)):new Uint8Array,me}finally{if(oe)b.exports.sqlite3_free(oe);b.scopedAllocPop(K)}},E.sqlite3_js_db_vfs=(S,P=b.ptr.null)=>J.sqlite3__wasm_db_vfs(S,P),E.sqlite3_js_aggregate_context=(S,P)=>E.sqlite3_aggregate_context(S,P)||(P?U.toss("Cannot allocate",P,"bytes for sqlite3_aggregate_context()"):0),E.sqlite3_js_posix_create_file=function(S,P,K){let oe;if(P&&b.isPtr(P))oe=P;else if(P instanceof ArrayBuffer||P instanceof Uint8Array){if(oe=b.allocFromTypedArray(P),arguments.length<3||!J.isInt32(K)||K<0)K=P.byteLength}else M.toss("Invalid 2nd argument for sqlite3_js_posix_create_file().");try{if(!J.isInt32(K)||K<0)M.toss("Invalid 3rd argument for sqlite3_js_posix_create_file().");let W=J.sqlite3__wasm_posix_create_file(S,oe,K);if(W)M.toss("Creation of file failed with sqlite3 result code",E.sqlite3_js_rc_str(W))}finally{if(oe&&oe!==P)b.dealloc(oe)}},E.sqlite3_js_vfs_create_file=function(S,P,K,oe){p.warn("sqlite3_js_vfs_create_file() is deprecated and","should be avoided because it can lead to C-level crashes.","See its documentation for alternatives.");let W;if(K)if(b.isPtr(K))W=K;else{if(K instanceof ArrayBuffer)K=new Uint8Array(K);if(K instanceof Uint8Array){if(W=b.allocFromTypedArray(K),arguments.length<4||!J.isInt32(oe)||oe<0)oe=K.byteLength}else M.toss("Invalid 3rd argument type for sqlite3_js_vfs_create_file().")}else W=0;if(!J.isInt32(oe)||oe<0){if(W&&W!==K)b.dealloc(W);M.toss("Invalid 4th argument for sqlite3_js_vfs_create_file().")}try{let he=J.sqlite3__wasm_vfs_create_file(S,P,W,oe);if(he)M.toss("Creation of file failed with sqlite3 result code",E.sqlite3_js_rc_str(he))}finally{if(W&&W!==K)b.dealloc(W)}},E.sqlite3_js_sql_to_string=(S)=>{if(typeof S==="string")return S;let P=ee(v);return P===v?void 0:P},E.sqlite3_db_config=function(S,P,...K){switch(P){case E.SQLITE_DBCONFIG_ENABLE_FKEY:case E.SQLITE_DBCONFIG_ENABLE_TRIGGER:case E.SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER:case E.SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION:case E.SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE:case E.SQLITE_DBCONFIG_ENABLE_QPSG:case E.SQLITE_DBCONFIG_TRIGGER_EQP:case E.SQLITE_DBCONFIG_RESET_DATABASE:case E.SQLITE_DBCONFIG_DEFENSIVE:case E.SQLITE_DBCONFIG_WRITABLE_SCHEMA:case E.SQLITE_DBCONFIG_LEGACY_ALTER_TABLE:case E.SQLITE_DBCONFIG_DQS_DML:case E.SQLITE_DBCONFIG_DQS_DDL:case E.SQLITE_DBCONFIG_ENABLE_VIEW:case E.SQLITE_DBCONFIG_LEGACY_FILE_FORMAT:case E.SQLITE_DBCONFIG_TRUSTED_SCHEMA:case E.SQLITE_DBCONFIG_STMT_SCANSTATUS:case E.SQLITE_DBCONFIG_REVERSE_SCANORDER:case E.SQLITE_DBCONFIG_ENABLE_ATTACH_CREATE:case E.SQLITE_DBCONFIG_ENABLE_ATTACH_WRITE:case E.SQLITE_DBCONFIG_ENABLE_COMMENTS:case E.SQLITE_DBCONFIG_FP_DIGITS:if(!this.ip)this.ip=b.xWrap("sqlite3__wasm_db_config_ip","int",["sqlite3*","int","int","*"]);return this.ip(S,P,K[0],K[1]||0);case E.SQLITE_DBCONFIG_LOOKASIDE:if(!this.pii)this.pii=b.xWrap("sqlite3__wasm_db_config_pii","int",["sqlite3*","int","*","int","int"]);return this.pii(S,P,K[0],K[1],K[2]);case E.SQLITE_DBCONFIG_MAINDBNAME:if(!this.s)this.s=b.xWrap("sqlite3__wasm_db_config_s","int",["sqlite3*","int","string:static"]);return this.s(S,P,K[0]);default:return E.SQLITE_MISUSE}}.bind(d()),E.sqlite3_value_to_js=function(S,P=!0){let K,oe=E.sqlite3_value_type(S);switch(oe){case E.SQLITE_INTEGER:if(b.bigIntEnabled){if(K=E.sqlite3_value_int64(S),J.bigIntFitsDouble(K))K=Number(K)}else K=E.sqlite3_value_double(S);break;case E.SQLITE_FLOAT:K=E.sqlite3_value_double(S);break;case E.SQLITE_TEXT:K=E.sqlite3_value_text(S);break;case E.SQLITE_BLOB:{let W=E.sqlite3_value_bytes(S),he=E.sqlite3_value_blob(S);if(W&&!he)pe.WasmAllocError.toss("Cannot allocate memory for blob argument of",W,"byte(s)");K=W?b.heap8u().slice(Number(he),Number(he)+Number(W)):null;break}case E.SQLITE_NULL:K=null;break;default:if(P)N(E.SQLITE_MISMATCH,"Unhandled sqlite3_value_type():",oe);K=void 0}return K},E.sqlite3_values_to_js=function(S,P,K=!0){let oe,W=[];for(oe=0;oe<S;++oe)W.push(E.sqlite3_value_to_js(b.peekPtr(b.ptr.add(P,b.ptr.size*oe)),K));return W},E.sqlite3_result_error_js=function(S,P){if(P instanceof U)E.sqlite3_result_error_nomem(S);else E.sqlite3_result_error(S,""+P,-1)},E.sqlite3_result_js=function(S,P){if(P instanceof Error){E.sqlite3_result_error_js(S,P);return}try{switch(typeof P){case"undefined":break;case"boolean":E.sqlite3_result_int(S,P?1:0);break;case"bigint":if(J.bigIntFits32(P))E.sqlite3_result_int(S,Number(P));else if(J.bigIntFitsDouble(P))E.sqlite3_result_double(S,Number(P));else if(b.bigIntEnabled)if(J.bigIntFits64(P))E.sqlite3_result_int64(S,P);else N("BigInt value",P.toString(),"is too BigInt for int64.");else N("BigInt value",P.toString(),"is too BigInt.");break;case"number":{let K;if(J.isInt32(P))K=E.sqlite3_result_int;else if(b.bigIntEnabled&&Number.isInteger(P)&&J.bigIntFits64(BigInt(P)))K=E.sqlite3_result_int64;else K=E.sqlite3_result_double;K(S,P);break}case"string":{let[K,oe]=b.allocCString(P,!0);E.sqlite3_result_text(S,K,oe,E.SQLITE_WASM_DEALLOC);break}case"object":if(P===null){E.sqlite3_result_null(S);break}else if(J.isBindableTypedArray(P)){let K=b.allocFromTypedArray(P);E.sqlite3_result_blob(S,K,P.byteLength,E.SQLITE_WASM_DEALLOC);break}default:N("Don't not how to handle this UDF result value:",typeof P,P)}}catch(K){E.sqlite3_result_error_js(S,K)}},E.sqlite3_column_js=function(S,P,K=!0){let oe=E.sqlite3_column_value(S,P);return oe===0?void 0:E.sqlite3_value_to_js(oe,K)};{let S=function(P,K,oe){if(oe=E[oe],!this.ptr)this.ptr=b.allocPtr();else b.pokePtr(this.ptr,0);let W=oe(P,K,this.ptr);if(W)return M.toss(W,arguments[2]+"() failed with code "+W);let he=b.peekPtr(this.ptr);return he?E.sqlite3_value_to_js(he,!0):void 0}.bind(d());E.sqlite3_preupdate_new_js=(P,K)=>S(P,K,"sqlite3_preupdate_new"),E.sqlite3_preupdate_old_js=(P,K)=>S(P,K,"sqlite3_preupdate_old"),E.sqlite3changeset_new_js=(P,K)=>S(P,K,"sqlite3changeset_new"),E.sqlite3changeset_old_js=(P,K)=>S(P,K,"sqlite3changeset_old")}E.sqlite3_js_retry_busy=function(S,P,K){for(let oe=1;oe<=S;++oe)try{if(K&&oe>1)K(oe);let W=P();if(E.SQLITE_BUSY===W){if(oe===S)throw new M(W,["sqlite3_js_retry_busy() max retry attempts (",S,") reached."].join(""));continue}return W}catch(W){if(oe<S&&W instanceof M&&W.resultCode===E.SQLITE_BUSY)continue;throw W}};let pe={WasmAllocError:U,SQLite3Error:M,capi:E,util:J,wasm:b,config:p,version:d(),client:void 0,asyncPostInit:async function S(){if(S.isReady instanceof Promise)return S.isReady;let P=this.initializersAsync;delete this.initializersAsync;let K=async()=>{if(!pe.__isUnderTest)delete pe.util,delete pe.StructBinder,delete pe.opfs;return pe},oe=(he)=>{throw p.error("an async sqlite3 initializer failed:",he),he};if(!P||!P.length)return S.isReady=K().catch(oe);P=P.map((he)=>he instanceof Function?async(be)=>he(pe):he),P.push(K);let W=Promise.resolve(pe);while(P.length)W=W.then(P.shift());return S.isReady=W.catch(oe)}.bind(f),scriptInfo:void 0};if(typeof h<"u")pe.__isUnderTest=!!h;try{f.initializers.forEach((S)=>{S(pe)})}catch(S){throw console.error("sqlite3 bootstrap initializer threw:",S),S}if(delete f.initializers,f.sqlite3=pe,typeof i<"u")i.debugModule("sqlite3ApiBootstrap() complete",pe),pe.scriptInfo=i;if(pe.__isUnderTest){if(typeof l<"u")pe.config.emscripten=l;let S=pe.scriptInfo?.instantiateWasm;if(S)pe.wasm.module=S.module,pe.wasm.instance=S.instance,pe.wasm.imports=S.imports}return delete globalThis.sqlite3ApiConfig,delete globalThis.sqlite3ApiBootstrap,delete f.defaultConfig,pe.asyncPostInit().then((S)=>{if(typeof i<"u")i.debugModule("sqlite3.asyncPostInit() complete",S);return delete S.asyncPostInit,delete S.scriptInfo,delete S.emscripten,S})},globalThis.sqlite3ApiBootstrap.initializers=[],globalThis.sqlite3ApiBootstrap.initializersAsync=[],globalThis.sqlite3ApiBootstrap.defaultConfig=Object.create(null),globalThis.sqlite3ApiBootstrap.sqlite3=void 0,globalThis.sqlite3ApiBootstrap.initializers.push(function(f){f.version={libVersion:"3.53.0",libVersionNumber:3053000,sourceId:"2026-04-09 11:41:38 4525003a53a7fc63ca75c59b22c79608659ca12f0131f52c18637f829977f20b",downloadVersion:3530000,scm:{"sha3-256":"4525003a53a7fc63ca75c59b22c79608659ca12f0131f52c18637f829977f20b",branch:"trunk",tags:"release major-release version-3.53.0",datetime:"2026-04-09T11:41:38.498Z"}}}),globalThis.WhWasmUtilInstaller=function(c){if(c.bigIntEnabled===void 0)c.bigIntEnabled=!!globalThis.BigInt64Array;let d=(...g)=>{throw Error(g.join(" "))};if(!c.pointerSize&&!c.pointerIR&&c.alloc&&c.dealloc){let g=c.alloc(1);c.pointerSize=typeof g==="bigint"?8:4,c.dealloc(g)}if(c.pointerSize&&!c.pointerIR)c.pointerIR=c.pointerSize===4?"i32":"i64";let p=c.pointerIR??="i32",E=c.pointerSize??=p==="i32"?4:p==="i64"?8:0;if(delete c.pointerSize,delete c.pointerIR,p!=="i32"&&p!=="i64")d("Invalid pointerIR:",p);else if(E!==8&&E!==4)d("Invalid pointerSize:",E);let b=c.bigIntEnabled?(g)=>BigInt(g||0):(g)=>d("BigInt support is disabled in this build."),V=E===4?(g)=>Number(g||0):b,M=V(0),N=function(...g){let w=V(0);for(let T of g)w+=V(T);return w};{let g=Object.create(null);Object.defineProperty(c,"ptr",{enumerable:!0,get:()=>g,set:()=>d("The ptr property is read-only.")}),function w(T,C){return Object.defineProperty(g,T,{enumerable:!0,get:()=>C,set:()=>d("ptr["+T+"] is read-only.")}),w}("null",M)("size",E)("ir",p)("coerce",V)("add",N)("addn",p===4?N:(...w)=>Number(N(...w)))}if(!c.exports)Object.defineProperty(c,"exports",{enumerable:!0,configurable:!0,get:()=>c.instance?.exports});let q=Object.create(null);q.heapSize=0,q.memory=null,q.freeFuncIndexes=[],q.scopedAlloc=[],q.scopedAlloc.pushPtr=(g)=>(q.scopedAlloc[q.scopedAlloc.length-1].push(g),g),q.utf8Decoder=new TextDecoder,q.utf8Encoder=new TextEncoder("utf-8"),c.sizeofIR=(g)=>{switch(g){case"i8":return 1;case"i16":return 2;case"i32":case"f32":case"float":return 4;case"i64":case"f64":case"double":return 8;case"*":return E;default:return(""+g).endsWith("*")?E:void 0}};let H=function(){if(!q.memory)q.memory=c.memory instanceof WebAssembly.Memory?c.memory:c.exports.memory;else if(q.heapSize===q.memory.buffer.byteLength)return q;let g=q.memory.buffer;if(q.HEAP8=new Int8Array(g),q.HEAP8U=new Uint8Array(g),q.HEAP16=new Int16Array(g),q.HEAP16U=new Uint16Array(g),q.HEAP32=new Int32Array(g),q.HEAP32U=new Uint32Array(g),q.HEAP32F=new Float32Array(g),q.HEAP64F=new Float64Array(g),c.bigIntEnabled)if(typeof BigInt64Array<"u")q.HEAP64=new BigInt64Array(g),q.HEAP64U=new BigUint64Array(g);else d("BigInt support is enabled, but the BigInt64Array type is missing.");return q.heapSize=g.byteLength,q};c.heap8=()=>H().HEAP8,c.heap8u=()=>H().HEAP8U,c.heap16=()=>H().HEAP16,c.heap16u=()=>H().HEAP16U,c.heap32=()=>H().HEAP32,c.heap32u=()=>H().HEAP32U,c.heapForSize=function(g,w=!0){let T=q.memory&&q.heapSize===q.memory.buffer.byteLength?q:H();switch(g){case Int8Array:return T.HEAP8;case Uint8Array:return T.HEAP8U;case Int16Array:return T.HEAP16;case Uint16Array:return T.HEAP16U;case Int32Array:return T.HEAP32;case Uint32Array:return T.HEAP32U;case 8:return w?T.HEAP8U:T.HEAP8;case 16:return w?T.HEAP16U:T.HEAP16;case 32:return w?T.HEAP32U:T.HEAP32;case 64:if(T.HEAP64)return w?T.HEAP64U:T.HEAP64;break;default:if(c.bigIntEnabled){if(g===globalThis.BigUint64Array)return T.HEAP64U;else if(g===globalThis.BigInt64Array)return T.HEAP64;break}}d("Invalid heapForSize() size: expecting 8, 16, 32,","or (if BigInt is enabled) 64.")};let G=c.functionTable;delete c.functionTable,c.functionTable=G?()=>G:()=>c.exports.__indirect_function_table,c.functionEntry=function(g){let w=c.functionTable();return g<w.length?w.get(V(g)):void 0},c.jsFuncToWasm=function g(w,T){if(!g._)g._={sigTypes:Object.assign(Object.create(null),{i:"i32",p,P:p,s:p,j:"i64",f:"f32",d:"f64"}),typeCodes:Object.assign(Object.create(null),{f64:124,f32:125,i64:126,i32:127}),uleb128Encode:(A,L,Q)=>{if(Q<128)A[L](Q);else A[L](Q%128|128,Q>>7)},rxJSig:/^(\w)\((\w*)\)$/,sigParams:(A)=>{let L=g._.rxJSig.exec(A);return L?L[2]:A.substr(1)},letterType:(A)=>g._.sigTypes[A]||d("Invalid signature letter:",A),pushSigType:(A,L)=>A.push(g._.typeCodes[g._.letterType(L)])};if(typeof w==="string"){let A=T;T=w,w=A}let C=g._,te=C.sigParams(T),se=[1,96];C.uleb128Encode(se,"push",te.length);for(let A of te)C.pushSigType(se,A);if(T[0]==="v")se.push(0);else se.push(1),C.pushSigType(se,T[0]);return C.uleb128Encode(se,"unshift",se.length),se.unshift(0,97,115,109,1,0,0,0,1),se.push(2,7,1,1,101,1,102,0,0,7,5,1,1,102,0,0),new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array(se)),{e:{f:w}}).exports.f};let le=function(w,T,C){if(C&&!q.scopedAlloc.length)d("No scopedAllocPush() scope is active.");if(typeof w==="string"){let L=T;T=w,w=L}if(typeof T!=="string"||!(w instanceof Function))d("Invalid arguments: expecting (function,signature) or (signature,function).");let te=c.functionTable(),se=V(te.length),A;while(A=q.freeFuncIndexes.pop())if(te.get(A)){A=null;continue}else break;if(!A)A=V(se),te.grow(V(1));try{if(te.set(A,w),C)q.scopedAlloc.pushPtr(A);return A}catch(L){if(!(L instanceof TypeError)){if(A===se)q.freeFuncIndexes.push(se);throw L}}try{let L=c.jsFuncToWasm(w,T);if(te.set(A,L),C)q.scopedAlloc.pushPtr(A)}catch(L){if(A===se)q.freeFuncIndexes.push(se);throw L}return A};c.installFunction=(g,w)=>le(g,w,!1),c.scopedInstallFunction=(g,w)=>le(g,w,!0),c.uninstallFunction=function(g){if(!g&&M!==g)return;let w=c.functionTable();q.freeFuncIndexes.push(g);let T=w.get(g);return w.set(g,null),T},c.peek=function(w,T="i8"){if(T.endsWith("*"))T=p;let C=q.memory&&q.heapSize===q.memory.buffer.byteLength?q:H(),te=Array.isArray(w)?[]:void 0,se;do{if(te)w=arguments[0].shift();switch(T){case"i1":case"i8":se=C.HEAP8[Number(w)>>0];break;case"i16":se=C.HEAP16[Number(w)>>1];break;case"i32":se=C.HEAP32[Number(w)>>2];break;case"float":case"f32":se=C.HEAP32F[Number(w)>>2];break;case"double":case"f64":se=Number(C.HEAP64F[Number(w)>>3]);break;case"i64":if(C.HEAP64){se=b(C.HEAP64[Number(w)>>3]);break}default:d("Invalid type for peek():",T)}if(te)te.push(se)}while(te&&arguments[0].length);return te||se},c.poke=function(g,w,T="i8"){if(T.endsWith("*"))T=p;let C=q.memory&&q.heapSize===q.memory.buffer.byteLength?q:H();for(let te of Array.isArray(g)?g:[g])switch(T){case"i1":case"i8":C.HEAP8[Number(te)>>0]=w;continue;case"i16":C.HEAP16[Number(te)>>1]=w;continue;case"i32":C.HEAP32[Number(te)>>2]=w;continue;case"float":case"f32":C.HEAP32F[Number(te)>>2]=w;continue;case"double":case"f64":C.HEAP64F[Number(te)>>3]=w;continue;case"i64":if(C.HEAP64){C.HEAP64[Number(te)>>3]=b(w);continue}default:d("Invalid type for poke(): "+T)}return this},c.peekPtr=(...g)=>c.peek(g.length===1?g[0]:g,p),c.pokePtr=(g,w=0)=>c.poke(g,w,p),c.peek8=(...g)=>c.peek(g.length===1?g[0]:g,"i8"),c.poke8=(g,w)=>c.poke(g,w,"i8"),c.peek16=(...g)=>c.peek(g.length===1?g[0]:g,"i16"),c.poke16=(g,w)=>c.poke(g,w,"i16"),c.peek32=(...g)=>c.peek(g.length===1?g[0]:g,"i32"),c.poke32=(g,w)=>c.poke(g,w,"i32"),c.peek64=(...g)=>c.peek(g.length===1?g[0]:g,"i64"),c.poke64=(g,w)=>c.poke(g,w,"i64"),c.peek32f=(...g)=>c.peek(g.length===1?g[0]:g,"f32"),c.poke32f=(g,w)=>c.poke(g,w,"f32"),c.peek64f=(...g)=>c.peek(g.length===1?g[0]:g,"f64"),c.poke64f=(g,w)=>c.poke(g,w,"f64"),c.getMemValue=c.peek,c.getPtrValue=c.peekPtr,c.setMemValue=c.poke,c.setPtrValue=c.pokePtr,c.isPtr32=(g)=>typeof g==="number"&&g>=0&&g===(g|0),c.isPtr64=(g)=>typeof g==="bigint"?g>=0:c.isPtr32(g),c.isPtr=E===4?c.isPtr32:c.isPtr64,c.cstrlen=function(g){if(!g||!c.isPtr(g))return null;g=Number(g);let w=H().HEAP8U,T=g;for(;w[T]!==0;++T);return T-g};let O=typeof SharedArrayBuffer>"u"?function(){}:SharedArrayBuffer,R=(g)=>g.buffer instanceof O;c.isSharedTypedArray=R;let X=(g,w,T)=>{if(E===8){if(typeof w==="bigint")w=Number(w);if(typeof T==="bigint")T=Number(T)}return R(g)?g.slice(w,T):g.subarray(w,T)};c.typedArrayPart=X;let ee=(g,w,T)=>q.utf8Decoder.decode(X(g,w,T));c.typedArrayToString=ee,c.cstrToJs=function(g){let w=c.cstrlen(g);return w?ee(H().HEAP8U,Number(g),Number(g)+w):w===null?w:""},c.jstrlen=function(g){if(typeof g!=="string")return null;let w=g.length,T=0;for(let C=0;C<w;++C){let te=g.charCodeAt(C);if(te>=55296&&te<=57343)te=65536+((te&1023)<<10)|g.charCodeAt(++C)&1023;if(te<=127)++T;else if(te<=2047)T+=2;else if(te<=65535)T+=3;else T+=4}return T},c.jstrcpy=function(g,w,T=0,C=-1,te=!0){if(!w||!(w instanceof Int8Array)&&!(w instanceof Uint8Array))d("jstrcpy() target must be an Int8Array or Uint8Array.");if(C=Number(C),T=Number(T),C<0)C=w.length-T;if(!(C>0)||!(T>=0))return 0;let se=0,A=g.length,L=T,Q=T+C-(te?1:0);for(;se<A&&T<Q;++se){let ne=g.charCodeAt(se);if(ne>=55296&&ne<=57343)ne=65536+((ne&1023)<<10)|g.charCodeAt(++se)&1023;if(ne<=127){if(T>=Q)break;w[T++]=ne}else if(ne<=2047){if(T+1>=Q)break;w[T++]=192|ne>>6,w[T++]=128|ne&63}else if(ne<=65535){if(T+2>=Q)break;w[T++]=224|ne>>12,w[T++]=128|ne>>6&63,w[T++]=128|ne&63}else{if(T+3>=Q)break;w[T++]=240|ne>>18,w[T++]=128|ne>>12&63,w[T++]=128|ne>>6&63,w[T++]=128|ne&63}}if(te)w[T++]=0;return T-L},c.cstrncpy=function(g,w,T){if(!g||!w)d("cstrncpy() does not accept NULL strings.");if(T<0)T=c.cstrlen(strPtr)+1;else if(!(T>0))return 0;let C=c.heap8u(),te=0,se,A=Number(g),L=Number(w);for(;te<T&&(se=C[L+te]);++te)C[A+te]=se;if(te<T)C[A+te++]=0;return te},c.jstrToUintArray=(g,w=!1)=>q.utf8Encoder.encode(w?g+"\x00":g);let U=(g,w)=>{if(!(g.alloc instanceof Function)||!(g.dealloc instanceof Function))d("Object is missing alloc() and/or dealloc() function(s)","required by",w+"().")},J=function(g,w,T,C){if(U(c,C),typeof g!=="string")return null;let te=q.utf8Encoder.encode(g),se=T(te.length+1),A=se;try{let L=H().HEAP8U;return L.set(te,Number(se)),L[N(se,te.length)]=0,A=M,w?[se,te.length]:se}finally{if(A)c.dealloc(A)}};c.allocCString=(g,w=!1)=>J(g,w,c.alloc,"allocCString()"),c.scopedAllocPush=function(){U(c,"scopedAllocPush");let g=[];return q.scopedAlloc.push(g),g},c.scopedAllocPop=function(g){U(c,"scopedAllocPop");let w=arguments.length?q.scopedAlloc.indexOf(g):q.scopedAlloc.length-1;if(w<0)d("Invalid state object for scopedAllocPop().");if(arguments.length===0)g=q.scopedAlloc[w];q.scopedAlloc.splice(w,1);for(let T;T=g.pop();)if(c.functionEntry(T))c.uninstallFunction(T);else c.dealloc(T)},c.scopedAlloc=function(g){if(!q.scopedAlloc.length)d("No scopedAllocPush() scope is active.");let w=V(c.alloc(g));return q.scopedAlloc.pushPtr(w)},Object.defineProperty(c.scopedAlloc,"level",{configurable:!1,enumerable:!1,get:()=>q.scopedAlloc.length,set:()=>d("The 'active' property is read-only.")}),c.scopedAllocCString=(g,w=!1)=>J(g,w,c.scopedAlloc,"scopedAllocCString()");let pe=function(g,w){let T=c[g?"scopedAlloc":"alloc"]((w.length+1)*c.ptr.size),C=0;return w.forEach((te)=>{c.pokePtr(N(T,c.ptr.size*C++),c[g?"scopedAllocCString":"allocCString"](""+te))}),c.pokePtr(N(T,c.ptr.size*C),0),T};c.scopedAllocMainArgv=(g)=>pe(!0,g),c.allocMainArgv=(g)=>pe(!1,g),c.cArgvToJs=(g,w)=>{let T=[];for(let C=0;C<g;++C){let te=c.peekPtr(N(w,c.ptr.size*C));T.push(te?c.cstrToJs(te):null)}return T},c.scopedAllocCall=function(g){c.scopedAllocPush();try{return g()}finally{c.scopedAllocPop()}};let S=function(g,w,T){U(c,T);let C=w?"i64":p,te=c[T](g*(w?8:E));if(c.poke(te,0,C),g===1)return te;let se=[te];for(let A=1;A<g;++A)te=N(te,w?8:E),se[A]=te,c.poke(te,0,C);return se};c.allocPtr=(g=1,w=!0)=>S(g,w,"alloc"),c.scopedAllocPtr=(g=1,w=!0)=>S(g,w,"scopedAlloc"),c.xGet=function(g){return c.exports[g]||d("Cannot find exported symbol:",g)};let P=(g,w)=>d(g+"() requires",w,"argument(s).");c.xCall=function(g,...w){let T=g instanceof Function?g:c.xGet(g);if(!(T instanceof Function))d("Exported symbol",g,"is not a function.");if(T.length!==w.length)P(T===g?T.name:g,T.length);return arguments.length===2&&Array.isArray(arguments[1])?T.apply(null,arguments[1]):T.apply(null,w)},q.xWrap=Object.create(null),q.xWrap.convert=Object.create(null),q.xWrap.convert.arg=new Map,q.xWrap.convert.result=new Map;let K=q.xWrap.convert.arg,oe=q.xWrap.convert.result,W=V;K.set("i64",b).set("i32",(g)=>g|0).set("i16",(g)=>(g|0)&65535).set("i8",(g)=>(g|0)&255).set("f32",(g)=>Number(g).valueOf()).set("float",K.get("f32")).set("f64",K.get("f32")).set("double",K.get("f64")).set("int",K.get("i32")).set("null",(g)=>g).set(null,K.get("null")).set("**",W).set("*",W),oe.set("*",W).set("pointer",W).set("number",(g)=>Number(g)).set("void",(g)=>{return}).set(void 0,oe.get("void")).set("null",(g)=>g).set(null,oe.get("null"));for(let g of["i8","i16","i32","i64","int","f32","float","f64","double"])K.set(g+"*",W),oe.set(g+"*",W),oe.set(g,K.get(g)||d("Maintenance required: missing arg converter for",g));let he=(g)=>typeof g==="string"?c.scopedAllocCString(g):V(g);K.set("string",he).set("utf8",he),oe.set("string",(g)=>c.cstrToJs(g)).set("utf8",oe.get("string")).set("string:dealloc",(g)=>{try{return g?c.cstrToJs(g):null}finally{c.dealloc(g)}}).set("utf8:dealloc",oe.get("string:dealloc")).set("json",(g)=>JSON.parse(c.cstrToJs(g))).set("json:dealloc",(g)=>{try{return g?JSON.parse(c.cstrToJs(g)):null}finally{c.dealloc(g)}});let be=class{constructor(g){this.name=g.name||"unnamed adapter"}convertArg(g,w,T){d("AbstractArgAdapter must be subclassed.")}};K.FuncPtrAdapter=class g extends be{constructor(w){super(w);if(K.FuncPtrAdapter.warnOnUse)console.warn("xArg.FuncPtrAdapter is an internal-only API","and is not intended to be invoked from","client-level code. Invoked with:",w);if(this.name=w.name||"unnamed",this.signature=w.signature,w.contextKey instanceof Function){if(this.contextKey=w.contextKey,!w.bindScope)w.bindScope="context"}if(this.bindScope=w.bindScope||d("FuncPtrAdapter options requires a bindScope (explicit or implied)."),g.bindScopes.indexOf(w.bindScope)<0)d("Invalid options.bindScope ("+w.bindMod+") for FuncPtrAdapter. Expecting one of: ("+g.bindScopes.join(", ")+")");this.isTransient=this.bindScope==="transient",this.isContext=this.bindScope==="context",this.isPermanent=this.bindScope==="permanent",this.singleton=this.bindScope==="singleton"?[]:void 0,this.callProxy=w.callProxy instanceof Function?w.callProxy:void 0}contextKey(w,T){return this}contextMap(w){let T=this.__cmap||(this.__cmap=new Map),C=T.get(w);if(C===void 0)T.set(w,C=[]);return C}convertArg(w,T,C){let te=this.singleton;if(!te&&this.isContext)te=this.contextMap(this.contextKey(T,C));if(te&&te.length===2&&te[0]===w)return te[1];if(w instanceof Function){if(this.callProxy)w=this.callProxy(w);let se=le(w,this.signature,this.isTransient);if(g.debugFuncInstall)g.debugOut("FuncPtrAdapter installed",this,this.contextKey(T,C),"@"+se,w);if(te){if(te[1]){if(g.debugFuncInstall)g.debugOut("FuncPtrAdapter uninstalling",this,this.contextKey(T,C),"@"+te[1],w);try{q.scopedAlloc.pushPtr(te[1])}catch(A){}}te[0]=arguments[0]||M,te[1]=se}return se}else if(c.isPtr(w)||w===null||w===void 0){if(te&&te[1]&&te[1]!==w){if(g.debugFuncInstall)g.debugOut("FuncPtrAdapter uninstalling",this,this.contextKey(T,C),"@"+te[1],w);try{q.scopedAlloc.pushPtr(te[1])}catch(se){}te[0]=te[1]=w||M}return w||M}else throw TypeError("Invalid FuncPtrAdapter argument type. Expecting a function pointer or a "+(this.name?this.name+" ":"")+"function matching signature "+this.signature+".")}},K.FuncPtrAdapter.warnOnUse=!1,K.FuncPtrAdapter.debugFuncInstall=!1,K.FuncPtrAdapter.debugOut=console.debug.bind(console),K.FuncPtrAdapter.bindScopes=["transient","context","singleton","permanent"];let me=(g)=>K.get(g)||d("Argument adapter not found:",g),ve=(g)=>oe.get(g)||d("Result adapter not found:",g);q.xWrap.convertArg=(g,...w)=>me(g)(...w),q.xWrap.convertArgNoCheck=(g,...w)=>K.get(g)(...w),q.xWrap.convertResult=(g,w)=>g===null?w:g?ve(g)(w):void 0,q.xWrap.convertResultNoCheck=(g,w)=>g===null?w:g?oe.get(g)(w):void 0,c.xWrap=function g(w,T,...C){if(arguments.length===3&&Array.isArray(arguments[2]))C=arguments[2];if(c.isPtr(w))w=c.functionEntry(w)||d("Function pointer not found in WASM function table.");let te=w instanceof Function,se=te?w:c.xGet(w);if(te)w=se.name||"unnamed function";if(C.length!==se.length)P(w,se.length);if(se.length===0&&(T===null||T==="null"))return se;ve(T);for(let L of C)if(L instanceof be)K.set(L,(...Q)=>L.convertArg(...Q));else me(L);let A=q.xWrap;if(se.length===0)return(...L)=>L.length?P(w,se.length):A.convertResult(T,se.call(null));return function(...L){if(L.length!==se.length)P(w,se.length);let Q=c.scopedAllocPush();try{let ne=0;if(g.debug)console.debug("xWrap() preparing: resultType ",T,"xf",se,"argTypes",C,"args",L);for(;ne<L.length;++ne)L[ne]=A.convertArgNoCheck(C[ne],L[ne],L,ne);if(g.debug)console.debug("xWrap() calling: resultType ",T,"xf",se,"argTypes",C,"args",L);return A.convertResultNoCheck(T,se.apply(null,L))}finally{c.scopedAllocPop(Q)}}};let z=function(g,w,T,C,te,se){if(typeof T==="string"){if(w===1)return se.get(T);else if(w===2){if(!C)return se.delete(T),g;else if(!(C instanceof Function))d(te,"requires a function argument.");return se.set(T,C),g}}d("Invalid arguments to",te)};return c.xWrap.resultAdapter=function g(w,T){return z(g,arguments.length,w,T,"resultAdapter()",oe)},c.xWrap.argAdapter=function g(w,T){return z(g,arguments.length,w,T,"argAdapter()",K)},c.xWrap.FuncPtrAdapter=K.FuncPtrAdapter,c.xCallWrapped=function(g,w,T,...C){if(Array.isArray(arguments[3]))C=arguments[3];return c.xWrap(g,w,T||[]).apply(null,C||[])},c.xWrap.testConvertArg=q.xWrap.convertArg,c.xWrap.testConvertResult=q.xWrap.convertResult,c},globalThis.WhWasmUtilInstaller.yawl=function(c){let d=()=>fetch(c.uri,{credentials:"same-origin"}),p=this,E=function(b){if(c.wasmUtilTarget){let I=(...M)=>{throw Error(M.join(" "))},V=c.wasmUtilTarget;if(V.module=b.module,V.instance=b.instance,!V.instance.exports.memory)V.memory=c?.imports?.env?.memory||I("Missing 'memory' object!");if(!V.alloc&&b.instance.exports.malloc){let M=b.instance.exports;V.alloc=function(N){return M.malloc(N)||I("Allocation of",N,"bytes failed.")},V.dealloc=function(N){N&&M.free(N)}}p(V)}if(b.config=c,c.onload)c.onload(b);return b};return WebAssembly.instantiateStreaming?()=>WebAssembly.instantiateStreaming(d(),c.imports||{}).then(E):()=>d().then((b)=>b.arrayBuffer()).then((b)=>WebAssembly.instantiate(b,c.imports||{})).then(E)}.bind(globalThis.WhWasmUtilInstaller),globalThis.Jaccwabyt=function f(c){let d=(...F)=>{throw Error(F.join(" "))};{let F=c.heap;if(F instanceof WebAssembly.Memory)F=function(){return new Uint8Array(this.buffer)}.bind(F);else if(!(F instanceof Function))d("config.heap must be WebAssembly.Memory instance or","a function which returns one.");c.heap=F}["alloc","dealloc"].forEach(function(F){c[F]instanceof Function||d("Config option '"+F+"' must be a function.")});let p=f,{heap:E,alloc:b,dealloc:I}=c;c.realloc;let V=c.log||console.debug.bind(console),M=c.memberPrefix||"",N=c.memberSuffix||"",{BigInt:q,BigInt64Array:H}=globalThis,G=c.bigIntEnabled??!!H,le,O=c.pointerSize||c.ptrSize||(typeof(le=b(1))==="bigint"?8:4),R=c.pointerIR||c.ptrIR||(O===4?"i32":"i64");if(le)I(le),le=void 0;if(O!==4&&O!==8)d("Invalid pointer size:",O);if(R!=="i32"&&R!=="i64")d("Invalid pointer representation:",R);let X=G&&q?(F)=>q(F||0):(F)=>d("BigInt support is disabled in this build."),ee=R=="i32"?Number:X,U=ee(0),J=function(...F){let ie=U;for(let fe=0;fe<F.length;++fe)ie+=ee(F[fe]);return ie},pe=function(...F){return J(this.pointer,...F)};if(!p.debugFlags)p.__makeDebugFlags=function(F=null){if(F&&F.__flags)F=F.__flags;let ie=function fe(Ee){if(arguments.length===0)return fe.__flags;if(Ee<0)delete fe.__flags.getter,delete fe.__flags.setter,delete fe.__flags.alloc,delete fe.__flags.dealloc;else fe.__flags.getter=(1&Ee)!==0,fe.__flags.setter=(2&Ee)!==0,fe.__flags.alloc=(4&Ee)!==0,fe.__flags.dealloc=(8&Ee)!==0;return fe._flags};if(Object.defineProperty(ie,"__flags",{iterable:!1,writable:!1,value:Object.create(F)}),!F)ie(0);return ie},p.debugFlags=p.__makeDebugFlags();let S=!0,P=(F)=>F[1]==="(",K=(F)=>F==="p"||F==="P"||F==="s",oe=(F)=>F==="P",W=(F)=>F?P(F)?"p":F[0]:void 0,he=function(F){switch(W(F)){case"c":case"C":return"i8";case"i":return"i32";case"p":case"P":case"s":return R;case"j":return"i64";case"f":return"float";case"d":return"double"}d("Unhandled signature IR:",F)},be=function(F){switch(W(F)){case"c":case"C":return 1;case"i":return 4;case"p":case"P":case"s":return O;case"j":return 8;case"f":return 4;case"d":return 8}d("Unhandled signature sizeof:",F)},me=H?()=>!0:()=>d("BigInt64Array is not available."),ve=function(F){switch(W(F)){case"p":case"P":case"s":switch(O){case 4:return"getInt32";case 8:return me()&&"getBigInt64"}break;case"i":return"getInt32";case"c":return"getInt8";case"C":return"getUint8";case"j":return me()&&"getBigInt64";case"f":return"getFloat32";case"d":return"getFloat64"}d("Unhandled DataView getter for signature:",F)},z=function(F){switch(W(F)){case"p":case"P":case"s":switch(O){case 4:return"setInt32";case 8:return me()&&"setBigInt64"}break;case"i":return"setInt32";case"c":return"setInt8";case"C":return"setUint8";case"j":return me()&&"setBigInt64";case"f":return"setFloat32";case"d":return"setFloat64"}d("Unhandled DataView setter for signature:",F)},g=function(F){switch(W(F)){case"i":case"f":case"c":case"C":case"d":return Number;case"j":return X;case"p":case"P":case"s":switch(O){case 4:return Number;case 8:return X}break}d("Unhandled DataView set wrapper for signature:",F)},w=(F,ie)=>F+"::"+ie,T=function(F,ie){return()=>d(w(F,ie),"is read-only.")},C=function F(ie,fe=!0){let Ee=F.map.get(ie);if(!Ee&&fe)F.map.set(ie,Ee=F.create(ie));return Ee};C.map=new WeakMap,C.create=(F)=>Object.assign(Object.create(null),{o:F,p:void 0,ownsPointer:!1,zod:!1,xb:0});let te=(F)=>C.map.delete(F),se=(F)=>typeof F==="number"&&F===(F|0)&&F>=0,L=O===4?se:(F)=>typeof F==="bigint"&&F>=0||se(F),Q=(F)=>L(F)&&F>0,ne=function(F,ie,fe){let Ee=C(ie,!1);if(!Ee)return;if(te(ie),!fe&&!(fe=Ee.p)){console.warn("Cannot(?) happen: __freeStruct() found no instanceInfo");return}if(Array.isArray(ie.ondispose)){let Ae;while(Ae=ie.ondispose.pop())try{if(Ae instanceof Function)Ae.call(ie);else if(Ae instanceof At)Ae.dispose();else if(L(Ae))I(Ae)}catch(Ke){console.warn("ondispose() for",F.structName,"@",fe,"threw. NOT propagating it.",Ke)}}else if(ie.ondispose instanceof Function)try{ie.ondispose()}catch(Ae){console.warn("ondispose() for",F.structName,"@",fe,"threw. NOT propagating it.",Ae)}if(delete ie.ondispose,F.debugFlags.__flags.dealloc)V("debug.dealloc:",Ee.ownsPointer?"":"EXTERNAL",F.structName,"instance:",F.structInfo.sizeof,"bytes @"+fe);if(Ee.ownsPointer){if(Ee.zod||F.structInfo.zeroOnDispose)E().fill(0,Number(fe),Number(fe)+F.structInfo.sizeof+Ee.xb);I(fe)}},ye=()=>({configurable:!1,writable:!1,iterable:!1}),Te=(F)=>({...ye(),value:F}),Ie=function(ie,fe,Ee){let Ae,Ke=(He)=>{Q(He)||d("Invalid pointer value",arguments[0],"for",ie.structName,"constructor.")};if(arguments.length>=3)if(Ee&&typeof Ee==="object")Ae=Ee,Ee=Ae?.wrap;else Ke(Ee),Ae={wrap:Ee};else Ae={};let ft=!Ee,xt=0,Dt=!1;if(Ee)Ke(Ee),Dt=!!Ae?.takeOwnership;else{let He=Ae?.extraBytes??0;if(He<0||He!==(He|0))d("Invalid extraBytes value:",Ae?.extraBytes);xt=ie.structInfo.sizeof+He,Ee=b(xt)||d("Allocation of",ie.structName,"structure failed."),Dt=!0}try{if(Ae?.debugFlags)fe.debugFlags(Ae.debugFlags);if(ie.debugFlags.__flags.alloc)V("debug.alloc:",ft?"":"EXTERNAL",ie.structName,"instance:",ie.structInfo.sizeof,"bytes @"+Ee);if(ft)E().fill(0,Number(Ee),Number(Ee)+xt);let He=C(fe);if(He.p=Ee,He.ownsPointer=Dt,He.xb=xt?xt-ie.structInfo.sizeof:0,He.zod=!!Ae?.zeroOnDispose,Ae?.ondispose&&Ae.ondispose!==Ee)fe.addOnDispose(Ae.ondispose)}catch(He){throw ne(ie,fe,Ee),He}},qe=function F(ie){return F.rxSig1??=/^[ipPsjfdcC]$/,F.rxSig2??=/^[vipPsjfdcC]\([ipPsjfdcC]*\)$/,F.rxSig1.test(ie)||F.rxSig2.test(ie)},Ge=function(F){let ie=this.get(F);if(!ie)ie=[Object.create(null),Object.create(null),Object.create(null)],this.set(F,ie);return ie}.bind(new WeakMap),ct=function(F,ie,fe,Ee){let Ae=Ge(F)[ie];if(arguments.length===3)return Ae[fe];if(Ee)return Ae[fe]=Ee;return delete Ae[fe]},zt=function(F,...ie){return ct(this,0,F,...ie)},Ir=function(F,ie){qe(ie)&&d(F,"(",ie,") collides with a data type signature.")},B=function(F,...ie){return Ir("Setter adaptor",F),ct(this,1,F,...ie)},re=function(F,...ie){return Ir("Struct adaptor",F),ct(this,2,F,...ie)},ae=function(F,ie){let fe=typeof ie==="string"?ct(F,2,ie):ie;if(typeof fe!=="object")d("Invalid struct mapping object. Arg =",ie,JSON.stringify(fe));return fe},Se=Te((F)=>M+F+N),Re=function(F,ie,fe=!0){let Ee=F.members[ie];if(!Ee&&(M||N)){for(let Ae of Object.values(F.members))if(Ae.key===ie){Ee=Ae;break}if(!Ee&&fe)d(w(F.name||F.structName,ie),"is not a mapped struct member.")}return Ee},Oe=function F(ie,fe,Ee=!1){if(!F._)F._=(Ke)=>Ke.replace(/[^vipPsjrdcC]/g,"").replace(/[pPscC]/g,"i");let Ae=Re(ie.structInfo,fe,!0);return Ee?F._(Ae.signature):Ae.signature},ke=Te(function(){let F=[];for(let ie of Object.keys(this.structInfo.members))F.push(this.memberKey(ie));return F}),Ne=new TextDecoder("utf-8"),je=new TextEncoder,Qe=typeof SharedArrayBuffer>"u"?function(){}:SharedArrayBuffer,Me=function(F,ie,fe){if(O===8)ie=Number(ie),fe=Number(fe);return Ne.decode(F.buffer instanceof Qe?F.slice(ie,fe):F.subarray(ie,fe))},yt=function(F,ie,fe=!1){let Ee=Re(F.structInfo,ie,fe);return Ee&&Ee.signature.length===1&&Ee.signature[0]==="s"?Ee:!1},Ft=function(F){if(F.signature==="s")return;d("Invalid member type signature for C-string value:",JSON.stringify(F))},rn=function(ie,fe){let Ee=Re(ie.structInfo,fe,!0);Ft(Ee);let Ae=ie[Ee.key];if(!Ae)return null;let Ke=Ae,ft=E();for(;ft[Ke]!==0;++Ke);return Ae===Ke?"":Me(ft,Ae,Ke)},Zt=function(F,...ie){if(F.ondispose){if(!Array.isArray(F.ondispose))F.ondispose=[F.ondispose]}else F.ondispose=[];F.ondispose.push(...ie)},Pr=function(F){let ie=je.encode(F),fe=b(ie.length+1);if(!fe)d("Allocation error while duplicating string:",F);let Ee=E();return Ee.set(ie,Number(fe)),Ee[J(fe,ie.length)]=0,fe},Nn=function(F,ie,fe){let Ee=Re(F.structInfo,ie,!0);Ft(Ee);let Ae=Pr(fe);return F[Ee.key]=Ae,Zt(F,Ae),F},At=function(ie,fe){if(arguments[2]!==Te)d("Do not call the StructType constructor","from client-level code.");Object.defineProperties(this,{structName:Te(ie),structInfo:Te(fe)})};At.prototype=Object.create(null,{dispose:Te(function(){ne(this.constructor,this)}),lookupMember:Te(function(F,ie=!0){return Re(this.structInfo,F,ie)}),memberToJsString:Te(function(F){return rn(this,F)}),memberIsString:Te(function(F,ie=!0){return yt(this,F,ie)}),memberKey:Se,memberKeys:ke,memberSignature:Te(function(F,ie=!1){return Oe(this,F,ie)}),memoryDump:Te(function(){let F=this.pointer;return F?new Uint8Array(E().slice(Number(F),Number(F)+this.structInfo.sizeof)):null}),extraBytes:{configurable:!1,enumerable:!1,get:function(){return C(this,!1)?.xb??0}},zeroOnDispose:{configurable:!1,enumerable:!1,get:function(){return C(this,!1)?.zod??!!this.structInfo.zeroOnDispose}},pointer:{configurable:!1,enumerable:!1,get:function(){return C(this,!1)?.p},set:()=>d("Cannot assign the 'pointer' property of a struct.")},setMemberCString:Te(function(F,ie){return Nn(this,F,ie)})}),Object.assign(At.prototype,{addOnDispose:function(...F){return Zt(this,...F),this}}),Object.defineProperties(At,{allocCString:Te(Pr),isA:Te((F)=>F instanceof At),hasExternalPointer:Te((F)=>{let ie=C(F,!1);return!!(ie?.p&&!ie?.ownsPointer)}),memberKey:Se});let mo=function(F){return F.get||(F.adaptGet?Ct.adaptGet(F.adaptGet):void 0)},Ac=function(F){return F.set||(F.adaptSet?Ct.adaptSet(F.adaptSet):void 0)},Pm=function F(ie,fe,Ee){let Ae=F.innerStructs??=new Map,Ke=ie.memberKey(fe);if(Ee.signature!==void 0)d("'signature' cannot be used on an embedded struct (",ie.structName,".",Ke,").");if(Ac(Ee))d("'set' and 'adaptSet' are not permitted for nested struct members.");Ee.structName??=ie.structName+"::"+fe,Ee.key=Ke,Ee.name=fe,Ee.constructor=this.call(this,Ee.structName,Ee);let ft=mo(Ee),xt=Object.assign(Object.create(null),{configurable:!1,enumerable:!1,set:T(ie.structName,Ke),get:function(){let Dt=this.debugFlags.__flags,He=this.pointer,pt=He+"."+Ke,Pe=Ae.get(pt);if(Dt.getter)V("debug.getter: k =",pt);if(!Pe)Pe=new Ee.constructor(J(He,Ee.offset)),Ae.set(pt,Pe),this.addOnDispose(()=>Pe.dispose()),Pe.addOnDispose(()=>Ae.delete(pt));if(ft)Pe=ft.apply(this,[Pe,Ke]);if(Dt.getter)V("debug.getter: result =",Pe);return Pe}});Object.defineProperty(ie.prototype,Ke,xt)},Cm=function F(ie,fe,Ee){if(Ee=ae(this,Ee),Ee.members)return Pm.call(this,ie,fe,Ee);if(!F.cache){F.cache={getters:{},setters:{},sw:{}};let pt=["i","c","C","p","P","s","f","d","v()"];if(G)pt.push("j");pt.forEach(function(Pe){F.cache.getters[Pe]=ve(Pe),F.cache.setters[Pe]=z(Pe),F.cache.sw[Pe]=g(Pe)}),F.sigCheck=function(Pe,lt,yo,Oc){if(Object.prototype.hasOwnProperty.call(Pe,yo))d(Pe.structName,"already has a property named",yo+".");qe(Oc)||d("Malformed signature for",w(Pe.structName,lt)+":",Oc)}}let Ae=ie.memberKey(fe);F.sigCheck(ie.prototype,fe,Ae,Ee.signature),Ee.key=Ae,Ee.name=fe;let Ke=W(Ee.signature),ft=w(ie.structName,Ae),xt=ie.debugFlags.__flags,Dt=mo(Ee),He=Object.create(null);if(He.configurable=!1,He.enumerable=!1,He.get=function(){if(xt.getter)V("debug.getter:",F.cache.getters[Ke],"for",he(Ke),ft,"@",this.pointer,"+",Ee.offset,"sz",Ee.sizeof);let pt=new DataView(E().buffer,Number(this.pointer)+Ee.offset,Ee.sizeof)[F.cache.getters[Ke]](0,S);if(Dt)pt=Dt.apply(this,[Ae,pt]);if(xt.getter)V("debug.getter:",ft,"result =",pt);return pt},Ee.readOnly)He.set=T(ie.prototype.structName,Ae);else{let pt=Ac(Ee);He.set=function(Pe){if(xt.setter)V("debug.setter:",F.cache.setters[Ke],"for",he(Ke),ft,"@",this.pointer,"+",Ee.offset,"sz",Ee.sizeof,Pe);if(!this.pointer)d("Cannot set native property on a disposed",this.structName,"instance.");if(pt)Pe=pt.apply(this,[Ae,Pe]);if(Pe===null||Pe===void 0)Pe=U;else if(K(Ee.signature)&&!L(Pe))if(oe(Ee.signature)&&Pe instanceof At){if(Pe=Pe.pointer||U,xt.setter)V("debug.setter:",ft,"resolved to",Pe)}else d("Invalid value for pointer-type",ft+".");new DataView(E().buffer,Number(this.pointer)+Ee.offset,Ee.sizeof)[F.cache.setters[Ke]](0,F.cache.sw[Ke](Pe),S)}}Object.defineProperty(ie.prototype,Ae,He)},Dc=function F(ie,fe,Ee=Object.create(null)){let Ae=function Pe(lt){if(!(this instanceof Pe))d("The",ie,"constructor may only be called via 'new'.");Ie(Pe,this,...arguments)},Ke=this,ft=(Pe)=>typeof Pe==="string"&&qe(Pe)?{signature:Pe}:ae(Ke,Pe);if(arguments.length===1)fe=ft(ie),ie=fe.structName||fe.name;else if(arguments.length===2)fe=ft(fe),fe.name??=ie;else fe=ft(fe);if(ie??=fe.structName,ie??=Ee.structName,!ie)d("One of 'name' or 'structName' are required.");if(fe.adapt)Object.keys(fe.adapt.struct||{}).forEach((Pe)=>{re.call(F,Pe,fe.adapt.struct[Pe])}),Object.keys(fe.adapt.set||{}).forEach((Pe)=>{B.call(F,Pe,fe.adapt.set[Pe])}),Object.keys(fe.adapt.get||{}).forEach((Pe)=>{zt.call(F,Pe,fe.adapt.get[Pe])});if(!fe.members&&!fe.sizeof)fe.sizeof=be(fe.signature);let xt=Te(p.__makeDebugFlags(Ct.debugFlags));Object.defineProperties(Ae,{debugFlags:xt,isA:Te((Pe)=>Pe instanceof Ae),memberKey:Se,memberKeys:ke,structInfo:Te(fe),structName:Te(ie),ptrAdd:Te(J)}),Ae.prototype=new At(ie,fe,Te),Object.defineProperties(Ae.prototype,{debugFlags:xt,constructor:Te(Ae),ptrAdd:Te(pe)});let Dt=!1,He=0,pt=!!fe.autoCalcSizeOffset;if(!pt){if(!fe.sizeof)d(ie,"description is missing its sizeof property.");fe.offset??=0}else fe.offset??=0;if(Object.keys(fe.members||{}).forEach((Pe)=>{let lt=ft(fe.members[Pe]);if(!lt.members&&!lt.sizeof){if(lt.sizeof=be(lt.signature),!lt.sizeof)d(w(ie,Pe),"is missing a sizeof property.",lt)}if(lt.offset===void 0)if(pt)lt.offset=He;else d(w(ie,Pe),"is missing its offset.",JSON.stringify(lt));if(fe.members[Pe]=lt,!Dt||Dt.offset<lt.offset)Dt=lt;let yo=!!lt.autoCalc;if(pt)lt.autoCalcSizeOffset=!0;if(Cm.call(Ke,Ae,Pe,lt),yo)lt.autoCalcSizeOffset=!0;else delete lt.autoCalcSizeOffset;He+=lt.sizeof}),!Dt)d("No member property descriptions found.");if(!fe.sizeof)fe.sizeof=He;if(fe.sizeof===1)fe.signature==="c"||fe.signature==="C"||d("Unexpected sizeof==1 member",w(ie,k),"with signature",fe.signature);else{if(fe.sizeof%4!==0)console.warn("Invalid struct member description",fe),d(ie,"sizeof is not aligned. sizeof="+fe.sizeof);if(fe.offset%4!==0)console.warn("Invalid struct member description",fe),d(ie,"offset is not aligned. offset="+fe.offset)}if(fe.sizeof<He)console.warn("Suspect struct description:",fe,"offset =",He),d("Mismatch in the calculated vs. the provided sizeof/offset info.","Expected sizeof",He,"but got",fe.sizeof,"for",fe);return delete fe.autoCalcSizeOffset,Ae},Ct=function F(ie,fe){return arguments.length==1?Dc.call(F,ie):Dc.call(F,ie,fe)};if(Ct.StructType=At,Ct.config=c,Ct.allocCString=Pr,Ct.adaptGet=zt,Ct.adaptSet=B,Ct.adaptStruct=re,Ct.ptrAdd=J,!Ct.debugFlags)Ct.debugFlags=p.__makeDebugFlags(p.debugFlags);return Ct},globalThis.sqlite3ApiBootstrap.initializers.push(function(f){let c=(...O)=>{throw Error(O.join(" "))},{capi:d,wasm:p,util:E}=f;globalThis.WhWasmUtilInstaller(p),delete globalThis.WhWasmUtilInstaller;let b={core:[["sqlite3_aggregate_context","void*","sqlite3_context*","int"],["sqlite3_bind_double","int","sqlite3_stmt*","int","f64"],["sqlite3_bind_int","int","sqlite3_stmt*","int","int"],["sqlite3_bind_null",void 0,"sqlite3_stmt*","int"],["sqlite3_bind_parameter_count","int","sqlite3_stmt*"],["sqlite3_bind_parameter_index","int","sqlite3_stmt*","string"],["sqlite3_bind_parameter_name","string","sqlite3_stmt*","int"],["sqlite3_bind_pointer","int","sqlite3_stmt*","int","*","string:static","*"],["sqlite3_bind_zeroblob","int","sqlite3_stmt*","int","int"],["sqlite3_busy_handler","int",["sqlite3*",new p.xWrap.FuncPtrAdapter({signature:"i(pi)",contextKey:(O,R)=>O[0]}),"*"]],["sqlite3_busy_timeout","int","sqlite3*","int"],["sqlite3_changes","int","sqlite3*"],["sqlite3_clear_bindings","int","sqlite3_stmt*"],["sqlite3_collation_needed","int","sqlite3*","*","*"],["sqlite3_column_blob","*","sqlite3_stmt*","int"],["sqlite3_column_bytes","int","sqlite3_stmt*","int"],["sqlite3_column_count","int","sqlite3_stmt*"],["sqlite3_column_decltype","string","sqlite3_stmt*","int"],["sqlite3_column_double","f64","sqlite3_stmt*","int"],["sqlite3_column_int","int","sqlite3_stmt*","int"],["sqlite3_column_name","string","sqlite3_stmt*","int"],["sqlite3_column_type","int","sqlite3_stmt*","int"],["sqlite3_column_value","sqlite3_value*","sqlite3_stmt*","int"],["sqlite3_commit_hook","void*",["sqlite3*",new p.xWrap.FuncPtrAdapter({name:"sqlite3_commit_hook",signature:"i(p)",contextKey:(O)=>O[0]}),"*"]],["sqlite3_compileoption_get","string","int"],["sqlite3_compileoption_used","int","string"],["sqlite3_complete","int","string:flexible"],["sqlite3_context_db_handle","sqlite3*","sqlite3_context*"],["sqlite3_data_count","int","sqlite3_stmt*"],["sqlite3_db_filename","string","sqlite3*","string"],["sqlite3_db_handle","sqlite3*","sqlite3_stmt*"],["sqlite3_db_name","string","sqlite3*","int"],["sqlite3_db_readonly","int","sqlite3*","string"],["sqlite3_db_status","int","sqlite3*","int","*","*","int"],["sqlite3_errcode","int","sqlite3*"],["sqlite3_errmsg","string","sqlite3*"],["sqlite3_error_offset","int","sqlite3*"],["sqlite3_errstr","string","int"],["sqlite3_exec","int",["sqlite3*","string:flexible",new p.xWrap.FuncPtrAdapter({signature:"i(pipp)",bindScope:"transient",callProxy:(O)=>{let R;return(X,ee,U,J)=>{try{let pe=p.cArgvToJs(ee,U);if(!R)R=p.cArgvToJs(ee,J);return O(pe,R)|0}catch(pe){return pe.resultCode||d.SQLITE_ERROR}}}}),"*","**"]],["sqlite3_expanded_sql","string","sqlite3_stmt*"],["sqlite3_extended_errcode","int","sqlite3*"],["sqlite3_extended_result_codes","int","sqlite3*","int"],["sqlite3_file_control","int","sqlite3*","string","int","*"],["sqlite3_finalize","int","sqlite3_stmt*"],["sqlite3_free",void 0,"*"],["sqlite3_get_autocommit","int","sqlite3*"],["sqlite3_get_auxdata","*","sqlite3_context*","int"],["sqlite3_initialize",void 0],["sqlite3_interrupt",void 0,"sqlite3*"],["sqlite3_is_interrupted","int","sqlite3*"],["sqlite3_keyword_count","int"],["sqlite3_keyword_name","int",["int","**","*"]],["sqlite3_keyword_check","int",["string","int"]],["sqlite3_libversion","string"],["sqlite3_libversion_number","int"],["sqlite3_limit","int",["sqlite3*","int","int"]],["sqlite3_malloc","*","int"],["sqlite3_next_stmt","sqlite3_stmt*",["sqlite3*","sqlite3_stmt*"]],["sqlite3_open","int","string","*"],["sqlite3_open_v2","int","string","*","int","string"],["sqlite3_realloc","*","*","int"],["sqlite3_reset","int","sqlite3_stmt*"],["sqlite3_result_blob",void 0,"sqlite3_context*","*","int","*"],["sqlite3_result_double",void 0,"sqlite3_context*","f64"],["sqlite3_result_error",void 0,"sqlite3_context*","string","int"],["sqlite3_result_error_code",void 0,"sqlite3_context*","int"],["sqlite3_result_error_nomem",void 0,"sqlite3_context*"],["sqlite3_result_error_toobig",void 0,"sqlite3_context*"],["sqlite3_result_int",void 0,"sqlite3_context*","int"],["sqlite3_result_null",void 0,"sqlite3_context*"],["sqlite3_result_pointer",void 0,"sqlite3_context*","*","string:static","*"],["sqlite3_result_subtype",void 0,"sqlite3_value*","int"],["sqlite3_result_text",void 0,"sqlite3_context*","string","int","*"],["sqlite3_result_zeroblob",void 0,"sqlite3_context*","int"],["sqlite3_rollback_hook","void*",["sqlite3*",new p.xWrap.FuncPtrAdapter({name:"sqlite3_rollback_hook",signature:"v(p)",contextKey:(O)=>O[0]}),"*"]],["sqlite3_set_auxdata",void 0,["sqlite3_context*","int","*","*"]],["sqlite3_set_errmsg","int","sqlite3*","int","string"],["sqlite3_shutdown",void 0],["sqlite3_sourceid","string"],["sqlite3_sql","string","sqlite3_stmt*"],["sqlite3_status","int","int","*","*","int"],["sqlite3_step","int","sqlite3_stmt*"],["sqlite3_stmt_busy","int","sqlite3_stmt*"],["sqlite3_stmt_readonly","int","sqlite3_stmt*"],["sqlite3_stmt_status","int","sqlite3_stmt*","int","int"],["sqlite3_strglob","int","string","string"],["sqlite3_stricmp","int","string","string"],["sqlite3_strlike","int","string","string","int"],["sqlite3_strnicmp","int","string","string","int"],["sqlite3_table_column_metadata","int","sqlite3*","string","string","string","**","**","*","*","*"],["sqlite3_total_changes","int","sqlite3*"],["sqlite3_trace_v2","int",["sqlite3*","int",new p.xWrap.FuncPtrAdapter({name:"sqlite3_trace_v2::callback",signature:"i(ippp)",contextKey:(O,R)=>O[0]}),"*"]],["sqlite3_txn_state","int",["sqlite3*","string"]],["sqlite3_uri_boolean","int","sqlite3_filename","string","int"],["sqlite3_uri_key","string","sqlite3_filename","int"],["sqlite3_uri_parameter","string","sqlite3_filename","string"],["sqlite3_user_data","void*","sqlite3_context*"],["sqlite3_value_blob","*","sqlite3_value*"],["sqlite3_value_bytes","int","sqlite3_value*"],["sqlite3_value_double","f64","sqlite3_value*"],["sqlite3_value_dup","sqlite3_value*","sqlite3_value*"],["sqlite3_value_free",void 0,"sqlite3_value*"],["sqlite3_value_frombind","int","sqlite3_value*"],["sqlite3_value_int","int","sqlite3_value*"],["sqlite3_value_nochange","int","sqlite3_value*"],["sqlite3_value_numeric_type","int","sqlite3_value*"],["sqlite3_value_pointer","*","sqlite3_value*","string:static"],["sqlite3_value_subtype","int","sqlite3_value*"],["sqlite3_value_type","int","sqlite3_value*"],["sqlite3_vfs_find","*","string"],["sqlite3_vfs_register","int","sqlite3_vfs*","int"],["sqlite3_vfs_unregister","int","sqlite3_vfs*"]],int64:[["sqlite3_bind_int64","int",["sqlite3_stmt*","int","i64"]],["sqlite3_changes64","i64",["sqlite3*"]],["sqlite3_column_int64","i64",["sqlite3_stmt*","int"]],["sqlite3_deserialize","int","sqlite3*","string","*","i64","i64","int"],["sqlite3_last_insert_rowid","i64",["sqlite3*"]],["sqlite3_malloc64","*","i64"],["sqlite3_msize","i64","*"],["sqlite3_overload_function","int",["sqlite3*","string","int"]],["sqlite3_realloc64","*","*","i64"],["sqlite3_result_int64",void 0,"*","i64"],["sqlite3_result_zeroblob64","int","*","i64"],["sqlite3_serialize","*","sqlite3*","string","*","int"],["sqlite3_set_last_insert_rowid",void 0,["sqlite3*","i64"]],["sqlite3_status64","int","int","*","*","int"],["sqlite3_db_status64","int","sqlite3*","int","*","*","int"],["sqlite3_total_changes64","i64",["sqlite3*"]],["sqlite3_update_hook","*",["sqlite3*",new p.xWrap.FuncPtrAdapter({name:"sqlite3_update_hook::callback",signature:"v(pippj)",contextKey:(O)=>O[0],callProxy:(O)=>(R,X,ee,U,J)=>{O(R,X,p.cstrToJs(ee),p.cstrToJs(U),J)}}),"*"]],["sqlite3_uri_int64","i64",["sqlite3_filename","string","i64"]],["sqlite3_value_int64","i64","sqlite3_value*"]],wasmInternal:[["sqlite3__wasm_db_reset","int","sqlite3*"],["sqlite3__wasm_db_vfs","sqlite3_vfs*","sqlite3*","string"],["sqlite3__wasm_vfs_create_file","int","sqlite3_vfs*","string","*","int"],["sqlite3__wasm_posix_create_file","int","string","*","int"],["sqlite3__wasm_vfs_unlink","int","sqlite3_vfs*","string"],["sqlite3__wasm_qfmt_token","string:dealloc","string","int"]]};if(p.exports.sqlite3_progress_handler)b.core.push(["sqlite3_progress_handler",void 0,["sqlite3*","int",new p.xWrap.FuncPtrAdapter({name:"xProgressHandler",signature:"i(p)",bindScope:"context",contextKey:(O,R)=>O[0]}),"*"]]);if(p.exports.sqlite3_stmt_explain)b.core.push(["sqlite3_stmt_explain","int","sqlite3_stmt*","int"],["sqlite3_stmt_isexplain","int","sqlite3_stmt*"]);if(p.exports.sqlite3_set_authorizer)b.core.push(["sqlite3_set_authorizer","int",["sqlite3*",new p.xWrap.FuncPtrAdapter({name:"sqlite3_set_authorizer::xAuth",signature:"i(pissss)",contextKey:(O,R)=>O[0],callProxy:(O)=>(R,X,ee,U,J,pe)=>{try{return ee=ee&&p.cstrToJs(ee),U=U&&p.cstrToJs(U),J=J&&p.cstrToJs(J),pe=pe&&p.cstrToJs(pe),O(R,X,ee,U,J,pe)|0}catch(S){return S.resultCode||d.SQLITE_ERROR}}}),"*"]]);if(p.exports.sqlite3_column_origin_name)b.core.push(["sqlite3_column_database_name","string","sqlite3_stmt*","int"],["sqlite3_column_origin_name","string","sqlite3_stmt*","int"],["sqlite3_column_table_name","string","sqlite3_stmt*","int"]);if(p.bigIntEnabled&&!!p.exports.sqlite3_declare_vtab)b.int64.push(["sqlite3_create_module","int",["sqlite3*","string","sqlite3_module*","*"]],["sqlite3_create_module_v2","int",["sqlite3*","string","sqlite3_module*","*","*"]],["sqlite3_declare_vtab","int",["sqlite3*","string:flexible"]],["sqlite3_drop_modules","int",["sqlite3*","**"]],["sqlite3_vtab_collation","string","sqlite3_index_info*","int"],["sqlite3_vtab_distinct","int","sqlite3_index_info*"],["sqlite3_vtab_in","int","sqlite3_index_info*","int","int"],["sqlite3_vtab_in_first","int","sqlite3_value*","**"],["sqlite3_vtab_in_next","int","sqlite3_value*","**"],["sqlite3_vtab_nochange","int","sqlite3_context*"],["sqlite3_vtab_on_conflict","int","sqlite3*"],["sqlite3_vtab_rhs_value","int","sqlite3_index_info*","int","**"]);if(p.bigIntEnabled&&!!p.exports.sqlite3_preupdate_hook)b.int64.push(["sqlite3_preupdate_blobwrite","int","sqlite3*"],["sqlite3_preupdate_count","int","sqlite3*"],["sqlite3_preupdate_depth","int","sqlite3*"],["sqlite3_preupdate_hook","*",["sqlite3*",new p.xWrap.FuncPtrAdapter({name:"sqlite3_preupdate_hook",signature:"v(ppippjj)",contextKey:(O)=>O[0],callProxy:(O)=>(R,X,ee,U,J,pe,S)=>{O(R,X,ee,p.cstrToJs(U),p.cstrToJs(J),pe,S)}}),"*"]],["sqlite3_preupdate_new","int",["sqlite3*","int","**"]],["sqlite3_preupdate_old","int",["sqlite3*","int","**"]]);if(p.bigIntEnabled&&!!p.exports.sqlite3changegroup_add&&!!p.exports.sqlite3session_create&&!!p.exports.sqlite3_preupdate_hook){let O={signature:"i(ps)",callProxy:(R)=>(X,ee)=>{try{return R(X,p.cstrToJs(ee))|0}catch(U){return U.resultCode||d.SQLITE_ERROR}}};b.int64.push(["sqlite3changegroup_add","int",["sqlite3_changegroup*","int","void*"]],["sqlite3changegroup_add_strm","int",["sqlite3_changegroup*",new p.xWrap.FuncPtrAdapter({name:"xInput",signature:"i(ppp)",bindScope:"transient"}),"void*"]],["sqlite3changegroup_delete",void 0,["sqlite3_changegroup*"]],["sqlite3changegroup_new","int",["**"]],["sqlite3changegroup_output","int",["sqlite3_changegroup*","int*","**"]],["sqlite3changegroup_output_strm","int",["sqlite3_changegroup*",new p.xWrap.FuncPtrAdapter({name:"xOutput",signature:"i(ppi)",bindScope:"transient"}),"void*"]],["sqlite3changeset_apply","int",["sqlite3*","int","void*",new p.xWrap.FuncPtrAdapter({name:"xFilter",bindScope:"transient",...O}),new p.xWrap.FuncPtrAdapter({name:"xConflict",signature:"i(pip)",bindScope:"transient"}),"void*"]],["sqlite3changeset_apply_strm","int",["sqlite3*",new p.xWrap.FuncPtrAdapter({name:"xInput",signature:"i(ppp)",bindScope:"transient"}),"void*",new p.xWrap.FuncPtrAdapter({name:"xFilter",bindScope:"transient",...O}),new p.xWrap.FuncPtrAdapter({name:"xConflict",signature:"i(pip)",bindScope:"transient"}),"void*"]],["sqlite3changeset_apply_v2","int",["sqlite3*","int","void*",new p.xWrap.FuncPtrAdapter({name:"xFilter",bindScope:"transient",...O}),new p.xWrap.FuncPtrAdapter({name:"xConflict",signature:"i(pip)",bindScope:"transient"}),"void*","**","int*","int"]],["sqlite3changeset_apply_v2_strm","int",["sqlite3*",new p.xWrap.FuncPtrAdapter({name:"xInput",signature:"i(ppp)",bindScope:"transient"}),"void*",new p.xWrap.FuncPtrAdapter({name:"xFilter",bindScope:"transient",...O}),new p.xWrap.FuncPtrAdapter({name:"xConflict",signature:"i(pip)",bindScope:"transient"}),"void*","**","int*","int"]],["sqlite3changeset_apply_v3","int",["sqlite3*","int","void*",new p.xWrap.FuncPtrAdapter({name:"xFilter",signature:"i(pp)",bindScope:"transient"}),new p.xWrap.FuncPtrAdapter({name:"xConflict",signature:"i(pip)",bindScope:"transient"}),"void*","**","int*","int"]],["sqlite3changeset_apply_v3_strm","int",["sqlite3*",new p.xWrap.FuncPtrAdapter({name:"xInput",signature:"i(ppp)",bindScope:"transient"}),"void*",new p.xWrap.FuncPtrAdapter({name:"xFilter",signature:"i(pp)",bindScope:"transient"}),new p.xWrap.FuncPtrAdapter({name:"xConflict",signature:"i(pip)",bindScope:"transient"}),"void*","**","int*","int"]],["sqlite3changeset_concat","int",["int","void*","int","void*","int*","**"]],["sqlite3changeset_concat_strm","int",[new p.xWrap.FuncPtrAdapter({name:"xInputA",signature:"i(ppp)",bindScope:"transient"}),"void*",new p.xWrap.FuncPtrAdapter({name:"xInputB",signature:"i(ppp)",bindScope:"transient"}),"void*",new p.xWrap.FuncPtrAdapter({name:"xOutput",signature:"i(ppi)",bindScope:"transient"}),"void*"]],["sqlite3changeset_conflict","int",["sqlite3_changeset_iter*","int","**"]],["sqlite3changeset_finalize","int",["sqlite3_changeset_iter*"]],["sqlite3changeset_fk_conflicts","int",["sqlite3_changeset_iter*","int*"]],["sqlite3changeset_invert","int",["int","void*","int*","**"]],["sqlite3changeset_invert_strm","int",[new p.xWrap.FuncPtrAdapter({name:"xInput",signature:"i(ppp)",bindScope:"transient"}),"void*",new p.xWrap.FuncPtrAdapter({name:"xOutput",signature:"i(ppi)",bindScope:"transient"}),"void*"]],["sqlite3changeset_new","int",["sqlite3_changeset_iter*","int","**"]],["sqlite3changeset_next","int",["sqlite3_changeset_iter*"]],["sqlite3changeset_old","int",["sqlite3_changeset_iter*","int","**"]],["sqlite3changeset_op","int",["sqlite3_changeset_iter*","**","int*","int*","int*"]],["sqlite3changeset_pk","int",["sqlite3_changeset_iter*","**","int*"]],["sqlite3changeset_start","int",["**","int","*"]],["sqlite3changeset_start_strm","int",["**",new p.xWrap.FuncPtrAdapter({name:"xInput",signature:"i(ppp)",bindScope:"transient"}),"void*"]],["sqlite3changeset_start_v2","int",["**","int","*","int"]],["sqlite3changeset_start_v2_strm","int",["**",new p.xWrap.FuncPtrAdapter({name:"xInput",signature:"i(ppp)",bindScope:"transient"}),"void*","int"]],["sqlite3session_attach","int",["sqlite3_session*","string"]],["sqlite3session_changeset","int",["sqlite3_session*","int*","**"]],["sqlite3session_changeset_size","i64",["sqlite3_session*"]],["sqlite3session_changeset_strm","int",["sqlite3_session*",new p.xWrap.FuncPtrAdapter({name:"xOutput",signature:"i(ppp)",bindScope:"transient"}),"void*"]],["sqlite3session_config","int",["int","void*"]],["sqlite3session_create","int",["sqlite3*","string","**"]],["sqlite3session_diff","int",["sqlite3_session*","string","string","**"]],["sqlite3session_enable","int",["sqlite3_session*","int"]],["sqlite3session_indirect","int",["sqlite3_session*","int"]],["sqlite3session_isempty","int",["sqlite3_session*"]],["sqlite3session_memory_used","i64",["sqlite3_session*"]],["sqlite3session_object_config","int",["sqlite3_session*","int","void*"]],["sqlite3session_patchset","int",["sqlite3_session*","*","**"]],["sqlite3session_patchset_strm","int",["sqlite3_session*",new p.xWrap.FuncPtrAdapter({name:"xOutput",signature:"i(ppp)",bindScope:"transient"}),"void*"]],["sqlite3session_table_filter",void 0,["sqlite3_session*",new p.xWrap.FuncPtrAdapter({name:"xFilter",...O,contextKey:(R,X)=>R[0]}),"*"]])}f.StructBinder=globalThis.Jaccwabyt({heap:p.heap8u,alloc:p.alloc,dealloc:p.dealloc,bigIntEnabled:p.bigIntEnabled,pointerIR:p.ptr.ir,memberPrefix:"$"}),delete globalThis.Jaccwabyt;{let O=p.xWrap.argAdapter("string");p.xWrap.argAdapter("string:flexible",(U)=>O(E.flexibleString(U))),p.xWrap.argAdapter("string:static",function(U){if(p.isPtr(U))return U;return U=""+U,this[U]||(this[U]=p.allocCString(U))}.bind(Object.create(null)));let R=p.xWrap.argAdapter("*"),X=function(){};if(p.xWrap.argAdapter("sqlite3_filename",R)("sqlite3_context*",R)("sqlite3_value*",R)("void*",R)("sqlite3_changegroup*",R)("sqlite3_changeset_iter*",R)("sqlite3_session*",R)("sqlite3_stmt*",(U)=>R(U instanceof(f?.oo1?.Stmt||X)?U.pointer:U))("sqlite3*",(U)=>R(U instanceof(f?.oo1?.DB||X)?U.pointer:U))("sqlite3_vfs*",(U)=>{if(typeof U==="string")return d.sqlite3_vfs_find(U)||f.SQLite3Error.toss(d.SQLITE_NOTFOUND,"Unknown sqlite3_vfs name:",U);return R(U instanceof(d.sqlite3_vfs||X)?U.pointer:U)}),p.exports.sqlite3_declare_vtab)p.xWrap.argAdapter("sqlite3_index_info*",(U)=>R(U instanceof(d.sqlite3_index_info||X)?U.pointer:U))("sqlite3_module*",(U)=>R(U instanceof(d.sqlite3_module||X)?U.pointer:U));let ee=p.xWrap.resultAdapter("*");p.xWrap.resultAdapter("sqlite3*",ee)("sqlite3_context*",ee)("sqlite3_stmt*",ee)("sqlite3_value*",ee)("sqlite3_vfs*",ee)("void*",ee);for(let U of b.core)d[U[0]]=p.xWrap.apply(null,U);for(let U of b.wasmInternal)E[U[0]]=p.xWrap.apply(null,U);for(let U of b.int64)d[U[0]]=p.bigIntEnabled?p.xWrap.apply(null,U):()=>c(U[0]+"() is unavailable due to lack","of BigInt support in this build.");delete b.core,delete b.int64,delete b.wasmInternal,E.sqlite3__wasm_db_error=function(U,J,pe){if(!U)return d.SQLITE_MISUSE;if(J instanceof f.WasmAllocError)J=d.SQLITE_NOMEM,pe=0;else if(J instanceof Error)pe=pe||""+J,J=J.resultCode||d.SQLITE_ERROR;return d.sqlite3_set_errmsg(U,J,pe)||J}}{let O=p.xCall("sqlite3__wasm_enum_json");if(!O)c("Maintenance required: increase sqlite3__wasm_enum_json()'s","static buffer size!");p.ctype=JSON.parse(p.cstrToJs(O));let R=["access","authorizer","blobFinalizers","changeset","config","dataTypes","dbConfig","dbStatus","encodings","fcntl","flock","ioCap","limits","openFlags","prepareFlags","resultCodes","sqlite3Status","stmtStatus","syncFlags","trace","txnState","udfFlags","version"];if(p.bigIntEnabled)R.push("serialize","session","vtab");for(let U of R)for(let J of Object.entries(p.ctype[U]))d[J[0]]=J[1];if(!p.functionEntry(d.SQLITE_WASM_DEALLOC))c("Internal error: cannot resolve exported function","entry SQLITE_WASM_DEALLOC (=="+d.SQLITE_WASM_DEALLOC+").");let X=Object.create(null);for(let U of Object.entries(p.ctype.resultCodes))X[U[1]]=U[0];d.sqlite3_js_rc_str=(U)=>X[U];let ee=Object.assign(Object.create(null),{WasmTestStruct:!0,sqlite3_index_info:!p.bigIntEnabled,sqlite3_index_constraint:!p.bigIntEnabled,sqlite3_index_orderby:!p.bigIntEnabled,sqlite3_index_constraint_usage:!p.bigIntEnabled});for(let U of p.ctype.structs)if(!ee[U.name])d[U.name]=f.StructBinder(U);if(d.sqlite3_index_info){for(let U of["sqlite3_index_constraint","sqlite3_index_orderby","sqlite3_index_constraint_usage"])d.sqlite3_index_info[U]=d[U],delete d[U];d.sqlite3_vtab_config=p.xWrap("sqlite3__wasm_vtab_config","int",["sqlite3*","int","int"])}}let I=(O,R,X)=>E.sqlite3__wasm_db_error(O,d.SQLITE_MISUSE,R+"() requires "+X+" argument"+(X===1?"":"s")+"."),V=(O)=>E.sqlite3__wasm_db_error(O,d.SQLITE_FORMAT,"SQLITE_UTF8 is the only supported encoding."),M=(O)=>p.xWrap.argAdapter("sqlite3*")(O),N=(O)=>p.isPtr(O)?p.cstrToJs(O):O,q=function(O,R){O=M(O);let X=this.dbMap.get(O);if(!R)return this.dbMap.delete(O),X;else if(!X&&R>0)this.dbMap.set(O,X=Object.create(null));return X}.bind(Object.assign(Object.create(null),{dbMap:new Map}));if(q.addCollation=function(O,R){let X=q(O,1);if(!X.collation)X.collation=new Set;X.collation.add(N(R).toLowerCase())},q._addUDF=function(O,R,X,ee){R=N(R).toLowerCase();let U=ee.get(R);if(!U)ee.set(R,U=new Set);U.add(X<0?-1:X)},q.addFunction=function(O,R,X){let ee=q(O,1);if(!ee.udf)ee.udf=new Map;this._addUDF(O,R,X,ee.udf)},p.exports.sqlite3_create_window_function)q.addWindowFunc=function(O,R,X){let ee=q(O,1);if(!ee.wudf)ee.wudf=new Map;this._addUDF(O,R,X,ee.wudf)};q.cleanup=function(O){O=M(O);for(let ee of[["sqlite3_busy_handler",3],["sqlite3_commit_hook",3],["sqlite3_preupdate_hook",3],["sqlite3_progress_handler",4],["sqlite3_rollback_hook",3],["sqlite3_set_authorizer",3],["sqlite3_trace_v2",4],["sqlite3_update_hook",3]]){let[U,J]=ee;if(!p.exports[U])continue;let pe=[O];pe.length=J;try{d[U](...pe)}catch(S){f.config.warn("close-time call of",U+"(",pe,") threw:",S)}}let R=q(O,0);if(!R)return;if(R.collation){for(let ee of R.collation)try{d.sqlite3_create_collation_v2(O,ee,d.SQLITE_UTF8,0,0,0)}catch(U){}delete R.collation}let X;for(X=0;X<2;++X){let ee=X?R.wudf:R.udf;if(!ee)continue;let U=X?d.sqlite3_create_window_function:d.sqlite3_create_function_v2;for(let J of ee){let pe=J[0],S=J[1],P=[O,pe,0,d.SQLITE_UTF8,0,0,0,0,0];if(X)P.push(0);for(let K of S)try{P[2]=K,U.apply(null,P)}catch(oe){}S.clear()}ee.clear()}delete R.udf,delete R.wudf};{let O=p.xWrap("sqlite3_close_v2","int","sqlite3*");d.sqlite3_close_v2=function(R){if(arguments.length!==1)return I(R,"sqlite3_close_v2",1);if(R)try{q.cleanup(R)}catch(X){}return O(R)}}if(d.sqlite3session_create){let O=p.xWrap("sqlite3session_delete",void 0,["sqlite3_session*"]);d.sqlite3session_delete=function(R){if(arguments.length!==1)return I(pDb,"sqlite3session_delete",1);else if(R)d.sqlite3session_table_filter(R,0,0);O(R)}}{let O=(X,ee)=>"argv["+ee+"]:"+X[0]+":"+p.cstrToJs(X[1]).toLowerCase(),R=p.xWrap("sqlite3_create_collation_v2","int",["sqlite3*","string","int","*",new p.xWrap.FuncPtrAdapter({name:"xCompare",signature:"i(pipip)",contextKey:O}),new p.xWrap.FuncPtrAdapter({name:"xDestroy",signature:"v(p)",contextKey:O})]);d.sqlite3_create_collation_v2=function(X,ee,U,J,pe,S){if(arguments.length!==6)return I(X,"sqlite3_create_collation_v2",6);else if((U&15)===0)U|=d.SQLITE_UTF8;else if(d.SQLITE_UTF8!==(U&15))return V(X);try{let P=R(X,ee,U,J,pe,S);if(P===0&&pe instanceof Function)q.addCollation(X,ee);return P}catch(P){return E.sqlite3__wasm_db_error(X,P)}},d.sqlite3_create_collation=(X,ee,U,J,pe)=>arguments.length===5?d.sqlite3_create_collation_v2(X,ee,U,J,pe,0):I(X,"sqlite3_create_collation",5)}{let O=function(U,J){return U[0]+":"+(U[2]<0?-1:U[2])+":"+J+":"+p.cstrToJs(U[1]).toLowerCase()},R=Object.assign(Object.create(null),{xInverseAndStep:{signature:"v(pip)",contextKey:O,callProxy:(U)=>(J,pe,S)=>{try{U(J,...d.sqlite3_values_to_js(pe,S))}catch(P){d.sqlite3_result_error_js(J,P)}}},xFinalAndValue:{signature:"v(p)",contextKey:O,callProxy:(U)=>(J)=>{try{d.sqlite3_result_js(J,U(J))}catch(pe){d.sqlite3_result_error_js(J,pe)}}},xFunc:{signature:"v(pip)",contextKey:O,callProxy:(U)=>(J,pe,S)=>{try{d.sqlite3_result_js(J,U(J,...d.sqlite3_values_to_js(pe,S)))}catch(P){d.sqlite3_result_error_js(J,P)}}},xDestroy:{signature:"v(p)",contextKey:O,callProxy:(U)=>(J)=>{try{U(J)}catch(pe){console.error("UDF xDestroy method threw:",pe)}}}}),X=p.xWrap("sqlite3_create_function_v2","int",["sqlite3*","string","int","int","*",new p.xWrap.FuncPtrAdapter({name:"xFunc",...R.xFunc}),new p.xWrap.FuncPtrAdapter({name:"xStep",...R.xInverseAndStep}),new p.xWrap.FuncPtrAdapter({name:"xFinal",...R.xFinalAndValue}),new p.xWrap.FuncPtrAdapter({name:"xDestroy",...R.xDestroy})]),ee=p.exports.sqlite3_create_window_function?p.xWrap("sqlite3_create_window_function","int",["sqlite3*","string","int","int","*",new p.xWrap.FuncPtrAdapter({name:"xStep",...R.xInverseAndStep}),new p.xWrap.FuncPtrAdapter({name:"xFinal",...R.xFinalAndValue}),new p.xWrap.FuncPtrAdapter({name:"xValue",...R.xFinalAndValue}),new p.xWrap.FuncPtrAdapter({name:"xInverse",...R.xInverseAndStep}),new p.xWrap.FuncPtrAdapter({name:"xDestroy",...R.xDestroy})]):void 0;if(d.sqlite3_create_function_v2=function U(J,pe,S,P,K,oe,W,he,be){if(U.length!==arguments.length)return I(J,"sqlite3_create_function_v2",U.length);else if((P&15)===0)P|=d.SQLITE_UTF8;else if(d.SQLITE_UTF8!==(P&15))return V(J);try{let me=X(J,pe,S,P,K,oe,W,he,be);if(me===0&&(oe instanceof Function||W instanceof Function||he instanceof Function||be instanceof Function))q.addFunction(J,pe,S);return me}catch(me){return console.error("sqlite3_create_function_v2() setup threw:",me),E.sqlite3__wasm_db_error(J,me,"Creation of UDF threw: "+me)}},d.sqlite3_create_function=function U(J,pe,S,P,K,oe,W,he){return U.length===arguments.length?d.sqlite3_create_function_v2(J,pe,S,P,K,oe,W,he,0):I(J,"sqlite3_create_function",U.length)},ee)d.sqlite3_create_window_function=function U(J,pe,S,P,K,oe,W,he,be,me){if(U.length!==arguments.length)return I(J,"sqlite3_create_window_function",U.length);else if((P&15)===0)P|=d.SQLITE_UTF8;else if(d.SQLITE_UTF8!==(P&15))return V(J);try{let ve=ee(J,pe,S,P,K,oe,W,he,be,me);if(ve===0&&(oe instanceof Function||W instanceof Function||he instanceof Function||be instanceof Function||me instanceof Function))q.addWindowFunc(J,pe,S);return ve}catch(ve){return console.error("sqlite3_create_window_function() setup threw:",ve),E.sqlite3__wasm_db_error(J,ve,"Creation of UDF threw: "+ve)}};else delete d.sqlite3_create_window_function;if(d.sqlite3_create_function_v2.udfSetResult=d.sqlite3_create_function.udfSetResult=d.sqlite3_result_js,d.sqlite3_create_window_function)d.sqlite3_create_window_function.udfSetResult=d.sqlite3_result_js;if(d.sqlite3_create_function_v2.udfConvertArgs=d.sqlite3_create_function.udfConvertArgs=d.sqlite3_values_to_js,d.sqlite3_create_window_function)d.sqlite3_create_window_function.udfConvertArgs=d.sqlite3_values_to_js;if(d.sqlite3_create_function_v2.udfSetError=d.sqlite3_create_function.udfSetError=d.sqlite3_result_error_js,d.sqlite3_create_window_function)d.sqlite3_create_window_function.udfSetError=d.sqlite3_result_error_js}{let O=(X,ee)=>{if(typeof X==="string")ee=-1;else if(E.isSQLableTypedArray(X))ee=X.byteLength,X=p.typedArrayToString(X instanceof ArrayBuffer?new Uint8Array(X):X);else if(Array.isArray(X))X=X.join(""),ee=-1;return[X,ee]},R={basic:p.xWrap("sqlite3_prepare_v3","int",["sqlite3*","string","int","int","**","**"]),full:p.xWrap("sqlite3_prepare_v3","int",["sqlite3*","*","int","int","**","**"])};d.sqlite3_prepare_v3=function X(ee,U,J,pe,S,P){if(X.length!==arguments.length)return I(ee,"sqlite3_prepare_v3",X.length);let[K,oe]=O(U,Number(J));switch(typeof K){case"string":return R.basic(ee,K,oe,pe,S,null);case typeof p.ptr.null:return R.full(ee,p.ptr.coerce(K),oe,pe,S,P);default:return E.sqlite3__wasm_db_error(ee,d.SQLITE_MISUSE,"Invalid SQL argument type for sqlite3_prepare_v2/v3(). typeof="+typeof K)}},d.sqlite3_prepare_v2=function X(ee,U,J,pe,S){return X.length===arguments.length?d.sqlite3_prepare_v3(ee,U,J,0,pe,S):I(ee,"sqlite3_prepare_v2",X.length)}}{let O=p.xWrap("sqlite3_bind_text","int",["sqlite3_stmt*","int","string","int","*"]),R=p.xWrap("sqlite3_bind_blob","int",["sqlite3_stmt*","int","*","int","*"]);d.sqlite3_bind_text=function X(ee,U,J,pe,S){if(X.length!==arguments.length)return I(d.sqlite3_db_handle(ee),"sqlite3_bind_text",X.length);else if(p.isPtr(J)||J===null)return O(ee,U,J,pe,S);else if(J instanceof ArrayBuffer)J=new Uint8Array(J);else if(Array.isArray(pMem))J=pMem.join("");let P,K;try{if(E.isSQLableTypedArray(J))P=p.allocFromTypedArray(J),K=J.byteLength;else if(typeof J==="string")[P,K]=p.allocCString(J);else return E.sqlite3__wasm_db_error(d.sqlite3_db_handle(ee),d.SQLITE_MISUSE,"Invalid 3rd argument type for sqlite3_bind_text().");return O(ee,U,P,K,d.SQLITE_WASM_DEALLOC)}catch(oe){return p.dealloc(P),E.sqlite3__wasm_db_error(d.sqlite3_db_handle(ee),oe)}},d.sqlite3_bind_blob=function X(ee,U,J,pe,S){if(X.length!==arguments.length)return I(d.sqlite3_db_handle(ee),"sqlite3_bind_blob",X.length);else if(p.isPtr(J)||J===null)return R(ee,U,J,pe,S);else if(J instanceof ArrayBuffer)J=new Uint8Array(J);else if(Array.isArray(J))J=J.join("");let P,K;try{if(E.isBindableTypedArray(J))P=p.allocFromTypedArray(J),K=pe>=0?pe:J.byteLength;else if(typeof J==="string")[P,K]=p.allocCString(J);else return E.sqlite3__wasm_db_error(d.sqlite3_db_handle(ee),d.SQLITE_MISUSE,"Invalid 3rd argument type for sqlite3_bind_blob().");return R(ee,U,P,K,d.SQLITE_WASM_DEALLOC)}catch(oe){return p.dealloc(P),E.sqlite3__wasm_db_error(d.sqlite3_db_handle(ee),oe)}}}if(!d.sqlite3_column_text){let O=p.xWrap.argAdapter("sqlite3_stmt*"),R=p.xWrap.argAdapter("int"),X=p.xWrap.argAdapter("sqlite3_value*"),ee=(U,J)=>p.typedArrayToString(p.heap8u(),Number(U),Number(U)+J);d.sqlite3_column_text=function(U,J){let pe=O(U),S=R(J),P=p.exports.sqlite3_column_text(pe,S);return P?ee(P,p.exports.sqlite3_column_bytes(pe,S)):null},d.sqlite3_value_text=function(U){let J=X(U),pe=p.exports.sqlite3_value_text(J);return pe?ee(pe,p.exports.sqlite3_value_bytes(J)):null}}d.sqlite3_config=function(O,...R){if(arguments.length<2)return d.SQLITE_MISUSE;switch(O){case d.SQLITE_CONFIG_COVERING_INDEX_SCAN:case d.SQLITE_CONFIG_MEMSTATUS:case d.SQLITE_CONFIG_SMALL_MALLOC:case d.SQLITE_CONFIG_SORTERREF_SIZE:case d.SQLITE_CONFIG_STMTJRNL_SPILL:case d.SQLITE_CONFIG_URI:return p.exports.sqlite3__wasm_config_i(O,R[0]);case d.SQLITE_CONFIG_LOOKASIDE:return p.exports.sqlite3__wasm_config_ii(O,R[0],R[1]);case d.SQLITE_CONFIG_MEMDB_MAXSIZE:return p.exports.sqlite3__wasm_config_j(O,R[0]);case d.SQLITE_CONFIG_GETMALLOC:case d.SQLITE_CONFIG_GETMUTEX:case d.SQLITE_CONFIG_GETPCACHE2:case d.SQLITE_CONFIG_GETPCACHE:case d.SQLITE_CONFIG_HEAP:case d.SQLITE_CONFIG_LOG:case d.SQLITE_CONFIG_MALLOC:case d.SQLITE_CONFIG_MMAP_SIZE:case d.SQLITE_CONFIG_MULTITHREAD:case d.SQLITE_CONFIG_MUTEX:case d.SQLITE_CONFIG_PAGECACHE:case d.SQLITE_CONFIG_PCACHE2:case d.SQLITE_CONFIG_PCACHE:case d.SQLITE_CONFIG_PCACHE_HDRSZ:case d.SQLITE_CONFIG_PMASZ:case d.SQLITE_CONFIG_SERIALIZED:case d.SQLITE_CONFIG_SINGLETHREAD:case d.SQLITE_CONFIG_SQLLOG:case d.SQLITE_CONFIG_WIN32_HEAPSIZE:default:return d.SQLITE_NOTFOUND}};{let O=new Set;d.sqlite3_auto_extension=function(R){if(R instanceof Function)R=p.installFunction("i(ppp)",R);else if(arguments.length!==1||!p.isPtr(R))return d.SQLITE_MISUSE;let X=p.exports.sqlite3_auto_extension(R);if(R!==arguments[0])if(X===0)O.add(R);else p.uninstallFunction(R);return X},d.sqlite3_cancel_auto_extension=function(R){if(!R||arguments.length!==1||!p.isPtr(R))return 0;return p.exports.sqlite3_cancel_auto_extension(R)},d.sqlite3_reset_auto_extension=function(){p.exports.sqlite3_reset_auto_extension();for(let R of O)p.uninstallFunction(R);O.clear()}}p.xWrap.FuncPtrAdapter.warnOnUse=!0;let H=f.StructBinder,G=function O(R,X,ee,U=O.installMethodArgcCheck){if(!(R instanceof H.StructType))c("Usage error: target object is-not-a StructType.");else if(!(ee instanceof Function)&&!p.isPtr(ee))c("Usage error: expecting a Function or WASM pointer to one.");if(arguments.length===1)return(P,K)=>O(R,P,K,U);if(!O.argcProxy)O.argcProxy=function(P,K,oe,W){return function(...he){if(oe.length!==arguments.length)c("Argument mismatch for",P.structInfo.name+"::"+K+": Native signature is:",W);return oe.apply(this,he)}},O.removeFuncList=function(){if(this.ondispose.__removeFuncList)this.ondispose.__removeFuncList.forEach((P,K)=>{if(p.isPtr(P))try{p.uninstallFunction(P)}catch(oe){}}),delete this.ondispose.__removeFuncList};let J=R.memberSignature(X);if(J.length<2)c("Member",X,"does not have a function pointer signature:",J);let pe=R.memberKey(X),S=U&&!p.isPtr(ee)?O.argcProxy(R,pe,ee,J):ee;if(p.isPtr(S)){if(S&&!p.functionEntry(S))c("Pointer",S,"is not a WASM function table entry.");R[pe]=S}else{let P=p.installFunction(S,J);if(R[pe]=P,!R.ondispose||!R.ondispose.__removeFuncList)R.addOnDispose("ondispose.__removeFuncList handler",O.removeFuncList),R.ondispose.__removeFuncList=[];R.ondispose.__removeFuncList.push(pe,P)}return(P,K)=>O(R,P,K,U)};G.installMethodArgcCheck=!1;let le=function(O,R,X=G.installMethodArgcCheck){let ee=new Map;for(let U of Object.keys(R)){let J=R[U],pe=ee.get(J);if(pe){let S=O.memberKey(U);O[S]=O[O.memberKey(pe)]}else G(O,U,J,X),ee.set(J,U)}return O};H.StructType.prototype.installMethod=function(R,X,ee=G.installMethodArgcCheck){return arguments.length<3&&R&&typeof R==="object"?le(this,...arguments):G(this,...arguments)},H.StructType.prototype.installMethods=function(O,R=G.installMethodArgcCheck){return le(this,O,R)}}),globalThis.sqlite3ApiBootstrap.initializers.push(function(f){let c=(...z)=>{throw new f.SQLite3Error(...z)},{capi:d,wasm:p,util:E}=f,b=function(z){return(...g)=>z("sqlite3.oo1:",...g)};f.__isUnderTest?b(console.debug.bind(console)):b(f.config.debug),f.__isUnderTest?b(console.warn.bind(console)):b(f.config.warn),f.__isUnderTest?b(console.error.bind(console)):b(f.config.error);let I=new WeakMap,V=new Set,M=new WeakMap,N=(z,g,w)=>{let T=Object.getOwnPropertyDescriptor(z,g);return T?T.value:w},q=function(z,g){if(g){if(z instanceof O)z=z.pointer;c(g,"sqlite3 result code",g+":",z?d.sqlite3_errmsg(z):d.sqlite3_errstr(g))}return arguments[0]},H=p.installFunction("i(ippp)",function(z,g,w,T){if(d.SQLITE_TRACE_STMT===z)console.log("SQL TRACE #"+ ++this.counter,"via sqlite3@"+g+"["+d.sqlite3_db_filename(g,null)+"]",p.cstrToJs(T))}.bind({counter:0})),G=Object.create(null),le=function z(...g){let w=z.normalizeArgs(...g),T;if(T=w["sqlite3*"]){if(!w["sqlite3*:takeOwnership"])V.add(this);this.filename=d.sqlite3_db_filename(T,"main")}else{let{filename:C,vfs:te,flags:se}=w;if(typeof C!=="string"&&!p.isPtr(C)||typeof se!=="string"||te&&typeof te!=="string"&&!p.isPtr(te))f.config.error("Invalid DB ctor args",w,arguments),c("Invalid arguments for DB constructor:",arguments,"opts:",w);let A=0;if(se.indexOf("c")>=0)A|=d.SQLITE_OPEN_CREATE|d.SQLITE_OPEN_READWRITE;if(se.indexOf("w")>=0)A|=d.SQLITE_OPEN_READWRITE;if(A===0)A|=d.SQLITE_OPEN_READONLY;A|=d.SQLITE_OPEN_EXRESCODE;let L=p.pstack.pointer;try{let Q=p.pstack.allocPtr(),ne=d.sqlite3_open_v2(C,Q,A,te||p.ptr.null);if(T=p.peekPtr(Q),q(T,ne),d.sqlite3_extended_result_codes(T,1),se.indexOf("t")>=0)d.sqlite3_trace_v2(T,d.SQLITE_TRACE_STMT,H,T)}catch(Q){if(T)d.sqlite3_close_v2(T);throw Q}finally{p.pstack.restore(L)}this.filename=p.isPtr(C)?p.cstrToJs(C):C}if(I.set(this,T),M.set(this,Object.create(null)),!w["sqlite3*"])try{let C=G[d.sqlite3_js_db_vfs(T)||c("Internal error: cannot get VFS for new db handle.")];if(C)if(C instanceof Function)C(this,f);else q(T,d.sqlite3_exec(T,C,0,0,0))}catch(C){throw this.close(),C}};le.setVfsPostOpenCallback=function(z,g){if(!(g instanceof Function))c("dbCtorHelper.setVfsPostOpenCallback() should not be used with a non-function argument.",arguments);G[z]=g},le.normalizeArgs=function(z=":memory:",g="c",w=null){let T={};if(arguments.length===1&&arguments[0]&&typeof arguments[0]==="object"){if(Object.assign(T,arguments[0]),T.flags===void 0)T.flags="c";if(T.vfs===void 0)T.vfs=null;if(T.filename===void 0)T.filename=":memory:"}else T.filename=z,T.flags=g,T.vfs=w;return T};let O=function(...z){le.apply(this,z)};O.dbCtorHelper=le;let R={null:1,number:2,string:3,boolean:4,blob:5};if(p.bigIntEnabled)R.bigint=R.number;let X=function(){if(R!==arguments[2])c(d.SQLITE_MISUSE,"Do not call the Stmt constructor directly. Use DB.prepare().");if(this.db=arguments[0],I.set(this,arguments[1]),arguments.length>3&&!arguments[3])V.add(this)},ee=function(z){if(!z.pointer)c("DB has been closed.");return z},U=function(z,g){if(g!==(g|0)||g<0||g>=z.columnCount)c("Column index",g,"is out of range.");return z},J=function(z,g){let w=Object.create(null);switch(w.opt=Object.create(null),g.length){case 1:if(typeof g[0]==="string"||E.isSQLableTypedArray(g[0]))w.sql=g[0];else if(Array.isArray(g[0]))w.sql=g[0];else if(g[0]&&typeof g[0]==="object")w.opt=g[0],w.sql=w.opt.sql;break;case 2:w.sql=g[0],w.opt=g[1];break;default:c("Invalid argument count for exec().")}if(w.sql=E.flexibleString(w.sql),typeof w.sql!=="string")c("Missing SQL argument or unsupported SQL value type.");let T=w.opt;switch(T.returnValue){case"resultRows":if(!T.resultRows)T.resultRows=[];w.returnVal=()=>T.resultRows;break;case"saveSql":if(!T.saveSql)T.saveSql=[];w.returnVal=()=>T.saveSql;break;case void 0:case"this":w.returnVal=()=>z;break;default:c("Invalid returnValue value:",T.returnValue)}if(!T.callback&&!T.returnValue&&T.rowMode!==void 0){if(!T.resultRows)T.resultRows=[];w.returnVal=()=>T.resultRows}if(T.callback||T.resultRows)switch(T.rowMode===void 0?"array":T.rowMode){case"object":w.cbArg=(C,te)=>{if(!te.columnNames)te.columnNames=C.getColumnNames([]);let se=C.get([]),A=Object.create(null);for(let L in te.columnNames)A[te.columnNames[L]]=se[L];return A};break;case"array":w.cbArg=(C)=>C.get([]);break;case"stmt":if(Array.isArray(T.resultRows))c("exec(): invalid rowMode for a resultRows array: must","be one of 'array', 'object',","a result column number, or column name reference.");w.cbArg=(C)=>C;break;default:if(E.isInt32(T.rowMode)){w.cbArg=(C)=>C.get(T.rowMode);break}else if(typeof T.rowMode==="string"&&T.rowMode.length>1&&T.rowMode[0]==="$"){let C=T.rowMode.substr(1);w.cbArg=(te)=>{let se=te.get(Object.create(null))[C];return se===void 0?c(d.SQLITE_NOTFOUND,"exec(): unknown result column:",C):se};break}c("Invalid rowMode:",T.rowMode)}return w},pe=(z,g,w,...T)=>{let C=z.prepare(g);try{let te=C.bind(w).step()?C.get(...T):void 0;return C.reset(),te}finally{C.finalize()}},S=(z,g,w,T)=>z.exec({sql:g,bind:w,rowMode:T,returnValue:"resultRows"});O.checkRc=(z,g)=>q(z,g),O.prototype={isOpen:function(){return!!this.pointer},affirmOpen:function(){return ee(this)},close:function(){let z=this.pointer;if(z){if(this.onclose&&this.onclose.before instanceof Function)try{this.onclose.before(this)}catch(g){}if(Object.keys(M.get(this)).forEach((g,w)=>{if(w&&w.pointer)try{w.finalize()}catch(T){}}),I.delete(this),M.delete(this),!V.delete(this))d.sqlite3_close_v2(z);if(this.onclose&&this.onclose.after instanceof Function)try{this.onclose.after(this)}catch(g){}delete this.filename}},changes:function(z=!1,g=!1){let w=ee(this).pointer;if(z)return g?d.sqlite3_total_changes64(w):d.sqlite3_total_changes(w);else return g?d.sqlite3_changes64(w):d.sqlite3_changes(w)},dbFilename:function(z="main"){return d.sqlite3_db_filename(ee(this).pointer,z)},dbName:function(z=0){return d.sqlite3_db_name(ee(this).pointer,z)},dbVfsName:function(z=0){let g,w=d.sqlite3_js_db_vfs(ee(this).pointer,z);if(w){let T=new d.sqlite3_vfs(w);try{g=p.cstrToJs(T.$zName)}finally{T.dispose()}}return g},prepare:function(z){ee(this);let g=p.pstack.pointer,w,T;try{w=p.pstack.alloc(8),O.checkRc(this,d.sqlite3_prepare_v2(this.pointer,z,-1,w,null)),T=p.peekPtr(w)}finally{p.pstack.restore(g)}if(!T)c("Cannot prepare empty SQL.");let C=new X(this,T,R);return M.get(this)[T]=C,C},exec:function(){ee(this);let z=J(this,arguments);if(!z.sql)return c("exec() requires an SQL string.");let g=z.opt,w=g.callback,T=Array.isArray(g.resultRows)?g.resultRows:void 0,C,te=g.bind,se=!!(z.cbArg||g.columnNames||T),A=p.scopedAllocPush(),L=Array.isArray(g.saveSql)?g.saveSql:void 0;try{let Q=E.isSQLableTypedArray(z.sql),ne=Q?z.sql.byteLength:p.jstrlen(z.sql),ye=p.scopedAlloc(2*p.ptr.size+(ne+1)),Te=p.ptr.add(ye,p.ptr.size),Ie=p.ptr.add(Te,p.ptr.size),qe=p.ptr.add(Ie,ne);if(Q)p.heap8().set(z.sql,Ie);else p.jstrcpy(z.sql,p.heap8(),Ie,ne,!1);p.poke8(p.ptr.add(Ie,ne),0);while(Ie&&p.peek8(Ie)){p.pokePtr([ye,Te],0),O.checkRc(this,d.sqlite3_prepare_v3(this.pointer,Ie,ne,0,ye,Te));let Ge=p.peekPtr(ye);if(Ie=p.peekPtr(Te),ne=Number(p.ptr.add(qe,-Ie)),!Ge)continue;if(L)L.push(d.sqlite3_sql(Ge).trim());if(C=new X(this,Ge,R),te&&C.parameterCount)C.bind(te),te=null;if(se&&C.columnCount){let ct=Array.isArray(g.columnNames)?0:1;if(se=!1,z.cbArg||T){let zt=Object.create(null);for(;C.step();he.delete(C)){if(ct++===0)C.getColumnNames(zt.columnNames=g.columnNames||[]);he.add(C);let Ir=z.cbArg(C,zt);if(T)T.push(Ir);if(w&&w.call(g,Ir,C)===!1)break}he.delete(C)}if(ct===0)C.getColumnNames(g.columnNames)}else C.step();C.reset().finalize(),C=null}}finally{if(C)he.delete(C),C.finalize();p.scopedAllocPop(A)}return z.returnVal()},createFunction:function(g,w,T){let C=(zt)=>zt instanceof Function;switch(arguments.length){case 1:T=g,g=T.name,w=T.xFunc||0;break;case 2:if(!C(w))T=w,w=T.xFunc||0;break;case 3:break;default:break}if(!T)T={};if(typeof g!=="string")c("Invalid arguments: missing function name.");let te=T.xStep||0,se=T.xFinal||0,A=T.xValue||0,L=T.xInverse||0,Q=void 0;if(C(w)){if(Q=!1,C(te)||C(se))c("Ambiguous arguments: scalar or aggregate?");te=se=null}else if(C(te)){if(!C(se))c("Missing xFinal() callback for aggregate or window UDF.");w=null}else if(C(se))c("Missing xStep() callback for aggregate or window UDF.");else c("Missing function-type properties.");if(Q===!1){if(C(A)||C(L))c("xValue and xInverse are not permitted for non-window UDFs.")}else if(C(A)){if(!C(L))c("xInverse must be provided if xValue is.");Q=!0}else if(C(L))c("xValue must be provided if xInverse is.");let ne=T.pApp;if(ne!==void 0&&ne!==null&&!p.isPtr(ne))c("Invalid value for pApp property. Must be a legal WASM pointer value.");let ye=T.xDestroy||0;if(ye&&!C(ye))c("xDestroy property must be a function.");let Te=0;if(N(T,"deterministic"))Te|=d.SQLITE_DETERMINISTIC;if(N(T,"directOnly"))Te|=d.SQLITE_DIRECTONLY;if(N(T,"innocuous"))Te|=d.SQLITE_INNOCUOUS;g=g.toLowerCase();let Ie=w||te,qe=N(T,"arity"),Ge=typeof qe==="number"?qe:Ie.length?Ie.length-1:0,ct;if(Q)ct=d.sqlite3_create_window_function(this.pointer,g,Ge,d.SQLITE_UTF8|Te,ne||0,te,se,A,L,ye);else ct=d.sqlite3_create_function_v2(this.pointer,g,Ge,d.SQLITE_UTF8|Te,ne||0,w,te,se,ye);return O.checkRc(this,ct),this},selectValue:function(z,g,w){return pe(this,z,g,0,w)},selectValues:function(z,g,w){let T=this.prepare(z),C=[];try{T.bind(g);while(T.step())C.push(T.get(0,w));T.reset()}finally{T.finalize()}return C},selectArray:function(z,g){return pe(this,z,g,[])},selectObject:function(z,g){return pe(this,z,g,{})},selectArrays:function(z,g){return S(this,z,g,"array")},selectObjects:function(z,g){return S(this,z,g,"object")},openStatementCount:function(){return this.pointer?Object.keys(M.get(this)).length:0},transaction:function(z){let g="BEGIN";if(arguments.length>1){if(/[^a-zA-Z]/.test(arguments[0]))c(d.SQLITE_MISUSE,"Invalid argument for BEGIN qualifier.");g+=" "+arguments[0],z=arguments[1]}ee(this).exec(g);try{let w=z(this);return this.exec("COMMIT"),w}catch(w){throw this.exec("ROLLBACK"),w}},savepoint:function(z){ee(this).exec("SAVEPOINT oo1");try{let g=z(this);return this.exec("RELEASE oo1"),g}catch(g){throw this.exec("ROLLBACK to SAVEPOINT oo1; RELEASE SAVEPOINT oo1"),g}},checkRc:function(z){return q(this,z)}},O.wrapHandle=function(z,g=!1){if(!z||!p.isPtr(z))throw new f.SQLite3Error(d.SQLITE_MISUSE,"Argument must be a WASM sqlite3 pointer");return new O({"sqlite3*":z,"sqlite3*:takeOwnership":!!g})};let P=function(z){if(!z.pointer)c("Stmt has been closed.");return z},K=function(z){let g=R[z===null||z===void 0?"null":typeof z];switch(g){case R.boolean:case R.null:case R.number:case R.string:return g;case R.bigint:return p.bigIntEnabled?g:void 0;default:return E.isBindableTypedArray(z)?R.blob:void 0}},oe=function(z){return K(z)||c("Unsupported bind() argument type:",typeof z)},W=function(z,g){let w=typeof g==="number"?g:d.sqlite3_bind_parameter_index(z.pointer,g);if(w===0||!E.isInt32(w))c("Invalid bind() parameter name: "+g);else if(w<1||w>z.parameterCount)c("Bind index",g,"is out of range.");return w},he=new Set,be=new Set,me=function(z,g){if(he.has(z))c("Operation is illegal when statement is locked:",g);return z},ve=function z(g,w,T,C){if(me(P(g),"bind()"),!z._)z._tooBigInt=(se)=>c("BigInt value is too big to store without precision loss:",se),z._={string:function(se,A,L,Q){let[ne,ye]=p.allocCString(L,!0);return(Q?d.sqlite3_bind_blob:d.sqlite3_bind_text)(se.pointer,A,ne,ye,d.SQLITE_WASM_DEALLOC)}};oe(C),w=W(g,w);let te=0;switch(C===null||C===void 0?R.null:T){case R.null:te=d.sqlite3_bind_null(g.pointer,w);break;case R.string:te=z._.string(g,w,C,!1);break;case R.number:{let se;if(E.isInt32(C))se=d.sqlite3_bind_int;else if(typeof C==="bigint")if(!E.bigIntFits64(C))z._tooBigInt(C);else if(p.bigIntEnabled)se=d.sqlite3_bind_int64;else if(E.bigIntFitsDouble(C))C=Number(C),se=d.sqlite3_bind_double;else z._tooBigInt(C);else if(C=Number(C),p.bigIntEnabled&&Number.isInteger(C))se=d.sqlite3_bind_int64;else se=d.sqlite3_bind_double;te=se(g.pointer,w,C);break}case R.boolean:te=d.sqlite3_bind_int(g.pointer,w,C?1:0);break;case R.blob:{if(typeof C==="string"){te=z._.string(g,w,C,!0);break}else if(C instanceof ArrayBuffer)C=new Uint8Array(C);else if(!E.isBindableTypedArray(C))c("Binding a value as a blob requires","that it be a string, Uint8Array, Int8Array, or ArrayBuffer.");let se=p.alloc(C.byteLength||1);p.heap8().set(C.byteLength?C:[0],Number(se)),te=d.sqlite3_bind_blob(g.pointer,w,se,C.byteLength,d.SQLITE_WASM_DEALLOC);break}default:f.config.warn("Unsupported bind() argument type:",C),c("Unsupported bind() argument type: "+typeof C)}if(te)O.checkRc(g.db.pointer,te);return g};X.prototype={finalize:function(){let z=this.pointer;if(z){me(this,"finalize()");let g=V.delete(this)?0:d.sqlite3_finalize(z);return delete M.get(this.db)[z],I.delete(this),he.delete(this),be.delete(this),delete this.parameterCount,delete this.db,g}},clearBindings:function(){return me(P(this),"clearBindings()"),d.sqlite3_clear_bindings(this.pointer),be.delete(this),this},reset:function(z){if(me(this,"reset()"),z)this.clearBindings();let g=d.sqlite3_reset(P(this).pointer);return be.delete(this),q(this.db,g),this},bind:function(){P(this);let z,g;switch(arguments.length){case 1:z=1,g=arguments[0];break;case 2:z=arguments[0],g=arguments[1];break;default:c("Invalid bind() arguments.")}if(g===void 0)return this;else if(!this.parameterCount)c("This statement has no bindable parameters.");if(be.delete(this),g===null)return ve(this,z,R.null,g);else if(Array.isArray(g)){if(arguments.length!==1)c("When binding an array, an index argument is not permitted.");return g.forEach((w,T)=>ve(this,T+1,oe(w),w)),this}else if(g instanceof ArrayBuffer)g=new Uint8Array(g);if(typeof g==="object"&&!E.isBindableTypedArray(g)){if(arguments.length!==1)c("When binding an object, an index argument is not permitted.");return Object.keys(g).forEach((w)=>ve(this,w,oe(g[w]),g[w])),this}else return ve(this,z,oe(g),g);c("Should not reach this point.")},bindAsBlob:function(z,g){if(P(this),arguments.length===1)g=z,z=1;let w=oe(g);if(R.string!==w&&R.blob!==w&&R.null!==w)c("Invalid value type for bindAsBlob()");return ve(this,z,R.blob,g)},step:function(){me(this,"step()");let z=d.sqlite3_step(P(this).pointer);switch(z){case d.SQLITE_DONE:return be.delete(this),!1;case d.SQLITE_ROW:return be.add(this),!0;default:be.delete(this),f.config.warn("sqlite3_step() rc=",z,d.sqlite3_js_rc_str(z),"SQL =",d.sqlite3_sql(this.pointer)),O.checkRc(this.db.pointer,z)}},stepReset:function(){return this.step(),this.reset()},stepFinalize:function(){try{let z=this.step();return this.reset(),z}finally{try{this.finalize()}catch(z){}}},get:function(z,g){if(!be.has(P(this)))c("Stmt.step() has not (recently) returned true.");if(Array.isArray(z)){let w=0,T=this.columnCount;while(w<T)z[w]=this.get(w++);return z}else if(z&&typeof z==="object"){let w=0,T=this.columnCount;while(w<T)z[d.sqlite3_column_name(this.pointer,w)]=this.get(w++);return z}switch(U(this,z),g===void 0?d.sqlite3_column_type(this.pointer,z):g){case d.SQLITE_NULL:return null;case d.SQLITE_INTEGER:if(p.bigIntEnabled){let w=d.sqlite3_column_int64(this.pointer,z);if(w>=Number.MIN_SAFE_INTEGER&&w<=Number.MAX_SAFE_INTEGER)return Number(w).valueOf();return w}else{let w=d.sqlite3_column_double(this.pointer,z);if(w>Number.MAX_SAFE_INTEGER||w<Number.MIN_SAFE_INTEGER)c("Integer is out of range for JS integer range: "+w);return E.isInt32(w)?w|0:w}case d.SQLITE_FLOAT:return d.sqlite3_column_double(this.pointer,z);case d.SQLITE_TEXT:return d.sqlite3_column_text(this.pointer,z);case d.SQLITE_BLOB:{let w=d.sqlite3_column_bytes(this.pointer,z),T=d.sqlite3_column_blob(this.pointer,z),C=new Uint8Array(w);if(w){if(C.set(p.heap8u().slice(Number(T),Number(T)+w),0),this.db._blobXfer instanceof Array)this.db._blobXfer.push(C.buffer)}return C}default:c("Don't know how to translate","type of result column #"+z+".")}c("Not reached.")},getInt:function(z){return this.get(z,d.SQLITE_INTEGER)},getFloat:function(z){return this.get(z,d.SQLITE_FLOAT)},getString:function(z){return this.get(z,d.SQLITE_TEXT)},getBlob:function(z){return this.get(z,d.SQLITE_BLOB)},getJSON:function(z){let g=this.get(z,d.SQLITE_STRING);return g===null?g:JSON.parse(g)},getColumnName:function(z){return d.sqlite3_column_name(U(P(this),z).pointer,z)},getColumnNames:function(z=[]){U(P(this),0);let g=this.columnCount;for(let w=0;w<g;++w)z.push(d.sqlite3_column_name(this.pointer,w));return z},getParamIndex:function(z){return P(this).parameterCount?d.sqlite3_bind_parameter_index(this.pointer,z):void 0},getParamName:function(z){return P(this).parameterCount?d.sqlite3_bind_parameter_name(this.pointer,z):void 0},isBusy:function(){return d.sqlite3_stmt_busy(P(this))!==0},isReadOnly:function(){return d.sqlite3_stmt_readonly(P(this))!==0}};{let z={enumerable:!0,get:function(){return I.get(this)},set:()=>c("The pointer property is read-only.")};Object.defineProperty(X.prototype,"pointer",z),Object.defineProperty(O.prototype,"pointer",z)}Object.defineProperty(X.prototype,"columnCount",{enumerable:!1,get:function(){return d.sqlite3_column_count(this.pointer)},set:()=>c("The columnCount property is read-only.")}),Object.defineProperty(X.prototype,"parameterCount",{enumerable:!1,get:function(){return d.sqlite3_bind_parameter_count(this.pointer)},set:()=>c("The parameterCount property is read-only.")}),X.wrapHandle=function(z,g,w=!1){if(!(z instanceof O)||!z.pointer)throw new f.SQLite3Error(f.SQLITE_MISUSE,"First argument must be an opened sqlite3.oo1.DB instance");if(!g||!p.isPtr(g))throw new f.SQLite3Error(f.SQLITE_MISUSE,"Second argument must be a WASM sqlite3_stmt pointer");return new X(z,g,R,!!w)},f.oo1={DB:O,Stmt:X}}),globalThis.sqlite3ApiBootstrap.initializers.push(function(f){let c=f.util;f.initWorker1API=function(){let d=(...H)=>{throw Error(H.join(" "))};if(!(globalThis.WorkerGlobalScope instanceof Function))d("initWorker1API() must be run from a Worker thread.");let p=this.sqlite3||d("Missing this.sqlite3 object."),E=p.oo1.DB,b=function(H){let G=I.idMap.get(H);if(G)return G;return G="db#"+ ++I.idSeq+":"+Math.floor(Math.random()*1e8)+":"+Math.floor(Math.random()*1e8),I.idMap.set(H,G),G},I={dbList:[],idSeq:0,idMap:new WeakMap,xfer:[],open:function(H){let G=new E(H);if(this.dbs[b(G)]=G,this.dbList.indexOf(G)<0)this.dbList.push(G);return G},close:function(H,G){if(H){delete this.dbs[b(H)];let le=H.filename,O=c.sqlite3__wasm_db_vfs(H.pointer,0);H.close();let R=this.dbList.indexOf(H);if(R>=0)this.dbList.splice(R,1);if(G&&le&&O)c.sqlite3__wasm_vfs_unlink(O,le)}},post:function(H,G){if(G&&G.length)globalThis.postMessage(H,Array.from(G)),G.length=0;else globalThis.postMessage(H)},dbs:Object.create(null),getDb:function(H,G=!0){return this.dbs[H]||(G?d("Unknown (or closed) DB ID:",H):void 0)}},V=function(H=I.dbList[0]){return H&&H.pointer?H:d("DB is not opened.")},M=function(H,G=!0){let le=I.getDb(H.dbId,!1)||I.dbList[0];return G?V(le):le},N=function(){return I.dbList[0]&&b(I.dbList[0])},q={open:function(H){let G=Object.create(null),le=H.args||Object.create(null);if(le.simulateError)d("Throwing because of simulateError flag.");let O=Object.create(null);G.vfs=le.vfs,G.filename=le.filename||"";let R=I.open(G);return O.filename=R.filename,O.persistent=!!p.capi.sqlite3_js_db_uses_vfs(R.pointer,"opfs"),O.dbId=b(R),O.vfs=R.dbVfsName(),O},close:function(H){let G=M(H,!1),le={filename:G&&G.filename};if(G){let O=H.args&&typeof H.args==="object"?!!H.args.unlink:!1;I.close(G,O)}return le},exec:function(H){let G=typeof H.args==="string"?{sql:H.args}:H.args||Object.create(null);if(G.rowMode==="stmt")d("Invalid rowMode for 'exec': stmt mode","does not work in the Worker API.");else if(!G.sql)d("'exec' requires input SQL.");let le=M(H);if(G.callback||Array.isArray(G.resultRows))le._blobXfer=I.xfer;let O=G.callback,R=0,X=!!G.columnNames;if(typeof O==="string"){if(!X)G.columnNames=[];G.callback=function(ee,U){I.post({type:O,columnNames:G.columnNames,rowNumber:++R,row:ee},I.xfer)}}try{let ee=G.countChanges?le.changes(!0,G.countChanges===64):void 0;if(le.exec(G),ee!==void 0)G.changeCount=le.changes(!0,G.countChanges===64)-ee;let U=G.lastInsertRowId?p.capi.sqlite3_last_insert_rowid(le):void 0;if(U!==void 0)G.lastInsertRowId=U;if(G.callback instanceof Function)G.callback=O,I.post({type:O,columnNames:G.columnNames,rowNumber:null,row:void 0})}finally{if(delete le._blobXfer,G.callback)G.callback=O}return G},"config-get":function(){let H=Object.create(null),G=p.config;return["bigIntEnabled"].forEach(function(le){if(Object.getOwnPropertyDescriptor(G,le))H[le]=G[le]}),H.version=p.version,H.vfsList=p.capi.sqlite3_js_vfs_list(),H},export:function(H){let G=M(H),le={byteArray:p.capi.sqlite3_js_db_export(G.pointer),filename:G.filename,mimetype:"application/x-sqlite3"};return I.xfer.push(le.byteArray.buffer),le},toss:function(H){d("Testing worker exception")}};globalThis.onmessage=async function(H){H=H.data;let G,le=H.dbId,O=H.type,R=performance.now();try{if(q.hasOwnProperty(O)&&q[O]instanceof Function)G=await q[O](H);else d("Unknown db worker message type:",H.type)}catch(X){if(O="error",G={operation:H.type,message:X.message,errorClass:X.name,input:H},X.stack)G.stack=typeof X.stack==="string"?X.stack.split(/\n\s*/):X.stack}if(!le)le=G.dbId||N();I.post({type:O,dbId:le,messageId:H.messageId,workerReceivedTime:R,workerRespondTime:performance.now(),departureTime:H.departureTime,result:G},I.xfer)},globalThis.postMessage({type:"sqlite3-api",result:"worker1-ready"})}.bind({sqlite3:f})}),globalThis.sqlite3ApiBootstrap.initializers.push(function(f){let{wasm:c,capi:d}=f,p=f.util.toss3,E=Object.create(null);f.vfs=E,d.sqlite3_vfs.prototype.registerVfs=function(b=!1){if(!(this instanceof f.capi.sqlite3_vfs))p("Expecting a sqlite3_vfs-type argument.");let I=d.sqlite3_vfs_register(this,b?1:0);if(I)p("sqlite3_vfs_register(",this,") failed with rc",I);if(this.pointer!==d.sqlite3_vfs_find(this.$zName))p("BUG: sqlite3_vfs_find(vfs.$zName) failed for just-installed VFS",this);return this},E.installVfs=function(b){let I=0,V=["io","vfs"];for(let M of V){let N=b[M];if(N){if(++I,N.struct.installMethods(N.methods,!!N.applyArgcCheck),M==="vfs"){if(!N.struct.$zName&&typeof N.name==="string")N.struct.addOnDispose(N.struct.$zName=c.allocCString(N.name));N.struct.registerVfs(!!N.asDefault)}}}if(!I)p("Misuse: installVfs() options object requires at least","one of:",V);return this}}),globalThis.sqlite3ApiBootstrap.initializers.push(function(f){if(!f.wasm.exports.sqlite3_declare_vtab)return;let{wasm:c,capi:d}=f,p=f.util.toss3,E=Object.create(null);f.vtab=E;let b=d.sqlite3_index_info;b.prototype.nthConstraint=function(M,N=!1){if(M<0||M>=this.$nConstraint)return!1;let q=c.ptr.add(this.$aConstraint,b.sqlite3_index_constraint.structInfo.sizeof*M);return N?q:new b.sqlite3_index_constraint(q)},b.prototype.nthConstraintUsage=function(M,N=!1){if(M<0||M>=this.$nConstraint)return!1;let q=c.ptr.add(this.$aConstraintUsage,b.sqlite3_index_constraint_usage.structInfo.sizeof*M);return N?q:new b.sqlite3_index_constraint_usage(q)},b.prototype.nthOrderBy=function(M,N=!1){if(M<0||M>=this.$nOrderBy)return!1;let q=c.ptr.add(this.$aOrderBy,b.sqlite3_index_orderby.structInfo.sizeof*M);return N?q:new b.sqlite3_index_orderby(q)};let I=function(M,N){return function(q,H=!1){if(arguments.length===0)q=new N;if(q instanceof N)return this.set(q.pointer,q),q;else if(!c.isPtr(q))f.SQLite3Error.toss("Invalid argument to",M+"()");let G=this.get(q);if(H)this.delete(q);return G}.bind(new Map)},V=function(M,N){let q=I(M,N);return Object.assign(Object.create(null),{StructType:N,create:(H)=>{let G=q();return c.pokePtr(H,G.pointer),G},get:(H)=>q(H),unget:(H)=>q(H,!0),dispose:(H)=>q(H,!0)?.dispose?.()})};E.xVtab=V("xVtab",d.sqlite3_vtab),E.xCursor=V("xCursor",d.sqlite3_vtab_cursor),E.xIndexInfo=(M)=>new d.sqlite3_index_info(M),E.xError=function M(N,q,H){if(M.errorReporter instanceof Function)try{M.errorReporter("sqlite3_module::"+N+"(): "+q.message)}catch(le){}let G;if(q instanceof f.WasmAllocError)G=d.SQLITE_NOMEM;else if(arguments.length>2)G=H;else if(q instanceof f.SQLite3Error)G=q.resultCode;return G||d.SQLITE_ERROR},E.xError.errorReporter=f.config.error.bind(f.config),E.xRowid=(M,N)=>c.poke(M,N,"i64"),E.setupModule=function(M){let N=!1,q=this instanceof d.sqlite3_module?this:M.struct||(N=new d.sqlite3_module);try{let H=M.methods||p("Missing 'methods' object.");for(let G of Object.entries({xConnect:"xCreate",xDisconnect:"xDestroy"})){let le=G[0],O=G[1];if(H[le]===!0)H[le]=H[O];else if(H[O]===!0)H[O]=H[le]}if(M.catchExceptions){let G=function(R,X){if(["xConnect","xCreate"].indexOf(R)>=0)return function(ee,U,J,pe,S,P){try{return X(...arguments)||0}catch(K){if(!(K instanceof f.WasmAllocError))c.dealloc(c.peekPtr(P)),c.pokePtr(P,c.allocCString(K.message));return E.xError(R,K)}};else return function(...ee){try{return X(...ee)||0}catch(U){return E.xError(R,U)}}},le=["xCreate","xConnect","xBestIndex","xDisconnect","xDestroy","xOpen","xClose","xFilter","xNext","xEof","xColumn","xRowid","xUpdate","xBegin","xSync","xCommit","xRollback","xFindFunction","xRename","xSavepoint","xRelease","xRollbackTo","xShadowName"],O=Object.create(null);for(let R of le){let X=H[R];if(!(X instanceof Function))continue;else if(R==="xConnect"&&H.xCreate===X)O[R]=H.xCreate;else if(R==="xCreate"&&H.xConnect===X)O[R]=H.xConnect;else O[R]=G(R,X)}q.installMethods(O,!1)}else q.installMethods(H,!!M.applyArgcCheck);if(q.$iVersion===0){let G;if(typeof M.iVersion==="number")G=M.iVersion;else if(q.$xIntegrity)G=4;else if(q.$xShadowName)G=3;else if(q.$xSavePoint||q.$xRelease||q.$xRollbackTo)G=2;else G=1;q.$iVersion=G}}catch(H){if(N)N.dispose();throw H}return q},d.sqlite3_module.prototype.setupModule=function(M){return E.setupModule.call(this,M)}}),globalThis.sqlite3ApiBootstrap.initializers.push(function(f){if(f.config.disable?.vfs?.kvvfs)return;let c=f.capi,{sqlite3_kvvfs_methods:d,KVVfsFile:p}=c,E=f.capi.sqlite3_vfs_find("kvvfs");if(delete c.sqlite3_kvvfs_methods,delete c.KVVfsFile,!E)return;let{util:b,wasm:I}=f,V=b.toss3,M=new d(I.exports.sqlite3__wasm_kvvfs_methods());b.assert(32<=M.$nKeySize,"unexpected kvvfsMethods.$nKeySize: "+M.$nKeySize);let N=Object.assign(Object.create(null),{rxJournalSuffix:/-journal$/,zKeyJrnl:I.allocCString("jrnl"),zKeySz:I.allocCString("sz"),keySize:M.$nKeySize,buffer:Object.assign(Object.create(null),{n:M.$nBufferSize,pool:Object.create(null)})});N.memBuffer=(B=0)=>N.buffer.pool[B]??=I.alloc(N.buffer.n),N.memBufferFree=(B)=>{let re=N.buffer.pool[B];if(re)I.dealloc(re),delete N.buffer.pool[B]};let q=()=>{},H=f.__isUnderTest?(...B)=>f.config.debug?.("kvvfs:",...B):q,G=(...B)=>f.config.warn?.("kvvfs:",...B),le=(...B)=>f.config.error?.("kvvfs:",...B);class O{#e=Object.create(null);#o=null;#i=0;constructor(){this.clear()}#t(){return this.#o??=Object.keys(this.#e)}key(B){if(B<0||B>=this.#i)return null;return this.#t()[B]}getItem(B){return this.#e[B]??null}setItem(B,re){if(!(B in this.#e))++this.#i,this.#o=null;this.#e[B]=""+re}removeItem(B){if(B in this.#e)delete this.#e[B],--this.#i,this.#o=null}clear(){this.#e=Object.create(null),this.#o=null,this.#i=0}get length(){return this.#i}}let R=(B)=>B==="local"||B==="session",X=(B)=>R(B)?"kvvfs-"+B+"-":"",ee=function(B,re=!1){if(R(B))return;let ae=new Blob([B]).size;if(!ae)V(c.SQLITE_MISUSE,"Empty name is not permitted.");let ue=N.keySize-1;if(N.rxJournalSuffix.test(B)){if(!re)V(c.SQLITE_MISUSE,"Storage names may not have a '-journal' suffix.")}else if(["-wal","-shm"].filter((Re)=>B.endsWith(Re)).length)V(c.SQLITE_MISUSE,"Storage names may not have a -wal or -shm suffix.");else ue-=8;if(ae>ue)V(c.SQLITE_RANGE,"Storage name is too long. Limit =",ue);let Se;for(Se=0;Se<ae;++Se){let Re=B.codePointAt(Se);if(Re<32)V(c.SQLITE_RANGE,"Illegal character ("+Re+"d) in storage name:",B)}},U=(B,re=void 0)=>Object.assign(Object.create(null),{jzClass:B,refc:1,deleteAtRefc0:!1,storage:re||new O,keyPrefix:X(B),files:[],listeners:void 0}),J=f.kvvfs=Object.create(null);if(f.__isUnderTest)J.log=Object.assign(Object.create(null),{xOpen:!1,xClose:!1,xWrite:!1,xRead:!1,xSync:!1,xAccess:!1,xFileControl:!1,xRcrdRead:!1,xRcrdWrite:!1,xRcrdDelete:!1});let pe=function(B){let re=N.rxJournalSuffix.test(B.jzClass)?B.jzClass.replace(N.rxJournalSuffix,""):B.jzClass+"-journal";if(J?.log?.xClose&&H("cleaning up storage handles [",B.jzClass,re,"]",B),delete N.storagePool[B.jzClass],delete N.storagePool[re],!f.__isUnderTest)delete B.storage,delete B.refc},S=(B)=>N.storagePool[B.jzClass]=N.storagePool[B.jzClass+"-journal"]=B,P=".";if(N.storagePool=Object.assign(Object.create(null),{[P]:U(P)}),globalThis.Storage){if(globalThis.localStorage instanceof globalThis.Storage)N.storagePool.local=U("local",globalThis.localStorage);if(globalThis.sessionStorage instanceof globalThis.Storage)N.storagePool.session=U("session",globalThis.sessionStorage)}N.builtinStorageNames=Object.keys(N.storagePool);let K=(B)=>N.builtinStorageNames.indexOf(B)>-1;for(let B of Object.keys(N.storagePool)){let re=N.storagePool[B];N.storagePool[B+"-journal"]=re}N.setError=(B=void 0,re=c.SQLITE_ERROR)=>{if(B)return N.lastError=B,B.resultCode|0||re;return delete N.lastError,0},N.popError=()=>{let B=N.lastError;return delete N.lastError,B};let oe=(B)=>{G("kvvfs.listener handler threw:",B)},W=I.exports.sqlite3__wasm_kvvfs_decode,he=I.exports.sqlite3__wasm_kvvfs_encode,be=async function(B,re,...ae){try{if(re.keyPrefix&&ae[0])ae[0]=ae[0].replace(re.keyPrefix,"");let ue,Se,Re,Oe;for(let ke of re.listeners){let Ne=Object.create(null);Ne.storageName=re.jzClass,Ne.type=B,ke.decodePages;let je=ke.events[B];if(je){if(!ke.includeJournal&&ae[0]==="jrnl")continue;if(B==="write"&&ke.decodePages&&+ae[0]>0){if(Ne.data=[ae[0]],Oe?.[ae[0]]){Ne.data[1]=Oe[ae[0]];continue}ue??=new TextEncoder("utf-8"),Se??=N.memBuffer(10),Re??=N.memBuffer(11);let Qe=ue.encode(ae[1]),Me=I.heap8u();Me.set(Qe,Number(Se)),Me[I.ptr.addn(Se,Qe.length)]=0;let yt=W(Se,Re,N.buffer.n);if(yt>0)Oe??=Object.create(null),Oe[ae[0]]=Ne.data[1]=Me.slice(Number(Re),I.ptr.addn(Re,yt));else continue}else Ne.data=ae.length?ae.length===1?ae[0]:ae:void 0;try{je(Ne)?.catch?.(oe)}catch(Qe){G("notifyListeners [",re.jzClass,"]",B,Qe)}}}}catch(ue){oe(ue)}},me=(B)=>typeof B==="string"?N.storagePool[B]:N.storagePool[I.cstrToJs(B)],ve=I.exports.sqlite3__wasm_kvvfsMakeKey,z=(B,re,ae)=>re&&B.keyPrefix?ve(re,ae):ae,g=(B,re,ae)=>I.cstrToJs(z(B,re,ae)),w=(B)=>+B.storage.getItem(B.keyPrefix+"sz"),T=new Map,C={vfs:Object.create(null),ioDb:Object.create(null),ioJrnl:Object.create(null)},te=new c.sqlite3_vfs(M.$pVfs),se=new c.sqlite3_io_methods(M.$pIoDb),A=new c.sqlite3_io_methods(M.$pIoJrnl),L=Object.create(null),Q=Object.assign(Object.create(null),{pFileHandles:T,cache:N,storageForZClass:me,KVVfsStorage:O,disablePageSizeChange:!0});if(J.log)J.internal=Q;let ne={recordHandler:{xRcrdRead:(B,re,ae,ue)=>{try{let Se=I.cstrToJs(B),Re=me(Se);if(!Re)return-1;let Oe=g(Re,B,re);J?.log?.xRcrdRead&&G("xRcrdRead",Se,Oe,ue,Re);let ke=Re.storage.getItem(Oe);if(ke===null)return-1;let Ne=ke.length;if(ue<=0)return Ne;else if(ue===1)return I.poke(ae,0),Ne;if(ue+1<Ne)V(c.SQLITE_RANGE,"xRcrdRead()",Se,Oe,"input buffer is too small: need",Ne,"but have",ue);let je=N.memBuffer(0),Qe=I.heap8(),Me;for(Me=0;Me<Ne;++Me)Qe[I.ptr.add(je,Me)]=ke.codePointAt(Me)&255;return Qe.copyWithin(Number(ae),Number(je),I.ptr.addn(je,Me)),Qe[I.ptr.add(ae,Ne)]=0,ue}catch(Se){return le("kvrecordRead()",Se),N.setError(Se),-2}},xRcrdWrite:(B,re,ae)=>{try{let ue=me(B),Se=g(ue,B,re),Re=I.cstrToJs(ae);return J?.log?.xRcrdWrite&&G("xRcrdWrite",Se,ue),ue.storage.setItem(Se,Re),ue.listeners&&be("write",ue,Se,Re),0}catch(ue){return le("kvrecordWrite()",ue),N.setError(ue,c.SQLITE_IOERR)}},xRcrdDelete:(B,re)=>{try{let ae=me(B),ue=g(ae,B,re);return J?.log?.xRcrdDelete&&G("xRcrdDelete",ue,ae),ae.storage.removeItem(ue),ae.listeners&&be("delete",ae,ue),0}catch(ae){return le("kvrecordDelete()",ae),N.setError(ae,c.SQLITE_IOERR)}}},vfs:{xOpen:function(B,re,ae,ue,Se){N.popError();let Re;try{if(!re)Re=I.allocCString(""+ae+"."+(Math.random()*1e5|0)),re=Re;let Oe=I.cstrToJs(re);if(J?.log?.xOpen&&H("xOpen",Oe,"flags =",ue),ee(Oe,!0),ue&(c.SQLITE_OPEN_MAIN_DB|c.SQLITE_OPEN_TEMP_DB|c.SQLITE_OPEN_TRANSIENT_DB)&&N.rxJournalSuffix.test(Oe))V(c.SQLITE_ERROR,"DB files may not have a '-journal' suffix.");let ke=me(Oe);if(!ke&&!(ue&c.SQLITE_OPEN_CREATE))V(c.SQLITE_ERROR,"Storage not found:",Oe);let Ne=C.vfs.xOpen(B,re,ae,ue,Se);if(Ne)return Ne;let je=!!(c.SQLITE_OPEN_DELETEONCLOSE&ue);if(I.isPtr(arguments[1])){if(c.sqlite3_uri_boolean(re,"delete-on-close",0))je=!0}let Qe=new p(ae);if(b.assert(Qe.$zClass,"Missing f.$zClass"),Qe.addOnDispose(Re),Re=void 0,ke)++ke.refc,ke.files.push(Qe),I.poke32(Se,ue);else{I.poke32(Se,ue|c.SQLITE_OPEN_CREATE),b.assert(!Qe.$isJournal,"Opening a journal before its db? "+Oe);let Me=Oe.replace(N.rxJournalSuffix,"");ke=U(Me),S(ke),ke.files.push(Qe),ke.deleteAtRefc0=je,J?.log?.xOpen&&H("xOpen installed storage handle [",Me,Me+"-journal","]",ke)}return T.set(ae,{store:ke,file:Qe,jzClass:Oe}),ke.listeners&&be("open",ke,ke.files.length),0}catch(Oe){return G("xOpen:",Oe),N.setError(Oe)}finally{Re&&I.dealloc(Re)}},xDelete:function(B,re,ae){N.popError();try{let ue=I.cstrToJs(re);if(N.rxJournalSuffix.test(ue))L.xRcrdDelete(re,N.zKeyJrnl);return 0}catch(ue){return G("xDelete",ue),N.setError(ue)}},xAccess:function(B,re,ae,ue){N.popError();try{let Se=me(re),Re=Se?.jzClass||I.cstrToJs(re);if(J?.log?.xAccess)H("xAccess",Re,"flags =",ae,"*pResOut =",I.peek32(ue),"store =",Se);if(!Se)try{ee(Re)}catch(Oe){return I.poke32(ue,0),0}if(Se){let Oe=Se.keyPrefix+(N.rxJournalSuffix.test(Re)?"jrnl":"1"),ke=Se.storage.getItem(Oe)?0:1;I.poke32(ue,ke)}else I.poke32(ue,0);return 0}catch(Se){return le("xAccess",Se),N.setError(Se)}},xRandomness:function(B,re,ae){let ue=I.heap8u(),Se=0,Re=Number(ae);for(;Se<re;++Se)ue[Re+Se]=Math.random()*255000&255;return re},xGetLastError:function(B,re,ae){let ue=N.popError();if(H("xGetLastError",ue),ue){let Se=I.scopedAllocPush();try{let[Re,Oe]=I.scopedAllocCString(ue.message,!0);if(I.cstrncpy(ae,Re,re),Oe>re)I.poke8(I.ptr.add(ae,re,-1),0);return H("set xGetLastError",ue.message),ue.resultCode|0||c.SQLITE_IOERR}catch(Re){return c.SQLITE_NOMEM}finally{I.scopedAllocPop(Se)}}return 0}},ioDb:{xClose:function(B){N.popError();try{let re=T.get(B);if(J?.log?.xClose&&H("xClose",B,re),re){T.delete(B);let ae=re.store;if(ae.files=ae.files.filter((ue)=>ue!==re.file),--ae.refc<=0&&ae.deleteAtRefc0)pe(ae);C.ioDb.xClose(B),re.file.dispose(),ae.listeners&&be("close",ae,ae.files.length)}return 0}catch(re){return le("xClose",re),N.setError(re)}},xFileControl:function(B,re,ae){N.popError();try{let ue=T.get(B);if(b.assert(ue,"Missing KVVfsFile handle"),J?.log?.xFileControl&&H("xFileControl",ue,"op =",re),re===c.SQLITE_FCNTL_PRAGMA&&Q.disablePageSizeChange){let Re=I.peekPtr(I.ptr.add(ae,I.ptr.size));if(I.cstrToJs(Re)==="page_size"){J?.log?.xFileControl&&H("xFileControl pragma",I.cstrToJs(Re));let Oe=I.peekPtr(I.ptr.add(ae,2*I.ptr.size));if(Oe)return J?.log?.xFileControl&&G("xFileControl pragma",ue,"NOT setting page size to",I.cstrToJs(Oe)),ue.file.$szPage=-1,0;else if(ue.file.$szPage>0)return J?.log?.xFileControl&&G("xFileControl",ue,"getting page size",ue.file.$szPage),I.pokePtr(ae,I.allocCString(""+ue.file.$szPage)),0}}let Se=C.ioDb.xFileControl(B,re,ae);if(Se==0&&c.SQLITE_FCNTL_SYNC===re)ue.store.listeners&&be("sync",ue.store,!1);return Se}catch(ue){return le("xFileControl",ue),N.setError(ue)}},xSync:function(B,re){N.popError();try{let ae=T.get(B);J?.log?.xSync&&H("xSync",ae),b.assert(ae,"Missing KVVfsFile handle");let ue=C.ioDb.xSync(B,re);if(ue==0&&ae.store.listeners)be("sync",ae.store,!0);return ue}catch(ae){return le("xSync",ae),N.setError(ae)}}},ioJrnl:{xClose:!0}};try{b.assert(N.buffer.n>132096,"Heap buffer is not large enough");for(let B of Object.entries(ne.recordHandler)){let re=B[0],ae=B[1];L[re]=ae,M[M.memberKey(re)]=I.installFunction(M.memberSignature(re),ae)}for(let B of Object.entries(ne.vfs)){let re=B[0],ae=B[1],ue=te.memberKey(re),Se=te.structInfo.members[re]||b.toss("Missing pVfs.structInfo[",re,"]");C.vfs[re]=I.functionEntry(te[ue]),te[ue]=I.installFunction(Se.signature,ae)}for(let B of Object.entries(ne.ioDb)){let re=B[0],ae=B[1],ue=se.memberKey(re);C.ioDb[re]=I.functionEntry(se[ue])||b.toss("Missing native pIoDb[",ue,"]"),se[ue]=I.installFunction(se.memberSignature(re),ae)}for(let B of Object.entries(ne.ioJrnl)){let re=B[0],ae=B[1],ue=A.memberKey(re);if(C.ioJrnl[re]=I.functionEntry(A[ue])||b.toss("Missing native pIoJrnl[",ue,"]"),ae===!0)A[ue]=se[ue]||b.toss("Missing copied pIoDb[",ue,"]");else A[ue]=I.installFunction(A.memberSignature(re),ae)}}finally{M.dispose(),te.dispose(),se.dispose(),A.dispose()}let ye=function B(re){if(re==="")return B("local")+B("session");let ae=me(re);if(!ae)return 0;if(ae.files.length)if(globalThis.localStorage===ae.storage||globalThis.sessionStorage===ae.storage);else V(c.SQLITE_ACCESS,"Cannot clear in-use database storage.");let ue=ae.storage,Se=[],Re,Oe=ue.length;for(Re=0;Re<Oe;++Re){let ke=ue.key(Re);if(!ae.keyPrefix||ke.startsWith(ae.keyPrefix))Se.push(ke)}return Se.forEach((ke)=>ue.removeItem(ke)),Se.length},Te=function B(re){if(re==="")return B("local")+B("session");let ae=me(re);if(!ae)return 0;let ue=ae.storage,Se,Re=0;for(Se=0;Se<ue.length;++Se){let Oe=ue.key(Se);if(!ae.keyPrefix||Oe.startsWith(ae.keyPrefix))Re+=Oe.length,Re+=ue.getItem(Oe).length}return Re*2},Ie=function(...re){let ae;if(re.length===1&&typeof re[0]==="object")ae=re[0];else if(re.length)ae=Object.assign(Object.create(null),{name:re[0]});let ue=ae?me(ae.name):null;if(!ue)V(c.SQLITE_NOTFOUND,"There is no kvvfs storage named",ae?.name);let Se=ue.storage,Re=Object.assign(Object.create(null),{name:ue.jzClass,timestamp:Date.now(),pages:[]}),Oe=Object.create(null),ke=ue.keyPrefix,Ne=ke?/^kvvfs-[^-]+-(\w+)/:void 0,je=0,Qe=Se.length;for(;je<Qe;++je){let Me=Se.key(je);if(!ke||Me.startsWith(ke)){let yt=(ke?Ne.exec(Me):void 0)?.[1]??Me;switch(yt){case"jrnl":if(ae.includeJournal)Re.journal=Se.getItem(Me);break;case"sz":Re.size=+Se.getItem(Me);break;default:if(yt=+yt,!b.isInt32(yt)||yt<=0)V(c.SQLITE_RANGE,"Malformed kvvfs key: "+Me);if(ae.decodePages){let Ft=Se.getItem(Me),rn=Ft.length,Zt=N.memBuffer(0),Pr=N.memBuffer(1),Nn=I.heap8u(),At=0;for(;At<rn;++At)Nn[I.ptr.add(Zt,At)]=Ft.codePointAt(At)&255;Nn[I.ptr.add(Zt,At)]=0;let mo=W(Zt,Pr,N.buffer.n);Oe[yt]=Nn.slice(Number(Pr),I.ptr.addn(Pr,mo))}else Oe[yt]=Se.getItem(Me);break}}}if(ae.decodePages)N.memBufferFree(1);return Object.keys(Oe).map((Me)=>+Me).sort().forEach((Me)=>Re.pages.push(Oe[Me])),Re},qe=function(B,re=!1){if(!B?.timestamp||!B.name||B.size===void 0||!Array.isArray(B.pages))V(c.SQLITE_MISUSE,"Malformed export object.");else if(!B.size||B.size!==(B.size|0)||B.size>=2147483647)V(c.SQLITE_RANGE,"Invalid db size: "+B.size);ee(B.name);let ae=me(B.name),ue=!ae;if(ae){if(!re)V(c.SQLITE_ACCESS,"Storage '"+B.name+"' already exists and","overwrite was not specified.");else if(!ae.files||!ae.jzClass)V(c.SQLITE_ERROR,"Internal storage object",B.name,"seems to be malformed.");else if(ae.files.length)V(c.SQLITE_IOERR_ACCESS,"Cannot import db storage while it is in use.");ye(B.name)}else ae=U(B.name);let Se=X(B.name),Re;try{let Oe=ae.storage;if(Oe.setItem(Se+"sz",B.size),B.journal)Oe.setItem(Se+"jrnl",B.journal);if(B.pages[0]instanceof Uint8Array)B.pages.forEach((ke,Ne)=>{let je=ke.length;Re??=N.memBuffer(1);let Qe=N.memBuffer(0),Me=I.heap8u();Me.set(ke,Number(Qe)),Me[I.ptr.addn(Qe,je)]=0;let yt=he(Qe,je,Re);b.assert(yt<N.buffer.n,"Impossibly long output - possibly smashed the heap"),b.assert(I.peek8(I.ptr.add(Re,yt))===0,"Expecting NUL-terminated encoded output");let Ft=I.cstrToJs(Re);Oe.setItem(Se+(Ne+1),Ft)});else if(B.pages[0])B.pages.forEach((ke,Ne)=>Oe.setItem(Se+(Ne+1),ke));if(ue)S(ae)}catch{if(!ue)try{ye(B.name)}catch(Oe){}}finally{if(Re)N.memBufferFree(1)}return this},Ge=function(B){let re=me(B);if(re){++re.refc;return}ee(B),S(U(B))},ct=function(B){let re=me(B);if(!re||R(re.jzClass)||K(re.jzClass)||N.rxJournalSuffix.test(B))return!1;if(re.refc>re.files.length||re.files.length===0){if(--re.refc<=0)pe(re);return!0}return!1},zt=function(B){if(!B||typeof B!=="object")V(c.SQLITE_MISUSE,"Expecting a listener object.");let re=me(B.storage);if(!re)if(B.storage&&B.reserve)Ge(B.storage),re=me(B.storage),b.assert(re,"Unexpectedly cannot fetch reserved storage "+B.storage);else V(c.SQLITE_NOTFOUND,"No such storage:",B.storage);if(B.events)(re.listeners??=[]).push(B)},Ir=function(B){let re=me(B?.storage);if(re?.listeners&&B.events){let ae=re.listeners.length;re.listeners=re.listeners.filter((Se)=>Se!==B);let ue=ae>re.listeners.length;if(!re.listeners.length)re.listeners=void 0;return ue}return!1};if(f.kvvfs.reserve=Ge,f.kvvfs.import=qe,f.kvvfs.export=Ie,f.kvvfs.unlink=ct,f.kvvfs.listen=zt,f.kvvfs.unlisten=Ir,f.kvvfs.exists=(B)=>!!me(B),f.kvvfs.estimateSize=Te,f.kvvfs.clear=ye,globalThis.Storage)c.sqlite3_js_kvvfs_size=(B="")=>Te(B),c.sqlite3_js_kvvfs_clear=(B="")=>ye(B);if(f.oo1?.DB){let B=f.oo1.DB;f.oo1.JsStorageDb=function(ae=f.oo1.JsStorageDb.defaultStorageName){let ue=B.dbCtorHelper.normalizeArgs(...arguments);switch(ue.vfs="kvvfs",ue.filename){case":sessionStorage:":ue.filename="session";break;case":localStorage:":ue.filename="local";break}let Se=/(file:(\/\/)?)([^?]+)/.exec(ue.filename);ee(Se?Se[3]:ue.filename),B.dbCtorHelper.call(this,ue)},f.oo1.JsStorageDb.defaultStorageName=N.storagePool.session?"session":P;let re=f.oo1.JsStorageDb;re.prototype=Object.create(B.prototype),re.clearStorage=ye,re.prototype.clearStorage=function(){return re.clearStorage(this.affirmOpen().dbFilename(),!0)},re.storageSize=Te,re.prototype.storageSize=function(){return re.storageSize(this.affirmOpen().dbFilename(),!0)}}if(f.__isUnderTest&&f.vtab){let B=Object.assign(Object.create(null),{rowid:{type:"INTEGER"},name:{type:"TEXT"},nRef:{type:"INTEGER"},nOpen:{type:"INTEGER"},isTransient:{type:"INTEGER"},dbSize:{type:"INTEGER"}});Object.keys(B).forEach((Oe,ke)=>B[Oe].colId=ke);let re=f.vtab,ae=Object.assign(Object.create(null),{row:function(){return N.storagePool[this.names[this.rowid]]}});Object.assign(Object.create(ae),{rowid:0,names:Object.keys(N.storagePool).filter((Oe)=>!N.rxJournalSuffix.test(Oe))});let ue=function(Oe,ke){let Ne=Oe instanceof c.sqlite3_vtab_cursor?Oe:re.xCursor.get(Oe);if(ke||!Ne.vTabState)Ne.vTabState=Object.assign(Object.create(ae),{rowid:0,names:Object.keys(N.storagePool).filter((je)=>!N.rxJournalSuffix.test(je))});return Ne.vTabState},Se=()=>{},Re=function Oe(){return Oe.mod??=new f.capi.sqlite3_module().setupModule({catchExceptions:!0,methods:{xConnect:function(ke,Ne,je,Qe,Me,yt){Se("xConnect");try{let Ft=[];Object.keys(B).forEach((Zt)=>{Ft.push(Zt+" "+B[Zt].type)});let rn=c.sqlite3_declare_vtab(ke,"CREATE TABLE ignored("+Ft.join(",")+")");if(rn===0){let Zt=re.xVtab.create(Me);b.assert(Zt===re.xVtab.get(I.peekPtr(Me)),"output pointer check failed")}return rn}catch(Ft){return re.xError("xConnect",Ft,c.SQLITE_ERROR)}},xCreate:I.ptr.null,xDisconnect:function(ke){return Se("xDisconnect",...arguments),re.xVtab.dispose(ke),0},xOpen:function(ke,Ne){return Se("xOpen",...arguments),re.xCursor.create(Ne),0},xClose:function(ke){Se("xClose",...arguments);let Ne=re.xCursor.unget(ke);return delete Ne.vTabState,Ne.dispose(),0},xNext:function(ke){Se("xNext",...arguments);let Ne=re.xCursor.get(ke);return++ue(Ne).rowid,0},xColumn:function(ke,Ne,je){Se("xColumn",...arguments);let Qe=ue(ke),Me=Qe.row();switch(b.assert(Me,"Unexpected xColumn call"),je){case B.rowid.colId:c.sqlite3_result_int(Ne,Qe.rowid);break;case B.name.colId:c.sqlite3_result_text(Ne,Me.jzClass,-1,c.SQLITE_TRANSIENT);break;case B.nRef.colId:c.sqlite3_result_int(Ne,Me.refc);break;case B.nOpen.colId:c.sqlite3_result_int(Ne,Me.files.length);break;case B.isTransient.colId:c.sqlite3_result_int(Ne,!!Me.deleteAtRefc0);break;case B.dbSize.colId:c.sqlite3_result_int(Ne,w(Me));break;default:return c.sqlite3_result_error(Ne,"Invalid column id: "+je),c.SQLITE_RANGE}return 0},xRowid:function(ke,Ne){Se("xRowid",...arguments);let je=ue(ke);return re.xRowid(Ne,je.rowid),0},xEof:function(ke){let Ne=ue(ke);return Se("xEof?="+!Ne.row(),...arguments),!Ne.row()},xFilter:function(ke,Ne,je,Qe,Me){return Se("xFilter",...arguments),ue(ke,!0),0},xBestIndex:function(ke,Ne){Se("xBestIndex",...arguments);let je=new c.sqlite3_index_info(Ne);return je.$estimatedRows=N.storagePool.size,je.$estimatedCost=1,je.dispose(),0}}})};f.kvvfs.create_module=function(Oe,ke="sqlite_kvvfs"){return c.sqlite3_create_module(Oe,ke,Re(),I.ptr.null)}}}),globalThis.sqlite3ApiBootstrap.initializers.push(function(f){if(f.config.disable?.vfs?.opfs&&f.config.disable.vfs["opfs-vfs"])return;let c=f.util.toss;f.capi;let d=f.util;f.wasm;let p=f.opfs=Object.create(null);p.thisThreadHasOPFS=()=>globalThis.FileSystemHandle&&globalThis.FileSystemDirectoryHandle&&globalThis.FileSystemFileHandle&&globalThis.FileSystemFileHandle.prototype.createSyncAccessHandle&&navigator?.storage?.getDirectory,p.getRootDir=async function b(){return b.promise??=navigator.storage.getDirectory().then((I)=>(p.rootDirectory=I,I)).catch((I)=>{throw delete b.promise,I})},p.getResolvedPath=function(b,I){let V=new URL(b,"file://irrelevant").pathname;return I?V.split("/").filter((M)=>!!M):V},p.getDirForFilename=async function(I,V=!1){let M=p.getResolvedPath(I,!0),N=M.pop(),q=await p.getRootDir();for(let H of M)if(H)q=await q.getDirectoryHandle(H,{create:!!V});return[q,N]},p.mkdir=async function(b){try{return await p.getDirForFilename(b+"/filepart",!0),!0}catch(I){return!1}},p.entryExists=async function(b){try{let[I,V]=await p.getDirForFilename(b);return await I.getFileHandle(V),!0}catch(I){return!1}},p.randomFilename=function b(I=16){if(!b._chars)b._chars="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012346789",b._n=b._chars.length;let V=[],M=0;for(;M<I;++M){let N=Math.random()*(b._n*64)%b._n|0;V[M]=b._chars[N]}return V.join("")},p.treeList=async function(){let b=async function V(M,N){N.name=M.name,N.dirs=[],N.files=[];for await(let q of M.values())if(q.kind==="directory"){let H=Object.create(null);N.dirs.push(H),await V(q,H)}else N.files.push(q.name)},I=Object.create(null);return await b(await p.getRootDir(),I),I},p.rmfr=async function(){let b=await p.getRootDir(),I={recurse:!0};for await(let V of b.values())b.removeEntry(V.name,I)},p.unlink=async function(b,I=!1,V=!1){try{let[M,N]=await p.getDirForFilename(b,!1);return await M.removeEntry(N,{recursive:I}),!0}catch(M){if(V)throw Error("unlink(",arguments[0],") failed: "+M.message,{cause:M});return!1}},p.traverse=async function(b){let I={recursive:!0,directory:await p.getRootDir()};if(typeof b==="function")b={callback:b};b=Object.assign(I,b||{}),async function V(M,N){for await(let q of M.values())if(b.callback(q,M,N)===!1)return!1;else if(b.recursive&&q.kind==="directory"){if(await V(q,N+1)===!1)break}}(b.directory,0)};let E=async function(b,I){let[V,M]=await p.getDirForFilename(b,!0),N=await(await V.getFileHandle(M,{create:!0})).createSyncAccessHandle(),q=0,H,G=!1;try{N.truncate(0);while((H=await I())!==void 0){if(H instanceof ArrayBuffer)H=new Uint8Array(H);if(!G&&q===0&&H.byteLength>=15)d.affirmDbHeader(H),G=!0;N.write(H,{at:q}),q+=H.byteLength}if(q<512||q%512!==0)c("Input size",q,"is not correct for an SQLite database.");if(!G){let le=new Uint8Array(20);N.read(le,{at:0}),d.affirmDbHeader(le)}return N.write(new Uint8Array([1,1]),{at:18}),q}catch(le){throw await N.close(),N=void 0,await V.removeEntry(M).catch(()=>{}),le}finally{if(N)await N.close()}};p.importDb=async function(b,I){if(I instanceof Function)return E(b,I);if(I instanceof ArrayBuffer)I=new Uint8Array(I);d.affirmIsDb(I);let V=I.byteLength,[M,N]=await p.getDirForFilename(b,!0),q,H=0;try{if(q=await(await M.getFileHandle(N,{create:!0})).createSyncAccessHandle(),q.truncate(0),H=q.write(I,{at:0}),H!=V)c("Expected to write "+V+" bytes but wrote "+H+".");return q.write(new Uint8Array([1,1]),{at:18}),H}catch(G){if(q)await q.close(),q=void 0;throw await M.removeEntry(N).catch(()=>{}),G}finally{if(q)await q.close()}},p.vfsInstallationFeatureCheck=function(b){if(!globalThis.SharedArrayBuffer||!globalThis.Atomics)c("Cannot install OPFS: Missing SharedArrayBuffer and/or Atomics.","The server must emit the COOP/COEP response headers to enable those.","See https://sqlite.org/wasm/doc/trunk/persistence.md#coop-coep");else if(typeof WorkerGlobalScope>"u")c("The OPFS sqlite3_vfs cannot run in the main thread","because it requires Atomics.wait().");else if(!globalThis.FileSystemHandle||!globalThis.FileSystemDirectoryHandle||!globalThis.FileSystemFileHandle?.prototype?.createSyncAccessHandle||!navigator?.storage?.getDirectory)c("Missing required OPFS APIs.");else if(b==="opfs-wl"&&!globalThis.Atomics.waitAsync)c("The",b,"VFS requires Atomics.waitAsync(), which is not available.")},p.initOptions=function(I,V){let M=new URL(globalThis.location.href).searchParams;if(M.has(I+"-disable"))return;try{p.vfsInstallationFeatureCheck(I)}catch(N){return}if(V=d.nu(V),V.vfsName=I,V.verbose??=M.has("opfs-verbose")?+M.get("opfs-verbose"):1,V.sanityChecks??=M.has("opfs-sanity-check"),!p.proxyUri){if(p.proxyUri="sqlite3-opfs-async-proxy.js",f.scriptInfo?.sqlite3Dir)p.proxyUri=f.scriptInfo.sqlite3Dir+p.proxyUri}if(V.proxyUri??=p.proxyUri,typeof V.proxyUri==="function")V.proxyUri=V.proxyUri();return p.options=V},p.createVfsState=function(){let b=d.nu(),I=p.options;b.verbose=I.verbose;let V=[f.config.error,f.config.warn,f.config.log],M=I.vfsName||c("Maintenance required: missing VFS name"),N=(W,...he)=>{if(b.verbose>W)V[W](M+":",...he)},q=(...W)=>N(2,...W),H=(...W)=>N(1,...W),G=(...W)=>N(0,...W),{capi:le,wasm:O}=f,R=b.vfs=new le.sqlite3_vfs,X=R.ioMethods=new le.sqlite3_io_methods;X.$iVersion=1,R.$iVersion=2,R.$szOsFile=le.sqlite3_file.structInfo.sizeof,R.$mxPathname=1024,R.$zName=O.allocCString(M),R.addOnDispose("$zName",R.$zName,X),R.metrics=d.nu({counters:d.nu(),dump:function(){let W,he=0,be=0,me=0;for(W in b.opIds){let ve=ee[W];he+=ve.count,be+=ve.time,me+=ve.wait,ve.avgTime=ve.count&&ve.time?ve.time/ve.count:0,ve.avgWait=ve.count&&ve.wait?ve.wait/ve.count:0}f.config.log(globalThis.location.href,"metrics for",globalThis.location.href,":",ee,`
522
- Total of`,he,"op(s) for",be,"ms (incl. "+me+" ms of waiting on the async side)"),f.config.log("Serialization metrics:",R.metrics.counters.s11n),R.worker?.postMessage?.({type:"opfs-async-metrics"})},reset:function(){let W,he=(ve)=>ve.count=ve.time=ve.wait=0,be=R.metrics.counters;for(W in b.opIds)he(be[W]=Object.create(null));let me=be.s11n=Object.create(null);me=me.serialize=Object.create(null),me.count=me.time=0,me=be.s11n.deserialize=Object.create(null),me.count=me.time=0}}),b.asyncIdleWaitTime=150,b.asyncS11nExceptions=1,b.fileBufferSize=65536,b.sabS11nOffset=b.fileBufferSize,b.sabS11nSize=R.$mxPathname*2,b.sabIO=new SharedArrayBuffer(b.fileBufferSize+b.sabS11nSize),b.opIds=Object.create(null);{let W=0;b.opIds.whichOp=W++,b.opIds.rc=W++,b.opIds.xAccess=W++,b.opIds.xClose=W++,b.opIds.xDelete=W++,b.opIds.xDeleteNoWait=W++,b.opIds.xFileSize=W++,b.opIds.xLock=W++,b.opIds.xOpen=W++,b.opIds.xRead=W++,b.opIds.xSleep=W++,b.opIds.xSync=W++,b.opIds.xTruncate=W++,b.opIds.xUnlock=W++,b.opIds.xWrite=W++,b.opIds.mkdir=W++,b.opIds["opfs-async-metrics"]=W++,b.opIds["opfs-async-shutdown"]=W++,b.opIds.retry=W++,b.sabOP=new SharedArrayBuffer(W*4)}b.sq3Codes=Object.create(null);for(let W of["SQLITE_ACCESS_EXISTS","SQLITE_ACCESS_READWRITE","SQLITE_BUSY","SQLITE_CANTOPEN","SQLITE_ERROR","SQLITE_IOERR","SQLITE_IOERR_ACCESS","SQLITE_IOERR_CLOSE","SQLITE_IOERR_DELETE","SQLITE_IOERR_FSYNC","SQLITE_IOERR_LOCK","SQLITE_IOERR_READ","SQLITE_IOERR_SHORT_READ","SQLITE_IOERR_TRUNCATE","SQLITE_IOERR_UNLOCK","SQLITE_IOERR_WRITE","SQLITE_LOCK_EXCLUSIVE","SQLITE_LOCK_NONE","SQLITE_LOCK_PENDING","SQLITE_LOCK_RESERVED","SQLITE_LOCK_SHARED","SQLITE_LOCKED","SQLITE_MISUSE","SQLITE_NOTFOUND","SQLITE_OPEN_CREATE","SQLITE_OPEN_DELETEONCLOSE","SQLITE_OPEN_MAIN_DB","SQLITE_OPEN_READONLY","SQLITE_LOCK_NONE","SQLITE_LOCK_SHARED","SQLITE_LOCK_RESERVED","SQLITE_LOCK_PENDING","SQLITE_LOCK_EXCLUSIVE"])b.sq3Codes[W]=le[W]??c("Maintenance required: not found:",W);b.opfsFlags=Object.assign(Object.create(null),{OPFS_UNLOCK_ASAP:1,OPFS_UNLINK_BEFORE_OPEN:2,defaultUnlockAsap:!1}),R.metrics.reset();let ee=R.metrics.counters,U=R.opRun=(W,...he)=>{let be=b.opIds[W]||c(R.vfsName+": Invalid op ID:",W);b.s11n.serialize(...he),Atomics.store(b.sabOPView,b.opIds.rc,-1),Atomics.store(b.sabOPView,b.opIds.whichOp,be),Atomics.notify(b.sabOPView,b.opIds.whichOp);let me=performance.now();while(Atomics.wait(b.sabOPView,b.opIds.rc,-1)!=="not-equal");let ve=Atomics.load(b.sabOPView,b.opIds.rc);if(ee[W].wait+=performance.now()-me,ve&&b.asyncS11nExceptions){let z=b.s11n.deserialize();if(z)G(W+"() async error:",...z)}return ve},J=Object.create(null);J.op=void 0,J.start=void 0;let pe=R.mTimeStart=(W)=>{J.start=performance.now(),J.op=W,++ee[W].count},S=R.mTimeEnd=()=>ee[J.op].time+=performance.now()-J.start,P=R.__openFiles=Object.create(null);R.ioSyncWrappers=d.nu({xCheckReservedLock:function(W,he){return O.poke(he,0,"i32"),0},xClose:function(W){pe("xClose");let he=0,be=P[W];if(be){if(delete P[W],he=U("xClose",W),be.sq3File)be.sq3File.dispose()}return S(),he},xDeviceCharacteristics:function(W){return le.SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN},xFileControl:function(W,he,be){return le.SQLITE_NOTFOUND},xFileSize:function(W,he){pe("xFileSize");let be=U("xFileSize",W);if(be==0)try{let me=b.s11n.deserialize()[0];O.poke(he,me,"i64")}catch(me){G("Unexpected error reading xFileSize() result:",me),be=b.sq3Codes.SQLITE_IOERR}return S(),be},xRead:function(W,he,be,me){pe("xRead");let ve=P[W],z;try{if(z=U("xRead",W,be,Number(me)),z===0||le.SQLITE_IOERR_SHORT_READ===z)O.heap8u().set(ve.sabView.subarray(0,be),Number(he))}catch(g){G("xRead(",arguments,") failed:",g,ve),z=le.SQLITE_IOERR_READ}return S(),z},xSync:function(W,he){pe("xSync");let be=U("xSync",W,he);return S(),be},xTruncate:function(W,he){pe("xTruncate");let be=U("xTruncate",W,Number(he));return S(),be},xWrite:function(W,he,be,me){pe("xWrite");let ve=P[W],z;try{ve.sabView.set(O.heap8u().subarray(Number(he),Number(he)+be)),z=U("xWrite",W,be,Number(me))}catch(g){G("xWrite(",arguments,") failed:",g,ve),z=le.SQLITE_IOERR_WRITE}return S(),z}}),R.vfsSyncWrappers={xAccess:function(W,he,be,me){pe("xAccess");let ve=U("xAccess",O.cstrToJs(he));return O.poke(me,ve?0:1,"i32"),S(),0},xCurrentTime:function(W,he){return O.poke(he,2440587.5+new Date().getTime()/86400000,"double"),0},xCurrentTimeInt64:function(W,he){return O.poke(he,210866760000000+new Date().getTime(),"i64"),0},xDelete:function(W,he,be){pe("xDelete");let me=U("xDelete",O.cstrToJs(he),be,!1);return S(),me},xFullPathname:function(W,he,be,me){return O.cstrncpy(me,he,be)<be?0:le.SQLITE_CANTOPEN},xGetLastError:function(W,he,be){return f.config.warn("OPFS xGetLastError() has nothing sensible to return."),0},xOpen:function(he,be,me,ve,z){pe("xOpen");let g=0,w,T;if(!be)w=p.randomFilename(),be=T=O.allocCString(w);else if(O.isPtr(be)){if(le.sqlite3_uri_boolean(be,"opfs-unlock-asap",0))g|=b.opfsFlags.OPFS_UNLOCK_ASAP;if(le.sqlite3_uri_boolean(be,"delete-before-open",0))g|=b.opfsFlags.OPFS_UNLINK_BEFORE_OPEN;w=O.cstrToJs(be)}else return f.config.error("Impossible zName value in xOpen?",be),le.SQLITE_CANTOPEN;let C=d.nu({fid:me,filename:w,sab:new SharedArrayBuffer(b.fileBufferSize),flags:ve,readOnly:!(le.SQLITE_OPEN_CREATE&ve)&&!!(ve&le.SQLITE_OPEN_READONLY)}),te=U("xOpen",me,w,ve,g);if(te){if(T)O.dealloc(T)}else{if(C.readOnly)O.poke(z,le.SQLITE_OPEN_READONLY,"i32");if(P[me]=C,C.sabView=b.sabFileBufView,C.sq3File=new le.sqlite3_file(me),T)C.sq3File.addOnDispose(T);C.sq3File.$pMethods=X.pointer,C.lockType=le.SQLITE_LOCK_NONE}return S(),te}};let K=le.sqlite3_vfs_find(null);if(K){let W=new le.sqlite3_vfs(K);R.$xRandomness=W.$xRandomness,R.$xSleep=W.$xSleep,W.dispose()}if(!R.$xRandomness)R.vfsSyncWrappers.xRandomness=function(W,he,be){let me=O.heap8u(),ve=0,z=Number(be);for(;ve<he;++ve)me[z+ve]=Math.random()*255000&255;return ve};if(!R.$xSleep)R.vfsSyncWrappers.xSleep=function(W,he){return pe("xSleep"),Atomics.wait(b.sabOPView,b.opIds.xSleep,0,he),S(),0};let oe=function(){if(b.s11n)return b.s11n;let W=new TextDecoder,he=new TextEncoder("utf-8"),be=new Uint8Array(b.sabIO,b.sabS11nOffset,b.sabS11nSize),me=new DataView(b.sabIO,b.sabS11nOffset,b.sabS11nSize);b.s11n=Object.create(null);let ve=Object.create(null);ve.number={id:1,size:8,getter:"getFloat64",setter:"setFloat64"},ve.bigint={id:2,size:8,getter:"getBigInt64",setter:"setBigInt64"},ve.boolean={id:3,size:4,getter:"getInt32",setter:"setInt32"},ve.string={id:4};let z=(w)=>ve[typeof w]||c("Maintenance required: this value type cannot be serialized.",w),g=(w)=>{switch(w){case ve.number.id:return ve.number;case ve.bigint.id:return ve.bigint;case ve.boolean.id:return ve.boolean;case ve.string.id:return ve.string;default:c("Invalid type ID:",w)}};return b.s11n.deserialize=function(w=!1){performance.now();let T=be[0],C=T?[]:null;if(T){let te=[],se=1,A,L,Q;for(A=0;A<T;++A,++se)te.push(g(be[se]));for(A=0;A<T;++A){let ne=te[A];if(ne.getter)Q=me[ne.getter](se,b.littleEndian),se+=ne.size;else L=me.getInt32(se,b.littleEndian),se+=4,Q=W.decode(be.slice(se,se+L)),se+=L;C.push(Q)}}if(w)be[0]=0;return C},b.s11n.serialize=function(...w){if(performance.now(),w.length){let T=[],C=0,te=1;be[0]=w.length&255;for(;C<w.length;++C,++te)T.push(z(w[C])),be[te]=T[C].id;for(C=0;C<w.length;++C){let se=T[C];if(se.setter)me[se.setter](te,w[C],b.littleEndian),te+=se.size;else{let A=he.encode(w[C]);me.setInt32(te,A.byteLength,b.littleEndian),te+=4,be.set(A,te),te+=A.byteLength}}}else be[0]=0},b.s11n};return R.initS11n=oe,R.bindVfs=function(W,he){return Object.assign(R.ioSyncWrappers,W),new Promise(function(be,me){let ve=void 0,z=(A)=>(ve=!0,R.dispose(),me(A)),g=()=>{try{he(f,R)}catch(A){return z(A)}return ve=!1,be(f)},w=p.options;w.proxyUri+(w.proxyUri.indexOf("?")<0?"?":"&")+M;let T=new URL("sqlite3-opfs-async-proxy.js",import.meta.url);T.searchParams.set("vfs",M);let C=R.worker=new Worker(T.toString()),te=setTimeout(()=>{if(ve===void 0)z(Error("Timeout while waiting for OPFS async proxy worker."))},4000);C._originalOnError=C.onerror,C.onerror=function(A){G("Error initializing OPFS asyncer:",A),z(Error("Loading OPFS async Worker failed for unknown reasons."))},R.opRun;let se=function(){let A=O.scopedAllocPush(),L=new le.sqlite3_file;try{let Q=L.pointer,ne=le.SQLITE_OPEN_CREATE|le.SQLITE_OPEN_READWRITE|le.SQLITE_OPEN_MAIN_DB,ye=O.scopedAlloc(8),Te="/sanity/check/file"+randomFilename(8),Ie=O.scopedAllocCString(Te),qe;if(b.s11n.serialize("This is ä string."),qe=b.s11n.deserialize(),q("deserialize() says:",qe),qe[0]!=="This is ä string.")c("String d13n error.");if(R.vfsSyncWrappers.xAccess(R.pointer,Ie,0,ye),qe=O.peek(ye,"i32"),q("xAccess(",Te,") exists ?=",qe),qe=R.vfsSyncWrappers.xOpen(R.pointer,Ie,Q,ne,ye),q("open rc =",qe,"state.sabOPView[xOpen] =",b.sabOPView[b.opIds.xOpen]),qe!==0){G("open failed with code",qe);return}if(R.vfsSyncWrappers.xAccess(R.pointer,Ie,0,ye),qe=O.peek(ye,"i32"),!qe)c("xAccess() failed to detect file.");if(qe=R.ioSyncWrappers.xSync(L.pointer,0),qe)c("sync failed w/ rc",qe);if(qe=R.ioSyncWrappers.xTruncate(L.pointer,1024),qe)c("truncate failed w/ rc",qe);if(O.poke(ye,0,"i64"),qe=R.ioSyncWrappers.xFileSize(L.pointer,ye),qe)c("xFileSize failed w/ rc",qe);if(q("xFileSize says:",O.peek(ye,"i64")),qe=R.ioSyncWrappers.xWrite(L.pointer,Ie,10,1),qe)c("xWrite() failed!");let Ge=O.scopedAlloc(16);qe=R.ioSyncWrappers.xRead(L.pointer,Ge,6,2),O.poke(Ge+6,0);let ct=O.cstrToJs(Ge);if(q("xRead() got:",ct),ct!=="sanity")c("Unexpected xRead() value.");if(R.vfsSyncWrappers.xSleep)q("xSleep()ing before close()ing..."),R.vfsSyncWrappers.xSleep(R.pointer,2000),q("waking up from xSleep()");if(qe=R.ioSyncWrappers.xClose(Q),q("xClose rc =",qe,"sabOPView =",b.sabOPView),q("Deleting file:",Te),R.vfsSyncWrappers.xDelete(R.pointer,Ie,4660),R.vfsSyncWrappers.xAccess(R.pointer,Ie,0,ye),qe=O.peek(ye,"i32"),qe)c("Expecting 0 from xAccess(",Te,") after xDelete().");H("End of OPFS sanity checks.")}finally{L.dispose(),O.scopedAllocPop(A)}};C.onmessage=function({data:A}){switch(A.type){case"opfs-unavailable":z(Error(A.payload.join(" ")));break;case"opfs-async-loaded":delete b.vfs,C.postMessage({type:"opfs-async-init",args:d.nu(b)});break;case"opfs-async-inited":if(ve===!0)break;clearTimeout(te),te=null;try{if(f.vfs.installVfs({io:{struct:R.ioMethods,methods:R.ioSyncWrappers},vfs:{struct:R,methods:R.vfsSyncWrappers}}),b.sabOPView=new Int32Array(b.sabOP),b.sabFileBufView=new Uint8Array(b.sabIO,0,b.fileBufferSize),b.sabS11nView=new Uint8Array(b.sabIO,b.sabS11nOffset,b.sabS11nSize),R.initS11n(),delete R.initS11n,w.sanityChecks)H("Running sanity checks because of opfs-sanity-check URL arg..."),se();if(p.thisThreadHasOPFS())p.getRootDir().then((L)=>{C.onerror=C._originalOnError,delete C._originalOnError,q("End of OPFS sqlite3_vfs setup.",R),g()}).catch(z);else g()}catch(L){G(L),z(L)}break;case"debug":H("debug message from worker:",A);break;default:{let L="Unexpected message from the OPFS async worker: "+JSON.stringify(A);G(L),z(Error(L));break}}}})},b}}),globalThis.sqlite3ApiBootstrap.initializers.push(function(f){if(!f.opfs||f.config.disable?.vfs?.opfs)return;let c=f.util,d=f.opfs||f.util.toss("Missing sqlite3.opfs"),p=async function(E){if(E=d.initOptions("opfs",E),!E)return f;let b=f.capi,I=d.createVfsState().vfs,V=I.metrics.counters,{mTimeStart:M,mTimeEnd:N,opRun:q,__openFiles:H}=I;return I.bindVfs(c.nu({xLock:function(G,le){M("xLock"),++V.xLock.count;let O=H[G],R=0;if(O.lockType)O.lockType=le;else if(R=q("xLock",G,le),R===0)O.lockType=le;return N(),R},xUnlock:function(G,le){M("xUnlock"),++V.xUnlock.count;let O=H[G],R=0;if(b.SQLITE_LOCK_NONE===le&&O.lockType)R=q("xUnlock",G,le);if(R===0)O.lockType=le;return N(),R}}),function(G,le){if(G.oo1){let O=function(...R){let X=G.oo1.DB.dbCtorHelper.normalizeArgs(...R);X.vfs=le.$zName,G.oo1.DB.dbCtorHelper.call(this,X)};O.prototype=Object.create(G.oo1.DB.prototype),G.oo1.OpfsDb=O,O.importDb=d.importDb,G.oo1.DB.dbCtorHelper.setVfsPostOpenCallback(I.pointer,function(R,X){X.capi.sqlite3_busy_timeout(R,1e4)})}})};globalThis.sqlite3ApiBootstrap.initializersAsync.push(async(E)=>p().catch((b)=>{E.config.warn("Ignoring inability to install 'opfs' sqlite3_vfs:",b)}))}),globalThis.sqlite3ApiBootstrap.initializers.push(function(f){if(f.config.disable?.vfs?.["opfs-sahpool"])return;let c=f.util.toss,d=f.util.toss3,p=Object.create(null),{capi:E,util:b,wasm:I}=f,V=4096,M=512,N=4,q=8,H=M+N,G=M,le=H,O=V,R=E.SQLITE_OPEN_MAIN_DB|E.SQLITE_OPEN_MAIN_JOURNAL|E.SQLITE_OPEN_SUPER_JOURNAL|E.SQLITE_OPEN_WAL,X=E.SQLITE_OPEN_MEMORY,ee=".opaque",U=()=>Math.random().toString(36).slice(2),J=new TextDecoder,pe=new TextEncoder,S=Object.assign(Object.create(null),{name:"opfs-sahpool",directory:void 0,initialCapacity:6,clearOnInit:!1,verbosity:2,forceReinitIfPreviouslyFailed:!1}),P=[f.config.error,f.config.warn,f.config.log];f.config.log;let K=f.config.warn;f.config.error;let oe=new Map,W=(A)=>oe.get(A),he=(A,L)=>{if(L)oe.set(A,L);else oe.delete(A)},be=new Map,me=(A)=>be.get(A),ve=(A,L)=>{if(L)be.set(A,L);else be.delete(A)},z={xCheckReservedLock:function(A,L){let Q=me(A);return Q.log("xCheckReservedLock"),Q.storeErr(),I.poke32(L,1),0},xClose:function(A){let L=me(A);L.storeErr();let Q=L.getOFileForS3File(A);if(Q)try{if(L.log(`xClose ${Q.path}`),L.mapS3FileToOFile(A,!1),Q.sah.flush(),Q.flags&E.SQLITE_OPEN_DELETEONCLOSE)L.deletePath(Q.path)}catch(ne){return L.storeErr(ne,E.SQLITE_IOERR)}return 0},xDeviceCharacteristics:function(A){return E.SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN},xFileControl:function(A,L,Q){return E.SQLITE_NOTFOUND},xFileSize:function(A,L){let Q=me(A);Q.log("xFileSize");let ne=Q.getOFileForS3File(A).sah.getSize()-O;return I.poke64(L,BigInt(ne)),0},xLock:function(A,L){let Q=me(A);Q.log(`xLock ${L}`),Q.storeErr();let ne=Q.getOFileForS3File(A);return ne.lockType=L,0},xRead:function(A,L,Q,ne){let ye=me(A);ye.storeErr();let Te=ye.getOFileForS3File(A);ye.log(`xRead ${Te.path} ${Q} @ ${ne}`);try{let Ie=Te.sah.read(I.heap8u().subarray(Number(L),Number(L)+Q),{at:O+Number(ne)});if(Ie<Q)return I.heap8u().fill(0,Number(L)+Ie,Number(L)+Q),E.SQLITE_IOERR_SHORT_READ;return 0}catch(Ie){return ye.storeErr(Ie,E.SQLITE_IOERR)}},xSectorSize:function(A){return V},xSync:function(A,L){let Q=me(A);Q.log(`xSync ${L}`),Q.storeErr();let ne=Q.getOFileForS3File(A);try{return ne.sah.flush(),0}catch(ye){return Q.storeErr(ye,E.SQLITE_IOERR)}},xTruncate:function(A,L){let Q=me(A);Q.log(`xTruncate ${L}`),Q.storeErr();let ne=Q.getOFileForS3File(A);try{return ne.sah.truncate(O+Number(L)),0}catch(ye){return Q.storeErr(ye,E.SQLITE_IOERR)}},xUnlock:function(A,L){let Q=me(A);Q.log("xUnlock");let ne=Q.getOFileForS3File(A);return ne.lockType=L,0},xWrite:function(A,L,Q,ne){let ye=me(A);ye.storeErr();let Te=ye.getOFileForS3File(A);ye.log(`xWrite ${Te.path} ${Q} ${ne}`);try{return Q===Te.sah.write(I.heap8u().subarray(Number(L),Number(L)+Q),{at:O+Number(ne)})?0:c("Unknown write() failure.")}catch(Ie){return ye.storeErr(Ie,E.SQLITE_IOERR)}}},g=new E.sqlite3_io_methods;g.$iVersion=1,f.vfs.installVfs({io:{struct:g,methods:z}});let w={xAccess:function(A,L,Q,ne){let ye=W(A);ye.storeErr();try{let Te=ye.getPath(L);I.poke32(ne,ye.hasFilename(Te)?1:0)}catch(Te){I.poke32(ne,0)}return 0},xCurrentTime:function(A,L){return I.poke(L,2440587.5+new Date().getTime()/86400000,"double"),0},xCurrentTimeInt64:function(A,L){return I.poke(L,210866760000000+new Date().getTime(),"i64"),0},xDelete:function(A,L,Q){let ne=W(A);ne.log(`xDelete ${I.cstrToJs(L)}`),ne.storeErr();try{return ne.deletePath(ne.getPath(L)),0}catch(ye){return ne.storeErr(ye),E.SQLITE_IOERR_DELETE}},xFullPathname:function(A,L,Q,ne){return I.cstrncpy(ne,L,Q)<Q?0:E.SQLITE_CANTOPEN},xGetLastError:function(A,L,Q){let ne=W(A),ye=ne.popErr();if(ne.log(`xGetLastError ${L} e =`,ye),ye){let Te=I.scopedAllocPush();try{let[Ie,qe]=I.scopedAllocCString(ye.message,!0);if(I.cstrncpy(Q,Ie,L),qe>L)I.poke8(I.ptr.add(Q,L,-1),0)}catch(Ie){return E.SQLITE_NOMEM}finally{I.scopedAllocPop(Te)}}return ye?ye.sqlite3Rc||E.SQLITE_IOERR:0},xOpen:function(L,Q,ne,ye,Te){let Ie=W(L);try{ye&=~X,Ie.log(`xOpen ${I.cstrToJs(Q)} ${ye}`);let qe=Q&&I.peek8(Q)?Ie.getPath(Q):U(),Ge=Ie.getSAHForPath(qe);if(!Ge&&ye&E.SQLITE_OPEN_CREATE)if(Ie.getFileCount()<Ie.getCapacity())Ge=Ie.nextAvailableSAH(),Ie.setAssociatedPath(Ge,qe,ye);else c("SAH pool is full. Cannot create file",qe);if(!Ge)c("file not found:",qe);let ct={path:qe,flags:ye,sah:Ge};Ie.mapS3FileToOFile(ne,ct),ct.lockType=E.SQLITE_LOCK_NONE;let zt=new E.sqlite3_file(ne);return zt.$pMethods=g.pointer,zt.dispose(),I.poke32(Te,ye),0}catch(qe){return Ie.storeErr(qe),E.SQLITE_CANTOPEN}}},T=function(A){if(f.capi.sqlite3_vfs_find(A))d("VFS name is already registered:",A);let L=new E.sqlite3_vfs,Q=E.sqlite3_vfs_find(null),ne=Q?new E.sqlite3_vfs(Q):null;if(L.$iVersion=2,L.$szOsFile=E.sqlite3_file.structInfo.sizeof,L.$mxPathname=M,L.addOnDispose(L.$zName=I.allocCString(A),()=>he(L.pointer,0)),ne)L.$xRandomness=ne.$xRandomness,L.$xSleep=ne.$xSleep,ne.dispose();if(!L.$xRandomness&&!w.xRandomness)w.xRandomness=function(ye,Te,Ie){let qe=I.heap8u(),Ge=0,ct=Number(Ie);for(;Ge<Te;++Ge)qe[ct+Ge]=Math.random()*255000&255;return Ge};if(!L.$xSleep&&!w.xSleep)w.xSleep=(ye,Te)=>0;return f.vfs.installVfs({vfs:{struct:L,methods:w}}),L};class C{vfsDir;#e;#o;#i;#t=new Map;#r=new Map;#s=new Set;#c=new Map;#n=new Uint8Array(H);#l;#a;#d;constructor(A=Object.create(null)){this.#d=A.verbosity??S.verbosity,this.vfsName=A.name||S.name,this.#a=T(this.vfsName),he(this.#a.pointer,this),this.vfsDir=A.directory||"."+this.vfsName,this.#l=new DataView(this.#n.buffer,this.#n.byteOffset),this.isReady=this.reset(!!(A.clearOnInit??S.clearOnInit)).then(()=>{if(this.$error)throw this.$error;return this.getCapacity()?Promise.resolve(void 0):this.addCapacity(A.initialCapacity||S.initialCapacity)})}#u(A,...L){if(this.#d>A)P[A](this.vfsName+":",...L)}log(...A){this.#u(2,...A)}warn(...A){this.#u(1,...A)}error(...A){this.#u(0,...A)}getVfs(){return this.#a}getCapacity(){return this.#t.size}getFileCount(){return this.#r.size}getFileNames(){let A=[];for(let L of this.#r.keys())A.push(L);return A}async addCapacity(A){for(let L=0;L<A;++L){let Q=U(),ne=await(await this.#o.getFileHandle(Q,{create:!0})).createSyncAccessHandle();this.#t.set(ne,Q),this.setAssociatedPath(ne,"",0)}return this.getCapacity()}async reduceCapacity(A){let L=0;for(let Q of Array.from(this.#s)){if(L===A||this.getFileCount()===this.getCapacity())break;let ne=this.#t.get(Q);Q.close(),await this.#o.removeEntry(ne),this.#t.delete(Q),this.#s.delete(Q),++L}return L}releaseAccessHandles(){for(let A of this.#t.keys())A.close();this.#t.clear(),this.#r.clear(),this.#s.clear()}async acquireAccessHandles(A=!1){let L=[];for await(let[Q,ne]of this.#o)if(ne.kind==="file")L.push([Q,ne]);return Promise.all(L.map(async([Q,ne])=>{try{let ye=await ne.createSyncAccessHandle();if(this.#t.set(ye,Q),A)ye.truncate(O),this.setAssociatedPath(ye,"",0);else{let Te=this.getAssociatedPath(ye);if(Te)this.#r.set(Te,ye);else this.#s.add(ye)}}catch(ye){throw this.storeErr(ye),this.releaseAccessHandles(),ye}}))}getAssociatedPath(A){A.read(this.#n,{at:0});let L=this.#l.getUint32(G);if(this.#n[0]&&(L&E.SQLITE_OPEN_DELETEONCLOSE||(L&R)===0))return K(`Removing file with unexpected flags ${L.toString(16)}`,this.#n),this.setAssociatedPath(A,"",0),"";let Q=new Uint32Array(q/4);A.read(Q,{at:le});let ne=this.computeDigest(this.#n,L);if(Q.every((ye,Te)=>ye===ne[Te])){let ye=this.#n.findIndex((Te)=>Te===0);if(ye===0)A.truncate(O);return ye?J.decode(this.#n.subarray(0,ye)):""}else return K("Disassociating file with bad digest."),this.setAssociatedPath(A,"",0),""}setAssociatedPath(A,L,Q){let ne=pe.encodeInto(L,this.#n);if(M<=ne.written+1)c("Path too long:",L);if(L&&Q)Q|=X;this.#n.fill(0,ne.written,M),this.#l.setUint32(G,Q);let ye=this.computeDigest(this.#n,Q);if(A.write(this.#n,{at:0}),A.write(ye,{at:le}),A.flush(),L)this.#r.set(L,A),this.#s.delete(A);else A.truncate(O),this.#s.add(A)}computeDigest(A,L){if(L&X){let Q=3735928559,ne=1103547991;for(let ye of A)Q=Math.imul(Q^ye,2654435761),ne=Math.imul(ne^ye,104729);return new Uint32Array([Q>>>0,ne>>>0])}else return new Uint32Array([0,0])}async reset(A){await this.isReady;let L=await navigator.storage.getDirectory(),Q;for(let ne of this.vfsDir.split("/"))if(ne)Q=L,L=await L.getDirectoryHandle(ne,{create:!0});return this.#e=L,this.#i=Q,this.#o=await this.#e.getDirectoryHandle(ee,{create:!0}),this.releaseAccessHandles(),this.acquireAccessHandles(A)}getPath(A){if(I.isPtr(A))A=I.cstrToJs(A);return(A instanceof URL?A:new URL(A,"file://localhost/")).pathname}deletePath(A){let L=this.#r.get(A);if(L)this.#r.delete(A),this.setAssociatedPath(L,"",0);return!!L}storeErr(A,L){if(A)A.sqlite3Rc=L||E.SQLITE_IOERR,this.error(A);return this.$error=A,L}popErr(){let A=this.$error;return this.$error=void 0,A}nextAvailableSAH(){let[A]=this.#s.keys();return A}getOFileForS3File(A){return this.#c.get(A)}mapS3FileToOFile(A,L){if(L)this.#c.set(A,L),ve(A,this);else this.#c.delete(A),ve(A,!1)}hasFilename(A){return this.#r.has(A)}getSAHForPath(A){return this.#r.get(A)}async removeVfs(){if(!this.#a.pointer||!this.#o)return!1;E.sqlite3_vfs_unregister(this.#a.pointer),this.#a.dispose(),delete p[this.vfsName];try{this.releaseAccessHandles(),await this.#e.removeEntry(ee,{recursive:!0}),this.#o=void 0,await this.#i.removeEntry(this.#e.name,{recursive:!0}),this.#e=this.#i=void 0}catch(A){f.config.error(this.vfsName,"removeVfs() failed with no recovery strategy:",A)}return!0}pauseVfs(){if(this.#c.size>0)f.SQLite3Error.toss(E.SQLITE_MISUSE,"Cannot pause VFS",this.vfsName,"because it has opened files.");if(this.#t.size>0)E.sqlite3_vfs_unregister(this.vfsName),this.releaseAccessHandles();return this}isPaused(){return this.#t.size===0}async unpauseVfs(){if(this.#t.size===0)return this.acquireAccessHandles(!1).then(()=>E.sqlite3_vfs_register(this.#a,0),this);return this}exportFile(A){//! Documented elsewhere in this file.
536
+ `)}async hexBodyHash(){let e=this.headers.get("X-Amz-Content-Sha256")||(this.service==="s3"&&this.signQuery?"UNSIGNED-PAYLOAD":null);if(e==null){if(this.body&&typeof this.body!=="string"&&!("byteLength"in this.body))throw Error("body must be a string, ArrayBuffer or ArrayBufferView, unless you include the X-Amz-Content-Sha256 header");e=Ua(await Sg(this.body||""))}return e}}async function co(e,t){let r=await crypto.subtle.importKey("raw",typeof e==="string"?ja.encode(e):e,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return crypto.subtle.sign("HMAC",r,ja.encode(t))}async function Sg(e){return crypto.subtle.digest("SHA-256",typeof e==="string"?ja.encode(e):e)}function Ua(e){let t=new Uint8Array(e),r="";for(let n=0;n<t.length;n++){let o=t[n];r+=xg[o>>>4&15],r+=xg[o&15]}return r}function Tg(e){return e.replace(/[!'()*]/g,(t)=>"%"+t.charCodeAt(0).toString(16).toUpperCase())}function Cv(e,t){let{hostname:r,pathname:n}=e;if(r.endsWith(".on.aws")){let u=r.match(/^[^.]{1,63}\.lambda-url\.([^.]{1,63})\.on\.aws$/);return u!=null?["lambda",u[1]||""]:["",""]}if(r.endsWith(".r2.cloudflarestorage.com"))return["s3","auto"];if(r.endsWith(".backblazeb2.com")){let u=r.match(/^(?:[^.]{1,63}\.)?s3\.([^.]{1,63})\.backblazeb2\.com$/);return u!=null?["s3",u[1]||""]:["",""]}let o=r.replace("dualstack.","").match(/([^.]{1,63})\.(?:([^.]{0,63})\.)?amazonaws\.com(?:\.cn)?$/),s=o&&o[1]||"",a=o&&o[2];if(a==="us-gov")a="us-gov-west-1";else if(a==="s3"||a==="s3-accelerate")a="us-east-1",s="s3";else if(s==="iot")if(r.startsWith("iot."))s="execute-api";else if(r.startsWith("data.jobs.iot."))s="iot-jobs-data";else s=n==="/mqtt"?"iotdevicegateway":"iotdata";else if(s==="autoscaling"){let u=(t.get("X-Amz-Target")||"").split(".")[0];if(u==="AnyScaleFrontendService")s="application-autoscaling";else if(u==="AnyScaleScalingPlannerFrontendService")s="autoscaling-plans"}else if(a==null&&s.startsWith("s3-"))a=s.slice(3).replace(/^fips-|^external-1/,""),s="s3";else if(s.endsWith("-fips"))s=s.slice(0,-5);else if(a&&/-\d$/.test(s)&&!/-\d$/.test(a))[s,a]=[a,s];return[Pv[s]||s,a||""]}var ja,Pv,Nv,xg;var Rg=De(()=>{ja=new TextEncoder,Pv={appstream2:"appstream",cloudhsmv2:"cloudhsm",email:"ses",marketplace:"aws-marketplace",mobile:"AWSMobileHubService",pinpoint:"mobiletargeting",queue:"sqs","git-codecommit":"codecommit","mturk-requester-sandbox":"mturk-requester","personalize-runtime":"personalize"},Nv=new Set(["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"]);xg=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"]});function Wa(e){return new Ha({accessKeyId:e.accessKeyId,secretAccessKey:e.secretAccessKey,region:e.region||"auto",service:"s3"})}function Za(e){let t=new URL(e.endpoint).origin;return s_(e)?t:`${t}/${e.bucket}`}function Ga(e,t){return`${Za(e)}/${t.split("/").map(encodeURIComponent).join("/")}`}async function lo(e,t,r){let n=Wa(e),o=new URL(Ga(e,t));return o.searchParams.set("X-Amz-Expires",String(Math.min(Math.max(1,Math.floor(r)),xn))),(await n.sign(o.toString(),{method:"GET",aws:{signQuery:!0}})).url}var xn=604800;var wi=De(()=>{Rg();bn()});function nE(e,t){let r=e.query("SELECT value FROM meta WHERE key = ?").get(t);return r?r.value:null}function ic(e,t,r){if(r===null){e.query("DELETE FROM meta WHERE key = ?").run(t);return}e.query("INSERT INTO meta (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(t,r)}function ki(e){let t=nE(e,"edge_config");if(!t)return null;try{let r=JSON.parse(t);if(!r||typeof r.endpoint!=="string"||typeof r.token!=="string")return null;if(r.cf&&"apiToken"in r.cf)delete r.cf.apiToken,ic(e,"edge_config",JSON.stringify(r));if(!Array.isArray(r.capabilities))r.capabilities=r.cf?["inbox","room"]:["inbox"],ic(e,"edge_config",JSON.stringify(r));return r}catch{return null}}function sc(e,t){if(t?.cf&&"apiToken"in t.cf)throw Error("Cloudflare API token must not be persisted");let r=t?{...t,capabilities:t.capabilities??(t.cf?["inbox","room"]:["inbox"])}:null;ic(e,"edge_config",r?JSON.stringify(r):null)}function uo(e){return e.capabilities??(e.cf?["inbox","room"]:["inbox"])}var Tr="3";function fo(e){let t=(e||"").replace(/^\/+|\/+$/g,"");return t?`${t}/shares`:"shares"}function ih(e){let t=new Set,r=/\/blob\/([0-9a-f]{16,64})/g,n;while(n=r.exec(e))t.add(n[1].toLowerCase());return[...t]}function ch(e,t){let r=new TextEncoder().encode(JSON.stringify(t));return e.encrypt&&e.masterKey?gr(Qt(e.masterKey),r):Promise.resolve(r)}async function cc(e,t){let n=await Ut(e).get(ac(fo(e.prefix),t)).catch(()=>null);if(!n)return null;try{let o=e.encrypt&&e.masterKey?await Hr(Qt(e.masterKey),n):n;return JSON.parse(new TextDecoder().decode(o))}catch{return null}}async function iE(e,t){let r=Ut(t.config),n=fo(t.config.prefix),o={v:1,kind:t.kind,title:""},s=[];if(t.kind==="doc"){let m=nt(e,t.targetId);if(!m)throw new Z("not_found",`no such document: ${t.targetId}`);o.title=m.title,o.body=m.body??"",s=ih(o.body)}else{let m=Pt(e,t.targetId);if(!m)throw new Z("not_found",`no such database: ${t.targetId}`);o.title=m.name;let x=Ct(e,t.targetId).sort((j,Y)=>j.position-Y.position);o.properties=x.map((j)=>({id:j.id,name:j.name,type:j.type}));let D=ln(e,t.targetId);o.records=D.map((j)=>({cells:j.cells})),s=ih(JSON.stringify(D.map((j)=>j.cells)))}let a=[],u={};if(s.length>0&&!$l())throw new Z("network","no blob-bytes resolver is registered for this runtime");for(let m of s){let x=await Ll(e,m);if(!x)continue;let D=ah(n,t.slug,m);await r.put(D,await gr(t.shareKey,x),{contentType:"application/octet-stream"}),a.push(D),u[m]={url:await lo(t.config,D,t.expiresSec),ct:Bl(e,m)??"application/octet-stream"}}if(Object.keys(u).length)o.blobs=u;let _=sh(n,t.slug);return await r.put(_,await gr(t.shareKey,new TextEncoder().encode(JSON.stringify(o))),{contentType:"application/octet-stream"}),a.push(_),{manifestUrl:await lo(t.config,_,t.expiresSec),objects:a,title:o.title}}async function lh(e,t,r,n=xn){let o=await cc(t,r);if(!o)throw new Z("not_found",`no such bucket share: ${r}`);let s=Qt(o.key),a=fh(n),{manifestUrl:u,objects:_,title:m}=await iE(e,{slug:r,kind:o.kind,targetId:o.target_id,config:t,shareKey:s,expiresSec:a}),x=Date.now()+a*1000,D={...o,title:m,presign_exp:x,objects:_,content_updated_at:Date.now()};return await Ut(t).put(ac(fo(t.prefix),r),await ch(t,D),{contentType:"application/octet-stream"}),{manifestUrl:u,presignExp:x,keyB64:o.has_password?void 0:o.key,saltB64:o.salt,title:m}}async function sE(e,t){if(!e.blobs)return e;let r={};for(let[n,o]of Object.entries(e.blobs))r[n]={...o,url:await t(n)};return{...e,blobs:r}}async function uh(e,t,r=xn){let n=await cc(e,t);if(!n)throw new Z("not_found",`no such bucket share: ${t}`);let o=Ut(e),s=fo(e.prefix),a=Qt(n.key),u=fh(r),_=sh(s,t),m=await o.get(_).catch(()=>null);if(!m)throw new Z("not_found",`bucket share ${t} has no manifest`);let x=JSON.parse(new TextDecoder().decode(await Hr(a,m))),D=await sE(x,(Y)=>lo(e,ah(s,t,Y),u));await o.put(_,await gr(a,new TextEncoder().encode(JSON.stringify(D))),{contentType:"application/octet-stream"});let j=Date.now()+u*1000;return await o.put(ac(s,t),await ch(e,{...n,presign_exp:j}),{contentType:"application/octet-stream"}),{manifestUrl:await lo(e,_,u),presignExp:j,keyB64:n.has_password?void 0:n.key,saltB64:n.salt,title:n.title}}async function dh(e){let t=Ut(e),r=fo(e.prefix),o=(await t.list(`${r}/`,void 0,"/").catch(()=>[])).map((a)=>a.key.slice(`${r}/`.length).replace(/\/$/,"")).filter((a)=>a&&!a.includes("/")),s=[];for(let a of o){let u=await cc(e,a);if(u)s.push(u)}return s}function fh(e){return Math.min(Math.max(60,Math.floor(e)),xn)}var ac=(e,t)=>`${e}/${t}/meta.json`,sh=(e,t)=>`${e}/${t}/manifest.bin`,ah=(e,t,r)=>`${e}/${t}/blobs/${r}`;var ph=De(()=>{Ye();pn();qr();Cr();Lr();$n();bn();wi();Xn()});function cE(e,t){if(t)return t.replace(/\/+$/,"");return(e.query("SELECT value FROM meta WHERE key='cfg_share_viewer_url'").get()?.value||aE).replace(/\/+$/,"")}function lE(e,t,r,n){let o=`m=${encodeURIComponent(t)}&`+(r?`k=${r}`:`s=${n}`);return`${e}/#${o}`}async function _h(e,t,r,n){for(let o of Ht(e).filter((s)=>s.kind==="s3"&&s.config)){let s=JSON.parse(o.config),u=(await dh(s).catch(()=>[])).find((x)=>x.slug===t);if(!u)continue;let _=cE(e,r),m=n?.refreshContent?await lh(e,s,t):await uh(s,t);return{slug:t,kind:u.kind,permission:"view",transport:"s3",hosting:"s3",url:lE(_,m.manifestUrl,m.keyB64,m.saltB64),expiresAt:m.presignExp,source:`桶 ${o.label??o.url}`}}throw new Z("not_found",`no such object-storage share: ${t}`)}var aE="https://share.mh.tensorix.org",XD;var gh=De(()=>{oa();Ye();bt();es();vn();pn();qr();oo();wn();ph();wi();ao();XD=jr({slug:at().min(1).max(128),kind:ni(["doc","database","site"]),permission:ni(["view","edit"]),transport:Kb("server"),hosting:ni(["server","room"]),url:at().url(),expiresAt:ri().nullable(),source:at()})});globalThis.sqlite3Worker1Promiser=function e(t=e.defaultConfig){if(arguments.length===1&&typeof arguments[0]==="function"){let D=t;t=Object.assign(Object.create(null),e.defaultConfig),t.onready=D}else t=Object.assign(Object.create(null),e.defaultConfig,t);let r=Object.create(null),n=function(){},o=t.onerror||n,s=t.debug||n,a=t.generateMessageId?void 0:Object.create(null),u=t.generateMessageId||function(D){return D.type+"#"+(a[D.type]=(a[D.type]||0)+1)},_=(...D)=>{throw Error(D.join(" "))};if(!t.worker)t.worker=e.defaultConfig.worker;if(typeof t.worker==="function")t.worker=t.worker();let m,x;return t.worker.onmessage=function(D){D=D.data,s("worker1.onmessage",D);let j=r[D.messageId];if(!j){if(D&&D.type==="sqlite3-api"&&D.result==="worker1-ready"){if(t.onready)t.onready(x);return}if(j=r[D.type],j&&j.onrow){j.onrow(D);return}if(t.onunhandled)t.onunhandled(arguments[0]);else o("sqlite3Worker1Promiser() unhandled worker message:",D);return}switch(delete r[D.messageId],D.type){case"error":j.reject(D);return;case"open":if(!m)m=D.dbId;break;case"close":if(D.dbId===m)m=void 0;break;default:break}try{j.resolve(D)}catch(Y){j.reject(Y)}},x=function(){let D;if(arguments.length===1)D=arguments[0];else if(arguments.length===2)D=Object.create(null),D.type=arguments[0],D.args=arguments[1],D.dbId=D.args.dbId;else _("Invalid arguments for sqlite3Worker1Promiser()-created factory.");if(!D.dbId&&D.type!=="open")D.dbId=m;D.messageId=u(D),D.departureTime=performance.now();let j=Object.create(null);j.message=D;let Y;if(D.type==="exec"&&D.args){if(typeof D.args.callback==="function")Y=D.messageId+":row",j.onrow=D.args.callback,D.args.callback=Y,r[Y]=j;else if(typeof D.args.callback==="string")_("exec callback may not be a string when using the Promise interface.")}let _e=new Promise(function(de,ge){j.resolve=de,j.reject=ge,r[D.messageId]=j,s("Posting",D.type,"message to Worker dbId="+(m||"default")+":",D),t.worker.postMessage(D)});if(Y)_e=_e.finally(()=>delete r[Y]);return _e}};globalThis.sqlite3Worker1Promiser.defaultConfig={worker:function(){return new Worker(new URL("sqlite3-worker1.mjs",import.meta.url),{type:"module"})},onerror:(...e)=>console.error("sqlite3Worker1Promiser():",...e)};globalThis.sqlite3Worker1Promiser.v2=function e(t=e.defaultConfig){let r;if(typeof t=="function")r=t,t={};else if(typeof t?.onready==="function")r=t.onready,delete t.onready;let n=Object.create(null);t=Object.assign(t||Object.create(null),{onready:async function(s){try{if(r)await r(s);n.resolve(s)}catch(a){n.reject(a)}}});let o=new Promise(function(s,a){n.resolve=s,n.reject=a});try{this.original(t)}catch(s){n.reject(s)}return o}.bind({original:sqlite3Worker1Promiser});globalThis.sqlite3Worker1Promiser.v2.defaultConfig=globalThis.sqlite3Worker1Promiser.defaultConfig;var RE=sqlite3Worker1Promiser.v2;delete globalThis.sqlite3Worker1Promiser;async function $i(e={}){var t,r=e,n=!!globalThis.window,o=!!globalThis.WorkerGlobalScope;globalThis.process?.versions?.node&&globalThis.process?.type;var s="./this.program",a=import.meta.url,u="";function _(i){if(r.locateFile)return r.locateFile(i,u);return u+i}var m,x;if(n||o){try{u=new URL(".",a).href}catch{}if(o)x=(i)=>{var l=new XMLHttpRequest;return l.open("GET",i,!1),l.responseType="arraybuffer",l.send(null),new Uint8Array(l.response)};m=async(i)=>{var l=await fetch(i,{credentials:"same-origin"});if(l.ok)return l.arrayBuffer();throw Error(l.status+" : "+l.url)}}var D=console.log.bind(console),j=console.error.bind(console),Y,_e=!1,de,ge,Le=!1;function Ze(){var i=ur.buffer;Ft=new Int8Array(i),Dn=new Int16Array(i),Ar=new Uint8Array(i),Ph=new Uint16Array(i),Je=new Int32Array(i),et=new Uint32Array(i),Oh=new Float32Array(i),Ih=new Float64Array(i),St=new BigInt64Array(i),Nh=new BigUint64Array(i)}function $e(){if(r.wasmMemory)ur=r.wasmMemory;else{var i=r.INITIAL_MEMORY||8388608;ur=new WebAssembly.Memory({initial:i/65536,maximum:32768})}Ze()}function Ue(){if(r.preRun){if(typeof r.preRun=="function")r.preRun=[r.preRun];while(r.preRun.length)qh(r.preRun.shift())}pc(gc)}function tt(){if(Le=!0,!r.noFSInit&&!y.initialized)y.init();yr.init(),tn.__wasm_call_ctors(),y.ignorePermissions=!1}function Rr(){if(r.postRun){if(typeof r.postRun=="function")r.postRun=[r.postRun];while(r.postRun.length)Ch(r.postRun.shift())}pc(_c)}function $t(i){r.onAbort?.(i),i=`Aborted(${i})`,j(i),_e=!0,i+=". Build with -sASSERTIONS for more info.";var l=new WebAssembly.RuntimeError(i);throw ge?.(l),l}var An;function Sh(){if(r.locateFile)return _("sqlite3.wasm");return new URL("sqlite3.wasm",import.meta.url).href}function xh(i){if(i==An&&Y)return new Uint8Array(Y);if(x)return x(i);throw"both async and sync fetching of the wasm failed"}async function Th(i){if(!Y)try{var l=await m(i);return new Uint8Array(l)}catch{}return xh(i)}async function kh(i,l){try{var h=await Th(i);return await WebAssembly.instantiate(h,l)}catch(f){j(`failed to asynchronously prepare wasm: ${f}`),$t(f)}}async function Rh(i,l,h){if(!i)try{var f=fetch(l,{credentials:"same-origin"});return await WebAssembly.instantiateStreaming(f,h)}catch(c){j(`wasm streaming compile failed: ${c}`),j("falling back to ArrayBuffer instantiation")}return kh(l,h)}function Ah(){return{env:Oc,wasi_snapshot_preview1:Oc}}async function Dh(){function i(f,c){return tn=f.exports,zm(tn),tn}function l(f){return i(f.instance)}var h=Ah();if(r.instantiateWasm)return new Promise((f,c)=>{r.instantiateWasm(h,(d,p)=>{f(i(d,p))})});return An??=Sh(),l(await Rh(Y,An,h))}var Dn,Je,St,Ft,Oh,Ih,Ph,et,Nh,Ar,pc=(i)=>{while(i.length>0)i.shift()(r)},_c=[],Ch=(i)=>_c.push(i),gc=[],qh=(i)=>gc.push(i),ur,Xe={isAbs:(i)=>i.charAt(0)==="/",splitPath:(i)=>/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/.exec(i).slice(1),normalizeArray:(i,l)=>{var h=0;for(var f=i.length-1;f>=0;f--){var c=i[f];if(c===".")i.splice(f,1);else if(c==="..")i.splice(f,1),h++;else if(h)i.splice(f,1),h--}if(l)for(;h;h--)i.unshift("..");return i},normalize:(i)=>{var l=Xe.isAbs(i),h=i.slice(-1)==="/";if(i=Xe.normalizeArray(i.split("/").filter((f)=>!!f),!l).join("/"),!i&&!l)i=".";if(i&&h)i+="/";return(l?"/":"")+i},dirname:(i)=>{var l=Xe.splitPath(i),h=l[0],f=l[1];if(!h&&!f)return".";if(f)f=f.slice(0,-1);return h+f},basename:(i)=>i&&i.match(/([^\/]+|\/)\/*$/)[1],join:(...i)=>Xe.normalize(i.join("/")),join2:(i,l)=>Xe.normalize(i+"/"+l)},Lh=()=>(i)=>(crypto.getRandomValues(i),0),hc=(i)=>(hc=Lh())(i),Qr={resolve:(...i)=>{var l="",h=!1;for(var f=i.length-1;f>=-1&&!h;f--){var c=f>=0?i[f]:y.cwd();if(typeof c!="string")throw TypeError("Arguments to path.resolve must be strings");else if(!c)return"";l=c+"/"+l,h=Xe.isAbs(c)}return l=Xe.normalizeArray(l.split("/").filter((d)=>!!d),!h).join("/"),(h?"/":"")+l||"."},relative:(i,l)=>{i=Qr.resolve(i).slice(1),l=Qr.resolve(l).slice(1);function h(I){var V=0;for(;V<I.length;V++)if(I[V]!=="")break;var M=I.length-1;for(;M>=0;M--)if(I[M]!=="")break;if(V>M)return[];return I.slice(V,M-V+1)}var f=h(i.split("/")),c=h(l.split("/")),d=Math.min(f.length,c.length),p=d;for(var E=0;E<d;E++)if(f[E]!==c[E]){p=E;break}var b=[];for(var E=p;E<f.length;E++)b.push("..");return b=b.concat(c.slice(p)),b.join("/")}},mc=new TextDecoder,yc=(i,l,h,f)=>{var c=l+h;if(f)return c;while(i[l]&&!(l>=c))++l;return l},On=(i,l=0,h,f)=>{var c=yc(i,l,h,f);return mc.decode(i.buffer?i.subarray(l,c):new Uint8Array(i.slice(l,c)))},Pi=[],_o=(i)=>{var l=0;for(var h=0;h<i.length;++h){var f=i.charCodeAt(h);if(f<=127)l++;else if(f<=2047)l+=2;else if(f>=55296&&f<=57343)l+=4,++h;else l+=3}return l},bc=(i,l,h,f)=>{if(!(f>0))return 0;var c=h,d=h+f-1;for(var p=0;p<i.length;++p){var E=i.codePointAt(p);if(E<=127){if(h>=d)break;l[h++]=E}else if(E<=2047){if(h+1>=d)break;l[h++]=192|E>>6,l[h++]=128|E&63}else if(E<=65535){if(h+2>=d)break;l[h++]=224|E>>12,l[h++]=128|E>>6&63,l[h++]=128|E&63}else{if(h+3>=d)break;l[h++]=240|E>>18,l[h++]=128|E>>12&63,l[h++]=128|E>>6&63,l[h++]=128|E&63,p++}}return l[h]=0,h-c},Ni=(i,l,h)=>{var f=h>0?h:_o(i)+1,c=Array(f),d=bc(i,c,0,c.length);if(l)c.length=d;return c},$h=()=>{if(!Pi.length){var i=null;if(globalThis.window?.prompt){if(i=window.prompt("Input: "),i!==null)i+=`
537
+ `}if(!i)return null;Pi=Ni(i,!0)}return Pi.shift()},yr={ttys:[],init(){},shutdown(){},register(i,l){yr.ttys[i]={input:[],output:[],ops:l},y.registerDevice(i,yr.stream_ops)},stream_ops:{open(i){var l=yr.ttys[i.node.rdev];if(!l)throw new y.ErrnoError(43);i.tty=l,i.seekable=!1},close(i){i.tty.ops.fsync(i.tty)},fsync(i){i.tty.ops.fsync(i.tty)},read(i,l,h,f,c){if(!i.tty||!i.tty.ops.get_char)throw new y.ErrnoError(60);var d=0;for(var p=0;p<f;p++){var E;try{E=i.tty.ops.get_char(i.tty)}catch(b){throw new y.ErrnoError(29)}if(E===void 0&&d===0)throw new y.ErrnoError(6);if(E===null||E===void 0)break;d++,l[h+p]=E}if(d)i.node.atime=Date.now();return d},write(i,l,h,f,c){if(!i.tty||!i.tty.ops.put_char)throw new y.ErrnoError(60);try{for(var d=0;d<f;d++)i.tty.ops.put_char(i.tty,l[h+d])}catch(p){throw new y.ErrnoError(29)}if(f)i.node.mtime=i.node.ctime=Date.now();return d}},default_tty_ops:{get_char(i){return $h()},put_char(i,l){if(l===null||l===10)D(On(i.output)),i.output=[];else if(l!=0)i.output.push(l)},fsync(i){if(i.output?.length>0)D(On(i.output)),i.output=[]},ioctl_tcgets(i){return{c_iflag:25856,c_oflag:5,c_cflag:191,c_lflag:35387,c_cc:[3,28,127,21,4,0,1,0,17,19,26,0,18,15,23,22,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]}},ioctl_tcsets(i,l,h){return 0},ioctl_tiocgwinsz(i){return[24,80]}},default_tty1_ops:{put_char(i,l){if(l===null||l===10)j(On(i.output)),i.output=[];else if(l!=0)i.output.push(l)},fsync(i){if(i.output?.length>0)j(On(i.output)),i.output=[]}}},Fh=(i,l)=>Ar.fill(0,i,i+l),wc=(i,l)=>Math.ceil(i/l)*l,vc=(i)=>{i=wc(i,65536);var l=Dc(65536,i);if(l)Fh(l,i);return l},Fe={ops_table:null,mount(i){return Fe.createNode(null,"/",16895,0)},createNode(i,l,h,f){if(y.isBlkdev(h)||y.isFIFO(h))throw new y.ErrnoError(63);Fe.ops_table||={dir:{node:{getattr:Fe.node_ops.getattr,setattr:Fe.node_ops.setattr,lookup:Fe.node_ops.lookup,mknod:Fe.node_ops.mknod,rename:Fe.node_ops.rename,unlink:Fe.node_ops.unlink,rmdir:Fe.node_ops.rmdir,readdir:Fe.node_ops.readdir,symlink:Fe.node_ops.symlink},stream:{llseek:Fe.stream_ops.llseek}},file:{node:{getattr:Fe.node_ops.getattr,setattr:Fe.node_ops.setattr},stream:{llseek:Fe.stream_ops.llseek,read:Fe.stream_ops.read,write:Fe.stream_ops.write,mmap:Fe.stream_ops.mmap,msync:Fe.stream_ops.msync}},link:{node:{getattr:Fe.node_ops.getattr,setattr:Fe.node_ops.setattr,readlink:Fe.node_ops.readlink},stream:{}},chrdev:{node:{getattr:Fe.node_ops.getattr,setattr:Fe.node_ops.setattr},stream:y.chrdev_stream_ops}};var c=y.createNode(i,l,h,f);if(y.isDir(c.mode))c.node_ops=Fe.ops_table.dir.node,c.stream_ops=Fe.ops_table.dir.stream,c.contents={};else if(y.isFile(c.mode))c.node_ops=Fe.ops_table.file.node,c.stream_ops=Fe.ops_table.file.stream,c.usedBytes=0,c.contents=Fe.emptyFileContents??=new Uint8Array(0);else if(y.isLink(c.mode))c.node_ops=Fe.ops_table.link.node,c.stream_ops=Fe.ops_table.link.stream;else if(y.isChrdev(c.mode))c.node_ops=Fe.ops_table.chrdev.node,c.stream_ops=Fe.ops_table.chrdev.stream;if(c.atime=c.mtime=c.ctime=Date.now(),i)i.contents[l]=c,i.atime=i.mtime=i.ctime=c.atime;return c},getFileDataAsTypedArray(i){return i.contents.subarray(0,i.usedBytes)},expandFileStorage(i,l){var h=i.contents.length;if(h>=l)return;if(l=Math.max(l,h*(h<1048576?2:1.125)>>>0),h)l=Math.max(l,256);var f=Fe.getFileDataAsTypedArray(i);i.contents=new Uint8Array(l),i.contents.set(f)},resizeFileStorage(i,l){if(i.usedBytes==l)return;var h=i.contents;i.contents=new Uint8Array(l),i.contents.set(h.subarray(0,Math.min(l,i.usedBytes))),i.usedBytes=l},node_ops:{getattr(i){var l={};if(l.dev=y.isChrdev(i.mode)?i.id:1,l.ino=i.id,l.mode=i.mode,l.nlink=1,l.uid=0,l.gid=0,l.rdev=i.rdev,y.isDir(i.mode))l.size=4096;else if(y.isFile(i.mode))l.size=i.usedBytes;else if(y.isLink(i.mode))l.size=i.link.length;else l.size=0;return l.atime=new Date(i.atime),l.mtime=new Date(i.mtime),l.ctime=new Date(i.ctime),l.blksize=4096,l.blocks=Math.ceil(l.size/l.blksize),l},setattr(i,l){for(let h of["mode","atime","mtime","ctime"])if(l[h]!=null)i[h]=l[h];if(l.size!==void 0)Fe.resizeFileStorage(i,l.size)},lookup(i,l){if(!Fe.doesNotExistError)Fe.doesNotExistError=new y.ErrnoError(44),Fe.doesNotExistError.stack="<generic error, no stack>";throw Fe.doesNotExistError},mknod(i,l,h,f){return Fe.createNode(i,l,h,f)},rename(i,l,h){var f;try{f=y.lookupNode(l,h)}catch(d){}if(f){if(y.isDir(i.mode))for(var c in f.contents)throw new y.ErrnoError(55);y.hashRemoveNode(f)}delete i.parent.contents[i.name],l.contents[h]=i,i.name=h,l.ctime=l.mtime=i.parent.ctime=i.parent.mtime=Date.now()},unlink(i,l){delete i.contents[l],i.ctime=i.mtime=Date.now()},rmdir(i,l){for(var h in y.lookupNode(i,l).contents)throw new y.ErrnoError(55);delete i.contents[l],i.ctime=i.mtime=Date.now()},readdir(i){return[".","..",...Object.keys(i.contents)]},symlink(i,l,h){var f=Fe.createNode(i,l,41471,0);return f.link=h,f},readlink(i){if(!y.isLink(i.mode))throw new y.ErrnoError(28);return i.link}},stream_ops:{read(i,l,h,f,c){var d=i.node.contents;if(c>=i.node.usedBytes)return 0;var p=Math.min(i.node.usedBytes-c,f);return l.set(d.subarray(c,c+p),h),p},write(i,l,h,f,c,d){if(l.buffer===Ft.buffer)d=!1;if(!f)return 0;var p=i.node;if(p.mtime=p.ctime=Date.now(),d)p.contents=l.subarray(h,h+f),p.usedBytes=f;else if(p.usedBytes===0&&c===0)p.contents=l.slice(h,h+f),p.usedBytes=f;else Fe.expandFileStorage(p,c+f),p.contents.set(l.subarray(h,h+f),c),p.usedBytes=Math.max(p.usedBytes,c+f);return f},llseek(i,l,h){var f=l;if(h===1)f+=i.position;else if(h===2){if(y.isFile(i.node.mode))f+=i.node.usedBytes}if(f<0)throw new y.ErrnoError(28);return f},mmap(i,l,h,f,c){if(!y.isFile(i.node.mode))throw new y.ErrnoError(43);var d,p,E=i.node.contents;if(!(c&2)&&E.buffer===Ft.buffer)p=!1,d=E.byteOffset;else{if(p=!0,d=vc(l),!d)throw new y.ErrnoError(48);if(E){if(h>0||h+l<E.length)if(E.subarray)E=E.subarray(h,h+l);else E=Array.prototype.slice.call(E,h,h+l);Ft.set(E,d)}}return{ptr:d,allocated:p}},msync(i,l,h,f,c){return Fe.stream_ops.write(i,l,0,f,h,!1),0}}},zh=(i)=>{if(typeof i!="string")return i;var l={r:0,"r+":2,w:577,"w+":578,a:1089,"a+":1090}[i];if(typeof l>"u")throw Error(`Unknown file open mode: ${i}`);return l},Ec=(i)=>{if(typeof i=="string")i=Ni(i,!0);if(!i.subarray)i=new Uint8Array(i);return i},Ci=(i,l)=>{var h=0;if(i)h|=365;if(l)h|=146;return h},Mh=async(i)=>{var l=await m(i);return new Uint8Array(l)},Bh=(...i)=>y.createDataFile(...i),Uh=(i)=>i,Dr=0,In=null,jh=(i)=>{if(Dr--,r.monitorRunDependencies?.(Dr),Dr==0){if(In){var l=In;In=null,l()}}},Hh=(i)=>{Dr++,r.monitorRunDependencies?.(Dr)},Sc=[],Wh=async(i,l)=>{if(typeof Browser<"u")Browser.init();for(var h of Sc)if(h.canHandle(l))return h.handle(i,l);return i},xc=async(i,l,h,f,c,d,p,E)=>{var b=l?Qr.resolve(Xe.join2(i,l)):i,I=Uh(`cp ${b}`);Hh(I);try{var V=h;if(typeof h=="string")V=await Mh(h);if(V=await Wh(V,b),E?.(),!d)Bh(i,l,V,f,c,p)}finally{jh(I)}},Zh=(i,l,h,f,c,d,p,E,b,I)=>{xc(i,l,h,f,c,E,b,I).then(d).catch(p)},y={root:null,mounts:[],devices:{},streams:[],nextInode:1,nameTable:null,currentPath:"/",initialized:!1,ignorePermissions:!0,filesystems:null,syncFSRequests:0,ErrnoError:class{name="ErrnoError";constructor(i){this.errno=i}},FSStream:class{shared={};get object(){return this.node}set object(i){this.node=i}get isRead(){return(this.flags&2097155)!==1}get isWrite(){return(this.flags&2097155)!==0}get isAppend(){return this.flags&1024}get flags(){return this.shared.flags}set flags(i){this.shared.flags=i}get position(){return this.shared.position}set position(i){this.shared.position=i}},FSNode:class{node_ops={};stream_ops={};readMode=365;writeMode=146;mounted=null;constructor(i,l,h,f){if(!i)i=this;this.parent=i,this.mount=i.mount,this.id=y.nextInode++,this.name=l,this.mode=h,this.rdev=f,this.atime=this.mtime=this.ctime=Date.now()}get read(){return(this.mode&this.readMode)===this.readMode}set read(i){i?this.mode|=this.readMode:this.mode&=~this.readMode}get write(){return(this.mode&this.writeMode)===this.writeMode}set write(i){i?this.mode|=this.writeMode:this.mode&=~this.writeMode}get isFolder(){return y.isDir(this.mode)}get isDevice(){return y.isChrdev(this.mode)}},lookupPath(i,l={}){if(!i)throw new y.ErrnoError(44);if(l.follow_mount??=!0,!Xe.isAbs(i))i=y.cwd()+"/"+i;e:for(var h=0;h<40;h++){var f=i.split("/").filter((I)=>!!I),c=y.root,d="/";for(var p=0;p<f.length;p++){var E=p===f.length-1;if(E&&l.parent)break;if(f[p]===".")continue;if(f[p]===".."){if(d=Xe.dirname(d),y.isRoot(c)){i=d+"/"+f.slice(p+1).join("/"),h--;continue e}else c=c.parent;continue}d=Xe.join2(d,f[p]);try{c=y.lookupNode(c,f[p])}catch(I){if(I?.errno===44&&E&&l.noent_okay)return{path:d};throw I}if(y.isMountpoint(c)&&(!E||l.follow_mount))c=c.mounted.root;if(y.isLink(c.mode)&&(!E||l.follow)){if(!c.node_ops.readlink)throw new y.ErrnoError(52);var b=c.node_ops.readlink(c);if(!Xe.isAbs(b))b=Xe.dirname(d)+"/"+b;i=b+"/"+f.slice(p+1).join("/");continue e}}return{path:d,node:c}}throw new y.ErrnoError(32)},getPath(i){var l;while(!0){if(y.isRoot(i)){var h=i.mount.mountpoint;if(!l)return h;return h[h.length-1]!=="/"?`${h}/${l}`:h+l}l=l?`${i.name}/${l}`:i.name,i=i.parent}},hashName(i,l){var h=0;for(var f=0;f<l.length;f++)h=(h<<5)-h+l.charCodeAt(f)|0;return(i+h>>>0)%y.nameTable.length},hashAddNode(i){var l=y.hashName(i.parent.id,i.name);i.name_next=y.nameTable[l],y.nameTable[l]=i},hashRemoveNode(i){var l=y.hashName(i.parent.id,i.name);if(y.nameTable[l]===i)y.nameTable[l]=i.name_next;else{var h=y.nameTable[l];while(h){if(h.name_next===i){h.name_next=i.name_next;break}h=h.name_next}}},lookupNode(i,l){var h=y.mayLookup(i);if(h)throw new y.ErrnoError(h);var f=y.hashName(i.id,l);for(var c=y.nameTable[f];c;c=c.name_next){var d=c.name;if(c.parent.id===i.id&&d===l)return c}return y.lookup(i,l)},createNode(i,l,h,f){var c=new y.FSNode(i,l,h,f);return y.hashAddNode(c),c},destroyNode(i){y.hashRemoveNode(i)},isRoot(i){return i===i.parent},isMountpoint(i){return!!i.mounted},isFile(i){return(i&61440)===32768},isDir(i){return(i&61440)===16384},isLink(i){return(i&61440)===40960},isChrdev(i){return(i&61440)===8192},isBlkdev(i){return(i&61440)===24576},isFIFO(i){return(i&61440)===4096},isSocket(i){return(i&49152)===49152},flagsToPermissionString(i){var l=["r","w","rw"][i&3];if(i&512)l+="w";return l},nodePermissions(i,l){if(y.ignorePermissions)return 0;if(l.includes("r")&&!(i.mode&292))return 2;if(l.includes("w")&&!(i.mode&146))return 2;if(l.includes("x")&&!(i.mode&73))return 2;return 0},mayLookup(i){if(!y.isDir(i.mode))return 54;var l=y.nodePermissions(i,"x");if(l)return l;if(!i.node_ops.lookup)return 2;return 0},mayCreate(i,l){if(!y.isDir(i.mode))return 54;try{return y.lookupNode(i,l),20}catch(h){}return y.nodePermissions(i,"wx")},mayDelete(i,l,h){var f;try{f=y.lookupNode(i,l)}catch(d){return d.errno}var c=y.nodePermissions(i,"wx");if(c)return c;if(h){if(!y.isDir(f.mode))return 54;if(y.isRoot(f)||y.getPath(f)===y.cwd())return 10}else if(y.isDir(f.mode))return 31;return 0},mayOpen(i,l){if(!i)return 44;if(y.isLink(i.mode))return 32;var h=y.flagsToPermissionString(l);if(y.isDir(i.mode)){if(h!=="r"||l&576)return 31}return y.nodePermissions(i,h)},checkOpExists(i,l){if(!i)throw new y.ErrnoError(l);return i},MAX_OPEN_FDS:4096,nextfd(){for(var i=0;i<=y.MAX_OPEN_FDS;i++)if(!y.streams[i])return i;throw new y.ErrnoError(33)},getStreamChecked(i){var l=y.getStream(i);if(!l)throw new y.ErrnoError(8);return l},getStream:(i)=>y.streams[i],createStream(i,l=-1){if(i=Object.assign(new y.FSStream,i),l==-1)l=y.nextfd();return i.fd=l,y.streams[l]=i,i},closeStream(i){y.streams[i]=null},dupStream(i,l=-1){var h=y.createStream(i,l);return h.stream_ops?.dup?.(h),h},doSetAttr(i,l,h){var f=i?.stream_ops.setattr,c=f?i:l;f??=l.node_ops.setattr,y.checkOpExists(f,63),f(c,h)},chrdev_stream_ops:{open(i){i.stream_ops=y.getDevice(i.node.rdev).stream_ops,i.stream_ops.open?.(i)},llseek(){throw new y.ErrnoError(70)}},major:(i)=>i>>8,minor:(i)=>i&255,makedev:(i,l)=>i<<8|l,registerDevice(i,l){y.devices[i]={stream_ops:l}},getDevice:(i)=>y.devices[i],getMounts(i){var l=[],h=[i];while(h.length){var f=h.pop();l.push(f),h.push(...f.mounts)}return l},syncfs(i,l){if(typeof i=="function")l=i,i=!1;if(y.syncFSRequests++,y.syncFSRequests>1)j(`warning: ${y.syncFSRequests} FS.syncfs operations in flight at once, probably just doing extra work`);var h=y.getMounts(y.root.mount),f=0;function c(E){return y.syncFSRequests--,l(E)}function d(E){if(E){if(!d.errored)return d.errored=!0,c(E);return}if(++f>=h.length)c(null)}for(var p of h)if(p.type.syncfs)p.type.syncfs(p,i,d);else d(null)},mount(i,l,h){var f=h==="/",c=!h,d;if(f&&y.root)throw new y.ErrnoError(10);else if(!f&&!c){var p=y.lookupPath(h,{follow_mount:!1});if(h=p.path,d=p.node,y.isMountpoint(d))throw new y.ErrnoError(10);if(!y.isDir(d.mode))throw new y.ErrnoError(54)}var E={type:i,opts:l,mountpoint:h,mounts:[]},b=i.mount(E);if(b.mount=E,E.root=b,f)y.root=b;else if(d){if(d.mounted=E,d.mount)d.mount.mounts.push(E)}return b},unmount(i){var l=y.lookupPath(i,{follow_mount:!1});if(!y.isMountpoint(l.node))throw new y.ErrnoError(28);var h=l.node,f=h.mounted,c=y.getMounts(f);for(var[d,p]of Object.entries(y.nameTable))while(p){var E=p.name_next;if(c.includes(p.mount))y.destroyNode(p);p=E}h.mounted=null;var b=h.mount.mounts.indexOf(f);h.mount.mounts.splice(b,1)},lookup(i,l){return i.node_ops.lookup(i,l)},mknod(i,l,h){var f=y.lookupPath(i,{parent:!0}).node,c=Xe.basename(i);if(!c)throw new y.ErrnoError(28);if(c==="."||c==="..")throw new y.ErrnoError(20);var d=y.mayCreate(f,c);if(d)throw new y.ErrnoError(d);if(!f.node_ops.mknod)throw new y.ErrnoError(63);return f.node_ops.mknod(f,c,l,h)},statfs(i){return y.statfsNode(y.lookupPath(i,{follow:!0}).node)},statfsStream(i){return y.statfsNode(i.node)},statfsNode(i){var l={bsize:4096,frsize:4096,blocks:1e6,bfree:500000,bavail:500000,files:y.nextInode,ffree:y.nextInode-1,fsid:42,flags:2,namelen:255};if(i.node_ops.statfs)Object.assign(l,i.node_ops.statfs(i.mount.opts.root));return l},create(i,l=438){return l&=4095,l|=32768,y.mknod(i,l,0)},mkdir(i,l=511){return l&=1023,l|=16384,y.mknod(i,l,0)},mkdirTree(i,l){var h=i.split("/"),f="";for(var c of h){if(!c)continue;if(f||Xe.isAbs(i))f+="/";f+=c;try{y.mkdir(f,l)}catch(d){if(d.errno!=20)throw d}}},mkdev(i,l,h){if(typeof h>"u")h=l,l=438;return l|=8192,y.mknod(i,l,h)},symlink(i,l){if(!Qr.resolve(i))throw new y.ErrnoError(44);var h=y.lookupPath(l,{parent:!0}).node;if(!h)throw new y.ErrnoError(44);var f=Xe.basename(l),c=y.mayCreate(h,f);if(c)throw new y.ErrnoError(c);if(!h.node_ops.symlink)throw new y.ErrnoError(63);return h.node_ops.symlink(h,f,i)},rename(i,l){var h=Xe.dirname(i),f=Xe.dirname(l),c=Xe.basename(i),d=Xe.basename(l),p=y.lookupPath(i,{parent:!0}),E=p.node,b;if(p=y.lookupPath(l,{parent:!0}),b=p.node,!E||!b)throw new y.ErrnoError(44);if(E.mount!==b.mount)throw new y.ErrnoError(75);var I=y.lookupNode(E,c),V=Qr.relative(i,f);if(V.charAt(0)!==".")throw new y.ErrnoError(28);if(V=Qr.relative(l,h),V.charAt(0)!==".")throw new y.ErrnoError(55);var M;try{M=y.lookupNode(b,d)}catch(H){}if(I===M)return;var C=y.isDir(I.mode),q=y.mayDelete(E,c,C);if(q)throw new y.ErrnoError(q);if(q=M?y.mayDelete(b,d,C):y.mayCreate(b,d),q)throw new y.ErrnoError(q);if(!E.node_ops.rename)throw new y.ErrnoError(63);if(y.isMountpoint(I)||M&&y.isMountpoint(M))throw new y.ErrnoError(10);if(b!==E){if(q=y.nodePermissions(E,"w"),q)throw new y.ErrnoError(q)}y.hashRemoveNode(I);try{E.node_ops.rename(I,b,d),I.parent=b}catch(H){throw H}finally{y.hashAddNode(I)}},rmdir(i){var l=y.lookupPath(i,{parent:!0}).node,h=Xe.basename(i),f=y.lookupNode(l,h),c=y.mayDelete(l,h,!0);if(c)throw new y.ErrnoError(c);if(!l.node_ops.rmdir)throw new y.ErrnoError(63);if(y.isMountpoint(f))throw new y.ErrnoError(10);l.node_ops.rmdir(l,h),y.destroyNode(f)},readdir(i){var l=y.lookupPath(i,{follow:!0}).node;return y.checkOpExists(l.node_ops.readdir,54)(l)},unlink(i){var l=y.lookupPath(i,{parent:!0}).node;if(!l)throw new y.ErrnoError(44);var h=Xe.basename(i),f=y.lookupNode(l,h),c=y.mayDelete(l,h,!1);if(c)throw new y.ErrnoError(c);if(!l.node_ops.unlink)throw new y.ErrnoError(63);if(y.isMountpoint(f))throw new y.ErrnoError(10);l.node_ops.unlink(l,h),y.destroyNode(f)},readlink(i){var l=y.lookupPath(i).node;if(!l)throw new y.ErrnoError(44);if(!l.node_ops.readlink)throw new y.ErrnoError(28);return l.node_ops.readlink(l)},stat(i,l){var h=y.lookupPath(i,{follow:!l}).node;return y.checkOpExists(h.node_ops.getattr,63)(h)},fstat(i){var l=y.getStreamChecked(i),h=l.node,f=l.stream_ops.getattr,c=f?l:h;return f??=h.node_ops.getattr,y.checkOpExists(f,63),f(c)},lstat(i){return y.stat(i,!0)},doChmod(i,l,h,f){y.doSetAttr(i,l,{mode:h&4095|l.mode&-4096,ctime:Date.now(),dontFollow:f})},chmod(i,l,h){var f;if(typeof i=="string")f=y.lookupPath(i,{follow:!h}).node;else f=i;y.doChmod(null,f,l,h)},lchmod(i,l){y.chmod(i,l,!0)},fchmod(i,l){var h=y.getStreamChecked(i);y.doChmod(h,h.node,l,!1)},doChown(i,l,h){y.doSetAttr(i,l,{timestamp:Date.now(),dontFollow:h})},chown(i,l,h,f){var c;if(typeof i=="string")c=y.lookupPath(i,{follow:!f}).node;else c=i;y.doChown(null,c,f)},lchown(i,l,h){y.chown(i,l,h,!0)},fchown(i,l,h){var f=y.getStreamChecked(i);y.doChown(f,f.node,!1)},doTruncate(i,l,h){if(y.isDir(l.mode))throw new y.ErrnoError(31);if(!y.isFile(l.mode))throw new y.ErrnoError(28);var f=y.nodePermissions(l,"w");if(f)throw new y.ErrnoError(f);y.doSetAttr(i,l,{size:h,timestamp:Date.now()})},truncate(i,l){if(l<0)throw new y.ErrnoError(28);var h;if(typeof i=="string")h=y.lookupPath(i,{follow:!0}).node;else h=i;y.doTruncate(null,h,l)},ftruncate(i,l){var h=y.getStreamChecked(i);if(l<0||(h.flags&2097155)===0)throw new y.ErrnoError(28);y.doTruncate(h,h.node,l)},utime(i,l,h){var f=y.lookupPath(i,{follow:!0}).node;y.checkOpExists(f.node_ops.setattr,63)(f,{atime:l,mtime:h})},open(i,l,h=438){if(i==="")throw new y.ErrnoError(44);if(l=zh(l),l&64)h=h&4095|32768;else h=0;var f,c;if(typeof i=="object")f=i;else{c=i.endsWith("/");var d=y.lookupPath(i,{follow:!(l&131072),noent_okay:!0});f=d.node,i=d.path}var p=!1;if(l&64)if(f){if(l&128)throw new y.ErrnoError(20)}else if(c)throw new y.ErrnoError(31);else f=y.mknod(i,h|511,0),p=!0;if(!f)throw new y.ErrnoError(44);if(y.isChrdev(f.mode))l&=-513;if(l&65536&&!y.isDir(f.mode))throw new y.ErrnoError(54);if(!p){var E=y.mayOpen(f,l);if(E)throw new y.ErrnoError(E)}if(l&512&&!p)y.truncate(f,0);l&=-131713;var b=y.createStream({node:f,path:y.getPath(f),flags:l,seekable:!0,position:0,stream_ops:f.stream_ops,ungotten:[],error:!1});if(b.stream_ops.open)b.stream_ops.open(b);if(p)y.chmod(f,h&511);return b},close(i){if(y.isClosed(i))throw new y.ErrnoError(8);if(i.getdents)i.getdents=null;try{if(i.stream_ops.close)i.stream_ops.close(i)}catch(l){throw l}finally{y.closeStream(i.fd)}i.fd=null},isClosed(i){return i.fd===null},llseek(i,l,h){if(y.isClosed(i))throw new y.ErrnoError(8);if(!i.seekable||!i.stream_ops.llseek)throw new y.ErrnoError(70);if(h!=0&&h!=1&&h!=2)throw new y.ErrnoError(28);return i.position=i.stream_ops.llseek(i,l,h),i.ungotten=[],i.position},read(i,l,h,f,c){if(f<0||c<0)throw new y.ErrnoError(28);if(y.isClosed(i))throw new y.ErrnoError(8);if((i.flags&2097155)===1)throw new y.ErrnoError(8);if(y.isDir(i.node.mode))throw new y.ErrnoError(31);if(!i.stream_ops.read)throw new y.ErrnoError(28);var d=typeof c<"u";if(!d)c=i.position;else if(!i.seekable)throw new y.ErrnoError(70);var p=i.stream_ops.read(i,l,h,f,c);if(!d)i.position+=p;return p},write(i,l,h,f,c,d){if(f<0||c<0)throw new y.ErrnoError(28);if(y.isClosed(i))throw new y.ErrnoError(8);if((i.flags&2097155)===0)throw new y.ErrnoError(8);if(y.isDir(i.node.mode))throw new y.ErrnoError(31);if(!i.stream_ops.write)throw new y.ErrnoError(28);if(i.seekable&&i.flags&1024)y.llseek(i,0,2);var p=typeof c<"u";if(!p)c=i.position;else if(!i.seekable)throw new y.ErrnoError(70);var E=i.stream_ops.write(i,l,h,f,c,d);if(!p)i.position+=E;return E},mmap(i,l,h,f,c){if((f&2)!==0&&(c&2)===0&&(i.flags&2097155)!==2)throw new y.ErrnoError(2);if((i.flags&2097155)===1)throw new y.ErrnoError(2);if(!i.stream_ops.mmap)throw new y.ErrnoError(43);if(!l)throw new y.ErrnoError(28);return i.stream_ops.mmap(i,l,h,f,c)},msync(i,l,h,f,c){if(!i.stream_ops.msync)return 0;return i.stream_ops.msync(i,l,h,f,c)},ioctl(i,l,h){if(!i.stream_ops.ioctl)throw new y.ErrnoError(59);return i.stream_ops.ioctl(i,l,h)},readFile(i,l={}){if(l.flags=l.flags||0,l.encoding=l.encoding||"binary",l.encoding!=="utf8"&&l.encoding!=="binary")$t(`Invalid encoding type "${l.encoding}"`);var h=y.open(i,l.flags),f=y.stat(i).size,c=new Uint8Array(f);if(y.read(h,c,0,f,0),l.encoding==="utf8")c=On(c);return y.close(h),c},writeFile(i,l,h={}){h.flags=h.flags||577;var f=y.open(i,h.flags,h.mode);l=Ec(l),y.write(f,l,0,l.byteLength,void 0,h.canOwn),y.close(f)},cwd:()=>y.currentPath,chdir(i){var l=y.lookupPath(i,{follow:!0});if(l.node===null)throw new y.ErrnoError(44);if(!y.isDir(l.node.mode))throw new y.ErrnoError(54);var h=y.nodePermissions(l.node,"x");if(h)throw new y.ErrnoError(h);y.currentPath=l.path},createDefaultDirectories(){y.mkdir("/tmp"),y.mkdir("/home"),y.mkdir("/home/web_user")},createDefaultDevices(){y.mkdir("/dev"),y.registerDevice(y.makedev(1,3),{read:()=>0,write:(f,c,d,p,E)=>p,llseek:()=>0}),y.mkdev("/dev/null",y.makedev(1,3)),yr.register(y.makedev(5,0),yr.default_tty_ops),yr.register(y.makedev(6,0),yr.default_tty1_ops),y.mkdev("/dev/tty",y.makedev(5,0)),y.mkdev("/dev/tty1",y.makedev(6,0));var i=new Uint8Array(1024),l=0,h=()=>{if(l===0)hc(i),l=i.byteLength;return i[--l]};y.createDevice("/dev","random",h),y.createDevice("/dev","urandom",h),y.mkdir("/dev/shm"),y.mkdir("/dev/shm/tmp")},createSpecialDirectories(){y.mkdir("/proc");var i=y.mkdir("/proc/self");y.mkdir("/proc/self/fd"),y.mount({mount(){var l=y.createNode(i,"fd",16895,73);return l.stream_ops={llseek:Fe.stream_ops.llseek},l.node_ops={lookup(h,f){var c=+f,d=y.getStreamChecked(c),p={parent:null,mount:{mountpoint:"fake"},node_ops:{readlink:()=>d.path},id:c+1};return p.parent=p,p},readdir(){return Array.from(y.streams.entries()).filter(([h,f])=>f).map(([h,f])=>h.toString())}},l}},{},"/proc/self/fd")},createStandardStreams(i,l,h){if(i)y.createDevice("/dev","stdin",i);else y.symlink("/dev/tty","/dev/stdin");if(l)y.createDevice("/dev","stdout",null,l);else y.symlink("/dev/tty","/dev/stdout");if(h)y.createDevice("/dev","stderr",null,h);else y.symlink("/dev/tty1","/dev/stderr");y.open("/dev/stdin",0),y.open("/dev/stdout",1),y.open("/dev/stderr",1)},staticInit(){y.nameTable=Array(4096),y.mount(Fe,{},"/"),y.createDefaultDirectories(),y.createDefaultDevices(),y.createSpecialDirectories(),y.filesystems={MEMFS:Fe}},init(i,l,h){y.initialized=!0,i??=r.stdin,l??=r.stdout,h??=r.stderr,y.createStandardStreams(i,l,h)},quit(){y.initialized=!1;for(var i of y.streams)if(i)y.close(i)},findObject(i,l){var h=y.analyzePath(i,l);if(!h.exists)return null;return h.object},analyzePath(i,l){try{var h=y.lookupPath(i,{follow:!l});i=h.path}catch(c){}var f={isRoot:!1,exists:!1,error:0,name:null,path:null,object:null,parentExists:!1,parentPath:null,parentObject:null};try{var h=y.lookupPath(i,{parent:!0});f.parentExists=!0,f.parentPath=h.path,f.parentObject=h.node,f.name=Xe.basename(i),h=y.lookupPath(i,{follow:!l}),f.exists=!0,f.path=h.path,f.object=h.node,f.name=h.node.name,f.isRoot=h.path==="/"}catch(c){f.error=c.errno}return f},createPath(i,l,h,f){i=typeof i=="string"?i:y.getPath(i);var c=l.split("/").reverse();while(c.length){var d=c.pop();if(!d)continue;var p=Xe.join2(i,d);try{y.mkdir(p)}catch(E){if(E.errno!=20)throw E}i=p}return p},createFile(i,l,h,f,c){var d=Xe.join2(typeof i=="string"?i:y.getPath(i),l),p=Ci(f,c);return y.create(d,p)},createDataFile(i,l,h,f,c,d){var p=l;if(i)i=typeof i=="string"?i:y.getPath(i),p=l?Xe.join2(i,l):i;var E=Ci(f,c),b=y.create(p,E);if(h){h=Ec(h),y.chmod(b,E|146);var I=y.open(b,577);y.write(I,h,0,h.length,0,d),y.close(I),y.chmod(b,E)}},createDevice(i,l,h,f){var c=Xe.join2(typeof i=="string"?i:y.getPath(i),l),d=Ci(!!h,!!f);y.createDevice.major??=64;var p=y.makedev(y.createDevice.major++,0);return y.registerDevice(p,{open(E){E.seekable=!1},close(E){if(f?.buffer?.length)f(10)},read(E,b,I,V,M){var C=0;for(var q=0;q<V;q++){var H;try{H=h()}catch(G){throw new y.ErrnoError(29)}if(H===void 0&&C===0)throw new y.ErrnoError(6);if(H===null||H===void 0)break;C++,b[I+q]=H}if(C)E.node.atime=Date.now();return C},write(E,b,I,V,M){for(var C=0;C<V;C++)try{f(b[I+C])}catch(q){throw new y.ErrnoError(29)}if(V)E.node.mtime=E.node.ctime=Date.now();return C}}),y.mkdev(c,d,p)},forceLoadFile(i){if(i.isDevice||i.isFolder||i.link||i.contents)return!0;if(globalThis.XMLHttpRequest)$t("Lazy loading should have been performed (contents set) in createLazyFile, but it was not. Lazy loading only works in web workers. Use --embed-file or --preload-file in emcc on the main thread.");else try{i.contents=x(i.url)}catch(l){throw new y.ErrnoError(29)}},createLazyFile(i,l,h,f,c){class d{lengthKnown=!1;chunks=[];get(V){if(V>this.length-1||V<0)return;var M=V%this.chunkSize,C=V/this.chunkSize|0;return this.getter(C)[M]}setDataGetter(V){this.getter=V}cacheLength(){var V=new XMLHttpRequest;if(V.open("HEAD",h,!1),V.send(null),!(V.status>=200&&V.status<300||V.status===304))$t("Couldn't load "+h+". Status: "+V.status);var M=Number(V.getResponseHeader("Content-length")),C,q=(C=V.getResponseHeader("Accept-Ranges"))&&C==="bytes",H=(C=V.getResponseHeader("Content-Encoding"))&&C==="gzip",G=1048576;if(!q)G=M;var le=(R,X)=>{if(R>X)$t("invalid range ("+R+", "+X+") or no bytes requested!");if(X>M-1)$t("only "+M+" bytes available! programmer error!");var ee=new XMLHttpRequest;if(ee.open("GET",h,!1),M!==G)ee.setRequestHeader("Range","bytes="+R+"-"+X);if(ee.responseType="arraybuffer",ee.overrideMimeType)ee.overrideMimeType("text/plain; charset=x-user-defined");if(ee.send(null),!(ee.status>=200&&ee.status<300||ee.status===304))$t("Couldn't load "+h+". Status: "+ee.status);if(ee.response!==void 0)return new Uint8Array(ee.response||[]);return Ni(ee.responseText||"",!0)},O=this;if(O.setDataGetter((R)=>{var X=R*G,ee=(R+1)*G-1;if(ee=Math.min(ee,M-1),typeof O.chunks[R]>"u")O.chunks[R]=le(X,ee);if(typeof O.chunks[R]>"u")$t("doXHR failed!");return O.chunks[R]}),H||!M)G=M=1,M=this.getter(0).length,G=M,D("LazyFiles on gzip forces download of the whole file when length is accessed");this._length=M,this._chunkSize=G,this.lengthKnown=!0}get length(){if(!this.lengthKnown)this.cacheLength();return this._length}get chunkSize(){if(!this.lengthKnown)this.cacheLength();return this._chunkSize}}if(globalThis.XMLHttpRequest){if(!o)$t("Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc");var p={isDevice:!1,contents:new d}}else var p={isDevice:!1,url:h};var E=y.createFile(i,l,p,f,c);if(p.contents)E.contents=p.contents;else if(p.url)E.contents=null,E.url=p.url;Object.defineProperties(E,{usedBytes:{get:function(){return this.contents.length}}});var b={};for(let[V,M]of Object.entries(E.stream_ops))b[V]=(...C)=>(y.forceLoadFile(E),M(...C));function I(V,M,C,q,H){var G=V.node.contents;if(H>=G.length)return 0;var le=Math.min(G.length-H,q);if(G.slice)for(var O=0;O<le;O++)M[C+O]=G[H+O];else for(var O=0;O<le;O++)M[C+O]=G.get(H+O);return le}return b.read=(V,M,C,q,H)=>(y.forceLoadFile(E),I(V,M,C,q,H)),b.mmap=(V,M,C,q,H)=>{y.forceLoadFile(E);var G=vc(M);if(!G)throw new y.ErrnoError(48);return I(V,Ft,G,M,C),{ptr:G,allocated:!0}},E.stream_ops=b,E}},Gh=(i,l,h)=>{if(!i)return"";var f=yc(Ar,i,l,h);return mc.decode(Ar.subarray(i,f))},Be={calculateAt(i,l,h){if(Xe.isAbs(l))return l;var f;if(i===-100)f=y.cwd();else f=Be.getStreamFromFD(i).path;if(l.length==0){if(!h)throw new y.ErrnoError(44);return f}return f+"/"+l},writeStat(i,l){et[i>>2]=l.dev,et[i+4>>2]=l.mode,et[i+8>>2]=l.nlink,et[i+12>>2]=l.uid,et[i+16>>2]=l.gid,et[i+20>>2]=l.rdev,St[i+24>>3]=BigInt(l.size),Je[i+32>>2]=4096,Je[i+36>>2]=l.blocks;var h=l.atime.getTime(),f=l.mtime.getTime(),c=l.ctime.getTime();return St[i+40>>3]=BigInt(Math.floor(h/1000)),et[i+48>>2]=h%1000*1000*1000,St[i+56>>3]=BigInt(Math.floor(f/1000)),et[i+64>>2]=f%1000*1000*1000,St[i+72>>3]=BigInt(Math.floor(c/1000)),et[i+80>>2]=c%1000*1000*1000,St[i+88>>3]=BigInt(l.ino),0},writeStatFs(i,l){et[i+4>>2]=l.bsize,et[i+60>>2]=l.bsize,St[i+8>>3]=BigInt(l.blocks),St[i+16>>3]=BigInt(l.bfree),St[i+24>>3]=BigInt(l.bavail),St[i+32>>3]=BigInt(l.files),St[i+40>>3]=BigInt(l.ffree),et[i+48>>2]=l.fsid,et[i+64>>2]=l.flags,et[i+56>>2]=l.namelen},doMsync(i,l,h,f,c){if(!y.isFile(l.node.mode))throw new y.ErrnoError(43);if(f&2)return 0;var d=Ar.slice(i,i+h);y.msync(l,d,c,h,f)},getStreamFromFD(i){return y.getStreamChecked(i)},varargs:void 0,getStr(i){return Gh(i)}};function Kh(i,l){try{return i=Be.getStr(i),y.chmod(i,l),0}catch(h){if(typeof y>"u"||h.name!=="ErrnoError")throw h;return-h.errno}}function Vh(i,l,h,f){try{if(l=Be.getStr(l),l=Be.calculateAt(i,l),h&-8)return-28;var c=y.lookupPath(l,{follow:!0}).node;if(!c)return-44;var d="";if(h&4)d+="r";if(h&2)d+="w";if(h&1)d+="x";if(d&&y.nodePermissions(c,d))return-2;return 0}catch(p){if(typeof y>"u"||p.name!=="ErrnoError")throw p;return-p.errno}}function Jh(i,l){try{return y.fchmod(i,l),0}catch(h){if(typeof y>"u"||h.name!=="ErrnoError")throw h;return-h.errno}}function Xh(i,l,h){try{return y.fchown(i,l,h),0}catch(f){if(typeof y>"u"||f.name!=="ErrnoError")throw f;return-f.errno}}var go=()=>{var i=Je[+Be.varargs>>2];return Be.varargs+=4,i},Yr=go;function Qh(i,l,h){Be.varargs=h;try{var f=Be.getStreamFromFD(i);switch(l){case 0:var c=go();if(c<0)return-28;while(y.streams[c])c++;return y.dupStream(f,c).fd;case 1:case 2:return 0;case 3:return f.flags;case 4:var c=go();return f.flags|=c,0;case 12:var c=Yr(),d=0;return Dn[c+d>>1]=2,0;case 13:case 14:return 0}return-28}catch(p){if(typeof y>"u"||p.name!=="ErrnoError")throw p;return-p.errno}}function Yh(i,l){try{return Be.writeStat(l,y.fstat(i))}catch(h){if(typeof y>"u"||h.name!=="ErrnoError")throw h;return-h.errno}}var em=9007199254740992,tm=-9007199254740992,en=(i)=>i<tm||i>em?NaN:Number(i);function rm(i,l){l=en(l);try{if(isNaN(l))return-61;return y.ftruncate(i,l),0}catch(h){if(typeof y>"u"||h.name!=="ErrnoError")throw h;return-h.errno}}var Or=(i,l,h)=>bc(i,Ar,l,h);function nm(i,l){try{if(l===0)return-28;var h=y.cwd(),f=_o(h)+1;if(l<f)return-68;return Or(h,i,l),f}catch(c){if(typeof y>"u"||c.name!=="ErrnoError")throw c;return-c.errno}}function om(i,l,h){Be.varargs=h;try{var f=Be.getStreamFromFD(i);switch(l){case 21509:if(!f.tty)return-59;return 0;case 21505:if(!f.tty)return-59;if(f.tty.ops.ioctl_tcgets){var c=f.tty.ops.ioctl_tcgets(f),M=Yr();Je[M>>2]=c.c_iflag||0,Je[M+4>>2]=c.c_oflag||0,Je[M+8>>2]=c.c_cflag||0,Je[M+12>>2]=c.c_lflag||0;for(var d=0;d<32;d++)Ft[M+d+17]=c.c_cc[d]||0;return 0}return 0;case 21510:case 21511:case 21512:if(!f.tty)return-59;return 0;case 21506:case 21507:case 21508:if(!f.tty)return-59;if(f.tty.ops.ioctl_tcsets){var M=Yr(),p=Je[M>>2],E=Je[M+4>>2],b=Je[M+8>>2],I=Je[M+12>>2],V=[];for(var d=0;d<32;d++)V.push(Ft[M+d+17]);return f.tty.ops.ioctl_tcsets(f.tty,l,{c_iflag:p,c_oflag:E,c_cflag:b,c_lflag:I,c_cc:V})}return 0;case 21519:if(!f.tty)return-59;var M=Yr();return Je[M>>2]=0,0;case 21520:if(!f.tty)return-59;return-28;case 21537:case 21531:var M=Yr();return y.ioctl(f,l,M);case 21523:if(!f.tty)return-59;if(f.tty.ops.ioctl_tiocgwinsz){var C=f.tty.ops.ioctl_tiocgwinsz(f.tty),M=Yr();Dn[M>>1]=C[0],Dn[M+2>>1]=C[1]}return 0;case 21524:if(!f.tty)return-59;return 0;case 21515:if(!f.tty)return-59;return 0;default:return-28}}catch(q){if(typeof y>"u"||q.name!=="ErrnoError")throw q;return-q.errno}}function im(i,l){try{return i=Be.getStr(i),Be.writeStat(l,y.lstat(i))}catch(h){if(typeof y>"u"||h.name!=="ErrnoError")throw h;return-h.errno}}function sm(i,l,h){try{return l=Be.getStr(l),l=Be.calculateAt(i,l),y.mkdir(l,h,0),0}catch(f){if(typeof y>"u"||f.name!=="ErrnoError")throw f;return-f.errno}}function am(i,l,h,f){try{l=Be.getStr(l);var c=f&256,d=f&4096;return f=f&-6401,l=Be.calculateAt(i,l,d),Be.writeStat(h,c?y.lstat(l):y.stat(l))}catch(p){if(typeof y>"u"||p.name!=="ErrnoError")throw p;return-p.errno}}function cm(i,l,h,f){Be.varargs=f;try{l=Be.getStr(l),l=Be.calculateAt(i,l);var c=f?go():0;return y.open(l,h,c).fd}catch(d){if(typeof y>"u"||d.name!=="ErrnoError")throw d;return-d.errno}}function lm(i,l,h,f){try{if(l=Be.getStr(l),l=Be.calculateAt(i,l),f<=0)return-28;var c=y.readlink(l),d=Math.min(f,_o(c)),p=Ft[h+d];return Or(c,h,f+1),Ft[h+d]=p,d}catch(E){if(typeof y>"u"||E.name!=="ErrnoError")throw E;return-E.errno}}function um(i){try{return i=Be.getStr(i),y.rmdir(i),0}catch(l){if(typeof y>"u"||l.name!=="ErrnoError")throw l;return-l.errno}}function dm(i,l){try{return i=Be.getStr(i),Be.writeStat(l,y.stat(i))}catch(h){if(typeof y>"u"||h.name!=="ErrnoError")throw h;return-h.errno}}function fm(i,l,h){try{if(l=Be.getStr(l),l=Be.calculateAt(i,l),!h)y.unlink(l);else if(h===512)y.rmdir(l);else return-28;return 0}catch(f){if(typeof y>"u"||f.name!=="ErrnoError")throw f;return-f.errno}}var Tc=(i)=>et[i>>2]+Je[i+4>>2]*4294967296;function pm(i,l,h,f){try{l=Be.getStr(l),l=Be.calculateAt(i,l,!0);var c=Date.now(),d,p;if(!h)d=c,p=c;else{var E=Tc(h),b=Je[h+8>>2];if(b==1073741823)d=c;else if(b==1073741822)d=null;else d=E*1000+b/1e6;if(h+=16,E=Tc(h),b=Je[h+8>>2],b==1073741823)p=c;else if(b==1073741822)p=null;else p=E*1000+b/1e6}if((p??d)!==null)y.utime(l,d,p);return 0}catch(I){if(typeof y>"u"||I.name!=="ErrnoError")throw I;return-I.errno}}var _m=(i)=>i%4===0&&(i%100!==0||i%400===0),gm=[0,31,60,91,121,152,182,213,244,274,305,335],hm=[0,31,59,90,120,151,181,212,243,273,304,334],mm=(i)=>(_m(i.getFullYear())?gm:hm)[i.getMonth()]+i.getDate()-1;function ym(i,l){i=en(i);var h=new Date(i*1000);Je[l>>2]=h.getSeconds(),Je[l+4>>2]=h.getMinutes(),Je[l+8>>2]=h.getHours(),Je[l+12>>2]=h.getDate(),Je[l+16>>2]=h.getMonth(),Je[l+20>>2]=h.getFullYear()-1900,Je[l+24>>2]=h.getDay();var f=mm(h)|0;Je[l+28>>2]=f,Je[l+36>>2]=-(h.getTimezoneOffset()*60);var c=new Date(h.getFullYear(),0,1),d=new Date(h.getFullYear(),6,1).getTimezoneOffset(),p=c.getTimezoneOffset(),E=(d!=p&&h.getTimezoneOffset()==Math.min(p,d))|0;Je[l+32>>2]=E}function bm(i,l,h,f,c,d,p){c=en(c);try{var E=Be.getStreamFromFD(f),b=y.mmap(E,i,c,l,h),I=b.ptr;return Je[d>>2]=b.allocated,et[p>>2]=I,0}catch(V){if(typeof y>"u"||V.name!=="ErrnoError")throw V;return-V.errno}}function wm(i,l,h,f,c,d){d=en(d);try{var p=Be.getStreamFromFD(c);if(h&2)Be.doMsync(i,p,l,f,d)}catch(E){if(typeof y>"u"||E.name!=="ErrnoError")throw E;return-E.errno}}var vm=(i,l,h,f)=>{var c=new Date().getFullYear(),d=new Date(c,0,1),p=new Date(c,6,1),E=d.getTimezoneOffset(),b=p.getTimezoneOffset(),I=Math.max(E,b);et[i>>2]=I*60,Je[l>>2]=Number(E!=b);var V=(q)=>{var H=q>=0?"-":"+",G=Math.abs(q);return`UTC${H}${String(Math.floor(G/60)).padStart(2,"0")}${String(G%60).padStart(2,"0")}`},M=V(E),C=V(b);if(b<E)Or(M,h,17),Or(C,f,17);else Or(M,f,17),Or(C,h,17)},kc=()=>performance.now(),Rc=()=>Date.now(),Em=1,Sm=(i)=>i>=0&&i<=3;function xm(i,l,h){if(l=en(l),!Sm(i))return 28;var f;if(i===0)f=Rc();else if(Em)f=kc();else return 52;var c=Math.round(f*1000*1000);return St[h>>3]=BigInt(c),0}var Ac=()=>2147483648,Tm=()=>Ac(),km=(i)=>{var l=(i-ur.buffer.byteLength+65535)/65536|0;try{return ur.grow(l),Ze(),1}catch(h){}},Rm=(i)=>{var l=Ar.length;i>>>=0;var h=Ac();if(i>h)return!1;for(var f=1;f<=4;f*=2){var c=l*(1+0.2/f);if(c=Math.min(c,i+100663296),km(Math.min(h,wc(Math.max(i,c),65536))))return!0}return!1},qi={},Am=()=>s||"./this.program",Pn=()=>{if(!Pn.strings){var i={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(globalThis.navigator?.language??"C").replace("-","_")+".UTF-8",_:Am()};for(var l in qi)if(qi[l]===void 0)delete i[l];else i[l]=qi[l];var h=[];for(var l in i)h.push(`${l}=${i[l]}`);Pn.strings=h}return Pn.strings},Dm=(i,l)=>{var h=0,f=0;for(var c of Pn()){var d=l+h;et[i+f>>2]=d,h+=Or(c,d,1/0)+1,f+=4}return 0},Om=(i,l)=>{var h=Pn();et[i>>2]=h.length;var f=0;for(var c of h)f+=_o(c)+1;return et[l>>2]=f,0};function Im(i){try{var l=Be.getStreamFromFD(i);return y.close(l),0}catch(h){if(typeof y>"u"||h.name!=="ErrnoError")throw h;return h.errno}}function Pm(i,l){try{var h=0,f=0,c=0,d=Be.getStreamFromFD(i),p=d.tty?2:y.isDir(d.mode)?3:y.isLink(d.mode)?7:4;return Ft[l]=p,Dn[l+2>>1]=c,St[l+8>>3]=BigInt(h),St[l+16>>3]=BigInt(f),0}catch(E){if(typeof y>"u"||E.name!=="ErrnoError")throw E;return E.errno}}var Nm=(i,l,h,f)=>{var c=0;for(var d=0;d<h;d++){var p=et[l>>2],E=et[l+4>>2];l+=8;var b=y.read(i,Ft,p,E,f);if(b<0)return-1;if(c+=b,b<E)break;if(typeof f<"u")f+=b}return c};function Cm(i,l,h,f){try{var c=Nm(Be.getStreamFromFD(i),l,h);return et[f>>2]=c,0}catch(d){if(typeof y>"u"||d.name!=="ErrnoError")throw d;return d.errno}}function qm(i,l,h,f){l=en(l);try{if(isNaN(l))return 61;var c=Be.getStreamFromFD(i);if(y.llseek(c,l,h),St[f>>3]=BigInt(c.position),c.getdents&&l===0&&h===0)c.getdents=null;return 0}catch(d){if(typeof y>"u"||d.name!=="ErrnoError")throw d;return d.errno}}function Lm(i){try{var l=Be.getStreamFromFD(i);return l.stream_ops?.fsync?.(l)}catch(h){if(typeof y>"u"||h.name!=="ErrnoError")throw h;return h.errno}}var $m=(i,l,h,f)=>{var c=0;for(var d=0;d<h;d++){var p=et[l>>2],E=et[l+4>>2];l+=8;var b=y.write(i,Ft,p,E,f);if(b<0)return-1;if(c+=b,b<E)break;if(typeof f<"u")f+=b}return c};function Fm(i,l,h,f){try{var c=$m(Be.getStreamFromFD(i),l,h);return et[f>>2]=c,0}catch(d){if(typeof y>"u"||d.name!=="ErrnoError")throw d;return d.errno}}if(y.createPreloadedFile=Zh,y.preloadFile=xc,y.staticInit(),$e(),r.noExitRuntime)r.noExitRuntime;if(r.preloadPlugins)Sc=r.preloadPlugins;if(r.print)D=r.print;if(r.printErr)j=r.printErr;if(r.wasmBinary)Y=r.wasmBinary;if(r.arguments)r.arguments;if(r.thisProgram)s=r.thisProgram;if(r.preInit){if(typeof r.preInit=="function")r.preInit=[r.preInit];while(r.preInit.length>0)r.preInit.shift()()}r.wasmMemory=ur;var Dc;function zm(i){r._sqlite3_status64=i.sqlite3_status64,r._sqlite3_status=i.sqlite3_status,r._sqlite3_db_status64=i.sqlite3_db_status64,r._sqlite3_msize=i.sqlite3_msize,r._sqlite3_db_status=i.sqlite3_db_status,r._sqlite3_vfs_find=i.sqlite3_vfs_find,r._sqlite3_initialize=i.sqlite3_initialize,r._sqlite3_malloc=i.sqlite3_malloc,r._sqlite3_free=i.sqlite3_free,r._sqlite3_vfs_register=i.sqlite3_vfs_register,r._sqlite3_vfs_unregister=i.sqlite3_vfs_unregister,r._sqlite3_malloc64=i.sqlite3_malloc64,r._sqlite3_realloc=i.sqlite3_realloc,r._sqlite3_realloc64=i.sqlite3_realloc64,r._sqlite3_value_text=i.sqlite3_value_text,r._sqlite3_randomness=i.sqlite3_randomness,r._sqlite3_stricmp=i.sqlite3_stricmp,r._sqlite3_strnicmp=i.sqlite3_strnicmp,r._sqlite3_uri_parameter=i.sqlite3_uri_parameter,r._sqlite3_uri_boolean=i.sqlite3_uri_boolean,r._sqlite3_serialize=i.sqlite3_serialize,r._sqlite3_prepare_v2=i.sqlite3_prepare_v2,r._sqlite3_step=i.sqlite3_step,r._sqlite3_column_int64=i.sqlite3_column_int64,r._sqlite3_reset=i.sqlite3_reset,r._sqlite3_exec=i.sqlite3_exec,r._sqlite3_column_int=i.sqlite3_column_int,r._sqlite3_finalize=i.sqlite3_finalize,r._sqlite3_file_control=i.sqlite3_file_control,r._sqlite3_column_name=i.sqlite3_column_name,r._sqlite3_column_text=i.sqlite3_column_text,r._sqlite3_column_type=i.sqlite3_column_type,r._sqlite3_errmsg=i.sqlite3_errmsg,r._sqlite3_deserialize=i.sqlite3_deserialize,r._sqlite3_clear_bindings=i.sqlite3_clear_bindings,r._sqlite3_value_blob=i.sqlite3_value_blob,r._sqlite3_value_bytes=i.sqlite3_value_bytes,r._sqlite3_value_double=i.sqlite3_value_double,r._sqlite3_value_int=i.sqlite3_value_int,r._sqlite3_value_int64=i.sqlite3_value_int64,r._sqlite3_value_subtype=i.sqlite3_value_subtype,r._sqlite3_value_pointer=i.sqlite3_value_pointer,r._sqlite3_value_type=i.sqlite3_value_type,r._sqlite3_value_nochange=i.sqlite3_value_nochange,r._sqlite3_value_frombind=i.sqlite3_value_frombind,r._sqlite3_value_dup=i.sqlite3_value_dup,r._sqlite3_value_free=i.sqlite3_value_free,r._sqlite3_result_blob=i.sqlite3_result_blob,r._sqlite3_result_error_toobig=i.sqlite3_result_error_toobig,r._sqlite3_result_error_nomem=i.sqlite3_result_error_nomem,r._sqlite3_result_double=i.sqlite3_result_double,r._sqlite3_result_error=i.sqlite3_result_error,r._sqlite3_result_int=i.sqlite3_result_int,r._sqlite3_result_int64=i.sqlite3_result_int64,r._sqlite3_result_null=i.sqlite3_result_null,r._sqlite3_result_pointer=i.sqlite3_result_pointer,r._sqlite3_result_subtype=i.sqlite3_result_subtype,r._sqlite3_result_text=i.sqlite3_result_text,r._sqlite3_result_zeroblob=i.sqlite3_result_zeroblob,r._sqlite3_result_zeroblob64=i.sqlite3_result_zeroblob64,r._sqlite3_result_error_code=i.sqlite3_result_error_code,r._sqlite3_user_data=i.sqlite3_user_data,r._sqlite3_context_db_handle=i.sqlite3_context_db_handle,r._sqlite3_vtab_nochange=i.sqlite3_vtab_nochange,r._sqlite3_vtab_in_first=i.sqlite3_vtab_in_first,r._sqlite3_vtab_in_next=i.sqlite3_vtab_in_next,r._sqlite3_aggregate_context=i.sqlite3_aggregate_context,r._sqlite3_get_auxdata=i.sqlite3_get_auxdata,r._sqlite3_set_auxdata=i.sqlite3_set_auxdata,r._sqlite3_column_count=i.sqlite3_column_count,r._sqlite3_data_count=i.sqlite3_data_count,r._sqlite3_column_blob=i.sqlite3_column_blob,r._sqlite3_column_bytes=i.sqlite3_column_bytes,r._sqlite3_column_double=i.sqlite3_column_double,r._sqlite3_column_value=i.sqlite3_column_value,r._sqlite3_column_decltype=i.sqlite3_column_decltype,r._sqlite3_column_database_name=i.sqlite3_column_database_name,r._sqlite3_column_table_name=i.sqlite3_column_table_name,r._sqlite3_column_origin_name=i.sqlite3_column_origin_name,r._sqlite3_bind_blob=i.sqlite3_bind_blob,r._sqlite3_bind_double=i.sqlite3_bind_double,r._sqlite3_bind_int=i.sqlite3_bind_int,r._sqlite3_bind_int64=i.sqlite3_bind_int64,r._sqlite3_bind_null=i.sqlite3_bind_null,r._sqlite3_bind_pointer=i.sqlite3_bind_pointer,r._sqlite3_bind_text=i.sqlite3_bind_text,r._sqlite3_bind_zeroblob=i.sqlite3_bind_zeroblob,r._sqlite3_bind_parameter_count=i.sqlite3_bind_parameter_count,r._sqlite3_bind_parameter_name=i.sqlite3_bind_parameter_name,r._sqlite3_bind_parameter_index=i.sqlite3_bind_parameter_index,r._sqlite3_db_handle=i.sqlite3_db_handle,r._sqlite3_stmt_readonly=i.sqlite3_stmt_readonly,r._sqlite3_stmt_isexplain=i.sqlite3_stmt_isexplain,r._sqlite3_stmt_explain=i.sqlite3_stmt_explain,r._sqlite3_stmt_busy=i.sqlite3_stmt_busy,r._sqlite3_next_stmt=i.sqlite3_next_stmt,r._sqlite3_stmt_status=i.sqlite3_stmt_status,r._sqlite3_sql=i.sqlite3_sql,r._sqlite3_expanded_sql=i.sqlite3_expanded_sql,r._sqlite3_preupdate_old=i.sqlite3_preupdate_old,r._sqlite3_preupdate_count=i.sqlite3_preupdate_count,r._sqlite3_preupdate_depth=i.sqlite3_preupdate_depth,r._sqlite3_preupdate_blobwrite=i.sqlite3_preupdate_blobwrite,r._sqlite3_preupdate_new=i.sqlite3_preupdate_new,r._sqlite3_value_numeric_type=i.sqlite3_value_numeric_type,r._sqlite3_set_authorizer=i.sqlite3_set_authorizer,r._sqlite3_strglob=i.sqlite3_strglob,r._sqlite3_strlike=i.sqlite3_strlike,r._sqlite3_auto_extension=i.sqlite3_auto_extension,r._sqlite3_cancel_auto_extension=i.sqlite3_cancel_auto_extension,r._sqlite3_reset_auto_extension=i.sqlite3_reset_auto_extension,r._sqlite3_prepare_v3=i.sqlite3_prepare_v3,r._sqlite3_create_module=i.sqlite3_create_module,r._sqlite3_create_module_v2=i.sqlite3_create_module_v2,r._sqlite3_drop_modules=i.sqlite3_drop_modules,r._sqlite3_declare_vtab=i.sqlite3_declare_vtab,r._sqlite3_vtab_on_conflict=i.sqlite3_vtab_on_conflict,r._sqlite3_vtab_collation=i.sqlite3_vtab_collation,r._sqlite3_vtab_in=i.sqlite3_vtab_in,r._sqlite3_vtab_rhs_value=i.sqlite3_vtab_rhs_value,r._sqlite3_vtab_distinct=i.sqlite3_vtab_distinct,r._sqlite3_keyword_name=i.sqlite3_keyword_name,r._sqlite3_keyword_count=i.sqlite3_keyword_count,r._sqlite3_keyword_check=i.sqlite3_keyword_check,r._sqlite3_complete=i.sqlite3_complete,r._sqlite3_libversion=i.sqlite3_libversion,r._sqlite3_libversion_number=i.sqlite3_libversion_number,r._sqlite3_shutdown=i.sqlite3_shutdown,r._sqlite3_last_insert_rowid=i.sqlite3_last_insert_rowid,r._sqlite3_set_last_insert_rowid=i.sqlite3_set_last_insert_rowid,r._sqlite3_changes64=i.sqlite3_changes64,r._sqlite3_changes=i.sqlite3_changes,r._sqlite3_total_changes64=i.sqlite3_total_changes64,r._sqlite3_total_changes=i.sqlite3_total_changes,r._sqlite3_txn_state=i.sqlite3_txn_state,r._sqlite3_close_v2=i.sqlite3_close_v2,r._sqlite3_busy_handler=i.sqlite3_busy_handler,r._sqlite3_progress_handler=i.sqlite3_progress_handler,r._sqlite3_busy_timeout=i.sqlite3_busy_timeout,r._sqlite3_interrupt=i.sqlite3_interrupt,r._sqlite3_is_interrupted=i.sqlite3_is_interrupted,r._sqlite3_create_function=i.sqlite3_create_function,r._sqlite3_create_function_v2=i.sqlite3_create_function_v2,r._sqlite3_create_window_function=i.sqlite3_create_window_function,r._sqlite3_overload_function=i.sqlite3_overload_function,r._sqlite3_trace_v2=i.sqlite3_trace_v2,r._sqlite3_commit_hook=i.sqlite3_commit_hook,r._sqlite3_update_hook=i.sqlite3_update_hook,r._sqlite3_rollback_hook=i.sqlite3_rollback_hook,r._sqlite3_preupdate_hook=i.sqlite3_preupdate_hook,r._sqlite3_set_errmsg=i.sqlite3_set_errmsg,r._sqlite3_error_offset=i.sqlite3_error_offset,r._sqlite3_errcode=i.sqlite3_errcode,r._sqlite3_extended_errcode=i.sqlite3_extended_errcode,r._sqlite3_errstr=i.sqlite3_errstr,r._sqlite3_limit=i.sqlite3_limit,r._sqlite3_open=i.sqlite3_open,r._sqlite3_open_v2=i.sqlite3_open_v2,r._sqlite3_create_collation=i.sqlite3_create_collation,r._sqlite3_create_collation_v2=i.sqlite3_create_collation_v2,r._sqlite3_collation_needed=i.sqlite3_collation_needed,r._sqlite3_get_autocommit=i.sqlite3_get_autocommit,r._sqlite3_table_column_metadata=i.sqlite3_table_column_metadata,r._sqlite3_extended_result_codes=i.sqlite3_extended_result_codes,r._sqlite3_uri_key=i.sqlite3_uri_key,r._sqlite3_uri_int64=i.sqlite3_uri_int64,r._sqlite3_db_name=i.sqlite3_db_name,r._sqlite3_db_filename=i.sqlite3_db_filename,r._sqlite3_db_readonly=i.sqlite3_db_readonly,r._sqlite3_compileoption_used=i.sqlite3_compileoption_used,r._sqlite3_compileoption_get=i.sqlite3_compileoption_get,r._sqlite3session_diff=i.sqlite3session_diff,r._sqlite3session_attach=i.sqlite3session_attach,r._sqlite3session_create=i.sqlite3session_create,r._sqlite3session_delete=i.sqlite3session_delete,r._sqlite3session_table_filter=i.sqlite3session_table_filter,r._sqlite3session_changeset=i.sqlite3session_changeset,r._sqlite3session_changeset_strm=i.sqlite3session_changeset_strm,r._sqlite3session_patchset_strm=i.sqlite3session_patchset_strm,r._sqlite3session_patchset=i.sqlite3session_patchset,r._sqlite3session_enable=i.sqlite3session_enable,r._sqlite3session_indirect=i.sqlite3session_indirect,r._sqlite3session_isempty=i.sqlite3session_isempty,r._sqlite3session_memory_used=i.sqlite3session_memory_used,r._sqlite3session_object_config=i.sqlite3session_object_config,r._sqlite3session_changeset_size=i.sqlite3session_changeset_size,r._sqlite3changeset_start=i.sqlite3changeset_start,r._sqlite3changeset_start_v2=i.sqlite3changeset_start_v2,r._sqlite3changeset_start_strm=i.sqlite3changeset_start_strm,r._sqlite3changeset_start_v2_strm=i.sqlite3changeset_start_v2_strm,r._sqlite3changeset_next=i.sqlite3changeset_next,r._sqlite3changeset_op=i.sqlite3changeset_op,r._sqlite3changeset_pk=i.sqlite3changeset_pk,r._sqlite3changeset_old=i.sqlite3changeset_old,r._sqlite3changeset_new=i.sqlite3changeset_new,r._sqlite3changeset_conflict=i.sqlite3changeset_conflict,r._sqlite3changeset_fk_conflicts=i.sqlite3changeset_fk_conflicts,r._sqlite3changeset_finalize=i.sqlite3changeset_finalize,r._sqlite3changeset_invert=i.sqlite3changeset_invert,r._sqlite3changeset_invert_strm=i.sqlite3changeset_invert_strm,r._sqlite3changeset_apply_v2=i.sqlite3changeset_apply_v2,r._sqlite3changeset_apply_v3=i.sqlite3changeset_apply_v3,r._sqlite3changeset_apply=i.sqlite3changeset_apply,r._sqlite3changeset_apply_v3_strm=i.sqlite3changeset_apply_v3_strm,r._sqlite3changeset_apply_v2_strm=i.sqlite3changeset_apply_v2_strm,r._sqlite3changeset_apply_strm=i.sqlite3changeset_apply_strm,r._sqlite3changegroup_new=i.sqlite3changegroup_new,r._sqlite3changegroup_add=i.sqlite3changegroup_add,r._sqlite3changegroup_output=i.sqlite3changegroup_output,r._sqlite3changegroup_add_strm=i.sqlite3changegroup_add_strm,r._sqlite3changegroup_output_strm=i.sqlite3changegroup_output_strm,r._sqlite3changegroup_delete=i.sqlite3changegroup_delete,r._sqlite3changeset_concat=i.sqlite3changeset_concat,r._sqlite3changeset_concat_strm=i.sqlite3changeset_concat_strm,r._sqlite3session_config=i.sqlite3session_config,r._sqlite3_sourceid=i.sqlite3_sourceid,r._sqlite3__wasm_pstack_ptr=i.sqlite3__wasm_pstack_ptr,r._sqlite3__wasm_pstack_restore=i.sqlite3__wasm_pstack_restore,r._sqlite3__wasm_pstack_alloc=i.sqlite3__wasm_pstack_alloc,r._sqlite3__wasm_pstack_remaining=i.sqlite3__wasm_pstack_remaining,r._sqlite3__wasm_pstack_quota=i.sqlite3__wasm_pstack_quota,r._sqlite3__wasm_test_struct=i.sqlite3__wasm_test_struct,r._sqlite3__wasm_enum_json=i.sqlite3__wasm_enum_json,r._sqlite3__wasm_vfs_unlink=i.sqlite3__wasm_vfs_unlink,r._sqlite3__wasm_db_vfs=i.sqlite3__wasm_db_vfs,r._sqlite3__wasm_db_reset=i.sqlite3__wasm_db_reset,r._sqlite3__wasm_db_export_chunked=i.sqlite3__wasm_db_export_chunked,r._sqlite3__wasm_db_serialize=i.sqlite3__wasm_db_serialize,r._sqlite3__wasm_vfs_create_file=i.sqlite3__wasm_vfs_create_file,r._sqlite3__wasm_posix_create_file=i.sqlite3__wasm_posix_create_file,r._sqlite3__wasm_kvvfsMakeKey=i.sqlite3__wasm_kvvfsMakeKey,r._sqlite3__wasm_kvvfs_methods=i.sqlite3__wasm_kvvfs_methods,r._sqlite3__wasm_vtab_config=i.sqlite3__wasm_vtab_config,r._sqlite3__wasm_db_config_ip=i.sqlite3__wasm_db_config_ip,r._sqlite3__wasm_db_config_pii=i.sqlite3__wasm_db_config_pii,r._sqlite3__wasm_db_config_s=i.sqlite3__wasm_db_config_s,r._sqlite3__wasm_config_i=i.sqlite3__wasm_config_i,r._sqlite3__wasm_config_ii=i.sqlite3__wasm_config_ii,r._sqlite3__wasm_config_j=i.sqlite3__wasm_config_j,r._sqlite3__wasm_qfmt_token=i.sqlite3__wasm_qfmt_token,r._sqlite3__wasm_kvvfs_decode=i.sqlite3__wasm_kvvfs_decode,r._sqlite3__wasm_kvvfs_encode=i.sqlite3__wasm_kvvfs_encode,r._sqlite3__wasm_init_wasmfs=i.sqlite3__wasm_init_wasmfs,r._sqlite3__wasm_test_intptr=i.sqlite3__wasm_test_intptr,r._sqlite3__wasm_test_voidptr=i.sqlite3__wasm_test_voidptr,r._sqlite3__wasm_test_int64_max=i.sqlite3__wasm_test_int64_max,r._sqlite3__wasm_test_int64_min=i.sqlite3__wasm_test_int64_min,r._sqlite3__wasm_test_int64_times2=i.sqlite3__wasm_test_int64_times2,r._sqlite3__wasm_test_int64_minmax=i.sqlite3__wasm_test_int64_minmax,r._sqlite3__wasm_test_int64ptr=i.sqlite3__wasm_test_int64ptr,r._sqlite3__wasm_test_stack_overflow=i.sqlite3__wasm_test_stack_overflow,r._sqlite3__wasm_test_str_hello=i.sqlite3__wasm_test_str_hello,r._sqlite3__wasm_SQLTester_strglob=i.sqlite3__wasm_SQLTester_strglob,r._malloc=i.malloc,r._free=i.free,r._realloc=i.realloc,Dc=i.emscripten_builtin_memalign,i._emscripten_stack_restore,i._emscripten_stack_alloc,i.emscripten_stack_get_current,i.__indirect_function_table}var Oc={__syscall_chmod:Kh,__syscall_faccessat:Vh,__syscall_fchmod:Jh,__syscall_fchown32:Xh,__syscall_fcntl64:Qh,__syscall_fstat64:Yh,__syscall_ftruncate64:rm,__syscall_getcwd:nm,__syscall_ioctl:om,__syscall_lstat64:im,__syscall_mkdirat:sm,__syscall_newfstatat:am,__syscall_openat:cm,__syscall_readlinkat:lm,__syscall_rmdir:um,__syscall_stat64:dm,__syscall_unlinkat:fm,__syscall_utimensat:pm,_localtime_js:ym,_mmap_js:bm,_munmap_js:wm,_tzset_js:vm,clock_time_get:xm,emscripten_date_now:Rc,emscripten_get_heap_max:Tm,emscripten_get_now:kc,emscripten_resize_heap:Rm,environ_get:Dm,environ_sizes_get:Om,fd_close:Im,fd_fdstat_get:Pm,fd_read:Cm,fd_seek:qm,fd_sync:Lm,fd_write:Fm,memory:ur};function Li(){if(Dr>0){In=Li;return}if(Ue(),Dr>0){In=Li;return}function i(){if(r.calledRun=!0,_e)return;tt(),de?.(r),r.onRuntimeInitialized?.(),Rr()}if(r.setStatus)r.setStatus("Running..."),setTimeout(()=>{setTimeout(()=>r.setStatus(""),1),i()},1);else i()}var tn=await Dh();if(Li(),r.runSQLite3PostLoadInit=async function(i,l,h){delete l.runSQLite3PostLoadInit,globalThis.sqlite3ApiBootstrap=async function f(c=globalThis.sqlite3ApiConfig||f.defaultConfig){if(f.sqlite3)return(f.sqlite3.config||console).warn("sqlite3ApiBootstrap() called multiple times.","Config and external initializers are ignored on calls after the first."),f.sqlite3;let d=(...S)=>Object.assign(Object.create(null),...S),p=d({exports:void 0,memory:void 0,bigIntEnabled:!!globalThis.BigInt64Array,debug:console.debug.bind(console),warn:console.warn.bind(console),error:console.error.bind(console),log:console.log.bind(console),wasmfsOpfsDir:"/opfs",useStdAlloc:!1},c);Object.assign(p,{allocExportName:p.useStdAlloc?"malloc":"sqlite3_malloc",deallocExportName:p.useStdAlloc?"free":"sqlite3_free",reallocExportName:p.useStdAlloc?"realloc":"sqlite3_realloc"}),["exports","memory","functionTable","wasmfsOpfsDir"].forEach((S)=>{if(typeof p[S]==="function")p[S]=p[S]()});let E=d(),b=d(),I=(S)=>E.sqlite3_js_rc_str&&E.sqlite3_js_rc_str(S)||"Unknown result code #"+S,V=(S)=>typeof S==="number"&&S===(S|0)&&S<=2147483647&&S>=-2147483648;class M extends Error{constructor(...S){let P;if(S.length)if(V(S[0]))if(P=S[0],S.length===1)super(I(S[0]));else{let K=I(P);if(typeof S[1]==="object")super(K,S[1]);else{S[0]=K+":";super(S.join(" "))}}else if(S.length===2&&typeof S[1]==="object")super(...S);else super(S.join(" "));this.resultCode=P||E.SQLITE_ERROR,this.name="SQLite3Error"}}M.toss=(...S)=>{throw new M(...S)};let C=M.toss;if(p.wasmfsOpfsDir&&!/^\/[^/]+$/.test(p.wasmfsOpfsDir))C("config.wasmfsOpfsDir must be falsy or in the form '/dir-name'.");let q=function S(P){if(!S._max)S._max=BigInt("0x7fffffffffffffff"),S._min=~S._max;return P>=S._min&&P<=S._max},H=(S)=>S>=-2147483647n-1n&&S<=2147483647n,G=function S(P){if(!S._min)S._min=Number.MIN_SAFE_INTEGER,S._max=Number.MAX_SAFE_INTEGER;return P>=S._min&&P<=S._max},le=(S)=>S&&S.constructor&&V(S.constructor.BYTES_PER_ELEMENT)?S:!1,O=(S)=>S&&(S instanceof Uint8Array||S instanceof Int8Array||S instanceof ArrayBuffer),R=(S)=>S&&(S instanceof Uint8Array||S instanceof Int8Array||S instanceof ArrayBuffer),X=(S)=>O(S)||C("Value is not of a supported TypedArray type."),ee=function(S){if(R(S))return b.typedArrayToString(S instanceof ArrayBuffer?new Uint8Array(S):S,0,S.length);else if(Array.isArray(S))return S.join("");else if(b.isPtr(S))S=b.cstrToJs(S);return S};class U extends Error{constructor(...S){if(S.length===2&&typeof S[1]==="object")super(...S);else if(S.length)super(S.join(" "));else super("Allocation failed.");this.resultCode=E.SQLITE_NOMEM,this.name="WasmAllocError"}}U.toss=(...S)=>{throw new U(...S)},Object.assign(E,{sqlite3_bind_blob:void 0,sqlite3_bind_text:void 0,sqlite3_create_function_v2:(S,P,K,oe,W,he,we,me,ve)=>{},sqlite3_create_function:(S,P,K,oe,W,he,we,me)=>{},sqlite3_create_window_function:(S,P,K,oe,W,he,we,me,ve,F)=>{},sqlite3_prepare_v3:(S,P,K,oe,W,he)=>{},sqlite3_prepare_v2:(S,P,K,oe,W)=>{},sqlite3_exec:(S,P,K,oe,W)=>{},sqlite3_randomness:(S,P)=>{}});let J={affirmBindableTypedArray:X,flexibleString:ee,bigIntFits32:H,bigIntFits64:q,bigIntFitsDouble:G,isBindableTypedArray:O,isInt32:V,isSQLableTypedArray:R,isTypedArray:le,isUIThread:()=>globalThis.window===globalThis&&!!globalThis.document,toss:function(...S){throw Error(S.join(" "))},toss3:C,typedArrayPart:b.typedArrayPart,nu:d,assert:function(S,P){if(!S)J.toss("Assertion failed:",P)},affirmDbHeader:function(S){if(S instanceof ArrayBuffer)S=new Uint8Array(S);let P="SQLite format 3";if(15>S.byteLength)C("Input does not contain an SQLite3 database header.");for(let K=0;K<15;++K)if(P.charCodeAt(K)!==S[K])C("Input does not contain an SQLite3 database header.")},affirmIsDb:function(S){if(S instanceof ArrayBuffer)S=new Uint8Array(S);let P=S.byteLength;if(P<512||P%512!==0)C("Byte array size",P,"is invalid for an SQLite3 db.");J.affirmDbHeader(S)}};Object.assign(b,{exports:p.exports||C("Missing API config.exports (WASM module exports)."),memory:p.memory||p.exports.memory||C("API config object requires a WebAssembly.Memory object","in either config.exports.memory (exported)","or config.memory (imported)."),pointerSize:typeof p.exports.sqlite3_libversion()==="number"?4:8,bigIntEnabled:!!p.bigIntEnabled,functionTable:p.functionTable,alloc:void 0,realloc:void 0,dealloc:void 0}),b.allocFromTypedArray=function(S){if(S instanceof ArrayBuffer)S=new Uint8Array(S);X(S);let P=b.alloc(S.byteLength||1);return b.heapForSize(S.constructor).set(S.byteLength?S:[0],Number(P)),P};{let{allocExportName:S,deallocExportName:P,reallocExportName:K}=p;for(let oe of[S,P,K])if(!(b.exports[oe]instanceof Function))C("Missing required exports[",oe,"] function.");b.alloc=function oe(W){return oe.impl(W)||U.toss("Failed to allocate",W," bytes.")},b.alloc.impl=b.exports[S],b.realloc=function oe(W,he){let we=oe.impl(b.ptr.coerce(W),he);return he?we||U.toss("Failed to reallocate",he," bytes."):b.ptr.null},b.realloc.impl=b.exports[K],b.dealloc=function oe(W){oe.impl(b.ptr.coerce(W))},b.dealloc.impl=b.exports[P]}b.compileOptionUsed=function S(P){if(!arguments.length){if(S._result)return S._result;else if(!S._opt)S._rx=/^([^=]+)=(.+)/,S._rxInt=/^-?\d+$/,S._opt=function(we,me){let ve=S._rx.exec(we);me[0]=ve?ve[1]:we,me[1]=ve?S._rxInt.test(ve[2])?+ve[2]:ve[2]:!0};let K=d(),oe=[0,0],W=0,he;while(he=E.sqlite3_compileoption_get(W++))S._opt(he,oe),K[oe[0]]=oe[1];return S._result=K}else if(Array.isArray(P)){let K=d();return P.forEach((oe)=>{K[oe]=E.sqlite3_compileoption_used(oe)}),K}else if(typeof P==="object")return Object.keys(P).forEach((K)=>{P[K]=E.sqlite3_compileoption_used(K)}),P;return typeof P==="string"?!!E.sqlite3_compileoption_used(P):!1},b.pstack=d({restore:b.exports.sqlite3__wasm_pstack_restore,alloc:function(S){if(typeof S==="string"&&!(S=b.sizeofIR(S)))U.toss("Invalid value for pstack.alloc(",arguments[0],")");return b.exports.sqlite3__wasm_pstack_alloc(S)||U.toss("Could not allocate",S,"bytes from the pstack.")},allocChunks:function(S,P){if(typeof P==="string"&&!(P=b.sizeofIR(P)))U.toss("Invalid size value for allocChunks(",arguments[1],")");let K=b.pstack.alloc(S*P),oe=[K],W=1,he=P;for(;W<S;++W,he+=P)oe.push(b.ptr.add(K,he));return oe},allocPtr:(S=1,P=!0)=>S===1?b.pstack.alloc(P?8:b.ptr.size):b.pstack.allocChunks(S,P?8:b.ptr.size),call:function(S){let P=b.pstack.pointer;try{return S(pe)}finally{b.pstack.restore(P)}}}),Object.defineProperties(b.pstack,{pointer:{configurable:!1,iterable:!0,writeable:!1,get:b.exports.sqlite3__wasm_pstack_ptr},quota:{configurable:!1,iterable:!0,writeable:!1,get:b.exports.sqlite3__wasm_pstack_quota},remaining:{configurable:!1,iterable:!0,writeable:!1,get:b.exports.sqlite3__wasm_pstack_remaining}}),E.sqlite3_randomness=(...S)=>{if(S.length===1&&J.isTypedArray(S[0])&&S[0].BYTES_PER_ELEMENT===1){let P=S[0];if(P.byteLength===0)return b.exports.sqlite3_randomness(0,b.ptr.null),P;let K=b.pstack.pointer;try{let oe=P.byteLength,W=0,he=b.exports.sqlite3_randomness,we=b.heap8u(),me=oe<512?oe:512,ve=b.pstack.alloc(me);do{let F=oe>me?me:oe;he(F,ve),P.set(b.typedArrayPart(we,ve,b.ptr.add(ve,F)),W),oe-=F,W+=F}while(oe>0)}catch(oe){p.error("Highly unexpected (and ignored!) exception in sqlite3_randomness():",oe)}finally{b.pstack.restore(K)}return P}b.exports.sqlite3_randomness(...S)},E.sqlite3_wasmfs_opfs_dir=function(){if(this.dir!==void 0)return this.dir;let S=p.wasmfsOpfsDir;if(!S||!globalThis.FileSystemHandle||!globalThis.FileSystemDirectoryHandle||!globalThis.FileSystemFileHandle||!b.exports.sqlite3__wasm_init_wasmfs)return this.dir="";try{if(S&&b.xCallWrapped("sqlite3__wasm_init_wasmfs","i32",["string"],S)===0)return this.dir=S;else return this.dir=""}catch(P){return this.dir=""}}.bind(d()),E.sqlite3_wasmfs_filename_is_persistent=function(S){let P=E.sqlite3_wasmfs_opfs_dir();return P&&S?S.startsWith(P+"/"):!1},E.sqlite3_js_db_uses_vfs=function(S,P,K=0){try{let oe=E.sqlite3_vfs_find(P);if(!oe)return!1;else if(!S)return oe===E.sqlite3_vfs_find(0)?oe:!1;else return oe===E.sqlite3_js_db_vfs(S,K)?oe:!1}catch(oe){return!1}},E.sqlite3_js_vfs_list=function(){let S=[],P=E.sqlite3_vfs_find(b.ptr.null);while(P){let K=new E.sqlite3_vfs(P);S.push(b.cstrToJs(K.$zName)),P=K.$pNext,K.dispose()}return S},E.sqlite3_js_db_export=function(S,P=0){if(S=b.xWrap.testConvertArg("sqlite3*",S),!S)C("Invalid sqlite3* argument.");if(!b.bigIntEnabled)C("BigInt support is not enabled.");let K=b.scopedAllocPush(),oe;try{let W=b.scopedAlloc(8+b.ptr.size),he=b.ptr.add(W,8),we=P?b.isPtr(P)?P:b.scopedAllocCString(""+P):b.ptr.null,me=b.exports.sqlite3__wasm_db_serialize(S,we,he,W,0);if(me)C("Database serialization failed with code",pe.capi.sqlite3_js_rc_str(me));oe=b.peekPtr(he);let ve=b.peek(W,"i64");return me=ve?b.heap8u().slice(Number(oe),Number(oe)+Number(ve)):new Uint8Array,me}finally{if(oe)b.exports.sqlite3_free(oe);b.scopedAllocPop(K)}},E.sqlite3_js_db_vfs=(S,P=b.ptr.null)=>J.sqlite3__wasm_db_vfs(S,P),E.sqlite3_js_aggregate_context=(S,P)=>E.sqlite3_aggregate_context(S,P)||(P?U.toss("Cannot allocate",P,"bytes for sqlite3_aggregate_context()"):0),E.sqlite3_js_posix_create_file=function(S,P,K){let oe;if(P&&b.isPtr(P))oe=P;else if(P instanceof ArrayBuffer||P instanceof Uint8Array){if(oe=b.allocFromTypedArray(P),arguments.length<3||!J.isInt32(K)||K<0)K=P.byteLength}else M.toss("Invalid 2nd argument for sqlite3_js_posix_create_file().");try{if(!J.isInt32(K)||K<0)M.toss("Invalid 3rd argument for sqlite3_js_posix_create_file().");let W=J.sqlite3__wasm_posix_create_file(S,oe,K);if(W)M.toss("Creation of file failed with sqlite3 result code",E.sqlite3_js_rc_str(W))}finally{if(oe&&oe!==P)b.dealloc(oe)}},E.sqlite3_js_vfs_create_file=function(S,P,K,oe){p.warn("sqlite3_js_vfs_create_file() is deprecated and","should be avoided because it can lead to C-level crashes.","See its documentation for alternatives.");let W;if(K)if(b.isPtr(K))W=K;else{if(K instanceof ArrayBuffer)K=new Uint8Array(K);if(K instanceof Uint8Array){if(W=b.allocFromTypedArray(K),arguments.length<4||!J.isInt32(oe)||oe<0)oe=K.byteLength}else M.toss("Invalid 3rd argument type for sqlite3_js_vfs_create_file().")}else W=0;if(!J.isInt32(oe)||oe<0){if(W&&W!==K)b.dealloc(W);M.toss("Invalid 4th argument for sqlite3_js_vfs_create_file().")}try{let he=J.sqlite3__wasm_vfs_create_file(S,P,W,oe);if(he)M.toss("Creation of file failed with sqlite3 result code",E.sqlite3_js_rc_str(he))}finally{if(W&&W!==K)b.dealloc(W)}},E.sqlite3_js_sql_to_string=(S)=>{if(typeof S==="string")return S;let P=ee(v);return P===v?void 0:P},E.sqlite3_db_config=function(S,P,...K){switch(P){case E.SQLITE_DBCONFIG_ENABLE_FKEY:case E.SQLITE_DBCONFIG_ENABLE_TRIGGER:case E.SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER:case E.SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION:case E.SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE:case E.SQLITE_DBCONFIG_ENABLE_QPSG:case E.SQLITE_DBCONFIG_TRIGGER_EQP:case E.SQLITE_DBCONFIG_RESET_DATABASE:case E.SQLITE_DBCONFIG_DEFENSIVE:case E.SQLITE_DBCONFIG_WRITABLE_SCHEMA:case E.SQLITE_DBCONFIG_LEGACY_ALTER_TABLE:case E.SQLITE_DBCONFIG_DQS_DML:case E.SQLITE_DBCONFIG_DQS_DDL:case E.SQLITE_DBCONFIG_ENABLE_VIEW:case E.SQLITE_DBCONFIG_LEGACY_FILE_FORMAT:case E.SQLITE_DBCONFIG_TRUSTED_SCHEMA:case E.SQLITE_DBCONFIG_STMT_SCANSTATUS:case E.SQLITE_DBCONFIG_REVERSE_SCANORDER:case E.SQLITE_DBCONFIG_ENABLE_ATTACH_CREATE:case E.SQLITE_DBCONFIG_ENABLE_ATTACH_WRITE:case E.SQLITE_DBCONFIG_ENABLE_COMMENTS:case E.SQLITE_DBCONFIG_FP_DIGITS:if(!this.ip)this.ip=b.xWrap("sqlite3__wasm_db_config_ip","int",["sqlite3*","int","int","*"]);return this.ip(S,P,K[0],K[1]||0);case E.SQLITE_DBCONFIG_LOOKASIDE:if(!this.pii)this.pii=b.xWrap("sqlite3__wasm_db_config_pii","int",["sqlite3*","int","*","int","int"]);return this.pii(S,P,K[0],K[1],K[2]);case E.SQLITE_DBCONFIG_MAINDBNAME:if(!this.s)this.s=b.xWrap("sqlite3__wasm_db_config_s","int",["sqlite3*","int","string:static"]);return this.s(S,P,K[0]);default:return E.SQLITE_MISUSE}}.bind(d()),E.sqlite3_value_to_js=function(S,P=!0){let K,oe=E.sqlite3_value_type(S);switch(oe){case E.SQLITE_INTEGER:if(b.bigIntEnabled){if(K=E.sqlite3_value_int64(S),J.bigIntFitsDouble(K))K=Number(K)}else K=E.sqlite3_value_double(S);break;case E.SQLITE_FLOAT:K=E.sqlite3_value_double(S);break;case E.SQLITE_TEXT:K=E.sqlite3_value_text(S);break;case E.SQLITE_BLOB:{let W=E.sqlite3_value_bytes(S),he=E.sqlite3_value_blob(S);if(W&&!he)pe.WasmAllocError.toss("Cannot allocate memory for blob argument of",W,"byte(s)");K=W?b.heap8u().slice(Number(he),Number(he)+Number(W)):null;break}case E.SQLITE_NULL:K=null;break;default:if(P)C(E.SQLITE_MISMATCH,"Unhandled sqlite3_value_type():",oe);K=void 0}return K},E.sqlite3_values_to_js=function(S,P,K=!0){let oe,W=[];for(oe=0;oe<S;++oe)W.push(E.sqlite3_value_to_js(b.peekPtr(b.ptr.add(P,b.ptr.size*oe)),K));return W},E.sqlite3_result_error_js=function(S,P){if(P instanceof U)E.sqlite3_result_error_nomem(S);else E.sqlite3_result_error(S,""+P,-1)},E.sqlite3_result_js=function(S,P){if(P instanceof Error){E.sqlite3_result_error_js(S,P);return}try{switch(typeof P){case"undefined":break;case"boolean":E.sqlite3_result_int(S,P?1:0);break;case"bigint":if(J.bigIntFits32(P))E.sqlite3_result_int(S,Number(P));else if(J.bigIntFitsDouble(P))E.sqlite3_result_double(S,Number(P));else if(b.bigIntEnabled)if(J.bigIntFits64(P))E.sqlite3_result_int64(S,P);else C("BigInt value",P.toString(),"is too BigInt for int64.");else C("BigInt value",P.toString(),"is too BigInt.");break;case"number":{let K;if(J.isInt32(P))K=E.sqlite3_result_int;else if(b.bigIntEnabled&&Number.isInteger(P)&&J.bigIntFits64(BigInt(P)))K=E.sqlite3_result_int64;else K=E.sqlite3_result_double;K(S,P);break}case"string":{let[K,oe]=b.allocCString(P,!0);E.sqlite3_result_text(S,K,oe,E.SQLITE_WASM_DEALLOC);break}case"object":if(P===null){E.sqlite3_result_null(S);break}else if(J.isBindableTypedArray(P)){let K=b.allocFromTypedArray(P);E.sqlite3_result_blob(S,K,P.byteLength,E.SQLITE_WASM_DEALLOC);break}default:C("Don't not how to handle this UDF result value:",typeof P,P)}}catch(K){E.sqlite3_result_error_js(S,K)}},E.sqlite3_column_js=function(S,P,K=!0){let oe=E.sqlite3_column_value(S,P);return oe===0?void 0:E.sqlite3_value_to_js(oe,K)};{let S=function(P,K,oe){if(oe=E[oe],!this.ptr)this.ptr=b.allocPtr();else b.pokePtr(this.ptr,0);let W=oe(P,K,this.ptr);if(W)return M.toss(W,arguments[2]+"() failed with code "+W);let he=b.peekPtr(this.ptr);return he?E.sqlite3_value_to_js(he,!0):void 0}.bind(d());E.sqlite3_preupdate_new_js=(P,K)=>S(P,K,"sqlite3_preupdate_new"),E.sqlite3_preupdate_old_js=(P,K)=>S(P,K,"sqlite3_preupdate_old"),E.sqlite3changeset_new_js=(P,K)=>S(P,K,"sqlite3changeset_new"),E.sqlite3changeset_old_js=(P,K)=>S(P,K,"sqlite3changeset_old")}E.sqlite3_js_retry_busy=function(S,P,K){for(let oe=1;oe<=S;++oe)try{if(K&&oe>1)K(oe);let W=P();if(E.SQLITE_BUSY===W){if(oe===S)throw new M(W,["sqlite3_js_retry_busy() max retry attempts (",S,") reached."].join(""));continue}return W}catch(W){if(oe<S&&W instanceof M&&W.resultCode===E.SQLITE_BUSY)continue;throw W}};let pe={WasmAllocError:U,SQLite3Error:M,capi:E,util:J,wasm:b,config:p,version:d(),client:void 0,asyncPostInit:async function S(){if(S.isReady instanceof Promise)return S.isReady;let P=this.initializersAsync;delete this.initializersAsync;let K=async()=>{if(!pe.__isUnderTest)delete pe.util,delete pe.StructBinder,delete pe.opfs;return pe},oe=(he)=>{throw p.error("an async sqlite3 initializer failed:",he),he};if(!P||!P.length)return S.isReady=K().catch(oe);P=P.map((he)=>he instanceof Function?async(we)=>he(pe):he),P.push(K);let W=Promise.resolve(pe);while(P.length)W=W.then(P.shift());return S.isReady=W.catch(oe)}.bind(f),scriptInfo:void 0};if(typeof h<"u")pe.__isUnderTest=!!h;try{f.initializers.forEach((S)=>{S(pe)})}catch(S){throw console.error("sqlite3 bootstrap initializer threw:",S),S}if(delete f.initializers,f.sqlite3=pe,typeof i<"u")i.debugModule("sqlite3ApiBootstrap() complete",pe),pe.scriptInfo=i;if(pe.__isUnderTest){if(typeof l<"u")pe.config.emscripten=l;let S=pe.scriptInfo?.instantiateWasm;if(S)pe.wasm.module=S.module,pe.wasm.instance=S.instance,pe.wasm.imports=S.imports}return delete globalThis.sqlite3ApiConfig,delete globalThis.sqlite3ApiBootstrap,delete f.defaultConfig,pe.asyncPostInit().then((S)=>{if(typeof i<"u")i.debugModule("sqlite3.asyncPostInit() complete",S);return delete S.asyncPostInit,delete S.scriptInfo,delete S.emscripten,S})},globalThis.sqlite3ApiBootstrap.initializers=[],globalThis.sqlite3ApiBootstrap.initializersAsync=[],globalThis.sqlite3ApiBootstrap.defaultConfig=Object.create(null),globalThis.sqlite3ApiBootstrap.sqlite3=void 0,globalThis.sqlite3ApiBootstrap.initializers.push(function(f){f.version={libVersion:"3.53.0",libVersionNumber:3053000,sourceId:"2026-04-09 11:41:38 4525003a53a7fc63ca75c59b22c79608659ca12f0131f52c18637f829977f20b",downloadVersion:3530000,scm:{"sha3-256":"4525003a53a7fc63ca75c59b22c79608659ca12f0131f52c18637f829977f20b",branch:"trunk",tags:"release major-release version-3.53.0",datetime:"2026-04-09T11:41:38.498Z"}}}),globalThis.WhWasmUtilInstaller=function(c){if(c.bigIntEnabled===void 0)c.bigIntEnabled=!!globalThis.BigInt64Array;let d=(...g)=>{throw Error(g.join(" "))};if(!c.pointerSize&&!c.pointerIR&&c.alloc&&c.dealloc){let g=c.alloc(1);c.pointerSize=typeof g==="bigint"?8:4,c.dealloc(g)}if(c.pointerSize&&!c.pointerIR)c.pointerIR=c.pointerSize===4?"i32":"i64";let p=c.pointerIR??="i32",E=c.pointerSize??=p==="i32"?4:p==="i64"?8:0;if(delete c.pointerSize,delete c.pointerIR,p!=="i32"&&p!=="i64")d("Invalid pointerIR:",p);else if(E!==8&&E!==4)d("Invalid pointerSize:",E);let b=c.bigIntEnabled?(g)=>BigInt(g||0):(g)=>d("BigInt support is disabled in this build."),V=E===4?(g)=>Number(g||0):b,M=V(0),C=function(...g){let w=V(0);for(let T of g)w+=V(T);return w};{let g=Object.create(null);Object.defineProperty(c,"ptr",{enumerable:!0,get:()=>g,set:()=>d("The ptr property is read-only.")}),function w(T,N){return Object.defineProperty(g,T,{enumerable:!0,get:()=>N,set:()=>d("ptr["+T+"] is read-only.")}),w}("null",M)("size",E)("ir",p)("coerce",V)("add",C)("addn",p===4?C:(...w)=>Number(C(...w)))}if(!c.exports)Object.defineProperty(c,"exports",{enumerable:!0,configurable:!0,get:()=>c.instance?.exports});let q=Object.create(null);q.heapSize=0,q.memory=null,q.freeFuncIndexes=[],q.scopedAlloc=[],q.scopedAlloc.pushPtr=(g)=>(q.scopedAlloc[q.scopedAlloc.length-1].push(g),g),q.utf8Decoder=new TextDecoder,q.utf8Encoder=new TextEncoder("utf-8"),c.sizeofIR=(g)=>{switch(g){case"i8":return 1;case"i16":return 2;case"i32":case"f32":case"float":return 4;case"i64":case"f64":case"double":return 8;case"*":return E;default:return(""+g).endsWith("*")?E:void 0}};let H=function(){if(!q.memory)q.memory=c.memory instanceof WebAssembly.Memory?c.memory:c.exports.memory;else if(q.heapSize===q.memory.buffer.byteLength)return q;let g=q.memory.buffer;if(q.HEAP8=new Int8Array(g),q.HEAP8U=new Uint8Array(g),q.HEAP16=new Int16Array(g),q.HEAP16U=new Uint16Array(g),q.HEAP32=new Int32Array(g),q.HEAP32U=new Uint32Array(g),q.HEAP32F=new Float32Array(g),q.HEAP64F=new Float64Array(g),c.bigIntEnabled)if(typeof BigInt64Array<"u")q.HEAP64=new BigInt64Array(g),q.HEAP64U=new BigUint64Array(g);else d("BigInt support is enabled, but the BigInt64Array type is missing.");return q.heapSize=g.byteLength,q};c.heap8=()=>H().HEAP8,c.heap8u=()=>H().HEAP8U,c.heap16=()=>H().HEAP16,c.heap16u=()=>H().HEAP16U,c.heap32=()=>H().HEAP32,c.heap32u=()=>H().HEAP32U,c.heapForSize=function(g,w=!0){let T=q.memory&&q.heapSize===q.memory.buffer.byteLength?q:H();switch(g){case Int8Array:return T.HEAP8;case Uint8Array:return T.HEAP8U;case Int16Array:return T.HEAP16;case Uint16Array:return T.HEAP16U;case Int32Array:return T.HEAP32;case Uint32Array:return T.HEAP32U;case 8:return w?T.HEAP8U:T.HEAP8;case 16:return w?T.HEAP16U:T.HEAP16;case 32:return w?T.HEAP32U:T.HEAP32;case 64:if(T.HEAP64)return w?T.HEAP64U:T.HEAP64;break;default:if(c.bigIntEnabled){if(g===globalThis.BigUint64Array)return T.HEAP64U;else if(g===globalThis.BigInt64Array)return T.HEAP64;break}}d("Invalid heapForSize() size: expecting 8, 16, 32,","or (if BigInt is enabled) 64.")};let G=c.functionTable;delete c.functionTable,c.functionTable=G?()=>G:()=>c.exports.__indirect_function_table,c.functionEntry=function(g){let w=c.functionTable();return g<w.length?w.get(V(g)):void 0},c.jsFuncToWasm=function g(w,T){if(!g._)g._={sigTypes:Object.assign(Object.create(null),{i:"i32",p,P:p,s:p,j:"i64",f:"f32",d:"f64"}),typeCodes:Object.assign(Object.create(null),{f64:124,f32:125,i64:126,i32:127}),uleb128Encode:(A,L,Q)=>{if(Q<128)A[L](Q);else A[L](Q%128|128,Q>>7)},rxJSig:/^(\w)\((\w*)\)$/,sigParams:(A)=>{let L=g._.rxJSig.exec(A);return L?L[2]:A.substr(1)},letterType:(A)=>g._.sigTypes[A]||d("Invalid signature letter:",A),pushSigType:(A,L)=>A.push(g._.typeCodes[g._.letterType(L)])};if(typeof w==="string"){let A=T;T=w,w=A}let N=g._,te=N.sigParams(T),se=[1,96];N.uleb128Encode(se,"push",te.length);for(let A of te)N.pushSigType(se,A);if(T[0]==="v")se.push(0);else se.push(1),N.pushSigType(se,T[0]);return N.uleb128Encode(se,"unshift",se.length),se.unshift(0,97,115,109,1,0,0,0,1),se.push(2,7,1,1,101,1,102,0,0,7,5,1,1,102,0,0),new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array(se)),{e:{f:w}}).exports.f};let le=function(w,T,N){if(N&&!q.scopedAlloc.length)d("No scopedAllocPush() scope is active.");if(typeof w==="string"){let L=T;T=w,w=L}if(typeof T!=="string"||!(w instanceof Function))d("Invalid arguments: expecting (function,signature) or (signature,function).");let te=c.functionTable(),se=V(te.length),A;while(A=q.freeFuncIndexes.pop())if(te.get(A)){A=null;continue}else break;if(!A)A=V(se),te.grow(V(1));try{if(te.set(A,w),N)q.scopedAlloc.pushPtr(A);return A}catch(L){if(!(L instanceof TypeError)){if(A===se)q.freeFuncIndexes.push(se);throw L}}try{let L=c.jsFuncToWasm(w,T);if(te.set(A,L),N)q.scopedAlloc.pushPtr(A)}catch(L){if(A===se)q.freeFuncIndexes.push(se);throw L}return A};c.installFunction=(g,w)=>le(g,w,!1),c.scopedInstallFunction=(g,w)=>le(g,w,!0),c.uninstallFunction=function(g){if(!g&&M!==g)return;let w=c.functionTable();q.freeFuncIndexes.push(g);let T=w.get(g);return w.set(g,null),T},c.peek=function(w,T="i8"){if(T.endsWith("*"))T=p;let N=q.memory&&q.heapSize===q.memory.buffer.byteLength?q:H(),te=Array.isArray(w)?[]:void 0,se;do{if(te)w=arguments[0].shift();switch(T){case"i1":case"i8":se=N.HEAP8[Number(w)>>0];break;case"i16":se=N.HEAP16[Number(w)>>1];break;case"i32":se=N.HEAP32[Number(w)>>2];break;case"float":case"f32":se=N.HEAP32F[Number(w)>>2];break;case"double":case"f64":se=Number(N.HEAP64F[Number(w)>>3]);break;case"i64":if(N.HEAP64){se=b(N.HEAP64[Number(w)>>3]);break}default:d("Invalid type for peek():",T)}if(te)te.push(se)}while(te&&arguments[0].length);return te||se},c.poke=function(g,w,T="i8"){if(T.endsWith("*"))T=p;let N=q.memory&&q.heapSize===q.memory.buffer.byteLength?q:H();for(let te of Array.isArray(g)?g:[g])switch(T){case"i1":case"i8":N.HEAP8[Number(te)>>0]=w;continue;case"i16":N.HEAP16[Number(te)>>1]=w;continue;case"i32":N.HEAP32[Number(te)>>2]=w;continue;case"float":case"f32":N.HEAP32F[Number(te)>>2]=w;continue;case"double":case"f64":N.HEAP64F[Number(te)>>3]=w;continue;case"i64":if(N.HEAP64){N.HEAP64[Number(te)>>3]=b(w);continue}default:d("Invalid type for poke(): "+T)}return this},c.peekPtr=(...g)=>c.peek(g.length===1?g[0]:g,p),c.pokePtr=(g,w=0)=>c.poke(g,w,p),c.peek8=(...g)=>c.peek(g.length===1?g[0]:g,"i8"),c.poke8=(g,w)=>c.poke(g,w,"i8"),c.peek16=(...g)=>c.peek(g.length===1?g[0]:g,"i16"),c.poke16=(g,w)=>c.poke(g,w,"i16"),c.peek32=(...g)=>c.peek(g.length===1?g[0]:g,"i32"),c.poke32=(g,w)=>c.poke(g,w,"i32"),c.peek64=(...g)=>c.peek(g.length===1?g[0]:g,"i64"),c.poke64=(g,w)=>c.poke(g,w,"i64"),c.peek32f=(...g)=>c.peek(g.length===1?g[0]:g,"f32"),c.poke32f=(g,w)=>c.poke(g,w,"f32"),c.peek64f=(...g)=>c.peek(g.length===1?g[0]:g,"f64"),c.poke64f=(g,w)=>c.poke(g,w,"f64"),c.getMemValue=c.peek,c.getPtrValue=c.peekPtr,c.setMemValue=c.poke,c.setPtrValue=c.pokePtr,c.isPtr32=(g)=>typeof g==="number"&&g>=0&&g===(g|0),c.isPtr64=(g)=>typeof g==="bigint"?g>=0:c.isPtr32(g),c.isPtr=E===4?c.isPtr32:c.isPtr64,c.cstrlen=function(g){if(!g||!c.isPtr(g))return null;g=Number(g);let w=H().HEAP8U,T=g;for(;w[T]!==0;++T);return T-g};let O=typeof SharedArrayBuffer>"u"?function(){}:SharedArrayBuffer,R=(g)=>g.buffer instanceof O;c.isSharedTypedArray=R;let X=(g,w,T)=>{if(E===8){if(typeof w==="bigint")w=Number(w);if(typeof T==="bigint")T=Number(T)}return R(g)?g.slice(w,T):g.subarray(w,T)};c.typedArrayPart=X;let ee=(g,w,T)=>q.utf8Decoder.decode(X(g,w,T));c.typedArrayToString=ee,c.cstrToJs=function(g){let w=c.cstrlen(g);return w?ee(H().HEAP8U,Number(g),Number(g)+w):w===null?w:""},c.jstrlen=function(g){if(typeof g!=="string")return null;let w=g.length,T=0;for(let N=0;N<w;++N){let te=g.charCodeAt(N);if(te>=55296&&te<=57343)te=65536+((te&1023)<<10)|g.charCodeAt(++N)&1023;if(te<=127)++T;else if(te<=2047)T+=2;else if(te<=65535)T+=3;else T+=4}return T},c.jstrcpy=function(g,w,T=0,N=-1,te=!0){if(!w||!(w instanceof Int8Array)&&!(w instanceof Uint8Array))d("jstrcpy() target must be an Int8Array or Uint8Array.");if(N=Number(N),T=Number(T),N<0)N=w.length-T;if(!(N>0)||!(T>=0))return 0;let se=0,A=g.length,L=T,Q=T+N-(te?1:0);for(;se<A&&T<Q;++se){let ne=g.charCodeAt(se);if(ne>=55296&&ne<=57343)ne=65536+((ne&1023)<<10)|g.charCodeAt(++se)&1023;if(ne<=127){if(T>=Q)break;w[T++]=ne}else if(ne<=2047){if(T+1>=Q)break;w[T++]=192|ne>>6,w[T++]=128|ne&63}else if(ne<=65535){if(T+2>=Q)break;w[T++]=224|ne>>12,w[T++]=128|ne>>6&63,w[T++]=128|ne&63}else{if(T+3>=Q)break;w[T++]=240|ne>>18,w[T++]=128|ne>>12&63,w[T++]=128|ne>>6&63,w[T++]=128|ne&63}}if(te)w[T++]=0;return T-L},c.cstrncpy=function(g,w,T){if(!g||!w)d("cstrncpy() does not accept NULL strings.");if(T<0)T=c.cstrlen(strPtr)+1;else if(!(T>0))return 0;let N=c.heap8u(),te=0,se,A=Number(g),L=Number(w);for(;te<T&&(se=N[L+te]);++te)N[A+te]=se;if(te<T)N[A+te++]=0;return te},c.jstrToUintArray=(g,w=!1)=>q.utf8Encoder.encode(w?g+"\x00":g);let U=(g,w)=>{if(!(g.alloc instanceof Function)||!(g.dealloc instanceof Function))d("Object is missing alloc() and/or dealloc() function(s)","required by",w+"().")},J=function(g,w,T,N){if(U(c,N),typeof g!=="string")return null;let te=q.utf8Encoder.encode(g),se=T(te.length+1),A=se;try{let L=H().HEAP8U;return L.set(te,Number(se)),L[C(se,te.length)]=0,A=M,w?[se,te.length]:se}finally{if(A)c.dealloc(A)}};c.allocCString=(g,w=!1)=>J(g,w,c.alloc,"allocCString()"),c.scopedAllocPush=function(){U(c,"scopedAllocPush");let g=[];return q.scopedAlloc.push(g),g},c.scopedAllocPop=function(g){U(c,"scopedAllocPop");let w=arguments.length?q.scopedAlloc.indexOf(g):q.scopedAlloc.length-1;if(w<0)d("Invalid state object for scopedAllocPop().");if(arguments.length===0)g=q.scopedAlloc[w];q.scopedAlloc.splice(w,1);for(let T;T=g.pop();)if(c.functionEntry(T))c.uninstallFunction(T);else c.dealloc(T)},c.scopedAlloc=function(g){if(!q.scopedAlloc.length)d("No scopedAllocPush() scope is active.");let w=V(c.alloc(g));return q.scopedAlloc.pushPtr(w)},Object.defineProperty(c.scopedAlloc,"level",{configurable:!1,enumerable:!1,get:()=>q.scopedAlloc.length,set:()=>d("The 'active' property is read-only.")}),c.scopedAllocCString=(g,w=!1)=>J(g,w,c.scopedAlloc,"scopedAllocCString()");let pe=function(g,w){let T=c[g?"scopedAlloc":"alloc"]((w.length+1)*c.ptr.size),N=0;return w.forEach((te)=>{c.pokePtr(C(T,c.ptr.size*N++),c[g?"scopedAllocCString":"allocCString"](""+te))}),c.pokePtr(C(T,c.ptr.size*N),0),T};c.scopedAllocMainArgv=(g)=>pe(!0,g),c.allocMainArgv=(g)=>pe(!1,g),c.cArgvToJs=(g,w)=>{let T=[];for(let N=0;N<g;++N){let te=c.peekPtr(C(w,c.ptr.size*N));T.push(te?c.cstrToJs(te):null)}return T},c.scopedAllocCall=function(g){c.scopedAllocPush();try{return g()}finally{c.scopedAllocPop()}};let S=function(g,w,T){U(c,T);let N=w?"i64":p,te=c[T](g*(w?8:E));if(c.poke(te,0,N),g===1)return te;let se=[te];for(let A=1;A<g;++A)te=C(te,w?8:E),se[A]=te,c.poke(te,0,N);return se};c.allocPtr=(g=1,w=!0)=>S(g,w,"alloc"),c.scopedAllocPtr=(g=1,w=!0)=>S(g,w,"scopedAlloc"),c.xGet=function(g){return c.exports[g]||d("Cannot find exported symbol:",g)};let P=(g,w)=>d(g+"() requires",w,"argument(s).");c.xCall=function(g,...w){let T=g instanceof Function?g:c.xGet(g);if(!(T instanceof Function))d("Exported symbol",g,"is not a function.");if(T.length!==w.length)P(T===g?T.name:g,T.length);return arguments.length===2&&Array.isArray(arguments[1])?T.apply(null,arguments[1]):T.apply(null,w)},q.xWrap=Object.create(null),q.xWrap.convert=Object.create(null),q.xWrap.convert.arg=new Map,q.xWrap.convert.result=new Map;let K=q.xWrap.convert.arg,oe=q.xWrap.convert.result,W=V;K.set("i64",b).set("i32",(g)=>g|0).set("i16",(g)=>(g|0)&65535).set("i8",(g)=>(g|0)&255).set("f32",(g)=>Number(g).valueOf()).set("float",K.get("f32")).set("f64",K.get("f32")).set("double",K.get("f64")).set("int",K.get("i32")).set("null",(g)=>g).set(null,K.get("null")).set("**",W).set("*",W),oe.set("*",W).set("pointer",W).set("number",(g)=>Number(g)).set("void",(g)=>{return}).set(void 0,oe.get("void")).set("null",(g)=>g).set(null,oe.get("null"));for(let g of["i8","i16","i32","i64","int","f32","float","f64","double"])K.set(g+"*",W),oe.set(g+"*",W),oe.set(g,K.get(g)||d("Maintenance required: missing arg converter for",g));let he=(g)=>typeof g==="string"?c.scopedAllocCString(g):V(g);K.set("string",he).set("utf8",he),oe.set("string",(g)=>c.cstrToJs(g)).set("utf8",oe.get("string")).set("string:dealloc",(g)=>{try{return g?c.cstrToJs(g):null}finally{c.dealloc(g)}}).set("utf8:dealloc",oe.get("string:dealloc")).set("json",(g)=>JSON.parse(c.cstrToJs(g))).set("json:dealloc",(g)=>{try{return g?JSON.parse(c.cstrToJs(g)):null}finally{c.dealloc(g)}});let we=class{constructor(g){this.name=g.name||"unnamed adapter"}convertArg(g,w,T){d("AbstractArgAdapter must be subclassed.")}};K.FuncPtrAdapter=class g extends we{constructor(w){super(w);if(K.FuncPtrAdapter.warnOnUse)console.warn("xArg.FuncPtrAdapter is an internal-only API","and is not intended to be invoked from","client-level code. Invoked with:",w);if(this.name=w.name||"unnamed",this.signature=w.signature,w.contextKey instanceof Function){if(this.contextKey=w.contextKey,!w.bindScope)w.bindScope="context"}if(this.bindScope=w.bindScope||d("FuncPtrAdapter options requires a bindScope (explicit or implied)."),g.bindScopes.indexOf(w.bindScope)<0)d("Invalid options.bindScope ("+w.bindMod+") for FuncPtrAdapter. Expecting one of: ("+g.bindScopes.join(", ")+")");this.isTransient=this.bindScope==="transient",this.isContext=this.bindScope==="context",this.isPermanent=this.bindScope==="permanent",this.singleton=this.bindScope==="singleton"?[]:void 0,this.callProxy=w.callProxy instanceof Function?w.callProxy:void 0}contextKey(w,T){return this}contextMap(w){let T=this.__cmap||(this.__cmap=new Map),N=T.get(w);if(N===void 0)T.set(w,N=[]);return N}convertArg(w,T,N){let te=this.singleton;if(!te&&this.isContext)te=this.contextMap(this.contextKey(T,N));if(te&&te.length===2&&te[0]===w)return te[1];if(w instanceof Function){if(this.callProxy)w=this.callProxy(w);let se=le(w,this.signature,this.isTransient);if(g.debugFuncInstall)g.debugOut("FuncPtrAdapter installed",this,this.contextKey(T,N),"@"+se,w);if(te){if(te[1]){if(g.debugFuncInstall)g.debugOut("FuncPtrAdapter uninstalling",this,this.contextKey(T,N),"@"+te[1],w);try{q.scopedAlloc.pushPtr(te[1])}catch(A){}}te[0]=arguments[0]||M,te[1]=se}return se}else if(c.isPtr(w)||w===null||w===void 0){if(te&&te[1]&&te[1]!==w){if(g.debugFuncInstall)g.debugOut("FuncPtrAdapter uninstalling",this,this.contextKey(T,N),"@"+te[1],w);try{q.scopedAlloc.pushPtr(te[1])}catch(se){}te[0]=te[1]=w||M}return w||M}else throw TypeError("Invalid FuncPtrAdapter argument type. Expecting a function pointer or a "+(this.name?this.name+" ":"")+"function matching signature "+this.signature+".")}},K.FuncPtrAdapter.warnOnUse=!1,K.FuncPtrAdapter.debugFuncInstall=!1,K.FuncPtrAdapter.debugOut=console.debug.bind(console),K.FuncPtrAdapter.bindScopes=["transient","context","singleton","permanent"];let me=(g)=>K.get(g)||d("Argument adapter not found:",g),ve=(g)=>oe.get(g)||d("Result adapter not found:",g);q.xWrap.convertArg=(g,...w)=>me(g)(...w),q.xWrap.convertArgNoCheck=(g,...w)=>K.get(g)(...w),q.xWrap.convertResult=(g,w)=>g===null?w:g?ve(g)(w):void 0,q.xWrap.convertResultNoCheck=(g,w)=>g===null?w:g?oe.get(g)(w):void 0,c.xWrap=function g(w,T,...N){if(arguments.length===3&&Array.isArray(arguments[2]))N=arguments[2];if(c.isPtr(w))w=c.functionEntry(w)||d("Function pointer not found in WASM function table.");let te=w instanceof Function,se=te?w:c.xGet(w);if(te)w=se.name||"unnamed function";if(N.length!==se.length)P(w,se.length);if(se.length===0&&(T===null||T==="null"))return se;ve(T);for(let L of N)if(L instanceof we)K.set(L,(...Q)=>L.convertArg(...Q));else me(L);let A=q.xWrap;if(se.length===0)return(...L)=>L.length?P(w,se.length):A.convertResult(T,se.call(null));return function(...L){if(L.length!==se.length)P(w,se.length);let Q=c.scopedAllocPush();try{let ne=0;if(g.debug)console.debug("xWrap() preparing: resultType ",T,"xf",se,"argTypes",N,"args",L);for(;ne<L.length;++ne)L[ne]=A.convertArgNoCheck(N[ne],L[ne],L,ne);if(g.debug)console.debug("xWrap() calling: resultType ",T,"xf",se,"argTypes",N,"args",L);return A.convertResultNoCheck(T,se.apply(null,L))}finally{c.scopedAllocPop(Q)}}};let F=function(g,w,T,N,te,se){if(typeof T==="string"){if(w===1)return se.get(T);else if(w===2){if(!N)return se.delete(T),g;else if(!(N instanceof Function))d(te,"requires a function argument.");return se.set(T,N),g}}d("Invalid arguments to",te)};return c.xWrap.resultAdapter=function g(w,T){return F(g,arguments.length,w,T,"resultAdapter()",oe)},c.xWrap.argAdapter=function g(w,T){return F(g,arguments.length,w,T,"argAdapter()",K)},c.xWrap.FuncPtrAdapter=K.FuncPtrAdapter,c.xCallWrapped=function(g,w,T,...N){if(Array.isArray(arguments[3]))N=arguments[3];return c.xWrap(g,w,T||[]).apply(null,N||[])},c.xWrap.testConvertArg=q.xWrap.convertArg,c.xWrap.testConvertResult=q.xWrap.convertResult,c},globalThis.WhWasmUtilInstaller.yawl=function(c){let d=()=>fetch(c.uri,{credentials:"same-origin"}),p=this,E=function(b){if(c.wasmUtilTarget){let I=(...M)=>{throw Error(M.join(" "))},V=c.wasmUtilTarget;if(V.module=b.module,V.instance=b.instance,!V.instance.exports.memory)V.memory=c?.imports?.env?.memory||I("Missing 'memory' object!");if(!V.alloc&&b.instance.exports.malloc){let M=b.instance.exports;V.alloc=function(C){return M.malloc(C)||I("Allocation of",C,"bytes failed.")},V.dealloc=function(C){C&&M.free(C)}}p(V)}if(b.config=c,c.onload)c.onload(b);return b};return WebAssembly.instantiateStreaming?()=>WebAssembly.instantiateStreaming(d(),c.imports||{}).then(E):()=>d().then((b)=>b.arrayBuffer()).then((b)=>WebAssembly.instantiate(b,c.imports||{})).then(E)}.bind(globalThis.WhWasmUtilInstaller),globalThis.Jaccwabyt=function f(c){let d=(...z)=>{throw Error(z.join(" "))};{let z=c.heap;if(z instanceof WebAssembly.Memory)z=function(){return new Uint8Array(this.buffer)}.bind(z);else if(!(z instanceof Function))d("config.heap must be WebAssembly.Memory instance or","a function which returns one.");c.heap=z}["alloc","dealloc"].forEach(function(z){c[z]instanceof Function||d("Config option '"+z+"' must be a function.")});let p=f,{heap:E,alloc:b,dealloc:I}=c;c.realloc;let V=c.log||console.debug.bind(console),M=c.memberPrefix||"",C=c.memberSuffix||"",{BigInt:q,BigInt64Array:H}=globalThis,G=c.bigIntEnabled??!!H,le,O=c.pointerSize||c.ptrSize||(typeof(le=b(1))==="bigint"?8:4),R=c.pointerIR||c.ptrIR||(O===4?"i32":"i64");if(le)I(le),le=void 0;if(O!==4&&O!==8)d("Invalid pointer size:",O);if(R!=="i32"&&R!=="i64")d("Invalid pointer representation:",R);let X=G&&q?(z)=>q(z||0):(z)=>d("BigInt support is disabled in this build."),ee=R=="i32"?Number:X,U=ee(0),J=function(...z){let ie=U;for(let fe=0;fe<z.length;++fe)ie+=ee(z[fe]);return ie},pe=function(...z){return J(this.pointer,...z)};if(!p.debugFlags)p.__makeDebugFlags=function(z=null){if(z&&z.__flags)z=z.__flags;let ie=function fe(Ee){if(arguments.length===0)return fe.__flags;if(Ee<0)delete fe.__flags.getter,delete fe.__flags.setter,delete fe.__flags.alloc,delete fe.__flags.dealloc;else fe.__flags.getter=(1&Ee)!==0,fe.__flags.setter=(2&Ee)!==0,fe.__flags.alloc=(4&Ee)!==0,fe.__flags.dealloc=(8&Ee)!==0;return fe._flags};if(Object.defineProperty(ie,"__flags",{iterable:!1,writable:!1,value:Object.create(z)}),!z)ie(0);return ie},p.debugFlags=p.__makeDebugFlags();let S=!0,P=(z)=>z[1]==="(",K=(z)=>z==="p"||z==="P"||z==="s",oe=(z)=>z==="P",W=(z)=>z?P(z)?"p":z[0]:void 0,he=function(z){switch(W(z)){case"c":case"C":return"i8";case"i":return"i32";case"p":case"P":case"s":return R;case"j":return"i64";case"f":return"float";case"d":return"double"}d("Unhandled signature IR:",z)},we=function(z){switch(W(z)){case"c":case"C":return 1;case"i":return 4;case"p":case"P":case"s":return O;case"j":return 8;case"f":return 4;case"d":return 8}d("Unhandled signature sizeof:",z)},me=H?()=>!0:()=>d("BigInt64Array is not available."),ve=function(z){switch(W(z)){case"p":case"P":case"s":switch(O){case 4:return"getInt32";case 8:return me()&&"getBigInt64"}break;case"i":return"getInt32";case"c":return"getInt8";case"C":return"getUint8";case"j":return me()&&"getBigInt64";case"f":return"getFloat32";case"d":return"getFloat64"}d("Unhandled DataView getter for signature:",z)},F=function(z){switch(W(z)){case"p":case"P":case"s":switch(O){case 4:return"setInt32";case 8:return me()&&"setBigInt64"}break;case"i":return"setInt32";case"c":return"setInt8";case"C":return"setUint8";case"j":return me()&&"setBigInt64";case"f":return"setFloat32";case"d":return"setFloat64"}d("Unhandled DataView setter for signature:",z)},g=function(z){switch(W(z)){case"i":case"f":case"c":case"C":case"d":return Number;case"j":return X;case"p":case"P":case"s":switch(O){case 4:return Number;case 8:return X}break}d("Unhandled DataView set wrapper for signature:",z)},w=(z,ie)=>z+"::"+ie,T=function(z,ie){return()=>d(w(z,ie),"is read-only.")},N=function z(ie,fe=!0){let Ee=z.map.get(ie);if(!Ee&&fe)z.map.set(ie,Ee=z.create(ie));return Ee};N.map=new WeakMap,N.create=(z)=>Object.assign(Object.create(null),{o:z,p:void 0,ownsPointer:!1,zod:!1,xb:0});let te=(z)=>N.map.delete(z),se=(z)=>typeof z==="number"&&z===(z|0)&&z>=0,L=O===4?se:(z)=>typeof z==="bigint"&&z>=0||se(z),Q=(z)=>L(z)&&z>0,ne=function(z,ie,fe){let Ee=N(ie,!1);if(!Ee)return;if(te(ie),!fe&&!(fe=Ee.p)){console.warn("Cannot(?) happen: __freeStruct() found no instanceInfo");return}if(Array.isArray(ie.ondispose)){let Ae;while(Ae=ie.ondispose.pop())try{if(Ae instanceof Function)Ae.call(ie);else if(Ae instanceof At)Ae.dispose();else if(L(Ae))I(Ae)}catch(Ke){console.warn("ondispose() for",z.structName,"@",fe,"threw. NOT propagating it.",Ke)}}else if(ie.ondispose instanceof Function)try{ie.ondispose()}catch(Ae){console.warn("ondispose() for",z.structName,"@",fe,"threw. NOT propagating it.",Ae)}if(delete ie.ondispose,z.debugFlags.__flags.dealloc)V("debug.dealloc:",Ee.ownsPointer?"":"EXTERNAL",z.structName,"instance:",z.structInfo.sizeof,"bytes @"+fe);if(Ee.ownsPointer){if(Ee.zod||z.structInfo.zeroOnDispose)E().fill(0,Number(fe),Number(fe)+z.structInfo.sizeof+Ee.xb);I(fe)}},ye=()=>({configurable:!1,writable:!1,iterable:!1}),Te=(z)=>({...ye(),value:z}),Ie=function(ie,fe,Ee){let Ae,Ke=(We)=>{Q(We)||d("Invalid pointer value",arguments[0],"for",ie.structName,"constructor.")};if(arguments.length>=3)if(Ee&&typeof Ee==="object")Ae=Ee,Ee=Ae?.wrap;else Ke(Ee),Ae={wrap:Ee};else Ae={};let ft=!Ee,xt=0,Dt=!1;if(Ee)Ke(Ee),Dt=!!Ae?.takeOwnership;else{let We=Ae?.extraBytes??0;if(We<0||We!==(We|0))d("Invalid extraBytes value:",Ae?.extraBytes);xt=ie.structInfo.sizeof+We,Ee=b(xt)||d("Allocation of",ie.structName,"structure failed."),Dt=!0}try{if(Ae?.debugFlags)fe.debugFlags(Ae.debugFlags);if(ie.debugFlags.__flags.alloc)V("debug.alloc:",ft?"":"EXTERNAL",ie.structName,"instance:",ie.structInfo.sizeof,"bytes @"+Ee);if(ft)E().fill(0,Number(Ee),Number(Ee)+xt);let We=N(fe);if(We.p=Ee,We.ownsPointer=Dt,We.xb=xt?xt-ie.structInfo.sizeof:0,We.zod=!!Ae?.zeroOnDispose,Ae?.ondispose&&Ae.ondispose!==Ee)fe.addOnDispose(Ae.ondispose)}catch(We){throw ne(ie,fe,Ee),We}},qe=function z(ie){return z.rxSig1??=/^[ipPsjfdcC]$/,z.rxSig2??=/^[vipPsjfdcC]\([ipPsjfdcC]*\)$/,z.rxSig1.test(ie)||z.rxSig2.test(ie)},Ge=function(z){let ie=this.get(z);if(!ie)ie=[Object.create(null),Object.create(null),Object.create(null)],this.set(z,ie);return ie}.bind(new WeakMap),ct=function(z,ie,fe,Ee){let Ae=Ge(z)[ie];if(arguments.length===3)return Ae[fe];if(Ee)return Ae[fe]=Ee;return delete Ae[fe]},zt=function(z,...ie){return ct(this,0,z,...ie)},Ir=function(z,ie){qe(ie)&&d(z,"(",ie,") collides with a data type signature.")},B=function(z,...ie){return Ir("Setter adaptor",z),ct(this,1,z,...ie)},re=function(z,...ie){return Ir("Struct adaptor",z),ct(this,2,z,...ie)},ae=function(z,ie){let fe=typeof ie==="string"?ct(z,2,ie):ie;if(typeof fe!=="object")d("Invalid struct mapping object. Arg =",ie,JSON.stringify(fe));return fe},Se=Te((z)=>M+z+C),Re=function(z,ie,fe=!0){let Ee=z.members[ie];if(!Ee&&(M||C)){for(let Ae of Object.values(z.members))if(Ae.key===ie){Ee=Ae;break}if(!Ee&&fe)d(w(z.name||z.structName,ie),"is not a mapped struct member.")}return Ee},Oe=function z(ie,fe,Ee=!1){if(!z._)z._=(Ke)=>Ke.replace(/[^vipPsjrdcC]/g,"").replace(/[pPscC]/g,"i");let Ae=Re(ie.structInfo,fe,!0);return Ee?z._(Ae.signature):Ae.signature},ke=Te(function(){let z=[];for(let ie of Object.keys(this.structInfo.members))z.push(this.memberKey(ie));return z}),Ce=new TextDecoder("utf-8"),He=new TextEncoder,Qe=typeof SharedArrayBuffer>"u"?function(){}:SharedArrayBuffer,Me=function(z,ie,fe){if(O===8)ie=Number(ie),fe=Number(fe);return Ce.decode(z.buffer instanceof Qe?z.slice(ie,fe):z.subarray(ie,fe))},mt=function(z,ie,fe=!1){let Ee=Re(z.structInfo,ie,fe);return Ee&&Ee.signature.length===1&&Ee.signature[0]==="s"?Ee:!1},Mt=function(z){if(z.signature==="s")return;d("Invalid member type signature for C-string value:",JSON.stringify(z))},rn=function(ie,fe){let Ee=Re(ie.structInfo,fe,!0);Mt(Ee);let Ae=ie[Ee.key];if(!Ae)return null;let Ke=Ae,ft=E();for(;ft[Ke]!==0;++Ke);return Ae===Ke?"":Me(ft,Ae,Ke)},Zt=function(z,...ie){if(z.ondispose){if(!Array.isArray(z.ondispose))z.ondispose=[z.ondispose]}else z.ondispose=[];z.ondispose.push(...ie)},Pr=function(z){let ie=He.encode(z),fe=b(ie.length+1);if(!fe)d("Allocation error while duplicating string:",z);let Ee=E();return Ee.set(ie,Number(fe)),Ee[J(fe,ie.length)]=0,fe},Nn=function(z,ie,fe){let Ee=Re(z.structInfo,ie,!0);Mt(Ee);let Ae=Pr(fe);return z[Ee.key]=Ae,Zt(z,Ae),z},At=function(ie,fe){if(arguments[2]!==Te)d("Do not call the StructType constructor","from client-level code.");Object.defineProperties(this,{structName:Te(ie),structInfo:Te(fe)})};At.prototype=Object.create(null,{dispose:Te(function(){ne(this.constructor,this)}),lookupMember:Te(function(z,ie=!0){return Re(this.structInfo,z,ie)}),memberToJsString:Te(function(z){return rn(this,z)}),memberIsString:Te(function(z,ie=!0){return mt(this,z,ie)}),memberKey:Se,memberKeys:ke,memberSignature:Te(function(z,ie=!1){return Oe(this,z,ie)}),memoryDump:Te(function(){let z=this.pointer;return z?new Uint8Array(E().slice(Number(z),Number(z)+this.structInfo.sizeof)):null}),extraBytes:{configurable:!1,enumerable:!1,get:function(){return N(this,!1)?.xb??0}},zeroOnDispose:{configurable:!1,enumerable:!1,get:function(){return N(this,!1)?.zod??!!this.structInfo.zeroOnDispose}},pointer:{configurable:!1,enumerable:!1,get:function(){return N(this,!1)?.p},set:()=>d("Cannot assign the 'pointer' property of a struct.")},setMemberCString:Te(function(z,ie){return Nn(this,z,ie)})}),Object.assign(At.prototype,{addOnDispose:function(...z){return Zt(this,...z),this}}),Object.defineProperties(At,{allocCString:Te(Pr),isA:Te((z)=>z instanceof At),hasExternalPointer:Te((z)=>{let ie=N(z,!1);return!!(ie?.p&&!ie?.ownsPointer)}),memberKey:Se});let ho=function(z){return z.get||(z.adaptGet?Nt.adaptGet(z.adaptGet):void 0)},Ic=function(z){return z.set||(z.adaptSet?Nt.adaptSet(z.adaptSet):void 0)},Mm=function z(ie,fe,Ee){let Ae=z.innerStructs??=new Map,Ke=ie.memberKey(fe);if(Ee.signature!==void 0)d("'signature' cannot be used on an embedded struct (",ie.structName,".",Ke,").");if(Ic(Ee))d("'set' and 'adaptSet' are not permitted for nested struct members.");Ee.structName??=ie.structName+"::"+fe,Ee.key=Ke,Ee.name=fe,Ee.constructor=this.call(this,Ee.structName,Ee);let ft=ho(Ee),xt=Object.assign(Object.create(null),{configurable:!1,enumerable:!1,set:T(ie.structName,Ke),get:function(){let Dt=this.debugFlags.__flags,We=this.pointer,pt=We+"."+Ke,Pe=Ae.get(pt);if(Dt.getter)V("debug.getter: k =",pt);if(!Pe)Pe=new Ee.constructor(J(We,Ee.offset)),Ae.set(pt,Pe),this.addOnDispose(()=>Pe.dispose()),Pe.addOnDispose(()=>Ae.delete(pt));if(ft)Pe=ft.apply(this,[Pe,Ke]);if(Dt.getter)V("debug.getter: result =",Pe);return Pe}});Object.defineProperty(ie.prototype,Ke,xt)},Bm=function z(ie,fe,Ee){if(Ee=ae(this,Ee),Ee.members)return Mm.call(this,ie,fe,Ee);if(!z.cache){z.cache={getters:{},setters:{},sw:{}};let pt=["i","c","C","p","P","s","f","d","v()"];if(G)pt.push("j");pt.forEach(function(Pe){z.cache.getters[Pe]=ve(Pe),z.cache.setters[Pe]=F(Pe),z.cache.sw[Pe]=g(Pe)}),z.sigCheck=function(Pe,lt,mo,Nc){if(Object.prototype.hasOwnProperty.call(Pe,mo))d(Pe.structName,"already has a property named",mo+".");qe(Nc)||d("Malformed signature for",w(Pe.structName,lt)+":",Nc)}}let Ae=ie.memberKey(fe);z.sigCheck(ie.prototype,fe,Ae,Ee.signature),Ee.key=Ae,Ee.name=fe;let Ke=W(Ee.signature),ft=w(ie.structName,Ae),xt=ie.debugFlags.__flags,Dt=ho(Ee),We=Object.create(null);if(We.configurable=!1,We.enumerable=!1,We.get=function(){if(xt.getter)V("debug.getter:",z.cache.getters[Ke],"for",he(Ke),ft,"@",this.pointer,"+",Ee.offset,"sz",Ee.sizeof);let pt=new DataView(E().buffer,Number(this.pointer)+Ee.offset,Ee.sizeof)[z.cache.getters[Ke]](0,S);if(Dt)pt=Dt.apply(this,[Ae,pt]);if(xt.getter)V("debug.getter:",ft,"result =",pt);return pt},Ee.readOnly)We.set=T(ie.prototype.structName,Ae);else{let pt=Ic(Ee);We.set=function(Pe){if(xt.setter)V("debug.setter:",z.cache.setters[Ke],"for",he(Ke),ft,"@",this.pointer,"+",Ee.offset,"sz",Ee.sizeof,Pe);if(!this.pointer)d("Cannot set native property on a disposed",this.structName,"instance.");if(pt)Pe=pt.apply(this,[Ae,Pe]);if(Pe===null||Pe===void 0)Pe=U;else if(K(Ee.signature)&&!L(Pe))if(oe(Ee.signature)&&Pe instanceof At){if(Pe=Pe.pointer||U,xt.setter)V("debug.setter:",ft,"resolved to",Pe)}else d("Invalid value for pointer-type",ft+".");new DataView(E().buffer,Number(this.pointer)+Ee.offset,Ee.sizeof)[z.cache.setters[Ke]](0,z.cache.sw[Ke](Pe),S)}}Object.defineProperty(ie.prototype,Ae,We)},Pc=function z(ie,fe,Ee=Object.create(null)){let Ae=function Pe(lt){if(!(this instanceof Pe))d("The",ie,"constructor may only be called via 'new'.");Ie(Pe,this,...arguments)},Ke=this,ft=(Pe)=>typeof Pe==="string"&&qe(Pe)?{signature:Pe}:ae(Ke,Pe);if(arguments.length===1)fe=ft(ie),ie=fe.structName||fe.name;else if(arguments.length===2)fe=ft(fe),fe.name??=ie;else fe=ft(fe);if(ie??=fe.structName,ie??=Ee.structName,!ie)d("One of 'name' or 'structName' are required.");if(fe.adapt)Object.keys(fe.adapt.struct||{}).forEach((Pe)=>{re.call(z,Pe,fe.adapt.struct[Pe])}),Object.keys(fe.adapt.set||{}).forEach((Pe)=>{B.call(z,Pe,fe.adapt.set[Pe])}),Object.keys(fe.adapt.get||{}).forEach((Pe)=>{zt.call(z,Pe,fe.adapt.get[Pe])});if(!fe.members&&!fe.sizeof)fe.sizeof=we(fe.signature);let xt=Te(p.__makeDebugFlags(Nt.debugFlags));Object.defineProperties(Ae,{debugFlags:xt,isA:Te((Pe)=>Pe instanceof Ae),memberKey:Se,memberKeys:ke,structInfo:Te(fe),structName:Te(ie),ptrAdd:Te(J)}),Ae.prototype=new At(ie,fe,Te),Object.defineProperties(Ae.prototype,{debugFlags:xt,constructor:Te(Ae),ptrAdd:Te(pe)});let Dt=!1,We=0,pt=!!fe.autoCalcSizeOffset;if(!pt){if(!fe.sizeof)d(ie,"description is missing its sizeof property.");fe.offset??=0}else fe.offset??=0;if(Object.keys(fe.members||{}).forEach((Pe)=>{let lt=ft(fe.members[Pe]);if(!lt.members&&!lt.sizeof){if(lt.sizeof=we(lt.signature),!lt.sizeof)d(w(ie,Pe),"is missing a sizeof property.",lt)}if(lt.offset===void 0)if(pt)lt.offset=We;else d(w(ie,Pe),"is missing its offset.",JSON.stringify(lt));if(fe.members[Pe]=lt,!Dt||Dt.offset<lt.offset)Dt=lt;let mo=!!lt.autoCalc;if(pt)lt.autoCalcSizeOffset=!0;if(Bm.call(Ke,Ae,Pe,lt),mo)lt.autoCalcSizeOffset=!0;else delete lt.autoCalcSizeOffset;We+=lt.sizeof}),!Dt)d("No member property descriptions found.");if(!fe.sizeof)fe.sizeof=We;if(fe.sizeof===1)fe.signature==="c"||fe.signature==="C"||d("Unexpected sizeof==1 member",w(ie,k),"with signature",fe.signature);else{if(fe.sizeof%4!==0)console.warn("Invalid struct member description",fe),d(ie,"sizeof is not aligned. sizeof="+fe.sizeof);if(fe.offset%4!==0)console.warn("Invalid struct member description",fe),d(ie,"offset is not aligned. offset="+fe.offset)}if(fe.sizeof<We)console.warn("Suspect struct description:",fe,"offset =",We),d("Mismatch in the calculated vs. the provided sizeof/offset info.","Expected sizeof",We,"but got",fe.sizeof,"for",fe);return delete fe.autoCalcSizeOffset,Ae},Nt=function z(ie,fe){return arguments.length==1?Pc.call(z,ie):Pc.call(z,ie,fe)};if(Nt.StructType=At,Nt.config=c,Nt.allocCString=Pr,Nt.adaptGet=zt,Nt.adaptSet=B,Nt.adaptStruct=re,Nt.ptrAdd=J,!Nt.debugFlags)Nt.debugFlags=p.__makeDebugFlags(p.debugFlags);return Nt},globalThis.sqlite3ApiBootstrap.initializers.push(function(f){let c=(...O)=>{throw Error(O.join(" "))},{capi:d,wasm:p,util:E}=f;globalThis.WhWasmUtilInstaller(p),delete globalThis.WhWasmUtilInstaller;let b={core:[["sqlite3_aggregate_context","void*","sqlite3_context*","int"],["sqlite3_bind_double","int","sqlite3_stmt*","int","f64"],["sqlite3_bind_int","int","sqlite3_stmt*","int","int"],["sqlite3_bind_null",void 0,"sqlite3_stmt*","int"],["sqlite3_bind_parameter_count","int","sqlite3_stmt*"],["sqlite3_bind_parameter_index","int","sqlite3_stmt*","string"],["sqlite3_bind_parameter_name","string","sqlite3_stmt*","int"],["sqlite3_bind_pointer","int","sqlite3_stmt*","int","*","string:static","*"],["sqlite3_bind_zeroblob","int","sqlite3_stmt*","int","int"],["sqlite3_busy_handler","int",["sqlite3*",new p.xWrap.FuncPtrAdapter({signature:"i(pi)",contextKey:(O,R)=>O[0]}),"*"]],["sqlite3_busy_timeout","int","sqlite3*","int"],["sqlite3_changes","int","sqlite3*"],["sqlite3_clear_bindings","int","sqlite3_stmt*"],["sqlite3_collation_needed","int","sqlite3*","*","*"],["sqlite3_column_blob","*","sqlite3_stmt*","int"],["sqlite3_column_bytes","int","sqlite3_stmt*","int"],["sqlite3_column_count","int","sqlite3_stmt*"],["sqlite3_column_decltype","string","sqlite3_stmt*","int"],["sqlite3_column_double","f64","sqlite3_stmt*","int"],["sqlite3_column_int","int","sqlite3_stmt*","int"],["sqlite3_column_name","string","sqlite3_stmt*","int"],["sqlite3_column_type","int","sqlite3_stmt*","int"],["sqlite3_column_value","sqlite3_value*","sqlite3_stmt*","int"],["sqlite3_commit_hook","void*",["sqlite3*",new p.xWrap.FuncPtrAdapter({name:"sqlite3_commit_hook",signature:"i(p)",contextKey:(O)=>O[0]}),"*"]],["sqlite3_compileoption_get","string","int"],["sqlite3_compileoption_used","int","string"],["sqlite3_complete","int","string:flexible"],["sqlite3_context_db_handle","sqlite3*","sqlite3_context*"],["sqlite3_data_count","int","sqlite3_stmt*"],["sqlite3_db_filename","string","sqlite3*","string"],["sqlite3_db_handle","sqlite3*","sqlite3_stmt*"],["sqlite3_db_name","string","sqlite3*","int"],["sqlite3_db_readonly","int","sqlite3*","string"],["sqlite3_db_status","int","sqlite3*","int","*","*","int"],["sqlite3_errcode","int","sqlite3*"],["sqlite3_errmsg","string","sqlite3*"],["sqlite3_error_offset","int","sqlite3*"],["sqlite3_errstr","string","int"],["sqlite3_exec","int",["sqlite3*","string:flexible",new p.xWrap.FuncPtrAdapter({signature:"i(pipp)",bindScope:"transient",callProxy:(O)=>{let R;return(X,ee,U,J)=>{try{let pe=p.cArgvToJs(ee,U);if(!R)R=p.cArgvToJs(ee,J);return O(pe,R)|0}catch(pe){return pe.resultCode||d.SQLITE_ERROR}}}}),"*","**"]],["sqlite3_expanded_sql","string","sqlite3_stmt*"],["sqlite3_extended_errcode","int","sqlite3*"],["sqlite3_extended_result_codes","int","sqlite3*","int"],["sqlite3_file_control","int","sqlite3*","string","int","*"],["sqlite3_finalize","int","sqlite3_stmt*"],["sqlite3_free",void 0,"*"],["sqlite3_get_autocommit","int","sqlite3*"],["sqlite3_get_auxdata","*","sqlite3_context*","int"],["sqlite3_initialize",void 0],["sqlite3_interrupt",void 0,"sqlite3*"],["sqlite3_is_interrupted","int","sqlite3*"],["sqlite3_keyword_count","int"],["sqlite3_keyword_name","int",["int","**","*"]],["sqlite3_keyword_check","int",["string","int"]],["sqlite3_libversion","string"],["sqlite3_libversion_number","int"],["sqlite3_limit","int",["sqlite3*","int","int"]],["sqlite3_malloc","*","int"],["sqlite3_next_stmt","sqlite3_stmt*",["sqlite3*","sqlite3_stmt*"]],["sqlite3_open","int","string","*"],["sqlite3_open_v2","int","string","*","int","string"],["sqlite3_realloc","*","*","int"],["sqlite3_reset","int","sqlite3_stmt*"],["sqlite3_result_blob",void 0,"sqlite3_context*","*","int","*"],["sqlite3_result_double",void 0,"sqlite3_context*","f64"],["sqlite3_result_error",void 0,"sqlite3_context*","string","int"],["sqlite3_result_error_code",void 0,"sqlite3_context*","int"],["sqlite3_result_error_nomem",void 0,"sqlite3_context*"],["sqlite3_result_error_toobig",void 0,"sqlite3_context*"],["sqlite3_result_int",void 0,"sqlite3_context*","int"],["sqlite3_result_null",void 0,"sqlite3_context*"],["sqlite3_result_pointer",void 0,"sqlite3_context*","*","string:static","*"],["sqlite3_result_subtype",void 0,"sqlite3_value*","int"],["sqlite3_result_text",void 0,"sqlite3_context*","string","int","*"],["sqlite3_result_zeroblob",void 0,"sqlite3_context*","int"],["sqlite3_rollback_hook","void*",["sqlite3*",new p.xWrap.FuncPtrAdapter({name:"sqlite3_rollback_hook",signature:"v(p)",contextKey:(O)=>O[0]}),"*"]],["sqlite3_set_auxdata",void 0,["sqlite3_context*","int","*","*"]],["sqlite3_set_errmsg","int","sqlite3*","int","string"],["sqlite3_shutdown",void 0],["sqlite3_sourceid","string"],["sqlite3_sql","string","sqlite3_stmt*"],["sqlite3_status","int","int","*","*","int"],["sqlite3_step","int","sqlite3_stmt*"],["sqlite3_stmt_busy","int","sqlite3_stmt*"],["sqlite3_stmt_readonly","int","sqlite3_stmt*"],["sqlite3_stmt_status","int","sqlite3_stmt*","int","int"],["sqlite3_strglob","int","string","string"],["sqlite3_stricmp","int","string","string"],["sqlite3_strlike","int","string","string","int"],["sqlite3_strnicmp","int","string","string","int"],["sqlite3_table_column_metadata","int","sqlite3*","string","string","string","**","**","*","*","*"],["sqlite3_total_changes","int","sqlite3*"],["sqlite3_trace_v2","int",["sqlite3*","int",new p.xWrap.FuncPtrAdapter({name:"sqlite3_trace_v2::callback",signature:"i(ippp)",contextKey:(O,R)=>O[0]}),"*"]],["sqlite3_txn_state","int",["sqlite3*","string"]],["sqlite3_uri_boolean","int","sqlite3_filename","string","int"],["sqlite3_uri_key","string","sqlite3_filename","int"],["sqlite3_uri_parameter","string","sqlite3_filename","string"],["sqlite3_user_data","void*","sqlite3_context*"],["sqlite3_value_blob","*","sqlite3_value*"],["sqlite3_value_bytes","int","sqlite3_value*"],["sqlite3_value_double","f64","sqlite3_value*"],["sqlite3_value_dup","sqlite3_value*","sqlite3_value*"],["sqlite3_value_free",void 0,"sqlite3_value*"],["sqlite3_value_frombind","int","sqlite3_value*"],["sqlite3_value_int","int","sqlite3_value*"],["sqlite3_value_nochange","int","sqlite3_value*"],["sqlite3_value_numeric_type","int","sqlite3_value*"],["sqlite3_value_pointer","*","sqlite3_value*","string:static"],["sqlite3_value_subtype","int","sqlite3_value*"],["sqlite3_value_type","int","sqlite3_value*"],["sqlite3_vfs_find","*","string"],["sqlite3_vfs_register","int","sqlite3_vfs*","int"],["sqlite3_vfs_unregister","int","sqlite3_vfs*"]],int64:[["sqlite3_bind_int64","int",["sqlite3_stmt*","int","i64"]],["sqlite3_changes64","i64",["sqlite3*"]],["sqlite3_column_int64","i64",["sqlite3_stmt*","int"]],["sqlite3_deserialize","int","sqlite3*","string","*","i64","i64","int"],["sqlite3_last_insert_rowid","i64",["sqlite3*"]],["sqlite3_malloc64","*","i64"],["sqlite3_msize","i64","*"],["sqlite3_overload_function","int",["sqlite3*","string","int"]],["sqlite3_realloc64","*","*","i64"],["sqlite3_result_int64",void 0,"*","i64"],["sqlite3_result_zeroblob64","int","*","i64"],["sqlite3_serialize","*","sqlite3*","string","*","int"],["sqlite3_set_last_insert_rowid",void 0,["sqlite3*","i64"]],["sqlite3_status64","int","int","*","*","int"],["sqlite3_db_status64","int","sqlite3*","int","*","*","int"],["sqlite3_total_changes64","i64",["sqlite3*"]],["sqlite3_update_hook","*",["sqlite3*",new p.xWrap.FuncPtrAdapter({name:"sqlite3_update_hook::callback",signature:"v(pippj)",contextKey:(O)=>O[0],callProxy:(O)=>(R,X,ee,U,J)=>{O(R,X,p.cstrToJs(ee),p.cstrToJs(U),J)}}),"*"]],["sqlite3_uri_int64","i64",["sqlite3_filename","string","i64"]],["sqlite3_value_int64","i64","sqlite3_value*"]],wasmInternal:[["sqlite3__wasm_db_reset","int","sqlite3*"],["sqlite3__wasm_db_vfs","sqlite3_vfs*","sqlite3*","string"],["sqlite3__wasm_vfs_create_file","int","sqlite3_vfs*","string","*","int"],["sqlite3__wasm_posix_create_file","int","string","*","int"],["sqlite3__wasm_vfs_unlink","int","sqlite3_vfs*","string"],["sqlite3__wasm_qfmt_token","string:dealloc","string","int"]]};if(p.exports.sqlite3_progress_handler)b.core.push(["sqlite3_progress_handler",void 0,["sqlite3*","int",new p.xWrap.FuncPtrAdapter({name:"xProgressHandler",signature:"i(p)",bindScope:"context",contextKey:(O,R)=>O[0]}),"*"]]);if(p.exports.sqlite3_stmt_explain)b.core.push(["sqlite3_stmt_explain","int","sqlite3_stmt*","int"],["sqlite3_stmt_isexplain","int","sqlite3_stmt*"]);if(p.exports.sqlite3_set_authorizer)b.core.push(["sqlite3_set_authorizer","int",["sqlite3*",new p.xWrap.FuncPtrAdapter({name:"sqlite3_set_authorizer::xAuth",signature:"i(pissss)",contextKey:(O,R)=>O[0],callProxy:(O)=>(R,X,ee,U,J,pe)=>{try{return ee=ee&&p.cstrToJs(ee),U=U&&p.cstrToJs(U),J=J&&p.cstrToJs(J),pe=pe&&p.cstrToJs(pe),O(R,X,ee,U,J,pe)|0}catch(S){return S.resultCode||d.SQLITE_ERROR}}}),"*"]]);if(p.exports.sqlite3_column_origin_name)b.core.push(["sqlite3_column_database_name","string","sqlite3_stmt*","int"],["sqlite3_column_origin_name","string","sqlite3_stmt*","int"],["sqlite3_column_table_name","string","sqlite3_stmt*","int"]);if(p.bigIntEnabled&&!!p.exports.sqlite3_declare_vtab)b.int64.push(["sqlite3_create_module","int",["sqlite3*","string","sqlite3_module*","*"]],["sqlite3_create_module_v2","int",["sqlite3*","string","sqlite3_module*","*","*"]],["sqlite3_declare_vtab","int",["sqlite3*","string:flexible"]],["sqlite3_drop_modules","int",["sqlite3*","**"]],["sqlite3_vtab_collation","string","sqlite3_index_info*","int"],["sqlite3_vtab_distinct","int","sqlite3_index_info*"],["sqlite3_vtab_in","int","sqlite3_index_info*","int","int"],["sqlite3_vtab_in_first","int","sqlite3_value*","**"],["sqlite3_vtab_in_next","int","sqlite3_value*","**"],["sqlite3_vtab_nochange","int","sqlite3_context*"],["sqlite3_vtab_on_conflict","int","sqlite3*"],["sqlite3_vtab_rhs_value","int","sqlite3_index_info*","int","**"]);if(p.bigIntEnabled&&!!p.exports.sqlite3_preupdate_hook)b.int64.push(["sqlite3_preupdate_blobwrite","int","sqlite3*"],["sqlite3_preupdate_count","int","sqlite3*"],["sqlite3_preupdate_depth","int","sqlite3*"],["sqlite3_preupdate_hook","*",["sqlite3*",new p.xWrap.FuncPtrAdapter({name:"sqlite3_preupdate_hook",signature:"v(ppippjj)",contextKey:(O)=>O[0],callProxy:(O)=>(R,X,ee,U,J,pe,S)=>{O(R,X,ee,p.cstrToJs(U),p.cstrToJs(J),pe,S)}}),"*"]],["sqlite3_preupdate_new","int",["sqlite3*","int","**"]],["sqlite3_preupdate_old","int",["sqlite3*","int","**"]]);if(p.bigIntEnabled&&!!p.exports.sqlite3changegroup_add&&!!p.exports.sqlite3session_create&&!!p.exports.sqlite3_preupdate_hook){let O={signature:"i(ps)",callProxy:(R)=>(X,ee)=>{try{return R(X,p.cstrToJs(ee))|0}catch(U){return U.resultCode||d.SQLITE_ERROR}}};b.int64.push(["sqlite3changegroup_add","int",["sqlite3_changegroup*","int","void*"]],["sqlite3changegroup_add_strm","int",["sqlite3_changegroup*",new p.xWrap.FuncPtrAdapter({name:"xInput",signature:"i(ppp)",bindScope:"transient"}),"void*"]],["sqlite3changegroup_delete",void 0,["sqlite3_changegroup*"]],["sqlite3changegroup_new","int",["**"]],["sqlite3changegroup_output","int",["sqlite3_changegroup*","int*","**"]],["sqlite3changegroup_output_strm","int",["sqlite3_changegroup*",new p.xWrap.FuncPtrAdapter({name:"xOutput",signature:"i(ppi)",bindScope:"transient"}),"void*"]],["sqlite3changeset_apply","int",["sqlite3*","int","void*",new p.xWrap.FuncPtrAdapter({name:"xFilter",bindScope:"transient",...O}),new p.xWrap.FuncPtrAdapter({name:"xConflict",signature:"i(pip)",bindScope:"transient"}),"void*"]],["sqlite3changeset_apply_strm","int",["sqlite3*",new p.xWrap.FuncPtrAdapter({name:"xInput",signature:"i(ppp)",bindScope:"transient"}),"void*",new p.xWrap.FuncPtrAdapter({name:"xFilter",bindScope:"transient",...O}),new p.xWrap.FuncPtrAdapter({name:"xConflict",signature:"i(pip)",bindScope:"transient"}),"void*"]],["sqlite3changeset_apply_v2","int",["sqlite3*","int","void*",new p.xWrap.FuncPtrAdapter({name:"xFilter",bindScope:"transient",...O}),new p.xWrap.FuncPtrAdapter({name:"xConflict",signature:"i(pip)",bindScope:"transient"}),"void*","**","int*","int"]],["sqlite3changeset_apply_v2_strm","int",["sqlite3*",new p.xWrap.FuncPtrAdapter({name:"xInput",signature:"i(ppp)",bindScope:"transient"}),"void*",new p.xWrap.FuncPtrAdapter({name:"xFilter",bindScope:"transient",...O}),new p.xWrap.FuncPtrAdapter({name:"xConflict",signature:"i(pip)",bindScope:"transient"}),"void*","**","int*","int"]],["sqlite3changeset_apply_v3","int",["sqlite3*","int","void*",new p.xWrap.FuncPtrAdapter({name:"xFilter",signature:"i(pp)",bindScope:"transient"}),new p.xWrap.FuncPtrAdapter({name:"xConflict",signature:"i(pip)",bindScope:"transient"}),"void*","**","int*","int"]],["sqlite3changeset_apply_v3_strm","int",["sqlite3*",new p.xWrap.FuncPtrAdapter({name:"xInput",signature:"i(ppp)",bindScope:"transient"}),"void*",new p.xWrap.FuncPtrAdapter({name:"xFilter",signature:"i(pp)",bindScope:"transient"}),new p.xWrap.FuncPtrAdapter({name:"xConflict",signature:"i(pip)",bindScope:"transient"}),"void*","**","int*","int"]],["sqlite3changeset_concat","int",["int","void*","int","void*","int*","**"]],["sqlite3changeset_concat_strm","int",[new p.xWrap.FuncPtrAdapter({name:"xInputA",signature:"i(ppp)",bindScope:"transient"}),"void*",new p.xWrap.FuncPtrAdapter({name:"xInputB",signature:"i(ppp)",bindScope:"transient"}),"void*",new p.xWrap.FuncPtrAdapter({name:"xOutput",signature:"i(ppi)",bindScope:"transient"}),"void*"]],["sqlite3changeset_conflict","int",["sqlite3_changeset_iter*","int","**"]],["sqlite3changeset_finalize","int",["sqlite3_changeset_iter*"]],["sqlite3changeset_fk_conflicts","int",["sqlite3_changeset_iter*","int*"]],["sqlite3changeset_invert","int",["int","void*","int*","**"]],["sqlite3changeset_invert_strm","int",[new p.xWrap.FuncPtrAdapter({name:"xInput",signature:"i(ppp)",bindScope:"transient"}),"void*",new p.xWrap.FuncPtrAdapter({name:"xOutput",signature:"i(ppi)",bindScope:"transient"}),"void*"]],["sqlite3changeset_new","int",["sqlite3_changeset_iter*","int","**"]],["sqlite3changeset_next","int",["sqlite3_changeset_iter*"]],["sqlite3changeset_old","int",["sqlite3_changeset_iter*","int","**"]],["sqlite3changeset_op","int",["sqlite3_changeset_iter*","**","int*","int*","int*"]],["sqlite3changeset_pk","int",["sqlite3_changeset_iter*","**","int*"]],["sqlite3changeset_start","int",["**","int","*"]],["sqlite3changeset_start_strm","int",["**",new p.xWrap.FuncPtrAdapter({name:"xInput",signature:"i(ppp)",bindScope:"transient"}),"void*"]],["sqlite3changeset_start_v2","int",["**","int","*","int"]],["sqlite3changeset_start_v2_strm","int",["**",new p.xWrap.FuncPtrAdapter({name:"xInput",signature:"i(ppp)",bindScope:"transient"}),"void*","int"]],["sqlite3session_attach","int",["sqlite3_session*","string"]],["sqlite3session_changeset","int",["sqlite3_session*","int*","**"]],["sqlite3session_changeset_size","i64",["sqlite3_session*"]],["sqlite3session_changeset_strm","int",["sqlite3_session*",new p.xWrap.FuncPtrAdapter({name:"xOutput",signature:"i(ppp)",bindScope:"transient"}),"void*"]],["sqlite3session_config","int",["int","void*"]],["sqlite3session_create","int",["sqlite3*","string","**"]],["sqlite3session_diff","int",["sqlite3_session*","string","string","**"]],["sqlite3session_enable","int",["sqlite3_session*","int"]],["sqlite3session_indirect","int",["sqlite3_session*","int"]],["sqlite3session_isempty","int",["sqlite3_session*"]],["sqlite3session_memory_used","i64",["sqlite3_session*"]],["sqlite3session_object_config","int",["sqlite3_session*","int","void*"]],["sqlite3session_patchset","int",["sqlite3_session*","*","**"]],["sqlite3session_patchset_strm","int",["sqlite3_session*",new p.xWrap.FuncPtrAdapter({name:"xOutput",signature:"i(ppp)",bindScope:"transient"}),"void*"]],["sqlite3session_table_filter",void 0,["sqlite3_session*",new p.xWrap.FuncPtrAdapter({name:"xFilter",...O,contextKey:(R,X)=>R[0]}),"*"]])}f.StructBinder=globalThis.Jaccwabyt({heap:p.heap8u,alloc:p.alloc,dealloc:p.dealloc,bigIntEnabled:p.bigIntEnabled,pointerIR:p.ptr.ir,memberPrefix:"$"}),delete globalThis.Jaccwabyt;{let O=p.xWrap.argAdapter("string");p.xWrap.argAdapter("string:flexible",(U)=>O(E.flexibleString(U))),p.xWrap.argAdapter("string:static",function(U){if(p.isPtr(U))return U;return U=""+U,this[U]||(this[U]=p.allocCString(U))}.bind(Object.create(null)));let R=p.xWrap.argAdapter("*"),X=function(){};if(p.xWrap.argAdapter("sqlite3_filename",R)("sqlite3_context*",R)("sqlite3_value*",R)("void*",R)("sqlite3_changegroup*",R)("sqlite3_changeset_iter*",R)("sqlite3_session*",R)("sqlite3_stmt*",(U)=>R(U instanceof(f?.oo1?.Stmt||X)?U.pointer:U))("sqlite3*",(U)=>R(U instanceof(f?.oo1?.DB||X)?U.pointer:U))("sqlite3_vfs*",(U)=>{if(typeof U==="string")return d.sqlite3_vfs_find(U)||f.SQLite3Error.toss(d.SQLITE_NOTFOUND,"Unknown sqlite3_vfs name:",U);return R(U instanceof(d.sqlite3_vfs||X)?U.pointer:U)}),p.exports.sqlite3_declare_vtab)p.xWrap.argAdapter("sqlite3_index_info*",(U)=>R(U instanceof(d.sqlite3_index_info||X)?U.pointer:U))("sqlite3_module*",(U)=>R(U instanceof(d.sqlite3_module||X)?U.pointer:U));let ee=p.xWrap.resultAdapter("*");p.xWrap.resultAdapter("sqlite3*",ee)("sqlite3_context*",ee)("sqlite3_stmt*",ee)("sqlite3_value*",ee)("sqlite3_vfs*",ee)("void*",ee);for(let U of b.core)d[U[0]]=p.xWrap.apply(null,U);for(let U of b.wasmInternal)E[U[0]]=p.xWrap.apply(null,U);for(let U of b.int64)d[U[0]]=p.bigIntEnabled?p.xWrap.apply(null,U):()=>c(U[0]+"() is unavailable due to lack","of BigInt support in this build.");delete b.core,delete b.int64,delete b.wasmInternal,E.sqlite3__wasm_db_error=function(U,J,pe){if(!U)return d.SQLITE_MISUSE;if(J instanceof f.WasmAllocError)J=d.SQLITE_NOMEM,pe=0;else if(J instanceof Error)pe=pe||""+J,J=J.resultCode||d.SQLITE_ERROR;return d.sqlite3_set_errmsg(U,J,pe)||J}}{let O=p.xCall("sqlite3__wasm_enum_json");if(!O)c("Maintenance required: increase sqlite3__wasm_enum_json()'s","static buffer size!");p.ctype=JSON.parse(p.cstrToJs(O));let R=["access","authorizer","blobFinalizers","changeset","config","dataTypes","dbConfig","dbStatus","encodings","fcntl","flock","ioCap","limits","openFlags","prepareFlags","resultCodes","sqlite3Status","stmtStatus","syncFlags","trace","txnState","udfFlags","version"];if(p.bigIntEnabled)R.push("serialize","session","vtab");for(let U of R)for(let J of Object.entries(p.ctype[U]))d[J[0]]=J[1];if(!p.functionEntry(d.SQLITE_WASM_DEALLOC))c("Internal error: cannot resolve exported function","entry SQLITE_WASM_DEALLOC (=="+d.SQLITE_WASM_DEALLOC+").");let X=Object.create(null);for(let U of Object.entries(p.ctype.resultCodes))X[U[1]]=U[0];d.sqlite3_js_rc_str=(U)=>X[U];let ee=Object.assign(Object.create(null),{WasmTestStruct:!0,sqlite3_index_info:!p.bigIntEnabled,sqlite3_index_constraint:!p.bigIntEnabled,sqlite3_index_orderby:!p.bigIntEnabled,sqlite3_index_constraint_usage:!p.bigIntEnabled});for(let U of p.ctype.structs)if(!ee[U.name])d[U.name]=f.StructBinder(U);if(d.sqlite3_index_info){for(let U of["sqlite3_index_constraint","sqlite3_index_orderby","sqlite3_index_constraint_usage"])d.sqlite3_index_info[U]=d[U],delete d[U];d.sqlite3_vtab_config=p.xWrap("sqlite3__wasm_vtab_config","int",["sqlite3*","int","int"])}}let I=(O,R,X)=>E.sqlite3__wasm_db_error(O,d.SQLITE_MISUSE,R+"() requires "+X+" argument"+(X===1?"":"s")+"."),V=(O)=>E.sqlite3__wasm_db_error(O,d.SQLITE_FORMAT,"SQLITE_UTF8 is the only supported encoding."),M=(O)=>p.xWrap.argAdapter("sqlite3*")(O),C=(O)=>p.isPtr(O)?p.cstrToJs(O):O,q=function(O,R){O=M(O);let X=this.dbMap.get(O);if(!R)return this.dbMap.delete(O),X;else if(!X&&R>0)this.dbMap.set(O,X=Object.create(null));return X}.bind(Object.assign(Object.create(null),{dbMap:new Map}));if(q.addCollation=function(O,R){let X=q(O,1);if(!X.collation)X.collation=new Set;X.collation.add(C(R).toLowerCase())},q._addUDF=function(O,R,X,ee){R=C(R).toLowerCase();let U=ee.get(R);if(!U)ee.set(R,U=new Set);U.add(X<0?-1:X)},q.addFunction=function(O,R,X){let ee=q(O,1);if(!ee.udf)ee.udf=new Map;this._addUDF(O,R,X,ee.udf)},p.exports.sqlite3_create_window_function)q.addWindowFunc=function(O,R,X){let ee=q(O,1);if(!ee.wudf)ee.wudf=new Map;this._addUDF(O,R,X,ee.wudf)};q.cleanup=function(O){O=M(O);for(let ee of[["sqlite3_busy_handler",3],["sqlite3_commit_hook",3],["sqlite3_preupdate_hook",3],["sqlite3_progress_handler",4],["sqlite3_rollback_hook",3],["sqlite3_set_authorizer",3],["sqlite3_trace_v2",4],["sqlite3_update_hook",3]]){let[U,J]=ee;if(!p.exports[U])continue;let pe=[O];pe.length=J;try{d[U](...pe)}catch(S){f.config.warn("close-time call of",U+"(",pe,") threw:",S)}}let R=q(O,0);if(!R)return;if(R.collation){for(let ee of R.collation)try{d.sqlite3_create_collation_v2(O,ee,d.SQLITE_UTF8,0,0,0)}catch(U){}delete R.collation}let X;for(X=0;X<2;++X){let ee=X?R.wudf:R.udf;if(!ee)continue;let U=X?d.sqlite3_create_window_function:d.sqlite3_create_function_v2;for(let J of ee){let pe=J[0],S=J[1],P=[O,pe,0,d.SQLITE_UTF8,0,0,0,0,0];if(X)P.push(0);for(let K of S)try{P[2]=K,U.apply(null,P)}catch(oe){}S.clear()}ee.clear()}delete R.udf,delete R.wudf};{let O=p.xWrap("sqlite3_close_v2","int","sqlite3*");d.sqlite3_close_v2=function(R){if(arguments.length!==1)return I(R,"sqlite3_close_v2",1);if(R)try{q.cleanup(R)}catch(X){}return O(R)}}if(d.sqlite3session_create){let O=p.xWrap("sqlite3session_delete",void 0,["sqlite3_session*"]);d.sqlite3session_delete=function(R){if(arguments.length!==1)return I(pDb,"sqlite3session_delete",1);else if(R)d.sqlite3session_table_filter(R,0,0);O(R)}}{let O=(X,ee)=>"argv["+ee+"]:"+X[0]+":"+p.cstrToJs(X[1]).toLowerCase(),R=p.xWrap("sqlite3_create_collation_v2","int",["sqlite3*","string","int","*",new p.xWrap.FuncPtrAdapter({name:"xCompare",signature:"i(pipip)",contextKey:O}),new p.xWrap.FuncPtrAdapter({name:"xDestroy",signature:"v(p)",contextKey:O})]);d.sqlite3_create_collation_v2=function(X,ee,U,J,pe,S){if(arguments.length!==6)return I(X,"sqlite3_create_collation_v2",6);else if((U&15)===0)U|=d.SQLITE_UTF8;else if(d.SQLITE_UTF8!==(U&15))return V(X);try{let P=R(X,ee,U,J,pe,S);if(P===0&&pe instanceof Function)q.addCollation(X,ee);return P}catch(P){return E.sqlite3__wasm_db_error(X,P)}},d.sqlite3_create_collation=(X,ee,U,J,pe)=>arguments.length===5?d.sqlite3_create_collation_v2(X,ee,U,J,pe,0):I(X,"sqlite3_create_collation",5)}{let O=function(U,J){return U[0]+":"+(U[2]<0?-1:U[2])+":"+J+":"+p.cstrToJs(U[1]).toLowerCase()},R=Object.assign(Object.create(null),{xInverseAndStep:{signature:"v(pip)",contextKey:O,callProxy:(U)=>(J,pe,S)=>{try{U(J,...d.sqlite3_values_to_js(pe,S))}catch(P){d.sqlite3_result_error_js(J,P)}}},xFinalAndValue:{signature:"v(p)",contextKey:O,callProxy:(U)=>(J)=>{try{d.sqlite3_result_js(J,U(J))}catch(pe){d.sqlite3_result_error_js(J,pe)}}},xFunc:{signature:"v(pip)",contextKey:O,callProxy:(U)=>(J,pe,S)=>{try{d.sqlite3_result_js(J,U(J,...d.sqlite3_values_to_js(pe,S)))}catch(P){d.sqlite3_result_error_js(J,P)}}},xDestroy:{signature:"v(p)",contextKey:O,callProxy:(U)=>(J)=>{try{U(J)}catch(pe){console.error("UDF xDestroy method threw:",pe)}}}}),X=p.xWrap("sqlite3_create_function_v2","int",["sqlite3*","string","int","int","*",new p.xWrap.FuncPtrAdapter({name:"xFunc",...R.xFunc}),new p.xWrap.FuncPtrAdapter({name:"xStep",...R.xInverseAndStep}),new p.xWrap.FuncPtrAdapter({name:"xFinal",...R.xFinalAndValue}),new p.xWrap.FuncPtrAdapter({name:"xDestroy",...R.xDestroy})]),ee=p.exports.sqlite3_create_window_function?p.xWrap("sqlite3_create_window_function","int",["sqlite3*","string","int","int","*",new p.xWrap.FuncPtrAdapter({name:"xStep",...R.xInverseAndStep}),new p.xWrap.FuncPtrAdapter({name:"xFinal",...R.xFinalAndValue}),new p.xWrap.FuncPtrAdapter({name:"xValue",...R.xFinalAndValue}),new p.xWrap.FuncPtrAdapter({name:"xInverse",...R.xInverseAndStep}),new p.xWrap.FuncPtrAdapter({name:"xDestroy",...R.xDestroy})]):void 0;if(d.sqlite3_create_function_v2=function U(J,pe,S,P,K,oe,W,he,we){if(U.length!==arguments.length)return I(J,"sqlite3_create_function_v2",U.length);else if((P&15)===0)P|=d.SQLITE_UTF8;else if(d.SQLITE_UTF8!==(P&15))return V(J);try{let me=X(J,pe,S,P,K,oe,W,he,we);if(me===0&&(oe instanceof Function||W instanceof Function||he instanceof Function||we instanceof Function))q.addFunction(J,pe,S);return me}catch(me){return console.error("sqlite3_create_function_v2() setup threw:",me),E.sqlite3__wasm_db_error(J,me,"Creation of UDF threw: "+me)}},d.sqlite3_create_function=function U(J,pe,S,P,K,oe,W,he){return U.length===arguments.length?d.sqlite3_create_function_v2(J,pe,S,P,K,oe,W,he,0):I(J,"sqlite3_create_function",U.length)},ee)d.sqlite3_create_window_function=function U(J,pe,S,P,K,oe,W,he,we,me){if(U.length!==arguments.length)return I(J,"sqlite3_create_window_function",U.length);else if((P&15)===0)P|=d.SQLITE_UTF8;else if(d.SQLITE_UTF8!==(P&15))return V(J);try{let ve=ee(J,pe,S,P,K,oe,W,he,we,me);if(ve===0&&(oe instanceof Function||W instanceof Function||he instanceof Function||we instanceof Function||me instanceof Function))q.addWindowFunc(J,pe,S);return ve}catch(ve){return console.error("sqlite3_create_window_function() setup threw:",ve),E.sqlite3__wasm_db_error(J,ve,"Creation of UDF threw: "+ve)}};else delete d.sqlite3_create_window_function;if(d.sqlite3_create_function_v2.udfSetResult=d.sqlite3_create_function.udfSetResult=d.sqlite3_result_js,d.sqlite3_create_window_function)d.sqlite3_create_window_function.udfSetResult=d.sqlite3_result_js;if(d.sqlite3_create_function_v2.udfConvertArgs=d.sqlite3_create_function.udfConvertArgs=d.sqlite3_values_to_js,d.sqlite3_create_window_function)d.sqlite3_create_window_function.udfConvertArgs=d.sqlite3_values_to_js;if(d.sqlite3_create_function_v2.udfSetError=d.sqlite3_create_function.udfSetError=d.sqlite3_result_error_js,d.sqlite3_create_window_function)d.sqlite3_create_window_function.udfSetError=d.sqlite3_result_error_js}{let O=(X,ee)=>{if(typeof X==="string")ee=-1;else if(E.isSQLableTypedArray(X))ee=X.byteLength,X=p.typedArrayToString(X instanceof ArrayBuffer?new Uint8Array(X):X);else if(Array.isArray(X))X=X.join(""),ee=-1;return[X,ee]},R={basic:p.xWrap("sqlite3_prepare_v3","int",["sqlite3*","string","int","int","**","**"]),full:p.xWrap("sqlite3_prepare_v3","int",["sqlite3*","*","int","int","**","**"])};d.sqlite3_prepare_v3=function X(ee,U,J,pe,S,P){if(X.length!==arguments.length)return I(ee,"sqlite3_prepare_v3",X.length);let[K,oe]=O(U,Number(J));switch(typeof K){case"string":return R.basic(ee,K,oe,pe,S,null);case typeof p.ptr.null:return R.full(ee,p.ptr.coerce(K),oe,pe,S,P);default:return E.sqlite3__wasm_db_error(ee,d.SQLITE_MISUSE,"Invalid SQL argument type for sqlite3_prepare_v2/v3(). typeof="+typeof K)}},d.sqlite3_prepare_v2=function X(ee,U,J,pe,S){return X.length===arguments.length?d.sqlite3_prepare_v3(ee,U,J,0,pe,S):I(ee,"sqlite3_prepare_v2",X.length)}}{let O=p.xWrap("sqlite3_bind_text","int",["sqlite3_stmt*","int","string","int","*"]),R=p.xWrap("sqlite3_bind_blob","int",["sqlite3_stmt*","int","*","int","*"]);d.sqlite3_bind_text=function X(ee,U,J,pe,S){if(X.length!==arguments.length)return I(d.sqlite3_db_handle(ee),"sqlite3_bind_text",X.length);else if(p.isPtr(J)||J===null)return O(ee,U,J,pe,S);else if(J instanceof ArrayBuffer)J=new Uint8Array(J);else if(Array.isArray(pMem))J=pMem.join("");let P,K;try{if(E.isSQLableTypedArray(J))P=p.allocFromTypedArray(J),K=J.byteLength;else if(typeof J==="string")[P,K]=p.allocCString(J);else return E.sqlite3__wasm_db_error(d.sqlite3_db_handle(ee),d.SQLITE_MISUSE,"Invalid 3rd argument type for sqlite3_bind_text().");return O(ee,U,P,K,d.SQLITE_WASM_DEALLOC)}catch(oe){return p.dealloc(P),E.sqlite3__wasm_db_error(d.sqlite3_db_handle(ee),oe)}},d.sqlite3_bind_blob=function X(ee,U,J,pe,S){if(X.length!==arguments.length)return I(d.sqlite3_db_handle(ee),"sqlite3_bind_blob",X.length);else if(p.isPtr(J)||J===null)return R(ee,U,J,pe,S);else if(J instanceof ArrayBuffer)J=new Uint8Array(J);else if(Array.isArray(J))J=J.join("");let P,K;try{if(E.isBindableTypedArray(J))P=p.allocFromTypedArray(J),K=pe>=0?pe:J.byteLength;else if(typeof J==="string")[P,K]=p.allocCString(J);else return E.sqlite3__wasm_db_error(d.sqlite3_db_handle(ee),d.SQLITE_MISUSE,"Invalid 3rd argument type for sqlite3_bind_blob().");return R(ee,U,P,K,d.SQLITE_WASM_DEALLOC)}catch(oe){return p.dealloc(P),E.sqlite3__wasm_db_error(d.sqlite3_db_handle(ee),oe)}}}if(!d.sqlite3_column_text){let O=p.xWrap.argAdapter("sqlite3_stmt*"),R=p.xWrap.argAdapter("int"),X=p.xWrap.argAdapter("sqlite3_value*"),ee=(U,J)=>p.typedArrayToString(p.heap8u(),Number(U),Number(U)+J);d.sqlite3_column_text=function(U,J){let pe=O(U),S=R(J),P=p.exports.sqlite3_column_text(pe,S);return P?ee(P,p.exports.sqlite3_column_bytes(pe,S)):null},d.sqlite3_value_text=function(U){let J=X(U),pe=p.exports.sqlite3_value_text(J);return pe?ee(pe,p.exports.sqlite3_value_bytes(J)):null}}d.sqlite3_config=function(O,...R){if(arguments.length<2)return d.SQLITE_MISUSE;switch(O){case d.SQLITE_CONFIG_COVERING_INDEX_SCAN:case d.SQLITE_CONFIG_MEMSTATUS:case d.SQLITE_CONFIG_SMALL_MALLOC:case d.SQLITE_CONFIG_SORTERREF_SIZE:case d.SQLITE_CONFIG_STMTJRNL_SPILL:case d.SQLITE_CONFIG_URI:return p.exports.sqlite3__wasm_config_i(O,R[0]);case d.SQLITE_CONFIG_LOOKASIDE:return p.exports.sqlite3__wasm_config_ii(O,R[0],R[1]);case d.SQLITE_CONFIG_MEMDB_MAXSIZE:return p.exports.sqlite3__wasm_config_j(O,R[0]);case d.SQLITE_CONFIG_GETMALLOC:case d.SQLITE_CONFIG_GETMUTEX:case d.SQLITE_CONFIG_GETPCACHE2:case d.SQLITE_CONFIG_GETPCACHE:case d.SQLITE_CONFIG_HEAP:case d.SQLITE_CONFIG_LOG:case d.SQLITE_CONFIG_MALLOC:case d.SQLITE_CONFIG_MMAP_SIZE:case d.SQLITE_CONFIG_MULTITHREAD:case d.SQLITE_CONFIG_MUTEX:case d.SQLITE_CONFIG_PAGECACHE:case d.SQLITE_CONFIG_PCACHE2:case d.SQLITE_CONFIG_PCACHE:case d.SQLITE_CONFIG_PCACHE_HDRSZ:case d.SQLITE_CONFIG_PMASZ:case d.SQLITE_CONFIG_SERIALIZED:case d.SQLITE_CONFIG_SINGLETHREAD:case d.SQLITE_CONFIG_SQLLOG:case d.SQLITE_CONFIG_WIN32_HEAPSIZE:default:return d.SQLITE_NOTFOUND}};{let O=new Set;d.sqlite3_auto_extension=function(R){if(R instanceof Function)R=p.installFunction("i(ppp)",R);else if(arguments.length!==1||!p.isPtr(R))return d.SQLITE_MISUSE;let X=p.exports.sqlite3_auto_extension(R);if(R!==arguments[0])if(X===0)O.add(R);else p.uninstallFunction(R);return X},d.sqlite3_cancel_auto_extension=function(R){if(!R||arguments.length!==1||!p.isPtr(R))return 0;return p.exports.sqlite3_cancel_auto_extension(R)},d.sqlite3_reset_auto_extension=function(){p.exports.sqlite3_reset_auto_extension();for(let R of O)p.uninstallFunction(R);O.clear()}}p.xWrap.FuncPtrAdapter.warnOnUse=!0;let H=f.StructBinder,G=function O(R,X,ee,U=O.installMethodArgcCheck){if(!(R instanceof H.StructType))c("Usage error: target object is-not-a StructType.");else if(!(ee instanceof Function)&&!p.isPtr(ee))c("Usage error: expecting a Function or WASM pointer to one.");if(arguments.length===1)return(P,K)=>O(R,P,K,U);if(!O.argcProxy)O.argcProxy=function(P,K,oe,W){return function(...he){if(oe.length!==arguments.length)c("Argument mismatch for",P.structInfo.name+"::"+K+": Native signature is:",W);return oe.apply(this,he)}},O.removeFuncList=function(){if(this.ondispose.__removeFuncList)this.ondispose.__removeFuncList.forEach((P,K)=>{if(p.isPtr(P))try{p.uninstallFunction(P)}catch(oe){}}),delete this.ondispose.__removeFuncList};let J=R.memberSignature(X);if(J.length<2)c("Member",X,"does not have a function pointer signature:",J);let pe=R.memberKey(X),S=U&&!p.isPtr(ee)?O.argcProxy(R,pe,ee,J):ee;if(p.isPtr(S)){if(S&&!p.functionEntry(S))c("Pointer",S,"is not a WASM function table entry.");R[pe]=S}else{let P=p.installFunction(S,J);if(R[pe]=P,!R.ondispose||!R.ondispose.__removeFuncList)R.addOnDispose("ondispose.__removeFuncList handler",O.removeFuncList),R.ondispose.__removeFuncList=[];R.ondispose.__removeFuncList.push(pe,P)}return(P,K)=>O(R,P,K,U)};G.installMethodArgcCheck=!1;let le=function(O,R,X=G.installMethodArgcCheck){let ee=new Map;for(let U of Object.keys(R)){let J=R[U],pe=ee.get(J);if(pe){let S=O.memberKey(U);O[S]=O[O.memberKey(pe)]}else G(O,U,J,X),ee.set(J,U)}return O};H.StructType.prototype.installMethod=function(R,X,ee=G.installMethodArgcCheck){return arguments.length<3&&R&&typeof R==="object"?le(this,...arguments):G(this,...arguments)},H.StructType.prototype.installMethods=function(O,R=G.installMethodArgcCheck){return le(this,O,R)}}),globalThis.sqlite3ApiBootstrap.initializers.push(function(f){let c=(...F)=>{throw new f.SQLite3Error(...F)},{capi:d,wasm:p,util:E}=f,b=function(F){return(...g)=>F("sqlite3.oo1:",...g)};f.__isUnderTest?b(console.debug.bind(console)):b(f.config.debug),f.__isUnderTest?b(console.warn.bind(console)):b(f.config.warn),f.__isUnderTest?b(console.error.bind(console)):b(f.config.error);let I=new WeakMap,V=new Set,M=new WeakMap,C=(F,g,w)=>{let T=Object.getOwnPropertyDescriptor(F,g);return T?T.value:w},q=function(F,g){if(g){if(F instanceof O)F=F.pointer;c(g,"sqlite3 result code",g+":",F?d.sqlite3_errmsg(F):d.sqlite3_errstr(g))}return arguments[0]},H=p.installFunction("i(ippp)",function(F,g,w,T){if(d.SQLITE_TRACE_STMT===F)console.log("SQL TRACE #"+ ++this.counter,"via sqlite3@"+g+"["+d.sqlite3_db_filename(g,null)+"]",p.cstrToJs(T))}.bind({counter:0})),G=Object.create(null),le=function F(...g){let w=F.normalizeArgs(...g),T;if(T=w["sqlite3*"]){if(!w["sqlite3*:takeOwnership"])V.add(this);this.filename=d.sqlite3_db_filename(T,"main")}else{let{filename:N,vfs:te,flags:se}=w;if(typeof N!=="string"&&!p.isPtr(N)||typeof se!=="string"||te&&typeof te!=="string"&&!p.isPtr(te))f.config.error("Invalid DB ctor args",w,arguments),c("Invalid arguments for DB constructor:",arguments,"opts:",w);let A=0;if(se.indexOf("c")>=0)A|=d.SQLITE_OPEN_CREATE|d.SQLITE_OPEN_READWRITE;if(se.indexOf("w")>=0)A|=d.SQLITE_OPEN_READWRITE;if(A===0)A|=d.SQLITE_OPEN_READONLY;A|=d.SQLITE_OPEN_EXRESCODE;let L=p.pstack.pointer;try{let Q=p.pstack.allocPtr(),ne=d.sqlite3_open_v2(N,Q,A,te||p.ptr.null);if(T=p.peekPtr(Q),q(T,ne),d.sqlite3_extended_result_codes(T,1),se.indexOf("t")>=0)d.sqlite3_trace_v2(T,d.SQLITE_TRACE_STMT,H,T)}catch(Q){if(T)d.sqlite3_close_v2(T);throw Q}finally{p.pstack.restore(L)}this.filename=p.isPtr(N)?p.cstrToJs(N):N}if(I.set(this,T),M.set(this,Object.create(null)),!w["sqlite3*"])try{let N=G[d.sqlite3_js_db_vfs(T)||c("Internal error: cannot get VFS for new db handle.")];if(N)if(N instanceof Function)N(this,f);else q(T,d.sqlite3_exec(T,N,0,0,0))}catch(N){throw this.close(),N}};le.setVfsPostOpenCallback=function(F,g){if(!(g instanceof Function))c("dbCtorHelper.setVfsPostOpenCallback() should not be used with a non-function argument.",arguments);G[F]=g},le.normalizeArgs=function(F=":memory:",g="c",w=null){let T={};if(arguments.length===1&&arguments[0]&&typeof arguments[0]==="object"){if(Object.assign(T,arguments[0]),T.flags===void 0)T.flags="c";if(T.vfs===void 0)T.vfs=null;if(T.filename===void 0)T.filename=":memory:"}else T.filename=F,T.flags=g,T.vfs=w;return T};let O=function(...F){le.apply(this,F)};O.dbCtorHelper=le;let R={null:1,number:2,string:3,boolean:4,blob:5};if(p.bigIntEnabled)R.bigint=R.number;let X=function(){if(R!==arguments[2])c(d.SQLITE_MISUSE,"Do not call the Stmt constructor directly. Use DB.prepare().");if(this.db=arguments[0],I.set(this,arguments[1]),arguments.length>3&&!arguments[3])V.add(this)},ee=function(F){if(!F.pointer)c("DB has been closed.");return F},U=function(F,g){if(g!==(g|0)||g<0||g>=F.columnCount)c("Column index",g,"is out of range.");return F},J=function(F,g){let w=Object.create(null);switch(w.opt=Object.create(null),g.length){case 1:if(typeof g[0]==="string"||E.isSQLableTypedArray(g[0]))w.sql=g[0];else if(Array.isArray(g[0]))w.sql=g[0];else if(g[0]&&typeof g[0]==="object")w.opt=g[0],w.sql=w.opt.sql;break;case 2:w.sql=g[0],w.opt=g[1];break;default:c("Invalid argument count for exec().")}if(w.sql=E.flexibleString(w.sql),typeof w.sql!=="string")c("Missing SQL argument or unsupported SQL value type.");let T=w.opt;switch(T.returnValue){case"resultRows":if(!T.resultRows)T.resultRows=[];w.returnVal=()=>T.resultRows;break;case"saveSql":if(!T.saveSql)T.saveSql=[];w.returnVal=()=>T.saveSql;break;case void 0:case"this":w.returnVal=()=>F;break;default:c("Invalid returnValue value:",T.returnValue)}if(!T.callback&&!T.returnValue&&T.rowMode!==void 0){if(!T.resultRows)T.resultRows=[];w.returnVal=()=>T.resultRows}if(T.callback||T.resultRows)switch(T.rowMode===void 0?"array":T.rowMode){case"object":w.cbArg=(N,te)=>{if(!te.columnNames)te.columnNames=N.getColumnNames([]);let se=N.get([]),A=Object.create(null);for(let L in te.columnNames)A[te.columnNames[L]]=se[L];return A};break;case"array":w.cbArg=(N)=>N.get([]);break;case"stmt":if(Array.isArray(T.resultRows))c("exec(): invalid rowMode for a resultRows array: must","be one of 'array', 'object',","a result column number, or column name reference.");w.cbArg=(N)=>N;break;default:if(E.isInt32(T.rowMode)){w.cbArg=(N)=>N.get(T.rowMode);break}else if(typeof T.rowMode==="string"&&T.rowMode.length>1&&T.rowMode[0]==="$"){let N=T.rowMode.substr(1);w.cbArg=(te)=>{let se=te.get(Object.create(null))[N];return se===void 0?c(d.SQLITE_NOTFOUND,"exec(): unknown result column:",N):se};break}c("Invalid rowMode:",T.rowMode)}return w},pe=(F,g,w,...T)=>{let N=F.prepare(g);try{let te=N.bind(w).step()?N.get(...T):void 0;return N.reset(),te}finally{N.finalize()}},S=(F,g,w,T)=>F.exec({sql:g,bind:w,rowMode:T,returnValue:"resultRows"});O.checkRc=(F,g)=>q(F,g),O.prototype={isOpen:function(){return!!this.pointer},affirmOpen:function(){return ee(this)},close:function(){let F=this.pointer;if(F){if(this.onclose&&this.onclose.before instanceof Function)try{this.onclose.before(this)}catch(g){}if(Object.keys(M.get(this)).forEach((g,w)=>{if(w&&w.pointer)try{w.finalize()}catch(T){}}),I.delete(this),M.delete(this),!V.delete(this))d.sqlite3_close_v2(F);if(this.onclose&&this.onclose.after instanceof Function)try{this.onclose.after(this)}catch(g){}delete this.filename}},changes:function(F=!1,g=!1){let w=ee(this).pointer;if(F)return g?d.sqlite3_total_changes64(w):d.sqlite3_total_changes(w);else return g?d.sqlite3_changes64(w):d.sqlite3_changes(w)},dbFilename:function(F="main"){return d.sqlite3_db_filename(ee(this).pointer,F)},dbName:function(F=0){return d.sqlite3_db_name(ee(this).pointer,F)},dbVfsName:function(F=0){let g,w=d.sqlite3_js_db_vfs(ee(this).pointer,F);if(w){let T=new d.sqlite3_vfs(w);try{g=p.cstrToJs(T.$zName)}finally{T.dispose()}}return g},prepare:function(F){ee(this);let g=p.pstack.pointer,w,T;try{w=p.pstack.alloc(8),O.checkRc(this,d.sqlite3_prepare_v2(this.pointer,F,-1,w,null)),T=p.peekPtr(w)}finally{p.pstack.restore(g)}if(!T)c("Cannot prepare empty SQL.");let N=new X(this,T,R);return M.get(this)[T]=N,N},exec:function(){ee(this);let F=J(this,arguments);if(!F.sql)return c("exec() requires an SQL string.");let g=F.opt,w=g.callback,T=Array.isArray(g.resultRows)?g.resultRows:void 0,N,te=g.bind,se=!!(F.cbArg||g.columnNames||T),A=p.scopedAllocPush(),L=Array.isArray(g.saveSql)?g.saveSql:void 0;try{let Q=E.isSQLableTypedArray(F.sql),ne=Q?F.sql.byteLength:p.jstrlen(F.sql),ye=p.scopedAlloc(2*p.ptr.size+(ne+1)),Te=p.ptr.add(ye,p.ptr.size),Ie=p.ptr.add(Te,p.ptr.size),qe=p.ptr.add(Ie,ne);if(Q)p.heap8().set(F.sql,Ie);else p.jstrcpy(F.sql,p.heap8(),Ie,ne,!1);p.poke8(p.ptr.add(Ie,ne),0);while(Ie&&p.peek8(Ie)){p.pokePtr([ye,Te],0),O.checkRc(this,d.sqlite3_prepare_v3(this.pointer,Ie,ne,0,ye,Te));let Ge=p.peekPtr(ye);if(Ie=p.peekPtr(Te),ne=Number(p.ptr.add(qe,-Ie)),!Ge)continue;if(L)L.push(d.sqlite3_sql(Ge).trim());if(N=new X(this,Ge,R),te&&N.parameterCount)N.bind(te),te=null;if(se&&N.columnCount){let ct=Array.isArray(g.columnNames)?0:1;if(se=!1,F.cbArg||T){let zt=Object.create(null);for(;N.step();he.delete(N)){if(ct++===0)N.getColumnNames(zt.columnNames=g.columnNames||[]);he.add(N);let Ir=F.cbArg(N,zt);if(T)T.push(Ir);if(w&&w.call(g,Ir,N)===!1)break}he.delete(N)}if(ct===0)N.getColumnNames(g.columnNames)}else N.step();N.reset().finalize(),N=null}}finally{if(N)he.delete(N),N.finalize();p.scopedAllocPop(A)}return F.returnVal()},createFunction:function(g,w,T){let N=(zt)=>zt instanceof Function;switch(arguments.length){case 1:T=g,g=T.name,w=T.xFunc||0;break;case 2:if(!N(w))T=w,w=T.xFunc||0;break;case 3:break;default:break}if(!T)T={};if(typeof g!=="string")c("Invalid arguments: missing function name.");let te=T.xStep||0,se=T.xFinal||0,A=T.xValue||0,L=T.xInverse||0,Q=void 0;if(N(w)){if(Q=!1,N(te)||N(se))c("Ambiguous arguments: scalar or aggregate?");te=se=null}else if(N(te)){if(!N(se))c("Missing xFinal() callback for aggregate or window UDF.");w=null}else if(N(se))c("Missing xStep() callback for aggregate or window UDF.");else c("Missing function-type properties.");if(Q===!1){if(N(A)||N(L))c("xValue and xInverse are not permitted for non-window UDFs.")}else if(N(A)){if(!N(L))c("xInverse must be provided if xValue is.");Q=!0}else if(N(L))c("xValue must be provided if xInverse is.");let ne=T.pApp;if(ne!==void 0&&ne!==null&&!p.isPtr(ne))c("Invalid value for pApp property. Must be a legal WASM pointer value.");let ye=T.xDestroy||0;if(ye&&!N(ye))c("xDestroy property must be a function.");let Te=0;if(C(T,"deterministic"))Te|=d.SQLITE_DETERMINISTIC;if(C(T,"directOnly"))Te|=d.SQLITE_DIRECTONLY;if(C(T,"innocuous"))Te|=d.SQLITE_INNOCUOUS;g=g.toLowerCase();let Ie=w||te,qe=C(T,"arity"),Ge=typeof qe==="number"?qe:Ie.length?Ie.length-1:0,ct;if(Q)ct=d.sqlite3_create_window_function(this.pointer,g,Ge,d.SQLITE_UTF8|Te,ne||0,te,se,A,L,ye);else ct=d.sqlite3_create_function_v2(this.pointer,g,Ge,d.SQLITE_UTF8|Te,ne||0,w,te,se,ye);return O.checkRc(this,ct),this},selectValue:function(F,g,w){return pe(this,F,g,0,w)},selectValues:function(F,g,w){let T=this.prepare(F),N=[];try{T.bind(g);while(T.step())N.push(T.get(0,w));T.reset()}finally{T.finalize()}return N},selectArray:function(F,g){return pe(this,F,g,[])},selectObject:function(F,g){return pe(this,F,g,{})},selectArrays:function(F,g){return S(this,F,g,"array")},selectObjects:function(F,g){return S(this,F,g,"object")},openStatementCount:function(){return this.pointer?Object.keys(M.get(this)).length:0},transaction:function(F){let g="BEGIN";if(arguments.length>1){if(/[^a-zA-Z]/.test(arguments[0]))c(d.SQLITE_MISUSE,"Invalid argument for BEGIN qualifier.");g+=" "+arguments[0],F=arguments[1]}ee(this).exec(g);try{let w=F(this);return this.exec("COMMIT"),w}catch(w){throw this.exec("ROLLBACK"),w}},savepoint:function(F){ee(this).exec("SAVEPOINT oo1");try{let g=F(this);return this.exec("RELEASE oo1"),g}catch(g){throw this.exec("ROLLBACK to SAVEPOINT oo1; RELEASE SAVEPOINT oo1"),g}},checkRc:function(F){return q(this,F)}},O.wrapHandle=function(F,g=!1){if(!F||!p.isPtr(F))throw new f.SQLite3Error(d.SQLITE_MISUSE,"Argument must be a WASM sqlite3 pointer");return new O({"sqlite3*":F,"sqlite3*:takeOwnership":!!g})};let P=function(F){if(!F.pointer)c("Stmt has been closed.");return F},K=function(F){let g=R[F===null||F===void 0?"null":typeof F];switch(g){case R.boolean:case R.null:case R.number:case R.string:return g;case R.bigint:return p.bigIntEnabled?g:void 0;default:return E.isBindableTypedArray(F)?R.blob:void 0}},oe=function(F){return K(F)||c("Unsupported bind() argument type:",typeof F)},W=function(F,g){let w=typeof g==="number"?g:d.sqlite3_bind_parameter_index(F.pointer,g);if(w===0||!E.isInt32(w))c("Invalid bind() parameter name: "+g);else if(w<1||w>F.parameterCount)c("Bind index",g,"is out of range.");return w},he=new Set,we=new Set,me=function(F,g){if(he.has(F))c("Operation is illegal when statement is locked:",g);return F},ve=function F(g,w,T,N){if(me(P(g),"bind()"),!F._)F._tooBigInt=(se)=>c("BigInt value is too big to store without precision loss:",se),F._={string:function(se,A,L,Q){let[ne,ye]=p.allocCString(L,!0);return(Q?d.sqlite3_bind_blob:d.sqlite3_bind_text)(se.pointer,A,ne,ye,d.SQLITE_WASM_DEALLOC)}};oe(N),w=W(g,w);let te=0;switch(N===null||N===void 0?R.null:T){case R.null:te=d.sqlite3_bind_null(g.pointer,w);break;case R.string:te=F._.string(g,w,N,!1);break;case R.number:{let se;if(E.isInt32(N))se=d.sqlite3_bind_int;else if(typeof N==="bigint")if(!E.bigIntFits64(N))F._tooBigInt(N);else if(p.bigIntEnabled)se=d.sqlite3_bind_int64;else if(E.bigIntFitsDouble(N))N=Number(N),se=d.sqlite3_bind_double;else F._tooBigInt(N);else if(N=Number(N),p.bigIntEnabled&&Number.isInteger(N))se=d.sqlite3_bind_int64;else se=d.sqlite3_bind_double;te=se(g.pointer,w,N);break}case R.boolean:te=d.sqlite3_bind_int(g.pointer,w,N?1:0);break;case R.blob:{if(typeof N==="string"){te=F._.string(g,w,N,!0);break}else if(N instanceof ArrayBuffer)N=new Uint8Array(N);else if(!E.isBindableTypedArray(N))c("Binding a value as a blob requires","that it be a string, Uint8Array, Int8Array, or ArrayBuffer.");let se=p.alloc(N.byteLength||1);p.heap8().set(N.byteLength?N:[0],Number(se)),te=d.sqlite3_bind_blob(g.pointer,w,se,N.byteLength,d.SQLITE_WASM_DEALLOC);break}default:f.config.warn("Unsupported bind() argument type:",N),c("Unsupported bind() argument type: "+typeof N)}if(te)O.checkRc(g.db.pointer,te);return g};X.prototype={finalize:function(){let F=this.pointer;if(F){me(this,"finalize()");let g=V.delete(this)?0:d.sqlite3_finalize(F);return delete M.get(this.db)[F],I.delete(this),he.delete(this),we.delete(this),delete this.parameterCount,delete this.db,g}},clearBindings:function(){return me(P(this),"clearBindings()"),d.sqlite3_clear_bindings(this.pointer),we.delete(this),this},reset:function(F){if(me(this,"reset()"),F)this.clearBindings();let g=d.sqlite3_reset(P(this).pointer);return we.delete(this),q(this.db,g),this},bind:function(){P(this);let F,g;switch(arguments.length){case 1:F=1,g=arguments[0];break;case 2:F=arguments[0],g=arguments[1];break;default:c("Invalid bind() arguments.")}if(g===void 0)return this;else if(!this.parameterCount)c("This statement has no bindable parameters.");if(we.delete(this),g===null)return ve(this,F,R.null,g);else if(Array.isArray(g)){if(arguments.length!==1)c("When binding an array, an index argument is not permitted.");return g.forEach((w,T)=>ve(this,T+1,oe(w),w)),this}else if(g instanceof ArrayBuffer)g=new Uint8Array(g);if(typeof g==="object"&&!E.isBindableTypedArray(g)){if(arguments.length!==1)c("When binding an object, an index argument is not permitted.");return Object.keys(g).forEach((w)=>ve(this,w,oe(g[w]),g[w])),this}else return ve(this,F,oe(g),g);c("Should not reach this point.")},bindAsBlob:function(F,g){if(P(this),arguments.length===1)g=F,F=1;let w=oe(g);if(R.string!==w&&R.blob!==w&&R.null!==w)c("Invalid value type for bindAsBlob()");return ve(this,F,R.blob,g)},step:function(){me(this,"step()");let F=d.sqlite3_step(P(this).pointer);switch(F){case d.SQLITE_DONE:return we.delete(this),!1;case d.SQLITE_ROW:return we.add(this),!0;default:we.delete(this),f.config.warn("sqlite3_step() rc=",F,d.sqlite3_js_rc_str(F),"SQL =",d.sqlite3_sql(this.pointer)),O.checkRc(this.db.pointer,F)}},stepReset:function(){return this.step(),this.reset()},stepFinalize:function(){try{let F=this.step();return this.reset(),F}finally{try{this.finalize()}catch(F){}}},get:function(F,g){if(!we.has(P(this)))c("Stmt.step() has not (recently) returned true.");if(Array.isArray(F)){let w=0,T=this.columnCount;while(w<T)F[w]=this.get(w++);return F}else if(F&&typeof F==="object"){let w=0,T=this.columnCount;while(w<T)F[d.sqlite3_column_name(this.pointer,w)]=this.get(w++);return F}switch(U(this,F),g===void 0?d.sqlite3_column_type(this.pointer,F):g){case d.SQLITE_NULL:return null;case d.SQLITE_INTEGER:if(p.bigIntEnabled){let w=d.sqlite3_column_int64(this.pointer,F);if(w>=Number.MIN_SAFE_INTEGER&&w<=Number.MAX_SAFE_INTEGER)return Number(w).valueOf();return w}else{let w=d.sqlite3_column_double(this.pointer,F);if(w>Number.MAX_SAFE_INTEGER||w<Number.MIN_SAFE_INTEGER)c("Integer is out of range for JS integer range: "+w);return E.isInt32(w)?w|0:w}case d.SQLITE_FLOAT:return d.sqlite3_column_double(this.pointer,F);case d.SQLITE_TEXT:return d.sqlite3_column_text(this.pointer,F);case d.SQLITE_BLOB:{let w=d.sqlite3_column_bytes(this.pointer,F),T=d.sqlite3_column_blob(this.pointer,F),N=new Uint8Array(w);if(w){if(N.set(p.heap8u().slice(Number(T),Number(T)+w),0),this.db._blobXfer instanceof Array)this.db._blobXfer.push(N.buffer)}return N}default:c("Don't know how to translate","type of result column #"+F+".")}c("Not reached.")},getInt:function(F){return this.get(F,d.SQLITE_INTEGER)},getFloat:function(F){return this.get(F,d.SQLITE_FLOAT)},getString:function(F){return this.get(F,d.SQLITE_TEXT)},getBlob:function(F){return this.get(F,d.SQLITE_BLOB)},getJSON:function(F){let g=this.get(F,d.SQLITE_STRING);return g===null?g:JSON.parse(g)},getColumnName:function(F){return d.sqlite3_column_name(U(P(this),F).pointer,F)},getColumnNames:function(F=[]){U(P(this),0);let g=this.columnCount;for(let w=0;w<g;++w)F.push(d.sqlite3_column_name(this.pointer,w));return F},getParamIndex:function(F){return P(this).parameterCount?d.sqlite3_bind_parameter_index(this.pointer,F):void 0},getParamName:function(F){return P(this).parameterCount?d.sqlite3_bind_parameter_name(this.pointer,F):void 0},isBusy:function(){return d.sqlite3_stmt_busy(P(this))!==0},isReadOnly:function(){return d.sqlite3_stmt_readonly(P(this))!==0}};{let F={enumerable:!0,get:function(){return I.get(this)},set:()=>c("The pointer property is read-only.")};Object.defineProperty(X.prototype,"pointer",F),Object.defineProperty(O.prototype,"pointer",F)}Object.defineProperty(X.prototype,"columnCount",{enumerable:!1,get:function(){return d.sqlite3_column_count(this.pointer)},set:()=>c("The columnCount property is read-only.")}),Object.defineProperty(X.prototype,"parameterCount",{enumerable:!1,get:function(){return d.sqlite3_bind_parameter_count(this.pointer)},set:()=>c("The parameterCount property is read-only.")}),X.wrapHandle=function(F,g,w=!1){if(!(F instanceof O)||!F.pointer)throw new f.SQLite3Error(f.SQLITE_MISUSE,"First argument must be an opened sqlite3.oo1.DB instance");if(!g||!p.isPtr(g))throw new f.SQLite3Error(f.SQLITE_MISUSE,"Second argument must be a WASM sqlite3_stmt pointer");return new X(F,g,R,!!w)},f.oo1={DB:O,Stmt:X}}),globalThis.sqlite3ApiBootstrap.initializers.push(function(f){let c=f.util;f.initWorker1API=function(){let d=(...H)=>{throw Error(H.join(" "))};if(!(globalThis.WorkerGlobalScope instanceof Function))d("initWorker1API() must be run from a Worker thread.");let p=this.sqlite3||d("Missing this.sqlite3 object."),E=p.oo1.DB,b=function(H){let G=I.idMap.get(H);if(G)return G;return G="db#"+ ++I.idSeq+":"+Math.floor(Math.random()*1e8)+":"+Math.floor(Math.random()*1e8),I.idMap.set(H,G),G},I={dbList:[],idSeq:0,idMap:new WeakMap,xfer:[],open:function(H){let G=new E(H);if(this.dbs[b(G)]=G,this.dbList.indexOf(G)<0)this.dbList.push(G);return G},close:function(H,G){if(H){delete this.dbs[b(H)];let le=H.filename,O=c.sqlite3__wasm_db_vfs(H.pointer,0);H.close();let R=this.dbList.indexOf(H);if(R>=0)this.dbList.splice(R,1);if(G&&le&&O)c.sqlite3__wasm_vfs_unlink(O,le)}},post:function(H,G){if(G&&G.length)globalThis.postMessage(H,Array.from(G)),G.length=0;else globalThis.postMessage(H)},dbs:Object.create(null),getDb:function(H,G=!0){return this.dbs[H]||(G?d("Unknown (or closed) DB ID:",H):void 0)}},V=function(H=I.dbList[0]){return H&&H.pointer?H:d("DB is not opened.")},M=function(H,G=!0){let le=I.getDb(H.dbId,!1)||I.dbList[0];return G?V(le):le},C=function(){return I.dbList[0]&&b(I.dbList[0])},q={open:function(H){let G=Object.create(null),le=H.args||Object.create(null);if(le.simulateError)d("Throwing because of simulateError flag.");let O=Object.create(null);G.vfs=le.vfs,G.filename=le.filename||"";let R=I.open(G);return O.filename=R.filename,O.persistent=!!p.capi.sqlite3_js_db_uses_vfs(R.pointer,"opfs"),O.dbId=b(R),O.vfs=R.dbVfsName(),O},close:function(H){let G=M(H,!1),le={filename:G&&G.filename};if(G){let O=H.args&&typeof H.args==="object"?!!H.args.unlink:!1;I.close(G,O)}return le},exec:function(H){let G=typeof H.args==="string"?{sql:H.args}:H.args||Object.create(null);if(G.rowMode==="stmt")d("Invalid rowMode for 'exec': stmt mode","does not work in the Worker API.");else if(!G.sql)d("'exec' requires input SQL.");let le=M(H);if(G.callback||Array.isArray(G.resultRows))le._blobXfer=I.xfer;let O=G.callback,R=0,X=!!G.columnNames;if(typeof O==="string"){if(!X)G.columnNames=[];G.callback=function(ee,U){I.post({type:O,columnNames:G.columnNames,rowNumber:++R,row:ee},I.xfer)}}try{let ee=G.countChanges?le.changes(!0,G.countChanges===64):void 0;if(le.exec(G),ee!==void 0)G.changeCount=le.changes(!0,G.countChanges===64)-ee;let U=G.lastInsertRowId?p.capi.sqlite3_last_insert_rowid(le):void 0;if(U!==void 0)G.lastInsertRowId=U;if(G.callback instanceof Function)G.callback=O,I.post({type:O,columnNames:G.columnNames,rowNumber:null,row:void 0})}finally{if(delete le._blobXfer,G.callback)G.callback=O}return G},"config-get":function(){let H=Object.create(null),G=p.config;return["bigIntEnabled"].forEach(function(le){if(Object.getOwnPropertyDescriptor(G,le))H[le]=G[le]}),H.version=p.version,H.vfsList=p.capi.sqlite3_js_vfs_list(),H},export:function(H){let G=M(H),le={byteArray:p.capi.sqlite3_js_db_export(G.pointer),filename:G.filename,mimetype:"application/x-sqlite3"};return I.xfer.push(le.byteArray.buffer),le},toss:function(H){d("Testing worker exception")}};globalThis.onmessage=async function(H){H=H.data;let G,le=H.dbId,O=H.type,R=performance.now();try{if(q.hasOwnProperty(O)&&q[O]instanceof Function)G=await q[O](H);else d("Unknown db worker message type:",H.type)}catch(X){if(O="error",G={operation:H.type,message:X.message,errorClass:X.name,input:H},X.stack)G.stack=typeof X.stack==="string"?X.stack.split(/\n\s*/):X.stack}if(!le)le=G.dbId||C();I.post({type:O,dbId:le,messageId:H.messageId,workerReceivedTime:R,workerRespondTime:performance.now(),departureTime:H.departureTime,result:G},I.xfer)},globalThis.postMessage({type:"sqlite3-api",result:"worker1-ready"})}.bind({sqlite3:f})}),globalThis.sqlite3ApiBootstrap.initializers.push(function(f){let{wasm:c,capi:d}=f,p=f.util.toss3,E=Object.create(null);f.vfs=E,d.sqlite3_vfs.prototype.registerVfs=function(b=!1){if(!(this instanceof f.capi.sqlite3_vfs))p("Expecting a sqlite3_vfs-type argument.");let I=d.sqlite3_vfs_register(this,b?1:0);if(I)p("sqlite3_vfs_register(",this,") failed with rc",I);if(this.pointer!==d.sqlite3_vfs_find(this.$zName))p("BUG: sqlite3_vfs_find(vfs.$zName) failed for just-installed VFS",this);return this},E.installVfs=function(b){let I=0,V=["io","vfs"];for(let M of V){let C=b[M];if(C){if(++I,C.struct.installMethods(C.methods,!!C.applyArgcCheck),M==="vfs"){if(!C.struct.$zName&&typeof C.name==="string")C.struct.addOnDispose(C.struct.$zName=c.allocCString(C.name));C.struct.registerVfs(!!C.asDefault)}}}if(!I)p("Misuse: installVfs() options object requires at least","one of:",V);return this}}),globalThis.sqlite3ApiBootstrap.initializers.push(function(f){if(!f.wasm.exports.sqlite3_declare_vtab)return;let{wasm:c,capi:d}=f,p=f.util.toss3,E=Object.create(null);f.vtab=E;let b=d.sqlite3_index_info;b.prototype.nthConstraint=function(M,C=!1){if(M<0||M>=this.$nConstraint)return!1;let q=c.ptr.add(this.$aConstraint,b.sqlite3_index_constraint.structInfo.sizeof*M);return C?q:new b.sqlite3_index_constraint(q)},b.prototype.nthConstraintUsage=function(M,C=!1){if(M<0||M>=this.$nConstraint)return!1;let q=c.ptr.add(this.$aConstraintUsage,b.sqlite3_index_constraint_usage.structInfo.sizeof*M);return C?q:new b.sqlite3_index_constraint_usage(q)},b.prototype.nthOrderBy=function(M,C=!1){if(M<0||M>=this.$nOrderBy)return!1;let q=c.ptr.add(this.$aOrderBy,b.sqlite3_index_orderby.structInfo.sizeof*M);return C?q:new b.sqlite3_index_orderby(q)};let I=function(M,C){return function(q,H=!1){if(arguments.length===0)q=new C;if(q instanceof C)return this.set(q.pointer,q),q;else if(!c.isPtr(q))f.SQLite3Error.toss("Invalid argument to",M+"()");let G=this.get(q);if(H)this.delete(q);return G}.bind(new Map)},V=function(M,C){let q=I(M,C);return Object.assign(Object.create(null),{StructType:C,create:(H)=>{let G=q();return c.pokePtr(H,G.pointer),G},get:(H)=>q(H),unget:(H)=>q(H,!0),dispose:(H)=>q(H,!0)?.dispose?.()})};E.xVtab=V("xVtab",d.sqlite3_vtab),E.xCursor=V("xCursor",d.sqlite3_vtab_cursor),E.xIndexInfo=(M)=>new d.sqlite3_index_info(M),E.xError=function M(C,q,H){if(M.errorReporter instanceof Function)try{M.errorReporter("sqlite3_module::"+C+"(): "+q.message)}catch(le){}let G;if(q instanceof f.WasmAllocError)G=d.SQLITE_NOMEM;else if(arguments.length>2)G=H;else if(q instanceof f.SQLite3Error)G=q.resultCode;return G||d.SQLITE_ERROR},E.xError.errorReporter=f.config.error.bind(f.config),E.xRowid=(M,C)=>c.poke(M,C,"i64"),E.setupModule=function(M){let C=!1,q=this instanceof d.sqlite3_module?this:M.struct||(C=new d.sqlite3_module);try{let H=M.methods||p("Missing 'methods' object.");for(let G of Object.entries({xConnect:"xCreate",xDisconnect:"xDestroy"})){let le=G[0],O=G[1];if(H[le]===!0)H[le]=H[O];else if(H[O]===!0)H[O]=H[le]}if(M.catchExceptions){let G=function(R,X){if(["xConnect","xCreate"].indexOf(R)>=0)return function(ee,U,J,pe,S,P){try{return X(...arguments)||0}catch(K){if(!(K instanceof f.WasmAllocError))c.dealloc(c.peekPtr(P)),c.pokePtr(P,c.allocCString(K.message));return E.xError(R,K)}};else return function(...ee){try{return X(...ee)||0}catch(U){return E.xError(R,U)}}},le=["xCreate","xConnect","xBestIndex","xDisconnect","xDestroy","xOpen","xClose","xFilter","xNext","xEof","xColumn","xRowid","xUpdate","xBegin","xSync","xCommit","xRollback","xFindFunction","xRename","xSavepoint","xRelease","xRollbackTo","xShadowName"],O=Object.create(null);for(let R of le){let X=H[R];if(!(X instanceof Function))continue;else if(R==="xConnect"&&H.xCreate===X)O[R]=H.xCreate;else if(R==="xCreate"&&H.xConnect===X)O[R]=H.xConnect;else O[R]=G(R,X)}q.installMethods(O,!1)}else q.installMethods(H,!!M.applyArgcCheck);if(q.$iVersion===0){let G;if(typeof M.iVersion==="number")G=M.iVersion;else if(q.$xIntegrity)G=4;else if(q.$xShadowName)G=3;else if(q.$xSavePoint||q.$xRelease||q.$xRollbackTo)G=2;else G=1;q.$iVersion=G}}catch(H){if(C)C.dispose();throw H}return q},d.sqlite3_module.prototype.setupModule=function(M){return E.setupModule.call(this,M)}}),globalThis.sqlite3ApiBootstrap.initializers.push(function(f){if(f.config.disable?.vfs?.kvvfs)return;let c=f.capi,{sqlite3_kvvfs_methods:d,KVVfsFile:p}=c,E=f.capi.sqlite3_vfs_find("kvvfs");if(delete c.sqlite3_kvvfs_methods,delete c.KVVfsFile,!E)return;let{util:b,wasm:I}=f,V=b.toss3,M=new d(I.exports.sqlite3__wasm_kvvfs_methods());b.assert(32<=M.$nKeySize,"unexpected kvvfsMethods.$nKeySize: "+M.$nKeySize);let C=Object.assign(Object.create(null),{rxJournalSuffix:/-journal$/,zKeyJrnl:I.allocCString("jrnl"),zKeySz:I.allocCString("sz"),keySize:M.$nKeySize,buffer:Object.assign(Object.create(null),{n:M.$nBufferSize,pool:Object.create(null)})});C.memBuffer=(B=0)=>C.buffer.pool[B]??=I.alloc(C.buffer.n),C.memBufferFree=(B)=>{let re=C.buffer.pool[B];if(re)I.dealloc(re),delete C.buffer.pool[B]};let q=()=>{},H=f.__isUnderTest?(...B)=>f.config.debug?.("kvvfs:",...B):q,G=(...B)=>f.config.warn?.("kvvfs:",...B),le=(...B)=>f.config.error?.("kvvfs:",...B);class O{#e=Object.create(null);#o=null;#i=0;constructor(){this.clear()}#t(){return this.#o??=Object.keys(this.#e)}key(B){if(B<0||B>=this.#i)return null;return this.#t()[B]}getItem(B){return this.#e[B]??null}setItem(B,re){if(!(B in this.#e))++this.#i,this.#o=null;this.#e[B]=""+re}removeItem(B){if(B in this.#e)delete this.#e[B],--this.#i,this.#o=null}clear(){this.#e=Object.create(null),this.#o=null,this.#i=0}get length(){return this.#i}}let R=(B)=>B==="local"||B==="session",X=(B)=>R(B)?"kvvfs-"+B+"-":"",ee=function(B,re=!1){if(R(B))return;let ae=new Blob([B]).size;if(!ae)V(c.SQLITE_MISUSE,"Empty name is not permitted.");let ue=C.keySize-1;if(C.rxJournalSuffix.test(B)){if(!re)V(c.SQLITE_MISUSE,"Storage names may not have a '-journal' suffix.")}else if(["-wal","-shm"].filter((Re)=>B.endsWith(Re)).length)V(c.SQLITE_MISUSE,"Storage names may not have a -wal or -shm suffix.");else ue-=8;if(ae>ue)V(c.SQLITE_RANGE,"Storage name is too long. Limit =",ue);let Se;for(Se=0;Se<ae;++Se){let Re=B.codePointAt(Se);if(Re<32)V(c.SQLITE_RANGE,"Illegal character ("+Re+"d) in storage name:",B)}},U=(B,re=void 0)=>Object.assign(Object.create(null),{jzClass:B,refc:1,deleteAtRefc0:!1,storage:re||new O,keyPrefix:X(B),files:[],listeners:void 0}),J=f.kvvfs=Object.create(null);if(f.__isUnderTest)J.log=Object.assign(Object.create(null),{xOpen:!1,xClose:!1,xWrite:!1,xRead:!1,xSync:!1,xAccess:!1,xFileControl:!1,xRcrdRead:!1,xRcrdWrite:!1,xRcrdDelete:!1});let pe=function(B){let re=C.rxJournalSuffix.test(B.jzClass)?B.jzClass.replace(C.rxJournalSuffix,""):B.jzClass+"-journal";if(J?.log?.xClose&&H("cleaning up storage handles [",B.jzClass,re,"]",B),delete C.storagePool[B.jzClass],delete C.storagePool[re],!f.__isUnderTest)delete B.storage,delete B.refc},S=(B)=>C.storagePool[B.jzClass]=C.storagePool[B.jzClass+"-journal"]=B,P=".";if(C.storagePool=Object.assign(Object.create(null),{[P]:U(P)}),globalThis.Storage){if(globalThis.localStorage instanceof globalThis.Storage)C.storagePool.local=U("local",globalThis.localStorage);if(globalThis.sessionStorage instanceof globalThis.Storage)C.storagePool.session=U("session",globalThis.sessionStorage)}C.builtinStorageNames=Object.keys(C.storagePool);let K=(B)=>C.builtinStorageNames.indexOf(B)>-1;for(let B of Object.keys(C.storagePool)){let re=C.storagePool[B];C.storagePool[B+"-journal"]=re}C.setError=(B=void 0,re=c.SQLITE_ERROR)=>{if(B)return C.lastError=B,B.resultCode|0||re;return delete C.lastError,0},C.popError=()=>{let B=C.lastError;return delete C.lastError,B};let oe=(B)=>{G("kvvfs.listener handler threw:",B)},W=I.exports.sqlite3__wasm_kvvfs_decode,he=I.exports.sqlite3__wasm_kvvfs_encode,we=async function(B,re,...ae){try{if(re.keyPrefix&&ae[0])ae[0]=ae[0].replace(re.keyPrefix,"");let ue,Se,Re,Oe;for(let ke of re.listeners){let Ce=Object.create(null);Ce.storageName=re.jzClass,Ce.type=B,ke.decodePages;let He=ke.events[B];if(He){if(!ke.includeJournal&&ae[0]==="jrnl")continue;if(B==="write"&&ke.decodePages&&+ae[0]>0){if(Ce.data=[ae[0]],Oe?.[ae[0]]){Ce.data[1]=Oe[ae[0]];continue}ue??=new TextEncoder("utf-8"),Se??=C.memBuffer(10),Re??=C.memBuffer(11);let Qe=ue.encode(ae[1]),Me=I.heap8u();Me.set(Qe,Number(Se)),Me[I.ptr.addn(Se,Qe.length)]=0;let mt=W(Se,Re,C.buffer.n);if(mt>0)Oe??=Object.create(null),Oe[ae[0]]=Ce.data[1]=Me.slice(Number(Re),I.ptr.addn(Re,mt));else continue}else Ce.data=ae.length?ae.length===1?ae[0]:ae:void 0;try{He(Ce)?.catch?.(oe)}catch(Qe){G("notifyListeners [",re.jzClass,"]",B,Qe)}}}}catch(ue){oe(ue)}},me=(B)=>typeof B==="string"?C.storagePool[B]:C.storagePool[I.cstrToJs(B)],ve=I.exports.sqlite3__wasm_kvvfsMakeKey,F=(B,re,ae)=>re&&B.keyPrefix?ve(re,ae):ae,g=(B,re,ae)=>I.cstrToJs(F(B,re,ae)),w=(B)=>+B.storage.getItem(B.keyPrefix+"sz"),T=new Map,N={vfs:Object.create(null),ioDb:Object.create(null),ioJrnl:Object.create(null)},te=new c.sqlite3_vfs(M.$pVfs),se=new c.sqlite3_io_methods(M.$pIoDb),A=new c.sqlite3_io_methods(M.$pIoJrnl),L=Object.create(null),Q=Object.assign(Object.create(null),{pFileHandles:T,cache:C,storageForZClass:me,KVVfsStorage:O,disablePageSizeChange:!0});if(J.log)J.internal=Q;let ne={recordHandler:{xRcrdRead:(B,re,ae,ue)=>{try{let Se=I.cstrToJs(B),Re=me(Se);if(!Re)return-1;let Oe=g(Re,B,re);J?.log?.xRcrdRead&&G("xRcrdRead",Se,Oe,ue,Re);let ke=Re.storage.getItem(Oe);if(ke===null)return-1;let Ce=ke.length;if(ue<=0)return Ce;else if(ue===1)return I.poke(ae,0),Ce;if(ue+1<Ce)V(c.SQLITE_RANGE,"xRcrdRead()",Se,Oe,"input buffer is too small: need",Ce,"but have",ue);let He=C.memBuffer(0),Qe=I.heap8(),Me;for(Me=0;Me<Ce;++Me)Qe[I.ptr.add(He,Me)]=ke.codePointAt(Me)&255;return Qe.copyWithin(Number(ae),Number(He),I.ptr.addn(He,Me)),Qe[I.ptr.add(ae,Ce)]=0,ue}catch(Se){return le("kvrecordRead()",Se),C.setError(Se),-2}},xRcrdWrite:(B,re,ae)=>{try{let ue=me(B),Se=g(ue,B,re),Re=I.cstrToJs(ae);return J?.log?.xRcrdWrite&&G("xRcrdWrite",Se,ue),ue.storage.setItem(Se,Re),ue.listeners&&we("write",ue,Se,Re),0}catch(ue){return le("kvrecordWrite()",ue),C.setError(ue,c.SQLITE_IOERR)}},xRcrdDelete:(B,re)=>{try{let ae=me(B),ue=g(ae,B,re);return J?.log?.xRcrdDelete&&G("xRcrdDelete",ue,ae),ae.storage.removeItem(ue),ae.listeners&&we("delete",ae,ue),0}catch(ae){return le("kvrecordDelete()",ae),C.setError(ae,c.SQLITE_IOERR)}}},vfs:{xOpen:function(B,re,ae,ue,Se){C.popError();let Re;try{if(!re)Re=I.allocCString(""+ae+"."+(Math.random()*1e5|0)),re=Re;let Oe=I.cstrToJs(re);if(J?.log?.xOpen&&H("xOpen",Oe,"flags =",ue),ee(Oe,!0),ue&(c.SQLITE_OPEN_MAIN_DB|c.SQLITE_OPEN_TEMP_DB|c.SQLITE_OPEN_TRANSIENT_DB)&&C.rxJournalSuffix.test(Oe))V(c.SQLITE_ERROR,"DB files may not have a '-journal' suffix.");let ke=me(Oe);if(!ke&&!(ue&c.SQLITE_OPEN_CREATE))V(c.SQLITE_ERROR,"Storage not found:",Oe);let Ce=N.vfs.xOpen(B,re,ae,ue,Se);if(Ce)return Ce;let He=!!(c.SQLITE_OPEN_DELETEONCLOSE&ue);if(I.isPtr(arguments[1])){if(c.sqlite3_uri_boolean(re,"delete-on-close",0))He=!0}let Qe=new p(ae);if(b.assert(Qe.$zClass,"Missing f.$zClass"),Qe.addOnDispose(Re),Re=void 0,ke)++ke.refc,ke.files.push(Qe),I.poke32(Se,ue);else{I.poke32(Se,ue|c.SQLITE_OPEN_CREATE),b.assert(!Qe.$isJournal,"Opening a journal before its db? "+Oe);let Me=Oe.replace(C.rxJournalSuffix,"");ke=U(Me),S(ke),ke.files.push(Qe),ke.deleteAtRefc0=He,J?.log?.xOpen&&H("xOpen installed storage handle [",Me,Me+"-journal","]",ke)}return T.set(ae,{store:ke,file:Qe,jzClass:Oe}),ke.listeners&&we("open",ke,ke.files.length),0}catch(Oe){return G("xOpen:",Oe),C.setError(Oe)}finally{Re&&I.dealloc(Re)}},xDelete:function(B,re,ae){C.popError();try{let ue=I.cstrToJs(re);if(C.rxJournalSuffix.test(ue))L.xRcrdDelete(re,C.zKeyJrnl);return 0}catch(ue){return G("xDelete",ue),C.setError(ue)}},xAccess:function(B,re,ae,ue){C.popError();try{let Se=me(re),Re=Se?.jzClass||I.cstrToJs(re);if(J?.log?.xAccess)H("xAccess",Re,"flags =",ae,"*pResOut =",I.peek32(ue),"store =",Se);if(!Se)try{ee(Re)}catch(Oe){return I.poke32(ue,0),0}if(Se){let Oe=Se.keyPrefix+(C.rxJournalSuffix.test(Re)?"jrnl":"1"),ke=Se.storage.getItem(Oe)?0:1;I.poke32(ue,ke)}else I.poke32(ue,0);return 0}catch(Se){return le("xAccess",Se),C.setError(Se)}},xRandomness:function(B,re,ae){let ue=I.heap8u(),Se=0,Re=Number(ae);for(;Se<re;++Se)ue[Re+Se]=Math.random()*255000&255;return re},xGetLastError:function(B,re,ae){let ue=C.popError();if(H("xGetLastError",ue),ue){let Se=I.scopedAllocPush();try{let[Re,Oe]=I.scopedAllocCString(ue.message,!0);if(I.cstrncpy(ae,Re,re),Oe>re)I.poke8(I.ptr.add(ae,re,-1),0);return H("set xGetLastError",ue.message),ue.resultCode|0||c.SQLITE_IOERR}catch(Re){return c.SQLITE_NOMEM}finally{I.scopedAllocPop(Se)}}return 0}},ioDb:{xClose:function(B){C.popError();try{let re=T.get(B);if(J?.log?.xClose&&H("xClose",B,re),re){T.delete(B);let ae=re.store;if(ae.files=ae.files.filter((ue)=>ue!==re.file),--ae.refc<=0&&ae.deleteAtRefc0)pe(ae);N.ioDb.xClose(B),re.file.dispose(),ae.listeners&&we("close",ae,ae.files.length)}return 0}catch(re){return le("xClose",re),C.setError(re)}},xFileControl:function(B,re,ae){C.popError();try{let ue=T.get(B);if(b.assert(ue,"Missing KVVfsFile handle"),J?.log?.xFileControl&&H("xFileControl",ue,"op =",re),re===c.SQLITE_FCNTL_PRAGMA&&Q.disablePageSizeChange){let Re=I.peekPtr(I.ptr.add(ae,I.ptr.size));if(I.cstrToJs(Re)==="page_size"){J?.log?.xFileControl&&H("xFileControl pragma",I.cstrToJs(Re));let Oe=I.peekPtr(I.ptr.add(ae,2*I.ptr.size));if(Oe)return J?.log?.xFileControl&&G("xFileControl pragma",ue,"NOT setting page size to",I.cstrToJs(Oe)),ue.file.$szPage=-1,0;else if(ue.file.$szPage>0)return J?.log?.xFileControl&&G("xFileControl",ue,"getting page size",ue.file.$szPage),I.pokePtr(ae,I.allocCString(""+ue.file.$szPage)),0}}let Se=N.ioDb.xFileControl(B,re,ae);if(Se==0&&c.SQLITE_FCNTL_SYNC===re)ue.store.listeners&&we("sync",ue.store,!1);return Se}catch(ue){return le("xFileControl",ue),C.setError(ue)}},xSync:function(B,re){C.popError();try{let ae=T.get(B);J?.log?.xSync&&H("xSync",ae),b.assert(ae,"Missing KVVfsFile handle");let ue=N.ioDb.xSync(B,re);if(ue==0&&ae.store.listeners)we("sync",ae.store,!0);return ue}catch(ae){return le("xSync",ae),C.setError(ae)}}},ioJrnl:{xClose:!0}};try{b.assert(C.buffer.n>132096,"Heap buffer is not large enough");for(let B of Object.entries(ne.recordHandler)){let re=B[0],ae=B[1];L[re]=ae,M[M.memberKey(re)]=I.installFunction(M.memberSignature(re),ae)}for(let B of Object.entries(ne.vfs)){let re=B[0],ae=B[1],ue=te.memberKey(re),Se=te.structInfo.members[re]||b.toss("Missing pVfs.structInfo[",re,"]");N.vfs[re]=I.functionEntry(te[ue]),te[ue]=I.installFunction(Se.signature,ae)}for(let B of Object.entries(ne.ioDb)){let re=B[0],ae=B[1],ue=se.memberKey(re);N.ioDb[re]=I.functionEntry(se[ue])||b.toss("Missing native pIoDb[",ue,"]"),se[ue]=I.installFunction(se.memberSignature(re),ae)}for(let B of Object.entries(ne.ioJrnl)){let re=B[0],ae=B[1],ue=A.memberKey(re);if(N.ioJrnl[re]=I.functionEntry(A[ue])||b.toss("Missing native pIoJrnl[",ue,"]"),ae===!0)A[ue]=se[ue]||b.toss("Missing copied pIoDb[",ue,"]");else A[ue]=I.installFunction(A.memberSignature(re),ae)}}finally{M.dispose(),te.dispose(),se.dispose(),A.dispose()}let ye=function B(re){if(re==="")return B("local")+B("session");let ae=me(re);if(!ae)return 0;if(ae.files.length)if(globalThis.localStorage===ae.storage||globalThis.sessionStorage===ae.storage);else V(c.SQLITE_ACCESS,"Cannot clear in-use database storage.");let ue=ae.storage,Se=[],Re,Oe=ue.length;for(Re=0;Re<Oe;++Re){let ke=ue.key(Re);if(!ae.keyPrefix||ke.startsWith(ae.keyPrefix))Se.push(ke)}return Se.forEach((ke)=>ue.removeItem(ke)),Se.length},Te=function B(re){if(re==="")return B("local")+B("session");let ae=me(re);if(!ae)return 0;let ue=ae.storage,Se,Re=0;for(Se=0;Se<ue.length;++Se){let Oe=ue.key(Se);if(!ae.keyPrefix||Oe.startsWith(ae.keyPrefix))Re+=Oe.length,Re+=ue.getItem(Oe).length}return Re*2},Ie=function(...re){let ae;if(re.length===1&&typeof re[0]==="object")ae=re[0];else if(re.length)ae=Object.assign(Object.create(null),{name:re[0]});let ue=ae?me(ae.name):null;if(!ue)V(c.SQLITE_NOTFOUND,"There is no kvvfs storage named",ae?.name);let Se=ue.storage,Re=Object.assign(Object.create(null),{name:ue.jzClass,timestamp:Date.now(),pages:[]}),Oe=Object.create(null),ke=ue.keyPrefix,Ce=ke?/^kvvfs-[^-]+-(\w+)/:void 0,He=0,Qe=Se.length;for(;He<Qe;++He){let Me=Se.key(He);if(!ke||Me.startsWith(ke)){let mt=(ke?Ce.exec(Me):void 0)?.[1]??Me;switch(mt){case"jrnl":if(ae.includeJournal)Re.journal=Se.getItem(Me);break;case"sz":Re.size=+Se.getItem(Me);break;default:if(mt=+mt,!b.isInt32(mt)||mt<=0)V(c.SQLITE_RANGE,"Malformed kvvfs key: "+Me);if(ae.decodePages){let Mt=Se.getItem(Me),rn=Mt.length,Zt=C.memBuffer(0),Pr=C.memBuffer(1),Nn=I.heap8u(),At=0;for(;At<rn;++At)Nn[I.ptr.add(Zt,At)]=Mt.codePointAt(At)&255;Nn[I.ptr.add(Zt,At)]=0;let ho=W(Zt,Pr,C.buffer.n);Oe[mt]=Nn.slice(Number(Pr),I.ptr.addn(Pr,ho))}else Oe[mt]=Se.getItem(Me);break}}}if(ae.decodePages)C.memBufferFree(1);return Object.keys(Oe).map((Me)=>+Me).sort().forEach((Me)=>Re.pages.push(Oe[Me])),Re},qe=function(B,re=!1){if(!B?.timestamp||!B.name||B.size===void 0||!Array.isArray(B.pages))V(c.SQLITE_MISUSE,"Malformed export object.");else if(!B.size||B.size!==(B.size|0)||B.size>=2147483647)V(c.SQLITE_RANGE,"Invalid db size: "+B.size);ee(B.name);let ae=me(B.name),ue=!ae;if(ae){if(!re)V(c.SQLITE_ACCESS,"Storage '"+B.name+"' already exists and","overwrite was not specified.");else if(!ae.files||!ae.jzClass)V(c.SQLITE_ERROR,"Internal storage object",B.name,"seems to be malformed.");else if(ae.files.length)V(c.SQLITE_IOERR_ACCESS,"Cannot import db storage while it is in use.");ye(B.name)}else ae=U(B.name);let Se=X(B.name),Re;try{let Oe=ae.storage;if(Oe.setItem(Se+"sz",B.size),B.journal)Oe.setItem(Se+"jrnl",B.journal);if(B.pages[0]instanceof Uint8Array)B.pages.forEach((ke,Ce)=>{let He=ke.length;Re??=C.memBuffer(1);let Qe=C.memBuffer(0),Me=I.heap8u();Me.set(ke,Number(Qe)),Me[I.ptr.addn(Qe,He)]=0;let mt=he(Qe,He,Re);b.assert(mt<C.buffer.n,"Impossibly long output - possibly smashed the heap"),b.assert(I.peek8(I.ptr.add(Re,mt))===0,"Expecting NUL-terminated encoded output");let Mt=I.cstrToJs(Re);Oe.setItem(Se+(Ce+1),Mt)});else if(B.pages[0])B.pages.forEach((ke,Ce)=>Oe.setItem(Se+(Ce+1),ke));if(ue)S(ae)}catch{if(!ue)try{ye(B.name)}catch(Oe){}}finally{if(Re)C.memBufferFree(1)}return this},Ge=function(B){let re=me(B);if(re){++re.refc;return}ee(B),S(U(B))},ct=function(B){let re=me(B);if(!re||R(re.jzClass)||K(re.jzClass)||C.rxJournalSuffix.test(B))return!1;if(re.refc>re.files.length||re.files.length===0){if(--re.refc<=0)pe(re);return!0}return!1},zt=function(B){if(!B||typeof B!=="object")V(c.SQLITE_MISUSE,"Expecting a listener object.");let re=me(B.storage);if(!re)if(B.storage&&B.reserve)Ge(B.storage),re=me(B.storage),b.assert(re,"Unexpectedly cannot fetch reserved storage "+B.storage);else V(c.SQLITE_NOTFOUND,"No such storage:",B.storage);if(B.events)(re.listeners??=[]).push(B)},Ir=function(B){let re=me(B?.storage);if(re?.listeners&&B.events){let ae=re.listeners.length;re.listeners=re.listeners.filter((Se)=>Se!==B);let ue=ae>re.listeners.length;if(!re.listeners.length)re.listeners=void 0;return ue}return!1};if(f.kvvfs.reserve=Ge,f.kvvfs.import=qe,f.kvvfs.export=Ie,f.kvvfs.unlink=ct,f.kvvfs.listen=zt,f.kvvfs.unlisten=Ir,f.kvvfs.exists=(B)=>!!me(B),f.kvvfs.estimateSize=Te,f.kvvfs.clear=ye,globalThis.Storage)c.sqlite3_js_kvvfs_size=(B="")=>Te(B),c.sqlite3_js_kvvfs_clear=(B="")=>ye(B);if(f.oo1?.DB){let B=f.oo1.DB;f.oo1.JsStorageDb=function(ae=f.oo1.JsStorageDb.defaultStorageName){let ue=B.dbCtorHelper.normalizeArgs(...arguments);switch(ue.vfs="kvvfs",ue.filename){case":sessionStorage:":ue.filename="session";break;case":localStorage:":ue.filename="local";break}let Se=/(file:(\/\/)?)([^?]+)/.exec(ue.filename);ee(Se?Se[3]:ue.filename),B.dbCtorHelper.call(this,ue)},f.oo1.JsStorageDb.defaultStorageName=C.storagePool.session?"session":P;let re=f.oo1.JsStorageDb;re.prototype=Object.create(B.prototype),re.clearStorage=ye,re.prototype.clearStorage=function(){return re.clearStorage(this.affirmOpen().dbFilename(),!0)},re.storageSize=Te,re.prototype.storageSize=function(){return re.storageSize(this.affirmOpen().dbFilename(),!0)}}if(f.__isUnderTest&&f.vtab){let B=Object.assign(Object.create(null),{rowid:{type:"INTEGER"},name:{type:"TEXT"},nRef:{type:"INTEGER"},nOpen:{type:"INTEGER"},isTransient:{type:"INTEGER"},dbSize:{type:"INTEGER"}});Object.keys(B).forEach((Oe,ke)=>B[Oe].colId=ke);let re=f.vtab,ae=Object.assign(Object.create(null),{row:function(){return C.storagePool[this.names[this.rowid]]}});Object.assign(Object.create(ae),{rowid:0,names:Object.keys(C.storagePool).filter((Oe)=>!C.rxJournalSuffix.test(Oe))});let ue=function(Oe,ke){let Ce=Oe instanceof c.sqlite3_vtab_cursor?Oe:re.xCursor.get(Oe);if(ke||!Ce.vTabState)Ce.vTabState=Object.assign(Object.create(ae),{rowid:0,names:Object.keys(C.storagePool).filter((He)=>!C.rxJournalSuffix.test(He))});return Ce.vTabState},Se=()=>{},Re=function Oe(){return Oe.mod??=new f.capi.sqlite3_module().setupModule({catchExceptions:!0,methods:{xConnect:function(ke,Ce,He,Qe,Me,mt){Se("xConnect");try{let Mt=[];Object.keys(B).forEach((Zt)=>{Mt.push(Zt+" "+B[Zt].type)});let rn=c.sqlite3_declare_vtab(ke,"CREATE TABLE ignored("+Mt.join(",")+")");if(rn===0){let Zt=re.xVtab.create(Me);b.assert(Zt===re.xVtab.get(I.peekPtr(Me)),"output pointer check failed")}return rn}catch(Mt){return re.xError("xConnect",Mt,c.SQLITE_ERROR)}},xCreate:I.ptr.null,xDisconnect:function(ke){return Se("xDisconnect",...arguments),re.xVtab.dispose(ke),0},xOpen:function(ke,Ce){return Se("xOpen",...arguments),re.xCursor.create(Ce),0},xClose:function(ke){Se("xClose",...arguments);let Ce=re.xCursor.unget(ke);return delete Ce.vTabState,Ce.dispose(),0},xNext:function(ke){Se("xNext",...arguments);let Ce=re.xCursor.get(ke);return++ue(Ce).rowid,0},xColumn:function(ke,Ce,He){Se("xColumn",...arguments);let Qe=ue(ke),Me=Qe.row();switch(b.assert(Me,"Unexpected xColumn call"),He){case B.rowid.colId:c.sqlite3_result_int(Ce,Qe.rowid);break;case B.name.colId:c.sqlite3_result_text(Ce,Me.jzClass,-1,c.SQLITE_TRANSIENT);break;case B.nRef.colId:c.sqlite3_result_int(Ce,Me.refc);break;case B.nOpen.colId:c.sqlite3_result_int(Ce,Me.files.length);break;case B.isTransient.colId:c.sqlite3_result_int(Ce,!!Me.deleteAtRefc0);break;case B.dbSize.colId:c.sqlite3_result_int(Ce,w(Me));break;default:return c.sqlite3_result_error(Ce,"Invalid column id: "+He),c.SQLITE_RANGE}return 0},xRowid:function(ke,Ce){Se("xRowid",...arguments);let He=ue(ke);return re.xRowid(Ce,He.rowid),0},xEof:function(ke){let Ce=ue(ke);return Se("xEof?="+!Ce.row(),...arguments),!Ce.row()},xFilter:function(ke,Ce,He,Qe,Me){return Se("xFilter",...arguments),ue(ke,!0),0},xBestIndex:function(ke,Ce){Se("xBestIndex",...arguments);let He=new c.sqlite3_index_info(Ce);return He.$estimatedRows=C.storagePool.size,He.$estimatedCost=1,He.dispose(),0}}})};f.kvvfs.create_module=function(Oe,ke="sqlite_kvvfs"){return c.sqlite3_create_module(Oe,ke,Re(),I.ptr.null)}}}),globalThis.sqlite3ApiBootstrap.initializers.push(function(f){if(f.config.disable?.vfs?.opfs&&f.config.disable.vfs["opfs-vfs"])return;let c=f.util.toss;f.capi;let d=f.util;f.wasm;let p=f.opfs=Object.create(null);p.thisThreadHasOPFS=()=>globalThis.FileSystemHandle&&globalThis.FileSystemDirectoryHandle&&globalThis.FileSystemFileHandle&&globalThis.FileSystemFileHandle.prototype.createSyncAccessHandle&&navigator?.storage?.getDirectory,p.getRootDir=async function b(){return b.promise??=navigator.storage.getDirectory().then((I)=>(p.rootDirectory=I,I)).catch((I)=>{throw delete b.promise,I})},p.getResolvedPath=function(b,I){let V=new URL(b,"file://irrelevant").pathname;return I?V.split("/").filter((M)=>!!M):V},p.getDirForFilename=async function(I,V=!1){let M=p.getResolvedPath(I,!0),C=M.pop(),q=await p.getRootDir();for(let H of M)if(H)q=await q.getDirectoryHandle(H,{create:!!V});return[q,C]},p.mkdir=async function(b){try{return await p.getDirForFilename(b+"/filepart",!0),!0}catch(I){return!1}},p.entryExists=async function(b){try{let[I,V]=await p.getDirForFilename(b);return await I.getFileHandle(V),!0}catch(I){return!1}},p.randomFilename=function b(I=16){if(!b._chars)b._chars="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012346789",b._n=b._chars.length;let V=[],M=0;for(;M<I;++M){let C=Math.random()*(b._n*64)%b._n|0;V[M]=b._chars[C]}return V.join("")},p.treeList=async function(){let b=async function V(M,C){C.name=M.name,C.dirs=[],C.files=[];for await(let q of M.values())if(q.kind==="directory"){let H=Object.create(null);C.dirs.push(H),await V(q,H)}else C.files.push(q.name)},I=Object.create(null);return await b(await p.getRootDir(),I),I},p.rmfr=async function(){let b=await p.getRootDir(),I={recurse:!0};for await(let V of b.values())b.removeEntry(V.name,I)},p.unlink=async function(b,I=!1,V=!1){try{let[M,C]=await p.getDirForFilename(b,!1);return await M.removeEntry(C,{recursive:I}),!0}catch(M){if(V)throw Error("unlink(",arguments[0],") failed: "+M.message,{cause:M});return!1}},p.traverse=async function(b){let I={recursive:!0,directory:await p.getRootDir()};if(typeof b==="function")b={callback:b};b=Object.assign(I,b||{}),async function V(M,C){for await(let q of M.values())if(b.callback(q,M,C)===!1)return!1;else if(b.recursive&&q.kind==="directory"){if(await V(q,C+1)===!1)break}}(b.directory,0)};let E=async function(b,I){let[V,M]=await p.getDirForFilename(b,!0),C=await(await V.getFileHandle(M,{create:!0})).createSyncAccessHandle(),q=0,H,G=!1;try{C.truncate(0);while((H=await I())!==void 0){if(H instanceof ArrayBuffer)H=new Uint8Array(H);if(!G&&q===0&&H.byteLength>=15)d.affirmDbHeader(H),G=!0;C.write(H,{at:q}),q+=H.byteLength}if(q<512||q%512!==0)c("Input size",q,"is not correct for an SQLite database.");if(!G){let le=new Uint8Array(20);C.read(le,{at:0}),d.affirmDbHeader(le)}return C.write(new Uint8Array([1,1]),{at:18}),q}catch(le){throw await C.close(),C=void 0,await V.removeEntry(M).catch(()=>{}),le}finally{if(C)await C.close()}};p.importDb=async function(b,I){if(I instanceof Function)return E(b,I);if(I instanceof ArrayBuffer)I=new Uint8Array(I);d.affirmIsDb(I);let V=I.byteLength,[M,C]=await p.getDirForFilename(b,!0),q,H=0;try{if(q=await(await M.getFileHandle(C,{create:!0})).createSyncAccessHandle(),q.truncate(0),H=q.write(I,{at:0}),H!=V)c("Expected to write "+V+" bytes but wrote "+H+".");return q.write(new Uint8Array([1,1]),{at:18}),H}catch(G){if(q)await q.close(),q=void 0;throw await M.removeEntry(C).catch(()=>{}),G}finally{if(q)await q.close()}},p.vfsInstallationFeatureCheck=function(b){if(!globalThis.SharedArrayBuffer||!globalThis.Atomics)c("Cannot install OPFS: Missing SharedArrayBuffer and/or Atomics.","The server must emit the COOP/COEP response headers to enable those.","See https://sqlite.org/wasm/doc/trunk/persistence.md#coop-coep");else if(typeof WorkerGlobalScope>"u")c("The OPFS sqlite3_vfs cannot run in the main thread","because it requires Atomics.wait().");else if(!globalThis.FileSystemHandle||!globalThis.FileSystemDirectoryHandle||!globalThis.FileSystemFileHandle?.prototype?.createSyncAccessHandle||!navigator?.storage?.getDirectory)c("Missing required OPFS APIs.");else if(b==="opfs-wl"&&!globalThis.Atomics.waitAsync)c("The",b,"VFS requires Atomics.waitAsync(), which is not available.")},p.initOptions=function(I,V){let M=new URL(globalThis.location.href).searchParams;if(M.has(I+"-disable"))return;try{p.vfsInstallationFeatureCheck(I)}catch(C){return}if(V=d.nu(V),V.vfsName=I,V.verbose??=M.has("opfs-verbose")?+M.get("opfs-verbose"):1,V.sanityChecks??=M.has("opfs-sanity-check"),!p.proxyUri){if(p.proxyUri="sqlite3-opfs-async-proxy.js",f.scriptInfo?.sqlite3Dir)p.proxyUri=f.scriptInfo.sqlite3Dir+p.proxyUri}if(V.proxyUri??=p.proxyUri,typeof V.proxyUri==="function")V.proxyUri=V.proxyUri();return p.options=V},p.createVfsState=function(){let b=d.nu(),I=p.options;b.verbose=I.verbose;let V=[f.config.error,f.config.warn,f.config.log],M=I.vfsName||c("Maintenance required: missing VFS name"),C=(W,...he)=>{if(b.verbose>W)V[W](M+":",...he)},q=(...W)=>C(2,...W),H=(...W)=>C(1,...W),G=(...W)=>C(0,...W),{capi:le,wasm:O}=f,R=b.vfs=new le.sqlite3_vfs,X=R.ioMethods=new le.sqlite3_io_methods;X.$iVersion=1,R.$iVersion=2,R.$szOsFile=le.sqlite3_file.structInfo.sizeof,R.$mxPathname=1024,R.$zName=O.allocCString(M),R.addOnDispose("$zName",R.$zName,X),R.metrics=d.nu({counters:d.nu(),dump:function(){let W,he=0,we=0,me=0;for(W in b.opIds){let ve=ee[W];he+=ve.count,we+=ve.time,me+=ve.wait,ve.avgTime=ve.count&&ve.time?ve.time/ve.count:0,ve.avgWait=ve.count&&ve.wait?ve.wait/ve.count:0}f.config.log(globalThis.location.href,"metrics for",globalThis.location.href,":",ee,`
538
+ Total of`,he,"op(s) for",we,"ms (incl. "+me+" ms of waiting on the async side)"),f.config.log("Serialization metrics:",R.metrics.counters.s11n),R.worker?.postMessage?.({type:"opfs-async-metrics"})},reset:function(){let W,he=(ve)=>ve.count=ve.time=ve.wait=0,we=R.metrics.counters;for(W in b.opIds)he(we[W]=Object.create(null));let me=we.s11n=Object.create(null);me=me.serialize=Object.create(null),me.count=me.time=0,me=we.s11n.deserialize=Object.create(null),me.count=me.time=0}}),b.asyncIdleWaitTime=150,b.asyncS11nExceptions=1,b.fileBufferSize=65536,b.sabS11nOffset=b.fileBufferSize,b.sabS11nSize=R.$mxPathname*2,b.sabIO=new SharedArrayBuffer(b.fileBufferSize+b.sabS11nSize),b.opIds=Object.create(null);{let W=0;b.opIds.whichOp=W++,b.opIds.rc=W++,b.opIds.xAccess=W++,b.opIds.xClose=W++,b.opIds.xDelete=W++,b.opIds.xDeleteNoWait=W++,b.opIds.xFileSize=W++,b.opIds.xLock=W++,b.opIds.xOpen=W++,b.opIds.xRead=W++,b.opIds.xSleep=W++,b.opIds.xSync=W++,b.opIds.xTruncate=W++,b.opIds.xUnlock=W++,b.opIds.xWrite=W++,b.opIds.mkdir=W++,b.opIds["opfs-async-metrics"]=W++,b.opIds["opfs-async-shutdown"]=W++,b.opIds.retry=W++,b.sabOP=new SharedArrayBuffer(W*4)}b.sq3Codes=Object.create(null);for(let W of["SQLITE_ACCESS_EXISTS","SQLITE_ACCESS_READWRITE","SQLITE_BUSY","SQLITE_CANTOPEN","SQLITE_ERROR","SQLITE_IOERR","SQLITE_IOERR_ACCESS","SQLITE_IOERR_CLOSE","SQLITE_IOERR_DELETE","SQLITE_IOERR_FSYNC","SQLITE_IOERR_LOCK","SQLITE_IOERR_READ","SQLITE_IOERR_SHORT_READ","SQLITE_IOERR_TRUNCATE","SQLITE_IOERR_UNLOCK","SQLITE_IOERR_WRITE","SQLITE_LOCK_EXCLUSIVE","SQLITE_LOCK_NONE","SQLITE_LOCK_PENDING","SQLITE_LOCK_RESERVED","SQLITE_LOCK_SHARED","SQLITE_LOCKED","SQLITE_MISUSE","SQLITE_NOTFOUND","SQLITE_OPEN_CREATE","SQLITE_OPEN_DELETEONCLOSE","SQLITE_OPEN_MAIN_DB","SQLITE_OPEN_READONLY","SQLITE_LOCK_NONE","SQLITE_LOCK_SHARED","SQLITE_LOCK_RESERVED","SQLITE_LOCK_PENDING","SQLITE_LOCK_EXCLUSIVE"])b.sq3Codes[W]=le[W]??c("Maintenance required: not found:",W);b.opfsFlags=Object.assign(Object.create(null),{OPFS_UNLOCK_ASAP:1,OPFS_UNLINK_BEFORE_OPEN:2,defaultUnlockAsap:!1}),R.metrics.reset();let ee=R.metrics.counters,U=R.opRun=(W,...he)=>{let we=b.opIds[W]||c(R.vfsName+": Invalid op ID:",W);b.s11n.serialize(...he),Atomics.store(b.sabOPView,b.opIds.rc,-1),Atomics.store(b.sabOPView,b.opIds.whichOp,we),Atomics.notify(b.sabOPView,b.opIds.whichOp);let me=performance.now();while(Atomics.wait(b.sabOPView,b.opIds.rc,-1)!=="not-equal");let ve=Atomics.load(b.sabOPView,b.opIds.rc);if(ee[W].wait+=performance.now()-me,ve&&b.asyncS11nExceptions){let F=b.s11n.deserialize();if(F)G(W+"() async error:",...F)}return ve},J=Object.create(null);J.op=void 0,J.start=void 0;let pe=R.mTimeStart=(W)=>{J.start=performance.now(),J.op=W,++ee[W].count},S=R.mTimeEnd=()=>ee[J.op].time+=performance.now()-J.start,P=R.__openFiles=Object.create(null);R.ioSyncWrappers=d.nu({xCheckReservedLock:function(W,he){return O.poke(he,0,"i32"),0},xClose:function(W){pe("xClose");let he=0,we=P[W];if(we){if(delete P[W],he=U("xClose",W),we.sq3File)we.sq3File.dispose()}return S(),he},xDeviceCharacteristics:function(W){return le.SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN},xFileControl:function(W,he,we){return le.SQLITE_NOTFOUND},xFileSize:function(W,he){pe("xFileSize");let we=U("xFileSize",W);if(we==0)try{let me=b.s11n.deserialize()[0];O.poke(he,me,"i64")}catch(me){G("Unexpected error reading xFileSize() result:",me),we=b.sq3Codes.SQLITE_IOERR}return S(),we},xRead:function(W,he,we,me){pe("xRead");let ve=P[W],F;try{if(F=U("xRead",W,we,Number(me)),F===0||le.SQLITE_IOERR_SHORT_READ===F)O.heap8u().set(ve.sabView.subarray(0,we),Number(he))}catch(g){G("xRead(",arguments,") failed:",g,ve),F=le.SQLITE_IOERR_READ}return S(),F},xSync:function(W,he){pe("xSync");let we=U("xSync",W,he);return S(),we},xTruncate:function(W,he){pe("xTruncate");let we=U("xTruncate",W,Number(he));return S(),we},xWrite:function(W,he,we,me){pe("xWrite");let ve=P[W],F;try{ve.sabView.set(O.heap8u().subarray(Number(he),Number(he)+we)),F=U("xWrite",W,we,Number(me))}catch(g){G("xWrite(",arguments,") failed:",g,ve),F=le.SQLITE_IOERR_WRITE}return S(),F}}),R.vfsSyncWrappers={xAccess:function(W,he,we,me){pe("xAccess");let ve=U("xAccess",O.cstrToJs(he));return O.poke(me,ve?0:1,"i32"),S(),0},xCurrentTime:function(W,he){return O.poke(he,2440587.5+new Date().getTime()/86400000,"double"),0},xCurrentTimeInt64:function(W,he){return O.poke(he,210866760000000+new Date().getTime(),"i64"),0},xDelete:function(W,he,we){pe("xDelete");let me=U("xDelete",O.cstrToJs(he),we,!1);return S(),me},xFullPathname:function(W,he,we,me){return O.cstrncpy(me,he,we)<we?0:le.SQLITE_CANTOPEN},xGetLastError:function(W,he,we){return f.config.warn("OPFS xGetLastError() has nothing sensible to return."),0},xOpen:function(he,we,me,ve,F){pe("xOpen");let g=0,w,T;if(!we)w=p.randomFilename(),we=T=O.allocCString(w);else if(O.isPtr(we)){if(le.sqlite3_uri_boolean(we,"opfs-unlock-asap",0))g|=b.opfsFlags.OPFS_UNLOCK_ASAP;if(le.sqlite3_uri_boolean(we,"delete-before-open",0))g|=b.opfsFlags.OPFS_UNLINK_BEFORE_OPEN;w=O.cstrToJs(we)}else return f.config.error("Impossible zName value in xOpen?",we),le.SQLITE_CANTOPEN;let N=d.nu({fid:me,filename:w,sab:new SharedArrayBuffer(b.fileBufferSize),flags:ve,readOnly:!(le.SQLITE_OPEN_CREATE&ve)&&!!(ve&le.SQLITE_OPEN_READONLY)}),te=U("xOpen",me,w,ve,g);if(te){if(T)O.dealloc(T)}else{if(N.readOnly)O.poke(F,le.SQLITE_OPEN_READONLY,"i32");if(P[me]=N,N.sabView=b.sabFileBufView,N.sq3File=new le.sqlite3_file(me),T)N.sq3File.addOnDispose(T);N.sq3File.$pMethods=X.pointer,N.lockType=le.SQLITE_LOCK_NONE}return S(),te}};let K=le.sqlite3_vfs_find(null);if(K){let W=new le.sqlite3_vfs(K);R.$xRandomness=W.$xRandomness,R.$xSleep=W.$xSleep,W.dispose()}if(!R.$xRandomness)R.vfsSyncWrappers.xRandomness=function(W,he,we){let me=O.heap8u(),ve=0,F=Number(we);for(;ve<he;++ve)me[F+ve]=Math.random()*255000&255;return ve};if(!R.$xSleep)R.vfsSyncWrappers.xSleep=function(W,he){return pe("xSleep"),Atomics.wait(b.sabOPView,b.opIds.xSleep,0,he),S(),0};let oe=function(){if(b.s11n)return b.s11n;let W=new TextDecoder,he=new TextEncoder("utf-8"),we=new Uint8Array(b.sabIO,b.sabS11nOffset,b.sabS11nSize),me=new DataView(b.sabIO,b.sabS11nOffset,b.sabS11nSize);b.s11n=Object.create(null);let ve=Object.create(null);ve.number={id:1,size:8,getter:"getFloat64",setter:"setFloat64"},ve.bigint={id:2,size:8,getter:"getBigInt64",setter:"setBigInt64"},ve.boolean={id:3,size:4,getter:"getInt32",setter:"setInt32"},ve.string={id:4};let F=(w)=>ve[typeof w]||c("Maintenance required: this value type cannot be serialized.",w),g=(w)=>{switch(w){case ve.number.id:return ve.number;case ve.bigint.id:return ve.bigint;case ve.boolean.id:return ve.boolean;case ve.string.id:return ve.string;default:c("Invalid type ID:",w)}};return b.s11n.deserialize=function(w=!1){performance.now();let T=we[0],N=T?[]:null;if(T){let te=[],se=1,A,L,Q;for(A=0;A<T;++A,++se)te.push(g(we[se]));for(A=0;A<T;++A){let ne=te[A];if(ne.getter)Q=me[ne.getter](se,b.littleEndian),se+=ne.size;else L=me.getInt32(se,b.littleEndian),se+=4,Q=W.decode(we.slice(se,se+L)),se+=L;N.push(Q)}}if(w)we[0]=0;return N},b.s11n.serialize=function(...w){if(performance.now(),w.length){let T=[],N=0,te=1;we[0]=w.length&255;for(;N<w.length;++N,++te)T.push(F(w[N])),we[te]=T[N].id;for(N=0;N<w.length;++N){let se=T[N];if(se.setter)me[se.setter](te,w[N],b.littleEndian),te+=se.size;else{let A=he.encode(w[N]);me.setInt32(te,A.byteLength,b.littleEndian),te+=4,we.set(A,te),te+=A.byteLength}}}else we[0]=0},b.s11n};return R.initS11n=oe,R.bindVfs=function(W,he){return Object.assign(R.ioSyncWrappers,W),new Promise(function(we,me){let ve=void 0,F=(A)=>(ve=!0,R.dispose(),me(A)),g=()=>{try{he(f,R)}catch(A){return F(A)}return ve=!1,we(f)},w=p.options;w.proxyUri+(w.proxyUri.indexOf("?")<0?"?":"&")+M;let T=new URL("sqlite3-opfs-async-proxy.js",import.meta.url);T.searchParams.set("vfs",M);let N=R.worker=new Worker(T.toString()),te=setTimeout(()=>{if(ve===void 0)F(Error("Timeout while waiting for OPFS async proxy worker."))},4000);N._originalOnError=N.onerror,N.onerror=function(A){G("Error initializing OPFS asyncer:",A),F(Error("Loading OPFS async Worker failed for unknown reasons."))},R.opRun;let se=function(){let A=O.scopedAllocPush(),L=new le.sqlite3_file;try{let Q=L.pointer,ne=le.SQLITE_OPEN_CREATE|le.SQLITE_OPEN_READWRITE|le.SQLITE_OPEN_MAIN_DB,ye=O.scopedAlloc(8),Te="/sanity/check/file"+randomFilename(8),Ie=O.scopedAllocCString(Te),qe;if(b.s11n.serialize("This is ä string."),qe=b.s11n.deserialize(),q("deserialize() says:",qe),qe[0]!=="This is ä string.")c("String d13n error.");if(R.vfsSyncWrappers.xAccess(R.pointer,Ie,0,ye),qe=O.peek(ye,"i32"),q("xAccess(",Te,") exists ?=",qe),qe=R.vfsSyncWrappers.xOpen(R.pointer,Ie,Q,ne,ye),q("open rc =",qe,"state.sabOPView[xOpen] =",b.sabOPView[b.opIds.xOpen]),qe!==0){G("open failed with code",qe);return}if(R.vfsSyncWrappers.xAccess(R.pointer,Ie,0,ye),qe=O.peek(ye,"i32"),!qe)c("xAccess() failed to detect file.");if(qe=R.ioSyncWrappers.xSync(L.pointer,0),qe)c("sync failed w/ rc",qe);if(qe=R.ioSyncWrappers.xTruncate(L.pointer,1024),qe)c("truncate failed w/ rc",qe);if(O.poke(ye,0,"i64"),qe=R.ioSyncWrappers.xFileSize(L.pointer,ye),qe)c("xFileSize failed w/ rc",qe);if(q("xFileSize says:",O.peek(ye,"i64")),qe=R.ioSyncWrappers.xWrite(L.pointer,Ie,10,1),qe)c("xWrite() failed!");let Ge=O.scopedAlloc(16);qe=R.ioSyncWrappers.xRead(L.pointer,Ge,6,2),O.poke(Ge+6,0);let ct=O.cstrToJs(Ge);if(q("xRead() got:",ct),ct!=="sanity")c("Unexpected xRead() value.");if(R.vfsSyncWrappers.xSleep)q("xSleep()ing before close()ing..."),R.vfsSyncWrappers.xSleep(R.pointer,2000),q("waking up from xSleep()");if(qe=R.ioSyncWrappers.xClose(Q),q("xClose rc =",qe,"sabOPView =",b.sabOPView),q("Deleting file:",Te),R.vfsSyncWrappers.xDelete(R.pointer,Ie,4660),R.vfsSyncWrappers.xAccess(R.pointer,Ie,0,ye),qe=O.peek(ye,"i32"),qe)c("Expecting 0 from xAccess(",Te,") after xDelete().");H("End of OPFS sanity checks.")}finally{L.dispose(),O.scopedAllocPop(A)}};N.onmessage=function({data:A}){switch(A.type){case"opfs-unavailable":F(Error(A.payload.join(" ")));break;case"opfs-async-loaded":delete b.vfs,N.postMessage({type:"opfs-async-init",args:d.nu(b)});break;case"opfs-async-inited":if(ve===!0)break;clearTimeout(te),te=null;try{if(f.vfs.installVfs({io:{struct:R.ioMethods,methods:R.ioSyncWrappers},vfs:{struct:R,methods:R.vfsSyncWrappers}}),b.sabOPView=new Int32Array(b.sabOP),b.sabFileBufView=new Uint8Array(b.sabIO,0,b.fileBufferSize),b.sabS11nView=new Uint8Array(b.sabIO,b.sabS11nOffset,b.sabS11nSize),R.initS11n(),delete R.initS11n,w.sanityChecks)H("Running sanity checks because of opfs-sanity-check URL arg..."),se();if(p.thisThreadHasOPFS())p.getRootDir().then((L)=>{N.onerror=N._originalOnError,delete N._originalOnError,q("End of OPFS sqlite3_vfs setup.",R),g()}).catch(F);else g()}catch(L){G(L),F(L)}break;case"debug":H("debug message from worker:",A);break;default:{let L="Unexpected message from the OPFS async worker: "+JSON.stringify(A);G(L),F(Error(L));break}}}})},b}}),globalThis.sqlite3ApiBootstrap.initializers.push(function(f){if(!f.opfs||f.config.disable?.vfs?.opfs)return;let c=f.util,d=f.opfs||f.util.toss("Missing sqlite3.opfs"),p=async function(E){if(E=d.initOptions("opfs",E),!E)return f;let b=f.capi,I=d.createVfsState().vfs,V=I.metrics.counters,{mTimeStart:M,mTimeEnd:C,opRun:q,__openFiles:H}=I;return I.bindVfs(c.nu({xLock:function(G,le){M("xLock"),++V.xLock.count;let O=H[G],R=0;if(O.lockType)O.lockType=le;else if(R=q("xLock",G,le),R===0)O.lockType=le;return C(),R},xUnlock:function(G,le){M("xUnlock"),++V.xUnlock.count;let O=H[G],R=0;if(b.SQLITE_LOCK_NONE===le&&O.lockType)R=q("xUnlock",G,le);if(R===0)O.lockType=le;return C(),R}}),function(G,le){if(G.oo1){let O=function(...R){let X=G.oo1.DB.dbCtorHelper.normalizeArgs(...R);X.vfs=le.$zName,G.oo1.DB.dbCtorHelper.call(this,X)};O.prototype=Object.create(G.oo1.DB.prototype),G.oo1.OpfsDb=O,O.importDb=d.importDb,G.oo1.DB.dbCtorHelper.setVfsPostOpenCallback(I.pointer,function(R,X){X.capi.sqlite3_busy_timeout(R,1e4)})}})};globalThis.sqlite3ApiBootstrap.initializersAsync.push(async(E)=>p().catch((b)=>{E.config.warn("Ignoring inability to install 'opfs' sqlite3_vfs:",b)}))}),globalThis.sqlite3ApiBootstrap.initializers.push(function(f){if(f.config.disable?.vfs?.["opfs-sahpool"])return;let c=f.util.toss,d=f.util.toss3,p=Object.create(null),{capi:E,util:b,wasm:I}=f,V=4096,M=512,C=4,q=8,H=M+C,G=M,le=H,O=V,R=E.SQLITE_OPEN_MAIN_DB|E.SQLITE_OPEN_MAIN_JOURNAL|E.SQLITE_OPEN_SUPER_JOURNAL|E.SQLITE_OPEN_WAL,X=E.SQLITE_OPEN_MEMORY,ee=".opaque",U=()=>Math.random().toString(36).slice(2),J=new TextDecoder,pe=new TextEncoder,S=Object.assign(Object.create(null),{name:"opfs-sahpool",directory:void 0,initialCapacity:6,clearOnInit:!1,verbosity:2,forceReinitIfPreviouslyFailed:!1}),P=[f.config.error,f.config.warn,f.config.log];f.config.log;let K=f.config.warn;f.config.error;let oe=new Map,W=(A)=>oe.get(A),he=(A,L)=>{if(L)oe.set(A,L);else oe.delete(A)},we=new Map,me=(A)=>we.get(A),ve=(A,L)=>{if(L)we.set(A,L);else we.delete(A)},F={xCheckReservedLock:function(A,L){let Q=me(A);return Q.log("xCheckReservedLock"),Q.storeErr(),I.poke32(L,1),0},xClose:function(A){let L=me(A);L.storeErr();let Q=L.getOFileForS3File(A);if(Q)try{if(L.log(`xClose ${Q.path}`),L.mapS3FileToOFile(A,!1),Q.sah.flush(),Q.flags&E.SQLITE_OPEN_DELETEONCLOSE)L.deletePath(Q.path)}catch(ne){return L.storeErr(ne,E.SQLITE_IOERR)}return 0},xDeviceCharacteristics:function(A){return E.SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN},xFileControl:function(A,L,Q){return E.SQLITE_NOTFOUND},xFileSize:function(A,L){let Q=me(A);Q.log("xFileSize");let ne=Q.getOFileForS3File(A).sah.getSize()-O;return I.poke64(L,BigInt(ne)),0},xLock:function(A,L){let Q=me(A);Q.log(`xLock ${L}`),Q.storeErr();let ne=Q.getOFileForS3File(A);return ne.lockType=L,0},xRead:function(A,L,Q,ne){let ye=me(A);ye.storeErr();let Te=ye.getOFileForS3File(A);ye.log(`xRead ${Te.path} ${Q} @ ${ne}`);try{let Ie=Te.sah.read(I.heap8u().subarray(Number(L),Number(L)+Q),{at:O+Number(ne)});if(Ie<Q)return I.heap8u().fill(0,Number(L)+Ie,Number(L)+Q),E.SQLITE_IOERR_SHORT_READ;return 0}catch(Ie){return ye.storeErr(Ie,E.SQLITE_IOERR)}},xSectorSize:function(A){return V},xSync:function(A,L){let Q=me(A);Q.log(`xSync ${L}`),Q.storeErr();let ne=Q.getOFileForS3File(A);try{return ne.sah.flush(),0}catch(ye){return Q.storeErr(ye,E.SQLITE_IOERR)}},xTruncate:function(A,L){let Q=me(A);Q.log(`xTruncate ${L}`),Q.storeErr();let ne=Q.getOFileForS3File(A);try{return ne.sah.truncate(O+Number(L)),0}catch(ye){return Q.storeErr(ye,E.SQLITE_IOERR)}},xUnlock:function(A,L){let Q=me(A);Q.log("xUnlock");let ne=Q.getOFileForS3File(A);return ne.lockType=L,0},xWrite:function(A,L,Q,ne){let ye=me(A);ye.storeErr();let Te=ye.getOFileForS3File(A);ye.log(`xWrite ${Te.path} ${Q} ${ne}`);try{return Q===Te.sah.write(I.heap8u().subarray(Number(L),Number(L)+Q),{at:O+Number(ne)})?0:c("Unknown write() failure.")}catch(Ie){return ye.storeErr(Ie,E.SQLITE_IOERR)}}},g=new E.sqlite3_io_methods;g.$iVersion=1,f.vfs.installVfs({io:{struct:g,methods:F}});let w={xAccess:function(A,L,Q,ne){let ye=W(A);ye.storeErr();try{let Te=ye.getPath(L);I.poke32(ne,ye.hasFilename(Te)?1:0)}catch(Te){I.poke32(ne,0)}return 0},xCurrentTime:function(A,L){return I.poke(L,2440587.5+new Date().getTime()/86400000,"double"),0},xCurrentTimeInt64:function(A,L){return I.poke(L,210866760000000+new Date().getTime(),"i64"),0},xDelete:function(A,L,Q){let ne=W(A);ne.log(`xDelete ${I.cstrToJs(L)}`),ne.storeErr();try{return ne.deletePath(ne.getPath(L)),0}catch(ye){return ne.storeErr(ye),E.SQLITE_IOERR_DELETE}},xFullPathname:function(A,L,Q,ne){return I.cstrncpy(ne,L,Q)<Q?0:E.SQLITE_CANTOPEN},xGetLastError:function(A,L,Q){let ne=W(A),ye=ne.popErr();if(ne.log(`xGetLastError ${L} e =`,ye),ye){let Te=I.scopedAllocPush();try{let[Ie,qe]=I.scopedAllocCString(ye.message,!0);if(I.cstrncpy(Q,Ie,L),qe>L)I.poke8(I.ptr.add(Q,L,-1),0)}catch(Ie){return E.SQLITE_NOMEM}finally{I.scopedAllocPop(Te)}}return ye?ye.sqlite3Rc||E.SQLITE_IOERR:0},xOpen:function(L,Q,ne,ye,Te){let Ie=W(L);try{ye&=~X,Ie.log(`xOpen ${I.cstrToJs(Q)} ${ye}`);let qe=Q&&I.peek8(Q)?Ie.getPath(Q):U(),Ge=Ie.getSAHForPath(qe);if(!Ge&&ye&E.SQLITE_OPEN_CREATE)if(Ie.getFileCount()<Ie.getCapacity())Ge=Ie.nextAvailableSAH(),Ie.setAssociatedPath(Ge,qe,ye);else c("SAH pool is full. Cannot create file",qe);if(!Ge)c("file not found:",qe);let ct={path:qe,flags:ye,sah:Ge};Ie.mapS3FileToOFile(ne,ct),ct.lockType=E.SQLITE_LOCK_NONE;let zt=new E.sqlite3_file(ne);return zt.$pMethods=g.pointer,zt.dispose(),I.poke32(Te,ye),0}catch(qe){return Ie.storeErr(qe),E.SQLITE_CANTOPEN}}},T=function(A){if(f.capi.sqlite3_vfs_find(A))d("VFS name is already registered:",A);let L=new E.sqlite3_vfs,Q=E.sqlite3_vfs_find(null),ne=Q?new E.sqlite3_vfs(Q):null;if(L.$iVersion=2,L.$szOsFile=E.sqlite3_file.structInfo.sizeof,L.$mxPathname=M,L.addOnDispose(L.$zName=I.allocCString(A),()=>he(L.pointer,0)),ne)L.$xRandomness=ne.$xRandomness,L.$xSleep=ne.$xSleep,ne.dispose();if(!L.$xRandomness&&!w.xRandomness)w.xRandomness=function(ye,Te,Ie){let qe=I.heap8u(),Ge=0,ct=Number(Ie);for(;Ge<Te;++Ge)qe[ct+Ge]=Math.random()*255000&255;return Ge};if(!L.$xSleep&&!w.xSleep)w.xSleep=(ye,Te)=>0;return f.vfs.installVfs({vfs:{struct:L,methods:w}}),L};class N{vfsDir;#e;#o;#i;#t=new Map;#r=new Map;#s=new Set;#c=new Map;#n=new Uint8Array(H);#l;#a;#d;constructor(A=Object.create(null)){this.#d=A.verbosity??S.verbosity,this.vfsName=A.name||S.name,this.#a=T(this.vfsName),he(this.#a.pointer,this),this.vfsDir=A.directory||"."+this.vfsName,this.#l=new DataView(this.#n.buffer,this.#n.byteOffset),this.isReady=this.reset(!!(A.clearOnInit??S.clearOnInit)).then(()=>{if(this.$error)throw this.$error;return this.getCapacity()?Promise.resolve(void 0):this.addCapacity(A.initialCapacity||S.initialCapacity)})}#u(A,...L){if(this.#d>A)P[A](this.vfsName+":",...L)}log(...A){this.#u(2,...A)}warn(...A){this.#u(1,...A)}error(...A){this.#u(0,...A)}getVfs(){return this.#a}getCapacity(){return this.#t.size}getFileCount(){return this.#r.size}getFileNames(){let A=[];for(let L of this.#r.keys())A.push(L);return A}async addCapacity(A){for(let L=0;L<A;++L){let Q=U(),ne=await(await this.#o.getFileHandle(Q,{create:!0})).createSyncAccessHandle();this.#t.set(ne,Q),this.setAssociatedPath(ne,"",0)}return this.getCapacity()}async reduceCapacity(A){let L=0;for(let Q of Array.from(this.#s)){if(L===A||this.getFileCount()===this.getCapacity())break;let ne=this.#t.get(Q);Q.close(),await this.#o.removeEntry(ne),this.#t.delete(Q),this.#s.delete(Q),++L}return L}releaseAccessHandles(){for(let A of this.#t.keys())A.close();this.#t.clear(),this.#r.clear(),this.#s.clear()}async acquireAccessHandles(A=!1){let L=[];for await(let[Q,ne]of this.#o)if(ne.kind==="file")L.push([Q,ne]);return Promise.all(L.map(async([Q,ne])=>{try{let ye=await ne.createSyncAccessHandle();if(this.#t.set(ye,Q),A)ye.truncate(O),this.setAssociatedPath(ye,"",0);else{let Te=this.getAssociatedPath(ye);if(Te)this.#r.set(Te,ye);else this.#s.add(ye)}}catch(ye){throw this.storeErr(ye),this.releaseAccessHandles(),ye}}))}getAssociatedPath(A){A.read(this.#n,{at:0});let L=this.#l.getUint32(G);if(this.#n[0]&&(L&E.SQLITE_OPEN_DELETEONCLOSE||(L&R)===0))return K(`Removing file with unexpected flags ${L.toString(16)}`,this.#n),this.setAssociatedPath(A,"",0),"";let Q=new Uint32Array(q/4);A.read(Q,{at:le});let ne=this.computeDigest(this.#n,L);if(Q.every((ye,Te)=>ye===ne[Te])){let ye=this.#n.findIndex((Te)=>Te===0);if(ye===0)A.truncate(O);return ye?J.decode(this.#n.subarray(0,ye)):""}else return K("Disassociating file with bad digest."),this.setAssociatedPath(A,"",0),""}setAssociatedPath(A,L,Q){let ne=pe.encodeInto(L,this.#n);if(M<=ne.written+1)c("Path too long:",L);if(L&&Q)Q|=X;this.#n.fill(0,ne.written,M),this.#l.setUint32(G,Q);let ye=this.computeDigest(this.#n,Q);if(A.write(this.#n,{at:0}),A.write(ye,{at:le}),A.flush(),L)this.#r.set(L,A),this.#s.delete(A);else A.truncate(O),this.#s.add(A)}computeDigest(A,L){if(L&X){let Q=3735928559,ne=1103547991;for(let ye of A)Q=Math.imul(Q^ye,2654435761),ne=Math.imul(ne^ye,104729);return new Uint32Array([Q>>>0,ne>>>0])}else return new Uint32Array([0,0])}async reset(A){await this.isReady;let L=await navigator.storage.getDirectory(),Q;for(let ne of this.vfsDir.split("/"))if(ne)Q=L,L=await L.getDirectoryHandle(ne,{create:!0});return this.#e=L,this.#i=Q,this.#o=await this.#e.getDirectoryHandle(ee,{create:!0}),this.releaseAccessHandles(),this.acquireAccessHandles(A)}getPath(A){if(I.isPtr(A))A=I.cstrToJs(A);return(A instanceof URL?A:new URL(A,"file://localhost/")).pathname}deletePath(A){let L=this.#r.get(A);if(L)this.#r.delete(A),this.setAssociatedPath(L,"",0);return!!L}storeErr(A,L){if(A)A.sqlite3Rc=L||E.SQLITE_IOERR,this.error(A);return this.$error=A,L}popErr(){let A=this.$error;return this.$error=void 0,A}nextAvailableSAH(){let[A]=this.#s.keys();return A}getOFileForS3File(A){return this.#c.get(A)}mapS3FileToOFile(A,L){if(L)this.#c.set(A,L),ve(A,this);else this.#c.delete(A),ve(A,!1)}hasFilename(A){return this.#r.has(A)}getSAHForPath(A){return this.#r.get(A)}async removeVfs(){if(!this.#a.pointer||!this.#o)return!1;E.sqlite3_vfs_unregister(this.#a.pointer),this.#a.dispose(),delete p[this.vfsName];try{this.releaseAccessHandles(),await this.#e.removeEntry(ee,{recursive:!0}),this.#o=void 0,await this.#i.removeEntry(this.#e.name,{recursive:!0}),this.#e=this.#i=void 0}catch(A){f.config.error(this.vfsName,"removeVfs() failed with no recovery strategy:",A)}return!0}pauseVfs(){if(this.#c.size>0)f.SQLite3Error.toss(E.SQLITE_MISUSE,"Cannot pause VFS",this.vfsName,"because it has opened files.");if(this.#t.size>0)E.sqlite3_vfs_unregister(this.vfsName),this.releaseAccessHandles();return this}isPaused(){return this.#t.size===0}async unpauseVfs(){if(this.#t.size===0)return this.acquireAccessHandles(!1).then(()=>E.sqlite3_vfs_register(this.#a,0),this);return this}exportFile(A){//! Documented elsewhere in this file.
523
539
  let L=this.#r.get(A)||c("File not found:",A),Q=L.getSize()-O,ne=new Uint8Array(Q>0?Q:0);if(Q>0){let ye=L.read(ne,{at:O});if(ye!=Q)c("Expected to read "+Q+" bytes but read "+ye+".")}return ne}async importDbChunked(A,L){//! Impl for importDb() when its 2nd arg is a function.
524
540
  let Q=this.#r.get(A)||this.nextAvailableSAH()||c("No available handles to import to.");Q.truncate(0);let ne=0,ye,Te=!1;try{while((ye=await L())!==void 0){if(ye instanceof ArrayBuffer)ye=new Uint8Array(ye);if(!Te&&ne===0&&ye.byteLength>=15)b.affirmDbHeader(ye),Te=!0;Q.write(ye,{at:O+ne}),ne+=ye.byteLength}if(ne<512||ne%512!==0)c("Input size",ne,"is not correct for an SQLite database.");if(!Te){let Ie=new Uint8Array(20);Q.read(Ie,{at:0}),b.affirmDbHeader(Ie)}Q.write(new Uint8Array([1,1]),{at:O+18})}catch(Ie){throw this.setAssociatedPath(Q,"",0),Ie}return this.setAssociatedPath(Q,A,E.SQLITE_OPEN_MAIN_DB),ne}importDb(A,L){//! Documented elsewhere in this file.
525
- if(L instanceof ArrayBuffer)L=new Uint8Array(L);else if(L instanceof Function)return this.importDbChunked(A,L);let Q=this.#r.get(A)||this.nextAvailableSAH()||c("No available handles to import to."),ne=L.byteLength;if(ne<512||ne%512!=0)c("Byte array size is invalid for an SQLite db.");let ye="SQLite format 3";for(let Ie=0;Ie<15;++Ie)if(ye.charCodeAt(Ie)!==L[Ie])c("Input does not contain an SQLite database header.");let Te=Q.write(L,{at:O});if(Te!=ne)this.setAssociatedPath(Q,"",0),c("Expected to write "+ne+" bytes but wrote "+Te+".");else Q.write(new Uint8Array([1,1]),{at:O+18}),this.setAssociatedPath(Q,A,E.SQLITE_OPEN_MAIN_DB);return Te}}class te{#e;constructor(A){this.#e=A,this.vfsName=A.vfsName}async addCapacity(A){return this.#e.addCapacity(A)}async reduceCapacity(A){return this.#e.reduceCapacity(A)}getCapacity(){return this.#e.getCapacity(this.#e)}getFileCount(){return this.#e.getFileCount()}getFileNames(){return this.#e.getFileNames()}async reserveMinimumCapacity(A){let L=this.#e.getCapacity();return L<A?this.#e.addCapacity(A-L):L}exportFile(A){return this.#e.exportFile(A)}importDb(A,L){return this.#e.importDb(A,L)}async wipeFiles(){return this.#e.reset(!0)}unlink(A){return this.#e.deletePath(A)}async removeVfs(){return this.#e.removeVfs()}pauseVfs(){return this.#e.pauseVfs(),this}async unpauseVfs(){return this.#e.unpauseVfs().then(()=>this)}isPaused(){return this.#e.isPaused()}}let se=async()=>{let A=await navigator.storage.getDirectory(),L=".opfs-sahpool-sync-check-"+U(),Q=(await(await A.getFileHandle(L,{create:!0})).createSyncAccessHandle()).close();if(await Q,await A.removeEntry(L),Q?.then)c("The local OPFS API is too old for opfs-sahpool:","it has an async FileSystemSyncAccessHandle.close() method.");return!0};f.installOpfsSAHPoolVfs=async function(A=Object.create(null)){A=Object.assign(Object.create(null),S,A||{});let L=A.name;if(A.$testThrowPhase1)throw A.$testThrowPhase1;if(p[L])try{return await p[L]}catch(Q){if(A.forceReinitIfPreviouslyFailed)delete p[L];else throw Q}if(!globalThis.FileSystemHandle||!globalThis.FileSystemDirectoryHandle||!globalThis.FileSystemFileHandle||!globalThis.FileSystemFileHandle.prototype.createSyncAccessHandle||!navigator?.storage?.getDirectory)return p[L]=Promise.reject(Error("Missing required OPFS APIs."));return p[L]=se().then(async function(){if(A.$testThrowPhase2)throw A.$testThrowPhase2;let Q=new C(A);return Q.isReady.then(async()=>{let ne=new te(Q);if(f.oo1){let ye=f.oo1,Te=Q.getVfs(),Ie=function(...qe){let Ge=ye.DB.dbCtorHelper.normalizeArgs(...qe);Ge.vfs=Te.$zName,ye.DB.dbCtorHelper.call(this,Ge)};Ie.prototype=Object.create(ye.DB.prototype),ne.OpfsSAHPoolDb=Ie}return Q.log("VFS initialized."),ne}).catch(async(ne)=>{throw await Q.removeVfs().catch(()=>{}),ne})}).catch((Q)=>p[L]=Promise.reject(Q))}}),globalThis.sqlite3ApiBootstrap.initializers.push(function(f){if(!f.opfs||f.config.disable?.vfs?.["opfs-wl"])return;let c=f.util;f.util.toss;let d=f.opfs,p="opfs-wl",E=async function(b){if(b=d.initOptions(p,b),!b)return f;f.capi;let I=d.createVfsState().vfs;I.metrics.counters;let{mTimeStart:V,mTimeEnd:M,opRun:N,__openFiles:q}=I;return I.bindVfs(c.nu({xLock:function(H,G){V("xLock");let le=q[H],O=N("xLock",H,G);if(!O)le.lockType=G;return M(),O},xUnlock:function(H,G){V("xUnlock");let le=q[H],O=N("xUnlock",H,G);if(!O)le.lockType=G;return M(),O}}),function(H,G){if(H.oo1){let le=function(...O){let R=H.oo1.DB.dbCtorHelper.normalizeArgs(...O);R.vfs=G.$zName,H.oo1.DB.dbCtorHelper.call(this,R)};le.prototype=Object.create(H.oo1.DB.prototype),H.oo1.OpfsWlDb=le,le.importDb=d.importDb}})};globalThis.sqlite3ApiBootstrap.initializersAsync.push(async(b)=>E().catch((I)=>{b.config.warn("Ignoring inability to install the",p,"sqlite3_vfs:",I)}))});try{let f=Object.assign(Object.create(null),{memory:typeof cr<"u"?cr:l.wasmMemory,exports:typeof tn<"u"?tn:Object.prototype.hasOwnProperty.call(l,"wasmExports")?l.wasmExports:l.asm},globalThis.sqlite3ApiBootstrap.defaultConfig,globalThis.sqlite3ApiConfig||{});i.debugModule("Bootstrapping lib config",f);let c=globalThis.sqlite3ApiBootstrap(f);return delete globalThis.sqlite3ApiBootstrap,c}catch(f){throw console.error("sqlite3ApiBootstrap() error:",f),f}},Le)t=r;else t=new Promise((i,l)=>{de=i,ge=l});return t}Li=function(){let e=Li;if(!e)throw Error("Expecting sqlite3InitModule to be defined by the Emscripten build.");let t=globalThis.sqlite3InitModuleState=Object.assign(Object.create(null),{moduleScript:globalThis?.document?.currentScript,isWorker:typeof WorkerGlobalScope<"u",location:globalThis.location,urlParams:globalThis?.location?.href?new URL(globalThis.location.href).searchParams:new URLSearchParams,wasmFilename:"sqlite3.wasm"});if(t.debugModule=t.urlParams.has("sqlite3.debugModule")?(...n)=>console.warn("sqlite3.debugModule:",...n):()=>{},t.urlParams.has("sqlite3.dir"))t.sqlite3Dir=t.urlParams.get("sqlite3.dir")+"/";else if(t.moduleScript){let n=t.moduleScript.src.split("/");n.pop(),t.sqlite3Dir=n.join("/")+"/"}let r=globalThis.sqlite3InitModule=function n(...o){return t.emscriptenLocateFile=o[0]?.locateFile,t.emscriptenInstantiateWasm=o[0]?.instantiateWasm,e(...o).then((s)=>{t.debugModule("sqlite3InitModule() sIMS =",t),t.debugModule("sqlite3InitModule() EmscriptenModule =",s);let a=s.runSQLite3PostLoadInit(t,s,!!n.__isUnderTest);return t.debugModule("sqlite3InitModule() sqlite3 =",a),a}).catch((s)=>{throw console.error("Exception loading sqlite3 module:",s),s})};if(r.ready=e.ready,t.moduleScript){let n=t.moduleScript.src.split("/");n.pop(),t.scriptDir=n.join("/")+"/"}return t.debugModule("extern-post-js.c-pp.js sqlite3InitModuleState =",t),r}();var Ic=Li;class zi{db;txDepth=0;constructor(e){this.db=e}query(e){let t=this.db;return{get(...r){return t.selectObject(e,$i(r))??null},all(...r){return t.selectObjects(e,$i(r))},run(...r){return t.exec({sql:e,bind:$i(r)}),{changes:t.changes()}}}}exec(e){this.db.exec({sql:e})}transaction(e){return(...t)=>{let r=`mh_tx_${this.txDepth}`;this.exec(this.txDepth===0?"BEGIN":`SAVEPOINT ${r}`),this.txDepth++;try{let n=e(...t);return this.txDepth--,this.exec(this.txDepth===0?"COMMIT":`RELEASE ${r}`),n}catch(n){throw this.txDepth--,this.exec(this.txDepth===0?"ROLLBACK":`ROLLBACK TO ${r}; RELEASE ${r}`),n}}}}function $i(e){if(e.length===0)return;return e.map((t)=>t===void 0?null:t)}Po();Gt();wt();Ye();dt();zn();ra();io();Fn();var fg=(e)=>{let t=/^[a-z0-9+]+:\/\/([^/]+)/i.exec(e);return t?t[1]:e};function wv(e,t,r,n,o,s){let a=e.kind==="s3",u=a?n:r,_=Math.max(0,u-e.pushCursor),m=a?["backend"]:["replica"],x=a?e.url:e.nodeId;if(x&&t.includes(x))m.push("blob_anchor");if(a&&e.publish)m.push("publisher");return{kind:a?"bucket":"device",url:e.url,label:e.label??(a?e.bucket??fg(e.url):fg(e.url)),freshness:!e.enabled?"disabled":e.lastStatus==="error"?"error":e.lastSuccessAt==null?"never":_>0?"behind":o-e.lastSuccessAt>s?"stale":"current",syncedAt:e.lastSuccessAt,error:e.lastStatus==="error"?e.lastError??null:null,acknowledgedSeq:e.pushCursor,highWaterSeq:u,lag:_,roles:m}}function za(e){let t={kind:"self",url:null,label:e.selfLabel??"本机",freshness:"live",syncedAt:null,error:null,acknowledgedSeq:e.globalHighWaterSeq,highWaterSeq:e.globalHighWaterSeq,lag:0,roles:e.blobFullNodes.includes(e.selfNodeId)?["replica","blob_anchor"]:["replica"]},r=(a)=>a==="current"?0:a==="stale"?1:a==="behind"?2:a==="error"?3:a==="never"?4:5,n=e.now??Date.now(),o=e.staleAfterMs??86400000,s=e.peers.map((a)=>wv(a,e.blobFullNodes,e.globalHighWaterSeq,e.ownHighWaterSeq,n,o)).sort((a,u)=>Number(a.kind==="bucket")-Number(u.kind==="bucket")||r(a.freshness)-r(u.freshness)||a.label.localeCompare(u.label));return[t,...s]}function pg(e){let r=za(e).filter((_)=>_.kind!=="self"&&_.freshness!=="disabled"),n=r.filter((_)=>_.syncedAt!=null&&_.acknowledgedSeq>=_.highWaterSeq),o=n.length?n.reduce((_,m)=>_==null||(m.syncedAt??0)<_?m.syncedAt:_,null):null,s=r.reduce((_,m)=>Math.max(_,m.lag),0),a=[];if(r.length===0)a.push({kind:"no_backup",placeUrl:null,placeLabel:null,message:null});for(let _ of r)if(_.freshness==="error")a.push({kind:"peer_error",placeUrl:_.url,placeLabel:_.label,message:_.error});if(e.pendingBlobCount>0)a.push({kind:"pending_blobs",placeUrl:null,placeLabel:null,message:null});for(let _ of r)if(_.freshness==="behind")a.push({kind:"behind",placeUrl:_.url,placeLabel:_.label,message:null});for(let _ of r)if(_.freshness==="never")a.push({kind:"never_synced",placeUrl:_.url,placeLabel:_.label,message:null});for(let _ of r)if(_.freshness==="stale")a.push({kind:"stale",placeUrl:_.url,placeLabel:_.label,message:null});let u={places:1+n.length,pendingBlobCount:e.pendingBlobCount,pendingBlobBytes:e.pendingBlobBytes,pendingChanges:s,oldestSyncedAt:o,issues:a};if(r.length===0)return{state:"no_backup",...u};if(r.some((_)=>_.freshness==="error"))return{state:"peer_error",...u};if(e.pendingBlobCount>0)return{state:"pending_blobs",...u};if(s>0)return{state:"unsynced_changes",...u};if(r.some((_)=>_.freshness==="never"))return{state:"syncing",...u};if(r.some((_)=>_.freshness==="stale"))return{state:"stale",...u};return{state:"healthy",...u}}Gt();zn();io();function _g(e){let t=We(e),r=e.query("SELECT MAX(seq) AS global_seq, MAX(CASE WHEN node_id = ? THEN seq END) AS own_seq FROM crdt_changes").get(t),n=e.query("SELECT value FROM meta WHERE key = 'cfg_sync_interval'").get(),o=Number(n?.value),s=Math.max(900000,Number.isFinite(o)&&o>0?o*3:0),a=jt(e).filter((m)=>m.kind==="http"||m.kind==="s3").map((m)=>{let x=null,D;if(m.kind==="s3"&&m.config)try{let j=JSON.parse(m.config);x=j.bucket??null,D=j.publish}catch{}return{url:m.url,kind:m.kind,label:m.label,nodeId:m.node_id,enabled:!!m.enabled,lastSuccessAt:m.last_success_at,lastStatus:m.last_status,lastError:m.last_error,pushCursor:m.push_cursor,bucket:x,publish:D}}),u=Cl(e),_={selfNodeId:t,selfLabel:on(e),peers:a,pendingBlobCount:u.length,pendingBlobBytes:u.reduce((m,x)=>m+x.size,0),blobFullNodes:$n(e).fullNodes,globalHighWaterSeq:r.global_seq??0,ownHighWaterSeq:r.own_seq??0,staleAfterMs:s};return{state:pg(_),places:za(_)}}La();Gt();En();co();function gg(e,t){let r=We(e),n=gr(e,t,"revoked");if(n.audience==="public"&&!Ut(e,n.site_id).some((o)=>o.audience==="public"&&o.desired_state==="active"))yi(e,n.site_id,{visibility:"private"});if(n.hosting==="device"&&n.target_ref===r)return Rt(e,{channelId:n.id,status:"revoked",lastVerifiedAt:Date.now()}),{channel:n,needsReconcile:!1};if(n.controller_node_id===r)return{channel:n,needsReconcile:!0};return Rt(e,{channelId:n.id,status:"cleanup_pending",lastError:"等待控制设备上线并应用撤销"}),{channel:n,needsReconcile:!1}}wn();Ye();wn();wi();function vg(e){return e.replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'")}function xv(e){let t=Ua(e),r=ja(e),n=(s)=>Ha(e,s);async function o(s,a){let u=await s.text().catch(()=>"");throw Error(`S3 ${a} failed: ${s.status} ${u.slice(0,200)}`)}return{async list(s,a,u){let _=[],m;do{let x=new URL(r);if(x.searchParams.set("list-type","2"),x.searchParams.set("prefix",s),x.searchParams.set("max-keys","1000"),a)x.searchParams.set("start-after",a);if(u)x.searchParams.set("delimiter",u);if(m)x.searchParams.set("continuation-token",m);let D=await t.fetch(x.toString(),{method:"GET"});if(!D.ok)await o(D,"list");let j=await D.text(),Y=/<Contents>([\s\S]*?)<\/Contents>/g,_e;while(_e=Y.exec(j)){let de=_e[1],ge=/<Key>([^<]+)<\/Key>/.exec(de)?.[1];if(!ge)continue;_.push({key:vg(ge),etag:/<ETag>([^<]*)<\/ETag>/.exec(de)?.[1]})}if(u){let de=/<CommonPrefixes>([\s\S]*?)<\/CommonPrefixes>/g;while(_e=de.exec(j)){let ge=/<Prefix>([^<]+)<\/Prefix>/.exec(_e[1])?.[1];if(ge)_.push({key:vg(ge)})}}m=/<IsTruncated>true<\/IsTruncated>/.test(j)?/<NextContinuationToken>([^<]+)<\/NextContinuationToken>/.exec(j)?.[1]:void 0}while(m);return _},async get(s){let a=await t.fetch(n(s));if(a.status===404)return null;if(!a.ok)await o(a,"get");return new Uint8Array(await a.arrayBuffer())},async put(s,a,u){let _={};if(u?.contentType)_["content-type"]=u.contentType;if(u?.ifNoneMatch)_["if-none-match"]="*";if(u?.ifMatch)_["if-match"]=u.ifMatch;let m=await t.fetch(n(s),{method:"PUT",body:a,headers:Object.keys(_).length?_:void 0});if((u?.ifNoneMatch||u?.ifMatch)&&m.status===412)throw new Z("conflict",`S3 conditional put failed (${u?.ifMatch?"If-Match":"exists"}): ${s}`);if(!m.ok)await o(m,"put")},async del(s){let a=await t.fetch(n(s),{method:"DELETE"});if(!a.ok&&a.status!==404)await o(a,"delete")}}}e_(xv);var Tv=Math.floor(167772160);function kv(e){if(e instanceof ArrayBuffer)return e;let t=new Uint8Array(e.byteLength);return t.set(e),t.buffer}async function Rv(e){let t=await crypto.subtle.digest("SHA-256",kv(e));return[...new Uint8Array(t)].map((r)=>r.toString(16).padStart(2,"0")).join("")}async function Wa(e,t){return(await Rv(e)).slice(0,t.length)===t}var vi=null;function Av(){if(vi)return vi;return vi=new Promise((e,t)=>{let r=indexedDB.open("mh-blobs",1);r.onupgradeneeded=()=>{let n=r.result;if(!n.objectStoreNames.contains("spool"))n.createObjectStore("spool",{keyPath:"hash"});if(!n.objectStoreNames.contains("meta"))n.createObjectStore("meta",{keyPath:"hash"})},r.onsuccess=()=>e(r.result),r.onerror=()=>t(r.error)}),vi}function Kr(e,t,r){return Av().then((n)=>new Promise((o,s)=>{let a=r(n.transaction(e,t).objectStore(e));a.onsuccess=()=>o(a.result),a.onerror=()=>s(a.error)}))}function Za(e){return Kr("spool","readonly",(t)=>t.get(e))}async function Eg(){return(await Kr("spool","readonly",(t)=>t.getAll())??[]).filter((t)=>!t.durable)}async function Sg(e){await Kr("spool","readwrite",(t)=>t.delete(e))}var xg=(e)=>`/blob/${e}`;async function Dv(e,t,r){let n=await Kr("meta","readonly",(s)=>s.get(e)),o={hash:e,size:t,accessed:Date.now(),pinned:n?.pinned??0,content_type:r??n?.content_type};await Kr("meta","readwrite",(s)=>s.put(o))}async function Tg(e,t,r){await(await caches.open("mh-blob-v1")).put(xg(e),new Response(t,{headers:{"content-type":r,"cache-control":"public, max-age=31536000, immutable"}})),await Dv(e,t.byteLength,r),await Ov()}async function Ov(){let e=await Kr("meta","readonly",(o)=>o.getAll())??[],t=e.reduce((o,s)=>o+s.size,0);if(t<=209715200)return;let r=await caches.open("mh-blob-v1"),n=e.filter((o)=>!o.pinned).sort((o,s)=>o.accessed-s.accessed);for(let o of n){if(t<=Tv)break;await r.delete(xg(o.hash)),await Kr("meta","readwrite",(s)=>s.delete(o.hash)),t-=o.size}}oi();qr();Nr();Lr();_n();dt();_n();Nr();Ye();var Iv=1500;function Ga(e){return Number(e.slice(0,15))}function kn(e){return new Date(Ga(e)).toISOString()}function Vr(e){let t=e??"",r=null,n=t.indexOf("/");if(n>0)r=t.slice(0,n),t=t.slice(n+1);let o=t.startsWith("repair:")?"repair":t.startsWith("revert:")?"revert":"user";return{actor:r,kind:o}}function Ka(e){return Vr(e).kind}function Rn(e){let t=[],r=[];for(let n of e){let o=r[r.length-1];if(o&&(o.txn!==null&&n.txn!==null?o.txn!==n.txn:o.node_id!==n.node_id||Ga(n.hlc)-Ga(o.hlc)>Iv))t.push(r),r=[];r.push(n)}if(r.length)t.push(r);return t}function Ht(e){return e!==null&&e!=="0"&&e!=="false"&&e!=="null"}function Ei(e,t){let r=new Map;for(let n of e){if(n.hlc>t)continue;let o=r.get(n.col);if(!o||n.hlc>o.hlc)r.set(n.col,{value:n.value,hlc:n.hlc})}return r}function xi(e,t,r){return e.query(`SELECT ${It} FROM crdt_changes WHERE dataset = ? AND row_id = ? ORDER BY hlc`).all(t,r)}function Pv(e,t){return e.query("SELECT DISTINCT row_id FROM crdt_changes WHERE dataset = 'doc_blocks' AND col = 'doc_id' AND value = ?").all(JSON.stringify(t)).map((r)=>r.row_id)}function kg(e,t){let r=Pv(e,t),n=r.map(()=>"?").join(","),o=r.length?` OR (dataset = 'doc_blocks' AND row_id IN (${n}))`:"";return e.query(`SELECT ${It} FROM crdt_changes
541
+ if(L instanceof ArrayBuffer)L=new Uint8Array(L);else if(L instanceof Function)return this.importDbChunked(A,L);let Q=this.#r.get(A)||this.nextAvailableSAH()||c("No available handles to import to."),ne=L.byteLength;if(ne<512||ne%512!=0)c("Byte array size is invalid for an SQLite db.");let ye="SQLite format 3";for(let Ie=0;Ie<15;++Ie)if(ye.charCodeAt(Ie)!==L[Ie])c("Input does not contain an SQLite database header.");let Te=Q.write(L,{at:O});if(Te!=ne)this.setAssociatedPath(Q,"",0),c("Expected to write "+ne+" bytes but wrote "+Te+".");else Q.write(new Uint8Array([1,1]),{at:O+18}),this.setAssociatedPath(Q,A,E.SQLITE_OPEN_MAIN_DB);return Te}}class te{#e;constructor(A){this.#e=A,this.vfsName=A.vfsName}async addCapacity(A){return this.#e.addCapacity(A)}async reduceCapacity(A){return this.#e.reduceCapacity(A)}getCapacity(){return this.#e.getCapacity(this.#e)}getFileCount(){return this.#e.getFileCount()}getFileNames(){return this.#e.getFileNames()}async reserveMinimumCapacity(A){let L=this.#e.getCapacity();return L<A?this.#e.addCapacity(A-L):L}exportFile(A){return this.#e.exportFile(A)}importDb(A,L){return this.#e.importDb(A,L)}async wipeFiles(){return this.#e.reset(!0)}unlink(A){return this.#e.deletePath(A)}async removeVfs(){return this.#e.removeVfs()}pauseVfs(){return this.#e.pauseVfs(),this}async unpauseVfs(){return this.#e.unpauseVfs().then(()=>this)}isPaused(){return this.#e.isPaused()}}let se=async()=>{let A=await navigator.storage.getDirectory(),L=".opfs-sahpool-sync-check-"+U(),Q=(await(await A.getFileHandle(L,{create:!0})).createSyncAccessHandle()).close();if(await Q,await A.removeEntry(L),Q?.then)c("The local OPFS API is too old for opfs-sahpool:","it has an async FileSystemSyncAccessHandle.close() method.");return!0};f.installOpfsSAHPoolVfs=async function(A=Object.create(null)){A=Object.assign(Object.create(null),S,A||{});let L=A.name;if(A.$testThrowPhase1)throw A.$testThrowPhase1;if(p[L])try{return await p[L]}catch(Q){if(A.forceReinitIfPreviouslyFailed)delete p[L];else throw Q}if(!globalThis.FileSystemHandle||!globalThis.FileSystemDirectoryHandle||!globalThis.FileSystemFileHandle||!globalThis.FileSystemFileHandle.prototype.createSyncAccessHandle||!navigator?.storage?.getDirectory)return p[L]=Promise.reject(Error("Missing required OPFS APIs."));return p[L]=se().then(async function(){if(A.$testThrowPhase2)throw A.$testThrowPhase2;let Q=new N(A);return Q.isReady.then(async()=>{let ne=new te(Q);if(f.oo1){let ye=f.oo1,Te=Q.getVfs(),Ie=function(...qe){let Ge=ye.DB.dbCtorHelper.normalizeArgs(...qe);Ge.vfs=Te.$zName,ye.DB.dbCtorHelper.call(this,Ge)};Ie.prototype=Object.create(ye.DB.prototype),ne.OpfsSAHPoolDb=Ie}return Q.log("VFS initialized."),ne}).catch(async(ne)=>{throw await Q.removeVfs().catch(()=>{}),ne})}).catch((Q)=>p[L]=Promise.reject(Q))}}),globalThis.sqlite3ApiBootstrap.initializers.push(function(f){if(!f.opfs||f.config.disable?.vfs?.["opfs-wl"])return;let c=f.util;f.util.toss;let d=f.opfs,p="opfs-wl",E=async function(b){if(b=d.initOptions(p,b),!b)return f;f.capi;let I=d.createVfsState().vfs;I.metrics.counters;let{mTimeStart:V,mTimeEnd:M,opRun:C,__openFiles:q}=I;return I.bindVfs(c.nu({xLock:function(H,G){V("xLock");let le=q[H],O=C("xLock",H,G);if(!O)le.lockType=G;return M(),O},xUnlock:function(H,G){V("xUnlock");let le=q[H],O=C("xUnlock",H,G);if(!O)le.lockType=G;return M(),O}}),function(H,G){if(H.oo1){let le=function(...O){let R=H.oo1.DB.dbCtorHelper.normalizeArgs(...O);R.vfs=G.$zName,H.oo1.DB.dbCtorHelper.call(this,R)};le.prototype=Object.create(H.oo1.DB.prototype),H.oo1.OpfsWlDb=le,le.importDb=d.importDb}})};globalThis.sqlite3ApiBootstrap.initializersAsync.push(async(b)=>E().catch((I)=>{b.config.warn("Ignoring inability to install the",p,"sqlite3_vfs:",I)}))});try{let f=Object.assign(Object.create(null),{memory:typeof ur<"u"?ur:l.wasmMemory,exports:typeof tn<"u"?tn:Object.prototype.hasOwnProperty.call(l,"wasmExports")?l.wasmExports:l.asm},globalThis.sqlite3ApiBootstrap.defaultConfig,globalThis.sqlite3ApiConfig||{});i.debugModule("Bootstrapping lib config",f);let c=globalThis.sqlite3ApiBootstrap(f);return delete globalThis.sqlite3ApiBootstrap,c}catch(f){throw console.error("sqlite3ApiBootstrap() error:",f),f}},Le)t=r;else t=new Promise((i,l)=>{de=i,ge=l});return t}$i=function(){let e=$i;if(!e)throw Error("Expecting sqlite3InitModule to be defined by the Emscripten build.");let t=globalThis.sqlite3InitModuleState=Object.assign(Object.create(null),{moduleScript:globalThis?.document?.currentScript,isWorker:typeof WorkerGlobalScope<"u",location:globalThis.location,urlParams:globalThis?.location?.href?new URL(globalThis.location.href).searchParams:new URLSearchParams,wasmFilename:"sqlite3.wasm"});if(t.debugModule=t.urlParams.has("sqlite3.debugModule")?(...n)=>console.warn("sqlite3.debugModule:",...n):()=>{},t.urlParams.has("sqlite3.dir"))t.sqlite3Dir=t.urlParams.get("sqlite3.dir")+"/";else if(t.moduleScript){let n=t.moduleScript.src.split("/");n.pop(),t.sqlite3Dir=n.join("/")+"/"}let r=globalThis.sqlite3InitModule=function n(...o){return t.emscriptenLocateFile=o[0]?.locateFile,t.emscriptenInstantiateWasm=o[0]?.instantiateWasm,e(...o).then((s)=>{t.debugModule("sqlite3InitModule() sIMS =",t),t.debugModule("sqlite3InitModule() EmscriptenModule =",s);let a=s.runSQLite3PostLoadInit(t,s,!!n.__isUnderTest);return t.debugModule("sqlite3InitModule() sqlite3 =",a),a}).catch((s)=>{throw console.error("Exception loading sqlite3 module:",s),s})};if(r.ready=e.ready,t.moduleScript){let n=t.moduleScript.src.split("/");n.pop(),t.scriptDir=n.join("/")+"/"}return t.debugModule("extern-post-js.c-pp.js sqlite3InitModuleState =",t),r}();var Cc=$i;class zi{db;txDepth=0;constructor(e){this.db=e}query(e){let t=this.db;return{get(...r){return t.selectObject(e,Fi(r))??null},all(...r){return t.selectObjects(e,Fi(r))},run(...r){return t.exec({sql:e,bind:Fi(r)}),{changes:t.changes()}}}}exec(e){this.db.exec({sql:e})}transaction(e){return(...t)=>{let r=`mh_tx_${this.txDepth}`;this.exec(this.txDepth===0?"BEGIN":`SAVEPOINT ${r}`),this.txDepth++;try{let n=e(...t);return this.txDepth--,this.exec(this.txDepth===0?"COMMIT":`RELEASE ${r}`),n}catch(n){throw this.txDepth--,this.exec(this.txDepth===0?"ROLLBACK":`ROLLBACK TO ${r}; RELEASE ${r}`),n}}}}function Fi(e){if(e.length===0)return;return e.map((t)=>t===void 0?null:t)}Po();Gt();bt();Ye();dt();$n();ia();oo();Fn();var bg=(e)=>{let t=/^[a-z0-9+]+:\/\/([^/]+)/i.exec(e);return t?t[1]:e};function Iv(e,t,r,n,o,s){let a=e.kind==="s3",u=a?n:r,_=Math.max(0,u-e.pushCursor),m=a?["backend"]:["replica"],x=a?e.url:e.nodeId;if(x&&t.includes(x))m.push("blob_anchor");if(a&&e.publish)m.push("publisher");return{kind:a?"bucket":"device",url:e.url,label:e.label??(a?e.bucket??bg(e.url):bg(e.url)),freshness:!e.enabled?"disabled":e.lastStatus==="error"?"error":e.lastSuccessAt==null?"never":_>0?"behind":o-e.lastSuccessAt>s?"stale":"current",syncedAt:e.lastSuccessAt,error:e.lastStatus==="error"?e.lastError??null:null,acknowledgedSeq:e.pushCursor,highWaterSeq:u,lag:_,roles:m}}function Ba(e){let t={kind:"self",url:null,label:e.selfLabel??"本机",freshness:"live",syncedAt:null,error:null,acknowledgedSeq:e.globalHighWaterSeq,highWaterSeq:e.globalHighWaterSeq,lag:0,roles:e.blobFullNodes.includes(e.selfNodeId)?["replica","blob_anchor"]:["replica"]},r=(a)=>a==="current"?0:a==="stale"?1:a==="behind"?2:a==="error"?3:a==="never"?4:5,n=e.now??Date.now(),o=e.staleAfterMs??86400000,s=e.peers.map((a)=>Iv(a,e.blobFullNodes,e.globalHighWaterSeq,e.ownHighWaterSeq,n,o)).sort((a,u)=>Number(a.kind==="bucket")-Number(u.kind==="bucket")||r(a.freshness)-r(u.freshness)||a.label.localeCompare(u.label));return[t,...s]}function wg(e){let r=Ba(e).filter((_)=>_.kind!=="self"&&_.freshness!=="disabled"),n=r.filter((_)=>_.syncedAt!=null&&_.acknowledgedSeq>=_.highWaterSeq),o=n.length?n.reduce((_,m)=>_==null||(m.syncedAt??0)<_?m.syncedAt:_,null):null,s=r.reduce((_,m)=>Math.max(_,m.lag),0),a=[];if(r.length===0)a.push({kind:"no_backup",placeUrl:null,placeLabel:null,message:null});for(let _ of r)if(_.freshness==="error")a.push({kind:"peer_error",placeUrl:_.url,placeLabel:_.label,message:_.error});if(e.pendingBlobCount>0)a.push({kind:"pending_blobs",placeUrl:null,placeLabel:null,message:null});for(let _ of r)if(_.freshness==="behind")a.push({kind:"behind",placeUrl:_.url,placeLabel:_.label,message:null});for(let _ of r)if(_.freshness==="never")a.push({kind:"never_synced",placeUrl:_.url,placeLabel:_.label,message:null});for(let _ of r)if(_.freshness==="stale")a.push({kind:"stale",placeUrl:_.url,placeLabel:_.label,message:null});let u={places:1+n.length,pendingBlobCount:e.pendingBlobCount,pendingBlobBytes:e.pendingBlobBytes,pendingChanges:s,oldestSyncedAt:o,issues:a};if(r.length===0)return{state:"no_backup",...u};if(r.some((_)=>_.freshness==="error"))return{state:"peer_error",...u};if(e.pendingBlobCount>0)return{state:"pending_blobs",...u};if(s>0)return{state:"unsynced_changes",...u};if(r.some((_)=>_.freshness==="never"))return{state:"syncing",...u};if(r.some((_)=>_.freshness==="stale"))return{state:"stale",...u};return{state:"healthy",...u}}Gt();$n();oo();function vg(e){let t=je(e),r=e.query("SELECT MAX(seq) AS global_seq, MAX(CASE WHEN node_id = ? THEN seq END) AS own_seq FROM crdt_changes").get(t),n=e.query("SELECT value FROM meta WHERE key = 'cfg_sync_interval'").get(),o=Number(n?.value),s=Math.max(900000,Number.isFinite(o)&&o>0?o*3:0),a=Ht(e).filter((m)=>m.kind==="http"||m.kind==="s3").map((m)=>{let x=null,D;if(m.kind==="s3"&&m.config)try{let j=JSON.parse(m.config);x=j.bucket??null,D=j.publish}catch{}return{url:m.url,kind:m.kind,label:m.label,nodeId:m.node_id,enabled:!!m.enabled,lastSuccessAt:m.last_success_at,lastStatus:m.last_status,lastError:m.last_error,pushCursor:m.push_cursor,bucket:x,publish:D}}),u=Ml(e),_={selfNodeId:t,selfLabel:Mc(e),peers:a,pendingBlobCount:u.length,pendingBlobBytes:u.reduce((m,x)=>m+x.size,0),blobFullNodes:Ln(e).fullNodes,globalHighWaterSeq:r.global_seq??0,ownHighWaterSeq:r.own_seq??0,staleAfterMs:s};return{state:wg(_),places:Ba(_)}}za();Gt();vn();ao();function Eg(e,t){let r=je(e),n=mr(e,t,"revoked");if(n.audience==="public"&&!jt(e,n.site_id).some((o)=>o.audience==="public"&&o.desired_state==="active"))yi(e,n.site_id,{visibility:"private"});if(n.hosting==="device"&&n.target_ref===r)return Rt(e,{channelId:n.id,status:"revoked",lastVerifiedAt:Date.now()}),{channel:n,needsReconcile:!1};if(n.controller_node_id===r)return{channel:n,needsReconcile:!0};return Rt(e,{channelId:n.id,status:"cleanup_pending",lastError:"等待控制设备上线并应用撤销"}),{channel:n,needsReconcile:!1}}bn();Ye();bn();wi();function Ag(e){return e.replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'")}function qv(e){let t=Wa(e),r=Za(e),n=(s)=>Ga(e,s);async function o(s,a){let u=await s.text().catch(()=>"");throw Error(`S3 ${a} failed: ${s.status} ${u.slice(0,200)}`)}return{async list(s,a,u){let _=[],m;do{let x=new URL(r);if(x.searchParams.set("list-type","2"),x.searchParams.set("prefix",s),x.searchParams.set("max-keys","1000"),a)x.searchParams.set("start-after",a);if(u)x.searchParams.set("delimiter",u);if(m)x.searchParams.set("continuation-token",m);let D=await t.fetch(x.toString(),{method:"GET"});if(!D.ok)await o(D,"list");let j=await D.text(),Y=/<Contents>([\s\S]*?)<\/Contents>/g,_e;while(_e=Y.exec(j)){let de=_e[1],ge=/<Key>([^<]+)<\/Key>/.exec(de)?.[1];if(!ge)continue;_.push({key:Ag(ge),etag:/<ETag>([^<]*)<\/ETag>/.exec(de)?.[1]})}if(u){let de=/<CommonPrefixes>([\s\S]*?)<\/CommonPrefixes>/g;while(_e=de.exec(j)){let ge=/<Prefix>([^<]+)<\/Prefix>/.exec(_e[1])?.[1];if(ge)_.push({key:Ag(ge)})}}m=/<IsTruncated>true<\/IsTruncated>/.test(j)?/<NextContinuationToken>([^<]+)<\/NextContinuationToken>/.exec(j)?.[1]:void 0}while(m);return _},async get(s){let a=await t.fetch(n(s));if(a.status===404)return null;if(!a.ok)await o(a,"get");return new Uint8Array(await a.arrayBuffer())},async put(s,a,u){let _={};if(u?.contentType)_["content-type"]=u.contentType;if(u?.ifNoneMatch)_["if-none-match"]="*";if(u?.ifMatch)_["if-match"]=u.ifMatch;let m=await t.fetch(n(s),{method:"PUT",body:a,headers:Object.keys(_).length?_:void 0});if((u?.ifNoneMatch||u?.ifMatch)&&m.status===412)throw new Z("conflict",`S3 conditional put failed (${u?.ifMatch?"If-Match":"exists"}): ${s}`);if(!m.ok)await o(m,"put")},async del(s){let a=await t.fetch(n(s),{method:"DELETE"});if(!a.ok&&a.status!==404)await o(a,"delete")}}}a_(qv);var Lv=Math.floor(167772160);function $v(e){if(e instanceof ArrayBuffer)return e;let t=new Uint8Array(e.byteLength);return t.set(e),t.buffer}async function Fv(e){let t=await crypto.subtle.digest("SHA-256",$v(e));return[...new Uint8Array(t)].map((r)=>r.toString(16).padStart(2,"0")).join("")}async function Ka(e,t){return(await Fv(e)).slice(0,t.length)===t}var vi=null;function zv(){if(vi)return vi;return vi=new Promise((e,t)=>{let r=indexedDB.open("mh-blobs",1);r.onupgradeneeded=()=>{let n=r.result;if(!n.objectStoreNames.contains("spool"))n.createObjectStore("spool",{keyPath:"hash"});if(!n.objectStoreNames.contains("meta"))n.createObjectStore("meta",{keyPath:"hash"})},r.onsuccess=()=>e(r.result),r.onerror=()=>t(r.error)}),vi}function Kr(e,t,r){return zv().then((n)=>new Promise((o,s)=>{let a=r(n.transaction(e,t).objectStore(e));a.onsuccess=()=>o(a.result),a.onerror=()=>s(a.error)}))}function Va(e){return Kr("spool","readonly",(t)=>t.get(e))}async function Dg(){return(await Kr("spool","readonly",(t)=>t.getAll())??[]).filter((t)=>!t.durable)}async function Og(e){await Kr("spool","readwrite",(t)=>t.delete(e))}var Ig=(e)=>`/blob/${e}`;async function Mv(e,t,r){let n=await Kr("meta","readonly",(s)=>s.get(e)),o={hash:e,size:t,accessed:Date.now(),pinned:n?.pinned??0,content_type:r??n?.content_type};await Kr("meta","readwrite",(s)=>s.put(o))}async function Pg(e,t,r){await(await caches.open("mh-blob-v1")).put(Ig(e),new Response(t,{headers:{"content-type":r,"cache-control":"public, max-age=31536000, immutable"}})),await Mv(e,t.byteLength,r),await Bv()}async function Bv(){let e=await Kr("meta","readonly",(o)=>o.getAll())??[],t=e.reduce((o,s)=>o+s.size,0);if(t<=209715200)return;let r=await caches.open("mh-blob-v1"),n=e.filter((o)=>!o.pinned).sort((o,s)=>o.accessed-s.accessed);for(let o of n){if(t<=Lv)break;await r.delete(Ig(o.hash)),await Kr("meta","readwrite",(s)=>s.delete(o.hash)),t-=o.size}}oi();qr();Cr();Lr();pn();dt();pn();Cr();Ye();var Uv=1500;function Ja(e){return Number(e.slice(0,15))}function Tn(e){return new Date(Ja(e)).toISOString()}function Vr(e){let t=e??"",r=null,n=t.indexOf("/");if(n>0)r=t.slice(0,n),t=t.slice(n+1);let o=t.startsWith("repair:")?"repair":t.startsWith("revert:")?"revert":"user";return{actor:r,kind:o}}function Xa(e){return Vr(e).kind}function kn(e){let t=[],r=[];for(let n of e){let o=r[r.length-1];if(o&&(o.txn!==null&&n.txn!==null?o.txn!==n.txn:o.node_id!==n.node_id||Ja(n.hlc)-Ja(o.hlc)>Uv))t.push(r),r=[];r.push(n)}if(r.length)t.push(r);return t}function Wt(e){return e!==null&&e!=="0"&&e!=="false"&&e!=="null"}function Ei(e,t){let r=new Map;for(let n of e){if(n.hlc>t)continue;let o=r.get(n.col);if(!o||n.hlc>o.hlc)r.set(n.col,{value:n.value,hlc:n.hlc})}return r}function xi(e,t,r){return e.query(`SELECT ${It} FROM crdt_changes WHERE dataset = ? AND row_id = ? ORDER BY hlc`).all(t,r)}function jv(e,t){return e.query("SELECT DISTINCT row_id FROM crdt_changes WHERE dataset = 'doc_blocks' AND col = 'doc_id' AND value = ?").all(JSON.stringify(t)).map((r)=>r.row_id)}function Ng(e,t){let r=jv(e,t),n=r.map(()=>"?").join(","),o=r.length?` OR (dataset = 'doc_blocks' AND row_id IN (${n}))`:"";return e.query(`SELECT ${It} FROM crdt_changes
526
542
  WHERE (dataset = 'documents' AND row_id = ?)${o}
527
- ORDER BY hlc`).all(t,...r)}function Rg(e,t){let r=kg(e,t);if(!r.length)throw new Z("not_found",`no such document: ${t}`);let n=new Map,o=[];for(let s of Rn(r)){let a=new Set,u=new Set,_=new Map,m=!1,x=!1,D=0;for(let de of s)if(de.dataset==="documents"){if(_.set(de.col,de.value),de.col==="created_hlc")m=!0;else if(de.col==="__deleted")x=Ht(de.value)}else if(D++,de.col==="__deleted"&&Ht(de.value))u.add(de.row_id);else if(de.col==="text")a.add(de.row_id);let j=!1,Y=0;for(let[de,ge]of _){let Le=!n.has(de)||n.get(de)!==ge;if(n.set(de,ge),!Le)continue;if(Y++,de==="title")j=!0}if(Y===0&&D===0)continue;let _e=s[s.length-1];o.push({version:_e.hlc,at:kn(_e.hlc),node_id:_e.node_id,kind:Ka(_e.txn),actor:Vr(_e.txn).actor,changes:s.length,created:m,deleted:x,title_changed:j,blocks_changed:a.size,blocks_deleted:u.size})}return o.reverse()}function Va(e,t,r){if(!r)throw new Z("invalid_input","missing version cutoff");let n=kg(e,t).filter((m)=>m.hlc<=r);if(!n.length)throw new Z("not_found",`no version of document ${t} at or before ${r}`);let o=Ei(n.filter((m)=>m.dataset==="documents"),r),s=(m)=>{let x=o.get(m);return x?.value==null?void 0:JSON.parse(x.value)},a=new Map;for(let m of n){if(m.dataset!=="doc_blocks")continue;(a.get(m.row_id)??a.set(m.row_id,[]).get(m.row_id)).push(m)}let u=[];for(let[m,x]of a){let D=Ei(x,r),j=(_e)=>{let de=D.get(_e);return de?.value==null?void 0:JSON.parse(de.value)};if(j("doc_id")!==t)continue;if(D.get("__deleted")&&Ht(D.get("__deleted").value))continue;let Y=j("text");if(typeof Y!=="string"||!Y)continue;u.push({id:m,text:Y,order_key:j("order_key")??null,blankAfter:j("blank_after")??0})}u.sort((m,x)=>{if(m.order_key!==x.order_key){if(m.order_key===null)return-1;if(x.order_key===null)return 1;return m.order_key<x.order_key?-1:1}return m.id<x.id?-1:1});let _=a.size?Cr(u):s("body")??"";return{id:t,title:s("title")??"",body:_,deleted:o.get("__deleted")?Ht(o.get("__deleted").value):!1,version:n[n.length-1].hlc}}var Ag=Fe(function(t,r,n,o={}){let s=nt(t,r);if(!s&&!t.query("SELECT 1 AS x FROM documents WHERE id = ?").get(r))throw new Z("not_found",`no such document: ${r}`);if(o.ifMatch!==void 0&&Tt(t,r)!==o.ifMatch)throw new Z("stale",`stale: document changed since ${o.ifMatch}; re-read first`);let a=Va(t,r,n);if(a.deleted)throw new Z("invalid_input","target version is a deleted state; use doc delete instead");let u=!s;if(!s)we(t,"documents",r,"__deleted",0),s=nt(t,r);let _={};if(a.title!==s.title)_.title=a.title;if(a.body!==(s.body??""))_.body=a.body;if(Object.keys(_).length)Oo(t,r,_);return{id:r,changed:Object.keys(_).length>0||u,restored:a.version,version:Tt(t,r),undeleted:u}},"revert"),Si=new Set(["database_id","created_hlc","order_key","__deleted"]);function Dg(e){let t=new Set,r=!1,n=!1,o=!1;for(let a of e)if(a.col==="created_hlc")r=!0;else if(a.col==="__deleted")n=Ht(a.value);else if(a.col==="order_key")o=!0;else if(!Si.has(a.col))t.add(a.col);let s=e[e.length-1];return{version:s.hlc,at:kn(s.hlc),node_id:s.node_id,kind:Ka(s.txn),actor:Vr(s.txn).actor,changes:e.length,created:r,deleted:n,fields:[...t],moved:o}}function Og(e,t){let r=xi(e,"records",t);if(!r.length)throw new Z("not_found",`no such record: ${t}`);return Rn(r).map(Dg).reverse()}function Ig(e,t,r={}){if(!e.query("SELECT 1 AS x FROM databases WHERE id = ?").get(t))throw new Z("not_found",`no such database: ${t}`);let n=e.query("SELECT id FROM properties WHERE database_id = ? AND type = 'text' AND __deleted = 0 ORDER BY position LIMIT 1").get(t)?.id??null,o=e.query(`SELECT ${It} FROM crdt_changes
543
+ ORDER BY hlc`).all(t,...r)}function Cg(e,t){let r=Ng(e,t);if(!r.length)throw new Z("not_found",`no such document: ${t}`);let n=new Map,o=[];for(let s of kn(r)){let a=new Set,u=new Set,_=new Map,m=!1,x=!1,D=0;for(let de of s)if(de.dataset==="documents"){if(_.set(de.col,de.value),de.col==="created_hlc")m=!0;else if(de.col==="__deleted")x=Wt(de.value)}else if(D++,de.col==="__deleted"&&Wt(de.value))u.add(de.row_id);else if(de.col==="text")a.add(de.row_id);let j=!1,Y=0;for(let[de,ge]of _){let Le=!n.has(de)||n.get(de)!==ge;if(n.set(de,ge),!Le)continue;if(Y++,de==="title")j=!0}if(Y===0&&D===0)continue;let _e=s[s.length-1];o.push({version:_e.hlc,at:Tn(_e.hlc),node_id:_e.node_id,kind:Xa(_e.txn),actor:Vr(_e.txn).actor,changes:s.length,created:m,deleted:x,title_changed:j,blocks_changed:a.size,blocks_deleted:u.size})}return o.reverse()}function Qa(e,t,r){if(!r)throw new Z("invalid_input","missing version cutoff");let n=Ng(e,t).filter((m)=>m.hlc<=r);if(!n.length)throw new Z("not_found",`no version of document ${t} at or before ${r}`);let o=Ei(n.filter((m)=>m.dataset==="documents"),r),s=(m)=>{let x=o.get(m);return x?.value==null?void 0:JSON.parse(x.value)},a=new Map;for(let m of n){if(m.dataset!=="doc_blocks")continue;(a.get(m.row_id)??a.set(m.row_id,[]).get(m.row_id)).push(m)}let u=[];for(let[m,x]of a){let D=Ei(x,r),j=(_e)=>{let de=D.get(_e);return de?.value==null?void 0:JSON.parse(de.value)};if(j("doc_id")!==t)continue;if(D.get("__deleted")&&Wt(D.get("__deleted").value))continue;let Y=j("text");if(typeof Y!=="string"||!Y)continue;u.push({id:m,text:Y,order_key:j("order_key")??null,blankAfter:j("blank_after")??0})}u.sort((m,x)=>{if(m.order_key!==x.order_key){if(m.order_key===null)return-1;if(x.order_key===null)return 1;return m.order_key<x.order_key?-1:1}return m.id<x.id?-1:1});let _=a.size?Nr(u):s("body")??"";return{id:t,title:s("title")??"",body:_,deleted:o.get("__deleted")?Wt(o.get("__deleted").value):!1,version:n[n.length-1].hlc}}var qg=ze(function(t,r,n,o={}){let s=nt(t,r);if(!s&&!t.query("SELECT 1 AS x FROM documents WHERE id = ?").get(r))throw new Z("not_found",`no such document: ${r}`);if(o.ifMatch!==void 0&&Tt(t,r)!==o.ifMatch)throw new Z("stale",`stale: document changed since ${o.ifMatch}; re-read first`);let a=Qa(t,r,n);if(a.deleted)throw new Z("invalid_input","target version is a deleted state; use doc delete instead");let u=!s;if(!s)be(t,"documents",r,"__deleted",0),s=nt(t,r);let _={};if(a.title!==s.title)_.title=a.title;if(a.body!==(s.body??""))_.body=a.body;if(Object.keys(_).length)Oo(t,r,_);return{id:r,changed:Object.keys(_).length>0||u,restored:a.version,version:Tt(t,r),undeleted:u}},"revert"),Si=new Set(["database_id","created_hlc","order_key","__deleted"]);function Lg(e){let t=new Set,r=!1,n=!1,o=!1;for(let a of e)if(a.col==="created_hlc")r=!0;else if(a.col==="__deleted")n=Wt(a.value);else if(a.col==="order_key")o=!0;else if(!Si.has(a.col))t.add(a.col);let s=e[e.length-1];return{version:s.hlc,at:Tn(s.hlc),node_id:s.node_id,kind:Xa(s.txn),actor:Vr(s.txn).actor,changes:e.length,created:r,deleted:n,fields:[...t],moved:o}}function $g(e,t){let r=xi(e,"records",t);if(!r.length)throw new Z("not_found",`no such record: ${t}`);return kn(r).map(Lg).reverse()}function Fg(e,t,r={}){if(!e.query("SELECT 1 AS x FROM databases WHERE id = ?").get(t))throw new Z("not_found",`no such database: ${t}`);let n=e.query("SELECT id FROM properties WHERE database_id = ? AND type = 'text' AND __deleted = 0 ORDER BY position LIMIT 1").get(t)?.id??null,o=e.query(`SELECT ${It} FROM crdt_changes
528
544
  WHERE dataset = 'records' AND row_id IN (SELECT id FROM records WHERE database_id = ?)
529
- ORDER BY row_id, hlc`).all(t),s=[],a=0;for(let u=1;u<=o.length;u++){if(u!==o.length&&o[u].row_id===o[a].row_id)continue;let _=o[a].row_id,m=new Map;for(let x of Rn(o.slice(a,u))){let D=new Set;for(let _e of x)if(!Si.has(_e.col))D.add(_e.col);let j=new Map;for(let _e of D)if(m.has(_e))j.set(_e,m.get(_e));for(let _e of x){if(Si.has(_e.col))continue;if(_e.value===null)m.delete(_e.col);else m.set(_e.col,JSON.parse(_e.value))}let Y=[];for(let _e of D){let de={prop:_e};if(j.has(_e))de.before=j.get(_e);if(m.has(_e))de.after=m.get(_e);Y.push(de)}s.push({...Dg(x),record_id:_,record_title:n&&m.has(n)?String(m.get(n)??""):null,diffs:Y})}a=u}return s.sort((u,_)=>u.version<_.version?1:-1),s.slice(0,r.limit??100)}function Ja(e,t,r){if(!r)throw new Z("invalid_input","missing version cutoff");let n=xi(e,"records",t).filter((u)=>u.hlc<=r);if(!n.length)throw new Z("not_found",`no version of record ${t} at or before ${r}`);let o=Ei(n,r),s={};for(let[u,_]of o){if(Si.has(u))continue;if(_.value===null)continue;s[u]=JSON.parse(_.value)}let a=o.get("database_id");return{id:t,database_id:a?.value==null?null:JSON.parse(a.value),deleted:o.get("__deleted")?Ht(o.get("__deleted").value):!1,data:s,version:n[n.length-1].hlc}}var Pg=Fe(function(t,r,n){let o=t.query("SELECT database_id, data, __deleted FROM records WHERE id = ?").get(r);if(!o)throw new Z("not_found",`no such record: ${r}`);let s=Ja(t,r,n);if(s.deleted)throw new Z("invalid_input","target version is a deleted state; use record delete instead");let a=new Set(o.database_id?Nt(t,o.database_id).map((x)=>x.id):[]),u=JSON.parse(o.data||"{}"),_=[];for(let x of a){let D=Object.hasOwn(s.data,x),j=Object.hasOwn(u,x);if(D&&(!j||JSON.stringify(s.data[x])!==JSON.stringify(u[x])))we(t,"records",r,x,s.data[x]),_.push(x);else if(!D&&j)we(t,"records",r,x,void 0),_.push(x)}let m=o.__deleted!==0;if(m)we(t,"records",r,"__deleted",0);return{id:r,changed:_.length>0||m,fields:_,undeleted:m,restored:s.version}},"revert"),Cg=["name","type","config","position"];function Ng(e,t){let r=xi(e,"properties",t);if(!r.length)throw new Z("not_found",`no such property: ${t}`);let n=new Map(e.query("SELECT txn, COUNT(*) AS n FROM crdt_changes WHERE dataset = 'records' AND col = ? AND txn IS NOT NULL GROUP BY txn").all(t).map((o)=>[o.txn,o.n]));return Rn(r).map((o)=>{let s=new Set,a=!1,u=!1;for(let m of o)if(m.col==="database_id")a=!0;else if(m.col==="__deleted")u=Ht(m.value);else if(Cg.includes(m.col))s.add(m.col);let _=o[o.length-1];return{version:_.hlc,at:kn(_.hlc),node_id:_.node_id,kind:Ka(_.txn),actor:Vr(_.txn).actor,changes:o.length,created:a,deleted:u,fields:[...s],cells_cleared:_.txn?n.get(_.txn)??0:0}}).reverse()}function Cv(e,t,r){if(!r)throw new Z("invalid_input","missing version cutoff");let n=xi(e,"properties",t).filter((a)=>a.hlc<=r);if(!n.length)throw new Z("not_found",`no version of property ${t} at or before ${r}`);let o=Ei(n,r),s=(a)=>{let u=o.get(a);return u?.value==null?void 0:JSON.parse(u.value)};return{id:t,database_id:s("database_id")??null,name:s("name")??"",type:s("type")??"text",config:s("config")??null,position:s("position")??null,deleted:o.get("__deleted")?Ht(o.get("__deleted").value):!1,version:n[n.length-1].hlc}}var qg=Fe(function(t,r,n){let o=t.query("SELECT database_id, name, type, config, position, __deleted FROM properties WHERE id = ?").get(r);if(!o)throw new Z("not_found",`no such property: ${r}`);let s=Cv(t,r,n);if(s.deleted)throw new Z("invalid_input","target version is a deleted state; use prop remove instead");let a={name:o.name,type:o.type,config:o.config?JSON.parse(o.config):null,position:o.position},u={name:s.name,type:s.type,config:s.config,position:s.position},_=[];for(let ge of Cg)if(JSON.stringify(u[ge]??null)!==JSON.stringify(a[ge]??null))we(t,"properties",r,ge,u[ge]),_.push(ge);let m=o.__deleted!==0;if(m)we(t,"properties",r,"__deleted",0);let x=new Set(t.query("SELECT DISTINCT txn FROM crdt_changes WHERE dataset = 'properties' AND row_id = ? AND hlc > ? AND txn IS NOT NULL").all(r,n).map((ge)=>ge.txn)),D=t.query("SELECT row_id, hlc, value, txn FROM crdt_changes WHERE dataset = 'records' AND col = ? ORDER BY row_id, hlc").all(r),j=(ge)=>ge!==null&&(x.has(ge)||Vr(ge).kind==="repair"),Y=0,_e=0,de=0;while(de<D.length){let ge=D[de].row_id,Le=D[de],Ze=null;for(;de<D.length&&D[de].row_id===ge;de++)if(Le=D[de],!j(Le.txn))Ze=Le;if(Le.hlc<=n)continue;if(!j(Le.txn)){_e++;continue}let $e=Ze?Ze.value:null;if($e===Le.value)continue;we(t,"records",ge,r,$e===null?void 0:JSON.parse($e)),Y++}return{id:r,changed:_.length>0||m||Y>0,fields:_,restored_cells:Y,skipped_cells:_e,undeleted:m,restored:s.version}},"revert");function Lg(e,t,r){return e.query("SELECT hlc, node_id, value FROM crdt_changes WHERE dataset = 'records' AND row_id = ? AND col = ? ORDER BY hlc DESC").all(t,r).map((o)=>({version:o.hlc,at:kn(o.hlc),node_id:o.node_id,value:o.value===null?void 0:JSON.parse(o.value),cleared:o.value===null}))}dt();Ye();function $g(e,t){if(e==="records")return Hi.has(t);return t==="created_hlc"||t==="__deleted"}function zg(){return{sql:[...Ln].map(()=>"dataset != ?"),params:[...Ln]}}function Xa(e,t,r){let n=zg(),o=["txn = ?",...n.sql],s=[t,...n.params];if(r)o.push("hlc < ?"),s.push(r);return e.query(`SELECT ${It} FROM crdt_changes WHERE ${o.join(" AND ")} ORDER BY hlc`).all(...s)}function Fg(e,t,r){if(!t)return null;if(!r.dbNames.has(t)){let n=e.query("SELECT name FROM databases WHERE id = ?").get(t);r.dbNames.set(t,n?.name??null)}return r.dbNames.get(t)}function Nv(e,t,r){if(!r.titleProps.has(t)){let n=e.query("SELECT id FROM properties WHERE database_id = ? AND type = 'text' AND __deleted = 0 ORDER BY position LIMIT 1").get(t);r.titleProps.set(t,n?.id??null)}return r.titleProps.get(t)??null}function qv(e,t,r,n){if(t==="records"){let o=e.query("SELECT database_id, data FROM records WHERE id = ?").get(r);if(!o)return{label:null,database_id:null};let s=o.database_id?Nv(e,o.database_id,n):null,a=JSON.parse(o.data||"{}");return{label:s&&a[s]!=null?String(a[s]):null,database_id:o.database_id}}if(t==="documents"){let o=e.query("SELECT title, database_id FROM documents WHERE id = ?").get(r);return{label:o?.title??null,database_id:o?.database_id??null}}if(t==="properties"){let o=e.query("SELECT name, database_id FROM properties WHERE id = ?").get(r);return{label:o?.name??null,database_id:o?.database_id??null}}if(t==="databases")return{label:Fg(e,r,n),database_id:r};if(t==="sites"){let o=e.query("SELECT title, name FROM sites WHERE id = ?").get(r);return{label:o?.title??o?.name??null,database_id:null}}return{label:null,database_id:null}}function Mg(e,t,r){for(let s of t)if(s.dataset==="doc_blocks"&&s.row_id===r&&s.col==="doc_id"&&s.value)return JSON.parse(s.value);let n=e.query("SELECT doc_id FROM doc_blocks WHERE id = ?").get(r);if(n?.doc_id)return n.doc_id;let o=e.query("SELECT value FROM crdt_changes WHERE dataset = 'doc_blocks' AND row_id = ? AND col = 'doc_id' AND value IS NOT NULL ORDER BY hlc DESC LIMIT 1").get(r);return o?JSON.parse(o.value):null}function Bg(e,t,r){let n=new Map,o=(m,x)=>{let D=m+"\x00"+x,j=n.get(D);if(!j)j={dataset:m,id:x,created:!1,deleted:!1,fields:new Set,blocksChanged:new Set,blocksDeleted:new Set},n.set(D,j);return j};for(let m of t){if(m.dataset==="doc_blocks"){let D=Mg(e,t,m.row_id),j=D?o("documents",D):o("doc_blocks",m.row_id);if(m.col==="__deleted"&&Ht(m.value))j.blocksDeleted.add(m.row_id);else j.blocksChanged.add(m.row_id);continue}let x=o(m.dataset,m.row_id);if(m.col==="created_hlc"||m.dataset==="properties"&&m.col==="database_id")x.created=!0;else if(m.col==="__deleted")x.deleted=Ht(m.value);if(!$g(m.dataset,m.col))x.fields.add(m.col)}let s=[...n.values()].map((m)=>{let{label:x,database_id:D}=qv(e,m.dataset,m.id,r);return{dataset:m.dataset,id:m.id,label:x,database_id:D,database_label:m.dataset==="databases"?null:Fg(e,D,r),created:m.created,deleted:m.deleted,fields:m.fields.size,blocks_changed:[...m.blocksChanged].filter((j)=>!m.blocksDeleted.has(j)).length,blocks_deleted:m.blocksDeleted.size}}),a=t[t.length-1],{actor:u,kind:_}=Vr(a.txn);return{version:a.hlc,at:kn(a.hlc),node_id:a.node_id,kind:_,actor:u,txn:a.txn,changes:t.length,entities:s}}function Ug(e,t={}){let r=Math.max(1,Math.min(t.limit??50,200));if(t.actor!==void 0&&!Hc.test(t.actor))throw new Z("invalid_input",`invalid actor tag: ${t.actor}`);let n=Math.min(Math.max(r*40,800),8000),o=zg(),s=[...o.sql],a=[...o.params];if(t.before)s.push("hlc < ?"),a.push(t.before);if(t.actor!==void 0)s.push("txn >= ?","txn < ?"),a.push(t.actor+"/",t.actor+"0");let u=e.query(`SELECT ${It} FROM crdt_changes
545
+ ORDER BY row_id, hlc`).all(t),s=[],a=0;for(let u=1;u<=o.length;u++){if(u!==o.length&&o[u].row_id===o[a].row_id)continue;let _=o[a].row_id,m=new Map;for(let x of kn(o.slice(a,u))){let D=new Set;for(let _e of x)if(!Si.has(_e.col))D.add(_e.col);let j=new Map;for(let _e of D)if(m.has(_e))j.set(_e,m.get(_e));for(let _e of x){if(Si.has(_e.col))continue;if(_e.value===null)m.delete(_e.col);else m.set(_e.col,JSON.parse(_e.value))}let Y=[];for(let _e of D){let de={prop:_e};if(j.has(_e))de.before=j.get(_e);if(m.has(_e))de.after=m.get(_e);Y.push(de)}s.push({...Lg(x),record_id:_,record_title:n&&m.has(n)?String(m.get(n)??""):null,diffs:Y})}a=u}return s.sort((u,_)=>u.version<_.version?1:-1),s.slice(0,r.limit??100)}function Ya(e,t,r){if(!r)throw new Z("invalid_input","missing version cutoff");let n=xi(e,"records",t).filter((u)=>u.hlc<=r);if(!n.length)throw new Z("not_found",`no version of record ${t} at or before ${r}`);let o=Ei(n,r),s={};for(let[u,_]of o){if(Si.has(u))continue;if(_.value===null)continue;s[u]=JSON.parse(_.value)}let a=o.get("database_id");return{id:t,database_id:a?.value==null?null:JSON.parse(a.value),deleted:o.get("__deleted")?Wt(o.get("__deleted").value):!1,data:s,version:n[n.length-1].hlc}}var zg=ze(function(t,r,n){let o=t.query("SELECT database_id, data, __deleted FROM records WHERE id = ?").get(r);if(!o)throw new Z("not_found",`no such record: ${r}`);let s=Ya(t,r,n);if(s.deleted)throw new Z("invalid_input","target version is a deleted state; use record delete instead");let a=new Set(o.database_id?Ct(t,o.database_id).map((x)=>x.id):[]),u=JSON.parse(o.data||"{}"),_=[];for(let x of a){let D=Object.hasOwn(s.data,x),j=Object.hasOwn(u,x);if(D&&(!j||JSON.stringify(s.data[x])!==JSON.stringify(u[x])))be(t,"records",r,x,s.data[x]),_.push(x);else if(!D&&j)be(t,"records",r,x,void 0),_.push(x)}let m=o.__deleted!==0;if(m)be(t,"records",r,"__deleted",0);return{id:r,changed:_.length>0||m,fields:_,undeleted:m,restored:s.version}},"revert"),Mg=["name","type","config","position"];function Bg(e,t){let r=xi(e,"properties",t);if(!r.length)throw new Z("not_found",`no such property: ${t}`);let n=new Map(e.query("SELECT txn, COUNT(*) AS n FROM crdt_changes WHERE dataset = 'records' AND col = ? AND txn IS NOT NULL GROUP BY txn").all(t).map((o)=>[o.txn,o.n]));return kn(r).map((o)=>{let s=new Set,a=!1,u=!1;for(let m of o)if(m.col==="database_id")a=!0;else if(m.col==="__deleted")u=Wt(m.value);else if(Mg.includes(m.col))s.add(m.col);let _=o[o.length-1];return{version:_.hlc,at:Tn(_.hlc),node_id:_.node_id,kind:Xa(_.txn),actor:Vr(_.txn).actor,changes:o.length,created:a,deleted:u,fields:[...s],cells_cleared:_.txn?n.get(_.txn)??0:0}}).reverse()}function Hv(e,t,r){if(!r)throw new Z("invalid_input","missing version cutoff");let n=xi(e,"properties",t).filter((a)=>a.hlc<=r);if(!n.length)throw new Z("not_found",`no version of property ${t} at or before ${r}`);let o=Ei(n,r),s=(a)=>{let u=o.get(a);return u?.value==null?void 0:JSON.parse(u.value)};return{id:t,database_id:s("database_id")??null,name:s("name")??"",type:s("type")??"text",config:s("config")??null,position:s("position")??null,deleted:o.get("__deleted")?Wt(o.get("__deleted").value):!1,version:n[n.length-1].hlc}}var Ug=ze(function(t,r,n){let o=t.query("SELECT database_id, name, type, config, position, __deleted FROM properties WHERE id = ?").get(r);if(!o)throw new Z("not_found",`no such property: ${r}`);let s=Hv(t,r,n);if(s.deleted)throw new Z("invalid_input","target version is a deleted state; use prop remove instead");let a={name:o.name,type:o.type,config:o.config?JSON.parse(o.config):null,position:o.position},u={name:s.name,type:s.type,config:s.config,position:s.position},_=[];for(let ge of Mg)if(JSON.stringify(u[ge]??null)!==JSON.stringify(a[ge]??null))be(t,"properties",r,ge,u[ge]),_.push(ge);let m=o.__deleted!==0;if(m)be(t,"properties",r,"__deleted",0);let x=new Set(t.query("SELECT DISTINCT txn FROM crdt_changes WHERE dataset = 'properties' AND row_id = ? AND hlc > ? AND txn IS NOT NULL").all(r,n).map((ge)=>ge.txn)),D=t.query("SELECT row_id, hlc, value, txn FROM crdt_changes WHERE dataset = 'records' AND col = ? ORDER BY row_id, hlc").all(r),j=(ge)=>ge!==null&&(x.has(ge)||Vr(ge).kind==="repair"),Y=0,_e=0,de=0;while(de<D.length){let ge=D[de].row_id,Le=D[de],Ze=null;for(;de<D.length&&D[de].row_id===ge;de++)if(Le=D[de],!j(Le.txn))Ze=Le;if(Le.hlc<=n)continue;if(!j(Le.txn)){_e++;continue}let $e=Ze?Ze.value:null;if($e===Le.value)continue;be(t,"records",ge,r,$e===null?void 0:JSON.parse($e)),Y++}return{id:r,changed:_.length>0||m||Y>0,fields:_,restored_cells:Y,skipped_cells:_e,undeleted:m,restored:s.version}},"revert");function jg(e,t,r){return e.query("SELECT hlc, node_id, value FROM crdt_changes WHERE dataset = 'records' AND row_id = ? AND col = ? ORDER BY hlc DESC").all(t,r).map((o)=>({version:o.hlc,at:Tn(o.hlc),node_id:o.node_id,value:o.value===null?void 0:JSON.parse(o.value),cleared:o.value===null}))}dt();Ye();var Wv={databases:{tier:"content",synced:!0},properties:{tier:"content",synced:!0},records:{tier:"content",synced:!0},documents:{tier:"content",synced:!0},doc_blocks:{tier:"content",synced:!0},sites:{tier:"content",synced:!0},site_files:{tier:"content",synced:!0},site_channels:{tier:"system",synced:!0},blob_policy:{tier:"system",synced:!0},nodes:{tier:"system",synced:!0},meta:{tier:"local",synced:!1},crdt_changes:{tier:"local",synced:!1},peers:{tier:"local",synced:!1},storage_cursors:{tier:"local",synced:!1},room_rows:{tier:"local",synced:!1},peer_grants:{tier:"local",synced:!1},pairing_codes:{tier:"local",synced:!1},shares:{tier:"local",synced:!1},site_channel_observations:{tier:"local",synced:!1},blob_cache:{tier:"local",synced:!1},drop_rejects:{tier:"local",synced:!1},search_fts:{tier:"local",synced:!1}},Ti=(e)=>Object.entries(Wv).filter(([,t])=>e(t)).map(([t])=>t),nD=Ti((e)=>e.synced),oD=Ti((e)=>e.tier==="content"),Hg=Ti((e)=>e.tier==="system"),iD=Ti((e)=>e.tier==="local");function Wg(e,t){if(e==="records")return Gi.has(t);return t==="created_hlc"||t==="__deleted"}function Zg(){let e=[...Eo,...Hg];return{sql:e.map(()=>"dataset != ?"),params:e}}function ec(e,t,r){let n=Zg(),o=["txn = ?",...n.sql],s=[t,...n.params];if(r)o.push("hlc < ?"),s.push(r);return e.query(`SELECT ${It} FROM crdt_changes WHERE ${o.join(" AND ")} ORDER BY hlc`).all(...s)}function Gg(e,t,r){if(!t)return null;if(!r.dbNames.has(t)){let n=e.query("SELECT name FROM databases WHERE id = ?").get(t);r.dbNames.set(t,n?.name??null)}return r.dbNames.get(t)}function Zv(e,t,r){if(!r.titleProps.has(t)){let n=e.query("SELECT id FROM properties WHERE database_id = ? AND type = 'text' AND __deleted = 0 ORDER BY position LIMIT 1").get(t);r.titleProps.set(t,n?.id??null)}return r.titleProps.get(t)??null}function Gv(e,t,r,n){if(t==="records"){let o=e.query("SELECT database_id, data FROM records WHERE id = ?").get(r);if(!o)return{label:null,database_id:null};let s=o.database_id?Zv(e,o.database_id,n):null,a=JSON.parse(o.data||"{}");return{label:s&&a[s]!=null?String(a[s]):null,database_id:o.database_id}}if(t==="documents"){let o=e.query("SELECT title, database_id FROM documents WHERE id = ?").get(r);return{label:o?.title??null,database_id:o?.database_id??null}}if(t==="properties"){let o=e.query("SELECT name, database_id FROM properties WHERE id = ?").get(r);return{label:o?.name??null,database_id:o?.database_id??null}}if(t==="databases")return{label:Gg(e,r,n),database_id:r};if(t==="sites"){let o=e.query("SELECT title, name FROM sites WHERE id = ?").get(r);return{label:o?.title??o?.name??null,database_id:null}}return{label:null,database_id:null}}function Kg(e,t,r){for(let s of t)if(s.dataset==="doc_blocks"&&s.row_id===r&&s.col==="doc_id"&&s.value)return JSON.parse(s.value);let n=e.query("SELECT doc_id FROM doc_blocks WHERE id = ?").get(r);if(n?.doc_id)return n.doc_id;let o=e.query("SELECT value FROM crdt_changes WHERE dataset = 'doc_blocks' AND row_id = ? AND col = 'doc_id' AND value IS NOT NULL ORDER BY hlc DESC LIMIT 1").get(r);return o?JSON.parse(o.value):null}function Vg(e,t,r){let n=new Map,o=(m,x)=>{let D=m+"\x00"+x,j=n.get(D);if(!j)j={dataset:m,id:x,created:!1,deleted:!1,fields:new Set,blocksChanged:new Set,blocksDeleted:new Set},n.set(D,j);return j};for(let m of t){if(m.dataset==="doc_blocks"){let D=Kg(e,t,m.row_id),j=D?o("documents",D):o("doc_blocks",m.row_id);if(m.col==="__deleted"&&Wt(m.value))j.blocksDeleted.add(m.row_id);else j.blocksChanged.add(m.row_id);continue}let x=o(m.dataset,m.row_id);if(m.col==="created_hlc"||m.dataset==="properties"&&m.col==="database_id")x.created=!0;else if(m.col==="__deleted")x.deleted=Wt(m.value);if(!Wg(m.dataset,m.col))x.fields.add(m.col)}let s=[...n.values()].map((m)=>{let{label:x,database_id:D}=Gv(e,m.dataset,m.id,r);return{dataset:m.dataset,id:m.id,label:x,database_id:D,database_label:m.dataset==="databases"?null:Gg(e,D,r),created:m.created,deleted:m.deleted,fields:m.fields.size,blocks_changed:[...m.blocksChanged].filter((j)=>!m.blocksDeleted.has(j)).length,blocks_deleted:m.blocksDeleted.size}}),a=t[t.length-1],{actor:u,kind:_}=Vr(a.txn);return{version:a.hlc,at:Tn(a.hlc),node_id:a.node_id,kind:_,actor:u,txn:a.txn,changes:t.length,entities:s}}function Jg(e,t={}){let r=Math.max(1,Math.min(t.limit??50,200));if(t.actor!==void 0&&!Xc.test(t.actor))throw new Z("invalid_input",`invalid actor tag: ${t.actor}`);let n=Math.min(Math.max(r*40,800),8000),o=Zg(),s=[...o.sql],a=[...o.params];if(t.before)s.push("hlc < ?"),a.push(t.before);if(t.actor!==void 0)s.push("txn >= ?","txn < ?"),a.push(t.actor+"/",t.actor+"0");let u=e.query(`SELECT ${It} FROM crdt_changes
530
546
  ${s.length?"WHERE "+s.join(" AND "):""}
531
- ORDER BY hlc DESC LIMIT ?`).all(...a,n),_=u.length<n;u.reverse();let m=Rn(u);if(!_&&m.length>0){let ge=m[0][0].txn;if(ge!==null)m[0]=Xa(e,ge,t.before);else if(m.length>1)m=m.slice(1)}let x={dbNames:new Map,titleProps:new Map},D=m.reverse(),j=D.slice(0,r),Y=j.map((ge)=>Bg(e,ge,x)),de=(!_||D.length>r)&&j.length?j[j.length-1][0].hlc:null;return{entries:Y,next:de}}function jg(e,t,r,n,o){return e.query("SELECT value FROM crdt_changes WHERE dataset = ? AND row_id = ? AND col = ? AND hlc < ? ORDER BY hlc DESC LIMIT 1").get(t,r,n,o)??void 0}function Lv(e,t,r){if(t!=="records")return r;return e.query("SELECT name FROM properties WHERE id = ?").get(r)?.name??r}function Hg(e,t){let r=Xa(e,t);if(!r.length)throw new Z("not_found",`no change group: ${t}`);let o=Bg(e,r,{dbNames:new Map,titleProps:new Map}),s=new Map,a=new Map;for(let m of r){let x=m.dataset+"\x00"+m.row_id+"\x00"+m.col;if(!s.has(x))s.set(x,m);a.set(x,m)}let u=o.entities.map((m)=>({...m,diffs:[],block_diffs:[]})),_=new Map(u.map((m)=>[m.dataset+"\x00"+m.id,m]));for(let[m,x]of a){let D=s.get(m),j=(Y)=>{let _e={col:x.dataset==="doc_blocks"?x.row_id:x.col,label:Y},de=jg(e,x.dataset,x.row_id,x.col,D.hlc);if(de&&de.value!==null)_e.before=JSON.parse(de.value);if(x.value!==null)_e.after=JSON.parse(x.value);return _e};if(x.dataset==="doc_blocks"){if(x.col!=="text")continue;let Y=Mg(e,r,x.row_id);_.get(Y?"documents\x00"+Y:"doc_blocks\x00"+x.row_id)?.block_diffs.push(j("block"));continue}if($g(x.dataset,x.col))continue;_.get(x.dataset+"\x00"+x.row_id)?.diffs.push(j(Lv(e,x.dataset,x.col)))}return{...o,entities:u}}var Wg=Fe(function(t,r){let n=Xa(t,r);if(!n.length)throw new Z("not_found",`no change group: ${r}`);let o=new Map;for(let m of n){let x=m.dataset+"\x00"+m.row_id,D=o.get(x);if(!D)o.set(x,D=[]);D.push(m)}let s=0,a=0,u=0,_=0;for(let m of o.values()){let{dataset:x,row_id:D}=m[0],j=m[0].hlc;if(!t.query("SELECT 1 AS x FROM crdt_changes WHERE dataset = ? AND row_id = ? AND hlc < ? LIMIT 1").get(x,D,j)){if(t.query("SELECT 1 AS x FROM crdt_changes WHERE dataset = ? AND row_id = ? AND txn IS NOT ? LIMIT 1").get(x,D,r)){_++;continue}let ge=[...m].reverse().find((Le)=>Le.col==="__deleted");if(ge&&Ht(ge.value))continue;we(t,x,D,"__deleted",1),u++;continue}let _e=new Map;for(let de of m)if(!_e.has(de.col))_e.set(de.col,de);for(let[de,ge]of _e){let Le=t.query("SELECT value, txn FROM crdt_changes WHERE dataset = ? AND row_id = ? AND col = ? ORDER BY hlc DESC LIMIT 1").get(x,D,de);if(Le.txn!==r){a++;continue}let Ze=jg(t,x,D,de,ge.hlc),$e=Ze===void 0?de==="__deleted"?0:void 0:Ze.value===null?void 0:JSON.parse(Ze.value);if(($e===void 0?null:JSON.stringify($e))===Le.value)continue;we(t,x,D,de,$e),s++}}return{txn:r,changed:s>0||u>0,restored_registers:s,skipped_registers:a,removed_rows:u,skipped_rows:_}},"revert");Po();dt();var Gg="('text','url','select','multi_select','date')",Kg="1";function Qa(e,t){return e.query("SELECT value FROM meta WHERE key = ?").get(t)?.value??null}function Ya(e,t,r){e.query("INSERT INTO meta (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(t,r)}function $v(e,t){e.query("DELETE FROM search_fts WHERE kind = 'document' AND id = ?").run(t);let r=e.query("SELECT id, title, body, database_id FROM documents WHERE id = ? AND __deleted = 0").get(t);if(r)e.query("INSERT INTO search_fts (kind, id, database_id, title, body) VALUES ('document', ?, ?, ?, ?)").run(r.id,r.database_id,r.title??"",r.body??"")}function ec(e,t,...r){return e.query(`SELECT r.id AS id, r.database_id AS database_id, group_concat(je.value, ' ') AS body
547
+ ORDER BY hlc DESC LIMIT ?`).all(...a,n),_=u.length<n;u.reverse();let m=kn(u);if(!_&&m.length>0){let ge=m[0][0].txn;if(ge!==null)m[0]=ec(e,ge,t.before);else if(m.length>1)m=m.slice(1)}let x={dbNames:new Map,titleProps:new Map},D=m.reverse(),j=D.slice(0,r),Y=j.map((ge)=>Vg(e,ge,x)),de=(!_||D.length>r)&&j.length?j[j.length-1][0].hlc:null;return{entries:Y,next:de}}function Xg(e,t,r,n,o){return e.query("SELECT value FROM crdt_changes WHERE dataset = ? AND row_id = ? AND col = ? AND hlc < ? ORDER BY hlc DESC LIMIT 1").get(t,r,n,o)??void 0}function Kv(e,t,r){if(t!=="records")return r;return e.query("SELECT name FROM properties WHERE id = ?").get(r)?.name??r}function Qg(e,t){let r=ec(e,t);if(!r.length)throw new Z("not_found",`no change group: ${t}`);let o=Vg(e,r,{dbNames:new Map,titleProps:new Map}),s=new Map,a=new Map;for(let m of r){let x=m.dataset+"\x00"+m.row_id+"\x00"+m.col;if(!s.has(x))s.set(x,m);a.set(x,m)}let u=o.entities.map((m)=>({...m,diffs:[],block_diffs:[]})),_=new Map(u.map((m)=>[m.dataset+"\x00"+m.id,m]));for(let[m,x]of a){let D=s.get(m),j=(Y)=>{let _e={col:x.dataset==="doc_blocks"?x.row_id:x.col,label:Y},de=Xg(e,x.dataset,x.row_id,x.col,D.hlc);if(de&&de.value!==null)_e.before=JSON.parse(de.value);if(x.value!==null)_e.after=JSON.parse(x.value);return _e};if(x.dataset==="doc_blocks"){if(x.col!=="text")continue;let Y=Kg(e,r,x.row_id);_.get(Y?"documents\x00"+Y:"doc_blocks\x00"+x.row_id)?.block_diffs.push(j("block"));continue}if(Wg(x.dataset,x.col))continue;_.get(x.dataset+"\x00"+x.row_id)?.diffs.push(j(Kv(e,x.dataset,x.col)))}return{...o,entities:u}}var Yg=ze(function(t,r){let n=ec(t,r);if(!n.length)throw new Z("not_found",`no change group: ${r}`);let o=new Map;for(let m of n){let x=m.dataset+"\x00"+m.row_id,D=o.get(x);if(!D)o.set(x,D=[]);D.push(m)}let s=0,a=0,u=0,_=0;for(let m of o.values()){let{dataset:x,row_id:D}=m[0],j=m[0].hlc;if(!t.query("SELECT 1 AS x FROM crdt_changes WHERE dataset = ? AND row_id = ? AND hlc < ? LIMIT 1").get(x,D,j)){if(t.query("SELECT 1 AS x FROM crdt_changes WHERE dataset = ? AND row_id = ? AND txn IS NOT ? LIMIT 1").get(x,D,r)){_++;continue}let ge=[...m].reverse().find((Le)=>Le.col==="__deleted");if(ge&&Wt(ge.value))continue;be(t,x,D,"__deleted",1),u++;continue}let _e=new Map;for(let de of m)if(!_e.has(de.col))_e.set(de.col,de);for(let[de,ge]of _e){let Le=t.query("SELECT value, txn FROM crdt_changes WHERE dataset = ? AND row_id = ? AND col = ? ORDER BY hlc DESC LIMIT 1").get(x,D,de);if(Le.txn!==r){a++;continue}let Ze=Xg(t,x,D,de,ge.hlc),$e=Ze===void 0?de==="__deleted"?0:void 0:Ze.value===null?void 0:JSON.parse(Ze.value);if(($e===void 0?null:JSON.stringify($e))===Le.value)continue;be(t,x,D,de,$e),s++}}return{txn:r,changed:s>0||u>0,restored_registers:s,skipped_registers:a,removed_rows:u,skipped_rows:_}},"revert");Po();dt();var th="('text','url','select','multi_select','date')",rh="1";function tc(e,t){return e.query("SELECT value FROM meta WHERE key = ?").get(t)?.value??null}function rc(e,t,r){e.query("INSERT INTO meta (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(t,r)}function Vv(e,t){e.query("DELETE FROM search_fts WHERE kind = 'document' AND id = ?").run(t);let r=e.query("SELECT id, title, body, database_id FROM documents WHERE id = ? AND __deleted = 0").get(t);if(r)e.query("INSERT INTO search_fts (kind, id, database_id, title, body) VALUES ('document', ?, ?, ?, ?)").run(r.id,r.database_id,r.title??"",r.body??"")}function nc(e,t,...r){return e.query(`SELECT r.id AS id, r.database_id AS database_id, group_concat(je.value, ' ') AS body
532
548
  FROM records r, json_each(r.data) je
533
549
  JOIN properties p ON p.id = je.key AND p.__deleted = 0
534
- WHERE ${t} AND r.__deleted = 0 AND p.type IN ${Gg}
535
- GROUP BY r.id`).all(...r)}function tc(e,t){e.query("INSERT INTO search_fts (kind, id, database_id, title, body) VALUES ('record', ?, ?, ?, ?)").run(t.id,t.database_id,t.id,t.body??"")}function zv(e,t){e.query("DELETE FROM search_fts WHERE kind = 'record' AND id = ?").run(t);let r=ec(e,"r.id = ?",t)[0];if(r)tc(e,r)}function Fv(e,t){e.query("DELETE FROM search_fts WHERE kind = 'record' AND database_id = ?").run(t);for(let r of ec(e,"r.database_id = ?",t))tc(e,r)}function Mv(e){e.query("DELETE FROM search_fts").run();for(let r of e.query("SELECT id, title, body, database_id FROM documents WHERE __deleted = 0").all())e.query("INSERT INTO search_fts (kind, id, database_id, title, body) VALUES ('document', ?, ?, ?, ?)").run(r.id,r.database_id,r.title??"",r.body??"");for(let r of ec(e,"1 = 1"))tc(e,r);let t=e.query("SELECT MAX(rowid) AS m FROM crdt_changes").get().m??0;Ya(e,"search_seq",String(t)),Ya(e,"search_index_version",Kg)}function Bv(e){let t=Number(Qa(e,"search_seq")??"0"),{changes:r,cursor:n}=br(e,t);if(r.length===0)return;let o=new Set,s=new Set,a=new Set;for(let u of r)switch(u.dataset){case"documents":o.add(u.row_id);break;case"doc_blocks":{let _=e.query("SELECT doc_id FROM doc_blocks WHERE id = ?").get(u.row_id);if(_?.doc_id)o.add(_.doc_id);break}case"records":s.add(u.row_id);break;case"properties":if(u.col==="type"||u.col==="__deleted"||u.col==="database_id"){let _=e.query("SELECT database_id FROM properties WHERE id = ?").get(u.row_id);if(_?.database_id)a.add(_.database_id)}break}for(let u of o)$v(e,u);for(let u of a)Fv(e,u);for(let u of s){let _=e.query("SELECT database_id FROM records WHERE id = ?").get(u);if(_?.database_id&&a.has(_.database_id))continue;zv(e,u)}Ya(e,"search_seq",String(n))}function Uv(e){if(!$l(e))return!1;let t=Qa(e,"search_index_version"),r=Qa(e,"search_seq");return e.transaction(()=>{if(t!==Kg||r===null)Mv(e);else Bv(e)})(),!0}function jv(e,t,r){let n=t.split(/\s+/).filter(Boolean).map((s)=>`"${s.replace(/"/g,'""')}"`).join(" ");if(!n)return[];return e.query("SELECT kind, id, database_id, title, snippet(search_fts, -1, '[', ']', '…', 10) AS snippet FROM search_fts WHERE search_fts MATCH ? ORDER BY rank LIMIT ?").all(n,r).map((s)=>({type:s.kind,id:s.id,database_id:s.database_id,title:s.title||void 0,snippet:s.snippet}))}function Zg(e,t){let r=e.toLowerCase().indexOf(t.toLowerCase());if(r<0)return e.slice(0,80);let n=Math.max(0,r-30);return`${n>0?"…":""}${e.slice(n,r+t.length+50)}…`}function Hv(e,t,r){let n=`%${t.replace(/[%_\\]/g,"\\$&")}%`,o=[],s=e.query("SELECT id, title, body, database_id FROM documents WHERE __deleted = 0 AND (title LIKE ? ESCAPE '\\' OR body LIKE ? ESCAPE '\\') LIMIT ?").all(n,n,r);for(let a of s)o.push({type:"document",id:a.id,database_id:a.database_id,title:a.title??void 0,snippet:Zg(a.body||a.title||"",t)});if(o.length<r){let a=e.query(`SELECT r.id AS id, r.database_id AS database_id, group_concat(je.value, ' ') AS body
550
+ WHERE ${t} AND r.__deleted = 0 AND p.type IN ${th}
551
+ GROUP BY r.id`).all(...r)}function oc(e,t){e.query("INSERT INTO search_fts (kind, id, database_id, title, body) VALUES ('record', ?, ?, ?, ?)").run(t.id,t.database_id,t.id,t.body??"")}function Jv(e,t){e.query("DELETE FROM search_fts WHERE kind = 'record' AND id = ?").run(t);let r=nc(e,"r.id = ?",t)[0];if(r)oc(e,r)}function Xv(e,t){e.query("DELETE FROM search_fts WHERE kind = 'record' AND database_id = ?").run(t);for(let r of nc(e,"r.database_id = ?",t))oc(e,r)}function Qv(e){e.query("DELETE FROM search_fts").run();for(let r of e.query("SELECT id, title, body, database_id FROM documents WHERE __deleted = 0").all())e.query("INSERT INTO search_fts (kind, id, database_id, title, body) VALUES ('document', ?, ?, ?, ?)").run(r.id,r.database_id,r.title??"",r.body??"");for(let r of nc(e,"1 = 1"))oc(e,r);let t=e.query("SELECT MAX(rowid) AS m FROM crdt_changes").get().m??0;rc(e,"search_seq",String(t)),rc(e,"search_index_version",rh)}function Yv(e){let t=Number(tc(e,"search_seq")??"0"),{changes:r,cursor:n}=br(e,t);if(r.length===0)return;let o=new Set,s=new Set,a=new Set;for(let u of r)switch(u.dataset){case"documents":o.add(u.row_id);break;case"doc_blocks":{let _=e.query("SELECT doc_id FROM doc_blocks WHERE id = ?").get(u.row_id);if(_?.doc_id)o.add(_.doc_id);break}case"records":s.add(u.row_id);break;case"properties":if(u.col==="type"||u.col==="__deleted"||u.col==="database_id"){let _=e.query("SELECT database_id FROM properties WHERE id = ?").get(u.row_id);if(_?.database_id)a.add(_.database_id)}break}for(let u of o)Vv(e,u);for(let u of a)Xv(e,u);for(let u of s){let _=e.query("SELECT database_id FROM records WHERE id = ?").get(u);if(_?.database_id&&a.has(_.database_id))continue;Jv(e,u)}rc(e,"search_seq",String(n))}function eE(e){if(!jl(e))return!1;let t=tc(e,"search_index_version"),r=tc(e,"search_seq");return e.transaction(()=>{if(t!==rh||r===null)Qv(e);else Yv(e)})(),!0}function tE(e,t,r){let n=t.split(/\s+/).filter(Boolean).map((s)=>`"${s.replace(/"/g,'""')}"`).join(" ");if(!n)return[];return e.query("SELECT kind, id, database_id, title, snippet(search_fts, -1, '[', ']', '…', 10) AS snippet FROM search_fts WHERE search_fts MATCH ? ORDER BY rank LIMIT ?").all(n,r).map((s)=>({type:s.kind,id:s.id,database_id:s.database_id,title:s.title||void 0,snippet:s.snippet}))}function eh(e,t){let r=e.toLowerCase().indexOf(t.toLowerCase());if(r<0)return e.slice(0,80);let n=Math.max(0,r-30);return`${n>0?"…":""}${e.slice(n,r+t.length+50)}…`}function rE(e,t,r){let n=`%${t.replace(/[%_\\]/g,"\\$&")}%`,o=[],s=e.query("SELECT id, title, body, database_id FROM documents WHERE __deleted = 0 AND (title LIKE ? ESCAPE '\\' OR body LIKE ? ESCAPE '\\') LIMIT ?").all(n,n,r);for(let a of s)o.push({type:"document",id:a.id,database_id:a.database_id,title:a.title??void 0,snippet:eh(a.body||a.title||"",t)});if(o.length<r){let a=e.query(`SELECT r.id AS id, r.database_id AS database_id, group_concat(je.value, ' ') AS body
536
552
  FROM records r, json_each(r.data) je
537
553
  JOIN properties p ON p.id = je.key AND p.__deleted = 0
538
- WHERE r.__deleted = 0 AND p.type IN ${Gg}
539
- GROUP BY r.id HAVING body LIKE ? ESCAPE '\\' LIMIT ?`).all(n,r-o.length);for(let u of a)o.push({type:"record",id:u.id,database_id:u.database_id,snippet:Zg(u.body||"",t)})}return o}function Vg(e,t,r={}){let n=r.limit??20;if(Uv(e))try{let o=jv(e,t,n);if(o.length)return o}catch{}return Hv(e,t,n)}En();co();Wr();vn();mi();Ye();function Zv(e){if(e===401)return"auth";if(e===404)return"not_found";if(e===429)return"rate_limited";return"network"}function ki(e,t,r=fetch){let n=e.replace(/\/+$/,"");async function o(a,u={},_=!0){let m;try{m=await r(n+a,{...u,signal:u.signal??AbortSignal.timeout(15000),headers:{...u.body!=null?{"content-type":"application/json"}:{},..._?{authorization:`Bearer ${t}`}:{},...u.headers}})}catch(D){throw new Z("network",`inbox host unreachable: ${D.message}`)}let x=await m.json().catch(()=>null);if(!m.ok)throw new Z(Zv(m.status),`inbox host: ${x?.error??`HTTP ${m.status}`}`);return x}let s=(a)=>`/v1/inbox/${encodeURIComponent(a)}`;return{async register(a,u){await o(s(a),{method:"PUT",body:JSON.stringify(u)})},async unregister(a){return(await o(s(a),{method:"DELETE"})).deleted},async listEnvelopes(a,u,_){return(await o(`${s(a)}/envelopes?after_id=${u}&limit=${_}`)).rows},async ackEnvelopes(a,u){if(u.length===0)return 0;return(await o(`${s(a)}/envelopes`,{method:"DELETE",body:JSON.stringify({ids:u})})).deleted},async stats(a){return o(`${s(a)}/stats`)},async health(){return o("/health",{},!1)},async ownerHealth(){return o("/owner/health")}}}Ye();async function Jg(e,t,r){let n;try{let u=new URL(e.trim());if(u.protocol!=="https:"&&u.hostname!=="localhost")throw Error(`${r==="edge"?"Edge":"Inbox"} endpoint must use HTTPS`);n=u.toString().replace(/\/+$/,"")}catch(u){throw new Z("invalid_input",u.message||"invalid Edge endpoint")}let o=t.trim();if(!o)throw new Z("invalid_input","owner token is required");let s=ki(n,o),a=r==="edge"?await s.ownerHealth():await s.health();if(!a.ok)throw new Z("network",`${r==="edge"?"Edge":"Inbox host"} at ${n} is not healthy`);if(r==="edge"&&a.version!==Tr)throw new Z("conflict",`Edge version ${a.version??"unknown"} is incompatible; expected ${Tr}`);return{endpoint:n,token:o,version:a.version,capabilities:r==="edge"?["inbox","room"]:["inbox"]}}var sc=15000,ch=2000,ar=self.location.origin,xe=null,Wt={state:"booting",paired:!1,node:null};function Ai(e){self.postMessage(e)}function hr(e){Wt={...Wt,...e},Ai({event:"status",status:Wt})}function gt(){if(!xe)throw new Z("network","本地副本未就绪");return xe}var cc=null,uh=null;function dh(){let e=new cc.OpfsSAHPoolDb("/metahub.db");uh=e;let t=new zi(e);ls(t),xe=t}var Qv=(async()=>{cc=await(await Ic()).installOpfsSAHPoolVfs({name:"metahub-replica"}),dh();let t=xe,r=We(t),n=Et(t,ar)?.token!=null,o=Di(t);if(o)Oi();hr({state:"ready",node:r,paired:n,bucketDirty:o})})().catch((e)=>{throw hr({state:"error",error:e instanceof Error?e.message:String(e)}),e}),Jr=null,lh=new Set;function Yv(e){if(Et(e,ar)?.token!=null)return!0;return jt(e).some((t)=>t.enabled===1&&(t.kind==="s3"||t.kind==="room"))}function kr(e){return jt(e).filter((t)=>t.enabled===1&&t.kind==="s3")}function eE(e){return jt(e).filter((t)=>t.enabled===1&&t.kind==="room")}async function lc(e,t){let r=await Za(t).catch(()=>{return});if(r)return new Uint8Array(r.bytes);for(let n of kr(gt())){if(!n.config)continue;let o=await ua(JSON.parse(n.config),t).catch(()=>null);if(o&&await Wa(o,t))return new Uint8Array(o)}return null}N_(lc);Al(lc);function Di(e){let t=We(e);return kr(e).some((r)=>br(e,r.push_cursor,{onlyNode:t}).changes.length>0)}var tE=25,fh=1e4,An=null;function Oi(){if(An)return;An=setTimeout(()=>{if(An=null,navigator.onLine!==!1)Xr(!0)},fh)}function ac(){if(!An)return;clearTimeout(An),An=null}function rE(){let e=xe;if(!e)return;let t=kr(e).length>0&&Di(e);if(hr({bucketDirty:t,bucketError:void 0}),t)Oi();else ac()}function nE(e,t){e.query(`UPDATE peers SET
554
+ WHERE r.__deleted = 0 AND p.type IN ${th}
555
+ GROUP BY r.id HAVING body LIKE ? ESCAPE '\\' LIMIT ?`).all(n,r-o.length);for(let u of a)o.push({type:"record",id:u.id,database_id:u.database_id,snippet:eh(u.body||"",t)})}return o}function nh(e,t,r={}){let n=r.limit??20;if(eE(e))try{let o=tE(e,t,n);if(o.length)return o}catch{}return rE(e,t,n)}vn();ao();Wr();wn();mi();Ye();function oE(e){if(e===401)return"auth";if(e===404)return"not_found";if(e===429)return"rate_limited";return"network"}function Ri(e,t,r=fetch){let n=e.replace(/\/+$/,"");async function o(a,u={},_=!0){let m;try{m=await r(n+a,{...u,signal:u.signal??AbortSignal.timeout(15000),headers:{...u.body!=null?{"content-type":"application/json"}:{},..._?{authorization:`Bearer ${t}`}:{},...u.headers}})}catch(D){throw new Z("network",`inbox host unreachable: ${D.message}`)}let x=await m.json().catch(()=>null);if(!m.ok)throw new Z(oE(m.status),`inbox host: ${x?.error??`HTTP ${m.status}`}`);return x}let s=(a)=>`/v1/inbox/${encodeURIComponent(a)}`;return{async register(a,u){await o(s(a),{method:"PUT",body:JSON.stringify(u)})},async unregister(a){return(await o(s(a),{method:"DELETE"})).deleted},async listEnvelopes(a,u,_){return(await o(`${s(a)}/envelopes?after_id=${u}&limit=${_}`)).rows},async ackEnvelopes(a,u){if(u.length===0)return 0;return(await o(`${s(a)}/envelopes`,{method:"DELETE",body:JSON.stringify({ids:u})})).deleted},async stats(a){return o(`${s(a)}/stats`)},async health(){return o("/health",{},!1)},async ownerHealth(){return o("/owner/health")}}}Ye();async function oh(e,t,r){let n;try{let u=new URL(e.trim());if(u.protocol!=="https:"&&u.hostname!=="localhost")throw Error(`${r==="edge"?"Edge":"Inbox"} endpoint must use HTTPS`);n=u.toString().replace(/\/+$/,"")}catch(u){throw new Z("invalid_input",u.message||"invalid Edge endpoint")}let o=t.trim();if(!o)throw new Z("invalid_input","owner token is required");let s=Ri(n,o),a=r==="edge"?await s.ownerHealth():await s.health();if(!a.ok)throw new Z("network",`${r==="edge"?"Edge":"Inbox host"} at ${n} is not healthy`);if(r==="edge"&&a.version!==Tr)throw new Z("conflict",`Edge version ${a.version??"unknown"} is incompatible; expected ${Tr}`);return{endpoint:n,token:o,version:a.version,capabilities:r==="edge"?["inbox","room"]:["inbox"]}}var lc=15000,hh=2000,lr=self.location.origin,xe=null,Lt={state:"booting",paired:!1,node:null};function Di(e){self.postMessage(e)}function tr(e){Lt={...Lt,...e},Di({event:"status",status:Lt})}function Et(){if(!xe)throw new Z("network","本地副本未就绪");return xe}var dc=null,yh=null;function bh(){let e=new dc.OpfsSAHPoolDb("/metahub.db");yh=e;let t=new zi(e);fs(t),xe=t;let r=uE();Uc(t,{app:"web",platform:r,form:"browser",defaultLabel:dE(r)})}function uE(){let e=self.navigator,t=(e.userAgentData?.platform??e.platform??"").toLowerCase(),r=(e.userAgent??"").toLowerCase();if(t.includes("iphone")||t.includes("ipad")||/iphone|ipad/.test(r))return"ios";if(t.includes("android")||r.includes("android"))return"android";if(t.includes("mac"))return"macos";if(t.includes("win"))return"windows";if(t.includes("linux")||t.includes("cros"))return"linux";return"web"}function dE(e){let t=self.navigator?.userAgent??"",r=/edg\//i.test(t)?"Edge":/firefox\//i.test(t)?"Firefox":/chrome\//i.test(t)?"Chrome":/safari\//i.test(t)?"Safari":"浏览器",n={macos:"macOS",windows:"Windows",linux:"Linux",ios:"iOS",android:"Android",web:""}[e??"web"]??"";return n?`${r} · ${n}`:r}var fE=(async()=>{dc=await(await Cc()).installOpfsSAHPoolVfs({name:"metahub-replica"}),bh();let t=xe,r=je(t),n=vt(t,lr)?.token!=null,o=Oi(t);if(o)Ii();tr({state:"ready",node:r,paired:n,bucketDirty:o})})().catch((e)=>{throw tr({state:"error",error:e instanceof Error?e.message:String(e)}),e}),Jr=null,mh=new Set;function pE(e){if(vt(e,lr)?.token!=null)return!0;return Ht(e).some((t)=>t.enabled===1&&(t.kind==="s3"||t.kind==="room"))}function kr(e){return Ht(e).filter((t)=>t.enabled===1&&t.kind==="s3")}function _E(e){return Ht(e).filter((t)=>t.enabled===1&&t.kind==="room")}async function fc(e,t){let r=await Va(t).catch(()=>{return});if(r)return new Uint8Array(r.bytes);for(let n of kr(Et())){if(!n.config)continue;let o=await pa(JSON.parse(n.config),t).catch(()=>null);if(o&&await Ka(o,t))return new Uint8Array(o)}return null}B_(fc);ql(fc);function Oi(e){let t=je(e);return kr(e).some((r)=>br(e,r.push_cursor,{onlyNode:t}).changes.length>0)}var gE=25,wh=1e4,Rn=null;function Ii(){if(Rn)return;Rn=setTimeout(()=>{if(Rn=null,navigator.onLine!==!1)Xr(!0)},wh)}function uc(){if(!Rn)return;clearTimeout(Rn),Rn=null}function hE(){let e=xe;if(!e)return;let t=kr(e).length>0&&Oi(e);if(tr({bucketDirty:t,bucketError:void 0}),t)Ii();else uc()}function mE(e,t){e.query(`UPDATE peers SET
540
556
  pull_cursor = ?,
541
557
  push_cursor = ?,
542
558
  token = ?,
@@ -549,4 +565,4 @@ if(L instanceof ArrayBuffer)L=new Uint8Array(L);else if(L instanceof Function)re
549
565
  last_error = ?,
550
566
  kind = ?,
551
567
  config = ?
552
- WHERE url = ?`).run(t.pull_cursor,t.push_cursor,t.token,t.label,t.node_id,t.enabled,t.last_sync_at,t.last_success_at,t.last_status,t.last_error,t.kind,t.config,t.url)}async function oE(e){let t=kr(e);if(!t.length)return;let r;try{r=await Eg()}catch{return}for(let n of r){let o=!1;for(let s of t){if(!s.config)continue;try{await a_(JSON.parse(s.config),n.hash,new Uint8Array(n.bytes)),o=!0;break}catch{}}if(o)await Tg(n.hash,n.bytes,n.content_type).catch(()=>{}),await Sg(n.hash).catch(()=>{})}}async function Xr(e=!1){if(!xe)return{pushed:0,pulled:0,ok:!0};let t=xe;if(!Yv(t))return{pushed:0,pulled:0,ok:!0};if(Jr)return Jr;return Jr=(async()=>{let r=t.query("SELECT MAX(rowid) AS m FROM crdt_changes").get().m??0,n=0,o=0,s=[],a=[],u=kr(t).length>0;if(u&&e)hr({bucketSyncing:!0,bucketError:void 0});let _=!1;if(Et(t,ar)?.token!=null)try{let D=0;for(;;){let j=Et(t,ar)?.pull_cursor??0,Y=await ii(t,ar,{pullLimit:ch});if(n+=Y.pushed,o+=Y.pulled,D+=Y.received??Y.pulled,(Y.received??Y.pulled)<ch)break;if((Et(t,ar)?.pull_cursor??0)===j)break;hr({state:"hydrating",hydrated:D})}_=!0}catch(D){s.push(`server: ${D instanceof Error?D.message:String(D)}`)}for(let D of kr(t)){let j=_&&!e&&lh.has(D.url),Y=await $a(t,D.url,{storage:{minPushChanges:tE,maxPushAgeMs:fh,forcePush:e,pull:!j}});if(Y.ok){if(n+=Y.pushed??0,o+=Y.pulled??0,!j)lh.add(D.url)}else{let _e=`${D.label??D.url}: ${Y.error}`;s.push(_e),a.push(_e)}}for(let D of eE(t)){let j=await $a(t,D.url);if(j.ok)n+=j.pushed??0,o+=j.pulled??0;else s.push(`${D.label??D.url}: ${j.error}`)}if(!_&&u)await oE(t);await xn(t);let m=u?Di(t):!1;if(m&&a.length===0)Oi();else ac();let x=t.query("SELECT DISTINCT dataset, row_id FROM crdt_changes WHERE rowid > ?").all(r);if(hr({state:"ready",hydrated:void 0,lastSync:{at:Date.now(),ok:s.length===0,pushed:n,pulled:o,error:s.join("; ")||void 0},bucketDirty:m,bucketSyncing:!1,bucketError:a.join("; ")||void 0}),x.length||n)Ai({event:"synced",datasets:[...new Set(x.map((D)=>D.dataset))],rowIds:x.map((D)=>D.row_id),pushed:n,pulled:o});return{pushed:n,pulled:o,ok:s.length===0}})().finally(()=>{if(xe&&kr(xe).length>0&&!Wt.bucketSyncing)if(Di(xe)&&!Wt.bucketError)Oi();else ac();Jr=null}),Jr}var iE=150000,_o=sc,sE=180000;function aE(){if(!xe)return!1;if(Et(xe,ar)?.token!=null)return!1;return jt(xe).some((e)=>e.enabled===1&&(e.kind==="s3"||e.kind==="room"))}async function ph(){try{if(navigator.onLine!==!1&&aE()){let e=await Xr();_o=e.pushed>0||e.pulled>0?sc:Math.min(_o*2,iE)}else _o=sc}finally{setTimeout(ph,_o)}}setTimeout(ph,_o);async function cE(e){let t=gt(),r={code:e,node_id:We(t),grant:bt(32)},n=await fetch(new URL(Bp,ar),{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(r)});if(!n.ok)throw new Z(n.status===401||n.status===403?"auth":"network",`pairing failed: ${n.status} ${await n.text()}`);let o=await n.json();return ug(t,{url:ar,token:o.grant,node_id:o.node_id,label:"server"}),hr({paired:!0}),Xr(),{node_id:o.node_id}}function lE(){let e=vt(gt(),ar);return hr({paired:!1}),{ok:e}}var _h={status:()=>Wt,pair:(e)=>cE(e),unpair:()=>lE(),sync:()=>Xr(!0).then(()=>Wt.lastSync),addStorageReplica:async(e,t)=>{let r=gt(),n={publish:!0,priority:10,...e};if(n.encrypt)n.masterKey=await pa(Bt(n),n,t)??void 0;let o=gn(n.endpoint,n.bucket,n.prefix);if(Jr)await Jr;let s=Et(r,o);if(dg(r,{url:o,config:n,label:n.bucket}),await Xr(!0),Wt.bucketError){if(s)nE(r,s);else vt(r,o);throw new Z("network",`storage peer first sync failed: ${Wt.bucketError}`)}return{url:o,lastSync:Wt.lastSync}},removeStorageReplica:(e)=>({ok:vt(gt(),e)}),storagePeerConfig:(e)=>{let t=Et(xe,e);return t?.config?JSON.parse(t.config):null},dataMap:()=>_g(gt()),listStoragePeers:()=>jt(xe).filter((e)=>e.kind==="s3").map((e)=>({url:e.url,label:e.label,enabled:e.enabled===1,status:e.last_status,error:e.last_error,lastSyncAt:e.last_success_at,lastAttemptAt:e.last_sync_at})),edgeStatus:async()=>{let e=gt(),t=Ti(e),r=jt(e).filter((n)=>n.kind==="room"&&n.config).map((n)=>{let o=JSON.parse(n.config);return{slug:o.slug,url:Zr(o),status:n.last_status,lastSuccessAt:n.last_success_at,error:n.last_error}});if(!t)return{configured:!1,expectedVersion:Tr,aligned:!1,reachable:!1,managed:!1,rooms:r,defaults:null,pending:null};try{let n=await ki(t.endpoint,t.token).ownerHealth();return{configured:!0,endpoint:t.endpoint,capabilities:fo(t),version:n.version??null,expectedVersion:Tr,aligned:n.version===Tr,reachable:n.ok,managed:!1,rooms:r,defaults:null,pending:null}}catch(n){return{configured:!0,endpoint:t.endpoint,capabilities:fo(t),version:null,expectedVersion:Tr,aligned:!1,reachable:!1,error:n.message,managed:!1,rooms:r,defaults:null,pending:null}}},connectEdge:async(e,t)=>{let r=await Jg(e,t,"edge");return nc(gt(),{endpoint:r.endpoint,token:r.token,capabilities:r.capabilities,deployedVersion:r.version}),{...await _h.edgeStatus(),status:"connected",wired:[],warnings:[]}},disconnectEdge:()=>{let e=gt();if(jt(e).some((t)=>t.kind==="room"))throw new Z("conflict","请先撤销所有 Edge Room 再断开");return nc(e,null),{ok:!0}},listLocalShares:(e)=>{let t=gt();return(e?ya(t,e):ma(t)).map((n)=>{let o=Et(t,`room://${n.slug}`),s=o?.config?JSON.parse(o.config):null,a=s?.lifecycle??"active",u=s&&a==="active"?Zr(s):void 0,_=n.kind==="site"?Gr(t,n.target_id):null;return{slug:n.slug,kind:n.kind,target_id:n.target_id,title:_?.title||_?.name||n.target_id,permission:n.permission,transport:"server",source:s?a==="cleanup_pending"?"Edge Room(撤销待确认)":"Edge Room":"本机",sourceKind:s?"room":"server",hosting:s?"room":"server",...s?{lifecycle:a}:{},expiresAt:n.expires_at,hasPassword:!!n.pw_hash,url:u}})},createLocalShare:async(e)=>{let t=gt();if(e.kind!=="site"||e.hosting!=="room")throw new Z("invalid_input","此设备不驻留在线托管,目前仅支持通过 Edge 发布站点");let r=Ti(t);if(!r)throw new Z("invalid_input","请先连接 Edge");if(!fo(r).includes("room"))throw new Z("conflict","当前 Edge 仅支持 inbox,不支持 Room 托管");let n=Gr(t,e.ref),o=e.password?await ba(e.password):null,s=ha(t,{kind:"site",target_id:n.id,permission:e.permission,pwSalt:o?.salt,pwHash:o?.hash,expiresAt:e.expiresMs!=null?Date.now()+e.expiresMs:null,grants:e.grants,requestId:e.requestId});try{let a=await $_(t,s,r,lc),u=ao(t,{siteId:n.id,audience:"link",hosting:"edge",targetRef:s.slug,canonicalUrl:a.url,policy:{permission:s.permission,hasPassword:!!s.pw_hash,expiresAt:s.expires_at}});return Rt(t,{channelId:u.id,status:"ready",lastVerifiedAt:Date.now()}),{slug:s.slug,kind:"site",permission:s.permission,transport:"server",hosting:"room",url:a.url,expiresAt:s.expires_at,source:"Edge Room"}}catch(a){if(await oo(t,s.slug)!=="cleanup_pending")Qt(t,s.slug);throw a}},revokeLocalShare:async(e)=>{let t=gt();if(!or(t,e))return{ok:!1,status:"not_found"};let r=Ut(t).filter((s)=>s.audience==="link"&&s.target_ref===e&&s.desired_state==="active");for(let s of r)gr(t,s.id,"revoked");if(await oo(t,e)==="cleanup_pending"){for(let s of r)Rt(t,{channelId:s.id,status:"cleanup_pending",lastError:"Edge 尚未确认销毁 Room"});return{ok:!1,status:"cleanup_pending"}}let o=Qt(t,e);for(let s of r)Rt(t,{channelId:s.id,status:"revoked",lastVerifiedAt:Date.now()});return{ok:o,status:"revoked"}},renewLocalShare:async(e,t)=>{let r=gt();await Promise.resolve().then(() => ah());return sh(r,e,void 0,t)},listDatabases:()=>sl(xe),createDatabase:(e)=>Vi(xe,e),updateDatabase:(e,t)=>ol(xe,e,t),duplicateDatabase:(e,t)=>il(xe,e,t??{}),deleteDatabase:(e)=>({ok:al(xe,e)}),listDatabaseActivity:(e,t)=>Ig(xe,e,{limit:t}),listAuditEntries:(e)=>Ug(xe,e??{}),auditEntryDetail:(e)=>Hg(xe,e),revertChangeGroup:(e)=>Wg(xe,e),listProperties:(e)=>Nt(xe,e),addProperty:(e,t)=>xo(xe,e,t),updateProperty:(e,t)=>Ki(xe,e,t),setPropertyWidth:(e,t)=>Jc(xe,e,t),removeProperty:(e)=>({ok:el(xe,e)}),renameSelectOption:(e,t,r)=>Qc(xe,e,t,r),removeSelectOption:(e,t)=>Yc(xe,e,t),listPropertyRevisions:(e)=>Ng(xe,e),revertProperty:(e,t)=>qg(xe,e,t),listRecords:(e,t)=>un(xe,e,t??{}),createRecord:(e,t)=>To(xe,e,t),getRecord:(e)=>{let t=vr(xe,e);if(!t)throw new Z("not_found",`no such record: ${e}`);return t},updateRecord:(e,t)=>ko(xe,e,t),moveRecord:(e,t,r)=>hl(xe,e,t,r),deleteRecord:(e)=>({ok:ml(xe,e)}),listRecordRevisions:(e)=>Og(xe,e),recordAtVersion:(e,t)=>Ja(xe,e,t),recordFieldHistory:(e,t)=>Lg(xe,e,t),revertRecord:(e,t)=>Pg(xe,e,t),listDocuments:(e)=>wl(xe,e??{}),createDocument:(e)=>is(xe,e),getDocument:(e)=>{let t=nt(xe,e);if(!t)throw new Z("not_found",`no such document: ${e}`);return{...t,version:Tt(xe,t.id)}},updateDocument:(e,t,r)=>{let n=Oo(xe,e,t,{ifMatch:r});return{...n,version:Tt(xe,n.id)}},duplicateDocument:(e,t)=>{let r=Tl(xe,e,{title:t?.title,parentId:t?.parent_id});return{...r,version:Tt(xe,r.id)}},moveDocument:(e,t,r)=>as(xe,e,t,r),listDocumentRevisions:(e)=>Rg(xe,e),documentAtVersion:(e,t)=>Va(xe,e,t),revertDocument:(e,t,r)=>Ag(xe,e,t,{ifMatch:r}),deleteDocument:(e)=>({ok:kl(xe,e)}),siteFile:async(e,t)=>{if((Wt.lastSync?.at?Date.now()-Wt.lastSync.at:1/0)>sE)await Xr(!0).catch(()=>{});let n=xe,o;try{o=Gr(n,e)}catch{return null}let s=j_(n,o.id,t,{spa:o.spa===1});if(!s)return null;return{...s.row,status:s.status,public:ig(n,o).serving}},blobBytes:async(e)=>{let t=await Za(e).catch(()=>{return});if(t)return t.bytes;for(let r of kr(xe)){if(!r.config)continue;try{let n=await ua(JSON.parse(r.config),e);if(n&&await Wa(n,e))return new Uint8Array(n).buffer}catch{}}return null},blobRefs:()=>[...Pl(xe)],listSites:()=>{let e=Y_(xe);return U_(xe).map((t)=>({...t,file_count:e.get(t.id)??0}))},listSiteFiles:(e)=>H_(xe,e),createSite:(e)=>{if(e.visibility==="public")throw new Z("invalid_input","此浏览器通过同步存储桶交换数据、不驻留在线;请在在线主节点管理公开发布");return{...G_(xe,e),file_count:0}},updateSite:(e,t)=>{if(t.visibility==="public")throw new Z("invalid_input","此浏览器通过同步存储桶交换数据、不驻留在线;请在在线主节点管理公开发布");return{...rg(xe,e,t),file_count:eg(xe,e)}},deleteSite:async(e)=>{let t=ng(xe,e);return await xn(xe),{ok:t}},getSiteGrants:(e)=>({grants:_r(Gr(xe,e).public_grants)}),setSiteGrants:(e,t)=>{let r=Gr(xe,e),n=K_(xe,r.id,t.tables.length?t:null);return tg(xe,r.id,_r(n.public_grants)),{grants:_r(n.public_grants)}},siteHosting:()=>({publicBaseUrl:null,scope:null,node:We(xe),pendingRollbacks:[],publishedSites:[],channels:qa(xe)}),revokeSiteChannel:async(e)=>{let t=gt(),{needsReconcile:r}=gg(t,e);if(r)await xn(t);let n=qa(t).find((o)=>o.id===e);if(!n)throw new Z("not_found",`no such site channel: ${e}`);return n},putSiteFile:(e,t,r,n)=>{let{content:o,...s}=X_(xe,e,t,{data:r,contentType:n});return{...s,size:W_(xe,{encoding:s.encoding,content:o})}},deleteSiteFile:(e,t)=>({ok:Q_(xe,e,t)}),reset:async()=>{try{uh?.close()}catch{}return xe=null,await cc?.wipeFiles(),dh(),hr({state:"ready",paired:!1,node:We(gt()),hydrated:void 0,lastSync:void 0}),{ok:!0}},nodes:()=>qc(xe),setNodeLabel:(e)=>(Nc(gt(),e),{node_id:We(gt()),label:on(gt()),self:!0}),search:(e,t)=>Vg(xe,e,{limit:t})},uE=/^(create|update|delete|move|duplicate|revert|add|remove|set|put)/,Ri=null;function dE(){if(Ri)clearTimeout(Ri);Ri=setTimeout(()=>{if(Ri=null,navigator.onLine!==!1)Xr()},800)}self.onmessage=async(e)=>{let{id:t,op:r,args:n}=e.data;try{await Qv;let o=_h[r];if(!o)throw new Z("invalid_input",`unknown op: ${r}`);let s=await o(...n??[]);if(Ai({id:t,ok:!0,result:s}),uE.test(r))rE(),dE()}catch(o){let s=o instanceof Error?o.message:String(o),a=ln(o)??void 0;Ai({id:t,ok:!1,error:{message:s,code:a}})}};
568
+ WHERE url = ?`).run(t.pull_cursor,t.push_cursor,t.token,t.label,t.node_id,t.enabled,t.last_sync_at,t.last_success_at,t.last_status,t.last_error,t.kind,t.config,t.url)}async function yE(e){let t=kr(e);if(!t.length)return;let r;try{r=await Dg()}catch{return}for(let n of r){let o=!1;for(let s of t){if(!s.config)continue;try{await __(JSON.parse(s.config),n.hash,new Uint8Array(n.bytes)),o=!0;break}catch{}}if(o)await Pg(n.hash,n.bytes,n.content_type).catch(()=>{}),await Og(n.hash).catch(()=>{})}}async function Xr(e=!1){if(!xe)return{pushed:0,pulled:0,ok:!0};let t=xe;if(!pE(t))return{pushed:0,pulled:0,ok:!0};if(Jr)return Jr;return Jr=(async()=>{tr({syncing:!0});let r=t.query("SELECT MAX(rowid) AS m FROM crdt_changes").get().m??0,n=0,o=0,s=[],a=[],u=kr(t).length>0;if(u&&e)tr({bucketSyncing:!0,bucketError:void 0});let _=!1;if(vt(t,lr)?.token!=null)try{let D=0;for(;;){let j=vt(t,lr)?.pull_cursor??0,Y=await ii(t,lr,{pullLimit:hh});if(n+=Y.pushed,o+=Y.pulled,D+=Y.received??Y.pulled,(Y.received??Y.pulled)<hh)break;if((vt(t,lr)?.pull_cursor??0)===j)break;tr({state:"hydrating",hydrated:D})}_=!0}catch(D){s.push(`server: ${D instanceof Error?D.message:String(D)}`)}for(let D of kr(t)){let j=_&&!e&&mh.has(D.url),Y=await Ma(t,D.url,{storage:{minPushChanges:gE,maxPushAgeMs:wh,forcePush:e,pull:!j}});if(Y.ok){if(n+=Y.pushed??0,o+=Y.pulled??0,!j)mh.add(D.url)}else{let _e=`${D.label??D.url}: ${Y.error}`;s.push(_e),a.push(_e)}}for(let D of _E(t)){let j=await Ma(t,D.url);if(j.ok)n+=j.pushed??0,o+=j.pulled??0;else s.push(`${D.label??D.url}: ${j.error}`)}if(!_&&u)await yE(t);await Sn(t);let m=u?Oi(t):!1;if(m&&a.length===0)Ii();else uc();let x=t.query("SELECT DISTINCT dataset, row_id FROM crdt_changes WHERE rowid > ?").all(r);if(tr({state:"ready",hydrated:void 0,lastSync:{at:Date.now(),ok:s.length===0,pushed:n,pulled:o,error:s.join("; ")||void 0},bucketDirty:m,bucketSyncing:!1,syncing:!1,bucketError:a.join("; ")||void 0}),x.length||n)Di({event:"synced",datasets:[...new Set(x.map((D)=>D.dataset))],rowIds:x.map((D)=>D.row_id),pushed:n,pulled:o});return{pushed:n,pulled:o,ok:s.length===0}})().finally(()=>{if(Lt.syncing)tr({syncing:!1});if(xe&&kr(xe).length>0&&!Lt.bucketSyncing)if(Oi(xe)&&!Lt.bucketError)Ii();else uc();Jr=null}),Jr}var bE=150000,po=lc,wE=180000;function vE(){if(!xe)return!1;if(vt(xe,lr)?.token!=null)return!1;return Ht(xe).some((e)=>e.enabled===1&&(e.kind==="s3"||e.kind==="room"))}async function vh(){try{if(navigator.onLine!==!1&&vE()){let e=await Xr();po=e.pushed>0||e.pulled>0?lc:Math.min(po*2,bE)}else po=lc}finally{setTimeout(vh,po)}}setTimeout(vh,po);async function EE(e){let t=Et(),r={code:e,node_id:je(t),grant:yt(32)},n=await fetch(new URL(Kp,lr),{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(r)});if(!n.ok)throw new Z(n.status===401||n.status===403?"auth":"network",`pairing failed: ${n.status} ${await n.text()}`);let o=await n.json();return mg(t,{url:lr,token:o.grant,node_id:o.node_id,label:"server"}),tr({paired:!0}),Xr(),{node_id:o.node_id}}function SE(){let e=wt(Et(),lr);return tr({paired:!1}),{ok:e}}var Eh={status:()=>Lt,pair:(e)=>EE(e),unpair:()=>SE(),sync:()=>Xr(!0).then(()=>Lt.lastSync),addStorageReplica:async(e,t)=>{let r=Et(),n={publish:!0,priority:10,...e};if(n.encrypt)n.masterKey=await ha(Ut(n),n,t)??void 0;let o=_n(n.endpoint,n.bucket,n.prefix);if(Jr)await Jr;let s=vt(r,o);if(yg(r,{url:o,config:n,label:n.bucket}),await Xr(!0),Lt.bucketError){if(s)mE(r,s);else wt(r,o);throw new Z("network",`storage peer first sync failed: ${Lt.bucketError}`)}return{url:o,lastSync:Lt.lastSync}},removeStorageReplica:(e)=>({ok:wt(Et(),e)}),storagePeerConfig:(e)=>{let t=vt(xe,e);return t?.config?JSON.parse(t.config):null},dataMap:()=>vg(Et()),listStoragePeers:()=>Ht(xe).filter((e)=>e.kind==="s3").map((e)=>{let t={};try{t=e.config?JSON.parse(e.config):{}}catch{}return{url:e.url,label:e.label,enabled:e.enabled===1,status:e.last_status,error:e.last_error,lastSyncAt:e.last_success_at,lastAttemptAt:e.last_sync_at,endpoint:t.endpoint??null,bucket:t.bucket??null,region:t.region??null,provider:t.provider??null}}),edgeStatus:async()=>{let e=Et(),t=ki(e),r=Ht(e).filter((n)=>n.kind==="room"&&n.config).map((n)=>{let o=JSON.parse(n.config);return{slug:o.slug,url:Zr(o),status:n.last_status,lastSuccessAt:n.last_success_at,error:n.last_error}});if(!t)return{configured:!1,expectedVersion:Tr,aligned:!1,reachable:!1,managed:!1,rooms:r,defaults:null,pending:null};try{let n=await Ri(t.endpoint,t.token).ownerHealth();return{configured:!0,endpoint:t.endpoint,capabilities:uo(t),version:n.version??null,expectedVersion:Tr,aligned:n.version===Tr,reachable:n.ok,managed:!1,rooms:r,defaults:null,pending:null}}catch(n){return{configured:!0,endpoint:t.endpoint,capabilities:uo(t),version:null,expectedVersion:Tr,aligned:!1,reachable:!1,error:n.message,managed:!1,rooms:r,defaults:null,pending:null}}},connectEdge:async(e,t)=>{let r=await oh(e,t,"edge");return sc(Et(),{endpoint:r.endpoint,token:r.token,capabilities:r.capabilities,deployedVersion:r.version}),{...await Eh.edgeStatus(),status:"connected",wired:[],warnings:[]}},disconnectEdge:()=>{let e=Et();if(Ht(e).some((t)=>t.kind==="room"))throw new Z("conflict","请先撤销所有 Edge Room 再断开");return sc(e,null),{ok:!0}},listLocalShares:(e)=>{let t=Et();return(e?va(t,e):wa(t)).map((n)=>{let o=vt(t,`room://${n.slug}`),s=o?.config?JSON.parse(o.config):null,a=s?.lifecycle??"active",u=s&&a==="active"?Zr(s):void 0,_=n.kind==="site"?Gr(t,n.target_id):null;return{slug:n.slug,kind:n.kind,target_id:n.target_id,title:_?.title||_?.name||n.target_id,permission:n.permission,transport:"server",source:s?a==="cleanup_pending"?"Edge Room(撤销待确认)":"Edge Room":"本机",sourceKind:s?"room":"server",hosting:s?"room":"server",...s?{lifecycle:a}:{},expiresAt:n.expires_at,hasPassword:!!n.pw_hash,url:u}})},createLocalShare:async(e)=>{let t=Et();if(e.kind!=="site"||e.hosting!=="room")throw new Z("invalid_input","此设备不驻留在线托管,目前仅支持通过 Edge 发布站点");let r=ki(t);if(!r)throw new Z("invalid_input","请先连接 Edge");if(!uo(r).includes("room"))throw new Z("conflict","当前 Edge 仅支持 inbox,不支持 Room 托管");let n=Gr(t,e.ref),o=e.password?await Ea(e.password):null,s=ba(t,{kind:"site",target_id:n.id,permission:e.permission,pwSalt:o?.salt,pwHash:o?.hash,expiresAt:e.expiresMs!=null?Date.now()+e.expiresMs:null,grants:e.grants,requestId:e.requestId});try{let a=await H_(t,s,r,fc),u=so(t,{siteId:n.id,audience:"link",hosting:"edge",targetRef:s.slug,canonicalUrl:a.url,policy:{permission:s.permission,hasPassword:!!s.pw_hash,expiresAt:s.expires_at}});return Rt(t,{channelId:u.id,status:"ready",lastVerifiedAt:Date.now()}),{slug:s.slug,kind:"site",permission:s.permission,transport:"server",hosting:"room",url:a.url,expiresAt:s.expires_at,source:"Edge Room"}}catch(a){if(await no(t,s.slug)!=="cleanup_pending")Yt(t,s.slug);throw a}},revokeLocalShare:async(e)=>{let t=Et();if(!sr(t,e))return{ok:!1,status:"not_found"};let r=jt(t).filter((s)=>s.audience==="link"&&s.target_ref===e&&s.desired_state==="active");for(let s of r)mr(t,s.id,"revoked");if(await no(t,e)==="cleanup_pending"){for(let s of r)Rt(t,{channelId:s.id,status:"cleanup_pending",lastError:"Edge 尚未确认销毁 Room"});return{ok:!1,status:"cleanup_pending"}}let o=Yt(t,e);for(let s of r)Rt(t,{channelId:s.id,status:"revoked",lastVerifiedAt:Date.now()});return{ok:o,status:"revoked"}},renewLocalShare:async(e,t)=>{let r=Et();await Promise.resolve().then(() => gh());return _h(r,e,void 0,t)},listDatabases:()=>pl(xe),createDatabase:(e)=>Qi(xe,e),updateDatabase:(e,t)=>dl(xe,e,t),duplicateDatabase:(e,t)=>fl(xe,e,t??{}),deleteDatabase:(e)=>({ok:_l(xe,e)}),listDatabaseActivity:(e,t)=>Fg(xe,e,{limit:t}),listAuditEntries:(e)=>Jg(xe,e??{}),auditEntryDetail:(e)=>Qg(xe,e),revertChangeGroup:(e)=>Yg(xe,e),listProperties:(e)=>Ct(xe,e),addProperty:(e,t)=>xo(xe,e,t),updateProperty:(e,t)=>Xi(xe,e,t),setPropertyWidth:(e,t)=>nl(xe,e,t),removeProperty:(e)=>({ok:al(xe,e)}),renameSelectOption:(e,t,r)=>il(xe,e,t,r),removeSelectOption:(e,t)=>sl(xe,e,t),listPropertyRevisions:(e)=>Bg(xe,e),revertProperty:(e,t)=>Ug(xe,e,t),listRecords:(e,t)=>ln(xe,e,t??{}),createRecord:(e,t)=>To(xe,e,t),getRecord:(e)=>{let t=vr(xe,e);if(!t)throw new Z("not_found",`no such record: ${e}`);return t},updateRecord:(e,t)=>ko(xe,e,t),moveRecord:(e,t,r)=>Sl(xe,e,t,r),deleteRecord:(e)=>({ok:xl(xe,e)}),listRecordRevisions:(e)=>$g(xe,e),recordAtVersion:(e,t)=>Ya(xe,e,t),recordFieldHistory:(e,t)=>jg(xe,e,t),revertRecord:(e,t)=>zg(xe,e,t),listDocuments:(e)=>Rl(xe,e??{}),createDocument:(e)=>cs(xe,e),getDocument:(e)=>{let t=nt(xe,e);if(!t)throw new Z("not_found",`no such document: ${e}`);return{...t,version:Tt(xe,t.id)}},updateDocument:(e,t,r)=>{let n=Oo(xe,e,t,{ifMatch:r});return{...n,version:Tt(xe,n.id)}},duplicateDocument:(e,t)=>{let r=Pl(xe,e,{title:t?.title,parentId:t?.parent_id});return{...r,version:Tt(xe,r.id)}},moveDocument:(e,t,r)=>us(xe,e,t,r),listDocumentRevisions:(e)=>Cg(xe,e),documentAtVersion:(e,t)=>Qa(xe,e,t),revertDocument:(e,t,r)=>qg(xe,e,t,{ifMatch:r}),deleteDocument:(e)=>({ok:Nl(xe,e)}),siteFile:async(e,t)=>{if((Lt.lastSync?.at?Date.now()-Lt.lastSync.at:1/0)>wE)await Xr(!0).catch(()=>{});let n=xe,o;try{o=Gr(n,e)}catch{return null}let s=J_(n,o.id,t,{spa:o.spa===1});if(!s)return null;return{...s.row,status:s.status,public:fg(n,o).serving}},blobBytes:async(e)=>{let t=await Va(e).catch(()=>{return});if(t)return t.bytes;for(let r of kr(xe)){if(!r.config)continue;try{let n=await pa(JSON.parse(r.config),e);if(n&&await Ka(n,e))return new Uint8Array(n).buffer}catch{}}return null},blobRefs:()=>[...zl(xe)],listSites:()=>{let e=sg(xe);return V_(xe).map((t)=>({...t,file_count:e.get(t.id)??0}))},listSiteFiles:(e)=>X_(xe,e),createSite:(e)=>{if(e.visibility==="public")throw new Z("invalid_input","此浏览器通过同步存储桶交换数据、不驻留在线;请在在线主节点管理公开发布");return{...eg(xe,e),file_count:0}},updateSite:(e,t)=>{if(t.visibility==="public")throw new Z("invalid_input","此浏览器通过同步存储桶交换数据、不驻留在线;请在在线主节点管理公开发布");return{...lg(xe,e,t),file_count:ag(xe,e)}},deleteSite:async(e)=>{let t=ug(xe,e);return await Sn(xe),{ok:t}},getSiteGrants:(e)=>({grants:hr(Gr(xe,e).public_grants)}),setSiteGrants:(e,t)=>{let r=Gr(xe,e),n=tg(xe,r.id,t.tables.length?t:null);return cg(xe,r.id,hr(n.public_grants)),{grants:hr(n.public_grants)}},siteHosting:()=>({publicBaseUrl:null,scope:null,node:je(xe),pendingRollbacks:[],publishedSites:[],channels:Fa(xe)}),revokeSiteChannel:async(e)=>{let t=Et(),{needsReconcile:r}=Eg(t,e);if(r)await Sn(t);let n=Fa(t).find((o)=>o.id===e);if(!n)throw new Z("not_found",`no such site channel: ${e}`);return n},putSiteFile:(e,t,r,n)=>{let{content:o,...s}=og(xe,e,t,{data:r,contentType:n});return{...s,size:Q_(xe,{encoding:s.encoding,content:o})}},deleteSiteFile:(e,t)=>({ok:ig(xe,e,t)}),reset:async()=>{try{yh?.close()}catch{}return xe=null,await dc?.wipeFiles(),bh(),tr({state:"ready",paired:!1,node:je(Et()),hydrated:void 0,lastSync:void 0}),{ok:!0}},nodes:()=>Ui(xe),setNodeLabel:(e,t)=>{let r=Et(),n=t??je(r);return Bc(r,e,n),Ui(r).find((o)=>o.node_id===n)},search:(e,t)=>nh(xe,e,{limit:t})},xE=/^(create|update|delete|move|duplicate|revert|add|remove|set|put)/,Ai=null;function TE(){if(Ai)clearTimeout(Ai);Ai=setTimeout(()=>{if(Ai=null,navigator.onLine!==!1)Xr()},800)}self.onmessage=async(e)=>{let{id:t,op:r,args:n}=e.data;try{await fE;let o=Eh[r];if(!o)throw new Z("invalid_input",`unknown op: ${r}`);let s=await o(...n??[]);if(Di({id:t,ok:!0,result:s}),xE.test(r))hE(),TE()}catch(o){let s=o instanceof Error?o.message:String(o),a=cn(o)??void 0;Di({id:t,ok:!1,error:{message:s,code:a}})}};