@forsion/extend 0.8.1 → 0.8.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/desktop.mjs CHANGED
@@ -1,7 +1,7 @@
1
- function Jn(t,e){if(typeof e!="string"||!e.startsWith("/"))return null;let n=String(t||"").replace(/\/+$/,"").replace(/\/api$/,"");if(!n)return null;let r,s;try{r=new URL(n),s=new URL(n+"/api"+e)}catch{return null}return r.protocol!=="http:"&&r.protocol!=="https:"||s.origin!==r.origin||!s.pathname.startsWith("/api/")?null:s.toString()}async function ge(t,e,n,r,s=6e4){let o=await fetch(t.base+n,{method:e,headers:{"Content-Type":"application/json","X-Project-Source":"connect",...t.token?{Authorization:`Bearer ${t.token}`}:{}},body:r===void 0?void 0:JSON.stringify(r),signal:AbortSignal.timeout(s)}),a=await o.json().catch(()=>({}));return{status:o.status,json:a}}import{readdirSync as Os,lstatSync as Us,readFileSync as Kt,writeFileSync as Fs,realpathSync as Kn}from"node:fs";import{join as Zt,extname as js,sep as Ls}from"node:path";var Xt=300,Xn=5*1024*1024,Zn=20*1024*1024,Hs=50*1024*1024,zs=new Set(["node_modules"]),qs=new Set([".ts",".tsx",".jsx",".mts",".cts"]);function Qn(t,e){let n=[],r=0,s=(o,a)=>{for(let i of Os(o)){if(i.startsWith("."))continue;let l=Zt(o,i),h;try{h=Us(l)}catch{continue}if(h.isSymbolicLink())continue;let d=a?`${a}/${i}`:i;if(h.isDirectory()){zs.has(i)||s(l,d);continue}if(!h.isFile()||i.endsWith(".d.ts"))continue;if(n.length>=Xt)throw new Error(`\u6587\u4EF6\u6570\u8D85\u8FC7 ${Xt}\uFF0C\u8BF7\u7CBE\u7B80\u9879\u76EE\uFF08node_modules \u4E0E\u9690\u85CF\u6587\u4EF6\u5DF2\u81EA\u52A8\u8DF3\u8FC7\uFF09`);let f=js(i).toLowerCase(),u,g=e.mimeOf(f)??"application/octet-stream";if(qs.has(f)){let S=e.transpile(Kt(l,"utf8"),f,d);u=Buffer.from(S??"","utf8"),g="text/javascript"}else u=Kt(l);if(u.length>Xn)throw new Error(`\u5355\u6587\u4EF6\u8D85\u8FC7 5MB\uFF1A${d}`);if(r+=u.length,r>Zn)throw new Error("\u9879\u76EE\u603B\u5927\u5C0F\u8D85\u8FC7 20MB\uFF0C\u65E0\u6CD5\u53D1\u5E03");n.push({path:d,content_b64:u.toString("base64"),content_type:g,size:u.length})}};if(s(t,""),!n.length)throw new Error("\u9879\u76EE\u4E3A\u7A7A\uFF0C\u6CA1\u6709\u53EF\u53D1\u5E03\u7684\u6587\u4EF6");return{files:n,totalBytes:r}}var er=".forsion-connect.json";function tr(t){try{return JSON.parse(Kt(Zt(t,er),"utf8"))}catch{return{}}}function nr(t,e){try{Fs(Zt(t,er),JSON.stringify(e,null,2)+`
2
- `,"utf8")}catch{}}function rr(t){let e={"/__forsion/chat":{method:"POST",path:"/api/chat/completions",auth:!0},"/__forsion/images":{method:"POST",path:"/api/images/generations",auth:!0},"/__forsion/user":{method:"GET",path:"/api/brain/users/me",auth:!0},"/__forsion/models":{method:"GET",path:"/api/models",auth:!1},"/__forsion/config":{method:"GET",path:"/api/connect/config",auth:!1},"/__forsion/agent":{method:"POST",path:"/api/agent/runs",auth:!0,agentRun:!0}};function n(r){if(e[r])return e[r];let s="/__forsion/agent-events/";if(r.startsWith(s)){let o=r.slice(s.length);if(/^[A-Za-z0-9-]{1,64}$/.test(o))return{method:"GET",path:`/api/agent/runs/${o}/events`,auth:!0,timeoutMs:9e5}}}return async(r,s)=>{let[o,a]=(r.url||"").split("?"),i=(S,x)=>{s.headersSent||(s.statusCode=S,s.setHeader("Content-Type","application/json")),s.end(JSON.stringify({detail:x}))},l=n(o);if(!l)return i(404,"unknown connect endpoint");if((r.method||"GET")!==l.method)return i(405,"method not allowed");let h="",d="";try{({base:h,token:d}=await t())}catch{}if(!h)return i(502,"\u672A\u914D\u7F6E Forsion \u4E91\u7AEF\u5730\u5740");if(l.auth&&!d)return i(401,"\u8BF7\u5148\u5728 Forsion Desktop \u4E2D\u767B\u5F55 Forsion \u8D26\u53F7");let f;if(l.method==="POST"){let S=[],x=0;try{for await(let w of r){if(x+=w.length,x>Hs)return r.destroy(),i(413,"\u8BF7\u6C42\u4F53\u8FC7\u5927");S.push(w)}}catch(w){return i(400,`\u8BF7\u6C42\u4F53\u8BFB\u53D6\u5931\u8D25\uFF1A${w?.message||String(w)}`)}f=Buffer.concat(S)}if(l.agentRun){let S;try{S=JSON.parse((f||Buffer.alloc(0)).toString("utf8")||"{}")}catch{return i(400,"agent \u8BF7\u6C42\u4F53\u5FC5\u987B\u662F JSON")}f=Buffer.from(JSON.stringify({session_id:typeof S.session_id=="string"?S.session_id:"",message:typeof S.message=="string"?S.message:"",app_id:"connect",agent_config:{}}))}let u=new AbortController,g=setTimeout(()=>u.abort(new Error("proxy timeout")),l.timeoutMs??3e5);r.on("close",()=>u.abort());try{let S=await fetch(h+l.path+(a?`?${a}`:""),{method:l.method,headers:{"Content-Type":"application/json","X-Project-Source":"connect",...d?{Authorization:`Bearer ${d}`}:{}},body:f&&f.length?new Uint8Array(f):void 0,signal:u.signal});if(s.statusCode=S.status,s.setHeader("Content-Type",S.headers.get("content-type")||"application/json"),s.setHeader("Cache-Control","no-store"),S.body)for await(let x of S.body)s.write(x);s.end()}catch(S){let x=`\u4E91\u7AEF\u8BF7\u6C42\u4E2D\u65AD\uFF1A${S?.message||String(S)}`;if(s.headersSent){try{s.write(`data: ${JSON.stringify({error:x})}
1
+ function Ht(t,e){if(typeof e!="string"||!e.startsWith("/"))return null;let n=String(t||"").replace(/\/+$/,"").replace(/\/api$/,"");if(!n)return null;let r,s;try{r=new URL(n),s=new URL(n+"/api"+e)}catch{return null}return r.protocol!=="http:"&&r.protocol!=="https:"||s.origin!==r.origin||!s.pathname.startsWith("/api/")?null:s.toString()}var di=50*1024*1024,fi=new Set(["type","source","name","summary","githubRepoUrl","npmPackage","version","readme"]);function mi(t){if(!t||typeof t!="object")return null;let e=t;if(e.id!==void 0&&(typeof e.id!="string"||!/^[a-zA-Z0-9_-]{1,128}$/.test(e.id))||!e.fields||typeof e.fields!="object"||Array.isArray(e.fields))return null;let n=new FormData,r=0;for(let[s,i]of Object.entries(e.fields)){if(!fi.has(s)||typeof i!="string"||(r+=i.length,r>25e4)||e.id&&!["summary","version","readme"].includes(s))return null;n.append(s,i)}if(e.zip!==void 0){if(!e.zip||typeof e.zip.name!="string"||!/\.zip$/i.test(e.zip.name)||!(e.zip.data instanceof Uint8Array)||!e.zip.data.byteLength||e.zip.data.byteLength>di)return null;n.append("zip",new Blob([new Uint8Array(e.zip.data)],{type:"application/zip"}),e.zip.name.replace(/[\\/]/g,"_").slice(-255))}return{path:e.id?`/market/mine/${e.id}/update`:"/market/submit",body:n}}function dr(t){t.handle("cloud:marketSubmit",async(e,n)=>{if(!t.isTrustedSender(e))return{status:0,error:"untrusted"};let r=mi(n);if(!r)return{status:400,json:{error:"invalid_request"}};let{base:s,token:i}=await t.getCloud();if(!i)return{status:401,error:"not_signed_in"};let o=Ht(s,r.path);if(!o)return{status:0,error:"no_cloud_url"};try{let a=await fetch(o,{method:"POST",headers:{Authorization:`Bearer ${i}`},body:r.body,redirect:"error",signal:AbortSignal.timeout(12e4)});return{status:a.status,json:await a.json().catch(()=>null)}}catch(a){return{status:0,error:String(a?.message||a)}}})}async function we(t,e,n,r,s=6e4){let i=await fetch(t.base+n,{method:e,headers:{"Content-Type":"application/json","X-Project-Source":"connect",...t.token?{Authorization:`Bearer ${t.token}`}:{}},body:r===void 0?void 0:JSON.stringify(r),signal:AbortSignal.timeout(s)}),o=await i.json().catch(()=>({}));return{status:i.status,json:o}}import{readdirSync as hi,lstatSync as gi,readFileSync as gn,writeFileSync as pi,realpathSync as fr}from"node:fs";import{join as yn,extname as yi,sep as wi}from"node:path";var pn=300,mr=5*1024*1024,hr=20*1024*1024,bi=50*1024*1024,Si=new Set(["node_modules"]),Ei=new Set([".ts",".tsx",".jsx",".mts",".cts"]);function gr(t,e){let n=[],r=0,s=(i,o)=>{for(let a of hi(i)){if(a.startsWith("."))continue;let l=yn(i,a),d;try{d=gi(l)}catch{continue}if(d.isSymbolicLink())continue;let f=o?`${o}/${a}`:a;if(d.isDirectory()){Si.has(a)||s(l,f);continue}if(!d.isFile()||a.endsWith(".d.ts"))continue;if(n.length>=pn)throw new Error(`\u6587\u4EF6\u6570\u8D85\u8FC7 ${pn}\uFF0C\u8BF7\u7CBE\u7B80\u9879\u76EE\uFF08node_modules \u4E0E\u9690\u85CF\u6587\u4EF6\u5DF2\u81EA\u52A8\u8DF3\u8FC7\uFF09`);let m=yi(a).toLowerCase(),c,h=e.mimeOf(m)??"application/octet-stream";if(Ei.has(m)){let g=e.transpile(gn(l,"utf8"),m,f);c=Buffer.from(g??"","utf8"),h="text/javascript"}else c=gn(l);if(c.length>mr)throw new Error(`\u5355\u6587\u4EF6\u8D85\u8FC7 5MB\uFF1A${f}`);if(r+=c.length,r>hr)throw new Error("\u9879\u76EE\u603B\u5927\u5C0F\u8D85\u8FC7 20MB\uFF0C\u65E0\u6CD5\u53D1\u5E03");n.push({path:f,content_b64:c.toString("base64"),content_type:h,size:c.length})}};if(s(t,""),!n.length)throw new Error("\u9879\u76EE\u4E3A\u7A7A\uFF0C\u6CA1\u6709\u53EF\u53D1\u5E03\u7684\u6587\u4EF6");return{files:n,totalBytes:r}}var pr=".forsion-connect.json";function yr(t){try{return JSON.parse(gn(yn(t,pr),"utf8"))}catch{return{}}}function wr(t,e){try{pi(yn(t,pr),JSON.stringify(e,null,2)+`
2
+ `,"utf8")}catch{}}function br(t){let e={"/__forsion/chat":{method:"POST",path:"/api/chat/completions",auth:!0},"/__forsion/images":{method:"POST",path:"/api/images/generations",auth:!0},"/__forsion/user":{method:"GET",path:"/api/brain/users/me",auth:!0},"/__forsion/models":{method:"GET",path:"/api/models",auth:!1},"/__forsion/config":{method:"GET",path:"/api/connect/config",auth:!1},"/__forsion/agent":{method:"POST",path:"/api/agent/runs",auth:!0,agentRun:!0}};function n(r){if(e[r])return e[r];let s="/__forsion/agent-events/";if(r.startsWith(s)){let i=r.slice(s.length);if(/^[A-Za-z0-9-]{1,64}$/.test(i))return{method:"GET",path:`/api/agent/runs/${i}/events`,auth:!0,timeoutMs:9e5}}}return async(r,s)=>{let[i,o]=(r.url||"").split("?"),a=(g,S)=>{s.headersSent||(s.statusCode=g,s.setHeader("Content-Type","application/json")),s.end(JSON.stringify({detail:S}))},l=n(i);if(!l)return a(404,"unknown connect endpoint");if((r.method||"GET")!==l.method)return a(405,"method not allowed");let d="",f="";try{({base:d,token:f}=await t())}catch{}if(!d)return a(502,"\u672A\u914D\u7F6E Forsion \u4E91\u7AEF\u5730\u5740");if(l.auth&&!f)return a(401,"\u8BF7\u5148\u5728 Forsion Desktop \u4E2D\u767B\u5F55 Forsion \u8D26\u53F7");let m;if(l.method==="POST"){let g=[],S=0;try{for await(let y of r){if(S+=y.length,S>bi)return r.destroy(),a(413,"\u8BF7\u6C42\u4F53\u8FC7\u5927");g.push(y)}}catch(y){return a(400,`\u8BF7\u6C42\u4F53\u8BFB\u53D6\u5931\u8D25\uFF1A${y?.message||String(y)}`)}m=Buffer.concat(g)}if(l.agentRun){let g;try{g=JSON.parse((m||Buffer.alloc(0)).toString("utf8")||"{}")}catch{return a(400,"agent \u8BF7\u6C42\u4F53\u5FC5\u987B\u662F JSON")}m=Buffer.from(JSON.stringify({session_id:typeof g.session_id=="string"?g.session_id:"",message:typeof g.message=="string"?g.message:"",app_id:"connect",agent_config:{}}))}let c=new AbortController,h=setTimeout(()=>c.abort(new Error("proxy timeout")),l.timeoutMs??3e5);r.on("close",()=>c.abort());try{let g=await fetch(d+l.path+(o?`?${o}`:""),{method:l.method,headers:{"Content-Type":"application/json","X-Project-Source":"connect",...f?{Authorization:`Bearer ${f}`}:{}},body:m&&m.length?new Uint8Array(m):void 0,signal:c.signal});if(s.statusCode=g.status,s.setHeader("Content-Type",g.headers.get("content-type")||"application/json"),s.setHeader("Cache-Control","no-store"),g.body)for await(let S of g.body)s.write(S);s.end()}catch(g){let S=`\u4E91\u7AEF\u8BF7\u6C42\u4E2D\u65AD\uFF1A${g?.message||String(g)}`;if(s.headersSent){try{s.write(`data: ${JSON.stringify({error:S})}
3
3
 
4
- `)}catch{}s.end()}else i(502,x)}finally{clearTimeout(g)}}}var sr=`
4
+ `)}catch{}s.end()}else a(502,S)}finally{clearTimeout(h)}}}var Sr=`
5
5
  (function () {
6
6
  'use strict';
7
7
  if (window.forsion) return;
@@ -190,26 +190,92 @@ function Jn(t,e){if(typeof e!="string"||!e.startsWith("/"))return null;let n=Str
190
190
  ai: { chat: chat, agent: agentRun, generateImage: generateImage }
191
191
  };
192
192
  })();
193
- `,Bs=t=>({transpile:(e,n,r)=>t.transpileForServe(e,n,r),mimeOf:e=>t.mimeOf(e)});function Qt(t){let e=t;return typeof e.projectsRoot=="function"&&typeof e.transpileForServe=="function"&&typeof e.mimeOf=="function"&&typeof e.setPreviewHooks=="function"}function en(t){t.setPreviewHooks({sdkJs:sr,proxy:rr(()=>t.getCloud())}),t.handle("connect:meta",(e,n)=>typeof n=="string"&&n?tr(n):{}),t.handle("connect:list",async()=>{let e=await t.getCloud();if(!e.token)return{ok:!1,code:"not_logged_in",detail:"\u8BF7\u5148\u767B\u5F55 Forsion \u8D26\u53F7"};try{let{status:n,json:r}=await ge(e,"GET","/api/connect/apps");return n===401||n===403?{ok:!1,code:"not_logged_in",detail:"\u767B\u5F55\u5DF2\u8FC7\u671F,\u8BF7\u91CD\u65B0\u767B\u5F55"}:n!==200?{ok:!1,code:"error",detail:r?.detail||`HTTP ${n}`}:{ok:!0,base:e.base,...r}}catch(n){return{ok:!1,code:"error",detail:n?.message||String(n)}}}),t.handle("connect:publish",async(e,n)=>{if(!n||typeof n.dir!="string"||!n.dir||!n.name||!n.slug||!n.entry)return{ok:!1,code:"error",detail:"\u53C2\u6570\u4E0D\u5B8C\u6574"};let r;try{let o=Kn(t.projectsRoot());if(r=Kn(n.dir),r!==o&&!r.startsWith(o+Ls))return{ok:!1,code:"error",detail:"\u53EA\u80FD\u53D1\u5E03 Coding Space \u9879\u76EE\u76EE\u5F55"}}catch{return{ok:!1,code:"error",detail:"\u9879\u76EE\u76EE\u5F55\u4E0D\u5B58\u5728\u6216\u65E0\u6CD5\u8BBF\u95EE"}}let s=await t.getCloud();if(!s.token)return{ok:!1,code:"not_logged_in",detail:"\u8BF7\u5148\u767B\u5F55 Forsion \u8D26\u53F7"};try{let{files:o,totalBytes:a}=Qn(r,Bs(t));if(!o.some(h=>h.path===n.entry))return{ok:!1,code:"error",detail:`\u5165\u53E3\u6587\u4EF6\u4E0D\u5B58\u5728:${n.entry}`};let{status:i,json:l}=await ge(s,"POST","/api/connect/apps",{slug:n.slug,name:n.name,entry:n.entry,files:o},3e5);return i===401?{ok:!1,code:"not_logged_in",detail:"\u767B\u5F55\u5DF2\u8FC7\u671F,\u8BF7\u91CD\u65B0\u767B\u5F55"}:i!==200?{ok:!1,code:l?.code||"error",detail:l?.detail||`HTTP ${i}`,used:l?.used,limit:l?.limit}:(nr(r,{slug:String(l.slug)}),{ok:!0,slug:l.slug,handle:l.handle,url:`${s.base}${l.url}`,totalBytes:a})}catch(o){return{ok:!1,code:"error",detail:o?.message||String(o)}}}),t.handle("connect:unpublish",async(e,n)=>{if(!n||typeof n!="string")return{ok:!1,code:"error",detail:"\u53C2\u6570\u4E0D\u5B8C\u6574"};let r=await t.getCloud();if(!r.token)return{ok:!1,code:"not_logged_in",detail:"\u8BF7\u5148\u767B\u5F55 Forsion \u8D26\u53F7"};try{let{status:s,json:o}=await ge(r,"DELETE",`/api/connect/apps/${encodeURIComponent(n)}`);return s===401||s===403?{ok:!1,code:"not_logged_in",detail:"\u767B\u5F55\u5DF2\u8FC7\u671F,\u8BF7\u91CD\u65B0\u767B\u5F55"}:s!==200&&s!==404?{ok:!1,code:"error",detail:o?.detail||`HTTP ${s}`}:{ok:!0}}catch(s){return{ok:!1,code:"error",detail:s?.message||String(s)}}}),t.handle("connect:listingApply",async(e,n)=>{if(!n||typeof n.slug!="string"||!n.slug||typeof n.summary!="string"||!n.summary.trim())return{ok:!1,code:"error",detail:"\u53C2\u6570\u4E0D\u5B8C\u6574"};let r=await t.getCloud();if(!r.token)return{ok:!1,code:"not_logged_in",detail:"\u8BF7\u5148\u767B\u5F55 Forsion \u8D26\u53F7"};try{let{status:s,json:o}=await ge(r,"PUT",`/api/connect/apps/${encodeURIComponent(n.slug)}/listing`,{summary:n.summary});return s===401?{ok:!1,code:"not_logged_in",detail:"\u767B\u5F55\u5DF2\u8FC7\u671F,\u8BF7\u91CD\u65B0\u767B\u5F55"}:s!==200?{ok:!1,code:o?.code||"error",detail:o?.detail||`HTTP ${s}`}:{ok:!0,status:o.status}}catch(s){return{ok:!1,code:"error",detail:s?.message||String(s)}}}),t.handle("connect:listingWithdraw",async(e,n)=>{if(!n||typeof n!="string")return{ok:!1,code:"error",detail:"\u53C2\u6570\u4E0D\u5B8C\u6574"};let r=await t.getCloud();if(!r.token)return{ok:!1,code:"not_logged_in",detail:"\u8BF7\u5148\u767B\u5F55 Forsion \u8D26\u53F7"};try{let{status:s,json:o}=await ge(r,"DELETE",`/api/connect/apps/${encodeURIComponent(n)}/listing`);return s===401?{ok:!1,code:"not_logged_in",detail:"\u767B\u5F55\u5DF2\u8FC7\u671F,\u8BF7\u91CD\u65B0\u767B\u5F55"}:s!==200&&s!==404?{ok:!1,code:"error",detail:o?.detail||`HTTP ${s}`}:{ok:!0}}catch(s){return{ok:!1,code:"error",detail:s?.message||String(s)}}}),t.handle("connect:store",async()=>{let e=await t.getCloud();try{let{status:n,json:r}=await ge(e,"GET","/api/connect/store");return n!==200?{ok:!1,detail:r?.detail||`HTTP ${n}`}:{ok:!0,base:e.base,items:Array.isArray(r.items)?r.items:[]}}catch(n){return{ok:!1,detail:n?.message||String(n)}}}),t.log("[forsion-extend] connect handlers registered")}import{createHash as Ws}from"node:crypto";async function lt(t,e){if(!t||!e)return{status:"offline"};let n=t.replace(/\/+$/,"");try{let r=await fetch(`${n}/api/brain/users/me`,{headers:{Authorization:`Bearer ${e}`},signal:AbortSignal.timeout(5e3)});if(r.status===401||r.status===403)return{status:(r.headers.get("content-type")||"").includes("application/json")?"expired":"offline"};if(!r.ok)return{status:"offline"};let s=await r.json();if(!s)return{status:"offline"};let o=s.avatar||s.avatarUrl||s.avatar_url||void 0;return o&&/^\/(?!\/)/.test(o)&&(o=n+o),{status:"ok",user:{username:s.username||s.nickname||void 0,nickname:s.nickname||void 0,avatar:o,membershipTier:s.membershipTier||s.membership_tier||void 0}}}catch{return{status:"offline"}}}var or=t=>`${t.seq}:${t.hash}`,Vs=t=>Ws("sha256").update(t).digest("hex");function tn(t){if(t===null)return{baseSeq:0,baseHash:null};if(typeof t!="string")return;let e=t.indexOf(":"),n=Number(e===-1?t:t.slice(0,e));if(!Number.isInteger(n)||n<=0)return;let r=e===-1?"":t.slice(e+1);return{baseSeq:n,baseHash:/^[0-9a-f]{64}$/.test(r)?r:null}}function Tt(t){let e=t.baseUrl.replace(/\/+$/,""),n=s=>`${e}/api/remotesync/vaults/${encodeURIComponent(t.vault)}${s}`,r=async(s,o)=>{let a=t.getToken();if(!a)throw new Error("penzor-not-logged-in");let i=await fetch(s,{...o,headers:{...o.headers,Authorization:`Bearer ${a}`}});if(i.status===409){let l=await i.json().catch(()=>({}));throw new Error(`cas-conflict ${String(l.code??"")}: seq=${String(l.seq??"?")}`)}if(!i.ok){let l=await i.text().catch(()=>"");throw new Error(`penzor ${o.method??"GET"} ${i.status}: ${l.slice(0,200)}`)}return i};return{kind:"penzor",async walk(s){let o=await r(n("/manifest"),{method:"GET",signal:s}),{files:a}=await o.json();return a.map(i=>({key:i.path,size:i.size,mtimeMs:i.mtimeMs,id:or(i)}))},async readFile(s,o){let i=await(await r(n(`/file?path=${encodeURIComponent(s)}`),{method:"GET",signal:o})).json(),l=await fetch(i.url,{signal:o});if(!l.ok)throw new Error(`penzor blob GET ${l.status}: ${s}`);let h=Buffer.from(await l.arrayBuffer());if(Vs(h)!==i.hash)throw new Error(`penzor hash mismatch: ${s}`);return h},async writeFile(s,o,a,i,l){let h=tn(l),d=new URLSearchParams({path:s,mtimeMs:String(Math.floor(a)||0)});h&&(d.set("baseSeq",String(h.baseSeq)),h.baseHash&&d.set("baseHash",h.baseHash));let u=await(await r(n(`/file?${d.toString()}`),{method:"PUT",body:new Uint8Array(o),headers:{"Content-Type":"application/octet-stream"},signal:i})).json();return{key:s,size:u.size,mtimeMs:u.mtimeMs,id:or(u)}},async rm(s,o,a){let i=tn(a),l=new URLSearchParams({path:s});i&&i.baseSeq>0&&(l.set("baseSeq",String(i.baseSeq)),i.baseHash&&l.set("baseHash",i.baseHash)),await r(n(`/file?${l.toString()}`),{method:"DELETE",signal:o})},async check(){try{return await r(n("/manifest"),{method:"GET"}),{ok:!0}}catch(s){return{ok:!1,error:String(s?.message||s)}}}}}var xt="forsion-diagnostics",ar=50*1024*1024,ir=new Map;async function Ys(t,e){let n=ir.get(e);if(n)return{id:n};let r=await lt(t,e);if(r.status==="offline")return{error:"penzor-offline"};if(r.status!=="ok")return{error:"penzor-not-logged-in"};let s=r.user?.username?.trim();return s?(ir.set(e,s),{id:s}):{error:"penzor-auth-unverified"}}var nn=t=>typeof t.registerRemoteSyncBackend=="function"&&typeof t.readCreds=="function";function rn(t){t.registerRemoteSyncBackend("penzor",async e=>{let n=t.readCreds();if(!n.token||!n.cloudUrl)return{error:"penzor-not-logged-in"};let r=e?.vault,s=(typeof r=="string"?r:"default").trim()||"default";if(!/^[A-Za-z0-9_-]{1,64}$/.test(s)||s===xt)return{error:"penzor-bad-vault"};let o=await Ys(n.cloudUrl,n.token);if("error"in o)return o;let a=n.token;return{remote:Tt({baseUrl:n.cloudUrl,vault:s,getToken:()=>a}),fingerprint:`penzor:${n.cloudUrl.replace(/\/+$/,"")}|u:${o.id}|${s}`,maxFileBytes:ar}}),t.log('[forsion-extend] remote-sync backend "penzor" registered')}import{readFileSync as Gs,writeFileSync as Js,mkdirSync as Ks,chmodSync as Xs,renameSync as Zs}from"node:fs";import{join as Qs}from"node:path";function Te(t,e){try{let n=new URL(t);if(n.protocol!=="https:"&&n.protocol!=="http:")return null;let r=e.split(".")[1];if(!r)return null;let s=r.replace(/-/g,"+").replace(/_/g,"/"),o=Uint8Array.from(atob(s),l=>l.charCodeAt(0)),a=JSON.parse(new TextDecoder().decode(o)),i=a.userId??a.sub;return typeof i!="string"&&typeof i!="number"||!String(i).trim()?null:`${n.origin}${n.pathname.replace(/\/+$/,"")}::${String(i)}`}catch{return null}}function sn(t){try{let e=t.split(".")[1];if(!e)return null;let n=JSON.parse(Buffer.from(e,"base64url").toString("utf8"));return n&&typeof n=="object"?n:null}catch{return null}}function cr(t,e=Date.now()){let n=sn(t)?.iat;return typeof n=="number"?e-n*1e3:1/0}function eo(t,e=Date.now()){let n=sn(t)?.exp;return typeof n=="number"?n*1e3-e:1/0}var to=36e5;function ur(t,e=Date.now()){return!!t&&cr(t,e)>=to}async function dr(t,e,n=8e3,r){if(!t||!e)return null;let s=t.replace(/\/+$/,"");try{let o=await fetch(`${s}/api/auth/refresh`,{method:"POST",headers:{Authorization:`Bearer ${e}`,...r?{"X-Forsion-Client":r}:{}},signal:AbortSignal.timeout(n)});if(!o.ok)return null;let a=await o.json().catch(()=>null),i=typeof a?.token=="string"?a.token:"";return i&&i!==e?i:null}catch{return null}}var At=(t,e)=>`${t.replace(/\/+$/,"")}\0${e}`,no=(t,e)=>new Promise((n,r)=>{let s=()=>{clearTimeout(o),r(new Error("Sign-in cancelled."))},o=setTimeout(()=>{e.removeEventListener("abort",s),n()},t);e.aborted?s():e.addEventListener("abort",s,{once:!0})});function fr(t){let e=()=>Qs(t.homeDir(),"auth-accounts.json"),n=(f,u)=>{Ks(t.homeDir(),{recursive:!0});let g=`${f}.tmp`;Js(g,JSON.stringify(u,null,2),{encoding:"utf8",mode:384}),Xs(g,384),Zs(g,f)},r=()=>{try{let f=JSON.parse(Gs(e(),"utf8"));return Array.isArray(f.accounts)?f.accounts.filter(u=>u&&typeof u.token=="string"&&u.id===Te(u.cloudUrl,u.token)):[]}catch{return[]}},s=(f,u)=>{let g=Te(f.cloudUrl||"",f.token||"");if(!g||!f.token||!f.cloudUrl)return;let S=r(),x=S.find(_=>_.id===g),w=sn(f.token),F={...x,id:g,cloudUrl:f.cloudUrl.replace(/\/+$/,""),token:f.token,username:u?.username||x?.username||w?.username,nickname:u?.nickname||x?.nickname};JSON.stringify(x)!==JSON.stringify(F)&&n(e(),{version:1,accounts:[...S.filter(_=>_.id!==g),F]})},o=()=>{let f=t.readCreds();s(f);let u=Te(f.cloudUrl,f.token);return r().map(({token:g,...S})=>({...S,active:S.id===u}))},a=f=>{let u=r().find(g=>g.id===f);if(!u)throw new Error("Account is no longer signed in. Sign in again.");return{cloudUrl:u.cloudUrl,token:u.token}},i=f=>{let u=Te(f.cloudUrl||"",f.token||"");u&&n(e(),{version:1,accounts:r().filter(g=>g.id!==u)})},l=null;return{rememberForsionAccount:s,forsionAccounts:o,savedForsionAccount:a,forgetForsionAccount:i,cancelForsionLogin:()=>{l?.abort(),l=null},forsionDeviceLogin:async(f,u,g)=>{if(l)throw new Error("A sign-in is already in progress.");if(!f)throw new Error("\u8BF7\u5148\u586B\u5199 Forsion \u4E91\u7AEF\u5730\u5740(\u6216\u8BBE\u7F6E\u73AF\u5883\u53D8\u91CF TANGU_CLOUD_URL)");let S=new AbortController;l=S;let x=()=>{if(S.signal.aborted||l!==S)throw new Error("Sign-in cancelled.")};try{let w=f.replace(/\/+$/,""),F;try{F=await fetch(`${w}/api/auth/cli/start`,{method:"POST",headers:{"Content-Type":"application/json"},body:"{}",signal:AbortSignal.any([S.signal,AbortSignal.timeout(15e3)])}).then(j=>j.json())}catch(j){throw new Error(`\u65E0\u6CD5\u8FDE\u63A5 ${w}:${j?.message||j}`)}if(x(),!F?.device_code)throw new Error("\u4E91\u7AEF\u4E0D\u652F\u6301 CLI \u767B\u5F55(/api/auth/cli/start \u8FD4\u56DE\u5F02\u5E38)");let _=F.verification_uri_complete||`${F.verification_uri}?code=${F.user_code}`,A=new URL(`${w}/auth`);A.searchParams.set("logout","1"),A.searchParams.set("app","forsion-desktop"),A.searchParams.set("redirect",_);let U=A.toString();u?.({url:U,userCode:String(F.user_code||"")}),t.openExternal(U);let M=Date.now()+(F.expires_in||600)*1e3,B=(F.interval||2)*1e3;for(;Date.now()<M;){await no(B,S.signal),x();let j=null;try{j=await fetch(`${w}/api/auth/cli/poll`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({device_code:F.device_code}),signal:AbortSignal.any([S.signal,AbortSignal.timeout(15e3)])})}catch{x();continue}if(x(),j.status===410)throw new Error("\u767B\u5F55\u7801\u5DF2\u8FC7\u671F,\u8BF7\u91CD\u65B0\u53D1\u8D77\u767B\u5F55");let K=await j.json().catch(()=>({status:"pending"}));if(x(),K.status==="approved"&&K.token){let se={cloudUrl:w,token:K.token};return await g(se,x),x(),{token:K.token,cloudUrl:w}}}throw new Error("\u767B\u5F55\u8D85\u65F6,\u8BF7\u91CD\u8BD5")}finally{l===S&&(l=null)}},readAccounts:r}}var hr=["homeDir","appVersion","broadcast","accountBackendState","accountTransition","accountCommit","accountClear","writeCreds","onExternalCredsChange","setTokenRefresher","readCreds"],on=t=>hr.every(e=>typeof t[e]=="function");function an(t){let e={ok:!1,error:"untrusted"},n={loggedIn:!1,error:"untrusted"},r=fr(t),s=0,o=()=>{let i=t.readCreds();return At(i.cloudUrl,i.token)},a=null;t.handle("auth:status",async i=>{if(!t.isTrustedSender(i))return n;let l=s,h=o(),{base:d}=await t.getCloud(),f=t.readCreds().token,u=f?await lt(d,f):null,g=await t.accountBackendState(),{base:S}=await t.getCloud(),x=t.readCreds(),w=At(S,x.token)!==At(d,f),F=At(d,f);!w&&u?.status==="ok"&&u.user&&(a={key:F,user:u.user},r.rememberForsionAccount({...x,cloudUrl:d},u.user));let _=w?void 0:u?.status==="ok"?u.user:u?.status==="offline"&&a?.key===F?a.user:void 0;if(w)return{loggedIn:!!x.token,tokenValid:null,cloudUrl:S,accountId:Te(S,x.token),username:null,nickname:null,avatar:null,membershipTier:null,tokenSource:x.token?"tangu-login":null,backendState:g};if(u?.status==="expired"){await t.accountTransition(async()=>{if(l!==s||o()!==h)return;let U=()=>{if(l!==s||o()!==h)throw lr};try{await t.accountClear(U,()=>{t.log("[auth] token \u5DF2\u5931\u6548(\u670D\u52A1\u7AEF 401/403),\u81EA\u52A8\u767B\u51FA"),++s,r.cancelForsionLogin(),r.forgetForsionAccount(t.readCreds()),a=null})}catch(M){if(M!==lr)throw M}});let A=t.readCreds();return{loggedIn:!!A.token,tokenValid:null,cloudUrl:A.cloudUrl||d,accountId:Te(A.cloudUrl||d,A.token),username:null,nickname:null,avatar:null,membershipTier:null,tokenSource:A.token?"tangu-login":null,backendState:g}}return{loggedIn:!!f,tokenValid:u&&u.status==="ok"?!0:null,cloudUrl:d,accountId:Te(d,f),username:_?.username||null,nickname:_?.nickname||null,avatar:_?.avatar||null,membershipTier:_?.membershipTier||null,tokenSource:f?"tangu-login":null,backendState:g}}),t.handle("auth:accounts",i=>t.isTrustedSender(i)?r.forsionAccounts():[]),t.handle("auth:switchAccount",async(i,l)=>{if(!t.isTrustedSender(i))return e;if(typeof l!="string")throw new Error("Invalid account.");let h=++s;return r.cancelForsionLogin(),t.accountTransition(async()=>{let d=r.savedForsionAccount(l);return await t.accountCommit(d,()=>{if(h!==s)throw new Error("Account switch cancelled.")},()=>{r.rememberForsionAccount(d),a=null}),{ok:!0,cloudUrl:d.cloudUrl||""}})}),t.handle("auth:forsionLogin",async(i,l)=>{if(!t.isTrustedSender(i))return e;let h=++s;r.cancelForsionLogin();let{base:d}=await t.getCloud();if(h!==s)throw new Error("Sign-in cancelled.");let f=(l||d||"").trim();return{ok:!0,cloudUrl:(await r.forsionDeviceLogin(f,g=>t.broadcast("auth:device",g),(g,S)=>t.accountTransition(()=>t.accountCommit(g,()=>{if(S(),h!==s)throw new Error("Sign-in cancelled.")},()=>{r.rememberForsionAccount(g),a=null})))).cloudUrl}}),t.handle("auth:logout",async i=>t.isTrustedSender(i)?(++s,r.cancelForsionLogin(),t.accountTransition(async()=>{let{base:l}=await t.getCloud(),h=t.readCreds();return await t.accountClear(void 0,()=>{r.forgetForsionAccount(h),a=null,l&&h.token&&fetch(`${l}/api/auth/logout`,{method:"POST",headers:{Authorization:`Bearer ${h.token}`},signal:AbortSignal.timeout(5e3)}).catch(()=>{})}),{ok:!0}})):e),t.onExternalCredsChange(({previous:i,current:l})=>{++s,r.cancelForsionLogin(),i.token&&!l.token&&r.forgetForsionAccount(i),a=null,r.rememberForsionAccount(l)}),t.setTokenRefresher(async i=>{let l=s,h=o(),d=t.readCreds().token;if(!ur(d))return;let{base:f}=await t.getCloud(),u=await dr(f,d,i,`desktop/${t.appVersion()}`);if(!u){t.log("[auth] \u6ED1\u52A8\u7EED\u671F\u672A\u6210\u529F(\u79BB\u7EBF/\u8001\u7248\u672C server/\u8FD9\u679A\u5DF2\u5931\u6548),\u7EE7\u7EED\u7528\u65E7 token");return}l!==s||o()!==h||(r.rememberForsionAccount({cloudUrl:f,token:u}),t.writeCreds({cloudUrl:f,token:u}),t.log("[auth] \u767B\u5F55\u6001\u5DF2\u6ED1\u52A8\u7EED\u671F(\u6709\u6548\u671F\u91CD\u65B0\u8BA1\u6EE1 2 \u5468)"))}),t.log("[forsion-extend] account core registered")}var lr=Symbol("stale-auth-intent");import{promises as nt}from"node:fs";import Be from"node:path";import{createHash as ro}from"node:crypto";var ln=null;function mr(t){ln=t}function pe(){if(!ln)throw new Error("amadeus sync env not set (registerAmadeus factory has not run)");return ln}var ye=()=>pe().accountId();function ct(t=ye()){return t?ro("sha256").update(t).digest("hex"):"signed-out"}var xe=(t=ye())=>pe().readConfig(t),Oe=(t,e=ye())=>pe().writeConfig(t,e),Ge=(t,e=ye())=>pe().updateConfig(t,e),Fe=(t=ye())=>pe().cloudVaultDir(t),It=t=>pe().isManagedCloudVault(t);import{createHash as li}from"node:crypto";import{promises as ne,existsSync as Vr}from"node:fs";import ie from"node:path";import{EventEmitter as Do}from"node:events";import{stat as Mo}from"node:fs";import{readdir as No,stat as Oo}from"node:fs/promises";import*as Y from"node:path";import{lstat as gr,readdir as so,realpath as oo,stat as io}from"node:fs/promises";import{join as ao,resolve as lo,sep as pr}from"node:path";import{Readable as co}from"node:stream";var Se={FILE_TYPE:"files",DIR_TYPE:"directories",FILE_DIR_TYPE:"files_directories",EVERYTHING_TYPE:"all"},Je={root:".",fileFilter:t=>!0,directoryFilter:t=>!0,type:Se.FILE_TYPE,lstat:!1,depth:2147483648,alwaysStat:!1,highWaterMark:256};Object.freeze(Je);var Sr="READDIRP_RECURSIVE_ERROR",uo=new Set(["ENOENT","EPERM","EACCES","ELOOP",Sr]),yr=[Se.DIR_TYPE,Se.EVERYTHING_TYPE,Se.FILE_DIR_TYPE,Se.FILE_TYPE],fo=new Set([Se.DIR_TYPE,Se.EVERYTHING_TYPE,Se.FILE_DIR_TYPE]),ho=new Set([Se.EVERYTHING_TYPE,Se.FILE_DIR_TYPE,Se.FILE_TYPE]),mo=t=>uo.has(t.code),go=process.platform==="win32",wr=t=>!0,br=t=>{if(t===void 0)return wr;if(typeof t=="function")return t;if(typeof t=="string"){let e=t.trim();return n=>n.basename===e}if(Array.isArray(t)){let e=t.map(n=>n.trim());return n=>e.some(r=>n.basename===r)}return wr},cn=class extends co{parents;reading;parent;_stat;_maxDepth;_wantsDir;_wantsFile;_wantsEverything;_root;_isDirent;_statsProp;_rdOptions;_fileFilter;_directoryFilter;_relStart;constructor(e={}){super({objectMode:!0,autoDestroy:!0,highWaterMark:e.highWaterMark??Je.highWaterMark});let n={...Je,...e},r=n.root??Je.root,s=n.type??Je.type;this._fileFilter=br(n.fileFilter),this._directoryFilter=br(n.directoryFilter);let o=n.lstat?gr:io;go?this._stat=i=>o(i,{bigint:!0}):this._stat=o,this._maxDepth=n.depth!=null&&Number.isSafeInteger(n.depth)?n.depth:Je.depth,this._wantsDir=fo.has(s),this._wantsFile=ho.has(s),this._wantsEverything=s===Se.EVERYTHING_TYPE,this._root=lo(r),this._relStart=this._root.endsWith(pr)?this._root.length:this._root.length+1,this._isDirent=!n.alwaysStat,this._statsProp=this._isDirent?"dirent":"stats",this._rdOptions={encoding:"utf8",withFileTypes:this._isDirent};let a={path:this._root,depth:1};a.pending=this._exploreDir(this._root,1),this.parents=[a],this.reading=!1,this.parent=void 0}async _read(e){if(!this.reading){this.reading=!0;try{for(;!this.destroyed&&e>0;){let n=this.parent,r=n&&n.files;if(r&&r.length>0){let{path:s,depth:o}=n,a=r.splice(0,e).map(l=>this._formatEntry(l,s)),i=this._isDirent?a:await Promise.all(a);for(let l of i){if(!l)continue;if(this.destroyed)return;let h=this._getEntryType(l);typeof h!="string"&&(h=await h),h==="directory"&&this._directoryFilter(l)?(o<=this._maxDepth&&this.parents.push({path:l.fullPath,depth:o+1}),this._wantsDir&&(this.push(l),e--)):(h==="file"||this._includeAsFile(l))&&this._fileFilter(l)&&this._wantsFile&&(this.push(l),e--)}}else{let s=this.parents.pop();if(!s){this.push(null);break}let o=s.pending??this._exploreDir(s.path,s.depth),a=this.parents[this.parents.length-1];if(a&&!a.pending&&(a.pending=this._exploreDir(a.path,a.depth)),this.parent=await o,this.destroyed)return}}}catch(n){this.destroy(n)}finally{this.reading=!1}}}async _exploreDir(e,n){let r;try{r=await so(e,this._rdOptions)}catch(s){this._onError(s)}return{files:r,depth:n,path:e}}_formatEntry(e,n){let r=this._isDirent?e.name:e,s=ao(n,r),o={path:s.slice(this._relStart),fullPath:s,basename:r};return this._isDirent?(o.dirent=e,o):this._stat(s).then(a=>(o.stats=a,o),a=>{this._onError(a)})}_onError(e){mo(e)&&!this.destroyed?this.emit("warn",e):this.destroy(e)}_getEntryType(e){if(!e||!(this._statsProp in e))return"";let n=e[this._statsProp];return n.isFile()?"file":n.isDirectory()?"directory":n.isSymbolicLink()?this._getSymlinkEntryType(e):""}async _getSymlinkEntryType(e){let n=e.fullPath;try{let r=await oo(n),s=await gr(r);if(s.isFile())return"file";if(s.isDirectory()){let o=r.length;if(n.startsWith(r)&&n[o]===pr){let a=new Error(`Circular symlink detected: "${n}" points to "${r}"`);return a.code=Sr,this._onError(a),""}return"directory"}}catch(r){this._onError(r)}return""}_includeAsFile(e){let n=e&&e[this._statsProp];return n&&this._wantsEverything&&!n.isDirectory()}};function vr(t,e={}){let n=e.entryType||e.type;if(n==="both"&&(n=Se.FILE_DIR_TYPE),t){if(typeof t!="string")throw new TypeError("readdirp: root argument must be a string. Usage: readdirp(root, options)");if(n&&!yr.includes(n))throw new Error(`readdirp: Invalid type passed. Use one of ${yr.join(", ")}`)}else throw new Error("readdirp: root argument is required. Usage: readdirp(root, options)");let r={...e,root:t};return n&&(r.type=n),new cn(r)}import{watch as po,unwatchFile as Er,watchFile as yo}from"node:fs";import{realpath as un,lstat as wo,open as bo,stat as kr}from"node:fs/promises";import{type as So}from"node:os";import*as Q from"node:path";var vo="data",hn="end",Cr="close",Mt=()=>{};var Nt=process.platform,mn=Nt==="win32",Eo=Nt==="darwin",_o=Nt==="linux",ko=Nt==="freebsd",Tr=So()==="OS400",te={ALL:"all",READY:"ready",ADD:"add",CHANGE:"change",ADD_DIR:"addDir",UNLINK:"unlink",UNLINK_DIR:"unlinkDir",RAW:"raw",ERROR:"error"},Ae=te,Co="watch",To={lstat:wo,stat:kr},qe="listeners",Rt="errHandlers",Ke="rawEmitters",xo=[qe,Rt,Ke],Ao=new Set(["3dm","3ds","3g2","3gp","7z","a","aac","adp","afdesign","afphoto","afpub","ai","aif","aiff","alz","ape","apk","appimage","ar","arj","asf","au","avi","bak","baml","bh","bin","bk","bmp","btif","bz2","bzip2","cab","caf","cgm","class","cmx","cpio","cr2","cur","dat","dcm","deb","dex","djvu","dll","dmg","dng","doc","docm","docx","dot","dotm","dra","DS_Store","dsk","dts","dtshd","dvb","dwg","dxf","ecelp4800","ecelp7470","ecelp9600","egg","eol","eot","epub","exe","f4v","fbs","fh","fla","flac","flatpak","fli","flv","fpx","fst","fvt","g3","gh","gif","graffle","gz","gzip","h261","h263","h264","icns","ico","ief","img","ipa","iso","jar","jpeg","jpg","jpgv","jpm","jxr","key","ktx","lha","lib","lvp","lz","lzh","lzma","lzo","m3u","m4a","m4v","mar","mdi","mht","mid","midi","mj2","mka","mkv","mmr","mng","mobi","mov","movie","mp3","mp4","mp4a","mpeg","mpg","mpga","mxu","nef","npx","numbers","nupkg","o","odp","ods","odt","oga","ogg","ogv","otf","ott","pages","pbm","pcx","pdb","pdf","pea","pgm","pic","png","pnm","pot","potm","potx","ppa","ppam","ppm","pps","ppsm","ppsx","ppt","pptm","pptx","psd","pya","pyc","pyo","pyv","qt","rar","ras","raw","resources","rgb","rip","rlc","rmf","rmvb","rpm","rtf","rz","s3m","s7z","scpt","sgi","shar","snap","sil","sketch","slk","smv","snk","so","stl","suo","sub","swf","tar","tbz","tbz2","tga","tgz","thmx","tif","tiff","tlz","ttc","ttf","txz","udf","uvh","uvi","uvm","uvp","uvs","uvu","viv","vob","war","wav","wax","wbmp","wdp","weba","webm","webp","whl","wim","wm","wma","wmv","wmx","woff","woff2","wrm","wvx","xbm","xif","xla","xlam","xls","xlsb","xlsm","xlsx","xlt","xltm","xltx","xm","xmind","xpi","xpm","xwd","xz","z","zip","zipx"]),Io=t=>Ao.has(Q.extname(t).slice(1).toLowerCase()),fn=(t,e)=>{t instanceof Set?t.forEach(e):e(t)},ut=(t,e,n)=>{let r=t[e];r instanceof Set||(t[e]=r=new Set([r])),r.add(n)},Ro=t=>e=>{let n=t[e];n instanceof Set?n.clear():delete t[e]},dt=(t,e,n)=>{let r=t[e];r instanceof Set?r.delete(n):r===n&&delete t[e]},xr=t=>t instanceof Set?t.size===0:!t,Pt=new Map;function _r(t,e,n,r,s){let o=(a,i)=>{n(t),s(a,i,{watchedPath:t}),i&&t!==i&&$t(Q.resolve(t,i),qe,Q.join(t,i))};try{return po(t,{persistent:e.persistent},o)}catch(a){r(a);return}}var $t=(t,e,n,r,s)=>{let o=Pt.get(t);o&&fn(o[e],a=>{a(n,r,s)})},Po=(t,e,n,r)=>{let{listener:s,errHandler:o,rawEmitter:a}=r,i=Pt.get(e),l;if(!n.persistent)return l=_r(t,n,s,o,a),l?l.close.bind(l):void 0;if(i)ut(i,qe,s),ut(i,Rt,o),ut(i,Ke,a);else{if(l=_r(t,n,$t.bind(null,e,qe),o,$t.bind(null,e,Ke)),!l)return;l.on(Ae.ERROR,async h=>{let d=$t.bind(null,e,Rt);if(i&&(i.watcherUnusable=!0),mn&&h.code==="EPERM")try{await(await bo(t,"r")).close(),d(h)}catch{}else d(h)}),i={listeners:s,errHandlers:o,rawEmitters:a,watcher:l},Pt.set(e,i)}return()=>{dt(i,qe,s),dt(i,Rt,o),dt(i,Ke,a),xr(i.listeners)&&(i.watcher.close(),Pt.delete(e),xo.forEach(Ro(i)),i.watcher=void 0,Object.freeze(i))}},dn=new Map,$o=(t,e,n,r)=>{let{listener:s,rawEmitter:o}=r,a=dn.get(e),i=a&&a.options;return i&&(i.persistent<n.persistent||i.interval>n.interval)&&(Er(e),a=void 0),a?(ut(a,qe,s),ut(a,Ke,o)):(a={listeners:s,rawEmitters:o,options:n,watcher:yo(e,n,(l,h)=>{fn(a.rawEmitters,f=>{f(Ae.CHANGE,e,{curr:l,prev:h})});let d=l.mtimeMs;(l.size!==h.size||d>h.mtimeMs||d===0)&&fn(a.listeners,f=>f(t,l))})},dn.set(e,a)),()=>{dt(a,qe,s),dt(a,Ke,o),xr(a.listeners)&&(dn.delete(e),Er(e),a.options=a.watcher=void 0,Object.freeze(a))}},Dt=class{fsw;_boundHandleError;constructor(e){this.fsw=e,this._boundHandleError=n=>e._handleError(n)}_watchWithNodeFs(e,n){let r=this.fsw.options,s=Q.dirname(e),o=Q.basename(e);this.fsw._getWatchedDir(s).add(o);let i=Q.resolve(e),l={persistent:r.persistent};n||(n=Mt);let h;if(r.usePolling){let d=r.interval!==r.binaryInterval;l.interval=d&&Io(o)?r.binaryInterval:r.interval,h=$o(e,i,l,{listener:n,rawEmitter:this.fsw._emitRaw})}else h=Po(e,i,l,{listener:n,errHandler:this._boundHandleError,rawEmitter:this.fsw._emitRaw});return h}_handleFile(e,n,r){if(this.fsw.closed)return;let s=Q.dirname(e),o=Q.basename(e),a=this.fsw._getWatchedDir(s),i=n;if(a.has(o))return;let l=async(d,f)=>{if(this.fsw._throttle(Co,e,5)){if(!f||f.mtimeMs===0)try{let u=await kr(e);if(this.fsw.closed)return;let g=u.atimeMs,S=u.mtimeMs;if((!g||g<=S||S!==i.mtimeMs)&&this.fsw._emit(Ae.CHANGE,e,u),(Eo||_o||ko)&&i.ino!==u.ino){this.fsw._closeFile(d),i=u;let x=this._watchWithNodeFs(e,l);x&&this.fsw._addPathCloser(d,x)}else i=u}catch{this.fsw._remove(s,o)}else if(a.has(o)){let u=f.atimeMs,g=f.mtimeMs;(!u||u<=g||g!==i.mtimeMs)&&this.fsw._emit(Ae.CHANGE,e,f),i=f}}},h=this._watchWithNodeFs(e,l);if(!(r&&this.fsw.options.ignoreInitial)&&this.fsw._isntIgnored(e)){if(!this.fsw._throttle(Ae.ADD,e,0))return;this.fsw._emit(Ae.ADD,e,n)}return h}async _handleSymlink(e,n,r,s){if(this.fsw.closed)return;let o=e.fullPath,a=this.fsw._getWatchedDir(n);if(!this.fsw.options.followSymlinks){this.fsw._incrReadyCount();let i;try{i=await un(r)}catch{return this.fsw._emitReady(),!0}return this.fsw.closed?void 0:(a.has(s)?this.fsw._symlinkPaths.get(o)!==i&&(this.fsw._symlinkPaths.set(o,i),this.fsw._emit(Ae.CHANGE,r,e.stats)):(a.add(s),this.fsw._symlinkPaths.set(o,i),this.fsw._emit(Ae.ADD,r,e.stats)),this.fsw._emitReady(),!0)}if(this.fsw._symlinkPaths.has(o))return!0;this.fsw._symlinkPaths.set(o,!0)}_handleRead(e,n,r,s,o,a,i){e=Q.join(e,"");let l=s?`${e}:${s}`:e;if(i=this.fsw._throttle("readdir",l,1e3),!i)return;let h=this.fsw._getWatchedDir(r.path),d=new Set,f=this.fsw._readdirp(e,{fileFilter:u=>r.filterPath(u),directoryFilter:u=>r.filterDir(u)});if(f)return f.on(vo,async u=>{if(this.fsw.closed){f=void 0;return}let g=u.path,S=Q.join(e,g);if(d.add(g),!(u.stats.isSymbolicLink()&&await this._handleSymlink(u,e,S,g))){if(this.fsw.closed){f=void 0;return}(g===s||!s&&!h.has(g))&&(this.fsw._incrReadyCount(),S=Q.join(o,Q.relative(o,S)),this._addToNodeFs(S,n,r,a+1))}}).on(Ae.ERROR,this._boundHandleError),new Promise((u,g)=>{if(!f)return g();f.once(hn,()=>{if(this.fsw.closed){f=void 0;return}let S=i?i.clear():!1;u(void 0),h.getChildren().filter(x=>x!==e&&!d.has(x)).forEach(x=>{this.fsw._remove(e,x)}),f=void 0,S&&this._handleRead(e,!1,r,s,o,a,i)})})}async _handleDir(e,n,r,s,o,a,i){let l=this.fsw._getWatchedDir(Q.dirname(e)),h=l.has(Q.basename(e));!(r&&this.fsw.options.ignoreInitial)&&!o&&!h&&this.fsw._emit(Ae.ADD_DIR,e,n),l.add(Q.basename(e)),this.fsw._getWatchedDir(e);let d,f,u=this.fsw.options.depth;if((u==null||s<=u)&&!this.fsw._symlinkPaths.has(i)){if(!o&&(await this._handleRead(e,r,a,o,e,s,d),this.fsw.closed))return;f=this._watchWithNodeFs(e,(g,S)=>{S&&S.mtimeMs===0||this._handleRead(g,!1,a,o,e,s,d)})}return f}async _addToNodeFs(e,n,r,s,o){let a=this.fsw._emitReady;if(this.fsw._isIgnored(e)||this.fsw.closed)return a(),!1;let i=this.fsw._getWatchHelpers(e);r&&(i.filterPath=l=>r.filterPath(l),i.filterDir=l=>r.filterDir(l));try{let l=await To[i.statMethod](i.watchPath);if(this.fsw.closed)return;if(this.fsw._isIgnored(i.watchPath,l))return a(),!1;let h=this.fsw.options.followSymlinks,d;if(l.isDirectory()){let f=Q.resolve(e),u=h?await un(e):e;if(this.fsw.closed||(d=await this._handleDir(i.watchPath,l,n,s,o,i,u),this.fsw.closed))return;f!==u&&u!==void 0&&this.fsw._symlinkPaths.set(f,u)}else if(l.isSymbolicLink()){let f=h?await un(e):e;if(this.fsw.closed)return;let u=Q.dirname(i.watchPath);if(this.fsw._getWatchedDir(u).add(i.watchPath),this.fsw._emit(Ae.ADD,i.watchPath,l),d=await this._handleDir(u,l,n,s,e,i,f),this.fsw.closed)return;f!==void 0&&this.fsw._symlinkPaths.set(Q.resolve(e),f)}else d=this._handleFile(i.watchPath,l,n);return a(),d&&this.fsw._addPathCloser(e,d),!1}catch(l){if(this.fsw._handleError(l))return a(),e}}};var gn="/",Uo="//",$r=".",Fo="..",jo="string",Lo=/\\/g,Dr=/\/\//g,Ho=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/,zo=/^\.[/\\]/;function Ot(t){return Array.isArray(t)?t:[t]}var pn=t=>typeof t=="object"&&t!==null&&!(t instanceof RegExp);function qo(t){return typeof t=="function"?t:typeof t=="string"?e=>t===e:t instanceof RegExp?e=>t.test(e):typeof t=="object"&&t!==null?e=>{if(t.path===e)return!0;if(t.recursive){let n=Y.relative(t.path,e);return n?!n.startsWith("..")&&!Y.isAbsolute(n):!1}return!1}:()=>!1}function Bo(t){if(typeof t!="string")throw new Error("string expected");t=Y.normalize(t),t=t.replace(/\\/g,"/");let e=!1;return t.startsWith("//")&&(e=!0),t=t.replace(Dr,"/"),e&&(t="/"+t),t}function Ar(t,e,n){let r=Bo(e);for(let s=0;s<t.length;s++){let o=t[s];if(o(r,n))return!0}return!1}function Wo(t,e){if(t==null)throw new TypeError("anymatch: specify first argument");let r=Ot(t).map(s=>qo(s));return e==null?(s,o)=>Ar(r,s,o):Ar(r,e)}var Ir=t=>{let e=Ot(t).flat();if(!e.every(n=>typeof n===jo))throw new TypeError(`Non-string provided as watch path: ${e}`);return e.map(Mr)},Rr=t=>{let e=t.replace(Lo,gn),n=!1;return e.startsWith(Uo)&&(n=!0),e=e.replace(Dr,gn),n&&(e=gn+e),e},Mr=t=>Rr(Y.normalize(Rr(t))),Pr=(t="")=>e=>typeof e=="string"?Mr(Y.isAbsolute(e)?e:Y.join(t,e)):e,Vo=(t,e)=>Y.isAbsolute(t)?t:Y.join(e,t),Yo=Object.freeze(new Set),yn=class{path;_removeWatcher;items;constructor(e,n){this.path=e,this._removeWatcher=n,this.items=new Set}add(e){let{items:n}=this;n&&e!==$r&&e!==Fo&&n.add(e)}async remove(e){let{items:n}=this;if(!n||(n.delete(e),n.size>0))return;let r=this.path;try{await No(r)}catch{this._removeWatcher&&this._removeWatcher(Y.dirname(r),Y.basename(r))}}has(e){let{items:n}=this;if(n)return n.has(e)}getChildren(){let{items:e}=this;return e?[...e.values()]:[]}dispose(){this.items.clear(),this.path="",this._removeWatcher=Mt,this.items=Yo,Object.freeze(this)}},Go="stat",Jo="lstat",wn=class{fsw;path;watchPath;fullWatchPath;dirParts;followSymlinks;statMethod;constructor(e,n,r){this.fsw=r;let s=e;this.path=e=e.replace(zo,""),this.watchPath=s,this.fullWatchPath=Y.resolve(s),this.dirParts=[],this.dirParts.forEach(o=>{o.length>1&&o.pop()}),this.followSymlinks=n,this.statMethod=n?Go:Jo}entryPath(e){return Y.join(this.watchPath,Y.relative(this.watchPath,e.fullPath))}filterPath(e){let{stats:n}=e;if(n&&n.isSymbolicLink())return this.filterDir(e);let r=this.entryPath(e);return this.fsw._isntIgnored(r,n)&&this.fsw._hasReadPermissions(n)}filterDir(e){return this.fsw._isntIgnored(this.entryPath(e),e.stats)}},Ut=class extends Do{closed;options;_closers;_ignoredPaths;_throttled;_streams;_symlinkPaths;_watched;_pendingWrites;_pendingUnlinks;_readyCount;_emitReady;_closePromise;_userIgnored;_readyEmitted;_emitRaw;_boundRemove;_nodeFsHandler;constructor(e={}){super(),this.closed=!1,this._closers=new Map,this._ignoredPaths=new Set,this._throttled=new Map,this._streams=new Set,this._symlinkPaths=new Map,this._watched=new Map,this._pendingWrites=new Map,this._pendingUnlinks=new Map,this._readyCount=0,this._readyEmitted=!1;let n=e.awaitWriteFinish,r={stabilityThreshold:2e3,pollInterval:100},s={persistent:!0,ignoreInitial:!1,ignorePermissionErrors:!1,interval:100,binaryInterval:300,followSymlinks:!0,usePolling:!1,atomic:!0,...e,ignored:e.ignored?Ot(e.ignored):Ot([]),awaitWriteFinish:n===!0?r:typeof n=="object"?{...r,...n}:!1};Tr&&(s.usePolling=!0),s.atomic===void 0&&(s.atomic=!s.usePolling);let o=process.env.CHOKIDAR_USEPOLLING;if(o!==void 0){let l=o.toLowerCase();l==="false"||l==="0"?s.usePolling=!1:l==="true"||l==="1"?s.usePolling=!0:s.usePolling=!!l}let a=process.env.CHOKIDAR_INTERVAL;a&&(s.interval=Number.parseInt(a,10));let i=0;this._emitReady=()=>{i++,i>=this._readyCount&&(this._emitReady=Mt,this._readyEmitted=!0,process.nextTick(()=>this.emit(te.READY)))},this._emitRaw=(...l)=>this.emit(te.RAW,...l),this._boundRemove=this._remove.bind(this),this.options=s,this._nodeFsHandler=new Dt(this),Object.freeze(s)}_addIgnoredPath(e){if(pn(e)){for(let n of this._ignoredPaths)if(pn(n)&&n.path===e.path&&n.recursive===e.recursive)return}this._ignoredPaths.add(e)}_removeIgnoredPath(e){if(this._ignoredPaths.delete(e),typeof e=="string")for(let n of this._ignoredPaths)pn(n)&&n.path===e&&this._ignoredPaths.delete(n)}add(e,n,r){let{cwd:s}=this.options;this.closed=!1,this._closePromise=void 0;let o=Ir(e);return s&&(o=o.map(a=>Vo(a,s))),o.forEach(a=>{this._removeIgnoredPath(a)}),this._userIgnored=void 0,this._readyCount||(this._readyCount=0),this._readyCount+=o.length,Promise.all(o.map(async a=>{let i=await this._nodeFsHandler._addToNodeFs(a,!r,void 0,0,n);return i&&this._emitReady(),i})).then(a=>{this.closed||a.forEach(i=>{i&&this.add(Y.dirname(i),Y.basename(n||i))})}),this}unwatch(e){if(this.closed)return this;let n=Ir(e),{cwd:r}=this.options;return n.forEach(s=>{!Y.isAbsolute(s)&&!this._closers.has(s)&&(r&&(s=Y.join(r,s)),s=Y.resolve(s)),this._closePath(s),this._addIgnoredPath(s),this._watched.has(s)&&this._addIgnoredPath({path:s,recursive:!0}),this._userIgnored=void 0}),this}close(){if(this._closePromise)return this._closePromise;this.closed=!0,this.removeAllListeners();let e=[];return this._closers.forEach(n=>n.forEach(r=>{let s=r();s instanceof Promise&&e.push(s)})),this._streams.forEach(n=>n.destroy()),this._userIgnored=void 0,this._readyCount=0,this._readyEmitted=!1,this._watched.forEach(n=>n.dispose()),this._closers.clear(),this._watched.clear(),this._streams.clear(),this._symlinkPaths.clear(),this._throttled.clear(),this._closePromise=e.length?Promise.all(e).then(()=>{}):Promise.resolve(),this._closePromise}getWatched(){let e={};return this._watched.forEach((n,r)=>{let o=(this.options.cwd?Y.relative(this.options.cwd,r):r)||$r;e[o]=n.getChildren().sort()}),e}emitWithAll(e,n){this.emit(e,...n),e!==te.ERROR&&this.emit(te.ALL,e,...n)}async _emit(e,n,r){if(this.closed)return;let s=this.options;mn&&(n=Y.normalize(n)),s.cwd&&(n=Y.relative(s.cwd,n));let o=[n];r!=null&&o.push(r);let a=s.awaitWriteFinish,i;if(a&&(i=this._pendingWrites.get(n)))return i.lastChange=new Date,this;if(s.atomic){if(e===te.UNLINK)return this._pendingUnlinks.set(n,[e,...o]),setTimeout(()=>{this._pendingUnlinks.forEach((l,h)=>{this.emit(...l),this.emit(te.ALL,...l),this._pendingUnlinks.delete(h)})},typeof s.atomic=="number"?s.atomic:100),this;e===te.ADD&&this._pendingUnlinks.has(n)&&(e=te.CHANGE,this._pendingUnlinks.delete(n))}if(a&&(e===te.ADD||e===te.CHANGE)&&this._readyEmitted){let l=(h,d)=>{h?(e=te.ERROR,o[0]=h,this.emitWithAll(e,o)):d&&(o.length>1?o[1]=d:o.push(d),this.emitWithAll(e,o))};return this._awaitWriteFinish(n,a.stabilityThreshold,e,l),this}if(e===te.CHANGE&&!this._throttle(te.CHANGE,n,50))return this;if(s.alwaysStat&&r===void 0&&(e===te.ADD||e===te.ADD_DIR||e===te.CHANGE)){let l=s.cwd?Y.join(s.cwd,n):n,h;try{h=await Oo(l)}catch{}if(!h||this.closed)return;o.push(h)}return this.emitWithAll(e,o),this}_handleError(e){let n=e&&e.code;return e&&n!=="ENOENT"&&n!=="ENOTDIR"&&(!this.options.ignorePermissionErrors||n!=="EPERM"&&n!=="EACCES")&&this.emit(te.ERROR,e),e||this.closed}_throttle(e,n,r){this._throttled.has(e)||this._throttled.set(e,new Map);let s=this._throttled.get(e);if(!s)throw new Error("invalid throttle");let o=s.get(n);if(o)return o.count++,!1;let a,i=()=>{let h=s.get(n),d=h?h.count:0;return s.delete(n),clearTimeout(a),h&&clearTimeout(h.timeoutObject),d};a=setTimeout(i,r);let l={timeoutObject:a,clear:i,count:0};return s.set(n,l),l}_incrReadyCount(){return this._readyCount++}_awaitWriteFinish(e,n,r,s){let o=this.options.awaitWriteFinish;if(typeof o!="object")return;let a=o.pollInterval,i,l=e;this.options.cwd&&!Y.isAbsolute(e)&&(l=Y.join(this.options.cwd,e));let h=new Date,d=this._pendingWrites;function f(u){Mo(l,(g,S)=>{if(g||!d.has(e)){g&&g.code!=="ENOENT"&&s(g);return}let x=Number(new Date);u&&S.size!==u.size&&(d.get(e).lastChange=x);let w=d.get(e);x-w.lastChange>=n?(d.delete(e),s(void 0,S)):i=setTimeout(f,a,S)})}d.has(e)||(d.set(e,{lastChange:h,cancelWait:()=>(d.delete(e),clearTimeout(i),r)}),i=setTimeout(f,a))}_isIgnored(e,n){if(this.options.atomic&&Ho.test(e))return!0;if(!this._userIgnored){let{cwd:r}=this.options,o=(this.options.ignored||[]).map(Pr(r)),i=[...[...this._ignoredPaths].map(Pr(r)),...o];this._userIgnored=Wo(i,void 0)}return this._userIgnored(e,n)}_isntIgnored(e,n){return!this._isIgnored(e,n)}_getWatchHelpers(e){return new wn(e,this.options.followSymlinks,this)}_getWatchedDir(e){let n=Y.resolve(e);return this._watched.has(n)||this._watched.set(n,new yn(n,this._boundRemove)),this._watched.get(n)}_hasReadPermissions(e){return this.options.ignorePermissionErrors?!0:!!(Number(e.mode)&256)}_remove(e,n,r){let s=Y.join(e,n),o=Y.resolve(s);if(r=r??(this._watched.has(s)||this._watched.has(o)),!this._throttle("remove",s,100))return;!r&&this._watched.size===1&&this.add(e,n,!0),this._getWatchedDir(s).getChildren().forEach(u=>this._remove(s,u));let l=this._getWatchedDir(e),h=l.has(n);l.remove(n),this._symlinkPaths.has(o)&&this._symlinkPaths.delete(o);let d=s;if(this.options.cwd&&(d=Y.relative(this.options.cwd,s)),this.options.awaitWriteFinish&&this._pendingWrites.has(d)&&this._pendingWrites.get(d).cancelWait()===te.ADD)return;this._watched.delete(s),this._watched.delete(o);let f=r?te.UNLINK_DIR:te.UNLINK;h&&!this._isIgnored(s)&&this._emit(f,s),this._closePath(s)}_closePath(e){this._closeFile(e);let n=Y.dirname(e);this._getWatchedDir(n).remove(Y.basename(e))}_closeFile(e){let n=this._closers.get(e);n&&(n.forEach(r=>r()),this._closers.delete(e))}_addPathCloser(e,n){if(!n)return;let r=this._closers.get(e);r||(r=[],this._closers.set(e,r)),r.push(n)}_readdirp(e,n){if(this.closed)return;let r={type:te.ALL,alwaysStat:!0,lstat:!0,...n,depth:0},s=vr(e,r);return this._streams.add(s),s.once(Cr,()=>{s=void 0}),s.once(hn,()=>{s&&(this._streams.delete(s),s=void 0)}),s}};function Ko(t,e={}){let n=new Ut(e);return n.add(t),n}var Nr={watch:Ko,FSWatcher:Ut};function Xo(t,e){let n=Object.create(null);for(let o=0;o<e.length;o++){let a=e[o];n[a]?n[a].push(o):n[a]=[o]}let s=[{buffer1index:-1,buffer2index:-1,chain:null}];for(let o=0;o<t.length;o++){let a=t[o],i=n[a]||[],l=0,h=s[0];for(let d of i){let f;for(f=l;f<s.length&&!(s[f].buffer2index<d&&(f===s.length-1||s[f+1].buffer2index>d));f++);if(f<s.length){let u={buffer1index:o,buffer2index:d,chain:s[f]};if(l===s.length?s.push(h):s[l]=h,l=f+1,h=u,l===s.length)break}}s[l]=h}return s[s.length-1]}function Or(t,e){let n=Xo(t,e),r=[],s=t.length,o=e.length;for(let a=n;a!==null;a=a.chain){let i=s-a.buffer1index-1,l=o-a.buffer2index-1;s=a.buffer1index,o=a.buffer2index,(i||l)&&r.push({buffer1:[s+1,i],buffer1Content:t.slice(s+1,s+1+i),buffer2:[o+1,l],buffer2Content:e.slice(o+1,o+1+l)})}return r.reverse(),r}function Zo(t,e,n){let r=[];function s(l,h){r.push({ab:h,oStart:l.buffer1[0],oLength:l.buffer1[1],abStart:l.buffer2[0],abLength:l.buffer2[1]})}Or(e,t).forEach(l=>s(l,"a")),Or(e,n).forEach(l=>s(l,"b")),r.sort((l,h)=>l.oStart-h.oStart);let o=[],a=0;function i(l){l>a&&(o.push({stable:!0,buffer:"o",bufferStart:a,bufferLength:l-a,bufferContent:e.slice(a,l)}),a=l)}for(;r.length;){let l=r.shift(),h=l.oStart,d=l.oStart+l.oLength,f=[l];for(i(h);r.length;){let u=r[0],g=u.oStart;if(g>d)break;d=Math.max(d,g+u.oLength),f.push(r.shift())}if(f.length===1){if(l.abLength>0){let u=l.ab==="a"?t:n;o.push({stable:!0,buffer:l.ab,bufferStart:l.abStart,bufferLength:l.abLength,bufferContent:u.slice(l.abStart,l.abStart+l.abLength)})}}else{let u={a:[t.length,-1,e.length,-1],b:[n.length,-1,e.length,-1]};for(;f.length;){l=f.shift();let _=l.oStart,A=_+l.oLength,U=l.abStart,M=U+l.abLength,B=u[l.ab];B[0]=Math.min(U,B[0]),B[1]=Math.max(M,B[1]),B[2]=Math.min(_,B[2]),B[3]=Math.max(A,B[3])}let g=u.a[0]+(h-u.a[2]),S=u.a[1]+(d-u.a[3]),x=u.b[0]+(h-u.b[2]),w=u.b[1]+(d-u.b[3]),F={stable:!1,aStart:g,aLength:S-g,aContent:t.slice(g,S),oStart:h,oLength:d-h,oContent:e.slice(h,d),bStart:x,bLength:w-x,bContent:n.slice(x,w)};o.push(F)}a=d}return i(e.length),o}function Ur(t,e,n,r){r=Object.assign({excludeFalseConflicts:!0,stringSeparator:/\s+/},r),typeof t=="string"&&(t=t.split(r.stringSeparator)),typeof e=="string"&&(e=e.split(r.stringSeparator)),typeof n=="string"&&(n=n.split(r.stringSeparator));let o=[],a=Zo(t,e,n),i=[];function l(){i.length&&o.push({ok:i}),i=[]}function h(d,f){if(d.length!==f.length)return!1;for(let u=0;u<d.length;u++)if(d[u]!==f[u])return!1;return!0}return a.forEach(d=>{d.stable?i.push(...d.bufferContent):r.excludeFalseConflicts&&h(d.aContent,d.bContent)?i.push(...d.aContent):(l(),o.push({conflict:{a:d.aContent,aIndex:d.aStart,o:d.oContent,oIndex:d.oStart,b:d.bContent,bIndex:d.bStart}}))}),l(),o}function Ft(t,e){let n=t.lastIndexOf("/"),r=n<0?"":t.slice(0,n+1),s=n<0?t:t.slice(n+1),o=s.lastIndexOf("."),a=o>0?s.slice(0,o):s,i=o>0?s.slice(o):"",l=d=>String(d).padStart(2,"0"),h=`${e.getFullYear()}-${l(e.getMonth()+1)}-${l(e.getDate())} ${l(e.getHours())}${l(e.getMinutes())}`;return`${r}${a} (conflict ${h})${i}`}function Qo(t,e){if(e<2)return t;let n=t.lastIndexOf("."),r=n>t.lastIndexOf("/")&&n>t.lastIndexOf(")"),s=r?t.slice(0,n):t,o=r?t.slice(n):"";return`${s}-${e}${o}`}function ei(t){let e=3735928559,n=1103547991;for(let s=0;s<t.length;s++){let o=t.charCodeAt(s);e=Math.imul(e^o,2654435761),n=Math.imul(n^o,1597334677)}e=Math.imul(e^e>>>16,2246822507)^Math.imul(n^n>>>13,3266489909),n=Math.imul(n^n>>>16,2246822507)^Math.imul(e^e>>>13,3266489909);let r=4294967296*(2097151&n)+(e>>>0);return`${t.length.toString(36)}-${r.toString(36)}`}function jt(t,e,n){if(t===null&&e===null&&n===null)return{kind:"none"};if(n===null)return t===null?e?{kind:"dropShadow"}:{kind:"none"}:e?t===e.hash?{kind:"deleteLocal"}:{kind:"pushCreate"}:{kind:"pushCreate"};if(t===null)return e?n.seq===e.seq?{kind:"pushDelete"}:{kind:"pull"}:{kind:"pull"};if(!e)return t===n.hash?{kind:"adopt"}:{kind:"conflict"};let r=t!==e.hash,s=n.seq!==e.seq;return!r&&!s?{kind:"none"}:r?s?t===n.hash?{kind:"adopt"}:n.hash===e.hash?{kind:"push",baseSeq:n.seq}:{kind:"conflict"}:{kind:"push",baseSeq:e.seq}:{kind:"pull"}}function Fr(t,e,n){let r=Ur(t.split(`
193
+ `,_i=t=>({transpile:(e,n,r)=>t.transpileForServe(e,n,r),mimeOf:e=>t.mimeOf(e)});function wn(t){let e=t;return typeof e.projectsRoot=="function"&&typeof e.transpileForServe=="function"&&typeof e.mimeOf=="function"&&typeof e.setPreviewHooks=="function"}function bn(t){t.setPreviewHooks({sdkJs:Sr,proxy:br(()=>t.getCloud())}),t.handle("connect:meta",(e,n)=>typeof n=="string"&&n?yr(n):{}),t.handle("connect:list",async()=>{let e=await t.getCloud();if(!e.token)return{ok:!1,code:"not_logged_in",detail:"\u8BF7\u5148\u767B\u5F55 Forsion \u8D26\u53F7"};try{let{status:n,json:r}=await we(e,"GET","/api/connect/apps");return n===401||n===403?{ok:!1,code:"not_logged_in",detail:"\u767B\u5F55\u5DF2\u8FC7\u671F,\u8BF7\u91CD\u65B0\u767B\u5F55"}:n!==200?{ok:!1,code:"error",detail:r?.detail||`HTTP ${n}`}:{ok:!0,base:e.base,...r}}catch(n){return{ok:!1,code:"error",detail:n?.message||String(n)}}}),t.handle("connect:publish",async(e,n)=>{if(!n||typeof n.dir!="string"||!n.dir||!n.name||!n.slug||!n.entry)return{ok:!1,code:"error",detail:"\u53C2\u6570\u4E0D\u5B8C\u6574"};let r;try{let i=fr(t.projectsRoot());if(r=fr(n.dir),r!==i&&!r.startsWith(i+wi))return{ok:!1,code:"error",detail:"\u53EA\u80FD\u53D1\u5E03 Coding Space \u9879\u76EE\u76EE\u5F55"}}catch{return{ok:!1,code:"error",detail:"\u9879\u76EE\u76EE\u5F55\u4E0D\u5B58\u5728\u6216\u65E0\u6CD5\u8BBF\u95EE"}}let s=await t.getCloud();if(!s.token)return{ok:!1,code:"not_logged_in",detail:"\u8BF7\u5148\u767B\u5F55 Forsion \u8D26\u53F7"};try{let{files:i,totalBytes:o}=gr(r,_i(t));if(!i.some(d=>d.path===n.entry))return{ok:!1,code:"error",detail:`\u5165\u53E3\u6587\u4EF6\u4E0D\u5B58\u5728:${n.entry}`};let{status:a,json:l}=await we(s,"POST","/api/connect/apps",{slug:n.slug,name:n.name,entry:n.entry,files:i},3e5);return a===401?{ok:!1,code:"not_logged_in",detail:"\u767B\u5F55\u5DF2\u8FC7\u671F,\u8BF7\u91CD\u65B0\u767B\u5F55"}:a!==200?{ok:!1,code:l?.code||"error",detail:l?.detail||`HTTP ${a}`,used:l?.used,limit:l?.limit}:(wr(r,{slug:String(l.slug)}),{ok:!0,slug:l.slug,handle:l.handle,url:`${s.base}${l.url}`,totalBytes:o})}catch(i){return{ok:!1,code:"error",detail:i?.message||String(i)}}}),t.handle("connect:unpublish",async(e,n)=>{if(!n||typeof n!="string")return{ok:!1,code:"error",detail:"\u53C2\u6570\u4E0D\u5B8C\u6574"};let r=await t.getCloud();if(!r.token)return{ok:!1,code:"not_logged_in",detail:"\u8BF7\u5148\u767B\u5F55 Forsion \u8D26\u53F7"};try{let{status:s,json:i}=await we(r,"DELETE",`/api/connect/apps/${encodeURIComponent(n)}`);return s===401||s===403?{ok:!1,code:"not_logged_in",detail:"\u767B\u5F55\u5DF2\u8FC7\u671F,\u8BF7\u91CD\u65B0\u767B\u5F55"}:s!==200&&s!==404?{ok:!1,code:"error",detail:i?.detail||`HTTP ${s}`}:{ok:!0}}catch(s){return{ok:!1,code:"error",detail:s?.message||String(s)}}}),t.handle("connect:listingApply",async(e,n)=>{if(!n||typeof n.slug!="string"||!n.slug||typeof n.summary!="string"||!n.summary.trim())return{ok:!1,code:"error",detail:"\u53C2\u6570\u4E0D\u5B8C\u6574"};let r=await t.getCloud();if(!r.token)return{ok:!1,code:"not_logged_in",detail:"\u8BF7\u5148\u767B\u5F55 Forsion \u8D26\u53F7"};try{let{status:s,json:i}=await we(r,"PUT",`/api/connect/apps/${encodeURIComponent(n.slug)}/listing`,{summary:n.summary});return s===401?{ok:!1,code:"not_logged_in",detail:"\u767B\u5F55\u5DF2\u8FC7\u671F,\u8BF7\u91CD\u65B0\u767B\u5F55"}:s!==200?{ok:!1,code:i?.code||"error",detail:i?.detail||`HTTP ${s}`}:{ok:!0,status:i.status}}catch(s){return{ok:!1,code:"error",detail:s?.message||String(s)}}}),t.handle("connect:listingWithdraw",async(e,n)=>{if(!n||typeof n!="string")return{ok:!1,code:"error",detail:"\u53C2\u6570\u4E0D\u5B8C\u6574"};let r=await t.getCloud();if(!r.token)return{ok:!1,code:"not_logged_in",detail:"\u8BF7\u5148\u767B\u5F55 Forsion \u8D26\u53F7"};try{let{status:s,json:i}=await we(r,"DELETE",`/api/connect/apps/${encodeURIComponent(n)}/listing`);return s===401?{ok:!1,code:"not_logged_in",detail:"\u767B\u5F55\u5DF2\u8FC7\u671F,\u8BF7\u91CD\u65B0\u767B\u5F55"}:s!==200&&s!==404?{ok:!1,code:"error",detail:i?.detail||`HTTP ${s}`}:{ok:!0}}catch(s){return{ok:!1,code:"error",detail:s?.message||String(s)}}}),t.handle("connect:store",async()=>{let e=await t.getCloud();try{let{status:n,json:r}=await we(e,"GET","/api/connect/store");return n!==200?{ok:!1,detail:r?.detail||`HTTP ${n}`}:{ok:!0,base:e.base,items:Array.isArray(r.items)?r.items:[]}}catch(n){return{ok:!1,detail:n?.message||String(n)}}}),t.log("[forsion-extend] connect handlers registered")}import{createHash as ki}from"node:crypto";async function wt(t,e){if(!t||!e)return{status:"offline"};let n=t.replace(/\/+$/,"");try{let r=await fetch(`${n}/api/brain/users/me`,{headers:{Authorization:`Bearer ${e}`},signal:AbortSignal.timeout(5e3)});if(r.status===401||r.status===403)return{status:(r.headers.get("content-type")||"").includes("application/json")?"expired":"offline"};if(!r.ok)return{status:"offline"};let s=await r.json();if(!s)return{status:"offline"};let i=s.avatar||s.avatarUrl||s.avatar_url||void 0;return i&&/^\/(?!\/)/.test(i)&&(i=n+i),{status:"ok",user:{username:s.username||s.nickname||void 0,nickname:s.nickname||void 0,avatar:i,membershipTier:s.membershipTier||s.membership_tier||void 0}}}catch{return{status:"offline"}}}var Er=t=>`${t.seq}:${t.hash}`,vi=t=>ki("sha256").update(t).digest("hex");function Sn(t){if(t===null)return{baseSeq:0,baseHash:null};if(typeof t!="string")return;let e=t.indexOf(":"),n=Number(e===-1?t:t.slice(0,e));if(!Number.isInteger(n)||n<=0)return;let r=e===-1?"":t.slice(e+1);return{baseSeq:n,baseHash:/^[0-9a-f]{64}$/.test(r)?r:null}}function zt(t){let e=t.baseUrl.replace(/\/+$/,""),n=s=>`${e}/api/remotesync/vaults/${encodeURIComponent(t.vault)}${s}`,r=async(s,i)=>{let o=t.getToken();if(!o)throw new Error("penzor-not-logged-in");let a=await fetch(s,{...i,headers:{...i.headers,Authorization:`Bearer ${o}`}});if(a.status===409){let l=await a.json().catch(()=>({}));throw new Error(`cas-conflict ${String(l.code??"")}: seq=${String(l.seq??"?")}`)}if(!a.ok){let l=await a.text().catch(()=>"");throw new Error(`penzor ${i.method??"GET"} ${a.status}: ${l.slice(0,200)}`)}return a};return{kind:"penzor",async walk(s){let i=await r(n("/manifest"),{method:"GET",signal:s}),{files:o}=await i.json();return o.map(a=>({key:a.path,size:a.size,mtimeMs:a.mtimeMs,id:Er(a)}))},async readFile(s,i){let a=await(await r(n(`/file?path=${encodeURIComponent(s)}`),{method:"GET",signal:i})).json(),l=await fetch(a.url,{signal:i});if(!l.ok)throw new Error(`penzor blob GET ${l.status}: ${s}`);let d=Buffer.from(await l.arrayBuffer());if(vi(d)!==a.hash)throw new Error(`penzor hash mismatch: ${s}`);return d},async writeFile(s,i,o,a,l){let d=Sn(l),f=new URLSearchParams({path:s,mtimeMs:String(Math.floor(o)||0)});d&&(f.set("baseSeq",String(d.baseSeq)),d.baseHash&&f.set("baseHash",d.baseHash));let c=await(await r(n(`/file?${f.toString()}`),{method:"PUT",body:new Uint8Array(i),headers:{"Content-Type":"application/octet-stream"},signal:a})).json();return{key:s,size:c.size,mtimeMs:c.mtimeMs,id:Er(c)}},async rm(s,i,o){let a=Sn(o),l=new URLSearchParams({path:s});a&&a.baseSeq>0&&(l.set("baseSeq",String(a.baseSeq)),a.baseHash&&l.set("baseHash",a.baseHash)),await r(n(`/file?${l.toString()}`),{method:"DELETE",signal:i})},async check(){try{return await r(n("/manifest"),{method:"GET"}),{ok:!0}}catch(s){return{ok:!1,error:String(s?.message||s)}}}}}var Bt="forsion-diagnostics",kr=50*1024*1024,_r=new Map;async function xi(t,e){let n=_r.get(e);if(n)return{id:n};let r=await wt(t,e);if(r.status==="offline")return{error:"penzor-offline"};if(r.status!=="ok")return{error:"penzor-not-logged-in"};let s=r.user?.username?.trim();return s?(_r.set(e,s),{id:s}):{error:"penzor-auth-unverified"}}var En=t=>typeof t.registerRemoteSyncBackend=="function"&&typeof t.readCreds=="function";function _n(t){t.registerRemoteSyncBackend("penzor",async e=>{let n=t.readCreds();if(!n.token||!n.cloudUrl)return{error:"penzor-not-logged-in"};let r=e?.vault,s=(typeof r=="string"?r:"default").trim()||"default";if(!/^[A-Za-z0-9_-]{1,64}$/.test(s)||s===Bt)return{error:"penzor-bad-vault"};let i=await xi(n.cloudUrl,n.token);if("error"in i)return i;let o=n.token;return{remote:zt({baseUrl:n.cloudUrl,vault:s,getToken:()=>o}),fingerprint:`penzor:${n.cloudUrl.replace(/\/+$/,"")}|u:${i.id}|${s}`,maxFileBytes:kr}}),t.log('[forsion-extend] remote-sync backend "penzor" registered')}import{readFileSync as Ci,writeFileSync as Ti,mkdirSync as Ai,chmodSync as Ii,renameSync as Ri}from"node:fs";import{join as $i}from"node:path";function Te(t,e){try{let n=new URL(t);if(n.protocol!=="https:"&&n.protocol!=="http:")return null;let r=e.split(".")[1];if(!r)return null;let s=r.replace(/-/g,"+").replace(/_/g,"/"),i=Uint8Array.from(atob(s),l=>l.charCodeAt(0)),o=JSON.parse(new TextDecoder().decode(i)),a=o.userId??o.sub;return typeof a!="string"&&typeof a!="number"||!String(a).trim()?null:`${n.origin}${n.pathname.replace(/\/+$/,"")}::${String(a)}`}catch{return null}}function kn(t){try{let e=t.split(".")[1];if(!e)return null;let n=JSON.parse(Buffer.from(e,"base64url").toString("utf8"));return n&&typeof n=="object"?n:null}catch{return null}}function xr(t,e=Date.now()){let n=kn(t)?.iat;return typeof n=="number"?e-n*1e3:1/0}function Di(t,e=Date.now()){let n=kn(t)?.exp;return typeof n=="number"?n*1e3-e:1/0}var Pi=36e5;function Cr(t,e=Date.now()){return!!t&&xr(t,e)>=Pi}async function Tr(t,e,n=8e3,r){if(!t||!e)return null;let s=t.replace(/\/+$/,"");try{let i=await fetch(`${s}/api/auth/refresh`,{method:"POST",headers:{Authorization:`Bearer ${e}`,...r?{"X-Forsion-Client":r}:{}},signal:AbortSignal.timeout(n)});if(!i.ok)return null;let o=await i.json().catch(()=>null),a=typeof o?.token=="string"?o.token:"";return a&&a!==e?a:null}catch{return null}}var qt=(t,e)=>`${t.replace(/\/+$/,"")}\0${e}`,Mi=(t,e)=>new Promise((n,r)=>{let s=()=>{clearTimeout(i),r(new Error("Sign-in cancelled."))},i=setTimeout(()=>{e.removeEventListener("abort",s),n()},t);e.aborted?s():e.addEventListener("abort",s,{once:!0})});function Ar(t){let e=()=>$i(t.homeDir(),"auth-accounts.json"),n=(m,c)=>{Ai(t.homeDir(),{recursive:!0});let h=`${m}.tmp`;Ti(h,JSON.stringify(c,null,2),{encoding:"utf8",mode:384}),Ii(h,384),Ri(h,m)},r=()=>{try{let m=JSON.parse(Ci(e(),"utf8"));return Array.isArray(m.accounts)?m.accounts.filter(c=>c&&typeof c.token=="string"&&c.id===Te(c.cloudUrl,c.token)):[]}catch{return[]}},s=(m,c)=>{let h=Te(m.cloudUrl||"",m.token||"");if(!h||!m.token||!m.cloudUrl)return;let g=r(),S=g.find(R=>R.id===h),y=kn(m.token),A={...S,id:h,cloudUrl:m.cloudUrl.replace(/\/+$/,""),token:m.token,username:c?.username||S?.username||y?.username,nickname:c?.nickname||S?.nickname};JSON.stringify(S)!==JSON.stringify(A)&&n(e(),{version:1,accounts:[...g.filter(R=>R.id!==h),A]})},i=()=>{let m=t.readCreds();s(m);let c=Te(m.cloudUrl,m.token);return r().map(({token:h,...g})=>({...g,active:g.id===c}))},o=m=>{let c=r().find(h=>h.id===m);if(!c)throw new Error("Account is no longer signed in. Sign in again.");return{cloudUrl:c.cloudUrl,token:c.token}},a=m=>{let c=Te(m.cloudUrl||"",m.token||"");c&&n(e(),{version:1,accounts:r().filter(h=>h.id!==c)})},l=null;return{rememberForsionAccount:s,forsionAccounts:i,savedForsionAccount:o,forgetForsionAccount:a,cancelForsionLogin:()=>{l?.abort(),l=null},forsionDeviceLogin:async(m,c,h)=>{if(l)throw new Error("A sign-in is already in progress.");if(!m)throw new Error("\u8BF7\u5148\u586B\u5199 Forsion \u4E91\u7AEF\u5730\u5740(\u6216\u8BBE\u7F6E\u73AF\u5883\u53D8\u91CF TANGU_CLOUD_URL)");let g=new AbortController;l=g;let S=()=>{if(g.signal.aborted||l!==g)throw new Error("Sign-in cancelled.")};try{let y=m.replace(/\/+$/,""),A;try{A=await fetch(`${y}/api/auth/cli/start`,{method:"POST",headers:{"Content-Type":"application/json"},body:"{}",signal:AbortSignal.any([g.signal,AbortSignal.timeout(15e3)])}).then(L=>L.json())}catch(L){throw new Error(`\u65E0\u6CD5\u8FDE\u63A5 ${y}:${L?.message||L}`)}if(S(),!A?.device_code)throw new Error("\u4E91\u7AEF\u4E0D\u652F\u6301 CLI \u767B\u5F55(/api/auth/cli/start \u8FD4\u56DE\u5F02\u5E38)");let R=A.verification_uri_complete||`${A.verification_uri}?code=${A.user_code}`,T=new URL(`${y}/auth`);T.searchParams.set("logout","1"),T.searchParams.set("app","forsion-desktop"),T.searchParams.set("redirect",R);let I=T.toString();c?.({url:I,userCode:String(A.user_code||"")}),t.openExternal(I);let D=Date.now()+(A.expires_in||600)*1e3,P=(A.interval||2)*1e3;for(;Date.now()<D;){await Mi(P,g.signal),S();let L=null;try{L=await fetch(`${y}/api/auth/cli/poll`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({device_code:A.device_code}),signal:AbortSignal.any([g.signal,AbortSignal.timeout(15e3)])})}catch{S();continue}if(S(),L.status===410)throw new Error("\u767B\u5F55\u7801\u5DF2\u8FC7\u671F,\u8BF7\u91CD\u65B0\u53D1\u8D77\u767B\u5F55");let H=await L.json().catch(()=>({status:"pending"}));if(S(),H.status==="approved"&&H.token){let Q={cloudUrl:y,token:H.token};return await h(Q,S),S(),{token:H.token,cloudUrl:y}}}throw new Error("\u767B\u5F55\u8D85\u65F6,\u8BF7\u91CD\u8BD5")}finally{l===g&&(l=null)}},readAccounts:r}}var Ir=["homeDir","appVersion","broadcast","accountBackendState","accountTransition","accountCommit","accountClear","writeCreds","onExternalCredsChange","setTokenRefresher","readCreds"],vn=t=>Ir.every(e=>typeof t[e]=="function");function xn(t){let e={ok:!1,error:"untrusted"},n={loggedIn:!1,error:"untrusted"},r=Ar(t),s=0,i=()=>{let a=t.readCreds();return qt(a.cloudUrl,a.token)},o=null;t.handle("auth:status",async a=>{if(!t.isTrustedSender(a))return n;let l=s,d=i(),{base:f}=await t.getCloud(),m=t.readCreds().token,c=m?await wt(f,m):null,h=await t.accountBackendState(),{base:g}=await t.getCloud(),S=t.readCreds(),y=qt(g,S.token)!==qt(f,m),A=qt(f,m);!y&&c?.status==="ok"&&c.user&&(o={key:A,user:c.user},r.rememberForsionAccount({...S,cloudUrl:f},c.user));let R=y?void 0:c?.status==="ok"?c.user:c?.status==="offline"&&o?.key===A?o.user:void 0;if(y)return{loggedIn:!!S.token,tokenValid:null,cloudUrl:g,accountId:Te(g,S.token),username:null,nickname:null,avatar:null,membershipTier:null,tokenSource:S.token?"tangu-login":null,backendState:h};if(c?.status==="expired"){await t.accountTransition(async()=>{if(l!==s||i()!==d)return;let I=()=>{if(l!==s||i()!==d)throw vr};try{await t.accountClear(I,()=>{t.log("[auth] token \u5DF2\u5931\u6548(\u670D\u52A1\u7AEF 401/403),\u81EA\u52A8\u767B\u51FA"),++s,r.cancelForsionLogin(),r.forgetForsionAccount(t.readCreds()),o=null})}catch(D){if(D!==vr)throw D}});let T=t.readCreds();return{loggedIn:!!T.token,tokenValid:null,cloudUrl:T.cloudUrl||f,accountId:Te(T.cloudUrl||f,T.token),username:null,nickname:null,avatar:null,membershipTier:null,tokenSource:T.token?"tangu-login":null,backendState:h}}return{loggedIn:!!m,tokenValid:c&&c.status==="ok"?!0:null,cloudUrl:f,accountId:Te(f,m),username:R?.username||null,nickname:R?.nickname||null,avatar:R?.avatar||null,membershipTier:R?.membershipTier||null,tokenSource:m?"tangu-login":null,backendState:h}}),t.handle("auth:accounts",a=>t.isTrustedSender(a)?r.forsionAccounts():[]),t.handle("auth:switchAccount",async(a,l)=>{if(!t.isTrustedSender(a))return e;if(typeof l!="string")throw new Error("Invalid account.");let d=++s;return r.cancelForsionLogin(),t.accountTransition(async()=>{let f=r.savedForsionAccount(l);return await t.accountCommit(f,()=>{if(d!==s)throw new Error("Account switch cancelled.")},()=>{r.rememberForsionAccount(f),o=null}),{ok:!0,cloudUrl:f.cloudUrl||""}})}),t.handle("auth:forsionLogin",async(a,l)=>{if(!t.isTrustedSender(a))return e;let d=++s;r.cancelForsionLogin();let{base:f}=await t.getCloud();if(d!==s)throw new Error("Sign-in cancelled.");let m=(l||f||"").trim();return{ok:!0,cloudUrl:(await r.forsionDeviceLogin(m,h=>t.broadcast("auth:device",h),(h,g)=>t.accountTransition(()=>t.accountCommit(h,()=>{if(g(),d!==s)throw new Error("Sign-in cancelled.")},()=>{r.rememberForsionAccount(h),o=null})))).cloudUrl}}),t.handle("auth:logout",async a=>t.isTrustedSender(a)?(++s,r.cancelForsionLogin(),t.accountTransition(async()=>{let{base:l}=await t.getCloud(),d=t.readCreds();return await t.accountClear(void 0,()=>{r.forgetForsionAccount(d),o=null,l&&d.token&&fetch(`${l}/api/auth/logout`,{method:"POST",headers:{Authorization:`Bearer ${d.token}`},signal:AbortSignal.timeout(5e3)}).catch(()=>{})}),{ok:!0}})):e),t.onExternalCredsChange(({previous:a,current:l})=>{++s,r.cancelForsionLogin(),a.token&&!l.token&&r.forgetForsionAccount(a),o=null,r.rememberForsionAccount(l)}),t.setTokenRefresher(async a=>{let l=s,d=i(),f=t.readCreds().token;if(!Cr(f))return;let{base:m}=await t.getCloud(),c=await Tr(m,f,a,`desktop/${t.appVersion()}`);if(!c){t.log("[auth] \u6ED1\u52A8\u7EED\u671F\u672A\u6210\u529F(\u79BB\u7EBF/\u8001\u7248\u672C server/\u8FD9\u679A\u5DF2\u5931\u6548),\u7EE7\u7EED\u7528\u65E7 token");return}l!==s||i()!==d||(r.rememberForsionAccount({cloudUrl:m,token:c}),t.writeCreds({cloudUrl:m,token:c}),t.log("[auth] \u767B\u5F55\u6001\u5DF2\u6ED1\u52A8\u7EED\u671F(\u6709\u6548\u671F\u91CD\u65B0\u8BA1\u6EE1 2 \u5468)"))}),t.log("[forsion-extend] account core registered")}var vr=Symbol("stale-auth-intent");import{promises as dt}from"node:fs";import Ze from"node:path";import{createHash as Oi}from"node:crypto";var Cn=null;function Rr(t){Cn=t}function be(){if(!Cn)throw new Error("amadeus sync env not set (registerAmadeus factory has not run)");return Cn}var Se=()=>be().accountId();function bt(t=Se()){return t?Oi("sha256").update(t).digest("hex"):"signed-out"}var Ae=(t=Se())=>be().readConfig(t),je=(t,e=Se())=>be().writeConfig(t,e),rt=(t,e=Se())=>be().updateConfig(t,e),Be=(t=Se())=>be().cloudVaultDir(t),Wt=t=>be().isManagedCloudVault(t);import{createHash as Lo}from"node:crypto";import{promises as oe,existsSync as ls}from"node:fs";import ue from"node:path";import{EventEmitter as uo}from"node:events";import{stat as fo}from"node:fs";import{readdir as mo,stat as ho}from"node:fs/promises";import*as X from"node:path";import{lstat as $r,readdir as Ni,realpath as Ui,stat as ji}from"node:fs/promises";import{join as Fi,resolve as Li,sep as Dr}from"node:path";import{Readable as Hi}from"node:stream";var _e={FILE_TYPE:"files",DIR_TYPE:"directories",FILE_DIR_TYPE:"files_directories",EVERYTHING_TYPE:"all"},st={root:".",fileFilter:t=>!0,directoryFilter:t=>!0,type:_e.FILE_TYPE,lstat:!1,depth:2147483648,alwaysStat:!1,highWaterMark:256};Object.freeze(st);var Nr="READDIRP_RECURSIVE_ERROR",zi=new Set(["ENOENT","EPERM","EACCES","ELOOP",Nr]),Pr=[_e.DIR_TYPE,_e.EVERYTHING_TYPE,_e.FILE_DIR_TYPE,_e.FILE_TYPE],Bi=new Set([_e.DIR_TYPE,_e.EVERYTHING_TYPE,_e.FILE_DIR_TYPE]),qi=new Set([_e.EVERYTHING_TYPE,_e.FILE_DIR_TYPE,_e.FILE_TYPE]),Wi=t=>zi.has(t.code),Vi=process.platform==="win32",Mr=t=>!0,Or=t=>{if(t===void 0)return Mr;if(typeof t=="function")return t;if(typeof t=="string"){let e=t.trim();return n=>n.basename===e}if(Array.isArray(t)){let e=t.map(n=>n.trim());return n=>e.some(r=>n.basename===r)}return Mr},Tn=class extends Hi{parents;reading;parent;_stat;_maxDepth;_wantsDir;_wantsFile;_wantsEverything;_root;_isDirent;_statsProp;_rdOptions;_fileFilter;_directoryFilter;_relStart;constructor(e={}){super({objectMode:!0,autoDestroy:!0,highWaterMark:e.highWaterMark??st.highWaterMark});let n={...st,...e},r=n.root??st.root,s=n.type??st.type;this._fileFilter=Or(n.fileFilter),this._directoryFilter=Or(n.directoryFilter);let i=n.lstat?$r:ji;Vi?this._stat=a=>i(a,{bigint:!0}):this._stat=i,this._maxDepth=n.depth!=null&&Number.isSafeInteger(n.depth)?n.depth:st.depth,this._wantsDir=Bi.has(s),this._wantsFile=qi.has(s),this._wantsEverything=s===_e.EVERYTHING_TYPE,this._root=Li(r),this._relStart=this._root.endsWith(Dr)?this._root.length:this._root.length+1,this._isDirent=!n.alwaysStat,this._statsProp=this._isDirent?"dirent":"stats",this._rdOptions={encoding:"utf8",withFileTypes:this._isDirent};let o={path:this._root,depth:1};o.pending=this._exploreDir(this._root,1),this.parents=[o],this.reading=!1,this.parent=void 0}async _read(e){if(!this.reading){this.reading=!0;try{for(;!this.destroyed&&e>0;){let n=this.parent,r=n&&n.files;if(r&&r.length>0){let{path:s,depth:i}=n,o=r.splice(0,e).map(l=>this._formatEntry(l,s)),a=this._isDirent?o:await Promise.all(o);for(let l of a){if(!l)continue;if(this.destroyed)return;let d=this._getEntryType(l);typeof d!="string"&&(d=await d),d==="directory"&&this._directoryFilter(l)?(i<=this._maxDepth&&this.parents.push({path:l.fullPath,depth:i+1}),this._wantsDir&&(this.push(l),e--)):(d==="file"||this._includeAsFile(l))&&this._fileFilter(l)&&this._wantsFile&&(this.push(l),e--)}}else{let s=this.parents.pop();if(!s){this.push(null);break}let i=s.pending??this._exploreDir(s.path,s.depth),o=this.parents[this.parents.length-1];if(o&&!o.pending&&(o.pending=this._exploreDir(o.path,o.depth)),this.parent=await i,this.destroyed)return}}}catch(n){this.destroy(n)}finally{this.reading=!1}}}async _exploreDir(e,n){let r;try{r=await Ni(e,this._rdOptions)}catch(s){this._onError(s)}return{files:r,depth:n,path:e}}_formatEntry(e,n){let r=this._isDirent?e.name:e,s=Fi(n,r),i={path:s.slice(this._relStart),fullPath:s,basename:r};return this._isDirent?(i.dirent=e,i):this._stat(s).then(o=>(i.stats=o,i),o=>{this._onError(o)})}_onError(e){Wi(e)&&!this.destroyed?this.emit("warn",e):this.destroy(e)}_getEntryType(e){if(!e||!(this._statsProp in e))return"";let n=e[this._statsProp];return n.isFile()?"file":n.isDirectory()?"directory":n.isSymbolicLink()?this._getSymlinkEntryType(e):""}async _getSymlinkEntryType(e){let n=e.fullPath;try{let r=await Ui(n),s=await $r(r);if(s.isFile())return"file";if(s.isDirectory()){let i=r.length;if(n.startsWith(r)&&n[i]===Dr){let o=new Error(`Circular symlink detected: "${n}" points to "${r}"`);return o.code=Nr,this._onError(o),""}return"directory"}}catch(r){this._onError(r)}return""}_includeAsFile(e){let n=e&&e[this._statsProp];return n&&this._wantsEverything&&!n.isDirectory()}};function Ur(t,e={}){let n=e.entryType||e.type;if(n==="both"&&(n=_e.FILE_DIR_TYPE),t){if(typeof t!="string")throw new TypeError("readdirp: root argument must be a string. Usage: readdirp(root, options)");if(n&&!Pr.includes(n))throw new Error(`readdirp: Invalid type passed. Use one of ${Pr.join(", ")}`)}else throw new Error("readdirp: root argument is required. Usage: readdirp(root, options)");let r={...e,root:t};return n&&(r.type=n),new Tn(r)}import{watch as Yi,unwatchFile as jr,watchFile as Gi}from"node:fs";import{realpath as An,lstat as Ji,open as Ki,stat as Lr}from"node:fs/promises";import{type as Xi}from"node:os";import*as re from"node:path";var Zi="data",$n="end",Hr="close",Kt=()=>{};var Xt=process.platform,Dn=Xt==="win32",Qi=Xt==="darwin",eo=Xt==="linux",to=Xt==="freebsd",zr=Xi()==="OS400",ie={ALL:"all",READY:"ready",ADD:"add",CHANGE:"change",ADD_DIR:"addDir",UNLINK:"unlink",UNLINK_DIR:"unlinkDir",RAW:"raw",ERROR:"error"},Ie=ie,no="watch",ro={lstat:Ji,stat:Lr},Xe="listeners",Vt="errHandlers",it="rawEmitters",so=[Xe,Vt,it],io=new Set(["3dm","3ds","3g2","3gp","7z","a","aac","adp","afdesign","afphoto","afpub","ai","aif","aiff","alz","ape","apk","appimage","ar","arj","asf","au","avi","bak","baml","bh","bin","bk","bmp","btif","bz2","bzip2","cab","caf","cgm","class","cmx","cpio","cr2","cur","dat","dcm","deb","dex","djvu","dll","dmg","dng","doc","docm","docx","dot","dotm","dra","DS_Store","dsk","dts","dtshd","dvb","dwg","dxf","ecelp4800","ecelp7470","ecelp9600","egg","eol","eot","epub","exe","f4v","fbs","fh","fla","flac","flatpak","fli","flv","fpx","fst","fvt","g3","gh","gif","graffle","gz","gzip","h261","h263","h264","icns","ico","ief","img","ipa","iso","jar","jpeg","jpg","jpgv","jpm","jxr","key","ktx","lha","lib","lvp","lz","lzh","lzma","lzo","m3u","m4a","m4v","mar","mdi","mht","mid","midi","mj2","mka","mkv","mmr","mng","mobi","mov","movie","mp3","mp4","mp4a","mpeg","mpg","mpga","mxu","nef","npx","numbers","nupkg","o","odp","ods","odt","oga","ogg","ogv","otf","ott","pages","pbm","pcx","pdb","pdf","pea","pgm","pic","png","pnm","pot","potm","potx","ppa","ppam","ppm","pps","ppsm","ppsx","ppt","pptm","pptx","psd","pya","pyc","pyo","pyv","qt","rar","ras","raw","resources","rgb","rip","rlc","rmf","rmvb","rpm","rtf","rz","s3m","s7z","scpt","sgi","shar","snap","sil","sketch","slk","smv","snk","so","stl","suo","sub","swf","tar","tbz","tbz2","tga","tgz","thmx","tif","tiff","tlz","ttc","ttf","txz","udf","uvh","uvi","uvm","uvp","uvs","uvu","viv","vob","war","wav","wax","wbmp","wdp","weba","webm","webp","whl","wim","wm","wma","wmv","wmx","woff","woff2","wrm","wvx","xbm","xif","xla","xlam","xls","xlsb","xlsm","xlsx","xlt","xltm","xltx","xm","xmind","xpi","xpm","xwd","xz","z","zip","zipx"]),oo=t=>io.has(re.extname(t).slice(1).toLowerCase()),Rn=(t,e)=>{t instanceof Set?t.forEach(e):e(t)},St=(t,e,n)=>{let r=t[e];r instanceof Set||(t[e]=r=new Set([r])),r.add(n)},ao=t=>e=>{let n=t[e];n instanceof Set?n.clear():delete t[e]},Et=(t,e,n)=>{let r=t[e];r instanceof Set?r.delete(n):r===n&&delete t[e]},Br=t=>t instanceof Set?t.size===0:!t,Yt=new Map;function Fr(t,e,n,r,s){let i=(o,a)=>{n(t),s(o,a,{watchedPath:t}),a&&t!==a&&Gt(re.resolve(t,a),Xe,re.join(t,a))};try{return Yi(t,{persistent:e.persistent},i)}catch(o){r(o);return}}var Gt=(t,e,n,r,s)=>{let i=Yt.get(t);i&&Rn(i[e],o=>{o(n,r,s)})},lo=(t,e,n,r)=>{let{listener:s,errHandler:i,rawEmitter:o}=r,a=Yt.get(e),l;if(!n.persistent)return l=Fr(t,n,s,i,o),l?l.close.bind(l):void 0;if(a)St(a,Xe,s),St(a,Vt,i),St(a,it,o);else{if(l=Fr(t,n,Gt.bind(null,e,Xe),i,Gt.bind(null,e,it)),!l)return;l.on(Ie.ERROR,async d=>{let f=Gt.bind(null,e,Vt);if(a&&(a.watcherUnusable=!0),Dn&&d.code==="EPERM")try{await(await Ki(t,"r")).close(),f(d)}catch{}else f(d)}),a={listeners:s,errHandlers:i,rawEmitters:o,watcher:l},Yt.set(e,a)}return()=>{Et(a,Xe,s),Et(a,Vt,i),Et(a,it,o),Br(a.listeners)&&(a.watcher.close(),Yt.delete(e),so.forEach(ao(a)),a.watcher=void 0,Object.freeze(a))}},In=new Map,co=(t,e,n,r)=>{let{listener:s,rawEmitter:i}=r,o=In.get(e),a=o&&o.options;return a&&(a.persistent<n.persistent||a.interval>n.interval)&&(jr(e),o=void 0),o?(St(o,Xe,s),St(o,it,i)):(o={listeners:s,rawEmitters:i,options:n,watcher:Gi(e,n,(l,d)=>{Rn(o.rawEmitters,m=>{m(Ie.CHANGE,e,{curr:l,prev:d})});let f=l.mtimeMs;(l.size!==d.size||f>d.mtimeMs||f===0)&&Rn(o.listeners,m=>m(t,l))})},In.set(e,o)),()=>{Et(o,Xe,s),Et(o,it,i),Br(o.listeners)&&(In.delete(e),jr(e),o.options=o.watcher=void 0,Object.freeze(o))}},Jt=class{fsw;_boundHandleError;constructor(e){this.fsw=e,this._boundHandleError=n=>e._handleError(n)}_watchWithNodeFs(e,n){let r=this.fsw.options,s=re.dirname(e),i=re.basename(e);this.fsw._getWatchedDir(s).add(i);let a=re.resolve(e),l={persistent:r.persistent};n||(n=Kt);let d;if(r.usePolling){let f=r.interval!==r.binaryInterval;l.interval=f&&oo(i)?r.binaryInterval:r.interval,d=co(e,a,l,{listener:n,rawEmitter:this.fsw._emitRaw})}else d=lo(e,a,l,{listener:n,errHandler:this._boundHandleError,rawEmitter:this.fsw._emitRaw});return d}_handleFile(e,n,r){if(this.fsw.closed)return;let s=re.dirname(e),i=re.basename(e),o=this.fsw._getWatchedDir(s),a=n;if(o.has(i))return;let l=async(f,m)=>{if(this.fsw._throttle(no,e,5)){if(!m||m.mtimeMs===0)try{let c=await Lr(e);if(this.fsw.closed)return;let h=c.atimeMs,g=c.mtimeMs;if((!h||h<=g||g!==a.mtimeMs)&&this.fsw._emit(Ie.CHANGE,e,c),(Qi||eo||to)&&a.ino!==c.ino){this.fsw._closeFile(f),a=c;let S=this._watchWithNodeFs(e,l);S&&this.fsw._addPathCloser(f,S)}else a=c}catch{this.fsw._remove(s,i)}else if(o.has(i)){let c=m.atimeMs,h=m.mtimeMs;(!c||c<=h||h!==a.mtimeMs)&&this.fsw._emit(Ie.CHANGE,e,m),a=m}}},d=this._watchWithNodeFs(e,l);if(!(r&&this.fsw.options.ignoreInitial)&&this.fsw._isntIgnored(e)){if(!this.fsw._throttle(Ie.ADD,e,0))return;this.fsw._emit(Ie.ADD,e,n)}return d}async _handleSymlink(e,n,r,s){if(this.fsw.closed)return;let i=e.fullPath,o=this.fsw._getWatchedDir(n);if(!this.fsw.options.followSymlinks){this.fsw._incrReadyCount();let a;try{a=await An(r)}catch{return this.fsw._emitReady(),!0}return this.fsw.closed?void 0:(o.has(s)?this.fsw._symlinkPaths.get(i)!==a&&(this.fsw._symlinkPaths.set(i,a),this.fsw._emit(Ie.CHANGE,r,e.stats)):(o.add(s),this.fsw._symlinkPaths.set(i,a),this.fsw._emit(Ie.ADD,r,e.stats)),this.fsw._emitReady(),!0)}if(this.fsw._symlinkPaths.has(i))return!0;this.fsw._symlinkPaths.set(i,!0)}_handleRead(e,n,r,s,i,o,a){e=re.join(e,"");let l=s?`${e}:${s}`:e;if(a=this.fsw._throttle("readdir",l,1e3),!a)return;let d=this.fsw._getWatchedDir(r.path),f=new Set,m=this.fsw._readdirp(e,{fileFilter:c=>r.filterPath(c),directoryFilter:c=>r.filterDir(c)});if(m)return m.on(Zi,async c=>{if(this.fsw.closed){m=void 0;return}let h=c.path,g=re.join(e,h);if(f.add(h),!(c.stats.isSymbolicLink()&&await this._handleSymlink(c,e,g,h))){if(this.fsw.closed){m=void 0;return}(h===s||!s&&!d.has(h))&&(this.fsw._incrReadyCount(),g=re.join(i,re.relative(i,g)),this._addToNodeFs(g,n,r,o+1))}}).on(Ie.ERROR,this._boundHandleError),new Promise((c,h)=>{if(!m)return h();m.once($n,()=>{if(this.fsw.closed){m=void 0;return}let g=a?a.clear():!1;c(void 0),d.getChildren().filter(S=>S!==e&&!f.has(S)).forEach(S=>{this.fsw._remove(e,S)}),m=void 0,g&&this._handleRead(e,!1,r,s,i,o,a)})})}async _handleDir(e,n,r,s,i,o,a){let l=this.fsw._getWatchedDir(re.dirname(e)),d=l.has(re.basename(e));!(r&&this.fsw.options.ignoreInitial)&&!i&&!d&&this.fsw._emit(Ie.ADD_DIR,e,n),l.add(re.basename(e)),this.fsw._getWatchedDir(e);let f,m,c=this.fsw.options.depth;if((c==null||s<=c)&&!this.fsw._symlinkPaths.has(a)){if(!i&&(await this._handleRead(e,r,o,i,e,s,f),this.fsw.closed))return;m=this._watchWithNodeFs(e,(h,g)=>{g&&g.mtimeMs===0||this._handleRead(h,!1,o,i,e,s,f)})}return m}async _addToNodeFs(e,n,r,s,i){let o=this.fsw._emitReady;if(this.fsw._isIgnored(e)||this.fsw.closed)return o(),!1;let a=this.fsw._getWatchHelpers(e);r&&(a.filterPath=l=>r.filterPath(l),a.filterDir=l=>r.filterDir(l));try{let l=await ro[a.statMethod](a.watchPath);if(this.fsw.closed)return;if(this.fsw._isIgnored(a.watchPath,l))return o(),!1;let d=this.fsw.options.followSymlinks,f;if(l.isDirectory()){let m=re.resolve(e),c=d?await An(e):e;if(this.fsw.closed||(f=await this._handleDir(a.watchPath,l,n,s,i,a,c),this.fsw.closed))return;m!==c&&c!==void 0&&this.fsw._symlinkPaths.set(m,c)}else if(l.isSymbolicLink()){let m=d?await An(e):e;if(this.fsw.closed)return;let c=re.dirname(a.watchPath);if(this.fsw._getWatchedDir(c).add(a.watchPath),this.fsw._emit(Ie.ADD,a.watchPath,l),f=await this._handleDir(c,l,n,s,e,a,m),this.fsw.closed)return;m!==void 0&&this.fsw._symlinkPaths.set(re.resolve(e),m)}else f=this._handleFile(a.watchPath,l,n);return o(),f&&this.fsw._addPathCloser(e,f),!1}catch(l){if(this.fsw._handleError(l))return o(),e}}};var Pn="/",go="//",Gr=".",po="..",yo="string",wo=/\\/g,Jr=/\/\//g,bo=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/,So=/^\.[/\\]/;function Zt(t){return Array.isArray(t)?t:[t]}var Mn=t=>typeof t=="object"&&t!==null&&!(t instanceof RegExp);function Eo(t){return typeof t=="function"?t:typeof t=="string"?e=>t===e:t instanceof RegExp?e=>t.test(e):typeof t=="object"&&t!==null?e=>{if(t.path===e)return!0;if(t.recursive){let n=X.relative(t.path,e);return n?!n.startsWith("..")&&!X.isAbsolute(n):!1}return!1}:()=>!1}function _o(t){if(typeof t!="string")throw new Error("string expected");t=X.normalize(t),t=t.replace(/\\/g,"/");let e=!1;return t.startsWith("//")&&(e=!0),t=t.replace(Jr,"/"),e&&(t="/"+t),t}function qr(t,e,n){let r=_o(e);for(let s=0;s<t.length;s++){let i=t[s];if(i(r,n))return!0}return!1}function ko(t,e){if(t==null)throw new TypeError("anymatch: specify first argument");let r=Zt(t).map(s=>Eo(s));return e==null?(s,i)=>qr(r,s,i):qr(r,e)}var Wr=t=>{let e=Zt(t).flat();if(!e.every(n=>typeof n===yo))throw new TypeError(`Non-string provided as watch path: ${e}`);return e.map(Kr)},Vr=t=>{let e=t.replace(wo,Pn),n=!1;return e.startsWith(go)&&(n=!0),e=e.replace(Jr,Pn),n&&(e=Pn+e),e},Kr=t=>Vr(X.normalize(Vr(t))),Yr=(t="")=>e=>typeof e=="string"?Kr(X.isAbsolute(e)?e:X.join(t,e)):e,vo=(t,e)=>X.isAbsolute(t)?t:X.join(e,t),xo=Object.freeze(new Set),On=class{path;_removeWatcher;items;constructor(e,n){this.path=e,this._removeWatcher=n,this.items=new Set}add(e){let{items:n}=this;n&&e!==Gr&&e!==po&&n.add(e)}async remove(e){let{items:n}=this;if(!n||(n.delete(e),n.size>0))return;let r=this.path;try{await mo(r)}catch{this._removeWatcher&&this._removeWatcher(X.dirname(r),X.basename(r))}}has(e){let{items:n}=this;if(n)return n.has(e)}getChildren(){let{items:e}=this;return e?[...e.values()]:[]}dispose(){this.items.clear(),this.path="",this._removeWatcher=Kt,this.items=xo,Object.freeze(this)}},Co="stat",To="lstat",Nn=class{fsw;path;watchPath;fullWatchPath;dirParts;followSymlinks;statMethod;constructor(e,n,r){this.fsw=r;let s=e;this.path=e=e.replace(So,""),this.watchPath=s,this.fullWatchPath=X.resolve(s),this.dirParts=[],this.dirParts.forEach(i=>{i.length>1&&i.pop()}),this.followSymlinks=n,this.statMethod=n?Co:To}entryPath(e){return X.join(this.watchPath,X.relative(this.watchPath,e.fullPath))}filterPath(e){let{stats:n}=e;if(n&&n.isSymbolicLink())return this.filterDir(e);let r=this.entryPath(e);return this.fsw._isntIgnored(r,n)&&this.fsw._hasReadPermissions(n)}filterDir(e){return this.fsw._isntIgnored(this.entryPath(e),e.stats)}},Qt=class extends uo{closed;options;_closers;_ignoredPaths;_throttled;_streams;_symlinkPaths;_watched;_pendingWrites;_pendingUnlinks;_readyCount;_emitReady;_closePromise;_userIgnored;_readyEmitted;_emitRaw;_boundRemove;_nodeFsHandler;constructor(e={}){super(),this.closed=!1,this._closers=new Map,this._ignoredPaths=new Set,this._throttled=new Map,this._streams=new Set,this._symlinkPaths=new Map,this._watched=new Map,this._pendingWrites=new Map,this._pendingUnlinks=new Map,this._readyCount=0,this._readyEmitted=!1;let n=e.awaitWriteFinish,r={stabilityThreshold:2e3,pollInterval:100},s={persistent:!0,ignoreInitial:!1,ignorePermissionErrors:!1,interval:100,binaryInterval:300,followSymlinks:!0,usePolling:!1,atomic:!0,...e,ignored:e.ignored?Zt(e.ignored):Zt([]),awaitWriteFinish:n===!0?r:typeof n=="object"?{...r,...n}:!1};zr&&(s.usePolling=!0),s.atomic===void 0&&(s.atomic=!s.usePolling);let i=process.env.CHOKIDAR_USEPOLLING;if(i!==void 0){let l=i.toLowerCase();l==="false"||l==="0"?s.usePolling=!1:l==="true"||l==="1"?s.usePolling=!0:s.usePolling=!!l}let o=process.env.CHOKIDAR_INTERVAL;o&&(s.interval=Number.parseInt(o,10));let a=0;this._emitReady=()=>{a++,a>=this._readyCount&&(this._emitReady=Kt,this._readyEmitted=!0,process.nextTick(()=>this.emit(ie.READY)))},this._emitRaw=(...l)=>this.emit(ie.RAW,...l),this._boundRemove=this._remove.bind(this),this.options=s,this._nodeFsHandler=new Jt(this),Object.freeze(s)}_addIgnoredPath(e){if(Mn(e)){for(let n of this._ignoredPaths)if(Mn(n)&&n.path===e.path&&n.recursive===e.recursive)return}this._ignoredPaths.add(e)}_removeIgnoredPath(e){if(this._ignoredPaths.delete(e),typeof e=="string")for(let n of this._ignoredPaths)Mn(n)&&n.path===e&&this._ignoredPaths.delete(n)}add(e,n,r){let{cwd:s}=this.options;this.closed=!1,this._closePromise=void 0;let i=Wr(e);return s&&(i=i.map(o=>vo(o,s))),i.forEach(o=>{this._removeIgnoredPath(o)}),this._userIgnored=void 0,this._readyCount||(this._readyCount=0),this._readyCount+=i.length,Promise.all(i.map(async o=>{let a=await this._nodeFsHandler._addToNodeFs(o,!r,void 0,0,n);return a&&this._emitReady(),a})).then(o=>{this.closed||o.forEach(a=>{a&&this.add(X.dirname(a),X.basename(n||a))})}),this}unwatch(e){if(this.closed)return this;let n=Wr(e),{cwd:r}=this.options;return n.forEach(s=>{!X.isAbsolute(s)&&!this._closers.has(s)&&(r&&(s=X.join(r,s)),s=X.resolve(s)),this._closePath(s),this._addIgnoredPath(s),this._watched.has(s)&&this._addIgnoredPath({path:s,recursive:!0}),this._userIgnored=void 0}),this}close(){if(this._closePromise)return this._closePromise;this.closed=!0,this.removeAllListeners();let e=[];return this._closers.forEach(n=>n.forEach(r=>{let s=r();s instanceof Promise&&e.push(s)})),this._streams.forEach(n=>n.destroy()),this._userIgnored=void 0,this._readyCount=0,this._readyEmitted=!1,this._watched.forEach(n=>n.dispose()),this._closers.clear(),this._watched.clear(),this._streams.clear(),this._symlinkPaths.clear(),this._throttled.clear(),this._closePromise=e.length?Promise.all(e).then(()=>{}):Promise.resolve(),this._closePromise}getWatched(){let e={};return this._watched.forEach((n,r)=>{let i=(this.options.cwd?X.relative(this.options.cwd,r):r)||Gr;e[i]=n.getChildren().sort()}),e}emitWithAll(e,n){this.emit(e,...n),e!==ie.ERROR&&this.emit(ie.ALL,e,...n)}async _emit(e,n,r){if(this.closed)return;let s=this.options;Dn&&(n=X.normalize(n)),s.cwd&&(n=X.relative(s.cwd,n));let i=[n];r!=null&&i.push(r);let o=s.awaitWriteFinish,a;if(o&&(a=this._pendingWrites.get(n)))return a.lastChange=new Date,this;if(s.atomic){if(e===ie.UNLINK)return this._pendingUnlinks.set(n,[e,...i]),setTimeout(()=>{this._pendingUnlinks.forEach((l,d)=>{this.emit(...l),this.emit(ie.ALL,...l),this._pendingUnlinks.delete(d)})},typeof s.atomic=="number"?s.atomic:100),this;e===ie.ADD&&this._pendingUnlinks.has(n)&&(e=ie.CHANGE,this._pendingUnlinks.delete(n))}if(o&&(e===ie.ADD||e===ie.CHANGE)&&this._readyEmitted){let l=(d,f)=>{d?(e=ie.ERROR,i[0]=d,this.emitWithAll(e,i)):f&&(i.length>1?i[1]=f:i.push(f),this.emitWithAll(e,i))};return this._awaitWriteFinish(n,o.stabilityThreshold,e,l),this}if(e===ie.CHANGE&&!this._throttle(ie.CHANGE,n,50))return this;if(s.alwaysStat&&r===void 0&&(e===ie.ADD||e===ie.ADD_DIR||e===ie.CHANGE)){let l=s.cwd?X.join(s.cwd,n):n,d;try{d=await ho(l)}catch{}if(!d||this.closed)return;i.push(d)}return this.emitWithAll(e,i),this}_handleError(e){let n=e&&e.code;return e&&n!=="ENOENT"&&n!=="ENOTDIR"&&(!this.options.ignorePermissionErrors||n!=="EPERM"&&n!=="EACCES")&&this.emit(ie.ERROR,e),e||this.closed}_throttle(e,n,r){this._throttled.has(e)||this._throttled.set(e,new Map);let s=this._throttled.get(e);if(!s)throw new Error("invalid throttle");let i=s.get(n);if(i)return i.count++,!1;let o,a=()=>{let d=s.get(n),f=d?d.count:0;return s.delete(n),clearTimeout(o),d&&clearTimeout(d.timeoutObject),f};o=setTimeout(a,r);let l={timeoutObject:o,clear:a,count:0};return s.set(n,l),l}_incrReadyCount(){return this._readyCount++}_awaitWriteFinish(e,n,r,s){let i=this.options.awaitWriteFinish;if(typeof i!="object")return;let o=i.pollInterval,a,l=e;this.options.cwd&&!X.isAbsolute(e)&&(l=X.join(this.options.cwd,e));let d=new Date,f=this._pendingWrites;function m(c){fo(l,(h,g)=>{if(h||!f.has(e)){h&&h.code!=="ENOENT"&&s(h);return}let S=Number(new Date);c&&g.size!==c.size&&(f.get(e).lastChange=S);let y=f.get(e);S-y.lastChange>=n?(f.delete(e),s(void 0,g)):a=setTimeout(m,o,g)})}f.has(e)||(f.set(e,{lastChange:d,cancelWait:()=>(f.delete(e),clearTimeout(a),r)}),a=setTimeout(m,o))}_isIgnored(e,n){if(this.options.atomic&&bo.test(e))return!0;if(!this._userIgnored){let{cwd:r}=this.options,i=(this.options.ignored||[]).map(Yr(r)),a=[...[...this._ignoredPaths].map(Yr(r)),...i];this._userIgnored=ko(a,void 0)}return this._userIgnored(e,n)}_isntIgnored(e,n){return!this._isIgnored(e,n)}_getWatchHelpers(e){return new Nn(e,this.options.followSymlinks,this)}_getWatchedDir(e){let n=X.resolve(e);return this._watched.has(n)||this._watched.set(n,new On(n,this._boundRemove)),this._watched.get(n)}_hasReadPermissions(e){return this.options.ignorePermissionErrors?!0:!!(Number(e.mode)&256)}_remove(e,n,r){let s=X.join(e,n),i=X.resolve(s);if(r=r??(this._watched.has(s)||this._watched.has(i)),!this._throttle("remove",s,100))return;!r&&this._watched.size===1&&this.add(e,n,!0),this._getWatchedDir(s).getChildren().forEach(c=>this._remove(s,c));let l=this._getWatchedDir(e),d=l.has(n);l.remove(n),this._symlinkPaths.has(i)&&this._symlinkPaths.delete(i);let f=s;if(this.options.cwd&&(f=X.relative(this.options.cwd,s)),this.options.awaitWriteFinish&&this._pendingWrites.has(f)&&this._pendingWrites.get(f).cancelWait()===ie.ADD)return;this._watched.delete(s),this._watched.delete(i);let m=r?ie.UNLINK_DIR:ie.UNLINK;d&&!this._isIgnored(s)&&this._emit(m,s),this._closePath(s)}_closePath(e){this._closeFile(e);let n=X.dirname(e);this._getWatchedDir(n).remove(X.basename(e))}_closeFile(e){let n=this._closers.get(e);n&&(n.forEach(r=>r()),this._closers.delete(e))}_addPathCloser(e,n){if(!n)return;let r=this._closers.get(e);r||(r=[],this._closers.set(e,r)),r.push(n)}_readdirp(e,n){if(this.closed)return;let r={type:ie.ALL,alwaysStat:!0,lstat:!0,...n,depth:0},s=Ur(e,r);return this._streams.add(s),s.once(Hr,()=>{s=void 0}),s.once($n,()=>{s&&(this._streams.delete(s),s=void 0)}),s}};function Ao(t,e={}){let n=new Qt(e);return n.add(t),n}var Xr={watch:Ao,FSWatcher:Qt};function Io(t,e){let n=Object.create(null);for(let i=0;i<e.length;i++){let o=e[i];n[o]?n[o].push(i):n[o]=[i]}let s=[{buffer1index:-1,buffer2index:-1,chain:null}];for(let i=0;i<t.length;i++){let o=t[i],a=n[o]||[],l=0,d=s[0];for(let f of a){let m;for(m=l;m<s.length&&!(s[m].buffer2index<f&&(m===s.length-1||s[m+1].buffer2index>f));m++);if(m<s.length){let c={buffer1index:i,buffer2index:f,chain:s[m]};if(l===s.length?s.push(d):s[l]=d,l=m+1,d=c,l===s.length)break}}s[l]=d}return s[s.length-1]}function Zr(t,e){let n=Io(t,e),r=[],s=t.length,i=e.length;for(let o=n;o!==null;o=o.chain){let a=s-o.buffer1index-1,l=i-o.buffer2index-1;s=o.buffer1index,i=o.buffer2index,(a||l)&&r.push({buffer1:[s+1,a],buffer1Content:t.slice(s+1,s+1+a),buffer2:[i+1,l],buffer2Content:e.slice(i+1,i+1+l)})}return r.reverse(),r}function Ro(t,e,n){let r=[];function s(l,d){r.push({ab:d,oStart:l.buffer1[0],oLength:l.buffer1[1],abStart:l.buffer2[0],abLength:l.buffer2[1]})}Zr(e,t).forEach(l=>s(l,"a")),Zr(e,n).forEach(l=>s(l,"b")),r.sort((l,d)=>l.oStart-d.oStart);let i=[],o=0;function a(l){l>o&&(i.push({stable:!0,buffer:"o",bufferStart:o,bufferLength:l-o,bufferContent:e.slice(o,l)}),o=l)}for(;r.length;){let l=r.shift(),d=l.oStart,f=l.oStart+l.oLength,m=[l];for(a(d);r.length;){let c=r[0],h=c.oStart;if(h>f)break;f=Math.max(f,h+c.oLength),m.push(r.shift())}if(m.length===1){if(l.abLength>0){let c=l.ab==="a"?t:n;i.push({stable:!0,buffer:l.ab,bufferStart:l.abStart,bufferLength:l.abLength,bufferContent:c.slice(l.abStart,l.abStart+l.abLength)})}}else{let c={a:[t.length,-1,e.length,-1],b:[n.length,-1,e.length,-1]};for(;m.length;){l=m.shift();let R=l.oStart,T=R+l.oLength,I=l.abStart,D=I+l.abLength,P=c[l.ab];P[0]=Math.min(I,P[0]),P[1]=Math.max(D,P[1]),P[2]=Math.min(R,P[2]),P[3]=Math.max(T,P[3])}let h=c.a[0]+(d-c.a[2]),g=c.a[1]+(f-c.a[3]),S=c.b[0]+(d-c.b[2]),y=c.b[1]+(f-c.b[3]),A={stable:!1,aStart:h,aLength:g-h,aContent:t.slice(h,g),oStart:d,oLength:f-d,oContent:e.slice(d,f),bStart:S,bLength:y-S,bContent:n.slice(S,y)};i.push(A)}o=f}return a(e.length),i}function Qr(t,e,n,r){r=Object.assign({excludeFalseConflicts:!0,stringSeparator:/\s+/},r),typeof t=="string"&&(t=t.split(r.stringSeparator)),typeof e=="string"&&(e=e.split(r.stringSeparator)),typeof n=="string"&&(n=n.split(r.stringSeparator));let i=[],o=Ro(t,e,n),a=[];function l(){a.length&&i.push({ok:a}),a=[]}function d(f,m){if(f.length!==m.length)return!1;for(let c=0;c<f.length;c++)if(f[c]!==m[c])return!1;return!0}return o.forEach(f=>{f.stable?a.push(...f.bufferContent):r.excludeFalseConflicts&&d(f.aContent,f.bContent)?a.push(...f.aContent):(l(),i.push({conflict:{a:f.aContent,aIndex:f.aStart,o:f.oContent,oIndex:f.oStart,b:f.bContent,bIndex:f.bStart}}))}),l(),i}function en(t,e){let n=t.lastIndexOf("/"),r=n<0?"":t.slice(0,n+1),s=n<0?t:t.slice(n+1),i=s.lastIndexOf("."),o=i>0?s.slice(0,i):s,a=i>0?s.slice(i):"",l=f=>String(f).padStart(2,"0"),d=`${e.getFullYear()}-${l(e.getMonth()+1)}-${l(e.getDate())} ${l(e.getHours())}${l(e.getMinutes())}`;return`${r}${o} (conflict ${d})${a}`}function $o(t,e){if(e<2)return t;let n=t.lastIndexOf("."),r=n>t.lastIndexOf("/")&&n>t.lastIndexOf(")"),s=r?t.slice(0,n):t,i=r?t.slice(n):"";return`${s}-${e}${i}`}function Do(t){let e=3735928559,n=1103547991;for(let s=0;s<t.length;s++){let i=t.charCodeAt(s);e=Math.imul(e^i,2654435761),n=Math.imul(n^i,1597334677)}e=Math.imul(e^e>>>16,2246822507)^Math.imul(n^n>>>13,3266489909),n=Math.imul(n^n>>>16,2246822507)^Math.imul(e^e>>>13,3266489909);let r=4294967296*(2097151&n)+(e>>>0);return`${t.length.toString(36)}-${r.toString(36)}`}function tn(t,e,n){if(t===null&&e===null&&n===null)return{kind:"none"};if(n===null)return t===null?e?{kind:"dropShadow"}:{kind:"none"}:e?t===e.hash?{kind:"deleteLocal"}:{kind:"pushCreate"}:{kind:"pushCreate"};if(t===null)return e?n.seq===e.seq?{kind:"pushDelete"}:{kind:"pull"}:{kind:"pull"};if(!e)return t===n.hash?{kind:"adopt"}:{kind:"conflict"};let r=t!==e.hash,s=n.seq!==e.seq;return!r&&!s?{kind:"none"}:r?s?t===n.hash?{kind:"adopt"}:n.hash===e.hash?{kind:"push",baseSeq:n.seq}:{kind:"conflict"}:{kind:"push",baseSeq:e.seq}:{kind:"pull"}}function es(t,e,n){let r=Qr(t.split(`
194
194
  `),e.split(`
195
195
  `),n.split(`
196
- `),{excludeFalseConflicts:!0}),s=[];for(let o of r){if(o.conflict)return null;o.ok&&s.push(...o.ok)}return s.join(`
197
- `)}function bn(t,e,n=200){return t>=n||e>=5&&t>=Math.max(5,Math.ceil(e/2))}var ti=/[\u0000-\u001f\u007f]/;function Xe(t){let e=t.replace(/\\/g,"/").normalize("NFC").trim();if(e=e.replace(/\/+$/,""),!e||e.length>512||e.startsWith("/")||ti.test(e))return null;let n=e.split("/");for(let r of n)if(!r||r==="."||r==="..")return null;return n.join("/")}function Sn(t,e){let n=t.replace(/\\/g,"/").normalize("NFC");return e===""?Xe(n):n.startsWith(`${e}/`)?Xe(n.slice(e.length+1)):null}function jr(t,e){return e===""?t:`${e}/${t}`}function ft(t){return!!(t===".DS_Store"||t==="Icon\r"||t===".sync-trash"||/\.tmp-\d+-\d+-\d+$/.test(t)||/^\..+\.lock$/.test(t))}function Pe(t){return/\.md$/i.test(t)?"page":/\.db$/i.test(t)?"db":"binary"}var je=t=>t==="page"||t==="db";import{gzip as ni}from"node:zlib";import{promisify as ri}from"node:util";var si=ri(ni),oi=1024,fe=class extends Error{status;body;constructor(e,n,r){super(`cloud http ${e} on ${r}`),this.status=e,this.body=n}},Lr=t=>12e4+Math.ceil(t/256);function Hr(t){let e=`${t.baseUrl.replace(/\/+$/,"")}/api/amadeus`,n=async(s,o,a)=>{let i={Authorization:`Bearer ${t.token}`,...a?.headers};s!=="GET"&&(i["X-Amadeus-Client"]=t.clientId);let l;a?.json!==void 0?(i["Content-Type"]="application/json",l=JSON.stringify(a.json),l.length>=oi&&(i["Content-Encoding"]="gzip",l=await si(l))):a?.form&&(l=a.form);let h=await fetch(o,{method:s,headers:i,body:l,signal:AbortSignal.timeout(a?.timeoutMs??3e4)});if(!h.ok){let d=null;try{d=await h.json()}catch{}throw new fe(h.status,d,o)}return h.json()},r=s=>new URLSearchParams(s).toString();return{clientId:t.clientId,async listVaults(){return((await n("GET",`${e}/vaults`)).vaults??[]).map(o=>({id:String(o.id),name:String(o.name),lastChangeSeq:Number(o.lastChangeSeq??0)}))},async tree(s){let o=await n("GET",`${e}/vaults/${s}/tree`);if(!Array.isArray(o.entries))throw new Error("server too old: tree has no entries[] (deploy the amadeus microserver update)");return{folders:o.folders??[],seq:Number(o.seq??0),maxFileBytes:Number.isInteger(o.maxFileBytes)&&o.maxFileBytes>0?o.maxFileBytes:void 0,entries:o.entries.map(a=>({path:String(a.path),kind:a.kind,seq:Number(a.seq??0),hash:a.hash??null,size:Number(a.size??0)}))}},async getFile(s,o){let a=await n("GET",`${e}/vaults/${s}/file?${r({path:o})}`);return{content:String(a.content??""),seq:Number(a.seq??0),hash:a.hash??null}},putFile(s,o,a,i,l=!1){return n("PUT",`${e}/vaults/${s}/file`,{json:{path:o,content:a,baseSeq:i,...l?{force:!0}:{}}})},async deleteFile(s,o,a,i){let l={path:o};a!==void 0&&(l.baseSeq=String(a)),await n("DELETE",`${e}/vaults/${s}/file?${r(l)}`,i?.confirmed?{headers:{"X-Amadeus-Delete-Confirmed":"1"}}:void 0)},move(s,o,a){return n("POST",`${e}/vaults/${s}/move`,{json:{from:o,to:a}})},renameFolder(s,o,a){return n("POST",`${e}/vaults/${s}/folders/rename`,{json:{path:o,newName:a}})},moveFolder(s,o,a){return n("POST",`${e}/vaults/${s}/folders/move`,{json:{path:o,dest:a}})},async deleteFolder(s,o){await n("DELETE",`${e}/vaults/${s}/folders?${r({path:o})}`)},putBinary(s,o,a,i){let l=new FormData;return l.set("path",o),i?.ifAbsent&&l.set("ifAbsent","true"),i?.baseSeq!==void 0&&l.set("baseSeq",String(i.baseSeq)),l.set("file",new Blob([new Uint8Array(a)]),o.split("/").pop()||"file"),n("POST",`${e}/vaults/${s}/binary`,{form:l,timeoutMs:Lr(a.length)})},async listVersions(s,o){return((await n("GET",`${e}/vaults/${s}/file/versions?${r({path:o})}`)).versions??[]).map(i=>({id:String(i.id),seq:Number(i.seq??0)}))},async getVersion(s,o){let a=await n("GET",`${e}/vaults/${s}/file/versions/${o}`);return String(a.content??"")},async getAsset(s,o){let a=new AbortController,i=setTimeout(()=>a.abort(),12e4);try{let l=await fetch(`${e}/vaults/${s}/asset?${r({ref:o})}`,{headers:{Authorization:`Bearer ${t.token}`},signal:a.signal});if(!l.ok)throw new fe(l.status,null,"asset:"+o);return clearTimeout(i),i=setTimeout(()=>a.abort(),Lr(Number(l.headers.get("content-length"))||0)),Buffer.from(await l.arrayBuffer())}finally{clearTimeout(i)}},async changes(s,o){let a=await n("GET",`${e}/vaults/${s}/changes?${r({since:String(o)})}`);return{changes:a.changes??[],seq:Number(a.seq??0)}}}}function zr(t,e){let n=!1,r=0,s=null,o=null,a=()=>`${t.baseUrl.replace(/\/+$/,"")}/api/amadeus/vaults/${t.vaultId}/events?since=${e.getSince()}`,i=h=>{if(n)return;e.onDown(h);let d=Math.min(3e4,1e3*2**r)*(.7+Math.random()*.6);r++,o=setTimeout(()=>void l(),d)},l=async()=>{if(n)return;s=new AbortController;let h;try{h=await fetch(a(),{headers:{Authorization:`Bearer ${t.token}`,Accept:"text/event-stream"},signal:s.signal})}catch(w){i(w);return}if(!h.ok||!h.body){i(new Error(`sse http ${h.status}`));return}r=0,e.onOpen();let d=h.body.getReader(),f=new TextDecoder,u="",g="",S=[],x=()=>{if(!S.length&&!g)return;let w=S.join(`
198
- `),F=g||"message";g="",S=[];let _=null;try{_=w?JSON.parse(w):null}catch{return}F==="hello"?e.onHello(Number(_?.seq??0)):F==="change"?e.onChange(_):F==="reset"?e.onReset():F==="presence"?e.onPresence?.(_):F==="presence-roster"&&e.onPresenceRoster?.(_)};try{for(;;){let{done:w,value:F}=await d.read();if(w)break;for(u+=f.decode(F,{stream:!0});;){let _=u.indexOf(`
199
- `);if(_<0)break;let A=u.slice(0,_).replace(/\r$/,"");if(u=u.slice(_+1),A==="")x();else{if(A.startsWith(":"))continue;A.startsWith("event:")?g=A.slice(6).trim():A.startsWith("data:")&&S.push(A.slice(5).replace(/^ /,""))}}}}catch(w){n||i(w);return}i(new Error("sse stream ended"))};return l(),{stop:()=>{n=!0,o&&clearTimeout(o),s?.abort()}}}import{constants as ii,promises as Qe}from"node:fs";import ai from"node:path";var Ze=t=>ai.join(pe().userDataDir(),pe().isDevMode()?`${t}.dev.json`:`${t}.json`);async function vn(t){try{let e=JSON.parse(await Qe.readFile(Ze(t),"utf8"));return!e||typeof e.vaultRoot!="string"||typeof e.vaultId!="string"?null:(e.files=e.files??{},e.cursor=Number(e.cursor??0),e.lastSyncAt=e.lastSyncAt??null,e)}catch{return null}}function qr(t){let e=null,n=null,r=Promise.resolve(),s=null,o=()=>{if(!e)return r;let a=e,i=JSON.stringify(e);return e=null,r=r.then(async()=>{try{let l=Ze(t),h=`${l}.tmp-${process.pid}-${Date.now()}-0`;await Qe.writeFile(h,i,"utf8"),await Qe.rename(h,l),s=null}catch(l){e??=a,s=l}}),r};return{save(a){e=a,!n&&(n=setTimeout(()=>{n=null,o()},500))},async flush(a=!1){if(n&&(clearTimeout(n),n=null),await o(),a&&s)throw s}}}async function Br(t){try{await Qe.unlink(Ze(t))}catch{}}async function Wr(t,e){try{await Qe.copyFile(Ze(t),Ze(e),ii.COPYFILE_EXCL)}catch(n){let r=n?.code;if(r==="EEXIST"||r==="ENOENT")return!1;throw n}return await Qe.unlink(Ze(t)).catch(()=>{}),!0}var ci=5*1024*1024,ui=5*1024*1024,di=3e4,fi=2500,hi=3e3,mi=5,gi=256*1024,pi=5,Yr=1024*1024,Gr=200,yi=6e4,wi=50,bi=".sync-trash",et=t=>li("sha256").update(t).digest("hex");function ht(t,e={localRoot:Fe(),shadowName:`amadeus-sync-${ct()}`,vaultId:"first",serverDir:"",excludePrefixes:["\u4E0E\u6211\u5171\u4EAB/"]}){let n=c=>{let m=Sn(c,"");if(!m)return null;for(let p of e.excludePrefixes??[])if(m===p.replace(/\/$/,"")||m.startsWith(p))return null;if(e.ignoreNames?.length&&m.split("/").some(p=>e.ignoreNames.includes(p)))return null;let y=e.serverDir?`${e.serverDir}/${m}`:m;return e.inScope&&!e.inScope(y,Pe(y))?null:y},r=c=>{let m;if(e.serverDir){if(!c.startsWith(`${e.serverDir}/`))return null;m=c.slice(e.serverDir.length+1)}else{for(let y of e.excludePrefixes??[])if(c.startsWith(y))return null;m=c}return m.split("/").some(y=>ft(y)||!!e.ignoreNames?.includes(y))?null:m},s=(c,m)=>!e.inScope||e.inScope(c,m),o=e.accountId??ye(),a=!1,i=0,l=Promise.resolve(),h=new Set,d="disabled",f=null,u=null,g=null,S=null,x=null,w=null,F=0,_=new Map,A=null,U=qr(e.shadowName),M=new Map,B=!1,j=!1,K=[],se=()=>{u&&(u.pending=M.size?Object.fromEntries(M):void 0,U.save(u))},he=()=>{j=!1,K.length=0},we=()=>{if(j)return!0;let c=Date.now();for(;K.length&&c-K[0]>yi;)K.shift();return K.length>=wi?(j=!0,!0):!1},ae=[],Ee=new Set,$e=!1,k=null,C=null,b=null,v=()=>{!a||b||(b=setTimeout(()=>{b=null,t.onStatus(ze())},200))},$=(c,m)=>{d=c,m!==void 0&&(f=m),v()},E=(c,m=!1)=>{if(a){if(c.key){if(Ee.has(c.key))return;Ee.add(c.key)}m?ae.unshift(c):ae.push(c),X()}},I=new Map,N=c=>{if(!a)return;let m=(u?.files[c]?.size??0)>gi,y=(e.pushQuietMs??hi)*(m?pi:1),p=Date.now(),T=I.get(c);T&&clearTimeout(T.timer);let P=T?.since??p,O=Math.max(0,Math.min(y,P+y*mi-p)),R=setTimeout(()=>{I.delete(c),E({key:c,run:()=>de(c,!0)})},O);I.set(c,{timer:R,since:P}),v()},W=()=>{for(let{timer:c}of I.values())clearTimeout(c);I.clear()},H=c=>!(c instanceof fe)||c.status>=500||c.status===0,z=c=>c instanceof fe&&(c.status===401||c.status===403),X=async()=>{if(!$e){$e=!0;try{for(;ae.length;){(d==="idle"||d==="starting")&&$("syncing");let c=ae.shift();c.key&&Ee.delete(c.key);try{await c.run()}catch(m){if(!a)return;if(z(m)){ae.length=0,Ee.clear(),_t(),$("auth-required","login-expired");return}if(H(m)){E(c,!0),_t(),$("offline",m?.message||"network error"),J();return}let y=c.key??"(op)";_.set(y,m?.body?.code||`http ${m?.status}`),v()}}a&&d==="syncing"&&(u&&(u.lastSyncAt=Date.now(),U.save(u)),$("idle",null))}finally{$e=!1;for(let c of h)c();h.clear()}}},J=()=>{!a||k||(k=setTimeout(()=>{k=null,at()},di))},G=c=>{if(!w||!u)throw new Error("engine not bound");let m=r(c);if(m===null)throw new Error("path outside binding: "+c);let y=ie.resolve(w,jr(m,u.folder)),p=ie.relative(w,y);if(p.startsWith("..")||ie.isAbsolute(p))throw new Error("path escapes vault: "+c);return y},ee=c=>({size:c,mtimeMs:-1}),Z=async c=>{try{let m=await ne.stat(c);return m.isFile()?{size:m.size,mtimeMs:Math.floor(m.mtimeMs)}:null}catch{return null}},ke=0,He=async(c,m,y=()=>!0)=>{await ne.mkdir(ie.dirname(c),{recursive:!0});let p=`${c}.tmp-${process.pid}-${Date.now()}-${ke++}`;await ne.writeFile(p,m);let T=await Z(p)??ee(Buffer.byteLength(m));return y()?(await ne.rename(p,c),T):(await ne.rm(p,{force:!0}),null)},We=async c=>{let m;try{m=await ne.readdir(c,{withFileTypes:!0})}catch{return}for(let y of m)y.isDirectory()&&await We(ie.join(c,y.name));try{await ne.rmdir(c)}catch{}},le=async c=>{let m=G(c),y=await Z(m),p;try{p=await ne.readFile(m)}catch{return null}return{hash:je(Pe(c))?et(p.toString("utf8")):et(p),size:y?.size??p.length,mtimeMs:y?.mtimeMs??-1,buf:p}},Ie=async(c,m,y,p)=>{u&&(u.files[c]={seq:m,hash:y,size:p.size,mtimeMs:p.mtimeMs},U.save(u))},_e=c=>{u&&c in u.files&&(delete u.files[c],U.save(u))},De=async(c,m)=>{if(!g||!u||Ce(c))return;let y=oe,p=Pe(c),T,P,O;if(je(p)){let q;try{q=await g.getFile(u.vaultId,c)}catch(V){if(V instanceof fe&&V.status===404){await Yt(c);return}throw V}T=q.content,P=q.seq,O=q.hash??et(q.content)}else{let q;try{q=await g.getAsset(u.vaultId,c)}catch(V){if(V instanceof fe&&V.status===404){_.set(c,"ASSET_404"),v();return}throw V}T=q,P=m??0,O=et(q)}let R=await le(c);if(y!==oe||Ce(c))return;if(R&&R.hash===O){await Ie(c,P,O,R);return}let L=u.files[c];if(R&&L&&O===L.hash&&R.hash!==L.hash){await Ie(c,P,O,ee(L.size)),E({key:c,run:()=>de(c)});return}if(R&&(!L||R.hash!==L.hash)){if(L&&p==="page"&&typeof T=="string"&&await xs(c,L,R,T,P,O,()=>y===oe&&!Ce(c))||y!==oe||Ce(c))return;await As(c)}let D=await He(G(c),T,()=>y===oe&&!Ce(c));D&&await Ie(c,P,O,D)},xs=async(c,m,y,p,T,P,O)=>{try{if(!g||!u||y.buf.length>Yr||p.length>Yr)return!1;let L=(await g.listVersions(u.vaultId,c)).find(V=>V.seq===m.seq);if(!L)return!1;let D=await g.getVersion(u.vaultId,L.id);if(et(D)!==m.hash)return!1;let q=Fr(y.buf.toString("utf8"),D,p);return q===null?!1:(await He(G(c),q,O)&&(await Ie(c,T,P,ee(Buffer.byteLength(q))),E({key:c,run:()=>de(c)})),!0)}catch{return!1}},As=async c=>{let m=Xe(Ft(c,new Date));if(!m)return;let y=m.lastIndexOf("."),p=y>m.lastIndexOf("/"),T=p?m.slice(0,y):m,P=p?m.slice(y):"",O=m;for(let R=2;Vr(G(O));R++)O=`${T}-${R}${P}`;try{await ne.rename(G(c),G(O))}catch(R){if(R?.code==="ENOENT")return;throw R}F++,E({key:O,run:()=>de(O)}),v()},jn=async c=>{if(!w)return;let m=G(c),y=r(c)??c,p=ie.join(w,bi,new Date().toISOString().slice(0,10),...y.split("/")),T=Vr(p)?`${p}.${Date.now()}`:p;try{await ne.mkdir(ie.dirname(T),{recursive:!0}),await ne.rename(m,T)}catch(P){if(P?.code==="ENOENT")return;throw new Error(`\u8F6F\u5220\u5931\u8D25,\u4FDD\u7559\u672C\u5730\u6587\u4EF6 ${m}: ${P?.message??String(P)}`)}},Yt=async c=>{if(!u)return;let m=await le(c);if(Ce(c))return;let y=u.files[c]??null,p=jt(m?.hash??null,y,null);if(p.kind==="deleteLocal"){if(!B&&we()){M.set(c,"local"),se(),v();return}K.push(Date.now()),await jn(c),_e(c)}else p.kind==="pushCreate"?(_e(c),E({key:c,run:()=>de(c)})):_e(c)},Ln=(c,m)=>{if(u){for(let y of Object.keys(u.files))if(y===c||y.startsWith(`${c}/`)){let p=m+y.slice(c.length);u.files[p]=u.files[y],delete u.files[y]}U.save(u)}},Hn=async c=>{if(!g||!u||c.seq<=u.cursor||!await St())return;if(c.origin.client&&g.clientId===c.origin.client){u.cursor=c.seq,U.save(u);return}let m=c.type==="structure"?"folder":c.type,y=T=>r(T)!==null&&s(T,m);if(!y(c.path)&&!(c.newPath&&y(c.newPath))){u.cursor=c.seq,U.save(u);return}let p=c.path;switch(c.op){case"write":await De(p,c.fileSeq);break;case"delete":await Yt(p);break;case"move":{let T=c.newPath;if(!T)break;let P=u.files[p];if(await le(p)&&P)try{await ne.mkdir(ie.dirname(G(T)),{recursive:!0}),await ne.rename(G(p),G(T)),u.files[T]={...P,seq:c.fileSeq??P.seq},delete u.files[p],U.save(u)}catch{await De(T,c.fileSeq)}else _e(p),await De(T,c.fileSeq);break}case"mkdir":await ne.mkdir(G(p),{recursive:!0});break;case"rename-folder":case"move-folder":{let T=c.newPath;if(!T)break;try{await ne.mkdir(ie.dirname(G(T)),{recursive:!0}),await ne.rename(G(p),G(T))}catch{}Ln(p,T);break}case"delete-folder":{let T=`${p}/`;for(let P of Object.keys(u.files))(P===p||P.startsWith(T))&&await Yt(P);await We(G(p));break}}if(u.cursor=c.seq,U.save(u),c.op==="move"||c.op==="rename-folder"||c.op==="move-folder"||c.op==="delete"||c.op==="delete-folder")try{await t.onRemoteApplied?.(c)}catch{}},Is=async(c,m,y)=>{let p=Number(m?.seq??0),T=m?.content??null;if(T!==null&&et(T)===y.hash){await Ie(c,p,y.hash,y);return}if(T===null&&p===0){if(!u?.files[c]){_.set(c,m?.code||"EXISTS"),v();return}_e(c),E({key:c,run:()=>de(c)});return}await De(c,p)},wt=async(c,m)=>{if(!g||!u)return;let y=await le(c);if(!y){E({key:c,run:()=>de(c)});return}if(y.size>ci){_.set(c,"TOO_LARGE"),v();return}let p=y.buf.toString("utf8");try{let T=await g.putFile(u.vaultId,c,p,m);_.delete(c),await Ie(c,T.seq,T.hash??y.hash,y)}catch(T){if(T instanceof fe&&T.status===409){await Is(c,T.body,y);return}throw T}},bt=async(c,m)=>{if(!g||!u)return;let y=await le(c);if(!y){E({key:c,run:()=>de(c)});return}if(y.size>(A??ui)){_.set(c,"TOO_LARGE"),v();return}try{let p=await g.putBinary(u.vaultId,c,y.buf,{baseSeq:m});_.delete(c),await Ie(c,p.seq,y.hash,y)}catch(p){if(p instanceof fe&&p.status===409){let T=Number(p.body?.seq??0),P=p.body?.hash??null;if(P!==null&&P===y.hash){await Ie(c,T,y.hash,y);return}if(T===0){if(!u.files[c]){_.set(c,p.body?.code||"EXISTS"),v();return}_e(c),E({key:c,run:()=>de(c)});return}await De(c,T);return}throw p}},zn=async c=>{if(!g||!u||Ce(c))return;let m=oe,y=u.files[c];if(y){if(je(Pe(c)))try{let p=await g.getFile(u.vaultId,c);if(p.seq!==y.seq){await De(c,p.seq);return}}catch(p){if(p instanceof fe&&p.status===404){_e(c);return}throw p}if(!(m!==oe||Ce(c))){try{await g.deleteFile(u.vaultId,c,y.seq,{confirmed:B})}catch(p){if(p instanceof fe&&p.status===409){await De(c,Number(p.body?.seq??0)||null);return}if(p instanceof fe&&p.status===429&&p.body?.code==="MASS_DELETE_BLOCKED"){M.set(c,"remote"),j=!0,se(),v();return}throw p}_e(c)}}},St=async()=>w?await ne.stat(w).then(m=>m.isDirectory()).catch(()=>!1)||!e.requireRootExists&&!Object.keys(u?.files??{}).length?!0:($("error",`vault-missing: ${w}`),J(),!1):!1,oe=0,vt=new Set,Et=new Map,be=c=>JSON.stringify([c.from,c.to]),Ue=(c,m)=>c===m||c.startsWith(`${m}/`),Ce=c=>[...u?.moves??[],...vt].some(m=>Ue(c,m.from)||Ue(c,m.to)),Me=()=>!!(u?.moves?.length||vt.size),Gt=async c=>{if(!g||!u)return;let{from:m,to:y,kind:p}=c;if(r(m)===null||r(y)===null)throw new Error("Invalid queued cloud move");c.hashes??=Object.fromEntries(Object.entries(u.files).filter(([R])=>Ue(R,m)).map(([R,L])=>[R.slice(m.length),L.hash])),U.save(u),await U.flush(!0);let T,P=!1;try{if(p==="folder"){let R=ie.posix.dirname(m)==="."?"":ie.posix.dirname(m),L=ie.posix.dirname(y)==="."?"":ie.posix.dirname(y);R===L?await g.renameFolder(u.vaultId,m,ie.posix.basename(y)):await g.moveFolder(u.vaultId,m,L)}else{let R=await g.move(u.vaultId,m,y);T=Number(R.seq)}}catch(R){if(!(R instanceof fe)||R.status!==404)throw R;let L=await g.tree(u.vaultId);if(L.entries.some(V=>Ue(V.path,m))||L.folders.some(V=>Ue(V,m)))throw R;let q=L.entries.find(V=>V.path===y);if(T=q?.seq,P=!q&&!L.entries.some(V=>Ue(V.path,y))&&!L.folders.some(V=>Ue(V,y)),!P){let V=Object.entries(c.hashes);if(!(V.length>0&&V.every(([Re,Ve])=>L.entries.some(Ye=>Ye.path===y+Re&&Ye.hash===Ve))))throw new fe(409,{code:"MOVE_DESTINATION_CHANGED"},"local-move")}}if(P)for(let R of Object.keys(u.files))Ue(R,m)&&delete u.files[R];else Ln(m,y),T!==void 0&&u.files[y]&&(u.files[y].seq=T);u.moves=(u.moves??[]).filter(R=>be(R)!==be(c)),U.save(u);try{await U.flush(!0)}catch(R){throw u.moves.unshift(c),U.save(u),R}let O=Et.get(be(c));Et.delete(be(c)),O?.(),Ce(y)||(p==="folder"?await Jt():await de(y))},de=async(c,m=!1)=>{if(!u||Ce(c))return;if(!s(c,Pe(c))){_e(c);return}if(!await St())return;let y=await le(c);if(Ce(c))return;let p=u.files[c]??null,T=jt(y?.hash??null,p,p?{seq:p.seq,hash:p.hash}:null);switch(T.kind){case"push":je(Pe(c))?await wt(c,T.baseSeq):await bt(c,T.baseSeq);break;case"pushCreate":je(Pe(c))?await wt(c,0):await bt(c,0);break;case"pushDelete":if(m){Ct();break}if(!B&&(M.has(c)||we())){M.set(c,"remote"),se(),v();break}K.push(Date.now()),await zn(c);break;case"dropShadow":_e(c);break;default:y&&p&&y.hash===p.hash&&y.mtimeMs>=0&&(p.size!==y.size||p.mtimeMs!==y.mtimeMs)&&await Ie(c,p.seq,p.hash,y);break}},qn=async()=>{let c=new Map;if(!w||!u)return c;let m=w,y=null,p=async T=>{if(y)return;let P;try{P=await ne.readdir(T,{withFileTypes:!0})}catch(O){y=`${T}: ${O?.message??String(O)}`;return}for(let O of P){if(ft(O.name)||O.isDirectory()&&e.ignoreNames?.includes(O.name))continue;let R=ie.join(T,O.name);if(O.isDirectory())await p(R);else if(O.isFile()){let L=ie.relative(m,R).split(ie.sep).join("/"),D=n(L);if(!D)continue;try{let q=await ne.stat(R);if(!q.isFile())continue;c.set(D,{size:q.size,mtimeMs:Math.floor(q.mtimeMs)})}catch(q){if(q?.code==="ENOENT")continue;y=`${R}: ${q?.message??String(q)}`;return}}}};return await p(m),y?($("error",`scan-failed: ${y}`),J(),null):c},Jt=async()=>{let c=oe;if(Me()||c!==oe||!u||!await St())return;let m=await qn();if(!m||Me()||c!==oe)return;let y=!1;for(let[P,O]of[...M])(O==="remote"&&m.has(P)||O==="local"&&!m.has(P))&&(M.delete(P),y=!0);M.size||he();for(let[P,O]of m){let R=u.files[P];R&&R.size===O.size&&R.mtimeMs===O.mtimeMs||E({key:P,run:()=>de(P)})}let p=Object.keys(u.files),T=p.filter(P=>!m.has(P));if(T.length&&!B&&(j||bn(T.length,p.length,Gr))){j=!0;for(let P of T)M.set(P,"remote");se(),v();return}y&&(se(),v());for(let P of T)M.has(P)||E({key:P,run:()=>de(P)})},it=async()=>{let c=oe;if(Me()||c!==oe||!g||!u||!w||!await St())return;let m=await g.tree(u.vaultId);if(m.maxFileBytes!==void 0&&m.maxFileBytes!==A&&(A=m.maxFileBytes,v()),Me()||c!==oe)return;let y=new Map;for(let D of m.entries)r(D.path)===null||!s(D.path,D.kind)||y.set(D.path,D);let p=await qn();if(!p||Me()||c!==oe)return;let T=new Set([...y.keys(),...p.keys(),...Object.keys(u.files)]),P=Object.keys(u.files).length,O=[];for(let D of T){if(Me()||c!==oe)return;let q=u.files[D]??null,V=y.get(D)??null,me=p.get(D)??null,Re=null,Ve=ee(me?.size??0);if(me)if(q&&q.size===me.size&&q.mtimeMs===me.mtimeMs)Re=q.hash,Ve=me;else{let Ye=await le(D);Ye&&(Re=Ye.hash,Ve=Ye)}O.push({sp:D,d:jt(Re,q,V?{seq:V.seq,hash:V.hash}:null),rSeq:V?.seq??null,localHash:Re,localStat:Ve})}if(Me()||c!==oe)return;let R=O.filter(D=>D.d.kind==="deleteLocal"||D.d.kind==="pushDelete").length,L=!B&&(j||bn(R,P,Gr));L&&R&&(j=!0),M.clear();for(let{sp:D,d:q,rSeq:V,localHash:me,localStat:Re}of O){if(Me()||c!==oe)return;if(L&&(q.kind==="deleteLocal"||q.kind==="pushDelete")){M.set(D,q.kind==="deleteLocal"?"local":"remote");continue}if((q.kind==="deleteLocal"||q.kind==="pushDelete")&&((await le(D))?.hash??null)!==me){E({key:D,run:()=>de(D)});continue}if(Me()||c!==oe)return;switch(q.kind){case"adopt":await Ie(D,V,me,Re);break;case"pull":await De(D,V);break;case"push":je(Pe(D))?await wt(D,q.baseSeq):await bt(D,q.baseSeq);break;case"pushCreate":je(Pe(D))?await wt(D,0):await bt(D,0);break;case"pushDelete":await zn(D);break;case"deleteLocal":await jn(D),_e(D);break;case"conflict":await De(D,V);break;case"dropShadow":_e(D);break;case"none":break}}B&&(B=!1,K.length=0),M.size||he(),se(),L&&v();for(let D of m.folders)if(!(r(D)===null||!s(D,"folder")))try{await ne.mkdir(G(D),{recursive:!0})}catch{}u.cursor=m.seq,u.lastSyncAt=Date.now(),U.save(u)},Rs=async()=>{if(!g||!u)return;let c=u.cursor,m=await g.changes(u.vaultId,c);if(m.changes.length===0&&m.seq>c||m.changes.length>0&&m.changes[0].seq!==c+1){await it();return}for(let p of m.changes)await Hn(p)},Ne=null,Bn=[],Wn=()=>{Ne&&Bn.push(Ne.close()),Ne=null},Ps=()=>{if(!a||Ne||!w)return;Ne=Nr.watch(w,{ignoreInitial:!0,depth:12,ignored:m=>{let y=ie.basename(m);return ft(y)||!!e.ignoreNames?.includes(y)}});let c=m=>{if(!w)return;let y=ie.relative(w,m);if(!y||y.startsWith(".."))return;let p=n(y);p&&N(p)};Ne.on("change",c),Ne.on("add",c),Ne.on("unlink",()=>Ct()),Ne.on("unlinkDir",()=>Ct())},_t=()=>{S?.stop(),S=null},$s=()=>{if(!a||!g||!u||S)return;let c=x;c&&(S=zr({baseUrl:c.cloudUrl,vaultId:u.vaultId,token:c.token},{getSince:()=>u?.cursor??0,onHello:m=>{u&&m>u.cursor&&E({run:Rs})},onChange:m=>{E({run:()=>Hn(m)})},onReset:()=>{E({run:it})},onOpen:()=>{(d==="offline"||d==="starting")&&$("idle",null),E({run:Jt})},onDown:()=>{(d==="idle"||d==="syncing")&&$("offline")},onPresence:m=>t.onPresence?.(u?.vaultId??"",m),onPresenceRoster:m=>t.onPresenceRoster?.(u?.vaultId??"",m)}))},Ds=async()=>{let c=await xe(o);if(c.cloudSync?.deviceId)return c.cloudSync.deviceId;let m=`desk-${Math.random().toString(36).slice(2,10)}${Date.now().toString(36)}`;return await Oe({cloudSync:{...c.cloudSync??{},deviceId:m}},o),m},Ms=async c=>{_t(),Wn(),ae.length=0,Ee.clear(),M.clear(),B=!1,j=!1,K.length=0;let m=await xe(o);if(c!==i)return;let y=m.cloudSync;if(y?.enabled===!1){w=null,g=null,$("disabled",null);return}if(!o||o!==ye()){$("auth-required","not-logged-in");return}if(w=e.localRoot,e.requireRootExists){let O=await ne.stat(w).then(R=>R.isDirectory()).catch(()=>!1);if(c!==i)return;if(!O){$("error",`vault-missing: ${w}`),J();return}}if(c!==i)return;let p=t.loadCreds();if(!p.cloudUrl||!p.token){g=null,$("auth-required","not-logged-in");return}$("starting",null);let T=y?.deviceId??await Ds();if(c!==i)return;let P=e.clientIdSuffix?`${T}#${e.clientIdSuffix}`:T;x={cloudUrl:p.cloudUrl,token:p.token},g=Hr({baseUrl:p.cloudUrl,token:p.token,clientId:P});try{let O=e.vaultId==="first"?y?.vaultId:e.vaultId;if(!O){let L=await g.listVaults();if(c!==i)return;if(!L.length)throw new Error("\u4E91\u7AEF\u65E0\u53EF\u7528 vault");O=L[0].id,await Oe({cloudSync:{...y??{},vaultId:O}},o)}if(c!==i)return;let R=await vn(e.shadowName);if(c!==i||(u=R&&R.vaultRoot===w&&R.vaultId===O&&R.folder===""?R:{vaultRoot:w,folder:"",vaultId:O,cursor:0,lastSyncAt:null,files:{}},c!==i))return;for(let[L,D]of Object.entries(u.pending??{}))M.set(L,D);if(M.size&&(j=!0),!e.requireRootExists){let L=await ne.stat(w).then(D=>D.isDirectory()).catch(()=>!1);if(c!==i)return;if(!L){if(Object.keys(u.files).length){$("error",`mirror-missing: ${w}`),J();return}if(await ne.mkdir(w,{recursive:!0}),c!==i)return}}Ps();for(let L of u.moves??[])E({key:`move:${be(L)}`,run:()=>Gt(L)});E({run:it}),E({run:async()=>{$s()}})}catch(O){if(c!==i)return;z(O)?$("auth-required","login-expired"):($("offline",O?.message||String(O)),J())}},Vn=()=>{a=!1,_t(),Wn(),ae.length=0,Ee.clear(),W();for(let c of[k,C,b])c&&clearTimeout(c);k=C=b=null},Yn=async()=>{$e&&await new Promise(c=>h.add(c)),await Promise.all(Bn.splice(0)),await U.flush(),u=null,g=null,x=null,w=null,F=0,_.clear(),A=null,M.clear(),B=!1,j=!1,K.length=0,d="disabled",f=null},Ns=()=>{Gn()},kt=null,at=()=>{kt?.(),kt=pe().onBeforeQuit(Ns);let c=++i;Vn();let m=l.catch(()=>{}).then(async()=>{await Yn(),c===i&&(a=!0,await Ms(c))});return l=m,m},Gn=()=>{kt?.(),kt=null,++i,Vn();let c=l.catch(()=>{}).then(Yn);return l=c,c},ze=()=>({enabled:d!=="disabled",state:d==="idle"&&I.size?"syncing":d,lastSyncAt:u?.lastSyncAt??null,pending:ae.length+I.size,conflicts:F,skipped:[..._].map(([c,m])=>({path:c,reason:m})),error:f,pendingDeletions:M.size,maxFileBytes:A});return{getStatus:ze,start(){at()},notifyLocal(c,m,y){if(!u||d==="disabled"||d==="auth-required")return;let p=n(c),T=y?n(y):null;if(m==="write"&&p){ft(p.split("/").pop()||"")||N(p);return}if(m==="remove"){if(!p)return;let P=`${p}/`,O=!1;for(let R of Object.keys(u.files))(R===p||R.startsWith(P))&&(O=!0,E({key:R,run:()=>de(R)}));!O&&p&&E({key:p,run:()=>de(p)})}},holdLocalMove(c,m){let y=T=>e.serverDir?`${e.serverDir}/${T.replace(/\\/g,"/").normalize("NFC")}`:T.replace(/\\/g,"/").normalize("NFC"),p={from:y(c),to:y(m)};return++oe,vt.add(p),()=>{vt.delete(p)}},async notifyLocalMove(c,m,y,p){let T=n(c),P=n(m),O=u??await vn(e.shadowName),R=Sn(c,""),L=R&&(e.serverDir?`${e.serverDir}/${R}`:R);if(!T&&P&&L&&O&&Object.keys(O.files).some(D=>D===L||D.startsWith(`${L}/`))&&(T=L),!T&&!P){y?.();return}if(T&&P){let D=u??O;if(!D){y?.();return}let q=p??(Object.keys(D.files).some(me=>me.startsWith(`${T}/`))?"folder":"file"),V={from:T,to:P,kind:q};D.moves??=[],D.moves.some(me=>be(me)===be(V))||(D.moves.push(V),++oe),y&&Et.set(be(V),y),U.save(D);try{await U.flush(!0)}catch(me){throw D.moves=D.moves.filter(Re=>be(Re)!==be(V)),Et.delete(be(V)),U.save(D),me}u===D&&a&&d!=="disabled"&&d!=="auth-required"&&E({key:`move:${be(V)}`,run:()=>Gt(V)});return}T&&this.notifyLocal(c,"remove"),P&&(E({key:P,run:()=>de(P)}),Ct()),y?.()},async setEnabled(c){let m=await xe(o);return await Oe({cloudSync:{...m.cloudSync??{},enabled:c}},o),await at(),ze()},async restart(){return await at(),ze()},async syncNow(){if(_.clear(),d==="disabled"||d==="auth-required"||!g)await at();else{for(let c of u?.moves??[])E({key:`move:${be(c)}`,run:()=>Gt(c)});E({run:it})}return ze()},confirmMassDeletions(){return M.size&&(B=!0,j=!1,M.clear(),K.length=0,se(),E({run:it})),ze()},stop:Gn};function Ct(){a&&(C&&clearTimeout(C),C=setTimeout(()=>{C=null,E({run:Jt})},fi))}}import{createHash as Si}from"node:crypto";function Jr(t){let e=t.replace(/\.md$/i,""),n=t.lastIndexOf("/"),r=n<0?"":t.slice(0,n);return{root:t,fdPrefix:`${e}.fd/`,assetPrefix:r?`${r}/.amadeus/`:".amadeus/"}}function Kr(t,e,n){return!!(e===t.root||e.startsWith(t.fdPrefix)||`${e}/`===t.fdPrefix||n==="binary"&&e.startsWith(t.assetPrefix)||n==="folder"&&(`${e}/`===t.assetPrefix||e.startsWith(t.assetPrefix)))}var vi=t=>Si("sha256").update(t).digest("hex").slice(0,8),Ei=t=>t.replace(/[\\/:*?"<>|]/g," ").trim().slice(0,40)||"shared",Lt="\u4E0E\u6211\u5171\u4EAB";function En(t){let e=vi(`${t.vaultId}:${t.path}`),n=Jr(t.path),r=t.path.includes("/")?t.path.slice(0,t.path.lastIndexOf("/")):"";return{key:e,vaultId:t.vaultId,rootPath:t.path,title:t.title,localRelDir:`${Lt}/${Ei(t.title)}-${e}`,serverDir:r,inScope:(s,o)=>Kr(n,s,o)}}function _n(){let t=pe().readCreds(),e=Te(t.cloudUrl??"",t.token??""),n=new AbortController,r=()=>{let f=pe().readCreds();if(n.signal.aborted||!e||Te(f.cloudUrl??"",f.token??"")!==e)throw Object.assign(new Error("Cloud account changed; retry from the current account"),{status:401});return f},s=()=>{let f=r();if(!f.cloudUrl||!f.token)throw Object.assign(new Error("\u672A\u767B\u5F55 Forsion \u8D26\u53F7"),{status:401});return f.cloudUrl.replace(/\/+$/,"")},o=async(f,u,g)=>{let S=r();if(!S.cloudUrl||!S.token)throw Object.assign(new Error("\u672A\u767B\u5F55 Forsion \u8D26\u53F7"),{status:401});let x=await fetch(`${S.cloudUrl.replace(/\/+$/,"")}/api/amadeus${u}`,{method:f,headers:{Authorization:`Bearer ${S.token}`,...g!==void 0?{"Content-Type":"application/json"}:{}},body:g!==void 0?JSON.stringify(g):void 0,signal:AbortSignal.any([n.signal,AbortSignal.timeout(2e4)])});if(!x.ok){let F=null;try{F=await x.json()}catch{}throw Object.assign(new Error(F?.detail||`http ${x.status}`),{status:x.status,code:F?.code})}let w=await x.json();return r(),w},a=null,i=async()=>(r(),a||(a=(await o("GET","/vaults")).vaults[0]?.id??"default",a)),l=()=>{try{let f=(r().token??"").split(".")[1],u=JSON.parse(Buffer.from(f.replace(/-/g,"+").replace(/_/g,"/"),"base64").toString());return typeof u.userId=="string"?u.userId:null}catch{return null}},h=async()=>(await o("GET","/shared-with-me")).items.map(u=>{let g=En(u),S=u.path.split("/").pop()??u.path;return{...u,localPath:`${g.localRelDir}/${S}`}}),d=null;return{stop:()=>n.abort(),call:o,ensureOwnVault:i,myUserId:l,sharedWithMe:h,linkBase:async()=>{if(r(),d)return d;try{d=((await o("GET","/collab/link-base")).webOrigin??"").trim().replace(/\/+$/,"")||s()}catch{d=s()}return d},async heartbeat(f,u){let g=(f??"").replace(/\\/g,"/"),S,x=null,w=u.find(F=>g.startsWith(`${F.localRelDir}/`));w?(S=w.vaultId,x=w.serverDir?`${w.serverDir}/${g.slice(w.localRelDir.length+1)}`:g.slice(w.localRelDir.length+1)):(S=await i(),x=g||null),await o("POST",`/vaults/${encodeURIComponent(S)}/presence`,{page:x})}}}import{promises as Xr}from"node:fs";import _i from"node:path";var kn=".forsion-vault.md",Cn=t=>`${t}/${kn}`;var ve=t=>t.replace(/\\/g,"/").normalize("NFC");function Tn(t){let e=ve(t.path);return e?t.kind==="folder"?`${e}/`:t.kind==="page"?`${e.replace(/\.md$/i,"")}.fd/`:null:null}function tt(t,e,n){let r=ve(n);if(!r)return!1;if(t.some(s=>ve(s.path)===r))return!0;for(let s of e??[]){let o=ve(s);if(!o)continue;let a=`${o.replace(/\.md$/i,"")}.fd`;if(r===o||r.startsWith(`${o}/`)||r===a||r.startsWith(`${a}/`))return!1}return t.some(s=>{let o=Tn(s);return!!o&&r.startsWith(o)})}function xn(t,e,n){let r=ve(t),s=ve(e);return r===s?ve(n):r.startsWith(`${s}/`)?ve(n)+r.slice(s.length):null}function mt(t,e,n){let r=!1,s=t.map(o=>{let a=xn(o,e,n);return a===null?o:(r=!0,a)});return{changed:r,next:s}}async function Zr(t){let e=await Xr.readdir(t,{withFileTypes:!0}).catch(()=>[]),n=[];for(let r of e)!r.isDirectory()||r.name.startsWith(".")||await Xr.access(_i.join(t,r.name,kn)).then(()=>!0,()=>!1)&&n.push(r.name);return n.sort()}var ce={get:"amadeus:sync:get",setEnabled:"amadeus:sync:set-enabled",syncNow:"amadeus:sync:now",confirmDeletions:"amadeus:sync:confirm-deletions",status:"amadeus:sync:status",switchSide:"amadeus:sync:switch-side",collabCall:"amadeus:collab:call",presence:"amadeus:collab:presence",entryGet:"amadeus:entry-sync:get",entryEnable:"amadeus:entry-sync:enable",entryDisable:"amadeus:entry-sync:disable",entryClosure:"amadeus:entry-sync:closure",entryChange:"amadeus:entry-sync:change",otherSideDbs:"amadeus:entry-sync:other-side-dbs"};import{createHash as ki}from"node:crypto";var Ht=t=>ki("sha256").update(t).digest("hex").slice(0,8);function Qr(t){return t.replace(/ \(conflict \d{4}-\d{2}-\d{2} \d{4}\)(?=(?:\.[^./]+)?$)/,"")}function Le(t,e=[]){let n=[],r=[];for(let s of t){let o=ve(s.path);if(!o)continue;r.push(o);let a=Tn(s);a&&n.push(a)}return{entries:t,exclude:e,prefixes:n,paths:r}}function es(t,e){let n=Qr(ve(e));if(!n)return!1;if(tt(t.entries,t.exclude,n))return!0;let r=`${n}/`;for(let s of t.paths)if(s.startsWith(r))return!0;for(let s of t.prefixes)if(s.startsWith(r))return!0;return!1}function gt(t,e,n){let r=!1,s=t.map(o=>{let a=xn(o.path,e,n);return a===null?o:(r=!0,{...o,path:a})});return{changed:r,next:s}}function ts(t,e,n,r){if(e==="delete"||e==="delete-folder"){let s=ve(n),o=t.filter(a=>{let i=ve(a.path);return!(i===s||e==="delete-folder"&&i.startsWith(`${s}/`))});return{changed:o.length!==t.length,next:o}}return r?gt(t,n,r):{changed:!1,next:t}}function An(t,e){let n=Xe(t);return!n||n!==t.normalize("NFC").trim()?"\u540D\u79F0\u4E0D\u5408\u6CD5":n.includes("/")?"\u540D\u79F0\u4E0D\u80FD\u5305\u542B /":n===Lt?`\u300C${Lt}\u300D\u662F\u4FDD\u7559\u540D\u79F0`:e.includes(n)?"\u8BE5\u540D\u79F0\u5DF2\u88AB\u5176\u4ED6\u667A\u5E93\u7684\u4E91\u540C\u6B65\u5360\u7528":null}var ns=["setAmadeusSyncFactory","readCreds","accountId","homeDir"],In=t=>ns.every(e=>typeof t[e]=="function"),Ci=()=>({enabled:!1,state:"disabled",lastSyncAt:null,pending:0,conflicts:0,skipped:[],error:null,pendingDeletions:0,maxFileBytes:null,side:"local"});function Rn(t){let e=null,n=()=>{if(!e)throw new Error("Cloud sync is not ready");return e};t.handle(ce.get,()=>e?e.get():Ci()),t.handle(ce.setEnabled,(r,s)=>n().setEnabled(s)),t.handle(ce.syncNow,()=>n().syncNow()),t.handle(ce.confirmDeletions,()=>n().confirmDeletions()),t.handle(ce.entryGet,()=>n().entryGet()),t.handle(ce.otherSideDbs,()=>n().otherSideDbs()),t.handle(ce.entryEnable,(r,s)=>n().entryEnable(s)),t.handle(ce.entryDisable,(r,s)=>n().entryDisable(s)),t.handle(ce.entryClosure,(r,s,o)=>n().entryClosure(s,o)),t.handle(ce.collabCall,(r,s,o)=>n().collabCall(s,o)),t.handle(ce.switchSide,(r,s)=>n().switchSide(r.sender.id,s)),t.setAmadeusSyncFactory(r=>{mr(r);let s=rs(r);return e=s.handlers,s.instance}),t.log("[forsion-extend] amadeus cloud sync registered")}function rs(t){let e=t.notifyAll,n=()=>t.vaultRoot(),r=0,s=!1,o=_n(),a=new Map,i=()=>{let k=Date.now();for(let[C,b]of a)k-b.at>7e4&&a.delete(C);e(ce.presence,[...a.values()])},l={loadCreds:()=>t.readCreds(),onStatus:k=>e(ce.status,{...k,pendingDeletions:K(),side:S()?"cloud":"local"}),onPresence:(k,C)=>{let b=C;b?.userId&&(a.set(b.userId,{userId:b.userId,username:String(b.username??"user"),page:b.page??null,at:Number(b.at)||Date.now()}),i())},onPresenceRoster:(k,C)=>{if(Array.isArray(C)){for(let b of C){let v=b;v?.userId&&a.set(v.userId,{userId:v.userId,username:String(v.username??"user"),page:v.page??null,at:Number(v.at)||Date.now()})}i()}}},h=()=>{let k=r;return{...l,onStatus:C=>{k===r&&l.onStatus(C)},onPresence:(C,b)=>{k===r&&l.onPresence(C,b)},onPresenceRoster:(C,b)=>{k===r&&l.onPresenceRoster(C,b)}}},d=ht(h()),f=new Map,u=[],g=async()=>{if(!s||!ye())return;let k=r,C=o,b;try{b=await C.sharedWithMe()}catch{return}if(k!==r||!s)return;let v=b.map(E=>En(E));u=v;let $=new Set(v.map(E=>E.key));for(let[E,I]of f)if(!$.has(E)){if(await I.engine.stop(),k!==r)return;f.delete(E)}for(let E of v){if(f.has(E.key))continue;let I=ht(h(),{localRoot:Be.join(Fe(),...E.localRelDir.split("/")),shadowName:`amadeus-sync-${ct()}-share-${E.key}`,vaultId:E.vaultId,serverDir:E.serverDir,inScope:E.inScope});f.set(E.key,{engine:I,plan:E}),I.start()}},S=()=>n()===Fe(),x=(k,C=k.base)=>{k.base=C;let b=[C,...k.pendingMoves];k.scope.current=Le(b.flatMap(v=>v.entries),b.flatMap(v=>v.exclude))},w=new Map,F=new Set,_=()=>{e(ce.entryChange)},A=async(k,C)=>{let b=w.get(k);if(!b)return;let v=I=>I&&I.startsWith(`${b.cloudName}/`)?I.slice(b.cloudName.length+1):null,$=v(C.path);if(!$)return;let E=!1;await Ge(I=>{if(w.get(k)!==b)return!1;let N=(I.entrySync??[]).find(J=>J.vaultRoot===k);if(!N)return!1;let W=C.op,H=v(C.newPath),z=ts(N.entries,W,$,H),X=H?mt(N.exclude??[],$,H):{changed:!1,next:N.exclude??[]};if(!z.changed&&!X.changed)return!1;E=!0,N.entries=z.next,X.changed&&(N.exclude=X.next),x(b,Le(N.entries,N.exclude??[]))}),E&&w.get(k)===b&&_()},U=k=>{let C=r;return{...h(),onStatus:b=>{C===r&&e(ce.status,{...b,pendingDeletions:K(),side:"local",binding:k})},onRemoteApplied:async b=>{C===r&&await A(k,b)}}},M=async()=>{let k=ye();if(!s||!k)return;let C=r,b=o,v=ct(k);await t.adoptLegacyCloudState(k,Wr);let $=await xe(k),E=$.entrySync??[];if(C!==r||!s||k!==ye())return;let I=new Map(E.map(N=>[N.vaultRoot,N]));for(let[N,W]of w){let H=I.get(N);if(!(H&&H.cloudName===W.cloudName)&&(await W.engine.stop(),C!==r||(w.delete(N),H&&await Br(`amadeus-sync-${v}-entry-${Ht(N)}`),C!==r)))return}for(let N of E){let W=w.get(N.vaultRoot);if(W){x(W,Le(N.entries,N.exclude??[]));continue}let H={current:Le(N.entries,N.exclude??[])},z=N.cloudName,X=ht(U(N.vaultRoot),{accountId:k,localRoot:N.vaultRoot,shadowName:`amadeus-sync-${v}-entry-${Ht(N.vaultRoot)}`,vaultId:"first",serverDir:z,clientIdSuffix:`entry-${Ht(N.vaultRoot)}`,requireRootExists:!0,ignoreNames:[".git","node_modules",".trash"],inScope:J=>J===z?!0:J.startsWith(`${z}/`)?es(H.current,J.slice(z.length+1)):!1});w.set(N.vaultRoot,{engine:X,scope:H,cloudName:z,base:H.current,pendingMoves:new Set}),X.start()}if($.cloudSync?.enabled!==!1)for(let N of E)F.has(N.cloudName)||(async()=>{try{let W=await b.ensureOwnVault();await b.call("PUT",`/vaults/${encodeURIComponent(W)}/file`,{path:Cn(N.cloudName),content:"",baseSeq:0}),C===r&&F.add(N.cloudName)}catch(W){W?.status===409&&C===r&&F.add(N.cloudName)}})()},B=async(k,C,b,v,$)=>{let E=C.replace(/\\/g,"/").normalize("NFC"),I=b.replace(/\\/g,"/").normalize("NFC"),N=!1,W,H,z,X=$??"file";try{await Ge(async J=>{if(w.get(k)!==v)return!1;let G=(J.entrySync??[]).find(le=>le.vaultRoot===k);if(!G)return!1;let ee=gt(G.entries,E,I),Z=mt(G.exclude??[],E,I),ke=tt(G.entries,G.exclude,E);!$&&await nt.stat(Be.join(k,...I.split("/"))).then(le=>le.isDirectory(),()=>!1)&&(X="folder");let He=X==="folder"?"folder":/\.md$/i.test(I)?"page":"asset";ke&&!tt(ee.next,Z.next,I)&&(ee.next.push({path:I,kind:He}),ee.changed=!0),N=ee.changed||Z.changed;let We=G.entries.filter(le=>gt([le],E,I).changed);return ke&&!We.some(le=>le.path===E)&&We.push({path:E,kind:He}),W=Le(We,(G.exclude??[]).filter(le=>mt([le],E,I).changed)),H=v.base,v.pendingMoves.add(W),G.entries=ee.next,G.exclude=Z.next,z=Le(G.entries,G.exclude),x(v,z),N})}catch(J){throw W&&v.pendingMoves.delete(W),x(v,v.base===z&&H?H:v.base),J}try{W&&await v.engine.notifyLocalMove(E,I,()=>{v.pendingMoves.delete(W),x(v)},X)}catch(J){throw W&&v.pendingMoves.delete(W),await Ge(G=>{let ee=G.entrySync?.find(Z=>Z.vaultRoot===k);if(!ee)return!1;ee.entries=gt(ee.entries,I,E).next,ee.exclude=mt(ee.exclude??[],I,E).next,x(v,Le(ee.entries,ee.exclude))}),J}N&&w.get(k)===v&&_()},j=k=>{let C=k.replace(/\\/g,"/");for(let{engine:b,plan:v}of f.values())if(C.startsWith(`${v.localRelDir}/`))return{engine:b,rel:C.slice(v.localRelDir.length+1)};return{engine:d,rel:C}};t.setMutationHooks((k,C)=>{if(S()){let b=j(k);b.engine.notifyLocal(b.rel,C);return}w.get(n()??"")?.engine.notifyLocal(k,C)},(k,C,b)=>{if(S()){let E=j(k),I=j(C);if(E.engine===I.engine)return E.engine.notifyLocalMove(E.rel,I.rel,void 0,b);E.engine.notifyLocal(E.rel,"remove"),I.engine.notifyLocal(I.rel,"write");return}let v=n()??"",$=w.get(v);if($)return B(v,k,C,$,b)},(k,C)=>{if(S()){let b=j(k),v=j(C),$=[b.engine.holdLocalMove(b.rel,v.rel)];return b.engine!==v.engine&&$.push(v.engine.holdLocalMove(b.rel,v.rel)),()=>{for(let E of $)E()}}return w.get(n()??"")?.engine.holdLocalMove(k,C)});let K=()=>{let k=d.getStatus().pendingDeletions;for(let{engine:C}of f.values())k+=C.getStatus().pendingDeletions;for(let{engine:C}of w.values())k+=C.getStatus().pendingDeletions;return k},se=k=>({...k,pendingDeletions:K(),side:S()?"cloud":"local"}),he=()=>{if(!s)return Promise.resolve(d.getStatus());g();for(let{engine:k}of f.values())k.syncNow();for(let{engine:k}of w.values())k.syncNow();return d.syncNow()},we=async()=>{++r,s=!1,o.stop();let k=[d.stop(),...[...f.values()].map(({engine:b})=>b.stop()),...[...w.values()].map(({engine:b})=>b.stop())];f.clear(),w.clear(),u=[],F.clear(),a.clear(),i(),await Promise.all(k),await t.awaitPendingVaultWrites();let C=n();if(C&&It(C)){let b=await xe(),v=b.localVault&&!It(b.localVault)?b.localVault:Be.join(t.workspaceDir(),"Amadeus");await nt.mkdir(v,{recursive:!0}),await Oe({lastVault:v,localVault:v,lastPage:void 0}),await t.activateRoot(v,!1)}_()};return{handlers:{get:()=>se(d.getStatus()),setEnabled:async k=>{if(!s)throw new Error("Cloud account is changing");let C=r;return await d.setEnabled(k),C!==r?d.getStatus():(await Promise.all([...f.values(),...w.values()].map(({engine:b})=>b.restart())),se(d.getStatus()))},syncNow:()=>he(),confirmDeletions:()=>{for(let{engine:k}of f.values())k.confirmMassDeletions();for(let{engine:k}of w.values())k.confirmMassDeletions();return se(d.confirmMassDeletions())},entryGet:async()=>{let k=await xe(),C=Fe();return{vaults:k.entrySync??[],activeRoot:n(),cloudRoot:C,mirrorVaults:await Zr(C)}},otherSideDbs:async()=>{let k=n();if(!k)return null;let C=Fe(),b=await xe(),v=k===C?b.localVault&&b.localVault!==C?b.localVault:null:C;if(!v)return null;let $=[],E=500,I=async(N,W)=>{if($.length>=E)return;let H;try{H=await nt.readdir(N,{withFileTypes:!0})}catch{return}for(let z of H){if($.length>=E)break;if(z.name.startsWith(".")||z.isSymbolicLink())continue;let X=W?`${W}/${z.name}`:z.name;if(z.isDirectory())await I(Be.join(N,z.name),X);else if(z.isFile()&&/\.db$/i.test(z.name))try{$.push({rel:X,source:await nt.readFile(Be.join(N,z.name),"utf8")})}catch{}}};return await I(v,""),{root:v,vaultName:v===C?"\u4E91\u7AEF":Be.basename(v),dbs:$}},entryEnable:async k=>{let C=r,b=o;if(!s||!ye())return{error:"Sign in to enable cloud sync"};let v=n();if(!v||S())return{error:"\u4EC5\u672C\u5730 vault \u53EF\u5F00\u542F\u4E91\u540C\u6B65"};let $=await xe(),E=$.entrySync??[],I=E.find(N=>N.vaultRoot===v);if(!I){let N=(k.cloudName??Be.basename(v)).normalize("NFC").trim(),W=An(N,E.map(H=>H.cloudName));if(W)return{error:W};if(!k.merge)try{let H=await b.ensureOwnVault(),z=await b.call("GET",`/vaults/${encodeURIComponent(H)}/tree`);if((z.folders??[]).some(J=>J===N||J.startsWith(`${N}/`))||(z.entries??[]).some(J=>J.path===N||J.path.startsWith(`${N}/`)))return{conflict:N}}catch(H){return{error:H?.message||"\u65E0\u6CD5\u8FDE\u63A5\u4E91\u7AEF(\u9996\u6B21\u5F00\u542F\u9700\u8981\u5728\u7EBF)"}}I={vaultRoot:v,cloudName:N,entries:[]},E.push(I),(async()=>{try{let H=await b.ensureOwnVault();await b.call("PUT",`/vaults/${encodeURIComponent(H)}/file`,{path:Cn(I.cloudName),content:"",baseSeq:0})}catch{}})()}return C!==r||!s?{error:"Cloud account changed; retry from the current account"}:(await Ge(N=>{if(C!==r||!s)return!1;let W=N.entrySync??[],H=W.find(Z=>Z.vaultRoot===v);if(!H){let Z=An(I.cloudName,W.map(ke=>ke.cloudName));if(Z)throw new Error(Z);H={vaultRoot:v,cloudName:I.cloudName,entries:[]},W.push(H)}let z=Z=>String(Z??"").replace(/\\/g,"/").normalize("NFC"),X=new Set;for(let Z of k.entries??[]){let ke=z(Z.path);ke&&(X.add(ke),!H.entries.some(He=>He.path===ke)&&H.entries.push({path:ke,kind:Z.kind==="folder"||Z.kind==="asset"?Z.kind:"page"}))}let J=(k.exclude??[]).map(z).filter(Boolean),G=new Set([...X,...(k.include??[]).map(z).filter(Boolean)]);H.exclude=[...new Set([...(H.exclude??[]).filter(Z=>!G.has(Z)),...J])];let ee=new Set(J);H.entries=H.entries.filter(Z=>!ee.has(Z.path)),N.entrySync=W,I=H},$.cloudAccountId),C!==r?{error:"Cloud account changed; retry from the current account"}:(await M(),w.get(v)?.engine.syncNow(),_(),{ok:!0,cloudName:I.cloudName}))},entryDisable:async k=>{let C=n(),b=!1,v=r;return await Ge($=>{if(v!==r||!s)return!1;let E=($.entrySync??[]).find(W=>W.vaultRoot===C);if(!C||!E)return!1;let I=String(k??"").replace(/\\/g,"/").normalize("NFC"),N=E.entries.length;if(E.entries=E.entries.filter(W=>W.path!==I),tt(E.entries,E.exclude,I))E.exclude=[...new Set([...E.exclude??[],I])];else if(E.entries.length===N)return!1;b=!0}),!b||v!==r?{ok:!1}:(await M(),_(),{ok:!0})},entryClosure:(k,C)=>t.relatedClosure(String(k??""),C==="folder"?"folder":"page"),collabCall:async(k,C)=>{let b=o,v=async()=>b.ensureOwnVault(),$=I=>String((C??[])[I]??""),E=I=>(C??[])[I]??{};switch(k){case"listVaults":return(await b.call("GET","/vaults")).vaults;case"activeVaultId":return v();case"pageShare":return b.call("GET",`/vaults/${encodeURIComponent(await v())}/page-shares?path=${encodeURIComponent($(0))}`);case"createPageShare":return b.call("POST",`/vaults/${encodeURIComponent(await v())}/page-shares`,{path:$(0),...E(1)});case"updatePageShare":return b.call("PATCH",`/vaults/${encodeURIComponent(await v())}/page-shares/${encodeURIComponent($(0))}`,E(1));case"revokePageShare":return b.call("DELETE",`/vaults/${encodeURIComponent(await v())}/page-shares/${encodeURIComponent($(0))}`);case"setParticipantRole":return b.call("PATCH",`/vaults/${encodeURIComponent(await v())}/page-shares/${encodeURIComponent($(0))}/members/${encodeURIComponent($(1))}`,{role:$(2)});case"removeParticipant":return b.call("DELETE",`/vaults/${encodeURIComponent(await v())}/page-shares/${encodeURIComponent($(0))}/members/${encodeURIComponent($(1))}`);case"sharedWithMe":{let I=await b.sharedWithMe();return g(),I}case"leaveShare":{let I=b.myUserId();if(!I)throw new Error("\u672A\u767B\u5F55");return b.call("DELETE",`/vaults/${encodeURIComponent(await v())}/page-shares/${encodeURIComponent($(0))}/members/${encodeURIComponent(I)}`)}case"publishes":return b.call("GET",`/vaults/${encodeURIComponent(await v())}/shares`);case"listAllShares":{let I=(await b.call("GET","/vaults")).vaults||[],N=b.myUserId(),W=[],H=[];for(let z of I){try{let X=await b.call("GET",`/vaults/${encodeURIComponent(z.id)}/shares`);for(let J of X.shares||[])W.push({...J,vaultId:z.id,vaultName:z.name||""})}catch(X){t.log(`[connect] listAllShares publishes vault ${z.id} failed: ${X?.message}`)}try{let X=await b.call("GET",`/vaults/${encodeURIComponent(z.id)}/page-shares`),J=X?.shares||X?.pageShares||(Array.isArray(X)?X:[]);for(let G of J){let ee=G.created_by??G.createdBy;(!N||!ee||ee===N)&&H.push({...G,vaultId:z.id,vaultName:z.name||""})}}catch(X){t.log(`[connect] listAllShares pageShares vault ${z.id} failed: ${X?.message}`)}}return{publishes:W,pageShares:H,linkBase:await b.linkBase()}}case"createPublish":{let I=await b.call("POST",`/vaults/${encodeURIComponent(await v())}/shares`,{mode:$(0),path:$(1)});return{...I,url:`${await b.linkBase()}/share/${I.token}`}}case"revokePublish":return b.call("DELETE",`/vaults/${encodeURIComponent(await v())}/shares/${encodeURIComponent($(0))}`);case"revokePublishIn":return b.call("DELETE",`/vaults/${encodeURIComponent($(0))}/shares/${encodeURIComponent($(1))}`);case"revokePageShareIn":return b.call("DELETE",`/vaults/${encodeURIComponent($(0))}/page-shares/${encodeURIComponent($(1))}`);case"myUserId":return b.myUserId();case"linkBase":return b.linkBase();case"heartbeat":return b.heartbeat((C??[])[0]??null,u);default:throw new Error(`unknown collab fn: ${k}`)}},switchSide:async(k,C)=>{let b=await xe();if(C==="cloud"){if(!s||!ye())throw new Error("Sign in to open cloud notes");let E=Fe();await nt.mkdir(E,{recursive:!0}),b.lastVault&&!It(b.lastVault)&&await Oe({localVault:b.lastVault}),await Oe({lastVault:E});let I=await t.activateRoot(E,!1);return t.bindRenderer(k,E),{...I,side:"cloud"}}let v=b.localVault&&await nt.stat(b.localVault).then(E=>E.isDirectory()).catch(()=>!1)?b.localVault:null;if(!v){let E=await t.ensureDefaultVault();return t.bindRenderer(k,E.root),{...E,side:"local"}}await Oe({lastVault:v});let $=await t.activateRoot(v,!1);return t.bindRenderer(k,v),{...$,side:"local"}}},instance:{start:()=>{s=!0,d.start(),g(),M()},stopAllSync:we,restartAllSync:async()=>{await we(),o=_n(),d=ht(h()),s=!0,await Promise.all([d.restart(),g(),M()]),_(),e(ce.status,se(d.getStatus()))}}}}import{hostname as Ti}from"node:os";var xi=256*1024;function ss(t,e,n){if(n?.hasSecHeaders&&!n.gatewayStreamsSecHeaders)return!1;if(t.includes("text/event-stream"))return!0;let r=Number(e||NaN);return!Number.isFinite(r)||r>xi}var Pn=45e3,Ai=3e3,Ii=16*1024,Ri=6e4,zt=t=>`${t.replace(/\/+$/,"")}/api`,pt=class{deps;ctrl=null;conn=null;wake=null;redialNow=!1;inflight=new Map;connected=!1;lastError=null;hubCaps=new Set;constructor(e){this.deps=e}hubFetch(e,n){return(this.deps.hubFetch??fetch)(e,n)}get requestTimeoutMs(){return this.deps.requestTimeoutMs??Ri}status(){return{running:!!this.ctrl,connected:this.connected,unitId:this.deps.getPairing()?.unitId??null,lastError:this.lastError}}start(){if(this.ctrl)return;let e=new AbortController;this.ctrl=e,this.loop(e)}stop(){this.ctrl?.abort(),this.ctrl=null,this.markDown(),this.abortEnvelopes(),this.wake?.()}reconnect(e){this.ctrl&&(this.deps.log(`[unit-host] \u7ACB\u5373\u91CD\u8FDE\u901A\u9053(${e})`),this.redialNow=!0,this.conn?.abort(),this.wake?.())}markDown(){this.connected=!1,this.hook(this.deps.onChannelDown)}hook(e){try{e?.()}catch(n){this.deps.log(`[unit-host] \u901A\u9053\u56DE\u8C03\u51FA\u9519(\u5DF2\u5FFD\u7565): ${n?.message||n}`)}}abortEnvelope(e){let n=this.inflight.get(e);return n?(this.inflight.delete(e),n.ctrl.abort(),!0):!1}abortEnvelopes(e){for(let[n,r]of[...this.inflight])e&&r.conn!==e||(this.inflight.delete(n),r.ctrl.abort())}sleep(e){return new Promise(n=>{let r=setTimeout(s,e);function s(){clearTimeout(r),n()}this.wake=()=>{this.wake=null,s()}})}async loop(e){let n=1e3;for(;!e.signal.aborted;){let r=new AbortController,s=()=>r.abort();e.signal.addEventListener("abort",s,{once:!0}),this.conn=r;try{let{cloudUrl:o,token:a}=this.deps.getCreds();if(!a)throw new Error("\u672A\u767B\u5F55 Forsion \u8D26\u53F7");let i=this.deps.getPairing();if(!i){if(i=await this.register(o,a,r),r.signal.aborted)throw new Error("\u5165\u518C\u671F\u95F4\u901A\u9053\u5DF2\u88AB\u505C\u7528");await this.deps.savePairing(i),this.deps.log(`[unit-host] \u5DF2\u5165\u518C\u4E3A\u8BBE\u5907 ${i.unitId}`)}let l=this.deps.getLanUrl();this.hubCaps=new Set;let h=this.deps.readIdleMs??Pn,d=h?setTimeout(()=>{this.deps.log(`[unit-host] \u901A\u9053 ${Math.round(h/1e3)}s \u672A\u6536\u5230\u54CD\u5E94\u5934,\u5224\u5B9A\u5DF2\u65AD,\u91CD\u8FDE`),r.abort()},h):null,f;try{f=await this.hubFetch(`${zt(o)}/units/${i.unitId}/channel`,{headers:{Authorization:`Bearer ${a}`,"X-Unit-Secret":i.secret,...l?{"X-Unit-Lan-Url":l}:{}},signal:r.signal})}finally{d&&clearTimeout(d)}if(f.status===403||f.status===404){let u=Number(f.headers.get("content-length"))>Ii,g=setTimeout(()=>r.abort(),u?0:Ai),S=await f.json().then(x=>x?.code,()=>null);throw clearTimeout(g),S==="UNIT_NOT_FOUND"||S==="UNIT_SECRET_MISMATCH"?(await this.deps.clearPairing(),new Error(`\u901A\u9053\u88AB\u62D2(${f.status} ${S}),\u5DF2\u6E05\u9664\u914D\u5BF9\u5F85\u91CD\u65B0\u5165\u518C`)):new Error(`channel HTTP ${f.status} (not a hub verdict; keeping pairing and retrying)`)}if(!f.ok||!f.body)throw new Error(`channel HTTP ${f.status}`);this.connected=!0,this.lastError=null,n=1e3,this.deps.log("[unit-host] \u901A\u9053\u5DF2\u8FDE\u63A5"),await this.consume(f.body,r),this.markDown(),this.deps.log("[unit-host] \u901A\u9053\u65AD\u5F00,\u51C6\u5907\u91CD\u8FDE")}catch(o){if(this.markDown(),e.signal.aborted)return;this.lastError=r.signal.aborted?"\u901A\u9053\u88AB\u672C\u673A\u65AD\u5F00(\u770B\u95E8\u72D7 / \u91CD\u8FDE)":String(o?.message||o),this.deps.log(`[unit-host] ${this.lastError};${this.redialNow?"\u7ACB\u5373":`${Math.round(n/1e3)}s \u540E`}\u91CD\u8BD5`)}finally{e.signal.removeEventListener("abort",s),this.conn===r&&(this.conn=null),r.abort(),this.abortEnvelopes(r)}if(e.signal.aborted)return;if(this.redialNow){this.redialNow=!1,n=1e3;continue}if(await this.sleep(n),this.redialNow){this.redialNow=!1,n=1e3;continue}n=Math.min(n*2,3e4)}}async register(e,n,r){let s=this.deps.readIdleMs??Pn,o=s?setTimeout(()=>{this.deps.log(`[unit-host] \u8BBE\u5907\u5165\u518C ${Math.round(s/1e3)}s \u672A\u8FD4\u56DE,\u4E2D\u6B62\u91CD\u8BD5`),r.abort()},s):null;try{let a=await this.hubFetch(`${zt(e)}/units/register`,{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify({name:Ti(),platform:process.platform}),signal:r.signal});if(!a.ok)throw new Error(`\u8BBE\u5907\u5165\u518C\u5931\u8D25 HTTP ${a.status}`);let i=await a.json();if(!i.unitId||!i.secret)throw new Error("\u8BBE\u5907\u5165\u518C\u54CD\u5E94\u7F3A\u5B57\u6BB5");return{unitId:i.unitId,secret:i.secret}}finally{o&&clearTimeout(o)}}async consume(e,n){let r=e.getReader(),s=new TextDecoder,o="",a=this.deps.readIdleMs??Pn,i=null,l=()=>{a&&(i&&clearTimeout(i),i=setTimeout(()=>{this.deps.log(`[unit-host] \u901A\u9053 ${Math.round(a/1e3)}s \u65E0\u4EFB\u4F55\u5B57\u8282(\u7F51\u5173 15s \u4E00\u6B21\u5FC3\u8DF3),\u5224\u5B9A\u5DF2\u65AD,\u91CD\u8FDE`),n.abort(),r.cancel().catch(()=>{})},a))};l();try{for(;;){let{done:h,value:d}=await r.read();if(h||n.signal.aborted)return;l(),o=this.parseFrames(o+s.decode(d,{stream:!0}),n)}}finally{i&&clearTimeout(i)}}parseFrames(e,n){let r=e,s;for(;(s=r.indexOf(`
196
+ `),{excludeFalseConflicts:!0}),s=[];for(let i of r){if(i.conflict)return null;i.ok&&s.push(...i.ok)}return s.join(`
197
+ `)}function Un(t,e,n=200){return t>=n||e>=5&&t>=Math.max(5,Math.ceil(e/2))}var Po=/[\u0000-\u001f\u007f]/;function ot(t){let e=t.replace(/\\/g,"/").normalize("NFC").trim();if(e=e.replace(/\/+$/,""),!e||e.length>512||e.startsWith("/")||Po.test(e))return null;let n=e.split("/");for(let r of n)if(!r||r==="."||r==="..")return null;return n.join("/")}function jn(t,e){let n=t.replace(/\\/g,"/").normalize("NFC");return e===""?ot(n):n.startsWith(`${e}/`)?ot(n.slice(e.length+1)):null}function ts(t,e){return e===""?t:`${e}/${t}`}function _t(t){return!!(t===".DS_Store"||t==="Icon\r"||t===".sync-trash"||/\.tmp-\d+-\d+-\d+$/.test(t)||/^\..+\.lock$/.test(t))}function De(t){return/\.md$/i.test(t)?"page":/\.db$/i.test(t)?"db":"binary"}var qe=t=>t==="page"||t==="db";import{gzip as Mo}from"node:zlib";import{promisify as Oo}from"node:util";var No=Oo(Mo),Uo=1024,ge=class extends Error{status;body;constructor(e,n,r){super(`cloud http ${e} on ${r}`),this.status=e,this.body=n}},ns=t=>12e4+Math.ceil(t/256);function rs(t){let e=`${t.baseUrl.replace(/\/+$/,"")}/api/amadeus`,n=async(s,i,o)=>{let a={Authorization:`Bearer ${t.token}`,...o?.headers};s!=="GET"&&(a["X-Amadeus-Client"]=t.clientId);let l;o?.json!==void 0?(a["Content-Type"]="application/json",l=JSON.stringify(o.json),l.length>=Uo&&(a["Content-Encoding"]="gzip",l=await No(l))):o?.form&&(l=o.form);let d=await fetch(i,{method:s,headers:a,body:l,signal:AbortSignal.timeout(o?.timeoutMs??3e4)});if(!d.ok){let f=null;try{f=await d.json()}catch{}throw new ge(d.status,f,i)}return d.json()},r=s=>new URLSearchParams(s).toString();return{clientId:t.clientId,async listVaults(){return((await n("GET",`${e}/vaults`)).vaults??[]).map(i=>({id:String(i.id),name:String(i.name),lastChangeSeq:Number(i.lastChangeSeq??0)}))},async tree(s){let i=await n("GET",`${e}/vaults/${s}/tree`);if(!Array.isArray(i.entries))throw new Error("server too old: tree has no entries[] (deploy the amadeus microserver update)");return{folders:i.folders??[],seq:Number(i.seq??0),maxFileBytes:Number.isInteger(i.maxFileBytes)&&i.maxFileBytes>0?i.maxFileBytes:void 0,entries:i.entries.map(o=>({path:String(o.path),kind:o.kind,seq:Number(o.seq??0),hash:o.hash??null,size:Number(o.size??0)}))}},async getFile(s,i){let o=await n("GET",`${e}/vaults/${s}/file?${r({path:i})}`);return{content:String(o.content??""),seq:Number(o.seq??0),hash:o.hash??null}},putFile(s,i,o,a,l=!1){return n("PUT",`${e}/vaults/${s}/file`,{json:{path:i,content:o,baseSeq:a,...l?{force:!0}:{}}})},async deleteFile(s,i,o,a){let l={path:i};o!==void 0&&(l.baseSeq=String(o)),await n("DELETE",`${e}/vaults/${s}/file?${r(l)}`,a?.confirmed?{headers:{"X-Amadeus-Delete-Confirmed":"1"}}:void 0)},move(s,i,o){return n("POST",`${e}/vaults/${s}/move`,{json:{from:i,to:o}})},renameFolder(s,i,o){return n("POST",`${e}/vaults/${s}/folders/rename`,{json:{path:i,newName:o}})},moveFolder(s,i,o){return n("POST",`${e}/vaults/${s}/folders/move`,{json:{path:i,dest:o}})},async deleteFolder(s,i){await n("DELETE",`${e}/vaults/${s}/folders?${r({path:i})}`)},putBinary(s,i,o,a){let l=new FormData;return l.set("path",i),a?.ifAbsent&&l.set("ifAbsent","true"),a?.baseSeq!==void 0&&l.set("baseSeq",String(a.baseSeq)),l.set("file",new Blob([new Uint8Array(o)]),i.split("/").pop()||"file"),n("POST",`${e}/vaults/${s}/binary`,{form:l,timeoutMs:ns(o.length)})},async listVersions(s,i){return((await n("GET",`${e}/vaults/${s}/file/versions?${r({path:i})}`)).versions??[]).map(a=>({id:String(a.id),seq:Number(a.seq??0)}))},async getVersion(s,i){let o=await n("GET",`${e}/vaults/${s}/file/versions/${i}`);return String(o.content??"")},async getAsset(s,i){let o=new AbortController,a=setTimeout(()=>o.abort(),12e4);try{let l=await fetch(`${e}/vaults/${s}/asset?${r({ref:i})}`,{headers:{Authorization:`Bearer ${t.token}`},signal:o.signal});if(!l.ok)throw new ge(l.status,null,"asset:"+i);return clearTimeout(a),a=setTimeout(()=>o.abort(),ns(Number(l.headers.get("content-length"))||0)),Buffer.from(await l.arrayBuffer())}finally{clearTimeout(a)}},async changes(s,i){let o=await n("GET",`${e}/vaults/${s}/changes?${r({since:String(i)})}`);return{changes:o.changes??[],seq:Number(o.seq??0)}}}}function ss(t,e){let n=!1,r=0,s=null,i=null,o=()=>`${t.baseUrl.replace(/\/+$/,"")}/api/amadeus/vaults/${t.vaultId}/events?since=${e.getSince()}`,a=d=>{if(n)return;e.onDown(d);let f=Math.min(3e4,1e3*2**r)*(.7+Math.random()*.6);r++,i=setTimeout(()=>void l(),f)},l=async()=>{if(n)return;s=new AbortController;let d;try{d=await fetch(o(),{headers:{Authorization:`Bearer ${t.token}`,Accept:"text/event-stream"},signal:s.signal})}catch(y){a(y);return}if(!d.ok||!d.body){a(new Error(`sse http ${d.status}`));return}r=0,e.onOpen();let f=d.body.getReader(),m=new TextDecoder,c="",h="",g=[],S=()=>{if(!g.length&&!h)return;let y=g.join(`
198
+ `),A=h||"message";h="",g=[];let R=null;try{R=y?JSON.parse(y):null}catch{return}A==="hello"?e.onHello(Number(R?.seq??0)):A==="change"?e.onChange(R):A==="reset"?e.onReset():A==="presence"?e.onPresence?.(R):A==="presence-roster"&&e.onPresenceRoster?.(R)};try{for(;;){let{done:y,value:A}=await f.read();if(y)break;for(c+=m.decode(A,{stream:!0});;){let R=c.indexOf(`
199
+ `);if(R<0)break;let T=c.slice(0,R).replace(/\r$/,"");if(c=c.slice(R+1),T==="")S();else{if(T.startsWith(":"))continue;T.startsWith("event:")?h=T.slice(6).trim():T.startsWith("data:")&&g.push(T.slice(5).replace(/^ /,""))}}}}catch(y){n||a(y);return}a(new Error("sse stream ended"))};return l(),{stop:()=>{n=!0,i&&clearTimeout(i),s?.abort()}}}import{constants as jo,promises as lt}from"node:fs";import Fo from"node:path";var at=t=>Fo.join(be().userDataDir(),be().isDevMode()?`${t}.dev.json`:`${t}.json`);async function Fn(t){try{let e=JSON.parse(await lt.readFile(at(t),"utf8"));return!e||typeof e.vaultRoot!="string"||typeof e.vaultId!="string"?null:(e.files=e.files??{},e.cursor=Number(e.cursor??0),e.lastSyncAt=e.lastSyncAt??null,e)}catch{return null}}function is(t){let e=null,n=null,r=Promise.resolve(),s=null,i=()=>{if(!e)return r;let o=e,a=JSON.stringify(e);return e=null,r=r.then(async()=>{try{let l=at(t),d=`${l}.tmp-${process.pid}-${Date.now()}-0`;await lt.writeFile(d,a,"utf8"),await lt.rename(d,l),s=null}catch(l){e??=o,s=l}}),r};return{save(o){e=o,!n&&(n=setTimeout(()=>{n=null,i()},500))},async flush(o=!1){if(n&&(clearTimeout(n),n=null),await i(),o&&s)throw s}}}async function os(t){try{await lt.unlink(at(t))}catch{}}async function as(t,e){try{await lt.copyFile(at(t),at(e),jo.COPYFILE_EXCL)}catch(n){let r=n?.code;if(r==="EEXIST"||r==="ENOENT")return!1;throw n}return await lt.unlink(at(t)).catch(()=>{}),!0}var Ho=5*1024*1024,zo=5*1024*1024,Bo=3e4,qo=2500,Wo=3e3,Vo=5,Yo=256*1024,Go=5,cs=1024*1024,us=200,Jo=6e4,Ko=50,Xo=".sync-trash",ct=t=>Lo("sha256").update(t).digest("hex");function kt(t,e={localRoot:Be(),shadowName:`amadeus-sync-${bt()}`,vaultId:"first",serverDir:"",excludePrefixes:["\u4E0E\u6211\u5171\u4EAB/"]}){let n=u=>{let p=jn(u,"");if(!p)return null;for(let w of e.excludePrefixes??[])if(p===w.replace(/\/$/,"")||p.startsWith(w))return null;if(e.ignoreNames?.length&&p.split("/").some(w=>e.ignoreNames.includes(w)))return null;let b=e.serverDir?`${e.serverDir}/${p}`:p;return e.inScope&&!e.inScope(b,De(b))?null:b},r=u=>{let p;if(e.serverDir){if(!u.startsWith(`${e.serverDir}/`))return null;p=u.slice(e.serverDir.length+1)}else{for(let b of e.excludePrefixes??[])if(u.startsWith(b))return null;p=u}return p.split("/").some(b=>_t(b)||!!e.ignoreNames?.includes(b))?null:p},s=(u,p)=>!e.inScope||e.inScope(u,p),i=e.accountId??Se(),o=!1,a=0,l=Promise.resolve(),d=new Set,f="disabled",m=null,c=null,h=null,g=null,S=null,y=null,A=0,R=new Map,T=null,I=is(e.shadowName),D=new Map,P=!1,L=!1,H=[],Q=()=>{c&&(c.pending=D.size?Object.fromEntries(D):void 0,I.save(c))},le=()=>{L=!1,H.length=0},me=()=>{if(L)return!0;let u=Date.now();for(;H.length&&u-H[0]>Jo;)H.shift();return H.length>=Ko?(L=!0,!0):!1},ce=[],ye=new Set,He=!1,v=null,C=null,E=null,_=()=>{!o||E||(E=setTimeout(()=>{E=null,t.onStatus(Ke())},200))},N=(u,p)=>{f=u,p!==void 0&&(m=p),_()},k=(u,p=!1)=>{if(o){if(u.key){if(ye.has(u.key))return;ye.add(u.key)}p?ce.unshift(u):ce.push(u),te()}},$=new Map,j=u=>{if(!o)return;let p=(c?.files[u]?.size??0)>Yo,b=(e.pushQuietMs??Wo)*(p?Go:1),w=Date.now(),x=$.get(u);x&&clearTimeout(x.timer);let O=x?.since??w,F=Math.max(0,Math.min(b,O+b*Vo-w)),M=setTimeout(()=>{$.delete(u),k({key:u,run:()=>he(u,!0)})},F);$.set(u,{timer:M,since:O}),_()},V=()=>{for(let{timer:u}of $.values())clearTimeout(u);$.clear()},B=u=>!(u instanceof ge)||u.status>=500||u.status===0,q=u=>u instanceof ge&&(u.status===401||u.status===403),te=async()=>{if(!He){He=!0;try{for(;ce.length;){(f==="idle"||f==="starting")&&N("syncing");let u=ce.shift();u.key&&ye.delete(u.key);try{await u.run()}catch(p){if(!o)return;if(q(p)){ce.length=0,ye.clear(),jt(),N("auth-required","login-expired");return}if(B(p)){k(u,!0),jt(),N("offline",p?.message||"network error"),ee();return}let b=u.key??"(op)";R.set(b,p?.body?.code||`http ${p?.status}`),_()}}o&&f==="syncing"&&(c&&(c.lastSyncAt=Date.now(),I.save(c)),N("idle",null))}finally{He=!1;for(let u of d)u();d.clear()}}},ee=()=>{!o||v||(v=setTimeout(()=>{v=null,yt()},Bo))},Z=u=>{if(!y||!c)throw new Error("engine not bound");let p=r(u);if(p===null)throw new Error("path outside binding: "+u);let b=ue.resolve(y,ts(p,c.folder)),w=ue.relative(y,b);if(w.startsWith("..")||ue.isAbsolute(w))throw new Error("path escapes vault: "+u);return b},se=u=>({size:u,mtimeMs:-1}),ne=async u=>{try{let p=await oe.stat(u);return p.isFile()?{size:p.size,mtimeMs:Math.floor(p.mtimeMs)}:null}catch{return null}},xe=0,Je=async(u,p,b=()=>!0)=>{await oe.mkdir(ue.dirname(u),{recursive:!0});let w=`${u}.tmp-${process.pid}-${Date.now()}-${xe++}`;await oe.writeFile(w,p);let x=await ne(w)??se(Buffer.byteLength(p));return b()?(await oe.rename(w,u),x):(await oe.rm(w,{force:!0}),null)},et=async u=>{let p;try{p=await oe.readdir(u,{withFileTypes:!0})}catch{return}for(let b of p)b.isDirectory()&&await et(ue.join(u,b.name));try{await oe.rmdir(u)}catch{}},de=async u=>{let p=Z(u),b=await ne(p),w;try{w=await oe.readFile(p)}catch{return null}return{hash:qe(De(u))?ct(w.toString("utf8")):ct(w),size:b?.size??w.length,mtimeMs:b?.mtimeMs??-1,buf:w}},Re=async(u,p,b,w)=>{c&&(c.files[u]={seq:p,hash:b,size:w.size,mtimeMs:w.mtimeMs},I.save(c))},ve=u=>{c&&u in c.files&&(delete c.files[u],I.save(c))},Oe=async(u,p)=>{if(!h||!c||Ce(u))return;let b=ae,w=De(u),x,O,F;if(qe(w)){let W;try{W=await h.getFile(c.vaultId,u)}catch(J){if(J instanceof ge&&J.status===404){await fn(u);return}throw J}x=W.content,O=W.seq,F=W.hash??ct(W.content)}else{let W;try{W=await h.getAsset(c.vaultId,u)}catch(J){if(J instanceof ge&&J.status===404){R.set(u,"ASSET_404"),_();return}throw J}x=W,O=p??0,F=ct(W)}let M=await de(u);if(b!==ae||Ce(u))return;if(M&&M.hash===F){await Re(u,O,F,M);return}let z=c.files[u];if(M&&z&&F===z.hash&&M.hash!==z.hash){await Re(u,O,F,se(z.size)),k({key:u,run:()=>he(u)});return}if(M&&(!z||M.hash!==z.hash)){if(z&&w==="page"&&typeof x=="string"&&await ni(u,z,M,x,O,F,()=>b===ae&&!Ce(u))||b!==ae||Ce(u))return;await ri(u)}let U=await Je(Z(u),x,()=>b===ae&&!Ce(u));U&&await Re(u,O,F,U)},ni=async(u,p,b,w,x,O,F)=>{try{if(!h||!c||b.buf.length>cs||w.length>cs)return!1;let z=(await h.listVersions(c.vaultId,u)).find(J=>J.seq===p.seq);if(!z)return!1;let U=await h.getVersion(c.vaultId,z.id);if(ct(U)!==p.hash)return!1;let W=es(b.buf.toString("utf8"),U,w);return W===null?!1:(await Je(Z(u),W,F)&&(await Re(u,x,O,se(Buffer.byteLength(W))),k({key:u,run:()=>he(u)})),!0)}catch{return!1}},ri=async u=>{let p=ot(en(u,new Date));if(!p)return;let b=p.lastIndexOf("."),w=b>p.lastIndexOf("/"),x=w?p.slice(0,b):p,O=w?p.slice(b):"",F=p;for(let M=2;ls(Z(F));M++)F=`${x}-${M}${O}`;try{await oe.rename(Z(u),Z(F))}catch(M){if(M?.code==="ENOENT")return;throw M}A++,k({key:F,run:()=>he(F)}),_()},tr=async u=>{if(!y)return;let p=Z(u),b=r(u)??u,w=ue.join(y,Xo,new Date().toISOString().slice(0,10),...b.split("/")),x=ls(w)?`${w}.${Date.now()}`:w;try{await oe.mkdir(ue.dirname(x),{recursive:!0}),await oe.rename(p,x)}catch(O){if(O?.code==="ENOENT")return;throw new Error(`\u8F6F\u5220\u5931\u8D25,\u4FDD\u7559\u672C\u5730\u6587\u4EF6 ${p}: ${O?.message??String(O)}`)}},fn=async u=>{if(!c)return;let p=await de(u);if(Ce(u))return;let b=c.files[u]??null,w=tn(p?.hash??null,b,null);if(w.kind==="deleteLocal"){if(!P&&me()){D.set(u,"local"),Q(),_();return}H.push(Date.now()),await tr(u),ve(u)}else w.kind==="pushCreate"?(ve(u),k({key:u,run:()=>he(u)})):ve(u)},nr=(u,p)=>{if(c){for(let b of Object.keys(c.files))if(b===u||b.startsWith(`${u}/`)){let w=p+b.slice(u.length);c.files[w]=c.files[b],delete c.files[b]}I.save(c)}},rr=async u=>{if(!h||!c||u.seq<=c.cursor||!await Ot())return;if(u.origin.client&&h.clientId===u.origin.client){c.cursor=u.seq,I.save(c);return}let p=u.type==="structure"?"folder":u.type,b=x=>r(x)!==null&&s(x,p);if(!b(u.path)&&!(u.newPath&&b(u.newPath))){c.cursor=u.seq,I.save(c);return}let w=u.path;switch(u.op){case"write":await Oe(w,u.fileSeq);break;case"delete":await fn(w);break;case"move":{let x=u.newPath;if(!x)break;let O=c.files[w];if(await de(w)&&O)try{await oe.mkdir(ue.dirname(Z(x)),{recursive:!0}),await oe.rename(Z(w),Z(x)),c.files[x]={...O,seq:u.fileSeq??O.seq},delete c.files[w],I.save(c)}catch{await Oe(x,u.fileSeq)}else ve(w),await Oe(x,u.fileSeq);break}case"mkdir":await oe.mkdir(Z(w),{recursive:!0});break;case"rename-folder":case"move-folder":{let x=u.newPath;if(!x)break;try{await oe.mkdir(ue.dirname(Z(x)),{recursive:!0}),await oe.rename(Z(w),Z(x))}catch{}nr(w,x);break}case"delete-folder":{let x=`${w}/`;for(let O of Object.keys(c.files))(O===w||O.startsWith(x))&&await fn(O);await et(Z(w));break}}if(c.cursor=u.seq,I.save(c),u.op==="move"||u.op==="rename-folder"||u.op==="move-folder"||u.op==="delete"||u.op==="delete-folder")try{await t.onRemoteApplied?.(u)}catch{}},si=async(u,p,b)=>{let w=Number(p?.seq??0),x=p?.content??null;if(x!==null&&ct(x)===b.hash){await Re(u,w,b.hash,b);return}if(x===null&&w===0){if(!c?.files[u]){R.set(u,p?.code||"EXISTS"),_();return}ve(u),k({key:u,run:()=>he(u)});return}await Oe(u,w)},Pt=async(u,p)=>{if(!h||!c)return;let b=await de(u);if(!b){k({key:u,run:()=>he(u)});return}if(b.size>Ho){R.set(u,"TOO_LARGE"),_();return}let w=b.buf.toString("utf8");try{let x=await h.putFile(c.vaultId,u,w,p);R.delete(u),await Re(u,x.seq,x.hash??b.hash,b)}catch(x){if(x instanceof ge&&x.status===409){await si(u,x.body,b);return}throw x}},Mt=async(u,p)=>{if(!h||!c)return;let b=await de(u);if(!b){k({key:u,run:()=>he(u)});return}if(b.size>(T??zo)){R.set(u,"TOO_LARGE"),_();return}try{let w=await h.putBinary(c.vaultId,u,b.buf,{baseSeq:p});R.delete(u),await Re(u,w.seq,b.hash,b)}catch(w){if(w instanceof ge&&w.status===409){let x=Number(w.body?.seq??0),O=w.body?.hash??null;if(O!==null&&O===b.hash){await Re(u,x,b.hash,b);return}if(x===0){if(!c.files[u]){R.set(u,w.body?.code||"EXISTS"),_();return}ve(u),k({key:u,run:()=>he(u)});return}await Oe(u,x);return}throw w}},sr=async u=>{if(!h||!c||Ce(u))return;let p=ae,b=c.files[u];if(b){if(qe(De(u)))try{let w=await h.getFile(c.vaultId,u);if(w.seq!==b.seq){await Oe(u,w.seq);return}}catch(w){if(w instanceof ge&&w.status===404){ve(u);return}throw w}if(!(p!==ae||Ce(u))){try{await h.deleteFile(c.vaultId,u,b.seq,{confirmed:P})}catch(w){if(w instanceof ge&&w.status===409){await Oe(u,Number(w.body?.seq??0)||null);return}if(w instanceof ge&&w.status===429&&w.body?.code==="MASS_DELETE_BLOCKED"){D.set(u,"remote"),L=!0,Q(),_();return}throw w}ve(u)}}},Ot=async()=>y?await oe.stat(y).then(p=>p.isDirectory()).catch(()=>!1)||!e.requireRootExists&&!Object.keys(c?.files??{}).length?!0:(N("error",`vault-missing: ${y}`),ee(),!1):!1,ae=0,Nt=new Set,Ut=new Map,Ee=u=>JSON.stringify([u.from,u.to]),ze=(u,p)=>u===p||u.startsWith(`${p}/`),Ce=u=>[...c?.moves??[],...Nt].some(p=>ze(u,p.from)||ze(u,p.to)),Ne=()=>!!(c?.moves?.length||Nt.size),mn=async u=>{if(!h||!c)return;let{from:p,to:b,kind:w}=u;if(r(p)===null||r(b)===null)throw new Error("Invalid queued cloud move");u.hashes??=Object.fromEntries(Object.entries(c.files).filter(([M])=>ze(M,p)).map(([M,z])=>[M.slice(p.length),z.hash])),I.save(c),await I.flush(!0);let x,O=!1;try{if(w==="folder"){let M=ue.posix.dirname(p)==="."?"":ue.posix.dirname(p),z=ue.posix.dirname(b)==="."?"":ue.posix.dirname(b);M===z?await h.renameFolder(c.vaultId,p,ue.posix.basename(b)):await h.moveFolder(c.vaultId,p,z)}else{let M=await h.move(c.vaultId,p,b);x=Number(M.seq)}}catch(M){if(!(M instanceof ge)||M.status!==404)throw M;let z=await h.tree(c.vaultId);if(z.entries.some(J=>ze(J.path,p))||z.folders.some(J=>ze(J,p)))throw M;let W=z.entries.find(J=>J.path===b);if(x=W?.seq,O=!W&&!z.entries.some(J=>ze(J.path,b))&&!z.folders.some(J=>ze(J,b)),!O){let J=Object.entries(u.hashes);if(!(J.length>0&&J.every(([$e,tt])=>z.entries.some(nt=>nt.path===b+$e&&nt.hash===tt))))throw new ge(409,{code:"MOVE_DESTINATION_CHANGED"},"local-move")}}if(O)for(let M of Object.keys(c.files))ze(M,p)&&delete c.files[M];else nr(p,b),x!==void 0&&c.files[b]&&(c.files[b].seq=x);c.moves=(c.moves??[]).filter(M=>Ee(M)!==Ee(u)),I.save(c);try{await I.flush(!0)}catch(M){throw c.moves.unshift(u),I.save(c),M}let F=Ut.get(Ee(u));Ut.delete(Ee(u)),F?.(),Ce(b)||(w==="folder"?await hn():await he(b))},he=async(u,p=!1)=>{if(!c||Ce(u))return;if(!s(u,De(u))){ve(u);return}if(!await Ot())return;let b=await de(u);if(Ce(u))return;let w=c.files[u]??null,x=tn(b?.hash??null,w,w?{seq:w.seq,hash:w.hash}:null);switch(x.kind){case"push":qe(De(u))?await Pt(u,x.baseSeq):await Mt(u,x.baseSeq);break;case"pushCreate":qe(De(u))?await Pt(u,0):await Mt(u,0);break;case"pushDelete":if(p){Lt();break}if(!P&&(D.has(u)||me())){D.set(u,"remote"),Q(),_();break}H.push(Date.now()),await sr(u);break;case"dropShadow":ve(u);break;default:b&&w&&b.hash===w.hash&&b.mtimeMs>=0&&(w.size!==b.size||w.mtimeMs!==b.mtimeMs)&&await Re(u,w.seq,w.hash,b);break}},ir=async()=>{let u=new Map;if(!y||!c)return u;let p=y,b=null,w=async x=>{if(b)return;let O;try{O=await oe.readdir(x,{withFileTypes:!0})}catch(F){b=`${x}: ${F?.message??String(F)}`;return}for(let F of O){if(_t(F.name)||F.isDirectory()&&e.ignoreNames?.includes(F.name))continue;let M=ue.join(x,F.name);if(F.isDirectory())await w(M);else if(F.isFile()){let z=ue.relative(p,M).split(ue.sep).join("/"),U=n(z);if(!U)continue;try{let W=await oe.stat(M);if(!W.isFile())continue;u.set(U,{size:W.size,mtimeMs:Math.floor(W.mtimeMs)})}catch(W){if(W?.code==="ENOENT")continue;b=`${M}: ${W?.message??String(W)}`;return}}}};return await w(p),b?(N("error",`scan-failed: ${b}`),ee(),null):u},hn=async()=>{let u=ae;if(Ne()||u!==ae||!c||!await Ot())return;let p=await ir();if(!p||Ne()||u!==ae)return;let b=!1;for(let[O,F]of[...D])(F==="remote"&&p.has(O)||F==="local"&&!p.has(O))&&(D.delete(O),b=!0);D.size||le();for(let[O,F]of p){let M=c.files[O];M&&M.size===F.size&&M.mtimeMs===F.mtimeMs||k({key:O,run:()=>he(O)})}let w=Object.keys(c.files),x=w.filter(O=>!p.has(O));if(x.length&&!P&&(L||Un(x.length,w.length,us))){L=!0;for(let O of x)D.set(O,"remote");Q(),_();return}b&&(Q(),_());for(let O of x)D.has(O)||k({key:O,run:()=>he(O)})},pt=async()=>{let u=ae;if(Ne()||u!==ae||!h||!c||!y||!await Ot())return;let p=await h.tree(c.vaultId);if(p.maxFileBytes!==void 0&&p.maxFileBytes!==T&&(T=p.maxFileBytes,_()),Ne()||u!==ae)return;let b=new Map;for(let U of p.entries)r(U.path)===null||!s(U.path,U.kind)||b.set(U.path,U);let w=await ir();if(!w||Ne()||u!==ae)return;let x=new Set([...b.keys(),...w.keys(),...Object.keys(c.files)]),O=Object.keys(c.files).length,F=[];for(let U of x){if(Ne()||u!==ae)return;let W=c.files[U]??null,J=b.get(U)??null,pe=w.get(U)??null,$e=null,tt=se(pe?.size??0);if(pe)if(W&&W.size===pe.size&&W.mtimeMs===pe.mtimeMs)$e=W.hash,tt=pe;else{let nt=await de(U);nt&&($e=nt.hash,tt=nt)}F.push({sp:U,d:tn($e,W,J?{seq:J.seq,hash:J.hash}:null),rSeq:J?.seq??null,localHash:$e,localStat:tt})}if(Ne()||u!==ae)return;let M=F.filter(U=>U.d.kind==="deleteLocal"||U.d.kind==="pushDelete").length,z=!P&&(L||Un(M,O,us));z&&M&&(L=!0),D.clear();for(let{sp:U,d:W,rSeq:J,localHash:pe,localStat:$e}of F){if(Ne()||u!==ae)return;if(z&&(W.kind==="deleteLocal"||W.kind==="pushDelete")){D.set(U,W.kind==="deleteLocal"?"local":"remote");continue}if((W.kind==="deleteLocal"||W.kind==="pushDelete")&&((await de(U))?.hash??null)!==pe){k({key:U,run:()=>he(U)});continue}if(Ne()||u!==ae)return;switch(W.kind){case"adopt":await Re(U,J,pe,$e);break;case"pull":await Oe(U,J);break;case"push":qe(De(U))?await Pt(U,W.baseSeq):await Mt(U,W.baseSeq);break;case"pushCreate":qe(De(U))?await Pt(U,0):await Mt(U,0);break;case"pushDelete":await sr(U);break;case"deleteLocal":await tr(U),ve(U);break;case"conflict":await Oe(U,J);break;case"dropShadow":ve(U);break;case"none":break}}P&&(P=!1,H.length=0),D.size||le(),Q(),z&&_();for(let U of p.folders)if(!(r(U)===null||!s(U,"folder")))try{await oe.mkdir(Z(U),{recursive:!0})}catch{}c.cursor=p.seq,c.lastSyncAt=Date.now(),I.save(c)},ii=async()=>{if(!h||!c)return;let u=c.cursor,p=await h.changes(c.vaultId,u);if(p.changes.length===0&&p.seq>u||p.changes.length>0&&p.changes[0].seq!==u+1){await pt();return}for(let w of p.changes)await rr(w)},Ue=null,or=[],ar=()=>{Ue&&or.push(Ue.close()),Ue=null},oi=()=>{if(!o||Ue||!y)return;Ue=Xr.watch(y,{ignoreInitial:!0,depth:12,ignored:p=>{let b=ue.basename(p);return _t(b)||!!e.ignoreNames?.includes(b)}});let u=p=>{if(!y)return;let b=ue.relative(y,p);if(!b||b.startsWith(".."))return;let w=n(b);w&&j(w)};Ue.on("change",u),Ue.on("add",u),Ue.on("unlink",()=>Lt()),Ue.on("unlinkDir",()=>Lt())},jt=()=>{g?.stop(),g=null},ai=()=>{if(!o||!h||!c||g)return;let u=S;u&&(g=ss({baseUrl:u.cloudUrl,vaultId:c.vaultId,token:u.token},{getSince:()=>c?.cursor??0,onHello:p=>{c&&p>c.cursor&&k({run:ii})},onChange:p=>{k({run:()=>rr(p)})},onReset:()=>{k({run:pt})},onOpen:()=>{(f==="offline"||f==="starting")&&N("idle",null),k({run:hn})},onDown:()=>{(f==="idle"||f==="syncing")&&N("offline")},onPresence:p=>t.onPresence?.(c?.vaultId??"",p),onPresenceRoster:p=>t.onPresenceRoster?.(c?.vaultId??"",p)}))},li=async()=>{let u=await Ae(i);if(u.cloudSync?.deviceId)return u.cloudSync.deviceId;let p=`desk-${Math.random().toString(36).slice(2,10)}${Date.now().toString(36)}`;return await je({cloudSync:{...u.cloudSync??{},deviceId:p}},i),p},ci=async u=>{jt(),ar(),ce.length=0,ye.clear(),D.clear(),P=!1,L=!1,H.length=0;let p=await Ae(i);if(u!==a)return;let b=p.cloudSync;if(b?.enabled===!1){y=null,h=null,N("disabled",null);return}if(!i||i!==Se()){N("auth-required","not-logged-in");return}if(y=e.localRoot,e.requireRootExists){let F=await oe.stat(y).then(M=>M.isDirectory()).catch(()=>!1);if(u!==a)return;if(!F){N("error",`vault-missing: ${y}`),ee();return}}if(u!==a)return;let w=t.loadCreds();if(!w.cloudUrl||!w.token){h=null,N("auth-required","not-logged-in");return}N("starting",null);let x=b?.deviceId??await li();if(u!==a)return;let O=e.clientIdSuffix?`${x}#${e.clientIdSuffix}`:x;S={cloudUrl:w.cloudUrl,token:w.token},h=rs({baseUrl:w.cloudUrl,token:w.token,clientId:O});try{let F=e.vaultId==="first"?b?.vaultId:e.vaultId;if(!F){let z=await h.listVaults();if(u!==a)return;if(!z.length)throw new Error("\u4E91\u7AEF\u65E0\u53EF\u7528 vault");F=z[0].id,await je({cloudSync:{...b??{},vaultId:F}},i)}if(u!==a)return;let M=await Fn(e.shadowName);if(u!==a||(c=M&&M.vaultRoot===y&&M.vaultId===F&&M.folder===""?M:{vaultRoot:y,folder:"",vaultId:F,cursor:0,lastSyncAt:null,files:{}},u!==a))return;for(let[z,U]of Object.entries(c.pending??{}))D.set(z,U);if(D.size&&(L=!0),!e.requireRootExists){let z=await oe.stat(y).then(U=>U.isDirectory()).catch(()=>!1);if(u!==a)return;if(!z){if(Object.keys(c.files).length){N("error",`mirror-missing: ${y}`),ee();return}if(await oe.mkdir(y,{recursive:!0}),u!==a)return}}oi();for(let z of c.moves??[])k({key:`move:${Ee(z)}`,run:()=>mn(z)});k({run:pt}),k({run:async()=>{ai()}})}catch(F){if(u!==a)return;q(F)?N("auth-required","login-expired"):(N("offline",F?.message||String(F)),ee())}},lr=()=>{o=!1,jt(),ar(),ce.length=0,ye.clear(),V();for(let u of[v,C,E])u&&clearTimeout(u);v=C=E=null},cr=async()=>{He&&await new Promise(u=>d.add(u)),await Promise.all(or.splice(0)),await I.flush(),c=null,h=null,S=null,y=null,A=0,R.clear(),T=null,D.clear(),P=!1,L=!1,H.length=0,f="disabled",m=null},ui=()=>{ur()},Ft=null,yt=()=>{Ft?.(),Ft=be().onBeforeQuit(ui);let u=++a;lr();let p=l.catch(()=>{}).then(async()=>{await cr(),u===a&&(o=!0,await ci(u))});return l=p,p},ur=()=>{Ft?.(),Ft=null,++a,lr();let u=l.catch(()=>{}).then(cr);return l=u,u},Ke=()=>({enabled:f!=="disabled",state:f==="idle"&&$.size?"syncing":f,lastSyncAt:c?.lastSyncAt??null,pending:ce.length+$.size,conflicts:A,skipped:[...R].map(([u,p])=>({path:u,reason:p})),error:m,pendingDeletions:D.size,maxFileBytes:T});return{getStatus:Ke,start(){yt()},notifyLocal(u,p,b){if(!c||f==="disabled"||f==="auth-required")return;let w=n(u),x=b?n(b):null;if(p==="write"&&w){_t(w.split("/").pop()||"")||j(w);return}if(p==="remove"){if(!w)return;let O=`${w}/`,F=!1;for(let M of Object.keys(c.files))(M===w||M.startsWith(O))&&(F=!0,k({key:M,run:()=>he(M)}));!F&&w&&k({key:w,run:()=>he(w)})}},holdLocalMove(u,p){let b=x=>e.serverDir?`${e.serverDir}/${x.replace(/\\/g,"/").normalize("NFC")}`:x.replace(/\\/g,"/").normalize("NFC"),w={from:b(u),to:b(p)};return++ae,Nt.add(w),()=>{Nt.delete(w)}},async notifyLocalMove(u,p,b,w){let x=n(u),O=n(p),F=c??await Fn(e.shadowName),M=jn(u,""),z=M&&(e.serverDir?`${e.serverDir}/${M}`:M);if(!x&&O&&z&&F&&Object.keys(F.files).some(U=>U===z||U.startsWith(`${z}/`))&&(x=z),!x&&!O){b?.();return}if(x&&O){let U=c??F;if(!U){b?.();return}let W=w??(Object.keys(U.files).some(pe=>pe.startsWith(`${x}/`))?"folder":"file"),J={from:x,to:O,kind:W};U.moves??=[],U.moves.some(pe=>Ee(pe)===Ee(J))||(U.moves.push(J),++ae),b&&Ut.set(Ee(J),b),I.save(U);try{await I.flush(!0)}catch(pe){throw U.moves=U.moves.filter($e=>Ee($e)!==Ee(J)),Ut.delete(Ee(J)),I.save(U),pe}c===U&&o&&f!=="disabled"&&f!=="auth-required"&&k({key:`move:${Ee(J)}`,run:()=>mn(J)});return}x&&this.notifyLocal(u,"remove"),O&&(k({key:O,run:()=>he(O)}),Lt()),b?.()},async setEnabled(u){let p=await Ae(i);return await je({cloudSync:{...p.cloudSync??{},enabled:u}},i),await yt(),Ke()},async restart(){return await yt(),Ke()},async syncNow(){if(R.clear(),f==="disabled"||f==="auth-required"||!h)await yt();else{for(let u of c?.moves??[])k({key:`move:${Ee(u)}`,run:()=>mn(u)});k({run:pt})}return Ke()},confirmMassDeletions(){return D.size&&(P=!0,L=!1,D.clear(),H.length=0,Q(),k({run:pt})),Ke()},stop:ur};function Lt(){o&&(C&&clearTimeout(C),C=setTimeout(()=>{C=null,k({run:hn})},qo))}}import{createHash as Zo}from"node:crypto";function ds(t){let e=t.replace(/\.md$/i,""),n=t.lastIndexOf("/"),r=n<0?"":t.slice(0,n);return{root:t,fdPrefix:`${e}.fd/`,assetPrefix:r?`${r}/.amadeus/`:".amadeus/"}}function fs(t,e,n){return!!(e===t.root||e.startsWith(t.fdPrefix)||`${e}/`===t.fdPrefix||n==="binary"&&e.startsWith(t.assetPrefix)||n==="folder"&&(`${e}/`===t.assetPrefix||e.startsWith(t.assetPrefix)))}var Qo=t=>Zo("sha256").update(t).digest("hex").slice(0,8),ea=t=>t.replace(/[\\/:*?"<>|]/g," ").trim().slice(0,40)||"shared",nn="\u4E0E\u6211\u5171\u4EAB";function Ln(t){let e=Qo(`${t.vaultId}:${t.path}`),n=ds(t.path),r=t.path.includes("/")?t.path.slice(0,t.path.lastIndexOf("/")):"";return{key:e,vaultId:t.vaultId,rootPath:t.path,title:t.title,localRelDir:`${nn}/${ea(t.title)}-${e}`,serverDir:r,inScope:(s,i)=>fs(n,s,i)}}function Hn(){let t=be().readCreds(),e=Te(t.cloudUrl??"",t.token??""),n=new AbortController,r=()=>{let m=be().readCreds();if(n.signal.aborted||!e||Te(m.cloudUrl??"",m.token??"")!==e)throw Object.assign(new Error("Cloud account changed; retry from the current account"),{status:401});return m},s=()=>{let m=r();if(!m.cloudUrl||!m.token)throw Object.assign(new Error("\u672A\u767B\u5F55 Forsion \u8D26\u53F7"),{status:401});return m.cloudUrl.replace(/\/+$/,"")},i=async(m,c,h)=>{let g=r();if(!g.cloudUrl||!g.token)throw Object.assign(new Error("\u672A\u767B\u5F55 Forsion \u8D26\u53F7"),{status:401});let S=await fetch(`${g.cloudUrl.replace(/\/+$/,"")}/api/amadeus${c}`,{method:m,headers:{Authorization:`Bearer ${g.token}`,...h!==void 0?{"Content-Type":"application/json"}:{}},body:h!==void 0?JSON.stringify(h):void 0,signal:AbortSignal.any([n.signal,AbortSignal.timeout(2e4)])});if(!S.ok){let A=null;try{A=await S.json()}catch{}throw Object.assign(new Error(A?.detail||`http ${S.status}`),{status:S.status,code:A?.code})}let y=await S.json();return r(),y},o=null,a=async()=>(r(),o||(o=(await i("GET","/vaults")).vaults[0]?.id??"default",o)),l=()=>{try{let m=(r().token??"").split(".")[1],c=JSON.parse(Buffer.from(m.replace(/-/g,"+").replace(/_/g,"/"),"base64").toString());return typeof c.userId=="string"?c.userId:null}catch{return null}},d=async()=>(await i("GET","/shared-with-me")).items.map(c=>{let h=Ln(c),g=c.path.split("/").pop()??c.path;return{...c,localPath:`${h.localRelDir}/${g}`}}),f=null;return{stop:()=>n.abort(),call:i,ensureOwnVault:a,myUserId:l,sharedWithMe:d,linkBase:async()=>{if(r(),f)return f;try{f=((await i("GET","/collab/link-base")).webOrigin??"").trim().replace(/\/+$/,"")||s()}catch{f=s()}return f},async heartbeat(m,c){let h=(m??"").replace(/\\/g,"/"),g,S=null,y=c.find(A=>h.startsWith(`${A.localRelDir}/`));y?(g=y.vaultId,S=y.serverDir?`${y.serverDir}/${h.slice(y.localRelDir.length+1)}`:h.slice(y.localRelDir.length+1)):(g=await a(),S=h||null),await i("POST",`/vaults/${encodeURIComponent(g)}/presence`,{page:S})}}}import{promises as ms}from"node:fs";import ta from"node:path";var zn=".forsion-vault.md",Bn=t=>`${t}/${zn}`;var ke=t=>t.replace(/\\/g,"/").normalize("NFC");function qn(t){let e=ke(t.path);return e?t.kind==="folder"?`${e}/`:t.kind==="page"?`${e.replace(/\.md$/i,"")}.fd/`:null:null}function ut(t,e,n){let r=ke(n);if(!r)return!1;if(t.some(s=>ke(s.path)===r))return!0;for(let s of e??[]){let i=ke(s);if(!i)continue;let o=`${i.replace(/\.md$/i,"")}.fd`;if(r===i||r.startsWith(`${i}/`)||r===o||r.startsWith(`${o}/`))return!1}return t.some(s=>{let i=qn(s);return!!i&&r.startsWith(i)})}function Wn(t,e,n){let r=ke(t),s=ke(e);return r===s?ke(n):r.startsWith(`${s}/`)?ke(n)+r.slice(s.length):null}function vt(t,e,n){let r=!1,s=t.map(i=>{let o=Wn(i,e,n);return o===null?i:(r=!0,o)});return{changed:r,next:s}}async function hs(t){let e=await ms.readdir(t,{withFileTypes:!0}).catch(()=>[]),n=[];for(let r of e)!r.isDirectory()||r.name.startsWith(".")||await ms.access(ta.join(t,r.name,zn)).then(()=>!0,()=>!1)&&n.push(r.name);return n.sort()}var fe={get:"amadeus:sync:get",setEnabled:"amadeus:sync:set-enabled",syncNow:"amadeus:sync:now",confirmDeletions:"amadeus:sync:confirm-deletions",status:"amadeus:sync:status",switchSide:"amadeus:sync:switch-side",collabCall:"amadeus:collab:call",presence:"amadeus:collab:presence",entryGet:"amadeus:entry-sync:get",entryEnable:"amadeus:entry-sync:enable",entryDisable:"amadeus:entry-sync:disable",entryClosure:"amadeus:entry-sync:closure",entryChange:"amadeus:entry-sync:change",otherSideDbs:"amadeus:entry-sync:other-side-dbs"};import{createHash as na}from"node:crypto";var rn=t=>na("sha256").update(t).digest("hex").slice(0,8);function gs(t){return t.replace(/ \(conflict \d{4}-\d{2}-\d{2} \d{4}\)(?=(?:\.[^./]+)?$)/,"")}function We(t,e=[]){let n=[],r=[];for(let s of t){let i=ke(s.path);if(!i)continue;r.push(i);let o=qn(s);o&&n.push(o)}return{entries:t,exclude:e,prefixes:n,paths:r}}function ps(t,e){let n=gs(ke(e));if(!n)return!1;if(ut(t.entries,t.exclude,n))return!0;let r=`${n}/`;for(let s of t.paths)if(s.startsWith(r))return!0;for(let s of t.prefixes)if(s.startsWith(r))return!0;return!1}function xt(t,e,n){let r=!1,s=t.map(i=>{let o=Wn(i.path,e,n);return o===null?i:(r=!0,{...i,path:o})});return{changed:r,next:s}}function ys(t,e,n,r){if(e==="delete"||e==="delete-folder"){let s=ke(n),i=t.filter(o=>{let a=ke(o.path);return!(a===s||e==="delete-folder"&&a.startsWith(`${s}/`))});return{changed:i.length!==t.length,next:i}}return r?xt(t,n,r):{changed:!1,next:t}}function Vn(t,e){let n=ot(t);return!n||n!==t.normalize("NFC").trim()?"\u540D\u79F0\u4E0D\u5408\u6CD5":n.includes("/")?"\u540D\u79F0\u4E0D\u80FD\u5305\u542B /":n===nn?`\u300C${nn}\u300D\u662F\u4FDD\u7559\u540D\u79F0`:e.includes(n)?"\u8BE5\u540D\u79F0\u5DF2\u88AB\u5176\u4ED6\u667A\u5E93\u7684\u4E91\u540C\u6B65\u5360\u7528":null}var ws=["setAmadeusSyncFactory","readCreds","accountId","homeDir"],Yn=t=>ws.every(e=>typeof t[e]=="function"),ra=()=>({enabled:!1,state:"disabled",lastSyncAt:null,pending:0,conflicts:0,skipped:[],error:null,pendingDeletions:0,maxFileBytes:null,side:"local"});function Gn(t){let e=null,n=()=>{if(!e)throw new Error("Cloud sync is not ready");return e};t.handle(fe.get,()=>e?e.get():ra()),t.handle(fe.setEnabled,(r,s)=>n().setEnabled(s)),t.handle(fe.syncNow,()=>n().syncNow()),t.handle(fe.confirmDeletions,()=>n().confirmDeletions()),t.handle(fe.entryGet,()=>n().entryGet()),t.handle(fe.otherSideDbs,()=>n().otherSideDbs()),t.handle(fe.entryEnable,(r,s)=>n().entryEnable(s)),t.handle(fe.entryDisable,(r,s)=>n().entryDisable(s)),t.handle(fe.entryClosure,(r,s,i)=>n().entryClosure(s,i)),t.handle(fe.collabCall,(r,s,i)=>n().collabCall(s,i)),t.handle(fe.switchSide,(r,s)=>n().switchSide(r.sender.id,s)),t.setAmadeusSyncFactory(r=>{Rr(r);let s=bs(r);return e=s.handlers,s.instance}),t.log("[forsion-extend] amadeus cloud sync registered")}function bs(t){let e=t.notifyAll,n=()=>t.vaultRoot(),r=0,s=!1,i=Hn(),o=new Map,a=()=>{let v=Date.now();for(let[C,E]of o)v-E.at>7e4&&o.delete(C);e(fe.presence,[...o.values()])},l={loadCreds:()=>t.readCreds(),onStatus:v=>e(fe.status,{...v,pendingDeletions:H(),side:g()?"cloud":"local"}),onPresence:(v,C)=>{let E=C;E?.userId&&(o.set(E.userId,{userId:E.userId,username:String(E.username??"user"),page:E.page??null,at:Number(E.at)||Date.now()}),a())},onPresenceRoster:(v,C)=>{if(Array.isArray(C)){for(let E of C){let _=E;_?.userId&&o.set(_.userId,{userId:_.userId,username:String(_.username??"user"),page:_.page??null,at:Number(_.at)||Date.now()})}a()}}},d=()=>{let v=r;return{...l,onStatus:C=>{v===r&&l.onStatus(C)},onPresence:(C,E)=>{v===r&&l.onPresence(C,E)},onPresenceRoster:(C,E)=>{v===r&&l.onPresenceRoster(C,E)}}},f=kt(d()),m=new Map,c=[],h=async()=>{if(!s||!Se())return;let v=r,C=i,E;try{E=await C.sharedWithMe()}catch{return}if(v!==r||!s)return;let _=E.map(k=>Ln(k));c=_;let N=new Set(_.map(k=>k.key));for(let[k,$]of m)if(!N.has(k)){if(await $.engine.stop(),v!==r)return;m.delete(k)}for(let k of _){if(m.has(k.key))continue;let $=kt(d(),{localRoot:Ze.join(Be(),...k.localRelDir.split("/")),shadowName:`amadeus-sync-${bt()}-share-${k.key}`,vaultId:k.vaultId,serverDir:k.serverDir,inScope:k.inScope});m.set(k.key,{engine:$,plan:k}),$.start()}},g=()=>n()===Be(),S=(v,C=v.base)=>{v.base=C;let E=[C,...v.pendingMoves];v.scope.current=We(E.flatMap(_=>_.entries),E.flatMap(_=>_.exclude))},y=new Map,A=new Set,R=()=>{e(fe.entryChange)},T=async(v,C)=>{let E=y.get(v);if(!E)return;let _=$=>$&&$.startsWith(`${E.cloudName}/`)?$.slice(E.cloudName.length+1):null,N=_(C.path);if(!N)return;let k=!1;await rt($=>{if(y.get(v)!==E)return!1;let j=($.entrySync??[]).find(ee=>ee.vaultRoot===v);if(!j)return!1;let V=C.op,B=_(C.newPath),q=ys(j.entries,V,N,B),te=B?vt(j.exclude??[],N,B):{changed:!1,next:j.exclude??[]};if(!q.changed&&!te.changed)return!1;k=!0,j.entries=q.next,te.changed&&(j.exclude=te.next),S(E,We(j.entries,j.exclude??[]))}),k&&y.get(v)===E&&R()},I=v=>{let C=r;return{...d(),onStatus:E=>{C===r&&e(fe.status,{...E,pendingDeletions:H(),side:"local",binding:v})},onRemoteApplied:async E=>{C===r&&await T(v,E)}}},D=async()=>{let v=Se();if(!s||!v)return;let C=r,E=i,_=bt(v);await t.adoptLegacyCloudState(v,as);let N=await Ae(v),k=N.entrySync??[];if(C!==r||!s||v!==Se())return;let $=new Map(k.map(j=>[j.vaultRoot,j]));for(let[j,V]of y){let B=$.get(j);if(!(B&&B.cloudName===V.cloudName)&&(await V.engine.stop(),C!==r||(y.delete(j),B&&await os(`amadeus-sync-${_}-entry-${rn(j)}`),C!==r)))return}for(let j of k){let V=y.get(j.vaultRoot);if(V){S(V,We(j.entries,j.exclude??[]));continue}let B={current:We(j.entries,j.exclude??[])},q=j.cloudName,te=kt(I(j.vaultRoot),{accountId:v,localRoot:j.vaultRoot,shadowName:`amadeus-sync-${_}-entry-${rn(j.vaultRoot)}`,vaultId:"first",serverDir:q,clientIdSuffix:`entry-${rn(j.vaultRoot)}`,requireRootExists:!0,ignoreNames:[".git","node_modules",".trash"],inScope:ee=>ee===q?!0:ee.startsWith(`${q}/`)?ps(B.current,ee.slice(q.length+1)):!1});y.set(j.vaultRoot,{engine:te,scope:B,cloudName:q,base:B.current,pendingMoves:new Set}),te.start()}if(N.cloudSync?.enabled!==!1)for(let j of k)A.has(j.cloudName)||(async()=>{try{let V=await E.ensureOwnVault();await E.call("PUT",`/vaults/${encodeURIComponent(V)}/file`,{path:Bn(j.cloudName),content:"",baseSeq:0}),C===r&&A.add(j.cloudName)}catch(V){V?.status===409&&C===r&&A.add(j.cloudName)}})()},P=async(v,C,E,_,N)=>{let k=C.replace(/\\/g,"/").normalize("NFC"),$=E.replace(/\\/g,"/").normalize("NFC"),j=!1,V,B,q,te=N??"file";try{await rt(async ee=>{if(y.get(v)!==_)return!1;let Z=(ee.entrySync??[]).find(de=>de.vaultRoot===v);if(!Z)return!1;let se=xt(Z.entries,k,$),ne=vt(Z.exclude??[],k,$),xe=ut(Z.entries,Z.exclude,k);!N&&await dt.stat(Ze.join(v,...$.split("/"))).then(de=>de.isDirectory(),()=>!1)&&(te="folder");let Je=te==="folder"?"folder":/\.md$/i.test($)?"page":"asset";xe&&!ut(se.next,ne.next,$)&&(se.next.push({path:$,kind:Je}),se.changed=!0),j=se.changed||ne.changed;let et=Z.entries.filter(de=>xt([de],k,$).changed);return xe&&!et.some(de=>de.path===k)&&et.push({path:k,kind:Je}),V=We(et,(Z.exclude??[]).filter(de=>vt([de],k,$).changed)),B=_.base,_.pendingMoves.add(V),Z.entries=se.next,Z.exclude=ne.next,q=We(Z.entries,Z.exclude),S(_,q),j})}catch(ee){throw V&&_.pendingMoves.delete(V),S(_,_.base===q&&B?B:_.base),ee}try{V&&await _.engine.notifyLocalMove(k,$,()=>{_.pendingMoves.delete(V),S(_)},te)}catch(ee){throw V&&_.pendingMoves.delete(V),await rt(Z=>{let se=Z.entrySync?.find(ne=>ne.vaultRoot===v);if(!se)return!1;se.entries=xt(se.entries,$,k).next,se.exclude=vt(se.exclude??[],$,k).next,S(_,We(se.entries,se.exclude))}),ee}j&&y.get(v)===_&&R()},L=v=>{let C=v.replace(/\\/g,"/");for(let{engine:E,plan:_}of m.values())if(C.startsWith(`${_.localRelDir}/`))return{engine:E,rel:C.slice(_.localRelDir.length+1)};return{engine:f,rel:C}};t.setMutationHooks((v,C)=>{if(g()){let E=L(v);E.engine.notifyLocal(E.rel,C);return}y.get(n()??"")?.engine.notifyLocal(v,C)},(v,C,E)=>{if(g()){let k=L(v),$=L(C);if(k.engine===$.engine)return k.engine.notifyLocalMove(k.rel,$.rel,void 0,E);k.engine.notifyLocal(k.rel,"remove"),$.engine.notifyLocal($.rel,"write");return}let _=n()??"",N=y.get(_);if(N)return P(_,v,C,N,E)},(v,C)=>{if(g()){let E=L(v),_=L(C),N=[E.engine.holdLocalMove(E.rel,_.rel)];return E.engine!==_.engine&&N.push(_.engine.holdLocalMove(E.rel,_.rel)),()=>{for(let k of N)k()}}return y.get(n()??"")?.engine.holdLocalMove(v,C)});let H=()=>{let v=f.getStatus().pendingDeletions;for(let{engine:C}of m.values())v+=C.getStatus().pendingDeletions;for(let{engine:C}of y.values())v+=C.getStatus().pendingDeletions;return v},Q=v=>({...v,pendingDeletions:H(),side:g()?"cloud":"local"}),le=()=>{if(!s)return Promise.resolve(f.getStatus());h();for(let{engine:v}of m.values())v.syncNow();for(let{engine:v}of y.values())v.syncNow();return f.syncNow()},me=async()=>{++r,s=!1,i.stop();let v=[f.stop(),...[...m.values()].map(({engine:E})=>E.stop()),...[...y.values()].map(({engine:E})=>E.stop())];m.clear(),y.clear(),c=[],A.clear(),o.clear(),a(),await Promise.all(v),await t.awaitPendingVaultWrites();let C=n();if(C&&Wt(C)){let E=await Ae(),_=E.localVault&&!Wt(E.localVault)?E.localVault:Ze.join(t.workspaceDir(),"Amadeus");await dt.mkdir(_,{recursive:!0}),await je({lastVault:_,localVault:_,lastPage:void 0}),await t.activateRoot(_,!1)}R()};return{handlers:{get:()=>Q(f.getStatus()),setEnabled:async v=>{if(!s)throw new Error("Cloud account is changing");let C=r;return await f.setEnabled(v),C!==r?f.getStatus():(await Promise.all([...m.values(),...y.values()].map(({engine:E})=>E.restart())),Q(f.getStatus()))},syncNow:()=>le(),confirmDeletions:()=>{for(let{engine:v}of m.values())v.confirmMassDeletions();for(let{engine:v}of y.values())v.confirmMassDeletions();return Q(f.confirmMassDeletions())},entryGet:async()=>{let v=await Ae(),C=Be();return{vaults:v.entrySync??[],activeRoot:n(),cloudRoot:C,mirrorVaults:await hs(C)}},otherSideDbs:async()=>{let v=n();if(!v)return null;let C=Be(),E=await Ae(),_=v===C?E.localVault&&E.localVault!==C?E.localVault:null:C;if(!_)return null;let N=[],k=500,$=async(j,V)=>{if(N.length>=k)return;let B;try{B=await dt.readdir(j,{withFileTypes:!0})}catch{return}for(let q of B){if(N.length>=k)break;if(q.name.startsWith(".")||q.isSymbolicLink())continue;let te=V?`${V}/${q.name}`:q.name;if(q.isDirectory())await $(Ze.join(j,q.name),te);else if(q.isFile()&&/\.db$/i.test(q.name))try{N.push({rel:te,source:await dt.readFile(Ze.join(j,q.name),"utf8")})}catch{}}};return await $(_,""),{root:_,vaultName:_===C?"\u4E91\u7AEF":Ze.basename(_),dbs:N}},entryEnable:async v=>{let C=r,E=i;if(!s||!Se())return{error:"Sign in to enable cloud sync"};let _=n();if(!_||g())return{error:"\u4EC5\u672C\u5730 vault \u53EF\u5F00\u542F\u4E91\u540C\u6B65"};let N=await Ae(),k=N.entrySync??[],$=k.find(j=>j.vaultRoot===_);if(!$){let j=(v.cloudName??Ze.basename(_)).normalize("NFC").trim(),V=Vn(j,k.map(B=>B.cloudName));if(V)return{error:V};if(!v.merge)try{let B=await E.ensureOwnVault(),q=await E.call("GET",`/vaults/${encodeURIComponent(B)}/tree`);if((q.folders??[]).some(ee=>ee===j||ee.startsWith(`${j}/`))||(q.entries??[]).some(ee=>ee.path===j||ee.path.startsWith(`${j}/`)))return{conflict:j}}catch(B){return{error:B?.message||"\u65E0\u6CD5\u8FDE\u63A5\u4E91\u7AEF(\u9996\u6B21\u5F00\u542F\u9700\u8981\u5728\u7EBF)"}}$={vaultRoot:_,cloudName:j,entries:[]},k.push($),(async()=>{try{let B=await E.ensureOwnVault();await E.call("PUT",`/vaults/${encodeURIComponent(B)}/file`,{path:Bn($.cloudName),content:"",baseSeq:0})}catch{}})()}return C!==r||!s?{error:"Cloud account changed; retry from the current account"}:(await rt(j=>{if(C!==r||!s)return!1;let V=j.entrySync??[],B=V.find(ne=>ne.vaultRoot===_);if(!B){let ne=Vn($.cloudName,V.map(xe=>xe.cloudName));if(ne)throw new Error(ne);B={vaultRoot:_,cloudName:$.cloudName,entries:[]},V.push(B)}let q=ne=>String(ne??"").replace(/\\/g,"/").normalize("NFC"),te=new Set;for(let ne of v.entries??[]){let xe=q(ne.path);xe&&(te.add(xe),!B.entries.some(Je=>Je.path===xe)&&B.entries.push({path:xe,kind:ne.kind==="folder"||ne.kind==="asset"?ne.kind:"page"}))}let ee=(v.exclude??[]).map(q).filter(Boolean),Z=new Set([...te,...(v.include??[]).map(q).filter(Boolean)]);B.exclude=[...new Set([...(B.exclude??[]).filter(ne=>!Z.has(ne)),...ee])];let se=new Set(ee);B.entries=B.entries.filter(ne=>!se.has(ne.path)),j.entrySync=V,$=B},N.cloudAccountId),C!==r?{error:"Cloud account changed; retry from the current account"}:(await D(),y.get(_)?.engine.syncNow(),R(),{ok:!0,cloudName:$.cloudName}))},entryDisable:async v=>{let C=n(),E=!1,_=r;return await rt(N=>{if(_!==r||!s)return!1;let k=(N.entrySync??[]).find(V=>V.vaultRoot===C);if(!C||!k)return!1;let $=String(v??"").replace(/\\/g,"/").normalize("NFC"),j=k.entries.length;if(k.entries=k.entries.filter(V=>V.path!==$),ut(k.entries,k.exclude,$))k.exclude=[...new Set([...k.exclude??[],$])];else if(k.entries.length===j)return!1;E=!0}),!E||_!==r?{ok:!1}:(await D(),R(),{ok:!0})},entryClosure:(v,C)=>t.relatedClosure(String(v??""),C==="folder"?"folder":"page"),collabCall:async(v,C)=>{let E=i,_=async()=>E.ensureOwnVault(),N=$=>String((C??[])[$]??""),k=$=>(C??[])[$]??{};switch(v){case"listVaults":return(await E.call("GET","/vaults")).vaults;case"activeVaultId":return _();case"pageShare":return E.call("GET",`/vaults/${encodeURIComponent(await _())}/page-shares?path=${encodeURIComponent(N(0))}`);case"createPageShare":return E.call("POST",`/vaults/${encodeURIComponent(await _())}/page-shares`,{path:N(0),...k(1)});case"updatePageShare":return E.call("PATCH",`/vaults/${encodeURIComponent(await _())}/page-shares/${encodeURIComponent(N(0))}`,k(1));case"revokePageShare":return E.call("DELETE",`/vaults/${encodeURIComponent(await _())}/page-shares/${encodeURIComponent(N(0))}`);case"setParticipantRole":return E.call("PATCH",`/vaults/${encodeURIComponent(await _())}/page-shares/${encodeURIComponent(N(0))}/members/${encodeURIComponent(N(1))}`,{role:N(2)});case"removeParticipant":return E.call("DELETE",`/vaults/${encodeURIComponent(await _())}/page-shares/${encodeURIComponent(N(0))}/members/${encodeURIComponent(N(1))}`);case"sharedWithMe":{let $=await E.sharedWithMe();return h(),$}case"leaveShare":{let $=E.myUserId();if(!$)throw new Error("\u672A\u767B\u5F55");return E.call("DELETE",`/vaults/${encodeURIComponent(await _())}/page-shares/${encodeURIComponent(N(0))}/members/${encodeURIComponent($)}`)}case"publishes":return E.call("GET",`/vaults/${encodeURIComponent(await _())}/shares`);case"listAllShares":{let $=(await E.call("GET","/vaults")).vaults||[],j=E.myUserId(),V=[],B=[];for(let q of $){try{let te=await E.call("GET",`/vaults/${encodeURIComponent(q.id)}/shares`);for(let ee of te.shares||[])V.push({...ee,vaultId:q.id,vaultName:q.name||""})}catch(te){t.log(`[connect] listAllShares publishes vault ${q.id} failed: ${te?.message}`)}try{let te=await E.call("GET",`/vaults/${encodeURIComponent(q.id)}/page-shares`),ee=te?.shares||te?.pageShares||(Array.isArray(te)?te:[]);for(let Z of ee){let se=Z.created_by??Z.createdBy;(!j||!se||se===j)&&B.push({...Z,vaultId:q.id,vaultName:q.name||""})}}catch(te){t.log(`[connect] listAllShares pageShares vault ${q.id} failed: ${te?.message}`)}}return{publishes:V,pageShares:B,linkBase:await E.linkBase()}}case"createPublish":{let $=await E.call("POST",`/vaults/${encodeURIComponent(await _())}/shares`,{mode:N(0),path:N(1)});return{...$,url:`${await E.linkBase()}/share/${$.token}`}}case"revokePublish":return E.call("DELETE",`/vaults/${encodeURIComponent(await _())}/shares/${encodeURIComponent(N(0))}`);case"revokePublishIn":return E.call("DELETE",`/vaults/${encodeURIComponent(N(0))}/shares/${encodeURIComponent(N(1))}`);case"revokePageShareIn":return E.call("DELETE",`/vaults/${encodeURIComponent(N(0))}/page-shares/${encodeURIComponent(N(1))}`);case"myUserId":return E.myUserId();case"linkBase":return E.linkBase();case"heartbeat":return E.heartbeat((C??[])[0]??null,c);default:throw new Error(`unknown collab fn: ${v}`)}},switchSide:async(v,C)=>{let E=await Ae();if(C==="cloud"){if(!s||!Se())throw new Error("Sign in to open cloud notes");let k=Be();await dt.mkdir(k,{recursive:!0}),E.lastVault&&!Wt(E.lastVault)&&await je({localVault:E.lastVault}),await je({lastVault:k});let $=await t.activateRoot(k,!1);return t.bindRenderer(v,k),{...$,side:"cloud"}}let _=E.localVault&&await dt.stat(E.localVault).then(k=>k.isDirectory()).catch(()=>!1)?E.localVault:null;if(!_){let k=await t.ensureDefaultVault();return t.bindRenderer(v,k.root),{...k,side:"local"}}await je({lastVault:_});let N=await t.activateRoot(_,!1);return t.bindRenderer(v,_),{...N,side:"local"}}},instance:{start:()=>{s=!0,f.start(),h(),D()},stopAllSync:me,restartAllSync:async()=>{await me(),i=Hn(),f=kt(d()),s=!0,await Promise.all([f.restart(),h(),D()]),R(),e(fe.status,Q(f.getStatus()))}}}}import{hostname as sa}from"node:os";var ia=256*1024;function Ss(t,e,n){if(n?.hasSecHeaders&&!n.gatewayStreamsSecHeaders)return!1;if(t.includes("text/event-stream"))return!0;let r=Number(e||NaN);return!Number.isFinite(r)||r>ia}var Jn=45e3,oa=3e3,aa=16*1024,la=6e4,sn=t=>`${t.replace(/\/+$/,"")}/api`,Ct=class{deps;ctrl=null;conn=null;wake=null;redialNow=!1;inflight=new Map;connected=!1;lastError=null;hubCaps=new Set;constructor(e){this.deps=e}hubFetch(e,n){return(this.deps.hubFetch??fetch)(e,n)}get requestTimeoutMs(){return this.deps.requestTimeoutMs??la}status(){return{running:!!this.ctrl,connected:this.connected,unitId:this.deps.getPairing()?.unitId??null,lastError:this.lastError}}start(){if(this.ctrl)return;let e=new AbortController;this.ctrl=e,this.loop(e)}stop(){this.ctrl?.abort(),this.ctrl=null,this.markDown(),this.abortEnvelopes(),this.wake?.()}reconnect(e){this.ctrl&&(this.deps.log(`[unit-host] \u7ACB\u5373\u91CD\u8FDE\u901A\u9053(${e})`),this.redialNow=!0,this.conn?.abort(),this.wake?.())}markDown(){this.connected=!1,this.hook(this.deps.onChannelDown)}hook(e){try{e?.()}catch(n){this.deps.log(`[unit-host] \u901A\u9053\u56DE\u8C03\u51FA\u9519(\u5DF2\u5FFD\u7565): ${n?.message||n}`)}}abortEnvelope(e){let n=this.inflight.get(e);return n?(this.inflight.delete(e),n.ctrl.abort(),!0):!1}abortEnvelopes(e){for(let[n,r]of[...this.inflight])e&&r.conn!==e||(this.inflight.delete(n),r.ctrl.abort())}sleep(e){return new Promise(n=>{let r=setTimeout(s,e);function s(){clearTimeout(r),n()}this.wake=()=>{this.wake=null,s()}})}async loop(e){let n=1e3;for(;!e.signal.aborted;){let r=new AbortController,s=()=>r.abort();e.signal.addEventListener("abort",s,{once:!0}),this.conn=r;try{let{cloudUrl:i,token:o}=this.deps.getCreds();if(!o)throw new Error("\u672A\u767B\u5F55 Forsion \u8D26\u53F7");let a=this.deps.getPairing();if(!a){if(a=await this.register(i,o,r),r.signal.aborted)throw new Error("\u5165\u518C\u671F\u95F4\u901A\u9053\u5DF2\u88AB\u505C\u7528");await this.deps.savePairing(a),this.deps.log(`[unit-host] \u5DF2\u5165\u518C\u4E3A\u8BBE\u5907 ${a.unitId}`)}let l=this.deps.getLanUrl();this.hubCaps=new Set;let d=this.deps.readIdleMs??Jn,f=d?setTimeout(()=>{this.deps.log(`[unit-host] \u901A\u9053 ${Math.round(d/1e3)}s \u672A\u6536\u5230\u54CD\u5E94\u5934,\u5224\u5B9A\u5DF2\u65AD,\u91CD\u8FDE`),r.abort()},d):null,m;try{m=await this.hubFetch(`${sn(i)}/units/${a.unitId}/channel`,{headers:{Authorization:`Bearer ${o}`,"X-Unit-Secret":a.secret,...l?{"X-Unit-Lan-Url":l}:{}},signal:r.signal})}finally{f&&clearTimeout(f)}if(m.status===403||m.status===404){let c=Number(m.headers.get("content-length"))>aa,h=setTimeout(()=>r.abort(),c?0:oa),g=await m.json().then(S=>S?.code,()=>null);throw clearTimeout(h),g==="UNIT_NOT_FOUND"||g==="UNIT_SECRET_MISMATCH"?(await this.deps.clearPairing(),new Error(`\u901A\u9053\u88AB\u62D2(${m.status} ${g}),\u5DF2\u6E05\u9664\u914D\u5BF9\u5F85\u91CD\u65B0\u5165\u518C`)):new Error(`channel HTTP ${m.status} (not a hub verdict; keeping pairing and retrying)`)}if(!m.ok||!m.body)throw new Error(`channel HTTP ${m.status}`);this.connected=!0,this.lastError=null,n=1e3,this.deps.log("[unit-host] \u901A\u9053\u5DF2\u8FDE\u63A5"),await this.consume(m.body,r),this.markDown(),this.deps.log("[unit-host] \u901A\u9053\u65AD\u5F00,\u51C6\u5907\u91CD\u8FDE")}catch(i){if(this.markDown(),e.signal.aborted)return;this.lastError=r.signal.aborted?"\u901A\u9053\u88AB\u672C\u673A\u65AD\u5F00(\u770B\u95E8\u72D7 / \u91CD\u8FDE)":String(i?.message||i),this.deps.log(`[unit-host] ${this.lastError};${this.redialNow?"\u7ACB\u5373":`${Math.round(n/1e3)}s \u540E`}\u91CD\u8BD5`)}finally{e.signal.removeEventListener("abort",s),this.conn===r&&(this.conn=null),r.abort(),this.abortEnvelopes(r)}if(e.signal.aborted)return;if(this.redialNow){this.redialNow=!1,n=1e3;continue}if(await this.sleep(n),this.redialNow){this.redialNow=!1,n=1e3;continue}n=Math.min(n*2,3e4)}}async register(e,n,r){let s=this.deps.readIdleMs??Jn,i=s?setTimeout(()=>{this.deps.log(`[unit-host] \u8BBE\u5907\u5165\u518C ${Math.round(s/1e3)}s \u672A\u8FD4\u56DE,\u4E2D\u6B62\u91CD\u8BD5`),r.abort()},s):null;try{let o=await this.hubFetch(`${sn(e)}/units/register`,{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify({name:sa(),platform:process.platform}),signal:r.signal});if(!o.ok)throw new Error(`\u8BBE\u5907\u5165\u518C\u5931\u8D25 HTTP ${o.status}`);let a=await o.json();if(!a.unitId||!a.secret)throw new Error("\u8BBE\u5907\u5165\u518C\u54CD\u5E94\u7F3A\u5B57\u6BB5");return{unitId:a.unitId,secret:a.secret}}finally{i&&clearTimeout(i)}}async consume(e,n){let r=e.getReader(),s=new TextDecoder,i="",o=this.deps.readIdleMs??Jn,a=null,l=()=>{o&&(a&&clearTimeout(a),a=setTimeout(()=>{this.deps.log(`[unit-host] \u901A\u9053 ${Math.round(o/1e3)}s \u65E0\u4EFB\u4F55\u5B57\u8282(\u7F51\u5173 15s \u4E00\u6B21\u5FC3\u8DF3),\u5224\u5B9A\u5DF2\u65AD,\u91CD\u8FDE`),n.abort(),r.cancel().catch(()=>{})},o))};l();try{for(;;){let{done:d,value:f}=await r.read();if(d||n.signal.aborted)return;l(),i=this.parseFrames(i+s.decode(f,{stream:!0}),n)}}finally{a&&clearTimeout(a)}}parseFrames(e,n){let r=e,s;for(;(s=r.indexOf(`
200
200
 
201
- `))>=0;){let o=r.slice(0,s);if(r=r.slice(s+2),o.includes("event: ready")){let i=o.split(`
202
- `).find(l=>l.startsWith("data: "))?.slice(6);try{let l=JSON.parse(i||"{}").caps;this.hubCaps=new Set(Array.isArray(l)?l.map(String):[])}catch{this.hubCaps=new Set}n.signal.aborted||this.hook(this.deps.onChannelReady);continue}if(!o.includes("event: dispatch"))continue;let a=o.split(`
203
- `).find(i=>i.startsWith("data: "))?.slice(6);if(a)try{let i=JSON.parse(a);this.dispatch(i,n).catch(l=>this.deps.log(`[unit-host] \u6D3E\u53D1\u5904\u7406\u5931\u8D25: ${l?.message||l}`))}catch{}}return r}async dispatch(e,n){let r=new AbortController;if(n.signal.aborted)return;this.inflight.get(e.id)?.ctrl.abort();let s={ctrl:r,conn:n};this.inflight.set(e.id,s);try{await this.handle(e,r)}finally{this.inflight.get(e.id)===s&&this.inflight.delete(e.id)}}async handle(e,n){let r=this.deps.getUnitWeb();if(!r.url){await this.respond(e.id,503,"application/json",Buffer.from(JSON.stringify({detail:"\u672C\u673A\u4E92\u8054\u670D\u52A1\u672A\u5C31\u7EEA",code:"UNIT_WEB_NOT_READY"})),void 0,n.signal);return}let s={"x-unit-internal":r.internalSecret};e.ct&&(s["Content-Type"]=e.ct),e.accept&&(s.Accept=e.accept);let o;try{let d=new URL(`${r.url}${e.path}`);Object.assign(s,this.deps.callerHeaders({dispatchId:e.id,method:e.method,target:d,proxyCaller:e.proxyCaller})),o=await fetch(d,{method:e.method,headers:s,body:e.body??void 0,signal:n.signal})}catch(d){if(n.signal.aborted)return;await this.respond(e.id,502,"application/json",Buffer.from(JSON.stringify({detail:`\u672C\u673A\u4E92\u8054\u670D\u52A1\u4E0D\u53EF\u8FBE: ${d?.message||d}`})),void 0,n.signal);return}let a=o.headers.get("content-type")||"",i={};for(let d of["content-security-policy","x-content-type-options"]){let f=o.headers.get(d);f&&(i[d]=f)}let l=a||"application/octet-stream";o.body&&ss(a,o.headers.get("content-length"),{hasSecHeaders:Object.keys(i).length>0,gatewayStreamsSecHeaders:this.hubCaps.has("stream-sec-headers")})?await this.streamBack(e.id,o,n,l,i):await this.respond(e.id,o.status,l,Buffer.from(await o.arrayBuffer()),i,n.signal)}async respond(e,n,r,s,o,a){if(a?.aborted)return;let{cloudUrl:i,token:l}=this.deps.getCreds(),h=this.deps.getPairing();if(!h)return;let d=this.requestTimeoutMs*2,f=[...d?[AbortSignal.timeout(d)]:[],...a?[a]:[]],u=f.length>1?AbortSignal.any(f):f[0];await this.hubFetch(`${zt(i)}/units/${h.unitId}/resp/${e}`,{method:"POST",headers:{Authorization:`Bearer ${l}`,"X-Unit-Secret":h.secret,"Content-Type":"application/json"},body:JSON.stringify({status:n,headers:{"content-type":r,...o},bodyB64:s.toString("base64")}),...u?{signal:u}:{}}).then(g=>{g.body?.cancel().catch(()=>{})}).catch(g=>{a?.aborted||this.deps.log(`[unit-host] \u56DE\u5305\u5931\u8D25: ${g?.name==="TimeoutError"?`${Math.round(d/1e3)}s \u672A\u5B8C\u6210`:g?.message||g}`)})}async streamBack(e,n,r,s,o){let{cloudUrl:a,token:i}=this.deps.getCreds(),l=this.deps.getPairing();if(!l)return;let h=o?.["content-security-policy"],d=o?.["x-content-type-options"],f=`${zt(a)}/units/${l.unitId}/stream/${e}?status=${n.status}&ct=${encodeURIComponent(s)}`+(h?`&csp=${encodeURIComponent(h)}`:"")+(d?`&xcto=${encodeURIComponent(d)}`:""),u=n.body;if(!u)return;let g=u.getReader(),S=0,x=this.requestTimeoutMs,w=x?setTimeout(()=>{S>=2||(this.deps.log(`[unit-host] \u6D41\u5F0F\u56DE\u4F20 ${Math.round(x/1e3)}s \u672A\u628A\u9996\u5757\u5199\u7ED9\u7F51\u5173,\u4E2D\u6B62\u672C\u6B21\u6D3E\u53D1`),r.abort())},x):null,F=new ReadableStream({async pull(_){++S===2&&w&&clearTimeout(w);let{done:A,value:U}=await g.read();A?_.close():_.enqueue(U)},cancel(_){return g.cancel(_)}},{highWaterMark:0});try{await this.hubFetch(f,{method:"POST",headers:{Authorization:`Bearer ${i}`,"X-Unit-Secret":l.secret,"Content-Type":"application/octet-stream"},body:F,signal:r.signal,duplex:"half"})}catch(_){this.deps.log(`[unit-host] \u6D41\u5F0F\u56DE\u4F20\u4E2D\u65AD: ${_?.message||_}`);try{await g.cancel()}catch{}}finally{w&&clearTimeout(w)}}};var yt=class{d;up=!1;gen=0;lastSent=null;disabled=!1;inflight=!1;again=!1;timer=null;warned=new Set;constructor(e){this.d=e}channelReady(){this.gen++,this.up=!0,this.lastSent=null,this.disabled=!1,this.clearTimer(),this.again=!1,this.flush()}channelDown(){this.gen++,this.up=!1,this.lastSent=null,this.again=!1,this.clearTimer()}engineChanged(){!this.up||this.disabled||(this.clearTimer(),this.timer=setTimeout(()=>{this.timer=null,this.flush()},this.d.debounceMs??500))}clearTimer(){this.timer&&(clearTimeout(this.timer),this.timer=null)}async flush(){if(!this.up||this.disabled)return;if(this.inflight){this.again=!0;return}let e;try{e=this.d.current()}catch(i){this.d.log(`[unit-caps] \u8BFB\u5F15\u64CE\u6001\u5931\u8D25:${i?.message||i}`);return}if(e===this.lastSent)return;let n=this.d.getPairing(),r;try{r=this.d.getCreds()}catch{return}if(!n||!r.token||!r.cloudUrl)return;let s=this.gen;this.inflight=!0;let o=new AbortController,a=setTimeout(()=>o.abort(),this.d.timeoutMs??1e4);try{let i=`${r.cloudUrl.replace(/\/+$/,"")}/api/units/${encodeURIComponent(n.unitId)}/caps`,l=await(this.d.hubFetch??fetch)(i,{method:"POST",headers:{Authorization:`Bearer ${r.token}`,"X-Unit-Secret":n.secret,"Content-Type":"application/json"},body:JSON.stringify({engine:e,tools:[]}),signal:o.signal});try{await l.text()}catch{}if(s!==this.gen)return;l.ok?(this.lastSent=e,this.d.log(`[unit-caps] \u5DF2\u4E0A\u62A5\u5F15\u64CE\u6001 ${e}`)):l.status===404||l.status===405?(this.disabled=!0,this.d.log(`[unit-caps] \u7F51\u5173\u4E0D\u6536 caps(HTTP ${l.status},\u8001\u7248\u672C),\u672C\u8FDE\u63A5\u5185\u4E0D\u518D\u4E0A\u62A5`)):l.status===400||l.status===401||l.status===403?this.warned.has(l.status)||(this.warned.add(l.status),this.d.log(`[unit-caps] \u4E0A\u62A5\u88AB\u62D2 HTTP ${l.status}`)):this.d.log(`[unit-caps] \u4E0A\u62A5\u5931\u8D25 HTTP ${l.status},\u7B49\u4E0B\u6B21\u53D8\u5316 / \u91CD\u8FDE\u518D\u62A5`)}catch(i){s===this.gen&&this.d.log(`[unit-caps] \u4E0A\u62A5\u5931\u8D25:${o.signal.aborted?"\u8D85\u65F6":i?.message||i}`)}finally{clearTimeout(a),this.inflight=!1,this.again&&this.up&&!this.disabled&&(this.again=!1,this.flush())}}};var os=["setUnitHubFactory"],$n=t=>os.every(e=>typeof t[e]=="function");function is(t){let e=new yt({getCreds:()=>t.getCreds(),getPairing:()=>t.getPairing(),current:()=>t.engineCaps(),log:r=>t.log(r)}),n=new pt({onChannelReady:()=>e.channelReady(),onChannelDown:()=>e.channelDown(),getCreds:()=>t.getCreds(),getUnitWeb:()=>t.getUnitWeb(),callerHeaders:r=>t.callerHeaders(r),getLanUrl:()=>t.getLanUrl(),getPairing:()=>t.getPairing(),savePairing:r=>t.savePairing(r),clearPairing:()=>t.clearPairing(),log:r=>t.log(r)});return{start:()=>n.start(),stop:()=>n.stop(),reconnect:r=>n.reconnect(r),status:()=>n.status(),engineChanged:()=>e.engineChanged()}}function Dn(t){let e=async(n,r,s)=>{let{base:o,token:a}=await t.getCloud();if(!a)return{status:401,json:{detail:"\u672A\u767B\u5F55 Forsion \u8D26\u53F7"}};try{let i=await fetch(`${o}/api${r}`,{method:n,headers:{Authorization:`Bearer ${a}`,...s!==void 0?{"Content-Type":"application/json"}:{}},body:s!==void 0?JSON.stringify(s):void 0});return{status:i.status,json:await i.json().catch(()=>null)}}catch(i){return{status:0,json:{detail:String(i?.message||i)}}}};t.handle("units:list",()=>e("GET","/units")),t.handle("units:update",(n,r,s)=>e("PATCH",`/units/${encodeURIComponent(String(r))}`,{name:s?.name,icon:s?.icon})),t.handle("units:remove",(n,r)=>e("DELETE",`/units/${encodeURIComponent(String(r))}`)),t.handle("units:openInBrowser",async(n,r)=>{if(typeof r!="string"||!/^[0-9a-zA-Z-]{8,64}$/.test(r))throw new Error("\u53C2\u6570\u4E0D\u5B8C\u6574");let{base:s,token:o}=await t.getCloud();await t.openExternal(`${s}/api/units/${r}/open${o?`#token=${encodeURIComponent(o)}`:""}`)}),t.setUnitHubFactory(is),t.log("[forsion-extend] unit hub registered")}import{createHash as Pi}from"node:crypto";import{mkdirSync as $i,readFileSync as Di,renameSync as Mi,writeFileSync as Ni}from"node:fs";import{lstat as Vt,open as Oi,readFile as Ui,readdir as ps}from"node:fs/promises";import{homedir as as,hostname as ys,release as Fi}from"node:os";import{basename as ji,join as ue}from"node:path";var ws=14,Un=60*6e4,Li=24*Un,Hi=2*6e4,zi=12e4,qi=10*6e4,ls=Un,Bi=15e3,cs=1792*1024,Wi=7,Vi=4*1024*1024,Yi=256*1024,ot=t=>t.toISOString().slice(0,10),Bt=t=>Date.parse(ot(t))-(Wi-1)*Li,us=["user","teamwork","discussion","delegate"],Gi=/^(?:New remarks in the team chat:|You are activated now \()/,bs={totalBytes:1024*1024,sessionBytes:256*1024,textChars:8e3,sessions:300,messages:400},Ji=["homeDir","readCreds","accountId","appVersion"],Ss=t=>Ji.every(e=>typeof t[e]=="function"),ds=as().length>3?as():null;function Mn(t){return typeof t=="string"?(ds?t.split(ds).join("~"):t).replace(/\bBearer\s+[A-Za-z0-9._~+\/-]+=*/gi,"Bearer [redacted]").replace(/\b(sk-[a-zA-Z0-9_-]{12,})\b/g,"[redacted]").replace(/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}/g,"[redacted]").replace(/\b(?:gh[pousr]_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,}|AKIA[0-9A-Z]{16}|LTAI[0-9A-Za-z]{12,}|xox[abeprs]-[A-Za-z0-9-]{10,}|AIza[0-9A-Za-z_-]{30,})/g,"[redacted]").replace(/-{5}BEGIN [A-Z ]*PRIVATE KEY-{5}[\s\S]*?(?:-{5}END [A-Z ]*PRIVATE KEY-{5}|$)/g,"[redacted]").replace(/\b[a-fA-F0-9]{32,}\b/g,e=>`[hex:${e.length}]`).replace(/((?:["']?)(?:api[_-]?key|access[_-]?token|refresh[_-]?token|token|password|secret|authorization|cookie)(?:["']?)\s*[:=]\s*)("[^"\n]*"|'[^'\n]*'|\[[^\]\n]*\]|[^\s,"';&}]+)/gi,"$1[redacted]"):Array.isArray(t)?t.map(Mn):t&&typeof t=="object"?Object.fromEntries(Object.entries(t).map(([e,n])=>[e,/^(?:token|.*api[_-]?key|access[_-]?token|refresh[_-]?token|password|secret|authorization|cookie|set-cookie)$/i.test(e)?"[redacted]":Mn(n)])):t}var Ki=/^(?:model|modelId|voice|mode|backend|notify|escalateTo|realtimeModel|realtimeVoice|vision|background)$/,re=(t,e=120)=>typeof t=="string"&&t.length<=e?t:void 0,Xi=(t,e)=>/^[A-Za-z_][\w.-]{0,63}$/.test(t)?t:`[key:${e}]`;function rt(t,e=0){if(typeof t=="boolean"||typeof t=="number"||t===null||t===void 0)return t??null;if(typeof t=="string")return`[string:${t.length}]`;if(Array.isArray(t))return`[array:${t.length}]`;if(typeof t!="object"||e>=4)return"[object]";let n={};for(let[r,[s,o]]of Object.entries(t).slice(0,100).entries())n[Xi(s,r)]=Ki.test(s)&&re(o,80)!==void 0?o:rt(o,e+1);return n}var Zi=/^(?:name|version|model|model_reasoning_effort|approval_mode|created_by|created_at|avatar|lead|slug)$/,Qi=/^(?:apps|enabled_skill_ids)$/;function ea(t){let e=[],n=t.split(/\r?\n/);for(let r=0;r<n.length;r++){let s=n[r].trim();if(/^\[\[?[\w.-]{1,80}\]\]?$/.test(s)){e.push(s);continue}let o=/^([\w.-]+)\s*=\s*(.*)$/.exec(s);if(!o)continue;let[,a,i]=o,l=/^('''|""")/.exec(i)?.[1],h=i.length;if(l&&!i.slice(3).includes(l))for(;++r<n.length&&!n[r].includes(l);)h+=n[r].length+1;let d=/^(?:true|false|[+-]?\d[\d._]*)$/.test(i)||Zi.test(a)&&h<=120&&/^(?:"[^"]*"|'[^']*'|\d{4}-\d{2}-\d{2}[\dT:.+Z -]*)$/.test(i)||Qi.test(a)&&h<=2e3&&/^\[[^\[\]{}]*\]$/.test(i);e.push(d?`${a} = ${i}`:`${a} = "[text:${h}]"`)}return e.join(`
204
- `)}var vs=async t=>{try{return(await Vt(t)).isFile()?await Ui(t,"utf8"):null}catch{return null}},ta=t=>Vt(t).then(e=>e.isDirectory(),()=>!1),Fn=async t=>{try{return JSON.parse(await vs(t)??"null")}catch{return null}},st=async(t,e=200)=>{try{return(await ps(t)).filter(n=>!n.startsWith(".")&&n.length<=120).sort().slice(0,e)}catch{return[]}};async function na(t,e){if(!(await Vt(t)).isFile())return"";let n=await Oi(t,"r");try{let{size:r}=await n.stat(),s=Math.max(0,r-e),o=Buffer.alloc(r-s);await n.read(o,0,o.length,s);let a=o.toString("utf8");return s>0?a.slice(a.indexOf(`
205
- `)+1):a}finally{await n.close()}}function ra(t){if(!t||typeof t!="object")return{};let e=n=>n&&typeof n=="object"?Object.entries(n).slice(0,100):[];return{defaultModel:re(t.cloud?.defaultModel)??null,models:rt(t.models),tts:rt(t.tts),asr:rt(t.asr),specialAgents:rt(t.specialAgents),pluginSettings:rt(t.plugins?.global),providers:(Array.isArray(t.providers)?t.providers:[]).slice(0,50).map(n=>({providerId:re(n?.providerId)??null,models:(Array.isArray(n?.modelIds)?n.modelIds:[]).filter(r=>re(r)!==void 0).slice(0,100)})),mcpServers:e(t.mcp?.mcpServers).map(([n,r])=>({name:re(n,64)??"[name]",enabled:r?.enabled!==!1})),channels:e(t.channels).map(([n,r])=>({name:re(n,64)??"[name]",enabled:r?.enabled===!0}))}}var sa=new Set(["config.toml","SOUL.md","MEMORY.md","HARNESS.md","HUMAN.md","Library","LOG","skills","plugins","Space","SCHEDULE.db","triggers.json"]);async function fs(t){let e=[];for(let n of await st(t,100)){let r=ue(t,n);if(!await ta(r))continue;let s=await vs(ue(r,"config.toml"));e.push({id:n,config:s===null?null:ea(s).slice(0,4096),files:(await st(r,400)).filter(o=>sa.has(o))})}return e}async function hs(t){let e=[];for(let n of await st(t,300)){let r=await Fn(ue(t,n,"manifest.json"));r&&e.push({id:re(r.id)??n,version:re(r.version,40)??null,name:re(r.nameEn)??re(r.name)??null})}return e}var Nn=t=>String(t?.code||t?.message||t).slice(0,120);async function oa(t,e,n,r=Yi){let s=u=>String(u).padStart(2,"0"),o=u=>{let g=new Date(u);return`${g.getFullYear()}${s(g.getMonth()+1)}${s(g.getDate())}${s(g.getHours())}${s(g.getMinutes())}`},a=u=>`${u.slice(0,4)}-${u.slice(4,6)}-${u.slice(6,8)}.log`,i=o(n),l=o(e.getTime()),h=[],d=r,f=!1;try{let u=(await ps(t)).filter(g=>/^\d{4}-\d{2}-\d{2}\.log$/.test(g)&&g>=a(i)&&g<=a(l)).sort().reverse();for(let g of u){if(f)break;let x=(await na(ue(t,g),Vi).catch(F=>{if(F?.code==="ENOENT")return"";throw F})).split(`
206
- `).filter(F=>/^\d{12} /.test(F)&&F.slice(0,12)>=i&&F.slice(0,12)<l),w=x.length;for(;w>0&&Buffer.byteLength(x[w-1])+1<=d;)d-=Buffer.byteLength(x[--w])+1;w>0&&(f=!0),w<x.length&&h.push({date:g.slice(0,10),log:x.slice(w).join(`
207
- `)})}}catch(u){return u?.code==="ENOENT"?{activity:[]}:{activity:[],activityError:Nn(u)}}return{activity:h.reverse(),...f?{activityTruncated:!0}:{}}}var qt=(t,e)=>{if(!(typeof t!="string"||!t))return t.length>e?`${t.slice(0,e)}\u2026[+${t.length-e}]`:t},ms=t=>{try{let e=typeof t=="string"?JSON.parse(t):t;return Array.isArray(e)?e:[]}catch{return[]}},gs=t=>new Date(t).toISOString().slice(0,19).replace("T"," ");async function ia(t,e,n=bs,r=Bt(e)){let s=ue(t,"tangu","state.db"),o=await Vt(s).then(i=>i.isFile(),i=>i?.code==="ENOENT"?!1:Nn(i));if(o!==!0)return o===!1?{sessions:[]}:{sessions:[],sessionsError:o};let a;try{let{DatabaseSync:i}=await import("node:sqlite");a=new i(s,{readOnly:!0}),a.exec("PRAGMA busy_timeout = 1500");let h="m.updated_at >= ? AND m.updated_at < ? AND m.timestamp >= ?",d=[gs(r),gs(e.getTime()),Bt(e)],f=a.prepare(`SELECT s.id, s.kind, s.parent_session_id, s.app_id, s.title, s.model_id, s.project_name, s.archived, s.created_at, s.updated_at, MAX(m.updated_at) AS changed_at
201
+ `))>=0;){let i=r.slice(0,s);if(r=r.slice(s+2),i.includes("event: ready")){let a=i.split(`
202
+ `).find(l=>l.startsWith("data: "))?.slice(6);try{let l=JSON.parse(a||"{}").caps;this.hubCaps=new Set(Array.isArray(l)?l.map(String):[])}catch{this.hubCaps=new Set}n.signal.aborted||this.hook(this.deps.onChannelReady);continue}if(!i.includes("event: dispatch"))continue;let o=i.split(`
203
+ `).find(a=>a.startsWith("data: "))?.slice(6);if(o)try{let a=JSON.parse(o);this.dispatch(a,n).catch(l=>this.deps.log(`[unit-host] \u6D3E\u53D1\u5904\u7406\u5931\u8D25: ${l?.message||l}`))}catch{}}return r}async dispatch(e,n){let r=new AbortController;if(n.signal.aborted)return;this.inflight.get(e.id)?.ctrl.abort();let s={ctrl:r,conn:n};this.inflight.set(e.id,s);try{await this.handle(e,r)}finally{this.inflight.get(e.id)===s&&this.inflight.delete(e.id)}}async handle(e,n){let r=this.deps.getUnitWeb();if(!r.url){await this.respond(e.id,503,"application/json",Buffer.from(JSON.stringify({detail:"\u672C\u673A\u4E92\u8054\u670D\u52A1\u672A\u5C31\u7EEA",code:"UNIT_WEB_NOT_READY"})),void 0,n.signal);return}let s={"x-unit-internal":r.internalSecret};e.ct&&(s["Content-Type"]=e.ct),e.accept&&(s.Accept=e.accept);let i;try{let f=new URL(`${r.url}${e.path}`);Object.assign(s,this.deps.callerHeaders({dispatchId:e.id,method:e.method,target:f,proxyCaller:e.proxyCaller})),i=await fetch(f,{method:e.method,headers:s,body:e.body??void 0,signal:n.signal})}catch(f){if(n.signal.aborted)return;await this.respond(e.id,502,"application/json",Buffer.from(JSON.stringify({detail:`\u672C\u673A\u4E92\u8054\u670D\u52A1\u4E0D\u53EF\u8FBE: ${f?.message||f}`})),void 0,n.signal);return}let o=i.headers.get("content-type")||"",a={};for(let f of["content-security-policy","x-content-type-options"]){let m=i.headers.get(f);m&&(a[f]=m)}let l=o||"application/octet-stream";i.body&&Ss(o,i.headers.get("content-length"),{hasSecHeaders:Object.keys(a).length>0,gatewayStreamsSecHeaders:this.hubCaps.has("stream-sec-headers")})?await this.streamBack(e.id,i,n,l,a):await this.respond(e.id,i.status,l,Buffer.from(await i.arrayBuffer()),a,n.signal)}async respond(e,n,r,s,i,o){if(o?.aborted)return;let{cloudUrl:a,token:l}=this.deps.getCreds(),d=this.deps.getPairing();if(!d)return;let f=this.requestTimeoutMs*2,m=[...f?[AbortSignal.timeout(f)]:[],...o?[o]:[]],c=m.length>1?AbortSignal.any(m):m[0];await this.hubFetch(`${sn(a)}/units/${d.unitId}/resp/${e}`,{method:"POST",headers:{Authorization:`Bearer ${l}`,"X-Unit-Secret":d.secret,"Content-Type":"application/json"},body:JSON.stringify({status:n,headers:{"content-type":r,...i},bodyB64:s.toString("base64")}),...c?{signal:c}:{}}).then(h=>{h.body?.cancel().catch(()=>{})}).catch(h=>{o?.aborted||this.deps.log(`[unit-host] \u56DE\u5305\u5931\u8D25: ${h?.name==="TimeoutError"?`${Math.round(f/1e3)}s \u672A\u5B8C\u6210`:h?.message||h}`)})}async streamBack(e,n,r,s,i){let{cloudUrl:o,token:a}=this.deps.getCreds(),l=this.deps.getPairing();if(!l)return;let d=i?.["content-security-policy"],f=i?.["x-content-type-options"],m=`${sn(o)}/units/${l.unitId}/stream/${e}?status=${n.status}&ct=${encodeURIComponent(s)}`+(d?`&csp=${encodeURIComponent(d)}`:"")+(f?`&xcto=${encodeURIComponent(f)}`:""),c=n.body;if(!c)return;let h=c.getReader(),g=0,S=this.requestTimeoutMs,y=S?setTimeout(()=>{g>=2||(this.deps.log(`[unit-host] \u6D41\u5F0F\u56DE\u4F20 ${Math.round(S/1e3)}s \u672A\u628A\u9996\u5757\u5199\u7ED9\u7F51\u5173,\u4E2D\u6B62\u672C\u6B21\u6D3E\u53D1`),r.abort())},S):null,A=new ReadableStream({async pull(R){++g===2&&y&&clearTimeout(y);let{done:T,value:I}=await h.read();T?R.close():R.enqueue(I)},cancel(R){return h.cancel(R)}},{highWaterMark:0});try{await this.hubFetch(m,{method:"POST",headers:{Authorization:`Bearer ${a}`,"X-Unit-Secret":l.secret,"Content-Type":"application/octet-stream"},body:A,signal:r.signal,duplex:"half"})}catch(R){this.deps.log(`[unit-host] \u6D41\u5F0F\u56DE\u4F20\u4E2D\u65AD: ${R?.message||R}`);try{await h.cancel()}catch{}}finally{y&&clearTimeout(y)}}};var Tt=class{d;up=!1;gen=0;lastSent=null;disabled=!1;inflight=!1;again=!1;timer=null;warned=new Set;constructor(e){this.d=e}channelReady(){this.gen++,this.up=!0,this.lastSent=null,this.disabled=!1,this.clearTimer(),this.again=!1,this.flush()}channelDown(){this.gen++,this.up=!1,this.lastSent=null,this.again=!1,this.clearTimer()}engineChanged(){!this.up||this.disabled||(this.clearTimer(),this.timer=setTimeout(()=>{this.timer=null,this.flush()},this.d.debounceMs??500))}clearTimer(){this.timer&&(clearTimeout(this.timer),this.timer=null)}async flush(){if(!this.up||this.disabled)return;if(this.inflight){this.again=!0;return}let e;try{e=this.d.current()}catch(a){this.d.log(`[unit-caps] \u8BFB\u5F15\u64CE\u6001\u5931\u8D25:${a?.message||a}`);return}if(e===this.lastSent)return;let n=this.d.getPairing(),r;try{r=this.d.getCreds()}catch{return}if(!n||!r.token||!r.cloudUrl)return;let s=this.gen;this.inflight=!0;let i=new AbortController,o=setTimeout(()=>i.abort(),this.d.timeoutMs??1e4);try{let a=`${r.cloudUrl.replace(/\/+$/,"")}/api/units/${encodeURIComponent(n.unitId)}/caps`,l=await(this.d.hubFetch??fetch)(a,{method:"POST",headers:{Authorization:`Bearer ${r.token}`,"X-Unit-Secret":n.secret,"Content-Type":"application/json"},body:JSON.stringify({engine:e,tools:[]}),signal:i.signal});try{await l.text()}catch{}if(s!==this.gen)return;l.ok?(this.lastSent=e,this.d.log(`[unit-caps] \u5DF2\u4E0A\u62A5\u5F15\u64CE\u6001 ${e}`)):l.status===404||l.status===405?(this.disabled=!0,this.d.log(`[unit-caps] \u7F51\u5173\u4E0D\u6536 caps(HTTP ${l.status},\u8001\u7248\u672C),\u672C\u8FDE\u63A5\u5185\u4E0D\u518D\u4E0A\u62A5`)):l.status===400||l.status===401||l.status===403?this.warned.has(l.status)||(this.warned.add(l.status),this.d.log(`[unit-caps] \u4E0A\u62A5\u88AB\u62D2 HTTP ${l.status}`)):this.d.log(`[unit-caps] \u4E0A\u62A5\u5931\u8D25 HTTP ${l.status},\u7B49\u4E0B\u6B21\u53D8\u5316 / \u91CD\u8FDE\u518D\u62A5`)}catch(a){s===this.gen&&this.d.log(`[unit-caps] \u4E0A\u62A5\u5931\u8D25:${i.signal.aborted?"\u8D85\u65F6":a?.message||a}`)}finally{clearTimeout(o),this.inflight=!1,this.again&&this.up&&!this.disabled&&(this.again=!1,this.flush())}}};var Es=["setUnitHubFactory"],Kn=t=>Es.every(e=>typeof t[e]=="function");function _s(t){let e=new Tt({getCreds:()=>t.getCreds(),getPairing:()=>t.getPairing(),current:()=>t.engineCaps(),log:r=>t.log(r)}),n=new Ct({onChannelReady:()=>e.channelReady(),onChannelDown:()=>e.channelDown(),getCreds:()=>t.getCreds(),getUnitWeb:()=>t.getUnitWeb(),callerHeaders:r=>t.callerHeaders(r),getLanUrl:()=>t.getLanUrl(),getPairing:()=>t.getPairing(),savePairing:r=>t.savePairing(r),clearPairing:()=>t.clearPairing(),log:r=>t.log(r)});return{start:()=>n.start(),stop:()=>n.stop(),reconnect:r=>n.reconnect(r),status:()=>n.status(),engineChanged:()=>e.engineChanged()}}function Xn(t){let e=async(n,r,s)=>{let{base:i,token:o}=await t.getCloud();if(!o)return{status:401,json:{detail:"\u672A\u767B\u5F55 Forsion \u8D26\u53F7"}};try{let a=await fetch(`${i}/api${r}`,{method:n,headers:{Authorization:`Bearer ${o}`,...s!==void 0?{"Content-Type":"application/json"}:{}},body:s!==void 0?JSON.stringify(s):void 0});return{status:a.status,json:await a.json().catch(()=>null)}}catch(a){return{status:0,json:{detail:String(a?.message||a)}}}};t.handle("units:list",()=>e("GET","/units")),t.handle("units:update",(n,r,s)=>e("PATCH",`/units/${encodeURIComponent(String(r))}`,{name:s?.name,icon:s?.icon})),t.handle("units:remove",(n,r)=>e("DELETE",`/units/${encodeURIComponent(String(r))}`)),t.handle("units:openInBrowser",async(n,r)=>{if(typeof r!="string"||!/^[0-9a-zA-Z-]{8,64}$/.test(r))throw new Error("\u53C2\u6570\u4E0D\u5B8C\u6574");let{base:s,token:i}=await t.getCloud();await t.openExternal(`${s}/api/units/${r}/open${i?`#token=${encodeURIComponent(i)}`:""}`)}),t.setUnitHubFactory(_s),t.log("[forsion-extend] unit hub registered")}import{createHash as ya}from"node:crypto";import{constants as As,mkdirSync as wa,readFileSync as ba,renameSync as Sa,writeFileSync as Ea}from"node:fs";import{lstat as Le,open as zs,readFile as _a,readdir as Bs,statfs as ka}from"node:fs/promises";import{cpus as va,freemem as xa,homedir as Is,hostname as qs,release as Ca,totalmem as Ta}from"node:os";import{basename as Ws,join as K}from"node:path";var ca=/^(\d{4}-\d{2}-\d{2})?[T ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|[-+]\d{2}:\d{2})?$/i,At=class t extends Date{#t=!1;#n=!1;#e=null;constructor(e){let n=!0,r=!0,s="Z";if(typeof e=="string"){let i=e.match(ca);i?(i[1]||(n=!1,e=`0000-01-01T${e}`),r=!!i[2],r&&e[10]===" "&&(e=e.replace(" ","T")),i[2]&&+i[2]>23?e="":(s=i[3]||null,e=e.toUpperCase(),!s&&r&&(e+="Z"))):e=""}super(e),isNaN(this.getTime())||(this.#t=n,this.#n=r,this.#e=s)}isDateTime(){return this.#t&&this.#n}isLocal(){return!this.#t||!this.#n||!this.#e}isDate(){return this.#t&&!this.#n}isTime(){return this.#n&&!this.#t}isValid(){return this.#t||this.#n}toISOString(){let e=super.toISOString();if(this.isDate())return e.slice(0,10);if(this.isTime())return e.slice(11,23);if(this.#e===null)return e.slice(0,-1);if(this.#e==="Z")return e;let n=+this.#e.slice(1,3)*60+ +this.#e.slice(4,6);return n=this.#e[0]==="-"?n:-n,new Date(this.getTime()-n*6e4).toISOString().slice(0,-1)+this.#e}static wrapAsOffsetDateTime(e,n="Z"){let r=new t(e);return r.#e=n,r}static wrapAsLocalDateTime(e){let n=new t(e);return n.#e=null,n}static wrapAsLocalDate(e){let n=new t(e);return n.#n=!1,n.#e=null,n}static wrapAsLocalTime(e){let n=new t(e);return n.#t=!1,n.#e=null,n}};function ua(t,e){let n=t.slice(0,e).split(/\r\n|\n|\r/g);return[n.length,n.pop().length+1]}function da(t,e,n){let r=t.split(/\r\n|\n|\r/g),s="",i=(Math.log10(e+1)|0)+1;for(let o=e-1;o<=e+1;o++){let a=r[o-1];a&&(s+=o.toString().padEnd(i," "),s+=": ",s+=a,s+=`
204
+ `,o===e&&(s+=" ".repeat(i+n+2),s+=`^
205
+ `))}return s}var Y=class extends Error{line;column;codeblock;constructor(e,n){let[r,s]=ua(n.toml,n.ptr),i=da(n.toml,r,s);super(`Invalid TOML document: ${e}
206
+
207
+ ${i}`,n),this.line=r,this.column=s,this.codeblock=i}};var fa=/^((0x[0-9a-fA-F](_?[0-9a-fA-F])*)|(([+-]|0[ob])?\d(_?\d)*))$/,ma=/^[+-]?\d(_?\d)*(\.\d(_?\d)*)?([eE][+-]?\d(_?\d)*)?$/,ha=/^[+-]?0[0-9_]/;function on(t,e){let n=t[e++],r=n,s=n==="'",i=n===t[e]&&n===t[e+1];i&&(t[e+=2]===`
208
+ `?e++:t[e]==="\r"&&t[e+1]===`
209
+ `&&(e+=2));let o="",a=e,l=0;for(let d=e;d<t.length;d++)if(n=t[d],i&&(n===`
210
+ `||n==="\r"&&t[d+1]===`
211
+ `))l=l&&3;else{if(n<" "&&n!==" "||n==="\x7F")throw new Y("control characters are not allowed in strings",{toml:t,ptr:d});if((!l||l===3)&&n===r&&(!i||t[d+1]===r&&t[d+2]===r))return i&&(t[d+3]===r&&d++,t[d+3]===r&&d++),[l?o:o+t.slice(a,d),d+(i?3:1)];if(!l)!s&&n==="\\"&&(o+=t.slice(a,a=d),l=1);else if(l===1)if(n==="x"||n==="u"||n==="U"){let f=0,m=n==="x"?2:n==="u"?4:8;for(let c=0;c<m;c++,d++){let h=t.charCodeAt(d+1),g=h>=48&&h<=57?h-48:h>=65&&h<=70?h-65+10:h>=97&&h<=102?h-97+10:-1;if(g<0)throw new Y("invalid non-hex character in unicode escape",{toml:t,ptr:d+1});f=f<<4|g}if(f<0||f>1114111||f>=55296&&f<=57343)throw new Y("invalid unicode escape",{toml:t,ptr:d});o+=String.fromCodePoint(f),a=d+1,l=0}else if(n===" "||n===" ")l=2;else{if(n==="b")o+="\b";else if(n==="t")o+=" ";else if(n==="n")o+=`
212
+ `;else if(n==="f")o+="\f";else if(n==="r")o+="\r";else if(n==="e")o+="\x1B";else if(n==='"')o+='"';else if(n==="\\")o+="\\";else throw new Y("unrecognized escape sequence",{toml:t,ptr:d});a=d+1,l=0}else if(n!==" "&&n!==" "){if(l===2)throw new Y("invalid escape: only line-ending whitespace may be escaped",{toml:t,ptr:a});l=!s&&n==="\\"?1:0,a=d}}throw new Y("unfinished string",{toml:t,ptr:e})}function ks(t,e,n,r){if(t==="true")return!0;if(t==="false")return!1;if(t==="-inf")return-1/0;if(t==="inf"||t==="+inf")return 1/0;if(t==="nan"||t==="+nan"||t==="-nan")return NaN;if(t==="-0")return r?0n:0;let s=fa.test(t);if(s||ma.test(t)){if(ha.test(t))throw new Y("leading zeroes are not allowed",{toml:e,ptr:n});t=t.replace(/_/g,"");let o=+t;if(isNaN(o))throw new Y("invalid number",{toml:e,ptr:n});if(s){if((s=!Number.isSafeInteger(o))&&!r)throw new Y("integer value cannot be represented losslessly",{toml:e,ptr:n});(s||r===!0)&&(o=BigInt(t))}return o}let i=new At(t);if(!i.isValid())throw new Y("invalid value",{toml:e,ptr:n});return i}function an(t,e=0,n=t.length){let r=t.indexOf(`
213
+ `,e);return t[r-1]==="\r"&&r--,r<=n?r:-1}function ft(t,e){for(let n=e;n<t.length;n++){let r=t[n];if(r===`
214
+ `)return n;if(r==="\r"&&t[n+1]===`
215
+ `)return n+1;if(r<" "&&r!==" "||r==="\x7F")throw new Y("control characters are not allowed in comments",{toml:t,ptr:e})}return t.length}function Pe(t,e,n,r){let s;for(;;){for(;(s=t[e])===" "||s===" "||!n&&(s===`
216
+ `||s==="\r"&&t[e+1]===`
217
+ `);)e++;if(r||s!=="#")break;e=ft(t,e)}return e}function vs(t,e,n,r,s=!1){if(!r)return e=an(t,e),e<0?t.length:e;for(let i=e;i<t.length;i++){let o=t[i];if(o==="#")i=an(t,i);else{if(o===n)return i+1;if(o===r||s&&(o===`
218
+ `||o==="\r"&&t[i+1]===`
219
+ `))return i}}throw new Y("cannot find end of structure",{toml:t,ptr:e})}function ga(t,e,n){let r=t.slice(e,n),s=r.indexOf("#");return s>-1&&(ft(t,s),r=r.slice(0,s)),[r.trimEnd(),s]}function It(t,e,n,r,s){if(r===0)throw new Y("document contains excessively nested structures. aborting.",{toml:t,ptr:e});let i=t[e];if(i==="["||i==="{"){let[l,d]=i==="["?Cs(t,e,r,s):xs(t,e,r,s);if(n){if(d=Pe(t,d),t[d]===",")d++;else if(t[d]!==n)throw new Y("expected comma or end of structure",{toml:t,ptr:d})}return[l,d]}if(i==='"'||i==="'"){let[l,d]=on(t,e);if(n){if(d=Pe(t,d),t[d]&&t[d]!==","&&t[d]!==n&&t[d]!==`
220
+ `&&t[d]!=="\r")throw new Y("unexpected character encountered",{toml:t,ptr:d});t[d]===","&&d++}return[l,d]}let o=vs(t,e,",",n),a=ga(t,e,o-(t[o-1]===","?1:0));if(!a[0])throw new Y("incomplete key-value declaration: no value specified",{toml:t,ptr:e});return n&&a[1]>-1&&(o=Pe(t,e+a[1]),t[o]===","&&o++),[ks(a[0],t,e,s),o]}var pa=/^[a-zA-Z0-9-_]+[ \t]*$/;function ln(t,e,n="="){let r=e-1,s=[],i=t.indexOf(n,e);if(i<0)throw new Y("incomplete key-value: cannot find end of key",{toml:t,ptr:e});do{let o=t[e=++r];if(o!==" "&&o!==" ")if(o==='"'||o==="'"){if(o===t[e+1]&&o===t[e+2])throw new Y("multiline strings are not allowed in keys",{toml:t,ptr:e});let[a,l]=on(t,e);r=t.indexOf(".",l);let d=t.slice(l,r<0||r>i?i:r),f=an(d);if(f>-1)throw new Y("newlines are not allowed in keys",{toml:t,ptr:e+r+f});if(d.trimStart())throw new Y("found extra tokens after the string part",{toml:t,ptr:l});if(i<l&&(i=t.indexOf(n,l),i<0))throw new Y("incomplete key-value: cannot find end of key",{toml:t,ptr:e});s.push(a)}else{r=t.indexOf(".",e);let a=t.slice(e,r<0||r>i?i:r);if(!pa.test(a))throw new Y("only letter, numbers, dashes and underscores are allowed in keys",{toml:t,ptr:e});s.push(a.trimEnd())}}while(r+1&&r<i);return[s,Pe(t,i+1,!0,!0)]}function xs(t,e,n,r){let s={},i=new Set,o;for(e++;(o=t[e++])!=="}"&&o;){if(o===",")throw new Y("expected value, found comma",{toml:t,ptr:e-1});if(o==="#")e=ft(t,e);else if(o!==" "&&o!==" "&&o!==`
221
+ `&&o!=="\r"){let a,l=s,d=!1,[f,m]=ln(t,e-1);for(let g=0;g<f.length;g++){if(g&&(l=d?l[a]:l[a]={}),a=f[g],(d=Object.hasOwn(l,a))&&(typeof l[a]!="object"||i.has(l[a])))throw new Y("trying to redefine an already defined value",{toml:t,ptr:e});!d&&a==="__proto__"&&Object.defineProperty(l,a,{enumerable:!0,configurable:!0,writable:!0})}if(d)throw new Y("trying to redefine an already defined value",{toml:t,ptr:e});let[c,h]=It(t,m,"}",n-1,r);i.add(c),l[a]=c,e=h}}if(!o)throw new Y("unfinished table encountered",{toml:t,ptr:e});return[s,e]}function Cs(t,e,n,r){let s=[],i;for(e++;(i=t[e++])!=="]"&&i;){if(i===",")throw new Y("expected value, found comma",{toml:t,ptr:e-1});if(i==="#")e=ft(t,e);else if(i!==" "&&i!==" "&&i!==`
222
+ `&&i!=="\r"){let o=It(t,e-1,"]",n-1,r);s.push(o[0]),e=o[1]}}if(!i)throw new Y("unfinished array encountered",{toml:t,ptr:e});return[s,e]}function Ts(t,e,n,r){let s=e,i=n,o,a=!1,l;for(let d=0;d<t.length;d++){if(d){if(s=a?s[o]:s[o]={},i=(l=i[o]).c,r===0&&(l.t===1||l.t===2))return null;if(l.t===2){let f=s.length-1;s=s[f],i=i[f].c}}if(o=t[d],(a=Object.hasOwn(s,o))&&i[o]?.t===0&&i[o]?.d)return null;a||(o==="__proto__"&&(Object.defineProperty(s,o,{enumerable:!0,configurable:!0,writable:!0}),Object.defineProperty(i,o,{enumerable:!0,configurable:!0,writable:!0})),i[o]={t:d<t.length-1&&r===2?3:r,d:!1,i:0,c:{}})}if(l=i[o],l.t!==r&&!(r===1&&l.t===3)||(r===2&&(l.d||(l.d=!0,s[o]=[]),s[o].push(s={}),l.c[l.i++]=l={t:1,d:!1,i:0,c:{}}),l.d))return null;if(l.d=!0,r===1)s=a?s[o]:s[o]={};else if(r===0&&a)return null;return[o,s,l.c]}function cn(t,{maxDepth:e=1e3,integersAsBigInt:n}={}){let r={},s={},i=r,o=s;for(let a=Pe(t,0);a<t.length;){if(t[a]==="["){let l=t[++a]==="[",d=ln(t,a+=+l,"]");if(l){if(t[d[1]-1]!=="]")throw new Y("expected end of table declaration",{toml:t,ptr:d[1]-1});d[1]++}let f=Ts(d[0],r,s,l?2:1);if(!f)throw new Y("trying to redefine an already defined table or value",{toml:t,ptr:a});o=f[2],i=f[1],a=d[1]}else{let l=ln(t,a),d=Ts(l[0],i,o,0);if(!d)throw new Y("trying to redefine an already defined table or value",{toml:t,ptr:a});let f=It(t,l[1],void 0,e,n);d[1][d[0]]=f[0],a=f[1]}if(a=Pe(t,a,!0),t[a]&&t[a]!==`
223
+ `&&t[a]!=="\r")throw new Y("each key-value declaration must be followed by an end-of-line",{toml:t,ptr:a});a=Pe(t,a)}return r}var Vs=14,er=60*6e4,Aa=24*er,Ia=2*6e4,Ra=12e4,$a=10*6e4,Rs=er,Da=15e3,$s=1792*1024,Pa=7,Ma=4*1024*1024,Oa=256*1024,Ve=t=>t.toISOString().slice(0,10),Ye=t=>Date.parse(Ve(t))-(Pa-1)*Aa,Ds=["user","teamwork","discussion","delegate"],Na=/^(?:New remarks in the team chat:|You are activated now \()/,Ys={totalBytes:1024*1024,sessionBytes:256*1024,textChars:8e3,sessions:300,messages:400},Ua=t=>t.replace(/\b[a-z][a-z0-9+.-]*:\/\/[^\s"'`<>]+|(?:~|\b[A-Za-z]:|\\)?(?:[\\/][^\s"'`<>:*?|\\/()[\]{},;]+){2,}[\\/]?/gi,e=>/^(?:[a-z][a-z0-9+.-]*:\/\/|\/(?:v\d+|api)\/)/i.test(e)?e:"[path]"),Dt=4e3,un=(t,e)=>typeof t=="string"&&t?Fe(Ua(Ge(t.slice(0,Dt))),e):void 0,ja={runs:200,totalBytes:128*1024,errorChars:300,events:2e3,tools:40},Fa=64*1024,Zn=500,La={totalBytes:256*1024,fileChars:24e3,logChars:12e3,activity:300,detailChars:300},Ha=256*1024,Ps=["SOUL.md","MEMORY.md",".memory-raw.md","HARNESS.md",".harness-raw.md",".harness-refinements.jsonl","HUMAN.md"],za=["description","developer_instructions"],Ba=["memory","harness","project_memory","human","dream","log_appended"],qa=["homeDir","readCreds","accountId","appVersion"],Gs=t=>qa.every(e=>typeof t[e]=="function"),Ms=Is().length>3?Is():null;function Ge(t){return typeof t=="string"?(Ms?t.split(Ms).join("~"):t).replace(/\bBearer\s+[A-Za-z0-9._~+\/-]+=*/gi,"Bearer [redacted]").replace(/\b(sk-[a-zA-Z0-9_-]{12,})\b/g,"[redacted]").replace(/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}/g,"[redacted]").replace(/\b(?:gh[pousr]_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,}|AKIA[0-9A-Z]{16}|LTAI[0-9A-Za-z]{12,}|xox[abeprs]-[A-Za-z0-9-]{10,}|AIza[0-9A-Za-z_-]{30,})/g,"[redacted]").replace(/-{5}BEGIN [A-Z ]*PRIVATE KEY-{5}[\s\S]*?(?:-{5}END [A-Z ]*PRIVATE KEY-{5}|$)/g,"[redacted]").replace(/\b[a-fA-F0-9]{32,}\b/g,(e,n,r)=>/^[a-f0-9]{48}$/.test(e)&&/(?:^|[^\w-])pr-$/.test(r.slice(Math.max(0,n-4),n))?e:`[hex:${e.length}]`).replace(/((?:["']?)(?:api[_-]?key|access[_-]?token|refresh[_-]?token|token|password|secret|authorization|cookie)(?:["']?)\s*[:=]\s*)("[^"\n]*"|'[^'\n]*'|\[[^\]\n]*\]|[^\s,"';&}]+)/gi,"$1[redacted]"):Array.isArray(t)?t.map(Ge):t&&typeof t=="object"?Object.fromEntries(Object.entries(t).map(([e,n])=>[e,/^(?:token|.*api[_-]?key|access[_-]?token|refresh[_-]?token|password|secret|authorization|cookie|set-cookie)$/i.test(e)?"[redacted]":Ge(n)])):t}var Wa=/^(?:model|modelId|voice|mode|backend|notify|escalateTo|realtimeModel|realtimeVoice|vision|background)$/,G=(t,e=120)=>typeof t=="string"&&t.length<=e?t:void 0,Va=(t,e)=>/^[A-Za-z_][\w.-]{0,63}$/.test(t)?t:`[key:${e}]`;function mt(t,e=0){if(typeof t=="boolean"||typeof t=="number"||t===null||t===void 0)return t??null;if(typeof t=="string")return`[string:${t.length}]`;if(Array.isArray(t))return`[array:${t.length}]`;if(typeof t!="object"||e>=4)return"[object]";let n={};for(let[r,[s,i]]of Object.entries(t).slice(0,100).entries())n[Va(s,r)]=Wa.test(s)&&G(i,80)!==void 0?i:mt(i,e+1);return n}var Ya={"":/^(?:name|version|description|model|model_reasoning_effort|approval_mode|max_iterations|tools|enabled_skill_ids|enabled_mcp_servers|library_order|apps|avatar|share_default_memory|cloud_sync|activity_access|tools_strict|tools_mode|tools_list|created_by|created_at|developer_instructions|compaction|lead|slug|members|mode|max_rounds)$/,compaction:/^(?:enabled|reserveTokens|thresholdPercent|keepRecentTokens|summaryMaxTokens|thinking|model|instructions|prompt)$/,members:/^(?:slug|role)$/},Os={"":/^(?:name|version|model|model_reasoning_effort|approval_mode|created_by|created_at|avatar|lead|slug)$/,compaction:/^model$/,members:/^slug$/},Ga=/^(?:apps|enabled_skill_ids)$/,Ns=t=>!!t&&typeof t=="object"&&!Array.isArray(t)&&!(t instanceof Date);function Ja(t){try{let e=cn(t),n=[],r=[],s=8192,i=(l,d)=>s<=0?!1:(s-=d.length+1,l.push(d),!0),o=(l,d,f)=>{let m=Ya[l].test(d)?d:`[key:${d.length}]`,c=Os[l].test(d),h;return typeof f=="boolean"||typeof f=="number"?h=String(f):c&&typeof f=="string"&&!/[\r\n]/.test(f)&&JSON.stringify(f).length<=120?h=JSON.stringify(f):c&&f instanceof Date?h=f.toISOString():l===""&&Ga.test(d)&&Array.isArray(f)&&f.every(g=>typeof g=="string"&&!/[\r\n]/.test(g))&&JSON.stringify(f).length<=2e3&&(h=`[${f.map(g=>JSON.stringify(g)).join(", ")}]`),`${m} = ${h??`"[text:${typeof f=="string"?f.length:JSON.stringify(f).length}]"`}`},a=(l,d,f)=>{if(i(r,d)){for(let[m,c]of Object.entries(f))if(!i(r,o(l,m,c)))return}};for(let[l,d]of Object.entries(e)){let f=l!==""&&Object.hasOwn(Os,l);if(f&&Ns(d))a(l,`[${l}]`,d);else if(f&&Array.isArray(d)&&d.length>0&&d.every(Ns))for(let m of d)a(l,`[[${l}]]`,m);else i(n,o("",l,d));if(s<=0)break}return[...n,...r].join(`
224
+ `)}catch{return`[unparsed:${t.length}]`}}var Js=async t=>{try{return(await Le(t)).isFile()?await _a(t,"utf8"):null}catch{return null}},$t=t=>Le(t).then(e=>e.isDirectory(),()=>!1),ht=async t=>{try{return JSON.parse(await Js(t)??"null")}catch{return null}},Me=async(t,e=200)=>{try{return(await Bs(t)).filter(n=>!n.startsWith(".")&&n.length<=120).sort().slice(0,e)}catch{return[]}};async function Ka(t,e){if(!(await Le(t)).isFile())return"";let n=await zs(t,"r");try{let{size:r}=await n.stat(),s=Math.max(0,r-e),i=Buffer.alloc(r-s);await n.read(i,0,i.length,s);let o=i.toString("utf8");return s>0?o.slice(o.indexOf(`
225
+ `)+1):o}finally{await n.close()}}function Xa(t){if(!t||typeof t!="object")return{};let e=n=>n&&typeof n=="object"?Object.entries(n).slice(0,100):[];return{defaultModel:G(t.cloud?.defaultModel)??null,models:mt(t.models),tts:mt(t.tts),asr:mt(t.asr),specialAgents:mt(t.specialAgents),pluginSettings:mt(t.plugins?.global),providers:(Array.isArray(t.providers)?t.providers:[]).slice(0,50).map(n=>({providerId:G(n?.providerId)??null,models:(Array.isArray(n?.modelIds)?n.modelIds:[]).filter(r=>G(r)!==void 0).slice(0,100)})),mcpServers:e(t.mcp?.mcpServers).map(([n,r])=>({name:G(n,64)??"[name]",enabled:r?.enabled!==!1})),channels:e(t.channels).map(([n,r])=>({name:G(n,64)??"[name]",enabled:r?.enabled===!0}))}}var Za=new Set(["config.toml","SOUL.md","MEMORY.md","HARNESS.md","HUMAN.md","Library","LOG","skills","plugins","Space","SCHEDULE.db","triggers.json"]);async function Us(t){let e=[];for(let n of await Me(t,100)){let r=K(t,n);if(!await $t(r))continue;let s=await Js(K(r,"config.toml"));e.push({id:n,config:s===null?null:Ja(s).slice(0,4096),files:(await Me(r,400)).filter(i=>Za.has(i))})}return e}async function js(t){let e=[];for(let n of await Me(t,300)){let r=await ht(K(t,n,"manifest.json"));r&&e.push({id:G(r.id)??n,version:G(r.version,40)??null,name:G(r.nameEn)??G(r.name)??null})}return e}var Qe=t=>String(t?.code||t?.message||t).slice(0,120);async function Qa(t,e,n,r=Oa){let s=c=>String(c).padStart(2,"0"),i=c=>{let h=new Date(c);return`${h.getFullYear()}${s(h.getMonth()+1)}${s(h.getDate())}${s(h.getHours())}${s(h.getMinutes())}`},o=c=>`${c.slice(0,4)}-${c.slice(4,6)}-${c.slice(6,8)}.log`,a=i(n),l=i(e.getTime()),d=[],f=r,m=!1;try{let c=(await Bs(t)).filter(h=>/^\d{4}-\d{2}-\d{2}\.log$/.test(h)&&h>=o(a)&&h<=o(l)).sort().reverse();for(let h of c){if(m)break;let S=(await Ka(K(t,h),Ma).catch(A=>{if(A?.code==="ENOENT")return"";throw A})).split(`
226
+ `).filter(A=>/^\d{12} /.test(A)&&A.slice(0,12)>=a&&A.slice(0,12)<l),y=S.length;for(;y>0&&Buffer.byteLength(S[y-1])+1<=f;)f-=Buffer.byteLength(S[--y])+1;y>0&&(m=!0),y<S.length&&d.push({date:h.slice(0,10),log:S.slice(y).join(`
227
+ `)})}}catch(c){return c?.code==="ENOENT"?{activity:[]}:{activity:[],activityError:Qe(c)}}return{activity:d.reverse(),...m?{activityTruncated:!0}:{}}}var Fe=(t,e)=>{if(!(typeof t!="string"||!t))return t.length>e?`${t.slice(0,e)}\u2026[+${t.length-e}]`:t},Fs=t=>{try{let e=typeof t=="string"?JSON.parse(t):t;return Array.isArray(e)?e:[]}catch{return[]}},gt=t=>new Date(t).toISOString().slice(0,19).replace("T"," ");async function el(t,e,n=Ys,r=Ye(e)){let s=K(t,"tangu","state.db"),i=await Le(s).then(a=>a.isFile(),a=>a?.code==="ENOENT"?!1:Qe(a));if(i!==!0)return i===!1?{sessions:[]}:{sessions:[],sessionsError:i};let o;try{let{DatabaseSync:a}=await import("node:sqlite");o=new a(s,{readOnly:!0}),o.exec("PRAGMA busy_timeout = 1500");let d="m.updated_at >= ? AND m.updated_at < ? AND m.timestamp >= ?",f=[gt(r),gt(e.getTime()),Ye(e)],m=o.prepare(`SELECT s.id, s.kind, s.parent_session_id, s.app_id, s.title, s.model_id, s.project_name, s.archived, s.created_at, s.updated_at, MAX(m.updated_at) AS changed_at
208
228
  FROM chat_messages m JOIN chat_sessions s ON s.id = m.session_id
209
- WHERE s.kind IN (${us.map(()=>"?").join(", ")}) AND ${h} GROUP BY s.id ORDER BY changed_at DESC, s.id LIMIT ?`).all(...us,...d,n.sessions+1),u=a.prepare(`SELECT m.role, m.content, m.reasoning, m.timestamp, m.model_id, m.is_error, m.tool_calls, length(m.tool_results) AS tool_result_chars, m.attachments, m.agent_slug
210
- FROM chat_messages m WHERE m.session_id = ? AND ${h} ORDER BY m.timestamp DESC, m.created_at DESC LIMIT ?`),g=[],S=0,x=f.length>n.sessions;for(let w of f.slice(0,n.sessions)){let F=u.all(w.id,...d,n.messages+1),_=F.length>n.messages,A=[],U=0;for(let j of F.slice(0,n.messages)){let K=ms(j.tool_calls),se=w.kind==="teamwork"&&j.role==="user"&&Gi.test(String(j.content??"")),he={role:re(j.role,16)??null,at:Number(j.timestamp)||null,agent:re(j.agent_slug,64),model:re(j.model_id,128),error:j.is_error?!0:void 0,text:se?void 0:qt(j.content,n.textChars),relayChars:se?String(j.content??"").length:void 0,reasoning:qt(j.reasoning,n.textChars),tools:K.length?K.map(ae=>re(ae?.function?.name??ae?.name,80)??"?"):void 0,toolArgChars:K.length?K.reduce((ae,Ee)=>ae+String(Ee?.function?.arguments??"").length,0):void 0,toolResultChars:Number(j.tool_result_chars)||void 0,attachments:ms(j.attachments).length||void 0},we=Buffer.byteLength(JSON.stringify(he));if(U+we>n.sessionBytes){_=!0;break}U+=we,A.push(he)}let M={id:re(w.id,64)??null,kind:re(w.kind,16)??null,parent:re(w.parent_session_id,64),app:re(w.app_id,50)??null,title:qt(w.title,200)??null,model:re(w.model_id,128)??null,project:qt(w.project_name,120),archived:w.archived?!0:void 0,createdAt:re(w.created_at,40)??null,updatedAt:re(w.updated_at,40)??null,messages:A.reverse(),..._?{olderMessagesDropped:!0}:{}},B=Buffer.byteLength(JSON.stringify(M));if(S+B>n.totalBytes){x=!0;break}S+=B,g.push(M)}return{sessions:g,...x?{sessionsTruncated:!0}:{}}}catch(i){return{sessions:[],sessionsError:Nn(i)}}finally{try{a?.close()}catch{}}}async function Es(t){let e=(await Fn(ue(t,"tangu","device.json")))?.deviceId;return typeof e=="string"&&/^[A-Za-z0-9_-]{1,64}$/.test(e)?e:`h${Pi("sha256").update(ys()).digest("hex").slice(0,8)}`}var _s=["sessions","activity"],Wt=t=>typeof t=="number"&&Number.isFinite(t)?t:void 0;function aa(t,e,n){let r=t?.day===ot(n)?t:void 0;return Object.fromEntries(_s.map(s=>[s,Wt(r?.[s])??Math.min(Math.max(Wt(e[s])??0,Bt(n)),n.getTime())]))}function la(t,e,n,r,s,o){let a=e?.day===ot(r)?e:void 0,i={sent:{...t},file:{day:ot(r)}};for(let l of _s){let h=l in s&&!o.includes(l)&&!(`${l}Error`in s),d=Wt(a?.[l]);h?(i.file[l]=n[l],i.sent[l]=r.getTime()):d!==void 0&&(i.sent[l]=Math.min(Wt(t[l])??d,d))}return i}async function ca(t){let{home:e}=t,n=ue(e,"tangu"),r=t.now??new Date,s=o=>t.since?.[o]??Bt(r);return Mn({schema:2,collectedAt:r.toISOString(),app:{version:t.appVersion,platform:process.platform,arch:process.arch,os:Fi(),electron:process.versions.electron??null,node:process.versions.node,locale:Intl.DateTimeFormat().resolvedOptions().locale,timeZone:Intl.DateTimeFormat().resolvedOptions().timeZone,home:ji(e),cloudUrl:t.cloudUrl},device:{id:await Es(e),name:ys()},config:ra(await Fn(ue(e,"config.json"))),agents:await fs(ue(n,"agents")),teams:await fs(ue(n,"teams")),plugins:{desktop:await hs(ue(e,"plugins")),engine:await hs(ue(n,"plugins"))},inventory:{skills:await st(ue(n,"skills")),spaces:await st(ue(e,"spaces")),themes:await st(ue(e,"themes"))},...t.activity?{...await oa(ue(e,"activity"),r,s("activity")),activitySince:new Date(s("activity")).toISOString()}:{},...t.sessions?{...await ia(e,r,bs,s("sessions")),sessionsSince:new Date(s("sessions")).toISOString()}:{}})}function ua(t,e=[]){let n={...t},r=Buffer.from(JSON.stringify(n),"utf8");for(let s of["activity","sessions"]){if(r.length<=cs)break;s in n&&(delete n[s],e.push(s),r=Buffer.from(JSON.stringify({...n,truncated:e}),"utf8"))}return r.length>cs?null:r}async function da(t,e,n,r=new Date){let s=AbortSignal.timeout(zi);await t.writeFile(`${e}/${ot(r)}.json`,n,r.getTime(),s);try{let o=ot(new Date(r.getTime()-ws*24*60*6e4));for(let a of await t.walk(s)){let i=/^([^/]+)\/(\d{4}-\d{2}-\d{2})\.json$/.exec(a.key);i&&i[1]===e&&i[2]<o&&await t.rm(a.key,s)}}catch{}}var ks={mode:"scheduled",intervalHours:24,requestedAt:0};function On(t){let e=t&&typeof t=="object"?t:{},n=Number(e.intervalHours),r=Number(e.requestedAt);return{mode:e.mode==="manual"?"manual":"scheduled",intervalHours:Number.isInteger(n)&&n>=1&&n<=720?n:ks.intervalHours,requestedAt:Number.isFinite(r)&&r>0?r:0}}async function fa(t){try{let e=await fetch(`${t.cloudUrl.replace(/\/+$/,"")}/api/remotesync/diagnostics/policy`,{headers:{Authorization:`Bearer ${t.token}`},signal:AbortSignal.timeout(Bi)});return e.status===404?{...ks}:e.ok?On(await e.json()):null}catch{return null}}function Cs(t,e={}){let n=e.now??(()=>new Date),r=e.remoteFor??(_=>Tt({baseUrl:_.cloudUrl,vault:xt,getToken:()=>_.token})),s=e.policyFor??fa,o=()=>ue(t.homeDir(),"extend-diagnostics.json"),a=()=>{let _=A=>A&&typeof A=="object"?A:{};try{let A=JSON.parse(Di(o(),"utf8"));return{accounts:_(A?.accounts),sent:_(A?.sent)}}catch{return{accounts:{},sent:{}}}},i=()=>a().accounts,l=(_,A,U)=>{let M=a();M.accounts[_]={...M.accounts[_],...A},Object.assign(M.sent,U),$i(t.homeDir(),{recursive:!0});let B=`${o()}.${process.pid}.tmp`;Ni(B,JSON.stringify(M,null,2),{encoding:"utf8",mode:384}),Mi(B,o())},h=()=>{let _=t.readCreds();return _.token&&_.cloudUrl?t.accountId():null},d=()=>{let _=h(),A=_?i()[_]??{}:{},U=On(A.policy);return{signedIn:!!_,enabled:A.enabled===!0,activity:A.activity!==!1,sessions:A.sessions??A.enabled!==!0,lastUploadAt:A.lastUploadAt??null,lastError:A.lastError??null,retainDays:ws,mode:U.mode,intervalHours:U.intervalHours}},f=null,u=new Map,g=async()=>{let _=h();if(!_)return!1;if(f)return f.id===_?f.done:(await f.done,g());let A={...t.readCreds()},U=n(),M=a(),B=M.accounts[_],j=A.cloudUrl.replace(/\/+$/,""),K=aa(B?.file,M.sent[j]??{},U),se=(async()=>{try{let he=await ca({home:t.homeDir(),appVersion:t.appVersion(),cloudUrl:A.cloudUrl,activity:B?.activity!==!1,sessions:B?.sessions===!0,now:U,since:K}),we=await Es(t.homeDir()),ae=i()[_];if(h()!==_||ae?.enabled!==!0)return!1;if(ae.activity===!1)for(let C of["activity","activityTruncated","activityError","activitySince"])delete he[C];if(ae.sessions!==!0)for(let C of["sessions","sessionsTruncated","sessionsError","sessionsSince"])delete he[C];let Ee=[],$e=ua(he,Ee);if(!$e)throw new Error("snapshot too large");await da(r(A),we,$e,U),u.delete(_);let k=la(a().sent[j]??{},B?.file,K,U,he,Ee);return l(_,{lastUploadAt:n().getTime(),lastError:void 0,file:k.file},{[j]:k.sent}),t.log(`[forsion-extend] diagnostics uploaded (${$e.length} bytes)`),!0}catch(he){u.set(_,n().getTime());let we=String(he?.message||he).slice(0,300);try{l(_,{lastError:we})}catch{}return t.log(`[forsion-extend] diagnostics upload failed: ${we}`),!1}finally{f=null}})();return f={id:_,done:se},se},S=async()=>{try{let _=h();if(!_||i()[_]?.enabled!==!0)return;let A=await s({...t.readCreds()}),U=h()===_?i()[_]:void 0;if(U?.enabled!==!0)return;A&&(A.mode!==U.policy?.mode||A.intervalHours!==U.policy?.intervalHours)&&l(_,{policy:{mode:A.mode,intervalHours:A.intervalHours}}),A&&U.requestSeen===void 0&&l(_,{requestSeen:A.requestedAt});let M=A??{...On(U.policy),requestedAt:0},B=M.requestedAt>(U.requestSeen??M.requestedAt),j=U.lastUploadAt??0,K=!j||M.mode==="scheduled"&&n().getTime()-j>=M.intervalHours*Un;if(!B&&!K||n().getTime()-(u.get(_)??-ls)<ls)return;await g()&&B&&l(_,{requestSeen:M.requestedAt})}catch(_){t.log(`[forsion-extend] diagnostics tick failed: ${String(_?.message||_)}`)}},x={ok:!1,error:"untrusted"};t.handle("diagnostics:get",_=>t.isTrustedSender(_)?d():x),t.handle("diagnostics:set",(_,A)=>{if(!t.isTrustedSender(_))return x;let U=h();if(!U)return d();let M={};typeof A?.enabled=="boolean"&&(M.enabled=A.enabled),M.enabled&&(M.requestSeen=void 0),typeof A?.activity=="boolean"&&(M.activity=A.activity),typeof A?.sessions=="boolean"&&(M.sessions=A.sessions);let B=i()[U];return M.sessions===void 0&&B?.sessions===void 0&&(B?.enabled===!0?M.sessions=!1:M.enabled&&(M.sessions=!0)),l(U,M),M.enabled&&(u.delete(U),S()),d()}),t.handle("diagnostics:uploadNow",async _=>t.isTrustedSender(_)?(d().enabled&&await g(),d()):x);let w=setTimeout(()=>void S(),Hi),F=setInterval(()=>void S(),qi);return w.unref?.(),F.unref?.(),t.log("[forsion-extend] diagnostics registered"),Object.assign(()=>{clearTimeout(w),clearInterval(F)},{tick:S})}async function Ts(t,e){if(!e)return"";try{let n=await ge({base:t,token:e},"POST","/api/auth/handoff",{},5e3);if(n.status===200&&typeof n.json?.code=="string"&&n.json.code)return`code=${encodeURIComponent(n.json.code)}`;if(n.status===404||n.status===405)return`token=${encodeURIComponent(e)}`}catch{}return""}var ha=["membership","credits","storefront"],ma=["monthly","quarterly","yearly"],ga=/^[A-Za-z0-9_-]{1,64}$/;function pc(t){let e={status:0,error:"untrusted"},n={ok:!1,error:"untrusted"};t.handle("auth:openAccountCenter",async(s,o)=>{if(!t.isTrustedSender(s))return n;let{base:a,token:i}=await t.getCloud();if(!a)return{ok:!1};let l=o&&/^[a-z0-9-]+$/i.test(o)?`#${o}`:"",h=await Ts(a,i),d=`${a}/account${h?`?${h}`:""}${l}`;return await t.openExternal(d),{ok:!0}}),t.handle("auth:openPayCenter",async(s,o,a,i)=>{if(!t.isTrustedSender(s))return n;if(o!==void 0&&!ha.includes(o))return{ok:!1,error:"invalid_tab"};if(a!==void 0&&(typeof a!="string"||!ga.test(a)))return{ok:!1,error:"invalid_plan"};if(i!==void 0&&!ma.includes(i))return{ok:!1,error:"invalid_period"};let l=(o??"membership")==="membership"&&a?`&plan=${encodeURIComponent(a)}${i?`&period=${i}`:""}`:"",{base:h,token:d}=await t.getCloud();if(!h)return{ok:!1};let f=await Ts(h,d),u=`${h}/pay?tab=${o??"membership"}${l}${f?`&${f}`:""}&redirect=${encodeURIComponent(`${h}/account`)}`;return await t.openExternal(u),{ok:!0}});let r=()=>t.getCloud();t.handle("account:quota",async s=>{if(!t.isTrustedSender(s))return e;let o=await r();if(!o.token)return{status:401,json:null};try{return await ge(o,"GET","/api/token-quota/my",void 0,15e3)}catch(a){return{status:0,json:{detail:String(a?.message||a)}}}}),t.handle("account:useResetCard",async(s,o)=>{if(!t.isTrustedSender(s))return e;let a=await r();if(!a.token)return{status:401,json:null};if(o!==void 0&&o!=="both")return{status:400,json:{error:"invalid_type",detail:`invalid reset card type: ${o}`}};let i=o??"both";try{return await ge(a,"POST","/api/token-quota/reset-card/use",{type:i},15e3)}catch(l){return{status:0,json:{detail:String(l?.message||l)}}}}),t.handle("account:bgConvert",async(s,o)=>{if(!t.isTrustedSender(s))return e;let a=await r();if(!a.token)return{status:401,json:null};if(!Number.isInteger(o)||o<1||o>100)return{status:400,json:{error:"invalid_percent"}};try{return await ge(a,"POST","/api/token-quota/background/convert",{percent:o},15e3)}catch(i){return{status:0,json:{detail:String(i?.message||i)}}}}),t.handle("account:bgAutoMain",async(s,o)=>{if(!t.isTrustedSender(s))return e;let a=await r();if(!a.token)return{status:401,json:null};if(typeof o!="boolean")return{status:400,json:{error:"invalid_request"}};try{return await ge(a,"POST","/api/token-quota/background/auto-main",{enabled:o},15e3)}catch(i){return{status:0,json:{detail:String(i?.message||i)}}}}),t.handle("feedback:submit",async(s,o)=>{if(!t.isTrustedSender(s))return n;let{base:a,token:i}=await t.getCloud();if(!a||!i)return{ok:!1,error:"not-logged-in"};let l=(o?.description||"").trim();if(!l)return{ok:!1,error:"empty"};if(l.length>1e4)return{ok:!1,error:"description-too-long"};let h=[],d=!1;if(o?.sessionLogJson){let f=Buffer.from(o.sessionLogJson,"utf8");if(f.length>5*1024*1024)return{ok:!1,error:"attachment-too-large"};h.push({filename:o.sessionLogName||"tangu-session.json",mime_type:"application/json",size:f.length,data_base64:f.toString("base64")})}try{let f=await fetch(`${a}/api/feedback`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${i}`},body:JSON.stringify({description:l,attachments:h}),signal:AbortSignal.timeout(2e4)});if(!f.ok){let g=`HTTP ${f.status}`;try{g=(await f.json())?.detail||g}catch{}return{ok:!1,error:g}}return{ok:!0,id:(await f.json().catch(()=>({})))?.id??null,attachmentSkipped:d}}catch(f){return{ok:!1,error:f?.message||String(f)}}}),t.handle("cloud:fetch",async(s,o)=>{if(!t.isTrustedSender(s))return{status:0,error:"untrusted"};let a=o??{},i=typeof a.path=="string"?a.path:"",l=Math.min(12e4,Math.max(1e3,Number(a.timeoutMs)||15e3)),h=typeof a.method=="string"?a.method.toUpperCase():"GET";if(!/^(GET|POST|PUT|PATCH|DELETE)$/.test(h))return{status:0,error:"bad_method"};if(!i.startsWith("/"))return{status:0,error:"bad_path"};let{base:d,token:f}=await t.getCloud();if(!String(d||""))return{status:0,error:"no_cloud_url"};let u=Jn(d,i);if(!u)return{status:0,error:"bad_path"};if(!f)return{status:401,error:"not_signed_in"};let g=a.body!==void 0&&h!=="GET"&&h!=="DELETE",S=new AbortController,x=setTimeout(()=>S.abort(),l);try{let w=await fetch(u,{method:h,headers:{Authorization:`Bearer ${f}`,...g?{"Content-Type":"application/json"}:{}},body:g?JSON.stringify(a.body):void 0,signal:S.signal});return{status:w.status,json:await w.json().catch(()=>null)}}catch(w){return{status:0,error:String(w?.message||w)}}finally{clearTimeout(x)}}),t.log("[forsion-extend] cloud account handlers registered"),Qt(t)?en(t):t.log("[forsion-extend] host has no Connect seam (projectsRoot / transpileForServe / mimeOf / setPreviewHooks); Connect stays with the host"),nn(t)?rn(t):t.log("[forsion-extend] host has no remote-sync seam (registerRemoteSyncBackend / readCreds); penzor stays with the host"),on(t)?an(t):t.log("[forsion-extend] host has no account seam (accountCommit / accountClear / \u2026); account core stays with the host"),In(t)?Rn(t):t.log("[forsion-extend] host has no amadeus seam (setAmadeusSyncFactory); cloud sync stays with the host"),$n(t)?Dn(t):t.log("[forsion-extend] host has no unit seam (setUnitHubFactory); the device channel stays with the host"),Ss(t)?Cs(t):t.log("[forsion-extend] host has no diagnostics seam (homeDir / readCreds / accountId / appVersion); diagnostics upload is off")}export{hr as ACCOUNT_SEAM,ns as AMADEUS_SEAM,Xt as CONNECT_MAX_FILES,Xn as CONNECT_MAX_FILE_BYTES,Zn as CONNECT_MAX_TOTAL_BYTES,xt as DIAGNOSTICS_VAULT,sr as FORSION_CONNECT_LOCAL_SDK,ma as PAY_PERIODS,ha as PAY_TABS,ar as PENZOR_MAX_FILE,ce as SYNC_IPC,os as UNIT_SEAM,yt as UnitCapsReporter,pt as UnitHost,ge as cloudJson,Qn as collectProjectFiles,Ft as conflictCopyPath,Qo as conflictCopyVariant,fr as createAccountCloud,rs as createAmadeusCloud,Tt as createPenzorRemote,is as createUnitHub,tn as expectedPartsOf,Te as forsionAccountId,dr as forsionRefreshToken,lt as forsionWhoami,on as hasAccountHost,In as hasAmadeusHost,Qt as hasConnectHost,nn as hasRemoteSyncHost,$n as hasUnitHost,rr as makePreviewProxy,tr as readConnectMeta,an as registerAccount,Rn as registerAmadeus,pc as registerCloud,en as registerConnect,rn as registerPenzor,Dn as registerUnit,ur as shouldRefreshToken,ss as streamWorthy,Qr as stripConflictSuffix,ei as textFingerprint,cr as tokenAgeMs,eo as tokenRemainingMs,nr as writeConnectMeta};
229
+ WHERE s.kind IN (${Ds.map(()=>"?").join(", ")}) AND ${d} GROUP BY s.id ORDER BY changed_at DESC, s.id LIMIT ?`).all(...Ds,...f,n.sessions+1),c=o.prepare(`SELECT m.role, m.content, m.reasoning, m.timestamp, m.model_id, m.is_error, m.tool_calls, length(m.tool_results) AS tool_result_chars, m.attachments, m.agent_slug
230
+ FROM chat_messages m WHERE m.session_id = ? AND ${d} ORDER BY m.timestamp DESC, m.created_at DESC LIMIT ?`),h=[],g=0,S=m.length>n.sessions;for(let y of m.slice(0,n.sessions)){let A=c.all(y.id,...f,n.messages+1),R=A.length>n.messages,T=[],I=0;for(let L of A.slice(0,n.messages)){let H=Fs(L.tool_calls),Q=y.kind==="teamwork"&&L.role==="user"&&Na.test(String(L.content??"")),le={role:G(L.role,16)??null,at:Number(L.timestamp)||null,agent:G(L.agent_slug,64),model:G(L.model_id,128),error:L.is_error?!0:void 0,text:Q?void 0:Fe(L.content,n.textChars),relayChars:Q?String(L.content??"").length:void 0,reasoning:Fe(L.reasoning,n.textChars),tools:H.length?H.map(ce=>G(ce?.function?.name??ce?.name,80)??"?"):void 0,toolArgChars:H.length?H.reduce((ce,ye)=>ce+String(ye?.function?.arguments??"").length,0):void 0,toolResultChars:Number(L.tool_result_chars)||void 0,attachments:Fs(L.attachments).length||void 0},me=Buffer.byteLength(JSON.stringify(le));if(I+me>n.sessionBytes){R=!0;break}I+=me,T.push(le)}let D={id:G(y.id,64)??null,kind:G(y.kind,16)??null,parent:G(y.parent_session_id,64),app:G(y.app_id,50)??null,title:Fe(y.title,200)??null,model:G(y.model_id,128)??null,project:Fe(y.project_name,120),archived:y.archived?!0:void 0,createdAt:G(y.created_at,40)??null,updatedAt:G(y.updated_at,40)??null,messages:T.reverse(),...R?{olderMessagesDropped:!0}:{}},P=Buffer.byteLength(JSON.stringify(D));if(g+P>n.totalBytes){S=!0;break}g+=P,h.push(D)}return{sessions:h,...S?{sessionsTruncated:!0}:{}}}catch(a){return{sessions:[],sessionsError:Qe(a)}}finally{try{o?.close()}catch{}}}async function tl(t,e,n=ja){let r=K(t,"tangu","state.db"),s=await Le(r).then(o=>o.isFile(),o=>o?.code==="ENOENT"?!1:Qe(o));if(s!==!0)return s===!1?{runs:[]}:{runs:[],runsError:s};let i;try{let{DatabaseSync:o}=await import("node:sqlite");i=new o(r,{readOnly:!0}),i.exec("PRAGMA busy_timeout = 1500");let l=i.prepare(`SELECT r.id, r.session_id, r.app_id, r.status, r.current_step, r.model_id, substr(r.error, 1, ${Dt}) AS error, r.tokens_total, r.created_at, r.updated_at, s.kind
231
+ FROM agent_runs r LEFT JOIN chat_sessions s ON s.id = r.session_id
232
+ WHERE r.updated_at >= ? AND r.updated_at < ? ORDER BY r.updated_at DESC, r.id LIMIT ?`).all(gt(Ye(e)),gt(e.getTime()),n.runs+1),d=i.prepare(`SELECT e.type, json_extract(e.payload, '$.name') AS name, json_extract(e.payload, '$.isError') AS failed, json_extract(e.payload, '$.elapsedMs') AS ms,
233
+ json_extract(e.payload, '$.prompt') AS prompt, json_extract(e.payload, '$.completion') AS completion, json_extract(e.payload, '$.cached') AS cached,
234
+ json_extract(e.payload, '$.reasoningTokens') AS reasoning, json_extract(e.payload, '$.llmMs') AS llm_ms, json_extract(e.payload, '$.ttftMs') AS ttft_ms,
235
+ json_extract(e.payload, '$.requestBytes') AS request_bytes, json_extract(e.payload, '$.phase') AS phase, substr(json_extract(e.payload, '$.error'), 1, ${Dt}) AS error
236
+ FROM agent_run_events e WHERE e.run_id = ? AND e.type IN ('usage', 'tool_result', 'error', 'status') AND json_valid(e.payload) ORDER BY e.seq LIMIT ?`),f=S=>typeof S=="number"&&Number.isFinite(S)&&S>0?S:0,m=S=>S||void 0,c=[],h=0,g=l.length>n.runs;for(let S of l.slice(0,n.runs)){let y={llmCalls:0,prompt:0,completion:0,cached:0,reasoning:0,llmMs:0,ttftMaxMs:0,requestMaxBytes:0},A=new Map,R=[],T=0,I=d.all(S.id,n.events+1),D=I.length>n.events;for(let H of I.slice(0,n.events))if(H.type==="usage")y.llmCalls++,y.prompt+=f(H.prompt),y.completion+=f(H.completion),y.cached+=f(H.cached),y.reasoning+=f(H.reasoning),y.llmMs+=f(H.llm_ms),y.ttftMaxMs=Math.max(y.ttftMaxMs,f(H.ttft_ms)),y.requestMaxBytes=Math.max(y.requestMaxBytes,f(H.request_bytes));else if(H.type==="tool_result"){let Q=G(H.name,80)??"?",le=A.get(Q)??(A.size<n.tools?{name:Q,n:0,ms:0,maxMs:0}:void 0);if(!le){D=!0;continue}A.set(Q,le),le.n++,H.failed&&(le.errors=(le.errors??0)+1),le.ms+=f(H.ms),le.maxMs=Math.max(le.maxMs,f(H.ms))}else if(H.type==="error"){let Q=un(H.error,n.errorChars);Q&&!R.includes(Q)&&R.length<3&&R.push(Q)}else H.phase==="llm_retry"&&T++;let P={id:G(S.id,64)??null,session:G(S.session_id,64)??null,kind:G(S.kind,16),app:G(S.app_id,50),model:G(S.model_id,128),status:G(S.status,16)??null,error:un(S.error,n.errorChars),createdAt:G(S.created_at,40)??null,updatedAt:G(S.updated_at,40)??null,steps:m(f(S.current_step)),tokens:m(f(S.tokens_total)),retries:m(T),...Object.fromEntries(Object.entries(y).map(([H,Q])=>[H,m(Q)])),errors:R.length?R:void 0,tools:A.size?[...A.values()]:void 0,partial:D||void 0},L=Buffer.byteLength(JSON.stringify(P));if(h+L>n.totalBytes){g=!0;break}h+=L,c.push(P)}return{runs:c,...g?{runsTruncated:!0}:{}}}catch(o){return{runs:[],runsError:Qe(o)}}finally{try{i?.close()}catch{}}}async function nl(t){let e=s=>Math.round(s/1048576),n=s=>Le(s).then(i=>i.isFile()?i.size:0,()=>0),r=K(t,"tangu","state.db");return{cpus:va().length,memTotalMB:e(Ta()),memFreeMB:e(xa()),diskFreeMB:await ka(t).then(s=>e(s.bavail*s.bsize),()=>null),stateDbMB:e(await n(r)+await n(`${r}-wal`)),uptimeMin:Math.round(process.uptime()/60)}}var Ls=t=>typeof t.diagnosticLogs=="function";function rl(t,e=Fa){let n=t?.engine;if(!n||typeof n!="object")return null;let r=(Array.isArray(n.lines)?n.lines:[]).filter(l=>typeof l=="string"&&!!l),s=r.map(l=>un(l,Zn)??""),i=s.some((l,d)=>l.length>Zn||r[d].length>Dt),o=s.length,a=e;for(;o>0&&Buffer.byteLength(s[o-1])+1<=a;)a-=Buffer.byteLength(s[--o])+1;return o>0&&(i=!0),{state:G(n.state,32)??null,lastError:un(n.lastError,Zn)??null,log:s.slice(o).join(`
237
+ `),...i?{logTruncated:!0}:{}}}function sl(t,e=za){let n;try{n=cn(t)}catch{return{}}return Object.fromEntries(e.flatMap(r=>typeof n[r]=="string"&&n[r]?[[r,n[r]]]:[]))}async function Ks(t,e=Ha){try{if(!(await Le(t)).isFile())return null;let n=await zs(t,As.O_RDONLY|(As.O_NOFOLLOW??0));try{let r=await n.stat();if(!r.isFile())return null;let s=Buffer.alloc(Math.min(e,r.size)),{bytesRead:i}=await n.read(s,0,s.length,0);return s.subarray(0,i).toString("utf8")}finally{await n.close()}}catch{return null}}var Rt=async(t,e)=>{let n=await Ks(t);return n?Fe(Ge(n),e):void 0};async function il(t,e){let n=await Ks(K(t,"config.toml")),r=Object.entries(n?sl(n):{}).map(([s,i])=>[s,Fe(Ge(i),e)??""]);return r.length?Object.fromEntries(r):void 0}async function Hs(t){let e=await ht(K(t,".memory-state.json"));if(!e||typeof e!="object")return;let n=r=>Array.isArray(r)?r.length:0;return{entries:n(e.entries),tombstones:n(e.tombstones),revisions:n(e.revisions),processedCandidates:n(e.processedCandidateIds),updatedAt:typeof e.updatedAt=="number"?e.updatedAt:null,projectionPending:e.projectionPending===!0?!0:void 0}}async function ol(t,e,n=La){let r=K(t,"tangu"),s=h=>Le(h).then(g=>g.isFile()?g.mtimeMs:0,()=>0),i=Ve(new Date(Ye(e))),o={agents:[],teams:[],projects:[],activity:[]},a=n.totalBytes,l=(h,g)=>{let S=Buffer.byteLength(JSON.stringify(g))+1;return S>a?(o.truncated=!0,!1):(a-=S,h.push(g),!0)},d=await Rt(K(r,"USER.md"),n.fileChars);d&&l([],d)&&(o.user=d);let f=K(r,"state.db"),m=await Le(f).then(h=>h.isFile(),h=>h?.code==="ENOENT"?!1:Qe(h));if(typeof m=="string")o.activityError=m;else if(m){let h;try{let{DatabaseSync:g}=await import("node:sqlite");h=new g(f,{readOnly:!0}),h.exec("PRAGMA busy_timeout = 1500");let y=h.prepare(`SELECT agent, action, substr(detail, 1, ${Dt}) AS detail, session_ref, created_at FROM special_agent_log
238
+ WHERE created_at >= ? AND created_at < ? AND (${Ba.map(A=>`action GLOB '${A}*'`).join(" OR ")})
239
+ ORDER BY created_at DESC, rowid DESC LIMIT ?`).all(gt(Ye(e)),gt(e.getTime()),n.activity+1);y.length>n.activity&&(o.truncated=!0);for(let A of y.slice(0,n.activity))if(!l(o.activity,{at:G(A.created_at,40)??null,agent:G(A.agent,64)??null,action:G(A.action,64)??null,detail:typeof A.detail=="string"&&A.detail?Fe(Ge(A.detail),n.detailChars):void 0,session:G(A.session_ref,64)}))break}catch(g){o.activityError=Qe(g)}finally{try{h?.close()}catch{}}}for(let h of await Me(K(r,"project-memory"),100)){let g=K(r,"project-memory",h);if(!await $t(g))continue;let S=await Rt(K(g,"MEMORY.md"),n.fileChars),y=await Hs(g);if(!S&&!y)continue;let A=(await ht(K(g,"PROJECT.json")))?.project;if(!l(o.projects,{id:G(h,64)??null,name:typeof A=="string"?G(Ws(A.replace(/[\\/]+$/,"").replace(/\\/g,"/"))):void 0,state:y,memory:S}))break}for(let h of await Me(K(r,"teams"),100)){if(!await $t(K(r,"teams",h)))continue;let g=await Rt(K(r,"teams",h,"TEAM.md"),n.fileChars);if(g&&!l(o.teams,{id:h,files:{"TEAM.md":g}}))break}let c=[];for(let h of await Me(K(r,"agents"),100)){let g=K(r,"agents",h);await $t(g)&&c.push({id:h,dir:g,at:Math.max(0,...await Promise.all([...Ps,".memory-state.json"].map(S=>s(K(g,S)))))})}for(let{id:h,dir:g,at:S}of c.sort((y,A)=>A.at-y.at||y.id.localeCompare(A.id))){let y={};for(let D of Ps){let P=await Rt(K(g,D),n.fileChars);P&&(y[D]=P)}let A=[];if(await $t(K(g,"LOG")))for(let D of(await Me(K(g,"LOG"),400)).filter(P=>/^\d{4}-\d{2}-\d{2}\.md$/.test(P)&&P.slice(0,10)>=i&&P.slice(0,10)<=Ve(e))){let P=await Rt(K(g,"LOG",D),n.logChars);P&&A.push({date:D.slice(0,10),text:P})}let R=(await ht(K(g,".memory-dream.json")))?.last,T=await Hs(g),I=await il(g,n.fileChars);!Object.keys(y).length&&!A.length&&!T&&!I||l(o.agents,{id:h,updatedAt:S?new Date(S).toISOString():null,config:I,state:T,dream:R&&typeof R=="object"?{state:G(R.state,32),startedAt:G(R.startedAt,40),finishedAt:G(R.finishedAt,40),calls:typeof R.calls=="number"?R.calls:void 0,detail:typeof R.detail=="string"?Fe(Ge(R.detail),n.detailChars):void 0}:void 0,files:Object.keys(y).length?y:void 0,log:A.length?A:void 0})}return o}async function Xs(t){let e=(await ht(K(t,"tangu","device.json")))?.deviceId;return typeof e=="string"&&/^[A-Za-z0-9_-]{1,64}$/.test(e)?e:`h${ya("sha256").update(qs()).digest("hex").slice(0,8)}`}var Zs=["sessions","activity"],dn=t=>typeof t=="number"&&Number.isFinite(t)?t:void 0;function al(t,e,n){let r=t?.day===Ve(n)?t:void 0;return Object.fromEntries(Zs.map(s=>[s,dn(r?.[s])??Math.min(Math.max(dn(e[s])??0,Ye(n)),n.getTime())]))}function ll(t,e,n,r,s,i){let o=e?.day===Ve(r)?e:void 0,a={sent:{...t},file:{day:Ve(r)}};for(let l of Zs){let d=l in s&&!i.includes(l)&&!(`${l}Error`in s),f=dn(o?.[l]);d?(a.file[l]=n[l],a.sent[l]=r.getTime()):f!==void 0&&(a.sent[l]=Math.min(dn(t[l])??f,f))}return a}async function cl(t){let{home:e}=t,n=K(e,"tangu"),r=t.now??new Date,s=o=>t.since?.[o]??Ye(r),i=rl(t.engineLogs);return Ge({schema:3,collectedAt:r.toISOString(),app:{version:t.appVersion,platform:process.platform,arch:process.arch,os:Ca(),electron:process.versions.electron??null,node:process.versions.node,locale:Intl.DateTimeFormat().resolvedOptions().locale,timeZone:Intl.DateTimeFormat().resolvedOptions().timeZone,home:Ws(e),cloudUrl:t.cloudUrl},device:{id:await Xs(e),name:qs()},system:await nl(e),config:Xa(await ht(K(e,"config.json"))),agents:await Us(K(n,"agents")),teams:await Us(K(n,"teams")),plugins:{desktop:await js(K(e,"plugins")),engine:await js(K(n,"plugins"))},inventory:{skills:await Me(K(n,"skills")),spaces:await Me(K(e,"spaces")),themes:await Me(K(e,"themes"))},...t.activity?{...await Qa(K(e,"activity"),r,s("activity")),activitySince:new Date(s("activity")).toISOString()}:{},...t.sessions?{...await el(e,r,Ys,s("sessions")),sessionsSince:new Date(s("sessions")).toISOString()}:{},...(typeof t.memory=="function"?t.memory():t.memory)===!0?{memory:await ol(e,r)}:{},...await tl(e,r),runsSince:new Date(Ye(r)).toISOString(),...i?{engine:i}:{}})}function ul(t,e=[]){let n={...t},r=Buffer.from(JSON.stringify(n),"utf8");for(let s of["activity","sessions","memory","runs","engine"]){if(r.length<=$s)break;s in n&&(delete n[s],e.push(s),r=Buffer.from(JSON.stringify({...n,truncated:e}),"utf8"))}return r.length>$s?null:r}async function dl(t,e,n,r=new Date){let s=AbortSignal.timeout(Ra);await t.writeFile(`${e}/${Ve(r)}.json`,n,r.getTime(),s);try{let i=Ve(new Date(r.getTime()-Vs*24*60*6e4));for(let o of await t.walk(s)){let a=/^([^/]+)\/(\d{4}-\d{2}-\d{2})\.json$/.exec(o.key);a&&a[1]===e&&a[2]<i&&await t.rm(o.key,s)}}catch{}}var Qs={mode:"scheduled",intervalHours:24,requestedAt:0};function Qn(t){let e=t&&typeof t=="object"?t:{},n=Number(e.intervalHours),r=Number(e.requestedAt);return{mode:e.mode==="manual"?"manual":"scheduled",intervalHours:Number.isInteger(n)&&n>=1&&n<=720?n:Qs.intervalHours,requestedAt:Number.isFinite(r)&&r>0?r:0}}async function fl(t){try{let e=await fetch(`${t.cloudUrl.replace(/\/+$/,"")}/api/remotesync/diagnostics/policy`,{headers:{Authorization:`Bearer ${t.token}`},signal:AbortSignal.timeout(Da)});return e.status===404?{...Qs}:e.ok?Qn(await e.json()):null}catch{return null}}function ei(t,e={}){let n=e.now??(()=>new Date),r=e.remoteFor??(T=>zt({baseUrl:T.cloudUrl,vault:Bt,getToken:()=>T.token})),s=e.policyFor??fl,i=()=>K(t.homeDir(),"extend-diagnostics.json"),o=()=>{let T=I=>I&&typeof I=="object"?I:{};try{let I=JSON.parse(ba(i(),"utf8"));return{accounts:T(I?.accounts),sent:T(I?.sent)}}catch{return{accounts:{},sent:{}}}},a=()=>o().accounts,l=(T,I,D)=>{let P=o();P.accounts[T]={...P.accounts[T],...I},Object.assign(P.sent,D),wa(t.homeDir(),{recursive:!0});let L=`${i()}.${process.pid}.tmp`;Ea(L,JSON.stringify(P,null,2),{encoding:"utf8",mode:384}),Sa(L,i())},d=()=>{let T=t.readCreds();return T.token&&T.cloudUrl?t.accountId():null},f=()=>{let T=d(),I=T?a()[T]??{}:{},D=Qn(I.policy);return{signedIn:!!T,enabled:I.enabled===!0,activity:I.activity!==!1,sessions:I.sessions??I.enabled!==!0,memory:I.memory??I.enabled!==!0,lastUploadAt:I.lastUploadAt??null,lastError:I.lastError??null,retainDays:Vs,mode:D.mode,intervalHours:D.intervalHours}},m=()=>{try{return Ls(t)?t.diagnosticLogs():null}catch{return null}},c=null,h=new Map,g=async()=>{let T=d();if(!T)return!1;if(c)return c.id===T?c.done:(await c.done,g());let I={...t.readCreds()},D=n(),P=o(),L=P.accounts[T],H=I.cloudUrl.replace(/\/+$/,""),Q=al(L?.file,P.sent[H]??{},D),le=(async()=>{try{let me=await cl({home:t.homeDir(),appVersion:t.appVersion(),cloudUrl:I.cloudUrl,activity:L?.activity!==!1,sessions:L?.sessions===!0,now:D,since:Q,engineLogs:m(),memory:()=>{let E=d()===T?a()[T]:void 0;return E?.enabled===!0&&E.memory===!0}}),ce=await Xs(t.homeDir()),ye=a()[T];if(d()!==T||ye?.enabled!==!0)return!1;if(ye.activity===!1)for(let E of["activity","activityTruncated","activityError","activitySince"])delete me[E];if(ye.sessions!==!0)for(let E of["sessions","sessionsTruncated","sessionsError","sessionsSince"])delete me[E];ye.memory!==!0&&delete me.memory;let He=[],v=ul(me,He);if(!v)throw new Error("snapshot too large");await dl(r(I),ce,v,D),h.delete(T);let C=ll(o().sent[H]??{},L?.file,Q,D,me,He);return l(T,{lastUploadAt:n().getTime(),lastError:void 0,file:C.file},{[H]:C.sent}),t.log(`[forsion-extend] diagnostics uploaded (${v.length} bytes)`),!0}catch(me){h.set(T,n().getTime());let ce=String(me?.message||me).slice(0,300);try{l(T,{lastError:ce})}catch{}return t.log(`[forsion-extend] diagnostics upload failed: ${ce}`),!1}finally{c=null}})();return c={id:T,done:le},le},S=async()=>{try{let T=d();if(!T||a()[T]?.enabled!==!0)return;let I=await s({...t.readCreds()}),D=d()===T?a()[T]:void 0;if(D?.enabled!==!0)return;I&&(I.mode!==D.policy?.mode||I.intervalHours!==D.policy?.intervalHours)&&l(T,{policy:{mode:I.mode,intervalHours:I.intervalHours}}),I&&D.requestSeen===void 0&&l(T,{requestSeen:I.requestedAt});let P=I??{...Qn(D.policy),requestedAt:0},L=P.requestedAt>(D.requestSeen??P.requestedAt),H=D.lastUploadAt??0,Q=!H||P.mode==="scheduled"&&n().getTime()-H>=P.intervalHours*er;if(!L&&!Q||n().getTime()-(h.get(T)??-Rs)<Rs)return;await g()&&L&&l(T,{requestSeen:P.requestedAt})}catch(T){t.log(`[forsion-extend] diagnostics tick failed: ${String(T?.message||T)}`)}},y={ok:!1,error:"untrusted"};t.handle("diagnostics:get",T=>t.isTrustedSender(T)?f():y),t.handle("diagnostics:set",(T,I)=>{if(!t.isTrustedSender(T))return y;let D=d();if(!D)return f();let P={};typeof I?.enabled=="boolean"&&(P.enabled=I.enabled),P.enabled&&(P.requestSeen=void 0),typeof I?.activity=="boolean"&&(P.activity=I.activity),typeof I?.sessions=="boolean"&&(P.sessions=I.sessions),typeof I?.memory=="boolean"&&(P.memory=I.memory);let L=a()[D];for(let H of["sessions","memory"])P[H]!==void 0||L?.[H]!==void 0||(L?.enabled===!0?P[H]=!1:P.enabled&&(P[H]=!0));return l(D,P),P.enabled&&(h.delete(D),S()),f()}),t.handle("diagnostics:uploadNow",async T=>t.isTrustedSender(T)?(f().enabled&&await g(),f()):y);let A=setTimeout(()=>void S(),Ia),R=setInterval(()=>void S(),$a);return A.unref?.(),R.unref?.(),t.log(`[forsion-extend] diagnostics registered${Ls(t)?"":" (host has no diagnosticLogs: snapshots carry no engine log)"}`),Object.assign(()=>{clearTimeout(A),clearInterval(R)},{tick:S})}async function ti(t,e){if(!e)return"";try{let n=await we({base:t,token:e},"POST","/api/auth/handoff",{},5e3);if(n.status===200&&typeof n.json?.code=="string"&&n.json.code)return`code=${encodeURIComponent(n.json.code)}`;if(n.status===404||n.status===405)return`token=${encodeURIComponent(e)}`}catch{}return""}var ml=["membership","credits","storefront"],hl=["monthly","quarterly","yearly"],gl=/^[A-Za-z0-9_-]{1,64}$/;function Ju(t){let e={status:0,error:"untrusted"},n={ok:!1,error:"untrusted"};t.handle("auth:openAccountCenter",async(s,i)=>{if(!t.isTrustedSender(s))return n;let{base:o,token:a}=await t.getCloud();if(!o)return{ok:!1};let l=i&&/^[a-z0-9-]+$/i.test(i)?`#${i}`:"",d=await ti(o,a),f=`${o}/account${d?`?${d}`:""}${l}`;return await t.openExternal(f),{ok:!0}}),t.handle("auth:openPayCenter",async(s,i,o,a)=>{if(!t.isTrustedSender(s))return n;if(i!==void 0&&!ml.includes(i))return{ok:!1,error:"invalid_tab"};if(o!==void 0&&(typeof o!="string"||!gl.test(o)))return{ok:!1,error:"invalid_plan"};if(a!==void 0&&!hl.includes(a))return{ok:!1,error:"invalid_period"};let l=(i??"membership")==="membership"&&o?`&plan=${encodeURIComponent(o)}${a?`&period=${a}`:""}`:"",{base:d,token:f}=await t.getCloud();if(!d)return{ok:!1};let m=await ti(d,f),c=`${d}/pay?tab=${i??"membership"}${l}${m?`&${m}`:""}&redirect=${encodeURIComponent(`${d}/account`)}`;return await t.openExternal(c),{ok:!0}}),t.handle("profile:publicOrigin",async s=>{if(!t.isTrustedSender(s))return n;let{base:i}=await t.getCloud();if(!i)return{ok:!1};try{let o=await fetch(`${i}/account`,{redirect:"manual",signal:AbortSignal.timeout(4e3)});o.body?.cancel().catch(()=>{});let a=o.status>=300&&o.status<400?o.headers.get("location"):null;return a&&/^https?:\/\//i.test(a)?{ok:!0,origin:new URL(a).origin}:{ok:!1}}catch{return{ok:!1}}});let r=()=>t.getCloud();t.handle("account:quota",async s=>{if(!t.isTrustedSender(s))return e;let i=await r();if(!i.token)return{status:401,json:null};try{return await we(i,"GET","/api/token-quota/my",void 0,15e3)}catch(o){return{status:0,json:{detail:String(o?.message||o)}}}}),t.handle("account:useResetCard",async(s,i)=>{if(!t.isTrustedSender(s))return e;let o=await r();if(!o.token)return{status:401,json:null};if(i!==void 0&&i!=="both")return{status:400,json:{error:"invalid_type",detail:`invalid reset card type: ${i}`}};let a=i??"both";try{return await we(o,"POST","/api/token-quota/reset-card/use",{type:a},15e3)}catch(l){return{status:0,json:{detail:String(l?.message||l)}}}}),t.handle("account:bgConvert",async(s,i)=>{if(!t.isTrustedSender(s))return e;let o=await r();if(!o.token)return{status:401,json:null};if(!Number.isInteger(i)||i<1||i>100)return{status:400,json:{error:"invalid_percent"}};try{return await we(o,"POST","/api/token-quota/background/convert",{percent:i},15e3)}catch(a){return{status:0,json:{detail:String(a?.message||a)}}}}),t.handle("account:bgAutoMain",async(s,i)=>{if(!t.isTrustedSender(s))return e;let o=await r();if(!o.token)return{status:401,json:null};if(typeof i!="boolean")return{status:400,json:{error:"invalid_request"}};try{return await we(o,"POST","/api/token-quota/background/auto-main",{enabled:i},15e3)}catch(a){return{status:0,json:{detail:String(a?.message||a)}}}}),t.handle("feedback:submit",async(s,i)=>{if(!t.isTrustedSender(s))return n;let{base:o,token:a}=await t.getCloud();if(!o||!a)return{ok:!1,error:"not-logged-in"};let l=(i?.description||"").trim();if(!l)return{ok:!1,error:"empty"};if(l.length>1e4)return{ok:!1,error:"description-too-long"};let d=[],f=!1;if(i?.sessionLogJson){let m=Buffer.from(i.sessionLogJson,"utf8");if(m.length>5*1024*1024)return{ok:!1,error:"attachment-too-large"};d.push({filename:i.sessionLogName||"tangu-session.json",mime_type:"application/json",size:m.length,data_base64:m.toString("base64")})}try{let m=await fetch(`${o}/api/feedback`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`},body:JSON.stringify({description:l,attachments:d}),signal:AbortSignal.timeout(2e4)});if(!m.ok){let h=`HTTP ${m.status}`;try{h=(await m.json())?.detail||h}catch{}return{ok:!1,error:h}}return{ok:!0,id:(await m.json().catch(()=>({})))?.id??null,attachmentSkipped:f}}catch(m){return{ok:!1,error:m?.message||String(m)}}}),t.handle("cloud:fetch",async(s,i)=>{if(!t.isTrustedSender(s))return{status:0,error:"untrusted"};let o=i??{},a=typeof o.path=="string"?o.path:"",l=Math.min(12e4,Math.max(1e3,Number(o.timeoutMs)||15e3)),d=typeof o.method=="string"?o.method.toUpperCase():"GET";if(!/^(GET|POST|PUT|PATCH|DELETE)$/.test(d))return{status:0,error:"bad_method"};if(!a.startsWith("/"))return{status:0,error:"bad_path"};let{base:f,token:m}=await t.getCloud();if(!String(f||""))return{status:0,error:"no_cloud_url"};let c=Ht(f,a);if(!c)return{status:0,error:"bad_path"};if(!m)return{status:401,error:"not_signed_in"};let h=o.body!==void 0&&d!=="GET"&&d!=="DELETE",g=new AbortController,S=setTimeout(()=>g.abort(),l);try{let y=await fetch(c,{method:d,headers:{Authorization:`Bearer ${m}`,...h?{"Content-Type":"application/json"}:{}},body:h?JSON.stringify(o.body):void 0,signal:g.signal});return{status:y.status,json:await y.json().catch(()=>null)}}catch(y){return{status:0,error:String(y?.message||y)}}finally{clearTimeout(S)}}),dr(t),t.log("[forsion-extend] cloud account handlers registered"),wn(t)?bn(t):t.log("[forsion-extend] host has no Connect seam (projectsRoot / transpileForServe / mimeOf / setPreviewHooks); Connect stays with the host"),En(t)?_n(t):t.log("[forsion-extend] host has no remote-sync seam (registerRemoteSyncBackend / readCreds); penzor stays with the host"),vn(t)?xn(t):t.log("[forsion-extend] host has no account seam (accountCommit / accountClear / \u2026); account core stays with the host"),Yn(t)?Gn(t):t.log("[forsion-extend] host has no amadeus seam (setAmadeusSyncFactory); cloud sync stays with the host"),Kn(t)?Xn(t):t.log("[forsion-extend] host has no unit seam (setUnitHubFactory); the device channel stays with the host"),Gs(t)?ei(t):t.log("[forsion-extend] host has no diagnostics seam (homeDir / readCreds / accountId / appVersion); diagnostics upload is off")}export{Ir as ACCOUNT_SEAM,ws as AMADEUS_SEAM,pn as CONNECT_MAX_FILES,mr as CONNECT_MAX_FILE_BYTES,hr as CONNECT_MAX_TOTAL_BYTES,Bt as DIAGNOSTICS_VAULT,Sr as FORSION_CONNECT_LOCAL_SDK,hl as PAY_PERIODS,ml as PAY_TABS,kr as PENZOR_MAX_FILE,fe as SYNC_IPC,Es as UNIT_SEAM,Tt as UnitCapsReporter,Ct as UnitHost,we as cloudJson,gr as collectProjectFiles,en as conflictCopyPath,$o as conflictCopyVariant,Ar as createAccountCloud,bs as createAmadeusCloud,zt as createPenzorRemote,_s as createUnitHub,Sn as expectedPartsOf,Te as forsionAccountId,Tr as forsionRefreshToken,wt as forsionWhoami,vn as hasAccountHost,Yn as hasAmadeusHost,wn as hasConnectHost,En as hasRemoteSyncHost,Kn as hasUnitHost,br as makePreviewProxy,yr as readConnectMeta,xn as registerAccount,Gn as registerAmadeus,Ju as registerCloud,bn as registerConnect,_n as registerPenzor,Xn as registerUnit,Cr as shouldRefreshToken,Ss as streamWorthy,gs as stripConflictSuffix,Do as textFingerprint,xr as tokenAgeMs,Di as tokenRemainingMs,wr as writeConnectMeta};
211
240
  /*! Bundled license information:
212
241
 
213
242
  chokidar/index.js:
214
243
  (*! chokidar - MIT License (c) 2012 Paul Miller (paulmillr.com) *)
244
+
245
+ smol-toml/dist/date.js:
246
+ smol-toml/dist/error.js:
247
+ smol-toml/dist/primitive.js:
248
+ smol-toml/dist/util.js:
249
+ smol-toml/dist/extract.js:
250
+ smol-toml/dist/struct.js:
251
+ smol-toml/dist/parse.js:
252
+ smol-toml/dist/stringify.js:
253
+ smol-toml/dist/index.js:
254
+ (*!
255
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
256
+ * SPDX-License-Identifier: BSD-3-Clause
257
+ *
258
+ * Redistribution and use in source and binary forms, with or without
259
+ * modification, are permitted provided that the following conditions are met:
260
+ *
261
+ * 1. Redistributions of source code must retain the above copyright notice, this
262
+ * list of conditions and the following disclaimer.
263
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
264
+ * this list of conditions and the following disclaimer in the
265
+ * documentation and/or other materials provided with the distribution.
266
+ * 3. Neither the name of the copyright holder nor the names of its contributors
267
+ * may be used to endorse or promote products derived from this software without
268
+ * specific prior written permission.
269
+ *
270
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
271
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
272
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
273
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
274
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
275
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
276
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
277
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
278
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
279
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
280
+ *)
215
281
  */