@tensorix/metahub 0.5.4 → 0.5.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/dist/cli.js +666 -152
  2. package/dist/cli.js.map +23 -17
  3. package/dist/core/copy-views.d.ts +3 -0
  4. package/dist/core/copy-views.d.ts.map +1 -0
  5. package/dist/core/csv-columns.d.ts +6 -0
  6. package/dist/core/csv-columns.d.ts.map +1 -0
  7. package/dist/core/databases.d.ts.map +1 -1
  8. package/dist/core/sync/auth.d.ts.map +1 -1
  9. package/dist/core/sync/cf-oauth.d.ts.map +1 -1
  10. package/dist/core/sync/files.d.ts.map +1 -1
  11. package/dist/core/sync/page-messages.d.ts +5 -0
  12. package/dist/core/sync/page-messages.d.ts.map +1 -1
  13. package/dist/core/sync/remote-shares-cache.d.ts.map +1 -1
  14. package/dist/core/sync/room-serve.d.ts.map +1 -1
  15. package/dist/core/sync/share-actions.d.ts.map +1 -1
  16. package/dist/core/sync/share-copy.d.ts +1 -1
  17. package/dist/core/sync/share-copy.d.ts.map +1 -1
  18. package/dist/core/sync/share-export.d.ts +4 -2
  19. package/dist/core/sync/share-export.d.ts.map +1 -1
  20. package/dist/core/sync/share-file-styles.d.ts +2 -0
  21. package/dist/core/sync/share-file-styles.d.ts.map +1 -0
  22. package/dist/core/sync/share-link.d.ts +27 -0
  23. package/dist/core/sync/share-link.d.ts.map +1 -0
  24. package/dist/core/sync/share-serve.d.ts.map +1 -1
  25. package/dist/core/sync/share-short-links.d.ts +8 -0
  26. package/dist/core/sync/share-short-links.d.ts.map +1 -0
  27. package/dist/core/sync/sites-serve.d.ts.map +1 -1
  28. package/dist/core/ui-theme.d.ts +44 -0
  29. package/dist/core/ui-theme.d.ts.map +1 -0
  30. package/dist/db-worker.js +64 -64
  31. package/dist/edge-worker.js +137 -8
  32. package/dist/index.js +619 -128
  33. package/dist/index.js.map +20 -15
  34. package/dist/metahub-sdk.js +4 -4
  35. package/dist/mh-runtime.js +2 -2
  36. package/dist/sw.js +9 -6
  37. package/dist/webui/server/assets.d.ts.map +1 -1
  38. package/dist/webui.js +130 -130
  39. package/package.json +1 -1
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};function st(e,t){let r=e.transaction(t);return(r.immediate??r)()}var al=`
1
+ var Ae=(e,t,r)=>()=>{if(e)try{t=e(e=0)}catch(n){r=[n]}if(r)throw r[0];return t};function at(e,t){let r=e.transaction(t);return(r.immediate??r)()}var ul=`
2
2
  CREATE TABLE IF NOT EXISTS meta (
3
3
  key TEXT PRIMARY KEY,
4
4
  value TEXT
@@ -324,7 +324,7 @@ CREATE TABLE IF NOT EXISTS nodes (
324
324
  first_seen INTEGER, -- epoch ms of the device's first self-description
325
325
  __deleted INTEGER NOT NULL DEFAULT 0
326
326
  );
327
- `,cl=`
327
+ `,dl=`
328
328
  CREATE VIRTUAL TABLE IF NOT EXISTS search_fts USING fts5(
329
329
  kind UNINDEXED,
330
330
  id UNINDEXED,
@@ -332,31 +332,31 @@ CREATE VIRTUAL TABLE IF NOT EXISTS search_fts USING fts5(
332
332
  title,
333
333
  body
334
334
  );
335
- `;function vt(e=6){let t=crypto.getRandomValues(new Uint8Array(e)),r="";for(let n of t)r+="0123456789abcdefghijklmnopqrstuvwxyz".charAt(n%36);return r}function is(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 Nt(e,t,r=e){return`${e}_${is(t,r)}-${vt()}`}function cn(e){let t=e.indexOf("_");if(t<=0)return null;let r=e.slice(0,t);return Uy.has(r)?r:null}var Uy;var Et=De(()=>{Uy=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=vt(8);return e.query("INSERT INTO meta (key, value) VALUES ('node_id', ?)").run(r),r}function zn(e,t){let r=e.query(`SELECT ${ll} FROM nodes WHERE id = ? AND __deleted = 0`).get(t);return r?ul(r):null}function By(e){return e.query(`SELECT ${ll} FROM nodes WHERE __deleted = 0`).all().map(ul)}function dl(e){return e.query("SELECT value FROM meta WHERE key = 'node_label'").get()?.value??null}function jy(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 ss(e,t){let r=zn(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===We(e)?dl(e):null}function fl(e){return ss(e,We(e))}function pl(e,t,r){let n=r??We(e),o=t==null||t.trim()===""?null:t.trim(),s=zn(e,n);if(n===We(e))jy(e,o);if(s&&s.label===o)return;if(!s&&o==null)return;Xt(e,"node",()=>{_e(e,"nodes",n,"label",o)})}function hl(e,t={}){let r=We(e),n=zn(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=dl(e)??t.defaultLabel??null;if(s)o.label=s}if(Object.keys(o).length>0)Xt(e,"node",()=>{for(let[s,a]of Object.entries(o))_e(e,"nodes",r,s,a)});return zn(e,r)}function as(e){let t=We(e),r=new Set([t]);for(let s of By(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=zn(e,s);return{node_id:s,label:ss(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 ll="id, label, platform, form, app, first_seen",ul=(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 Wt=De(()=>{Et();ct()});function Hy(e,t){return t?e.replace(/\{(\w+)\}/g,(r,n)=>(n in t)?String(t[n]):r):e}function cs(e,t,r){return new Z(e,Hy(t,r),{key:t,params:r})}function Zy(e){if(!(e instanceof Error))return!1;let t=e.code;if(typeof t==="string"&&Wy.test(t))return!0;return e.message==="database is locked"}function Gy(e){if(e instanceof Z)return e;if(Zy(e))return cs("busy","数据库正被另一个进程写入,请稍后重试");return null}function ln(e){return Gy(e)?.code}var Z,Wy;var Xe=De(()=>{Z=class Z extends Error{code;i18n;constructor(e,t,r){super(t);this.code=e;this.i18n=r;this.name="MhError"}};Wy=/^SQLITE_(BUSY|LOCKED)/});function Io(e){return Co({millis:e+Lr,counter:Oo,node:"~~~~~~~~"})}function gl(e,t){return e>Io(t)}function ls(e,t){if(t<=Oo)return{millis:e,counter:t};return{millis:e+Math.floor(t/(Oo+1)),counter:t%(Oo+1)}}function Co(e){let{millis:t,counter:r}=ls(e.millis,e.counter);return`${String(t).padStart(15,"0")}-${r.toString(16).padStart(4,"0")}-${e.node}`}function Po(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 _l(e,t){let r=e.query("SELECT value FROM meta WHERE key = 'hlc'").get();return r?Po(r.value):{millis:0,counter:0,node:t}}function us(e,t){e.query("INSERT INTO meta (key, value) VALUES ('hlc', ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(Co(t))}function No(e,t,r=Date.now()){let n=_l(e,t);if(n.millis>r+Lr)throw cs("clock_skew","本机逻辑时钟比系统时间超前 {min} 分钟(系统时钟曾被调错,或收到过时钟错误设备的数据),运行 mh repair --clock 修复",{min:Math.ceil((n.millis-r)/60000)});let o=Math.max(n.millis,r),s=o===n.millis?n.counter+1:0,a={...ls(o,s),node:t};return us(e,a),Co(a)}function ml(e,t,r,n=Date.now()){let o=_l(e,t),s=Po(r);if(!Number.isFinite(s.millis)||!Number.isFinite(s.counter))return;if(s.millis>n+Lr)return;let a=Math.max(o.millis,s.millis,n),c;if(a===o.millis&&a===s.millis)c=Math.max(o.counter,s.counter)+1;else if(a===o.millis)c=o.counter+1;else if(a===s.millis)c=s.counter+1;else c=0;us(e,{...ls(a,c),node:t})}function ds(e){let t=e.query("SELECT value FROM meta WHERE key = 'hlc'").get();return t?Po(t.value):null}function yl(e,t,r=Date.now()){us(e,{millis:r,counter:0,node:t})}var Oo=65535,Lr=300000;var qo=De(()=>{Xe()});function un(e){if(!e)return[];let t=e.replace(/\r\n?/g,`
335
+ `;function Et(e=6){let t=crypto.getRandomValues(new Uint8Array(e)),r="";for(let n of t)r+="0123456789abcdefghijklmnopqrstuvwxyz".charAt(n%36);return r}function as(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 qt(e,t,r=e){return`${e}_${as(t,r)}-${Et()}`}function dn(e){let t=e.indexOf("_");if(t<=0)return null;let r=e.slice(0,t);return Yy.has(r)?r:null}var Yy;var St=Ae(()=>{Yy=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=Et(8);return e.query("INSERT INTO meta (key, value) VALUES ('node_id', ?)").run(r),r}function Bn(e,t){let r=e.query(`SELECT ${fl} FROM nodes WHERE id = ? AND __deleted = 0`).get(t);return r?pl(r):null}function eb(e){return e.query(`SELECT ${fl} FROM nodes WHERE __deleted = 0`).all().map(pl)}function hl(e){return e.query("SELECT value FROM meta WHERE key = 'node_label'").get()?.value??null}function tb(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 cs(e,t){let r=Bn(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===We(e)?hl(e):null}function gl(e){return cs(e,We(e))}function ml(e,t,r){let n=r??We(e),o=t==null||t.trim()===""?null:t.trim(),s=Bn(e,n);if(n===We(e))tb(e,o);if(s&&s.label===o)return;if(!s&&o==null)return;Qt(e,"node",()=>{me(e,"nodes",n,"label",o)})}function _l(e,t={}){let r=We(e),n=Bn(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=hl(e)??t.defaultLabel??null;if(s)o.label=s}if(Object.keys(o).length>0)Qt(e,"node",()=>{for(let[s,a]of Object.entries(o))me(e,"nodes",r,s,a)});return Bn(e,r)}function ls(e){let t=We(e),r=new Set([t]);for(let s of eb(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=Bn(e,s);return{node_id:s,label:cs(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 fl="id, label, platform, form, app, first_seen",pl=(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 Kt=Ae(()=>{St();lt()});function rb(e,t){return t?e.replace(/\{(\w+)\}/g,(r,n)=>(n in t)?String(t[n]):r):e}function us(e,t,r){return new H(e,rb(t,r),{key:t,params:r})}function ob(e){if(!(e instanceof Error))return!1;let t=e.code;if(typeof t==="string"&&nb.test(t))return!0;return e.message==="database is locked"}function ib(e){if(e instanceof H)return e;if(ob(e))return us("busy","数据库正被另一个进程写入,请稍后重试");return null}function fn(e){return ib(e)?.code}var H,nb;var Xe=Ae(()=>{H=class H extends Error{code;i18n;constructor(e,t,r){super(t);this.code=e;this.i18n=r;this.name="MhError"}};nb=/^SQLITE_(BUSY|LOCKED)/});function Po(e){return No({millis:e+$r,counter:Co,node:"~~~~~~~~"})}function yl(e,t){return e>Po(t)}function ds(e,t){if(t<=Co)return{millis:e,counter:t};return{millis:e+Math.floor(t/(Co+1)),counter:t%(Co+1)}}function No(e){let{millis:t,counter:r}=ds(e.millis,e.counter);return`${String(t).padStart(15,"0")}-${r.toString(16).padStart(4,"0")}-${e.node}`}function qo(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 bl(e,t){let r=e.query("SELECT value FROM meta WHERE key = 'hlc'").get();return r?qo(r.value):{millis:0,counter:0,node:t}}function fs(e,t){e.query("INSERT INTO meta (key, value) VALUES ('hlc', ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(No(t))}function Lo(e,t,r=Date.now()){let n=bl(e,t);if(n.millis>r+$r)throw us("clock_skew","本机逻辑时钟比系统时间超前 {min} 分钟(系统时钟曾被调错,或收到过时钟错误设备的数据),运行 mh repair --clock 修复",{min:Math.ceil((n.millis-r)/60000)});let o=Math.max(n.millis,r),s=o===n.millis?n.counter+1:0,a={...ds(o,s),node:t};return fs(e,a),No(a)}function wl(e,t,r,n=Date.now()){let o=bl(e,t),s=qo(r);if(!Number.isFinite(s.millis)||!Number.isFinite(s.counter))return;if(s.millis>n+$r)return;let a=Math.max(o.millis,s.millis,n),c;if(a===o.millis&&a===s.millis)c=Math.max(o.counter,s.counter)+1;else if(a===o.millis)c=o.counter+1;else if(a===s.millis)c=s.counter+1;else c=0;fs(e,{...ds(a,c),node:t})}function ps(e){let t=e.query("SELECT value FROM meta WHERE key = 'hlc'").get();return t?qo(t.value):null}function vl(e,t,r=Date.now()){fs(e,{millis:r,counter:0,node:t})}var Co=65535,$r=300000;var $o=Ae(()=>{Xe()});function pn(e){if(!e)return[];let t=e.replace(/\r\n?/g,`
336
336
  `).split(`
337
337
  `),r=[],n=[],o=null,s=0,a=()=>{if(n.length)r.push({text:n.join(`
338
- `),blankAfter:0}),n=[]},c=()=>{if(a(),r.length)r[r.length-1].blankAfter++};for(let p of t){if(o){n.push(p);let x=p.match(/^\s*(`{3,}|~{3,})\s*$/);if(x&&x[1][0]===o&&x[1].length>=s)a(),o=null,s=0;continue}let m=p.match(/^\s*(`{3,}|~{3,})/);if(m)a(),o=m[1][0],s=m[1].length,n.push(p);else if(p.trim()==="")c();else n.push(p)}a();for(let p=0;p<r.length-1;p++)r[p].blankAfter=Math.max(0,r[p].blankAfter-1);return r}function $r(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=[]},c=()=>{if(a(),r.length)r[r.length-1].blankAfter++};for(let p of t){if(o){n.push(p);let x=p.match(/^\s*(`{3,}|~{3,})\s*$/);if(x&&x[1][0]===o&&x[1].length>=s)a(),o=null,s=0;continue}let m=p.match(/^\s*(`{3,}|~{3,})/);if(m)a(),o=m[1][0],s=m[1].length,n.push(p);else if(p.trim()==="")c();else n.push(p)}a();for(let p=0;p<r.length-1;p++)r[p].blankAfter=Math.max(0,r[p].blankAfter-1);return r}function Mr(e){let t=e.filter((n)=>!!n.text&&n.text.length>0),r=[];return t.forEach((n,o)=>{r.push(...n.text.split(`
339
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(`
340
- `)}function bl(e,t){let r=Ky(e,t),n=new Set(r.map((c)=>c[0])),o=new Map(r.map((c)=>[c[1],c[0]])),s=t.map((c,p)=>o.has(p)?{keep:o.get(p)}:{insert:c}),a=[];for(let c=0;c<e.length;c++)if(!n.has(c))a.push(c);return{items:s,deleted:a}}function Ky(e,t){let r=e.length,n=t.length,o=Array.from({length:r+1},()=>Array(n+1).fill(0));for(let p=r-1;p>=0;p--)for(let m=n-1;m>=0;m--)o[p][m]=e[p]===t[m]?o[p+1][m+1]+1:Math.max(o[p+1][m],o[p][m+1]);let s=[],a=0,c=0;while(a<r&&c<n)if(e[a]===t[c])s.push([a,c]),a++,c++;else if(o[a+1][c]>=o[a][c+1])a++;else c++;return s}function Vy(e){let t=Bn.get(e);if(!t)t={docs:new Map,blockToDoc:new Map},Bn.set(e,t);return t}function Un(e,t){let r=e.docs.get(t);if(!r)return;e.docs.delete(t);for(let n of r.blockIds)if(e.blockToDoc.get(n)===t)e.blockToDoc.delete(n)}function wl(e,t){let r=Bn.get(e),n=r?.docs.get(t);if(!r||!n)return;return r.docs.delete(t),r.docs.set(t,n),n}function vl(e,t,r,n){let o=Vy(e);Un(o,t);let s={changes:r,blockIds:new Set(n),revisions:null,states:new Map};o.docs.set(t,s);for(let a of s.blockIds)o.blockToDoc.set(a,t);while(o.docs.size>16)Un(o,o.docs.keys().next().value);return s}function El(e,t,r){if(e.states.size>=64)e.states.delete(e.states.keys().next().value);e.states.set(t,r)}function fs(e,t,r,n,o){let s=Bn.get(e);if(!s)return;if(t==="documents"){Un(s,r);return}if(t!=="doc_blocks")return;let a=s.blockToDoc.get(r);if(a)Un(s,a);if(n==="doc_id"&&o)try{let c=JSON.parse(o);if(typeof c==="string")Un(s,c)}catch{}}function Sl(e){Bn.delete(e)}var Bn;var jn=De(()=>{Bn=new WeakMap});function Jy(e){return Math.max(0,Math.trunc(Number.isFinite(e)?e:Date.now()))}function Hn(e=Date.now()){let t=Math.max(0,Jy(e)-2678400000);return String(t).padStart(15,"0")+"-"}function Lo(e,t=Date.now()){return e.dataset==="intent_receipts"&&e.hlc<Hn(t)}function ps(e,t=Date.now()){return e.filter((r)=>!Lo(r,t))}function fn(e,t=Date.now()){return e.query("DELETE FROM crdt_changes WHERE dataset = 'intent_receipts' AND hlc < ?").run(Hn(t)).changes}var dn="intent_receipts";function Xt(e,t,r){if(Zn!==null)return r();Zn=(xl?xl+"/":"")+(t?t+":":"")+vt(8);try{return st(e,r)}finally{Zn=null}}function Fe(e,t=null){return(r,...n)=>Xt(r,t,()=>e(r,...n))}function kl(e,t,r){if(r!==null)return JSON.parse(r);return Qy.has(`${e}:${t}`)?0:null}function Tl(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 Wn(e,t,r){e.query(`INSERT OR IGNORE INTO ${t} (id) VALUES (?)`).run(r)}function Yy(e,t){return e.query("SELECT 1 AS x FROM doc_blocks WHERE doc_id = ? LIMIT 1").get(t)!=null}function eb(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);Wn(e,"documents",t),e.query("UPDATE documents SET body = ? WHERE id = ?").run($r(r.map((n)=>({text:n.text,blankAfter:n.blank_after??0}))),t)}function tb(e,t,r,n,o){if(Mo.has(t))return;if(t==="records"){if(hs.has(n)){Wn(e,"records",r);let c=kl("records",n,o);e.query(`UPDATE records SET "${n}" = ? WHERE id = ?`).run(Tl(c),r)}else if(Wn(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}if(t==="databases"&&n.startsWith("meta.")){Wn(e,"databases",r);let c=n.slice(5);if(o===null)e.query(`UPDATE databases SET meta = json_remove(coalesce(meta, '{}'), '$."' || ? || '"') WHERE id = ?`).run(c,r);else e.query(`UPDATE databases SET meta = json_set(coalesce(meta, '{}'), '$."' || ? || '"', json(?)) WHERE id = ?`).run(c,o,r);return}let s=Al[t];if(!s||!s.cols.has(n))return;if(t==="documents"&&n==="body"&&Yy(e,r))return;Wn(e,s.table,r);let a=kl(t,n,o);if(e.query(`UPDATE ${s.table} SET "${n}" = ? WHERE id = ?`).run(Tl(a),r),t==="doc_blocks"){let c=e.query("SELECT doc_id FROM doc_blocks WHERE id = ?").get(r);if(c?.doc_id)eb(e,c.doc_id)}}function Mr(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,n=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);if(r)fs(e,t.dataset,t.row_id,t.col,t.value);if(n.h!==t.hlc)return{inserted:r,winner:!1};try{tb(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 _e(e,t,r,n,o){let s=()=>{let a=Xy??We(e),c={hlc:No(e,a),node_id:a,dataset:t,row_id:r,col:n,value:o===void 0?null:JSON.stringify(o),txn:Zn};return Mr(e,c),c};return Zn!==null?s():st(e,s)}function Gn(e,t,r={}){return pn(e,t,r).received}function pn(e,t,r={}){let n=r.now??Date.now();fn(e,n);let o=We(e),s=0,a=0,c={};if(st(e,()=>{for(let m of t){if(Lo(m,n))continue;if(gl(m.hlc,n)){c[m.node_id]=(c[m.node_id]??0)+1;continue}ml(e,o,m.hlc,n);try{if(Mr(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}`)}}}),a)console.error(`[ingest] ${a} change(s) skipped this batch (see above)`);for(let[m,x]of Object.entries(c))console.error(`[ingest] refused ${x} change(s) from node ${m}: stamped more than 5 min in the future (that device should run mh repair --clock)`);return{received:s,skewed:c}}function vr(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(dn,Hn(r.now??Date.now()));let a=o.join(" AND "),c=r.limit!=null&&r.limit>0?` LIMIT ${Math.floor(r.limit)}`:"",p=e.query(`SELECT rowid AS seq, ${mt} FROM crdt_changes WHERE ${a} ORDER BY rowid${c}`).all(...s),m=r.limit==null||r.limit<=0||p.length<r.limit,x;if(m){let O=e.query("SELECT MAX(rowid) AS m FROM crdt_changes").get();x=Math.max(t,O.m??t)}else x=p[p.length-1].seq;return{changes:p.map(({seq:O,...F})=>F),cursor:x}}var $o,mt,Zn=null,xl=null,Rl,Xy=null,Al,hs,Mo,Qy;var ct=De(()=>{Wt();qo();Et();jn();$o=["hlc","node_id","dataset","row_id","col","value","txn"],mt=$o.join(", "),Rl=/^[a-z0-9_-]{1,16}$/;Al={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"])}},hs=new Set(["database_id","created_hlc","order_key","__deleted"]),Mo=new Set([dn]),Qy=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 Dl(e){return e.replace(/[^a-zA-Z0-9_]/g,"_")}function Ol(e){return e.replace(/'/g,"''")}function Il(e,t){return`idx_rec_${Dl(e)}_${Dl(t)}`}function rb(e,t,r){return e.query("SELECT 1 AS ok FROM sqlite_master WHERE type = 'index' AND name = ?").get(Il(t,r))!=null}function gs(e,t,r){let n=Il(t,r);e.exec(`CREATE INDEX IF NOT EXISTS "${n}" ON records (data ->> '${Ol(r)}', created_hlc) WHERE database_id = '${Ol(t)}' AND __deleted = 0`)}function _s(e,t,r){if(rb(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}gs(e,t,r.id)}function ms(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 ob(e,t){return(e.query("SELECT MAX(position) AS m FROM properties WHERE database_id = ? AND __deleted = 0").get(t).m??0)+1}function Er(e,t){let r=e.query(`SELECT ${Cl} FROM properties WHERE id = ? AND __deleted = 0`).get(t);if(!r)return null;return{...r,config:r.config?JSON.parse(r.config):null}}function Ft(e,t){return e.query(`SELECT ${Cl} 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 Pl(e,t,r){let n=Er(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 ys(e,t,{config:{...n.config??{},width:o}})}function Nl(e,t){let r=Er(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 Fo,nb,Cl,zo,ys,ql,Ll,$l;var Sr=De(()=>{Et();ct();Fr();Xe();Fo=new Set(["text","number","checkbox","select","multi_select","date","relation","doc","url"]),nb=["id","database_id","name","type","config","position"],Cl=nb.join(", ");zo=Fe(function(t,r,n){if(!Dt(t,r))throw new Z("not_found",`no such database: ${r}`);if(!Fo.has(n.type))throw new Z("invalid_input",`unknown property type: ${n.type}`);ms(n.type,n.config);let o=n.indexed?{...n.config??{},indexed:!0}:n.config??null,s=Nt("prop",n.name);if(_e(t,"properties",s,"database_id",r),_e(t,"properties",s,"name",n.name),_e(t,"properties",s,"type",n.type),_e(t,"properties",s,"config",o),_e(t,"properties",s,"position",n.position??ob(t,r)),n.type==="relation"||n.type==="doc"||n.indexed===!0)gs(t,r,s);return Er(t,s)});ys=Fe(function(t,r,n){let o=Er(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&&!Fo.has(n.type))throw new Z("invalid_input",`unknown property type: ${n.type}`);let a=n.type??o.type,c;if(n.config!==void 0){let p={...o.config??{}};for(let[m,x]of Object.entries(n.config))if(x===null)delete p[m];else p[m]=x;c=p,ms(a,c)}else if(s)ms(n.type,o.config??void 0);if(n.name!==void 0)_e(t,"properties",r,"name",n.name);if(n.type!==void 0)_e(t,"properties",r,"type",n.type);if(c!==void 0)_e(t,"properties",r,"config",c);if(n.position!==void 0)_e(t,"properties",r,"position",n.position);if(s){let p=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 p)_e(t,"records",m.id,r,null)}return Er(t,r)});ql=Fe(function(t,r,n,o){let{prop:s,options:a}=Nl(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}`);_e(t,"properties",r,"config",{...s.config??{},options:a.map((p)=>p===n?o:p)});let c=0;if(s.type==="select"){let p=t.query("SELECT id FROM records WHERE database_id = ? AND __deleted = 0 AND data ->> ? = ?").all(s.database_id,r,n);for(let m of p)_e(t,"records",m.id,r,o);c=p.length}else{let p=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 p){let x=JSON.parse(m.v);if(!Array.isArray(x)||!x.includes(n))continue;_e(t,"records",m.id,r,[...new Set(x.map((O)=>O===n?o:O))]),c++}}return{property:Er(t,r),renamed:c}}),Ll=Fe(function(t,r,n){let{prop:o,options:s}=Nl(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");_e(t,"properties",r,"config",{...o.config??{},options:s.filter((c)=>c!==n)});let a=0;if(o.type==="select"){let c=t.query("SELECT id FROM records WHERE database_id = ? AND __deleted = 0 AND data ->> ? = ?").all(o.database_id,r,n);for(let p of c)_e(t,"records",p.id,r,null);a=c.length}else{let c=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 p of c){let m=JSON.parse(p.v);if(!Array.isArray(m)||!m.includes(n))continue;_e(t,"records",p.id,r,m.filter((x)=>x!==n)),a++}}return{property:Er(t,r),cleared:a}}),$l=Fe(function(t,r){let n=Er(t,r);if(!n)return!1;_e(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)_e(t,"records",s.id,r,void 0);return!0})});function zl(e){if(!e)return null;let t=e.meta===null?null:JSON.parse(e.meta);return{...e,meta:t&&Object.keys(t).length?t:null}}function Ul(e,t,r,n){for(let[o,s]of Object.entries(n)){if(o.includes("."))throw new Z("invalid_input",`meta key must not contain ".": ${o}`);let a=s===void 0?null:s,c=r&&o in r?r[o]:null;if(JSON.stringify(c??null)===JSON.stringify(a??null))continue;_e(e,"databases",t,`meta.${o}`,a===null?void 0:a)}}function Dt(e,t){return zl(e.query(`SELECT ${Fl} FROM databases WHERE id = ? AND __deleted = 0`).get(t))}function Hl(e){return e.query(`SELECT ${Fl} FROM databases WHERE __deleted = 0 ORDER BY created_hlc`).all().map((r)=>zl(r))}function Ml(e,t,r,n){return e.query(`SELECT id FROM ${t} WHERE ${r} = ? AND __deleted = 0`).all(n).map((o)=>o.id)}var ib,Fl,bs,Bl,jl,Wl;var Fr=De(()=>{Et();ct();Xe();Sr();zr();ib=["id","name","icon","meta","created_hlc"],Fl=ib.join(", ");bs=Fe(function(t,r){let n=Nt("db",r.name),o=_e(t,"databases",n,"name",r.name);if(_e(t,"databases",n,"created_hlc",o.hlc),r.icon!==void 0)_e(t,"databases",n,"icon",r.icon);return Dt(t,n)}),Bl=Fe(function(t,r,n){if(!Dt(t,r))throw new Z("not_found",`no such database: ${r}`);if(n.name!==void 0)_e(t,"databases",r,"name",n.name);if(n.icon!==void 0)_e(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");let o=Dt(t,r).meta,s=n.meta??Object.fromEntries(Object.keys(o??{}).map((a)=>[a,null]));Ul(t,r,o,s)}return Dt(t,r)}),jl=Fe(function(t,r,n={}){let o=Dt(t,r);if(!o)throw new Z("not_found",`no such database: ${r}`);let s=bs(t,{name:n.name??o.name,icon:n.icon??o.icon??void 0});if(o.meta!==null){let{collapsed:x,...O}=o.meta;Ul(t,s.id,null,O)}let a=new Map,c=new Set;for(let x of Ft(t,r)){let O=x.type==="relation"&&x.config?.database===r,F=O?{...x.config,database:s.id}:x.config??void 0,X=zo(t,s.id,{name:x.name,type:x.type,config:F,position:x.position});if(a.set(x.id,X.id),O)c.add(X.id)}let p=hn(t,r),m=new Map;for(let x of p){let O={};for(let[F,X]of Object.entries(x.cells)){let he=a.get(F);if(!he)continue;if(c.has(he)&&Array.isArray(X)&&X.length>0)continue;O[he]=X}m.set(x.id,Uo(t,s.id,O).id)}for(let x of p){let O={};for(let[F,X]of Object.entries(x.cells)){let he=a.get(F);if(he&&c.has(he)&&Array.isArray(X)&&X.length>0)O[he]=X.map((be)=>m.get(String(be))??be)}if(Object.keys(O).length)Bo(t,m.get(x.id),O)}return Dt(t,s.id)});Wl=Fe(function(t,r){if(!Dt(t,r))return!1;_e(t,"databases",r,"__deleted",1);let n=(o)=>{for(let s of Ml(t,o,"database_id",r))_e(t,o,s,"__deleted",1)};n("properties"),n("records");for(let o of Ml(t,"documents","database_id",r))_e(t,"documents",o,"database_id",null);return t.query("DELETE FROM meta WHERE key = 'current_db' AND value = ?").run(r),!0})});function ab(e){return e!==null&&e!=="blk"}function ws(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 cb(e,t,r,n){let o=Gl[t],s=o.nameCol;if(t==="rec"&&n){let F=ws(e,n);if(F)s=`data ->> '${F.replace(/'/g,"''")}'`}let a=s??"''",c=[],p=[];c.push("(id >= ? AND id < ?)"),p.push(r,r+Zl);let m=`${t}_${r}`;if(c.push("(id >= ? AND id < ?)"),p.push(m,m+Zl),s)c.push(`lower(${s}) = lower(?)`),p.push(r);let x=`SELECT id, ${a} AS label FROM ${o.table} WHERE __deleted = 0 AND (${c.join(" OR ")})`;if(o.scoped&&n)x+=" AND database_id = ?",p.push(n);return e.query(x).all(...p).map((F)=>({kind:t,id:F.id,label:F.label??""}))}function jo(e,t,r={}){let n=r.kind?[r.kind]:ab(cn(t))?[cn(t)]:sb,o=[],s=new Set;for(let a of n)for(let c of cb(e,a,t,r.databaseId)){if(s.has(c.id))continue;s.add(c.id),o.push(c)}return o}function Kl(e,t,r={}){let n=t.trim();if(!n)return[];let o=Math.max(1,Math.min(r.limit??lb,100)),s=jo(e,n).filter((p)=>p.kind!=="prop");s.sort((p,m)=>Number(m.id===n)-Number(p.id===n));let a=new Map,c=[];for(let p of s.slice(0,o)){if(p.kind==="db"){c.push({...p,database_id:null});continue}let x=e.query(`SELECT database_id FROM ${Gl[p.kind].table} WHERE id = ?`).get(p.id)?.database_id??null,O=p.label;if(p.kind==="rec"&&!O&&x){if(!a.has(x))a.set(x,ws(e,x));let F=a.get(x);if(F){let X=e.query(`SELECT data ->> '${F.replace(/'/g,"''")}' AS title FROM records WHERE id = ?`).get(p.id);O=X?.title?String(X.title):""}}c.push({kind:p.kind,id:p.id,label:O,database_id:x})}return c}var Gl,sb,Zl="{",lb=20;var Ho=De(()=>{Et();Xe();Gl={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"}},sb=["db","prop","rec","doc"]});function vs(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)+vs(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]+vs(e.slice(1),null)}function Zt(e,t){return vs(e??"",t)}function pr(e,t,r){if(r<=0)return[];if(r===1)return[Zt(e,t)];if(t===null){let s=Zt(e,null),a=[s];for(let c=1;c<r;c++)s=Zt(s,null),a.push(s);return a}if(e===null){let s=Zt(null,t),a=[s];for(let c=1;c<r;c++)s=Zt(null,s),a.unshift(s);return a}let n=Math.floor(r/2),o=Zt(e,t);return[...pr(e,o,n),o,...pr(o,t,r-n-1)]}function Vl(e){return typeof e==="string"||typeof e==="number"||typeof e==="boolean"}function ub(e){return typeof e==="boolean"?e?1:0:e}function db(e,t,r){let n=t.config?.database;if(!n)return r;let o=jo(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(cn(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 fb(e,t,r){let n=jo(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(cn(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 Ss(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)=>db(e,t,String(o)));case"doc":return(r===null?[]:Array.isArray(r)?r:[r]).map((o)=>fb(e,t,String(o)))}}function pb(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 xs(e,t){let r=new Map(e.map((s)=>[s.id,s])),n=pb(e),o=[];for(let[s,a]of Object.entries(t)){let c=r.get(s);if(!c){let p=n.get(s.toLowerCase())??[];if(p.length>1)throw new Z("ambiguous",`property name "${s}" matches ${p.length} properties; use a property id`);c=p[0]}if(!c)throw new Z("not_found",`unknown property: ${s}`);o.push({prop:c,value:a})}return o}function Ql(e,t,r){return xs(Ft(e,t),r).map(({prop:n,value:o})=>({prop:n,value:Ss(e,n,o)}))}function Yl(e,t){let r=JSON.parse(e.data||"{}"),n=new Map(t.map((a)=>[a.id,a])),o={},s={};for(let[a,c]of Object.entries(r)){let p=n.get(a);if(!p)continue;o[p.name]=c,s[p.id]=c}return{id:e.id,database_id:e.database_id,values:o,cells:s}}function hb(e,t){let r=e.find((n)=>n.prop.type==="text"&&typeof n.value==="string"&&n.value);return Nt("rec",r?String(r.value):"",t)}function Jl(e,t){return e.query("SELECT 1 AS ok FROM sqlite_master WHERE type = 'table' AND name = ?").get(t)!=null}function gb(e){return Jl(e,"meta")&&Jl(e,"crdt_changes")}function _b(e,t,r,n){if(n)_e(e,"records",t,"order_key",r);else e.query("UPDATE records SET order_key = ? WHERE id = ?").run(r,t)}function eu(e,t){return e.query(`SELECT order_key FROM records
340
+ `)}function El(e,t){let r=sb(e,t),n=new Set(r.map((c)=>c[0])),o=new Map(r.map((c)=>[c[1],c[0]])),s=t.map((c,p)=>o.has(p)?{keep:o.get(p)}:{insert:c}),a=[];for(let c=0;c<e.length;c++)if(!n.has(c))a.push(c);return{items:s,deleted:a}}function sb(e,t){let r=e.length,n=t.length,o=Array.from({length:r+1},()=>Array(n+1).fill(0));for(let p=r-1;p>=0;p--)for(let m=n-1;m>=0;m--)o[p][m]=e[p]===t[m]?o[p+1][m+1]+1:Math.max(o[p+1][m],o[p][m+1]);let s=[],a=0,c=0;while(a<r&&c<n)if(e[a]===t[c])s.push([a,c]),a++,c++;else if(o[a+1][c]>=o[a][c+1])a++;else c++;return s}function ab(e){let t=Hn.get(e);if(!t)t={docs:new Map,blockToDoc:new Map},Hn.set(e,t);return t}function jn(e,t){let r=e.docs.get(t);if(!r)return;e.docs.delete(t);for(let n of r.blockIds)if(e.blockToDoc.get(n)===t)e.blockToDoc.delete(n)}function Sl(e,t){let r=Hn.get(e),n=r?.docs.get(t);if(!r||!n)return;return r.docs.delete(t),r.docs.set(t,n),n}function kl(e,t,r,n){let o=ab(e);jn(o,t);let s={changes:r,blockIds:new Set(n),revisions:null,states:new Map};o.docs.set(t,s);for(let a of s.blockIds)o.blockToDoc.set(a,t);while(o.docs.size>16)jn(o,o.docs.keys().next().value);return s}function xl(e,t,r){if(e.states.size>=64)e.states.delete(e.states.keys().next().value);e.states.set(t,r)}function hs(e,t,r,n,o){let s=Hn.get(e);if(!s)return;if(t==="documents"){jn(s,r);return}if(t!=="doc_blocks")return;let a=s.blockToDoc.get(r);if(a)jn(s,a);if(n==="doc_id"&&o)try{let c=JSON.parse(o);if(typeof c==="string")jn(s,c)}catch{}}function Tl(e){Hn.delete(e)}var Hn;var Wn=Ae(()=>{Hn=new WeakMap});function cb(e){return Math.max(0,Math.trunc(Number.isFinite(e)?e:Date.now()))}function Zn(e=Date.now()){let t=Math.max(0,cb(e)-2678400000);return String(t).padStart(15,"0")+"-"}function Mo(e,t=Date.now()){return e.dataset==="intent_receipts"&&e.hlc<Zn(t)}function gs(e,t=Date.now()){return e.filter((r)=>!Mo(r,t))}function gn(e,t=Date.now()){return e.query("DELETE FROM crdt_changes WHERE dataset = 'intent_receipts' AND hlc < ?").run(Zn(t)).changes}var hn="intent_receipts";function Qt(e,t,r){if(Gn!==null)return r();Gn=(Rl?Rl+"/":"")+(t?t+":":"")+Et(8);try{return at(e,r)}finally{Gn=null}}function Fe(e,t=null){return(r,...n)=>Qt(r,t,()=>e(r,...n))}function Al(e,t,r){if(r!==null)return JSON.parse(r);return ub.has(`${e}:${t}`)?0:null}function Dl(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 Kn(e,t,r){e.query(`INSERT OR IGNORE INTO ${t} (id) VALUES (?)`).run(r)}function db(e,t){return e.query("SELECT 1 AS x FROM doc_blocks WHERE doc_id = ? LIMIT 1").get(t)!=null}function fb(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);Kn(e,"documents",t),e.query("UPDATE documents SET body = ? WHERE id = ?").run(Mr(r.map((n)=>({text:n.text,blankAfter:n.blank_after??0}))),t)}function pb(e,t,r,n,o){if(zo.has(t))return;if(t==="records"){if(ms.has(n)){Kn(e,"records",r);let c=Al("records",n,o);e.query(`UPDATE records SET "${n}" = ? WHERE id = ?`).run(Dl(c),r)}else if(Kn(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}if(t==="databases"&&n.startsWith("meta.")){Kn(e,"databases",r);let c=n.slice(5);if(o===null)e.query(`UPDATE databases SET meta = json_remove(coalesce(meta, '{}'), '$."' || ? || '"') WHERE id = ?`).run(c,r);else e.query(`UPDATE databases SET meta = json_set(coalesce(meta, '{}'), '$."' || ? || '"', json(?)) WHERE id = ?`).run(c,o,r);return}let s=Il[t];if(!s||!s.cols.has(n))return;if(t==="documents"&&n==="body"&&db(e,r))return;Kn(e,s.table,r);let a=Al(t,n,o);if(e.query(`UPDATE ${s.table} SET "${n}" = ? WHERE id = ?`).run(Dl(a),r),t==="doc_blocks"){let c=e.query("SELECT doc_id FROM doc_blocks WHERE id = ?").get(r);if(c?.doc_id)fb(e,c.doc_id)}}function Fr(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,n=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);if(r)hs(e,t.dataset,t.row_id,t.col,t.value);if(n.h!==t.hlc)return{inserted:r,winner:!1};try{pb(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 me(e,t,r,n,o){let s=()=>{let a=lb??We(e),c={hlc:Lo(e,a),node_id:a,dataset:t,row_id:r,col:n,value:o===void 0?null:JSON.stringify(o),txn:Gn};return Fr(e,c),c};return Gn!==null?s():at(e,s)}function Vn(e,t,r={}){return mn(e,t,r).received}function mn(e,t,r={}){let n=r.now??Date.now();gn(e,n);let o=We(e),s=0,a=0,c={};if(at(e,()=>{for(let m of t){if(Mo(m,n))continue;if(yl(m.hlc,n)){c[m.node_id]=(c[m.node_id]??0)+1;continue}wl(e,o,m.hlc,n);try{if(Fr(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}`)}}}),a)console.error(`[ingest] ${a} change(s) skipped this batch (see above)`);for(let[m,x]of Object.entries(c))console.error(`[ingest] refused ${x} change(s) from node ${m}: stamped more than 5 min in the future (that device should run mh repair --clock)`);return{received:s,skewed:c}}function Er(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(hn,Zn(r.now??Date.now()));let a=o.join(" AND "),c=r.limit!=null&&r.limit>0?` LIMIT ${Math.floor(r.limit)}`:"",p=e.query(`SELECT rowid AS seq, ${_t} FROM crdt_changes WHERE ${a} ORDER BY rowid${c}`).all(...s),m=r.limit==null||r.limit<=0||p.length<r.limit,x;if(m){let A=e.query("SELECT MAX(rowid) AS m FROM crdt_changes").get();x=Math.max(t,A.m??t)}else x=p[p.length-1].seq;return{changes:p.map(({seq:A,...F})=>F),cursor:x}}var Fo,_t,Gn=null,Rl=null,Ol,lb=null,Il,ms,zo,ub;var lt=Ae(()=>{Kt();$o();St();Wn();Fo=["hlc","node_id","dataset","row_id","col","value","txn"],_t=Fo.join(", "),Ol=/^[a-z0-9_-]{1,16}$/;Il={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"])}},ms=new Set(["database_id","created_hlc","order_key","__deleted"]),zo=new Set([hn]),ub=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 Cl(e,t,r,n){if(!Array.isArray(e))return e;let o=(a)=>!!a&&typeof a==="object"&&!Array.isArray(a),s=(a)=>typeof a==="string"?t.get(a)??a:a;return e.map((a)=>{if(!o(a))return a;let c={...a};for(let p of["group","dateProp","start","end"])if(p in c)c[p]=s(c[p]);if(Array.isArray(a.hidden))c.hidden=a.hidden.map(s);if(Array.isArray(a.sort))c.sort=a.sort.map((p)=>o(p)?{...p,prop:s(p.prop)}:p);if(o(a.filter)&&Array.isArray(a.filter.rules))c.filter={...a.filter,rules:a.filter.rules.map((p)=>{if(!o(p))return p;return{...p,prop:s(p.prop),...typeof p.prop==="string"&&n.has(p.prop)&&Array.isArray(p.value)?{value:p.value.map((m)=>typeof m==="string"?r.get(m)??m:m)}:{}}})};if(o(a.calc))c.calc=Object.fromEntries(Object.entries(a.calc).map(([p,m])=>[t.get(p)??p,m]));return c})}function Pl(e){return e.replace(/[^a-zA-Z0-9_]/g,"_")}function Nl(e){return e.replace(/'/g,"''")}function ql(e,t){return`idx_rec_${Pl(e)}_${Pl(t)}`}function hb(e,t,r){return e.query("SELECT 1 AS ok FROM sqlite_master WHERE type = 'index' AND name = ?").get(ql(t,r))!=null}function _s(e,t,r){let n=ql(t,r);e.exec(`CREATE INDEX IF NOT EXISTS "${n}" ON records (data ->> '${Nl(r)}', created_hlc) WHERE database_id = '${Nl(t)}' AND __deleted = 0`)}function ys(e,t,r){if(hb(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}_s(e,t,r.id)}function bs(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 H("invalid_input",`${e} requires config.options: string[]`)}if(e==="relation"){if(typeof t?.database!=="string")throw new H("invalid_input","relation requires config.database (target database id)")}}function mb(e,t){return(e.query("SELECT MAX(position) AS m FROM properties WHERE database_id = ? AND __deleted = 0").get(t).m??0)+1}function Sr(e,t){let r=e.query(`SELECT ${Ll} FROM properties WHERE id = ? AND __deleted = 0`).get(t);if(!r)return null;return{...r,config:r.config?JSON.parse(r.config):null}}function Lt(e,t){return e.query(`SELECT ${Ll} 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 $l(e,t,r){let n=Sr(e,t);if(!n)throw new H("not_found",`no such property: ${t}`);if(!Number.isFinite(r))throw new H("invalid_input","width must be a finite number");let o=Math.max(80,Math.min(2000,Math.round(r)));return ws(e,t,{config:{...n.config??{},width:o}})}function Ml(e,t){let r=Sr(e,t);if(!r)throw new H("not_found",`no such property: ${t}`);if(r.type!=="select"&&r.type!=="multi_select")throw new H("invalid_input",`${r.type} property has no options`);return{prop:r,options:r.config?.options??[]}}var Uo,gb,Ll,Bo,ws,Fl,zl,Ul;var kr=Ae(()=>{St();lt();zr();Xe();Uo=new Set(["text","number","checkbox","select","multi_select","date","relation","doc","url"]),gb=["id","database_id","name","type","config","position"],Ll=gb.join(", ");Bo=Fe(function(t,r,n){if(!Ot(t,r))throw new H("not_found",`no such database: ${r}`);if(!Uo.has(n.type))throw new H("invalid_input",`unknown property type: ${n.type}`);bs(n.type,n.config);let o=n.indexed?{...n.config??{},indexed:!0}:n.config??null,s=qt("prop",n.name);if(me(t,"properties",s,"database_id",r),me(t,"properties",s,"name",n.name),me(t,"properties",s,"type",n.type),me(t,"properties",s,"config",o),me(t,"properties",s,"position",n.position??mb(t,r)),n.type==="relation"||n.type==="doc"||n.indexed===!0)_s(t,r,s);return Sr(t,s)});ws=Fe(function(t,r,n){let o=Sr(t,r);if(!o)throw new H("not_found",`no such property: ${r}`);let s=n.type!==void 0&&n.type!==o.type;if(n.type!==void 0&&!Uo.has(n.type))throw new H("invalid_input",`unknown property type: ${n.type}`);let a=n.type??o.type,c;if(n.config!==void 0){let p={...o.config??{}};for(let[m,x]of Object.entries(n.config))if(x===null)delete p[m];else p[m]=x;c=p,bs(a,c)}else if(s)bs(n.type,o.config??void 0);if(n.name!==void 0)me(t,"properties",r,"name",n.name);if(n.type!==void 0)me(t,"properties",r,"type",n.type);if(c!==void 0)me(t,"properties",r,"config",c);if(n.position!==void 0)me(t,"properties",r,"position",n.position);if(s){let p=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 p)me(t,"records",m.id,r,null)}return Sr(t,r)});Fl=Fe(function(t,r,n,o){let{prop:s,options:a}=Ml(t,r);if(o=o.trim(),!o)throw new H("invalid_input","option name must not be empty");if(!a.includes(n))throw new H("not_found",`no such option: ${n}`);if(o===n)return{property:s,renamed:0};if(a.includes(o))throw new H("conflict",`option already exists: ${o}`);me(t,"properties",r,"config",{...s.config??{},options:a.map((p)=>p===n?o:p)});let c=0;if(s.type==="select"){let p=t.query("SELECT id FROM records WHERE database_id = ? AND __deleted = 0 AND data ->> ? = ?").all(s.database_id,r,n);for(let m of p)me(t,"records",m.id,r,o);c=p.length}else{let p=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 p){let x=JSON.parse(m.v);if(!Array.isArray(x)||!x.includes(n))continue;me(t,"records",m.id,r,[...new Set(x.map((A)=>A===n?o:A))]),c++}}return{property:Sr(t,r),renamed:c}}),zl=Fe(function(t,r,n){let{prop:o,options:s}=Ml(t,r);if(!s.includes(n))throw new H("not_found",`no such option: ${n}`);if(s.length===1)throw new H("invalid_input","cannot remove the last option; delete the property instead");me(t,"properties",r,"config",{...o.config??{},options:s.filter((c)=>c!==n)});let a=0;if(o.type==="select"){let c=t.query("SELECT id FROM records WHERE database_id = ? AND __deleted = 0 AND data ->> ? = ?").all(o.database_id,r,n);for(let p of c)me(t,"records",p.id,r,null);a=c.length}else{let c=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 p of c){let m=JSON.parse(p.v);if(!Array.isArray(m)||!m.includes(n))continue;me(t,"records",p.id,r,m.filter((x)=>x!==n)),a++}}return{property:Sr(t,r),cleared:a}}),Ul=Fe(function(t,r){let n=Sr(t,r);if(!n)return!1;me(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)me(t,"records",s.id,r,void 0);return!0})});function Hl(e){if(!e)return null;let t=e.meta===null?null:JSON.parse(e.meta);return{...e,meta:t&&Object.keys(t).length?t:null}}function Wl(e,t,r,n){for(let[o,s]of Object.entries(n)){if(o.includes("."))throw new H("invalid_input",`meta key must not contain ".": ${o}`);let a=s===void 0?null:s,c=r&&o in r?r[o]:null;if(JSON.stringify(c??null)===JSON.stringify(a??null))continue;me(e,"databases",t,`meta.${o}`,a===null?void 0:a)}}function Ot(e,t){return Hl(e.query(`SELECT ${jl} FROM databases WHERE id = ? AND __deleted = 0`).get(t))}function Gl(e){return e.query(`SELECT ${jl} FROM databases WHERE __deleted = 0 ORDER BY created_hlc`).all().map((r)=>Hl(r))}function Bl(e,t,r,n){return e.query(`SELECT id FROM ${t} WHERE ${r} = ? AND __deleted = 0`).all(n).map((o)=>o.id)}var _b,jl,vs,Zl,Kl,Vl;var zr=Ae(()=>{St();lt();Xe();kr();Ur();_b=["id","name","icon","meta","created_hlc"],jl=_b.join(", ");vs=Fe(function(t,r){let n=qt("db",r.name),o=me(t,"databases",n,"name",r.name);if(me(t,"databases",n,"created_hlc",o.hlc),r.icon!==void 0)me(t,"databases",n,"icon",r.icon);return Ot(t,n)}),Zl=Fe(function(t,r,n){if(!Ot(t,r))throw new H("not_found",`no such database: ${r}`);if(n.name!==void 0)me(t,"databases",r,"name",n.name);if(n.icon!==void 0)me(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 H("invalid_input","meta must be a JSON object or null");let o=Ot(t,r).meta,s=n.meta??Object.fromEntries(Object.keys(o??{}).map((a)=>[a,null]));Wl(t,r,o,s)}return Ot(t,r)}),Kl=Fe(function(t,r,n={}){let o=Ot(t,r);if(!o)throw new H("not_found",`no such database: ${r}`);let s=vs(t,{name:n.name??o.name,icon:n.icon??o.icon??void 0}),a=new Map,c=new Set;for(let x of Lt(t,r)){let A=x.type==="relation"&&x.config?.database===r,F=A?{...x.config,database:s.id}:x.config??void 0,X=Bo(t,s.id,{name:x.name,type:x.type,config:F,position:x.position});if(a.set(x.id,X.id),A)c.add(X.id)}let p=_n(t,r),m=new Map;for(let x of p){let A={};for(let[F,X]of Object.entries(x.cells)){let he=a.get(F);if(!he)continue;if(c.has(he)&&Array.isArray(X)&&X.length>0)continue;A[he]=X}m.set(x.id,jo(t,s.id,A).id)}for(let x of p){let A={};for(let[F,X]of Object.entries(x.cells)){let he=a.get(F);if(he&&c.has(he)&&Array.isArray(X)&&X.length>0)A[he]=X.map((_e)=>m.get(String(_e))??_e)}if(Object.keys(A).length)Ho(t,m.get(x.id),A)}if(o.meta!==null){let{collapsed:x,...A}=o.meta;if("views"in A)A.views=Cl(A.views,a,m,new Set(Lt(t,r).filter((F)=>F.type==="relation"&&F.config?.database===r).map((F)=>F.id)));Wl(t,s.id,null,A)}return Ot(t,s.id)});Vl=Fe(function(t,r){if(!Ot(t,r))return!1;me(t,"databases",r,"__deleted",1);let n=(o)=>{for(let s of Bl(t,o,"database_id",r))me(t,o,s,"__deleted",1)};n("properties"),n("records");for(let o of Bl(t,"documents","database_id",r))me(t,"documents",o,"database_id",null);return t.query("DELETE FROM meta WHERE key = 'current_db' AND value = ?").run(r),!0})});function bb(e){return e!==null&&e!=="blk"}function Es(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 wb(e,t,r,n){let o=Xl[t],s=o.nameCol;if(t==="rec"&&n){let F=Es(e,n);if(F)s=`data ->> '${F.replace(/'/g,"''")}'`}let a=s??"''",c=[],p=[];c.push("(id >= ? AND id < ?)"),p.push(r,r+Jl);let m=`${t}_${r}`;if(c.push("(id >= ? AND id < ?)"),p.push(m,m+Jl),s)c.push(`lower(${s}) = lower(?)`),p.push(r);let x=`SELECT id, ${a} AS label FROM ${o.table} WHERE __deleted = 0 AND (${c.join(" OR ")})`;if(o.scoped&&n)x+=" AND database_id = ?",p.push(n);return e.query(x).all(...p).map((F)=>({kind:t,id:F.id,label:F.label??""}))}function Wo(e,t,r={}){let n=r.kind?[r.kind]:bb(dn(t))?[dn(t)]:yb,o=[],s=new Set;for(let a of n)for(let c of wb(e,a,t,r.databaseId)){if(s.has(c.id))continue;s.add(c.id),o.push(c)}return o}function Ql(e,t,r={}){let n=t.trim();if(!n)return[];let o=Math.max(1,Math.min(r.limit??vb,100)),s=Wo(e,n).filter((p)=>p.kind!=="prop");s.sort((p,m)=>Number(m.id===n)-Number(p.id===n));let a=new Map,c=[];for(let p of s.slice(0,o)){if(p.kind==="db"){c.push({...p,database_id:null});continue}let x=e.query(`SELECT database_id FROM ${Xl[p.kind].table} WHERE id = ?`).get(p.id)?.database_id??null,A=p.label;if(p.kind==="rec"&&!A&&x){if(!a.has(x))a.set(x,Es(e,x));let F=a.get(x);if(F){let X=e.query(`SELECT data ->> '${F.replace(/'/g,"''")}' AS title FROM records WHERE id = ?`).get(p.id);A=X?.title?String(X.title):""}}c.push({kind:p.kind,id:p.id,label:A,database_id:x})}return c}var Xl,yb,Jl="{",vb=20;var Zo=Ae(()=>{St();Xe();Xl={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"}},yb=["db","prop","rec","doc"]});function Ss(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)+Ss(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]+Ss(e.slice(1),null)}function Gt(e,t){return Ss(e??"",t)}function hr(e,t,r){if(r<=0)return[];if(r===1)return[Gt(e,t)];if(t===null){let s=Gt(e,null),a=[s];for(let c=1;c<r;c++)s=Gt(s,null),a.push(s);return a}if(e===null){let s=Gt(null,t),a=[s];for(let c=1;c<r;c++)s=Gt(null,s),a.unshift(s);return a}let n=Math.floor(r/2),o=Gt(e,t);return[...hr(e,o,n),o,...hr(o,t,r-n-1)]}function Yl(e){return typeof e==="string"||typeof e==="number"||typeof e==="boolean"}function Eb(e){return typeof e==="boolean"?e?1:0:e}function Sb(e,t,r){let n=t.config?.database;if(!n)return r;let o=Wo(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(dn(r)==="rec")return r;throw new H("not_found",`${t.name}: no such record in target database: ${r}`)}throw new H("ambiguous",`${t.name}: ambiguous relation "${r}" (${o.length} matches); use a full id`)}function kb(e,t,r){let n=Wo(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(dn(r)==="doc")return r;throw new H("not_found",`${t.name}: no such document: ${r}`)}throw new H("ambiguous",`${t.name}: ambiguous document "${r}" (${n.length} matches); use a full id`)}function xs(e,t,r){switch(t.type){case"text":case"url":case"date":{if(r===null)return null;if(typeof r!=="string")throw new H("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 H("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 H("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 H("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 H("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)=>Sb(e,t,String(o)));case"doc":return(r===null?[]:Array.isArray(r)?r:[r]).map((o)=>kb(e,t,String(o)))}}function xb(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=xb(e),o=[];for(let[s,a]of Object.entries(t)){let c=r.get(s);if(!c){let p=n.get(s.toLowerCase())??[];if(p.length>1)throw new H("ambiguous",`property name "${s}" matches ${p.length} properties; use a property id`);c=p[0]}if(!c)throw new H("not_found",`unknown property: ${s}`);o.push({prop:c,value:a})}return o}function ru(e,t,r){return Ts(Lt(e,t),r).map(({prop:n,value:o})=>({prop:n,value:xs(e,n,o)}))}function nu(e,t){let r=JSON.parse(e.data||"{}"),n=new Map(t.map((a)=>[a.id,a])),o={},s={};for(let[a,c]of Object.entries(r)){let p=n.get(a);if(!p)continue;o[p.name]=c,s[p.id]=c}return{id:e.id,database_id:e.database_id,values:o,cells:s}}function Tb(e,t){let r=e.find((n)=>n.prop.type==="text"&&typeof n.value==="string"&&n.value);return qt("rec",r?String(r.value):"",t)}function eu(e,t){return e.query("SELECT 1 AS ok FROM sqlite_master WHERE type = 'table' AND name = ?").get(t)!=null}function Rb(e){return eu(e,"meta")&&eu(e,"crdt_changes")}function Ab(e,t,r,n){if(n)me(e,"records",t,"order_key",r);else e.query("UPDATE records SET order_key = ? WHERE id = ?").run(r,t)}function ou(e,t){return e.query(`SELECT order_key FROM records
341
341
  WHERE database_id = ? AND __deleted = 0 AND order_key IS NOT NULL
342
- ORDER BY order_key DESC, id DESC LIMIT 1`).get(t)?.order_key??null}function Es(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 ks(e,t){return e.query(`SELECT id, database_id, created_hlc, order_key FROM records
343
343
  WHERE database_id = ? AND __deleted = 0
344
- ORDER BY order_key IS NULL, order_key, created_hlc, id`).all(t)}function mb(e,t){let r=Es(e,t),n=pr(null,null,r.length);r.forEach((o,s)=>{if(o.order_key!==n[s])_e(e,"records",o.id,"order_key",n[s])})}function xr(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 Yl(r,Ft(e,r.database_id))}function Xl(e){return e.replace(/'/g,"''")}function hn(e,t,r={}){let n=Ft(e,t),o=r.filter&&Object.keys(r.filter).length?xs(n,r.filter).map(({prop:le,value:Oe})=>({prop:le,value:Ss(e,le,Oe)})):[],s=o.filter((le)=>Vl(le.value)),a=o.filter((le)=>!Vl(le.value)),c,p=!1;if(r.sort){let le=r.sort;if(le.startsWith("-"))p=!0,le=le.slice(1);if(le!=="created"&&le!=="created_hlc"){let Oe=n.find((Be)=>Be.id===le);if(!Oe){let Be=n.filter((Me)=>Me.name.toLowerCase()===le.toLowerCase());if(Be.length>1)throw new Z("ambiguous",`sort field "${le}" matches ${Be.length} properties; use a property id`);Oe=Be[0]}if(!Oe)throw new Z("not_found",`unknown sort field: ${le}`);c=Oe}}for(let le of s)_s(e,t,le.prop);if(c)_s(e,t,c);let m=["database_id = ?","__deleted = 0"],x=[t];for(let le of s)m.push(`data ->> '${Xl(le.prop.id)}' = ?`),x.push(ub(le.value));let O=r.sort==null,F=c?`data ->> '${Xl(c.id)}'`:"created_hlc",X=`SELECT id, database_id, data FROM records WHERE ${m.join(" AND ")} `+(O?"ORDER BY order_key IS NULL, order_key, id":`ORDER BY ${F} ${p?"DESC":"ASC"}, id`);if(r.limit!=null&&a.length===0)X+=" LIMIT ?",x.push(r.limit);let be=e.query(X).all(...x).map((le)=>Yl(le,n));if(a.length){if(be=be.filter((le)=>a.every((Oe)=>JSON.stringify(le.cells[Oe.prop.id]??null)===JSON.stringify(Oe.value))),r.limit!=null)be=be.slice(0,r.limit)}return be}var Wo,ks,Uo,tu,Ts,Bo,ru;var zr=De(()=>{Et();ct();Fr();Sr();Ho();Xe();Wo=Fe(function(t,r){let n=gb(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 Db(e,t){let r=ks(e,t),n=hr(null,null,r.length);r.forEach((o,s)=>{if(o.order_key!==n[s])me(e,"records",o.id,"order_key",n[s])})}function xr(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 nu(r,Lt(e,r.database_id))}function tu(e){return e.replace(/'/g,"''")}function _n(e,t,r={}){let n=Lt(e,t),o=r.filter&&Object.keys(r.filter).length?Ts(n,r.filter).map(({prop:le,value:Oe})=>({prop:le,value:xs(e,le,Oe)})):[],s=o.filter((le)=>Yl(le.value)),a=o.filter((le)=>!Yl(le.value)),c,p=!1;if(r.sort){let le=r.sort;if(le.startsWith("-"))p=!0,le=le.slice(1);if(le!=="created"&&le!=="created_hlc"){let Oe=n.find((Be)=>Be.id===le);if(!Oe){let Be=n.filter((Me)=>Me.name.toLowerCase()===le.toLowerCase());if(Be.length>1)throw new H("ambiguous",`sort field "${le}" matches ${Be.length} properties; use a property id`);Oe=Be[0]}if(!Oe)throw new H("not_found",`unknown sort field: ${le}`);c=Oe}}for(let le of s)ys(e,t,le.prop);if(c)ys(e,t,c);let m=["database_id = ?","__deleted = 0"],x=[t];for(let le of s)m.push(`data ->> '${tu(le.prop.id)}' = ?`),x.push(Eb(le.value));let A=r.sort==null,F=c?`data ->> '${tu(c.id)}'`:"created_hlc",X=`SELECT id, database_id, data FROM records WHERE ${m.join(" AND ")} `+(A?"ORDER BY order_key IS NULL, order_key, id":`ORDER BY ${F} ${p?"DESC":"ASC"}, id`);if(r.limit!=null&&a.length===0)X+=" LIMIT ?",x.push(r.limit);let _e=e.query(X).all(...x).map((le)=>nu(le,n));if(a.length){if(_e=_e.filter((le)=>a.every((Oe)=>JSON.stringify(le.cells[Oe.prop.id]??null)===JSON.stringify(Oe.value))),r.limit!=null)_e=_e.slice(0,r.limit)}return _e}var Ko,Rs,jo,iu,As,Ho,su;var Ur=Ae(()=>{St();lt();zr();kr();Zo();Xe();Ko=Fe(function(t,r){let n=Rb(t),o=r?[{database_id:r}]:t.query(`SELECT DISTINCT database_id FROM records
345
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
346
346
  WHERE database_id = ? AND __deleted = 0 AND order_key IS NULL
347
- ORDER BY created_hlc, id`).all(s.database_id);if(!a.length)continue;let c=eu(t,s.database_id),p=pr(c,null,a.length);a.forEach((m,x)=>_b(t,m.id,p[x],n))}}),ks=Fe(function(t,r,n){let o=hb(n,is(r.name,"rec")),s=Zt(eu(t,r.id),null),a=_e(t,"records",o,"database_id",r.id);_e(t,"records",o,"created_hlc",a.hlc),_e(t,"records",o,"order_key",s);for(let{prop:c,value:p}of n)_e(t,"records",o,c.id,p);return xr(t,o)}),Uo=Fe(function(t,r,n){let o=Dt(t,r);if(!o)throw new Z("not_found",`no such database: ${r}`);return ks(t,o,Ql(t,o.id,n))});tu=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 xr(t,r);Wo(t,s.database_id);let c=Es(t,s.database_id).filter((O)=>O.id!==r),p=c.findIndex((O)=>O.id===n);if(p<0)throw new Z("not_found",`no such target record: ${n}`);let m=o==="before"?c[p-1]?.order_key??null:c[p].order_key,x=o==="before"?c[p].order_key:c[p+1]?.order_key??null;if(m!==null&&x!==null&&m>=x)mb(t,s.database_id),c=Es(t,s.database_id).filter((O)=>O.id!==r),p=c.findIndex((O)=>O.id===n),m=o==="before"?c[p-1]?.order_key??null:c[p].order_key,x=o==="before"?c[p].order_key:c[p+1]?.order_key??null;return _e(t,"records",r,"order_key",Zt(m,x)),xr(t,r)}),Ts=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:c}of n){let p=Object.hasOwn(s,a.id);if(!(c===void 0?!p:p&&JSON.stringify(c)===JSON.stringify(s[a.id])))_e(t,"records",r,a.id,c)}return xr(t,r)}),Bo=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 Ts(t,r,Ql(t,o.database_id,n))}),ru=Fe(function(t,r){if(!t.query("SELECT id FROM records WHERE id = ? AND __deleted = 0").get(r))return!1;return _e(t,"records",r,"__deleted",1),!0})});function gn(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 Eb(e){return Nt("blk",e.split(`
348
- `,1)[0]??"")}function Sb(e,t,r){let n=Eb(r.text);if(_e(e,"doc_blocks",n,"doc_id",t),_e(e,"doc_blocks",n,"order_key",r.order_key),r.blankAfter)_e(e,"doc_blocks",n,"blank_after",r.blankAfter);_e(e,"doc_blocks",n,"text",r.text)}function _n(e,t,r,n,o){let s=pr(n,o,r.length);r.forEach((a,c)=>Sb(e,t,{text:a.text,order_key:s[c],blankAfter:a.blankAfter}))}function mn(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=un(r?.body??"");if(n.length)_n(e,t,n,null,null)}function Rs(e,t,r){let n=gn(e,t),o=un(r),s=bl(n.map((p)=>p.text),o.map((p)=>p.text));for(let p of s.deleted)_e(e,"doc_blocks",n[p].id,"__deleted",1);let{items:a}=s,c=0;while(c<a.length){let p=a[c];if("keep"in p){let F=n[p.keep],X=o[c].blankAfter;if((F.blank_after??0)!==X)_e(e,"doc_blocks",F.id,"blank_after",X);c++;continue}let m=c;while(m<a.length&&"insert"in a[m])m++;let x=c>0?n[a[c-1].keep].order_key:null,O=m<a.length?n[a[m].keep].order_key:null;_n(e,t,o.slice(c,m),x,O),c=m}}function qt(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 c=ou(t,s.database_id),p=hr(c,null,a.length);a.forEach((m,x)=>Ab(t,m.id,p[x],n))}}),Rs=Fe(function(t,r,n){let o=Tb(n,as(r.name,"rec")),s=Gt(ou(t,r.id),null),a=me(t,"records",o,"database_id",r.id);me(t,"records",o,"created_hlc",a.hlc),me(t,"records",o,"order_key",s);for(let{prop:c,value:p}of n)me(t,"records",o,c.id,p);return xr(t,o)}),jo=Fe(function(t,r,n){let o=Ot(t,r);if(!o)throw new H("not_found",`no such database: ${r}`);return Rs(t,o,ru(t,o.id,n))});iu=Fe(function(t,r,n,o){if(o!=="before"&&o!=="after")throw new H("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 H("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 H("not_found",`no such record: ${n}`);if(s.database_id!==a.database_id)throw new H("invalid_input","cannot move a record across databases");if(r===n)return xr(t,r);Ko(t,s.database_id);let c=ks(t,s.database_id).filter((A)=>A.id!==r),p=c.findIndex((A)=>A.id===n);if(p<0)throw new H("not_found",`no such target record: ${n}`);let m=o==="before"?c[p-1]?.order_key??null:c[p].order_key,x=o==="before"?c[p].order_key:c[p+1]?.order_key??null;if(m!==null&&x!==null&&m>=x)Db(t,s.database_id),c=ks(t,s.database_id).filter((A)=>A.id!==r),p=c.findIndex((A)=>A.id===n),m=o==="before"?c[p-1]?.order_key??null:c[p].order_key,x=o==="before"?c[p].order_key:c[p+1]?.order_key??null;return me(t,"records",r,"order_key",Gt(m,x)),xr(t,r)}),As=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 H("not_found",`no such record: ${r}`);let s=JSON.parse(o.data||"{}");for(let{prop:a,value:c}of n){let p=Object.hasOwn(s,a.id);if(!(c===void 0?!p:p&&JSON.stringify(c)===JSON.stringify(s[a.id])))me(t,"records",r,a.id,c)}return xr(t,r)}),Ho=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 H("not_found",`no such record: ${r}`);return As(t,r,ru(t,o.database_id,n))}),su=Fe(function(t,r){if(!t.query("SELECT id FROM records WHERE id = ? AND __deleted = 0").get(r))return!1;return me(t,"records",r,"__deleted",1),!0})});function yn(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 Nb(e){return qt("blk",e.split(`
348
+ `,1)[0]??"")}function qb(e,t,r){let n=Nb(r.text);if(me(e,"doc_blocks",n,"doc_id",t),me(e,"doc_blocks",n,"order_key",r.order_key),r.blankAfter)me(e,"doc_blocks",n,"blank_after",r.blankAfter);me(e,"doc_blocks",n,"text",r.text)}function bn(e,t,r,n,o){let s=hr(n,o,r.length);r.forEach((a,c)=>qb(e,t,{text:a.text,order_key:s[c],blankAfter:a.blankAfter}))}function wn(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=pn(r?.body??"");if(n.length)bn(e,t,n,null,null)}function Ds(e,t,r){let n=yn(e,t),o=pn(r),s=El(n.map((p)=>p.text),o.map((p)=>p.text));for(let p of s.deleted)me(e,"doc_blocks",n[p].id,"__deleted",1);let{items:a}=s,c=0;while(c<a.length){let p=a[c];if("keep"in p){let F=n[p.keep],X=o[c].blankAfter;if((F.blank_after??0)!==X)me(e,"doc_blocks",F.id,"blank_after",X);c++;continue}let m=c;while(m<a.length&&"insert"in a[m])m++;let x=c>0?n[a[c-1].keep].order_key:null,A=m<a.length?n[a[m].keep].order_key:null;bn(e,t,o.slice(c,m),x,A),c=m}}function $t(e,t){return e.query(`SELECT MAX(hlc) AS h FROM crdt_changes
349
349
  WHERE (dataset = 'documents' AND row_id = ?)
350
- OR (dataset = 'doc_blocks' AND row_id IN (SELECT id FROM doc_blocks WHERE doc_id = ?))`).get(t,t).h??""}function ot(e,t){return e.query(`SELECT ${bb} FROM documents WHERE id = ? AND __deleted = 0`).get(t)}function iu(e,t={}){let r=`SELECT ${vb} FROM documents WHERE __deleted = 0`;if(t.parent_id!==void 0)return e.query(`${r} AND parent_id = ? ${Zo}`).all(t.parent_id);if(t.database_id)return e.query(`${r} AND database_id = ? ${Zo}`).all(t.database_id);return e.query(`${r} ${Zo}`).all()}function Ds(e){return e===null?{clause:"parent_id IS NULL",args:[]}:{clause:"parent_id = ?",args:[e]}}function xb(e){return nu(e,"meta")&&nu(e,"crdt_changes")}function nu(e,t){return e.query("SELECT 1 AS ok FROM sqlite_master WHERE type = 'table' AND name = ?").get(t)!=null}function su(e,t,r){let n=Ds(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 ot(e,t){return e.query(`SELECT ${Ib} FROM documents WHERE id = ? AND __deleted = 0`).get(t)}function lu(e,t={}){let r=`SELECT ${Pb} FROM documents WHERE __deleted = 0`;if(t.parent_id!==void 0)return e.query(`${r} AND parent_id = ? ${Go}`).all(t.parent_id);if(t.database_id)return e.query(`${r} AND database_id = ? ${Go}`).all(t.database_id);return e.query(`${r} ${Go}`).all()}function Is(e){return e===null?{clause:"parent_id IS NULL",args:[]}:{clause:"parent_id = ?",args:[e]}}function Lb(e){return au(e,"meta")&&au(e,"crdt_changes")}function au(e,t){return e.query("SELECT 1 AS ok FROM sqlite_master WHERE type = 'table' AND name = ?").get(t)!=null}function uu(e,t,r){let n=Is(t),o=r?" AND id <> ?":"";return e.query(`SELECT order_key FROM documents WHERE ${n.clause}${o}
351
351
  AND __deleted = 0 AND order_key IS NOT NULL
352
- ORDER BY order_key DESC, id DESC LIMIT 1`).get(...n.args,...r?[r]:[])?.order_key??null}function au(e,t){let r=Ds(t);return e.query(`SELECT id, order_key FROM documents WHERE ${r.clause} AND __deleted = 0 ${Zo}`).all(...r.args)}function kb(e,t){let r=au(e,t),n=pr(null,null,r.length);r.forEach((o,s)=>{if(o.order_key!==n[s])_e(e,"documents",o.id,"order_key",n[s])})}function cu(e,t){let r=xb(e),n=Ds(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=pr(su(e,t),null,o.length);o.forEach((a,c)=>{if(r)_e(e,"documents",a.id,"order_key",s[c]);else e.query("UPDATE documents SET order_key = ? WHERE id = ?").run(s[c],a.id)})}function Go(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=ot(e,o)?.parent_id??null}let s=ot(e,t);if(s&&(s.parent_id??null)!==r)_e(e,"documents",t,"parent_id",r);let a;if(!n)a=Zt(su(e,r,t),null);else{cu(e,r);let c=()=>{let x=au(e,r).filter((F)=>F.id!==t),O=x.findIndex((F)=>F.id===n.targetId);if(O<0)throw new Z("not_found",`no such target document: ${n.targetId}`);return n.where==="before"?[x[O-1]?.order_key??null,x[O].order_key]:[x[O].order_key,x[O+1]?.order_key??null]},[p,m]=c();if(p!==null&&m!==null&&p>=m)kb(e,r),[p,m]=c();a=Zt(p,m)}_e(e,"documents",t,"order_key",a)}function ou(e,t,r,n){return e.query(`SELECT id FROM ${t} WHERE ${r} = ? AND __deleted = 0`).all(n).map((o)=>o.id)}function fu(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 yb,bb,wb,vb,As,Zo="ORDER BY order_key IS NULL, order_key, created_hlc, id",lu,Os,uu,Ko,uk,dk,fk,pk,du;var yn=De(()=>{Et();ct();Xe();yb=["id","title","body","database_id","parent_id","created_hlc","order_key"],bb=yb.join(", "),wb=["id","title","database_id","parent_id","created_hlc","order_key"],vb=wb.join(", ");As=Fe(function(t,r){let n=Nt("doc",r.title),o=_e(t,"documents",n,"title",r.title);if(_e(t,"documents",n,"created_hlc",o.hlc),r.database_id!==void 0)_e(t,"documents",n,"database_id",r.database_id);if(r.parent_id!==void 0)_e(t,"documents",n,"parent_id",r.parent_id);if(Go(t,n,r.parent_id??null),r.body!==void 0){let s=un(r.body);if(s.length)_n(t,n,s,null,null)}return ot(t,n)});lu=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)cu(t,n.parent_id)});Os=Fe(function(t,r,n,o){let s=ot(t,r);if(!s)throw new Z("not_found",`no such document: ${r}`);if(r===n)return s;let a=ot(t,n);if(!a)throw new Z("not_found",`no such target document: ${n}`);if(o==="into")Go(t,r,n);else Go(t,r,a.parent_id,{targetId:n,where:o});return ot(t,r)}),uu=Fe(function(t,r,n={}){let o=ot(t,r);if(!o)throw new Z("not_found",`no such document: ${r}`);mn(t,r);let s=gn(t,r),a=n.parentId!==void 0?n.parentId:o.parent_id,c=As(t,{title:n.title??o.title,database_id:o.database_id??void 0,parent_id:a??void 0});if(s.length)_n(t,c.id,s.map((p)=>({text:p.text,blankAfter:p.blank_after})),null,null);if(a===o.parent_id)Os(t,c.id,o.id,"after");return ot(t,c.id)}),Ko=Fe(function(t,r,n,o={}){let s=ot(t,r);if(!s)throw new Z("not_found",`no such document: ${r}`);if(o.ifMatch!==void 0&&qt(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??""))_e(t,"documents",r,"title",n.title);if(n.database_id!==void 0&&n.database_id!==(s.database_id??null))_e(t,"documents",r,"database_id",n.database_id);if(n.parent_id!==void 0){let a=n.parent_id??null;if((ot(t,r).parent_id??null)!==a)Go(t,r,a)}if(n.body!==void 0)mn(t,r),Rs(t,r,n.body);return ot(t,r)}),uk=Fe(function(t,r,n){if(!ot(t,r))throw new Z("not_found",`no such document: ${r}`);if(n.ifMatch!==void 0&&qt(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");mn(t,r);let o=gn(t,r),s=$r(o.map((p)=>({text:p.text,blankAfter:p.blank_after}))),a=fu(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`);let c=n.replaceAll?s.replaceAll(n.old,()=>n.new):s.replace(n.old,()=>n.new);return Rs(t,r,c),{id:r,changed:c!==s,replaced:n.replaceAll?a:1,version:qt(t,r)}}),dk=Fe(function(t,r,n){if(!ot(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&&qt(t,r)!==n.ifMatch)throw new Z("stale",`stale: document changed since ${n.ifMatch}; re-read first`);mn(t,r);let o=$r(gn(t,r).map((c)=>({text:c.text,blankAfter:c.blank_after}))),s=o,a=0;if(n.edits.forEach((c,p)=>{if(c.old==="")throw new Z("invalid_input",`edit[${p}]: old must not be empty`);let m=fu(s,c.old);if(m===0)throw new Z("invalid_input",`edit[${p}]: anchor not found: no match for old`);if(m>1&&!c.replaceAll)throw new Z("ambiguous",`edit[${p}]: ${m} matches for old; add surrounding context or set replaceAll`);let x=c.new??"";s=c.replaceAll?s.replaceAll(c.old,()=>x):s.replace(c.old,()=>x),a+=c.replaceAll?m:1}),s!==o)Rs(t,r,s);return{id:r,changed:s!==o,replaced:a,version:qt(t,r)}}),fk=Fe(function(t,r,n){if(!ot(t,r))throw new Z("not_found",`no such document: ${r}`);mn(t,r);let o=un(n);if(o.length){let s=gn(t,r),a=s.length?s[s.length-1].order_key:null;_n(t,r,o,a,null)}return{id:r,changed:o.length>0,replaced:o.length,version:qt(t,r)}}),pk=Fe(function(t,r,n){if(!ot(t,r))throw new Z("not_found",`no such document: ${r}`);mn(t,r);let o=un(n);if(o.length){let s=gn(t,r),a=s.length?s[0].order_key:null;_n(t,r,o,null,a)}return{id:r,changed:o.length>0,replaced:o.length,version:qt(t,r)}}),du=Fe(function(t,r){if(!ot(t,r))return!1;_e(t,"documents",r,"__deleted",1);for(let n of ou(t,"doc_blocks","doc_id",r))_e(t,"doc_blocks",n,"__deleted",1);for(let n of ou(t,"documents","parent_id",r))_e(t,"documents",n,"parent_id",null);return!0})});function pu(e){Vo=e}function hu(e,t){return Vo?Vo(e,t):Promise.resolve(null)}function gu(){return Vo!==null}function Kn(e){let t=e.query("SELECT full_nodes, redundancy FROM blob_policy WHERE id = ? AND __deleted = 0").get(Is),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 Tb(e){e.query("UPDATE blob_cache SET anchored = 0").run(),e.query("DELETE FROM meta WHERE key = ?").run(Rb)}function Db(e){if(!e)return[];let t=[];for(let r of e.matchAll(Ab))t.push(r[1]);return t}function mu(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 Db(o.text))t.add(s);return t}function yu(e){return e.query("SELECT hash, size FROM blob_cache WHERE pending = 1").all()}function bu(e,t){return e.query("SELECT content_type FROM blob_cache WHERE hash = ?").get(t)?.content_type??null}var Is="default",Vo=null,_u=(e,t)=>{Xt(e,null,()=>{let r=new Set,n=t.filter((s)=>s&&!r.has(s)&&r.add(s)!=null);if(_e(e,"blob_policy",Is,"full_nodes",n),Kn(e).redundancy==null)_e(e,"blob_policy",Is,"redundancy","all")}),Tb(e)},Rb="blob_verified_at",Ab;var Vn=De(()=>{ct();Wt();Ab=/\/blob\/([0-9a-f]{16,64})/g});function wu(e){try{let t=new URL(e),r=t.port&&t.port!==Ob[t.protocol]?`:${t.port}`:"";return t.hostname+r}catch{return e.trim().replace(/^[a-z]+:\/\//i,"").replace(/\/.*$/,"").replace(/:(80|443)$/,"")}}function bn(e,t,r){let n=r?.trim()||"metahub";return`s3://${wu(e)}/${t}/${n}`}var Ob;var Jn=De(()=>{Ob={"https:":"443","http:":"80"}});function Ib(e){e.exec(al);try{e.exec(cl)}catch{}}function vu(e){return e.query("SELECT 1 AS ok FROM sqlite_master WHERE name = 'search_fts'").get()!=null}function yt(e,t,r){return e.query(`PRAGMA table_info(${t})`).all().some((o)=>o.name===r)}function Ur(e,t){return e.query("SELECT 1 AS ok FROM sqlite_master WHERE type = 'table' AND name = ?").get(t)!=null}function Cb(e){if(!yt(e,"records","data"))e.exec("ALTER TABLE records ADD COLUMN data TEXT NOT NULL DEFAULT '{}'");if(!yt(e,"records","order_key"))e.exec("ALTER TABLE records ADD COLUMN order_key TEXT");if(!Ur(e,"record_values"))return;st(e,()=>{e.exec(`
352
+ ORDER BY order_key DESC, id DESC LIMIT 1`).get(...n.args,...r?[r]:[])?.order_key??null}function du(e,t){let r=Is(t);return e.query(`SELECT id, order_key FROM documents WHERE ${r.clause} AND __deleted = 0 ${Go}`).all(...r.args)}function $b(e,t){let r=du(e,t),n=hr(null,null,r.length);r.forEach((o,s)=>{if(o.order_key!==n[s])me(e,"documents",o.id,"order_key",n[s])})}function fu(e,t){let r=Lb(e),n=Is(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=hr(uu(e,t),null,o.length);o.forEach((a,c)=>{if(r)me(e,"documents",a.id,"order_key",s[c]);else e.query("UPDATE documents SET order_key = ? WHERE id = ?").run(s[c],a.id)})}function Vo(e,t,r,n){let o=r;while(o){if(o===t)throw new H("invalid_input",`cannot set parent_id: would create a cycle (${t})`);o=ot(e,o)?.parent_id??null}let s=ot(e,t);if(s&&(s.parent_id??null)!==r)me(e,"documents",t,"parent_id",r);let a;if(!n)a=Gt(uu(e,r,t),null);else{fu(e,r);let c=()=>{let x=du(e,r).filter((F)=>F.id!==t),A=x.findIndex((F)=>F.id===n.targetId);if(A<0)throw new H("not_found",`no such target document: ${n.targetId}`);return n.where==="before"?[x[A-1]?.order_key??null,x[A].order_key]:[x[A].order_key,x[A+1]?.order_key??null]},[p,m]=c();if(p!==null&&m!==null&&p>=m)$b(e,r),[p,m]=c();a=Gt(p,m)}me(e,"documents",t,"order_key",a)}function cu(e,t,r,n){return e.query(`SELECT id FROM ${t} WHERE ${r} = ? AND __deleted = 0`).all(n).map((o)=>o.id)}function mu(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 Ob,Ib,Cb,Pb,Os,Go="ORDER BY order_key IS NULL, order_key, created_hlc, id",pu,Cs,hu,Jo,Tx,Rx,Ax,Dx,gu;var vn=Ae(()=>{St();lt();Xe();Ob=["id","title","body","database_id","parent_id","created_hlc","order_key"],Ib=Ob.join(", "),Cb=["id","title","database_id","parent_id","created_hlc","order_key"],Pb=Cb.join(", ");Os=Fe(function(t,r){let n=qt("doc",r.title),o=me(t,"documents",n,"title",r.title);if(me(t,"documents",n,"created_hlc",o.hlc),r.database_id!==void 0)me(t,"documents",n,"database_id",r.database_id);if(r.parent_id!==void 0)me(t,"documents",n,"parent_id",r.parent_id);if(Vo(t,n,r.parent_id??null),r.body!==void 0){let s=pn(r.body);if(s.length)bn(t,n,s,null,null)}return ot(t,n)});pu=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)fu(t,n.parent_id)});Cs=Fe(function(t,r,n,o){let s=ot(t,r);if(!s)throw new H("not_found",`no such document: ${r}`);if(r===n)return s;let a=ot(t,n);if(!a)throw new H("not_found",`no such target document: ${n}`);if(o==="into")Vo(t,r,n);else Vo(t,r,a.parent_id,{targetId:n,where:o});return ot(t,r)}),hu=Fe(function(t,r,n={}){let o=ot(t,r);if(!o)throw new H("not_found",`no such document: ${r}`);wn(t,r);let s=yn(t,r),a=n.parentId!==void 0?n.parentId:o.parent_id,c=Os(t,{title:n.title??o.title,database_id:o.database_id??void 0,parent_id:a??void 0});if(s.length)bn(t,c.id,s.map((p)=>({text:p.text,blankAfter:p.blank_after})),null,null);if(a===o.parent_id)Cs(t,c.id,o.id,"after");return ot(t,c.id)}),Jo=Fe(function(t,r,n,o={}){let s=ot(t,r);if(!s)throw new H("not_found",`no such document: ${r}`);if(o.ifMatch!==void 0&&$t(t,r)!==o.ifMatch)throw new H("stale",`stale: document changed since ${o.ifMatch}; re-read first`);if(n.title!==void 0&&n.title!==(s.title??""))me(t,"documents",r,"title",n.title);if(n.database_id!==void 0&&n.database_id!==(s.database_id??null))me(t,"documents",r,"database_id",n.database_id);if(n.parent_id!==void 0){let a=n.parent_id??null;if((ot(t,r).parent_id??null)!==a)Vo(t,r,a)}if(n.body!==void 0)wn(t,r),Ds(t,r,n.body);return ot(t,r)}),Tx=Fe(function(t,r,n){if(!ot(t,r))throw new H("not_found",`no such document: ${r}`);if(n.ifMatch!==void 0&&$t(t,r)!==n.ifMatch)throw new H("stale",`stale: document changed since ${n.ifMatch}; re-read first`);if(n.old==="")throw new H("invalid_input","--old must not be empty");wn(t,r);let o=yn(t,r),s=Mr(o.map((p)=>({text:p.text,blankAfter:p.blank_after}))),a=mu(s,n.old);if(a===0)throw new H("invalid_input","anchor not found: no match for --old");if(a>1&&!n.replaceAll)throw new H("ambiguous",`${a} matches for --old; add surrounding context or use --replace-all`);let c=n.replaceAll?s.replaceAll(n.old,()=>n.new):s.replace(n.old,()=>n.new);return Ds(t,r,c),{id:r,changed:c!==s,replaced:n.replaceAll?a:1,version:$t(t,r)}}),Rx=Fe(function(t,r,n){if(!ot(t,r))throw new H("not_found",`no such document: ${r}`);if(n.edits.length===0)throw new H("invalid_input","no edits given");if(n.ifMatch!==void 0&&$t(t,r)!==n.ifMatch)throw new H("stale",`stale: document changed since ${n.ifMatch}; re-read first`);wn(t,r);let o=Mr(yn(t,r).map((c)=>({text:c.text,blankAfter:c.blank_after}))),s=o,a=0;if(n.edits.forEach((c,p)=>{if(c.old==="")throw new H("invalid_input",`edit[${p}]: old must not be empty`);let m=mu(s,c.old);if(m===0)throw new H("invalid_input",`edit[${p}]: anchor not found: no match for old`);if(m>1&&!c.replaceAll)throw new H("ambiguous",`edit[${p}]: ${m} matches for old; add surrounding context or set replaceAll`);let x=c.new??"";s=c.replaceAll?s.replaceAll(c.old,()=>x):s.replace(c.old,()=>x),a+=c.replaceAll?m:1}),s!==o)Ds(t,r,s);return{id:r,changed:s!==o,replaced:a,version:$t(t,r)}}),Ax=Fe(function(t,r,n){if(!ot(t,r))throw new H("not_found",`no such document: ${r}`);wn(t,r);let o=pn(n);if(o.length){let s=yn(t,r),a=s.length?s[s.length-1].order_key:null;bn(t,r,o,a,null)}return{id:r,changed:o.length>0,replaced:o.length,version:$t(t,r)}}),Dx=Fe(function(t,r,n){if(!ot(t,r))throw new H("not_found",`no such document: ${r}`);wn(t,r);let o=pn(n);if(o.length){let s=yn(t,r),a=s.length?s[0].order_key:null;bn(t,r,o,null,a)}return{id:r,changed:o.length>0,replaced:o.length,version:$t(t,r)}}),gu=Fe(function(t,r){if(!ot(t,r))return!1;me(t,"documents",r,"__deleted",1);for(let n of cu(t,"doc_blocks","doc_id",r))me(t,"doc_blocks",n,"__deleted",1);for(let n of cu(t,"documents","parent_id",r))me(t,"documents",n,"parent_id",null);return!0})});function _u(e){Xo=e}function yu(e,t){return Xo?Xo(e,t):Promise.resolve(null)}function bu(){return Xo!==null}function Jn(e){let t=e.query("SELECT full_nodes, redundancy FROM blob_policy WHERE id = ? AND __deleted = 0").get(Ps),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 Mb(e){e.query("UPDATE blob_cache SET anchored = 0").run(),e.query("DELETE FROM meta WHERE key = ?").run(Fb)}function Ub(e){if(!e)return[];let t=[];for(let r of e.matchAll(zb))t.push(r[1]);return t}function vu(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 Ub(o.text))t.add(s);return t}function Eu(e){return e.query("SELECT hash, size FROM blob_cache WHERE pending = 1").all()}function Su(e,t){return e.query("SELECT content_type FROM blob_cache WHERE hash = ?").get(t)?.content_type??null}var Ps="default",Xo=null,wu=(e,t)=>{Qt(e,null,()=>{let r=new Set,n=t.filter((s)=>s&&!r.has(s)&&r.add(s)!=null);if(me(e,"blob_policy",Ps,"full_nodes",n),Jn(e).redundancy==null)me(e,"blob_policy",Ps,"redundancy","all")}),Mb(e)},Fb="blob_verified_at",zb;var Xn=Ae(()=>{lt();Kt();zb=/\/blob\/([0-9a-f]{16,64})/g});function ku(e){try{let t=new URL(e),r=t.port&&t.port!==Bb[t.protocol]?`:${t.port}`:"";return t.hostname+r}catch{return e.trim().replace(/^[a-z]+:\/\//i,"").replace(/\/.*$/,"").replace(/:(80|443)$/,"")}}function En(e,t,r){let n=r?.trim()||"metahub";return`s3://${ku(e)}/${t}/${n}`}var Bb;var Qn=Ae(()=>{Bb={"https:":"443","http:":"80"}});function jb(e){e.exec(ul);try{e.exec(dl)}catch{}}function xu(e){return e.query("SELECT 1 AS ok FROM sqlite_master WHERE name = 'search_fts'").get()!=null}function yt(e,t,r){return e.query(`PRAGMA table_info(${t})`).all().some((o)=>o.name===r)}function Br(e,t){return e.query("SELECT 1 AS ok FROM sqlite_master WHERE type = 'table' AND name = ?").get(t)!=null}function Hb(e){if(!yt(e,"records","data"))e.exec("ALTER TABLE records ADD COLUMN data TEXT NOT NULL DEFAULT '{}'");if(!yt(e,"records","order_key"))e.exec("ALTER TABLE records ADD COLUMN order_key TEXT");if(!Br(e,"record_values"))return;at(e,()=>{e.exec(`
354
354
  UPDATE records SET data = coalesce((
355
355
  SELECT json_group_object(rv.property_id, json(rv.value))
356
356
  FROM record_values rv WHERE rv.record_id = records.id
357
357
  ), '{}')
358
358
  WHERE id IN (SELECT DISTINCT record_id FROM record_values);
359
- `),e.exec("DROP TABLE record_values"),Wo(e)}),Wo(e)}function Pb(e){if(!yt(e,"shares","served_base"))e.exec("ALTER TABLE shares ADD COLUMN served_base TEXT");if(!yt(e,"shares","grants"))e.exec("ALTER TABLE shares ADD COLUMN grants TEXT");if(!yt(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 Nb(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(!yt(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 qb(e){if(!yt(e,"doc_blocks","blank_after"))e.exec("ALTER TABLE doc_blocks ADD COLUMN blank_after INTEGER NOT NULL DEFAULT 0")}function Lb(e){if(!yt(e,"blob_cache","pinned"))e.exec("ALTER TABLE blob_cache ADD COLUMN pinned INTEGER NOT NULL DEFAULT 0");if(!yt(e,"blob_cache","pending"))e.exec("ALTER TABLE blob_cache ADD COLUMN pending INTEGER NOT NULL DEFAULT 1");if(!yt(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 $b(e){if(!yt(e,"documents","order_key"))e.exec("ALTER TABLE documents ADD COLUMN order_key TEXT");lu(e)}function Mb(e){if(!yt(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 Fb(e){if(yt(e,"crdt_changes","seq"))return;st(e,()=>{if(e.exec(`
359
+ `),e.exec("DROP TABLE record_values"),Ko(e)}),Ko(e)}function Wb(e){if(!yt(e,"shares","served_base"))e.exec("ALTER TABLE shares ADD COLUMN served_base TEXT");if(!yt(e,"shares","grants"))e.exec("ALTER TABLE shares ADD COLUMN grants TEXT");if(!yt(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 Zb(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(!yt(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 Kb(e){if(!yt(e,"doc_blocks","blank_after"))e.exec("ALTER TABLE doc_blocks ADD COLUMN blank_after INTEGER NOT NULL DEFAULT 0")}function Gb(e){if(!yt(e,"blob_cache","pinned"))e.exec("ALTER TABLE blob_cache ADD COLUMN pinned INTEGER NOT NULL DEFAULT 0");if(!yt(e,"blob_cache","pending"))e.exec("ALTER TABLE blob_cache ADD COLUMN pending INTEGER NOT NULL DEFAULT 1");if(!yt(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 Vb(e){if(!yt(e,"documents","order_key"))e.exec("ALTER TABLE documents ADD COLUMN order_key TEXT");pu(e)}function Jb(e){if(!yt(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 Xb(e){if(yt(e,"crdt_changes","seq"))return;at(e,()=>{if(e.exec(`
360
360
  DROP TABLE IF EXISTS crdt_changes_new;
361
361
  CREATE TABLE crdt_changes_new (
362
362
  seq INTEGER PRIMARY KEY AUTOINCREMENT,
@@ -381,7 +381,7 @@ CREATE VIRTUAL TABLE IF NOT EXISTS search_fts USING fts5(
381
381
  WHERE dataset = 'intent_receipts';
382
382
  CREATE INDEX IF NOT EXISTS idx_changes_docref ON crdt_changes(value)
383
383
  WHERE dataset = 'doc_blocks' AND col = 'doc_id';
384
- `),Ur(e,"peers"))e.exec("UPDATE peers SET push_cursor = 0, pull_cursor = 0")})}function zb(e){if(!Ur(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 s of t){let a;try{a=JSON.parse(s.config)}catch{continue}if(!a.endpoint||!a.bucket||!a.prefix)continue;let c=bn(a.endpoint,a.bucket,a.prefix);if(c===s.url){n.add(c);continue}if(n.has(c)||e.query("SELECT 1 FROM peers WHERE url = ?").get(c)||Ur(e,"storage_cursors")&&e.query("SELECT 1 FROM storage_cursors WHERE peer_url = ?").get(c))continue;n.add(c),r.push({oldUrl:s.url,newUrl:c})}if(r.length===0)return;let o=new Map(r.map(({oldUrl:s,newUrl:a})=>[s,a]));st(e,()=>{for(let{oldUrl:s,newUrl:a}of r){if(Ur(e,"storage_cursors"))e.query("UPDATE storage_cursors SET peer_url = ? WHERE peer_url = ?").run(a,s);e.query("UPDATE peers SET url = ? WHERE url = ?").run(a,s)}if(Ur(e,"blob_policy")){let s=Kn(e).fullNodes;if(s.some((a)=>o.has(a)))_u(e,s.map((a)=>o.get(a)??a))}})}function Ub(e){if(yt(e,"databases","meta"))return;e.exec("ALTER TABLE databases ADD COLUMN meta TEXT"),e.exec(`
384
+ `),Br(e,"peers"))e.exec("UPDATE peers SET push_cursor = 0, pull_cursor = 0")})}function Qb(e){if(!Br(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 s of t){let a;try{a=JSON.parse(s.config)}catch{continue}if(!a.endpoint||!a.bucket||!a.prefix)continue;let c=En(a.endpoint,a.bucket,a.prefix);if(c===s.url){n.add(c);continue}if(n.has(c)||e.query("SELECT 1 FROM peers WHERE url = ?").get(c)||Br(e,"storage_cursors")&&e.query("SELECT 1 FROM storage_cursors WHERE peer_url = ?").get(c))continue;n.add(c),r.push({oldUrl:s.url,newUrl:c})}if(r.length===0)return;let o=new Map(r.map(({oldUrl:s,newUrl:a})=>[s,a]));at(e,()=>{for(let{oldUrl:s,newUrl:a}of r){if(Br(e,"storage_cursors"))e.query("UPDATE storage_cursors SET peer_url = ? WHERE peer_url = ?").run(a,s);e.query("UPDATE peers SET url = ? WHERE url = ?").run(a,s)}if(Br(e,"blob_policy")){let s=Jn(e).fullNodes;if(s.some((a)=>o.has(a)))wu(e,s.map((a)=>o.get(a)??a))}})}function Yb(e){if(yt(e,"databases","meta"))return;e.exec("ALTER TABLE databases ADD COLUMN meta TEXT"),e.exec(`
385
385
  UPDATE databases SET meta = (
386
386
  SELECT c.value FROM crdt_changes c
387
387
  WHERE c.dataset = 'databases' AND c.col = 'meta' AND c.row_id = databases.id
@@ -390,7 +390,7 @@ CREATE VIRTUAL TABLE IF NOT EXISTS search_fts USING fts5(
390
390
  WHERE id IN (
391
391
  SELECT DISTINCT row_id FROM crdt_changes WHERE dataset = 'databases' AND col = 'meta'
392
392
  )
393
- `)}function Bb(e){let t=(r,n)=>{e.exec(`
393
+ `)}function ew(e){let t=(r,n)=>{e.exec(`
394
394
  UPDATE sites SET ${r} = COALESCE((
395
395
  SELECT json_extract(c.value, '$') FROM crdt_changes c
396
396
  WHERE c.dataset = 'sites' AND c.col = '${r}' AND c.row_id = sites.id
@@ -399,10 +399,10 @@ CREATE VIRTUAL TABLE IF NOT EXISTS search_fts USING fts5(
399
399
  WHERE id IN (
400
400
  SELECT DISTINCT row_id FROM crdt_changes WHERE dataset = 'sites' AND col = '${r}'
401
401
  )
402
- `)};if(!yt(e,"sites","visibility"))e.exec("ALTER TABLE sites ADD COLUMN visibility TEXT"),t("visibility","NULL");if(!yt(e,"sites","spa"))e.exec("ALTER TABLE sites ADD COLUMN spa INTEGER NOT NULL DEFAULT 0"),t("spa","0");if(!yt(e,"sites","public_grants"))e.exec("ALTER TABLE sites ADD COLUMN public_grants TEXT"),t("public_grants","NULL")}function Eu(e,t){if(!Ur(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, ${mt} FROM crdt_changes
403
- WHERE dataset = ? AND seq > ? ORDER BY seq`).all(t,o);if(s.length===0)return;st(e,()=>{for(let a of s)Mr(e,a);e.query("INSERT INTO meta (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(r,String(s[s.length-1].seq))})}function jb(e){Eu(e,"site_channels")}function Hb(e){Eu(e,"nodes")}function Cs(e){Ib(e),Mb(e),Ub(e),Fb(e),Cb(e),Nb(e),zb(e),qb(e),$b(e),Lb(e),Pb(e),Bb(e),jb(e),Hb(e)}var Jo=De(()=>{zr();yn();Vn();Jn();ct()});function ce(e,t,r){function n(c,p){if(!c._zod)Object.defineProperty(c,"_zod",{value:{def:p,constr:a,traits:new Set},enumerable:!1});if(c._zod.traits.has(e))return;c._zod.traits.add(e),t(c,p);let m=a.prototype,x=Object.keys(m);for(let O=0;O<x.length;O++){let F=x[O];if(!(F in c))c[F]=m[F].bind(c)}}let o=r?.Parent??Object;class s extends o{}Object.defineProperty(s,"name",{value:e});function a(c){var p;let m=r?.Parent?new s:this;n(m,c),(p=m._zod).deferred??(p.deferred=[]);for(let x of m._zod.deferred)x();return m}return Object.defineProperty(a,"init",{value:n}),Object.defineProperty(a,Symbol.hasInstance,{value:(c)=>{if(r?.Parent&&c instanceof r.Parent)return!0;return c?._zod?.traits?.has(e)}}),Object.defineProperty(a,"name",{value:e}),a}function Qt(e){if(e)Object.assign(wn,e);return wn}var qu,aT,hr,Xn,wn;var Br=De(()=>{aT=Symbol("zod_brand");hr=class hr extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}};Xn=class Xn extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`);this.name="ZodEncodeError"}};(qu=globalThis).__zod_globalConfig??(qu.__zod_globalConfig={});wn=globalThis.__zod_globalConfig});function Yo(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)=>Us(r)).join(t)}function Yn(e,t){if(typeof t==="bigint")return t.toString();return t}function ei(e){return{get value(){{let r=e();return Object.defineProperty(this,"value",{value:r}),r}throw Error("cached value already set")}}}function ti(e){return e===null||e===void 0}function ri(e){let t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function $u(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 Qe(e,t,r){let n=void 0;Object.defineProperty(e,t,{get(){if(n===Lu)return;if(n===void 0)n=Lu,n=r();return n},set(o){Object.defineProperty(e,t,{value:o})},configurable:!0})}function jr(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function Tr(...e){let t={};for(let r of e){let n=Object.getOwnPropertyDescriptors(r);Object.assign(t,n)}return Object.defineProperties({},t)}function Ms(e){return JSON.stringify(e)}function Mu(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}function Qn(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function vn(e){if(Qn(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(Qn(r)===!1)return!1;if(Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)return!1;return!0}function zs(e){if(vn(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 Rr(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ir(e,t,r){let n=new e._zod.constr(t??e._zod.def);if(!t||r?.parent)n._zod.parent=e;return n}function qe(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 Us(e){if(typeof e==="bigint")return e.toString()+"n";if(typeof e==="string")return`"${e}"`;return`${e}`}function Uu(e){return Object.keys(e).filter((t)=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}function ew(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=Tr(e._zod.def,{get shape(){let a={};for(let c in t){if(!(c in r.shape))throw Error(`Unrecognized key: "${c}"`);if(!t[c])continue;a[c]=r.shape[c]}return jr(this,"shape",a),a},checks:[]});return ir(e,s)}function tw(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=Tr(e._zod.def,{get shape(){let a={...e._zod.def.shape};for(let c in t){if(!(c in r.shape))throw Error(`Unrecognized key: "${c}"`);if(!t[c])continue;delete a[c]}return jr(this,"shape",a),a},checks:[]});return ir(e,s)}function rw(e,t){if(!vn(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=Tr(e._zod.def,{get shape(){let s={...e._zod.def.shape,...t};return jr(this,"shape",s),s}});return ir(e,o)}function nw(e,t){if(!vn(t))throw Error("Invalid input to safeExtend: expected a plain object");let r=Tr(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return jr(this,"shape",n),n}});return ir(e,r)}function ow(e,t){if(e._zod.def.checks?.length)throw Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let r=Tr(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t._zod.def.shape};return jr(this,"shape",n),n},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return ir(e,r)}function iw(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=Tr(t._zod.def,{get shape(){let c=t._zod.def.shape,p={...c};if(r)for(let m in r){if(!(m in c))throw Error(`Unrecognized key: "${m}"`);if(!r[m])continue;p[m]=e?new e({type:"optional",innerType:c[m]}):c[m]}else for(let m in c)p[m]=e?new e({type:"optional",innerType:c[m]}):c[m];return jr(this,"shape",p),p},checks:[]});return ir(t,a)}function sw(e,t,r){let n=Tr(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 jr(this,"shape",s),s}});return ir(t,n)}function Hr(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 ju(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 ni(e,t){return t.map((r)=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(e),r})}function Qo(e){return typeof e==="string"?e:e?.message}function gr(e,t,r){let n=e.message?e.message:Qo(e.inst?._zod.def?.error?.(e))??Qo(t?.error?.(e))??Qo(r.customError?.(e))??Qo(r.localeError?.(e))??"Invalid input",{inst:o,continue:s,input:a,...c}=e;if(c.path??(c.path=[]),c.message=n,t?.reportInput)c.input=a;return c}function oi(e){if(Array.isArray(e))return"array";if(typeof e==="string")return"string";return"unknown"}function Hu(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 Wr(...e){let[t,r,n]=e;if(typeof t==="string")return{message:t,code:"custom",input:r,inst:n};return{...t}}var Lu,Fs,Fu,zu,Bu;var Yt=De(()=>{Br();Lu=Symbol("evaluating");Fs="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};Fu=ei(()=>{if(wn.jitless)return!1;if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(e){return!1}});zu=new Set(["string","number","symbol"]);Bu={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 Zu(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 Gu(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((c)=>n({issues:c},[...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 c=[...s,...a.path];if(c.length===0)r._errors.push(t(a));else{let p=r,m=0;while(m<c.length){let x=c[m];if(m!==c.length-1)p[x]=p[x]||{_errors:[]};else p[x]=p[x]||{_errors:[]},p[x]._errors.push(t(a));p=p[x],m++}}}};return n(e),r}var Wu=(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,Yn,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},ii,Bs;var js=De(()=>{Br();Yt();ii=ce("$ZodError",Wu),Bs=ce("$ZodError",Wu,{Parent:Error})});var si=(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 hr;if(a.issues.length){let c=new(o?.Err??e)(a.issues.map((p)=>gr(p,s,Qt())));throw Fs(c,o?.callee),c}return a.value},ai=(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 c=new(o?.Err??e)(a.issues.map((p)=>gr(p,s,Qt())));throw Fs(c,o?.callee),c}return a.value},eo=(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 hr;return s.issues.length?{success:!1,error:new(e??ii)(s.issues.map((a)=>gr(a,o,Qt())))}:{success:!0,data:s.value}},Ku,to=(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)=>gr(a,o,Qt())))}:{success:!0,data:s.value}},Vu,Ju=(e)=>(t,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return si(e)(t,r,o)},Xu=(e)=>(t,r,n)=>si(e)(t,r,n),Qu=(e)=>async(t,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return ai(e)(t,r,o)},Yu=(e)=>async(t,r,n)=>ai(e)(t,r,n),ed=(e)=>(t,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return eo(e)(t,r,o)},td=(e)=>(t,r,n)=>eo(e)(t,r,n),rd=(e)=>async(t,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return to(e)(t,r,o)},nd=(e)=>async(t,r,n)=>to(e)(t,r,n);var Hs=De(()=>{Br();js();Yt();Ku=eo(Bs),Vu=to(Bs)});function pd(){return new RegExp(cw,"u")}function Sd(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 xd(e){return new RegExp(`^${Sd(e)}$`)}function kd(e){let t=Sd({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(`^${vd}T(?:${n})$`)}var od,id,sd,ad,cd,ld,ud,dd,Ws=(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})$`)},fd,cw="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",hd,gd,_d,md,yd,Zs,bd,wd,vd="(?:(?:\\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])))",Ed,Td=(e)=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},Rd,Ad,Dd,Od,Id;var li=De(()=>{od=/^[cC][0-9a-z]{6,}$/,id=/^[0-9a-z]+$/,sd=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,ad=/^[0-9a-vA-V]{20}$/,cd=/^[A-Za-z0-9]{27}$/,ld=/^[a-zA-Z0-9_-]{21}$/,ud=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,dd=/^([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})$/,fd=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;hd=/^(?:(?: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])$/,gd=/^(([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}|:))$/,_d=/^((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])$/,md=/^(([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])$/,yd=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Zs=/^[A-Za-z0-9_-]*$/,bd=/^https?$/,wd=/^\+[1-9]\d{6,14}$/,Ed=new RegExp(`^${vd}$`);Rd=/^-?\d+$/,Ad=/^-?\d+(?:\.\d+)?$/,Dd=/^(?:true|false)$/i,Od=/^[^A-Z]*$/,Id=/^[^a-z]*$/});var bt,Cd,Gs,Ks,Pd,Nd,qd,Ld,$d,ro,Md,Fd,zd,Ud,Bd,jd,Hd;var ui=De(()=>{Br();li();Yt();bt=ce("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),Cd={number:"number",bigint:"bigint",object:"date"},Gs=ce("$ZodCheckLessThan",(e,t)=>{bt.init(e,t);let r=Cd[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})}}),Ks=ce("$ZodCheckGreaterThan",(e,t)=>{bt.init(e,t);let r=Cd[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})}}),Pd=ce("$ZodCheckMultipleOf",(e,t)=>{bt.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):$u(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})}}),Nd=ce("$ZodCheckNumberFormat",(e,t)=>{bt.init(e,t),t.format=t.format||"float64";let r=t.format?.includes("int"),n=r?"int":"number",[o,s]=Bu[t.format];e._zod.onattach.push((a)=>{let c=a._zod.bag;if(c.format=t.format,c.minimum=o,c.maximum=s,r)c.pattern=Rd}),e._zod.check=(a)=>{let c=a.value;if(r){if(!Number.isInteger(c)){a.issues.push({expected:n,format:t.format,code:"invalid_type",continue:!1,input:c,inst:e});return}if(!Number.isSafeInteger(c)){if(c>0)a.issues.push({input:c,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:c,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(c<o)a.issues.push({origin:"number",input:c,code:"too_small",minimum:o,inclusive:!0,inst:e,continue:!t.abort});if(c>s)a.issues.push({origin:"number",input:c,code:"too_big",maximum:s,inclusive:!0,inst:e,continue:!t.abort})}}),qd=ce("$ZodCheckMaxLength",(e,t)=>{var r;bt.init(e,t),(r=e._zod.def).when??(r.when=(n)=>{let o=n.value;return!ti(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=oi(o);n.issues.push({origin:a,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),Ld=ce("$ZodCheckMinLength",(e,t)=>{var r;bt.init(e,t),(r=e._zod.def).when??(r.when=(n)=>{let o=n.value;return!ti(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=oi(o);n.issues.push({origin:a,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),$d=ce("$ZodCheckLengthEquals",(e,t)=>{var r;bt.init(e,t),(r=e._zod.def).when??(r.when=(n)=>{let o=n.value;return!ti(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=oi(o),c=s>t.length;n.issues.push({origin:a,...c?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),ro=ce("$ZodCheckStringFormat",(e,t)=>{var r,n;if(bt.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=()=>{})}),Md=ce("$ZodCheckRegex",(e,t)=>{ro.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})}}),Fd=ce("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=Od),ro.init(e,t)}),zd=ce("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=Id),ro.init(e,t)}),Ud=ce("$ZodCheckIncludes",(e,t)=>{bt.init(e,t);let r=Rr(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})}}),Bd=ce("$ZodCheckStartsWith",(e,t)=>{bt.init(e,t);let r=new RegExp(`^${Rr(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})}}),jd=ce("$ZodCheckEndsWith",(e,t)=>{bt.init(e,t);let r=new RegExp(`.*${Rr(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})}}),Hd=ce("$ZodCheckOverwrite",(e,t)=>{bt.init(e,t),e._zod.check=(r)=>{r.value=t.tx(r.value)}})});class Vs{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(`
402
+ `)};if(!yt(e,"sites","visibility"))e.exec("ALTER TABLE sites ADD COLUMN visibility TEXT"),t("visibility","NULL");if(!yt(e,"sites","spa"))e.exec("ALTER TABLE sites ADD COLUMN spa INTEGER NOT NULL DEFAULT 0"),t("spa","0");if(!yt(e,"sites","public_grants"))e.exec("ALTER TABLE sites ADD COLUMN public_grants TEXT"),t("public_grants","NULL")}function Tu(e,t){if(!Br(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, ${_t} FROM crdt_changes
403
+ WHERE dataset = ? AND seq > ? ORDER BY seq`).all(t,o);if(s.length===0)return;at(e,()=>{for(let a of s)Fr(e,a);e.query("INSERT INTO meta (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(r,String(s[s.length-1].seq))})}function tw(e){Tu(e,"site_channels")}function rw(e){Tu(e,"nodes")}function Ns(e){jb(e),Jb(e),Yb(e),Xb(e),Hb(e),Zb(e),Qb(e),Kb(e),Vb(e),Gb(e),Wb(e),ew(e),tw(e),rw(e)}var Qo=Ae(()=>{Ur();vn();Xn();Qn();lt()});function ce(e,t,r){function n(c,p){if(!c._zod)Object.defineProperty(c,"_zod",{value:{def:p,constr:a,traits:new Set},enumerable:!1});if(c._zod.traits.has(e))return;c._zod.traits.add(e),t(c,p);let m=a.prototype,x=Object.keys(m);for(let A=0;A<x.length;A++){let F=x[A];if(!(F in c))c[F]=m[F].bind(c)}}let o=r?.Parent??Object;class s extends o{}Object.defineProperty(s,"name",{value:e});function a(c){var p;let m=r?.Parent?new s:this;n(m,c),(p=m._zod).deferred??(p.deferred=[]);for(let x of m._zod.deferred)x();return m}return Object.defineProperty(a,"init",{value:n}),Object.defineProperty(a,Symbol.hasInstance,{value:(c)=>{if(r?.Parent&&c instanceof r.Parent)return!0;return c?._zod?.traits?.has(e)}}),Object.defineProperty(a,"name",{value:e}),a}function Yt(e){if(e)Object.assign(Sn,e);return Sn}var Fu,ST,gr,Yn,Sn;var jr=Ae(()=>{ST=Symbol("zod_brand");gr=class gr extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}};Yn=class Yn extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`);this.name="ZodEncodeError"}};(Fu=globalThis).__zod_globalConfig??(Fu.__zod_globalConfig={});Sn=globalThis.__zod_globalConfig});function ti(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 Fs(e,t="|"){return e.map((r)=>js(r)).join(t)}function to(e,t){if(typeof t==="bigint")return t.toString();return t}function ri(e){return{get value(){{let r=e();return Object.defineProperty(this,"value",{value:r}),r}throw Error("cached value already set")}}}function ni(e){return e===null||e===void 0}function oi(e){let t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function Uu(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 Qe(e,t,r){let n=void 0;Object.defineProperty(e,t,{get(){if(n===zu)return;if(n===void 0)n=zu,n=r();return n},set(o){Object.defineProperty(e,t,{value:o})},configurable:!0})}function Hr(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function Rr(...e){let t={};for(let r of e){let n=Object.getOwnPropertyDescriptors(r);Object.assign(t,n)}return Object.defineProperties({},t)}function zs(e){return JSON.stringify(e)}function Bu(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}function eo(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function kn(e){if(eo(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(eo(r)===!1)return!1;if(Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)return!1;return!0}function Bs(e){if(kn(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 Ar(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ar(e,t,r){let n=new e._zod.constr(t??e._zod.def);if(!t||r?.parent)n._zod.parent=e;return n}function qe(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 js(e){if(typeof e==="bigint")return e.toString()+"n";if(typeof e==="string")return`"${e}"`;return`${e}`}function Wu(e){return Object.keys(e).filter((t)=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}function fw(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=Rr(e._zod.def,{get shape(){let a={};for(let c in t){if(!(c in r.shape))throw Error(`Unrecognized key: "${c}"`);if(!t[c])continue;a[c]=r.shape[c]}return Hr(this,"shape",a),a},checks:[]});return ar(e,s)}function pw(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=Rr(e._zod.def,{get shape(){let a={...e._zod.def.shape};for(let c in t){if(!(c in r.shape))throw Error(`Unrecognized key: "${c}"`);if(!t[c])continue;delete a[c]}return Hr(this,"shape",a),a},checks:[]});return ar(e,s)}function hw(e,t){if(!kn(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=Rr(e._zod.def,{get shape(){let s={...e._zod.def.shape,...t};return Hr(this,"shape",s),s}});return ar(e,o)}function gw(e,t){if(!kn(t))throw Error("Invalid input to safeExtend: expected a plain object");let r=Rr(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return Hr(this,"shape",n),n}});return ar(e,r)}function mw(e,t){if(e._zod.def.checks?.length)throw Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let r=Rr(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t._zod.def.shape};return Hr(this,"shape",n),n},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return ar(e,r)}function _w(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=Rr(t._zod.def,{get shape(){let c=t._zod.def.shape,p={...c};if(r)for(let m in r){if(!(m in c))throw Error(`Unrecognized key: "${m}"`);if(!r[m])continue;p[m]=e?new e({type:"optional",innerType:c[m]}):c[m]}else for(let m in c)p[m]=e?new e({type:"optional",innerType:c[m]}):c[m];return Hr(this,"shape",p),p},checks:[]});return ar(t,a)}function yw(e,t,r){let n=Rr(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 Hr(this,"shape",s),s}});return ar(t,n)}function Wr(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 Ku(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 ii(e,t){return t.map((r)=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(e),r})}function ei(e){return typeof e==="string"?e:e?.message}function mr(e,t,r){let n=e.message?e.message:ei(e.inst?._zod.def?.error?.(e))??ei(t?.error?.(e))??ei(r.customError?.(e))??ei(r.localeError?.(e))??"Invalid input",{inst:o,continue:s,input:a,...c}=e;if(c.path??(c.path=[]),c.message=n,t?.reportInput)c.input=a;return c}function si(e){if(Array.isArray(e))return"array";if(typeof e==="string")return"string";return"unknown"}function Gu(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 Zr(...e){let[t,r,n]=e;if(typeof t==="string")return{message:t,code:"custom",input:r,inst:n};return{...t}}var zu,Us,ju,Hu,Zu;var er=Ae(()=>{jr();zu=Symbol("evaluating");Us="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};ju=ri(()=>{if(Sn.jitless)return!1;if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(e){return!1}});Hu=new Set(["string","number","symbol"]);Zu={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 Ju(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 Xu(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((c)=>n({issues:c},[...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 c=[...s,...a.path];if(c.length===0)r._errors.push(t(a));else{let p=r,m=0;while(m<c.length){let x=c[m];if(m!==c.length-1)p[x]=p[x]||{_errors:[]};else p[x]=p[x]||{_errors:[]},p[x]._errors.push(t(a));p=p[x],m++}}}};return n(e),r}var Vu=(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,to,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},ai,Hs;var Ws=Ae(()=>{jr();er();ai=ce("$ZodError",Vu),Hs=ce("$ZodError",Vu,{Parent:Error})});var ci=(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 gr;if(a.issues.length){let c=new(o?.Err??e)(a.issues.map((p)=>mr(p,s,Yt())));throw Us(c,o?.callee),c}return a.value},li=(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 c=new(o?.Err??e)(a.issues.map((p)=>mr(p,s,Yt())));throw Us(c,o?.callee),c}return a.value},ro=(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 gr;return s.issues.length?{success:!1,error:new(e??ai)(s.issues.map((a)=>mr(a,o,Yt())))}:{success:!0,data:s.value}},Qu,no=(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)=>mr(a,o,Yt())))}:{success:!0,data:s.value}},Yu,ed=(e)=>(t,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return ci(e)(t,r,o)},td=(e)=>(t,r,n)=>ci(e)(t,r,n),rd=(e)=>async(t,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return li(e)(t,r,o)},nd=(e)=>async(t,r,n)=>li(e)(t,r,n),od=(e)=>(t,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return ro(e)(t,r,o)},id=(e)=>(t,r,n)=>ro(e)(t,r,n),sd=(e)=>async(t,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return no(e)(t,r,o)},ad=(e)=>async(t,r,n)=>no(e)(t,r,n);var Zs=Ae(()=>{jr();Ws();er();Qu=ro(Hs),Yu=no(Hs)});function _d(){return new RegExp(ww,"u")}function Rd(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 Ad(e){return new RegExp(`^${Rd(e)}$`)}function Dd(e){let t=Rd({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(`^${xd}T(?:${n})$`)}var cd,ld,ud,dd,fd,pd,hd,gd,Ks=(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})$`)},md,ww="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",yd,bd,wd,vd,Ed,Gs,Sd,kd,xd="(?:(?:\\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])))",Td,Od=(e)=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},Id,Cd,Pd,Nd,qd;var di=Ae(()=>{cd=/^[cC][0-9a-z]{6,}$/,ld=/^[0-9a-z]+$/,ud=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,dd=/^[0-9a-vA-V]{20}$/,fd=/^[A-Za-z0-9]{27}$/,pd=/^[a-zA-Z0-9_-]{21}$/,hd=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,gd=/^([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})$/,md=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;yd=/^(?:(?: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])$/,bd=/^(([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}|:))$/,wd=/^((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])$/,vd=/^(([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])$/,Ed=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Gs=/^[A-Za-z0-9_-]*$/,Sd=/^https?$/,kd=/^\+[1-9]\d{6,14}$/,Td=new RegExp(`^${xd}$`);Id=/^-?\d+$/,Cd=/^-?\d+(?:\.\d+)?$/,Pd=/^(?:true|false)$/i,Nd=/^[^A-Z]*$/,qd=/^[^a-z]*$/});var bt,Ld,Vs,Js,$d,Md,Fd,zd,Ud,oo,Bd,jd,Hd,Wd,Zd,Kd,Gd;var fi=Ae(()=>{jr();di();er();bt=ce("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),Ld={number:"number",bigint:"bigint",object:"date"},Vs=ce("$ZodCheckLessThan",(e,t)=>{bt.init(e,t);let r=Ld[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})}}),Js=ce("$ZodCheckGreaterThan",(e,t)=>{bt.init(e,t);let r=Ld[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})}}),$d=ce("$ZodCheckMultipleOf",(e,t)=>{bt.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):Uu(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})}}),Md=ce("$ZodCheckNumberFormat",(e,t)=>{bt.init(e,t),t.format=t.format||"float64";let r=t.format?.includes("int"),n=r?"int":"number",[o,s]=Zu[t.format];e._zod.onattach.push((a)=>{let c=a._zod.bag;if(c.format=t.format,c.minimum=o,c.maximum=s,r)c.pattern=Id}),e._zod.check=(a)=>{let c=a.value;if(r){if(!Number.isInteger(c)){a.issues.push({expected:n,format:t.format,code:"invalid_type",continue:!1,input:c,inst:e});return}if(!Number.isSafeInteger(c)){if(c>0)a.issues.push({input:c,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:c,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(c<o)a.issues.push({origin:"number",input:c,code:"too_small",minimum:o,inclusive:!0,inst:e,continue:!t.abort});if(c>s)a.issues.push({origin:"number",input:c,code:"too_big",maximum:s,inclusive:!0,inst:e,continue:!t.abort})}}),Fd=ce("$ZodCheckMaxLength",(e,t)=>{var r;bt.init(e,t),(r=e._zod.def).when??(r.when=(n)=>{let o=n.value;return!ni(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=si(o);n.issues.push({origin:a,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),zd=ce("$ZodCheckMinLength",(e,t)=>{var r;bt.init(e,t),(r=e._zod.def).when??(r.when=(n)=>{let o=n.value;return!ni(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=si(o);n.issues.push({origin:a,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),Ud=ce("$ZodCheckLengthEquals",(e,t)=>{var r;bt.init(e,t),(r=e._zod.def).when??(r.when=(n)=>{let o=n.value;return!ni(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=si(o),c=s>t.length;n.issues.push({origin:a,...c?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),oo=ce("$ZodCheckStringFormat",(e,t)=>{var r,n;if(bt.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=()=>{})}),Bd=ce("$ZodCheckRegex",(e,t)=>{oo.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})}}),jd=ce("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=Nd),oo.init(e,t)}),Hd=ce("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=qd),oo.init(e,t)}),Wd=ce("$ZodCheckIncludes",(e,t)=>{bt.init(e,t);let r=Ar(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})}}),Zd=ce("$ZodCheckStartsWith",(e,t)=>{bt.init(e,t);let r=new RegExp(`^${Ar(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})}}),Kd=ce("$ZodCheckEndsWith",(e,t)=>{bt.init(e,t);let r=new RegExp(`.*${Ar(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})}}),Gd=ce("$ZodCheckOverwrite",(e,t)=>{bt.init(e,t),e._zod.check=(r)=>{r.value=t.tx(r.value)}})});class Xs{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(`
404
404
  `).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(`
405
- `))}}var Zd;var Js=De(()=>{Zd={major:4,minor:4,patch:3}});function vf(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 lw(e){if(!Zs.test(e))return!1;let t=e.replace(/[-_]/g,(n)=>n==="-"?"+":"/"),r=t.padEnd(Math.ceil(t.length/4)*4,"=");return vf(r)}function uw(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 Gd(e,t,r){if(e.issues.length)t.issues.push(...ni(r,e.issues));t.value[r]=e.value}function fi(e,t,r,n,o,s){let a=r in n;if(e.issues.length){if(o&&s&&!a)return;t.issues.push(...ni(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 If(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=Uu(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(r)}}function Cf(e,t,r,n,o,s){let a=[],c=o.keySet,p=o.catchall._zod,m=p.def.type,x=p.optin==="optional",O=p.optout==="optional";for(let F in t){if(F==="__proto__")continue;if(c.has(F))continue;if(m==="never"){a.push(F);continue}let X=p.run({value:t[F],issues:[]},n);if(X instanceof Promise)e.push(X.then((he)=>fi(he,r,F,t,x,O)));else fi(X,r,F,t,x,O)}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 Kd(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)=>!Hr(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)=>gr(a,n,Qt())))}),t}function Xs(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(vn(e)&&vn(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=Xs(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=Xs(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 Vd(e,t,r){let n=new Map,o;for(let c of t.issues)if(c.code==="unrecognized_keys"){o??(o=c);for(let p of c.keys){if(!n.has(p))n.set(p,{});n.get(p).l=!0}}else e.issues.push(c);for(let c of r.issues)if(c.code==="unrecognized_keys")for(let p of c.keys){if(!n.has(p))n.set(p,{});n.get(p).r=!0}else e.issues.push(c);let s=[...n].filter(([,c])=>c.l&&c.r).map(([c])=>c);if(s.length&&o)e.issues.push({...o,keys:s});if(Hr(e))return e;let a=Xs(t.value,r.value);if(!a.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(a.mergeErrorPath)}`);return e.value=a.data,e}function Jd(e,t){if(t===void 0&&(e.issues.length||e.fallback))return{issues:[],value:void 0};return e}function Xd(e,t){if(e.value===void 0)e.value=t.defaultValue;return e}function Qd(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 di(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 Yd(e){return e.value=Object.freeze(e.value),e}function ef(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(Wr(o))}}var at,pi,nt,tf,rf,nf,of,sf,af,cf,lf,uf,df,ff,pf,hf,gf,_f,mf,yf,bf,wf,Ef,Sf,xf,kf,Qs,Tf,Rf,Af,Df,Of,dw,Pf,Nf,qf,Lf,$f,Mf,Ys,Ff,zf,Uf,Bf,jf,Hf,Wf,Zf,Gf;var Kf=De(()=>{ui();Br();Hs();li();Yt();Js();Yt();at=ce("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Zd;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,c,p)=>{let m=Hr(a),x;for(let O of c){if(O._zod.def.when){if(ju(a))continue;if(!O._zod.def.when(a))continue}else if(m)continue;let F=a.issues.length,X=O._zod.check(a);if(X instanceof Promise&&p?.async===!1)throw new hr;if(x||X instanceof Promise)x=(x??Promise.resolve()).then(async()=>{if(await X,a.issues.length===F)return;if(!m)m=Hr(a,F)});else{if(a.issues.length===F)continue;if(!m)m=Hr(a,F)}}if(x)return x.then(()=>a);return a},s=(a,c,p)=>{if(Hr(a))return a.aborted=!0,a;let m=o(c,n,p);if(m instanceof Promise){if(p.async===!1)throw new hr;return m.then((x)=>e._zod.parse(x,p))}return e._zod.parse(m,p)};e._zod.run=(a,c)=>{if(c.skipChecks)return e._zod.parse(a,c);if(c.direction==="backward"){let m=e._zod.parse({value:a.value,issues:[]},{...c,skipChecks:!0});if(m instanceof Promise)return m.then((x)=>s(x,a,c));return s(m,a,c)}let p=e._zod.parse(a,c);if(p instanceof Promise){if(c.async===!1)throw new hr;return p.then((m)=>o(m,n,c))}return o(p,n,c)}}Qe(e,"~standard",()=>({validate:(o)=>{try{let s=Ku(e,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch(s){return Vu(e,o).then((a)=>a.success?{value:a.data}:{issues:a.error?.issues})}},vendor:"zod",version:1}))}),pi=ce("$ZodString",(e,t)=>{at.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??Td(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}}),nt=ce("$ZodStringFormat",(e,t)=>{ro.init(e,t),pi.init(e,t)}),tf=ce("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=dd),nt.init(e,t)}),rf=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=Ws(n))}else t.pattern??(t.pattern=Ws());nt.init(e,t)}),nf=ce("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=fd),nt.init(e,t)}),of=ce("$ZodURL",(e,t)=>{nt.init(e,t),e._zod.check=(r)=>{try{let n=r.value.trim();if(!t.normalize&&t.protocol?.source===bd.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})}}}),sf=ce("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=pd()),nt.init(e,t)}),af=ce("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=ld),nt.init(e,t)}),cf=ce("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=od),nt.init(e,t)}),lf=ce("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=id),nt.init(e,t)}),uf=ce("$ZodULID",(e,t)=>{t.pattern??(t.pattern=sd),nt.init(e,t)}),df=ce("$ZodXID",(e,t)=>{t.pattern??(t.pattern=ad),nt.init(e,t)}),ff=ce("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=cd),nt.init(e,t)}),pf=ce("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=kd(t)),nt.init(e,t)}),hf=ce("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=Ed),nt.init(e,t)}),gf=ce("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=xd(t)),nt.init(e,t)}),_f=ce("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=ud),nt.init(e,t)}),mf=ce("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=hd),nt.init(e,t),e._zod.bag.format="ipv4"}),yf=ce("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=gd),nt.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})}}}),bf=ce("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=_d),nt.init(e,t)}),wf=ce("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=md),nt.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})}}});Ef=ce("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=yd),nt.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=(r)=>{if(vf(r.value))return;r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}});Sf=ce("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=Zs),nt.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=(r)=>{if(lw(r.value))return;r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),xf=ce("$ZodE164",(e,t)=>{t.pattern??(t.pattern=wd),nt.init(e,t)});kf=ce("$ZodJWT",(e,t)=>{nt.init(e,t),e._zod.check=(r)=>{if(uw(r.value,t.alg))return;r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}}),Qs=ce("$ZodNumber",(e,t)=>{at.init(e,t),e._zod.pattern=e._zod.bag.pattern??Ad,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}}),Tf=ce("$ZodNumberFormat",(e,t)=>{Nd.init(e,t),Qs.init(e,t)}),Rf=ce("$ZodBoolean",(e,t)=>{at.init(e,t),e._zod.pattern=Dd,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}}),Af=ce("$ZodUnknown",(e,t)=>{at.init(e,t),e._zod.parse=(r)=>r}),Df=ce("$ZodNever",(e,t)=>{at.init(e,t),e._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:e}),r)});Of=ce("$ZodArray",(e,t)=>{at.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 c=o[a],p=t.element._zod.run({value:c,issues:[]},n);if(p instanceof Promise)s.push(p.then((m)=>Gd(m,r,a)));else Gd(p,r,a)}if(s.length)return Promise.all(s).then(()=>r);return r}});dw=ce("$ZodObject",(e,t)=>{if(at.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){let c=t.shape;Object.defineProperty(t,"shape",{get:()=>{let p={...c};return Object.defineProperty(t,"shape",{value:p}),p}})}let n=ei(()=>If(t));Qe(e._zod,"propValues",()=>{let c=t.shape,p={};for(let m in c){let x=c[m]._zod;if(x.values){p[m]??(p[m]=new Set);for(let O of x.values)p[m].add(O)}}return p});let o=Qn,s=t.catchall,a;e._zod.parse=(c,p)=>{a??(a=n.value);let m=c.value;if(!o(m))return c.issues.push({expected:"object",code:"invalid_type",input:m,inst:e}),c;c.value={};let x=[],O=a.shape;for(let F of a.keys){let X=O[F],he=X._zod.optin==="optional",be=X._zod.optout==="optional",le=X._zod.run({value:m[F],issues:[]},p);if(le instanceof Promise)x.push(le.then((Oe)=>fi(Oe,c,F,m,he,be)));else fi(le,c,F,m,he,be)}if(!s)return x.length?Promise.all(x).then(()=>c):c;return Cf(x,m,c,p,n.value,e)}}),Pf=ce("$ZodObjectJIT",(e,t)=>{dw.init(e,t);let r=e._zod.parse,n=ei(()=>If(t)),o=(F)=>{let X=new Vs(["shape","payload","ctx"]),he=n.value,be=(Me)=>{let He=Ms(Me);return`shape[${He}]._zod.run({ value: input[${He}], issues: [] }, ctx)`};X.write("const input = payload.value;");let le=Object.create(null),Oe=0;for(let Me of he.keys)le[Me]=`key_${Oe++}`;X.write("const newResult = {};");for(let Me of he.keys){let He=le[Me],Ze=Ms(Me),$t=F[Me],Tt=$t?._zod?.optin==="optional",Nn=$t?._zod?.optout==="optional";if(X.write(`const ${He} = ${be(Me)};`),Tt&&Nn)X.write(`
405
+ `))}}var Jd;var Qs=Ae(()=>{Jd={major:4,minor:4,patch:3}});function xf(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 vw(e){if(!Gs.test(e))return!1;let t=e.replace(/[-_]/g,(n)=>n==="-"?"+":"/"),r=t.padEnd(Math.ceil(t.length/4)*4,"=");return xf(r)}function Ew(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 Xd(e,t,r){if(e.issues.length)t.issues.push(...ii(r,e.issues));t.value[r]=e.value}function hi(e,t,r,n,o,s){let a=r in n;if(e.issues.length){if(o&&s&&!a)return;t.issues.push(...ii(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 qf(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=Wu(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(r)}}function Lf(e,t,r,n,o,s){let a=[],c=o.keySet,p=o.catchall._zod,m=p.def.type,x=p.optin==="optional",A=p.optout==="optional";for(let F in t){if(F==="__proto__")continue;if(c.has(F))continue;if(m==="never"){a.push(F);continue}let X=p.run({value:t[F],issues:[]},n);if(X instanceof Promise)e.push(X.then((he)=>hi(he,r,F,t,x,A)));else hi(X,r,F,t,x,A)}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 Qd(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)=>!Wr(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)=>mr(a,n,Yt())))}),t}function Ys(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(kn(e)&&kn(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=Ys(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=Ys(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 Yd(e,t,r){let n=new Map,o;for(let c of t.issues)if(c.code==="unrecognized_keys"){o??(o=c);for(let p of c.keys){if(!n.has(p))n.set(p,{});n.get(p).l=!0}}else e.issues.push(c);for(let c of r.issues)if(c.code==="unrecognized_keys")for(let p of c.keys){if(!n.has(p))n.set(p,{});n.get(p).r=!0}else e.issues.push(c);let s=[...n].filter(([,c])=>c.l&&c.r).map(([c])=>c);if(s.length&&o)e.issues.push({...o,keys:s});if(Wr(e))return e;let a=Ys(t.value,r.value);if(!a.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(a.mergeErrorPath)}`);return e.value=a.data,e}function ef(e,t){if(t===void 0&&(e.issues.length||e.fallback))return{issues:[],value:void 0};return e}function tf(e,t){if(e.value===void 0)e.value=t.defaultValue;return e}function rf(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 pi(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 nf(e){return e.value=Object.freeze(e.value),e}function of(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(Zr(o))}}var ct,gi,nt,sf,af,cf,lf,uf,df,ff,pf,hf,gf,mf,_f,yf,bf,wf,vf,Ef,Sf,kf,Tf,Rf,Af,Df,ea,Of,If,Cf,Pf,Nf,Sw,$f,Mf,Ff,zf,Uf,Bf,ta,jf,Hf,Wf,Zf,Kf,Gf,Vf,Jf,Xf;var Qf=Ae(()=>{fi();jr();Zs();di();er();Qs();er();ct=ce("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Jd;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,c,p)=>{let m=Wr(a),x;for(let A of c){if(A._zod.def.when){if(Ku(a))continue;if(!A._zod.def.when(a))continue}else if(m)continue;let F=a.issues.length,X=A._zod.check(a);if(X instanceof Promise&&p?.async===!1)throw new gr;if(x||X instanceof Promise)x=(x??Promise.resolve()).then(async()=>{if(await X,a.issues.length===F)return;if(!m)m=Wr(a,F)});else{if(a.issues.length===F)continue;if(!m)m=Wr(a,F)}}if(x)return x.then(()=>a);return a},s=(a,c,p)=>{if(Wr(a))return a.aborted=!0,a;let m=o(c,n,p);if(m instanceof Promise){if(p.async===!1)throw new gr;return m.then((x)=>e._zod.parse(x,p))}return e._zod.parse(m,p)};e._zod.run=(a,c)=>{if(c.skipChecks)return e._zod.parse(a,c);if(c.direction==="backward"){let m=e._zod.parse({value:a.value,issues:[]},{...c,skipChecks:!0});if(m instanceof Promise)return m.then((x)=>s(x,a,c));return s(m,a,c)}let p=e._zod.parse(a,c);if(p instanceof Promise){if(c.async===!1)throw new gr;return p.then((m)=>o(m,n,c))}return o(p,n,c)}}Qe(e,"~standard",()=>({validate:(o)=>{try{let s=Qu(e,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch(s){return Yu(e,o).then((a)=>a.success?{value:a.data}:{issues:a.error?.issues})}},vendor:"zod",version:1}))}),gi=ce("$ZodString",(e,t)=>{ct.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??Od(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}}),nt=ce("$ZodStringFormat",(e,t)=>{oo.init(e,t),gi.init(e,t)}),sf=ce("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=gd),nt.init(e,t)}),af=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=Ks(n))}else t.pattern??(t.pattern=Ks());nt.init(e,t)}),cf=ce("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=md),nt.init(e,t)}),lf=ce("$ZodURL",(e,t)=>{nt.init(e,t),e._zod.check=(r)=>{try{let n=r.value.trim();if(!t.normalize&&t.protocol?.source===Sd.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})}}}),uf=ce("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=_d()),nt.init(e,t)}),df=ce("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=pd),nt.init(e,t)}),ff=ce("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=cd),nt.init(e,t)}),pf=ce("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=ld),nt.init(e,t)}),hf=ce("$ZodULID",(e,t)=>{t.pattern??(t.pattern=ud),nt.init(e,t)}),gf=ce("$ZodXID",(e,t)=>{t.pattern??(t.pattern=dd),nt.init(e,t)}),mf=ce("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=fd),nt.init(e,t)}),_f=ce("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=Dd(t)),nt.init(e,t)}),yf=ce("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=Td),nt.init(e,t)}),bf=ce("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=Ad(t)),nt.init(e,t)}),wf=ce("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=hd),nt.init(e,t)}),vf=ce("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=yd),nt.init(e,t),e._zod.bag.format="ipv4"}),Ef=ce("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=bd),nt.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})}}}),Sf=ce("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=wd),nt.init(e,t)}),kf=ce("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=vd),nt.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})}}});Tf=ce("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=Ed),nt.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=(r)=>{if(xf(r.value))return;r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}});Rf=ce("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=Gs),nt.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=(r)=>{if(vw(r.value))return;r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),Af=ce("$ZodE164",(e,t)=>{t.pattern??(t.pattern=kd),nt.init(e,t)});Df=ce("$ZodJWT",(e,t)=>{nt.init(e,t),e._zod.check=(r)=>{if(Ew(r.value,t.alg))return;r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}}),ea=ce("$ZodNumber",(e,t)=>{ct.init(e,t),e._zod.pattern=e._zod.bag.pattern??Cd,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}}),Of=ce("$ZodNumberFormat",(e,t)=>{Md.init(e,t),ea.init(e,t)}),If=ce("$ZodBoolean",(e,t)=>{ct.init(e,t),e._zod.pattern=Pd,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}}),Cf=ce("$ZodUnknown",(e,t)=>{ct.init(e,t),e._zod.parse=(r)=>r}),Pf=ce("$ZodNever",(e,t)=>{ct.init(e,t),e._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:e}),r)});Nf=ce("$ZodArray",(e,t)=>{ct.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 c=o[a],p=t.element._zod.run({value:c,issues:[]},n);if(p instanceof Promise)s.push(p.then((m)=>Xd(m,r,a)));else Xd(p,r,a)}if(s.length)return Promise.all(s).then(()=>r);return r}});Sw=ce("$ZodObject",(e,t)=>{if(ct.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){let c=t.shape;Object.defineProperty(t,"shape",{get:()=>{let p={...c};return Object.defineProperty(t,"shape",{value:p}),p}})}let n=ri(()=>qf(t));Qe(e._zod,"propValues",()=>{let c=t.shape,p={};for(let m in c){let x=c[m]._zod;if(x.values){p[m]??(p[m]=new Set);for(let A of x.values)p[m].add(A)}}return p});let o=eo,s=t.catchall,a;e._zod.parse=(c,p)=>{a??(a=n.value);let m=c.value;if(!o(m))return c.issues.push({expected:"object",code:"invalid_type",input:m,inst:e}),c;c.value={};let x=[],A=a.shape;for(let F of a.keys){let X=A[F],he=X._zod.optin==="optional",_e=X._zod.optout==="optional",le=X._zod.run({value:m[F],issues:[]},p);if(le instanceof Promise)x.push(le.then((Oe)=>hi(Oe,c,F,m,he,_e)));else hi(le,c,F,m,he,_e)}if(!s)return x.length?Promise.all(x).then(()=>c):c;return Lf(x,m,c,p,n.value,e)}}),$f=ce("$ZodObjectJIT",(e,t)=>{Sw.init(e,t);let r=e._zod.parse,n=ri(()=>qf(t)),o=(F)=>{let X=new Xs(["shape","payload","ctx"]),he=n.value,_e=(Me)=>{let He=zs(Me);return`shape[${He}]._zod.run({ value: input[${He}], issues: [] }, ctx)`};X.write("const input = payload.value;");let le=Object.create(null),Oe=0;for(let Me of he.keys)le[Me]=`key_${Oe++}`;X.write("const newResult = {};");for(let Me of he.keys){let He=le[Me],Ze=zs(Me),zt=F[Me],Rt=zt?._zod?.optin==="optional",Ln=zt?._zod?.optout==="optional";if(X.write(`const ${He} = ${_e(Me)};`),Rt&&Ln)X.write(`
406
406
  if (${He}.issues.length) {
407
407
  if (${Ze} in input) {
408
408
  payload.issues = payload.issues.concat(${He}.issues.map(iss => ({
@@ -420,7 +420,7 @@ CREATE VIRTUAL TABLE IF NOT EXISTS search_fts USING fts5(
420
420
  newResult[${Ze}] = ${He}.value;
421
421
  }
422
422
 
423
- `);else if(!Tt)X.write(`
423
+ `);else if(!Rt)X.write(`
424
424
  const ${He}_present = ${Ze} in input;
425
425
  if (${He}.issues.length) {
426
426
  payload.issues = payload.issues.concat(${He}.issues.map(iss => ({
@@ -461,80 +461,80 @@ CREATE VIRTUAL TABLE IF NOT EXISTS search_fts USING fts5(
461
461
  newResult[${Ze}] = ${He}.value;
462
462
  }
463
463
 
464
- `)}X.write("payload.value = newResult;"),X.write("return payload;");let Be=X.compile();return(Me,He)=>Be(F,Me,He)},s,a=Qn,c=!wn.jitless,m=c&&Fu.value,x=t.catchall,O;e._zod.parse=(F,X)=>{O??(O=n.value);let he=F.value;if(!a(he))return F.issues.push({expected:"object",code:"invalid_type",input:he,inst:e}),F;if(c&&m&&X?.async===!1&&X.jitless!==!0){if(!s)s=o(t.shape);if(F=s(F,X),!x)return F;return Cf([],he,F,X,O,e)}return r(F,X)}});Nf=ce("$ZodUnion",(e,t)=>{at.init(e,t),Qe(e._zod,"optin",()=>t.options.some((n)=>n._zod.optin==="optional")?"optional":void 0),Qe(e._zod,"optout",()=>t.options.some((n)=>n._zod.optout==="optional")?"optional":void 0),Qe(e._zod,"values",()=>{if(t.options.every((n)=>n._zod.values))return new Set(t.options.flatMap((n)=>Array.from(n._zod.values)));return}),Qe(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)=>ri(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 c of t.options){let p=c._zod.run({value:n.value,issues:[]},o);if(p instanceof Promise)a.push(p),s=!0;else{if(p.issues.length===0)return p;a.push(p)}}if(!s)return Kd(a,n,e,o);return Promise.all(a).then((c)=>Kd(c,n,e,o))}}),qf=ce("$ZodIntersection",(e,t)=>{at.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(([p,m])=>Vd(r,p,m));return Vd(r,s,a)}});Lf=ce("$ZodEnum",(e,t)=>{at.init(e,t);let r=Yo(t.entries),n=new Set(r);e._zod.values=n,e._zod.pattern=new RegExp(`^(${r.filter((o)=>zu.has(typeof o)).map((o)=>typeof o==="string"?Rr(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}}),$f=ce("$ZodLiteral",(e,t)=>{if(at.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"?Rr(n):n?Rr(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}}),Mf=ce("$ZodTransform",(e,t)=>{at.init(e,t),e._zod.optin="optional",e._zod.parse=(r,n)=>{if(n.direction==="backward")throw new Xn(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 hr;return r.value=o,r.fallback=!0,r}});Ys=ce("$ZodOptional",(e,t)=>{at.init(e,t),e._zod.optin="optional",e._zod.optout="optional",Qe(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),Qe(e._zod,"pattern",()=>{let r=t.innerType._zod.pattern;return r?new RegExp(`^(${ri(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)=>Jd(a,o));return Jd(s,o)}if(r.value===void 0)return r;return t.innerType._zod.run(r,n)}}),Ff=ce("$ZodExactOptional",(e,t)=>{Ys.init(e,t),Qe(e._zod,"values",()=>t.innerType._zod.values),Qe(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(r,n)=>t.innerType._zod.run(r,n)}),zf=ce("$ZodNullable",(e,t)=>{at.init(e,t),Qe(e._zod,"optin",()=>t.innerType._zod.optin),Qe(e._zod,"optout",()=>t.innerType._zod.optout),Qe(e._zod,"pattern",()=>{let r=t.innerType._zod.pattern;return r?new RegExp(`^(${ri(r.source)}|null)$`):void 0}),Qe(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)}}),Uf=ce("$ZodDefault",(e,t)=>{at.init(e,t),e._zod.optin="optional",Qe(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)=>Xd(s,t));return Xd(o,t)}});Bf=ce("$ZodPrefault",(e,t)=>{at.init(e,t),e._zod.optin="optional",Qe(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)}}),jf=ce("$ZodNonOptional",(e,t)=>{at.init(e,t),Qe(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)=>Qd(s,e));return Qd(o,e)}});Hf=ce("$ZodCatch",(e,t)=>{at.init(e,t),e._zod.optin="optional",Qe(e._zod,"optout",()=>t.innerType._zod.optout),Qe(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)=>gr(a,n,Qt()))},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)=>gr(s,n,Qt()))},input:r.value}),r.issues=[],r.fallback=!0;return r}}),Wf=ce("$ZodPipe",(e,t)=>{at.init(e,t),Qe(e._zod,"values",()=>t.in._zod.values),Qe(e._zod,"optin",()=>t.in._zod.optin),Qe(e._zod,"optout",()=>t.out._zod.optout),Qe(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)=>di(a,t.in,n));return di(s,t.in,n)}let o=t.in._zod.run(r,n);if(o instanceof Promise)return o.then((s)=>di(s,t.out,n));return di(o,t.out,n)}});Zf=ce("$ZodReadonly",(e,t)=>{at.init(e,t),Qe(e._zod,"propValues",()=>t.innerType._zod.propValues),Qe(e._zod,"values",()=>t.innerType._zod.values),Qe(e._zod,"optin",()=>t.innerType?._zod?.optin),Qe(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(Yd);return Yd(o)}});Gf=ce("$ZodCustom",(e,t)=>{bt.init(e,t),at.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)=>ef(s,r,n,e));ef(o,r,n,e);return}})});function ea(){return{localeError:fw()}}var fw=()=>{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=Hu(o.input),c=n[a]??a;return`Invalid input: expected ${s}, received ${c}`}case"invalid_value":if(o.values.length===1)return`Invalid input: expected ${Us(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 Vf=De(()=>{Yt()});var ta=()=>{};class Qf{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 pw(){return new Qf}var Xf,DT,OT,Zr;var ra=De(()=>{DT=Symbol("ZodOutput"),OT=Symbol("ZodInput");(Xf=globalThis).__zod_globalRegistry??(Xf.__zod_globalRegistry=pw());Zr=globalThis.__zod_globalRegistry});function Yf(e,t){return new e({type:"string",...qe(t)})}function ep(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...qe(t)})}function na(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...qe(t)})}function tp(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...qe(t)})}function rp(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...qe(t)})}function np(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...qe(t)})}function op(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...qe(t)})}function ip(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...qe(t)})}function sp(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...qe(t)})}function ap(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...qe(t)})}function cp(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...qe(t)})}function lp(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...qe(t)})}function up(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...qe(t)})}function dp(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...qe(t)})}function fp(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...qe(t)})}function pp(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...qe(t)})}function hp(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...qe(t)})}function gp(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...qe(t)})}function _p(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...qe(t)})}function mp(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...qe(t)})}function yp(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...qe(t)})}function bp(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...qe(t)})}function wp(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...qe(t)})}function vp(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...qe(t)})}function Ep(e,t){return new e({type:"string",format:"date",check:"string_format",...qe(t)})}function Sp(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...qe(t)})}function xp(e,t){return new e({type:"string",format:"duration",check:"string_format",...qe(t)})}function kp(e,t){return new e({type:"number",checks:[],...qe(t)})}function Tp(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...qe(t)})}function Rp(e,t){return new e({type:"boolean",...qe(t)})}function Ap(e){return new e({type:"unknown"})}function Dp(e,t){return new e({type:"never",...qe(t)})}function hi(e,t){return new Gs({check:"less_than",...qe(t),value:e,inclusive:!1})}function no(e,t){return new Gs({check:"less_than",...qe(t),value:e,inclusive:!0})}function gi(e,t){return new Ks({check:"greater_than",...qe(t),value:e,inclusive:!1})}function oo(e,t){return new Ks({check:"greater_than",...qe(t),value:e,inclusive:!0})}function _i(e,t){return new Pd({check:"multiple_of",...qe(t),value:e})}function mi(e,t){return new qd({check:"max_length",...qe(t),maximum:e})}function En(e,t){return new Ld({check:"min_length",...qe(t),minimum:e})}function yi(e,t){return new $d({check:"length_equals",...qe(t),length:e})}function oa(e,t){return new Md({check:"string_format",format:"regex",...qe(t),pattern:e})}function ia(e){return new Fd({check:"string_format",format:"lowercase",...qe(e)})}function sa(e){return new zd({check:"string_format",format:"uppercase",...qe(e)})}function aa(e,t){return new Ud({check:"string_format",format:"includes",...qe(t),includes:e})}function ca(e,t){return new Bd({check:"string_format",format:"starts_with",...qe(t),prefix:e})}function la(e,t){return new jd({check:"string_format",format:"ends_with",...qe(t),suffix:e})}function Ar(e){return new Hd({check:"overwrite",tx:e})}function ua(e){return Ar((t)=>t.normalize(e))}function da(){return Ar((e)=>e.trim())}function fa(){return Ar((e)=>e.toLowerCase())}function pa(){return Ar((e)=>e.toUpperCase())}function ha(){return Ar((e)=>Mu(e))}function Op(e,t,r){return new e({type:"array",element:t,...qe(r)})}function Ip(e,t,r){return new e({type:"custom",check:"custom",fn:t,...qe(r)})}function Cp(e,t){let r=hw((n)=>(n.addIssue=(o)=>{if(typeof o==="string")n.issues.push(Wr(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(Wr(s))}},e(n.value,n)),t);return r}function hw(e,t){let r=new bt({check:"custom",...qe(t)});return r._zod.check=e,r}var Pp=De(()=>{ui();Yt()});function ga(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??Zr,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 c=e._zod.toJSONSchema?.();if(c)a.schema=c;else{let x={...r,schemaPath:[...r.schemaPath,e],path:r.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,a.schema,x);else{let F=a.schema,X=t.processors[o.type];if(!X)throw Error(`[toJSONSchema]: Non-representable type encountered: ${o.type}`);X(e,t,F,x)}let O=e._zod.parent;if(O){if(!a.ref)a.ref=O;_t(O,t,x),t.seen.get(O).isParent=!0}}let p=t.metadataRegistry.get(e);if(p)Object.assign(a.schema,p);if(t.io==="input"&&Ot(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 _a(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 c=e.metadataRegistry.get(a[0])?.id;if(c){let p=n.get(c);if(p&&p!==a[0])throw Error(`Duplicate schema id "${c}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);n.set(c,a[0])}}let o=(a)=>{let c=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){let O=e.external.registry.get(a[0])?.id,F=e.external.uri??((he)=>he);if(O)return{ref:F(O)};let X=a[1].defId??a[1].schema.id??`schema${e.counter++}`;return a[1].defId=X,{defId:X,ref:`${F("__shared")}#/${c}/${X}`}}if(a[1]===r)return{ref:"#"};let m=`${"#"}/${c}/`,x=a[1].schema.id??`__schema${e.counter++}`;return{defId:x,ref:m+x}},s=(a)=>{if(a[1].schema.$ref)return;let c=a[1],{ref:p,defId:m}=o(a);if(c.def={...c.schema},m)c.defId=m;let x=c.schema;for(let O in x)delete x[O];x.$ref=p};if(e.cycles==="throw")for(let a of e.seen.entries()){let c=a[1];if(c.cycle)throw Error(`Cycle detected: #/${c.cycle?.join("/")}/<root>
464
+ `)}X.write("payload.value = newResult;"),X.write("return payload;");let Be=X.compile();return(Me,He)=>Be(F,Me,He)},s,a=eo,c=!Sn.jitless,m=c&&ju.value,x=t.catchall,A;e._zod.parse=(F,X)=>{A??(A=n.value);let he=F.value;if(!a(he))return F.issues.push({expected:"object",code:"invalid_type",input:he,inst:e}),F;if(c&&m&&X?.async===!1&&X.jitless!==!0){if(!s)s=o(t.shape);if(F=s(F,X),!x)return F;return Lf([],he,F,X,A,e)}return r(F,X)}});Mf=ce("$ZodUnion",(e,t)=>{ct.init(e,t),Qe(e._zod,"optin",()=>t.options.some((n)=>n._zod.optin==="optional")?"optional":void 0),Qe(e._zod,"optout",()=>t.options.some((n)=>n._zod.optout==="optional")?"optional":void 0),Qe(e._zod,"values",()=>{if(t.options.every((n)=>n._zod.values))return new Set(t.options.flatMap((n)=>Array.from(n._zod.values)));return}),Qe(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)=>oi(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 c of t.options){let p=c._zod.run({value:n.value,issues:[]},o);if(p instanceof Promise)a.push(p),s=!0;else{if(p.issues.length===0)return p;a.push(p)}}if(!s)return Qd(a,n,e,o);return Promise.all(a).then((c)=>Qd(c,n,e,o))}}),Ff=ce("$ZodIntersection",(e,t)=>{ct.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(([p,m])=>Yd(r,p,m));return Yd(r,s,a)}});zf=ce("$ZodEnum",(e,t)=>{ct.init(e,t);let r=ti(t.entries),n=new Set(r);e._zod.values=n,e._zod.pattern=new RegExp(`^(${r.filter((o)=>Hu.has(typeof o)).map((o)=>typeof o==="string"?Ar(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}}),Uf=ce("$ZodLiteral",(e,t)=>{if(ct.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"?Ar(n):n?Ar(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}}),Bf=ce("$ZodTransform",(e,t)=>{ct.init(e,t),e._zod.optin="optional",e._zod.parse=(r,n)=>{if(n.direction==="backward")throw new Yn(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 gr;return r.value=o,r.fallback=!0,r}});ta=ce("$ZodOptional",(e,t)=>{ct.init(e,t),e._zod.optin="optional",e._zod.optout="optional",Qe(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),Qe(e._zod,"pattern",()=>{let r=t.innerType._zod.pattern;return r?new RegExp(`^(${oi(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)=>ef(a,o));return ef(s,o)}if(r.value===void 0)return r;return t.innerType._zod.run(r,n)}}),jf=ce("$ZodExactOptional",(e,t)=>{ta.init(e,t),Qe(e._zod,"values",()=>t.innerType._zod.values),Qe(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(r,n)=>t.innerType._zod.run(r,n)}),Hf=ce("$ZodNullable",(e,t)=>{ct.init(e,t),Qe(e._zod,"optin",()=>t.innerType._zod.optin),Qe(e._zod,"optout",()=>t.innerType._zod.optout),Qe(e._zod,"pattern",()=>{let r=t.innerType._zod.pattern;return r?new RegExp(`^(${oi(r.source)}|null)$`):void 0}),Qe(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)}}),Wf=ce("$ZodDefault",(e,t)=>{ct.init(e,t),e._zod.optin="optional",Qe(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)=>tf(s,t));return tf(o,t)}});Zf=ce("$ZodPrefault",(e,t)=>{ct.init(e,t),e._zod.optin="optional",Qe(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)}}),Kf=ce("$ZodNonOptional",(e,t)=>{ct.init(e,t),Qe(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)=>rf(s,e));return rf(o,e)}});Gf=ce("$ZodCatch",(e,t)=>{ct.init(e,t),e._zod.optin="optional",Qe(e._zod,"optout",()=>t.innerType._zod.optout),Qe(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)=>mr(a,n,Yt()))},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)=>mr(s,n,Yt()))},input:r.value}),r.issues=[],r.fallback=!0;return r}}),Vf=ce("$ZodPipe",(e,t)=>{ct.init(e,t),Qe(e._zod,"values",()=>t.in._zod.values),Qe(e._zod,"optin",()=>t.in._zod.optin),Qe(e._zod,"optout",()=>t.out._zod.optout),Qe(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)=>pi(a,t.in,n));return pi(s,t.in,n)}let o=t.in._zod.run(r,n);if(o instanceof Promise)return o.then((s)=>pi(s,t.out,n));return pi(o,t.out,n)}});Jf=ce("$ZodReadonly",(e,t)=>{ct.init(e,t),Qe(e._zod,"propValues",()=>t.innerType._zod.propValues),Qe(e._zod,"values",()=>t.innerType._zod.values),Qe(e._zod,"optin",()=>t.innerType?._zod?.optin),Qe(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(nf);return nf(o)}});Xf=ce("$ZodCustom",(e,t)=>{bt.init(e,t),ct.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)=>of(s,r,n,e));of(o,r,n,e);return}})});function ra(){return{localeError:kw()}}var kw=()=>{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=Gu(o.input),c=n[a]??a;return`Invalid input: expected ${s}, received ${c}`}case"invalid_value":if(o.values.length===1)return`Invalid input: expected ${js(o.values[0])}`;return`Invalid option: expected one of ${Fs(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":""}: ${Fs(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 Yf=Ae(()=>{er()});var na=()=>{};class rp{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 xw(){return new rp}var tp,WT,ZT,Kr;var oa=Ae(()=>{WT=Symbol("ZodOutput"),ZT=Symbol("ZodInput");(tp=globalThis).__zod_globalRegistry??(tp.__zod_globalRegistry=xw());Kr=globalThis.__zod_globalRegistry});function np(e,t){return new e({type:"string",...qe(t)})}function op(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...qe(t)})}function ia(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...qe(t)})}function ip(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...qe(t)})}function sp(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...qe(t)})}function ap(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...qe(t)})}function cp(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...qe(t)})}function lp(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...qe(t)})}function up(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...qe(t)})}function dp(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...qe(t)})}function fp(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...qe(t)})}function pp(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...qe(t)})}function hp(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...qe(t)})}function gp(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...qe(t)})}function mp(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...qe(t)})}function _p(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...qe(t)})}function yp(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...qe(t)})}function bp(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...qe(t)})}function wp(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...qe(t)})}function vp(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...qe(t)})}function Ep(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...qe(t)})}function Sp(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...qe(t)})}function kp(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...qe(t)})}function xp(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...qe(t)})}function Tp(e,t){return new e({type:"string",format:"date",check:"string_format",...qe(t)})}function Rp(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...qe(t)})}function Ap(e,t){return new e({type:"string",format:"duration",check:"string_format",...qe(t)})}function Dp(e,t){return new e({type:"number",checks:[],...qe(t)})}function Op(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...qe(t)})}function Ip(e,t){return new e({type:"boolean",...qe(t)})}function Cp(e){return new e({type:"unknown"})}function Pp(e,t){return new e({type:"never",...qe(t)})}function mi(e,t){return new Vs({check:"less_than",...qe(t),value:e,inclusive:!1})}function io(e,t){return new Vs({check:"less_than",...qe(t),value:e,inclusive:!0})}function _i(e,t){return new Js({check:"greater_than",...qe(t),value:e,inclusive:!1})}function so(e,t){return new Js({check:"greater_than",...qe(t),value:e,inclusive:!0})}function yi(e,t){return new $d({check:"multiple_of",...qe(t),value:e})}function bi(e,t){return new Fd({check:"max_length",...qe(t),maximum:e})}function xn(e,t){return new zd({check:"min_length",...qe(t),minimum:e})}function wi(e,t){return new Ud({check:"length_equals",...qe(t),length:e})}function sa(e,t){return new Bd({check:"string_format",format:"regex",...qe(t),pattern:e})}function aa(e){return new jd({check:"string_format",format:"lowercase",...qe(e)})}function ca(e){return new Hd({check:"string_format",format:"uppercase",...qe(e)})}function la(e,t){return new Wd({check:"string_format",format:"includes",...qe(t),includes:e})}function ua(e,t){return new Zd({check:"string_format",format:"starts_with",...qe(t),prefix:e})}function da(e,t){return new Kd({check:"string_format",format:"ends_with",...qe(t),suffix:e})}function Dr(e){return new Gd({check:"overwrite",tx:e})}function fa(e){return Dr((t)=>t.normalize(e))}function pa(){return Dr((e)=>e.trim())}function ha(){return Dr((e)=>e.toLowerCase())}function ga(){return Dr((e)=>e.toUpperCase())}function ma(){return Dr((e)=>Bu(e))}function Np(e,t,r){return new e({type:"array",element:t,...qe(r)})}function qp(e,t,r){return new e({type:"custom",check:"custom",fn:t,...qe(r)})}function Lp(e,t){let r=Tw((n)=>(n.addIssue=(o)=>{if(typeof o==="string")n.issues.push(Zr(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(Zr(s))}},e(n.value,n)),t);return r}function Tw(e,t){let r=new bt({check:"custom",...qe(t)});return r._zod.check=e,r}var $p=Ae(()=>{fi();er()});function _a(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??Kr,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 mt(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 c=e._zod.toJSONSchema?.();if(c)a.schema=c;else{let x={...r,schemaPath:[...r.schemaPath,e],path:r.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,a.schema,x);else{let F=a.schema,X=t.processors[o.type];if(!X)throw Error(`[toJSONSchema]: Non-representable type encountered: ${o.type}`);X(e,t,F,x)}let A=e._zod.parent;if(A){if(!a.ref)a.ref=A;mt(A,t,x),t.seen.get(A).isParent=!0}}let p=t.metadataRegistry.get(e);if(p)Object.assign(a.schema,p);if(t.io==="input"&&It(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 ya(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 c=e.metadataRegistry.get(a[0])?.id;if(c){let p=n.get(c);if(p&&p!==a[0])throw Error(`Duplicate schema id "${c}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);n.set(c,a[0])}}let o=(a)=>{let c=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){let A=e.external.registry.get(a[0])?.id,F=e.external.uri??((he)=>he);if(A)return{ref:F(A)};let X=a[1].defId??a[1].schema.id??`schema${e.counter++}`;return a[1].defId=X,{defId:X,ref:`${F("__shared")}#/${c}/${X}`}}if(a[1]===r)return{ref:"#"};let m=`${"#"}/${c}/`,x=a[1].schema.id??`__schema${e.counter++}`;return{defId:x,ref:m+x}},s=(a)=>{if(a[1].schema.$ref)return;let c=a[1],{ref:p,defId:m}=o(a);if(c.def={...c.schema},m)c.defId=m;let x=c.schema;for(let A in x)delete x[A];x.$ref=p};if(e.cycles==="throw")for(let a of e.seen.entries()){let c=a[1];if(c.cycle)throw Error(`Cycle detected: #/${c.cycle?.join("/")}/<root>
465
465
 
466
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let a of e.seen.entries()){let c=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(c.cycle){s(a);continue}if(c.count>1){if(e.reused==="ref"){s(a);continue}}}}function ma(e,t){let r=e.seen.get(t);if(!r)throw Error("Unprocessed schema. This is a bug in Zod.");let n=(c)=>{let p=e.seen.get(c);if(p.ref===null)return;let m=p.def??p.schema,x={...m},O=p.ref;if(p.ref=null,O){n(O);let X=e.seen.get(O),he=X.schema;if(he.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"))m.allOf=m.allOf??[],m.allOf.push(he);else Object.assign(m,he);if(Object.assign(m,x),c._zod.parent===O)for(let le in m){if(le==="$ref"||le==="allOf")continue;if(!(le in x))delete m[le]}if(he.$ref&&X.def)for(let le in m){if(le==="$ref"||le==="allOf")continue;if(le in X.def&&JSON.stringify(m[le])===JSON.stringify(X.def[le]))delete m[le]}}let F=c._zod.parent;if(F&&F!==O){n(F);let X=e.seen.get(F);if(X?.schema.$ref){if(m.$ref=X.schema.$ref,X.def)for(let he in m){if(he==="$ref"||he==="allOf")continue;if(he in X.def&&JSON.stringify(m[he])===JSON.stringify(X.def[he]))delete m[he]}}}e.override({zodSchema:c,jsonSchema:m,path:p.path??[]})};for(let c of[...e.seen.entries()].reverse())n(c[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 c=e.external.registry.get(t)?.id;if(!c)throw Error("Schema is missing an `id` property");o.$id=e.external.uri(c)}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 c of e.seen.entries()){let p=c[1];if(p.def&&p.defId){if(p.def.id===p.defId)delete p.def.id;a[p.defId]=p.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 c=JSON.parse(JSON.stringify(o));return Object.defineProperty(c,"~standard",{value:{...t["~standard"],jsonSchema:{input:io(t,"input",e.processors),output:io(t,"output",e.processors)}},enumerable:!1,writable:!1}),c}catch(c){throw Error("Error converting schema to JSON.")}}function Ot(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 Ot(n.element,r);if(n.type==="set")return Ot(n.valueType,r);if(n.type==="lazy")return Ot(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 Ot(n.innerType,r);if(n.type==="intersection")return Ot(n.left,r)||Ot(n.right,r);if(n.type==="record"||n.type==="map")return Ot(n.keyType,r)||Ot(n.valueType,r);if(n.type==="pipe"){if(e._zod.traits.has("$ZodCodec"))return!0;return Ot(n.in,r)||Ot(n.out,r)}if(n.type==="object"){for(let o in n.shape)if(Ot(n.shape[o],r))return!0;return!1}if(n.type==="union"){for(let o of n.options)if(Ot(o,r))return!0;return!1}if(n.type==="tuple"){for(let o of n.items)if(Ot(o,r))return!0;if(n.rest&&Ot(n.rest,r))return!0;return!1}return!1}var Np=(e,t={})=>(r)=>{let n=ga({...r,processors:t});return _t(e,n),_a(n,e),ma(n,e)},io=(e,t,r={})=>(n)=>{let{libraryOptions:o,target:s}=n??{},a=ga({...o??{},target:s,io:t,processors:r});return _t(e,a),_a(a,e),ma(a,e)};var bi=De(()=>{ra()});var gw,qp=(e,t,r,n)=>{let o=r;o.type="string";let{minimum:s,maximum:a,format:c,patterns:p,contentEncoding:m}=e._zod.bag;if(typeof s==="number")o.minLength=s;if(typeof a==="number")o.maxLength=a;if(c){if(o.format=gw[c]??c,o.format==="")delete o.format;if(c==="time")delete o.format}if(m)o.contentEncoding=m;if(p&&p.size>0){let x=[...p];if(x.length===1)o.pattern=x[0].source;else if(x.length>1)o.allOf=[...x.map((O)=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:O.source}))]}},Lp=(e,t,r,n)=>{let o=r,{minimum:s,maximum:a,format:c,multipleOf:p,exclusiveMaximum:m,exclusiveMinimum:x}=e._zod.bag;if(typeof c==="string"&&c.includes("int"))o.type="integer";else o.type="number";let O=typeof x==="number"&&x>=(s??Number.NEGATIVE_INFINITY),F=typeof m==="number"&&m<=(a??Number.POSITIVE_INFINITY),X=t.target==="draft-04"||t.target==="openapi-3.0";if(O)if(X)o.minimum=x,o.exclusiveMinimum=!0;else o.exclusiveMinimum=x;else if(typeof s==="number")o.minimum=s;if(F)if(X)o.maximum=m,o.exclusiveMaximum=!0;else o.exclusiveMaximum=m;else if(typeof a==="number")o.maximum=a;if(typeof p==="number")o.multipleOf=p},$p=(e,t,r,n)=>{r.type="boolean"},Mp=(e,t,r,n)=>{r.not={}},Fp=(e,t,r,n)=>{},zp=(e,t,r,n)=>{let o=e._zod.def,s=Yo(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},Up=(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}},Bp=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw Error("Custom types cannot be represented in JSON Schema")},jp=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw Error("Transforms cannot be represented in JSON Schema")},Hp=(e,t,r,n)=>{let o=r,s=e._zod.def,{minimum:a,maximum:c}=e._zod.bag;if(typeof a==="number")o.minItems=a;if(typeof c==="number")o.maxItems=c;o.type="array",o.items=_t(s.element,t,{...n,path:[...n.path,"items"]})},Wp=(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 c=new Set(Object.keys(a)),p=new Set([...c].filter((m)=>{let x=s.shape[m]._zod;if(t.io==="input")return x.optin===void 0;else return x.optout===void 0}));if(p.size>0)o.required=Array.from(p);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"]})},Zp=(e,t,r,n)=>{let o=e._zod.def,s=o.inclusive===!1,a=o.options.map((c,p)=>_t(c,t,{...n,path:[...n.path,s?"oneOf":"anyOf",p]}));if(s)r.oneOf=a;else r.anyOf=a},Gp=(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]}),c=(m)=>("allOf"in m)&&Object.keys(m).length===1,p=[...c(s)?s.allOf:[s],...c(a)?a.allOf:[a]];r.allOf=p},Kp=(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"}]},Vp=(e,t,r,n)=>{let o=e._zod.def;_t(o.innerType,t,n);let s=t.seen.get(e);s.ref=o.innerType},Jp=(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))},Xp=(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))},Qp=(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},Yp=(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 c=t.seen.get(e);c.ref=a},eh=(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},ya=(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 th=De(()=>{bi();Yt();gw={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""}});var rh=()=>{};var sr=De(()=>{Yt();li();ta();rh();Br();Hs();js();Kf();ui();Js();ra();Pp();bi()});var ba=De(()=>{sr()});function nh(e){return vp(Ew,e)}function oh(e){return Ep(Sw,e)}function ih(e){return Sp(xw,e)}function sh(e){return xp(kw,e)}var Ew,Sw,xw,kw;var wa=De(()=>{sr();va();Ew=ce("ZodISODateTime",(e,t)=>{pf.init(e,t),it.init(e,t)});Sw=ce("ZodISODate",(e,t)=>{hf.init(e,t),it.init(e,t)});xw=ce("ZodISOTime",(e,t)=>{gf.init(e,t),it.init(e,t)});kw=ce("ZodISODuration",(e,t)=>{_f.init(e,t),it.init(e,t)})});var Rw=(e,t)=>{ii.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:(r)=>Gu(e,r)},flatten:{value:(r)=>Zu(e,r)},addIssue:{value:(r)=>{e.issues.push(r),e.message=JSON.stringify(e.issues,Yn,2)}},addIssues:{value:(r)=>{e.issues.push(...r),e.message=JSON.stringify(e.issues,Yn,2)}},isEmpty:{get(){return e.issues.length===0}}})},zt;var Ea=De(()=>{sr();sr();Yt();zt=ce("ZodError",Rw,{Parent:Error})});var ch,lh,uh,dh,fh,ph,hh,gh,_h,mh,yh,bh;var Sa=De(()=>{sr();Ea();ch=si(zt),lh=ai(zt),uh=eo(zt),dh=to(zt),fh=Ju(zt),ph=Xu(zt),hh=Qu(zt),gh=Yu(zt),_h=ed(zt),mh=td(zt),yh=rd(zt),bh=nd(zt)});function ao(e,t,r){let n=Object.getPrototypeOf(e),o=wh.get(n);if(!o)o=new Set,wh.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 c=a.bind(this);return Object.defineProperty(this,s,{configurable:!0,writable:!0,enumerable:!0,value:c}),c},set(c){Object.defineProperty(this,s,{configurable:!0,writable:!0,enumerable:!0,value:c})}})}}function ut(e){return Yf(Dw,e)}function co(e){return kp(Ah,e)}function Eh(e){return Tp(Gw,e)}function Vw(e){return Rp(Kw,e)}function Sh(){return Ap(Jw)}function Qw(e){return Dp(Xw,e)}function lo(e,t){return Op(Yw,e,t)}function Gr(e,t){let r={type:"object",shape:e??{},...qe(t)};return new ev(r)}function rv(e,t){return new tv({type:"union",options:e,...qe(t)})}function ov(e,t){return new nv({type:"intersection",left:e,right:t})}function vi(e,t){let r=Array.isArray(e)?Object.fromEntries(e.map((n)=>[n,n])):e;return new xa({type:"enum",entries:r,...qe(t)})}function sv(e,t){return new iv({type:"literal",values:Array.isArray(e)?e:[e],...qe(t)})}function cv(e){return new av({type:"transform",transform:e})}function xh(e){return new Dh({type:"optional",innerType:e})}function uv(e){return new lv({type:"optional",innerType:e})}function kh(e){return new dv({type:"nullable",innerType:e})}function pv(e,t){return new fv({type:"default",innerType:e,get defaultValue(){return typeof t==="function"?t():zs(t)}})}function gv(e,t){return new hv({type:"prefault",innerType:e,get defaultValue(){return typeof t==="function"?t():zs(t)}})}function _v(e,t){return new Oh({type:"nonoptional",innerType:e,...qe(t)})}function yv(e,t){return new mv({type:"catch",innerType:e,catchValue:typeof t==="function"?t:()=>t})}function Th(e,t){return new bv({type:"pipe",in:e,out:t})}function vv(e){return new wv({type:"readonly",innerType:e})}function Sv(e,t={}){return Ip(Ev,e,t)}function xv(e,t){return Cp(e,t)}var wh,lt,Rh,Dw,it,Ow,vh,wi,Iw,Cw,Pw,Nw,qw,Lw,$w,Mw,Fw,zw,Uw,Bw,jw,Hw,Ww,Zw,Ah,Gw,Kw,Jw,Xw,Yw,ev,tv,nv,xa,iv,av,Dh,lv,dv,fv,hv,Oh,mv,bv,wv,Ev;var va=De(()=>{sr();sr();th();bi();ba();wa();Sa();wh=new WeakMap;lt=ce("ZodType",(e,t)=>(at.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:io(e,"input"),output:io(e,"output")}}),e.toJSONSchema=Np(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(r,n)=>ch(e,r,n,{callee:e.parse}),e.safeParse=(r,n)=>uh(e,r,n),e.parseAsync=async(r,n)=>lh(e,r,n,{callee:e.parseAsync}),e.safeParseAsync=async(r,n)=>dh(e,r,n),e.spa=e.safeParseAsync,e.encode=(r,n)=>fh(e,r,n),e.decode=(r,n)=>ph(e,r,n),e.encodeAsync=async(r,n)=>hh(e,r,n),e.decodeAsync=async(r,n)=>gh(e,r,n),e.safeEncode=(r,n)=>_h(e,r,n),e.safeDecode=(r,n)=>mh(e,r,n),e.safeEncodeAsync=async(r,n)=>yh(e,r,n),e.safeDecodeAsync=async(r,n)=>bh(e,r,n),ao(e,"ZodType",{check(...r){let n=this.def;return this.clone(Tr(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 ir(this,r,n)},brand(){return this},register(r,n){return r.add(this,n),this},refine(r,n){return this.check(Sv(r,n))},superRefine(r,n){return this.check(xv(r,n))},overwrite(r){return this.check(Ar(r))},optional(){return xh(this)},exactOptional(){return uv(this)},nullable(){return kh(this)},nullish(){return xh(kh(this))},nonoptional(r){return _v(this,r)},array(){return lo(this)},or(r){return rv([this,r])},and(r){return ov(this,r)},transform(r){return Th(this,cv(r))},default(r){return pv(this,r)},prefault(r){return gv(this,r)},catch(r){return yv(this,r)},pipe(r){return Th(this,r)},readonly(){return vv(this)},describe(r){let n=this.clone();return Zr.add(n,{description:r}),n},meta(...r){if(r.length===0)return Zr.get(this);let n=this.clone();return Zr.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 Zr.get(e)?.description},configurable:!0}),e)),Rh=ce("_ZodString",(e,t)=>{pi.init(e,t),lt.init(e,t),e._zod.processJSONSchema=(n,o,s)=>qp(e,n,o,s);let r=e._zod.bag;e.format=r.format??null,e.minLength=r.minimum??null,e.maxLength=r.maximum??null,ao(e,"_ZodString",{regex(...n){return this.check(oa(...n))},includes(...n){return this.check(aa(...n))},startsWith(...n){return this.check(ca(...n))},endsWith(...n){return this.check(la(...n))},min(...n){return this.check(En(...n))},max(...n){return this.check(mi(...n))},length(...n){return this.check(yi(...n))},nonempty(...n){return this.check(En(1,...n))},lowercase(n){return this.check(ia(n))},uppercase(n){return this.check(sa(n))},trim(){return this.check(da())},normalize(...n){return this.check(ua(...n))},toLowerCase(){return this.check(fa())},toUpperCase(){return this.check(pa())},slugify(){return this.check(ha())}})}),Dw=ce("ZodString",(e,t)=>{pi.init(e,t),Rh.init(e,t),e.email=(r)=>e.check(ep(Ow,r)),e.url=(r)=>e.check(ip(Iw,r)),e.jwt=(r)=>e.check(wp(Zw,r)),e.emoji=(r)=>e.check(sp(Cw,r)),e.guid=(r)=>e.check(na(vh,r)),e.uuid=(r)=>e.check(tp(wi,r)),e.uuidv4=(r)=>e.check(rp(wi,r)),e.uuidv6=(r)=>e.check(np(wi,r)),e.uuidv7=(r)=>e.check(op(wi,r)),e.nanoid=(r)=>e.check(ap(Pw,r)),e.guid=(r)=>e.check(na(vh,r)),e.cuid=(r)=>e.check(cp(Nw,r)),e.cuid2=(r)=>e.check(lp(qw,r)),e.ulid=(r)=>e.check(up(Lw,r)),e.base64=(r)=>e.check(mp(jw,r)),e.base64url=(r)=>e.check(yp(Hw,r)),e.xid=(r)=>e.check(dp($w,r)),e.ksuid=(r)=>e.check(fp(Mw,r)),e.ipv4=(r)=>e.check(pp(Fw,r)),e.ipv6=(r)=>e.check(hp(zw,r)),e.cidrv4=(r)=>e.check(gp(Uw,r)),e.cidrv6=(r)=>e.check(_p(Bw,r)),e.e164=(r)=>e.check(bp(Ww,r)),e.datetime=(r)=>e.check(nh(r)),e.date=(r)=>e.check(oh(r)),e.time=(r)=>e.check(ih(r)),e.duration=(r)=>e.check(sh(r))});it=ce("ZodStringFormat",(e,t)=>{nt.init(e,t),Rh.init(e,t)}),Ow=ce("ZodEmail",(e,t)=>{nf.init(e,t),it.init(e,t)}),vh=ce("ZodGUID",(e,t)=>{tf.init(e,t),it.init(e,t)}),wi=ce("ZodUUID",(e,t)=>{rf.init(e,t),it.init(e,t)}),Iw=ce("ZodURL",(e,t)=>{of.init(e,t),it.init(e,t)}),Cw=ce("ZodEmoji",(e,t)=>{sf.init(e,t),it.init(e,t)}),Pw=ce("ZodNanoID",(e,t)=>{af.init(e,t),it.init(e,t)}),Nw=ce("ZodCUID",(e,t)=>{cf.init(e,t),it.init(e,t)}),qw=ce("ZodCUID2",(e,t)=>{lf.init(e,t),it.init(e,t)}),Lw=ce("ZodULID",(e,t)=>{uf.init(e,t),it.init(e,t)}),$w=ce("ZodXID",(e,t)=>{df.init(e,t),it.init(e,t)}),Mw=ce("ZodKSUID",(e,t)=>{ff.init(e,t),it.init(e,t)}),Fw=ce("ZodIPv4",(e,t)=>{mf.init(e,t),it.init(e,t)}),zw=ce("ZodIPv6",(e,t)=>{yf.init(e,t),it.init(e,t)}),Uw=ce("ZodCIDRv4",(e,t)=>{bf.init(e,t),it.init(e,t)}),Bw=ce("ZodCIDRv6",(e,t)=>{wf.init(e,t),it.init(e,t)}),jw=ce("ZodBase64",(e,t)=>{Ef.init(e,t),it.init(e,t)}),Hw=ce("ZodBase64URL",(e,t)=>{Sf.init(e,t),it.init(e,t)}),Ww=ce("ZodE164",(e,t)=>{xf.init(e,t),it.init(e,t)}),Zw=ce("ZodJWT",(e,t)=>{kf.init(e,t),it.init(e,t)}),Ah=ce("ZodNumber",(e,t)=>{Qs.init(e,t),lt.init(e,t),e._zod.processJSONSchema=(n,o,s)=>Lp(e,n,o,s),ao(e,"ZodNumber",{gt(n,o){return this.check(gi(n,o))},gte(n,o){return this.check(oo(n,o))},min(n,o){return this.check(oo(n,o))},lt(n,o){return this.check(hi(n,o))},lte(n,o){return this.check(no(n,o))},max(n,o){return this.check(no(n,o))},int(n){return this.check(Eh(n))},safe(n){return this.check(Eh(n))},positive(n){return this.check(gi(0,n))},nonnegative(n){return this.check(oo(0,n))},negative(n){return this.check(hi(0,n))},nonpositive(n){return this.check(no(0,n))},multipleOf(n,o){return this.check(_i(n,o))},step(n,o){return this.check(_i(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});Gw=ce("ZodNumberFormat",(e,t)=>{Tf.init(e,t),Ah.init(e,t)});Kw=ce("ZodBoolean",(e,t)=>{Rf.init(e,t),lt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>$p(e,r,n,o)});Jw=ce("ZodUnknown",(e,t)=>{Af.init(e,t),lt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Fp(e,r,n,o)});Xw=ce("ZodNever",(e,t)=>{Df.init(e,t),lt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Mp(e,r,n,o)});Yw=ce("ZodArray",(e,t)=>{Of.init(e,t),lt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Hp(e,r,n,o),e.element=t.element,ao(e,"ZodArray",{min(r,n){return this.check(En(r,n))},nonempty(r){return this.check(En(1,r))},max(r,n){return this.check(mi(r,n))},length(r,n){return this.check(yi(r,n))},unwrap(){return this.element}})});ev=ce("ZodObject",(e,t)=>{Pf.init(e,t),lt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Wp(e,r,n,o),Qe(e,"shape",()=>t.shape),ao(e,"ZodObject",{keyof(){return vi(Object.keys(this._zod.def.shape))},catchall(r){return this.clone({...this._zod.def,catchall:r})},passthrough(){return this.clone({...this._zod.def,catchall:Sh()})},loose(){return this.clone({...this._zod.def,catchall:Sh()})},strict(){return this.clone({...this._zod.def,catchall:Qw()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(r){return rw(this,r)},safeExtend(r){return nw(this,r)},merge(r){return ow(this,r)},pick(r){return ew(this,r)},omit(r){return tw(this,r)},partial(...r){return iw(Dh,this,r[0])},required(...r){return sw(Oh,this,r[0])}})});tv=ce("ZodUnion",(e,t)=>{Nf.init(e,t),lt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Zp(e,r,n,o),e.options=t.options});nv=ce("ZodIntersection",(e,t)=>{qf.init(e,t),lt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Gp(e,r,n,o)});xa=ce("ZodEnum",(e,t)=>{Lf.init(e,t),lt.init(e,t),e._zod.processJSONSchema=(n,o,s)=>zp(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 xa({...t,checks:[],...qe(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 xa({...t,checks:[],...qe(o),entries:s})}});iv=ce("ZodLiteral",(e,t)=>{$f.init(e,t),lt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Up(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]}})});av=ce("ZodTransform",(e,t)=>{Mf.init(e,t),lt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>jp(e,r,n,o),e._zod.parse=(r,n)=>{if(n.direction==="backward")throw new Xn(e.constructor.name);r.addIssue=(s)=>{if(typeof s==="string")r.issues.push(Wr(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(Wr(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}});Dh=ce("ZodOptional",(e,t)=>{Ys.init(e,t),lt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>ya(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});lv=ce("ZodExactOptional",(e,t)=>{Ff.init(e,t),lt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>ya(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});dv=ce("ZodNullable",(e,t)=>{zf.init(e,t),lt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Kp(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});fv=ce("ZodDefault",(e,t)=>{Uf.init(e,t),lt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Jp(e,r,n,o),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});hv=ce("ZodPrefault",(e,t)=>{Bf.init(e,t),lt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Xp(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});Oh=ce("ZodNonOptional",(e,t)=>{jf.init(e,t),lt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Vp(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});mv=ce("ZodCatch",(e,t)=>{Hf.init(e,t),lt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Qp(e,r,n,o),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});bv=ce("ZodPipe",(e,t)=>{Wf.init(e,t),lt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Yp(e,r,n,o),e.in=t.in,e.out=t.out});wv=ce("ZodReadonly",(e,t)=>{Zf.init(e,t),lt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>eh(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});Ev=ce("ZodCustom",(e,t)=>{Gf.init(e,t),lt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Bp(e,r,n,o)})});var Ih;var Ch=De(()=>{(function(e){})(Ih||(Ih={}))});var Ph=()=>{};var Ta=De(()=>{sr();sr();Vf();ta();wa();Ph();va();ba();Ea();Sa();Ch();Qt(ea())});var Ra=De(()=>{Ta();Ta()});var Nh,IA,CA,qh,PA,NA,Lh="/sync",$h="/health",Mh="/api/pair";var Ei=De(()=>{Ra();Nh=Gr({hlc:ut().describe("Hybrid Logical Clock timestamp"),node_id:ut().describe("Origin node that produced the change"),dataset:ut().describe("CRDT dataset, e.g. databases / records / documents"),row_id:ut().describe("Row identifier within the dataset"),col:ut().describe("Column / property identifier"),value:ut().nullable().describe("JSON-encoded field value, or null"),txn:ut().nullable().optional().describe("Change-group id (one logical mutation)")}),IA=Gr({node_id:ut().describe("Calling client's node id"),since:co().describe("Server cursor the client last pulled"),changes:lo(Nh).describe("Client's changes to push"),limit:co().optional().describe("Max changes to return (pagination for hydration)"),exclude_datasets:lo(ut()).optional().describe("Datasets to omit from the pull (partial replica)")}),CA=Gr({node_id:ut().describe("Server's node id"),changes:lo(Nh).describe("Server changes after `since`"),cursor:co().describe("New server cursor for the client to store"),skewed_rejected:co().optional().describe("Pushed changes the server refused for being stamped >5 min in the future")}),qh=Gr({ok:Vw(),node:ut().describe("Server's node id"),capabilities:lo(ut()).optional().describe("Optional protocol features supported by this server"),version:ut().optional().describe("Core version, for mixed-version workspace warnings")}),PA=Gr({code:ut().describe("One-time pairing code minted by this server"),node_id:ut().describe("Calling device's node id"),grant:ut().describe("Durable credential the caller issues to us"),self_url:ut().optional().describe("Caller's reachable server URL (for mutual sync)")}),NA=Gr({node_id:ut().describe("This server's node id"),grant:ut().describe("Durable credential we issue to the caller")})});function Tv(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 Rv(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 Aa(e,t){return Object.entries(t).map(([r,n])=>`${e}: refused ${n} change(s) from device ${r} stamped more than 5 min in the future — run \`mh repair --clock\` on that device`)}function Av(e,t,r){if(r.length===0)return t;let n=new Set(r.map(Fh)),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(Fh(a)))break;s=a.seq}return s}async function Si(e,t,r={}){let n=typeof r==="string"?{token:r}:r,o=We(e),s=Tv(e,t),a=n.token??s.token??void 0,c=vr(e,s.push_cursor),p={"content-type":"application/json"};if(a)p.authorization=`Bearer ${a}`;let m=await fetch(new URL(Lh,t),{method:"POST",headers:p,body:JSON.stringify({node_id:o,since:s.pull_cursor,changes:c.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(),O=x.changes??[],F=pn(e,O),X=F.received;Rv(e,t,{pull_cursor:x.cursor,push_cursor:Av(e,c.cursor,O)});let he=Aa(t,F.skewed);if(x.skewed_rejected)he.push(`${t} refused ${x.skewed_rejected} of this device's change(s) as stamped more than 5 min in the future — run \`mh repair --clock\` here`);return{pushed:c.changes.length,pulled:X,received:O.length,...he.length?{warnings:he}:{}}}var Fh=(e)=>`${e.hlc}\x00${e.node_id}\x00${e.dataset}\x00${e.row_id}\x00${e.col}`;var xi=De(()=>{Wt();ct();Ei();Xe()});async function Uh(e,t,r,n,o=Date.now()){let s=`${t}\x00${r}`;if(o-(zh.get(s)??0)>=1e5){let m={node:r,priority:n,expiresAt:o+300000};await e.put(Ov(t,r),new TextEncoder().encode(JSON.stringify(m)),{contentType:"application/json"}),zh.set(s,o)}let a=null,c=[];for(let m of await e.list(Dv(t))){if(!m.key.endsWith(".lease"))continue;let x=await e.get(m.key);if(!x)continue;let O;try{O=JSON.parse(new TextDecoder().decode(x))}catch{continue}if(!O.node||O.expiresAt<=o){if(O.expiresAt<=o-300000)c.push(m.key);continue}if(!a||O.priority>a.priority||O.priority===a.priority&&O.node<a.node)a=O}let p=a?a.node===r:!0;if(p)for(let m of c)await e.del(m);return p}var Dv=(e)=>`${e}/publisher/`,Ov=(e,t)=>`${e}/publisher/${t}.lease`,zh;var Bh=De(()=>{zh=new Map});function er(e){let t=new Uint8Array(e.byteLength);return t.set(e),t.buffer}function ar(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return btoa(t)}function tr(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 Da(){return crypto.getRandomValues(new Uint8Array(Cv))}async function Hh(e,t){let r=await crypto.subtle.importKey("raw",er(new TextEncoder().encode(e)),"PBKDF2",!1,["deriveKey"]);return crypto.subtle.deriveKey({name:"PBKDF2",salt:er(t),iterations:jh,hash:"SHA-256"},r,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async function Wh(e,t){let r=crypto.getRandomValues(new Uint8Array(Iv)),n=await Hh(t,r),o=crypto.getRandomValues(new Uint8Array(Sn)),s=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:er(o)},n,er(e))),a=new Uint8Array(o.length+s.length);return a.set(o,0),a.set(s,o.length),{v:1,kdf:"PBKDF2-SHA256",iter:jh,salt:ar(r),wrap:"AES-GCM",wrapped_key:ar(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=tr(e.salt),n=await Hh(t,r),o=tr(e.wrapped_key),s=o.subarray(0,Sn),a=o.subarray(Sn);try{let c=await crypto.subtle.decrypt({name:"AES-GCM",iv:er(s)},n,er(a));return new Uint8Array(c)}catch{throw new Z("auth","wrong passphrase — could not unwrap the master key")}}async function Zh(e){return crypto.subtle.importKey("raw",er(e),{name:"AES-GCM"},!1,["encrypt","decrypt"])}async function mr(e,t){let r=await Zh(e),n=crypto.getRandomValues(new Uint8Array(Sn)),o=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:er(n)},r,er(t))),s=new Uint8Array(n.length+o.length);return s.set(n,0),s.set(o,n.length),s}async function Kr(e,t){let r=await Zh(e),n=t.subarray(0,Sn),o=t.subarray(Sn);try{let s=await crypto.subtle.decrypt({name:"AES-GCM",iv:er(n)},r,er(o));return new Uint8Array(s)}catch{throw new Z("auth","could not decrypt — wrong master key or corrupt data")}}var jh=600000,Iv=16,Sn=12,Cv=32;var uo=De(()=>{Xe()});function Jh(e){if(e.virtualHostedStyle!=null)return e.virtualHostedStyle;try{return new URL(e.endpoint).hostname.startsWith(`${e.bucket}.`)}catch{return!1}}function Xh(e){Ia=e}function Gt(e){if(!Ia)throw new Z("network","no S3 storage client is registered for this runtime");return Ia(e)}function po(e){let t=(e||"").replace(/^\/+|\/+$/g,"");return t?`${t}/spaces/default`:"spaces/default"}function qa(e){let t=new Uint8Array(e.byteLength);return t.set(e),t.buffer}async function Yh(e){let t=new Response(qa(e)).body.pipeThrough(new CompressionStream("gzip"));return new Uint8Array(await new Response(t).arrayBuffer())}async function eg(e){let t=new Response(qa(e)).body.pipeThrough(new DecompressionStream("gzip"));return new Uint8Array(await new Response(t).arrayBuffer())}function Uv(e){return e.map((t)=>JSON.stringify(t)).join(`
467
- `)}async function tg(e,t){let r=await Yh(new TextEncoder().encode(Uv(e)));return t?mr(t,r):r}async function rg(e,t){let r=t?await Kr(t,e):e,n=new TextDecoder().decode(await eg(r));if(!n)return[];return n.split(`
468
- `).filter((o)=>o.length>0).map((o)=>JSON.parse(o))}function ki(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 tr(e.masterKey)}async function og(e,t,r){let n=Gt(e),o=ng(po(e.prefix),t),s=ki(e),a=s?await mr(s,r):r;try{return await n.put(o,a,{ifNoneMatch:!0,contentType:"application/octet-stream"}),!0}catch(c){if(ln(c)==="conflict")return!1;throw c}}async function La(e,t){let n=await Gt(e).get(ng(po(e.prefix),t));if(!n)return null;let o=ki(e);return o?Kr(o,n):n}async function Bv(e){let t=await crypto.subtle.digest("SHA-256",qa(new TextEncoder().encode(e)));return[...new Uint8Array(t)].map((r)=>r.toString(16).padStart(2,"0")).join("").slice(0,16)}function jv(e,t){return e.query("SELECT push_cursor FROM peers WHERE url = ?").get(t)?.push_cursor??0}function Kh(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 Ma(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 Hv(e,t){let r=$a(e,t,Qh);return new Set(r?r.split(`
469
- `).filter(Boolean):[])}function Wv(e,t,r){Ma(e,t,Qh,[...r].join(`
470
- `))}function Zv(e,t=Date.now()){let r=e.query(`SELECT ${mt} FROM crdt_changes c
466
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let a of e.seen.entries()){let c=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(c.cycle){s(a);continue}if(c.count>1){if(e.reused==="ref"){s(a);continue}}}}function ba(e,t){let r=e.seen.get(t);if(!r)throw Error("Unprocessed schema. This is a bug in Zod.");let n=(c)=>{let p=e.seen.get(c);if(p.ref===null)return;let m=p.def??p.schema,x={...m},A=p.ref;if(p.ref=null,A){n(A);let X=e.seen.get(A),he=X.schema;if(he.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"))m.allOf=m.allOf??[],m.allOf.push(he);else Object.assign(m,he);if(Object.assign(m,x),c._zod.parent===A)for(let le in m){if(le==="$ref"||le==="allOf")continue;if(!(le in x))delete m[le]}if(he.$ref&&X.def)for(let le in m){if(le==="$ref"||le==="allOf")continue;if(le in X.def&&JSON.stringify(m[le])===JSON.stringify(X.def[le]))delete m[le]}}let F=c._zod.parent;if(F&&F!==A){n(F);let X=e.seen.get(F);if(X?.schema.$ref){if(m.$ref=X.schema.$ref,X.def)for(let he in m){if(he==="$ref"||he==="allOf")continue;if(he in X.def&&JSON.stringify(m[he])===JSON.stringify(X.def[he]))delete m[he]}}}e.override({zodSchema:c,jsonSchema:m,path:p.path??[]})};for(let c of[...e.seen.entries()].reverse())n(c[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 c=e.external.registry.get(t)?.id;if(!c)throw Error("Schema is missing an `id` property");o.$id=e.external.uri(c)}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 c of e.seen.entries()){let p=c[1];if(p.def&&p.defId){if(p.def.id===p.defId)delete p.def.id;a[p.defId]=p.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 c=JSON.parse(JSON.stringify(o));return Object.defineProperty(c,"~standard",{value:{...t["~standard"],jsonSchema:{input:ao(t,"input",e.processors),output:ao(t,"output",e.processors)}},enumerable:!1,writable:!1}),c}catch(c){throw Error("Error converting schema to JSON.")}}function It(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 It(n.element,r);if(n.type==="set")return It(n.valueType,r);if(n.type==="lazy")return It(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 It(n.innerType,r);if(n.type==="intersection")return It(n.left,r)||It(n.right,r);if(n.type==="record"||n.type==="map")return It(n.keyType,r)||It(n.valueType,r);if(n.type==="pipe"){if(e._zod.traits.has("$ZodCodec"))return!0;return It(n.in,r)||It(n.out,r)}if(n.type==="object"){for(let o in n.shape)if(It(n.shape[o],r))return!0;return!1}if(n.type==="union"){for(let o of n.options)if(It(o,r))return!0;return!1}if(n.type==="tuple"){for(let o of n.items)if(It(o,r))return!0;if(n.rest&&It(n.rest,r))return!0;return!1}return!1}var Mp=(e,t={})=>(r)=>{let n=_a({...r,processors:t});return mt(e,n),ya(n,e),ba(n,e)},ao=(e,t,r={})=>(n)=>{let{libraryOptions:o,target:s}=n??{},a=_a({...o??{},target:s,io:t,processors:r});return mt(e,a),ya(a,e),ba(a,e)};var vi=Ae(()=>{oa()});var Rw,Fp=(e,t,r,n)=>{let o=r;o.type="string";let{minimum:s,maximum:a,format:c,patterns:p,contentEncoding:m}=e._zod.bag;if(typeof s==="number")o.minLength=s;if(typeof a==="number")o.maxLength=a;if(c){if(o.format=Rw[c]??c,o.format==="")delete o.format;if(c==="time")delete o.format}if(m)o.contentEncoding=m;if(p&&p.size>0){let x=[...p];if(x.length===1)o.pattern=x[0].source;else if(x.length>1)o.allOf=[...x.map((A)=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:A.source}))]}},zp=(e,t,r,n)=>{let o=r,{minimum:s,maximum:a,format:c,multipleOf:p,exclusiveMaximum:m,exclusiveMinimum:x}=e._zod.bag;if(typeof c==="string"&&c.includes("int"))o.type="integer";else o.type="number";let A=typeof x==="number"&&x>=(s??Number.NEGATIVE_INFINITY),F=typeof m==="number"&&m<=(a??Number.POSITIVE_INFINITY),X=t.target==="draft-04"||t.target==="openapi-3.0";if(A)if(X)o.minimum=x,o.exclusiveMinimum=!0;else o.exclusiveMinimum=x;else if(typeof s==="number")o.minimum=s;if(F)if(X)o.maximum=m,o.exclusiveMaximum=!0;else o.exclusiveMaximum=m;else if(typeof a==="number")o.maximum=a;if(typeof p==="number")o.multipleOf=p},Up=(e,t,r,n)=>{r.type="boolean"},Bp=(e,t,r,n)=>{r.not={}},jp=(e,t,r,n)=>{},Hp=(e,t,r,n)=>{let o=e._zod.def,s=ti(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},Wp=(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}},Zp=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw Error("Custom types cannot be represented in JSON Schema")},Kp=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw Error("Transforms cannot be represented in JSON Schema")},Gp=(e,t,r,n)=>{let o=r,s=e._zod.def,{minimum:a,maximum:c}=e._zod.bag;if(typeof a==="number")o.minItems=a;if(typeof c==="number")o.maxItems=c;o.type="array",o.items=mt(s.element,t,{...n,path:[...n.path,"items"]})},Vp=(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]=mt(a[m],t,{...n,path:[...n.path,"properties",m]});let c=new Set(Object.keys(a)),p=new Set([...c].filter((m)=>{let x=s.shape[m]._zod;if(t.io==="input")return x.optin===void 0;else return x.optout===void 0}));if(p.size>0)o.required=Array.from(p);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=mt(s.catchall,t,{...n,path:[...n.path,"additionalProperties"]})},Jp=(e,t,r,n)=>{let o=e._zod.def,s=o.inclusive===!1,a=o.options.map((c,p)=>mt(c,t,{...n,path:[...n.path,s?"oneOf":"anyOf",p]}));if(s)r.oneOf=a;else r.anyOf=a},Xp=(e,t,r,n)=>{let o=e._zod.def,s=mt(o.left,t,{...n,path:[...n.path,"allOf",0]}),a=mt(o.right,t,{...n,path:[...n.path,"allOf",1]}),c=(m)=>("allOf"in m)&&Object.keys(m).length===1,p=[...c(s)?s.allOf:[s],...c(a)?a.allOf:[a]];r.allOf=p},Qp=(e,t,r,n)=>{let o=e._zod.def,s=mt(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"}]},Yp=(e,t,r,n)=>{let o=e._zod.def;mt(o.innerType,t,n);let s=t.seen.get(e);s.ref=o.innerType},eh=(e,t,r,n)=>{let o=e._zod.def;mt(o.innerType,t,n);let s=t.seen.get(e);s.ref=o.innerType,r.default=JSON.parse(JSON.stringify(o.defaultValue))},th=(e,t,r,n)=>{let o=e._zod.def;mt(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))},rh=(e,t,r,n)=>{let o=e._zod.def;mt(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},nh=(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;mt(a,t,n);let c=t.seen.get(e);c.ref=a},oh=(e,t,r,n)=>{let o=e._zod.def;mt(o.innerType,t,n);let s=t.seen.get(e);s.ref=o.innerType,r.readOnly=!0},wa=(e,t,r,n)=>{let o=e._zod.def;mt(o.innerType,t,n);let s=t.seen.get(e);s.ref=o.innerType};var ih=Ae(()=>{vi();er();Rw={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""}});var sh=()=>{};var cr=Ae(()=>{er();di();na();sh();jr();Zs();Ws();Qf();fi();Qs();oa();$p();vi()});var va=Ae(()=>{cr()});function ah(e){return xp(Nw,e)}function ch(e){return Tp(qw,e)}function lh(e){return Rp(Lw,e)}function uh(e){return Ap($w,e)}var Nw,qw,Lw,$w;var Ea=Ae(()=>{cr();Sa();Nw=ce("ZodISODateTime",(e,t)=>{_f.init(e,t),it.init(e,t)});qw=ce("ZodISODate",(e,t)=>{yf.init(e,t),it.init(e,t)});Lw=ce("ZodISOTime",(e,t)=>{bf.init(e,t),it.init(e,t)});$w=ce("ZodISODuration",(e,t)=>{wf.init(e,t),it.init(e,t)})});var Fw=(e,t)=>{ai.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:(r)=>Xu(e,r)},flatten:{value:(r)=>Ju(e,r)},addIssue:{value:(r)=>{e.issues.push(r),e.message=JSON.stringify(e.issues,to,2)}},addIssues:{value:(r)=>{e.issues.push(...r),e.message=JSON.stringify(e.issues,to,2)}},isEmpty:{get(){return e.issues.length===0}}})},Bt;var ka=Ae(()=>{cr();cr();er();Bt=ce("ZodError",Fw,{Parent:Error})});var fh,ph,hh,gh,mh,_h,yh,bh,wh,vh,Eh,Sh;var xa=Ae(()=>{cr();ka();fh=ci(Bt),ph=li(Bt),hh=ro(Bt),gh=no(Bt),mh=ed(Bt),_h=td(Bt),yh=rd(Bt),bh=nd(Bt),wh=od(Bt),vh=id(Bt),Eh=sd(Bt),Sh=ad(Bt)});function lo(e,t,r){let n=Object.getPrototypeOf(e),o=kh.get(n);if(!o)o=new Set,kh.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 c=a.bind(this);return Object.defineProperty(this,s,{configurable:!0,writable:!0,enumerable:!0,value:c}),c},set(c){Object.defineProperty(this,s,{configurable:!0,writable:!0,enumerable:!0,value:c})}})}}function dt(e){return np(Uw,e)}function uo(e){return Dp(Ch,e)}function Th(e){return Op(iv,e)}function av(e){return Ip(sv,e)}function Rh(){return Cp(cv)}function uv(e){return Pp(lv,e)}function fo(e,t){return Np(dv,e,t)}function Gr(e,t){let r={type:"object",shape:e??{},...qe(t)};return new fv(r)}function hv(e,t){return new pv({type:"union",options:e,...qe(t)})}function mv(e,t){return new gv({type:"intersection",left:e,right:t})}function Si(e,t){let r=Array.isArray(e)?Object.fromEntries(e.map((n)=>[n,n])):e;return new Ta({type:"enum",entries:r,...qe(t)})}function yv(e,t){return new _v({type:"literal",values:Array.isArray(e)?e:[e],...qe(t)})}function wv(e){return new bv({type:"transform",transform:e})}function Ah(e){return new Ph({type:"optional",innerType:e})}function Ev(e){return new vv({type:"optional",innerType:e})}function Dh(e){return new Sv({type:"nullable",innerType:e})}function xv(e,t){return new kv({type:"default",innerType:e,get defaultValue(){return typeof t==="function"?t():Bs(t)}})}function Rv(e,t){return new Tv({type:"prefault",innerType:e,get defaultValue(){return typeof t==="function"?t():Bs(t)}})}function Av(e,t){return new Nh({type:"nonoptional",innerType:e,...qe(t)})}function Ov(e,t){return new Dv({type:"catch",innerType:e,catchValue:typeof t==="function"?t:()=>t})}function Oh(e,t){return new Iv({type:"pipe",in:e,out:t})}function Pv(e){return new Cv({type:"readonly",innerType:e})}function qv(e,t={}){return qp(Nv,e,t)}function Lv(e,t){return Lp(e,t)}var kh,ut,Ih,Uw,it,Bw,xh,Ei,jw,Hw,Ww,Zw,Kw,Gw,Vw,Jw,Xw,Qw,Yw,ev,tv,rv,nv,ov,Ch,iv,sv,cv,lv,dv,fv,pv,gv,Ta,_v,bv,Ph,vv,Sv,kv,Tv,Nh,Dv,Iv,Cv,Nv;var Sa=Ae(()=>{cr();cr();ih();vi();va();Ea();xa();kh=new WeakMap;ut=ce("ZodType",(e,t)=>(ct.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:ao(e,"input"),output:ao(e,"output")}}),e.toJSONSchema=Mp(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(r,n)=>fh(e,r,n,{callee:e.parse}),e.safeParse=(r,n)=>hh(e,r,n),e.parseAsync=async(r,n)=>ph(e,r,n,{callee:e.parseAsync}),e.safeParseAsync=async(r,n)=>gh(e,r,n),e.spa=e.safeParseAsync,e.encode=(r,n)=>mh(e,r,n),e.decode=(r,n)=>_h(e,r,n),e.encodeAsync=async(r,n)=>yh(e,r,n),e.decodeAsync=async(r,n)=>bh(e,r,n),e.safeEncode=(r,n)=>wh(e,r,n),e.safeDecode=(r,n)=>vh(e,r,n),e.safeEncodeAsync=async(r,n)=>Eh(e,r,n),e.safeDecodeAsync=async(r,n)=>Sh(e,r,n),lo(e,"ZodType",{check(...r){let n=this.def;return this.clone(Rr(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 ar(this,r,n)},brand(){return this},register(r,n){return r.add(this,n),this},refine(r,n){return this.check(qv(r,n))},superRefine(r,n){return this.check(Lv(r,n))},overwrite(r){return this.check(Dr(r))},optional(){return Ah(this)},exactOptional(){return Ev(this)},nullable(){return Dh(this)},nullish(){return Ah(Dh(this))},nonoptional(r){return Av(this,r)},array(){return fo(this)},or(r){return hv([this,r])},and(r){return mv(this,r)},transform(r){return Oh(this,wv(r))},default(r){return xv(this,r)},prefault(r){return Rv(this,r)},catch(r){return Ov(this,r)},pipe(r){return Oh(this,r)},readonly(){return Pv(this)},describe(r){let n=this.clone();return Kr.add(n,{description:r}),n},meta(...r){if(r.length===0)return Kr.get(this);let n=this.clone();return Kr.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 Kr.get(e)?.description},configurable:!0}),e)),Ih=ce("_ZodString",(e,t)=>{gi.init(e,t),ut.init(e,t),e._zod.processJSONSchema=(n,o,s)=>Fp(e,n,o,s);let r=e._zod.bag;e.format=r.format??null,e.minLength=r.minimum??null,e.maxLength=r.maximum??null,lo(e,"_ZodString",{regex(...n){return this.check(sa(...n))},includes(...n){return this.check(la(...n))},startsWith(...n){return this.check(ua(...n))},endsWith(...n){return this.check(da(...n))},min(...n){return this.check(xn(...n))},max(...n){return this.check(bi(...n))},length(...n){return this.check(wi(...n))},nonempty(...n){return this.check(xn(1,...n))},lowercase(n){return this.check(aa(n))},uppercase(n){return this.check(ca(n))},trim(){return this.check(pa())},normalize(...n){return this.check(fa(...n))},toLowerCase(){return this.check(ha())},toUpperCase(){return this.check(ga())},slugify(){return this.check(ma())}})}),Uw=ce("ZodString",(e,t)=>{gi.init(e,t),Ih.init(e,t),e.email=(r)=>e.check(op(Bw,r)),e.url=(r)=>e.check(lp(jw,r)),e.jwt=(r)=>e.check(kp(ov,r)),e.emoji=(r)=>e.check(up(Hw,r)),e.guid=(r)=>e.check(ia(xh,r)),e.uuid=(r)=>e.check(ip(Ei,r)),e.uuidv4=(r)=>e.check(sp(Ei,r)),e.uuidv6=(r)=>e.check(ap(Ei,r)),e.uuidv7=(r)=>e.check(cp(Ei,r)),e.nanoid=(r)=>e.check(dp(Ww,r)),e.guid=(r)=>e.check(ia(xh,r)),e.cuid=(r)=>e.check(fp(Zw,r)),e.cuid2=(r)=>e.check(pp(Kw,r)),e.ulid=(r)=>e.check(hp(Gw,r)),e.base64=(r)=>e.check(vp(tv,r)),e.base64url=(r)=>e.check(Ep(rv,r)),e.xid=(r)=>e.check(gp(Vw,r)),e.ksuid=(r)=>e.check(mp(Jw,r)),e.ipv4=(r)=>e.check(_p(Xw,r)),e.ipv6=(r)=>e.check(yp(Qw,r)),e.cidrv4=(r)=>e.check(bp(Yw,r)),e.cidrv6=(r)=>e.check(wp(ev,r)),e.e164=(r)=>e.check(Sp(nv,r)),e.datetime=(r)=>e.check(ah(r)),e.date=(r)=>e.check(ch(r)),e.time=(r)=>e.check(lh(r)),e.duration=(r)=>e.check(uh(r))});it=ce("ZodStringFormat",(e,t)=>{nt.init(e,t),Ih.init(e,t)}),Bw=ce("ZodEmail",(e,t)=>{cf.init(e,t),it.init(e,t)}),xh=ce("ZodGUID",(e,t)=>{sf.init(e,t),it.init(e,t)}),Ei=ce("ZodUUID",(e,t)=>{af.init(e,t),it.init(e,t)}),jw=ce("ZodURL",(e,t)=>{lf.init(e,t),it.init(e,t)}),Hw=ce("ZodEmoji",(e,t)=>{uf.init(e,t),it.init(e,t)}),Ww=ce("ZodNanoID",(e,t)=>{df.init(e,t),it.init(e,t)}),Zw=ce("ZodCUID",(e,t)=>{ff.init(e,t),it.init(e,t)}),Kw=ce("ZodCUID2",(e,t)=>{pf.init(e,t),it.init(e,t)}),Gw=ce("ZodULID",(e,t)=>{hf.init(e,t),it.init(e,t)}),Vw=ce("ZodXID",(e,t)=>{gf.init(e,t),it.init(e,t)}),Jw=ce("ZodKSUID",(e,t)=>{mf.init(e,t),it.init(e,t)}),Xw=ce("ZodIPv4",(e,t)=>{vf.init(e,t),it.init(e,t)}),Qw=ce("ZodIPv6",(e,t)=>{Ef.init(e,t),it.init(e,t)}),Yw=ce("ZodCIDRv4",(e,t)=>{Sf.init(e,t),it.init(e,t)}),ev=ce("ZodCIDRv6",(e,t)=>{kf.init(e,t),it.init(e,t)}),tv=ce("ZodBase64",(e,t)=>{Tf.init(e,t),it.init(e,t)}),rv=ce("ZodBase64URL",(e,t)=>{Rf.init(e,t),it.init(e,t)}),nv=ce("ZodE164",(e,t)=>{Af.init(e,t),it.init(e,t)}),ov=ce("ZodJWT",(e,t)=>{Df.init(e,t),it.init(e,t)}),Ch=ce("ZodNumber",(e,t)=>{ea.init(e,t),ut.init(e,t),e._zod.processJSONSchema=(n,o,s)=>zp(e,n,o,s),lo(e,"ZodNumber",{gt(n,o){return this.check(_i(n,o))},gte(n,o){return this.check(so(n,o))},min(n,o){return this.check(so(n,o))},lt(n,o){return this.check(mi(n,o))},lte(n,o){return this.check(io(n,o))},max(n,o){return this.check(io(n,o))},int(n){return this.check(Th(n))},safe(n){return this.check(Th(n))},positive(n){return this.check(_i(0,n))},nonnegative(n){return this.check(so(0,n))},negative(n){return this.check(mi(0,n))},nonpositive(n){return this.check(io(0,n))},multipleOf(n,o){return this.check(yi(n,o))},step(n,o){return this.check(yi(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});iv=ce("ZodNumberFormat",(e,t)=>{Of.init(e,t),Ch.init(e,t)});sv=ce("ZodBoolean",(e,t)=>{If.init(e,t),ut.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Up(e,r,n,o)});cv=ce("ZodUnknown",(e,t)=>{Cf.init(e,t),ut.init(e,t),e._zod.processJSONSchema=(r,n,o)=>jp(e,r,n,o)});lv=ce("ZodNever",(e,t)=>{Pf.init(e,t),ut.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Bp(e,r,n,o)});dv=ce("ZodArray",(e,t)=>{Nf.init(e,t),ut.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Gp(e,r,n,o),e.element=t.element,lo(e,"ZodArray",{min(r,n){return this.check(xn(r,n))},nonempty(r){return this.check(xn(1,r))},max(r,n){return this.check(bi(r,n))},length(r,n){return this.check(wi(r,n))},unwrap(){return this.element}})});fv=ce("ZodObject",(e,t)=>{$f.init(e,t),ut.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Vp(e,r,n,o),Qe(e,"shape",()=>t.shape),lo(e,"ZodObject",{keyof(){return Si(Object.keys(this._zod.def.shape))},catchall(r){return this.clone({...this._zod.def,catchall:r})},passthrough(){return this.clone({...this._zod.def,catchall:Rh()})},loose(){return this.clone({...this._zod.def,catchall:Rh()})},strict(){return this.clone({...this._zod.def,catchall:uv()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(r){return hw(this,r)},safeExtend(r){return gw(this,r)},merge(r){return mw(this,r)},pick(r){return fw(this,r)},omit(r){return pw(this,r)},partial(...r){return _w(Ph,this,r[0])},required(...r){return yw(Nh,this,r[0])}})});pv=ce("ZodUnion",(e,t)=>{Mf.init(e,t),ut.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Jp(e,r,n,o),e.options=t.options});gv=ce("ZodIntersection",(e,t)=>{Ff.init(e,t),ut.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Xp(e,r,n,o)});Ta=ce("ZodEnum",(e,t)=>{zf.init(e,t),ut.init(e,t),e._zod.processJSONSchema=(n,o,s)=>Hp(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:[],...qe(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:[],...qe(o),entries:s})}});_v=ce("ZodLiteral",(e,t)=>{Uf.init(e,t),ut.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Wp(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]}})});bv=ce("ZodTransform",(e,t)=>{Bf.init(e,t),ut.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Kp(e,r,n,o),e._zod.parse=(r,n)=>{if(n.direction==="backward")throw new Yn(e.constructor.name);r.addIssue=(s)=>{if(typeof s==="string")r.issues.push(Zr(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(Zr(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}});Ph=ce("ZodOptional",(e,t)=>{ta.init(e,t),ut.init(e,t),e._zod.processJSONSchema=(r,n,o)=>wa(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});vv=ce("ZodExactOptional",(e,t)=>{jf.init(e,t),ut.init(e,t),e._zod.processJSONSchema=(r,n,o)=>wa(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});Sv=ce("ZodNullable",(e,t)=>{Hf.init(e,t),ut.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Qp(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});kv=ce("ZodDefault",(e,t)=>{Wf.init(e,t),ut.init(e,t),e._zod.processJSONSchema=(r,n,o)=>eh(e,r,n,o),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});Tv=ce("ZodPrefault",(e,t)=>{Zf.init(e,t),ut.init(e,t),e._zod.processJSONSchema=(r,n,o)=>th(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});Nh=ce("ZodNonOptional",(e,t)=>{Kf.init(e,t),ut.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Yp(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});Dv=ce("ZodCatch",(e,t)=>{Gf.init(e,t),ut.init(e,t),e._zod.processJSONSchema=(r,n,o)=>rh(e,r,n,o),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});Iv=ce("ZodPipe",(e,t)=>{Vf.init(e,t),ut.init(e,t),e._zod.processJSONSchema=(r,n,o)=>nh(e,r,n,o),e.in=t.in,e.out=t.out});Cv=ce("ZodReadonly",(e,t)=>{Jf.init(e,t),ut.init(e,t),e._zod.processJSONSchema=(r,n,o)=>oh(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});Nv=ce("ZodCustom",(e,t)=>{Xf.init(e,t),ut.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Zp(e,r,n,o)})});var qh;var Lh=Ae(()=>{(function(e){})(qh||(qh={}))});var $h=()=>{};var Aa=Ae(()=>{cr();cr();Yf();na();Ea();$h();Sa();va();ka();xa();Lh();Yt(ra())});var Da=Ae(()=>{Aa();Aa()});var Mh,KA,GA,Fh,VA,JA,zh="/sync",Uh="/health",Bh="/api/pair";var ki=Ae(()=>{Da();Mh=Gr({hlc:dt().describe("Hybrid Logical Clock timestamp"),node_id:dt().describe("Origin node that produced the change"),dataset:dt().describe("CRDT dataset, e.g. databases / records / documents"),row_id:dt().describe("Row identifier within the dataset"),col:dt().describe("Column / property identifier"),value:dt().nullable().describe("JSON-encoded field value, or null"),txn:dt().nullable().optional().describe("Change-group id (one logical mutation)")}),KA=Gr({node_id:dt().describe("Calling client's node id"),since:uo().describe("Server cursor the client last pulled"),changes:fo(Mh).describe("Client's changes to push"),limit:uo().optional().describe("Max changes to return (pagination for hydration)"),exclude_datasets:fo(dt()).optional().describe("Datasets to omit from the pull (partial replica)")}),GA=Gr({node_id:dt().describe("Server's node id"),changes:fo(Mh).describe("Server changes after `since`"),cursor:uo().describe("New server cursor for the client to store"),skewed_rejected:uo().optional().describe("Pushed changes the server refused for being stamped >5 min in the future")}),Fh=Gr({ok:av(),node:dt().describe("Server's node id"),capabilities:fo(dt()).optional().describe("Optional protocol features supported by this server"),version:dt().optional().describe("Core version, for mixed-version workspace warnings")}),VA=Gr({code:dt().describe("One-time pairing code minted by this server"),node_id:dt().describe("Calling device's node id"),grant:dt().describe("Durable credential the caller issues to us"),self_url:dt().optional().describe("Caller's reachable server URL (for mutual sync)")}),JA=Gr({node_id:dt().describe("This server's node id"),grant:dt().describe("Durable credential we issue to the caller")})});function Mv(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 Fv(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 Oa(e,t){return Object.entries(t).map(([r,n])=>`${e}: refused ${n} change(s) from device ${r} stamped more than 5 min in the future — run \`mh repair --clock\` on that device`)}function zv(e,t,r){if(r.length===0)return t;let n=new Set(r.map(jh)),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(jh(a)))break;s=a.seq}return s}async function xi(e,t,r={}){let n=typeof r==="string"?{token:r}:r,o=We(e),s=Mv(e,t),a=n.token??s.token??void 0,c=Er(e,s.push_cursor),p={"content-type":"application/json"};if(a)p.authorization=`Bearer ${a}`;let m=await fetch(new URL(zh,t),{method:"POST",headers:p,body:JSON.stringify({node_id:o,since:s.pull_cursor,changes:c.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 H(m.status===401||m.status===403?"auth":"network",`sync failed: ${m.status} ${await m.text()}`);let x=await m.json(),A=x.changes??[],F=mn(e,A),X=F.received;Fv(e,t,{pull_cursor:x.cursor,push_cursor:zv(e,c.cursor,A)});let he=Oa(t,F.skewed);if(x.skewed_rejected)he.push(`${t} refused ${x.skewed_rejected} of this device's change(s) as stamped more than 5 min in the future — run \`mh repair --clock\` here`);return{pushed:c.changes.length,pulled:X,received:A.length,...he.length?{warnings:he}:{}}}var jh=(e)=>`${e.hlc}\x00${e.node_id}\x00${e.dataset}\x00${e.row_id}\x00${e.col}`;var Ti=Ae(()=>{Kt();lt();ki();Xe()});async function Wh(e,t,r,n,o=Date.now()){let s=`${t}\x00${r}`;if(o-(Hh.get(s)??0)>=1e5){let m={node:r,priority:n,expiresAt:o+300000};await e.put(Bv(t,r),new TextEncoder().encode(JSON.stringify(m)),{contentType:"application/json"}),Hh.set(s,o)}let a=null,c=[];for(let m of await e.list(Uv(t))){if(!m.key.endsWith(".lease"))continue;let x=await e.get(m.key);if(!x)continue;let A;try{A=JSON.parse(new TextDecoder().decode(x))}catch{continue}if(!A.node||A.expiresAt<=o){if(A.expiresAt<=o-300000)c.push(m.key);continue}if(!a||A.priority>a.priority||A.priority===a.priority&&A.node<a.node)a=A}let p=a?a.node===r:!0;if(p)for(let m of c)await e.del(m);return p}var Uv=(e)=>`${e}/publisher/`,Bv=(e,t)=>`${e}/publisher/${t}.lease`,Hh;var Zh=Ae(()=>{Hh=new Map});function tr(e){let t=new Uint8Array(e.byteLength);return t.set(e),t.buffer}function rr(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return btoa(t)}function wt(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 Vr(e){return rr(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function po(){return crypto.getRandomValues(new Uint8Array(Hv))}async function Gh(e,t){let r=await crypto.subtle.importKey("raw",tr(new TextEncoder().encode(e)),"PBKDF2",!1,["deriveKey"]);return crypto.subtle.deriveKey({name:"PBKDF2",salt:tr(t),iterations:Kh,hash:"SHA-256"},r,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async function Vh(e,t){let r=crypto.getRandomValues(new Uint8Array(jv)),n=await Gh(t,r),o=crypto.getRandomValues(new Uint8Array(Tn)),s=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:tr(o)},n,tr(e))),a=new Uint8Array(o.length+s.length);return a.set(o,0),a.set(s,o.length),{v:1,kdf:"PBKDF2-SHA256",iter:Kh,salt:rr(r),wrap:"AES-GCM",wrapped_key:rr(a)}}async function Ia(e,t){if(e.v!==1||e.kdf!=="PBKDF2-SHA256"||e.wrap!=="AES-GCM")throw new H("invalid_input","unsupported key envelope format");let r=wt(e.salt),n=await Gh(t,r),o=wt(e.wrapped_key),s=o.subarray(0,Tn),a=o.subarray(Tn);try{let c=await crypto.subtle.decrypt({name:"AES-GCM",iv:tr(s)},n,tr(a));return new Uint8Array(c)}catch{throw new H("auth","wrong passphrase — could not unwrap the master key")}}async function Jh(e){return crypto.subtle.importKey("raw",tr(e),{name:"AES-GCM"},!1,["encrypt","decrypt"])}async function nr(e,t){let r=await Jh(e),n=crypto.getRandomValues(new Uint8Array(Tn)),o=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:tr(n)},r,tr(t))),s=new Uint8Array(n.length+o.length);return s.set(n,0),s.set(o,n.length),s}async function yr(e,t){let r=await Jh(e),n=t.subarray(0,Tn),o=t.subarray(Tn);try{let s=await crypto.subtle.decrypt({name:"AES-GCM",iv:tr(n)},r,tr(o));return new Uint8Array(s)}catch{throw new H("auth","could not decrypt — wrong master key or corrupt data")}}var Kh=600000,jv=16,Tn=12,Hv=32;var Jr=Ae(()=>{Xe()});function eg(e){if(e.virtualHostedStyle!=null)return e.virtualHostedStyle;try{return new URL(e.endpoint).hostname.startsWith(`${e.bucket}.`)}catch{return!1}}function tg(e){Ca=e}function Mt(e){if(!Ca)throw new H("network","no S3 storage client is registered for this runtime");return Ca(e)}function go(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 ng(e){let t=new Response(La(e)).body.pipeThrough(new CompressionStream("gzip"));return new Uint8Array(await new Response(t).arrayBuffer())}async function og(e){let t=new Response(La(e)).body.pipeThrough(new DecompressionStream("gzip"));return new Uint8Array(await new Response(t).arrayBuffer())}function Yv(e){return e.map((t)=>JSON.stringify(t)).join(`
467
+ `)}async function ig(e,t){let r=await ng(new TextEncoder().encode(Yv(e)));return t?nr(t,r):r}async function sg(e,t){let r=t?await yr(t,e):e,n=new TextDecoder().decode(await og(r));if(!n)return[];return n.split(`
468
+ `).filter((o)=>o.length>0).map((o)=>JSON.parse(o))}function Ri(e){if(!e.encrypt)return null;if(!e.masterKey)throw new H("invalid_input","encrypted bucket but master key missing — refusing to read/write plaintext");return wt(e.masterKey)}async function cg(e,t,r){let n=Mt(e),o=ag(go(e.prefix),t),s=Ri(e),a=s?await nr(s,r):r;try{return await n.put(o,a,{ifNoneMatch:!0,contentType:"application/octet-stream"}),!0}catch(c){if(fn(c)==="conflict")return!1;throw c}}async function $a(e,t){let n=await Mt(e).get(ag(go(e.prefix),t));if(!n)return null;let o=Ri(e);return o?yr(o,n):n}async function eE(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 tE(e,t){return e.query("SELECT push_cursor FROM peers WHERE url = ?").get(t)?.push_cursor??0}function Qh(e,t,r){e.query("UPDATE peers SET push_cursor = ? WHERE url = ?").run(r,t)}function Ma(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 rE(e,t){let r=Ma(e,t,rg);return new Set(r?r.split(`
469
+ `).filter(Boolean):[])}function nE(e,t,r){Fa(e,t,rg,[...r].join(`
470
+ `))}function oE(e,t=Date.now()){let r=e.query(`SELECT ${_t} FROM crdt_changes c
471
471
  WHERE NOT EXISTS (
472
472
  SELECT 1 FROM crdt_changes k
473
473
  WHERE k.dataset = c.dataset AND k.row_id = c.row_id AND k.col = c.col AND k.hlc > c.hlc
474
- )`).all();return ps(r,t)}function Gv(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 Kv(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 Vv(e,t){for(let r in t)if(!e[r]||e[r]<t[r])return!1;return!0}async function Jv(e,t){let r=await Yh(new TextEncoder().encode(JSON.stringify(e)));return t?mr(t,r):r}async function Xv(e,t){try{let r=t?await Kr(t,e):e;return JSON.parse(new TextDecoder().decode(await eg(r)))}catch{return null}}function Qv(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 Yv(e,t){let r=Mv(t);return Qv(await e.list(r,void 0,"/"),r)}async function Fa(e,t,r){if(!t.encrypt)return null;let n=po(t.prefix),o=zv(n),s=async(m)=>ar(await Oa(JSON.parse(new TextDecoder().decode(m)),r)),a=await e.get(o);if(a)return s(a);let c=Da(),p=await Wh(c,r);try{return await e.put(o,new TextEncoder().encode(JSON.stringify(p)),{contentType:"application/json",ifNoneMatch:!0}),ar(c)}catch(m){if(ln(m)==="conflict"){let x=await e.get(o);if(x)return s(x)}throw m}}async function Vh(e,t,r,n=Nv){let o=Date.now();fn(e,o);let s=ki(r),a=po(r.prefix),c=We(e),p=(await t.list(Pa(a,c))).map((be)=>be.key).filter((be)=>be.endsWith(".seg")).sort(),m=p.length?p[p.length-1]:null,x=Zv(e,o);if(x.length===0)return null;let O=x.reduce((be,le)=>le.hlc>be?le.hlc:be,""),F=await Bv(x.map((be)=>JSON.stringify(be)).sort().join(`
475
- `)),X=`${fo(a)}${O}${Ca}${F}.snap`;await t.put(X,await tg(x,s),{contentType:"application/octet-stream"}),await t.put(Na(X),await Jv({frontier:Gv(x),ownNode:c,ownSegHigh:m},s),{contentType:"application/octet-stream"});for(let be of await t.list(fo(a))){if(!be.key.endsWith(".snap"))continue;if(be.key.slice(fo(a).length).split(Ca)[0]<O)await t.del(be.key),await t.del(Na(be.key))}let he=p.slice(0,Math.max(0,p.length-n));for(let be of he)await t.del(be);return{key:X,changes:x.length}}function ig(e){return parseInt(e.slice(0,15),10)}function eE(e){return Date.now()-ig(e.hlc)}function tE(e,t){let r=fo(t),n=null;for(let o of e){let s=o.slice(r.length).split(Ca)[0];if(n===null||s>n)n=s}return n}async function sg(e,t,r,n,o={}){fn(e);let s=We(e),a=ki(n),c=po(n.prefix),p=jv(e,t),m=vr(e,p,{onlyNode:s}),x=0,O=!1;if(m.changes.length===0)Kh(e,t,m.cursor);else{let Oe=o.minPushChanges??1,Be=o.maxPushAgeMs??0;if(o.forcePush||m.changes.length>=Oe||eE(m.changes[0])>=Be){let He=Fv(c,s,m.cursor);await r.put(Gh(c,s),new TextEncoder().encode(He),{contentType:"text/plain"}),await r.put(He,await tg(m.changes,a),{contentType:"application/octet-stream"}),Kh(e,t,m.cursor),x=m.changes.length}else O=!0}let F=[],X=0,he={};if(o.pull??!0){F=(await r.list(fo(c))).map((Oe)=>Oe.key).filter((Oe)=>Oe.endsWith(".snap")),X+=await rE(e,t,F,r,a,he);for(let Oe of await Yv(r,c)){if(Oe===s)continue;let Be=$a(e,t,Oe),Me=await r.get(Gh(c,Oe));if(Me){let Ze=new TextDecoder().decode(Me);if(Be&&Ze<=Be)continue}let He=(await r.list(Pa(c,Oe),Be??void 0)).filter((Ze)=>Ze.key.endsWith(".seg"));for(let Ze of He){let $t=await r.get(Ze.key);if(!$t)continue;let Tt=await rg($t,a);X+=ag(he,pn(e,Tt)),Ma(e,t,Oe,Ze.key)}}}let be=!1;if(o.publish){let Oe=e.query("SELECT COUNT(*) AS n FROM crdt_changes").get().n;if(Oe>0){let Be=tE(F,c),Me=o.snapshotMinDelta??qv,He=o.snapshotDeltaRatio??Lv,Ze=o.snapshotMaxIntervalMs??$v,$t=Be===null?Oe:e.query("SELECT COUNT(*) AS n FROM crdt_changes WHERE hlc > ?").get(Be).n;if((Be===null||$t>=Math.max(Me,Oe*He)||$t>0&&Date.now()-ig(Be)>=Ze)&&await Uh(r,c,s,o.priority??0))await Vh(e,r,n,o.snapshotRetainSegments),be=!0}}if(o.publish&&!be&&x>0){let Oe=o.snapshotEverySegments??200;if((await r.list(Pa(c,s))).filter((Me)=>Me.key.endsWith(".seg")).length>=Oe)await Vh(e,r,n,o.snapshotRetainSegments)}let le=Aa(t,he);return{pushed:x,pulled:X,pendingPush:O,...le.length?{warnings:le}:{}}}function ag(e,t){for(let[r,n]of Object.entries(t.skewed))e[r]=(e[r]??0)+n;return t.received}async function rE(e,t,r,n,o,s={}){if(r.length===0)return 0;let a=Hv(e,t),c=Kv(e),p=0;for(let x of[...r].sort().reverse()){if(a.has(x))continue;let O=await n.get(Na(x)),F=O?await Xv(O,o):null;if(F&&Vv(c,F.frontier)){a.add(x);continue}let X=await n.get(x);if(!X)continue;let he=await rg(X,o);p+=ag(s,pn(e,he)),a.add(x);for(let be of he)if(!c[be.node_id]||be.hlc>c[be.node_id])c[be.node_id]=be.hlc;if(F?.ownSegHigh){let be=$a(e,t,F.ownNode);if(!be||be<F.ownSegHigh)Ma(e,t,F.ownNode,F.ownSegHigh)}}let m=new Set(r);return Wv(e,t,[...a].filter((x)=>m.has(x))),p}var Ia=null,Qh="__snapshot__",Pv=16,Ca="~",Nv=40,qv=200,Lv=0.5,$v=1800000,Mv=(e)=>`${e}/oplog/`,Pa=(e,t)=>`${e}/oplog/${t}/`,Gh=(e,t)=>`${e}/oplog/${t}/HEAD`,Fv=(e,t,r)=>`${e}/oplog/${t}/${String(r).padStart(Pv,"0")}.seg`,fo=(e)=>`${e}/snapshot/`,zv=(e)=>`${e}/keys/main.json`,ng=(e,t)=>`${e}/blobs/${t}`,Na=(e)=>`${e}.vc`;var xn=De(()=>{Wt();ct();Bh();Xe();xi();uo()});var nE=32,oE=3,YA;var cg=De(()=>{Xe();YA=(nE+oE)*8/5});var lg=De(()=>{Xe()});function iE(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 sE(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 ug(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=iE(e),o=n.filter((s)=>s.peerUrl!==t||s.requiredSeq>r.push_cursor);return sE(e,o),n.length-o.length}var fg;var dg=De(()=>{fg={name:"@tensorix/metahub",version:"0.5.4",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 za(){return{v:1,tables:[]}}function lE(e){return typeof e==="string"&&Ua.includes(e)}function pg(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=Ua.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 yr(e){if(!e)return za();let t;try{t=JSON.parse(e)}catch{return za()}try{return ho(t)}catch{return za()}}function ho(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(lE))throw new Z("invalid_input",`grant ops must be a subset of ${Ua.join("|")} (delete is never grantable)`);r.push({db:o,ops:s})}return pg(r)}function Ti(e){return JSON.stringify(pg(e.tables))}function hg(e){return e.tables.some((t)=>t.ops.some((r)=>r!=="read"))}var Ua;var Vr=De(()=>{Xe();Fr();Sr();zr();ct();Ua=["read","create","update"]});function Ba(e,t){let r=t.permission??"view";if(!uE.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 p=_g(e,n);if(p){if(p.kind!==t.kind||p.target_id!==t.target_id)throw new Z("conflict","share request id was already used for another target");return p}}let o=null;if(t.grants!=null){let p;try{p=JSON.parse(t.grants)}catch{throw new Z("invalid_input","grants must be a JSON GrantSet")}o=Ti(ho(p))}let s=vt(12);while(cr(e,s))s=vt(12);let c=r==="edit"||hg(yr(o))?"g"+vt(8):null;return e.query(`INSERT INTO shares (${go}) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(s,t.kind,t.target_id,r,"server",t.pwSalt??null,t.pwHash??null,t.expiresAt??null,c,t.servedBase??null,null,null,null,null,Date.now(),n,o),cr(e,s)}function _g(e,t){return e.query(`SELECT ${go} FROM shares WHERE request_id = ?`).get(t)??null}function cr(e,t){return e.query(`SELECT ${go} FROM shares WHERE slug = ?`).get(t)??null}function ja(e){return e.query(`SELECT ${go} FROM shares ORDER BY created_at DESC`).all()}function Ha(e,t){return e.query(`SELECT ${go} FROM shares WHERE target_id = ? ORDER BY created_at DESC`).all(t)}function rr(e,t){return e.query("DELETE FROM shares WHERE slug = ?").run(t).changes>0}function gg(e){let t=new Uint8Array(e.byteLength);return t.set(e),t.buffer}async function hE(e,t){let r=await crypto.subtle.importKey("raw",gg(new TextEncoder().encode(e)),"PBKDF2",!1,["deriveBits"]),n=await crypto.subtle.deriveBits({name:"PBKDF2",salt:gg(t),iterations:dE,hash:"SHA-256"},r,pE);return new Uint8Array(n)}async function Wa(e){let t=crypto.getRandomValues(new Uint8Array(fE)),r=await hE(e,t);return{salt:ar(t),hash:ar(r)}}var uE,go="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",dE=600000,fE=16,pE=256;var kn=De(()=>{Xe();Et();uo();Vr();uE=new Set(["doc","database","site"])});function Za(e){let t=gE;for(let r=0;r<e.length;r++)t^=BigInt(e.charCodeAt(r)),t=t*_E&mE;return t.toString(16).padStart(16,"0")}var gE=0xcbf29ce484222325n,_E=0x100000001b3n,mE=0xffffffffffffffffn;function Ga(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 bg(e,t){let r=Ga(t);return e.query(`SELECT dataset, row_id FROM (${r.sql}) ORDER BY dataset, row_id`).all(...r.params)}function Ka(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 wg(e,t,r){let n=Ga(r),o=e.query(`WITH m(dataset, row_id) AS (${n.sql})
474
+ )`).all();return gs(r,t)}function iE(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 sE(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 aE(e,t){for(let r in t)if(!e[r]||e[r]<t[r])return!1;return!0}async function cE(e,t){let r=await ng(new TextEncoder().encode(JSON.stringify(e)));return t?nr(t,r):r}async function lE(e,t){try{let r=t?await yr(t,e):e;return JSON.parse(new TextDecoder().decode(await og(r)))}catch{return null}}function uE(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 dE(e,t){let r=Jv(t);return uE(await e.list(r,void 0,"/"),r)}async function za(e,t,r){if(!t.encrypt)return null;let n=go(t.prefix),o=Qv(n),s=async(m)=>rr(await Ia(JSON.parse(new TextDecoder().decode(m)),r)),a=await e.get(o);if(a)return s(a);let c=po(),p=await Vh(c,r);try{return await e.put(o,new TextEncoder().encode(JSON.stringify(p)),{contentType:"application/json",ifNoneMatch:!0}),rr(c)}catch(m){if(fn(m)==="conflict"){let x=await e.get(o);if(x)return s(x)}throw m}}async function Yh(e,t,r,n=Zv){let o=Date.now();gn(e,o);let s=Ri(r),a=go(r.prefix),c=We(e),p=(await t.list(Na(a,c))).map((_e)=>_e.key).filter((_e)=>_e.endsWith(".seg")).sort(),m=p.length?p[p.length-1]:null,x=oE(e,o);if(x.length===0)return null;let A=x.reduce((_e,le)=>le.hlc>_e?le.hlc:_e,""),F=await eE(x.map((_e)=>JSON.stringify(_e)).sort().join(`
475
+ `)),X=`${ho(a)}${A}${Pa}${F}.snap`;await t.put(X,await ig(x,s),{contentType:"application/octet-stream"}),await t.put(qa(X),await cE({frontier:iE(x),ownNode:c,ownSegHigh:m},s),{contentType:"application/octet-stream"});for(let _e of await t.list(ho(a))){if(!_e.key.endsWith(".snap"))continue;if(_e.key.slice(ho(a).length).split(Pa)[0]<A)await t.del(_e.key),await t.del(qa(_e.key))}let he=p.slice(0,Math.max(0,p.length-n));for(let _e of he)await t.del(_e);return{key:X,changes:x.length}}function lg(e){return parseInt(e.slice(0,15),10)}function fE(e){return Date.now()-lg(e.hlc)}function pE(e,t){let r=ho(t),n=null;for(let o of e){let s=o.slice(r.length).split(Pa)[0];if(n===null||s>n)n=s}return n}async function ug(e,t,r,n,o={}){gn(e);let s=We(e),a=Ri(n),c=go(n.prefix),p=tE(e,t),m=Er(e,p,{onlyNode:s}),x=0,A=!1;if(m.changes.length===0)Qh(e,t,m.cursor);else{let Oe=o.minPushChanges??1,Be=o.maxPushAgeMs??0;if(o.forcePush||m.changes.length>=Oe||fE(m.changes[0])>=Be){let He=Xv(c,s,m.cursor);await r.put(Xh(c,s),new TextEncoder().encode(He),{contentType:"text/plain"}),await r.put(He,await ig(m.changes,a),{contentType:"application/octet-stream"}),Qh(e,t,m.cursor),x=m.changes.length}else A=!0}let F=[],X=0,he={};if(o.pull??!0){F=(await r.list(ho(c))).map((Oe)=>Oe.key).filter((Oe)=>Oe.endsWith(".snap")),X+=await hE(e,t,F,r,a,he);for(let Oe of await dE(r,c)){if(Oe===s)continue;let Be=Ma(e,t,Oe),Me=await r.get(Xh(c,Oe));if(Me){let Ze=new TextDecoder().decode(Me);if(Be&&Ze<=Be)continue}let He=(await r.list(Na(c,Oe),Be??void 0)).filter((Ze)=>Ze.key.endsWith(".seg"));for(let Ze of He){let zt=await r.get(Ze.key);if(!zt)continue;let Rt=await sg(zt,a);X+=dg(he,mn(e,Rt)),Fa(e,t,Oe,Ze.key)}}}let _e=!1;if(o.publish){let Oe=e.query("SELECT COUNT(*) AS n FROM crdt_changes").get().n;if(Oe>0){let Be=pE(F,c),Me=o.snapshotMinDelta??Kv,He=o.snapshotDeltaRatio??Gv,Ze=o.snapshotMaxIntervalMs??Vv,zt=Be===null?Oe:e.query("SELECT COUNT(*) AS n FROM crdt_changes WHERE hlc > ?").get(Be).n;if((Be===null||zt>=Math.max(Me,Oe*He)||zt>0&&Date.now()-lg(Be)>=Ze)&&await Wh(r,c,s,o.priority??0))await Yh(e,r,n,o.snapshotRetainSegments),_e=!0}}if(o.publish&&!_e&&x>0){let Oe=o.snapshotEverySegments??200;if((await r.list(Na(c,s))).filter((Me)=>Me.key.endsWith(".seg")).length>=Oe)await Yh(e,r,n,o.snapshotRetainSegments)}let le=Oa(t,he);return{pushed:x,pulled:X,pendingPush:A,...le.length?{warnings:le}:{}}}function dg(e,t){for(let[r,n]of Object.entries(t.skewed))e[r]=(e[r]??0)+n;return t.received}async function hE(e,t,r,n,o,s={}){if(r.length===0)return 0;let a=rE(e,t),c=sE(e),p=0;for(let x of[...r].sort().reverse()){if(a.has(x))continue;let A=await n.get(qa(x)),F=A?await lE(A,o):null;if(F&&aE(c,F.frontier)){a.add(x);continue}let X=await n.get(x);if(!X)continue;let he=await sg(X,o);p+=dg(s,mn(e,he)),a.add(x);for(let _e of he)if(!c[_e.node_id]||_e.hlc>c[_e.node_id])c[_e.node_id]=_e.hlc;if(F?.ownSegHigh){let _e=Ma(e,t,F.ownNode);if(!_e||_e<F.ownSegHigh)Fa(e,t,F.ownNode,F.ownSegHigh)}}let m=new Set(r);return nE(e,t,[...a].filter((x)=>m.has(x))),p}var Ca=null,rg="__snapshot__",Wv=16,Pa="~",Zv=40,Kv=200,Gv=0.5,Vv=1800000,Jv=(e)=>`${e}/oplog/`,Na=(e,t)=>`${e}/oplog/${t}/`,Xh=(e,t)=>`${e}/oplog/${t}/HEAD`,Xv=(e,t,r)=>`${e}/oplog/${t}/${String(r).padStart(Wv,"0")}.seg`,ho=(e)=>`${e}/snapshot/`,Qv=(e)=>`${e}/keys/main.json`,ag=(e,t)=>`${e}/blobs/${t}`,qa=(e)=>`${e}.vc`;var Xr=Ae(()=>{Kt();lt();Zh();Xe();Ti();Jr()});var gE=32,mE=3,gD;var fg=Ae(()=>{Xe();gD=(gE+mE)*8/5});var pg=Ae(()=>{Xe()});function _E(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 yE(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 hg(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=_E(e),o=n.filter((s)=>s.peerUrl!==t||s.requiredSeq>r.push_cursor);return yE(e,o),n.length-o.length}var mg;var gg=Ae(()=>{mg={name:"@tensorix/metahub",version:"0.5.6",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 Ua(){return{v:1,tables:[]}}function vE(e){return typeof e==="string"&&Ba.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=Ba.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 br(e){if(!e)return Ua();let t;try{t=JSON.parse(e)}catch{return Ua()}try{return mo(t)}catch{return Ua()}}function mo(e){if(typeof e!=="object"||e===null||Array.isArray(e))throw new H("invalid_input","grants must be an object {v:1, tables:[...]}");let t=e;if(t.v!==1)throw new H("invalid_input","grants version must be 1");if(!Array.isArray(t.tables))throw new H("invalid_input","grants.tables must be an array");let r=[];for(let n of t.tables){if(typeof n!=="object"||n===null)throw new H("invalid_input","each grant table must be an object {db, ops}");let{db:o,ops:s}=n;if(typeof o!=="string"||!o)throw new H("invalid_input","grant table `db` must be a database id");if(!Array.isArray(s)||!s.every(vE))throw new H("invalid_input",`grant ops must be a subset of ${Ba.join("|")} (delete is never grantable)`);r.push({db:o,ops:s})}return _g(r)}function Ai(e){return JSON.stringify(_g(e.tables))}function yg(e){return e.tables.some((t)=>t.ops.some((r)=>r!=="read"))}var Ba;var Qr=Ae(()=>{Xe();zr();kr();Ur();lt();Ba=["read","create","update"]});function ja(e,t){let r=t.permission??"view";if(!EE.has(t.kind))throw new H("invalid_input",`unknown share kind: ${t.kind}`);if(r!=="view"&&r!=="edit")throw new H("invalid_input",`unknown share permission: ${r}`);let n=t.requestId?.trim()||null;if(n&&!/^[A-Za-z0-9_-]{16,80}$/.test(n))throw new H("invalid_input","share request id is invalid");if(n){let p=wg(e,n);if(p){if(p.kind!==t.kind||p.target_id!==t.target_id)throw new H("conflict","share request id was already used for another target");return p}}let o=null;if(t.grants!=null){let p;try{p=JSON.parse(t.grants)}catch{throw new H("invalid_input","grants must be a JSON GrantSet")}o=Ai(mo(p))}let s=Et(12);while(lr(e,s))s=Et(12);let c=r==="edit"||yg(br(o))?"g"+Et(8):null;return e.query(`INSERT INTO shares (${_o}) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(s,t.kind,t.target_id,r,"server",t.pwSalt??null,t.pwHash??null,t.expiresAt??null,c,t.servedBase??null,null,null,null,null,Date.now(),n,o),lr(e,s)}function wg(e,t){return e.query(`SELECT ${_o} FROM shares WHERE request_id = ?`).get(t)??null}function lr(e,t){return e.query(`SELECT ${_o} FROM shares WHERE slug = ?`).get(t)??null}function Ha(e){return e.query(`SELECT ${_o} FROM shares ORDER BY created_at DESC`).all()}function Wa(e,t){return e.query(`SELECT ${_o} FROM shares WHERE target_id = ? ORDER BY created_at DESC`).all(t)}function or(e,t){return e.query("DELETE FROM shares WHERE slug = ?").run(t).changes>0}function bg(e){let t=new Uint8Array(e.byteLength);return t.set(e),t.buffer}async function TE(e,t){let r=await crypto.subtle.importKey("raw",bg(new TextEncoder().encode(e)),"PBKDF2",!1,["deriveBits"]),n=await crypto.subtle.deriveBits({name:"PBKDF2",salt:bg(t),iterations:SE,hash:"SHA-256"},r,xE);return new Uint8Array(n)}async function Za(e){let t=crypto.getRandomValues(new Uint8Array(kE)),r=await TE(e,t);return{salt:rr(t),hash:rr(r)}}var EE,_o="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",SE=600000,kE=16,xE=256;var Rn=Ae(()=>{Xe();St();Jr();Qr();EE=new Set(["doc","database","site"])});function Ka(e){let t=RE;for(let r=0;r<e.length;r++)t^=BigInt(e.charCodeAt(r)),t=t*AE&DE;return t.toString(16).padStart(16,"0")}var RE=0xcbf29ce484222325n,AE=0x100000001b3n,DE=0xffffffffffffffffn;function Ga(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 Sg(e,t){let r=Ga(t);return e.query(`SELECT dataset, row_id FROM (${r.sql}) ORDER BY dataset, row_id`).all(...r.params)}function Va(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 kg(e,t,r){let n=Ga(r),o=e.query(`WITH m(dataset, row_id) AS (${n.sql})
476
476
  SELECT dataset, row_id FROM m
477
477
  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})
478
478
  SELECT dataset, row_id FROM room_rows WHERE peer_key = ?
479
- EXCEPT SELECT dataset, row_id FROM m`).all(...n.params,t);return{entered:o,left:s}}function Ri(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 vg(e,t,r){e.query("DELETE FROM room_rows WHERE peer_key = ?").run(t),Ri(e,t,{entered:r,left:[]})}function Eg(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)}`:"",c=e.query(`SELECT c.seq AS seq, ${yg} FROM crdt_changes c
479
+ EXCEPT SELECT dataset, row_id FROM m`).all(...n.params,t);return{entered:o,left:s}}function Di(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 xg(e,t,r){e.query("DELETE FROM room_rows WHERE peer_key = ?").run(t),Di(e,t,{entered:r,left:[]})}function Tg(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)}`:"",c=e.query(`SELECT c.seq AS seq, ${Eg} FROM crdt_changes c
480
480
  JOIN room_rows r ON r.peer_key = ? AND r.dataset = c.dataset AND r.row_id = c.row_id
481
- WHERE ${o.join(" AND ")} ORDER BY c.seq${a}`).all(...s),p=n.limit==null||n.limit<=0||c.length<n.limit,m;if(p){let x=e.query("SELECT MAX(seq) AS m FROM crdt_changes").get();m=Math.max(t,x.m??t)}else m=c[c.length-1].seq;return{changes:c.map(({seq:x,...O})=>O),cursor:m}}function Va(e,t,r){return e.query(`SELECT ${mt} FROM crdt_changes c
481
+ WHERE ${o.join(" AND ")} ORDER BY c.seq${a}`).all(...s),p=n.limit==null||n.limit<=0||c.length<n.limit,m;if(p){let x=e.query("SELECT MAX(seq) AS m FROM crdt_changes").get();m=Math.max(t,x.m??t)}else m=c[c.length-1].seq;return{changes:c.map(({seq:x,...A})=>A),cursor:m}}function Ja(e,t,r){return e.query(`SELECT ${_t} FROM crdt_changes c
482
482
  WHERE c.dataset = ? AND c.row_id = ? AND NOT EXISTS (
483
483
  SELECT 1 FROM crdt_changes k
484
484
  WHERE k.dataset = c.dataset AND k.row_id = c.row_id AND k.col = c.col AND k.hlc > c.hlc
485
- )`).all(t,r)}function Ai(e,t){let r=Ga(t);return e.query(`WITH m(dataset, row_id) AS (${r.sql})
486
- SELECT ${yg} FROM crdt_changes c
485
+ )`).all(t,r)}function Oi(e,t){let r=Ga(t);return e.query(`WITH m(dataset, row_id) AS (${r.sql})
486
+ SELECT ${Eg} FROM crdt_changes c
487
487
  JOIN m ON m.dataset = c.dataset AND m.row_id = c.row_id
488
488
  WHERE NOT EXISTS (
489
489
  SELECT 1 FROM crdt_changes k
490
490
  WHERE k.dataset = c.dataset AND k.row_id = c.row_id AND k.col = c.col AND k.hlc > c.hlc
491
- )`).all(...r.params)}function Di(e){let t=e.map((r)=>`${r.dataset}\x00${r.row_id}\x00${r.col}\x00${r.hlc}`).sort();return Za(t.map((r)=>r+"\x1E").join(""))}var mg,yg;var Ja=De(()=>{ct();mg=["databases","properties","records","sites","site_files"],yg=$o.map((e)=>"c."+e).join(", ")});var Sg=De(()=>{Vr();kn()});var xg=De(()=>{Xe();zr();qo();ct();Et();Vr()});var Oi=1,Ii=1048576,nO;var Xa=De(()=>{Xe();jn();ct();Jo();Et();Sg();xg();Ja();nO=Object.fromEntries(mg.map((e)=>[e,e]))});function yE(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 _o(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 Qa(e,t,r){e.query("UPDATE peers SET pull_cursor = ?, push_cursor = ? WHERE url = ?").run(r.pull,r.push,t)}function Tg(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 Rg(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 c={dataset:s.dataset,row_id:s.row_id};if(Ka(e,t.scope,c))o.push(c)}return o}function bE(e,t,r){return e.transaction(()=>{let{push:o}=_o(e,t.peerKey),s=wg(e,t.peerKey,t.scope),a=Eg(e,o,t.peerKey,{limit:r,excludeGuestBase:t.guestBase}),c=[...a.changes],p=[];for(let m of s.entered){if(c.length>=r&&p.length>0)break;if(c.push(...Va(e,m.dataset,m.row_id)),p.push(m),c.length>=r)break}return{diff:s,shipped:p,changes:c,pushCursor:a.cursor,pendingBaselines:p.length<s.entered.length,incrementFull:a.changes.length>=r}})()}async function Ag(e,t,r,n={}){let o=n.limit??500;yE(e,t.peerKey);let s=_o(e,t.peerKey).pull,a=bE(e,t,o),c={protocol:Oi,mh_version:n.mhVersion,node_id:We(e),since:s,changes:a.changes,evict:a.diff.left,digest:n.digest?Di(Ai(e,t.scope)):void 0},p=await r(c);if(p.protocol!==Oi)throw new Z("conflict",`room answered protocol ${p.protocol} — upgrade required`);if(p.share_state==="expired")return{pushed:0,pulled:0,evicted:0,pending:!1,healed:!1,needBlobs:[],shareState:"expired"};Tg(p.changes,t.guestBase);let m=Gn(e,p.changes);if(st(e,()=>{Ri(e,t.peerKey,{entered:[...a.shipped,...Rg(e,t,p.changes)],left:a.diff.left}),Qa(e,t.peerKey,{pull:p.cursor,push:a.pushCursor})}),p.need_baseline.length>0)await wE(e,t,r,p.need_baseline);let x=!1;if(n.digest&&p.digest!==void 0){if(Di(Ai(e,t.scope))!==p.digest)await vE(e,t,r),x=!0}return{pushed:a.changes.length,pulled:m,evicted:a.diff.left.length,pending:a.pendingBaselines||a.incrementFull||p.more===!0,healed:x,needBlobs:p.need_blobs??[],shareState:"active"}}async function wE(e,t,r,n){let o=[],s=[],a=[];for(let p of n)if(Ka(e,t.scope,p))o.push(...Va(e,p.dataset,p.row_id)),a.push(p);else s.push(p);let c=await Dg(e,t,r,o,s);if(c.share_state==="expired")return;st(e,()=>{Ri(e,t.peerKey,{entered:[...a,...Rg(e,t,c.changes)],left:s});let p=_o(e,t.peerKey);Qa(e,t.peerKey,{pull:c.cursor,push:p.push})})}async function vE(e,t,r){let n=bg(e,t.scope),o=Ai(e,t.scope),s=await Dg(e,t,r,o,[],n);if(s.share_state==="expired")return;st(e,()=>{vg(e,t.peerKey,n);let a=_o(e,t.peerKey);Qa(e,t.peerKey,{pull:s.cursor,push:a.push})})}async function Dg(e,t,r,n,o,s){let a=await r({protocol:Oi,node_id:We(e),since:_o(e,t.peerKey).pull,changes:n,evict:o,members:s});if(a.share_state==="expired")return a;return Tg(a.changes,t.guestBase),Gn(e,a.changes),a}var kg=16;var Og=De(()=>{Xe();Wt();ct();Ja();Xa()});function Jr(e){return`${e.base.replace(/\/+$/,"")}/r/${e.slug}/`}function Cg(e){Ig=e}function Ya(e){return`room://${e}`}function ur(e,t,r,n){let o={...t,lifecycle:r,...n?{cleanupError:n}:{cleanupError:void 0}};return ec(e,{url:Ya(t.slug),config:o,label:`room ${t.slug}`}),o}function Pi(e,t){return`${e.base.replace(/\/+$/,"")}/r/${encodeURIComponent(e.slug)}/${t}`}function Ni(e,t=!0){return{authorization:`Bearer ${e.ownerSecret}`,...t?{"content-type":"application/json"}:{}}}async function Pg(e,t){try{return await fetch(Pi(e,"owner/provision"),{method:"POST",headers:Ni(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 Ng(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 EE(e){return async(t)=>{let r;try{r=await fetch(Pi(e,"owner/sync"),{method:"POST",headers:Ni(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 qi(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 lr(n).catch(()=>!1))throw new Z("network",n.cleanupError||`room ${n.slug} cleanup is still pending`);return St(e,t.url),rr(e,n.slug),Ci.delete(t.url),{pushed:0,pulled:0,pendingPush:!1}}let o=cr(e,n.slug);if(!o){if(await lr(n).catch(()=>!1))return St(e,t.url),{pushed:0,pulled:0,pendingPush:!1};throw n=ur(e,n,"cleanup_pending","share row is gone but remote room destruction is unconfirmed"),new Z("network",n.cleanupError)}if(n.lifecycle==="provisioning"){let X;try{X=await Pg(n,o)}catch(le){if(await lr(n).catch(()=>!1))St(e,t.url),rr(e,o.slug);else ur(e,n,"cleanup_pending",le.message);throw le}if(!X.ok){let le=Ng(X);if(X.status===401||X.status===404||await lr(n).catch(()=>!1))St(e,t.url),rr(e,o.slug);else ur(e,n,"cleanup_pending",le.message);throw le}let he=ur(e,n,"active"),be=xt(e,t.url);try{return await qi(e,be,r)}catch(le){if(await lr(he).catch(()=>!1))St(e,t.url),rr(e,o.slug);else ur(e,he,"cleanup_pending",le.message);throw le}}let s={grantedDbIds:yr(o.grants).tables.map((X)=>X.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 c=Ci.get(t.url)??{rounds:0,lastGrants:o.grants},p=EE(n),m=0,x=0,O=[],F=!1;for(let X=0;X<SE;X++){c.rounds++;let he=c.rounds%kg===0||c.lastGrants!==o.grants;c.lastGrants=o.grants,Ci.set(t.url,c);let be=await Ag(e,{peerKey:t.url,scope:s,guestBase:a},p,{digest:he});if(be.shareState==="expired")return await lr(n).catch(()=>{return}),St(e,t.url),{pushed:m,pulled:x,pendingPush:!1};if(m+=be.pushed,x+=be.pulled,O=be.needBlobs,F=be.pending,!be.pending)break}if(O.length>0)await xE(e,n,O,r.resolveBlob);return{pushed:m,pulled:x,pendingPush:F}}async function xE(e,t,r,n){let o=n??Ig;if(!o)return 0;let s=0;for(let a of r){if(!/^[0-9a-f]{16,64}$/.test(a))continue;let c=await o(e,a).catch(()=>null);if(!c)continue;let p=Math.max(1,Math.ceil(c.byteLength/Ii)),m=!0;for(let x=0;x<p&&m;x++){let O=c.subarray(x*Ii,(x+1)*Ii),F=new Uint8Array(O.byteLength);F.set(O),m=!!(await fetch(`${Pi(t,`owner/blob/${a}`)}?idx=${x}&total=${p}`,{method:"POST",headers:{...Ni(t,!1),"content-type":"application/octet-stream"},body:F.buffer,signal:AbortSignal.timeout(30000)}).catch(()=>null))?.ok}if(m)s++}return s}async function qg(e,t,r,n){let o={base:r.endpoint.replace(/\/+$/,""),slug:t.slug,ownerSecret:r.token,guestBase:t.guest_node_id??"g"+vt(8),lifecycle:"provisioning"},s=Ya(t.slug);ec(e,{url:s,config:o,label:`room ${t.slug}`});let a;try{a=await Pg(o,t)}catch(m){let x=m.message;if(await lr(o).catch(()=>!1))St(e,s);else ur(e,o,"cleanup_pending",x);throw m}if(!a.ok){let m=Ng(a);if(a.status===401||a.status===404)throw St(e,s),m;let x=m.message;if(await lr(o).catch(()=>!1))St(e,s);else ur(e,o,"cleanup_pending",x);throw m}let c=ur(e,o,"active"),p=xt(e,s);try{await qi(e,p,{resolveBlob:n})}catch(m){let x=m.message;if(await lr(c).catch(()=>!1))St(e,s);else ur(e,c,"cleanup_pending",x);throw m}return{url:Jr(c),peerKey:s}}async function lr(e){let t=await fetch(Pi(e,"owner/destroy"),{method:"POST",headers:Ni(e),signal:AbortSignal.timeout(30000)});return t.ok||t.status===404}async function mo(e,t){let r=xt(e,Ya(t));if(!r||r.kind!=="room"||!r.config)return"absent";let n=JSON.parse(r.config),o=ur(e,n,"cleanup_pending","remote room destruction is unconfirmed");if(!await lr(o).catch(()=>!1))return"cleanup_pending";return St(e,r.url),Ci.delete(r.url),"destroyed"}var Ig,Ci,SE=50;var Li=De(()=>{Xe();Et();kn();Vr();Tn();Og();Xa();Ci=new Map});function AE(e){let t=e.slice(e.lastIndexOf(".")+1).toLowerCase();return RE[t]??"application/octet-stream"}function nc(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 oc(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 Mg(e){return e.visibility==="public"}function nr(e,t){return e.query(`SELECT ${rc} FROM sites WHERE id = ? AND __deleted = 0`).get(t)}function Fg(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 ic(e,t){let r;try{r=nc(t)}catch{return null}return e.query(`SELECT ${rc} FROM sites WHERE name = ? AND __deleted = 0 ORDER BY created_hlc DESC LIMIT 1`).get(r)}function zg(e){return e.query(`SELECT ${rc} FROM sites WHERE __deleted = 0 ORDER BY created_hlc`).all()}function Xr(e,t){let n=(t.startsWith("site_")?nr(e,t):null)??ic(e,t);if(!n)throw new Z("not_found",`no such site: ${t}`);return n}function tc(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 Ug(e,t,r,n={}){let o=r===""||r.endsWith("/")?`${r}index.html`:r,s=oc(o);if(s){let c=tc(e,t,s);if(c)return{row:c,status:200}}if(n.spa){let c=r.split("/").pop()??"";if(!/\.[a-z0-9]+$/i.test(c)){let p=tc(e,t,"index.html");if(p)return{row:p,status:200}}}let a=tc(e,t,"404.html");if(a)return{row:a,status:404};return null}function Bg(e,t){return e.query(`SELECT id, site_id, path, content_type, encoding,
491
+ )`).all(...r.params)}function Ii(e){let t=e.map((r)=>`${r.dataset}\x00${r.row_id}\x00${r.col}\x00${r.hlc}`).sort();return Ka(t.map((r)=>r+"\x1E").join(""))}var vg,Eg;var Xa=Ae(()=>{lt();vg=["databases","properties","records","sites","site_files"],Eg=Fo.map((e)=>"c."+e).join(", ")});var Rg=Ae(()=>{Qr();Rn()});var Ag=Ae(()=>{Xe();Ur();$o();lt();St();Qr()});var Ci=1,Pi=1048576,bO;var Qa=Ae(()=>{Xe();Wn();lt();Qo();St();Rg();Ag();Xa();bO=Object.fromEntries(vg.map((e)=>[e,e]))});function OE(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 yo(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 Ya(e,t,r){e.query("UPDATE peers SET pull_cursor = ?, push_cursor = ? WHERE url = ?").run(r.pull,r.push,t)}function Og(e,t){for(let r of e)if(r.node_id!==t&&!r.node_id.startsWith(t+"-"))throw new H("auth",`room returned an op authored by ${JSON.stringify(r.node_id)} — refusing to ingest`)}function Ig(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 c={dataset:s.dataset,row_id:s.row_id};if(Va(e,t.scope,c))o.push(c)}return o}function IE(e,t,r){return e.transaction(()=>{let{push:o}=yo(e,t.peerKey),s=kg(e,t.peerKey,t.scope),a=Tg(e,o,t.peerKey,{limit:r,excludeGuestBase:t.guestBase}),c=[...a.changes],p=[];for(let m of s.entered){if(c.length>=r&&p.length>0)break;if(c.push(...Ja(e,m.dataset,m.row_id)),p.push(m),c.length>=r)break}return{diff:s,shipped:p,changes:c,pushCursor:a.cursor,pendingBaselines:p.length<s.entered.length,incrementFull:a.changes.length>=r}})()}async function Cg(e,t,r,n={}){let o=n.limit??500;OE(e,t.peerKey);let s=yo(e,t.peerKey).pull,a=IE(e,t,o),c={protocol:Ci,mh_version:n.mhVersion,node_id:We(e),since:s,changes:a.changes,evict:a.diff.left,digest:n.digest?Ii(Oi(e,t.scope)):void 0},p=await r(c);if(p.protocol!==Ci)throw new H("conflict",`room answered protocol ${p.protocol} — upgrade required`);if(p.share_state==="expired")return{pushed:0,pulled:0,evicted:0,pending:!1,healed:!1,needBlobs:[],shareState:"expired"};Og(p.changes,t.guestBase);let m=Vn(e,p.changes);if(at(e,()=>{Di(e,t.peerKey,{entered:[...a.shipped,...Ig(e,t,p.changes)],left:a.diff.left}),Ya(e,t.peerKey,{pull:p.cursor,push:a.pushCursor})}),p.need_baseline.length>0)await CE(e,t,r,p.need_baseline);let x=!1;if(n.digest&&p.digest!==void 0){if(Ii(Oi(e,t.scope))!==p.digest)await PE(e,t,r),x=!0}return{pushed:a.changes.length,pulled:m,evicted:a.diff.left.length,pending:a.pendingBaselines||a.incrementFull||p.more===!0,healed:x,needBlobs:p.need_blobs??[],shareState:"active"}}async function CE(e,t,r,n){let o=[],s=[],a=[];for(let p of n)if(Va(e,t.scope,p))o.push(...Ja(e,p.dataset,p.row_id)),a.push(p);else s.push(p);let c=await Pg(e,t,r,o,s);if(c.share_state==="expired")return;at(e,()=>{Di(e,t.peerKey,{entered:[...a,...Ig(e,t,c.changes)],left:s});let p=yo(e,t.peerKey);Ya(e,t.peerKey,{pull:c.cursor,push:p.push})})}async function PE(e,t,r){let n=Sg(e,t.scope),o=Oi(e,t.scope),s=await Pg(e,t,r,o,[],n);if(s.share_state==="expired")return;at(e,()=>{xg(e,t.peerKey,n);let a=yo(e,t.peerKey);Ya(e,t.peerKey,{pull:s.cursor,push:a.push})})}async function Pg(e,t,r,n,o,s){let a=await r({protocol:Ci,node_id:We(e),since:yo(e,t.peerKey).pull,changes:n,evict:o,members:s});if(a.share_state==="expired")return a;return Og(a.changes,t.guestBase),Vn(e,a.changes),a}var Dg=16;var Ng=Ae(()=>{Xe();Kt();lt();Xa();Qa()});function Yr(e){return`${e.base.replace(/\/+$/,"")}/r/${e.slug}/`}function Lg(e){qg=e}function ec(e){return`room://${e}`}function dr(e,t,r,n){let o={...t,lifecycle:r,...n?{cleanupError:n}:{cleanupError:void 0}};return tc(e,{url:ec(t.slug),config:o,label:`room ${t.slug}`}),o}function qi(e,t){return`${e.base.replace(/\/+$/,"")}/r/${encodeURIComponent(e.slug)}/${t}`}function Li(e,t=!0){return{authorization:`Bearer ${e.ownerSecret}`,...t?{"content-type":"application/json"}:{}}}async function $g(e,t){try{return await fetch(qi(e,"owner/provision"),{method:"POST",headers:Li(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 H("network",`edge worker unreachable: ${r.message}`)}}function Mg(e){if(e.status===401)return new H("auth","edge worker refused the owner secret");if(e.status===404)return new H("not_found","the deployed edge worker has no room support — run `mh edge deploy` to upgrade it");return new H("network",`room provisioning failed: HTTP ${e.status}`)}function NE(e){return async(t)=>{let r;try{r=await fetch(qi(e,"owner/sync"),{method:"POST",headers:Li(e),body:JSON.stringify(t),signal:AbortSignal.timeout(30000)})}catch(n){throw new H("network",`room ${e.slug} unreachable: ${n.message}`)}if(r.status===409)throw new H("conflict","room protocol outdated — run `mh edge deploy`");if(r.status===401)throw new H("auth",`room ${e.slug} refused the owner secret`);if(r.status===404)throw new H("not_found",`room ${e.slug} is not provisioned — re-create the share with --room`);if(!r.ok)throw new H("network",`room sync failed: HTTP ${r.status}`);return await r.json()}}async function $i(e,t,r={}){if(!t.config)throw new H("invalid_input",`room peer ${t.url} has no config`);let n=JSON.parse(t.config);if(n.lifecycle==="cleanup_pending"){if(!await ur(n).catch(()=>!1))throw new H("network",n.cleanupError||`room ${n.slug} cleanup is still pending`);return kt(e,t.url),or(e,n.slug),Ni.delete(t.url),{pushed:0,pulled:0,pendingPush:!1}}let o=lr(e,n.slug);if(!o){if(await ur(n).catch(()=>!1))return kt(e,t.url),{pushed:0,pulled:0,pendingPush:!1};throw n=dr(e,n,"cleanup_pending","share row is gone but remote room destruction is unconfirmed"),new H("network",n.cleanupError)}if(n.lifecycle==="provisioning"){let X;try{X=await $g(n,o)}catch(le){if(await ur(n).catch(()=>!1))kt(e,t.url),or(e,o.slug);else dr(e,n,"cleanup_pending",le.message);throw le}if(!X.ok){let le=Mg(X);if(X.status===401||X.status===404||await ur(n).catch(()=>!1))kt(e,t.url),or(e,o.slug);else dr(e,n,"cleanup_pending",le.message);throw le}let he=dr(e,n,"active"),_e=xt(e,t.url);try{return await $i(e,_e,r)}catch(le){if(await ur(he).catch(()=>!1))kt(e,t.url),or(e,o.slug);else dr(e,he,"cleanup_pending",le.message);throw le}}let s={grantedDbIds:br(o.grants).tables.map((X)=>X.db),siteId:o.kind==="site"?o.target_id:null},a=n.guestBase??o.guest_node_id;if(!a)throw new H("invalid_input",`room peer ${t.url} has no guest base id — revoke and re-create the share with --room`);let c=Ni.get(t.url)??{rounds:0,lastGrants:o.grants},p=NE(n),m=0,x=0,A=[],F=!1;for(let X=0;X<qE;X++){c.rounds++;let he=c.rounds%Dg===0||c.lastGrants!==o.grants;c.lastGrants=o.grants,Ni.set(t.url,c);let _e=await Cg(e,{peerKey:t.url,scope:s,guestBase:a},p,{digest:he});if(_e.shareState==="expired")return await ur(n).catch(()=>{return}),kt(e,t.url),{pushed:m,pulled:x,pendingPush:!1};if(m+=_e.pushed,x+=_e.pulled,A=_e.needBlobs,F=_e.pending,!_e.pending)break}if(A.length>0)await LE(e,n,A,r.resolveBlob);return{pushed:m,pulled:x,pendingPush:F}}async function LE(e,t,r,n){let o=n??qg;if(!o)return 0;let s=0;for(let a of r){if(!/^[0-9a-f]{16,64}$/.test(a))continue;let c=await o(e,a).catch(()=>null);if(!c)continue;let p=Math.max(1,Math.ceil(c.byteLength/Pi)),m=!0;for(let x=0;x<p&&m;x++){let A=c.subarray(x*Pi,(x+1)*Pi),F=new Uint8Array(A.byteLength);F.set(A),m=!!(await fetch(`${qi(t,`owner/blob/${a}`)}?idx=${x}&total=${p}`,{method:"POST",headers:{...Li(t,!1),"content-type":"application/octet-stream"},body:F.buffer,signal:AbortSignal.timeout(30000)}).catch(()=>null))?.ok}if(m)s++}return s}async function Fg(e,t,r,n){let o={base:r.endpoint.replace(/\/+$/,""),slug:t.slug,ownerSecret:r.token,guestBase:t.guest_node_id??"g"+Et(8),lifecycle:"provisioning"},s=ec(t.slug);tc(e,{url:s,config:o,label:`room ${t.slug}`});let a;try{a=await $g(o,t)}catch(m){let x=m.message;if(await ur(o).catch(()=>!1))kt(e,s);else dr(e,o,"cleanup_pending",x);throw m}if(!a.ok){let m=Mg(a);if(a.status===401||a.status===404)throw kt(e,s),m;let x=m.message;if(await ur(o).catch(()=>!1))kt(e,s);else dr(e,o,"cleanup_pending",x);throw m}let c=dr(e,o,"active"),p=xt(e,s);try{await $i(e,p,{resolveBlob:n})}catch(m){let x=m.message;if(await ur(c).catch(()=>!1))kt(e,s);else dr(e,c,"cleanup_pending",x);throw m}return{url:Yr(c),peerKey:s}}async function ur(e){let t=await fetch(qi(e,"owner/destroy"),{method:"POST",headers:Li(e),signal:AbortSignal.timeout(30000)});return t.ok||t.status===404}async function bo(e,t){let r=xt(e,ec(t));if(!r||r.kind!=="room"||!r.config)return"absent";let n=JSON.parse(r.config),o=dr(e,n,"cleanup_pending","remote room destruction is unconfirmed");if(!await ur(o).catch(()=>!1))return"cleanup_pending";return kt(e,r.url),Ni.delete(r.url),"destroyed"}var qg,Ni,qE=50;var Mi=Ae(()=>{Xe();St();Rn();Qr();An();Ng();Qa();Ni=new Map});function zE(e){let t=e.slice(e.lastIndexOf(".")+1).toLowerCase();return FE[t]??"application/octet-stream"}function oc(e){let t=e.trim().toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^-+|-+$/g,"");if(!t)throw new H("invalid_input",`invalid site name: ${JSON.stringify(e)}`);return t}function ic(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 Bg(e){return e.visibility==="public"}function ir(e,t){return e.query(`SELECT ${nc} FROM sites WHERE id = ? AND __deleted = 0`).get(t)}function jg(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 sc(e,t){let r;try{r=oc(t)}catch{return null}return e.query(`SELECT ${nc} FROM sites WHERE name = ? AND __deleted = 0 ORDER BY created_hlc DESC LIMIT 1`).get(r)}function Hg(e){return e.query(`SELECT ${nc} FROM sites WHERE __deleted = 0 ORDER BY created_hlc`).all()}function en(e,t){let n=(t.startsWith("site_")?ir(e,t):null)??sc(e,t);if(!n)throw new H("not_found",`no such site: ${t}`);return n}function rc(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 Wg(e,t,r,n={}){let o=r===""||r.endsWith("/")?`${r}index.html`:r,s=ic(o);if(s){let c=rc(e,t,s);if(c)return{row:c,status:200}}if(n.spa){let c=r.split("/").pop()??"";if(!/\.[a-z0-9]+$/i.test(c)){let p=rc(e,t,"index.html");if(p)return{row:p,status:200}}}let a=rc(e,t,"404.html");if(a)return{row:a,status:404};return null}function Zg(e,t){return e.query(`SELECT id, site_id, path, content_type, encoding,
492
492
  CASE encoding
493
493
  WHEN 'utf8' THEN LENGTH(CAST(content AS BLOB))
494
494
  WHEN 'base64' THEN (LENGTH(content) / 4) * 3
495
495
  ELSE (SELECT size FROM blob_cache WHERE hash = content)
496
496
  END AS size
497
- FROM site_files WHERE site_id = ? AND __deleted = 0 ORDER BY path`).all(t)}function jg(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 OE(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 Lg(e){if(typeof e==="string")return new TextEncoder().encode(e);return e instanceof Uint8Array?e:new Uint8Array(e)}function IE(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return btoa(t)}function Hg(e){if(e!=="public"&&e!=="private")throw new Z("invalid_input",`visibility must be "public" or "private", got ${JSON.stringify(e)}`)}function Kg(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 CE(e,t,r,n,o,s){let a=e.query(`SELECT ${$g} 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 PE(e,t,r,n,o,s){let a=CE(e,t,r,n,o,s);if(a)return{...a,changed:!1};let c=Kg(e,t,r),p=c??Nt("sf",r);return Xt(e,null,()=>{if(!c){let x=_e(e,"site_files",p,"site_id",t);_e(e,"site_files",p,"path",r),_e(e,"site_files",p,"created_hlc",x.hlc)}_e(e,"site_files",p,"content_type",n),_e(e,"site_files",p,"encoding",o),_e(e,"site_files",p,"content",s),_e(e,"site_files",p,"__deleted",0)}),{...e.query(`SELECT ${$g} FROM site_files WHERE id = ?`).get(p),changed:!0}}function Vg(e,t,r,n){let o=oc(r);if(!o)throw new Z("invalid_input",`invalid file path: ${JSON.stringify(r)}`);let s=n.contentType??AE(o),a,c;if(OE(s))a="utf8",c=typeof n.data==="string"?n.data:new TextDecoder().decode(Lg(n.data));else{let p=Lg(n.data);if(p.byteLength>DE)throw new Z("invalid_input","binary too large for inline storage (needs a server-backed blob)");a="base64",c=IE(p)}return PE(e,t,o,s,a,c)}function Xg(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 Qg(e,t){return e.query("SELECT COUNT(*) AS n FROM site_files WHERE site_id = ? AND __deleted = 0").get(t).n}var kE,rc,TE,$g,RE,DE=262144,Wg,$i,Zg,Gg,Jg;var Rn=De(()=>{Xe();ct();Et();Vr();kE=["id","name","title","created_hlc","visibility","spa","public_grants"],rc=kE.join(", "),TE=["id","site_id","path","content_type","encoding","content"],$g=TE.join(", "),RE={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"};Wg=Fe(function(t,r){let n=nc(r.name);if(ic(t,n))throw new Z("conflict",`site name already exists: ${n}`);if(r.visibility!==void 0)Hg(r.visibility);let o=Nt("site",n),s=_e(t,"sites",o,"name",n);if(_e(t,"sites",o,"created_hlc",s.hlc),r.title!==void 0)_e(t,"sites",o,"title",r.title);if(r.visibility!==void 0)_e(t,"sites",o,"visibility",r.visibility);return nr(t,o)}),$i=Fe(function(t,r,n){if(!nr(t,r))throw new Z("not_found",`no such site: ${r}`);if(n.visibility!==void 0)Hg(n.visibility);if(n.name!==void 0){let o=nc(n.name),s=ic(t,o);if(s&&s.id!==r)throw new Z("conflict",`site name already exists: ${o}`);_e(t,"sites",r,"name",o)}if(n.title!==void 0)_e(t,"sites",r,"title",n.title);if(n.visibility!==void 0)_e(t,"sites",r,"visibility",n.visibility);if(n.spa!==void 0)_e(t,"sites",r,"spa",n.spa?1:0);return nr(t,r)}),Zg=Fe(function(t,r,n){if(!nr(t,r))throw new Z("not_found",`no such site: ${r}`);let o=n==null?null:Ti(ho(n));return _e(t,"sites",r,"public_grants",o),nr(t,r)}),Gg=Fe(function(t,r){if(!nr(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)_e(t,"site_files",o.id,"__deleted",1);return _e(t,"sites",r,"__deleted",1),!0});Jg=Fe(function(t,r,n){let o=Kg(t,r,oc(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 _e(t,"site_files",o,"__deleted",1),!0})});function sc(e){return(e.audience==="public"||e.audience==="link")&&(e.hosting==="device"||e.hosting==="edge")&&(e.desired_state==="active"||e.desired_state==="revoked")}function Kt(e,t){return(t?e.query(`SELECT ${yo} FROM site_channels
498
- WHERE site_id = ? AND __deleted = 0 ORDER BY created_hlc, id`).all(t):e.query(`SELECT ${yo} FROM site_channels
499
- WHERE __deleted = 0 ORDER BY created_hlc, id`).all()).filter(sc)}function An(e,t){let r=e.query(`SELECT ${yo} FROM site_channels WHERE id = ? AND __deleted = 0`).get(t);return r&&sc(r)?r:null}function qE(e,t){let r=Kt(e,t).filter((n)=>n.audience==="public"&&n.desired_state==="active");for(let n of r)br(e,n.id,"revoked");return r.length}function Yg(e,t,r){let n=Kt(e,t).filter((o)=>o.audience==="public"&&o.desired_state==="active");for(let o of n)bo(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 LE(e){if(e==null)return null;try{return JSON.parse(e)}catch{return null}}function $E(e,t,r){let n=Kt(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 c=new URL(s.canonical_url);c.pathname=`/sites/${encodeURIComponent(r)}/`,c.search="",c.hash="",a=c.toString()}catch{continue}bo(e,{id:s.id,siteId:s.site_id,audience:"public",hosting:"device",controllerNodeId:s.controller_node_id,targetRef:s.target_ref,canonicalUrl:a,policy:LE(s.policy_json),desiredState:"active"}),o++}return o}function e_(e,t,r,n){return Xt(e,"site.update",()=>{let o=$i(e,t,{...r,visibility:r.visibility==="public"?"private":r.visibility});if(r.visibility==="private")qE(e,t);if(r.visibility==="public")n?.recordPublic?.(o);if(r.name!==void 0)$E(e,t,o.name);return nr(e,t)})}function t_(e,t){return Xt(e,"site.delete",()=>{if(!Gg(e,t))return!1;return ME(e,t),!0})}function ME(e,t){let r=Kt(e,t).filter((n)=>n.desired_state==="active");for(let n of r)br(e,n.id,"revoked");return r.length}function It(e,t){return e.query(`INSERT INTO site_channel_observations
497
+ FROM site_files WHERE site_id = ? AND __deleted = 0 ORDER BY path`).all(t)}function Kg(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 BE(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 zg(e){if(typeof e==="string")return new TextEncoder().encode(e);return e instanceof Uint8Array?e:new Uint8Array(e)}function jE(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return btoa(t)}function Gg(e){if(e!=="public"&&e!=="private")throw new H("invalid_input",`visibility must be "public" or "private", got ${JSON.stringify(e)}`)}function Qg(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 HE(e,t,r,n,o,s){let a=e.query(`SELECT ${Ug} 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 WE(e,t,r,n,o,s){let a=HE(e,t,r,n,o,s);if(a)return{...a,changed:!1};let c=Qg(e,t,r),p=c??qt("sf",r);return Qt(e,null,()=>{if(!c){let x=me(e,"site_files",p,"site_id",t);me(e,"site_files",p,"path",r),me(e,"site_files",p,"created_hlc",x.hlc)}me(e,"site_files",p,"content_type",n),me(e,"site_files",p,"encoding",o),me(e,"site_files",p,"content",s),me(e,"site_files",p,"__deleted",0)}),{...e.query(`SELECT ${Ug} FROM site_files WHERE id = ?`).get(p),changed:!0}}function Yg(e,t,r,n){let o=ic(r);if(!o)throw new H("invalid_input",`invalid file path: ${JSON.stringify(r)}`);let s=n.contentType??zE(o),a,c;if(BE(s))a="utf8",c=typeof n.data==="string"?n.data:new TextDecoder().decode(zg(n.data));else{let p=zg(n.data);if(p.byteLength>UE)throw new H("invalid_input","binary too large for inline storage (needs a server-backed blob)");a="base64",c=jE(p)}return WE(e,t,o,s,a,c)}function tm(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 rm(e,t){return e.query("SELECT COUNT(*) AS n FROM site_files WHERE site_id = ? AND __deleted = 0").get(t).n}var $E,nc,ME,Ug,FE,UE=262144,Vg,Fi,Jg,Xg,em;var Dn=Ae(()=>{Xe();lt();St();Qr();$E=["id","name","title","created_hlc","visibility","spa","public_grants"],nc=$E.join(", "),ME=["id","site_id","path","content_type","encoding","content"],Ug=ME.join(", "),FE={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"};Vg=Fe(function(t,r){let n=oc(r.name);if(sc(t,n))throw new H("conflict",`site name already exists: ${n}`);if(r.visibility!==void 0)Gg(r.visibility);let o=qt("site",n),s=me(t,"sites",o,"name",n);if(me(t,"sites",o,"created_hlc",s.hlc),r.title!==void 0)me(t,"sites",o,"title",r.title);if(r.visibility!==void 0)me(t,"sites",o,"visibility",r.visibility);return ir(t,o)}),Fi=Fe(function(t,r,n){if(!ir(t,r))throw new H("not_found",`no such site: ${r}`);if(n.visibility!==void 0)Gg(n.visibility);if(n.name!==void 0){let o=oc(n.name),s=sc(t,o);if(s&&s.id!==r)throw new H("conflict",`site name already exists: ${o}`);me(t,"sites",r,"name",o)}if(n.title!==void 0)me(t,"sites",r,"title",n.title);if(n.visibility!==void 0)me(t,"sites",r,"visibility",n.visibility);if(n.spa!==void 0)me(t,"sites",r,"spa",n.spa?1:0);return ir(t,r)}),Jg=Fe(function(t,r,n){if(!ir(t,r))throw new H("not_found",`no such site: ${r}`);let o=n==null?null:Ai(mo(n));return me(t,"sites",r,"public_grants",o),ir(t,r)}),Xg=Fe(function(t,r){if(!ir(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)me(t,"site_files",o.id,"__deleted",1);return me(t,"sites",r,"__deleted",1),!0});em=Fe(function(t,r,n){let o=Qg(t,r,ic(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 me(t,"site_files",o,"__deleted",1),!0})});function ac(e){return(e.audience==="public"||e.audience==="link")&&(e.hosting==="device"||e.hosting==="edge")&&(e.desired_state==="active"||e.desired_state==="revoked")}function Vt(e,t){return(t?e.query(`SELECT ${wo} FROM site_channels
498
+ WHERE site_id = ? AND __deleted = 0 ORDER BY created_hlc, id`).all(t):e.query(`SELECT ${wo} FROM site_channels
499
+ WHERE __deleted = 0 ORDER BY created_hlc, id`).all()).filter(ac)}function On(e,t){let r=e.query(`SELECT ${wo} FROM site_channels WHERE id = ? AND __deleted = 0`).get(t);return r&&ac(r)?r:null}function KE(e,t){let r=Vt(e,t).filter((n)=>n.audience==="public"&&n.desired_state==="active");for(let n of r)wr(e,n.id,"revoked");return r.length}function nm(e,t,r){let n=Vt(e,t).filter((o)=>o.audience==="public"&&o.desired_state==="active");for(let o of n)vo(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 GE(e){if(e==null)return null;try{return JSON.parse(e)}catch{return null}}function VE(e,t,r){let n=Vt(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 c=new URL(s.canonical_url);c.pathname=`/sites/${encodeURIComponent(r)}/`,c.search="",c.hash="",a=c.toString()}catch{continue}vo(e,{id:s.id,siteId:s.site_id,audience:"public",hosting:"device",controllerNodeId:s.controller_node_id,targetRef:s.target_ref,canonicalUrl:a,policy:GE(s.policy_json),desiredState:"active"}),o++}return o}function om(e,t,r,n){return Qt(e,"site.update",()=>{let o=Fi(e,t,{...r,visibility:r.visibility==="public"?"private":r.visibility});if(r.visibility==="private")KE(e,t);if(r.visibility==="public")n?.recordPublic?.(o);if(r.name!==void 0)VE(e,t,o.name);return ir(e,t)})}function im(e,t){return Qt(e,"site.delete",()=>{if(!Xg(e,t))return!1;return JE(e,t),!0})}function JE(e,t){let r=Vt(e,t).filter((n)=>n.desired_state==="active");for(let n of r)wr(e,n.id,"revoked");return r.length}function Ct(e,t){return e.query(`INSERT INTO site_channel_observations
500
500
  (channel_id,status,last_verified_at,last_error)
501
501
  VALUES (?,?,?,?)
502
502
  ON CONFLICT(channel_id) DO UPDATE SET
503
503
  status=excluded.status,
504
504
  last_verified_at=excluded.last_verified_at,
505
- 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 r_(e,t){e.query("DELETE FROM site_channel_observations WHERE channel_id = ?").run(t)}function Mi(e,t){let r=e.query(`SELECT channel_id,status,last_verified_at,last_error
506
- 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 ac(e,t){let r=We(e);return Kt(e,t).map((n)=>{let o=Mi(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 n_(e,t){let r=e.query(`SELECT ${yo} FROM site_channels
507
- WHERE site_id = ? AND audience = 'public' AND __deleted = 0 ORDER BY created_hlc, id`).all(t.id);if(r.length===0){let a=Mg(t);return{serving:a,configured:a,anomaly:null}}let n=r.filter(sc),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 NE,yo,bo,br;var wo=De(()=>{ct();Xe();Et();Wt();Rn();NE=["id","site_id","audience","hosting","controller_node_id","target_ref","canonical_url","policy_json","desired_state","created_hlc","__deleted"],yo=NE.join(", ");bo=Fe(function(t,r){if(!nr(t,r.siteId))throw new Z("not_found",`no such site: ${r.siteId}`);let n=r.controllerNodeId??We(t),o=r.id?An(t,r.id):t.query(`SELECT ${yo} FROM site_channels
505
+ 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 sm(e,t){e.query("DELETE FROM site_channel_observations WHERE channel_id = ?").run(t)}function zi(e,t){let r=e.query(`SELECT channel_id,status,last_verified_at,last_error
506
+ 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 cc(e,t){let r=We(e);return Vt(e,t).map((n)=>{let o=zi(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 am(e,t){let r=e.query(`SELECT ${wo} FROM site_channels
507
+ WHERE site_id = ? AND audience = 'public' AND __deleted = 0 ORDER BY created_hlc, id`).all(t.id);if(r.length===0){let a=Bg(t);return{serving:a,configured:a,anomaly:null}}let n=r.filter(ac),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 ZE,wo,vo,wr;var Eo=Ae(()=>{lt();Xe();St();Kt();Dn();ZE=["id","site_id","audience","hosting","controller_node_id","target_ref","canonical_url","policy_json","desired_state","created_hlc","__deleted"],wo=ZE.join(", ");vo=Fe(function(t,r){if(!ir(t,r.siteId))throw new H("not_found",`no such site: ${r.siteId}`);let n=r.controllerNodeId??We(t),o=r.id?On(t,r.id):t.query(`SELECT ${wo} FROM site_channels
508
508
  WHERE site_id = ? AND audience = ? AND hosting = ? AND target_ref = ?
509
509
  AND __deleted = 0
510
- ORDER BY created_hlc LIMIT 1`).get(r.siteId,r.audience,r.hosting,r.targetRef),s=o?.id??Nt("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 st(t,()=>{if(!o){let c=_e(t,"site_channels",s,"site_id",r.siteId);_e(t,"site_channels",s,"created_hlc",c.hlc)}for(let[c,p]of Object.entries(a)){if(o&&o[c]===p)continue;_e(t,"site_channels",s,c,p)}}),An(t,s)}),br=Fe(function(t,r,n){if(!An(t,r))throw new Z("not_found",`no such site channel: ${r}`);return _e(t,"site_channels",r,"desired_state",n),An(t,r)})});async function Dn(e){try{return await FE(e),null}catch(t){let r=t instanceof Error?t.message:String(t);return console.error(`site channel reconcile failed: ${r}`),r}}async function FE(e){let t=We(e),r=Kt(e),n=new Set;for(let s of r){if(s.desired_state!=="active")continue;if(Fg(e,s.site_id)==="tombstoned"){br(e,s.id,"revoked"),n.add(s.id);continue}if(s.audience!=="link"||s.controller_node_id!==t)continue;if(!cr(e,s.target_ref))It(e,{channelId:s.id,status:"error",lastError:`${o_}: 本机缺少该链接的凭据记录`});else if(Mi(e,s.id)?.lastError?.startsWith(o_))r_(e,s.id)}let o=r.map((s)=>n.has(s.id)?An(e,s.id)??s:s).filter((s)=>s.controller_node_id===t&&s.desired_state==="revoked"&&s.audience==="link"&&!(s.hosting==="edge"&&Mi(e,s.id)?.status==="revoked"));for(let s of o){let a=cr(e,s.target_ref);try{if(s.hosting==="edge"){await Promise.resolve().then(() => Li());let p=await mo(e,s.target_ref);if(p==="cleanup_pending"){It(e,{channelId:s.id,status:"cleanup_pending",lastError:"Edge 尚未确认销毁 Room"});continue}if(p==="absent"){It(e,{channelId:s.id,status:"cleanup_pending",lastError:"Edge Room 记录缺失,销毁未确认"});continue}}else if(!a){It(e,{channelId:s.id,status:"revoked",lastVerifiedAt:Date.now()});continue}if(a)rr(e,a.slug);It(e,{channelId:s.id,status:"revoked",lastVerifiedAt:Date.now()})}catch(c){It(e,{channelId:s.id,status:"cleanup_pending",lastError:c instanceof Error?c.message:String(c)})}}}var o_="controller_state_missing";var cc=De(()=>{Wt();wo();kn();Rn()});function Lt(e){return e.query(`SELECT ${a_} FROM peers ORDER BY url`).all()}function xt(e,t){return e.query(`SELECT ${a_} FROM peers WHERE url = ?`).get(t)??null}function c_(e,t){e.query(`INSERT INTO peers (url, token, label, node_id, enabled, pull_cursor, push_cursor)
510
+ ORDER BY created_hlc LIMIT 1`).get(r.siteId,r.audience,r.hosting,r.targetRef),s=o?.id??qt("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 at(t,()=>{if(!o){let c=me(t,"site_channels",s,"site_id",r.siteId);me(t,"site_channels",s,"created_hlc",c.hlc)}for(let[c,p]of Object.entries(a)){if(o&&o[c]===p)continue;me(t,"site_channels",s,c,p)}}),On(t,s)}),wr=Fe(function(t,r,n){if(!On(t,r))throw new H("not_found",`no such site channel: ${r}`);return me(t,"site_channels",r,"desired_state",n),On(t,r)})});async function In(e){try{return await XE(e),null}catch(t){let r=t instanceof Error?t.message:String(t);return console.error(`site channel reconcile failed: ${r}`),r}}async function XE(e){let t=We(e),r=Vt(e),n=new Set;for(let s of r){if(s.desired_state!=="active")continue;if(jg(e,s.site_id)==="tombstoned"){wr(e,s.id,"revoked"),n.add(s.id);continue}if(s.audience!=="link"||s.controller_node_id!==t)continue;if(!lr(e,s.target_ref))Ct(e,{channelId:s.id,status:"error",lastError:`${cm}: 本机缺少该链接的凭据记录`});else if(zi(e,s.id)?.lastError?.startsWith(cm))sm(e,s.id)}let o=r.map((s)=>n.has(s.id)?On(e,s.id)??s:s).filter((s)=>s.controller_node_id===t&&s.desired_state==="revoked"&&s.audience==="link"&&!(s.hosting==="edge"&&zi(e,s.id)?.status==="revoked"));for(let s of o){let a=lr(e,s.target_ref);try{if(s.hosting==="edge"){await Promise.resolve().then(() => Mi());let p=await bo(e,s.target_ref);if(p==="cleanup_pending"){Ct(e,{channelId:s.id,status:"cleanup_pending",lastError:"Edge 尚未确认销毁 Room"});continue}if(p==="absent"){Ct(e,{channelId:s.id,status:"cleanup_pending",lastError:"Edge Room 记录缺失,销毁未确认"});continue}}else if(!a){Ct(e,{channelId:s.id,status:"revoked",lastVerifiedAt:Date.now()});continue}if(a)or(e,a.slug);Ct(e,{channelId:s.id,status:"revoked",lastVerifiedAt:Date.now()})}catch(c){Ct(e,{channelId:s.id,status:"cleanup_pending",lastError:c instanceof Error?c.message:String(c)})}}}var cm="controller_state_missing";var lc=Ae(()=>{Kt();Eo();Rn();Dn()});function Ft(e){return e.query(`SELECT ${dm} FROM peers ORDER BY url`).all()}function xt(e,t){return e.query(`SELECT ${dm} FROM peers WHERE url = ?`).get(t)??null}function fm(e,t){e.query(`INSERT INTO peers (url, token, label, node_id, enabled, pull_cursor, push_cursor)
511
511
  VALUES (?, ?, ?, ?, 1, 0, 0)
512
512
  ON CONFLICT(url) DO UPDATE SET
513
513
  token = coalesce(excluded.token, peers.token),
514
514
  label = coalesce(excluded.label, peers.label),
515
515
  node_id = coalesce(excluded.node_id, peers.node_id),
516
- enabled = 1`).run(t.url,t.token??null,t.label??null,t.node_id??null)}function l_(e,t){e.query(`INSERT INTO peers (url, kind, config, label, enabled, pull_cursor, push_cursor)
516
+ enabled = 1`).run(t.url,t.token??null,t.label??null,t.node_id??null)}function pm(e,t){e.query(`INSERT INTO peers (url, kind, config, label, enabled, pull_cursor, push_cursor)
517
517
  VALUES (?, 's3', ?, ?, 1, 0, 0)
518
518
  ON CONFLICT(url) DO UPDATE SET
519
519
  kind = 's3',
520
520
  config = excluded.config,
521
521
  label = coalesce(excluded.label, peers.label),
522
- enabled = 1`).run(t.url,JSON.stringify(t.config),t.label??null)}function ec(e,t){e.query(`INSERT INTO peers (url, kind, config, label, enabled, pull_cursor, push_cursor)
522
+ enabled = 1`).run(t.url,JSON.stringify(t.config),t.label??null)}function tc(e,t){e.query(`INSERT INTO peers (url, kind, config, label, enabled, pull_cursor, push_cursor)
523
523
  VALUES (?, 'room', ?, ?, 1, 0, 0)
524
524
  ON CONFLICT(url) DO UPDATE SET
525
525
  kind = 'room',
526
526
  config = excluded.config,
527
527
  label = coalesce(excluded.label, peers.label),
528
- enabled = 1`).run(t.url,JSON.stringify(t.config),t.label??null)}function St(e,t){return st(e,()=>{let r=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),r})}function s_(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 lc(e,t,r){let n=i_.get(e);if(!n)n=new Map,i_.set(e,n);let o=n.get(t);if(o)return o;let s=BE(e,t,r).finally(()=>{if(n.get(t)===s)n.delete(t)});return n.set(t,s),s}function zE(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 UE(e){try{let t=await fetch(new URL($h,e),{signal:AbortSignal.timeout(5000)});if(!t.ok)return null;let r=qh.safeParse(await t.json());return r.success?r.data:null}catch{return null}}async function BE(e,t,r){try{let n=xt(e,t),o;if(n?.kind==="s3"){if(!n.config)throw Error(`storage peer ${t} has no config`);let p=JSON.parse(n.config),m={...r?.storage,publish:r?.storage?.publish??p.publish,priority:r?.storage?.priority??p.priority};o=await sg(e,t,Gt(p),p,m)}else if(n?.kind==="room"){await Promise.resolve().then(() => Li());o=await qi(e,n)}else o=await Si(e,t,{timeoutMs:r?.timeoutMs});s_(e,t,"ok",null);let s=[...o.warnings??[]];try{if(n?.kind!=="s3"&&n?.kind!=="room")ug(e,t)}catch(p){s.push(`site rollback bookkeeping failed: ${p.message}`)}if(n?.kind!=="s3"&&n?.kind!=="room"){let p=zE(fg.version,await UE(t));if(p)s.push(`${t}: ${p}`)}await Promise.resolve().then(() => cc());let c=await Dn(e);if(c)s.push(`site channel reconcile failed: ${c}`);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 s_(e,t,"error",o),{url:t,ok:!1,error:o}}}var a_="url, pull_cursor, push_cursor, token, label, node_id, enabled, last_sync_at, last_success_at, last_status, last_error, kind, config",i_;var Tn=De(()=>{Xe();xi();Jn();xn();cg();lg();uo();Ei();dg();Jn();i_=new WeakMap});class pc{constructor({accessKeyId:e,secretAccessKey:t,sessionToken:r,service:n,region:o,cache:s,retries:a,initRetryMs:c}){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=c||50}async sign(e,t){if(e instanceof Request){let{method:o,url:s,headers:a,body:c}=e;if(t=Object.assign({method:o,url:s,headers:a},t),t.body==null&&a.has("Content-Type"))t.body=c!=null&&a.has("X-Amz-Content-Sha256")?c:await e.clone().arrayBuffer();e=s}let r=new m_(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 m_{constructor({method:e,url:t,headers:r,body:n,accessKeyId:o,secretAccessKey:s,sessionToken:a,service:c,region:p,cache:m,datetime:x,signQuery:O,appendSessionToken:F,allHeaders:X,singleEncode:he}){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 be,le;if(!c||!p)[be,le]=ZE(this.url,this.headers);if(this.service=c||be||"",this.region=p||le||"us-east-1",this.cache=m||new Map,this.datetime=x||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=O,this.appendSessionToken=F||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 Oe=this.signQuery?this.url.searchParams:this.headers;if(Oe.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken)Oe.set("X-Amz-Security-Token",this.sessionToken);if(this.signableHeaders=["host",...this.headers.keys()].filter((Me)=>X||!WE.has(Me)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map((Me)=>Me+":"+(Me==="host"?this.url.host:(this.headers.get(Me)||"").replace(/\s+/g," "))).join(`
529
- `),this.credentialString=[this.datetime.slice(0,8),this.region,this.service,"aws4_request"].join("/"),this.signQuery){if(this.service==="s3"&&!Oe.has("X-Amz-Expires"))Oe.set("X-Amz-Expires","86400");Oe.set("X-Amz-Algorithm","AWS4-HMAC-SHA256"),Oe.set("X-Amz-Credential",this.accessKeyId+"/"+this.credentialString),Oe.set("X-Amz-SignedHeaders",this.signedHeaders)}if(this.service==="s3")try{this.encodedPath=decodeURIComponent(this.url.pathname.replace(/\+/g," "))}catch(Me){this.encodedPath=this.url.pathname}else this.encodedPath=this.url.pathname.replace(/\/+/g,"/");if(!he)this.encodedPath=encodeURIComponent(this.encodedPath).replace(/%2F/g,"/");this.encodedPath=__(this.encodedPath);let Be=new Set;this.encodedSearch=[...this.url.searchParams].filter(([Me])=>{if(!Me)return!1;if(this.service==="s3"){if(Be.has(Me))return!1;Be.add(Me)}return!0}).map((Me)=>Me.map((He)=>__(encodeURIComponent(He)))).sort(([Me,He],[Ze,$t])=>Me<Ze?-1:Me>Ze?1:He<$t?-1:He>$t?1:0).map((Me)=>Me.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 vo("AWS4"+this.secretAccessKey,e),o=await vo(n,this.region),s=await vo(o,this.service);r=await vo(s,"aws4_request"),this.cache.set(t,r)}return dc(await vo(r,await this.stringToSign()))}async stringToSign(){return["AWS4-HMAC-SHA256",this.datetime,this.credentialString,dc(await h_(await this.canonicalString()))].join(`
528
+ enabled = 1`).run(t.url,JSON.stringify(t.config),t.label??null)}function kt(e,t){return at(e,()=>{let r=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),r})}function um(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 uc(e,t,r){let n=lm.get(e);if(!n)n=new Map,lm.set(e,n);let o=n.get(t);if(o)return o;let s=eS(e,t,r).finally(()=>{if(n.get(t)===s)n.delete(t)});return n.set(t,s),s}function QE(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 YE(e){try{let t=await fetch(new URL(Uh,e),{signal:AbortSignal.timeout(5000)});if(!t.ok)return null;let r=Fh.safeParse(await t.json());return r.success?r.data:null}catch{return null}}async function eS(e,t,r){try{let n=xt(e,t),o;if(n?.kind==="s3"){if(!n.config)throw Error(`storage peer ${t} has no config`);let p=JSON.parse(n.config),m={...r?.storage,publish:r?.storage?.publish??p.publish,priority:r?.storage?.priority??p.priority};o=await ug(e,t,Mt(p),p,m)}else if(n?.kind==="room"){await Promise.resolve().then(() => Mi());o=await $i(e,n)}else o=await xi(e,t,{timeoutMs:r?.timeoutMs});um(e,t,"ok",null);let s=[...o.warnings??[]];try{if(n?.kind!=="s3"&&n?.kind!=="room")hg(e,t)}catch(p){s.push(`site rollback bookkeeping failed: ${p.message}`)}if(n?.kind!=="s3"&&n?.kind!=="room"){let p=QE(mg.version,await YE(t));if(p)s.push(`${t}: ${p}`)}await Promise.resolve().then(() => lc());let c=await In(e);if(c)s.push(`site channel reconcile failed: ${c}`);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 um(e,t,"error",o),{url:t,ok:!1,error:o}}}var dm="url, pull_cursor, push_cursor, token, label, node_id, enabled, last_sync_at, last_success_at, last_status, last_error, kind, config",lm;var An=Ae(()=>{Xe();Ti();Qn();Xr();fg();pg();Jr();ki();gg();Qn();lm=new WeakMap});class hc{constructor({accessKeyId:e,secretAccessKey:t,sessionToken:r,service:n,region:o,cache:s,retries:a,initRetryMs:c}){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=c||50}async sign(e,t){if(e instanceof Request){let{method:o,url:s,headers:a,body:c}=e;if(t=Object.assign({method:o,url:s,headers:a},t),t.body==null&&a.has("Content-Type"))t.body=c!=null&&a.has("X-Amz-Content-Sha256")?c:await e.clone().arrayBuffer();e=s}let r=new vm(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 vm{constructor({method:e,url:t,headers:r,body:n,accessKeyId:o,secretAccessKey:s,sessionToken:a,service:c,region:p,cache:m,datetime:x,signQuery:A,appendSessionToken:F,allHeaders:X,singleEncode:he}){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 _e,le;if(!c||!p)[_e,le]=oS(this.url,this.headers);if(this.service=c||_e||"",this.region=p||le||"us-east-1",this.cache=m||new Map,this.datetime=x||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=A,this.appendSessionToken=F||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 Oe=this.signQuery?this.url.searchParams:this.headers;if(Oe.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken)Oe.set("X-Amz-Security-Token",this.sessionToken);if(this.signableHeaders=["host",...this.headers.keys()].filter((Me)=>X||!nS.has(Me)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map((Me)=>Me+":"+(Me==="host"?this.url.host:(this.headers.get(Me)||"").replace(/\s+/g," "))).join(`
529
+ `),this.credentialString=[this.datetime.slice(0,8),this.region,this.service,"aws4_request"].join("/"),this.signQuery){if(this.service==="s3"&&!Oe.has("X-Amz-Expires"))Oe.set("X-Amz-Expires","86400");Oe.set("X-Amz-Algorithm","AWS4-HMAC-SHA256"),Oe.set("X-Amz-Credential",this.accessKeyId+"/"+this.credentialString),Oe.set("X-Amz-SignedHeaders",this.signedHeaders)}if(this.service==="s3")try{this.encodedPath=decodeURIComponent(this.url.pathname.replace(/\+/g," "))}catch(Me){this.encodedPath=this.url.pathname}else this.encodedPath=this.url.pathname.replace(/\/+/g,"/");if(!he)this.encodedPath=encodeURIComponent(this.encodedPath).replace(/%2F/g,"/");this.encodedPath=wm(this.encodedPath);let Be=new Set;this.encodedSearch=[...this.url.searchParams].filter(([Me])=>{if(!Me)return!1;if(this.service==="s3"){if(Be.has(Me))return!1;Be.add(Me)}return!0}).map((Me)=>Me.map((He)=>wm(encodeURIComponent(He)))).sort(([Me,He],[Ze,zt])=>Me<Ze?-1:Me>Ze?1:He<zt?-1:He>zt?1:0).map((Me)=>Me.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 So("AWS4"+this.secretAccessKey,e),o=await So(n,this.region),s=await So(o,this.service);r=await So(s,"aws4_request"),this.cache.set(t,r)}return fc(await So(r,await this.stringToSign()))}async stringToSign(){return["AWS4-HMAC-SHA256",this.datetime,this.credentialString,fc(await ym(await this.canonicalString()))].join(`
530
530
  `)}async canonicalString(){return[this.method.toUpperCase(),this.encodedPath,this.encodedSearch,this.canonicalHeaders+`
531
531
  `,this.signedHeaders,await this.hexBodyHash()].join(`
532
- `)}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=dc(await h_(this.body||""))}return e}}async function vo(e,t){let r=await crypto.subtle.importKey("raw",typeof e==="string"?fc.encode(e):e,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return crypto.subtle.sign("HMAC",r,fc.encode(t))}async function h_(e){return crypto.subtle.digest("SHA-256",typeof e==="string"?fc.encode(e):e)}function dc(e){let t=new Uint8Array(e),r="";for(let n=0;n<t.length;n++){let o=t[n];r+=g_[o>>>4&15],r+=g_[o&15]}return r}function __(e){return e.replace(/[!'()*]/g,(t)=>"%"+t.charCodeAt(0).toString(16).toUpperCase())}function ZE(e,t){let{hostname:r,pathname:n}=e;if(r.endsWith(".on.aws")){let c=r.match(/^[^.]{1,63}\.lambda-url\.([^.]{1,63})\.on\.aws$/);return c!=null?["lambda",c[1]||""]:["",""]}if(r.endsWith(".r2.cloudflarestorage.com"))return["s3","auto"];if(r.endsWith(".backblazeb2.com")){let c=r.match(/^(?:[^.]{1,63}\.)?s3\.([^.]{1,63})\.backblazeb2\.com$/);return c!=null?["s3",c[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 c=(t.get("X-Amz-Target")||"").split(".")[0];if(c==="AnyScaleFrontendService")s="application-autoscaling";else if(c==="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[HE[s]||s,a||""]}var fc,HE,WE,g_;var y_=De(()=>{fc=new TextEncoder,HE={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"},WE=new Set(["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"]);g_=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"]});function hc(e){return new pc({accessKeyId:e.accessKeyId,secretAccessKey:e.secretAccessKey,region:e.region||"auto",service:"s3"})}function gc(e){let t=new URL(e.endpoint).origin;return Jh(e)?t:`${t}/${e.bucket}`}function _c(e,t){return`${gc(e)}/${t.split("/").map(encodeURIComponent).join("/")}`}async function Eo(e,t,r){let n=hc(e),o=new URL(_c(e,t));return o.searchParams.set("X-Amz-Expires",String(Math.min(Math.max(1,Math.floor(r)),On))),(await n.sign(o.toString(),{method:"GET",aws:{signQuery:!0}})).url}var On=604800;var Fi=De(()=>{y_();xn()});function CS(e,t){let r=e.query("SELECT value FROM meta WHERE key = ?").get(t);return r?r.value:null}function Ac(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 Wi(e){let t=CS(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,Ac(e,"edge_config",JSON.stringify(r));if(!Array.isArray(r.capabilities))r.capabilities=r.cf?["inbox","room"]:["inbox"],Ac(e,"edge_config",JSON.stringify(r));return r}catch{return null}}function Dc(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;Ac(e,"edge_config",r?JSON.stringify(r):null)}function So(e){return e.capabilities??(e.cf?["inbox","room"]:["inbox"])}var Dr="3";function xo(e){let t=(e||"").replace(/^\/+|\/+$/g,"");return t?`${t}/shares`:"shares"}function nm(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 sm(e,t){let r=new TextEncoder().encode(JSON.stringify(t));return e.encrypt&&e.masterKey?mr(tr(e.masterKey),r):Promise.resolve(r)}async function Ic(e,t){let n=await Gt(e).get(Oc(xo(e.prefix),t)).catch(()=>null);if(!n)return null;try{let o=e.encrypt&&e.masterKey?await Kr(tr(e.masterKey),n):n;return JSON.parse(new TextDecoder().decode(o))}catch{return null}}async function NS(e,t){let r=Gt(t.config),n=xo(t.config.prefix),o={v:1,kind:t.kind,title:""},s=[];if(t.kind==="doc"){let m=ot(e,t.targetId);if(!m)throw new Z("not_found",`no such document: ${t.targetId}`);o.title=m.title,o.body=m.body??"",s=nm(o.body)}else{let m=Dt(e,t.targetId);if(!m)throw new Z("not_found",`no such database: ${t.targetId}`);o.title=m.name;let x=Ft(e,t.targetId).sort((F,X)=>F.position-X.position);o.properties=x.map((F)=>({id:F.id,name:F.name,type:F.type}));let O=hn(e,t.targetId);o.records=O.map((F)=>({cells:F.cells})),s=nm(JSON.stringify(O.map((F)=>F.cells)))}let a=[],c={};if(s.length>0&&!gu())throw new Z("network","no blob-bytes resolver is registered for this runtime");for(let m of s){let x=await hu(e,m);if(!x)continue;let O=im(n,t.slug,m);await r.put(O,await mr(t.shareKey,x),{contentType:"application/octet-stream"}),a.push(O),c[m]={url:await Eo(t.config,O,t.expiresSec),ct:bu(e,m)??"application/octet-stream"}}if(Object.keys(c).length)o.blobs=c;let p=om(n,t.slug);return await r.put(p,await mr(t.shareKey,new TextEncoder().encode(JSON.stringify(o))),{contentType:"application/octet-stream"}),a.push(p),{manifestUrl:await Eo(t.config,p,t.expiresSec),objects:a,title:o.title}}async function am(e,t,r,n=On){let o=await Ic(t,r);if(!o)throw new Z("not_found",`no such bucket share: ${r}`);let s=tr(o.key),a=lm(n),{manifestUrl:c,objects:p,title:m}=await NS(e,{slug:r,kind:o.kind,targetId:o.target_id,config:t,shareKey:s,expiresSec:a}),x=Date.now()+a*1000,O={...o,title:m,presign_exp:x,objects:p,content_updated_at:Date.now()};return await Gt(t).put(Oc(xo(t.prefix),r),await sm(t,O),{contentType:"application/octet-stream"}),{manifestUrl:c,presignExp:x,keyB64:o.has_password?void 0:o.key,saltB64:o.salt,title:m}}async function qS(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 cm(e,t,r=On){let n=await Ic(e,t);if(!n)throw new Z("not_found",`no such bucket share: ${t}`);let o=Gt(e),s=xo(e.prefix),a=tr(n.key),c=lm(r),p=om(s,t),m=await o.get(p).catch(()=>null);if(!m)throw new Z("not_found",`bucket share ${t} has no manifest`);let x=JSON.parse(new TextDecoder().decode(await Kr(a,m))),O=await qS(x,(X)=>Eo(e,im(s,t,X),c));await o.put(p,await mr(a,new TextEncoder().encode(JSON.stringify(O))),{contentType:"application/octet-stream"});let F=Date.now()+c*1000;return await o.put(Oc(s,t),await sm(e,{...n,presign_exp:F}),{contentType:"application/octet-stream"}),{manifestUrl:await Eo(e,p,c),presignExp:F,keyB64:n.has_password?void 0:n.key,saltB64:n.salt,title:n.title}}async function Cc(e){let t=Gt(e),r=xo(e.prefix),o=(await t.list(`${r}/`,void 0,"/")).map((a)=>a.key.slice(`${r}/`.length).replace(/\/$/,"")).filter((a)=>a&&!a.includes("/")),s=[];for(let a of o){let c=await Ic(e,a);if(c)s.push(c)}return s}function lm(e){return Math.min(Math.max(60,Math.floor(e)),On)}var Oc=(e,t)=>`${e}/${t}/meta.json`,om=(e,t)=>`${e}/${t}/manifest.bin`,im=(e,t,r)=>`${e}/${t}/blobs/${r}`;var Pc=De(()=>{Xe();yn();Fr();Sr();zr();Vn();xn();Fi();uo()});function LS(e){return Lt(e).flatMap((t)=>{if(t.kind==="s3"&&t.config)return[{url:t.url,kind:"bucket",peer:t}];if(t.kind==="http"&&t.token)return[{url:t.url,kind:"peer",peer:t}];return[]})}function $S(e){let t=Nc.get(e);if(!t)t=new Map,Nc.set(e,t);return t}function MS(e,t){let r=$S(e),n=r.get(t);if(!n)n={items:[],fetchedAt:0,error:null,inflight:null},r.set(t,n);return n}function um(e,t,r){let n=MS(e,t);n.items=[...n.items.filter((o)=>o.slug!==r.slug),r]}function dm(e,t){let r=Nc.get(e);if(!r)return null;for(let n of LS(e)){if(n.kind!=="bucket")continue;let o=r.get(n.url)?.items.find((s)=>s.slug===t);if(o)return{source:n,item:o}}return null}var Nc;var fm=De(()=>{Tn();Pc();Nc=new WeakMap});function zS(e,t){if(t)return t.replace(/\/+$/,"");return(e.query("SELECT value FROM meta WHERE key='cfg_share_viewer_url'").get()?.value||FS).replace(/\/+$/,"")}function US(e,t,r,n){let o=`m=${encodeURIComponent(t)}&`+(r?`k=${r}`:`s=${n}`);return`${e}/#${o}`}async function BS(e,t){let r=dm(e,t);if(r)return{peer:r.source.peer,kind:r.item.kind,item:r.item};for(let n of Lt(e).filter((o)=>o.kind==="s3"&&o.config)){let s=(await Cc(JSON.parse(n.config)).catch(()=>[])).find((a)=>a.slug===t);if(s)return{peer:n,kind:s.kind,item:null}}return null}async function pm(e,t,r,n){let o=await BS(e,t);if(!o)throw new Z("not_found",`no such object-storage share: ${t}`);let{peer:s}=o,a=JSON.parse(s.config),c=zS(e,r),p=n?.refreshContent?await am(e,a,t):await cm(a,t);if(o.item)um(e,s.url,{...o.item,title:p.title||o.item.title,expiresAt:p.presignExp,...n?.refreshContent?{contentUpdatedAt:Date.now()}:{}});return{slug:t,kind:o.kind,permission:"view",transport:"s3",hosting:"s3",url:US(c,p.manifestUrl,p.keyB64,p.saltB64),expiresAt:p.presignExp,source:`桶 ${s.label??s.url}`}}var FS="https://share.mh.tensorix.org",BC;var hm=De(()=>{Ra();Xe();Et();Ho();Rn();yn();Fr();Tn();kn();Pc();Fi();fm();wo();BC=Gr({slug:ut().min(1).max(128),kind:vi(["doc","database","site"]),permission:vi(["view","edit"]),transport:sv("server"),hosting:vi(["server","room"]),url:ut().url(),expiresAt:co().nullable(),source:ut()})});globalThis.sqlite3Worker1Promiser=function e(t=e.defaultConfig){if(arguments.length===1&&typeof arguments[0]==="function"){let O=t;t=Object.assign(Object.create(null),e.defaultConfig),t.onready=O}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),c=t.generateMessageId||function(O){return O.type+"#"+(a[O.type]=(a[O.type]||0)+1)},p=(...O)=>{throw Error(O.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(O){O=O.data,s("worker1.onmessage",O);let F=r[O.messageId];if(!F){if(O&&O.type==="sqlite3-api"&&O.result==="worker1-ready"){if(t.onready)t.onready(x);return}if(F=r[O.type],F&&F.onrow){F.onrow(O);return}if(t.onunhandled)t.onunhandled(arguments[0]);else o("sqlite3Worker1Promiser() unhandled worker message:",O);return}switch(delete r[O.messageId],O.type){case"error":F.reject(O);return;case"open":if(!m)m=O.dbId;break;case"close":if(O.dbId===m)m=void 0;break;default:break}try{F.resolve(O)}catch(X){F.reject(X)}},x=function(){let O;if(arguments.length===1)O=arguments[0];else if(arguments.length===2)O=Object.create(null),O.type=arguments[0],O.args=arguments[1],O.dbId=O.args.dbId;else p("Invalid arguments for sqlite3Worker1Promiser()-created factory.");if(!O.dbId&&O.type!=="open")O.dbId=m;O.messageId=c(O),O.departureTime=performance.now();let F=Object.create(null);F.message=O;let X;if(O.type==="exec"&&O.args){if(typeof O.args.callback==="function")X=O.messageId+":row",F.onrow=O.args.callback,O.args.callback=X,r[X]=F;else if(typeof O.args.callback==="string")p("exec callback may not be a string when using the Promise interface.")}let he=new Promise(function(be,le){F.resolve=be,F.reject=le,r[O.messageId]=F,s("Posting",O.type,"message to Worker dbId="+(m||"default")+":",O),t.worker.postMessage(O)});if(X)he=he.finally(()=>delete r[X]);return he}};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 sx=sqlite3Worker1Promiser.v2;delete globalThis.sqlite3Worker1Promiser;async function rs(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,c="";function p(i){if(r.locateFile)return r.locateFile(i,c);return c+i}var m,x;if(n||o){try{c=new URL(".",a).href}catch{}if(o)x=(i)=>{var u=new XMLHttpRequest;return u.open("GET",i,!1),u.responseType="arraybuffer",u.send(null),new Uint8Array(u.response)};m=async(i)=>{var u=await fetch(i,{credentials:"same-origin"});if(u.ok)return u.arrayBuffer();throw Error(u.status+" : "+u.url)}}var O=console.log.bind(console),F=console.error.bind(console),X,he=!1,be,le,Oe=!1;function Be(){var i=fr.buffer;Bt=new Int8Array(i),qn=new Int16Array(i),Ir=new Uint8Array(i),Im=new Uint16Array(i),Ye=new Int32Array(i),rt=new Uint32Array(i),Dm=new Float32Array(i),Om=new Float64Array(i),Rt=new BigInt64Array(i),Cm=new BigUint64Array(i)}function Me(){if(r.wasmMemory)fr=r.wasmMemory;else{var i=r.INITIAL_MEMORY||8388608;fr=new WebAssembly.Memory({initial:i/65536,maximum:32768})}Be()}function He(){if(r.preRun){if(typeof r.preRun=="function")r.preRun=[r.preRun];while(r.preRun.length)Nm(r.preRun.shift())}Fc(Uc)}function Ze(){if(Oe=!0,!r.noFSInit&&!y.initialized)y.init();wr.init(),sn.__wasm_call_ctors(),y.ignorePermissions=!1}function $t(){if(r.postRun){if(typeof r.postRun=="function")r.postRun=[r.postRun];while(r.postRun.length)Pm(r.postRun.shift())}Fc(zc)}function Tt(i){r.onAbort?.(i),i=`Aborted(${i})`,F(i),he=!0,i+=". Build with -sASSERTIONS for more info.";var u=new WebAssembly.RuntimeError(i);throw le?.(u),u}var Nn;function Em(){if(r.locateFile)return p("sqlite3.wasm");return new URL("sqlite3.wasm",import.meta.url).href}function Sm(i){if(i==Nn&&X)return new Uint8Array(X);if(x)return x(i);throw"both async and sync fetching of the wasm failed"}async function xm(i){if(!X)try{var u=await m(i);return new Uint8Array(u)}catch{}return Sm(i)}async function km(i,u){try{var _=await xm(i);return await WebAssembly.instantiate(_,u)}catch(f){F(`failed to asynchronously prepare wasm: ${f}`),Tt(f)}}async function Tm(i,u,_){if(!i)try{var f=fetch(u,{credentials:"same-origin"});return await WebAssembly.instantiateStreaming(f,_)}catch(l){F(`wasm streaming compile failed: ${l}`),F("falling back to ArrayBuffer instantiation")}return km(u,_)}function Rm(){return{env:rl,wasi_snapshot_preview1:rl}}async function Am(){function i(f,l){return sn=f.exports,My(sn),sn}function u(f){return i(f.instance)}var _=Rm();if(r.instantiateWasm)return new Promise((f,l)=>{r.instantiateWasm(_,(d,h)=>{f(i(d,h))})});return Nn??=Em(),u(await Tm(X,Nn,_))}var qn,Ye,Rt,Bt,Dm,Om,Im,rt,Cm,Ir,Fc=(i)=>{while(i.length>0)i.shift()(r)},zc=[],Pm=(i)=>zc.push(i),Uc=[],Nm=(i)=>Uc.push(i),fr,et={isAbs:(i)=>i.charAt(0)==="/",splitPath:(i)=>/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/.exec(i).slice(1),normalizeArray:(i,u)=>{var _=0;for(var f=i.length-1;f>=0;f--){var l=i[f];if(l===".")i.splice(f,1);else if(l==="..")i.splice(f,1),_++;else if(_)i.splice(f,1),_--}if(u)for(;_;_--)i.unshift("..");return i},normalize:(i)=>{var u=et.isAbs(i),_=i.slice(-1)==="/";if(i=et.normalizeArray(i.split("/").filter((f)=>!!f),!u).join("/"),!i&&!u)i=".";if(i&&_)i+="/";return(u?"/":"")+i},dirname:(i)=>{var u=et.splitPath(i),_=u[0],f=u[1];if(!_&&!f)return".";if(f)f=f.slice(0,-1);return _+f},basename:(i)=>i&&i.match(/([^\/]+|\/)\/*$/)[1],join:(...i)=>et.normalize(i.join("/")),join2:(i,u)=>et.normalize(i+"/"+u)},qm=()=>(i)=>(crypto.getRandomValues(i),0),Bc=(i)=>(Bc=qm())(i),rn={resolve:(...i)=>{var u="",_=!1;for(var f=i.length-1;f>=-1&&!_;f--){var l=f>=0?i[f]:y.cwd();if(typeof l!="string")throw TypeError("Arguments to path.resolve must be strings");else if(!l)return"";u=l+"/"+u,_=et.isAbs(l)}return u=et.normalizeArray(u.split("/").filter((d)=>!!d),!_).join("/"),(_?"/":"")+u||"."},relative:(i,u)=>{i=rn.resolve(i).slice(1),u=rn.resolve(u).slice(1);function _(I){var V=0;for(;V<I.length;V++)if(I[V]!=="")break;var U=I.length-1;for(;U>=0;U--)if(I[U]!=="")break;if(V>U)return[];return I.slice(V,U-V+1)}var f=_(i.split("/")),l=_(u.split("/")),d=Math.min(f.length,l.length),h=d;for(var E=0;E<d;E++)if(f[E]!==l[E]){h=E;break}var b=[];for(var E=h;E<f.length;E++)b.push("..");return b=b.concat(l.slice(h)),b.join("/")}},jc=new TextDecoder,Hc=(i,u,_,f)=>{var l=u+_;if(f)return l;while(i[u]&&!(u>=l))++u;return u},Ln=(i,u=0,_,f)=>{var l=Hc(i,u,_,f);return jc.decode(i.buffer?i.subarray(u,l):new Uint8Array(i.slice(u,l)))},Xi=[],To=(i)=>{var u=0;for(var _=0;_<i.length;++_){var f=i.charCodeAt(_);if(f<=127)u++;else if(f<=2047)u+=2;else if(f>=55296&&f<=57343)u+=4,++_;else u+=3}return u},Wc=(i,u,_,f)=>{if(!(f>0))return 0;var l=_,d=_+f-1;for(var h=0;h<i.length;++h){var E=i.codePointAt(h);if(E<=127){if(_>=d)break;u[_++]=E}else if(E<=2047){if(_+1>=d)break;u[_++]=192|E>>6,u[_++]=128|E&63}else if(E<=65535){if(_+2>=d)break;u[_++]=224|E>>12,u[_++]=128|E>>6&63,u[_++]=128|E&63}else{if(_+3>=d)break;u[_++]=240|E>>18,u[_++]=128|E>>12&63,u[_++]=128|E>>6&63,u[_++]=128|E&63,h++}}return u[_]=0,_-l},Qi=(i,u,_)=>{var f=_>0?_:To(i)+1,l=Array(f),d=Wc(i,l,0,l.length);if(u)l.length=d;return l},Lm=()=>{if(!Xi.length){var i=null;if(globalThis.window?.prompt){if(i=window.prompt("Input: "),i!==null)i+=`
533
- `}if(!i)return null;Xi=Qi(i,!0)}return Xi.shift()},wr={ttys:[],init(){},shutdown(){},register(i,u){wr.ttys[i]={input:[],output:[],ops:u},y.registerDevice(i,wr.stream_ops)},stream_ops:{open(i){var u=wr.ttys[i.node.rdev];if(!u)throw new y.ErrnoError(43);i.tty=u,i.seekable=!1},close(i){i.tty.ops.fsync(i.tty)},fsync(i){i.tty.ops.fsync(i.tty)},read(i,u,_,f,l){if(!i.tty||!i.tty.ops.get_char)throw new y.ErrnoError(60);var d=0;for(var h=0;h<f;h++){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++,u[_+h]=E}if(d)i.node.atime=Date.now();return d},write(i,u,_,f,l){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,u[_+d])}catch(h){throw new y.ErrnoError(29)}if(f)i.node.mtime=i.node.ctime=Date.now();return d}},default_tty_ops:{get_char(i){return Lm()},put_char(i,u){if(u===null||u===10)O(Ln(i.output)),i.output=[];else if(u!=0)i.output.push(u)},fsync(i){if(i.output?.length>0)O(Ln(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,u,_){return 0},ioctl_tiocgwinsz(i){return[24,80]}},default_tty1_ops:{put_char(i,u){if(u===null||u===10)F(Ln(i.output)),i.output=[];else if(u!=0)i.output.push(u)},fsync(i){if(i.output?.length>0)F(Ln(i.output)),i.output=[]}}},$m=(i,u)=>Ir.fill(0,i,i+u),Zc=(i,u)=>Math.ceil(i/u)*u,Gc=(i)=>{i=Zc(i,65536);var u=tl(65536,i);if(u)$m(u,i);return u},ze={ops_table:null,mount(i){return ze.createNode(null,"/",16895,0)},createNode(i,u,_,f){if(y.isBlkdev(_)||y.isFIFO(_))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 l=y.createNode(i,u,_,f);if(y.isDir(l.mode))l.node_ops=ze.ops_table.dir.node,l.stream_ops=ze.ops_table.dir.stream,l.contents={};else if(y.isFile(l.mode))l.node_ops=ze.ops_table.file.node,l.stream_ops=ze.ops_table.file.stream,l.usedBytes=0,l.contents=ze.emptyFileContents??=new Uint8Array(0);else if(y.isLink(l.mode))l.node_ops=ze.ops_table.link.node,l.stream_ops=ze.ops_table.link.stream;else if(y.isChrdev(l.mode))l.node_ops=ze.ops_table.chrdev.node,l.stream_ops=ze.ops_table.chrdev.stream;if(l.atime=l.mtime=l.ctime=Date.now(),i)i.contents[u]=l,i.atime=i.mtime=i.ctime=l.atime;return l},getFileDataAsTypedArray(i){return i.contents.subarray(0,i.usedBytes)},expandFileStorage(i,u){var _=i.contents.length;if(_>=u)return;if(u=Math.max(u,_*(_<1048576?2:1.125)>>>0),_)u=Math.max(u,256);var f=ze.getFileDataAsTypedArray(i);i.contents=new Uint8Array(u),i.contents.set(f)},resizeFileStorage(i,u){if(i.usedBytes==u)return;var _=i.contents;i.contents=new Uint8Array(u),i.contents.set(_.subarray(0,Math.min(u,i.usedBytes))),i.usedBytes=u},node_ops:{getattr(i){var u={};if(u.dev=y.isChrdev(i.mode)?i.id:1,u.ino=i.id,u.mode=i.mode,u.nlink=1,u.uid=0,u.gid=0,u.rdev=i.rdev,y.isDir(i.mode))u.size=4096;else if(y.isFile(i.mode))u.size=i.usedBytes;else if(y.isLink(i.mode))u.size=i.link.length;else u.size=0;return u.atime=new Date(i.atime),u.mtime=new Date(i.mtime),u.ctime=new Date(i.ctime),u.blksize=4096,u.blocks=Math.ceil(u.size/u.blksize),u},setattr(i,u){for(let _ of["mode","atime","mtime","ctime"])if(u[_]!=null)i[_]=u[_];if(u.size!==void 0)ze.resizeFileStorage(i,u.size)},lookup(i,u){if(!ze.doesNotExistError)ze.doesNotExistError=new y.ErrnoError(44),ze.doesNotExistError.stack="<generic error, no stack>";throw ze.doesNotExistError},mknod(i,u,_,f){return ze.createNode(i,u,_,f)},rename(i,u,_){var f;try{f=y.lookupNode(u,_)}catch(d){}if(f){if(y.isDir(i.mode))for(var l in f.contents)throw new y.ErrnoError(55);y.hashRemoveNode(f)}delete i.parent.contents[i.name],u.contents[_]=i,i.name=_,u.ctime=u.mtime=i.parent.ctime=i.parent.mtime=Date.now()},unlink(i,u){delete i.contents[u],i.ctime=i.mtime=Date.now()},rmdir(i,u){for(var _ in y.lookupNode(i,u).contents)throw new y.ErrnoError(55);delete i.contents[u],i.ctime=i.mtime=Date.now()},readdir(i){return[".","..",...Object.keys(i.contents)]},symlink(i,u,_){var f=ze.createNode(i,u,41471,0);return f.link=_,f},readlink(i){if(!y.isLink(i.mode))throw new y.ErrnoError(28);return i.link}},stream_ops:{read(i,u,_,f,l){var d=i.node.contents;if(l>=i.node.usedBytes)return 0;var h=Math.min(i.node.usedBytes-l,f);return u.set(d.subarray(l,l+h),_),h},write(i,u,_,f,l,d){if(u.buffer===Bt.buffer)d=!1;if(!f)return 0;var h=i.node;if(h.mtime=h.ctime=Date.now(),d)h.contents=u.subarray(_,_+f),h.usedBytes=f;else if(h.usedBytes===0&&l===0)h.contents=u.slice(_,_+f),h.usedBytes=f;else ze.expandFileStorage(h,l+f),h.contents.set(u.subarray(_,_+f),l),h.usedBytes=Math.max(h.usedBytes,l+f);return f},llseek(i,u,_){var f=u;if(_===1)f+=i.position;else if(_===2){if(y.isFile(i.node.mode))f+=i.node.usedBytes}if(f<0)throw new y.ErrnoError(28);return f},mmap(i,u,_,f,l){if(!y.isFile(i.node.mode))throw new y.ErrnoError(43);var d,h,E=i.node.contents;if(!(l&2)&&E.buffer===Bt.buffer)h=!1,d=E.byteOffset;else{if(h=!0,d=Gc(u),!d)throw new y.ErrnoError(48);if(E){if(_>0||_+u<E.length)if(E.subarray)E=E.subarray(_,_+u);else E=Array.prototype.slice.call(E,_,_+u);Bt.set(E,d)}}return{ptr:d,allocated:h}},msync(i,u,_,f,l){return ze.stream_ops.write(i,u,0,f,_,!1),0}}},Mm=(i)=>{if(typeof i!="string")return i;var u={r:0,"r+":2,w:577,"w+":578,a:1089,"a+":1090}[i];if(typeof u>"u")throw Error(`Unknown file open mode: ${i}`);return u},Kc=(i)=>{if(typeof i=="string")i=Qi(i,!0);if(!i.subarray)i=new Uint8Array(i);return i},Yi=(i,u)=>{var _=0;if(i)_|=365;if(u)_|=146;return _},Fm=async(i)=>{var u=await m(i);return new Uint8Array(u)},zm=(...i)=>y.createDataFile(...i),Um=(i)=>i,Cr=0,$n=null,Bm=(i)=>{if(Cr--,r.monitorRunDependencies?.(Cr),Cr==0){if($n){var u=$n;$n=null,u()}}},jm=(i)=>{Cr++,r.monitorRunDependencies?.(Cr)},Vc=[],Hm=async(i,u)=>{if(typeof Browser<"u")Browser.init();for(var _ of Vc)if(_.canHandle(u))return _.handle(i,u);return i},Jc=async(i,u,_,f,l,d,h,E)=>{var b=u?rn.resolve(et.join2(i,u)):i,I=Um(`cp ${b}`);jm(I);try{var V=_;if(typeof _=="string")V=await Fm(_);if(V=await Hm(V,b),E?.(),!d)zm(i,u,V,f,l,h)}finally{Bm(I)}},Wm=(i,u,_,f,l,d,h,E,b,I)=>{Jc(i,u,_,f,l,E,b,I).then(d).catch(h)},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,u,_,f){if(!i)i=this;this.parent=i,this.mount=i.mount,this.id=y.nextInode++,this.name=u,this.mode=_,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,u={}){if(!i)throw new y.ErrnoError(44);if(u.follow_mount??=!0,!et.isAbs(i))i=y.cwd()+"/"+i;e:for(var _=0;_<40;_++){var f=i.split("/").filter((I)=>!!I),l=y.root,d="/";for(var h=0;h<f.length;h++){var E=h===f.length-1;if(E&&u.parent)break;if(f[h]===".")continue;if(f[h]===".."){if(d=et.dirname(d),y.isRoot(l)){i=d+"/"+f.slice(h+1).join("/"),_--;continue e}else l=l.parent;continue}d=et.join2(d,f[h]);try{l=y.lookupNode(l,f[h])}catch(I){if(I?.errno===44&&E&&u.noent_okay)return{path:d};throw I}if(y.isMountpoint(l)&&(!E||u.follow_mount))l=l.mounted.root;if(y.isLink(l.mode)&&(!E||u.follow)){if(!l.node_ops.readlink)throw new y.ErrnoError(52);var b=l.node_ops.readlink(l);if(!et.isAbs(b))b=et.dirname(d)+"/"+b;i=b+"/"+f.slice(h+1).join("/");continue e}}return{path:d,node:l}}throw new y.ErrnoError(32)},getPath(i){var u;while(!0){if(y.isRoot(i)){var _=i.mount.mountpoint;if(!u)return _;return _[_.length-1]!=="/"?`${_}/${u}`:_+u}u=u?`${i.name}/${u}`:i.name,i=i.parent}},hashName(i,u){var _=0;for(var f=0;f<u.length;f++)_=(_<<5)-_+u.charCodeAt(f)|0;return(i+_>>>0)%y.nameTable.length},hashAddNode(i){var u=y.hashName(i.parent.id,i.name);i.name_next=y.nameTable[u],y.nameTable[u]=i},hashRemoveNode(i){var u=y.hashName(i.parent.id,i.name);if(y.nameTable[u]===i)y.nameTable[u]=i.name_next;else{var _=y.nameTable[u];while(_){if(_.name_next===i){_.name_next=i.name_next;break}_=_.name_next}}},lookupNode(i,u){var _=y.mayLookup(i);if(_)throw new y.ErrnoError(_);var f=y.hashName(i.id,u);for(var l=y.nameTable[f];l;l=l.name_next){var d=l.name;if(l.parent.id===i.id&&d===u)return l}return y.lookup(i,u)},createNode(i,u,_,f){var l=new y.FSNode(i,u,_,f);return y.hashAddNode(l),l},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 u=["r","w","rw"][i&3];if(i&512)u+="w";return u},nodePermissions(i,u){if(y.ignorePermissions)return 0;if(u.includes("r")&&!(i.mode&292))return 2;if(u.includes("w")&&!(i.mode&146))return 2;if(u.includes("x")&&!(i.mode&73))return 2;return 0},mayLookup(i){if(!y.isDir(i.mode))return 54;var u=y.nodePermissions(i,"x");if(u)return u;if(!i.node_ops.lookup)return 2;return 0},mayCreate(i,u){if(!y.isDir(i.mode))return 54;try{return y.lookupNode(i,u),20}catch(_){}return y.nodePermissions(i,"wx")},mayDelete(i,u,_){var f;try{f=y.lookupNode(i,u)}catch(d){return d.errno}var l=y.nodePermissions(i,"wx");if(l)return l;if(_){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,u){if(!i)return 44;if(y.isLink(i.mode))return 32;var _=y.flagsToPermissionString(u);if(y.isDir(i.mode)){if(_!=="r"||u&576)return 31}return y.nodePermissions(i,_)},checkOpExists(i,u){if(!i)throw new y.ErrnoError(u);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 u=y.getStream(i);if(!u)throw new y.ErrnoError(8);return u},getStream:(i)=>y.streams[i],createStream(i,u=-1){if(i=Object.assign(new y.FSStream,i),u==-1)u=y.nextfd();return i.fd=u,y.streams[u]=i,i},closeStream(i){y.streams[i]=null},dupStream(i,u=-1){var _=y.createStream(i,u);return _.stream_ops?.dup?.(_),_},doSetAttr(i,u,_){var f=i?.stream_ops.setattr,l=f?i:u;f??=u.node_ops.setattr,y.checkOpExists(f,63),f(l,_)},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,u)=>i<<8|u,registerDevice(i,u){y.devices[i]={stream_ops:u}},getDevice:(i)=>y.devices[i],getMounts(i){var u=[],_=[i];while(_.length){var f=_.pop();u.push(f),_.push(...f.mounts)}return u},syncfs(i,u){if(typeof i=="function")u=i,i=!1;if(y.syncFSRequests++,y.syncFSRequests>1)F(`warning: ${y.syncFSRequests} FS.syncfs operations in flight at once, probably just doing extra work`);var _=y.getMounts(y.root.mount),f=0;function l(E){return y.syncFSRequests--,u(E)}function d(E){if(E){if(!d.errored)return d.errored=!0,l(E);return}if(++f>=_.length)l(null)}for(var h of _)if(h.type.syncfs)h.type.syncfs(h,i,d);else d(null)},mount(i,u,_){var f=_==="/",l=!_,d;if(f&&y.root)throw new y.ErrnoError(10);else if(!f&&!l){var h=y.lookupPath(_,{follow_mount:!1});if(_=h.path,d=h.node,y.isMountpoint(d))throw new y.ErrnoError(10);if(!y.isDir(d.mode))throw new y.ErrnoError(54)}var E={type:i,opts:u,mountpoint:_,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 u=y.lookupPath(i,{follow_mount:!1});if(!y.isMountpoint(u.node))throw new y.ErrnoError(28);var _=u.node,f=_.mounted,l=y.getMounts(f);for(var[d,h]of Object.entries(y.nameTable))while(h){var E=h.name_next;if(l.includes(h.mount))y.destroyNode(h);h=E}_.mounted=null;var b=_.mount.mounts.indexOf(f);_.mount.mounts.splice(b,1)},lookup(i,u){return i.node_ops.lookup(i,u)},mknod(i,u,_){var f=y.lookupPath(i,{parent:!0}).node,l=et.basename(i);if(!l)throw new y.ErrnoError(28);if(l==="."||l==="..")throw new y.ErrnoError(20);var d=y.mayCreate(f,l);if(d)throw new y.ErrnoError(d);if(!f.node_ops.mknod)throw new y.ErrnoError(63);return f.node_ops.mknod(f,l,u,_)},statfs(i){return y.statfsNode(y.lookupPath(i,{follow:!0}).node)},statfsStream(i){return y.statfsNode(i.node)},statfsNode(i){var u={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(u,i.node_ops.statfs(i.mount.opts.root));return u},create(i,u=438){return u&=4095,u|=32768,y.mknod(i,u,0)},mkdir(i,u=511){return u&=1023,u|=16384,y.mknod(i,u,0)},mkdirTree(i,u){var _=i.split("/"),f="";for(var l of _){if(!l)continue;if(f||et.isAbs(i))f+="/";f+=l;try{y.mkdir(f,u)}catch(d){if(d.errno!=20)throw d}}},mkdev(i,u,_){if(typeof _>"u")_=u,u=438;return u|=8192,y.mknod(i,u,_)},symlink(i,u){if(!rn.resolve(i))throw new y.ErrnoError(44);var _=y.lookupPath(u,{parent:!0}).node;if(!_)throw new y.ErrnoError(44);var f=et.basename(u),l=y.mayCreate(_,f);if(l)throw new y.ErrnoError(l);if(!_.node_ops.symlink)throw new y.ErrnoError(63);return _.node_ops.symlink(_,f,i)},rename(i,u){var _=et.dirname(i),f=et.dirname(u),l=et.basename(i),d=et.basename(u),h=y.lookupPath(i,{parent:!0}),E=h.node,b;if(h=y.lookupPath(u,{parent:!0}),b=h.node,!E||!b)throw new y.ErrnoError(44);if(E.mount!==b.mount)throw new y.ErrnoError(75);var I=y.lookupNode(E,l),V=rn.relative(i,f);if(V.charAt(0)!==".")throw new y.ErrnoError(28);if(V=rn.relative(u,_),V.charAt(0)!==".")throw new y.ErrnoError(55);var U;try{U=y.lookupNode(b,d)}catch(H){}if(I===U)return;var N=y.isDir(I.mode),q=y.mayDelete(E,l,N);if(q)throw new y.ErrnoError(q);if(q=U?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)||U&&y.isMountpoint(U))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 u=y.lookupPath(i,{parent:!0}).node,_=et.basename(i),f=y.lookupNode(u,_),l=y.mayDelete(u,_,!0);if(l)throw new y.ErrnoError(l);if(!u.node_ops.rmdir)throw new y.ErrnoError(63);if(y.isMountpoint(f))throw new y.ErrnoError(10);u.node_ops.rmdir(u,_),y.destroyNode(f)},readdir(i){var u=y.lookupPath(i,{follow:!0}).node;return y.checkOpExists(u.node_ops.readdir,54)(u)},unlink(i){var u=y.lookupPath(i,{parent:!0}).node;if(!u)throw new y.ErrnoError(44);var _=et.basename(i),f=y.lookupNode(u,_),l=y.mayDelete(u,_,!1);if(l)throw new y.ErrnoError(l);if(!u.node_ops.unlink)throw new y.ErrnoError(63);if(y.isMountpoint(f))throw new y.ErrnoError(10);u.node_ops.unlink(u,_),y.destroyNode(f)},readlink(i){var u=y.lookupPath(i).node;if(!u)throw new y.ErrnoError(44);if(!u.node_ops.readlink)throw new y.ErrnoError(28);return u.node_ops.readlink(u)},stat(i,u){var _=y.lookupPath(i,{follow:!u}).node;return y.checkOpExists(_.node_ops.getattr,63)(_)},fstat(i){var u=y.getStreamChecked(i),_=u.node,f=u.stream_ops.getattr,l=f?u:_;return f??=_.node_ops.getattr,y.checkOpExists(f,63),f(l)},lstat(i){return y.stat(i,!0)},doChmod(i,u,_,f){y.doSetAttr(i,u,{mode:_&4095|u.mode&-4096,ctime:Date.now(),dontFollow:f})},chmod(i,u,_){var f;if(typeof i=="string")f=y.lookupPath(i,{follow:!_}).node;else f=i;y.doChmod(null,f,u,_)},lchmod(i,u){y.chmod(i,u,!0)},fchmod(i,u){var _=y.getStreamChecked(i);y.doChmod(_,_.node,u,!1)},doChown(i,u,_){y.doSetAttr(i,u,{timestamp:Date.now(),dontFollow:_})},chown(i,u,_,f){var l;if(typeof i=="string")l=y.lookupPath(i,{follow:!f}).node;else l=i;y.doChown(null,l,f)},lchown(i,u,_){y.chown(i,u,_,!0)},fchown(i,u,_){var f=y.getStreamChecked(i);y.doChown(f,f.node,!1)},doTruncate(i,u,_){if(y.isDir(u.mode))throw new y.ErrnoError(31);if(!y.isFile(u.mode))throw new y.ErrnoError(28);var f=y.nodePermissions(u,"w");if(f)throw new y.ErrnoError(f);y.doSetAttr(i,u,{size:_,timestamp:Date.now()})},truncate(i,u){if(u<0)throw new y.ErrnoError(28);var _;if(typeof i=="string")_=y.lookupPath(i,{follow:!0}).node;else _=i;y.doTruncate(null,_,u)},ftruncate(i,u){var _=y.getStreamChecked(i);if(u<0||(_.flags&2097155)===0)throw new y.ErrnoError(28);y.doTruncate(_,_.node,u)},utime(i,u,_){var f=y.lookupPath(i,{follow:!0}).node;y.checkOpExists(f.node_ops.setattr,63)(f,{atime:u,mtime:_})},open(i,u,_=438){if(i==="")throw new y.ErrnoError(44);if(u=Mm(u),u&64)_=_&4095|32768;else _=0;var f,l;if(typeof i=="object")f=i;else{l=i.endsWith("/");var d=y.lookupPath(i,{follow:!(u&131072),noent_okay:!0});f=d.node,i=d.path}var h=!1;if(u&64)if(f){if(u&128)throw new y.ErrnoError(20)}else if(l)throw new y.ErrnoError(31);else f=y.mknod(i,_|511,0),h=!0;if(!f)throw new y.ErrnoError(44);if(y.isChrdev(f.mode))u&=-513;if(u&65536&&!y.isDir(f.mode))throw new y.ErrnoError(54);if(!h){var E=y.mayOpen(f,u);if(E)throw new y.ErrnoError(E)}if(u&512&&!h)y.truncate(f,0);u&=-131713;var b=y.createStream({node:f,path:y.getPath(f),flags:u,seekable:!0,position:0,stream_ops:f.stream_ops,ungotten:[],error:!1});if(b.stream_ops.open)b.stream_ops.open(b);if(h)y.chmod(f,_&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(u){throw u}finally{y.closeStream(i.fd)}i.fd=null},isClosed(i){return i.fd===null},llseek(i,u,_){if(y.isClosed(i))throw new y.ErrnoError(8);if(!i.seekable||!i.stream_ops.llseek)throw new y.ErrnoError(70);if(_!=0&&_!=1&&_!=2)throw new y.ErrnoError(28);return i.position=i.stream_ops.llseek(i,u,_),i.ungotten=[],i.position},read(i,u,_,f,l){if(f<0||l<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 l<"u";if(!d)l=i.position;else if(!i.seekable)throw new y.ErrnoError(70);var h=i.stream_ops.read(i,u,_,f,l);if(!d)i.position+=h;return h},write(i,u,_,f,l,d){if(f<0||l<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 h=typeof l<"u";if(!h)l=i.position;else if(!i.seekable)throw new y.ErrnoError(70);var E=i.stream_ops.write(i,u,_,f,l,d);if(!h)i.position+=E;return E},mmap(i,u,_,f,l){if((f&2)!==0&&(l&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(!u)throw new y.ErrnoError(28);return i.stream_ops.mmap(i,u,_,f,l)},msync(i,u,_,f,l){if(!i.stream_ops.msync)return 0;return i.stream_ops.msync(i,u,_,f,l)},ioctl(i,u,_){if(!i.stream_ops.ioctl)throw new y.ErrnoError(59);return i.stream_ops.ioctl(i,u,_)},readFile(i,u={}){if(u.flags=u.flags||0,u.encoding=u.encoding||"binary",u.encoding!=="utf8"&&u.encoding!=="binary")Tt(`Invalid encoding type "${u.encoding}"`);var _=y.open(i,u.flags),f=y.stat(i).size,l=new Uint8Array(f);if(y.read(_,l,0,f,0),u.encoding==="utf8")l=Ln(l);return y.close(_),l},writeFile(i,u,_={}){_.flags=_.flags||577;var f=y.open(i,_.flags,_.mode);u=Kc(u),y.write(f,u,0,u.byteLength,void 0,_.canOwn),y.close(f)},cwd:()=>y.currentPath,chdir(i){var u=y.lookupPath(i,{follow:!0});if(u.node===null)throw new y.ErrnoError(44);if(!y.isDir(u.node.mode))throw new y.ErrnoError(54);var _=y.nodePermissions(u.node,"x");if(_)throw new y.ErrnoError(_);y.currentPath=u.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,l,d,h,E)=>h,llseek:()=>0}),y.mkdev("/dev/null",y.makedev(1,3)),wr.register(y.makedev(5,0),wr.default_tty_ops),wr.register(y.makedev(6,0),wr.default_tty1_ops),y.mkdev("/dev/tty",y.makedev(5,0)),y.mkdev("/dev/tty1",y.makedev(6,0));var i=new Uint8Array(1024),u=0,_=()=>{if(u===0)Bc(i),u=i.byteLength;return i[--u]};y.createDevice("/dev","random",_),y.createDevice("/dev","urandom",_),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 u=y.createNode(i,"fd",16895,73);return u.stream_ops={llseek:ze.stream_ops.llseek},u.node_ops={lookup(_,f){var l=+f,d=y.getStreamChecked(l),h={parent:null,mount:{mountpoint:"fake"},node_ops:{readlink:()=>d.path},id:l+1};return h.parent=h,h},readdir(){return Array.from(y.streams.entries()).filter(([_,f])=>f).map(([_,f])=>_.toString())}},u}},{},"/proc/self/fd")},createStandardStreams(i,u,_){if(i)y.createDevice("/dev","stdin",i);else y.symlink("/dev/tty","/dev/stdin");if(u)y.createDevice("/dev","stdout",null,u);else y.symlink("/dev/tty","/dev/stdout");if(_)y.createDevice("/dev","stderr",null,_);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,u,_){y.initialized=!0,i??=r.stdin,u??=r.stdout,_??=r.stderr,y.createStandardStreams(i,u,_)},quit(){y.initialized=!1;for(var i of y.streams)if(i)y.close(i)},findObject(i,u){var _=y.analyzePath(i,u);if(!_.exists)return null;return _.object},analyzePath(i,u){try{var _=y.lookupPath(i,{follow:!u});i=_.path}catch(l){}var f={isRoot:!1,exists:!1,error:0,name:null,path:null,object:null,parentExists:!1,parentPath:null,parentObject:null};try{var _=y.lookupPath(i,{parent:!0});f.parentExists=!0,f.parentPath=_.path,f.parentObject=_.node,f.name=et.basename(i),_=y.lookupPath(i,{follow:!u}),f.exists=!0,f.path=_.path,f.object=_.node,f.name=_.node.name,f.isRoot=_.path==="/"}catch(l){f.error=l.errno}return f},createPath(i,u,_,f){i=typeof i=="string"?i:y.getPath(i);var l=u.split("/").reverse();while(l.length){var d=l.pop();if(!d)continue;var h=et.join2(i,d);try{y.mkdir(h)}catch(E){if(E.errno!=20)throw E}i=h}return h},createFile(i,u,_,f,l){var d=et.join2(typeof i=="string"?i:y.getPath(i),u),h=Yi(f,l);return y.create(d,h)},createDataFile(i,u,_,f,l,d){var h=u;if(i)i=typeof i=="string"?i:y.getPath(i),h=u?et.join2(i,u):i;var E=Yi(f,l),b=y.create(h,E);if(_){_=Kc(_),y.chmod(b,E|146);var I=y.open(b,577);y.write(I,_,0,_.length,0,d),y.close(I),y.chmod(b,E)}},createDevice(i,u,_,f){var l=et.join2(typeof i=="string"?i:y.getPath(i),u),d=Yi(!!_,!!f);y.createDevice.major??=64;var h=y.makedev(y.createDevice.major++,0);return y.registerDevice(h,{open(E){E.seekable=!1},close(E){if(f?.buffer?.length)f(10)},read(E,b,I,V,U){var N=0;for(var q=0;q<V;q++){var H;try{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,U){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(l,d,h)},forceLoadFile(i){if(i.isDevice||i.isFolder||i.link||i.contents)return!0;if(globalThis.XMLHttpRequest)Tt("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(u){throw new y.ErrnoError(29)}},createLazyFile(i,u,_,f,l){class d{lengthKnown=!1;chunks=[];get(V){if(V>this.length-1||V<0)return;var U=V%this.chunkSize,N=V/this.chunkSize|0;return this.getter(N)[U]}setDataGetter(V){this.getter=V}cacheLength(){var V=new XMLHttpRequest;if(V.open("HEAD",_,!1),V.send(null),!(V.status>=200&&V.status<300||V.status===304))Tt("Couldn't load "+_+". Status: "+V.status);var U=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=U;var ue=(R,Q)=>{if(R>Q)Tt("invalid range ("+R+", "+Q+") or no bytes requested!");if(Q>U-1)Tt("only "+U+" bytes available! programmer error!");var ee=new XMLHttpRequest;if(ee.open("GET",_,!1),U!==G)ee.setRequestHeader("Range","bytes="+R+"-"+Q);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))Tt("Couldn't load "+_+". Status: "+ee.status);if(ee.response!==void 0)return new Uint8Array(ee.response||[]);return Qi(ee.responseText||"",!0)},D=this;if(D.setDataGetter((R)=>{var Q=R*G,ee=(R+1)*G-1;if(ee=Math.min(ee,U-1),typeof D.chunks[R]>"u")D.chunks[R]=ue(Q,ee);if(typeof D.chunks[R]>"u")Tt("doXHR failed!");return D.chunks[R]}),H||!U)G=U=1,U=this.getter(0).length,G=U,O("LazyFiles on gzip forces download of the whole file when length is accessed");this._length=U,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)Tt("Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc");var h={isDevice:!1,contents:new d}}else var h={isDevice:!1,url:_};var E=y.createFile(i,u,h,f,l);if(h.contents)E.contents=h.contents;else if(h.url)E.contents=null,E.url=h.url;Object.defineProperties(E,{usedBytes:{get:function(){return this.contents.length}}});var b={};for(let[V,U]of Object.entries(E.stream_ops))b[V]=(...N)=>(y.forceLoadFile(E),U(...N));function I(V,U,N,q,H){var G=V.node.contents;if(H>=G.length)return 0;var ue=Math.min(G.length-H,q);if(G.slice)for(var D=0;D<ue;D++)U[N+D]=G[H+D];else for(var D=0;D<ue;D++)U[N+D]=G.get(H+D);return ue}return b.read=(V,U,N,q,H)=>(y.forceLoadFile(E),I(V,U,N,q,H)),b.mmap=(V,U,N,q,H)=>{y.forceLoadFile(E);var G=Gc(U);if(!G)throw new y.ErrnoError(48);return I(V,Bt,G,U,N),{ptr:G,allocated:!0}},E.stream_ops=b,E}},Zm=(i,u,_)=>{if(!i)return"";var f=Hc(Ir,i,u,_);return jc.decode(Ir.subarray(i,f))},je={calculateAt(i,u,_){if(et.isAbs(u))return u;var f;if(i===-100)f=y.cwd();else f=je.getStreamFromFD(i).path;if(u.length==0){if(!_)throw new y.ErrnoError(44);return f}return f+"/"+u},writeStat(i,u){rt[i>>2]=u.dev,rt[i+4>>2]=u.mode,rt[i+8>>2]=u.nlink,rt[i+12>>2]=u.uid,rt[i+16>>2]=u.gid,rt[i+20>>2]=u.rdev,Rt[i+24>>3]=BigInt(u.size),Ye[i+32>>2]=4096,Ye[i+36>>2]=u.blocks;var _=u.atime.getTime(),f=u.mtime.getTime(),l=u.ctime.getTime();return Rt[i+40>>3]=BigInt(Math.floor(_/1000)),rt[i+48>>2]=_%1000*1000*1000,Rt[i+56>>3]=BigInt(Math.floor(f/1000)),rt[i+64>>2]=f%1000*1000*1000,Rt[i+72>>3]=BigInt(Math.floor(l/1000)),rt[i+80>>2]=l%1000*1000*1000,Rt[i+88>>3]=BigInt(u.ino),0},writeStatFs(i,u){rt[i+4>>2]=u.bsize,rt[i+60>>2]=u.bsize,Rt[i+8>>3]=BigInt(u.blocks),Rt[i+16>>3]=BigInt(u.bfree),Rt[i+24>>3]=BigInt(u.bavail),Rt[i+32>>3]=BigInt(u.files),Rt[i+40>>3]=BigInt(u.ffree),rt[i+48>>2]=u.fsid,rt[i+64>>2]=u.flags,rt[i+56>>2]=u.namelen},doMsync(i,u,_,f,l){if(!y.isFile(u.node.mode))throw new y.ErrnoError(43);if(f&2)return 0;var d=Ir.slice(i,i+_);y.msync(u,d,l,_,f)},getStreamFromFD(i){return y.getStreamChecked(i)},varargs:void 0,getStr(i){return Zm(i)}};function Gm(i,u){try{return i=je.getStr(i),y.chmod(i,u),0}catch(_){if(typeof y>"u"||_.name!=="ErrnoError")throw _;return-_.errno}}function Km(i,u,_,f){try{if(u=je.getStr(u),u=je.calculateAt(i,u),_&-8)return-28;var l=y.lookupPath(u,{follow:!0}).node;if(!l)return-44;var d="";if(_&4)d+="r";if(_&2)d+="w";if(_&1)d+="x";if(d&&y.nodePermissions(l,d))return-2;return 0}catch(h){if(typeof y>"u"||h.name!=="ErrnoError")throw h;return-h.errno}}function Vm(i,u){try{return y.fchmod(i,u),0}catch(_){if(typeof y>"u"||_.name!=="ErrnoError")throw _;return-_.errno}}function Jm(i,u,_){try{return y.fchown(i,u,_),0}catch(f){if(typeof y>"u"||f.name!=="ErrnoError")throw f;return-f.errno}}var Ro=()=>{var i=Ye[+je.varargs>>2];return je.varargs+=4,i},nn=Ro;function Xm(i,u,_){je.varargs=_;try{var f=je.getStreamFromFD(i);switch(u){case 0:var l=Ro();if(l<0)return-28;while(y.streams[l])l++;return y.dupStream(f,l).fd;case 1:case 2:return 0;case 3:return f.flags;case 4:var l=Ro();return f.flags|=l,0;case 12:var l=nn(),d=0;return qn[l+d>>1]=2,0;case 13:case 14:return 0}return-28}catch(h){if(typeof y>"u"||h.name!=="ErrnoError")throw h;return-h.errno}}function Qm(i,u){try{return je.writeStat(u,y.fstat(i))}catch(_){if(typeof y>"u"||_.name!=="ErrnoError")throw _;return-_.errno}}var Ym=9007199254740992,ey=-9007199254740992,on=(i)=>i<ey||i>Ym?NaN:Number(i);function ty(i,u){u=on(u);try{if(isNaN(u))return-61;return y.ftruncate(i,u),0}catch(_){if(typeof y>"u"||_.name!=="ErrnoError")throw _;return-_.errno}}var Pr=(i,u,_)=>Wc(i,Ir,u,_);function ry(i,u){try{if(u===0)return-28;var _=y.cwd(),f=To(_)+1;if(u<f)return-68;return Pr(_,i,u),f}catch(l){if(typeof y>"u"||l.name!=="ErrnoError")throw l;return-l.errno}}function ny(i,u,_){je.varargs=_;try{var f=je.getStreamFromFD(i);switch(u){case 21509:if(!f.tty)return-59;return 0;case 21505:if(!f.tty)return-59;if(f.tty.ops.ioctl_tcgets){var l=f.tty.ops.ioctl_tcgets(f),U=nn();Ye[U>>2]=l.c_iflag||0,Ye[U+4>>2]=l.c_oflag||0,Ye[U+8>>2]=l.c_cflag||0,Ye[U+12>>2]=l.c_lflag||0;for(var d=0;d<32;d++)Bt[U+d+17]=l.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 U=nn(),h=Ye[U>>2],E=Ye[U+4>>2],b=Ye[U+8>>2],I=Ye[U+12>>2],V=[];for(var d=0;d<32;d++)V.push(Bt[U+d+17]);return f.tty.ops.ioctl_tcsets(f.tty,u,{c_iflag:h,c_oflag:E,c_cflag:b,c_lflag:I,c_cc:V})}return 0;case 21519:if(!f.tty)return-59;var U=nn();return Ye[U>>2]=0,0;case 21520:if(!f.tty)return-59;return-28;case 21537:case 21531:var U=nn();return y.ioctl(f,u,U);case 21523:if(!f.tty)return-59;if(f.tty.ops.ioctl_tiocgwinsz){var N=f.tty.ops.ioctl_tiocgwinsz(f.tty),U=nn();qn[U>>1]=N[0],qn[U+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 oy(i,u){try{return i=je.getStr(i),je.writeStat(u,y.lstat(i))}catch(_){if(typeof y>"u"||_.name!=="ErrnoError")throw _;return-_.errno}}function iy(i,u,_){try{return u=je.getStr(u),u=je.calculateAt(i,u),y.mkdir(u,_,0),0}catch(f){if(typeof y>"u"||f.name!=="ErrnoError")throw f;return-f.errno}}function sy(i,u,_,f){try{u=je.getStr(u);var l=f&256,d=f&4096;return f=f&-6401,u=je.calculateAt(i,u,d),je.writeStat(_,l?y.lstat(u):y.stat(u))}catch(h){if(typeof y>"u"||h.name!=="ErrnoError")throw h;return-h.errno}}function ay(i,u,_,f){je.varargs=f;try{u=je.getStr(u),u=je.calculateAt(i,u);var l=f?Ro():0;return y.open(u,_,l).fd}catch(d){if(typeof y>"u"||d.name!=="ErrnoError")throw d;return-d.errno}}function cy(i,u,_,f){try{if(u=je.getStr(u),u=je.calculateAt(i,u),f<=0)return-28;var l=y.readlink(u),d=Math.min(f,To(l)),h=Bt[_+d];return Pr(l,_,f+1),Bt[_+d]=h,d}catch(E){if(typeof y>"u"||E.name!=="ErrnoError")throw E;return-E.errno}}function ly(i){try{return i=je.getStr(i),y.rmdir(i),0}catch(u){if(typeof y>"u"||u.name!=="ErrnoError")throw u;return-u.errno}}function uy(i,u){try{return i=je.getStr(i),je.writeStat(u,y.stat(i))}catch(_){if(typeof y>"u"||_.name!=="ErrnoError")throw _;return-_.errno}}function dy(i,u,_){try{if(u=je.getStr(u),u=je.calculateAt(i,u),!_)y.unlink(u);else if(_===512)y.rmdir(u);else return-28;return 0}catch(f){if(typeof y>"u"||f.name!=="ErrnoError")throw f;return-f.errno}}var Xc=(i)=>rt[i>>2]+Ye[i+4>>2]*4294967296;function fy(i,u,_,f){try{u=je.getStr(u),u=je.calculateAt(i,u,!0);var l=Date.now(),d,h;if(!_)d=l,h=l;else{var E=Xc(_),b=Ye[_+8>>2];if(b==1073741823)d=l;else if(b==1073741822)d=null;else d=E*1000+b/1e6;if(_+=16,E=Xc(_),b=Ye[_+8>>2],b==1073741823)h=l;else if(b==1073741822)h=null;else h=E*1000+b/1e6}if((h??d)!==null)y.utime(u,d,h);return 0}catch(I){if(typeof y>"u"||I.name!=="ErrnoError")throw I;return-I.errno}}var py=(i)=>i%4===0&&(i%100!==0||i%400===0),hy=[0,31,60,91,121,152,182,213,244,274,305,335],gy=[0,31,59,90,120,151,181,212,243,273,304,334],_y=(i)=>(py(i.getFullYear())?hy:gy)[i.getMonth()]+i.getDate()-1;function my(i,u){i=on(i);var _=new Date(i*1000);Ye[u>>2]=_.getSeconds(),Ye[u+4>>2]=_.getMinutes(),Ye[u+8>>2]=_.getHours(),Ye[u+12>>2]=_.getDate(),Ye[u+16>>2]=_.getMonth(),Ye[u+20>>2]=_.getFullYear()-1900,Ye[u+24>>2]=_.getDay();var f=_y(_)|0;Ye[u+28>>2]=f,Ye[u+36>>2]=-(_.getTimezoneOffset()*60);var l=new Date(_.getFullYear(),0,1),d=new Date(_.getFullYear(),6,1).getTimezoneOffset(),h=l.getTimezoneOffset(),E=(d!=h&&_.getTimezoneOffset()==Math.min(h,d))|0;Ye[u+32>>2]=E}function yy(i,u,_,f,l,d,h){l=on(l);try{var E=je.getStreamFromFD(f),b=y.mmap(E,i,l,u,_),I=b.ptr;return Ye[d>>2]=b.allocated,rt[h>>2]=I,0}catch(V){if(typeof y>"u"||V.name!=="ErrnoError")throw V;return-V.errno}}function by(i,u,_,f,l,d){d=on(d);try{var h=je.getStreamFromFD(l);if(_&2)je.doMsync(i,h,u,f,d)}catch(E){if(typeof y>"u"||E.name!=="ErrnoError")throw E;return-E.errno}}var wy=(i,u,_,f)=>{var l=new Date().getFullYear(),d=new Date(l,0,1),h=new Date(l,6,1),E=d.getTimezoneOffset(),b=h.getTimezoneOffset(),I=Math.max(E,b);rt[i>>2]=I*60,Ye[u>>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")}`},U=V(E),N=V(b);if(b<E)Pr(U,_,17),Pr(N,f,17);else Pr(U,f,17),Pr(N,_,17)},Qc=()=>performance.now(),Yc=()=>Date.now(),vy=1,Ey=(i)=>i>=0&&i<=3;function Sy(i,u,_){if(u=on(u),!Ey(i))return 28;var f;if(i===0)f=Yc();else if(vy)f=Qc();else return 52;var l=Math.round(f*1000*1000);return Rt[_>>3]=BigInt(l),0}var el=()=>2147483648,xy=()=>el(),ky=(i)=>{var u=(i-fr.buffer.byteLength+65535)/65536|0;try{return fr.grow(u),Be(),1}catch(_){}},Ty=(i)=>{var u=Ir.length;i>>>=0;var _=el();if(i>_)return!1;for(var f=1;f<=4;f*=2){var l=u*(1+0.2/f);if(l=Math.min(l,i+100663296),ky(Math.min(_,Zc(Math.max(i,l),65536))))return!0}return!1},es={},Ry=()=>s||"./this.program",Mn=()=>{if(!Mn.strings){var i={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(globalThis.navigator?.language??"C").replace("-","_")+".UTF-8",_:Ry()};for(var u in es)if(es[u]===void 0)delete i[u];else i[u]=es[u];var _=[];for(var u in i)_.push(`${u}=${i[u]}`);Mn.strings=_}return Mn.strings},Ay=(i,u)=>{var _=0,f=0;for(var l of Mn()){var d=u+_;rt[i+f>>2]=d,_+=Pr(l,d,1/0)+1,f+=4}return 0},Dy=(i,u)=>{var _=Mn();rt[i>>2]=_.length;var f=0;for(var l of _)f+=To(l)+1;return rt[u>>2]=f,0};function Oy(i){try{var u=je.getStreamFromFD(i);return y.close(u),0}catch(_){if(typeof y>"u"||_.name!=="ErrnoError")throw _;return _.errno}}function Iy(i,u){try{var _=0,f=0,l=0,d=je.getStreamFromFD(i),h=d.tty?2:y.isDir(d.mode)?3:y.isLink(d.mode)?7:4;return Bt[u]=h,qn[u+2>>1]=l,Rt[u+8>>3]=BigInt(_),Rt[u+16>>3]=BigInt(f),0}catch(E){if(typeof y>"u"||E.name!=="ErrnoError")throw E;return E.errno}}var Cy=(i,u,_,f)=>{var l=0;for(var d=0;d<_;d++){var h=rt[u>>2],E=rt[u+4>>2];u+=8;var b=y.read(i,Bt,h,E,f);if(b<0)return-1;if(l+=b,b<E)break;if(typeof f<"u")f+=b}return l};function Py(i,u,_,f){try{var l=Cy(je.getStreamFromFD(i),u,_);return rt[f>>2]=l,0}catch(d){if(typeof y>"u"||d.name!=="ErrnoError")throw d;return d.errno}}function Ny(i,u,_,f){u=on(u);try{if(isNaN(u))return 61;var l=je.getStreamFromFD(i);if(y.llseek(l,u,_),Rt[f>>3]=BigInt(l.position),l.getdents&&u===0&&_===0)l.getdents=null;return 0}catch(d){if(typeof y>"u"||d.name!=="ErrnoError")throw d;return d.errno}}function qy(i){try{var u=je.getStreamFromFD(i);return u.stream_ops?.fsync?.(u)}catch(_){if(typeof y>"u"||_.name!=="ErrnoError")throw _;return _.errno}}var Ly=(i,u,_,f)=>{var l=0;for(var d=0;d<_;d++){var h=rt[u>>2],E=rt[u+4>>2];u+=8;var b=y.write(i,Bt,h,E,f);if(b<0)return-1;if(l+=b,b<E)break;if(typeof f<"u")f+=b}return l};function $y(i,u,_,f){try{var l=Ly(je.getStreamFromFD(i),u,_);return rt[f>>2]=l,0}catch(d){if(typeof y>"u"||d.name!=="ErrnoError")throw d;return d.errno}}if(y.createPreloadedFile=Wm,y.preloadFile=Jc,y.staticInit(),Me(),r.noExitRuntime)r.noExitRuntime;if(r.preloadPlugins)Vc=r.preloadPlugins;if(r.print)O=r.print;if(r.printErr)F=r.printErr;if(r.wasmBinary)X=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=fr;var tl;function My(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,tl=i.emscripten_builtin_memalign,i._emscripten_stack_restore,i._emscripten_stack_alloc,i.emscripten_stack_get_current,i.__indirect_function_table}var rl={__syscall_chmod:Gm,__syscall_faccessat:Km,__syscall_fchmod:Vm,__syscall_fchown32:Jm,__syscall_fcntl64:Xm,__syscall_fstat64:Qm,__syscall_ftruncate64:ty,__syscall_getcwd:ry,__syscall_ioctl:ny,__syscall_lstat64:oy,__syscall_mkdirat:iy,__syscall_newfstatat:sy,__syscall_openat:ay,__syscall_readlinkat:cy,__syscall_rmdir:ly,__syscall_stat64:uy,__syscall_unlinkat:dy,__syscall_utimensat:fy,_localtime_js:my,_mmap_js:yy,_munmap_js:by,_tzset_js:wy,clock_time_get:Sy,emscripten_date_now:Yc,emscripten_get_heap_max:xy,emscripten_get_now:Qc,emscripten_resize_heap:Ty,environ_get:Ay,environ_sizes_get:Dy,fd_close:Oy,fd_fdstat_get:Iy,fd_read:Py,fd_seek:Ny,fd_sync:qy,fd_write:$y,memory:fr};function ts(){if(Cr>0){$n=ts;return}if(He(),Cr>0){$n=ts;return}function i(){if(r.calledRun=!0,he)return;Ze(),be?.(r),r.onRuntimeInitialized?.(),$t()}if(r.setStatus)r.setStatus("Running..."),setTimeout(()=>{setTimeout(()=>r.setStatus(""),1),i()},1);else i()}var sn=await Am();if(ts(),r.runSQLite3PostLoadInit=async function(i,u,_){delete u.runSQLite3PostLoadInit,globalThis.sqlite3ApiBootstrap=async function f(l=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),h=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},l);Object.assign(h,{allocExportName:h.useStdAlloc?"malloc":"sqlite3_malloc",deallocExportName:h.useStdAlloc?"free":"sqlite3_free",reallocExportName:h.useStdAlloc?"realloc":"sqlite3_realloc"}),["exports","memory","functionTable","wasmfsOpfsDir"].forEach((S)=>{if(typeof h[S]==="function")h[S]=h[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 U extends Error{constructor(...S){let C;if(S.length)if(V(S[0]))if(C=S[0],S.length===1)super(I(S[0]));else{let K=I(C);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=C||E.SQLITE_ERROR,this.name="SQLite3Error"}}U.toss=(...S)=>{throw new U(...S)};let N=U.toss;if(h.wasmfsOpfsDir&&!/^\/[^/]+$/.test(h.wasmfsOpfsDir))N("config.wasmfsOpfsDir must be falsy or in the form '/dir-name'.");let q=function S(C){if(!S._max)S._max=BigInt("0x7fffffffffffffff"),S._min=~S._max;return C>=S._min&&C<=S._max},H=(S)=>S>=-2147483647n-1n&&S<=2147483647n,G=function S(C){if(!S._min)S._min=Number.MIN_SAFE_INTEGER,S._max=Number.MAX_SAFE_INTEGER;return C>=S._min&&C<=S._max},ue=(S)=>S&&S.constructor&&V(S.constructor.BYTES_PER_ELEMENT)?S:!1,D=(S)=>S&&(S instanceof Uint8Array||S instanceof Int8Array||S instanceof ArrayBuffer),R=(S)=>S&&(S instanceof Uint8Array||S instanceof Int8Array||S instanceof ArrayBuffer),Q=(S)=>D(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 j 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"}}j.toss=(...S)=>{throw new j(...S)},Object.assign(E,{sqlite3_bind_blob:void 0,sqlite3_bind_text:void 0,sqlite3_create_function_v2:(S,C,K,oe,W,ge,we,me,ve)=>{},sqlite3_create_function:(S,C,K,oe,W,ge,we,me)=>{},sqlite3_create_window_function:(S,C,K,oe,W,ge,we,me,ve,M)=>{},sqlite3_prepare_v3:(S,C,K,oe,W,ge)=>{},sqlite3_prepare_v2:(S,C,K,oe,W)=>{},sqlite3_exec:(S,C,K,oe,W)=>{},sqlite3_randomness:(S,C)=>{}});let J={affirmBindableTypedArray:Q,flexibleString:ee,bigIntFits32:H,bigIntFits64:q,bigIntFitsDouble:G,isBindableTypedArray:D,isInt32:V,isSQLableTypedArray:R,isTypedArray:ue,isUIThread:()=>globalThis.window===globalThis&&!!globalThis.document,toss:function(...S){throw Error(S.join(" "))},toss3:N,typedArrayPart:b.typedArrayPart,nu:d,assert:function(S,C){if(!S)J.toss("Assertion failed:",C)},affirmDbHeader:function(S){if(S instanceof ArrayBuffer)S=new Uint8Array(S);let C="SQLite format 3";if(15>S.byteLength)N("Input does not contain an SQLite3 database header.");for(let K=0;K<15;++K)if(C.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 C=S.byteLength;if(C<512||C%512!==0)N("Byte array size",C,"is invalid for an SQLite3 db.");J.affirmDbHeader(S)}};Object.assign(b,{exports:h.exports||N("Missing API config.exports (WASM module exports)."),memory:h.memory||h.exports.memory||N("API config object requires a WebAssembly.Memory object","in either config.exports.memory (exported)","or config.memory (imported)."),pointerSize:typeof h.exports.sqlite3_libversion()==="number"?4:8,bigIntEnabled:!!h.bigIntEnabled,functionTable:h.functionTable,alloc:void 0,realloc:void 0,dealloc:void 0}),b.allocFromTypedArray=function(S){if(S instanceof ArrayBuffer)S=new Uint8Array(S);Q(S);let C=b.alloc(S.byteLength||1);return b.heapForSize(S.constructor).set(S.byteLength?S:[0],Number(C)),C};{let{allocExportName:S,deallocExportName:C,reallocExportName:K}=h;for(let oe of[S,C,K])if(!(b.exports[oe]instanceof Function))N("Missing required exports[",oe,"] function.");b.alloc=function oe(W){return oe.impl(W)||j.toss("Failed to allocate",W," bytes.")},b.alloc.impl=b.exports[S],b.realloc=function oe(W,ge){let we=oe.impl(b.ptr.coerce(W),ge);return ge?we||j.toss("Failed to reallocate",ge," 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[C]}b.compileOptionUsed=function S(C){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,ge;while(ge=E.sqlite3_compileoption_get(W++))S._opt(ge,oe),K[oe[0]]=oe[1];return S._result=K}else if(Array.isArray(C)){let K=d();return C.forEach((oe)=>{K[oe]=E.sqlite3_compileoption_used(oe)}),K}else if(typeof C==="object")return Object.keys(C).forEach((K)=>{C[K]=E.sqlite3_compileoption_used(K)}),C;return typeof C==="string"?!!E.sqlite3_compileoption_used(C):!1},b.pstack=d({restore:b.exports.sqlite3__wasm_pstack_restore,alloc:function(S){if(typeof S==="string"&&!(S=b.sizeofIR(S)))j.toss("Invalid value for pstack.alloc(",arguments[0],")");return b.exports.sqlite3__wasm_pstack_alloc(S)||j.toss("Could not allocate",S,"bytes from the pstack.")},allocChunks:function(S,C){if(typeof C==="string"&&!(C=b.sizeofIR(C)))j.toss("Invalid size value for allocChunks(",arguments[1],")");let K=b.pstack.alloc(S*C),oe=[K],W=1,ge=C;for(;W<S;++W,ge+=C)oe.push(b.ptr.add(K,ge));return oe},allocPtr:(S=1,C=!0)=>S===1?b.pstack.alloc(C?8:b.ptr.size):b.pstack.allocChunks(S,C?8:b.ptr.size),call:function(S){let C=b.pstack.pointer;try{return S(pe)}finally{b.pstack.restore(C)}}}),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 C=S[0];if(C.byteLength===0)return b.exports.sqlite3_randomness(0,b.ptr.null),C;let K=b.pstack.pointer;try{let oe=C.byteLength,W=0,ge=b.exports.sqlite3_randomness,we=b.heap8u(),me=oe<512?oe:512,ve=b.pstack.alloc(me);do{let M=oe>me?me:oe;ge(M,ve),C.set(b.typedArrayPart(we,ve,b.ptr.add(ve,M)),W),oe-=M,W+=M}while(oe>0)}catch(oe){h.error("Highly unexpected (and ignored!) exception in sqlite3_randomness():",oe)}finally{b.pstack.restore(K)}return C}b.exports.sqlite3_randomness(...S)},E.sqlite3_wasmfs_opfs_dir=function(){if(this.dir!==void 0)return this.dir;let S=h.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(C){return this.dir=""}}.bind(d()),E.sqlite3_wasmfs_filename_is_persistent=function(S){let C=E.sqlite3_wasmfs_opfs_dir();return C&&S?S.startsWith(C+"/"):!1},E.sqlite3_js_db_uses_vfs=function(S,C,K=0){try{let oe=E.sqlite3_vfs_find(C);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=[],C=E.sqlite3_vfs_find(b.ptr.null);while(C){let K=new E.sqlite3_vfs(C);S.push(b.cstrToJs(K.$zName)),C=K.$pNext,K.dispose()}return S},E.sqlite3_js_db_export=function(S,C=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),ge=b.ptr.add(W,8),we=C?b.isPtr(C)?C:b.scopedAllocCString(""+C):b.ptr.null,me=b.exports.sqlite3__wasm_db_serialize(S,we,ge,W,0);if(me)N("Database serialization failed with code",pe.capi.sqlite3_js_rc_str(me));oe=b.peekPtr(ge);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,C=b.ptr.null)=>J.sqlite3__wasm_db_vfs(S,C),E.sqlite3_js_aggregate_context=(S,C)=>E.sqlite3_aggregate_context(S,C)||(C?j.toss("Cannot allocate",C,"bytes for sqlite3_aggregate_context()"):0),E.sqlite3_js_posix_create_file=function(S,C,K){let oe;if(C&&b.isPtr(C))oe=C;else if(C instanceof ArrayBuffer||C instanceof Uint8Array){if(oe=b.allocFromTypedArray(C),arguments.length<3||!J.isInt32(K)||K<0)K=C.byteLength}else U.toss("Invalid 2nd argument for sqlite3_js_posix_create_file().");try{if(!J.isInt32(K)||K<0)U.toss("Invalid 3rd argument for sqlite3_js_posix_create_file().");let W=J.sqlite3__wasm_posix_create_file(S,oe,K);if(W)U.toss("Creation of file failed with sqlite3 result code",E.sqlite3_js_rc_str(W))}finally{if(oe&&oe!==C)b.dealloc(oe)}},E.sqlite3_js_vfs_create_file=function(S,C,K,oe){h.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 U.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);U.toss("Invalid 4th argument for sqlite3_js_vfs_create_file().")}try{let ge=J.sqlite3__wasm_vfs_create_file(S,C,W,oe);if(ge)U.toss("Creation of file failed with sqlite3 result code",E.sqlite3_js_rc_str(ge))}finally{if(W&&W!==K)b.dealloc(W)}},E.sqlite3_js_sql_to_string=(S)=>{if(typeof S==="string")return S;let C=ee(v);return C===v?void 0:C},E.sqlite3_db_config=function(S,C,...K){switch(C){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,C,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,C,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,C,K[0]);default:return E.SQLITE_MISUSE}}.bind(d()),E.sqlite3_value_to_js=function(S,C=!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),ge=E.sqlite3_value_blob(S);if(W&&!ge)pe.WasmAllocError.toss("Cannot allocate memory for blob argument of",W,"byte(s)");K=W?b.heap8u().slice(Number(ge),Number(ge)+Number(W)):null;break}case E.SQLITE_NULL:K=null;break;default:if(C)N(E.SQLITE_MISMATCH,"Unhandled sqlite3_value_type():",oe);K=void 0}return K},E.sqlite3_values_to_js=function(S,C,K=!0){let oe,W=[];for(oe=0;oe<S;++oe)W.push(E.sqlite3_value_to_js(b.peekPtr(b.ptr.add(C,b.ptr.size*oe)),K));return W},E.sqlite3_result_error_js=function(S,C){if(C instanceof j)E.sqlite3_result_error_nomem(S);else E.sqlite3_result_error(S,""+C,-1)},E.sqlite3_result_js=function(S,C){if(C instanceof Error){E.sqlite3_result_error_js(S,C);return}try{switch(typeof C){case"undefined":break;case"boolean":E.sqlite3_result_int(S,C?1:0);break;case"bigint":if(J.bigIntFits32(C))E.sqlite3_result_int(S,Number(C));else if(J.bigIntFitsDouble(C))E.sqlite3_result_double(S,Number(C));else if(b.bigIntEnabled)if(J.bigIntFits64(C))E.sqlite3_result_int64(S,C);else N("BigInt value",C.toString(),"is too BigInt for int64.");else N("BigInt value",C.toString(),"is too BigInt.");break;case"number":{let K;if(J.isInt32(C))K=E.sqlite3_result_int;else if(b.bigIntEnabled&&Number.isInteger(C)&&J.bigIntFits64(BigInt(C)))K=E.sqlite3_result_int64;else K=E.sqlite3_result_double;K(S,C);break}case"string":{let[K,oe]=b.allocCString(C,!0);E.sqlite3_result_text(S,K,oe,E.SQLITE_WASM_DEALLOC);break}case"object":if(C===null){E.sqlite3_result_null(S);break}else if(J.isBindableTypedArray(C)){let K=b.allocFromTypedArray(C);E.sqlite3_result_blob(S,K,C.byteLength,E.SQLITE_WASM_DEALLOC);break}default:N("Don't not how to handle this UDF result value:",typeof C,C)}}catch(K){E.sqlite3_result_error_js(S,K)}},E.sqlite3_column_js=function(S,C,K=!0){let oe=E.sqlite3_column_value(S,C);return oe===0?void 0:E.sqlite3_value_to_js(oe,K)};{let S=function(C,K,oe){if(oe=E[oe],!this.ptr)this.ptr=b.allocPtr();else b.pokePtr(this.ptr,0);let W=oe(C,K,this.ptr);if(W)return U.toss(W,arguments[2]+"() failed with code "+W);let ge=b.peekPtr(this.ptr);return ge?E.sqlite3_value_to_js(ge,!0):void 0}.bind(d());E.sqlite3_preupdate_new_js=(C,K)=>S(C,K,"sqlite3_preupdate_new"),E.sqlite3_preupdate_old_js=(C,K)=>S(C,K,"sqlite3_preupdate_old"),E.sqlite3changeset_new_js=(C,K)=>S(C,K,"sqlite3changeset_new"),E.sqlite3changeset_old_js=(C,K)=>S(C,K,"sqlite3changeset_old")}E.sqlite3_js_retry_busy=function(S,C,K){for(let oe=1;oe<=S;++oe)try{if(K&&oe>1)K(oe);let W=C();if(E.SQLITE_BUSY===W){if(oe===S)throw new U(W,["sqlite3_js_retry_busy() max retry attempts (",S,") reached."].join(""));continue}return W}catch(W){if(oe<S&&W instanceof U&&W.resultCode===E.SQLITE_BUSY)continue;throw W}};let pe={WasmAllocError:j,SQLite3Error:U,capi:E,util:J,wasm:b,config:h,version:d(),client:void 0,asyncPostInit:async function S(){if(S.isReady instanceof Promise)return S.isReady;let C=this.initializersAsync;delete this.initializersAsync;let K=async()=>{if(!pe.__isUnderTest)delete pe.util,delete pe.StructBinder,delete pe.opfs;return pe},oe=(ge)=>{throw h.error("an async sqlite3 initializer failed:",ge),ge};if(!C||!C.length)return S.isReady=K().catch(oe);C=C.map((ge)=>ge instanceof Function?async(we)=>ge(pe):ge),C.push(K);let W=Promise.resolve(pe);while(C.length)W=W.then(C.shift());return S.isReady=W.catch(oe)}.bind(f),scriptInfo:void 0};if(typeof _<"u")pe.__isUnderTest=!!_;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 u<"u")pe.config.emscripten=u;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(l){if(l.bigIntEnabled===void 0)l.bigIntEnabled=!!globalThis.BigInt64Array;let d=(...g)=>{throw Error(g.join(" "))};if(!l.pointerSize&&!l.pointerIR&&l.alloc&&l.dealloc){let g=l.alloc(1);l.pointerSize=typeof g==="bigint"?8:4,l.dealloc(g)}if(l.pointerSize&&!l.pointerIR)l.pointerIR=l.pointerSize===4?"i32":"i64";let h=l.pointerIR??="i32",E=l.pointerSize??=h==="i32"?4:h==="i64"?8:0;if(delete l.pointerSize,delete l.pointerIR,h!=="i32"&&h!=="i64")d("Invalid pointerIR:",h);else if(E!==8&&E!==4)d("Invalid pointerSize:",E);let b=l.bigIntEnabled?(g)=>BigInt(g||0):(g)=>d("BigInt support is disabled in this build."),V=E===4?(g)=>Number(g||0):b,U=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(l,"ptr",{enumerable:!0,get:()=>g,set:()=>d("The ptr property is read-only.")}),function w(T,P){return Object.defineProperty(g,T,{enumerable:!0,get:()=>P,set:()=>d("ptr["+T+"] is read-only.")}),w}("null",U)("size",E)("ir",h)("coerce",V)("add",N)("addn",h===4?N:(...w)=>Number(N(...w)))}if(!l.exports)Object.defineProperty(l,"exports",{enumerable:!0,configurable:!0,get:()=>l.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"),l.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=l.memory instanceof WebAssembly.Memory?l.memory:l.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),l.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};l.heap8=()=>H().HEAP8,l.heap8u=()=>H().HEAP8U,l.heap16=()=>H().HEAP16,l.heap16u=()=>H().HEAP16U,l.heap32=()=>H().HEAP32,l.heap32u=()=>H().HEAP32U,l.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(l.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=l.functionTable;delete l.functionTable,l.functionTable=G?()=>G:()=>l.exports.__indirect_function_table,l.functionEntry=function(g){let w=l.functionTable();return g<w.length?w.get(V(g)):void 0},l.jsFuncToWasm=function g(w,T){if(!g._)g._={sigTypes:Object.assign(Object.create(null),{i:"i32",p:h,P:h,s:h,j:"i64",f:"f32",d:"f64"}),typeCodes:Object.assign(Object.create(null),{f64:124,f32:125,i64:126,i32:127}),uleb128Encode:(A,L,Y)=>{if(Y<128)A[L](Y);else A[L](Y%128|128,Y>>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 P=g._,te=P.sigParams(T),se=[1,96];P.uleb128Encode(se,"push",te.length);for(let A of te)P.pushSigType(se,A);if(T[0]==="v")se.push(0);else se.push(1),P.pushSigType(se,T[0]);return P.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 ue=function(w,T,P){if(P&&!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=l.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),P)q.scopedAlloc.pushPtr(A);return A}catch(L){if(!(L instanceof TypeError)){if(A===se)q.freeFuncIndexes.push(se);throw L}}try{let L=l.jsFuncToWasm(w,T);if(te.set(A,L),P)q.scopedAlloc.pushPtr(A)}catch(L){if(A===se)q.freeFuncIndexes.push(se);throw L}return A};l.installFunction=(g,w)=>ue(g,w,!1),l.scopedInstallFunction=(g,w)=>ue(g,w,!0),l.uninstallFunction=function(g){if(!g&&U!==g)return;let w=l.functionTable();q.freeFuncIndexes.push(g);let T=w.get(g);return w.set(g,null),T},l.peek=function(w,T="i8"){if(T.endsWith("*"))T=h;let P=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=P.HEAP8[Number(w)>>0];break;case"i16":se=P.HEAP16[Number(w)>>1];break;case"i32":se=P.HEAP32[Number(w)>>2];break;case"float":case"f32":se=P.HEAP32F[Number(w)>>2];break;case"double":case"f64":se=Number(P.HEAP64F[Number(w)>>3]);break;case"i64":if(P.HEAP64){se=b(P.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},l.poke=function(g,w,T="i8"){if(T.endsWith("*"))T=h;let P=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":P.HEAP8[Number(te)>>0]=w;continue;case"i16":P.HEAP16[Number(te)>>1]=w;continue;case"i32":P.HEAP32[Number(te)>>2]=w;continue;case"float":case"f32":P.HEAP32F[Number(te)>>2]=w;continue;case"double":case"f64":P.HEAP64F[Number(te)>>3]=w;continue;case"i64":if(P.HEAP64){P.HEAP64[Number(te)>>3]=b(w);continue}default:d("Invalid type for poke(): "+T)}return this},l.peekPtr=(...g)=>l.peek(g.length===1?g[0]:g,h),l.pokePtr=(g,w=0)=>l.poke(g,w,h),l.peek8=(...g)=>l.peek(g.length===1?g[0]:g,"i8"),l.poke8=(g,w)=>l.poke(g,w,"i8"),l.peek16=(...g)=>l.peek(g.length===1?g[0]:g,"i16"),l.poke16=(g,w)=>l.poke(g,w,"i16"),l.peek32=(...g)=>l.peek(g.length===1?g[0]:g,"i32"),l.poke32=(g,w)=>l.poke(g,w,"i32"),l.peek64=(...g)=>l.peek(g.length===1?g[0]:g,"i64"),l.poke64=(g,w)=>l.poke(g,w,"i64"),l.peek32f=(...g)=>l.peek(g.length===1?g[0]:g,"f32"),l.poke32f=(g,w)=>l.poke(g,w,"f32"),l.peek64f=(...g)=>l.peek(g.length===1?g[0]:g,"f64"),l.poke64f=(g,w)=>l.poke(g,w,"f64"),l.getMemValue=l.peek,l.getPtrValue=l.peekPtr,l.setMemValue=l.poke,l.setPtrValue=l.pokePtr,l.isPtr32=(g)=>typeof g==="number"&&g>=0&&g===(g|0),l.isPtr64=(g)=>typeof g==="bigint"?g>=0:l.isPtr32(g),l.isPtr=E===4?l.isPtr32:l.isPtr64,l.cstrlen=function(g){if(!g||!l.isPtr(g))return null;g=Number(g);let w=H().HEAP8U,T=g;for(;w[T]!==0;++T);return T-g};let D=typeof SharedArrayBuffer>"u"?function(){}:SharedArrayBuffer,R=(g)=>g.buffer instanceof D;l.isSharedTypedArray=R;let Q=(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)};l.typedArrayPart=Q;let ee=(g,w,T)=>q.utf8Decoder.decode(Q(g,w,T));l.typedArrayToString=ee,l.cstrToJs=function(g){let w=l.cstrlen(g);return w?ee(H().HEAP8U,Number(g),Number(g)+w):w===null?w:""},l.jstrlen=function(g){if(typeof g!=="string")return null;let w=g.length,T=0;for(let P=0;P<w;++P){let te=g.charCodeAt(P);if(te>=55296&&te<=57343)te=65536+((te&1023)<<10)|g.charCodeAt(++P)&1023;if(te<=127)++T;else if(te<=2047)T+=2;else if(te<=65535)T+=3;else T+=4}return T},l.jstrcpy=function(g,w,T=0,P=-1,te=!0){if(!w||!(w instanceof Int8Array)&&!(w instanceof Uint8Array))d("jstrcpy() target must be an Int8Array or Uint8Array.");if(P=Number(P),T=Number(T),P<0)P=w.length-T;if(!(P>0)||!(T>=0))return 0;let se=0,A=g.length,L=T,Y=T+P-(te?1:0);for(;se<A&&T<Y;++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>=Y)break;w[T++]=ne}else if(ne<=2047){if(T+1>=Y)break;w[T++]=192|ne>>6,w[T++]=128|ne&63}else if(ne<=65535){if(T+2>=Y)break;w[T++]=224|ne>>12,w[T++]=128|ne>>6&63,w[T++]=128|ne&63}else{if(T+3>=Y)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},l.cstrncpy=function(g,w,T){if(!g||!w)d("cstrncpy() does not accept NULL strings.");if(T<0)T=l.cstrlen(strPtr)+1;else if(!(T>0))return 0;let P=l.heap8u(),te=0,se,A=Number(g),L=Number(w);for(;te<T&&(se=P[L+te]);++te)P[A+te]=se;if(te<T)P[A+te++]=0;return te},l.jstrToUintArray=(g,w=!1)=>q.utf8Encoder.encode(w?g+"\x00":g);let j=(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,P){if(j(l,P),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=U,w?[se,te.length]:se}finally{if(A)l.dealloc(A)}};l.allocCString=(g,w=!1)=>J(g,w,l.alloc,"allocCString()"),l.scopedAllocPush=function(){j(l,"scopedAllocPush");let g=[];return q.scopedAlloc.push(g),g},l.scopedAllocPop=function(g){j(l,"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(l.functionEntry(T))l.uninstallFunction(T);else l.dealloc(T)},l.scopedAlloc=function(g){if(!q.scopedAlloc.length)d("No scopedAllocPush() scope is active.");let w=V(l.alloc(g));return q.scopedAlloc.pushPtr(w)},Object.defineProperty(l.scopedAlloc,"level",{configurable:!1,enumerable:!1,get:()=>q.scopedAlloc.length,set:()=>d("The 'active' property is read-only.")}),l.scopedAllocCString=(g,w=!1)=>J(g,w,l.scopedAlloc,"scopedAllocCString()");let pe=function(g,w){let T=l[g?"scopedAlloc":"alloc"]((w.length+1)*l.ptr.size),P=0;return w.forEach((te)=>{l.pokePtr(N(T,l.ptr.size*P++),l[g?"scopedAllocCString":"allocCString"](""+te))}),l.pokePtr(N(T,l.ptr.size*P),0),T};l.scopedAllocMainArgv=(g)=>pe(!0,g),l.allocMainArgv=(g)=>pe(!1,g),l.cArgvToJs=(g,w)=>{let T=[];for(let P=0;P<g;++P){let te=l.peekPtr(N(w,l.ptr.size*P));T.push(te?l.cstrToJs(te):null)}return T},l.scopedAllocCall=function(g){l.scopedAllocPush();try{return g()}finally{l.scopedAllocPop()}};let S=function(g,w,T){j(l,T);let P=w?"i64":h,te=l[T](g*(w?8:E));if(l.poke(te,0,P),g===1)return te;let se=[te];for(let A=1;A<g;++A)te=N(te,w?8:E),se[A]=te,l.poke(te,0,P);return se};l.allocPtr=(g=1,w=!0)=>S(g,w,"alloc"),l.scopedAllocPtr=(g=1,w=!0)=>S(g,w,"scopedAlloc"),l.xGet=function(g){return l.exports[g]||d("Cannot find exported symbol:",g)};let C=(g,w)=>d(g+"() requires",w,"argument(s).");l.xCall=function(g,...w){let T=g instanceof Function?g:l.xGet(g);if(!(T instanceof Function))d("Exported symbol",g,"is not a function.");if(T.length!==w.length)C(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 ge=(g)=>typeof g==="string"?l.scopedAllocCString(g):V(g);K.set("string",ge).set("utf8",ge),oe.set("string",(g)=>l.cstrToJs(g)).set("utf8",oe.get("string")).set("string:dealloc",(g)=>{try{return g?l.cstrToJs(g):null}finally{l.dealloc(g)}}).set("utf8:dealloc",oe.get("string:dealloc")).set("json",(g)=>JSON.parse(l.cstrToJs(g))).set("json:dealloc",(g)=>{try{return g?JSON.parse(l.cstrToJs(g)):null}finally{l.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),P=T.get(w);if(P===void 0)T.set(w,P=[]);return P}convertArg(w,T,P){let te=this.singleton;if(!te&&this.isContext)te=this.contextMap(this.contextKey(T,P));if(te&&te.length===2&&te[0]===w)return te[1];if(w instanceof Function){if(this.callProxy)w=this.callProxy(w);let se=ue(w,this.signature,this.isTransient);if(g.debugFuncInstall)g.debugOut("FuncPtrAdapter installed",this,this.contextKey(T,P),"@"+se,w);if(te){if(te[1]){if(g.debugFuncInstall)g.debugOut("FuncPtrAdapter uninstalling",this,this.contextKey(T,P),"@"+te[1],w);try{q.scopedAlloc.pushPtr(te[1])}catch(A){}}te[0]=arguments[0]||U,te[1]=se}return se}else if(l.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,P),"@"+te[1],w);try{q.scopedAlloc.pushPtr(te[1])}catch(se){}te[0]=te[1]=w||U}return w||U}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,l.xWrap=function g(w,T,...P){if(arguments.length===3&&Array.isArray(arguments[2]))P=arguments[2];if(l.isPtr(w))w=l.functionEntry(w)||d("Function pointer not found in WASM function table.");let te=w instanceof Function,se=te?w:l.xGet(w);if(te)w=se.name||"unnamed function";if(P.length!==se.length)C(w,se.length);if(se.length===0&&(T===null||T==="null"))return se;ve(T);for(let L of P)if(L instanceof we)K.set(L,(...Y)=>L.convertArg(...Y));else me(L);let A=q.xWrap;if(se.length===0)return(...L)=>L.length?C(w,se.length):A.convertResult(T,se.call(null));return function(...L){if(L.length!==se.length)C(w,se.length);let Y=l.scopedAllocPush();try{let ne=0;if(g.debug)console.debug("xWrap() preparing: resultType ",T,"xf",se,"argTypes",P,"args",L);for(;ne<L.length;++ne)L[ne]=A.convertArgNoCheck(P[ne],L[ne],L,ne);if(g.debug)console.debug("xWrap() calling: resultType ",T,"xf",se,"argTypes",P,"args",L);return A.convertResultNoCheck(T,se.apply(null,L))}finally{l.scopedAllocPop(Y)}}};let M=function(g,w,T,P,te,se){if(typeof T==="string"){if(w===1)return se.get(T);else if(w===2){if(!P)return se.delete(T),g;else if(!(P instanceof Function))d(te,"requires a function argument.");return se.set(T,P),g}}d("Invalid arguments to",te)};return l.xWrap.resultAdapter=function g(w,T){return M(g,arguments.length,w,T,"resultAdapter()",oe)},l.xWrap.argAdapter=function g(w,T){return M(g,arguments.length,w,T,"argAdapter()",K)},l.xWrap.FuncPtrAdapter=K.FuncPtrAdapter,l.xCallWrapped=function(g,w,T,...P){if(Array.isArray(arguments[3]))P=arguments[3];return l.xWrap(g,w,T||[]).apply(null,P||[])},l.xWrap.testConvertArg=q.xWrap.convertArg,l.xWrap.testConvertResult=q.xWrap.convertResult,l},globalThis.WhWasmUtilInstaller.yawl=function(l){let d=()=>fetch(l.uri,{credentials:"same-origin"}),h=this,E=function(b){if(l.wasmUtilTarget){let I=(...U)=>{throw Error(U.join(" "))},V=l.wasmUtilTarget;if(V.module=b.module,V.instance=b.instance,!V.instance.exports.memory)V.memory=l?.imports?.env?.memory||I("Missing 'memory' object!");if(!V.alloc&&b.instance.exports.malloc){let U=b.instance.exports;V.alloc=function(N){return U.malloc(N)||I("Allocation of",N,"bytes failed.")},V.dealloc=function(N){N&&U.free(N)}}h(V)}if(b.config=l,l.onload)l.onload(b);return b};return WebAssembly.instantiateStreaming?()=>WebAssembly.instantiateStreaming(d(),l.imports||{}).then(E):()=>d().then((b)=>b.arrayBuffer()).then((b)=>WebAssembly.instantiate(b,l.imports||{})).then(E)}.bind(globalThis.WhWasmUtilInstaller),globalThis.Jaccwabyt=function f(l){let d=(...z)=>{throw Error(z.join(" "))};{let z=l.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.");l.heap=z}["alloc","dealloc"].forEach(function(z){l[z]instanceof Function||d("Config option '"+z+"' must be a function.")});let h=f,{heap:E,alloc:b,dealloc:I}=l;l.realloc;let V=l.log||console.debug.bind(console),U=l.memberPrefix||"",N=l.memberSuffix||"",{BigInt:q,BigInt64Array:H}=globalThis,G=l.bigIntEnabled??!!H,ue,D=l.pointerSize||l.ptrSize||(typeof(ue=b(1))==="bigint"?8:4),R=l.pointerIR||l.ptrIR||(D===4?"i32":"i64");if(ue)I(ue),ue=void 0;if(D!==4&&D!==8)d("Invalid pointer size:",D);if(R!=="i32"&&R!=="i64")d("Invalid pointer representation:",R);let Q=G&&q?(z)=>q(z||0):(z)=>d("BigInt support is disabled in this build."),ee=R=="i32"?Number:Q,j=ee(0),J=function(...z){let ie=j;for(let fe=0;fe<z.length;++fe)ie+=ee(z[fe]);return ie},pe=function(...z){return J(this.pointer,...z)};if(!h.debugFlags)h.__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},h.debugFlags=h.__makeDebugFlags();let S=!0,C=(z)=>z[1]==="(",K=(z)=>z==="p"||z==="P"||z==="s",oe=(z)=>z==="P",W=(z)=>z?C(z)?"p":z[0]:void 0,ge=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 D;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(D){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)},M=function(z){switch(W(z)){case"p":case"P":case"s":switch(D){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 Q;case"p":case"P":case"s":switch(D){case 4:return Number;case 8:return Q}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.")},P=function z(ie,fe=!0){let Ee=z.map.get(ie);if(!Ee&&fe)z.map.set(ie,Ee=z.create(ie));return Ee};P.map=new WeakMap,P.create=(z)=>Object.assign(Object.create(null),{o:z,p:void 0,ownsPointer:!1,zod:!1,xb:0});let te=(z)=>P.map.delete(z),se=(z)=>typeof z==="number"&&z===(z|0)&&z>=0,L=D===4?se:(z)=>typeof z==="bigint"&&z>=0||se(z),Y=(z)=>L(z)&&z>0,ne=function(z,ie,fe){let Ee=P(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 Ie;while(Ie=ie.ondispose.pop())try{if(Ie instanceof Function)Ie.call(ie);else if(Ie instanceof Ct)Ie.dispose();else if(L(Ie))I(Ie)}catch(Je){console.warn("ondispose() for",z.structName,"@",fe,"threw. NOT propagating it.",Je)}}else if(ie.ondispose instanceof Function)try{ie.ondispose()}catch(Ie){console.warn("ondispose() for",z.structName,"@",fe,"threw. NOT propagating it.",Ie)}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}),ke=(z)=>({...ye(),value:z}),Pe=function(ie,fe,Ee){let Ie,Je=(Ke)=>{Y(Ke)||d("Invalid pointer value",arguments[0],"for",ie.structName,"constructor.")};if(arguments.length>=3)if(Ee&&typeof Ee==="object")Ie=Ee,Ee=Ie?.wrap;else Je(Ee),Ie={wrap:Ee};else Ie={};let ht=!Ee,At=0,Pt=!1;if(Ee)Je(Ee),Pt=!!Ie?.takeOwnership;else{let Ke=Ie?.extraBytes??0;if(Ke<0||Ke!==(Ke|0))d("Invalid extraBytes value:",Ie?.extraBytes);At=ie.structInfo.sizeof+Ke,Ee=b(At)||d("Allocation of",ie.structName,"structure failed."),Pt=!0}try{if(Ie?.debugFlags)fe.debugFlags(Ie.debugFlags);if(ie.debugFlags.__flags.alloc)V("debug.alloc:",ht?"":"EXTERNAL",ie.structName,"instance:",ie.structInfo.sizeof,"bytes @"+Ee);if(ht)E().fill(0,Number(Ee),Number(Ee)+At);let Ke=P(fe);if(Ke.p=Ee,Ke.ownsPointer=Pt,Ke.xb=At?At-ie.structInfo.sizeof:0,Ke.zod=!!Ie?.zeroOnDispose,Ie?.ondispose&&Ie.ondispose!==Ee)fe.addOnDispose(Ie.ondispose)}catch(Ke){throw ne(ie,fe,Ee),Ke}},$e=function z(ie){return z.rxSig1??=/^[ipPsjfdcC]$/,z.rxSig2??=/^[vipPsjfdcC]\([ipPsjfdcC]*\)$/,z.rxSig1.test(ie)||z.rxSig2.test(ie)},Ve=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),dt=function(z,ie,fe,Ee){let Ie=Ve(z)[ie];if(arguments.length===3)return Ie[fe];if(Ee)return Ie[fe]=Ee;return delete Ie[fe]},jt=function(z,...ie){return dt(this,0,z,...ie)},Nr=function(z,ie){$e(ie)&&d(z,"(",ie,") collides with a data type signature.")},B=function(z,...ie){return Nr("Setter adaptor",z),dt(this,1,z,...ie)},re=function(z,...ie){return Nr("Struct adaptor",z),dt(this,2,z,...ie)},ae=function(z,ie){let fe=typeof ie==="string"?dt(z,2,ie):ie;if(typeof fe!=="object")d("Invalid struct mapping object. Arg =",ie,JSON.stringify(fe));return fe},Se=ke((z)=>U+z+N),Ae=function(z,ie,fe=!0){let Ee=z.members[ie];if(!Ee&&(U||N)){for(let Ie of Object.values(z.members))if(Ie.key===ie){Ee=Ie;break}if(!Ee&&fe)d(w(z.name||z.structName,ie),"is not a mapped struct member.")}return Ee},Ce=function z(ie,fe,Ee=!1){if(!z._)z._=(Je)=>Je.replace(/[^vipPsjrdcC]/g,"").replace(/[pPscC]/g,"i");let Ie=Ae(ie.structInfo,fe,!0);return Ee?z._(Ie.signature):Ie.signature},Re=ke(function(){let z=[];for(let ie of Object.keys(this.structInfo.members))z.push(this.memberKey(ie));return z}),Le=new TextDecoder("utf-8"),Ge=new TextEncoder,tt=typeof SharedArrayBuffer>"u"?function(){}:SharedArrayBuffer,Ue=function(z,ie,fe){if(D===8)ie=Number(ie),fe=Number(fe);return Le.decode(z.buffer instanceof tt?z.slice(ie,fe):z.subarray(ie,fe))},wt=function(z,ie,fe=!1){let Ee=Ae(z.structInfo,ie,fe);return Ee&&Ee.signature.length===1&&Ee.signature[0]==="s"?Ee:!1},Ht=function(z){if(z.signature==="s")return;d("Invalid member type signature for C-string value:",JSON.stringify(z))},an=function(ie,fe){let Ee=Ae(ie.structInfo,fe,!0);Ht(Ee);let Ie=ie[Ee.key];if(!Ie)return null;let Je=Ie,ht=E();for(;ht[Je]!==0;++Je);return Ie===Je?"":Ue(ht,Ie,Je)},Jt=function(z,...ie){if(z.ondispose){if(!Array.isArray(z.ondispose))z.ondispose=[z.ondispose]}else z.ondispose=[];z.ondispose.push(...ie)},qr=function(z){let ie=Ge.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},Fn=function(z,ie,fe){let Ee=Ae(z.structInfo,ie,!0);Ht(Ee);let Ie=qr(fe);return z[Ee.key]=Ie,Jt(z,Ie),z},Ct=function(ie,fe){if(arguments[2]!==ke)d("Do not call the StructType constructor","from client-level code.");Object.defineProperties(this,{structName:ke(ie),structInfo:ke(fe)})};Ct.prototype=Object.create(null,{dispose:ke(function(){ne(this.constructor,this)}),lookupMember:ke(function(z,ie=!0){return Ae(this.structInfo,z,ie)}),memberToJsString:ke(function(z){return an(this,z)}),memberIsString:ke(function(z,ie=!0){return wt(this,z,ie)}),memberKey:Se,memberKeys:Re,memberSignature:ke(function(z,ie=!1){return Ce(this,z,ie)}),memoryDump:ke(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 P(this,!1)?.xb??0}},zeroOnDispose:{configurable:!1,enumerable:!1,get:function(){return P(this,!1)?.zod??!!this.structInfo.zeroOnDispose}},pointer:{configurable:!1,enumerable:!1,get:function(){return P(this,!1)?.p},set:()=>d("Cannot assign the 'pointer' property of a struct.")},setMemberCString:ke(function(z,ie){return Fn(this,z,ie)})}),Object.assign(Ct.prototype,{addOnDispose:function(...z){return Jt(this,...z),this}}),Object.defineProperties(Ct,{allocCString:ke(qr),isA:ke((z)=>z instanceof Ct),hasExternalPointer:ke((z)=>{let ie=P(z,!1);return!!(ie?.p&&!ie?.ownsPointer)}),memberKey:Se});let Ao=function(z){return z.get||(z.adaptGet?Mt.adaptGet(z.adaptGet):void 0)},nl=function(z){return z.set||(z.adaptSet?Mt.adaptSet(z.adaptSet):void 0)},Fy=function z(ie,fe,Ee){let Ie=z.innerStructs??=new Map,Je=ie.memberKey(fe);if(Ee.signature!==void 0)d("'signature' cannot be used on an embedded struct (",ie.structName,".",Je,").");if(nl(Ee))d("'set' and 'adaptSet' are not permitted for nested struct members.");Ee.structName??=ie.structName+"::"+fe,Ee.key=Je,Ee.name=fe,Ee.constructor=this.call(this,Ee.structName,Ee);let ht=Ao(Ee),At=Object.assign(Object.create(null),{configurable:!1,enumerable:!1,set:T(ie.structName,Je),get:function(){let Pt=this.debugFlags.__flags,Ke=this.pointer,gt=Ke+"."+Je,Ne=Ie.get(gt);if(Pt.getter)V("debug.getter: k =",gt);if(!Ne)Ne=new Ee.constructor(J(Ke,Ee.offset)),Ie.set(gt,Ne),this.addOnDispose(()=>Ne.dispose()),Ne.addOnDispose(()=>Ie.delete(gt));if(ht)Ne=ht.apply(this,[Ne,Je]);if(Pt.getter)V("debug.getter: result =",Ne);return Ne}});Object.defineProperty(ie.prototype,Je,At)},zy=function z(ie,fe,Ee){if(Ee=ae(this,Ee),Ee.members)return Fy.call(this,ie,fe,Ee);if(!z.cache){z.cache={getters:{},setters:{},sw:{}};let gt=["i","c","C","p","P","s","f","d","v()"];if(G)gt.push("j");gt.forEach(function(Ne){z.cache.getters[Ne]=ve(Ne),z.cache.setters[Ne]=M(Ne),z.cache.sw[Ne]=g(Ne)}),z.sigCheck=function(Ne,ft,Do,il){if(Object.prototype.hasOwnProperty.call(Ne,Do))d(Ne.structName,"already has a property named",Do+".");$e(il)||d("Malformed signature for",w(Ne.structName,ft)+":",il)}}let Ie=ie.memberKey(fe);z.sigCheck(ie.prototype,fe,Ie,Ee.signature),Ee.key=Ie,Ee.name=fe;let Je=W(Ee.signature),ht=w(ie.structName,Ie),At=ie.debugFlags.__flags,Pt=Ao(Ee),Ke=Object.create(null);if(Ke.configurable=!1,Ke.enumerable=!1,Ke.get=function(){if(At.getter)V("debug.getter:",z.cache.getters[Je],"for",ge(Je),ht,"@",this.pointer,"+",Ee.offset,"sz",Ee.sizeof);let gt=new DataView(E().buffer,Number(this.pointer)+Ee.offset,Ee.sizeof)[z.cache.getters[Je]](0,S);if(Pt)gt=Pt.apply(this,[Ie,gt]);if(At.getter)V("debug.getter:",ht,"result =",gt);return gt},Ee.readOnly)Ke.set=T(ie.prototype.structName,Ie);else{let gt=nl(Ee);Ke.set=function(Ne){if(At.setter)V("debug.setter:",z.cache.setters[Je],"for",ge(Je),ht,"@",this.pointer,"+",Ee.offset,"sz",Ee.sizeof,Ne);if(!this.pointer)d("Cannot set native property on a disposed",this.structName,"instance.");if(gt)Ne=gt.apply(this,[Ie,Ne]);if(Ne===null||Ne===void 0)Ne=j;else if(K(Ee.signature)&&!L(Ne))if(oe(Ee.signature)&&Ne instanceof Ct){if(Ne=Ne.pointer||j,At.setter)V("debug.setter:",ht,"resolved to",Ne)}else d("Invalid value for pointer-type",ht+".");new DataView(E().buffer,Number(this.pointer)+Ee.offset,Ee.sizeof)[z.cache.setters[Je]](0,z.cache.sw[Je](Ne),S)}}Object.defineProperty(ie.prototype,Ie,Ke)},ol=function z(ie,fe,Ee=Object.create(null)){let Ie=function Ne(ft){if(!(this instanceof Ne))d("The",ie,"constructor may only be called via 'new'.");Pe(Ne,this,...arguments)},Je=this,ht=(Ne)=>typeof Ne==="string"&&$e(Ne)?{signature:Ne}:ae(Je,Ne);if(arguments.length===1)fe=ht(ie),ie=fe.structName||fe.name;else if(arguments.length===2)fe=ht(fe),fe.name??=ie;else fe=ht(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((Ne)=>{re.call(z,Ne,fe.adapt.struct[Ne])}),Object.keys(fe.adapt.set||{}).forEach((Ne)=>{B.call(z,Ne,fe.adapt.set[Ne])}),Object.keys(fe.adapt.get||{}).forEach((Ne)=>{jt.call(z,Ne,fe.adapt.get[Ne])});if(!fe.members&&!fe.sizeof)fe.sizeof=we(fe.signature);let At=ke(h.__makeDebugFlags(Mt.debugFlags));Object.defineProperties(Ie,{debugFlags:At,isA:ke((Ne)=>Ne instanceof Ie),memberKey:Se,memberKeys:Re,structInfo:ke(fe),structName:ke(ie),ptrAdd:ke(J)}),Ie.prototype=new Ct(ie,fe,ke),Object.defineProperties(Ie.prototype,{debugFlags:At,constructor:ke(Ie),ptrAdd:ke(pe)});let Pt=!1,Ke=0,gt=!!fe.autoCalcSizeOffset;if(!gt){if(!fe.sizeof)d(ie,"description is missing its sizeof property.");fe.offset??=0}else fe.offset??=0;if(Object.keys(fe.members||{}).forEach((Ne)=>{let ft=ht(fe.members[Ne]);if(!ft.members&&!ft.sizeof){if(ft.sizeof=we(ft.signature),!ft.sizeof)d(w(ie,Ne),"is missing a sizeof property.",ft)}if(ft.offset===void 0)if(gt)ft.offset=Ke;else d(w(ie,Ne),"is missing its offset.",JSON.stringify(ft));if(fe.members[Ne]=ft,!Pt||Pt.offset<ft.offset)Pt=ft;let Do=!!ft.autoCalc;if(gt)ft.autoCalcSizeOffset=!0;if(zy.call(Je,Ie,Ne,ft),Do)ft.autoCalcSizeOffset=!0;else delete ft.autoCalcSizeOffset;Ke+=ft.sizeof}),!Pt)d("No member property descriptions found.");if(!fe.sizeof)fe.sizeof=Ke;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<Ke)console.warn("Suspect struct description:",fe,"offset =",Ke),d("Mismatch in the calculated vs. the provided sizeof/offset info.","Expected sizeof",Ke,"but got",fe.sizeof,"for",fe);return delete fe.autoCalcSizeOffset,Ie},Mt=function z(ie,fe){return arguments.length==1?ol.call(z,ie):ol.call(z,ie,fe)};if(Mt.StructType=Ct,Mt.config=l,Mt.allocCString=qr,Mt.adaptGet=jt,Mt.adaptSet=B,Mt.adaptStruct=re,Mt.ptrAdd=J,!Mt.debugFlags)Mt.debugFlags=h.__makeDebugFlags(h.debugFlags);return Mt},globalThis.sqlite3ApiBootstrap.initializers.push(function(f){let l=(...D)=>{throw Error(D.join(" "))},{capi:d,wasm:h,util:E}=f;globalThis.WhWasmUtilInstaller(h),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 h.xWrap.FuncPtrAdapter({signature:"i(pi)",contextKey:(D,R)=>D[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 h.xWrap.FuncPtrAdapter({name:"sqlite3_commit_hook",signature:"i(p)",contextKey:(D)=>D[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 h.xWrap.FuncPtrAdapter({signature:"i(pipp)",bindScope:"transient",callProxy:(D)=>{let R;return(Q,ee,j,J)=>{try{let pe=h.cArgvToJs(ee,j);if(!R)R=h.cArgvToJs(ee,J);return D(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 h.xWrap.FuncPtrAdapter({name:"sqlite3_rollback_hook",signature:"v(p)",contextKey:(D)=>D[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 h.xWrap.FuncPtrAdapter({name:"sqlite3_trace_v2::callback",signature:"i(ippp)",contextKey:(D,R)=>D[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 h.xWrap.FuncPtrAdapter({name:"sqlite3_update_hook::callback",signature:"v(pippj)",contextKey:(D)=>D[0],callProxy:(D)=>(R,Q,ee,j,J)=>{D(R,Q,h.cstrToJs(ee),h.cstrToJs(j),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(h.exports.sqlite3_progress_handler)b.core.push(["sqlite3_progress_handler",void 0,["sqlite3*","int",new h.xWrap.FuncPtrAdapter({name:"xProgressHandler",signature:"i(p)",bindScope:"context",contextKey:(D,R)=>D[0]}),"*"]]);if(h.exports.sqlite3_stmt_explain)b.core.push(["sqlite3_stmt_explain","int","sqlite3_stmt*","int"],["sqlite3_stmt_isexplain","int","sqlite3_stmt*"]);if(h.exports.sqlite3_set_authorizer)b.core.push(["sqlite3_set_authorizer","int",["sqlite3*",new h.xWrap.FuncPtrAdapter({name:"sqlite3_set_authorizer::xAuth",signature:"i(pissss)",contextKey:(D,R)=>D[0],callProxy:(D)=>(R,Q,ee,j,J,pe)=>{try{return ee=ee&&h.cstrToJs(ee),j=j&&h.cstrToJs(j),J=J&&h.cstrToJs(J),pe=pe&&h.cstrToJs(pe),D(R,Q,ee,j,J,pe)|0}catch(S){return S.resultCode||d.SQLITE_ERROR}}}),"*"]]);if(h.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(h.bigIntEnabled&&!!h.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(h.bigIntEnabled&&!!h.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 h.xWrap.FuncPtrAdapter({name:"sqlite3_preupdate_hook",signature:"v(ppippjj)",contextKey:(D)=>D[0],callProxy:(D)=>(R,Q,ee,j,J,pe,S)=>{D(R,Q,ee,h.cstrToJs(j),h.cstrToJs(J),pe,S)}}),"*"]],["sqlite3_preupdate_new","int",["sqlite3*","int","**"]],["sqlite3_preupdate_old","int",["sqlite3*","int","**"]]);if(h.bigIntEnabled&&!!h.exports.sqlite3changegroup_add&&!!h.exports.sqlite3session_create&&!!h.exports.sqlite3_preupdate_hook){let D={signature:"i(ps)",callProxy:(R)=>(Q,ee)=>{try{return R(Q,h.cstrToJs(ee))|0}catch(j){return j.resultCode||d.SQLITE_ERROR}}};b.int64.push(["sqlite3changegroup_add","int",["sqlite3_changegroup*","int","void*"]],["sqlite3changegroup_add_strm","int",["sqlite3_changegroup*",new h.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 h.xWrap.FuncPtrAdapter({name:"xOutput",signature:"i(ppi)",bindScope:"transient"}),"void*"]],["sqlite3changeset_apply","int",["sqlite3*","int","void*",new h.xWrap.FuncPtrAdapter({name:"xFilter",bindScope:"transient",...D}),new h.xWrap.FuncPtrAdapter({name:"xConflict",signature:"i(pip)",bindScope:"transient"}),"void*"]],["sqlite3changeset_apply_strm","int",["sqlite3*",new h.xWrap.FuncPtrAdapter({name:"xInput",signature:"i(ppp)",bindScope:"transient"}),"void*",new h.xWrap.FuncPtrAdapter({name:"xFilter",bindScope:"transient",...D}),new h.xWrap.FuncPtrAdapter({name:"xConflict",signature:"i(pip)",bindScope:"transient"}),"void*"]],["sqlite3changeset_apply_v2","int",["sqlite3*","int","void*",new h.xWrap.FuncPtrAdapter({name:"xFilter",bindScope:"transient",...D}),new h.xWrap.FuncPtrAdapter({name:"xConflict",signature:"i(pip)",bindScope:"transient"}),"void*","**","int*","int"]],["sqlite3changeset_apply_v2_strm","int",["sqlite3*",new h.xWrap.FuncPtrAdapter({name:"xInput",signature:"i(ppp)",bindScope:"transient"}),"void*",new h.xWrap.FuncPtrAdapter({name:"xFilter",bindScope:"transient",...D}),new h.xWrap.FuncPtrAdapter({name:"xConflict",signature:"i(pip)",bindScope:"transient"}),"void*","**","int*","int"]],["sqlite3changeset_apply_v3","int",["sqlite3*","int","void*",new h.xWrap.FuncPtrAdapter({name:"xFilter",signature:"i(pp)",bindScope:"transient"}),new h.xWrap.FuncPtrAdapter({name:"xConflict",signature:"i(pip)",bindScope:"transient"}),"void*","**","int*","int"]],["sqlite3changeset_apply_v3_strm","int",["sqlite3*",new h.xWrap.FuncPtrAdapter({name:"xInput",signature:"i(ppp)",bindScope:"transient"}),"void*",new h.xWrap.FuncPtrAdapter({name:"xFilter",signature:"i(pp)",bindScope:"transient"}),new h.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 h.xWrap.FuncPtrAdapter({name:"xInputA",signature:"i(ppp)",bindScope:"transient"}),"void*",new h.xWrap.FuncPtrAdapter({name:"xInputB",signature:"i(ppp)",bindScope:"transient"}),"void*",new h.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 h.xWrap.FuncPtrAdapter({name:"xInput",signature:"i(ppp)",bindScope:"transient"}),"void*",new h.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 h.xWrap.FuncPtrAdapter({name:"xInput",signature:"i(ppp)",bindScope:"transient"}),"void*"]],["sqlite3changeset_start_v2","int",["**","int","*","int"]],["sqlite3changeset_start_v2_strm","int",["**",new h.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 h.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 h.xWrap.FuncPtrAdapter({name:"xOutput",signature:"i(ppp)",bindScope:"transient"}),"void*"]],["sqlite3session_table_filter",void 0,["sqlite3_session*",new h.xWrap.FuncPtrAdapter({name:"xFilter",...D,contextKey:(R,Q)=>R[0]}),"*"]])}f.StructBinder=globalThis.Jaccwabyt({heap:h.heap8u,alloc:h.alloc,dealloc:h.dealloc,bigIntEnabled:h.bigIntEnabled,pointerIR:h.ptr.ir,memberPrefix:"$"}),delete globalThis.Jaccwabyt;{let D=h.xWrap.argAdapter("string");h.xWrap.argAdapter("string:flexible",(j)=>D(E.flexibleString(j))),h.xWrap.argAdapter("string:static",function(j){if(h.isPtr(j))return j;return j=""+j,this[j]||(this[j]=h.allocCString(j))}.bind(Object.create(null)));let R=h.xWrap.argAdapter("*"),Q=function(){};if(h.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*",(j)=>R(j instanceof(f?.oo1?.Stmt||Q)?j.pointer:j))("sqlite3*",(j)=>R(j instanceof(f?.oo1?.DB||Q)?j.pointer:j))("sqlite3_vfs*",(j)=>{if(typeof j==="string")return d.sqlite3_vfs_find(j)||f.SQLite3Error.toss(d.SQLITE_NOTFOUND,"Unknown sqlite3_vfs name:",j);return R(j instanceof(d.sqlite3_vfs||Q)?j.pointer:j)}),h.exports.sqlite3_declare_vtab)h.xWrap.argAdapter("sqlite3_index_info*",(j)=>R(j instanceof(d.sqlite3_index_info||Q)?j.pointer:j))("sqlite3_module*",(j)=>R(j instanceof(d.sqlite3_module||Q)?j.pointer:j));let ee=h.xWrap.resultAdapter("*");h.xWrap.resultAdapter("sqlite3*",ee)("sqlite3_context*",ee)("sqlite3_stmt*",ee)("sqlite3_value*",ee)("sqlite3_vfs*",ee)("void*",ee);for(let j of b.core)d[j[0]]=h.xWrap.apply(null,j);for(let j of b.wasmInternal)E[j[0]]=h.xWrap.apply(null,j);for(let j of b.int64)d[j[0]]=h.bigIntEnabled?h.xWrap.apply(null,j):()=>l(j[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(j,J,pe){if(!j)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(j,J,pe)||J}}{let D=h.xCall("sqlite3__wasm_enum_json");if(!D)l("Maintenance required: increase sqlite3__wasm_enum_json()'s","static buffer size!");h.ctype=JSON.parse(h.cstrToJs(D));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(h.bigIntEnabled)R.push("serialize","session","vtab");for(let j of R)for(let J of Object.entries(h.ctype[j]))d[J[0]]=J[1];if(!h.functionEntry(d.SQLITE_WASM_DEALLOC))l("Internal error: cannot resolve exported function","entry SQLITE_WASM_DEALLOC (=="+d.SQLITE_WASM_DEALLOC+").");let Q=Object.create(null);for(let j of Object.entries(h.ctype.resultCodes))Q[j[1]]=j[0];d.sqlite3_js_rc_str=(j)=>Q[j];let ee=Object.assign(Object.create(null),{WasmTestStruct:!0,sqlite3_index_info:!h.bigIntEnabled,sqlite3_index_constraint:!h.bigIntEnabled,sqlite3_index_orderby:!h.bigIntEnabled,sqlite3_index_constraint_usage:!h.bigIntEnabled});for(let j of h.ctype.structs)if(!ee[j.name])d[j.name]=f.StructBinder(j);if(d.sqlite3_index_info){for(let j of["sqlite3_index_constraint","sqlite3_index_orderby","sqlite3_index_constraint_usage"])d.sqlite3_index_info[j]=d[j],delete d[j];d.sqlite3_vtab_config=h.xWrap("sqlite3__wasm_vtab_config","int",["sqlite3*","int","int"])}}let I=(D,R,Q)=>E.sqlite3__wasm_db_error(D,d.SQLITE_MISUSE,R+"() requires "+Q+" argument"+(Q===1?"":"s")+"."),V=(D)=>E.sqlite3__wasm_db_error(D,d.SQLITE_FORMAT,"SQLITE_UTF8 is the only supported encoding."),U=(D)=>h.xWrap.argAdapter("sqlite3*")(D),N=(D)=>h.isPtr(D)?h.cstrToJs(D):D,q=function(D,R){D=U(D);let Q=this.dbMap.get(D);if(!R)return this.dbMap.delete(D),Q;else if(!Q&&R>0)this.dbMap.set(D,Q=Object.create(null));return Q}.bind(Object.assign(Object.create(null),{dbMap:new Map}));if(q.addCollation=function(D,R){let Q=q(D,1);if(!Q.collation)Q.collation=new Set;Q.collation.add(N(R).toLowerCase())},q._addUDF=function(D,R,Q,ee){R=N(R).toLowerCase();let j=ee.get(R);if(!j)ee.set(R,j=new Set);j.add(Q<0?-1:Q)},q.addFunction=function(D,R,Q){let ee=q(D,1);if(!ee.udf)ee.udf=new Map;this._addUDF(D,R,Q,ee.udf)},h.exports.sqlite3_create_window_function)q.addWindowFunc=function(D,R,Q){let ee=q(D,1);if(!ee.wudf)ee.wudf=new Map;this._addUDF(D,R,Q,ee.wudf)};q.cleanup=function(D){D=U(D);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[j,J]=ee;if(!h.exports[j])continue;let pe=[D];pe.length=J;try{d[j](...pe)}catch(S){f.config.warn("close-time call of",j+"(",pe,") threw:",S)}}let R=q(D,0);if(!R)return;if(R.collation){for(let ee of R.collation)try{d.sqlite3_create_collation_v2(D,ee,d.SQLITE_UTF8,0,0,0)}catch(j){}delete R.collation}let Q;for(Q=0;Q<2;++Q){let ee=Q?R.wudf:R.udf;if(!ee)continue;let j=Q?d.sqlite3_create_window_function:d.sqlite3_create_function_v2;for(let J of ee){let pe=J[0],S=J[1],C=[D,pe,0,d.SQLITE_UTF8,0,0,0,0,0];if(Q)C.push(0);for(let K of S)try{C[2]=K,j.apply(null,C)}catch(oe){}S.clear()}ee.clear()}delete R.udf,delete R.wudf};{let D=h.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(Q){}return D(R)}}if(d.sqlite3session_create){let D=h.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);D(R)}}{let D=(Q,ee)=>"argv["+ee+"]:"+Q[0]+":"+h.cstrToJs(Q[1]).toLowerCase(),R=h.xWrap("sqlite3_create_collation_v2","int",["sqlite3*","string","int","*",new h.xWrap.FuncPtrAdapter({name:"xCompare",signature:"i(pipip)",contextKey:D}),new h.xWrap.FuncPtrAdapter({name:"xDestroy",signature:"v(p)",contextKey:D})]);d.sqlite3_create_collation_v2=function(Q,ee,j,J,pe,S){if(arguments.length!==6)return I(Q,"sqlite3_create_collation_v2",6);else if((j&15)===0)j|=d.SQLITE_UTF8;else if(d.SQLITE_UTF8!==(j&15))return V(Q);try{let C=R(Q,ee,j,J,pe,S);if(C===0&&pe instanceof Function)q.addCollation(Q,ee);return C}catch(C){return E.sqlite3__wasm_db_error(Q,C)}},d.sqlite3_create_collation=(Q,ee,j,J,pe)=>arguments.length===5?d.sqlite3_create_collation_v2(Q,ee,j,J,pe,0):I(Q,"sqlite3_create_collation",5)}{let D=function(j,J){return j[0]+":"+(j[2]<0?-1:j[2])+":"+J+":"+h.cstrToJs(j[1]).toLowerCase()},R=Object.assign(Object.create(null),{xInverseAndStep:{signature:"v(pip)",contextKey:D,callProxy:(j)=>(J,pe,S)=>{try{j(J,...d.sqlite3_values_to_js(pe,S))}catch(C){d.sqlite3_result_error_js(J,C)}}},xFinalAndValue:{signature:"v(p)",contextKey:D,callProxy:(j)=>(J)=>{try{d.sqlite3_result_js(J,j(J))}catch(pe){d.sqlite3_result_error_js(J,pe)}}},xFunc:{signature:"v(pip)",contextKey:D,callProxy:(j)=>(J,pe,S)=>{try{d.sqlite3_result_js(J,j(J,...d.sqlite3_values_to_js(pe,S)))}catch(C){d.sqlite3_result_error_js(J,C)}}},xDestroy:{signature:"v(p)",contextKey:D,callProxy:(j)=>(J)=>{try{j(J)}catch(pe){console.error("UDF xDestroy method threw:",pe)}}}}),Q=h.xWrap("sqlite3_create_function_v2","int",["sqlite3*","string","int","int","*",new h.xWrap.FuncPtrAdapter({name:"xFunc",...R.xFunc}),new h.xWrap.FuncPtrAdapter({name:"xStep",...R.xInverseAndStep}),new h.xWrap.FuncPtrAdapter({name:"xFinal",...R.xFinalAndValue}),new h.xWrap.FuncPtrAdapter({name:"xDestroy",...R.xDestroy})]),ee=h.exports.sqlite3_create_window_function?h.xWrap("sqlite3_create_window_function","int",["sqlite3*","string","int","int","*",new h.xWrap.FuncPtrAdapter({name:"xStep",...R.xInverseAndStep}),new h.xWrap.FuncPtrAdapter({name:"xFinal",...R.xFinalAndValue}),new h.xWrap.FuncPtrAdapter({name:"xValue",...R.xFinalAndValue}),new h.xWrap.FuncPtrAdapter({name:"xInverse",...R.xInverseAndStep}),new h.xWrap.FuncPtrAdapter({name:"xDestroy",...R.xDestroy})]):void 0;if(d.sqlite3_create_function_v2=function j(J,pe,S,C,K,oe,W,ge,we){if(j.length!==arguments.length)return I(J,"sqlite3_create_function_v2",j.length);else if((C&15)===0)C|=d.SQLITE_UTF8;else if(d.SQLITE_UTF8!==(C&15))return V(J);try{let me=Q(J,pe,S,C,K,oe,W,ge,we);if(me===0&&(oe instanceof Function||W instanceof Function||ge 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 j(J,pe,S,C,K,oe,W,ge){return j.length===arguments.length?d.sqlite3_create_function_v2(J,pe,S,C,K,oe,W,ge,0):I(J,"sqlite3_create_function",j.length)},ee)d.sqlite3_create_window_function=function j(J,pe,S,C,K,oe,W,ge,we,me){if(j.length!==arguments.length)return I(J,"sqlite3_create_window_function",j.length);else if((C&15)===0)C|=d.SQLITE_UTF8;else if(d.SQLITE_UTF8!==(C&15))return V(J);try{let ve=ee(J,pe,S,C,K,oe,W,ge,we,me);if(ve===0&&(oe instanceof Function||W instanceof Function||ge 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 D=(Q,ee)=>{if(typeof Q==="string")ee=-1;else if(E.isSQLableTypedArray(Q))ee=Q.byteLength,Q=h.typedArrayToString(Q instanceof ArrayBuffer?new Uint8Array(Q):Q);else if(Array.isArray(Q))Q=Q.join(""),ee=-1;return[Q,ee]},R={basic:h.xWrap("sqlite3_prepare_v3","int",["sqlite3*","string","int","int","**","**"]),full:h.xWrap("sqlite3_prepare_v3","int",["sqlite3*","*","int","int","**","**"])};d.sqlite3_prepare_v3=function Q(ee,j,J,pe,S,C){if(Q.length!==arguments.length)return I(ee,"sqlite3_prepare_v3",Q.length);let[K,oe]=D(j,Number(J));switch(typeof K){case"string":return R.basic(ee,K,oe,pe,S,null);case typeof h.ptr.null:return R.full(ee,h.ptr.coerce(K),oe,pe,S,C);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 Q(ee,j,J,pe,S){return Q.length===arguments.length?d.sqlite3_prepare_v3(ee,j,J,0,pe,S):I(ee,"sqlite3_prepare_v2",Q.length)}}{let D=h.xWrap("sqlite3_bind_text","int",["sqlite3_stmt*","int","string","int","*"]),R=h.xWrap("sqlite3_bind_blob","int",["sqlite3_stmt*","int","*","int","*"]);d.sqlite3_bind_text=function Q(ee,j,J,pe,S){if(Q.length!==arguments.length)return I(d.sqlite3_db_handle(ee),"sqlite3_bind_text",Q.length);else if(h.isPtr(J)||J===null)return D(ee,j,J,pe,S);else if(J instanceof ArrayBuffer)J=new Uint8Array(J);else if(Array.isArray(pMem))J=pMem.join("");let C,K;try{if(E.isSQLableTypedArray(J))C=h.allocFromTypedArray(J),K=J.byteLength;else if(typeof J==="string")[C,K]=h.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 D(ee,j,C,K,d.SQLITE_WASM_DEALLOC)}catch(oe){return h.dealloc(C),E.sqlite3__wasm_db_error(d.sqlite3_db_handle(ee),oe)}},d.sqlite3_bind_blob=function Q(ee,j,J,pe,S){if(Q.length!==arguments.length)return I(d.sqlite3_db_handle(ee),"sqlite3_bind_blob",Q.length);else if(h.isPtr(J)||J===null)return R(ee,j,J,pe,S);else if(J instanceof ArrayBuffer)J=new Uint8Array(J);else if(Array.isArray(J))J=J.join("");let C,K;try{if(E.isBindableTypedArray(J))C=h.allocFromTypedArray(J),K=pe>=0?pe:J.byteLength;else if(typeof J==="string")[C,K]=h.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,j,C,K,d.SQLITE_WASM_DEALLOC)}catch(oe){return h.dealloc(C),E.sqlite3__wasm_db_error(d.sqlite3_db_handle(ee),oe)}}}if(!d.sqlite3_column_text){let D=h.xWrap.argAdapter("sqlite3_stmt*"),R=h.xWrap.argAdapter("int"),Q=h.xWrap.argAdapter("sqlite3_value*"),ee=(j,J)=>h.typedArrayToString(h.heap8u(),Number(j),Number(j)+J);d.sqlite3_column_text=function(j,J){let pe=D(j),S=R(J),C=h.exports.sqlite3_column_text(pe,S);return C?ee(C,h.exports.sqlite3_column_bytes(pe,S)):null},d.sqlite3_value_text=function(j){let J=Q(j),pe=h.exports.sqlite3_value_text(J);return pe?ee(pe,h.exports.sqlite3_value_bytes(J)):null}}d.sqlite3_config=function(D,...R){if(arguments.length<2)return d.SQLITE_MISUSE;switch(D){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 h.exports.sqlite3__wasm_config_i(D,R[0]);case d.SQLITE_CONFIG_LOOKASIDE:return h.exports.sqlite3__wasm_config_ii(D,R[0],R[1]);case d.SQLITE_CONFIG_MEMDB_MAXSIZE:return h.exports.sqlite3__wasm_config_j(D,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 D=new Set;d.sqlite3_auto_extension=function(R){if(R instanceof Function)R=h.installFunction("i(ppp)",R);else if(arguments.length!==1||!h.isPtr(R))return d.SQLITE_MISUSE;let Q=h.exports.sqlite3_auto_extension(R);if(R!==arguments[0])if(Q===0)D.add(R);else h.uninstallFunction(R);return Q},d.sqlite3_cancel_auto_extension=function(R){if(!R||arguments.length!==1||!h.isPtr(R))return 0;return h.exports.sqlite3_cancel_auto_extension(R)},d.sqlite3_reset_auto_extension=function(){h.exports.sqlite3_reset_auto_extension();for(let R of D)h.uninstallFunction(R);D.clear()}}h.xWrap.FuncPtrAdapter.warnOnUse=!0;let H=f.StructBinder,G=function D(R,Q,ee,j=D.installMethodArgcCheck){if(!(R instanceof H.StructType))l("Usage error: target object is-not-a StructType.");else if(!(ee instanceof Function)&&!h.isPtr(ee))l("Usage error: expecting a Function or WASM pointer to one.");if(arguments.length===1)return(C,K)=>D(R,C,K,j);if(!D.argcProxy)D.argcProxy=function(C,K,oe,W){return function(...ge){if(oe.length!==arguments.length)l("Argument mismatch for",C.structInfo.name+"::"+K+": Native signature is:",W);return oe.apply(this,ge)}},D.removeFuncList=function(){if(this.ondispose.__removeFuncList)this.ondispose.__removeFuncList.forEach((C,K)=>{if(h.isPtr(C))try{h.uninstallFunction(C)}catch(oe){}}),delete this.ondispose.__removeFuncList};let J=R.memberSignature(Q);if(J.length<2)l("Member",Q,"does not have a function pointer signature:",J);let pe=R.memberKey(Q),S=j&&!h.isPtr(ee)?D.argcProxy(R,pe,ee,J):ee;if(h.isPtr(S)){if(S&&!h.functionEntry(S))l("Pointer",S,"is not a WASM function table entry.");R[pe]=S}else{let C=h.installFunction(S,J);if(R[pe]=C,!R.ondispose||!R.ondispose.__removeFuncList)R.addOnDispose("ondispose.__removeFuncList handler",D.removeFuncList),R.ondispose.__removeFuncList=[];R.ondispose.__removeFuncList.push(pe,C)}return(C,K)=>D(R,C,K,j)};G.installMethodArgcCheck=!1;let ue=function(D,R,Q=G.installMethodArgcCheck){let ee=new Map;for(let j of Object.keys(R)){let J=R[j],pe=ee.get(J);if(pe){let S=D.memberKey(j);D[S]=D[D.memberKey(pe)]}else G(D,j,J,Q),ee.set(J,j)}return D};H.StructType.prototype.installMethod=function(R,Q,ee=G.installMethodArgcCheck){return arguments.length<3&&R&&typeof R==="object"?ue(this,...arguments):G(this,...arguments)},H.StructType.prototype.installMethods=function(D,R=G.installMethodArgcCheck){return ue(this,D,R)}}),globalThis.sqlite3ApiBootstrap.initializers.push(function(f){let l=(...M)=>{throw new f.SQLite3Error(...M)},{capi:d,wasm:h,util:E}=f,b=function(M){return(...g)=>M("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,U=new WeakMap,N=(M,g,w)=>{let T=Object.getOwnPropertyDescriptor(M,g);return T?T.value:w},q=function(M,g){if(g){if(M instanceof D)M=M.pointer;l(g,"sqlite3 result code",g+":",M?d.sqlite3_errmsg(M):d.sqlite3_errstr(g))}return arguments[0]},H=h.installFunction("i(ippp)",function(M,g,w,T){if(d.SQLITE_TRACE_STMT===M)console.log("SQL TRACE #"+ ++this.counter,"via sqlite3@"+g+"["+d.sqlite3_db_filename(g,null)+"]",h.cstrToJs(T))}.bind({counter:0})),G=Object.create(null),ue=function M(...g){let w=M.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:P,vfs:te,flags:se}=w;if(typeof P!=="string"&&!h.isPtr(P)||typeof se!=="string"||te&&typeof te!=="string"&&!h.isPtr(te))f.config.error("Invalid DB ctor args",w,arguments),l("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=h.pstack.pointer;try{let Y=h.pstack.allocPtr(),ne=d.sqlite3_open_v2(P,Y,A,te||h.ptr.null);if(T=h.peekPtr(Y),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(Y){if(T)d.sqlite3_close_v2(T);throw Y}finally{h.pstack.restore(L)}this.filename=h.isPtr(P)?h.cstrToJs(P):P}if(I.set(this,T),U.set(this,Object.create(null)),!w["sqlite3*"])try{let P=G[d.sqlite3_js_db_vfs(T)||l("Internal error: cannot get VFS for new db handle.")];if(P)if(P instanceof Function)P(this,f);else q(T,d.sqlite3_exec(T,P,0,0,0))}catch(P){throw this.close(),P}};ue.setVfsPostOpenCallback=function(M,g){if(!(g instanceof Function))l("dbCtorHelper.setVfsPostOpenCallback() should not be used with a non-function argument.",arguments);G[M]=g},ue.normalizeArgs=function(M=":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=M,T.flags=g,T.vfs=w;return T};let D=function(...M){ue.apply(this,M)};D.dbCtorHelper=ue;let R={null:1,number:2,string:3,boolean:4,blob:5};if(h.bigIntEnabled)R.bigint=R.number;let Q=function(){if(R!==arguments[2])l(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(M){if(!M.pointer)l("DB has been closed.");return M},j=function(M,g){if(g!==(g|0)||g<0||g>=M.columnCount)l("Column index",g,"is out of range.");return M},J=function(M,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:l("Invalid argument count for exec().")}if(w.sql=E.flexibleString(w.sql),typeof w.sql!=="string")l("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=()=>M;break;default:l("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=(P,te)=>{if(!te.columnNames)te.columnNames=P.getColumnNames([]);let se=P.get([]),A=Object.create(null);for(let L in te.columnNames)A[te.columnNames[L]]=se[L];return A};break;case"array":w.cbArg=(P)=>P.get([]);break;case"stmt":if(Array.isArray(T.resultRows))l("exec(): invalid rowMode for a resultRows array: must","be one of 'array', 'object',","a result column number, or column name reference.");w.cbArg=(P)=>P;break;default:if(E.isInt32(T.rowMode)){w.cbArg=(P)=>P.get(T.rowMode);break}else if(typeof T.rowMode==="string"&&T.rowMode.length>1&&T.rowMode[0]==="$"){let P=T.rowMode.substr(1);w.cbArg=(te)=>{let se=te.get(Object.create(null))[P];return se===void 0?l(d.SQLITE_NOTFOUND,"exec(): unknown result column:",P):se};break}l("Invalid rowMode:",T.rowMode)}return w},pe=(M,g,w,...T)=>{let P=M.prepare(g);try{let te=P.bind(w).step()?P.get(...T):void 0;return P.reset(),te}finally{P.finalize()}},S=(M,g,w,T)=>M.exec({sql:g,bind:w,rowMode:T,returnValue:"resultRows"});D.checkRc=(M,g)=>q(M,g),D.prototype={isOpen:function(){return!!this.pointer},affirmOpen:function(){return ee(this)},close:function(){let M=this.pointer;if(M){if(this.onclose&&this.onclose.before instanceof Function)try{this.onclose.before(this)}catch(g){}if(Object.keys(U.get(this)).forEach((g,w)=>{if(w&&w.pointer)try{w.finalize()}catch(T){}}),I.delete(this),U.delete(this),!V.delete(this))d.sqlite3_close_v2(M);if(this.onclose&&this.onclose.after instanceof Function)try{this.onclose.after(this)}catch(g){}delete this.filename}},changes:function(M=!1,g=!1){let w=ee(this).pointer;if(M)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(M="main"){return d.sqlite3_db_filename(ee(this).pointer,M)},dbName:function(M=0){return d.sqlite3_db_name(ee(this).pointer,M)},dbVfsName:function(M=0){let g,w=d.sqlite3_js_db_vfs(ee(this).pointer,M);if(w){let T=new d.sqlite3_vfs(w);try{g=h.cstrToJs(T.$zName)}finally{T.dispose()}}return g},prepare:function(M){ee(this);let g=h.pstack.pointer,w,T;try{w=h.pstack.alloc(8),D.checkRc(this,d.sqlite3_prepare_v2(this.pointer,M,-1,w,null)),T=h.peekPtr(w)}finally{h.pstack.restore(g)}if(!T)l("Cannot prepare empty SQL.");let P=new Q(this,T,R);return U.get(this)[T]=P,P},exec:function(){ee(this);let M=J(this,arguments);if(!M.sql)return l("exec() requires an SQL string.");let g=M.opt,w=g.callback,T=Array.isArray(g.resultRows)?g.resultRows:void 0,P,te=g.bind,se=!!(M.cbArg||g.columnNames||T),A=h.scopedAllocPush(),L=Array.isArray(g.saveSql)?g.saveSql:void 0;try{let Y=E.isSQLableTypedArray(M.sql),ne=Y?M.sql.byteLength:h.jstrlen(M.sql),ye=h.scopedAlloc(2*h.ptr.size+(ne+1)),ke=h.ptr.add(ye,h.ptr.size),Pe=h.ptr.add(ke,h.ptr.size),$e=h.ptr.add(Pe,ne);if(Y)h.heap8().set(M.sql,Pe);else h.jstrcpy(M.sql,h.heap8(),Pe,ne,!1);h.poke8(h.ptr.add(Pe,ne),0);while(Pe&&h.peek8(Pe)){h.pokePtr([ye,ke],0),D.checkRc(this,d.sqlite3_prepare_v3(this.pointer,Pe,ne,0,ye,ke));let Ve=h.peekPtr(ye);if(Pe=h.peekPtr(ke),ne=Number(h.ptr.add($e,-Pe)),!Ve)continue;if(L)L.push(d.sqlite3_sql(Ve).trim());if(P=new Q(this,Ve,R),te&&P.parameterCount)P.bind(te),te=null;if(se&&P.columnCount){let dt=Array.isArray(g.columnNames)?0:1;if(se=!1,M.cbArg||T){let jt=Object.create(null);for(;P.step();ge.delete(P)){if(dt++===0)P.getColumnNames(jt.columnNames=g.columnNames||[]);ge.add(P);let Nr=M.cbArg(P,jt);if(T)T.push(Nr);if(w&&w.call(g,Nr,P)===!1)break}ge.delete(P)}if(dt===0)P.getColumnNames(g.columnNames)}else P.step();P.reset().finalize(),P=null}}finally{if(P)ge.delete(P),P.finalize();h.scopedAllocPop(A)}return M.returnVal()},createFunction:function(g,w,T){let P=(jt)=>jt instanceof Function;switch(arguments.length){case 1:T=g,g=T.name,w=T.xFunc||0;break;case 2:if(!P(w))T=w,w=T.xFunc||0;break;case 3:break;default:break}if(!T)T={};if(typeof g!=="string")l("Invalid arguments: missing function name.");let te=T.xStep||0,se=T.xFinal||0,A=T.xValue||0,L=T.xInverse||0,Y=void 0;if(P(w)){if(Y=!1,P(te)||P(se))l("Ambiguous arguments: scalar or aggregate?");te=se=null}else if(P(te)){if(!P(se))l("Missing xFinal() callback for aggregate or window UDF.");w=null}else if(P(se))l("Missing xStep() callback for aggregate or window UDF.");else l("Missing function-type properties.");if(Y===!1){if(P(A)||P(L))l("xValue and xInverse are not permitted for non-window UDFs.")}else if(P(A)){if(!P(L))l("xInverse must be provided if xValue is.");Y=!0}else if(P(L))l("xValue must be provided if xInverse is.");let ne=T.pApp;if(ne!==void 0&&ne!==null&&!h.isPtr(ne))l("Invalid value for pApp property. Must be a legal WASM pointer value.");let ye=T.xDestroy||0;if(ye&&!P(ye))l("xDestroy property must be a function.");let ke=0;if(N(T,"deterministic"))ke|=d.SQLITE_DETERMINISTIC;if(N(T,"directOnly"))ke|=d.SQLITE_DIRECTONLY;if(N(T,"innocuous"))ke|=d.SQLITE_INNOCUOUS;g=g.toLowerCase();let Pe=w||te,$e=N(T,"arity"),Ve=typeof $e==="number"?$e:Pe.length?Pe.length-1:0,dt;if(Y)dt=d.sqlite3_create_window_function(this.pointer,g,Ve,d.SQLITE_UTF8|ke,ne||0,te,se,A,L,ye);else dt=d.sqlite3_create_function_v2(this.pointer,g,Ve,d.SQLITE_UTF8|ke,ne||0,w,te,se,ye);return D.checkRc(this,dt),this},selectValue:function(M,g,w){return pe(this,M,g,0,w)},selectValues:function(M,g,w){let T=this.prepare(M),P=[];try{T.bind(g);while(T.step())P.push(T.get(0,w));T.reset()}finally{T.finalize()}return P},selectArray:function(M,g){return pe(this,M,g,[])},selectObject:function(M,g){return pe(this,M,g,{})},selectArrays:function(M,g){return S(this,M,g,"array")},selectObjects:function(M,g){return S(this,M,g,"object")},openStatementCount:function(){return this.pointer?Object.keys(U.get(this)).length:0},transaction:function(M){let g="BEGIN";if(arguments.length>1){if(/[^a-zA-Z]/.test(arguments[0]))l(d.SQLITE_MISUSE,"Invalid argument for BEGIN qualifier.");g+=" "+arguments[0],M=arguments[1]}ee(this).exec(g);try{let w=M(this);return this.exec("COMMIT"),w}catch(w){throw this.exec("ROLLBACK"),w}},savepoint:function(M){ee(this).exec("SAVEPOINT oo1");try{let g=M(this);return this.exec("RELEASE oo1"),g}catch(g){throw this.exec("ROLLBACK to SAVEPOINT oo1; RELEASE SAVEPOINT oo1"),g}},checkRc:function(M){return q(this,M)}},D.wrapHandle=function(M,g=!1){if(!M||!h.isPtr(M))throw new f.SQLite3Error(d.SQLITE_MISUSE,"Argument must be a WASM sqlite3 pointer");return new D({"sqlite3*":M,"sqlite3*:takeOwnership":!!g})};let C=function(M){if(!M.pointer)l("Stmt has been closed.");return M},K=function(M){let g=R[M===null||M===void 0?"null":typeof M];switch(g){case R.boolean:case R.null:case R.number:case R.string:return g;case R.bigint:return h.bigIntEnabled?g:void 0;default:return E.isBindableTypedArray(M)?R.blob:void 0}},oe=function(M){return K(M)||l("Unsupported bind() argument type:",typeof M)},W=function(M,g){let w=typeof g==="number"?g:d.sqlite3_bind_parameter_index(M.pointer,g);if(w===0||!E.isInt32(w))l("Invalid bind() parameter name: "+g);else if(w<1||w>M.parameterCount)l("Bind index",g,"is out of range.");return w},ge=new Set,we=new Set,me=function(M,g){if(ge.has(M))l("Operation is illegal when statement is locked:",g);return M},ve=function M(g,w,T,P){if(me(C(g),"bind()"),!M._)M._tooBigInt=(se)=>l("BigInt value is too big to store without precision loss:",se),M._={string:function(se,A,L,Y){let[ne,ye]=h.allocCString(L,!0);return(Y?d.sqlite3_bind_blob:d.sqlite3_bind_text)(se.pointer,A,ne,ye,d.SQLITE_WASM_DEALLOC)}};oe(P),w=W(g,w);let te=0;switch(P===null||P===void 0?R.null:T){case R.null:te=d.sqlite3_bind_null(g.pointer,w);break;case R.string:te=M._.string(g,w,P,!1);break;case R.number:{let se;if(E.isInt32(P))se=d.sqlite3_bind_int;else if(typeof P==="bigint")if(!E.bigIntFits64(P))M._tooBigInt(P);else if(h.bigIntEnabled)se=d.sqlite3_bind_int64;else if(E.bigIntFitsDouble(P))P=Number(P),se=d.sqlite3_bind_double;else M._tooBigInt(P);else if(P=Number(P),h.bigIntEnabled&&Number.isInteger(P))se=d.sqlite3_bind_int64;else se=d.sqlite3_bind_double;te=se(g.pointer,w,P);break}case R.boolean:te=d.sqlite3_bind_int(g.pointer,w,P?1:0);break;case R.blob:{if(typeof P==="string"){te=M._.string(g,w,P,!0);break}else if(P instanceof ArrayBuffer)P=new Uint8Array(P);else if(!E.isBindableTypedArray(P))l("Binding a value as a blob requires","that it be a string, Uint8Array, Int8Array, or ArrayBuffer.");let se=h.alloc(P.byteLength||1);h.heap8().set(P.byteLength?P:[0],Number(se)),te=d.sqlite3_bind_blob(g.pointer,w,se,P.byteLength,d.SQLITE_WASM_DEALLOC);break}default:f.config.warn("Unsupported bind() argument type:",P),l("Unsupported bind() argument type: "+typeof P)}if(te)D.checkRc(g.db.pointer,te);return g};Q.prototype={finalize:function(){let M=this.pointer;if(M){me(this,"finalize()");let g=V.delete(this)?0:d.sqlite3_finalize(M);return delete U.get(this.db)[M],I.delete(this),ge.delete(this),we.delete(this),delete this.parameterCount,delete this.db,g}},clearBindings:function(){return me(C(this),"clearBindings()"),d.sqlite3_clear_bindings(this.pointer),we.delete(this),this},reset:function(M){if(me(this,"reset()"),M)this.clearBindings();let g=d.sqlite3_reset(C(this).pointer);return we.delete(this),q(this.db,g),this},bind:function(){C(this);let M,g;switch(arguments.length){case 1:M=1,g=arguments[0];break;case 2:M=arguments[0],g=arguments[1];break;default:l("Invalid bind() arguments.")}if(g===void 0)return this;else if(!this.parameterCount)l("This statement has no bindable parameters.");if(we.delete(this),g===null)return ve(this,M,R.null,g);else if(Array.isArray(g)){if(arguments.length!==1)l("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)l("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,M,oe(g),g);l("Should not reach this point.")},bindAsBlob:function(M,g){if(C(this),arguments.length===1)g=M,M=1;let w=oe(g);if(R.string!==w&&R.blob!==w&&R.null!==w)l("Invalid value type for bindAsBlob()");return ve(this,M,R.blob,g)},step:function(){me(this,"step()");let M=d.sqlite3_step(C(this).pointer);switch(M){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=",M,d.sqlite3_js_rc_str(M),"SQL =",d.sqlite3_sql(this.pointer)),D.checkRc(this.db.pointer,M)}},stepReset:function(){return this.step(),this.reset()},stepFinalize:function(){try{let M=this.step();return this.reset(),M}finally{try{this.finalize()}catch(M){}}},get:function(M,g){if(!we.has(C(this)))l("Stmt.step() has not (recently) returned true.");if(Array.isArray(M)){let w=0,T=this.columnCount;while(w<T)M[w]=this.get(w++);return M}else if(M&&typeof M==="object"){let w=0,T=this.columnCount;while(w<T)M[d.sqlite3_column_name(this.pointer,w)]=this.get(w++);return M}switch(j(this,M),g===void 0?d.sqlite3_column_type(this.pointer,M):g){case d.SQLITE_NULL:return null;case d.SQLITE_INTEGER:if(h.bigIntEnabled){let w=d.sqlite3_column_int64(this.pointer,M);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,M);if(w>Number.MAX_SAFE_INTEGER||w<Number.MIN_SAFE_INTEGER)l("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,M);case d.SQLITE_TEXT:return d.sqlite3_column_text(this.pointer,M);case d.SQLITE_BLOB:{let w=d.sqlite3_column_bytes(this.pointer,M),T=d.sqlite3_column_blob(this.pointer,M),P=new Uint8Array(w);if(w){if(P.set(h.heap8u().slice(Number(T),Number(T)+w),0),this.db._blobXfer instanceof Array)this.db._blobXfer.push(P.buffer)}return P}default:l("Don't know how to translate","type of result column #"+M+".")}l("Not reached.")},getInt:function(M){return this.get(M,d.SQLITE_INTEGER)},getFloat:function(M){return this.get(M,d.SQLITE_FLOAT)},getString:function(M){return this.get(M,d.SQLITE_TEXT)},getBlob:function(M){return this.get(M,d.SQLITE_BLOB)},getJSON:function(M){let g=this.get(M,d.SQLITE_STRING);return g===null?g:JSON.parse(g)},getColumnName:function(M){return d.sqlite3_column_name(j(C(this),M).pointer,M)},getColumnNames:function(M=[]){j(C(this),0);let g=this.columnCount;for(let w=0;w<g;++w)M.push(d.sqlite3_column_name(this.pointer,w));return M},getParamIndex:function(M){return C(this).parameterCount?d.sqlite3_bind_parameter_index(this.pointer,M):void 0},getParamName:function(M){return C(this).parameterCount?d.sqlite3_bind_parameter_name(this.pointer,M):void 0},isBusy:function(){return d.sqlite3_stmt_busy(C(this))!==0},isReadOnly:function(){return d.sqlite3_stmt_readonly(C(this))!==0}};{let M={enumerable:!0,get:function(){return I.get(this)},set:()=>l("The pointer property is read-only.")};Object.defineProperty(Q.prototype,"pointer",M),Object.defineProperty(D.prototype,"pointer",M)}Object.defineProperty(Q.prototype,"columnCount",{enumerable:!1,get:function(){return d.sqlite3_column_count(this.pointer)},set:()=>l("The columnCount property is read-only.")}),Object.defineProperty(Q.prototype,"parameterCount",{enumerable:!1,get:function(){return d.sqlite3_bind_parameter_count(this.pointer)},set:()=>l("The parameterCount property is read-only.")}),Q.wrapHandle=function(M,g,w=!1){if(!(M instanceof D)||!M.pointer)throw new f.SQLite3Error(f.SQLITE_MISUSE,"First argument must be an opened sqlite3.oo1.DB instance");if(!g||!h.isPtr(g))throw new f.SQLite3Error(f.SQLITE_MISUSE,"Second argument must be a WASM sqlite3_stmt pointer");return new Q(M,g,R,!!w)},f.oo1={DB:D,Stmt:Q}}),globalThis.sqlite3ApiBootstrap.initializers.push(function(f){let l=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 h=this.sqlite3||d("Missing this.sqlite3 object."),E=h.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 ue=H.filename,D=l.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&&ue&&D)l.sqlite3__wasm_vfs_unlink(D,ue)}},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.")},U=function(H,G=!0){let ue=I.getDb(H.dbId,!1)||I.dbList[0];return G?V(ue):ue},N=function(){return I.dbList[0]&&b(I.dbList[0])},q={open:function(H){let G=Object.create(null),ue=H.args||Object.create(null);if(ue.simulateError)d("Throwing because of simulateError flag.");let D=Object.create(null);G.vfs=ue.vfs,G.filename=ue.filename||"";let R=I.open(G);return D.filename=R.filename,D.persistent=!!h.capi.sqlite3_js_db_uses_vfs(R.pointer,"opfs"),D.dbId=b(R),D.vfs=R.dbVfsName(),D},close:function(H){let G=U(H,!1),ue={filename:G&&G.filename};if(G){let D=H.args&&typeof H.args==="object"?!!H.args.unlink:!1;I.close(G,D)}return ue},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 ue=U(H);if(G.callback||Array.isArray(G.resultRows))ue._blobXfer=I.xfer;let D=G.callback,R=0,Q=!!G.columnNames;if(typeof D==="string"){if(!Q)G.columnNames=[];G.callback=function(ee,j){I.post({type:D,columnNames:G.columnNames,rowNumber:++R,row:ee},I.xfer)}}try{let ee=G.countChanges?ue.changes(!0,G.countChanges===64):void 0;if(ue.exec(G),ee!==void 0)G.changeCount=ue.changes(!0,G.countChanges===64)-ee;let j=G.lastInsertRowId?h.capi.sqlite3_last_insert_rowid(ue):void 0;if(j!==void 0)G.lastInsertRowId=j;if(G.callback instanceof Function)G.callback=D,I.post({type:D,columnNames:G.columnNames,rowNumber:null,row:void 0})}finally{if(delete ue._blobXfer,G.callback)G.callback=D}return G},"config-get":function(){let H=Object.create(null),G=h.config;return["bigIntEnabled"].forEach(function(ue){if(Object.getOwnPropertyDescriptor(G,ue))H[ue]=G[ue]}),H.version=h.version,H.vfsList=h.capi.sqlite3_js_vfs_list(),H},export:function(H){let G=U(H),ue={byteArray:h.capi.sqlite3_js_db_export(G.pointer),filename:G.filename,mimetype:"application/x-sqlite3"};return I.xfer.push(ue.byteArray.buffer),ue},toss:function(H){d("Testing worker exception")}};globalThis.onmessage=async function(H){H=H.data;let G,ue=H.dbId,D=H.type,R=performance.now();try{if(q.hasOwnProperty(D)&&q[D]instanceof Function)G=await q[D](H);else d("Unknown db worker message type:",H.type)}catch(Q){if(D="error",G={operation:H.type,message:Q.message,errorClass:Q.name,input:H},Q.stack)G.stack=typeof Q.stack==="string"?Q.stack.split(/\n\s*/):Q.stack}if(!ue)ue=G.dbId||N();I.post({type:D,dbId:ue,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:l,capi:d}=f,h=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))h("Expecting a sqlite3_vfs-type argument.");let I=d.sqlite3_vfs_register(this,b?1:0);if(I)h("sqlite3_vfs_register(",this,") failed with rc",I);if(this.pointer!==d.sqlite3_vfs_find(this.$zName))h("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 U of V){let N=b[U];if(N){if(++I,N.struct.installMethods(N.methods,!!N.applyArgcCheck),U==="vfs"){if(!N.struct.$zName&&typeof N.name==="string")N.struct.addOnDispose(N.struct.$zName=l.allocCString(N.name));N.struct.registerVfs(!!N.asDefault)}}}if(!I)h("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:l,capi:d}=f,h=f.util.toss3,E=Object.create(null);f.vtab=E;let b=d.sqlite3_index_info;b.prototype.nthConstraint=function(U,N=!1){if(U<0||U>=this.$nConstraint)return!1;let q=l.ptr.add(this.$aConstraint,b.sqlite3_index_constraint.structInfo.sizeof*U);return N?q:new b.sqlite3_index_constraint(q)},b.prototype.nthConstraintUsage=function(U,N=!1){if(U<0||U>=this.$nConstraint)return!1;let q=l.ptr.add(this.$aConstraintUsage,b.sqlite3_index_constraint_usage.structInfo.sizeof*U);return N?q:new b.sqlite3_index_constraint_usage(q)},b.prototype.nthOrderBy=function(U,N=!1){if(U<0||U>=this.$nOrderBy)return!1;let q=l.ptr.add(this.$aOrderBy,b.sqlite3_index_orderby.structInfo.sizeof*U);return N?q:new b.sqlite3_index_orderby(q)};let I=function(U,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(!l.isPtr(q))f.SQLite3Error.toss("Invalid argument to",U+"()");let G=this.get(q);if(H)this.delete(q);return G}.bind(new Map)},V=function(U,N){let q=I(U,N);return Object.assign(Object.create(null),{StructType:N,create:(H)=>{let G=q();return l.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=(U)=>new d.sqlite3_index_info(U),E.xError=function U(N,q,H){if(U.errorReporter instanceof Function)try{U.errorReporter("sqlite3_module::"+N+"(): "+q.message)}catch(ue){}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=(U,N)=>l.poke(U,N,"i64"),E.setupModule=function(U){let N=!1,q=this instanceof d.sqlite3_module?this:U.struct||(N=new d.sqlite3_module);try{let H=U.methods||h("Missing 'methods' object.");for(let G of Object.entries({xConnect:"xCreate",xDisconnect:"xDestroy"})){let ue=G[0],D=G[1];if(H[ue]===!0)H[ue]=H[D];else if(H[D]===!0)H[D]=H[ue]}if(U.catchExceptions){let G=function(R,Q){if(["xConnect","xCreate"].indexOf(R)>=0)return function(ee,j,J,pe,S,C){try{return Q(...arguments)||0}catch(K){if(!(K instanceof f.WasmAllocError))l.dealloc(l.peekPtr(C)),l.pokePtr(C,l.allocCString(K.message));return E.xError(R,K)}};else return function(...ee){try{return Q(...ee)||0}catch(j){return E.xError(R,j)}}},ue=["xCreate","xConnect","xBestIndex","xDisconnect","xDestroy","xOpen","xClose","xFilter","xNext","xEof","xColumn","xRowid","xUpdate","xBegin","xSync","xCommit","xRollback","xFindFunction","xRename","xSavepoint","xRelease","xRollbackTo","xShadowName"],D=Object.create(null);for(let R of ue){let Q=H[R];if(!(Q instanceof Function))continue;else if(R==="xConnect"&&H.xCreate===Q)D[R]=H.xCreate;else if(R==="xCreate"&&H.xConnect===Q)D[R]=H.xConnect;else D[R]=G(R,Q)}q.installMethods(D,!1)}else q.installMethods(H,!!U.applyArgcCheck);if(q.$iVersion===0){let G;if(typeof U.iVersion==="number")G=U.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(U){return E.setupModule.call(this,U)}}),globalThis.sqlite3ApiBootstrap.initializers.push(function(f){if(f.config.disable?.vfs?.kvvfs)return;let l=f.capi,{sqlite3_kvvfs_methods:d,KVVfsFile:h}=l,E=f.capi.sqlite3_vfs_find("kvvfs");if(delete l.sqlite3_kvvfs_methods,delete l.KVVfsFile,!E)return;let{util:b,wasm:I}=f,V=b.toss3,U=new d(I.exports.sqlite3__wasm_kvvfs_methods());b.assert(32<=U.$nKeySize,"unexpected kvvfsMethods.$nKeySize: "+U.$nKeySize);let N=Object.assign(Object.create(null),{rxJournalSuffix:/-journal$/,zKeyJrnl:I.allocCString("jrnl"),zKeySz:I.allocCString("sz"),keySize:U.$nKeySize,buffer:Object.assign(Object.create(null),{n:U.$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),ue=(...B)=>f.config.error?.("kvvfs:",...B);class D{#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",Q=(B)=>R(B)?"kvvfs-"+B+"-":"",ee=function(B,re=!1){if(R(B))return;let ae=new Blob([B]).size;if(!ae)V(l.SQLITE_MISUSE,"Empty name is not permitted.");let de=N.keySize-1;if(N.rxJournalSuffix.test(B)){if(!re)V(l.SQLITE_MISUSE,"Storage names may not have a '-journal' suffix.")}else if(["-wal","-shm"].filter((Ae)=>B.endsWith(Ae)).length)V(l.SQLITE_MISUSE,"Storage names may not have a -wal or -shm suffix.");else de-=8;if(ae>de)V(l.SQLITE_RANGE,"Storage name is too long. Limit =",de);let Se;for(Se=0;Se<ae;++Se){let Ae=B.codePointAt(Se);if(Ae<32)V(l.SQLITE_RANGE,"Illegal character ("+Ae+"d) in storage name:",B)}},j=(B,re=void 0)=>Object.assign(Object.create(null),{jzClass:B,refc:1,deleteAtRefc0:!1,storage:re||new D,keyPrefix:Q(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,C=".";if(N.storagePool=Object.assign(Object.create(null),{[C]:j(C)}),globalThis.Storage){if(globalThis.localStorage instanceof globalThis.Storage)N.storagePool.local=j("local",globalThis.localStorage);if(globalThis.sessionStorage instanceof globalThis.Storage)N.storagePool.session=j("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=l.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,ge=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 de,Se,Ae,Ce;for(let Re of re.listeners){let Le=Object.create(null);Le.storageName=re.jzClass,Le.type=B,Re.decodePages;let Ge=Re.events[B];if(Ge){if(!Re.includeJournal&&ae[0]==="jrnl")continue;if(B==="write"&&Re.decodePages&&+ae[0]>0){if(Le.data=[ae[0]],Ce?.[ae[0]]){Le.data[1]=Ce[ae[0]];continue}de??=new TextEncoder("utf-8"),Se??=N.memBuffer(10),Ae??=N.memBuffer(11);let tt=de.encode(ae[1]),Ue=I.heap8u();Ue.set(tt,Number(Se)),Ue[I.ptr.addn(Se,tt.length)]=0;let wt=W(Se,Ae,N.buffer.n);if(wt>0)Ce??=Object.create(null),Ce[ae[0]]=Le.data[1]=Ue.slice(Number(Ae),I.ptr.addn(Ae,wt));else continue}else Le.data=ae.length?ae.length===1?ae[0]:ae:void 0;try{Ge(Le)?.catch?.(oe)}catch(tt){G("notifyListeners [",re.jzClass,"]",B,tt)}}}}catch(de){oe(de)}},me=(B)=>typeof B==="string"?N.storagePool[B]:N.storagePool[I.cstrToJs(B)],ve=I.exports.sqlite3__wasm_kvvfsMakeKey,M=(B,re,ae)=>re&&B.keyPrefix?ve(re,ae):ae,g=(B,re,ae)=>I.cstrToJs(M(B,re,ae)),w=(B)=>+B.storage.getItem(B.keyPrefix+"sz"),T=new Map,P={vfs:Object.create(null),ioDb:Object.create(null),ioJrnl:Object.create(null)},te=new l.sqlite3_vfs(U.$pVfs),se=new l.sqlite3_io_methods(U.$pIoDb),A=new l.sqlite3_io_methods(U.$pIoJrnl),L=Object.create(null),Y=Object.assign(Object.create(null),{pFileHandles:T,cache:N,storageForZClass:me,KVVfsStorage:D,disablePageSizeChange:!0});if(J.log)J.internal=Y;let ne={recordHandler:{xRcrdRead:(B,re,ae,de)=>{try{let Se=I.cstrToJs(B),Ae=me(Se);if(!Ae)return-1;let Ce=g(Ae,B,re);J?.log?.xRcrdRead&&G("xRcrdRead",Se,Ce,de,Ae);let Re=Ae.storage.getItem(Ce);if(Re===null)return-1;let Le=Re.length;if(de<=0)return Le;else if(de===1)return I.poke(ae,0),Le;if(de+1<Le)V(l.SQLITE_RANGE,"xRcrdRead()",Se,Ce,"input buffer is too small: need",Le,"but have",de);let Ge=N.memBuffer(0),tt=I.heap8(),Ue;for(Ue=0;Ue<Le;++Ue)tt[I.ptr.add(Ge,Ue)]=Re.codePointAt(Ue)&255;return tt.copyWithin(Number(ae),Number(Ge),I.ptr.addn(Ge,Ue)),tt[I.ptr.add(ae,Le)]=0,de}catch(Se){return ue("kvrecordRead()",Se),N.setError(Se),-2}},xRcrdWrite:(B,re,ae)=>{try{let de=me(B),Se=g(de,B,re),Ae=I.cstrToJs(ae);return J?.log?.xRcrdWrite&&G("xRcrdWrite",Se,de),de.storage.setItem(Se,Ae),de.listeners&&we("write",de,Se,Ae),0}catch(de){return ue("kvrecordWrite()",de),N.setError(de,l.SQLITE_IOERR)}},xRcrdDelete:(B,re)=>{try{let ae=me(B),de=g(ae,B,re);return J?.log?.xRcrdDelete&&G("xRcrdDelete",de,ae),ae.storage.removeItem(de),ae.listeners&&we("delete",ae,de),0}catch(ae){return ue("kvrecordDelete()",ae),N.setError(ae,l.SQLITE_IOERR)}}},vfs:{xOpen:function(B,re,ae,de,Se){N.popError();let Ae;try{if(!re)Ae=I.allocCString(""+ae+"."+(Math.random()*1e5|0)),re=Ae;let Ce=I.cstrToJs(re);if(J?.log?.xOpen&&H("xOpen",Ce,"flags =",de),ee(Ce,!0),de&(l.SQLITE_OPEN_MAIN_DB|l.SQLITE_OPEN_TEMP_DB|l.SQLITE_OPEN_TRANSIENT_DB)&&N.rxJournalSuffix.test(Ce))V(l.SQLITE_ERROR,"DB files may not have a '-journal' suffix.");let Re=me(Ce);if(!Re&&!(de&l.SQLITE_OPEN_CREATE))V(l.SQLITE_ERROR,"Storage not found:",Ce);let Le=P.vfs.xOpen(B,re,ae,de,Se);if(Le)return Le;let Ge=!!(l.SQLITE_OPEN_DELETEONCLOSE&de);if(I.isPtr(arguments[1])){if(l.sqlite3_uri_boolean(re,"delete-on-close",0))Ge=!0}let tt=new h(ae);if(b.assert(tt.$zClass,"Missing f.$zClass"),tt.addOnDispose(Ae),Ae=void 0,Re)++Re.refc,Re.files.push(tt),I.poke32(Se,de);else{I.poke32(Se,de|l.SQLITE_OPEN_CREATE),b.assert(!tt.$isJournal,"Opening a journal before its db? "+Ce);let Ue=Ce.replace(N.rxJournalSuffix,"");Re=j(Ue),S(Re),Re.files.push(tt),Re.deleteAtRefc0=Ge,J?.log?.xOpen&&H("xOpen installed storage handle [",Ue,Ue+"-journal","]",Re)}return T.set(ae,{store:Re,file:tt,jzClass:Ce}),Re.listeners&&we("open",Re,Re.files.length),0}catch(Ce){return G("xOpen:",Ce),N.setError(Ce)}finally{Ae&&I.dealloc(Ae)}},xDelete:function(B,re,ae){N.popError();try{let de=I.cstrToJs(re);if(N.rxJournalSuffix.test(de))L.xRcrdDelete(re,N.zKeyJrnl);return 0}catch(de){return G("xDelete",de),N.setError(de)}},xAccess:function(B,re,ae,de){N.popError();try{let Se=me(re),Ae=Se?.jzClass||I.cstrToJs(re);if(J?.log?.xAccess)H("xAccess",Ae,"flags =",ae,"*pResOut =",I.peek32(de),"store =",Se);if(!Se)try{ee(Ae)}catch(Ce){return I.poke32(de,0),0}if(Se){let Ce=Se.keyPrefix+(N.rxJournalSuffix.test(Ae)?"jrnl":"1"),Re=Se.storage.getItem(Ce)?0:1;I.poke32(de,Re)}else I.poke32(de,0);return 0}catch(Se){return ue("xAccess",Se),N.setError(Se)}},xRandomness:function(B,re,ae){let de=I.heap8u(),Se=0,Ae=Number(ae);for(;Se<re;++Se)de[Ae+Se]=Math.random()*255000&255;return re},xGetLastError:function(B,re,ae){let de=N.popError();if(H("xGetLastError",de),de){let Se=I.scopedAllocPush();try{let[Ae,Ce]=I.scopedAllocCString(de.message,!0);if(I.cstrncpy(ae,Ae,re),Ce>re)I.poke8(I.ptr.add(ae,re,-1),0);return H("set xGetLastError",de.message),de.resultCode|0||l.SQLITE_IOERR}catch(Ae){return l.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((de)=>de!==re.file),--ae.refc<=0&&ae.deleteAtRefc0)pe(ae);P.ioDb.xClose(B),re.file.dispose(),ae.listeners&&we("close",ae,ae.files.length)}return 0}catch(re){return ue("xClose",re),N.setError(re)}},xFileControl:function(B,re,ae){N.popError();try{let de=T.get(B);if(b.assert(de,"Missing KVVfsFile handle"),J?.log?.xFileControl&&H("xFileControl",de,"op =",re),re===l.SQLITE_FCNTL_PRAGMA&&Y.disablePageSizeChange){let Ae=I.peekPtr(I.ptr.add(ae,I.ptr.size));if(I.cstrToJs(Ae)==="page_size"){J?.log?.xFileControl&&H("xFileControl pragma",I.cstrToJs(Ae));let Ce=I.peekPtr(I.ptr.add(ae,2*I.ptr.size));if(Ce)return J?.log?.xFileControl&&G("xFileControl pragma",de,"NOT setting page size to",I.cstrToJs(Ce)),de.file.$szPage=-1,0;else if(de.file.$szPage>0)return J?.log?.xFileControl&&G("xFileControl",de,"getting page size",de.file.$szPage),I.pokePtr(ae,I.allocCString(""+de.file.$szPage)),0}}let Se=P.ioDb.xFileControl(B,re,ae);if(Se==0&&l.SQLITE_FCNTL_SYNC===re)de.store.listeners&&we("sync",de.store,!1);return Se}catch(de){return ue("xFileControl",de),N.setError(de)}},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 de=P.ioDb.xSync(B,re);if(de==0&&ae.store.listeners)we("sync",ae.store,!0);return de}catch(ae){return ue("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,U[U.memberKey(re)]=I.installFunction(U.memberSignature(re),ae)}for(let B of Object.entries(ne.vfs)){let re=B[0],ae=B[1],de=te.memberKey(re),Se=te.structInfo.members[re]||b.toss("Missing pVfs.structInfo[",re,"]");P.vfs[re]=I.functionEntry(te[de]),te[de]=I.installFunction(Se.signature,ae)}for(let B of Object.entries(ne.ioDb)){let re=B[0],ae=B[1],de=se.memberKey(re);P.ioDb[re]=I.functionEntry(se[de])||b.toss("Missing native pIoDb[",de,"]"),se[de]=I.installFunction(se.memberSignature(re),ae)}for(let B of Object.entries(ne.ioJrnl)){let re=B[0],ae=B[1],de=A.memberKey(re);if(P.ioJrnl[re]=I.functionEntry(A[de])||b.toss("Missing native pIoJrnl[",de,"]"),ae===!0)A[de]=se[de]||b.toss("Missing copied pIoDb[",de,"]");else A[de]=I.installFunction(A.memberSignature(re),ae)}}finally{U.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(l.SQLITE_ACCESS,"Cannot clear in-use database storage.");let de=ae.storage,Se=[],Ae,Ce=de.length;for(Ae=0;Ae<Ce;++Ae){let Re=de.key(Ae);if(!ae.keyPrefix||Re.startsWith(ae.keyPrefix))Se.push(Re)}return Se.forEach((Re)=>de.removeItem(Re)),Se.length},ke=function B(re){if(re==="")return B("local")+B("session");let ae=me(re);if(!ae)return 0;let de=ae.storage,Se,Ae=0;for(Se=0;Se<de.length;++Se){let Ce=de.key(Se);if(!ae.keyPrefix||Ce.startsWith(ae.keyPrefix))Ae+=Ce.length,Ae+=de.getItem(Ce).length}return Ae*2},Pe=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 de=ae?me(ae.name):null;if(!de)V(l.SQLITE_NOTFOUND,"There is no kvvfs storage named",ae?.name);let Se=de.storage,Ae=Object.assign(Object.create(null),{name:de.jzClass,timestamp:Date.now(),pages:[]}),Ce=Object.create(null),Re=de.keyPrefix,Le=Re?/^kvvfs-[^-]+-(\w+)/:void 0,Ge=0,tt=Se.length;for(;Ge<tt;++Ge){let Ue=Se.key(Ge);if(!Re||Ue.startsWith(Re)){let wt=(Re?Le.exec(Ue):void 0)?.[1]??Ue;switch(wt){case"jrnl":if(ae.includeJournal)Ae.journal=Se.getItem(Ue);break;case"sz":Ae.size=+Se.getItem(Ue);break;default:if(wt=+wt,!b.isInt32(wt)||wt<=0)V(l.SQLITE_RANGE,"Malformed kvvfs key: "+Ue);if(ae.decodePages){let Ht=Se.getItem(Ue),an=Ht.length,Jt=N.memBuffer(0),qr=N.memBuffer(1),Fn=I.heap8u(),Ct=0;for(;Ct<an;++Ct)Fn[I.ptr.add(Jt,Ct)]=Ht.codePointAt(Ct)&255;Fn[I.ptr.add(Jt,Ct)]=0;let Ao=W(Jt,qr,N.buffer.n);Ce[wt]=Fn.slice(Number(qr),I.ptr.addn(qr,Ao))}else Ce[wt]=Se.getItem(Ue);break}}}if(ae.decodePages)N.memBufferFree(1);return Object.keys(Ce).map((Ue)=>+Ue).sort().forEach((Ue)=>Ae.pages.push(Ce[Ue])),Ae},$e=function(B,re=!1){if(!B?.timestamp||!B.name||B.size===void 0||!Array.isArray(B.pages))V(l.SQLITE_MISUSE,"Malformed export object.");else if(!B.size||B.size!==(B.size|0)||B.size>=2147483647)V(l.SQLITE_RANGE,"Invalid db size: "+B.size);ee(B.name);let ae=me(B.name),de=!ae;if(ae){if(!re)V(l.SQLITE_ACCESS,"Storage '"+B.name+"' already exists and","overwrite was not specified.");else if(!ae.files||!ae.jzClass)V(l.SQLITE_ERROR,"Internal storage object",B.name,"seems to be malformed.");else if(ae.files.length)V(l.SQLITE_IOERR_ACCESS,"Cannot import db storage while it is in use.");ye(B.name)}else ae=j(B.name);let Se=Q(B.name),Ae;try{let Ce=ae.storage;if(Ce.setItem(Se+"sz",B.size),B.journal)Ce.setItem(Se+"jrnl",B.journal);if(B.pages[0]instanceof Uint8Array)B.pages.forEach((Re,Le)=>{let Ge=Re.length;Ae??=N.memBuffer(1);let tt=N.memBuffer(0),Ue=I.heap8u();Ue.set(Re,Number(tt)),Ue[I.ptr.addn(tt,Ge)]=0;let wt=ge(tt,Ge,Ae);b.assert(wt<N.buffer.n,"Impossibly long output - possibly smashed the heap"),b.assert(I.peek8(I.ptr.add(Ae,wt))===0,"Expecting NUL-terminated encoded output");let Ht=I.cstrToJs(Ae);Ce.setItem(Se+(Le+1),Ht)});else if(B.pages[0])B.pages.forEach((Re,Le)=>Ce.setItem(Se+(Le+1),Re));if(de)S(ae)}catch{if(!de)try{ye(B.name)}catch(Ce){}}finally{if(Ae)N.memBufferFree(1)}return this},Ve=function(B){let re=me(B);if(re){++re.refc;return}ee(B),S(j(B))},dt=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},jt=function(B){if(!B||typeof B!=="object")V(l.SQLITE_MISUSE,"Expecting a listener object.");let re=me(B.storage);if(!re)if(B.storage&&B.reserve)Ve(B.storage),re=me(B.storage),b.assert(re,"Unexpectedly cannot fetch reserved storage "+B.storage);else V(l.SQLITE_NOTFOUND,"No such storage:",B.storage);if(B.events)(re.listeners??=[]).push(B)},Nr=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 de=ae>re.listeners.length;if(!re.listeners.length)re.listeners=void 0;return de}return!1};if(f.kvvfs.reserve=Ve,f.kvvfs.import=$e,f.kvvfs.export=Pe,f.kvvfs.unlink=dt,f.kvvfs.listen=jt,f.kvvfs.unlisten=Nr,f.kvvfs.exists=(B)=>!!me(B),f.kvvfs.estimateSize=ke,f.kvvfs.clear=ye,globalThis.Storage)l.sqlite3_js_kvvfs_size=(B="")=>ke(B),l.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 de=B.dbCtorHelper.normalizeArgs(...arguments);switch(de.vfs="kvvfs",de.filename){case":sessionStorage:":de.filename="session";break;case":localStorage:":de.filename="local";break}let Se=/(file:(\/\/)?)([^?]+)/.exec(de.filename);ee(Se?Se[3]:de.filename),B.dbCtorHelper.call(this,de)},f.oo1.JsStorageDb.defaultStorageName=N.storagePool.session?"session":C;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=ke,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((Ce,Re)=>B[Ce].colId=Re);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((Ce)=>!N.rxJournalSuffix.test(Ce))});let de=function(Ce,Re){let Le=Ce instanceof l.sqlite3_vtab_cursor?Ce:re.xCursor.get(Ce);if(Re||!Le.vTabState)Le.vTabState=Object.assign(Object.create(ae),{rowid:0,names:Object.keys(N.storagePool).filter((Ge)=>!N.rxJournalSuffix.test(Ge))});return Le.vTabState},Se=()=>{},Ae=function Ce(){return Ce.mod??=new f.capi.sqlite3_module().setupModule({catchExceptions:!0,methods:{xConnect:function(Re,Le,Ge,tt,Ue,wt){Se("xConnect");try{let Ht=[];Object.keys(B).forEach((Jt)=>{Ht.push(Jt+" "+B[Jt].type)});let an=l.sqlite3_declare_vtab(Re,"CREATE TABLE ignored("+Ht.join(",")+")");if(an===0){let Jt=re.xVtab.create(Ue);b.assert(Jt===re.xVtab.get(I.peekPtr(Ue)),"output pointer check failed")}return an}catch(Ht){return re.xError("xConnect",Ht,l.SQLITE_ERROR)}},xCreate:I.ptr.null,xDisconnect:function(Re){return Se("xDisconnect",...arguments),re.xVtab.dispose(Re),0},xOpen:function(Re,Le){return Se("xOpen",...arguments),re.xCursor.create(Le),0},xClose:function(Re){Se("xClose",...arguments);let Le=re.xCursor.unget(Re);return delete Le.vTabState,Le.dispose(),0},xNext:function(Re){Se("xNext",...arguments);let Le=re.xCursor.get(Re);return++de(Le).rowid,0},xColumn:function(Re,Le,Ge){Se("xColumn",...arguments);let tt=de(Re),Ue=tt.row();switch(b.assert(Ue,"Unexpected xColumn call"),Ge){case B.rowid.colId:l.sqlite3_result_int(Le,tt.rowid);break;case B.name.colId:l.sqlite3_result_text(Le,Ue.jzClass,-1,l.SQLITE_TRANSIENT);break;case B.nRef.colId:l.sqlite3_result_int(Le,Ue.refc);break;case B.nOpen.colId:l.sqlite3_result_int(Le,Ue.files.length);break;case B.isTransient.colId:l.sqlite3_result_int(Le,!!Ue.deleteAtRefc0);break;case B.dbSize.colId:l.sqlite3_result_int(Le,w(Ue));break;default:return l.sqlite3_result_error(Le,"Invalid column id: "+Ge),l.SQLITE_RANGE}return 0},xRowid:function(Re,Le){Se("xRowid",...arguments);let Ge=de(Re);return re.xRowid(Le,Ge.rowid),0},xEof:function(Re){let Le=de(Re);return Se("xEof?="+!Le.row(),...arguments),!Le.row()},xFilter:function(Re,Le,Ge,tt,Ue){return Se("xFilter",...arguments),de(Re,!0),0},xBestIndex:function(Re,Le){Se("xBestIndex",...arguments);let Ge=new l.sqlite3_index_info(Le);return Ge.$estimatedRows=N.storagePool.size,Ge.$estimatedCost=1,Ge.dispose(),0}}})};f.kvvfs.create_module=function(Ce,Re="sqlite_kvvfs"){return l.sqlite3_create_module(Ce,Re,Ae(),I.ptr.null)}}}),globalThis.sqlite3ApiBootstrap.initializers.push(function(f){if(f.config.disable?.vfs?.opfs&&f.config.disable.vfs["opfs-vfs"])return;let l=f.util.toss;f.capi;let d=f.util;f.wasm;let h=f.opfs=Object.create(null);h.thisThreadHasOPFS=()=>globalThis.FileSystemHandle&&globalThis.FileSystemDirectoryHandle&&globalThis.FileSystemFileHandle&&globalThis.FileSystemFileHandle.prototype.createSyncAccessHandle&&navigator?.storage?.getDirectory,h.getRootDir=async function b(){return b.promise??=navigator.storage.getDirectory().then((I)=>(h.rootDirectory=I,I)).catch((I)=>{throw delete b.promise,I})},h.getResolvedPath=function(b,I){let V=new URL(b,"file://irrelevant").pathname;return I?V.split("/").filter((U)=>!!U):V},h.getDirForFilename=async function(I,V=!1){let U=h.getResolvedPath(I,!0),N=U.pop(),q=await h.getRootDir();for(let H of U)if(H)q=await q.getDirectoryHandle(H,{create:!!V});return[q,N]},h.mkdir=async function(b){try{return await h.getDirForFilename(b+"/filepart",!0),!0}catch(I){return!1}},h.entryExists=async function(b){try{let[I,V]=await h.getDirForFilename(b);return await I.getFileHandle(V),!0}catch(I){return!1}},h.randomFilename=function b(I=16){if(!b._chars)b._chars="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012346789",b._n=b._chars.length;let V=[],U=0;for(;U<I;++U){let N=Math.random()*(b._n*64)%b._n|0;V[U]=b._chars[N]}return V.join("")},h.treeList=async function(){let b=async function V(U,N){N.name=U.name,N.dirs=[],N.files=[];for await(let q of U.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 h.getRootDir(),I),I},h.rmfr=async function(){let b=await h.getRootDir(),I={recurse:!0};for await(let V of b.values())b.removeEntry(V.name,I)},h.unlink=async function(b,I=!1,V=!1){try{let[U,N]=await h.getDirForFilename(b,!1);return await U.removeEntry(N,{recursive:I}),!0}catch(U){if(V)throw Error("unlink(",arguments[0],") failed: "+U.message,{cause:U});return!1}},h.traverse=async function(b){let I={recursive:!0,directory:await h.getRootDir()};if(typeof b==="function")b={callback:b};b=Object.assign(I,b||{}),async function V(U,N){for await(let q of U.values())if(b.callback(q,U,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,U]=await h.getDirForFilename(b,!0),N=await(await V.getFileHandle(U,{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)l("Input size",q,"is not correct for an SQLite database.");if(!G){let ue=new Uint8Array(20);N.read(ue,{at:0}),d.affirmDbHeader(ue)}return N.write(new Uint8Array([1,1]),{at:18}),q}catch(ue){throw await N.close(),N=void 0,await V.removeEntry(U).catch(()=>{}),ue}finally{if(N)await N.close()}};h.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,[U,N]=await h.getDirForFilename(b,!0),q,H=0;try{if(q=await(await U.getFileHandle(N,{create:!0})).createSyncAccessHandle(),q.truncate(0),H=q.write(I,{at:0}),H!=V)l("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 U.removeEntry(N).catch(()=>{}),G}finally{if(q)await q.close()}},h.vfsInstallationFeatureCheck=function(b){if(!globalThis.SharedArrayBuffer||!globalThis.Atomics)l("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")l("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)l("Missing required OPFS APIs.");else if(b==="opfs-wl"&&!globalThis.Atomics.waitAsync)l("The",b,"VFS requires Atomics.waitAsync(), which is not available.")},h.initOptions=function(I,V){let U=new URL(globalThis.location.href).searchParams;if(U.has(I+"-disable"))return;try{h.vfsInstallationFeatureCheck(I)}catch(N){return}if(V=d.nu(V),V.vfsName=I,V.verbose??=U.has("opfs-verbose")?+U.get("opfs-verbose"):1,V.sanityChecks??=U.has("opfs-sanity-check"),!h.proxyUri){if(h.proxyUri="sqlite3-opfs-async-proxy.js",f.scriptInfo?.sqlite3Dir)h.proxyUri=f.scriptInfo.sqlite3Dir+h.proxyUri}if(V.proxyUri??=h.proxyUri,typeof V.proxyUri==="function")V.proxyUri=V.proxyUri();return h.options=V},h.createVfsState=function(){let b=d.nu(),I=h.options;b.verbose=I.verbose;let V=[f.config.error,f.config.warn,f.config.log],U=I.vfsName||l("Maintenance required: missing VFS name"),N=(W,...ge)=>{if(b.verbose>W)V[W](U+":",...ge)},q=(...W)=>N(2,...W),H=(...W)=>N(1,...W),G=(...W)=>N(0,...W),{capi:ue,wasm:D}=f,R=b.vfs=new ue.sqlite3_vfs,Q=R.ioMethods=new ue.sqlite3_io_methods;Q.$iVersion=1,R.$iVersion=2,R.$szOsFile=ue.sqlite3_file.structInfo.sizeof,R.$mxPathname=1024,R.$zName=D.allocCString(U),R.addOnDispose("$zName",R.$zName,Q),R.metrics=d.nu({counters:d.nu(),dump:function(){let W,ge=0,we=0,me=0;for(W in b.opIds){let ve=ee[W];ge+=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,`
534
- Total of`,ge,"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,ge=(ve)=>ve.count=ve.time=ve.wait=0,we=R.metrics.counters;for(W in b.opIds)ge(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]=ue[W]??l("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,j=R.opRun=(W,...ge)=>{let we=b.opIds[W]||l(R.vfsName+": Invalid op ID:",W);b.s11n.serialize(...ge),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 M=b.s11n.deserialize();if(M)G(W+"() async error:",...M)}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,C=R.__openFiles=Object.create(null);R.ioSyncWrappers=d.nu({xCheckReservedLock:function(W,ge){return D.poke(ge,0,"i32"),0},xClose:function(W){pe("xClose");let ge=0,we=C[W];if(we){if(delete C[W],ge=j("xClose",W),we.sq3File)we.sq3File.dispose()}return S(),ge},xDeviceCharacteristics:function(W){return ue.SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN},xFileControl:function(W,ge,we){return ue.SQLITE_NOTFOUND},xFileSize:function(W,ge){pe("xFileSize");let we=j("xFileSize",W);if(we==0)try{let me=b.s11n.deserialize()[0];D.poke(ge,me,"i64")}catch(me){G("Unexpected error reading xFileSize() result:",me),we=b.sq3Codes.SQLITE_IOERR}return S(),we},xRead:function(W,ge,we,me){pe("xRead");let ve=C[W],M;try{if(M=j("xRead",W,we,Number(me)),M===0||ue.SQLITE_IOERR_SHORT_READ===M)D.heap8u().set(ve.sabView.subarray(0,we),Number(ge))}catch(g){G("xRead(",arguments,") failed:",g,ve),M=ue.SQLITE_IOERR_READ}return S(),M},xSync:function(W,ge){pe("xSync");let we=j("xSync",W,ge);return S(),we},xTruncate:function(W,ge){pe("xTruncate");let we=j("xTruncate",W,Number(ge));return S(),we},xWrite:function(W,ge,we,me){pe("xWrite");let ve=C[W],M;try{ve.sabView.set(D.heap8u().subarray(Number(ge),Number(ge)+we)),M=j("xWrite",W,we,Number(me))}catch(g){G("xWrite(",arguments,") failed:",g,ve),M=ue.SQLITE_IOERR_WRITE}return S(),M}}),R.vfsSyncWrappers={xAccess:function(W,ge,we,me){pe("xAccess");let ve=j("xAccess",D.cstrToJs(ge));return D.poke(me,ve?0:1,"i32"),S(),0},xCurrentTime:function(W,ge){return D.poke(ge,2440587.5+new Date().getTime()/86400000,"double"),0},xCurrentTimeInt64:function(W,ge){return D.poke(ge,210866760000000+new Date().getTime(),"i64"),0},xDelete:function(W,ge,we){pe("xDelete");let me=j("xDelete",D.cstrToJs(ge),we,!1);return S(),me},xFullPathname:function(W,ge,we,me){return D.cstrncpy(me,ge,we)<we?0:ue.SQLITE_CANTOPEN},xGetLastError:function(W,ge,we){return f.config.warn("OPFS xGetLastError() has nothing sensible to return."),0},xOpen:function(ge,we,me,ve,M){pe("xOpen");let g=0,w,T;if(!we)w=h.randomFilename(),we=T=D.allocCString(w);else if(D.isPtr(we)){if(ue.sqlite3_uri_boolean(we,"opfs-unlock-asap",0))g|=b.opfsFlags.OPFS_UNLOCK_ASAP;if(ue.sqlite3_uri_boolean(we,"delete-before-open",0))g|=b.opfsFlags.OPFS_UNLINK_BEFORE_OPEN;w=D.cstrToJs(we)}else return f.config.error("Impossible zName value in xOpen?",we),ue.SQLITE_CANTOPEN;let P=d.nu({fid:me,filename:w,sab:new SharedArrayBuffer(b.fileBufferSize),flags:ve,readOnly:!(ue.SQLITE_OPEN_CREATE&ve)&&!!(ve&ue.SQLITE_OPEN_READONLY)}),te=j("xOpen",me,w,ve,g);if(te){if(T)D.dealloc(T)}else{if(P.readOnly)D.poke(M,ue.SQLITE_OPEN_READONLY,"i32");if(C[me]=P,P.sabView=b.sabFileBufView,P.sq3File=new ue.sqlite3_file(me),T)P.sq3File.addOnDispose(T);P.sq3File.$pMethods=Q.pointer,P.lockType=ue.SQLITE_LOCK_NONE}return S(),te}};let K=ue.sqlite3_vfs_find(null);if(K){let W=new ue.sqlite3_vfs(K);R.$xRandomness=W.$xRandomness,R.$xSleep=W.$xSleep,W.dispose()}if(!R.$xRandomness)R.vfsSyncWrappers.xRandomness=function(W,ge,we){let me=D.heap8u(),ve=0,M=Number(we);for(;ve<ge;++ve)me[M+ve]=Math.random()*255000&255;return ve};if(!R.$xSleep)R.vfsSyncWrappers.xSleep=function(W,ge){return pe("xSleep"),Atomics.wait(b.sabOPView,b.opIds.xSleep,0,ge),S(),0};let oe=function(){if(b.s11n)return b.s11n;let W=new TextDecoder,ge=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 M=(w)=>ve[typeof w]||l("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:l("Invalid type ID:",w)}};return b.s11n.deserialize=function(w=!1){performance.now();let T=we[0],P=T?[]:null;if(T){let te=[],se=1,A,L,Y;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)Y=me[ne.getter](se,b.littleEndian),se+=ne.size;else L=me.getInt32(se,b.littleEndian),se+=4,Y=W.decode(we.slice(se,se+L)),se+=L;P.push(Y)}}if(w)we[0]=0;return P},b.s11n.serialize=function(...w){if(performance.now(),w.length){let T=[],P=0,te=1;we[0]=w.length&255;for(;P<w.length;++P,++te)T.push(M(w[P])),we[te]=T[P].id;for(P=0;P<w.length;++P){let se=T[P];if(se.setter)me[se.setter](te,w[P],b.littleEndian),te+=se.size;else{let A=ge.encode(w[P]);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,ge){return Object.assign(R.ioSyncWrappers,W),new Promise(function(we,me){let ve=void 0,M=(A)=>(ve=!0,R.dispose(),me(A)),g=()=>{try{ge(f,R)}catch(A){return M(A)}return ve=!1,we(f)},w=h.options;w.proxyUri+(w.proxyUri.indexOf("?")<0?"?":"&")+U;let T=new URL("sqlite3-opfs-async-proxy.js",import.meta.url);T.searchParams.set("vfs",U);let P=R.worker=new Worker(T.toString()),te=setTimeout(()=>{if(ve===void 0)M(Error("Timeout while waiting for OPFS async proxy worker."))},4000);P._originalOnError=P.onerror,P.onerror=function(A){G("Error initializing OPFS asyncer:",A),M(Error("Loading OPFS async Worker failed for unknown reasons."))},R.opRun;let se=function(){let A=D.scopedAllocPush(),L=new ue.sqlite3_file;try{let Y=L.pointer,ne=ue.SQLITE_OPEN_CREATE|ue.SQLITE_OPEN_READWRITE|ue.SQLITE_OPEN_MAIN_DB,ye=D.scopedAlloc(8),ke="/sanity/check/file"+randomFilename(8),Pe=D.scopedAllocCString(ke),$e;if(b.s11n.serialize("This is ä string."),$e=b.s11n.deserialize(),q("deserialize() says:",$e),$e[0]!=="This is ä string.")l("String d13n error.");if(R.vfsSyncWrappers.xAccess(R.pointer,Pe,0,ye),$e=D.peek(ye,"i32"),q("xAccess(",ke,") exists ?=",$e),$e=R.vfsSyncWrappers.xOpen(R.pointer,Pe,Y,ne,ye),q("open rc =",$e,"state.sabOPView[xOpen] =",b.sabOPView[b.opIds.xOpen]),$e!==0){G("open failed with code",$e);return}if(R.vfsSyncWrappers.xAccess(R.pointer,Pe,0,ye),$e=D.peek(ye,"i32"),!$e)l("xAccess() failed to detect file.");if($e=R.ioSyncWrappers.xSync(L.pointer,0),$e)l("sync failed w/ rc",$e);if($e=R.ioSyncWrappers.xTruncate(L.pointer,1024),$e)l("truncate failed w/ rc",$e);if(D.poke(ye,0,"i64"),$e=R.ioSyncWrappers.xFileSize(L.pointer,ye),$e)l("xFileSize failed w/ rc",$e);if(q("xFileSize says:",D.peek(ye,"i64")),$e=R.ioSyncWrappers.xWrite(L.pointer,Pe,10,1),$e)l("xWrite() failed!");let Ve=D.scopedAlloc(16);$e=R.ioSyncWrappers.xRead(L.pointer,Ve,6,2),D.poke(Ve+6,0);let dt=D.cstrToJs(Ve);if(q("xRead() got:",dt),dt!=="sanity")l("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($e=R.ioSyncWrappers.xClose(Y),q("xClose rc =",$e,"sabOPView =",b.sabOPView),q("Deleting file:",ke),R.vfsSyncWrappers.xDelete(R.pointer,Pe,4660),R.vfsSyncWrappers.xAccess(R.pointer,Pe,0,ye),$e=D.peek(ye,"i32"),$e)l("Expecting 0 from xAccess(",ke,") after xDelete().");H("End of OPFS sanity checks.")}finally{L.dispose(),D.scopedAllocPop(A)}};P.onmessage=function({data:A}){switch(A.type){case"opfs-unavailable":M(Error(A.payload.join(" ")));break;case"opfs-async-loaded":delete b.vfs,P.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(h.thisThreadHasOPFS())h.getRootDir().then((L)=>{P.onerror=P._originalOnError,delete P._originalOnError,q("End of OPFS sqlite3_vfs setup.",R),g()}).catch(M);else g()}catch(L){G(L),M(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),M(Error(L));break}}}})},b}}),globalThis.sqlite3ApiBootstrap.initializers.push(function(f){if(!f.opfs||f.config.disable?.vfs?.opfs)return;let l=f.util,d=f.opfs||f.util.toss("Missing sqlite3.opfs"),h=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:U,mTimeEnd:N,opRun:q,__openFiles:H}=I;return I.bindVfs(l.nu({xLock:function(G,ue){U("xLock"),++V.xLock.count;let D=H[G],R=0;if(D.lockType)D.lockType=ue;else if(R=q("xLock",G,ue),R===0)D.lockType=ue;return N(),R},xUnlock:function(G,ue){U("xUnlock"),++V.xUnlock.count;let D=H[G],R=0;if(b.SQLITE_LOCK_NONE===ue&&D.lockType)R=q("xUnlock",G,ue);if(R===0)D.lockType=ue;return N(),R}}),function(G,ue){if(G.oo1){let D=function(...R){let Q=G.oo1.DB.dbCtorHelper.normalizeArgs(...R);Q.vfs=ue.$zName,G.oo1.DB.dbCtorHelper.call(this,Q)};D.prototype=Object.create(G.oo1.DB.prototype),G.oo1.OpfsDb=D,D.importDb=d.importDb,G.oo1.DB.dbCtorHelper.setVfsPostOpenCallback(I.pointer,function(R,Q){Q.capi.sqlite3_busy_timeout(R,1e4)})}})};globalThis.sqlite3ApiBootstrap.initializersAsync.push(async(E)=>h().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 l=f.util.toss,d=f.util.toss3,h=Object.create(null),{capi:E,util:b,wasm:I}=f,V=4096,U=512,N=4,q=8,H=U+N,G=U,ue=H,D=V,R=E.SQLITE_OPEN_MAIN_DB|E.SQLITE_OPEN_MAIN_JOURNAL|E.SQLITE_OPEN_SUPER_JOURNAL|E.SQLITE_OPEN_WAL,Q=E.SQLITE_OPEN_MEMORY,ee=".opaque",j=()=>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}),C=[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),ge=(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)},M={xCheckReservedLock:function(A,L){let Y=me(A);return Y.log("xCheckReservedLock"),Y.storeErr(),I.poke32(L,1),0},xClose:function(A){let L=me(A);L.storeErr();let Y=L.getOFileForS3File(A);if(Y)try{if(L.log(`xClose ${Y.path}`),L.mapS3FileToOFile(A,!1),Y.sah.flush(),Y.flags&E.SQLITE_OPEN_DELETEONCLOSE)L.deletePath(Y.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,Y){return E.SQLITE_NOTFOUND},xFileSize:function(A,L){let Y=me(A);Y.log("xFileSize");let ne=Y.getOFileForS3File(A).sah.getSize()-D;return I.poke64(L,BigInt(ne)),0},xLock:function(A,L){let Y=me(A);Y.log(`xLock ${L}`),Y.storeErr();let ne=Y.getOFileForS3File(A);return ne.lockType=L,0},xRead:function(A,L,Y,ne){let ye=me(A);ye.storeErr();let ke=ye.getOFileForS3File(A);ye.log(`xRead ${ke.path} ${Y} @ ${ne}`);try{let Pe=ke.sah.read(I.heap8u().subarray(Number(L),Number(L)+Y),{at:D+Number(ne)});if(Pe<Y)return I.heap8u().fill(0,Number(L)+Pe,Number(L)+Y),E.SQLITE_IOERR_SHORT_READ;return 0}catch(Pe){return ye.storeErr(Pe,E.SQLITE_IOERR)}},xSectorSize:function(A){return V},xSync:function(A,L){let Y=me(A);Y.log(`xSync ${L}`),Y.storeErr();let ne=Y.getOFileForS3File(A);try{return ne.sah.flush(),0}catch(ye){return Y.storeErr(ye,E.SQLITE_IOERR)}},xTruncate:function(A,L){let Y=me(A);Y.log(`xTruncate ${L}`),Y.storeErr();let ne=Y.getOFileForS3File(A);try{return ne.sah.truncate(D+Number(L)),0}catch(ye){return Y.storeErr(ye,E.SQLITE_IOERR)}},xUnlock:function(A,L){let Y=me(A);Y.log("xUnlock");let ne=Y.getOFileForS3File(A);return ne.lockType=L,0},xWrite:function(A,L,Y,ne){let ye=me(A);ye.storeErr();let ke=ye.getOFileForS3File(A);ye.log(`xWrite ${ke.path} ${Y} ${ne}`);try{return Y===ke.sah.write(I.heap8u().subarray(Number(L),Number(L)+Y),{at:D+Number(ne)})?0:l("Unknown write() failure.")}catch(Pe){return ye.storeErr(Pe,E.SQLITE_IOERR)}}},g=new E.sqlite3_io_methods;g.$iVersion=1,f.vfs.installVfs({io:{struct:g,methods:M}});let w={xAccess:function(A,L,Y,ne){let ye=W(A);ye.storeErr();try{let ke=ye.getPath(L);I.poke32(ne,ye.hasFilename(ke)?1:0)}catch(ke){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,Y){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,Y,ne){return I.cstrncpy(ne,L,Y)<Y?0:E.SQLITE_CANTOPEN},xGetLastError:function(A,L,Y){let ne=W(A),ye=ne.popErr();if(ne.log(`xGetLastError ${L} e =`,ye),ye){let ke=I.scopedAllocPush();try{let[Pe,$e]=I.scopedAllocCString(ye.message,!0);if(I.cstrncpy(Y,Pe,L),$e>L)I.poke8(I.ptr.add(Y,L,-1),0)}catch(Pe){return E.SQLITE_NOMEM}finally{I.scopedAllocPop(ke)}}return ye?ye.sqlite3Rc||E.SQLITE_IOERR:0},xOpen:function(L,Y,ne,ye,ke){let Pe=W(L);try{ye&=~Q,Pe.log(`xOpen ${I.cstrToJs(Y)} ${ye}`);let $e=Y&&I.peek8(Y)?Pe.getPath(Y):j(),Ve=Pe.getSAHForPath($e);if(!Ve&&ye&E.SQLITE_OPEN_CREATE)if(Pe.getFileCount()<Pe.getCapacity())Ve=Pe.nextAvailableSAH(),Pe.setAssociatedPath(Ve,$e,ye);else l("SAH pool is full. Cannot create file",$e);if(!Ve)l("file not found:",$e);let dt={path:$e,flags:ye,sah:Ve};Pe.mapS3FileToOFile(ne,dt),dt.lockType=E.SQLITE_LOCK_NONE;let jt=new E.sqlite3_file(ne);return jt.$pMethods=g.pointer,jt.dispose(),I.poke32(ke,ye),0}catch($e){return Pe.storeErr($e),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,Y=E.sqlite3_vfs_find(null),ne=Y?new E.sqlite3_vfs(Y):null;if(L.$iVersion=2,L.$szOsFile=E.sqlite3_file.structInfo.sizeof,L.$mxPathname=U,L.addOnDispose(L.$zName=I.allocCString(A),()=>ge(L.pointer,0)),ne)L.$xRandomness=ne.$xRandomness,L.$xSleep=ne.$xSleep,ne.dispose();if(!L.$xRandomness&&!w.xRandomness)w.xRandomness=function(ye,ke,Pe){let $e=I.heap8u(),Ve=0,dt=Number(Pe);for(;Ve<ke;++Ve)$e[dt+Ve]=Math.random()*255000&255;return Ve};if(!L.$xSleep&&!w.xSleep)w.xSleep=(ye,ke)=>0;return f.vfs.installVfs({vfs:{struct:L,methods:w}}),L};class P{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),ge(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)C[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 Y=j(),ne=await(await this.#o.getFileHandle(Y,{create:!0})).createSyncAccessHandle();this.#t.set(ne,Y),this.setAssociatedPath(ne,"",0)}return this.getCapacity()}async reduceCapacity(A){let L=0;for(let Y of Array.from(this.#s)){if(L===A||this.getFileCount()===this.getCapacity())break;let ne=this.#t.get(Y);Y.close(),await this.#o.removeEntry(ne),this.#t.delete(Y),this.#s.delete(Y),++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[Y,ne]of this.#o)if(ne.kind==="file")L.push([Y,ne]);return Promise.all(L.map(async([Y,ne])=>{try{let ye=await ne.createSyncAccessHandle();if(this.#t.set(ye,Y),A)ye.truncate(D),this.setAssociatedPath(ye,"",0);else{let ke=this.getAssociatedPath(ye);if(ke)this.#r.set(ke,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 Y=new Uint32Array(q/4);A.read(Y,{at:ue});let ne=this.computeDigest(this.#n,L);if(Y.every((ye,ke)=>ye===ne[ke])){let ye=this.#n.findIndex((ke)=>ke===0);if(ye===0)A.truncate(D);return ye?J.decode(this.#n.subarray(0,ye)):""}else return K("Disassociating file with bad digest."),this.setAssociatedPath(A,"",0),""}setAssociatedPath(A,L,Y){let ne=pe.encodeInto(L,this.#n);if(U<=ne.written+1)l("Path too long:",L);if(L&&Y)Y|=Q;this.#n.fill(0,ne.written,U),this.#l.setUint32(G,Y);let ye=this.computeDigest(this.#n,Y);if(A.write(this.#n,{at:0}),A.write(ye,{at:ue}),A.flush(),L)this.#r.set(L,A),this.#s.delete(A);else A.truncate(D),this.#s.add(A)}computeDigest(A,L){if(L&Q){let Y=3735928559,ne=1103547991;for(let ye of A)Y=Math.imul(Y^ye,2654435761),ne=Math.imul(ne^ye,104729);return new Uint32Array([Y>>>0,ne>>>0])}else return new Uint32Array([0,0])}async reset(A){await this.isReady;let L=await navigator.storage.getDirectory(),Y;for(let ne of this.vfsDir.split("/"))if(ne)Y=L,L=await L.getDirectoryHandle(ne,{create:!0});return this.#e=L,this.#i=Y,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 h[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.
535
- let L=this.#r.get(A)||l("File not found:",A),Y=L.getSize()-D,ne=new Uint8Array(Y>0?Y:0);if(Y>0){let ye=L.read(ne,{at:D});if(ye!=Y)l("Expected to read "+Y+" bytes but read "+ye+".")}return ne}async importDbChunked(A,L){//! Impl for importDb() when its 2nd arg is a function.
536
- let Y=this.#r.get(A)||this.nextAvailableSAH()||l("No available handles to import to.");Y.truncate(0);let ne=0,ye,ke=!1;try{while((ye=await L())!==void 0){if(ye instanceof ArrayBuffer)ye=new Uint8Array(ye);if(!ke&&ne===0&&ye.byteLength>=15)b.affirmDbHeader(ye),ke=!0;Y.write(ye,{at:D+ne}),ne+=ye.byteLength}if(ne<512||ne%512!==0)l("Input size",ne,"is not correct for an SQLite database.");if(!ke){let Pe=new Uint8Array(20);Y.read(Pe,{at:0}),b.affirmDbHeader(Pe)}Y.write(new Uint8Array([1,1]),{at:D+18})}catch(Pe){throw this.setAssociatedPath(Y,"",0),Pe}return this.setAssociatedPath(Y,A,E.SQLITE_OPEN_MAIN_DB),ne}importDb(A,L){//! Documented elsewhere in this file.
537
- if(L instanceof ArrayBuffer)L=new Uint8Array(L);else if(L instanceof Function)return this.importDbChunked(A,L);let Y=this.#r.get(A)||this.nextAvailableSAH()||l("No available handles to import to."),ne=L.byteLength;if(ne<512||ne%512!=0)l("Byte array size is invalid for an SQLite db.");let ye="SQLite format 3";for(let Pe=0;Pe<15;++Pe)if(ye.charCodeAt(Pe)!==L[Pe])l("Input does not contain an SQLite database header.");let ke=Y.write(L,{at:D});if(ke!=ne)this.setAssociatedPath(Y,"",0),l("Expected to write "+ne+" bytes but wrote "+ke+".");else Y.write(new Uint8Array([1,1]),{at:D+18}),this.setAssociatedPath(Y,A,E.SQLITE_OPEN_MAIN_DB);return ke}}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-"+j(),Y=(await(await A.getFileHandle(L,{create:!0})).createSyncAccessHandle()).close();if(await Y,await A.removeEntry(L),Y?.then)l("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(h[L])try{return await h[L]}catch(Y){if(A.forceReinitIfPreviouslyFailed)delete h[L];else throw Y}if(!globalThis.FileSystemHandle||!globalThis.FileSystemDirectoryHandle||!globalThis.FileSystemFileHandle||!globalThis.FileSystemFileHandle.prototype.createSyncAccessHandle||!navigator?.storage?.getDirectory)return h[L]=Promise.reject(Error("Missing required OPFS APIs."));return h[L]=se().then(async function(){if(A.$testThrowPhase2)throw A.$testThrowPhase2;let Y=new P(A);return Y.isReady.then(async()=>{let ne=new te(Y);if(f.oo1){let ye=f.oo1,ke=Y.getVfs(),Pe=function(...$e){let Ve=ye.DB.dbCtorHelper.normalizeArgs(...$e);Ve.vfs=ke.$zName,ye.DB.dbCtorHelper.call(this,Ve)};Pe.prototype=Object.create(ye.DB.prototype),ne.OpfsSAHPoolDb=Pe}return Y.log("VFS initialized."),ne}).catch(async(ne)=>{throw await Y.removeVfs().catch(()=>{}),ne})}).catch((Y)=>h[L]=Promise.reject(Y))}}),globalThis.sqlite3ApiBootstrap.initializers.push(function(f){if(!f.opfs||f.config.disable?.vfs?.["opfs-wl"])return;let l=f.util;f.util.toss;let d=f.opfs,h="opfs-wl",E=async function(b){if(b=d.initOptions(h,b),!b)return f;f.capi;let I=d.createVfsState().vfs;I.metrics.counters;let{mTimeStart:V,mTimeEnd:U,opRun:N,__openFiles:q}=I;return I.bindVfs(l.nu({xLock:function(H,G){V("xLock");let ue=q[H],D=N("xLock",H,G);if(!D)ue.lockType=G;return U(),D},xUnlock:function(H,G){V("xUnlock");let ue=q[H],D=N("xUnlock",H,G);if(!D)ue.lockType=G;return U(),D}}),function(H,G){if(H.oo1){let ue=function(...D){let R=H.oo1.DB.dbCtorHelper.normalizeArgs(...D);R.vfs=G.$zName,H.oo1.DB.dbCtorHelper.call(this,R)};ue.prototype=Object.create(H.oo1.DB.prototype),H.oo1.OpfsWlDb=ue,ue.importDb=d.importDb}})};globalThis.sqlite3ApiBootstrap.initializersAsync.push(async(b)=>E().catch((I)=>{b.config.warn("Ignoring inability to install the",h,"sqlite3_vfs:",I)}))});try{let f=Object.assign(Object.create(null),{memory:typeof fr<"u"?fr:u.wasmMemory,exports:typeof sn<"u"?sn:Object.prototype.hasOwnProperty.call(u,"wasmExports")?u.wasmExports:u.asm},globalThis.sqlite3ApiBootstrap.defaultConfig,globalThis.sqlite3ApiConfig||{});i.debugModule("Bootstrapping lib config",f);let l=globalThis.sqlite3ApiBootstrap(f);return delete globalThis.sqlite3ApiBootstrap,l}catch(f){throw console.error("sqlite3ApiBootstrap() error:",f),f}},Oe)t=r;else t=new Promise((i,u)=>{be=i,le=u});return t}rs=function(){let e=rs;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 sl=rs;class os{db;txDepth=0;constructor(e){this.db=e}query(e){let t=this.db;return{get(...r){return t.selectObject(e,ns(r))??null},all(...r){return t.selectObjects(e,ns(r))},run(...r){return t.exec({sql:e,bind:ns(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 ns(e){if(e.length===0)return;return e.map((t)=>t===void 0?null:t)}Jo();Wt();Et();Xe();var Te=(e,t,r)=>Number(e)===1?t:r;var Su={刚刚:"just now","{n} 分钟前":({n:e})=>`${e} ${Te(e,"minute","minutes")} ago`,"{n} 小时前":({n:e})=>`${e} ${Te(e,"hour","hours")} ago`,"{n} 天前":({n:e})=>`${e} ${Te(e,"day","days")} ago`,今天:"Today",昨天:"Yesterday",本周:"This week","{n} 天后过期":({n:e})=>`Expires in ${e} ${Te(e,"day","days")}`,"{n} 小时后过期":({n:e})=>`Expires in ${e} ${Te(e,"hour","hours")}`,"{n} 分钟后过期":({n:e})=>`Expires in ${e} ${Te(e,"minute","minutes")}`,"快照 {when}":"Snapshot {when}",还没有活动:"No activity yet","{ago}活跃":"Active {ago}","{day}后无活动":"Inactive since {day}",从未:"Never",无标题:"Untitled",语言:"Language",跟随系统:"System","更改语言后页面会重新加载。":"The page reloads after changing the language.",本地副本未就绪:"Local replica is not ready","请先撤销所有 Edge Room 再断开":"Revoke all Edge Rooms before disconnecting","此设备不驻留在线托管,目前仅支持通过 Edge 发布站点":"This device is not hosted online; sites can only be published through Edge for now","请先连接 Edge":"Connect Edge first","当前 Edge 仅支持 inbox,不支持 Room 托管":"This Edge only supports inbox, not Room hosting","此浏览器通过同步存储桶交换数据、不驻留在线;请在在线主节点管理公开发布":"This browser exchanges data through the sync bucket and is not hosted online; manage public publishing on the online primary node","当前离线,且此浏览器尚未启用本地副本。请先在线打开 Metahub,在设置中开启「离线副本」。":"You are offline and this browser has no local replica yet. Open Metahub online first and enable “Offline replica” in Settings.","离线副本中没有这个页面。":"This page is not in the offline replica.","此资源不是页面,无法离线打开。":"This resource is not a page and cannot be opened offline.","此页面以二进制块存储,无法离线打开。":"This page is stored as a binary blob and cannot be opened offline.","离线加载失败:{msg}":"Offline load failed: {msg}","正在从本地副本加载…":"Loading from the local replica…"};var xu={复制链接:"Copy link",复制内链:"Copy internal link","通过设备分享…":"Share via device…","导出 Markdown":"Export Markdown","导出 CSV":"Export CSV","保存中…":"Saving…",已保存:"Saved",分享:"Share",保存:"Save","保存到同步存储桶失败:{msg}":"Failed to save to the sync bucket: {msg}",保存到同步存储桶:"Save to sync bucket",仍有改动尚未保存到同步存储桶:"Some changes are not yet saved to the sync bucket","保存失败:{msg}":"Save failed: {msg}","按 ID 打开…":"Open by ID…",搜索:"Search",打开设置:"Open settings","折叠 / 展开侧栏":"Collapse / expand sidebar",后退:"Back",前进:"Forward","块 / 代码方式切换":"Toggle blocks / source view",宽屏模式:"Wide mode",版本历史:"Version history","复制 ID":"Copy ID",块方式显示:"Show as blocks",代码方式显示:"Show as source",创建副本:"Duplicate","{title} 副本":"{title} copy","重命名…":"Rename…",重命名文档:"Rename document",删除文档:"Delete document",删除:"Delete",最近动态:"Recent activity",重命名数据库:"Rename database",删除数据库:"Delete database","删除数据库?":"Delete database?","「{name}」及其所有记录将被永久删除。":"“{name}” and all of its records will be permanently deleted.",返回:"Back",展开侧栏:"Expand sidebar",站点配置:"Site settings",配置:"Settings",菜单:"Menu","搜索:“{q}”":"Search: “{q}”",设置:"Settings",站点管理:"Sites",站点:"Sites",发布与分享:"Publish & share",更多:"More","⚡ 离线 — 本地副本模式:可正常查看和编辑全部内容,恢复连接后自动同步":"⚡ Offline — local replica mode: everything stays readable and editable, syncs when the connection returns","⚡ 离线 — 可浏览已缓存的内容,修改会失败;恢复网络后自动恢复":"⚡ Offline — cached content is readable, edits will fail; resumes when the network returns","数据库不存在或已被删除。":"This database does not exist or was deleted.","加载中…":"Loading…",空空如也:"Nothing here yet","从左侧选择一个数据库或文档,或新建一个开始。":"Pick a database or document on the left, or create one to get started.","+ 新建文档":"+ New document",文档:"Documents",记录:"Record","正在从同步存储桶恢复本地副本…":"Restoring the local replica from the sync bucket…",数据表:"Databases",新建文档:"New document",新建数据库:"New database","侧栏:文档":"Sidebar: documents","侧栏:数据表":"Sidebar: databases","侧栏:站点":"Sidebar: sites",移出折叠组:"Unfold",折叠此数据库:"Fold this database",新建子页:"New subpage",移到顶层:"Move to top level",有可用更新:"Update available",收起侧栏:"Collapse sidebar",新建站点:"New site","搜索…":"Search…","已折叠 · {n}":"Folded · {n}",名称:"Name",状态:"Status",待办:"To do",进行中:"In progress",已完成:"Done",优先级:"Priority",高:"High",中:"Medium",低:"Low",截止:"Due",姓名:"Name",公司:"Company",分类:"Category",客户:"Customer",合作:"Partner",潜在:"Lead",邮箱:"Email",空白:"Blank","仅一个「名称」列":"Just a “Name” column",任务:"Tasks","状态·优先级·截止":"Status · Priority · Due",联系人:"Contacts","公司·分类·邮箱":"Company · Category · Email",未命名数据库:"Unnamed database","已创建数据库「{name}」":"Created database “{name}”","创建一个带属性列的结构化数据表。":"Create a structured table with property columns.",取消:"Cancel",创建:"Create","例如:项目、客户、库存…":"e.g. Projects, Customers, Inventory…",图标:"Icon",模板:"Template",导航:"Navigation",新建:"Create",编辑器:"Editor",快速笔记:"Quick Note",命令面板:"Command palette","关闭菜单 / 弹窗":"Close menu / dialog",保存到同步桶:"Save to sync bucket",文内查找:"Find in document",复制当前块:"Duplicate current block",列表缩进:"Indent list item",列表反缩进:"Outdent list item",新建笔记:"New note",上一条笔记:"Previous note",下一条笔记:"Next note",在主窗口中打开:"Open in main window",隐藏小窗:"Hide window",外观:"Appearance",快速小窗:"Quick windows",离线与缓存:"Offline & cache",数据与备份:"Data & backup","设备##page":"Devices",操作审计:"Audit log",站点与发布:"Sites & publishing",快捷键:"Shortcuts",关于:"About",失败:"Failed",重试:"Retry",移除:"Remove","拖动调整宽度,双击复原":"Drag to resize, double-click to reset",确定:"OK",数据库:"Database",未命名记录:"Unnamed record",打开:"Open","输入 ID、前缀或名称":"Enter an ID, prefix or name","搜索页面、输入命令或粘贴 ID":"Search pages, type a command or paste an ID",清空:"Clear","未找到 {ref},可能未同步或已删除":"{ref} not found — it may not be synced yet or was deleted",没有匹配的页面或命令:"No matching pages or commands",暂无可用命令:"No commands available",最近打开:"Recent",命令:"Commands",内容匹配:"Content matches",选择:"Select","可粘贴 ID 或链接":"You can paste an ID or link","文档##kind":"Document","没有找到“{q}”":"Nothing found for “{q}”","换个关键词试试,或用命令面板按标题、ID 直达。":"Try another keyword, or jump by title or ID from the command palette.",打开命令面板:"Open command palette",键盘快捷键:"Keyboard shortcuts","还没有文档,新建一个":"No documents yet — create one","还没有数据表,新建一个":"No databases yet — create one","还没有站点,新建一个":"No sites yet — create one","在全部内容中搜索 “{q}”":"Search all content for “{q}”","已删除「{title}」":"Deleted “{title}”","已删除「{title}」及 {n} 个子页":({title:e,n:t})=>`Deleted “${e}” and ${t} ${Te(t,"subpage","subpages")}`,"撤销##undo":"Undo",已删除笔记:"Note deleted","下载中 · {n}":"Downloading · {n}","正在下载本地副本,已接收 {n} 条变更":"Downloading the local replica, {n} changes received",同步中:"Syncing",正在与服务器同步:"Syncing with the server",已更新:"Updated",已同步:"Synced",同步失败:"Sync failed","上次同步失败:{msg} · 本地读写不受影响,点击查看":"Last sync failed: {msg} · local reads and writes are unaffected, click for details",未知错误:"Unknown error",当前文档:"Current document","标注「仅桌面应用」的组合键被浏览器保留,只在桌面应用里可用。":"Shortcuts marked “Desktop app only” are reserved by the browser and only work in the desktop app.",仅桌面应用:"Desktop app only",正在加载:"Loading",链接已复制:"Link copied","内链已复制,可粘贴到任意文档":"Internal link copied — paste it into any document",已是最新:"Already up to date","已复制 ID":"ID copied",已创建副本:"Copy created"};var ku={没有匹配的页面:"No matching pages",没有匹配的块:"No matching blocks",上一个:"Previous",下一个:"Next","查找:下一个":"Find: next","查找:上一个":"Find: previous",文件:"File",纯文本:"Plain text",文本:"Text",普通段落:"Plain paragraph","标题 1":"Heading 1",大号标题:"Large heading","标题 2":"Heading 2",中号标题:"Medium heading","标题 3":"Heading 3",小号标题:"Small heading",无序列表:"Bulleted list",项目符号:"Bullet points",有序列表:"Numbered list",编号列表:"Numbered items",待办清单:"To-do list",复选项:"Checkboxes",引用:"Quote",引用块:"Quote block",代码:"Code",代码块:"Code block",表格:"Table",插入表格:"Insert a table",分隔线:"Divider",水平分隔:"Horizontal rule",图片:"Image",上传或拖入图片:"Upload or drop an image",视频:"Video",上传视频文件:"Upload a video file",音频:"Audio",上传音频文件:"Upload an audio file",上传任意文件:"Upload any file","嵌入并渲染 HTML":"Embed and render HTML","保存失败:{msg}":"Save failed: {msg}",已合并其他设备的修改:"Merged changes from another device","加载中…":"Loading…","文档已被其他端修改,自动保存已暂停。":"This document was changed elsewhere; autosave is paused.","载入最新(弃本地改动)":"Load latest (discard local changes)",用本地版本覆盖:"Overwrite with local version","已分享 · 管理分享":"Shared · Manage sharing",已分享:"Shared",未知错误:"Unknown error",同步失败:"Sync failed","上次同步 {when}":"Last synced {when}",实时同步:"Live sync",对齐方式:"Alignment",左对齐:"Align left",居中:"Center",右对齐:"Align right",在左侧插入列:"Insert column left",在右侧插入列:"Insert column right",复制列:"Duplicate column",左移列:"Move column left",右移列:"Move column right",删除列:"Delete column",在上方插入行:"Insert row above",在下方插入行:"Insert row below",复制行:"Duplicate row",上移行:"Move row up",下移行:"Move row down",删除行:"Delete row",行选项:"Row options",列选项:"Column options",复制:"Copy",清空:"Clear",新增列:"Add column",新增行:"Add row",表头:"Header","输入代码…":"Type code…",关闭自动换行:"Turn off line wrap","自动换行(所有代码块)":"Line wrap (all code blocks)",换行:"Wrap","格式化代码 (Shift+Alt+F)":"Format code (Shift+Alt+F)","格式化中…":"Formatting…",已格式化:"Formatted",失败:"Failed",格式化:"Format",复制代码:"Copy code",已复制:"Copied","转换为({n} 行)":({n:e})=>`Turn into (${e} ${Te(e,"line","lines")})`,转换为:"Turn into",复制块组:"Duplicate blocks",复制块:"Duplicate block",删除块组:"Delete blocks",删除块:"Delete block",在下方插入:"Insert below","拖动重排 / 点击菜单":"Drag to reorder / click for menu",媒体:"Media",字节未同步到本设备或加载失败:"Not synced to this device or failed to load",重试:"Retry","上传中…":"Uploading…","双击预览 / 标注":"Double-click to preview / annotate",预览:"Preview",下载文件:"Download file",矩形框选:"Rectangle",箭头:"Arrow",文字:"Text","撤销 (⌘Z)":"Undo (⌘Z)","重做 (⇧⌘Z)":"Redo (⇧⌘Z)",取消:"Cancel","保存中…":"Saving…",保存:"Save",关闭:"Close",在文档中查找:"Find in document",无结果:"No results",区分大小写:"Match case",全词匹配:"Whole word",全词:"Word",缩小:"Zoom out",重置:"Reset",放大:"Zoom in","标注 / 编辑":"Annotate / edit",加粗:"Bold",斜体:"Italic",删除线:"Strikethrough",行内代码:"Inline code",链接:"Link",插入链接:"Insert link",链接地址:"URL","{name} 超过 {mb}MB 上限":"{name} exceeds the {mb}MB limit","上传失败:{msg}":"Upload failed: {msg}","已选 {n} 字":"{n} words selected","{n} 字符":"{n} chars","{n} 字":"{n} words","约 {n} 分钟阅读":"~{n} min read","JSON 解析失败:{msg}":"JSON parse failed: {msg}","格式化组件加载失败(离线?):{msg}":"Formatter failed to load (offline?): {msg}",文档不存在或未同步:"Document does not exist or is not synced","⏳ 正在上传 {name}…":"⏳ Uploading {name}…",文档目录:"Table of contents",列1:"Column 1",列2:"Column 2",基础块:"Basic blocks",链接到:"Link to",'输入文本,"/" 唤出命令':'Type text, "/" for commands',"HTML 预览":"HTML preview",编辑源码:"Edit source",源码:"Source"};var Tu={上一条:"Previous",下一条:"Next",复制失败:"Copy failed","{n} 列已隐藏":({n:e})=>`${e} ${Te(e,"column","columns")} hidden`,"{n} 项":({n:e})=>`${e} ${Te(e,"item","items")}`,"{name} 副本":"{name} copy","「{name}」的筛选、排序和隐藏列设置将一并删除,记录不受影响。":"The filters, sorts and hidden columns of “{name}” will be deleted. Records are not affected.",按属性筛选:"Filter by property",包含:"contains",包含全部:"contains all of",包含任一:"contains any of",本月:"This month",标题列始终显示:"The title column is always shown",不包含:"does not contain",不等于:"is not",不是:"is not",不晚于:"is on or before",不为空:"is not empty",不早于:"is on or after",等于:"is","调整或清除筛选条件后会再次显示记录。":"Adjust or clear the filters to see records again.",都不包含:"contains none of",非空:"Filled",复制视图:"Duplicate view","改为「{type}」会清空这一列的 {n} 个单元格,可在版本历史中回滚。":({type:e,n:t})=>`Changing to “${e}” clears ${t} ${Te(t,"cell","cells")} in this column. You can roll back from version history.`,"更改属性类型?":"Change property type?",关闭搜索:"Close search","过去 30 天":"Past 30 days","过去 7 天":"Past 7 days",还没有选项:"No options yet","还有 {n} 个隐藏的属性":({n:e})=>`${e} more hidden ${Te(e,"property","properties")}`,"换个关键词,或清除筛选条件。":"Try another keyword, or clear the filters.",换行文本:"Wrap text",计数:"Count",计算:"Calculate",满足全部:"Match all",满足任一:"Match any",没有符合条件的记录:"No records match",没有匹配的属性:"No matching properties",平均:"Average",求和:"Sum",全部显示:"Show all",筛选:"Filter",筛选此列:"Filter by this column",删除视图:"Delete view","删除视图?":"Delete view?",是:"is",收起隐藏的属性:"Hide hidden properties",属性:"Properties",数值:"Number",搜索属性:"Search properties",添加排序:"Add sort",晚于:"is after",唯一值:"Unique",为空:"is empty",未勾选:"Unchecked","未来 30 天":"Next 30 days","未来 7 天":"Next 7 days",未选择:"None selected",无:"None","显示 {m} / {n} 条记录":"Showing {m} of {n} records",显示:"Show","新建视图 · 选择布局":"New view · Choose a layout",新建视图:"New view","选择…":"Choose…",移除排序:"Remove sort",移除筛选:"Remove filter",已勾选:"Checked",隐藏:"Hide",隐藏全部:"Hide all",右侧插入列:"Insert column right",在表中搜索:"Search in table","在表中搜索…":"Search in table…",在范围内:"is within",早于:"is before",中位数:"Median",重命名视图:"Rename view",最大:"Max",最小:"Min",左侧插入列:"Insert column left",已撤销:"Undone",已重做:"Redone","{n} 个单元格因类型不匹配未写入":({n:e})=>`${e} ${Te(e,"cell","cells")} skipped: value doesn't fit the column type`,设置属性:"Set property","设置属性…":"Set property…",勾选:"Check",取消勾选:"Uncheck",应用:"Apply",编辑单元格:"Edit cell",选中整行:"Select row",选中全部单元格:"Select all cells",复制单元格:"Copy cells",粘贴到单元格:"Paste into cells",清空单元格:"Clear cells",撤销单元格修改:"Undo cell edit",重做:"Redo",清除:"Clear","↑↓ 换日 · ↵ 选定":"↑↓ day · ↵ pick","看板视图需要一个「单选」或「多选」属性来分组。请在表格视图中添加一个单选列后再切换到看板。":"The board needs a select or multi-select property to group by. Add one in the table view, then switch back.",按属性分组:"Group by property","分组:{name}":"Group: {name}",多选分组不支持拖拽改值:"Dragging can't reassign a multi-select group",未分组:"Ungrouped",看板:"Board",日历:"Calendar",时间轴:"Timeline",在浮窗中打开这个数据库的看板:"Open this database's board in a floating window",记录不存在或已被删除:"Record does not exist or has been deleted",移动属性:"Move property",排序:"Sort",清除排序后可拖拽移动:"Clear the sort to drag rows",拖拽移动:"Drag to move",新建属性:"New property",新建记录:"New record","共 {n} 条记录":({n:e})=>`${e} ${Te(e,"record","records")}`,"{n} 已选":"{n} selected","删除记录?":"Delete record?","确定删除选中的 {n} 条记录?":({n:e})=>`Delete the ${e} selected ${Te(e,"record","records")}?`,"已删除 {n} 条记录":({n:e})=>`Deleted ${e} ${Te(e,"record","records")}`,"{n} 个单元格":({n:e})=>`${e} ${Te(e,"cell","cells")}`,填充:"Fill",移动记录:"Move record","创建选项失败:{msg}":"Failed to create option: {msg}",搜索或创建选项:"Search or create an option","创建记录失败:{msg}":"Failed to create record: {msg}",搜索或创建记录:"Search or create a record",该属性未设置关联目标:"This property has no relation target",无法加载目标数据表:"Could not load the target database",目标数据表暂无记录:"The target database has no records yet","还有 {n} 条,继续输入过滤":({n:e})=>`${e} more ${Te(e,"match","matches")}, keep typing to filter`,"创建文档失败:{msg}":"Failed to create document: {msg}",搜索或创建文档:"Search or create a document","暂无文档,输入标题创建":"No documents yet; type a title to create one","更新属性失败:{msg}":"Failed to update property: {msg}","选项 1":"Option 1","选项 2":"Option 2",已存在同名选项:"An option with that name already exists","重命名选项失败:{msg}":"Failed to rename option: {msg}",至少保留一个选项:"Keep at least one option","删除选项?":"Delete option?","「{name}」将从所有使用它的记录中清除。":"“{name}” will be cleared from every record that uses it.","删除选项失败:{msg}":"Failed to delete option: {msg}",属性类型:"Property type",选项:"Options",确认:"Confirm",重命名选项:"Rename option",删除选项:"Delete option",添加选项:"Add option",关联目标:"Relation target",选择关联的数据表:"Choose the related database","新建属性失败:{msg}":"Failed to create property: {msg}",删除属性:"Delete property","删除属性?":"Delete property?","「{name}」及其所有单元格数据将被移除。":"“{name}” and all of its cell data will be removed.",搜索数据表:"Search databases",没有匹配的数据表:"No matching databases",还没有数据库:"No databases yet",没有匹配的记录:"No matching records",没有匹配的文档:"No matching documents",没有匹配的选项:"No matching options","还没有选项,输入名称创建":"No options yet — type a name to create one",升序:"Ascending",还没有记录:"No records yet","新建一条记录,或从 CLI 导入。":"Create a record, or import from the CLI.","没有符合筛选的动态。":"No activity matches the filters.",降序:"Descending",当前表:"Current table","新建属性 · 选择类型":"New property · Choose a type",排序依据:"Sort by",清除排序:"Clear sort",打开记录:"Open record",复制记录:"Duplicate record",删除记录:"Delete record",返回字段:"Back to fields",字段修改历史:"Field history",在主视图打开:"Open in main view",修复:"Repair",回滚:"Rollback",本设备:"This device","(空)":"(empty)","{n} 块修改":({n:e})=>`${e} ${Te(e,"block","blocks")} changed`,"{n} 块删除":({n:e})=>`${e} ${Te(e,"block","blocks")} deleted`,元数据:"Metadata",变更:"Changes",源码:"Source","展开 {n} 个未变更块":({n:e})=>`Show ${e} unchanged ${Te(e,"block","blocks")}`,"展开 {n} 行未变更内容":({n:e})=>`Show ${e} unchanged ${Te(e,"line","lines")}`,"恢复到此版本?":"Restore this version?","标题和正文将恢复到 {when} 的状态。此操作会作为一次新修订记录,任何版本都仍可从历史找回。":"The title and body will be restored to their state at {when}. This is recorded as a new revision; every version stays recoverable from history.",恢复:"Restore",已恢复:"Restored","文档刚被其他端修改,已刷新,请重试":"The document was just changed elsewhere and has been refreshed; please try again",当前:"Current",取消对比基准:"Unpin comparison base","设为对比基准(Shift+点击)":"Pin as comparison base (Shift+click)","{n} 次连续小修改":({n:e})=>`${e} consecutive small ${Te(e,"edit","edits")}`,显示修复:"Show repairs","对比基准:{when}":"Comparing against: {when}",清除基准:"Clear base",此修订删除了文档:"This revision deleted the document",初始版本:"Initial version","更早的修订已被存储压缩合并,此处按整篇新增显示":"Earlier revisions were compacted in storage, so this one shows as a whole-document addition","两个版本相同。":"The two versions are identical.","(空文档)":"(empty document)","此修订未改动正文。":"This revision did not change the body.",恢复到此版本:"Restore this version","「{name}」字段历史":"History of “{name}”","该单元格的每一次写入,最新在前。":"Every write to this cell, newest first.","暂无写入记录。":"No writes yet.","(清空)":"(cleared)",已删除:"Deleted",调整排序:"Reordered",全部记录:"All records",全部设备:"All devices",清除筛选:"Clear filters","暂无动态。":"No activity yet.",只看这条记录:"Only this record","(已删字段)":"(deleted field)","…还有 {n} 项":({n:e})=>`…${e} more ${Te(e,"item","items")}`,"记录字段将恢复到该修订时的值。此操作会作为一次新修订记录。":"The record's fields will be restored to their values at that revision. This is recorded as a new revision.",修改历史:"Edit history","暂无历史。":"No history yet.",查看此字段完整历史:"View this field's full history",字段:"Field",站点渠道:"Site channel",站点文件:"Site file",文档块:"Document block",附件策略:"Attachment policy","修改##audit":"Edited",段落:"Paragraph",撤销这组改动:"Undo this change set","会以一次新的正向修改还原到改动前的状态,本身也会记入审计,可以再撤销。之后被其他编辑覆盖过的字段会保留,不会被回退。":"Restores the pre-change state as a new forward edit, which is itself audited and can be undone. Fields overwritten by later edits are kept, not rolled back.",撤销改动:"Undo changes","已恢复 {n} 项,保留了 {kept} 项更晚的编辑":({n:e,kept:t})=>`Restored ${e} ${Te(e,"item","items")}, kept ${t} later ${Te(t,"edit","edits")}`,"已恢复 {n} 项":({n:e})=>`Restored ${e} ${Te(e,"item","items")}`,"无需恢复:已是改动前的状态":"Nothing to restore: already in the pre-change state",全部:"All","AI 操作":"AI actions",这台设备:"This device",其他设备:"Other devices","工作区里每一次改动:谁、什么时候、改了什么。AI 通过命令行做的操作会标出来,可以逐条检查并撤销。":"Every change in the workspace: who, when, and what. Actions the AI made through the command line are marked so you can review and undo them one by one.","还没有 AI 操作的记录。":"No AI actions recorded yet.","暂无改动记录。":"No changes recorded yet.",以一次新的正向修改撤销这组改动:"Undo this change set with a new forward edit","撤销##audit":"Undo","早期版本的改动,仅可查看摘要。":"Change from an earlier version; only the summary is available.",",":", ",显示更早的记录:"Show earlier changes","已显示全部 · 只保留最近 90 天,更早的改动已合并且无法撤销":"That's everything · Only the last 90 days are kept; earlier changes were merged and cannot be undone","日历视图需要一个「日期」属性。请在表格视图中添加一个日期列后再切换到日历。":"The calendar view needs a Date property. Add a date column in the table view, then switch to the calendar.",按日期属性:"By date property",上个月:"Previous month",下个月:"Next month","{date} · {n} 条记录":({date:e,n:t})=>`${e} · ${t} ${Te(t,"record","records")}`,"+{n} 更多":"+{n} more","时间轴视图需要一个「日期」属性作为开始日期。请在表格视图中添加一个日期列后再切换到时间轴。":"The timeline view needs a Date property as the start date. Add a date column in the table view, then switch to the timeline.",开始日期:"Start date","结束日期(可选)":"End date (optional)","无(里程碑)":"None (milestone)","(里程碑)":"(milestone)",点击空白处排期:"Click an empty spot to schedule","未排期 · 排到今天":"Unscheduled · Schedule for today",数字:"Number",单选:"Select",多选:"Multi-select",复选框:"Checkbox",日期:"Date",关联:"Relation"};var Ru={"Logo 底色":"Logo background","浅底 Logo":"Light logo","深底 Logo":"Dark logo","Logo 配色":"Logo colors","彩色(默认)":"Color (default)","蓝色单色":"Monochrome blue","应用内标识与浏览器图标即时切换,选择保存在当前设备。安装图标使用默认彩色版。":"App logos and the browser icon update instantly. Your choice is saved on this device. Installed icons use the default color version.",浅色:"Light",始终使用明亮界面:"Always use the light interface",深色:"Dark",始终使用暗色界面:"Always use the dark interface",随操作系统外观自动切换:"Follow the operating system appearance","重命名失败:{msg}":"Rename failed: {msg}",此设备:"This device",重命名本机:"Rename this device",工作区:"Workspace",颜色主题:"Color theme",字数统计:"Word count","在文档右下角显示字数,悬停查看字符数与预计阅读时间。":"Show the word count in the bottom-right corner of a document; hover for characters and estimated reading time.",入口验证成功并已保存:"Entry point verified and saved",已清除设备托管入口:"Device hosting entry point cleared","已连接 Edge;{notes}":"Connected to Edge; {notes}","已连接 Edge":"Connected to Edge","断开 Edge?":"Disconnect Edge?","只移除本机连接,不会删除 Cloudflare Worker 或 D1。存在活动 Room 时会拒绝断开。":"Only removes this device's connection; the Cloudflare Worker and D1 are kept. Disconnecting is refused while Rooms are active.",断开:"Disconnect","已断开 Edge":"Disconnected from Edge",不可达:"Unreachable",需升级:"Upgrade needed",设备托管入口:"Device hosting entry point",公网入口地址:"Public entry URL","已验证 · {scope}":"Verified · {scope}","公网 HTTPS":"Public HTTPS",局域网:"LAN",仅本机:"Local only","填写已由反向代理、隧道或公网 IP 转发到本节点的地址;保存时会访问 /health 并核对节点身份。":"Enter the address a reverse proxy, tunnel or public IP forwards to this node; saving fetches /health and checks the node identity.","验证中…":"Verifying…",验证并保存:"Verify and save","Desktop 内置 sidecar 只监听本机且关闭鉴权,不能直接暴露到公网。需要设备托管时请另行启动带鉴权的":"The desktop's built-in sidecar listens on localhost only with authentication off and cannot be exposed to the internet. For device hosting, run an authenticated",",或使用下方 Edge。":" separately, or use Edge below.","Edge 始终在线托管":"Edge always-on hosting","此设备把数据存放在云端存储桶、不常驻在线,站点需由 Edge 托管。你的设备离线期间,Edge 继续提供最后一次同步的版本。":"This device keeps its data in a cloud bucket and is not always online, so sites must be hosted by Edge. While your device is offline, Edge keeps serving the last synced version.","Edge Room 不依赖设备在线。可一键部署到你的 Cloudflare 账户,或连接已有兼容端点。":"Edge Rooms do not depend on your device being online. Deploy to your Cloudflare account in one click, or connect an existing compatible endpoint.",端点:"Endpoint","升级部署…":"Upgrade deployment…","{status} · 版本 {version} / {expected} · 活动 Room {rooms} · {note}":"{status} · version {version} / {expected} · active Rooms {rooms} · {note}",未知:"unknown","暂无 Room":"No Rooms yet","Room 同步存在异常":"Room sync has errors","Room 最近同步 {ago}":"Rooms last synced {ago}",等待首次同步:"Waiting for the first sync","部署到 Cloudflare":"Deploy to Cloudflare","在你自己的账户创建 Worker + D1(可顺带创建 R2 同步桶),断开时不会自动删除。":"Creates a Worker + D1 in your own account (optionally an R2 sync bucket too); nothing is deleted automatically when you disconnect.","一键部署…":"Deploy…","连接已有 Edge":"Connect an existing Edge","任意兼容 /v1/inbox 协议的端点。":"Any endpoint compatible with the /v1/inbox protocol.","断开 Edge":"Disconnect Edge","只移除本机连接,不会删除 Cloudflare Worker 或 D1;存在活动 Room 时会拒绝断开。":"Only removes this device's connection; the Cloudflare Worker and D1 are kept. Disconnecting is refused while Rooms are active.","已开始在此浏览器保存完整副本,正在下载数据…":"Started keeping a full replica in this browser; downloading data…","停止使用此同步存储桶?":"Stop using this sync bucket?",切回在线模式:"Switch back to online mode","此页面没有在线主节点可回退。停止后会返回「连接同步存储桶」;已下载的数据仍保留在此浏览器里,重新连接后可从断点继续。若要同时删除本地数据,请使用下方「删除此浏览器的副本」。":"This page has no online primary node to fall back to. Stopping returns you to “Connect a sync bucket”; downloaded data stays in this browser and resumes where it left off when you reconnect. To also delete the local data, use “Delete this browser's replica” below.","此浏览器将恢复纯在线模式。已下载的本地数据保留在此浏览器里,重新启用后从断点续传。":"This browser returns to online-only mode. Downloaded local data stays in this browser and resumes where it left off when re-enabled.",停止使用:"Stop using","已停止,请重新连接同步存储桶":"Stopped; reconnect a sync bucket",已切回在线模式:"Switched back to online mode",删除此浏览器的副本:"Delete this browser's replica","将删除此浏览器的副本并返回「连接同步存储桶」。\n① 已同步到存储桶的内容不会丢;\n② 尚未同步的本地编辑会丢失;\n③ 尚未上传的本地附件会丢失;\n④ 建议先确认上方显示“当前版本已确认”。":`Deletes this browser's replica and returns to “Connect a sync bucket”.
532
+ `)}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=fc(await ym(this.body||""))}return e}}async function So(e,t){let r=await crypto.subtle.importKey("raw",typeof e==="string"?pc.encode(e):e,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return crypto.subtle.sign("HMAC",r,pc.encode(t))}async function ym(e){return crypto.subtle.digest("SHA-256",typeof e==="string"?pc.encode(e):e)}function fc(e){let t=new Uint8Array(e),r="";for(let n=0;n<t.length;n++){let o=t[n];r+=bm[o>>>4&15],r+=bm[o&15]}return r}function wm(e){return e.replace(/[!'()*]/g,(t)=>"%"+t.charCodeAt(0).toString(16).toUpperCase())}function oS(e,t){let{hostname:r,pathname:n}=e;if(r.endsWith(".on.aws")){let c=r.match(/^[^.]{1,63}\.lambda-url\.([^.]{1,63})\.on\.aws$/);return c!=null?["lambda",c[1]||""]:["",""]}if(r.endsWith(".r2.cloudflarestorage.com"))return["s3","auto"];if(r.endsWith(".backblazeb2.com")){let c=r.match(/^(?:[^.]{1,63}\.)?s3\.([^.]{1,63})\.backblazeb2\.com$/);return c!=null?["s3",c[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 c=(t.get("X-Amz-Target")||"").split(".")[0];if(c==="AnyScaleFrontendService")s="application-autoscaling";else if(c==="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[rS[s]||s,a||""]}var pc,rS,nS,bm;var Em=Ae(()=>{pc=new TextEncoder,rS={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"},nS=new Set(["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"]);bm=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"]});function gc(e){return new hc({accessKeyId:e.accessKeyId,secretAccessKey:e.secretAccessKey,region:e.region||"auto",service:"s3"})}function mc(e){let t=new URL(e.endpoint).origin;return eg(e)?t:`${t}/${e.bucket}`}function _c(e,t){return`${mc(e)}/${t.split("/").map(encodeURIComponent).join("/")}`}async function ko(e,t,r){let n=gc(e),o=new URL(_c(e,t));return o.searchParams.set("X-Amz-Expires",String(Math.min(Math.max(1,Math.floor(r)),Cn))),(await n.sign(o.toString(),{method:"GET",aws:{signQuery:!0}})).url}var Cn=604800;var Ui=Ae(()=>{Em();Xr()});function HS(e,t){let r=e.query("SELECT value FROM meta WHERE key = ?").get(t);return r?r.value:null}function Dc(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=HS(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,Dc(e,"edge_config",JSON.stringify(r));if(!Array.isArray(r.capabilities))r.capabilities=r.cf?["inbox","room"]:["inbox"],Dc(e,"edge_config",JSON.stringify(r));return r}catch{return null}}function Oc(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;Dc(e,"edge_config",r?JSON.stringify(r):null)}function xo(e){return e.capabilities??(e.cf?["inbox","room"]:["inbox"])}var Or="3";async function a_(e){return Vr(new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(e))))}async function c_(e){let t=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return Vr(new Uint8Array(t).slice(0,16))}function l_(e){try{let t=new URL(e);if(t.protocol!=="https:"||t.username||t.password||t.hash||e.length>8192)return null;let r=t.searchParams.get("X-Amz-Date")??"",n=Number(t.searchParams.get("X-Amz-Expires"));if(!/^\d{8}T\d{6}Z$/.test(r)||!Number.isInteger(n)||n<1||n>604800)return null;if(!/^[a-f0-9]{64}$/i.test(t.searchParams.get("X-Amz-Signature")??""))return null;let o=`${r.slice(0,4)}-${r.slice(4,6)}-${r.slice(6,8)}T${r.slice(9,11)}:${r.slice(11,13)}:${r.slice(13,15)}Z`,s=Date.parse(o);return Number.isFinite(s)?s+n*1000:null}catch{return null}}function u_(e,t){return`${e.replace(/\/+$/,"")}/#m=${encodeURIComponent(t.manifestUrl)}&${t.keyB64?`k=${t.keyB64}`:`s=${t.saltB64}`}`}var d_=Ae(()=>{Jr()});function KS(e,t){return`${e.prefix.replace(/^\/+|\/+$/g,"")?`${e.prefix.replace(/^\/+|\/+$/g,"")}/`:""}shares/${t}/links/`}function p_(e){let t=new URL(e);if(t.protocol!=="https:"||t.username||t.password||t.search||t.hash)throw Error("invalid viewer");if(t.pathname!=="/")throw Error("static subpath viewer");return t.origin}async function f_(e,t){let r=e.encrypt&&e.masterKey?await yr(wt(e.masterKey),t):t,n=JSON.parse(new TextDecoder().decode(r));if(n.v!==1||!/^[A-Za-z0-9_-]{43}$/.test(n.token)||p_(n.base)!==n.base)throw Error("invalid short-link control");return n}async function GS(e,t,r){let n=Mt(e),o=`${KS(e,t)}${await a_(r)}.json`,s=await n.get(o);if(s){let m=await f_(e,s);if(m.base!==r)throw Error("viewer mismatch");return m}let a={v:1,base:r,token:Vr(po())},c=new TextEncoder().encode(JSON.stringify(a)),p=e.encrypt&&e.masterKey?await nr(wt(e.masterKey),c):c;try{await n.put(o,p,{ifNoneMatch:!0,contentType:"application/octet-stream"})}catch(m){let x=await n.get(o);if(!x)throw m;let A=await f_(e,x);if(A.base!==r)throw Error("viewer mismatch");return A}return a}function Ic(e,t={}){return fetch(e,{...t,redirect:"error",credentials:"omit",cache:"no-store",signal:AbortSignal.timeout(ZS)})}async function h_(e,t,r,n){let o=u_(r,n);try{let s=p_(r),a=Math.min(n.presignExp,l_(n.manifestUrl)??0);if(a<=Date.now())return o;let c=await Ic(`${s}/api/links`);if(!c.ok||(await c.json()).service!=="metahub-share-links")throw Error("static viewer");let p=await GS(e,t,s),m=await c_(p.token),x=`${s}/api/links/${m}`,A=`Bearer ${p.token}`,F={v:1,manifestUrl:n.manifestUrl,expiresAt:a,...n.saltB64?{salt:Vr(wt(n.saltB64))}:{}},X=await Ic(x,{headers:{authorization:A}});if(!X.ok&&X.status!==404)throw Error("short-link lookup failed");let he=X.headers.get("etag");if(X.ok&&!he)throw Error("not a short-link API");let _e=await Ic(x,{method:"PUT",headers:{authorization:A,"content-type":"application/json",...X.ok?{"if-match":he}:{"if-none-match":"*"}},body:JSON.stringify(F)});if(!_e.ok||!_e.headers.get("etag")||(await _e.json()).ok!==!0)throw Error("short-link registration failed");return`${s}/s/${m}${n.keyB64?`#k=${Vr(wt(n.keyB64))}`:""}`}catch{return console.warn("share: short-link service unavailable; using the original long link"),o}}var ZS=8000;var Cc=Ae(()=>{Jr();Xr();d_()});function To(e){let t=(e||"").replace(/^\/+|\/+$/g,"");return t?`${t}/shares`:"shares"}function g_(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 y_(e,t){let r=new TextEncoder().encode(JSON.stringify(t));return e.encrypt&&e.masterKey?nr(wt(e.masterKey),r):Promise.resolve(r)}async function Nc(e,t){let n=await Mt(e).get(Pc(To(e.prefix),t)).catch(()=>null);if(!n)return null;try{let o=e.encrypt&&e.masterKey?await yr(wt(e.masterKey),n):n;return JSON.parse(new TextDecoder().decode(o))}catch{return null}}async function VS(e,t){let r=Mt(t.config),n=To(t.config.prefix),o={v:1,kind:t.kind,title:""},s=[];if(t.kind==="doc"){let m=ot(e,t.targetId);if(!m)throw new H("not_found",`no such document: ${t.targetId}`);o.title=m.title,o.body=m.body??"",s=g_(o.body)}else{let m=Ot(e,t.targetId);if(!m)throw new H("not_found",`no such database: ${t.targetId}`);o.title=m.name;let x=Lt(e,t.targetId).sort((F,X)=>F.position-X.position);o.properties=x.map((F)=>({id:F.id,name:F.name,type:F.type}));let A=_n(e,t.targetId);o.records=A.map((F)=>({cells:F.cells})),s=g_(JSON.stringify(A.map((F)=>F.cells)))}let a=[],c={};if(s.length>0&&!bu())throw new H("network","no blob-bytes resolver is registered for this runtime");for(let m of s){let x=await yu(e,m);if(!x)continue;let A=__(n,t.slug,m);await r.put(A,await nr(t.shareKey,x),{contentType:"application/octet-stream"}),a.push(A),c[m]={url:await ko(t.config,A,t.expiresSec),ct:Su(e,m)??"application/octet-stream"}}if(Object.keys(c).length)o.blobs=c;let p=m_(n,t.slug);return await r.put(p,await nr(t.shareKey,new TextEncoder().encode(JSON.stringify(o))),{contentType:"application/octet-stream"}),a.push(p),{manifestUrl:await ko(t.config,p,t.expiresSec),objects:a,title:o.title}}async function b_(e,t,r,n=Cn){let o=await Nc(t,r);if(!o)throw new H("not_found",`no such bucket share: ${r}`);if(o.revoking)throw new H("conflict","share revocation is pending; retry revocation instead");let s=wt(o.key),a=v_(n),{manifestUrl:c,objects:p,title:m}=await VS(e,{slug:r,kind:o.kind,targetId:o.target_id,config:t,shareKey:s,expiresSec:a}),x=Date.now()+a*1000,A={...o,title:m,presign_exp:x,objects:p,content_updated_at:Date.now()};return await Mt(t).put(Pc(To(t.prefix),r),await y_(t,A),{contentType:"application/octet-stream"}),{manifestUrl:c,presignExp:x,keyB64:o.has_password?void 0:o.key,saltB64:o.salt,title:m}}async function JS(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 w_(e,t,r=Cn){let n=await Nc(e,t);if(!n)throw new H("not_found",`no such bucket share: ${t}`);if(n.revoking)throw new H("conflict","share revocation is pending; retry revocation instead");let o=Mt(e),s=To(e.prefix),a=wt(n.key),c=v_(r),p=m_(s,t),m=await o.get(p).catch(()=>null);if(!m)throw new H("not_found",`bucket share ${t} has no manifest`);let x=JSON.parse(new TextDecoder().decode(await yr(a,m))),A=await JS(x,(X)=>ko(e,__(s,t,X),c));await o.put(p,await nr(a,new TextEncoder().encode(JSON.stringify(A))),{contentType:"application/octet-stream"});let F=Date.now()+c*1000;return await o.put(Pc(s,t),await y_(e,{...n,presign_exp:F}),{contentType:"application/octet-stream"}),{manifestUrl:await ko(e,p,c),presignExp:F,keyB64:n.has_password?void 0:n.key,saltB64:n.salt,title:n.title}}async function qc(e){let t=Mt(e),r=To(e.prefix),o=(await t.list(`${r}/`,void 0,"/")).map((a)=>a.key.slice(`${r}/`.length).replace(/\/$/,"")).filter((a)=>a&&!a.includes("/")),s=[];for(let a of o){let c=await Nc(e,a);if(c)s.push(c)}return s}function v_(e){return Math.min(Math.max(60,Math.floor(e)),Cn)}var Pc=(e,t)=>`${e}/${t}/meta.json`,m_=(e,t)=>`${e}/${t}/manifest.bin`,__=(e,t,r)=>`${e}/${t}/blobs/${r}`;var Lc=Ae(()=>{Xe();vn();zr();kr();Ur();Xn();Xr();Ui();Cc();Jr()});function XS(e){return Ft(e).flatMap((t)=>{if(t.kind==="s3"&&t.config)return[{url:t.url,kind:"bucket",peer:t}];if(t.kind==="http"&&t.token)return[{url:t.url,kind:"peer",peer:t}];return[]})}function QS(e){let t=$c.get(e);if(!t)t=new Map,$c.set(e,t);return t}function YS(e,t){let r=QS(e),n=r.get(t);if(!n)n={items:[],fetchedAt:0,error:null,inflight:null},r.set(t,n);return n}function E_(e,t,r){let n=YS(e,t);n.items=[...n.items.filter((o)=>o.slug!==r.slug),r]}function S_(e,t){let r=$c.get(e);if(!r)return null;for(let n of XS(e)){if(n.kind!=="bucket")continue;let o=r.get(n.url)?.items.find((s)=>s.slug===t);if(o)return{source:n,item:o}}return null}var $c;var k_=Ae(()=>{An();Lc();$c=new WeakMap});function tk(e,t){if(t)return t.replace(/\/+$/,"");return(e.query("SELECT value FROM meta WHERE key='cfg_share_viewer_url'").get()?.value||ek).replace(/\/+$/,"")}async function rk(e,t){let r=S_(e,t);if(r)return{peer:r.source.peer,kind:r.item.kind,item:r.item};for(let n of Ft(e).filter((o)=>o.kind==="s3"&&o.config)){let s=(await qc(JSON.parse(n.config)).catch(()=>[])).find((a)=>a.slug===t);if(s)return{peer:n,kind:s.kind,item:null}}return null}async function x_(e,t,r,n){let o=await rk(e,t);if(!o)throw new H("not_found",`no such object-storage share: ${t}`);let{peer:s}=o,a=JSON.parse(s.config),c=tk(e,r),p=n?.refreshContent?await b_(e,a,t):await w_(a,t);if(o.item)E_(e,s.url,{...o.item,title:p.title||o.item.title,expiresAt:p.presignExp,...n?.refreshContent?{contentUpdatedAt:Date.now()}:{}});return{slug:t,kind:o.kind,permission:"view",transport:"s3",hosting:"s3",url:await h_(a,t,c,p),expiresAt:p.presignExp,source:`桶 ${s.label??s.url}`}}var ek="https://share.mh.tensorix.org",pP;var T_=Ae(()=>{Da();Xe();St();Zo();Dn();vn();zr();An();Rn();Lc();Ui();Cc();k_();Eo();pP=Gr({slug:dt().min(1).max(128),kind:Si(["doc","database","site"]),permission:Si(["view","edit"]),transport:yv("server"),hosting:Si(["server","room"]),url:dt().url(),expiresAt:uo().nullable(),source:dt()})});globalThis.sqlite3Worker1Promiser=function e(t=e.defaultConfig){if(arguments.length===1&&typeof arguments[0]==="function"){let A=t;t=Object.assign(Object.create(null),e.defaultConfig),t.onready=A}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),c=t.generateMessageId||function(A){return A.type+"#"+(a[A.type]=(a[A.type]||0)+1)},p=(...A)=>{throw Error(A.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(A){A=A.data,s("worker1.onmessage",A);let F=r[A.messageId];if(!F){if(A&&A.type==="sqlite3-api"&&A.result==="worker1-ready"){if(t.onready)t.onready(x);return}if(F=r[A.type],F&&F.onrow){F.onrow(A);return}if(t.onunhandled)t.onunhandled(arguments[0]);else o("sqlite3Worker1Promiser() unhandled worker message:",A);return}switch(delete r[A.messageId],A.type){case"error":F.reject(A);return;case"open":if(!m)m=A.dbId;break;case"close":if(A.dbId===m)m=void 0;break;default:break}try{F.resolve(A)}catch(X){F.reject(X)}},x=function(){let A;if(arguments.length===1)A=arguments[0];else if(arguments.length===2)A=Object.create(null),A.type=arguments[0],A.args=arguments[1],A.dbId=A.args.dbId;else p("Invalid arguments for sqlite3Worker1Promiser()-created factory.");if(!A.dbId&&A.type!=="open")A.dbId=m;A.messageId=c(A),A.departureTime=performance.now();let F=Object.create(null);F.message=A;let X;if(A.type==="exec"&&A.args){if(typeof A.args.callback==="function")X=A.messageId+":row",F.onrow=A.args.callback,A.args.callback=X,r[X]=F;else if(typeof A.args.callback==="string")p("exec callback may not be a string when using the Promise interface.")}let he=new Promise(function(_e,le){F.resolve=_e,F.reject=le,r[A.messageId]=F,s("Posting",A.type,"message to Worker dbId="+(m||"default")+":",A),t.worker.postMessage(A)});if(X)he=he.finally(()=>delete r[X]);return he}};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 wk=sqlite3Worker1Promiser.v2;delete globalThis.sqlite3Worker1Promiser;async function os(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,c="";function p(i){if(r.locateFile)return r.locateFile(i,c);return c+i}var m,x;if(n||o){try{c=new URL(".",a).href}catch{}if(o)x=(i)=>{var u=new XMLHttpRequest;return u.open("GET",i,!1),u.responseType="arraybuffer",u.send(null),new Uint8Array(u.response)};m=async(i)=>{var u=await fetch(i,{credentials:"same-origin"});if(u.ok)return u.arrayBuffer();throw Error(u.status+" : "+u.url)}}var A=console.log.bind(console),F=console.error.bind(console),X,he=!1,_e,le,Oe=!1;function Be(){var i=pr.buffer;Ht=new Int8Array(i),$n=new Int16Array(i),Cr=new Uint8Array(i),j_=new Uint16Array(i),Ye=new Int32Array(i),rt=new Uint32Array(i),U_=new Float32Array(i),B_=new Float64Array(i),At=new BigInt64Array(i),H_=new BigUint64Array(i)}function Me(){if(r.wasmMemory)pr=r.wasmMemory;else{var i=r.INITIAL_MEMORY||8388608;pr=new WebAssembly.Memory({initial:i/65536,maximum:32768})}Be()}function He(){if(r.preRun){if(typeof r.preRun=="function")r.preRun=[r.preRun];while(r.preRun.length)Z_(r.preRun.shift())}Bc(Hc)}function Ze(){if(Oe=!0,!r.noFSInit&&!y.initialized)y.init();vr.init(),ln.__wasm_call_ctors(),y.ignorePermissions=!1}function zt(){if(r.postRun){if(typeof r.postRun=="function")r.postRun=[r.postRun];while(r.postRun.length)W_(r.postRun.shift())}Bc(jc)}function Rt(i){r.onAbort?.(i),i=`Aborted(${i})`,F(i),he=!0,i+=". Build with -sASSERTIONS for more info.";var u=new WebAssembly.RuntimeError(i);throw le?.(u),u}var Ln;function N_(){if(r.locateFile)return p("sqlite3.wasm");return new URL("sqlite3.wasm",import.meta.url).href}function q_(i){if(i==Ln&&X)return new Uint8Array(X);if(x)return x(i);throw"both async and sync fetching of the wasm failed"}async function L_(i){if(!X)try{var u=await m(i);return new Uint8Array(u)}catch{}return q_(i)}async function $_(i,u){try{var _=await L_(i);return await WebAssembly.instantiate(_,u)}catch(f){F(`failed to asynchronously prepare wasm: ${f}`),Rt(f)}}async function M_(i,u,_){if(!i)try{var f=fetch(u,{credentials:"same-origin"});return await WebAssembly.instantiateStreaming(f,_)}catch(l){F(`wasm streaming compile failed: ${l}`),F("falling back to ArrayBuffer instantiation")}return $_(u,_)}function F_(){return{env:il,wasi_snapshot_preview1:il}}async function z_(){function i(f,l){return ln=f.exports,Jy(ln),ln}function u(f){return i(f.instance)}var _=F_();if(r.instantiateWasm)return new Promise((f,l)=>{r.instantiateWasm(_,(d,h)=>{f(i(d,h))})});return Ln??=N_(),u(await M_(X,Ln,_))}var $n,Ye,At,Ht,U_,B_,j_,rt,H_,Cr,Bc=(i)=>{while(i.length>0)i.shift()(r)},jc=[],W_=(i)=>jc.push(i),Hc=[],Z_=(i)=>Hc.push(i),pr,et={isAbs:(i)=>i.charAt(0)==="/",splitPath:(i)=>/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/.exec(i).slice(1),normalizeArray:(i,u)=>{var _=0;for(var f=i.length-1;f>=0;f--){var l=i[f];if(l===".")i.splice(f,1);else if(l==="..")i.splice(f,1),_++;else if(_)i.splice(f,1),_--}if(u)for(;_;_--)i.unshift("..");return i},normalize:(i)=>{var u=et.isAbs(i),_=i.slice(-1)==="/";if(i=et.normalizeArray(i.split("/").filter((f)=>!!f),!u).join("/"),!i&&!u)i=".";if(i&&_)i+="/";return(u?"/":"")+i},dirname:(i)=>{var u=et.splitPath(i),_=u[0],f=u[1];if(!_&&!f)return".";if(f)f=f.slice(0,-1);return _+f},basename:(i)=>i&&i.match(/([^\/]+|\/)\/*$/)[1],join:(...i)=>et.normalize(i.join("/")),join2:(i,u)=>et.normalize(i+"/"+u)},K_=()=>(i)=>(crypto.getRandomValues(i),0),Wc=(i)=>(Wc=K_())(i),sn={resolve:(...i)=>{var u="",_=!1;for(var f=i.length-1;f>=-1&&!_;f--){var l=f>=0?i[f]:y.cwd();if(typeof l!="string")throw TypeError("Arguments to path.resolve must be strings");else if(!l)return"";u=l+"/"+u,_=et.isAbs(l)}return u=et.normalizeArray(u.split("/").filter((d)=>!!d),!_).join("/"),(_?"/":"")+u||"."},relative:(i,u)=>{i=sn.resolve(i).slice(1),u=sn.resolve(u).slice(1);function _(I){var V=0;for(;V<I.length;V++)if(I[V]!=="")break;var U=I.length-1;for(;U>=0;U--)if(I[U]!=="")break;if(V>U)return[];return I.slice(V,U-V+1)}var f=_(i.split("/")),l=_(u.split("/")),d=Math.min(f.length,l.length),h=d;for(var E=0;E<d;E++)if(f[E]!==l[E]){h=E;break}var b=[];for(var E=h;E<f.length;E++)b.push("..");return b=b.concat(l.slice(h)),b.join("/")}},Zc=new TextDecoder,Kc=(i,u,_,f)=>{var l=u+_;if(f)return l;while(i[u]&&!(u>=l))++u;return u},Mn=(i,u=0,_,f)=>{var l=Kc(i,u,_,f);return Zc.decode(i.buffer?i.subarray(u,l):new Uint8Array(i.slice(u,l)))},Yi=[],Ao=(i)=>{var u=0;for(var _=0;_<i.length;++_){var f=i.charCodeAt(_);if(f<=127)u++;else if(f<=2047)u+=2;else if(f>=55296&&f<=57343)u+=4,++_;else u+=3}return u},Gc=(i,u,_,f)=>{if(!(f>0))return 0;var l=_,d=_+f-1;for(var h=0;h<i.length;++h){var E=i.codePointAt(h);if(E<=127){if(_>=d)break;u[_++]=E}else if(E<=2047){if(_+1>=d)break;u[_++]=192|E>>6,u[_++]=128|E&63}else if(E<=65535){if(_+2>=d)break;u[_++]=224|E>>12,u[_++]=128|E>>6&63,u[_++]=128|E&63}else{if(_+3>=d)break;u[_++]=240|E>>18,u[_++]=128|E>>12&63,u[_++]=128|E>>6&63,u[_++]=128|E&63,h++}}return u[_]=0,_-l},es=(i,u,_)=>{var f=_>0?_:Ao(i)+1,l=Array(f),d=Gc(i,l,0,l.length);if(u)l.length=d;return l},G_=()=>{if(!Yi.length){var i=null;if(globalThis.window?.prompt){if(i=window.prompt("Input: "),i!==null)i+=`
533
+ `}if(!i)return null;Yi=es(i,!0)}return Yi.shift()},vr={ttys:[],init(){},shutdown(){},register(i,u){vr.ttys[i]={input:[],output:[],ops:u},y.registerDevice(i,vr.stream_ops)},stream_ops:{open(i){var u=vr.ttys[i.node.rdev];if(!u)throw new y.ErrnoError(43);i.tty=u,i.seekable=!1},close(i){i.tty.ops.fsync(i.tty)},fsync(i){i.tty.ops.fsync(i.tty)},read(i,u,_,f,l){if(!i.tty||!i.tty.ops.get_char)throw new y.ErrnoError(60);var d=0;for(var h=0;h<f;h++){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++,u[_+h]=E}if(d)i.node.atime=Date.now();return d},write(i,u,_,f,l){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,u[_+d])}catch(h){throw new y.ErrnoError(29)}if(f)i.node.mtime=i.node.ctime=Date.now();return d}},default_tty_ops:{get_char(i){return G_()},put_char(i,u){if(u===null||u===10)A(Mn(i.output)),i.output=[];else if(u!=0)i.output.push(u)},fsync(i){if(i.output?.length>0)A(Mn(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,u,_){return 0},ioctl_tiocgwinsz(i){return[24,80]}},default_tty1_ops:{put_char(i,u){if(u===null||u===10)F(Mn(i.output)),i.output=[];else if(u!=0)i.output.push(u)},fsync(i){if(i.output?.length>0)F(Mn(i.output)),i.output=[]}}},V_=(i,u)=>Cr.fill(0,i,i+u),Vc=(i,u)=>Math.ceil(i/u)*u,Jc=(i)=>{i=Vc(i,65536);var u=ol(65536,i);if(u)V_(u,i);return u},ze={ops_table:null,mount(i){return ze.createNode(null,"/",16895,0)},createNode(i,u,_,f){if(y.isBlkdev(_)||y.isFIFO(_))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 l=y.createNode(i,u,_,f);if(y.isDir(l.mode))l.node_ops=ze.ops_table.dir.node,l.stream_ops=ze.ops_table.dir.stream,l.contents={};else if(y.isFile(l.mode))l.node_ops=ze.ops_table.file.node,l.stream_ops=ze.ops_table.file.stream,l.usedBytes=0,l.contents=ze.emptyFileContents??=new Uint8Array(0);else if(y.isLink(l.mode))l.node_ops=ze.ops_table.link.node,l.stream_ops=ze.ops_table.link.stream;else if(y.isChrdev(l.mode))l.node_ops=ze.ops_table.chrdev.node,l.stream_ops=ze.ops_table.chrdev.stream;if(l.atime=l.mtime=l.ctime=Date.now(),i)i.contents[u]=l,i.atime=i.mtime=i.ctime=l.atime;return l},getFileDataAsTypedArray(i){return i.contents.subarray(0,i.usedBytes)},expandFileStorage(i,u){var _=i.contents.length;if(_>=u)return;if(u=Math.max(u,_*(_<1048576?2:1.125)>>>0),_)u=Math.max(u,256);var f=ze.getFileDataAsTypedArray(i);i.contents=new Uint8Array(u),i.contents.set(f)},resizeFileStorage(i,u){if(i.usedBytes==u)return;var _=i.contents;i.contents=new Uint8Array(u),i.contents.set(_.subarray(0,Math.min(u,i.usedBytes))),i.usedBytes=u},node_ops:{getattr(i){var u={};if(u.dev=y.isChrdev(i.mode)?i.id:1,u.ino=i.id,u.mode=i.mode,u.nlink=1,u.uid=0,u.gid=0,u.rdev=i.rdev,y.isDir(i.mode))u.size=4096;else if(y.isFile(i.mode))u.size=i.usedBytes;else if(y.isLink(i.mode))u.size=i.link.length;else u.size=0;return u.atime=new Date(i.atime),u.mtime=new Date(i.mtime),u.ctime=new Date(i.ctime),u.blksize=4096,u.blocks=Math.ceil(u.size/u.blksize),u},setattr(i,u){for(let _ of["mode","atime","mtime","ctime"])if(u[_]!=null)i[_]=u[_];if(u.size!==void 0)ze.resizeFileStorage(i,u.size)},lookup(i,u){if(!ze.doesNotExistError)ze.doesNotExistError=new y.ErrnoError(44),ze.doesNotExistError.stack="<generic error, no stack>";throw ze.doesNotExistError},mknod(i,u,_,f){return ze.createNode(i,u,_,f)},rename(i,u,_){var f;try{f=y.lookupNode(u,_)}catch(d){}if(f){if(y.isDir(i.mode))for(var l in f.contents)throw new y.ErrnoError(55);y.hashRemoveNode(f)}delete i.parent.contents[i.name],u.contents[_]=i,i.name=_,u.ctime=u.mtime=i.parent.ctime=i.parent.mtime=Date.now()},unlink(i,u){delete i.contents[u],i.ctime=i.mtime=Date.now()},rmdir(i,u){for(var _ in y.lookupNode(i,u).contents)throw new y.ErrnoError(55);delete i.contents[u],i.ctime=i.mtime=Date.now()},readdir(i){return[".","..",...Object.keys(i.contents)]},symlink(i,u,_){var f=ze.createNode(i,u,41471,0);return f.link=_,f},readlink(i){if(!y.isLink(i.mode))throw new y.ErrnoError(28);return i.link}},stream_ops:{read(i,u,_,f,l){var d=i.node.contents;if(l>=i.node.usedBytes)return 0;var h=Math.min(i.node.usedBytes-l,f);return u.set(d.subarray(l,l+h),_),h},write(i,u,_,f,l,d){if(u.buffer===Ht.buffer)d=!1;if(!f)return 0;var h=i.node;if(h.mtime=h.ctime=Date.now(),d)h.contents=u.subarray(_,_+f),h.usedBytes=f;else if(h.usedBytes===0&&l===0)h.contents=u.slice(_,_+f),h.usedBytes=f;else ze.expandFileStorage(h,l+f),h.contents.set(u.subarray(_,_+f),l),h.usedBytes=Math.max(h.usedBytes,l+f);return f},llseek(i,u,_){var f=u;if(_===1)f+=i.position;else if(_===2){if(y.isFile(i.node.mode))f+=i.node.usedBytes}if(f<0)throw new y.ErrnoError(28);return f},mmap(i,u,_,f,l){if(!y.isFile(i.node.mode))throw new y.ErrnoError(43);var d,h,E=i.node.contents;if(!(l&2)&&E.buffer===Ht.buffer)h=!1,d=E.byteOffset;else{if(h=!0,d=Jc(u),!d)throw new y.ErrnoError(48);if(E){if(_>0||_+u<E.length)if(E.subarray)E=E.subarray(_,_+u);else E=Array.prototype.slice.call(E,_,_+u);Ht.set(E,d)}}return{ptr:d,allocated:h}},msync(i,u,_,f,l){return ze.stream_ops.write(i,u,0,f,_,!1),0}}},J_=(i)=>{if(typeof i!="string")return i;var u={r:0,"r+":2,w:577,"w+":578,a:1089,"a+":1090}[i];if(typeof u>"u")throw Error(`Unknown file open mode: ${i}`);return u},Xc=(i)=>{if(typeof i=="string")i=es(i,!0);if(!i.subarray)i=new Uint8Array(i);return i},ts=(i,u)=>{var _=0;if(i)_|=365;if(u)_|=146;return _},X_=async(i)=>{var u=await m(i);return new Uint8Array(u)},Q_=(...i)=>y.createDataFile(...i),Y_=(i)=>i,Pr=0,Fn=null,ey=(i)=>{if(Pr--,r.monitorRunDependencies?.(Pr),Pr==0){if(Fn){var u=Fn;Fn=null,u()}}},ty=(i)=>{Pr++,r.monitorRunDependencies?.(Pr)},Qc=[],ry=async(i,u)=>{if(typeof Browser<"u")Browser.init();for(var _ of Qc)if(_.canHandle(u))return _.handle(i,u);return i},Yc=async(i,u,_,f,l,d,h,E)=>{var b=u?sn.resolve(et.join2(i,u)):i,I=Y_(`cp ${b}`);ty(I);try{var V=_;if(typeof _=="string")V=await X_(_);if(V=await ry(V,b),E?.(),!d)Q_(i,u,V,f,l,h)}finally{ey(I)}},ny=(i,u,_,f,l,d,h,E,b,I)=>{Yc(i,u,_,f,l,E,b,I).then(d).catch(h)},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,u,_,f){if(!i)i=this;this.parent=i,this.mount=i.mount,this.id=y.nextInode++,this.name=u,this.mode=_,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,u={}){if(!i)throw new y.ErrnoError(44);if(u.follow_mount??=!0,!et.isAbs(i))i=y.cwd()+"/"+i;e:for(var _=0;_<40;_++){var f=i.split("/").filter((I)=>!!I),l=y.root,d="/";for(var h=0;h<f.length;h++){var E=h===f.length-1;if(E&&u.parent)break;if(f[h]===".")continue;if(f[h]===".."){if(d=et.dirname(d),y.isRoot(l)){i=d+"/"+f.slice(h+1).join("/"),_--;continue e}else l=l.parent;continue}d=et.join2(d,f[h]);try{l=y.lookupNode(l,f[h])}catch(I){if(I?.errno===44&&E&&u.noent_okay)return{path:d};throw I}if(y.isMountpoint(l)&&(!E||u.follow_mount))l=l.mounted.root;if(y.isLink(l.mode)&&(!E||u.follow)){if(!l.node_ops.readlink)throw new y.ErrnoError(52);var b=l.node_ops.readlink(l);if(!et.isAbs(b))b=et.dirname(d)+"/"+b;i=b+"/"+f.slice(h+1).join("/");continue e}}return{path:d,node:l}}throw new y.ErrnoError(32)},getPath(i){var u;while(!0){if(y.isRoot(i)){var _=i.mount.mountpoint;if(!u)return _;return _[_.length-1]!=="/"?`${_}/${u}`:_+u}u=u?`${i.name}/${u}`:i.name,i=i.parent}},hashName(i,u){var _=0;for(var f=0;f<u.length;f++)_=(_<<5)-_+u.charCodeAt(f)|0;return(i+_>>>0)%y.nameTable.length},hashAddNode(i){var u=y.hashName(i.parent.id,i.name);i.name_next=y.nameTable[u],y.nameTable[u]=i},hashRemoveNode(i){var u=y.hashName(i.parent.id,i.name);if(y.nameTable[u]===i)y.nameTable[u]=i.name_next;else{var _=y.nameTable[u];while(_){if(_.name_next===i){_.name_next=i.name_next;break}_=_.name_next}}},lookupNode(i,u){var _=y.mayLookup(i);if(_)throw new y.ErrnoError(_);var f=y.hashName(i.id,u);for(var l=y.nameTable[f];l;l=l.name_next){var d=l.name;if(l.parent.id===i.id&&d===u)return l}return y.lookup(i,u)},createNode(i,u,_,f){var l=new y.FSNode(i,u,_,f);return y.hashAddNode(l),l},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 u=["r","w","rw"][i&3];if(i&512)u+="w";return u},nodePermissions(i,u){if(y.ignorePermissions)return 0;if(u.includes("r")&&!(i.mode&292))return 2;if(u.includes("w")&&!(i.mode&146))return 2;if(u.includes("x")&&!(i.mode&73))return 2;return 0},mayLookup(i){if(!y.isDir(i.mode))return 54;var u=y.nodePermissions(i,"x");if(u)return u;if(!i.node_ops.lookup)return 2;return 0},mayCreate(i,u){if(!y.isDir(i.mode))return 54;try{return y.lookupNode(i,u),20}catch(_){}return y.nodePermissions(i,"wx")},mayDelete(i,u,_){var f;try{f=y.lookupNode(i,u)}catch(d){return d.errno}var l=y.nodePermissions(i,"wx");if(l)return l;if(_){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,u){if(!i)return 44;if(y.isLink(i.mode))return 32;var _=y.flagsToPermissionString(u);if(y.isDir(i.mode)){if(_!=="r"||u&576)return 31}return y.nodePermissions(i,_)},checkOpExists(i,u){if(!i)throw new y.ErrnoError(u);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 u=y.getStream(i);if(!u)throw new y.ErrnoError(8);return u},getStream:(i)=>y.streams[i],createStream(i,u=-1){if(i=Object.assign(new y.FSStream,i),u==-1)u=y.nextfd();return i.fd=u,y.streams[u]=i,i},closeStream(i){y.streams[i]=null},dupStream(i,u=-1){var _=y.createStream(i,u);return _.stream_ops?.dup?.(_),_},doSetAttr(i,u,_){var f=i?.stream_ops.setattr,l=f?i:u;f??=u.node_ops.setattr,y.checkOpExists(f,63),f(l,_)},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,u)=>i<<8|u,registerDevice(i,u){y.devices[i]={stream_ops:u}},getDevice:(i)=>y.devices[i],getMounts(i){var u=[],_=[i];while(_.length){var f=_.pop();u.push(f),_.push(...f.mounts)}return u},syncfs(i,u){if(typeof i=="function")u=i,i=!1;if(y.syncFSRequests++,y.syncFSRequests>1)F(`warning: ${y.syncFSRequests} FS.syncfs operations in flight at once, probably just doing extra work`);var _=y.getMounts(y.root.mount),f=0;function l(E){return y.syncFSRequests--,u(E)}function d(E){if(E){if(!d.errored)return d.errored=!0,l(E);return}if(++f>=_.length)l(null)}for(var h of _)if(h.type.syncfs)h.type.syncfs(h,i,d);else d(null)},mount(i,u,_){var f=_==="/",l=!_,d;if(f&&y.root)throw new y.ErrnoError(10);else if(!f&&!l){var h=y.lookupPath(_,{follow_mount:!1});if(_=h.path,d=h.node,y.isMountpoint(d))throw new y.ErrnoError(10);if(!y.isDir(d.mode))throw new y.ErrnoError(54)}var E={type:i,opts:u,mountpoint:_,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 u=y.lookupPath(i,{follow_mount:!1});if(!y.isMountpoint(u.node))throw new y.ErrnoError(28);var _=u.node,f=_.mounted,l=y.getMounts(f);for(var[d,h]of Object.entries(y.nameTable))while(h){var E=h.name_next;if(l.includes(h.mount))y.destroyNode(h);h=E}_.mounted=null;var b=_.mount.mounts.indexOf(f);_.mount.mounts.splice(b,1)},lookup(i,u){return i.node_ops.lookup(i,u)},mknod(i,u,_){var f=y.lookupPath(i,{parent:!0}).node,l=et.basename(i);if(!l)throw new y.ErrnoError(28);if(l==="."||l==="..")throw new y.ErrnoError(20);var d=y.mayCreate(f,l);if(d)throw new y.ErrnoError(d);if(!f.node_ops.mknod)throw new y.ErrnoError(63);return f.node_ops.mknod(f,l,u,_)},statfs(i){return y.statfsNode(y.lookupPath(i,{follow:!0}).node)},statfsStream(i){return y.statfsNode(i.node)},statfsNode(i){var u={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(u,i.node_ops.statfs(i.mount.opts.root));return u},create(i,u=438){return u&=4095,u|=32768,y.mknod(i,u,0)},mkdir(i,u=511){return u&=1023,u|=16384,y.mknod(i,u,0)},mkdirTree(i,u){var _=i.split("/"),f="";for(var l of _){if(!l)continue;if(f||et.isAbs(i))f+="/";f+=l;try{y.mkdir(f,u)}catch(d){if(d.errno!=20)throw d}}},mkdev(i,u,_){if(typeof _>"u")_=u,u=438;return u|=8192,y.mknod(i,u,_)},symlink(i,u){if(!sn.resolve(i))throw new y.ErrnoError(44);var _=y.lookupPath(u,{parent:!0}).node;if(!_)throw new y.ErrnoError(44);var f=et.basename(u),l=y.mayCreate(_,f);if(l)throw new y.ErrnoError(l);if(!_.node_ops.symlink)throw new y.ErrnoError(63);return _.node_ops.symlink(_,f,i)},rename(i,u){var _=et.dirname(i),f=et.dirname(u),l=et.basename(i),d=et.basename(u),h=y.lookupPath(i,{parent:!0}),E=h.node,b;if(h=y.lookupPath(u,{parent:!0}),b=h.node,!E||!b)throw new y.ErrnoError(44);if(E.mount!==b.mount)throw new y.ErrnoError(75);var I=y.lookupNode(E,l),V=sn.relative(i,f);if(V.charAt(0)!==".")throw new y.ErrnoError(28);if(V=sn.relative(u,_),V.charAt(0)!==".")throw new y.ErrnoError(55);var U;try{U=y.lookupNode(b,d)}catch(W){}if(I===U)return;var N=y.isDir(I.mode),q=y.mayDelete(E,l,N);if(q)throw new y.ErrnoError(q);if(q=U?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)||U&&y.isMountpoint(U))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(W){throw W}finally{y.hashAddNode(I)}},rmdir(i){var u=y.lookupPath(i,{parent:!0}).node,_=et.basename(i),f=y.lookupNode(u,_),l=y.mayDelete(u,_,!0);if(l)throw new y.ErrnoError(l);if(!u.node_ops.rmdir)throw new y.ErrnoError(63);if(y.isMountpoint(f))throw new y.ErrnoError(10);u.node_ops.rmdir(u,_),y.destroyNode(f)},readdir(i){var u=y.lookupPath(i,{follow:!0}).node;return y.checkOpExists(u.node_ops.readdir,54)(u)},unlink(i){var u=y.lookupPath(i,{parent:!0}).node;if(!u)throw new y.ErrnoError(44);var _=et.basename(i),f=y.lookupNode(u,_),l=y.mayDelete(u,_,!1);if(l)throw new y.ErrnoError(l);if(!u.node_ops.unlink)throw new y.ErrnoError(63);if(y.isMountpoint(f))throw new y.ErrnoError(10);u.node_ops.unlink(u,_),y.destroyNode(f)},readlink(i){var u=y.lookupPath(i).node;if(!u)throw new y.ErrnoError(44);if(!u.node_ops.readlink)throw new y.ErrnoError(28);return u.node_ops.readlink(u)},stat(i,u){var _=y.lookupPath(i,{follow:!u}).node;return y.checkOpExists(_.node_ops.getattr,63)(_)},fstat(i){var u=y.getStreamChecked(i),_=u.node,f=u.stream_ops.getattr,l=f?u:_;return f??=_.node_ops.getattr,y.checkOpExists(f,63),f(l)},lstat(i){return y.stat(i,!0)},doChmod(i,u,_,f){y.doSetAttr(i,u,{mode:_&4095|u.mode&-4096,ctime:Date.now(),dontFollow:f})},chmod(i,u,_){var f;if(typeof i=="string")f=y.lookupPath(i,{follow:!_}).node;else f=i;y.doChmod(null,f,u,_)},lchmod(i,u){y.chmod(i,u,!0)},fchmod(i,u){var _=y.getStreamChecked(i);y.doChmod(_,_.node,u,!1)},doChown(i,u,_){y.doSetAttr(i,u,{timestamp:Date.now(),dontFollow:_})},chown(i,u,_,f){var l;if(typeof i=="string")l=y.lookupPath(i,{follow:!f}).node;else l=i;y.doChown(null,l,f)},lchown(i,u,_){y.chown(i,u,_,!0)},fchown(i,u,_){var f=y.getStreamChecked(i);y.doChown(f,f.node,!1)},doTruncate(i,u,_){if(y.isDir(u.mode))throw new y.ErrnoError(31);if(!y.isFile(u.mode))throw new y.ErrnoError(28);var f=y.nodePermissions(u,"w");if(f)throw new y.ErrnoError(f);y.doSetAttr(i,u,{size:_,timestamp:Date.now()})},truncate(i,u){if(u<0)throw new y.ErrnoError(28);var _;if(typeof i=="string")_=y.lookupPath(i,{follow:!0}).node;else _=i;y.doTruncate(null,_,u)},ftruncate(i,u){var _=y.getStreamChecked(i);if(u<0||(_.flags&2097155)===0)throw new y.ErrnoError(28);y.doTruncate(_,_.node,u)},utime(i,u,_){var f=y.lookupPath(i,{follow:!0}).node;y.checkOpExists(f.node_ops.setattr,63)(f,{atime:u,mtime:_})},open(i,u,_=438){if(i==="")throw new y.ErrnoError(44);if(u=J_(u),u&64)_=_&4095|32768;else _=0;var f,l;if(typeof i=="object")f=i;else{l=i.endsWith("/");var d=y.lookupPath(i,{follow:!(u&131072),noent_okay:!0});f=d.node,i=d.path}var h=!1;if(u&64)if(f){if(u&128)throw new y.ErrnoError(20)}else if(l)throw new y.ErrnoError(31);else f=y.mknod(i,_|511,0),h=!0;if(!f)throw new y.ErrnoError(44);if(y.isChrdev(f.mode))u&=-513;if(u&65536&&!y.isDir(f.mode))throw new y.ErrnoError(54);if(!h){var E=y.mayOpen(f,u);if(E)throw new y.ErrnoError(E)}if(u&512&&!h)y.truncate(f,0);u&=-131713;var b=y.createStream({node:f,path:y.getPath(f),flags:u,seekable:!0,position:0,stream_ops:f.stream_ops,ungotten:[],error:!1});if(b.stream_ops.open)b.stream_ops.open(b);if(h)y.chmod(f,_&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(u){throw u}finally{y.closeStream(i.fd)}i.fd=null},isClosed(i){return i.fd===null},llseek(i,u,_){if(y.isClosed(i))throw new y.ErrnoError(8);if(!i.seekable||!i.stream_ops.llseek)throw new y.ErrnoError(70);if(_!=0&&_!=1&&_!=2)throw new y.ErrnoError(28);return i.position=i.stream_ops.llseek(i,u,_),i.ungotten=[],i.position},read(i,u,_,f,l){if(f<0||l<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 l<"u";if(!d)l=i.position;else if(!i.seekable)throw new y.ErrnoError(70);var h=i.stream_ops.read(i,u,_,f,l);if(!d)i.position+=h;return h},write(i,u,_,f,l,d){if(f<0||l<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 h=typeof l<"u";if(!h)l=i.position;else if(!i.seekable)throw new y.ErrnoError(70);var E=i.stream_ops.write(i,u,_,f,l,d);if(!h)i.position+=E;return E},mmap(i,u,_,f,l){if((f&2)!==0&&(l&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(!u)throw new y.ErrnoError(28);return i.stream_ops.mmap(i,u,_,f,l)},msync(i,u,_,f,l){if(!i.stream_ops.msync)return 0;return i.stream_ops.msync(i,u,_,f,l)},ioctl(i,u,_){if(!i.stream_ops.ioctl)throw new y.ErrnoError(59);return i.stream_ops.ioctl(i,u,_)},readFile(i,u={}){if(u.flags=u.flags||0,u.encoding=u.encoding||"binary",u.encoding!=="utf8"&&u.encoding!=="binary")Rt(`Invalid encoding type "${u.encoding}"`);var _=y.open(i,u.flags),f=y.stat(i).size,l=new Uint8Array(f);if(y.read(_,l,0,f,0),u.encoding==="utf8")l=Mn(l);return y.close(_),l},writeFile(i,u,_={}){_.flags=_.flags||577;var f=y.open(i,_.flags,_.mode);u=Xc(u),y.write(f,u,0,u.byteLength,void 0,_.canOwn),y.close(f)},cwd:()=>y.currentPath,chdir(i){var u=y.lookupPath(i,{follow:!0});if(u.node===null)throw new y.ErrnoError(44);if(!y.isDir(u.node.mode))throw new y.ErrnoError(54);var _=y.nodePermissions(u.node,"x");if(_)throw new y.ErrnoError(_);y.currentPath=u.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,l,d,h,E)=>h,llseek:()=>0}),y.mkdev("/dev/null",y.makedev(1,3)),vr.register(y.makedev(5,0),vr.default_tty_ops),vr.register(y.makedev(6,0),vr.default_tty1_ops),y.mkdev("/dev/tty",y.makedev(5,0)),y.mkdev("/dev/tty1",y.makedev(6,0));var i=new Uint8Array(1024),u=0,_=()=>{if(u===0)Wc(i),u=i.byteLength;return i[--u]};y.createDevice("/dev","random",_),y.createDevice("/dev","urandom",_),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 u=y.createNode(i,"fd",16895,73);return u.stream_ops={llseek:ze.stream_ops.llseek},u.node_ops={lookup(_,f){var l=+f,d=y.getStreamChecked(l),h={parent:null,mount:{mountpoint:"fake"},node_ops:{readlink:()=>d.path},id:l+1};return h.parent=h,h},readdir(){return Array.from(y.streams.entries()).filter(([_,f])=>f).map(([_,f])=>_.toString())}},u}},{},"/proc/self/fd")},createStandardStreams(i,u,_){if(i)y.createDevice("/dev","stdin",i);else y.symlink("/dev/tty","/dev/stdin");if(u)y.createDevice("/dev","stdout",null,u);else y.symlink("/dev/tty","/dev/stdout");if(_)y.createDevice("/dev","stderr",null,_);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,u,_){y.initialized=!0,i??=r.stdin,u??=r.stdout,_??=r.stderr,y.createStandardStreams(i,u,_)},quit(){y.initialized=!1;for(var i of y.streams)if(i)y.close(i)},findObject(i,u){var _=y.analyzePath(i,u);if(!_.exists)return null;return _.object},analyzePath(i,u){try{var _=y.lookupPath(i,{follow:!u});i=_.path}catch(l){}var f={isRoot:!1,exists:!1,error:0,name:null,path:null,object:null,parentExists:!1,parentPath:null,parentObject:null};try{var _=y.lookupPath(i,{parent:!0});f.parentExists=!0,f.parentPath=_.path,f.parentObject=_.node,f.name=et.basename(i),_=y.lookupPath(i,{follow:!u}),f.exists=!0,f.path=_.path,f.object=_.node,f.name=_.node.name,f.isRoot=_.path==="/"}catch(l){f.error=l.errno}return f},createPath(i,u,_,f){i=typeof i=="string"?i:y.getPath(i);var l=u.split("/").reverse();while(l.length){var d=l.pop();if(!d)continue;var h=et.join2(i,d);try{y.mkdir(h)}catch(E){if(E.errno!=20)throw E}i=h}return h},createFile(i,u,_,f,l){var d=et.join2(typeof i=="string"?i:y.getPath(i),u),h=ts(f,l);return y.create(d,h)},createDataFile(i,u,_,f,l,d){var h=u;if(i)i=typeof i=="string"?i:y.getPath(i),h=u?et.join2(i,u):i;var E=ts(f,l),b=y.create(h,E);if(_){_=Xc(_),y.chmod(b,E|146);var I=y.open(b,577);y.write(I,_,0,_.length,0,d),y.close(I),y.chmod(b,E)}},createDevice(i,u,_,f){var l=et.join2(typeof i=="string"?i:y.getPath(i),u),d=ts(!!_,!!f);y.createDevice.major??=64;var h=y.makedev(y.createDevice.major++,0);return y.registerDevice(h,{open(E){E.seekable=!1},close(E){if(f?.buffer?.length)f(10)},read(E,b,I,V,U){var N=0;for(var q=0;q<V;q++){var W;try{W=_()}catch(K){throw new y.ErrnoError(29)}if(W===void 0&&N===0)throw new y.ErrnoError(6);if(W===null||W===void 0)break;N++,b[I+q]=W}if(N)E.node.atime=Date.now();return N},write(E,b,I,V,U){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(l,d,h)},forceLoadFile(i){if(i.isDevice||i.isFolder||i.link||i.contents)return!0;if(globalThis.XMLHttpRequest)Rt("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(u){throw new y.ErrnoError(29)}},createLazyFile(i,u,_,f,l){class d{lengthKnown=!1;chunks=[];get(V){if(V>this.length-1||V<0)return;var U=V%this.chunkSize,N=V/this.chunkSize|0;return this.getter(N)[U]}setDataGetter(V){this.getter=V}cacheLength(){var V=new XMLHttpRequest;if(V.open("HEAD",_,!1),V.send(null),!(V.status>=200&&V.status<300||V.status===304))Rt("Couldn't load "+_+". Status: "+V.status);var U=Number(V.getResponseHeader("Content-length")),N,q=(N=V.getResponseHeader("Accept-Ranges"))&&N==="bytes",W=(N=V.getResponseHeader("Content-Encoding"))&&N==="gzip",K=1048576;if(!q)K=U;var ue=(R,Q)=>{if(R>Q)Rt("invalid range ("+R+", "+Q+") or no bytes requested!");if(Q>U-1)Rt("only "+U+" bytes available! programmer error!");var ee=new XMLHttpRequest;if(ee.open("GET",_,!1),U!==K)ee.setRequestHeader("Range","bytes="+R+"-"+Q);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))Rt("Couldn't load "+_+". Status: "+ee.status);if(ee.response!==void 0)return new Uint8Array(ee.response||[]);return es(ee.responseText||"",!0)},O=this;if(O.setDataGetter((R)=>{var Q=R*K,ee=(R+1)*K-1;if(ee=Math.min(ee,U-1),typeof O.chunks[R]>"u")O.chunks[R]=ue(Q,ee);if(typeof O.chunks[R]>"u")Rt("doXHR failed!");return O.chunks[R]}),W||!U)K=U=1,U=this.getter(0).length,K=U,A("LazyFiles on gzip forces download of the whole file when length is accessed");this._length=U,this._chunkSize=K,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)Rt("Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc");var h={isDevice:!1,contents:new d}}else var h={isDevice:!1,url:_};var E=y.createFile(i,u,h,f,l);if(h.contents)E.contents=h.contents;else if(h.url)E.contents=null,E.url=h.url;Object.defineProperties(E,{usedBytes:{get:function(){return this.contents.length}}});var b={};for(let[V,U]of Object.entries(E.stream_ops))b[V]=(...N)=>(y.forceLoadFile(E),U(...N));function I(V,U,N,q,W){var K=V.node.contents;if(W>=K.length)return 0;var ue=Math.min(K.length-W,q);if(K.slice)for(var O=0;O<ue;O++)U[N+O]=K[W+O];else for(var O=0;O<ue;O++)U[N+O]=K.get(W+O);return ue}return b.read=(V,U,N,q,W)=>(y.forceLoadFile(E),I(V,U,N,q,W)),b.mmap=(V,U,N,q,W)=>{y.forceLoadFile(E);var K=Jc(U);if(!K)throw new y.ErrnoError(48);return I(V,Ht,K,U,N),{ptr:K,allocated:!0}},E.stream_ops=b,E}},oy=(i,u,_)=>{if(!i)return"";var f=Kc(Cr,i,u,_);return Zc.decode(Cr.subarray(i,f))},je={calculateAt(i,u,_){if(et.isAbs(u))return u;var f;if(i===-100)f=y.cwd();else f=je.getStreamFromFD(i).path;if(u.length==0){if(!_)throw new y.ErrnoError(44);return f}return f+"/"+u},writeStat(i,u){rt[i>>2]=u.dev,rt[i+4>>2]=u.mode,rt[i+8>>2]=u.nlink,rt[i+12>>2]=u.uid,rt[i+16>>2]=u.gid,rt[i+20>>2]=u.rdev,At[i+24>>3]=BigInt(u.size),Ye[i+32>>2]=4096,Ye[i+36>>2]=u.blocks;var _=u.atime.getTime(),f=u.mtime.getTime(),l=u.ctime.getTime();return At[i+40>>3]=BigInt(Math.floor(_/1000)),rt[i+48>>2]=_%1000*1000*1000,At[i+56>>3]=BigInt(Math.floor(f/1000)),rt[i+64>>2]=f%1000*1000*1000,At[i+72>>3]=BigInt(Math.floor(l/1000)),rt[i+80>>2]=l%1000*1000*1000,At[i+88>>3]=BigInt(u.ino),0},writeStatFs(i,u){rt[i+4>>2]=u.bsize,rt[i+60>>2]=u.bsize,At[i+8>>3]=BigInt(u.blocks),At[i+16>>3]=BigInt(u.bfree),At[i+24>>3]=BigInt(u.bavail),At[i+32>>3]=BigInt(u.files),At[i+40>>3]=BigInt(u.ffree),rt[i+48>>2]=u.fsid,rt[i+64>>2]=u.flags,rt[i+56>>2]=u.namelen},doMsync(i,u,_,f,l){if(!y.isFile(u.node.mode))throw new y.ErrnoError(43);if(f&2)return 0;var d=Cr.slice(i,i+_);y.msync(u,d,l,_,f)},getStreamFromFD(i){return y.getStreamChecked(i)},varargs:void 0,getStr(i){return oy(i)}};function iy(i,u){try{return i=je.getStr(i),y.chmod(i,u),0}catch(_){if(typeof y>"u"||_.name!=="ErrnoError")throw _;return-_.errno}}function sy(i,u,_,f){try{if(u=je.getStr(u),u=je.calculateAt(i,u),_&-8)return-28;var l=y.lookupPath(u,{follow:!0}).node;if(!l)return-44;var d="";if(_&4)d+="r";if(_&2)d+="w";if(_&1)d+="x";if(d&&y.nodePermissions(l,d))return-2;return 0}catch(h){if(typeof y>"u"||h.name!=="ErrnoError")throw h;return-h.errno}}function ay(i,u){try{return y.fchmod(i,u),0}catch(_){if(typeof y>"u"||_.name!=="ErrnoError")throw _;return-_.errno}}function cy(i,u,_){try{return y.fchown(i,u,_),0}catch(f){if(typeof y>"u"||f.name!=="ErrnoError")throw f;return-f.errno}}var Do=()=>{var i=Ye[+je.varargs>>2];return je.varargs+=4,i},an=Do;function ly(i,u,_){je.varargs=_;try{var f=je.getStreamFromFD(i);switch(u){case 0:var l=Do();if(l<0)return-28;while(y.streams[l])l++;return y.dupStream(f,l).fd;case 1:case 2:return 0;case 3:return f.flags;case 4:var l=Do();return f.flags|=l,0;case 12:var l=an(),d=0;return $n[l+d>>1]=2,0;case 13:case 14:return 0}return-28}catch(h){if(typeof y>"u"||h.name!=="ErrnoError")throw h;return-h.errno}}function uy(i,u){try{return je.writeStat(u,y.fstat(i))}catch(_){if(typeof y>"u"||_.name!=="ErrnoError")throw _;return-_.errno}}var dy=9007199254740992,fy=-9007199254740992,cn=(i)=>i<fy||i>dy?NaN:Number(i);function py(i,u){u=cn(u);try{if(isNaN(u))return-61;return y.ftruncate(i,u),0}catch(_){if(typeof y>"u"||_.name!=="ErrnoError")throw _;return-_.errno}}var Nr=(i,u,_)=>Gc(i,Cr,u,_);function hy(i,u){try{if(u===0)return-28;var _=y.cwd(),f=Ao(_)+1;if(u<f)return-68;return Nr(_,i,u),f}catch(l){if(typeof y>"u"||l.name!=="ErrnoError")throw l;return-l.errno}}function gy(i,u,_){je.varargs=_;try{var f=je.getStreamFromFD(i);switch(u){case 21509:if(!f.tty)return-59;return 0;case 21505:if(!f.tty)return-59;if(f.tty.ops.ioctl_tcgets){var l=f.tty.ops.ioctl_tcgets(f),U=an();Ye[U>>2]=l.c_iflag||0,Ye[U+4>>2]=l.c_oflag||0,Ye[U+8>>2]=l.c_cflag||0,Ye[U+12>>2]=l.c_lflag||0;for(var d=0;d<32;d++)Ht[U+d+17]=l.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 U=an(),h=Ye[U>>2],E=Ye[U+4>>2],b=Ye[U+8>>2],I=Ye[U+12>>2],V=[];for(var d=0;d<32;d++)V.push(Ht[U+d+17]);return f.tty.ops.ioctl_tcsets(f.tty,u,{c_iflag:h,c_oflag:E,c_cflag:b,c_lflag:I,c_cc:V})}return 0;case 21519:if(!f.tty)return-59;var U=an();return Ye[U>>2]=0,0;case 21520:if(!f.tty)return-59;return-28;case 21537:case 21531:var U=an();return y.ioctl(f,u,U);case 21523:if(!f.tty)return-59;if(f.tty.ops.ioctl_tiocgwinsz){var N=f.tty.ops.ioctl_tiocgwinsz(f.tty),U=an();$n[U>>1]=N[0],$n[U+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 my(i,u){try{return i=je.getStr(i),je.writeStat(u,y.lstat(i))}catch(_){if(typeof y>"u"||_.name!=="ErrnoError")throw _;return-_.errno}}function _y(i,u,_){try{return u=je.getStr(u),u=je.calculateAt(i,u),y.mkdir(u,_,0),0}catch(f){if(typeof y>"u"||f.name!=="ErrnoError")throw f;return-f.errno}}function yy(i,u,_,f){try{u=je.getStr(u);var l=f&256,d=f&4096;return f=f&-6401,u=je.calculateAt(i,u,d),je.writeStat(_,l?y.lstat(u):y.stat(u))}catch(h){if(typeof y>"u"||h.name!=="ErrnoError")throw h;return-h.errno}}function by(i,u,_,f){je.varargs=f;try{u=je.getStr(u),u=je.calculateAt(i,u);var l=f?Do():0;return y.open(u,_,l).fd}catch(d){if(typeof y>"u"||d.name!=="ErrnoError")throw d;return-d.errno}}function wy(i,u,_,f){try{if(u=je.getStr(u),u=je.calculateAt(i,u),f<=0)return-28;var l=y.readlink(u),d=Math.min(f,Ao(l)),h=Ht[_+d];return Nr(l,_,f+1),Ht[_+d]=h,d}catch(E){if(typeof y>"u"||E.name!=="ErrnoError")throw E;return-E.errno}}function vy(i){try{return i=je.getStr(i),y.rmdir(i),0}catch(u){if(typeof y>"u"||u.name!=="ErrnoError")throw u;return-u.errno}}function Ey(i,u){try{return i=je.getStr(i),je.writeStat(u,y.stat(i))}catch(_){if(typeof y>"u"||_.name!=="ErrnoError")throw _;return-_.errno}}function Sy(i,u,_){try{if(u=je.getStr(u),u=je.calculateAt(i,u),!_)y.unlink(u);else if(_===512)y.rmdir(u);else return-28;return 0}catch(f){if(typeof y>"u"||f.name!=="ErrnoError")throw f;return-f.errno}}var el=(i)=>rt[i>>2]+Ye[i+4>>2]*4294967296;function ky(i,u,_,f){try{u=je.getStr(u),u=je.calculateAt(i,u,!0);var l=Date.now(),d,h;if(!_)d=l,h=l;else{var E=el(_),b=Ye[_+8>>2];if(b==1073741823)d=l;else if(b==1073741822)d=null;else d=E*1000+b/1e6;if(_+=16,E=el(_),b=Ye[_+8>>2],b==1073741823)h=l;else if(b==1073741822)h=null;else h=E*1000+b/1e6}if((h??d)!==null)y.utime(u,d,h);return 0}catch(I){if(typeof y>"u"||I.name!=="ErrnoError")throw I;return-I.errno}}var xy=(i)=>i%4===0&&(i%100!==0||i%400===0),Ty=[0,31,60,91,121,152,182,213,244,274,305,335],Ry=[0,31,59,90,120,151,181,212,243,273,304,334],Ay=(i)=>(xy(i.getFullYear())?Ty:Ry)[i.getMonth()]+i.getDate()-1;function Dy(i,u){i=cn(i);var _=new Date(i*1000);Ye[u>>2]=_.getSeconds(),Ye[u+4>>2]=_.getMinutes(),Ye[u+8>>2]=_.getHours(),Ye[u+12>>2]=_.getDate(),Ye[u+16>>2]=_.getMonth(),Ye[u+20>>2]=_.getFullYear()-1900,Ye[u+24>>2]=_.getDay();var f=Ay(_)|0;Ye[u+28>>2]=f,Ye[u+36>>2]=-(_.getTimezoneOffset()*60);var l=new Date(_.getFullYear(),0,1),d=new Date(_.getFullYear(),6,1).getTimezoneOffset(),h=l.getTimezoneOffset(),E=(d!=h&&_.getTimezoneOffset()==Math.min(h,d))|0;Ye[u+32>>2]=E}function Oy(i,u,_,f,l,d,h){l=cn(l);try{var E=je.getStreamFromFD(f),b=y.mmap(E,i,l,u,_),I=b.ptr;return Ye[d>>2]=b.allocated,rt[h>>2]=I,0}catch(V){if(typeof y>"u"||V.name!=="ErrnoError")throw V;return-V.errno}}function Iy(i,u,_,f,l,d){d=cn(d);try{var h=je.getStreamFromFD(l);if(_&2)je.doMsync(i,h,u,f,d)}catch(E){if(typeof y>"u"||E.name!=="ErrnoError")throw E;return-E.errno}}var Cy=(i,u,_,f)=>{var l=new Date().getFullYear(),d=new Date(l,0,1),h=new Date(l,6,1),E=d.getTimezoneOffset(),b=h.getTimezoneOffset(),I=Math.max(E,b);rt[i>>2]=I*60,Ye[u>>2]=Number(E!=b);var V=(q)=>{var W=q>=0?"-":"+",K=Math.abs(q);return`UTC${W}${String(Math.floor(K/60)).padStart(2,"0")}${String(K%60).padStart(2,"0")}`},U=V(E),N=V(b);if(b<E)Nr(U,_,17),Nr(N,f,17);else Nr(U,f,17),Nr(N,_,17)},tl=()=>performance.now(),rl=()=>Date.now(),Py=1,Ny=(i)=>i>=0&&i<=3;function qy(i,u,_){if(u=cn(u),!Ny(i))return 28;var f;if(i===0)f=rl();else if(Py)f=tl();else return 52;var l=Math.round(f*1000*1000);return At[_>>3]=BigInt(l),0}var nl=()=>2147483648,Ly=()=>nl(),$y=(i)=>{var u=(i-pr.buffer.byteLength+65535)/65536|0;try{return pr.grow(u),Be(),1}catch(_){}},My=(i)=>{var u=Cr.length;i>>>=0;var _=nl();if(i>_)return!1;for(var f=1;f<=4;f*=2){var l=u*(1+0.2/f);if(l=Math.min(l,i+100663296),$y(Math.min(_,Vc(Math.max(i,l),65536))))return!0}return!1},rs={},Fy=()=>s||"./this.program",zn=()=>{if(!zn.strings){var i={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(globalThis.navigator?.language??"C").replace("-","_")+".UTF-8",_:Fy()};for(var u in rs)if(rs[u]===void 0)delete i[u];else i[u]=rs[u];var _=[];for(var u in i)_.push(`${u}=${i[u]}`);zn.strings=_}return zn.strings},zy=(i,u)=>{var _=0,f=0;for(var l of zn()){var d=u+_;rt[i+f>>2]=d,_+=Nr(l,d,1/0)+1,f+=4}return 0},Uy=(i,u)=>{var _=zn();rt[i>>2]=_.length;var f=0;for(var l of _)f+=Ao(l)+1;return rt[u>>2]=f,0};function By(i){try{var u=je.getStreamFromFD(i);return y.close(u),0}catch(_){if(typeof y>"u"||_.name!=="ErrnoError")throw _;return _.errno}}function jy(i,u){try{var _=0,f=0,l=0,d=je.getStreamFromFD(i),h=d.tty?2:y.isDir(d.mode)?3:y.isLink(d.mode)?7:4;return Ht[u]=h,$n[u+2>>1]=l,At[u+8>>3]=BigInt(_),At[u+16>>3]=BigInt(f),0}catch(E){if(typeof y>"u"||E.name!=="ErrnoError")throw E;return E.errno}}var Hy=(i,u,_,f)=>{var l=0;for(var d=0;d<_;d++){var h=rt[u>>2],E=rt[u+4>>2];u+=8;var b=y.read(i,Ht,h,E,f);if(b<0)return-1;if(l+=b,b<E)break;if(typeof f<"u")f+=b}return l};function Wy(i,u,_,f){try{var l=Hy(je.getStreamFromFD(i),u,_);return rt[f>>2]=l,0}catch(d){if(typeof y>"u"||d.name!=="ErrnoError")throw d;return d.errno}}function Zy(i,u,_,f){u=cn(u);try{if(isNaN(u))return 61;var l=je.getStreamFromFD(i);if(y.llseek(l,u,_),At[f>>3]=BigInt(l.position),l.getdents&&u===0&&_===0)l.getdents=null;return 0}catch(d){if(typeof y>"u"||d.name!=="ErrnoError")throw d;return d.errno}}function Ky(i){try{var u=je.getStreamFromFD(i);return u.stream_ops?.fsync?.(u)}catch(_){if(typeof y>"u"||_.name!=="ErrnoError")throw _;return _.errno}}var Gy=(i,u,_,f)=>{var l=0;for(var d=0;d<_;d++){var h=rt[u>>2],E=rt[u+4>>2];u+=8;var b=y.write(i,Ht,h,E,f);if(b<0)return-1;if(l+=b,b<E)break;if(typeof f<"u")f+=b}return l};function Vy(i,u,_,f){try{var l=Gy(je.getStreamFromFD(i),u,_);return rt[f>>2]=l,0}catch(d){if(typeof y>"u"||d.name!=="ErrnoError")throw d;return d.errno}}if(y.createPreloadedFile=ny,y.preloadFile=Yc,y.staticInit(),Me(),r.noExitRuntime)r.noExitRuntime;if(r.preloadPlugins)Qc=r.preloadPlugins;if(r.print)A=r.print;if(r.printErr)F=r.printErr;if(r.wasmBinary)X=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=pr;var ol;function Jy(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,ol=i.emscripten_builtin_memalign,i._emscripten_stack_restore,i._emscripten_stack_alloc,i.emscripten_stack_get_current,i.__indirect_function_table}var il={__syscall_chmod:iy,__syscall_faccessat:sy,__syscall_fchmod:ay,__syscall_fchown32:cy,__syscall_fcntl64:ly,__syscall_fstat64:uy,__syscall_ftruncate64:py,__syscall_getcwd:hy,__syscall_ioctl:gy,__syscall_lstat64:my,__syscall_mkdirat:_y,__syscall_newfstatat:yy,__syscall_openat:by,__syscall_readlinkat:wy,__syscall_rmdir:vy,__syscall_stat64:Ey,__syscall_unlinkat:Sy,__syscall_utimensat:ky,_localtime_js:Dy,_mmap_js:Oy,_munmap_js:Iy,_tzset_js:Cy,clock_time_get:qy,emscripten_date_now:rl,emscripten_get_heap_max:Ly,emscripten_get_now:tl,emscripten_resize_heap:My,environ_get:zy,environ_sizes_get:Uy,fd_close:By,fd_fdstat_get:jy,fd_read:Wy,fd_seek:Zy,fd_sync:Ky,fd_write:Vy,memory:pr};function ns(){if(Pr>0){Fn=ns;return}if(He(),Pr>0){Fn=ns;return}function i(){if(r.calledRun=!0,he)return;Ze(),_e?.(r),r.onRuntimeInitialized?.(),zt()}if(r.setStatus)r.setStatus("Running..."),setTimeout(()=>{setTimeout(()=>r.setStatus(""),1),i()},1);else i()}var ln=await z_();if(ns(),r.runSQLite3PostLoadInit=async function(i,u,_){delete u.runSQLite3PostLoadInit,globalThis.sqlite3ApiBootstrap=async function f(l=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),h=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},l);Object.assign(h,{allocExportName:h.useStdAlloc?"malloc":"sqlite3_malloc",deallocExportName:h.useStdAlloc?"free":"sqlite3_free",reallocExportName:h.useStdAlloc?"realloc":"sqlite3_realloc"}),["exports","memory","functionTable","wasmfsOpfsDir"].forEach((S)=>{if(typeof h[S]==="function")h[S]=h[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 U extends Error{constructor(...S){let C;if(S.length)if(V(S[0]))if(C=S[0],S.length===1)super(I(S[0]));else{let G=I(C);if(typeof S[1]==="object")super(G,S[1]);else{S[0]=G+":";super(S.join(" "))}}else if(S.length===2&&typeof S[1]==="object")super(...S);else super(S.join(" "));this.resultCode=C||E.SQLITE_ERROR,this.name="SQLite3Error"}}U.toss=(...S)=>{throw new U(...S)};let N=U.toss;if(h.wasmfsOpfsDir&&!/^\/[^/]+$/.test(h.wasmfsOpfsDir))N("config.wasmfsOpfsDir must be falsy or in the form '/dir-name'.");let q=function S(C){if(!S._max)S._max=BigInt("0x7fffffffffffffff"),S._min=~S._max;return C>=S._min&&C<=S._max},W=(S)=>S>=-2147483647n-1n&&S<=2147483647n,K=function S(C){if(!S._min)S._min=Number.MIN_SAFE_INTEGER,S._max=Number.MAX_SAFE_INTEGER;return C>=S._min&&C<=S._max},ue=(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),Q=(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 j 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"}}j.toss=(...S)=>{throw new j(...S)},Object.assign(E,{sqlite3_bind_blob:void 0,sqlite3_bind_text:void 0,sqlite3_create_function_v2:(S,C,G,oe,Z,ge,we,ye,ve)=>{},sqlite3_create_function:(S,C,G,oe,Z,ge,we,ye)=>{},sqlite3_create_window_function:(S,C,G,oe,Z,ge,we,ye,ve,M)=>{},sqlite3_prepare_v3:(S,C,G,oe,Z,ge)=>{},sqlite3_prepare_v2:(S,C,G,oe,Z)=>{},sqlite3_exec:(S,C,G,oe,Z)=>{},sqlite3_randomness:(S,C)=>{}});let J={affirmBindableTypedArray:Q,flexibleString:ee,bigIntFits32:W,bigIntFits64:q,bigIntFitsDouble:K,isBindableTypedArray:O,isInt32:V,isSQLableTypedArray:R,isTypedArray:ue,isUIThread:()=>globalThis.window===globalThis&&!!globalThis.document,toss:function(...S){throw Error(S.join(" "))},toss3:N,typedArrayPart:b.typedArrayPart,nu:d,assert:function(S,C){if(!S)J.toss("Assertion failed:",C)},affirmDbHeader:function(S){if(S instanceof ArrayBuffer)S=new Uint8Array(S);let C="SQLite format 3";if(15>S.byteLength)N("Input does not contain an SQLite3 database header.");for(let G=0;G<15;++G)if(C.charCodeAt(G)!==S[G])N("Input does not contain an SQLite3 database header.")},affirmIsDb:function(S){if(S instanceof ArrayBuffer)S=new Uint8Array(S);let C=S.byteLength;if(C<512||C%512!==0)N("Byte array size",C,"is invalid for an SQLite3 db.");J.affirmDbHeader(S)}};Object.assign(b,{exports:h.exports||N("Missing API config.exports (WASM module exports)."),memory:h.memory||h.exports.memory||N("API config object requires a WebAssembly.Memory object","in either config.exports.memory (exported)","or config.memory (imported)."),pointerSize:typeof h.exports.sqlite3_libversion()==="number"?4:8,bigIntEnabled:!!h.bigIntEnabled,functionTable:h.functionTable,alloc:void 0,realloc:void 0,dealloc:void 0}),b.allocFromTypedArray=function(S){if(S instanceof ArrayBuffer)S=new Uint8Array(S);Q(S);let C=b.alloc(S.byteLength||1);return b.heapForSize(S.constructor).set(S.byteLength?S:[0],Number(C)),C};{let{allocExportName:S,deallocExportName:C,reallocExportName:G}=h;for(let oe of[S,C,G])if(!(b.exports[oe]instanceof Function))N("Missing required exports[",oe,"] function.");b.alloc=function oe(Z){return oe.impl(Z)||j.toss("Failed to allocate",Z," bytes.")},b.alloc.impl=b.exports[S],b.realloc=function oe(Z,ge){let we=oe.impl(b.ptr.coerce(Z),ge);return ge?we||j.toss("Failed to reallocate",ge," bytes."):b.ptr.null},b.realloc.impl=b.exports[G],b.dealloc=function oe(Z){oe.impl(b.ptr.coerce(Z))},b.dealloc.impl=b.exports[C]}b.compileOptionUsed=function S(C){if(!arguments.length){if(S._result)return S._result;else if(!S._opt)S._rx=/^([^=]+)=(.+)/,S._rxInt=/^-?\d+$/,S._opt=function(we,ye){let ve=S._rx.exec(we);ye[0]=ve?ve[1]:we,ye[1]=ve?S._rxInt.test(ve[2])?+ve[2]:ve[2]:!0};let G=d(),oe=[0,0],Z=0,ge;while(ge=E.sqlite3_compileoption_get(Z++))S._opt(ge,oe),G[oe[0]]=oe[1];return S._result=G}else if(Array.isArray(C)){let G=d();return C.forEach((oe)=>{G[oe]=E.sqlite3_compileoption_used(oe)}),G}else if(typeof C==="object")return Object.keys(C).forEach((G)=>{C[G]=E.sqlite3_compileoption_used(G)}),C;return typeof C==="string"?!!E.sqlite3_compileoption_used(C):!1},b.pstack=d({restore:b.exports.sqlite3__wasm_pstack_restore,alloc:function(S){if(typeof S==="string"&&!(S=b.sizeofIR(S)))j.toss("Invalid value for pstack.alloc(",arguments[0],")");return b.exports.sqlite3__wasm_pstack_alloc(S)||j.toss("Could not allocate",S,"bytes from the pstack.")},allocChunks:function(S,C){if(typeof C==="string"&&!(C=b.sizeofIR(C)))j.toss("Invalid size value for allocChunks(",arguments[1],")");let G=b.pstack.alloc(S*C),oe=[G],Z=1,ge=C;for(;Z<S;++Z,ge+=C)oe.push(b.ptr.add(G,ge));return oe},allocPtr:(S=1,C=!0)=>S===1?b.pstack.alloc(C?8:b.ptr.size):b.pstack.allocChunks(S,C?8:b.ptr.size),call:function(S){let C=b.pstack.pointer;try{return S(pe)}finally{b.pstack.restore(C)}}}),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 C=S[0];if(C.byteLength===0)return b.exports.sqlite3_randomness(0,b.ptr.null),C;let G=b.pstack.pointer;try{let oe=C.byteLength,Z=0,ge=b.exports.sqlite3_randomness,we=b.heap8u(),ye=oe<512?oe:512,ve=b.pstack.alloc(ye);do{let M=oe>ye?ye:oe;ge(M,ve),C.set(b.typedArrayPart(we,ve,b.ptr.add(ve,M)),Z),oe-=M,Z+=M}while(oe>0)}catch(oe){h.error("Highly unexpected (and ignored!) exception in sqlite3_randomness():",oe)}finally{b.pstack.restore(G)}return C}b.exports.sqlite3_randomness(...S)},E.sqlite3_wasmfs_opfs_dir=function(){if(this.dir!==void 0)return this.dir;let S=h.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(C){return this.dir=""}}.bind(d()),E.sqlite3_wasmfs_filename_is_persistent=function(S){let C=E.sqlite3_wasmfs_opfs_dir();return C&&S?S.startsWith(C+"/"):!1},E.sqlite3_js_db_uses_vfs=function(S,C,G=0){try{let oe=E.sqlite3_vfs_find(C);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,G)?oe:!1}catch(oe){return!1}},E.sqlite3_js_vfs_list=function(){let S=[],C=E.sqlite3_vfs_find(b.ptr.null);while(C){let G=new E.sqlite3_vfs(C);S.push(b.cstrToJs(G.$zName)),C=G.$pNext,G.dispose()}return S},E.sqlite3_js_db_export=function(S,C=0){if(S=b.xWrap.testConvertArg("sqlite3*",S),!S)N("Invalid sqlite3* argument.");if(!b.bigIntEnabled)N("BigInt support is not enabled.");let G=b.scopedAllocPush(),oe;try{let Z=b.scopedAlloc(8+b.ptr.size),ge=b.ptr.add(Z,8),we=C?b.isPtr(C)?C:b.scopedAllocCString(""+C):b.ptr.null,ye=b.exports.sqlite3__wasm_db_serialize(S,we,ge,Z,0);if(ye)N("Database serialization failed with code",pe.capi.sqlite3_js_rc_str(ye));oe=b.peekPtr(ge);let ve=b.peek(Z,"i64");return ye=ve?b.heap8u().slice(Number(oe),Number(oe)+Number(ve)):new Uint8Array,ye}finally{if(oe)b.exports.sqlite3_free(oe);b.scopedAllocPop(G)}},E.sqlite3_js_db_vfs=(S,C=b.ptr.null)=>J.sqlite3__wasm_db_vfs(S,C),E.sqlite3_js_aggregate_context=(S,C)=>E.sqlite3_aggregate_context(S,C)||(C?j.toss("Cannot allocate",C,"bytes for sqlite3_aggregate_context()"):0),E.sqlite3_js_posix_create_file=function(S,C,G){let oe;if(C&&b.isPtr(C))oe=C;else if(C instanceof ArrayBuffer||C instanceof Uint8Array){if(oe=b.allocFromTypedArray(C),arguments.length<3||!J.isInt32(G)||G<0)G=C.byteLength}else U.toss("Invalid 2nd argument for sqlite3_js_posix_create_file().");try{if(!J.isInt32(G)||G<0)U.toss("Invalid 3rd argument for sqlite3_js_posix_create_file().");let Z=J.sqlite3__wasm_posix_create_file(S,oe,G);if(Z)U.toss("Creation of file failed with sqlite3 result code",E.sqlite3_js_rc_str(Z))}finally{if(oe&&oe!==C)b.dealloc(oe)}},E.sqlite3_js_vfs_create_file=function(S,C,G,oe){h.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 Z;if(G)if(b.isPtr(G))Z=G;else{if(G instanceof ArrayBuffer)G=new Uint8Array(G);if(G instanceof Uint8Array){if(Z=b.allocFromTypedArray(G),arguments.length<4||!J.isInt32(oe)||oe<0)oe=G.byteLength}else U.toss("Invalid 3rd argument type for sqlite3_js_vfs_create_file().")}else Z=0;if(!J.isInt32(oe)||oe<0){if(Z&&Z!==G)b.dealloc(Z);U.toss("Invalid 4th argument for sqlite3_js_vfs_create_file().")}try{let ge=J.sqlite3__wasm_vfs_create_file(S,C,Z,oe);if(ge)U.toss("Creation of file failed with sqlite3 result code",E.sqlite3_js_rc_str(ge))}finally{if(Z&&Z!==G)b.dealloc(Z)}},E.sqlite3_js_sql_to_string=(S)=>{if(typeof S==="string")return S;let C=ee(v);return C===v?void 0:C},E.sqlite3_db_config=function(S,C,...G){switch(C){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,C,G[0],G[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,C,G[0],G[1],G[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,C,G[0]);default:return E.SQLITE_MISUSE}}.bind(d()),E.sqlite3_value_to_js=function(S,C=!0){let G,oe=E.sqlite3_value_type(S);switch(oe){case E.SQLITE_INTEGER:if(b.bigIntEnabled){if(G=E.sqlite3_value_int64(S),J.bigIntFitsDouble(G))G=Number(G)}else G=E.sqlite3_value_double(S);break;case E.SQLITE_FLOAT:G=E.sqlite3_value_double(S);break;case E.SQLITE_TEXT:G=E.sqlite3_value_text(S);break;case E.SQLITE_BLOB:{let Z=E.sqlite3_value_bytes(S),ge=E.sqlite3_value_blob(S);if(Z&&!ge)pe.WasmAllocError.toss("Cannot allocate memory for blob argument of",Z,"byte(s)");G=Z?b.heap8u().slice(Number(ge),Number(ge)+Number(Z)):null;break}case E.SQLITE_NULL:G=null;break;default:if(C)N(E.SQLITE_MISMATCH,"Unhandled sqlite3_value_type():",oe);G=void 0}return G},E.sqlite3_values_to_js=function(S,C,G=!0){let oe,Z=[];for(oe=0;oe<S;++oe)Z.push(E.sqlite3_value_to_js(b.peekPtr(b.ptr.add(C,b.ptr.size*oe)),G));return Z},E.sqlite3_result_error_js=function(S,C){if(C instanceof j)E.sqlite3_result_error_nomem(S);else E.sqlite3_result_error(S,""+C,-1)},E.sqlite3_result_js=function(S,C){if(C instanceof Error){E.sqlite3_result_error_js(S,C);return}try{switch(typeof C){case"undefined":break;case"boolean":E.sqlite3_result_int(S,C?1:0);break;case"bigint":if(J.bigIntFits32(C))E.sqlite3_result_int(S,Number(C));else if(J.bigIntFitsDouble(C))E.sqlite3_result_double(S,Number(C));else if(b.bigIntEnabled)if(J.bigIntFits64(C))E.sqlite3_result_int64(S,C);else N("BigInt value",C.toString(),"is too BigInt for int64.");else N("BigInt value",C.toString(),"is too BigInt.");break;case"number":{let G;if(J.isInt32(C))G=E.sqlite3_result_int;else if(b.bigIntEnabled&&Number.isInteger(C)&&J.bigIntFits64(BigInt(C)))G=E.sqlite3_result_int64;else G=E.sqlite3_result_double;G(S,C);break}case"string":{let[G,oe]=b.allocCString(C,!0);E.sqlite3_result_text(S,G,oe,E.SQLITE_WASM_DEALLOC);break}case"object":if(C===null){E.sqlite3_result_null(S);break}else if(J.isBindableTypedArray(C)){let G=b.allocFromTypedArray(C);E.sqlite3_result_blob(S,G,C.byteLength,E.SQLITE_WASM_DEALLOC);break}default:N("Don't not how to handle this UDF result value:",typeof C,C)}}catch(G){E.sqlite3_result_error_js(S,G)}},E.sqlite3_column_js=function(S,C,G=!0){let oe=E.sqlite3_column_value(S,C);return oe===0?void 0:E.sqlite3_value_to_js(oe,G)};{let S=function(C,G,oe){if(oe=E[oe],!this.ptr)this.ptr=b.allocPtr();else b.pokePtr(this.ptr,0);let Z=oe(C,G,this.ptr);if(Z)return U.toss(Z,arguments[2]+"() failed with code "+Z);let ge=b.peekPtr(this.ptr);return ge?E.sqlite3_value_to_js(ge,!0):void 0}.bind(d());E.sqlite3_preupdate_new_js=(C,G)=>S(C,G,"sqlite3_preupdate_new"),E.sqlite3_preupdate_old_js=(C,G)=>S(C,G,"sqlite3_preupdate_old"),E.sqlite3changeset_new_js=(C,G)=>S(C,G,"sqlite3changeset_new"),E.sqlite3changeset_old_js=(C,G)=>S(C,G,"sqlite3changeset_old")}E.sqlite3_js_retry_busy=function(S,C,G){for(let oe=1;oe<=S;++oe)try{if(G&&oe>1)G(oe);let Z=C();if(E.SQLITE_BUSY===Z){if(oe===S)throw new U(Z,["sqlite3_js_retry_busy() max retry attempts (",S,") reached."].join(""));continue}return Z}catch(Z){if(oe<S&&Z instanceof U&&Z.resultCode===E.SQLITE_BUSY)continue;throw Z}};let pe={WasmAllocError:j,SQLite3Error:U,capi:E,util:J,wasm:b,config:h,version:d(),client:void 0,asyncPostInit:async function S(){if(S.isReady instanceof Promise)return S.isReady;let C=this.initializersAsync;delete this.initializersAsync;let G=async()=>{if(!pe.__isUnderTest)delete pe.util,delete pe.StructBinder,delete pe.opfs;return pe},oe=(ge)=>{throw h.error("an async sqlite3 initializer failed:",ge),ge};if(!C||!C.length)return S.isReady=G().catch(oe);C=C.map((ge)=>ge instanceof Function?async(we)=>ge(pe):ge),C.push(G);let Z=Promise.resolve(pe);while(C.length)Z=Z.then(C.shift());return S.isReady=Z.catch(oe)}.bind(f),scriptInfo:void 0};if(typeof _<"u")pe.__isUnderTest=!!_;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 u<"u")pe.config.emscripten=u;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(l){if(l.bigIntEnabled===void 0)l.bigIntEnabled=!!globalThis.BigInt64Array;let d=(...g)=>{throw Error(g.join(" "))};if(!l.pointerSize&&!l.pointerIR&&l.alloc&&l.dealloc){let g=l.alloc(1);l.pointerSize=typeof g==="bigint"?8:4,l.dealloc(g)}if(l.pointerSize&&!l.pointerIR)l.pointerIR=l.pointerSize===4?"i32":"i64";let h=l.pointerIR??="i32",E=l.pointerSize??=h==="i32"?4:h==="i64"?8:0;if(delete l.pointerSize,delete l.pointerIR,h!=="i32"&&h!=="i64")d("Invalid pointerIR:",h);else if(E!==8&&E!==4)d("Invalid pointerSize:",E);let b=l.bigIntEnabled?(g)=>BigInt(g||0):(g)=>d("BigInt support is disabled in this build."),V=E===4?(g)=>Number(g||0):b,U=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(l,"ptr",{enumerable:!0,get:()=>g,set:()=>d("The ptr property is read-only.")}),function w(T,P){return Object.defineProperty(g,T,{enumerable:!0,get:()=>P,set:()=>d("ptr["+T+"] is read-only.")}),w}("null",U)("size",E)("ir",h)("coerce",V)("add",N)("addn",h===4?N:(...w)=>Number(N(...w)))}if(!l.exports)Object.defineProperty(l,"exports",{enumerable:!0,configurable:!0,get:()=>l.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"),l.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 W=function(){if(!q.memory)q.memory=l.memory instanceof WebAssembly.Memory?l.memory:l.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),l.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};l.heap8=()=>W().HEAP8,l.heap8u=()=>W().HEAP8U,l.heap16=()=>W().HEAP16,l.heap16u=()=>W().HEAP16U,l.heap32=()=>W().HEAP32,l.heap32u=()=>W().HEAP32U,l.heapForSize=function(g,w=!0){let T=q.memory&&q.heapSize===q.memory.buffer.byteLength?q:W();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(l.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 K=l.functionTable;delete l.functionTable,l.functionTable=K?()=>K:()=>l.exports.__indirect_function_table,l.functionEntry=function(g){let w=l.functionTable();return g<w.length?w.get(V(g)):void 0},l.jsFuncToWasm=function g(w,T){if(!g._)g._={sigTypes:Object.assign(Object.create(null),{i:"i32",p:h,P:h,s:h,j:"i64",f:"f32",d:"f64"}),typeCodes:Object.assign(Object.create(null),{f64:124,f32:125,i64:126,i32:127}),uleb128Encode:(D,L,Y)=>{if(Y<128)D[L](Y);else D[L](Y%128|128,Y>>7)},rxJSig:/^(\w)\((\w*)\)$/,sigParams:(D)=>{let L=g._.rxJSig.exec(D);return L?L[2]:D.substr(1)},letterType:(D)=>g._.sigTypes[D]||d("Invalid signature letter:",D),pushSigType:(D,L)=>D.push(g._.typeCodes[g._.letterType(L)])};if(typeof w==="string"){let D=T;T=w,w=D}let P=g._,te=P.sigParams(T),se=[1,96];P.uleb128Encode(se,"push",te.length);for(let D of te)P.pushSigType(se,D);if(T[0]==="v")se.push(0);else se.push(1),P.pushSigType(se,T[0]);return P.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 ue=function(w,T,P){if(P&&!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=l.functionTable(),se=V(te.length),D;while(D=q.freeFuncIndexes.pop())if(te.get(D)){D=null;continue}else break;if(!D)D=V(se),te.grow(V(1));try{if(te.set(D,w),P)q.scopedAlloc.pushPtr(D);return D}catch(L){if(!(L instanceof TypeError)){if(D===se)q.freeFuncIndexes.push(se);throw L}}try{let L=l.jsFuncToWasm(w,T);if(te.set(D,L),P)q.scopedAlloc.pushPtr(D)}catch(L){if(D===se)q.freeFuncIndexes.push(se);throw L}return D};l.installFunction=(g,w)=>ue(g,w,!1),l.scopedInstallFunction=(g,w)=>ue(g,w,!0),l.uninstallFunction=function(g){if(!g&&U!==g)return;let w=l.functionTable();q.freeFuncIndexes.push(g);let T=w.get(g);return w.set(g,null),T},l.peek=function(w,T="i8"){if(T.endsWith("*"))T=h;let P=q.memory&&q.heapSize===q.memory.buffer.byteLength?q:W(),te=Array.isArray(w)?[]:void 0,se;do{if(te)w=arguments[0].shift();switch(T){case"i1":case"i8":se=P.HEAP8[Number(w)>>0];break;case"i16":se=P.HEAP16[Number(w)>>1];break;case"i32":se=P.HEAP32[Number(w)>>2];break;case"float":case"f32":se=P.HEAP32F[Number(w)>>2];break;case"double":case"f64":se=Number(P.HEAP64F[Number(w)>>3]);break;case"i64":if(P.HEAP64){se=b(P.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},l.poke=function(g,w,T="i8"){if(T.endsWith("*"))T=h;let P=q.memory&&q.heapSize===q.memory.buffer.byteLength?q:W();for(let te of Array.isArray(g)?g:[g])switch(T){case"i1":case"i8":P.HEAP8[Number(te)>>0]=w;continue;case"i16":P.HEAP16[Number(te)>>1]=w;continue;case"i32":P.HEAP32[Number(te)>>2]=w;continue;case"float":case"f32":P.HEAP32F[Number(te)>>2]=w;continue;case"double":case"f64":P.HEAP64F[Number(te)>>3]=w;continue;case"i64":if(P.HEAP64){P.HEAP64[Number(te)>>3]=b(w);continue}default:d("Invalid type for poke(): "+T)}return this},l.peekPtr=(...g)=>l.peek(g.length===1?g[0]:g,h),l.pokePtr=(g,w=0)=>l.poke(g,w,h),l.peek8=(...g)=>l.peek(g.length===1?g[0]:g,"i8"),l.poke8=(g,w)=>l.poke(g,w,"i8"),l.peek16=(...g)=>l.peek(g.length===1?g[0]:g,"i16"),l.poke16=(g,w)=>l.poke(g,w,"i16"),l.peek32=(...g)=>l.peek(g.length===1?g[0]:g,"i32"),l.poke32=(g,w)=>l.poke(g,w,"i32"),l.peek64=(...g)=>l.peek(g.length===1?g[0]:g,"i64"),l.poke64=(g,w)=>l.poke(g,w,"i64"),l.peek32f=(...g)=>l.peek(g.length===1?g[0]:g,"f32"),l.poke32f=(g,w)=>l.poke(g,w,"f32"),l.peek64f=(...g)=>l.peek(g.length===1?g[0]:g,"f64"),l.poke64f=(g,w)=>l.poke(g,w,"f64"),l.getMemValue=l.peek,l.getPtrValue=l.peekPtr,l.setMemValue=l.poke,l.setPtrValue=l.pokePtr,l.isPtr32=(g)=>typeof g==="number"&&g>=0&&g===(g|0),l.isPtr64=(g)=>typeof g==="bigint"?g>=0:l.isPtr32(g),l.isPtr=E===4?l.isPtr32:l.isPtr64,l.cstrlen=function(g){if(!g||!l.isPtr(g))return null;g=Number(g);let w=W().HEAP8U,T=g;for(;w[T]!==0;++T);return T-g};let O=typeof SharedArrayBuffer>"u"?function(){}:SharedArrayBuffer,R=(g)=>g.buffer instanceof O;l.isSharedTypedArray=R;let Q=(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)};l.typedArrayPart=Q;let ee=(g,w,T)=>q.utf8Decoder.decode(Q(g,w,T));l.typedArrayToString=ee,l.cstrToJs=function(g){let w=l.cstrlen(g);return w?ee(W().HEAP8U,Number(g),Number(g)+w):w===null?w:""},l.jstrlen=function(g){if(typeof g!=="string")return null;let w=g.length,T=0;for(let P=0;P<w;++P){let te=g.charCodeAt(P);if(te>=55296&&te<=57343)te=65536+((te&1023)<<10)|g.charCodeAt(++P)&1023;if(te<=127)++T;else if(te<=2047)T+=2;else if(te<=65535)T+=3;else T+=4}return T},l.jstrcpy=function(g,w,T=0,P=-1,te=!0){if(!w||!(w instanceof Int8Array)&&!(w instanceof Uint8Array))d("jstrcpy() target must be an Int8Array or Uint8Array.");if(P=Number(P),T=Number(T),P<0)P=w.length-T;if(!(P>0)||!(T>=0))return 0;let se=0,D=g.length,L=T,Y=T+P-(te?1:0);for(;se<D&&T<Y;++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>=Y)break;w[T++]=ne}else if(ne<=2047){if(T+1>=Y)break;w[T++]=192|ne>>6,w[T++]=128|ne&63}else if(ne<=65535){if(T+2>=Y)break;w[T++]=224|ne>>12,w[T++]=128|ne>>6&63,w[T++]=128|ne&63}else{if(T+3>=Y)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},l.cstrncpy=function(g,w,T){if(!g||!w)d("cstrncpy() does not accept NULL strings.");if(T<0)T=l.cstrlen(strPtr)+1;else if(!(T>0))return 0;let P=l.heap8u(),te=0,se,D=Number(g),L=Number(w);for(;te<T&&(se=P[L+te]);++te)P[D+te]=se;if(te<T)P[D+te++]=0;return te},l.jstrToUintArray=(g,w=!1)=>q.utf8Encoder.encode(w?g+"\x00":g);let j=(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,P){if(j(l,P),typeof g!=="string")return null;let te=q.utf8Encoder.encode(g),se=T(te.length+1),D=se;try{let L=W().HEAP8U;return L.set(te,Number(se)),L[N(se,te.length)]=0,D=U,w?[se,te.length]:se}finally{if(D)l.dealloc(D)}};l.allocCString=(g,w=!1)=>J(g,w,l.alloc,"allocCString()"),l.scopedAllocPush=function(){j(l,"scopedAllocPush");let g=[];return q.scopedAlloc.push(g),g},l.scopedAllocPop=function(g){j(l,"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(l.functionEntry(T))l.uninstallFunction(T);else l.dealloc(T)},l.scopedAlloc=function(g){if(!q.scopedAlloc.length)d("No scopedAllocPush() scope is active.");let w=V(l.alloc(g));return q.scopedAlloc.pushPtr(w)},Object.defineProperty(l.scopedAlloc,"level",{configurable:!1,enumerable:!1,get:()=>q.scopedAlloc.length,set:()=>d("The 'active' property is read-only.")}),l.scopedAllocCString=(g,w=!1)=>J(g,w,l.scopedAlloc,"scopedAllocCString()");let pe=function(g,w){let T=l[g?"scopedAlloc":"alloc"]((w.length+1)*l.ptr.size),P=0;return w.forEach((te)=>{l.pokePtr(N(T,l.ptr.size*P++),l[g?"scopedAllocCString":"allocCString"](""+te))}),l.pokePtr(N(T,l.ptr.size*P),0),T};l.scopedAllocMainArgv=(g)=>pe(!0,g),l.allocMainArgv=(g)=>pe(!1,g),l.cArgvToJs=(g,w)=>{let T=[];for(let P=0;P<g;++P){let te=l.peekPtr(N(w,l.ptr.size*P));T.push(te?l.cstrToJs(te):null)}return T},l.scopedAllocCall=function(g){l.scopedAllocPush();try{return g()}finally{l.scopedAllocPop()}};let S=function(g,w,T){j(l,T);let P=w?"i64":h,te=l[T](g*(w?8:E));if(l.poke(te,0,P),g===1)return te;let se=[te];for(let D=1;D<g;++D)te=N(te,w?8:E),se[D]=te,l.poke(te,0,P);return se};l.allocPtr=(g=1,w=!0)=>S(g,w,"alloc"),l.scopedAllocPtr=(g=1,w=!0)=>S(g,w,"scopedAlloc"),l.xGet=function(g){return l.exports[g]||d("Cannot find exported symbol:",g)};let C=(g,w)=>d(g+"() requires",w,"argument(s).");l.xCall=function(g,...w){let T=g instanceof Function?g:l.xGet(g);if(!(T instanceof Function))d("Exported symbol",g,"is not a function.");if(T.length!==w.length)C(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 G=q.xWrap.convert.arg,oe=q.xWrap.convert.result,Z=V;G.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",G.get("f32")).set("f64",G.get("f32")).set("double",G.get("f64")).set("int",G.get("i32")).set("null",(g)=>g).set(null,G.get("null")).set("**",Z).set("*",Z),oe.set("*",Z).set("pointer",Z).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"])G.set(g+"*",Z),oe.set(g+"*",Z),oe.set(g,G.get(g)||d("Maintenance required: missing arg converter for",g));let ge=(g)=>typeof g==="string"?l.scopedAllocCString(g):V(g);G.set("string",ge).set("utf8",ge),oe.set("string",(g)=>l.cstrToJs(g)).set("utf8",oe.get("string")).set("string:dealloc",(g)=>{try{return g?l.cstrToJs(g):null}finally{l.dealloc(g)}}).set("utf8:dealloc",oe.get("string:dealloc")).set("json",(g)=>JSON.parse(l.cstrToJs(g))).set("json:dealloc",(g)=>{try{return g?JSON.parse(l.cstrToJs(g)):null}finally{l.dealloc(g)}});let we=class{constructor(g){this.name=g.name||"unnamed adapter"}convertArg(g,w,T){d("AbstractArgAdapter must be subclassed.")}};G.FuncPtrAdapter=class g extends we{constructor(w){super(w);if(G.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),P=T.get(w);if(P===void 0)T.set(w,P=[]);return P}convertArg(w,T,P){let te=this.singleton;if(!te&&this.isContext)te=this.contextMap(this.contextKey(T,P));if(te&&te.length===2&&te[0]===w)return te[1];if(w instanceof Function){if(this.callProxy)w=this.callProxy(w);let se=ue(w,this.signature,this.isTransient);if(g.debugFuncInstall)g.debugOut("FuncPtrAdapter installed",this,this.contextKey(T,P),"@"+se,w);if(te){if(te[1]){if(g.debugFuncInstall)g.debugOut("FuncPtrAdapter uninstalling",this,this.contextKey(T,P),"@"+te[1],w);try{q.scopedAlloc.pushPtr(te[1])}catch(D){}}te[0]=arguments[0]||U,te[1]=se}return se}else if(l.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,P),"@"+te[1],w);try{q.scopedAlloc.pushPtr(te[1])}catch(se){}te[0]=te[1]=w||U}return w||U}else throw TypeError("Invalid FuncPtrAdapter argument type. Expecting a function pointer or a "+(this.name?this.name+" ":"")+"function matching signature "+this.signature+".")}},G.FuncPtrAdapter.warnOnUse=!1,G.FuncPtrAdapter.debugFuncInstall=!1,G.FuncPtrAdapter.debugOut=console.debug.bind(console),G.FuncPtrAdapter.bindScopes=["transient","context","singleton","permanent"];let ye=(g)=>G.get(g)||d("Argument adapter not found:",g),ve=(g)=>oe.get(g)||d("Result adapter not found:",g);q.xWrap.convertArg=(g,...w)=>ye(g)(...w),q.xWrap.convertArgNoCheck=(g,...w)=>G.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,l.xWrap=function g(w,T,...P){if(arguments.length===3&&Array.isArray(arguments[2]))P=arguments[2];if(l.isPtr(w))w=l.functionEntry(w)||d("Function pointer not found in WASM function table.");let te=w instanceof Function,se=te?w:l.xGet(w);if(te)w=se.name||"unnamed function";if(P.length!==se.length)C(w,se.length);if(se.length===0&&(T===null||T==="null"))return se;ve(T);for(let L of P)if(L instanceof we)G.set(L,(...Y)=>L.convertArg(...Y));else ye(L);let D=q.xWrap;if(se.length===0)return(...L)=>L.length?C(w,se.length):D.convertResult(T,se.call(null));return function(...L){if(L.length!==se.length)C(w,se.length);let Y=l.scopedAllocPush();try{let ne=0;if(g.debug)console.debug("xWrap() preparing: resultType ",T,"xf",se,"argTypes",P,"args",L);for(;ne<L.length;++ne)L[ne]=D.convertArgNoCheck(P[ne],L[ne],L,ne);if(g.debug)console.debug("xWrap() calling: resultType ",T,"xf",se,"argTypes",P,"args",L);return D.convertResultNoCheck(T,se.apply(null,L))}finally{l.scopedAllocPop(Y)}}};let M=function(g,w,T,P,te,se){if(typeof T==="string"){if(w===1)return se.get(T);else if(w===2){if(!P)return se.delete(T),g;else if(!(P instanceof Function))d(te,"requires a function argument.");return se.set(T,P),g}}d("Invalid arguments to",te)};return l.xWrap.resultAdapter=function g(w,T){return M(g,arguments.length,w,T,"resultAdapter()",oe)},l.xWrap.argAdapter=function g(w,T){return M(g,arguments.length,w,T,"argAdapter()",G)},l.xWrap.FuncPtrAdapter=G.FuncPtrAdapter,l.xCallWrapped=function(g,w,T,...P){if(Array.isArray(arguments[3]))P=arguments[3];return l.xWrap(g,w,T||[]).apply(null,P||[])},l.xWrap.testConvertArg=q.xWrap.convertArg,l.xWrap.testConvertResult=q.xWrap.convertResult,l},globalThis.WhWasmUtilInstaller.yawl=function(l){let d=()=>fetch(l.uri,{credentials:"same-origin"}),h=this,E=function(b){if(l.wasmUtilTarget){let I=(...U)=>{throw Error(U.join(" "))},V=l.wasmUtilTarget;if(V.module=b.module,V.instance=b.instance,!V.instance.exports.memory)V.memory=l?.imports?.env?.memory||I("Missing 'memory' object!");if(!V.alloc&&b.instance.exports.malloc){let U=b.instance.exports;V.alloc=function(N){return U.malloc(N)||I("Allocation of",N,"bytes failed.")},V.dealloc=function(N){N&&U.free(N)}}h(V)}if(b.config=l,l.onload)l.onload(b);return b};return WebAssembly.instantiateStreaming?()=>WebAssembly.instantiateStreaming(d(),l.imports||{}).then(E):()=>d().then((b)=>b.arrayBuffer()).then((b)=>WebAssembly.instantiate(b,l.imports||{})).then(E)}.bind(globalThis.WhWasmUtilInstaller),globalThis.Jaccwabyt=function f(l){let d=(...z)=>{throw Error(z.join(" "))};{let z=l.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.");l.heap=z}["alloc","dealloc"].forEach(function(z){l[z]instanceof Function||d("Config option '"+z+"' must be a function.")});let h=f,{heap:E,alloc:b,dealloc:I}=l;l.realloc;let V=l.log||console.debug.bind(console),U=l.memberPrefix||"",N=l.memberSuffix||"",{BigInt:q,BigInt64Array:W}=globalThis,K=l.bigIntEnabled??!!W,ue,O=l.pointerSize||l.ptrSize||(typeof(ue=b(1))==="bigint"?8:4),R=l.pointerIR||l.ptrIR||(O===4?"i32":"i64");if(ue)I(ue),ue=void 0;if(O!==4&&O!==8)d("Invalid pointer size:",O);if(R!=="i32"&&R!=="i64")d("Invalid pointer representation:",R);let Q=K&&q?(z)=>q(z||0):(z)=>d("BigInt support is disabled in this build."),ee=R=="i32"?Number:Q,j=ee(0),J=function(...z){let ie=j;for(let fe=0;fe<z.length;++fe)ie+=ee(z[fe]);return ie},pe=function(...z){return J(this.pointer,...z)};if(!h.debugFlags)h.__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},h.debugFlags=h.__makeDebugFlags();let S=!0,C=(z)=>z[1]==="(",G=(z)=>z==="p"||z==="P"||z==="s",oe=(z)=>z==="P",Z=(z)=>z?C(z)?"p":z[0]:void 0,ge=function(z){switch(Z(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(Z(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)},ye=W?()=>!0:()=>d("BigInt64Array is not available."),ve=function(z){switch(Z(z)){case"p":case"P":case"s":switch(O){case 4:return"getInt32";case 8:return ye()&&"getBigInt64"}break;case"i":return"getInt32";case"c":return"getInt8";case"C":return"getUint8";case"j":return ye()&&"getBigInt64";case"f":return"getFloat32";case"d":return"getFloat64"}d("Unhandled DataView getter for signature:",z)},M=function(z){switch(Z(z)){case"p":case"P":case"s":switch(O){case 4:return"setInt32";case 8:return ye()&&"setBigInt64"}break;case"i":return"setInt32";case"c":return"setInt8";case"C":return"setUint8";case"j":return ye()&&"setBigInt64";case"f":return"setFloat32";case"d":return"setFloat64"}d("Unhandled DataView setter for signature:",z)},g=function(z){switch(Z(z)){case"i":case"f":case"c":case"C":case"d":return Number;case"j":return Q;case"p":case"P":case"s":switch(O){case 4:return Number;case 8:return Q}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.")},P=function z(ie,fe=!0){let Ee=z.map.get(ie);if(!Ee&&fe)z.map.set(ie,Ee=z.create(ie));return Ee};P.map=new WeakMap,P.create=(z)=>Object.assign(Object.create(null),{o:z,p:void 0,ownsPointer:!1,zod:!1,xb:0});let te=(z)=>P.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),Y=(z)=>L(z)&&z>0,ne=function(z,ie,fe){let Ee=P(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 Ie;while(Ie=ie.ondispose.pop())try{if(Ie instanceof Function)Ie.call(ie);else if(Ie instanceof Pt)Ie.dispose();else if(L(Ie))I(Ie)}catch(Je){console.warn("ondispose() for",z.structName,"@",fe,"threw. NOT propagating it.",Je)}}else if(ie.ondispose instanceof Function)try{ie.ondispose()}catch(Ie){console.warn("ondispose() for",z.structName,"@",fe,"threw. NOT propagating it.",Ie)}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)}},be=()=>({configurable:!1,writable:!1,iterable:!1}),xe=(z)=>({...be(),value:z}),Pe=function(ie,fe,Ee){let Ie,Je=(Ge)=>{Y(Ge)||d("Invalid pointer value",arguments[0],"for",ie.structName,"constructor.")};if(arguments.length>=3)if(Ee&&typeof Ee==="object")Ie=Ee,Ee=Ie?.wrap;else Je(Ee),Ie={wrap:Ee};else Ie={};let ht=!Ee,Dt=0,Nt=!1;if(Ee)Je(Ee),Nt=!!Ie?.takeOwnership;else{let Ge=Ie?.extraBytes??0;if(Ge<0||Ge!==(Ge|0))d("Invalid extraBytes value:",Ie?.extraBytes);Dt=ie.structInfo.sizeof+Ge,Ee=b(Dt)||d("Allocation of",ie.structName,"structure failed."),Nt=!0}try{if(Ie?.debugFlags)fe.debugFlags(Ie.debugFlags);if(ie.debugFlags.__flags.alloc)V("debug.alloc:",ht?"":"EXTERNAL",ie.structName,"instance:",ie.structInfo.sizeof,"bytes @"+Ee);if(ht)E().fill(0,Number(Ee),Number(Ee)+Dt);let Ge=P(fe);if(Ge.p=Ee,Ge.ownsPointer=Nt,Ge.xb=Dt?Dt-ie.structInfo.sizeof:0,Ge.zod=!!Ie?.zeroOnDispose,Ie?.ondispose&&Ie.ondispose!==Ee)fe.addOnDispose(Ie.ondispose)}catch(Ge){throw ne(ie,fe,Ee),Ge}},$e=function z(ie){return z.rxSig1??=/^[ipPsjfdcC]$/,z.rxSig2??=/^[vipPsjfdcC]\([ipPsjfdcC]*\)$/,z.rxSig1.test(ie)||z.rxSig2.test(ie)},Ve=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),ft=function(z,ie,fe,Ee){let Ie=Ve(z)[ie];if(arguments.length===3)return Ie[fe];if(Ee)return Ie[fe]=Ee;return delete Ie[fe]},Wt=function(z,...ie){return ft(this,0,z,...ie)},qr=function(z,ie){$e(ie)&&d(z,"(",ie,") collides with a data type signature.")},B=function(z,...ie){return qr("Setter adaptor",z),ft(this,1,z,...ie)},re=function(z,...ie){return qr("Struct adaptor",z),ft(this,2,z,...ie)},ae=function(z,ie){let fe=typeof ie==="string"?ft(z,2,ie):ie;if(typeof fe!=="object")d("Invalid struct mapping object. Arg =",ie,JSON.stringify(fe));return fe},Se=xe((z)=>U+z+N),De=function(z,ie,fe=!0){let Ee=z.members[ie];if(!Ee&&(U||N)){for(let Ie of Object.values(z.members))if(Ie.key===ie){Ee=Ie;break}if(!Ee&&fe)d(w(z.name||z.structName,ie),"is not a mapped struct member.")}return Ee},Ce=function z(ie,fe,Ee=!1){if(!z._)z._=(Je)=>Je.replace(/[^vipPsjrdcC]/g,"").replace(/[pPscC]/g,"i");let Ie=De(ie.structInfo,fe,!0);return Ee?z._(Ie.signature):Ie.signature},Re=xe(function(){let z=[];for(let ie of Object.keys(this.structInfo.members))z.push(this.memberKey(ie));return z}),Le=new TextDecoder("utf-8"),Ke=new TextEncoder,tt=typeof SharedArrayBuffer>"u"?function(){}:SharedArrayBuffer,Ue=function(z,ie,fe){if(O===8)ie=Number(ie),fe=Number(fe);return Le.decode(z.buffer instanceof tt?z.slice(ie,fe):z.subarray(ie,fe))},vt=function(z,ie,fe=!1){let Ee=De(z.structInfo,ie,fe);return Ee&&Ee.signature.length===1&&Ee.signature[0]==="s"?Ee:!1},Zt=function(z){if(z.signature==="s")return;d("Invalid member type signature for C-string value:",JSON.stringify(z))},un=function(ie,fe){let Ee=De(ie.structInfo,fe,!0);Zt(Ee);let Ie=ie[Ee.key];if(!Ie)return null;let Je=Ie,ht=E();for(;ht[Je]!==0;++Je);return Ie===Je?"":Ue(ht,Ie,Je)},Xt=function(z,...ie){if(z.ondispose){if(!Array.isArray(z.ondispose))z.ondispose=[z.ondispose]}else z.ondispose=[];z.ondispose.push(...ie)},Lr=function(z){let ie=Ke.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},Un=function(z,ie,fe){let Ee=De(z.structInfo,ie,!0);Zt(Ee);let Ie=Lr(fe);return z[Ee.key]=Ie,Xt(z,Ie),z},Pt=function(ie,fe){if(arguments[2]!==xe)d("Do not call the StructType constructor","from client-level code.");Object.defineProperties(this,{structName:xe(ie),structInfo:xe(fe)})};Pt.prototype=Object.create(null,{dispose:xe(function(){ne(this.constructor,this)}),lookupMember:xe(function(z,ie=!0){return De(this.structInfo,z,ie)}),memberToJsString:xe(function(z){return un(this,z)}),memberIsString:xe(function(z,ie=!0){return vt(this,z,ie)}),memberKey:Se,memberKeys:Re,memberSignature:xe(function(z,ie=!1){return Ce(this,z,ie)}),memoryDump:xe(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 P(this,!1)?.xb??0}},zeroOnDispose:{configurable:!1,enumerable:!1,get:function(){return P(this,!1)?.zod??!!this.structInfo.zeroOnDispose}},pointer:{configurable:!1,enumerable:!1,get:function(){return P(this,!1)?.p},set:()=>d("Cannot assign the 'pointer' property of a struct.")},setMemberCString:xe(function(z,ie){return Un(this,z,ie)})}),Object.assign(Pt.prototype,{addOnDispose:function(...z){return Xt(this,...z),this}}),Object.defineProperties(Pt,{allocCString:xe(Lr),isA:xe((z)=>z instanceof Pt),hasExternalPointer:xe((z)=>{let ie=P(z,!1);return!!(ie?.p&&!ie?.ownsPointer)}),memberKey:Se});let Oo=function(z){return z.get||(z.adaptGet?Ut.adaptGet(z.adaptGet):void 0)},sl=function(z){return z.set||(z.adaptSet?Ut.adaptSet(z.adaptSet):void 0)},Xy=function z(ie,fe,Ee){let Ie=z.innerStructs??=new Map,Je=ie.memberKey(fe);if(Ee.signature!==void 0)d("'signature' cannot be used on an embedded struct (",ie.structName,".",Je,").");if(sl(Ee))d("'set' and 'adaptSet' are not permitted for nested struct members.");Ee.structName??=ie.structName+"::"+fe,Ee.key=Je,Ee.name=fe,Ee.constructor=this.call(this,Ee.structName,Ee);let ht=Oo(Ee),Dt=Object.assign(Object.create(null),{configurable:!1,enumerable:!1,set:T(ie.structName,Je),get:function(){let Nt=this.debugFlags.__flags,Ge=this.pointer,gt=Ge+"."+Je,Ne=Ie.get(gt);if(Nt.getter)V("debug.getter: k =",gt);if(!Ne)Ne=new Ee.constructor(J(Ge,Ee.offset)),Ie.set(gt,Ne),this.addOnDispose(()=>Ne.dispose()),Ne.addOnDispose(()=>Ie.delete(gt));if(ht)Ne=ht.apply(this,[Ne,Je]);if(Nt.getter)V("debug.getter: result =",Ne);return Ne}});Object.defineProperty(ie.prototype,Je,Dt)},Qy=function z(ie,fe,Ee){if(Ee=ae(this,Ee),Ee.members)return Xy.call(this,ie,fe,Ee);if(!z.cache){z.cache={getters:{},setters:{},sw:{}};let gt=["i","c","C","p","P","s","f","d","v()"];if(K)gt.push("j");gt.forEach(function(Ne){z.cache.getters[Ne]=ve(Ne),z.cache.setters[Ne]=M(Ne),z.cache.sw[Ne]=g(Ne)}),z.sigCheck=function(Ne,pt,Io,cl){if(Object.prototype.hasOwnProperty.call(Ne,Io))d(Ne.structName,"already has a property named",Io+".");$e(cl)||d("Malformed signature for",w(Ne.structName,pt)+":",cl)}}let Ie=ie.memberKey(fe);z.sigCheck(ie.prototype,fe,Ie,Ee.signature),Ee.key=Ie,Ee.name=fe;let Je=Z(Ee.signature),ht=w(ie.structName,Ie),Dt=ie.debugFlags.__flags,Nt=Oo(Ee),Ge=Object.create(null);if(Ge.configurable=!1,Ge.enumerable=!1,Ge.get=function(){if(Dt.getter)V("debug.getter:",z.cache.getters[Je],"for",ge(Je),ht,"@",this.pointer,"+",Ee.offset,"sz",Ee.sizeof);let gt=new DataView(E().buffer,Number(this.pointer)+Ee.offset,Ee.sizeof)[z.cache.getters[Je]](0,S);if(Nt)gt=Nt.apply(this,[Ie,gt]);if(Dt.getter)V("debug.getter:",ht,"result =",gt);return gt},Ee.readOnly)Ge.set=T(ie.prototype.structName,Ie);else{let gt=sl(Ee);Ge.set=function(Ne){if(Dt.setter)V("debug.setter:",z.cache.setters[Je],"for",ge(Je),ht,"@",this.pointer,"+",Ee.offset,"sz",Ee.sizeof,Ne);if(!this.pointer)d("Cannot set native property on a disposed",this.structName,"instance.");if(gt)Ne=gt.apply(this,[Ie,Ne]);if(Ne===null||Ne===void 0)Ne=j;else if(G(Ee.signature)&&!L(Ne))if(oe(Ee.signature)&&Ne instanceof Pt){if(Ne=Ne.pointer||j,Dt.setter)V("debug.setter:",ht,"resolved to",Ne)}else d("Invalid value for pointer-type",ht+".");new DataView(E().buffer,Number(this.pointer)+Ee.offset,Ee.sizeof)[z.cache.setters[Je]](0,z.cache.sw[Je](Ne),S)}}Object.defineProperty(ie.prototype,Ie,Ge)},al=function z(ie,fe,Ee=Object.create(null)){let Ie=function Ne(pt){if(!(this instanceof Ne))d("The",ie,"constructor may only be called via 'new'.");Pe(Ne,this,...arguments)},Je=this,ht=(Ne)=>typeof Ne==="string"&&$e(Ne)?{signature:Ne}:ae(Je,Ne);if(arguments.length===1)fe=ht(ie),ie=fe.structName||fe.name;else if(arguments.length===2)fe=ht(fe),fe.name??=ie;else fe=ht(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((Ne)=>{re.call(z,Ne,fe.adapt.struct[Ne])}),Object.keys(fe.adapt.set||{}).forEach((Ne)=>{B.call(z,Ne,fe.adapt.set[Ne])}),Object.keys(fe.adapt.get||{}).forEach((Ne)=>{Wt.call(z,Ne,fe.adapt.get[Ne])});if(!fe.members&&!fe.sizeof)fe.sizeof=we(fe.signature);let Dt=xe(h.__makeDebugFlags(Ut.debugFlags));Object.defineProperties(Ie,{debugFlags:Dt,isA:xe((Ne)=>Ne instanceof Ie),memberKey:Se,memberKeys:Re,structInfo:xe(fe),structName:xe(ie),ptrAdd:xe(J)}),Ie.prototype=new Pt(ie,fe,xe),Object.defineProperties(Ie.prototype,{debugFlags:Dt,constructor:xe(Ie),ptrAdd:xe(pe)});let Nt=!1,Ge=0,gt=!!fe.autoCalcSizeOffset;if(!gt){if(!fe.sizeof)d(ie,"description is missing its sizeof property.");fe.offset??=0}else fe.offset??=0;if(Object.keys(fe.members||{}).forEach((Ne)=>{let pt=ht(fe.members[Ne]);if(!pt.members&&!pt.sizeof){if(pt.sizeof=we(pt.signature),!pt.sizeof)d(w(ie,Ne),"is missing a sizeof property.",pt)}if(pt.offset===void 0)if(gt)pt.offset=Ge;else d(w(ie,Ne),"is missing its offset.",JSON.stringify(pt));if(fe.members[Ne]=pt,!Nt||Nt.offset<pt.offset)Nt=pt;let Io=!!pt.autoCalc;if(gt)pt.autoCalcSizeOffset=!0;if(Qy.call(Je,Ie,Ne,pt),Io)pt.autoCalcSizeOffset=!0;else delete pt.autoCalcSizeOffset;Ge+=pt.sizeof}),!Nt)d("No member property descriptions found.");if(!fe.sizeof)fe.sizeof=Ge;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<Ge)console.warn("Suspect struct description:",fe,"offset =",Ge),d("Mismatch in the calculated vs. the provided sizeof/offset info.","Expected sizeof",Ge,"but got",fe.sizeof,"for",fe);return delete fe.autoCalcSizeOffset,Ie},Ut=function z(ie,fe){return arguments.length==1?al.call(z,ie):al.call(z,ie,fe)};if(Ut.StructType=Pt,Ut.config=l,Ut.allocCString=Lr,Ut.adaptGet=Wt,Ut.adaptSet=B,Ut.adaptStruct=re,Ut.ptrAdd=J,!Ut.debugFlags)Ut.debugFlags=h.__makeDebugFlags(h.debugFlags);return Ut},globalThis.sqlite3ApiBootstrap.initializers.push(function(f){let l=(...O)=>{throw Error(O.join(" "))},{capi:d,wasm:h,util:E}=f;globalThis.WhWasmUtilInstaller(h),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 h.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 h.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 h.xWrap.FuncPtrAdapter({signature:"i(pipp)",bindScope:"transient",callProxy:(O)=>{let R;return(Q,ee,j,J)=>{try{let pe=h.cArgvToJs(ee,j);if(!R)R=h.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 h.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 h.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 h.xWrap.FuncPtrAdapter({name:"sqlite3_update_hook::callback",signature:"v(pippj)",contextKey:(O)=>O[0],callProxy:(O)=>(R,Q,ee,j,J)=>{O(R,Q,h.cstrToJs(ee),h.cstrToJs(j),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(h.exports.sqlite3_progress_handler)b.core.push(["sqlite3_progress_handler",void 0,["sqlite3*","int",new h.xWrap.FuncPtrAdapter({name:"xProgressHandler",signature:"i(p)",bindScope:"context",contextKey:(O,R)=>O[0]}),"*"]]);if(h.exports.sqlite3_stmt_explain)b.core.push(["sqlite3_stmt_explain","int","sqlite3_stmt*","int"],["sqlite3_stmt_isexplain","int","sqlite3_stmt*"]);if(h.exports.sqlite3_set_authorizer)b.core.push(["sqlite3_set_authorizer","int",["sqlite3*",new h.xWrap.FuncPtrAdapter({name:"sqlite3_set_authorizer::xAuth",signature:"i(pissss)",contextKey:(O,R)=>O[0],callProxy:(O)=>(R,Q,ee,j,J,pe)=>{try{return ee=ee&&h.cstrToJs(ee),j=j&&h.cstrToJs(j),J=J&&h.cstrToJs(J),pe=pe&&h.cstrToJs(pe),O(R,Q,ee,j,J,pe)|0}catch(S){return S.resultCode||d.SQLITE_ERROR}}}),"*"]]);if(h.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(h.bigIntEnabled&&!!h.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(h.bigIntEnabled&&!!h.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 h.xWrap.FuncPtrAdapter({name:"sqlite3_preupdate_hook",signature:"v(ppippjj)",contextKey:(O)=>O[0],callProxy:(O)=>(R,Q,ee,j,J,pe,S)=>{O(R,Q,ee,h.cstrToJs(j),h.cstrToJs(J),pe,S)}}),"*"]],["sqlite3_preupdate_new","int",["sqlite3*","int","**"]],["sqlite3_preupdate_old","int",["sqlite3*","int","**"]]);if(h.bigIntEnabled&&!!h.exports.sqlite3changegroup_add&&!!h.exports.sqlite3session_create&&!!h.exports.sqlite3_preupdate_hook){let O={signature:"i(ps)",callProxy:(R)=>(Q,ee)=>{try{return R(Q,h.cstrToJs(ee))|0}catch(j){return j.resultCode||d.SQLITE_ERROR}}};b.int64.push(["sqlite3changegroup_add","int",["sqlite3_changegroup*","int","void*"]],["sqlite3changegroup_add_strm","int",["sqlite3_changegroup*",new h.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 h.xWrap.FuncPtrAdapter({name:"xOutput",signature:"i(ppi)",bindScope:"transient"}),"void*"]],["sqlite3changeset_apply","int",["sqlite3*","int","void*",new h.xWrap.FuncPtrAdapter({name:"xFilter",bindScope:"transient",...O}),new h.xWrap.FuncPtrAdapter({name:"xConflict",signature:"i(pip)",bindScope:"transient"}),"void*"]],["sqlite3changeset_apply_strm","int",["sqlite3*",new h.xWrap.FuncPtrAdapter({name:"xInput",signature:"i(ppp)",bindScope:"transient"}),"void*",new h.xWrap.FuncPtrAdapter({name:"xFilter",bindScope:"transient",...O}),new h.xWrap.FuncPtrAdapter({name:"xConflict",signature:"i(pip)",bindScope:"transient"}),"void*"]],["sqlite3changeset_apply_v2","int",["sqlite3*","int","void*",new h.xWrap.FuncPtrAdapter({name:"xFilter",bindScope:"transient",...O}),new h.xWrap.FuncPtrAdapter({name:"xConflict",signature:"i(pip)",bindScope:"transient"}),"void*","**","int*","int"]],["sqlite3changeset_apply_v2_strm","int",["sqlite3*",new h.xWrap.FuncPtrAdapter({name:"xInput",signature:"i(ppp)",bindScope:"transient"}),"void*",new h.xWrap.FuncPtrAdapter({name:"xFilter",bindScope:"transient",...O}),new h.xWrap.FuncPtrAdapter({name:"xConflict",signature:"i(pip)",bindScope:"transient"}),"void*","**","int*","int"]],["sqlite3changeset_apply_v3","int",["sqlite3*","int","void*",new h.xWrap.FuncPtrAdapter({name:"xFilter",signature:"i(pp)",bindScope:"transient"}),new h.xWrap.FuncPtrAdapter({name:"xConflict",signature:"i(pip)",bindScope:"transient"}),"void*","**","int*","int"]],["sqlite3changeset_apply_v3_strm","int",["sqlite3*",new h.xWrap.FuncPtrAdapter({name:"xInput",signature:"i(ppp)",bindScope:"transient"}),"void*",new h.xWrap.FuncPtrAdapter({name:"xFilter",signature:"i(pp)",bindScope:"transient"}),new h.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 h.xWrap.FuncPtrAdapter({name:"xInputA",signature:"i(ppp)",bindScope:"transient"}),"void*",new h.xWrap.FuncPtrAdapter({name:"xInputB",signature:"i(ppp)",bindScope:"transient"}),"void*",new h.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 h.xWrap.FuncPtrAdapter({name:"xInput",signature:"i(ppp)",bindScope:"transient"}),"void*",new h.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 h.xWrap.FuncPtrAdapter({name:"xInput",signature:"i(ppp)",bindScope:"transient"}),"void*"]],["sqlite3changeset_start_v2","int",["**","int","*","int"]],["sqlite3changeset_start_v2_strm","int",["**",new h.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 h.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 h.xWrap.FuncPtrAdapter({name:"xOutput",signature:"i(ppp)",bindScope:"transient"}),"void*"]],["sqlite3session_table_filter",void 0,["sqlite3_session*",new h.xWrap.FuncPtrAdapter({name:"xFilter",...O,contextKey:(R,Q)=>R[0]}),"*"]])}f.StructBinder=globalThis.Jaccwabyt({heap:h.heap8u,alloc:h.alloc,dealloc:h.dealloc,bigIntEnabled:h.bigIntEnabled,pointerIR:h.ptr.ir,memberPrefix:"$"}),delete globalThis.Jaccwabyt;{let O=h.xWrap.argAdapter("string");h.xWrap.argAdapter("string:flexible",(j)=>O(E.flexibleString(j))),h.xWrap.argAdapter("string:static",function(j){if(h.isPtr(j))return j;return j=""+j,this[j]||(this[j]=h.allocCString(j))}.bind(Object.create(null)));let R=h.xWrap.argAdapter("*"),Q=function(){};if(h.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*",(j)=>R(j instanceof(f?.oo1?.Stmt||Q)?j.pointer:j))("sqlite3*",(j)=>R(j instanceof(f?.oo1?.DB||Q)?j.pointer:j))("sqlite3_vfs*",(j)=>{if(typeof j==="string")return d.sqlite3_vfs_find(j)||f.SQLite3Error.toss(d.SQLITE_NOTFOUND,"Unknown sqlite3_vfs name:",j);return R(j instanceof(d.sqlite3_vfs||Q)?j.pointer:j)}),h.exports.sqlite3_declare_vtab)h.xWrap.argAdapter("sqlite3_index_info*",(j)=>R(j instanceof(d.sqlite3_index_info||Q)?j.pointer:j))("sqlite3_module*",(j)=>R(j instanceof(d.sqlite3_module||Q)?j.pointer:j));let ee=h.xWrap.resultAdapter("*");h.xWrap.resultAdapter("sqlite3*",ee)("sqlite3_context*",ee)("sqlite3_stmt*",ee)("sqlite3_value*",ee)("sqlite3_vfs*",ee)("void*",ee);for(let j of b.core)d[j[0]]=h.xWrap.apply(null,j);for(let j of b.wasmInternal)E[j[0]]=h.xWrap.apply(null,j);for(let j of b.int64)d[j[0]]=h.bigIntEnabled?h.xWrap.apply(null,j):()=>l(j[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(j,J,pe){if(!j)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(j,J,pe)||J}}{let O=h.xCall("sqlite3__wasm_enum_json");if(!O)l("Maintenance required: increase sqlite3__wasm_enum_json()'s","static buffer size!");h.ctype=JSON.parse(h.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(h.bigIntEnabled)R.push("serialize","session","vtab");for(let j of R)for(let J of Object.entries(h.ctype[j]))d[J[0]]=J[1];if(!h.functionEntry(d.SQLITE_WASM_DEALLOC))l("Internal error: cannot resolve exported function","entry SQLITE_WASM_DEALLOC (=="+d.SQLITE_WASM_DEALLOC+").");let Q=Object.create(null);for(let j of Object.entries(h.ctype.resultCodes))Q[j[1]]=j[0];d.sqlite3_js_rc_str=(j)=>Q[j];let ee=Object.assign(Object.create(null),{WasmTestStruct:!0,sqlite3_index_info:!h.bigIntEnabled,sqlite3_index_constraint:!h.bigIntEnabled,sqlite3_index_orderby:!h.bigIntEnabled,sqlite3_index_constraint_usage:!h.bigIntEnabled});for(let j of h.ctype.structs)if(!ee[j.name])d[j.name]=f.StructBinder(j);if(d.sqlite3_index_info){for(let j of["sqlite3_index_constraint","sqlite3_index_orderby","sqlite3_index_constraint_usage"])d.sqlite3_index_info[j]=d[j],delete d[j];d.sqlite3_vtab_config=h.xWrap("sqlite3__wasm_vtab_config","int",["sqlite3*","int","int"])}}let I=(O,R,Q)=>E.sqlite3__wasm_db_error(O,d.SQLITE_MISUSE,R+"() requires "+Q+" argument"+(Q===1?"":"s")+"."),V=(O)=>E.sqlite3__wasm_db_error(O,d.SQLITE_FORMAT,"SQLITE_UTF8 is the only supported encoding."),U=(O)=>h.xWrap.argAdapter("sqlite3*")(O),N=(O)=>h.isPtr(O)?h.cstrToJs(O):O,q=function(O,R){O=U(O);let Q=this.dbMap.get(O);if(!R)return this.dbMap.delete(O),Q;else if(!Q&&R>0)this.dbMap.set(O,Q=Object.create(null));return Q}.bind(Object.assign(Object.create(null),{dbMap:new Map}));if(q.addCollation=function(O,R){let Q=q(O,1);if(!Q.collation)Q.collation=new Set;Q.collation.add(N(R).toLowerCase())},q._addUDF=function(O,R,Q,ee){R=N(R).toLowerCase();let j=ee.get(R);if(!j)ee.set(R,j=new Set);j.add(Q<0?-1:Q)},q.addFunction=function(O,R,Q){let ee=q(O,1);if(!ee.udf)ee.udf=new Map;this._addUDF(O,R,Q,ee.udf)},h.exports.sqlite3_create_window_function)q.addWindowFunc=function(O,R,Q){let ee=q(O,1);if(!ee.wudf)ee.wudf=new Map;this._addUDF(O,R,Q,ee.wudf)};q.cleanup=function(O){O=U(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[j,J]=ee;if(!h.exports[j])continue;let pe=[O];pe.length=J;try{d[j](...pe)}catch(S){f.config.warn("close-time call of",j+"(",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(j){}delete R.collation}let Q;for(Q=0;Q<2;++Q){let ee=Q?R.wudf:R.udf;if(!ee)continue;let j=Q?d.sqlite3_create_window_function:d.sqlite3_create_function_v2;for(let J of ee){let pe=J[0],S=J[1],C=[O,pe,0,d.SQLITE_UTF8,0,0,0,0,0];if(Q)C.push(0);for(let G of S)try{C[2]=G,j.apply(null,C)}catch(oe){}S.clear()}ee.clear()}delete R.udf,delete R.wudf};{let O=h.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(Q){}return O(R)}}if(d.sqlite3session_create){let O=h.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=(Q,ee)=>"argv["+ee+"]:"+Q[0]+":"+h.cstrToJs(Q[1]).toLowerCase(),R=h.xWrap("sqlite3_create_collation_v2","int",["sqlite3*","string","int","*",new h.xWrap.FuncPtrAdapter({name:"xCompare",signature:"i(pipip)",contextKey:O}),new h.xWrap.FuncPtrAdapter({name:"xDestroy",signature:"v(p)",contextKey:O})]);d.sqlite3_create_collation_v2=function(Q,ee,j,J,pe,S){if(arguments.length!==6)return I(Q,"sqlite3_create_collation_v2",6);else if((j&15)===0)j|=d.SQLITE_UTF8;else if(d.SQLITE_UTF8!==(j&15))return V(Q);try{let C=R(Q,ee,j,J,pe,S);if(C===0&&pe instanceof Function)q.addCollation(Q,ee);return C}catch(C){return E.sqlite3__wasm_db_error(Q,C)}},d.sqlite3_create_collation=(Q,ee,j,J,pe)=>arguments.length===5?d.sqlite3_create_collation_v2(Q,ee,j,J,pe,0):I(Q,"sqlite3_create_collation",5)}{let O=function(j,J){return j[0]+":"+(j[2]<0?-1:j[2])+":"+J+":"+h.cstrToJs(j[1]).toLowerCase()},R=Object.assign(Object.create(null),{xInverseAndStep:{signature:"v(pip)",contextKey:O,callProxy:(j)=>(J,pe,S)=>{try{j(J,...d.sqlite3_values_to_js(pe,S))}catch(C){d.sqlite3_result_error_js(J,C)}}},xFinalAndValue:{signature:"v(p)",contextKey:O,callProxy:(j)=>(J)=>{try{d.sqlite3_result_js(J,j(J))}catch(pe){d.sqlite3_result_error_js(J,pe)}}},xFunc:{signature:"v(pip)",contextKey:O,callProxy:(j)=>(J,pe,S)=>{try{d.sqlite3_result_js(J,j(J,...d.sqlite3_values_to_js(pe,S)))}catch(C){d.sqlite3_result_error_js(J,C)}}},xDestroy:{signature:"v(p)",contextKey:O,callProxy:(j)=>(J)=>{try{j(J)}catch(pe){console.error("UDF xDestroy method threw:",pe)}}}}),Q=h.xWrap("sqlite3_create_function_v2","int",["sqlite3*","string","int","int","*",new h.xWrap.FuncPtrAdapter({name:"xFunc",...R.xFunc}),new h.xWrap.FuncPtrAdapter({name:"xStep",...R.xInverseAndStep}),new h.xWrap.FuncPtrAdapter({name:"xFinal",...R.xFinalAndValue}),new h.xWrap.FuncPtrAdapter({name:"xDestroy",...R.xDestroy})]),ee=h.exports.sqlite3_create_window_function?h.xWrap("sqlite3_create_window_function","int",["sqlite3*","string","int","int","*",new h.xWrap.FuncPtrAdapter({name:"xStep",...R.xInverseAndStep}),new h.xWrap.FuncPtrAdapter({name:"xFinal",...R.xFinalAndValue}),new h.xWrap.FuncPtrAdapter({name:"xValue",...R.xFinalAndValue}),new h.xWrap.FuncPtrAdapter({name:"xInverse",...R.xInverseAndStep}),new h.xWrap.FuncPtrAdapter({name:"xDestroy",...R.xDestroy})]):void 0;if(d.sqlite3_create_function_v2=function j(J,pe,S,C,G,oe,Z,ge,we){if(j.length!==arguments.length)return I(J,"sqlite3_create_function_v2",j.length);else if((C&15)===0)C|=d.SQLITE_UTF8;else if(d.SQLITE_UTF8!==(C&15))return V(J);try{let ye=Q(J,pe,S,C,G,oe,Z,ge,we);if(ye===0&&(oe instanceof Function||Z instanceof Function||ge instanceof Function||we instanceof Function))q.addFunction(J,pe,S);return ye}catch(ye){return console.error("sqlite3_create_function_v2() setup threw:",ye),E.sqlite3__wasm_db_error(J,ye,"Creation of UDF threw: "+ye)}},d.sqlite3_create_function=function j(J,pe,S,C,G,oe,Z,ge){return j.length===arguments.length?d.sqlite3_create_function_v2(J,pe,S,C,G,oe,Z,ge,0):I(J,"sqlite3_create_function",j.length)},ee)d.sqlite3_create_window_function=function j(J,pe,S,C,G,oe,Z,ge,we,ye){if(j.length!==arguments.length)return I(J,"sqlite3_create_window_function",j.length);else if((C&15)===0)C|=d.SQLITE_UTF8;else if(d.SQLITE_UTF8!==(C&15))return V(J);try{let ve=ee(J,pe,S,C,G,oe,Z,ge,we,ye);if(ve===0&&(oe instanceof Function||Z instanceof Function||ge instanceof Function||we instanceof Function||ye 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=(Q,ee)=>{if(typeof Q==="string")ee=-1;else if(E.isSQLableTypedArray(Q))ee=Q.byteLength,Q=h.typedArrayToString(Q instanceof ArrayBuffer?new Uint8Array(Q):Q);else if(Array.isArray(Q))Q=Q.join(""),ee=-1;return[Q,ee]},R={basic:h.xWrap("sqlite3_prepare_v3","int",["sqlite3*","string","int","int","**","**"]),full:h.xWrap("sqlite3_prepare_v3","int",["sqlite3*","*","int","int","**","**"])};d.sqlite3_prepare_v3=function Q(ee,j,J,pe,S,C){if(Q.length!==arguments.length)return I(ee,"sqlite3_prepare_v3",Q.length);let[G,oe]=O(j,Number(J));switch(typeof G){case"string":return R.basic(ee,G,oe,pe,S,null);case typeof h.ptr.null:return R.full(ee,h.ptr.coerce(G),oe,pe,S,C);default:return E.sqlite3__wasm_db_error(ee,d.SQLITE_MISUSE,"Invalid SQL argument type for sqlite3_prepare_v2/v3(). typeof="+typeof G)}},d.sqlite3_prepare_v2=function Q(ee,j,J,pe,S){return Q.length===arguments.length?d.sqlite3_prepare_v3(ee,j,J,0,pe,S):I(ee,"sqlite3_prepare_v2",Q.length)}}{let O=h.xWrap("sqlite3_bind_text","int",["sqlite3_stmt*","int","string","int","*"]),R=h.xWrap("sqlite3_bind_blob","int",["sqlite3_stmt*","int","*","int","*"]);d.sqlite3_bind_text=function Q(ee,j,J,pe,S){if(Q.length!==arguments.length)return I(d.sqlite3_db_handle(ee),"sqlite3_bind_text",Q.length);else if(h.isPtr(J)||J===null)return O(ee,j,J,pe,S);else if(J instanceof ArrayBuffer)J=new Uint8Array(J);else if(Array.isArray(pMem))J=pMem.join("");let C,G;try{if(E.isSQLableTypedArray(J))C=h.allocFromTypedArray(J),G=J.byteLength;else if(typeof J==="string")[C,G]=h.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,j,C,G,d.SQLITE_WASM_DEALLOC)}catch(oe){return h.dealloc(C),E.sqlite3__wasm_db_error(d.sqlite3_db_handle(ee),oe)}},d.sqlite3_bind_blob=function Q(ee,j,J,pe,S){if(Q.length!==arguments.length)return I(d.sqlite3_db_handle(ee),"sqlite3_bind_blob",Q.length);else if(h.isPtr(J)||J===null)return R(ee,j,J,pe,S);else if(J instanceof ArrayBuffer)J=new Uint8Array(J);else if(Array.isArray(J))J=J.join("");let C,G;try{if(E.isBindableTypedArray(J))C=h.allocFromTypedArray(J),G=pe>=0?pe:J.byteLength;else if(typeof J==="string")[C,G]=h.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,j,C,G,d.SQLITE_WASM_DEALLOC)}catch(oe){return h.dealloc(C),E.sqlite3__wasm_db_error(d.sqlite3_db_handle(ee),oe)}}}if(!d.sqlite3_column_text){let O=h.xWrap.argAdapter("sqlite3_stmt*"),R=h.xWrap.argAdapter("int"),Q=h.xWrap.argAdapter("sqlite3_value*"),ee=(j,J)=>h.typedArrayToString(h.heap8u(),Number(j),Number(j)+J);d.sqlite3_column_text=function(j,J){let pe=O(j),S=R(J),C=h.exports.sqlite3_column_text(pe,S);return C?ee(C,h.exports.sqlite3_column_bytes(pe,S)):null},d.sqlite3_value_text=function(j){let J=Q(j),pe=h.exports.sqlite3_value_text(J);return pe?ee(pe,h.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 h.exports.sqlite3__wasm_config_i(O,R[0]);case d.SQLITE_CONFIG_LOOKASIDE:return h.exports.sqlite3__wasm_config_ii(O,R[0],R[1]);case d.SQLITE_CONFIG_MEMDB_MAXSIZE:return h.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=h.installFunction("i(ppp)",R);else if(arguments.length!==1||!h.isPtr(R))return d.SQLITE_MISUSE;let Q=h.exports.sqlite3_auto_extension(R);if(R!==arguments[0])if(Q===0)O.add(R);else h.uninstallFunction(R);return Q},d.sqlite3_cancel_auto_extension=function(R){if(!R||arguments.length!==1||!h.isPtr(R))return 0;return h.exports.sqlite3_cancel_auto_extension(R)},d.sqlite3_reset_auto_extension=function(){h.exports.sqlite3_reset_auto_extension();for(let R of O)h.uninstallFunction(R);O.clear()}}h.xWrap.FuncPtrAdapter.warnOnUse=!0;let W=f.StructBinder,K=function O(R,Q,ee,j=O.installMethodArgcCheck){if(!(R instanceof W.StructType))l("Usage error: target object is-not-a StructType.");else if(!(ee instanceof Function)&&!h.isPtr(ee))l("Usage error: expecting a Function or WASM pointer to one.");if(arguments.length===1)return(C,G)=>O(R,C,G,j);if(!O.argcProxy)O.argcProxy=function(C,G,oe,Z){return function(...ge){if(oe.length!==arguments.length)l("Argument mismatch for",C.structInfo.name+"::"+G+": Native signature is:",Z);return oe.apply(this,ge)}},O.removeFuncList=function(){if(this.ondispose.__removeFuncList)this.ondispose.__removeFuncList.forEach((C,G)=>{if(h.isPtr(C))try{h.uninstallFunction(C)}catch(oe){}}),delete this.ondispose.__removeFuncList};let J=R.memberSignature(Q);if(J.length<2)l("Member",Q,"does not have a function pointer signature:",J);let pe=R.memberKey(Q),S=j&&!h.isPtr(ee)?O.argcProxy(R,pe,ee,J):ee;if(h.isPtr(S)){if(S&&!h.functionEntry(S))l("Pointer",S,"is not a WASM function table entry.");R[pe]=S}else{let C=h.installFunction(S,J);if(R[pe]=C,!R.ondispose||!R.ondispose.__removeFuncList)R.addOnDispose("ondispose.__removeFuncList handler",O.removeFuncList),R.ondispose.__removeFuncList=[];R.ondispose.__removeFuncList.push(pe,C)}return(C,G)=>O(R,C,G,j)};K.installMethodArgcCheck=!1;let ue=function(O,R,Q=K.installMethodArgcCheck){let ee=new Map;for(let j of Object.keys(R)){let J=R[j],pe=ee.get(J);if(pe){let S=O.memberKey(j);O[S]=O[O.memberKey(pe)]}else K(O,j,J,Q),ee.set(J,j)}return O};W.StructType.prototype.installMethod=function(R,Q,ee=K.installMethodArgcCheck){return arguments.length<3&&R&&typeof R==="object"?ue(this,...arguments):K(this,...arguments)},W.StructType.prototype.installMethods=function(O,R=K.installMethodArgcCheck){return ue(this,O,R)}}),globalThis.sqlite3ApiBootstrap.initializers.push(function(f){let l=(...M)=>{throw new f.SQLite3Error(...M)},{capi:d,wasm:h,util:E}=f,b=function(M){return(...g)=>M("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,U=new WeakMap,N=(M,g,w)=>{let T=Object.getOwnPropertyDescriptor(M,g);return T?T.value:w},q=function(M,g){if(g){if(M instanceof O)M=M.pointer;l(g,"sqlite3 result code",g+":",M?d.sqlite3_errmsg(M):d.sqlite3_errstr(g))}return arguments[0]},W=h.installFunction("i(ippp)",function(M,g,w,T){if(d.SQLITE_TRACE_STMT===M)console.log("SQL TRACE #"+ ++this.counter,"via sqlite3@"+g+"["+d.sqlite3_db_filename(g,null)+"]",h.cstrToJs(T))}.bind({counter:0})),K=Object.create(null),ue=function M(...g){let w=M.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:P,vfs:te,flags:se}=w;if(typeof P!=="string"&&!h.isPtr(P)||typeof se!=="string"||te&&typeof te!=="string"&&!h.isPtr(te))f.config.error("Invalid DB ctor args",w,arguments),l("Invalid arguments for DB constructor:",arguments,"opts:",w);let D=0;if(se.indexOf("c")>=0)D|=d.SQLITE_OPEN_CREATE|d.SQLITE_OPEN_READWRITE;if(se.indexOf("w")>=0)D|=d.SQLITE_OPEN_READWRITE;if(D===0)D|=d.SQLITE_OPEN_READONLY;D|=d.SQLITE_OPEN_EXRESCODE;let L=h.pstack.pointer;try{let Y=h.pstack.allocPtr(),ne=d.sqlite3_open_v2(P,Y,D,te||h.ptr.null);if(T=h.peekPtr(Y),q(T,ne),d.sqlite3_extended_result_codes(T,1),se.indexOf("t")>=0)d.sqlite3_trace_v2(T,d.SQLITE_TRACE_STMT,W,T)}catch(Y){if(T)d.sqlite3_close_v2(T);throw Y}finally{h.pstack.restore(L)}this.filename=h.isPtr(P)?h.cstrToJs(P):P}if(I.set(this,T),U.set(this,Object.create(null)),!w["sqlite3*"])try{let P=K[d.sqlite3_js_db_vfs(T)||l("Internal error: cannot get VFS for new db handle.")];if(P)if(P instanceof Function)P(this,f);else q(T,d.sqlite3_exec(T,P,0,0,0))}catch(P){throw this.close(),P}};ue.setVfsPostOpenCallback=function(M,g){if(!(g instanceof Function))l("dbCtorHelper.setVfsPostOpenCallback() should not be used with a non-function argument.",arguments);K[M]=g},ue.normalizeArgs=function(M=":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=M,T.flags=g,T.vfs=w;return T};let O=function(...M){ue.apply(this,M)};O.dbCtorHelper=ue;let R={null:1,number:2,string:3,boolean:4,blob:5};if(h.bigIntEnabled)R.bigint=R.number;let Q=function(){if(R!==arguments[2])l(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(M){if(!M.pointer)l("DB has been closed.");return M},j=function(M,g){if(g!==(g|0)||g<0||g>=M.columnCount)l("Column index",g,"is out of range.");return M},J=function(M,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:l("Invalid argument count for exec().")}if(w.sql=E.flexibleString(w.sql),typeof w.sql!=="string")l("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=()=>M;break;default:l("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=(P,te)=>{if(!te.columnNames)te.columnNames=P.getColumnNames([]);let se=P.get([]),D=Object.create(null);for(let L in te.columnNames)D[te.columnNames[L]]=se[L];return D};break;case"array":w.cbArg=(P)=>P.get([]);break;case"stmt":if(Array.isArray(T.resultRows))l("exec(): invalid rowMode for a resultRows array: must","be one of 'array', 'object',","a result column number, or column name reference.");w.cbArg=(P)=>P;break;default:if(E.isInt32(T.rowMode)){w.cbArg=(P)=>P.get(T.rowMode);break}else if(typeof T.rowMode==="string"&&T.rowMode.length>1&&T.rowMode[0]==="$"){let P=T.rowMode.substr(1);w.cbArg=(te)=>{let se=te.get(Object.create(null))[P];return se===void 0?l(d.SQLITE_NOTFOUND,"exec(): unknown result column:",P):se};break}l("Invalid rowMode:",T.rowMode)}return w},pe=(M,g,w,...T)=>{let P=M.prepare(g);try{let te=P.bind(w).step()?P.get(...T):void 0;return P.reset(),te}finally{P.finalize()}},S=(M,g,w,T)=>M.exec({sql:g,bind:w,rowMode:T,returnValue:"resultRows"});O.checkRc=(M,g)=>q(M,g),O.prototype={isOpen:function(){return!!this.pointer},affirmOpen:function(){return ee(this)},close:function(){let M=this.pointer;if(M){if(this.onclose&&this.onclose.before instanceof Function)try{this.onclose.before(this)}catch(g){}if(Object.keys(U.get(this)).forEach((g,w)=>{if(w&&w.pointer)try{w.finalize()}catch(T){}}),I.delete(this),U.delete(this),!V.delete(this))d.sqlite3_close_v2(M);if(this.onclose&&this.onclose.after instanceof Function)try{this.onclose.after(this)}catch(g){}delete this.filename}},changes:function(M=!1,g=!1){let w=ee(this).pointer;if(M)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(M="main"){return d.sqlite3_db_filename(ee(this).pointer,M)},dbName:function(M=0){return d.sqlite3_db_name(ee(this).pointer,M)},dbVfsName:function(M=0){let g,w=d.sqlite3_js_db_vfs(ee(this).pointer,M);if(w){let T=new d.sqlite3_vfs(w);try{g=h.cstrToJs(T.$zName)}finally{T.dispose()}}return g},prepare:function(M){ee(this);let g=h.pstack.pointer,w,T;try{w=h.pstack.alloc(8),O.checkRc(this,d.sqlite3_prepare_v2(this.pointer,M,-1,w,null)),T=h.peekPtr(w)}finally{h.pstack.restore(g)}if(!T)l("Cannot prepare empty SQL.");let P=new Q(this,T,R);return U.get(this)[T]=P,P},exec:function(){ee(this);let M=J(this,arguments);if(!M.sql)return l("exec() requires an SQL string.");let g=M.opt,w=g.callback,T=Array.isArray(g.resultRows)?g.resultRows:void 0,P,te=g.bind,se=!!(M.cbArg||g.columnNames||T),D=h.scopedAllocPush(),L=Array.isArray(g.saveSql)?g.saveSql:void 0;try{let Y=E.isSQLableTypedArray(M.sql),ne=Y?M.sql.byteLength:h.jstrlen(M.sql),be=h.scopedAlloc(2*h.ptr.size+(ne+1)),xe=h.ptr.add(be,h.ptr.size),Pe=h.ptr.add(xe,h.ptr.size),$e=h.ptr.add(Pe,ne);if(Y)h.heap8().set(M.sql,Pe);else h.jstrcpy(M.sql,h.heap8(),Pe,ne,!1);h.poke8(h.ptr.add(Pe,ne),0);while(Pe&&h.peek8(Pe)){h.pokePtr([be,xe],0),O.checkRc(this,d.sqlite3_prepare_v3(this.pointer,Pe,ne,0,be,xe));let Ve=h.peekPtr(be);if(Pe=h.peekPtr(xe),ne=Number(h.ptr.add($e,-Pe)),!Ve)continue;if(L)L.push(d.sqlite3_sql(Ve).trim());if(P=new Q(this,Ve,R),te&&P.parameterCount)P.bind(te),te=null;if(se&&P.columnCount){let ft=Array.isArray(g.columnNames)?0:1;if(se=!1,M.cbArg||T){let Wt=Object.create(null);for(;P.step();ge.delete(P)){if(ft++===0)P.getColumnNames(Wt.columnNames=g.columnNames||[]);ge.add(P);let qr=M.cbArg(P,Wt);if(T)T.push(qr);if(w&&w.call(g,qr,P)===!1)break}ge.delete(P)}if(ft===0)P.getColumnNames(g.columnNames)}else P.step();P.reset().finalize(),P=null}}finally{if(P)ge.delete(P),P.finalize();h.scopedAllocPop(D)}return M.returnVal()},createFunction:function(g,w,T){let P=(Wt)=>Wt instanceof Function;switch(arguments.length){case 1:T=g,g=T.name,w=T.xFunc||0;break;case 2:if(!P(w))T=w,w=T.xFunc||0;break;case 3:break;default:break}if(!T)T={};if(typeof g!=="string")l("Invalid arguments: missing function name.");let te=T.xStep||0,se=T.xFinal||0,D=T.xValue||0,L=T.xInverse||0,Y=void 0;if(P(w)){if(Y=!1,P(te)||P(se))l("Ambiguous arguments: scalar or aggregate?");te=se=null}else if(P(te)){if(!P(se))l("Missing xFinal() callback for aggregate or window UDF.");w=null}else if(P(se))l("Missing xStep() callback for aggregate or window UDF.");else l("Missing function-type properties.");if(Y===!1){if(P(D)||P(L))l("xValue and xInverse are not permitted for non-window UDFs.")}else if(P(D)){if(!P(L))l("xInverse must be provided if xValue is.");Y=!0}else if(P(L))l("xValue must be provided if xInverse is.");let ne=T.pApp;if(ne!==void 0&&ne!==null&&!h.isPtr(ne))l("Invalid value for pApp property. Must be a legal WASM pointer value.");let be=T.xDestroy||0;if(be&&!P(be))l("xDestroy property must be a function.");let xe=0;if(N(T,"deterministic"))xe|=d.SQLITE_DETERMINISTIC;if(N(T,"directOnly"))xe|=d.SQLITE_DIRECTONLY;if(N(T,"innocuous"))xe|=d.SQLITE_INNOCUOUS;g=g.toLowerCase();let Pe=w||te,$e=N(T,"arity"),Ve=typeof $e==="number"?$e:Pe.length?Pe.length-1:0,ft;if(Y)ft=d.sqlite3_create_window_function(this.pointer,g,Ve,d.SQLITE_UTF8|xe,ne||0,te,se,D,L,be);else ft=d.sqlite3_create_function_v2(this.pointer,g,Ve,d.SQLITE_UTF8|xe,ne||0,w,te,se,be);return O.checkRc(this,ft),this},selectValue:function(M,g,w){return pe(this,M,g,0,w)},selectValues:function(M,g,w){let T=this.prepare(M),P=[];try{T.bind(g);while(T.step())P.push(T.get(0,w));T.reset()}finally{T.finalize()}return P},selectArray:function(M,g){return pe(this,M,g,[])},selectObject:function(M,g){return pe(this,M,g,{})},selectArrays:function(M,g){return S(this,M,g,"array")},selectObjects:function(M,g){return S(this,M,g,"object")},openStatementCount:function(){return this.pointer?Object.keys(U.get(this)).length:0},transaction:function(M){let g="BEGIN";if(arguments.length>1){if(/[^a-zA-Z]/.test(arguments[0]))l(d.SQLITE_MISUSE,"Invalid argument for BEGIN qualifier.");g+=" "+arguments[0],M=arguments[1]}ee(this).exec(g);try{let w=M(this);return this.exec("COMMIT"),w}catch(w){throw this.exec("ROLLBACK"),w}},savepoint:function(M){ee(this).exec("SAVEPOINT oo1");try{let g=M(this);return this.exec("RELEASE oo1"),g}catch(g){throw this.exec("ROLLBACK to SAVEPOINT oo1; RELEASE SAVEPOINT oo1"),g}},checkRc:function(M){return q(this,M)}},O.wrapHandle=function(M,g=!1){if(!M||!h.isPtr(M))throw new f.SQLite3Error(d.SQLITE_MISUSE,"Argument must be a WASM sqlite3 pointer");return new O({"sqlite3*":M,"sqlite3*:takeOwnership":!!g})};let C=function(M){if(!M.pointer)l("Stmt has been closed.");return M},G=function(M){let g=R[M===null||M===void 0?"null":typeof M];switch(g){case R.boolean:case R.null:case R.number:case R.string:return g;case R.bigint:return h.bigIntEnabled?g:void 0;default:return E.isBindableTypedArray(M)?R.blob:void 0}},oe=function(M){return G(M)||l("Unsupported bind() argument type:",typeof M)},Z=function(M,g){let w=typeof g==="number"?g:d.sqlite3_bind_parameter_index(M.pointer,g);if(w===0||!E.isInt32(w))l("Invalid bind() parameter name: "+g);else if(w<1||w>M.parameterCount)l("Bind index",g,"is out of range.");return w},ge=new Set,we=new Set,ye=function(M,g){if(ge.has(M))l("Operation is illegal when statement is locked:",g);return M},ve=function M(g,w,T,P){if(ye(C(g),"bind()"),!M._)M._tooBigInt=(se)=>l("BigInt value is too big to store without precision loss:",se),M._={string:function(se,D,L,Y){let[ne,be]=h.allocCString(L,!0);return(Y?d.sqlite3_bind_blob:d.sqlite3_bind_text)(se.pointer,D,ne,be,d.SQLITE_WASM_DEALLOC)}};oe(P),w=Z(g,w);let te=0;switch(P===null||P===void 0?R.null:T){case R.null:te=d.sqlite3_bind_null(g.pointer,w);break;case R.string:te=M._.string(g,w,P,!1);break;case R.number:{let se;if(E.isInt32(P))se=d.sqlite3_bind_int;else if(typeof P==="bigint")if(!E.bigIntFits64(P))M._tooBigInt(P);else if(h.bigIntEnabled)se=d.sqlite3_bind_int64;else if(E.bigIntFitsDouble(P))P=Number(P),se=d.sqlite3_bind_double;else M._tooBigInt(P);else if(P=Number(P),h.bigIntEnabled&&Number.isInteger(P))se=d.sqlite3_bind_int64;else se=d.sqlite3_bind_double;te=se(g.pointer,w,P);break}case R.boolean:te=d.sqlite3_bind_int(g.pointer,w,P?1:0);break;case R.blob:{if(typeof P==="string"){te=M._.string(g,w,P,!0);break}else if(P instanceof ArrayBuffer)P=new Uint8Array(P);else if(!E.isBindableTypedArray(P))l("Binding a value as a blob requires","that it be a string, Uint8Array, Int8Array, or ArrayBuffer.");let se=h.alloc(P.byteLength||1);h.heap8().set(P.byteLength?P:[0],Number(se)),te=d.sqlite3_bind_blob(g.pointer,w,se,P.byteLength,d.SQLITE_WASM_DEALLOC);break}default:f.config.warn("Unsupported bind() argument type:",P),l("Unsupported bind() argument type: "+typeof P)}if(te)O.checkRc(g.db.pointer,te);return g};Q.prototype={finalize:function(){let M=this.pointer;if(M){ye(this,"finalize()");let g=V.delete(this)?0:d.sqlite3_finalize(M);return delete U.get(this.db)[M],I.delete(this),ge.delete(this),we.delete(this),delete this.parameterCount,delete this.db,g}},clearBindings:function(){return ye(C(this),"clearBindings()"),d.sqlite3_clear_bindings(this.pointer),we.delete(this),this},reset:function(M){if(ye(this,"reset()"),M)this.clearBindings();let g=d.sqlite3_reset(C(this).pointer);return we.delete(this),q(this.db,g),this},bind:function(){C(this);let M,g;switch(arguments.length){case 1:M=1,g=arguments[0];break;case 2:M=arguments[0],g=arguments[1];break;default:l("Invalid bind() arguments.")}if(g===void 0)return this;else if(!this.parameterCount)l("This statement has no bindable parameters.");if(we.delete(this),g===null)return ve(this,M,R.null,g);else if(Array.isArray(g)){if(arguments.length!==1)l("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)l("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,M,oe(g),g);l("Should not reach this point.")},bindAsBlob:function(M,g){if(C(this),arguments.length===1)g=M,M=1;let w=oe(g);if(R.string!==w&&R.blob!==w&&R.null!==w)l("Invalid value type for bindAsBlob()");return ve(this,M,R.blob,g)},step:function(){ye(this,"step()");let M=d.sqlite3_step(C(this).pointer);switch(M){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=",M,d.sqlite3_js_rc_str(M),"SQL =",d.sqlite3_sql(this.pointer)),O.checkRc(this.db.pointer,M)}},stepReset:function(){return this.step(),this.reset()},stepFinalize:function(){try{let M=this.step();return this.reset(),M}finally{try{this.finalize()}catch(M){}}},get:function(M,g){if(!we.has(C(this)))l("Stmt.step() has not (recently) returned true.");if(Array.isArray(M)){let w=0,T=this.columnCount;while(w<T)M[w]=this.get(w++);return M}else if(M&&typeof M==="object"){let w=0,T=this.columnCount;while(w<T)M[d.sqlite3_column_name(this.pointer,w)]=this.get(w++);return M}switch(j(this,M),g===void 0?d.sqlite3_column_type(this.pointer,M):g){case d.SQLITE_NULL:return null;case d.SQLITE_INTEGER:if(h.bigIntEnabled){let w=d.sqlite3_column_int64(this.pointer,M);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,M);if(w>Number.MAX_SAFE_INTEGER||w<Number.MIN_SAFE_INTEGER)l("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,M);case d.SQLITE_TEXT:return d.sqlite3_column_text(this.pointer,M);case d.SQLITE_BLOB:{let w=d.sqlite3_column_bytes(this.pointer,M),T=d.sqlite3_column_blob(this.pointer,M),P=new Uint8Array(w);if(w){if(P.set(h.heap8u().slice(Number(T),Number(T)+w),0),this.db._blobXfer instanceof Array)this.db._blobXfer.push(P.buffer)}return P}default:l("Don't know how to translate","type of result column #"+M+".")}l("Not reached.")},getInt:function(M){return this.get(M,d.SQLITE_INTEGER)},getFloat:function(M){return this.get(M,d.SQLITE_FLOAT)},getString:function(M){return this.get(M,d.SQLITE_TEXT)},getBlob:function(M){return this.get(M,d.SQLITE_BLOB)},getJSON:function(M){let g=this.get(M,d.SQLITE_STRING);return g===null?g:JSON.parse(g)},getColumnName:function(M){return d.sqlite3_column_name(j(C(this),M).pointer,M)},getColumnNames:function(M=[]){j(C(this),0);let g=this.columnCount;for(let w=0;w<g;++w)M.push(d.sqlite3_column_name(this.pointer,w));return M},getParamIndex:function(M){return C(this).parameterCount?d.sqlite3_bind_parameter_index(this.pointer,M):void 0},getParamName:function(M){return C(this).parameterCount?d.sqlite3_bind_parameter_name(this.pointer,M):void 0},isBusy:function(){return d.sqlite3_stmt_busy(C(this))!==0},isReadOnly:function(){return d.sqlite3_stmt_readonly(C(this))!==0}};{let M={enumerable:!0,get:function(){return I.get(this)},set:()=>l("The pointer property is read-only.")};Object.defineProperty(Q.prototype,"pointer",M),Object.defineProperty(O.prototype,"pointer",M)}Object.defineProperty(Q.prototype,"columnCount",{enumerable:!1,get:function(){return d.sqlite3_column_count(this.pointer)},set:()=>l("The columnCount property is read-only.")}),Object.defineProperty(Q.prototype,"parameterCount",{enumerable:!1,get:function(){return d.sqlite3_bind_parameter_count(this.pointer)},set:()=>l("The parameterCount property is read-only.")}),Q.wrapHandle=function(M,g,w=!1){if(!(M instanceof O)||!M.pointer)throw new f.SQLite3Error(f.SQLITE_MISUSE,"First argument must be an opened sqlite3.oo1.DB instance");if(!g||!h.isPtr(g))throw new f.SQLite3Error(f.SQLITE_MISUSE,"Second argument must be a WASM sqlite3_stmt pointer");return new Q(M,g,R,!!w)},f.oo1={DB:O,Stmt:Q}}),globalThis.sqlite3ApiBootstrap.initializers.push(function(f){let l=f.util;f.initWorker1API=function(){let d=(...W)=>{throw Error(W.join(" "))};if(!(globalThis.WorkerGlobalScope instanceof Function))d("initWorker1API() must be run from a Worker thread.");let h=this.sqlite3||d("Missing this.sqlite3 object."),E=h.oo1.DB,b=function(W){let K=I.idMap.get(W);if(K)return K;return K="db#"+ ++I.idSeq+":"+Math.floor(Math.random()*1e8)+":"+Math.floor(Math.random()*1e8),I.idMap.set(W,K),K},I={dbList:[],idSeq:0,idMap:new WeakMap,xfer:[],open:function(W){let K=new E(W);if(this.dbs[b(K)]=K,this.dbList.indexOf(K)<0)this.dbList.push(K);return K},close:function(W,K){if(W){delete this.dbs[b(W)];let ue=W.filename,O=l.sqlite3__wasm_db_vfs(W.pointer,0);W.close();let R=this.dbList.indexOf(W);if(R>=0)this.dbList.splice(R,1);if(K&&ue&&O)l.sqlite3__wasm_vfs_unlink(O,ue)}},post:function(W,K){if(K&&K.length)globalThis.postMessage(W,Array.from(K)),K.length=0;else globalThis.postMessage(W)},dbs:Object.create(null),getDb:function(W,K=!0){return this.dbs[W]||(K?d("Unknown (or closed) DB ID:",W):void 0)}},V=function(W=I.dbList[0]){return W&&W.pointer?W:d("DB is not opened.")},U=function(W,K=!0){let ue=I.getDb(W.dbId,!1)||I.dbList[0];return K?V(ue):ue},N=function(){return I.dbList[0]&&b(I.dbList[0])},q={open:function(W){let K=Object.create(null),ue=W.args||Object.create(null);if(ue.simulateError)d("Throwing because of simulateError flag.");let O=Object.create(null);K.vfs=ue.vfs,K.filename=ue.filename||"";let R=I.open(K);return O.filename=R.filename,O.persistent=!!h.capi.sqlite3_js_db_uses_vfs(R.pointer,"opfs"),O.dbId=b(R),O.vfs=R.dbVfsName(),O},close:function(W){let K=U(W,!1),ue={filename:K&&K.filename};if(K){let O=W.args&&typeof W.args==="object"?!!W.args.unlink:!1;I.close(K,O)}return ue},exec:function(W){let K=typeof W.args==="string"?{sql:W.args}:W.args||Object.create(null);if(K.rowMode==="stmt")d("Invalid rowMode for 'exec': stmt mode","does not work in the Worker API.");else if(!K.sql)d("'exec' requires input SQL.");let ue=U(W);if(K.callback||Array.isArray(K.resultRows))ue._blobXfer=I.xfer;let O=K.callback,R=0,Q=!!K.columnNames;if(typeof O==="string"){if(!Q)K.columnNames=[];K.callback=function(ee,j){I.post({type:O,columnNames:K.columnNames,rowNumber:++R,row:ee},I.xfer)}}try{let ee=K.countChanges?ue.changes(!0,K.countChanges===64):void 0;if(ue.exec(K),ee!==void 0)K.changeCount=ue.changes(!0,K.countChanges===64)-ee;let j=K.lastInsertRowId?h.capi.sqlite3_last_insert_rowid(ue):void 0;if(j!==void 0)K.lastInsertRowId=j;if(K.callback instanceof Function)K.callback=O,I.post({type:O,columnNames:K.columnNames,rowNumber:null,row:void 0})}finally{if(delete ue._blobXfer,K.callback)K.callback=O}return K},"config-get":function(){let W=Object.create(null),K=h.config;return["bigIntEnabled"].forEach(function(ue){if(Object.getOwnPropertyDescriptor(K,ue))W[ue]=K[ue]}),W.version=h.version,W.vfsList=h.capi.sqlite3_js_vfs_list(),W},export:function(W){let K=U(W),ue={byteArray:h.capi.sqlite3_js_db_export(K.pointer),filename:K.filename,mimetype:"application/x-sqlite3"};return I.xfer.push(ue.byteArray.buffer),ue},toss:function(W){d("Testing worker exception")}};globalThis.onmessage=async function(W){W=W.data;let K,ue=W.dbId,O=W.type,R=performance.now();try{if(q.hasOwnProperty(O)&&q[O]instanceof Function)K=await q[O](W);else d("Unknown db worker message type:",W.type)}catch(Q){if(O="error",K={operation:W.type,message:Q.message,errorClass:Q.name,input:W},Q.stack)K.stack=typeof Q.stack==="string"?Q.stack.split(/\n\s*/):Q.stack}if(!ue)ue=K.dbId||N();I.post({type:O,dbId:ue,messageId:W.messageId,workerReceivedTime:R,workerRespondTime:performance.now(),departureTime:W.departureTime,result:K},I.xfer)},globalThis.postMessage({type:"sqlite3-api",result:"worker1-ready"})}.bind({sqlite3:f})}),globalThis.sqlite3ApiBootstrap.initializers.push(function(f){let{wasm:l,capi:d}=f,h=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))h("Expecting a sqlite3_vfs-type argument.");let I=d.sqlite3_vfs_register(this,b?1:0);if(I)h("sqlite3_vfs_register(",this,") failed with rc",I);if(this.pointer!==d.sqlite3_vfs_find(this.$zName))h("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 U of V){let N=b[U];if(N){if(++I,N.struct.installMethods(N.methods,!!N.applyArgcCheck),U==="vfs"){if(!N.struct.$zName&&typeof N.name==="string")N.struct.addOnDispose(N.struct.$zName=l.allocCString(N.name));N.struct.registerVfs(!!N.asDefault)}}}if(!I)h("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:l,capi:d}=f,h=f.util.toss3,E=Object.create(null);f.vtab=E;let b=d.sqlite3_index_info;b.prototype.nthConstraint=function(U,N=!1){if(U<0||U>=this.$nConstraint)return!1;let q=l.ptr.add(this.$aConstraint,b.sqlite3_index_constraint.structInfo.sizeof*U);return N?q:new b.sqlite3_index_constraint(q)},b.prototype.nthConstraintUsage=function(U,N=!1){if(U<0||U>=this.$nConstraint)return!1;let q=l.ptr.add(this.$aConstraintUsage,b.sqlite3_index_constraint_usage.structInfo.sizeof*U);return N?q:new b.sqlite3_index_constraint_usage(q)},b.prototype.nthOrderBy=function(U,N=!1){if(U<0||U>=this.$nOrderBy)return!1;let q=l.ptr.add(this.$aOrderBy,b.sqlite3_index_orderby.structInfo.sizeof*U);return N?q:new b.sqlite3_index_orderby(q)};let I=function(U,N){return function(q,W=!1){if(arguments.length===0)q=new N;if(q instanceof N)return this.set(q.pointer,q),q;else if(!l.isPtr(q))f.SQLite3Error.toss("Invalid argument to",U+"()");let K=this.get(q);if(W)this.delete(q);return K}.bind(new Map)},V=function(U,N){let q=I(U,N);return Object.assign(Object.create(null),{StructType:N,create:(W)=>{let K=q();return l.pokePtr(W,K.pointer),K},get:(W)=>q(W),unget:(W)=>q(W,!0),dispose:(W)=>q(W,!0)?.dispose?.()})};E.xVtab=V("xVtab",d.sqlite3_vtab),E.xCursor=V("xCursor",d.sqlite3_vtab_cursor),E.xIndexInfo=(U)=>new d.sqlite3_index_info(U),E.xError=function U(N,q,W){if(U.errorReporter instanceof Function)try{U.errorReporter("sqlite3_module::"+N+"(): "+q.message)}catch(ue){}let K;if(q instanceof f.WasmAllocError)K=d.SQLITE_NOMEM;else if(arguments.length>2)K=W;else if(q instanceof f.SQLite3Error)K=q.resultCode;return K||d.SQLITE_ERROR},E.xError.errorReporter=f.config.error.bind(f.config),E.xRowid=(U,N)=>l.poke(U,N,"i64"),E.setupModule=function(U){let N=!1,q=this instanceof d.sqlite3_module?this:U.struct||(N=new d.sqlite3_module);try{let W=U.methods||h("Missing 'methods' object.");for(let K of Object.entries({xConnect:"xCreate",xDisconnect:"xDestroy"})){let ue=K[0],O=K[1];if(W[ue]===!0)W[ue]=W[O];else if(W[O]===!0)W[O]=W[ue]}if(U.catchExceptions){let K=function(R,Q){if(["xConnect","xCreate"].indexOf(R)>=0)return function(ee,j,J,pe,S,C){try{return Q(...arguments)||0}catch(G){if(!(G instanceof f.WasmAllocError))l.dealloc(l.peekPtr(C)),l.pokePtr(C,l.allocCString(G.message));return E.xError(R,G)}};else return function(...ee){try{return Q(...ee)||0}catch(j){return E.xError(R,j)}}},ue=["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 ue){let Q=W[R];if(!(Q instanceof Function))continue;else if(R==="xConnect"&&W.xCreate===Q)O[R]=W.xCreate;else if(R==="xCreate"&&W.xConnect===Q)O[R]=W.xConnect;else O[R]=K(R,Q)}q.installMethods(O,!1)}else q.installMethods(W,!!U.applyArgcCheck);if(q.$iVersion===0){let K;if(typeof U.iVersion==="number")K=U.iVersion;else if(q.$xIntegrity)K=4;else if(q.$xShadowName)K=3;else if(q.$xSavePoint||q.$xRelease||q.$xRollbackTo)K=2;else K=1;q.$iVersion=K}}catch(W){if(N)N.dispose();throw W}return q},d.sqlite3_module.prototype.setupModule=function(U){return E.setupModule.call(this,U)}}),globalThis.sqlite3ApiBootstrap.initializers.push(function(f){if(f.config.disable?.vfs?.kvvfs)return;let l=f.capi,{sqlite3_kvvfs_methods:d,KVVfsFile:h}=l,E=f.capi.sqlite3_vfs_find("kvvfs");if(delete l.sqlite3_kvvfs_methods,delete l.KVVfsFile,!E)return;let{util:b,wasm:I}=f,V=b.toss3,U=new d(I.exports.sqlite3__wasm_kvvfs_methods());b.assert(32<=U.$nKeySize,"unexpected kvvfsMethods.$nKeySize: "+U.$nKeySize);let N=Object.assign(Object.create(null),{rxJournalSuffix:/-journal$/,zKeyJrnl:I.allocCString("jrnl"),zKeySz:I.allocCString("sz"),keySize:U.$nKeySize,buffer:Object.assign(Object.create(null),{n:U.$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=()=>{},W=f.__isUnderTest?(...B)=>f.config.debug?.("kvvfs:",...B):q,K=(...B)=>f.config.warn?.("kvvfs:",...B),ue=(...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",Q=(B)=>R(B)?"kvvfs-"+B+"-":"",ee=function(B,re=!1){if(R(B))return;let ae=new Blob([B]).size;if(!ae)V(l.SQLITE_MISUSE,"Empty name is not permitted.");let de=N.keySize-1;if(N.rxJournalSuffix.test(B)){if(!re)V(l.SQLITE_MISUSE,"Storage names may not have a '-journal' suffix.")}else if(["-wal","-shm"].filter((De)=>B.endsWith(De)).length)V(l.SQLITE_MISUSE,"Storage names may not have a -wal or -shm suffix.");else de-=8;if(ae>de)V(l.SQLITE_RANGE,"Storage name is too long. Limit =",de);let Se;for(Se=0;Se<ae;++Se){let De=B.codePointAt(Se);if(De<32)V(l.SQLITE_RANGE,"Illegal character ("+De+"d) in storage name:",B)}},j=(B,re=void 0)=>Object.assign(Object.create(null),{jzClass:B,refc:1,deleteAtRefc0:!1,storage:re||new O,keyPrefix:Q(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&&W("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,C=".";if(N.storagePool=Object.assign(Object.create(null),{[C]:j(C)}),globalThis.Storage){if(globalThis.localStorage instanceof globalThis.Storage)N.storagePool.local=j("local",globalThis.localStorage);if(globalThis.sessionStorage instanceof globalThis.Storage)N.storagePool.session=j("session",globalThis.sessionStorage)}N.builtinStorageNames=Object.keys(N.storagePool);let G=(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=l.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)=>{K("kvvfs.listener handler threw:",B)},Z=I.exports.sqlite3__wasm_kvvfs_decode,ge=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 de,Se,De,Ce;for(let Re of re.listeners){let Le=Object.create(null);Le.storageName=re.jzClass,Le.type=B,Re.decodePages;let Ke=Re.events[B];if(Ke){if(!Re.includeJournal&&ae[0]==="jrnl")continue;if(B==="write"&&Re.decodePages&&+ae[0]>0){if(Le.data=[ae[0]],Ce?.[ae[0]]){Le.data[1]=Ce[ae[0]];continue}de??=new TextEncoder("utf-8"),Se??=N.memBuffer(10),De??=N.memBuffer(11);let tt=de.encode(ae[1]),Ue=I.heap8u();Ue.set(tt,Number(Se)),Ue[I.ptr.addn(Se,tt.length)]=0;let vt=Z(Se,De,N.buffer.n);if(vt>0)Ce??=Object.create(null),Ce[ae[0]]=Le.data[1]=Ue.slice(Number(De),I.ptr.addn(De,vt));else continue}else Le.data=ae.length?ae.length===1?ae[0]:ae:void 0;try{Ke(Le)?.catch?.(oe)}catch(tt){K("notifyListeners [",re.jzClass,"]",B,tt)}}}}catch(de){oe(de)}},ye=(B)=>typeof B==="string"?N.storagePool[B]:N.storagePool[I.cstrToJs(B)],ve=I.exports.sqlite3__wasm_kvvfsMakeKey,M=(B,re,ae)=>re&&B.keyPrefix?ve(re,ae):ae,g=(B,re,ae)=>I.cstrToJs(M(B,re,ae)),w=(B)=>+B.storage.getItem(B.keyPrefix+"sz"),T=new Map,P={vfs:Object.create(null),ioDb:Object.create(null),ioJrnl:Object.create(null)},te=new l.sqlite3_vfs(U.$pVfs),se=new l.sqlite3_io_methods(U.$pIoDb),D=new l.sqlite3_io_methods(U.$pIoJrnl),L=Object.create(null),Y=Object.assign(Object.create(null),{pFileHandles:T,cache:N,storageForZClass:ye,KVVfsStorage:O,disablePageSizeChange:!0});if(J.log)J.internal=Y;let ne={recordHandler:{xRcrdRead:(B,re,ae,de)=>{try{let Se=I.cstrToJs(B),De=ye(Se);if(!De)return-1;let Ce=g(De,B,re);J?.log?.xRcrdRead&&K("xRcrdRead",Se,Ce,de,De);let Re=De.storage.getItem(Ce);if(Re===null)return-1;let Le=Re.length;if(de<=0)return Le;else if(de===1)return I.poke(ae,0),Le;if(de+1<Le)V(l.SQLITE_RANGE,"xRcrdRead()",Se,Ce,"input buffer is too small: need",Le,"but have",de);let Ke=N.memBuffer(0),tt=I.heap8(),Ue;for(Ue=0;Ue<Le;++Ue)tt[I.ptr.add(Ke,Ue)]=Re.codePointAt(Ue)&255;return tt.copyWithin(Number(ae),Number(Ke),I.ptr.addn(Ke,Ue)),tt[I.ptr.add(ae,Le)]=0,de}catch(Se){return ue("kvrecordRead()",Se),N.setError(Se),-2}},xRcrdWrite:(B,re,ae)=>{try{let de=ye(B),Se=g(de,B,re),De=I.cstrToJs(ae);return J?.log?.xRcrdWrite&&K("xRcrdWrite",Se,de),de.storage.setItem(Se,De),de.listeners&&we("write",de,Se,De),0}catch(de){return ue("kvrecordWrite()",de),N.setError(de,l.SQLITE_IOERR)}},xRcrdDelete:(B,re)=>{try{let ae=ye(B),de=g(ae,B,re);return J?.log?.xRcrdDelete&&K("xRcrdDelete",de,ae),ae.storage.removeItem(de),ae.listeners&&we("delete",ae,de),0}catch(ae){return ue("kvrecordDelete()",ae),N.setError(ae,l.SQLITE_IOERR)}}},vfs:{xOpen:function(B,re,ae,de,Se){N.popError();let De;try{if(!re)De=I.allocCString(""+ae+"."+(Math.random()*1e5|0)),re=De;let Ce=I.cstrToJs(re);if(J?.log?.xOpen&&W("xOpen",Ce,"flags =",de),ee(Ce,!0),de&(l.SQLITE_OPEN_MAIN_DB|l.SQLITE_OPEN_TEMP_DB|l.SQLITE_OPEN_TRANSIENT_DB)&&N.rxJournalSuffix.test(Ce))V(l.SQLITE_ERROR,"DB files may not have a '-journal' suffix.");let Re=ye(Ce);if(!Re&&!(de&l.SQLITE_OPEN_CREATE))V(l.SQLITE_ERROR,"Storage not found:",Ce);let Le=P.vfs.xOpen(B,re,ae,de,Se);if(Le)return Le;let Ke=!!(l.SQLITE_OPEN_DELETEONCLOSE&de);if(I.isPtr(arguments[1])){if(l.sqlite3_uri_boolean(re,"delete-on-close",0))Ke=!0}let tt=new h(ae);if(b.assert(tt.$zClass,"Missing f.$zClass"),tt.addOnDispose(De),De=void 0,Re)++Re.refc,Re.files.push(tt),I.poke32(Se,de);else{I.poke32(Se,de|l.SQLITE_OPEN_CREATE),b.assert(!tt.$isJournal,"Opening a journal before its db? "+Ce);let Ue=Ce.replace(N.rxJournalSuffix,"");Re=j(Ue),S(Re),Re.files.push(tt),Re.deleteAtRefc0=Ke,J?.log?.xOpen&&W("xOpen installed storage handle [",Ue,Ue+"-journal","]",Re)}return T.set(ae,{store:Re,file:tt,jzClass:Ce}),Re.listeners&&we("open",Re,Re.files.length),0}catch(Ce){return K("xOpen:",Ce),N.setError(Ce)}finally{De&&I.dealloc(De)}},xDelete:function(B,re,ae){N.popError();try{let de=I.cstrToJs(re);if(N.rxJournalSuffix.test(de))L.xRcrdDelete(re,N.zKeyJrnl);return 0}catch(de){return K("xDelete",de),N.setError(de)}},xAccess:function(B,re,ae,de){N.popError();try{let Se=ye(re),De=Se?.jzClass||I.cstrToJs(re);if(J?.log?.xAccess)W("xAccess",De,"flags =",ae,"*pResOut =",I.peek32(de),"store =",Se);if(!Se)try{ee(De)}catch(Ce){return I.poke32(de,0),0}if(Se){let Ce=Se.keyPrefix+(N.rxJournalSuffix.test(De)?"jrnl":"1"),Re=Se.storage.getItem(Ce)?0:1;I.poke32(de,Re)}else I.poke32(de,0);return 0}catch(Se){return ue("xAccess",Se),N.setError(Se)}},xRandomness:function(B,re,ae){let de=I.heap8u(),Se=0,De=Number(ae);for(;Se<re;++Se)de[De+Se]=Math.random()*255000&255;return re},xGetLastError:function(B,re,ae){let de=N.popError();if(W("xGetLastError",de),de){let Se=I.scopedAllocPush();try{let[De,Ce]=I.scopedAllocCString(de.message,!0);if(I.cstrncpy(ae,De,re),Ce>re)I.poke8(I.ptr.add(ae,re,-1),0);return W("set xGetLastError",de.message),de.resultCode|0||l.SQLITE_IOERR}catch(De){return l.SQLITE_NOMEM}finally{I.scopedAllocPop(Se)}}return 0}},ioDb:{xClose:function(B){N.popError();try{let re=T.get(B);if(J?.log?.xClose&&W("xClose",B,re),re){T.delete(B);let ae=re.store;if(ae.files=ae.files.filter((de)=>de!==re.file),--ae.refc<=0&&ae.deleteAtRefc0)pe(ae);P.ioDb.xClose(B),re.file.dispose(),ae.listeners&&we("close",ae,ae.files.length)}return 0}catch(re){return ue("xClose",re),N.setError(re)}},xFileControl:function(B,re,ae){N.popError();try{let de=T.get(B);if(b.assert(de,"Missing KVVfsFile handle"),J?.log?.xFileControl&&W("xFileControl",de,"op =",re),re===l.SQLITE_FCNTL_PRAGMA&&Y.disablePageSizeChange){let De=I.peekPtr(I.ptr.add(ae,I.ptr.size));if(I.cstrToJs(De)==="page_size"){J?.log?.xFileControl&&W("xFileControl pragma",I.cstrToJs(De));let Ce=I.peekPtr(I.ptr.add(ae,2*I.ptr.size));if(Ce)return J?.log?.xFileControl&&K("xFileControl pragma",de,"NOT setting page size to",I.cstrToJs(Ce)),de.file.$szPage=-1,0;else if(de.file.$szPage>0)return J?.log?.xFileControl&&K("xFileControl",de,"getting page size",de.file.$szPage),I.pokePtr(ae,I.allocCString(""+de.file.$szPage)),0}}let Se=P.ioDb.xFileControl(B,re,ae);if(Se==0&&l.SQLITE_FCNTL_SYNC===re)de.store.listeners&&we("sync",de.store,!1);return Se}catch(de){return ue("xFileControl",de),N.setError(de)}},xSync:function(B,re){N.popError();try{let ae=T.get(B);J?.log?.xSync&&W("xSync",ae),b.assert(ae,"Missing KVVfsFile handle");let de=P.ioDb.xSync(B,re);if(de==0&&ae.store.listeners)we("sync",ae.store,!0);return de}catch(ae){return ue("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,U[U.memberKey(re)]=I.installFunction(U.memberSignature(re),ae)}for(let B of Object.entries(ne.vfs)){let re=B[0],ae=B[1],de=te.memberKey(re),Se=te.structInfo.members[re]||b.toss("Missing pVfs.structInfo[",re,"]");P.vfs[re]=I.functionEntry(te[de]),te[de]=I.installFunction(Se.signature,ae)}for(let B of Object.entries(ne.ioDb)){let re=B[0],ae=B[1],de=se.memberKey(re);P.ioDb[re]=I.functionEntry(se[de])||b.toss("Missing native pIoDb[",de,"]"),se[de]=I.installFunction(se.memberSignature(re),ae)}for(let B of Object.entries(ne.ioJrnl)){let re=B[0],ae=B[1],de=D.memberKey(re);if(P.ioJrnl[re]=I.functionEntry(D[de])||b.toss("Missing native pIoJrnl[",de,"]"),ae===!0)D[de]=se[de]||b.toss("Missing copied pIoDb[",de,"]");else D[de]=I.installFunction(D.memberSignature(re),ae)}}finally{U.dispose(),te.dispose(),se.dispose(),D.dispose()}let be=function B(re){if(re==="")return B("local")+B("session");let ae=ye(re);if(!ae)return 0;if(ae.files.length)if(globalThis.localStorage===ae.storage||globalThis.sessionStorage===ae.storage);else V(l.SQLITE_ACCESS,"Cannot clear in-use database storage.");let de=ae.storage,Se=[],De,Ce=de.length;for(De=0;De<Ce;++De){let Re=de.key(De);if(!ae.keyPrefix||Re.startsWith(ae.keyPrefix))Se.push(Re)}return Se.forEach((Re)=>de.removeItem(Re)),Se.length},xe=function B(re){if(re==="")return B("local")+B("session");let ae=ye(re);if(!ae)return 0;let de=ae.storage,Se,De=0;for(Se=0;Se<de.length;++Se){let Ce=de.key(Se);if(!ae.keyPrefix||Ce.startsWith(ae.keyPrefix))De+=Ce.length,De+=de.getItem(Ce).length}return De*2},Pe=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 de=ae?ye(ae.name):null;if(!de)V(l.SQLITE_NOTFOUND,"There is no kvvfs storage named",ae?.name);let Se=de.storage,De=Object.assign(Object.create(null),{name:de.jzClass,timestamp:Date.now(),pages:[]}),Ce=Object.create(null),Re=de.keyPrefix,Le=Re?/^kvvfs-[^-]+-(\w+)/:void 0,Ke=0,tt=Se.length;for(;Ke<tt;++Ke){let Ue=Se.key(Ke);if(!Re||Ue.startsWith(Re)){let vt=(Re?Le.exec(Ue):void 0)?.[1]??Ue;switch(vt){case"jrnl":if(ae.includeJournal)De.journal=Se.getItem(Ue);break;case"sz":De.size=+Se.getItem(Ue);break;default:if(vt=+vt,!b.isInt32(vt)||vt<=0)V(l.SQLITE_RANGE,"Malformed kvvfs key: "+Ue);if(ae.decodePages){let Zt=Se.getItem(Ue),un=Zt.length,Xt=N.memBuffer(0),Lr=N.memBuffer(1),Un=I.heap8u(),Pt=0;for(;Pt<un;++Pt)Un[I.ptr.add(Xt,Pt)]=Zt.codePointAt(Pt)&255;Un[I.ptr.add(Xt,Pt)]=0;let Oo=Z(Xt,Lr,N.buffer.n);Ce[vt]=Un.slice(Number(Lr),I.ptr.addn(Lr,Oo))}else Ce[vt]=Se.getItem(Ue);break}}}if(ae.decodePages)N.memBufferFree(1);return Object.keys(Ce).map((Ue)=>+Ue).sort().forEach((Ue)=>De.pages.push(Ce[Ue])),De},$e=function(B,re=!1){if(!B?.timestamp||!B.name||B.size===void 0||!Array.isArray(B.pages))V(l.SQLITE_MISUSE,"Malformed export object.");else if(!B.size||B.size!==(B.size|0)||B.size>=2147483647)V(l.SQLITE_RANGE,"Invalid db size: "+B.size);ee(B.name);let ae=ye(B.name),de=!ae;if(ae){if(!re)V(l.SQLITE_ACCESS,"Storage '"+B.name+"' already exists and","overwrite was not specified.");else if(!ae.files||!ae.jzClass)V(l.SQLITE_ERROR,"Internal storage object",B.name,"seems to be malformed.");else if(ae.files.length)V(l.SQLITE_IOERR_ACCESS,"Cannot import db storage while it is in use.");be(B.name)}else ae=j(B.name);let Se=Q(B.name),De;try{let Ce=ae.storage;if(Ce.setItem(Se+"sz",B.size),B.journal)Ce.setItem(Se+"jrnl",B.journal);if(B.pages[0]instanceof Uint8Array)B.pages.forEach((Re,Le)=>{let Ke=Re.length;De??=N.memBuffer(1);let tt=N.memBuffer(0),Ue=I.heap8u();Ue.set(Re,Number(tt)),Ue[I.ptr.addn(tt,Ke)]=0;let vt=ge(tt,Ke,De);b.assert(vt<N.buffer.n,"Impossibly long output - possibly smashed the heap"),b.assert(I.peek8(I.ptr.add(De,vt))===0,"Expecting NUL-terminated encoded output");let Zt=I.cstrToJs(De);Ce.setItem(Se+(Le+1),Zt)});else if(B.pages[0])B.pages.forEach((Re,Le)=>Ce.setItem(Se+(Le+1),Re));if(de)S(ae)}catch{if(!de)try{be(B.name)}catch(Ce){}}finally{if(De)N.memBufferFree(1)}return this},Ve=function(B){let re=ye(B);if(re){++re.refc;return}ee(B),S(j(B))},ft=function(B){let re=ye(B);if(!re||R(re.jzClass)||G(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},Wt=function(B){if(!B||typeof B!=="object")V(l.SQLITE_MISUSE,"Expecting a listener object.");let re=ye(B.storage);if(!re)if(B.storage&&B.reserve)Ve(B.storage),re=ye(B.storage),b.assert(re,"Unexpectedly cannot fetch reserved storage "+B.storage);else V(l.SQLITE_NOTFOUND,"No such storage:",B.storage);if(B.events)(re.listeners??=[]).push(B)},qr=function(B){let re=ye(B?.storage);if(re?.listeners&&B.events){let ae=re.listeners.length;re.listeners=re.listeners.filter((Se)=>Se!==B);let de=ae>re.listeners.length;if(!re.listeners.length)re.listeners=void 0;return de}return!1};if(f.kvvfs.reserve=Ve,f.kvvfs.import=$e,f.kvvfs.export=Pe,f.kvvfs.unlink=ft,f.kvvfs.listen=Wt,f.kvvfs.unlisten=qr,f.kvvfs.exists=(B)=>!!ye(B),f.kvvfs.estimateSize=xe,f.kvvfs.clear=be,globalThis.Storage)l.sqlite3_js_kvvfs_size=(B="")=>xe(B),l.sqlite3_js_kvvfs_clear=(B="")=>be(B);if(f.oo1?.DB){let B=f.oo1.DB;f.oo1.JsStorageDb=function(ae=f.oo1.JsStorageDb.defaultStorageName){let de=B.dbCtorHelper.normalizeArgs(...arguments);switch(de.vfs="kvvfs",de.filename){case":sessionStorage:":de.filename="session";break;case":localStorage:":de.filename="local";break}let Se=/(file:(\/\/)?)([^?]+)/.exec(de.filename);ee(Se?Se[3]:de.filename),B.dbCtorHelper.call(this,de)},f.oo1.JsStorageDb.defaultStorageName=N.storagePool.session?"session":C;let re=f.oo1.JsStorageDb;re.prototype=Object.create(B.prototype),re.clearStorage=be,re.prototype.clearStorage=function(){return re.clearStorage(this.affirmOpen().dbFilename(),!0)},re.storageSize=xe,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((Ce,Re)=>B[Ce].colId=Re);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((Ce)=>!N.rxJournalSuffix.test(Ce))});let de=function(Ce,Re){let Le=Ce instanceof l.sqlite3_vtab_cursor?Ce:re.xCursor.get(Ce);if(Re||!Le.vTabState)Le.vTabState=Object.assign(Object.create(ae),{rowid:0,names:Object.keys(N.storagePool).filter((Ke)=>!N.rxJournalSuffix.test(Ke))});return Le.vTabState},Se=()=>{},De=function Ce(){return Ce.mod??=new f.capi.sqlite3_module().setupModule({catchExceptions:!0,methods:{xConnect:function(Re,Le,Ke,tt,Ue,vt){Se("xConnect");try{let Zt=[];Object.keys(B).forEach((Xt)=>{Zt.push(Xt+" "+B[Xt].type)});let un=l.sqlite3_declare_vtab(Re,"CREATE TABLE ignored("+Zt.join(",")+")");if(un===0){let Xt=re.xVtab.create(Ue);b.assert(Xt===re.xVtab.get(I.peekPtr(Ue)),"output pointer check failed")}return un}catch(Zt){return re.xError("xConnect",Zt,l.SQLITE_ERROR)}},xCreate:I.ptr.null,xDisconnect:function(Re){return Se("xDisconnect",...arguments),re.xVtab.dispose(Re),0},xOpen:function(Re,Le){return Se("xOpen",...arguments),re.xCursor.create(Le),0},xClose:function(Re){Se("xClose",...arguments);let Le=re.xCursor.unget(Re);return delete Le.vTabState,Le.dispose(),0},xNext:function(Re){Se("xNext",...arguments);let Le=re.xCursor.get(Re);return++de(Le).rowid,0},xColumn:function(Re,Le,Ke){Se("xColumn",...arguments);let tt=de(Re),Ue=tt.row();switch(b.assert(Ue,"Unexpected xColumn call"),Ke){case B.rowid.colId:l.sqlite3_result_int(Le,tt.rowid);break;case B.name.colId:l.sqlite3_result_text(Le,Ue.jzClass,-1,l.SQLITE_TRANSIENT);break;case B.nRef.colId:l.sqlite3_result_int(Le,Ue.refc);break;case B.nOpen.colId:l.sqlite3_result_int(Le,Ue.files.length);break;case B.isTransient.colId:l.sqlite3_result_int(Le,!!Ue.deleteAtRefc0);break;case B.dbSize.colId:l.sqlite3_result_int(Le,w(Ue));break;default:return l.sqlite3_result_error(Le,"Invalid column id: "+Ke),l.SQLITE_RANGE}return 0},xRowid:function(Re,Le){Se("xRowid",...arguments);let Ke=de(Re);return re.xRowid(Le,Ke.rowid),0},xEof:function(Re){let Le=de(Re);return Se("xEof?="+!Le.row(),...arguments),!Le.row()},xFilter:function(Re,Le,Ke,tt,Ue){return Se("xFilter",...arguments),de(Re,!0),0},xBestIndex:function(Re,Le){Se("xBestIndex",...arguments);let Ke=new l.sqlite3_index_info(Le);return Ke.$estimatedRows=N.storagePool.size,Ke.$estimatedCost=1,Ke.dispose(),0}}})};f.kvvfs.create_module=function(Ce,Re="sqlite_kvvfs"){return l.sqlite3_create_module(Ce,Re,De(),I.ptr.null)}}}),globalThis.sqlite3ApiBootstrap.initializers.push(function(f){if(f.config.disable?.vfs?.opfs&&f.config.disable.vfs["opfs-vfs"])return;let l=f.util.toss;f.capi;let d=f.util;f.wasm;let h=f.opfs=Object.create(null);h.thisThreadHasOPFS=()=>globalThis.FileSystemHandle&&globalThis.FileSystemDirectoryHandle&&globalThis.FileSystemFileHandle&&globalThis.FileSystemFileHandle.prototype.createSyncAccessHandle&&navigator?.storage?.getDirectory,h.getRootDir=async function b(){return b.promise??=navigator.storage.getDirectory().then((I)=>(h.rootDirectory=I,I)).catch((I)=>{throw delete b.promise,I})},h.getResolvedPath=function(b,I){let V=new URL(b,"file://irrelevant").pathname;return I?V.split("/").filter((U)=>!!U):V},h.getDirForFilename=async function(I,V=!1){let U=h.getResolvedPath(I,!0),N=U.pop(),q=await h.getRootDir();for(let W of U)if(W)q=await q.getDirectoryHandle(W,{create:!!V});return[q,N]},h.mkdir=async function(b){try{return await h.getDirForFilename(b+"/filepart",!0),!0}catch(I){return!1}},h.entryExists=async function(b){try{let[I,V]=await h.getDirForFilename(b);return await I.getFileHandle(V),!0}catch(I){return!1}},h.randomFilename=function b(I=16){if(!b._chars)b._chars="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012346789",b._n=b._chars.length;let V=[],U=0;for(;U<I;++U){let N=Math.random()*(b._n*64)%b._n|0;V[U]=b._chars[N]}return V.join("")},h.treeList=async function(){let b=async function V(U,N){N.name=U.name,N.dirs=[],N.files=[];for await(let q of U.values())if(q.kind==="directory"){let W=Object.create(null);N.dirs.push(W),await V(q,W)}else N.files.push(q.name)},I=Object.create(null);return await b(await h.getRootDir(),I),I},h.rmfr=async function(){let b=await h.getRootDir(),I={recurse:!0};for await(let V of b.values())b.removeEntry(V.name,I)},h.unlink=async function(b,I=!1,V=!1){try{let[U,N]=await h.getDirForFilename(b,!1);return await U.removeEntry(N,{recursive:I}),!0}catch(U){if(V)throw Error("unlink(",arguments[0],") failed: "+U.message,{cause:U});return!1}},h.traverse=async function(b){let I={recursive:!0,directory:await h.getRootDir()};if(typeof b==="function")b={callback:b};b=Object.assign(I,b||{}),async function V(U,N){for await(let q of U.values())if(b.callback(q,U,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,U]=await h.getDirForFilename(b,!0),N=await(await V.getFileHandle(U,{create:!0})).createSyncAccessHandle(),q=0,W,K=!1;try{N.truncate(0);while((W=await I())!==void 0){if(W instanceof ArrayBuffer)W=new Uint8Array(W);if(!K&&q===0&&W.byteLength>=15)d.affirmDbHeader(W),K=!0;N.write(W,{at:q}),q+=W.byteLength}if(q<512||q%512!==0)l("Input size",q,"is not correct for an SQLite database.");if(!K){let ue=new Uint8Array(20);N.read(ue,{at:0}),d.affirmDbHeader(ue)}return N.write(new Uint8Array([1,1]),{at:18}),q}catch(ue){throw await N.close(),N=void 0,await V.removeEntry(U).catch(()=>{}),ue}finally{if(N)await N.close()}};h.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,[U,N]=await h.getDirForFilename(b,!0),q,W=0;try{if(q=await(await U.getFileHandle(N,{create:!0})).createSyncAccessHandle(),q.truncate(0),W=q.write(I,{at:0}),W!=V)l("Expected to write "+V+" bytes but wrote "+W+".");return q.write(new Uint8Array([1,1]),{at:18}),W}catch(K){if(q)await q.close(),q=void 0;throw await U.removeEntry(N).catch(()=>{}),K}finally{if(q)await q.close()}},h.vfsInstallationFeatureCheck=function(b){if(!globalThis.SharedArrayBuffer||!globalThis.Atomics)l("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")l("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)l("Missing required OPFS APIs.");else if(b==="opfs-wl"&&!globalThis.Atomics.waitAsync)l("The",b,"VFS requires Atomics.waitAsync(), which is not available.")},h.initOptions=function(I,V){let U=new URL(globalThis.location.href).searchParams;if(U.has(I+"-disable"))return;try{h.vfsInstallationFeatureCheck(I)}catch(N){return}if(V=d.nu(V),V.vfsName=I,V.verbose??=U.has("opfs-verbose")?+U.get("opfs-verbose"):1,V.sanityChecks??=U.has("opfs-sanity-check"),!h.proxyUri){if(h.proxyUri="sqlite3-opfs-async-proxy.js",f.scriptInfo?.sqlite3Dir)h.proxyUri=f.scriptInfo.sqlite3Dir+h.proxyUri}if(V.proxyUri??=h.proxyUri,typeof V.proxyUri==="function")V.proxyUri=V.proxyUri();return h.options=V},h.createVfsState=function(){let b=d.nu(),I=h.options;b.verbose=I.verbose;let V=[f.config.error,f.config.warn,f.config.log],U=I.vfsName||l("Maintenance required: missing VFS name"),N=(Z,...ge)=>{if(b.verbose>Z)V[Z](U+":",...ge)},q=(...Z)=>N(2,...Z),W=(...Z)=>N(1,...Z),K=(...Z)=>N(0,...Z),{capi:ue,wasm:O}=f,R=b.vfs=new ue.sqlite3_vfs,Q=R.ioMethods=new ue.sqlite3_io_methods;Q.$iVersion=1,R.$iVersion=2,R.$szOsFile=ue.sqlite3_file.structInfo.sizeof,R.$mxPathname=1024,R.$zName=O.allocCString(U),R.addOnDispose("$zName",R.$zName,Q),R.metrics=d.nu({counters:d.nu(),dump:function(){let Z,ge=0,we=0,ye=0;for(Z in b.opIds){let ve=ee[Z];ge+=ve.count,we+=ve.time,ye+=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,`
534
+ Total of`,ge,"op(s) for",we,"ms (incl. "+ye+" 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 Z,ge=(ve)=>ve.count=ve.time=ve.wait=0,we=R.metrics.counters;for(Z in b.opIds)ge(we[Z]=Object.create(null));let ye=we.s11n=Object.create(null);ye=ye.serialize=Object.create(null),ye.count=ye.time=0,ye=we.s11n.deserialize=Object.create(null),ye.count=ye.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 Z=0;b.opIds.whichOp=Z++,b.opIds.rc=Z++,b.opIds.xAccess=Z++,b.opIds.xClose=Z++,b.opIds.xDelete=Z++,b.opIds.xDeleteNoWait=Z++,b.opIds.xFileSize=Z++,b.opIds.xLock=Z++,b.opIds.xOpen=Z++,b.opIds.xRead=Z++,b.opIds.xSleep=Z++,b.opIds.xSync=Z++,b.opIds.xTruncate=Z++,b.opIds.xUnlock=Z++,b.opIds.xWrite=Z++,b.opIds.mkdir=Z++,b.opIds["opfs-async-metrics"]=Z++,b.opIds["opfs-async-shutdown"]=Z++,b.opIds.retry=Z++,b.sabOP=new SharedArrayBuffer(Z*4)}b.sq3Codes=Object.create(null);for(let Z 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[Z]=ue[Z]??l("Maintenance required: not found:",Z);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,j=R.opRun=(Z,...ge)=>{let we=b.opIds[Z]||l(R.vfsName+": Invalid op ID:",Z);b.s11n.serialize(...ge),Atomics.store(b.sabOPView,b.opIds.rc,-1),Atomics.store(b.sabOPView,b.opIds.whichOp,we),Atomics.notify(b.sabOPView,b.opIds.whichOp);let ye=performance.now();while(Atomics.wait(b.sabOPView,b.opIds.rc,-1)!=="not-equal");let ve=Atomics.load(b.sabOPView,b.opIds.rc);if(ee[Z].wait+=performance.now()-ye,ve&&b.asyncS11nExceptions){let M=b.s11n.deserialize();if(M)K(Z+"() async error:",...M)}return ve},J=Object.create(null);J.op=void 0,J.start=void 0;let pe=R.mTimeStart=(Z)=>{J.start=performance.now(),J.op=Z,++ee[Z].count},S=R.mTimeEnd=()=>ee[J.op].time+=performance.now()-J.start,C=R.__openFiles=Object.create(null);R.ioSyncWrappers=d.nu({xCheckReservedLock:function(Z,ge){return O.poke(ge,0,"i32"),0},xClose:function(Z){pe("xClose");let ge=0,we=C[Z];if(we){if(delete C[Z],ge=j("xClose",Z),we.sq3File)we.sq3File.dispose()}return S(),ge},xDeviceCharacteristics:function(Z){return ue.SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN},xFileControl:function(Z,ge,we){return ue.SQLITE_NOTFOUND},xFileSize:function(Z,ge){pe("xFileSize");let we=j("xFileSize",Z);if(we==0)try{let ye=b.s11n.deserialize()[0];O.poke(ge,ye,"i64")}catch(ye){K("Unexpected error reading xFileSize() result:",ye),we=b.sq3Codes.SQLITE_IOERR}return S(),we},xRead:function(Z,ge,we,ye){pe("xRead");let ve=C[Z],M;try{if(M=j("xRead",Z,we,Number(ye)),M===0||ue.SQLITE_IOERR_SHORT_READ===M)O.heap8u().set(ve.sabView.subarray(0,we),Number(ge))}catch(g){K("xRead(",arguments,") failed:",g,ve),M=ue.SQLITE_IOERR_READ}return S(),M},xSync:function(Z,ge){pe("xSync");let we=j("xSync",Z,ge);return S(),we},xTruncate:function(Z,ge){pe("xTruncate");let we=j("xTruncate",Z,Number(ge));return S(),we},xWrite:function(Z,ge,we,ye){pe("xWrite");let ve=C[Z],M;try{ve.sabView.set(O.heap8u().subarray(Number(ge),Number(ge)+we)),M=j("xWrite",Z,we,Number(ye))}catch(g){K("xWrite(",arguments,") failed:",g,ve),M=ue.SQLITE_IOERR_WRITE}return S(),M}}),R.vfsSyncWrappers={xAccess:function(Z,ge,we,ye){pe("xAccess");let ve=j("xAccess",O.cstrToJs(ge));return O.poke(ye,ve?0:1,"i32"),S(),0},xCurrentTime:function(Z,ge){return O.poke(ge,2440587.5+new Date().getTime()/86400000,"double"),0},xCurrentTimeInt64:function(Z,ge){return O.poke(ge,210866760000000+new Date().getTime(),"i64"),0},xDelete:function(Z,ge,we){pe("xDelete");let ye=j("xDelete",O.cstrToJs(ge),we,!1);return S(),ye},xFullPathname:function(Z,ge,we,ye){return O.cstrncpy(ye,ge,we)<we?0:ue.SQLITE_CANTOPEN},xGetLastError:function(Z,ge,we){return f.config.warn("OPFS xGetLastError() has nothing sensible to return."),0},xOpen:function(ge,we,ye,ve,M){pe("xOpen");let g=0,w,T;if(!we)w=h.randomFilename(),we=T=O.allocCString(w);else if(O.isPtr(we)){if(ue.sqlite3_uri_boolean(we,"opfs-unlock-asap",0))g|=b.opfsFlags.OPFS_UNLOCK_ASAP;if(ue.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),ue.SQLITE_CANTOPEN;let P=d.nu({fid:ye,filename:w,sab:new SharedArrayBuffer(b.fileBufferSize),flags:ve,readOnly:!(ue.SQLITE_OPEN_CREATE&ve)&&!!(ve&ue.SQLITE_OPEN_READONLY)}),te=j("xOpen",ye,w,ve,g);if(te){if(T)O.dealloc(T)}else{if(P.readOnly)O.poke(M,ue.SQLITE_OPEN_READONLY,"i32");if(C[ye]=P,P.sabView=b.sabFileBufView,P.sq3File=new ue.sqlite3_file(ye),T)P.sq3File.addOnDispose(T);P.sq3File.$pMethods=Q.pointer,P.lockType=ue.SQLITE_LOCK_NONE}return S(),te}};let G=ue.sqlite3_vfs_find(null);if(G){let Z=new ue.sqlite3_vfs(G);R.$xRandomness=Z.$xRandomness,R.$xSleep=Z.$xSleep,Z.dispose()}if(!R.$xRandomness)R.vfsSyncWrappers.xRandomness=function(Z,ge,we){let ye=O.heap8u(),ve=0,M=Number(we);for(;ve<ge;++ve)ye[M+ve]=Math.random()*255000&255;return ve};if(!R.$xSleep)R.vfsSyncWrappers.xSleep=function(Z,ge){return pe("xSleep"),Atomics.wait(b.sabOPView,b.opIds.xSleep,0,ge),S(),0};let oe=function(){if(b.s11n)return b.s11n;let Z=new TextDecoder,ge=new TextEncoder("utf-8"),we=new Uint8Array(b.sabIO,b.sabS11nOffset,b.sabS11nSize),ye=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 M=(w)=>ve[typeof w]||l("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:l("Invalid type ID:",w)}};return b.s11n.deserialize=function(w=!1){performance.now();let T=we[0],P=T?[]:null;if(T){let te=[],se=1,D,L,Y;for(D=0;D<T;++D,++se)te.push(g(we[se]));for(D=0;D<T;++D){let ne=te[D];if(ne.getter)Y=ye[ne.getter](se,b.littleEndian),se+=ne.size;else L=ye.getInt32(se,b.littleEndian),se+=4,Y=Z.decode(we.slice(se,se+L)),se+=L;P.push(Y)}}if(w)we[0]=0;return P},b.s11n.serialize=function(...w){if(performance.now(),w.length){let T=[],P=0,te=1;we[0]=w.length&255;for(;P<w.length;++P,++te)T.push(M(w[P])),we[te]=T[P].id;for(P=0;P<w.length;++P){let se=T[P];if(se.setter)ye[se.setter](te,w[P],b.littleEndian),te+=se.size;else{let D=ge.encode(w[P]);ye.setInt32(te,D.byteLength,b.littleEndian),te+=4,we.set(D,te),te+=D.byteLength}}}else we[0]=0},b.s11n};return R.initS11n=oe,R.bindVfs=function(Z,ge){return Object.assign(R.ioSyncWrappers,Z),new Promise(function(we,ye){let ve=void 0,M=(D)=>(ve=!0,R.dispose(),ye(D)),g=()=>{try{ge(f,R)}catch(D){return M(D)}return ve=!1,we(f)},w=h.options;w.proxyUri+(w.proxyUri.indexOf("?")<0?"?":"&")+U;let T=new URL("sqlite3-opfs-async-proxy.js",import.meta.url);T.searchParams.set("vfs",U);let P=R.worker=new Worker(T.toString()),te=setTimeout(()=>{if(ve===void 0)M(Error("Timeout while waiting for OPFS async proxy worker."))},4000);P._originalOnError=P.onerror,P.onerror=function(D){K("Error initializing OPFS asyncer:",D),M(Error("Loading OPFS async Worker failed for unknown reasons."))},R.opRun;let se=function(){let D=O.scopedAllocPush(),L=new ue.sqlite3_file;try{let Y=L.pointer,ne=ue.SQLITE_OPEN_CREATE|ue.SQLITE_OPEN_READWRITE|ue.SQLITE_OPEN_MAIN_DB,be=O.scopedAlloc(8),xe="/sanity/check/file"+randomFilename(8),Pe=O.scopedAllocCString(xe),$e;if(b.s11n.serialize("This is ä string."),$e=b.s11n.deserialize(),q("deserialize() says:",$e),$e[0]!=="This is ä string.")l("String d13n error.");if(R.vfsSyncWrappers.xAccess(R.pointer,Pe,0,be),$e=O.peek(be,"i32"),q("xAccess(",xe,") exists ?=",$e),$e=R.vfsSyncWrappers.xOpen(R.pointer,Pe,Y,ne,be),q("open rc =",$e,"state.sabOPView[xOpen] =",b.sabOPView[b.opIds.xOpen]),$e!==0){K("open failed with code",$e);return}if(R.vfsSyncWrappers.xAccess(R.pointer,Pe,0,be),$e=O.peek(be,"i32"),!$e)l("xAccess() failed to detect file.");if($e=R.ioSyncWrappers.xSync(L.pointer,0),$e)l("sync failed w/ rc",$e);if($e=R.ioSyncWrappers.xTruncate(L.pointer,1024),$e)l("truncate failed w/ rc",$e);if(O.poke(be,0,"i64"),$e=R.ioSyncWrappers.xFileSize(L.pointer,be),$e)l("xFileSize failed w/ rc",$e);if(q("xFileSize says:",O.peek(be,"i64")),$e=R.ioSyncWrappers.xWrite(L.pointer,Pe,10,1),$e)l("xWrite() failed!");let Ve=O.scopedAlloc(16);$e=R.ioSyncWrappers.xRead(L.pointer,Ve,6,2),O.poke(Ve+6,0);let ft=O.cstrToJs(Ve);if(q("xRead() got:",ft),ft!=="sanity")l("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($e=R.ioSyncWrappers.xClose(Y),q("xClose rc =",$e,"sabOPView =",b.sabOPView),q("Deleting file:",xe),R.vfsSyncWrappers.xDelete(R.pointer,Pe,4660),R.vfsSyncWrappers.xAccess(R.pointer,Pe,0,be),$e=O.peek(be,"i32"),$e)l("Expecting 0 from xAccess(",xe,") after xDelete().");W("End of OPFS sanity checks.")}finally{L.dispose(),O.scopedAllocPop(D)}};P.onmessage=function({data:D}){switch(D.type){case"opfs-unavailable":M(Error(D.payload.join(" ")));break;case"opfs-async-loaded":delete b.vfs,P.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)W("Running sanity checks because of opfs-sanity-check URL arg..."),se();if(h.thisThreadHasOPFS())h.getRootDir().then((L)=>{P.onerror=P._originalOnError,delete P._originalOnError,q("End of OPFS sqlite3_vfs setup.",R),g()}).catch(M);else g()}catch(L){K(L),M(L)}break;case"debug":W("debug message from worker:",D);break;default:{let L="Unexpected message from the OPFS async worker: "+JSON.stringify(D);K(L),M(Error(L));break}}}})},b}}),globalThis.sqlite3ApiBootstrap.initializers.push(function(f){if(!f.opfs||f.config.disable?.vfs?.opfs)return;let l=f.util,d=f.opfs||f.util.toss("Missing sqlite3.opfs"),h=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:U,mTimeEnd:N,opRun:q,__openFiles:W}=I;return I.bindVfs(l.nu({xLock:function(K,ue){U("xLock"),++V.xLock.count;let O=W[K],R=0;if(O.lockType)O.lockType=ue;else if(R=q("xLock",K,ue),R===0)O.lockType=ue;return N(),R},xUnlock:function(K,ue){U("xUnlock"),++V.xUnlock.count;let O=W[K],R=0;if(b.SQLITE_LOCK_NONE===ue&&O.lockType)R=q("xUnlock",K,ue);if(R===0)O.lockType=ue;return N(),R}}),function(K,ue){if(K.oo1){let O=function(...R){let Q=K.oo1.DB.dbCtorHelper.normalizeArgs(...R);Q.vfs=ue.$zName,K.oo1.DB.dbCtorHelper.call(this,Q)};O.prototype=Object.create(K.oo1.DB.prototype),K.oo1.OpfsDb=O,O.importDb=d.importDb,K.oo1.DB.dbCtorHelper.setVfsPostOpenCallback(I.pointer,function(R,Q){Q.capi.sqlite3_busy_timeout(R,1e4)})}})};globalThis.sqlite3ApiBootstrap.initializersAsync.push(async(E)=>h().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 l=f.util.toss,d=f.util.toss3,h=Object.create(null),{capi:E,util:b,wasm:I}=f,V=4096,U=512,N=4,q=8,W=U+N,K=U,ue=W,O=V,R=E.SQLITE_OPEN_MAIN_DB|E.SQLITE_OPEN_MAIN_JOURNAL|E.SQLITE_OPEN_SUPER_JOURNAL|E.SQLITE_OPEN_WAL,Q=E.SQLITE_OPEN_MEMORY,ee=".opaque",j=()=>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}),C=[f.config.error,f.config.warn,f.config.log];f.config.log;let G=f.config.warn;f.config.error;let oe=new Map,Z=(D)=>oe.get(D),ge=(D,L)=>{if(L)oe.set(D,L);else oe.delete(D)},we=new Map,ye=(D)=>we.get(D),ve=(D,L)=>{if(L)we.set(D,L);else we.delete(D)},M={xCheckReservedLock:function(D,L){let Y=ye(D);return Y.log("xCheckReservedLock"),Y.storeErr(),I.poke32(L,1),0},xClose:function(D){let L=ye(D);L.storeErr();let Y=L.getOFileForS3File(D);if(Y)try{if(L.log(`xClose ${Y.path}`),L.mapS3FileToOFile(D,!1),Y.sah.flush(),Y.flags&E.SQLITE_OPEN_DELETEONCLOSE)L.deletePath(Y.path)}catch(ne){return L.storeErr(ne,E.SQLITE_IOERR)}return 0},xDeviceCharacteristics:function(D){return E.SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN},xFileControl:function(D,L,Y){return E.SQLITE_NOTFOUND},xFileSize:function(D,L){let Y=ye(D);Y.log("xFileSize");let ne=Y.getOFileForS3File(D).sah.getSize()-O;return I.poke64(L,BigInt(ne)),0},xLock:function(D,L){let Y=ye(D);Y.log(`xLock ${L}`),Y.storeErr();let ne=Y.getOFileForS3File(D);return ne.lockType=L,0},xRead:function(D,L,Y,ne){let be=ye(D);be.storeErr();let xe=be.getOFileForS3File(D);be.log(`xRead ${xe.path} ${Y} @ ${ne}`);try{let Pe=xe.sah.read(I.heap8u().subarray(Number(L),Number(L)+Y),{at:O+Number(ne)});if(Pe<Y)return I.heap8u().fill(0,Number(L)+Pe,Number(L)+Y),E.SQLITE_IOERR_SHORT_READ;return 0}catch(Pe){return be.storeErr(Pe,E.SQLITE_IOERR)}},xSectorSize:function(D){return V},xSync:function(D,L){let Y=ye(D);Y.log(`xSync ${L}`),Y.storeErr();let ne=Y.getOFileForS3File(D);try{return ne.sah.flush(),0}catch(be){return Y.storeErr(be,E.SQLITE_IOERR)}},xTruncate:function(D,L){let Y=ye(D);Y.log(`xTruncate ${L}`),Y.storeErr();let ne=Y.getOFileForS3File(D);try{return ne.sah.truncate(O+Number(L)),0}catch(be){return Y.storeErr(be,E.SQLITE_IOERR)}},xUnlock:function(D,L){let Y=ye(D);Y.log("xUnlock");let ne=Y.getOFileForS3File(D);return ne.lockType=L,0},xWrite:function(D,L,Y,ne){let be=ye(D);be.storeErr();let xe=be.getOFileForS3File(D);be.log(`xWrite ${xe.path} ${Y} ${ne}`);try{return Y===xe.sah.write(I.heap8u().subarray(Number(L),Number(L)+Y),{at:O+Number(ne)})?0:l("Unknown write() failure.")}catch(Pe){return be.storeErr(Pe,E.SQLITE_IOERR)}}},g=new E.sqlite3_io_methods;g.$iVersion=1,f.vfs.installVfs({io:{struct:g,methods:M}});let w={xAccess:function(D,L,Y,ne){let be=Z(D);be.storeErr();try{let xe=be.getPath(L);I.poke32(ne,be.hasFilename(xe)?1:0)}catch(xe){I.poke32(ne,0)}return 0},xCurrentTime:function(D,L){return I.poke(L,2440587.5+new Date().getTime()/86400000,"double"),0},xCurrentTimeInt64:function(D,L){return I.poke(L,210866760000000+new Date().getTime(),"i64"),0},xDelete:function(D,L,Y){let ne=Z(D);ne.log(`xDelete ${I.cstrToJs(L)}`),ne.storeErr();try{return ne.deletePath(ne.getPath(L)),0}catch(be){return ne.storeErr(be),E.SQLITE_IOERR_DELETE}},xFullPathname:function(D,L,Y,ne){return I.cstrncpy(ne,L,Y)<Y?0:E.SQLITE_CANTOPEN},xGetLastError:function(D,L,Y){let ne=Z(D),be=ne.popErr();if(ne.log(`xGetLastError ${L} e =`,be),be){let xe=I.scopedAllocPush();try{let[Pe,$e]=I.scopedAllocCString(be.message,!0);if(I.cstrncpy(Y,Pe,L),$e>L)I.poke8(I.ptr.add(Y,L,-1),0)}catch(Pe){return E.SQLITE_NOMEM}finally{I.scopedAllocPop(xe)}}return be?be.sqlite3Rc||E.SQLITE_IOERR:0},xOpen:function(L,Y,ne,be,xe){let Pe=Z(L);try{be&=~Q,Pe.log(`xOpen ${I.cstrToJs(Y)} ${be}`);let $e=Y&&I.peek8(Y)?Pe.getPath(Y):j(),Ve=Pe.getSAHForPath($e);if(!Ve&&be&E.SQLITE_OPEN_CREATE)if(Pe.getFileCount()<Pe.getCapacity())Ve=Pe.nextAvailableSAH(),Pe.setAssociatedPath(Ve,$e,be);else l("SAH pool is full. Cannot create file",$e);if(!Ve)l("file not found:",$e);let ft={path:$e,flags:be,sah:Ve};Pe.mapS3FileToOFile(ne,ft),ft.lockType=E.SQLITE_LOCK_NONE;let Wt=new E.sqlite3_file(ne);return Wt.$pMethods=g.pointer,Wt.dispose(),I.poke32(xe,be),0}catch($e){return Pe.storeErr($e),E.SQLITE_CANTOPEN}}},T=function(D){if(f.capi.sqlite3_vfs_find(D))d("VFS name is already registered:",D);let L=new E.sqlite3_vfs,Y=E.sqlite3_vfs_find(null),ne=Y?new E.sqlite3_vfs(Y):null;if(L.$iVersion=2,L.$szOsFile=E.sqlite3_file.structInfo.sizeof,L.$mxPathname=U,L.addOnDispose(L.$zName=I.allocCString(D),()=>ge(L.pointer,0)),ne)L.$xRandomness=ne.$xRandomness,L.$xSleep=ne.$xSleep,ne.dispose();if(!L.$xRandomness&&!w.xRandomness)w.xRandomness=function(be,xe,Pe){let $e=I.heap8u(),Ve=0,ft=Number(Pe);for(;Ve<xe;++Ve)$e[ft+Ve]=Math.random()*255000&255;return Ve};if(!L.$xSleep&&!w.xSleep)w.xSleep=(be,xe)=>0;return f.vfs.installVfs({vfs:{struct:L,methods:w}}),L};class P{vfsDir;#e;#o;#i;#t=new Map;#r=new Map;#s=new Set;#c=new Map;#n=new Uint8Array(W);#l;#a;#d;constructor(D=Object.create(null)){this.#d=D.verbosity??S.verbosity,this.vfsName=D.name||S.name,this.#a=T(this.vfsName),ge(this.#a.pointer,this),this.vfsDir=D.directory||"."+this.vfsName,this.#l=new DataView(this.#n.buffer,this.#n.byteOffset),this.isReady=this.reset(!!(D.clearOnInit??S.clearOnInit)).then(()=>{if(this.$error)throw this.$error;return this.getCapacity()?Promise.resolve(void 0):this.addCapacity(D.initialCapacity||S.initialCapacity)})}#u(D,...L){if(this.#d>D)C[D](this.vfsName+":",...L)}log(...D){this.#u(2,...D)}warn(...D){this.#u(1,...D)}error(...D){this.#u(0,...D)}getVfs(){return this.#a}getCapacity(){return this.#t.size}getFileCount(){return this.#r.size}getFileNames(){let D=[];for(let L of this.#r.keys())D.push(L);return D}async addCapacity(D){for(let L=0;L<D;++L){let Y=j(),ne=await(await this.#o.getFileHandle(Y,{create:!0})).createSyncAccessHandle();this.#t.set(ne,Y),this.setAssociatedPath(ne,"",0)}return this.getCapacity()}async reduceCapacity(D){let L=0;for(let Y of Array.from(this.#s)){if(L===D||this.getFileCount()===this.getCapacity())break;let ne=this.#t.get(Y);Y.close(),await this.#o.removeEntry(ne),this.#t.delete(Y),this.#s.delete(Y),++L}return L}releaseAccessHandles(){for(let D of this.#t.keys())D.close();this.#t.clear(),this.#r.clear(),this.#s.clear()}async acquireAccessHandles(D=!1){let L=[];for await(let[Y,ne]of this.#o)if(ne.kind==="file")L.push([Y,ne]);return Promise.all(L.map(async([Y,ne])=>{try{let be=await ne.createSyncAccessHandle();if(this.#t.set(be,Y),D)be.truncate(O),this.setAssociatedPath(be,"",0);else{let xe=this.getAssociatedPath(be);if(xe)this.#r.set(xe,be);else this.#s.add(be)}}catch(be){throw this.storeErr(be),this.releaseAccessHandles(),be}}))}getAssociatedPath(D){D.read(this.#n,{at:0});let L=this.#l.getUint32(K);if(this.#n[0]&&(L&E.SQLITE_OPEN_DELETEONCLOSE||(L&R)===0))return G(`Removing file with unexpected flags ${L.toString(16)}`,this.#n),this.setAssociatedPath(D,"",0),"";let Y=new Uint32Array(q/4);D.read(Y,{at:ue});let ne=this.computeDigest(this.#n,L);if(Y.every((be,xe)=>be===ne[xe])){let be=this.#n.findIndex((xe)=>xe===0);if(be===0)D.truncate(O);return be?J.decode(this.#n.subarray(0,be)):""}else return G("Disassociating file with bad digest."),this.setAssociatedPath(D,"",0),""}setAssociatedPath(D,L,Y){let ne=pe.encodeInto(L,this.#n);if(U<=ne.written+1)l("Path too long:",L);if(L&&Y)Y|=Q;this.#n.fill(0,ne.written,U),this.#l.setUint32(K,Y);let be=this.computeDigest(this.#n,Y);if(D.write(this.#n,{at:0}),D.write(be,{at:ue}),D.flush(),L)this.#r.set(L,D),this.#s.delete(D);else D.truncate(O),this.#s.add(D)}computeDigest(D,L){if(L&Q){let Y=3735928559,ne=1103547991;for(let be of D)Y=Math.imul(Y^be,2654435761),ne=Math.imul(ne^be,104729);return new Uint32Array([Y>>>0,ne>>>0])}else return new Uint32Array([0,0])}async reset(D){await this.isReady;let L=await navigator.storage.getDirectory(),Y;for(let ne of this.vfsDir.split("/"))if(ne)Y=L,L=await L.getDirectoryHandle(ne,{create:!0});return this.#e=L,this.#i=Y,this.#o=await this.#e.getDirectoryHandle(ee,{create:!0}),this.releaseAccessHandles(),this.acquireAccessHandles(D)}getPath(D){if(I.isPtr(D))D=I.cstrToJs(D);return(D instanceof URL?D:new URL(D,"file://localhost/")).pathname}deletePath(D){let L=this.#r.get(D);if(L)this.#r.delete(D),this.setAssociatedPath(L,"",0);return!!L}storeErr(D,L){if(D)D.sqlite3Rc=L||E.SQLITE_IOERR,this.error(D);return this.$error=D,L}popErr(){let D=this.$error;return this.$error=void 0,D}nextAvailableSAH(){let[D]=this.#s.keys();return D}getOFileForS3File(D){return this.#c.get(D)}mapS3FileToOFile(D,L){if(L)this.#c.set(D,L),ve(D,this);else this.#c.delete(D),ve(D,!1)}hasFilename(D){return this.#r.has(D)}getSAHForPath(D){return this.#r.get(D)}async removeVfs(){if(!this.#a.pointer||!this.#o)return!1;E.sqlite3_vfs_unregister(this.#a.pointer),this.#a.dispose(),delete h[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(D){f.config.error(this.vfsName,"removeVfs() failed with no recovery strategy:",D)}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(D){//! Documented elsewhere in this file.
535
+ let L=this.#r.get(D)||l("File not found:",D),Y=L.getSize()-O,ne=new Uint8Array(Y>0?Y:0);if(Y>0){let be=L.read(ne,{at:O});if(be!=Y)l("Expected to read "+Y+" bytes but read "+be+".")}return ne}async importDbChunked(D,L){//! Impl for importDb() when its 2nd arg is a function.
536
+ let Y=this.#r.get(D)||this.nextAvailableSAH()||l("No available handles to import to.");Y.truncate(0);let ne=0,be,xe=!1;try{while((be=await L())!==void 0){if(be instanceof ArrayBuffer)be=new Uint8Array(be);if(!xe&&ne===0&&be.byteLength>=15)b.affirmDbHeader(be),xe=!0;Y.write(be,{at:O+ne}),ne+=be.byteLength}if(ne<512||ne%512!==0)l("Input size",ne,"is not correct for an SQLite database.");if(!xe){let Pe=new Uint8Array(20);Y.read(Pe,{at:0}),b.affirmDbHeader(Pe)}Y.write(new Uint8Array([1,1]),{at:O+18})}catch(Pe){throw this.setAssociatedPath(Y,"",0),Pe}return this.setAssociatedPath(Y,D,E.SQLITE_OPEN_MAIN_DB),ne}importDb(D,L){//! Documented elsewhere in this file.
537
+ if(L instanceof ArrayBuffer)L=new Uint8Array(L);else if(L instanceof Function)return this.importDbChunked(D,L);let Y=this.#r.get(D)||this.nextAvailableSAH()||l("No available handles to import to."),ne=L.byteLength;if(ne<512||ne%512!=0)l("Byte array size is invalid for an SQLite db.");let be="SQLite format 3";for(let Pe=0;Pe<15;++Pe)if(be.charCodeAt(Pe)!==L[Pe])l("Input does not contain an SQLite database header.");let xe=Y.write(L,{at:O});if(xe!=ne)this.setAssociatedPath(Y,"",0),l("Expected to write "+ne+" bytes but wrote "+xe+".");else Y.write(new Uint8Array([1,1]),{at:O+18}),this.setAssociatedPath(Y,D,E.SQLITE_OPEN_MAIN_DB);return xe}}class te{#e;constructor(D){this.#e=D,this.vfsName=D.vfsName}async addCapacity(D){return this.#e.addCapacity(D)}async reduceCapacity(D){return this.#e.reduceCapacity(D)}getCapacity(){return this.#e.getCapacity(this.#e)}getFileCount(){return this.#e.getFileCount()}getFileNames(){return this.#e.getFileNames()}async reserveMinimumCapacity(D){let L=this.#e.getCapacity();return L<D?this.#e.addCapacity(D-L):L}exportFile(D){return this.#e.exportFile(D)}importDb(D,L){return this.#e.importDb(D,L)}async wipeFiles(){return this.#e.reset(!0)}unlink(D){return this.#e.deletePath(D)}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 D=await navigator.storage.getDirectory(),L=".opfs-sahpool-sync-check-"+j(),Y=(await(await D.getFileHandle(L,{create:!0})).createSyncAccessHandle()).close();if(await Y,await D.removeEntry(L),Y?.then)l("The local OPFS API is too old for opfs-sahpool:","it has an async FileSystemSyncAccessHandle.close() method.");return!0};f.installOpfsSAHPoolVfs=async function(D=Object.create(null)){D=Object.assign(Object.create(null),S,D||{});let L=D.name;if(D.$testThrowPhase1)throw D.$testThrowPhase1;if(h[L])try{return await h[L]}catch(Y){if(D.forceReinitIfPreviouslyFailed)delete h[L];else throw Y}if(!globalThis.FileSystemHandle||!globalThis.FileSystemDirectoryHandle||!globalThis.FileSystemFileHandle||!globalThis.FileSystemFileHandle.prototype.createSyncAccessHandle||!navigator?.storage?.getDirectory)return h[L]=Promise.reject(Error("Missing required OPFS APIs."));return h[L]=se().then(async function(){if(D.$testThrowPhase2)throw D.$testThrowPhase2;let Y=new P(D);return Y.isReady.then(async()=>{let ne=new te(Y);if(f.oo1){let be=f.oo1,xe=Y.getVfs(),Pe=function(...$e){let Ve=be.DB.dbCtorHelper.normalizeArgs(...$e);Ve.vfs=xe.$zName,be.DB.dbCtorHelper.call(this,Ve)};Pe.prototype=Object.create(be.DB.prototype),ne.OpfsSAHPoolDb=Pe}return Y.log("VFS initialized."),ne}).catch(async(ne)=>{throw await Y.removeVfs().catch(()=>{}),ne})}).catch((Y)=>h[L]=Promise.reject(Y))}}),globalThis.sqlite3ApiBootstrap.initializers.push(function(f){if(!f.opfs||f.config.disable?.vfs?.["opfs-wl"])return;let l=f.util;f.util.toss;let d=f.opfs,h="opfs-wl",E=async function(b){if(b=d.initOptions(h,b),!b)return f;f.capi;let I=d.createVfsState().vfs;I.metrics.counters;let{mTimeStart:V,mTimeEnd:U,opRun:N,__openFiles:q}=I;return I.bindVfs(l.nu({xLock:function(W,K){V("xLock");let ue=q[W],O=N("xLock",W,K);if(!O)ue.lockType=K;return U(),O},xUnlock:function(W,K){V("xUnlock");let ue=q[W],O=N("xUnlock",W,K);if(!O)ue.lockType=K;return U(),O}}),function(W,K){if(W.oo1){let ue=function(...O){let R=W.oo1.DB.dbCtorHelper.normalizeArgs(...O);R.vfs=K.$zName,W.oo1.DB.dbCtorHelper.call(this,R)};ue.prototype=Object.create(W.oo1.DB.prototype),W.oo1.OpfsWlDb=ue,ue.importDb=d.importDb}})};globalThis.sqlite3ApiBootstrap.initializersAsync.push(async(b)=>E().catch((I)=>{b.config.warn("Ignoring inability to install the",h,"sqlite3_vfs:",I)}))});try{let f=Object.assign(Object.create(null),{memory:typeof pr<"u"?pr:u.wasmMemory,exports:typeof ln<"u"?ln:Object.prototype.hasOwnProperty.call(u,"wasmExports")?u.wasmExports:u.asm},globalThis.sqlite3ApiBootstrap.defaultConfig,globalThis.sqlite3ApiConfig||{});i.debugModule("Bootstrapping lib config",f);let l=globalThis.sqlite3ApiBootstrap(f);return delete globalThis.sqlite3ApiBootstrap,l}catch(f){throw console.error("sqlite3ApiBootstrap() error:",f),f}},Oe)t=r;else t=new Promise((i,u)=>{_e=i,le=u});return t}os=function(){let e=os;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 ll=os;class ss{db;txDepth=0;constructor(e){this.db=e}query(e){let t=this.db;return{get(...r){return t.selectObject(e,is(r))??null},all(...r){return t.selectObjects(e,is(r))},run(...r){return t.exec({sql:e,bind:is(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 is(e){if(e.length===0)return;return e.map((t)=>t===void 0?null:t)}Qo();Kt();St();Xe();var Te=(e,t,r)=>Number(e)===1?t:r;var Ru={刚刚:"just now","{n} 分钟前":({n:e})=>`${e} ${Te(e,"minute","minutes")} ago`,"{n} 小时前":({n:e})=>`${e} ${Te(e,"hour","hours")} ago`,"{n} 天前":({n:e})=>`${e} ${Te(e,"day","days")} ago`,今天:"Today",昨天:"Yesterday",本周:"This week","{n} 天后过期":({n:e})=>`Expires in ${e} ${Te(e,"day","days")}`,"{n} 小时后过期":({n:e})=>`Expires in ${e} ${Te(e,"hour","hours")}`,"{n} 分钟后过期":({n:e})=>`Expires in ${e} ${Te(e,"minute","minutes")}`,"快照 {when}":"Snapshot {when}",还没有活动:"No activity yet","{ago}活跃":"Active {ago}","{day}后无活动":"Inactive since {day}",从未:"Never",无标题:"Untitled",语言:"Language",跟随系统:"System","更改语言后页面会重新加载。":"The page reloads after changing the language.",本地副本未就绪:"Local replica is not ready","请先撤销所有 Edge Room 再断开":"Revoke all Edge Rooms before disconnecting","此设备不驻留在线托管,目前仅支持通过 Edge 发布站点":"This device is not hosted online; sites can only be published through Edge for now","请先连接 Edge":"Connect Edge first","当前 Edge 仅支持 inbox,不支持 Room 托管":"This Edge only supports inbox, not Room hosting","此浏览器通过同步存储桶交换数据、不驻留在线;请在在线主节点管理公开发布":"This browser exchanges data through the sync bucket and is not hosted online; manage public publishing on the online primary node","当前离线,且此浏览器尚未启用本地副本。请先在线打开 Metahub,在设置中开启「离线副本」。":"You are offline and this browser has no local replica yet. Open Metahub online first and enable “Offline replica” in Settings.","离线副本中没有这个页面。":"This page is not in the offline replica.","此资源不是页面,无法离线打开。":"This resource is not a page and cannot be opened offline.","此页面以二进制块存储,无法离线打开。":"This page is stored as a binary blob and cannot be opened offline.","离线加载失败:{msg}":"Offline load failed: {msg}","正在从本地副本加载…":"Loading from the local replica…"};var Au={复制链接:"Copy link",复制内链:"Copy internal link","通过设备分享…":"Share via device…","导出 Markdown":"Export Markdown","导出 CSV":"Export CSV","保存中…":"Saving…",已保存:"Saved",分享:"Share",保存:"Save","保存到同步存储桶失败:{msg}":"Failed to save to the sync bucket: {msg}",保存到同步存储桶:"Save to sync bucket",仍有改动尚未保存到同步存储桶:"Some changes are not yet saved to the sync bucket","保存失败:{msg}":"Save failed: {msg}","按 ID 打开…":"Open by ID…",搜索:"Search",打开设置:"Open settings","折叠 / 展开侧栏":"Collapse / expand sidebar",后退:"Back",前进:"Forward","块 / 代码方式切换":"Toggle blocks / source view",宽屏模式:"Wide mode",版本历史:"Version history","复制 ID":"Copy ID",块方式显示:"Show as blocks",代码方式显示:"Show as source",创建副本:"Duplicate","{title} 副本":"{title} copy","重命名…":"Rename…",重命名文档:"Rename document",删除文档:"Delete document",删除:"Delete",最近动态:"Recent activity",重命名数据库:"Rename database",删除数据库:"Delete database","删除数据库?":"Delete database?","「{name}」及其所有记录将被永久删除。":"“{name}” and all of its records will be permanently deleted.",返回:"Back",展开侧栏:"Expand sidebar",站点配置:"Site settings",配置:"Settings",菜单:"Menu","搜索:“{q}”":"Search: “{q}”",设置:"Settings",站点管理:"Sites",站点:"Sites",发布与分享:"Publish & share",更多:"More","⚡ 离线 — 本地副本模式:可正常查看和编辑全部内容,恢复连接后自动同步":"⚡ Offline — local replica mode: everything stays readable and editable, syncs when the connection returns","⚡ 离线 — 可浏览已缓存的内容,修改会失败;恢复网络后自动恢复":"⚡ Offline — cached content is readable, edits will fail; resumes when the network returns","数据库不存在或已被删除。":"This database does not exist or was deleted.","加载中…":"Loading…",空空如也:"Nothing here yet","从左侧选择一个数据库或文档,或新建一个开始。":"Pick a database or document on the left, or create one to get started.","+ 新建文档":"+ New document",文档:"Documents",记录:"Record","正在从同步存储桶恢复本地副本…":"Restoring the local replica from the sync bucket…",数据表:"Databases",新建文档:"New document",新建数据库:"New database","侧栏:文档":"Sidebar: documents","侧栏:数据表":"Sidebar: databases","侧栏:站点":"Sidebar: sites",移出折叠组:"Unfold",折叠此数据库:"Fold this database",新建子页:"New subpage",移到顶层:"Move to top level",有可用更新:"Update available",收起侧栏:"Collapse sidebar",新建站点:"New site","搜索…":"Search…","已折叠 · {n}":"Folded · {n}",名称:"Name",状态:"Status",待办:"To do",进行中:"In progress",已完成:"Done",优先级:"Priority",高:"High",中:"Medium",低:"Low",截止:"Due",姓名:"Name",公司:"Company",分类:"Category",客户:"Customer",合作:"Partner",潜在:"Lead",邮箱:"Email",空白:"Blank","仅一个「名称」列":"Just a “Name” column",任务:"Tasks","状态·优先级·截止":"Status · Priority · Due",联系人:"Contacts","公司·分类·邮箱":"Company · Category · Email",未命名数据库:"Unnamed database","已创建数据库「{name}」":"Created database “{name}”","创建一个带属性列的结构化数据表。":"Create a structured table with property columns.",取消:"Cancel",创建:"Create","例如:项目、客户、库存…":"e.g. Projects, Customers, Inventory…",图标:"Icon",模板:"Template",导航:"Navigation",新建:"Create",编辑器:"Editor",快速笔记:"Quick Note",命令面板:"Command palette","关闭菜单 / 弹窗":"Close menu / dialog",保存到同步桶:"Save to sync bucket",文内查找:"Find in document",复制当前块:"Duplicate current block",列表缩进:"Indent list item",列表反缩进:"Outdent list item",新建笔记:"New note",上一条笔记:"Previous note",下一条笔记:"Next note",在主窗口中打开:"Open in main window",隐藏小窗:"Hide window",外观:"Appearance",快速小窗:"Quick windows",离线与缓存:"Offline & cache",数据与备份:"Data & backup","设备##page":"Devices",操作审计:"Audit log",站点与发布:"Sites & publishing",快捷键:"Shortcuts",关于:"About",失败:"Failed",重试:"Retry",移除:"Remove","拖动调整宽度,双击复原":"Drag to resize, double-click to reset",确定:"OK",数据库:"Database",未命名记录:"Unnamed record",打开:"Open","输入 ID、前缀或名称":"Enter an ID, prefix or name","搜索页面、输入命令或粘贴 ID":"Search pages, type a command or paste an ID",清空:"Clear","未找到 {ref},可能未同步或已删除":"{ref} not found — it may not be synced yet or was deleted",没有匹配的页面或命令:"No matching pages or commands",暂无可用命令:"No commands available",最近打开:"Recent",命令:"Commands",内容匹配:"Content matches",选择:"Select","可粘贴 ID 或链接":"You can paste an ID or link","文档##kind":"Document","没有找到“{q}”":"Nothing found for “{q}”","换个关键词试试,或用命令面板按标题、ID 直达。":"Try another keyword, or jump by title or ID from the command palette.",打开命令面板:"Open command palette",键盘快捷键:"Keyboard shortcuts","还没有文档,新建一个":"No documents yet — create one","还没有数据表,新建一个":"No databases yet — create one","还没有站点,新建一个":"No sites yet — create one","在全部内容中搜索 “{q}”":"Search all content for “{q}”","已删除「{title}」":"Deleted “{title}”","已删除「{title}」及 {n} 个子页":({title:e,n:t})=>`Deleted “${e}” and ${t} ${Te(t,"subpage","subpages")}`,"撤销##undo":"Undo",已删除笔记:"Note deleted","下载中 · {n}":"Downloading · {n}","正在下载本地副本,已接收 {n} 条变更":"Downloading the local replica, {n} changes received",同步中:"Syncing",正在与服务器同步:"Syncing with the server",已更新:"Updated",已同步:"Synced",同步失败:"Sync failed","上次同步失败:{msg} · 本地读写不受影响,点击查看":"Last sync failed: {msg} · local reads and writes are unaffected, click for details",未知错误:"Unknown error",当前文档:"Current document","标注「仅桌面应用」的组合键被浏览器保留,只在桌面应用里可用。":"Shortcuts marked “Desktop app only” are reserved by the browser and only work in the desktop app.",仅桌面应用:"Desktop app only",正在加载:"Loading",链接已复制:"Link copied","内链已复制,可粘贴到任意文档":"Internal link copied — paste it into any document",已是最新:"Already up to date","已复制 ID":"ID copied",已创建副本:"Copy created"};var Du={"在独立窗口中打开":"Open in Separate Window","无法打开独立窗口:{msg}":"Could not open window: {msg}","已保存到本机":"Saved on this device","有未保存修改":"Unsaved changes","需要处理冲突":"Resolve conflict","保存失败":"Save failed","文档尚未保存,草稿已保留。":"Document not saved. Your draft has been retained.","查看草稿":"View draft","文档不存在或已被删除。未保存内容仍可导出。":"This document no longer exists. You can still export your unsaved work.","载入最新版本?":"Load the latest version?","未保存的本地改动将被丢弃。":"Your unsaved local changes will be discarded.","用本地版本覆盖?":"Replace with your local version?","其他位置的修改将被当前草稿替换。":"Changes made elsewhere will be replaced with this draft.","本地草稿":"Local draft","另存草稿":"Save draft as new document","草稿已另存为文档":"Draft saved as a new document",没有匹配的页面:"No matching pages",没有匹配的块:"No matching blocks",上一个:"Previous",下一个:"Next","查找:下一个":"Find: next","查找:上一个":"Find: previous",文件:"File",纯文本:"Plain text",文本:"Text",普通段落:"Plain paragraph","标题 1":"Heading 1",大号标题:"Large heading","标题 2":"Heading 2",中号标题:"Medium heading","标题 3":"Heading 3",小号标题:"Small heading",无序列表:"Bulleted list",项目符号:"Bullet points",有序列表:"Numbered list",编号列表:"Numbered items",待办清单:"To-do list",复选项:"Checkboxes",引用:"Quote",引用块:"Quote block",代码:"Code",代码块:"Code block",表格:"Table",插入表格:"Insert a table",分隔线:"Divider",水平分隔:"Horizontal rule",图片:"Image",上传或拖入图片:"Upload or drop an image",视频:"Video",上传视频文件:"Upload a video file",音频:"Audio",上传音频文件:"Upload an audio file",上传任意文件:"Upload any file","嵌入并渲染 HTML":"Embed and render HTML","保存失败:{msg}":"Save failed: {msg}","加载中…":"Loading…","文档已被其他端修改,自动保存已暂停。":"This document was changed elsewhere; autosave is paused.","载入最新(弃本地改动)":"Load latest (discard local changes)",用本地版本覆盖:"Overwrite with local version","已分享 · 管理分享":"Shared · Manage sharing",已分享:"Shared",未知错误:"Unknown error",同步失败:"Sync failed","上次同步 {when}":"Last synced {when}",实时同步:"Live sync",对齐方式:"Alignment",左对齐:"Align left",居中:"Center",右对齐:"Align right",在左侧插入列:"Insert column left",在右侧插入列:"Insert column right",复制列:"Duplicate column",左移列:"Move column left",右移列:"Move column right",删除列:"Delete column",在上方插入行:"Insert row above",在下方插入行:"Insert row below",复制行:"Duplicate row",上移行:"Move row up",下移行:"Move row down",删除行:"Delete row",行选项:"Row options",列选项:"Column options",复制:"Copy",清空:"Clear",新增列:"Add column",新增行:"Add row",表头:"Header","输入代码…":"Type code…",关闭自动换行:"Turn off line wrap","自动换行(所有代码块)":"Line wrap (all code blocks)",换行:"Wrap","格式化代码 (Shift+Alt+F)":"Format code (Shift+Alt+F)","格式化中…":"Formatting…",已格式化:"Formatted",失败:"Failed",格式化:"Format",复制代码:"Copy code",已复制:"Copied","转换为({n} 行)":({n:e})=>`Turn into (${e} ${Te(e,"line","lines")})`,转换为:"Turn into",复制块组:"Duplicate blocks",复制块:"Duplicate block",删除块组:"Delete blocks",删除块:"Delete block",在下方插入:"Insert below","拖动重排 / 点击菜单":"Drag to reorder / click for menu",媒体:"Media",字节未同步到本设备或加载失败:"Not synced to this device or failed to load",重试:"Retry","上传中…":"Uploading…","双击预览 / 标注":"Double-click to preview / annotate",预览:"Preview",下载文件:"Download file",矩形框选:"Rectangle",箭头:"Arrow",文字:"Text","撤销 (⌘Z)":"Undo (⌘Z)","重做 (⇧⌘Z)":"Redo (⇧⌘Z)",取消:"Cancel","保存中…":"Saving…",保存:"Save",关闭:"Close",在文档中查找:"Find in document",无结果:"No results",区分大小写:"Match case",全词匹配:"Whole word",全词:"Word",缩小:"Zoom out",重置:"Reset",放大:"Zoom in","标注 / 编辑":"Annotate / edit",加粗:"Bold",斜体:"Italic",删除线:"Strikethrough",行内代码:"Inline code",链接:"Link",插入链接:"Insert link",链接地址:"URL","{name} 超过 {mb}MB 上限":"{name} exceeds the {mb}MB limit","上传失败:{msg}":"Upload failed: {msg}","已选 {n} 字":"{n} words selected","{n} 字符":"{n} chars","{n} 字":"{n} words","约 {n} 分钟阅读":"~{n} min read","JSON 解析失败:{msg}":"JSON parse failed: {msg}","格式化组件加载失败(离线?):{msg}":"Formatter failed to load (offline?): {msg}",文档不存在或未同步:"Document does not exist or is not synced","⏳ 正在上传 {name}…":"⏳ Uploading {name}…",文档目录:"Table of contents",列1:"Column 1",列2:"Column 2",基础块:"Basic blocks",链接到:"Link to",'输入文本,"/" 唤出命令':'Type text, "/" for commands',"HTML 预览":"HTML preview",编辑源码:"Edit source",源码:"Source"};var Ou={上一条:"Previous",下一条:"Next",复制失败:"Copy failed","{n} 列已隐藏":({n:e})=>`${e} ${Te(e,"column","columns")} hidden`,"{n} 项":({n:e})=>`${e} ${Te(e,"item","items")}`,"{name} 副本":"{name} copy","「{name}」的筛选、排序和隐藏列设置将一并删除,记录不受影响。":"The filters, sorts and hidden columns of “{name}” will be deleted. Records are not affected.",按属性筛选:"Filter by property",包含:"contains",包含全部:"contains all of",包含任一:"contains any of",本月:"This month",标题列始终显示:"The title column is always shown",不包含:"does not contain",不等于:"is not",不是:"is not",不晚于:"is on or before",不为空:"is not empty",不早于:"is on or after",等于:"is","调整或清除筛选条件后会再次显示记录。":"Adjust or clear the filters to see records again.",都不包含:"contains none of",非空:"Filled",复制视图:"Duplicate view","改为「{type}」会清空这一列的 {n} 个单元格,可在版本历史中回滚。":({type:e,n:t})=>`Changing to “${e}” clears ${t} ${Te(t,"cell","cells")} in this column. You can roll back from version history.`,"更改属性类型?":"Change property type?",关闭搜索:"Close search","过去 30 天":"Past 30 days","过去 7 天":"Past 7 days",还没有选项:"No options yet","还有 {n} 个隐藏的属性":({n:e})=>`${e} more hidden ${Te(e,"property","properties")}`,"换个关键词,或清除筛选条件。":"Try another keyword, or clear the filters.",换行文本:"Wrap text",计数:"Count",计算:"Calculate",满足全部:"Match all",满足任一:"Match any",没有符合条件的记录:"No records match",没有匹配的属性:"No matching properties",平均:"Average",求和:"Sum",全部显示:"Show all",筛选:"Filter",筛选此列:"Filter by this column",删除视图:"Delete view","删除视图?":"Delete view?",是:"is",收起隐藏的属性:"Hide hidden properties",属性:"Properties",数值:"Number",搜索属性:"Search properties",添加排序:"Add sort",晚于:"is after",唯一值:"Unique",为空:"is empty",未勾选:"Unchecked","未来 30 天":"Next 30 days","未来 7 天":"Next 7 days",未选择:"None selected",无:"None","显示 {m} / {n} 条记录":"Showing {m} of {n} records",显示:"Show","新建视图 · 选择布局":"New view · Choose a layout",新建视图:"New view","选择…":"Choose…",移除排序:"Remove sort",移除筛选:"Remove filter",已勾选:"Checked",隐藏:"Hide",隐藏全部:"Hide all",右侧插入列:"Insert column right",在表中搜索:"Search in table","在表中搜索…":"Search in table…",在范围内:"is within",早于:"is before",中位数:"Median",重命名视图:"Rename view",最大:"Max",最小:"Min",左侧插入列:"Insert column left",已撤销:"Undone",已重做:"Redone","{n} 个单元格因类型不匹配未写入":({n:e})=>`${e} ${Te(e,"cell","cells")} skipped: value doesn't fit the column type`,设置属性:"Set property","设置属性…":"Set property…",勾选:"Check",取消勾选:"Uncheck",应用:"Apply",编辑单元格:"Edit cell",选中整行:"Select row",选中全部单元格:"Select all cells",复制单元格:"Copy cells",粘贴到单元格:"Paste into cells",清空单元格:"Clear cells",撤销单元格修改:"Undo cell edit",重做:"Redo",清除:"Clear","↑↓ 换日 · ↵ 选定":"↑↓ day · ↵ pick","看板视图需要一个「单选」或「多选」属性来分组。请在表格视图中添加一个单选列后再切换到看板。":"The board needs a select or multi-select property to group by. Add one in the table view, then switch back.",按属性分组:"Group by property","分组:{name}":"Group: {name}",多选分组不支持拖拽改值:"Dragging can't reassign a multi-select group",未分组:"Ungrouped",看板:"Board",日历:"Calendar",时间轴:"Timeline",在浮窗中打开这个数据库的看板:"Open this database's board in a floating window",记录不存在或已被删除:"Record does not exist or has been deleted",移动属性:"Move property",排序:"Sort",清除排序后可拖拽移动:"Clear the sort to drag rows",拖拽移动:"Drag to move",新建属性:"New property",新建记录:"New record","共 {n} 条记录":({n:e})=>`${e} ${Te(e,"record","records")}`,"{n} 已选":"{n} selected","删除记录?":"Delete record?","确定删除选中的 {n} 条记录?":({n:e})=>`Delete the ${e} selected ${Te(e,"record","records")}?`,"已删除 {n} 条记录":({n:e})=>`Deleted ${e} ${Te(e,"record","records")}`,"{n} 个单元格":({n:e})=>`${e} ${Te(e,"cell","cells")}`,填充:"Fill",移动记录:"Move record","创建选项失败:{msg}":"Failed to create option: {msg}",搜索或创建选项:"Search or create an option","创建记录失败:{msg}":"Failed to create record: {msg}",搜索或创建记录:"Search or create a record",该属性未设置关联目标:"This property has no relation target",无法加载目标数据表:"Could not load the target database",目标数据表暂无记录:"The target database has no records yet","还有 {n} 条,继续输入过滤":({n:e})=>`${e} more ${Te(e,"match","matches")}, keep typing to filter`,"创建文档失败:{msg}":"Failed to create document: {msg}",搜索或创建文档:"Search or create a document","暂无文档,输入标题创建":"No documents yet; type a title to create one","更新属性失败:{msg}":"Failed to update property: {msg}","选项 1":"Option 1","选项 2":"Option 2",已存在同名选项:"An option with that name already exists","重命名选项失败:{msg}":"Failed to rename option: {msg}",至少保留一个选项:"Keep at least one option","删除选项?":"Delete option?","「{name}」将从所有使用它的记录中清除。":"“{name}” will be cleared from every record that uses it.","删除选项失败:{msg}":"Failed to delete option: {msg}",属性类型:"Property type",选项:"Options",确认:"Confirm",重命名选项:"Rename option",删除选项:"Delete option",添加选项:"Add option",关联目标:"Relation target",选择关联的数据表:"Choose the related database","新建属性失败:{msg}":"Failed to create property: {msg}",删除属性:"Delete property","删除属性?":"Delete property?","「{name}」及其所有单元格数据将被移除。":"“{name}” and all of its cell data will be removed.",搜索数据表:"Search databases",没有匹配的数据表:"No matching databases",还没有数据库:"No databases yet",没有匹配的记录:"No matching records",没有匹配的文档:"No matching documents",没有匹配的选项:"No matching options","还没有选项,输入名称创建":"No options yet — type a name to create one",升序:"Ascending",还没有记录:"No records yet","新建一条记录,或从 CLI 导入。":"Create a record, or import from the CLI.","没有符合筛选的动态。":"No activity matches the filters.",降序:"Descending",当前表:"Current table","新建属性 · 选择类型":"New property · Choose a type",排序依据:"Sort by",清除排序:"Clear sort",打开记录:"Open record",复制记录:"Duplicate record",删除记录:"Delete record",返回字段:"Back to fields",字段修改历史:"Field history",在主视图打开:"Open in main view",修复:"Repair",回滚:"Rollback",本设备:"This device","(空)":"(empty)","{n} 块修改":({n:e})=>`${e} ${Te(e,"block","blocks")} changed`,"{n} 块删除":({n:e})=>`${e} ${Te(e,"block","blocks")} deleted`,元数据:"Metadata",变更:"Changes",源码:"Source","展开 {n} 个未变更块":({n:e})=>`Show ${e} unchanged ${Te(e,"block","blocks")}`,"展开 {n} 行未变更内容":({n:e})=>`Show ${e} unchanged ${Te(e,"line","lines")}`,"恢复到此版本?":"Restore this version?","标题和正文将恢复到 {when} 的状态。此操作会作为一次新修订记录,任何版本都仍可从历史找回。":"The title and body will be restored to their state at {when}. This is recorded as a new revision; every version stays recoverable from history.",恢复:"Restore",已恢复:"Restored","文档刚被其他端修改,已刷新,请重试":"The document was just changed elsewhere and has been refreshed; please try again",当前:"Current",取消对比基准:"Unpin comparison base","设为对比基准(Shift+点击)":"Pin as comparison base (Shift+click)","{n} 次连续小修改":({n:e})=>`${e} consecutive small ${Te(e,"edit","edits")}`,显示修复:"Show repairs","对比基准:{when}":"Comparing against: {when}",清除基准:"Clear base",此修订删除了文档:"This revision deleted the document",初始版本:"Initial version","更早的修订已被存储压缩合并,此处按整篇新增显示":"Earlier revisions were compacted in storage, so this one shows as a whole-document addition","两个版本相同。":"The two versions are identical.","(空文档)":"(empty document)","此修订未改动正文。":"This revision did not change the body.",恢复到此版本:"Restore this version","「{name}」字段历史":"History of “{name}”","该单元格的每一次写入,最新在前。":"Every write to this cell, newest first.","暂无写入记录。":"No writes yet.","(清空)":"(cleared)",已删除:"Deleted",调整排序:"Reordered",全部记录:"All records",全部设备:"All devices",清除筛选:"Clear filters","暂无动态。":"No activity yet.",只看这条记录:"Only this record","(已删字段)":"(deleted field)","…还有 {n} 项":({n:e})=>`…${e} more ${Te(e,"item","items")}`,"记录字段将恢复到该修订时的值。此操作会作为一次新修订记录。":"The record's fields will be restored to their values at that revision. This is recorded as a new revision.",修改历史:"Edit history","暂无历史。":"No history yet.",查看此字段完整历史:"View this field's full history",字段:"Field",站点渠道:"Site channel",站点文件:"Site file",文档块:"Document block",附件策略:"Attachment policy","修改##audit":"Edited",段落:"Paragraph",撤销这组改动:"Undo this change set","会以一次新的正向修改还原到改动前的状态,本身也会记入审计,可以再撤销。之后被其他编辑覆盖过的字段会保留,不会被回退。":"Restores the pre-change state as a new forward edit, which is itself audited and can be undone. Fields overwritten by later edits are kept, not rolled back.",撤销改动:"Undo changes","已恢复 {n} 项,保留了 {kept} 项更晚的编辑":({n:e,kept:t})=>`Restored ${e} ${Te(e,"item","items")}, kept ${t} later ${Te(t,"edit","edits")}`,"已恢复 {n} 项":({n:e})=>`Restored ${e} ${Te(e,"item","items")}`,"无需恢复:已是改动前的状态":"Nothing to restore: already in the pre-change state",全部:"All","AI 操作":"AI actions",这台设备:"This device",其他设备:"Other devices","工作区里每一次改动:谁、什么时候、改了什么。AI 通过命令行做的操作会标出来,可以逐条检查并撤销。":"Every change in the workspace: who, when, and what. Actions the AI made through the command line are marked so you can review and undo them one by one.","还没有 AI 操作的记录。":"No AI actions recorded yet.","暂无改动记录。":"No changes recorded yet.",以一次新的正向修改撤销这组改动:"Undo this change set with a new forward edit","撤销##audit":"Undo","早期版本的改动,仅可查看摘要。":"Change from an earlier version; only the summary is available.",",":", ",显示更早的记录:"Show earlier changes","已显示全部 · 只保留最近 90 天,更早的改动已合并且无法撤销":"That's everything · Only the last 90 days are kept; earlier changes were merged and cannot be undone","日历视图需要一个「日期」属性。请在表格视图中添加一个日期列后再切换到日历。":"The calendar view needs a Date property. Add a date column in the table view, then switch to the calendar.",按日期属性:"By date property",上个月:"Previous month",下个月:"Next month","{date} · {n} 条记录":({date:e,n:t})=>`${e} · ${t} ${Te(t,"record","records")}`,"+{n} 更多":"+{n} more","时间轴视图需要一个「日期」属性作为开始日期。请在表格视图中添加一个日期列后再切换到时间轴。":"The timeline view needs a Date property as the start date. Add a date column in the table view, then switch to the timeline.",开始日期:"Start date","结束日期(可选)":"End date (optional)","无(里程碑)":"None (milestone)","(里程碑)":"(milestone)",点击空白处排期:"Click an empty spot to schedule","未排期 · 排到今天":"Unscheduled · Schedule for today",数字:"Number",单选:"Select",多选:"Multi-select",复选框:"Checkbox",日期:"Date",关联:"Relation"};var Iu={"Logo 底色":"Logo background","浅底 Logo":"Light logo","深底 Logo":"Dark logo","Logo 配色":"Logo colors","彩色(默认)":"Color (default)","蓝色单色":"Monochrome blue","应用内标识与浏览器图标即时切换,选择保存在当前设备。安装图标使用默认彩色版。":"App logos and the browser icon update instantly. Your choice is saved on this device. Installed icons use the default color version.",浅色:"Light",始终使用明亮界面:"Always use the light interface",深色:"Dark",始终使用暗色界面:"Always use the dark interface",随操作系统外观自动切换:"Follow the operating system appearance","重命名失败:{msg}":"Rename failed: {msg}",此设备:"This device",重命名本机:"Rename this device",工作区:"Workspace",颜色主题:"Color theme",字数统计:"Word count","在文档右下角显示字数,悬停查看字符数与预计阅读时间。":"Show the word count in the bottom-right corner of a document; hover for characters and estimated reading time.",入口验证成功并已保存:"Entry point verified and saved",已清除设备托管入口:"Device hosting entry point cleared","已连接 Edge;{notes}":"Connected to Edge; {notes}","已连接 Edge":"Connected to Edge","断开 Edge?":"Disconnect Edge?","只移除本机连接,不会删除 Cloudflare Worker 或 D1。存在活动 Room 时会拒绝断开。":"Only removes this device's connection; the Cloudflare Worker and D1 are kept. Disconnecting is refused while Rooms are active.",断开:"Disconnect","已断开 Edge":"Disconnected from Edge",不可达:"Unreachable",需升级:"Upgrade needed",设备托管入口:"Device hosting entry point",公网入口地址:"Public entry URL","已验证 · {scope}":"Verified · {scope}","公网 HTTPS":"Public HTTPS",局域网:"LAN",仅本机:"Local only","填写已由反向代理、隧道或公网 IP 转发到本节点的地址;保存时会访问 /health 并核对节点身份。":"Enter the address a reverse proxy, tunnel or public IP forwards to this node; saving fetches /health and checks the node identity.","验证中…":"Verifying…",验证并保存:"Verify and save","Desktop 内置 sidecar 只监听本机且关闭鉴权,不能直接暴露到公网。需要设备托管时请另行启动带鉴权的":"The desktop's built-in sidecar listens on localhost only with authentication off and cannot be exposed to the internet. For device hosting, run an authenticated",",或使用下方 Edge。":" separately, or use Edge below.","Edge 始终在线托管":"Edge always-on hosting","此设备把数据存放在云端存储桶、不常驻在线,站点需由 Edge 托管。你的设备离线期间,Edge 继续提供最后一次同步的版本。":"This device keeps its data in a cloud bucket and is not always online, so sites must be hosted by Edge. While your device is offline, Edge keeps serving the last synced version.","Edge Room 不依赖设备在线。可一键部署到你的 Cloudflare 账户,或连接已有兼容端点。":"Edge Rooms do not depend on your device being online. Deploy to your Cloudflare account in one click, or connect an existing compatible endpoint.",端点:"Endpoint","升级部署…":"Upgrade deployment…","{status} · 版本 {version} / {expected} · 活动 Room {rooms} · {note}":"{status} · version {version} / {expected} · active Rooms {rooms} · {note}",未知:"unknown","暂无 Room":"No Rooms yet","Room 同步存在异常":"Room sync has errors","Room 最近同步 {ago}":"Rooms last synced {ago}",等待首次同步:"Waiting for the first sync","部署到 Cloudflare":"Deploy to Cloudflare","在你自己的账户创建 Worker + D1(可顺带创建 R2 同步桶),断开时不会自动删除。":"Creates a Worker + D1 in your own account (optionally an R2 sync bucket too); nothing is deleted automatically when you disconnect.","一键部署…":"Deploy…","连接已有 Edge":"Connect an existing Edge","任意兼容 /v1/inbox 协议的端点。":"Any endpoint compatible with the /v1/inbox protocol.","断开 Edge":"Disconnect Edge","只移除本机连接,不会删除 Cloudflare Worker 或 D1;存在活动 Room 时会拒绝断开。":"Only removes this device's connection; the Cloudflare Worker and D1 are kept. Disconnecting is refused while Rooms are active.","已开始在此浏览器保存完整副本,正在下载数据…":"Started keeping a full replica in this browser; downloading data…","停止使用此同步存储桶?":"Stop using this sync bucket?",切回在线模式:"Switch back to online mode","此页面没有在线主节点可回退。停止后会返回「连接同步存储桶」;已下载的数据仍保留在此浏览器里,重新连接后可从断点继续。若要同时删除本地数据,请使用下方「删除此浏览器的副本」。":"This page has no online primary node to fall back to. Stopping returns you to “Connect a sync bucket”; downloaded data stays in this browser and resumes where it left off when you reconnect. To also delete the local data, use “Delete this browser's replica” below.","此浏览器将恢复纯在线模式。已下载的本地数据保留在此浏览器里,重新启用后从断点续传。":"This browser returns to online-only mode. Downloaded local data stays in this browser and resumes where it left off when re-enabled.",停止使用:"Stop using","已停止,请重新连接同步存储桶":"Stopped; reconnect a sync bucket",已切回在线模式:"Switched back to online mode",删除此浏览器的副本:"Delete this browser's replica","将删除此浏览器的副本并返回「连接同步存储桶」。\n① 已同步到存储桶的内容不会丢;\n② 尚未同步的本地编辑会丢失;\n③ 尚未上传的本地附件会丢失;\n④ 建议先确认上方显示“当前版本已确认”。":`Deletes this browser's replica and returns to “Connect a sync bucket”.
538
538
  1. Content already synced to the bucket is safe;
539
539
  2. Local edits not yet synced will be lost;
540
540
  3. Local attachments not yet uploaded will be lost;
@@ -542,44 +542,44 @@ if(L instanceof ArrayBuffer)L=new Uint8Array(L);else if(L instanceof Function)re
542
542
  1. Synced content stays on the workspace primary node;
543
543
  2. Local edits not yet synced will be lost;
544
544
  3. Local attachments not yet uploaded will be lost;
545
- 4. Run “Sync now” first.`,删除并重置:"Delete and reset","已删除此浏览器的副本,请重新连接同步存储桶":"This browser's replica was deleted; reconnect a sync bucket",已删除此浏览器的副本:"This browser's replica was deleted","重置失败:{msg}":"Reset failed: {msg}","开启后断网也能读写全部内容,改动自动同步。":"Read and write everything even without a network; changes sync automatically.","副本异常(已自动回退在线模式):{msg}":"Replica error (fell back to online mode): {msg}","正在下载数据… 已接收 {n} 条变更":({n:e})=>`Downloading data… ${e} ${Te(e,"change","changes")} received`,"离线可用 · 上次同步 {when}(推送 {pushed} / 拉取 {pulled})":"Available offline · last synced {when} (pushed {pushed} / pulled {pulled})","上次同步失败({when}):{msg} — 本地读写不受影响,恢复网络后自动重试":"Last sync failed ({when}): {msg} — local reads and writes are unaffected; retries automatically once the network is back","等待首次同步…":"Waiting for the first sync…","此浏览器暂不支持保存完整副本:{reason}":"This browser cannot keep a full replica: {reason}"," · 节点 {node}":" · node {node}"," · 本地占用 {mb} MB":" · {mb} MB used locally",离线副本:"Offline replica",在此浏览器保存完整副本:"Keep a full replica in this browser",立即同步:"Sync now","把本机改动推送出去,并拉取其他设备的最新内容。":"Push local changes and pull the latest from other devices.","删除此浏览器里的全部本地数据并切回在线模式;未同步的编辑和未上传的附件会丢失。":"Deletes all local data in this browser and switches back to online mode; unsynced edits and unuploaded attachments will be lost.",删除副本:"Delete replica",清理腾空间:"Free up space","将释放约 {bytes}。只清本机缓存,文件已存在云端,用到时自动取回。待上传的内容不会动。":"About {bytes} will be freed. Only the local cache is cleared; the files are in the cloud and are fetched again when needed. Pending uploads are untouched.","已腾出 {bytes}({n} 项)":({bytes:e,n:t})=>`Freed ${e} (${t} ${Te(t,"item","items")})`,"本地数据已受保护,系统不会自动清理":"Local data is protected; the system will not clear it automatically",浏览器暂未授予保护:"The browser did not grant protection",本机缓存:"Local cache","只存在这台设备上;清理不影响其他设备,文件用到时自动取回。":"Exists only on this device; clearing does not affect other devices, and files are fetched again when needed.","{n} 项(约 {bytes})还没上传,仅存在这台设备上。建议先「立即同步」再清理——清理不会动这些待上传的内容。":({n:e,bytes:t})=>`${e} ${Te(e,"item","items")} (about ${t}) not uploaded yet and only on this device. Run “Sync now” before clearing — clearing never touches pending uploads.`,无需清理:"Nothing to clear",防止浏览器自动清理:"Prevent the browser from clearing automatically","已开启:系统空间紧张时不会自动清掉本地数据。":"On: local data will not be cleared automatically when the system runs low on space.","浏览器未授予保护;系统空间紧张时可能清理本地数据。可稍后重试,或保持定期同步。":"The browser did not grant protection; local data may be cleared when the system runs low on space. Retry later, or keep syncing regularly.","开启后,系统空间紧张时也不会自动清掉本地数据。浏览器授予与否由其自行决定。":"When on, local data is not cleared automatically even when the system runs low on space. Whether the browser grants this is up to the browser.",请求保留本地数据:"Request to keep local data","此浏览器为本工作区共占用约 {usage}(含本地数据库与缓存)。缓存超过 {quota} 时自动清理最久没用、已有备份的,你固定的不动。":"This browser uses about {usage} for this workspace (local database plus cache). When the cache exceeds {quota}, the least recently used items that already have a backup are cleared automatically; pinned items are kept.","无法获取最新版本(网络不可用或 GitHub API 受限)":"Could not fetch the latest version (network unavailable or GitHub API rate-limited)",已是最新版本:"Already up to date","已下载 v{v}":"Downloaded v{v}","从 GitHub Releases 获取核心更新":"Fetch core updates from GitHub Releases",检查更新:"Check for updates","正在检查…":"Checking…","下载中 · {pct}%":"Downloading · {pct}%","下载中…":"Downloading…",下载:"Download",新版本:"New version",可用:"available","下载并更新到 v{v}":"Download and update to v{v}","已就绪,重启后生效":"is ready; restart to apply","重启应用以更新到 v{v}":"Restart the app to update to v{v}",重启:"Restart",检查失败:"Check failed",更新:"Updates",软件更新:"Software update",资源:"Resources","GitHub 仓库":"GitHub repository",源代码与问题反馈:"Source code and issue tracker",更新日志:"Changelog",各版本的发布说明:"Release notes for each version","快捷键已设为 {keys}":"Shortcut set to {keys}","设置失败:{msg}":"Could not save: {msg}",唤起快捷键:"Summon shortcut","点击右侧按钮,然后按下你想用的组合键。":"Click the button on the right, then press the key combination you want.",重置默认:"Reset to default","按下组合键…":"Press a key combination…",默认始终置顶:"Always on top by default","用全局快捷键随时唤起小窗:记录想法,或瞄一眼任务看板。小窗也可从菜单栏图标打开。":"Summon a small window anytime with a global shortcut: jot down an idea, or glance at the task board. The windows can also be opened from the menu bar icon.","小窗浮在其他窗口之上;也可在小窗内用 \uD83D\uDCCC 按钮切换。":"The window floats above other windows; you can also toggle it with the \uD83D\uDCCC button inside the window.",快速看板:"Quick Board","看板小窗浮在其他窗口之上;AI 通过 CLI 更新任务时看板实时刷新。":"The board window floats above other windows; it refreshes live when an AI updates tasks through the CLI.",管理本机缓存:"Manage local cache","已下载到这台设备的图片和大文件。清理只删本机副本,需要时从云端重新取回;桶里的原件始终不动。":"Images and large files downloaded to this device. Clearing only removes the local copy and fetches it again from the cloud when needed; the originals in the bucket are never touched.",管理附件存储:"Manage attachment storage","工作区里的全部图片和大文件,所有设备共用。可清理项已有长期备份、随时能腾空间(用时自动取回);没被任何文档或站点引用的孤儿可彻底删除。":"All images and large files in the workspace, shared by every device. Clearable items already have a long-term backup and can free space anytime (fetched again when used); orphans referenced by no document or site can be deleted permanently.",其他:"Other",待上传:"Pending upload",已固定:"Pinned",孤儿:"Orphan",可清理:"Clearable",保留:"Retained",大小:"Size",类型:"Type",最近使用:"Last used",全部类型:"All types",全部状态:"All statuses",保留中:"Retained","已清理 {n} 项 · 腾出 {bytes}":({n:e,bytes:t})=>`Cleared ${e} ${Te(e,"item","items")} · freed ${t}`,没有可清理的项:"Nothing to clear","删除孤儿 blob":"Delete orphan blobs","将从这台设备移除 {n} 个未被任何文档/站点引用的 blob,约 {bytes}。桶里的原件不动,需要时仍可重新下载。":({n:e,bytes:t})=>`Removes ${e} ${Te(e,"blob","blobs")} referenced by no document or site from this device, about ${t}. The originals in the bucket are kept and can be downloaded again when needed.`,"将永久删除 {n} 个未被任何文档/站点引用的 blob,约 {bytes}。此操作不可恢复。":({n:e,bytes:t})=>`Permanently deletes ${e} ${Te(e,"blob","blobs")} referenced by no document or site, about ${t}. This cannot be undone.`,"已删除 {n} 项 · 腾出 {bytes}":({n:e,bytes:t})=>`Deleted ${e} ${Te(e,"item","items")} · freed ${t}`,没有可删除的孤儿:"No orphans to delete",排序依据:"Sort by",按类型:"By type",按状态:"By status","已选 {n} 项 · {bytes}":({n:e,bytes:t})=>`${e} ${Te(e,"item","items")} selected · ${t}`,"共 {n} 项 · {bytes}":({n:e,bytes:t})=>`${e} ${Te(e,"item","items")} · ${t}`,"清理所选({n})":"Clear selected ({n})",清理所选:"Clear selected","删除孤儿({n})":"Delete orphans ({n})",删除孤儿:"Delete orphans","搜索 hash 或类型…":"Search hash or type…","无法读取:{err}":"Could not read: {err}",没有符合条件的项:"No matching items","这台设备还没有缓存的 blob":"No cached blobs on this device yet",取消固定:"Unpin","固定(不被自动清理)":"Pin (never cleared automatically)",可释放:"Freeable",都备份好了:"All backed up",暂时无需清理:"Nothing to clear for now",未设置长期备份:"No long-term backup set",指定后才能清理:"Set one to enable clearing","检查中…":"Checking…",未检查:"Not checked",检查后才知道:"Check to find out",原件都在这里:"All originals are here",还没有笔记:"No notes yet",删除当前笔记:"Delete current note",笔记列表:"Note list",取消置顶:"Unpin from top",始终置顶:"Always on top","{error}(点击关闭)":"{error} (click to dismiss)","此浏览器不支持 Web Worker。":"This browser does not support Web Workers.","需要 HTTPS(安全上下文)。当前是 http:// 访问,浏览器不开放离线所需的 OPFS 与 Service Worker——给服务器配置 TLS(--tls-cert/--tls-key,或 Caddy / Tailscale Serve 反代;iPhone 需要受信任的证书),或在本机用 localhost 访问。":"HTTPS (a secure context) is required. This page is served over http://, so the browser withholds the OPFS and Service Worker features offline mode needs. Configure TLS on the server (--tls-cert/--tls-key, or a Caddy / Tailscale Serve reverse proxy; iPhone needs a trusted certificate), or open it locally via localhost.","此浏览器不支持 OPFS 本地存储(需要 Safari 17+ / Chrome / Firefox 较新版本)。":"This browser does not support OPFS local storage (requires Safari 17+ or a recent Chrome / Firefox).","阿里云 OSS":"Alibaba Cloud OSS",上海:"Shanghai",北京:"Beijing",广州:"Guangzhou",成都:"Chengdu",南京:"Nanjing",香港:"Hong Kong",新加坡:"Singapore",东京:"Tokyo",杭州:"Hangzhou",深圳:"Shenzhen",美国东部:"US East","美国东部 2":"US East 2",美国西部:"US West","美国西部 2":"US West 2",爱尔兰:"Ireland",法兰克福:"Frankfurt",切换数据库:"Switch database",还没有数据库:"No databases yet",搜索数据库:"Search databases","实时同步中——AI 通过 CLI 的修改会即时出现":"Live — changes an AI makes through the CLI appear instantly",还没有看板:"No board yet","在主窗口创建一个带「单选」属性的数据库,任务进度就会出现在这里。":"Create a database with a “Select” property in the main window and task progress will show up here.",编辑器尚未就绪:"The editor is not ready yet",缺少文件路径:"Missing file path",文件编辑窗口仅在桌面应用内可用:"The file editor window is only available in the desktop app","已导入到 MetaHub":"Imported into MetaHub",预览模式:"Preview",源码模式:"Source","在 MetaHub 中打开":"Open in MetaHub","已导入 ✓":"Imported ✓","导入中…":"Importing…","导入到 MetaHub":"Import into MetaHub",本地副本启动超时:"Timed out starting the local replica",本地副本启动失败:"Failed to start the local replica","此页面没有工作区主节点,不能使用服务器配对;请重新连接同步存储桶。":"This page has no workspace primary node, so server pairing is unavailable; reconnect a sync bucket.","无法获取配对码: {status}":"Could not get a pairing code: {status}","此设备通过同步存储桶交换数据,不支持设备托管发布;请在在线主节点操作":"This device exchanges data through a sync bucket and does not support device-hosted publishing; do this on the online primary node",此设备没有可配置的托管入口:"This device has no configurable hosting entry point",本机:"This device",这台设备上的副本:"The replica on this device",工作区主节点:"Workspace primary node",当前连接的工作区:"The workspace you are connected to",本机工作区:"Local workspace",这台电脑上的工作区:"The workspace on this computer",危险操作:"Danger zone"};var Au={"加载失败:{msg}":"Failed to load: {msg}",连接存储桶:"Connect a bucket",所有设备通过它同步:"Every device syncs through it",两台服务器互相实时同步:"Two servers sync each other in real time",已触发同步:"Sync started","同步失败:{msg}":"Sync failed: {msg}","停止使用 {name}":"Stop using {name}","将停止与它同步。桶内数据不受影响,可以随时重新连接。":"Syncing with it will stop. Data in the bucket is untouched, and you can reconnect at any time.",停止使用:"Stop using",停止此浏览器离线同步:"Stop offline sync in this browser","此浏览器将不再直连 {name}。存储桶仍在服务器上;此浏览器在线时照常经服务器同步。":"This browser will no longer connect to {name} directly. The bucket stays on the server, and this browser keeps syncing through the server while online.",停止:"Stop","停止直连 {name}":"Stop direct sync with {name}","将停止与它的直连同步。它上面已同步的数据仍在,无法远程删除。":"Direct sync with it will stop. Data already synced to it stays there and cannot be deleted remotely.",停止直连:"Stop direct sync","实时 · 数据在这里产生":"Live · data is created here",直连:"Direct",已暂停:"Paused","重试中…":"Retrying…",重试:"Retry",地址:"Address","节点 ID":"Node ID",上次成功同步:"Last successful sync",尚未确认:"Unconfirmed","{n} 条改动":({n:e})=>`${e} ${Te(e,"change","changes")}`,立即同步:"Sync now",恢复同步:"Resume sync",暂停同步:"Pause sync",这台设备的名字与接入权限在:"This device's name and access are managed on the",设备:"Device","页管理。":"page.","同步失败 · {error}":"Sync failed · {error}","上次同步 {ago}":"Last synced {ago}",还没同步过:"Never synced",本机发布:"Published from this device",此浏览器可离线同步:"Offline sync available in this browser",这台设备:"This device","服务器,此浏览器也保存了一份":"Server, with a copy in this browser",服务器:"Server",服务商:"Provider",存储桶:"Bucket",加密:"Encryption","已加密,上传前在本地完成":"Encrypted locally before upload",未加密:"Not encrypted",凭据保存在:"Credentials stored on",用途:"Roles",上次同步:"Last sync",让此浏览器可离线同步:"Enable offline sync in this browser","更换存储密钥…":"Rotate storage key…","导出恢复码…":"Export recovery code…","让此浏览器可离线同步后,服务器连不上时它也能直接经存储桶同步。":"With offline sync enabled, this browser can sync straight through the bucket whenever the server is unreachable.","更换密钥…":"Rotate key…","先在「离线与缓存」把这台设备设为在本机保存,再连接存储桶。":"First set this device to keep data locally under “Offline & cache”, then connect a bucket.",前往设置:"Open settings",添加设备:"Add device",添加同步目标:"Add sync target",同步目标:"Sync targets","这台设备的云端后端,其他设备通过它加入并同步。":"This device's cloud backend; other devices join and sync through it.","数据保存在这些地方;上传到云端前已在本地加密。":"Your data lives in these places, encrypted locally before it goes to the cloud.","用 Cloudflare 开始":"Start with Cloudflare","登录后创建 R2 存储桶并部署 Edge,向导会带你在控制台生成访问密钥。":"Sign in to create an R2 bucket and deploy Edge; the wizard walks you through generating access keys in the console.","连接 Cloudflare":"Connect Cloudflare",还没有其他同步目标:"No other sync targets yet","连接一个存储桶,所有设备通过它交换加密后的工作区数据。":"Connect a bucket so every device can exchange encrypted workspace data through it.","还没连接存储桶。直连只在两边都在线时同步;存储桶能让离线的设备稍后补齐。":"No bucket connected yet. Direct sync only works while both sides are online; a bucket lets offline devices catch up later.",它是怎么工作的:"How it works","存储桶只做中转:每台设备把改动加密后上传,再拉取别人的——不必同时在线,也不需要公网 IP。直连则是两台服务器互相推送,实时但要求两边同时在线。":"A bucket is just a relay: each device encrypts its changes, uploads them and pulls everyone else's, with no need to be online at the same time or have a public IP. Direct sync pushes between two servers in real time, but both must be online.","这台设备把改动发布到桶,其他设备从桶拉取;新设备扫码加入即可。":"This device publishes changes to the bucket and other devices pull from it; a new device joins by scanning the QR code.","这台设备把整个工作区发布到桶,新设备扫码加入后从桶恢复。":"This device publishes the whole workspace to the bucket; a new device scans the QR code and restores from it.","密钥只保存在服务器;信任的设备重输一次密钥即可直连桶,离线、在外也不中断。":"The key stays on the server only; a trusted device re-enters it once to sync straight through the bucket, even offline or away.","清理腾出 {bytes}":"Clean up to free {bytes}","只删除别处已确认备份的副本,文件不会丢,用到时自动取回。":"Only copies confirmed backed up elsewhere are removed. Nothing is lost; files are fetched again when needed.",清理:"Clean up","已腾出 {bytes}({n} 项)":({bytes:e,n:t})=>`Freed ${e} (${t} ${Te(t,"item","items")})`,暂时没有可清理的:"Nothing to clean up right now","附件原件保存在「{place}」,所有设备共用。":"Original attachments are stored on “{place}”, shared by every device.","开启的位置会保留所有附件的完整副本。只要确认这里有备份,其他设备就可以放心清理本地缓存。":"Places switched on keep a full copy of every attachment. Once a backup is confirmed here, other devices can safely clear their local cache.",附件:"Attachments",长期保留副本:"Long-term copies","这里保留全部附件原件,无需清理":"All original attachments are kept here; nothing to clean up",还没指定长期保留的位置:"No long-term location chosen yet",核对备份后才能清理:"Verify backups before cleaning up","都已备份,暂时没有可清理的":"Everything is backed up; nothing to clean up right now","核对中…":"Verifying…","上次核对 {ago}":"Last verified {ago}",还没核对过:"Not verified yet","查看附件…":"View attachments…",云端存储桶:"Cloud bucket",未命名设备:"Unnamed device","还没有长期保留的位置。先指定一处,其他设备才能放心清理本地缓存。":"No long-term location yet. Pick one first so other devices can safely clear their local cache.",清理前需要几处确认:"Confirmations required before cleanup","设备清理缓存前,要有几处长期副本确认持有该附件。":"How many long-term copies must confirm they hold an attachment before a device clears it from its cache.",一处即可:"Any one place",任一长期副本确认即可清理:"Any single long-term copy is enough",每处都要:"Every place",所有长期副本都确认后才清理:"Clean up only after every long-term copy confirms","部分位置连不上,相关文件暂不清理":"Some places are unreachable; their files are kept for now",重新核对:"Verify again","占用超过 {bytes} 时,自动清理最久没用、已有备份的;你固定的不动。":"Above {bytes}, the least recently used files that are backed up are cleaned automatically; pinned files stay.",命令行:"Command line",桌面应用:"Desktop app",浏览器:"Browser",网页:"Web","设备来源刷新失败:{msg}":"Failed to refresh device sources: {msg}","撤销 {name} 的接入":"Revoke access for {name}","将同时撤销它的 {n} 个授权码。它将无法再同步进这个工作区。已同步到它上面的数据仍在,无法远程删除。":({n:e})=>`Its ${e} enrollment codes will be revoked too. It can no longer sync into this workspace. Data already synced to it stays there and cannot be deleted remotely.`,"它将无法再同步进这个工作区。已同步到它上面的数据仍在,无法远程删除。":"It can no longer sync into this workspace. Data already synced to it stays there and cannot be deleted remotely.",撤销接入:"Revoke access",重命名这台设备:"Rename this device","给 {name} 起个名字":"Name {name}",所有设备都会看到这个名字:"Every device will see this name","例如:工作室 iMac":"e.g. Studio iMac","重命名失败:{msg}":"Rename failed: {msg}",工作区所在的服务器:"The server hosting this workspace","经存储桶 {name} 同步":"Syncs through bucket {name}",直连同步:"Direct sync",直连已暂停:"Direct sync paused",通过授权码接入:"Joined with an enrollment code",曾同步过:"Synced before",工作区所在的这台设备:"The device hosting this workspace","经存储桶 {name}":"Through bucket {name}","(在线,租约至 {until})":"(online, lease until {until})",授权码:"Enrollment code","曾写入过工作区,来源未确认":"Has written to the workspace; source unconfirmed",接入方式:"Connection",应用:"App",最近活动:"Last active",重命名:"Rename","同步状态、暂停与停止直连在":"Sync status, pausing and stopping direct sync live in",数据与备份:"Data & backup","。":".","撤销后它不能再同步进来;此前已同步到它上面的数据无法远程删除。":"Once revoked it can no longer sync in; data already synced to it cannot be deleted remotely.","这台设备和其他设备共用同一把存储密钥,无法单独移除。":"This device shares the storage key with the others, so it cannot be removed on its own. After you ",更换密钥:"rotate the key","后它将不能再同步;已下载到它上面的数据无法追回。":" it can no longer sync; data already downloaded to it cannot be recalled.","正在核对已连接的存储桶…":"Checking connected buckets…","只能确认它曾写入过工作区,无法确认它现在经哪条渠道接入,所以这里不提供断开操作。":"We can only confirm it once wrote to the workspace, not which channel it uses now, so there is no disconnect action here.","{n} 台设备同步过这个工作区。":({n:e})=>`${e} ${Te(e,"device has","devices have")} synced this workspace.`,"最近 30 天":"Last 30 days","还没有其他设备。":"No other devices yet.",很久没活动:"Inactive for a while","超过 30 天没有同步的设备。如果已经不再使用,可以在这里撤销它们的接入。":"Devices that have not synced for over 30 days. If they are no longer in use, revoke their access here.","数据只在这一处,还没有备份":"Data lives in one place only; no backup yet","已保存在 {n} 处 · {m} 个附件还只在这里":({n:e,m:t})=>`Saved in ${e} ${Te(e,"place","places")} · ${t} ${Te(t,"attachment is","attachments are")} still only here`,"已保存在 {n} 处 · 有改动尚未同步":({n:e})=>`Saved in ${e} ${Te(e,"place","places")} · unsynced changes`,"已保存在 {n} 处 · {m} 处同步失败":({n:e,m:t})=>`Saved in ${e} ${Te(e,"place","places")} · ${t} ${Te(t,"place","places")} failing to sync`,"已保存在 {n} 处 · 首次同步进行中":({n:e})=>`Saved in ${e} ${Te(e,"place","places")} · first sync in progress`,"已保存在 {n} 处 · 备份确认已过期":({n:e})=>`Saved in ${e} ${Te(e,"place","places")} · backup confirmation expired`,"已安全保存在 {n} 处 · 上次确认 {ago}":({n:e,ago:t})=>`Safely saved in ${e} ${Te(e,"place","places")} · last confirmed ${t}`,"已安全保存在 {n} 处":({n:e})=>`Safely saved in ${e} ${Te(e,"place","places")}`,尚未配置任何同步目标:"No sync target configured yet",同步失败:"Sync failed",尚未完成首次同步:"First sync not finished yet",有改动尚未同步:"Unsynced changes",备份确认已过期:"Backup confirmation expired",有附件仅在本机:"Some attachments exist only on this device","{place}:{issue}":"{place}: {issue}","{issue} — {detail}":"{issue} — {detail}",本机:"This device","实时(本机)":"Live (this device)",当前版本已确认:"Current version confirmed",确认已过期:"Confirmation expired",尚未同步:"Not synced yet",已停用:"Disabled",完整副本:"Full replica",工作区同步:"Workspace sync",附件长期保存:"Long-term attachments",发布快照:"Published snapshots",尚未确认当前版本:"Current version not confirmed yet",加密口令必填:"Encryption passphrase is required","加密口令不正确,请输入与其他设备相同的口令。":"Wrong encryption passphrase. Enter the same passphrase as on your other devices.","连接被浏览器拦截:请给存储桶配置 CORS,允许此源的 GET/PUT/HEAD/DELETE。":"The browser blocked the connection. Configure CORS on the bucket to allow GET/PUT/HEAD/DELETE from this origin.","连接失败:{msg}":"Connection failed: {msg}","endpoint、bucket、access key、secret key 必填":"Endpoint, bucket, access key and secret key are required",没有在图片中找到有效的接入二维码:"No valid enrollment QR code found in the image",连接你的存储桶:"Connect your bucket","扫描主设备上的二维码:在桌面端打开 设置 → 同步 → 手机接入。":"Scan the QR code on your primary device: open Settings → Sync → Mobile access on the desktop.",相机权限被拒绝:"Camera access denied","允许访问相机,或改用下方粘贴/手动方式。":"Allow camera access, or paste or fill in the details below instead.",重试授权:"Try again",这不是有效的接入二维码:"This is not a valid enrollment QR code",无效的接入链接或代码:"Invalid enrollment link or code",从图片识别:"Read from image",手动填写:"Enter manually","已读取桶信息,输入加密口令即可同步你的数据。":"Bucket details loaded. Enter the encryption passphrase to sync your data.","已读取桶信息,点击连接即可同步你的数据。":"Bucket details loaded. Click Connect to sync your data.",端到端加密:"End-to-end encrypted",加密口令:"Encryption passphrase",与其他设备相同的口令:"Same passphrase as your other devices","连接中…":"Connecting…",连接并同步:"Connect and sync",重新扫码:"Scan again",改为手动填写:"Enter manually instead","填入 S3 兼容存储桶(R2/COS/MinIO/S3)的连接信息;数据上传前端到端加密。":"Enter the connection details of an S3-compatible bucket (R2/COS/MinIO/S3). Data is end-to-end encrypted before upload.",路径前缀:"Path prefix",改为扫码:"Scan a QR code instead","提示:iPhone 请用 Safari 的「分享 → 添加到主屏」装成 App,离线与持久存储才生效。":"Tip: on iPhone, use Safari's Share → Add to Home Screen to install as an app; offline mode and persistent storage only work that way.","或粘贴接入链接 / 接入码…":"Or paste an enrollment link / code…",当前服务器:"Current server"};var Du={回滚待确认:"Rollback pending confirmation",撤销待确认:"Revoke pending confirmation",发布失败:"Publish failed","正在创建 Edge 渠道":"Creating Edge channel","已上线 · Edge 始终在线":"Live · Edge, always on","已上线 · 设备托管":"Live · device hosted","正在同步 · 设备托管":"Syncing · device hosted","已设公开 · 入口未验证":"Set public · entry point unverified",链接分享中:"Shared by link",链接已过期:"Link expired",私有预览:"Private preview",在线:"Online",同步中:"Syncing",入口未验证:"Entry point unverified",正在创建:"Creating",等待控制设备:"Waiting for controller device",失败:"Failed",已过期:"Expired",任何人:"Anyone",持链接者:"Anyone with the link",已复制:"Copied","{n} 个 api/ 下的文件会被站点数据 API 遮蔽(仍会上传,但无法访问)":({n:e})=>`${e} ${Te(e,"file","files")} under api/ will be shadowed by the site data API (uploaded, but unreachable)`,"已上传 {n} 个文件":({n:e})=>`Uploaded ${e} ${Te(e,"file","files")}`,"已上传 {ok}/{total} 个,{failed} 个失败":"Uploaded {ok}/{total}, {failed} failed",部分文件上传失败:"Some files failed to upload","{n} 个文件未能上传,可修正后重新拖入(成功的文件无需重传)。":({n:e})=>`${e} ${Te(e,"file","files")} could not be uploaded. Fix and drop them in again; successful files need no re-upload.`,关闭:"Close","上传中 {done}/{total}…":"Uploading {done}/{total}…","已关闭 SPA 模式":"SPA mode off","已开启 SPA 模式(无扩展名路径回落到 index.html)":"SPA mode on (extensionless paths fall back to index.html)",配置管理:"Configuration",复制私有预览地址:"Copy private preview URL","发布与分享…":"Publish & share…","关闭 SPA 模式":"Turn off SPA mode","开启 SPA 模式":"Turn on SPA mode","修改标题…":"Edit title…",修改标题:"Edit title",标题:"Title","重命名(slug)…":"Rename (slug)…",删除站点:"Delete site","删除站点?":"Delete site?","「{name}」及其 {n} 个文件将被删除。":({name:e,n:t})=>`“${e}” and its ${t} ${Te(t,"file","files")} will be deleted.`,删除:"Delete","加载失败:{msg}":"Failed to load: {msg}","拖入一个目录即可上传为站点(目录名 = 站点名)":"Drop a folder to upload it as a site (folder name = site name)","目录名「{name}」无法转成有效的站点名":"Folder name “{name}” cannot be turned into a valid site name",目录里没有可上传的文件:"The folder has no files to upload","创建站点「{name}」?":"Create site “{name}”?","站点「{name}」不存在。创建它并上传 {n} 个文件?":({name:e,n:t})=>`Site “${e}” does not exist. Create it and upload ${t} ${Te(t,"file","files")}?`,创建并上传:"Create and upload",站点管理:"Sites","发布静态站点,生成可分享的访问链接。":"Publish static sites and get shareable links.",新建站点:"New site",正在加载:"Loading",还没有站点:"No sites yet","站点是一组网页文件,可先在本机预览,发布后供他人访问。":"A site is a set of web files. Preview it locally, then publish it for others.",未命名站点:"Untitled site",点击复制公开地址:"Click to copy the public URL","存在多个公开地址;打开详情选择":"Several public URLs; open details to choose","私密链接不在卡片显示;打开详情管理":"Private links are not shown on the card; open details to manage",点击复制私有预览地址:"Click to copy the private preview URL","{n} 个公开地址":({n:e})=>`${e} public ${Te(e,"URL","URLs")}`,"{n} 个私密链接":({n:e})=>`${e} private ${Te(e,"link","links")}`,"私有预览 · {url}":"Private preview · {url}","{n} 文件":({n:e})=>`${e} ${Te(e,"file","files")}`,预览:"Preview","回滚仍未确认:{msg}":"Rollback still unconfirmed: {msg}",目标设备不可达:"target device unreachable",目标设备已确认恢复发布前状态:"Target device confirmed the pre-publish state is restored",重试回滚:"Retry rollback",管理:"Manage",发布:"Publish",更多:"More","共 {n} 个站点":({n:e})=>`${e} ${Te(e,"site","sites")}`,"{n} 个文件":({n:e})=>`${e} ${Te(e,"file","files")}`,请填写站点名称:"Enter a site name","已创建站点「{name}」":"Created site “{name}”","创建一组网页文件,随你的设备自动同步。":"Create a set of web files that sync with your devices.",取消:"Cancel",创建:"Create","名称(slug)":"Name (slug)","例如:docs、demo、status":"e.g. docs, demo, status","标题(可选)":"Title (optional)",人类可读的标题:"A human-readable title","将通过 /sites/<名称>/ 对外提供。":"Served at /sites/<name>/.","请输入有效的站点名(a-z、0-9、-)":"Enter a valid site name (a-z, 0-9, -)","已重命名为「{name}」":"Renamed to “{name}”","重命名(slug)":"Rename (slug)","slug 决定站点的访问地址 /sites/<slug>/。":"The slug sets the site address: /sites/<slug>/.","保存中…":"Saving…",重命名:"Rename","新名称(slug)":"New name (slug)","将保存为 /sites/{name}/":"Will be saved as /sites/{name}/",无法从输入得到有效的站点名:"No valid site name can be made from the input","注意:重命名后旧链接将失效 — /sites/{name}/ 不再可访问,已分发的地址需要更新。":"Note: old links break after renaming — /sites/{name}/ will no longer work, so distributed URLs must be updated.",站点不存在:"Site not found","「{name}」可能已被删除或重命名。":"“{name}” may have been deleted or renamed.",查看全部站点:"View all sites",站点还没有文件:"This site has no files yet","上传文件后,这里会直接显示站点页面。":"Once files are uploaded, the site page shows here.",去配置:"Configure",还没有文件:"No files yet",打开站点:"Open site",打开:"Open","删除文件?":"Delete file?","「{path}」将从站点「{name}」中删除。":"“{path}” will be removed from site “{name}”.","{n} 个文件 · 创建于 {date}":({n:e,date:t})=>`${e} ${Te(e,"file","files")} · created ${t}`,"已发布 · {n} 个渠道":({n:e})=>`Published · ${e} ${Te(e,"channel","channels")}`,私有:"Private",访问:"Access",仅你和已配对设备可打开:"Only you and paired devices can open it",复制地址:"Copy URL",访问站点:"Visit site",发布渠道:"Publish channels","还没有发布 — 目前只有你(和已配对设备)能打开上面的预览地址。":"Not published yet — only you (and paired devices) can open the preview URL above.","{host}托管":"{host} hosted",需要口令:"Password required","文件##tab":"Files",上传文件:"Upload files","上传整个目录(保留相对路径),也可以直接拖拽目录进来":"Upload a whole folder (relative paths kept); you can also drag a folder in",上传目录:"Upload folder","上传文件后即可通过站点地址访问。":"Once files are uploaded, the site is reachable at its URL.",文件大小:"File size",复制路径:"Copy path","(无法加载内容)":"(content could not be loaded)","二进制文件 · 在新标签打开查看":"Binary file · open in a new tab to view","Cloudflare 授权失败":"Cloudflare authorization failed","请先确认将创建或更新列出的 Cloudflare 资源":"Confirm first that the listed Cloudflare resources will be created or updated","请先用 Cloudflare 登录":"Sign in with Cloudflare first","请选择要部署到的 Cloudflare 账号":"Choose the Cloudflare account to deploy to","{n} 个站点重新接线失败:{sites}":({n:e,sites:t})=>`${e} ${Te(e,"site","sites")} failed to rewire: ${t}`,"、":", ",";":"; ","R2 桶创建失败:{msg}":"R2 bucket creation failed: {msg}","Edge 部署完成;{notes}":"Edge deployed; {notes}","Edge 部署完成":"Edge deployed","请填入 Access Key ID 与 Secret":"Enter the Access Key ID and Secret",请设置加密口令:"Set an encryption passphrase",同步桶已接入:"Sync bucket connected",接入同步桶:"Connect sync bucket","R2 桶 {name} 已创建。最后一步:Cloudflare 不允许应用代为创建 S3 凭据,请到控制台生成后粘贴到这里。":"R2 bucket {name} created. Last step: Cloudflare does not let apps create S3 credentials, so generate them in the dashboard and paste them here.",稍后再接:"Connect later","接入中…":"Connecting…","R2 → 管理 R2 API 令牌":"R2 → Manage R2 API Tokens",",创建一个「对象读和写」令牌(可只勾选 {bucket} 这个桶),把页面显示的 Access Key ID 与 Secret Access Key 粘贴到下面。":", create an “Object Read & Write” token (you can limit it to the {bucket} bucket), then paste the Access Key ID and Secret Access Key shown there below.","加密口令(新工作区在此设置;其他设备加入时需输入同一口令)":"Encryption passphrase (set here for a new workspace; other devices enter the same one to join)","口令保护数据机密性,请牢记;接入完成后建议在「设备与授权 → 导出恢复码」打印备份。":"The passphrase protects your data; remember it. After connecting, print a backup via “Devices → Export recovery code”.","升级 Edge":"Upgrade Edge","部署 Edge":"Deploy Edge","将在你自己的 Cloudflare 账户中创建或更新一个 Worker、一个 D1 数据库和 workers.dev 入口。凭据仅用于本次请求,不会保存。":"Creates or updates a Worker, a D1 database and a workers.dev entry point in your own Cloudflare account. Credentials are used for this request only and never stored.","部署中…":"Deploying…",确认并部署:"Confirm and deploy","Cloudflare 账号":"Cloudflare account","选择账号…":"Choose an account…","{name}({id})":"{name} ({id})","✅ 已登录:{name}":"✅ Signed in: {name}","等待浏览器授权…":"Waiting for browser authorization…","用 Cloudflare 登录":"Sign in with Cloudflare","将打开 Cloudflare 授权页,只申请 Workers 与 D1 的最小权限;令牌仅用于本次部署、不会保存。":"Opens the Cloudflare consent page requesting only the minimal Workers and D1 permissions; the token is used for this deployment only and never stored.","改用 API Token":"Use an API token instead","临时 API Token":"Temporary API token","需要 Workers Scripts Write 与 D1 Write。Cloudflare Token 是账户级凭据,请仅使用最小权限 Token。":"Needs Workers Scripts Write and D1 Write. A Cloudflare token is an account-level credential; use one with minimal permissions.","改用 Cloudflare 登录":"Sign in with Cloudflare instead","Worker 名称":"Worker name","D1 名称":"D1 name","workers.dev 子域(账户尚未设置时创建)":"workers.dev subdomain (created if the account has none)","子域属于整个 Cloudflare 账户;如果账户已有子域,将使用现有值并在完成结果中提示。":"The subdomain belongs to the whole Cloudflare account; if one already exists it is used and noted in the result.","同时创建 R2 同步桶(创建桶后仍需单独生成 S3 凭据)":"Also create an R2 sync bucket (S3 credentials must still be generated separately)","R2 桶名称":"R2 bucket name","创建后还差一步:到 Cloudflare 控制台生成 S3 凭据并粘贴(授权无法代办这一步),本向导会引导你完成。":"One more step after creation: generate S3 credentials in the Cloudflare dashboard and paste them (authorization cannot do this for you); this wizard walks you through it.","检测到未完成部署,当前步骤:{step}。使用相同名称可继续,不会自动删除已创建资源。":"An unfinished deployment was found at step {step}. Keep the same names to continue; created resources are not deleted automatically.","我确认创建或更新上述 Cloudflare 资源;断开 MetaHub 时不会自动删除它们。":"I confirm creating or updating the Cloudflare resources above; they are not deleted automatically when MetaHub disconnects.",密钥必填:"Secret is required",加密口令必填:"Encryption passphrase is required","服务器未提供该桶的完整配置,无法在本设备激活":"The server did not provide the full bucket configuration; cannot activate on this device","已让本机直连存储桶 · 离线、在外也能直接同步":"This device now syncs with the bucket directly · works offline and away","连接被浏览器拦截:请给存储桶配置 CORS,允许此源的 GET/PUT/HEAD/DELETE。":"The browser blocked the connection: configure CORS on the bucket to allow GET/PUT/HEAD/DELETE from this origin.","启用失败:{msg}":"Failed to enable: {msg}",在本设备启用直连:"Enable direct sync on this device","服务器已配置这个存储桶。为保护密钥,服务器不会把它同步到浏览器——再输入一次密钥,这台设备就能与桶直接同步(离线、在外也不中断)。":"The server already has this bucket configured. To protect the secret it is never sent to the browser — enter it once more and this device syncs with the bucket directly (offline and away too).","连接中…":"Connecting…",启用直连:"Enable direct sync",存储桶:"Bucket",服务地址:"Endpoint","访问密钥 ID":"Access key ID",密钥:"Secret",重新输入该桶的密钥:"Re-enter the bucket's secret",加密口令:"Encryption passphrase",与其它设备相同的加密口令:"The same passphrase as your other devices","跨设备共用的那把加密钥——用它解开桶里别人的数据。":"The encryption key shared across devices — it unlocks the data others put in the bucket.","壳地址(手机访问的静态站点域名;留空用当前地址)":"Shell URL (static site domain the phone opens; blank = current address)",复制链接:"Copy link",已复制链接:"Link copied","手机相机扫码打开,输入加密口令即可同步。":"Scan with the phone camera, enter the passphrase, and it syncs.",在另一台电脑的终端运行:"Run in a terminal on the other computer",复制命令:"Copy command",已复制命令:"Command copied",复制接入码:"Copy enrollment code",已复制接入码:"Enrollment code copied","对方运行后会提示输入加密口令。也可在":"It will prompt for the passphrase. Alternatively, in the","向导选「粘贴接入码加入存储」。":"wizard choose “Join storage with an enrollment code”.","{time} 后过期":"Expires in {time}","已过期,请重新生成":"Expired, generate a new one",复制配对码:"Copy pairing code",已复制配对码:"Pairing code copied","生成失败:{msg}":"Failed to generate: {msg}",地址和配对码必填:"Address and pairing code are required","已配对 {url}":"Paired with {url}","配对失败:{msg}":"Pairing failed: {msg}",邀请另一台服务器配对:"Invite another server to pair","生成中…":"Generating…",生成本机配对码:"Generate a pairing code","已有对方的配对码?":"Have the other side's pairing code?",对方服务器地址:"Other server's address",配对码:"Pairing code","对方「生成本机配对码」得到的码":"The code from “Generate a pairing code” on the other side","本机可达地址(可选)":"Reachable address of this server (optional)",留空则仅本机主动同步:"Blank = only this server initiates sync","配对中…":"Pairing…",配对:"Pair",直连另一台服务器:"Connect another server directly","两台服务器互相实时同步。一边生成配对码,另一边填入。":"Two servers sync with each other in real time. Generate a pairing code on one side and enter it on the other.",完成:"Done",在手机上打开本服务器:"Open this server on your phone","服务器地址(手机访问的域名;留空用当前地址)":"Server address (domain the phone opens; blank = current address)","⚠ 含访问令牌,请勿公开分享。":"⚠ Contains the access token; do not share publicly.",手机扫码:"Scan on phone","电脑 / 命令行":"Computer / CLI",手机打开服务器:"Open server on phone",找不到该存储的配置:"Configuration for this storage was not found",添加设备:"Add device","让另一台设备加入同一个工作区——手机扫码,或在电脑上粘贴接入码。":"Bring another device into this workspace — scan on a phone, or paste the enrollment code on a computer.","加载中…":"Loading…","⚠ 接入码含桶访问密钥,请勿公开分享;不含加密口令——新设备需另输口令。":"⚠ The enrollment code contains the bucket access key; do not share publicly. It does not contain the passphrase — the new device enters it separately.","https://<账户ID>.r2.cloudflarestorage.com":"https://<account-id>.r2.cloudflarestorage.com","R2 控制台 → 管理 R2 API 令牌,创建仅限目标桶的对象读写凭据;区域填 auto。价格与额度以 Cloudflare 控制台为准。":"R2 dashboard → Manage R2 API Tokens: create object read/write credentials limited to the target bucket; region is auto. Pricing and quotas as shown in the Cloudflare dashboard.","https://s3.<区域>.amazonaws.com":"https://s3.<region>.amazonaws.com","IAM 用户的访问密钥;区域如 us-east-1。":"An IAM user's access key; region such as us-east-1.","https://minio.你的域名":"https://minio.your-domain","自建 MinIO 的访问地址与 access / secret key。":"Your self-hosted MinIO endpoint and access / secret key.","腾讯云 COS":"Tencent Cloud COS","https://<桶名-APPID>.cos.<区域>.myqcloud.com":"https://<bucket-APPID>.cos.<region>.myqcloud.com","桶名须含 APPID,用虚拟主机风格地址(host 以桶名开头)。":"The bucket name must include the APPID; use a virtual-hosted-style endpoint (host starts with the bucket name).",自定义:"Custom","任何 S3 兼容存储桶。":"Any S3-compatible bucket.","服务地址、桶名称、访问密钥 ID、密钥都要填":"Endpoint, bucket name, access key ID and secret are all required","加密口令必填(或关闭加密)":"Encryption passphrase is required (or turn encryption off)","已连接存储桶 · 服务器开始同步到桶,这台设备也直接同步":"Bucket connected · the server syncs to it, and so does this device directly","已连接存储桶 · 服务器开始同步到桶":"Bucket connected · the server now syncs to it","已连接存储桶 · 这台设备开始同步到桶":"Bucket connected · this device now syncs to it","连接被浏览器拦截:请给存储桶配置 CORS,允许此源的 GET/PUT/HEAD/DELETE(R2 控制台一条规则即可)。":"The browser blocked the connection: configure CORS on the bucket to allow GET/PUT/HEAD/DELETE from this origin (one rule in the R2 dashboard is enough).","添加失败:{msg}":"Failed to add: {msg}",连接存储桶:"Connect a bucket","连接一个 S3 兼容存储桶,所有设备就能同步——不需要公网服务器。新桶自动初始化;已有桶用相同加密口令即可加入。":"Connect an S3-compatible bucket and all devices sync — no public server needed. A new bucket is initialized automatically; join an existing one with the same passphrase.",连接:"Connect","连接后,工作区主节点负责把整库同步到这个桶;这台设备和其他设备都从它同步。":"Once connected, the workspace primary node syncs the whole hub to this bucket; this and other devices sync from it.","连接后,这台设备(本机)把整库同步到这个桶;新设备扫码加入即可一起用。":"Once connected, this device syncs the whole hub to this bucket; new devices join by scanning.",存储服务商:"Storage provider",桶名称:"Bucket name","端到端加密(强烈建议;关闭后文件以明文存放,仅限完全信任的存储)":"End-to-end encryption (strongly recommended; off = files stored in plain text, only for fully trusted storage)","新桶以此创建;其它设备用同一口令加入":"Used to create a new bucket; other devices join with the same passphrase","这是跨设备共用的一把加密钥——记牢它,换设备 / 加入已有桶时都要用它解开数据。":"This is the encryption key shared across devices — remember it; you need it to unlock data on a new device or when joining an existing bucket.",进阶:"Advanced",区域:"Region","大多按服务商默认即可(R2 用 auto)。":"Usually the provider default (auto for R2).",路径前缀:"Path prefix","同一个桶里隔离多个工作区时用;默认 metahub。":"For keeping several workspaces apart in one bucket; default metahub.","新密钥需要同时填 Access Key ID 和 Secret。":"A new key needs both the Access Key ID and the Secret.","两次输入的新口令不一致。":"The two new passphrases do not match.","没有要更改的内容。":"Nothing to change.",轮换完成:"Rotation complete","✓ 存储密钥已更换 — 现在可以到服务商控制台停用旧密钥了。":"✓ Storage key rotated — you can now disable the old key in the provider console.","✓ 口令已更换 — 已配置设备无需重输,只有新加入的设备需要新口令。":"✓ Passphrase changed — configured devices need not re-enter it; only newly joining devices use the new one.","⚠️ 轮换后的首次同步失败:{msg}(凭据已保存,稍后可在同步页重试)":"⚠️ First sync after rotation failed: {msg} (credentials saved; retry later from the sync page)","其他设备用下面的新接入码重新接入(数据与同步进度不受影响)。丢失设备此前已同步的数据无法远程抹除;它只是无法再获取之后的数据。":"Other devices reconnect with the new enrollment code below (data and sync progress are unaffected). Data a lost device already synced cannot be wiped remotely; it just receives nothing further.",复制:"Copy",轮换存储密钥:"Rotate storage keys","适用于「手机丢了 / 密钥泄露 / 想换口令」。":"For a lost phone, a leaked key, or a passphrase change.","轮换中…":"Rotating…",开始轮换:"Start rotation","请先在存储服务商控制台新建一把 Access Key——先不要删除旧的,完成后再停用。 中途任何失败,旧钥匙都还能用;重试即可续接。":"In the storage provider console, create a new Access Key first — do not delete the old one yet; disable it once done. If anything fails midway the old key keeps working; retry to resume.","新 Access Key ID(留空 = 不更换密钥)":"New Access Key ID (blank = keep current key)","新 Secret Access Key":"New Secret Access Key","同时更换加密口令(不会重新加密历史数据;已配置设备无需重输)":"Also change the passphrase (past data is not re-encrypted; configured devices need not re-enter it)",新口令:"New passphrase",再输一次确认:"Confirm new passphrase",导出恢复码:"Export recovery code",打印:"Print","没有加密的存储桶,无需恢复码。":"No encrypted bucket; no recovery code needed.","Metahub 恢复码":"Metahub recovery code","存储桶 {bucket} · 生成于 {date}":"Bucket {bucket} · generated {date}","这串代码等于你全部数据的钥匙。忘记加密口令时,凭它可恢复数据并设置新口令。 请打印或抄写,放在安全的地方;不要保存在会被同步的笔记里。 任何拿到它的人都能读取你的全部数据。":"This code is the key to all your data. If you forget the passphrase, it restores your data and lets you set a new one. Print it or write it down and keep it somewhere safe; do not store it in a note that syncs. Anyone holding it can read all your data."};var Ou={"Edge 托管 · 设备离线仍可访问":"Edge hosted · reachable while offline",修改:"Update",全部:"All",关闭:"Close",分享:"Share","加载失败:{msg}":"Failed to load: {msg}",发布与分享:"Publish & share",同步失败:"Sync failed",复制:"Copy",复制链接:"Copy link",存储桶:"Bucket",已过期:"Expired",打开:"Open",撤销:"Revoke",更多:"More",本机:"This device",正在创建:"Creating",清理:"Clean up",清除筛选:"Clear filters",立即同步:"Sync now",设备:"Device",重试:"Retry",链接已复制:"Link copied",链接已过期:"Link expired","\uD83D\uDD12 有口令":"\uD83D\uDD12 Passcode","{n} 个分享":({n:e})=>`${e} ${Te(e,"share","shares")}`,"1 小时":"1 hour","24 小时":"24 hours","30 天":"30 days","7 天":"7 days","Edge 链接":"Edge link","Edge 托管 — 设备离线仍可访问":"Edge hosted — reachable while your devices are offline","Edge 托管 · 设备离线仍可访问(当前端点仅支持 inbox)":"Edge hosted · reachable while offline (this endpoint only supports inbox)","Edge 托管 · 设备离线仍可访问(公开网页暂不支持)":"Edge hosted · reachable while offline (not available for public pages yet)","Edge 托管 · 设备离线仍可访问(请先配置)":"Edge hosted · reachable while offline (set up Edge first)",按来源筛选:"Filter by source",本设备未记录已验证入口:"No verified entry recorded on this device",撤销链接:"Revoke link","撤销已请求,等待 Edge 确认销毁":"Revoke requested, waiting for Edge to confirm teardown","撤销已请求,等待控制设备上线完成清理":"Revoke requested, waiting for the controlling device to come online and clean up","撤销已请求,等待控制设备完成清理":"Revoke requested, waiting for the controlling device to clean up","撤销已提交,但 Edge 尚未确认销毁 Room;本地保留管理记录并会继续重试。":"Revoke submitted, but Edge has not confirmed the Room teardown yet; the local record is kept and retries continue.","撤销意图会同步到控制设备。若控制设备离线,Edge Room 会显示“等待控制设备”,上线后自动销毁。":"The revoke syncs to the controlling device. If it is offline, the Edge Room shows “waiting for controller” and is torn down once it comes online.","撤销意图会同步到托管设备;该设备收到后将停止提供这个渠道。":"The revoke syncs to the hosting device, which stops serving this channel once it receives it.","撤销这个分享?":"Revoke this share?","撤销这个链接?":"Revoke this link?",撤销中:"Revoking","处理中…":"Working…",创建并复制链接:"Create and copy link",创建失败:"Creation failed",创建私密链接:"Create private link","创建中…":"Creating…","此设备通过同步存储桶交换数据、不常驻在线;请改为 Edge 托管的链接":"This device exchanges data through the sync bucket and is not always online; use an Edge-hosted link instead","此设备通过同步存储桶交换数据、不常驻在线。请在在线主节点管理公开发布;这里仍可创建由 Edge 托管的私密分享链接。":"This device exchanges data through the sync bucket and is not always online. Manage public publishing on the online primary node; you can still create Edge-hosted private links here.","此设备通过同步存储桶交换数据、不常驻在线,无法直接托管站点。":"This device exchanges data through the sync bucket and is not always online, so it cannot host a site directly.","从过期链接重新创建 — 口令需重新设置(旧口令无法恢复)。":"Re-creating from an expired link — set the passcode again (the old one cannot be recovered).","存储桶 {name}":"Bucket {name}","存储桶分享是快照链接:内容是导出时的版本,之后不会随数据变化;「更新内容并续期」才会覆盖快照。":"A bucket share is a snapshot link: the content is the version at export time and does not follow later changes; “Update content and renew” overwrites the snapshot.","存储桶分享是一份快照;链接需续签后生成":"A bucket share is a snapshot; the link is generated on renewal",打开链接:"Open link",打开原表格:"Open source table",打开原对象:"Open source item",打开原文档:"Open source document",打开站点配置:"Open site settings","当前 Edge 端点仅支持数据收件(inbox),不能托管站点":"This Edge endpoint only supports the data inbox and cannot host sites","当前 Edge 端点仅支持数据收件(inbox),不能托管站点;重新部署官方 Edge Worker 即可启用。":"This Edge endpoint only supports the data inbox and cannot host sites; redeploy the official Edge Worker to enable it.","当前访问渠道({n})":"Current access channels ({n})","当前设备还没有配置公网或局域网入口,访客将无法访问。":"This device has no public or LAN entry configured yet, so visitors cannot reach it.",等待生成地址:"Waiting for an address","(等待首次同步)":"(waiting for first sync)",点击复制:"Click to copy",读:"Read",发布公开网页:"Publish public page","发布失败,目标设备的回滚尚未确认;在确认前它可能仍可公开访问。":"Publishing failed and the target device has not confirmed the rollback; it may still be publicly reachable until it does.",发布未返回访问地址:"Publishing returned no address","发布与分享:{title}":"Publish & share: {title}","发布中…":"Publishing…","分享:{title}":"Share: {title}",分享列表加载失败:"Failed to load shares","改用 Edge 托管":"Use Edge hosting instead","高级:数据授权(让页面读写数据)…":"Advanced: data grants (let the page read and write data)…","高级:允许修改已有行…":"Advanced: allow editing existing rows…",更改:"Change",更新快照并续期:"Update snapshot and renew","更新快照内容并续期?":"Update snapshot content and renew?",更新内容并续期:"Update content and renew",公开:"Public",公开地址已复制:"Public address copied",还没有分享出去的内容:"Nothing shared yet","还没有分享这个对象。":"This item has not been shared yet.","还没有连接 Edge。部署到你自己的 Cloudflare 后,站点始终在线,你的设备关机也能访问。":"Edge is not connected yet. Deploy to your own Cloudflare and the site stays online even when your devices are off.","还没有任何访问渠道 — 在下方创建。":"No access channels yet — create one below.","换个关键词,或清除当前的状态与来源筛选。":"Try another keyword, or clear the status and source filters.","记录将被删除。设备与 Edge 分享如需再次公开,可以重新分享。":"The records will be deleted. Device and Edge shares can be shared again later.","将用当前最新数据覆盖这份快照,接收者会看到更新后的版本;同时生成新的访问链接。":"The snapshot will be overwritten with the latest data, recipients will see the updated version, and a new access link is generated.",可编辑:"Editable","可编辑(仅服务器)":"Editable (server only)",可选:"Optional",口令:"Passcode",口令保护:"Passcode protected",快过期:"Expiring",快照链接:"Snapshot link",来源:"Source",了解此设备的同步方式:"How this device syncs","链接立即失效,接收者将无法再打开。":"The link stops working immediately and recipients can no longer open it.","链接无法被猜到;可加口令和有效期。":"The link cannot be guessed; add a passcode and expiry if you like.","链接已过期 — 过期链接无法访问,可重新创建":"Link expired — expired links cannot be opened; you can re-create it",链接已失效:"Link no longer valid","链接有效至 {when}":"Link valid until {when}","(没有可授权的数据库)":"(no databases to grant)","没有可托管站点的设备。":"No device can host the site.",没有匹配的分享:"No matching shares","内容不变,重新生成访问链接":"Content unchanged, generates a new access link","内容生成于 {when}":"Content generated {when}","内容同步于 {ago}":"Content synced {ago}","前往设置 → 站点与发布":"Go to Settings → Sites & publishing","清理 {n} 个已过期分享?":({n:e})=>`Clean up ${e} expired ${Te(e,"share","shares")}?`,清理全部已过期:"Clean up all expired","清理中…":"Cleaning up…","请先在“设置 → 站点与发布”连接或部署 Edge":"Connect or deploy Edge in “Settings → Sites & publishing” first","请先在“设置 → 站点与发布”配置当前设备的公网或局域网入口":"Configure this device's public or LAN entry in “Settings → Sites & publishing” first",渠道已撤销:"Channel revoked",全部来源:"All sources",权限:"Permission",确认公开发布:"Confirm public publish","确认公开发布到设备?":"Publish publicly on this device?","任何人将无法再通过公开地址访问这个站点;已有的分享链接不受影响。浏览器或 CDN 缓存可能仍保留数分钟。":"Nobody will be able to reach this site through the public address anymore; existing share links are unaffected. Browser or CDN caches may linger for a few minutes.",任何人可访问:"Anyone can access","任何人无需登录即可访问公开地址。":"Anyone can open the public address without signing in.","任何人无需登录即可通过这个地址访问。公开权限会同步,但只有选定的托管设备提供此渠道;改回私有后,浏览器或 CDN 缓存仍可能保留数分钟。数据授权:{n} 个数据库。设备必须保持在线。":({n:e})=>`Anyone can open this address without signing in. Public permissions sync, but only the selected hosting device serves this channel; after switching back to private, browser or CDN caches may linger for a few minutes. Data grants: ${e} ${Te(e,"database","databases")}. The device must stay online.`,"设备 {name}":"Device {name}",设备链接:"Device link",设备在线托管:"Hosted on a device","设备在线托管 — {device},需保持在线":"Hosted on a device — {device}, must stay online","设备在线托管(此设备无法托管)":"Hosted on a device (this device cannot host)",收起高级选项:"Hide advanced options",收起数据授权:"Hide data grants","数据授权:已开启 {n} 张表…":({n:e})=>`Data grants: ${e} ${Te(e,"table","tables")} enabled…`,"搜索标题 / 链接…":"Search titles / links…","所有对外公开的链接都在这里:谁能看、看到哪个版本、还能看多久。":"Every outbound link lives here: who can see it, which version, and for how long.",停止公开:"Stop public access",停止公开访问:"Stop public access","停止公开访问?":"Stop public access?","停止这个公开渠道?":"Stop this public channel?","(同步失败)":"(sync failed)","同步中…":"Syncing…","托管设备必须保持在线。渠道和撤销意图会随工作区同步,其他设备不会自动获得这个公开地址。":"The hosting device must stay online. Channels and revokes sync with the workspace; other devices do not automatically get this public address.",托管位置:"Hosting","无法读取现有公开权限:{msg}":"Could not read the current public permissions: {msg}","现有公开权限尚未加载。":"Current public permissions have not loaded.","现有公开权限尚未加载,请先点「重新加载权限」。":"Current public permissions have not loaded; click “Reload permissions” first.",新建分享:"New share",新增:"Create",新增访问方式:"Add access",续期:"Renew","续期(仅链接)":"Renew (link only)",延长有效期:"Extend expiry","页面内的数据接口({api})默认关闭。若这个站点需要访客读取或提交数据,在这里按表开启。":"The page's data API ({api}) is off by default. If this site needs visitors to read or submit data, enable it per table here.","已按过期链接预填上方表单。":"The form above was pre-filled from the expired link.","已按过期链接预填上方表单;原口令无法恢复,请重新设置。":"The form above was pre-filled from the expired link; the old passcode cannot be recovered, set a new one.",已撤销:"Revoked",已更新快照内容并复制新链接:"Snapshot updated and the new link copied","已配对的托管设备当前未确认可用。请先同步成功,或配置当前主节点的访问入口。":"No paired hosting device is confirmed available. Sync successfully first, or configure this primary node's entry.","已清理 {done} 个,{fail} 个失败:{err}":"Cleaned up {done}, {fail} failed: {err}","已清理 {n} 个分享":({n:e})=>`Cleaned up ${e} ${Te(e,"share","shares")}`,已提交撤销:"Revoke submitted","已提交停止公开,等待托管设备收到同步":"Stop request submitted, waiting for the hosting device to sync","(已停用)":"(disabled)",已停止公开访问:"Public access stopped","已通过「{source}」创建私密链接,地址已复制":"Private link created via “{source}”, address copied","已通过「{source}」上线,地址已复制":"Now live via “{source}”, address copied","已有分享({n})":"Existing shares ({n})","已重新生成访问链接并复制(内容不变)":"Access link regenerated and copied (content unchanged)","已重新生成访问链接并复制(内容为 {when} 的快照)":"Access link regenerated and copied (snapshot from {when})","已重新生成访问链接,新链接已复制(内容不变)":"Access link regenerated, new link copied (content unchanged)",永不过期:"Never expires",永久:"Permanent",用当前最新内容覆盖接收者看到的版本:"Overwrite what recipients see with the latest content",有效:"Active",有效期:"Expires","在文档、表格或站点里点「分享」即可创建链接。":"Click “Share” in a document, table or site to create a link.","站点页面与管理界面同源运行:站点内的脚本可以以你的身份读写整个工作区。只发布你信任的代码。":"Site pages run on the same origin as the admin UI: scripts inside the site can read and write the whole workspace as you. Only publish code you trust.","站点已上线,地址已复制":"Site is live, address copied",这类对象无法在这里重新分享:"This kind of item cannot be re-shared here",正在加载分享列表:"Loading shares","正在同步到目标设备;确认地址可访问后才会视为发布成功":"Syncing to the target device; publishing counts as done once the address is confirmed reachable",只读:"Read-only","至 {when}":"Until {when}",重试撤销:"Retry revoke",重新创建链接:"Re-create link",重新分享:"Share again",重新加载权限:"Reload permissions",准备中:"Preparing"};var Iu={...Su,...xu,...ku,...Tu,...Ru,...Au,...Du,...Ou};var Cu="mh-lang",Ps=(e)=>e==="zh-CN"||e==="en";function Ns(e){if(!e||e.length===0)return"zh-CN";for(let t of e){if(!t)continue;if(/^zh\b/i.test(t))return"zh-CN";if(/^en\b/i.test(t))return"en"}return"en"}var Wb=Cu;function Zb(){try{return typeof localStorage<"u"?localStorage:null}catch{return null}}function Gb(){let e=Zb()?.getItem(Wb);return Ps(e)?e:"system"}function Kb(){if(typeof navigator>"u")return"zh-CN";let e=navigator.languages?.length?navigator.languages:[navigator.language];return Ns(e)}function Vb(){if(typeof location>"u")return null;let e=new URLSearchParams(location.search).get("lang");return Ps(e)?e:null}var Xo=null,qs=null;function Jb(){if(typeof globalThis.Bun<"u")return"zh-CN";let e=Vb();if(e)return e;let t=Gb();return t==="system"?Kb():t}function Pu(){if(qs)return qs;if(!Xo)Xo=Jb();return Xo}function Nu(e){qs=e,Xo=null}function Xb(e,t){if(!t)return e;return e.replace(/\{(\w+)\}/g,(r,n)=>(n in t)?String(t[n]):r)}var Qb="##";function Yb(e,t,r){let n=e==="en"?Iu[t]:void 0;if(typeof n==="function")return n(r??{});let o=t.indexOf(Qb);return Xb(n??(o<0?t:t.slice(0,o)),r)}function kr(e,t){return Yb(Pu(),e,t)}ct();Vn();xi();Tn();Jn();var u_=(e)=>{let t=/^[a-z0-9+]+:\/\/([^/]+)/i.exec(e);return t?t[1]:e};function jE(e,t,r,n,o,s){let a=e.kind==="s3",c=a?n:r,p=Math.max(0,c-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??u_(e.url):u_(e.url)),freshness:!e.enabled?"disabled":e.lastStatus==="error"?"error":e.lastSuccessAt==null?"never":p>0?"behind":o-e.lastSuccessAt>s?"stale":"current",syncedAt:e.lastSuccessAt,error:e.lastStatus==="error"?e.lastError??null:null,acknowledgedSeq:e.pushCursor,highWaterSeq:c,lag:p,roles:m}}function uc(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)=>jE(a,e.blobFullNodes,e.globalHighWaterSeq,e.ownHighWaterSeq,n,o)).sort((a,c)=>Number(a.kind==="bucket")-Number(c.kind==="bucket")||r(a.freshness)-r(c.freshness)||a.label.localeCompare(c.label));return[t,...s]}function d_(e){let r=uc(e).filter((p)=>p.kind!=="self"&&p.freshness!=="disabled"),n=r.filter((p)=>p.syncedAt!=null&&p.acknowledgedSeq>=p.highWaterSeq),o=n.length?n.reduce((p,m)=>p==null||(m.syncedAt??0)<p?m.syncedAt:p,null):null,s=r.reduce((p,m)=>Math.max(p,m.lag),0),a=[];if(r.length===0)a.push({kind:"no_backup",placeUrl:null,placeLabel:null,message:null});for(let p of r)if(p.freshness==="error")a.push({kind:"peer_error",placeUrl:p.url,placeLabel:p.label,message:p.error});if(e.pendingBlobCount>0)a.push({kind:"pending_blobs",placeUrl:null,placeLabel:null,message:null});for(let p of r)if(p.freshness==="behind")a.push({kind:"behind",placeUrl:p.url,placeLabel:p.label,message:null});for(let p of r)if(p.freshness==="never")a.push({kind:"never_synced",placeUrl:p.url,placeLabel:p.label,message:null});for(let p of r)if(p.freshness==="stale")a.push({kind:"stale",placeUrl:p.url,placeLabel:p.label,message:null});let c={places:1+n.length,pendingBlobCount:e.pendingBlobCount,pendingBlobBytes:e.pendingBlobBytes,pendingChanges:s,oldestSyncedAt:o,issues:a};if(r.length===0)return{state:"no_backup",...c};if(r.some((p)=>p.freshness==="error"))return{state:"peer_error",...c};if(e.pendingBlobCount>0)return{state:"pending_blobs",...c};if(s>0)return{state:"unsynced_changes",...c};if(r.some((p)=>p.freshness==="never"))return{state:"syncing",...c};if(r.some((p)=>p.freshness==="stale"))return{state:"stale",...c};return{state:"healthy",...c}}Wt();Vn();Tn();function f_(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=Lt(e).filter((m)=>m.kind==="http"||m.kind==="s3").map((m)=>{let x=null,O;if(m.kind==="s3"&&m.config)try{let F=JSON.parse(m.config);x=F.bucket??null,O=F.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:O}}),c=yu(e),p={selfNodeId:t,selfLabel:fl(e),peers:a,pendingBlobCount:c.length,pendingBlobBytes:c.reduce((m,x)=>m+x.size,0),blobFullNodes:Kn(e).fullNodes,globalHighWaterSeq:r.global_seq??0,ownHighWaterSeq:r.own_seq??0,staleAfterMs:s};return{state:d_(p),places:uc(p)}}cc();Wt();Rn();wo();function p_(e,t){let r=We(e),n=br(e,t,"revoked");if(n.audience==="public"&&!Kt(e,n.site_id).some((o)=>o.audience==="public"&&o.desired_state==="active"))$i(e,n.site_id,{visibility:"private"});if(n.hosting==="device"&&n.target_ref===r)return It(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 It(e,{channelId:n.id,status:"cleanup_pending",lastError:"等待控制设备上线并应用撤销"}),{channel:n,needsReconcile:!1}}xn();Xe();xn();Fi();function b_(e){return e.replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'")}function GE(e){let t=hc(e),r=gc(e),n=(s)=>_c(e,s);async function o(s,a){let c=await s.text().catch(()=>"");throw Error(`S3 ${a} failed: ${s.status} ${c.slice(0,200)}`)}return{async list(s,a,c){let p=[],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(c)x.searchParams.set("delimiter",c);if(m)x.searchParams.set("continuation-token",m);let O=await t.fetch(x.toString(),{method:"GET"});if(!O.ok)await o(O,"list");let F=await O.text(),X=/<Contents>([\s\S]*?)<\/Contents>/g,he;while(he=X.exec(F)){let be=he[1],le=/<Key>([^<]+)<\/Key>/.exec(be)?.[1];if(!le)continue;p.push({key:b_(le),etag:/<ETag>([^<]*)<\/ETag>/.exec(be)?.[1]})}if(c){let be=/<CommonPrefixes>([\s\S]*?)<\/CommonPrefixes>/g;while(he=be.exec(F)){let le=/<Prefix>([^<]+)<\/Prefix>/.exec(he[1])?.[1];if(le)p.push({key:b_(le)})}}m=/<IsTruncated>true<\/IsTruncated>/.test(F)?/<NextContinuationToken>([^<]+)<\/NextContinuationToken>/.exec(F)?.[1]:void 0}while(m);return p},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,c){let p={};if(c?.contentType)p["content-type"]=c.contentType;if(c?.ifNoneMatch)p["if-none-match"]="*";if(c?.ifMatch)p["if-match"]=c.ifMatch;let m=await t.fetch(n(s),{method:"PUT",body:a,headers:Object.keys(p).length?p:void 0});if((c?.ifNoneMatch||c?.ifMatch)&&m.status===412)throw new Z("conflict",`S3 conditional put failed (${c?.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")}}}Xh(GE);var KE=Math.floor(167772160);function VE(e){if(e instanceof ArrayBuffer)return e;let t=new Uint8Array(e.byteLength);return t.set(e),t.buffer}async function JE(e){let t=await crypto.subtle.digest("SHA-256",VE(e));return[...new Uint8Array(t)].map((r)=>r.toString(16).padStart(2,"0")).join("")}async function mc(e,t){return(await JE(e)).slice(0,t.length)===t}var zi=null;function XE(){if(zi)return zi;return zi=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)}),zi}function Qr(e,t,r){return XE().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 yc(e){return Qr("spool","readonly",(t)=>t.get(e))}async function w_(){return(await Qr("spool","readonly",(t)=>t.getAll())??[]).filter((t)=>!t.durable)}async function v_(e){await Qr("spool","readwrite",(t)=>t.delete(e))}var E_=(e)=>`/blob/${e}`;async function QE(e,t,r){let n=await Qr("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 Qr("meta","readwrite",(s)=>s.put(o))}async function S_(e,t,r){await(await caches.open("mh-blob-v1")).put(E_(e),new Response(t,{headers:{"content-type":r,"cache-control":"public, max-age=31536000, immutable"}})),await QE(e,t.byteLength,r),await YE()}async function YE(){let e=await Qr("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<=KE)break;await r.delete(E_(o.hash)),await Qr("meta","readwrite",(s)=>s.delete(o.hash)),t-=o.size}}Ei();Fr();Sr();zr();yn();ct();yn();Sr();Xe();jn();var eS=1500;function bc(e){return Number(e.slice(0,15))}function In(e){return new Date(bc(e)).toISOString()}function Yr(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 wc(e){return Yr(e).kind}function Cn(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||bc(n.hlc)-bc(o.hlc)>eS))t.push(r),r=[];r.push(n)}if(r.length)t.push(r);return t}function Vt(e){return e!==null&&e!=="0"&&e!=="false"&&e!=="null"}function Ui(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 ji(e,t,r){return e.query(`SELECT ${mt} FROM crdt_changes WHERE dataset = ? AND row_id = ? ORDER BY hlc`).all(t,r)}function tS(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 x_(e,t){let r=wl(e,t);if(r)return r;let n=tS(e,t),o=n.map(()=>"?").join(","),s=n.length?` OR (dataset = 'doc_blocks' AND row_id IN (${o}))`:"",a=e.query(`SELECT ${mt} FROM crdt_changes
545
+ 4. Run “Sync now” first.`,删除并重置:"Delete and reset","已删除此浏览器的副本,请重新连接同步存储桶":"This browser's replica was deleted; reconnect a sync bucket",已删除此浏览器的副本:"This browser's replica was deleted","重置失败:{msg}":"Reset failed: {msg}","开启后断网也能读写全部内容,改动自动同步。":"Read and write everything even without a network; changes sync automatically.","副本异常(已自动回退在线模式):{msg}":"Replica error (fell back to online mode): {msg}","正在下载数据… 已接收 {n} 条变更":({n:e})=>`Downloading data… ${e} ${Te(e,"change","changes")} received`,"离线可用 · 上次同步 {when}(推送 {pushed} / 拉取 {pulled})":"Available offline · last synced {when} (pushed {pushed} / pulled {pulled})","上次同步失败({when}):{msg} — 本地读写不受影响,恢复网络后自动重试":"Last sync failed ({when}): {msg} — local reads and writes are unaffected; retries automatically once the network is back","等待首次同步…":"Waiting for the first sync…","此浏览器暂不支持保存完整副本:{reason}":"This browser cannot keep a full replica: {reason}"," · 节点 {node}":" · node {node}"," · 本地占用 {mb} MB":" · {mb} MB used locally",离线副本:"Offline replica",在此浏览器保存完整副本:"Keep a full replica in this browser",立即同步:"Sync now","把本机改动推送出去,并拉取其他设备的最新内容。":"Push local changes and pull the latest from other devices.","删除此浏览器里的全部本地数据并切回在线模式;未同步的编辑和未上传的附件会丢失。":"Deletes all local data in this browser and switches back to online mode; unsynced edits and unuploaded attachments will be lost.",删除副本:"Delete replica",清理腾空间:"Free up space","将释放约 {bytes}。只清本机缓存,文件已存在云端,用到时自动取回。待上传的内容不会动。":"About {bytes} will be freed. Only the local cache is cleared; the files are in the cloud and are fetched again when needed. Pending uploads are untouched.","已腾出 {bytes}({n} 项)":({bytes:e,n:t})=>`Freed ${e} (${t} ${Te(t,"item","items")})`,"本地数据已受保护,系统不会自动清理":"Local data is protected; the system will not clear it automatically",浏览器暂未授予保护:"The browser did not grant protection",本机缓存:"Local cache","只存在这台设备上;清理不影响其他设备,文件用到时自动取回。":"Exists only on this device; clearing does not affect other devices, and files are fetched again when needed.","{n} 项(约 {bytes})还没上传,仅存在这台设备上。建议先「立即同步」再清理——清理不会动这些待上传的内容。":({n:e,bytes:t})=>`${e} ${Te(e,"item","items")} (about ${t}) not uploaded yet and only on this device. Run “Sync now” before clearing — clearing never touches pending uploads.`,无需清理:"Nothing to clear",防止浏览器自动清理:"Prevent the browser from clearing automatically","已开启:系统空间紧张时不会自动清掉本地数据。":"On: local data will not be cleared automatically when the system runs low on space.","浏览器未授予保护;系统空间紧张时可能清理本地数据。可稍后重试,或保持定期同步。":"The browser did not grant protection; local data may be cleared when the system runs low on space. Retry later, or keep syncing regularly.","开启后,系统空间紧张时也不会自动清掉本地数据。浏览器授予与否由其自行决定。":"When on, local data is not cleared automatically even when the system runs low on space. Whether the browser grants this is up to the browser.",请求保留本地数据:"Request to keep local data","此浏览器为本工作区共占用约 {usage}(含本地数据库与缓存)。缓存超过 {quota} 时自动清理最久没用、已有备份的,你固定的不动。":"This browser uses about {usage} for this workspace (local database plus cache). When the cache exceeds {quota}, the least recently used items that already have a backup are cleared automatically; pinned items are kept.","无法获取最新版本(网络不可用或 GitHub API 受限)":"Could not fetch the latest version (network unavailable or GitHub API rate-limited)",已是最新版本:"Already up to date","已下载 v{v}":"Downloaded v{v}","从 GitHub Releases 获取核心更新":"Fetch core updates from GitHub Releases",检查更新:"Check for updates","正在检查…":"Checking…","下载中 · {pct}%":"Downloading · {pct}%","下载中…":"Downloading…",下载:"Download",新版本:"New version",可用:"available","下载并更新到 v{v}":"Download and update to v{v}","已就绪,重启后生效":"is ready; restart to apply","重启应用以更新到 v{v}":"Restart the app to update to v{v}",重启:"Restart",检查失败:"Check failed",更新:"Updates",软件更新:"Software update",资源:"Resources","GitHub 仓库":"GitHub repository",源代码与问题反馈:"Source code and issue tracker",更新日志:"Changelog",各版本的发布说明:"Release notes for each version","快捷键已设为 {keys}":"Shortcut set to {keys}","设置失败:{msg}":"Could not save: {msg}",唤起快捷键:"Summon shortcut","点击右侧按钮,然后按下你想用的组合键。":"Click the button on the right, then press the key combination you want.",重置默认:"Reset to default","按下组合键…":"Press a key combination…",默认始终置顶:"Always on top by default","用全局快捷键随时唤起小窗:记录想法,或瞄一眼任务看板。小窗也可从菜单栏图标打开。":"Summon a small window anytime with a global shortcut: jot down an idea, or glance at the task board. The windows can also be opened from the menu bar icon.","小窗浮在其他窗口之上;也可在小窗内用 \uD83D\uDCCC 按钮切换。":"The window floats above other windows; you can also toggle it with the \uD83D\uDCCC button inside the window.",快速看板:"Quick Board","看板小窗浮在其他窗口之上;AI 通过 CLI 更新任务时看板实时刷新。":"The board window floats above other windows; it refreshes live when an AI updates tasks through the CLI.",管理本机缓存:"Manage local cache","已下载到这台设备的图片和大文件。清理只删本机副本,需要时从云端重新取回;桶里的原件始终不动。":"Images and large files downloaded to this device. Clearing only removes the local copy and fetches it again from the cloud when needed; the originals in the bucket are never touched.",管理附件存储:"Manage attachment storage","工作区里的全部图片和大文件,所有设备共用。可清理项已有长期备份、随时能腾空间(用时自动取回);没被任何文档或站点引用的孤儿可彻底删除。":"All images and large files in the workspace, shared by every device. Clearable items already have a long-term backup and can free space anytime (fetched again when used); orphans referenced by no document or site can be deleted permanently.",其他:"Other",待上传:"Pending upload",已固定:"Pinned",孤儿:"Orphan",可清理:"Clearable",保留:"Retained",大小:"Size",类型:"Type",最近使用:"Last used",全部类型:"All types",全部状态:"All statuses",保留中:"Retained","已清理 {n} 项 · 腾出 {bytes}":({n:e,bytes:t})=>`Cleared ${e} ${Te(e,"item","items")} · freed ${t}`,没有可清理的项:"Nothing to clear","删除孤儿 blob":"Delete orphan blobs","将从这台设备移除 {n} 个未被任何文档/站点引用的 blob,约 {bytes}。桶里的原件不动,需要时仍可重新下载。":({n:e,bytes:t})=>`Removes ${e} ${Te(e,"blob","blobs")} referenced by no document or site from this device, about ${t}. The originals in the bucket are kept and can be downloaded again when needed.`,"将永久删除 {n} 个未被任何文档/站点引用的 blob,约 {bytes}。此操作不可恢复。":({n:e,bytes:t})=>`Permanently deletes ${e} ${Te(e,"blob","blobs")} referenced by no document or site, about ${t}. This cannot be undone.`,"已删除 {n} 项 · 腾出 {bytes}":({n:e,bytes:t})=>`Deleted ${e} ${Te(e,"item","items")} · freed ${t}`,没有可删除的孤儿:"No orphans to delete",排序依据:"Sort by",按类型:"By type",按状态:"By status","已选 {n} 项 · {bytes}":({n:e,bytes:t})=>`${e} ${Te(e,"item","items")} selected · ${t}`,"共 {n} 项 · {bytes}":({n:e,bytes:t})=>`${e} ${Te(e,"item","items")} · ${t}`,"清理所选({n})":"Clear selected ({n})",清理所选:"Clear selected","删除孤儿({n})":"Delete orphans ({n})",删除孤儿:"Delete orphans","搜索 hash 或类型…":"Search hash or type…","无法读取:{err}":"Could not read: {err}",没有符合条件的项:"No matching items","这台设备还没有缓存的 blob":"No cached blobs on this device yet",取消固定:"Unpin","固定(不被自动清理)":"Pin (never cleared automatically)",可释放:"Freeable",都备份好了:"All backed up",暂时无需清理:"Nothing to clear for now",未设置长期备份:"No long-term backup set",指定后才能清理:"Set one to enable clearing","检查中…":"Checking…",未检查:"Not checked",检查后才知道:"Check to find out",原件都在这里:"All originals are here",还没有笔记:"No notes yet",删除当前笔记:"Delete current note",笔记列表:"Note list",取消置顶:"Unpin from top",始终置顶:"Always on top","此浏览器不支持 Web Worker。":"This browser does not support Web Workers.","需要 HTTPS(安全上下文)。当前是 http:// 访问,浏览器不开放离线所需的 OPFS 与 Service Worker——给服务器配置 TLS(--tls-cert/--tls-key,或 Caddy / Tailscale Serve 反代;iPhone 需要受信任的证书),或在本机用 localhost 访问。":"HTTPS (a secure context) is required. This page is served over http://, so the browser withholds the OPFS and Service Worker features offline mode needs. Configure TLS on the server (--tls-cert/--tls-key, or a Caddy / Tailscale Serve reverse proxy; iPhone needs a trusted certificate), or open it locally via localhost.","此浏览器不支持 OPFS 本地存储(需要 Safari 17+ / Chrome / Firefox 较新版本)。":"This browser does not support OPFS local storage (requires Safari 17+ or a recent Chrome / Firefox).","阿里云 OSS":"Alibaba Cloud OSS",上海:"Shanghai",北京:"Beijing",广州:"Guangzhou",成都:"Chengdu",南京:"Nanjing",香港:"Hong Kong",新加坡:"Singapore",东京:"Tokyo",杭州:"Hangzhou",深圳:"Shenzhen",美国东部:"US East","美国东部 2":"US East 2",美国西部:"US West","美国西部 2":"US West 2",爱尔兰:"Ireland",法兰克福:"Frankfurt",切换数据库:"Switch database",还没有数据库:"No databases yet",搜索数据库:"Search databases","实时同步中——AI 通过 CLI 的修改会即时出现":"Live — changes an AI makes through the CLI appear instantly",还没有看板:"No board yet","在主窗口创建一个带「单选」属性的数据库,任务进度就会出现在这里。":"Create a database with a “Select” property in the main window and task progress will show up here.",编辑器尚未就绪:"The editor is not ready yet",缺少文件路径:"Missing file path",文件编辑窗口仅在桌面应用内可用:"The file editor window is only available in the desktop app","已导入到 MetaHub":"Imported into MetaHub",预览模式:"Preview",源码模式:"Source","在 MetaHub 中打开":"Open in MetaHub","已导入 ✓":"Imported ✓","导入中…":"Importing…","导入到 MetaHub":"Import into MetaHub",本地副本启动超时:"Timed out starting the local replica",本地副本启动失败:"Failed to start the local replica","此页面没有工作区主节点,不能使用服务器配对;请重新连接同步存储桶。":"This page has no workspace primary node, so server pairing is unavailable; reconnect a sync bucket.","无法获取配对码: {status}":"Could not get a pairing code: {status}","此设备通过同步存储桶交换数据,不支持设备托管发布;请在在线主节点操作":"This device exchanges data through a sync bucket and does not support device-hosted publishing; do this on the online primary node",此设备没有可配置的托管入口:"This device has no configurable hosting entry point",本机:"This device",这台设备上的副本:"The replica on this device",工作区主节点:"Workspace primary node",当前连接的工作区:"The workspace you are connected to",本机工作区:"Local workspace",这台电脑上的工作区:"The workspace on this computer",危险操作:"Danger zone"};var Cu={"加载失败:{msg}":"Failed to load: {msg}",连接存储桶:"Connect a bucket",所有设备通过它同步:"Every device syncs through it",两台服务器互相实时同步:"Two servers sync each other in real time",已触发同步:"Sync started","同步失败:{msg}":"Sync failed: {msg}","停止使用 {name}":"Stop using {name}","将停止与它同步。桶内数据不受影响,可以随时重新连接。":"Syncing with it will stop. Data in the bucket is untouched, and you can reconnect at any time.",停止使用:"Stop using",停止此浏览器离线同步:"Stop offline sync in this browser","此浏览器将不再直连 {name}。存储桶仍在服务器上;此浏览器在线时照常经服务器同步。":"This browser will no longer connect to {name} directly. The bucket stays on the server, and this browser keeps syncing through the server while online.",停止:"Stop","停止直连 {name}":"Stop direct sync with {name}","将停止与它的直连同步。它上面已同步的数据仍在,无法远程删除。":"Direct sync with it will stop. Data already synced to it stays there and cannot be deleted remotely.",停止直连:"Stop direct sync","实时 · 数据在这里产生":"Live · data is created here",直连:"Direct",已暂停:"Paused","重试中…":"Retrying…",重试:"Retry",地址:"Address","节点 ID":"Node ID",上次成功同步:"Last successful sync",尚未确认:"Unconfirmed","{n} 条改动":({n:e})=>`${e} ${Te(e,"change","changes")}`,立即同步:"Sync now",恢复同步:"Resume sync",暂停同步:"Pause sync",这台设备的名字与接入权限在:"This device's name and access are managed on the",设备:"Device","页管理。":"page.","同步失败 · {error}":"Sync failed · {error}","上次同步 {ago}":"Last synced {ago}",还没同步过:"Never synced",本机发布:"Published from this device",此浏览器可离线同步:"Offline sync available in this browser",这台设备:"This device","服务器,此浏览器也保存了一份":"Server, with a copy in this browser",服务器:"Server",服务商:"Provider",存储桶:"Bucket",加密:"Encryption","已加密,上传前在本地完成":"Encrypted locally before upload",未加密:"Not encrypted",凭据保存在:"Credentials stored on",用途:"Roles",上次同步:"Last sync",让此浏览器可离线同步:"Enable offline sync in this browser","更换存储密钥…":"Rotate storage key…","导出恢复码…":"Export recovery code…","让此浏览器可离线同步后,服务器连不上时它也能直接经存储桶同步。":"With offline sync enabled, this browser can sync straight through the bucket whenever the server is unreachable.","更换密钥…":"Rotate key…","先在「离线与缓存」把这台设备设为在本机保存,再连接存储桶。":"First set this device to keep data locally under “Offline & cache”, then connect a bucket.",前往设置:"Open settings",添加设备:"Add device",添加同步目标:"Add sync target",同步目标:"Sync targets","这台设备的云端后端,其他设备通过它加入并同步。":"This device's cloud backend; other devices join and sync through it.","数据保存在这些地方;上传到云端前已在本地加密。":"Your data lives in these places, encrypted locally before it goes to the cloud.","用 Cloudflare 开始":"Start with Cloudflare","登录后创建 R2 存储桶并部署 Edge,向导会带你在控制台生成访问密钥。":"Sign in to create an R2 bucket and deploy Edge; the wizard walks you through generating access keys in the console.","连接 Cloudflare":"Connect Cloudflare",还没有其他同步目标:"No other sync targets yet","连接一个存储桶,所有设备通过它交换加密后的工作区数据。":"Connect a bucket so every device can exchange encrypted workspace data through it.","还没连接存储桶。直连只在两边都在线时同步;存储桶能让离线的设备稍后补齐。":"No bucket connected yet. Direct sync only works while both sides are online; a bucket lets offline devices catch up later.",它是怎么工作的:"How it works","存储桶只做中转:每台设备把改动加密后上传,再拉取别人的——不必同时在线,也不需要公网 IP。直连则是两台服务器互相推送,实时但要求两边同时在线。":"A bucket is just a relay: each device encrypts its changes, uploads them and pulls everyone else's, with no need to be online at the same time or have a public IP. Direct sync pushes between two servers in real time, but both must be online.","这台设备把改动发布到桶,其他设备从桶拉取;新设备扫码加入即可。":"This device publishes changes to the bucket and other devices pull from it; a new device joins by scanning the QR code.","这台设备把整个工作区发布到桶,新设备扫码加入后从桶恢复。":"This device publishes the whole workspace to the bucket; a new device scans the QR code and restores from it.","密钥只保存在服务器;信任的设备重输一次密钥即可直连桶,离线、在外也不中断。":"The key stays on the server only; a trusted device re-enters it once to sync straight through the bucket, even offline or away.","清理腾出 {bytes}":"Clean up to free {bytes}","只删除别处已确认备份的副本,文件不会丢,用到时自动取回。":"Only copies confirmed backed up elsewhere are removed. Nothing is lost; files are fetched again when needed.",清理:"Clean up","已腾出 {bytes}({n} 项)":({bytes:e,n:t})=>`Freed ${e} (${t} ${Te(t,"item","items")})`,暂时没有可清理的:"Nothing to clean up right now","附件原件保存在「{place}」,所有设备共用。":"Original attachments are stored on “{place}”, shared by every device.","开启的位置会保留所有附件的完整副本。只要确认这里有备份,其他设备就可以放心清理本地缓存。":"Places switched on keep a full copy of every attachment. Once a backup is confirmed here, other devices can safely clear their local cache.",附件:"Attachments",长期保留副本:"Long-term copies","这里保留全部附件原件,无需清理":"All original attachments are kept here; nothing to clean up",还没指定长期保留的位置:"No long-term location chosen yet",核对备份后才能清理:"Verify backups before cleaning up","都已备份,暂时没有可清理的":"Everything is backed up; nothing to clean up right now","核对中…":"Verifying…","上次核对 {ago}":"Last verified {ago}",还没核对过:"Not verified yet","查看附件…":"View attachments…",云端存储桶:"Cloud bucket",未命名设备:"Unnamed device","还没有长期保留的位置。先指定一处,其他设备才能放心清理本地缓存。":"No long-term location yet. Pick one first so other devices can safely clear their local cache.",清理前需要几处确认:"Confirmations required before cleanup","设备清理缓存前,要有几处长期副本确认持有该附件。":"How many long-term copies must confirm they hold an attachment before a device clears it from its cache.",一处即可:"Any one place",任一长期副本确认即可清理:"Any single long-term copy is enough",每处都要:"Every place",所有长期副本都确认后才清理:"Clean up only after every long-term copy confirms","部分位置连不上,相关文件暂不清理":"Some places are unreachable; their files are kept for now",重新核对:"Verify again","占用超过 {bytes} 时,自动清理最久没用、已有备份的;你固定的不动。":"Above {bytes}, the least recently used files that are backed up are cleaned automatically; pinned files stay.",命令行:"Command line",桌面应用:"Desktop app",浏览器:"Browser",网页:"Web","设备来源刷新失败:{msg}":"Failed to refresh device sources: {msg}","撤销 {name} 的接入":"Revoke access for {name}","将同时撤销它的 {n} 个授权码。它将无法再同步进这个工作区。已同步到它上面的数据仍在,无法远程删除。":({n:e})=>`Its ${e} enrollment codes will be revoked too. It can no longer sync into this workspace. Data already synced to it stays there and cannot be deleted remotely.`,"它将无法再同步进这个工作区。已同步到它上面的数据仍在,无法远程删除。":"It can no longer sync into this workspace. Data already synced to it stays there and cannot be deleted remotely.",撤销接入:"Revoke access",重命名这台设备:"Rename this device","给 {name} 起个名字":"Name {name}",所有设备都会看到这个名字:"Every device will see this name","例如:工作室 iMac":"e.g. Studio iMac","重命名失败:{msg}":"Rename failed: {msg}",工作区所在的服务器:"The server hosting this workspace","经存储桶 {name} 同步":"Syncs through bucket {name}",直连同步:"Direct sync",直连已暂停:"Direct sync paused",通过授权码接入:"Joined with an enrollment code",曾同步过:"Synced before",工作区所在的这台设备:"The device hosting this workspace","经存储桶 {name}":"Through bucket {name}","(在线,租约至 {until})":"(online, lease until {until})",授权码:"Enrollment code","曾写入过工作区,来源未确认":"Has written to the workspace; source unconfirmed",接入方式:"Connection",应用:"App",最近活动:"Last active",重命名:"Rename","同步状态、暂停与停止直连在":"Sync status, pausing and stopping direct sync live in",数据与备份:"Data & backup","。":".","撤销后它不能再同步进来;此前已同步到它上面的数据无法远程删除。":"Once revoked it can no longer sync in; data already synced to it cannot be deleted remotely.","这台设备和其他设备共用同一把存储密钥,无法单独移除。":"This device shares the storage key with the others, so it cannot be removed on its own. After you ",更换密钥:"rotate the key","后它将不能再同步;已下载到它上面的数据无法追回。":" it can no longer sync; data already downloaded to it cannot be recalled.","正在核对已连接的存储桶…":"Checking connected buckets…","只能确认它曾写入过工作区,无法确认它现在经哪条渠道接入,所以这里不提供断开操作。":"We can only confirm it once wrote to the workspace, not which channel it uses now, so there is no disconnect action here.","{n} 台设备同步过这个工作区。":({n:e})=>`${e} ${Te(e,"device has","devices have")} synced this workspace.`,"最近 30 天":"Last 30 days","还没有其他设备。":"No other devices yet.",很久没活动:"Inactive for a while","超过 30 天没有同步的设备。如果已经不再使用,可以在这里撤销它们的接入。":"Devices that have not synced for over 30 days. If they are no longer in use, revoke their access here.","数据只在这一处,还没有备份":"Data lives in one place only; no backup yet","已保存在 {n} 处 · {m} 个附件还只在这里":({n:e,m:t})=>`Saved in ${e} ${Te(e,"place","places")} · ${t} ${Te(t,"attachment is","attachments are")} still only here`,"已保存在 {n} 处 · 有改动尚未同步":({n:e})=>`Saved in ${e} ${Te(e,"place","places")} · unsynced changes`,"已保存在 {n} 处 · {m} 处同步失败":({n:e,m:t})=>`Saved in ${e} ${Te(e,"place","places")} · ${t} ${Te(t,"place","places")} failing to sync`,"已保存在 {n} 处 · 首次同步进行中":({n:e})=>`Saved in ${e} ${Te(e,"place","places")} · first sync in progress`,"已保存在 {n} 处 · 备份确认已过期":({n:e})=>`Saved in ${e} ${Te(e,"place","places")} · backup confirmation expired`,"已安全保存在 {n} 处 · 上次确认 {ago}":({n:e,ago:t})=>`Safely saved in ${e} ${Te(e,"place","places")} · last confirmed ${t}`,"已安全保存在 {n} 处":({n:e})=>`Safely saved in ${e} ${Te(e,"place","places")}`,尚未配置任何同步目标:"No sync target configured yet",同步失败:"Sync failed",尚未完成首次同步:"First sync not finished yet",有改动尚未同步:"Unsynced changes",备份确认已过期:"Backup confirmation expired",有附件仅在本机:"Some attachments exist only on this device","{place}:{issue}":"{place}: {issue}","{issue} — {detail}":"{issue} — {detail}",本机:"This device","实时(本机)":"Live (this device)",当前版本已确认:"Current version confirmed",确认已过期:"Confirmation expired",尚未同步:"Not synced yet",已停用:"Disabled",完整副本:"Full replica",工作区同步:"Workspace sync",附件长期保存:"Long-term attachments",发布快照:"Published snapshots",尚未确认当前版本:"Current version not confirmed yet",加密口令必填:"Encryption passphrase is required","加密口令不正确,请输入与其他设备相同的口令。":"Wrong encryption passphrase. Enter the same passphrase as on your other devices.","连接被浏览器拦截:请给存储桶配置 CORS,允许此源的 GET/PUT/HEAD/DELETE。":"The browser blocked the connection. Configure CORS on the bucket to allow GET/PUT/HEAD/DELETE from this origin.","连接失败:{msg}":"Connection failed: {msg}","endpoint、bucket、access key、secret key 必填":"Endpoint, bucket, access key and secret key are required",没有在图片中找到有效的接入二维码:"No valid enrollment QR code found in the image",连接你的存储桶:"Connect your bucket","扫描主设备上的二维码:在桌面端打开 设置 → 同步 → 手机接入。":"Scan the QR code on your primary device: open Settings → Sync → Mobile access on the desktop.",相机权限被拒绝:"Camera access denied","允许访问相机,或改用下方粘贴/手动方式。":"Allow camera access, or paste or fill in the details below instead.",重试授权:"Try again",这不是有效的接入二维码:"This is not a valid enrollment QR code",无效的接入链接或代码:"Invalid enrollment link or code",从图片识别:"Read from image",手动填写:"Enter manually","已读取桶信息,输入加密口令即可同步你的数据。":"Bucket details loaded. Enter the encryption passphrase to sync your data.","已读取桶信息,点击连接即可同步你的数据。":"Bucket details loaded. Click Connect to sync your data.",端到端加密:"End-to-end encrypted",加密口令:"Encryption passphrase",与其他设备相同的口令:"Same passphrase as your other devices","连接中…":"Connecting…",连接并同步:"Connect and sync",重新扫码:"Scan again",改为手动填写:"Enter manually instead","填入 S3 兼容存储桶(R2/COS/MinIO/S3)的连接信息;数据上传前端到端加密。":"Enter the connection details of an S3-compatible bucket (R2/COS/MinIO/S3). Data is end-to-end encrypted before upload.",路径前缀:"Path prefix",改为扫码:"Scan a QR code instead","提示:iPhone 请用 Safari 的「分享 → 添加到主屏」装成 App,离线与持久存储才生效。":"Tip: on iPhone, use Safari's Share → Add to Home Screen to install as an app; offline mode and persistent storage only work that way.","或粘贴接入链接 / 接入码…":"Or paste an enrollment link / code…",当前服务器:"Current server"};var Pu={回滚待确认:"Rollback pending confirmation",撤销待确认:"Revoke pending confirmation",发布失败:"Publish failed","正在创建 Edge 渠道":"Creating Edge channel","已上线 · Edge 始终在线":"Live · Edge, always on","已上线 · 设备托管":"Live · device hosted","正在同步 · 设备托管":"Syncing · device hosted","已设公开 · 入口未验证":"Set public · entry point unverified",链接分享中:"Shared by link",链接已过期:"Link expired",私有预览:"Private preview",在线:"Online",同步中:"Syncing",入口未验证:"Entry point unverified",正在创建:"Creating",等待控制设备:"Waiting for controller device",失败:"Failed",已过期:"Expired",任何人:"Anyone",持链接者:"Anyone with the link",已复制:"Copied","{n} 个 api/ 下的文件会被站点数据 API 遮蔽(仍会上传,但无法访问)":({n:e})=>`${e} ${Te(e,"file","files")} under api/ will be shadowed by the site data API (uploaded, but unreachable)`,"已上传 {n} 个文件":({n:e})=>`Uploaded ${e} ${Te(e,"file","files")}`,"已上传 {ok}/{total} 个,{failed} 个失败":"Uploaded {ok}/{total}, {failed} failed",部分文件上传失败:"Some files failed to upload","{n} 个文件未能上传,可修正后重新拖入(成功的文件无需重传)。":({n:e})=>`${e} ${Te(e,"file","files")} could not be uploaded. Fix and drop them in again; successful files need no re-upload.`,关闭:"Close","上传中 {done}/{total}…":"Uploading {done}/{total}…","已关闭 SPA 模式":"SPA mode off","已开启 SPA 模式(无扩展名路径回落到 index.html)":"SPA mode on (extensionless paths fall back to index.html)",配置管理:"Configuration",复制私有预览地址:"Copy private preview URL","发布与分享…":"Publish & share…","关闭 SPA 模式":"Turn off SPA mode","开启 SPA 模式":"Turn on SPA mode","修改标题…":"Edit title…",修改标题:"Edit title",标题:"Title","重命名(slug)…":"Rename (slug)…",删除站点:"Delete site","删除站点?":"Delete site?","「{name}」及其 {n} 个文件将被删除。":({name:e,n:t})=>`“${e}” and its ${t} ${Te(t,"file","files")} will be deleted.`,删除:"Delete","加载失败:{msg}":"Failed to load: {msg}","拖入一个目录即可上传为站点(目录名 = 站点名)":"Drop a folder to upload it as a site (folder name = site name)","目录名「{name}」无法转成有效的站点名":"Folder name “{name}” cannot be turned into a valid site name",目录里没有可上传的文件:"The folder has no files to upload","创建站点「{name}」?":"Create site “{name}”?","站点「{name}」不存在。创建它并上传 {n} 个文件?":({name:e,n:t})=>`Site “${e}” does not exist. Create it and upload ${t} ${Te(t,"file","files")}?`,创建并上传:"Create and upload",站点管理:"Sites","发布静态站点,生成可分享的访问链接。":"Publish static sites and get shareable links.",新建站点:"New site",正在加载:"Loading",还没有站点:"No sites yet","站点是一组网页文件,可先在本机预览,发布后供他人访问。":"A site is a set of web files. Preview it locally, then publish it for others.",未命名站点:"Untitled site",点击复制公开地址:"Click to copy the public URL","存在多个公开地址;打开详情选择":"Several public URLs; open details to choose","私密链接不在卡片显示;打开详情管理":"Private links are not shown on the card; open details to manage",点击复制私有预览地址:"Click to copy the private preview URL","{n} 个公开地址":({n:e})=>`${e} public ${Te(e,"URL","URLs")}`,"{n} 个私密链接":({n:e})=>`${e} private ${Te(e,"link","links")}`,"私有预览 · {url}":"Private preview · {url}","{n} 文件":({n:e})=>`${e} ${Te(e,"file","files")}`,预览:"Preview","回滚仍未确认:{msg}":"Rollback still unconfirmed: {msg}",目标设备不可达:"target device unreachable",目标设备已确认恢复发布前状态:"Target device confirmed the pre-publish state is restored",重试回滚:"Retry rollback",管理:"Manage",发布:"Publish",更多:"More","共 {n} 个站点":({n:e})=>`${e} ${Te(e,"site","sites")}`,"{n} 个文件":({n:e})=>`${e} ${Te(e,"file","files")}`,请填写站点名称:"Enter a site name","已创建站点「{name}」":"Created site “{name}”","创建一组网页文件,随你的设备自动同步。":"Create a set of web files that sync with your devices.",取消:"Cancel",创建:"Create","名称(slug)":"Name (slug)","例如:docs、demo、status":"e.g. docs, demo, status","标题(可选)":"Title (optional)",人类可读的标题:"A human-readable title","将通过 /sites/<名称>/ 对外提供。":"Served at /sites/<name>/.","请输入有效的站点名(a-z、0-9、-)":"Enter a valid site name (a-z, 0-9, -)","已重命名为「{name}」":"Renamed to “{name}”","重命名(slug)":"Rename (slug)","slug 决定站点的访问地址 /sites/<slug>/。":"The slug sets the site address: /sites/<slug>/.","保存中…":"Saving…",重命名:"Rename","新名称(slug)":"New name (slug)","将保存为 /sites/{name}/":"Will be saved as /sites/{name}/",无法从输入得到有效的站点名:"No valid site name can be made from the input","注意:重命名后旧链接将失效 — /sites/{name}/ 不再可访问,已分发的地址需要更新。":"Note: old links break after renaming — /sites/{name}/ will no longer work, so distributed URLs must be updated.",站点不存在:"Site not found","「{name}」可能已被删除或重命名。":"“{name}” may have been deleted or renamed.",查看全部站点:"View all sites",站点还没有文件:"This site has no files yet","上传文件后,这里会直接显示站点页面。":"Once files are uploaded, the site page shows here.",去配置:"Configure",还没有文件:"No files yet",打开站点:"Open site",打开:"Open","删除文件?":"Delete file?","「{path}」将从站点「{name}」中删除。":"“{path}” will be removed from site “{name}”.","{n} 个文件 · 创建于 {date}":({n:e,date:t})=>`${e} ${Te(e,"file","files")} · created ${t}`,"已发布 · {n} 个渠道":({n:e})=>`Published · ${e} ${Te(e,"channel","channels")}`,私有:"Private",访问:"Access",仅你和已配对设备可打开:"Only you and paired devices can open it",复制地址:"Copy URL",访问站点:"Visit site",发布渠道:"Publish channels","还没有发布 — 目前只有你(和已配对设备)能打开上面的预览地址。":"Not published yet — only you (and paired devices) can open the preview URL above.","{host}托管":"{host} hosted",需要口令:"Password required","文件##tab":"Files",上传文件:"Upload files","上传整个目录(保留相对路径),也可以直接拖拽目录进来":"Upload a whole folder (relative paths kept); you can also drag a folder in",上传目录:"Upload folder","上传文件后即可通过站点地址访问。":"Once files are uploaded, the site is reachable at its URL.",文件大小:"File size",复制路径:"Copy path","(无法加载内容)":"(content could not be loaded)","二进制文件 · 在新标签打开查看":"Binary file · open in a new tab to view","Cloudflare 授权失败":"Cloudflare authorization failed","请先确认将创建或更新列出的 Cloudflare 资源":"Confirm first that the listed Cloudflare resources will be created or updated","请先用 Cloudflare 登录":"Sign in with Cloudflare first","请选择要部署到的 Cloudflare 账号":"Choose the Cloudflare account to deploy to","{n} 个站点重新接线失败:{sites}":({n:e,sites:t})=>`${e} ${Te(e,"site","sites")} failed to rewire: ${t}`,"、":", ",";":"; ","R2 桶创建失败:{msg}":"R2 bucket creation failed: {msg}","Edge 部署完成;{notes}":"Edge deployed; {notes}","Edge 部署完成":"Edge deployed","请填入 Access Key ID 与 Secret":"Enter the Access Key ID and Secret",请设置加密口令:"Set an encryption passphrase",同步桶已接入:"Sync bucket connected",接入同步桶:"Connect sync bucket","R2 桶 {name} 已创建。最后一步:Cloudflare 不允许应用代为创建 S3 凭据,请到控制台生成后粘贴到这里。":"R2 bucket {name} created. Last step: Cloudflare does not let apps create S3 credentials, so generate them in the dashboard and paste them here.",稍后再接:"Connect later","接入中…":"Connecting…","R2 → 管理 R2 API 令牌":"R2 → Manage R2 API Tokens",",创建一个「对象读和写」令牌(可只勾选 {bucket} 这个桶),把页面显示的 Access Key ID 与 Secret Access Key 粘贴到下面。":", create an “Object Read & Write” token (you can limit it to the {bucket} bucket), then paste the Access Key ID and Secret Access Key shown there below.","加密口令(新工作区在此设置;其他设备加入时需输入同一口令)":"Encryption passphrase (set here for a new workspace; other devices enter the same one to join)","口令保护数据机密性,请牢记;接入完成后建议在「设备与授权 → 导出恢复码」打印备份。":"The passphrase protects your data; remember it. After connecting, print a backup via “Devices → Export recovery code”.","升级 Edge":"Upgrade Edge","部署 Edge":"Deploy Edge","将在你自己的 Cloudflare 账户中创建或更新一个 Worker、一个 D1 数据库和 workers.dev 入口。凭据仅用于本次请求,不会保存。":"Creates or updates a Worker, a D1 database and a workers.dev entry point in your own Cloudflare account. Credentials are used for this request only and never stored.","部署中…":"Deploying…",确认并部署:"Confirm and deploy","Cloudflare 账号":"Cloudflare account","选择账号…":"Choose an account…","{name}({id})":"{name} ({id})","✅ 已登录:{name}":"✅ Signed in: {name}","等待浏览器授权…":"Waiting for browser authorization…","用 Cloudflare 登录":"Sign in with Cloudflare","将打开 Cloudflare 授权页,只申请 Workers 与 D1 的最小权限;令牌仅用于本次部署、不会保存。":"Opens the Cloudflare consent page requesting only the minimal Workers and D1 permissions; the token is used for this deployment only and never stored.","改用 API Token":"Use an API token instead","临时 API Token":"Temporary API token","需要 Workers Scripts Write 与 D1 Write。Cloudflare Token 是账户级凭据,请仅使用最小权限 Token。":"Needs Workers Scripts Write and D1 Write. A Cloudflare token is an account-level credential; use one with minimal permissions.","改用 Cloudflare 登录":"Sign in with Cloudflare instead","Worker 名称":"Worker name","D1 名称":"D1 name","workers.dev 子域(账户尚未设置时创建)":"workers.dev subdomain (created if the account has none)","子域属于整个 Cloudflare 账户;如果账户已有子域,将使用现有值并在完成结果中提示。":"The subdomain belongs to the whole Cloudflare account; if one already exists it is used and noted in the result.","同时创建 R2 同步桶(创建桶后仍需单独生成 S3 凭据)":"Also create an R2 sync bucket (S3 credentials must still be generated separately)","R2 桶名称":"R2 bucket name","创建后还差一步:到 Cloudflare 控制台生成 S3 凭据并粘贴(授权无法代办这一步),本向导会引导你完成。":"One more step after creation: generate S3 credentials in the Cloudflare dashboard and paste them (authorization cannot do this for you); this wizard walks you through it.","检测到未完成部署,当前步骤:{step}。使用相同名称可继续,不会自动删除已创建资源。":"An unfinished deployment was found at step {step}. Keep the same names to continue; created resources are not deleted automatically.","我确认创建或更新上述 Cloudflare 资源;断开 MetaHub 时不会自动删除它们。":"I confirm creating or updating the Cloudflare resources above; they are not deleted automatically when MetaHub disconnects.",密钥必填:"Secret is required",加密口令必填:"Encryption passphrase is required","服务器未提供该桶的完整配置,无法在本设备激活":"The server did not provide the full bucket configuration; cannot activate on this device","已让本机直连存储桶 · 离线、在外也能直接同步":"This device now syncs with the bucket directly · works offline and away","连接被浏览器拦截:请给存储桶配置 CORS,允许此源的 GET/PUT/HEAD/DELETE。":"The browser blocked the connection: configure CORS on the bucket to allow GET/PUT/HEAD/DELETE from this origin.","启用失败:{msg}":"Failed to enable: {msg}",在本设备启用直连:"Enable direct sync on this device","服务器已配置这个存储桶。为保护密钥,服务器不会把它同步到浏览器——再输入一次密钥,这台设备就能与桶直接同步(离线、在外也不中断)。":"The server already has this bucket configured. To protect the secret it is never sent to the browser — enter it once more and this device syncs with the bucket directly (offline and away too).","连接中…":"Connecting…",启用直连:"Enable direct sync",存储桶:"Bucket",服务地址:"Endpoint","访问密钥 ID":"Access key ID",密钥:"Secret",重新输入该桶的密钥:"Re-enter the bucket's secret",加密口令:"Encryption passphrase",与其它设备相同的加密口令:"The same passphrase as your other devices","跨设备共用的那把加密钥——用它解开桶里别人的数据。":"The encryption key shared across devices — it unlocks the data others put in the bucket.","壳地址(手机访问的静态站点域名;留空用当前地址)":"Shell URL (static site domain the phone opens; blank = current address)",复制链接:"Copy link",已复制链接:"Link copied","手机相机扫码打开,输入加密口令即可同步。":"Scan with the phone camera, enter the passphrase, and it syncs.",在另一台电脑的终端运行:"Run in a terminal on the other computer",复制命令:"Copy command",已复制命令:"Command copied",复制接入码:"Copy enrollment code",已复制接入码:"Enrollment code copied","对方运行后会提示输入加密口令。也可在":"It will prompt for the passphrase. Alternatively, in the","向导选「粘贴接入码加入存储」。":"wizard choose “Join storage with an enrollment code”.","{time} 后过期":"Expires in {time}","已过期,请重新生成":"Expired, generate a new one",复制配对码:"Copy pairing code",已复制配对码:"Pairing code copied","生成失败:{msg}":"Failed to generate: {msg}",地址和配对码必填:"Address and pairing code are required","已配对 {url}":"Paired with {url}","配对失败:{msg}":"Pairing failed: {msg}",邀请另一台服务器配对:"Invite another server to pair","生成中…":"Generating…",生成本机配对码:"Generate a pairing code","已有对方的配对码?":"Have the other side's pairing code?",对方服务器地址:"Other server's address",配对码:"Pairing code","对方「生成本机配对码」得到的码":"The code from “Generate a pairing code” on the other side","本机可达地址(可选)":"Reachable address of this server (optional)",留空则仅本机主动同步:"Blank = only this server initiates sync","配对中…":"Pairing…",配对:"Pair",直连另一台服务器:"Connect another server directly","两台服务器互相实时同步。一边生成配对码,另一边填入。":"Two servers sync with each other in real time. Generate a pairing code on one side and enter it on the other.",完成:"Done",在手机上打开本服务器:"Open this server on your phone","服务器地址(手机访问的域名;留空用当前地址)":"Server address (domain the phone opens; blank = current address)","⚠ 含访问令牌,请勿公开分享。":"⚠ Contains the access token; do not share publicly.",手机扫码:"Scan on phone","电脑 / 命令行":"Computer / CLI",手机打开服务器:"Open server on phone",找不到该存储的配置:"Configuration for this storage was not found",添加设备:"Add device","让另一台设备加入同一个工作区——手机扫码,或在电脑上粘贴接入码。":"Bring another device into this workspace — scan on a phone, or paste the enrollment code on a computer.","加载中…":"Loading…","⚠ 接入码含桶访问密钥,请勿公开分享;不含加密口令——新设备需另输口令。":"⚠ The enrollment code contains the bucket access key; do not share publicly. It does not contain the passphrase — the new device enters it separately.","https://<账户ID>.r2.cloudflarestorage.com":"https://<account-id>.r2.cloudflarestorage.com","R2 控制台 → 管理 R2 API 令牌,创建仅限目标桶的对象读写凭据;区域填 auto。价格与额度以 Cloudflare 控制台为准。":"R2 dashboard → Manage R2 API Tokens: create object read/write credentials limited to the target bucket; region is auto. Pricing and quotas as shown in the Cloudflare dashboard.","https://s3.<区域>.amazonaws.com":"https://s3.<region>.amazonaws.com","IAM 用户的访问密钥;区域如 us-east-1。":"An IAM user's access key; region such as us-east-1.","https://minio.你的域名":"https://minio.your-domain","自建 MinIO 的访问地址与 access / secret key。":"Your self-hosted MinIO endpoint and access / secret key.","腾讯云 COS":"Tencent Cloud COS","https://<桶名-APPID>.cos.<区域>.myqcloud.com":"https://<bucket-APPID>.cos.<region>.myqcloud.com","桶名须含 APPID,用虚拟主机风格地址(host 以桶名开头)。":"The bucket name must include the APPID; use a virtual-hosted-style endpoint (host starts with the bucket name).",自定义:"Custom","任何 S3 兼容存储桶。":"Any S3-compatible bucket.","服务地址、桶名称、访问密钥 ID、密钥都要填":"Endpoint, bucket name, access key ID and secret are all required","加密口令必填(或关闭加密)":"Encryption passphrase is required (or turn encryption off)","已连接存储桶 · 服务器开始同步到桶,这台设备也直接同步":"Bucket connected · the server syncs to it, and so does this device directly","已连接存储桶 · 服务器开始同步到桶":"Bucket connected · the server now syncs to it","已连接存储桶 · 这台设备开始同步到桶":"Bucket connected · this device now syncs to it","连接被浏览器拦截:请给存储桶配置 CORS,允许此源的 GET/PUT/HEAD/DELETE(R2 控制台一条规则即可)。":"The browser blocked the connection: configure CORS on the bucket to allow GET/PUT/HEAD/DELETE from this origin (one rule in the R2 dashboard is enough).","添加失败:{msg}":"Failed to add: {msg}",连接存储桶:"Connect a bucket","连接一个 S3 兼容存储桶,所有设备就能同步——不需要公网服务器。新桶自动初始化;已有桶用相同加密口令即可加入。":"Connect an S3-compatible bucket and all devices sync — no public server needed. A new bucket is initialized automatically; join an existing one with the same passphrase.",连接:"Connect","连接后,工作区主节点负责把整库同步到这个桶;这台设备和其他设备都从它同步。":"Once connected, the workspace primary node syncs the whole hub to this bucket; this and other devices sync from it.","连接后,这台设备(本机)把整库同步到这个桶;新设备扫码加入即可一起用。":"Once connected, this device syncs the whole hub to this bucket; new devices join by scanning.",存储服务商:"Storage provider",桶名称:"Bucket name","端到端加密(强烈建议;关闭后文件以明文存放,仅限完全信任的存储)":"End-to-end encryption (strongly recommended; off = files stored in plain text, only for fully trusted storage)","新桶以此创建;其它设备用同一口令加入":"Used to create a new bucket; other devices join with the same passphrase","这是跨设备共用的一把加密钥——记牢它,换设备 / 加入已有桶时都要用它解开数据。":"This is the encryption key shared across devices — remember it; you need it to unlock data on a new device or when joining an existing bucket.",进阶:"Advanced",区域:"Region","大多按服务商默认即可(R2 用 auto)。":"Usually the provider default (auto for R2).",路径前缀:"Path prefix","同一个桶里隔离多个工作区时用;默认 metahub。":"For keeping several workspaces apart in one bucket; default metahub.","新密钥需要同时填 Access Key ID 和 Secret。":"A new key needs both the Access Key ID and the Secret.","两次输入的新口令不一致。":"The two new passphrases do not match.","没有要更改的内容。":"Nothing to change.",轮换完成:"Rotation complete","✓ 存储密钥已更换 — 现在可以到服务商控制台停用旧密钥了。":"✓ Storage key rotated — you can now disable the old key in the provider console.","✓ 口令已更换 — 已配置设备无需重输,只有新加入的设备需要新口令。":"✓ Passphrase changed — configured devices need not re-enter it; only newly joining devices use the new one.","⚠️ 轮换后的首次同步失败:{msg}(凭据已保存,稍后可在同步页重试)":"⚠️ First sync after rotation failed: {msg} (credentials saved; retry later from the sync page)","其他设备用下面的新接入码重新接入(数据与同步进度不受影响)。丢失设备此前已同步的数据无法远程抹除;它只是无法再获取之后的数据。":"Other devices reconnect with the new enrollment code below (data and sync progress are unaffected). Data a lost device already synced cannot be wiped remotely; it just receives nothing further.",复制:"Copy",轮换存储密钥:"Rotate storage keys","适用于「手机丢了 / 密钥泄露 / 想换口令」。":"For a lost phone, a leaked key, or a passphrase change.","轮换中…":"Rotating…",开始轮换:"Start rotation","请先在存储服务商控制台新建一把 Access Key——先不要删除旧的,完成后再停用。 中途任何失败,旧钥匙都还能用;重试即可续接。":"In the storage provider console, create a new Access Key first — do not delete the old one yet; disable it once done. If anything fails midway the old key keeps working; retry to resume.","新 Access Key ID(留空 = 不更换密钥)":"New Access Key ID (blank = keep current key)","新 Secret Access Key":"New Secret Access Key","同时更换加密口令(不会重新加密历史数据;已配置设备无需重输)":"Also change the passphrase (past data is not re-encrypted; configured devices need not re-enter it)",新口令:"New passphrase",再输一次确认:"Confirm new passphrase",导出恢复码:"Export recovery code",打印:"Print","没有加密的存储桶,无需恢复码。":"No encrypted bucket; no recovery code needed.","Metahub 恢复码":"Metahub recovery code","存储桶 {bucket} · 生成于 {date}":"Bucket {bucket} · generated {date}","这串代码等于你全部数据的钥匙。忘记加密口令时,凭它可恢复数据并设置新口令。 请打印或抄写,放在安全的地方;不要保存在会被同步的笔记里。 任何拿到它的人都能读取你的全部数据。":"This code is the key to all your data. If you forget the passphrase, it restores your data and lets you set a new one. Print it or write it down and keep it somewhere safe; do not store it in a note that syncs. Anyone holding it can read all your data."};var Nu={"新建链接":"New link","暂无可用的托管位置":"No hosting destination available","设备与服务器":"Devices and servers","存储桶托管 · 固定快照":"Bucket hosting · Snapshot","设备托管 · 实时内容":"Device hosting · Live content","本机离线也可访问。内容固定为创建时的版本,后续修改需手动更新快照。":"Accessible while this device is offline. Shares the version at creation; update the snapshot to include later edits.","由所选设备提供访问,需保持在线。接收者看到最新内容。":"Served by the selected device, which must stay online. Recipients see the latest content.","设置访问口令":"Set an access passcode","到期状态":"Expiration","操作":"Actions","原口令无法恢复,请为新链接重新设置口令。":"The original passcode cannot be recovered. Set a new one for this link.","链接已准备好。自动复制失败,请选中下方地址手动复制。":"Your link is ready. Copy failed; select the address below to copy it manually.","撤销已提交,等待托管端确认。":"Revocation requested. Waiting for the host to confirm.","链接已撤销。":"Link revoked.","刷新状态":"Refresh status","续期并复制链接":"Renew and copy link","创建分享链接":"Create a share link","无法加载分享状态。请重试后再操作。":"Unable to load sharing status. Please retry before continuing.","分享内容":"Shared content","访问权限":"Access level","可以查看":"Can view","可以编辑":"Can edit","链接有效期":"Link expires","更多设置":"More settings","已设口令":"Passcode set","访问口令":"Passcode","暂无可用的托管位置,请先在设置中连接存储桶或服务器。":"No available host. Connect a bucket or server in Settings first.","正在撤销访问":"Revoking access","链接正在创建":"Link is being created","托管端尚未确认,链接可能仍可访问。":"The host has not confirmed yet. This link may still be accessible.","{date} 到期":"Expires {date}","已设置":"Set","未设置":"Not set","快照时间":"Snapshot taken","管理此链接":"Manage this link","更新快照内容":"Update snapshot","替换为最新版本,并延长链接有效期":"Replace with the latest version and renew the link","仅延长有效期":"Extend expiration only","保留当前快照内容":"Keep the current snapshot content","分享链接":"Shared links","正在加载分享链接…":"Loading shared links…","链接详情":"Link details","Edge 托管 · 设备离线仍可访问":"Edge hosted · reachable while offline",修改:"Update",全部:"All",关闭:"Close",分享:"Share","加载失败:{msg}":"Failed to load: {msg}",发布与分享:"Publish & share",同步失败:"Sync failed",复制:"Copy",复制链接:"Copy link",存储桶:"Bucket",已过期:"Expired",打开:"Open",撤销:"Revoke",更多:"More",本机:"This device",正在创建:"Creating",清理:"Clean up",清除筛选:"Clear filters",立即同步:"Sync now",设备:"Device",重试:"Retry",链接已复制:"Link copied",链接已过期:"Link expired","\uD83D\uDD12 有口令":"\uD83D\uDD12 Passcode","{n} 个分享":({n:e})=>`${e} ${Te(e,"share","shares")}`,"1 小时":"1 hour","24 小时":"24 hours","30 天":"30 days","7 天":"7 days","Edge 链接":"Edge link","Edge 托管 — 设备离线仍可访问":"Edge hosted — reachable while your devices are offline","Edge 托管 · 设备离线仍可访问(当前端点仅支持 inbox)":"Edge hosted · reachable while offline (this endpoint only supports inbox)","Edge 托管 · 设备离线仍可访问(公开网页暂不支持)":"Edge hosted · reachable while offline (not available for public pages yet)","Edge 托管 · 设备离线仍可访问(请先配置)":"Edge hosted · reachable while offline (set up Edge first)",按来源筛选:"Filter by source",本设备未记录已验证入口:"No verified entry recorded on this device",撤销链接:"Revoke link","撤销已请求,等待 Edge 确认销毁":"Revoke requested, waiting for Edge to confirm teardown","远端尚未确认完成撤销,管理记录已保留,请重试撤销。":"Remote cleanup is not confirmed. Management records are retained; retry revocation.","撤销已请求,等待控制设备上线完成清理":"Revoke requested, waiting for the controlling device to come online and clean up","撤销已请求,等待控制设备完成清理":"Revoke requested, waiting for the controlling device to clean up","撤销已提交,但 Edge 尚未确认销毁 Room;本地保留管理记录并会继续重试。":"Revoke submitted, but Edge has not confirmed the Room teardown yet; the local record is kept and retries continue.","撤销意图会同步到控制设备。若控制设备离线,Edge Room 会显示“等待控制设备”,上线后自动销毁。":"The revoke syncs to the controlling device. If it is offline, the Edge Room shows “waiting for controller” and is torn down once it comes online.","撤销意图会同步到托管设备;该设备收到后将停止提供这个渠道。":"The revoke syncs to the hosting device, which stops serving this channel once it receives it.","撤销这个分享?":"Revoke this share?","撤销这个链接?":"Revoke this link?",撤销中:"Revoking","处理中…":"Working…",创建并复制链接:"Create and copy link",创建失败:"Creation failed",创建私密链接:"Create private link","创建中…":"Creating…","此设备通过同步存储桶交换数据、不常驻在线;请改为 Edge 托管的链接":"This device exchanges data through the sync bucket and is not always online; use an Edge-hosted link instead","此设备通过同步存储桶交换数据、不常驻在线。请在在线主节点管理公开发布;这里仍可创建由 Edge 托管的私密分享链接。":"This device exchanges data through the sync bucket and is not always online. Manage public publishing on the online primary node; you can still create Edge-hosted private links here.","此设备通过同步存储桶交换数据、不常驻在线,无法直接托管站点。":"This device exchanges data through the sync bucket and is not always online, so it cannot host a site directly.","从过期链接重新创建 — 口令需重新设置(旧口令无法恢复)。":"Re-creating from an expired link — set the passcode again (the old one cannot be recovered).","存储桶 {name}":"Bucket {name}","存储桶分享是一份快照;链接需续签后生成":"A bucket share is a snapshot; the link is generated on renewal",打开链接:"Open link",打开原表格:"Open source table",打开原对象:"Open source item",打开原文档:"Open source document",打开站点配置:"Open site settings","当前 Edge 端点仅支持数据收件(inbox),不能托管站点":"This Edge endpoint only supports the data inbox and cannot host sites","当前 Edge 端点仅支持数据收件(inbox),不能托管站点;重新部署官方 Edge Worker 即可启用。":"This Edge endpoint only supports the data inbox and cannot host sites; redeploy the official Edge Worker to enable it.","当前访问渠道({n})":"Current access channels ({n})","当前设备还没有配置公网或局域网入口,访客将无法访问。":"This device has no public or LAN entry configured yet, so visitors cannot reach it.",等待生成地址:"Waiting for an address","(等待首次同步)":"(waiting for first sync)",点击复制:"Click to copy",读:"Read",发布公开网页:"Publish public page","发布失败,目标设备的回滚尚未确认;在确认前它可能仍可公开访问。":"Publishing failed and the target device has not confirmed the rollback; it may still be publicly reachable until it does.",发布未返回访问地址:"Publishing returned no address","发布与分享:{title}":"Publish & share: {title}","发布中…":"Publishing…",分享列表加载失败:"Failed to load shares","改用 Edge 托管":"Use Edge hosting instead","高级:数据授权(让页面读写数据)…":"Advanced: data grants (let the page read and write data)…","高级:允许修改已有行…":"Advanced: allow editing existing rows…",更改:"Change",更新快照并续期:"Update snapshot and renew","更新快照内容并续期?":"Update snapshot content and renew?",更新内容并续期:"Update content and renew",公开:"Public",公开地址已复制:"Public address copied",还没有分享出去的内容:"Nothing shared yet","还没有连接 Edge。部署到你自己的 Cloudflare 后,站点始终在线,你的设备关机也能访问。":"Edge is not connected yet. Deploy to your own Cloudflare and the site stays online even when your devices are off.","还没有任何访问渠道 — 在下方创建。":"No access channels yet — create one below.","换个关键词,或清除当前的状态与来源筛选。":"Try another keyword, or clear the status and source filters.","记录将被删除。设备与 Edge 分享如需再次公开,可以重新分享。":"The records will be deleted. Device and Edge shares can be shared again later.","将用当前最新数据覆盖这份快照,接收者会看到更新后的版本;同时生成新的访问链接。":"The snapshot will be overwritten with the latest data, recipients will see the updated version, and a new access link is generated.",可编辑:"Editable",可选:"Optional",口令:"Passcode",口令保护:"Passcode protected",快过期:"Expiring",快照链接:"Snapshot link",来源:"Source",了解此设备的同步方式:"How this device syncs","链接立即失效,接收者将无法再打开。":"The link stops working immediately and recipients can no longer open it.","链接无法被猜到;可加口令和有效期。":"The link cannot be guessed; add a passcode and expiry if you like.","链接已过期 — 过期链接无法访问,可重新创建":"Link expired — expired links cannot be opened; you can re-create it",链接已失效:"Link no longer valid","链接有效至 {when}":"Link valid until {when}","(没有可授权的数据库)":"(no databases to grant)","没有可托管站点的设备。":"No device can host the site.",没有匹配的分享:"No matching shares","内容不变,重新生成访问链接":"Content unchanged, generates a new access link","内容生成于 {when}":"Content generated {when}","内容同步于 {ago}":"Content synced {ago}","前往设置 → 站点与发布":"Go to Settings → Sites & publishing","清理 {n} 个已过期分享?":({n:e})=>`Clean up ${e} expired ${Te(e,"share","shares")}?`,清理全部已过期:"Clean up all expired","清理中…":"Cleaning up…","请先在“设置 → 站点与发布”连接或部署 Edge":"Connect or deploy Edge in “Settings → Sites & publishing” first","请先在“设置 → 站点与发布”配置当前设备的公网或局域网入口":"Configure this device's public or LAN entry in “Settings → Sites & publishing” first",渠道已撤销:"Channel revoked",全部来源:"All sources",权限:"Permission",确认公开发布:"Confirm public publish","确认公开发布到设备?":"Publish publicly on this device?","任何人将无法再通过公开地址访问这个站点;已有的分享链接不受影响。浏览器或 CDN 缓存可能仍保留数分钟。":"Nobody will be able to reach this site through the public address anymore; existing share links are unaffected. Browser or CDN caches may linger for a few minutes.",任何人可访问:"Anyone can access","任何人无需登录即可访问公开地址。":"Anyone can open the public address without signing in.","任何人无需登录即可通过这个地址访问。公开权限会同步,但只有选定的托管设备提供此渠道;改回私有后,浏览器或 CDN 缓存仍可能保留数分钟。数据授权:{n} 个数据库。设备必须保持在线。":({n:e})=>`Anyone can open this address without signing in. Public permissions sync, but only the selected hosting device serves this channel; after switching back to private, browser or CDN caches may linger for a few minutes. Data grants: ${e} ${Te(e,"database","databases")}. The device must stay online.`,"设备 {name}":"Device {name}",设备链接:"Device link",设备在线托管:"Hosted on a device","设备在线托管 — {device},需保持在线":"Hosted on a device — {device}, must stay online","设备在线托管(此设备无法托管)":"Hosted on a device (this device cannot host)",收起高级选项:"Hide advanced options",收起数据授权:"Hide data grants","数据授权:已开启 {n} 张表…":({n:e})=>`Data grants: ${e} ${Te(e,"table","tables")} enabled…`,"搜索标题 / 链接…":"Search titles / links…","所有对外公开的链接都在这里:谁能看、看到哪个版本、还能看多久。":"Every outbound link lives here: who can see it, which version, and for how long.",停止公开:"Stop public access",停止公开访问:"Stop public access","停止公开访问?":"Stop public access?","停止这个公开渠道?":"Stop this public channel?","(同步失败)":"(sync failed)","同步中…":"Syncing…","托管设备必须保持在线。渠道和撤销意图会随工作区同步,其他设备不会自动获得这个公开地址。":"The hosting device must stay online. Channels and revokes sync with the workspace; other devices do not automatically get this public address.",托管位置:"Hosting","无法读取现有公开权限:{msg}":"Could not read the current public permissions: {msg}","现有公开权限尚未加载。":"Current public permissions have not loaded.","现有公开权限尚未加载,请先点「重新加载权限」。":"Current public permissions have not loaded; click “Reload permissions” first.",新增:"Create",新增访问方式:"Add access",续期:"Renew","续期(仅链接)":"Renew (link only)",延长有效期:"Extend expiry","页面内的数据接口({api})默认关闭。若这个站点需要访客读取或提交数据,在这里按表开启。":"The page's data API ({api}) is off by default. If this site needs visitors to read or submit data, enable it per table here.",已撤销:"Revoked",已更新快照内容并复制新链接:"Snapshot updated and the new link copied","已配对的托管设备当前未确认可用。请先同步成功,或配置当前主节点的访问入口。":"No paired hosting device is confirmed available. Sync successfully first, or configure this primary node's entry.","已清理 {done} 个,{fail} 个失败:{err}":"Cleaned up {done}, {fail} failed: {err}","已清理 {n} 个分享":({n:e})=>`Cleaned up ${e} ${Te(e,"share","shares")}`,已提交撤销:"Revoke submitted","已提交停止公开,等待托管设备收到同步":"Stop request submitted, waiting for the hosting device to sync","(已停用)":"(disabled)",已停止公开访问:"Public access stopped","已通过「{source}」创建私密链接,地址已复制":"Private link created via “{source}”, address copied","已重新生成访问链接并复制(内容不变)":"Access link regenerated and copied (content unchanged)","已重新生成访问链接并复制(内容为 {when} 的快照)":"Access link regenerated and copied (snapshot from {when})","已重新生成访问链接,新链接已复制(内容不变)":"Access link regenerated, new link copied (content unchanged)",永不过期:"Never expires",永久:"Permanent",用当前最新内容覆盖接收者看到的版本:"Overwrite what recipients see with the latest content",有效:"Active",有效期:"Expires","在文档、表格或站点里点「分享」即可创建链接。":"Click “Share” in a document, table or site to create a link.","站点页面与管理界面同源运行:站点内的脚本可以以你的身份读写整个工作区。只发布你信任的代码。":"Site pages run on the same origin as the admin UI: scripts inside the site can read and write the whole workspace as you. Only publish code you trust.","站点已上线,地址已复制":"Site is live, address copied",这类对象无法在这里重新分享:"This kind of item cannot be re-shared here",正在加载分享列表:"Loading shares","正在同步到目标设备;确认地址可访问后才会视为发布成功":"Syncing to the target device; publishing counts as done once the address is confirmed reachable",只读:"Read-only","至 {when}":"Until {when}",重试撤销:"Retry revoke",重新创建链接:"Re-create link",重新分享:"Share again",重新加载权限:"Reload permissions",准备中:"Preparing"};var qu={...Ru,...Au,...Du,...Ou,...Iu,...Cu,...Pu,...Nu};var Lu="mh-lang",qs=(e)=>e==="zh-CN"||e==="en";function Ls(e){if(!e||e.length===0)return"zh-CN";for(let t of e){if(!t)continue;if(/^zh\b/i.test(t))return"zh-CN";if(/^en\b/i.test(t))return"en"}return"en"}var nw=Lu;function ow(){try{return typeof localStorage<"u"?localStorage:null}catch{return null}}function iw(){let e=ow()?.getItem(nw);return qs(e)?e:"system"}function sw(){if(typeof navigator>"u")return"zh-CN";let e=navigator.languages?.length?navigator.languages:[navigator.language];return Ls(e)}function aw(){if(typeof location>"u")return null;let e=new URLSearchParams(location.search).get("lang");return qs(e)?e:null}var Yo=null,$s=null;function cw(){if(typeof globalThis.Bun<"u")return"zh-CN";let e=aw();if(e)return e;let t=iw();return t==="system"?sw():t}function $u(){if($s)return $s;if(!Yo)Yo=cw();return Yo}function Mu(e){$s=e,Yo=null}function lw(e,t){if(!t)return e;return e.replace(/\{(\w+)\}/g,(r,n)=>(n in t)?String(t[n]):r)}var uw="##";function dw(e,t,r){let n=e==="en"?qu[t]:void 0;if(typeof n==="function")return n(r??{});let o=t.indexOf(uw);return lw(n??(o<0?t:t.slice(0,o)),r)}function Tr(e,t){return dw($u(),e,t)}lt();Xn();Ti();An();Qn();var hm=(e)=>{let t=/^[a-z0-9+]+:\/\/([^/]+)/i.exec(e);return t?t[1]:e};function tS(e,t,r,n,o,s){let a=e.kind==="s3",c=a?n:r,p=Math.max(0,c-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??hm(e.url):hm(e.url)),freshness:!e.enabled?"disabled":e.lastStatus==="error"?"error":e.lastSuccessAt==null?"never":p>0?"behind":o-e.lastSuccessAt>s?"stale":"current",syncedAt:e.lastSuccessAt,error:e.lastStatus==="error"?e.lastError??null:null,acknowledgedSeq:e.pushCursor,highWaterSeq:c,lag:p,roles:m}}function dc(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)=>tS(a,e.blobFullNodes,e.globalHighWaterSeq,e.ownHighWaterSeq,n,o)).sort((a,c)=>Number(a.kind==="bucket")-Number(c.kind==="bucket")||r(a.freshness)-r(c.freshness)||a.label.localeCompare(c.label));return[t,...s]}function gm(e){let r=dc(e).filter((p)=>p.kind!=="self"&&p.freshness!=="disabled"),n=r.filter((p)=>p.syncedAt!=null&&p.acknowledgedSeq>=p.highWaterSeq),o=n.length?n.reduce((p,m)=>p==null||(m.syncedAt??0)<p?m.syncedAt:p,null):null,s=r.reduce((p,m)=>Math.max(p,m.lag),0),a=[];if(r.length===0)a.push({kind:"no_backup",placeUrl:null,placeLabel:null,message:null});for(let p of r)if(p.freshness==="error")a.push({kind:"peer_error",placeUrl:p.url,placeLabel:p.label,message:p.error});if(e.pendingBlobCount>0)a.push({kind:"pending_blobs",placeUrl:null,placeLabel:null,message:null});for(let p of r)if(p.freshness==="behind")a.push({kind:"behind",placeUrl:p.url,placeLabel:p.label,message:null});for(let p of r)if(p.freshness==="never")a.push({kind:"never_synced",placeUrl:p.url,placeLabel:p.label,message:null});for(let p of r)if(p.freshness==="stale")a.push({kind:"stale",placeUrl:p.url,placeLabel:p.label,message:null});let c={places:1+n.length,pendingBlobCount:e.pendingBlobCount,pendingBlobBytes:e.pendingBlobBytes,pendingChanges:s,oldestSyncedAt:o,issues:a};if(r.length===0)return{state:"no_backup",...c};if(r.some((p)=>p.freshness==="error"))return{state:"peer_error",...c};if(e.pendingBlobCount>0)return{state:"pending_blobs",...c};if(s>0)return{state:"unsynced_changes",...c};if(r.some((p)=>p.freshness==="never"))return{state:"syncing",...c};if(r.some((p)=>p.freshness==="stale"))return{state:"stale",...c};return{state:"healthy",...c}}Kt();Xn();An();function mm(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=Ft(e).filter((m)=>m.kind==="http"||m.kind==="s3").map((m)=>{let x=null,A;if(m.kind==="s3"&&m.config)try{let F=JSON.parse(m.config);x=F.bucket??null,A=F.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:A}}),c=Eu(e),p={selfNodeId:t,selfLabel:gl(e),peers:a,pendingBlobCount:c.length,pendingBlobBytes:c.reduce((m,x)=>m+x.size,0),blobFullNodes:Jn(e).fullNodes,globalHighWaterSeq:r.global_seq??0,ownHighWaterSeq:r.own_seq??0,staleAfterMs:s};return{state:gm(p),places:dc(p)}}lc();Kt();Dn();Eo();function _m(e,t){let r=We(e),n=wr(e,t,"revoked");if(n.audience==="public"&&!Vt(e,n.site_id).some((o)=>o.audience==="public"&&o.desired_state==="active"))Fi(e,n.site_id,{visibility:"private"});if(n.hosting==="device"&&n.target_ref===r)return Ct(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 Ct(e,{channelId:n.id,status:"cleanup_pending",lastError:"等待控制设备上线并应用撤销"}),{channel:n,needsReconcile:!1}}Xr();Xe();Xr();Ui();function Sm(e){return e.replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'")}function iS(e){let t=gc(e),r=mc(e),n=(s)=>_c(e,s);async function o(s,a){let c=await s.text().catch(()=>"");throw Error(`S3 ${a} failed: ${s.status} ${c.slice(0,200)}`)}return{async list(s,a,c){let p=[],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(c)x.searchParams.set("delimiter",c);if(m)x.searchParams.set("continuation-token",m);let A=await t.fetch(x.toString(),{method:"GET"});if(!A.ok)await o(A,"list");let F=await A.text(),X=/<Contents>([\s\S]*?)<\/Contents>/g,he;while(he=X.exec(F)){let _e=he[1],le=/<Key>([^<]+)<\/Key>/.exec(_e)?.[1];if(!le)continue;p.push({key:Sm(le),etag:/<ETag>([^<]*)<\/ETag>/.exec(_e)?.[1]})}if(c){let _e=/<CommonPrefixes>([\s\S]*?)<\/CommonPrefixes>/g;while(he=_e.exec(F)){let le=/<Prefix>([^<]+)<\/Prefix>/.exec(he[1])?.[1];if(le)p.push({key:Sm(le)})}}m=/<IsTruncated>true<\/IsTruncated>/.test(F)?/<NextContinuationToken>([^<]+)<\/NextContinuationToken>/.exec(F)?.[1]:void 0}while(m);return p},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,c){let p={};if(c?.contentType)p["content-type"]=c.contentType;if(c?.ifNoneMatch)p["if-none-match"]="*";if(c?.ifMatch)p["if-match"]=c.ifMatch;let m=await t.fetch(n(s),{method:"PUT",body:a,headers:Object.keys(p).length?p:void 0});if((c?.ifNoneMatch||c?.ifMatch)&&m.status===412)throw new H("conflict",`S3 conditional put failed (${c?.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")}}}tg(iS);var sS=Math.floor(167772160);function aS(e){if(e instanceof ArrayBuffer)return e;let t=new Uint8Array(e.byteLength);return t.set(e),t.buffer}async function cS(e){let t=await crypto.subtle.digest("SHA-256",aS(e));return[...new Uint8Array(t)].map((r)=>r.toString(16).padStart(2,"0")).join("")}async function yc(e,t){return(await cS(e)).slice(0,t.length)===t}var Bi=null;function lS(){if(Bi)return Bi;return Bi=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)}),Bi}function tn(e,t,r){return lS().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 bc(e){return tn("spool","readonly",(t)=>t.get(e))}async function km(){return(await tn("spool","readonly",(t)=>t.getAll())??[]).filter((t)=>!t.durable)}async function xm(e){await tn("spool","readwrite",(t)=>t.delete(e))}var Tm=(e)=>`/blob/${e}`;async function uS(e,t,r){let n=await tn("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 tn("meta","readwrite",(s)=>s.put(o))}async function Rm(e,t,r){await(await caches.open("mh-blob-v1")).put(Tm(e),new Response(t,{headers:{"content-type":r,"cache-control":"public, max-age=31536000, immutable"}})),await uS(e,t.byteLength,r),await dS()}async function dS(){let e=await tn("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<=sS)break;await r.delete(Tm(o.hash)),await tn("meta","readwrite",(s)=>s.delete(o.hash)),t-=o.size}}ki();zr();kr();Ur();vn();lt();vn();kr();Xe();Wn();var fS=1500;function wc(e){return Number(e.slice(0,15))}function Pn(e){return new Date(wc(e)).toISOString()}function rn(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 vc(e){return rn(e).kind}function Nn(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||wc(n.hlc)-wc(o.hlc)>fS))t.push(r),r=[];r.push(n)}if(r.length)t.push(r);return t}function Jt(e){return e!==null&&e!=="0"&&e!=="false"&&e!=="null"}function ji(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 Wi(e,t,r){return e.query(`SELECT ${_t} FROM crdt_changes WHERE dataset = ? AND row_id = ? ORDER BY hlc`).all(t,r)}function pS(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 Am(e,t){let r=Sl(e,t);if(r)return r;let n=pS(e,t),o=n.map(()=>"?").join(","),s=n.length?` OR (dataset = 'doc_blocks' AND row_id IN (${o}))`:"",a=e.query(`SELECT ${_t} FROM crdt_changes
546
546
  WHERE (dataset = 'documents' AND row_id = ?)${s}
547
- ORDER BY hlc`).all(t,...n);return vl(e,t,a,n)}function k_(e,t){let r=x_(e,t);if(r.revisions)return r.revisions.slice();let n=r.changes;if(!n.length)throw new Z("not_found",`no such document: ${t}`);let o=new Map,s=[];for(let a of Cn(n)){let c=new Set,p=new Set,m=new Map,x=!1,O=!1,F=0;for(let le of a)if(le.dataset==="documents"){if(m.set(le.col,le.value),le.col==="created_hlc")x=!0;else if(le.col==="__deleted")O=Vt(le.value)}else if(F++,le.col==="__deleted"&&Vt(le.value))p.add(le.row_id);else if(le.col==="text")c.add(le.row_id);let X=!1,he=0;for(let[le,Oe]of m){let Be=!o.has(le)||o.get(le)!==Oe;if(o.set(le,Oe),!Be)continue;if(he++,le==="title")X=!0}if(he===0&&F===0)continue;let be=a[a.length-1];s.push({version:be.hlc,at:In(be.hlc),node_id:be.node_id,kind:wc(be.txn),actor:Yr(be.txn).actor,changes:a.length,created:x,deleted:O,title_changed:X,blocks_changed:c.size,blocks_deleted:p.size})}return r.revisions=s.reverse(),r.revisions.slice()}function vc(e,t,r){if(!r)throw new Z("invalid_input","missing version cutoff");let n=x_(e,t),o=n.states.get(r);if(o)return{...o};let s=n.changes.filter((F)=>F.hlc<=r);if(!s.length)throw new Z("not_found",`no version of document ${t} at or before ${r}`);let a=Ui(s.filter((F)=>F.dataset==="documents"),r),c=(F)=>{let X=a.get(F);return X?.value==null?void 0:JSON.parse(X.value)},p=new Map;for(let F of s){if(F.dataset!=="doc_blocks")continue;(p.get(F.row_id)??p.set(F.row_id,[]).get(F.row_id)).push(F)}let m=[];for(let[F,X]of p){let he=Ui(X,r),be=(Oe)=>{let Be=he.get(Oe);return Be?.value==null?void 0:JSON.parse(Be.value)};if(be("doc_id")!==t)continue;if(he.get("__deleted")&&Vt(he.get("__deleted").value))continue;let le=be("text");if(typeof le!=="string"||!le)continue;m.push({id:F,text:le,order_key:be("order_key")??null,blankAfter:be("blank_after")??0})}m.sort((F,X)=>{if(F.order_key!==X.order_key){if(F.order_key===null)return-1;if(X.order_key===null)return 1;return F.order_key<X.order_key?-1:1}return F.id<X.id?-1:1});let x=p.size?$r(m):c("body")??"",O={id:t,title:c("title")??"",body:x,deleted:a.get("__deleted")?Vt(a.get("__deleted").value):!1,version:s[s.length-1].hlc};return El(n,r,O),{...O}}var T_=Fe(function(t,r,n,o={}){let s=ot(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&&qt(t,r)!==o.ifMatch)throw new Z("stale",`stale: document changed since ${o.ifMatch}; re-read first`);let a=vc(t,r,n);if(a.deleted)throw new Z("invalid_input","target version is a deleted state; use doc delete instead");let c=!s;if(!s)_e(t,"documents",r,"__deleted",0),s=ot(t,r);let p={};if(a.title!==s.title)p.title=a.title;if(a.body!==(s.body??""))p.body=a.body;if(Object.keys(p).length)Ko(t,r,p);return{id:r,changed:Object.keys(p).length>0||c,restored:a.version,version:qt(t,r),undeleted:c}},"revert"),Bi=new Set(["database_id","created_hlc","order_key","__deleted"]);function R_(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=Vt(a.value);else if(a.col==="order_key")o=!0;else if(!Bi.has(a.col))t.add(a.col);let s=e[e.length-1];return{version:s.hlc,at:In(s.hlc),node_id:s.node_id,kind:wc(s.txn),actor:Yr(s.txn).actor,changes:e.length,created:r,deleted:n,fields:[...t],moved:o}}function A_(e,t){let r=ji(e,"records",t);if(!r.length)throw new Z("not_found",`no such record: ${t}`);return Cn(r).map(R_).reverse()}function D_(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 ${mt} FROM crdt_changes
547
+ ORDER BY hlc`).all(t,...n);return kl(e,t,a,n)}function Dm(e,t){let r=Am(e,t);if(r.revisions)return r.revisions.slice();let n=r.changes;if(!n.length)throw new H("not_found",`no such document: ${t}`);let o=new Map,s=[];for(let a of Nn(n)){let c=new Set,p=new Set,m=new Map,x=!1,A=!1,F=0;for(let le of a)if(le.dataset==="documents"){if(m.set(le.col,le.value),le.col==="created_hlc")x=!0;else if(le.col==="__deleted")A=Jt(le.value)}else if(F++,le.col==="__deleted"&&Jt(le.value))p.add(le.row_id);else if(le.col==="text")c.add(le.row_id);let X=!1,he=0;for(let[le,Oe]of m){let Be=!o.has(le)||o.get(le)!==Oe;if(o.set(le,Oe),!Be)continue;if(he++,le==="title")X=!0}if(he===0&&F===0)continue;let _e=a[a.length-1];s.push({version:_e.hlc,at:Pn(_e.hlc),node_id:_e.node_id,kind:vc(_e.txn),actor:rn(_e.txn).actor,changes:a.length,created:x,deleted:A,title_changed:X,blocks_changed:c.size,blocks_deleted:p.size})}return r.revisions=s.reverse(),r.revisions.slice()}function Ec(e,t,r){if(!r)throw new H("invalid_input","missing version cutoff");let n=Am(e,t),o=n.states.get(r);if(o)return{...o};let s=n.changes.filter((F)=>F.hlc<=r);if(!s.length)throw new H("not_found",`no version of document ${t} at or before ${r}`);let a=ji(s.filter((F)=>F.dataset==="documents"),r),c=(F)=>{let X=a.get(F);return X?.value==null?void 0:JSON.parse(X.value)},p=new Map;for(let F of s){if(F.dataset!=="doc_blocks")continue;(p.get(F.row_id)??p.set(F.row_id,[]).get(F.row_id)).push(F)}let m=[];for(let[F,X]of p){let he=ji(X,r),_e=(Oe)=>{let Be=he.get(Oe);return Be?.value==null?void 0:JSON.parse(Be.value)};if(_e("doc_id")!==t)continue;if(he.get("__deleted")&&Jt(he.get("__deleted").value))continue;let le=_e("text");if(typeof le!=="string"||!le)continue;m.push({id:F,text:le,order_key:_e("order_key")??null,blankAfter:_e("blank_after")??0})}m.sort((F,X)=>{if(F.order_key!==X.order_key){if(F.order_key===null)return-1;if(X.order_key===null)return 1;return F.order_key<X.order_key?-1:1}return F.id<X.id?-1:1});let x=p.size?Mr(m):c("body")??"",A={id:t,title:c("title")??"",body:x,deleted:a.get("__deleted")?Jt(a.get("__deleted").value):!1,version:s[s.length-1].hlc};return xl(n,r,A),{...A}}var Om=Fe(function(t,r,n,o={}){let s=ot(t,r);if(!s&&!t.query("SELECT 1 AS x FROM documents WHERE id = ?").get(r))throw new H("not_found",`no such document: ${r}`);if(o.ifMatch!==void 0&&$t(t,r)!==o.ifMatch)throw new H("stale",`stale: document changed since ${o.ifMatch}; re-read first`);let a=Ec(t,r,n);if(a.deleted)throw new H("invalid_input","target version is a deleted state; use doc delete instead");let c=!s;if(!s)me(t,"documents",r,"__deleted",0),s=ot(t,r);let p={};if(a.title!==s.title)p.title=a.title;if(a.body!==(s.body??""))p.body=a.body;if(Object.keys(p).length)Jo(t,r,p);return{id:r,changed:Object.keys(p).length>0||c,restored:a.version,version:$t(t,r),undeleted:c}},"revert"),Hi=new Set(["database_id","created_hlc","order_key","__deleted"]);function Im(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=Jt(a.value);else if(a.col==="order_key")o=!0;else if(!Hi.has(a.col))t.add(a.col);let s=e[e.length-1];return{version:s.hlc,at:Pn(s.hlc),node_id:s.node_id,kind:vc(s.txn),actor:rn(s.txn).actor,changes:e.length,created:r,deleted:n,fields:[...t],moved:o}}function Cm(e,t){let r=Wi(e,"records",t);if(!r.length)throw new H("not_found",`no such record: ${t}`);return Nn(r).map(Im).reverse()}function Pm(e,t,r={}){if(!e.query("SELECT 1 AS x FROM databases WHERE id = ?").get(t))throw new H("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 ${_t} FROM crdt_changes
548
548
  WHERE dataset = 'records' AND row_id IN (SELECT id FROM records WHERE database_id = ?)
549
- ORDER BY row_id, hlc`).all(t),s=[],a=0;for(let c=1;c<=o.length;c++){if(c!==o.length&&o[c].row_id===o[a].row_id)continue;let p=o[a].row_id,m=new Map;for(let x of Cn(o.slice(a,c))){let O=new Set;for(let he of x)if(!Bi.has(he.col))O.add(he.col);let F=new Map;for(let he of O)if(m.has(he))F.set(he,m.get(he));for(let he of x){if(Bi.has(he.col))continue;if(he.value===null)m.delete(he.col);else m.set(he.col,JSON.parse(he.value))}let X=[];for(let he of O){let be={prop:he};if(F.has(he))be.before=F.get(he);if(m.has(he))be.after=m.get(he);X.push(be)}s.push({...R_(x),record_id:p,record_title:n&&m.has(n)?String(m.get(n)??""):null,diffs:X})}a=c}return s.sort((c,p)=>c.version<p.version?1:-1),s.slice(0,r.limit??100)}function Ec(e,t,r){if(!r)throw new Z("invalid_input","missing version cutoff");let n=ji(e,"records",t).filter((c)=>c.hlc<=r);if(!n.length)throw new Z("not_found",`no version of record ${t} at or before ${r}`);let o=Ui(n,r),s={};for(let[c,p]of o){if(Bi.has(c))continue;if(p.value===null)continue;s[c]=JSON.parse(p.value)}let a=o.get("database_id");return{id:t,database_id:a?.value==null?null:JSON.parse(a.value),deleted:o.get("__deleted")?Vt(o.get("__deleted").value):!1,data:s,version:n[n.length-1].hlc}}var O_=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=Ec(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?Ft(t,o.database_id).map((x)=>x.id):[]),c=JSON.parse(o.data||"{}"),p=[];for(let x of a){let O=Object.hasOwn(s.data,x),F=Object.hasOwn(c,x);if(O&&(!F||JSON.stringify(s.data[x])!==JSON.stringify(c[x])))_e(t,"records",r,x,s.data[x]),p.push(x);else if(!O&&F)_e(t,"records",r,x,void 0),p.push(x)}let m=o.__deleted!==0;if(m)_e(t,"records",r,"__deleted",0);return{id:r,changed:p.length>0||m,fields:p,undeleted:m,restored:s.version}},"revert"),I_=["name","type","config","position"];function C_(e,t){let r=ji(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 Cn(r).map((o)=>{let s=new Set,a=!1,c=!1;for(let m of o)if(m.col==="database_id")a=!0;else if(m.col==="__deleted")c=Vt(m.value);else if(I_.includes(m.col))s.add(m.col);let p=o[o.length-1];return{version:p.hlc,at:In(p.hlc),node_id:p.node_id,kind:wc(p.txn),actor:Yr(p.txn).actor,changes:o.length,created:a,deleted:c,fields:[...s],cells_cleared:p.txn?n.get(p.txn)??0:0}}).reverse()}function rS(e,t,r){if(!r)throw new Z("invalid_input","missing version cutoff");let n=ji(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=Ui(n,r),s=(a)=>{let c=o.get(a);return c?.value==null?void 0:JSON.parse(c.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")?Vt(o.get("__deleted").value):!1,version:n[n.length-1].hlc}}var P_=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=rS(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},c={name:s.name,type:s.type,config:s.config,position:s.position},p=[];for(let le of I_)if(JSON.stringify(c[le]??null)!==JSON.stringify(a[le]??null))_e(t,"properties",r,le,c[le]),p.push(le);let m=o.__deleted!==0;if(m)_e(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((le)=>le.txn)),O=t.query("SELECT row_id, hlc, value, txn FROM crdt_changes WHERE dataset = 'records' AND col = ? ORDER BY row_id, hlc").all(r),F=(le)=>le!==null&&(x.has(le)||Yr(le).kind==="repair"),X=0,he=0,be=0;while(be<O.length){let le=O[be].row_id,Oe=O[be],Be=null;for(;be<O.length&&O[be].row_id===le;be++)if(Oe=O[be],!F(Oe.txn))Be=Oe;if(Oe.hlc<=n)continue;if(!F(Oe.txn)){he++;continue}let Me=Be?Be.value:null;if(Me===Oe.value)continue;_e(t,"records",le,r,Me===null?void 0:JSON.parse(Me)),X++}return{id:r,changed:p.length>0||m||X>0,fields:p,restored_cells:X,skipped_cells:he,undeleted:m,restored:s.version}},"revert");function N_(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:In(o.hlc),node_id:o.node_id,value:o.value===null?void 0:JSON.parse(o.value),cleared:o.value===null}))}ct();Xe();var nS={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}},Hi=(e)=>Object.entries(nS).filter(([,t])=>e(t)).map(([t])=>t),OI=Hi((e)=>e.synced),II=Hi((e)=>e.tier==="content"),q_=Hi((e)=>e.tier==="system"),CI=Hi((e)=>e.tier==="local");function L_(e,t){if(e==="records")return hs.has(t);return t==="created_hlc"||t==="__deleted"}function $_(){let e=[...Mo,...q_];return{sql:e.map(()=>"dataset != ?"),params:e}}function Sc(e,t,r){let n=$_(),o=["txn = ?",...n.sql],s=[t,...n.params];if(r)o.push("hlc < ?"),s.push(r);return e.query(`SELECT ${mt} FROM crdt_changes WHERE ${o.join(" AND ")} ORDER BY hlc`).all(...s)}function M_(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 oS(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 iS(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?oS(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:M_(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 F_(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 z_(e,t,r){let n=new Map,o=(m,x)=>{let O=m+"\x00"+x,F=n.get(O);if(!F)F={dataset:m,id:x,created:!1,deleted:!1,fields:new Set,blocksChanged:new Set,blocksDeleted:new Set},n.set(O,F);return F};for(let m of t){if(m.dataset==="doc_blocks"){let O=F_(e,t,m.row_id),F=O?o("documents",O):o("doc_blocks",m.row_id);if(m.col==="__deleted"&&Vt(m.value))F.blocksDeleted.add(m.row_id);else F.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=Vt(m.value);if(!L_(m.dataset,m.col))x.fields.add(m.col)}let s=[...n.values()].map((m)=>{let{label:x,database_id:O}=iS(e,m.dataset,m.id,r);return{dataset:m.dataset,id:m.id,label:x,database_id:O,database_label:m.dataset==="databases"?null:M_(e,O,r),created:m.created,deleted:m.deleted,fields:m.fields.size,blocks_changed:[...m.blocksChanged].filter((F)=>!m.blocksDeleted.has(F)).length,blocks_deleted:m.blocksDeleted.size}}),a=t[t.length-1],{actor:c,kind:p}=Yr(a.txn);return{version:a.hlc,at:In(a.hlc),node_id:a.node_id,kind:p,actor:c,txn:a.txn,changes:t.length,entities:s}}function U_(e,t={}){let r=Math.max(1,Math.min(t.limit??50,200));if(t.actor!==void 0&&!Rl.test(t.actor))throw new Z("invalid_input",`invalid actor tag: ${t.actor}`);let n=Math.min(Math.max(r*40,800),8000),o=$_(),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 c=e.query(`SELECT ${mt} FROM crdt_changes
549
+ ORDER BY row_id, hlc`).all(t),s=[],a=0;for(let c=1;c<=o.length;c++){if(c!==o.length&&o[c].row_id===o[a].row_id)continue;let p=o[a].row_id,m=new Map;for(let x of Nn(o.slice(a,c))){let A=new Set;for(let he of x)if(!Hi.has(he.col))A.add(he.col);let F=new Map;for(let he of A)if(m.has(he))F.set(he,m.get(he));for(let he of x){if(Hi.has(he.col))continue;if(he.value===null)m.delete(he.col);else m.set(he.col,JSON.parse(he.value))}let X=[];for(let he of A){let _e={prop:he};if(F.has(he))_e.before=F.get(he);if(m.has(he))_e.after=m.get(he);X.push(_e)}s.push({...Im(x),record_id:p,record_title:n&&m.has(n)?String(m.get(n)??""):null,diffs:X})}a=c}return s.sort((c,p)=>c.version<p.version?1:-1),s.slice(0,r.limit??100)}function Sc(e,t,r){if(!r)throw new H("invalid_input","missing version cutoff");let n=Wi(e,"records",t).filter((c)=>c.hlc<=r);if(!n.length)throw new H("not_found",`no version of record ${t} at or before ${r}`);let o=ji(n,r),s={};for(let[c,p]of o){if(Hi.has(c))continue;if(p.value===null)continue;s[c]=JSON.parse(p.value)}let a=o.get("database_id");return{id:t,database_id:a?.value==null?null:JSON.parse(a.value),deleted:o.get("__deleted")?Jt(o.get("__deleted").value):!1,data:s,version:n[n.length-1].hlc}}var Nm=Fe(function(t,r,n){let o=t.query("SELECT database_id, data, __deleted FROM records WHERE id = ?").get(r);if(!o)throw new H("not_found",`no such record: ${r}`);let s=Sc(t,r,n);if(s.deleted)throw new H("invalid_input","target version is a deleted state; use record delete instead");let a=new Set(o.database_id?Lt(t,o.database_id).map((x)=>x.id):[]),c=JSON.parse(o.data||"{}"),p=[];for(let x of a){let A=Object.hasOwn(s.data,x),F=Object.hasOwn(c,x);if(A&&(!F||JSON.stringify(s.data[x])!==JSON.stringify(c[x])))me(t,"records",r,x,s.data[x]),p.push(x);else if(!A&&F)me(t,"records",r,x,void 0),p.push(x)}let m=o.__deleted!==0;if(m)me(t,"records",r,"__deleted",0);return{id:r,changed:p.length>0||m,fields:p,undeleted:m,restored:s.version}},"revert"),qm=["name","type","config","position"];function Lm(e,t){let r=Wi(e,"properties",t);if(!r.length)throw new H("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 Nn(r).map((o)=>{let s=new Set,a=!1,c=!1;for(let m of o)if(m.col==="database_id")a=!0;else if(m.col==="__deleted")c=Jt(m.value);else if(qm.includes(m.col))s.add(m.col);let p=o[o.length-1];return{version:p.hlc,at:Pn(p.hlc),node_id:p.node_id,kind:vc(p.txn),actor:rn(p.txn).actor,changes:o.length,created:a,deleted:c,fields:[...s],cells_cleared:p.txn?n.get(p.txn)??0:0}}).reverse()}function hS(e,t,r){if(!r)throw new H("invalid_input","missing version cutoff");let n=Wi(e,"properties",t).filter((a)=>a.hlc<=r);if(!n.length)throw new H("not_found",`no version of property ${t} at or before ${r}`);let o=ji(n,r),s=(a)=>{let c=o.get(a);return c?.value==null?void 0:JSON.parse(c.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")?Jt(o.get("__deleted").value):!1,version:n[n.length-1].hlc}}var $m=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 H("not_found",`no such property: ${r}`);let s=hS(t,r,n);if(s.deleted)throw new H("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},c={name:s.name,type:s.type,config:s.config,position:s.position},p=[];for(let le of qm)if(JSON.stringify(c[le]??null)!==JSON.stringify(a[le]??null))me(t,"properties",r,le,c[le]),p.push(le);let m=o.__deleted!==0;if(m)me(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((le)=>le.txn)),A=t.query("SELECT row_id, hlc, value, txn FROM crdt_changes WHERE dataset = 'records' AND col = ? ORDER BY row_id, hlc").all(r),F=(le)=>le!==null&&(x.has(le)||rn(le).kind==="repair"),X=0,he=0,_e=0;while(_e<A.length){let le=A[_e].row_id,Oe=A[_e],Be=null;for(;_e<A.length&&A[_e].row_id===le;_e++)if(Oe=A[_e],!F(Oe.txn))Be=Oe;if(Oe.hlc<=n)continue;if(!F(Oe.txn)){he++;continue}let Me=Be?Be.value:null;if(Me===Oe.value)continue;me(t,"records",le,r,Me===null?void 0:JSON.parse(Me)),X++}return{id:r,changed:p.length>0||m||X>0,fields:p,restored_cells:X,skipped_cells:he,undeleted:m,restored:s.version}},"revert");function Mm(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:Pn(o.hlc),node_id:o.node_id,value:o.value===null?void 0:JSON.parse(o.value),cleared:o.value===null}))}lt();Xe();var gS={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}},Zi=(e)=>Object.entries(gS).filter(([,t])=>e(t)).map(([t])=>t),ZI=Zi((e)=>e.synced),KI=Zi((e)=>e.tier==="content"),Fm=Zi((e)=>e.tier==="system"),GI=Zi((e)=>e.tier==="local");function zm(e,t){if(e==="records")return ms.has(t);return t==="created_hlc"||t==="__deleted"}function Um(){let e=[...zo,...Fm];return{sql:e.map(()=>"dataset != ?"),params:e}}function kc(e,t,r){let n=Um(),o=["txn = ?",...n.sql],s=[t,...n.params];if(r)o.push("hlc < ?"),s.push(r);return e.query(`SELECT ${_t} FROM crdt_changes WHERE ${o.join(" AND ")} ORDER BY hlc`).all(...s)}function Bm(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 mS(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 _S(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?mS(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:Bm(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 jm(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 Hm(e,t,r){let n=new Map,o=(m,x)=>{let A=m+"\x00"+x,F=n.get(A);if(!F)F={dataset:m,id:x,created:!1,deleted:!1,fields:new Set,blocksChanged:new Set,blocksDeleted:new Set},n.set(A,F);return F};for(let m of t){if(m.dataset==="doc_blocks"){let A=jm(e,t,m.row_id),F=A?o("documents",A):o("doc_blocks",m.row_id);if(m.col==="__deleted"&&Jt(m.value))F.blocksDeleted.add(m.row_id);else F.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=Jt(m.value);if(!zm(m.dataset,m.col))x.fields.add(m.col)}let s=[...n.values()].map((m)=>{let{label:x,database_id:A}=_S(e,m.dataset,m.id,r);return{dataset:m.dataset,id:m.id,label:x,database_id:A,database_label:m.dataset==="databases"?null:Bm(e,A,r),created:m.created,deleted:m.deleted,fields:m.fields.size,blocks_changed:[...m.blocksChanged].filter((F)=>!m.blocksDeleted.has(F)).length,blocks_deleted:m.blocksDeleted.size}}),a=t[t.length-1],{actor:c,kind:p}=rn(a.txn);return{version:a.hlc,at:Pn(a.hlc),node_id:a.node_id,kind:p,actor:c,txn:a.txn,changes:t.length,entities:s}}function Wm(e,t={}){let r=Math.max(1,Math.min(t.limit??50,200));if(t.actor!==void 0&&!Ol.test(t.actor))throw new H("invalid_input",`invalid actor tag: ${t.actor}`);let n=Math.min(Math.max(r*40,800),8000),o=Um(),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 c=e.query(`SELECT ${_t} FROM crdt_changes
550
550
  ${s.length?"WHERE "+s.join(" AND "):""}
551
- ORDER BY hlc DESC LIMIT ?`).all(...a,n),p=c.length<n;c.reverse();let m=Cn(c);if(!p&&m.length>0){let le=m[0][0].txn;if(le!==null)m[0]=Sc(e,le,t.before);else if(m.length>1)m=m.slice(1)}let x={dbNames:new Map,titleProps:new Map},O=m.reverse(),F=O.slice(0,r),X=F.map((le)=>z_(e,le,x)),be=(!p||O.length>r)&&F.length?F[F.length-1][0].hlc:null;return{entries:X,next:be}}function B_(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 sS(e,t,r){if(t!=="records")return r;return e.query("SELECT name FROM properties WHERE id = ?").get(r)?.name??r}function j_(e,t){let r=Sc(e,t);if(!r.length)throw new Z("not_found",`no change group: ${t}`);let o=z_(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 c=o.entities.map((m)=>({...m,diffs:[],block_diffs:[]})),p=new Map(c.map((m)=>[m.dataset+"\x00"+m.id,m]));for(let[m,x]of a){let O=s.get(m),F=(X)=>{let he={col:x.dataset==="doc_blocks"?x.row_id:x.col,label:X},be=B_(e,x.dataset,x.row_id,x.col,O.hlc);if(be&&be.value!==null)he.before=JSON.parse(be.value);if(x.value!==null)he.after=JSON.parse(x.value);return he};if(x.dataset==="doc_blocks"){if(x.col!=="text")continue;let X=F_(e,r,x.row_id);p.get(X?"documents\x00"+X:"doc_blocks\x00"+x.row_id)?.block_diffs.push(F("block"));continue}if(L_(x.dataset,x.col))continue;p.get(x.dataset+"\x00"+x.row_id)?.diffs.push(F(sS(e,x.dataset,x.col)))}return{...o,entities:c}}var H_=Fe(function(t,r){let n=Sc(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,O=o.get(x);if(!O)o.set(x,O=[]);O.push(m)}let s=0,a=0,c=0,p=0;for(let m of o.values()){let{dataset:x,row_id:O}=m[0],F=m[0].hlc;if(!t.query("SELECT 1 AS x FROM crdt_changes WHERE dataset = ? AND row_id = ? AND hlc < ? LIMIT 1").get(x,O,F)){if(t.query("SELECT 1 AS x FROM crdt_changes WHERE dataset = ? AND row_id = ? AND txn IS NOT ? LIMIT 1").get(x,O,r)){p++;continue}let le=[...m].reverse().find((Oe)=>Oe.col==="__deleted");if(le&&Vt(le.value))continue;_e(t,x,O,"__deleted",1),c++;continue}let he=new Map;for(let be of m)if(!he.has(be.col))he.set(be.col,be);for(let[be,le]of he){let Oe=t.query("SELECT value, txn FROM crdt_changes WHERE dataset = ? AND row_id = ? AND col = ? ORDER BY hlc DESC LIMIT 1").get(x,O,be);if(Oe.txn!==r){a++;continue}let Be=B_(t,x,O,be,le.hlc),Me=Be===void 0?be==="__deleted"?0:void 0:Be.value===null?void 0:JSON.parse(Be.value);if((Me===void 0?null:JSON.stringify(Me))===Oe.value)continue;_e(t,x,O,be,Me),s++}}return{txn:r,changed:s>0||c>0,restored_registers:s,skipped_registers:a,removed_rows:c,skipped_rows:p}},"revert");ct();Sr();qo();Wt();jn();var W_=[{srcTable:"properties",fk:"database_id",tgtTable:"databases",fix:"tombstone-src"},{srcTable:"records",fk:"database_id",tgtTable:"databases",fix:"tombstone-src"},{srcTable:"documents",fk:"database_id",tgtTable:"databases",fix:"null-fk"},{srcTable:"documents",fk:"parent_id",tgtTable:"documents",fix:"null-fk"},{srcTable:"doc_blocks",fk:"doc_id",tgtTable:"documents",fix:"tombstone-src"},{srcTable:"site_files",fk:"site_id",tgtTable:"sites",fix:"tombstone-src"}];function Z_(e,t){return e.query(`SELECT s.id AS id, s.${t.fk} AS ref FROM ${t.srcTable} s
551
+ ORDER BY hlc DESC LIMIT ?`).all(...a,n),p=c.length<n;c.reverse();let m=Nn(c);if(!p&&m.length>0){let le=m[0][0].txn;if(le!==null)m[0]=kc(e,le,t.before);else if(m.length>1)m=m.slice(1)}let x={dbNames:new Map,titleProps:new Map},A=m.reverse(),F=A.slice(0,r),X=F.map((le)=>Hm(e,le,x)),_e=(!p||A.length>r)&&F.length?F[F.length-1][0].hlc:null;return{entries:X,next:_e}}function Zm(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 yS(e,t,r){if(t!=="records")return r;return e.query("SELECT name FROM properties WHERE id = ?").get(r)?.name??r}function Km(e,t){let r=kc(e,t);if(!r.length)throw new H("not_found",`no change group: ${t}`);let o=Hm(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 c=o.entities.map((m)=>({...m,diffs:[],block_diffs:[]})),p=new Map(c.map((m)=>[m.dataset+"\x00"+m.id,m]));for(let[m,x]of a){let A=s.get(m),F=(X)=>{let he={col:x.dataset==="doc_blocks"?x.row_id:x.col,label:X},_e=Zm(e,x.dataset,x.row_id,x.col,A.hlc);if(_e&&_e.value!==null)he.before=JSON.parse(_e.value);if(x.value!==null)he.after=JSON.parse(x.value);return he};if(x.dataset==="doc_blocks"){if(x.col!=="text")continue;let X=jm(e,r,x.row_id);p.get(X?"documents\x00"+X:"doc_blocks\x00"+x.row_id)?.block_diffs.push(F("block"));continue}if(zm(x.dataset,x.col))continue;p.get(x.dataset+"\x00"+x.row_id)?.diffs.push(F(yS(e,x.dataset,x.col)))}return{...o,entities:c}}var Gm=Fe(function(t,r){let n=kc(t,r);if(!n.length)throw new H("not_found",`no change group: ${r}`);let o=new Map;for(let m of n){let x=m.dataset+"\x00"+m.row_id,A=o.get(x);if(!A)o.set(x,A=[]);A.push(m)}let s=0,a=0,c=0,p=0;for(let m of o.values()){let{dataset:x,row_id:A}=m[0],F=m[0].hlc;if(!t.query("SELECT 1 AS x FROM crdt_changes WHERE dataset = ? AND row_id = ? AND hlc < ? LIMIT 1").get(x,A,F)){if(t.query("SELECT 1 AS x FROM crdt_changes WHERE dataset = ? AND row_id = ? AND txn IS NOT ? LIMIT 1").get(x,A,r)){p++;continue}let le=[...m].reverse().find((Oe)=>Oe.col==="__deleted");if(le&&Jt(le.value))continue;me(t,x,A,"__deleted",1),c++;continue}let he=new Map;for(let _e of m)if(!he.has(_e.col))he.set(_e.col,_e);for(let[_e,le]of he){let Oe=t.query("SELECT value, txn FROM crdt_changes WHERE dataset = ? AND row_id = ? AND col = ? ORDER BY hlc DESC LIMIT 1").get(x,A,_e);if(Oe.txn!==r){a++;continue}let Be=Zm(t,x,A,_e,le.hlc),Me=Be===void 0?_e==="__deleted"?0:void 0:Be.value===null?void 0:JSON.parse(Be.value);if((Me===void 0?null:JSON.stringify(Me))===Oe.value)continue;me(t,x,A,_e,Me),s++}}return{txn:r,changed:s>0||c>0,restored_registers:s,skipped_registers:a,removed_rows:c,skipped_rows:p}},"revert");lt();kr();$o();Kt();Wn();var Vm=[{srcTable:"properties",fk:"database_id",tgtTable:"databases",fix:"tombstone-src"},{srcTable:"records",fk:"database_id",tgtTable:"databases",fix:"tombstone-src"},{srcTable:"documents",fk:"database_id",tgtTable:"databases",fix:"null-fk"},{srcTable:"documents",fk:"parent_id",tgtTable:"documents",fix:"null-fk"},{srcTable:"doc_blocks",fk:"doc_id",tgtTable:"documents",fix:"tombstone-src"},{srcTable:"site_files",fk:"site_id",tgtTable:"sites",fix:"tombstone-src"}];function Jm(e,t){return e.query(`SELECT s.id AS id, s.${t.fk} AS ref FROM ${t.srcTable} s
552
552
  JOIN ${t.tgtTable} t ON t.id = s.${t.fk} AND t.__deleted = 1
553
553
  WHERE s.__deleted = 0 AND s.${t.fk} IS NOT NULL
554
- ORDER BY s.id`).all()}function aS(e){let t=[];for(let r of W_)for(let n of Z_(e,r))t.push({category:"broken_ref",entity:r.srcTable,id:n.id,detail:`${r.fk} → deleted ${r.tgtTable} ${n.ref} (${r.fix==="tombstone-src"?"tombstone":`clear ${r.fk}`})`,fixable:!0});return t}function cS(e){let t=0;for(let r of W_)for(let n of Z_(e,r)){if(r.fix==="tombstone-src")_e(e,r.srcTable,n.id,"__deleted",1);else _e(e,r.srcTable,n.id,r.fk,null);t++}return t}function G_(e){return e.query(`SELECT r.id AS rec, j.key AS prop
554
+ ORDER BY s.id`).all()}function bS(e){let t=[];for(let r of Vm)for(let n of Jm(e,r))t.push({category:"broken_ref",entity:r.srcTable,id:n.id,detail:`${r.fk} → deleted ${r.tgtTable} ${n.ref} (${r.fix==="tombstone-src"?"tombstone":`clear ${r.fk}`})`,fixable:!0});return t}function wS(e){let t=0;for(let r of Vm)for(let n of Jm(e,r)){if(r.fix==="tombstone-src")me(e,r.srcTable,n.id,"__deleted",1);else me(e,r.srcTable,n.id,r.fk,null);t++}return t}function Xm(e){return e.query(`SELECT r.id AS rec, j.key AS prop
555
555
  FROM records r, json_each(coalesce(r.data, '{}')) j
556
556
  JOIN properties p ON p.id = j.key AND p.__deleted = 1
557
557
  WHERE r.__deleted = 0
558
- ORDER BY r.id, j.key`).all()}function lS(e){return G_(e).map((t)=>({category:"orphan_cell",entity:"records",id:t.rec,detail:`cell for deleted property ${t.prop}`,fixable:!0}))}function uS(e){let t=G_(e);for(let r of t)_e(e,"records",r.rec,r.prop,void 0);return t.length}function K_(e){let t=e.query("SELECT id, type FROM properties WHERE __deleted = 0 AND type IN ('relation', 'doc') ORDER BY id").all(),r=[];for(let n of t){let o=n.type==="relation"?"records":"documents",s=n.id.replace(/'/g,"''"),a=e.query(`SELECT r.id AS rec, j.value AS dead
558
+ ORDER BY r.id, j.key`).all()}function vS(e){return Xm(e).map((t)=>({category:"orphan_cell",entity:"records",id:t.rec,detail:`cell for deleted property ${t.prop}`,fixable:!0}))}function ES(e){let t=Xm(e);for(let r of t)me(e,"records",r.rec,r.prop,void 0);return t.length}function Qm(e){let t=e.query("SELECT id, type FROM properties WHERE __deleted = 0 AND type IN ('relation', 'doc') ORDER BY id").all(),r=[];for(let n of t){let o=n.type==="relation"?"records":"documents",s=n.id.replace(/'/g,"''"),a=e.query(`SELECT r.id AS rec, j.value AS dead
559
559
  FROM records r, json_each(r.data -> '${s}') j
560
560
  JOIN ${o} t ON t.id = j.value AND t.__deleted = 1
561
561
  WHERE r.__deleted = 0 AND json_type(r.data -> '${s}') = 'array'
562
- ORDER BY r.id, j.value`).all(),c=null;for(let p of a){if(!c||c.rec!==p.rec)c={rec:p.rec,prop:n.id,tgtTable:o,dead:[]},r.push(c);c.dead.push(p.dead)}}return r}function dS(e){return K_(e).map((t)=>({category:"dead_cell_ref",entity:"records",id:t.rec,detail:`cell ${t.prop} references deleted ${t.tgtTable==="records"?"record":"document"}: ${t.dead.join(", ")}`,fixable:!0}))}function fS(e){let t=K_(e);for(let r of t){let n=e.query("SELECT data FROM records WHERE id = ?").get(r.rec);if(!n)continue;let s=JSON.parse(n.data||"{}")[r.prop];if(!Array.isArray(s))continue;let a=new Set(r.dead);_e(e,"records",r.rec,r.prop,s.filter((c)=>!a.has(String(c))))}return t.length}function V_(e){let t=e.query(`SELECT id, site_id, path FROM site_files
562
+ ORDER BY r.id, j.value`).all(),c=null;for(let p of a){if(!c||c.rec!==p.rec)c={rec:p.rec,prop:n.id,tgtTable:o,dead:[]},r.push(c);c.dead.push(p.dead)}}return r}function SS(e){return Qm(e).map((t)=>({category:"dead_cell_ref",entity:"records",id:t.rec,detail:`cell ${t.prop} references deleted ${t.tgtTable==="records"?"record":"document"}: ${t.dead.join(", ")}`,fixable:!0}))}function kS(e){let t=Qm(e);for(let r of t){let n=e.query("SELECT data FROM records WHERE id = ?").get(r.rec);if(!n)continue;let s=JSON.parse(n.data||"{}")[r.prop];if(!Array.isArray(s))continue;let a=new Set(r.dead);me(e,"records",r.rec,r.prop,s.filter((c)=>!a.has(String(c))))}return t.length}function Ym(e){let t=e.query(`SELECT id, site_id, path FROM site_files
563
563
  WHERE __deleted = 0 AND site_id IS NOT NULL AND path IS NOT NULL
564
- ORDER BY site_id, path, created_hlc, id`).all(),r=[],n=null;for(let o of t){let s=`${o.site_id}\x00${o.path}`;if(s===n)r.push({id:o.id});else n=s}return r}function pS(e){return V_(e).map((t)=>({category:"dup_path",entity:"site_files",id:t.id,detail:"redundant duplicate (site_id, path); loser tombstoned",fixable:!0}))}function hS(e){let t=V_(e);for(let r of t)_e(e,"site_files",r.id,"__deleted",1);return t.length}function J_(e){let t=e.query(`SELECT d.id AS id, d.parent_id AS parent, d.created_hlc AS hlc
564
+ ORDER BY site_id, path, created_hlc, id`).all(),r=[],n=null;for(let o of t){let s=`${o.site_id}\x00${o.path}`;if(s===n)r.push({id:o.id});else n=s}return r}function xS(e){return Ym(e).map((t)=>({category:"dup_path",entity:"site_files",id:t.id,detail:"redundant duplicate (site_id, path); loser tombstoned",fixable:!0}))}function TS(e){let t=Ym(e);for(let r of t)me(e,"site_files",r.id,"__deleted",1);return t.length}function e_(e){let t=e.query(`SELECT d.id AS id, d.parent_id AS parent, d.created_hlc AS hlc
565
565
  FROM documents d
566
566
  WHERE d.__deleted = 0 AND d.parent_id IS NOT NULL
567
567
  AND EXISTS (SELECT 1 FROM documents p WHERE p.id = d.parent_id AND p.__deleted = 0)
568
- ORDER BY d.id`).all(),r=new Map(t.map((a)=>[a.id,a.parent])),n=new Map(t.map((a)=>[a.id,a.hlc])),o=new Set,s=[];for(let a of r.keys()){if(o.has(a))continue;let c=[],p=new Map,m=a;while(m!=null&&r.has(m)&&!o.has(m)){if(p.has(m)){s.push(c.slice(p.get(m)));break}p.set(m,c.length),c.push(m),m=r.get(m)}for(let x of c)o.add(x)}return{cycles:s,hlc:n}}function gS(e,t,r){let n=e.get(t)??"",o=e.get(r)??"";if(n!==o)return n>o;return t>=r}function _S(e){let{cycles:t}=J_(e);return t.map((r)=>({category:"parent_cycle",entity:"documents",id:[...r].sort()[0],detail:`parent cycle: ${[...r].sort().join(" → ")}`,fixable:!0}))}function mS(e){let{cycles:t,hlc:r}=J_(e);for(let n of t){let o=n.reduce((s,a)=>gS(r,s,a)?s:a);_e(e,"documents",o,"parent_id",null)}return t.length}function yS(e){let t=[],r=e.query(`SELECT database_id AS db, lower(name) AS n, count(*) AS c, group_concat(id) AS ids
568
+ ORDER BY d.id`).all(),r=new Map(t.map((a)=>[a.id,a.parent])),n=new Map(t.map((a)=>[a.id,a.hlc])),o=new Set,s=[];for(let a of r.keys()){if(o.has(a))continue;let c=[],p=new Map,m=a;while(m!=null&&r.has(m)&&!o.has(m)){if(p.has(m)){s.push(c.slice(p.get(m)));break}p.set(m,c.length),c.push(m),m=r.get(m)}for(let x of c)o.add(x)}return{cycles:s,hlc:n}}function RS(e,t,r){let n=e.get(t)??"",o=e.get(r)??"";if(n!==o)return n>o;return t>=r}function AS(e){let{cycles:t}=e_(e);return t.map((r)=>({category:"parent_cycle",entity:"documents",id:[...r].sort()[0],detail:`parent cycle: ${[...r].sort().join(" → ")}`,fixable:!0}))}function DS(e){let{cycles:t,hlc:r}=e_(e);for(let n of t){let o=n.reduce((s,a)=>RS(r,s,a)?s:a);me(e,"documents",o,"parent_id",null)}return t.length}function OS(e){let t=[],r=e.query(`SELECT database_id AS db, lower(name) AS n, count(*) AS c, group_concat(id) AS ids
569
569
  FROM properties
570
570
  WHERE __deleted = 0 AND name IS NOT NULL AND database_id IS NOT NULL
571
571
  GROUP BY database_id, lower(name) HAVING c > 1
572
572
  ORDER BY database_id, n`).all();for(let o of r)t.push({category:"dup_name",entity:"properties",id:o.ids.split(",").sort()[0],detail:`${o.c} properties named "${o.n}" in database ${o.db}: ${o.ids}`,fixable:!1});let n=e.query(`SELECT lower(name) AS n, count(*) AS c, group_concat(id) AS ids
573
573
  FROM databases WHERE __deleted = 0 AND name IS NOT NULL
574
- GROUP BY lower(name) HAVING c > 1 ORDER BY n`).all();for(let o of n)t.push({category:"dup_name",entity:"databases",id:o.ids.split(",").sort()[0],detail:`${o.c} databases named "${o.n}": ${o.ids}`,fixable:!1});return t}function bS(e,t){if(!Fo.has(e))return`unknown property type: ${e}`;if(e==="select"||e==="multi_select"){let r=t?.options;if(!Array.isArray(r)||r.length===0||!r.every((n)=>typeof n==="string"))return`${e} missing config.options: string[]`}if(e==="relation"&&typeof t?.database!=="string")return"relation missing config.database";return null}function wS(e){let t=e.query("SELECT id, type, config FROM properties WHERE __deleted = 0 ORDER BY id").all(),r=[];for(let n of t){let o=null;try{o=n.config?JSON.parse(n.config):null}catch{r.push({category:"bad_config",entity:"properties",id:n.id,detail:"config is not valid JSON",fixable:!1});continue}let s=bS(n.type,o);if(s)r.push({category:"bad_config",entity:"properties",id:n.id,detail:s,fixable:!1})}return r}function vS(e,t){let n=e.query("SELECT node_id, COUNT(*) AS n FROM crdt_changes WHERE hlc > ? GROUP BY node_id").all(Io(t)).map((s)=>({category:"clock_skew",entity:"nodes",id:s.node_id,detail:`${s.n} change(s) stamped more than 5 min in the future — run \`mh repair --clock\``,fixable:!1})),o=ds(e);if(o&&o.millis>t+Lr)n.push({category:"clock_skew",entity:"meta",id:"hlc",detail:`local logical clock is ${Math.ceil((o.millis-t)/60000)} min ahead of wall time — writes refuse until \`mh repair --clock\``,fixable:!1});return n}function X_(e,t=Date.now()){return st(e,()=>{let r=e.query(`SELECT seq, ${mt} FROM crdt_changes WHERE hlc > ? ORDER BY hlc, seq`).all(Io(t)),n={},o=ds(e),s=r.length>0||o!=null&&o.millis>t+Lr;if(s)yl(e,We(e),t);if(r.length===0)return{restamped:0,byNode:n,clockReset:s};let a=new Map;for(let c of r){e.query("DELETE FROM crdt_changes WHERE seq = ?").run(c.seq);let{seq:p,...m}=c,x={...m,hlc:No(e,c.node_id,t)};Mr(e,x),a.set(`${m.dataset}\x00${m.row_id}\x00${m.col}`,x),n[c.node_id]=(n[c.node_id]??0)+1}for(let c of a.values()){let p=e.query(`SELECT ${mt} FROM crdt_changes WHERE dataset = ? AND row_id = ? AND col = ? ORDER BY hlc DESC LIMIT 1`).get(c.dataset,c.row_id,c.col);if(p)Mr(e,p)}return Sl(e),{restamped:r.length,byNode:n,clockReset:s}})}function ES(e,t={}){let r=[...aS(e),...lS(e),...dS(e),...pS(e),..._S(e),...yS(e),...wS(e),...vS(e,t.now??Date.now())],n={};for(let o of r)n[o.category]=(n[o.category]??0)+1;return{ok:r.length===0,total:r.length,counts:n,issues:r}}function SS(e){let t={},r=(o,s)=>{if(s)t[o]=(t[o]??0)+s};return r("broken_ref",cS(e)),r("orphan_cell",uS(e)),r("dead_cell_ref",fS(e)),r("dup_path",hS(e)),r("parent_cycle",mS(e)),{applied:Object.values(t).reduce((o,s)=>o+s,0),fixed:t}}var WI=Fe(function(t){let r={},n=0;for(let o=0;o<20;o++){let s=SS(t);if(s.applied===0)break;n+=s.applied;for(let[a,c]of Object.entries(s.fixed))r[a]=(r[a]??0)+c}return{applied:n,fixed:r,remaining:ES(t)}},"repair");Jo();ct();var Y_="('text','url','select','multi_select','date')",em="1";function xc(e,t){return e.query("SELECT value FROM meta WHERE key = ?").get(t)?.value??null}function kc(e,t,r){e.query("INSERT INTO meta (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(t,r)}function xS(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 Tc(e,t,...r){return e.query(`SELECT r.id AS id, r.database_id AS database_id, group_concat(je.value, ' ') AS body
574
+ GROUP BY lower(name) HAVING c > 1 ORDER BY n`).all();for(let o of n)t.push({category:"dup_name",entity:"databases",id:o.ids.split(",").sort()[0],detail:`${o.c} databases named "${o.n}": ${o.ids}`,fixable:!1});return t}function IS(e,t){if(!Uo.has(e))return`unknown property type: ${e}`;if(e==="select"||e==="multi_select"){let r=t?.options;if(!Array.isArray(r)||r.length===0||!r.every((n)=>typeof n==="string"))return`${e} missing config.options: string[]`}if(e==="relation"&&typeof t?.database!=="string")return"relation missing config.database";return null}function CS(e){let t=e.query("SELECT id, type, config FROM properties WHERE __deleted = 0 ORDER BY id").all(),r=[];for(let n of t){let o=null;try{o=n.config?JSON.parse(n.config):null}catch{r.push({category:"bad_config",entity:"properties",id:n.id,detail:"config is not valid JSON",fixable:!1});continue}let s=IS(n.type,o);if(s)r.push({category:"bad_config",entity:"properties",id:n.id,detail:s,fixable:!1})}return r}function PS(e,t){let n=e.query("SELECT node_id, COUNT(*) AS n FROM crdt_changes WHERE hlc > ? GROUP BY node_id").all(Po(t)).map((s)=>({category:"clock_skew",entity:"nodes",id:s.node_id,detail:`${s.n} change(s) stamped more than 5 min in the future — run \`mh repair --clock\``,fixable:!1})),o=ps(e);if(o&&o.millis>t+$r)n.push({category:"clock_skew",entity:"meta",id:"hlc",detail:`local logical clock is ${Math.ceil((o.millis-t)/60000)} min ahead of wall time — writes refuse until \`mh repair --clock\``,fixable:!1});return n}function t_(e,t=Date.now()){return at(e,()=>{let r=e.query(`SELECT seq, ${_t} FROM crdt_changes WHERE hlc > ? ORDER BY hlc, seq`).all(Po(t)),n={},o=ps(e),s=r.length>0||o!=null&&o.millis>t+$r;if(s)vl(e,We(e),t);if(r.length===0)return{restamped:0,byNode:n,clockReset:s};let a=new Map;for(let c of r){e.query("DELETE FROM crdt_changes WHERE seq = ?").run(c.seq);let{seq:p,...m}=c,x={...m,hlc:Lo(e,c.node_id,t)};Fr(e,x),a.set(`${m.dataset}\x00${m.row_id}\x00${m.col}`,x),n[c.node_id]=(n[c.node_id]??0)+1}for(let c of a.values()){let p=e.query(`SELECT ${_t} FROM crdt_changes WHERE dataset = ? AND row_id = ? AND col = ? ORDER BY hlc DESC LIMIT 1`).get(c.dataset,c.row_id,c.col);if(p)Fr(e,p)}return Tl(e),{restamped:r.length,byNode:n,clockReset:s}})}function NS(e,t={}){let r=[...bS(e),...vS(e),...SS(e),...xS(e),...AS(e),...OS(e),...CS(e),...PS(e,t.now??Date.now())],n={};for(let o of r)n[o.category]=(n[o.category]??0)+1;return{ok:r.length===0,total:r.length,counts:n,issues:r}}function qS(e){let t={},r=(o,s)=>{if(s)t[o]=(t[o]??0)+s};return r("broken_ref",wS(e)),r("orphan_cell",ES(e)),r("dead_cell_ref",kS(e)),r("dup_path",TS(e)),r("parent_cycle",DS(e)),{applied:Object.values(t).reduce((o,s)=>o+s,0),fixed:t}}var aC=Fe(function(t){let r={},n=0;for(let o=0;o<20;o++){let s=qS(t);if(s.applied===0)break;n+=s.applied;for(let[a,c]of Object.entries(s.fixed))r[a]=(r[a]??0)+c}return{applied:n,fixed:r,remaining:NS(t)}},"repair");Qo();lt();var n_="('text','url','select','multi_select','date')",o_="1";function xc(e,t){return e.query("SELECT value FROM meta WHERE key = ?").get(t)?.value??null}function Tc(e,t,r){e.query("INSERT INTO meta (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(t,r)}function LS(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 Rc(e,t,...r){return e.query(`SELECT r.id AS id, r.database_id AS database_id, group_concat(je.value, ' ') AS body
575
575
  FROM records r, json_each(r.data) je
576
576
  JOIN properties p ON p.id = je.key AND p.__deleted = 0
577
- WHERE ${t} AND r.__deleted = 0 AND p.type IN ${Y_}
578
- GROUP BY r.id`).all(...r)}function Rc(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 kS(e,t){e.query("DELETE FROM search_fts WHERE kind = 'record' AND id = ?").run(t);let r=Tc(e,"r.id = ?",t)[0];if(r)Rc(e,r)}function TS(e,t){e.query("DELETE FROM search_fts WHERE kind = 'record' AND database_id = ?").run(t);for(let r of Tc(e,"r.database_id = ?",t))Rc(e,r)}function RS(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 Tc(e,"1 = 1"))Rc(e,r);let t=e.query("SELECT MAX(rowid) AS m FROM crdt_changes").get().m??0;kc(e,"search_seq",String(t)),kc(e,"search_index_version",em)}function AS(e){let t=Number(xc(e,"search_seq")??"0"),{changes:r,cursor:n}=vr(e,t);if(r.length===0)return;let o=new Set,s=new Set,a=new Set;for(let c of r)switch(c.dataset){case"documents":o.add(c.row_id);break;case"doc_blocks":{let p=e.query("SELECT doc_id FROM doc_blocks WHERE id = ?").get(c.row_id);if(p?.doc_id)o.add(p.doc_id);break}case"records":s.add(c.row_id);break;case"properties":if(c.col==="type"||c.col==="__deleted"||c.col==="database_id"){let p=e.query("SELECT database_id FROM properties WHERE id = ?").get(c.row_id);if(p?.database_id)a.add(p.database_id)}break}for(let c of o)xS(e,c);for(let c of a)TS(e,c);for(let c of s){let p=e.query("SELECT database_id FROM records WHERE id = ?").get(c);if(p?.database_id&&a.has(p.database_id))continue;kS(e,c)}kc(e,"search_seq",String(n))}function DS(e){if(!vu(e))return!1;let t=xc(e,"search_index_version"),r=xc(e,"search_seq");return st(e,()=>{if(t!==em||r===null)RS(e);else AS(e)}),!0}function OS(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 Q_(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 IS(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:Q_(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
577
+ WHERE ${t} AND r.__deleted = 0 AND p.type IN ${n_}
578
+ GROUP BY r.id`).all(...r)}function Ac(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 $S(e,t){e.query("DELETE FROM search_fts WHERE kind = 'record' AND id = ?").run(t);let r=Rc(e,"r.id = ?",t)[0];if(r)Ac(e,r)}function MS(e,t){e.query("DELETE FROM search_fts WHERE kind = 'record' AND database_id = ?").run(t);for(let r of Rc(e,"r.database_id = ?",t))Ac(e,r)}function FS(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 Rc(e,"1 = 1"))Ac(e,r);let t=e.query("SELECT MAX(rowid) AS m FROM crdt_changes").get().m??0;Tc(e,"search_seq",String(t)),Tc(e,"search_index_version",o_)}function zS(e){let t=Number(xc(e,"search_seq")??"0"),{changes:r,cursor:n}=Er(e,t);if(r.length===0)return;let o=new Set,s=new Set,a=new Set;for(let c of r)switch(c.dataset){case"documents":o.add(c.row_id);break;case"doc_blocks":{let p=e.query("SELECT doc_id FROM doc_blocks WHERE id = ?").get(c.row_id);if(p?.doc_id)o.add(p.doc_id);break}case"records":s.add(c.row_id);break;case"properties":if(c.col==="type"||c.col==="__deleted"||c.col==="database_id"){let p=e.query("SELECT database_id FROM properties WHERE id = ?").get(c.row_id);if(p?.database_id)a.add(p.database_id)}break}for(let c of o)LS(e,c);for(let c of a)MS(e,c);for(let c of s){let p=e.query("SELECT database_id FROM records WHERE id = ?").get(c);if(p?.database_id&&a.has(p.database_id))continue;$S(e,c)}Tc(e,"search_seq",String(n))}function US(e){if(!xu(e))return!1;let t=xc(e,"search_index_version"),r=xc(e,"search_seq");return at(e,()=>{if(t!==o_||r===null)FS(e);else zS(e)}),!0}function BS(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 r_(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 jS(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:r_(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
579
579
  FROM records r, json_each(r.data) je
580
580
  JOIN properties p ON p.id = je.key AND p.__deleted = 0
581
- WHERE r.__deleted = 0 AND p.type IN ${Y_}
582
- GROUP BY r.id HAVING body LIKE ? ESCAPE '\\' LIMIT ?`).all(n,r-o.length);for(let c of a)o.push({type:"record",id:c.id,database_id:c.database_id,snippet:Q_(c.body||"",t)})}return o}function tm(e,t,r={}){let n=r.limit??20;if(DS(e))try{let o=OS(e,t,n);if(o.length)return o}catch{}return IS(e,t,n)}Ho();Rn();wo();Vr();kn();Li();Xe();function PS(e){if(e===401)return"auth";if(e===404)return"not_found";if(e===429)return"rate_limited";return"network"}function Zi(e,t,r=fetch){let n=e.replace(/\/+$/,"");async function o(a,c={},p=!0){let m;try{m=await r(n+a,{...c,signal:c.signal??AbortSignal.timeout(15000),headers:{...c.body!=null?{"content-type":"application/json"}:{},...p?{authorization:`Bearer ${t}`}:{},...c.headers}})}catch(O){throw new Z("network",`inbox host unreachable: ${O.message}`)}let x=await m.json().catch(()=>null);if(!m.ok)throw new Z(PS(m.status),`inbox host: ${x?.error??`HTTP ${m.status}`}`);return x}let s=(a)=>`/v1/inbox/${encodeURIComponent(a)}`;return{async register(a,c){await o(s(a),{method:"PUT",body:JSON.stringify(c)})},async unregister(a){return(await o(s(a),{method:"DELETE"})).deleted},async listEnvelopes(a,c,p){return(await o(`${s(a)}/envelopes?after_id=${c}&limit=${p}`)).rows},async ackEnvelopes(a,c){if(c.length===0)return 0;return(await o(`${s(a)}/envelopes`,{method:"DELETE",body:JSON.stringify({ids:c})})).deleted},async stats(a){return o(`${s(a)}/stats`)},async health(){return o("/health",{},!1)},async ownerHealth(){return o("/owner/health")}}}Xe();async function rm(e,t,r){let n;try{let c=new URL(e.trim());if(c.protocol!=="https:"&&c.hostname!=="localhost")throw Error(`${r==="edge"?"Edge":"Inbox"} endpoint must use HTTPS`);n=c.toString().replace(/\/+$/,"")}catch(c){throw new Z("invalid_input",c.message||"invalid Edge endpoint")}let o=t.trim();if(!o)throw new Z("invalid_input","owner token is required");let s=Zi(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!==Dr)throw new Z("conflict",`Edge version ${a.version??"unknown"} is incompatible; expected ${Dr}`);return{endpoint:n,token:o,version:a.version,capabilities:r==="edge"?["inbox","room"]:["inbox"]}}var qc=15000,gm=2000,dr=self.location.origin,xe=null,Ut={state:"booting",paired:!1,node:null};function Ki(e){self.postMessage(e)}function or(e){Ut={...Ut,...e},Ki({event:"status",status:Ut})}function kt(){if(!xe)throw new Z("network",kr("本地副本未就绪"));return xe}var $c=null,mm=null;function ym(){let e=new $c.OpfsSAHPoolDb("/metahub.db");mm=e;let t=new os(e);Cs(t),xe=t;let r=jS();hl(t,{app:"web",platform:r,form:"browser",defaultLabel:HS(r)})}function jS(){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 HS(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 WS=(async()=>{$c=await(await sl()).installOpfsSAHPoolVfs({name:"metahub-replica"}),ym();let t=xe,r=We(t),n=xt(t,dr)?.token!=null,o=Vi(t);if(o)Ji();or({state:"ready",node:r,paired:n,bucketDirty:o})})().catch((e)=>{throw or({state:"error",error:e instanceof Error?e.message:String(e)}),e}),en=null,_m=new Set;function ZS(e){if(xt(e,dr)?.token!=null)return!0;return Lt(e).some((t)=>t.enabled===1&&(t.kind==="s3"||t.kind==="room"))}function Or(e){return Lt(e).filter((t)=>t.enabled===1&&t.kind==="s3")}function GS(e){return Lt(e).filter((t)=>t.enabled===1&&t.kind==="room")}async function Mc(e,t){let r=await yc(t).catch(()=>{return});if(r)return new Uint8Array(r.bytes);for(let n of Or(kt())){if(!n.config)continue;let o=await La(JSON.parse(n.config),t).catch(()=>null);if(o&&await mc(o,t))return new Uint8Array(o)}return null}Cg(Mc);pu(Mc);function Vi(e){let t=We(e);return Or(e).some((r)=>vr(e,r.push_cursor,{onlyNode:t}).changes.length>0)}var KS=25,bm=1e4,Pn=null;function Ji(){if(Pn)return;Pn=setTimeout(()=>{if(Pn=null,navigator.onLine!==!1)tn(!0)},bm)}function Lc(){if(!Pn)return;clearTimeout(Pn),Pn=null}function VS(){let e=xe;if(!e)return;let t=Or(e).length>0&&Vi(e);if(or({bucketDirty:t,bucketError:void 0}),t)Ji();else Lc()}function JS(e,t){e.query(`UPDATE peers SET
581
+ WHERE r.__deleted = 0 AND p.type IN ${n_}
582
+ GROUP BY r.id HAVING body LIKE ? ESCAPE '\\' LIMIT ?`).all(n,r-o.length);for(let c of a)o.push({type:"record",id:c.id,database_id:c.database_id,snippet:r_(c.body||"",t)})}return o}function i_(e,t,r={}){let n=r.limit??20;if(US(e))try{let o=BS(e,t,n);if(o.length)return o}catch{}return jS(e,t,n)}Zo();Dn();Eo();Qr();Rn();Mi();Xe();function WS(e){if(e===401)return"auth";if(e===404)return"not_found";if(e===429)return"rate_limited";return"network"}function Gi(e,t,r=fetch){let n=e.replace(/\/+$/,"");async function o(a,c={},p=!0){let m;try{m=await r(n+a,{...c,signal:c.signal??AbortSignal.timeout(15000),headers:{...c.body!=null?{"content-type":"application/json"}:{},...p?{authorization:`Bearer ${t}`}:{},...c.headers}})}catch(A){throw new H("network",`inbox host unreachable: ${A.message}`)}let x=await m.json().catch(()=>null);if(!m.ok)throw new H(WS(m.status),`inbox host: ${x?.error??`HTTP ${m.status}`}`);return x}let s=(a)=>`/v1/inbox/${encodeURIComponent(a)}`;return{async register(a,c){await o(s(a),{method:"PUT",body:JSON.stringify(c)})},async unregister(a){return(await o(s(a),{method:"DELETE"})).deleted},async listEnvelopes(a,c,p){return(await o(`${s(a)}/envelopes?after_id=${c}&limit=${p}`)).rows},async ackEnvelopes(a,c){if(c.length===0)return 0;return(await o(`${s(a)}/envelopes`,{method:"DELETE",body:JSON.stringify({ids:c})})).deleted},async stats(a){return o(`${s(a)}/stats`)},async health(){return o("/health",{},!1)},async ownerHealth(){return o("/owner/health")}}}Xe();async function s_(e,t,r){let n;try{let c=new URL(e.trim());if(c.protocol!=="https:"&&c.hostname!=="localhost")throw Error(`${r==="edge"?"Edge":"Inbox"} endpoint must use HTTPS`);n=c.toString().replace(/\/+$/,"")}catch(c){throw new H("invalid_input",c.message||"invalid Edge endpoint")}let o=t.trim();if(!o)throw new H("invalid_input","owner token is required");let s=Gi(n,o),a=r==="edge"?await s.ownerHealth():await s.health();if(!a.ok)throw new H("network",`${r==="edge"?"Edge":"Inbox host"} at ${n} is not healthy`);if(r==="edge"&&a.version!==Or)throw new H("conflict",`Edge version ${a.version??"unknown"} is incompatible; expected ${Or}`);return{endpoint:n,token:o,version:a.version,capabilities:r==="edge"?["inbox","room"]:["inbox"]}}var Mc=15000,R_=2000,fr=self.location.origin,ke=null,jt={state:"booting",paired:!1,node:null};function Ji(e){self.postMessage(e)}function sr(e){jt={...jt,...e},Ji({event:"status",status:jt})}function Tt(){if(!ke)throw new H("network",Tr("本地副本未就绪"));return ke}var zc=null,D_=null;function O_(){let e=new zc.OpfsSAHPoolDb("/metahub.db");D_=e;let t=new ss(e);Ns(t),ke=t;let r=nk();_l(t,{app:"web",platform:r,form:"browser",defaultLabel:ok(r)})}function nk(){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 ok(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 ik=(async()=>{zc=await(await ll()).installOpfsSAHPoolVfs({name:"metahub-replica"}),O_();let t=ke,r=We(t),n=xt(t,fr)?.token!=null,o=Xi(t);if(o)Qi();sr({state:"ready",node:r,paired:n,bucketDirty:o})})().catch((e)=>{throw sr({state:"error",error:e instanceof Error?e.message:String(e)}),e}),nn=null,A_=new Set;function sk(e){if(xt(e,fr)?.token!=null)return!0;return Ft(e).some((t)=>t.enabled===1&&(t.kind==="s3"||t.kind==="room"))}function Ir(e){return Ft(e).filter((t)=>t.enabled===1&&t.kind==="s3")}function ak(e){return Ft(e).filter((t)=>t.enabled===1&&t.kind==="room")}async function Uc(e,t){let r=await bc(t).catch(()=>{return});if(r)return new Uint8Array(r.bytes);for(let n of Ir(Tt())){if(!n.config)continue;let o=await $a(JSON.parse(n.config),t).catch(()=>null);if(o&&await yc(o,t))return new Uint8Array(o)}return null}Lg(Uc);_u(Uc);function Xi(e){let t=We(e);return Ir(e).some((r)=>Er(e,r.push_cursor,{onlyNode:t}).changes.length>0)}var ck=25,I_=1e4,qn=null;function Qi(){if(qn)return;qn=setTimeout(()=>{if(qn=null,navigator.onLine!==!1)on(!0)},I_)}function Fc(){if(!qn)return;clearTimeout(qn),qn=null}function lk(){let e=ke;if(!e)return;let t=Ir(e).length>0&&Xi(e);if(sr({bucketDirty:t,bucketError:void 0}),t)Qi();else Fc()}function uk(e,t){e.query(`UPDATE peers SET
583
583
  pull_cursor = ?,
584
584
  push_cursor = ?,
585
585
  token = ?,
@@ -592,4 +592,4 @@ if(L instanceof ArrayBuffer)L=new Uint8Array(L);else if(L instanceof Function)re
592
592
  last_error = ?,
593
593
  kind = ?,
594
594
  config = ?
595
- 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 XS(e){let t=Or(e);if(!t.length)return;let r;try{r=await w_()}catch{return}for(let n of r){let o=!1;for(let s of t){if(!s.config)continue;try{await og(JSON.parse(s.config),n.hash,new Uint8Array(n.bytes)),o=!0;break}catch{}}if(o)await S_(n.hash,n.bytes,n.content_type).catch(()=>{}),await v_(n.hash).catch(()=>{})}}async function tn(e=!1){if(!xe)return{pushed:0,pulled:0,ok:!0};let t=xe;if(!ZS(t))return{pushed:0,pulled:0,ok:!0};if(en)return en;return en=(async()=>{or({syncing:!0});let r=t.query("SELECT MAX(rowid) AS m FROM crdt_changes").get().m??0,n=0,o=0,s=[],a=[],c=Or(t).length>0;if(c&&e)or({bucketSyncing:!0,bucketError:void 0});let p=!1;if(xt(t,dr)?.token!=null)try{let O=0;for(;;){let F=xt(t,dr)?.pull_cursor??0,X=await Si(t,dr,{pullLimit:gm});if(n+=X.pushed,o+=X.pulled,O+=X.received??X.pulled,(X.received??X.pulled)<gm)break;if((xt(t,dr)?.pull_cursor??0)===F)break;or({state:"hydrating",hydrated:O})}p=!0}catch(O){s.push(`server: ${O instanceof Error?O.message:String(O)}`)}for(let O of Or(t)){let F=p&&!e&&_m.has(O.url),X=await lc(t,O.url,{storage:{minPushChanges:KS,maxPushAgeMs:bm,forcePush:e,pull:!F}});if(X.ok){if(n+=X.pushed??0,o+=X.pulled??0,!F)_m.add(O.url)}else{let he=`${O.label??O.url}: ${X.error}`;s.push(he),a.push(he)}}for(let O of GS(t)){let F=await lc(t,O.url);if(F.ok)n+=F.pushed??0,o+=F.pulled??0;else s.push(`${O.label??O.url}: ${F.error}`)}if(!p&&c)await XS(t);await Dn(t);let m=c?Vi(t):!1;if(m&&a.length===0)Ji();else Lc();let x=t.query("SELECT DISTINCT dataset, row_id FROM crdt_changes WHERE rowid > ?").all(r);if(or({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)Ki({event:"synced",datasets:[...new Set(x.map((O)=>O.dataset))],rowIds:x.map((O)=>O.row_id),pushed:n,pulled:o});return{pushed:n,pulled:o,ok:s.length===0}})().finally(()=>{if(Ut.syncing)or({syncing:!1});if(xe&&Or(xe).length>0&&!Ut.bucketSyncing)if(Vi(xe)&&!Ut.bucketError)Ji();else Lc();en=null}),en}var QS=150000,ko=qc,YS=180000;function ex(){if(!xe)return!1;if(xt(xe,dr)?.token!=null)return!1;return Lt(xe).some((e)=>e.enabled===1&&(e.kind==="s3"||e.kind==="room"))}async function wm(){try{if(navigator.onLine!==!1&&ex()){let e=await tn();ko=e.pushed>0||e.pulled>0?qc:Math.min(ko*2,QS)}else ko=qc}finally{setTimeout(wm,ko)}}setTimeout(wm,ko);async function tx(e){let t=kt(),r={code:e,node_id:We(t),grant:vt(32)},n=await fetch(new URL(Mh,dr),{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 c_(t,{url:dr,token:o.grant,node_id:o.node_id,label:"server"}),or({paired:!0}),tn(),{node_id:o.node_id}}function rx(){let e=St(kt(),dr);return or({paired:!1}),{ok:e}}var vm={applyLocale:(e)=>(Nu(e),{ok:!0}),status:()=>Ut,pair:(e)=>tx(e),unpair:()=>rx(),sync:()=>tn(!0).then(()=>Ut.lastSync),addStorageReplica:async(e,t)=>{let r=kt(),n={publish:!0,priority:10,...e};if(n.encrypt)n.masterKey=await Fa(Gt(n),n,t)??void 0;let o=bn(n.endpoint,n.bucket,n.prefix);if(en)await en;let s=xt(r,o);if(l_(r,{url:o,config:n,label:n.bucket}),await tn(!0),Ut.bucketError){if(s)JS(r,s);else St(r,o);throw new Z("network",`storage peer first sync failed: ${Ut.bucketError}`)}return{url:o,lastSync:Ut.lastSync}},removeStorageReplica:(e)=>({ok:St(kt(),e)}),storagePeerConfig:(e)=>{let t=xt(xe,e);return t?.config?JSON.parse(t.config):null},dataMap:()=>f_(kt()),listStoragePeers:()=>Lt(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=kt(),t=Wi(e),r=Lt(e).filter((n)=>n.kind==="room"&&n.config).map((n)=>{let o=JSON.parse(n.config);return{slug:o.slug,url:Jr(o),status:n.last_status,lastSuccessAt:n.last_success_at,error:n.last_error}});if(!t)return{configured:!1,expectedVersion:Dr,aligned:!1,reachable:!1,managed:!1,rooms:r,defaults:null,pending:null};try{let n=await Zi(t.endpoint,t.token).ownerHealth();return{configured:!0,endpoint:t.endpoint,capabilities:So(t),version:n.version??null,expectedVersion:Dr,aligned:n.version===Dr,reachable:n.ok,managed:!1,rooms:r,defaults:null,pending:null}}catch(n){return{configured:!0,endpoint:t.endpoint,capabilities:So(t),version:null,expectedVersion:Dr,aligned:!1,reachable:!1,error:n.message,managed:!1,rooms:r,defaults:null,pending:null}}},connectEdge:async(e,t)=>{let r=await rm(e,t,"edge");return Dc(kt(),{endpoint:r.endpoint,token:r.token,capabilities:r.capabilities,deployedVersion:r.version}),{...await vm.edgeStatus(),status:"connected",wired:[],warnings:[]}},disconnectEdge:()=>{let e=kt();if(Lt(e).some((t)=>t.kind==="room"))throw new Z("conflict",kr("请先撤销所有 Edge Room 再断开"));return Dc(e,null),{ok:!0}},listLocalShares:(e)=>{let t=kt();return(e?Ha(t,e):ja(t)).map((n)=>{let o=xt(t,`room://${n.slug}`),s=o?.config?JSON.parse(o.config):null,a=s?.lifecycle??"active",c=s&&a==="active"?Jr(s):void 0,p=n.kind==="site"?Xr(t,n.target_id):null;return{slug:n.slug,kind:n.kind,target_id:n.target_id,title:p?.title||p?.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:c}})},createLocalShare:async(e)=>{let t=kt();if(e.kind!=="site"||e.hosting!=="room")throw new Z("invalid_input",kr("此设备不驻留在线托管,目前仅支持通过 Edge 发布站点"));let r=Wi(t);if(!r)throw new Z("invalid_input",kr("请先连接 Edge"));if(!So(r).includes("room"))throw new Z("conflict",kr("当前 Edge 仅支持 inbox,不支持 Room 托管"));let n=Xr(t,e.ref),o=e.password?await Wa(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 qg(t,s,r,Mc),c=bo(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 It(t,{channelId:c.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 mo(t,s.slug)!=="cleanup_pending")rr(t,s.slug);throw a}},revokeLocalShare:async(e)=>{let t=kt();if(!cr(t,e))return{ok:!1,status:"not_found"};let r=Kt(t).filter((s)=>s.audience==="link"&&s.target_ref===e&&s.desired_state==="active");for(let s of r)br(t,s.id,"revoked");if(await mo(t,e)==="cleanup_pending"){for(let s of r)It(t,{channelId:s.id,status:"cleanup_pending",lastError:"Edge 尚未确认销毁 Room"});return{ok:!1,status:"cleanup_pending"}}let o=rr(t,e);for(let s of r)It(t,{channelId:s.id,status:"revoked",lastVerifiedAt:Date.now()});return{ok:o,status:"revoked"}},renewLocalShare:async(e,t)=>{let r=kt();await Promise.resolve().then(() => hm());return pm(r,e,void 0,t)},listDatabases:()=>Hl(xe),createDatabase:(e)=>bs(xe,e),updateDatabase:(e,t)=>Bl(xe,e,t),duplicateDatabase:(e,t)=>jl(xe,e,t??{}),deleteDatabase:(e)=>({ok:Wl(xe,e)}),listDatabaseActivity:(e,t)=>D_(xe,e,{limit:t}),repairClock:()=>X_(xe),listAuditEntries:(e)=>U_(xe,e??{}),auditEntryDetail:(e)=>j_(xe,e),revertChangeGroup:(e)=>H_(xe,e),listProperties:(e)=>Ft(xe,e),addProperty:(e,t)=>zo(xe,e,t),updateProperty:(e,t)=>ys(xe,e,t),setPropertyWidth:(e,t)=>Pl(xe,e,t),removeProperty:(e)=>({ok:$l(xe,e)}),renameSelectOption:(e,t,r)=>ql(xe,e,t,r),removeSelectOption:(e,t)=>Ll(xe,e,t),listPropertyRevisions:(e)=>C_(xe,e),revertProperty:(e,t)=>P_(xe,e,t),listRecords:(e,t)=>hn(xe,e,t??{}),createRecord:(e,t)=>Uo(xe,e,t),getRecord:(e)=>{let t=xr(xe,e);if(!t)throw new Z("not_found",`no such record: ${e}`);return t},updateRecord:(e,t)=>Bo(xe,e,t),moveRecord:(e,t,r)=>tu(xe,e,t,r),deleteRecord:(e)=>({ok:ru(xe,e)}),listRecordRevisions:(e)=>A_(xe,e),recordAtVersion:(e,t)=>Ec(xe,e,t),recordFieldHistory:(e,t)=>N_(xe,e,t),revertRecord:(e,t)=>O_(xe,e,t),listDocuments:(e)=>iu(xe,e??{}),createDocument:(e)=>As(xe,e),getDocument:(e)=>{let t=ot(xe,e);if(!t)throw new Z("not_found",`no such document: ${e}`);return{...t,version:qt(xe,t.id)}},updateDocument:(e,t,r)=>{let n=Ko(xe,e,t,{ifMatch:r});return{...n,version:qt(xe,n.id)}},duplicateDocument:(e,t)=>{let r=uu(xe,e,{title:t?.title,parentId:t?.parent_id});return{...r,version:qt(xe,r.id)}},moveDocument:(e,t,r)=>Os(xe,e,t,r),listDocumentRevisions:(e)=>k_(xe,e),documentAtVersion:(e,t)=>vc(xe,e,t),revertDocument:(e,t,r)=>T_(xe,e,t,{ifMatch:r}),deleteDocument:(e)=>({ok:du(xe,e)}),siteFile:async(e,t)=>{if((Ut.lastSync?.at?Date.now()-Ut.lastSync.at:1/0)>YS)await tn(!0).catch(()=>{});let n=xe,o;try{o=Xr(n,e)}catch{return null}let s=Ug(n,o.id,t,{spa:o.spa===1});if(!s)return null;return{...s.row,status:s.status,public:n_(n,o).serving}},blobBytes:async(e)=>{let t=await yc(e).catch(()=>{return});if(t)return t.bytes;for(let r of Or(xe)){if(!r.config)continue;try{let n=await La(JSON.parse(r.config),e);if(n&&await mc(n,e))return new Uint8Array(n).buffer}catch{}}return null},blobRefs:()=>[...mu(xe)],listSites:()=>{let e=Xg(xe);return zg(xe).map((t)=>({...t,file_count:e.get(t.id)??0}))},listSiteFiles:(e)=>Bg(xe,e),createSite:(e)=>{if(e.visibility==="public")throw new Z("invalid_input",kr("此浏览器通过同步存储桶交换数据、不驻留在线;请在在线主节点管理公开发布"));return{...Wg(xe,e),file_count:0}},updateSite:(e,t)=>{if(t.visibility==="public")throw new Z("invalid_input",kr("此浏览器通过同步存储桶交换数据、不驻留在线;请在在线主节点管理公开发布"));return{...e_(xe,e,t),file_count:Qg(xe,e)}},deleteSite:async(e)=>{let t=t_(xe,e);return await Dn(xe),{ok:t}},getSiteGrants:(e)=>({grants:yr(Xr(xe,e).public_grants)}),setSiteGrants:(e,t)=>{let r=Xr(xe,e),n=Zg(xe,r.id,t.tables.length?t:null);return Yg(xe,r.id,yr(n.public_grants)),{grants:yr(n.public_grants)}},siteHosting:()=>({publicBaseUrl:null,scope:null,node:We(xe),pendingRollbacks:[],publishedSites:[],channels:ac(xe)}),revokeSiteChannel:async(e)=>{let t=kt(),{needsReconcile:r}=p_(t,e);if(r)await Dn(t);let n=ac(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}=Vg(xe,e,t,{data:r,contentType:n});return{...s,size:jg(xe,{encoding:s.encoding,content:o})}},deleteSiteFile:(e,t)=>({ok:Jg(xe,e,t)}),reset:async()=>{try{mm?.close()}catch{}return xe=null,await $c?.wipeFiles(),ym(),or({state:"ready",paired:!1,node:We(kt()),hydrated:void 0,lastSync:void 0}),{ok:!0}},nodes:()=>as(xe),setNodeLabel:(e,t)=>{let r=kt(),n=t??We(r);return pl(r,e,n),as(r).find((o)=>o.node_id===n)},search:(e,t)=>tm(xe,e,{limit:t}),resolve:(e,t)=>Kl(xe,e,{limit:t})},nx=/^(create|update|delete|move|duplicate|revert|add|remove|set|put)/,Gi=null;function ox(){if(Gi)clearTimeout(Gi);Gi=setTimeout(()=>{if(Gi=null,navigator.onLine!==!1)tn()},800)}self.onmessage=async(e)=>{let{id:t,op:r,args:n}=e.data;try{await WS;let o=vm[r];if(!o)throw new Z("invalid_input",`unknown op: ${r}`);let s=await o(...n??[]);if(Ki({id:t,ok:!0,result:s}),nx.test(r))VS(),ox()}catch(o){let s=o instanceof Error?o.message:String(o),a=ln(o)??void 0;Ki({id:t,ok:!1,error:{message:s,code:a}})}};
595
+ 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 dk(e){let t=Ir(e);if(!t.length)return;let r;try{r=await km()}catch{return}for(let n of r){let o=!1;for(let s of t){if(!s.config)continue;try{await cg(JSON.parse(s.config),n.hash,new Uint8Array(n.bytes)),o=!0;break}catch{}}if(o)await Rm(n.hash,n.bytes,n.content_type).catch(()=>{}),await xm(n.hash).catch(()=>{})}}async function on(e=!1){if(!ke)return{pushed:0,pulled:0,ok:!0};let t=ke;if(!sk(t))return{pushed:0,pulled:0,ok:!0};if(nn)return nn;return nn=(async()=>{sr({syncing:!0});let r=t.query("SELECT MAX(rowid) AS m FROM crdt_changes").get().m??0,n=0,o=0,s=[],a=[],c=Ir(t).length>0;if(c&&e)sr({bucketSyncing:!0,bucketError:void 0});let p=!1;if(xt(t,fr)?.token!=null)try{let A=0;for(;;){let F=xt(t,fr)?.pull_cursor??0,X=await xi(t,fr,{pullLimit:R_});if(n+=X.pushed,o+=X.pulled,A+=X.received??X.pulled,(X.received??X.pulled)<R_)break;if((xt(t,fr)?.pull_cursor??0)===F)break;sr({state:"hydrating",hydrated:A})}p=!0}catch(A){s.push(`server: ${A instanceof Error?A.message:String(A)}`)}for(let A of Ir(t)){let F=p&&!e&&A_.has(A.url),X=await uc(t,A.url,{storage:{minPushChanges:ck,maxPushAgeMs:I_,forcePush:e,pull:!F}});if(X.ok){if(n+=X.pushed??0,o+=X.pulled??0,!F)A_.add(A.url)}else{let he=`${A.label??A.url}: ${X.error}`;s.push(he),a.push(he)}}for(let A of ak(t)){let F=await uc(t,A.url);if(F.ok)n+=F.pushed??0,o+=F.pulled??0;else s.push(`${A.label??A.url}: ${F.error}`)}if(!p&&c)await dk(t);await In(t);let m=c?Xi(t):!1;if(m&&a.length===0)Qi();else Fc();let x=t.query("SELECT DISTINCT dataset, row_id FROM crdt_changes WHERE rowid > ?").all(r);if(sr({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)Ji({event:"synced",datasets:[...new Set(x.map((A)=>A.dataset))],rowIds:x.map((A)=>A.row_id),pushed:n,pulled:o});return{pushed:n,pulled:o,ok:s.length===0}})().finally(()=>{if(jt.syncing)sr({syncing:!1});if(ke&&Ir(ke).length>0&&!jt.bucketSyncing)if(Xi(ke)&&!jt.bucketError)Qi();else Fc();nn=null}),nn}var fk=150000,Ro=Mc,pk=180000;function hk(){if(!ke)return!1;if(xt(ke,fr)?.token!=null)return!1;return Ft(ke).some((e)=>e.enabled===1&&(e.kind==="s3"||e.kind==="room"))}async function C_(){try{if(navigator.onLine!==!1&&hk()){let e=await on();Ro=e.pushed>0||e.pulled>0?Mc:Math.min(Ro*2,fk)}else Ro=Mc}finally{setTimeout(C_,Ro)}}setTimeout(C_,Ro);async function gk(e){let t=Tt(),r={code:e,node_id:We(t),grant:Et(32)},n=await fetch(new URL(Bh,fr),{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(r)});if(!n.ok)throw new H(n.status===401||n.status===403?"auth":"network",`pairing failed: ${n.status} ${await n.text()}`);let o=await n.json();return fm(t,{url:fr,token:o.grant,node_id:o.node_id,label:"server"}),sr({paired:!0}),on(),{node_id:o.node_id}}function mk(){let e=kt(Tt(),fr);return sr({paired:!1}),{ok:e}}var P_={applyLocale:(e)=>(Mu(e),{ok:!0}),status:()=>jt,pair:(e)=>gk(e),unpair:()=>mk(),sync:()=>on(!0).then(()=>jt.lastSync),addStorageReplica:async(e,t)=>{let r=Tt(),n={publish:!0,priority:10,...e};if(n.encrypt)n.masterKey=await za(Mt(n),n,t)??void 0;let o=En(n.endpoint,n.bucket,n.prefix);if(nn)await nn;let s=xt(r,o);if(pm(r,{url:o,config:n,label:n.bucket}),await on(!0),jt.bucketError){if(s)uk(r,s);else kt(r,o);throw new H("network",`storage peer first sync failed: ${jt.bucketError}`)}return{url:o,lastSync:jt.lastSync}},removeStorageReplica:(e)=>({ok:kt(Tt(),e)}),storagePeerConfig:(e)=>{let t=xt(ke,e);return t?.config?JSON.parse(t.config):null},dataMap:()=>mm(Tt()),listStoragePeers:()=>Ft(ke).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=Tt(),t=Ki(e),r=Ft(e).filter((n)=>n.kind==="room"&&n.config).map((n)=>{let o=JSON.parse(n.config);return{slug:o.slug,url:Yr(o),status:n.last_status,lastSuccessAt:n.last_success_at,error:n.last_error}});if(!t)return{configured:!1,expectedVersion:Or,aligned:!1,reachable:!1,managed:!1,rooms:r,defaults:null,pending:null};try{let n=await Gi(t.endpoint,t.token).ownerHealth();return{configured:!0,endpoint:t.endpoint,capabilities:xo(t),version:n.version??null,expectedVersion:Or,aligned:n.version===Or,reachable:n.ok,managed:!1,rooms:r,defaults:null,pending:null}}catch(n){return{configured:!0,endpoint:t.endpoint,capabilities:xo(t),version:null,expectedVersion:Or,aligned:!1,reachable:!1,error:n.message,managed:!1,rooms:r,defaults:null,pending:null}}},connectEdge:async(e,t)=>{let r=await s_(e,t,"edge");return Oc(Tt(),{endpoint:r.endpoint,token:r.token,capabilities:r.capabilities,deployedVersion:r.version}),{...await P_.edgeStatus(),status:"connected",wired:[],warnings:[]}},disconnectEdge:()=>{let e=Tt();if(Ft(e).some((t)=>t.kind==="room"))throw new H("conflict",Tr("请先撤销所有 Edge Room 再断开"));return Oc(e,null),{ok:!0}},listLocalShares:(e)=>{let t=Tt();return(e?Wa(t,e):Ha(t)).map((n)=>{let o=xt(t,`room://${n.slug}`),s=o?.config?JSON.parse(o.config):null,a=s?.lifecycle??"active",c=s&&a==="active"?Yr(s):void 0,p=n.kind==="site"?en(t,n.target_id):null;return{slug:n.slug,kind:n.kind,target_id:n.target_id,title:p?.title||p?.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:c}})},createLocalShare:async(e)=>{let t=Tt();if(e.kind!=="site"||e.hosting!=="room")throw new H("invalid_input",Tr("此设备不驻留在线托管,目前仅支持通过 Edge 发布站点"));let r=Ki(t);if(!r)throw new H("invalid_input",Tr("请先连接 Edge"));if(!xo(r).includes("room"))throw new H("conflict",Tr("当前 Edge 仅支持 inbox,不支持 Room 托管"));let n=en(t,e.ref),o=e.password?await Za(e.password):null,s=ja(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 Fg(t,s,r,Uc),c=vo(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 Ct(t,{channelId:c.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 bo(t,s.slug)!=="cleanup_pending")or(t,s.slug);throw a}},revokeLocalShare:async(e)=>{let t=Tt();if(!lr(t,e))return{ok:!1,status:"not_found"};let r=Vt(t).filter((s)=>s.audience==="link"&&s.target_ref===e&&s.desired_state==="active");for(let s of r)wr(t,s.id,"revoked");if(await bo(t,e)==="cleanup_pending"){for(let s of r)Ct(t,{channelId:s.id,status:"cleanup_pending",lastError:"Edge 尚未确认销毁 Room"});return{ok:!1,status:"cleanup_pending"}}let o=or(t,e);for(let s of r)Ct(t,{channelId:s.id,status:"revoked",lastVerifiedAt:Date.now()});return{ok:o,status:"revoked"}},renewLocalShare:async(e,t)=>{let r=Tt();await Promise.resolve().then(() => T_());return x_(r,e,void 0,t)},listDatabases:()=>Gl(ke),createDatabase:(e)=>vs(ke,e),updateDatabase:(e,t)=>Zl(ke,e,t),duplicateDatabase:(e,t)=>Kl(ke,e,t??{}),deleteDatabase:(e)=>({ok:Vl(ke,e)}),listDatabaseActivity:(e,t)=>Pm(ke,e,{limit:t}),repairClock:()=>t_(ke),listAuditEntries:(e)=>Wm(ke,e??{}),auditEntryDetail:(e)=>Km(ke,e),revertChangeGroup:(e)=>Gm(ke,e),listProperties:(e)=>Lt(ke,e),addProperty:(e,t)=>Bo(ke,e,t),updateProperty:(e,t)=>ws(ke,e,t),setPropertyWidth:(e,t)=>$l(ke,e,t),removeProperty:(e)=>({ok:Ul(ke,e)}),renameSelectOption:(e,t,r)=>Fl(ke,e,t,r),removeSelectOption:(e,t)=>zl(ke,e,t),listPropertyRevisions:(e)=>Lm(ke,e),revertProperty:(e,t)=>$m(ke,e,t),listRecords:(e,t)=>_n(ke,e,t??{}),createRecord:(e,t)=>jo(ke,e,t),getRecord:(e)=>{let t=xr(ke,e);if(!t)throw new H("not_found",`no such record: ${e}`);return t},updateRecord:(e,t)=>Ho(ke,e,t),moveRecord:(e,t,r)=>iu(ke,e,t,r),deleteRecord:(e)=>({ok:su(ke,e)}),listRecordRevisions:(e)=>Cm(ke,e),recordAtVersion:(e,t)=>Sc(ke,e,t),recordFieldHistory:(e,t)=>Mm(ke,e,t),revertRecord:(e,t)=>Nm(ke,e,t),listDocuments:(e)=>lu(ke,e??{}),createDocument:(e)=>Os(ke,e),getDocument:(e)=>{let t=ot(ke,e);if(!t)throw new H("not_found",`no such document: ${e}`);return{...t,version:$t(ke,t.id)}},updateDocument:(e,t,r)=>{let n=Jo(ke,e,t,{ifMatch:r});return{...n,version:$t(ke,n.id)}},duplicateDocument:(e,t)=>{let r=hu(ke,e,{title:t?.title,parentId:t?.parent_id});return{...r,version:$t(ke,r.id)}},moveDocument:(e,t,r)=>Cs(ke,e,t,r),listDocumentRevisions:(e)=>Dm(ke,e),documentAtVersion:(e,t)=>Ec(ke,e,t),revertDocument:(e,t,r)=>Om(ke,e,t,{ifMatch:r}),deleteDocument:(e)=>({ok:gu(ke,e)}),siteFile:async(e,t)=>{if((jt.lastSync?.at?Date.now()-jt.lastSync.at:1/0)>pk)await on(!0).catch(()=>{});let n=ke,o;try{o=en(n,e)}catch{return null}let s=Wg(n,o.id,t,{spa:o.spa===1});if(!s)return null;return{...s.row,status:s.status,public:am(n,o).serving}},blobBytes:async(e)=>{let t=await bc(e).catch(()=>{return});if(t)return t.bytes;for(let r of Ir(ke)){if(!r.config)continue;try{let n=await $a(JSON.parse(r.config),e);if(n&&await yc(n,e))return new Uint8Array(n).buffer}catch{}}return null},blobRefs:()=>[...vu(ke)],listSites:()=>{let e=tm(ke);return Hg(ke).map((t)=>({...t,file_count:e.get(t.id)??0}))},listSiteFiles:(e)=>Zg(ke,e),createSite:(e)=>{if(e.visibility==="public")throw new H("invalid_input",Tr("此浏览器通过同步存储桶交换数据、不驻留在线;请在在线主节点管理公开发布"));return{...Vg(ke,e),file_count:0}},updateSite:(e,t)=>{if(t.visibility==="public")throw new H("invalid_input",Tr("此浏览器通过同步存储桶交换数据、不驻留在线;请在在线主节点管理公开发布"));return{...om(ke,e,t),file_count:rm(ke,e)}},deleteSite:async(e)=>{let t=im(ke,e);return await In(ke),{ok:t}},getSiteGrants:(e)=>({grants:br(en(ke,e).public_grants)}),setSiteGrants:(e,t)=>{let r=en(ke,e),n=Jg(ke,r.id,t.tables.length?t:null);return nm(ke,r.id,br(n.public_grants)),{grants:br(n.public_grants)}},siteHosting:()=>({publicBaseUrl:null,scope:null,node:We(ke),pendingRollbacks:[],publishedSites:[],channels:cc(ke)}),revokeSiteChannel:async(e)=>{let t=Tt(),{needsReconcile:r}=_m(t,e);if(r)await In(t);let n=cc(t).find((o)=>o.id===e);if(!n)throw new H("not_found",`no such site channel: ${e}`);return n},putSiteFile:(e,t,r,n)=>{let{content:o,...s}=Yg(ke,e,t,{data:r,contentType:n});return{...s,size:Kg(ke,{encoding:s.encoding,content:o})}},deleteSiteFile:(e,t)=>({ok:em(ke,e,t)}),reset:async()=>{try{D_?.close()}catch{}return ke=null,await zc?.wipeFiles(),O_(),sr({state:"ready",paired:!1,node:We(Tt()),hydrated:void 0,lastSync:void 0}),{ok:!0}},nodes:()=>ls(ke),setNodeLabel:(e,t)=>{let r=Tt(),n=t??We(r);return ml(r,e,n),ls(r).find((o)=>o.node_id===n)},search:(e,t)=>i_(ke,e,{limit:t}),resolve:(e,t)=>Ql(ke,e,{limit:t})},_k=/^(create|update|delete|move|duplicate|revert|add|remove|set|put)/,Vi=null;function yk(){if(Vi)clearTimeout(Vi);Vi=setTimeout(()=>{if(Vi=null,navigator.onLine!==!1)on()},800)}self.onmessage=async(e)=>{let{id:t,op:r,args:n}=e.data;try{await ik;let o=P_[r];if(!o)throw new H("invalid_input",`unknown op: ${r}`);let s=await o(...n??[]);if(Ji({id:t,ok:!0,result:s}),_k.test(r))lk(),yk()}catch(o){let s=o instanceof Error?o.message:String(o),a=fn(o)??void 0;Ji({id:t,ok:!1,error:{message:s,code:a}})}};