@tensorix/metahub 0.5.8 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (120) hide show
  1. package/README.md +35 -14
  2. package/README.zh-CN.md +41 -13
  3. package/dist/cli.js +5175 -2272
  4. package/dist/cli.js.map +69 -48
  5. package/dist/core/blobs.d.ts.map +1 -1
  6. package/dist/core/blocks.d.ts +6 -2
  7. package/dist/core/blocks.d.ts.map +1 -1
  8. package/dist/core/compact.d.ts.map +1 -1
  9. package/dist/core/crdt.d.ts +5 -6
  10. package/dist/core/crdt.d.ts.map +1 -1
  11. package/dist/core/db.d.ts.map +1 -1
  12. package/dist/core/documents.d.ts +39 -0
  13. package/dist/core/documents.d.ts.map +1 -1
  14. package/dist/core/errors.d.ts +6 -1
  15. package/dist/core/errors.d.ts.map +1 -1
  16. package/dist/core/history-archive.d.ts +41 -0
  17. package/dist/core/history-archive.d.ts.map +1 -0
  18. package/dist/core/history.d.ts.map +1 -1
  19. package/dist/core/hlc.d.ts +4 -0
  20. package/dist/core/hlc.d.ts.map +1 -1
  21. package/dist/core/node.d.ts.map +1 -1
  22. package/dist/core/properties.d.ts +6 -0
  23. package/dist/core/properties.d.ts.map +1 -1
  24. package/dist/core/replica/drafts.d.ts +26 -0
  25. package/dist/core/replica/drafts.d.ts.map +1 -0
  26. package/dist/core/replica/rpc.d.ts +8 -0
  27. package/dist/core/replica/rpc.d.ts.map +1 -0
  28. package/dist/core/replica/service.d.ts +970 -0
  29. package/dist/core/replica/service.d.ts.map +1 -0
  30. package/dist/core/replica/sync.d.ts +55 -0
  31. package/dist/core/replica/sync.d.ts.map +1 -0
  32. package/dist/core/schema-init.d.ts +1 -1
  33. package/dist/core/schema-init.d.ts.map +1 -1
  34. package/dist/core/search.d.ts +34 -0
  35. package/dist/core/search.d.ts.map +1 -1
  36. package/dist/core/snapshot.d.ts.map +1 -1
  37. package/dist/core/sync/bucket-v2.d.ts +110 -0
  38. package/dist/core/sync/bucket-v2.d.ts.map +1 -0
  39. package/dist/core/sync/client.d.ts +14 -1
  40. package/dist/core/sync/client.d.ts.map +1 -1
  41. package/dist/core/sync/commit-log.d.ts +41 -0
  42. package/dist/core/sync/commit-log.d.ts.map +1 -0
  43. package/dist/core/sync/current-checkpoint.d.ts +47 -0
  44. package/dist/core/sync/current-checkpoint.d.ts.map +1 -0
  45. package/dist/core/sync/data-map-db.d.ts.map +1 -1
  46. package/dist/core/sync/data-version.d.ts +29 -0
  47. package/dist/core/sync/data-version.d.ts.map +1 -0
  48. package/dist/core/sync/drop-keys.d.ts.map +1 -1
  49. package/dist/core/sync/drop-pull.d.ts.map +1 -1
  50. package/dist/core/sync/e2ee.d.ts +5 -0
  51. package/dist/core/sync/e2ee.d.ts.map +1 -1
  52. package/dist/core/sync/enroll.d.ts +2 -0
  53. package/dist/core/sync/enroll.d.ts.map +1 -1
  54. package/dist/core/sync/history-observation.d.ts +5 -0
  55. package/dist/core/sync/history-observation.d.ts.map +1 -0
  56. package/dist/core/sync/http-status.d.ts.map +1 -1
  57. package/dist/core/sync/page-messages.d.ts +8 -0
  58. package/dist/core/sync/page-messages.d.ts.map +1 -1
  59. package/dist/core/sync/peer-v2.d.ts +9 -0
  60. package/dist/core/sync/peer-v2.d.ts.map +1 -0
  61. package/dist/core/sync/peers.d.ts +1 -0
  62. package/dist/core/sync/peers.d.ts.map +1 -1
  63. package/dist/core/sync/portable-json.d.ts +5 -0
  64. package/dist/core/sync/portable-json.d.ts.map +1 -0
  65. package/dist/core/sync/protocol.d.ts +32 -0
  66. package/dist/core/sync/protocol.d.ts.map +1 -1
  67. package/dist/core/sync/recovery-desktop.d.ts +6 -0
  68. package/dist/core/sync/recovery-desktop.d.ts.map +1 -0
  69. package/dist/core/sync/recovery-intent.d.ts +7 -0
  70. package/dist/core/sync/recovery-intent.d.ts.map +1 -0
  71. package/dist/core/sync/recovery-local.d.ts +21 -0
  72. package/dist/core/sync/recovery-local.d.ts.map +1 -0
  73. package/dist/core/sync/recovery-v2.d.ts +40 -0
  74. package/dist/core/sync/recovery-v2.d.ts.map +1 -0
  75. package/dist/core/sync/retention-executor.d.ts +77 -0
  76. package/dist/core/sync/retention-executor.d.ts.map +1 -0
  77. package/dist/core/sync/retention-protocol.d.ts +74 -0
  78. package/dist/core/sync/retention-protocol.d.ts.map +1 -0
  79. package/dist/core/sync/retention-state.d.ts +87 -0
  80. package/dist/core/sync/retention-state.d.ts.map +1 -0
  81. package/dist/core/sync/routes.d.ts +1 -1
  82. package/dist/core/sync/routes.d.ts.map +1 -1
  83. package/dist/core/sync/server.d.ts +1 -1
  84. package/dist/core/sync/server.d.ts.map +1 -1
  85. package/dist/core/sync/share-export.d.ts.map +1 -1
  86. package/dist/core/sync/share-serve.d.ts.map +1 -1
  87. package/dist/core/sync/share-tools.d.ts +10 -0
  88. package/dist/core/sync/share-tools.d.ts.map +1 -0
  89. package/dist/core/sync/storage-s3-bun.d.ts +2 -1
  90. package/dist/core/sync/storage-s3-bun.d.ts.map +1 -1
  91. package/dist/core/sync/storage-s3-fetch.d.ts +8 -0
  92. package/dist/core/sync/storage-s3-fetch.d.ts.map +1 -0
  93. package/dist/core/sync/storage-s3-sign.d.ts +3 -0
  94. package/dist/core/sync/storage-s3-sign.d.ts.map +1 -1
  95. package/dist/core/sync/storage-v2.d.ts +18 -0
  96. package/dist/core/sync/storage-v2.d.ts.map +1 -0
  97. package/dist/core/sync/storage.d.ts +47 -6
  98. package/dist/core/sync/storage.d.ts.map +1 -1
  99. package/dist/core/sync/transport.d.ts +4 -0
  100. package/dist/core/sync/transport.d.ts.map +1 -0
  101. package/dist/core/sync/v2-ingest.d.ts +10 -0
  102. package/dist/core/sync/v2-ingest.d.ts.map +1 -0
  103. package/dist/core/sync/v2-maintenance.d.ts +10 -0
  104. package/dist/core/sync/v2-maintenance.d.ts.map +1 -0
  105. package/dist/db-worker.js +212 -160
  106. package/dist/edge-worker.js +4952 -186
  107. package/dist/index.js +9243 -6455
  108. package/dist/index.js.map +67 -47
  109. package/dist/metahub-sdk.js +5 -5
  110. package/dist/mh-runtime.js +2 -2
  111. package/dist/shared/views/date.d.ts +21 -0
  112. package/dist/shared/views/date.d.ts.map +1 -0
  113. package/dist/shared/views/model.d.ts +65 -0
  114. package/dist/shared/views/model.d.ts.map +1 -0
  115. package/dist/shared/views/query.d.ts +47 -0
  116. package/dist/shared/views/query.d.ts.map +1 -0
  117. package/dist/sw.js +9 -9
  118. package/dist/webui/server/routes.d.ts.map +1 -1
  119. package/dist/webui.js +131 -131
  120. package/package.json +1 -1
package/dist/db-worker.js CHANGED
@@ -1,4 +1,124 @@
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=`
1
+ var Oe=(e,t,r)=>()=>{if(e)try{t=e(e=0)}catch(n){r=[n]}if(r)throw r[0];return t};function Ve(e,t){let r=e.transaction(t);return(r.immediate??r)()}function Xv(e,t){return t?e.replace(/\{(\w+)\}/g,(r,n)=>(n in t)?String(t[n]):r):e}function Ua(e,t,r){return new T(e,Xv(t,r),{key:t,params:r})}function Qv(e){if(!(e instanceof Error))return!1;let t=e.code;if(typeof t==="string"&&Yv.test(t))return!0;return e.message==="database is locked"}function eE(e){if(e instanceof T)return e;let t=e instanceof Error&&/^client_update_required:(\d+):(\d+)$/.exec(e.message);if(t)return new Zi(Number(t[1]),Number(t[2]));if(Qv(e))return Ua("busy","数据库正被另一个进程写入,请稍后重试");return null}function pn(e){return eE(e)?.code}var T,Zi,Yv;var Ke=Oe(()=>{T=class T extends Error{code;i18n;constructor(e,t,r){super(t);this.code=e;this.i18n=r;this.name="MhError"}};Zi=class Zi extends T{workspaceDataVersion;clientMaxDataVersion;constructor(e,t){super("client_update_required",`需要更新客户端:工作区数据版本为 ${e},本客户端最高支持 ${t}。`,{key:"需要更新客户端:工作区数据版本为 {workspaceDataVersion},本客户端最高支持 {clientMaxDataVersion}。",params:{workspaceDataVersion:e,clientMaxDataVersion:t}});this.workspaceDataVersion=e;this.clientMaxDataVersion=t}};Yv=/^SQLITE_(BUSY|LOCKED)/});var tE,Gi=(e)=>Object.entries(tE).filter(([,t])=>e(t)).map(([t])=>t),hd,TT,gd,DT;var Ba=Oe(()=>{tE={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}},hd=Gi((e)=>e.synced),TT=Gi((e)=>e.tier==="content"),gd=Gi((e)=>e.tier==="system"),DT=Gi((e)=>e.tier==="local")});function Ot(e){let t=e.query("SELECT value FROM meta WHERE key=?").get(md);if(!t)return null;let r=JSON.parse(t.value);if(!r||typeof r.workspaceId!=="string"||!r.workspaceId||!Number.isSafeInteger(r.dataVersion)||r.dataVersion<2)throw new T("invalid_input","Invalid saved workspace data version");return r}function lr(e,t=Number(vr.maxSupportedDataVersion),r=Number(vr.minSupportedDataVersion)){if(!Number.isSafeInteger(e)||e<1)throw new T("invalid_input","Invalid workspace data version");if(!Number.isSafeInteger(t)||!Number.isSafeInteger(r)||r<1||t<r)throw new T("invalid_input","Invalid supported data version");if(e>t)throw new Zi(e,t);if(e<r)throw new T("upgrade_required","Workspace data version requires migration")}function Xr(e){return Ot(e)?.dataVersion??(e.query("SELECT 1 FROM meta WHERE key='sync_v2_generation'").get()?2:1)}function ja(e,t){if(Ot(e)||e.query("SELECT 1 FROM meta WHERE key IN (?, 'sync_v2_generation')").get(`sync_verified_peer:${t}`))return;if(e.query("SELECT 1 FROM peers WHERE url=? AND last_success_at IS NOT NULL").get(t))return;if(e.query("SELECT 1 FROM crdt_changes WHERE dataset<>'nodes' LIMIT 1").get())return;e.query("INSERT OR IGNORE INTO meta(key,value) VALUES('sync_version_pending_join',?)").run(t)}function Ko(e,t){Ve(e,()=>{if(e.query("DELETE FROM meta WHERE key='sync_version_pending_join' AND value=?").run(t).changes)e.query("INSERT OR REPLACE INTO meta(key,value) VALUES(?, '1')").run(`sync_verified_peer:${t}`)})}function _d(e){if(Qt(e),e.query("SELECT 1 FROM meta WHERE key='sync_version_pending_join'").get())throw new T("busy","请先联网确认工作区版本")}function Qt(e){let t=Ot(e);if(lr(t?.dataVersion??2),t?.awaitingCompatibleClient)throw new T("busy","请先联网确认工作区版本")}function yd(e,t,r){if(!Number.isSafeInteger(r)||r<2)throw new T("invalid_input","Invalid workspace data version");Ve(e,()=>{let n=Ot(e);if(n&&n.workspaceId!==t)throw new T("conflict","Workspace identity mismatch");if(n&&n.dataVersion>r)return;let o=r>vr.maxSupportedDataVersion;if(n?.dataVersion===r&&!!n.awaitingCompatibleClient===o)return;if(e.query("INSERT OR REPLACE INTO meta(key,value) VALUES(?,?)").run(md,JSON.stringify({workspaceId:t,dataVersion:r,awaitingCompatibleClient:o})),o||n?.awaitingCompatibleClient)for(let i of[...hd,"crdt_changes"]){if(!e.query("SELECT 1 FROM sqlite_master WHERE type='table' AND name=?").get(i))continue;for(let s of["INSERT","UPDATE","DELETE"]){let c=`version_lock_${i}_${s}`;if(e.exec(`DROP TRIGGER IF EXISTS ${c}`),o)e.exec(`CREATE TRIGGER ${c} BEFORE ${s} ON ${i} BEGIN SELECT RAISE(ABORT,'client_update_required:${r}:${vr.maxSupportedDataVersion}'); END`)}}})}function In(e,t,r){yd(e,t,r),Qt(e)}function bd(e){let t=Ot(e);if(!t)return!1;if(t.dataVersion>vr.maxSupportedDataVersion){if(!t.awaitingCompatibleClient)yd(e,t.workspaceId,t.dataVersion);return!0}return!!t.awaitingCompatibleClient}function wd(e,t){if((Ot(e)?.dataVersion??2)<=vr.maxSupportedDataVersion)throw new T("conflict","Workspace is not version locked");e.exec("CREATE TABLE IF NOT EXISTS sync_version_drafts(editor TEXT PRIMARY KEY, doc_id TEXT NOT NULL, title TEXT NOT NULL, body TEXT NOT NULL, version TEXT)"),e.query("INSERT OR REPLACE INTO sync_version_drafts(editor,doc_id,title,body,version) VALUES(?,?,?,?,?)").run(t.editor,t.doc_id,t.title,t.body,t.version)}var vr,md="sync_workspace_data_version";var er=Oe(()=>{Ba();Ke();vr={minSupportedDataVersion:1,maxSupportedDataVersion:2}});function fo(e,t,r){if(!Number.isSafeInteger(r)||r<0)throw new T("clock_skew","invalid history observation time");e.exec(`CREATE TABLE IF NOT EXISTS sync_history_observations (
2
+ dataset TEXT NOT NULL,row_id TEXT NOT NULL,col TEXT NOT NULL,hlc TEXT NOT NULL,at INTEGER NOT NULL,
3
+ PRIMARY KEY(dataset,row_id,col,hlc))`);let n=e.query(`INSERT INTO sync_history_observations(dataset,row_id,col,hlc,at) VALUES(?,?,?,?,?)
4
+ ON CONFLICT(dataset,row_id,col,hlc) DO UPDATE SET at=MIN(at,excluded.at)`);for(let o of t)n.run(o.dataset,o.row_id,o.col,o.hlc,r)}var Mr=(e)=>JSON.stringify([e.dataset,e.row_id,e.col,e.hlc]);var ho=Oe(()=>{Ke()});function Wt(e=6){let t=crypto.getRandomValues(new Uint8Array(e)),r="";for(let n of t)r+="0123456789abcdefghijklmnopqrstuvwxyz".charAt(n%36);return r}function Ha(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 ur(e,t,r=e){return`${e}_${Ha(t,r)}-${Wt()}`}function go(e){let t=e.indexOf("_");if(t<=0)return null;let r=e.slice(0,t);return rE.has(r)?r:null}var rE;var Vt=Oe(()=>{rE=new Set(["db","prop","rec","doc","blk","site","sf","chan"])});function Je(e){let t=e.query("SELECT value FROM meta WHERE key = 'node_id'").get();if(t)return t.value;let r=Wt(8);return e.query("INSERT INTO meta (key, value) VALUES ('node_id', ?)").run(r),r}function Jo(e,t){let r=e.query(`SELECT ${vd} FROM nodes WHERE id = ? AND __deleted = 0`).get(t);return r?Ed(r):null}function nE(e){return e.query(`SELECT ${vd} FROM nodes WHERE __deleted = 0`).all().map(Ed)}function Sd(e){return e.query("SELECT value FROM meta WHERE key = 'node_label'").get()?.value??null}function oE(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 Wa(e,t){let r=Jo(e,t)?.label;if(r)return r;let n=e.query("SELECT label FROM peers WHERE node_id = ? AND label IS NOT NULL AND label <> '' LIMIT 1").get(t);if(n?.label)return n.label;return t===Je(e)?Sd(e):null}function kd(e){return Wa(e,Je(e))}function xd(e,t,r){let n=r??Je(e),o=t==null||t.trim()===""?null:t.trim(),i=Jo(e,n);if(n===Je(e))oE(e,o);if(i&&i.label===o)return;if(!i&&o==null)return;Ar(e,"node",()=>{_e(e,"nodes",n,"label",o)})}function Rd(e,t={}){let r=Je(e),n=Jo(e,r);if(Ot(e)?.awaitingCompatibleClient||e.query("SELECT 1 FROM meta WHERE key='sync_version_pending_join'").get())return n??{node_id:r,label:null,platform:null,form:null,app:null,first_seen:null};let 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 i=Sd(e)??t.defaultLabel??null;if(i)o.label=i}if(Object.keys(o).length>0)Ar(e,"node",()=>{for(let[i,s]of Object.entries(o))_e(e,"nodes",r,i,s)});return Jo(e,r)}function Va(e){let t=Je(e),r=new Set([t]);for(let i of nE(e))r.add(i.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 i of n)r.add(i.node_id);let o=[...r].map((i)=>{let s=Jo(e,i);return{node_id:i,label:Wa(e,i),self:i===t,platform:s?.platform??null,form:s?.form??null,app:s?.app??null}});return o.sort((i,s)=>Number(s.self)-Number(i.self)),o}var vd="id, label, platform, form, app, first_seen",Ed=(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 Zt=Oe(()=>{er();Vt();it()});function Ji(e){return Xi({millis:e+Nn,counter:Ki,node:"~~~~~~~~"})}function Td(e,t){return e>Ji(t)}function Za(e,t){if(t<=Ki)return{millis:e,counter:t};return{millis:e+Math.floor(t/(Ki+1)),counter:t%(Ki+1)}}function Xi(e){let{millis:t,counter:r}=Za(e.millis,e.counter);return`${String(t).padStart(15,"0")}-${r.toString(16).padStart(4,"0")}-${e.node}`}function Yi(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 Dd(e,t){let r=e.query("SELECT value FROM meta WHERE key = 'hlc'").get();return r?Yi(r.value):{millis:0,counter:0,node:t}}function Ga(e,t){e.query("INSERT INTO meta (key, value) VALUES ('hlc', ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(Xi(t))}function Qi(e,t,r=Date.now()){let n=Dd(e,t);if(n.millis>r+Nn)throw Ua("clock_skew","本机逻辑时钟比系统时间超前 {min} 分钟(系统时钟曾被调错,或收到过时钟错误设备的数据),运行 mh repair --clock 修复",{min:Math.ceil((n.millis-r)/60000)});let o=Math.max(n.millis,r),i=o===n.millis?n.counter+1:0,s={...Za(o,i),node:t};return Ga(e,s),Xi(s)}function Ad(e,t,r,n=Date.now()){let o=Dd(e,t),i=!1;for(let s of r){let c=Yi(s);if(!Number.isFinite(c.millis)||!Number.isFinite(c.counter))continue;if(c.millis>n+Nn)continue;let l=Math.max(o.millis,c.millis,n),u;if(l===o.millis&&l===c.millis)u=Math.max(o.counter,c.counter)+1;else if(l===o.millis)u=o.counter+1;else if(l===c.millis)u=c.counter+1;else u=0;o={...Za(l,u),node:t},i=!0}if(i)Ga(e,o)}function Ka(e){let t=e.query("SELECT value FROM meta WHERE key = 'hlc'").get();return t?Yi(t.value):null}function Od(e,t,r=Date.now()){Ga(e,{millis:r,counter:0,node:t})}var Ki=65535,Nn=300000;var es=Oe(()=>{Ke()});function Pn(e){if(!e)return[];let t=e.replace(/\r\n?/g,`
5
+ `).split(`
6
+ `),r=[],n=[],o=null,i=0,s=()=>{if(n.length)r.push({text:n.join(`
7
+ `),blankAfter:0}),n=[]},c=()=>{if(s(),r.length)r[r.length-1].blankAfter++};for(let l of t){if(o){n.push(l);let f=l.match(/^\s*(`{3,}|~{3,})\s*$/);if(f&&f[1][0]===o&&f[1].length>=i)s(),o=null,i=0;continue}let u=l.match(/^\s*(`{3,}|~{3,})/);if(u)s(),o=u[1][0],i=u[1].length,n.push(l);else if(l.trim()==="")c();else n.push(l)}s();for(let l=0;l<r.length-1;l++)r[l].blankAfter=Math.max(0,r[l].blankAfter-1);return r}function qn(e){let t=e.filter((n)=>!!n.text&&n.text.length>0),r=[];return t.forEach((n,o)=>{r.push(...n.text.split(`
8
+ `));let i=Math.max(0,n.blankAfter??0);if(o<t.length-1)r.push("");for(let s=0;s<i;s++)r.push("")}),r.join(`
9
+ `)}function Cd(e,t,r={}){let n=iE(e,t),o=new Set(n.map((l)=>l[0])),i=new Map(n.map((l)=>[l[1],l[0]]));if(r.preserveReplacements){let l=[[-1,-1],...n,[e.length,t.length]];for(let u=1;u<l.length;u++){let[f,_]=l[u-1],[E,g]=l[u];if(E-f===2&&g-_===2)o.add(f+1),i.set(_+1,f+1)}}let s=t.map((l,u)=>i.has(u)?{keep:i.get(u)}:{insert:l}),c=[];for(let l=0;l<e.length;l++)if(!o.has(l))c.push(l);return{items:s,deleted:c}}function iE(e,t){let r=e.length,n=t.length,o=Array.from({length:r+1},()=>Array(n+1).fill(0));for(let l=r-1;l>=0;l--)for(let u=n-1;u>=0;u--)o[l][u]=e[l]===t[u]?o[l+1][u+1]+1:Math.max(o[l+1][u],o[l][u+1]);let i=[],s=0,c=0;while(s<r&&c<n)if(e[s]===t[c])i.push([s,c]),s++,c++;else if(o[s+1][c]>=o[s][c+1])s++;else c++;return i}function sE(e){let t=Yo.get(e);if(!t)t={docs:new Map,blockToDoc:new Map},Yo.set(e,t);return t}function Xo(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 Id(e,t){let r=Yo.get(e),n=r?.docs.get(t);if(!r||!n)return;return r.docs.delete(t),r.docs.set(t,n),n}function Nd(e,t,r,n){let o=sE(e);Xo(o,t);let i={changes:r,blockIds:new Set(n),revisions:null,states:new Map};o.docs.set(t,i);for(let s of i.blockIds)o.blockToDoc.set(s,t);while(o.docs.size>16)Xo(o,o.docs.keys().next().value);return i}function Pd(e,t,r){if(e.states.size>=64)e.states.delete(e.states.keys().next().value);e.states.set(t,r)}function Ja(e,t,r,n,o){let i=Yo.get(e);if(!i)return;if(t==="documents"){Xo(i,r);return}if(t!=="doc_blocks")return;let s=i.blockToDoc.get(r);if(s)Xo(i,s);if(n==="doc_id"&&o)try{let c=JSON.parse(o);if(typeof c==="string")Xo(i,c)}catch{}}function mo(e){Yo.delete(e)}var Yo;var Ln=Oe(()=>{Yo=new WeakMap});function aE(e){return Math.max(0,Math.trunc(Number.isFinite(e)?e:Date.now()))}function $n(e=Date.now()){let t=Math.max(0,aE(e)-2678400000);return String(t).padStart(15,"0")+"-"}function ts(e,t=Date.now()){return e.dataset==="intent_receipts"&&e.hlc<$n(t)}function Xa(e,t=Date.now()){return e.filter((r)=>!ts(r,t))}function _o(e,t=Date.now()){return e.query("DELETE FROM crdt_changes WHERE dataset = 'intent_receipts' AND hlc < ?").run($n(t)).changes}var fn="intent_receipts";function Ar(e,t,r){if(ei!==null)return r();ei=(qd?qd+"/":"")+(t?t+":":"")+Wt(8);try{return Ve(e,r)}finally{ei=null}}function We(e,t=null){return(r,...n)=>Ar(r,t,()=>e(r,...n))}function Ld(e,t,r){if(r!==null)return JSON.parse(r);return lE.has(`${e}:${t}`)?0:null}function $d(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 Qo(e,t,r){e.query(`INSERT OR IGNORE INTO ${t} (id) VALUES (?)`).run(r)}function Qa(e,t){if(e.query("SELECT 1 FROM meta WHERE key=?").get(`sync_v2_managed:${t}`))return!0;return e.query("SELECT 1 AS x FROM doc_blocks WHERE doc_id = ? LIMIT 1").get(t)!=null}function uE(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);Qo(e,"documents",t),e.query("UPDATE documents SET body = ? WHERE id = ?").run(qn(r.map((n)=>({text:n.text,blankAfter:n.blank_after??0}))),t)}function dE(e,t,r,n,o){if(ns.has(t))return;if(t==="records"){if(Ya.has(n)){Qo(e,"records",r);let c=Ld("records",n,o);e.query(`UPDATE records SET "${n}" = ? WHERE id = ?`).run($d(c),r)}else if(Qo(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.")){Qo(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 i=Fd[t];if(!i||!i.cols.has(n))return;if(t==="documents"&&n==="body"&&Qa(e,r))return;Qo(e,i.table,r);let s=Ld(t,n,o);if(e.query(`UPDATE ${i.table} SET "${n}" = ? WHERE id = ?`).run($d(s),r),t==="doc_blocks"){let c=e.query("SELECT doc_id FROM doc_blocks WHERE id = ?").get(r);if(c?.doc_id)uE(e,c.doc_id)}}function zd(e,t,r){let n=e.query("INSERT OR IGNORE INTO crdt_changes (hlc, node_id, dataset, row_id, col, value, txn) VALUES (?, ?, ?, ?, ?, ?, ?)").run(t.hlc,t.node_id,t.dataset,t.row_id,t.col,t.value,t.txn??null).changes>0;if(!n&&!r)return{inserted:!1,winner:!1};let o=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(n)Ja(e,t.dataset,t.row_id,t.col,t.value);if(o.h!==t.hlc)return{inserted:n,winner:!1};try{dE(e,t.dataset,t.row_id,t.col,t.value)}catch(i){if(n)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 i}return{inserted:n,winner:!0}}function yo(e,t){return zd(e,t,!0)}function _e(e,t,r,n,o){_d(e);let i=()=>{let s=cE??Je(e),c={hlc:Qi(e,s),node_id:s,dataset:t,row_id:r,col:n,value:o===void 0?null:JSON.stringify(o),txn:ei};if(e.query("SELECT 1 FROM meta WHERE key='sync_v2_generation'").get()){let l=e.query("SELECT MAX(hlc) AS h FROM crdt_changes WHERE dataset=? AND row_id=? AND col=?").get(t,r,t==="doc_blocks"&&n==="__deleted"&&o===1?"text":n);e.query("INSERT OR REPLACE INTO meta(key,value) VALUES(?,?)").run(`sync_v2_base:${c.hlc}:${t}:${r}:${n}`,JSON.stringify(l.h))}return yo(e,c),c};return ei!==null?i():Ve(e,i)}function ti(e,t,r={}){return Fr(e,t,r).received}function Fr(e,t,r={}){Qt(e);let n=r.now??Date.now();_o(e,n);let o=Je(e),i=0,s=0,c={};if(Ve(e,()=>{let u=[];for(let f of t){if(ts(f,n))continue;if(Td(f.hlc,n)){c[f.node_id]=(c[f.node_id]??0)+1;continue}u.push(f.hlc);try{if(zd(e,f,!1).inserted)i++}catch(_){let E=_ instanceof Error?_.message:String(_),g=_ instanceof SyntaxError,A=/(?:NOT NULL|UNIQUE|CHECK|FOREIGN KEY) constraint failed(?:[: ]|$)|datatype mismatch|malformed JSON|JSON path error near/i.test(E);if(!g&&!A)throw _;s++,console.error(`[ingest] skipped a change that failed to apply (dataset=${f.dataset} col=${f.col} row=${f.row_id}): ${_.message}`)}}if(u.length)Ad(e,o,u,n)}),s)console.error(`[ingest] ${s} change(s) skipped this batch (see above)`);for(let[u,f]of Object.entries(c))console.error(`[ingest] refused ${f} change(s) from node ${u}: stamped more than 5 min in the future (that device should run mh repair --clock)`);return{received:i,skewed:c,...s?{poisoned:s}:{}}}function Lt(e,t,r={}){let n=r.excludeDatasets??[],o=["rowid > ?"],i=[t];if(n.length)o.push(`dataset NOT IN (${n.map(()=>"?").join(", ")})`),i.push(...n);if(r.onlyNode!=null)o.push("node_id = ?"),i.push(r.onlyNode);o.push("(dataset != ? OR hlc >= ?)"),i.push(fn,$n(r.now??Date.now()));let s=o.join(" AND "),c=r.limit!=null&&r.limit>0?` LIMIT ${Math.floor(r.limit)}`:"",l=e.query(`SELECT rowid AS seq, ${vt} FROM crdt_changes WHERE ${s} ORDER BY rowid${c}`).all(...i),u=r.limit==null||r.limit<=0||l.length<r.limit,f;if(u){let _=e.query("SELECT MAX(rowid) AS m FROM crdt_changes").get();f=Math.max(t,_.m??t)}else f=l[l.length-1].seq;return{changes:l.map(({seq:_,...E})=>E),cursor:f}}var rs,vt,ei=null,qd=null,Md,cE=null,Fd,Ya,ns,lE;var it=Oe(()=>{er();Zt();es();Vt();Ln();rs=["hlc","node_id","dataset","row_id","col","value","txn"],vt=rs.join(", "),Md=/^[a-z0-9_-]{1,16}$/;Fd={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"])}},Ya=new Set(["database_id","created_hlc","order_key","__deleted"]),ns=new Set([fn]),lE=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 he(e,t,r){function n(c,l){if(!c._zod)Object.defineProperty(c,"_zod",{value:{def:l,constr:s,traits:new Set},enumerable:!1});if(c._zod.traits.has(e))return;c._zod.traits.add(e),t(c,l);let u=s.prototype,f=Object.keys(u);for(let _=0;_<f.length;_++){let E=f[_];if(!(E in c))c[E]=u[E].bind(c)}}let o=r?.Parent??Object;class i extends o{}Object.defineProperty(i,"name",{value:e});function s(c){var l;let u=r?.Parent?new i:this;n(u,c),(l=u._zod).deferred??(l.deferred=[]);for(let f of u._zod.deferred)f();return u}return Object.defineProperty(s,"init",{value:n}),Object.defineProperty(s,Symbol.hasInstance,{value:(c)=>{if(r?.Parent&&c instanceof r.Parent)return!0;return c?._zod?.traits?.has(e)}}),Object.defineProperty(s,"name",{value:e}),s}function gr(e){if(e)Object.assign(bo,e);return bo}var Ud,tD,Yr,ri,bo;var Mn=Oe(()=>{tD=Symbol("zod_brand");Yr=class Yr extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}};ri=class ri extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`);this.name="ZodEncodeError"}};(Ud=globalThis).__zod_globalConfig??(Ud.__zod_globalConfig={});bo=globalThis.__zod_globalConfig});function is(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 tc(e,t="|"){return e.map((r)=>ic(r)).join(t)}function ni(e,t){if(typeof t==="bigint")return t.toString();return t}function oi(e){return{get value(){{let r=e();return Object.defineProperty(this,"value",{value:r}),r}throw Error("cached value already set")}}}function ss(e){return e===null||e===void 0}function as(e){let t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function jd(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 st(e,t,r){let n=void 0;Object.defineProperty(e,t,{get(){if(n===Bd)return;if(n===void 0)n=Bd,n=r();return n},set(o){Object.defineProperty(e,t,{value:o})},configurable:!0})}function Fn(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function hn(...e){let t={};for(let r of e){let n=Object.getOwnPropertyDescriptors(r);Object.assign(t,n)}return Object.defineProperties({},t)}function rc(e){return JSON.stringify(e)}function Hd(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}function wo(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function zn(e){if(wo(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(wo(r)===!1)return!1;if(Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)return!1;return!0}function oc(e){if(zn(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 gn(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function zr(e,t,r){let n=new e._zod.constr(t??e._zod.def);if(!t||r?.parent)n._zod.parent=e;return n}function Fe(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 ic(e){if(typeof e==="bigint")return e.toString()+"n";if(typeof e==="string")return`"${e}"`;return`${e}`}function Zd(e){return Object.keys(e).filter((t)=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}function pE(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 i=hn(e._zod.def,{get shape(){let s={};for(let c in t){if(!(c in r.shape))throw Error(`Unrecognized key: "${c}"`);if(!t[c])continue;s[c]=r.shape[c]}return Fn(this,"shape",s),s},checks:[]});return zr(e,i)}function fE(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 i=hn(e._zod.def,{get shape(){let s={...e._zod.def.shape};for(let c in t){if(!(c in r.shape))throw Error(`Unrecognized key: "${c}"`);if(!t[c])continue;delete s[c]}return Fn(this,"shape",s),s},checks:[]});return zr(e,i)}function hE(e,t){if(!zn(t))throw Error("Invalid input to extend: expected a plain object");let r=e._zod.def.checks;if(r&&r.length>0){let i=e._zod.def.shape;for(let s in t)if(Object.getOwnPropertyDescriptor(i,s)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let o=hn(e._zod.def,{get shape(){let i={...e._zod.def.shape,...t};return Fn(this,"shape",i),i}});return zr(e,o)}function gE(e,t){if(!zn(t))throw Error("Invalid input to safeExtend: expected a plain object");let r=hn(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return Fn(this,"shape",n),n}});return zr(e,r)}function mE(e,t){if(e._zod.def.checks?.length)throw Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let r=hn(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t._zod.def.shape};return Fn(this,"shape",n),n},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return zr(e,r)}function _E(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 s=hn(t._zod.def,{get shape(){let c=t._zod.def.shape,l={...c};if(r)for(let u in r){if(!(u in c))throw Error(`Unrecognized key: "${u}"`);if(!r[u])continue;l[u]=e?new e({type:"optional",innerType:c[u]}):c[u]}else for(let u in c)l[u]=e?new e({type:"optional",innerType:c[u]}):c[u];return Fn(this,"shape",l),l},checks:[]});return zr(t,s)}function yE(e,t,r){let n=hn(t._zod.def,{get shape(){let o=t._zod.def.shape,i={...o};if(r)for(let s in r){if(!(s in i))throw Error(`Unrecognized key: "${s}"`);if(!r[s])continue;i[s]=new e({type:"nonoptional",innerType:o[s]})}else for(let s in o)i[s]=new e({type:"nonoptional",innerType:o[s]});return Fn(this,"shape",i),i}});return zr(t,n)}function Un(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 Kd(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 mn(e,t){return t.map((r)=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(e),r})}function os(e){return typeof e==="string"?e:e?.message}function Or(e,t,r){let n=e.message?e.message:os(e.inst?._zod.def?.error?.(e))??os(t?.error?.(e))??os(r.customError?.(e))??os(r.localeError?.(e))??"Invalid input",{inst:o,continue:i,input:s,...c}=e;if(c.path??(c.path=[]),c.message=n,t?.reportInput)c.input=s;return c}function cs(e){if(Array.isArray(e))return"array";if(typeof e==="string")return"string";return"unknown"}function Jd(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 Bn(...e){let[t,r,n]=e;if(typeof t==="string")return{message:t,code:"custom",input:r,inst:n};return{...t}}var Bd,nc,Wd,Vd,Gd;var Cr=Oe(()=>{Mn();Bd=Symbol("evaluating");nc="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};Wd=oi(()=>{if(bo.jitless)return!1;if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(e){return!1}});Vd=new Set(["string","number","symbol"]);Gd={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 Yd(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 Qd(e,t=(r)=>r.message){let r={_errors:[]},n=(o,i=[])=>{for(let s of o.issues)if(s.code==="invalid_union"&&s.errors.length)s.errors.map((c)=>n({issues:c},[...i,...s.path]));else if(s.code==="invalid_key")n({issues:s.issues},[...i,...s.path]);else if(s.code==="invalid_element")n({issues:s.issues},[...i,...s.path]);else{let c=[...i,...s.path];if(c.length===0)r._errors.push(t(s));else{let l=r,u=0;while(u<c.length){let f=c[u];if(u!==c.length-1)l[f]=l[f]||{_errors:[]};else l[f]=l[f]||{_errors:[]},l[f]._errors.push(t(s));l=l[f],u++}}}};return n(e),r}var Xd=(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,ni,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},ls,sc;var ac=Oe(()=>{Mn();Cr();ls=he("$ZodError",Xd),sc=he("$ZodError",Xd,{Parent:Error})});var us=(e)=>(t,r,n,o)=>{let i=n?{...n,async:!1}:{async:!1},s=t._zod.run({value:r,issues:[]},i);if(s instanceof Promise)throw new Yr;if(s.issues.length){let c=new(o?.Err??e)(s.issues.map((l)=>Or(l,i,gr())));throw nc(c,o?.callee),c}return s.value},ds=(e)=>async(t,r,n,o)=>{let i=n?{...n,async:!0}:{async:!0},s=t._zod.run({value:r,issues:[]},i);if(s instanceof Promise)s=await s;if(s.issues.length){let c=new(o?.Err??e)(s.issues.map((l)=>Or(l,i,gr())));throw nc(c,o?.callee),c}return s.value},ii=(e)=>(t,r,n)=>{let o=n?{...n,async:!1}:{async:!1},i=t._zod.run({value:r,issues:[]},o);if(i instanceof Promise)throw new Yr;return i.issues.length?{success:!1,error:new(e??ls)(i.issues.map((s)=>Or(s,o,gr())))}:{success:!0,data:i.value}},ep,si=(e)=>async(t,r,n)=>{let o=n?{...n,async:!0}:{async:!0},i=t._zod.run({value:r,issues:[]},o);if(i instanceof Promise)i=await i;return i.issues.length?{success:!1,error:new e(i.issues.map((s)=>Or(s,o,gr())))}:{success:!0,data:i.value}},tp,rp=(e)=>(t,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return us(e)(t,r,o)},np=(e)=>(t,r,n)=>us(e)(t,r,n),op=(e)=>async(t,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return ds(e)(t,r,o)},ip=(e)=>async(t,r,n)=>ds(e)(t,r,n),sp=(e)=>(t,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return ii(e)(t,r,o)},ap=(e)=>(t,r,n)=>ii(e)(t,r,n),cp=(e)=>async(t,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return si(e)(t,r,o)},lp=(e)=>async(t,r,n)=>si(e)(t,r,n);var cc=Oe(()=>{Mn();ac();Cr();ep=ii(sc),tp=si(sc)});function bp(){return new RegExp(wE,"u")}function Ap(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 Op(e){return new RegExp(`^${Ap(e)}$`)}function Cp(e){let t=Ap({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(`^${Tp}T(?:${n})$`)}var up,dp,pp,fp,hp,gp,mp,_p,lc=(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})$`)},yp,wE="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",wp,vp,Ep,Sp,kp,uc,xp,Rp,Tp="(?:(?:\\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])))",Dp,Ip=(e)=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},Np,dc,Pp,qp,Lp;var fs=Oe(()=>{up=/^[cC][0-9a-z]{6,}$/,dp=/^[0-9a-z]+$/,pp=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,fp=/^[0-9a-vA-V]{20}$/,hp=/^[A-Za-z0-9]{27}$/,gp=/^[a-zA-Z0-9_-]{21}$/,mp=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,_p=/^([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})$/,yp=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;wp=/^(?:(?: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])$/,vp=/^(([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}|:))$/,Ep=/^((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])$/,Sp=/^(([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])$/,kp=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,uc=/^[A-Za-z0-9_-]*$/,xp=/^https?$/,Rp=/^\+[1-9]\d{6,14}$/,Dp=new RegExp(`^${Tp}$`);Np=/^-?\d+$/,dc=/^-?\d+(?:\.\d+)?$/,Pp=/^(?:true|false)$/i,qp=/^[^A-Z]*$/,Lp=/^[^a-z]*$/});var zt,$p,pc,fc,Mp,Fp,zp,Up,Bp,ai,jp,Hp,Wp,Vp,Zp,Gp,Kp;var hs=Oe(()=>{Mn();fs();Cr();zt=he("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),$p={number:"number",bigint:"bigint",object:"date"},pc=he("$ZodCheckLessThan",(e,t)=>{zt.init(e,t);let r=$p[typeof t.value];e._zod.onattach.push((n)=>{let o=n._zod.bag,i=(t.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;if(t.value<i)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})}}),fc=he("$ZodCheckGreaterThan",(e,t)=>{zt.init(e,t);let r=$p[typeof t.value];e._zod.onattach.push((n)=>{let o=n._zod.bag,i=(t.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if(t.value>i)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})}}),Mp=he("$ZodCheckMultipleOf",(e,t)=>{zt.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):jd(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})}}),Fp=he("$ZodCheckNumberFormat",(e,t)=>{zt.init(e,t),t.format=t.format||"float64";let r=t.format?.includes("int"),n=r?"int":"number",[o,i]=Gd[t.format];e._zod.onattach.push((s)=>{let c=s._zod.bag;if(c.format=t.format,c.minimum=o,c.maximum=i,r)c.pattern=Np}),e._zod.check=(s)=>{let c=s.value;if(r){if(!Number.isInteger(c)){s.issues.push({expected:n,format:t.format,code:"invalid_type",continue:!1,input:c,inst:e});return}if(!Number.isSafeInteger(c)){if(c>0)s.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 s.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)s.issues.push({origin:"number",input:c,code:"too_small",minimum:o,inclusive:!0,inst:e,continue:!t.abort});if(c>i)s.issues.push({origin:"number",input:c,code:"too_big",maximum:i,inclusive:!0,inst:e,continue:!t.abort})}}),zp=he("$ZodCheckMaxLength",(e,t)=>{var r;zt.init(e,t),(r=e._zod.def).when??(r.when=(n)=>{let o=n.value;return!ss(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 s=cs(o);n.issues.push({origin:s,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),Up=he("$ZodCheckMinLength",(e,t)=>{var r;zt.init(e,t),(r=e._zod.def).when??(r.when=(n)=>{let o=n.value;return!ss(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 s=cs(o);n.issues.push({origin:s,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),Bp=he("$ZodCheckLengthEquals",(e,t)=>{var r;zt.init(e,t),(r=e._zod.def).when??(r.when=(n)=>{let o=n.value;return!ss(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,i=o.length;if(i===t.length)return;let s=cs(o),c=i>t.length;n.issues.push({origin:s,...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})}}),ai=he("$ZodCheckStringFormat",(e,t)=>{var r,n;if(zt.init(e,t),e._zod.onattach.push((o)=>{let i=o._zod.bag;if(i.format=t.format,t.pattern)i.patterns??(i.patterns=new Set),i.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=()=>{})}),jp=he("$ZodCheckRegex",(e,t)=>{ai.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})}}),Hp=he("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=qp),ai.init(e,t)}),Wp=he("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=Lp),ai.init(e,t)}),Vp=he("$ZodCheckIncludes",(e,t)=>{zt.init(e,t);let r=gn(t.includes),n=new RegExp(typeof t.position==="number"?`^.{${t.position}}${r}`:r);t.pattern=n,e._zod.onattach.push((o)=>{let i=o._zod.bag;i.patterns??(i.patterns=new Set),i.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})}}),Zp=he("$ZodCheckStartsWith",(e,t)=>{zt.init(e,t);let r=new RegExp(`^${gn(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})}}),Gp=he("$ZodCheckEndsWith",(e,t)=>{zt.init(e,t);let r=new RegExp(`.*${gn(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})}}),Kp=he("$ZodCheckOverwrite",(e,t)=>{zt.init(e,t),e._zod.check=(r)=>{r.value=t.tx(r.value)}})});class hc{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(`
10
+ `).filter((i)=>i),n=Math.min(...r.map((i)=>i.length-i.trimStart().length)),o=r.map((i)=>i.slice(n)).map((i)=>" ".repeat(this.indent*2)+i);for(let i of o)this.content.push(i)}compile(){let e=Function,t=this?.args,n=[...(this?.content??[""]).map((o)=>` ${o}`)];return new e(...t,n.join(`
11
+ `))}}var Xp;var gc=Oe(()=>{Xp={major:4,minor:4,patch:3}});function Rf(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 vE(e){if(!uc.test(e))return!1;let t=e.replace(/[-_]/g,(n)=>n==="-"?"+":"/"),r=t.padEnd(Math.ceil(t.length/4)*4,"=");return Rf(r)}function EE(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 Yp(e,t,r){if(e.issues.length)t.issues.push(...mn(r,e.issues));t.value[r]=e.value}function ms(e,t,r,n,o,i){let s=r in n;if(e.issues.length){if(o&&i&&!s)return;t.issues.push(...mn(r,e.issues))}if(!s&&!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(s)t.value[r]=void 0}else t.value[r]=e.value}function Lf(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=Zd(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(r)}}function $f(e,t,r,n,o,i){let s=[],c=o.keySet,l=o.catchall._zod,u=l.def.type,f=l.optin==="optional",_=l.optout==="optional";for(let E in t){if(E==="__proto__")continue;if(c.has(E))continue;if(u==="never"){s.push(E);continue}let g=l.run({value:t[E],issues:[]},n);if(g instanceof Promise)e.push(g.then((A)=>ms(A,r,E,t,f,_)));else ms(g,r,E,t,f,_)}if(s.length)r.issues.push({code:"unrecognized_keys",keys:s,input:t,inst:i});if(!e.length)return r;return Promise.all(e).then(()=>r)}function Qp(e,t,r,n){for(let i of e)if(i.issues.length===0)return t.value=i.value,t;let o=e.filter((i)=>!Un(i));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((i)=>i.issues.map((s)=>Or(s,n,gr())))}),t}function mc(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(zn(e)&&zn(t)){let r=Object.keys(t),n=Object.keys(e).filter((i)=>r.indexOf(i)!==-1),o={...e,...t};for(let i of n){let s=mc(e[i],t[i]);if(!s.valid)return{valid:!1,mergeErrorPath:[i,...s.mergeErrorPath]};o[i]=s.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],i=t[n],s=mc(o,i);if(!s.valid)return{valid:!1,mergeErrorPath:[n,...s.mergeErrorPath]};r.push(s.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function ef(e,t,r){let n=new Map,o;for(let c of t.issues)if(c.code==="unrecognized_keys"){o??(o=c);for(let l of c.keys){if(!n.has(l))n.set(l,{});n.get(l).l=!0}}else e.issues.push(c);for(let c of r.issues)if(c.code==="unrecognized_keys")for(let l of c.keys){if(!n.has(l))n.set(l,{});n.get(l).r=!0}else e.issues.push(c);let i=[...n].filter(([,c])=>c.l&&c.r).map(([c])=>c);if(i.length&&o)e.issues.push({...o,keys:i});if(Un(e))return e;let s=mc(t.value,r.value);if(!s.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(s.mergeErrorPath)}`);return e.value=s.data,e}function tf(e,t){if(t===void 0&&(e.issues.length||e.fallback))return{issues:[],value:void 0};return e}function rf(e,t){if(e.value===void 0)e.value=t.defaultValue;return e}function nf(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 gs(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 of(e){return e.value=Object.freeze(e.value),e}function sf(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(Bn(o))}}var bt,_s,mt,af,cf,lf,uf,df,pf,ff,hf,gf,mf,_f,yf,bf,wf,vf,Ef,Sf,kf,xf,Tf,Df,Af,Of,_c,Cf,If,Nf,Pf,qf,SE,Mf,yc,Ff,zf,Uf,Bf,jf,Hf,bc,Wf,Vf,Zf,Gf,Kf,Jf,Xf,Yf,Qf;var eh=Oe(()=>{hs();Mn();cc();fs();Cr();gc();Cr();bt=he("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Xp;let n=[...e._zod.def.checks??[]];if(e._zod.traits.has("$ZodCheck"))n.unshift(e);for(let o of n)for(let i of o._zod.onattach)i(e);if(n.length===0)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let o=(s,c,l)=>{let u=Un(s),f;for(let _ of c){if(_._zod.def.when){if(Kd(s))continue;if(!_._zod.def.when(s))continue}else if(u)continue;let E=s.issues.length,g=_._zod.check(s);if(g instanceof Promise&&l?.async===!1)throw new Yr;if(f||g instanceof Promise)f=(f??Promise.resolve()).then(async()=>{if(await g,s.issues.length===E)return;if(!u)u=Un(s,E)});else{if(s.issues.length===E)continue;if(!u)u=Un(s,E)}}if(f)return f.then(()=>s);return s},i=(s,c,l)=>{if(Un(s))return s.aborted=!0,s;let u=o(c,n,l);if(u instanceof Promise){if(l.async===!1)throw new Yr;return u.then((f)=>e._zod.parse(f,l))}return e._zod.parse(u,l)};e._zod.run=(s,c)=>{if(c.skipChecks)return e._zod.parse(s,c);if(c.direction==="backward"){let u=e._zod.parse({value:s.value,issues:[]},{...c,skipChecks:!0});if(u instanceof Promise)return u.then((f)=>i(f,s,c));return i(u,s,c)}let l=e._zod.parse(s,c);if(l instanceof Promise){if(c.async===!1)throw new Yr;return l.then((u)=>o(u,n,c))}return o(l,n,c)}}st(e,"~standard",()=>({validate:(o)=>{try{let i=ep(e,o);return i.success?{value:i.data}:{issues:i.error?.issues}}catch(i){return tp(e,o).then((s)=>s.success?{value:s.data}:{issues:s.error?.issues})}},vendor:"zod",version:1}))}),_s=he("$ZodString",(e,t)=>{bt.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??Ip(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}}),mt=he("$ZodStringFormat",(e,t)=>{ai.init(e,t),_s.init(e,t)}),af=he("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=_p),mt.init(e,t)}),cf=he("$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=lc(n))}else t.pattern??(t.pattern=lc());mt.init(e,t)}),lf=he("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=yp),mt.init(e,t)}),uf=he("$ZodURL",(e,t)=>{mt.init(e,t),e._zod.check=(r)=>{try{let n=r.value.trim();if(!t.normalize&&t.protocol?.source===xp.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})}}}),df=he("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=bp()),mt.init(e,t)}),pf=he("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=gp),mt.init(e,t)}),ff=he("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=up),mt.init(e,t)}),hf=he("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=dp),mt.init(e,t)}),gf=he("$ZodULID",(e,t)=>{t.pattern??(t.pattern=pp),mt.init(e,t)}),mf=he("$ZodXID",(e,t)=>{t.pattern??(t.pattern=fp),mt.init(e,t)}),_f=he("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=hp),mt.init(e,t)}),yf=he("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=Cp(t)),mt.init(e,t)}),bf=he("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=Dp),mt.init(e,t)}),wf=he("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=Op(t)),mt.init(e,t)}),vf=he("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=mp),mt.init(e,t)}),Ef=he("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=wp),mt.init(e,t),e._zod.bag.format="ipv4"}),Sf=he("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=vp),mt.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})}}}),kf=he("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=Ep),mt.init(e,t)}),xf=he("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=Sp),mt.init(e,t),e._zod.check=(r)=>{let n=r.value.split("/");try{if(n.length!==2)throw Error();let[o,i]=n;if(!i)throw Error();let s=Number(i);if(`${s}`!==i)throw Error();if(s<0||s>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=he("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=kp),mt.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=(r)=>{if(Rf(r.value))return;r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}});Df=he("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=uc),mt.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=(r)=>{if(vE(r.value))return;r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),Af=he("$ZodE164",(e,t)=>{t.pattern??(t.pattern=Rp),mt.init(e,t)});Of=he("$ZodJWT",(e,t)=>{mt.init(e,t),e._zod.check=(r)=>{if(EE(r.value,t.alg))return;r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}}),_c=he("$ZodNumber",(e,t)=>{bt.init(e,t),e._zod.pattern=e._zod.bag.pattern??dc,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=Number(r.value)}catch(s){}let o=r.value;if(typeof o==="number"&&!Number.isNaN(o)&&Number.isFinite(o))return r;let i=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,...i?{received:i}:{}}),r}}),Cf=he("$ZodNumberFormat",(e,t)=>{Fp.init(e,t),_c.init(e,t)}),If=he("$ZodBoolean",(e,t)=>{bt.init(e,t),e._zod.pattern=Pp,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=Boolean(r.value)}catch(i){}let o=r.value;if(typeof o==="boolean")return r;return r.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:e}),r}}),Nf=he("$ZodUnknown",(e,t)=>{bt.init(e,t),e._zod.parse=(r)=>r}),Pf=he("$ZodNever",(e,t)=>{bt.init(e,t),e._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:e}),r)});qf=he("$ZodArray",(e,t)=>{bt.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 i=[];for(let s=0;s<o.length;s++){let c=o[s],l=t.element._zod.run({value:c,issues:[]},n);if(l instanceof Promise)i.push(l.then((u)=>Yp(u,r,s)));else Yp(l,r,s)}if(i.length)return Promise.all(i).then(()=>r);return r}});SE=he("$ZodObject",(e,t)=>{if(bt.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){let c=t.shape;Object.defineProperty(t,"shape",{get:()=>{let l={...c};return Object.defineProperty(t,"shape",{value:l}),l}})}let n=oi(()=>Lf(t));st(e._zod,"propValues",()=>{let c=t.shape,l={};for(let u in c){let f=c[u]._zod;if(f.values){l[u]??(l[u]=new Set);for(let _ of f.values)l[u].add(_)}}return l});let o=wo,i=t.catchall,s;e._zod.parse=(c,l)=>{s??(s=n.value);let u=c.value;if(!o(u))return c.issues.push({expected:"object",code:"invalid_type",input:u,inst:e}),c;c.value={};let f=[],_=s.shape;for(let E of s.keys){let g=_[E],A=g._zod.optin==="optional",L=g._zod.optout==="optional",F=g._zod.run({value:u[E],issues:[]},l);if(F instanceof Promise)f.push(F.then((X)=>ms(X,c,E,u,A,L)));else ms(F,c,E,u,A,L)}if(!i)return f.length?Promise.all(f).then(()=>c):c;return $f(f,u,c,l,n.value,e)}}),Mf=he("$ZodObjectJIT",(e,t)=>{SE.init(e,t);let r=e._zod.parse,n=oi(()=>Lf(t)),o=(E)=>{let g=new hc(["shape","payload","ctx"]),A=n.value,L=(ce)=>{let de=rc(ce);return`shape[${de}]._zod.run({ value: input[${de}], issues: [] }, ctx)`};g.write("const input = payload.value;");let F=Object.create(null),X=0;for(let ce of A.keys)F[ce]=`key_${X++}`;g.write("const newResult = {};");for(let ce of A.keys){let de=F[ce],Ce=rc(ce),ge=E[ce],Pe=ge?._zod?.optin==="optional",Qe=ge?._zod?.optout==="optional";if(g.write(`const ${de} = ${L(ce)};`),Pe&&Qe)g.write(`
12
+ if (${de}.issues.length) {
13
+ if (${Ce} in input) {
14
+ payload.issues = payload.issues.concat(${de}.issues.map(iss => ({
15
+ ...iss,
16
+ path: iss.path ? [${Ce}, ...iss.path] : [${Ce}]
17
+ })));
18
+ }
19
+ }
20
+
21
+ if (${de}.value === undefined) {
22
+ if (${Ce} in input) {
23
+ newResult[${Ce}] = undefined;
24
+ }
25
+ } else {
26
+ newResult[${Ce}] = ${de}.value;
27
+ }
28
+
29
+ `);else if(!Pe)g.write(`
30
+ const ${de}_present = ${Ce} in input;
31
+ if (${de}.issues.length) {
32
+ payload.issues = payload.issues.concat(${de}.issues.map(iss => ({
33
+ ...iss,
34
+ path: iss.path ? [${Ce}, ...iss.path] : [${Ce}]
35
+ })));
36
+ }
37
+ if (!${de}_present && !${de}.issues.length) {
38
+ payload.issues.push({
39
+ code: "invalid_type",
40
+ expected: "nonoptional",
41
+ input: undefined,
42
+ path: [${Ce}]
43
+ });
44
+ }
45
+
46
+ if (${de}_present) {
47
+ if (${de}.value === undefined) {
48
+ newResult[${Ce}] = undefined;
49
+ } else {
50
+ newResult[${Ce}] = ${de}.value;
51
+ }
52
+ }
53
+
54
+ `);else g.write(`
55
+ if (${de}.issues.length) {
56
+ payload.issues = payload.issues.concat(${de}.issues.map(iss => ({
57
+ ...iss,
58
+ path: iss.path ? [${Ce}, ...iss.path] : [${Ce}]
59
+ })));
60
+ }
61
+
62
+ if (${de}.value === undefined) {
63
+ if (${Ce} in input) {
64
+ newResult[${Ce}] = undefined;
65
+ }
66
+ } else {
67
+ newResult[${Ce}] = ${de}.value;
68
+ }
69
+
70
+ `)}g.write("payload.value = newResult;"),g.write("return payload;");let te=g.compile();return(ce,de)=>te(E,ce,de)},i,s=wo,c=!bo.jitless,u=c&&Wd.value,f=t.catchall,_;e._zod.parse=(E,g)=>{_??(_=n.value);let A=E.value;if(!s(A))return E.issues.push({expected:"object",code:"invalid_type",input:A,inst:e}),E;if(c&&u&&g?.async===!1&&g.jitless!==!0){if(!i)i=o(t.shape);if(E=i(E,g),!f)return E;return $f([],A,E,g,_,e)}return r(E,g)}});yc=he("$ZodUnion",(e,t)=>{bt.init(e,t),st(e._zod,"optin",()=>t.options.some((n)=>n._zod.optin==="optional")?"optional":void 0),st(e._zod,"optout",()=>t.options.some((n)=>n._zod.optout==="optional")?"optional":void 0),st(e._zod,"values",()=>{if(t.options.every((n)=>n._zod.values))return new Set(t.options.flatMap((n)=>Array.from(n._zod.values)));return}),st(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)=>as(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 i=!1,s=[];for(let c of t.options){let l=c._zod.run({value:n.value,issues:[]},o);if(l instanceof Promise)s.push(l),i=!0;else{if(l.issues.length===0)return l;s.push(l)}}if(!i)return Qp(s,n,e,o);return Promise.all(s).then((c)=>Qp(c,n,e,o))}}),Ff=he("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,yc.init(e,t);let r=e._zod.parse;st(e._zod,"propValues",()=>{let o={};for(let i of t.options){let s=i._zod.propValues;if(!s||Object.keys(s).length===0)throw Error(`Invalid discriminated union option at index "${t.options.indexOf(i)}"`);for(let[c,l]of Object.entries(s)){if(!o[c])o[c]=new Set;for(let u of l)o[c].add(u)}}return o});let n=oi(()=>{let o=t.options,i=new Map;for(let s of o){let c=s._zod.propValues?.[t.discriminator];if(!c||c.size===0)throw Error(`Invalid discriminated union option at index "${t.options.indexOf(s)}"`);for(let l of c){if(i.has(l))throw Error(`Duplicate discriminator value "${String(l)}"`);i.set(l,s)}}return i});e._zod.parse=(o,i)=>{let s=o.value;if(!wo(s))return o.issues.push({code:"invalid_type",expected:"object",input:s,inst:e}),o;let c=n.value.get(s?.[t.discriminator]);if(c)return c._zod.run(o,i);if(t.unionFallback||i.direction==="backward")return r(o,i);return o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,options:Array.from(n.value.keys()),input:s,path:[t.discriminator],inst:e}),o}}),zf=he("$ZodIntersection",(e,t)=>{bt.init(e,t),e._zod.parse=(r,n)=>{let o=r.value,i=t.left._zod.run({value:o,issues:[]},n),s=t.right._zod.run({value:o,issues:[]},n);if(i instanceof Promise||s instanceof Promise)return Promise.all([i,s]).then(([l,u])=>ef(r,l,u));return ef(r,i,s)}});Uf=he("$ZodRecord",(e,t)=>{bt.init(e,t),e._zod.parse=(r,n)=>{let o=r.value;if(!zn(o))return r.issues.push({expected:"record",code:"invalid_type",input:o,inst:e}),r;let i=[],s=t.keyType._zod.values;if(s){r.value={};let c=new Set;for(let u of s)if(typeof u==="string"||typeof u==="number"||typeof u==="symbol"){c.add(typeof u==="number"?u.toString():u);let f=t.keyType._zod.run({value:u,issues:[]},n);if(f instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(f.issues.length){r.issues.push({code:"invalid_key",origin:"record",issues:f.issues.map((g)=>Or(g,n,gr())),input:u,path:[u],inst:e});continue}let _=f.value,E=t.valueType._zod.run({value:o[u],issues:[]},n);if(E instanceof Promise)i.push(E.then((g)=>{if(g.issues.length)r.issues.push(...mn(u,g.issues));r.value[_]=g.value}));else{if(E.issues.length)r.issues.push(...mn(u,E.issues));r.value[_]=E.value}}let l;for(let u in o)if(!c.has(u))l=l??[],l.push(u);if(l&&l.length>0)r.issues.push({code:"unrecognized_keys",input:o,inst:e,keys:l})}else{r.value={};for(let c of Reflect.ownKeys(o)){if(c==="__proto__")continue;if(!Object.prototype.propertyIsEnumerable.call(o,c))continue;let l=t.keyType._zod.run({value:c,issues:[]},n);if(l instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(typeof c==="string"&&dc.test(c)&&l.issues.length){let _=t.keyType._zod.run({value:Number(c),issues:[]},n);if(_ instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(_.issues.length===0)l=_}if(l.issues.length){if(t.mode==="loose")r.value[c]=o[c];else r.issues.push({code:"invalid_key",origin:"record",issues:l.issues.map((_)=>Or(_,n,gr())),input:c,path:[c],inst:e});continue}let f=t.valueType._zod.run({value:o[c],issues:[]},n);if(f instanceof Promise)i.push(f.then((_)=>{if(_.issues.length)r.issues.push(...mn(c,_.issues));r.value[l.value]=_.value}));else{if(f.issues.length)r.issues.push(...mn(c,f.issues));r.value[l.value]=f.value}}}if(i.length)return Promise.all(i).then(()=>r);return r}}),Bf=he("$ZodEnum",(e,t)=>{bt.init(e,t);let r=is(t.entries),n=new Set(r);e._zod.values=n,e._zod.pattern=new RegExp(`^(${r.filter((o)=>Vd.has(typeof o)).map((o)=>typeof o==="string"?gn(o):o.toString()).join("|")})$`),e._zod.parse=(o,i)=>{let s=o.value;if(n.has(s))return o;return o.issues.push({code:"invalid_value",values:r,input:s,inst:e}),o}}),jf=he("$ZodLiteral",(e,t)=>{if(bt.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"?gn(n):n?gn(n.toString()):String(n)).join("|")})$`),e._zod.parse=(n,o)=>{let i=n.value;if(r.has(i))return n;return n.issues.push({code:"invalid_value",values:t.values,input:i,inst:e}),n}}),Hf=he("$ZodTransform",(e,t)=>{bt.init(e,t),e._zod.optin="optional",e._zod.parse=(r,n)=>{if(n.direction==="backward")throw new ri(e.constructor.name);let o=t.transform(r.value,r);if(n.async)return(o instanceof Promise?o:Promise.resolve(o)).then((s)=>(r.value=s,r.fallback=!0,r));if(o instanceof Promise)throw new Yr;return r.value=o,r.fallback=!0,r}});bc=he("$ZodOptional",(e,t)=>{bt.init(e,t),e._zod.optin="optional",e._zod.optout="optional",st(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),st(e._zod,"pattern",()=>{let r=t.innerType._zod.pattern;return r?new RegExp(`^(${as(r.source)})?$`):void 0}),e._zod.parse=(r,n)=>{if(t.innerType._zod.optin==="optional"){let o=r.value,i=t.innerType._zod.run(r,n);if(i instanceof Promise)return i.then((s)=>tf(s,o));return tf(i,o)}if(r.value===void 0)return r;return t.innerType._zod.run(r,n)}}),Wf=he("$ZodExactOptional",(e,t)=>{bc.init(e,t),st(e._zod,"values",()=>t.innerType._zod.values),st(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(r,n)=>t.innerType._zod.run(r,n)}),Vf=he("$ZodNullable",(e,t)=>{bt.init(e,t),st(e._zod,"optin",()=>t.innerType._zod.optin),st(e._zod,"optout",()=>t.innerType._zod.optout),st(e._zod,"pattern",()=>{let r=t.innerType._zod.pattern;return r?new RegExp(`^(${as(r.source)}|null)$`):void 0}),st(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)}}),Zf=he("$ZodDefault",(e,t)=>{bt.init(e,t),e._zod.optin="optional",st(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((i)=>rf(i,t));return rf(o,t)}});Gf=he("$ZodPrefault",(e,t)=>{bt.init(e,t),e._zod.optin="optional",st(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=he("$ZodNonOptional",(e,t)=>{bt.init(e,t),st(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((i)=>nf(i,e));return nf(o,e)}});Jf=he("$ZodCatch",(e,t)=>{bt.init(e,t),e._zod.optin="optional",st(e._zod,"optout",()=>t.innerType._zod.optout),st(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((i)=>{if(r.value=i.value,i.issues.length)r.value=t.catchValue({...r,error:{issues:i.issues.map((s)=>Or(s,n,gr()))},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((i)=>Or(i,n,gr()))},input:r.value}),r.issues=[],r.fallback=!0;return r}}),Xf=he("$ZodPipe",(e,t)=>{bt.init(e,t),st(e._zod,"values",()=>t.in._zod.values),st(e._zod,"optin",()=>t.in._zod.optin),st(e._zod,"optout",()=>t.out._zod.optout),st(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(r,n)=>{if(n.direction==="backward"){let i=t.out._zod.run(r,n);if(i instanceof Promise)return i.then((s)=>gs(s,t.in,n));return gs(i,t.in,n)}let o=t.in._zod.run(r,n);if(o instanceof Promise)return o.then((i)=>gs(i,t.out,n));return gs(o,t.out,n)}});Yf=he("$ZodReadonly",(e,t)=>{bt.init(e,t),st(e._zod,"propValues",()=>t.innerType._zod.propValues),st(e._zod,"values",()=>t.innerType._zod.values),st(e._zod,"optin",()=>t.innerType?._zod?.optin),st(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(of);return of(o)}});Qf=he("$ZodCustom",(e,t)=>{zt.init(e,t),bt.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((i)=>sf(i,r,n,e));sf(o,r,n,e);return}})});function wc(){return{localeError:kE()}}var kE=()=>{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 i=n[o.expected]??o.expected,s=Jd(o.input),c=n[s]??s;return`Invalid input: expected ${i}, received ${c}`}case"invalid_value":if(o.values.length===1)return`Invalid input: expected ${ic(o.values[0])}`;return`Invalid option: expected one of ${tc(o.values,"|")}`;case"too_big":{let i=o.inclusive?"<=":"<",s=t(o.origin);if(s)return`Too big: expected ${o.origin??"value"} to have ${i}${o.maximum.toString()} ${s.unit??"elements"}`;return`Too big: expected ${o.origin??"value"} to be ${i}${o.maximum.toString()}`}case"too_small":{let i=o.inclusive?">=":">",s=t(o.origin);if(s)return`Too small: expected ${o.origin} to have ${i}${o.minimum.toString()} ${s.unit}`;return`Too small: expected ${o.origin} to be ${i}${o.minimum.toString()}`}case"invalid_format":{let i=o;if(i.format==="starts_with")return`Invalid string: must start with "${i.prefix}"`;if(i.format==="ends_with")return`Invalid string: must end with "${i.suffix}"`;if(i.format==="includes")return`Invalid string: must include "${i.includes}"`;if(i.format==="regex")return`Invalid string: must match pattern ${i.pattern}`;return`Invalid ${r[i.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":""}: ${tc(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((s)=>`'${s}'`).join(" | ")}`;return"Invalid input";case"invalid_element":return`Invalid value in ${o.origin}`;default:return"Invalid input"}}};var th=Oe(()=>{Cr()});var vc=()=>{};class oh{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 xE(){return new oh}var nh,SD,kD,jn;var Ec=Oe(()=>{SD=Symbol("ZodOutput"),kD=Symbol("ZodInput");(nh=globalThis).__zod_globalRegistry??(nh.__zod_globalRegistry=xE());jn=globalThis.__zod_globalRegistry});function ih(e,t){return new e({type:"string",...Fe(t)})}function sh(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...Fe(t)})}function Sc(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...Fe(t)})}function ah(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...Fe(t)})}function ch(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...Fe(t)})}function lh(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...Fe(t)})}function uh(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...Fe(t)})}function dh(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...Fe(t)})}function ph(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...Fe(t)})}function fh(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...Fe(t)})}function hh(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...Fe(t)})}function gh(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...Fe(t)})}function mh(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...Fe(t)})}function _h(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...Fe(t)})}function yh(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...Fe(t)})}function bh(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...Fe(t)})}function wh(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...Fe(t)})}function vh(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...Fe(t)})}function Eh(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...Fe(t)})}function Sh(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...Fe(t)})}function kh(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...Fe(t)})}function xh(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...Fe(t)})}function Rh(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...Fe(t)})}function Th(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...Fe(t)})}function Dh(e,t){return new e({type:"string",format:"date",check:"string_format",...Fe(t)})}function Ah(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...Fe(t)})}function Oh(e,t){return new e({type:"string",format:"duration",check:"string_format",...Fe(t)})}function Ch(e,t){return new e({type:"number",checks:[],...Fe(t)})}function Ih(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...Fe(t)})}function Nh(e,t){return new e({type:"boolean",...Fe(t)})}function Ph(e){return new e({type:"unknown"})}function qh(e,t){return new e({type:"never",...Fe(t)})}function ys(e,t){return new pc({check:"less_than",...Fe(t),value:e,inclusive:!1})}function ci(e,t){return new pc({check:"less_than",...Fe(t),value:e,inclusive:!0})}function bs(e,t){return new fc({check:"greater_than",...Fe(t),value:e,inclusive:!1})}function li(e,t){return new fc({check:"greater_than",...Fe(t),value:e,inclusive:!0})}function ws(e,t){return new Mp({check:"multiple_of",...Fe(t),value:e})}function vs(e,t){return new zp({check:"max_length",...Fe(t),maximum:e})}function vo(e,t){return new Up({check:"min_length",...Fe(t),minimum:e})}function Es(e,t){return new Bp({check:"length_equals",...Fe(t),length:e})}function kc(e,t){return new jp({check:"string_format",format:"regex",...Fe(t),pattern:e})}function xc(e){return new Hp({check:"string_format",format:"lowercase",...Fe(e)})}function Rc(e){return new Wp({check:"string_format",format:"uppercase",...Fe(e)})}function Tc(e,t){return new Vp({check:"string_format",format:"includes",...Fe(t),includes:e})}function Dc(e,t){return new Zp({check:"string_format",format:"starts_with",...Fe(t),prefix:e})}function Ac(e,t){return new Gp({check:"string_format",format:"ends_with",...Fe(t),suffix:e})}function _n(e){return new Kp({check:"overwrite",tx:e})}function Oc(e){return _n((t)=>t.normalize(e))}function Cc(){return _n((e)=>e.trim())}function Ic(){return _n((e)=>e.toLowerCase())}function Nc(){return _n((e)=>e.toUpperCase())}function Pc(){return _n((e)=>Hd(e))}function Lh(e,t,r){return new e({type:"array",element:t,...Fe(r)})}function $h(e,t,r){return new e({type:"custom",check:"custom",fn:t,...Fe(r)})}function Mh(e,t){let r=RE((n)=>(n.addIssue=(o)=>{if(typeof o==="string")n.issues.push(Bn(o,n.value,r._zod.def));else{let i=o;if(i.fatal)i.continue=!1;i.code??(i.code="custom"),i.input??(i.input=n.value),i.inst??(i.inst=r),i.continue??(i.continue=!r._zod.def.abort),n.issues.push(Bn(i))}},e(n.value,n)),t);return r}function RE(e,t){let r=new zt({check:"custom",...Fe(t)});return r._zod.check=e,r}var Fh=Oe(()=>{hs();Cr()});function qc(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??jn,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 Tt(e,t,r={path:[],schemaPath:[]}){var n;let o=e._zod.def,i=t.seen.get(e);if(i){if(i.count++,r.schemaPath.includes(e))i.cycle=r.path;return i.schema}let s={schema:{},count:1,cycle:void 0,path:r.path};t.seen.set(e,s);let c=e._zod.toJSONSchema?.();if(c)s.schema=c;else{let f={...r,schemaPath:[...r.schemaPath,e],path:r.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,s.schema,f);else{let E=s.schema,g=t.processors[o.type];if(!g)throw Error(`[toJSONSchema]: Non-representable type encountered: ${o.type}`);g(e,t,E,f)}let _=e._zod.parent;if(_){if(!s.ref)s.ref=_;Tt(_,t,f),t.seen.get(_).isParent=!0}}let l=t.metadataRegistry.get(e);if(l)Object.assign(s.schema,l);if(t.io==="input"&&tr(e))delete s.schema.examples,delete s.schema.default;if(t.io==="input"&&"_prefault"in s.schema)(n=s.schema).default??(n.default=s.schema._prefault);return delete s.schema._prefault,t.seen.get(e).schema}function Lc(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 s of e.seen.entries()){let c=e.metadataRegistry.get(s[0])?.id;if(c){let l=n.get(c);if(l&&l!==s[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,s[0])}}let o=(s)=>{let c=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){let _=e.external.registry.get(s[0])?.id,E=e.external.uri??((A)=>A);if(_)return{ref:E(_)};let g=s[1].defId??s[1].schema.id??`schema${e.counter++}`;return s[1].defId=g,{defId:g,ref:`${E("__shared")}#/${c}/${g}`}}if(s[1]===r)return{ref:"#"};let u=`${"#"}/${c}/`,f=s[1].schema.id??`__schema${e.counter++}`;return{defId:f,ref:u+f}},i=(s)=>{if(s[1].schema.$ref)return;let c=s[1],{ref:l,defId:u}=o(s);if(c.def={...c.schema},u)c.defId=u;let f=c.schema;for(let _ in f)delete f[_];f.$ref=l};if(e.cycles==="throw")for(let s of e.seen.entries()){let c=s[1];if(c.cycle)throw Error(`Cycle detected: #/${c.cycle?.join("/")}/<root>
71
+
72
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let s of e.seen.entries()){let c=s[1];if(t===s[0]){i(s);continue}if(e.external){let u=e.external.registry.get(s[0])?.id;if(t!==s[0]&&u){i(s);continue}}if(e.metadataRegistry.get(s[0])?.id){i(s);continue}if(c.cycle){i(s);continue}if(c.count>1){if(e.reused==="ref"){i(s);continue}}}}function $c(e,t){let r=e.seen.get(t);if(!r)throw Error("Unprocessed schema. This is a bug in Zod.");let n=(c)=>{let l=e.seen.get(c);if(l.ref===null)return;let u=l.def??l.schema,f={...u},_=l.ref;if(l.ref=null,_){n(_);let g=e.seen.get(_),A=g.schema;if(A.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"))u.allOf=u.allOf??[],u.allOf.push(A);else Object.assign(u,A);if(Object.assign(u,f),c._zod.parent===_)for(let F in u){if(F==="$ref"||F==="allOf")continue;if(!(F in f))delete u[F]}if(A.$ref&&g.def)for(let F in u){if(F==="$ref"||F==="allOf")continue;if(F in g.def&&JSON.stringify(u[F])===JSON.stringify(g.def[F]))delete u[F]}}let E=c._zod.parent;if(E&&E!==_){n(E);let g=e.seen.get(E);if(g?.schema.$ref){if(u.$ref=g.schema.$ref,g.def)for(let A in u){if(A==="$ref"||A==="allOf")continue;if(A in g.def&&JSON.stringify(u[A])===JSON.stringify(g.def[A]))delete u[A]}}}e.override({zodSchema:c,jsonSchema:u,path:l.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 i=e.metadataRegistry.get(t)?.id;if(i!==void 0&&o.id===i)delete o.id;let s=e.external?.defs??{};for(let c of e.seen.entries()){let l=c[1];if(l.def&&l.defId){if(l.def.id===l.defId)delete l.def.id;s[l.defId]=l.def}}if(e.external);else if(Object.keys(s).length>0)if(e.target==="draft-2020-12")o.$defs=s;else o.definitions=s;try{let c=JSON.parse(JSON.stringify(o));return Object.defineProperty(c,"~standard",{value:{...t["~standard"],jsonSchema:{input:ui(t,"input",e.processors),output:ui(t,"output",e.processors)}},enumerable:!1,writable:!1}),c}catch(c){throw Error("Error converting schema to JSON.")}}function tr(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 tr(n.element,r);if(n.type==="set")return tr(n.valueType,r);if(n.type==="lazy")return tr(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 tr(n.innerType,r);if(n.type==="intersection")return tr(n.left,r)||tr(n.right,r);if(n.type==="record"||n.type==="map")return tr(n.keyType,r)||tr(n.valueType,r);if(n.type==="pipe"){if(e._zod.traits.has("$ZodCodec"))return!0;return tr(n.in,r)||tr(n.out,r)}if(n.type==="object"){for(let o in n.shape)if(tr(n.shape[o],r))return!0;return!1}if(n.type==="union"){for(let o of n.options)if(tr(o,r))return!0;return!1}if(n.type==="tuple"){for(let o of n.items)if(tr(o,r))return!0;if(n.rest&&tr(n.rest,r))return!0;return!1}return!1}var zh=(e,t={})=>(r)=>{let n=qc({...r,processors:t});return Tt(e,n),Lc(n,e),$c(n,e)},ui=(e,t,r={})=>(n)=>{let{libraryOptions:o,target:i}=n??{},s=qc({...o??{},target:i,io:t,processors:r});return Tt(e,s),Lc(s,e),$c(s,e)};var Ss=Oe(()=>{Ec()});var TE,Uh=(e,t,r,n)=>{let o=r;o.type="string";let{minimum:i,maximum:s,format:c,patterns:l,contentEncoding:u}=e._zod.bag;if(typeof i==="number")o.minLength=i;if(typeof s==="number")o.maxLength=s;if(c){if(o.format=TE[c]??c,o.format==="")delete o.format;if(c==="time")delete o.format}if(u)o.contentEncoding=u;if(l&&l.size>0){let f=[...l];if(f.length===1)o.pattern=f[0].source;else if(f.length>1)o.allOf=[...f.map((_)=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:_.source}))]}},Bh=(e,t,r,n)=>{let o=r,{minimum:i,maximum:s,format:c,multipleOf:l,exclusiveMaximum:u,exclusiveMinimum:f}=e._zod.bag;if(typeof c==="string"&&c.includes("int"))o.type="integer";else o.type="number";let _=typeof f==="number"&&f>=(i??Number.NEGATIVE_INFINITY),E=typeof u==="number"&&u<=(s??Number.POSITIVE_INFINITY),g=t.target==="draft-04"||t.target==="openapi-3.0";if(_)if(g)o.minimum=f,o.exclusiveMinimum=!0;else o.exclusiveMinimum=f;else if(typeof i==="number")o.minimum=i;if(E)if(g)o.maximum=u,o.exclusiveMaximum=!0;else o.exclusiveMaximum=u;else if(typeof s==="number")o.maximum=s;if(typeof l==="number")o.multipleOf=l},jh=(e,t,r,n)=>{r.type="boolean"},Hh=(e,t,r,n)=>{r.not={}},Wh=(e,t,r,n)=>{},Vh=(e,t,r,n)=>{let o=e._zod.def,i=is(o.entries);if(i.every((s)=>typeof s==="number"))r.type="number";if(i.every((s)=>typeof s==="string"))r.type="string";r.enum=i},Zh=(e,t,r,n)=>{let o=e._zod.def,i=[];for(let s of o.values)if(s===void 0){if(t.unrepresentable==="throw")throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof s==="bigint")if(t.unrepresentable==="throw")throw Error("BigInt literals cannot be represented in JSON Schema");else i.push(Number(s));else i.push(s);if(i.length===0);else if(i.length===1){let s=i[0];if(r.type=s===null?"null":typeof s,t.target==="draft-04"||t.target==="openapi-3.0")r.enum=[s];else r.const=s}else{if(i.every((s)=>typeof s==="number"))r.type="number";if(i.every((s)=>typeof s==="string"))r.type="string";if(i.every((s)=>typeof s==="boolean"))r.type="boolean";if(i.every((s)=>s===null))r.type="null";r.enum=i}},Gh=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw Error("Custom types cannot be represented in JSON Schema")},Kh=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw Error("Transforms cannot be represented in JSON Schema")},Jh=(e,t,r,n)=>{let o=r,i=e._zod.def,{minimum:s,maximum:c}=e._zod.bag;if(typeof s==="number")o.minItems=s;if(typeof c==="number")o.maxItems=c;o.type="array",o.items=Tt(i.element,t,{...n,path:[...n.path,"items"]})},Xh=(e,t,r,n)=>{let o=r,i=e._zod.def;o.type="object",o.properties={};let s=i.shape;for(let u in s)o.properties[u]=Tt(s[u],t,{...n,path:[...n.path,"properties",u]});let c=new Set(Object.keys(s)),l=new Set([...c].filter((u)=>{let f=i.shape[u]._zod;if(t.io==="input")return f.optin===void 0;else return f.optout===void 0}));if(l.size>0)o.required=Array.from(l);if(i.catchall?._zod.def.type==="never")o.additionalProperties=!1;else if(!i.catchall){if(t.io==="output")o.additionalProperties=!1}else if(i.catchall)o.additionalProperties=Tt(i.catchall,t,{...n,path:[...n.path,"additionalProperties"]})},Yh=(e,t,r,n)=>{let o=e._zod.def,i=o.inclusive===!1,s=o.options.map((c,l)=>Tt(c,t,{...n,path:[...n.path,i?"oneOf":"anyOf",l]}));if(i)r.oneOf=s;else r.anyOf=s},Qh=(e,t,r,n)=>{let o=e._zod.def,i=Tt(o.left,t,{...n,path:[...n.path,"allOf",0]}),s=Tt(o.right,t,{...n,path:[...n.path,"allOf",1]}),c=(u)=>("allOf"in u)&&Object.keys(u).length===1,l=[...c(i)?i.allOf:[i],...c(s)?s.allOf:[s]];r.allOf=l},eg=(e,t,r,n)=>{let o=r,i=e._zod.def;o.type="object";let s=i.keyType,l=s._zod.bag?.patterns;if(i.mode==="loose"&&l&&l.size>0){let f=Tt(i.valueType,t,{...n,path:[...n.path,"patternProperties","*"]});o.patternProperties={};for(let _ of l)o.patternProperties[_.source]=f}else{if(t.target==="draft-07"||t.target==="draft-2020-12")o.propertyNames=Tt(i.keyType,t,{...n,path:[...n.path,"propertyNames"]});o.additionalProperties=Tt(i.valueType,t,{...n,path:[...n.path,"additionalProperties"]})}let u=s._zod.values;if(u){let f=[...u].filter((_)=>typeof _==="string"||typeof _==="number");if(f.length>0)o.required=f}},tg=(e,t,r,n)=>{let o=e._zod.def,i=Tt(o.innerType,t,n),s=t.seen.get(e);if(t.target==="openapi-3.0")s.ref=o.innerType,r.nullable=!0;else r.anyOf=[i,{type:"null"}]},rg=(e,t,r,n)=>{let o=e._zod.def;Tt(o.innerType,t,n);let i=t.seen.get(e);i.ref=o.innerType},ng=(e,t,r,n)=>{let o=e._zod.def;Tt(o.innerType,t,n);let i=t.seen.get(e);i.ref=o.innerType,r.default=JSON.parse(JSON.stringify(o.defaultValue))},og=(e,t,r,n)=>{let o=e._zod.def;Tt(o.innerType,t,n);let i=t.seen.get(e);if(i.ref=o.innerType,t.io==="input")r._prefault=JSON.parse(JSON.stringify(o.defaultValue))},ig=(e,t,r,n)=>{let o=e._zod.def;Tt(o.innerType,t,n);let i=t.seen.get(e);i.ref=o.innerType;let s;try{s=o.catchValue(void 0)}catch{throw Error("Dynamic catch values are not supported in JSON Schema")}r.default=s},sg=(e,t,r,n)=>{let o=e._zod.def,i=o.in._zod.traits.has("$ZodTransform"),s=t.io==="input"?i?o.out:o.in:o.out;Tt(s,t,n);let c=t.seen.get(e);c.ref=s},ag=(e,t,r,n)=>{let o=e._zod.def;Tt(o.innerType,t,n);let i=t.seen.get(e);i.ref=o.innerType,r.readOnly=!0},Mc=(e,t,r,n)=>{let o=e._zod.def;Tt(o.innerType,t,n);let i=t.seen.get(e);i.ref=o.innerType};var cg=Oe(()=>{Ss();Cr();TE={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""}});var lg=()=>{};var Ur=Oe(()=>{Cr();fs();vc();lg();Mn();cc();ac();eh();hs();gc();Ec();Fh();Ss()});var Fc=Oe(()=>{Ur()});function ug(e){return Th(PE,e)}function dg(e){return Dh(qE,e)}function pg(e){return Ah(LE,e)}function fg(e){return Oh($E,e)}var PE,qE,LE,$E;var zc=Oe(()=>{Ur();Uc();PE=he("ZodISODateTime",(e,t)=>{yf.init(e,t),wt.init(e,t)});qE=he("ZodISODate",(e,t)=>{bf.init(e,t),wt.init(e,t)});LE=he("ZodISOTime",(e,t)=>{wf.init(e,t),wt.init(e,t)});$E=he("ZodISODuration",(e,t)=>{vf.init(e,t),wt.init(e,t)})});var FE=(e,t)=>{ls.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:(r)=>Qd(e,r)},flatten:{value:(r)=>Yd(e,r)},addIssue:{value:(r)=>{e.issues.push(r),e.message=JSON.stringify(e.issues,ni,2)}},addIssues:{value:(r)=>{e.issues.push(...r),e.message=JSON.stringify(e.issues,ni,2)}},isEmpty:{get(){return e.issues.length===0}}})},mr;var Bc=Oe(()=>{Ur();Ur();Cr();mr=he("ZodError",FE,{Parent:Error})});var gg,mg,_g,yg,bg,wg,vg,Eg,Sg,kg,xg,Rg;var jc=Oe(()=>{Ur();Bc();gg=us(mr),mg=ds(mr),_g=ii(mr),yg=si(mr),bg=rp(mr),wg=np(mr),vg=op(mr),Eg=ip(mr),Sg=sp(mr),kg=ap(mr),xg=cp(mr),Rg=lp(mr)});function pi(e,t,r){let n=Object.getPrototypeOf(e),o=Tg.get(n);if(!o)o=new Set,Tg.set(n,o);if(o.has(t))return;o.add(t);for(let i in r){let s=r[i];Object.defineProperty(n,i,{configurable:!0,enumerable:!1,get(){let c=s.bind(this);return Object.defineProperty(this,i,{configurable:!0,writable:!0,enumerable:!0,value:c}),c},set(c){Object.defineProperty(this,i,{configurable:!0,writable:!0,enumerable:!0,value:c})}})}}function Be(e){return ih(UE,e)}function Dt(e){return Ch(Lg,e)}function Ag(e){return Ih(iS,e)}function aS(e){return Nh(sS,e)}function Og(){return Ph(cS)}function uS(e){return qh(lS,e)}function Gt(e,t){return Lh(dS,e,t)}function _t(e,t){let r={type:"object",shape:e??{},...Fe(t)};return new pS(r)}function fS(e,t){return new $g({type:"union",options:e,...Fe(t)})}function gS(e,t,r){return new hS({type:"union",options:t,discriminator:e,...Fe(r)})}function _S(e,t){return new mS({type:"intersection",left:e,right:t})}function Mg(e,t,r){if(!t||!t._zod)return new Cg({type:"record",keyType:Be(),valueType:e,...Fe(t)});return new Cg({type:"record",keyType:e,valueType:t,...Fe(r)})}function xs(e,t){let r=Array.isArray(e)?Object.fromEntries(e.map((n)=>[n,n])):e;return new Hc({type:"enum",entries:r,...Fe(t)})}function Ut(e,t){return new yS({type:"literal",values:Array.isArray(e)?e:[e],...Fe(t)})}function wS(e){return new bS({type:"transform",transform:e})}function Ig(e){return new Fg({type:"optional",innerType:e})}function ES(e){return new vS({type:"optional",innerType:e})}function Ng(e){return new SS({type:"nullable",innerType:e})}function xS(e,t){return new kS({type:"default",innerType:e,get defaultValue(){return typeof t==="function"?t():oc(t)}})}function TS(e,t){return new RS({type:"prefault",innerType:e,get defaultValue(){return typeof t==="function"?t():oc(t)}})}function DS(e,t){return new zg({type:"nonoptional",innerType:e,...Fe(t)})}function OS(e,t){return new AS({type:"catch",innerType:e,catchValue:typeof t==="function"?t:()=>t})}function Pg(e,t){return new CS({type:"pipe",in:e,out:t})}function NS(e){return new IS({type:"readonly",innerType:e})}function qS(e,t={}){return $h(PS,e,t)}function LS(e,t){return Mh(e,t)}var Tg,Et,qg,UE,wt,BE,Dg,ks,jE,HE,WE,VE,ZE,GE,KE,JE,XE,YE,QE,eS,tS,rS,nS,oS,Lg,iS,sS,cS,lS,dS,pS,$g,hS,mS,Cg,Hc,yS,bS,Fg,vS,SS,kS,RS,zg,AS,CS,IS,PS;var Uc=Oe(()=>{Ur();Ur();cg();Ss();Fc();zc();jc();Tg=new WeakMap;Et=he("ZodType",(e,t)=>(bt.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:ui(e,"input"),output:ui(e,"output")}}),e.toJSONSchema=zh(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(r,n)=>gg(e,r,n,{callee:e.parse}),e.safeParse=(r,n)=>_g(e,r,n),e.parseAsync=async(r,n)=>mg(e,r,n,{callee:e.parseAsync}),e.safeParseAsync=async(r,n)=>yg(e,r,n),e.spa=e.safeParseAsync,e.encode=(r,n)=>bg(e,r,n),e.decode=(r,n)=>wg(e,r,n),e.encodeAsync=async(r,n)=>vg(e,r,n),e.decodeAsync=async(r,n)=>Eg(e,r,n),e.safeEncode=(r,n)=>Sg(e,r,n),e.safeDecode=(r,n)=>kg(e,r,n),e.safeEncodeAsync=async(r,n)=>xg(e,r,n),e.safeDecodeAsync=async(r,n)=>Rg(e,r,n),pi(e,"ZodType",{check(...r){let n=this.def;return this.clone(hn(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 zr(this,r,n)},brand(){return this},register(r,n){return r.add(this,n),this},refine(r,n){return this.check(qS(r,n))},superRefine(r,n){return this.check(LS(r,n))},overwrite(r){return this.check(_n(r))},optional(){return Ig(this)},exactOptional(){return ES(this)},nullable(){return Ng(this)},nullish(){return Ig(Ng(this))},nonoptional(r){return DS(this,r)},array(){return Gt(this)},or(r){return fS([this,r])},and(r){return _S(this,r)},transform(r){return Pg(this,wS(r))},default(r){return xS(this,r)},prefault(r){return TS(this,r)},catch(r){return OS(this,r)},pipe(r){return Pg(this,r)},readonly(){return NS(this)},describe(r){let n=this.clone();return jn.add(n,{description:r}),n},meta(...r){if(r.length===0)return jn.get(this);let n=this.clone();return jn.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 jn.get(e)?.description},configurable:!0}),e)),qg=he("_ZodString",(e,t)=>{_s.init(e,t),Et.init(e,t),e._zod.processJSONSchema=(n,o,i)=>Uh(e,n,o,i);let r=e._zod.bag;e.format=r.format??null,e.minLength=r.minimum??null,e.maxLength=r.maximum??null,pi(e,"_ZodString",{regex(...n){return this.check(kc(...n))},includes(...n){return this.check(Tc(...n))},startsWith(...n){return this.check(Dc(...n))},endsWith(...n){return this.check(Ac(...n))},min(...n){return this.check(vo(...n))},max(...n){return this.check(vs(...n))},length(...n){return this.check(Es(...n))},nonempty(...n){return this.check(vo(1,...n))},lowercase(n){return this.check(xc(n))},uppercase(n){return this.check(Rc(n))},trim(){return this.check(Cc())},normalize(...n){return this.check(Oc(...n))},toLowerCase(){return this.check(Ic())},toUpperCase(){return this.check(Nc())},slugify(){return this.check(Pc())}})}),UE=he("ZodString",(e,t)=>{_s.init(e,t),qg.init(e,t),e.email=(r)=>e.check(sh(BE,r)),e.url=(r)=>e.check(dh(jE,r)),e.jwt=(r)=>e.check(Rh(oS,r)),e.emoji=(r)=>e.check(ph(HE,r)),e.guid=(r)=>e.check(Sc(Dg,r)),e.uuid=(r)=>e.check(ah(ks,r)),e.uuidv4=(r)=>e.check(ch(ks,r)),e.uuidv6=(r)=>e.check(lh(ks,r)),e.uuidv7=(r)=>e.check(uh(ks,r)),e.nanoid=(r)=>e.check(fh(WE,r)),e.guid=(r)=>e.check(Sc(Dg,r)),e.cuid=(r)=>e.check(hh(VE,r)),e.cuid2=(r)=>e.check(gh(ZE,r)),e.ulid=(r)=>e.check(mh(GE,r)),e.base64=(r)=>e.check(Sh(tS,r)),e.base64url=(r)=>e.check(kh(rS,r)),e.xid=(r)=>e.check(_h(KE,r)),e.ksuid=(r)=>e.check(yh(JE,r)),e.ipv4=(r)=>e.check(bh(XE,r)),e.ipv6=(r)=>e.check(wh(YE,r)),e.cidrv4=(r)=>e.check(vh(QE,r)),e.cidrv6=(r)=>e.check(Eh(eS,r)),e.e164=(r)=>e.check(xh(nS,r)),e.datetime=(r)=>e.check(ug(r)),e.date=(r)=>e.check(dg(r)),e.time=(r)=>e.check(pg(r)),e.duration=(r)=>e.check(fg(r))});wt=he("ZodStringFormat",(e,t)=>{mt.init(e,t),qg.init(e,t)}),BE=he("ZodEmail",(e,t)=>{lf.init(e,t),wt.init(e,t)}),Dg=he("ZodGUID",(e,t)=>{af.init(e,t),wt.init(e,t)}),ks=he("ZodUUID",(e,t)=>{cf.init(e,t),wt.init(e,t)}),jE=he("ZodURL",(e,t)=>{uf.init(e,t),wt.init(e,t)}),HE=he("ZodEmoji",(e,t)=>{df.init(e,t),wt.init(e,t)}),WE=he("ZodNanoID",(e,t)=>{pf.init(e,t),wt.init(e,t)}),VE=he("ZodCUID",(e,t)=>{ff.init(e,t),wt.init(e,t)}),ZE=he("ZodCUID2",(e,t)=>{hf.init(e,t),wt.init(e,t)}),GE=he("ZodULID",(e,t)=>{gf.init(e,t),wt.init(e,t)}),KE=he("ZodXID",(e,t)=>{mf.init(e,t),wt.init(e,t)}),JE=he("ZodKSUID",(e,t)=>{_f.init(e,t),wt.init(e,t)}),XE=he("ZodIPv4",(e,t)=>{Ef.init(e,t),wt.init(e,t)}),YE=he("ZodIPv6",(e,t)=>{Sf.init(e,t),wt.init(e,t)}),QE=he("ZodCIDRv4",(e,t)=>{kf.init(e,t),wt.init(e,t)}),eS=he("ZodCIDRv6",(e,t)=>{xf.init(e,t),wt.init(e,t)}),tS=he("ZodBase64",(e,t)=>{Tf.init(e,t),wt.init(e,t)}),rS=he("ZodBase64URL",(e,t)=>{Df.init(e,t),wt.init(e,t)}),nS=he("ZodE164",(e,t)=>{Af.init(e,t),wt.init(e,t)}),oS=he("ZodJWT",(e,t)=>{Of.init(e,t),wt.init(e,t)}),Lg=he("ZodNumber",(e,t)=>{_c.init(e,t),Et.init(e,t),e._zod.processJSONSchema=(n,o,i)=>Bh(e,n,o,i),pi(e,"ZodNumber",{gt(n,o){return this.check(bs(n,o))},gte(n,o){return this.check(li(n,o))},min(n,o){return this.check(li(n,o))},lt(n,o){return this.check(ys(n,o))},lte(n,o){return this.check(ci(n,o))},max(n,o){return this.check(ci(n,o))},int(n){return this.check(Ag(n))},safe(n){return this.check(Ag(n))},positive(n){return this.check(bs(0,n))},nonnegative(n){return this.check(li(0,n))},negative(n){return this.check(ys(0,n))},nonpositive(n){return this.check(ci(0,n))},multipleOf(n,o){return this.check(ws(n,o))},step(n,o){return this.check(ws(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});iS=he("ZodNumberFormat",(e,t)=>{Cf.init(e,t),Lg.init(e,t)});sS=he("ZodBoolean",(e,t)=>{If.init(e,t),Et.init(e,t),e._zod.processJSONSchema=(r,n,o)=>jh(e,r,n,o)});cS=he("ZodUnknown",(e,t)=>{Nf.init(e,t),Et.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Wh(e,r,n,o)});lS=he("ZodNever",(e,t)=>{Pf.init(e,t),Et.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Hh(e,r,n,o)});dS=he("ZodArray",(e,t)=>{qf.init(e,t),Et.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Jh(e,r,n,o),e.element=t.element,pi(e,"ZodArray",{min(r,n){return this.check(vo(r,n))},nonempty(r){return this.check(vo(1,r))},max(r,n){return this.check(vs(r,n))},length(r,n){return this.check(Es(r,n))},unwrap(){return this.element}})});pS=he("ZodObject",(e,t)=>{Mf.init(e,t),Et.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Xh(e,r,n,o),st(e,"shape",()=>t.shape),pi(e,"ZodObject",{keyof(){return xs(Object.keys(this._zod.def.shape))},catchall(r){return this.clone({...this._zod.def,catchall:r})},passthrough(){return this.clone({...this._zod.def,catchall:Og()})},loose(){return this.clone({...this._zod.def,catchall:Og()})},strict(){return this.clone({...this._zod.def,catchall:uS()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(r){return hE(this,r)},safeExtend(r){return gE(this,r)},merge(r){return mE(this,r)},pick(r){return pE(this,r)},omit(r){return fE(this,r)},partial(...r){return _E(Fg,this,r[0])},required(...r){return yE(zg,this,r[0])}})});$g=he("ZodUnion",(e,t)=>{yc.init(e,t),Et.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Yh(e,r,n,o),e.options=t.options});hS=he("ZodDiscriminatedUnion",(e,t)=>{$g.init(e,t),Ff.init(e,t)});mS=he("ZodIntersection",(e,t)=>{zf.init(e,t),Et.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Qh(e,r,n,o)});Cg=he("ZodRecord",(e,t)=>{Uf.init(e,t),Et.init(e,t),e._zod.processJSONSchema=(r,n,o)=>eg(e,r,n,o),e.keyType=t.keyType,e.valueType=t.valueType});Hc=he("ZodEnum",(e,t)=>{Bf.init(e,t),Et.init(e,t),e._zod.processJSONSchema=(n,o,i)=>Vh(e,n,o,i),e.enum=t.entries,e.options=Object.values(t.entries);let r=new Set(Object.keys(t.entries));e.extract=(n,o)=>{let i={};for(let s of n)if(r.has(s))i[s]=t.entries[s];else throw Error(`Key ${s} not found in enum`);return new Hc({...t,checks:[],...Fe(o),entries:i})},e.exclude=(n,o)=>{let i={...t.entries};for(let s of n)if(r.has(s))delete i[s];else throw Error(`Key ${s} not found in enum`);return new Hc({...t,checks:[],...Fe(o),entries:i})}});yS=he("ZodLiteral",(e,t)=>{jf.init(e,t),Et.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Zh(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]}})});bS=he("ZodTransform",(e,t)=>{Hf.init(e,t),Et.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Kh(e,r,n,o),e._zod.parse=(r,n)=>{if(n.direction==="backward")throw new ri(e.constructor.name);r.addIssue=(i)=>{if(typeof i==="string")r.issues.push(Bn(i,r.value,t));else{let s=i;if(s.fatal)s.continue=!1;s.code??(s.code="custom"),s.input??(s.input=r.value),s.inst??(s.inst=e),r.issues.push(Bn(s))}};let o=t.transform(r.value,r);if(o instanceof Promise)return o.then((i)=>(r.value=i,r.fallback=!0,r));return r.value=o,r.fallback=!0,r}});Fg=he("ZodOptional",(e,t)=>{bc.init(e,t),Et.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Mc(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});vS=he("ZodExactOptional",(e,t)=>{Wf.init(e,t),Et.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Mc(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});SS=he("ZodNullable",(e,t)=>{Vf.init(e,t),Et.init(e,t),e._zod.processJSONSchema=(r,n,o)=>tg(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});kS=he("ZodDefault",(e,t)=>{Zf.init(e,t),Et.init(e,t),e._zod.processJSONSchema=(r,n,o)=>ng(e,r,n,o),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});RS=he("ZodPrefault",(e,t)=>{Gf.init(e,t),Et.init(e,t),e._zod.processJSONSchema=(r,n,o)=>og(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});zg=he("ZodNonOptional",(e,t)=>{Kf.init(e,t),Et.init(e,t),e._zod.processJSONSchema=(r,n,o)=>rg(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});AS=he("ZodCatch",(e,t)=>{Jf.init(e,t),Et.init(e,t),e._zod.processJSONSchema=(r,n,o)=>ig(e,r,n,o),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});CS=he("ZodPipe",(e,t)=>{Xf.init(e,t),Et.init(e,t),e._zod.processJSONSchema=(r,n,o)=>sg(e,r,n,o),e.in=t.in,e.out=t.out});IS=he("ZodReadonly",(e,t)=>{Yf.init(e,t),Et.init(e,t),e._zod.processJSONSchema=(r,n,o)=>ag(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});PS=he("ZodCustom",(e,t)=>{Qf.init(e,t),Et.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Gh(e,r,n,o)})});var Ug;var Bg=Oe(()=>{(function(e){})(Ug||(Ug={}))});var jg=()=>{};var Wc=Oe(()=>{Ur();Ur();th();vc();zc();jg();Uc();Fc();Bc();jc();Bg();gr(wc())});var Wn=Oe(()=>{Wc();Wc()});function Hg(e){let t=MS.safeParse(e);if(!t.success)throw new T("invalid_input","invalid retention event");return t.data}function at(e){let t=e.query("SELECT value FROM meta WHERE key = ?").get(Wg);if(!t)return null;let r=Vn.safeParse(JSON.parse(t.value));if(!r.success)throw new T("rebootstrap_required","local synchronization generation is invalid");return r.data}function Ts(e,t,r){let n=at(e);if(!n)return r;let o=e.query("SELECT value FROM meta WHERE key='local_v2_history_peer'").get();if(o?o.value!==t:e.query("SELECT 1 FROM peers WHERE kind='s3' AND url<>? LIMIT 1").get(t))return r;let i=e.query("SELECT value FROM meta WHERE key=?").get(`sync_v2_transport:${n.incarnationId}`);return i?JSON.parse(i.value).cursor:0}function Vg(e,t){if(Xr(e)>vr.maxSupportedDataVersion)return!1;return!at(e)||!!e.query("SELECT 1 FROM meta WHERE key=?").get(`sync_v2_rebuild_required:${t}`)}function Ds(e,t){let r=Vn.parse(t),n=at(e);if(n&&(r.workspaceId!==n.workspaceId||r.epoch<n.epoch))throw new T("rebootstrap_required","workspace or synchronization generation cannot roll back");if(n&&r.epoch===n.epoch&&r.checkpoint!==n.checkpoint)throw new T("rebootstrap_required","checkpoint cannot change within a synchronization generation");e.query("INSERT INTO meta (key,value) VALUES (?,?) ON CONFLICT(key) DO UPDATE SET value=excluded.value").run(Wg,JSON.stringify(r))}function Zc(e,t){Qt(e);let r=at(e);if(!r){if(t!=null)throw new T("upgrade_required","workspace migration is required");return}let n=Vn.safeParse(t);if(!n.success)throw new T("upgrade_required","sync protocol version 2 is required");if(n.data.workspaceId!==r.workspaceId||n.data.epoch!==r.epoch||n.data.checkpoint!==r.checkpoint)throw new T("rebootstrap_required","synchronization checkpoint is obsolete")}var en,tn,Rs,Ir,Vc,MS,Vn,Wg="sync_v2_generation";var Kt=Oe(()=>{er();Wn();Ke();en=Dt().int().nonnegative().safe(),tn=en,Rs=Be().regex(/^[a-f0-9]{64}$/),Ir=Be().regex(/^[a-zA-Z0-9_-]{1,128}$/).refine((e)=>!["__proto__","constructor","prototype"].includes(e)),Vc=Rs.nullable(),MS=gS("type",[_t({type:Ut("upgrade"),workspaceId:Be().min(1),epoch:tn,id:Ir,from:en,to:en,checkpoint:Rs}).strict(),_t({type:Ut("clock")}).strict(),_t({type:Ut("join"),epoch:tn,member:Ir,checkpoint:Vc,replaces:_t({member:Ir,sequence:en}).strict().optional()}).strict(),_t({type:Ut("batch"),epoch:tn,member:Ir,first:en.positive(),last:en.positive(),objectHash:Rs}).strict(),_t({type:Ut("renew"),epoch:tn,member:Ir,sequence:en,checkpoint:Vc}).strict(),_t({type:Ut("prepare"),epoch:tn,id:Ir,targetDataVersion:en.positive().optional()}).strict(),_t({type:Ut("seal"),epoch:tn,id:Ir,member:Ir,sequence:en}).strict(),_t({type:Ut("cancel"),epoch:tn,id:Ir}).strict(),_t({type:Ut("commit"),epoch:tn,id:Ir,checkpoint:Rs}).strict()]);Vn=_t({protocolVersion:Ut(2),workspaceId:Be().min(1).max(128),epoch:tn,incarnationId:Ir,checkpoint:Vc}).strict()});function Eo(e,t){return Ve(e,()=>{e.exec(`CREATE TABLE IF NOT EXISTS sync_recovery_items (
73
+ id TEXT PRIMARY KEY, kind TEXT NOT NULL, target TEXT NOT NULL, local TEXT NOT NULL,
74
+ remote TEXT, status TEXT NOT NULL DEFAULT 'pending', result TEXT)`);let r=new Map;for(let E of t.changes){let g=JSON.stringify([E.dataset,E.row_id,E.col,E.hlc]),A=r.get(g)??e.query("SELECT node_id,value,txn FROM crdt_changes WHERE dataset=? AND row_id=? AND col=? AND hlc=?").get(E.dataset,E.row_id,E.col,E.hlc);if(A&&(A.value!==E.value||A.node_id!==E.node_id||(A.txn??null)!==(E.txn??null)))throw new T("invalid_input","conflicting change identity");r.set(g,E)}let n=0,o=0,i={},s=new Set(e.query("SELECT id FROM doc_blocks").all().map((E)=>E.id)),c=new Set(t.changes.filter((E,g)=>E.dataset==="doc_blocks"&&E.col==="doc_id"&&t.bases?.[g]==null).map((E)=>E.row_id)),l=new Set(e.query("SELECT id FROM doc_blocks WHERE __deleted=1").all().map((E)=>E.id)),u=(E,g)=>`sync_v2_base:${g}:${E.dataset}:${E.row_id}:${E.col}`;for(let E=0;E<t.changes.length;E++){let g=t.changes[E],A=t.bases?.[E];if(A===void 0)continue;if(A!==null&&A>=g.hlc)throw new T("invalid_input","edit baseline must precede its change");let L=e.query("SELECT value FROM meta WHERE key=?").get(u(g,g.hlc));if(L&&JSON.parse(L.value)!==A)throw new T("invalid_input","conflicting edit baseline");e.query("INSERT OR IGNORE INTO meta(key,value) VALUES(?,?)").run(u(g,g.hlc),JSON.stringify(A))}let f=(E,g,A)=>{let L=g;while(L&&L>=A){if(L===A)return!0;let F=e.query("SELECT value FROM meta WHERE key=?").get(u(E,L));if(!F)return!1;let X=JSON.parse(F.value);if(X!==null&&X>=L)return!1;L=X}return!1},_=new Map;for(let E of e.query("SELECT row_id,MAX(hlc) AS hlc FROM crdt_changes WHERE dataset='doc_blocks' AND col='__deleted' AND value='1' GROUP BY row_id").all())_.set(E.row_id,E.hlc);for(let E of t.changes)if(E.dataset==="doc_blocks"&&E.col==="__deleted"&&E.value==="1"&&(_.get(E.row_id)??"")<E.hlc)_.set(E.row_id,E.hlc);for(let E of t.changes)if(E.dataset==="doc_blocks"&&E.col==="__deleted"&&E.value==="1")l.add(E.row_id);for(let E=0;E<t.changes.length;E++){let g=t.changes[E],A=e.query("SELECT hlc,value FROM crdt_changes WHERE dataset=? AND row_id=? AND col=? ORDER BY hlc DESC LIMIT 1").get(g.dataset,g.row_id,g.col),L=g.dataset==="doc_blocks"&&!s.has(g.row_id)&&!c.has(g.row_id),F=g.dataset==="doc_blocks"&&(l.has(g.row_id)||L)&&g.col!=="__deleted"&&g.col!=="doc_id",X=g.dataset==="doc_blocks"&&g.col==="text"&&A&&A.hlc!==g.hlc&&A.value!==g.value&&A.hlc!==t.bases?.[E]&&!f(g,A.hlc,g.hlc)&&!f(g,g.hlc,A.hlc),te=_.get(g.row_id),ce=te?e.query("SELECT value FROM meta WHERE key=?").get(`sync_v2_base:${te}:doc_blocks:${g.row_id}:__deleted`):null,de=ce?JSON.parse(ce.value):null,Ce=F&&de!==null&&f(g,de,g.hlc);if(g.dataset==="doc_blocks"&&g.col==="__deleted"&&g.value==="1"){let Pe=e.query("SELECT hlc,value FROM crdt_changes WHERE dataset='doc_blocks' AND row_id=? AND col='text' ORDER BY hlc DESC LIMIT 1").get(g.row_id);if(Pe&&(!de||!f({...g,col:"text"},de,Pe.hlc)))e.query("INSERT OR IGNORE INTO sync_recovery_items(id,kind,target,local,remote) VALUES(?,?,?,?,NULL)").run(`${t.workspaceId}:${Pe.hlc}:${g.row_id}:text`,"block",g.row_id,JSON.stringify({title:"删除与编辑冲突",body:Pe.value===null?"":JSON.parse(Pe.value)}))}if(F&&g.col==="text"&&!Ce&&A?.hlc!==g.hlc||!F&&X){let Pe=!F&&A&&g.hlc>A.hlc,Qe=(De)=>De===null?"":JSON.parse(De);e.query("INSERT OR IGNORE INTO sync_recovery_items(id,kind,target,local,remote) VALUES(?,?,?,?,?)").run(`${t.workspaceId}:${g.hlc}:${g.row_id}:${g.col}`,"block",g.row_id,JSON.stringify({title:F?"已删除段落的编辑":"段落编辑冲突",body:Qe(Pe?A.value:g.value),recoveryVersion:2}),A?JSON.stringify({body:Qe(Pe?g.value:A.value)}):null)}if(L||F||g.dataset==="doc_blocks"&&l.has(g.row_id)&&g.col==="__deleted"&&g.value!=="1")continue;let ge=Fr(e,[g]);n+=ge.received,o+=ge.poisoned??0;for(let[Pe,Qe]of Object.entries(ge.skewed))i[Pe]=(i[Pe]??0)+Qe}return{received:n,skewed:i,poisoned:o}})}var As=Oe(()=>{Ke();it()});function Zg(e,t){return t.map((r)=>{let n=e.query("SELECT value FROM meta WHERE key=?").get(`sync_v2_base:${r.hlc}:${r.dataset}:${r.row_id}:${r.col}`);return n?JSON.parse(n.value):null})}function Gg(e,t,r){let n=at(e);if(!n)return Fr(e,t);if(!r||r.length!==t.length||r.some((o)=>o!==null&&typeof o!=="string"))throw new T("upgrade_required","v2 peer edit baselines are required");return Ve(e,()=>{e.exec("CREATE TABLE IF NOT EXISTS sync_v2_peer_pending (id TEXT PRIMARY KEY, change_json TEXT NOT NULL)");let o=t.filter((s)=>!e.query("SELECT 1 FROM crdt_changes WHERE dataset=? AND row_id=? AND col=? AND hlc=?").get(s.dataset,s.row_id,s.col,s.hlc)),i=Eo(e,{protocolVersion:2,workspaceId:n.workspaceId,epoch:n.epoch,member:"http-delivery",first:1,last:t.length,changes:t,bases:r});if(i.poisoned||Object.values(i.skewed).some((s)=>s>0))throw new T("invalid_input","v2 peer batch was not completely accepted");for(let s of o)e.query("INSERT OR IGNORE INTO sync_v2_peer_pending(id,change_json) VALUES(?,?)").run(Mr(s),JSON.stringify(s));return i})}function Zn(e){if(!e.query("SELECT 1 FROM sqlite_master WHERE type='table' AND name='sync_v2_peer_pending'").get())return[];return e.query("SELECT change_json FROM sync_v2_peer_pending ORDER BY id").all().map((t)=>JSON.parse(t.change_json))}function Kg(e,t){if(!e.query("SELECT 1 FROM sqlite_master WHERE type='table' AND name='sync_v2_peer_pending'").get())return;for(let r of t)e.query("DELETE FROM sync_v2_peer_pending WHERE id=?").run(Mr(r))}var fi=Oe(()=>{ho();it();Ke();Kt();As()});var Br,MO,FO,Jg,zO,UO,Xg="/sync",Yg="/health",Qg="/api/pair";var yn=Oe(()=>{Kt();Wn();Br=_t({hlc:Be().describe("Hybrid Logical Clock timestamp"),node_id:Be().describe("Origin node that produced the change"),dataset:Be().describe("CRDT dataset, e.g. databases / records / documents"),row_id:Be().describe("Row identifier within the dataset"),col:Be().describe("Column / property identifier"),value:Be().nullable().describe("JSON-encoded field value, or null"),txn:Be().nullable().optional().describe("Change-group id (one logical mutation)")}),MO=_t({dataVersion:Dt().int().positive().safe().optional(),minSupportedDataVersion:Dt().int().positive().safe().optional(),maxSupportedDataVersion:Dt().int().positive().safe().optional(),generation:Vn.optional(),bases:Gt(Be().nullable()).optional(),node_id:Be().describe("Calling client's node id"),since:Dt().describe("Server cursor the client last pulled"),changes:Gt(Br).describe("Client's changes to push"),limit:Dt().optional().describe("Max changes to return (pagination for hydration)"),exclude_datasets:Gt(Be()).optional().describe("Datasets to omit from the pull (partial replica)")}),FO=_t({dataVersion:Dt().int().positive().safe().optional(),minSupportedDataVersion:Dt().int().positive().safe().optional(),maxSupportedDataVersion:Dt().int().positive().safe().optional(),generation:Vn.optional(),bases:Gt(Be().nullable()).optional(),node_id:Be().describe("Server's node id"),changes:Gt(Br).describe("Server changes after `since`"),cursor:Dt().describe("New server cursor for the client to store"),skewed_rejected:Dt().optional().describe("Pushed changes the server refused for being stamped >5 min in the future")}),Jg=_t({dataVersion:Dt().int().positive().safe().optional(),minSupportedDataVersion:Dt().int().positive().safe().optional(),maxSupportedDataVersion:Dt().int().positive().safe().optional(),generation:Vn.optional(),ok:aS(),node:Be().describe("Server's node id"),capabilities:Gt(Be()).optional().describe("Optional protocol features supported by this server"),version:Be().optional().describe("Core version, for mixed-version workspace warnings")}),zO=_t({code:Be().describe("One-time pairing code minted by this server"),node_id:Be().describe("Calling device's node id"),grant:Be().describe("Durable credential the caller issues to us"),self_url:Be().optional().describe("Caller's reachable server URL (for mutual sync)")}),UO=_t({node_id:Be().describe("This server's node id"),grant:Be().describe("Durable credential we issue to the caller")})});async function rr(e,t=30000,r){if(!Number.isFinite(t)||t<=0)throw RangeError("sync timeoutMs must be a positive finite number");let n=new AbortController,o=()=>n.abort(r?.reason);if(r?.aborted)o();else r?.addEventListener("abort",o,{once:!0});let i=setTimeout(()=>n.abort(Error("sync request timed out")),t),s;try{let c=new Promise((l,u)=>{if(s=()=>u(n.signal.reason??Error("sync request aborted")),n.signal.aborted)s();else n.signal.addEventListener("abort",s,{once:!0})});if(n.signal.aborted)return await c;return await Promise.race([e(n.signal),c])}finally{if(clearTimeout(i),r?.removeEventListener("abort",o),s)n.signal.removeEventListener("abort",s)}}function FS(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 zS(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 Gc(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 US(e,t,r){if(r.length===0)return t;let n=new Set(r.map(em)),o=e.query("SELECT rowid AS seq, hlc, node_id, dataset, row_id, col FROM crdt_changes WHERE rowid > ? ORDER BY rowid LIMIT ?").all(t,r.length),i=t;for(let s of o){if(!n.has(em(s)))break;i=s.seq}return i}async function Os(e,t,r={}){let n=typeof r==="string"?{token:r}:r,o=n.measureSync??((F,X)=>X()),{node:i,peer:s,bearer:c,toPush:l}=o("prepare",()=>{let F=Je(e),X=FS(e,t),te=n.token??X.token??void 0;if(n.pushLimit!=null&&(!Number.isSafeInteger(n.pushLimit)||n.pushLimit<=0))throw RangeError("sync pushLimit must be a positive integer");if(n.pullLimit!=null&&(!Number.isSafeInteger(n.pullLimit)||n.pullLimit<=0))throw RangeError("sync pullLimit must be a positive integer");let ce=Lt(e,X.push_cursor,{limit:n.pushLimit});return{node:F,peer:X,bearer:te,toPush:ce}}),u={"content-type":"application/json"};if(c)u.authorization=`Bearer ${c}`;lr(Xr(e));let f=at(e),_=!!e.query("SELECT 1 FROM meta WHERE key='sync_version_pending_join' AND value=?").get(t),E=(F)=>{if(F.dataVersion===void 0)return;let X=F.generation?.workspaceId;if(f&&X&&f.workspaceId!==X)throw new T("rebootstrap_required","Peer workspace differs");if(typeof X==="string"&&F.dataVersion>=2&&(f?.workspaceId===X||!f&&_)){if((Ot(e)?.dataVersion??1)>F.dataVersion)throw new T("busy","Peer data version moved backwards");In(e,X,F.dataVersion)}lr(F.dataVersion)},g=await rr(async(F)=>{{let te=await(n.fetch??fetch)(new URL("/health",t),{method:"GET",headers:u,signal:F});if(!te.ok)throw new T(te.status===401||te.status===403?"auth":"network",`sync preflight failed: ${te.status}`);let ce=await te.json();if(F.aborted)throw F.reason;E(ce),Zc(e,ce.generation)}Qt(e);let X=await(n.fetch??fetch)(new URL(Xg,t),{method:"POST",headers:u,body:o("serialize",()=>JSON.stringify({...vr,dataVersion:Xr(e),...f?{generation:f,bases:Zg(e,l.changes)}:{},node_id:i,since:s.pull_cursor,changes:l.changes,...n.pullLimit!=null?{limit:n.pullLimit}:{},...n.excludeDatasets?.length?{exclude_datasets:n.excludeDatasets}:{}})),signal:F});if(!X.ok){let te=await X.text(),ce,de,Ce;try{let ge=JSON.parse(te);if(ge.code==="client_update_required"&&Number.isSafeInteger(ge.workspaceDataVersion))ce=ge.workspaceDataVersion,de=ge.workspaceId;if(ge.code==="client_update_required"||ge.code==="upgrade_required"||ge.code==="rebootstrap_required"||ge.code==="history_unavailable")Ce=ge.code}catch{}if(ce!==void 0){if(F.aborted)throw F.reason;E({dataVersion:ce,generation:{workspaceId:de}})}throw new T(Ce??(X.status===401||X.status===403?"auth":"network"),`sync failed: ${X.status} ${te}`)}return await X.json()},n.timeoutMs,n.signal);if(n.signal?.aborted)throw n.signal.reason??Error("sync request aborted");E(g),Zc(e,g.generation),Ko(e,t);let A=g.changes??[],L=o("ingest",()=>Gg(e,A,g.bases));return o("acknowledge",()=>{let F=L.received,X=US(e,l.cursor,A);zS(e,t,{pull_cursor:g.cursor,push_cursor:X});let te=Gc(t,L.skewed);if(g.skewed_rejected)te.push(`${t} refused ${g.skewed_rejected} of this device's change(s) as stamped more than 5 min in the future — run \`mh repair --clock\` here`);return{pushed:l.changes.length,pulled:F,received:A.length,...n.pushLimit!=null?{pendingPush:Lt(e,X,{limit:1}).changes.length>0}:{},...te.length?{warnings:te}:{}}})}var em=(e)=>`${e.hlc}\x00${e.node_id}\x00${e.dataset}\x00${e.row_id}\x00${e.col}`;var Cs=Oe(()=>{fi();er();Kt();Zt();it();yn();Ke()});function tm(e){try{let t=new URL(e),r=t.port&&t.port!==BS[t.protocol]?`:${t.port}`:"";return t.hostname+r}catch{return e.trim().replace(/^[a-z]+:\/\//i,"").replace(/\/.*$/,"").replace(/:(80|443)$/,"")}}function So(e,t,r){let n=r?.trim()||"metahub";return`s3://${tm(e)}/${t}/${n}`}var BS;var hi=Oe(()=>{BS={"https:":"443","http:":"80"}});function bn(e){return typeof structuredClone==="function"?structuredClone(e):JSON.parse(JSON.stringify(e))}function wn(e){if(typeof TextDecoder<"u")return new TextDecoder("utf-8",{fatal:!0}).decode(e);let t=[],r=[],n=()=>{t.push(String.fromCharCode(...r)),r.length=0};for(let o=0;o<e.length;){let i=e[o++],s=i,c=0,l=0;if(i>=194&&i<=223)s=i&31,c=1,l=128;else if(i>=224&&i<=239)s=i&15,c=2,l=2048;else if(i>=240&&i<=244)s=i&7,c=3,l=65536;else if(i>=128)throw Error("Invalid UTF-8 leading byte");while(c--){let u=e[o++];if(u===void 0||(u&192)!==128)throw Error("Invalid UTF-8 continuation");s=s<<6|u&63}if(s<l||s>1114111||s>=55296&&s<=57343)throw Error("Invalid UTF-8 code point");if(s>65535)s-=65536,r.push(55296|s>>10,56320|s&1023);else r.push(s);if(r.length>=4096)n()}if(r.length)n();return t.join("").replace(/^\uFEFF/,"")}async function nr(e){let t=new Uint8Array(e.length);return t.set(e),[...new Uint8Array(await crypto.subtle.digest("SHA-256",t))].map((r)=>r.toString(16).padStart(2,"0")).join("")}function rm(e){let{client:t,codec:r}=e,n=1048576,o=(u)=>`${e.prefix}/control/${String(u).padStart(16,"0")}.commit`,i=()=>({sequence:0,hash:null,state:e.initialState(),serverTime:null}),s=(u)=>{if(!u||typeof u!=="object")throw new T("invalid_input","invalid commit record");let f=u;if(f.protocolVersion!==2||f.workspaceId!==e.workspaceId||!Number.isSafeInteger(f.sequence)||f.sequence<1||typeof f.requestId!=="string"||!f.requestId.length||!(f.previous===null||typeof f.previous==="string"&&/^[a-f0-9]{64}$/.test(f.previous)))throw new T("invalid_input","invalid commit envelope");return{...f,payload:e.parsePayload(f.payload)}},c=new Map,l=async(u)=>{if(!t.getWithMetadata)throw new T("invalid_input","commit log requires metadata reads");let f=c.get(u.sequence+1);if(!f){let F=await t.getWithMetadata(o(u.sequence+1),{maxBytes:1048576});if(!F)return null;let X=s(await r.decode(F.bytes)),{lastModified:te,serverDate:ce}=F;if(te===null||ce===null||te>ce)throw new T("clock_skew","commit time cannot be verified");f={record:X,hash:await nr(F.bytes),at:te}}let _=bn(f.record),E=f.at;if(_.sequence!==u.sequence+1||_.previous!==u.hash)throw new T("conflict","commit chain is discontinuous");if(u.serverTime!==null&&E<u.serverTime)throw new T("clock_skew","commit time cannot be verified");c.set(_.sequence,f);let g=bn(u.state),A=null;try{g=e.reduce(g,_.payload,E)}catch(F){if(!(F instanceof T))throw F;A=F,g=bn(u.state)}if(!A)e.checkAccepted?.(g,_.payload);let L={sequence:_.sequence,hash:f.hash,state:g,serverTime:E};return{record:_,head:L,rejected:A}};return{initial:i,async read(u=i(),f,_=1/0){let E=u;while(E.sequence<_){let g=await l(E);if(!g){if(_===1/0)e.checkHead?.(E.state);return E}if(f)await f(g.record,g.head,g.rejected);E=g.head}return E},async append(u,f){if(!await t.conditionalCreateCapability?.())throw new T("invalid_input","atomic conditional creation is unavailable");if(!u)throw new T("invalid_input","requestId is required");let _=i();for(let E=0;E<1e4;){let g=await l(_);if(g){if(_=g.head,g.record.requestId===u){if(g.rejected)throw g.rejected;return _}continue}e.checkHead?.(_.state),E++;let A=e.parsePayload(f(bn(_.state)));e.validateProposal?.(A),e.reduce(bn(_.state),A,_.serverTime??0);let L={protocolVersion:2,workspaceId:e.workspaceId,sequence:_.sequence+1,previous:_.hash,requestId:u,payload:A},F=await r.encode(L);if(F.length>1048576)throw new T("invalid_input","commit metadata exceeds limit");try{await t.put(o(L.sequence),F,{ifNoneMatch:!0})}catch(te){if(!(te instanceof T)||te.code!=="conflict")throw te}let X=await l(_);if(!X)throw new T("busy","commit is not yet visible; retry the same requestId");if(_=X.head,X.record.requestId===u){if(X.rejected)throw X.rejected;return _}}throw new T("busy","commit contention; retry the same requestId")}}}var ko=Oe(()=>{Ke()});function om(){return{dataVersion:2,epoch:0,members:{},preparing:null,lastGcAt:null,checkpoint:null,protectedUntil:null}}function im(e,t,r){if(!Number.isSafeInteger(r)||r<0)throw new T("clock_skew","invalid storage time");let n=bn(e);if(t.type==="clock")return n;if(t.epoch!==n.epoch)yt("sync epoch is obsolete; rebootstrap required");let o=(s)=>{let c=Object.hasOwn(n.members,s)?n.members[s]:void 0;if(!c||c.expiresAt<=r)return yt("member qualification expired");return c},i=(s)=>{if(!n.preparing||n.preparing.id!==s)return yt("prepare is not active");return n.preparing};switch(t.type){case"join":if(n.preparing)yt("membership frozen during prepare");if(!/^[a-zA-Z0-9_-]{1,128}$/.test(t.member)||["__proto__","constructor","prototype"].includes(t.member))yt("invalid member id");if(Object.hasOwn(n.members,t.member))yt("incarnation already registered");if(t.checkpoint!==n.checkpoint)yt("checkpoint mismatch");if(t.replaces){let s=n.members[t.replaces.member];if(!s||s.sequence!==t.replaces.sequence||t.replaces.member===t.member)yt("replacement does not cover the previous source prefix");delete n.members[t.replaces.member]}n.members[t.member]={sequence:0,expiresAt:r+30*dr,renewedAt:r,sealed:!1};break;case"batch":{let s=o(t.member);if(s.sealed)yt("member is sealed");if(!Number.isSafeInteger(t.first)||!Number.isSafeInteger(t.last)||t.first!==s.sequence+1||t.last<t.first||!nm(t.objectHash))yt("noncontiguous source batch");s.sequence=t.last;break}case"renew":{if(n.preparing)yt("membership frozen during prepare");let s=o(t.member);if(t.sequence!==s.sequence||t.checkpoint!==n.checkpoint)yt("incomplete synchronization receipt");if(r-s.renewedAt<dr)yt("qualification can renew only once per day");s.renewedAt=r,s.expiresAt=r+30*dr;break}case"prepare":if(n.preparing)yt("another prepare is active");if(t.targetDataVersion!==void 0&&t.targetDataVersion!==n.dataVersion+1)yt("invalid target data version");if(!t.id||t.targetDataVersion===void 0&&n.lastGcAt!==null&&r-n.lastGcAt<Er.gcIntervalMs)yt("collection is not due");n.preparing={id:t.id,startedAt:r,...t.targetDataVersion===void 0?{}:{targetDataVersion:t.targetDataVersion},members:Object.keys(n.members).filter((s)=>n.members[s].expiresAt>r).sort()};break;case"seal":{let s=i(t.id),c=n.members[t.member];if(!c)return yt("seal member is missing");if(!s.members.includes(t.member)||c.sequence!==t.sequence)yt("seal does not cover source prefix");if(r-s.startedAt>=Er.prepareMs)yt("prepare timed out");c.sealed=!0;break}case"cancel":i(t.id),n.preparing=null;for(let s of Object.values(n.members))s.sealed=!1;break;case"upgrade":case"commit":{if(t.type==="upgrade"){if(t.from!==e.dataVersion||t.to!==t.from+1)yt("invalid data version transition");n.dataVersion=t.to}let s=i(t.id);if(s.targetDataVersion!==(t.type==="upgrade"?t.to:void 0))yt("different barrier purpose");if(r-s.startedAt>=Er.prepareMs)yt("prepare timed out");if(!s.members.every((l)=>n.members[l].sealed))yt("unsealed member blocks collection");if(!nm(t.checkpoint))yt("invalid checkpoint hash");let c={};for(let l of s.members)c[l]={...n.members[l],sealed:!1};if(n.members=c,n.epoch++,n.checkpoint=t.checkpoint,t.type==="commit")n.lastGcAt=r;n.protectedUntil=r+Er.protectionDays*dr,n.preparing=null;break}default:yt("unknown retention event")}return n}var dr=86400000,Er,yt=(e)=>{throw new T("conflict",e)},nm=(e)=>/^[a-f0-9]{64}$/.test(e);var gi=Oe(()=>{Ke();Er=Object.freeze({syncDays:30,historyDays:90,protectionDays:7,prepareMs:60000,gcIntervalMs:7*dr})});function Sr(e){let t=new Uint8Array(e.byteLength);return t.set(e),t.buffer}function Nr(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return btoa(t)}function Nt(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 Gn(e){return Nr(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function mi(){return crypto.getRandomValues(new Uint8Array(am))}async function cm(e,t){if(sm){let n=await sm(e,t,Kc);if(n.length!==am)throw new T("invalid_input","invalid derived key length");return crypto.subtle.importKey("raw",Sr(n),{name:"AES-GCM"},!1,["encrypt","decrypt"])}let r=await crypto.subtle.importKey("raw",Sr(new TextEncoder().encode(e)),"PBKDF2",!1,["deriveKey"]);return crypto.subtle.deriveKey({name:"PBKDF2",salt:Sr(t),iterations:Kc,hash:"SHA-256"},r,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async function lm(e,t){let r=crypto.getRandomValues(new Uint8Array(jS)),n=await cm(t,r),o=crypto.getRandomValues(new Uint8Array(xo)),i=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:Sr(o)},n,Sr(e))),s=new Uint8Array(o.length+i.length);return s.set(o,0),s.set(i,o.length),{v:1,kdf:"PBKDF2-SHA256",iter:Kc,salt:Nr(r),wrap:"AES-GCM",wrapped_key:Nr(s)}}async function Jc(e,t){if(e.v!==1||e.kdf!=="PBKDF2-SHA256"||e.wrap!=="AES-GCM")throw new T("invalid_input","unsupported key envelope format");let r=Nt(e.salt),n=await cm(t,r),o=Nt(e.wrapped_key),i=o.subarray(0,xo),s=o.subarray(xo);try{let c=await crypto.subtle.decrypt({name:"AES-GCM",iv:Sr(i)},n,Sr(s));return new Uint8Array(c)}catch{throw new T("auth","wrong passphrase — could not unwrap the master key")}}async function um(e){return crypto.subtle.importKey("raw",Sr(e),{name:"AES-GCM"},!1,["encrypt","decrypt"])}async function pr(e,t){let r=await um(e),n=crypto.getRandomValues(new Uint8Array(xo)),o=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:Sr(n)},r,Sr(t))),i=new Uint8Array(n.length+o.length);return i.set(n,0),i.set(o,n.length),i}async function kr(e,t){let r=await um(e),n=t.subarray(0,xo),o=t.subarray(xo);try{let i=await crypto.subtle.decrypt({name:"AES-GCM",iv:Sr(n)},r,Sr(o));return new Uint8Array(i)}catch{throw new T("auth","could not decrypt — wrong master key or corrupt data")}}var Kc=600000,jS=16,xo=12,am=32,sm=null;var rn=Oe(()=>{Ke()});function Xc(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 i=0;while((e[i]??"0")===t[i])i++;if(i>0)return t.slice(0,i)+Xc(e.slice(i),t.slice(i))}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]+Xc(e.slice(1),null)}function _r(e,t){return Xc(e??"",t)}function nn(e,t,r){if(r<=0)return[];if(r===1)return[_r(e,t)];if(t===null){let i=_r(e,null),s=[i];for(let c=1;c<r;c++)i=_r(i,null),s.push(i);return s}if(e===null){let i=_r(null,t),s=[i];for(let c=1;c<r;c++)i=_r(null,i),s.unshift(i);return s}let n=Math.floor(r/2),o=_r(e,t);return[...nn(e,o,n),o,...nn(o,t,r-n-1)]}function jr(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 fm(e){return ur("blk",e.split(`
75
+ `,1)[0]??"")}function GS(e,t,r){let n=fm(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 Ro(e,t,r,n,o){let i=nn(n,o,r.length);r.forEach((s,c)=>GS(e,t,{text:s.text,order_key:i[c],blankAfter:s.blankAfter}))}function Kn(e,t){if(Qa(e,t))return;let r=e.query("SELECT body FROM documents WHERE id = ?").get(t),n=Pn(r?.body??"");if(n.length)Ro(e,t,n,null,null)}function Yc(e,t,r,n=!!at(e)){let o=jr(e,t),i=Pn(r),s=Cd(o.map((u)=>u.text),i.map((u)=>u.text),{preserveReplacements:n});for(let u of s.deleted)_e(e,"doc_blocks",o[u].id,"__deleted",1);let{items:c}=s,l=0;while(l<c.length){let u=c[l];if("keep"in u){let g=o[u.keep];if(g.text!==i[l].text)_e(e,"doc_blocks",g.id,"text",i[l].text);let A=i[l].blankAfter;if((g.blank_after??0)!==A)_e(e,"doc_blocks",g.id,"blank_after",A);l++;continue}let f=l;while(f<c.length&&"insert"in c[f])f++;let _=l>0?o[c[l-1].keep].order_key:null,E=f<c.length?o[c[f].keep].order_key:null;Ro(e,t,i.slice(l,f),_,E),l=f}}function At(e,t){let r=e.query(`SELECT MAX(hlc) AS h FROM crdt_changes
76
+ WHERE (dataset = 'documents' AND row_id = ?)
77
+ OR (dataset = 'doc_blocks' AND row_id IN (SELECT id FROM doc_blocks WHERE doc_id = ?))`).get(t,t),n=e.query("SELECT value FROM meta WHERE key=?").get(`sync_v2_doc_version:${t}`);return(n?.value??"")>(r.h??"")?n.value:r.h??""}function nt(e,t){return e.query(`SELECT ${WS} FROM documents WHERE id = ? AND __deleted = 0`).get(t)}function hm(e,t={}){let r=`SELECT ${ZS} FROM documents WHERE __deleted = 0`;if(t.parent_id!==void 0)return e.query(`${r} AND parent_id = ? ${Is}`).all(t.parent_id);if(t.database_id)return e.query(`${r} AND database_id = ? ${Is}`).all(t.database_id);return e.query(`${r} ${Is}`).all()}function Qc(e){return e===null?{clause:"parent_id IS NULL",args:[]}:{clause:"parent_id = ?",args:[e]}}function KS(e){return dm(e,"meta")&&dm(e,"crdt_changes")}function dm(e,t){return e.query("SELECT 1 AS ok FROM sqlite_master WHERE type = 'table' AND name = ?").get(t)!=null}function gm(e,t,r){let n=Qc(t),o=r?" AND id <> ?":"";return e.query(`SELECT order_key FROM documents WHERE ${n.clause}${o}
78
+ AND __deleted = 0 AND order_key IS NOT NULL
79
+ ORDER BY order_key DESC, id DESC LIMIT 1`).get(...n.args,...r?[r]:[])?.order_key??null}function mm(e,t){let r=Qc(t);return e.query(`SELECT id, order_key FROM documents WHERE ${r.clause} AND __deleted = 0 ${Is}`).all(...r.args)}function JS(e,t){let r=mm(e,t),n=nn(null,null,r.length);r.forEach((o,i)=>{if(o.order_key!==n[i])_e(e,"documents",o.id,"order_key",n[i])})}function _m(e,t){let r=KS(e),n=Qc(t),o=e.query(`SELECT id FROM documents WHERE ${n.clause} AND __deleted = 0 AND order_key IS NULL
80
+ ORDER BY created_hlc, id`).all(...n.args);if(!o.length)return;let i=nn(gm(e,t),null,o.length);o.forEach((s,c)=>{if(r)_e(e,"documents",s.id,"order_key",i[c]);else e.query("UPDATE documents SET order_key = ? WHERE id = ?").run(i[c],s.id)})}function Ns(e,t,r,n){let o=r;while(o){if(o===t)throw new T("invalid_input",`cannot set parent_id: would create a cycle (${t})`);o=nt(e,o)?.parent_id??null}let i=nt(e,t);if(i&&(i.parent_id??null)!==r)_e(e,"documents",t,"parent_id",r);let s;if(!n)s=_r(gm(e,r,t),null);else{_m(e,r);let c=()=>{let f=mm(e,r).filter((E)=>E.id!==t),_=f.findIndex((E)=>E.id===n.targetId);if(_<0)throw new T("not_found",`no such target document: ${n.targetId}`);return n.where==="before"?[f[_-1]?.order_key??null,f[_].order_key]:[f[_].order_key,f[_+1]?.order_key??null]},[l,u]=c();if(l!==null&&u!==null&&l>=u)JS(e,r),[l,u]=c();s=_r(l,u)}_e(e,"documents",t,"order_key",s)}function pm(e,t,r,n){return e.query(`SELECT id FROM ${t} WHERE ${r} = ? AND __deleted = 0`).all(n).map((o)=>o.id)}function vm(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 HS,WS,VS,ZS,_i,Is="ORDER BY order_key IS NULL, order_key, created_hlc, id",ym,el,bm,Ps,_C,yC,bC,wC,wm,qs;var on=Oe(()=>{Kt();it();Vt();it();Ke();HS=["id","title","body","database_id","parent_id","created_hlc","order_key"],WS=HS.join(", "),VS=["id","title","database_id","parent_id","created_hlc","order_key"],ZS=VS.join(", ");_i=We(function(t,r){let n=ur("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(Ns(t,n,r.parent_id??null),r.body!==void 0){let i=Pn(r.body);if(i.length)Ro(t,n,i,null,null)}return nt(t,n)});ym=We(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)_m(t,n.parent_id)});el=We(function(t,r,n,o){let i=nt(t,r);if(!i)throw new T("not_found",`no such document: ${r}`);if(r===n)return i;let s=nt(t,n);if(!s)throw new T("not_found",`no such target document: ${n}`);if(o==="into")Ns(t,r,n);else Ns(t,r,s.parent_id,{targetId:n,where:o});return nt(t,r)}),bm=We(function(t,r,n={}){let o=nt(t,r);if(!o)throw new T("not_found",`no such document: ${r}`);Kn(t,r);let i=jr(t,r),s=n.parentId!==void 0?n.parentId:o.parent_id,c=_i(t,{title:n.title??o.title,database_id:o.database_id??void 0,parent_id:s??void 0});if(i.length)Ro(t,c.id,i.map((l)=>({text:l.text,blankAfter:l.blank_after})),null,null);if(s===o.parent_id)el(t,c.id,o.id,"after");return nt(t,c.id)}),Ps=We(function(t,r,n,o={}){if(o.preserveBlockIdentity&&o.ifMatch===void 0)throw new T("invalid_input","stable block edits require ifMatch");let i=nt(t,r);if(!i)throw new T("not_found",`no such document: ${r}`);if(o.ifMatch!==void 0&&At(t,r)!==o.ifMatch)throw new T("stale",`stale: document changed since ${o.ifMatch}; re-read first`);if(n.title!==void 0&&n.title!==(i.title??""))_e(t,"documents",r,"title",n.title);if(n.database_id!==void 0&&n.database_id!==(i.database_id??null))_e(t,"documents",r,"database_id",n.database_id);if(n.parent_id!==void 0){let s=n.parent_id??null;if((nt(t,r).parent_id??null)!==s)Ns(t,r,s)}if(n.body!==void 0)Kn(t,r),Yc(t,r,n.body,o.preserveBlockIdentity??(o.ifMatch!==void 0&&!!at(t)));return nt(t,r)}),_C=We(function(t,r,n){if(!nt(t,r))throw new T("not_found",`no such document: ${r}`);if(n.ifMatch!==void 0&&At(t,r)!==n.ifMatch)throw new T("stale",`stale: document changed since ${n.ifMatch}; re-read first`);if(n.old==="")throw new T("invalid_input","--old must not be empty");Kn(t,r);let o=jr(t,r),i=qn(o.map((l)=>({text:l.text,blankAfter:l.blank_after}))),s=vm(i,n.old);if(s===0)throw new T("invalid_input","anchor not found: no match for --old");if(s>1&&!n.replaceAll)throw new T("ambiguous",`${s} matches for --old; add surrounding context or use --replace-all`);let c=n.replaceAll?i.replaceAll(n.old,()=>n.new):i.replace(n.old,()=>n.new);return Yc(t,r,c),{id:r,changed:c!==i,replaced:n.replaceAll?s:1,version:At(t,r)}}),yC=We(function(t,r,n){if(!nt(t,r))throw new T("not_found",`no such document: ${r}`);if(n.edits.length===0)throw new T("invalid_input","no edits given");if(n.ifMatch!==void 0&&At(t,r)!==n.ifMatch)throw new T("stale",`stale: document changed since ${n.ifMatch}; re-read first`);Kn(t,r);let o=qn(jr(t,r).map((c)=>({text:c.text,blankAfter:c.blank_after}))),i=o,s=0;if(n.edits.forEach((c,l)=>{if(c.old==="")throw new T("invalid_input",`edit[${l}]: old must not be empty`);let u=vm(i,c.old);if(u===0)throw new T("invalid_input",`edit[${l}]: anchor not found: no match for old`);if(u>1&&!c.replaceAll)throw new T("ambiguous",`edit[${l}]: ${u} matches for old; add surrounding context or set replaceAll`);let f=c.new??"";i=c.replaceAll?i.replaceAll(c.old,()=>f):i.replace(c.old,()=>f),s+=c.replaceAll?u:1}),i!==o)Yc(t,r,i);return{id:r,changed:i!==o,replaced:s,version:At(t,r)}}),bC=We(function(t,r,n){if(!nt(t,r))throw new T("not_found",`no such document: ${r}`);Kn(t,r);let o=Pn(n);if(o.length){let i=jr(t,r),s=i.length?i[i.length-1].order_key:null;Ro(t,r,o,s,null)}return{id:r,changed:o.length>0,replaced:o.length,version:At(t,r)}}),wC=We(function(t,r,n){if(!nt(t,r))throw new T("not_found",`no such document: ${r}`);Kn(t,r);let o=Pn(n);if(o.length){let i=jr(t,r),s=i.length?i[0].order_key:null;Ro(t,r,o,null,s)}return{id:r,changed:o.length>0,replaced:o.length,version:At(t,r)}}),wm=We(function(t,r){if(!nt(t,r))return!1;_e(t,"documents",r,"__deleted",1);for(let n of pm(t,"doc_blocks","doc_id",r))_e(t,"doc_blocks",n,"__deleted",1);for(let n of pm(t,"documents","parent_id",r))_e(t,"documents",n,"parent_id",null);return!0});qs=We(function(t,r,n,o){if(!nt(t,r))throw new T("not_found",`no such document: ${r}`);if(!o?.ifMatch)throw new T("invalid_input","block edits require ifMatch");if(At(t,r)!==o.ifMatch)throw new T("stale","document changed; re-read first");Kn(t,r);let s=[],c=(E)=>{let g=jr(t,r).find((A)=>A.id===E);if(!g)throw new T("not_found","block is missing, deleted, or belongs to another document");return g},l=(E,g)=>{if(typeof E!=="string"||!E.length||Pn(E).length!==1)throw new T("invalid_input","expected one nonempty block");if(g!==void 0&&(!Number.isSafeInteger(g)||g<0))throw new T("invalid_input","blankAfter must be a nonnegative integer")},u=(E,g,A)=>{l(g,A);let L=c(E);if(L.text!==g)_e(t,"doc_blocks",E,"text",g);if(A!==void 0&&L.blank_after!==A)_e(t,"doc_blocks",E,"blank_after",A)},f=(E,g)=>{let A=jr(t,r).filter((F)=>F.id!==g),L=E===null?-1:A.findIndex((F)=>F.id===E);if(E!==null&&L===-1)throw new T("not_found","insertion anchor is missing");return _r(A[L]?.order_key??null,A[L+1]?.order_key??null)},_=(E,g,A=0)=>{l(g,A);let L=fm(g),F=f(E);if(_e(t,"doc_blocks",L,"doc_id",r),_e(t,"doc_blocks",L,"order_key",F),A)_e(t,"doc_blocks",L,"blank_after",A);return _e(t,"doc_blocks",L,"text",g),s.push(L),L};for(let E of n)switch(E.type){case"update":u(E.id,E.text,E.blankAfter);break;case"insert":_(E.after,E.text,E.blankAfter);break;case"delete":c(E.id),_e(t,"doc_blocks",E.id,"__deleted",1);break;case"move":{let g=c(E.id);if(E.after===E.id)throw new T("invalid_input","cannot move after itself");let A=jr(t,r);if((A[A.findIndex((L)=>L.id===g.id)-1]?.id??null)===E.after)break;_e(t,"doc_blocks",E.id,"order_key",f(E.after,E.id));break}case"split":{let g=c(E.id);if(E.parts.length<2)throw new T("invalid_input","split requires at least two parts");E.parts.forEach((L)=>l(L.text,L.blankAfter)),u(E.id,E.parts[0].text,E.parts[0].blankAfter??0);let A=E.id;for(let L=1;L<E.parts.length;L++){let F=E.parts[L];A=_(A,F.text,F.blankAfter??(L===E.parts.length-1?g.blank_after:0))}break}case"merge":{if(E.ids.length<2||new Set(E.ids).size!==E.ids.length)throw new T("invalid_input","merge requires distinct adjacent blocks");let g=jr(t,r),A=g.findIndex((L)=>L.id===E.ids[0]);if(A<0||!E.ids.every((L,F)=>g[A+F]?.id===L))throw new T("invalid_input","merge blocks must be adjacent and ordered");u(E.ids[0],E.text,E.blankAfter??g[A+E.ids.length-1].blank_after);for(let L of E.ids.slice(1))_e(t,"doc_blocks",L,"__deleted",1);break}default:throw new T("invalid_input","unknown block edit")}return{document:nt(t,r),version:At(t,r),inserted:s}},"block-edit")});function bi(e,t,r){return Ve(e,()=>{let n=e.query("SELECT id, doc_id AS documentId FROM doc_blocks WHERE __deleted=1 ORDER BY id").all(),o=new Set(n.map((f)=>f.id)),i=e.query(`SELECT ${vt} FROM crdt_changes c WHERE NOT EXISTS (
81
+ SELECT 1 FROM crdt_changes k WHERE k.dataset=c.dataset AND k.row_id=c.row_id AND k.col=c.col AND k.hlc>c.hlc
82
+ ) ORDER BY dataset,row_id,col`).all().filter((f)=>f.dataset!=="doc_blocks"||!o.has(f.row_id)||f.col==="__deleted"||f.col==="doc_id"),s=e.query("SELECT id FROM documents ORDER BY id").all(),c=s.filter(({id:f})=>e.query("SELECT 1 FROM doc_blocks WHERE doc_id=? LIMIT 1").get(f)||e.query("SELECT 1 FROM meta WHERE key=?").get(`sync_v2_managed:${f}`)).map((f)=>f.id),l=Object.fromEntries(s.map(({id:f})=>[f,At(e,f)])),u=e.query("SELECT 1 FROM sqlite_master WHERE type='table' AND name='sync_recovery_items'").get()?e.query("SELECT * FROM sync_recovery_items WHERE status='pending' ORDER BY id").all():[];return yi.parse({pendingRecovery:u,managedDocuments:c,documentVersions:l,format:"metahub-current",protocolVersion:2,workspaceId:t,epoch:r,changes:i,deletedBlocks:n})})}function Em(e,t,r){let n=yi.parse(t);if(n.workspaceId!==r)throw new T("invalid_input","checkpoint workspace mismatch");let o=new Set(n.deletedBlocks.map((s)=>s.id));if(o.size!==n.deletedBlocks.length)throw new T("invalid_input","duplicate deleted block identity");let i=new Set;for(let s of n.changes){let c=JSON.stringify([s.dataset,s.row_id,s.col]);if(i.has(c))throw new T("invalid_input","checkpoint contains multiple register winners");if(i.add(c),s.dataset==="doc_blocks"&&o.has(s.row_id)&&s.col!=="__deleted"&&s.col!=="doc_id")throw new T("invalid_input","deleted content in current checkpoint")}for(let s of o)if(!n.changes.some((c)=>c.dataset==="doc_blocks"&&c.row_id===s&&c.col==="__deleted"&&c.value==="1"))throw new T("invalid_input","deleted block has no deletion register");Ve(e,()=>{if(e.query("SELECT 1 FROM crdt_changes LIMIT 1").get())throw new T("conflict","checkpoint installation requires an empty shadow database");for(let l of n.managedDocuments)e.query("INSERT OR REPLACE INTO meta(key,value) VALUES(?,?)").run(`sync_v2_managed:${l}`,"1");for(let[l,u]of Object.entries(n.documentVersions))e.query("INSERT OR REPLACE INTO meta(key,value) VALUES(?,?)").run(`sync_v2_doc_version:${l}`,u);e.exec("CREATE TABLE IF NOT EXISTS sync_recovery_items (id TEXT PRIMARY KEY, kind TEXT NOT NULL, target TEXT NOT NULL, local TEXT NOT NULL, remote TEXT, status TEXT NOT NULL DEFAULT 'pending', result TEXT)");for(let l of n.pendingRecovery)e.query("INSERT OR IGNORE INTO sync_recovery_items(id,kind,target,local,remote,status,result) VALUES(?,?,?,?,?,?,?)").run(l.id,l.kind,l.target,l.local,l.remote,l.status,l.result);let s=[...n.changes].sort((l,u)=>Number(u.col==="__deleted")-Number(l.col==="__deleted")),c=Fr(e,s);if(e.query("INSERT INTO meta(key,value) VALUES(?,?) ON CONFLICT(key) DO UPDATE SET value=excluded.value").run("sync_v2_checkpoint",JSON.stringify({history:n.history,coveredSequence:n.coveredSequence,sourceCoverage:n.sourceCoverage})),c.poisoned||Object.values(c.skewed).some((l)=>l>0)||c.received!==s.length)throw new T("invalid_input","checkpoint could not be installed completely");for(let l of n.managedDocuments)if(!e.query("SELECT 1 FROM doc_blocks WHERE doc_id=? AND __deleted=0 LIMIT 1").get(l))e.query("UPDATE documents SET body='' WHERE id=?").run(l)}),mo(e)}var YS,yi;var Ls=Oe(()=>{on();Wn();it();yn();Ke();Ln();YS=_t({id:Be(),documentId:Be().nullable(),confirmedAt:Dt().int().nonnegative().safe().optional()}).strict(),yi=_t({format:Ut("metahub-current"),protocolVersion:Ut(2),workspaceId:Be().min(1),epoch:Dt().int().nonnegative().safe(),pendingRecovery:Gt(_t({id:Be(),kind:Be(),target:Be(),local:Be(),remote:Be().nullable(),status:Be(),result:Be().nullable()}).strict()).default([]),managedDocuments:Gt(Be()).default([]),documentVersions:Mg(Be(),Be()).default({}),history:Gt(_t({documentId:Be(),hash:Be().regex(/^[a-f0-9]{64}$/)}).strict()).default([]),coveredSequence:Dt().int().nonnegative().safe().default(0),sourceCoverage:Mg(Be(),Dt().int().nonnegative().safe()).default({}),changes:Gt(Br),deletedBlocks:Gt(YS)}).strict()});function Bt(e,t,r){let n=`${nl(t.prefix)}/v2`;if(t.encrypt&&!t.masterKey)throw new T("invalid_input","missing workspace encryption key");let o=t.encrypt?Nt(t.masterKey):null,i={async encode(X){let te=new TextEncoder().encode(JSON.stringify(X));if(te.length>$s-28)throw new T("invalid_input","v2 object exceeds bounded object size");let ce=await Ms(te);return o?pr(o,ce):ce},async decode(X){if(X.length>$s)throw new T("invalid_input","v2 object exceeds bounded object size");return JSON.parse(wn(await Fs(o?await kr(o,X):X,$s)))}};async function s(X){if(!e.getWithMetadata)throw new T("invalid_input","v2 requires bounded metadata reads");return e.getWithMetadata(X,{maxBytes:$s})}let c=(X)=>`${n}/objects/${Sm.parse(X)}`;async function l(X){let te=await s(c(X));if(!te)throw new T("busy","committed v2 object is not visible; retry without advancing coverage");if(await nr(te.bytes)!==X)throw new T("invalid_input","v2 object hash mismatch");return i.decode(te.bytes)}async function u(X){let te=await i.encode(X),ce=await nr(te);await e.put(c(ce),te);let de=await s(c(ce));if(!de||await nr(de.bytes)!==ce)throw new T("busy","v2 object durability could not be verified");return ce}let f=null,_=null;async function E(){if(r)lr(Ot(r)?.dataVersion??2);let X=await s(`${n}/root`);if(!X&&r&&(Ot(r)||at(r)))throw new T("busy","Known workspace root unavailable");if(X)f=X.serverDate,_=X.lastModified;if(!X){if(await s(`${n}/control/0000000000000001.commit`))throw new T("busy","Workspace control log exists but its root is unavailable");return null}let te=QS.parse(await i.decode(X.bytes));if(r){let ce=at(r);if(ce&&ce.workspaceId!==te.workspaceId)throw new T("rebootstrap_required","workspace identity mismatch");let de=Ot(r);if(de&&de.workspaceId!==te.workspaceId)throw new T("rebootstrap_required","workspace identity mismatch")}return te}async function g(X){if(!await e.conditionalCreateCapability?.())throw new T("invalid_input","v2 requires atomic conditional creation");let te=await E();if(te)return te;if(X.epoch!==0)throw new T("invalid_input","initial checkpoint must have epoch zero");let ce=await u(yi.parse(X)),de={protocolVersion:2,workspaceId:X.workspaceId,checkpoint:ce};try{await e.put(`${n}/root`,await i.encode(de),{ifNoneMatch:!0})}catch(ge){if(!(ge instanceof T)||ge.code!=="conflict")throw ge}let Ce=await E();if(!Ce)throw new T("busy","initialization result is not yet visible");return await A(Ce,Ce.checkpoint,0),Ce}async function A(X,te,ce){let de=yi.parse(await l(te));if(de.workspaceId!==X.workspaceId||de.epoch!==ce)throw new T("invalid_input","checkpoint identity mismatch");if(ce===0){if(te!==X.checkpoint||de.coveredSequence!==0||Object.keys(de.sourceCoverage).length)throw new T("invalid_input","initial checkpoint has invalid coverage")}else{let Ce=!1,ge=!1,Pe=!1;if(await L(X).read(void 0,async(Qe,De,Xe)=>{if(Qe.sequence===de.coveredSequence){let kt=De.state,Gr=Object.fromEntries(Object.entries(kt.members).map(([qt,Kr])=>[qt,Kr.sequence]));Ce=kt.epoch===ce-1&&!!kt.preparing&&kt.preparing.members.every((qt)=>kt.members[qt].sealed)&&Object.keys(Gr).length===Object.keys(de.sourceCoverage).length&&Object.entries(Gr).every(([qt,Kr])=>de.sourceCoverage[qt]===Kr)}if(Xe||Qe.sequence<=de.coveredSequence||ge)return;let tt=Qe.payload;if((tt.type==="commit"||tt.type==="upgrade")&&tt.checkpoint===te&&tt.epoch===ce-1)ge=Ce&&!Pe&&De.state.epoch===ce;else if(!["clock","renew"].includes(tt.type))Pe=!0}),!ge)throw new T("invalid_input","checkpoint lacks sealed source coverage proof")}return de}function L(X){return rm({client:e,prefix:n,workspaceId:X.workspaceId,codec:i,initialState:()=>({...om(),checkpoint:X.checkpoint}),parsePayload:Hg,reduce(te,ce,de){if(ce.type==="upgrade"&&ce.workspaceId!==X.workspaceId)throw new T("conflict","Workspace identity mismatch");return im(te,ce,de)},checkHead(te){if(!r)return;let ce=Ot(r);if(ce&&ce.dataVersion>te.dataVersion)throw new T("busy","Workspace data version moved backwards");if(!ce||ce.awaitingCompatibleClient)In(r,X.workspaceId,te.dataVersion)},validateProposal(te){if(te.type==="upgrade")lr(te.to);if(te.type==="prepare"&&te.targetDataVersion)lr(te.targetDataVersion)},checkAccepted(te,ce){if(ce.type==="upgrade"&&r)In(r,X.workspaceId,te.dataVersion);lr(te.dataVersion)}})}async function F(X,te){let ce=rl.parse(await l(te.objectHash));if(ce.workspaceId!==X.workspaceId||ce.epoch!==te.epoch||ce.member!==te.member||ce.first!==te.first||ce.last!==te.last)throw new T("invalid_input","committed batch identity mismatch");return ce}return{prefix:n,codec:i,root:E,initialize:g,publish:u,load:l,checkpointFor:A,log:L,batchFor:F,objectKey:c,serverTime:()=>f,rootCommittedAt:()=>_}}var Sm,tl,QS,rl,$s=67108864;var vn=Oe(()=>{er();Kt();Wn();Pr();ko();gi();Kt();rn();yn();Ls();Ke();Sm=Be().regex(/^[a-f0-9]{64}$/),tl=Dt().int().nonnegative().safe(),QS=_t({protocolVersion:Ut(2),workspaceId:Be().min(1).max(128),checkpoint:Sm}).strict(),rl=_t({protocolVersion:Ut(2),workspaceId:Be(),epoch:tl,member:Be(),first:tl.positive(),last:tl.positive(),changes:Gt(Br).min(1),bases:Gt(Be().nullable()).optional()}).strict().refine((e)=>e.last-e.first+1===e.changes.length&&(!e.bases||e.bases.length===e.changes.length),"source sequence coverage mismatch")});function wi(e){return e.query("SELECT 1 FROM sqlite_master WHERE type='table' AND name='document_history_changes'").get()?`(SELECT ${vt} FROM crdt_changes UNION SELECT ${vt} FROM document_history_changes)`:"crdt_changes"}function zs(e,t,r){let n=wi(e),o=e.query(`SELECT ${vt} FROM ${n} WHERE
83
+ (dataset='documents' AND row_id=?) OR (dataset='doc_blocks' AND row_id IN
84
+ (SELECT row_id FROM ${n} WHERE dataset='doc_blocks' AND col='doc_id' AND value=?)) ORDER BY hlc,row_id,col`).all(r,JSON.stringify(r));if(!o.length)throw new T("history_unavailable","no collected document history");let i=new Map;if(e.query("SELECT 1 FROM sqlite_master WHERE type='table' AND name='sync_history_observations'").get()){let s=e.query(`SELECT * FROM sync_history_observations WHERE
85
+ (dataset='documents' AND row_id=?) OR (dataset='doc_blocks' AND row_id IN
86
+ (SELECT row_id FROM ${n} WHERE dataset='doc_blocks' AND col='doc_id' AND value=?))`).all(r,JSON.stringify(r));for(let c of s)i.set(Mr(c),c.at)}return{format:"metahub-document-history",version:1,workspaceId:t,documentId:r,coveredFrom:null,coveredThrough:null,changes:o,observedAt:o.map((s)=>i.get(Mr(s))??null)}}function Us(e,t,r){let n=To.parse(t);if(n.workspaceId!==r)throw new T("invalid_input","history workspace mismatch");let o=new Set(n.changes.filter((i)=>i.dataset==="doc_blocks"&&i.col==="doc_id"&&i.value===JSON.stringify(n.documentId)).map((i)=>i.row_id));for(let i of n.changes)if(!(i.dataset==="documents"&&i.row_id===n.documentId)&&!(i.dataset==="doc_blocks"&&o.has(i.row_id)))throw new T("invalid_input","archive contains unrelated entity changes");Ve(e,()=>{e.exec(`CREATE TABLE IF NOT EXISTS document_history_changes (
87
+ hlc TEXT NOT NULL, node_id TEXT NOT NULL, dataset TEXT NOT NULL, row_id TEXT NOT NULL,
88
+ col TEXT NOT NULL, value TEXT, txn TEXT, PRIMARY KEY(dataset,row_id,col,hlc));
89
+ CREATE INDEX IF NOT EXISTS document_history_row ON document_history_changes(dataset,row_id,hlc)`);let i=e.query("INSERT OR IGNORE INTO document_history_changes (hlc,node_id,dataset,row_id,col,value,txn) VALUES (?,?,?,?,?,?,?)");for(let s=0;s<n.changes.length;s++){let c=n.changes[s];if(e.query(`SELECT value,node_id,txn FROM ${wi(e)} WHERE dataset=? AND row_id=? AND col=? AND hlc=?`).all(c.dataset,c.row_id,c.col,c.hlc).some((f)=>f.value!==c.value||f.node_id!==c.node_id||(f.txn??null)!==(c.txn??null)))throw new T("invalid_input","conflicting history change identity");i.run(c.hlc,c.node_id,c.dataset,c.row_id,c.col,c.value,c.txn??null);let u=n.observedAt?.[s];if(u!=null)fo(e,[c],u)}}),mo(e)}function Bs(e,t=1048576){if(!Number.isSafeInteger(t)||t<256)throw new T("invalid_input","invalid history chunk target");let r=new Map;e.changes.forEach((u,f)=>{if(u.dataset==="doc_blocks"&&u.col==="doc_id"&&u.value===JSON.stringify(e.documentId))r.set(u.row_id,f)});let n=new TextEncoder,o=[],i=new Set,s=256,c=()=>{if(!i.size)return;let u=[...i].sort((f,_)=>f-_);o.push({...e,changes:u.map((f)=>e.changes[f]),observedAt:u.map((f)=>e.observedAt?.[f]??null)}),i=new Set,s=256},l=e.changes.map((u)=>n.encode(JSON.stringify(u)).length+24);for(let u=0;u<e.changes.length;u++){let f=e.changes[u],_=f.dataset==="doc_blocks"?r.get(f.row_id):void 0;if(f.dataset==="doc_blocks"&&_===void 0)throw new T("invalid_input","history block has no ownership record");let E=[u,..._===void 0||_===u?[]:[_]].filter((g)=>!i.has(g));if(i.size&&s+E.reduce((g,A)=>g+l[A],0)>t)c(),E=[u,..._===void 0||_===u?[]:[_]];for(let g of E)i.add(g),s+=l[g]}return c(),o.length?o:[e]}var To;var js=Oe(()=>{ho();Wn();it();yn();Ln();Ke();rn();ko();To=_t({format:Ut("metahub-document-history"),version:Ut(1),workspaceId:Be().min(1),documentId:Be().min(1),coveredFrom:Be().nullable(),coveredThrough:Be().nullable(),changes:Gt(Br),observedAt:Gt(Dt().int().nonnegative().safe().nullable()).optional()}).strict().refine((e)=>!e.observedAt||e.observedAt.length===e.changes.length,"history observation count mismatch")});function ek(e,t){let r=new Map,n=[],o=new Map(e.changes.map((l,u)=>[Mr(l),e.observedAt?.[u]??null]));for(let l of e.changes){let u=o.get(Mr(l));if(u==null||u>=t){n.push(l);continue}let f=JSON.stringify([l.dataset,l.row_id,l.col]);if(!r.has(f)||r.get(f).hlc<l.hlc)r.set(f,l)}let i=new Set(n.filter((l)=>l.dataset==="doc_blocks").map((l)=>l.row_id)),s=new Set([...r.values()].filter((l)=>l.dataset==="doc_blocks"&&l.col==="__deleted"&&l.value==="1"&&!i.has(l.row_id)).map((l)=>l.row_id)),c=[...r.values(),...n].filter((l)=>l.dataset!=="doc_blocks"||!s.has(l.row_id)).sort((l,u)=>l.hlc.localeCompare(u.hlc));return{...e,changes:c,observedAt:c.map((l)=>o.get(Mr(l))??null)}}async function tk(e,t,r){let n=at(e);if(!n)throw new T("upgrade_required","retention requires v2");let o=Bt(t,r,e),i=await o.root();if(!i)throw new T("busy","v2 root unavailable");let s=o.log(i),c=await s.read(),l=o.serverTime();if(l===null||o.rootCommittedAt()===null)throw new T("clock_skew","bucket time unavailable");if(c.state.epoch!==n.epoch||c.state.checkpoint!==n.checkpoint)throw new T("rebootstrap_required","retention requires current epoch");let u=new Map,f=await o.checkpointFor(i,n.checkpoint,n.epoch),_=c.state.lastGcAt??o.rootCommittedAt();for(let de of f.deletedBlocks)u.set(de.id,de.confirmedAt??_);await s.read(void 0,async(de,Ce,ge)=>{if(ge||de.sequence<=f.coveredSequence||de.payload.type!=="batch")return;let Pe=await o.batchFor(i,de.payload);for(let Qe of Pe.changes)if(Qe.dataset==="doc_blocks"&&Qe.col==="__deleted"&&Qe.value==="1"&&!u.has(Qe.row_id))u.set(Qe.row_id,Ce.serverTime)});let E=new Set(e.query("SELECT id FROM doc_blocks WHERE __deleted=1").all().map((de)=>de.id)),g=[...u].filter(([de,Ce])=>E.has(de)&&l-Ce>=Er.syncDays*dr).map(([de])=>de).sort(),A=bi(e,n.workspaceId,n.epoch),L=new Set(g),F=Object.entries(c.state.members).filter(([,de])=>de.expiresAt>l&&!de.sealed).map(([de])=>de),X=e.query("SELECT value FROM meta WHERE key=?").get(`sync_v2_transport:${n.incarnationId}`),te=X?JSON.parse(X.value).applied:f.coveredSequence,ce=Zn(e).length?"等待对等同步变更提交到存储桶":!g.length?"没有满 30 天的删除块":te<c.sequence?"等待完整同步":c.state.lastGcAt!==null&&l-c.state.lastGcAt<Er.gcIntervalMs?"距上次回收未满 7 天":null;return{workspaceId:n.workspaceId,checkpoint:n.checkpoint,epoch:n.epoch,observedAt:l,candidates:g,blockedBy:F,deletionTimes:Object.fromEntries(u),eligible:ce===null,reason:ce,currentFields:A.changes.length,projectedFields:A.changes.filter((de)=>de.dataset!=="doc_blocks"||!L.has(de.row_id)).length}}async function km(e,t,r,n){return rk(e,t,r,n.enabled)}async function rk(e,t,r,n,o){let i=await tk(e,t,r);if(!n||o===void 0&&!i.eligible)return{status:"dry_run",report:i};let s=Bt(t,r,e),c=await s.root(),l=s.log(c);await l.append(crypto.randomUUID(),()=>({type:"clock"}));let u=await l.read();if(o!==void 0&&o!==u.state.dataVersion+1)throw new T("invalid_input","Invalid target data version");if(!u.state.preparing){let de=crypto.randomUUID();return await l.append(`prepare-${de}`,(Ce)=>({type:"prepare",epoch:Ce.epoch,id:de,targetDataVersion:o})),{status:"waiting_for_seals",report:i}}let f=u.state.preparing;if(u.serverTime-f.startedAt>=Er.prepareMs)return await l.append(`cancel-${f.id}`,(de)=>({type:"cancel",epoch:de.epoch,id:f.id})),{status:"cancelled",report:i};if(!f.members.every((de)=>u.state.members[de].sealed))return{status:"waiting_for_seals",report:i};if(f.targetDataVersion!==o)return{status:"waiting_for_seals",report:i};let _=at(e);if(_.epoch!==u.state.epoch||_.checkpoint!==u.state.checkpoint)throw new T("rebootstrap_required","retention epoch changed");if((await ol(e,s,c,l,_,{},u.sequence)).head.hash!==u.hash)throw new T("busy","sealed log prefix unavailable");let g=await s.checkpointFor(c,_.checkpoint,_.epoch);for(let de of g.history){let Ce=To.parse(await s.load(de.hash));if(Ce.documentId!==de.documentId)throw new T("invalid_input","history identity mismatch");Us(e,Ce,_.workspaceId)}let A=await l.read(u);if(A.state.preparing?.id!==f.id||A.state.epoch!==_.epoch)throw new T("busy","collection barrier changed");let{checkpoint:L,parts:F}=Ve(e,()=>{let de=e.query("SELECT value FROM meta WHERE key=?").get(`sync_v2_transport:${_.incarnationId}`),Ce=de&&JSON.parse(de.value);if(at(e)?.incarnationId!==_.incarnationId||Ce?.applied!==u.sequence)throw new T("busy","local replica does not cover the sealed log");if(Zn(e).length||Lt(e,Ce.cursor,{onlyNode:Je(e),limit:1}).changes.length)throw new T("busy","post-seal local edits must remain queued; use another complete node for collection");let ge=bi(e,_.workspaceId,_.epoch+1);ge.coveredSequence=u.sequence,ge.sourceCoverage=Object.fromEntries(Object.entries(u.state.members).map(([Qe,De])=>[Qe,De.sequence]));let Pe=[];for(let Qe of e.query("SELECT id FROM documents ORDER BY id").all()){let De=zs(e,_.workspaceId,Qe.id);De.observedAt=De.changes.map((tt,kt)=>De.observedAt?.[kt]??u.serverTime);let Xe=o?De:ek(De,u.serverTime-Er.historyDays*dr);for(let tt of Bs(Xe))Pe.push(tt)}return{checkpoint:ge,parts:Pe}});for(let de of F)L.history.push({documentId:de.documentId,hash:await s.publish(de)});let X=new Set(o?[]:i.candidates);L.changes=L.changes.filter((de)=>de.dataset!=="doc_blocks"||!X.has(de.row_id)),L.deletedBlocks=L.deletedBlocks.filter((de)=>!X.has(de.id)).map((de)=>({...de,confirmedAt:i.deletionTimes[de.id]??u.serverTime}));let te=await s.publish(L),ce=await l.append(`commit-${f.id}`,()=>o===void 0?{type:"commit",epoch:_.epoch,id:f.id,checkpoint:te}:{type:"upgrade",workspaceId:c.workspaceId,epoch:_.epoch,id:f.id,checkpoint:te,from:u.state.dataVersion,to:o});return{status:"committed",report:i,checkpoint:ce.state.checkpoint,protectedUntil:ce.state.protectedUntil}}async function xm(e,t,r,n){let o=Bt(e,t,n),i=await o.root();if(!i)return{deleted:0,candidates:0};let s=o.log(i),c=await s.read(),l=o.serverTime();if(!c.state.protectedUntil||l===null||l<c.state.protectedUntil)return{deleted:0,candidates:0};let u=await o.checkpointFor(i,c.state.checkpoint,c.state.epoch);for(let F of u.history){let X=To.parse(await o.load(F.hash));if(X.documentId!==F.documentId||X.workspaceId!==i.workspaceId)throw new T("invalid_input","retained history dependency mismatch")}let f=new Set([c.state.checkpoint,...u.history.map((F)=>F.hash)]),_=new Set;if(await s.read(void 0,async(F,X,te)=>{if(te||F.sequence>u.coveredSequence)return;if(F.payload.type==="batch"){if(await e.get(o.objectKey(F.payload.objectHash),{maxBytes:67108864})){if((await o.batchFor(i,F.payload)).changes.every((Ce)=>Ce.dataset==="doc_blocks"))_.add(F.payload.objectHash)}}if(F.payload.type==="commit"&&F.payload.checkpoint!==c.state.checkpoint)_.add(F.payload.checkpoint)}),i.checkpoint!==c.state.checkpoint)_.add(i.checkpoint);for(let F of[..._]){let X=await e.get(o.objectKey(F),{maxBytes:67108864});if(!X)continue;if(await nr(X)!==F)throw new T("invalid_input","retired object integrity check failed");let te=await o.codec.decode(X);if(te.format==="metahub-current")for(let ce of te.history??[])_.add(ce.hash)}let E=[..._].filter((F)=>!f.has(F));if(!r.enabled)return{deleted:0,candidates:E.length};let g=await s.read();if(g.state.epoch!==c.state.epoch)throw new T("busy","retention generation changed during cleanup");let A=0,L=g;for(let F of E){if(L=await s.read(L),L.state.epoch!==c.state.epoch)throw new T("busy","retention generation changed during cleanup");await e.del(o.objectKey(F)),A++}return{deleted:A,candidates:E.length}}var Rm=Oe(()=>{er();il();fi();ho();ko();vn();Ls();Kt();js();gi();Ke();Zt();it()});async function Hs(e,t,r){let n=Bt(t,r,e),o=await n.root();if(!o)return;let i=n.serverTime();if(i===null)return;let s=await n.log(o).read(),c=e.query("SELECT value FROM meta WHERE key='sync_v2_retention_report'").get();if(!s.state.preparing&&c&&i-JSON.parse(c.value).checkedAt<dr)return;let l=e.query("SELECT value FROM meta WHERE key='sync_v2_retention_review'").get(),u=!1;if(l)try{let _=JSON.parse(l.value);u=_.workspaceId===o.workspaceId&&typeof _.reviewedCheckpoint==="string"}catch{u=l.value===s.state.checkpoint}let f=await km(e,t,r,{enabled:u});if(e.query("INSERT INTO meta(key,value) VALUES('sync_v2_retention_report',?) ON CONFLICT(key) DO UPDATE SET value=excluded.value").run(JSON.stringify({checkedAt:i,result:f})),u)await xm(t,r,{enabled:!0},e)}var sl=Oe(()=>{Kt();Ke();vn();Rm();gi()});function Ao(e,t,r){let n=e.query("SELECT value FROM meta WHERE key=?").get(t);return n?JSON.parse(n.value):r}function Do(e,t,r){e.query("INSERT INTO meta(key,value) VALUES(?,?) ON CONFLICT(key) DO UPDATE SET value=excluded.value").run(t,JSON.stringify(r))}function Tm(e){if(e?.aborted)throw e.reason??Error("sync aborted")}async function ol(e,t,r,n,o,i={},s=1/0){let c=()=>Tm(i.signal),l=`sync_v2_transport:${o.incarnationId}`,u=Ao(e,"sync_v2_checkpoint",{coveredSequence:0}),f=Ao(e,l,{applied:u.coveredSequence,cursor:0,origin:0}),_=0;return{head:await n.read(void 0,async(g,A,L)=>{if(c(),g.sequence<=f.applied)return;if(A.state.epoch!==o.epoch||A.state.checkpoint!==o.checkpoint)throw new T("rebootstrap_required","checkpoint changed while downloading; preserve local edits before rebuilding");let F=g.payload,X=!L&&F.type==="batch"?await t.batchFor(r,F):null;if(c(),Ve(e,()=>{if(f=Ao(e,l,f),g.sequence<=f.applied)return;if(X){let te=Eo(e,X);if(te.poisoned||Object.values(te.skewed).some((ce)=>ce>0))throw new T("clock_skew","v2 batch cannot be completely applied");fo(e,X.changes,A.serverTime),Kg(e,X.changes),_+=te.received}f={...f,applied:g.sequence},Do(e,l,f)}),X)i.onIngest?.()},s),local:f,pulled:_}}async function al(e,t,r,n={}){let o=()=>Tm(n.signal);o();let i=t,s=async(ge)=>{o();let Pe=await rr(ge,void 0,n.signal);return o(),Pe};t={list:(...ge)=>s(()=>i.list(...ge)),get:(...ge)=>s(()=>i.get(...ge)),put:(...ge)=>s(()=>i.put(...ge)),del:(...ge)=>s(()=>i.del(...ge)),...i.getWithMetadata?{getWithMetadata:(...ge)=>s(()=>i.getWithMetadata(...ge))}:{},...i.conditionalCreateCapability?{conditionalCreateCapability:()=>s(()=>i.conditionalCreateCapability())}:{}},lr(Xr(e));let c=at(e);if(!c)throw new T("upgrade_required","workspace migration is required");let l=Bt(t,r,e),u=await l.root();if(o(),!u)throw new T("busy","workspace root is temporarily unavailable");if(u.workspaceId!==c.workspaceId)throw new T("rebootstrap_required","workspace identity mismatch");let f=l.log(u),_=await f.read(),E=l.serverTime();if(E!==null&&_.serverTime!==null&&(E-_.serverTime>=dr||_.state.preparing&&E-_.state.preparing.startedAt>=Er.prepareMs))await f.append(crypto.randomUUID(),()=>({type:"clock"})),_=await f.read();if(o(),_.state.epoch!==c.epoch||_.state.checkpoint!==c.checkpoint)throw new T("rebootstrap_required","current checkpoint must be installed before upload");let g=`sync_v2_transport:${c.incarnationId}`,A=await ol(e,l,u,f,c,n);_=A.head;let{local:L,pulled:F}=A,X=0;o();let te=_.state.members[c.incarnationId];if(!te){if(L.origin)throw new T("rebootstrap_required","device instance has been retired");let ge=Ao(e,"sync_v2_retire",null);await f.append(`join-${c.incarnationId}`,()=>({type:"join",epoch:c.epoch,member:c.incarnationId,checkpoint:c.checkpoint,...ge?{replaces:ge}:{}})),_=await f.read(),te=_.state.members[c.incarnationId]}if(_.state.preparing&&_.serverTime-_.state.preparing.startedAt>=Er.prepareMs){let ge=_.state.preparing;await f.append(`cancel-${ge.id}`,()=>({type:"cancel",epoch:c.epoch,id:ge.id})),_=await f.read(),te=_.state.members[c.incarnationId]}if(_.serverTime!==null&&te.expiresAt<=_.serverTime){if(_.state.preparing)throw new T("busy","membership registration waits for collection to commit or cancel");let ge=crypto.randomUUID();return Ve(e,()=>{Ds(e,{...c,incarnationId:ge}),Do(e,`sync_v2_transport:${ge}`,{...L,origin:0})}),al(e,t,r,n)}if(te.sealed){await Promise.resolve().then(() => sl());return await Hs(e,t,r),{pushed:X,pulled:F,pendingPush:!0,warnings:["正在更新本地副本;新编辑已在本地保存"]}}let ce=Ao(e,`${g}:outbox`,null);if(!ce){let ge=Lt(e,L.cursor,{onlyNode:Je(e),limit:n.pushLimit??1000});if(ge.changes.length)ce={requestId:crypto.randomUUID(),cursor:ge.cursor,batch:{protocolVersion:2,workspaceId:c.workspaceId,epoch:c.epoch,member:c.incarnationId,first:L.origin+1,last:L.origin+ge.changes.length,changes:ge.changes,bases:ge.changes.map((Pe)=>Ao(e,`sync_v2_base:${Pe.hlc}:${Pe.dataset}:${Pe.row_id}:${Pe.col}`,null))}},Do(e,`${g}:outbox`,ce)}if(ce){if(rl.parse(ce.batch),!ce.hash)ce.hash=await l.publish(ce.batch),o(),Do(e,`${g}:outbox`,ce);let ge=ce;await f.append(ge.requestId,()=>({type:"batch",epoch:c.epoch,member:c.incarnationId,first:ge.batch.first,last:ge.batch.last,objectHash:ge.hash})),o(),Ve(e,()=>{L={...L,cursor:ge.cursor,origin:ge.batch.last},Do(e,g,L),Do(e,`${g}:outbox`,null)}),X=ge.batch.changes.length,_=await f.read()}let de=Zn(e).length>0,Ce=de||Lt(e,L.cursor,{onlyNode:Je(e),limit:1}).changes.length>0;if(_.state.preparing&&!Ce){let ge=_.state.preparing;await f.append(`seal-${ge.id}-${c.incarnationId}`,()=>({type:"seal",epoch:c.epoch,id:ge.id,member:c.incarnationId,sequence:L.origin}))}else if(!_.state.preparing&&_.serverTime-te.renewedAt>=dr)await f.append(`renew-${c.incarnationId}-${Math.floor(_.serverTime/dr)}`,()=>({type:"renew",epoch:c.epoch,member:c.incarnationId,sequence:L.origin,checkpoint:c.checkpoint}));if(!Ce)try{await Promise.resolve().then(() => sl());await Hs(e,t,r)}catch(ge){return{pushed:X,pulled:F,pendingPush:Ce,warnings:[ge instanceof Error?ge.message:"回收预览暂不可用"]}}return{pushed:X,pulled:F,pendingPush:Ce,...de?{warnings:["对等设备的编辑已保存在本地,等待来源设备提交到云端"]}:{}}}var il=Oe(()=>{er();fi();ho();As();it();Zt();vn();Kt();Ke();gi()});async function Am(e,t,r,n,o=Date.now()){let i=`${t}\x00${r}`;if(o-(Dm.get(i)??0)>=1e5){let u={node:r,priority:n,expiresAt:o+300000};await e.put(ok(t,r),new TextEncoder().encode(JSON.stringify(u)),{contentType:"application/json"}),Dm.set(i,o)}let s=null,c=[];for(let u of await e.list(nk(t))){if(!u.key.endsWith(".lease"))continue;let f=await e.get(u.key);if(!f)continue;let _;try{_=JSON.parse(new TextDecoder().decode(f))}catch{continue}if(!_.node||_.expiresAt<=o){if(_.expiresAt<=o-300000)c.push(u.key);continue}if(!s||_.priority>s.priority||_.priority===s.priority&&_.node<s.node)s=_}let l=s?s.node===r:!0;if(l)for(let u of c)await e.del(u);return l}var nk=(e)=>`${e}/publisher/`,ok=(e,t)=>`${e}/publisher/${t}.lease`,Dm;var Om=Oe(()=>{Dm=new Map});function Pm(e){if(e.virtualHostedStyle!=null)return e.virtualHostedStyle;try{return new URL(e.endpoint).hostname.startsWith(`${e.bucket}.`)}catch{return!1}}function qm(e){cl=e}function $t(e,t){if(!cl)throw new T("network","no S3 storage client is registered for this runtime");return cl(e,t)}function Oo(e){let t=(e||"").replace(/^\/+|\/+$/g,"");return t?`${t}/spaces/default`:"spaces/default"}function nl(e){return Oo(e)}function fl(e){let t=new Uint8Array(e.byteLength);return t.set(e),t.buffer}async function Ms(e){if(Ws)return Ws.gzip(e);let t=new Response(fl(e)).body.pipeThrough(new CompressionStream("gzip"));return new Uint8Array(await new Response(t).arrayBuffer())}async function Fs(e,t=1/0){if(Ws)return Ws.gunzip(e,t);let r=new Response(fl(e)).body.pipeThrough(new DecompressionStream("gzip")).getReader(),n=[],o=0;try{for(;;){let c=await r.read();if(c.done)break;if(o+=c.value.length,o>t)throw await r.cancel(),new T("invalid_input","decompressed object exceeds limit");n.push(c.value)}}finally{r.releaseLock()}let i=new Uint8Array(o),s=0;for(let c of n)i.set(c,s),s+=c.length;return i}function fk(e){return e.map((t)=>JSON.stringify(t)).join(`
90
+ `)}async function $m(e,t){let r=await Ms(new TextEncoder().encode(fk(e)));return t?pr(t,r):r}async function Mm(e,t,r={}){let n=()=>{if(r.signal?.aborted)throw r.signal.reason??Error("sync request aborted")};n();let o=t?await rr(()=>kr(t,e),void 0,r.signal):e;n();let i=wn(await rr(()=>Fs(o),void 0,r.signal));if(n(),!i)return[];let s=[],c=0,l=0,u=performance.now();while(c<i.length){let f=i.indexOf(`
91
+ `,c),_=i.slice(c,f<0?i.length:f);if(_)s.push(JSON.parse(_));if(c=f<0?i.length:f+1,r.batchSize&&++l%r.batchSize===0&&c<i.length){if(n(),performance.now()-u>=8)await new Promise((E)=>setTimeout(E,0)),n(),u=performance.now()}}return s}function Si(e){if(!e.encrypt)return null;if(!e.masterKey)throw new T("invalid_input","encrypted bucket but master key missing — refusing to read/write plaintext");return Nt(e.masterKey)}function zm(e){if(e.maxBytes!=null&&(!Number.isSafeInteger(e.maxBytes)||e.maxBytes<0||e.maxBytes>Number.MAX_SAFE_INTEGER-28))throw RangeError("blob maxBytes must be a nonnegative safe integer");return e.maxBytes}function Ei(e){if(e.aborted)throw e.reason??Error("blob transfer aborted")}function dl(e,t){if(t!=null&&e.byteLength>t)throw new T("invalid_input","Attachment exceeds the size limit")}async function Um(e,t,r,n={}){let o=zm(n);return dl(r,o),rr(async(i)=>{let s=$t(e,{signal:i});if(n.db){await Promise.resolve().then(() => vn());let _=Bt(s,e,n.db),E=await _.root();if(E)await _.log(E).read()}let c=Fm(Oo(e.prefix),t),l=Si(e),u=l?await pr(l,r):r;Ei(i);try{return await s.put(c,u,{ifNoneMatch:!0,contentType:"application/octet-stream"}),Ei(i),!0}catch(f){if(Ei(i),pn(f)==="conflict")return!1;throw f}},void 0,n.signal)}async function hl(e,t,r={}){let n=zm(r);return rr(async(o)=>{let i=$t(e,{signal:o}),s=Si(e),c=n==null?void 0:n+(s?28:0),l=await i.get(Fm(Oo(e.prefix),t),{maxBytes:c});if(Ei(o),!l)return null;dl(l,c);let u=s?await kr(s,l):l;return Ei(o),dl(u,n),u},void 0,r.signal)}async function hk(e){let t=await crypto.subtle.digest("SHA-256",fl(new TextEncoder().encode(e)));return[...new Uint8Array(t)].map((r)=>r.toString(16).padStart(2,"0")).join("").slice(0,16)}function gk(e,t){return e.query("SELECT push_cursor FROM peers WHERE url = ?").get(t)?.push_cursor??0}function Im(e,t,r){e.query("UPDATE peers SET push_cursor = ? WHERE url = ?").run(r,t)}function gl(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 ml(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 mk(e,t){let r=gl(e,t,Lm);return new Set(r?r.split(`
92
+ `).filter(Boolean):[])}function _k(e,t,r){ml(e,t,Lm,[...r].join(`
93
+ `))}function yk(e,t=Date.now()){let r=e.query(`SELECT ${vt} FROM crdt_changes c
94
+ WHERE NOT EXISTS (
95
+ SELECT 1 FROM crdt_changes k
96
+ WHERE k.dataset = c.dataset AND k.row_id = c.row_id AND k.col = c.col AND k.hlc > c.hlc
97
+ )`).all();return Xa(r,t)}function bk(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 wk(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 vk(e,t){for(let r in t)if(!e[r]||e[r]<t[r])return!1;return!0}async function Ek(e,t){let r=await Ms(new TextEncoder().encode(JSON.stringify(e)));return t?pr(t,r):r}async function Sk(e,t){try{let r=t?await kr(t,e):e;return JSON.parse(wn(await Fs(r)))}catch{return null}}function kk(e,t){let r=new Set;for(let n of e){let o=n.key.slice(t.length),i=o.indexOf("/");if(i>0)r.add(o.slice(0,i))}return[...r]}async function xk(e,t){let r=uk(t);return kk(await e.list(r,void 0,"/"),r)}async function _l(e,t,r){if(!t.encrypt)return null;let n=Oo(t.prefix),o=pk(n),i=async(u)=>Nr(await Jc(JSON.parse(wn(u)),r)),s=await e.get(o);if(s)return i(s);let c=mi(),l=await lm(c,r);try{return await e.put(o,new TextEncoder().encode(JSON.stringify(l)),{contentType:"application/json",ifNoneMatch:!0}),Nr(c)}catch(u){if(pn(u)==="conflict"){let f=await e.get(o);if(f)return i(f)}throw u}}async function Nm(e,t,r,n=sk){let o=Date.now();_o(e,o);let i=Si(r),s=Oo(r.prefix),c=Je(e),l=(await t.list(ul(s,c))).map((L)=>L.key).filter((L)=>L.endsWith(".seg")).sort(),u=l.length?l[l.length-1]:null,f=yk(e,o);if(f.length===0)return null;let _=f.reduce((L,F)=>F.hlc>L?F.hlc:L,""),E=await hk(f.map((L)=>JSON.stringify(L)).sort().join(`
98
+ `)),g=`${vi(s)}${_}${ll}${E}.snap`;await t.put(g,await $m(f,i),{contentType:"application/octet-stream"}),await t.put(pl(g),await Ek({frontier:bk(f),ownNode:c,ownSegHigh:u},i),{contentType:"application/octet-stream"});for(let L of await t.list(vi(s))){if(!L.key.endsWith(".snap"))continue;if(L.key.slice(vi(s).length).split(ll)[0]<_)await t.del(L.key),await t.del(pl(L.key))}let A=l.slice(0,Math.max(0,l.length-n));for(let L of A)await t.del(L);return{key:g,changes:f.length}}function Bm(e){return parseInt(e.slice(0,15),10)}function Rk(e){return Date.now()-Bm(e.hlc)}function Tk(e,t){let r=vi(t),n=null;for(let o of e){let i=o.slice(r.length).split(ll)[0];if(n===null||i>n)n=i}return n}async function Vs(e,t,r,n,o={}){if(lr(Xr(e)),!r.getWithMetadata&&Ot(e))throw new T("busy","Cannot verify known workspace version");if(at(e)){let ge=`sync_v2_rebuild_required:${t}`;try{let Pe=await al(e,r,n,o);if(Ko(e,t),!o.signal?.aborted)e.query("DELETE FROM meta WHERE key=?").run(ge);return Pe}catch(Pe){if(!o.signal?.aborted&&pn(Pe)==="rebootstrap_required")e.query("INSERT OR REPLACE INTO meta(key,value) VALUES(?, '1')").run(ge);throw Pe}}if(r.getWithMetadata){await Promise.resolve().then(() => vn());let Pe=Bt(r,n,e),Qe=await Pe.root();if(Qe)await Pe.log(Qe).read();if(Qe)throw new T("upgrade_required","此工作区已升级同步格式;请先保全本地编辑并升级本地副本")}let i=()=>{if(o.signal?.aborted)throw o.signal.reason??Error("sync request aborted")};i();for(let ge of[o.pushLimit,o.ingestBatchSize,o.pullObjectLimit])if(ge!=null&&(!Number.isSafeInteger(ge)||ge<=0))throw RangeError("storage batch sizes must be positive integers");let s=r;r={list:async(...ge)=>{i();let Pe=await rr(()=>s.list(...ge),void 0,o.signal);return i(),Pe},get:async(...ge)=>{i();let Pe=await rr(()=>s.get(...ge),void 0,o.signal);return i(),Pe},put:async(...ge)=>{i(),await rr(()=>s.put(...ge),void 0,o.signal),i()},del:async(...ge)=>{i(),await rr(()=>s.del(...ge),void 0,o.signal),i()}};let c=(ge)=>Mm(ge,Si(n),{batchSize:o.ingestBatchSize,signal:o.signal}),l=async(ge)=>{let Pe=0,Qe=o.ingestBatchSize??Math.max(1,ge.length);for(let De=0;De<ge.length;De+=Qe)if(i(),Pe+=jm(ce,Fr(e,ge.slice(De,De+Qe))),o.onIngest?.(),De+Qe<ge.length)await new Promise((Xe)=>setTimeout(Xe,0));return i(),Pe};_o(e);let u=Je(e),f=Si(n),_=Oo(n.prefix),E=gk(e,t),g=Lt(e,E,{onlyNode:u,limit:o.pushLimit}),A=0,L=!1;if(g.changes.length===0)Im(e,t,g.cursor);else{let ge=o.minPushChanges??1,Pe=o.maxPushAgeMs??0;if(o.forcePush||g.changes.length>=ge||Rk(g.changes[0])>=Pe){let De=dk(_,u,g.cursor);await r.put(Cm(_,u),new TextEncoder().encode(De),{contentType:"text/plain"}),await r.put(De,await $m(g.changes,f),{contentType:"application/octet-stream"}),Im(e,t,g.cursor),A=g.changes.length,L=Lt(e,g.cursor,{onlyNode:u,limit:1}).changes.length>0}else L=!0}let F=[],X=0,te={remaining:o.pullObjectLimit??1/0,pending:!1},ce={};if(o.pull??!0){F=(await r.list(vi(_))).map((ge)=>ge.key).filter((ge)=>ge.endsWith(".snap")),X+=await Dk(e,t,F,r,f,ce,l,c,te);for(let ge of await xk(r,_)){if(ge===u)continue;let Pe=gl(e,t,ge),Qe=await r.get(Cm(_,ge));if(Qe){let Xe=wn(Qe);if(Pe&&Xe<=Pe)continue}let De=(await r.list(ul(_,ge),Pe??void 0)).filter((Xe)=>Xe.key.endsWith(".seg"));for(let Xe of De){if(te.remaining<=0){te.pending=!0;break}te.remaining--;let tt=await r.get(Xe.key);if(!tt)throw new T("network","Storage segment disappeared during synchronization");let kt=await c(tt);X+=await l(kt),ml(e,t,ge,Xe.key)}}}let de=!1;if(o.publish){let ge=e.query("SELECT COUNT(*) AS n FROM crdt_changes").get().n;if(ge>0){let Pe=Tk(F,_),Qe=o.snapshotMinDelta??ak,De=o.snapshotDeltaRatio??ck,Xe=o.snapshotMaxIntervalMs??lk,tt=Pe===null?ge:e.query("SELECT COUNT(*) AS n FROM crdt_changes WHERE hlc > ?").get(Pe).n;if((Pe===null||tt>=Math.max(Qe,ge*De)||tt>0&&Date.now()-Bm(Pe)>=Xe)&&await Am(r,_,u,o.priority??0))await Nm(e,r,n,o.snapshotRetainSegments),de=!0}}if(o.publish&&!de&&A>0){let ge=o.snapshotEverySegments??200;if((await r.list(ul(_,u))).filter((Qe)=>Qe.key.endsWith(".seg")).length>=ge)await Nm(e,r,n,o.snapshotRetainSegments)}Ko(e,t);let Ce=Gc(t,ce);return{pushed:A,pulled:X,pendingPush:L,pendingPull:te.pending,...Ce.length?{warnings:Ce}:{}}}function jm(e,t){for(let[r,n]of Object.entries(t.skewed))e[r]=(e[r]??0)+n;return t.received}async function Dk(e,t,r,n,o,i={},s,c,l={remaining:1/0,pending:!1}){if(r.length===0)return 0;let u=mk(e,t),f=wk(e),_=0;for(let g of[...r].sort().reverse()){if(u.has(g))continue;if(l.remaining<=0){l.pending=!0;break}l.remaining--;let A=await n.get(pl(g)),L=A?await Sk(A,o):null;if(L&&vk(f,L.frontier)){u.add(g);continue}let F=await n.get(g);if(!F)throw new T("network","Storage snapshot disappeared during synchronization");let X=c?await c(F):await Mm(F,o);_+=s?await s(X):jm(i,Fr(e,X)),u.add(g);for(let te of X)if(!f[te.node_id]||te.hlc>f[te.node_id])f[te.node_id]=te.hlc;if(L?.ownSegHigh){let te=gl(e,t,L.ownNode);if(!te||te<L.ownSegHigh)ml(e,t,L.ownNode,L.ownSegHigh)}}let E=new Set(r);return _k(e,t,[...u].filter((g)=>E.has(g))),_}var cl=null,Lm="__snapshot__",ik=16,ll="~",sk=40,ak=200,ck=0.5,lk=1800000,uk=(e)=>`${e}/oplog/`,ul=(e,t)=>`${e}/oplog/${t}/`,Cm=(e,t)=>`${e}/oplog/${t}/HEAD`,dk=(e,t,r)=>`${e}/oplog/${t}/${String(r).padStart(ik,"0")}.seg`,vi=(e)=>`${e}/snapshot/`,pk=(e)=>`${e}/keys/main.json`,Ws=null,Fm=(e,t)=>`${e}/blobs/${t}`,pl=(e)=>`${e}.vc`;var Pr=Oe(()=>{er();il();Kt();Zt();it();Om();Ke();Cs();rn()});var Ak=32,Ok=3,GI;var Hm=Oe(()=>{Ke();GI=(Ak+Ok)*8/5});var Wm=Oe(()=>{Ke()});function Ck(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 Ik(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 Vm(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=Ck(e),o=n.filter((i)=>i.peerUrl!==t||i.requiredSeq>r.push_cursor);return Ik(e,o),n.length-o.length}var Gm;var Zm=Oe(()=>{Gm={name:"@tensorix/metahub",version:"0.6.0",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 Km(e,t,r,n){if(!Array.isArray(e))return e;let o=(s)=>!!s&&typeof s==="object"&&!Array.isArray(s),i=(s)=>typeof s==="string"?t.get(s)??s:s;return e.map((s)=>{if(!o(s))return s;let c={...s};for(let l of["group","dateProp","start","end"])if(l in c)c[l]=i(c[l]);if(Array.isArray(s.hidden))c.hidden=s.hidden.map(i);if(Array.isArray(s.sort))c.sort=s.sort.map((l)=>o(l)?{...l,prop:i(l.prop)}:l);if(o(s.filter)&&Array.isArray(s.filter.rules))c.filter={...s.filter,rules:s.filter.rules.map((l)=>{if(!o(l))return l;return{...l,prop:i(l.prop),...typeof l.prop==="string"&&n.has(l.prop)&&Array.isArray(l.value)?{value:l.value.map((u)=>typeof u==="string"?r.get(u)??u:u)}:{}}})};if(o(s.calc))c.calc=Object.fromEntries(Object.entries(s.calc).map(([l,u])=>[t.get(l)??l,u]));return c})}function Jm(e){return e.replace(/[^a-zA-Z0-9_]/g,"_")}function Xm(e){return e.replace(/'/g,"''")}function Ym(e,t){return`idx_rec_${Jm(e)}_${Jm(t)}`}function Pk(e,t,r){return e.query("SELECT 1 AS ok FROM sqlite_master WHERE type = 'index' AND name = ?").get(Ym(t,r))!=null}function yl(e,t,r){let n=Ym(t,r);e.exec(`CREATE INDEX IF NOT EXISTS "${n}" ON records (data ->> '${Xm(r)}', created_hlc) WHERE database_id = '${Xm(t)}' AND __deleted = 0`)}function bl(e,t,r){if(Pk(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}yl(e,t,r.id)}function wl(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 T("invalid_input",`${e} requires config.options: string[]`)}if(e==="relation"){if(typeof t?.database!=="string")throw new T("invalid_input","relation requires config.database (target database id)")}}function Lk(e,t){return(e.query("SELECT MAX(position) AS m FROM properties WHERE database_id = ? AND __deleted = 0").get(t).m??0)+1}function xr(e,t){let r=e.query(`SELECT ${Qm} FROM properties WHERE id = ? AND __deleted = 0`).get(t);if(!r)return null;return{...r,config:r.config?JSON.parse(r.config):null}}function Mt(e,t){return e.query(`SELECT ${Qm} FROM properties WHERE database_id = ? AND __deleted = 0 ORDER BY position, id`).all(t).map((n)=>({...n,config:n.config?JSON.parse(n.config):null}))}function e_(e,t,r){let n=xr(e,t);if(!n)throw new T("not_found",`no such property: ${t}`);if(!Number.isFinite(r))throw new T("invalid_input","width must be a finite number");let o=Math.max(80,Math.min(2000,Math.round(r)));return vl(e,t,{config:{...n.config??{},width:o}})}function El(e,t){let r=xr(e,t);if(!r)throw new T("not_found",`no such property: ${t}`);if(r.type!=="select"&&r.type!=="multi_select")throw new T("invalid_input",`${r.type} property has no options`);return{prop:r,options:r.config?.options??[]}}var Zs,qk,Qm,Gs,vl,t_,r_,n_,o_,i_;var sn=Oe(()=>{Vt();it();Jn();Ke();Zs=new Set(["text","number","checkbox","select","multi_select","date","relation","doc","url"]),qk=["id","database_id","name","type","config","position"],Qm=qk.join(", ");Gs=We(function(t,r,n){if(!or(t,r))throw new T("not_found",`no such database: ${r}`);if(!Zs.has(n.type))throw new T("invalid_input",`unknown property type: ${n.type}`);wl(n.type,n.config);let o=n.indexed?{...n.config??{},indexed:!0}:n.config??null,i=ur("prop",n.name);if(_e(t,"properties",i,"database_id",r),_e(t,"properties",i,"name",n.name),_e(t,"properties",i,"type",n.type),_e(t,"properties",i,"config",o),_e(t,"properties",i,"position",n.position??Lk(t,r)),n.type==="relation"||n.type==="doc"||n.indexed===!0)yl(t,r,i);return xr(t,i)});vl=We(function(t,r,n){let o=xr(t,r);if(!o)throw new T("not_found",`no such property: ${r}`);let i=n.type!==void 0&&n.type!==o.type;if(n.type!==void 0&&!Zs.has(n.type))throw new T("invalid_input",`unknown property type: ${n.type}`);let s=n.type??o.type,c;if(n.config!==void 0){let l={...o.config??{}};for(let[u,f]of Object.entries(n.config))if(f===null)delete l[u];else l[u]=f;c=l,wl(s,c)}else if(i)wl(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(i){let l=t.query("SELECT id FROM records WHERE database_id = ? AND __deleted = 0 AND data ->> ? IS NOT NULL").all(o.database_id,r);for(let u of l)_e(t,"records",u.id,r,null)}return xr(t,r)});t_=We(function(t,r,n,o){let{prop:i,options:s}=El(t,r);if(o=o.trim(),!o)throw new T("invalid_input","option name must not be empty");if(!s.includes(n))throw new T("not_found",`no such option: ${n}`);if(o===n)return{property:i,renamed:0};if(s.includes(o))throw new T("conflict",`option already exists: ${o}`);_e(t,"properties",r,"config",{...i.config??{},options:s.map((l)=>l===n?o:l)});let c=0;if(i.type==="select"){let l=t.query("SELECT id FROM records WHERE database_id = ? AND __deleted = 0 AND data ->> ? = ?").all(i.database_id,r,n);for(let u of l)_e(t,"records",u.id,r,o);c=l.length}else{let l=t.query("SELECT id, data ->> ? AS v FROM records WHERE database_id = ? AND __deleted = 0 AND data ->> ? IS NOT NULL").all(r,i.database_id,r);for(let u of l){let f=JSON.parse(u.v);if(!Array.isArray(f)||!f.includes(n))continue;_e(t,"records",u.id,r,[...new Set(f.map((_)=>_===n?o:_))]),c++}}return{property:xr(t,r),renamed:c}}),r_=We(function(t,r,n){let{prop:o,options:i}=El(t,r);if(!i.includes(n))throw new T("not_found",`no such option: ${n}`);if(i.length===1)throw new T("invalid_input","cannot remove the last option; delete the property instead");_e(t,"properties",r,"config",{...o.config??{},options:i.filter((c)=>c!==n)});let s=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 l of c)_e(t,"records",l.id,r,null);s=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 l of c){let u=JSON.parse(l.v);if(!Array.isArray(u)||!u.includes(n))continue;_e(t,"records",l.id,r,u.filter((f)=>f!==n)),s++}}return{property:xr(t,r),cleared:s}}),n_=We(function(t,r){let n=xr(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 i of o)_e(t,"records",i.id,r,void 0);return!0}),o_=We(function(t,r,n,o){if(o!=="before"&&o!=="after")throw new T("invalid_input","unknown move position");let i=xr(t,r),s=xr(t,n);if(!i)throw new T("not_found",`no such property: ${r}`);if(!s)throw new T("not_found",`no such property: ${n}`);if(i.database_id!==s.database_id)throw new T("invalid_input","cannot move a property across databases");if(r===n)return i;let c=Mt(t,i.database_id).filter((f)=>f.id!==r),l=()=>{let f=c.findIndex((L)=>L.id===n);if(f<0)throw new T("not_found",`no such property: ${n}`);let _=o==="before"?f:f+1,E=c[_-1]?.position,g=c[_]?.position,A=E===void 0?g-1:g===void 0?E+1:E/2+g/2;return Number.isFinite(A)&&(E===void 0||A>E)&&(g===void 0||A<g)?A:null},u=c.every((f)=>Number.isFinite(f.position))?l():null;if(u===null){for(let f=0;f<c.length;f++)_e(t,"properties",c[f].id,"position",f+1);c=Mt(t,i.database_id).filter((f)=>f.id!==r),u=l()}if(u===null)throw new T("invalid_input","could not allocate a finite property position");if(u!==i.position)_e(t,"properties",r,"position",u);return xr(t,r)}),i_=We(function(t,r,n,o,i){if(i!=="before"&&i!=="after")throw new T("invalid_input","unknown move position");let{prop:s,options:c}=El(t,r);if(!c.includes(n))throw new T("not_found",`no such option: ${n}`);if(!c.includes(o))throw new T("not_found",`no such option: ${o}`);if(n===o)return s;let l=[...c];l.splice(l.indexOf(n),1);let u=l.indexOf(o)+(i==="after"?1:0);if(l.splice(u,0,n),l.some((f,_)=>f!==c[_]))_e(t,"properties",r,"config",{...s.config,options:l});return xr(t,r)})});function Fk(e){return e!==null&&e!=="blk"}function Sl(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 zk(e,t,r,n){let o=a_[t],i=o.nameCol;if(t==="rec"&&n){let E=Sl(e,n);if(E)i=`data ->> '${E.replace(/'/g,"''")}'`}let s=i??"''",c=[],l=[];c.push("(id >= ? AND id < ?)"),l.push(r,r+s_);let u=`${t}_${r}`;if(c.push("(id >= ? AND id < ?)"),l.push(u,u+s_),i)c.push(`lower(${i}) = lower(?)`),l.push(r);let f=`SELECT id, ${s} AS label FROM ${o.table} WHERE __deleted = 0 AND (${c.join(" OR ")})`;if(o.scoped&&n)f+=" AND database_id = ?",l.push(n);return e.query(f).all(...l).map((E)=>({kind:t,id:E.id,label:E.label??""}))}function Ks(e,t,r={}){let n=r.kind?[r.kind]:Fk(go(t))?[go(t)]:Mk,o=[],i=new Set;for(let s of n)for(let c of zk(e,s,t,r.databaseId)){if(i.has(c.id))continue;i.add(c.id),o.push(c)}return o}function c_(e,t,r={}){let n=t.trim();if(!n)return[];let o=Math.max(1,Math.min(r.limit??Uk,100)),i=Ks(e,n).filter((l)=>l.kind!=="prop");i.sort((l,u)=>Number(u.id===n)-Number(l.id===n));let s=new Map,c=[];for(let l of i.slice(0,o)){if(l.kind==="db"){c.push({...l,database_id:null});continue}let f=e.query(`SELECT database_id FROM ${a_[l.kind].table} WHERE id = ?`).get(l.id)?.database_id??null,_=l.label;if(l.kind==="rec"&&!_&&f){if(!s.has(f))s.set(f,Sl(e,f));let E=s.get(f);if(E){let g=e.query(`SELECT data ->> '${E.replace(/'/g,"''")}' AS title FROM records WHERE id = ?`).get(l.id);_=g?.title?String(g.title):""}}c.push({kind:l.kind,id:l.id,label:_,database_id:f})}return c}var a_,Mk,s_="{",Uk=20;var Js=Oe(()=>{Vt();Ke();a_={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"}},Mk=["db","prop","rec","doc"]});function l_(e){return typeof e==="string"||typeof e==="number"||typeof e==="boolean"}function Bk(e){return typeof e==="boolean"?e?1:0:e}function jk(e,t,r){let n=t.config?.database;if(!n)return r;let o=Ks(e,r,{kind:"rec",databaseId:n}),i=o.find((s)=>s.id===r);if(i)return i.id;if(o.length===1)return o[0].id;if(o.length===0){if(go(r)==="rec")return r;throw new T("not_found",`${t.name}: no such record in target database: ${r}`)}throw new T("ambiguous",`${t.name}: ambiguous relation "${r}" (${o.length} matches); use a full id`)}function Hk(e,t,r){let n=Ks(e,r,{kind:"doc"}),o=n.find((i)=>i.id===r);if(o)return o.id;if(n.length===1)return n[0].id;if(n.length===0){if(go(r)==="doc")return r;throw new T("not_found",`${t.name}: no such document: ${r}`)}throw new T("ambiguous",`${t.name}: ambiguous document "${r}" (${n.length} matches); use a full id`)}function xl(e,t,r){switch(t.type){case"text":case"url":case"date":{if(r===null)return null;if(typeof r!=="string")throw new T("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 T("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 T("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 T("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 i of n)if(!o.includes(String(i)))throw new T("invalid_input",`${t.name}: '${i}' is not an allowed option`);return n.map(String)}case"relation":return(r===null?[]:Array.isArray(r)?r:[r]).map((o)=>jk(e,t,String(o)));case"doc":return(r===null?[]:Array.isArray(r)?r:[r]).map((o)=>Hk(e,t,String(o)))}}function Wk(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 Rl(e,t){let r=new Map(e.map((i)=>[i.id,i])),n=Wk(e),o=[];for(let[i,s]of Object.entries(t)){let c=r.get(i);if(!c){let l=n.get(i.toLowerCase())??[];if(l.length>1)throw new T("ambiguous",`property name "${i}" matches ${l.length} properties; use a property id`);c=l[0]}if(!c)throw new T("not_found",`unknown property: ${i}`);o.push({prop:c,value:s})}return o}function p_(e,t,r){return Rl(Mt(e,t),r).map(({prop:n,value:o})=>({prop:n,value:xl(e,n,o)}))}function f_(e,t){let r=JSON.parse(e.data||"{}"),n=new Map(t.map((s)=>[s.id,s])),o={},i={};for(let[s,c]of Object.entries(r)){let l=n.get(s);if(!l)continue;o[l.name]=c,i[l.id]=c}return{id:e.id,database_id:e.database_id,values:o,cells:i}}function Vk(e,t){let r=e.find((n)=>n.prop.type==="text"&&typeof n.value==="string"&&n.value);return ur("rec",r?String(r.value):"",t)}function u_(e,t){return e.query("SELECT 1 AS ok FROM sqlite_master WHERE type = 'table' AND name = ?").get(t)!=null}function Zk(e){return u_(e,"meta")&&u_(e,"crdt_changes")}function Gk(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 h_(e,t){return e.query(`SELECT order_key FROM records
99
+ WHERE database_id = ? AND __deleted = 0 AND order_key IS NOT NULL
100
+ ORDER BY order_key DESC, id DESC LIMIT 1`).get(t)?.order_key??null}function kl(e,t){return e.query(`SELECT id, database_id, created_hlc, order_key FROM records
101
+ WHERE database_id = ? AND __deleted = 0
102
+ ORDER BY order_key IS NULL, order_key, created_hlc, id`).all(t)}function Kk(e,t){let r=kl(e,t),n=nn(null,null,r.length);r.forEach((o,i)=>{if(o.order_key!==n[i])_e(e,"records",o.id,"order_key",n[i])})}function En(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 f_(r,Mt(e,r.database_id))}function d_(e){return e.replace(/'/g,"''")}function Co(e,t,r={}){let n=Mt(e,t),o=r.filter&&Object.keys(r.filter).length?Rl(n,r.filter).map(({prop:F,value:X})=>({prop:F,value:xl(e,F,X)})):[],i=o.filter((F)=>l_(F.value)),s=o.filter((F)=>!l_(F.value)),c,l=!1;if(r.sort){let F=r.sort;if(F.startsWith("-"))l=!0,F=F.slice(1);if(F!=="created"&&F!=="created_hlc"){let X=n.find((te)=>te.id===F);if(!X){let te=n.filter((ce)=>ce.name.toLowerCase()===F.toLowerCase());if(te.length>1)throw new T("ambiguous",`sort field "${F}" matches ${te.length} properties; use a property id`);X=te[0]}if(!X)throw new T("not_found",`unknown sort field: ${F}`);c=X}}for(let F of i)bl(e,t,F.prop);if(c)bl(e,t,c);let u=["database_id = ?","__deleted = 0"],f=[t];for(let F of i)u.push(`data ->> '${d_(F.prop.id)}' = ?`),f.push(Bk(F.value));let _=r.sort==null,E=c?`data ->> '${d_(c.id)}'`:"created_hlc",g=`SELECT id, database_id, data FROM records WHERE ${u.join(" AND ")} `+(_?"ORDER BY order_key IS NULL, order_key, id":`ORDER BY ${E} ${l?"DESC":"ASC"}, id`);if(r.limit!=null&&s.length===0)g+=" LIMIT ?",f.push(r.limit);let L=e.query(g).all(...f).map((F)=>f_(F,n));if(s.length){if(L=L.filter((F)=>s.every((X)=>JSON.stringify(F.cells[X.prop.id]??null)===JSON.stringify(X.value))),r.limit!=null)L=L.slice(0,r.limit)}return L}var Xs,Tl,Ys,g_,Dl,Qs,m_;var Xn=Oe(()=>{Vt();it();Jn();sn();Js();Ke();Xs=We(function(t,r){let n=Zk(t),o=r?[{database_id:r}]:t.query(`SELECT DISTINCT database_id FROM records
103
+ WHERE database_id IS NOT NULL AND __deleted = 0 AND order_key IS NULL`).all();for(let i of o){let s=t.query(`SELECT id FROM records
104
+ WHERE database_id = ? AND __deleted = 0 AND order_key IS NULL
105
+ ORDER BY created_hlc, id`).all(i.database_id);if(!s.length)continue;let c=h_(t,i.database_id),l=nn(c,null,s.length);s.forEach((u,f)=>Gk(t,u.id,l[f],n))}}),Tl=We(function(t,r,n){let o=Vk(n,Ha(r.name,"rec")),i=_r(h_(t,r.id),null),s=_e(t,"records",o,"database_id",r.id);_e(t,"records",o,"created_hlc",s.hlc),_e(t,"records",o,"order_key",i);for(let{prop:c,value:l}of n)_e(t,"records",o,c.id,l);return En(t,o)}),Ys=We(function(t,r,n){let o=or(t,r);if(!o)throw new T("not_found",`no such database: ${r}`);return Tl(t,o,p_(t,o.id,n))});g_=We(function(t,r,n,o){if(o!=="before"&&o!=="after")throw new T("invalid_input",`unknown move position: ${o}`);let i=t.query("SELECT id, database_id FROM records WHERE id = ? AND __deleted = 0").get(r);if(!i)throw new T("not_found",`no such record: ${r}`);let s=t.query("SELECT id, database_id FROM records WHERE id = ? AND __deleted = 0").get(n);if(!s)throw new T("not_found",`no such record: ${n}`);if(i.database_id!==s.database_id)throw new T("invalid_input","cannot move a record across databases");if(r===n)return En(t,r);Xs(t,i.database_id);let c=kl(t,i.database_id).filter((_)=>_.id!==r),l=c.findIndex((_)=>_.id===n);if(l<0)throw new T("not_found",`no such target record: ${n}`);let u=o==="before"?c[l-1]?.order_key??null:c[l].order_key,f=o==="before"?c[l].order_key:c[l+1]?.order_key??null;if(u!==null&&f!==null&&u>=f)Kk(t,i.database_id),c=kl(t,i.database_id).filter((_)=>_.id!==r),l=c.findIndex((_)=>_.id===n),u=o==="before"?c[l-1]?.order_key??null:c[l].order_key,f=o==="before"?c[l].order_key:c[l+1]?.order_key??null;return _e(t,"records",r,"order_key",_r(u,f)),En(t,r)}),Dl=We(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 T("not_found",`no such record: ${r}`);let i=JSON.parse(o.data||"{}");for(let{prop:s,value:c}of n){let l=Object.hasOwn(i,s.id);if(!(c===void 0?!l:l&&JSON.stringify(c)===JSON.stringify(i[s.id])))_e(t,"records",r,s.id,c)}return En(t,r)}),Qs=We(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 T("not_found",`no such record: ${r}`);return Dl(t,r,p_(t,o.database_id,n))}),m_=We(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 b_(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 w_(e,t,r,n){for(let[o,i]of Object.entries(n)){if(o.includes("."))throw new T("invalid_input",`meta key must not contain ".": ${o}`);let s=i===void 0?null:i,c=r&&o in r?r[o]:null;if(JSON.stringify(c??null)===JSON.stringify(s??null))continue;_e(e,"databases",t,`meta.${o}`,s===null?void 0:s)}}function or(e,t){return b_(e.query(`SELECT ${y_} FROM databases WHERE id = ? AND __deleted = 0`).get(t))}function S_(e){return e.query(`SELECT ${y_} FROM databases WHERE __deleted = 0 ORDER BY created_hlc`).all().map((r)=>b_(r))}function __(e,t,r,n){return e.query(`SELECT id FROM ${t} WHERE ${r} = ? AND __deleted = 0`).all(n).map((o)=>o.id)}var Xk,y_,Al,v_,E_,k_;var Jn=Oe(()=>{Vt();it();Ke();sn();Xn();Xk=["id","name","icon","meta","created_hlc"],y_=Xk.join(", ");Al=We(function(t,r){let n=ur("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 or(t,n)}),v_=We(function(t,r,n){if(!or(t,r))throw new T("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 T("invalid_input","meta must be a JSON object or null");let o=or(t,r).meta,i=n.meta??Object.fromEntries(Object.keys(o??{}).map((s)=>[s,null]));w_(t,r,o,i)}return or(t,r)}),E_=We(function(t,r,n={}){let o=or(t,r);if(!o)throw new T("not_found",`no such database: ${r}`);let i=Al(t,{name:n.name??o.name,icon:n.icon??o.icon??void 0}),s=new Map,c=new Set;for(let f of Mt(t,r)){let _=f.type==="relation"&&f.config?.database===r,E=_?{...f.config,database:i.id}:f.config??void 0,g=Gs(t,i.id,{name:f.name,type:f.type,config:E,position:f.position});if(s.set(f.id,g.id),_)c.add(g.id)}let l=Co(t,r),u=new Map;for(let f of l){let _={};for(let[E,g]of Object.entries(f.cells)){let A=s.get(E);if(!A)continue;if(c.has(A)&&Array.isArray(g)&&g.length>0)continue;_[A]=g}u.set(f.id,Ys(t,i.id,_).id)}for(let f of l){let _={};for(let[E,g]of Object.entries(f.cells)){let A=s.get(E);if(A&&c.has(A)&&Array.isArray(g)&&g.length>0)_[A]=g.map((L)=>u.get(String(L))??L)}if(Object.keys(_).length)Qs(t,u.get(f.id),_)}if(o.meta!==null){let{collapsed:f,..._}=o.meta;if("views"in _)_.views=Km(_.views,s,u,new Set(Mt(t,r).filter((E)=>E.type==="relation"&&E.config?.database===r).map((E)=>E.id)));w_(t,i.id,null,_)}return or(t,i.id)});k_=We(function(t,r){if(!or(t,r))return!1;_e(t,"databases",r,"__deleted",1);let n=(o)=>{for(let i of __(t,o,"database_id",r))_e(t,o,i,"__deleted",1)};n("properties"),n("records");for(let o of __(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 Ol(){return{v:1,tables:[]}}function ex(e){return typeof e==="string"&&Cl.includes(e)}function x_(e){let t=new Map;for(let n of e){let o=t.get(n.db)??new Set;for(let i of n.ops)o.add(i);t.set(n.db,o)}let r=[];for(let[n,o]of t){let i=Cl.filter((s)=>o.has(s));if(i.length)r.push({db:n,ops:i})}return r.sort((n,o)=>n.db<o.db?-1:n.db>o.db?1:0),{v:1,tables:r}}function an(e){if(!e)return Ol();let t;try{t=JSON.parse(e)}catch{return Ol()}try{return ki(t)}catch{return Ol()}}function ki(e){if(typeof e!=="object"||e===null||Array.isArray(e))throw new T("invalid_input","grants must be an object {v:1, tables:[...]}");let t=e;if(t.v!==1)throw new T("invalid_input","grants version must be 1");if(!Array.isArray(t.tables))throw new T("invalid_input","grants.tables must be an array");let r=[];for(let n of t.tables){if(typeof n!=="object"||n===null)throw new T("invalid_input","each grant table must be an object {db, ops}");let{db:o,ops:i}=n;if(typeof o!=="string"||!o)throw new T("invalid_input","grant table `db` must be a database id");if(!Array.isArray(i)||!i.every(ex))throw new T("invalid_input",`grant ops must be a subset of ${Cl.join("|")} (delete is never grantable)`);r.push({db:o,ops:i})}return x_(r)}function ea(e){return JSON.stringify(x_(e.tables))}function R_(e){return e.tables.some((t)=>t.ops.some((r)=>r!=="read"))}var Cl;var Yn=Oe(()=>{Ke();Jn();sn();Xn();it();Cl=["read","create","update"]});function Il(e,t){let r=t.permission??"view";if(!tx.has(t.kind))throw new T("invalid_input",`unknown share kind: ${t.kind}`);if(r!=="view"&&r!=="edit")throw new T("invalid_input",`unknown share permission: ${r}`);let n=t.requestId?.trim()||null;if(n&&!/^[A-Za-z0-9_-]{16,80}$/.test(n))throw new T("invalid_input","share request id is invalid");if(n){let l=D_(e,n);if(l){if(l.kind!==t.kind||l.target_id!==t.target_id)throw new T("conflict","share request id was already used for another target");return l}}let o=null;if(t.grants!=null){let l;try{l=JSON.parse(t.grants)}catch{throw new T("invalid_input","grants must be a JSON GrantSet")}o=ea(ki(l))}let i=Wt(12);while(Hr(e,i))i=Wt(12);let c=r==="edit"||R_(an(o))?"g"+Wt(8):null;return e.query(`INSERT INTO shares (${xi}) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(i,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),Hr(e,i)}function D_(e,t){return e.query(`SELECT ${xi} FROM shares WHERE request_id = ?`).get(t)??null}function Hr(e,t){return e.query(`SELECT ${xi} FROM shares WHERE slug = ?`).get(t)??null}function Nl(e){return e.query(`SELECT ${xi} FROM shares ORDER BY created_at DESC`).all()}function Pl(e,t){return e.query(`SELECT ${xi} FROM shares WHERE target_id = ? ORDER BY created_at DESC`).all(t)}function qr(e,t){return e.query("DELETE FROM shares WHERE slug = ?").run(t).changes>0}function T_(e){let t=new Uint8Array(e.byteLength);return t.set(e),t.buffer}async function ix(e,t){let r=await crypto.subtle.importKey("raw",T_(new TextEncoder().encode(e)),"PBKDF2",!1,["deriveBits"]),n=await crypto.subtle.deriveBits({name:"PBKDF2",salt:T_(t),iterations:rx,hash:"SHA-256"},r,ox);return new Uint8Array(n)}async function ql(e){let t=crypto.getRandomValues(new Uint8Array(nx)),r=await ix(e,t);return{salt:Nr(t),hash:Nr(r)}}var tx,xi="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",rx=600000,nx=16,ox=256;var Io=Oe(()=>{Ke();Vt();rn();Yn();tx=new Set(["doc","database","site"])});function Ll(e){let t=sx;for(let r=0;r<e.length;r++)t^=BigInt(e.charCodeAt(r)),t=t*ax&cx;return t.toString(16).padStart(16,"0")}var sx=0xcbf29ce484222325n,ax=0x100000001b3n,cx=0xffffffffffffffffn;function $l(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 C_(e,t){let r=$l(t);return e.query(`SELECT dataset, row_id FROM (${r.sql}) ORDER BY dataset, row_id`).all(...r.params)}function Ml(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 I_(e,t,r){let n=$l(r),o=e.query(`WITH m(dataset, row_id) AS (${n.sql})
106
+ SELECT dataset, row_id FROM m
107
+ EXCEPT SELECT dataset, row_id FROM room_rows WHERE peer_key = ?`).all(...n.params,t),i=e.query(`WITH m(dataset, row_id) AS (${n.sql})
108
+ SELECT dataset, row_id FROM room_rows WHERE peer_key = ?
109
+ EXCEPT SELECT dataset, row_id FROM m`).all(...n.params,t);return{entered:o,left:i}}function ta(e,t,r){let n=e.query("DELETE FROM room_rows WHERE peer_key = ? AND dataset = ? AND row_id = ?");for(let i of r.left)n.run(t,i.dataset,i.row_id);let o=e.query("INSERT OR IGNORE INTO room_rows (peer_key, dataset, row_id) VALUES (?, ?, ?)");for(let i of r.entered)o.run(t,i.dataset,i.row_id)}function N_(e,t,r){e.query("DELETE FROM room_rows WHERE peer_key = ?").run(t),ta(e,t,{entered:r,left:[]})}function P_(e,t,r,n={}){let o=["c.seq > ?"],i=[r,t];if(n.excludeGuestBase!=null)o.push("NOT (c.node_id = ? OR c.node_id LIKE ? || '-%')"),i.push(n.excludeGuestBase,n.excludeGuestBase);let s=n.limit!=null&&n.limit>0?` LIMIT ${Math.floor(n.limit)}`:"",c=e.query(`SELECT c.seq AS seq, ${O_} FROM crdt_changes c
110
+ JOIN room_rows r ON r.peer_key = ? AND r.dataset = c.dataset AND r.row_id = c.row_id
111
+ WHERE ${o.join(" AND ")} ORDER BY c.seq${s}`).all(...i),l=n.limit==null||n.limit<=0||c.length<n.limit,u;if(l){let f=e.query("SELECT MAX(seq) AS m FROM crdt_changes").get();u=Math.max(t,f.m??t)}else u=c[c.length-1].seq;return{changes:c.map(({seq:f,..._})=>_),cursor:u}}function Fl(e,t,r){return e.query(`SELECT ${vt} FROM crdt_changes c
112
+ WHERE c.dataset = ? AND c.row_id = ? AND NOT EXISTS (
113
+ SELECT 1 FROM crdt_changes k
114
+ WHERE k.dataset = c.dataset AND k.row_id = c.row_id AND k.col = c.col AND k.hlc > c.hlc
115
+ )`).all(t,r)}function ra(e,t){let r=$l(t);return e.query(`WITH m(dataset, row_id) AS (${r.sql})
116
+ SELECT ${O_} FROM crdt_changes c
117
+ JOIN m ON m.dataset = c.dataset AND m.row_id = c.row_id
118
+ WHERE NOT EXISTS (
119
+ SELECT 1 FROM crdt_changes k
120
+ WHERE k.dataset = c.dataset AND k.row_id = c.row_id AND k.col = c.col AND k.hlc > c.hlc
121
+ )`).all(...r.params)}function na(e){let t=e.map((r)=>`${r.dataset}\x00${r.row_id}\x00${r.col}\x00${r.hlc}`).sort();return Ll(t.map((r)=>r+"\x1E").join(""))}var A_,O_;var zl=Oe(()=>{it();A_=["databases","properties","records","sites","site_files"],O_=rs.map((e)=>"c."+e).join(", ")});var q_=`
2
122
  CREATE TABLE IF NOT EXISTS meta (
3
123
  key TEXT PRIMARY KEY,
4
124
  value TEXT
@@ -324,7 +444,7 @@ CREATE TABLE IF NOT EXISTS nodes (
324
444
  first_seen INTEGER, -- epoch ms of the device's first self-description
325
445
  __deleted INTEGER NOT NULL DEFAULT 0
326
446
  );
327
- `,dl=`
447
+ `,L_=`
328
448
  CREATE VIRTUAL TABLE IF NOT EXISTS search_fts USING fts5(
329
449
  kind UNINDEXED,
330
450
  id UNINDEXED,
@@ -332,31 +452,13 @@ CREATE VIRTUAL TABLE IF NOT EXISTS search_fts USING fts5(
332
452
  title,
333
453
  body
334
454
  );
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:Io,node:"~~~~~~~~"})}function yl(e,t){return e>Po(t)}function ds(e,t){if(t<=Io)return{millis:e,counter:t};return{millis:e+Math.floor(t/(Io+1)),counter:t%(Io+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 Io=65535,$r=300000;var $o=Ae(()=>{Xe()});function pn(e){if(!e)return[];let t=e.replace(/\r\n?/g,`
336
- `).split(`
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 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
- `));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 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=Cl[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,Cl,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}$/;Cl={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 Il(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=Il(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
- 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 ks(e,t){return e.query(`SELECT id, database_id, created_hlc, order_key FROM records
343
- WHERE database_id = ? AND __deleted = 0
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
- 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
- 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=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
- 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 ${Cb} 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 Cs(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=Cs(t),o=r?" AND id <> ?":"";return e.query(`SELECT order_key FROM documents WHERE ${n.clause}${o}
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 du(e,t){let r=Cs(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=Cs(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,Cb,Ib,Pb,Os,Go="ORDER BY order_key IS NULL, order_key, created_hlc, id",pu,Is,hu,Jo,Rx,Ax,Dx,Ox,gu;var vn=Ae(()=>{St();lt();Xe();Ob=["id","title","body","database_id","parent_id","created_hlc","order_key"],Cb=Ob.join(", "),Ib=["id","title","database_id","parent_id","created_hlc","order_key"],Pb=Ib.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)});Is=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)Is(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)}),Rx=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)}}),Ax=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)}}),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[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)}}),Ox=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
- UPDATE records SET data = coalesce((
355
- SELECT json_group_object(rv.property_id, json(rv.value))
356
- FROM record_values rv WHERE rv.record_id = records.id
357
- ), '{}')
358
- WHERE id IN (SELECT DISTINCT record_id FROM record_values);
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(`
455
+ `;function $_(e){oa=e}function M_(e,t){return oa?oa(e,t):Promise.resolve(null)}function F_(){return oa!==null}function Ri(e){let t=e.query("SELECT full_nodes, redundancy FROM blob_policy WHERE id = ? AND __deleted = 0").get(Ul),r=[];if(t?.full_nodes)try{let o=JSON.parse(t.full_nodes);if(Array.isArray(o))r=o.filter((i)=>typeof i==="string")}catch{}let n=t?.redundancy==="any"?"any":"all";return{fullNodes:r,redundancy:n}}function lx(e){e.query("UPDATE blob_cache SET anchored = 0").run(),e.query("DELETE FROM meta WHERE key = ?").run(ux)}function px(e){if(!e)return[];let t=[];for(let r of e.matchAll(dx))t.push(r[1]);return t}function U_(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 i of px(o.text))t.add(i);return t}function B_(e){return e.query("SELECT hash, size FROM blob_cache WHERE pending = 1").all()}function j_(e,t){return e.query("SELECT content_type FROM blob_cache WHERE hash = ?").get(t)?.content_type??null}var Ul="default",oa=null,z_=(e,t)=>{Ar(e,null,()=>{let r=new Set,n=t.filter((i)=>i&&!r.has(i)&&r.add(i)!=null);if(_e(e,"blob_policy",Ul,"full_nodes",n),Ri(e).redundancy==null)_e(e,"blob_policy",Ul,"redundancy","all")}),lx(e)},ux="blob_verified_at",dx;var Ti=Oe(()=>{it();Zt();dx=/\/blob\/([0-9a-f]{16,64})/g});function fx(e){e.exec(q_);try{e.exec(L_)}catch{}}function Di(e){return e.query("SELECT 1 AS ok FROM sqlite_master WHERE name = 'search_fts'").get()!=null}function jt(e,t,r){return e.query(`PRAGMA table_info(${t})`).all().some((o)=>o.name===r)}function Sn(e,t){return e.query("SELECT 1 AS ok FROM sqlite_master WHERE type = 'table' AND name = ?").get(t)!=null}function hx(e){if(!jt(e,"records","data"))e.exec("ALTER TABLE records ADD COLUMN data TEXT NOT NULL DEFAULT '{}'");if(!jt(e,"records","order_key"))e.exec("ALTER TABLE records ADD COLUMN order_key TEXT");if(Sn(e,"record_values"))Ve(e,()=>{e.exec(`
456
+ UPDATE records SET data = coalesce((
457
+ SELECT json_group_object(rv.property_id, json(rv.value))
458
+ FROM record_values rv WHERE rv.record_id = records.id
459
+ ), '{}')
460
+ WHERE id IN (SELECT DISTINCT record_id FROM record_values);
461
+ `),e.exec("DROP TABLE record_values"),Xs(e)}),Xs(e);e.exec("CREATE INDEX IF NOT EXISTS idx_mobile_record_page ON records(database_id, __deleted, order_key IS NULL, order_key, id)")}function gx(e){if(!jt(e,"shares","served_base"))e.exec("ALTER TABLE shares ADD COLUMN served_base TEXT");if(!jt(e,"shares","grants"))e.exec("ALTER TABLE shares ADD COLUMN grants TEXT");if(!jt(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 mx(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(!jt(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 _x(e){if(!jt(e,"doc_blocks","blank_after"))e.exec("ALTER TABLE doc_blocks ADD COLUMN blank_after INTEGER NOT NULL DEFAULT 0")}function yx(e){if(!jt(e,"blob_cache","pinned"))e.exec("ALTER TABLE blob_cache ADD COLUMN pinned INTEGER NOT NULL DEFAULT 0");if(!jt(e,"blob_cache","pending"))e.exec("ALTER TABLE blob_cache ADD COLUMN pending INTEGER NOT NULL DEFAULT 1");if(!jt(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 bx(e){if(!jt(e,"documents","order_key"))e.exec("ALTER TABLE documents ADD COLUMN order_key TEXT");ym(e)}function wx(e){if(!jt(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 vx(e){if(jt(e,"crdt_changes","seq"))return;Ve(e,()=>{if(e.exec(`
360
462
  DROP TABLE IF EXISTS crdt_changes_new;
361
463
  CREATE TABLE crdt_changes_new (
362
464
  seq INTEGER PRIMARY KEY AUTOINCREMENT,
@@ -381,7 +483,7 @@ CREATE VIRTUAL TABLE IF NOT EXISTS search_fts USING fts5(
381
483
  WHERE dataset = 'intent_receipts';
382
484
  CREATE INDEX IF NOT EXISTS idx_changes_docref ON crdt_changes(value)
383
485
  WHERE dataset = 'doc_blocks' AND col = 'doc_id';
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(`
486
+ `),Sn(e,"peers"))e.exec("UPDATE peers SET push_cursor = 0, pull_cursor = 0")})}function Ex(e){if(!Sn(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 i of t){let s;try{s=JSON.parse(i.config)}catch{continue}if(!s.endpoint||!s.bucket||!s.prefix)continue;let c=So(s.endpoint,s.bucket,s.prefix);if(c===i.url){n.add(c);continue}if(n.has(c)||e.query("SELECT 1 FROM peers WHERE url = ?").get(c)||Sn(e,"storage_cursors")&&e.query("SELECT 1 FROM storage_cursors WHERE peer_url = ?").get(c))continue;n.add(c),r.push({oldUrl:i.url,newUrl:c})}if(r.length===0)return;let o=new Map(r.map(({oldUrl:i,newUrl:s})=>[i,s]));Ve(e,()=>{for(let{oldUrl:i,newUrl:s}of r){if(Sn(e,"storage_cursors"))e.query("UPDATE storage_cursors SET peer_url = ? WHERE peer_url = ?").run(s,i);e.query("UPDATE peers SET url = ? WHERE url = ?").run(s,i)}if(Sn(e,"blob_policy")){let i=Ri(e).fullNodes;if(i.some((s)=>o.has(s)))z_(e,i.map((s)=>o.get(s)??s))}})}function Sx(e){if(jt(e,"databases","meta"))return;e.exec("ALTER TABLE databases ADD COLUMN meta TEXT"),e.exec(`
385
487
  UPDATE databases SET meta = (
386
488
  SELECT c.value FROM crdt_changes c
387
489
  WHERE c.dataset = 'databases' AND c.col = 'meta' AND c.row_id = databases.id
@@ -390,7 +492,7 @@ CREATE VIRTUAL TABLE IF NOT EXISTS search_fts USING fts5(
390
492
  WHERE id IN (
391
493
  SELECT DISTINCT row_id FROM crdt_changes WHERE dataset = 'databases' AND col = 'meta'
392
494
  )
393
- `)}function ew(e){let t=(r,n)=>{e.exec(`
495
+ `)}function kx(e){let t=(r,n)=>{e.exec(`
394
496
  UPDATE sites SET ${r} = COALESCE((
395
497
  SELECT json_extract(c.value, '$') FROM crdt_changes c
396
498
  WHERE c.dataset = 'sites' AND c.col = '${r}' AND c.row_id = sites.id
@@ -399,142 +501,104 @@ CREATE VIRTUAL TABLE IF NOT EXISTS search_fts USING fts5(
399
501
  WHERE id IN (
400
502
  SELECT DISTINCT row_id FROM crdt_changes WHERE dataset = 'sites' AND col = '${r}'
401
503
  )
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,kT,gr,Yn,Sn;var jr=Ae(()=>{kT=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}$`)},Cd,Id,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}$`);Cd=/^-?\d+$/,Id=/^-?\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=Cd}),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
- `).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 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,Cf,If,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??Id,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)}),Cf=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}}),If=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
- if (${He}.issues.length) {
407
- if (${Ze} in input) {
408
- payload.issues = payload.issues.concat(${He}.issues.map(iss => ({
409
- ...iss,
410
- path: iss.path ? [${Ze}, ...iss.path] : [${Ze}]
411
- })));
412
- }
413
- }
414
-
415
- if (${He}.value === undefined) {
416
- if (${Ze} in input) {
417
- newResult[${Ze}] = undefined;
418
- }
419
- } else {
420
- newResult[${Ze}] = ${He}.value;
421
- }
422
-
423
- `);else if(!Rt)X.write(`
424
- const ${He}_present = ${Ze} in input;
425
- if (${He}.issues.length) {
426
- payload.issues = payload.issues.concat(${He}.issues.map(iss => ({
427
- ...iss,
428
- path: iss.path ? [${Ze}, ...iss.path] : [${Ze}]
429
- })));
430
- }
431
- if (!${He}_present && !${He}.issues.length) {
432
- payload.issues.push({
433
- code: "invalid_type",
434
- expected: "nonoptional",
435
- input: undefined,
436
- path: [${Ze}]
437
- });
438
- }
439
-
440
- if (${He}_present) {
441
- if (${He}.value === undefined) {
442
- newResult[${Ze}] = undefined;
443
- } else {
444
- newResult[${Ze}] = ${He}.value;
445
- }
446
- }
447
-
448
- `);else X.write(`
449
- if (${He}.issues.length) {
450
- payload.issues = payload.issues.concat(${He}.issues.map(iss => ({
451
- ...iss,
452
- path: iss.path ? [${Ze}, ...iss.path] : [${Ze}]
453
- })));
454
- }
455
-
456
- if (${He}.value === undefined) {
457
- if (${Ze} in input) {
458
- newResult[${Ze}] = undefined;
459
- }
460
- } else {
461
- newResult[${Ze}] = ${He}.value;
462
- }
463
-
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,ZT,KT,Kr;var oa=Ae(()=>{ZT=Symbol("ZodOutput"),KT=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 Cp(e,t){return new e({type:"boolean",...qe(t)})}function Ip(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"&&Ct(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
-
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 Ct(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 Ct(n.element,r);if(n.type==="set")return Ct(n.valueType,r);if(n.type==="lazy")return Ct(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 Ct(n.innerType,r);if(n.type==="intersection")return Ct(n.left,r)||Ct(n.right,r);if(n.type==="record"||n.type==="map")return Ct(n.keyType,r)||Ct(n.valueType,r);if(n.type==="pipe"){if(e._zod.traits.has("$ZodCodec"))return!0;return Ct(n.in,r)||Ct(n.out,r)}if(n.type==="object"){for(let o in n.shape)if(Ct(n.shape[o],r))return!0;return!1}if(n.type==="union"){for(let o of n.options)if(Ct(o,r))return!0;return!1}if(n.type==="tuple"){for(let o of n.items)if(Ct(o,r))return!0;if(n.rest&&Ct(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(Ih,e)}function Th(e){return Op(iv,e)}function av(e){return Cp(sv,e)}function Rh(){return Ip(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 Cv({type:"pipe",in:e,out:t})}function Pv(e){return new Iv({type:"readonly",innerType:e})}function qv(e,t={}){return qp(Nv,e,t)}function Lv(e,t){return Lp(e,t)}var kh,ut,Ch,Uw,it,Bw,xh,Ei,jw,Hw,Ww,Zw,Kw,Gw,Vw,Jw,Xw,Qw,Yw,ev,tv,rv,nv,ov,Ih,iv,sv,cv,lv,dv,fv,pv,gv,Ta,_v,bv,Ph,vv,Sv,kv,Tv,Nh,Dv,Cv,Iv,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)),Ch=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),Ch.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),Ch.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)}),Ih=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),Ih.init(e,t)});sv=ce("ZodBoolean",(e,t)=>{Cf.init(e,t),ut.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Up(e,r,n,o)});cv=ce("ZodUnknown",(e,t)=>{If.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});Cv=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});Iv=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,GA,VA,Fh,JA,XA,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)")}),GA=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)")}),VA=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")}),JA=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)")}),XA=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 Ca(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){Ia=e}function Mt(e){if(!Ia)throw new H("network","no S3 storage client is registered for this runtime");return Ia(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
- WHERE NOT EXISTS (
472
- SELECT 1 FROM crdt_changes k
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 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 Ca(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 Ia=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,mD;var fg=Ae(()=>{Xe();mD=(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.8",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
- SELECT dataset, row_id FROM m
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
- 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 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
- 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,...A})=>A),cursor:m}}function Ja(e,t,r){return e.query(`SELECT ${_t} FROM crdt_changes c
482
- WHERE c.dataset = ? AND c.row_id = ? AND NOT EXISTS (
483
- SELECT 1 FROM crdt_changes k
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 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
- JOIN m ON m.dataset = c.dataset AND m.row_id = c.row_id
488
- WHERE NOT EXISTS (
489
- SELECT 1 FROM crdt_changes k
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 Ci(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 Ii=1,Pi=1048576,wO;var Qa=Ae(()=>{Xe();Wn();lt();Qo();St();Rg();Ag();Xa();wO=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 Cg(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 CE(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 Ig(e,t,r,n={}){let o=n.limit??500;OE(e,t.peerKey);let s=yo(e,t.peerKey).pull,a=CE(e,t,o),c={protocol:Ii,mh_version:n.mhVersion,node_id:We(e),since:s,changes:a.changes,evict:a.diff.left,digest:n.digest?Ci(Oi(e,t.scope)):void 0},p=await r(c);if(p.protocol!==Ii)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,...Cg(e,t,p.changes)],left:a.diff.left}),Ya(e,t.peerKey,{pull:p.cursor,push:a.pushCursor})}),p.need_baseline.length>0)await IE(e,t,r,p.need_baseline);let x=!1;if(n.digest&&p.digest!==void 0){if(Ci(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 IE(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,...Cg(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:Ii,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 Ig(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,
504
+ `)};if(!jt(e,"sites","visibility"))e.exec("ALTER TABLE sites ADD COLUMN visibility TEXT"),t("visibility","NULL");if(!jt(e,"sites","spa"))e.exec("ALTER TABLE sites ADD COLUMN spa INTEGER NOT NULL DEFAULT 0"),t("spa","0");if(!jt(e,"sites","public_grants"))e.exec("ALTER TABLE sites ADD COLUMN public_grants TEXT"),t("public_grants","NULL")}function H_(e,t){if(!Sn(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,i=e.query(`SELECT seq, ${vt} FROM crdt_changes
505
+ WHERE dataset = ? AND seq > ? ORDER BY seq`).all(t,o);if(i.length===0)return;Ve(e,()=>{for(let s of i)yo(e,s);e.query("INSERT INTO meta (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(r,String(i[i.length-1].seq))})}function xx(e){H_(e,"site_channels")}function Rx(e){H_(e,"nodes")}function Ai(e){if(Sn(e,"meta")&&bd(e))return;fx(e),wx(e),Sx(e),vx(e),hx(e),mx(e),Ex(e),_x(e),bx(e),yx(e),gx(e),kx(e),xx(e),Rx(e)}var Oi=Oe(()=>{er();Xn();on();Ti();hi();it()});var W_=Oe(()=>{Yn();Io()});var V_=Oe(()=>{Ke();Xn();es();it();Vt();Yn()});var ia=1,sa=1048576,q0;var Bl=Oe(()=>{Ke();Ln();it();Oi();Vt();W_();V_();zl();q0=Object.fromEntries(A_.map((e)=>[e,e]))});function Tx(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 Ci(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 jl(e,t,r){e.query("UPDATE peers SET pull_cursor = ?, push_cursor = ? WHERE url = ?").run(r.pull,r.push,t)}function G_(e,t){for(let r of e)if(r.node_id!==t&&!r.node_id.startsWith(t+"-"))throw new T("auth",`room returned an op authored by ${JSON.stringify(r.node_id)} — refusing to ingest`)}function K_(e,t,r){let n=new Set,o=[];for(let i of r){let s=`${i.dataset} ${i.row_id}`;if(n.has(s))continue;n.add(s);let c={dataset:i.dataset,row_id:i.row_id};if(Ml(e,t.scope,c))o.push(c)}return o}function Dx(e,t,r){return e.transaction(()=>{let{push:o}=Ci(e,t.peerKey),i=I_(e,t.peerKey,t.scope),s=P_(e,o,t.peerKey,{limit:r,excludeGuestBase:t.guestBase}),c=[...s.changes],l=[];for(let u of i.entered){if(c.length>=r&&l.length>0)break;if(c.push(...Fl(e,u.dataset,u.row_id)),l.push(u),c.length>=r)break}return{diff:i,shipped:l,changes:c,pushCursor:s.cursor,pendingBaselines:l.length<i.entered.length,incrementFull:s.changes.length>=r}})()}async function J_(e,t,r,n={}){let o=n.limit??500;Tx(e,t.peerKey);let i=Ci(e,t.peerKey).pull,s=Dx(e,t,o),c={protocol:ia,mh_version:n.mhVersion,node_id:Je(e),since:i,changes:s.changes,evict:s.diff.left,digest:n.digest?na(ra(e,t.scope)):void 0},l=await r(c);if(l.protocol!==ia)throw new T("conflict",`room answered protocol ${l.protocol} — upgrade required`);if(l.share_state==="expired")return{pushed:0,pulled:0,evicted:0,pending:!1,healed:!1,needBlobs:[],shareState:"expired"};G_(l.changes,t.guestBase);let u=ti(e,l.changes);if(Ve(e,()=>{ta(e,t.peerKey,{entered:[...s.shipped,...K_(e,t,l.changes)],left:s.diff.left}),jl(e,t.peerKey,{pull:l.cursor,push:s.pushCursor})}),l.need_baseline.length>0)await Ax(e,t,r,l.need_baseline);let f=!1;if(n.digest&&l.digest!==void 0){if(na(ra(e,t.scope))!==l.digest)await Ox(e,t,r),f=!0}return{pushed:s.changes.length,pulled:u,evicted:s.diff.left.length,pending:s.pendingBaselines||s.incrementFull||l.more===!0,healed:f,needBlobs:l.need_blobs??[],shareState:"active"}}async function Ax(e,t,r,n){let o=[],i=[],s=[];for(let l of n)if(Ml(e,t.scope,l))o.push(...Fl(e,l.dataset,l.row_id)),s.push(l);else i.push(l);let c=await X_(e,t,r,o,i);if(c.share_state==="expired")return;Ve(e,()=>{ta(e,t.peerKey,{entered:[...s,...K_(e,t,c.changes)],left:i});let l=Ci(e,t.peerKey);jl(e,t.peerKey,{pull:c.cursor,push:l.push})})}async function Ox(e,t,r){let n=C_(e,t.scope),o=ra(e,t.scope),i=await X_(e,t,r,o,[],n);if(i.share_state==="expired")return;Ve(e,()=>{N_(e,t.peerKey,n);let s=Ci(e,t.peerKey);jl(e,t.peerKey,{pull:i.cursor,push:s.push})})}async function X_(e,t,r,n,o,i){let s=await r({protocol:ia,node_id:Je(e),since:Ci(e,t.peerKey).pull,changes:n,evict:o,members:i});if(s.share_state==="expired")return s;return G_(s.changes,t.guestBase),ti(e,s.changes),s}var Z_=16;var Y_=Oe(()=>{Ke();Zt();it();zl();Bl()});function Qn(e){return`${e.base.replace(/\/+$/,"")}/r/${e.slug}/`}function ey(e){Q_=e}function Hl(e){return`room://${e}`}function Vr(e,t,r,n){let o={...t,lifecycle:r,...n?{cleanupError:n}:{cleanupError:void 0}};return Wl(e,{url:Hl(t.slug),config:o,label:`room ${t.slug}`}),o}function ca(e,t){return`${e.base.replace(/\/+$/,"")}/r/${encodeURIComponent(e.slug)}/${t}`}function la(e,t=!0){return{authorization:`Bearer ${e.ownerSecret}`,...t?{"content-type":"application/json"}:{}}}async function ty(e,t){try{return await fetch(ca(e,"owner/provision"),{method:"POST",headers:la(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 T("network",`edge worker unreachable: ${r.message}`)}}function ry(e){if(e.status===401)return new T("auth","edge worker refused the owner secret");if(e.status===404)return new T("not_found","the deployed edge worker has no room support — run `mh edge deploy` to upgrade it");return new T("network",`room provisioning failed: HTTP ${e.status}`)}function Cx(e){return async(t)=>{let r;try{r=await fetch(ca(e,"owner/sync"),{method:"POST",headers:la(e),body:JSON.stringify(t),signal:AbortSignal.timeout(30000)})}catch(n){throw new T("network",`room ${e.slug} unreachable: ${n.message}`)}if(r.status===409)throw new T("conflict","room protocol outdated — run `mh edge deploy`");if(r.status===401)throw new T("auth",`room ${e.slug} refused the owner secret`);if(r.status===404)throw new T("not_found",`room ${e.slug} is not provisioned — re-create the share with --room`);if(!r.ok)throw new T("network",`room sync failed: HTTP ${r.status}`);return await r.json()}}async function ua(e,t,r={}){if(!t.config)throw new T("invalid_input",`room peer ${t.url} has no config`);let n=JSON.parse(t.config);if(n.lifecycle==="cleanup_pending"){if(!await Wr(n).catch(()=>!1))throw new T("network",n.cleanupError||`room ${n.slug} cleanup is still pending`);return Jt(e,t.url),qr(e,n.slug),aa.delete(t.url),{pushed:0,pulled:0,pendingPush:!1}}let o=Hr(e,n.slug);if(!o){if(await Wr(n).catch(()=>!1))return Jt(e,t.url),{pushed:0,pulled:0,pendingPush:!1};throw n=Vr(e,n,"cleanup_pending","share row is gone but remote room destruction is unconfirmed"),new T("network",n.cleanupError)}if(n.lifecycle==="provisioning"){let g;try{g=await ty(n,o)}catch(F){if(await Wr(n).catch(()=>!1))Jt(e,t.url),qr(e,o.slug);else Vr(e,n,"cleanup_pending",F.message);throw F}if(!g.ok){let F=ry(g);if(g.status===401||g.status===404||await Wr(n).catch(()=>!1))Jt(e,t.url),qr(e,o.slug);else Vr(e,n,"cleanup_pending",F.message);throw F}let A=Vr(e,n,"active"),L=Pt(e,t.url);try{return await ua(e,L,r)}catch(F){if(await Wr(A).catch(()=>!1))Jt(e,t.url),qr(e,o.slug);else Vr(e,A,"cleanup_pending",F.message);throw F}}let i={grantedDbIds:an(o.grants).tables.map((g)=>g.db),siteId:o.kind==="site"?o.target_id:null},s=n.guestBase??o.guest_node_id;if(!s)throw new T("invalid_input",`room peer ${t.url} has no guest base id — revoke and re-create the share with --room`);let c=aa.get(t.url)??{rounds:0,lastGrants:o.grants},l=Cx(n),u=0,f=0,_=[],E=!1;for(let g=0;g<Ix;g++){c.rounds++;let A=c.rounds%Z_===0||c.lastGrants!==o.grants;c.lastGrants=o.grants,aa.set(t.url,c);let L=await J_(e,{peerKey:t.url,scope:i,guestBase:s},l,{digest:A});if(L.shareState==="expired")return await Wr(n).catch(()=>{return}),Jt(e,t.url),{pushed:u,pulled:f,pendingPush:!1};if(u+=L.pushed,f+=L.pulled,_=L.needBlobs,E=L.pending,!L.pending)break}if(_.length>0)await Nx(e,n,_,r.resolveBlob);return{pushed:u,pulled:f,pendingPush:E}}async function Nx(e,t,r,n){let o=n??Q_;if(!o)return 0;let i=0;for(let s of r){if(!/^[0-9a-f]{16,64}$/.test(s))continue;let c=await o(e,s).catch(()=>null);if(!c)continue;let l=Math.max(1,Math.ceil(c.byteLength/sa)),u=!0;for(let f=0;f<l&&u;f++){let _=c.subarray(f*sa,(f+1)*sa),E=new Uint8Array(_.byteLength);E.set(_),u=!!(await fetch(`${ca(t,`owner/blob/${s}`)}?idx=${f}&total=${l}`,{method:"POST",headers:{...la(t,!1),"content-type":"application/octet-stream"},body:E.buffer,signal:AbortSignal.timeout(30000)}).catch(()=>null))?.ok}if(u)i++}return i}async function ny(e,t,r,n){let o={base:r.endpoint.replace(/\/+$/,""),slug:t.slug,ownerSecret:r.token,guestBase:t.guest_node_id??"g"+Wt(8),lifecycle:"provisioning"},i=Hl(t.slug);Wl(e,{url:i,config:o,label:`room ${t.slug}`});let s;try{s=await ty(o,t)}catch(u){let f=u.message;if(await Wr(o).catch(()=>!1))Jt(e,i);else Vr(e,o,"cleanup_pending",f);throw u}if(!s.ok){let u=ry(s);if(s.status===401||s.status===404)throw Jt(e,i),u;let f=u.message;if(await Wr(o).catch(()=>!1))Jt(e,i);else Vr(e,o,"cleanup_pending",f);throw u}let c=Vr(e,o,"active"),l=Pt(e,i);try{await ua(e,l,{resolveBlob:n})}catch(u){let f=u.message;if(await Wr(c).catch(()=>!1))Jt(e,i);else Vr(e,c,"cleanup_pending",f);throw u}return{url:Qn(c),peerKey:i}}async function Wr(e){let t=await fetch(ca(e,"owner/destroy"),{method:"POST",headers:la(e),signal:AbortSignal.timeout(30000)});return t.ok||t.status===404}async function Ii(e,t){let r=Pt(e,Hl(t));if(!r||r.kind!=="room"||!r.config)return"absent";let n=JSON.parse(r.config),o=Vr(e,n,"cleanup_pending","remote room destruction is unconfirmed");if(!await Wr(o).catch(()=>!1))return"cleanup_pending";return Jt(e,r.url),aa.delete(r.url),"destroyed"}var Q_,aa,Ix=50;var da=Oe(()=>{Ke();Vt();Io();Yn();eo();Y_();Bl();aa=new Map});function $x(e){let t=e.slice(e.lastIndexOf(".")+1).toLowerCase();return Lx[t]??"application/octet-stream"}function Gl(e){let t=e.trim().toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^-+|-+$/g,"");if(!t)throw new T("invalid_input",`invalid site name: ${JSON.stringify(e)}`);return t}function Kl(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 sy(e){return e.visibility==="public"}function Lr(e,t){return e.query(`SELECT ${Zl} FROM sites WHERE id = ? AND __deleted = 0`).get(t)}function ay(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 Jl(e,t){let r;try{r=Gl(t)}catch{return null}return e.query(`SELECT ${Zl} FROM sites WHERE name = ? AND __deleted = 0 ORDER BY created_hlc DESC LIMIT 1`).get(r)}function cy(e){return e.query(`SELECT ${Zl} FROM sites WHERE __deleted = 0 ORDER BY created_hlc`).all()}function to(e,t){let n=(t.startsWith("site_")?Lr(e,t):null)??Jl(e,t);if(!n)throw new T("not_found",`no such site: ${t}`);return n}function Vl(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 ly(e,t,r,n={}){let o=r===""||r.endsWith("/")?`${r}index.html`:r,i=Kl(o);if(i){let c=Vl(e,t,i);if(c)return{row:c,status:200}}if(n.spa){let c=r.split("/").pop()??"";if(!/\.[a-z0-9]+$/i.test(c)){let l=Vl(e,t,"index.html");if(l)return{row:l,status:200}}}let s=Vl(e,t,"404.html");if(s)return{row:s,status:404};return null}function uy(e,t){return e.query(`SELECT id, site_id, path, content_type, encoding,
492
506
  CASE encoding
493
507
  WHEN 'utf8' THEN LENGTH(CAST(content AS BLOB))
494
508
  WHEN 'base64' THEN (LENGTH(content) / 4) * 3
495
509
  ELSE (SELECT size FROM blob_cache WHERE hash = content)
496
510
  END AS size
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 It(e,t){return e.query(`INSERT INTO site_channel_observations
511
+ FROM site_files WHERE site_id = ? AND __deleted = 0 ORDER BY path`).all(t)}function dy(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 Fx(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 oy(e){if(typeof e==="string")return new TextEncoder().encode(e);return e instanceof Uint8Array?e:new Uint8Array(e)}function zx(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return btoa(t)}function py(e){if(e!=="public"&&e!=="private")throw new T("invalid_input",`visibility must be "public" or "private", got ${JSON.stringify(e)}`)}function my(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 Ux(e,t,r,n,o,i){let s=e.query(`SELECT ${iy} FROM site_files WHERE site_id = ? AND path = ? AND __deleted = 0 ORDER BY created_hlc LIMIT 1`).get(t,r);if(!s)return null;return s.content_type===n&&s.encoding===o&&s.content===i?s:null}function Bx(e,t,r,n,o,i){let s=Ux(e,t,r,n,o,i);if(s)return{...s,changed:!1};let c=my(e,t,r),l=c??ur("sf",r);return Ar(e,null,()=>{if(!c){let f=_e(e,"site_files",l,"site_id",t);_e(e,"site_files",l,"path",r),_e(e,"site_files",l,"created_hlc",f.hlc)}_e(e,"site_files",l,"content_type",n),_e(e,"site_files",l,"encoding",o),_e(e,"site_files",l,"content",i),_e(e,"site_files",l,"__deleted",0)}),{...e.query(`SELECT ${iy} FROM site_files WHERE id = ?`).get(l),changed:!0}}function _y(e,t,r,n){let o=Kl(r);if(!o)throw new T("invalid_input",`invalid file path: ${JSON.stringify(r)}`);let i=n.contentType??$x(o),s,c;if(Fx(i))s="utf8",c=typeof n.data==="string"?n.data:new TextDecoder().decode(oy(n.data));else{let l=oy(n.data);if(l.byteLength>Mx)throw new T("invalid_input","binary too large for inline storage (needs a server-backed blob)");s="base64",c=zx(l)}return Bx(e,t,o,i,s,c)}function by(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 wy(e,t){return e.query("SELECT COUNT(*) AS n FROM site_files WHERE site_id = ? AND __deleted = 0").get(t).n}var Px,Zl,qx,iy,Lx,Mx=262144,fy,pa,hy,gy,yy;var No=Oe(()=>{Ke();it();Vt();Yn();Px=["id","name","title","created_hlc","visibility","spa","public_grants"],Zl=Px.join(", "),qx=["id","site_id","path","content_type","encoding","content"],iy=qx.join(", "),Lx={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"};fy=We(function(t,r){let n=Gl(r.name);if(Jl(t,n))throw new T("conflict",`site name already exists: ${n}`);if(r.visibility!==void 0)py(r.visibility);let o=ur("site",n),i=_e(t,"sites",o,"name",n);if(_e(t,"sites",o,"created_hlc",i.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 Lr(t,o)}),pa=We(function(t,r,n){if(!Lr(t,r))throw new T("not_found",`no such site: ${r}`);if(n.visibility!==void 0)py(n.visibility);if(n.name!==void 0){let o=Gl(n.name),i=Jl(t,o);if(i&&i.id!==r)throw new T("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 Lr(t,r)}),hy=We(function(t,r,n){if(!Lr(t,r))throw new T("not_found",`no such site: ${r}`);let o=n==null?null:ea(ki(n));return _e(t,"sites",r,"public_grants",o),Lr(t,r)}),gy=We(function(t,r){if(!Lr(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});yy=We(function(t,r,n){let o=my(t,r,Kl(n));if(!o)return!1;let i=t.query("SELECT __deleted AS d FROM site_files WHERE id = ?").get(o);if(!i||i.d)return!1;return _e(t,"site_files",o,"__deleted",1),!0})});function Xl(e){return(e.audience==="public"||e.audience==="link")&&(e.hosting==="device"||e.hosting==="edge")&&(e.desired_state==="active"||e.desired_state==="revoked")}function Rr(e,t){return(t?e.query(`SELECT ${Ni} FROM site_channels
512
+ WHERE site_id = ? AND __deleted = 0 ORDER BY created_hlc, id`).all(t):e.query(`SELECT ${Ni} FROM site_channels
513
+ WHERE __deleted = 0 ORDER BY created_hlc, id`).all()).filter(Xl)}function Po(e,t){let r=e.query(`SELECT ${Ni} FROM site_channels WHERE id = ? AND __deleted = 0`).get(t);return r&&Xl(r)?r:null}function Hx(e,t){let r=Rr(e,t).filter((n)=>n.audience==="public"&&n.desired_state==="active");for(let n of r)cn(e,n.id,"revoked");return r.length}function vy(e,t,r){let n=Rr(e,t).filter((o)=>o.audience==="public"&&o.desired_state==="active");for(let o of n)Pi(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 Wx(e){if(e==null)return null;try{return JSON.parse(e)}catch{return null}}function Vx(e,t,r){let n=Rr(e,t).filter((i)=>i.audience==="public"&&i.hosting==="device"&&i.desired_state==="active"&&i.canonical_url!=null),o=0;for(let i of n){let s;try{let c=new URL(i.canonical_url);c.pathname=`/sites/${encodeURIComponent(r)}/`,c.search="",c.hash="",s=c.toString()}catch{continue}Pi(e,{id:i.id,siteId:i.site_id,audience:"public",hosting:"device",controllerNodeId:i.controller_node_id,targetRef:i.target_ref,canonicalUrl:s,policy:Wx(i.policy_json),desiredState:"active"}),o++}return o}function Ey(e,t,r,n){return Ar(e,"site.update",()=>{let o=pa(e,t,{...r,visibility:r.visibility==="public"?"private":r.visibility});if(r.visibility==="private")Hx(e,t);if(r.visibility==="public")n?.recordPublic?.(o);if(r.name!==void 0)Vx(e,t,o.name);return Lr(e,t)})}function Sy(e,t){return Ar(e,"site.delete",()=>{if(!gy(e,t))return!1;return Zx(e,t),!0})}function Zx(e,t){let r=Rr(e,t).filter((n)=>n.desired_state==="active");for(let n of r)cn(e,n.id,"revoked");return r.length}function ir(e,t){return e.query(`INSERT INTO site_channel_observations
500
514
  (channel_id,status,last_verified_at,last_error)
501
515
  VALUES (?,?,?,?)
502
516
  ON CONFLICT(channel_id) DO UPDATE SET
503
517
  status=excluded.status,
504
518
  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 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
519
+ 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 ky(e,t){e.query("DELETE FROM site_channel_observations WHERE channel_id = ?").run(t)}function fa(e,t){let r=e.query(`SELECT channel_id,status,last_verified_at,last_error
520
+ 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 Yl(e,t){let r=Je(e);return Rr(e,t).map((n)=>{let o=fa(e,n.id),i;if(n.desired_state==="active")i=o?.status??"unverified";else if(n.hosting==="device"&&n.target_ref===r)i="revoked";else if(o?.status==="revoked"||o?.status==="cleanup_pending"||o?.status==="rollback_pending"||o?.status==="error")i=o.status;else i=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:i,lastVerifiedAt:o?.lastVerifiedAt??null,lastError:o?.lastError??null}})}function xy(e,t){let r=e.query(`SELECT ${Ni} FROM site_channels
521
+ WHERE site_id = ? AND audience = 'public' AND __deleted = 0 ORDER BY created_hlc, id`).all(t.id);if(r.length===0){let s=sy(t);return{serving:s,configured:s,anomaly:null}}let n=r.filter(Xl),o=n.filter((s)=>s.desired_state==="active"),i=Je(e);return{serving:o.some((s)=>s.hosting==="device"&&s.target_ref===i),configured:o.length>0,anomaly:r.length>n.length?"malformed_public_channel":null}}var jx,Ni,Pi,cn;var qi=Oe(()=>{it();Ke();Vt();Zt();No();jx=["id","site_id","audience","hosting","controller_node_id","target_ref","canonical_url","policy_json","desired_state","created_hlc","__deleted"],Ni=jx.join(", ");Pi=We(function(t,r){if(!Lr(t,r.siteId))throw new T("not_found",`no such site: ${r.siteId}`);let n=r.controllerNodeId??Je(t),o=r.id?Po(t,r.id):t.query(`SELECT ${Ni} FROM site_channels
508
522
  WHERE site_id = ? AND audience = ? AND hosting = ? AND target_ref = ?
509
523
  AND __deleted = 0
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 Cn(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))It(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"){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)or(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 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)
524
+ ORDER BY created_hlc LIMIT 1`).get(r.siteId,r.audience,r.hosting,r.targetRef),i=o?.id??ur("chan",`${r.audience}-${r.hosting}-${r.siteId}`,"channel"),s={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 Ve(t,()=>{if(!o){let c=_e(t,"site_channels",i,"site_id",r.siteId);_e(t,"site_channels",i,"created_hlc",c.hlc)}for(let[c,l]of Object.entries(s)){if(o&&o[c]===l)continue;_e(t,"site_channels",i,c,l)}}),Po(t,i)}),cn=We(function(t,r,n){if(!Po(t,r))throw new T("not_found",`no such site channel: ${r}`);return _e(t,"site_channels",r,"desired_state",n),Po(t,r)})});async function qo(e){try{return await Gx(e),null}catch(t){let r=t instanceof Error?t.message:String(t);return console.error(`site channel reconcile failed: ${r}`),r}}async function Gx(e){let t=Je(e),r=Rr(e),n=new Set;for(let i of r){if(i.desired_state!=="active")continue;if(ay(e,i.site_id)==="tombstoned"){cn(e,i.id,"revoked"),n.add(i.id);continue}if(i.audience!=="link"||i.controller_node_id!==t)continue;if(!Hr(e,i.target_ref))ir(e,{channelId:i.id,status:"error",lastError:`${Ry}: 本机缺少该链接的凭据记录`});else if(fa(e,i.id)?.lastError?.startsWith(Ry))ky(e,i.id)}let o=r.map((i)=>n.has(i.id)?Po(e,i.id)??i:i).filter((i)=>i.controller_node_id===t&&i.desired_state==="revoked"&&i.audience==="link"&&!(i.hosting==="edge"&&fa(e,i.id)?.status==="revoked"));for(let i of o){let s=Hr(e,i.target_ref);try{if(i.hosting==="edge"){await Promise.resolve().then(() => da());let l=await Ii(e,i.target_ref);if(l==="cleanup_pending"){ir(e,{channelId:i.id,status:"cleanup_pending",lastError:"Edge 尚未确认销毁 Room"});continue}if(l==="absent"){ir(e,{channelId:i.id,status:"cleanup_pending",lastError:"Edge Room 记录缺失,销毁未确认"});continue}}else if(!s){ir(e,{channelId:i.id,status:"revoked",lastVerifiedAt:Date.now()});continue}if(s)qr(e,s.slug);ir(e,{channelId:i.id,status:"revoked",lastVerifiedAt:Date.now()})}catch(c){ir(e,{channelId:i.id,status:"cleanup_pending",lastError:c instanceof Error?c.message:String(c)})}}}var Ry="controller_state_missing";var Ql=Oe(()=>{Zt();qi();Io();No()});function Ft(e){return e.query(`SELECT ${Ay} FROM peers ORDER BY url`).all()}function Pt(e,t){return e.query(`SELECT ${Ay} FROM peers WHERE url = ?`).get(t)??null}function ha(e,t){e.query(`INSERT INTO peers (url, token, label, node_id, enabled, pull_cursor, push_cursor)
511
525
  VALUES (?, ?, ?, ?, 1, 0, 0)
512
526
  ON CONFLICT(url) DO UPDATE SET
513
527
  token = coalesce(excluded.token, peers.token),
514
528
  label = coalesce(excluded.label, peers.label),
515
529
  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 pm(e,t){e.query(`INSERT INTO peers (url, kind, config, label, enabled, pull_cursor, push_cursor)
530
+ enabled = 1`).run(t.url,t.token??null,t.label??null,t.node_id??null)}function ga(e,t){e.query(`INSERT INTO peers (url, kind, config, label, enabled, pull_cursor, push_cursor)
517
531
  VALUES (?, 's3', ?, ?, 1, 0, 0)
518
532
  ON CONFLICT(url) DO UPDATE SET
519
533
  kind = 's3',
520
534
  config = excluded.config,
521
535
  label = coalesce(excluded.label, peers.label),
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)
536
+ enabled = 1`).run(t.url,JSON.stringify(t.config),t.label??null)}function Wl(e,t){e.query(`INSERT INTO peers (url, kind, config, label, enabled, pull_cursor, push_cursor)
523
537
  VALUES (?, 'room', ?, ?, 1, 0, 0)
524
538
  ON CONFLICT(url) DO UPDATE SET
525
539
  kind = 'room',
526
540
  config = excluded.config,
527
541
  label = coalesce(excluded.label, peers.label),
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 Cn(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(`
542
+ enabled = 1`).run(t.url,JSON.stringify(t.config),t.label??null)}function Jt(e,t){return Ve(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 Dy(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 eu(e,t,r){let n=Ty.get(e);if(!n)n=new Map,Ty.set(e,n);let o=n.get(t);if(o)return o;let i=Xx(e,t,r).finally(()=>{if(n.get(t)===i)n.delete(t)});return n.set(t,i),i}function Kx(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 Jx(e){try{let t=await fetch(new URL(Yg,e),{signal:AbortSignal.timeout(5000)});if(!t.ok)return null;let r=Jg.safeParse(await t.json());return r.success?r.data:null}catch{return null}}async function Xx(e,t,r){try{let n=Pt(e,t),o;if(n?.kind==="s3"){if(!n.config)throw Error(`storage peer ${t} has no config`);let l=JSON.parse(n.config),u={...r?.storage,publish:r?.storage?.publish??l.publish,priority:r?.storage?.priority??l.priority};o=await Vs(e,t,$t(l),l,u)}else if(n?.kind==="room"){Qt(e);await Promise.resolve().then(() => da());o=await ua(e,n)}else o=await Os(e,t,{timeoutMs:r?.timeoutMs});Dy(e,t,"ok",null);let i=[...o.warnings??[]];try{if(n?.kind!=="s3"&&n?.kind!=="room")Vm(e,t)}catch(l){i.push(`site rollback bookkeeping failed: ${l.message}`)}if(n?.kind!=="s3"&&n?.kind!=="room"){let l=Kx(Gm.version,await Jx(t));if(l)i.push(`${t}: ${l}`)}await Promise.resolve().then(() => Ql());let c=await qo(e);if(c)i.push(`site channel reconcile failed: ${c}`);return{url:t,ok:!0,pushed:o.pushed,pulled:o.pulled,pendingPush:o.pendingPush,...i.length?{warnings:i}:{}}}catch(n){let o=n.message;return Dy(e,t,"error",o),{url:t,ok:!1,error:o,code:pn(n)}}}var Ay="url, pull_cursor, push_cursor, token, label, node_id, enabled, last_sync_at, last_success_at, last_status, last_error, kind, config",Ty;var eo=Oe(()=>{er();Ke();Cs();hi();Pr();Hm();Wm();rn();yn();Zm();hi();Ty=new WeakMap});class xu{constructor({accessKeyId:e,secretAccessKey:t,sessionToken:r,service:n,region:o,cache:i,retries:s,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=i||new Map,this.retries=s!=null?s:10,this.initRetryMs=c||50}async sign(e,t){if(e instanceof Request){let{method:o,url:i,headers:s,body:c}=e;if(t=Object.assign({method:o,url:i,headers:s},t),t.body==null&&s.has("Content-Type"))t.body=c!=null&&s.has("X-Amz-Content-Sha256")?c:await e.clone().arrayBuffer();e=i}let r=new Wb(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((i)=>setTimeout(i,Math.random()*this.initRetryMs*Math.pow(2,r)))}throw Error("An unknown error occurred, ensure retries is not negative")}}class Wb{constructor({method:e,url:t,headers:r,body:n,accessKeyId:o,secretAccessKey:i,sessionToken:s,service:c,region:l,cache:u,datetime:f,signQuery:_,appendSessionToken:E,allHeaders:g,singleEncode:A}){if(t==null)throw TypeError("url is a required option");if(o==null)throw TypeError("accessKeyId is a required option");if(i==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=i,this.sessionToken=s;let L,F;if(!c||!l)[L,F]=AR(this.url,this.headers);if(this.service=c||L||"",this.region=l||F||"us-east-1",this.cache=u||new Map,this.datetime=f||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=_,this.appendSessionToken=E||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 X=this.signQuery?this.url.searchParams:this.headers;if(X.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken)X.set("X-Amz-Security-Token",this.sessionToken);if(this.signableHeaders=["host",...this.headers.keys()].filter((ce)=>g||!DR.has(ce)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map((ce)=>ce+":"+(ce==="host"?this.url.host:(this.headers.get(ce)||"").replace(/\s+/g," "))).join(`
543
+ `),this.credentialString=[this.datetime.slice(0,8),this.region,this.service,"aws4_request"].join("/"),this.signQuery){if(this.service==="s3"&&!X.has("X-Amz-Expires"))X.set("X-Amz-Expires","86400");X.set("X-Amz-Algorithm","AWS4-HMAC-SHA256"),X.set("X-Amz-Credential",this.accessKeyId+"/"+this.credentialString),X.set("X-Amz-SignedHeaders",this.signedHeaders)}if(this.service==="s3")try{this.encodedPath=decodeURIComponent(this.url.pathname.replace(/\+/g," "))}catch(ce){this.encodedPath=this.url.pathname}else this.encodedPath=this.url.pathname.replace(/\/+/g,"/");if(!A)this.encodedPath=encodeURIComponent(this.encodedPath).replace(/%2F/g,"/");this.encodedPath=Hb(this.encodedPath);let te=new Set;this.encodedSearch=[...this.url.searchParams].filter(([ce])=>{if(!ce)return!1;if(this.service==="s3"){if(te.has(ce))return!1;te.add(ce)}return!0}).map((ce)=>ce.map((de)=>Hb(encodeURIComponent(de)))).sort(([ce,de],[Ce,ge])=>ce<Ce?-1:ce>Ce?1:de<ge?-1:de>ge?1:0).map((ce)=>ce.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 $i("AWS4"+this.secretAccessKey,e),o=await $i(n,this.region),i=await $i(o,this.service);r=await $i(i,"aws4_request"),this.cache.set(t,r)}return Su(await $i(r,await this.stringToSign()))}async stringToSign(){return["AWS4-HMAC-SHA256",this.datetime,this.credentialString,Su(await Bb(await this.canonicalString()))].join(`
530
544
  `)}async canonicalString(){return[this.method.toUpperCase(),this.encodedPath,this.encodedSearch,this.canonicalHeaders+`
531
545
  `,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=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)),In))),(await n.sign(o.toString(),{method:"GET",aws:{signQuery:!0}})).url}var In=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 Cc(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 Cc(`${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 Cc(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 Cc(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 Ic=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=In){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=In){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)),In)}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();Ic();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",hP;var T_=Ae(()=>{Da();Xe();St();Zo();Dn();vn();zr();An();Rn();Lc();Ui();Ic();k_();Eo();hP=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 vk=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),Ir=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_,Ir,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 _(C){var V=0;for(;V<C.length;V++)if(C[V]!=="")break;var U=C.length-1;for(;U>=0;U--)if(C[U]!=="")break;if(V>U)return[];return C.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)=>Ir.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,C=Y_(`cp ${b}`);ty(C);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(C)}},ny=(i,u,_,f,l,d,h,E,b,C)=>{Yc(i,u,_,f,l,E,b,C).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((C)=>!!C),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(C){if(C?.errno===44&&E&&u.noent_okay)return{path:d};throw C}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 C=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(C===U)return;var N=y.isDir(C.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(C)||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(C);try{E.node_ops.rename(C,b,d),C.parent=b}catch(W){throw W}finally{y.hashAddNode(C)}},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 C=y.open(b,577);y.write(C,_,0,_.length,0,d),y.close(C),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,C,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[C+q]=W}if(N)E.node.atime=Date.now();return N},write(E,b,C,V,U){for(var N=0;N<V;N++)try{f(b[C+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 C(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),C(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 C(V,Ht,K,U,N),{ptr:K,allocated:!0}},E.stream_ops=b,E}},oy=(i,u,_)=>{if(!i)return"";var f=Kc(Ir,i,u,_);return Zc.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,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=Ir.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,Ir,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],C=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:C,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(C){if(typeof y>"u"||C.name!=="ErrnoError")throw C;return-C.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,_),C=b.ptr;return Ye[d>>2]=b.allocated,rt[h>>2]=C,0}catch(V){if(typeof y>"u"||V.name!=="ErrnoError")throw V;return-V.errno}}function Cy(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 Iy=(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(),C=Math.max(E,b);rt[i>>2]=C*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=Ir.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:Cy,_tzset_js:Iy,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(),C=(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 I;if(S.length)if(V(S[0]))if(I=S[0],S.length===1)super(C(S[0]));else{let G=C(I);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=I||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(I){if(!S._max)S._max=BigInt("0x7fffffffffffffff"),S._min=~S._max;return I>=S._min&&I<=S._max},W=(S)=>S>=-2147483647n-1n&&S<=2147483647n,K=function S(I){if(!S._min)S._min=Number.MIN_SAFE_INTEGER,S._max=Number.MAX_SAFE_INTEGER;return I>=S._min&&I<=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,I,G,oe,Z,ge,we,ye,ve)=>{},sqlite3_create_function:(S,I,G,oe,Z,ge,we,ye)=>{},sqlite3_create_window_function:(S,I,G,oe,Z,ge,we,ye,ve,M)=>{},sqlite3_prepare_v3:(S,I,G,oe,Z,ge)=>{},sqlite3_prepare_v2:(S,I,G,oe,Z)=>{},sqlite3_exec:(S,I,G,oe,Z)=>{},sqlite3_randomness:(S,I)=>{}});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,I){if(!S)J.toss("Assertion failed:",I)},affirmDbHeader:function(S){if(S instanceof ArrayBuffer)S=new Uint8Array(S);let I="SQLite format 3";if(15>S.byteLength)N("Input does not contain an SQLite3 database header.");for(let G=0;G<15;++G)if(I.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 I=S.byteLength;if(I<512||I%512!==0)N("Byte array size",I,"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 I=b.alloc(S.byteLength||1);return b.heapForSize(S.constructor).set(S.byteLength?S:[0],Number(I)),I};{let{allocExportName:S,deallocExportName:I,reallocExportName:G}=h;for(let oe of[S,I,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[I]}b.compileOptionUsed=function S(I){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(I)){let G=d();return I.forEach((oe)=>{G[oe]=E.sqlite3_compileoption_used(oe)}),G}else if(typeof I==="object")return Object.keys(I).forEach((G)=>{I[G]=E.sqlite3_compileoption_used(G)}),I;return typeof I==="string"?!!E.sqlite3_compileoption_used(I):!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,I){if(typeof I==="string"&&!(I=b.sizeofIR(I)))j.toss("Invalid size value for allocChunks(",arguments[1],")");let G=b.pstack.alloc(S*I),oe=[G],Z=1,ge=I;for(;Z<S;++Z,ge+=I)oe.push(b.ptr.add(G,ge));return oe},allocPtr:(S=1,I=!0)=>S===1?b.pstack.alloc(I?8:b.ptr.size):b.pstack.allocChunks(S,I?8:b.ptr.size),call:function(S){let I=b.pstack.pointer;try{return S(pe)}finally{b.pstack.restore(I)}}}),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 I=S[0];if(I.byteLength===0)return b.exports.sqlite3_randomness(0,b.ptr.null),I;let G=b.pstack.pointer;try{let oe=I.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),I.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 I}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(I){return this.dir=""}}.bind(d()),E.sqlite3_wasmfs_filename_is_persistent=function(S){let I=E.sqlite3_wasmfs_opfs_dir();return I&&S?S.startsWith(I+"/"):!1},E.sqlite3_js_db_uses_vfs=function(S,I,G=0){try{let oe=E.sqlite3_vfs_find(I);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=[],I=E.sqlite3_vfs_find(b.ptr.null);while(I){let G=new E.sqlite3_vfs(I);S.push(b.cstrToJs(G.$zName)),I=G.$pNext,G.dispose()}return S},E.sqlite3_js_db_export=function(S,I=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=I?b.isPtr(I)?I:b.scopedAllocCString(""+I):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,I=b.ptr.null)=>J.sqlite3__wasm_db_vfs(S,I),E.sqlite3_js_aggregate_context=(S,I)=>E.sqlite3_aggregate_context(S,I)||(I?j.toss("Cannot allocate",I,"bytes for sqlite3_aggregate_context()"):0),E.sqlite3_js_posix_create_file=function(S,I,G){let oe;if(I&&b.isPtr(I))oe=I;else if(I instanceof ArrayBuffer||I instanceof Uint8Array){if(oe=b.allocFromTypedArray(I),arguments.length<3||!J.isInt32(G)||G<0)G=I.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!==I)b.dealloc(oe)}},E.sqlite3_js_vfs_create_file=function(S,I,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,I,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 I=ee(v);return I===v?void 0:I},E.sqlite3_db_config=function(S,I,...G){switch(I){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,I,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,I,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,I,G[0]);default:return E.SQLITE_MISUSE}}.bind(d()),E.sqlite3_value_to_js=function(S,I=!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(I)N(E.SQLITE_MISMATCH,"Unhandled sqlite3_value_type():",oe);G=void 0}return G},E.sqlite3_values_to_js=function(S,I,G=!0){let oe,Z=[];for(oe=0;oe<S;++oe)Z.push(E.sqlite3_value_to_js(b.peekPtr(b.ptr.add(I,b.ptr.size*oe)),G));return Z},E.sqlite3_result_error_js=function(S,I){if(I instanceof j)E.sqlite3_result_error_nomem(S);else E.sqlite3_result_error(S,""+I,-1)},E.sqlite3_result_js=function(S,I){if(I instanceof Error){E.sqlite3_result_error_js(S,I);return}try{switch(typeof I){case"undefined":break;case"boolean":E.sqlite3_result_int(S,I?1:0);break;case"bigint":if(J.bigIntFits32(I))E.sqlite3_result_int(S,Number(I));else if(J.bigIntFitsDouble(I))E.sqlite3_result_double(S,Number(I));else if(b.bigIntEnabled)if(J.bigIntFits64(I))E.sqlite3_result_int64(S,I);else N("BigInt value",I.toString(),"is too BigInt for int64.");else N("BigInt value",I.toString(),"is too BigInt.");break;case"number":{let G;if(J.isInt32(I))G=E.sqlite3_result_int;else if(b.bigIntEnabled&&Number.isInteger(I)&&J.bigIntFits64(BigInt(I)))G=E.sqlite3_result_int64;else G=E.sqlite3_result_double;G(S,I);break}case"string":{let[G,oe]=b.allocCString(I,!0);E.sqlite3_result_text(S,G,oe,E.SQLITE_WASM_DEALLOC);break}case"object":if(I===null){E.sqlite3_result_null(S);break}else if(J.isBindableTypedArray(I)){let G=b.allocFromTypedArray(I);E.sqlite3_result_blob(S,G,I.byteLength,E.SQLITE_WASM_DEALLOC);break}default:N("Don't not how to handle this UDF result value:",typeof I,I)}}catch(G){E.sqlite3_result_error_js(S,G)}},E.sqlite3_column_js=function(S,I,G=!0){let oe=E.sqlite3_column_value(S,I);return oe===0?void 0:E.sqlite3_value_to_js(oe,G)};{let S=function(I,G,oe){if(oe=E[oe],!this.ptr)this.ptr=b.allocPtr();else b.pokePtr(this.ptr,0);let Z=oe(I,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=(I,G)=>S(I,G,"sqlite3_preupdate_new"),E.sqlite3_preupdate_old_js=(I,G)=>S(I,G,"sqlite3_preupdate_old"),E.sqlite3changeset_new_js=(I,G)=>S(I,G,"sqlite3changeset_new"),E.sqlite3changeset_old_js=(I,G)=>S(I,G,"sqlite3changeset_old")}E.sqlite3_js_retry_busy=function(S,I,G){for(let oe=1;oe<=S;++oe)try{if(G&&oe>1)G(oe);let Z=I();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 I=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(!I||!I.length)return S.isReady=G().catch(oe);I=I.map((ge)=>ge instanceof Function?async(we)=>ge(pe):ge),I.push(G);let Z=Promise.resolve(pe);while(I.length)Z=Z.then(I.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 I=(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)I(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)I(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?I(w,se.length):D.convertResult(T,se.call(null));return function(...L){if(L.length!==se.length)I(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 C=(...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||C("Missing 'memory' object!");if(!V.alloc&&b.instance.exports.malloc){let U=b.instance.exports;V.alloc=function(N){return U.malloc(N)||C("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:C}=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)C(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,I=(z)=>z[1]==="(",G=(z)=>z==="p"||z==="P"||z==="s",oe=(z)=>z==="P",Z=(z)=>z?I(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 Ce;while(Ce=ie.ondispose.pop())try{if(Ce instanceof Function)Ce.call(ie);else if(Ce instanceof Pt)Ce.dispose();else if(L(Ce))C(Ce)}catch(Je){console.warn("ondispose() for",z.structName,"@",fe,"threw. NOT propagating it.",Je)}}else if(ie.ondispose instanceof Function)try{ie.ondispose()}catch(Ce){console.warn("ondispose() for",z.structName,"@",fe,"threw. NOT propagating it.",Ce)}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);C(fe)}},be=()=>({configurable:!1,writable:!1,iterable:!1}),xe=(z)=>({...be(),value:z}),Pe=function(ie,fe,Ee){let Ce,Je=(Ge)=>{Y(Ge)||d("Invalid pointer value",arguments[0],"for",ie.structName,"constructor.")};if(arguments.length>=3)if(Ee&&typeof Ee==="object")Ce=Ee,Ee=Ce?.wrap;else Je(Ee),Ce={wrap:Ee};else Ce={};let ht=!Ee,Dt=0,Nt=!1;if(Ee)Je(Ee),Nt=!!Ce?.takeOwnership;else{let Ge=Ce?.extraBytes??0;if(Ge<0||Ge!==(Ge|0))d("Invalid extraBytes value:",Ce?.extraBytes);Dt=ie.structInfo.sizeof+Ge,Ee=b(Dt)||d("Allocation of",ie.structName,"structure failed."),Nt=!0}try{if(Ce?.debugFlags)fe.debugFlags(Ce.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=!!Ce?.zeroOnDispose,Ce?.ondispose&&Ce.ondispose!==Ee)fe.addOnDispose(Ce.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 Ce=Ve(z)[ie];if(arguments.length===3)return Ce[fe];if(Ee)return Ce[fe]=Ee;return delete Ce[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 Ce of Object.values(z.members))if(Ce.key===ie){Ee=Ce;break}if(!Ee&&fe)d(w(z.name||z.structName,ie),"is not a mapped struct member.")}return Ee},Ie=function z(ie,fe,Ee=!1){if(!z._)z._=(Je)=>Je.replace(/[^vipPsjrdcC]/g,"").replace(/[pPscC]/g,"i");let Ce=De(ie.structInfo,fe,!0);return Ee?z._(Ce.signature):Ce.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 Ce=ie[Ee.key];if(!Ce)return null;let Je=Ce,ht=E();for(;ht[Je]!==0;++Je);return Ce===Je?"":Ue(ht,Ce,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 Ce=Lr(fe);return z[Ee.key]=Ce,Xt(z,Ce),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 Ie(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 Ce=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=Ce.get(gt);if(Nt.getter)V("debug.getter: k =",gt);if(!Ne)Ne=new Ee.constructor(J(Ge,Ee.offset)),Ce.set(gt,Ne),this.addOnDispose(()=>Ne.dispose()),Ne.addOnDispose(()=>Ce.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,Co,cl){if(Object.prototype.hasOwnProperty.call(Ne,Co))d(Ne.structName,"already has a property named",Co+".");$e(cl)||d("Malformed signature for",w(Ne.structName,pt)+":",cl)}}let Ce=ie.memberKey(fe);z.sigCheck(ie.prototype,fe,Ce,Ee.signature),Ee.key=Ce,Ee.name=fe;let Je=Z(Ee.signature),ht=w(ie.structName,Ce),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,[Ce,gt]);if(Dt.getter)V("debug.getter:",ht,"result =",gt);return gt},Ee.readOnly)Ge.set=T(ie.prototype.structName,Ce);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,[Ce,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,Ce,Ge)},al=function z(ie,fe,Ee=Object.create(null)){let Ce=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(Ce,{debugFlags:Dt,isA:xe((Ne)=>Ne instanceof Ce),memberKey:Se,memberKeys:Re,structInfo:xe(fe),structName:xe(ie),ptrAdd:xe(J)}),Ce.prototype=new Pt(ie,fe,xe),Object.defineProperties(Ce.prototype,{debugFlags:Dt,constructor:xe(Ce),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 Co=!!pt.autoCalc;if(gt)pt.autoCalcSizeOffset=!0;if(Qy.call(Je,Ce,Ne,pt),Co)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,Ce},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 C=(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],I=[O,pe,0,d.SQLITE_UTF8,0,0,0,0,0];if(Q)I.push(0);for(let G of S)try{I[2]=G,j.apply(null,I)}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 C(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 C(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 C(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 I=R(Q,ee,j,J,pe,S);if(I===0&&pe instanceof Function)q.addCollation(Q,ee);return I}catch(I){return E.sqlite3__wasm_db_error(Q,I)}},d.sqlite3_create_collation=(Q,ee,j,J,pe)=>arguments.length===5?d.sqlite3_create_collation_v2(Q,ee,j,J,pe,0):C(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(I){d.sqlite3_result_error_js(J,I)}}},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(I){d.sqlite3_result_error_js(J,I)}}},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,I,G,oe,Z,ge,we){if(j.length!==arguments.length)return C(J,"sqlite3_create_function_v2",j.length);else if((I&15)===0)I|=d.SQLITE_UTF8;else if(d.SQLITE_UTF8!==(I&15))return V(J);try{let ye=Q(J,pe,S,I,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,I,G,oe,Z,ge){return j.length===arguments.length?d.sqlite3_create_function_v2(J,pe,S,I,G,oe,Z,ge,0):C(J,"sqlite3_create_function",j.length)},ee)d.sqlite3_create_window_function=function j(J,pe,S,I,G,oe,Z,ge,we,ye){if(j.length!==arguments.length)return C(J,"sqlite3_create_window_function",j.length);else if((I&15)===0)I|=d.SQLITE_UTF8;else if(d.SQLITE_UTF8!==(I&15))return V(J);try{let ve=ee(J,pe,S,I,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,I){if(Q.length!==arguments.length)return C(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,I);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):C(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 C(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 I,G;try{if(E.isSQLableTypedArray(J))I=h.allocFromTypedArray(J),G=J.byteLength;else if(typeof J==="string")[I,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,I,G,d.SQLITE_WASM_DEALLOC)}catch(oe){return h.dealloc(I),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 C(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 I,G;try{if(E.isBindableTypedArray(J))I=h.allocFromTypedArray(J),G=pe>=0?pe:J.byteLength;else if(typeof J==="string")[I,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,I,G,d.SQLITE_WASM_DEALLOC)}catch(oe){return h.dealloc(I),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),I=h.exports.sqlite3_column_text(pe,S);return I?ee(I,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(I,G)=>O(R,I,G,j);if(!O.argcProxy)O.argcProxy=function(I,G,oe,Z){return function(...ge){if(oe.length!==arguments.length)l("Argument mismatch for",I.structInfo.name+"::"+G+": Native signature is:",Z);return oe.apply(this,ge)}},O.removeFuncList=function(){if(this.ondispose.__removeFuncList)this.ondispose.__removeFuncList.forEach((I,G)=>{if(h.isPtr(I))try{h.uninstallFunction(I)}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 I=h.installFunction(S,J);if(R[pe]=I,!R.ondispose||!R.ondispose.__removeFuncList)R.addOnDispose("ondispose.__removeFuncList handler",O.removeFuncList),R.ondispose.__removeFuncList=[];R.ondispose.__removeFuncList.push(pe,I)}return(I,G)=>O(R,I,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 C=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(C.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],C.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){}}),C.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 I=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(I(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],C.delete(this),ge.delete(this),we.delete(this),delete this.parameterCount,delete this.db,g}},clearBindings:function(){return ye(I(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(I(this).pointer);return we.delete(this),q(this.db,g),this},bind:function(){I(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(I(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(I(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(I(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(I(this),M).pointer,M)},getColumnNames:function(M=[]){j(I(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 I(this).parameterCount?d.sqlite3_bind_parameter_index(this.pointer,M):void 0},getParamName:function(M){return I(this).parameterCount?d.sqlite3_bind_parameter_name(this.pointer,M):void 0},isBusy:function(){return d.sqlite3_stmt_busy(I(this))!==0},isReadOnly:function(){return d.sqlite3_stmt_readonly(I(this))!==0}};{let M={enumerable:!0,get:function(){return C.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=C.idMap.get(W);if(K)return K;return K="db#"+ ++C.idSeq+":"+Math.floor(Math.random()*1e8)+":"+Math.floor(Math.random()*1e8),C.idMap.set(W,K),K},C={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=C.dbList[0]){return W&&W.pointer?W:d("DB is not opened.")},U=function(W,K=!0){let ue=C.getDb(W.dbId,!1)||C.dbList[0];return K?V(ue):ue},N=function(){return C.dbList[0]&&b(C.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=C.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;C.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=C.xfer;let O=K.callback,R=0,Q=!!K.columnNames;if(typeof O==="string"){if(!Q)K.columnNames=[];K.callback=function(ee,j){C.post({type:O,columnNames:K.columnNames,rowNumber:++R,row:ee},C.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,C.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 C.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();C.post({type:O,dbId:ue,messageId:W.messageId,workerReceivedTime:R,workerRespondTime:performance.now(),departureTime:W.departureTime,result:K},C.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 C=d.sqlite3_vfs_register(this,b?1:0);if(C)h("sqlite3_vfs_register(",this,") failed with rc",C);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 C=0,V=["io","vfs"];for(let U of V){let N=b[U];if(N){if(++C,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(!C)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 C=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=C(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,I){try{return Q(...arguments)||0}catch(G){if(!(G instanceof f.WasmAllocError))l.dealloc(l.peekPtr(I)),l.pokePtr(I,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:C}=f,V=b.toss3,U=new d(C.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:C.allocCString("jrnl"),zKeySz:C.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]??=C.alloc(N.buffer.n),N.memBufferFree=(B)=>{let re=N.buffer.pool[B];if(re)C.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,I=".";if(N.storagePool=Object.assign(Object.create(null),{[I]:j(I)}),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=C.exports.sqlite3__wasm_kvvfs_decode,ge=C.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,Ie;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]],Ie?.[ae[0]]){Le.data[1]=Ie[ae[0]];continue}de??=new TextEncoder("utf-8"),Se??=N.memBuffer(10),De??=N.memBuffer(11);let tt=de.encode(ae[1]),Ue=C.heap8u();Ue.set(tt,Number(Se)),Ue[C.ptr.addn(Se,tt.length)]=0;let vt=Z(Se,De,N.buffer.n);if(vt>0)Ie??=Object.create(null),Ie[ae[0]]=Le.data[1]=Ue.slice(Number(De),C.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[C.cstrToJs(B)],ve=C.exports.sqlite3__wasm_kvvfsMakeKey,M=(B,re,ae)=>re&&B.keyPrefix?ve(re,ae):ae,g=(B,re,ae)=>C.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=C.cstrToJs(B),De=ye(Se);if(!De)return-1;let Ie=g(De,B,re);J?.log?.xRcrdRead&&K("xRcrdRead",Se,Ie,de,De);let Re=De.storage.getItem(Ie);if(Re===null)return-1;let Le=Re.length;if(de<=0)return Le;else if(de===1)return C.poke(ae,0),Le;if(de+1<Le)V(l.SQLITE_RANGE,"xRcrdRead()",Se,Ie,"input buffer is too small: need",Le,"but have",de);let Ke=N.memBuffer(0),tt=C.heap8(),Ue;for(Ue=0;Ue<Le;++Ue)tt[C.ptr.add(Ke,Ue)]=Re.codePointAt(Ue)&255;return tt.copyWithin(Number(ae),Number(Ke),C.ptr.addn(Ke,Ue)),tt[C.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=C.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=C.allocCString(""+ae+"."+(Math.random()*1e5|0)),re=De;let Ie=C.cstrToJs(re);if(J?.log?.xOpen&&W("xOpen",Ie,"flags =",de),ee(Ie,!0),de&(l.SQLITE_OPEN_MAIN_DB|l.SQLITE_OPEN_TEMP_DB|l.SQLITE_OPEN_TRANSIENT_DB)&&N.rxJournalSuffix.test(Ie))V(l.SQLITE_ERROR,"DB files may not have a '-journal' suffix.");let Re=ye(Ie);if(!Re&&!(de&l.SQLITE_OPEN_CREATE))V(l.SQLITE_ERROR,"Storage not found:",Ie);let Le=P.vfs.xOpen(B,re,ae,de,Se);if(Le)return Le;let Ke=!!(l.SQLITE_OPEN_DELETEONCLOSE&de);if(C.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),C.poke32(Se,de);else{C.poke32(Se,de|l.SQLITE_OPEN_CREATE),b.assert(!tt.$isJournal,"Opening a journal before its db? "+Ie);let Ue=Ie.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:Ie}),Re.listeners&&we("open",Re,Re.files.length),0}catch(Ie){return K("xOpen:",Ie),N.setError(Ie)}finally{De&&C.dealloc(De)}},xDelete:function(B,re,ae){N.popError();try{let de=C.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||C.cstrToJs(re);if(J?.log?.xAccess)W("xAccess",De,"flags =",ae,"*pResOut =",C.peek32(de),"store =",Se);if(!Se)try{ee(De)}catch(Ie){return C.poke32(de,0),0}if(Se){let Ie=Se.keyPrefix+(N.rxJournalSuffix.test(De)?"jrnl":"1"),Re=Se.storage.getItem(Ie)?0:1;C.poke32(de,Re)}else C.poke32(de,0);return 0}catch(Se){return ue("xAccess",Se),N.setError(Se)}},xRandomness:function(B,re,ae){let de=C.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=C.scopedAllocPush();try{let[De,Ie]=C.scopedAllocCString(de.message,!0);if(C.cstrncpy(ae,De,re),Ie>re)C.poke8(C.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{C.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=C.peekPtr(C.ptr.add(ae,C.ptr.size));if(C.cstrToJs(De)==="page_size"){J?.log?.xFileControl&&W("xFileControl pragma",C.cstrToJs(De));let Ie=C.peekPtr(C.ptr.add(ae,2*C.ptr.size));if(Ie)return J?.log?.xFileControl&&K("xFileControl pragma",de,"NOT setting page size to",C.cstrToJs(Ie)),de.file.$szPage=-1,0;else if(de.file.$szPage>0)return J?.log?.xFileControl&&K("xFileControl",de,"getting page size",de.file.$szPage),C.pokePtr(ae,C.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)]=C.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]=C.functionEntry(te[de]),te[de]=C.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]=C.functionEntry(se[de])||b.toss("Missing native pIoDb[",de,"]"),se[de]=C.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]=C.functionEntry(D[de])||b.toss("Missing native pIoJrnl[",de,"]"),ae===!0)D[de]=se[de]||b.toss("Missing copied pIoDb[",de,"]");else D[de]=C.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,Ie=de.length;for(De=0;De<Ie;++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 Ie=de.key(Se);if(!ae.keyPrefix||Ie.startsWith(ae.keyPrefix))De+=Ie.length,De+=de.getItem(Ie).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:[]}),Ie=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=C.heap8u(),Pt=0;for(;Pt<un;++Pt)Un[C.ptr.add(Xt,Pt)]=Zt.codePointAt(Pt)&255;Un[C.ptr.add(Xt,Pt)]=0;let Oo=Z(Xt,Lr,N.buffer.n);Ie[vt]=Un.slice(Number(Lr),C.ptr.addn(Lr,Oo))}else Ie[vt]=Se.getItem(Ue);break}}}if(ae.decodePages)N.memBufferFree(1);return Object.keys(Ie).map((Ue)=>+Ue).sort().forEach((Ue)=>De.pages.push(Ie[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 Ie=ae.storage;if(Ie.setItem(Se+"sz",B.size),B.journal)Ie.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=C.heap8u();Ue.set(Re,Number(tt)),Ue[C.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(C.peek8(C.ptr.add(De,vt))===0,"Expecting NUL-terminated encoded output");let Zt=C.cstrToJs(De);Ie.setItem(Se+(Le+1),Zt)});else if(B.pages[0])B.pages.forEach((Re,Le)=>Ie.setItem(Se+(Le+1),Re));if(de)S(ae)}catch{if(!de)try{be(B.name)}catch(Ie){}}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":I;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((Ie,Re)=>B[Ie].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((Ie)=>!N.rxJournalSuffix.test(Ie))});let de=function(Ie,Re){let Le=Ie instanceof l.sqlite3_vtab_cursor?Ie:re.xCursor.get(Ie);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 Ie(){return Ie.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(C.peekPtr(Ue)),"output pointer check failed")}return un}catch(Zt){return re.xError("xConnect",Zt,l.SQLITE_ERROR)}},xCreate:C.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(Ie,Re="sqlite_kvvfs"){return l.sqlite3_create_module(Ie,Re,De(),C.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((C)=>(h.rootDirectory=C,C)).catch((C)=>{throw delete b.promise,C})},h.getResolvedPath=function(b,C){let V=new URL(b,"file://irrelevant").pathname;return C?V.split("/").filter((U)=>!!U):V},h.getDirForFilename=async function(C,V=!1){let U=h.getResolvedPath(C,!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(C){return!1}},h.entryExists=async function(b){try{let[C,V]=await h.getDirForFilename(b);return await C.getFileHandle(V),!0}catch(C){return!1}},h.randomFilename=function b(C=16){if(!b._chars)b._chars="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012346789",b._n=b._chars.length;let V=[],U=0;for(;U<C;++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)},C=Object.create(null);return await b(await h.getRootDir(),C),C},h.rmfr=async function(){let b=await h.getRootDir(),C={recurse:!0};for await(let V of b.values())b.removeEntry(V.name,C)},h.unlink=async function(b,C=!1,V=!1){try{let[U,N]=await h.getDirForFilename(b,!1);return await U.removeEntry(N,{recursive:C}),!0}catch(U){if(V)throw Error("unlink(",arguments[0],") failed: "+U.message,{cause:U});return!1}},h.traverse=async function(b){let C={recursive:!0,directory:await h.getRootDir()};if(typeof b==="function")b={callback:b};b=Object.assign(C,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,C){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 C())!==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,C){if(C instanceof Function)return E(b,C);if(C instanceof ArrayBuffer)C=new Uint8Array(C);d.affirmIsDb(C);let V=C.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(C,{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(C,V){let U=new URL(globalThis.location.href).searchParams;if(U.has(C+"-disable"))return;try{h.vfsInstallationFeatureCheck(C)}catch(N){return}if(V=d.nu(V),V.vfsName=C,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(),C=h.options;b.verbose=C.verbose;let V=[f.config.error,f.config.warn,f.config.log],U=C.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,I=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=I[Z];if(we){if(delete I[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=I[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=I[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(I[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,C=d.createVfsState().vfs,V=C.metrics.counters,{mTimeStart:U,mTimeEnd:N,opRun:q,__openFiles:W}=C;return C.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(C.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:C}=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}),I=[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(),C.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 C.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(C.heap8u().subarray(Number(L),Number(L)+Y),{at:O+Number(ne)});if(Pe<Y)return C.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(C.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);C.poke32(ne,be.hasFilename(xe)?1:0)}catch(xe){C.poke32(ne,0)}return 0},xCurrentTime:function(D,L){return C.poke(L,2440587.5+new Date().getTime()/86400000,"double"),0},xCurrentTimeInt64:function(D,L){return C.poke(L,210866760000000+new Date().getTime(),"i64"),0},xDelete:function(D,L,Y){let ne=Z(D);ne.log(`xDelete ${C.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 C.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=C.scopedAllocPush();try{let[Pe,$e]=C.scopedAllocCString(be.message,!0);if(C.cstrncpy(Y,Pe,L),$e>L)C.poke8(C.ptr.add(Y,L,-1),0)}catch(Pe){return E.SQLITE_NOMEM}finally{C.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 ${C.cstrToJs(Y)} ${be}`);let $e=Y&&C.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(),C.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=C.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=C.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)I[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(C.isPtr(D))D=C.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 C=d.createVfsState().vfs;C.metrics.counters;let{mTimeStart:V,mTimeEnd:U,opRun:N,__openFiles:q}=C;return C.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((C)=>{b.config.warn("Ignoring inability to install the",h,"sqlite3_vfs:",C)}))});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",查看全文:"Read more","查看「{name}」全文":"Read full {name}",复制全文:"Copy full text","复制「{name}」全文":"Copy full {name}",计数:"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 Cu={"Logo 外观":"Logo appearance","当前 Logo":"Current logo",配色:"Color",彩色:"Multicolor",蓝色:"Blue",底色:"Background",浅底:"Light",深底:"Dark",浅色:"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”.
546
+ `)}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=Su(await Bb(this.body||""))}return e}}async function $i(e,t){let r=await crypto.subtle.importKey("raw",typeof e==="string"?ku.encode(e):e,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return crypto.subtle.sign("HMAC",r,ku.encode(t))}async function Bb(e){return crypto.subtle.digest("SHA-256",typeof e==="string"?ku.encode(e):e)}function Su(e){let t=new Uint8Array(e),r="";for(let n=0;n<t.length;n++){let o=t[n];r+=jb[o>>>4&15],r+=jb[o&15]}return r}function Hb(e){return e.replace(/[!'()*]/g,(t)=>"%"+t.charCodeAt(0).toString(16).toUpperCase())}function AR(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)?$/),i=o&&o[1]||"",s=o&&o[2];if(s==="us-gov")s="us-gov-west-1";else if(s==="s3"||s==="s3-accelerate")s="us-east-1",i="s3";else if(i==="iot")if(r.startsWith("iot."))i="execute-api";else if(r.startsWith("data.jobs.iot."))i="iot-jobs-data";else i=n==="/mqtt"?"iotdevicegateway":"iotdata";else if(i==="autoscaling"){let c=(t.get("X-Amz-Target")||"").split(".")[0];if(c==="AnyScaleFrontendService")i="application-autoscaling";else if(c==="AnyScaleScalingPlannerFrontendService")i="autoscaling-plans"}else if(s==null&&i.startsWith("s3-"))s=i.slice(3).replace(/^fips-|^external-1/,""),i="s3";else if(i.endsWith("-fips"))i=i.slice(0,-5);else if(s&&/-\d$/.test(i)&&!/-\d$/.test(s))[i,s]=[s,i];return[TR[i]||i,s||""]}var ku,TR,DR,jb;var Vb=Oe(()=>{ku=new TextEncoder,TR={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"},DR=new Set(["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"]);jb=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"]});function Ru(e){return new xu({accessKeyId:e.accessKeyId,secretAccessKey:e.secretAccessKey,region:e.region||"auto",service:"s3"})}function Tu(e){let t=new URL(e.endpoint).hostname;if(/^(?:[a-z0-9-]+\.)?cos(?:-internal)?\.[a-z0-9-]+\.myqcloud\.com$/i.test(t))return"cos";if(e.provider==="cos")throw new T("invalid_input","Tencent COS conditional writes require a supported official COS endpoint; custom-domain capabilities cannot be verified");return"s3"}function Du(e){let t=new URL(e.endpoint).origin;return Pm(e)?t:`${t}/${e.bucket}`}function Au(e,t){return`${Du(e)}/${t.split("/").map(encodeURIComponent).join("/")}`}async function Mi(e,t,r){let n=Ru(e),o=new URL(Au(e,t));return o.searchParams.set("X-Amz-Expires",String(Math.min(Math.max(1,Math.floor(r)),Uo))),(await n.sign(o.toString(),{method:"GET",aws:{signQuery:!0}})).url}var Uo=604800;var Da=Oe(()=>{Vb();Ke();Pr()});function JR(e,t){let r=e.query("SELECT value FROM meta WHERE key = ?").get(t);return r?r.value:null}function Iu(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 Aa(e){let t=JR(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,Iu(e,"edge_config",JSON.stringify(r));if(!Array.isArray(r.capabilities))r.capabilities=r.cf?["inbox","room"]:["inbox"],Iu(e,"edge_config",JSON.stringify(r));return r}catch{return null}}function Nu(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;Iu(e,"edge_config",r?JSON.stringify(r):null)}function Fi(e){return e.capabilities??(e.cf?["inbox","room"]:["inbox"])}var xn="3";async function dw(e){return Gn(new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(e))))}async function pw(e){let t=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return Gn(new Uint8Array(t).slice(0,16))}function fw(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`,i=Date.parse(o);return Number.isFinite(i)?i+n*1000:null}catch{return null}}function hw(e,t){return`${e.replace(/\/+$/,"")}/#m=${encodeURIComponent(t.manifestUrl)}&${t.keyB64?`k=${t.keyB64}`:`s=${t.saltB64}`}`}var gw=Oe(()=>{rn()});function QR(e,t){return`${e.prefix.replace(/^\/+|\/+$/g,"")?`${e.prefix.replace(/^\/+|\/+$/g,"")}/`:""}shares/${t}/links/`}function _w(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 mw(e,t){let r=e.encrypt&&e.masterKey?await kr(Nt(e.masterKey),t):t,n=JSON.parse(new TextDecoder().decode(r));if(n.v!==1||!/^[A-Za-z0-9_-]{43}$/.test(n.token)||_w(n.base)!==n.base)throw Error("invalid short-link control");return n}async function eT(e,t,r){let n=$t(e),o=`${QR(e,t)}${await dw(r)}.json`,i=await n.get(o);if(i){let u=await mw(e,i);if(u.base!==r)throw Error("viewer mismatch");return u}let s={v:1,base:r,token:Gn(mi())},c=new TextEncoder().encode(JSON.stringify(s)),l=e.encrypt&&e.masterKey?await pr(Nt(e.masterKey),c):c;try{await n.put(o,l,{ifNoneMatch:!0,contentType:"application/octet-stream"})}catch(u){let f=await n.get(o);if(!f)throw u;let _=await mw(e,f);if(_.base!==r)throw Error("viewer mismatch");return _}return s}function Pu(e,t={}){return fetch(e,{...t,redirect:"error",credentials:"omit",cache:"no-store",signal:AbortSignal.timeout(YR)})}async function yw(e,t,r,n){let o=hw(r,n);try{let i=_w(r),s=Math.min(n.presignExp,fw(n.manifestUrl)??0);if(s<=Date.now())return o;let c=await Pu(`${i}/api/links`);if(!c.ok||(await c.json()).service!=="metahub-share-links")throw Error("static viewer");let l=await eT(e,t,i),u=await pw(l.token),f=`${i}/api/links/${u}`,_=`Bearer ${l.token}`,E={v:1,manifestUrl:n.manifestUrl,expiresAt:s,...n.saltB64?{salt:Gn(Nt(n.saltB64))}:{}},g=await Pu(f,{headers:{authorization:_}});if(!g.ok&&g.status!==404)throw Error("short-link lookup failed");let A=g.headers.get("etag");if(g.ok&&!A)throw Error("not a short-link API");let L=await Pu(f,{method:"PUT",headers:{authorization:_,"content-type":"application/json",...g.ok?{"if-match":A}:{"if-none-match":"*"}},body:JSON.stringify(E)});if(!L.ok||!L.headers.get("etag")||(await L.json()).ok!==!0)throw Error("short-link registration failed");return`${i}/s/${u}${n.keyB64?`#k=${Gn(Nt(n.keyB64))}`:""}`}catch{return console.warn("share: short-link service unavailable; using the original long link"),o}}var YR=8000;var qu=Oe(()=>{rn();Pr();gw()});function zi(e){let t=(e||"").replace(/^\/+|\/+$/g,"");return t?`${t}/shares`:"shares"}function bw(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 Ew(e,t){let r=new TextEncoder().encode(JSON.stringify(t));return e.encrypt&&e.masterKey?pr(Nt(e.masterKey),r):Promise.resolve(r)}async function $u(e,t){let n=await $t(e).get(Lu(zi(e.prefix),t)).catch(()=>null);if(!n)return null;try{let o=e.encrypt&&e.masterKey?await kr(Nt(e.masterKey),n):n;return JSON.parse(new TextDecoder().decode(o))}catch{return null}}async function tT(e,t){let r=$t(t.config),n=zi(t.config.prefix),o={v:1,kind:t.kind,title:""},i=[];if(t.kind==="doc"){let u=nt(e,t.targetId);if(!u)throw new T("not_found",`no such document: ${t.targetId}`);o.title=u.title,o.body=u.body??"",i=bw(o.body)}else{let u=or(e,t.targetId);if(!u)throw new T("not_found",`no such database: ${t.targetId}`);o.title=u.name;let f=Mt(e,t.targetId).sort((E,g)=>E.position-g.position);o.properties=f.map((E)=>({id:E.id,name:E.name,type:E.type}));let _=Co(e,t.targetId);o.records=_.map((E)=>({cells:E.cells})),i=bw(JSON.stringify(_.map((E)=>E.cells)))}let s=[],c={};if(i.length>0&&!F_())throw new T("network","no blob-bytes resolver is registered for this runtime");for(let u of i){let f=await M_(e,u);if(!f)continue;let _=vw(n,t.slug,u);await r.put(_,await pr(t.shareKey,f),{contentType:"application/octet-stream"}),s.push(_),c[u]={url:await Mi(t.config,_,t.expiresSec),ct:j_(e,u)??"application/octet-stream"}}if(Object.keys(c).length)o.blobs=c;let l=ww(n,t.slug);return await r.put(l,await pr(t.shareKey,new TextEncoder().encode(JSON.stringify(o))),{contentType:"application/octet-stream"}),s.push(l),{manifestUrl:await Mi(t.config,l,t.expiresSec),objects:s,title:o.title}}async function Sw(e,t,r,n=Uo){let o=await $u(t,r);if(!o)throw new T("not_found",`no such bucket share: ${r}`);if(o.revoking)throw new T("conflict","share revocation is pending; retry revocation instead");let i=Nt(o.key),s=xw(n),{manifestUrl:c,objects:l,title:u}=await tT(e,{slug:r,kind:o.kind,targetId:o.target_id,config:t,shareKey:i,expiresSec:s}),f=Date.now()+s*1000,_={...o,title:u,presign_exp:f,objects:l,content_updated_at:Date.now()};return await $t(t).put(Lu(zi(t.prefix),r),await Ew(t,_),{contentType:"application/octet-stream"}),{manifestUrl:c,presignExp:f,keyB64:o.has_password?void 0:o.key,saltB64:o.salt,title:u}}async function rT(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 kw(e,t,r=Uo){let n=await $u(e,t);if(!n)throw new T("not_found",`no such bucket share: ${t}`);if(n.revoking)throw new T("conflict","share revocation is pending; retry revocation instead");let o=$t(e),i=zi(e.prefix),s=Nt(n.key),c=xw(r),l=ww(i,t),u=await o.get(l).catch(()=>null);if(!u)throw new T("not_found",`bucket share ${t} has no manifest`);let f=JSON.parse(new TextDecoder().decode(await kr(s,u))),_=await rT(f,(g)=>Mi(e,vw(i,t,g),c));await o.put(l,await pr(s,new TextEncoder().encode(JSON.stringify(_))),{contentType:"application/octet-stream"});let E=Date.now()+c*1000;return await o.put(Lu(i,t),await Ew(e,{...n,presign_exp:E}),{contentType:"application/octet-stream"}),{manifestUrl:await Mi(e,l,c),presignExp:E,keyB64:n.has_password?void 0:n.key,saltB64:n.salt,title:n.title}}async function Mu(e){let t=$t(e),r=zi(e.prefix),o=(await t.list(`${r}/`,void 0,"/")).map((s)=>s.key.slice(`${r}/`.length).replace(/\/$/,"")).filter((s)=>s&&!s.includes("/")),i=[];for(let s of o){let c=await $u(e,s);if(c)i.push(c)}return i}function xw(e){return Math.min(Math.max(60,Math.floor(e)),Uo)}var Lu=(e,t)=>`${e}/${t}/meta.json`,ww=(e,t)=>`${e}/${t}/manifest.bin`,vw=(e,t,r)=>`${e}/${t}/blobs/${r}`;var Fu=Oe(()=>{er();Ke();on();Jn();sn();Xn();Ti();Pr();Da();qu();rn()});function nT(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 oT(e){let t=zu.get(e);if(!t)t=new Map,zu.set(e,t);return t}function iT(e,t){let r=oT(e),n=r.get(t);if(!n)n={items:[],fetchedAt:0,error:null,inflight:null},r.set(t,n);return n}function Rw(e,t,r){let n=iT(e,t);n.items=[...n.items.filter((o)=>o.slug!==r.slug),r]}function Tw(e,t){let r=zu.get(e);if(!r)return null;for(let n of nT(e)){if(n.kind!=="bucket")continue;let o=r.get(n.url)?.items.find((i)=>i.slug===t);if(o)return{source:n,item:o}}return null}var zu;var Dw=Oe(()=>{eo();Fu();zu=new WeakMap});function aT(e,t){if(t)return t.replace(/\/+$/,"");return(e.query("SELECT value FROM meta WHERE key='cfg_share_viewer_url'").get()?.value||sT).replace(/\/+$/,"")}async function cT(e,t){let r=Tw(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 i=(await Mu(JSON.parse(n.config)).catch(()=>[])).find((s)=>s.slug===t);if(i)return{peer:n,kind:i.kind,item:null}}return null}async function Aw(e,t,r,n){let o=await cT(e,t);if(!o)throw new T("not_found",`no such object-storage share: ${t}`);let{peer:i}=o,s=JSON.parse(i.config),c=aT(e,r),l=n?.refreshContent?await Sw(e,s,t):await kw(s,t);if(o.item)Rw(e,i.url,{...o.item,title:l.title||o.item.title,expiresAt:l.presignExp,...n?.refreshContent?{contentUpdatedAt:Date.now()}:{}});return{slug:t,kind:o.kind,permission:"view",transport:"s3",hosting:"s3",url:await yw(s,t,c,l),expiresAt:l.presignExp,source:`桶 ${i.label??i.url}`}}var sT="https://share.mh.tensorix.org",w$;var Ow=Oe(()=>{Wn();Ke();Vt();Js();No();on();Jn();eo();Io();Fu();Da();qu();Dw();qi();w$=_t({slug:Be().min(1).max(128),kind:xs(["doc","database","site"]),permission:xs(["view","edit"]),transport:Ut("server"),hosting:xs(["server","room"]),url:Be().url(),expiresAt:Dt().nullable(),source:Be()})});Ke();eo();fi();on();function Oy(e,t,r,n){if(!nt(t,r))return!1;let o=n.filter((c)=>c.dataset==="doc_blocks"&&!!e.query("SELECT 1 FROM doc_blocks WHERE id=? AND doc_id=?").get(c.row_id,r));if(!o.length||o.some((c)=>c.col!=="text"))return!1;if(n.some((c)=>c.dataset==="documents"&&c.row_id===r&&!["body","updated_at"].includes(c.col)))return!1;let i=new Map;for(let c of o)i.set(c.row_id,[...i.get(c.row_id)??[],c]);let s=[];for(let[c,l]of i){l.sort((A,L)=>A.hlc.localeCompare(L.hlc));let u=l[0],f=l.at(-1);if(!t.query("SELECT 1 FROM doc_blocks WHERE id=? AND doc_id=? AND __deleted=0").get(c,r))return!1;let _=t.query("SELECT hlc,value FROM crdt_changes WHERE dataset='doc_blocks' AND row_id=? AND col='text' ORDER BY hlc DESC LIMIT 1").get(c);if(_?.value===f.value)continue;let E=e.query("SELECT value FROM meta WHERE key=?").get(`sync_v2_base:${u.hlc}:doc_blocks:${c}:text`);if(!E||!_||_.hlc!==JSON.parse(E.value))return!1;let g=f.value===null?null:JSON.parse(f.value);if(typeof g!=="string"||!g)return!1;s.push({type:"update",id:c,text:g})}if(s.length)qs(t,r,s,{ifMatch:At(t,r)});return!0}ho();er();yn();it();Zt();As();vn();Pr();Ls();js();Kt();on();Ke();ko();function tu(e){e.exec(`CREATE TABLE IF NOT EXISTS sync_recovery_items (
547
+ id TEXT PRIMARY KEY, kind TEXT NOT NULL, target TEXT NOT NULL, local TEXT NOT NULL,
548
+ remote TEXT, status TEXT NOT NULL DEFAULT 'pending', result TEXT);
549
+ CREATE TABLE IF NOT EXISTS sync_recovery_packages (id TEXT PRIMARY KEY, proof TEXT NOT NULL, status TEXT NOT NULL DEFAULT 'pending');`)}function Cy(e,t){if(t.kind!=="block"||!t.remote)return t;let r=JSON.parse(t.local),n=JSON.parse(t.remote);if(r.recoveryVersion||r.title!=="段落编辑冲突")return t;let o=e.query("SELECT hlc,value FROM crdt_changes WHERE dataset='doc_blocks' AND row_id=? AND col='text'").all(t.target),i=o.find((c)=>t.id.endsWith(`:${c.hlc}:${t.target}:text`)&&JSON.parse(c.value??'""')===r.body),s=o.filter((c)=>JSON.parse(c.value??'""')===n.body);if(i&&s.length){if(s.every((c)=>c.hlc<i.hlc))return{...t,local:JSON.stringify({...r,body:n.body}),remote:JSON.stringify({body:r.body})};if(s.every((c)=>c.hlc>i.hlc))return t}return{...t,local:JSON.stringify({...r,body:`版本一
550
+ ${r.body}
551
+
552
+ 版本二
553
+ ${n.body}`})}}function Iy(e,t){if(!t.length)return!1;let r=new Map,{dataset:n,row_id:o}=t[0];for(let c of t){if(c.dataset!==n||c.row_id!==o)return!1;let l=r.get(c.col);if(l?.hlc===c.hlc&&l.value!==c.value)return!1;if(!l||l.hlc<c.hlc)r.set(c.col,c)}let i=e.query("SELECT value FROM crdt_changes WHERE dataset=? AND row_id=? AND col=? ORDER BY hlc DESC LIMIT 1"),s=(c)=>i.get(n,o,c)?.value;if(s("__deleted")==="1"&&r.get("__deleted")?.value!=="1")return!1;return[...r.values()].every((c)=>s(c.col)===c.value)}function ru(e){return tu(e),Ve(e,()=>e.query("SELECT * FROM sync_recovery_items WHERE status='pending' ORDER BY id").all().filter((r)=>{if(r.kind!=="entity")return!0;let n;try{n=JSON.parse(r.local)}catch{return!0}let o=Br.array().safeParse(n?.changes);if(!o.success||!Iy(e,o.data))return!0;return e.query("UPDATE sync_recovery_items SET status='matched' WHERE id=? AND status='pending'").run(r.id),!1}).map((r)=>Cy(e,r)))}function Ny(e,t,r){return Qt(e),tu(e),Ve(e,()=>{let n=e.query("SELECT * FROM sync_recovery_items WHERE id=?").get(t);if(!n)throw new T("not_found","recovery item not found");if(n.status!=="pending")return n.result;let o=null;if(r==="copy"){let i=JSON.parse(Cy(e,n).local);o=_i(e,{title:`${i.title??n.target} · 恢复副本`,body:typeof i.body==="string"?i.body:`\`\`\`json
554
+ ${JSON.stringify(i,null,2)}
555
+ \`\`\``}).id}return e.query("UPDATE sync_recovery_items SET status=?,result=? WHERE id=?").run(r==="copy"?"restored":"discarded",o,t),o})}async function Py(e,t,r,n,o){let i=Bt(t,r,e),s=await i.root();if(s)await i.log(s).read();let c=crypto.randomUUID(),l=null,u=!1,f=(_)=>o.phase?.(_);f("saving");try{await o.pauseAndFlush(),f("protecting");let _=await o.protect(c);if(!_.proof)throw new T("invalid_input","recovery protection was not verified");let E=Bt(t,r,e),g=await E.root(),A=at(e);if(!g&&A)throw new T("busy","workspace root is unavailable");if(!g&&o.legacyPeerUrl)try{let De=await Vs(e,o.legacyPeerUrl,t,r,{forcePush:!0});if(De.pendingPull||De.pendingPush||De.warnings?.length)throw new T("busy","请先完成旧版同步,再升级工作区")}catch(De){if(!(De instanceof T)||De.code!=="upgrade_required")throw De;if(g=await E.root(),!g)throw De}if(!g){let De=bi(e,n,0);for(let Xe of e.query("SELECT id FROM documents ORDER BY id").all()){let tt=zs(e,n,Xe.id);for(let kt of Bs(tt))De.history.push({documentId:Xe.id,hash:await E.publish(kt)})}g=await E.initialize(De)}if(A&&A.workspaceId!==g.workspaceId)throw new T("invalid_input","recovery cannot switch workspace identities");f("downloading");let L=E.log(g),F=await L.read(),X=await E.checkpointFor(g,F.state.checkpoint,F.state.epoch);l=await o.createShadow(c),Em(l,X,g.workspaceId),In(l,g.workspaceId,F.state.dataVersion),await L.read(void 0,async(De,Xe,tt)=>{if(tt||De.sequence<=X.coveredSequence||De.payload.type!=="batch")return;let kt=await E.batchFor(g,De.payload),Gr=Eo(l,kt);if(fo(l,kt.changes,Xe.serverTime),Gr.poisoned||Object.values(Gr.skewed).some((qt)=>qt>0))throw new T("clock_skew","recovery rejected remote data")}),f("verifying"),tu(l);let te=e.query("SELECT value FROM meta WHERE key='sync_v2_retention_review'").get();if(te)try{if(JSON.parse(te.value).workspaceId===g.workspaceId)l.query("INSERT OR REPLACE INTO meta(key,value) VALUES('sync_v2_retention_review',?)").run(te.value)}catch{}if(e.query("SELECT 1 FROM sqlite_master WHERE type='table' AND name='sync_recovery_items'").get())for(let De of e.query("SELECT * FROM sync_recovery_items").all())l.query("INSERT OR REPLACE INTO sync_recovery_items(id,kind,target,local,remote,status,result) VALUES(?,?,?,?,?,?,?)").run(De.id,De.kind,De.target,De.local,De.remote,De.status,De.result);if(e.query("SELECT 1 FROM sqlite_master WHERE type='table' AND name='sync_recovery_packages'").get())for(let De of e.query("SELECT * FROM sync_recovery_packages").all())l.query("INSERT OR IGNORE INTO sync_recovery_packages(id,proof,status) VALUES(?,?,?)").run(De.id,De.proof,De.status);Ds(l,{protocolVersion:2,workspaceId:g.workspaceId,epoch:F.state.epoch,checkpoint:F.state.checkpoint,incarnationId:crypto.randomUUID()}),l.query("INSERT INTO sync_recovery_packages(id,proof) VALUES(?,?)").run(c,_.proof);let ce=A?e.query("SELECT value FROM meta WHERE key=?").get(`sync_v2_transport:${A.incarnationId}`):null,de=[...Lt(e,ce?JSON.parse(ce.value).cursor:0,{onlyNode:Je(e)}).changes,...Zn(e)],Ce=new Set(de.filter((De)=>De.dataset==="documents").map((De)=>De.row_id));for(let De of de)if(De.dataset==="doc_blocks"){let Xe=e.query("SELECT doc_id FROM doc_blocks WHERE id=?").get(De.row_id);if(Xe?.doc_id)Ce.add(Xe.doc_id)}let ge=e.query("SELECT id FROM documents WHERE __deleted=0 ORDER BY id").all().filter((De)=>!ce||Ce.has(De.id)),Pe=new Map;for(let De of de){if(De.dataset==="doc_blocks"||De.dataset==="documents"&&ge.some((tt)=>tt.id===De.row_id))continue;let Xe=JSON.stringify([De.dataset,De.row_id]);Pe.set(Xe,[...Pe.get(Xe)??[],De])}for(let[De,Xe]of Pe){if(Iy(l,Xe))continue;let tt=await nr(new TextEncoder().encode(JSON.stringify([g.workspaceId,De,Xe])));l.query("INSERT OR IGNORE INTO sync_recovery_items(id,kind,target,local,remote) VALUES(?,?,?,?,NULL)").run(tt,"entity",De,JSON.stringify({title:"未提交的数据编辑",changes:Xe}))}for(let{id:De}of ge){let Xe=nt(e,De),tt=nt(l,De),kt=Object.fromEntries(["parent_id","database_id","order_key"].filter((qt)=>tt&&Xe[qt]!==tt[qt]&&de.some((Kr)=>Kr.dataset==="documents"&&Kr.row_id===De&&Kr.col===qt)).map((qt)=>[qt,Xe[qt]]));if(Object.keys(kt).length){let qt=await nr(new TextEncoder().encode(JSON.stringify([g.workspaceId,"document-structure",De,kt])));l.query("INSERT OR IGNORE INTO sync_recovery_items(id,kind,target,local,remote) VALUES(?,?,?,?,NULL)").run(qt,"entity",De,JSON.stringify({title:"未提交的文档结构编辑",documentId:De,fields:kt}))}if(tt&&Xe.body===tt.body&&Xe.title===tt.title)continue;if(ce&&Xe.title===tt?.title&&Oy(e,l,De,de))continue;let Gr=await nr(new TextEncoder().encode(JSON.stringify([g.workspaceId,De,Xe.title,Xe.body])));l.query("INSERT OR IGNORE INTO sync_recovery_items(id,kind,target,local,remote) VALUES(?,?,?,?,?)").run(Gr,"document",De,JSON.stringify(Xe),tt?JSON.stringify(tt):null)}for(let De of["replica_document_drafts","replica_field_drafts","sync_version_drafts"]){if(!e.query("SELECT 1 FROM sqlite_master WHERE type='table' AND name=?").get(De))continue;for(let Xe of e.query(`SELECT * FROM ${De}`).all()){let tt=await nr(new TextEncoder().encode(JSON.stringify([g.workspaceId,De,Xe])));l.query("INSERT OR IGNORE INTO sync_recovery_items(id,kind,target,local,remote) VALUES(?,?,?,?,NULL)").run(tt,De,String(Xe.doc_id??Xe.record_id),JSON.stringify(Xe))}}if(A&&F.state.members[A.incarnationId])l.query("INSERT OR REPLACE INTO meta(key,value) VALUES('sync_v2_retire',?)").run(JSON.stringify({member:A.incarnationId,sequence:F.state.members[A.incarnationId].sequence}));if(l.query("PRAGMA quick_check").get()?.quick_check!=="ok")throw new T("invalid_input","shadow database integrity check failed");if((await L.read()).state.epoch!==F.state.epoch)throw new T("busy","checkpoint changed during recovery; original database retained");return f("swapping"),await o.swap(l,c),u=!0,f("pending"),{packageId:c,pending:ru(l).length}}finally{try{if(l)await o.releaseShadow(l,u)}finally{await o.resume()}}}async function qy(e,t,r,n){let o=at(e);if(!o)throw new T("upgrade_required","v2 history requires migration");let i=Bt(t,r,e),s=e.query("SELECT value FROM meta WHERE key='sync_v2_checkpoint'").get(),l=(s?JSON.parse(s.value).history??[]:[]).filter((u)=>u.documentId===n);if(!l.length)return;for(let u of l){if(e.query("SELECT 1 FROM meta WHERE key=?").get(`sync_v2_history_loaded:${u.hash}`))continue;let f;try{f=await i.load(u.hash)}catch(E){throw new T("history_unavailable","历史尚未下载,请联网后重试")}let _=To.parse(f);if(_.documentId!==n)throw new T("invalid_input","history document mismatch");Ve(e,()=>{Us(e,_,o.workspaceId),e.query("INSERT OR REPLACE INTO meta(key,value) VALUES(?,?)").run(`sync_v2_history_loaded:${u.hash}`,"1")})}}vn();er();Pr();Kt();var Ly="local_recovery_successor",nu=(e)=>`replica-${e}.db`;function $y(e){if(!/^replica-[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}\.db$/.test(e))throw new T("invalid_input","Invalid local replica pointer");return e}function My(e){let t="metahub.db",r=new Set;for(;;){if(r.has(t))throw new T("invalid_input","Local replica pointer cycle");r.add(t);let n=e(t,r.size===1);try{if(!n.db.query("SELECT 1 FROM sqlite_master WHERE name='meta' AND type='table'").get()){if(r.size!==1)throw new T("invalid_input","Local replacement is incomplete");return n}let o=n.db.query("SELECT value FROM meta WHERE key=?").get(Ly);if(!o)return n;t=$y(o.value)}catch(o){throw n.close(),o}n.close()}}function Fy(e,t){$y(t),Ve(e,()=>{e.query("INSERT INTO meta(key,value) VALUES(?,?)").run(Ly,t),e.exec("CREATE TRIGGER retired_replica BEFORE INSERT ON crdt_changes BEGIN SELECT RAISE(ABORT,'local replica was rebuilt; reopen it'); END")})}function ou(e){return Ft(e).filter((t)=>t.enabled&&t.kind==="s3"&&t.config&&Vg(e,t.url)).map((t)=>t.url)}function zy(e,t){let r=Ft(e).find((n)=>n.url===t&&n.enabled&&n.kind==="s3"&&n.config);if(!r?.config)throw new T("invalid_input","Select a connected bucket on this device");return{config:JSON.parse(r.config),workspaceId:at(e)?.workspaceId??crypto.randomUUID()}}async function Uy(e,t){let r=e.query("SELECT value FROM meta WHERE key='sync_v2_checkpoint'").get();if(!r)return;if(!(JSON.parse(r.value).history??[]).some((c)=>c.documentId===t&&!e.query("SELECT 1 FROM meta WHERE key=?").get(`sync_v2_history_loaded:${c.hash}`)))return;let o=e.query("SELECT value FROM meta WHERE key='local_v2_history_peer'").get(),i=o&&Pt(e,o.value);if(!i?.enabled||!i.config)throw new T("history_unavailable","历史尚未下载,请连接原存储桶");let s=JSON.parse(i.config);await qy(e,$t(s),s,t)}function By(e,t,r){t.query("INSERT INTO meta(key,value) VALUES('local_v2_history_peer',?)").run(r);for(let n of Ft(e)){if(n.kind==="s3"&&n.config)ga(t,{url:n.url,label:n.label,config:JSON.parse(n.config)});else if(n.kind==="http")ha(t,{url:n.url,label:n.label,token:n.token,node_id:n.node_id});else t.query("INSERT INTO peers(url,kind,config,label,token,node_id) VALUES(?,?,?,?,?,?)").run(n.url,n.kind,n.config,n.label,n.token,n.node_id);t.query("UPDATE peers SET enabled=? WHERE url=?").run(n.enabled,n.url)}}Oi();Pr();ko();var Yx=Math.floor(167772160);function Qx(e){if(e instanceof ArrayBuffer)return e;let t=new Uint8Array(e.byteLength);return t.set(e),t.buffer}async function eR(e){let t=await crypto.subtle.digest("SHA-256",Qx(e));return[...new Uint8Array(t)].map((r)=>r.toString(16).padStart(2,"0")).join("")}async function Lo(e,t){return(await eR(e)).slice(0,t.length)===t}var ma=null;function tR(){if(ma)return ma;return ma=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)}),ma}function ro(e,t,r){return tR().then((n)=>new Promise((o,i)=>{let s=r(n.transaction(e,t).objectStore(e));s.onsuccess=()=>o(s.result),s.onerror=()=>i(s.error)}))}function iu(e){return ro("spool","readonly",(t)=>t.get(e))}async function _a(){return(await ro("spool","readonly",(t)=>t.getAll())??[]).filter((t)=>!t.durable)}async function jy(e){await ro("spool","readwrite",(t)=>t.delete(e))}var Hy=(e)=>`/blob/${e}`;async function rR(e,t,r){let n=await ro("meta","readonly",(i)=>i.get(e)),o={hash:e,size:t,accessed:Date.now(),pinned:n?.pinned??0,content_type:r??n?.content_type};await ro("meta","readwrite",(i)=>i.put(o))}async function Wy(e,t,r){await(await caches.open("mh-blob-v1")).put(Hy(e),new Response(t,{headers:{"content-type":r,"cache-control":"public, max-age=31536000, immutable"}})),await rR(e,t.byteLength,r),await nR()}async function nR(){let e=await ro("meta","readonly",(o)=>o.getAll())??[],t=e.reduce((o,i)=>o+i.size,0);if(t<=209715200)return;let r=await caches.open("mh-blob-v1"),n=e.filter((o)=>!o.pinned).sort((o,i)=>o.accessed-i.accessed);for(let o of n){if(t<=Yx)break;await r.delete(Hy(o.hash)),await ro("meta","readwrite",(i)=>i.delete(o.hash)),t-=o.size}}async function Vy(e,t,r,n,o,i=_a){let{config:s,workspaceId:c}=zy(e,t),l;return Py(e,o??$t(s),s,c,{legacyPeerUrl:t,phase:n,async pauseAndFlush(){await r.reserve(),e.exec("PRAGMA synchronous=FULL")},async protect(u){let f=`protection-${u}.db`;e.query("VACUUM INTO ?").run("/"+f);let _=r.open(f);try{_.db.exec("CREATE TABLE protected_spool(hash TEXT PRIMARY KEY, content_type TEXT NOT NULL, bytes BLOB NOT NULL)");for(let E of await i()){if(!/^(?:[a-f0-9]{32}|[a-f0-9]{64})$/.test(E.hash)||!await Lo(E.bytes,E.hash))throw Error("待上传附件校验失败");_.db.query("INSERT INTO protected_spool VALUES(?,?,?)").run(E.hash,E.content_type,new Uint8Array(E.bytes));let g=_.db.query("SELECT bytes FROM protected_spool WHERE hash=?").get(E.hash);if(!await Lo(g.bytes,E.hash))throw Error("附件保护副本校验失败")}if(_.db.query("PRAGMA quick_check").get().quick_check!=="ok")throw Error("数据库保护副本校验失败")}finally{_.close()}return{proof:await nr(await r.bytes(f))}},async createShadow(u){l=r.open(nu(u));try{return l.db.exec("PRAGMA synchronous=FULL"),Ai(l.db),By(e,l.db,t),l.db}catch(f){throw l.close(),f}},async swap(u,f){Fy(e,nu(f)),r.activate(l)},async releaseShadow(u,f){if(!f)l?.close()},async resume(){}})}globalThis.sqlite3Worker1Promiser=function e(t=e.defaultConfig){if(arguments.length===1&&typeof arguments[0]==="function"){let _=t;t=Object.assign(Object.create(null),e.defaultConfig),t.onready=_}else t=Object.assign(Object.create(null),e.defaultConfig,t);let r=Object.create(null),n=function(){},o=t.onerror||n,i=t.debug||n,s=t.generateMessageId?void 0:Object.create(null),c=t.generateMessageId||function(_){return _.type+"#"+(s[_.type]=(s[_.type]||0)+1)},l=(..._)=>{throw Error(_.join(" "))};if(!t.worker)t.worker=e.defaultConfig.worker;if(typeof t.worker==="function")t.worker=t.worker();let u,f;return t.worker.onmessage=function(_){_=_.data,i("worker1.onmessage",_);let E=r[_.messageId];if(!E){if(_&&_.type==="sqlite3-api"&&_.result==="worker1-ready"){if(t.onready)t.onready(f);return}if(E=r[_.type],E&&E.onrow){E.onrow(_);return}if(t.onunhandled)t.onunhandled(arguments[0]);else o("sqlite3Worker1Promiser() unhandled worker message:",_);return}switch(delete r[_.messageId],_.type){case"error":E.reject(_);return;case"open":if(!u)u=_.dbId;break;case"close":if(_.dbId===u)u=void 0;break;default:break}try{E.resolve(_)}catch(g){E.reject(g)}},f=function(){let _;if(arguments.length===1)_=arguments[0];else if(arguments.length===2)_=Object.create(null),_.type=arguments[0],_.args=arguments[1],_.dbId=_.args.dbId;else l("Invalid arguments for sqlite3Worker1Promiser()-created factory.");if(!_.dbId&&_.type!=="open")_.dbId=u;_.messageId=c(_),_.departureTime=performance.now();let E=Object.create(null);E.message=_;let g;if(_.type==="exec"&&_.args){if(typeof _.args.callback==="function")g=_.messageId+":row",E.onrow=_.args.callback,_.args.callback=g,r[g]=E;else if(typeof _.args.callback==="string")l("exec callback may not be a string when using the Promise interface.")}let A=new Promise(function(L,F){E.resolve=L,E.reject=F,r[_.messageId]=E,i("Posting",_.type,"message to Worker dbId="+(u||"default")+":",_),t.worker.postMessage(_)});if(g)A=A.finally(()=>delete r[g]);return A}};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(i){try{if(r)await r(i);n.resolve(i)}catch(s){n.reject(s)}}});let o=new Promise(function(i,s){n.resolve=i,n.reject=s});try{this.original(t)}catch(i){n.reject(i)}return o}.bind({original:sqlite3Worker1Promiser});globalThis.sqlite3Worker1Promiser.v2.defaultConfig=globalThis.sqlite3Worker1Promiser.defaultConfig;var wq=sqlite3Worker1Promiser.v2;delete globalThis.sqlite3Worker1Promiser;async function su(e={}){var t,r=e,n=!!globalThis.window,o=!!globalThis.WorkerGlobalScope;globalThis.process?.versions?.node&&globalThis.process?.type;var i="./this.program",s=import.meta.url,c="";function l(a){if(r.locateFile)return r.locateFile(a,c);return c+a}var u,f;if(n||o){try{c=new URL(".",s).href}catch{}if(o)f=(a)=>{var p=new XMLHttpRequest;return p.open("GET",a,!1),p.responseType="arraybuffer",p.send(null),new Uint8Array(p.response)};u=async(a)=>{var p=await fetch(a,{credentials:"same-origin"});if(p.ok)return p.arrayBuffer();throw Error(p.status+" : "+p.url)}}var _=console.log.bind(console),E=console.error.bind(console),g,A=!1,L,F,X=!1;function te(){var a=Jr.buffer;yr=new Int8Array(a),Ho=new Int16Array(a),Tn=new Uint8Array(a),Uw=new Uint16Array(a),ut=new Int32Array(a),ft=new Uint32Array(a),Fw=new Float32Array(a),zw=new Float64Array(a),Xt=new BigInt64Array(a),Bw=new BigUint64Array(a)}function ce(){if(r.wasmMemory)Jr=r.wasmMemory;else{var a=r.INITIAL_MEMORY||8388608;Jr=new WebAssembly.Memory({initial:a/65536,maximum:32768})}te()}function de(){if(r.preRun){if(typeof r.preRun=="function")r.preRun=[r.preRun];while(r.preRun.length)Hw(r.preRun.shift())}Zu(Ku)}function Ce(){if(X=!0,!r.noFSInit&&!S.initialized)S.init();dn.init(),uo.__wasm_call_ctors(),S.ignorePermissions=!1}function ge(){if(r.postRun){if(typeof r.postRun=="function")r.postRun=[r.postRun];while(r.postRun.length)jw(r.postRun.shift())}Zu(Gu)}function Pe(a){r.onAbort?.(a),a=`Aborted(${a})`,E(a),A=!0,a+=". Build with -sASSERTIONS for more info.";var p=new WebAssembly.RuntimeError(a);throw F?.(p),p}var Qe;function De(){if(r.locateFile)return l("sqlite3.wasm");return new URL("sqlite3.wasm",import.meta.url).href}function Xe(a){if(a==Qe&&g)return new Uint8Array(g);if(f)return f(a);throw"both async and sync fetching of the wasm failed"}async function tt(a){if(!g)try{var p=await u(a);return new Uint8Array(p)}catch{}return Xe(a)}async function kt(a,p){try{var w=await tt(a);return await WebAssembly.instantiate(w,p)}catch(m){E(`failed to asynchronously prepare wasm: ${m}`),Pe(m)}}async function Gr(a,p,w){if(!a)try{var m=fetch(p,{credentials:"same-origin"});return await WebAssembly.instantiateStreaming(m,w)}catch(d){E(`wasm streaming compile failed: ${d}`),E("falling back to ArrayBuffer instantiation")}return kt(p,w)}function qt(){return{env:ud,wasi_snapshot_preview1:ud}}async function Kr(){function a(m,d){return uo=m.exports,Gv(uo),uo}function p(m){return a(m.instance)}var w=qt();if(r.instantiateWasm)return new Promise((m,d)=>{r.instantiateWasm(w,(h,y)=>{m(a(h,y))})});return Qe??=De(),p(await Gr(g,Qe,w))}var Ho,ut,Xt,yr,Fw,zw,Uw,ft,Bw,Tn,Zu=(a)=>{while(a.length>0)a.shift()(r)},Gu=[],jw=(a)=>Gu.push(a),Ku=[],Hw=(a)=>Ku.push(a),Jr,dt={isAbs:(a)=>a.charAt(0)==="/",splitPath:(a)=>/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/.exec(a).slice(1),normalizeArray:(a,p)=>{var w=0;for(var m=a.length-1;m>=0;m--){var d=a[m];if(d===".")a.splice(m,1);else if(d==="..")a.splice(m,1),w++;else if(w)a.splice(m,1),w--}if(p)for(;w;w--)a.unshift("..");return a},normalize:(a)=>{var p=dt.isAbs(a),w=a.slice(-1)==="/";if(a=dt.normalizeArray(a.split("/").filter((m)=>!!m),!p).join("/"),!a&&!p)a=".";if(a&&w)a+="/";return(p?"/":"")+a},dirname:(a)=>{var p=dt.splitPath(a),w=p[0],m=p[1];if(!w&&!m)return".";if(m)m=m.slice(0,-1);return w+m},basename:(a)=>a&&a.match(/([^\/]+|\/)\/*$/)[1],join:(...a)=>dt.normalize(a.join("/")),join2:(a,p)=>dt.normalize(a+"/"+p)},Ww=()=>(a)=>(crypto.getRandomValues(a),0),Ju=(a)=>(Ju=Ww())(a),ao={resolve:(...a)=>{var p="",w=!1;for(var m=a.length-1;m>=-1&&!w;m--){var d=m>=0?a[m]:S.cwd();if(typeof d!="string")throw TypeError("Arguments to path.resolve must be strings");else if(!d)return"";p=d+"/"+p,w=dt.isAbs(d)}return p=dt.normalizeArray(p.split("/").filter((h)=>!!h),!w).join("/"),(w?"/":"")+p||"."},relative:(a,p)=>{a=ao.resolve(a).slice(1),p=ao.resolve(p).slice(1);function w(q){var ee=0;for(;ee<q.length;ee++)if(q[ee]!=="")break;var V=q.length-1;for(;V>=0;V--)if(q[V]!=="")break;if(ee>V)return[];return q.slice(ee,V-ee+1)}var m=w(a.split("/")),d=w(p.split("/")),h=Math.min(m.length,d.length),y=h;for(var D=0;D<h;D++)if(m[D]!==d[D]){y=D;break}var x=[];for(var D=y;D<m.length;D++)x.push("..");return x=x.concat(d.slice(y)),x.join("/")}},Xu=new TextDecoder,Yu=(a,p,w,m)=>{var d=p+w;if(m)return d;while(a[p]&&!(p>=d))++p;return p},Wo=(a,p=0,w,m)=>{var d=Yu(a,p,w,m);return Xu.decode(a.buffer?a.subarray(p,d):new Uint8Array(a.slice(p,d)))},La=[],ji=(a)=>{var p=0;for(var w=0;w<a.length;++w){var m=a.charCodeAt(w);if(m<=127)p++;else if(m<=2047)p+=2;else if(m>=55296&&m<=57343)p+=4,++w;else p+=3}return p},Qu=(a,p,w,m)=>{if(!(m>0))return 0;var d=w,h=w+m-1;for(var y=0;y<a.length;++y){var D=a.codePointAt(y);if(D<=127){if(w>=h)break;p[w++]=D}else if(D<=2047){if(w+1>=h)break;p[w++]=192|D>>6,p[w++]=128|D&63}else if(D<=65535){if(w+2>=h)break;p[w++]=224|D>>12,p[w++]=128|D>>6&63,p[w++]=128|D&63}else{if(w+3>=h)break;p[w++]=240|D>>18,p[w++]=128|D>>12&63,p[w++]=128|D>>6&63,p[w++]=128|D&63,y++}}return p[w]=0,w-d},$a=(a,p,w)=>{var m=w>0?w:ji(a)+1,d=Array(m),h=Qu(a,d,0,d.length);if(p)d.length=h;return d},Vw=()=>{if(!La.length){var a=null;if(globalThis.window?.prompt){if(a=window.prompt("Input: "),a!==null)a+=`
556
+ `}if(!a)return null;La=$a(a,!0)}return La.shift()},dn={ttys:[],init(){},shutdown(){},register(a,p){dn.ttys[a]={input:[],output:[],ops:p},S.registerDevice(a,dn.stream_ops)},stream_ops:{open(a){var p=dn.ttys[a.node.rdev];if(!p)throw new S.ErrnoError(43);a.tty=p,a.seekable=!1},close(a){a.tty.ops.fsync(a.tty)},fsync(a){a.tty.ops.fsync(a.tty)},read(a,p,w,m,d){if(!a.tty||!a.tty.ops.get_char)throw new S.ErrnoError(60);var h=0;for(var y=0;y<m;y++){var D;try{D=a.tty.ops.get_char(a.tty)}catch(x){throw new S.ErrnoError(29)}if(D===void 0&&h===0)throw new S.ErrnoError(6);if(D===null||D===void 0)break;h++,p[w+y]=D}if(h)a.node.atime=Date.now();return h},write(a,p,w,m,d){if(!a.tty||!a.tty.ops.put_char)throw new S.ErrnoError(60);try{for(var h=0;h<m;h++)a.tty.ops.put_char(a.tty,p[w+h])}catch(y){throw new S.ErrnoError(29)}if(m)a.node.mtime=a.node.ctime=Date.now();return h}},default_tty_ops:{get_char(a){return Vw()},put_char(a,p){if(p===null||p===10)_(Wo(a.output)),a.output=[];else if(p!=0)a.output.push(p)},fsync(a){if(a.output?.length>0)_(Wo(a.output)),a.output=[]},ioctl_tcgets(a){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(a,p,w){return 0},ioctl_tiocgwinsz(a){return[24,80]}},default_tty1_ops:{put_char(a,p){if(p===null||p===10)E(Wo(a.output)),a.output=[];else if(p!=0)a.output.push(p)},fsync(a){if(a.output?.length>0)E(Wo(a.output)),a.output=[]}}},Zw=(a,p)=>Tn.fill(0,a,a+p),ed=(a,p)=>Math.ceil(a/p)*p,td=(a)=>{a=ed(a,65536);var p=ld(65536,a);if(p)Zw(p,a);return p},Ge={ops_table:null,mount(a){return Ge.createNode(null,"/",16895,0)},createNode(a,p,w,m){if(S.isBlkdev(w)||S.isFIFO(w))throw new S.ErrnoError(63);Ge.ops_table||={dir:{node:{getattr:Ge.node_ops.getattr,setattr:Ge.node_ops.setattr,lookup:Ge.node_ops.lookup,mknod:Ge.node_ops.mknod,rename:Ge.node_ops.rename,unlink:Ge.node_ops.unlink,rmdir:Ge.node_ops.rmdir,readdir:Ge.node_ops.readdir,symlink:Ge.node_ops.symlink},stream:{llseek:Ge.stream_ops.llseek}},file:{node:{getattr:Ge.node_ops.getattr,setattr:Ge.node_ops.setattr},stream:{llseek:Ge.stream_ops.llseek,read:Ge.stream_ops.read,write:Ge.stream_ops.write,mmap:Ge.stream_ops.mmap,msync:Ge.stream_ops.msync}},link:{node:{getattr:Ge.node_ops.getattr,setattr:Ge.node_ops.setattr,readlink:Ge.node_ops.readlink},stream:{}},chrdev:{node:{getattr:Ge.node_ops.getattr,setattr:Ge.node_ops.setattr},stream:S.chrdev_stream_ops}};var d=S.createNode(a,p,w,m);if(S.isDir(d.mode))d.node_ops=Ge.ops_table.dir.node,d.stream_ops=Ge.ops_table.dir.stream,d.contents={};else if(S.isFile(d.mode))d.node_ops=Ge.ops_table.file.node,d.stream_ops=Ge.ops_table.file.stream,d.usedBytes=0,d.contents=Ge.emptyFileContents??=new Uint8Array(0);else if(S.isLink(d.mode))d.node_ops=Ge.ops_table.link.node,d.stream_ops=Ge.ops_table.link.stream;else if(S.isChrdev(d.mode))d.node_ops=Ge.ops_table.chrdev.node,d.stream_ops=Ge.ops_table.chrdev.stream;if(d.atime=d.mtime=d.ctime=Date.now(),a)a.contents[p]=d,a.atime=a.mtime=a.ctime=d.atime;return d},getFileDataAsTypedArray(a){return a.contents.subarray(0,a.usedBytes)},expandFileStorage(a,p){var w=a.contents.length;if(w>=p)return;if(p=Math.max(p,w*(w<1048576?2:1.125)>>>0),w)p=Math.max(p,256);var m=Ge.getFileDataAsTypedArray(a);a.contents=new Uint8Array(p),a.contents.set(m)},resizeFileStorage(a,p){if(a.usedBytes==p)return;var w=a.contents;a.contents=new Uint8Array(p),a.contents.set(w.subarray(0,Math.min(p,a.usedBytes))),a.usedBytes=p},node_ops:{getattr(a){var p={};if(p.dev=S.isChrdev(a.mode)?a.id:1,p.ino=a.id,p.mode=a.mode,p.nlink=1,p.uid=0,p.gid=0,p.rdev=a.rdev,S.isDir(a.mode))p.size=4096;else if(S.isFile(a.mode))p.size=a.usedBytes;else if(S.isLink(a.mode))p.size=a.link.length;else p.size=0;return p.atime=new Date(a.atime),p.mtime=new Date(a.mtime),p.ctime=new Date(a.ctime),p.blksize=4096,p.blocks=Math.ceil(p.size/p.blksize),p},setattr(a,p){for(let w of["mode","atime","mtime","ctime"])if(p[w]!=null)a[w]=p[w];if(p.size!==void 0)Ge.resizeFileStorage(a,p.size)},lookup(a,p){if(!Ge.doesNotExistError)Ge.doesNotExistError=new S.ErrnoError(44),Ge.doesNotExistError.stack="<generic error, no stack>";throw Ge.doesNotExistError},mknod(a,p,w,m){return Ge.createNode(a,p,w,m)},rename(a,p,w){var m;try{m=S.lookupNode(p,w)}catch(h){}if(m){if(S.isDir(a.mode))for(var d in m.contents)throw new S.ErrnoError(55);S.hashRemoveNode(m)}delete a.parent.contents[a.name],p.contents[w]=a,a.name=w,p.ctime=p.mtime=a.parent.ctime=a.parent.mtime=Date.now()},unlink(a,p){delete a.contents[p],a.ctime=a.mtime=Date.now()},rmdir(a,p){for(var w in S.lookupNode(a,p).contents)throw new S.ErrnoError(55);delete a.contents[p],a.ctime=a.mtime=Date.now()},readdir(a){return[".","..",...Object.keys(a.contents)]},symlink(a,p,w){var m=Ge.createNode(a,p,41471,0);return m.link=w,m},readlink(a){if(!S.isLink(a.mode))throw new S.ErrnoError(28);return a.link}},stream_ops:{read(a,p,w,m,d){var h=a.node.contents;if(d>=a.node.usedBytes)return 0;var y=Math.min(a.node.usedBytes-d,m);return p.set(h.subarray(d,d+y),w),y},write(a,p,w,m,d,h){if(p.buffer===yr.buffer)h=!1;if(!m)return 0;var y=a.node;if(y.mtime=y.ctime=Date.now(),h)y.contents=p.subarray(w,w+m),y.usedBytes=m;else if(y.usedBytes===0&&d===0)y.contents=p.slice(w,w+m),y.usedBytes=m;else Ge.expandFileStorage(y,d+m),y.contents.set(p.subarray(w,w+m),d),y.usedBytes=Math.max(y.usedBytes,d+m);return m},llseek(a,p,w){var m=p;if(w===1)m+=a.position;else if(w===2){if(S.isFile(a.node.mode))m+=a.node.usedBytes}if(m<0)throw new S.ErrnoError(28);return m},mmap(a,p,w,m,d){if(!S.isFile(a.node.mode))throw new S.ErrnoError(43);var h,y,D=a.node.contents;if(!(d&2)&&D.buffer===yr.buffer)y=!1,h=D.byteOffset;else{if(y=!0,h=td(p),!h)throw new S.ErrnoError(48);if(D){if(w>0||w+p<D.length)if(D.subarray)D=D.subarray(w,w+p);else D=Array.prototype.slice.call(D,w,w+p);yr.set(D,h)}}return{ptr:h,allocated:y}},msync(a,p,w,m,d){return Ge.stream_ops.write(a,p,0,m,w,!1),0}}},Gw=(a)=>{if(typeof a!="string")return a;var p={r:0,"r+":2,w:577,"w+":578,a:1089,"a+":1090}[a];if(typeof p>"u")throw Error(`Unknown file open mode: ${a}`);return p},rd=(a)=>{if(typeof a=="string")a=$a(a,!0);if(!a.subarray)a=new Uint8Array(a);return a},Ma=(a,p)=>{var w=0;if(a)w|=365;if(p)w|=146;return w},Kw=async(a)=>{var p=await u(a);return new Uint8Array(p)},Jw=(...a)=>S.createDataFile(...a),Xw=(a)=>a,Dn=0,Vo=null,Yw=(a)=>{if(Dn--,r.monitorRunDependencies?.(Dn),Dn==0){if(Vo){var p=Vo;Vo=null,p()}}},Qw=(a)=>{Dn++,r.monitorRunDependencies?.(Dn)},nd=[],ev=async(a,p)=>{if(typeof Browser<"u")Browser.init();for(var w of nd)if(w.canHandle(p))return w.handle(a,p);return a},od=async(a,p,w,m,d,h,y,D)=>{var x=p?ao.resolve(dt.join2(a,p)):a,q=Xw(`cp ${x}`);Qw(q);try{var ee=w;if(typeof w=="string")ee=await Kw(w);if(ee=await ev(ee,x),D?.(),!h)Jw(a,p,ee,m,d,y)}finally{Yw(q)}},tv=(a,p,w,m,d,h,y,D,x,q)=>{od(a,p,w,m,d,D,x,q).then(h).catch(y)},S={root:null,mounts:[],devices:{},streams:[],nextInode:1,nameTable:null,currentPath:"/",initialized:!1,ignorePermissions:!0,filesystems:null,syncFSRequests:0,ErrnoError:class{name="ErrnoError";constructor(a){this.errno=a}},FSStream:class{shared={};get object(){return this.node}set object(a){this.node=a}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(a){this.shared.flags=a}get position(){return this.shared.position}set position(a){this.shared.position=a}},FSNode:class{node_ops={};stream_ops={};readMode=365;writeMode=146;mounted=null;constructor(a,p,w,m){if(!a)a=this;this.parent=a,this.mount=a.mount,this.id=S.nextInode++,this.name=p,this.mode=w,this.rdev=m,this.atime=this.mtime=this.ctime=Date.now()}get read(){return(this.mode&this.readMode)===this.readMode}set read(a){a?this.mode|=this.readMode:this.mode&=~this.readMode}get write(){return(this.mode&this.writeMode)===this.writeMode}set write(a){a?this.mode|=this.writeMode:this.mode&=~this.writeMode}get isFolder(){return S.isDir(this.mode)}get isDevice(){return S.isChrdev(this.mode)}},lookupPath(a,p={}){if(!a)throw new S.ErrnoError(44);if(p.follow_mount??=!0,!dt.isAbs(a))a=S.cwd()+"/"+a;e:for(var w=0;w<40;w++){var m=a.split("/").filter((q)=>!!q),d=S.root,h="/";for(var y=0;y<m.length;y++){var D=y===m.length-1;if(D&&p.parent)break;if(m[y]===".")continue;if(m[y]===".."){if(h=dt.dirname(h),S.isRoot(d)){a=h+"/"+m.slice(y+1).join("/"),w--;continue e}else d=d.parent;continue}h=dt.join2(h,m[y]);try{d=S.lookupNode(d,m[y])}catch(q){if(q?.errno===44&&D&&p.noent_okay)return{path:h};throw q}if(S.isMountpoint(d)&&(!D||p.follow_mount))d=d.mounted.root;if(S.isLink(d.mode)&&(!D||p.follow)){if(!d.node_ops.readlink)throw new S.ErrnoError(52);var x=d.node_ops.readlink(d);if(!dt.isAbs(x))x=dt.dirname(h)+"/"+x;a=x+"/"+m.slice(y+1).join("/");continue e}}return{path:h,node:d}}throw new S.ErrnoError(32)},getPath(a){var p;while(!0){if(S.isRoot(a)){var w=a.mount.mountpoint;if(!p)return w;return w[w.length-1]!=="/"?`${w}/${p}`:w+p}p=p?`${a.name}/${p}`:a.name,a=a.parent}},hashName(a,p){var w=0;for(var m=0;m<p.length;m++)w=(w<<5)-w+p.charCodeAt(m)|0;return(a+w>>>0)%S.nameTable.length},hashAddNode(a){var p=S.hashName(a.parent.id,a.name);a.name_next=S.nameTable[p],S.nameTable[p]=a},hashRemoveNode(a){var p=S.hashName(a.parent.id,a.name);if(S.nameTable[p]===a)S.nameTable[p]=a.name_next;else{var w=S.nameTable[p];while(w){if(w.name_next===a){w.name_next=a.name_next;break}w=w.name_next}}},lookupNode(a,p){var w=S.mayLookup(a);if(w)throw new S.ErrnoError(w);var m=S.hashName(a.id,p);for(var d=S.nameTable[m];d;d=d.name_next){var h=d.name;if(d.parent.id===a.id&&h===p)return d}return S.lookup(a,p)},createNode(a,p,w,m){var d=new S.FSNode(a,p,w,m);return S.hashAddNode(d),d},destroyNode(a){S.hashRemoveNode(a)},isRoot(a){return a===a.parent},isMountpoint(a){return!!a.mounted},isFile(a){return(a&61440)===32768},isDir(a){return(a&61440)===16384},isLink(a){return(a&61440)===40960},isChrdev(a){return(a&61440)===8192},isBlkdev(a){return(a&61440)===24576},isFIFO(a){return(a&61440)===4096},isSocket(a){return(a&49152)===49152},flagsToPermissionString(a){var p=["r","w","rw"][a&3];if(a&512)p+="w";return p},nodePermissions(a,p){if(S.ignorePermissions)return 0;if(p.includes("r")&&!(a.mode&292))return 2;if(p.includes("w")&&!(a.mode&146))return 2;if(p.includes("x")&&!(a.mode&73))return 2;return 0},mayLookup(a){if(!S.isDir(a.mode))return 54;var p=S.nodePermissions(a,"x");if(p)return p;if(!a.node_ops.lookup)return 2;return 0},mayCreate(a,p){if(!S.isDir(a.mode))return 54;try{return S.lookupNode(a,p),20}catch(w){}return S.nodePermissions(a,"wx")},mayDelete(a,p,w){var m;try{m=S.lookupNode(a,p)}catch(h){return h.errno}var d=S.nodePermissions(a,"wx");if(d)return d;if(w){if(!S.isDir(m.mode))return 54;if(S.isRoot(m)||S.getPath(m)===S.cwd())return 10}else if(S.isDir(m.mode))return 31;return 0},mayOpen(a,p){if(!a)return 44;if(S.isLink(a.mode))return 32;var w=S.flagsToPermissionString(p);if(S.isDir(a.mode)){if(w!=="r"||p&576)return 31}return S.nodePermissions(a,w)},checkOpExists(a,p){if(!a)throw new S.ErrnoError(p);return a},MAX_OPEN_FDS:4096,nextfd(){for(var a=0;a<=S.MAX_OPEN_FDS;a++)if(!S.streams[a])return a;throw new S.ErrnoError(33)},getStreamChecked(a){var p=S.getStream(a);if(!p)throw new S.ErrnoError(8);return p},getStream:(a)=>S.streams[a],createStream(a,p=-1){if(a=Object.assign(new S.FSStream,a),p==-1)p=S.nextfd();return a.fd=p,S.streams[p]=a,a},closeStream(a){S.streams[a]=null},dupStream(a,p=-1){var w=S.createStream(a,p);return w.stream_ops?.dup?.(w),w},doSetAttr(a,p,w){var m=a?.stream_ops.setattr,d=m?a:p;m??=p.node_ops.setattr,S.checkOpExists(m,63),m(d,w)},chrdev_stream_ops:{open(a){a.stream_ops=S.getDevice(a.node.rdev).stream_ops,a.stream_ops.open?.(a)},llseek(){throw new S.ErrnoError(70)}},major:(a)=>a>>8,minor:(a)=>a&255,makedev:(a,p)=>a<<8|p,registerDevice(a,p){S.devices[a]={stream_ops:p}},getDevice:(a)=>S.devices[a],getMounts(a){var p=[],w=[a];while(w.length){var m=w.pop();p.push(m),w.push(...m.mounts)}return p},syncfs(a,p){if(typeof a=="function")p=a,a=!1;if(S.syncFSRequests++,S.syncFSRequests>1)E(`warning: ${S.syncFSRequests} FS.syncfs operations in flight at once, probably just doing extra work`);var w=S.getMounts(S.root.mount),m=0;function d(D){return S.syncFSRequests--,p(D)}function h(D){if(D){if(!h.errored)return h.errored=!0,d(D);return}if(++m>=w.length)d(null)}for(var y of w)if(y.type.syncfs)y.type.syncfs(y,a,h);else h(null)},mount(a,p,w){var m=w==="/",d=!w,h;if(m&&S.root)throw new S.ErrnoError(10);else if(!m&&!d){var y=S.lookupPath(w,{follow_mount:!1});if(w=y.path,h=y.node,S.isMountpoint(h))throw new S.ErrnoError(10);if(!S.isDir(h.mode))throw new S.ErrnoError(54)}var D={type:a,opts:p,mountpoint:w,mounts:[]},x=a.mount(D);if(x.mount=D,D.root=x,m)S.root=x;else if(h){if(h.mounted=D,h.mount)h.mount.mounts.push(D)}return x},unmount(a){var p=S.lookupPath(a,{follow_mount:!1});if(!S.isMountpoint(p.node))throw new S.ErrnoError(28);var w=p.node,m=w.mounted,d=S.getMounts(m);for(var[h,y]of Object.entries(S.nameTable))while(y){var D=y.name_next;if(d.includes(y.mount))S.destroyNode(y);y=D}w.mounted=null;var x=w.mount.mounts.indexOf(m);w.mount.mounts.splice(x,1)},lookup(a,p){return a.node_ops.lookup(a,p)},mknod(a,p,w){var m=S.lookupPath(a,{parent:!0}).node,d=dt.basename(a);if(!d)throw new S.ErrnoError(28);if(d==="."||d==="..")throw new S.ErrnoError(20);var h=S.mayCreate(m,d);if(h)throw new S.ErrnoError(h);if(!m.node_ops.mknod)throw new S.ErrnoError(63);return m.node_ops.mknod(m,d,p,w)},statfs(a){return S.statfsNode(S.lookupPath(a,{follow:!0}).node)},statfsStream(a){return S.statfsNode(a.node)},statfsNode(a){var p={bsize:4096,frsize:4096,blocks:1e6,bfree:500000,bavail:500000,files:S.nextInode,ffree:S.nextInode-1,fsid:42,flags:2,namelen:255};if(a.node_ops.statfs)Object.assign(p,a.node_ops.statfs(a.mount.opts.root));return p},create(a,p=438){return p&=4095,p|=32768,S.mknod(a,p,0)},mkdir(a,p=511){return p&=1023,p|=16384,S.mknod(a,p,0)},mkdirTree(a,p){var w=a.split("/"),m="";for(var d of w){if(!d)continue;if(m||dt.isAbs(a))m+="/";m+=d;try{S.mkdir(m,p)}catch(h){if(h.errno!=20)throw h}}},mkdev(a,p,w){if(typeof w>"u")w=p,p=438;return p|=8192,S.mknod(a,p,w)},symlink(a,p){if(!ao.resolve(a))throw new S.ErrnoError(44);var w=S.lookupPath(p,{parent:!0}).node;if(!w)throw new S.ErrnoError(44);var m=dt.basename(p),d=S.mayCreate(w,m);if(d)throw new S.ErrnoError(d);if(!w.node_ops.symlink)throw new S.ErrnoError(63);return w.node_ops.symlink(w,m,a)},rename(a,p){var w=dt.dirname(a),m=dt.dirname(p),d=dt.basename(a),h=dt.basename(p),y=S.lookupPath(a,{parent:!0}),D=y.node,x;if(y=S.lookupPath(p,{parent:!0}),x=y.node,!D||!x)throw new S.ErrnoError(44);if(D.mount!==x.mount)throw new S.ErrnoError(75);var q=S.lookupNode(D,d),ee=ao.relative(a,m);if(ee.charAt(0)!==".")throw new S.ErrnoError(28);if(ee=ao.relative(p,w),ee.charAt(0)!==".")throw new S.ErrnoError(55);var V;try{V=S.lookupNode(x,h)}catch(K){}if(q===V)return;var U=S.isDir(q.mode),B=S.mayDelete(D,d,U);if(B)throw new S.ErrnoError(B);if(B=V?S.mayDelete(x,h,U):S.mayCreate(x,h),B)throw new S.ErrnoError(B);if(!D.node_ops.rename)throw new S.ErrnoError(63);if(S.isMountpoint(q)||V&&S.isMountpoint(V))throw new S.ErrnoError(10);if(x!==D){if(B=S.nodePermissions(D,"w"),B)throw new S.ErrnoError(B)}S.hashRemoveNode(q);try{D.node_ops.rename(q,x,h),q.parent=x}catch(K){throw K}finally{S.hashAddNode(q)}},rmdir(a){var p=S.lookupPath(a,{parent:!0}).node,w=dt.basename(a),m=S.lookupNode(p,w),d=S.mayDelete(p,w,!0);if(d)throw new S.ErrnoError(d);if(!p.node_ops.rmdir)throw new S.ErrnoError(63);if(S.isMountpoint(m))throw new S.ErrnoError(10);p.node_ops.rmdir(p,w),S.destroyNode(m)},readdir(a){var p=S.lookupPath(a,{follow:!0}).node;return S.checkOpExists(p.node_ops.readdir,54)(p)},unlink(a){var p=S.lookupPath(a,{parent:!0}).node;if(!p)throw new S.ErrnoError(44);var w=dt.basename(a),m=S.lookupNode(p,w),d=S.mayDelete(p,w,!1);if(d)throw new S.ErrnoError(d);if(!p.node_ops.unlink)throw new S.ErrnoError(63);if(S.isMountpoint(m))throw new S.ErrnoError(10);p.node_ops.unlink(p,w),S.destroyNode(m)},readlink(a){var p=S.lookupPath(a).node;if(!p)throw new S.ErrnoError(44);if(!p.node_ops.readlink)throw new S.ErrnoError(28);return p.node_ops.readlink(p)},stat(a,p){var w=S.lookupPath(a,{follow:!p}).node;return S.checkOpExists(w.node_ops.getattr,63)(w)},fstat(a){var p=S.getStreamChecked(a),w=p.node,m=p.stream_ops.getattr,d=m?p:w;return m??=w.node_ops.getattr,S.checkOpExists(m,63),m(d)},lstat(a){return S.stat(a,!0)},doChmod(a,p,w,m){S.doSetAttr(a,p,{mode:w&4095|p.mode&-4096,ctime:Date.now(),dontFollow:m})},chmod(a,p,w){var m;if(typeof a=="string")m=S.lookupPath(a,{follow:!w}).node;else m=a;S.doChmod(null,m,p,w)},lchmod(a,p){S.chmod(a,p,!0)},fchmod(a,p){var w=S.getStreamChecked(a);S.doChmod(w,w.node,p,!1)},doChown(a,p,w){S.doSetAttr(a,p,{timestamp:Date.now(),dontFollow:w})},chown(a,p,w,m){var d;if(typeof a=="string")d=S.lookupPath(a,{follow:!m}).node;else d=a;S.doChown(null,d,m)},lchown(a,p,w){S.chown(a,p,w,!0)},fchown(a,p,w){var m=S.getStreamChecked(a);S.doChown(m,m.node,!1)},doTruncate(a,p,w){if(S.isDir(p.mode))throw new S.ErrnoError(31);if(!S.isFile(p.mode))throw new S.ErrnoError(28);var m=S.nodePermissions(p,"w");if(m)throw new S.ErrnoError(m);S.doSetAttr(a,p,{size:w,timestamp:Date.now()})},truncate(a,p){if(p<0)throw new S.ErrnoError(28);var w;if(typeof a=="string")w=S.lookupPath(a,{follow:!0}).node;else w=a;S.doTruncate(null,w,p)},ftruncate(a,p){var w=S.getStreamChecked(a);if(p<0||(w.flags&2097155)===0)throw new S.ErrnoError(28);S.doTruncate(w,w.node,p)},utime(a,p,w){var m=S.lookupPath(a,{follow:!0}).node;S.checkOpExists(m.node_ops.setattr,63)(m,{atime:p,mtime:w})},open(a,p,w=438){if(a==="")throw new S.ErrnoError(44);if(p=Gw(p),p&64)w=w&4095|32768;else w=0;var m,d;if(typeof a=="object")m=a;else{d=a.endsWith("/");var h=S.lookupPath(a,{follow:!(p&131072),noent_okay:!0});m=h.node,a=h.path}var y=!1;if(p&64)if(m){if(p&128)throw new S.ErrnoError(20)}else if(d)throw new S.ErrnoError(31);else m=S.mknod(a,w|511,0),y=!0;if(!m)throw new S.ErrnoError(44);if(S.isChrdev(m.mode))p&=-513;if(p&65536&&!S.isDir(m.mode))throw new S.ErrnoError(54);if(!y){var D=S.mayOpen(m,p);if(D)throw new S.ErrnoError(D)}if(p&512&&!y)S.truncate(m,0);p&=-131713;var x=S.createStream({node:m,path:S.getPath(m),flags:p,seekable:!0,position:0,stream_ops:m.stream_ops,ungotten:[],error:!1});if(x.stream_ops.open)x.stream_ops.open(x);if(y)S.chmod(m,w&511);return x},close(a){if(S.isClosed(a))throw new S.ErrnoError(8);if(a.getdents)a.getdents=null;try{if(a.stream_ops.close)a.stream_ops.close(a)}catch(p){throw p}finally{S.closeStream(a.fd)}a.fd=null},isClosed(a){return a.fd===null},llseek(a,p,w){if(S.isClosed(a))throw new S.ErrnoError(8);if(!a.seekable||!a.stream_ops.llseek)throw new S.ErrnoError(70);if(w!=0&&w!=1&&w!=2)throw new S.ErrnoError(28);return a.position=a.stream_ops.llseek(a,p,w),a.ungotten=[],a.position},read(a,p,w,m,d){if(m<0||d<0)throw new S.ErrnoError(28);if(S.isClosed(a))throw new S.ErrnoError(8);if((a.flags&2097155)===1)throw new S.ErrnoError(8);if(S.isDir(a.node.mode))throw new S.ErrnoError(31);if(!a.stream_ops.read)throw new S.ErrnoError(28);var h=typeof d<"u";if(!h)d=a.position;else if(!a.seekable)throw new S.ErrnoError(70);var y=a.stream_ops.read(a,p,w,m,d);if(!h)a.position+=y;return y},write(a,p,w,m,d,h){if(m<0||d<0)throw new S.ErrnoError(28);if(S.isClosed(a))throw new S.ErrnoError(8);if((a.flags&2097155)===0)throw new S.ErrnoError(8);if(S.isDir(a.node.mode))throw new S.ErrnoError(31);if(!a.stream_ops.write)throw new S.ErrnoError(28);if(a.seekable&&a.flags&1024)S.llseek(a,0,2);var y=typeof d<"u";if(!y)d=a.position;else if(!a.seekable)throw new S.ErrnoError(70);var D=a.stream_ops.write(a,p,w,m,d,h);if(!y)a.position+=D;return D},mmap(a,p,w,m,d){if((m&2)!==0&&(d&2)===0&&(a.flags&2097155)!==2)throw new S.ErrnoError(2);if((a.flags&2097155)===1)throw new S.ErrnoError(2);if(!a.stream_ops.mmap)throw new S.ErrnoError(43);if(!p)throw new S.ErrnoError(28);return a.stream_ops.mmap(a,p,w,m,d)},msync(a,p,w,m,d){if(!a.stream_ops.msync)return 0;return a.stream_ops.msync(a,p,w,m,d)},ioctl(a,p,w){if(!a.stream_ops.ioctl)throw new S.ErrnoError(59);return a.stream_ops.ioctl(a,p,w)},readFile(a,p={}){if(p.flags=p.flags||0,p.encoding=p.encoding||"binary",p.encoding!=="utf8"&&p.encoding!=="binary")Pe(`Invalid encoding type "${p.encoding}"`);var w=S.open(a,p.flags),m=S.stat(a).size,d=new Uint8Array(m);if(S.read(w,d,0,m,0),p.encoding==="utf8")d=Wo(d);return S.close(w),d},writeFile(a,p,w={}){w.flags=w.flags||577;var m=S.open(a,w.flags,w.mode);p=rd(p),S.write(m,p,0,p.byteLength,void 0,w.canOwn),S.close(m)},cwd:()=>S.currentPath,chdir(a){var p=S.lookupPath(a,{follow:!0});if(p.node===null)throw new S.ErrnoError(44);if(!S.isDir(p.node.mode))throw new S.ErrnoError(54);var w=S.nodePermissions(p.node,"x");if(w)throw new S.ErrnoError(w);S.currentPath=p.path},createDefaultDirectories(){S.mkdir("/tmp"),S.mkdir("/home"),S.mkdir("/home/web_user")},createDefaultDevices(){S.mkdir("/dev"),S.registerDevice(S.makedev(1,3),{read:()=>0,write:(m,d,h,y,D)=>y,llseek:()=>0}),S.mkdev("/dev/null",S.makedev(1,3)),dn.register(S.makedev(5,0),dn.default_tty_ops),dn.register(S.makedev(6,0),dn.default_tty1_ops),S.mkdev("/dev/tty",S.makedev(5,0)),S.mkdev("/dev/tty1",S.makedev(6,0));var a=new Uint8Array(1024),p=0,w=()=>{if(p===0)Ju(a),p=a.byteLength;return a[--p]};S.createDevice("/dev","random",w),S.createDevice("/dev","urandom",w),S.mkdir("/dev/shm"),S.mkdir("/dev/shm/tmp")},createSpecialDirectories(){S.mkdir("/proc");var a=S.mkdir("/proc/self");S.mkdir("/proc/self/fd"),S.mount({mount(){var p=S.createNode(a,"fd",16895,73);return p.stream_ops={llseek:Ge.stream_ops.llseek},p.node_ops={lookup(w,m){var d=+m,h=S.getStreamChecked(d),y={parent:null,mount:{mountpoint:"fake"},node_ops:{readlink:()=>h.path},id:d+1};return y.parent=y,y},readdir(){return Array.from(S.streams.entries()).filter(([w,m])=>m).map(([w,m])=>w.toString())}},p}},{},"/proc/self/fd")},createStandardStreams(a,p,w){if(a)S.createDevice("/dev","stdin",a);else S.symlink("/dev/tty","/dev/stdin");if(p)S.createDevice("/dev","stdout",null,p);else S.symlink("/dev/tty","/dev/stdout");if(w)S.createDevice("/dev","stderr",null,w);else S.symlink("/dev/tty1","/dev/stderr");S.open("/dev/stdin",0),S.open("/dev/stdout",1),S.open("/dev/stderr",1)},staticInit(){S.nameTable=Array(4096),S.mount(Ge,{},"/"),S.createDefaultDirectories(),S.createDefaultDevices(),S.createSpecialDirectories(),S.filesystems={MEMFS:Ge}},init(a,p,w){S.initialized=!0,a??=r.stdin,p??=r.stdout,w??=r.stderr,S.createStandardStreams(a,p,w)},quit(){S.initialized=!1;for(var a of S.streams)if(a)S.close(a)},findObject(a,p){var w=S.analyzePath(a,p);if(!w.exists)return null;return w.object},analyzePath(a,p){try{var w=S.lookupPath(a,{follow:!p});a=w.path}catch(d){}var m={isRoot:!1,exists:!1,error:0,name:null,path:null,object:null,parentExists:!1,parentPath:null,parentObject:null};try{var w=S.lookupPath(a,{parent:!0});m.parentExists=!0,m.parentPath=w.path,m.parentObject=w.node,m.name=dt.basename(a),w=S.lookupPath(a,{follow:!p}),m.exists=!0,m.path=w.path,m.object=w.node,m.name=w.node.name,m.isRoot=w.path==="/"}catch(d){m.error=d.errno}return m},createPath(a,p,w,m){a=typeof a=="string"?a:S.getPath(a);var d=p.split("/").reverse();while(d.length){var h=d.pop();if(!h)continue;var y=dt.join2(a,h);try{S.mkdir(y)}catch(D){if(D.errno!=20)throw D}a=y}return y},createFile(a,p,w,m,d){var h=dt.join2(typeof a=="string"?a:S.getPath(a),p),y=Ma(m,d);return S.create(h,y)},createDataFile(a,p,w,m,d,h){var y=p;if(a)a=typeof a=="string"?a:S.getPath(a),y=p?dt.join2(a,p):a;var D=Ma(m,d),x=S.create(y,D);if(w){w=rd(w),S.chmod(x,D|146);var q=S.open(x,577);S.write(q,w,0,w.length,0,h),S.close(q),S.chmod(x,D)}},createDevice(a,p,w,m){var d=dt.join2(typeof a=="string"?a:S.getPath(a),p),h=Ma(!!w,!!m);S.createDevice.major??=64;var y=S.makedev(S.createDevice.major++,0);return S.registerDevice(y,{open(D){D.seekable=!1},close(D){if(m?.buffer?.length)m(10)},read(D,x,q,ee,V){var U=0;for(var B=0;B<ee;B++){var K;try{K=w()}catch(Y){throw new S.ErrnoError(29)}if(K===void 0&&U===0)throw new S.ErrnoError(6);if(K===null||K===void 0)break;U++,x[q+B]=K}if(U)D.node.atime=Date.now();return U},write(D,x,q,ee,V){for(var U=0;U<ee;U++)try{m(x[q+U])}catch(B){throw new S.ErrnoError(29)}if(ee)D.node.mtime=D.node.ctime=Date.now();return U}}),S.mkdev(d,h,y)},forceLoadFile(a){if(a.isDevice||a.isFolder||a.link||a.contents)return!0;if(globalThis.XMLHttpRequest)Pe("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{a.contents=f(a.url)}catch(p){throw new S.ErrnoError(29)}},createLazyFile(a,p,w,m,d){class h{lengthKnown=!1;chunks=[];get(ee){if(ee>this.length-1||ee<0)return;var V=ee%this.chunkSize,U=ee/this.chunkSize|0;return this.getter(U)[V]}setDataGetter(ee){this.getter=ee}cacheLength(){var ee=new XMLHttpRequest;if(ee.open("HEAD",w,!1),ee.send(null),!(ee.status>=200&&ee.status<300||ee.status===304))Pe("Couldn't load "+w+". Status: "+ee.status);var V=Number(ee.getResponseHeader("Content-length")),U,B=(U=ee.getResponseHeader("Accept-Ranges"))&&U==="bytes",K=(U=ee.getResponseHeader("Content-Encoding"))&&U==="gzip",Y=1048576;if(!B)Y=V;var ye=(I,ne)=>{if(I>ne)Pe("invalid range ("+I+", "+ne+") or no bytes requested!");if(ne>V-1)Pe("only "+V+" bytes available! programmer error!");var ie=new XMLHttpRequest;if(ie.open("GET",w,!1),V!==Y)ie.setRequestHeader("Range","bytes="+I+"-"+ne);if(ie.responseType="arraybuffer",ie.overrideMimeType)ie.overrideMimeType("text/plain; charset=x-user-defined");if(ie.send(null),!(ie.status>=200&&ie.status<300||ie.status===304))Pe("Couldn't load "+w+". Status: "+ie.status);if(ie.response!==void 0)return new Uint8Array(ie.response||[]);return $a(ie.responseText||"",!0)},P=this;if(P.setDataGetter((I)=>{var ne=I*Y,ie=(I+1)*Y-1;if(ie=Math.min(ie,V-1),typeof P.chunks[I]>"u")P.chunks[I]=ye(ne,ie);if(typeof P.chunks[I]>"u")Pe("doXHR failed!");return P.chunks[I]}),K||!V)Y=V=1,V=this.getter(0).length,Y=V,_("LazyFiles on gzip forces download of the whole file when length is accessed");this._length=V,this._chunkSize=Y,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)Pe("Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc");var y={isDevice:!1,contents:new h}}else var y={isDevice:!1,url:w};var D=S.createFile(a,p,y,m,d);if(y.contents)D.contents=y.contents;else if(y.url)D.contents=null,D.url=y.url;Object.defineProperties(D,{usedBytes:{get:function(){return this.contents.length}}});var x={};for(let[ee,V]of Object.entries(D.stream_ops))x[ee]=(...U)=>(S.forceLoadFile(D),V(...U));function q(ee,V,U,B,K){var Y=ee.node.contents;if(K>=Y.length)return 0;var ye=Math.min(Y.length-K,B);if(Y.slice)for(var P=0;P<ye;P++)V[U+P]=Y[K+P];else for(var P=0;P<ye;P++)V[U+P]=Y.get(K+P);return ye}return x.read=(ee,V,U,B,K)=>(S.forceLoadFile(D),q(ee,V,U,B,K)),x.mmap=(ee,V,U,B,K)=>{S.forceLoadFile(D);var Y=td(V);if(!Y)throw new S.ErrnoError(48);return q(ee,yr,Y,V,U),{ptr:Y,allocated:!0}},D.stream_ops=x,D}},rv=(a,p,w)=>{if(!a)return"";var m=Yu(Tn,a,p,w);return Xu.decode(Tn.subarray(a,m))},et={calculateAt(a,p,w){if(dt.isAbs(p))return p;var m;if(a===-100)m=S.cwd();else m=et.getStreamFromFD(a).path;if(p.length==0){if(!w)throw new S.ErrnoError(44);return m}return m+"/"+p},writeStat(a,p){ft[a>>2]=p.dev,ft[a+4>>2]=p.mode,ft[a+8>>2]=p.nlink,ft[a+12>>2]=p.uid,ft[a+16>>2]=p.gid,ft[a+20>>2]=p.rdev,Xt[a+24>>3]=BigInt(p.size),ut[a+32>>2]=4096,ut[a+36>>2]=p.blocks;var w=p.atime.getTime(),m=p.mtime.getTime(),d=p.ctime.getTime();return Xt[a+40>>3]=BigInt(Math.floor(w/1000)),ft[a+48>>2]=w%1000*1000*1000,Xt[a+56>>3]=BigInt(Math.floor(m/1000)),ft[a+64>>2]=m%1000*1000*1000,Xt[a+72>>3]=BigInt(Math.floor(d/1000)),ft[a+80>>2]=d%1000*1000*1000,Xt[a+88>>3]=BigInt(p.ino),0},writeStatFs(a,p){ft[a+4>>2]=p.bsize,ft[a+60>>2]=p.bsize,Xt[a+8>>3]=BigInt(p.blocks),Xt[a+16>>3]=BigInt(p.bfree),Xt[a+24>>3]=BigInt(p.bavail),Xt[a+32>>3]=BigInt(p.files),Xt[a+40>>3]=BigInt(p.ffree),ft[a+48>>2]=p.fsid,ft[a+64>>2]=p.flags,ft[a+56>>2]=p.namelen},doMsync(a,p,w,m,d){if(!S.isFile(p.node.mode))throw new S.ErrnoError(43);if(m&2)return 0;var h=Tn.slice(a,a+w);S.msync(p,h,d,w,m)},getStreamFromFD(a){return S.getStreamChecked(a)},varargs:void 0,getStr(a){return rv(a)}};function nv(a,p){try{return a=et.getStr(a),S.chmod(a,p),0}catch(w){if(typeof S>"u"||w.name!=="ErrnoError")throw w;return-w.errno}}function ov(a,p,w,m){try{if(p=et.getStr(p),p=et.calculateAt(a,p),w&-8)return-28;var d=S.lookupPath(p,{follow:!0}).node;if(!d)return-44;var h="";if(w&4)h+="r";if(w&2)h+="w";if(w&1)h+="x";if(h&&S.nodePermissions(d,h))return-2;return 0}catch(y){if(typeof S>"u"||y.name!=="ErrnoError")throw y;return-y.errno}}function iv(a,p){try{return S.fchmod(a,p),0}catch(w){if(typeof S>"u"||w.name!=="ErrnoError")throw w;return-w.errno}}function sv(a,p,w){try{return S.fchown(a,p,w),0}catch(m){if(typeof S>"u"||m.name!=="ErrnoError")throw m;return-m.errno}}var Hi=()=>{var a=ut[+et.varargs>>2];return et.varargs+=4,a},co=Hi;function av(a,p,w){et.varargs=w;try{var m=et.getStreamFromFD(a);switch(p){case 0:var d=Hi();if(d<0)return-28;while(S.streams[d])d++;return S.dupStream(m,d).fd;case 1:case 2:return 0;case 3:return m.flags;case 4:var d=Hi();return m.flags|=d,0;case 12:var d=co(),h=0;return Ho[d+h>>1]=2,0;case 13:case 14:return 0}return-28}catch(y){if(typeof S>"u"||y.name!=="ErrnoError")throw y;return-y.errno}}function cv(a,p){try{return et.writeStat(p,S.fstat(a))}catch(w){if(typeof S>"u"||w.name!=="ErrnoError")throw w;return-w.errno}}var lv=9007199254740992,uv=-9007199254740992,lo=(a)=>a<uv||a>lv?NaN:Number(a);function dv(a,p){p=lo(p);try{if(isNaN(p))return-61;return S.ftruncate(a,p),0}catch(w){if(typeof S>"u"||w.name!=="ErrnoError")throw w;return-w.errno}}var An=(a,p,w)=>Qu(a,Tn,p,w);function pv(a,p){try{if(p===0)return-28;var w=S.cwd(),m=ji(w)+1;if(p<m)return-68;return An(w,a,p),m}catch(d){if(typeof S>"u"||d.name!=="ErrnoError")throw d;return-d.errno}}function fv(a,p,w){et.varargs=w;try{var m=et.getStreamFromFD(a);switch(p){case 21509:if(!m.tty)return-59;return 0;case 21505:if(!m.tty)return-59;if(m.tty.ops.ioctl_tcgets){var d=m.tty.ops.ioctl_tcgets(m),V=co();ut[V>>2]=d.c_iflag||0,ut[V+4>>2]=d.c_oflag||0,ut[V+8>>2]=d.c_cflag||0,ut[V+12>>2]=d.c_lflag||0;for(var h=0;h<32;h++)yr[V+h+17]=d.c_cc[h]||0;return 0}return 0;case 21510:case 21511:case 21512:if(!m.tty)return-59;return 0;case 21506:case 21507:case 21508:if(!m.tty)return-59;if(m.tty.ops.ioctl_tcsets){var V=co(),y=ut[V>>2],D=ut[V+4>>2],x=ut[V+8>>2],q=ut[V+12>>2],ee=[];for(var h=0;h<32;h++)ee.push(yr[V+h+17]);return m.tty.ops.ioctl_tcsets(m.tty,p,{c_iflag:y,c_oflag:D,c_cflag:x,c_lflag:q,c_cc:ee})}return 0;case 21519:if(!m.tty)return-59;var V=co();return ut[V>>2]=0,0;case 21520:if(!m.tty)return-59;return-28;case 21537:case 21531:var V=co();return S.ioctl(m,p,V);case 21523:if(!m.tty)return-59;if(m.tty.ops.ioctl_tiocgwinsz){var U=m.tty.ops.ioctl_tiocgwinsz(m.tty),V=co();Ho[V>>1]=U[0],Ho[V+2>>1]=U[1]}return 0;case 21524:if(!m.tty)return-59;return 0;case 21515:if(!m.tty)return-59;return 0;default:return-28}}catch(B){if(typeof S>"u"||B.name!=="ErrnoError")throw B;return-B.errno}}function hv(a,p){try{return a=et.getStr(a),et.writeStat(p,S.lstat(a))}catch(w){if(typeof S>"u"||w.name!=="ErrnoError")throw w;return-w.errno}}function gv(a,p,w){try{return p=et.getStr(p),p=et.calculateAt(a,p),S.mkdir(p,w,0),0}catch(m){if(typeof S>"u"||m.name!=="ErrnoError")throw m;return-m.errno}}function mv(a,p,w,m){try{p=et.getStr(p);var d=m&256,h=m&4096;return m=m&-6401,p=et.calculateAt(a,p,h),et.writeStat(w,d?S.lstat(p):S.stat(p))}catch(y){if(typeof S>"u"||y.name!=="ErrnoError")throw y;return-y.errno}}function _v(a,p,w,m){et.varargs=m;try{p=et.getStr(p),p=et.calculateAt(a,p);var d=m?Hi():0;return S.open(p,w,d).fd}catch(h){if(typeof S>"u"||h.name!=="ErrnoError")throw h;return-h.errno}}function yv(a,p,w,m){try{if(p=et.getStr(p),p=et.calculateAt(a,p),m<=0)return-28;var d=S.readlink(p),h=Math.min(m,ji(d)),y=yr[w+h];return An(d,w,m+1),yr[w+h]=y,h}catch(D){if(typeof S>"u"||D.name!=="ErrnoError")throw D;return-D.errno}}function bv(a){try{return a=et.getStr(a),S.rmdir(a),0}catch(p){if(typeof S>"u"||p.name!=="ErrnoError")throw p;return-p.errno}}function wv(a,p){try{return a=et.getStr(a),et.writeStat(p,S.stat(a))}catch(w){if(typeof S>"u"||w.name!=="ErrnoError")throw w;return-w.errno}}function vv(a,p,w){try{if(p=et.getStr(p),p=et.calculateAt(a,p),!w)S.unlink(p);else if(w===512)S.rmdir(p);else return-28;return 0}catch(m){if(typeof S>"u"||m.name!=="ErrnoError")throw m;return-m.errno}}var id=(a)=>ft[a>>2]+ut[a+4>>2]*4294967296;function Ev(a,p,w,m){try{p=et.getStr(p),p=et.calculateAt(a,p,!0);var d=Date.now(),h,y;if(!w)h=d,y=d;else{var D=id(w),x=ut[w+8>>2];if(x==1073741823)h=d;else if(x==1073741822)h=null;else h=D*1000+x/1e6;if(w+=16,D=id(w),x=ut[w+8>>2],x==1073741823)y=d;else if(x==1073741822)y=null;else y=D*1000+x/1e6}if((y??h)!==null)S.utime(p,h,y);return 0}catch(q){if(typeof S>"u"||q.name!=="ErrnoError")throw q;return-q.errno}}var Sv=(a)=>a%4===0&&(a%100!==0||a%400===0),kv=[0,31,60,91,121,152,182,213,244,274,305,335],xv=[0,31,59,90,120,151,181,212,243,273,304,334],Rv=(a)=>(Sv(a.getFullYear())?kv:xv)[a.getMonth()]+a.getDate()-1;function Tv(a,p){a=lo(a);var w=new Date(a*1000);ut[p>>2]=w.getSeconds(),ut[p+4>>2]=w.getMinutes(),ut[p+8>>2]=w.getHours(),ut[p+12>>2]=w.getDate(),ut[p+16>>2]=w.getMonth(),ut[p+20>>2]=w.getFullYear()-1900,ut[p+24>>2]=w.getDay();var m=Rv(w)|0;ut[p+28>>2]=m,ut[p+36>>2]=-(w.getTimezoneOffset()*60);var d=new Date(w.getFullYear(),0,1),h=new Date(w.getFullYear(),6,1).getTimezoneOffset(),y=d.getTimezoneOffset(),D=(h!=y&&w.getTimezoneOffset()==Math.min(y,h))|0;ut[p+32>>2]=D}function Dv(a,p,w,m,d,h,y){d=lo(d);try{var D=et.getStreamFromFD(m),x=S.mmap(D,a,d,p,w),q=x.ptr;return ut[h>>2]=x.allocated,ft[y>>2]=q,0}catch(ee){if(typeof S>"u"||ee.name!=="ErrnoError")throw ee;return-ee.errno}}function Av(a,p,w,m,d,h){h=lo(h);try{var y=et.getStreamFromFD(d);if(w&2)et.doMsync(a,y,p,m,h)}catch(D){if(typeof S>"u"||D.name!=="ErrnoError")throw D;return-D.errno}}var Ov=(a,p,w,m)=>{var d=new Date().getFullYear(),h=new Date(d,0,1),y=new Date(d,6,1),D=h.getTimezoneOffset(),x=y.getTimezoneOffset(),q=Math.max(D,x);ft[a>>2]=q*60,ut[p>>2]=Number(D!=x);var ee=(B)=>{var K=B>=0?"-":"+",Y=Math.abs(B);return`UTC${K}${String(Math.floor(Y/60)).padStart(2,"0")}${String(Y%60).padStart(2,"0")}`},V=ee(D),U=ee(x);if(x<D)An(V,w,17),An(U,m,17);else An(V,m,17),An(U,w,17)},sd=()=>performance.now(),ad=()=>Date.now(),Cv=1,Iv=(a)=>a>=0&&a<=3;function Nv(a,p,w){if(p=lo(p),!Iv(a))return 28;var m;if(a===0)m=ad();else if(Cv)m=sd();else return 52;var d=Math.round(m*1000*1000);return Xt[w>>3]=BigInt(d),0}var cd=()=>2147483648,Pv=()=>cd(),qv=(a)=>{var p=(a-Jr.buffer.byteLength+65535)/65536|0;try{return Jr.grow(p),te(),1}catch(w){}},Lv=(a)=>{var p=Tn.length;a>>>=0;var w=cd();if(a>w)return!1;for(var m=1;m<=4;m*=2){var d=p*(1+0.2/m);if(d=Math.min(d,a+100663296),qv(Math.min(w,ed(Math.max(a,d),65536))))return!0}return!1},Fa={},$v=()=>i||"./this.program",Zo=()=>{if(!Zo.strings){var a={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(globalThis.navigator?.language??"C").replace("-","_")+".UTF-8",_:$v()};for(var p in Fa)if(Fa[p]===void 0)delete a[p];else a[p]=Fa[p];var w=[];for(var p in a)w.push(`${p}=${a[p]}`);Zo.strings=w}return Zo.strings},Mv=(a,p)=>{var w=0,m=0;for(var d of Zo()){var h=p+w;ft[a+m>>2]=h,w+=An(d,h,1/0)+1,m+=4}return 0},Fv=(a,p)=>{var w=Zo();ft[a>>2]=w.length;var m=0;for(var d of w)m+=ji(d)+1;return ft[p>>2]=m,0};function zv(a){try{var p=et.getStreamFromFD(a);return S.close(p),0}catch(w){if(typeof S>"u"||w.name!=="ErrnoError")throw w;return w.errno}}function Uv(a,p){try{var w=0,m=0,d=0,h=et.getStreamFromFD(a),y=h.tty?2:S.isDir(h.mode)?3:S.isLink(h.mode)?7:4;return yr[p]=y,Ho[p+2>>1]=d,Xt[p+8>>3]=BigInt(w),Xt[p+16>>3]=BigInt(m),0}catch(D){if(typeof S>"u"||D.name!=="ErrnoError")throw D;return D.errno}}var Bv=(a,p,w,m)=>{var d=0;for(var h=0;h<w;h++){var y=ft[p>>2],D=ft[p+4>>2];p+=8;var x=S.read(a,yr,y,D,m);if(x<0)return-1;if(d+=x,x<D)break;if(typeof m<"u")m+=x}return d};function jv(a,p,w,m){try{var d=Bv(et.getStreamFromFD(a),p,w);return ft[m>>2]=d,0}catch(h){if(typeof S>"u"||h.name!=="ErrnoError")throw h;return h.errno}}function Hv(a,p,w,m){p=lo(p);try{if(isNaN(p))return 61;var d=et.getStreamFromFD(a);if(S.llseek(d,p,w),Xt[m>>3]=BigInt(d.position),d.getdents&&p===0&&w===0)d.getdents=null;return 0}catch(h){if(typeof S>"u"||h.name!=="ErrnoError")throw h;return h.errno}}function Wv(a){try{var p=et.getStreamFromFD(a);return p.stream_ops?.fsync?.(p)}catch(w){if(typeof S>"u"||w.name!=="ErrnoError")throw w;return w.errno}}var Vv=(a,p,w,m)=>{var d=0;for(var h=0;h<w;h++){var y=ft[p>>2],D=ft[p+4>>2];p+=8;var x=S.write(a,yr,y,D,m);if(x<0)return-1;if(d+=x,x<D)break;if(typeof m<"u")m+=x}return d};function Zv(a,p,w,m){try{var d=Vv(et.getStreamFromFD(a),p,w);return ft[m>>2]=d,0}catch(h){if(typeof S>"u"||h.name!=="ErrnoError")throw h;return h.errno}}if(S.createPreloadedFile=tv,S.preloadFile=od,S.staticInit(),ce(),r.noExitRuntime)r.noExitRuntime;if(r.preloadPlugins)nd=r.preloadPlugins;if(r.print)_=r.print;if(r.printErr)E=r.printErr;if(r.wasmBinary)g=r.wasmBinary;if(r.arguments)r.arguments;if(r.thisProgram)i=r.thisProgram;if(r.preInit){if(typeof r.preInit=="function")r.preInit=[r.preInit];while(r.preInit.length>0)r.preInit.shift()()}r.wasmMemory=Jr;var ld;function Gv(a){r._sqlite3_status64=a.sqlite3_status64,r._sqlite3_status=a.sqlite3_status,r._sqlite3_db_status64=a.sqlite3_db_status64,r._sqlite3_msize=a.sqlite3_msize,r._sqlite3_db_status=a.sqlite3_db_status,r._sqlite3_vfs_find=a.sqlite3_vfs_find,r._sqlite3_initialize=a.sqlite3_initialize,r._sqlite3_malloc=a.sqlite3_malloc,r._sqlite3_free=a.sqlite3_free,r._sqlite3_vfs_register=a.sqlite3_vfs_register,r._sqlite3_vfs_unregister=a.sqlite3_vfs_unregister,r._sqlite3_malloc64=a.sqlite3_malloc64,r._sqlite3_realloc=a.sqlite3_realloc,r._sqlite3_realloc64=a.sqlite3_realloc64,r._sqlite3_value_text=a.sqlite3_value_text,r._sqlite3_randomness=a.sqlite3_randomness,r._sqlite3_stricmp=a.sqlite3_stricmp,r._sqlite3_strnicmp=a.sqlite3_strnicmp,r._sqlite3_uri_parameter=a.sqlite3_uri_parameter,r._sqlite3_uri_boolean=a.sqlite3_uri_boolean,r._sqlite3_serialize=a.sqlite3_serialize,r._sqlite3_prepare_v2=a.sqlite3_prepare_v2,r._sqlite3_step=a.sqlite3_step,r._sqlite3_column_int64=a.sqlite3_column_int64,r._sqlite3_reset=a.sqlite3_reset,r._sqlite3_exec=a.sqlite3_exec,r._sqlite3_column_int=a.sqlite3_column_int,r._sqlite3_finalize=a.sqlite3_finalize,r._sqlite3_file_control=a.sqlite3_file_control,r._sqlite3_column_name=a.sqlite3_column_name,r._sqlite3_column_text=a.sqlite3_column_text,r._sqlite3_column_type=a.sqlite3_column_type,r._sqlite3_errmsg=a.sqlite3_errmsg,r._sqlite3_deserialize=a.sqlite3_deserialize,r._sqlite3_clear_bindings=a.sqlite3_clear_bindings,r._sqlite3_value_blob=a.sqlite3_value_blob,r._sqlite3_value_bytes=a.sqlite3_value_bytes,r._sqlite3_value_double=a.sqlite3_value_double,r._sqlite3_value_int=a.sqlite3_value_int,r._sqlite3_value_int64=a.sqlite3_value_int64,r._sqlite3_value_subtype=a.sqlite3_value_subtype,r._sqlite3_value_pointer=a.sqlite3_value_pointer,r._sqlite3_value_type=a.sqlite3_value_type,r._sqlite3_value_nochange=a.sqlite3_value_nochange,r._sqlite3_value_frombind=a.sqlite3_value_frombind,r._sqlite3_value_dup=a.sqlite3_value_dup,r._sqlite3_value_free=a.sqlite3_value_free,r._sqlite3_result_blob=a.sqlite3_result_blob,r._sqlite3_result_error_toobig=a.sqlite3_result_error_toobig,r._sqlite3_result_error_nomem=a.sqlite3_result_error_nomem,r._sqlite3_result_double=a.sqlite3_result_double,r._sqlite3_result_error=a.sqlite3_result_error,r._sqlite3_result_int=a.sqlite3_result_int,r._sqlite3_result_int64=a.sqlite3_result_int64,r._sqlite3_result_null=a.sqlite3_result_null,r._sqlite3_result_pointer=a.sqlite3_result_pointer,r._sqlite3_result_subtype=a.sqlite3_result_subtype,r._sqlite3_result_text=a.sqlite3_result_text,r._sqlite3_result_zeroblob=a.sqlite3_result_zeroblob,r._sqlite3_result_zeroblob64=a.sqlite3_result_zeroblob64,r._sqlite3_result_error_code=a.sqlite3_result_error_code,r._sqlite3_user_data=a.sqlite3_user_data,r._sqlite3_context_db_handle=a.sqlite3_context_db_handle,r._sqlite3_vtab_nochange=a.sqlite3_vtab_nochange,r._sqlite3_vtab_in_first=a.sqlite3_vtab_in_first,r._sqlite3_vtab_in_next=a.sqlite3_vtab_in_next,r._sqlite3_aggregate_context=a.sqlite3_aggregate_context,r._sqlite3_get_auxdata=a.sqlite3_get_auxdata,r._sqlite3_set_auxdata=a.sqlite3_set_auxdata,r._sqlite3_column_count=a.sqlite3_column_count,r._sqlite3_data_count=a.sqlite3_data_count,r._sqlite3_column_blob=a.sqlite3_column_blob,r._sqlite3_column_bytes=a.sqlite3_column_bytes,r._sqlite3_column_double=a.sqlite3_column_double,r._sqlite3_column_value=a.sqlite3_column_value,r._sqlite3_column_decltype=a.sqlite3_column_decltype,r._sqlite3_column_database_name=a.sqlite3_column_database_name,r._sqlite3_column_table_name=a.sqlite3_column_table_name,r._sqlite3_column_origin_name=a.sqlite3_column_origin_name,r._sqlite3_bind_blob=a.sqlite3_bind_blob,r._sqlite3_bind_double=a.sqlite3_bind_double,r._sqlite3_bind_int=a.sqlite3_bind_int,r._sqlite3_bind_int64=a.sqlite3_bind_int64,r._sqlite3_bind_null=a.sqlite3_bind_null,r._sqlite3_bind_pointer=a.sqlite3_bind_pointer,r._sqlite3_bind_text=a.sqlite3_bind_text,r._sqlite3_bind_zeroblob=a.sqlite3_bind_zeroblob,r._sqlite3_bind_parameter_count=a.sqlite3_bind_parameter_count,r._sqlite3_bind_parameter_name=a.sqlite3_bind_parameter_name,r._sqlite3_bind_parameter_index=a.sqlite3_bind_parameter_index,r._sqlite3_db_handle=a.sqlite3_db_handle,r._sqlite3_stmt_readonly=a.sqlite3_stmt_readonly,r._sqlite3_stmt_isexplain=a.sqlite3_stmt_isexplain,r._sqlite3_stmt_explain=a.sqlite3_stmt_explain,r._sqlite3_stmt_busy=a.sqlite3_stmt_busy,r._sqlite3_next_stmt=a.sqlite3_next_stmt,r._sqlite3_stmt_status=a.sqlite3_stmt_status,r._sqlite3_sql=a.sqlite3_sql,r._sqlite3_expanded_sql=a.sqlite3_expanded_sql,r._sqlite3_preupdate_old=a.sqlite3_preupdate_old,r._sqlite3_preupdate_count=a.sqlite3_preupdate_count,r._sqlite3_preupdate_depth=a.sqlite3_preupdate_depth,r._sqlite3_preupdate_blobwrite=a.sqlite3_preupdate_blobwrite,r._sqlite3_preupdate_new=a.sqlite3_preupdate_new,r._sqlite3_value_numeric_type=a.sqlite3_value_numeric_type,r._sqlite3_set_authorizer=a.sqlite3_set_authorizer,r._sqlite3_strglob=a.sqlite3_strglob,r._sqlite3_strlike=a.sqlite3_strlike,r._sqlite3_auto_extension=a.sqlite3_auto_extension,r._sqlite3_cancel_auto_extension=a.sqlite3_cancel_auto_extension,r._sqlite3_reset_auto_extension=a.sqlite3_reset_auto_extension,r._sqlite3_prepare_v3=a.sqlite3_prepare_v3,r._sqlite3_create_module=a.sqlite3_create_module,r._sqlite3_create_module_v2=a.sqlite3_create_module_v2,r._sqlite3_drop_modules=a.sqlite3_drop_modules,r._sqlite3_declare_vtab=a.sqlite3_declare_vtab,r._sqlite3_vtab_on_conflict=a.sqlite3_vtab_on_conflict,r._sqlite3_vtab_collation=a.sqlite3_vtab_collation,r._sqlite3_vtab_in=a.sqlite3_vtab_in,r._sqlite3_vtab_rhs_value=a.sqlite3_vtab_rhs_value,r._sqlite3_vtab_distinct=a.sqlite3_vtab_distinct,r._sqlite3_keyword_name=a.sqlite3_keyword_name,r._sqlite3_keyword_count=a.sqlite3_keyword_count,r._sqlite3_keyword_check=a.sqlite3_keyword_check,r._sqlite3_complete=a.sqlite3_complete,r._sqlite3_libversion=a.sqlite3_libversion,r._sqlite3_libversion_number=a.sqlite3_libversion_number,r._sqlite3_shutdown=a.sqlite3_shutdown,r._sqlite3_last_insert_rowid=a.sqlite3_last_insert_rowid,r._sqlite3_set_last_insert_rowid=a.sqlite3_set_last_insert_rowid,r._sqlite3_changes64=a.sqlite3_changes64,r._sqlite3_changes=a.sqlite3_changes,r._sqlite3_total_changes64=a.sqlite3_total_changes64,r._sqlite3_total_changes=a.sqlite3_total_changes,r._sqlite3_txn_state=a.sqlite3_txn_state,r._sqlite3_close_v2=a.sqlite3_close_v2,r._sqlite3_busy_handler=a.sqlite3_busy_handler,r._sqlite3_progress_handler=a.sqlite3_progress_handler,r._sqlite3_busy_timeout=a.sqlite3_busy_timeout,r._sqlite3_interrupt=a.sqlite3_interrupt,r._sqlite3_is_interrupted=a.sqlite3_is_interrupted,r._sqlite3_create_function=a.sqlite3_create_function,r._sqlite3_create_function_v2=a.sqlite3_create_function_v2,r._sqlite3_create_window_function=a.sqlite3_create_window_function,r._sqlite3_overload_function=a.sqlite3_overload_function,r._sqlite3_trace_v2=a.sqlite3_trace_v2,r._sqlite3_commit_hook=a.sqlite3_commit_hook,r._sqlite3_update_hook=a.sqlite3_update_hook,r._sqlite3_rollback_hook=a.sqlite3_rollback_hook,r._sqlite3_preupdate_hook=a.sqlite3_preupdate_hook,r._sqlite3_set_errmsg=a.sqlite3_set_errmsg,r._sqlite3_error_offset=a.sqlite3_error_offset,r._sqlite3_errcode=a.sqlite3_errcode,r._sqlite3_extended_errcode=a.sqlite3_extended_errcode,r._sqlite3_errstr=a.sqlite3_errstr,r._sqlite3_limit=a.sqlite3_limit,r._sqlite3_open=a.sqlite3_open,r._sqlite3_open_v2=a.sqlite3_open_v2,r._sqlite3_create_collation=a.sqlite3_create_collation,r._sqlite3_create_collation_v2=a.sqlite3_create_collation_v2,r._sqlite3_collation_needed=a.sqlite3_collation_needed,r._sqlite3_get_autocommit=a.sqlite3_get_autocommit,r._sqlite3_table_column_metadata=a.sqlite3_table_column_metadata,r._sqlite3_extended_result_codes=a.sqlite3_extended_result_codes,r._sqlite3_uri_key=a.sqlite3_uri_key,r._sqlite3_uri_int64=a.sqlite3_uri_int64,r._sqlite3_db_name=a.sqlite3_db_name,r._sqlite3_db_filename=a.sqlite3_db_filename,r._sqlite3_db_readonly=a.sqlite3_db_readonly,r._sqlite3_compileoption_used=a.sqlite3_compileoption_used,r._sqlite3_compileoption_get=a.sqlite3_compileoption_get,r._sqlite3session_diff=a.sqlite3session_diff,r._sqlite3session_attach=a.sqlite3session_attach,r._sqlite3session_create=a.sqlite3session_create,r._sqlite3session_delete=a.sqlite3session_delete,r._sqlite3session_table_filter=a.sqlite3session_table_filter,r._sqlite3session_changeset=a.sqlite3session_changeset,r._sqlite3session_changeset_strm=a.sqlite3session_changeset_strm,r._sqlite3session_patchset_strm=a.sqlite3session_patchset_strm,r._sqlite3session_patchset=a.sqlite3session_patchset,r._sqlite3session_enable=a.sqlite3session_enable,r._sqlite3session_indirect=a.sqlite3session_indirect,r._sqlite3session_isempty=a.sqlite3session_isempty,r._sqlite3session_memory_used=a.sqlite3session_memory_used,r._sqlite3session_object_config=a.sqlite3session_object_config,r._sqlite3session_changeset_size=a.sqlite3session_changeset_size,r._sqlite3changeset_start=a.sqlite3changeset_start,r._sqlite3changeset_start_v2=a.sqlite3changeset_start_v2,r._sqlite3changeset_start_strm=a.sqlite3changeset_start_strm,r._sqlite3changeset_start_v2_strm=a.sqlite3changeset_start_v2_strm,r._sqlite3changeset_next=a.sqlite3changeset_next,r._sqlite3changeset_op=a.sqlite3changeset_op,r._sqlite3changeset_pk=a.sqlite3changeset_pk,r._sqlite3changeset_old=a.sqlite3changeset_old,r._sqlite3changeset_new=a.sqlite3changeset_new,r._sqlite3changeset_conflict=a.sqlite3changeset_conflict,r._sqlite3changeset_fk_conflicts=a.sqlite3changeset_fk_conflicts,r._sqlite3changeset_finalize=a.sqlite3changeset_finalize,r._sqlite3changeset_invert=a.sqlite3changeset_invert,r._sqlite3changeset_invert_strm=a.sqlite3changeset_invert_strm,r._sqlite3changeset_apply_v2=a.sqlite3changeset_apply_v2,r._sqlite3changeset_apply_v3=a.sqlite3changeset_apply_v3,r._sqlite3changeset_apply=a.sqlite3changeset_apply,r._sqlite3changeset_apply_v3_strm=a.sqlite3changeset_apply_v3_strm,r._sqlite3changeset_apply_v2_strm=a.sqlite3changeset_apply_v2_strm,r._sqlite3changeset_apply_strm=a.sqlite3changeset_apply_strm,r._sqlite3changegroup_new=a.sqlite3changegroup_new,r._sqlite3changegroup_add=a.sqlite3changegroup_add,r._sqlite3changegroup_output=a.sqlite3changegroup_output,r._sqlite3changegroup_add_strm=a.sqlite3changegroup_add_strm,r._sqlite3changegroup_output_strm=a.sqlite3changegroup_output_strm,r._sqlite3changegroup_delete=a.sqlite3changegroup_delete,r._sqlite3changeset_concat=a.sqlite3changeset_concat,r._sqlite3changeset_concat_strm=a.sqlite3changeset_concat_strm,r._sqlite3session_config=a.sqlite3session_config,r._sqlite3_sourceid=a.sqlite3_sourceid,r._sqlite3__wasm_pstack_ptr=a.sqlite3__wasm_pstack_ptr,r._sqlite3__wasm_pstack_restore=a.sqlite3__wasm_pstack_restore,r._sqlite3__wasm_pstack_alloc=a.sqlite3__wasm_pstack_alloc,r._sqlite3__wasm_pstack_remaining=a.sqlite3__wasm_pstack_remaining,r._sqlite3__wasm_pstack_quota=a.sqlite3__wasm_pstack_quota,r._sqlite3__wasm_test_struct=a.sqlite3__wasm_test_struct,r._sqlite3__wasm_enum_json=a.sqlite3__wasm_enum_json,r._sqlite3__wasm_vfs_unlink=a.sqlite3__wasm_vfs_unlink,r._sqlite3__wasm_db_vfs=a.sqlite3__wasm_db_vfs,r._sqlite3__wasm_db_reset=a.sqlite3__wasm_db_reset,r._sqlite3__wasm_db_export_chunked=a.sqlite3__wasm_db_export_chunked,r._sqlite3__wasm_db_serialize=a.sqlite3__wasm_db_serialize,r._sqlite3__wasm_vfs_create_file=a.sqlite3__wasm_vfs_create_file,r._sqlite3__wasm_posix_create_file=a.sqlite3__wasm_posix_create_file,r._sqlite3__wasm_kvvfsMakeKey=a.sqlite3__wasm_kvvfsMakeKey,r._sqlite3__wasm_kvvfs_methods=a.sqlite3__wasm_kvvfs_methods,r._sqlite3__wasm_vtab_config=a.sqlite3__wasm_vtab_config,r._sqlite3__wasm_db_config_ip=a.sqlite3__wasm_db_config_ip,r._sqlite3__wasm_db_config_pii=a.sqlite3__wasm_db_config_pii,r._sqlite3__wasm_db_config_s=a.sqlite3__wasm_db_config_s,r._sqlite3__wasm_config_i=a.sqlite3__wasm_config_i,r._sqlite3__wasm_config_ii=a.sqlite3__wasm_config_ii,r._sqlite3__wasm_config_j=a.sqlite3__wasm_config_j,r._sqlite3__wasm_qfmt_token=a.sqlite3__wasm_qfmt_token,r._sqlite3__wasm_kvvfs_decode=a.sqlite3__wasm_kvvfs_decode,r._sqlite3__wasm_kvvfs_encode=a.sqlite3__wasm_kvvfs_encode,r._sqlite3__wasm_init_wasmfs=a.sqlite3__wasm_init_wasmfs,r._sqlite3__wasm_test_intptr=a.sqlite3__wasm_test_intptr,r._sqlite3__wasm_test_voidptr=a.sqlite3__wasm_test_voidptr,r._sqlite3__wasm_test_int64_max=a.sqlite3__wasm_test_int64_max,r._sqlite3__wasm_test_int64_min=a.sqlite3__wasm_test_int64_min,r._sqlite3__wasm_test_int64_times2=a.sqlite3__wasm_test_int64_times2,r._sqlite3__wasm_test_int64_minmax=a.sqlite3__wasm_test_int64_minmax,r._sqlite3__wasm_test_int64ptr=a.sqlite3__wasm_test_int64ptr,r._sqlite3__wasm_test_stack_overflow=a.sqlite3__wasm_test_stack_overflow,r._sqlite3__wasm_test_str_hello=a.sqlite3__wasm_test_str_hello,r._sqlite3__wasm_SQLTester_strglob=a.sqlite3__wasm_SQLTester_strglob,r._malloc=a.malloc,r._free=a.free,r._realloc=a.realloc,ld=a.emscripten_builtin_memalign,a._emscripten_stack_restore,a._emscripten_stack_alloc,a.emscripten_stack_get_current,a.__indirect_function_table}var ud={__syscall_chmod:nv,__syscall_faccessat:ov,__syscall_fchmod:iv,__syscall_fchown32:sv,__syscall_fcntl64:av,__syscall_fstat64:cv,__syscall_ftruncate64:dv,__syscall_getcwd:pv,__syscall_ioctl:fv,__syscall_lstat64:hv,__syscall_mkdirat:gv,__syscall_newfstatat:mv,__syscall_openat:_v,__syscall_readlinkat:yv,__syscall_rmdir:bv,__syscall_stat64:wv,__syscall_unlinkat:vv,__syscall_utimensat:Ev,_localtime_js:Tv,_mmap_js:Dv,_munmap_js:Av,_tzset_js:Ov,clock_time_get:Nv,emscripten_date_now:ad,emscripten_get_heap_max:Pv,emscripten_get_now:sd,emscripten_resize_heap:Lv,environ_get:Mv,environ_sizes_get:Fv,fd_close:zv,fd_fdstat_get:Uv,fd_read:jv,fd_seek:Hv,fd_sync:Wv,fd_write:Zv,memory:Jr};function za(){if(Dn>0){Vo=za;return}if(de(),Dn>0){Vo=za;return}function a(){if(r.calledRun=!0,A)return;Ce(),L?.(r),r.onRuntimeInitialized?.(),ge()}if(r.setStatus)r.setStatus("Running..."),setTimeout(()=>{setTimeout(()=>r.setStatus(""),1),a()},1);else a()}var uo=await Kr();if(za(),r.runSQLite3PostLoadInit=async function(a,p,w){delete p.runSQLite3PostLoadInit,globalThis.sqlite3ApiBootstrap=async function m(d=globalThis.sqlite3ApiConfig||m.defaultConfig){if(m.sqlite3)return(m.sqlite3.config||console).warn("sqlite3ApiBootstrap() called multiple times.","Config and external initializers are ignored on calls after the first."),m.sqlite3;let h=(...O)=>Object.assign(Object.create(null),...O),y=h({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},d);Object.assign(y,{allocExportName:y.useStdAlloc?"malloc":"sqlite3_malloc",deallocExportName:y.useStdAlloc?"free":"sqlite3_free",reallocExportName:y.useStdAlloc?"realloc":"sqlite3_realloc"}),["exports","memory","functionTable","wasmfsOpfsDir"].forEach((O)=>{if(typeof y[O]==="function")y[O]=y[O]()});let D=h(),x=h(),q=(O)=>D.sqlite3_js_rc_str&&D.sqlite3_js_rc_str(O)||"Unknown result code #"+O,ee=(O)=>typeof O==="number"&&O===(O|0)&&O<=2147483647&&O>=-2147483648;class V extends Error{constructor(...O){let M;if(O.length)if(ee(O[0]))if(M=O[0],O.length===1)super(q(O[0]));else{let Q=q(M);if(typeof O[1]==="object")super(Q,O[1]);else{O[0]=Q+":";super(O.join(" "))}}else if(O.length===2&&typeof O[1]==="object")super(...O);else super(O.join(" "));this.resultCode=M||D.SQLITE_ERROR,this.name="SQLite3Error"}}V.toss=(...O)=>{throw new V(...O)};let U=V.toss;if(y.wasmfsOpfsDir&&!/^\/[^/]+$/.test(y.wasmfsOpfsDir))U("config.wasmfsOpfsDir must be falsy or in the form '/dir-name'.");let B=function O(M){if(!O._max)O._max=BigInt("0x7fffffffffffffff"),O._min=~O._max;return M>=O._min&&M<=O._max},K=(O)=>O>=-2147483647n-1n&&O<=2147483647n,Y=function O(M){if(!O._min)O._min=Number.MIN_SAFE_INTEGER,O._max=Number.MAX_SAFE_INTEGER;return M>=O._min&&M<=O._max},ye=(O)=>O&&O.constructor&&ee(O.constructor.BYTES_PER_ELEMENT)?O:!1,P=(O)=>O&&(O instanceof Uint8Array||O instanceof Int8Array||O instanceof ArrayBuffer),I=(O)=>O&&(O instanceof Uint8Array||O instanceof Int8Array||O instanceof ArrayBuffer),ne=(O)=>P(O)||U("Value is not of a supported TypedArray type."),ie=function(O){if(I(O))return x.typedArrayToString(O instanceof ArrayBuffer?new Uint8Array(O):O,0,O.length);else if(Array.isArray(O))return O.join("");else if(x.isPtr(O))O=x.cstrToJs(O);return O};class G extends Error{constructor(...O){if(O.length===2&&typeof O[1]==="object")super(...O);else if(O.length)super(O.join(" "));else super("Allocation failed.");this.resultCode=D.SQLITE_NOMEM,this.name="WasmAllocError"}}G.toss=(...O)=>{throw new G(...O)},Object.assign(D,{sqlite3_bind_blob:void 0,sqlite3_bind_text:void 0,sqlite3_create_function_v2:(O,M,Q,ue,J,Ee,xe,Se,Re)=>{},sqlite3_create_function:(O,M,Q,ue,J,Ee,xe,Se)=>{},sqlite3_create_window_function:(O,M,Q,ue,J,Ee,xe,Se,Re,H)=>{},sqlite3_prepare_v3:(O,M,Q,ue,J,Ee)=>{},sqlite3_prepare_v2:(O,M,Q,ue,J)=>{},sqlite3_exec:(O,M,Q,ue,J)=>{},sqlite3_randomness:(O,M)=>{}});let re={affirmBindableTypedArray:ne,flexibleString:ie,bigIntFits32:K,bigIntFits64:B,bigIntFitsDouble:Y,isBindableTypedArray:P,isInt32:ee,isSQLableTypedArray:I,isTypedArray:ye,isUIThread:()=>globalThis.window===globalThis&&!!globalThis.document,toss:function(...O){throw Error(O.join(" "))},toss3:U,typedArrayPart:x.typedArrayPart,nu:h,assert:function(O,M){if(!O)re.toss("Assertion failed:",M)},affirmDbHeader:function(O){if(O instanceof ArrayBuffer)O=new Uint8Array(O);let M="SQLite format 3";if(15>O.byteLength)U("Input does not contain an SQLite3 database header.");for(let Q=0;Q<15;++Q)if(M.charCodeAt(Q)!==O[Q])U("Input does not contain an SQLite3 database header.")},affirmIsDb:function(O){if(O instanceof ArrayBuffer)O=new Uint8Array(O);let M=O.byteLength;if(M<512||M%512!==0)U("Byte array size",M,"is invalid for an SQLite3 db.");re.affirmDbHeader(O)}};Object.assign(x,{exports:y.exports||U("Missing API config.exports (WASM module exports)."),memory:y.memory||y.exports.memory||U("API config object requires a WebAssembly.Memory object","in either config.exports.memory (exported)","or config.memory (imported)."),pointerSize:typeof y.exports.sqlite3_libversion()==="number"?4:8,bigIntEnabled:!!y.bigIntEnabled,functionTable:y.functionTable,alloc:void 0,realloc:void 0,dealloc:void 0}),x.allocFromTypedArray=function(O){if(O instanceof ArrayBuffer)O=new Uint8Array(O);ne(O);let M=x.alloc(O.byteLength||1);return x.heapForSize(O.constructor).set(O.byteLength?O:[0],Number(M)),M};{let{allocExportName:O,deallocExportName:M,reallocExportName:Q}=y;for(let ue of[O,M,Q])if(!(x.exports[ue]instanceof Function))U("Missing required exports[",ue,"] function.");x.alloc=function ue(J){return ue.impl(J)||G.toss("Failed to allocate",J," bytes.")},x.alloc.impl=x.exports[O],x.realloc=function ue(J,Ee){let xe=ue.impl(x.ptr.coerce(J),Ee);return Ee?xe||G.toss("Failed to reallocate",Ee," bytes."):x.ptr.null},x.realloc.impl=x.exports[Q],x.dealloc=function ue(J){ue.impl(x.ptr.coerce(J))},x.dealloc.impl=x.exports[M]}x.compileOptionUsed=function O(M){if(!arguments.length){if(O._result)return O._result;else if(!O._opt)O._rx=/^([^=]+)=(.+)/,O._rxInt=/^-?\d+$/,O._opt=function(xe,Se){let Re=O._rx.exec(xe);Se[0]=Re?Re[1]:xe,Se[1]=Re?O._rxInt.test(Re[2])?+Re[2]:Re[2]:!0};let Q=h(),ue=[0,0],J=0,Ee;while(Ee=D.sqlite3_compileoption_get(J++))O._opt(Ee,ue),Q[ue[0]]=ue[1];return O._result=Q}else if(Array.isArray(M)){let Q=h();return M.forEach((ue)=>{Q[ue]=D.sqlite3_compileoption_used(ue)}),Q}else if(typeof M==="object")return Object.keys(M).forEach((Q)=>{M[Q]=D.sqlite3_compileoption_used(Q)}),M;return typeof M==="string"?!!D.sqlite3_compileoption_used(M):!1},x.pstack=h({restore:x.exports.sqlite3__wasm_pstack_restore,alloc:function(O){if(typeof O==="string"&&!(O=x.sizeofIR(O)))G.toss("Invalid value for pstack.alloc(",arguments[0],")");return x.exports.sqlite3__wasm_pstack_alloc(O)||G.toss("Could not allocate",O,"bytes from the pstack.")},allocChunks:function(O,M){if(typeof M==="string"&&!(M=x.sizeofIR(M)))G.toss("Invalid size value for allocChunks(",arguments[1],")");let Q=x.pstack.alloc(O*M),ue=[Q],J=1,Ee=M;for(;J<O;++J,Ee+=M)ue.push(x.ptr.add(Q,Ee));return ue},allocPtr:(O=1,M=!0)=>O===1?x.pstack.alloc(M?8:x.ptr.size):x.pstack.allocChunks(O,M?8:x.ptr.size),call:function(O){let M=x.pstack.pointer;try{return O(ve)}finally{x.pstack.restore(M)}}}),Object.defineProperties(x.pstack,{pointer:{configurable:!1,iterable:!0,writeable:!1,get:x.exports.sqlite3__wasm_pstack_ptr},quota:{configurable:!1,iterable:!0,writeable:!1,get:x.exports.sqlite3__wasm_pstack_quota},remaining:{configurable:!1,iterable:!0,writeable:!1,get:x.exports.sqlite3__wasm_pstack_remaining}}),D.sqlite3_randomness=(...O)=>{if(O.length===1&&re.isTypedArray(O[0])&&O[0].BYTES_PER_ELEMENT===1){let M=O[0];if(M.byteLength===0)return x.exports.sqlite3_randomness(0,x.ptr.null),M;let Q=x.pstack.pointer;try{let ue=M.byteLength,J=0,Ee=x.exports.sqlite3_randomness,xe=x.heap8u(),Se=ue<512?ue:512,Re=x.pstack.alloc(Se);do{let H=ue>Se?Se:ue;Ee(H,Re),M.set(x.typedArrayPart(xe,Re,x.ptr.add(Re,H)),J),ue-=H,J+=H}while(ue>0)}catch(ue){y.error("Highly unexpected (and ignored!) exception in sqlite3_randomness():",ue)}finally{x.pstack.restore(Q)}return M}x.exports.sqlite3_randomness(...O)},D.sqlite3_wasmfs_opfs_dir=function(){if(this.dir!==void 0)return this.dir;let O=y.wasmfsOpfsDir;if(!O||!globalThis.FileSystemHandle||!globalThis.FileSystemDirectoryHandle||!globalThis.FileSystemFileHandle||!x.exports.sqlite3__wasm_init_wasmfs)return this.dir="";try{if(O&&x.xCallWrapped("sqlite3__wasm_init_wasmfs","i32",["string"],O)===0)return this.dir=O;else return this.dir=""}catch(M){return this.dir=""}}.bind(h()),D.sqlite3_wasmfs_filename_is_persistent=function(O){let M=D.sqlite3_wasmfs_opfs_dir();return M&&O?O.startsWith(M+"/"):!1},D.sqlite3_js_db_uses_vfs=function(O,M,Q=0){try{let ue=D.sqlite3_vfs_find(M);if(!ue)return!1;else if(!O)return ue===D.sqlite3_vfs_find(0)?ue:!1;else return ue===D.sqlite3_js_db_vfs(O,Q)?ue:!1}catch(ue){return!1}},D.sqlite3_js_vfs_list=function(){let O=[],M=D.sqlite3_vfs_find(x.ptr.null);while(M){let Q=new D.sqlite3_vfs(M);O.push(x.cstrToJs(Q.$zName)),M=Q.$pNext,Q.dispose()}return O},D.sqlite3_js_db_export=function(O,M=0){if(O=x.xWrap.testConvertArg("sqlite3*",O),!O)U("Invalid sqlite3* argument.");if(!x.bigIntEnabled)U("BigInt support is not enabled.");let Q=x.scopedAllocPush(),ue;try{let J=x.scopedAlloc(8+x.ptr.size),Ee=x.ptr.add(J,8),xe=M?x.isPtr(M)?M:x.scopedAllocCString(""+M):x.ptr.null,Se=x.exports.sqlite3__wasm_db_serialize(O,xe,Ee,J,0);if(Se)U("Database serialization failed with code",ve.capi.sqlite3_js_rc_str(Se));ue=x.peekPtr(Ee);let Re=x.peek(J,"i64");return Se=Re?x.heap8u().slice(Number(ue),Number(ue)+Number(Re)):new Uint8Array,Se}finally{if(ue)x.exports.sqlite3_free(ue);x.scopedAllocPop(Q)}},D.sqlite3_js_db_vfs=(O,M=x.ptr.null)=>re.sqlite3__wasm_db_vfs(O,M),D.sqlite3_js_aggregate_context=(O,M)=>D.sqlite3_aggregate_context(O,M)||(M?G.toss("Cannot allocate",M,"bytes for sqlite3_aggregate_context()"):0),D.sqlite3_js_posix_create_file=function(O,M,Q){let ue;if(M&&x.isPtr(M))ue=M;else if(M instanceof ArrayBuffer||M instanceof Uint8Array){if(ue=x.allocFromTypedArray(M),arguments.length<3||!re.isInt32(Q)||Q<0)Q=M.byteLength}else V.toss("Invalid 2nd argument for sqlite3_js_posix_create_file().");try{if(!re.isInt32(Q)||Q<0)V.toss("Invalid 3rd argument for sqlite3_js_posix_create_file().");let J=re.sqlite3__wasm_posix_create_file(O,ue,Q);if(J)V.toss("Creation of file failed with sqlite3 result code",D.sqlite3_js_rc_str(J))}finally{if(ue&&ue!==M)x.dealloc(ue)}},D.sqlite3_js_vfs_create_file=function(O,M,Q,ue){y.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 J;if(Q)if(x.isPtr(Q))J=Q;else{if(Q instanceof ArrayBuffer)Q=new Uint8Array(Q);if(Q instanceof Uint8Array){if(J=x.allocFromTypedArray(Q),arguments.length<4||!re.isInt32(ue)||ue<0)ue=Q.byteLength}else V.toss("Invalid 3rd argument type for sqlite3_js_vfs_create_file().")}else J=0;if(!re.isInt32(ue)||ue<0){if(J&&J!==Q)x.dealloc(J);V.toss("Invalid 4th argument for sqlite3_js_vfs_create_file().")}try{let Ee=re.sqlite3__wasm_vfs_create_file(O,M,J,ue);if(Ee)V.toss("Creation of file failed with sqlite3 result code",D.sqlite3_js_rc_str(Ee))}finally{if(J&&J!==Q)x.dealloc(J)}},D.sqlite3_js_sql_to_string=(O)=>{if(typeof O==="string")return O;let M=ie(v);return M===v?void 0:M},D.sqlite3_db_config=function(O,M,...Q){switch(M){case D.SQLITE_DBCONFIG_ENABLE_FKEY:case D.SQLITE_DBCONFIG_ENABLE_TRIGGER:case D.SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER:case D.SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION:case D.SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE:case D.SQLITE_DBCONFIG_ENABLE_QPSG:case D.SQLITE_DBCONFIG_TRIGGER_EQP:case D.SQLITE_DBCONFIG_RESET_DATABASE:case D.SQLITE_DBCONFIG_DEFENSIVE:case D.SQLITE_DBCONFIG_WRITABLE_SCHEMA:case D.SQLITE_DBCONFIG_LEGACY_ALTER_TABLE:case D.SQLITE_DBCONFIG_DQS_DML:case D.SQLITE_DBCONFIG_DQS_DDL:case D.SQLITE_DBCONFIG_ENABLE_VIEW:case D.SQLITE_DBCONFIG_LEGACY_FILE_FORMAT:case D.SQLITE_DBCONFIG_TRUSTED_SCHEMA:case D.SQLITE_DBCONFIG_STMT_SCANSTATUS:case D.SQLITE_DBCONFIG_REVERSE_SCANORDER:case D.SQLITE_DBCONFIG_ENABLE_ATTACH_CREATE:case D.SQLITE_DBCONFIG_ENABLE_ATTACH_WRITE:case D.SQLITE_DBCONFIG_ENABLE_COMMENTS:case D.SQLITE_DBCONFIG_FP_DIGITS:if(!this.ip)this.ip=x.xWrap("sqlite3__wasm_db_config_ip","int",["sqlite3*","int","int","*"]);return this.ip(O,M,Q[0],Q[1]||0);case D.SQLITE_DBCONFIG_LOOKASIDE:if(!this.pii)this.pii=x.xWrap("sqlite3__wasm_db_config_pii","int",["sqlite3*","int","*","int","int"]);return this.pii(O,M,Q[0],Q[1],Q[2]);case D.SQLITE_DBCONFIG_MAINDBNAME:if(!this.s)this.s=x.xWrap("sqlite3__wasm_db_config_s","int",["sqlite3*","int","string:static"]);return this.s(O,M,Q[0]);default:return D.SQLITE_MISUSE}}.bind(h()),D.sqlite3_value_to_js=function(O,M=!0){let Q,ue=D.sqlite3_value_type(O);switch(ue){case D.SQLITE_INTEGER:if(x.bigIntEnabled){if(Q=D.sqlite3_value_int64(O),re.bigIntFitsDouble(Q))Q=Number(Q)}else Q=D.sqlite3_value_double(O);break;case D.SQLITE_FLOAT:Q=D.sqlite3_value_double(O);break;case D.SQLITE_TEXT:Q=D.sqlite3_value_text(O);break;case D.SQLITE_BLOB:{let J=D.sqlite3_value_bytes(O),Ee=D.sqlite3_value_blob(O);if(J&&!Ee)ve.WasmAllocError.toss("Cannot allocate memory for blob argument of",J,"byte(s)");Q=J?x.heap8u().slice(Number(Ee),Number(Ee)+Number(J)):null;break}case D.SQLITE_NULL:Q=null;break;default:if(M)U(D.SQLITE_MISMATCH,"Unhandled sqlite3_value_type():",ue);Q=void 0}return Q},D.sqlite3_values_to_js=function(O,M,Q=!0){let ue,J=[];for(ue=0;ue<O;++ue)J.push(D.sqlite3_value_to_js(x.peekPtr(x.ptr.add(M,x.ptr.size*ue)),Q));return J},D.sqlite3_result_error_js=function(O,M){if(M instanceof G)D.sqlite3_result_error_nomem(O);else D.sqlite3_result_error(O,""+M,-1)},D.sqlite3_result_js=function(O,M){if(M instanceof Error){D.sqlite3_result_error_js(O,M);return}try{switch(typeof M){case"undefined":break;case"boolean":D.sqlite3_result_int(O,M?1:0);break;case"bigint":if(re.bigIntFits32(M))D.sqlite3_result_int(O,Number(M));else if(re.bigIntFitsDouble(M))D.sqlite3_result_double(O,Number(M));else if(x.bigIntEnabled)if(re.bigIntFits64(M))D.sqlite3_result_int64(O,M);else U("BigInt value",M.toString(),"is too BigInt for int64.");else U("BigInt value",M.toString(),"is too BigInt.");break;case"number":{let Q;if(re.isInt32(M))Q=D.sqlite3_result_int;else if(x.bigIntEnabled&&Number.isInteger(M)&&re.bigIntFits64(BigInt(M)))Q=D.sqlite3_result_int64;else Q=D.sqlite3_result_double;Q(O,M);break}case"string":{let[Q,ue]=x.allocCString(M,!0);D.sqlite3_result_text(O,Q,ue,D.SQLITE_WASM_DEALLOC);break}case"object":if(M===null){D.sqlite3_result_null(O);break}else if(re.isBindableTypedArray(M)){let Q=x.allocFromTypedArray(M);D.sqlite3_result_blob(O,Q,M.byteLength,D.SQLITE_WASM_DEALLOC);break}default:U("Don't not how to handle this UDF result value:",typeof M,M)}}catch(Q){D.sqlite3_result_error_js(O,Q)}},D.sqlite3_column_js=function(O,M,Q=!0){let ue=D.sqlite3_column_value(O,M);return ue===0?void 0:D.sqlite3_value_to_js(ue,Q)};{let O=function(M,Q,ue){if(ue=D[ue],!this.ptr)this.ptr=x.allocPtr();else x.pokePtr(this.ptr,0);let J=ue(M,Q,this.ptr);if(J)return V.toss(J,arguments[2]+"() failed with code "+J);let Ee=x.peekPtr(this.ptr);return Ee?D.sqlite3_value_to_js(Ee,!0):void 0}.bind(h());D.sqlite3_preupdate_new_js=(M,Q)=>O(M,Q,"sqlite3_preupdate_new"),D.sqlite3_preupdate_old_js=(M,Q)=>O(M,Q,"sqlite3_preupdate_old"),D.sqlite3changeset_new_js=(M,Q)=>O(M,Q,"sqlite3changeset_new"),D.sqlite3changeset_old_js=(M,Q)=>O(M,Q,"sqlite3changeset_old")}D.sqlite3_js_retry_busy=function(O,M,Q){for(let ue=1;ue<=O;++ue)try{if(Q&&ue>1)Q(ue);let J=M();if(D.SQLITE_BUSY===J){if(ue===O)throw new V(J,["sqlite3_js_retry_busy() max retry attempts (",O,") reached."].join(""));continue}return J}catch(J){if(ue<O&&J instanceof V&&J.resultCode===D.SQLITE_BUSY)continue;throw J}};let ve={WasmAllocError:G,SQLite3Error:V,capi:D,util:re,wasm:x,config:y,version:h(),client:void 0,asyncPostInit:async function O(){if(O.isReady instanceof Promise)return O.isReady;let M=this.initializersAsync;delete this.initializersAsync;let Q=async()=>{if(!ve.__isUnderTest)delete ve.util,delete ve.StructBinder,delete ve.opfs;return ve},ue=(Ee)=>{throw y.error("an async sqlite3 initializer failed:",Ee),Ee};if(!M||!M.length)return O.isReady=Q().catch(ue);M=M.map((Ee)=>Ee instanceof Function?async(xe)=>Ee(ve):Ee),M.push(Q);let J=Promise.resolve(ve);while(M.length)J=J.then(M.shift());return O.isReady=J.catch(ue)}.bind(m),scriptInfo:void 0};if(typeof w<"u")ve.__isUnderTest=!!w;try{m.initializers.forEach((O)=>{O(ve)})}catch(O){throw console.error("sqlite3 bootstrap initializer threw:",O),O}if(delete m.initializers,m.sqlite3=ve,typeof a<"u")a.debugModule("sqlite3ApiBootstrap() complete",ve),ve.scriptInfo=a;if(ve.__isUnderTest){if(typeof p<"u")ve.config.emscripten=p;let O=ve.scriptInfo?.instantiateWasm;if(O)ve.wasm.module=O.module,ve.wasm.instance=O.instance,ve.wasm.imports=O.imports}return delete globalThis.sqlite3ApiConfig,delete globalThis.sqlite3ApiBootstrap,delete m.defaultConfig,ve.asyncPostInit().then((O)=>{if(typeof a<"u")a.debugModule("sqlite3.asyncPostInit() complete",O);return delete O.asyncPostInit,delete O.scriptInfo,delete O.emscripten,O})},globalThis.sqlite3ApiBootstrap.initializers=[],globalThis.sqlite3ApiBootstrap.initializersAsync=[],globalThis.sqlite3ApiBootstrap.defaultConfig=Object.create(null),globalThis.sqlite3ApiBootstrap.sqlite3=void 0,globalThis.sqlite3ApiBootstrap.initializers.push(function(m){m.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(d){if(d.bigIntEnabled===void 0)d.bigIntEnabled=!!globalThis.BigInt64Array;let h=(...b)=>{throw Error(b.join(" "))};if(!d.pointerSize&&!d.pointerIR&&d.alloc&&d.dealloc){let b=d.alloc(1);d.pointerSize=typeof b==="bigint"?8:4,d.dealloc(b)}if(d.pointerSize&&!d.pointerIR)d.pointerIR=d.pointerSize===4?"i32":"i64";let y=d.pointerIR??="i32",D=d.pointerSize??=y==="i32"?4:y==="i64"?8:0;if(delete d.pointerSize,delete d.pointerIR,y!=="i32"&&y!=="i64")h("Invalid pointerIR:",y);else if(D!==8&&D!==4)h("Invalid pointerSize:",D);let x=d.bigIntEnabled?(b)=>BigInt(b||0):(b)=>h("BigInt support is disabled in this build."),ee=D===4?(b)=>Number(b||0):x,V=ee(0),U=function(...b){let R=ee(0);for(let C of b)R+=ee(C);return R};{let b=Object.create(null);Object.defineProperty(d,"ptr",{enumerable:!0,get:()=>b,set:()=>h("The ptr property is read-only.")}),function R(C,z){return Object.defineProperty(b,C,{enumerable:!0,get:()=>z,set:()=>h("ptr["+C+"] is read-only.")}),R}("null",V)("size",D)("ir",y)("coerce",ee)("add",U)("addn",y===4?U:(...R)=>Number(U(...R)))}if(!d.exports)Object.defineProperty(d,"exports",{enumerable:!0,configurable:!0,get:()=>d.instance?.exports});let B=Object.create(null);B.heapSize=0,B.memory=null,B.freeFuncIndexes=[],B.scopedAlloc=[],B.scopedAlloc.pushPtr=(b)=>(B.scopedAlloc[B.scopedAlloc.length-1].push(b),b),B.utf8Decoder=new TextDecoder,B.utf8Encoder=new TextEncoder("utf-8"),d.sizeofIR=(b)=>{switch(b){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 D;default:return(""+b).endsWith("*")?D:void 0}};let K=function(){if(!B.memory)B.memory=d.memory instanceof WebAssembly.Memory?d.memory:d.exports.memory;else if(B.heapSize===B.memory.buffer.byteLength)return B;let b=B.memory.buffer;if(B.HEAP8=new Int8Array(b),B.HEAP8U=new Uint8Array(b),B.HEAP16=new Int16Array(b),B.HEAP16U=new Uint16Array(b),B.HEAP32=new Int32Array(b),B.HEAP32U=new Uint32Array(b),B.HEAP32F=new Float32Array(b),B.HEAP64F=new Float64Array(b),d.bigIntEnabled)if(typeof BigInt64Array<"u")B.HEAP64=new BigInt64Array(b),B.HEAP64U=new BigUint64Array(b);else h("BigInt support is enabled, but the BigInt64Array type is missing.");return B.heapSize=b.byteLength,B};d.heap8=()=>K().HEAP8,d.heap8u=()=>K().HEAP8U,d.heap16=()=>K().HEAP16,d.heap16u=()=>K().HEAP16U,d.heap32=()=>K().HEAP32,d.heap32u=()=>K().HEAP32U,d.heapForSize=function(b,R=!0){let C=B.memory&&B.heapSize===B.memory.buffer.byteLength?B:K();switch(b){case Int8Array:return C.HEAP8;case Uint8Array:return C.HEAP8U;case Int16Array:return C.HEAP16;case Uint16Array:return C.HEAP16U;case Int32Array:return C.HEAP32;case Uint32Array:return C.HEAP32U;case 8:return R?C.HEAP8U:C.HEAP8;case 16:return R?C.HEAP16U:C.HEAP16;case 32:return R?C.HEAP32U:C.HEAP32;case 64:if(C.HEAP64)return R?C.HEAP64U:C.HEAP64;break;default:if(d.bigIntEnabled){if(b===globalThis.BigUint64Array)return C.HEAP64U;else if(b===globalThis.BigInt64Array)return C.HEAP64;break}}h("Invalid heapForSize() size: expecting 8, 16, 32,","or (if BigInt is enabled) 64.")};let Y=d.functionTable;delete d.functionTable,d.functionTable=Y?()=>Y:()=>d.exports.__indirect_function_table,d.functionEntry=function(b){let R=d.functionTable();return b<R.length?R.get(ee(b)):void 0},d.jsFuncToWasm=function b(R,C){if(!b._)b._={sigTypes:Object.assign(Object.create(null),{i:"i32",p:y,P:y,s:y,j:"i64",f:"f32",d:"f64"}),typeCodes:Object.assign(Object.create(null),{f64:124,f32:125,i64:126,i32:127}),uleb128Encode:(N,j,oe)=>{if(oe<128)N[j](oe);else N[j](oe%128|128,oe>>7)},rxJSig:/^(\w)\((\w*)\)$/,sigParams:(N)=>{let j=b._.rxJSig.exec(N);return j?j[2]:N.substr(1)},letterType:(N)=>b._.sigTypes[N]||h("Invalid signature letter:",N),pushSigType:(N,j)=>N.push(b._.typeCodes[b._.letterType(j)])};if(typeof R==="string"){let N=C;C=R,R=N}let z=b._,se=z.sigParams(C),fe=[1,96];z.uleb128Encode(fe,"push",se.length);for(let N of se)z.pushSigType(fe,N);if(C[0]==="v")fe.push(0);else fe.push(1),z.pushSigType(fe,C[0]);return z.uleb128Encode(fe,"unshift",fe.length),fe.unshift(0,97,115,109,1,0,0,0,1),fe.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(fe)),{e:{f:R}}).exports.f};let ye=function(R,C,z){if(z&&!B.scopedAlloc.length)h("No scopedAllocPush() scope is active.");if(typeof R==="string"){let j=C;C=R,R=j}if(typeof C!=="string"||!(R instanceof Function))h("Invalid arguments: expecting (function,signature) or (signature,function).");let se=d.functionTable(),fe=ee(se.length),N;while(N=B.freeFuncIndexes.pop())if(se.get(N)){N=null;continue}else break;if(!N)N=ee(fe),se.grow(ee(1));try{if(se.set(N,R),z)B.scopedAlloc.pushPtr(N);return N}catch(j){if(!(j instanceof TypeError)){if(N===fe)B.freeFuncIndexes.push(fe);throw j}}try{let j=d.jsFuncToWasm(R,C);if(se.set(N,j),z)B.scopedAlloc.pushPtr(N)}catch(j){if(N===fe)B.freeFuncIndexes.push(fe);throw j}return N};d.installFunction=(b,R)=>ye(b,R,!1),d.scopedInstallFunction=(b,R)=>ye(b,R,!0),d.uninstallFunction=function(b){if(!b&&V!==b)return;let R=d.functionTable();B.freeFuncIndexes.push(b);let C=R.get(b);return R.set(b,null),C},d.peek=function(R,C="i8"){if(C.endsWith("*"))C=y;let z=B.memory&&B.heapSize===B.memory.buffer.byteLength?B:K(),se=Array.isArray(R)?[]:void 0,fe;do{if(se)R=arguments[0].shift();switch(C){case"i1":case"i8":fe=z.HEAP8[Number(R)>>0];break;case"i16":fe=z.HEAP16[Number(R)>>1];break;case"i32":fe=z.HEAP32[Number(R)>>2];break;case"float":case"f32":fe=z.HEAP32F[Number(R)>>2];break;case"double":case"f64":fe=Number(z.HEAP64F[Number(R)>>3]);break;case"i64":if(z.HEAP64){fe=x(z.HEAP64[Number(R)>>3]);break}default:h("Invalid type for peek():",C)}if(se)se.push(fe)}while(se&&arguments[0].length);return se||fe},d.poke=function(b,R,C="i8"){if(C.endsWith("*"))C=y;let z=B.memory&&B.heapSize===B.memory.buffer.byteLength?B:K();for(let se of Array.isArray(b)?b:[b])switch(C){case"i1":case"i8":z.HEAP8[Number(se)>>0]=R;continue;case"i16":z.HEAP16[Number(se)>>1]=R;continue;case"i32":z.HEAP32[Number(se)>>2]=R;continue;case"float":case"f32":z.HEAP32F[Number(se)>>2]=R;continue;case"double":case"f64":z.HEAP64F[Number(se)>>3]=R;continue;case"i64":if(z.HEAP64){z.HEAP64[Number(se)>>3]=x(R);continue}default:h("Invalid type for poke(): "+C)}return this},d.peekPtr=(...b)=>d.peek(b.length===1?b[0]:b,y),d.pokePtr=(b,R=0)=>d.poke(b,R,y),d.peek8=(...b)=>d.peek(b.length===1?b[0]:b,"i8"),d.poke8=(b,R)=>d.poke(b,R,"i8"),d.peek16=(...b)=>d.peek(b.length===1?b[0]:b,"i16"),d.poke16=(b,R)=>d.poke(b,R,"i16"),d.peek32=(...b)=>d.peek(b.length===1?b[0]:b,"i32"),d.poke32=(b,R)=>d.poke(b,R,"i32"),d.peek64=(...b)=>d.peek(b.length===1?b[0]:b,"i64"),d.poke64=(b,R)=>d.poke(b,R,"i64"),d.peek32f=(...b)=>d.peek(b.length===1?b[0]:b,"f32"),d.poke32f=(b,R)=>d.poke(b,R,"f32"),d.peek64f=(...b)=>d.peek(b.length===1?b[0]:b,"f64"),d.poke64f=(b,R)=>d.poke(b,R,"f64"),d.getMemValue=d.peek,d.getPtrValue=d.peekPtr,d.setMemValue=d.poke,d.setPtrValue=d.pokePtr,d.isPtr32=(b)=>typeof b==="number"&&b>=0&&b===(b|0),d.isPtr64=(b)=>typeof b==="bigint"?b>=0:d.isPtr32(b),d.isPtr=D===4?d.isPtr32:d.isPtr64,d.cstrlen=function(b){if(!b||!d.isPtr(b))return null;b=Number(b);let R=K().HEAP8U,C=b;for(;R[C]!==0;++C);return C-b};let P=typeof SharedArrayBuffer>"u"?function(){}:SharedArrayBuffer,I=(b)=>b.buffer instanceof P;d.isSharedTypedArray=I;let ne=(b,R,C)=>{if(D===8){if(typeof R==="bigint")R=Number(R);if(typeof C==="bigint")C=Number(C)}return I(b)?b.slice(R,C):b.subarray(R,C)};d.typedArrayPart=ne;let ie=(b,R,C)=>B.utf8Decoder.decode(ne(b,R,C));d.typedArrayToString=ie,d.cstrToJs=function(b){let R=d.cstrlen(b);return R?ie(K().HEAP8U,Number(b),Number(b)+R):R===null?R:""},d.jstrlen=function(b){if(typeof b!=="string")return null;let R=b.length,C=0;for(let z=0;z<R;++z){let se=b.charCodeAt(z);if(se>=55296&&se<=57343)se=65536+((se&1023)<<10)|b.charCodeAt(++z)&1023;if(se<=127)++C;else if(se<=2047)C+=2;else if(se<=65535)C+=3;else C+=4}return C},d.jstrcpy=function(b,R,C=0,z=-1,se=!0){if(!R||!(R instanceof Int8Array)&&!(R instanceof Uint8Array))h("jstrcpy() target must be an Int8Array or Uint8Array.");if(z=Number(z),C=Number(C),z<0)z=R.length-C;if(!(z>0)||!(C>=0))return 0;let fe=0,N=b.length,j=C,oe=C+z-(se?1:0);for(;fe<N&&C<oe;++fe){let le=b.charCodeAt(fe);if(le>=55296&&le<=57343)le=65536+((le&1023)<<10)|b.charCodeAt(++fe)&1023;if(le<=127){if(C>=oe)break;R[C++]=le}else if(le<=2047){if(C+1>=oe)break;R[C++]=192|le>>6,R[C++]=128|le&63}else if(le<=65535){if(C+2>=oe)break;R[C++]=224|le>>12,R[C++]=128|le>>6&63,R[C++]=128|le&63}else{if(C+3>=oe)break;R[C++]=240|le>>18,R[C++]=128|le>>12&63,R[C++]=128|le>>6&63,R[C++]=128|le&63}}if(se)R[C++]=0;return C-j},d.cstrncpy=function(b,R,C){if(!b||!R)h("cstrncpy() does not accept NULL strings.");if(C<0)C=d.cstrlen(strPtr)+1;else if(!(C>0))return 0;let z=d.heap8u(),se=0,fe,N=Number(b),j=Number(R);for(;se<C&&(fe=z[j+se]);++se)z[N+se]=fe;if(se<C)z[N+se++]=0;return se},d.jstrToUintArray=(b,R=!1)=>B.utf8Encoder.encode(R?b+"\x00":b);let G=(b,R)=>{if(!(b.alloc instanceof Function)||!(b.dealloc instanceof Function))h("Object is missing alloc() and/or dealloc() function(s)","required by",R+"().")},re=function(b,R,C,z){if(G(d,z),typeof b!=="string")return null;let se=B.utf8Encoder.encode(b),fe=C(se.length+1),N=fe;try{let j=K().HEAP8U;return j.set(se,Number(fe)),j[U(fe,se.length)]=0,N=V,R?[fe,se.length]:fe}finally{if(N)d.dealloc(N)}};d.allocCString=(b,R=!1)=>re(b,R,d.alloc,"allocCString()"),d.scopedAllocPush=function(){G(d,"scopedAllocPush");let b=[];return B.scopedAlloc.push(b),b},d.scopedAllocPop=function(b){G(d,"scopedAllocPop");let R=arguments.length?B.scopedAlloc.indexOf(b):B.scopedAlloc.length-1;if(R<0)h("Invalid state object for scopedAllocPop().");if(arguments.length===0)b=B.scopedAlloc[R];B.scopedAlloc.splice(R,1);for(let C;C=b.pop();)if(d.functionEntry(C))d.uninstallFunction(C);else d.dealloc(C)},d.scopedAlloc=function(b){if(!B.scopedAlloc.length)h("No scopedAllocPush() scope is active.");let R=ee(d.alloc(b));return B.scopedAlloc.pushPtr(R)},Object.defineProperty(d.scopedAlloc,"level",{configurable:!1,enumerable:!1,get:()=>B.scopedAlloc.length,set:()=>h("The 'active' property is read-only.")}),d.scopedAllocCString=(b,R=!1)=>re(b,R,d.scopedAlloc,"scopedAllocCString()");let ve=function(b,R){let C=d[b?"scopedAlloc":"alloc"]((R.length+1)*d.ptr.size),z=0;return R.forEach((se)=>{d.pokePtr(U(C,d.ptr.size*z++),d[b?"scopedAllocCString":"allocCString"](""+se))}),d.pokePtr(U(C,d.ptr.size*z),0),C};d.scopedAllocMainArgv=(b)=>ve(!0,b),d.allocMainArgv=(b)=>ve(!1,b),d.cArgvToJs=(b,R)=>{let C=[];for(let z=0;z<b;++z){let se=d.peekPtr(U(R,d.ptr.size*z));C.push(se?d.cstrToJs(se):null)}return C},d.scopedAllocCall=function(b){d.scopedAllocPush();try{return b()}finally{d.scopedAllocPop()}};let O=function(b,R,C){G(d,C);let z=R?"i64":y,se=d[C](b*(R?8:D));if(d.poke(se,0,z),b===1)return se;let fe=[se];for(let N=1;N<b;++N)se=U(se,R?8:D),fe[N]=se,d.poke(se,0,z);return fe};d.allocPtr=(b=1,R=!0)=>O(b,R,"alloc"),d.scopedAllocPtr=(b=1,R=!0)=>O(b,R,"scopedAlloc"),d.xGet=function(b){return d.exports[b]||h("Cannot find exported symbol:",b)};let M=(b,R)=>h(b+"() requires",R,"argument(s).");d.xCall=function(b,...R){let C=b instanceof Function?b:d.xGet(b);if(!(C instanceof Function))h("Exported symbol",b,"is not a function.");if(C.length!==R.length)M(C===b?C.name:b,C.length);return arguments.length===2&&Array.isArray(arguments[1])?C.apply(null,arguments[1]):C.apply(null,R)},B.xWrap=Object.create(null),B.xWrap.convert=Object.create(null),B.xWrap.convert.arg=new Map,B.xWrap.convert.result=new Map;let Q=B.xWrap.convert.arg,ue=B.xWrap.convert.result,J=ee;Q.set("i64",x).set("i32",(b)=>b|0).set("i16",(b)=>(b|0)&65535).set("i8",(b)=>(b|0)&255).set("f32",(b)=>Number(b).valueOf()).set("float",Q.get("f32")).set("f64",Q.get("f32")).set("double",Q.get("f64")).set("int",Q.get("i32")).set("null",(b)=>b).set(null,Q.get("null")).set("**",J).set("*",J),ue.set("*",J).set("pointer",J).set("number",(b)=>Number(b)).set("void",(b)=>{return}).set(void 0,ue.get("void")).set("null",(b)=>b).set(null,ue.get("null"));for(let b of["i8","i16","i32","i64","int","f32","float","f64","double"])Q.set(b+"*",J),ue.set(b+"*",J),ue.set(b,Q.get(b)||h("Maintenance required: missing arg converter for",b));let Ee=(b)=>typeof b==="string"?d.scopedAllocCString(b):ee(b);Q.set("string",Ee).set("utf8",Ee),ue.set("string",(b)=>d.cstrToJs(b)).set("utf8",ue.get("string")).set("string:dealloc",(b)=>{try{return b?d.cstrToJs(b):null}finally{d.dealloc(b)}}).set("utf8:dealloc",ue.get("string:dealloc")).set("json",(b)=>JSON.parse(d.cstrToJs(b))).set("json:dealloc",(b)=>{try{return b?JSON.parse(d.cstrToJs(b)):null}finally{d.dealloc(b)}});let xe=class{constructor(b){this.name=b.name||"unnamed adapter"}convertArg(b,R,C){h("AbstractArgAdapter must be subclassed.")}};Q.FuncPtrAdapter=class b extends xe{constructor(R){super(R);if(Q.FuncPtrAdapter.warnOnUse)console.warn("xArg.FuncPtrAdapter is an internal-only API","and is not intended to be invoked from","client-level code. Invoked with:",R);if(this.name=R.name||"unnamed",this.signature=R.signature,R.contextKey instanceof Function){if(this.contextKey=R.contextKey,!R.bindScope)R.bindScope="context"}if(this.bindScope=R.bindScope||h("FuncPtrAdapter options requires a bindScope (explicit or implied)."),b.bindScopes.indexOf(R.bindScope)<0)h("Invalid options.bindScope ("+R.bindMod+") for FuncPtrAdapter. Expecting one of: ("+b.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=R.callProxy instanceof Function?R.callProxy:void 0}contextKey(R,C){return this}contextMap(R){let C=this.__cmap||(this.__cmap=new Map),z=C.get(R);if(z===void 0)C.set(R,z=[]);return z}convertArg(R,C,z){let se=this.singleton;if(!se&&this.isContext)se=this.contextMap(this.contextKey(C,z));if(se&&se.length===2&&se[0]===R)return se[1];if(R instanceof Function){if(this.callProxy)R=this.callProxy(R);let fe=ye(R,this.signature,this.isTransient);if(b.debugFuncInstall)b.debugOut("FuncPtrAdapter installed",this,this.contextKey(C,z),"@"+fe,R);if(se){if(se[1]){if(b.debugFuncInstall)b.debugOut("FuncPtrAdapter uninstalling",this,this.contextKey(C,z),"@"+se[1],R);try{B.scopedAlloc.pushPtr(se[1])}catch(N){}}se[0]=arguments[0]||V,se[1]=fe}return fe}else if(d.isPtr(R)||R===null||R===void 0){if(se&&se[1]&&se[1]!==R){if(b.debugFuncInstall)b.debugOut("FuncPtrAdapter uninstalling",this,this.contextKey(C,z),"@"+se[1],R);try{B.scopedAlloc.pushPtr(se[1])}catch(fe){}se[0]=se[1]=R||V}return R||V}else throw TypeError("Invalid FuncPtrAdapter argument type. Expecting a function pointer or a "+(this.name?this.name+" ":"")+"function matching signature "+this.signature+".")}},Q.FuncPtrAdapter.warnOnUse=!1,Q.FuncPtrAdapter.debugFuncInstall=!1,Q.FuncPtrAdapter.debugOut=console.debug.bind(console),Q.FuncPtrAdapter.bindScopes=["transient","context","singleton","permanent"];let Se=(b)=>Q.get(b)||h("Argument adapter not found:",b),Re=(b)=>ue.get(b)||h("Result adapter not found:",b);B.xWrap.convertArg=(b,...R)=>Se(b)(...R),B.xWrap.convertArgNoCheck=(b,...R)=>Q.get(b)(...R),B.xWrap.convertResult=(b,R)=>b===null?R:b?Re(b)(R):void 0,B.xWrap.convertResultNoCheck=(b,R)=>b===null?R:b?ue.get(b)(R):void 0,d.xWrap=function b(R,C,...z){if(arguments.length===3&&Array.isArray(arguments[2]))z=arguments[2];if(d.isPtr(R))R=d.functionEntry(R)||h("Function pointer not found in WASM function table.");let se=R instanceof Function,fe=se?R:d.xGet(R);if(se)R=fe.name||"unnamed function";if(z.length!==fe.length)M(R,fe.length);if(fe.length===0&&(C===null||C==="null"))return fe;Re(C);for(let j of z)if(j instanceof xe)Q.set(j,(...oe)=>j.convertArg(...oe));else Se(j);let N=B.xWrap;if(fe.length===0)return(...j)=>j.length?M(R,fe.length):N.convertResult(C,fe.call(null));return function(...j){if(j.length!==fe.length)M(R,fe.length);let oe=d.scopedAllocPush();try{let le=0;if(b.debug)console.debug("xWrap() preparing: resultType ",C,"xf",fe,"argTypes",z,"args",j);for(;le<j.length;++le)j[le]=N.convertArgNoCheck(z[le],j[le],j,le);if(b.debug)console.debug("xWrap() calling: resultType ",C,"xf",fe,"argTypes",z,"args",j);return N.convertResultNoCheck(C,fe.apply(null,j))}finally{d.scopedAllocPop(oe)}}};let H=function(b,R,C,z,se,fe){if(typeof C==="string"){if(R===1)return fe.get(C);else if(R===2){if(!z)return fe.delete(C),b;else if(!(z instanceof Function))h(se,"requires a function argument.");return fe.set(C,z),b}}h("Invalid arguments to",se)};return d.xWrap.resultAdapter=function b(R,C){return H(b,arguments.length,R,C,"resultAdapter()",ue)},d.xWrap.argAdapter=function b(R,C){return H(b,arguments.length,R,C,"argAdapter()",Q)},d.xWrap.FuncPtrAdapter=Q.FuncPtrAdapter,d.xCallWrapped=function(b,R,C,...z){if(Array.isArray(arguments[3]))z=arguments[3];return d.xWrap(b,R,C||[]).apply(null,z||[])},d.xWrap.testConvertArg=B.xWrap.convertArg,d.xWrap.testConvertResult=B.xWrap.convertResult,d},globalThis.WhWasmUtilInstaller.yawl=function(d){let h=()=>fetch(d.uri,{credentials:"same-origin"}),y=this,D=function(x){if(d.wasmUtilTarget){let q=(...V)=>{throw Error(V.join(" "))},ee=d.wasmUtilTarget;if(ee.module=x.module,ee.instance=x.instance,!ee.instance.exports.memory)ee.memory=d?.imports?.env?.memory||q("Missing 'memory' object!");if(!ee.alloc&&x.instance.exports.malloc){let V=x.instance.exports;ee.alloc=function(U){return V.malloc(U)||q("Allocation of",U,"bytes failed.")},ee.dealloc=function(U){U&&V.free(U)}}y(ee)}if(x.config=d,d.onload)d.onload(x);return x};return WebAssembly.instantiateStreaming?()=>WebAssembly.instantiateStreaming(h(),d.imports||{}).then(D):()=>h().then((x)=>x.arrayBuffer()).then((x)=>WebAssembly.instantiate(x,d.imports||{})).then(D)}.bind(globalThis.WhWasmUtilInstaller),globalThis.Jaccwabyt=function m(d){let h=(...W)=>{throw Error(W.join(" "))};{let W=d.heap;if(W instanceof WebAssembly.Memory)W=function(){return new Uint8Array(this.buffer)}.bind(W);else if(!(W instanceof Function))h("config.heap must be WebAssembly.Memory instance or","a function which returns one.");d.heap=W}["alloc","dealloc"].forEach(function(W){d[W]instanceof Function||h("Config option '"+W+"' must be a function.")});let y=m,{heap:D,alloc:x,dealloc:q}=d;d.realloc;let ee=d.log||console.debug.bind(console),V=d.memberPrefix||"",U=d.memberSuffix||"",{BigInt:B,BigInt64Array:K}=globalThis,Y=d.bigIntEnabled??!!K,ye,P=d.pointerSize||d.ptrSize||(typeof(ye=x(1))==="bigint"?8:4),I=d.pointerIR||d.ptrIR||(P===4?"i32":"i64");if(ye)q(ye),ye=void 0;if(P!==4&&P!==8)h("Invalid pointer size:",P);if(I!=="i32"&&I!=="i64")h("Invalid pointer representation:",I);let ne=Y&&B?(W)=>B(W||0):(W)=>h("BigInt support is disabled in this build."),ie=I=="i32"?Number:ne,G=ie(0),re=function(...W){let pe=G;for(let we=0;we<W.length;++we)pe+=ie(W[we]);return pe},ve=function(...W){return re(this.pointer,...W)};if(!y.debugFlags)y.__makeDebugFlags=function(W=null){if(W&&W.__flags)W=W.__flags;let pe=function we(Te){if(arguments.length===0)return we.__flags;if(Te<0)delete we.__flags.getter,delete we.__flags.setter,delete we.__flags.alloc,delete we.__flags.dealloc;else we.__flags.getter=(1&Te)!==0,we.__flags.setter=(2&Te)!==0,we.__flags.alloc=(4&Te)!==0,we.__flags.dealloc=(8&Te)!==0;return we._flags};if(Object.defineProperty(pe,"__flags",{iterable:!1,writable:!1,value:Object.create(W)}),!W)pe(0);return pe},y.debugFlags=y.__makeDebugFlags();let O=!0,M=(W)=>W[1]==="(",Q=(W)=>W==="p"||W==="P"||W==="s",ue=(W)=>W==="P",J=(W)=>W?M(W)?"p":W[0]:void 0,Ee=function(W){switch(J(W)){case"c":case"C":return"i8";case"i":return"i32";case"p":case"P":case"s":return I;case"j":return"i64";case"f":return"float";case"d":return"double"}h("Unhandled signature IR:",W)},xe=function(W){switch(J(W)){case"c":case"C":return 1;case"i":return 4;case"p":case"P":case"s":return P;case"j":return 8;case"f":return 4;case"d":return 8}h("Unhandled signature sizeof:",W)},Se=K?()=>!0:()=>h("BigInt64Array is not available."),Re=function(W){switch(J(W)){case"p":case"P":case"s":switch(P){case 4:return"getInt32";case 8:return Se()&&"getBigInt64"}break;case"i":return"getInt32";case"c":return"getInt8";case"C":return"getUint8";case"j":return Se()&&"getBigInt64";case"f":return"getFloat32";case"d":return"getFloat64"}h("Unhandled DataView getter for signature:",W)},H=function(W){switch(J(W)){case"p":case"P":case"s":switch(P){case 4:return"setInt32";case 8:return Se()&&"setBigInt64"}break;case"i":return"setInt32";case"c":return"setInt8";case"C":return"setUint8";case"j":return Se()&&"setBigInt64";case"f":return"setFloat32";case"d":return"setFloat64"}h("Unhandled DataView setter for signature:",W)},b=function(W){switch(J(W)){case"i":case"f":case"c":case"C":case"d":return Number;case"j":return ne;case"p":case"P":case"s":switch(P){case 4:return Number;case 8:return ne}break}h("Unhandled DataView set wrapper for signature:",W)},R=(W,pe)=>W+"::"+pe,C=function(W,pe){return()=>h(R(W,pe),"is read-only.")},z=function W(pe,we=!0){let Te=W.map.get(pe);if(!Te&&we)W.map.set(pe,Te=W.create(pe));return Te};z.map=new WeakMap,z.create=(W)=>Object.assign(Object.create(null),{o:W,p:void 0,ownsPointer:!1,zod:!1,xb:0});let se=(W)=>z.map.delete(W),fe=(W)=>typeof W==="number"&&W===(W|0)&&W>=0,j=P===4?fe:(W)=>typeof W==="bigint"&&W>=0||fe(W),oe=(W)=>j(W)&&W>0,le=function(W,pe,we){let Te=z(pe,!1);if(!Te)return;if(se(pe),!we&&!(we=Te.p)){console.warn("Cannot(?) happen: __freeStruct() found no instanceInfo");return}if(Array.isArray(pe.ondispose)){let $e;while($e=pe.ondispose.pop())try{if($e instanceof Function)$e.call(pe);else if($e instanceof ar)$e.dispose();else if(j($e))q($e)}catch(lt){console.warn("ondispose() for",W.structName,"@",we,"threw. NOT propagating it.",lt)}}else if(pe.ondispose instanceof Function)try{pe.ondispose()}catch($e){console.warn("ondispose() for",W.structName,"@",we,"threw. NOT propagating it.",$e)}if(delete pe.ondispose,W.debugFlags.__flags.dealloc)ee("debug.dealloc:",Te.ownsPointer?"":"EXTERNAL",W.structName,"instance:",W.structInfo.sizeof,"bytes @"+we);if(Te.ownsPointer){if(Te.zod||W.structInfo.zeroOnDispose)D().fill(0,Number(we),Number(we)+W.structInfo.sizeof+Te.xb);q(we)}},ke=()=>({configurable:!1,writable:!1,iterable:!1}),Ie=(W)=>({...ke(),value:W}),ze=function(pe,we,Te){let $e,lt=(ot)=>{oe(ot)||h("Invalid pointer value",arguments[0],"for",pe.structName,"constructor.")};if(arguments.length>=3)if(Te&&typeof Te==="object")$e=Te,Te=$e?.wrap;else lt(Te),$e={wrap:Te};else $e={};let Ct=!Te,Yt=0,cr=!1;if(Te)lt(Te),cr=!!$e?.takeOwnership;else{let ot=$e?.extraBytes??0;if(ot<0||ot!==(ot|0))h("Invalid extraBytes value:",$e?.extraBytes);Yt=pe.structInfo.sizeof+ot,Te=x(Yt)||h("Allocation of",pe.structName,"structure failed."),cr=!0}try{if($e?.debugFlags)we.debugFlags($e.debugFlags);if(pe.debugFlags.__flags.alloc)ee("debug.alloc:",Ct?"":"EXTERNAL",pe.structName,"instance:",pe.structInfo.sizeof,"bytes @"+Te);if(Ct)D().fill(0,Number(Te),Number(Te)+Yt);let ot=z(we);if(ot.p=Te,ot.ownsPointer=cr,ot.xb=Yt?Yt-pe.structInfo.sizeof:0,ot.zod=!!$e?.zeroOnDispose,$e?.ondispose&&$e.ondispose!==Te)we.addOnDispose($e.ondispose)}catch(ot){throw le(pe,we,Te),ot}},He=function W(pe){return W.rxSig1??=/^[ipPsjfdcC]$/,W.rxSig2??=/^[vipPsjfdcC]\([ipPsjfdcC]*\)$/,W.rxSig1.test(pe)||W.rxSig2.test(pe)},ct=function(W){let pe=this.get(W);if(!pe)pe=[Object.create(null),Object.create(null),Object.create(null)],this.set(W,pe);return pe}.bind(new WeakMap),xt=function(W,pe,we,Te){let $e=ct(W)[pe];if(arguments.length===3)return $e[we];if(Te)return $e[we]=Te;return delete $e[we]},br=function(W,...pe){return xt(this,0,W,...pe)},On=function(W,pe){He(pe)&&h(W,"(",pe,") collides with a data type signature.")},Z=function(W,...pe){return On("Setter adaptor",W),xt(this,1,W,...pe)},ae=function(W,...pe){return On("Struct adaptor",W),xt(this,2,W,...pe)},me=function(W,pe){let we=typeof pe==="string"?xt(W,2,pe):pe;if(typeof we!=="object")h("Invalid struct mapping object. Arg =",pe,JSON.stringify(we));return we},Ae=Ie((W)=>V+W+U),Le=function(W,pe,we=!0){let Te=W.members[pe];if(!Te&&(V||U)){for(let $e of Object.values(W.members))if($e.key===pe){Te=$e;break}if(!Te&&we)h(R(W.name||W.structName,pe),"is not a mapped struct member.")}return Te},Me=function W(pe,we,Te=!1){if(!W._)W._=(lt)=>lt.replace(/[^vipPsjrdcC]/g,"").replace(/[pPscC]/g,"i");let $e=Le(pe.structInfo,we,!0);return Te?W._($e.signature):$e.signature},qe=Ie(function(){let W=[];for(let pe of Object.keys(this.structInfo.members))W.push(this.memberKey(pe));return W}),je=new TextDecoder("utf-8"),rt=new TextEncoder,pt=typeof SharedArrayBuffer>"u"?function(){}:SharedArrayBuffer,Ye=function(W,pe,we){if(P===8)pe=Number(pe),we=Number(we);return je.decode(W.buffer instanceof pt?W.slice(pe,we):W.subarray(pe,we))},Ht=function(W,pe,we=!1){let Te=Le(W.structInfo,pe,we);return Te&&Te.signature.length===1&&Te.signature[0]==="s"?Te:!1},wr=function(W){if(W.signature==="s")return;h("Invalid member type signature for C-string value:",JSON.stringify(W))},po=function(pe,we){let Te=Le(pe.structInfo,we,!0);wr(Te);let $e=pe[Te.key];if(!$e)return null;let lt=$e,Ct=D();for(;Ct[lt]!==0;++lt);return $e===lt?"":Ye(Ct,$e,lt)},Dr=function(W,...pe){if(W.ondispose){if(!Array.isArray(W.ondispose))W.ondispose=[W.ondispose]}else W.ondispose=[];W.ondispose.push(...pe)},Cn=function(W){let pe=rt.encode(W),we=x(pe.length+1);if(!we)h("Allocation error while duplicating string:",W);let Te=D();return Te.set(pe,Number(we)),Te[re(we,pe.length)]=0,we},Go=function(W,pe,we){let Te=Le(W.structInfo,pe,!0);wr(Te);let $e=Cn(we);return W[Te.key]=$e,Dr(W,$e),W},ar=function(pe,we){if(arguments[2]!==Ie)h("Do not call the StructType constructor","from client-level code.");Object.defineProperties(this,{structName:Ie(pe),structInfo:Ie(we)})};ar.prototype=Object.create(null,{dispose:Ie(function(){le(this.constructor,this)}),lookupMember:Ie(function(W,pe=!0){return Le(this.structInfo,W,pe)}),memberToJsString:Ie(function(W){return po(this,W)}),memberIsString:Ie(function(W,pe=!0){return Ht(this,W,pe)}),memberKey:Ae,memberKeys:qe,memberSignature:Ie(function(W,pe=!1){return Me(this,W,pe)}),memoryDump:Ie(function(){let W=this.pointer;return W?new Uint8Array(D().slice(Number(W),Number(W)+this.structInfo.sizeof)):null}),extraBytes:{configurable:!1,enumerable:!1,get:function(){return z(this,!1)?.xb??0}},zeroOnDispose:{configurable:!1,enumerable:!1,get:function(){return z(this,!1)?.zod??!!this.structInfo.zeroOnDispose}},pointer:{configurable:!1,enumerable:!1,get:function(){return z(this,!1)?.p},set:()=>h("Cannot assign the 'pointer' property of a struct.")},setMemberCString:Ie(function(W,pe){return Go(this,W,pe)})}),Object.assign(ar.prototype,{addOnDispose:function(...W){return Dr(this,...W),this}}),Object.defineProperties(ar,{allocCString:Ie(Cn),isA:Ie((W)=>W instanceof ar),hasExternalPointer:Ie((W)=>{let pe=z(W,!1);return!!(pe?.p&&!pe?.ownsPointer)}),memberKey:Ae});let Wi=function(W){return W.get||(W.adaptGet?hr.adaptGet(W.adaptGet):void 0)},dd=function(W){return W.set||(W.adaptSet?hr.adaptSet(W.adaptSet):void 0)},Kv=function W(pe,we,Te){let $e=W.innerStructs??=new Map,lt=pe.memberKey(we);if(Te.signature!==void 0)h("'signature' cannot be used on an embedded struct (",pe.structName,".",lt,").");if(dd(Te))h("'set' and 'adaptSet' are not permitted for nested struct members.");Te.structName??=pe.structName+"::"+we,Te.key=lt,Te.name=we,Te.constructor=this.call(this,Te.structName,Te);let Ct=Wi(Te),Yt=Object.assign(Object.create(null),{configurable:!1,enumerable:!1,set:C(pe.structName,lt),get:function(){let cr=this.debugFlags.__flags,ot=this.pointer,It=ot+"."+lt,Ue=$e.get(It);if(cr.getter)ee("debug.getter: k =",It);if(!Ue)Ue=new Te.constructor(re(ot,Te.offset)),$e.set(It,Ue),this.addOnDispose(()=>Ue.dispose()),Ue.addOnDispose(()=>$e.delete(It));if(Ct)Ue=Ct.apply(this,[Ue,lt]);if(cr.getter)ee("debug.getter: result =",Ue);return Ue}});Object.defineProperty(pe.prototype,lt,Yt)},Jv=function W(pe,we,Te){if(Te=me(this,Te),Te.members)return Kv.call(this,pe,we,Te);if(!W.cache){W.cache={getters:{},setters:{},sw:{}};let It=["i","c","C","p","P","s","f","d","v()"];if(Y)It.push("j");It.forEach(function(Ue){W.cache.getters[Ue]=Re(Ue),W.cache.setters[Ue]=H(Ue),W.cache.sw[Ue]=b(Ue)}),W.sigCheck=function(Ue,Rt,Vi,fd){if(Object.prototype.hasOwnProperty.call(Ue,Vi))h(Ue.structName,"already has a property named",Vi+".");He(fd)||h("Malformed signature for",R(Ue.structName,Rt)+":",fd)}}let $e=pe.memberKey(we);W.sigCheck(pe.prototype,we,$e,Te.signature),Te.key=$e,Te.name=we;let lt=J(Te.signature),Ct=R(pe.structName,$e),Yt=pe.debugFlags.__flags,cr=Wi(Te),ot=Object.create(null);if(ot.configurable=!1,ot.enumerable=!1,ot.get=function(){if(Yt.getter)ee("debug.getter:",W.cache.getters[lt],"for",Ee(lt),Ct,"@",this.pointer,"+",Te.offset,"sz",Te.sizeof);let It=new DataView(D().buffer,Number(this.pointer)+Te.offset,Te.sizeof)[W.cache.getters[lt]](0,O);if(cr)It=cr.apply(this,[$e,It]);if(Yt.getter)ee("debug.getter:",Ct,"result =",It);return It},Te.readOnly)ot.set=C(pe.prototype.structName,$e);else{let It=dd(Te);ot.set=function(Ue){if(Yt.setter)ee("debug.setter:",W.cache.setters[lt],"for",Ee(lt),Ct,"@",this.pointer,"+",Te.offset,"sz",Te.sizeof,Ue);if(!this.pointer)h("Cannot set native property on a disposed",this.structName,"instance.");if(It)Ue=It.apply(this,[$e,Ue]);if(Ue===null||Ue===void 0)Ue=G;else if(Q(Te.signature)&&!j(Ue))if(ue(Te.signature)&&Ue instanceof ar){if(Ue=Ue.pointer||G,Yt.setter)ee("debug.setter:",Ct,"resolved to",Ue)}else h("Invalid value for pointer-type",Ct+".");new DataView(D().buffer,Number(this.pointer)+Te.offset,Te.sizeof)[W.cache.setters[lt]](0,W.cache.sw[lt](Ue),O)}}Object.defineProperty(pe.prototype,$e,ot)},pd=function W(pe,we,Te=Object.create(null)){let $e=function Ue(Rt){if(!(this instanceof Ue))h("The",pe,"constructor may only be called via 'new'.");ze(Ue,this,...arguments)},lt=this,Ct=(Ue)=>typeof Ue==="string"&&He(Ue)?{signature:Ue}:me(lt,Ue);if(arguments.length===1)we=Ct(pe),pe=we.structName||we.name;else if(arguments.length===2)we=Ct(we),we.name??=pe;else we=Ct(we);if(pe??=we.structName,pe??=Te.structName,!pe)h("One of 'name' or 'structName' are required.");if(we.adapt)Object.keys(we.adapt.struct||{}).forEach((Ue)=>{ae.call(W,Ue,we.adapt.struct[Ue])}),Object.keys(we.adapt.set||{}).forEach((Ue)=>{Z.call(W,Ue,we.adapt.set[Ue])}),Object.keys(we.adapt.get||{}).forEach((Ue)=>{br.call(W,Ue,we.adapt.get[Ue])});if(!we.members&&!we.sizeof)we.sizeof=xe(we.signature);let Yt=Ie(y.__makeDebugFlags(hr.debugFlags));Object.defineProperties($e,{debugFlags:Yt,isA:Ie((Ue)=>Ue instanceof $e),memberKey:Ae,memberKeys:qe,structInfo:Ie(we),structName:Ie(pe),ptrAdd:Ie(re)}),$e.prototype=new ar(pe,we,Ie),Object.defineProperties($e.prototype,{debugFlags:Yt,constructor:Ie($e),ptrAdd:Ie(ve)});let cr=!1,ot=0,It=!!we.autoCalcSizeOffset;if(!It){if(!we.sizeof)h(pe,"description is missing its sizeof property.");we.offset??=0}else we.offset??=0;if(Object.keys(we.members||{}).forEach((Ue)=>{let Rt=Ct(we.members[Ue]);if(!Rt.members&&!Rt.sizeof){if(Rt.sizeof=xe(Rt.signature),!Rt.sizeof)h(R(pe,Ue),"is missing a sizeof property.",Rt)}if(Rt.offset===void 0)if(It)Rt.offset=ot;else h(R(pe,Ue),"is missing its offset.",JSON.stringify(Rt));if(we.members[Ue]=Rt,!cr||cr.offset<Rt.offset)cr=Rt;let Vi=!!Rt.autoCalc;if(It)Rt.autoCalcSizeOffset=!0;if(Jv.call(lt,$e,Ue,Rt),Vi)Rt.autoCalcSizeOffset=!0;else delete Rt.autoCalcSizeOffset;ot+=Rt.sizeof}),!cr)h("No member property descriptions found.");if(!we.sizeof)we.sizeof=ot;if(we.sizeof===1)we.signature==="c"||we.signature==="C"||h("Unexpected sizeof==1 member",R(pe,k),"with signature",we.signature);else{if(we.sizeof%4!==0)console.warn("Invalid struct member description",we),h(pe,"sizeof is not aligned. sizeof="+we.sizeof);if(we.offset%4!==0)console.warn("Invalid struct member description",we),h(pe,"offset is not aligned. offset="+we.offset)}if(we.sizeof<ot)console.warn("Suspect struct description:",we,"offset =",ot),h("Mismatch in the calculated vs. the provided sizeof/offset info.","Expected sizeof",ot,"but got",we.sizeof,"for",we);return delete we.autoCalcSizeOffset,$e},hr=function W(pe,we){return arguments.length==1?pd.call(W,pe):pd.call(W,pe,we)};if(hr.StructType=ar,hr.config=d,hr.allocCString=Cn,hr.adaptGet=br,hr.adaptSet=Z,hr.adaptStruct=ae,hr.ptrAdd=re,!hr.debugFlags)hr.debugFlags=y.__makeDebugFlags(y.debugFlags);return hr},globalThis.sqlite3ApiBootstrap.initializers.push(function(m){let d=(...P)=>{throw Error(P.join(" "))},{capi:h,wasm:y,util:D}=m;globalThis.WhWasmUtilInstaller(y),delete globalThis.WhWasmUtilInstaller;let x={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 y.xWrap.FuncPtrAdapter({signature:"i(pi)",contextKey:(P,I)=>P[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 y.xWrap.FuncPtrAdapter({name:"sqlite3_commit_hook",signature:"i(p)",contextKey:(P)=>P[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 y.xWrap.FuncPtrAdapter({signature:"i(pipp)",bindScope:"transient",callProxy:(P)=>{let I;return(ne,ie,G,re)=>{try{let ve=y.cArgvToJs(ie,G);if(!I)I=y.cArgvToJs(ie,re);return P(ve,I)|0}catch(ve){return ve.resultCode||h.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 y.xWrap.FuncPtrAdapter({name:"sqlite3_rollback_hook",signature:"v(p)",contextKey:(P)=>P[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 y.xWrap.FuncPtrAdapter({name:"sqlite3_trace_v2::callback",signature:"i(ippp)",contextKey:(P,I)=>P[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 y.xWrap.FuncPtrAdapter({name:"sqlite3_update_hook::callback",signature:"v(pippj)",contextKey:(P)=>P[0],callProxy:(P)=>(I,ne,ie,G,re)=>{P(I,ne,y.cstrToJs(ie),y.cstrToJs(G),re)}}),"*"]],["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(y.exports.sqlite3_progress_handler)x.core.push(["sqlite3_progress_handler",void 0,["sqlite3*","int",new y.xWrap.FuncPtrAdapter({name:"xProgressHandler",signature:"i(p)",bindScope:"context",contextKey:(P,I)=>P[0]}),"*"]]);if(y.exports.sqlite3_stmt_explain)x.core.push(["sqlite3_stmt_explain","int","sqlite3_stmt*","int"],["sqlite3_stmt_isexplain","int","sqlite3_stmt*"]);if(y.exports.sqlite3_set_authorizer)x.core.push(["sqlite3_set_authorizer","int",["sqlite3*",new y.xWrap.FuncPtrAdapter({name:"sqlite3_set_authorizer::xAuth",signature:"i(pissss)",contextKey:(P,I)=>P[0],callProxy:(P)=>(I,ne,ie,G,re,ve)=>{try{return ie=ie&&y.cstrToJs(ie),G=G&&y.cstrToJs(G),re=re&&y.cstrToJs(re),ve=ve&&y.cstrToJs(ve),P(I,ne,ie,G,re,ve)|0}catch(O){return O.resultCode||h.SQLITE_ERROR}}}),"*"]]);if(y.exports.sqlite3_column_origin_name)x.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(y.bigIntEnabled&&!!y.exports.sqlite3_declare_vtab)x.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(y.bigIntEnabled&&!!y.exports.sqlite3_preupdate_hook)x.int64.push(["sqlite3_preupdate_blobwrite","int","sqlite3*"],["sqlite3_preupdate_count","int","sqlite3*"],["sqlite3_preupdate_depth","int","sqlite3*"],["sqlite3_preupdate_hook","*",["sqlite3*",new y.xWrap.FuncPtrAdapter({name:"sqlite3_preupdate_hook",signature:"v(ppippjj)",contextKey:(P)=>P[0],callProxy:(P)=>(I,ne,ie,G,re,ve,O)=>{P(I,ne,ie,y.cstrToJs(G),y.cstrToJs(re),ve,O)}}),"*"]],["sqlite3_preupdate_new","int",["sqlite3*","int","**"]],["sqlite3_preupdate_old","int",["sqlite3*","int","**"]]);if(y.bigIntEnabled&&!!y.exports.sqlite3changegroup_add&&!!y.exports.sqlite3session_create&&!!y.exports.sqlite3_preupdate_hook){let P={signature:"i(ps)",callProxy:(I)=>(ne,ie)=>{try{return I(ne,y.cstrToJs(ie))|0}catch(G){return G.resultCode||h.SQLITE_ERROR}}};x.int64.push(["sqlite3changegroup_add","int",["sqlite3_changegroup*","int","void*"]],["sqlite3changegroup_add_strm","int",["sqlite3_changegroup*",new y.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 y.xWrap.FuncPtrAdapter({name:"xOutput",signature:"i(ppi)",bindScope:"transient"}),"void*"]],["sqlite3changeset_apply","int",["sqlite3*","int","void*",new y.xWrap.FuncPtrAdapter({name:"xFilter",bindScope:"transient",...P}),new y.xWrap.FuncPtrAdapter({name:"xConflict",signature:"i(pip)",bindScope:"transient"}),"void*"]],["sqlite3changeset_apply_strm","int",["sqlite3*",new y.xWrap.FuncPtrAdapter({name:"xInput",signature:"i(ppp)",bindScope:"transient"}),"void*",new y.xWrap.FuncPtrAdapter({name:"xFilter",bindScope:"transient",...P}),new y.xWrap.FuncPtrAdapter({name:"xConflict",signature:"i(pip)",bindScope:"transient"}),"void*"]],["sqlite3changeset_apply_v2","int",["sqlite3*","int","void*",new y.xWrap.FuncPtrAdapter({name:"xFilter",bindScope:"transient",...P}),new y.xWrap.FuncPtrAdapter({name:"xConflict",signature:"i(pip)",bindScope:"transient"}),"void*","**","int*","int"]],["sqlite3changeset_apply_v2_strm","int",["sqlite3*",new y.xWrap.FuncPtrAdapter({name:"xInput",signature:"i(ppp)",bindScope:"transient"}),"void*",new y.xWrap.FuncPtrAdapter({name:"xFilter",bindScope:"transient",...P}),new y.xWrap.FuncPtrAdapter({name:"xConflict",signature:"i(pip)",bindScope:"transient"}),"void*","**","int*","int"]],["sqlite3changeset_apply_v3","int",["sqlite3*","int","void*",new y.xWrap.FuncPtrAdapter({name:"xFilter",signature:"i(pp)",bindScope:"transient"}),new y.xWrap.FuncPtrAdapter({name:"xConflict",signature:"i(pip)",bindScope:"transient"}),"void*","**","int*","int"]],["sqlite3changeset_apply_v3_strm","int",["sqlite3*",new y.xWrap.FuncPtrAdapter({name:"xInput",signature:"i(ppp)",bindScope:"transient"}),"void*",new y.xWrap.FuncPtrAdapter({name:"xFilter",signature:"i(pp)",bindScope:"transient"}),new y.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 y.xWrap.FuncPtrAdapter({name:"xInputA",signature:"i(ppp)",bindScope:"transient"}),"void*",new y.xWrap.FuncPtrAdapter({name:"xInputB",signature:"i(ppp)",bindScope:"transient"}),"void*",new y.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 y.xWrap.FuncPtrAdapter({name:"xInput",signature:"i(ppp)",bindScope:"transient"}),"void*",new y.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 y.xWrap.FuncPtrAdapter({name:"xInput",signature:"i(ppp)",bindScope:"transient"}),"void*"]],["sqlite3changeset_start_v2","int",["**","int","*","int"]],["sqlite3changeset_start_v2_strm","int",["**",new y.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 y.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 y.xWrap.FuncPtrAdapter({name:"xOutput",signature:"i(ppp)",bindScope:"transient"}),"void*"]],["sqlite3session_table_filter",void 0,["sqlite3_session*",new y.xWrap.FuncPtrAdapter({name:"xFilter",...P,contextKey:(I,ne)=>I[0]}),"*"]])}m.StructBinder=globalThis.Jaccwabyt({heap:y.heap8u,alloc:y.alloc,dealloc:y.dealloc,bigIntEnabled:y.bigIntEnabled,pointerIR:y.ptr.ir,memberPrefix:"$"}),delete globalThis.Jaccwabyt;{let P=y.xWrap.argAdapter("string");y.xWrap.argAdapter("string:flexible",(G)=>P(D.flexibleString(G))),y.xWrap.argAdapter("string:static",function(G){if(y.isPtr(G))return G;return G=""+G,this[G]||(this[G]=y.allocCString(G))}.bind(Object.create(null)));let I=y.xWrap.argAdapter("*"),ne=function(){};if(y.xWrap.argAdapter("sqlite3_filename",I)("sqlite3_context*",I)("sqlite3_value*",I)("void*",I)("sqlite3_changegroup*",I)("sqlite3_changeset_iter*",I)("sqlite3_session*",I)("sqlite3_stmt*",(G)=>I(G instanceof(m?.oo1?.Stmt||ne)?G.pointer:G))("sqlite3*",(G)=>I(G instanceof(m?.oo1?.DB||ne)?G.pointer:G))("sqlite3_vfs*",(G)=>{if(typeof G==="string")return h.sqlite3_vfs_find(G)||m.SQLite3Error.toss(h.SQLITE_NOTFOUND,"Unknown sqlite3_vfs name:",G);return I(G instanceof(h.sqlite3_vfs||ne)?G.pointer:G)}),y.exports.sqlite3_declare_vtab)y.xWrap.argAdapter("sqlite3_index_info*",(G)=>I(G instanceof(h.sqlite3_index_info||ne)?G.pointer:G))("sqlite3_module*",(G)=>I(G instanceof(h.sqlite3_module||ne)?G.pointer:G));let ie=y.xWrap.resultAdapter("*");y.xWrap.resultAdapter("sqlite3*",ie)("sqlite3_context*",ie)("sqlite3_stmt*",ie)("sqlite3_value*",ie)("sqlite3_vfs*",ie)("void*",ie);for(let G of x.core)h[G[0]]=y.xWrap.apply(null,G);for(let G of x.wasmInternal)D[G[0]]=y.xWrap.apply(null,G);for(let G of x.int64)h[G[0]]=y.bigIntEnabled?y.xWrap.apply(null,G):()=>d(G[0]+"() is unavailable due to lack","of BigInt support in this build.");delete x.core,delete x.int64,delete x.wasmInternal,D.sqlite3__wasm_db_error=function(G,re,ve){if(!G)return h.SQLITE_MISUSE;if(re instanceof m.WasmAllocError)re=h.SQLITE_NOMEM,ve=0;else if(re instanceof Error)ve=ve||""+re,re=re.resultCode||h.SQLITE_ERROR;return h.sqlite3_set_errmsg(G,re,ve)||re}}{let P=y.xCall("sqlite3__wasm_enum_json");if(!P)d("Maintenance required: increase sqlite3__wasm_enum_json()'s","static buffer size!");y.ctype=JSON.parse(y.cstrToJs(P));let I=["access","authorizer","blobFinalizers","changeset","config","dataTypes","dbConfig","dbStatus","encodings","fcntl","flock","ioCap","limits","openFlags","prepareFlags","resultCodes","sqlite3Status","stmtStatus","syncFlags","trace","txnState","udfFlags","version"];if(y.bigIntEnabled)I.push("serialize","session","vtab");for(let G of I)for(let re of Object.entries(y.ctype[G]))h[re[0]]=re[1];if(!y.functionEntry(h.SQLITE_WASM_DEALLOC))d("Internal error: cannot resolve exported function","entry SQLITE_WASM_DEALLOC (=="+h.SQLITE_WASM_DEALLOC+").");let ne=Object.create(null);for(let G of Object.entries(y.ctype.resultCodes))ne[G[1]]=G[0];h.sqlite3_js_rc_str=(G)=>ne[G];let ie=Object.assign(Object.create(null),{WasmTestStruct:!0,sqlite3_index_info:!y.bigIntEnabled,sqlite3_index_constraint:!y.bigIntEnabled,sqlite3_index_orderby:!y.bigIntEnabled,sqlite3_index_constraint_usage:!y.bigIntEnabled});for(let G of y.ctype.structs)if(!ie[G.name])h[G.name]=m.StructBinder(G);if(h.sqlite3_index_info){for(let G of["sqlite3_index_constraint","sqlite3_index_orderby","sqlite3_index_constraint_usage"])h.sqlite3_index_info[G]=h[G],delete h[G];h.sqlite3_vtab_config=y.xWrap("sqlite3__wasm_vtab_config","int",["sqlite3*","int","int"])}}let q=(P,I,ne)=>D.sqlite3__wasm_db_error(P,h.SQLITE_MISUSE,I+"() requires "+ne+" argument"+(ne===1?"":"s")+"."),ee=(P)=>D.sqlite3__wasm_db_error(P,h.SQLITE_FORMAT,"SQLITE_UTF8 is the only supported encoding."),V=(P)=>y.xWrap.argAdapter("sqlite3*")(P),U=(P)=>y.isPtr(P)?y.cstrToJs(P):P,B=function(P,I){P=V(P);let ne=this.dbMap.get(P);if(!I)return this.dbMap.delete(P),ne;else if(!ne&&I>0)this.dbMap.set(P,ne=Object.create(null));return ne}.bind(Object.assign(Object.create(null),{dbMap:new Map}));if(B.addCollation=function(P,I){let ne=B(P,1);if(!ne.collation)ne.collation=new Set;ne.collation.add(U(I).toLowerCase())},B._addUDF=function(P,I,ne,ie){I=U(I).toLowerCase();let G=ie.get(I);if(!G)ie.set(I,G=new Set);G.add(ne<0?-1:ne)},B.addFunction=function(P,I,ne){let ie=B(P,1);if(!ie.udf)ie.udf=new Map;this._addUDF(P,I,ne,ie.udf)},y.exports.sqlite3_create_window_function)B.addWindowFunc=function(P,I,ne){let ie=B(P,1);if(!ie.wudf)ie.wudf=new Map;this._addUDF(P,I,ne,ie.wudf)};B.cleanup=function(P){P=V(P);for(let ie 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[G,re]=ie;if(!y.exports[G])continue;let ve=[P];ve.length=re;try{h[G](...ve)}catch(O){m.config.warn("close-time call of",G+"(",ve,") threw:",O)}}let I=B(P,0);if(!I)return;if(I.collation){for(let ie of I.collation)try{h.sqlite3_create_collation_v2(P,ie,h.SQLITE_UTF8,0,0,0)}catch(G){}delete I.collation}let ne;for(ne=0;ne<2;++ne){let ie=ne?I.wudf:I.udf;if(!ie)continue;let G=ne?h.sqlite3_create_window_function:h.sqlite3_create_function_v2;for(let re of ie){let ve=re[0],O=re[1],M=[P,ve,0,h.SQLITE_UTF8,0,0,0,0,0];if(ne)M.push(0);for(let Q of O)try{M[2]=Q,G.apply(null,M)}catch(ue){}O.clear()}ie.clear()}delete I.udf,delete I.wudf};{let P=y.xWrap("sqlite3_close_v2","int","sqlite3*");h.sqlite3_close_v2=function(I){if(arguments.length!==1)return q(I,"sqlite3_close_v2",1);if(I)try{B.cleanup(I)}catch(ne){}return P(I)}}if(h.sqlite3session_create){let P=y.xWrap("sqlite3session_delete",void 0,["sqlite3_session*"]);h.sqlite3session_delete=function(I){if(arguments.length!==1)return q(pDb,"sqlite3session_delete",1);else if(I)h.sqlite3session_table_filter(I,0,0);P(I)}}{let P=(ne,ie)=>"argv["+ie+"]:"+ne[0]+":"+y.cstrToJs(ne[1]).toLowerCase(),I=y.xWrap("sqlite3_create_collation_v2","int",["sqlite3*","string","int","*",new y.xWrap.FuncPtrAdapter({name:"xCompare",signature:"i(pipip)",contextKey:P}),new y.xWrap.FuncPtrAdapter({name:"xDestroy",signature:"v(p)",contextKey:P})]);h.sqlite3_create_collation_v2=function(ne,ie,G,re,ve,O){if(arguments.length!==6)return q(ne,"sqlite3_create_collation_v2",6);else if((G&15)===0)G|=h.SQLITE_UTF8;else if(h.SQLITE_UTF8!==(G&15))return ee(ne);try{let M=I(ne,ie,G,re,ve,O);if(M===0&&ve instanceof Function)B.addCollation(ne,ie);return M}catch(M){return D.sqlite3__wasm_db_error(ne,M)}},h.sqlite3_create_collation=(ne,ie,G,re,ve)=>arguments.length===5?h.sqlite3_create_collation_v2(ne,ie,G,re,ve,0):q(ne,"sqlite3_create_collation",5)}{let P=function(G,re){return G[0]+":"+(G[2]<0?-1:G[2])+":"+re+":"+y.cstrToJs(G[1]).toLowerCase()},I=Object.assign(Object.create(null),{xInverseAndStep:{signature:"v(pip)",contextKey:P,callProxy:(G)=>(re,ve,O)=>{try{G(re,...h.sqlite3_values_to_js(ve,O))}catch(M){h.sqlite3_result_error_js(re,M)}}},xFinalAndValue:{signature:"v(p)",contextKey:P,callProxy:(G)=>(re)=>{try{h.sqlite3_result_js(re,G(re))}catch(ve){h.sqlite3_result_error_js(re,ve)}}},xFunc:{signature:"v(pip)",contextKey:P,callProxy:(G)=>(re,ve,O)=>{try{h.sqlite3_result_js(re,G(re,...h.sqlite3_values_to_js(ve,O)))}catch(M){h.sqlite3_result_error_js(re,M)}}},xDestroy:{signature:"v(p)",contextKey:P,callProxy:(G)=>(re)=>{try{G(re)}catch(ve){console.error("UDF xDestroy method threw:",ve)}}}}),ne=y.xWrap("sqlite3_create_function_v2","int",["sqlite3*","string","int","int","*",new y.xWrap.FuncPtrAdapter({name:"xFunc",...I.xFunc}),new y.xWrap.FuncPtrAdapter({name:"xStep",...I.xInverseAndStep}),new y.xWrap.FuncPtrAdapter({name:"xFinal",...I.xFinalAndValue}),new y.xWrap.FuncPtrAdapter({name:"xDestroy",...I.xDestroy})]),ie=y.exports.sqlite3_create_window_function?y.xWrap("sqlite3_create_window_function","int",["sqlite3*","string","int","int","*",new y.xWrap.FuncPtrAdapter({name:"xStep",...I.xInverseAndStep}),new y.xWrap.FuncPtrAdapter({name:"xFinal",...I.xFinalAndValue}),new y.xWrap.FuncPtrAdapter({name:"xValue",...I.xFinalAndValue}),new y.xWrap.FuncPtrAdapter({name:"xInverse",...I.xInverseAndStep}),new y.xWrap.FuncPtrAdapter({name:"xDestroy",...I.xDestroy})]):void 0;if(h.sqlite3_create_function_v2=function G(re,ve,O,M,Q,ue,J,Ee,xe){if(G.length!==arguments.length)return q(re,"sqlite3_create_function_v2",G.length);else if((M&15)===0)M|=h.SQLITE_UTF8;else if(h.SQLITE_UTF8!==(M&15))return ee(re);try{let Se=ne(re,ve,O,M,Q,ue,J,Ee,xe);if(Se===0&&(ue instanceof Function||J instanceof Function||Ee instanceof Function||xe instanceof Function))B.addFunction(re,ve,O);return Se}catch(Se){return console.error("sqlite3_create_function_v2() setup threw:",Se),D.sqlite3__wasm_db_error(re,Se,"Creation of UDF threw: "+Se)}},h.sqlite3_create_function=function G(re,ve,O,M,Q,ue,J,Ee){return G.length===arguments.length?h.sqlite3_create_function_v2(re,ve,O,M,Q,ue,J,Ee,0):q(re,"sqlite3_create_function",G.length)},ie)h.sqlite3_create_window_function=function G(re,ve,O,M,Q,ue,J,Ee,xe,Se){if(G.length!==arguments.length)return q(re,"sqlite3_create_window_function",G.length);else if((M&15)===0)M|=h.SQLITE_UTF8;else if(h.SQLITE_UTF8!==(M&15))return ee(re);try{let Re=ie(re,ve,O,M,Q,ue,J,Ee,xe,Se);if(Re===0&&(ue instanceof Function||J instanceof Function||Ee instanceof Function||xe instanceof Function||Se instanceof Function))B.addWindowFunc(re,ve,O);return Re}catch(Re){return console.error("sqlite3_create_window_function() setup threw:",Re),D.sqlite3__wasm_db_error(re,Re,"Creation of UDF threw: "+Re)}};else delete h.sqlite3_create_window_function;if(h.sqlite3_create_function_v2.udfSetResult=h.sqlite3_create_function.udfSetResult=h.sqlite3_result_js,h.sqlite3_create_window_function)h.sqlite3_create_window_function.udfSetResult=h.sqlite3_result_js;if(h.sqlite3_create_function_v2.udfConvertArgs=h.sqlite3_create_function.udfConvertArgs=h.sqlite3_values_to_js,h.sqlite3_create_window_function)h.sqlite3_create_window_function.udfConvertArgs=h.sqlite3_values_to_js;if(h.sqlite3_create_function_v2.udfSetError=h.sqlite3_create_function.udfSetError=h.sqlite3_result_error_js,h.sqlite3_create_window_function)h.sqlite3_create_window_function.udfSetError=h.sqlite3_result_error_js}{let P=(ne,ie)=>{if(typeof ne==="string")ie=-1;else if(D.isSQLableTypedArray(ne))ie=ne.byteLength,ne=y.typedArrayToString(ne instanceof ArrayBuffer?new Uint8Array(ne):ne);else if(Array.isArray(ne))ne=ne.join(""),ie=-1;return[ne,ie]},I={basic:y.xWrap("sqlite3_prepare_v3","int",["sqlite3*","string","int","int","**","**"]),full:y.xWrap("sqlite3_prepare_v3","int",["sqlite3*","*","int","int","**","**"])};h.sqlite3_prepare_v3=function ne(ie,G,re,ve,O,M){if(ne.length!==arguments.length)return q(ie,"sqlite3_prepare_v3",ne.length);let[Q,ue]=P(G,Number(re));switch(typeof Q){case"string":return I.basic(ie,Q,ue,ve,O,null);case typeof y.ptr.null:return I.full(ie,y.ptr.coerce(Q),ue,ve,O,M);default:return D.sqlite3__wasm_db_error(ie,h.SQLITE_MISUSE,"Invalid SQL argument type for sqlite3_prepare_v2/v3(). typeof="+typeof Q)}},h.sqlite3_prepare_v2=function ne(ie,G,re,ve,O){return ne.length===arguments.length?h.sqlite3_prepare_v3(ie,G,re,0,ve,O):q(ie,"sqlite3_prepare_v2",ne.length)}}{let P=y.xWrap("sqlite3_bind_text","int",["sqlite3_stmt*","int","string","int","*"]),I=y.xWrap("sqlite3_bind_blob","int",["sqlite3_stmt*","int","*","int","*"]);h.sqlite3_bind_text=function ne(ie,G,re,ve,O){if(ne.length!==arguments.length)return q(h.sqlite3_db_handle(ie),"sqlite3_bind_text",ne.length);else if(y.isPtr(re)||re===null)return P(ie,G,re,ve,O);else if(re instanceof ArrayBuffer)re=new Uint8Array(re);else if(Array.isArray(pMem))re=pMem.join("");let M,Q;try{if(D.isSQLableTypedArray(re))M=y.allocFromTypedArray(re),Q=re.byteLength;else if(typeof re==="string")[M,Q]=y.allocCString(re);else return D.sqlite3__wasm_db_error(h.sqlite3_db_handle(ie),h.SQLITE_MISUSE,"Invalid 3rd argument type for sqlite3_bind_text().");return P(ie,G,M,Q,h.SQLITE_WASM_DEALLOC)}catch(ue){return y.dealloc(M),D.sqlite3__wasm_db_error(h.sqlite3_db_handle(ie),ue)}},h.sqlite3_bind_blob=function ne(ie,G,re,ve,O){if(ne.length!==arguments.length)return q(h.sqlite3_db_handle(ie),"sqlite3_bind_blob",ne.length);else if(y.isPtr(re)||re===null)return I(ie,G,re,ve,O);else if(re instanceof ArrayBuffer)re=new Uint8Array(re);else if(Array.isArray(re))re=re.join("");let M,Q;try{if(D.isBindableTypedArray(re))M=y.allocFromTypedArray(re),Q=ve>=0?ve:re.byteLength;else if(typeof re==="string")[M,Q]=y.allocCString(re);else return D.sqlite3__wasm_db_error(h.sqlite3_db_handle(ie),h.SQLITE_MISUSE,"Invalid 3rd argument type for sqlite3_bind_blob().");return I(ie,G,M,Q,h.SQLITE_WASM_DEALLOC)}catch(ue){return y.dealloc(M),D.sqlite3__wasm_db_error(h.sqlite3_db_handle(ie),ue)}}}if(!h.sqlite3_column_text){let P=y.xWrap.argAdapter("sqlite3_stmt*"),I=y.xWrap.argAdapter("int"),ne=y.xWrap.argAdapter("sqlite3_value*"),ie=(G,re)=>y.typedArrayToString(y.heap8u(),Number(G),Number(G)+re);h.sqlite3_column_text=function(G,re){let ve=P(G),O=I(re),M=y.exports.sqlite3_column_text(ve,O);return M?ie(M,y.exports.sqlite3_column_bytes(ve,O)):null},h.sqlite3_value_text=function(G){let re=ne(G),ve=y.exports.sqlite3_value_text(re);return ve?ie(ve,y.exports.sqlite3_value_bytes(re)):null}}h.sqlite3_config=function(P,...I){if(arguments.length<2)return h.SQLITE_MISUSE;switch(P){case h.SQLITE_CONFIG_COVERING_INDEX_SCAN:case h.SQLITE_CONFIG_MEMSTATUS:case h.SQLITE_CONFIG_SMALL_MALLOC:case h.SQLITE_CONFIG_SORTERREF_SIZE:case h.SQLITE_CONFIG_STMTJRNL_SPILL:case h.SQLITE_CONFIG_URI:return y.exports.sqlite3__wasm_config_i(P,I[0]);case h.SQLITE_CONFIG_LOOKASIDE:return y.exports.sqlite3__wasm_config_ii(P,I[0],I[1]);case h.SQLITE_CONFIG_MEMDB_MAXSIZE:return y.exports.sqlite3__wasm_config_j(P,I[0]);case h.SQLITE_CONFIG_GETMALLOC:case h.SQLITE_CONFIG_GETMUTEX:case h.SQLITE_CONFIG_GETPCACHE2:case h.SQLITE_CONFIG_GETPCACHE:case h.SQLITE_CONFIG_HEAP:case h.SQLITE_CONFIG_LOG:case h.SQLITE_CONFIG_MALLOC:case h.SQLITE_CONFIG_MMAP_SIZE:case h.SQLITE_CONFIG_MULTITHREAD:case h.SQLITE_CONFIG_MUTEX:case h.SQLITE_CONFIG_PAGECACHE:case h.SQLITE_CONFIG_PCACHE2:case h.SQLITE_CONFIG_PCACHE:case h.SQLITE_CONFIG_PCACHE_HDRSZ:case h.SQLITE_CONFIG_PMASZ:case h.SQLITE_CONFIG_SERIALIZED:case h.SQLITE_CONFIG_SINGLETHREAD:case h.SQLITE_CONFIG_SQLLOG:case h.SQLITE_CONFIG_WIN32_HEAPSIZE:default:return h.SQLITE_NOTFOUND}};{let P=new Set;h.sqlite3_auto_extension=function(I){if(I instanceof Function)I=y.installFunction("i(ppp)",I);else if(arguments.length!==1||!y.isPtr(I))return h.SQLITE_MISUSE;let ne=y.exports.sqlite3_auto_extension(I);if(I!==arguments[0])if(ne===0)P.add(I);else y.uninstallFunction(I);return ne},h.sqlite3_cancel_auto_extension=function(I){if(!I||arguments.length!==1||!y.isPtr(I))return 0;return y.exports.sqlite3_cancel_auto_extension(I)},h.sqlite3_reset_auto_extension=function(){y.exports.sqlite3_reset_auto_extension();for(let I of P)y.uninstallFunction(I);P.clear()}}y.xWrap.FuncPtrAdapter.warnOnUse=!0;let K=m.StructBinder,Y=function P(I,ne,ie,G=P.installMethodArgcCheck){if(!(I instanceof K.StructType))d("Usage error: target object is-not-a StructType.");else if(!(ie instanceof Function)&&!y.isPtr(ie))d("Usage error: expecting a Function or WASM pointer to one.");if(arguments.length===1)return(M,Q)=>P(I,M,Q,G);if(!P.argcProxy)P.argcProxy=function(M,Q,ue,J){return function(...Ee){if(ue.length!==arguments.length)d("Argument mismatch for",M.structInfo.name+"::"+Q+": Native signature is:",J);return ue.apply(this,Ee)}},P.removeFuncList=function(){if(this.ondispose.__removeFuncList)this.ondispose.__removeFuncList.forEach((M,Q)=>{if(y.isPtr(M))try{y.uninstallFunction(M)}catch(ue){}}),delete this.ondispose.__removeFuncList};let re=I.memberSignature(ne);if(re.length<2)d("Member",ne,"does not have a function pointer signature:",re);let ve=I.memberKey(ne),O=G&&!y.isPtr(ie)?P.argcProxy(I,ve,ie,re):ie;if(y.isPtr(O)){if(O&&!y.functionEntry(O))d("Pointer",O,"is not a WASM function table entry.");I[ve]=O}else{let M=y.installFunction(O,re);if(I[ve]=M,!I.ondispose||!I.ondispose.__removeFuncList)I.addOnDispose("ondispose.__removeFuncList handler",P.removeFuncList),I.ondispose.__removeFuncList=[];I.ondispose.__removeFuncList.push(ve,M)}return(M,Q)=>P(I,M,Q,G)};Y.installMethodArgcCheck=!1;let ye=function(P,I,ne=Y.installMethodArgcCheck){let ie=new Map;for(let G of Object.keys(I)){let re=I[G],ve=ie.get(re);if(ve){let O=P.memberKey(G);P[O]=P[P.memberKey(ve)]}else Y(P,G,re,ne),ie.set(re,G)}return P};K.StructType.prototype.installMethod=function(I,ne,ie=Y.installMethodArgcCheck){return arguments.length<3&&I&&typeof I==="object"?ye(this,...arguments):Y(this,...arguments)},K.StructType.prototype.installMethods=function(P,I=Y.installMethodArgcCheck){return ye(this,P,I)}}),globalThis.sqlite3ApiBootstrap.initializers.push(function(m){let d=(...H)=>{throw new m.SQLite3Error(...H)},{capi:h,wasm:y,util:D}=m,x=function(H){return(...b)=>H("sqlite3.oo1:",...b)};m.__isUnderTest?x(console.debug.bind(console)):x(m.config.debug),m.__isUnderTest?x(console.warn.bind(console)):x(m.config.warn),m.__isUnderTest?x(console.error.bind(console)):x(m.config.error);let q=new WeakMap,ee=new Set,V=new WeakMap,U=(H,b,R)=>{let C=Object.getOwnPropertyDescriptor(H,b);return C?C.value:R},B=function(H,b){if(b){if(H instanceof P)H=H.pointer;d(b,"sqlite3 result code",b+":",H?h.sqlite3_errmsg(H):h.sqlite3_errstr(b))}return arguments[0]},K=y.installFunction("i(ippp)",function(H,b,R,C){if(h.SQLITE_TRACE_STMT===H)console.log("SQL TRACE #"+ ++this.counter,"via sqlite3@"+b+"["+h.sqlite3_db_filename(b,null)+"]",y.cstrToJs(C))}.bind({counter:0})),Y=Object.create(null),ye=function H(...b){let R=H.normalizeArgs(...b),C;if(C=R["sqlite3*"]){if(!R["sqlite3*:takeOwnership"])ee.add(this);this.filename=h.sqlite3_db_filename(C,"main")}else{let{filename:z,vfs:se,flags:fe}=R;if(typeof z!=="string"&&!y.isPtr(z)||typeof fe!=="string"||se&&typeof se!=="string"&&!y.isPtr(se))m.config.error("Invalid DB ctor args",R,arguments),d("Invalid arguments for DB constructor:",arguments,"opts:",R);let N=0;if(fe.indexOf("c")>=0)N|=h.SQLITE_OPEN_CREATE|h.SQLITE_OPEN_READWRITE;if(fe.indexOf("w")>=0)N|=h.SQLITE_OPEN_READWRITE;if(N===0)N|=h.SQLITE_OPEN_READONLY;N|=h.SQLITE_OPEN_EXRESCODE;let j=y.pstack.pointer;try{let oe=y.pstack.allocPtr(),le=h.sqlite3_open_v2(z,oe,N,se||y.ptr.null);if(C=y.peekPtr(oe),B(C,le),h.sqlite3_extended_result_codes(C,1),fe.indexOf("t")>=0)h.sqlite3_trace_v2(C,h.SQLITE_TRACE_STMT,K,C)}catch(oe){if(C)h.sqlite3_close_v2(C);throw oe}finally{y.pstack.restore(j)}this.filename=y.isPtr(z)?y.cstrToJs(z):z}if(q.set(this,C),V.set(this,Object.create(null)),!R["sqlite3*"])try{let z=Y[h.sqlite3_js_db_vfs(C)||d("Internal error: cannot get VFS for new db handle.")];if(z)if(z instanceof Function)z(this,m);else B(C,h.sqlite3_exec(C,z,0,0,0))}catch(z){throw this.close(),z}};ye.setVfsPostOpenCallback=function(H,b){if(!(b instanceof Function))d("dbCtorHelper.setVfsPostOpenCallback() should not be used with a non-function argument.",arguments);Y[H]=b},ye.normalizeArgs=function(H=":memory:",b="c",R=null){let C={};if(arguments.length===1&&arguments[0]&&typeof arguments[0]==="object"){if(Object.assign(C,arguments[0]),C.flags===void 0)C.flags="c";if(C.vfs===void 0)C.vfs=null;if(C.filename===void 0)C.filename=":memory:"}else C.filename=H,C.flags=b,C.vfs=R;return C};let P=function(...H){ye.apply(this,H)};P.dbCtorHelper=ye;let I={null:1,number:2,string:3,boolean:4,blob:5};if(y.bigIntEnabled)I.bigint=I.number;let ne=function(){if(I!==arguments[2])d(h.SQLITE_MISUSE,"Do not call the Stmt constructor directly. Use DB.prepare().");if(this.db=arguments[0],q.set(this,arguments[1]),arguments.length>3&&!arguments[3])ee.add(this)},ie=function(H){if(!H.pointer)d("DB has been closed.");return H},G=function(H,b){if(b!==(b|0)||b<0||b>=H.columnCount)d("Column index",b,"is out of range.");return H},re=function(H,b){let R=Object.create(null);switch(R.opt=Object.create(null),b.length){case 1:if(typeof b[0]==="string"||D.isSQLableTypedArray(b[0]))R.sql=b[0];else if(Array.isArray(b[0]))R.sql=b[0];else if(b[0]&&typeof b[0]==="object")R.opt=b[0],R.sql=R.opt.sql;break;case 2:R.sql=b[0],R.opt=b[1];break;default:d("Invalid argument count for exec().")}if(R.sql=D.flexibleString(R.sql),typeof R.sql!=="string")d("Missing SQL argument or unsupported SQL value type.");let C=R.opt;switch(C.returnValue){case"resultRows":if(!C.resultRows)C.resultRows=[];R.returnVal=()=>C.resultRows;break;case"saveSql":if(!C.saveSql)C.saveSql=[];R.returnVal=()=>C.saveSql;break;case void 0:case"this":R.returnVal=()=>H;break;default:d("Invalid returnValue value:",C.returnValue)}if(!C.callback&&!C.returnValue&&C.rowMode!==void 0){if(!C.resultRows)C.resultRows=[];R.returnVal=()=>C.resultRows}if(C.callback||C.resultRows)switch(C.rowMode===void 0?"array":C.rowMode){case"object":R.cbArg=(z,se)=>{if(!se.columnNames)se.columnNames=z.getColumnNames([]);let fe=z.get([]),N=Object.create(null);for(let j in se.columnNames)N[se.columnNames[j]]=fe[j];return N};break;case"array":R.cbArg=(z)=>z.get([]);break;case"stmt":if(Array.isArray(C.resultRows))d("exec(): invalid rowMode for a resultRows array: must","be one of 'array', 'object',","a result column number, or column name reference.");R.cbArg=(z)=>z;break;default:if(D.isInt32(C.rowMode)){R.cbArg=(z)=>z.get(C.rowMode);break}else if(typeof C.rowMode==="string"&&C.rowMode.length>1&&C.rowMode[0]==="$"){let z=C.rowMode.substr(1);R.cbArg=(se)=>{let fe=se.get(Object.create(null))[z];return fe===void 0?d(h.SQLITE_NOTFOUND,"exec(): unknown result column:",z):fe};break}d("Invalid rowMode:",C.rowMode)}return R},ve=(H,b,R,...C)=>{let z=H.prepare(b);try{let se=z.bind(R).step()?z.get(...C):void 0;return z.reset(),se}finally{z.finalize()}},O=(H,b,R,C)=>H.exec({sql:b,bind:R,rowMode:C,returnValue:"resultRows"});P.checkRc=(H,b)=>B(H,b),P.prototype={isOpen:function(){return!!this.pointer},affirmOpen:function(){return ie(this)},close:function(){let H=this.pointer;if(H){if(this.onclose&&this.onclose.before instanceof Function)try{this.onclose.before(this)}catch(b){}if(Object.keys(V.get(this)).forEach((b,R)=>{if(R&&R.pointer)try{R.finalize()}catch(C){}}),q.delete(this),V.delete(this),!ee.delete(this))h.sqlite3_close_v2(H);if(this.onclose&&this.onclose.after instanceof Function)try{this.onclose.after(this)}catch(b){}delete this.filename}},changes:function(H=!1,b=!1){let R=ie(this).pointer;if(H)return b?h.sqlite3_total_changes64(R):h.sqlite3_total_changes(R);else return b?h.sqlite3_changes64(R):h.sqlite3_changes(R)},dbFilename:function(H="main"){return h.sqlite3_db_filename(ie(this).pointer,H)},dbName:function(H=0){return h.sqlite3_db_name(ie(this).pointer,H)},dbVfsName:function(H=0){let b,R=h.sqlite3_js_db_vfs(ie(this).pointer,H);if(R){let C=new h.sqlite3_vfs(R);try{b=y.cstrToJs(C.$zName)}finally{C.dispose()}}return b},prepare:function(H){ie(this);let b=y.pstack.pointer,R,C;try{R=y.pstack.alloc(8),P.checkRc(this,h.sqlite3_prepare_v2(this.pointer,H,-1,R,null)),C=y.peekPtr(R)}finally{y.pstack.restore(b)}if(!C)d("Cannot prepare empty SQL.");let z=new ne(this,C,I);return V.get(this)[C]=z,z},exec:function(){ie(this);let H=re(this,arguments);if(!H.sql)return d("exec() requires an SQL string.");let b=H.opt,R=b.callback,C=Array.isArray(b.resultRows)?b.resultRows:void 0,z,se=b.bind,fe=!!(H.cbArg||b.columnNames||C),N=y.scopedAllocPush(),j=Array.isArray(b.saveSql)?b.saveSql:void 0;try{let oe=D.isSQLableTypedArray(H.sql),le=oe?H.sql.byteLength:y.jstrlen(H.sql),ke=y.scopedAlloc(2*y.ptr.size+(le+1)),Ie=y.ptr.add(ke,y.ptr.size),ze=y.ptr.add(Ie,y.ptr.size),He=y.ptr.add(ze,le);if(oe)y.heap8().set(H.sql,ze);else y.jstrcpy(H.sql,y.heap8(),ze,le,!1);y.poke8(y.ptr.add(ze,le),0);while(ze&&y.peek8(ze)){y.pokePtr([ke,Ie],0),P.checkRc(this,h.sqlite3_prepare_v3(this.pointer,ze,le,0,ke,Ie));let ct=y.peekPtr(ke);if(ze=y.peekPtr(Ie),le=Number(y.ptr.add(He,-ze)),!ct)continue;if(j)j.push(h.sqlite3_sql(ct).trim());if(z=new ne(this,ct,I),se&&z.parameterCount)z.bind(se),se=null;if(fe&&z.columnCount){let xt=Array.isArray(b.columnNames)?0:1;if(fe=!1,H.cbArg||C){let br=Object.create(null);for(;z.step();Ee.delete(z)){if(xt++===0)z.getColumnNames(br.columnNames=b.columnNames||[]);Ee.add(z);let On=H.cbArg(z,br);if(C)C.push(On);if(R&&R.call(b,On,z)===!1)break}Ee.delete(z)}if(xt===0)z.getColumnNames(b.columnNames)}else z.step();z.reset().finalize(),z=null}}finally{if(z)Ee.delete(z),z.finalize();y.scopedAllocPop(N)}return H.returnVal()},createFunction:function(b,R,C){let z=(br)=>br instanceof Function;switch(arguments.length){case 1:C=b,b=C.name,R=C.xFunc||0;break;case 2:if(!z(R))C=R,R=C.xFunc||0;break;case 3:break;default:break}if(!C)C={};if(typeof b!=="string")d("Invalid arguments: missing function name.");let se=C.xStep||0,fe=C.xFinal||0,N=C.xValue||0,j=C.xInverse||0,oe=void 0;if(z(R)){if(oe=!1,z(se)||z(fe))d("Ambiguous arguments: scalar or aggregate?");se=fe=null}else if(z(se)){if(!z(fe))d("Missing xFinal() callback for aggregate or window UDF.");R=null}else if(z(fe))d("Missing xStep() callback for aggregate or window UDF.");else d("Missing function-type properties.");if(oe===!1){if(z(N)||z(j))d("xValue and xInverse are not permitted for non-window UDFs.")}else if(z(N)){if(!z(j))d("xInverse must be provided if xValue is.");oe=!0}else if(z(j))d("xValue must be provided if xInverse is.");let le=C.pApp;if(le!==void 0&&le!==null&&!y.isPtr(le))d("Invalid value for pApp property. Must be a legal WASM pointer value.");let ke=C.xDestroy||0;if(ke&&!z(ke))d("xDestroy property must be a function.");let Ie=0;if(U(C,"deterministic"))Ie|=h.SQLITE_DETERMINISTIC;if(U(C,"directOnly"))Ie|=h.SQLITE_DIRECTONLY;if(U(C,"innocuous"))Ie|=h.SQLITE_INNOCUOUS;b=b.toLowerCase();let ze=R||se,He=U(C,"arity"),ct=typeof He==="number"?He:ze.length?ze.length-1:0,xt;if(oe)xt=h.sqlite3_create_window_function(this.pointer,b,ct,h.SQLITE_UTF8|Ie,le||0,se,fe,N,j,ke);else xt=h.sqlite3_create_function_v2(this.pointer,b,ct,h.SQLITE_UTF8|Ie,le||0,R,se,fe,ke);return P.checkRc(this,xt),this},selectValue:function(H,b,R){return ve(this,H,b,0,R)},selectValues:function(H,b,R){let C=this.prepare(H),z=[];try{C.bind(b);while(C.step())z.push(C.get(0,R));C.reset()}finally{C.finalize()}return z},selectArray:function(H,b){return ve(this,H,b,[])},selectObject:function(H,b){return ve(this,H,b,{})},selectArrays:function(H,b){return O(this,H,b,"array")},selectObjects:function(H,b){return O(this,H,b,"object")},openStatementCount:function(){return this.pointer?Object.keys(V.get(this)).length:0},transaction:function(H){let b="BEGIN";if(arguments.length>1){if(/[^a-zA-Z]/.test(arguments[0]))d(h.SQLITE_MISUSE,"Invalid argument for BEGIN qualifier.");b+=" "+arguments[0],H=arguments[1]}ie(this).exec(b);try{let R=H(this);return this.exec("COMMIT"),R}catch(R){throw this.exec("ROLLBACK"),R}},savepoint:function(H){ie(this).exec("SAVEPOINT oo1");try{let b=H(this);return this.exec("RELEASE oo1"),b}catch(b){throw this.exec("ROLLBACK to SAVEPOINT oo1; RELEASE SAVEPOINT oo1"),b}},checkRc:function(H){return B(this,H)}},P.wrapHandle=function(H,b=!1){if(!H||!y.isPtr(H))throw new m.SQLite3Error(h.SQLITE_MISUSE,"Argument must be a WASM sqlite3 pointer");return new P({"sqlite3*":H,"sqlite3*:takeOwnership":!!b})};let M=function(H){if(!H.pointer)d("Stmt has been closed.");return H},Q=function(H){let b=I[H===null||H===void 0?"null":typeof H];switch(b){case I.boolean:case I.null:case I.number:case I.string:return b;case I.bigint:return y.bigIntEnabled?b:void 0;default:return D.isBindableTypedArray(H)?I.blob:void 0}},ue=function(H){return Q(H)||d("Unsupported bind() argument type:",typeof H)},J=function(H,b){let R=typeof b==="number"?b:h.sqlite3_bind_parameter_index(H.pointer,b);if(R===0||!D.isInt32(R))d("Invalid bind() parameter name: "+b);else if(R<1||R>H.parameterCount)d("Bind index",b,"is out of range.");return R},Ee=new Set,xe=new Set,Se=function(H,b){if(Ee.has(H))d("Operation is illegal when statement is locked:",b);return H},Re=function H(b,R,C,z){if(Se(M(b),"bind()"),!H._)H._tooBigInt=(fe)=>d("BigInt value is too big to store without precision loss:",fe),H._={string:function(fe,N,j,oe){let[le,ke]=y.allocCString(j,!0);return(oe?h.sqlite3_bind_blob:h.sqlite3_bind_text)(fe.pointer,N,le,ke,h.SQLITE_WASM_DEALLOC)}};ue(z),R=J(b,R);let se=0;switch(z===null||z===void 0?I.null:C){case I.null:se=h.sqlite3_bind_null(b.pointer,R);break;case I.string:se=H._.string(b,R,z,!1);break;case I.number:{let fe;if(D.isInt32(z))fe=h.sqlite3_bind_int;else if(typeof z==="bigint")if(!D.bigIntFits64(z))H._tooBigInt(z);else if(y.bigIntEnabled)fe=h.sqlite3_bind_int64;else if(D.bigIntFitsDouble(z))z=Number(z),fe=h.sqlite3_bind_double;else H._tooBigInt(z);else if(z=Number(z),y.bigIntEnabled&&Number.isInteger(z))fe=h.sqlite3_bind_int64;else fe=h.sqlite3_bind_double;se=fe(b.pointer,R,z);break}case I.boolean:se=h.sqlite3_bind_int(b.pointer,R,z?1:0);break;case I.blob:{if(typeof z==="string"){se=H._.string(b,R,z,!0);break}else if(z instanceof ArrayBuffer)z=new Uint8Array(z);else if(!D.isBindableTypedArray(z))d("Binding a value as a blob requires","that it be a string, Uint8Array, Int8Array, or ArrayBuffer.");let fe=y.alloc(z.byteLength||1);y.heap8().set(z.byteLength?z:[0],Number(fe)),se=h.sqlite3_bind_blob(b.pointer,R,fe,z.byteLength,h.SQLITE_WASM_DEALLOC);break}default:m.config.warn("Unsupported bind() argument type:",z),d("Unsupported bind() argument type: "+typeof z)}if(se)P.checkRc(b.db.pointer,se);return b};ne.prototype={finalize:function(){let H=this.pointer;if(H){Se(this,"finalize()");let b=ee.delete(this)?0:h.sqlite3_finalize(H);return delete V.get(this.db)[H],q.delete(this),Ee.delete(this),xe.delete(this),delete this.parameterCount,delete this.db,b}},clearBindings:function(){return Se(M(this),"clearBindings()"),h.sqlite3_clear_bindings(this.pointer),xe.delete(this),this},reset:function(H){if(Se(this,"reset()"),H)this.clearBindings();let b=h.sqlite3_reset(M(this).pointer);return xe.delete(this),B(this.db,b),this},bind:function(){M(this);let H,b;switch(arguments.length){case 1:H=1,b=arguments[0];break;case 2:H=arguments[0],b=arguments[1];break;default:d("Invalid bind() arguments.")}if(b===void 0)return this;else if(!this.parameterCount)d("This statement has no bindable parameters.");if(xe.delete(this),b===null)return Re(this,H,I.null,b);else if(Array.isArray(b)){if(arguments.length!==1)d("When binding an array, an index argument is not permitted.");return b.forEach((R,C)=>Re(this,C+1,ue(R),R)),this}else if(b instanceof ArrayBuffer)b=new Uint8Array(b);if(typeof b==="object"&&!D.isBindableTypedArray(b)){if(arguments.length!==1)d("When binding an object, an index argument is not permitted.");return Object.keys(b).forEach((R)=>Re(this,R,ue(b[R]),b[R])),this}else return Re(this,H,ue(b),b);d("Should not reach this point.")},bindAsBlob:function(H,b){if(M(this),arguments.length===1)b=H,H=1;let R=ue(b);if(I.string!==R&&I.blob!==R&&I.null!==R)d("Invalid value type for bindAsBlob()");return Re(this,H,I.blob,b)},step:function(){Se(this,"step()");let H=h.sqlite3_step(M(this).pointer);switch(H){case h.SQLITE_DONE:return xe.delete(this),!1;case h.SQLITE_ROW:return xe.add(this),!0;default:xe.delete(this),m.config.warn("sqlite3_step() rc=",H,h.sqlite3_js_rc_str(H),"SQL =",h.sqlite3_sql(this.pointer)),P.checkRc(this.db.pointer,H)}},stepReset:function(){return this.step(),this.reset()},stepFinalize:function(){try{let H=this.step();return this.reset(),H}finally{try{this.finalize()}catch(H){}}},get:function(H,b){if(!xe.has(M(this)))d("Stmt.step() has not (recently) returned true.");if(Array.isArray(H)){let R=0,C=this.columnCount;while(R<C)H[R]=this.get(R++);return H}else if(H&&typeof H==="object"){let R=0,C=this.columnCount;while(R<C)H[h.sqlite3_column_name(this.pointer,R)]=this.get(R++);return H}switch(G(this,H),b===void 0?h.sqlite3_column_type(this.pointer,H):b){case h.SQLITE_NULL:return null;case h.SQLITE_INTEGER:if(y.bigIntEnabled){let R=h.sqlite3_column_int64(this.pointer,H);if(R>=Number.MIN_SAFE_INTEGER&&R<=Number.MAX_SAFE_INTEGER)return Number(R).valueOf();return R}else{let R=h.sqlite3_column_double(this.pointer,H);if(R>Number.MAX_SAFE_INTEGER||R<Number.MIN_SAFE_INTEGER)d("Integer is out of range for JS integer range: "+R);return D.isInt32(R)?R|0:R}case h.SQLITE_FLOAT:return h.sqlite3_column_double(this.pointer,H);case h.SQLITE_TEXT:return h.sqlite3_column_text(this.pointer,H);case h.SQLITE_BLOB:{let R=h.sqlite3_column_bytes(this.pointer,H),C=h.sqlite3_column_blob(this.pointer,H),z=new Uint8Array(R);if(R){if(z.set(y.heap8u().slice(Number(C),Number(C)+R),0),this.db._blobXfer instanceof Array)this.db._blobXfer.push(z.buffer)}return z}default:d("Don't know how to translate","type of result column #"+H+".")}d("Not reached.")},getInt:function(H){return this.get(H,h.SQLITE_INTEGER)},getFloat:function(H){return this.get(H,h.SQLITE_FLOAT)},getString:function(H){return this.get(H,h.SQLITE_TEXT)},getBlob:function(H){return this.get(H,h.SQLITE_BLOB)},getJSON:function(H){let b=this.get(H,h.SQLITE_STRING);return b===null?b:JSON.parse(b)},getColumnName:function(H){return h.sqlite3_column_name(G(M(this),H).pointer,H)},getColumnNames:function(H=[]){G(M(this),0);let b=this.columnCount;for(let R=0;R<b;++R)H.push(h.sqlite3_column_name(this.pointer,R));return H},getParamIndex:function(H){return M(this).parameterCount?h.sqlite3_bind_parameter_index(this.pointer,H):void 0},getParamName:function(H){return M(this).parameterCount?h.sqlite3_bind_parameter_name(this.pointer,H):void 0},isBusy:function(){return h.sqlite3_stmt_busy(M(this))!==0},isReadOnly:function(){return h.sqlite3_stmt_readonly(M(this))!==0}};{let H={enumerable:!0,get:function(){return q.get(this)},set:()=>d("The pointer property is read-only.")};Object.defineProperty(ne.prototype,"pointer",H),Object.defineProperty(P.prototype,"pointer",H)}Object.defineProperty(ne.prototype,"columnCount",{enumerable:!1,get:function(){return h.sqlite3_column_count(this.pointer)},set:()=>d("The columnCount property is read-only.")}),Object.defineProperty(ne.prototype,"parameterCount",{enumerable:!1,get:function(){return h.sqlite3_bind_parameter_count(this.pointer)},set:()=>d("The parameterCount property is read-only.")}),ne.wrapHandle=function(H,b,R=!1){if(!(H instanceof P)||!H.pointer)throw new m.SQLite3Error(m.SQLITE_MISUSE,"First argument must be an opened sqlite3.oo1.DB instance");if(!b||!y.isPtr(b))throw new m.SQLite3Error(m.SQLITE_MISUSE,"Second argument must be a WASM sqlite3_stmt pointer");return new ne(H,b,I,!!R)},m.oo1={DB:P,Stmt:ne}}),globalThis.sqlite3ApiBootstrap.initializers.push(function(m){let d=m.util;m.initWorker1API=function(){let h=(...K)=>{throw Error(K.join(" "))};if(!(globalThis.WorkerGlobalScope instanceof Function))h("initWorker1API() must be run from a Worker thread.");let y=this.sqlite3||h("Missing this.sqlite3 object."),D=y.oo1.DB,x=function(K){let Y=q.idMap.get(K);if(Y)return Y;return Y="db#"+ ++q.idSeq+":"+Math.floor(Math.random()*1e8)+":"+Math.floor(Math.random()*1e8),q.idMap.set(K,Y),Y},q={dbList:[],idSeq:0,idMap:new WeakMap,xfer:[],open:function(K){let Y=new D(K);if(this.dbs[x(Y)]=Y,this.dbList.indexOf(Y)<0)this.dbList.push(Y);return Y},close:function(K,Y){if(K){delete this.dbs[x(K)];let ye=K.filename,P=d.sqlite3__wasm_db_vfs(K.pointer,0);K.close();let I=this.dbList.indexOf(K);if(I>=0)this.dbList.splice(I,1);if(Y&&ye&&P)d.sqlite3__wasm_vfs_unlink(P,ye)}},post:function(K,Y){if(Y&&Y.length)globalThis.postMessage(K,Array.from(Y)),Y.length=0;else globalThis.postMessage(K)},dbs:Object.create(null),getDb:function(K,Y=!0){return this.dbs[K]||(Y?h("Unknown (or closed) DB ID:",K):void 0)}},ee=function(K=q.dbList[0]){return K&&K.pointer?K:h("DB is not opened.")},V=function(K,Y=!0){let ye=q.getDb(K.dbId,!1)||q.dbList[0];return Y?ee(ye):ye},U=function(){return q.dbList[0]&&x(q.dbList[0])},B={open:function(K){let Y=Object.create(null),ye=K.args||Object.create(null);if(ye.simulateError)h("Throwing because of simulateError flag.");let P=Object.create(null);Y.vfs=ye.vfs,Y.filename=ye.filename||"";let I=q.open(Y);return P.filename=I.filename,P.persistent=!!y.capi.sqlite3_js_db_uses_vfs(I.pointer,"opfs"),P.dbId=x(I),P.vfs=I.dbVfsName(),P},close:function(K){let Y=V(K,!1),ye={filename:Y&&Y.filename};if(Y){let P=K.args&&typeof K.args==="object"?!!K.args.unlink:!1;q.close(Y,P)}return ye},exec:function(K){let Y=typeof K.args==="string"?{sql:K.args}:K.args||Object.create(null);if(Y.rowMode==="stmt")h("Invalid rowMode for 'exec': stmt mode","does not work in the Worker API.");else if(!Y.sql)h("'exec' requires input SQL.");let ye=V(K);if(Y.callback||Array.isArray(Y.resultRows))ye._blobXfer=q.xfer;let P=Y.callback,I=0,ne=!!Y.columnNames;if(typeof P==="string"){if(!ne)Y.columnNames=[];Y.callback=function(ie,G){q.post({type:P,columnNames:Y.columnNames,rowNumber:++I,row:ie},q.xfer)}}try{let ie=Y.countChanges?ye.changes(!0,Y.countChanges===64):void 0;if(ye.exec(Y),ie!==void 0)Y.changeCount=ye.changes(!0,Y.countChanges===64)-ie;let G=Y.lastInsertRowId?y.capi.sqlite3_last_insert_rowid(ye):void 0;if(G!==void 0)Y.lastInsertRowId=G;if(Y.callback instanceof Function)Y.callback=P,q.post({type:P,columnNames:Y.columnNames,rowNumber:null,row:void 0})}finally{if(delete ye._blobXfer,Y.callback)Y.callback=P}return Y},"config-get":function(){let K=Object.create(null),Y=y.config;return["bigIntEnabled"].forEach(function(ye){if(Object.getOwnPropertyDescriptor(Y,ye))K[ye]=Y[ye]}),K.version=y.version,K.vfsList=y.capi.sqlite3_js_vfs_list(),K},export:function(K){let Y=V(K),ye={byteArray:y.capi.sqlite3_js_db_export(Y.pointer),filename:Y.filename,mimetype:"application/x-sqlite3"};return q.xfer.push(ye.byteArray.buffer),ye},toss:function(K){h("Testing worker exception")}};globalThis.onmessage=async function(K){K=K.data;let Y,ye=K.dbId,P=K.type,I=performance.now();try{if(B.hasOwnProperty(P)&&B[P]instanceof Function)Y=await B[P](K);else h("Unknown db worker message type:",K.type)}catch(ne){if(P="error",Y={operation:K.type,message:ne.message,errorClass:ne.name,input:K},ne.stack)Y.stack=typeof ne.stack==="string"?ne.stack.split(/\n\s*/):ne.stack}if(!ye)ye=Y.dbId||U();q.post({type:P,dbId:ye,messageId:K.messageId,workerReceivedTime:I,workerRespondTime:performance.now(),departureTime:K.departureTime,result:Y},q.xfer)},globalThis.postMessage({type:"sqlite3-api",result:"worker1-ready"})}.bind({sqlite3:m})}),globalThis.sqlite3ApiBootstrap.initializers.push(function(m){let{wasm:d,capi:h}=m,y=m.util.toss3,D=Object.create(null);m.vfs=D,h.sqlite3_vfs.prototype.registerVfs=function(x=!1){if(!(this instanceof m.capi.sqlite3_vfs))y("Expecting a sqlite3_vfs-type argument.");let q=h.sqlite3_vfs_register(this,x?1:0);if(q)y("sqlite3_vfs_register(",this,") failed with rc",q);if(this.pointer!==h.sqlite3_vfs_find(this.$zName))y("BUG: sqlite3_vfs_find(vfs.$zName) failed for just-installed VFS",this);return this},D.installVfs=function(x){let q=0,ee=["io","vfs"];for(let V of ee){let U=x[V];if(U){if(++q,U.struct.installMethods(U.methods,!!U.applyArgcCheck),V==="vfs"){if(!U.struct.$zName&&typeof U.name==="string")U.struct.addOnDispose(U.struct.$zName=d.allocCString(U.name));U.struct.registerVfs(!!U.asDefault)}}}if(!q)y("Misuse: installVfs() options object requires at least","one of:",ee);return this}}),globalThis.sqlite3ApiBootstrap.initializers.push(function(m){if(!m.wasm.exports.sqlite3_declare_vtab)return;let{wasm:d,capi:h}=m,y=m.util.toss3,D=Object.create(null);m.vtab=D;let x=h.sqlite3_index_info;x.prototype.nthConstraint=function(V,U=!1){if(V<0||V>=this.$nConstraint)return!1;let B=d.ptr.add(this.$aConstraint,x.sqlite3_index_constraint.structInfo.sizeof*V);return U?B:new x.sqlite3_index_constraint(B)},x.prototype.nthConstraintUsage=function(V,U=!1){if(V<0||V>=this.$nConstraint)return!1;let B=d.ptr.add(this.$aConstraintUsage,x.sqlite3_index_constraint_usage.structInfo.sizeof*V);return U?B:new x.sqlite3_index_constraint_usage(B)},x.prototype.nthOrderBy=function(V,U=!1){if(V<0||V>=this.$nOrderBy)return!1;let B=d.ptr.add(this.$aOrderBy,x.sqlite3_index_orderby.structInfo.sizeof*V);return U?B:new x.sqlite3_index_orderby(B)};let q=function(V,U){return function(B,K=!1){if(arguments.length===0)B=new U;if(B instanceof U)return this.set(B.pointer,B),B;else if(!d.isPtr(B))m.SQLite3Error.toss("Invalid argument to",V+"()");let Y=this.get(B);if(K)this.delete(B);return Y}.bind(new Map)},ee=function(V,U){let B=q(V,U);return Object.assign(Object.create(null),{StructType:U,create:(K)=>{let Y=B();return d.pokePtr(K,Y.pointer),Y},get:(K)=>B(K),unget:(K)=>B(K,!0),dispose:(K)=>B(K,!0)?.dispose?.()})};D.xVtab=ee("xVtab",h.sqlite3_vtab),D.xCursor=ee("xCursor",h.sqlite3_vtab_cursor),D.xIndexInfo=(V)=>new h.sqlite3_index_info(V),D.xError=function V(U,B,K){if(V.errorReporter instanceof Function)try{V.errorReporter("sqlite3_module::"+U+"(): "+B.message)}catch(ye){}let Y;if(B instanceof m.WasmAllocError)Y=h.SQLITE_NOMEM;else if(arguments.length>2)Y=K;else if(B instanceof m.SQLite3Error)Y=B.resultCode;return Y||h.SQLITE_ERROR},D.xError.errorReporter=m.config.error.bind(m.config),D.xRowid=(V,U)=>d.poke(V,U,"i64"),D.setupModule=function(V){let U=!1,B=this instanceof h.sqlite3_module?this:V.struct||(U=new h.sqlite3_module);try{let K=V.methods||y("Missing 'methods' object.");for(let Y of Object.entries({xConnect:"xCreate",xDisconnect:"xDestroy"})){let ye=Y[0],P=Y[1];if(K[ye]===!0)K[ye]=K[P];else if(K[P]===!0)K[P]=K[ye]}if(V.catchExceptions){let Y=function(I,ne){if(["xConnect","xCreate"].indexOf(I)>=0)return function(ie,G,re,ve,O,M){try{return ne(...arguments)||0}catch(Q){if(!(Q instanceof m.WasmAllocError))d.dealloc(d.peekPtr(M)),d.pokePtr(M,d.allocCString(Q.message));return D.xError(I,Q)}};else return function(...ie){try{return ne(...ie)||0}catch(G){return D.xError(I,G)}}},ye=["xCreate","xConnect","xBestIndex","xDisconnect","xDestroy","xOpen","xClose","xFilter","xNext","xEof","xColumn","xRowid","xUpdate","xBegin","xSync","xCommit","xRollback","xFindFunction","xRename","xSavepoint","xRelease","xRollbackTo","xShadowName"],P=Object.create(null);for(let I of ye){let ne=K[I];if(!(ne instanceof Function))continue;else if(I==="xConnect"&&K.xCreate===ne)P[I]=K.xCreate;else if(I==="xCreate"&&K.xConnect===ne)P[I]=K.xConnect;else P[I]=Y(I,ne)}B.installMethods(P,!1)}else B.installMethods(K,!!V.applyArgcCheck);if(B.$iVersion===0){let Y;if(typeof V.iVersion==="number")Y=V.iVersion;else if(B.$xIntegrity)Y=4;else if(B.$xShadowName)Y=3;else if(B.$xSavePoint||B.$xRelease||B.$xRollbackTo)Y=2;else Y=1;B.$iVersion=Y}}catch(K){if(U)U.dispose();throw K}return B},h.sqlite3_module.prototype.setupModule=function(V){return D.setupModule.call(this,V)}}),globalThis.sqlite3ApiBootstrap.initializers.push(function(m){if(m.config.disable?.vfs?.kvvfs)return;let d=m.capi,{sqlite3_kvvfs_methods:h,KVVfsFile:y}=d,D=m.capi.sqlite3_vfs_find("kvvfs");if(delete d.sqlite3_kvvfs_methods,delete d.KVVfsFile,!D)return;let{util:x,wasm:q}=m,ee=x.toss3,V=new h(q.exports.sqlite3__wasm_kvvfs_methods());x.assert(32<=V.$nKeySize,"unexpected kvvfsMethods.$nKeySize: "+V.$nKeySize);let U=Object.assign(Object.create(null),{rxJournalSuffix:/-journal$/,zKeyJrnl:q.allocCString("jrnl"),zKeySz:q.allocCString("sz"),keySize:V.$nKeySize,buffer:Object.assign(Object.create(null),{n:V.$nBufferSize,pool:Object.create(null)})});U.memBuffer=(Z=0)=>U.buffer.pool[Z]??=q.alloc(U.buffer.n),U.memBufferFree=(Z)=>{let ae=U.buffer.pool[Z];if(ae)q.dealloc(ae),delete U.buffer.pool[Z]};let B=()=>{},K=m.__isUnderTest?(...Z)=>m.config.debug?.("kvvfs:",...Z):B,Y=(...Z)=>m.config.warn?.("kvvfs:",...Z),ye=(...Z)=>m.config.error?.("kvvfs:",...Z);class P{#e=Object.create(null);#o=null;#i=0;constructor(){this.clear()}#t(){return this.#o??=Object.keys(this.#e)}key(Z){if(Z<0||Z>=this.#i)return null;return this.#t()[Z]}getItem(Z){return this.#e[Z]??null}setItem(Z,ae){if(!(Z in this.#e))++this.#i,this.#o=null;this.#e[Z]=""+ae}removeItem(Z){if(Z in this.#e)delete this.#e[Z],--this.#i,this.#o=null}clear(){this.#e=Object.create(null),this.#o=null,this.#i=0}get length(){return this.#i}}let I=(Z)=>Z==="local"||Z==="session",ne=(Z)=>I(Z)?"kvvfs-"+Z+"-":"",ie=function(Z,ae=!1){if(I(Z))return;let me=new Blob([Z]).size;if(!me)ee(d.SQLITE_MISUSE,"Empty name is not permitted.");let be=U.keySize-1;if(U.rxJournalSuffix.test(Z)){if(!ae)ee(d.SQLITE_MISUSE,"Storage names may not have a '-journal' suffix.")}else if(["-wal","-shm"].filter((Le)=>Z.endsWith(Le)).length)ee(d.SQLITE_MISUSE,"Storage names may not have a -wal or -shm suffix.");else be-=8;if(me>be)ee(d.SQLITE_RANGE,"Storage name is too long. Limit =",be);let Ae;for(Ae=0;Ae<me;++Ae){let Le=Z.codePointAt(Ae);if(Le<32)ee(d.SQLITE_RANGE,"Illegal character ("+Le+"d) in storage name:",Z)}},G=(Z,ae=void 0)=>Object.assign(Object.create(null),{jzClass:Z,refc:1,deleteAtRefc0:!1,storage:ae||new P,keyPrefix:ne(Z),files:[],listeners:void 0}),re=m.kvvfs=Object.create(null);if(m.__isUnderTest)re.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 ve=function(Z){let ae=U.rxJournalSuffix.test(Z.jzClass)?Z.jzClass.replace(U.rxJournalSuffix,""):Z.jzClass+"-journal";if(re?.log?.xClose&&K("cleaning up storage handles [",Z.jzClass,ae,"]",Z),delete U.storagePool[Z.jzClass],delete U.storagePool[ae],!m.__isUnderTest)delete Z.storage,delete Z.refc},O=(Z)=>U.storagePool[Z.jzClass]=U.storagePool[Z.jzClass+"-journal"]=Z,M=".";if(U.storagePool=Object.assign(Object.create(null),{[M]:G(M)}),globalThis.Storage){if(globalThis.localStorage instanceof globalThis.Storage)U.storagePool.local=G("local",globalThis.localStorage);if(globalThis.sessionStorage instanceof globalThis.Storage)U.storagePool.session=G("session",globalThis.sessionStorage)}U.builtinStorageNames=Object.keys(U.storagePool);let Q=(Z)=>U.builtinStorageNames.indexOf(Z)>-1;for(let Z of Object.keys(U.storagePool)){let ae=U.storagePool[Z];U.storagePool[Z+"-journal"]=ae}U.setError=(Z=void 0,ae=d.SQLITE_ERROR)=>{if(Z)return U.lastError=Z,Z.resultCode|0||ae;return delete U.lastError,0},U.popError=()=>{let Z=U.lastError;return delete U.lastError,Z};let ue=(Z)=>{Y("kvvfs.listener handler threw:",Z)},J=q.exports.sqlite3__wasm_kvvfs_decode,Ee=q.exports.sqlite3__wasm_kvvfs_encode,xe=async function(Z,ae,...me){try{if(ae.keyPrefix&&me[0])me[0]=me[0].replace(ae.keyPrefix,"");let be,Ae,Le,Me;for(let qe of ae.listeners){let je=Object.create(null);je.storageName=ae.jzClass,je.type=Z,qe.decodePages;let rt=qe.events[Z];if(rt){if(!qe.includeJournal&&me[0]==="jrnl")continue;if(Z==="write"&&qe.decodePages&&+me[0]>0){if(je.data=[me[0]],Me?.[me[0]]){je.data[1]=Me[me[0]];continue}be??=new TextEncoder("utf-8"),Ae??=U.memBuffer(10),Le??=U.memBuffer(11);let pt=be.encode(me[1]),Ye=q.heap8u();Ye.set(pt,Number(Ae)),Ye[q.ptr.addn(Ae,pt.length)]=0;let Ht=J(Ae,Le,U.buffer.n);if(Ht>0)Me??=Object.create(null),Me[me[0]]=je.data[1]=Ye.slice(Number(Le),q.ptr.addn(Le,Ht));else continue}else je.data=me.length?me.length===1?me[0]:me:void 0;try{rt(je)?.catch?.(ue)}catch(pt){Y("notifyListeners [",ae.jzClass,"]",Z,pt)}}}}catch(be){ue(be)}},Se=(Z)=>typeof Z==="string"?U.storagePool[Z]:U.storagePool[q.cstrToJs(Z)],Re=q.exports.sqlite3__wasm_kvvfsMakeKey,H=(Z,ae,me)=>ae&&Z.keyPrefix?Re(ae,me):me,b=(Z,ae,me)=>q.cstrToJs(H(Z,ae,me)),R=(Z)=>+Z.storage.getItem(Z.keyPrefix+"sz"),C=new Map,z={vfs:Object.create(null),ioDb:Object.create(null),ioJrnl:Object.create(null)},se=new d.sqlite3_vfs(V.$pVfs),fe=new d.sqlite3_io_methods(V.$pIoDb),N=new d.sqlite3_io_methods(V.$pIoJrnl),j=Object.create(null),oe=Object.assign(Object.create(null),{pFileHandles:C,cache:U,storageForZClass:Se,KVVfsStorage:P,disablePageSizeChange:!0});if(re.log)re.internal=oe;let le={recordHandler:{xRcrdRead:(Z,ae,me,be)=>{try{let Ae=q.cstrToJs(Z),Le=Se(Ae);if(!Le)return-1;let Me=b(Le,Z,ae);re?.log?.xRcrdRead&&Y("xRcrdRead",Ae,Me,be,Le);let qe=Le.storage.getItem(Me);if(qe===null)return-1;let je=qe.length;if(be<=0)return je;else if(be===1)return q.poke(me,0),je;if(be+1<je)ee(d.SQLITE_RANGE,"xRcrdRead()",Ae,Me,"input buffer is too small: need",je,"but have",be);let rt=U.memBuffer(0),pt=q.heap8(),Ye;for(Ye=0;Ye<je;++Ye)pt[q.ptr.add(rt,Ye)]=qe.codePointAt(Ye)&255;return pt.copyWithin(Number(me),Number(rt),q.ptr.addn(rt,Ye)),pt[q.ptr.add(me,je)]=0,be}catch(Ae){return ye("kvrecordRead()",Ae),U.setError(Ae),-2}},xRcrdWrite:(Z,ae,me)=>{try{let be=Se(Z),Ae=b(be,Z,ae),Le=q.cstrToJs(me);return re?.log?.xRcrdWrite&&Y("xRcrdWrite",Ae,be),be.storage.setItem(Ae,Le),be.listeners&&xe("write",be,Ae,Le),0}catch(be){return ye("kvrecordWrite()",be),U.setError(be,d.SQLITE_IOERR)}},xRcrdDelete:(Z,ae)=>{try{let me=Se(Z),be=b(me,Z,ae);return re?.log?.xRcrdDelete&&Y("xRcrdDelete",be,me),me.storage.removeItem(be),me.listeners&&xe("delete",me,be),0}catch(me){return ye("kvrecordDelete()",me),U.setError(me,d.SQLITE_IOERR)}}},vfs:{xOpen:function(Z,ae,me,be,Ae){U.popError();let Le;try{if(!ae)Le=q.allocCString(""+me+"."+(Math.random()*1e5|0)),ae=Le;let Me=q.cstrToJs(ae);if(re?.log?.xOpen&&K("xOpen",Me,"flags =",be),ie(Me,!0),be&(d.SQLITE_OPEN_MAIN_DB|d.SQLITE_OPEN_TEMP_DB|d.SQLITE_OPEN_TRANSIENT_DB)&&U.rxJournalSuffix.test(Me))ee(d.SQLITE_ERROR,"DB files may not have a '-journal' suffix.");let qe=Se(Me);if(!qe&&!(be&d.SQLITE_OPEN_CREATE))ee(d.SQLITE_ERROR,"Storage not found:",Me);let je=z.vfs.xOpen(Z,ae,me,be,Ae);if(je)return je;let rt=!!(d.SQLITE_OPEN_DELETEONCLOSE&be);if(q.isPtr(arguments[1])){if(d.sqlite3_uri_boolean(ae,"delete-on-close",0))rt=!0}let pt=new y(me);if(x.assert(pt.$zClass,"Missing f.$zClass"),pt.addOnDispose(Le),Le=void 0,qe)++qe.refc,qe.files.push(pt),q.poke32(Ae,be);else{q.poke32(Ae,be|d.SQLITE_OPEN_CREATE),x.assert(!pt.$isJournal,"Opening a journal before its db? "+Me);let Ye=Me.replace(U.rxJournalSuffix,"");qe=G(Ye),O(qe),qe.files.push(pt),qe.deleteAtRefc0=rt,re?.log?.xOpen&&K("xOpen installed storage handle [",Ye,Ye+"-journal","]",qe)}return C.set(me,{store:qe,file:pt,jzClass:Me}),qe.listeners&&xe("open",qe,qe.files.length),0}catch(Me){return Y("xOpen:",Me),U.setError(Me)}finally{Le&&q.dealloc(Le)}},xDelete:function(Z,ae,me){U.popError();try{let be=q.cstrToJs(ae);if(U.rxJournalSuffix.test(be))j.xRcrdDelete(ae,U.zKeyJrnl);return 0}catch(be){return Y("xDelete",be),U.setError(be)}},xAccess:function(Z,ae,me,be){U.popError();try{let Ae=Se(ae),Le=Ae?.jzClass||q.cstrToJs(ae);if(re?.log?.xAccess)K("xAccess",Le,"flags =",me,"*pResOut =",q.peek32(be),"store =",Ae);if(!Ae)try{ie(Le)}catch(Me){return q.poke32(be,0),0}if(Ae){let Me=Ae.keyPrefix+(U.rxJournalSuffix.test(Le)?"jrnl":"1"),qe=Ae.storage.getItem(Me)?0:1;q.poke32(be,qe)}else q.poke32(be,0);return 0}catch(Ae){return ye("xAccess",Ae),U.setError(Ae)}},xRandomness:function(Z,ae,me){let be=q.heap8u(),Ae=0,Le=Number(me);for(;Ae<ae;++Ae)be[Le+Ae]=Math.random()*255000&255;return ae},xGetLastError:function(Z,ae,me){let be=U.popError();if(K("xGetLastError",be),be){let Ae=q.scopedAllocPush();try{let[Le,Me]=q.scopedAllocCString(be.message,!0);if(q.cstrncpy(me,Le,ae),Me>ae)q.poke8(q.ptr.add(me,ae,-1),0);return K("set xGetLastError",be.message),be.resultCode|0||d.SQLITE_IOERR}catch(Le){return d.SQLITE_NOMEM}finally{q.scopedAllocPop(Ae)}}return 0}},ioDb:{xClose:function(Z){U.popError();try{let ae=C.get(Z);if(re?.log?.xClose&&K("xClose",Z,ae),ae){C.delete(Z);let me=ae.store;if(me.files=me.files.filter((be)=>be!==ae.file),--me.refc<=0&&me.deleteAtRefc0)ve(me);z.ioDb.xClose(Z),ae.file.dispose(),me.listeners&&xe("close",me,me.files.length)}return 0}catch(ae){return ye("xClose",ae),U.setError(ae)}},xFileControl:function(Z,ae,me){U.popError();try{let be=C.get(Z);if(x.assert(be,"Missing KVVfsFile handle"),re?.log?.xFileControl&&K("xFileControl",be,"op =",ae),ae===d.SQLITE_FCNTL_PRAGMA&&oe.disablePageSizeChange){let Le=q.peekPtr(q.ptr.add(me,q.ptr.size));if(q.cstrToJs(Le)==="page_size"){re?.log?.xFileControl&&K("xFileControl pragma",q.cstrToJs(Le));let Me=q.peekPtr(q.ptr.add(me,2*q.ptr.size));if(Me)return re?.log?.xFileControl&&Y("xFileControl pragma",be,"NOT setting page size to",q.cstrToJs(Me)),be.file.$szPage=-1,0;else if(be.file.$szPage>0)return re?.log?.xFileControl&&Y("xFileControl",be,"getting page size",be.file.$szPage),q.pokePtr(me,q.allocCString(""+be.file.$szPage)),0}}let Ae=z.ioDb.xFileControl(Z,ae,me);if(Ae==0&&d.SQLITE_FCNTL_SYNC===ae)be.store.listeners&&xe("sync",be.store,!1);return Ae}catch(be){return ye("xFileControl",be),U.setError(be)}},xSync:function(Z,ae){U.popError();try{let me=C.get(Z);re?.log?.xSync&&K("xSync",me),x.assert(me,"Missing KVVfsFile handle");let be=z.ioDb.xSync(Z,ae);if(be==0&&me.store.listeners)xe("sync",me.store,!0);return be}catch(me){return ye("xSync",me),U.setError(me)}}},ioJrnl:{xClose:!0}};try{x.assert(U.buffer.n>132096,"Heap buffer is not large enough");for(let Z of Object.entries(le.recordHandler)){let ae=Z[0],me=Z[1];j[ae]=me,V[V.memberKey(ae)]=q.installFunction(V.memberSignature(ae),me)}for(let Z of Object.entries(le.vfs)){let ae=Z[0],me=Z[1],be=se.memberKey(ae),Ae=se.structInfo.members[ae]||x.toss("Missing pVfs.structInfo[",ae,"]");z.vfs[ae]=q.functionEntry(se[be]),se[be]=q.installFunction(Ae.signature,me)}for(let Z of Object.entries(le.ioDb)){let ae=Z[0],me=Z[1],be=fe.memberKey(ae);z.ioDb[ae]=q.functionEntry(fe[be])||x.toss("Missing native pIoDb[",be,"]"),fe[be]=q.installFunction(fe.memberSignature(ae),me)}for(let Z of Object.entries(le.ioJrnl)){let ae=Z[0],me=Z[1],be=N.memberKey(ae);if(z.ioJrnl[ae]=q.functionEntry(N[be])||x.toss("Missing native pIoJrnl[",be,"]"),me===!0)N[be]=fe[be]||x.toss("Missing copied pIoDb[",be,"]");else N[be]=q.installFunction(N.memberSignature(ae),me)}}finally{V.dispose(),se.dispose(),fe.dispose(),N.dispose()}let ke=function Z(ae){if(ae==="")return Z("local")+Z("session");let me=Se(ae);if(!me)return 0;if(me.files.length)if(globalThis.localStorage===me.storage||globalThis.sessionStorage===me.storage);else ee(d.SQLITE_ACCESS,"Cannot clear in-use database storage.");let be=me.storage,Ae=[],Le,Me=be.length;for(Le=0;Le<Me;++Le){let qe=be.key(Le);if(!me.keyPrefix||qe.startsWith(me.keyPrefix))Ae.push(qe)}return Ae.forEach((qe)=>be.removeItem(qe)),Ae.length},Ie=function Z(ae){if(ae==="")return Z("local")+Z("session");let me=Se(ae);if(!me)return 0;let be=me.storage,Ae,Le=0;for(Ae=0;Ae<be.length;++Ae){let Me=be.key(Ae);if(!me.keyPrefix||Me.startsWith(me.keyPrefix))Le+=Me.length,Le+=be.getItem(Me).length}return Le*2},ze=function(...ae){let me;if(ae.length===1&&typeof ae[0]==="object")me=ae[0];else if(ae.length)me=Object.assign(Object.create(null),{name:ae[0]});let be=me?Se(me.name):null;if(!be)ee(d.SQLITE_NOTFOUND,"There is no kvvfs storage named",me?.name);let Ae=be.storage,Le=Object.assign(Object.create(null),{name:be.jzClass,timestamp:Date.now(),pages:[]}),Me=Object.create(null),qe=be.keyPrefix,je=qe?/^kvvfs-[^-]+-(\w+)/:void 0,rt=0,pt=Ae.length;for(;rt<pt;++rt){let Ye=Ae.key(rt);if(!qe||Ye.startsWith(qe)){let Ht=(qe?je.exec(Ye):void 0)?.[1]??Ye;switch(Ht){case"jrnl":if(me.includeJournal)Le.journal=Ae.getItem(Ye);break;case"sz":Le.size=+Ae.getItem(Ye);break;default:if(Ht=+Ht,!x.isInt32(Ht)||Ht<=0)ee(d.SQLITE_RANGE,"Malformed kvvfs key: "+Ye);if(me.decodePages){let wr=Ae.getItem(Ye),po=wr.length,Dr=U.memBuffer(0),Cn=U.memBuffer(1),Go=q.heap8u(),ar=0;for(;ar<po;++ar)Go[q.ptr.add(Dr,ar)]=wr.codePointAt(ar)&255;Go[q.ptr.add(Dr,ar)]=0;let Wi=J(Dr,Cn,U.buffer.n);Me[Ht]=Go.slice(Number(Cn),q.ptr.addn(Cn,Wi))}else Me[Ht]=Ae.getItem(Ye);break}}}if(me.decodePages)U.memBufferFree(1);return Object.keys(Me).map((Ye)=>+Ye).sort().forEach((Ye)=>Le.pages.push(Me[Ye])),Le},He=function(Z,ae=!1){if(!Z?.timestamp||!Z.name||Z.size===void 0||!Array.isArray(Z.pages))ee(d.SQLITE_MISUSE,"Malformed export object.");else if(!Z.size||Z.size!==(Z.size|0)||Z.size>=2147483647)ee(d.SQLITE_RANGE,"Invalid db size: "+Z.size);ie(Z.name);let me=Se(Z.name),be=!me;if(me){if(!ae)ee(d.SQLITE_ACCESS,"Storage '"+Z.name+"' already exists and","overwrite was not specified.");else if(!me.files||!me.jzClass)ee(d.SQLITE_ERROR,"Internal storage object",Z.name,"seems to be malformed.");else if(me.files.length)ee(d.SQLITE_IOERR_ACCESS,"Cannot import db storage while it is in use.");ke(Z.name)}else me=G(Z.name);let Ae=ne(Z.name),Le;try{let Me=me.storage;if(Me.setItem(Ae+"sz",Z.size),Z.journal)Me.setItem(Ae+"jrnl",Z.journal);if(Z.pages[0]instanceof Uint8Array)Z.pages.forEach((qe,je)=>{let rt=qe.length;Le??=U.memBuffer(1);let pt=U.memBuffer(0),Ye=q.heap8u();Ye.set(qe,Number(pt)),Ye[q.ptr.addn(pt,rt)]=0;let Ht=Ee(pt,rt,Le);x.assert(Ht<U.buffer.n,"Impossibly long output - possibly smashed the heap"),x.assert(q.peek8(q.ptr.add(Le,Ht))===0,"Expecting NUL-terminated encoded output");let wr=q.cstrToJs(Le);Me.setItem(Ae+(je+1),wr)});else if(Z.pages[0])Z.pages.forEach((qe,je)=>Me.setItem(Ae+(je+1),qe));if(be)O(me)}catch{if(!be)try{ke(Z.name)}catch(Me){}}finally{if(Le)U.memBufferFree(1)}return this},ct=function(Z){let ae=Se(Z);if(ae){++ae.refc;return}ie(Z),O(G(Z))},xt=function(Z){let ae=Se(Z);if(!ae||I(ae.jzClass)||Q(ae.jzClass)||U.rxJournalSuffix.test(Z))return!1;if(ae.refc>ae.files.length||ae.files.length===0){if(--ae.refc<=0)ve(ae);return!0}return!1},br=function(Z){if(!Z||typeof Z!=="object")ee(d.SQLITE_MISUSE,"Expecting a listener object.");let ae=Se(Z.storage);if(!ae)if(Z.storage&&Z.reserve)ct(Z.storage),ae=Se(Z.storage),x.assert(ae,"Unexpectedly cannot fetch reserved storage "+Z.storage);else ee(d.SQLITE_NOTFOUND,"No such storage:",Z.storage);if(Z.events)(ae.listeners??=[]).push(Z)},On=function(Z){let ae=Se(Z?.storage);if(ae?.listeners&&Z.events){let me=ae.listeners.length;ae.listeners=ae.listeners.filter((Ae)=>Ae!==Z);let be=me>ae.listeners.length;if(!ae.listeners.length)ae.listeners=void 0;return be}return!1};if(m.kvvfs.reserve=ct,m.kvvfs.import=He,m.kvvfs.export=ze,m.kvvfs.unlink=xt,m.kvvfs.listen=br,m.kvvfs.unlisten=On,m.kvvfs.exists=(Z)=>!!Se(Z),m.kvvfs.estimateSize=Ie,m.kvvfs.clear=ke,globalThis.Storage)d.sqlite3_js_kvvfs_size=(Z="")=>Ie(Z),d.sqlite3_js_kvvfs_clear=(Z="")=>ke(Z);if(m.oo1?.DB){let Z=m.oo1.DB;m.oo1.JsStorageDb=function(me=m.oo1.JsStorageDb.defaultStorageName){let be=Z.dbCtorHelper.normalizeArgs(...arguments);switch(be.vfs="kvvfs",be.filename){case":sessionStorage:":be.filename="session";break;case":localStorage:":be.filename="local";break}let Ae=/(file:(\/\/)?)([^?]+)/.exec(be.filename);ie(Ae?Ae[3]:be.filename),Z.dbCtorHelper.call(this,be)},m.oo1.JsStorageDb.defaultStorageName=U.storagePool.session?"session":M;let ae=m.oo1.JsStorageDb;ae.prototype=Object.create(Z.prototype),ae.clearStorage=ke,ae.prototype.clearStorage=function(){return ae.clearStorage(this.affirmOpen().dbFilename(),!0)},ae.storageSize=Ie,ae.prototype.storageSize=function(){return ae.storageSize(this.affirmOpen().dbFilename(),!0)}}if(m.__isUnderTest&&m.vtab){let Z=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(Z).forEach((Me,qe)=>Z[Me].colId=qe);let ae=m.vtab,me=Object.assign(Object.create(null),{row:function(){return U.storagePool[this.names[this.rowid]]}});Object.assign(Object.create(me),{rowid:0,names:Object.keys(U.storagePool).filter((Me)=>!U.rxJournalSuffix.test(Me))});let be=function(Me,qe){let je=Me instanceof d.sqlite3_vtab_cursor?Me:ae.xCursor.get(Me);if(qe||!je.vTabState)je.vTabState=Object.assign(Object.create(me),{rowid:0,names:Object.keys(U.storagePool).filter((rt)=>!U.rxJournalSuffix.test(rt))});return je.vTabState},Ae=()=>{},Le=function Me(){return Me.mod??=new m.capi.sqlite3_module().setupModule({catchExceptions:!0,methods:{xConnect:function(qe,je,rt,pt,Ye,Ht){Ae("xConnect");try{let wr=[];Object.keys(Z).forEach((Dr)=>{wr.push(Dr+" "+Z[Dr].type)});let po=d.sqlite3_declare_vtab(qe,"CREATE TABLE ignored("+wr.join(",")+")");if(po===0){let Dr=ae.xVtab.create(Ye);x.assert(Dr===ae.xVtab.get(q.peekPtr(Ye)),"output pointer check failed")}return po}catch(wr){return ae.xError("xConnect",wr,d.SQLITE_ERROR)}},xCreate:q.ptr.null,xDisconnect:function(qe){return Ae("xDisconnect",...arguments),ae.xVtab.dispose(qe),0},xOpen:function(qe,je){return Ae("xOpen",...arguments),ae.xCursor.create(je),0},xClose:function(qe){Ae("xClose",...arguments);let je=ae.xCursor.unget(qe);return delete je.vTabState,je.dispose(),0},xNext:function(qe){Ae("xNext",...arguments);let je=ae.xCursor.get(qe);return++be(je).rowid,0},xColumn:function(qe,je,rt){Ae("xColumn",...arguments);let pt=be(qe),Ye=pt.row();switch(x.assert(Ye,"Unexpected xColumn call"),rt){case Z.rowid.colId:d.sqlite3_result_int(je,pt.rowid);break;case Z.name.colId:d.sqlite3_result_text(je,Ye.jzClass,-1,d.SQLITE_TRANSIENT);break;case Z.nRef.colId:d.sqlite3_result_int(je,Ye.refc);break;case Z.nOpen.colId:d.sqlite3_result_int(je,Ye.files.length);break;case Z.isTransient.colId:d.sqlite3_result_int(je,!!Ye.deleteAtRefc0);break;case Z.dbSize.colId:d.sqlite3_result_int(je,R(Ye));break;default:return d.sqlite3_result_error(je,"Invalid column id: "+rt),d.SQLITE_RANGE}return 0},xRowid:function(qe,je){Ae("xRowid",...arguments);let rt=be(qe);return ae.xRowid(je,rt.rowid),0},xEof:function(qe){let je=be(qe);return Ae("xEof?="+!je.row(),...arguments),!je.row()},xFilter:function(qe,je,rt,pt,Ye){return Ae("xFilter",...arguments),be(qe,!0),0},xBestIndex:function(qe,je){Ae("xBestIndex",...arguments);let rt=new d.sqlite3_index_info(je);return rt.$estimatedRows=U.storagePool.size,rt.$estimatedCost=1,rt.dispose(),0}}})};m.kvvfs.create_module=function(Me,qe="sqlite_kvvfs"){return d.sqlite3_create_module(Me,qe,Le(),q.ptr.null)}}}),globalThis.sqlite3ApiBootstrap.initializers.push(function(m){if(m.config.disable?.vfs?.opfs&&m.config.disable.vfs["opfs-vfs"])return;let d=m.util.toss;m.capi;let h=m.util;m.wasm;let y=m.opfs=Object.create(null);y.thisThreadHasOPFS=()=>globalThis.FileSystemHandle&&globalThis.FileSystemDirectoryHandle&&globalThis.FileSystemFileHandle&&globalThis.FileSystemFileHandle.prototype.createSyncAccessHandle&&navigator?.storage?.getDirectory,y.getRootDir=async function x(){return x.promise??=navigator.storage.getDirectory().then((q)=>(y.rootDirectory=q,q)).catch((q)=>{throw delete x.promise,q})},y.getResolvedPath=function(x,q){let ee=new URL(x,"file://irrelevant").pathname;return q?ee.split("/").filter((V)=>!!V):ee},y.getDirForFilename=async function(q,ee=!1){let V=y.getResolvedPath(q,!0),U=V.pop(),B=await y.getRootDir();for(let K of V)if(K)B=await B.getDirectoryHandle(K,{create:!!ee});return[B,U]},y.mkdir=async function(x){try{return await y.getDirForFilename(x+"/filepart",!0),!0}catch(q){return!1}},y.entryExists=async function(x){try{let[q,ee]=await y.getDirForFilename(x);return await q.getFileHandle(ee),!0}catch(q){return!1}},y.randomFilename=function x(q=16){if(!x._chars)x._chars="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012346789",x._n=x._chars.length;let ee=[],V=0;for(;V<q;++V){let U=Math.random()*(x._n*64)%x._n|0;ee[V]=x._chars[U]}return ee.join("")},y.treeList=async function(){let x=async function ee(V,U){U.name=V.name,U.dirs=[],U.files=[];for await(let B of V.values())if(B.kind==="directory"){let K=Object.create(null);U.dirs.push(K),await ee(B,K)}else U.files.push(B.name)},q=Object.create(null);return await x(await y.getRootDir(),q),q},y.rmfr=async function(){let x=await y.getRootDir(),q={recurse:!0};for await(let ee of x.values())x.removeEntry(ee.name,q)},y.unlink=async function(x,q=!1,ee=!1){try{let[V,U]=await y.getDirForFilename(x,!1);return await V.removeEntry(U,{recursive:q}),!0}catch(V){if(ee)throw Error("unlink(",arguments[0],") failed: "+V.message,{cause:V});return!1}},y.traverse=async function(x){let q={recursive:!0,directory:await y.getRootDir()};if(typeof x==="function")x={callback:x};x=Object.assign(q,x||{}),async function ee(V,U){for await(let B of V.values())if(x.callback(B,V,U)===!1)return!1;else if(x.recursive&&B.kind==="directory"){if(await ee(B,U+1)===!1)break}}(x.directory,0)};let D=async function(x,q){let[ee,V]=await y.getDirForFilename(x,!0),U=await(await ee.getFileHandle(V,{create:!0})).createSyncAccessHandle(),B=0,K,Y=!1;try{U.truncate(0);while((K=await q())!==void 0){if(K instanceof ArrayBuffer)K=new Uint8Array(K);if(!Y&&B===0&&K.byteLength>=15)h.affirmDbHeader(K),Y=!0;U.write(K,{at:B}),B+=K.byteLength}if(B<512||B%512!==0)d("Input size",B,"is not correct for an SQLite database.");if(!Y){let ye=new Uint8Array(20);U.read(ye,{at:0}),h.affirmDbHeader(ye)}return U.write(new Uint8Array([1,1]),{at:18}),B}catch(ye){throw await U.close(),U=void 0,await ee.removeEntry(V).catch(()=>{}),ye}finally{if(U)await U.close()}};y.importDb=async function(x,q){if(q instanceof Function)return D(x,q);if(q instanceof ArrayBuffer)q=new Uint8Array(q);h.affirmIsDb(q);let ee=q.byteLength,[V,U]=await y.getDirForFilename(x,!0),B,K=0;try{if(B=await(await V.getFileHandle(U,{create:!0})).createSyncAccessHandle(),B.truncate(0),K=B.write(q,{at:0}),K!=ee)d("Expected to write "+ee+" bytes but wrote "+K+".");return B.write(new Uint8Array([1,1]),{at:18}),K}catch(Y){if(B)await B.close(),B=void 0;throw await V.removeEntry(U).catch(()=>{}),Y}finally{if(B)await B.close()}},y.vfsInstallationFeatureCheck=function(x){if(!globalThis.SharedArrayBuffer||!globalThis.Atomics)d("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")d("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)d("Missing required OPFS APIs.");else if(x==="opfs-wl"&&!globalThis.Atomics.waitAsync)d("The",x,"VFS requires Atomics.waitAsync(), which is not available.")},y.initOptions=function(q,ee){let V=new URL(globalThis.location.href).searchParams;if(V.has(q+"-disable"))return;try{y.vfsInstallationFeatureCheck(q)}catch(U){return}if(ee=h.nu(ee),ee.vfsName=q,ee.verbose??=V.has("opfs-verbose")?+V.get("opfs-verbose"):1,ee.sanityChecks??=V.has("opfs-sanity-check"),!y.proxyUri){if(y.proxyUri="sqlite3-opfs-async-proxy.js",m.scriptInfo?.sqlite3Dir)y.proxyUri=m.scriptInfo.sqlite3Dir+y.proxyUri}if(ee.proxyUri??=y.proxyUri,typeof ee.proxyUri==="function")ee.proxyUri=ee.proxyUri();return y.options=ee},y.createVfsState=function(){let x=h.nu(),q=y.options;x.verbose=q.verbose;let ee=[m.config.error,m.config.warn,m.config.log],V=q.vfsName||d("Maintenance required: missing VFS name"),U=(J,...Ee)=>{if(x.verbose>J)ee[J](V+":",...Ee)},B=(...J)=>U(2,...J),K=(...J)=>U(1,...J),Y=(...J)=>U(0,...J),{capi:ye,wasm:P}=m,I=x.vfs=new ye.sqlite3_vfs,ne=I.ioMethods=new ye.sqlite3_io_methods;ne.$iVersion=1,I.$iVersion=2,I.$szOsFile=ye.sqlite3_file.structInfo.sizeof,I.$mxPathname=1024,I.$zName=P.allocCString(V),I.addOnDispose("$zName",I.$zName,ne),I.metrics=h.nu({counters:h.nu(),dump:function(){let J,Ee=0,xe=0,Se=0;for(J in x.opIds){let Re=ie[J];Ee+=Re.count,xe+=Re.time,Se+=Re.wait,Re.avgTime=Re.count&&Re.time?Re.time/Re.count:0,Re.avgWait=Re.count&&Re.wait?Re.wait/Re.count:0}m.config.log(globalThis.location.href,"metrics for",globalThis.location.href,":",ie,`
557
+ Total of`,Ee,"op(s) for",xe,"ms (incl. "+Se+" ms of waiting on the async side)"),m.config.log("Serialization metrics:",I.metrics.counters.s11n),I.worker?.postMessage?.({type:"opfs-async-metrics"})},reset:function(){let J,Ee=(Re)=>Re.count=Re.time=Re.wait=0,xe=I.metrics.counters;for(J in x.opIds)Ee(xe[J]=Object.create(null));let Se=xe.s11n=Object.create(null);Se=Se.serialize=Object.create(null),Se.count=Se.time=0,Se=xe.s11n.deserialize=Object.create(null),Se.count=Se.time=0}}),x.asyncIdleWaitTime=150,x.asyncS11nExceptions=1,x.fileBufferSize=65536,x.sabS11nOffset=x.fileBufferSize,x.sabS11nSize=I.$mxPathname*2,x.sabIO=new SharedArrayBuffer(x.fileBufferSize+x.sabS11nSize),x.opIds=Object.create(null);{let J=0;x.opIds.whichOp=J++,x.opIds.rc=J++,x.opIds.xAccess=J++,x.opIds.xClose=J++,x.opIds.xDelete=J++,x.opIds.xDeleteNoWait=J++,x.opIds.xFileSize=J++,x.opIds.xLock=J++,x.opIds.xOpen=J++,x.opIds.xRead=J++,x.opIds.xSleep=J++,x.opIds.xSync=J++,x.opIds.xTruncate=J++,x.opIds.xUnlock=J++,x.opIds.xWrite=J++,x.opIds.mkdir=J++,x.opIds["opfs-async-metrics"]=J++,x.opIds["opfs-async-shutdown"]=J++,x.opIds.retry=J++,x.sabOP=new SharedArrayBuffer(J*4)}x.sq3Codes=Object.create(null);for(let J 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"])x.sq3Codes[J]=ye[J]??d("Maintenance required: not found:",J);x.opfsFlags=Object.assign(Object.create(null),{OPFS_UNLOCK_ASAP:1,OPFS_UNLINK_BEFORE_OPEN:2,defaultUnlockAsap:!1}),I.metrics.reset();let ie=I.metrics.counters,G=I.opRun=(J,...Ee)=>{let xe=x.opIds[J]||d(I.vfsName+": Invalid op ID:",J);x.s11n.serialize(...Ee),Atomics.store(x.sabOPView,x.opIds.rc,-1),Atomics.store(x.sabOPView,x.opIds.whichOp,xe),Atomics.notify(x.sabOPView,x.opIds.whichOp);let Se=performance.now();while(Atomics.wait(x.sabOPView,x.opIds.rc,-1)!=="not-equal");let Re=Atomics.load(x.sabOPView,x.opIds.rc);if(ie[J].wait+=performance.now()-Se,Re&&x.asyncS11nExceptions){let H=x.s11n.deserialize();if(H)Y(J+"() async error:",...H)}return Re},re=Object.create(null);re.op=void 0,re.start=void 0;let ve=I.mTimeStart=(J)=>{re.start=performance.now(),re.op=J,++ie[J].count},O=I.mTimeEnd=()=>ie[re.op].time+=performance.now()-re.start,M=I.__openFiles=Object.create(null);I.ioSyncWrappers=h.nu({xCheckReservedLock:function(J,Ee){return P.poke(Ee,0,"i32"),0},xClose:function(J){ve("xClose");let Ee=0,xe=M[J];if(xe){if(delete M[J],Ee=G("xClose",J),xe.sq3File)xe.sq3File.dispose()}return O(),Ee},xDeviceCharacteristics:function(J){return ye.SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN},xFileControl:function(J,Ee,xe){return ye.SQLITE_NOTFOUND},xFileSize:function(J,Ee){ve("xFileSize");let xe=G("xFileSize",J);if(xe==0)try{let Se=x.s11n.deserialize()[0];P.poke(Ee,Se,"i64")}catch(Se){Y("Unexpected error reading xFileSize() result:",Se),xe=x.sq3Codes.SQLITE_IOERR}return O(),xe},xRead:function(J,Ee,xe,Se){ve("xRead");let Re=M[J],H;try{if(H=G("xRead",J,xe,Number(Se)),H===0||ye.SQLITE_IOERR_SHORT_READ===H)P.heap8u().set(Re.sabView.subarray(0,xe),Number(Ee))}catch(b){Y("xRead(",arguments,") failed:",b,Re),H=ye.SQLITE_IOERR_READ}return O(),H},xSync:function(J,Ee){ve("xSync");let xe=G("xSync",J,Ee);return O(),xe},xTruncate:function(J,Ee){ve("xTruncate");let xe=G("xTruncate",J,Number(Ee));return O(),xe},xWrite:function(J,Ee,xe,Se){ve("xWrite");let Re=M[J],H;try{Re.sabView.set(P.heap8u().subarray(Number(Ee),Number(Ee)+xe)),H=G("xWrite",J,xe,Number(Se))}catch(b){Y("xWrite(",arguments,") failed:",b,Re),H=ye.SQLITE_IOERR_WRITE}return O(),H}}),I.vfsSyncWrappers={xAccess:function(J,Ee,xe,Se){ve("xAccess");let Re=G("xAccess",P.cstrToJs(Ee));return P.poke(Se,Re?0:1,"i32"),O(),0},xCurrentTime:function(J,Ee){return P.poke(Ee,2440587.5+new Date().getTime()/86400000,"double"),0},xCurrentTimeInt64:function(J,Ee){return P.poke(Ee,210866760000000+new Date().getTime(),"i64"),0},xDelete:function(J,Ee,xe){ve("xDelete");let Se=G("xDelete",P.cstrToJs(Ee),xe,!1);return O(),Se},xFullPathname:function(J,Ee,xe,Se){return P.cstrncpy(Se,Ee,xe)<xe?0:ye.SQLITE_CANTOPEN},xGetLastError:function(J,Ee,xe){return m.config.warn("OPFS xGetLastError() has nothing sensible to return."),0},xOpen:function(Ee,xe,Se,Re,H){ve("xOpen");let b=0,R,C;if(!xe)R=y.randomFilename(),xe=C=P.allocCString(R);else if(P.isPtr(xe)){if(ye.sqlite3_uri_boolean(xe,"opfs-unlock-asap",0))b|=x.opfsFlags.OPFS_UNLOCK_ASAP;if(ye.sqlite3_uri_boolean(xe,"delete-before-open",0))b|=x.opfsFlags.OPFS_UNLINK_BEFORE_OPEN;R=P.cstrToJs(xe)}else return m.config.error("Impossible zName value in xOpen?",xe),ye.SQLITE_CANTOPEN;let z=h.nu({fid:Se,filename:R,sab:new SharedArrayBuffer(x.fileBufferSize),flags:Re,readOnly:!(ye.SQLITE_OPEN_CREATE&Re)&&!!(Re&ye.SQLITE_OPEN_READONLY)}),se=G("xOpen",Se,R,Re,b);if(se){if(C)P.dealloc(C)}else{if(z.readOnly)P.poke(H,ye.SQLITE_OPEN_READONLY,"i32");if(M[Se]=z,z.sabView=x.sabFileBufView,z.sq3File=new ye.sqlite3_file(Se),C)z.sq3File.addOnDispose(C);z.sq3File.$pMethods=ne.pointer,z.lockType=ye.SQLITE_LOCK_NONE}return O(),se}};let Q=ye.sqlite3_vfs_find(null);if(Q){let J=new ye.sqlite3_vfs(Q);I.$xRandomness=J.$xRandomness,I.$xSleep=J.$xSleep,J.dispose()}if(!I.$xRandomness)I.vfsSyncWrappers.xRandomness=function(J,Ee,xe){let Se=P.heap8u(),Re=0,H=Number(xe);for(;Re<Ee;++Re)Se[H+Re]=Math.random()*255000&255;return Re};if(!I.$xSleep)I.vfsSyncWrappers.xSleep=function(J,Ee){return ve("xSleep"),Atomics.wait(x.sabOPView,x.opIds.xSleep,0,Ee),O(),0};let ue=function(){if(x.s11n)return x.s11n;let J=new TextDecoder,Ee=new TextEncoder("utf-8"),xe=new Uint8Array(x.sabIO,x.sabS11nOffset,x.sabS11nSize),Se=new DataView(x.sabIO,x.sabS11nOffset,x.sabS11nSize);x.s11n=Object.create(null);let Re=Object.create(null);Re.number={id:1,size:8,getter:"getFloat64",setter:"setFloat64"},Re.bigint={id:2,size:8,getter:"getBigInt64",setter:"setBigInt64"},Re.boolean={id:3,size:4,getter:"getInt32",setter:"setInt32"},Re.string={id:4};let H=(R)=>Re[typeof R]||d("Maintenance required: this value type cannot be serialized.",R),b=(R)=>{switch(R){case Re.number.id:return Re.number;case Re.bigint.id:return Re.bigint;case Re.boolean.id:return Re.boolean;case Re.string.id:return Re.string;default:d("Invalid type ID:",R)}};return x.s11n.deserialize=function(R=!1){performance.now();let C=xe[0],z=C?[]:null;if(C){let se=[],fe=1,N,j,oe;for(N=0;N<C;++N,++fe)se.push(b(xe[fe]));for(N=0;N<C;++N){let le=se[N];if(le.getter)oe=Se[le.getter](fe,x.littleEndian),fe+=le.size;else j=Se.getInt32(fe,x.littleEndian),fe+=4,oe=J.decode(xe.slice(fe,fe+j)),fe+=j;z.push(oe)}}if(R)xe[0]=0;return z},x.s11n.serialize=function(...R){if(performance.now(),R.length){let C=[],z=0,se=1;xe[0]=R.length&255;for(;z<R.length;++z,++se)C.push(H(R[z])),xe[se]=C[z].id;for(z=0;z<R.length;++z){let fe=C[z];if(fe.setter)Se[fe.setter](se,R[z],x.littleEndian),se+=fe.size;else{let N=Ee.encode(R[z]);Se.setInt32(se,N.byteLength,x.littleEndian),se+=4,xe.set(N,se),se+=N.byteLength}}}else xe[0]=0},x.s11n};return I.initS11n=ue,I.bindVfs=function(J,Ee){return Object.assign(I.ioSyncWrappers,J),new Promise(function(xe,Se){let Re=void 0,H=(N)=>(Re=!0,I.dispose(),Se(N)),b=()=>{try{Ee(m,I)}catch(N){return H(N)}return Re=!1,xe(m)},R=y.options;R.proxyUri+(R.proxyUri.indexOf("?")<0?"?":"&")+V;let C=new URL("sqlite3-opfs-async-proxy.js",import.meta.url);C.searchParams.set("vfs",V);let z=I.worker=new Worker(C.toString()),se=setTimeout(()=>{if(Re===void 0)H(Error("Timeout while waiting for OPFS async proxy worker."))},4000);z._originalOnError=z.onerror,z.onerror=function(N){Y("Error initializing OPFS asyncer:",N),H(Error("Loading OPFS async Worker failed for unknown reasons."))},I.opRun;let fe=function(){let N=P.scopedAllocPush(),j=new ye.sqlite3_file;try{let oe=j.pointer,le=ye.SQLITE_OPEN_CREATE|ye.SQLITE_OPEN_READWRITE|ye.SQLITE_OPEN_MAIN_DB,ke=P.scopedAlloc(8),Ie="/sanity/check/file"+randomFilename(8),ze=P.scopedAllocCString(Ie),He;if(x.s11n.serialize("This is ä string."),He=x.s11n.deserialize(),B("deserialize() says:",He),He[0]!=="This is ä string.")d("String d13n error.");if(I.vfsSyncWrappers.xAccess(I.pointer,ze,0,ke),He=P.peek(ke,"i32"),B("xAccess(",Ie,") exists ?=",He),He=I.vfsSyncWrappers.xOpen(I.pointer,ze,oe,le,ke),B("open rc =",He,"state.sabOPView[xOpen] =",x.sabOPView[x.opIds.xOpen]),He!==0){Y("open failed with code",He);return}if(I.vfsSyncWrappers.xAccess(I.pointer,ze,0,ke),He=P.peek(ke,"i32"),!He)d("xAccess() failed to detect file.");if(He=I.ioSyncWrappers.xSync(j.pointer,0),He)d("sync failed w/ rc",He);if(He=I.ioSyncWrappers.xTruncate(j.pointer,1024),He)d("truncate failed w/ rc",He);if(P.poke(ke,0,"i64"),He=I.ioSyncWrappers.xFileSize(j.pointer,ke),He)d("xFileSize failed w/ rc",He);if(B("xFileSize says:",P.peek(ke,"i64")),He=I.ioSyncWrappers.xWrite(j.pointer,ze,10,1),He)d("xWrite() failed!");let ct=P.scopedAlloc(16);He=I.ioSyncWrappers.xRead(j.pointer,ct,6,2),P.poke(ct+6,0);let xt=P.cstrToJs(ct);if(B("xRead() got:",xt),xt!=="sanity")d("Unexpected xRead() value.");if(I.vfsSyncWrappers.xSleep)B("xSleep()ing before close()ing..."),I.vfsSyncWrappers.xSleep(I.pointer,2000),B("waking up from xSleep()");if(He=I.ioSyncWrappers.xClose(oe),B("xClose rc =",He,"sabOPView =",x.sabOPView),B("Deleting file:",Ie),I.vfsSyncWrappers.xDelete(I.pointer,ze,4660),I.vfsSyncWrappers.xAccess(I.pointer,ze,0,ke),He=P.peek(ke,"i32"),He)d("Expecting 0 from xAccess(",Ie,") after xDelete().");K("End of OPFS sanity checks.")}finally{j.dispose(),P.scopedAllocPop(N)}};z.onmessage=function({data:N}){switch(N.type){case"opfs-unavailable":H(Error(N.payload.join(" ")));break;case"opfs-async-loaded":delete x.vfs,z.postMessage({type:"opfs-async-init",args:h.nu(x)});break;case"opfs-async-inited":if(Re===!0)break;clearTimeout(se),se=null;try{if(m.vfs.installVfs({io:{struct:I.ioMethods,methods:I.ioSyncWrappers},vfs:{struct:I,methods:I.vfsSyncWrappers}}),x.sabOPView=new Int32Array(x.sabOP),x.sabFileBufView=new Uint8Array(x.sabIO,0,x.fileBufferSize),x.sabS11nView=new Uint8Array(x.sabIO,x.sabS11nOffset,x.sabS11nSize),I.initS11n(),delete I.initS11n,R.sanityChecks)K("Running sanity checks because of opfs-sanity-check URL arg..."),fe();if(y.thisThreadHasOPFS())y.getRootDir().then((j)=>{z.onerror=z._originalOnError,delete z._originalOnError,B("End of OPFS sqlite3_vfs setup.",I),b()}).catch(H);else b()}catch(j){Y(j),H(j)}break;case"debug":K("debug message from worker:",N);break;default:{let j="Unexpected message from the OPFS async worker: "+JSON.stringify(N);Y(j),H(Error(j));break}}}})},x}}),globalThis.sqlite3ApiBootstrap.initializers.push(function(m){if(!m.opfs||m.config.disable?.vfs?.opfs)return;let d=m.util,h=m.opfs||m.util.toss("Missing sqlite3.opfs"),y=async function(D){if(D=h.initOptions("opfs",D),!D)return m;let x=m.capi,q=h.createVfsState().vfs,ee=q.metrics.counters,{mTimeStart:V,mTimeEnd:U,opRun:B,__openFiles:K}=q;return q.bindVfs(d.nu({xLock:function(Y,ye){V("xLock"),++ee.xLock.count;let P=K[Y],I=0;if(P.lockType)P.lockType=ye;else if(I=B("xLock",Y,ye),I===0)P.lockType=ye;return U(),I},xUnlock:function(Y,ye){V("xUnlock"),++ee.xUnlock.count;let P=K[Y],I=0;if(x.SQLITE_LOCK_NONE===ye&&P.lockType)I=B("xUnlock",Y,ye);if(I===0)P.lockType=ye;return U(),I}}),function(Y,ye){if(Y.oo1){let P=function(...I){let ne=Y.oo1.DB.dbCtorHelper.normalizeArgs(...I);ne.vfs=ye.$zName,Y.oo1.DB.dbCtorHelper.call(this,ne)};P.prototype=Object.create(Y.oo1.DB.prototype),Y.oo1.OpfsDb=P,P.importDb=h.importDb,Y.oo1.DB.dbCtorHelper.setVfsPostOpenCallback(q.pointer,function(I,ne){ne.capi.sqlite3_busy_timeout(I,1e4)})}})};globalThis.sqlite3ApiBootstrap.initializersAsync.push(async(D)=>y().catch((x)=>{D.config.warn("Ignoring inability to install 'opfs' sqlite3_vfs:",x)}))}),globalThis.sqlite3ApiBootstrap.initializers.push(function(m){if(m.config.disable?.vfs?.["opfs-sahpool"])return;let d=m.util.toss,h=m.util.toss3,y=Object.create(null),{capi:D,util:x,wasm:q}=m,ee=4096,V=512,U=4,B=8,K=V+U,Y=V,ye=K,P=ee,I=D.SQLITE_OPEN_MAIN_DB|D.SQLITE_OPEN_MAIN_JOURNAL|D.SQLITE_OPEN_SUPER_JOURNAL|D.SQLITE_OPEN_WAL,ne=D.SQLITE_OPEN_MEMORY,ie=".opaque",G=()=>Math.random().toString(36).slice(2),re=new TextDecoder,ve=new TextEncoder,O=Object.assign(Object.create(null),{name:"opfs-sahpool",directory:void 0,initialCapacity:6,clearOnInit:!1,verbosity:2,forceReinitIfPreviouslyFailed:!1}),M=[m.config.error,m.config.warn,m.config.log];m.config.log;let Q=m.config.warn;m.config.error;let ue=new Map,J=(N)=>ue.get(N),Ee=(N,j)=>{if(j)ue.set(N,j);else ue.delete(N)},xe=new Map,Se=(N)=>xe.get(N),Re=(N,j)=>{if(j)xe.set(N,j);else xe.delete(N)},H={xCheckReservedLock:function(N,j){let oe=Se(N);return oe.log("xCheckReservedLock"),oe.storeErr(),q.poke32(j,1),0},xClose:function(N){let j=Se(N);j.storeErr();let oe=j.getOFileForS3File(N);if(oe)try{if(j.log(`xClose ${oe.path}`),j.mapS3FileToOFile(N,!1),oe.sah.flush(),oe.flags&D.SQLITE_OPEN_DELETEONCLOSE)j.deletePath(oe.path)}catch(le){return j.storeErr(le,D.SQLITE_IOERR)}return 0},xDeviceCharacteristics:function(N){return D.SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN},xFileControl:function(N,j,oe){return D.SQLITE_NOTFOUND},xFileSize:function(N,j){let oe=Se(N);oe.log("xFileSize");let le=oe.getOFileForS3File(N).sah.getSize()-P;return q.poke64(j,BigInt(le)),0},xLock:function(N,j){let oe=Se(N);oe.log(`xLock ${j}`),oe.storeErr();let le=oe.getOFileForS3File(N);return le.lockType=j,0},xRead:function(N,j,oe,le){let ke=Se(N);ke.storeErr();let Ie=ke.getOFileForS3File(N);ke.log(`xRead ${Ie.path} ${oe} @ ${le}`);try{let ze=Ie.sah.read(q.heap8u().subarray(Number(j),Number(j)+oe),{at:P+Number(le)});if(ze<oe)return q.heap8u().fill(0,Number(j)+ze,Number(j)+oe),D.SQLITE_IOERR_SHORT_READ;return 0}catch(ze){return ke.storeErr(ze,D.SQLITE_IOERR)}},xSectorSize:function(N){return ee},xSync:function(N,j){let oe=Se(N);oe.log(`xSync ${j}`),oe.storeErr();let le=oe.getOFileForS3File(N);try{return le.sah.flush(),0}catch(ke){return oe.storeErr(ke,D.SQLITE_IOERR)}},xTruncate:function(N,j){let oe=Se(N);oe.log(`xTruncate ${j}`),oe.storeErr();let le=oe.getOFileForS3File(N);try{return le.sah.truncate(P+Number(j)),0}catch(ke){return oe.storeErr(ke,D.SQLITE_IOERR)}},xUnlock:function(N,j){let oe=Se(N);oe.log("xUnlock");let le=oe.getOFileForS3File(N);return le.lockType=j,0},xWrite:function(N,j,oe,le){let ke=Se(N);ke.storeErr();let Ie=ke.getOFileForS3File(N);ke.log(`xWrite ${Ie.path} ${oe} ${le}`);try{return oe===Ie.sah.write(q.heap8u().subarray(Number(j),Number(j)+oe),{at:P+Number(le)})?0:d("Unknown write() failure.")}catch(ze){return ke.storeErr(ze,D.SQLITE_IOERR)}}},b=new D.sqlite3_io_methods;b.$iVersion=1,m.vfs.installVfs({io:{struct:b,methods:H}});let R={xAccess:function(N,j,oe,le){let ke=J(N);ke.storeErr();try{let Ie=ke.getPath(j);q.poke32(le,ke.hasFilename(Ie)?1:0)}catch(Ie){q.poke32(le,0)}return 0},xCurrentTime:function(N,j){return q.poke(j,2440587.5+new Date().getTime()/86400000,"double"),0},xCurrentTimeInt64:function(N,j){return q.poke(j,210866760000000+new Date().getTime(),"i64"),0},xDelete:function(N,j,oe){let le=J(N);le.log(`xDelete ${q.cstrToJs(j)}`),le.storeErr();try{return le.deletePath(le.getPath(j)),0}catch(ke){return le.storeErr(ke),D.SQLITE_IOERR_DELETE}},xFullPathname:function(N,j,oe,le){return q.cstrncpy(le,j,oe)<oe?0:D.SQLITE_CANTOPEN},xGetLastError:function(N,j,oe){let le=J(N),ke=le.popErr();if(le.log(`xGetLastError ${j} e =`,ke),ke){let Ie=q.scopedAllocPush();try{let[ze,He]=q.scopedAllocCString(ke.message,!0);if(q.cstrncpy(oe,ze,j),He>j)q.poke8(q.ptr.add(oe,j,-1),0)}catch(ze){return D.SQLITE_NOMEM}finally{q.scopedAllocPop(Ie)}}return ke?ke.sqlite3Rc||D.SQLITE_IOERR:0},xOpen:function(j,oe,le,ke,Ie){let ze=J(j);try{ke&=~ne,ze.log(`xOpen ${q.cstrToJs(oe)} ${ke}`);let He=oe&&q.peek8(oe)?ze.getPath(oe):G(),ct=ze.getSAHForPath(He);if(!ct&&ke&D.SQLITE_OPEN_CREATE)if(ze.getFileCount()<ze.getCapacity())ct=ze.nextAvailableSAH(),ze.setAssociatedPath(ct,He,ke);else d("SAH pool is full. Cannot create file",He);if(!ct)d("file not found:",He);let xt={path:He,flags:ke,sah:ct};ze.mapS3FileToOFile(le,xt),xt.lockType=D.SQLITE_LOCK_NONE;let br=new D.sqlite3_file(le);return br.$pMethods=b.pointer,br.dispose(),q.poke32(Ie,ke),0}catch(He){return ze.storeErr(He),D.SQLITE_CANTOPEN}}},C=function(N){if(m.capi.sqlite3_vfs_find(N))h("VFS name is already registered:",N);let j=new D.sqlite3_vfs,oe=D.sqlite3_vfs_find(null),le=oe?new D.sqlite3_vfs(oe):null;if(j.$iVersion=2,j.$szOsFile=D.sqlite3_file.structInfo.sizeof,j.$mxPathname=V,j.addOnDispose(j.$zName=q.allocCString(N),()=>Ee(j.pointer,0)),le)j.$xRandomness=le.$xRandomness,j.$xSleep=le.$xSleep,le.dispose();if(!j.$xRandomness&&!R.xRandomness)R.xRandomness=function(ke,Ie,ze){let He=q.heap8u(),ct=0,xt=Number(ze);for(;ct<Ie;++ct)He[xt+ct]=Math.random()*255000&255;return ct};if(!j.$xSleep&&!R.xSleep)R.xSleep=(ke,Ie)=>0;return m.vfs.installVfs({vfs:{struct:j,methods:R}}),j};class z{vfsDir;#e;#o;#i;#t=new Map;#r=new Map;#s=new Set;#c=new Map;#n=new Uint8Array(K);#l;#a;#d;constructor(N=Object.create(null)){this.#d=N.verbosity??O.verbosity,this.vfsName=N.name||O.name,this.#a=C(this.vfsName),Ee(this.#a.pointer,this),this.vfsDir=N.directory||"."+this.vfsName,this.#l=new DataView(this.#n.buffer,this.#n.byteOffset),this.isReady=this.reset(!!(N.clearOnInit??O.clearOnInit)).then(()=>{if(this.$error)throw this.$error;return this.getCapacity()?Promise.resolve(void 0):this.addCapacity(N.initialCapacity||O.initialCapacity)})}#u(N,...j){if(this.#d>N)M[N](this.vfsName+":",...j)}log(...N){this.#u(2,...N)}warn(...N){this.#u(1,...N)}error(...N){this.#u(0,...N)}getVfs(){return this.#a}getCapacity(){return this.#t.size}getFileCount(){return this.#r.size}getFileNames(){let N=[];for(let j of this.#r.keys())N.push(j);return N}async addCapacity(N){for(let j=0;j<N;++j){let oe=G(),le=await(await this.#o.getFileHandle(oe,{create:!0})).createSyncAccessHandle();this.#t.set(le,oe),this.setAssociatedPath(le,"",0)}return this.getCapacity()}async reduceCapacity(N){let j=0;for(let oe of Array.from(this.#s)){if(j===N||this.getFileCount()===this.getCapacity())break;let le=this.#t.get(oe);oe.close(),await this.#o.removeEntry(le),this.#t.delete(oe),this.#s.delete(oe),++j}return j}releaseAccessHandles(){for(let N of this.#t.keys())N.close();this.#t.clear(),this.#r.clear(),this.#s.clear()}async acquireAccessHandles(N=!1){let j=[];for await(let[oe,le]of this.#o)if(le.kind==="file")j.push([oe,le]);return Promise.all(j.map(async([oe,le])=>{try{let ke=await le.createSyncAccessHandle();if(this.#t.set(ke,oe),N)ke.truncate(P),this.setAssociatedPath(ke,"",0);else{let Ie=this.getAssociatedPath(ke);if(Ie)this.#r.set(Ie,ke);else this.#s.add(ke)}}catch(ke){throw this.storeErr(ke),this.releaseAccessHandles(),ke}}))}getAssociatedPath(N){N.read(this.#n,{at:0});let j=this.#l.getUint32(Y);if(this.#n[0]&&(j&D.SQLITE_OPEN_DELETEONCLOSE||(j&I)===0))return Q(`Removing file with unexpected flags ${j.toString(16)}`,this.#n),this.setAssociatedPath(N,"",0),"";let oe=new Uint32Array(B/4);N.read(oe,{at:ye});let le=this.computeDigest(this.#n,j);if(oe.every((ke,Ie)=>ke===le[Ie])){let ke=this.#n.findIndex((Ie)=>Ie===0);if(ke===0)N.truncate(P);return ke?re.decode(this.#n.subarray(0,ke)):""}else return Q("Disassociating file with bad digest."),this.setAssociatedPath(N,"",0),""}setAssociatedPath(N,j,oe){let le=ve.encodeInto(j,this.#n);if(V<=le.written+1)d("Path too long:",j);if(j&&oe)oe|=ne;this.#n.fill(0,le.written,V),this.#l.setUint32(Y,oe);let ke=this.computeDigest(this.#n,oe);if(N.write(this.#n,{at:0}),N.write(ke,{at:ye}),N.flush(),j)this.#r.set(j,N),this.#s.delete(N);else N.truncate(P),this.#s.add(N)}computeDigest(N,j){if(j&ne){let oe=3735928559,le=1103547991;for(let ke of N)oe=Math.imul(oe^ke,2654435761),le=Math.imul(le^ke,104729);return new Uint32Array([oe>>>0,le>>>0])}else return new Uint32Array([0,0])}async reset(N){await this.isReady;let j=await navigator.storage.getDirectory(),oe;for(let le of this.vfsDir.split("/"))if(le)oe=j,j=await j.getDirectoryHandle(le,{create:!0});return this.#e=j,this.#i=oe,this.#o=await this.#e.getDirectoryHandle(ie,{create:!0}),this.releaseAccessHandles(),this.acquireAccessHandles(N)}getPath(N){if(q.isPtr(N))N=q.cstrToJs(N);return(N instanceof URL?N:new URL(N,"file://localhost/")).pathname}deletePath(N){let j=this.#r.get(N);if(j)this.#r.delete(N),this.setAssociatedPath(j,"",0);return!!j}storeErr(N,j){if(N)N.sqlite3Rc=j||D.SQLITE_IOERR,this.error(N);return this.$error=N,j}popErr(){let N=this.$error;return this.$error=void 0,N}nextAvailableSAH(){let[N]=this.#s.keys();return N}getOFileForS3File(N){return this.#c.get(N)}mapS3FileToOFile(N,j){if(j)this.#c.set(N,j),Re(N,this);else this.#c.delete(N),Re(N,!1)}hasFilename(N){return this.#r.has(N)}getSAHForPath(N){return this.#r.get(N)}async removeVfs(){if(!this.#a.pointer||!this.#o)return!1;D.sqlite3_vfs_unregister(this.#a.pointer),this.#a.dispose(),delete y[this.vfsName];try{this.releaseAccessHandles(),await this.#e.removeEntry(ie,{recursive:!0}),this.#o=void 0,await this.#i.removeEntry(this.#e.name,{recursive:!0}),this.#e=this.#i=void 0}catch(N){m.config.error(this.vfsName,"removeVfs() failed with no recovery strategy:",N)}return!0}pauseVfs(){if(this.#c.size>0)m.SQLite3Error.toss(D.SQLITE_MISUSE,"Cannot pause VFS",this.vfsName,"because it has opened files.");if(this.#t.size>0)D.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(()=>D.sqlite3_vfs_register(this.#a,0),this);return this}exportFile(N){//! Documented elsewhere in this file.
558
+ let j=this.#r.get(N)||d("File not found:",N),oe=j.getSize()-P,le=new Uint8Array(oe>0?oe:0);if(oe>0){let ke=j.read(le,{at:P});if(ke!=oe)d("Expected to read "+oe+" bytes but read "+ke+".")}return le}async importDbChunked(N,j){//! Impl for importDb() when its 2nd arg is a function.
559
+ let oe=this.#r.get(N)||this.nextAvailableSAH()||d("No available handles to import to.");oe.truncate(0);let le=0,ke,Ie=!1;try{while((ke=await j())!==void 0){if(ke instanceof ArrayBuffer)ke=new Uint8Array(ke);if(!Ie&&le===0&&ke.byteLength>=15)x.affirmDbHeader(ke),Ie=!0;oe.write(ke,{at:P+le}),le+=ke.byteLength}if(le<512||le%512!==0)d("Input size",le,"is not correct for an SQLite database.");if(!Ie){let ze=new Uint8Array(20);oe.read(ze,{at:0}),x.affirmDbHeader(ze)}oe.write(new Uint8Array([1,1]),{at:P+18})}catch(ze){throw this.setAssociatedPath(oe,"",0),ze}return this.setAssociatedPath(oe,N,D.SQLITE_OPEN_MAIN_DB),le}importDb(N,j){//! Documented elsewhere in this file.
560
+ if(j instanceof ArrayBuffer)j=new Uint8Array(j);else if(j instanceof Function)return this.importDbChunked(N,j);let oe=this.#r.get(N)||this.nextAvailableSAH()||d("No available handles to import to."),le=j.byteLength;if(le<512||le%512!=0)d("Byte array size is invalid for an SQLite db.");let ke="SQLite format 3";for(let ze=0;ze<15;++ze)if(ke.charCodeAt(ze)!==j[ze])d("Input does not contain an SQLite database header.");let Ie=oe.write(j,{at:P});if(Ie!=le)this.setAssociatedPath(oe,"",0),d("Expected to write "+le+" bytes but wrote "+Ie+".");else oe.write(new Uint8Array([1,1]),{at:P+18}),this.setAssociatedPath(oe,N,D.SQLITE_OPEN_MAIN_DB);return Ie}}class se{#e;constructor(N){this.#e=N,this.vfsName=N.vfsName}async addCapacity(N){return this.#e.addCapacity(N)}async reduceCapacity(N){return this.#e.reduceCapacity(N)}getCapacity(){return this.#e.getCapacity(this.#e)}getFileCount(){return this.#e.getFileCount()}getFileNames(){return this.#e.getFileNames()}async reserveMinimumCapacity(N){let j=this.#e.getCapacity();return j<N?this.#e.addCapacity(N-j):j}exportFile(N){return this.#e.exportFile(N)}importDb(N,j){return this.#e.importDb(N,j)}async wipeFiles(){return this.#e.reset(!0)}unlink(N){return this.#e.deletePath(N)}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 fe=async()=>{let N=await navigator.storage.getDirectory(),j=".opfs-sahpool-sync-check-"+G(),oe=(await(await N.getFileHandle(j,{create:!0})).createSyncAccessHandle()).close();if(await oe,await N.removeEntry(j),oe?.then)d("The local OPFS API is too old for opfs-sahpool:","it has an async FileSystemSyncAccessHandle.close() method.");return!0};m.installOpfsSAHPoolVfs=async function(N=Object.create(null)){N=Object.assign(Object.create(null),O,N||{});let j=N.name;if(N.$testThrowPhase1)throw N.$testThrowPhase1;if(y[j])try{return await y[j]}catch(oe){if(N.forceReinitIfPreviouslyFailed)delete y[j];else throw oe}if(!globalThis.FileSystemHandle||!globalThis.FileSystemDirectoryHandle||!globalThis.FileSystemFileHandle||!globalThis.FileSystemFileHandle.prototype.createSyncAccessHandle||!navigator?.storage?.getDirectory)return y[j]=Promise.reject(Error("Missing required OPFS APIs."));return y[j]=fe().then(async function(){if(N.$testThrowPhase2)throw N.$testThrowPhase2;let oe=new z(N);return oe.isReady.then(async()=>{let le=new se(oe);if(m.oo1){let ke=m.oo1,Ie=oe.getVfs(),ze=function(...He){let ct=ke.DB.dbCtorHelper.normalizeArgs(...He);ct.vfs=Ie.$zName,ke.DB.dbCtorHelper.call(this,ct)};ze.prototype=Object.create(ke.DB.prototype),le.OpfsSAHPoolDb=ze}return oe.log("VFS initialized."),le}).catch(async(le)=>{throw await oe.removeVfs().catch(()=>{}),le})}).catch((oe)=>y[j]=Promise.reject(oe))}}),globalThis.sqlite3ApiBootstrap.initializers.push(function(m){if(!m.opfs||m.config.disable?.vfs?.["opfs-wl"])return;let d=m.util;m.util.toss;let h=m.opfs,y="opfs-wl",D=async function(x){if(x=h.initOptions(y,x),!x)return m;m.capi;let q=h.createVfsState().vfs;q.metrics.counters;let{mTimeStart:ee,mTimeEnd:V,opRun:U,__openFiles:B}=q;return q.bindVfs(d.nu({xLock:function(K,Y){ee("xLock");let ye=B[K],P=U("xLock",K,Y);if(!P)ye.lockType=Y;return V(),P},xUnlock:function(K,Y){ee("xUnlock");let ye=B[K],P=U("xUnlock",K,Y);if(!P)ye.lockType=Y;return V(),P}}),function(K,Y){if(K.oo1){let ye=function(...P){let I=K.oo1.DB.dbCtorHelper.normalizeArgs(...P);I.vfs=Y.$zName,K.oo1.DB.dbCtorHelper.call(this,I)};ye.prototype=Object.create(K.oo1.DB.prototype),K.oo1.OpfsWlDb=ye,ye.importDb=h.importDb}})};globalThis.sqlite3ApiBootstrap.initializersAsync.push(async(x)=>D().catch((q)=>{x.config.warn("Ignoring inability to install the",y,"sqlite3_vfs:",q)}))});try{let m=Object.assign(Object.create(null),{memory:typeof Jr<"u"?Jr:p.wasmMemory,exports:typeof uo<"u"?uo:Object.prototype.hasOwnProperty.call(p,"wasmExports")?p.wasmExports:p.asm},globalThis.sqlite3ApiBootstrap.defaultConfig,globalThis.sqlite3ApiConfig||{});a.debugModule("Bootstrapping lib config",m);let d=globalThis.sqlite3ApiBootstrap(m);return delete globalThis.sqlite3ApiBootstrap,d}catch(m){throw console.error("sqlite3ApiBootstrap() error:",m),m}},X)t=r;else t=new Promise((a,p)=>{L=a,F=p});return t}su=function(){let e=su;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((i)=>{t.debugModule("sqlite3InitModule() sIMS =",t),t.debugModule("sqlite3InitModule() EmscriptenModule =",i);let s=i.runSQLite3PostLoadInit(t,i,!!n.__isUnderTest);return t.debugModule("sqlite3InitModule() sqlite3 =",s),s}).catch((i)=>{throw console.error("Exception loading sqlite3 module:",i),i})};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 Zy=su;class cu{db;txDepth=0;constructor(e){this.db=e}query(e){let t=this.db;return{get(...r){return t.selectObject(e,au(r))??null},all(...r){return t.selectObjects(e,au(r))},run(...r){return t.exec({sql:e,bind:au(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 au(e){if(e.length===0)return;return e.map((t)=>t===void 0?null:t)}Kt();sn();function lu(e){if(e==null)return null;let t=String(e).trim();if(!t)return null;let r=/^(\d{4})-(\d{2})-(\d{2})/.exec(t);if(r)return new Date(Number(r[1]),Number(r[2])-1,Number(r[3]));let n=new Date(t);return Number.isNaN(n.getTime())?null:new Date(n.getFullYear(),n.getMonth(),n.getDate())}function no(e,t){return new Date(e.getFullYear(),e.getMonth(),e.getDate()+t)}function Gy(e,t){return new Date(e,t,1)}function Ky(e,t){return new Date(e,t+1,0)}function ya(){let e=new Date;return new Date(e.getFullYear(),e.getMonth(),e.getDate())}function Jy(e){let t=(e.getDay()+6)%7;return no(e,-t)}var oR=(e,t)=>t==null?"":Array.isArray(t)?t.join(", "):String(t),ln=(e)=>e;var Oq=[{id:"empty",label:ln("为空"),value:"none"},{id:"not_empty",label:ln("不为空"),value:"none"}];var Cq=[{id:"today",label:ln("今天")},{id:"this_week",label:ln("本周")},{id:"this_month",label:ln("本月")},{id:"past7",label:ln("过去 7 天")},{id:"next7",label:ln("未来 7 天")},{id:"past30",label:ln("过去 30 天")},{id:"next30",label:ln("未来 30 天")}];function iR(e,t=ya()){switch(e){case"this_week":{let r=Jy(t);return[r,no(r,6)]}case"this_month":return[Gy(t.getFullYear(),t.getMonth()),Ky(t.getFullYear(),t.getMonth())];case"past7":return[no(t,-6),t];case"next7":return[t,no(t,6)];case"past30":return[no(t,-29),t];case"next30":return[t,no(t,29)];default:return[t,t]}}var Xy=(e)=>e==null||e===""||Array.isArray(e)&&e.length===0,wa=(e)=>Array.isArray(e)?e.map(String):[],Zr=(e)=>e==null?"":String(e);function sR(e,t,r,n=ya()){let o=e.cond;if(o==="empty")return Xy(r);if(o==="not_empty")return!Xy(r);let i=e.value;switch(t.type){case"text":case"url":{let s=Zr(i).toLowerCase();if(!s)return!0;let c=Zr(r).toLowerCase();if(o==="contains")return c.includes(s);if(o==="not_contains")return!c.includes(s);if(o==="is")return c===s;if(o==="is_not")return c!==s;return!0}case"number":{if(i==null||i==="")return!0;let s=Number(i);if(!Number.isFinite(s))return!0;let c=r==null||r===""?NaN:Number(r);if(!Number.isFinite(c))return o==="ne";if(o==="eq")return c===s;if(o==="ne")return c!==s;if(o==="gt")return c>s;if(o==="lt")return c<s;if(o==="ge")return c>=s;if(o==="le")return c<=s;return!0}case"select":{let s=Zr(i);if(!s)return!0;if(o==="is")return Zr(r)===s;if(o==="is_not")return Zr(r)!==s;return!0}case"multi_select":case"relation":case"doc":{let s=wa(i);if(!s.length)return!0;let c=wa(r);if(o==="has_any")return s.some((l)=>c.includes(l));if(o==="has_all")return s.every((l)=>c.includes(l));if(o==="has_none")return!s.some((l)=>c.includes(l));return!0}case"checkbox":return o==="is"?!!r===(i===!0||i==="true"):!0;case"date":{let s=lu(r);if(o==="within"){let f=Zr(i);if(!f)return!0;if(!s)return!1;let[_,E]=iR(f,n);return s>=_&&s<=E}let c=lu(i);if(!c)return!0;if(!s)return!1;let l=s.getTime(),u=c.getTime();if(o==="is")return l===u;if(o==="before")return l<u;if(o==="after")return l>u;if(o==="on_or_before")return l<=u;if(o==="on_or_after")return l>=u;return!0}}}function Yy(e,t,r,n=ya()){let o=r.rules.map((i)=>({rule:i,prop:t.find((s)=>s.id===i.prop)})).filter((i)=>!!i.prop);if(!o.length)return e;return e.filter((i)=>{let s=o.map(({rule:c,prop:l})=>sR(c,l,i.cells[l.id],n));return r.op==="or"?s.some(Boolean):s.every(Boolean)})}var ba=(e)=>{let t=e==null||e===""?NaN:Number(e);return Number.isFinite(t)?t:Number.NEGATIVE_INFINITY};function Qy(e,t,r){switch(e.type){case"number":return ba(t)===ba(r)?0:ba(t)-ba(r);case"checkbox":return Number(!!t)-Number(!!r);case"date":return Zr(t).localeCompare(Zr(r));case"multi_select":case"relation":case"doc":return wa(t).join(",").localeCompare(wa(r).join(","),"zh");default:return Zr(t).localeCompare(Zr(r),"zh")}}function eb(e,t,r){let n=r.trim().toLowerCase();if(!n)return e;return e.filter((o)=>t.some((i)=>oR(i,o.cells[i.id]).toLowerCase().includes(n)))}function*tb(e,t,r={}){yield;let n=Mt(e,t),o=Number.isFinite(r.limit)?Math.max(1,Math.min(200,Math.floor(r.limit))):60,i=Number.isFinite(r.offset)?Math.max(0,Math.floor(r.offset)):0,s=i+o,c=(r.sort??[]).flatMap((_)=>{let E=n.find((g)=>g.id===_.prop);return E?[{rule:_,prop:E}]:[]}),l=(_,E)=>{for(let{rule:g,prop:A}of c){let L=Qy(A,_.cells[A.id],E.cells[A.id]);if(L&&Number.isFinite(L))return g.desc?-L:L;if(L===1/0||L===-1/0)return g.desc?-L:L}return 0};if(!c.length&&!r.search?.trim()&&!r.filter?.rules.length){let _=e.query("SELECT count(*) AS n FROM records WHERE database_id = ? AND __deleted = 0").get(t).n;return{records:e.query("SELECT id, database_id, data FROM records WHERE database_id = ? AND __deleted = 0 ORDER BY order_key IS NULL, order_key, id LIMIT ? OFFSET ?").all(t,o,i).map((A)=>{let L=JSON.parse(A.data||"{}"),F={},X={};for(let te of n)if(Object.hasOwn(L,te.id))F[te.id]=L[te.id],X[te.name]=L[te.id];return{id:A.id,database_id:A.database_id,cells:F,values:X}}),total:_,hasMore:_>i+o,offset:i,limit:o}}let u=[],f=0;for(let _=0;;_+=200){let E=e.query("SELECT id, database_id, data FROM records WHERE database_id = ? AND __deleted = 0 ORDER BY order_key IS NULL, order_key, id LIMIT 200 OFFSET ?").all(t,_);for(let g of E){let A=JSON.parse(g.data||"{}"),L={},F={};for(let de of n)if(Object.hasOwn(A,de.id))L[de.id]=A[de.id],F[de.name]=A[de.id];let X={id:g.id,database_id:g.database_id,cells:L,values:F};if(r.filter&&!Yy([X],n,r.filter).length)continue;if(!eb([X],n,r.search??"").length)continue;if(f++,!c.length){if(u.length<s)u.push(X);continue}let te=0,ce=u.length;while(te<ce){let de=te+ce>>>1;if(l(X,u[de])<0)ce=de;else te=de+1}if(te<s){if(u.splice(te,0,X),u.length>s)u.pop()}}if(E.length<200)break;yield}return{records:u.slice(i),total:f,hasMore:f>i+o,offset:i,limit:o}}function rb(e,t,r={}){let n=tb(e,t,r),o=n.next();while(!o.done)o=n.next();return o.value}async function nb(e,t,r={},n=()=>!0){let o=tb(e,t,r);for(;;){if(!n())throw Error("Replica query cancelled");let i=o.next();if(i.done)return i.value;await new Promise((s)=>setTimeout(s,0))}}function ob(e,t={}){let r=Number.isFinite(t.limit)?Math.max(1,Math.min(200,Math.floor(t.limit))):60,n=Number.isFinite(t.offset)?Math.max(0,Math.floor(t.offset)):0,o=`%${(t.search??"").trim().replace(/[\\%_]/g,"\\$&")}%`,i="__deleted = 0 AND (title LIKE ? ESCAPE '\\' OR id LIKE ? ESCAPE '\\')",s=e.query("SELECT count(*) AS n FROM documents WHERE __deleted = 0 AND (title LIKE ? ESCAPE '\\' OR id LIKE ? ESCAPE '\\')").get(o,o).n;return{documents:e.query("SELECT id, title, database_id, parent_id, created_hlc, order_key FROM documents WHERE __deleted = 0 AND (title LIKE ? ESCAPE '\\' OR id LIKE ? ESCAPE '\\') ORDER BY order_key IS NULL, order_key, id LIMIT ? OFFSET ?").all(o,o,r,n),total:s,hasMore:s>n+r,offset:n,limit:r}}Jn();sn();Xn();on();js();it();on();sn();Ke();Ln();var aR=1500;function uu(e){return Number(e.slice(0,15))}function $o(e){return new Date(uu(e)).toISOString()}function oo(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 du(e){return oo(e).kind}function Mo(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||uu(n.hlc)-uu(o.hlc)>aR))t.push(r),r=[];r.push(n)}if(r.length)t.push(r);return t}function Tr(e){return e!==null&&e!=="0"&&e!=="false"&&e!=="null"}function va(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 Sa(e,t,r){return e.query(`SELECT ${vt} FROM crdt_changes WHERE dataset = ? AND row_id = ? ORDER BY hlc`).all(t,r)}function cR(e,t){return e.query(`SELECT DISTINCT row_id FROM ${wi(e)} WHERE dataset = 'doc_blocks' AND col = 'doc_id' AND value = ?`).all(JSON.stringify(t)).map((r)=>r.row_id)}function ib(e,t){let r=Id(e,t);if(r)return r;let n=cR(e,t),o=n.map(()=>"?").join(","),i=n.length?` OR (dataset = 'doc_blocks' AND row_id IN (${o}))`:"",s=e.query(`SELECT ${vt} FROM ${wi(e)}
561
+ WHERE (dataset = 'documents' AND row_id = ?)${i}
562
+ ORDER BY hlc`).all(t,...n);return Nd(e,t,s,n)}function sb(e,t){let r=ib(e,t);if(r.revisions)return r.revisions.slice();let n=r.changes;if(!n.length)throw new T("not_found",`no such document: ${t}`);let o=new Map,i=[];for(let s of Mo(n)){let c=new Set,l=new Set,u=new Map,f=!1,_=!1,E=0;for(let F of s)if(F.dataset==="documents"){if(u.set(F.col,F.value),F.col==="created_hlc")f=!0;else if(F.col==="__deleted")_=Tr(F.value)}else if(E++,F.col==="__deleted"&&Tr(F.value))l.add(F.row_id);else if(F.col==="text")c.add(F.row_id);let g=!1,A=0;for(let[F,X]of u){let te=!o.has(F)||o.get(F)!==X;if(o.set(F,X),!te)continue;if(A++,F==="title")g=!0}if(A===0&&E===0)continue;let L=s[s.length-1];i.push({version:L.hlc,at:$o(L.hlc),node_id:L.node_id,kind:du(L.txn),actor:oo(L.txn).actor,changes:s.length,created:f,deleted:_,title_changed:g,blocks_changed:c.size,blocks_deleted:l.size})}return r.revisions=i.reverse(),r.revisions.slice()}function pu(e,t,r){if(!r)throw new T("invalid_input","missing version cutoff");let n=ib(e,t),o=n.states.get(r);if(o)return{...o};let i=n.changes.filter((E)=>E.hlc<=r);if(!i.length)throw new T("not_found",`no version of document ${t} at or before ${r}`);let s=va(i.filter((E)=>E.dataset==="documents"),r),c=(E)=>{let g=s.get(E);return g?.value==null?void 0:JSON.parse(g.value)},l=new Map;for(let E of i){if(E.dataset!=="doc_blocks")continue;(l.get(E.row_id)??l.set(E.row_id,[]).get(E.row_id)).push(E)}let u=[];for(let[E,g]of l){let A=va(g,r),L=(X)=>{let te=A.get(X);return te?.value==null?void 0:JSON.parse(te.value)};if(L("doc_id")!==t)continue;if(A.get("__deleted")&&Tr(A.get("__deleted").value))continue;let F=L("text");if(typeof F!=="string"||!F)continue;u.push({id:E,text:F,order_key:L("order_key")??null,blankAfter:L("blank_after")??0})}u.sort((E,g)=>{if(E.order_key!==g.order_key){if(E.order_key===null)return-1;if(g.order_key===null)return 1;return E.order_key<g.order_key?-1:1}return E.id<g.id?-1:1});let f=l.size?qn(u):c("body")??"",_={id:t,title:c("title")??"",body:f,deleted:s.get("__deleted")?Tr(s.get("__deleted").value):!1,version:i[i.length-1].hlc};return Pd(n,r,_),{..._}}var ab=We(function(t,r,n,o={}){let i=nt(t,r);if(!i&&!t.query("SELECT 1 AS x FROM documents WHERE id = ?").get(r))throw new T("not_found",`no such document: ${r}`);if(o.ifMatch!==void 0&&At(t,r)!==o.ifMatch)throw new T("stale",`stale: document changed since ${o.ifMatch}; re-read first`);let s=pu(t,r,n);if(s.deleted)throw new T("invalid_input","target version is a deleted state; use doc delete instead");let c=!i;if(!i)_e(t,"documents",r,"__deleted",0),i=nt(t,r);let l={};if(s.title!==i.title)l.title=s.title;if(s.body!==(i.body??""))l.body=s.body;if(Object.keys(l).length)Ps(t,r,l);return{id:r,changed:Object.keys(l).length>0||c,restored:s.version,version:At(t,r),undeleted:c}},"revert"),Ea=new Set(["database_id","created_hlc","order_key","__deleted"]);function cb(e){let t=new Set,r=!1,n=!1,o=!1;for(let s of e)if(s.col==="created_hlc")r=!0;else if(s.col==="__deleted")n=Tr(s.value);else if(s.col==="order_key")o=!0;else if(!Ea.has(s.col))t.add(s.col);let i=e[e.length-1];return{version:i.hlc,at:$o(i.hlc),node_id:i.node_id,kind:du(i.txn),actor:oo(i.txn).actor,changes:e.length,created:r,deleted:n,fields:[...t],moved:o}}function lb(e,t){let r=Sa(e,"records",t);if(!r.length)throw new T("not_found",`no such record: ${t}`);return Mo(r).map(cb).reverse()}function ub(e,t,r={}){if(!e.query("SELECT 1 AS x FROM databases WHERE id = ?").get(t))throw new T("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 ${vt} FROM crdt_changes
563
+ WHERE dataset = 'records' AND row_id IN (SELECT id FROM records WHERE database_id = ?)
564
+ ORDER BY row_id, hlc`).all(t),i=[],s=0;for(let c=1;c<=o.length;c++){if(c!==o.length&&o[c].row_id===o[s].row_id)continue;let l=o[s].row_id,u=new Map;for(let f of Mo(o.slice(s,c))){let _=new Set;for(let A of f)if(!Ea.has(A.col))_.add(A.col);let E=new Map;for(let A of _)if(u.has(A))E.set(A,u.get(A));for(let A of f){if(Ea.has(A.col))continue;if(A.value===null)u.delete(A.col);else u.set(A.col,JSON.parse(A.value))}let g=[];for(let A of _){let L={prop:A};if(E.has(A))L.before=E.get(A);if(u.has(A))L.after=u.get(A);g.push(L)}i.push({...cb(f),record_id:l,record_title:n&&u.has(n)?String(u.get(n)??""):null,diffs:g})}s=c}return i.sort((c,l)=>c.version<l.version?1:-1),i.slice(0,r.limit??100)}function fu(e,t,r){if(!r)throw new T("invalid_input","missing version cutoff");let n=Sa(e,"records",t).filter((c)=>c.hlc<=r);if(!n.length)throw new T("not_found",`no version of record ${t} at or before ${r}`);let o=va(n,r),i={};for(let[c,l]of o){if(Ea.has(c))continue;if(l.value===null)continue;i[c]=JSON.parse(l.value)}let s=o.get("database_id");return{id:t,database_id:s?.value==null?null:JSON.parse(s.value),deleted:o.get("__deleted")?Tr(o.get("__deleted").value):!1,data:i,version:n[n.length-1].hlc}}var db=We(function(t,r,n){let o=t.query("SELECT database_id, data, __deleted FROM records WHERE id = ?").get(r);if(!o)throw new T("not_found",`no such record: ${r}`);let i=fu(t,r,n);if(i.deleted)throw new T("invalid_input","target version is a deleted state; use record delete instead");let s=new Set(o.database_id?Mt(t,o.database_id).map((f)=>f.id):[]),c=JSON.parse(o.data||"{}"),l=[];for(let f of s){let _=Object.hasOwn(i.data,f),E=Object.hasOwn(c,f);if(_&&(!E||JSON.stringify(i.data[f])!==JSON.stringify(c[f])))_e(t,"records",r,f,i.data[f]),l.push(f);else if(!_&&E)_e(t,"records",r,f,void 0),l.push(f)}let u=o.__deleted!==0;if(u)_e(t,"records",r,"__deleted",0);return{id:r,changed:l.length>0||u,fields:l,undeleted:u,restored:i.version}},"revert"),pb=["name","type","config","position"];function fb(e,t){let r=Sa(e,"properties",t);if(!r.length)throw new T("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 Mo(r).map((o)=>{let i=new Set,s=!1,c=!1;for(let u of o)if(u.col==="database_id")s=!0;else if(u.col==="__deleted")c=Tr(u.value);else if(pb.includes(u.col))i.add(u.col);let l=o[o.length-1];return{version:l.hlc,at:$o(l.hlc),node_id:l.node_id,kind:du(l.txn),actor:oo(l.txn).actor,changes:o.length,created:s,deleted:c,fields:[...i],cells_cleared:l.txn?n.get(l.txn)??0:0}}).reverse()}function hu(e,t,r){if(!r)throw new T("invalid_input","missing version cutoff");let n=Sa(e,"properties",t).filter((s)=>s.hlc<=r);if(!n.length)throw new T("not_found",`no version of property ${t} at or before ${r}`);let o=va(n,r),i=(s)=>{let c=o.get(s);return c?.value==null?void 0:JSON.parse(c.value)};return{id:t,database_id:i("database_id")??null,name:i("name")??"",type:i("type")??"text",config:i("config")??null,position:i("position")??null,deleted:o.get("__deleted")?Tr(o.get("__deleted").value):!1,version:n[n.length-1].hlc}}var hb=We(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 T("not_found",`no such property: ${r}`);let i=hu(t,r,n);if(i.deleted)throw new T("invalid_input","target version is a deleted state; use prop remove instead");let s={name:o.name,type:o.type,config:o.config?JSON.parse(o.config):null,position:o.position},c={name:i.name,type:i.type,config:i.config,position:i.position},l=[];for(let F of pb)if(JSON.stringify(c[F]??null)!==JSON.stringify(s[F]??null))_e(t,"properties",r,F,c[F]),l.push(F);let u=o.__deleted!==0;if(u)_e(t,"properties",r,"__deleted",0);let f=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((F)=>F.txn)),_=t.query("SELECT row_id, hlc, value, txn FROM crdt_changes WHERE dataset = 'records' AND col = ? ORDER BY row_id, hlc").all(r),E=(F)=>F!==null&&(f.has(F)||oo(F).kind==="repair"),g=0,A=0,L=0;while(L<_.length){let F=_[L].row_id,X=_[L],te=null;for(;L<_.length&&_[L].row_id===F;L++)if(X=_[L],!E(X.txn))te=X;if(X.hlc<=n)continue;if(!E(X.txn)){A++;continue}let ce=te?te.value:null;if(ce===X.value)continue;_e(t,"records",F,r,ce===null?void 0:JSON.parse(ce)),g++}return{id:r,changed:l.length>0||u||g>0,fields:l,restored_cells:g,skipped_cells:A,undeleted:u,restored:i.version}},"revert");function gb(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:$o(o.hlc),node_id:o.node_id,value:o.value===null?void 0:JSON.parse(o.value),cleared:o.value===null}))}Oi();it();var xa="('text','url','select','multi_select','date')",ka="1";function Fo(e,t){return e.query("SELECT value FROM meta WHERE key = ?").get(t)?.value??null}function zo(e,t,r){e.query("INSERT INTO meta (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(t,r)}function mb(e,t,...r){return e.query(`SELECT r.id AS id, r.database_id AS database_id, group_concat(je.value, ' ') AS body
565
+ FROM records r, json_each(r.data) je
566
+ JOIN properties p ON p.id = je.key AND p.__deleted = 0
567
+ WHERE ${t} AND r.__deleted = 0 AND p.type IN ${xa}
568
+ GROUP BY r.id`).all(...r)}function _b(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 gu(e,t,r){for(let n=0;n<r.length;n+=200){let o=r.slice(n,n+200),i=o.map(()=>"?").join(",");if(e.query(`DELETE FROM search_fts WHERE kind = ? AND id IN (${i})`).run(t,...o),t==="document")e.query(`INSERT INTO search_fts (kind, id, database_id, title, body)
569
+ SELECT 'document', id, database_id, coalesce(title, ''), coalesce(body, '')
570
+ FROM documents WHERE __deleted = 0 AND id IN (${i})`).run(...o);else e.query(`INSERT INTO search_fts (kind, id, database_id, title, body)
571
+ SELECT 'record', r.id, r.database_id, r.id, coalesce(group_concat(je.value, ' '), '')
572
+ FROM records r, json_each(r.data) je JOIN properties p ON p.id = je.key AND p.__deleted = 0
573
+ WHERE r.id IN (${i}) AND r.__deleted = 0 AND p.type IN ${xa}
574
+ GROUP BY r.id`).run(...o)}}function uR(e,t){e.query("DELETE FROM search_fts WHERE kind = 'record' AND database_id = ?").run(t);for(let r of mb(e,"r.database_id = ?",t))_b(e,r)}function dR(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 mb(e,"1 = 1"))_b(e,r);let t=e.query("SELECT MAX(rowid) AS m FROM crdt_changes").get().m??0;zo(e,"search_seq",String(t)),zo(e,"search_index_version",ka),e.query("DELETE FROM meta WHERE key = 'search_rebuild'").run()}function yb(e,t,r){let n=Number(Fo(e,"search_seq")??"0"),{changes:o,cursor:i}=r??Lt(e,n,{limit:t});if(o.length===0)return;let s=new Set,c=new Set,l=new Set;for(let f of o)switch(f.dataset){case"documents":s.add(f.row_id);break;case"doc_blocks":{let _=e.query("SELECT doc_id FROM doc_blocks WHERE id = ?").get(f.row_id);if(_?.doc_id)s.add(_.doc_id);break}case"records":c.add(f.row_id);break;case"properties":if(f.col==="type"||f.col==="__deleted"||f.col==="database_id"){let _=e.query("SELECT database_id FROM properties WHERE id = ?").get(f.row_id);if(_?.database_id)l.add(_.database_id)}break}gu(e,"document",[...s]);for(let f of l)uR(e,f);let u=l.size?[...c].filter((f)=>{let _=e.query("SELECT database_id FROM records WHERE id = ?").get(f);return!_?.database_id||!l.has(_.database_id)}):[...c];gu(e,"record",u),zo(e,"search_seq",String(i))}function bb(e){if(!Di(e))return!1;let t=Fo(e,"search_index_version"),r=Fo(e,"search_seq");return Ve(e,()=>{if(t!==ka||r===null)dR(e);else yb(e)}),!0}function wb(e,t=200){if(!Number.isSafeInteger(t)||t<=0)throw RangeError("search batch size must be a positive integer");if(!Di(e))return{ready:!0,available:!1};return Ve(e,()=>{let r=Fo(e,"search_rebuild"),n;if(!r){let o=Fo(e,"search_seq"),i=o===null||Fo(e,"search_index_version")!==ka;if(!i)n=Lt(e,Number(o),{limit:t});let s=n?.changes.some((c)=>c.dataset==="properties"&&["type","__deleted","database_id"].includes(c.col));if(i||s){e.query("DELETE FROM search_fts").run();let c=e.query("SELECT coalesce(max(seq),0) AS n FROM crdt_changes").get().n;r=JSON.stringify({stage:"documents",after:"",head:c})}}if(r){let o=JSON.parse(r),i=o.stage,s=e.query(`SELECT id FROM ${i} WHERE __deleted = 0 AND id > ? ORDER BY id LIMIT ?`).all(o.after,t);if(gu(e,o.stage==="documents"?"document":"record",s.map((c)=>c.id)),s.length===t)o.after=s[s.length-1].id;else if(o.stage==="documents")o.stage="records",o.after="";else return zo(e,"search_seq",String(o.head)),zo(e,"search_index_version",ka),e.query("DELETE FROM meta WHERE key = 'search_rebuild'").run(),{ready:!1,available:!0};return zo(e,"search_rebuild",JSON.stringify(o)),{ready:!1,available:!0}}return yb(e,t,n),{ready:n.changes.length<t,available:!0}})}async function vb(e,t,r={}){while(!0){if(r.signal?.aborted)throw r.signal.reason??Error("search cancelled");if(wb(e,r.batchSize).ready)break;await new Promise((o)=>setTimeout(o,0))}return Li(e,t,{limit:r.limit,maintainIndex:!1})}function mu(e,t,r,n=0){let o=t.split(/\s+/).filter(Boolean).map((s)=>`"${s.replace(/"/g,'""')}"`).join(" ");if(!o)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, kind, id LIMIT ? OFFSET ?").all(o,r,n).map((s)=>({type:s.kind,id:s.id,database_id:s.database_id,title:s.title||void 0,snippet:s.snippet}))}function _u(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 pR(e,t,r){let n=`%${t.replace(/[%_\\]/g,"\\$&")}%`,o=[],i=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 s of i)o.push({type:"document",id:s.id,database_id:s.database_id,title:s.title??void 0,snippet:_u(s.body||s.title||"",t)});if(o.length<r){let s=e.query(`SELECT r.id AS id, r.database_id AS database_id, group_concat(je.value, ' ') AS body
575
+ FROM records r, json_each(r.data) je
576
+ JOIN properties p ON p.id = je.key AND p.__deleted = 0
577
+ WHERE r.__deleted = 0 AND p.type IN ${xa}
578
+ GROUP BY r.id HAVING body LIKE ? ESCAPE '\\' LIMIT ?`).all(n,r-o.length);for(let c of s)o.push({type:"record",id:c.id,database_id:c.database_id,snippet:_u(c.body||"",t)})}return o}function Li(e,t,r={}){let n=r.limit??20;if(r.maintainIndex===!1?Di(e):bb(e))try{let o=mu(e,t,n);if(o.length)return o}catch{}return pR(e,t,n)}function fR(e,t,r,n){let o=`%${t.replace(/[%_\\]/g,"\\$&")}%`;return e.query(`
579
+ SELECT 'document' AS kind, id, database_id, title, coalesce(body, title, '') AS body
580
+ FROM documents WHERE __deleted = 0 AND (title LIKE ? ESCAPE '\\' OR body LIKE ? ESCAPE '\\')
581
+ UNION ALL
582
+ SELECT 'record' AS kind, r.id, r.database_id, NULL AS title, group_concat(je.value, ' ') AS body
583
+ FROM records r, json_each(r.data) je JOIN properties p ON p.id = je.key AND p.__deleted = 0
584
+ WHERE r.__deleted = 0 AND p.type IN ${xa}
585
+ GROUP BY r.id HAVING body LIKE ? ESCAPE '\\'
586
+ ORDER BY kind, id LIMIT ? OFFSET ?
587
+ `).all(o,o,o,n,r).map((s)=>({type:s.kind,id:s.id,database_id:s.database_id,title:s.title??void 0,snippet:_u(s.body,t)}))}function yu(e,t,r={}){let n=Number.isFinite(r.offset)?Math.max(0,Math.floor(r.offset)):0,o=Number.isFinite(r.limit)?Math.max(1,Math.min(200,Math.floor(r.limit))):50;if(t=t.trim(),!t)return{hits:[],offset:n,limit:o,hasMore:!1};let i;if((r.maintainIndex===!1?Di(e):bb(e))&&!/[\u3040-\u30ff\u3400-\u9fff\uac00-\ud7af]/u.test(t))try{if(mu(e,t,1).length)i=mu(e,t,o+1,n)}catch{}return i??=fR(e,t,n,o+1),{hits:i.slice(0,o),offset:n,limit:o,hasMore:i.length>o}}async function Ra(e,t,r={}){while(!0){if(r.signal?.aborted)throw r.signal.reason??Error("search cancelled");if(wb(e,r.batchSize).ready)break;await new Promise((n)=>setTimeout(n,0))}return yu(e,t,{...r,maintainIndex:!1})}Js();Zt();Ke();function Eb(e){return e.exec(`CREATE TABLE IF NOT EXISTS replica_document_drafts (
588
+ doc_id TEXT PRIMARY KEY, revision INTEGER NOT NULL, title TEXT NOT NULL,
589
+ body TEXT NOT NULL, version TEXT, updated_at INTEGER NOT NULL
590
+ );
591
+ CREATE TABLE IF NOT EXISTS replica_field_drafts (
592
+ record_id TEXT NOT NULL, prop_id TEXT NOT NULL, value TEXT NOT NULL,
593
+ status TEXT NOT NULL, error TEXT, updated_at INTEGER NOT NULL,
594
+ PRIMARY KEY(record_id, prop_id)
595
+ );`),{readDocument(t){return e.query("SELECT revision, title, body, version FROM replica_document_drafts WHERE doc_id = ?").get(t)},checkpointDocument(t,r){if(!Number.isSafeInteger(r.revision)||r.revision<0)throw Error("invalid draft revision");e.query(`INSERT INTO replica_document_drafts (doc_id, revision, title, body, version, updated_at)
596
+ VALUES (?, ?, ?, ?, ?, ?) ON CONFLICT(doc_id) DO UPDATE SET
597
+ revision=excluded.revision, title=excluded.title, body=excluded.body,
598
+ version=excluded.version, updated_at=excluded.updated_at
599
+ WHERE excluded.revision >= replica_document_drafts.revision`).run(t,r.revision,r.title,r.body,r.version,Date.now())},acknowledgeDocument(t,r,n){e.query("DELETE FROM replica_document_drafts WHERE doc_id = ? AND revision <= ?").run(t,r)},discardDocument(t){e.query("DELETE FROM replica_document_drafts WHERE doc_id = ?").run(t)},readFields(t){let r=e.query("SELECT prop_id, value, status, error FROM replica_field_drafts WHERE record_id = ?").all(t);return Object.fromEntries(r.map((n)=>[n.prop_id,{value:JSON.parse(n.value),status:n.status,...n.error?{error:n.error}:{}}]))},checkpointField(t,r,n){e.query(`INSERT INTO replica_field_drafts (record_id, prop_id, value, status, error, updated_at)
600
+ VALUES (?, ?, ?, ?, ?, ?) ON CONFLICT(record_id, prop_id) DO UPDATE SET
601
+ value=excluded.value, status=excluded.status, error=excluded.error, updated_at=excluded.updated_at`).run(t,r,JSON.stringify(n.value??null),n.status,n.error??null,Date.now())},acknowledgeField(t,r,n){e.query("DELETE FROM replica_field_drafts WHERE record_id = ? AND prop_id = ? AND value = ?").run(t,r,JSON.stringify(n??null))},discardRecord(t){e.query("DELETE FROM replica_field_drafts WHERE record_id = ?").run(t)}}}function Sb(e){return e.query("SELECT coalesce(max(seq),0) AS seq FROM crdt_changes").get().seq}function hR(e,t){let r=e.query("SELECT dataset, row_id FROM crdt_changes WHERE seq > ? ORDER BY seq LIMIT 501").all(t);if(!r.length)return null;return{datasets:r.length>500?e.query("SELECT DISTINCT dataset FROM crdt_changes WHERE seq > ?").all(t).map((o)=>o.dataset):[...new Set(r.map((o)=>o.dataset))],rowIds:[...new Set(r.slice(0,500).map((o)=>o.row_id))],truncated:r.length>500}}function gt(e,t){return(...r)=>t(e,...r)}function gR(e,t){if(t.kind!=="document"&&t.kind!=="record")throw new T("invalid_input","unknown reference kind");if(!Array.isArray(t.ids)||!t.ids.every((o)=>typeof o==="string"))throw new T("invalid_input","reference ids must be strings");let r=[...new Set(t.ids)],n=new Map;for(let o=0;o<r.length;o+=200){let i=r.slice(o,o+200),s=[...i,...t.databaseId===void 0?[]:[t.databaseId]],c=t.databaseId===void 0?"":" AND database_id = ?",l=t.kind==="document"?"documents":"records",u=t.kind==="document"?"title":"data ->> (SELECT p.id FROM properties p WHERE p.database_id = records.database_id AND p.__deleted = 0 AND p.type = 'text' ORDER BY p.position, p.id LIMIT 1)",f=e.query(`SELECT id, ${u} AS title FROM ${l} WHERE __deleted = 0 AND id IN (${i.map(()=>"?").join(",")})${c}`).all(...s);for(let _ of f)n.set(_.id,_.title===null?null:String(_.title))}return t.ids.map((o)=>({id:o,title:n.get(o)??null,missing:!n.has(o)}))}function kb(e,t={}){let r=t.searchBatchSize??200;if(!Number.isSafeInteger(r)||r<=0)throw RangeError("searchBatchSize must be a positive integer");let n=new AbortController,o=!1,i=!1,s=new Set;if(t.onChange)s.add(t.onChange);let c=(g)=>{for(let A of s)A(g)},l={listDatabases:gt(e,S_),queryDocuments:(g)=>ob(e,g),createDatabase:gt(e,Al),updateDatabase:gt(e,v_),duplicateDatabase:(g,A={})=>E_(e,g,A),deleteDatabase:(g)=>({ok:k_(e,g)}),listProperties:gt(e,Mt),addProperty:gt(e,Gs),updateProperty:gt(e,vl),moveProperty:gt(e,o_),moveSelectOption:gt(e,i_),setPropertyWidth:gt(e,e_),removeProperty:(g)=>({ok:n_(e,g)}),renameSelectOption:gt(e,t_),removeSelectOption:gt(e,r_),listRecords:gt(e,Co),queryRecords:(g,A)=>rb(e,g,A),getRecord:(g)=>{let A=En(e,g);if(!A)throw new T("not_found",`no such record: ${g}`);return A},createRecord:gt(e,Ys),updateRecord:gt(e,Qs),moveRecord:gt(e,g_),deleteRecord:(g)=>({ok:m_(e,g)}),listRecordRevisions:gt(e,lb),recordAtVersion:gt(e,fu),recordFieldHistory:gt(e,gb),revertRecord:gt(e,db),listPropertyRevisions:gt(e,fb),propertyAtVersion:gt(e,hu),revertProperty:gt(e,hb),listDatabaseActivity:(g,A)=>ub(e,g,{limit:A}),listDocuments:gt(e,hm),getDocument:(g)=>{let A=nt(e,g);if(!A)throw new T("not_found",`no such document: ${g}`);return{...A,version:At(e,g)}},createDocument:(g)=>{let A=_i(e,g);return{...A,version:At(e,A.id)}},updateDocument:(g,A,L)=>({...Ps(e,g,A,{ifMatch:L,preserveBlockIdentity:!!L&&!!at(e)}),version:At(e,g)}),editDocumentBlocks:gt(e,qs),moveDocument:gt(e,el),duplicateDocument:(g,A)=>{let L=bm(e,g,{title:A?.title,parentId:A?.parent_id});return{...L,version:At(e,L.id)}},deleteDocument:(g)=>({ok:wm(e,g)}),listDocumentRevisions:gt(e,sb),documentAtVersion:gt(e,pu),revertDocument:(g,A,L)=>ab(e,g,A,{ifMatch:L}),nodes:()=>Va(e),setNodeLabel:(g,A)=>(xd(e,g,A),Va(e).find((L)=>L.node_id===(A??Je(e)))),search:(g,A)=>Li(e,g,{limit:A,maintainIndex:!1}),querySearch:(g,A)=>yu(e,g,A),referenceSummaries:(g)=>gR(e,g),resolve:(g,A)=>c_(e,g,{limit:A})};function u(g,A){if(i&&!/^(list|get|query|search|reference|resolve|nodes|documentAt|recordAt|propertyAt)/.test(g))throw new T("busy","正在更新本地副本,编辑已暂停");if(!Object.hasOwn(l,g))throw new T("invalid_input",`unknown replica command: ${g}`);let L=Sb(e),F=l[g],X=F(...A),te=hR(e,L);if(te)c(te);return X}function f(g,A){return u(g,A)}async function _(g,...A){return f(g,A)}return{db:e,commands:l,dispatch:f,dispatchRpc:u,call:_,client:{listDatabases:()=>_("listDatabases"),queryDocuments:(g)=>_("queryDocuments",g),createDatabase:(...g)=>_("createDatabase",...g),updateDatabase:(...g)=>_("updateDatabase",...g),duplicateDatabase:(...g)=>_("duplicateDatabase",...g),deleteDatabase:(g)=>_("deleteDatabase",g),listProperties:(g)=>_("listProperties",g),createProperty:(g)=>{let{db:A,...L}=g;return _("addProperty",A,L)},addProperty:(...g)=>_("addProperty",...g),updateProperty:(...g)=>_("updateProperty",...g),moveProperty:(...g)=>_("moveProperty",...g),moveSelectOption:(...g)=>_("moveSelectOption",...g),deleteProperty:(g)=>_("removeProperty",g),listRecords:(...g)=>_("listRecords",...g),queryRecords:(g,A)=>nb(e,g,A,()=>!o),renameSelectOption:(...g)=>_("renameSelectOption",...g),getRecord:(g)=>_("getRecord",g),createRecord:(...g)=>_("createRecord",...g),updateRecord:(...g)=>_("updateRecord",...g),deleteRecord:(g)=>_("deleteRecord",g),moveRecord:(...g)=>_("moveRecord",...g),recordHistory:(g)=>_("listRecordRevisions",g),recordAt:(g,A)=>_("recordAtVersion",g,A),revertRecord:(g,A)=>_("revertRecord",g,A),listDocuments:(g)=>_("listDocuments",g?{database_id:g}:{}),listDocumentsByParent:(g)=>_("listDocuments",{parent_id:g}),getDocument:(g)=>_("getDocument",g),createDocument:(...g)=>_("createDocument",...g),updateDocument:(g,A)=>{let{if_match:L,...F}=A;return _("updateDocument",g,F,L)},editDocumentBlocks:(...g)=>_("editDocumentBlocks",...g),deleteDocument:(g)=>_("deleteDocument",g),duplicateDocument:(...g)=>_("duplicateDocument",...g),moveDocument:(...g)=>_("moveDocument",...g),documentHistory:(g)=>_("listDocumentRevisions",g),documentAt:(g,A)=>_("documentAtVersion",g,A),revertDocument:(g,A,L)=>_("revertDocument",g,A,L),search:(g,A)=>vb(e,g,{limit:A,batchSize:r,signal:n.signal}),querySearch:(g,A)=>Ra(e,g,{...A,batchSize:r,signal:n.signal}),referenceSummaries:(g)=>_("referenceSummaries",g),resolve:(g,A)=>_("resolve",g,A),onUpdate:(g)=>{let A=()=>g({seq:Sb(e)});return s.add(A),()=>{s.delete(A)}}},drafts:Eb(e),pauseMutations(g){i=g},notifyChanges:c,onChange(g){return s.add(g),()=>{s.delete(g)}},dispose(){o=!0,n.abort(),s.clear()}}}var mR=["listDatabases","createDatabase","updateDatabase","duplicateDatabase","deleteDatabase","listDatabaseActivity","listProperties","addProperty","updateProperty","setPropertyWidth","moveProperty","moveSelectOption","removeProperty","renameSelectOption","removeSelectOption","listPropertyRevisions","revertProperty","listRecords","getRecord","createRecord","updateRecord","moveRecord","deleteRecord","listRecordRevisions","recordAtVersion","recordFieldHistory","revertRecord","listDocuments","getDocument","createDocument","updateDocument","duplicateDocument","moveDocument","deleteDocument","listDocumentRevisions","documentAtVersion","revertDocument","nodes","setNodeLabel","resolve","querySearch","referenceSummaries"];function xb(e){let t={};for(let r of mR)t[r]=(...n)=>e().dispatchRpc(r,n);return t.createDocument=(...r)=>{let{version:n,...o}=e().dispatchRpc("createDocument",r);return o},t}Oi();Zt();Vt();Ke();var Ne=(e,t,r)=>Number(e)===1?t:r;var Rb={刚刚:"just now","{n} 分钟前":({n:e})=>`${e} ${Ne(e,"minute","minutes")} ago`,"{n} 小时前":({n:e})=>`${e} ${Ne(e,"hour","hours")} ago`,"{n} 天前":({n:e})=>`${e} ${Ne(e,"day","days")} ago`,今天:"Today",昨天:"Yesterday",本周:"This week","{n} 天后过期":({n:e})=>`Expires in ${e} ${Ne(e,"day","days")}`,"{n} 小时后过期":({n:e})=>`Expires in ${e} ${Ne(e,"hour","hours")}`,"{n} 分钟后过期":({n:e})=>`Expires in ${e} ${Ne(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 Tb={复制链接:"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} ${Ne(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 Db={"在独立窗口中打开":"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} ${Ne(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 Ab={上一条:"Previous",下一条:"Next",复制失败:"Copy failed","{n} 列已隐藏":({n:e})=>`${e} ${Ne(e,"column","columns")} hidden`,"{n} 项":({n:e})=>`${e} ${Ne(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} ${Ne(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 ${Ne(e,"property","properties")}`,"换个关键词,或清除筛选条件。":"Try another keyword, or clear the filters.",换行文本:"Wrap text",查看全文:"Read more","查看「{name}」全文":"Read full {name}",复制全文:"Copy full text","复制「{name}」全文":"Copy full {name}",计数:"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} ${Ne(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} ${Ne(e,"record","records")}`,"{n} 已选":"{n} selected","删除记录?":"Delete record?","确定删除选中的 {n} 条记录?":({n:e})=>`Delete the ${e} selected ${Ne(e,"record","records")}?`,"已删除 {n} 条记录":({n:e})=>`Deleted ${e} ${Ne(e,"record","records")}`,"{n} 个单元格":({n:e})=>`${e} ${Ne(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 ${Ne(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} ${Ne(e,"block","blocks")} changed`,"{n} 块删除":({n:e})=>`${e} ${Ne(e,"block","blocks")} deleted`,元数据:"Metadata",变更:"Changes",源码:"Source","展开 {n} 个未变更块":({n:e})=>`Show ${e} unchanged ${Ne(e,"block","blocks")}`,"展开 {n} 行未变更内容":({n:e})=>`Show ${e} unchanged ${Ne(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 ${Ne(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 ${Ne(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} ${Ne(e,"item","items")}, kept ${t} later ${Ne(t,"edit","edits")}`,"已恢复 {n} 项":({n:e})=>`Restored ${e} ${Ne(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} ${Ne(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 Ob={"Logo 外观":"Logo appearance","当前 Logo":"Current logo",配色:"Color",彩色:"Multicolor",蓝色:"Blue",底色:"Background",浅底:"Light",深底:"Dark",浅色:"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
602
  1. Content already synced to the bucket is safe;
539
603
  2. Local edits not yet synced will be lost;
540
604
  3. Local attachments not yet uploaded will be lost;
@@ -542,44 +606,32 @@ if(L instanceof ArrayBuffer)L=new Uint8Array(L);else if(L instanceof Function)re
542
606
  1. Synced content stays on the workspace primary node;
543
607
  2. Local edits not yet synced will be lost;
544
608
  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","此浏览器不支持 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 Iu={"加载失败:{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,...Cu,...Iu,...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 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}}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
- WHERE (dataset = 'documents' AND row_id = ?)${s}
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 Cm(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 Im(e,t){let r=Wi(e,"records",t);if(!r.length)throw new H("not_found",`no such record: ${t}`);return Nn(r).map(Cm).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
- 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 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({...Cm(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),KC=Zi((e)=>e.synced),GC=Zi((e)=>e.tier==="content"),Fm=Zi((e)=>e.tier==="system"),VC=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
- ${s.length?"WHERE "+s.join(" AND "):""}
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
609
+ 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} ${Ne(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} ${Ne(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} ${Ne(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} ${Ne(e,"item","items")} · freed ${t}`,没有可清理的项:"Nothing to clear","删除孤儿 blob":"Delete orphan blobs","将从这台设备移除 {n} 个未被任何文档/站点引用的 blob,约 {bytes}。桶里的原件不动,需要时仍可重新下载。":({n:e,bytes:t})=>`Removes ${e} ${Ne(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} ${Ne(e,"blob","blobs")} referenced by no document or site, about ${t}. This cannot be undone.`,"已删除 {n} 项 · 腾出 {bytes}":({n:e,bytes:t})=>`Deleted ${e} ${Ne(e,"item","items")} · freed ${t}`,没有可删除的孤儿:"No orphans to delete",排序依据:"Sort by",按类型:"By type",按状态:"By status","已选 {n} 项 · {bytes}":({n:e,bytes:t})=>`${e} ${Ne(e,"item","items")} selected · ${t}`,"共 {n} 项 · {bytes}":({n:e,bytes:t})=>`${e} ${Ne(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 Cb={"查看":"Review","稍后":"Later","需要更新客户端":"App update required","只读查看":"View read-only","更新安装完成后,请重新打开应用。":"Reopen the app after the update has been installed.","工作区数据版本为 {remote},当前客户端最高支持 {max}。本地内容可查看和导出。":"This workspace uses data version {remote}. Your app supports up to {max}. You can view and export local content.","更新应用":"Update app","立即升级":"Upgrade now","升级工作区同步":"Upgrade workspace sync","应用会备份本机编辑并更新同步格式。升级期间请保持应用打开,编辑会短暂停用。":"Your edits will be backed up before sync is upgraded. Keep the app open. Editing will pause briefly.","本地副本与恢复":"Local replica and recovery","正在保存编辑并更新本地副本…":"Saving edits and rebuilding the local replica…","本地副本已更新,有 {n} 项编辑待恢复。":"Local replica updated. Edits awaiting recovery: {n}.","本地副本已更新。":"Local replica updated.","丢弃此项编辑?":"Discard this edit?","此项将从待恢复列表移除。":"This will remove the edit from the recovery list.","重建使用的存储桶":"Bucket to rebuild from","待恢复内容":"Edit to recover","另一份内容":"Other version","创建恢复副本":"Create recovered copy","丢弃此项":"Discard this edit","丢弃":"Discard","加载失败:{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} ${Ne(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} ${Ne(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} ${Ne(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} ${Ne(e,"place","places")} · ${t} ${Ne(t,"attachment is","attachments are")} still only here`,"已保存在 {n} 处 · 有改动尚未同步":({n:e})=>`Saved in ${e} ${Ne(e,"place","places")} · unsynced changes`,"已保存在 {n} 处 · {m} 处同步失败":({n:e,m:t})=>`Saved in ${e} ${Ne(e,"place","places")} · ${t} ${Ne(t,"place","places")} failing to sync`,"已保存在 {n} 处 · 首次同步进行中":({n:e})=>`Saved in ${e} ${Ne(e,"place","places")} · first sync in progress`,"已保存在 {n} 处 · 备份确认已过期":({n:e})=>`Saved in ${e} ${Ne(e,"place","places")} · backup confirmation expired`,"已安全保存在 {n} 处 · 上次确认 {ago}":({n:e,ago:t})=>`Safely saved in ${e} ${Ne(e,"place","places")} · last confirmed ${t}`,"已安全保存在 {n} 处":({n:e})=>`Safely saved in ${e} ${Ne(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 Ib={手机:"Phone","复制失败,请手动选择并复制":"Copy failed. Select and copy the text manually.","选择设备和接入方式,加入同一个工作区。":"Choose a device and connection method to join this workspace.","连接当前服务器":"Connect to this server","通过存储桶同步":"Sync through a bucket","连接时需要服务器在线且可访问。":"The server must be online and reachable when connecting.","设备通过桶交换数据,不必同时在线。":"Devices exchange data through the bucket without being online at the same time.","桌面应用的本机服务仅允许本机访问,不能邀请其他设备直连。":"The desktop service only accepts connections from this computer. Other devices cannot connect directly.","当前工作区通过存储桶同步,没有可供连接的服务器。":"This workspace syncs through a bucket and has no server to connect to.","连接已有服务器":"Connect to an existing server","当前服务器的可访问地址":"Reachable address of this server","请输入另一台设备可访问的 HTTP/HTTPS 根地址,不能使用 localhost、回环地址或带凭据的链接。":"Enter an HTTP/HTTPS root address reachable from the other device, without localhost, loopback addresses or embedded credentials.","请填写同一服务器的地址;这里不会验证另一台设备能否访问。":"Use an address for this same server. Reachability from the other device is not checked here.","打开服务器工作区;离线副本可在「离线与缓存」中设置。":"Open the server workspace. Configure an offline copy under Offline & cache.","重新生成":"Regenerate","生成接入命令":"Generate connection command","配对码仅供一次接入,请勿公开分享。":"The pairing code allows one connection. Do not share it publicly.","在另一台已安装 mh 的电脑运行,建立本地同步关系并尝试首次同步。后续运行 mh sync;命令退出后不会持续自动同步。":"Run on another computer with mh installed to pair a local copy and attempt the first sync. Run mh sync afterwards; syncing does not continue after the command exits.","尚未连接存储桶":"No bucket connected","前往数据与备份":"Go to Data & backup","手机访问的站点地址":"Site address to open on the phone","请输入手机可访问的 HTTP/HTTPS 站点根地址。":"Enter an HTTP/HTTPS site root reachable from the phone.","电脑或服务器均可主动连接。请填入对方服务器的地址和配对码。":"A computer or server can initiate the connection. Enter the remote server address and pairing code.",回滚待确认:"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} ${Ne(e,"file","files")} under api/ will be shadowed by the site data API (uploaded, but unreachable)`,"已上传 {n} 个文件":({n:e})=>`Uploaded ${e} ${Ne(e,"file","files")}`,"已上传 {ok}/{total} 个,{failed} 个失败":"Uploaded {ok}/{total}, {failed} failed",部分文件上传失败:"Some files failed to upload","{n} 个文件未能上传,可修正后重新拖入(成功的文件无需重传)。":({n:e})=>`${e} ${Ne(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} ${Ne(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} ${Ne(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 ${Ne(e,"URL","URLs")}`,"{n} 个私密链接":({n:e})=>`${e} private ${Ne(e,"link","links")}`,"私有预览 · {url}":"Private preview · {url}","{n} 文件":({n:e})=>`${e} ${Ne(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} ${Ne(e,"site","sites")}`,"{n} 个文件":({n:e})=>`${e} ${Ne(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} ${Ne(e,"file","files")} · created ${t}`,"已发布 · {n} 个渠道":({n:e})=>`Published · ${e} ${Ne(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} ${Ne(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.",复制链接:"Copy link",已复制链接:"Link copied",打开方式:"Open in","Metahub 手机 App":"Metahub mobile app","浏览器 / PWA":"Browser / PWA","请先在手机上安装 Metahub App,再用相机扫描二维码;也可把链接粘贴到 App 的连接页面。":"Install the Metahub app on your phone first, then scan with the camera, or paste the link into the app's Connect screen.","用手机相机扫码,在浏览器中打开;可添加到主屏幕作为 PWA 使用。":"Scan with your phone camera to open in the browser. Add it to your home screen to use it as a PWA.","连接后,请在手机上另行输入此存储桶的加密口令。链接和二维码不包含口令。":"After connecting, enter this bucket's encryption passphrase separately on your phone. The link and QR code do not include it.",在另一台电脑的终端运行:"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",完成:"Done","⚠ 含访问令牌,请勿公开分享。":"⚠ Contains the access token; do not share publicly.","电脑 / 命令行":"Computer / CLI",找不到该存储的配置:"Configuration for this storage was not found",添加设备:"Add device","加载中…":"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 Nb={"新建链接":"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} ${Ne(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 ${Ne(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} ${Ne(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} ${Ne(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} ${Ne(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 Pb={...Rb,...Tb,...Db,...Ab,...Ob,...Cb,...Ib,...Nb};var qb="mh-lang",bu=(e)=>e==="zh-CN"||e==="en";function wu(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 _R=qb;function yR(){try{return typeof localStorage<"u"?localStorage:null}catch{return null}}function bR(){let e=yR()?.getItem(_R);return bu(e)?e:"system"}function wR(){if(typeof navigator>"u")return"zh-CN";let e=navigator.languages?.length?navigator.languages:[navigator.language];return wu(e)}function vR(){if(typeof location>"u")return null;let e=new URLSearchParams(location.search).get("lang");return bu(e)?e:null}var Ta=null,vu=null;function ER(){if(typeof globalThis.Bun<"u")return"zh-CN";let e=vR();if(e)return e;let t=bR();return t==="system"?wR():t}function Lb(){if(vu)return vu;if(!Ta)Ta=ER();return Ta}function $b(e){vu=e,Ta=null}function SR(e,t){if(!t)return e;return e.replace(/\{(\w+)\}/g,(r,n)=>(n in t)?String(t[n]):r)}var kR="##";function xR(e,t,r){let n=e==="en"?Pb[t]:void 0;if(typeof n==="function")return n(r??{});let o=t.indexOf(kR);return SR(n??(o<0?t:t.slice(0,o)),r)}function kn(e,t){return xR(Lb(),e,t)}er();Kt();it();Ti();Cs();eo();hi();var Mb=(e)=>{let t=/^[a-z0-9+]+:\/\/([^/]+)/i.exec(e);return t?t[1]:e};function RR(e,t,r,n,o,i){let s=e.kind==="s3",c=s?n:r,l=Math.max(0,c-e.pushCursor),u=s?["backend"]:["replica"],f=s?e.url:e.nodeId;if(f&&t.includes(f))u.push("blob_anchor");if(s&&e.publish)u.push("publisher");return{kind:s?"bucket":"device",url:e.url,label:e.label??(s?e.bucket??Mb(e.url):Mb(e.url)),freshness:!e.enabled?"disabled":e.lastStatus==="error"?"error":e.lastSuccessAt==null?"never":l>0?"behind":o-e.lastSuccessAt>i?"stale":"current",syncedAt:e.lastSuccessAt,error:e.lastStatus==="error"?e.lastError??null:null,acknowledgedSeq:e.pushCursor,highWaterSeq:c,lag:l,roles:u}}function Eu(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=(s)=>s==="current"?0:s==="stale"?1:s==="behind"?2:s==="error"?3:s==="never"?4:5,n=e.now??Date.now(),o=e.staleAfterMs??86400000,i=e.peers.map((s)=>RR(s,e.blobFullNodes,e.globalHighWaterSeq,e.ownHighWaterSeq,n,o)).sort((s,c)=>Number(s.kind==="bucket")-Number(c.kind==="bucket")||r(s.freshness)-r(c.freshness)||s.label.localeCompare(c.label));return[t,...i]}function Fb(e){let r=Eu(e).filter((l)=>l.kind!=="self"&&l.freshness!=="disabled"),n=r.filter((l)=>l.syncedAt!=null&&l.acknowledgedSeq>=l.highWaterSeq),o=n.length?n.reduce((l,u)=>l==null||(u.syncedAt??0)<l?u.syncedAt:l,null):null,i=r.reduce((l,u)=>Math.max(l,u.lag),0),s=[];if(r.length===0)s.push({kind:"no_backup",placeUrl:null,placeLabel:null,message:null});for(let l of r)if(l.freshness==="error")s.push({kind:"peer_error",placeUrl:l.url,placeLabel:l.label,message:l.error});if(e.pendingBlobCount>0)s.push({kind:"pending_blobs",placeUrl:null,placeLabel:null,message:null});for(let l of r)if(l.freshness==="behind")s.push({kind:"behind",placeUrl:l.url,placeLabel:l.label,message:null});for(let l of r)if(l.freshness==="never")s.push({kind:"never_synced",placeUrl:l.url,placeLabel:l.label,message:null});for(let l of r)if(l.freshness==="stale")s.push({kind:"stale",placeUrl:l.url,placeLabel:l.label,message:null});let c={places:1+n.length,pendingBlobCount:e.pendingBlobCount,pendingBlobBytes:e.pendingBlobBytes,pendingChanges:i,oldestSyncedAt:o,issues:s};if(r.length===0)return{state:"no_backup",...c};if(r.some((l)=>l.freshness==="error"))return{state:"peer_error",...c};if(e.pendingBlobCount>0)return{state:"pending_blobs",...c};if(i>0)return{state:"unsynced_changes",...c};if(r.some((l)=>l.freshness==="never"))return{state:"syncing",...c};if(r.some((l)=>l.freshness==="stale"))return{state:"stale",...c};return{state:"healthy",...c}}Zt();Ti();Kt();eo();function zb(e){let t=Je(e),r=e.query("SELECT MAX(seq) AS global_seq, MAX(CASE WHEN node_id = ? THEN seq END) AS own_seq FROM crdt_changes WHERE dataset != ? OR hlc >= ?").get(t,fn,$n()),n=e.query("SELECT value FROM meta WHERE key = 'cfg_sync_interval'").get(),o=Number(n?.value),i=Math.max(900000,Number.isFinite(o)&&o>0?o*3:0),s=Ft(e).filter((u)=>u.kind==="http"||u.kind==="s3").map((u)=>{let f=null,_;if(u.kind==="s3"&&u.config)try{let E=JSON.parse(u.config);f=E.bucket??null,_=E.publish}catch{}return{url:u.url,kind:u.kind,label:u.label,nodeId:u.node_id,enabled:!!u.enabled,lastSuccessAt:u.last_success_at,lastStatus:u.last_status,lastError:u.last_error,pushCursor:u.kind==="s3"?Ts(e,u.url,u.push_cursor):u.push_cursor,bucket:f,publish:_}}),c=B_(e),l={selfNodeId:t,selfLabel:kd(e),peers:s,pendingBlobCount:c.length,pendingBlobBytes:c.reduce((u,f)=>u+f.size,0),blobFullNodes:Ri(e).fullNodes,globalHighWaterSeq:r.global_seq??0,ownHighWaterSeq:r.own_seq??0,staleAfterMs:i};return{state:Fb(l),places:Eu(l)}}Ql();Zt();No();qi();function Ub(e,t){let r=Je(e),n=cn(e,t,"revoked");if(n.audience==="public"&&!Rr(e,n.site_id).some((o)=>o.audience==="public"&&o.desired_state==="active"))pa(e,n.site_id,{visibility:"private"});if(n.hosting==="device"&&n.target_ref===r)return ir(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 ir(e,{channelId:n.id,status:"cleanup_pending",lastError:"等待控制设备上线并应用撤销"}),{channel:n,needsReconcile:!1}}Pr();Pr();Ke();Da();function Ou(e){return e.replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'")}function Zb(e,t={}){let r=Ru(e);async function n(l,u,f){return rr(async(_)=>{let E=t.fetch?await t.fetch(await r.sign(l,{...u,signal:_})):await r.fetch(l,{...u,signal:_});return f(E,_)},t.timeoutMs,t.signal)}let o=Du(e),i=(l)=>Au(e,l);async function s(){await n(`${o}/?versioning`,{method:"GET"},async(l)=>{if(!l.ok)throw new T(l.status===401||l.status===403?"auth":"network",`Tencent COS conditional creation requires cos:GetBucketVersioning permission; versioning check failed: ${l.status}`);let u=await l.text();if(!/^\s*(?:<\?xml[\s\S]*?\?>\s*)?<VersioningConfiguration(?:\s+[^>]*?)?\s*(?:\/>|>\s*<\/VersioningConfiguration>)\s*$/.test(u))throw new T("invalid_input","Tencent COS conditional creation requires a bucket that has never enabled versioning; enabled, suspended or unverified versioning cannot prevent overwrites")})}async function c(l,u){throw new T(l.status===401||l.status===403?"auth":"network",`S3 ${u} failed: ${l.status}`)}return{async conditionalCreateCapability(){if(Tu(e)==="cos")return await s(),!0;let u=new URL(e.endpoint).hostname;return/(?:^|\.)amazonaws\.com(?:\.cn)?$|(?:^|\.)r2\.cloudflarestorage\.com$/i.test(u)},async getWithMetadata(l,u){let f=u.maxBytes;if(!Number.isSafeInteger(f)||f<0)throw RangeError("maxBytes must be a nonnegative safe integer");return n(i(l),{},async(_,E)=>{if(_.status===404)return null;if(!_.ok)await c(_,"get");let g=_.headers.get("content-length"),A=()=>new T("invalid_input","Storage object exceeds the size limit");if(g!==null&&Number(g)>f)throw await _.body?.cancel(),A();let L=_.body?.getReader?.(),F=[],X=0;if(L){let Ce=()=>{L.cancel(E.reason).catch(()=>{})};E.addEventListener("abort",Ce,{once:!0});try{while(!0){if(E.aborted)throw E.reason;let ge=await L.read();if(E.aborted)throw E.reason;if(ge.done)break;if(X+=ge.value.length,X>f)throw await L.cancel(),A();F.push(ge.value)}}finally{E.removeEventListener("abort",Ce),L.releaseLock()}}else{let Ce=new Uint8Array(await _.arrayBuffer());if(Ce.length>f)throw A();F.push(Ce),X=Ce.length}let te=new Uint8Array(X),ce=0;for(let Ce of F)te.set(Ce,ce),ce+=Ce.length;let de=(Ce)=>{let ge=_.headers.get(Ce),Pe=ge===null?NaN:Date.parse(ge);return Number.isFinite(Pe)?Pe:null};return{bytes:te,serverDate:de("date"),lastModified:de("last-modified"),etag:_.headers.get("etag")}})},async list(l,u,f){let _=[],E,g=new Set;do{let A=new URL(o);if(A.searchParams.set("list-type","2"),A.searchParams.set("prefix",l),A.searchParams.set("max-keys","1000"),u)A.searchParams.set("start-after",u);if(f)A.searchParams.set("delimiter",f);if(E)A.searchParams.set("continuation-token",E);let L=await n(A.toString(),{method:"GET"},async(te)=>{if(!te.ok)await c(te,"list");return te.text()}),F=/<Contents>([\s\S]*?)<\/Contents>/g,X;while(X=F.exec(L)){let te=X[1],ce=/<Key>([^<]+)<\/Key>/.exec(te)?.[1];if(!ce)continue;_.push({key:Ou(ce),etag:/<ETag>([^<]*)<\/ETag>/.exec(te)?.[1]})}if(f){let te=/<CommonPrefixes>([\s\S]*?)<\/CommonPrefixes>/g;while(X=te.exec(L)){let ce=/<Prefix>([^<]+)<\/Prefix>/.exec(X[1])?.[1];if(ce)_.push({key:Ou(ce)})}}if(/<IsTruncated>true<\/IsTruncated>/.test(L)){let te=/<NextContinuationToken>([^<]+)<\/NextContinuationToken>/.exec(L)?.[1];if(!te||g.has(te))throw Error("S3 list returned an invalid continuation token");g.add(te),E=Ou(te)}else E=void 0}while(E);return _},async get(l,u){return n(i(l),{},async(f,_)=>{if(f.status===404)return null;if(!f.ok)await c(f,"get");let E=u?.maxBytes;if(E==null)return new Uint8Array(await f.arrayBuffer());if(!Number.isSafeInteger(E)||E<0)throw RangeError("maxBytes must be a nonnegative safe integer");let g=()=>new T("invalid_input","Attachment exceeds the size limit"),A=f.headers.get("content-length");if(A!=null&&Number(A)>E)throw f.body?.cancel().catch(()=>{}),g();let L=f.body?.getReader?.();if(!L){let ce=new Uint8Array(await f.arrayBuffer());if(ce.byteLength>E)throw g();return ce}let F=[],X=0,te=()=>{L.cancel(_.reason).catch(()=>{})};_.addEventListener("abort",te,{once:!0});try{while(!0){if(_.aborted)throw _.reason??Error("blob transfer aborted");let Ce=await L.read();if(_.aborted)throw _.reason??Error("blob transfer aborted");if(Ce.done)break;if(X+=Ce.value.byteLength,X>E)throw te(),g();F.push(Ce.value)}let ce=new Uint8Array(X),de=0;for(let Ce of F)ce.set(Ce,de),de+=Ce.byteLength;return ce}finally{_.removeEventListener("abort",te),L.releaseLock()}})},async put(l,u,f){let _=!!f?.ifNoneMatch||f?.ifMatch!==void 0;if(f?.ifMatch!==void 0&&(!f.ifMatch.trim()||f.ifNoneMatch))throw new T("invalid_input","Conditional put requires one nonempty If-Match value or If-None-Match");let E=_?Tu(e):"s3";if(E==="cos"&&f?.ifMatch!==void 0)throw new T("invalid_input","Tencent COS does not support atomic conditional updates (If-Match); use storage with atomic conditional writes for key rotation or passphrase changes");let g={};if(f?.contentType)g["content-type"]=f.contentType;if(f?.ifNoneMatch)if(E==="cos")await s(),g["x-cos-forbid-overwrite"]="true";else g["if-none-match"]="*";if(f?.ifMatch!==void 0)g["if-match"]=f.ifMatch;await n(i(l),{method:"PUT",body:u,headers:Object.keys(g).length?g:void 0},async(A)=>{if(_&&A.status===412)throw new T("conflict","S3 conditional put precondition failed");if(E==="cos"&&f?.ifNoneMatch&&A.status===409){let L=await A.text();if(/<Code>\s*FileAlreadyExists\s*<\/Code>/.test(L))throw new T("conflict","Tencent COS object already exists")}if(!A.ok)await c(A,"put")})},async del(l){await n(i(l),{method:"DELETE"},async(u)=>{if(!u.ok&&u.status!==404)await c(u,"delete")})}}}qm(Zb);yn();it();Ke();Ba();function Gb(e,t){if(e==="records")return Ya.has(t);return t==="created_hlc"||t==="__deleted"}function Kb(){let e=[...ns,...gd];return{sql:e.map(()=>"dataset != ?"),params:e}}function Cu(e,t,r){let n=Kb(),o=["txn = ?",...n.sql],i=[t,...n.params];if(r)o.push("hlc < ?"),i.push(r);return e.query(`SELECT ${vt} FROM crdt_changes WHERE ${o.join(" AND ")} ORDER BY hlc`).all(...i)}function Jb(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 OR(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 CR(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 i=o.database_id?OR(e,o.database_id,n):null,s=JSON.parse(o.data||"{}");return{label:i&&s[i]!=null?String(s[i]):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:Jb(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 Xb(e,t,r){for(let i of t)if(i.dataset==="doc_blocks"&&i.row_id===r&&i.col==="doc_id"&&i.value)return JSON.parse(i.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 Yb(e,t,r){let n=new Map,o=(u,f)=>{let _=u+"\x00"+f,E=n.get(_);if(!E)E={dataset:u,id:f,created:!1,deleted:!1,fields:new Set,blocksChanged:new Set,blocksDeleted:new Set},n.set(_,E);return E};for(let u of t){if(u.dataset==="doc_blocks"){let _=Xb(e,t,u.row_id),E=_?o("documents",_):o("doc_blocks",u.row_id);if(u.col==="__deleted"&&Tr(u.value))E.blocksDeleted.add(u.row_id);else E.blocksChanged.add(u.row_id);continue}let f=o(u.dataset,u.row_id);if(u.col==="created_hlc"||u.dataset==="properties"&&u.col==="database_id")f.created=!0;else if(u.col==="__deleted")f.deleted=Tr(u.value);if(!Gb(u.dataset,u.col))f.fields.add(u.col)}let i=[...n.values()].map((u)=>{let{label:f,database_id:_}=CR(e,u.dataset,u.id,r);return{dataset:u.dataset,id:u.id,label:f,database_id:_,database_label:u.dataset==="databases"?null:Jb(e,_,r),created:u.created,deleted:u.deleted,fields:u.fields.size,blocks_changed:[...u.blocksChanged].filter((E)=>!u.blocksDeleted.has(E)).length,blocks_deleted:u.blocksDeleted.size}}),s=t[t.length-1],{actor:c,kind:l}=oo(s.txn);return{version:s.hlc,at:$o(s.hlc),node_id:s.node_id,kind:l,actor:c,txn:s.txn,changes:t.length,entities:i}}function Qb(e,t={}){let r=Math.max(1,Math.min(t.limit??50,200));if(t.actor!==void 0&&!Md.test(t.actor))throw new T("invalid_input",`invalid actor tag: ${t.actor}`);let n=Math.min(Math.max(r*40,800),8000),o=Kb(),i=[...o.sql],s=[...o.params];if(t.before)i.push("hlc < ?"),s.push(t.before);if(t.actor!==void 0)i.push("txn >= ?","txn < ?"),s.push(t.actor+"/",t.actor+"0");let c=e.query(`SELECT ${vt} FROM crdt_changes
610
+ ${i.length?"WHERE "+i.join(" AND "):""}
611
+ ORDER BY hlc DESC LIMIT ?`).all(...s,n),l=c.length<n;c.reverse();let u=Mo(c);if(!l&&u.length>0){let F=u[0][0].txn;if(F!==null)u[0]=Cu(e,F,t.before);else if(u.length>1)u=u.slice(1)}let f={dbNames:new Map,titleProps:new Map},_=u.reverse(),E=_.slice(0,r),g=E.map((F)=>Yb(e,F,f)),L=(!l||_.length>r)&&E.length?E[E.length-1][0].hlc:null;return{entries:g,next:L}}function ew(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 IR(e,t,r){if(t!=="records")return r;return e.query("SELECT name FROM properties WHERE id = ?").get(r)?.name??r}function tw(e,t){let r=Cu(e,t);if(!r.length)throw new T("not_found",`no change group: ${t}`);let o=Yb(e,r,{dbNames:new Map,titleProps:new Map}),i=new Map,s=new Map;for(let u of r){let f=u.dataset+"\x00"+u.row_id+"\x00"+u.col;if(!i.has(f))i.set(f,u);s.set(f,u)}let c=o.entities.map((u)=>({...u,diffs:[],block_diffs:[]})),l=new Map(c.map((u)=>[u.dataset+"\x00"+u.id,u]));for(let[u,f]of s){let _=i.get(u),E=(g)=>{let A={col:f.dataset==="doc_blocks"?f.row_id:f.col,label:g},L=ew(e,f.dataset,f.row_id,f.col,_.hlc);if(L&&L.value!==null)A.before=JSON.parse(L.value);if(f.value!==null)A.after=JSON.parse(f.value);return A};if(f.dataset==="doc_blocks"){if(f.col!=="text")continue;let g=Xb(e,r,f.row_id);l.get(g?"documents\x00"+g:"doc_blocks\x00"+f.row_id)?.block_diffs.push(E("block"));continue}if(Gb(f.dataset,f.col))continue;l.get(f.dataset+"\x00"+f.row_id)?.diffs.push(E(IR(e,f.dataset,f.col)))}return{...o,entities:c}}var rw=We(function(t,r){let n=Cu(t,r);if(!n.length)throw new T("not_found",`no change group: ${r}`);let o=new Map;for(let u of n){let f=u.dataset+"\x00"+u.row_id,_=o.get(f);if(!_)o.set(f,_=[]);_.push(u)}let i=0,s=0,c=0,l=0;for(let u of o.values()){let{dataset:f,row_id:_}=u[0],E=u[0].hlc;if(!t.query("SELECT 1 AS x FROM crdt_changes WHERE dataset = ? AND row_id = ? AND hlc < ? LIMIT 1").get(f,_,E)){if(t.query("SELECT 1 AS x FROM crdt_changes WHERE dataset = ? AND row_id = ? AND txn IS NOT ? LIMIT 1").get(f,_,r)){l++;continue}let F=[...u].reverse().find((X)=>X.col==="__deleted");if(F&&Tr(F.value))continue;_e(t,f,_,"__deleted",1),c++;continue}let A=new Map;for(let L of u)if(!A.has(L.col))A.set(L.col,L);for(let[L,F]of A){let X=t.query("SELECT value, txn FROM crdt_changes WHERE dataset = ? AND row_id = ? AND col = ? ORDER BY hlc DESC LIMIT 1").get(f,_,L);if(X.txn!==r){s++;continue}let te=ew(t,f,_,L,F.hlc),ce=te===void 0?L==="__deleted"?0:void 0:te.value===null?void 0:JSON.parse(te.value);if((ce===void 0?null:JSON.stringify(ce))===X.value)continue;_e(t,f,_,L,ce),i++}}return{txn:r,changed:i>0||c>0,restored_registers:i,skipped_registers:s,removed_rows:c,skipped_rows:l}},"revert");it();sn();es();Zt();Ln();var nw=[{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 ow(e,t){return e.query(`SELECT s.id AS id, s.${t.fk} AS ref FROM ${t.srcTable} s
552
612
  JOIN ${t.tgtTable} t ON t.id = s.${t.fk} AND t.__deleted = 1
553
613
  WHERE s.__deleted = 0 AND s.${t.fk} IS NOT NULL
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
614
+ ORDER BY s.id`).all()}function NR(e){let t=[];for(let r of nw)for(let n of ow(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 PR(e){let t=0;for(let r of nw)for(let n of ow(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 iw(e){return e.query(`SELECT r.id AS rec, j.key AS prop
555
615
  FROM records r, json_each(coalesce(r.data, '{}')) j
556
616
  JOIN properties p ON p.id = j.key AND p.__deleted = 1
557
617
  WHERE r.__deleted = 0
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
- FROM records r, json_each(r.data -> '${s}') j
618
+ ORDER BY r.id, j.key`).all()}function qR(e){return iw(e).map((t)=>({category:"orphan_cell",entity:"records",id:t.rec,detail:`cell for deleted property ${t.prop}`,fixable:!0}))}function LR(e){let t=iw(e);for(let r of t)_e(e,"records",r.rec,r.prop,void 0);return t.length}function sw(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",i=n.id.replace(/'/g,"''"),s=e.query(`SELECT r.id AS rec, j.value AS dead
619
+ FROM records r, json_each(r.data -> '${i}') j
560
620
  JOIN ${o} t ON t.id = j.value AND t.__deleted = 1
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 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
621
+ WHERE r.__deleted = 0 AND json_type(r.data -> '${i}') = 'array'
622
+ ORDER BY r.id, j.value`).all(),c=null;for(let l of s){if(!c||c.rec!==l.rec)c={rec:l.rec,prop:n.id,tgtTable:o,dead:[]},r.push(c);c.dead.push(l.dead)}}return r}function $R(e){return sw(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 MR(e){let t=sw(e);for(let r of t){let n=e.query("SELECT data FROM records WHERE id = ?").get(r.rec);if(!n)continue;let i=JSON.parse(n.data||"{}")[r.prop];if(!Array.isArray(i))continue;let s=new Set(r.dead);_e(e,"records",r.rec,r.prop,i.filter((c)=>!s.has(String(c))))}return t.length}function aw(e){let t=e.query(`SELECT id, site_id, path FROM site_files
563
623
  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 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
624
+ ORDER BY site_id, path, created_hlc, id`).all(),r=[],n=null;for(let o of t){let i=`${o.site_id}\x00${o.path}`;if(i===n)r.push({id:o.id});else n=i}return r}function FR(e){return aw(e).map((t)=>({category:"dup_path",entity:"site_files",id:t.id,detail:"redundant duplicate (site_id, path); loser tombstoned",fixable:!0}))}function zR(e){let t=aw(e);for(let r of t)_e(e,"site_files",r.id,"__deleted",1);return t.length}function cw(e){let t=e.query(`SELECT d.id AS id, d.parent_id AS parent, d.created_hlc AS hlc
565
625
  FROM documents d
566
626
  WHERE d.__deleted = 0 AND d.parent_id IS NOT NULL
567
627
  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 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
628
+ ORDER BY d.id`).all(),r=new Map(t.map((s)=>[s.id,s.parent])),n=new Map(t.map((s)=>[s.id,s.hlc])),o=new Set,i=[];for(let s of r.keys()){if(o.has(s))continue;let c=[],l=new Map,u=s;while(u!=null&&r.has(u)&&!o.has(u)){if(l.has(u)){i.push(c.slice(l.get(u)));break}l.set(u,c.length),c.push(u),u=r.get(u)}for(let f of c)o.add(f)}return{cycles:i,hlc:n}}function UR(e,t,r){let n=e.get(t)??"",o=e.get(r)??"";if(n!==o)return n>o;return t>=r}function BR(e){let{cycles:t}=cw(e);return t.map((r)=>({category:"parent_cycle",entity:"documents",id:[...r].sort()[0],detail:`parent cycle: ${[...r].sort().join(" → ")}`,fixable:!0}))}function jR(e){let{cycles:t,hlc:r}=cw(e);for(let n of t){let o=n.reduce((i,s)=>UR(r,i,s)?i:s);_e(e,"documents",o,"parent_id",null)}return t.length}function HR(e){let t=[],r=e.query(`SELECT database_id AS db, lower(name) AS n, count(*) AS c, group_concat(id) AS ids
569
629
  FROM properties
570
630
  WHERE __deleted = 0 AND name IS NOT NULL AND database_id IS NOT NULL
571
631
  GROUP BY database_id, lower(name) HAVING c > 1
572
632
  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
633
  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 CS(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 IS(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=CS(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),...IS(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 cI=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
- FROM records r, json_each(r.data) je
576
- JOIN properties p ON p.id = je.key AND p.__deleted = 0
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
- FROM records r, json_each(r.data) je
580
- JOIN properties p ON p.id = je.key AND p.__deleted = 0
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,O_=null;function C_(){let e=new zc.OpfsSAHPoolDb("/metahub.db");O_=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"}),C_();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 Cr(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 Cr(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 Cr(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=Cr(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
634
+ 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 WR(e,t){if(!Zs.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 VR(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 i=WR(n.type,o);if(i)r.push({category:"bad_config",entity:"properties",id:n.id,detail:i,fixable:!1})}return r}function ZR(e,t){let n=e.query("SELECT node_id, COUNT(*) AS n FROM crdt_changes WHERE hlc > ? GROUP BY node_id").all(Ji(t)).map((i)=>({category:"clock_skew",entity:"nodes",id:i.node_id,detail:`${i.n} change(s) stamped more than 5 min in the future — run \`mh repair --clock\``,fixable:!1})),o=Ka(e);if(o&&o.millis>t+Nn)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 lw(e,t=Date.now()){return Ve(e,()=>{let r=e.query(`SELECT seq, ${vt} FROM crdt_changes WHERE hlc > ? ORDER BY hlc, seq`).all(Ji(t)),n={},o=Ka(e),i=r.length>0||o!=null&&o.millis>t+Nn;if(i)Od(e,Je(e),t);if(r.length===0)return{restamped:0,byNode:n,clockReset:i};let s=new Map;for(let c of r){e.query("DELETE FROM crdt_changes WHERE seq = ?").run(c.seq);let{seq:l,...u}=c,f={...u,hlc:Qi(e,c.node_id,t)};yo(e,f),s.set(`${u.dataset}\x00${u.row_id}\x00${u.col}`,f),n[c.node_id]=(n[c.node_id]??0)+1}for(let c of s.values()){let l=e.query(`SELECT ${vt} 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(l)yo(e,l)}return mo(e),{restamped:r.length,byNode:n,clockReset:i}})}function GR(e,t={}){let r=[...NR(e),...qR(e),...$R(e),...FR(e),...BR(e),...HR(e),...VR(e),...ZR(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 KR(e){let t={},r=(o,i)=>{if(i)t[o]=(t[o]??0)+i};return r("broken_ref",PR(e)),r("orphan_cell",LR(e)),r("dead_cell_ref",MR(e)),r("dup_path",zR(e)),r("parent_cycle",jR(e)),{applied:Object.values(t).reduce((o,i)=>o+i,0),fixed:t}}var _3=We(function(t){let r={},n=0;for(let o=0;o<20;o++){let i=KR(t);if(i.applied===0)break;n+=i.applied;for(let[s,c]of Object.entries(i.fixed))r[s]=(r[s]??0)+c}return{applied:n,fixed:r,remaining:GR(t)}},"repair");No();qi();Yn();Io();da();Ke();function XR(e){if(e===401)return"auth";if(e===404)return"not_found";if(e===429)return"rate_limited";return"network"}function Oa(e,t,r=fetch){let n=e.replace(/\/+$/,"");async function o(s,c={},l=!0){let u;try{u=await r(n+s,{...c,signal:c.signal??AbortSignal.timeout(15000),headers:{...c.body!=null?{"content-type":"application/json"}:{},...l?{authorization:`Bearer ${t}`}:{},...c.headers}})}catch(_){throw new T("network",`inbox host unreachable: ${_.message}`)}let f=await u.json().catch(()=>null);if(!u.ok)throw new T(XR(u.status),`inbox host: ${f?.error??`HTTP ${u.status}`}`);return f}let i=(s)=>`/v1/inbox/${encodeURIComponent(s)}`;return{async register(s,c){await o(i(s),{method:"PUT",body:JSON.stringify(c)})},async unregister(s){return(await o(i(s),{method:"DELETE"})).deleted},async listEnvelopes(s,c,l){return(await o(`${i(s)}/envelopes?after_id=${c}&limit=${l}`)).rows},async ackEnvelopes(s,c){if(c.length===0)return 0;return(await o(`${i(s)}/envelopes`,{method:"DELETE",body:JSON.stringify({ids:c})})).deleted},async stats(s){return o(`${i(s)}/stats`)},async health(){return o("/health",{},!1)},async ownerHealth(){return o("/owner/health")}}}Ke();async function uw(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 T("invalid_input",c.message||"invalid Edge endpoint")}let o=t.trim();if(!o)throw new T("invalid_input","owner token is required");let i=Oa(n,o),s=r==="edge"?await i.ownerHealth():await i.health();if(!s.ok)throw new T("network",`${r==="edge"?"Edge":"Inbox host"} at ${n} is not healthy`);if(r==="edge"&&s.version!==xn)throw new T("conflict",`Edge version ${s.version??"unknown"} is incompatible; expected ${xn}`);return{endpoint:n,token:o,version:s.version,capabilities:r==="edge"?["inbox","room"]:["inbox"]}}var Uu=15000,Cw=2000,$r=self.location.origin,Ze=null,Bo=null;function Iw(){let e=St();if(Bo?.db!==e)Bo?.dispose(),Bo=kb(e);return Bo}var sr={state:"booting",paired:!1,node:null};function Bi(e){self.postMessage(e)}function fr(e){sr={...sr,...e,dataVersion:Ze?Ot(Ze)?.dataVersion??2:void 0},Bi({event:"status",status:sr})}function St(){if(!Ze)throw new T("network",kn("本地副本未就绪"));return Ze}var io=null,Ia=null,Na=!1,Bu=new Set;function Pw(e){let t=new io.OpfsSAHPoolDb("/"+e);return{db:new cu(t),close:()=>t.close()}}function qw(){let e=My((n,o)=>{if(!o&&!io.getFileNames().includes("/"+n))throw Error("已选择的本地数据库缺失");return Pw(n)});Ia=e;let t=e.db;Ai(t),Ze=t;let r=lT();Rd(t,{app:"web",platform:r,form:"browser",defaultLabel:uT(r)})}function lT(){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 uT(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 dT=(async()=>{io=await(await Zy()).installOpfsSAHPoolVfs({name:"metahub-replica"}),qw();let t=Ze,r=Je(t),n=Pt(t,$r)?.token!=null,o=Pa(t);if(o)qa();let i=!!t.query("SELECT 1 FROM meta WHERE key='sync_v2_checkpoint'").get();fr({state:"ready",node:r,paired:n,bucketDirty:o,checkpointInstalled:i,upgradeBuckets:ou(t)})})().catch((e)=>{throw fr({state:"error",error:e instanceof Error?e.message:String(e)}),e}),un=null,ju=new Set;function pT(e){if(Pt(e,$r)?.token!=null)return!0;return Ft(e).some((t)=>t.enabled===1&&(t.kind==="s3"||t.kind==="room"))}function Rn(e){return Ft(e).filter((t)=>t.enabled===1&&t.kind==="s3")}function fT(e){return Ft(e).filter((t)=>t.enabled===1&&t.kind==="room")}async function Vu(e,t){let r=await iu(t).catch(()=>{return});if(r)return new Uint8Array(r.bytes);for(let n of Rn(St())){if(!n.config)continue;let o=await hl(JSON.parse(n.config),t).catch(()=>null);if(o&&await Lo(o,t))return new Uint8Array(o)}return null}ey(Vu);$_(Vu);function Pa(e){let t=Je(e);return Rn(e).some((r)=>Lt(e,Ts(e,r.url,r.push_cursor),{onlyNode:t,limit:1}).changes.length>0)}var hT=25,Lw=1e4,jo=null;function qa(){if(jo)return;jo=setTimeout(()=>{if(jo=null,navigator.onLine!==!1)so(!0)},Lw)}function Hu(){if(!jo)return;clearTimeout(jo),jo=null}function $w(){let e=Ze;if(!e)return;let t=Rn(e).length>0&&Pa(e);if(fr({bucketDirty:t,bucketError:void 0}),t)qa();else Hu()}function gT(e,t){e.query(`UPDATE peers SET
583
635
  pull_cursor = ?,
584
636
  push_cursor = ?,
585
637
  token = ?,
@@ -592,4 +644,4 @@ if(L instanceof ArrayBuffer)L=new Uint8Array(L);else if(L instanceof Function)re
592
644
  last_error = ?,
593
645
  kind = ?,
594
646
  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 dk(e){let t=Cr(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=Cr(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 Cr(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 Cn(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&&Cr(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 P_(){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(P_,Ro)}}setTimeout(P_,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}}async function D_(){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}}}var _k={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:D_,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 D_(),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 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 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)It(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)It(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)=>Im(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)=>Is(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 Cr(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 Cn(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 Cn(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{O_?.close()}catch{}return ke=null,await zc?.wipeFiles(),C_(),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})},yk=/^(create|update|delete|move|duplicate|revert|add|remove|set|put)/,Vi=null;function bk(){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=_k[r];if(!o)throw new H("invalid_input",`unknown op: ${r}`);let s=await o(...n??[]);if(Ji({id:t,ok:!0,result:s}),yk.test(r))lk(),bk()}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}})}};
647
+ 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 mT(e){let t=Rn(e);if(!t.length)return;let r;try{r=await _a()}catch{return}for(let n of r){let o=!1;for(let i of t){if(!i.config)continue;try{await Um(JSON.parse(i.config),n.hash,new Uint8Array(n.bytes),{db:e}),o=!0;break}catch{}}if(o)await Wy(n.hash,n.bytes,n.content_type).catch(()=>{}),await jy(n.hash).catch(()=>{})}}async function so(e=!1){if(!Ze||Na)return{pushed:0,pulled:0,ok:!0};let t=Ze;if(!pT(t))return{pushed:0,pulled:0,ok:!0};if(un)return un;return un=(async()=>{fr({syncing:!0});let r=t.query("SELECT MAX(rowid) AS m FROM crdt_changes").get().m??0,n=0,o=0,i=[],s=[],c=Rn(t).length>0;if(c&&e)fr({bucketSyncing:!0,bucketError:void 0});let l=!1;if(Pt(t,$r)?.token!=null)try{let E=0;for(;;){let g=Pt(t,$r)?.pull_cursor??0,A=await Os(t,$r,{pullLimit:Cw});if(n+=A.pushed,o+=A.pulled,E+=A.received??A.pulled,(A.received??A.pulled)<Cw)break;if((Pt(t,$r)?.pull_cursor??0)===g)break;fr({state:"hydrating",hydrated:E})}l=!0}catch(E){i.push(`server: ${E instanceof Error?E.message:String(E)}`)}let u=[];for(let E of Rn(t)){let g=l&&!e&&ju.has(E.url),A=await eu(t,E.url,{storage:{minPushChanges:hT,maxPushAgeMs:Lw,forcePush:e,pull:!g}});if(A.ok){if(n+=A.pushed??0,o+=A.pulled??0,!g)ju.add(E.url)}else{if(A.code==="upgrade_required"||A.code==="rebootstrap_required")u.push(E.url);let L=`${E.label??E.url}: ${A.error}`;i.push(L),s.push(L)}}for(let E of fT(t)){let g=await eu(t,E.url);if(g.ok)n+=g.pushed??0,o+=g.pulled??0;else i.push(`${E.label??E.url}: ${g.error}`)}if(!l&&c&&!s.length)await mT(t);await qo(t);let f=c?Pa(t):!1;if(f&&s.length===0)qa();else Hu();let _=t.query("SELECT DISTINCT dataset, row_id FROM crdt_changes WHERE rowid > ?").all(r);if(fr({state:"ready",hydrated:void 0,lastSync:{at:Date.now(),ok:i.length===0,pushed:n,pulled:o,error:i.join("; ")||void 0},bucketDirty:f,bucketSyncing:!1,syncing:!1,recoveryRequired:u,upgradeBuckets:ou(t),bucketError:s.join("; ")||void 0}),_.length||n)Bi({event:"synced",datasets:[...new Set(_.map((E)=>E.dataset))],rowIds:_.map((E)=>E.row_id),pushed:n,pulled:o});return{pushed:n,pulled:o,ok:i.length===0}})().finally(()=>{if(sr.syncing)fr({syncing:!1});if(Ze&&Rn(Ze).length>0&&!sr.bucketSyncing)if(Pa(Ze)&&!sr.bucketError)qa();else Hu();un=null}),un}var _T=150000,Ui=Uu,yT=180000;function bT(){if(!Ze)return!1;if(Pt(Ze,$r)?.token!=null)return!1;return Ft(Ze).some((e)=>e.enabled===1&&(e.kind==="s3"||e.kind==="room"))}async function Mw(){try{if(navigator.onLine!==!1&&bT()){let e=await so();Ui=e.pushed>0||e.pulled>0?Uu:Math.min(Ui*2,_T)}else Ui=Uu}finally{setTimeout(Mw,Ui)}}setTimeout(Mw,Ui);async function wT(e){let t=St(),r={code:e,node_id:Je(t),grant:Wt(32)},n=await fetch(new URL(Qg,$r),{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(r)});if(!n.ok)throw new T(n.status===401||n.status===403?"auth":"network",`pairing failed: ${n.status} ${await n.text()}`);let o=await n.json();return ha(t,{url:$r,token:o.grant,node_id:o.node_id,label:"server"}),fr({paired:!0}),so(),{node_id:o.node_id}}function vT(){let e=Jt(St(),$r);return fr({paired:!1}),{ok:e}}async function Nw(){let e=St(),t=Aa(e),r=Ft(e).filter((n)=>n.kind==="room"&&n.config).map((n)=>{let o=JSON.parse(n.config);return{slug:o.slug,url:Qn(o),status:n.last_status,lastSuccessAt:n.last_success_at,error:n.last_error}});if(!t)return{configured:!1,expectedVersion:xn,aligned:!1,reachable:!1,managed:!1,rooms:r,defaults:null,pending:null};try{let n=await Oa(t.endpoint,t.token).ownerHealth();return{configured:!0,endpoint:t.endpoint,capabilities:Fi(t),version:n.version??null,expectedVersion:xn,aligned:n.version===xn,reachable:n.ok,managed:!1,rooms:r,defaults:null,pending:null}}catch(n){return{configured:!0,endpoint:t.endpoint,capabilities:Fi(t),version:null,expectedVersion:xn,aligned:!1,reachable:!1,error:n.message,managed:!1,rooms:r,defaults:null,pending:null}}}var ET={applyLocale:(e)=>($b(e),{ok:!0}),status:()=>sr,pair:(e)=>wT(e),unpair:()=>vT(),sync:()=>so(!0).then(()=>sr.lastSync),saveVersionDraft:(e)=>wd(St(),e),recoveryItems:()=>ru(St()),resolveRecoveryItem:(e,t)=>{if(t!=="copy"&&t!=="discard")throw new T("invalid_input","Invalid recovery action");let r=Ny(St(),e,t);if(t==="copy")$w(),Wu();return r},rebuildReplica:async(e)=>{Na=!0;try{if(await Promise.allSettled([...Bu]),un)await un;let t=await Vy(St(),e,{reserve:async()=>{await io.reserveMinimumCapacity(io.getFileCount()+8)},open:Pw,bytes:async(r)=>io.exportFile("/"+r),activate:(r)=>{let n=Ia,o=Bo;Bo=null,Ze=r.db,Ia=r;try{o?.dispose()}catch(i){console.warn("Retired replica service cleanup failed",i)}try{n?.close()}catch(i){console.warn("Retired database cleanup failed",i)}}},()=>fr({syncing:!0}));return ju.clear(),fr({state:"ready",node:Je(St()),paired:!!Pt(St(),$r)?.token,lastSync:void 0,bucketDirty:!0,bucketError:void 0,recoveryRequired:[],upgradeBuckets:[],checkpointInstalled:!0}),Bi({event:"synced",datasets:["documents","doc_blocks","databases","records"],rowIds:[],pushed:0,pulled:0}),Wu(),t}finally{Na=!1,fr({syncing:!1})}},addStorageReplica:async(e,t)=>{let r=St(),n={publish:!0,priority:10,...e};if(n.encrypt)n.masterKey=await _l($t(n),n,t)??void 0;let o=So(n.endpoint,n.bucket,n.prefix);if(un)await un;let i=Pt(r,o);if(ga(r,{url:o,config:n,label:n.bucket}),ja(r,o),await so(!0),sr.bucketError&&(sr.dataVersion??2)<=vr.maxSupportedDataVersion&&!sr.recoveryRequired?.includes(o)){if(r.query("DELETE FROM meta WHERE key='sync_version_pending_join' AND value=?").run(o),i)gT(r,i);else Jt(r,o);throw new T("network",`storage peer first sync failed: ${sr.bucketError}`)}return{url:o,lastSync:sr.lastSync}},removeStorageReplica:(e)=>({ok:Jt(St(),e)}),storagePeerConfig:(e)=>{let t=Pt(Ze,e);return t?.config?JSON.parse(t.config):null},dataMap:()=>zb(St()),listStoragePeers:()=>Ft(Ze).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:Nw,connectEdge:async(e,t)=>{let r=await uw(e,t,"edge");return Nu(St(),{endpoint:r.endpoint,token:r.token,capabilities:r.capabilities,deployedVersion:r.version}),{...await Nw(),status:"connected",wired:[],warnings:[]}},disconnectEdge:()=>{let e=St();if(Ft(e).some((t)=>t.kind==="room"))throw new T("conflict",kn("请先撤销所有 Edge Room 再断开"));return Nu(e,null),{ok:!0}},listLocalShares:(e)=>{let t=St();return(e?Pl(t,e):Nl(t)).map((n)=>{let o=Pt(t,`room://${n.slug}`),i=o?.config?JSON.parse(o.config):null,s=i?.lifecycle??"active",c=i&&s==="active"?Qn(i):void 0,l=n.kind==="site"?to(t,n.target_id):null;return{slug:n.slug,kind:n.kind,target_id:n.target_id,title:l?.title||l?.name||n.target_id,permission:n.permission,transport:"server",source:i?s==="cleanup_pending"?"Edge Room(撤销待确认)":"Edge Room":"本机",sourceKind:i?"room":"server",hosting:i?"room":"server",...i?{lifecycle:s}:{},expiresAt:n.expires_at,hasPassword:!!n.pw_hash,url:c}})},createLocalShare:async(e)=>{let t=St();if(e.kind!=="site"||e.hosting!=="room")throw new T("invalid_input",kn("此设备不驻留在线托管,目前仅支持通过 Edge 发布站点"));let r=Aa(t);if(!r)throw new T("invalid_input",kn("请先连接 Edge"));if(!Fi(r).includes("room"))throw new T("conflict",kn("当前 Edge 仅支持 inbox,不支持 Room 托管"));let n=to(t,e.ref),o=e.password?await ql(e.password):null,i=Il(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 s=await ny(t,i,r,Vu),c=Pi(t,{siteId:n.id,audience:"link",hosting:"edge",targetRef:i.slug,canonicalUrl:s.url,policy:{permission:i.permission,hasPassword:!!i.pw_hash,expiresAt:i.expires_at}});return ir(t,{channelId:c.id,status:"ready",lastVerifiedAt:Date.now()}),{slug:i.slug,kind:"site",permission:i.permission,transport:"server",hosting:"room",url:s.url,expiresAt:i.expires_at,source:"Edge Room"}}catch(s){if(await Ii(t,i.slug)!=="cleanup_pending")qr(t,i.slug);throw s}},revokeLocalShare:async(e)=>{let t=St();if(!Hr(t,e))return{ok:!1,status:"not_found"};let r=Rr(t).filter((i)=>i.audience==="link"&&i.target_ref===e&&i.desired_state==="active");for(let i of r)cn(t,i.id,"revoked");if(await Ii(t,e)==="cleanup_pending"){for(let i of r)ir(t,{channelId:i.id,status:"cleanup_pending",lastError:"Edge 尚未确认销毁 Room"});return{ok:!1,status:"cleanup_pending"}}let o=qr(t,e);for(let i of r)ir(t,{channelId:i.id,status:"revoked",lastVerifiedAt:Date.now()});return{ok:o,status:"revoked"}},renewLocalShare:async(e,t)=>{let r=St();await Promise.resolve().then(() => Ow());return Aw(r,e,void 0,t)},...xb(Iw),...Object.fromEntries(["listDocumentRevisions","documentAtVersion","revertDocument"].map((e)=>[e,async(t,...r)=>(await Uy(St(),t),Iw().dispatchRpc(e,[t,...r]))])),repairClock:()=>lw(Ze),listAuditEntries:(e)=>Qb(Ze,e??{}),auditEntryDetail:(e)=>tw(Ze,e),revertChangeGroup:(e)=>rw(Ze,e),siteFile:async(e,t)=>{if((sr.lastSync?.at?Date.now()-sr.lastSync.at:1/0)>yT)await so(!0).catch(()=>{});let n=Ze,o;try{o=to(n,e)}catch{return null}let i=ly(n,o.id,t,{spa:o.spa===1});if(!i)return null;return{...i.row,status:i.status,public:xy(n,o).serving}},blobBytes:async(e)=>{let t=await iu(e).catch(()=>{return});if(t)return t.bytes;for(let r of Rn(Ze)){if(!r.config)continue;try{let n=await hl(JSON.parse(r.config),e);if(n&&await Lo(n,e))return new Uint8Array(n).buffer}catch{}}return null},blobRefs:()=>[...U_(Ze)],listSites:()=>{let e=by(Ze);return cy(Ze).map((t)=>({...t,file_count:e.get(t.id)??0}))},listSiteFiles:(e)=>uy(Ze,e),createSite:(e)=>{if(e.visibility==="public")throw new T("invalid_input",kn("此浏览器通过同步存储桶交换数据、不驻留在线;请在在线主节点管理公开发布"));return{...fy(Ze,e),file_count:0}},updateSite:(e,t)=>{if(t.visibility==="public")throw new T("invalid_input",kn("此浏览器通过同步存储桶交换数据、不驻留在线;请在在线主节点管理公开发布"));return{...Ey(Ze,e,t),file_count:wy(Ze,e)}},deleteSite:async(e)=>{let t=Sy(Ze,e);return await qo(Ze),{ok:t}},getSiteGrants:(e)=>({grants:an(to(Ze,e).public_grants)}),setSiteGrants:(e,t)=>{let r=to(Ze,e),n=hy(Ze,r.id,t.tables.length?t:null);return vy(Ze,r.id,an(n.public_grants)),{grants:an(n.public_grants)}},siteHosting:()=>({publicBaseUrl:null,scope:null,node:Je(Ze),pendingRollbacks:[],publishedSites:[],channels:Yl(Ze)}),revokeSiteChannel:async(e)=>{let t=St(),{needsReconcile:r}=Ub(t,e);if(r)await qo(t);let n=Yl(t).find((o)=>o.id===e);if(!n)throw new T("not_found",`no such site channel: ${e}`);return n},putSiteFile:(e,t,r,n)=>{let{content:o,...i}=_y(Ze,e,t,{data:r,contentType:n});return{...i,size:dy(Ze,{encoding:i.encoding,content:o})}},deleteSiteFile:(e,t)=>({ok:yy(Ze,e,t)}),reset:async()=>{if(Ze)Qt(Ze);try{Ia?.close()}catch{}return Ze=null,await io?.wipeFiles(),qw(),fr({state:"ready",paired:!1,node:Je(St()),checkpointInstalled:!1,upgradeBuckets:[],recoveryRequired:[],hydrated:void 0,lastSync:void 0}),{ok:!0}},search:(e,t)=>Li(Ze,e,{limit:t}),querySearch:(e,t)=>Ra(Ze,e,t)},ST=/^(create|update|delete|move|duplicate|revert|add|remove|set|put)/,Ca=null;function Wu(){if(Ca)clearTimeout(Ca);Ca=setTimeout(()=>{if(Ca=null,navigator.onLine!==!1)so()},800)}self.onmessage=async(e)=>{let{id:t,op:r,args:n}=e.data;try{await dT;let o=ET[r];if(!o)throw new T("invalid_input",`unknown op: ${r}`);if(Na)throw new T("busy","正在重建本地副本");let i=Promise.resolve(o(...n??[]));if(r!=="rebuildReplica")Bu.add(i);let s;try{s=await i}finally{Bu.delete(i)}if(Bi({id:t,ok:!0,result:s}),ST.test(r))$w(),Wu()}catch(o){let i=o instanceof Error?o.message:String(o),s=pn(o)??void 0;Bi({id:t,ok:!1,error:{message:i,code:s}})}};