sliccy 6.99.8 → 6.99.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (95) hide show
  1. package/dist/node-server/_shared/tray-signaling.d.ts +2 -0
  2. package/dist/node-server/_shared/tray-signaling.d.ts.map +1 -1
  3. package/dist/ui/.vite/manifest.json +116 -116
  4. package/dist/ui/assets/{account-store-BHr78r-q.js → account-store-CYMEkNNe.js} +1 -1
  5. package/dist/ui/assets/{account-store-DhN2-vXh.js → account-store-ktNi3pcb.js} +1 -1
  6. package/dist/ui/assets/{adobe-C-61Gw8p.js → adobe-B9bqpVA6.js} +1 -1
  7. package/dist/ui/assets/{adobe-BgNEArvI.js → adobe-D2l8vW4Z.js} +1 -1
  8. package/dist/ui/assets/{agent-panels-DwH4FR7k.js → agent-panels-BFjOOqNh.js} +1 -1
  9. package/dist/ui/assets/{apply-layout-DWTxIKYs.js → apply-layout-C9atHx_R.js} +1 -1
  10. package/dist/ui/assets/{apps-CDrFK--r.js → apps-bxajdBmb.js} +1 -1
  11. package/dist/ui/assets/{azure-openai-BCHBeybM.js → azure-openai-B7WXqTuL.js} +1 -1
  12. package/dist/ui/assets/{azure-openai-C1aiXjjQ.js → azure-openai-DbxXj8zK.js} +1 -1
  13. package/dist/ui/assets/{cerebras-X5XOc6kT.js → cerebras-CUwJMnYY.js} +1 -1
  14. package/dist/ui/assets/{cerebras-BWY_xN7G.js → cerebras-CfOSdVHz.js} +1 -1
  15. package/dist/ui/assets/{connect-surface-BqfnkTNQ.js → connect-surface-BIhkXU-D.js} +1 -1
  16. package/dist/ui/assets/{fs-qMMHgiDM.js → fs-CvM7tq2t.js} +2 -2
  17. package/dist/ui/assets/{fs-tsCmhLpU.js → fs-DUneCuZW.js} +1 -1
  18. package/dist/ui/assets/git-config-Bdgu8kD2.js +7 -0
  19. package/dist/ui/assets/git-config-D2u6LGfT.js +5 -0
  20. package/dist/ui/assets/{github-CLAenO0m.js → github-CHdABf-3.js} +2 -2
  21. package/dist/ui/assets/{github-TenSKQL4.js → github-DvD4qs-U.js} +1 -1
  22. package/dist/ui/assets/{github-copilot-CvxZKmtr.js → github-copilot-BB3QwaLu.js} +1 -1
  23. package/dist/ui/assets/{github-copilot-B-pJOojX.js → github-copilot-K0sRIoSq.js} +1 -1
  24. package/dist/ui/assets/{github-install-CSrLhUFy.js → github-install-vA3zHPFd.js} +1 -1
  25. package/dist/ui/assets/{github-zip-KaxQyKKS.js → github-zip-C7KlmYg5.js} +1 -1
  26. package/dist/ui/assets/{js-realm-worker-CXQhPnY0.js → js-realm-worker-CJBsByLD.js} +1 -1
  27. package/dist/ui/assets/{kernel-worker-BpjE-7BD.js → kernel-worker-DL4H-NBi.js} +27 -27
  28. package/dist/ui/assets/{local-llm-onyoDvHB.js → local-llm-BxbXSRY1.js} +1 -1
  29. package/dist/ui/assets/{local-llm-D5B7umV1.js → local-llm-DFV3ffPY.js} +1 -1
  30. package/dist/ui/assets/{main-DjAHuk3R.js → main-B6Og2ks7.js} +3 -3
  31. package/dist/ui/assets/{mount-Cr-j5Qvu.js → mount-CqTvny3n.js} +2 -2
  32. package/dist/ui/assets/{mount-BcopcDTf.js → mount-iK3BWJwS.js} +1 -1
  33. package/dist/ui/assets/{mount-recovery-DnWemQVb.js → mount-recovery-BNtMtfx7.js} +1 -1
  34. package/dist/ui/assets/{new-session-DagG-ZZy.js → new-session-Dq10ablA.js} +2 -2
  35. package/dist/ui/assets/{oauth-bootstrap-CDgbPc25.js → oauth-bootstrap-BriIqrT5.js} +2 -2
  36. package/dist/ui/assets/{onboarding-orchestrator-DwBmySbw.js → onboarding-orchestrator-Cd0lVIve.js} +1 -1
  37. package/dist/ui/assets/{openai-codex-CFHJKZXk.js → openai-codex-CrPEnCvZ.js} +1 -1
  38. package/dist/ui/assets/{openai-codex-B8nK05u1.js → openai-codex-D50qgZ4K.js} +1 -1
  39. package/dist/ui/assets/{openrouter-brhW7dHW.js → openrouter-0FxeBdE5.js} +1 -1
  40. package/dist/ui/assets/{openrouter-BQXiRTOg.js → openrouter-Dhsi_ko9.js} +1 -1
  41. package/dist/ui/assets/{openrouter-oauth-DuIS_qNZ.js → openrouter-oauth-CIzZhpZg.js} +1 -1
  42. package/dist/ui/assets/{openrouter-oauth-DQ7iHoUX.js → openrouter-oauth-CpKt1MA8.js} +1 -1
  43. package/dist/ui/assets/{panel-rpc-handlers-BBgO_HM3.js → panel-rpc-handlers-DRmkHDcC.js} +2 -2
  44. package/dist/ui/assets/{panelize-shell-DpfBeau6.js → panelize-shell-B1SCUwME.js} +1 -1
  45. package/dist/ui/assets/{provider-D1IQTDOu.js → provider-CHFkYrg5.js} +1 -1
  46. package/dist/ui/assets/{provider-VbLD3Pa_.js → provider-DR7pS55u.js} +2 -2
  47. package/dist/ui/assets/{provider-settings-D24NB2-U.js → provider-settings-QhXeD8p1.js} +1 -1
  48. package/dist/ui/assets/provider-store-access-BWBUxNsZ.js +1 -0
  49. package/dist/ui/assets/provider-store-access-WTMg_H8y.js +1 -0
  50. package/dist/ui/assets/{providers-PfyMAay1.js → providers-CMHd9MFS.js} +1 -1
  51. package/dist/ui/assets/{providers-CZ_sFfrt.js → providers-D-6LGcDk.js} +2 -2
  52. package/dist/ui/assets/{quick-llm-drlxgkUg.js → quick-llm-CPywyeCK.js} +1 -1
  53. package/dist/ui/assets/{recovery-screen-BccxAWe7.js → recovery-screen-CmRYQ0rB.js} +1 -1
  54. package/dist/ui/assets/{redirect-uri-AfF6uLvV.js → redirect-uri-C8-Woku_.js} +1 -1
  55. package/dist/ui/assets/{run-BIKu737n.js → run-CxkS2v3b.js} +1 -1
  56. package/dist/ui/assets/{setup-feature-flags-remote-Dxg6pIkQ.js → setup-feature-flags-remote-bBB7gD8w.js} +1 -1
  57. package/dist/ui/assets/sidecar-repair-CwI_pMMe.js +1 -0
  58. package/dist/ui/assets/{skills-Cc4T1Cfp.js → skills-D0atjE-P.js} +1 -1
  59. package/dist/ui/assets/slicc-version-Bc9r0Wca.js +1 -0
  60. package/dist/ui/assets/{state-B8PB53C0.js → state-o12tamuF.js} +1 -1
  61. package/dist/ui/assets/{store-SXMbC-35.js → store-BT0FKeS5.js} +1 -1
  62. package/dist/ui/assets/{store-BsTL1Wgg.js → store-BUjz66P2.js} +1 -1
  63. package/dist/ui/assets/{sudo-Blo41kLx.js → sudo-Cb_jI2eu.js} +1 -1
  64. package/dist/ui/assets/{sync-dialog-yRY0wRJj.js → sync-dialog-CV7-2aVT.js} +1 -1
  65. package/dist/ui/assets/{upgrade-detection-DqD1aedt.js → upgrade-detection-CNu3KNsM.js} +1 -1
  66. package/dist/ui/assets/{voice-reply-B-I-XncI.js → voice-reply-BFImQhAG.js} +1 -1
  67. package/dist/ui/assets/{wc-attach-DgJVZRem.js → wc-attach-d-lHwJPz.js} +2 -2
  68. package/dist/ui/assets/{wc-extension-b7ONOPn6.js → wc-extension-p4la3vtz.js} +2 -2
  69. package/dist/ui/assets/{wc-float-label-d3I12c8W.js → wc-float-label-Dtx9Io98.js} +1 -1
  70. package/dist/ui/assets/{wc-floatbar-online-CFeU9jju.js → wc-floatbar-online-pmlV024x.js} +1 -1
  71. package/dist/ui/assets/{wc-follower-BU7l80Bf.js → wc-follower-2DQ7Q3wG.js} +3 -3
  72. package/dist/ui/assets/{wc-follower-oauth-DIH7qpbt.js → wc-follower-oauth-BXi7U3s5.js} +1 -1
  73. package/dist/ui/assets/{wc-live-DL5TcdQ7.js → wc-live-BfpVK1Kd.js} +6 -6
  74. package/dist/ui/assets/{wc-nav-DjOpEDo-.js → wc-nav-BNZDsOwH.js} +2 -2
  75. package/dist/ui/assets/{wc-onboarding-BeunqMQZ.js → wc-onboarding-BinmjNb5.js} +2 -2
  76. package/dist/ui/assets/{wc-placeholder-mYgmrH75.js → wc-placeholder-CPP2DyEf.js} +3 -3
  77. package/dist/ui/assets/{wc-settings-JfsyJgL9.js → wc-settings-ChigIGe8.js} +3 -3
  78. package/dist/ui/assets/{wc-shell-B7yZ6nn6.js → wc-shell-C8rORiLz.js} +2 -2
  79. package/dist/ui/assets/{wc-shortcut-config-CRticSXA.js → wc-shortcut-config-CsiYOxaR.js} +1 -1
  80. package/dist/ui/assets/{wc-sprinkles-D-DWMPsX.js → wc-sprinkles-DwSBE-SU.js} +2 -2
  81. package/dist/ui/assets/{wc-transcript-export-DVjtNvuR.js → wc-transcript-export-CjvhPpom.js} +2 -2
  82. package/dist/ui/assets/{wc-tray-D6joGkUe.js → wc-tray-g89TbAbd.js} +2 -2
  83. package/dist/ui/assets/welcome-detection-BHAB2hpt.js +1 -0
  84. package/dist/ui/assets/{xai-grok-DHRw8xLj.js → xai-grok-CaAyB00w.js} +1 -1
  85. package/dist/ui/assets/{xai-grok-DIhtpBYR.js → xai-grok-FS5CaRb2.js} +1 -1
  86. package/dist/ui/index.html +3 -3
  87. package/dist/ui/packages/webapp/index.html +3 -3
  88. package/package.json +1 -1
  89. package/dist/ui/assets/git-config-DA8M5e8O.js +0 -7
  90. package/dist/ui/assets/git-config-DLJIrKjL.js +0 -5
  91. package/dist/ui/assets/provider-store-access-CFkv-yrf.js +0 -1
  92. package/dist/ui/assets/provider-store-access-Dh0tBZso.js +0 -1
  93. package/dist/ui/assets/sidecar-repair-DCvPqdWE.js +0 -1
  94. package/dist/ui/assets/slicc-version-CzfOvAya.js +0 -1
  95. package/dist/ui/assets/welcome-detection-CEmFgOCI.js +0 -1
@@ -1,4 +1,4 @@
1
- import{C as e,I as t,d as n,f as r}from"./account-store-BHr78r-q.js";import{n as i}from"./main-DjAHuk3R.js";var a=`slicc_cloud_model_catalog`,o=`adobe`;function s(t){if(t===o)return!1;let n=e(t);return!(n.hidden||n.onOAuthLoginIntercepted)}function c(){try{let e=r().map(e=>({providerId:e.providerId,providerName:e.providerName,models:e.models.map(e=>({id:e.id,name:e.name}))}));localStorage.setItem(a,JSON.stringify(e))}catch{}}async function l(r){for(;r.firstChild;)r.removeChild(r.firstChild);r.className=`connect-surface`;let a=document.createElement(`h1`);a.className=`connect-surface__title`,a.textContent=`Connect providers`,r.appendChild(a);let l=document.createElement(`p`);l.className=`connect-surface__desc`,l.textContent=`Log in or add API keys for the providers your cone should use, then click Done to return to the dashboard.`,r.appendChild(l);let u=document.createElement(`div`);u.className=`connect-surface__accounts`,r.appendChild(u);function d(){for(;u.firstChild;)u.removeChild(u.firstChild);let r=n().filter(e=>e.providerId!==o);if(r.length===0){let e=document.createElement(`div`);e.className=`connect-surface__empty`,e.textContent=`No providers connected yet.`,u.appendChild(e)}else{let n=document.createElement(`div`);n.className=`connect-surface__accounts-list`;for(let i of r){let r=e(i.providerId),a=document.createElement(`div`);a.className=`connect-surface__account-row`;let o=document.createElement(`div`);o.className=`connect-surface__account-info`;let s=document.createElement(`div`);s.className=`connect-surface__account-name`,s.textContent=r.name,o.appendChild(s);let l=document.createElement(`div`);l.className=`connect-surface__account-detail`,l.textContent=i.userName?i.userName:i.accessToken?`Logged in`:i.apiKey?`API key set`:`No credentials`,o.appendChild(l),a.appendChild(o);let u=document.createElement(`button`);u.className=`connect-surface__remove-btn`,u.textContent=`Remove`,u.onclick=async()=>{await t(i.providerId),c(),d()},a.appendChild(u),n.appendChild(a)}u.appendChild(n)}let a=document.createElement(`button`);a.className=`connect-surface__add-btn`,a.textContent=r.length===0?`Add provider`:`Manage providers`,a.onclick=async()=>{await i({startInAddAccount:!0,providerFilter:s})&&(c(),d())},u.appendChild(a)}d(),c();let f=document.createElement(`div`);f.className=`connect-surface__footer`;let p=document.createElement(`button`);if(p.className=`connect-surface__done-btn`,p.textContent=`Done — return to dashboard`,p.onclick=()=>{c(),window.close()},f.appendChild(p),r.appendChild(f),!document.getElementById(`connect-surface-style`)){let e=document.createElement(`style`);e.id=`connect-surface-style`,e.textContent=`
1
+ import{C as e,I as t,d as n,f as r}from"./account-store-CYMEkNNe.js";import{n as i}from"./main-B6Og2ks7.js";var a=`slicc_cloud_model_catalog`,o=`adobe`;function s(t){if(t===o)return!1;let n=e(t);return!(n.hidden||n.onOAuthLoginIntercepted)}function c(){try{let e=r().map(e=>({providerId:e.providerId,providerName:e.providerName,models:e.models.map(e=>({id:e.id,name:e.name}))}));localStorage.setItem(a,JSON.stringify(e))}catch{}}async function l(r){for(;r.firstChild;)r.removeChild(r.firstChild);r.className=`connect-surface`;let a=document.createElement(`h1`);a.className=`connect-surface__title`,a.textContent=`Connect providers`,r.appendChild(a);let l=document.createElement(`p`);l.className=`connect-surface__desc`,l.textContent=`Log in or add API keys for the providers your cone should use, then click Done to return to the dashboard.`,r.appendChild(l);let u=document.createElement(`div`);u.className=`connect-surface__accounts`,r.appendChild(u);function d(){for(;u.firstChild;)u.removeChild(u.firstChild);let r=n().filter(e=>e.providerId!==o);if(r.length===0){let e=document.createElement(`div`);e.className=`connect-surface__empty`,e.textContent=`No providers connected yet.`,u.appendChild(e)}else{let n=document.createElement(`div`);n.className=`connect-surface__accounts-list`;for(let i of r){let r=e(i.providerId),a=document.createElement(`div`);a.className=`connect-surface__account-row`;let o=document.createElement(`div`);o.className=`connect-surface__account-info`;let s=document.createElement(`div`);s.className=`connect-surface__account-name`,s.textContent=r.name,o.appendChild(s);let l=document.createElement(`div`);l.className=`connect-surface__account-detail`,l.textContent=i.userName?i.userName:i.accessToken?`Logged in`:i.apiKey?`API key set`:`No credentials`,o.appendChild(l),a.appendChild(o);let u=document.createElement(`button`);u.className=`connect-surface__remove-btn`,u.textContent=`Remove`,u.onclick=async()=>{await t(i.providerId),c(),d()},a.appendChild(u),n.appendChild(a)}u.appendChild(n)}let a=document.createElement(`button`);a.className=`connect-surface__add-btn`,a.textContent=r.length===0?`Add provider`:`Manage providers`,a.onclick=async()=>{await i({startInAddAccount:!0,providerFilter:s})&&(c(),d())},u.appendChild(a)}d(),c();let f=document.createElement(`div`);f.className=`connect-surface__footer`;let p=document.createElement(`button`);if(p.className=`connect-surface__done-btn`,p.textContent=`Done — return to dashboard`,p.onclick=()=>{c(),window.close()},f.appendChild(p),r.appendChild(f),!document.getElementById(`connect-surface-style`)){let e=document.createElement(`style`);e.id=`connect-surface-style`,e.textContent=`
2
2
  .connect-surface {
3
3
  padding: 2rem;
4
4
  max-width: 560px;
@@ -1,2 +1,2 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/dist-RekgwRC0.js","assets/rolldown-runtime-Dd_uD5pT.js","assets/safe-buffer-iah92gQe.js","assets/dist-BmTb9jmr.js","assets/backend-hostfs-Com-zF5W.js","assets/api-endpoint-GRCyib6X.js","assets/types-idfTVsM8.js","assets/mount-Cr-j5Qvu.js","assets/preload-helper-Czpn1I53.js","assets/mime-types-ugOWOUZ9.js","assets/base64-DpPqYZJF.js","assets/src-CAWTvdAa.js","assets/proxied-fetch-BGeNrvQ4.js","assets/runtime-env-Dlaokqg1.js","assets/fetch-body-D2PwksUW.js","assets/runtime-env-E-i2SW1s.js","assets/mount-table-store-dY2IfQ5S.js","assets/mount-bridge-client-DZE6sHdr.js","assets/port-bridge-client-BhmNRlRv.js","assets/logger-DDBAeTLF.js"])))=>i.map(i=>d[i]);
2
- import{n as e}from"./rolldown-runtime-Dd_uD5pT.js";import{t}from"./preload-helper-Czpn1I53.js";import{t as n}from"./logger-DDBAeTLF.js";import{n as r,r as i}from"./tool-ui-DfXu6quJ.js";import{a,i as o,n as s,r as c,t as l}from"./path-utils-DNJG-zQf.js";import{t as u}from"./types-idfTVsM8.js";import{t as d}from"./virtual-device-paths-9EXC9iPp.js";import{t as ee}from"./picker-approval-D89YhXsA.js";import{i as f,r as p,t as m}from"./mount-picker-popup-Bc3ca2Vl.js";import{a as te,i as h,n as g,t as _}from"./mount-table-store-dY2IfQ5S.js";var v=n(`fs-watcher`),ne=0;function re(e,t){return t===`/`||e===t||e.startsWith(t+`/`)}var y=class{registrations=new Map;watch(e,t,n){let r=`fsw-${++ne}`;return this.registrations.set(r,{id:r,basePath:e,filter:t,callback:n}),v.debug(`Watch registered`,{id:r,basePath:e}),()=>{this.registrations.delete(r),v.debug(`Watch unregistered`,{id:r})}}notify(e){if(e.length!==0)for(let[,t]of this.registrations){let n=e.filter(e=>re(e.path,t.basePath)&&t.filter(e.path));if(n.length>0)try{t.callback(n)}catch(e){v.error(`Watch callback error`,{id:t.id,error:e instanceof Error?e.message:String(e)})}}}dispose(){this.registrations.clear(),v.debug(`All watchers disposed`)}get size(){return this.registrations.size}},b=n(`mount-index`),x=400,ie=2e6,ae=`SLICC_MOUNT_INDEX_MAX_DEPTH`,oe=`SLICC_MOUNT_INDEX_MAX_ENTRIES`,S=256,C=class extends Error{cause;constructor(e,t){super(e),this.name=`MountIndexAbortError`,this.cause=t}};function se(e){let t=e.map(([e,t])=>`${e}\u0000${t.kind}`).sort(),n=t.length>S?t.slice(0,S):t;return`${t.length}\u0001${n.join(``)}`}async function ce(e,t){let n=e.isSameEntry;if(typeof n!=`function`)return!1;try{return await n.call(e,t)}catch{return!1}}function w(e,t){return e instanceof Map?e.get(t):e[t]}function le(e){let t=e.trim();if(t===``)return;let n=Number(t);if(!(!Number.isInteger(n)||n<=0))return n}function T(e,t,n){let r=w(e,t);if(r===void 0||r.trim()===``)return n;let i=le(r);return i===void 0?(b.warn(`Ignoring invalid ${t}; expected a positive integer, using default`,{value:r,fallback:n}),n):i}function E(e){return{maxDepth:T(e,ae,x),maxEntries:T(e,oe,ie)}}var D=class{mounts=new Map;listeners=new Set;registerMount(e,t,n=E({})){this.mounts.get(e)?.abortController?.abort();let r=new AbortController,i={handle:t,state:{status:`pending`,indexed:0},files:new Set,directories:new Set,abortController:r,limits:n};this.mounts.set(e,i),this.notifyListeners(),this.indexMount(e,i,r.signal)}unregisterMount(e){let t=this.mounts.get(e);t&&(t.abortController?.abort(),this.mounts.delete(e),this.notifyListeners())}async refreshMount(e,t){let n=this.mounts.get(e);if(!n)throw Error(`No mount at ${e}`);n.abortController?.abort();let r=new AbortController;n.abortController=r,n.state={status:`pending`,indexed:0},n.files.clear(),n.directories.clear(),t&&(n.limits=t),this.notifyListeners(),await this.indexMount(e,n,r.signal)}isReady(e){return this.mounts.get(e)?.state.status===`ready`}isAnyIndexing(){for(let e of this.mounts.values())if(e.state.status===`indexing`||e.state.status===`pending`)return!0;return!1}dispose(){for(let e of this.mounts.values())e.abortController?.abort();this.mounts.clear(),this.listeners.clear()}getState(e){return this.mounts.get(e)?.state}getFiles(e,t){let n=this.mounts.get(e);if(n?.state.status!==`ready`)return;if(!t)return[...n.files];let r=[];for(let e of n.files)t(e)&&r.push(e);return r}getDirectoryEntries(e,t){let n=this.mounts.get(e);if(n?.state.status!==`ready`)return;let r=t===`/`?`/`:t+`/`,i=new Map;for(let e of n.files){if(!e.startsWith(r))continue;let t=e.slice(r.length);t.includes(`/`)||i.set(t,`file`)}for(let e of n.directories){if(!e.startsWith(r))continue;let t=e.slice(r.length);t.includes(`/`)||i.set(t,`directory`)}return[...i.entries()].map(([e,t])=>({name:e,type:t}))}hasPath(e,t){let n=this.mounts.get(e);if(n?.state.status===`ready`)return n.files.has(t)||n.directories.has(t)}notifyWrite(e){let t=this.findMountForPath(e);if(!t)return;let n=this.mounts.get(t);if(n?.state.status!==`ready`)return;n.files.add(e);let r=e;for(;r!==t;){let e=r.lastIndexOf(`/`);if(e<=0)break;r=r.slice(0,e)||`/`,r.length>=t.length&&n.directories.add(r)}}notifyDelete(e){let t=this.findMountForPath(e);if(!t)return;let n=this.mounts.get(t);if(n?.state.status!==`ready`)return;n.files.delete(e),n.directories.delete(e);let r=e+`/`;for(let e of n.files)e.startsWith(r)&&n.files.delete(e);for(let e of n.directories)e.startsWith(r)&&n.directories.delete(e)}notifyRename(e,t){let n=this.findMountForPath(e);if(!n)return;let r=this.mounts.get(n);if(r?.state.status===`ready`){if(r.files.has(e)){r.files.delete(e),r.files.add(t);return}if(r.directories.has(e)){r.directories.delete(e),r.directories.add(t);let n=e+`/`,i=t+`/`;for(let e of[...r.files])e.startsWith(n)&&(r.files.delete(e),r.files.add(i+e.slice(n.length)));for(let e of[...r.directories])e.startsWith(n)&&(r.directories.delete(e),r.directories.add(i+e.slice(n.length)))}}}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}findMountForPath(e){let t;for(let n of this.mounts.keys())(e===n||e.startsWith(n+`/`))&&(!t||n.length>t.length)&&(t=n);return t}notifyListeners(){for(let e of this.listeners)try{e()}catch{}}async indexMount(e,t,n){t.state={status:`indexing`,indexed:0},this.notifyListeners();try{if(await this.walkHandle(e,t.handle,t,n),n.aborted)return;t.state={status:`ready`,indexed:t.files.size+t.directories.size,total:t.files.size+t.directories.size},t.abortController=null,b.info(`Mount indexed`,{path:e,files:t.files.size,directories:t.directories.size})}catch(r){if(n.aborted)return;let i=r instanceof Error?r.message:String(r),a=r instanceof C?r.cause:`indexing-error`;t.state={status:`error`,indexed:0,error:i,abortCause:a},b.error(`Mount indexing failed`,{path:e,error:i,abortCause:a})}this.notifyListeners()}async walkHandle(e,t,n,r,i=0,a=new Map){if(r.aborted)return;this.enforceWalkBounds(i,n),n.directories.add(e);let o=await this.readChildren(t,r,n);if(r.aborted)return;let s=await this.confirmNoCycle(e,t,o,a),c=this.pushAncestor(a,s,e,t);try{await this.walkChildren(e,o,n,r,i,a)}finally{this.popAncestor(a,s,c)}}enforceWalkBounds(e,t){if(e>t.limits.maxDepth)throw new C(`mount indexing aborted: directory nesting exceeded ${t.limits.maxDepth} levels`,`depth-exceeded`);if(t.directories.size+t.files.size>=t.limits.maxEntries)throw new C(`mount indexing aborted: exceeded ${t.limits.maxEntries} entries`,`entries-exceeded`)}async readChildren(e,t,n){let r=e,i=[];for await(let e of r){if(t.aborted)break;if(n.directories.size+n.files.size+i.length>=n.limits.maxEntries)throw new C(`mount indexing aborted: exceeded ${n.limits.maxEntries} entries`,`entries-exceeded`);i.push(e)}return i}async confirmNoCycle(e,t,n,r){let i=se(n),a=r.get(i);if(a){for(let n of a)if(await ce(n.handle,t))throw new C(`mount indexing aborted: self-referential mount cycle detected at ${e} (re-exposes ${n.path})`,`cycle-detected`)}return i}pushAncestor(e,t,n,r){let i=e.get(t);return i||(i=[],e.set(t,i)),i.push({path:n,handle:r,signature:t}),i}popAncestor(e,t,n){n.pop(),n.length===0&&e.delete(t)}async walkChildren(e,t,n,r,i,a){for(let[o,s]of t){if(r.aborted)return;let t=e===`/`?`/${o}`:`${e}/${o}`;s.kind===`file`?(n.files.add(t),n.state.indexed++):s.kind===`directory`&&await this.walkHandle(t,s,n,r,i+1,a),n.state.indexed%500==0&&(this.notifyListeners(),await new Promise(e=>setTimeout(e,0)))}}},O={[d]:{stat:()=>({type:`file`,size:0,mtime:0,ctime:0}),read:e=>(e?.encoding??`utf-8`)===`utf-8`?``:new Uint8Array,readText:()=>``,write:()=>{}}},k=[`/tmp/`],A=class{vfs;allowedPrefixes;readOnlyPrefixes;readGrantPatterns=[];writeEnforcement;constructor(e,t,n=[],r=`hard`){this.vfs=e;let i=e=>{let t=s(e);return t.endsWith(`/`)?t:t+`/`};this.allowedPrefixes=t.map(i),this.readOnlyPrefixes=n.map(i),this.writeEnforcement=r}getAllPrefixes(){let e=this.vfs.listMounts().map(e=>e.endsWith(`/`)?e:e+`/`);return[...this.allowedPrefixes,...this.readOnlyPrefixes,...e,...k]}setReadGrants(e){this.readGrantPatterns=[];for(let t of new Set(e))this.addReadGrant(t)}addReadGrant(e){let t=e.split(`/`),n=[];for(let e=1;e<t.length;e++)n.push(c(t.slice(0,e).join(`/`)||`/`));this.readGrantPatterns.push({pattern:e,regex:c(e),ancestorRegexes:n})}matchesReadGrant(e){return this.readGrantPatterns.some(t=>t.regex.test(e))}leadsToReadGrant(e){return this.readGrantPatterns.some(t=>t.ancestorRegexes.some(t=>t.test(e)))}isAllowed(e){let t=s(e),n=this.getAllPrefixes();return this.matchesReadGrant(t)||this.leadsToReadGrant(t)||n.some(e=>t===e.slice(0,-1)||t.startsWith(e)||t===`/`||e.startsWith(t+`/`))}isAllowedStrict(e){let t=s(e),n=this.getAllPrefixes();return this.matchesReadGrant(t)||n.some(e=>t===e.slice(0,-1)||t.startsWith(e))}isWritable(e){let t=s(e);return[...this.allowedPrefixes,...k].some(e=>t===e.slice(0,-1)||t.startsWith(e))}canWrite(e){return this.isWritable(e)}checkWrite(e){if(this.writeEnforcement!==`sudo-delegated`&&!this.isWritable(e))throw new u(`EACCES`,`permission denied`,s(e))}async resolveAndCheckRead(e){try{let t=await this.vfs.realpath(e);if(!this.isAllowedStrict(t))throw new u(`ENOENT`,`no such file or directory`,s(e));return t}catch(t){throw t instanceof u?t:new u(`ENOENT`,`no such file or directory`,s(e))}}async resolveAndCheckWrite(e){try{let t=await this.vfs.realpath(e);if(!this.isWritable(t)&&!this.isSymlinkEscapeAllowed(t))throw new u(`EACCES`,`permission denied`,s(e));return t}catch(t){throw t instanceof u?t:new u(`EACCES`,`permission denied`,s(e))}}isSymlinkEscapeAllowed(e){return!1}async checkParentRealpathEscape(e){let t=this.vfs.dirname(e),n=this.vfs.basename(e),r;try{r=await this.vfs.realpath(t)}catch(e){if(e instanceof u&&e.code===`EACCES`)throw e;return}let i=r+`/`+n;if(this.isWritable(i))return;let a=s(r)!==s(t);if(!(this.writeEnforcement===`sudo-delegated`&&!a))throw new u(`EACCES`,`permission denied`,s(e))}getUnderlyingFS(){return this.vfs}invalidatePaths(e){this.vfs.invalidatePaths(e)}async flush(){await this.vfs.flush()}isPathUnderMount(e){return this.vfs.isPathUnderMount(e)}async readFile(e,t){let n=O[s(e)];if(n)return n.read(t);if(!this.isAllowedStrict(e))throw new u(`ENOENT`,`no such file or directory`,s(e));let r=await this.resolveAndCheckRead(e);return this.vfs.readFile(r,t)}async readDir(e){if(!this.isAllowed(e))return[];let t=e;if(this.isAllowedStrict(e))try{t=await this.resolveAndCheckRead(e)}catch{return[]}let n=await this.vfs.readDir(t);if(!this.isAllowedStrict(e)){let t=s(e);return n.filter(e=>{let n=t===`/`?`/${e.name}`:`${t}/${e.name}`;return this.isAllowed(n)})}return n}async stat(e){let t=O[s(e)];if(t)return t.stat();if(!this.isAllowed(e))throw new u(`ENOENT`,`no such file or directory`,s(e));if(this.isAllowedStrict(e)){let t=await this.resolveAndCheckRead(e);return this.vfs.stat(t)}return this.vfs.stat(e)}scanPathForSymlinks(e,t){let n=s(e);if(n===`/`)return!1;let r=n.slice(1).split(`/`),i=t?r.length:r.length-1,a=``;for(let e=0;e<i;e++){a=a+`/`+r[e];let t=this.vfs.lstatSync(a);if(t===null)return null;if(t.type===`symlink`)return!0}return!1}statSync(e){let t=O[s(e)];return t?t.stat():!this.isAllowedStrict(e)||this.scanPathForSymlinks(e,!0)!==!1?null:this.vfs.statSync(e)}lstatSync(e){let t=O[s(e)];return t?t.stat():!this.isAllowed(e)||this.scanPathForSymlinks(e,!1)!==!1?null:this.vfs.lstatSync(e)}readDirSync(e){if(!this.isAllowed(e)||this.scanPathForSymlinks(e,!0)!==!1)return null;let t=this.vfs.readDirSync(e);if(t===null)return null;if(this.isAllowedStrict(e))return t;let n=s(e);return t.filter(e=>{let t=n===`/`?`/${e.name}`:`${n}/${e.name}`;return this.isAllowed(t)})}async realpath(e){let t;try{t=await this.vfs.realpath(e)}catch(t){throw t instanceof u?t:new u(`ENOENT`,`no such file or directory`,s(e))}if(!this.isAllowedStrict(t))throw new u(`ENOENT`,`no such file or directory`,s(e));return t}async exists(e){if(O[s(e)])return!0;if(!this.isAllowed(e))return!1;if(this.isAllowedStrict(e))try{await this.resolveAndCheckRead(e)}catch{return!1}return this.vfs.exists(e)}async readTextFile(e){let t=O[s(e)];if(t)return t.readText();if(!this.isAllowedStrict(e))throw new u(`ENOENT`,`no such file or directory`,s(e));let n=await this.resolveAndCheckRead(e);return this.vfs.readTextFile(n)}async*walk(e){if(!this.isAllowed(e))return;let t=e;if(this.isAllowedStrict(e))try{t=await this.resolveAndCheckRead(e)}catch{return}for await(let e of this.vfs.walk(t))this.isAllowed(e)&&(yield e)}async writeFile(e,t,n){let r=O[s(e)];if(r){r.write(t);return}this.checkWrite(e),await this.checkParentRealpathEscape(e);try{(await this.vfs.lstat(e)).type===`symlink`&&await this.resolveAndCheckWrite(e)}catch(e){if(e instanceof u&&e.code===`EACCES`)throw e}return this.vfs.writeFile(e,t,n)}async mkdir(e,t){return this.checkWrite(e),await this.checkParentRealpathEscape(e),this.vfs.mkdir(e,t)}async rm(e,t){this.checkWrite(e);try{(await this.vfs.lstat(e)).type===`symlink`||await this.resolveAndCheckWrite(e)}catch(e){if(e instanceof u&&e.code===`EACCES`)throw e}return this.vfs.rm(e,t)}async rename(e,t){return this.checkWrite(e),this.checkWrite(t),await this.resolveAndCheckWrite(e),await this.checkParentRealpathEscape(t),this.vfs.rename(e,t)}async copyFile(e,t){if(!this.isAllowed(e))throw new u(`ENOENT`,`no such file or directory`,s(e));this.checkWrite(t);let n=await this.resolveAndCheckRead(e);await this.checkParentRealpathEscape(t);try{(await this.vfs.lstat(t)).type===`symlink`&&await this.resolveAndCheckWrite(t)}catch(e){if(e instanceof u&&e.code===`EACCES`)throw e}return this.vfs.copyFile(n,t)}async symlink(e,t){return this.checkWrite(t),await this.checkParentRealpathEscape(t),this.vfs.symlink(e,t)}async readlink(e){if(!this.isAllowedStrict(e))throw new u(`ENOENT`,`no such file or directory`,s(e));let t=await this.vfs.readlink(e),n;if(t.startsWith(`/`))n=s(t);else{let r=this.vfs.dirname(e);n=s(r+`/`+t)}if(!this.isAllowedStrict(n))throw new u(`ENOENT`,`no such file or directory`,s(e));return t}async lstat(e){let t=O[s(e)];if(t)return t.stat();if(!this.isAllowed(e))throw new u(`ENOENT`,`no such file or directory`,s(e));let n=s(e),r=this.vfs.dirname(n),i=this.vfs.basename(n),a;if(r===n)a=r;else try{a=await this.vfs.realpath(r)}catch{throw new u(`ENOENT`,`no such file or directory`,n)}let o=a===`/`?`/${i}`:`${a}/${i}`;if(!this.isAllowed(o))throw new u(`ENOENT`,`no such file or directory`,n);return this.vfs.lstat(o)}watch(e,t,n){if(!this.isAllowed(e))throw new u(`EACCES`,`permission denied`,s(e));let r=this.vfs.getWatcher();if(!r)throw new u(`EINVAL`,`no watcher configured`);return r.watch(s(e),t,n)}dirname(e){return this.vfs.dirname(e)}basename(e){return this.vfs.basename(e)}async mount(e,t,n){return this.checkWrite(e),await this.checkParentRealpathEscape(e),this.vfs.mount(e,t,n)}async unmount(e){return this.checkWrite(e),await this.checkParentRealpathEscape(e),this.vfs.unmount(e)}listMounts(){return this.vfs.listMounts()}getMountIndex(){return this.vfs.getMountIndex()}async refreshMount(e,t){return this.checkWrite(e),this.vfs.refreshMount(e,t)}async dispose(){await this.vfs.dispose()}};function j(e,t){if(e instanceof u){let n=`${e.code}: `,r=e.message;throw r.startsWith(n)&&(r=r.slice(n.length)),e.path&&r.endsWith(` '${e.path}'`)&&(r=r.slice(0,r.length-` '${e.path}'`.length)),new u(e.code,r,t)}throw e}var ue=[`ENOENT`,`EEXIST`,`ENOTDIR`,`EISDIR`,`ENOTEMPTY`,`EINVAL`,`EACCES`,`ELOOP`,`EBUSY`,`EFBIG`,`EBADF`,`ENOSYS`,`EIO`];function M(e,t){if(e instanceof u)return e;{let n=e instanceof Error?e.message:String(e);if(n.includes(`maximum size exceeded`)||n.includes(`call stack size exceeded`))return new u(`EIO`,`internal overflow, not storage: ${n} — reload the session`,t)}let n=e?.code;if(typeof n==`string`){let r=n;if(ue.includes(r)){let n=e instanceof Error?e.message:String(e);return n.startsWith(`${r}: `)&&(n=n.slice(r.length+2),n=n.replace(/, undefined( '[^']*')?$/,``).replace(/ '[^']*'$/,``)),new u(r,n||r,t)}}let r=e instanceof Error?e.message:String(e);return r.includes(`ENOENT`)?new u(`ENOENT`,`no such file or directory`,t):r.includes(`EEXIST`)?new u(`EEXIST`,`file already exists`,t):r.includes(`ENOTDIR`)?new u(`ENOTDIR`,`not a directory`,t):r.includes(`EISDIR`)?new u(`EISDIR`,`is a directory`,t):r.includes(`ENOTEMPTY`)?new u(`ENOTEMPTY`,`directory not empty`,t):r.includes(`ELOOP`)?new u(`ELOOP`,`too many levels of symbolic links`,t):new u(`EINVAL`,r,t)}var de=61440,fe=16384;function N(e){return e===void 0?`absent`:(e&de)===fe?`directory`:`file`}function P(e,t){return t===`absent`?!1:e.kind===`missing`||e.kind!==t}function F(e){let t=e?.mode;return typeof t==`number`?t:void 0}function I(e,t,n,r=new Set){let i=new Set(n);if(r.size>0){for(let t of Object.keys(e.entries??{}))for(let e of r)if(t===e||t.startsWith(`${e}/`)){i.add(t);break}}let a=[];for(let n of i){let r=e.entries?.[n],i=t.entries?.[n];if(!r||!i)continue;let o=N(F(r));o!==N(F(i))&&a.push({path:n,ownIsDirectory:o===`directory`})}return a}var L=3e5,R=5e3,z=Symbol(`mount:timeout`),B=Symbol(`mount:no-panel`),V=class e{kind=`local`;source=void 0;profile=void 0;mountId;handle;closed=!1;constructor(e,t){this.handle=e,this.mountId=t.mountId}static fromHandle(t,n){return new e(t,n)}static async create(t){if(t.isScoop())throw Error(`mount: cannot mount local directories from a scoop (no UI). Ask the cone.`);let n;return n=t.toolContext?await e.acquireHandleViaToolUI(t.toolContext,t.targetPath):t.isExtension?await e.acquireHandleViaPopup():await e.acquireHandleViaDirectPicker(),new e(n,{mountId:t.mountId})}static async acquireHandleViaPopup(){try{let e=await p();if(e.cancelled)throw Error(`mount: cancelled`);if(e.error)throw Error(`mount: ${e.error}`);if(e.handleInIdb&&typeof e.idbKey==`string`){let t=await m(e.idbKey);if(!t)throw Error(`mount: no directory handle found in storage`);return await f(t),t}throw Error(`mount: unexpected popup result`)}catch(e){throw Error(`mount: ${e instanceof Error?e.message:String(e)}`)}}static async acquireHandleViaDirectPicker(){if(typeof window>`u`||!(`showDirectoryPicker`in window))throw Error(`mount: local picker requires a user gesture in the panel (unavailable in this runtime). Ask the agent to mount it instead.`);try{return await window.showDirectoryPicker({mode:`readwrite`})}catch(e){throw e instanceof Error&&e.name===`AbortError`?Error(`mount: cancelled`):Error(`mount: ${e instanceof Error?e.message:String(e)}`)}}static async acquireHandleViaToolUI(t,n){let a=i.generateId(),o=!1,s=!1,c=r({id:a,html:ee(`directory`,[],n),onAction:(t,n)=>e.resolveApprovalAction(t,n)},t.onUpdate).catch(e=>{if(o)return z;if(s)return B;throw e}),l,u=new Promise(e=>{l=setTimeout(()=>{o=!0,i.cancel(a,`mount: timed out`),e(z)},L)}),d=new Promise(e=>{i.waitForMount(a,R).then(()=>{},()=>{o||(s=!0,i.cancel(a,`mount: panel did not render the approval card`),e(B))})}),f=await Promise.race([c,u,d]);if(l&&clearTimeout(l),f===z)throw Error(`mount: timed out after ${Math.round(L/6e4)} minute(s) waiting for user approval`);if(f===B)throw Error(`mount: chat panel did not render the approval card — open the chat panel and retry`);if(!f)throw Error(`mount: tool UI not available`);let p=f;if(p.denied)throw Error(`mount: denied by user`);if(p.cancelled)throw Error(`mount: cancelled`);if(p.error)throw Error(`mount: ${p.error}`);if(!p.handle)throw Error(`mount: no directory selected`);return p.handle}static async resolveApprovalAction(e,t){if(e!==`approve`)return{denied:!0};let n=t;if(n?.handleInIdb&&typeof n.idbKey==`string`)try{let e=await m(n.idbKey);return e?(await f(e),{approved:!0,handle:e}):{error:`No directory handle found in storage`}}catch(e){return{error:e instanceof Error?e.message:String(e)}}if(n?.cancelled)return{cancelled:!0};if(n?.error)return{error:String(n.error)};try{return{approved:!0,handle:await window.showDirectoryPicker({mode:`readwrite`})}}catch(e){return e instanceof Error&&e.name===`AbortError`?{cancelled:!0}:{error:e instanceof Error?e.message:String(e)}}}getHandle(){return this.handle}assertOpen(e){if(this.closed)throw new u(`EBADF`,`mount closed`,e)}splitPath(e){return e.replace(/^\/+/,``).replace(/\/+$/,``).split(`/`).filter(e=>e.length>0)}async resolveDir(e,t=!1){let n=this.splitPath(e),r=this.handle;for(let i of n)try{r=await r.getDirectoryHandle(i,{create:t})}catch(t){throw this.toFsError(t,e)}return r}async resolveFile(e,t=!1){let n=this.splitPath(e);if(n.length===0)throw new u(`EISDIR`,`is a directory`,e);let r=n.pop(),i=this.handle;for(let r of n)try{i=await i.getDirectoryHandle(r,{create:t})}catch(t){throw this.toFsError(t,e)}try{return await i.getFileHandle(r,{create:t})}catch(t){throw this.toFsError(t,e)}}toFsError(e,t){if(e instanceof u)return e;if(e instanceof DOMException){if(e.name===`NotFoundError`)return new u(`ENOENT`,`no such file or directory`,t);if(e.name===`TypeMismatchError`)return new u(`ENOTDIR`,`not a directory`,t);if(e.name===`NotAllowedError`)return new u(`EACCES`,`permission denied`,t);if(e.name===`InvalidModificationError`)return new u(`ENOTEMPTY`,`directory not empty`,t)}if(e instanceof Error){if(e.name===`NotFound`||e.name===`NotFoundError`)return new u(`ENOENT`,`no such file or directory`,t);if(e.name===`TypeMismatch`||e.name===`TypeMismatchError`)return new u(`ENOTDIR`,`not a directory`,t);if(e.name===`InvalidModification`||e.name===`InvalidModificationError`)return new u(`ENOTEMPTY`,`directory not empty`,t)}return new u(`EINVAL`,e instanceof Error?e.message:String(e),t)}async readDir(e){this.assertOpen(e);let t=await this.resolveDir(e),n=[];for await(let[e,r]of t)if(r.kind===`file`){let t=await r.getFile();n.push({name:e,kind:`file`,size:t.size,lastModified:t.lastModified})}else n.push({name:e,kind:`directory`});return n}async readFile(e){this.assertOpen(e);let t=await(await this.resolveFile(e)).getFile();return new Uint8Array(await t.arrayBuffer())}async writeFile(e,t){this.assertOpen(e);let n=await(await this.resolveFile(e,!0)).createWritable();await n.write(t),await n.close()}async stat(e){if(this.assertOpen(e),this.splitPath(e).length===0)return{kind:`directory`,size:0,mtime:0};try{let t=await(await this.resolveFile(e)).getFile();return{kind:`file`,size:t.size,mtime:t.lastModified}}catch{}return await this.resolveDir(e),{kind:`directory`,size:0,mtime:0}}async mkdir(e){this.assertOpen(e),await this.resolveDir(e,!0)}async remove(e,t){this.assertOpen(e);let n=this.splitPath(e);if(n.length===0)throw new u(`EINVAL`,`cannot remove mount root`,e);let r=n.pop(),i=n.join(`/`),a=await this.resolveDir(i||`/`);try{await a.removeEntry(r,{recursive:t?.recursive??!1})}catch(t){throw this.toFsError(t,e)}}async refresh(){return this.assertOpen(`/`),{added:[],removed:[],changed:[],unchanged:0,errors:[]}}describe(){return{displayName:this.handle.name}}async close(){this.closed=!0}};function H(e,t){return e===t||e.startsWith(t===`/`?`/`:`${t}/`)}var pe=`/.metadata.json`;function U(e){return e.entries&&delete e.entries[pe],e}function me(e,t,n){let r=t.entries??{},i={...e.entries??{}};`/`in r&&(i[`/`]=r[`/`]);for(let e of n.paths)e in r?i[e]=r[e]:delete i[e];for(let e of n.prefixes){for(let t of Object.keys(i))H(t,e)&&delete i[t];for(let t of Object.keys(r))H(t,e)&&(i[t]=r[t])}let{entries:a,...o}=t;return U({...o,entries:i})}var he=61440,W=16384,G=32768,ge=40960;async function K(e,t,n){let r={kindFixed:[],sizesFixed:0,dropped:0,selfEntryDropped:!1,inosReassigned:0,nlinksFixed:0,changed:!1},i=e.entries??{};for(let[e,a]of Object.entries(i)){if(n?.(),e===`/`||typeof a!=`object`||!a)continue;if(e===`/.metadata.json`){delete i[e],r.selfEntryDropped=!0,r.changed=!0;continue}let o=a,s=(o.mode??0)&he;if(s===ge){q(o,r);continue}let c=await t(e);if(c.kind===`missing`){delete i[e],r.dropped+=1,r.changed=!0;continue}q(o,r),ve(e,o,s,c,r)}return _e(i,r),r}function _e(e,t){let n=0;for(let t of Object.values(e)){let e=t;typeof e?.ino==`number`&&(n=Math.max(n,e.ino)),typeof e?.data==`number`&&(n=Math.max(n,e.data))}let r=n+1,i=new Set;for(let[n,a]of Object.entries(e)){if(typeof a!=`object`||!a)continue;let e=a;if(n===`/`){typeof e.ino==`number`&&i.add(e.ino);continue}let o=e.ino;if(typeof o==`number`&&o!==0&&!i.has(o)){i.add(o);continue}e.ino=r,e.data=r+1,i.add(r),r+=2,t.inosReassigned+=1,t.changed=!0}}function q(e,t){e.nlink||(e.nlink=1,t.nlinksFixed+=1,t.changed=!0)}function ve(e,t,n,r,i){if(n===G&&r.kind===`directory`){t.mode=((t.mode??0)&511||493)|W,i.kindFixed.push(`${e} file→dir`),i.changed=!0;return}if(n===W&&r.kind===`file`){t.mode=((t.mode??0)&511||420)|G,t.size=r.size,i.kindFixed.push(`${e} dir→file`),i.changed=!0;return}n===G&&r.kind===`file`&&typeof t.size==`number`&&t.size!==r.size&&(t.size=r.size,i.sizesFixed+=1,i.changed=!0)}function J(e){return async t=>{let n=t.split(`/`).filter(Boolean),r=e;for(let e=0;e<n.length-1;e+=1)try{r=await r.getDirectoryHandle(n[e])}catch{return{kind:`missing`}}let i=n[n.length-1];if(i===void 0)return{kind:`directory`};try{return{kind:`file`,size:(await(await r.getFileHandle(i)).getFile()).size}}catch{}try{return await r.getDirectoryHandle(i),{kind:`directory`}}catch{return{kind:`missing`}}}}async function ye(e,t,n){try{return await e()}catch(r){let i=null;try{i=await t()}catch{}if(!i?.changed)throw r;return n(i),await e()}}async function be(e,t){let n;try{let t=await e.getFileHandle(`.metadata.json`),r=JSON.parse(await(await t.getFile()).text());if(!r||typeof r!=`object`||!r.entries)return null;n=r}catch{return null}let r=await K(n,J(e),t);if(!r.changed)return r;let i=await(await e.getFileHandle(`.metadata.json`,{create:!0})).createWritable();return await i.write(JSON.stringify(n)),await i.close(),r}async function xe(e,t,n,r){try{return await e.lstat(t)}catch(e){let t=M(e,r);if(t.code===`ENOENT`&&n)return null;throw t}}async function Se(e,t,n){let r;try{r=await e.readlink(t)}catch(e){throw M(e,n)}return r.startsWith(`/`)?s(r):s(l(a(t).dir,r))}async function Y(e,t,n,r,i,a){let o=t===`/`?`/${n}`:`${t}/${n}`;for(;;){let t=await xe(e,o,r,i);if(t===null||!t.isSymbolicLink())return{resolved:o,hops:a};if(++a>10)throw new u(`ELOOP`,`too many symbolic links encountered`,i);o=await Se(e,o,i)}}async function X(e,t,n){let r=s(n);if(t(r))return r;let i=r.split(`/`).filter(Boolean),a=`/`,o=0;for(let t=0;t<i.length;t++){let n=await Y(e,a,i[t],t===i.length-1,r,o);a=n.resolved,o=n.hops}return a}async function Ce(e,t,n){return t(n)?n:X(e,t,n)}function we(e,t,n){return e.size===0||!e.has(n)||!t.isReady(n)?!1:!Array.from(e.keys()).some(e=>e!==n&&e.startsWith(n+`/`))}async function Te(e,t){try{return await e(t)}catch{return t}}async function*Z(e,t,n,r=0){let i=s(t);if(we(e.mountPoints,e.mountIndex,i)){let t=e.mountIndex.getFiles(i);if(t){for(let e of t)yield e;return}}let a=n??new Set;if(r>64||a.size>=1e5)return;let o=await Te(t=>e.realpath(t),i);if(a.has(o))return;a.add(o);let c=await e.readDir(i);for(let t of c)yield*Ee(e,t,i===`/`?`/${t.name}`:`${i}/${t.name}`,a,r+1)}async function*Ee(e,t,n,r,i){if(t.type===`file`){yield n;return}if(t.type===`symlink`){yield*De(e,n,r,i);return}yield*Z(e,n,r,i)}async function*De(e,t,n,r){try{let i=await e.stat(t);i.type===`file`?yield t:i.type===`directory`&&(yield*Z(e,t,n,r))}catch{}}function Q(){try{if(typeof globalThis.navigator?.storage?.getDirectory==`function`)return`opfs`}catch{}return`memory`}function Oe(e,t){switch(e.kind){case`local`:case`proc`:return{kind:`local`,mountId:e.mountId,idbHandleKey:t};case`hostfs`:return{kind:`hostfs`,mountId:e.mountId,hostPath:e.getHostPath()};default:return{kind:e.kind===`s3`?`s3`:e.kind===`aem`?`aem`:`da`,mountId:e.mountId,source:e.source,profile:e.profile??`default`}}}var $=class e{lfs;lfsSync;rawLfs=null;rawLfsSync=null;_ready;_readyResolved=!1;backend;mountPoints=new Map;opfsBackendFs=null;opfsHandle=null;mountRoot=``;internalMounts=new Set;watcher=null;dbName;mountSyncChannel=null;mountIndex=new D;static writeChains=new Map;onRepairProgress;constructor(t,n,r,i,a){if(this.dbName=t,this.onRepairProgress=a,this.backend=r===`opfs`?`opfs`:`memory`,this.lfs=this.makeDeferredLfs(),this.lfsSync=this.makeDeferredLfsSync(),this._ready=this.backend===`opfs`?e.initOpfsBackend(this,i,n===!0):e.initMemoryBackend(this,t,n===!0),this._ready.then(()=>{this._readyResolved=!0},()=>{}),typeof BroadcastChannel<`u`)try{this.mountSyncChannel=new BroadcastChannel(`vfs-mount-sync:${t}`),this.mountSyncChannel.onmessage=e=>{let{type:t,path:n,descriptor:r}=e.data??{};if(t===`mount`&&typeof n==`string`&&r)this.reconstructBackendFromDescriptor(r,n).then(e=>{this.mountPoints.set(n,e),e.kind===`local`&&this.mountIndex.registerMount(n,e.getHandle()),this.watcher?.notify([{type:`modify`,path:n,entryType:`directory`}])}).catch(()=>{});else if(t===`unmount`&&typeof n==`string`){let e=this.mountPoints.get(n);this.mountPoints.delete(n),this.mountIndex.unregisterMount(n),e?.close(),this.watcher?.notify([{type:`modify`,path:n,entryType:`directory`}])}}}catch{}}static async initOpfsBackend(n,r,i){let a=r??await e.acquireOpfsHandle(n.dbName,i);await e.seedOpfsMetadataSidecarIfMissing(a);let[o,{WebAccess:s}]=await Promise.all([t(()=>import(`./dist-RekgwRC0.js`).then(e=>e.t),__vite__mapDeps([0,1,2])),t(()=>import(`./dist-BmTb9jmr.js`),__vite__mapDeps([3,0,1,2]))]);await e.ensureRootMount(o);let c=`/__opfs__/${n.dbName}`,l=e.opfsBackends.get(n.dbName);if(l&&i){try{o.umount(c)}catch{}e.opfsBackends.delete(n.dbName),l=void 0}if(!l){let r=()=>o.resolveMountConfig({backend:s,handle:a,metadata:`/.metadata.json`}),{resolveWithSidecarRepair:i,repairOpfsMetadataSidecar:u}=await t(async()=>{let{resolveWithSidecarRepair:e,repairOpfsMetadataSidecar:t}=await import(`./sidecar-repair-DCvPqdWE.js`);return{resolveWithSidecarRepair:e,repairOpfsMetadataSidecar:t}},[]);try{let e=await n.withWriteLock(()=>u(a,n.onRepairProgress));e?.changed&&console.warn(`[virtual-fs] repaired metadata sidecar before mount (#2146)`,{dbName:n.dbName,kindFixed:e.kindFixed,sizesFixed:e.sizesFixed,dropped:e.dropped,inosReassigned:e.inosReassigned,nlinksFixed:e.nlinksFixed,selfEntryDropped:e.selfEntryDropped})}catch{}let d=await i(r,()=>n.withWriteLock(()=>u(a,n.onRepairProgress)),e=>console.warn(`[virtual-fs] repaired poisoned metadata sidecar; retrying mount`,{dbName:n.dbName,kindFixed:e.kindFixed,sizesFixed:e.sizesFixed,dropped:e.dropped,nlinksFixed:e.nlinksFixed,selfEntryDropped:e.selfEntryDropped}));try{o.mount(c,d)}catch{}l={backendFs:d,refs:0,sidecarDirty:{paths:new Set,prefixes:new Set}},e.opfsBackends.set(n.dbName,l)}l.refs+=1,n.opfsBackendFs=l.backendFs.index?l.backendFs:null,n.opfsHandle=a,n.mountRoot=c,n.rawLfs=o.promises,n.rawLfsSync=o}static async initMemoryBackend(n,r,i){let a=await t(()=>import(`./dist-RekgwRC0.js`).then(e=>e.t),__vite__mapDeps([0,1,2]));await e.ensureRootMount(a);let o=`/__zenfs__/${r}`,s=e.memoryBackends.get(r);if(s&&i){try{a.umount(o)}catch{}e.memoryBackends.delete(r),s=void 0}s||(s={store:a.InMemory.create({label:r}),refs:0},e.memoryBackends.set(r,s)),s.refs+=1;try{a.mount(o,s.store)}catch{}n.mountRoot=o,n.rawLfs=a.promises,n.rawLfsSync=a,n.opfsBackendFs=null,n.opfsHandle=null}static rootMountReady=null;static memoryBackends=new Map;static opfsBackends=new Map;static async ensureRootMount(t){return e.rootMountReady===null&&(e.rootMountReady=(async()=>{await t.configureSingle({backend:t.InMemory,label:`__vfs_root__`})})()),e.rootMountReady}prefix(e){return this.mountRoot?e===`/`?this.mountRoot:this.mountRoot+e:e}unprefix(e){return!this.mountRoot||!e.startsWith(this.mountRoot)?e:e.slice(this.mountRoot.length)||`/`}makeDeferredLfs(){let e=e=>this.prefix(e),t=e=>this.unprefix(e),n=()=>{if(!this.rawLfs)throw Error(`VirtualFS used before init resolved`);return this.rawLfs};return{readFile:(t,r)=>this._readyResolved?n().readFile(e(t),r):this._ready.then(()=>n().readFile(e(t),r)),writeFile:(t,r,i)=>this._readyResolved?n().writeFile(e(t),r,i):this._ready.then(()=>n().writeFile(e(t),r,i)),readdir:t=>this._readyResolved?n().readdir(e(t)):this._ready.then(()=>n().readdir(e(t))),mkdir:(t,r)=>this._readyResolved?n().mkdir(e(t),r):this._ready.then(()=>n().mkdir(e(t),r)),rmdir:t=>this._readyResolved?n().rmdir(e(t)):this._ready.then(()=>n().rmdir(e(t))),unlink:t=>this._readyResolved?n().unlink(e(t)):this._ready.then(()=>n().unlink(e(t))),rename:(t,r)=>this._readyResolved?n().rename(e(t),e(r)):this._ready.then(()=>n().rename(e(t),e(r))),stat:t=>this._readyResolved?n().stat(e(t)):this._ready.then(()=>n().stat(e(t))),lstat:t=>this._readyResolved?n().lstat(e(t)):this._ready.then(()=>n().lstat(e(t))),symlink:(t,r)=>{let i=t.startsWith(`/`)?e(t):t;return this._readyResolved?n().symlink(i,e(r)):this._ready.then(()=>n().symlink(i,e(r)))},readlink:async r=>(this._readyResolved||await this._ready,t(await n().readlink(e(r)))),truncate:async(t,r)=>{this._readyResolved||await this._ready;let i=n();typeof i.truncate==`function`&&await i.truncate(e(t),r)},realpath:async r=>{this._readyResolved||await this._ready;let i=n();return typeof i.realpath==`function`?t(await i.realpath(e(r))):e(r)}}}makeDeferredLfsSync(){let e=e=>this.prefix(e),t=e=>this.unprefix(e);return{readdirSync:t=>{let n=this.rawLfsSync;return n?.readdirSync?n.readdirSync(e(t)):void 0},statSync:t=>{let n=this.rawLfsSync;return n?.statSync?n.statSync(e(t)):void 0},lstatSync:t=>{let n=this.rawLfsSync;return n?.lstatSync?n.lstatSync(e(t)):void 0},readlinkSync:n=>{let r=this.rawLfsSync;return r?.readlinkSync?t(r.readlinkSync(e(n))):void 0}}}static async seedOpfsMetadataSidecarIfMissing(e){let t=`.metadata.json`;try{await e.getFileHandle(t);return}catch(e){if(e?.name!==`NotFoundError`)throw e}let n=await(await e.getFileHandle(t,{create:!0})).createWritable(),r=JSON.stringify({version:1,maxSize:4294967295,entries:{}});await n.write(r),await n.close()}static async acquireOpfsHandle(e,t){let n=navigator.storage;if(!n?.getDirectory)throw new u(`EINVAL`,`OPFS is not available in this environment`);let r=await n.getDirectory();if(t)try{await r.removeEntry(e,{recursive:!0})}catch{}return r.getDirectoryHandle(e,{create:!0})}static _createSyncForTests(t){return new e(t)}static async create(t){let n=t?.dbName??`browser-fs`,r=t?.wipe===!0,i=t?.backend??Q(),a=new e(n,r,i,void 0,t?.onRepairProgress);return await a._ready,r&&await _().catch(()=>{}),a}async flush(){await this.writeOpfsMetadataSidecar()}async writeOpfsMetadataSidecar(){this.backend===`opfs`&&await this.withWriteLock(()=>this.writeOpfsMetadataSidecarUnlocked())}async writeOpfsMetadataSidecarUnlocked(){if(this.backend!==`opfs`)return;let t=this.opfsBackendFs,n=this.opfsHandle;if(!t||!n)return;let r=t.index.toJSON(),i=e.opfsBackends.get(this.dbName)?.sidecarDirty,a=r;if(i){let e=null;try{let t=await n.getFileHandle(`.metadata.json`),r=JSON.parse(await(await t.getFile()).text());r&&typeof r==`object`&&r.entries&&(e=r)}catch{}e&&(await this.auditDirtyKindFlips(r,e,i,n),a=me(e,r,i))}let o=JSON.stringify(U(a)),s=await(await n.getFileHandle(`.metadata.json`,{create:!0})).createWritable();await s.write(o),await s.close(),i&&(i.paths.clear(),i.prefixes.clear())}async auditDirtyKindFlips(e,t,n,r){let i=I(e,t,n.paths,n.prefixes);if(i.length===0)return;let a=J(r),o=this.opfsBackendFs;for(let n of i){let r=await a(n.path).catch(()=>null);if(r!==null&&r.kind!==`missing`&&r.kind===`directory`===n.ownIsDirectory)continue;let i=t.entries?.[n.path];e.entries&&i!==void 0&&(e.entries[n.path]=i);let s=r!==null&&r.kind!==`missing`;s&&(o?.index?.delete(n.path),o?._handles?.delete(n.path)),console.warn(`[virtual-fs] refused to flush in-memory kind flip over sidecar record (#2006)`,{path:n.path,reality:r?.kind??`unverifiable`,evicted:s})}}markSidecarDirty(t,n=`path`){if(this.backend!==`opfs`)return;let r=e.opfsBackends.get(this.dbName)?.sidecarDirty;if(!r)return;let i=s(t);(n===`prefix`?r.prefixes:r.paths).add(i);let{dir:o}=a(i);for(;o!==`/`;)r.paths.add(o),o=a(o).dir}invalidatePaths(e){if(this.backend!==`opfs`||!this.opfsBackendFs)return;let t=this.opfsBackendFs;for(let n of e){let e=s(n);t.index.delete(e),t._handles?.delete(e),this.markSidecarDirty(e)}}async withKindMismatchRetry(e,t){return this.withKindMismatchRetryPaths([e],t)}async withKindMismatchRetryPaths(e,t){try{return await t()}catch(n){let r=n?.code;if(r!==`EISDIR`&&r!==`ENOTDIR`&&r!==`EINVAL`)throw n;for(let n of e)if(await this.reconcileKindMismatch(n).catch(()=>!1))return await t();throw n}}async reconcileKindMismatch(e){if(this.backend!==`opfs`)return!1;let t=this.opfsBackendFs,n=this.opfsHandle;if(!t?.index||!n)return!1;let r=s(e),i=r;try{i=await this.resolveSymlinks(r)}catch{}let a=await J(n)(i),o=N(t.index.get(i)?.mode),c=t._handles?.get(i),l=c?.kind===`directory`?`directory`:c?.kind===`file`?`file`:`absent`,u=P(a,o),d=P(a,l);if(!u&&!d)return!1;if(t.index.delete(i),t._handles?.delete(i),o===`directory`||l===`directory`){let e=`${i}/`;for(let n of[...t.index.keys()])n.startsWith(e)&&t.index.delete(n);if(t._handles)for(let n of[...t._handles.keys()])n.startsWith(e)&&t._handles.delete(n)}return this.markSidecarDirty(i),console.warn(`[virtual-fs] reconciled in-memory kind mismatch (#2006)`,{path:i,reality:a.kind,indexHeld:o,handleHeld:l}),!0}canWrite(e){return!0}setWatcher(e){this.watcher=e}getWatcher(){return this.watcher}async watch(e,t){let n=this.watcher;if(!n)throw new u(`ENOSYS`,`no FsWatcher attached to this VirtualFS`);let r=e.map(e=>n.watch(e,()=>!0,t));return()=>{for(let e of r)e()}}async dispose(){if(this.mountSyncChannel?.close(),this.mountSyncChannel=null,this.watcher?.dispose(),this.watcher=null,this.mountIndex.dispose(),await this.writeOpfsMetadataSidecar(),this.mountRoot){let n=this.backend===`opfs`?e.opfsBackends:e.memoryBackends,r=n.get(this.dbName);if(r&&(--r.refs,r.refs<=0)){n.delete(this.dbName);try{(await t(()=>import(`./dist-RekgwRC0.js`).then(e=>e.t),__vite__mapDeps([0,1,2]))).umount(this.mountRoot)}catch{}}}}readDirSync(e){let t=s(e);if(this.findMount(t))return null;let n=this.lfsSync;if(typeof n.readdirSync!=`function`||typeof n.lstatSync!=`function`)return null;try{let e=n.readdirSync(t),r=[];for(let i of e){let e=t===`/`?`/${i}`:`${t}/${i}`;try{let t=n.lstatSync(e),a=t.isSymbolicLink()?`symlink`:t.isDirectory()?`directory`:`file`;r.push({name:i,type:a})}catch{}}return r}catch{return null}}statSync(e){let t=s(e);if(this.findMount(t))return null;let n=this.lfsSync;if(typeof n.statSync!=`function`||typeof n.lstatSync!=`function`||typeof n.readlinkSync!=`function`)return null;if(t===`/`)try{let e=n.statSync(t);return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs}}catch{return null}let r=t;for(let e=0;e<=10;e++){let e;try{e=n.lstatSync(r)}catch{return null}if(!e.isSymbolicLink())return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs};let t;try{t=n.readlinkSync(r)}catch{return null}r=t.startsWith(`/`)?s(t):s(l(a(r).dir,t))}return null}lstatSync(e){let t=s(e);if(this.findMount(t))return null;let n=this.lfsSync;if(typeof n.lstatSync!=`function`)return null;if(t===`/`)return this.statSync(t);try{let e=n.lstatSync(t);if(e.isSymbolicLink()){let r=n.readlinkSync?n.readlinkSync(t):``;return{type:`symlink`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,isSymlink:!0,symlinkTarget:r}}return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs}}catch{return null}}async mount(e,t,n){let r=s(e);if(this.mountPoints.has(r))throw new u(`EEXIST`,`mount point is already mounted`,r);try{if((await this.lstat(r)).type!==`directory`)throw new u(`ENOTDIR`,`mount point must be a directory`,r);if((await this.readDir(r)).length>0)throw new u(`ENOTEMPTY`,`mount point must be empty to avoid shadowing existing files`,r)}catch(e){if(!(e instanceof u)||e.code!==`ENOENT`)throw e}let{dir:i}=a(r);i!==`/`&&await this.mkdir(i,{recursive:!0});try{await this.lfs.mkdir(r)}catch{}if(this.mountPoints.set(r,t),t.kind===`local`){let e=n?.limits??E(n?.env??{});this.mountIndex.registerMount(r,t.getHandle(),e)}let o=Oe(t,r);try{this.mountSyncChannel?.postMessage({type:`mount`,path:r,descriptor:o})}catch{}if(this.watcher?.notify([{type:`modify`,path:r,entryType:`directory`}]),t.kind!==`hostfs`)try{let e={targetPath:r,descriptor:o,createdAt:Date.now()},n=t.kind===`local`?t.getHandle():void 0;await te(e,n)}catch{}}async unmount(e){let t=s(e),n=this.mountPoints.get(t);this.mountPoints.delete(t),this.mountIndex.unregisterMount(t);try{this.mountSyncChannel?.postMessage({type:`unmount`,path:t})}catch{}this.watcher?.notify([{type:`modify`,path:t,entryType:`directory`}]),await n?.close();try{await h(t)}catch{}}async reconstructBackendFromDescriptor(e,n){switch(e.kind){case`local`:{let t=await g(e.idbHandleKey);if(!t)throw Error(`no handle stored for ${e.idbHandleKey}`);return V.fromHandle(t,{mountId:e.mountId})}case`hostfs`:{let{HostFsMountBackend:r}=await t(async()=>{let{HostFsMountBackend:e}=await import(`./backend-hostfs-Com-zF5W.js`);return{HostFsMountBackend:e}},__vite__mapDeps([4,5,6]));return new r({targetPath:n,hostPath:e.hostPath,mountId:e.mountId})}case`s3`:{let{S3MountBackend:n,RemoteMountCache:r,makeSignedFetchS3:i}=await t(async()=>{let{S3MountBackend:e,RemoteMountCache:t,makeSignedFetchS3:n}=await import(`./mount-Cr-j5Qvu.js`);return{S3MountBackend:e,RemoteMountCache:t,makeSignedFetchS3:n}},__vite__mapDeps([7,8,9,10,11,12,1,13,14,5,15,6,16,17,18,19])),a=new r({mountId:e.mountId,ttlMs:3e4});return new n({source:e.source,profile:e.profile,cache:a,mountId:e.mountId,signedFetch:i(e.profile)})}case`da`:{let{DaMountBackend:n,RemoteMountCache:r,makeSignedFetchDa:i}=await t(async()=>{let{DaMountBackend:e,RemoteMountCache:t,makeSignedFetchDa:n}=await import(`./mount-Cr-j5Qvu.js`);return{DaMountBackend:e,RemoteMountCache:t,makeSignedFetchDa:n}},__vite__mapDeps([7,8,9,10,11,12,1,13,14,5,15,6,16,17,18,19])),a=new r({mountId:e.mountId,ttlMs:3e4});return new n({source:e.source,profile:e.profile,cache:a,mountId:e.mountId,signedFetch:i()})}case`aem`:{let{AemMountBackend:n,RemoteMountCache:r,makeSignedFetchDa:i}=await t(async()=>{let{AemMountBackend:e,RemoteMountCache:t,makeSignedFetchDa:n}=await import(`./mount-Cr-j5Qvu.js`);return{AemMountBackend:e,RemoteMountCache:t,makeSignedFetchDa:n}},__vite__mapDeps([7,8,9,10,11,12,1,13,14,5,15,6,16,17,18,19])),a=new r({mountId:e.mountId,ttlMs:3e4});return new n({source:e.source,profile:e.profile,cache:a,mountId:e.mountId,signedFetch:i()})}}}listMounts(){let e=[];for(let t of this.mountPoints.keys())this.internalMounts.has(t)||e.push(t);return e}listInternalMounts(){return[...this.internalMounts]}listMountPoints(){let e=[];for(let[t,n]of this.mountPoints)this.internalMounts.has(t)||e.push({path:t,kind:n.kind});return e}async mountInternal(e,t){let n=s(e);if(this.mountPoints.has(n))throw new u(`EEXIST`,`mount point is already mounted`,n);let{dir:r}=a(n);r!==`/`&&await this.mkdir(r,{recursive:!0});try{await this.lfs.mkdir(n)}catch{}this.mountPoints.set(n,t),this.internalMounts.add(n),this.watcher?.notify([{type:`modify`,path:n,entryType:`directory`}])}async unmountInternal(e){let t=s(e);if(!this.internalMounts.has(t))throw new u(`ENOENT`,`not an internal mount point`,t);let n=this.mountPoints.get(t);this.mountPoints.delete(t),this.internalMounts.delete(t),this.watcher?.notify([{type:`modify`,path:t,entryType:`directory`}]),await n?.close()}getMountIndex(){return this.mountIndex}async refreshMount(e,t){let n=s(e),r=this.mountPoints.get(n);if(!r)throw new u(`ENOENT`,`not a mount point`,n);let i=await r.refresh(t);return r.kind===`local`&&await this.mountIndex.refreshMount(n,E(t?.env??{})),this.watcher?.notify([{type:`modify`,path:n,entryType:`directory`}]),i}isPathUnderMount(e){for(let t of this.mountPoints.keys())if(e===t||e.startsWith(t+`/`))return!0;return!1}findMount(e){let t=null;for(let[n,r]of this.mountPoints)(e===n||e.startsWith(n+`/`))&&(!t||n.length>t.mountPath.length)&&(t={mountPath:n,backend:r});return t?e===t.mountPath?{path:t.mountPath,backend:t.backend,relParts:[]}:{path:t.mountPath,backend:t.backend,relParts:e.slice(t.mountPath.length+1).split(`/`).filter(Boolean)}:null}async readFile(e,t){return this.withKindMismatchRetry(e,()=>this.readFileInner(e,t))}async readFileInner(e,t){let n=s(e),r=this.findMount(n);if(r){if(r.relParts.length===0)throw new u(`EISDIR`,`is a directory`,n);let e=r.relParts.join(`/`);try{let n=await r.backend.readFile(e);return(t?.encoding??`utf-8`)===`utf-8`?new TextDecoder(`utf-8`).decode(n):n}catch(e){j(e,n)}}let i=await this.resolveSymlinks(n);try{return(t?.encoding??`utf-8`)===`utf-8`?await this.lfs.readFile(i,{encoding:`utf8`}):await this.lfs.readFile(i)}catch(e){throw M(e,n)}}async writeFile(e,t,n){return this.withKindMismatchRetry(e,()=>this.writeFileInner(e,t,n))}async writeFileInner(e,t,n){let r=s(e),i=this.findMount(r);if(i){if(i.relParts.length===0)throw new u(`EISDIR`,`is a directory`,r);let e=i.relParts.join(`/`),n=!1;try{await this.stat(r),n=!0}catch{}let a=typeof t==`string`?new TextEncoder().encode(t):t instanceof Uint8Array?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):new Uint8Array(t);try{await i.backend.writeFile(e,a)}catch(e){j(e,r)}this.watcher?.notify([{type:n?`modify`:`create`,path:r,entryType:`file`}]),this.mountIndex.notifyWrite(r);return}let o;try{o=await this.resolveSymlinks(r)}catch{o=r}let c=!1;try{await this.lfs.stat(o),c=!0}catch{}let{dir:l}=a(o);await this.withWriteLock(async()=>{this.markSidecarDirty(o),l!==`/`&&await this.mkdirRecursiveUnlocked(l);let e=typeof t==`string`?new TextEncoder().encode(t).byteLength:(t instanceof Uint8Array,t.byteLength);try{await this.lfs.writeFile(o,t)}catch(e){if(l!==`/`&&e instanceof Error&&e.message.includes(`ENOENT`)){await this.mkdirRecursiveUnlocked(l);try{await this.lfs.writeFile(o,t)}catch(e){throw M(e,r)}}else throw M(e,r)}try{await this.lfs.truncate?.(o,e)}catch(e){throw M(e,r)}}),this.watcher?.notify([{type:c?`modify`:`create`,path:o,entryType:`file`}])}async readDir(e){let t=s(e),n=this.findMount(t);return n?this.readDirMounted(t,n):this.readDirLocal(t)}async readDirMounted(e,t){let n=this.mountIndex.getDirectoryEntries(t.path,e);if(n!==void 0){let t=new Map;for(let e of n)t.set(e.name,{name:e.name,type:e.type});return this.addNestedMountEntries(t,e),[...t.values()]}let r=t.relParts.join(`/`)||`/`,i;try{i=await t.backend.readDir(r)}catch(t){j(t,e)}let a=new Map;for(let e of i)a.set(e.name,{name:e.name,type:e.kind===`directory`?`directory`:`file`});return this.addNestedMountEntries(a,e),[...a.values()]}async readDirLocal(e){return this.withKindMismatchRetry(e,()=>this.readDirLocalInner(e))}async readDirLocalInner(e){let t=await this.resolveSymlinks(e);try{let e=await this.lfs.readdir(t),n=[];for(let r of e){let e=await this.statDirEntry(t,r);e&&n.push(e)}return n}catch(t){throw M(t,e)}}async statDirEntry(e,t){let n=e===`/`?`/${t}`:`${e}/${t}`;try{let e=await this.lfs.lstat(n);return e.isSymbolicLink()?{name:t,type:`symlink`}:{name:t,type:e.isDirectory()?`directory`:`file`}}catch{return null}}addNestedMountEntries(e,t){let n=t===`/`?`/`:`${t}/`;for(let r of this.mountPoints.keys()){if(r===t||!r.startsWith(n))continue;let i=r.slice(n.length);!i||i.includes(`/`)||e.has(i)||e.set(i,{name:i,type:`directory`})}}async withWriteLock(t){let n=this.dbName,r,i=new Promise(e=>{r=e}),a=e.writeChains.get(n)??Promise.resolve();e.writeChains.set(n,i),await a;try{let e=globalThis.navigator?.locks;return this.backend!==`opfs`||typeof e?.request!=`function`?await t():await e.request(`slicc-vfs:${n}`,()=>t())}finally{r(),e.writeChains.get(n)===i&&e.writeChains.delete(n)}}async mkdirRecursiveUnlocked(e){let t=e.split(`/`).filter(Boolean),n=[],r=``;for(let e of t){r+=`/`+e;try{await this.lfs.mkdir(r),n.push(r)}catch(e){if(e instanceof Error&&!e.message.includes(`EEXIST`))throw M(e,r);try{let e=await this.lfs.lstat(r);if(!e.isDirectory()&&!e.isSymbolicLink())throw new u(`ENOTDIR`,`not a directory`,r)}catch(e){if(e instanceof u&&e.code===`ENOTDIR`)throw e}}}return n}async mkdir(e,t){let n=s(e);if(n===`/`)return;let r=this.findMount(n);if(r){if(r.relParts.length===0)return;let e=r.relParts.join(`/`),t=await this.exists(n);try{await r.backend.mkdir(e)}catch(e){j(e,n)}t||this.watcher?.notify([{type:`create`,path:n,entryType:`directory`}]);return}if(t?.recursive){let e=await this.withWriteLock(()=>(this.markSidecarDirty(n),this.mkdirRecursiveUnlocked(n)));e.length>0&&this.watcher?.notify(e.map(e=>({type:`create`,path:e,entryType:`directory`})))}else await this.withWriteLock(async()=>{this.markSidecarDirty(n);try{await this.lfs.mkdir(n)}catch(e){throw M(e,n)}}),this.watcher?.notify([{type:`create`,path:n,entryType:`directory`}])}async rm(e,t){return this.withKindMismatchRetry(s(e),()=>this.rmInner(e,t))}async rmInner(e,t){let n=s(e),r=this.findMount(n);if(r){if(r.relParts.length===0)throw new u(`EINVAL`,`cannot remove a mount point — use unmount`,n);let e;try{e=(await this.stat(n)).type}catch{}let i=r.relParts.join(`/`);try{await r.backend.remove(i,{recursive:t?.recursive})}catch(e){j(e,n)}this.watcher?.notify([{type:`delete`,path:n,entryType:e}]),this.mountIndex.notifyDelete(n);return}try{let e=await this.lfs.lstat(n);await this.withWriteLock(async()=>{e.isSymbolicLink()?await this.lfs.unlink(n):e.isDirectory()?t?.recursive?await this.rmRecursiveUnlocked(n):await this.lfs.rmdir(n):await this.lfs.unlink(n),this.markSidecarDirty(n,`prefix`),await this.writeOpfsMetadataSidecarUnlocked()})}catch(e){throw M(e,n)}this.watcher?.notify([{type:`delete`,path:n}])}async rmRecursiveUnlocked(e){let t=await this.lfs.readdir(e);for(let n of t){let t=e===`/`?`/${n}`:`${e}/${n}`,r=await this.lfs.lstat(t);r.isSymbolicLink()?await this.lfs.unlink(t):r.isDirectory()?await this.rmRecursiveUnlocked(t):await this.lfs.unlink(t)}await this.lfs.rmdir(e)}async stat(e){return this.withKindMismatchRetry(e,()=>this.statInner(e))}async statInner(e){let t=s(e),n=this.findMount(t);if(n){if(n.relParts.length===0)try{let e=await this.lfs.stat(t);return{type:`directory`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs}}catch{return{type:`directory`,size:0,mtime:Date.now(),ctime:Date.now()}}let e=n.relParts.join(`/`);try{let t=await n.backend.stat(e);return{type:t.kind===`directory`?`directory`:`file`,size:t.size,mtime:t.mtime,ctime:t.mtime}}catch(e){j(e,t)}}let r=await this.resolveSymlinks(t);try{let e=await this.lfs.stat(r);return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs}}catch(e){throw M(e,t)}}async exists(e){let t=s(e),n=this.findMount(t);if(n){if(n.relParts.length===0)return!0;try{return await this.stat(t),!0}catch{return!1}}try{return await this.stat(t),!0}catch{try{return await this.lfs.lstat(t),!0}catch{return!1}}}async rename(e,t){return this.withKindMismatchRetryPaths([s(e),s(t)],()=>this.renameInner(e,t))}async renameInner(e,t){let n=s(e),r=s(t),i;try{i=(await this.lstat(n)).type}catch{}let a=this.findMount(n);if(a?.backend.rename){let e=this.findMount(r);if(e&&e.backend===a.backend){try{await a.backend.rename(a.relParts.join(`/`),e.relParts.join(`/`))}catch(e){j(e,n)}this.watcher?.notify([{type:`delete`,path:n,entryType:i},{type:`create`,path:r,entryType:i}]),this.mountIndex.notifyRename(n,r);return}}try{await this.withWriteLock(async()=>{this.markSidecarDirty(n,`prefix`),this.markSidecarDirty(r,`prefix`),await this.lfs.rename(n,r),await this.writeOpfsMetadataSidecarUnlocked()})}catch(e){throw M(e,n)}this.watcher?.notify([{type:`delete`,path:n,entryType:i},{type:`create`,path:r,entryType:i}]),this.mountIndex.notifyRename(n,r)}async readTextFile(e){return await this.readFile(e,{encoding:`utf-8`})}async*walk(e,t,n=0){yield*Z({mountPoints:this.mountPoints,mountIndex:this.mountIndex,realpath:e=>this.realpath(e),readDir:e=>this.readDir(e),stat:e=>this.stat(e)},e,t,n)}async copyFile(e,t){if((await this.stat(e)).type===`directory`)throw new u(`EISDIR`,`is a directory`,e);let n=await this.readFile(e,{encoding:`binary`});await this.writeFile(t,n)}dirname(e){return a(s(e)).dir}basename(e){return a(s(e)).base}async symlink(e,t){let n=s(t);if(this.findMount(n))throw new u(`EINVAL`,`symlinks not supported on mounted filesystems`,n);let{dir:r}=a(n);await this.withWriteLock(async()=>{r!==`/`&&await this.mkdirRecursiveUnlocked(r);try{await this.lfs.symlink(e,n)}catch(t){if(r!==`/`&&t instanceof Error&&t.message.includes(`ENOENT`)){await this.mkdirRecursiveUnlocked(r);try{await this.lfs.symlink(e,n)}catch(e){throw M(e,n)}}else throw M(t,n)}this.markSidecarDirty(n),await this.writeOpfsMetadataSidecarUnlocked()}),this.watcher?.notify([{type:`create`,path:n,entryType:`symlink`}])}async readlink(e){let t=s(e);try{return await this.lfs.readlink(t)}catch(e){throw M(e,t)}}async lstat(e){let t=s(e);if(this.findMount(t)||t===`/`)return this.stat(t);try{let e=await this.lfs.lstat(t);if(e.isSymbolicLink()){let n=await this.lfs.readlink(t);return{type:`symlink`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,isSymlink:!0,symlinkTarget:n}}return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs}}catch(e){throw M(e,t)}}async realpath(e){return X(this.lfs,e=>this.findMount(e)!==null,e)}resolveSymlinks(e){return Ce(this.lfs,e=>this.findMount(e)!==null,e)}},ke=e({FsError:()=>u,FsWatcher:()=>y,MountIndex:()=>D,RestrictedFS:()=>A,VirtualFS:()=>$,joinPath:()=>l,normalizePath:()=>s,pathSegments:()=>o,resolveVfsBackendFromEnv:()=>Q,splitPath:()=>a});export{u as FsError,y as FsWatcher,D as MountIndex,A as RestrictedFS,$ as VirtualFS,ye as a,K as i,l as joinPath,J as n,s as normalizePath,V as o,o as pathSegments,be as r,Q as resolveVfsBackendFromEnv,a as splitPath,ke as t};
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/dist-RekgwRC0.js","assets/rolldown-runtime-Dd_uD5pT.js","assets/safe-buffer-iah92gQe.js","assets/dist-BmTb9jmr.js","assets/backend-hostfs-Com-zF5W.js","assets/api-endpoint-GRCyib6X.js","assets/types-idfTVsM8.js","assets/mount-CqTvny3n.js","assets/preload-helper-Czpn1I53.js","assets/mime-types-ugOWOUZ9.js","assets/base64-DpPqYZJF.js","assets/src-CAWTvdAa.js","assets/proxied-fetch-BGeNrvQ4.js","assets/runtime-env-Dlaokqg1.js","assets/fetch-body-D2PwksUW.js","assets/runtime-env-E-i2SW1s.js","assets/mount-table-store-dY2IfQ5S.js","assets/mount-bridge-client-DZE6sHdr.js","assets/port-bridge-client-BhmNRlRv.js","assets/logger-DDBAeTLF.js"])))=>i.map(i=>d[i]);
2
+ import{n as e}from"./rolldown-runtime-Dd_uD5pT.js";import{t}from"./preload-helper-Czpn1I53.js";import{t as n}from"./logger-DDBAeTLF.js";import{n as r,r as i}from"./tool-ui-DfXu6quJ.js";import{a,i as o,n as s,r as c,t as l}from"./path-utils-DNJG-zQf.js";import{t as u}from"./types-idfTVsM8.js";import{t as d}from"./virtual-device-paths-9EXC9iPp.js";import{t as ee}from"./picker-approval-D89YhXsA.js";import{i as f,r as p,t as m}from"./mount-picker-popup-Bc3ca2Vl.js";import{a as te,i as h,n as g,t as _}from"./mount-table-store-dY2IfQ5S.js";var v=n(`fs-watcher`),ne=0;function re(e,t){return t===`/`||e===t||e.startsWith(t+`/`)}var y=class{registrations=new Map;watch(e,t,n){let r=`fsw-${++ne}`;return this.registrations.set(r,{id:r,basePath:e,filter:t,callback:n}),v.debug(`Watch registered`,{id:r,basePath:e}),()=>{this.registrations.delete(r),v.debug(`Watch unregistered`,{id:r})}}notify(e){if(e.length!==0)for(let[,t]of this.registrations){let n=e.filter(e=>re(e.path,t.basePath)&&t.filter(e.path));if(n.length>0)try{t.callback(n)}catch(e){v.error(`Watch callback error`,{id:t.id,error:e instanceof Error?e.message:String(e)})}}}dispose(){this.registrations.clear(),v.debug(`All watchers disposed`)}get size(){return this.registrations.size}},b=n(`mount-index`),x=400,ie=2e6,ae=`SLICC_MOUNT_INDEX_MAX_DEPTH`,oe=`SLICC_MOUNT_INDEX_MAX_ENTRIES`,S=256,C=class extends Error{cause;constructor(e,t){super(e),this.name=`MountIndexAbortError`,this.cause=t}};function se(e){let t=e.map(([e,t])=>`${e}\u0000${t.kind}`).sort(),n=t.length>S?t.slice(0,S):t;return`${t.length}\u0001${n.join(``)}`}async function ce(e,t){let n=e.isSameEntry;if(typeof n!=`function`)return!1;try{return await n.call(e,t)}catch{return!1}}function w(e,t){return e instanceof Map?e.get(t):e[t]}function le(e){let t=e.trim();if(t===``)return;let n=Number(t);if(!(!Number.isInteger(n)||n<=0))return n}function T(e,t,n){let r=w(e,t);if(r===void 0||r.trim()===``)return n;let i=le(r);return i===void 0?(b.warn(`Ignoring invalid ${t}; expected a positive integer, using default`,{value:r,fallback:n}),n):i}function E(e){return{maxDepth:T(e,ae,x),maxEntries:T(e,oe,ie)}}var D=class{mounts=new Map;listeners=new Set;registerMount(e,t,n=E({})){this.mounts.get(e)?.abortController?.abort();let r=new AbortController,i={handle:t,state:{status:`pending`,indexed:0},files:new Set,directories:new Set,abortController:r,limits:n};this.mounts.set(e,i),this.notifyListeners(),this.indexMount(e,i,r.signal)}unregisterMount(e){let t=this.mounts.get(e);t&&(t.abortController?.abort(),this.mounts.delete(e),this.notifyListeners())}async refreshMount(e,t){let n=this.mounts.get(e);if(!n)throw Error(`No mount at ${e}`);n.abortController?.abort();let r=new AbortController;n.abortController=r,n.state={status:`pending`,indexed:0},n.files.clear(),n.directories.clear(),t&&(n.limits=t),this.notifyListeners(),await this.indexMount(e,n,r.signal)}isReady(e){return this.mounts.get(e)?.state.status===`ready`}isAnyIndexing(){for(let e of this.mounts.values())if(e.state.status===`indexing`||e.state.status===`pending`)return!0;return!1}dispose(){for(let e of this.mounts.values())e.abortController?.abort();this.mounts.clear(),this.listeners.clear()}getState(e){return this.mounts.get(e)?.state}getFiles(e,t){let n=this.mounts.get(e);if(n?.state.status!==`ready`)return;if(!t)return[...n.files];let r=[];for(let e of n.files)t(e)&&r.push(e);return r}getDirectoryEntries(e,t){let n=this.mounts.get(e);if(n?.state.status!==`ready`)return;let r=t===`/`?`/`:t+`/`,i=new Map;for(let e of n.files){if(!e.startsWith(r))continue;let t=e.slice(r.length);t.includes(`/`)||i.set(t,`file`)}for(let e of n.directories){if(!e.startsWith(r))continue;let t=e.slice(r.length);t.includes(`/`)||i.set(t,`directory`)}return[...i.entries()].map(([e,t])=>({name:e,type:t}))}hasPath(e,t){let n=this.mounts.get(e);if(n?.state.status===`ready`)return n.files.has(t)||n.directories.has(t)}notifyWrite(e){let t=this.findMountForPath(e);if(!t)return;let n=this.mounts.get(t);if(n?.state.status!==`ready`)return;n.files.add(e);let r=e;for(;r!==t;){let e=r.lastIndexOf(`/`);if(e<=0)break;r=r.slice(0,e)||`/`,r.length>=t.length&&n.directories.add(r)}}notifyDelete(e){let t=this.findMountForPath(e);if(!t)return;let n=this.mounts.get(t);if(n?.state.status!==`ready`)return;n.files.delete(e),n.directories.delete(e);let r=e+`/`;for(let e of n.files)e.startsWith(r)&&n.files.delete(e);for(let e of n.directories)e.startsWith(r)&&n.directories.delete(e)}notifyRename(e,t){let n=this.findMountForPath(e);if(!n)return;let r=this.mounts.get(n);if(r?.state.status===`ready`){if(r.files.has(e)){r.files.delete(e),r.files.add(t);return}if(r.directories.has(e)){r.directories.delete(e),r.directories.add(t);let n=e+`/`,i=t+`/`;for(let e of[...r.files])e.startsWith(n)&&(r.files.delete(e),r.files.add(i+e.slice(n.length)));for(let e of[...r.directories])e.startsWith(n)&&(r.directories.delete(e),r.directories.add(i+e.slice(n.length)))}}}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}findMountForPath(e){let t;for(let n of this.mounts.keys())(e===n||e.startsWith(n+`/`))&&(!t||n.length>t.length)&&(t=n);return t}notifyListeners(){for(let e of this.listeners)try{e()}catch{}}async indexMount(e,t,n){t.state={status:`indexing`,indexed:0},this.notifyListeners();try{if(await this.walkHandle(e,t.handle,t,n),n.aborted)return;t.state={status:`ready`,indexed:t.files.size+t.directories.size,total:t.files.size+t.directories.size},t.abortController=null,b.info(`Mount indexed`,{path:e,files:t.files.size,directories:t.directories.size})}catch(r){if(n.aborted)return;let i=r instanceof Error?r.message:String(r),a=r instanceof C?r.cause:`indexing-error`;t.state={status:`error`,indexed:0,error:i,abortCause:a},b.error(`Mount indexing failed`,{path:e,error:i,abortCause:a})}this.notifyListeners()}async walkHandle(e,t,n,r,i=0,a=new Map){if(r.aborted)return;this.enforceWalkBounds(i,n),n.directories.add(e);let o=await this.readChildren(t,r,n);if(r.aborted)return;let s=await this.confirmNoCycle(e,t,o,a),c=this.pushAncestor(a,s,e,t);try{await this.walkChildren(e,o,n,r,i,a)}finally{this.popAncestor(a,s,c)}}enforceWalkBounds(e,t){if(e>t.limits.maxDepth)throw new C(`mount indexing aborted: directory nesting exceeded ${t.limits.maxDepth} levels`,`depth-exceeded`);if(t.directories.size+t.files.size>=t.limits.maxEntries)throw new C(`mount indexing aborted: exceeded ${t.limits.maxEntries} entries`,`entries-exceeded`)}async readChildren(e,t,n){let r=e,i=[];for await(let e of r){if(t.aborted)break;if(n.directories.size+n.files.size+i.length>=n.limits.maxEntries)throw new C(`mount indexing aborted: exceeded ${n.limits.maxEntries} entries`,`entries-exceeded`);i.push(e)}return i}async confirmNoCycle(e,t,n,r){let i=se(n),a=r.get(i);if(a){for(let n of a)if(await ce(n.handle,t))throw new C(`mount indexing aborted: self-referential mount cycle detected at ${e} (re-exposes ${n.path})`,`cycle-detected`)}return i}pushAncestor(e,t,n,r){let i=e.get(t);return i||(i=[],e.set(t,i)),i.push({path:n,handle:r,signature:t}),i}popAncestor(e,t,n){n.pop(),n.length===0&&e.delete(t)}async walkChildren(e,t,n,r,i,a){for(let[o,s]of t){if(r.aborted)return;let t=e===`/`?`/${o}`:`${e}/${o}`;s.kind===`file`?(n.files.add(t),n.state.indexed++):s.kind===`directory`&&await this.walkHandle(t,s,n,r,i+1,a),n.state.indexed%500==0&&(this.notifyListeners(),await new Promise(e=>setTimeout(e,0)))}}},O={[d]:{stat:()=>({type:`file`,size:0,mtime:0,ctime:0}),read:e=>(e?.encoding??`utf-8`)===`utf-8`?``:new Uint8Array,readText:()=>``,write:()=>{}}},k=[`/tmp/`],A=class{vfs;allowedPrefixes;readOnlyPrefixes;readGrantPatterns=[];writeEnforcement;constructor(e,t,n=[],r=`hard`){this.vfs=e;let i=e=>{let t=s(e);return t.endsWith(`/`)?t:t+`/`};this.allowedPrefixes=t.map(i),this.readOnlyPrefixes=n.map(i),this.writeEnforcement=r}getAllPrefixes(){let e=this.vfs.listMounts().map(e=>e.endsWith(`/`)?e:e+`/`);return[...this.allowedPrefixes,...this.readOnlyPrefixes,...e,...k]}setReadGrants(e){this.readGrantPatterns=[];for(let t of new Set(e))this.addReadGrant(t)}addReadGrant(e){let t=e.split(`/`),n=[];for(let e=1;e<t.length;e++)n.push(c(t.slice(0,e).join(`/`)||`/`));this.readGrantPatterns.push({pattern:e,regex:c(e),ancestorRegexes:n})}matchesReadGrant(e){return this.readGrantPatterns.some(t=>t.regex.test(e))}leadsToReadGrant(e){return this.readGrantPatterns.some(t=>t.ancestorRegexes.some(t=>t.test(e)))}isAllowed(e){let t=s(e),n=this.getAllPrefixes();return this.matchesReadGrant(t)||this.leadsToReadGrant(t)||n.some(e=>t===e.slice(0,-1)||t.startsWith(e)||t===`/`||e.startsWith(t+`/`))}isAllowedStrict(e){let t=s(e),n=this.getAllPrefixes();return this.matchesReadGrant(t)||n.some(e=>t===e.slice(0,-1)||t.startsWith(e))}isWritable(e){let t=s(e);return[...this.allowedPrefixes,...k].some(e=>t===e.slice(0,-1)||t.startsWith(e))}canWrite(e){return this.isWritable(e)}checkWrite(e){if(this.writeEnforcement!==`sudo-delegated`&&!this.isWritable(e))throw new u(`EACCES`,`permission denied`,s(e))}async resolveAndCheckRead(e){try{let t=await this.vfs.realpath(e);if(!this.isAllowedStrict(t))throw new u(`ENOENT`,`no such file or directory`,s(e));return t}catch(t){throw t instanceof u?t:new u(`ENOENT`,`no such file or directory`,s(e))}}async resolveAndCheckWrite(e){try{let t=await this.vfs.realpath(e);if(!this.isWritable(t)&&!this.isSymlinkEscapeAllowed(t))throw new u(`EACCES`,`permission denied`,s(e));return t}catch(t){throw t instanceof u?t:new u(`EACCES`,`permission denied`,s(e))}}isSymlinkEscapeAllowed(e){return!1}async checkParentRealpathEscape(e){let t=this.vfs.dirname(e),n=this.vfs.basename(e),r;try{r=await this.vfs.realpath(t)}catch(e){if(e instanceof u&&e.code===`EACCES`)throw e;return}let i=r+`/`+n;if(this.isWritable(i))return;let a=s(r)!==s(t);if(!(this.writeEnforcement===`sudo-delegated`&&!a))throw new u(`EACCES`,`permission denied`,s(e))}getUnderlyingFS(){return this.vfs}invalidatePaths(e){this.vfs.invalidatePaths(e)}async flush(){await this.vfs.flush()}isPathUnderMount(e){return this.vfs.isPathUnderMount(e)}async readFile(e,t){let n=O[s(e)];if(n)return n.read(t);if(!this.isAllowedStrict(e))throw new u(`ENOENT`,`no such file or directory`,s(e));let r=await this.resolveAndCheckRead(e);return this.vfs.readFile(r,t)}async readDir(e){if(!this.isAllowed(e))return[];let t=e;if(this.isAllowedStrict(e))try{t=await this.resolveAndCheckRead(e)}catch{return[]}let n=await this.vfs.readDir(t);if(!this.isAllowedStrict(e)){let t=s(e);return n.filter(e=>{let n=t===`/`?`/${e.name}`:`${t}/${e.name}`;return this.isAllowed(n)})}return n}async stat(e){let t=O[s(e)];if(t)return t.stat();if(!this.isAllowed(e))throw new u(`ENOENT`,`no such file or directory`,s(e));if(this.isAllowedStrict(e)){let t=await this.resolveAndCheckRead(e);return this.vfs.stat(t)}return this.vfs.stat(e)}scanPathForSymlinks(e,t){let n=s(e);if(n===`/`)return!1;let r=n.slice(1).split(`/`),i=t?r.length:r.length-1,a=``;for(let e=0;e<i;e++){a=a+`/`+r[e];let t=this.vfs.lstatSync(a);if(t===null)return null;if(t.type===`symlink`)return!0}return!1}statSync(e){let t=O[s(e)];return t?t.stat():!this.isAllowedStrict(e)||this.scanPathForSymlinks(e,!0)!==!1?null:this.vfs.statSync(e)}lstatSync(e){let t=O[s(e)];return t?t.stat():!this.isAllowed(e)||this.scanPathForSymlinks(e,!1)!==!1?null:this.vfs.lstatSync(e)}readDirSync(e){if(!this.isAllowed(e)||this.scanPathForSymlinks(e,!0)!==!1)return null;let t=this.vfs.readDirSync(e);if(t===null)return null;if(this.isAllowedStrict(e))return t;let n=s(e);return t.filter(e=>{let t=n===`/`?`/${e.name}`:`${n}/${e.name}`;return this.isAllowed(t)})}async realpath(e){let t;try{t=await this.vfs.realpath(e)}catch(t){throw t instanceof u?t:new u(`ENOENT`,`no such file or directory`,s(e))}if(!this.isAllowedStrict(t))throw new u(`ENOENT`,`no such file or directory`,s(e));return t}async exists(e){if(O[s(e)])return!0;if(!this.isAllowed(e))return!1;if(this.isAllowedStrict(e))try{await this.resolveAndCheckRead(e)}catch{return!1}return this.vfs.exists(e)}async readTextFile(e){let t=O[s(e)];if(t)return t.readText();if(!this.isAllowedStrict(e))throw new u(`ENOENT`,`no such file or directory`,s(e));let n=await this.resolveAndCheckRead(e);return this.vfs.readTextFile(n)}async*walk(e){if(!this.isAllowed(e))return;let t=e;if(this.isAllowedStrict(e))try{t=await this.resolveAndCheckRead(e)}catch{return}for await(let e of this.vfs.walk(t))this.isAllowed(e)&&(yield e)}async writeFile(e,t,n){let r=O[s(e)];if(r){r.write(t);return}this.checkWrite(e),await this.checkParentRealpathEscape(e);try{(await this.vfs.lstat(e)).type===`symlink`&&await this.resolveAndCheckWrite(e)}catch(e){if(e instanceof u&&e.code===`EACCES`)throw e}return this.vfs.writeFile(e,t,n)}async mkdir(e,t){return this.checkWrite(e),await this.checkParentRealpathEscape(e),this.vfs.mkdir(e,t)}async rm(e,t){this.checkWrite(e);try{(await this.vfs.lstat(e)).type===`symlink`||await this.resolveAndCheckWrite(e)}catch(e){if(e instanceof u&&e.code===`EACCES`)throw e}return this.vfs.rm(e,t)}async rename(e,t){return this.checkWrite(e),this.checkWrite(t),await this.resolveAndCheckWrite(e),await this.checkParentRealpathEscape(t),this.vfs.rename(e,t)}async copyFile(e,t){if(!this.isAllowed(e))throw new u(`ENOENT`,`no such file or directory`,s(e));this.checkWrite(t);let n=await this.resolveAndCheckRead(e);await this.checkParentRealpathEscape(t);try{(await this.vfs.lstat(t)).type===`symlink`&&await this.resolveAndCheckWrite(t)}catch(e){if(e instanceof u&&e.code===`EACCES`)throw e}return this.vfs.copyFile(n,t)}async symlink(e,t){return this.checkWrite(t),await this.checkParentRealpathEscape(t),this.vfs.symlink(e,t)}async readlink(e){if(!this.isAllowedStrict(e))throw new u(`ENOENT`,`no such file or directory`,s(e));let t=await this.vfs.readlink(e),n;if(t.startsWith(`/`))n=s(t);else{let r=this.vfs.dirname(e);n=s(r+`/`+t)}if(!this.isAllowedStrict(n))throw new u(`ENOENT`,`no such file or directory`,s(e));return t}async lstat(e){let t=O[s(e)];if(t)return t.stat();if(!this.isAllowed(e))throw new u(`ENOENT`,`no such file or directory`,s(e));let n=s(e),r=this.vfs.dirname(n),i=this.vfs.basename(n),a;if(r===n)a=r;else try{a=await this.vfs.realpath(r)}catch{throw new u(`ENOENT`,`no such file or directory`,n)}let o=a===`/`?`/${i}`:`${a}/${i}`;if(!this.isAllowed(o))throw new u(`ENOENT`,`no such file or directory`,n);return this.vfs.lstat(o)}watch(e,t,n){if(!this.isAllowed(e))throw new u(`EACCES`,`permission denied`,s(e));let r=this.vfs.getWatcher();if(!r)throw new u(`EINVAL`,`no watcher configured`);return r.watch(s(e),t,n)}dirname(e){return this.vfs.dirname(e)}basename(e){return this.vfs.basename(e)}async mount(e,t,n){return this.checkWrite(e),await this.checkParentRealpathEscape(e),this.vfs.mount(e,t,n)}async unmount(e){return this.checkWrite(e),await this.checkParentRealpathEscape(e),this.vfs.unmount(e)}listMounts(){return this.vfs.listMounts()}getMountIndex(){return this.vfs.getMountIndex()}async refreshMount(e,t){return this.checkWrite(e),this.vfs.refreshMount(e,t)}async dispose(){await this.vfs.dispose()}};function j(e,t){if(e instanceof u){let n=`${e.code}: `,r=e.message;throw r.startsWith(n)&&(r=r.slice(n.length)),e.path&&r.endsWith(` '${e.path}'`)&&(r=r.slice(0,r.length-` '${e.path}'`.length)),new u(e.code,r,t)}throw e}var ue=[`ENOENT`,`EEXIST`,`ENOTDIR`,`EISDIR`,`ENOTEMPTY`,`EINVAL`,`EACCES`,`ELOOP`,`EBUSY`,`EFBIG`,`EBADF`,`ENOSYS`,`EIO`];function M(e,t){if(e instanceof u)return e;{let n=e instanceof Error?e.message:String(e);if(n.includes(`maximum size exceeded`)||n.includes(`call stack size exceeded`))return new u(`EIO`,`internal overflow, not storage: ${n} — reload the session`,t)}let n=e?.code;if(typeof n==`string`){let r=n;if(ue.includes(r)){let n=e instanceof Error?e.message:String(e);return n.startsWith(`${r}: `)&&(n=n.slice(r.length+2),n=n.replace(/, undefined( '[^']*')?$/,``).replace(/ '[^']*'$/,``)),new u(r,n||r,t)}}let r=e instanceof Error?e.message:String(e);return r.includes(`ENOENT`)?new u(`ENOENT`,`no such file or directory`,t):r.includes(`EEXIST`)?new u(`EEXIST`,`file already exists`,t):r.includes(`ENOTDIR`)?new u(`ENOTDIR`,`not a directory`,t):r.includes(`EISDIR`)?new u(`EISDIR`,`is a directory`,t):r.includes(`ENOTEMPTY`)?new u(`ENOTEMPTY`,`directory not empty`,t):r.includes(`ELOOP`)?new u(`ELOOP`,`too many levels of symbolic links`,t):new u(`EINVAL`,r,t)}var de=61440,fe=16384;function N(e){return e===void 0?`absent`:(e&de)===fe?`directory`:`file`}function P(e,t){return t===`absent`?!1:e.kind===`missing`||e.kind!==t}function F(e){let t=e?.mode;return typeof t==`number`?t:void 0}function I(e,t,n,r=new Set){let i=new Set(n);if(r.size>0){for(let t of Object.keys(e.entries??{}))for(let e of r)if(t===e||t.startsWith(`${e}/`)){i.add(t);break}}let a=[];for(let n of i){let r=e.entries?.[n],i=t.entries?.[n];if(!r||!i)continue;let o=N(F(r));o!==N(F(i))&&a.push({path:n,ownIsDirectory:o===`directory`})}return a}var L=3e5,R=5e3,z=Symbol(`mount:timeout`),B=Symbol(`mount:no-panel`),V=class e{kind=`local`;source=void 0;profile=void 0;mountId;handle;closed=!1;constructor(e,t){this.handle=e,this.mountId=t.mountId}static fromHandle(t,n){return new e(t,n)}static async create(t){if(t.isScoop())throw Error(`mount: cannot mount local directories from a scoop (no UI). Ask the cone.`);let n;return n=t.toolContext?await e.acquireHandleViaToolUI(t.toolContext,t.targetPath):t.isExtension?await e.acquireHandleViaPopup():await e.acquireHandleViaDirectPicker(),new e(n,{mountId:t.mountId})}static async acquireHandleViaPopup(){try{let e=await p();if(e.cancelled)throw Error(`mount: cancelled`);if(e.error)throw Error(`mount: ${e.error}`);if(e.handleInIdb&&typeof e.idbKey==`string`){let t=await m(e.idbKey);if(!t)throw Error(`mount: no directory handle found in storage`);return await f(t),t}throw Error(`mount: unexpected popup result`)}catch(e){throw Error(`mount: ${e instanceof Error?e.message:String(e)}`)}}static async acquireHandleViaDirectPicker(){if(typeof window>`u`||!(`showDirectoryPicker`in window))throw Error(`mount: local picker requires a user gesture in the panel (unavailable in this runtime). Ask the agent to mount it instead.`);try{return await window.showDirectoryPicker({mode:`readwrite`})}catch(e){throw e instanceof Error&&e.name===`AbortError`?Error(`mount: cancelled`):Error(`mount: ${e instanceof Error?e.message:String(e)}`)}}static async acquireHandleViaToolUI(t,n){let a=i.generateId(),o=!1,s=!1,c=r({id:a,html:ee(`directory`,[],n),onAction:(t,n)=>e.resolveApprovalAction(t,n)},t.onUpdate).catch(e=>{if(o)return z;if(s)return B;throw e}),l,u=new Promise(e=>{l=setTimeout(()=>{o=!0,i.cancel(a,`mount: timed out`),e(z)},L)}),d=new Promise(e=>{i.waitForMount(a,R).then(()=>{},()=>{o||(s=!0,i.cancel(a,`mount: panel did not render the approval card`),e(B))})}),f=await Promise.race([c,u,d]);if(l&&clearTimeout(l),f===z)throw Error(`mount: timed out after ${Math.round(L/6e4)} minute(s) waiting for user approval`);if(f===B)throw Error(`mount: chat panel did not render the approval card — open the chat panel and retry`);if(!f)throw Error(`mount: tool UI not available`);let p=f;if(p.denied)throw Error(`mount: denied by user`);if(p.cancelled)throw Error(`mount: cancelled`);if(p.error)throw Error(`mount: ${p.error}`);if(!p.handle)throw Error(`mount: no directory selected`);return p.handle}static async resolveApprovalAction(e,t){if(e!==`approve`)return{denied:!0};let n=t;if(n?.handleInIdb&&typeof n.idbKey==`string`)try{let e=await m(n.idbKey);return e?(await f(e),{approved:!0,handle:e}):{error:`No directory handle found in storage`}}catch(e){return{error:e instanceof Error?e.message:String(e)}}if(n?.cancelled)return{cancelled:!0};if(n?.error)return{error:String(n.error)};try{return{approved:!0,handle:await window.showDirectoryPicker({mode:`readwrite`})}}catch(e){return e instanceof Error&&e.name===`AbortError`?{cancelled:!0}:{error:e instanceof Error?e.message:String(e)}}}getHandle(){return this.handle}assertOpen(e){if(this.closed)throw new u(`EBADF`,`mount closed`,e)}splitPath(e){return e.replace(/^\/+/,``).replace(/\/+$/,``).split(`/`).filter(e=>e.length>0)}async resolveDir(e,t=!1){let n=this.splitPath(e),r=this.handle;for(let i of n)try{r=await r.getDirectoryHandle(i,{create:t})}catch(t){throw this.toFsError(t,e)}return r}async resolveFile(e,t=!1){let n=this.splitPath(e);if(n.length===0)throw new u(`EISDIR`,`is a directory`,e);let r=n.pop(),i=this.handle;for(let r of n)try{i=await i.getDirectoryHandle(r,{create:t})}catch(t){throw this.toFsError(t,e)}try{return await i.getFileHandle(r,{create:t})}catch(t){throw this.toFsError(t,e)}}toFsError(e,t){if(e instanceof u)return e;if(e instanceof DOMException){if(e.name===`NotFoundError`)return new u(`ENOENT`,`no such file or directory`,t);if(e.name===`TypeMismatchError`)return new u(`ENOTDIR`,`not a directory`,t);if(e.name===`NotAllowedError`)return new u(`EACCES`,`permission denied`,t);if(e.name===`InvalidModificationError`)return new u(`ENOTEMPTY`,`directory not empty`,t)}if(e instanceof Error){if(e.name===`NotFound`||e.name===`NotFoundError`)return new u(`ENOENT`,`no such file or directory`,t);if(e.name===`TypeMismatch`||e.name===`TypeMismatchError`)return new u(`ENOTDIR`,`not a directory`,t);if(e.name===`InvalidModification`||e.name===`InvalidModificationError`)return new u(`ENOTEMPTY`,`directory not empty`,t)}return new u(`EINVAL`,e instanceof Error?e.message:String(e),t)}async readDir(e){this.assertOpen(e);let t=await this.resolveDir(e),n=[];for await(let[e,r]of t)if(r.kind===`file`){let t=await r.getFile();n.push({name:e,kind:`file`,size:t.size,lastModified:t.lastModified})}else n.push({name:e,kind:`directory`});return n}async readFile(e){this.assertOpen(e);let t=await(await this.resolveFile(e)).getFile();return new Uint8Array(await t.arrayBuffer())}async writeFile(e,t){this.assertOpen(e);let n=await(await this.resolveFile(e,!0)).createWritable();await n.write(t),await n.close()}async stat(e){if(this.assertOpen(e),this.splitPath(e).length===0)return{kind:`directory`,size:0,mtime:0};try{let t=await(await this.resolveFile(e)).getFile();return{kind:`file`,size:t.size,mtime:t.lastModified}}catch{}return await this.resolveDir(e),{kind:`directory`,size:0,mtime:0}}async mkdir(e){this.assertOpen(e),await this.resolveDir(e,!0)}async remove(e,t){this.assertOpen(e);let n=this.splitPath(e);if(n.length===0)throw new u(`EINVAL`,`cannot remove mount root`,e);let r=n.pop(),i=n.join(`/`),a=await this.resolveDir(i||`/`);try{await a.removeEntry(r,{recursive:t?.recursive??!1})}catch(t){throw this.toFsError(t,e)}}async refresh(){return this.assertOpen(`/`),{added:[],removed:[],changed:[],unchanged:0,errors:[]}}describe(){return{displayName:this.handle.name}}async close(){this.closed=!0}};function H(e,t){return e===t||e.startsWith(t===`/`?`/`:`${t}/`)}var pe=`/.metadata.json`;function U(e){return e.entries&&delete e.entries[pe],e}function me(e,t,n){let r=t.entries??{},i={...e.entries??{}};`/`in r&&(i[`/`]=r[`/`]);for(let e of n.paths)e in r?i[e]=r[e]:delete i[e];for(let e of n.prefixes){for(let t of Object.keys(i))H(t,e)&&delete i[t];for(let t of Object.keys(r))H(t,e)&&(i[t]=r[t])}let{entries:a,...o}=t;return U({...o,entries:i})}var he=61440,W=16384,G=32768,ge=40960;async function K(e,t,n){let r={kindFixed:[],sizesFixed:0,dropped:0,selfEntryDropped:!1,inosReassigned:0,nlinksFixed:0,changed:!1},i=e.entries??{};for(let[e,a]of Object.entries(i)){if(n?.(),e===`/`||typeof a!=`object`||!a)continue;if(e===`/.metadata.json`){delete i[e],r.selfEntryDropped=!0,r.changed=!0;continue}let o=a,s=(o.mode??0)&he;if(s===ge){q(o,r);continue}let c=await t(e);if(c.kind===`missing`){delete i[e],r.dropped+=1,r.changed=!0;continue}q(o,r),ve(e,o,s,c,r)}return _e(i,r),r}function _e(e,t){let n=0;for(let t of Object.values(e)){let e=t;typeof e?.ino==`number`&&(n=Math.max(n,e.ino)),typeof e?.data==`number`&&(n=Math.max(n,e.data))}let r=n+1,i=new Set;for(let[n,a]of Object.entries(e)){if(typeof a!=`object`||!a)continue;let e=a;if(n===`/`){typeof e.ino==`number`&&i.add(e.ino);continue}let o=e.ino;if(typeof o==`number`&&o!==0&&!i.has(o)){i.add(o);continue}e.ino=r,e.data=r+1,i.add(r),r+=2,t.inosReassigned+=1,t.changed=!0}}function q(e,t){e.nlink||(e.nlink=1,t.nlinksFixed+=1,t.changed=!0)}function ve(e,t,n,r,i){if(n===G&&r.kind===`directory`){t.mode=((t.mode??0)&511||493)|W,i.kindFixed.push(`${e} file→dir`),i.changed=!0;return}if(n===W&&r.kind===`file`){t.mode=((t.mode??0)&511||420)|G,t.size=r.size,i.kindFixed.push(`${e} dir→file`),i.changed=!0;return}n===G&&r.kind===`file`&&typeof t.size==`number`&&t.size!==r.size&&(t.size=r.size,i.sizesFixed+=1,i.changed=!0)}function J(e){return async t=>{let n=t.split(`/`).filter(Boolean),r=e;for(let e=0;e<n.length-1;e+=1)try{r=await r.getDirectoryHandle(n[e])}catch{return{kind:`missing`}}let i=n[n.length-1];if(i===void 0)return{kind:`directory`};try{return{kind:`file`,size:(await(await r.getFileHandle(i)).getFile()).size}}catch{}try{return await r.getDirectoryHandle(i),{kind:`directory`}}catch{return{kind:`missing`}}}}async function ye(e,t,n){try{return await e()}catch(r){let i=null;try{i=await t()}catch{}if(!i?.changed)throw r;return n(i),await e()}}async function be(e,t){let n;try{let t=await e.getFileHandle(`.metadata.json`),r=JSON.parse(await(await t.getFile()).text());if(!r||typeof r!=`object`||!r.entries)return null;n=r}catch{return null}let r=await K(n,J(e),t);if(!r.changed)return r;let i=await(await e.getFileHandle(`.metadata.json`,{create:!0})).createWritable();return await i.write(JSON.stringify(n)),await i.close(),r}async function xe(e,t,n,r){try{return await e.lstat(t)}catch(e){let t=M(e,r);if(t.code===`ENOENT`&&n)return null;throw t}}async function Se(e,t,n){let r;try{r=await e.readlink(t)}catch(e){throw M(e,n)}return r.startsWith(`/`)?s(r):s(l(a(t).dir,r))}async function Y(e,t,n,r,i,a){let o=t===`/`?`/${n}`:`${t}/${n}`;for(;;){let t=await xe(e,o,r,i);if(t===null||!t.isSymbolicLink())return{resolved:o,hops:a};if(++a>10)throw new u(`ELOOP`,`too many symbolic links encountered`,i);o=await Se(e,o,i)}}async function X(e,t,n){let r=s(n);if(t(r))return r;let i=r.split(`/`).filter(Boolean),a=`/`,o=0;for(let t=0;t<i.length;t++){let n=await Y(e,a,i[t],t===i.length-1,r,o);a=n.resolved,o=n.hops}return a}async function Ce(e,t,n){return t(n)?n:X(e,t,n)}function we(e,t,n){return e.size===0||!e.has(n)||!t.isReady(n)?!1:!Array.from(e.keys()).some(e=>e!==n&&e.startsWith(n+`/`))}async function Te(e,t){try{return await e(t)}catch{return t}}async function*Z(e,t,n,r=0){let i=s(t);if(we(e.mountPoints,e.mountIndex,i)){let t=e.mountIndex.getFiles(i);if(t){for(let e of t)yield e;return}}let a=n??new Set;if(r>64||a.size>=1e5)return;let o=await Te(t=>e.realpath(t),i);if(a.has(o))return;a.add(o);let c=await e.readDir(i);for(let t of c)yield*Ee(e,t,i===`/`?`/${t.name}`:`${i}/${t.name}`,a,r+1)}async function*Ee(e,t,n,r,i){if(t.type===`file`){yield n;return}if(t.type===`symlink`){yield*De(e,n,r,i);return}yield*Z(e,n,r,i)}async function*De(e,t,n,r){try{let i=await e.stat(t);i.type===`file`?yield t:i.type===`directory`&&(yield*Z(e,t,n,r))}catch{}}function Q(){try{if(typeof globalThis.navigator?.storage?.getDirectory==`function`)return`opfs`}catch{}return`memory`}function Oe(e,t){switch(e.kind){case`local`:case`proc`:return{kind:`local`,mountId:e.mountId,idbHandleKey:t};case`hostfs`:return{kind:`hostfs`,mountId:e.mountId,hostPath:e.getHostPath()};default:return{kind:e.kind===`s3`?`s3`:e.kind===`aem`?`aem`:`da`,mountId:e.mountId,source:e.source,profile:e.profile??`default`}}}var $=class e{lfs;lfsSync;rawLfs=null;rawLfsSync=null;_ready;_readyResolved=!1;backend;mountPoints=new Map;opfsBackendFs=null;opfsHandle=null;mountRoot=``;internalMounts=new Set;watcher=null;dbName;mountSyncChannel=null;mountIndex=new D;static writeChains=new Map;onRepairProgress;constructor(t,n,r,i,a){if(this.dbName=t,this.onRepairProgress=a,this.backend=r===`opfs`?`opfs`:`memory`,this.lfs=this.makeDeferredLfs(),this.lfsSync=this.makeDeferredLfsSync(),this._ready=this.backend===`opfs`?e.initOpfsBackend(this,i,n===!0):e.initMemoryBackend(this,t,n===!0),this._ready.then(()=>{this._readyResolved=!0},()=>{}),typeof BroadcastChannel<`u`)try{this.mountSyncChannel=new BroadcastChannel(`vfs-mount-sync:${t}`),this.mountSyncChannel.onmessage=e=>{let{type:t,path:n,descriptor:r}=e.data??{};if(t===`mount`&&typeof n==`string`&&r)this.reconstructBackendFromDescriptor(r,n).then(e=>{this.mountPoints.set(n,e),e.kind===`local`&&this.mountIndex.registerMount(n,e.getHandle()),this.watcher?.notify([{type:`modify`,path:n,entryType:`directory`}])}).catch(()=>{});else if(t===`unmount`&&typeof n==`string`){let e=this.mountPoints.get(n);this.mountPoints.delete(n),this.mountIndex.unregisterMount(n),e?.close(),this.watcher?.notify([{type:`modify`,path:n,entryType:`directory`}])}}}catch{}}static async initOpfsBackend(n,r,i){let a=r??await e.acquireOpfsHandle(n.dbName,i);await e.seedOpfsMetadataSidecarIfMissing(a);let[o,{WebAccess:s}]=await Promise.all([t(()=>import(`./dist-RekgwRC0.js`).then(e=>e.t),__vite__mapDeps([0,1,2])),t(()=>import(`./dist-BmTb9jmr.js`),__vite__mapDeps([3,0,1,2]))]);await e.ensureRootMount(o);let c=`/__opfs__/${n.dbName}`,l=e.opfsBackends.get(n.dbName);if(l&&i){try{o.umount(c)}catch{}e.opfsBackends.delete(n.dbName),l=void 0}if(!l){let r=()=>o.resolveMountConfig({backend:s,handle:a,metadata:`/.metadata.json`}),{resolveWithSidecarRepair:i,repairOpfsMetadataSidecar:u}=await t(async()=>{let{resolveWithSidecarRepair:e,repairOpfsMetadataSidecar:t}=await import(`./sidecar-repair-CwI_pMMe.js`);return{resolveWithSidecarRepair:e,repairOpfsMetadataSidecar:t}},[]);try{let e=await n.withWriteLock(()=>u(a,n.onRepairProgress));e?.changed&&console.warn(`[virtual-fs] repaired metadata sidecar before mount (#2146)`,{dbName:n.dbName,kindFixed:e.kindFixed,sizesFixed:e.sizesFixed,dropped:e.dropped,inosReassigned:e.inosReassigned,nlinksFixed:e.nlinksFixed,selfEntryDropped:e.selfEntryDropped})}catch{}let d=await i(r,()=>n.withWriteLock(()=>u(a,n.onRepairProgress)),e=>console.warn(`[virtual-fs] repaired poisoned metadata sidecar; retrying mount`,{dbName:n.dbName,kindFixed:e.kindFixed,sizesFixed:e.sizesFixed,dropped:e.dropped,nlinksFixed:e.nlinksFixed,selfEntryDropped:e.selfEntryDropped}));try{o.mount(c,d)}catch{}l={backendFs:d,refs:0,sidecarDirty:{paths:new Set,prefixes:new Set}},e.opfsBackends.set(n.dbName,l)}l.refs+=1,n.opfsBackendFs=l.backendFs.index?l.backendFs:null,n.opfsHandle=a,n.mountRoot=c,n.rawLfs=o.promises,n.rawLfsSync=o}static async initMemoryBackend(n,r,i){let a=await t(()=>import(`./dist-RekgwRC0.js`).then(e=>e.t),__vite__mapDeps([0,1,2]));await e.ensureRootMount(a);let o=`/__zenfs__/${r}`,s=e.memoryBackends.get(r);if(s&&i){try{a.umount(o)}catch{}e.memoryBackends.delete(r),s=void 0}s||(s={store:a.InMemory.create({label:r}),refs:0},e.memoryBackends.set(r,s)),s.refs+=1;try{a.mount(o,s.store)}catch{}n.mountRoot=o,n.rawLfs=a.promises,n.rawLfsSync=a,n.opfsBackendFs=null,n.opfsHandle=null}static rootMountReady=null;static memoryBackends=new Map;static opfsBackends=new Map;static async ensureRootMount(t){return e.rootMountReady===null&&(e.rootMountReady=(async()=>{await t.configureSingle({backend:t.InMemory,label:`__vfs_root__`})})()),e.rootMountReady}prefix(e){return this.mountRoot?e===`/`?this.mountRoot:this.mountRoot+e:e}unprefix(e){return!this.mountRoot||!e.startsWith(this.mountRoot)?e:e.slice(this.mountRoot.length)||`/`}makeDeferredLfs(){let e=e=>this.prefix(e),t=e=>this.unprefix(e),n=()=>{if(!this.rawLfs)throw Error(`VirtualFS used before init resolved`);return this.rawLfs};return{readFile:(t,r)=>this._readyResolved?n().readFile(e(t),r):this._ready.then(()=>n().readFile(e(t),r)),writeFile:(t,r,i)=>this._readyResolved?n().writeFile(e(t),r,i):this._ready.then(()=>n().writeFile(e(t),r,i)),readdir:t=>this._readyResolved?n().readdir(e(t)):this._ready.then(()=>n().readdir(e(t))),mkdir:(t,r)=>this._readyResolved?n().mkdir(e(t),r):this._ready.then(()=>n().mkdir(e(t),r)),rmdir:t=>this._readyResolved?n().rmdir(e(t)):this._ready.then(()=>n().rmdir(e(t))),unlink:t=>this._readyResolved?n().unlink(e(t)):this._ready.then(()=>n().unlink(e(t))),rename:(t,r)=>this._readyResolved?n().rename(e(t),e(r)):this._ready.then(()=>n().rename(e(t),e(r))),stat:t=>this._readyResolved?n().stat(e(t)):this._ready.then(()=>n().stat(e(t))),lstat:t=>this._readyResolved?n().lstat(e(t)):this._ready.then(()=>n().lstat(e(t))),symlink:(t,r)=>{let i=t.startsWith(`/`)?e(t):t;return this._readyResolved?n().symlink(i,e(r)):this._ready.then(()=>n().symlink(i,e(r)))},readlink:async r=>(this._readyResolved||await this._ready,t(await n().readlink(e(r)))),truncate:async(t,r)=>{this._readyResolved||await this._ready;let i=n();typeof i.truncate==`function`&&await i.truncate(e(t),r)},realpath:async r=>{this._readyResolved||await this._ready;let i=n();return typeof i.realpath==`function`?t(await i.realpath(e(r))):e(r)}}}makeDeferredLfsSync(){let e=e=>this.prefix(e),t=e=>this.unprefix(e);return{readdirSync:t=>{let n=this.rawLfsSync;return n?.readdirSync?n.readdirSync(e(t)):void 0},statSync:t=>{let n=this.rawLfsSync;return n?.statSync?n.statSync(e(t)):void 0},lstatSync:t=>{let n=this.rawLfsSync;return n?.lstatSync?n.lstatSync(e(t)):void 0},readlinkSync:n=>{let r=this.rawLfsSync;return r?.readlinkSync?t(r.readlinkSync(e(n))):void 0}}}static async seedOpfsMetadataSidecarIfMissing(e){let t=`.metadata.json`;try{await e.getFileHandle(t);return}catch(e){if(e?.name!==`NotFoundError`)throw e}let n=await(await e.getFileHandle(t,{create:!0})).createWritable(),r=JSON.stringify({version:1,maxSize:4294967295,entries:{}});await n.write(r),await n.close()}static async acquireOpfsHandle(e,t){let n=navigator.storage;if(!n?.getDirectory)throw new u(`EINVAL`,`OPFS is not available in this environment`);let r=await n.getDirectory();if(t)try{await r.removeEntry(e,{recursive:!0})}catch{}return r.getDirectoryHandle(e,{create:!0})}static _createSyncForTests(t){return new e(t)}static async create(t){let n=t?.dbName??`browser-fs`,r=t?.wipe===!0,i=t?.backend??Q(),a=new e(n,r,i,void 0,t?.onRepairProgress);return await a._ready,r&&await _().catch(()=>{}),a}async flush(){await this.writeOpfsMetadataSidecar()}async writeOpfsMetadataSidecar(){this.backend===`opfs`&&await this.withWriteLock(()=>this.writeOpfsMetadataSidecarUnlocked())}async writeOpfsMetadataSidecarUnlocked(){if(this.backend!==`opfs`)return;let t=this.opfsBackendFs,n=this.opfsHandle;if(!t||!n)return;let r=t.index.toJSON(),i=e.opfsBackends.get(this.dbName)?.sidecarDirty,a=r;if(i){let e=null;try{let t=await n.getFileHandle(`.metadata.json`),r=JSON.parse(await(await t.getFile()).text());r&&typeof r==`object`&&r.entries&&(e=r)}catch{}e&&(await this.auditDirtyKindFlips(r,e,i,n),a=me(e,r,i))}let o=JSON.stringify(U(a)),s=await(await n.getFileHandle(`.metadata.json`,{create:!0})).createWritable();await s.write(o),await s.close(),i&&(i.paths.clear(),i.prefixes.clear())}async auditDirtyKindFlips(e,t,n,r){let i=I(e,t,n.paths,n.prefixes);if(i.length===0)return;let a=J(r),o=this.opfsBackendFs;for(let n of i){let r=await a(n.path).catch(()=>null);if(r!==null&&r.kind!==`missing`&&r.kind===`directory`===n.ownIsDirectory)continue;let i=t.entries?.[n.path];e.entries&&i!==void 0&&(e.entries[n.path]=i);let s=r!==null&&r.kind!==`missing`;s&&(o?.index?.delete(n.path),o?._handles?.delete(n.path)),console.warn(`[virtual-fs] refused to flush in-memory kind flip over sidecar record (#2006)`,{path:n.path,reality:r?.kind??`unverifiable`,evicted:s})}}markSidecarDirty(t,n=`path`){if(this.backend!==`opfs`)return;let r=e.opfsBackends.get(this.dbName)?.sidecarDirty;if(!r)return;let i=s(t);(n===`prefix`?r.prefixes:r.paths).add(i);let{dir:o}=a(i);for(;o!==`/`;)r.paths.add(o),o=a(o).dir}invalidatePaths(e){if(this.backend!==`opfs`||!this.opfsBackendFs)return;let t=this.opfsBackendFs;for(let n of e){let e=s(n);t.index.delete(e),t._handles?.delete(e),this.markSidecarDirty(e)}}async withKindMismatchRetry(e,t){return this.withKindMismatchRetryPaths([e],t)}async withKindMismatchRetryPaths(e,t){try{return await t()}catch(n){let r=n?.code;if(r!==`EISDIR`&&r!==`ENOTDIR`&&r!==`EINVAL`)throw n;for(let n of e)if(await this.reconcileKindMismatch(n).catch(()=>!1))return await t();throw n}}async reconcileKindMismatch(e){if(this.backend!==`opfs`)return!1;let t=this.opfsBackendFs,n=this.opfsHandle;if(!t?.index||!n)return!1;let r=s(e),i=r;try{i=await this.resolveSymlinks(r)}catch{}let a=await J(n)(i),o=N(t.index.get(i)?.mode),c=t._handles?.get(i),l=c?.kind===`directory`?`directory`:c?.kind===`file`?`file`:`absent`,u=P(a,o),d=P(a,l);if(!u&&!d)return!1;if(t.index.delete(i),t._handles?.delete(i),o===`directory`||l===`directory`){let e=`${i}/`;for(let n of[...t.index.keys()])n.startsWith(e)&&t.index.delete(n);if(t._handles)for(let n of[...t._handles.keys()])n.startsWith(e)&&t._handles.delete(n)}return this.markSidecarDirty(i),console.warn(`[virtual-fs] reconciled in-memory kind mismatch (#2006)`,{path:i,reality:a.kind,indexHeld:o,handleHeld:l}),!0}canWrite(e){return!0}setWatcher(e){this.watcher=e}getWatcher(){return this.watcher}async watch(e,t){let n=this.watcher;if(!n)throw new u(`ENOSYS`,`no FsWatcher attached to this VirtualFS`);let r=e.map(e=>n.watch(e,()=>!0,t));return()=>{for(let e of r)e()}}async dispose(){if(this.mountSyncChannel?.close(),this.mountSyncChannel=null,this.watcher?.dispose(),this.watcher=null,this.mountIndex.dispose(),await this.writeOpfsMetadataSidecar(),this.mountRoot){let n=this.backend===`opfs`?e.opfsBackends:e.memoryBackends,r=n.get(this.dbName);if(r&&(--r.refs,r.refs<=0)){n.delete(this.dbName);try{(await t(()=>import(`./dist-RekgwRC0.js`).then(e=>e.t),__vite__mapDeps([0,1,2]))).umount(this.mountRoot)}catch{}}}}readDirSync(e){let t=s(e);if(this.findMount(t))return null;let n=this.lfsSync;if(typeof n.readdirSync!=`function`||typeof n.lstatSync!=`function`)return null;try{let e=n.readdirSync(t),r=[];for(let i of e){let e=t===`/`?`/${i}`:`${t}/${i}`;try{let t=n.lstatSync(e),a=t.isSymbolicLink()?`symlink`:t.isDirectory()?`directory`:`file`;r.push({name:i,type:a})}catch{}}return r}catch{return null}}statSync(e){let t=s(e);if(this.findMount(t))return null;let n=this.lfsSync;if(typeof n.statSync!=`function`||typeof n.lstatSync!=`function`||typeof n.readlinkSync!=`function`)return null;if(t===`/`)try{let e=n.statSync(t);return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs}}catch{return null}let r=t;for(let e=0;e<=10;e++){let e;try{e=n.lstatSync(r)}catch{return null}if(!e.isSymbolicLink())return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs};let t;try{t=n.readlinkSync(r)}catch{return null}r=t.startsWith(`/`)?s(t):s(l(a(r).dir,t))}return null}lstatSync(e){let t=s(e);if(this.findMount(t))return null;let n=this.lfsSync;if(typeof n.lstatSync!=`function`)return null;if(t===`/`)return this.statSync(t);try{let e=n.lstatSync(t);if(e.isSymbolicLink()){let r=n.readlinkSync?n.readlinkSync(t):``;return{type:`symlink`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,isSymlink:!0,symlinkTarget:r}}return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs}}catch{return null}}async mount(e,t,n){let r=s(e);if(this.mountPoints.has(r))throw new u(`EEXIST`,`mount point is already mounted`,r);try{if((await this.lstat(r)).type!==`directory`)throw new u(`ENOTDIR`,`mount point must be a directory`,r);if((await this.readDir(r)).length>0)throw new u(`ENOTEMPTY`,`mount point must be empty to avoid shadowing existing files`,r)}catch(e){if(!(e instanceof u)||e.code!==`ENOENT`)throw e}let{dir:i}=a(r);i!==`/`&&await this.mkdir(i,{recursive:!0});try{await this.lfs.mkdir(r)}catch{}if(this.mountPoints.set(r,t),t.kind===`local`){let e=n?.limits??E(n?.env??{});this.mountIndex.registerMount(r,t.getHandle(),e)}let o=Oe(t,r);try{this.mountSyncChannel?.postMessage({type:`mount`,path:r,descriptor:o})}catch{}if(this.watcher?.notify([{type:`modify`,path:r,entryType:`directory`}]),t.kind!==`hostfs`)try{let e={targetPath:r,descriptor:o,createdAt:Date.now()},n=t.kind===`local`?t.getHandle():void 0;await te(e,n)}catch{}}async unmount(e){let t=s(e),n=this.mountPoints.get(t);this.mountPoints.delete(t),this.mountIndex.unregisterMount(t);try{this.mountSyncChannel?.postMessage({type:`unmount`,path:t})}catch{}this.watcher?.notify([{type:`modify`,path:t,entryType:`directory`}]),await n?.close();try{await h(t)}catch{}}async reconstructBackendFromDescriptor(e,n){switch(e.kind){case`local`:{let t=await g(e.idbHandleKey);if(!t)throw Error(`no handle stored for ${e.idbHandleKey}`);return V.fromHandle(t,{mountId:e.mountId})}case`hostfs`:{let{HostFsMountBackend:r}=await t(async()=>{let{HostFsMountBackend:e}=await import(`./backend-hostfs-Com-zF5W.js`);return{HostFsMountBackend:e}},__vite__mapDeps([4,5,6]));return new r({targetPath:n,hostPath:e.hostPath,mountId:e.mountId})}case`s3`:{let{S3MountBackend:n,RemoteMountCache:r,makeSignedFetchS3:i}=await t(async()=>{let{S3MountBackend:e,RemoteMountCache:t,makeSignedFetchS3:n}=await import(`./mount-CqTvny3n.js`);return{S3MountBackend:e,RemoteMountCache:t,makeSignedFetchS3:n}},__vite__mapDeps([7,8,9,10,11,12,1,13,14,5,15,6,16,17,18,19])),a=new r({mountId:e.mountId,ttlMs:3e4});return new n({source:e.source,profile:e.profile,cache:a,mountId:e.mountId,signedFetch:i(e.profile)})}case`da`:{let{DaMountBackend:n,RemoteMountCache:r,makeSignedFetchDa:i}=await t(async()=>{let{DaMountBackend:e,RemoteMountCache:t,makeSignedFetchDa:n}=await import(`./mount-CqTvny3n.js`);return{DaMountBackend:e,RemoteMountCache:t,makeSignedFetchDa:n}},__vite__mapDeps([7,8,9,10,11,12,1,13,14,5,15,6,16,17,18,19])),a=new r({mountId:e.mountId,ttlMs:3e4});return new n({source:e.source,profile:e.profile,cache:a,mountId:e.mountId,signedFetch:i()})}case`aem`:{let{AemMountBackend:n,RemoteMountCache:r,makeSignedFetchDa:i}=await t(async()=>{let{AemMountBackend:e,RemoteMountCache:t,makeSignedFetchDa:n}=await import(`./mount-CqTvny3n.js`);return{AemMountBackend:e,RemoteMountCache:t,makeSignedFetchDa:n}},__vite__mapDeps([7,8,9,10,11,12,1,13,14,5,15,6,16,17,18,19])),a=new r({mountId:e.mountId,ttlMs:3e4});return new n({source:e.source,profile:e.profile,cache:a,mountId:e.mountId,signedFetch:i()})}}}listMounts(){let e=[];for(let t of this.mountPoints.keys())this.internalMounts.has(t)||e.push(t);return e}listInternalMounts(){return[...this.internalMounts]}listMountPoints(){let e=[];for(let[t,n]of this.mountPoints)this.internalMounts.has(t)||e.push({path:t,kind:n.kind});return e}async mountInternal(e,t){let n=s(e);if(this.mountPoints.has(n))throw new u(`EEXIST`,`mount point is already mounted`,n);let{dir:r}=a(n);r!==`/`&&await this.mkdir(r,{recursive:!0});try{await this.lfs.mkdir(n)}catch{}this.mountPoints.set(n,t),this.internalMounts.add(n),this.watcher?.notify([{type:`modify`,path:n,entryType:`directory`}])}async unmountInternal(e){let t=s(e);if(!this.internalMounts.has(t))throw new u(`ENOENT`,`not an internal mount point`,t);let n=this.mountPoints.get(t);this.mountPoints.delete(t),this.internalMounts.delete(t),this.watcher?.notify([{type:`modify`,path:t,entryType:`directory`}]),await n?.close()}getMountIndex(){return this.mountIndex}async refreshMount(e,t){let n=s(e),r=this.mountPoints.get(n);if(!r)throw new u(`ENOENT`,`not a mount point`,n);let i=await r.refresh(t);return r.kind===`local`&&await this.mountIndex.refreshMount(n,E(t?.env??{})),this.watcher?.notify([{type:`modify`,path:n,entryType:`directory`}]),i}isPathUnderMount(e){for(let t of this.mountPoints.keys())if(e===t||e.startsWith(t+`/`))return!0;return!1}findMount(e){let t=null;for(let[n,r]of this.mountPoints)(e===n||e.startsWith(n+`/`))&&(!t||n.length>t.mountPath.length)&&(t={mountPath:n,backend:r});return t?e===t.mountPath?{path:t.mountPath,backend:t.backend,relParts:[]}:{path:t.mountPath,backend:t.backend,relParts:e.slice(t.mountPath.length+1).split(`/`).filter(Boolean)}:null}async readFile(e,t){return this.withKindMismatchRetry(e,()=>this.readFileInner(e,t))}async readFileInner(e,t){let n=s(e),r=this.findMount(n);if(r){if(r.relParts.length===0)throw new u(`EISDIR`,`is a directory`,n);let e=r.relParts.join(`/`);try{let n=await r.backend.readFile(e);return(t?.encoding??`utf-8`)===`utf-8`?new TextDecoder(`utf-8`).decode(n):n}catch(e){j(e,n)}}let i=await this.resolveSymlinks(n);try{return(t?.encoding??`utf-8`)===`utf-8`?await this.lfs.readFile(i,{encoding:`utf8`}):await this.lfs.readFile(i)}catch(e){throw M(e,n)}}async writeFile(e,t,n){return this.withKindMismatchRetry(e,()=>this.writeFileInner(e,t,n))}async writeFileInner(e,t,n){let r=s(e),i=this.findMount(r);if(i){if(i.relParts.length===0)throw new u(`EISDIR`,`is a directory`,r);let e=i.relParts.join(`/`),n=!1;try{await this.stat(r),n=!0}catch{}let a=typeof t==`string`?new TextEncoder().encode(t):t instanceof Uint8Array?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):new Uint8Array(t);try{await i.backend.writeFile(e,a)}catch(e){j(e,r)}this.watcher?.notify([{type:n?`modify`:`create`,path:r,entryType:`file`}]),this.mountIndex.notifyWrite(r);return}let o;try{o=await this.resolveSymlinks(r)}catch{o=r}let c=!1;try{await this.lfs.stat(o),c=!0}catch{}let{dir:l}=a(o);await this.withWriteLock(async()=>{this.markSidecarDirty(o),l!==`/`&&await this.mkdirRecursiveUnlocked(l);let e=typeof t==`string`?new TextEncoder().encode(t).byteLength:(t instanceof Uint8Array,t.byteLength);try{await this.lfs.writeFile(o,t)}catch(e){if(l!==`/`&&e instanceof Error&&e.message.includes(`ENOENT`)){await this.mkdirRecursiveUnlocked(l);try{await this.lfs.writeFile(o,t)}catch(e){throw M(e,r)}}else throw M(e,r)}try{await this.lfs.truncate?.(o,e)}catch(e){throw M(e,r)}}),this.watcher?.notify([{type:c?`modify`:`create`,path:o,entryType:`file`}])}async readDir(e){let t=s(e),n=this.findMount(t);return n?this.readDirMounted(t,n):this.readDirLocal(t)}async readDirMounted(e,t){let n=this.mountIndex.getDirectoryEntries(t.path,e);if(n!==void 0){let t=new Map;for(let e of n)t.set(e.name,{name:e.name,type:e.type});return this.addNestedMountEntries(t,e),[...t.values()]}let r=t.relParts.join(`/`)||`/`,i;try{i=await t.backend.readDir(r)}catch(t){j(t,e)}let a=new Map;for(let e of i)a.set(e.name,{name:e.name,type:e.kind===`directory`?`directory`:`file`});return this.addNestedMountEntries(a,e),[...a.values()]}async readDirLocal(e){return this.withKindMismatchRetry(e,()=>this.readDirLocalInner(e))}async readDirLocalInner(e){let t=await this.resolveSymlinks(e);try{let e=await this.lfs.readdir(t),n=[];for(let r of e){let e=await this.statDirEntry(t,r);e&&n.push(e)}return n}catch(t){throw M(t,e)}}async statDirEntry(e,t){let n=e===`/`?`/${t}`:`${e}/${t}`;try{let e=await this.lfs.lstat(n);return e.isSymbolicLink()?{name:t,type:`symlink`}:{name:t,type:e.isDirectory()?`directory`:`file`}}catch{return null}}addNestedMountEntries(e,t){let n=t===`/`?`/`:`${t}/`;for(let r of this.mountPoints.keys()){if(r===t||!r.startsWith(n))continue;let i=r.slice(n.length);!i||i.includes(`/`)||e.has(i)||e.set(i,{name:i,type:`directory`})}}async withWriteLock(t){let n=this.dbName,r,i=new Promise(e=>{r=e}),a=e.writeChains.get(n)??Promise.resolve();e.writeChains.set(n,i),await a;try{let e=globalThis.navigator?.locks;return this.backend!==`opfs`||typeof e?.request!=`function`?await t():await e.request(`slicc-vfs:${n}`,()=>t())}finally{r(),e.writeChains.get(n)===i&&e.writeChains.delete(n)}}async mkdirRecursiveUnlocked(e){let t=e.split(`/`).filter(Boolean),n=[],r=``;for(let e of t){r+=`/`+e;try{await this.lfs.mkdir(r),n.push(r)}catch(e){if(e instanceof Error&&!e.message.includes(`EEXIST`))throw M(e,r);try{let e=await this.lfs.lstat(r);if(!e.isDirectory()&&!e.isSymbolicLink())throw new u(`ENOTDIR`,`not a directory`,r)}catch(e){if(e instanceof u&&e.code===`ENOTDIR`)throw e}}}return n}async mkdir(e,t){let n=s(e);if(n===`/`)return;let r=this.findMount(n);if(r){if(r.relParts.length===0)return;let e=r.relParts.join(`/`),t=await this.exists(n);try{await r.backend.mkdir(e)}catch(e){j(e,n)}t||this.watcher?.notify([{type:`create`,path:n,entryType:`directory`}]);return}if(t?.recursive){let e=await this.withWriteLock(()=>(this.markSidecarDirty(n),this.mkdirRecursiveUnlocked(n)));e.length>0&&this.watcher?.notify(e.map(e=>({type:`create`,path:e,entryType:`directory`})))}else await this.withWriteLock(async()=>{this.markSidecarDirty(n);try{await this.lfs.mkdir(n)}catch(e){throw M(e,n)}}),this.watcher?.notify([{type:`create`,path:n,entryType:`directory`}])}async rm(e,t){return this.withKindMismatchRetry(s(e),()=>this.rmInner(e,t))}async rmInner(e,t){let n=s(e),r=this.findMount(n);if(r){if(r.relParts.length===0)throw new u(`EINVAL`,`cannot remove a mount point — use unmount`,n);let e;try{e=(await this.stat(n)).type}catch{}let i=r.relParts.join(`/`);try{await r.backend.remove(i,{recursive:t?.recursive})}catch(e){j(e,n)}this.watcher?.notify([{type:`delete`,path:n,entryType:e}]),this.mountIndex.notifyDelete(n);return}try{let e=await this.lfs.lstat(n);await this.withWriteLock(async()=>{e.isSymbolicLink()?await this.lfs.unlink(n):e.isDirectory()?t?.recursive?await this.rmRecursiveUnlocked(n):await this.lfs.rmdir(n):await this.lfs.unlink(n),this.markSidecarDirty(n,`prefix`),await this.writeOpfsMetadataSidecarUnlocked()})}catch(e){throw M(e,n)}this.watcher?.notify([{type:`delete`,path:n}])}async rmRecursiveUnlocked(e){let t=await this.lfs.readdir(e);for(let n of t){let t=e===`/`?`/${n}`:`${e}/${n}`,r=await this.lfs.lstat(t);r.isSymbolicLink()?await this.lfs.unlink(t):r.isDirectory()?await this.rmRecursiveUnlocked(t):await this.lfs.unlink(t)}await this.lfs.rmdir(e)}async stat(e){return this.withKindMismatchRetry(e,()=>this.statInner(e))}async statInner(e){let t=s(e),n=this.findMount(t);if(n){if(n.relParts.length===0)try{let e=await this.lfs.stat(t);return{type:`directory`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs}}catch{return{type:`directory`,size:0,mtime:Date.now(),ctime:Date.now()}}let e=n.relParts.join(`/`);try{let t=await n.backend.stat(e);return{type:t.kind===`directory`?`directory`:`file`,size:t.size,mtime:t.mtime,ctime:t.mtime}}catch(e){j(e,t)}}let r=await this.resolveSymlinks(t);try{let e=await this.lfs.stat(r);return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs}}catch(e){throw M(e,t)}}async exists(e){let t=s(e),n=this.findMount(t);if(n){if(n.relParts.length===0)return!0;try{return await this.stat(t),!0}catch{return!1}}try{return await this.stat(t),!0}catch{try{return await this.lfs.lstat(t),!0}catch{return!1}}}async rename(e,t){return this.withKindMismatchRetryPaths([s(e),s(t)],()=>this.renameInner(e,t))}async renameInner(e,t){let n=s(e),r=s(t),i;try{i=(await this.lstat(n)).type}catch{}let a=this.findMount(n);if(a?.backend.rename){let e=this.findMount(r);if(e&&e.backend===a.backend){try{await a.backend.rename(a.relParts.join(`/`),e.relParts.join(`/`))}catch(e){j(e,n)}this.watcher?.notify([{type:`delete`,path:n,entryType:i},{type:`create`,path:r,entryType:i}]),this.mountIndex.notifyRename(n,r);return}}try{await this.withWriteLock(async()=>{this.markSidecarDirty(n,`prefix`),this.markSidecarDirty(r,`prefix`),await this.lfs.rename(n,r),await this.writeOpfsMetadataSidecarUnlocked()})}catch(e){throw M(e,n)}this.watcher?.notify([{type:`delete`,path:n,entryType:i},{type:`create`,path:r,entryType:i}]),this.mountIndex.notifyRename(n,r)}async readTextFile(e){return await this.readFile(e,{encoding:`utf-8`})}async*walk(e,t,n=0){yield*Z({mountPoints:this.mountPoints,mountIndex:this.mountIndex,realpath:e=>this.realpath(e),readDir:e=>this.readDir(e),stat:e=>this.stat(e)},e,t,n)}async copyFile(e,t){if((await this.stat(e)).type===`directory`)throw new u(`EISDIR`,`is a directory`,e);let n=await this.readFile(e,{encoding:`binary`});await this.writeFile(t,n)}dirname(e){return a(s(e)).dir}basename(e){return a(s(e)).base}async symlink(e,t){let n=s(t);if(this.findMount(n))throw new u(`EINVAL`,`symlinks not supported on mounted filesystems`,n);let{dir:r}=a(n);await this.withWriteLock(async()=>{r!==`/`&&await this.mkdirRecursiveUnlocked(r);try{await this.lfs.symlink(e,n)}catch(t){if(r!==`/`&&t instanceof Error&&t.message.includes(`ENOENT`)){await this.mkdirRecursiveUnlocked(r);try{await this.lfs.symlink(e,n)}catch(e){throw M(e,n)}}else throw M(t,n)}this.markSidecarDirty(n),await this.writeOpfsMetadataSidecarUnlocked()}),this.watcher?.notify([{type:`create`,path:n,entryType:`symlink`}])}async readlink(e){let t=s(e);try{return await this.lfs.readlink(t)}catch(e){throw M(e,t)}}async lstat(e){let t=s(e);if(this.findMount(t)||t===`/`)return this.stat(t);try{let e=await this.lfs.lstat(t);if(e.isSymbolicLink()){let n=await this.lfs.readlink(t);return{type:`symlink`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,isSymlink:!0,symlinkTarget:n}}return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs}}catch(e){throw M(e,t)}}async realpath(e){return X(this.lfs,e=>this.findMount(e)!==null,e)}resolveSymlinks(e){return Ce(this.lfs,e=>this.findMount(e)!==null,e)}},ke=e({FsError:()=>u,FsWatcher:()=>y,MountIndex:()=>D,RestrictedFS:()=>A,VirtualFS:()=>$,joinPath:()=>l,normalizePath:()=>s,pathSegments:()=>o,resolveVfsBackendFromEnv:()=>Q,splitPath:()=>a});export{u as FsError,y as FsWatcher,D as MountIndex,A as RestrictedFS,$ as VirtualFS,ye as a,K as i,l as joinPath,J as n,s as normalizePath,V as o,o as pathSegments,be as r,Q as resolveVfsBackendFromEnv,a as splitPath,ke as t};
@@ -1 +1 @@
1
- import{n as e}from"./rolldown-runtime-Dd_uD5pT.js";import{t}from"./logger-LESFN7Hj.js";import{a as n,i as r,n as i,r as a,t as o}from"./path-utils-DNJG-zQf.js";import{t as s}from"./backend-local-B6kc_FvN.js";import{t as c}from"./types-idfTVsM8.js";import{a as l,i as u,n as d,t as f}from"./mount-table-store-DrF_Ifaz.js";import{r as p,t as m}from"./mount-index-CD1UKs2l.js";import{i as h,r as g,t as _}from"./sidecar-repair-CIHuOk7H.js";const v=t(`fs-watcher`);let y=0;function b(e,t){return t===`/`||e===t||e.startsWith(t+`/`)}var x=class{registrations=new Map;watch(e,t,n){let r=`fsw-${++y}`;return this.registrations.set(r,{id:r,basePath:e,filter:t,callback:n}),v.debug(`Watch registered`,{id:r,basePath:e}),()=>{this.registrations.delete(r),v.debug(`Watch unregistered`,{id:r})}}notify(e){if(e.length!==0)for(let[,t]of this.registrations){let n=e.filter(e=>b(e.path,t.basePath)&&t.filter(e.path));if(n.length>0)try{t.callback(n)}catch(e){v.error(`Watch callback error`,{id:t.id,error:e instanceof Error?e.message:String(e)})}}}dispose(){this.registrations.clear(),v.debug(`All watchers disposed`)}get size(){return this.registrations.size}};const S=`/dev/null`,C=new Set([S]);function w(e){return C.has(e)}const T={[S]:{stat:()=>({type:`file`,size:0,mtime:0,ctime:0}),read:e=>(e?.encoding??`utf-8`)===`utf-8`?``:new Uint8Array,readText:()=>``,write:()=>{}}},E=[`/tmp/`];var D=class{vfs;allowedPrefixes;readOnlyPrefixes;readGrantPatterns=[];writeEnforcement;constructor(e,t,n=[],r=`hard`){this.vfs=e;let a=e=>{let t=i(e);return t.endsWith(`/`)?t:t+`/`};this.allowedPrefixes=t.map(a),this.readOnlyPrefixes=n.map(a),this.writeEnforcement=r}getAllPrefixes(){let e=this.vfs.listMounts().map(e=>e.endsWith(`/`)?e:e+`/`);return[...this.allowedPrefixes,...this.readOnlyPrefixes,...e,...E]}setReadGrants(e){this.readGrantPatterns=[];for(let t of new Set(e))this.addReadGrant(t)}addReadGrant(e){let t=e.split(`/`),n=[];for(let e=1;e<t.length;e++)n.push(a(t.slice(0,e).join(`/`)||`/`));this.readGrantPatterns.push({pattern:e,regex:a(e),ancestorRegexes:n})}matchesReadGrant(e){return this.readGrantPatterns.some(t=>t.regex.test(e))}leadsToReadGrant(e){return this.readGrantPatterns.some(t=>t.ancestorRegexes.some(t=>t.test(e)))}isAllowed(e){let t=i(e),n=this.getAllPrefixes();return this.matchesReadGrant(t)||this.leadsToReadGrant(t)||n.some(e=>t===e.slice(0,-1)||t.startsWith(e)||t===`/`||e.startsWith(t+`/`))}isAllowedStrict(e){let t=i(e),n=this.getAllPrefixes();return this.matchesReadGrant(t)||n.some(e=>t===e.slice(0,-1)||t.startsWith(e))}isWritable(e){let t=i(e);return[...this.allowedPrefixes,...E].some(e=>t===e.slice(0,-1)||t.startsWith(e))}canWrite(e){return this.isWritable(e)}checkWrite(e){if(this.writeEnforcement!==`sudo-delegated`&&!this.isWritable(e))throw new c(`EACCES`,`permission denied`,i(e))}async resolveAndCheckRead(e){try{let t=await this.vfs.realpath(e);if(!this.isAllowedStrict(t))throw new c(`ENOENT`,`no such file or directory`,i(e));return t}catch(t){throw t instanceof c?t:new c(`ENOENT`,`no such file or directory`,i(e))}}async resolveAndCheckWrite(e){try{let t=await this.vfs.realpath(e);if(!this.isWritable(t)&&!this.isSymlinkEscapeAllowed(t))throw new c(`EACCES`,`permission denied`,i(e));return t}catch(t){throw t instanceof c?t:new c(`EACCES`,`permission denied`,i(e))}}isSymlinkEscapeAllowed(e){return!1}async checkParentRealpathEscape(e){let t=this.vfs.dirname(e),n=this.vfs.basename(e),r;try{r=await this.vfs.realpath(t)}catch(e){if(e instanceof c&&e.code===`EACCES`)throw e;return}let a=r+`/`+n;if(this.isWritable(a))return;let o=i(r)!==i(t);if(!(this.writeEnforcement===`sudo-delegated`&&!o))throw new c(`EACCES`,`permission denied`,i(e))}getUnderlyingFS(){return this.vfs}invalidatePaths(e){this.vfs.invalidatePaths(e)}async flush(){await this.vfs.flush()}isPathUnderMount(e){return this.vfs.isPathUnderMount(e)}async readFile(e,t){let n=T[i(e)];if(n)return n.read(t);if(!this.isAllowedStrict(e))throw new c(`ENOENT`,`no such file or directory`,i(e));let r=await this.resolveAndCheckRead(e);return this.vfs.readFile(r,t)}async readDir(e){if(!this.isAllowed(e))return[];let t=e;if(this.isAllowedStrict(e))try{t=await this.resolveAndCheckRead(e)}catch{return[]}let n=await this.vfs.readDir(t);if(!this.isAllowedStrict(e)){let t=i(e);return n.filter(e=>{let n=t===`/`?`/${e.name}`:`${t}/${e.name}`;return this.isAllowed(n)})}return n}async stat(e){let t=T[i(e)];if(t)return t.stat();if(!this.isAllowed(e))throw new c(`ENOENT`,`no such file or directory`,i(e));if(this.isAllowedStrict(e)){let t=await this.resolveAndCheckRead(e);return this.vfs.stat(t)}return this.vfs.stat(e)}scanPathForSymlinks(e,t){let n=i(e);if(n===`/`)return!1;let r=n.slice(1).split(`/`),a=t?r.length:r.length-1,o=``;for(let e=0;e<a;e++){o=o+`/`+r[e];let t=this.vfs.lstatSync(o);if(t===null)return null;if(t.type===`symlink`)return!0}return!1}statSync(e){let t=T[i(e)];return t?t.stat():!this.isAllowedStrict(e)||this.scanPathForSymlinks(e,!0)!==!1?null:this.vfs.statSync(e)}lstatSync(e){let t=T[i(e)];return t?t.stat():!this.isAllowed(e)||this.scanPathForSymlinks(e,!1)!==!1?null:this.vfs.lstatSync(e)}readDirSync(e){if(!this.isAllowed(e)||this.scanPathForSymlinks(e,!0)!==!1)return null;let t=this.vfs.readDirSync(e);if(t===null)return null;if(this.isAllowedStrict(e))return t;let n=i(e);return t.filter(e=>{let t=n===`/`?`/${e.name}`:`${n}/${e.name}`;return this.isAllowed(t)})}async realpath(e){let t;try{t=await this.vfs.realpath(e)}catch(t){throw t instanceof c?t:new c(`ENOENT`,`no such file or directory`,i(e))}if(!this.isAllowedStrict(t))throw new c(`ENOENT`,`no such file or directory`,i(e));return t}async exists(e){if(T[i(e)])return!0;if(!this.isAllowed(e))return!1;if(this.isAllowedStrict(e))try{await this.resolveAndCheckRead(e)}catch{return!1}return this.vfs.exists(e)}async readTextFile(e){let t=T[i(e)];if(t)return t.readText();if(!this.isAllowedStrict(e))throw new c(`ENOENT`,`no such file or directory`,i(e));let n=await this.resolveAndCheckRead(e);return this.vfs.readTextFile(n)}async*walk(e){if(!this.isAllowed(e))return;let t=e;if(this.isAllowedStrict(e))try{t=await this.resolveAndCheckRead(e)}catch{return}for await(let e of this.vfs.walk(t))this.isAllowed(e)&&(yield e)}async writeFile(e,t,n){let r=T[i(e)];if(r){r.write(t);return}this.checkWrite(e),await this.checkParentRealpathEscape(e);try{(await this.vfs.lstat(e)).type===`symlink`&&await this.resolveAndCheckWrite(e)}catch(e){if(e instanceof c&&e.code===`EACCES`)throw e}return this.vfs.writeFile(e,t,n)}async mkdir(e,t){return this.checkWrite(e),await this.checkParentRealpathEscape(e),this.vfs.mkdir(e,t)}async rm(e,t){this.checkWrite(e);try{(await this.vfs.lstat(e)).type===`symlink`||await this.resolveAndCheckWrite(e)}catch(e){if(e instanceof c&&e.code===`EACCES`)throw e}return this.vfs.rm(e,t)}async rename(e,t){return this.checkWrite(e),this.checkWrite(t),await this.resolveAndCheckWrite(e),await this.checkParentRealpathEscape(t),this.vfs.rename(e,t)}async copyFile(e,t){if(!this.isAllowed(e))throw new c(`ENOENT`,`no such file or directory`,i(e));this.checkWrite(t);let n=await this.resolveAndCheckRead(e);await this.checkParentRealpathEscape(t);try{(await this.vfs.lstat(t)).type===`symlink`&&await this.resolveAndCheckWrite(t)}catch(e){if(e instanceof c&&e.code===`EACCES`)throw e}return this.vfs.copyFile(n,t)}async symlink(e,t){return this.checkWrite(t),await this.checkParentRealpathEscape(t),this.vfs.symlink(e,t)}async readlink(e){if(!this.isAllowedStrict(e))throw new c(`ENOENT`,`no such file or directory`,i(e));let t=await this.vfs.readlink(e),n;if(t.startsWith(`/`))n=i(t);else{let r=this.vfs.dirname(e);n=i(r+`/`+t)}if(!this.isAllowedStrict(n))throw new c(`ENOENT`,`no such file or directory`,i(e));return t}async lstat(e){let t=T[i(e)];if(t)return t.stat();if(!this.isAllowed(e))throw new c(`ENOENT`,`no such file or directory`,i(e));let n=i(e),r=this.vfs.dirname(n),a=this.vfs.basename(n),o;if(r===n)o=r;else try{o=await this.vfs.realpath(r)}catch{throw new c(`ENOENT`,`no such file or directory`,n)}let s=o===`/`?`/${a}`:`${o}/${a}`;if(!this.isAllowed(s))throw new c(`ENOENT`,`no such file or directory`,n);return this.vfs.lstat(s)}watch(e,t,n){if(!this.isAllowed(e))throw new c(`EACCES`,`permission denied`,i(e));let r=this.vfs.getWatcher();if(!r)throw new c(`EINVAL`,`no watcher configured`);return r.watch(i(e),t,n)}dirname(e){return this.vfs.dirname(e)}basename(e){return this.vfs.basename(e)}async mount(e,t,n){return this.checkWrite(e),await this.checkParentRealpathEscape(e),this.vfs.mount(e,t,n)}async unmount(e){return this.checkWrite(e),await this.checkParentRealpathEscape(e),this.vfs.unmount(e)}listMounts(){return this.vfs.listMounts()}getMountIndex(){return this.vfs.getMountIndex()}async refreshMount(e,t){return this.checkWrite(e),this.vfs.refreshMount(e,t)}async dispose(){await this.vfs.dispose()}};function O(e,t){if(e instanceof c){let n=`${e.code}: `,r=e.message;throw r.startsWith(n)&&(r=r.slice(n.length)),e.path&&r.endsWith(` '${e.path}'`)&&(r=r.slice(0,r.length-` '${e.path}'`.length)),new c(e.code,r,t)}throw e}const k=[`ENOENT`,`EEXIST`,`ENOTDIR`,`EISDIR`,`ENOTEMPTY`,`EINVAL`,`EACCES`,`ELOOP`,`EBUSY`,`EFBIG`,`EBADF`,`ENOSYS`,`EIO`];function A(e,t){if(e instanceof c)return e;{let n=e instanceof Error?e.message:String(e);if(n.includes(`maximum size exceeded`)||n.includes(`call stack size exceeded`))return new c(`EIO`,`internal overflow, not storage: ${n} — reload the session`,t)}let n=e?.code;if(typeof n==`string`){let r=n;if(k.includes(r)){let n=e instanceof Error?e.message:String(e);return n.startsWith(`${r}: `)&&(n=n.slice(r.length+2),n=n.replace(/, undefined( '[^']*')?$/,``).replace(/ '[^']*'$/,``)),new c(r,n||r,t)}}let r=e instanceof Error?e.message:String(e);return r.includes(`ENOENT`)?new c(`ENOENT`,`no such file or directory`,t):r.includes(`EEXIST`)?new c(`EEXIST`,`file already exists`,t):r.includes(`ENOTDIR`)?new c(`ENOTDIR`,`not a directory`,t):r.includes(`EISDIR`)?new c(`EISDIR`,`is a directory`,t):r.includes(`ENOTEMPTY`)?new c(`ENOTEMPTY`,`directory not empty`,t):r.includes(`ELOOP`)?new c(`ELOOP`,`too many levels of symbolic links`,t):new c(`EINVAL`,r,t)}function j(e){return e===void 0?`absent`:(e&61440)==16384?`directory`:`file`}function M(e,t){return t===`absent`?!1:e.kind===`missing`||e.kind!==t}function N(e){let t=e?.mode;return typeof t==`number`?t:void 0}function P(e,t,n,r=new Set){let i=new Set(n);if(r.size>0){for(let t of Object.keys(e.entries??{}))for(let e of r)if(t===e||t.startsWith(`${e}/`)){i.add(t);break}}let a=[];for(let n of i){let r=e.entries?.[n],i=t.entries?.[n];if(!r||!i)continue;let o=j(N(r));o!==j(N(i))&&a.push({path:n,ownIsDirectory:o===`directory`})}return a}async function F(e,t,n,r){try{return await e.lstat(t)}catch(e){let t=A(e,r);if(t.code===`ENOENT`&&n)return null;throw t}}async function I(e,t,r){let a;try{a=await e.readlink(t)}catch(e){throw A(e,r)}return a.startsWith(`/`)?i(a):i(o(n(t).dir,a))}async function L(e,t,n,r,i,a){let o=t===`/`?`/${n}`:`${t}/${n}`;for(;;){let t=await F(e,o,r,i);if(t===null||!t.isSymbolicLink())return{resolved:o,hops:a};if(++a>10)throw new c(`ELOOP`,`too many symbolic links encountered`,i);o=await I(e,o,i)}}async function R(e,t,n){let r=i(n);if(t(r))return r;let a=r.split(`/`).filter(Boolean),o=`/`,s=0;for(let t=0;t<a.length;t++){let n=await L(e,o,a[t],t===a.length-1,r,s);o=n.resolved,s=n.hops}return o}async function z(e,t,n){return t(n)?n:R(e,t,n)}function B(e,t,n){return e.size===0||!e.has(n)||!t.isReady(n)?!1:!Array.from(e.keys()).some(e=>e!==n&&e.startsWith(n+`/`))}async function V(e,t){try{return await e(t)}catch{return t}}async function*H(e,t,n,r=0){let a=i(t);if(B(e.mountPoints,e.mountIndex,a)){let t=e.mountIndex.getFiles(a);if(t){for(let e of t)yield e;return}}let o=n??new Set;if(r>64||o.size>=1e5)return;let s=await V(t=>e.realpath(t),a);if(o.has(s))return;o.add(s);let c=await e.readDir(a);for(let t of c)yield*U(e,t,a===`/`?`/${t.name}`:`${a}/${t.name}`,o,r+1)}async function*U(e,t,n,r,i){if(t.type===`file`){yield n;return}if(t.type===`symlink`){yield*W(e,n,r,i);return}yield*H(e,n,r,i)}async function*W(e,t,n,r){try{let i=await e.stat(t);i.type===`file`?yield t:i.type===`directory`&&(yield*H(e,t,n,r))}catch{}}function G(){try{if(typeof globalThis.navigator?.storage?.getDirectory==`function`)return`opfs`}catch{}return`memory`}function K(e,t){switch(e.kind){case`local`:case`proc`:return{kind:`local`,mountId:e.mountId,idbHandleKey:t};case`hostfs`:return{kind:`hostfs`,mountId:e.mountId,hostPath:e.getHostPath()};default:return{kind:e.kind===`s3`?`s3`:e.kind===`aem`?`aem`:`da`,mountId:e.mountId,source:e.source,profile:e.profile??`default`}}}var q=class e{lfs;lfsSync;rawLfs=null;rawLfsSync=null;_ready;_readyResolved=!1;backend;mountPoints=new Map;opfsBackendFs=null;opfsHandle=null;mountRoot=``;internalMounts=new Set;watcher=null;dbName;mountSyncChannel=null;mountIndex=new m;static writeChains=new Map;onRepairProgress;constructor(t,n,r,i,a){if(this.dbName=t,this.onRepairProgress=a,this.backend=r===`opfs`?`opfs`:`memory`,this.lfs=this.makeDeferredLfs(),this.lfsSync=this.makeDeferredLfsSync(),this._ready=this.backend===`opfs`?e.initOpfsBackend(this,i,n===!0):e.initMemoryBackend(this,t,n===!0),this._ready.then(()=>{this._readyResolved=!0},()=>{}),typeof BroadcastChannel<`u`)try{this.mountSyncChannel=new BroadcastChannel(`vfs-mount-sync:${t}`),this.mountSyncChannel.onmessage=e=>{let{type:t,path:n,descriptor:r}=e.data??{};if(t===`mount`&&typeof n==`string`&&r)this.reconstructBackendFromDescriptor(r,n).then(e=>{this.mountPoints.set(n,e),e.kind===`local`&&this.mountIndex.registerMount(n,e.getHandle()),this.watcher?.notify([{type:`modify`,path:n,entryType:`directory`}])}).catch(()=>{});else if(t===`unmount`&&typeof n==`string`){let e=this.mountPoints.get(n);this.mountPoints.delete(n),this.mountIndex.unregisterMount(n),e?.close(),this.watcher?.notify([{type:`modify`,path:n,entryType:`directory`}])}}}catch{}}static async initOpfsBackend(t,n,r){let i=n??await e.acquireOpfsHandle(t.dbName,r);await e.seedOpfsMetadataSidecarIfMissing(i);let[a,{WebAccess:o}]=await Promise.all([import(`./dist-N1MMHRNk.js`).then(e=>e.t),import(`./dist-BnDrtqYs.js`)]);await e.ensureRootMount(a);let s=`/__opfs__/${t.dbName}`,c=e.opfsBackends.get(t.dbName);if(c&&r){try{a.umount(s)}catch{}e.opfsBackends.delete(t.dbName),c=void 0}if(!c){let n=()=>a.resolveMountConfig({backend:o,handle:i,metadata:`/.metadata.json`}),{resolveWithSidecarRepair:r,repairOpfsMetadataSidecar:l}=await import(`./sidecar-repair-CIHuOk7H.js`).then(e=>e.n);try{let e=await t.withWriteLock(()=>l(i,t.onRepairProgress));e?.changed&&console.warn(`[virtual-fs] repaired metadata sidecar before mount (#2146)`,{dbName:t.dbName,kindFixed:e.kindFixed,sizesFixed:e.sizesFixed,dropped:e.dropped,inosReassigned:e.inosReassigned,nlinksFixed:e.nlinksFixed,selfEntryDropped:e.selfEntryDropped})}catch{}let u=await r(n,()=>t.withWriteLock(()=>l(i,t.onRepairProgress)),e=>console.warn(`[virtual-fs] repaired poisoned metadata sidecar; retrying mount`,{dbName:t.dbName,kindFixed:e.kindFixed,sizesFixed:e.sizesFixed,dropped:e.dropped,nlinksFixed:e.nlinksFixed,selfEntryDropped:e.selfEntryDropped}));try{a.mount(s,u)}catch{}c={backendFs:u,refs:0,sidecarDirty:{paths:new Set,prefixes:new Set}},e.opfsBackends.set(t.dbName,c)}c.refs+=1,t.opfsBackendFs=c.backendFs.index?c.backendFs:null,t.opfsHandle=i,t.mountRoot=s,t.rawLfs=a.promises,t.rawLfsSync=a}static async initMemoryBackend(t,n,r){let i=await import(`./dist-N1MMHRNk.js`).then(e=>e.t);await e.ensureRootMount(i);let a=`/__zenfs__/${n}`,o=e.memoryBackends.get(n);if(o&&r){try{i.umount(a)}catch{}e.memoryBackends.delete(n),o=void 0}o||(o={store:i.InMemory.create({label:n}),refs:0},e.memoryBackends.set(n,o)),o.refs+=1;try{i.mount(a,o.store)}catch{}t.mountRoot=a,t.rawLfs=i.promises,t.rawLfsSync=i,t.opfsBackendFs=null,t.opfsHandle=null}static rootMountReady=null;static memoryBackends=new Map;static opfsBackends=new Map;static async ensureRootMount(t){return e.rootMountReady===null&&(e.rootMountReady=(async()=>{await t.configureSingle({backend:t.InMemory,label:`__vfs_root__`})})()),e.rootMountReady}prefix(e){return this.mountRoot?e===`/`?this.mountRoot:this.mountRoot+e:e}unprefix(e){return!this.mountRoot||!e.startsWith(this.mountRoot)?e:e.slice(this.mountRoot.length)||`/`}makeDeferredLfs(){let e=e=>this.prefix(e),t=e=>this.unprefix(e),n=()=>{if(!this.rawLfs)throw Error(`VirtualFS used before init resolved`);return this.rawLfs};return{readFile:(t,r)=>this._readyResolved?n().readFile(e(t),r):this._ready.then(()=>n().readFile(e(t),r)),writeFile:(t,r,i)=>this._readyResolved?n().writeFile(e(t),r,i):this._ready.then(()=>n().writeFile(e(t),r,i)),readdir:t=>this._readyResolved?n().readdir(e(t)):this._ready.then(()=>n().readdir(e(t))),mkdir:(t,r)=>this._readyResolved?n().mkdir(e(t),r):this._ready.then(()=>n().mkdir(e(t),r)),rmdir:t=>this._readyResolved?n().rmdir(e(t)):this._ready.then(()=>n().rmdir(e(t))),unlink:t=>this._readyResolved?n().unlink(e(t)):this._ready.then(()=>n().unlink(e(t))),rename:(t,r)=>this._readyResolved?n().rename(e(t),e(r)):this._ready.then(()=>n().rename(e(t),e(r))),stat:t=>this._readyResolved?n().stat(e(t)):this._ready.then(()=>n().stat(e(t))),lstat:t=>this._readyResolved?n().lstat(e(t)):this._ready.then(()=>n().lstat(e(t))),symlink:(t,r)=>{let i=t.startsWith(`/`)?e(t):t;return this._readyResolved?n().symlink(i,e(r)):this._ready.then(()=>n().symlink(i,e(r)))},readlink:async r=>(this._readyResolved||await this._ready,t(await n().readlink(e(r)))),truncate:async(t,r)=>{this._readyResolved||await this._ready;let i=n();typeof i.truncate==`function`&&await i.truncate(e(t),r)},realpath:async r=>{this._readyResolved||await this._ready;let i=n();return typeof i.realpath==`function`?t(await i.realpath(e(r))):e(r)}}}makeDeferredLfsSync(){let e=e=>this.prefix(e),t=e=>this.unprefix(e);return{readdirSync:t=>{let n=this.rawLfsSync;return n?.readdirSync?n.readdirSync(e(t)):void 0},statSync:t=>{let n=this.rawLfsSync;return n?.statSync?n.statSync(e(t)):void 0},lstatSync:t=>{let n=this.rawLfsSync;return n?.lstatSync?n.lstatSync(e(t)):void 0},readlinkSync:n=>{let r=this.rawLfsSync;return r?.readlinkSync?t(r.readlinkSync(e(n))):void 0}}}static async seedOpfsMetadataSidecarIfMissing(e){let t=`.metadata.json`;try{await e.getFileHandle(t);return}catch(e){if(e?.name!==`NotFoundError`)throw e}let n=await(await e.getFileHandle(t,{create:!0})).createWritable(),r=JSON.stringify({version:1,maxSize:4294967295,entries:{}});await n.write(r),await n.close()}static async acquireOpfsHandle(e,t){let n=navigator.storage;if(!n?.getDirectory)throw new c(`EINVAL`,`OPFS is not available in this environment`);let r=await n.getDirectory();if(t)try{await r.removeEntry(e,{recursive:!0})}catch{}return r.getDirectoryHandle(e,{create:!0})}static _createSyncForTests(t){return new e(t)}static async create(t){let n=t?.dbName??`browser-fs`,r=t?.wipe===!0,i=t?.backend??G(),a=new e(n,r,i,void 0,t?.onRepairProgress);return await a._ready,r&&await f().catch(()=>{}),a}async flush(){await this.writeOpfsMetadataSidecar()}async writeOpfsMetadataSidecar(){this.backend===`opfs`&&await this.withWriteLock(()=>this.writeOpfsMetadataSidecarUnlocked())}async writeOpfsMetadataSidecarUnlocked(){if(this.backend!==`opfs`)return;let t=this.opfsBackendFs,n=this.opfsHandle;if(!t||!n)return;let r=t.index.toJSON(),i=e.opfsBackends.get(this.dbName)?.sidecarDirty,a=r;if(i){let e=null;try{let t=await n.getFileHandle(`.metadata.json`),r=JSON.parse(await(await t.getFile()).text());r&&typeof r==`object`&&r.entries&&(e=r)}catch{}e&&(await this.auditDirtyKindFlips(r,e,i,n),a=g(e,r,i))}let o=JSON.stringify(h(a)),s=await(await n.getFileHandle(`.metadata.json`,{create:!0})).createWritable();await s.write(o),await s.close(),i&&(i.paths.clear(),i.prefixes.clear())}async auditDirtyKindFlips(e,t,n,r){let i=P(e,t,n.paths,n.prefixes);if(i.length===0)return;let a=_(r),o=this.opfsBackendFs;for(let n of i){let r=await a(n.path).catch(()=>null);if(r!==null&&r.kind!==`missing`&&r.kind===`directory`===n.ownIsDirectory)continue;let i=t.entries?.[n.path];e.entries&&i!==void 0&&(e.entries[n.path]=i);let s=r!==null&&r.kind!==`missing`;s&&(o?.index?.delete(n.path),o?._handles?.delete(n.path)),console.warn(`[virtual-fs] refused to flush in-memory kind flip over sidecar record (#2006)`,{path:n.path,reality:r?.kind??`unverifiable`,evicted:s})}}markSidecarDirty(t,r=`path`){if(this.backend!==`opfs`)return;let a=e.opfsBackends.get(this.dbName)?.sidecarDirty;if(!a)return;let o=i(t);(r===`prefix`?a.prefixes:a.paths).add(o);let{dir:s}=n(o);for(;s!==`/`;)a.paths.add(s),s=n(s).dir}invalidatePaths(e){if(this.backend!==`opfs`||!this.opfsBackendFs)return;let t=this.opfsBackendFs;for(let n of e){let e=i(n);t.index.delete(e),t._handles?.delete(e),this.markSidecarDirty(e)}}async withKindMismatchRetry(e,t){return this.withKindMismatchRetryPaths([e],t)}async withKindMismatchRetryPaths(e,t){try{return await t()}catch(n){let r=n?.code;if(r!==`EISDIR`&&r!==`ENOTDIR`&&r!==`EINVAL`)throw n;for(let n of e)if(await this.reconcileKindMismatch(n).catch(()=>!1))return await t();throw n}}async reconcileKindMismatch(e){if(this.backend!==`opfs`)return!1;let t=this.opfsBackendFs,n=this.opfsHandle;if(!t?.index||!n)return!1;let r=i(e),a=r;try{a=await this.resolveSymlinks(r)}catch{}let o=await _(n)(a),s=j(t.index.get(a)?.mode),c=t._handles?.get(a),l=c?.kind===`directory`?`directory`:c?.kind===`file`?`file`:`absent`,u=M(o,s),d=M(o,l);if(!u&&!d)return!1;if(t.index.delete(a),t._handles?.delete(a),s===`directory`||l===`directory`){let e=`${a}/`;for(let n of[...t.index.keys()])n.startsWith(e)&&t.index.delete(n);if(t._handles)for(let n of[...t._handles.keys()])n.startsWith(e)&&t._handles.delete(n)}return this.markSidecarDirty(a),console.warn(`[virtual-fs] reconciled in-memory kind mismatch (#2006)`,{path:a,reality:o.kind,indexHeld:s,handleHeld:l}),!0}canWrite(e){return!0}setWatcher(e){this.watcher=e}getWatcher(){return this.watcher}async watch(e,t){let n=this.watcher;if(!n)throw new c(`ENOSYS`,`no FsWatcher attached to this VirtualFS`);let r=e.map(e=>n.watch(e,()=>!0,t));return()=>{for(let e of r)e()}}async dispose(){if(this.mountSyncChannel?.close(),this.mountSyncChannel=null,this.watcher?.dispose(),this.watcher=null,this.mountIndex.dispose(),await this.writeOpfsMetadataSidecar(),this.mountRoot){let t=this.backend===`opfs`?e.opfsBackends:e.memoryBackends,n=t.get(this.dbName);if(n&&(--n.refs,n.refs<=0)){t.delete(this.dbName);try{(await import(`./dist-N1MMHRNk.js`).then(e=>e.t)).umount(this.mountRoot)}catch{}}}}readDirSync(e){let t=i(e);if(this.findMount(t))return null;let n=this.lfsSync;if(typeof n.readdirSync!=`function`||typeof n.lstatSync!=`function`)return null;try{let e=n.readdirSync(t),r=[];for(let i of e){let e=t===`/`?`/${i}`:`${t}/${i}`;try{let t=n.lstatSync(e),a=t.isSymbolicLink()?`symlink`:t.isDirectory()?`directory`:`file`;r.push({name:i,type:a})}catch{}}return r}catch{return null}}statSync(e){let t=i(e);if(this.findMount(t))return null;let r=this.lfsSync;if(typeof r.statSync!=`function`||typeof r.lstatSync!=`function`||typeof r.readlinkSync!=`function`)return null;if(t===`/`)try{let e=r.statSync(t);return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs}}catch{return null}let a=t;for(let e=0;e<=10;e++){let e;try{e=r.lstatSync(a)}catch{return null}if(!e.isSymbolicLink())return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs};let t;try{t=r.readlinkSync(a)}catch{return null}a=t.startsWith(`/`)?i(t):i(o(n(a).dir,t))}return null}lstatSync(e){let t=i(e);if(this.findMount(t))return null;let n=this.lfsSync;if(typeof n.lstatSync!=`function`)return null;if(t===`/`)return this.statSync(t);try{let e=n.lstatSync(t);if(e.isSymbolicLink()){let r=n.readlinkSync?n.readlinkSync(t):``;return{type:`symlink`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,isSymlink:!0,symlinkTarget:r}}return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs}}catch{return null}}async mount(e,t,r){let a=i(e);if(this.mountPoints.has(a))throw new c(`EEXIST`,`mount point is already mounted`,a);try{if((await this.lstat(a)).type!==`directory`)throw new c(`ENOTDIR`,`mount point must be a directory`,a);if((await this.readDir(a)).length>0)throw new c(`ENOTEMPTY`,`mount point must be empty to avoid shadowing existing files`,a)}catch(e){if(!(e instanceof c)||e.code!==`ENOENT`)throw e}let{dir:o}=n(a);o!==`/`&&await this.mkdir(o,{recursive:!0});try{await this.lfs.mkdir(a)}catch{}if(this.mountPoints.set(a,t),t.kind===`local`){let e=r?.limits??p(r?.env??{});this.mountIndex.registerMount(a,t.getHandle(),e)}let s=K(t,a);try{this.mountSyncChannel?.postMessage({type:`mount`,path:a,descriptor:s})}catch{}if(this.watcher?.notify([{type:`modify`,path:a,entryType:`directory`}]),t.kind!==`hostfs`)try{let e={targetPath:a,descriptor:s,createdAt:Date.now()},n=t.kind===`local`?t.getHandle():void 0;await l(e,n)}catch{}}async unmount(e){let t=i(e),n=this.mountPoints.get(t);this.mountPoints.delete(t),this.mountIndex.unregisterMount(t);try{this.mountSyncChannel?.postMessage({type:`unmount`,path:t})}catch{}this.watcher?.notify([{type:`modify`,path:t,entryType:`directory`}]),await n?.close();try{await u(t)}catch{}}async reconstructBackendFromDescriptor(e,t){switch(e.kind){case`local`:{let t=await d(e.idbHandleKey);if(!t)throw Error(`no handle stored for ${e.idbHandleKey}`);return s.fromHandle(t,{mountId:e.mountId})}case`hostfs`:{let{HostFsMountBackend:n}=await import(`./backend-hostfs-bQQx-S0W.js`);return new n({targetPath:t,hostPath:e.hostPath,mountId:e.mountId})}case`s3`:{let{S3MountBackend:t,RemoteMountCache:n,makeSignedFetchS3:r}=await import(`./mount-BcopcDTf.js`).then(e=>e.t),i=new n({mountId:e.mountId,ttlMs:3e4});return new t({source:e.source,profile:e.profile,cache:i,mountId:e.mountId,signedFetch:r(e.profile)})}case`da`:{let{DaMountBackend:t,RemoteMountCache:n,makeSignedFetchDa:r}=await import(`./mount-BcopcDTf.js`).then(e=>e.t),i=new n({mountId:e.mountId,ttlMs:3e4});return new t({source:e.source,profile:e.profile,cache:i,mountId:e.mountId,signedFetch:r()})}case`aem`:{let{AemMountBackend:t,RemoteMountCache:n,makeSignedFetchDa:r}=await import(`./mount-BcopcDTf.js`).then(e=>e.t),i=new n({mountId:e.mountId,ttlMs:3e4});return new t({source:e.source,profile:e.profile,cache:i,mountId:e.mountId,signedFetch:r()})}}}listMounts(){let e=[];for(let t of this.mountPoints.keys())this.internalMounts.has(t)||e.push(t);return e}listInternalMounts(){return[...this.internalMounts]}listMountPoints(){let e=[];for(let[t,n]of this.mountPoints)this.internalMounts.has(t)||e.push({path:t,kind:n.kind});return e}async mountInternal(e,t){let r=i(e);if(this.mountPoints.has(r))throw new c(`EEXIST`,`mount point is already mounted`,r);let{dir:a}=n(r);a!==`/`&&await this.mkdir(a,{recursive:!0});try{await this.lfs.mkdir(r)}catch{}this.mountPoints.set(r,t),this.internalMounts.add(r),this.watcher?.notify([{type:`modify`,path:r,entryType:`directory`}])}async unmountInternal(e){let t=i(e);if(!this.internalMounts.has(t))throw new c(`ENOENT`,`not an internal mount point`,t);let n=this.mountPoints.get(t);this.mountPoints.delete(t),this.internalMounts.delete(t),this.watcher?.notify([{type:`modify`,path:t,entryType:`directory`}]),await n?.close()}getMountIndex(){return this.mountIndex}async refreshMount(e,t){let n=i(e),r=this.mountPoints.get(n);if(!r)throw new c(`ENOENT`,`not a mount point`,n);let a=await r.refresh(t);return r.kind===`local`&&await this.mountIndex.refreshMount(n,p(t?.env??{})),this.watcher?.notify([{type:`modify`,path:n,entryType:`directory`}]),a}isPathUnderMount(e){for(let t of this.mountPoints.keys())if(e===t||e.startsWith(t+`/`))return!0;return!1}findMount(e){let t=null;for(let[n,r]of this.mountPoints)(e===n||e.startsWith(n+`/`))&&(!t||n.length>t.mountPath.length)&&(t={mountPath:n,backend:r});return t?e===t.mountPath?{path:t.mountPath,backend:t.backend,relParts:[]}:{path:t.mountPath,backend:t.backend,relParts:e.slice(t.mountPath.length+1).split(`/`).filter(Boolean)}:null}async readFile(e,t){return this.withKindMismatchRetry(e,()=>this.readFileInner(e,t))}async readFileInner(e,t){let n=i(e),r=this.findMount(n);if(r){if(r.relParts.length===0)throw new c(`EISDIR`,`is a directory`,n);let e=r.relParts.join(`/`);try{let n=await r.backend.readFile(e);return(t?.encoding??`utf-8`)===`utf-8`?new TextDecoder(`utf-8`).decode(n):n}catch(e){O(e,n)}}let a=await this.resolveSymlinks(n);try{return(t?.encoding??`utf-8`)===`utf-8`?await this.lfs.readFile(a,{encoding:`utf8`}):await this.lfs.readFile(a)}catch(e){throw A(e,n)}}async writeFile(e,t,n){return this.withKindMismatchRetry(e,()=>this.writeFileInner(e,t,n))}async writeFileInner(e,t,r){let a=i(e),o=this.findMount(a);if(o){if(o.relParts.length===0)throw new c(`EISDIR`,`is a directory`,a);let e=o.relParts.join(`/`),n=!1;try{await this.stat(a),n=!0}catch{}let r=typeof t==`string`?new TextEncoder().encode(t):t instanceof Uint8Array?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):new Uint8Array(t);try{await o.backend.writeFile(e,r)}catch(e){O(e,a)}this.watcher?.notify([{type:n?`modify`:`create`,path:a,entryType:`file`}]),this.mountIndex.notifyWrite(a);return}let s;try{s=await this.resolveSymlinks(a)}catch{s=a}let l=!1;try{await this.lfs.stat(s),l=!0}catch{}let{dir:u}=n(s);await this.withWriteLock(async()=>{this.markSidecarDirty(s),u!==`/`&&await this.mkdirRecursiveUnlocked(u);let e=typeof t==`string`?new TextEncoder().encode(t).byteLength:(t instanceof Uint8Array,t.byteLength);try{await this.lfs.writeFile(s,t)}catch(e){if(u!==`/`&&e instanceof Error&&e.message.includes(`ENOENT`)){await this.mkdirRecursiveUnlocked(u);try{await this.lfs.writeFile(s,t)}catch(e){throw A(e,a)}}else throw A(e,a)}try{await this.lfs.truncate?.(s,e)}catch(e){throw A(e,a)}}),this.watcher?.notify([{type:l?`modify`:`create`,path:s,entryType:`file`}])}async readDir(e){let t=i(e),n=this.findMount(t);return n?this.readDirMounted(t,n):this.readDirLocal(t)}async readDirMounted(e,t){let n=this.mountIndex.getDirectoryEntries(t.path,e);if(n!==void 0){let t=new Map;for(let e of n)t.set(e.name,{name:e.name,type:e.type});return this.addNestedMountEntries(t,e),[...t.values()]}let r=t.relParts.join(`/`)||`/`,i;try{i=await t.backend.readDir(r)}catch(t){O(t,e)}let a=new Map;for(let e of i)a.set(e.name,{name:e.name,type:e.kind===`directory`?`directory`:`file`});return this.addNestedMountEntries(a,e),[...a.values()]}async readDirLocal(e){return this.withKindMismatchRetry(e,()=>this.readDirLocalInner(e))}async readDirLocalInner(e){let t=await this.resolveSymlinks(e);try{let e=await this.lfs.readdir(t),n=[];for(let r of e){let e=await this.statDirEntry(t,r);e&&n.push(e)}return n}catch(t){throw A(t,e)}}async statDirEntry(e,t){let n=e===`/`?`/${t}`:`${e}/${t}`;try{let e=await this.lfs.lstat(n);return e.isSymbolicLink()?{name:t,type:`symlink`}:{name:t,type:e.isDirectory()?`directory`:`file`}}catch{return null}}addNestedMountEntries(e,t){let n=t===`/`?`/`:`${t}/`;for(let r of this.mountPoints.keys()){if(r===t||!r.startsWith(n))continue;let i=r.slice(n.length);!i||i.includes(`/`)||e.has(i)||e.set(i,{name:i,type:`directory`})}}async withWriteLock(t){let n=this.dbName,r,i=new Promise(e=>{r=e}),a=e.writeChains.get(n)??Promise.resolve();e.writeChains.set(n,i),await a;try{let e=globalThis.navigator?.locks;return this.backend!==`opfs`||typeof e?.request!=`function`?await t():await e.request(`slicc-vfs:${n}`,()=>t())}finally{r(),e.writeChains.get(n)===i&&e.writeChains.delete(n)}}async mkdirRecursiveUnlocked(e){let t=e.split(`/`).filter(Boolean),n=[],r=``;for(let e of t){r+=`/`+e;try{await this.lfs.mkdir(r),n.push(r)}catch(e){if(e instanceof Error&&!e.message.includes(`EEXIST`))throw A(e,r);try{let e=await this.lfs.lstat(r);if(!e.isDirectory()&&!e.isSymbolicLink())throw new c(`ENOTDIR`,`not a directory`,r)}catch(e){if(e instanceof c&&e.code===`ENOTDIR`)throw e}}}return n}async mkdir(e,t){let n=i(e);if(n===`/`)return;let r=this.findMount(n);if(r){if(r.relParts.length===0)return;let e=r.relParts.join(`/`),t=await this.exists(n);try{await r.backend.mkdir(e)}catch(e){O(e,n)}t||this.watcher?.notify([{type:`create`,path:n,entryType:`directory`}]);return}if(t?.recursive){let e=await this.withWriteLock(()=>(this.markSidecarDirty(n),this.mkdirRecursiveUnlocked(n)));e.length>0&&this.watcher?.notify(e.map(e=>({type:`create`,path:e,entryType:`directory`})))}else await this.withWriteLock(async()=>{this.markSidecarDirty(n);try{await this.lfs.mkdir(n)}catch(e){throw A(e,n)}}),this.watcher?.notify([{type:`create`,path:n,entryType:`directory`}])}async rm(e,t){return this.withKindMismatchRetry(i(e),()=>this.rmInner(e,t))}async rmInner(e,t){let n=i(e),r=this.findMount(n);if(r){if(r.relParts.length===0)throw new c(`EINVAL`,`cannot remove a mount point — use unmount`,n);let e;try{e=(await this.stat(n)).type}catch{}let i=r.relParts.join(`/`);try{await r.backend.remove(i,{recursive:t?.recursive})}catch(e){O(e,n)}this.watcher?.notify([{type:`delete`,path:n,entryType:e}]),this.mountIndex.notifyDelete(n);return}try{let e=await this.lfs.lstat(n);await this.withWriteLock(async()=>{e.isSymbolicLink()?await this.lfs.unlink(n):e.isDirectory()?t?.recursive?await this.rmRecursiveUnlocked(n):await this.lfs.rmdir(n):await this.lfs.unlink(n),this.markSidecarDirty(n,`prefix`),await this.writeOpfsMetadataSidecarUnlocked()})}catch(e){throw A(e,n)}this.watcher?.notify([{type:`delete`,path:n}])}async rmRecursiveUnlocked(e){let t=await this.lfs.readdir(e);for(let n of t){let t=e===`/`?`/${n}`:`${e}/${n}`,r=await this.lfs.lstat(t);r.isSymbolicLink()?await this.lfs.unlink(t):r.isDirectory()?await this.rmRecursiveUnlocked(t):await this.lfs.unlink(t)}await this.lfs.rmdir(e)}async stat(e){return this.withKindMismatchRetry(e,()=>this.statInner(e))}async statInner(e){let t=i(e),n=this.findMount(t);if(n){if(n.relParts.length===0)try{let e=await this.lfs.stat(t);return{type:`directory`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs}}catch{return{type:`directory`,size:0,mtime:Date.now(),ctime:Date.now()}}let e=n.relParts.join(`/`);try{let t=await n.backend.stat(e);return{type:t.kind===`directory`?`directory`:`file`,size:t.size,mtime:t.mtime,ctime:t.mtime}}catch(e){O(e,t)}}let r=await this.resolveSymlinks(t);try{let e=await this.lfs.stat(r);return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs}}catch(e){throw A(e,t)}}async exists(e){let t=i(e),n=this.findMount(t);if(n){if(n.relParts.length===0)return!0;try{return await this.stat(t),!0}catch{return!1}}try{return await this.stat(t),!0}catch{try{return await this.lfs.lstat(t),!0}catch{return!1}}}async rename(e,t){return this.withKindMismatchRetryPaths([i(e),i(t)],()=>this.renameInner(e,t))}async renameInner(e,t){let n=i(e),r=i(t),a;try{a=(await this.lstat(n)).type}catch{}let o=this.findMount(n);if(o?.backend.rename){let e=this.findMount(r);if(e&&e.backend===o.backend){try{await o.backend.rename(o.relParts.join(`/`),e.relParts.join(`/`))}catch(e){O(e,n)}this.watcher?.notify([{type:`delete`,path:n,entryType:a},{type:`create`,path:r,entryType:a}]),this.mountIndex.notifyRename(n,r);return}}try{await this.withWriteLock(async()=>{this.markSidecarDirty(n,`prefix`),this.markSidecarDirty(r,`prefix`),await this.lfs.rename(n,r),await this.writeOpfsMetadataSidecarUnlocked()})}catch(e){throw A(e,n)}this.watcher?.notify([{type:`delete`,path:n,entryType:a},{type:`create`,path:r,entryType:a}]),this.mountIndex.notifyRename(n,r)}async readTextFile(e){return await this.readFile(e,{encoding:`utf-8`})}async*walk(e,t,n=0){yield*H({mountPoints:this.mountPoints,mountIndex:this.mountIndex,realpath:e=>this.realpath(e),readDir:e=>this.readDir(e),stat:e=>this.stat(e)},e,t,n)}async copyFile(e,t){if((await this.stat(e)).type===`directory`)throw new c(`EISDIR`,`is a directory`,e);let n=await this.readFile(e,{encoding:`binary`});await this.writeFile(t,n)}dirname(e){return n(i(e)).dir}basename(e){return n(i(e)).base}async symlink(e,t){let r=i(t);if(this.findMount(r))throw new c(`EINVAL`,`symlinks not supported on mounted filesystems`,r);let{dir:a}=n(r);await this.withWriteLock(async()=>{a!==`/`&&await this.mkdirRecursiveUnlocked(a);try{await this.lfs.symlink(e,r)}catch(t){if(a!==`/`&&t instanceof Error&&t.message.includes(`ENOENT`)){await this.mkdirRecursiveUnlocked(a);try{await this.lfs.symlink(e,r)}catch(e){throw A(e,r)}}else throw A(t,r)}this.markSidecarDirty(r),await this.writeOpfsMetadataSidecarUnlocked()}),this.watcher?.notify([{type:`create`,path:r,entryType:`symlink`}])}async readlink(e){let t=i(e);try{return await this.lfs.readlink(t)}catch(e){throw A(e,t)}}async lstat(e){let t=i(e);if(this.findMount(t)||t===`/`)return this.stat(t);try{let e=await this.lfs.lstat(t);if(e.isSymbolicLink()){let n=await this.lfs.readlink(t);return{type:`symlink`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,isSymlink:!0,symlinkTarget:n}}return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs}}catch(e){throw A(e,t)}}async realpath(e){return R(this.lfs,e=>this.findMount(e)!==null,e)}resolveSymlinks(e){return z(this.lfs,e=>this.findMount(e)!==null,e)}},J=e({FsError:()=>c,FsWatcher:()=>x,MountIndex:()=>m,RestrictedFS:()=>D,VirtualFS:()=>q,joinPath:()=>o,normalizePath:()=>i,pathSegments:()=>r,resolveVfsBackendFromEnv:()=>G,splitPath:()=>n});export{x as a,w as i,q as n,D as r,J as t};
1
+ import{n as e}from"./rolldown-runtime-Dd_uD5pT.js";import{t}from"./logger-LESFN7Hj.js";import{a as n,i as r,n as i,r as a,t as o}from"./path-utils-DNJG-zQf.js";import{t as s}from"./backend-local-B6kc_FvN.js";import{t as c}from"./types-idfTVsM8.js";import{a as l,i as u,n as d,t as f}from"./mount-table-store-DrF_Ifaz.js";import{r as p,t as m}from"./mount-index-CD1UKs2l.js";import{i as h,r as g,t as _}from"./sidecar-repair-CIHuOk7H.js";const v=t(`fs-watcher`);let y=0;function b(e,t){return t===`/`||e===t||e.startsWith(t+`/`)}var x=class{registrations=new Map;watch(e,t,n){let r=`fsw-${++y}`;return this.registrations.set(r,{id:r,basePath:e,filter:t,callback:n}),v.debug(`Watch registered`,{id:r,basePath:e}),()=>{this.registrations.delete(r),v.debug(`Watch unregistered`,{id:r})}}notify(e){if(e.length!==0)for(let[,t]of this.registrations){let n=e.filter(e=>b(e.path,t.basePath)&&t.filter(e.path));if(n.length>0)try{t.callback(n)}catch(e){v.error(`Watch callback error`,{id:t.id,error:e instanceof Error?e.message:String(e)})}}}dispose(){this.registrations.clear(),v.debug(`All watchers disposed`)}get size(){return this.registrations.size}};const S=`/dev/null`,C=new Set([S]);function w(e){return C.has(e)}const T={[S]:{stat:()=>({type:`file`,size:0,mtime:0,ctime:0}),read:e=>(e?.encoding??`utf-8`)===`utf-8`?``:new Uint8Array,readText:()=>``,write:()=>{}}},E=[`/tmp/`];var D=class{vfs;allowedPrefixes;readOnlyPrefixes;readGrantPatterns=[];writeEnforcement;constructor(e,t,n=[],r=`hard`){this.vfs=e;let a=e=>{let t=i(e);return t.endsWith(`/`)?t:t+`/`};this.allowedPrefixes=t.map(a),this.readOnlyPrefixes=n.map(a),this.writeEnforcement=r}getAllPrefixes(){let e=this.vfs.listMounts().map(e=>e.endsWith(`/`)?e:e+`/`);return[...this.allowedPrefixes,...this.readOnlyPrefixes,...e,...E]}setReadGrants(e){this.readGrantPatterns=[];for(let t of new Set(e))this.addReadGrant(t)}addReadGrant(e){let t=e.split(`/`),n=[];for(let e=1;e<t.length;e++)n.push(a(t.slice(0,e).join(`/`)||`/`));this.readGrantPatterns.push({pattern:e,regex:a(e),ancestorRegexes:n})}matchesReadGrant(e){return this.readGrantPatterns.some(t=>t.regex.test(e))}leadsToReadGrant(e){return this.readGrantPatterns.some(t=>t.ancestorRegexes.some(t=>t.test(e)))}isAllowed(e){let t=i(e),n=this.getAllPrefixes();return this.matchesReadGrant(t)||this.leadsToReadGrant(t)||n.some(e=>t===e.slice(0,-1)||t.startsWith(e)||t===`/`||e.startsWith(t+`/`))}isAllowedStrict(e){let t=i(e),n=this.getAllPrefixes();return this.matchesReadGrant(t)||n.some(e=>t===e.slice(0,-1)||t.startsWith(e))}isWritable(e){let t=i(e);return[...this.allowedPrefixes,...E].some(e=>t===e.slice(0,-1)||t.startsWith(e))}canWrite(e){return this.isWritable(e)}checkWrite(e){if(this.writeEnforcement!==`sudo-delegated`&&!this.isWritable(e))throw new c(`EACCES`,`permission denied`,i(e))}async resolveAndCheckRead(e){try{let t=await this.vfs.realpath(e);if(!this.isAllowedStrict(t))throw new c(`ENOENT`,`no such file or directory`,i(e));return t}catch(t){throw t instanceof c?t:new c(`ENOENT`,`no such file or directory`,i(e))}}async resolveAndCheckWrite(e){try{let t=await this.vfs.realpath(e);if(!this.isWritable(t)&&!this.isSymlinkEscapeAllowed(t))throw new c(`EACCES`,`permission denied`,i(e));return t}catch(t){throw t instanceof c?t:new c(`EACCES`,`permission denied`,i(e))}}isSymlinkEscapeAllowed(e){return!1}async checkParentRealpathEscape(e){let t=this.vfs.dirname(e),n=this.vfs.basename(e),r;try{r=await this.vfs.realpath(t)}catch(e){if(e instanceof c&&e.code===`EACCES`)throw e;return}let a=r+`/`+n;if(this.isWritable(a))return;let o=i(r)!==i(t);if(!(this.writeEnforcement===`sudo-delegated`&&!o))throw new c(`EACCES`,`permission denied`,i(e))}getUnderlyingFS(){return this.vfs}invalidatePaths(e){this.vfs.invalidatePaths(e)}async flush(){await this.vfs.flush()}isPathUnderMount(e){return this.vfs.isPathUnderMount(e)}async readFile(e,t){let n=T[i(e)];if(n)return n.read(t);if(!this.isAllowedStrict(e))throw new c(`ENOENT`,`no such file or directory`,i(e));let r=await this.resolveAndCheckRead(e);return this.vfs.readFile(r,t)}async readDir(e){if(!this.isAllowed(e))return[];let t=e;if(this.isAllowedStrict(e))try{t=await this.resolveAndCheckRead(e)}catch{return[]}let n=await this.vfs.readDir(t);if(!this.isAllowedStrict(e)){let t=i(e);return n.filter(e=>{let n=t===`/`?`/${e.name}`:`${t}/${e.name}`;return this.isAllowed(n)})}return n}async stat(e){let t=T[i(e)];if(t)return t.stat();if(!this.isAllowed(e))throw new c(`ENOENT`,`no such file or directory`,i(e));if(this.isAllowedStrict(e)){let t=await this.resolveAndCheckRead(e);return this.vfs.stat(t)}return this.vfs.stat(e)}scanPathForSymlinks(e,t){let n=i(e);if(n===`/`)return!1;let r=n.slice(1).split(`/`),a=t?r.length:r.length-1,o=``;for(let e=0;e<a;e++){o=o+`/`+r[e];let t=this.vfs.lstatSync(o);if(t===null)return null;if(t.type===`symlink`)return!0}return!1}statSync(e){let t=T[i(e)];return t?t.stat():!this.isAllowedStrict(e)||this.scanPathForSymlinks(e,!0)!==!1?null:this.vfs.statSync(e)}lstatSync(e){let t=T[i(e)];return t?t.stat():!this.isAllowed(e)||this.scanPathForSymlinks(e,!1)!==!1?null:this.vfs.lstatSync(e)}readDirSync(e){if(!this.isAllowed(e)||this.scanPathForSymlinks(e,!0)!==!1)return null;let t=this.vfs.readDirSync(e);if(t===null)return null;if(this.isAllowedStrict(e))return t;let n=i(e);return t.filter(e=>{let t=n===`/`?`/${e.name}`:`${n}/${e.name}`;return this.isAllowed(t)})}async realpath(e){let t;try{t=await this.vfs.realpath(e)}catch(t){throw t instanceof c?t:new c(`ENOENT`,`no such file or directory`,i(e))}if(!this.isAllowedStrict(t))throw new c(`ENOENT`,`no such file or directory`,i(e));return t}async exists(e){if(T[i(e)])return!0;if(!this.isAllowed(e))return!1;if(this.isAllowedStrict(e))try{await this.resolveAndCheckRead(e)}catch{return!1}return this.vfs.exists(e)}async readTextFile(e){let t=T[i(e)];if(t)return t.readText();if(!this.isAllowedStrict(e))throw new c(`ENOENT`,`no such file or directory`,i(e));let n=await this.resolveAndCheckRead(e);return this.vfs.readTextFile(n)}async*walk(e){if(!this.isAllowed(e))return;let t=e;if(this.isAllowedStrict(e))try{t=await this.resolveAndCheckRead(e)}catch{return}for await(let e of this.vfs.walk(t))this.isAllowed(e)&&(yield e)}async writeFile(e,t,n){let r=T[i(e)];if(r){r.write(t);return}this.checkWrite(e),await this.checkParentRealpathEscape(e);try{(await this.vfs.lstat(e)).type===`symlink`&&await this.resolveAndCheckWrite(e)}catch(e){if(e instanceof c&&e.code===`EACCES`)throw e}return this.vfs.writeFile(e,t,n)}async mkdir(e,t){return this.checkWrite(e),await this.checkParentRealpathEscape(e),this.vfs.mkdir(e,t)}async rm(e,t){this.checkWrite(e);try{(await this.vfs.lstat(e)).type===`symlink`||await this.resolveAndCheckWrite(e)}catch(e){if(e instanceof c&&e.code===`EACCES`)throw e}return this.vfs.rm(e,t)}async rename(e,t){return this.checkWrite(e),this.checkWrite(t),await this.resolveAndCheckWrite(e),await this.checkParentRealpathEscape(t),this.vfs.rename(e,t)}async copyFile(e,t){if(!this.isAllowed(e))throw new c(`ENOENT`,`no such file or directory`,i(e));this.checkWrite(t);let n=await this.resolveAndCheckRead(e);await this.checkParentRealpathEscape(t);try{(await this.vfs.lstat(t)).type===`symlink`&&await this.resolveAndCheckWrite(t)}catch(e){if(e instanceof c&&e.code===`EACCES`)throw e}return this.vfs.copyFile(n,t)}async symlink(e,t){return this.checkWrite(t),await this.checkParentRealpathEscape(t),this.vfs.symlink(e,t)}async readlink(e){if(!this.isAllowedStrict(e))throw new c(`ENOENT`,`no such file or directory`,i(e));let t=await this.vfs.readlink(e),n;if(t.startsWith(`/`))n=i(t);else{let r=this.vfs.dirname(e);n=i(r+`/`+t)}if(!this.isAllowedStrict(n))throw new c(`ENOENT`,`no such file or directory`,i(e));return t}async lstat(e){let t=T[i(e)];if(t)return t.stat();if(!this.isAllowed(e))throw new c(`ENOENT`,`no such file or directory`,i(e));let n=i(e),r=this.vfs.dirname(n),a=this.vfs.basename(n),o;if(r===n)o=r;else try{o=await this.vfs.realpath(r)}catch{throw new c(`ENOENT`,`no such file or directory`,n)}let s=o===`/`?`/${a}`:`${o}/${a}`;if(!this.isAllowed(s))throw new c(`ENOENT`,`no such file or directory`,n);return this.vfs.lstat(s)}watch(e,t,n){if(!this.isAllowed(e))throw new c(`EACCES`,`permission denied`,i(e));let r=this.vfs.getWatcher();if(!r)throw new c(`EINVAL`,`no watcher configured`);return r.watch(i(e),t,n)}dirname(e){return this.vfs.dirname(e)}basename(e){return this.vfs.basename(e)}async mount(e,t,n){return this.checkWrite(e),await this.checkParentRealpathEscape(e),this.vfs.mount(e,t,n)}async unmount(e){return this.checkWrite(e),await this.checkParentRealpathEscape(e),this.vfs.unmount(e)}listMounts(){return this.vfs.listMounts()}getMountIndex(){return this.vfs.getMountIndex()}async refreshMount(e,t){return this.checkWrite(e),this.vfs.refreshMount(e,t)}async dispose(){await this.vfs.dispose()}};function O(e,t){if(e instanceof c){let n=`${e.code}: `,r=e.message;throw r.startsWith(n)&&(r=r.slice(n.length)),e.path&&r.endsWith(` '${e.path}'`)&&(r=r.slice(0,r.length-` '${e.path}'`.length)),new c(e.code,r,t)}throw e}const k=[`ENOENT`,`EEXIST`,`ENOTDIR`,`EISDIR`,`ENOTEMPTY`,`EINVAL`,`EACCES`,`ELOOP`,`EBUSY`,`EFBIG`,`EBADF`,`ENOSYS`,`EIO`];function A(e,t){if(e instanceof c)return e;{let n=e instanceof Error?e.message:String(e);if(n.includes(`maximum size exceeded`)||n.includes(`call stack size exceeded`))return new c(`EIO`,`internal overflow, not storage: ${n} — reload the session`,t)}let n=e?.code;if(typeof n==`string`){let r=n;if(k.includes(r)){let n=e instanceof Error?e.message:String(e);return n.startsWith(`${r}: `)&&(n=n.slice(r.length+2),n=n.replace(/, undefined( '[^']*')?$/,``).replace(/ '[^']*'$/,``)),new c(r,n||r,t)}}let r=e instanceof Error?e.message:String(e);return r.includes(`ENOENT`)?new c(`ENOENT`,`no such file or directory`,t):r.includes(`EEXIST`)?new c(`EEXIST`,`file already exists`,t):r.includes(`ENOTDIR`)?new c(`ENOTDIR`,`not a directory`,t):r.includes(`EISDIR`)?new c(`EISDIR`,`is a directory`,t):r.includes(`ENOTEMPTY`)?new c(`ENOTEMPTY`,`directory not empty`,t):r.includes(`ELOOP`)?new c(`ELOOP`,`too many levels of symbolic links`,t):new c(`EINVAL`,r,t)}function j(e){return e===void 0?`absent`:(e&61440)==16384?`directory`:`file`}function M(e,t){return t===`absent`?!1:e.kind===`missing`||e.kind!==t}function N(e){let t=e?.mode;return typeof t==`number`?t:void 0}function P(e,t,n,r=new Set){let i=new Set(n);if(r.size>0){for(let t of Object.keys(e.entries??{}))for(let e of r)if(t===e||t.startsWith(`${e}/`)){i.add(t);break}}let a=[];for(let n of i){let r=e.entries?.[n],i=t.entries?.[n];if(!r||!i)continue;let o=j(N(r));o!==j(N(i))&&a.push({path:n,ownIsDirectory:o===`directory`})}return a}async function F(e,t,n,r){try{return await e.lstat(t)}catch(e){let t=A(e,r);if(t.code===`ENOENT`&&n)return null;throw t}}async function I(e,t,r){let a;try{a=await e.readlink(t)}catch(e){throw A(e,r)}return a.startsWith(`/`)?i(a):i(o(n(t).dir,a))}async function L(e,t,n,r,i,a){let o=t===`/`?`/${n}`:`${t}/${n}`;for(;;){let t=await F(e,o,r,i);if(t===null||!t.isSymbolicLink())return{resolved:o,hops:a};if(++a>10)throw new c(`ELOOP`,`too many symbolic links encountered`,i);o=await I(e,o,i)}}async function R(e,t,n){let r=i(n);if(t(r))return r;let a=r.split(`/`).filter(Boolean),o=`/`,s=0;for(let t=0;t<a.length;t++){let n=await L(e,o,a[t],t===a.length-1,r,s);o=n.resolved,s=n.hops}return o}async function z(e,t,n){return t(n)?n:R(e,t,n)}function B(e,t,n){return e.size===0||!e.has(n)||!t.isReady(n)?!1:!Array.from(e.keys()).some(e=>e!==n&&e.startsWith(n+`/`))}async function V(e,t){try{return await e(t)}catch{return t}}async function*H(e,t,n,r=0){let a=i(t);if(B(e.mountPoints,e.mountIndex,a)){let t=e.mountIndex.getFiles(a);if(t){for(let e of t)yield e;return}}let o=n??new Set;if(r>64||o.size>=1e5)return;let s=await V(t=>e.realpath(t),a);if(o.has(s))return;o.add(s);let c=await e.readDir(a);for(let t of c)yield*U(e,t,a===`/`?`/${t.name}`:`${a}/${t.name}`,o,r+1)}async function*U(e,t,n,r,i){if(t.type===`file`){yield n;return}if(t.type===`symlink`){yield*W(e,n,r,i);return}yield*H(e,n,r,i)}async function*W(e,t,n,r){try{let i=await e.stat(t);i.type===`file`?yield t:i.type===`directory`&&(yield*H(e,t,n,r))}catch{}}function G(){try{if(typeof globalThis.navigator?.storage?.getDirectory==`function`)return`opfs`}catch{}return`memory`}function K(e,t){switch(e.kind){case`local`:case`proc`:return{kind:`local`,mountId:e.mountId,idbHandleKey:t};case`hostfs`:return{kind:`hostfs`,mountId:e.mountId,hostPath:e.getHostPath()};default:return{kind:e.kind===`s3`?`s3`:e.kind===`aem`?`aem`:`da`,mountId:e.mountId,source:e.source,profile:e.profile??`default`}}}var q=class e{lfs;lfsSync;rawLfs=null;rawLfsSync=null;_ready;_readyResolved=!1;backend;mountPoints=new Map;opfsBackendFs=null;opfsHandle=null;mountRoot=``;internalMounts=new Set;watcher=null;dbName;mountSyncChannel=null;mountIndex=new m;static writeChains=new Map;onRepairProgress;constructor(t,n,r,i,a){if(this.dbName=t,this.onRepairProgress=a,this.backend=r===`opfs`?`opfs`:`memory`,this.lfs=this.makeDeferredLfs(),this.lfsSync=this.makeDeferredLfsSync(),this._ready=this.backend===`opfs`?e.initOpfsBackend(this,i,n===!0):e.initMemoryBackend(this,t,n===!0),this._ready.then(()=>{this._readyResolved=!0},()=>{}),typeof BroadcastChannel<`u`)try{this.mountSyncChannel=new BroadcastChannel(`vfs-mount-sync:${t}`),this.mountSyncChannel.onmessage=e=>{let{type:t,path:n,descriptor:r}=e.data??{};if(t===`mount`&&typeof n==`string`&&r)this.reconstructBackendFromDescriptor(r,n).then(e=>{this.mountPoints.set(n,e),e.kind===`local`&&this.mountIndex.registerMount(n,e.getHandle()),this.watcher?.notify([{type:`modify`,path:n,entryType:`directory`}])}).catch(()=>{});else if(t===`unmount`&&typeof n==`string`){let e=this.mountPoints.get(n);this.mountPoints.delete(n),this.mountIndex.unregisterMount(n),e?.close(),this.watcher?.notify([{type:`modify`,path:n,entryType:`directory`}])}}}catch{}}static async initOpfsBackend(t,n,r){let i=n??await e.acquireOpfsHandle(t.dbName,r);await e.seedOpfsMetadataSidecarIfMissing(i);let[a,{WebAccess:o}]=await Promise.all([import(`./dist-N1MMHRNk.js`).then(e=>e.t),import(`./dist-BnDrtqYs.js`)]);await e.ensureRootMount(a);let s=`/__opfs__/${t.dbName}`,c=e.opfsBackends.get(t.dbName);if(c&&r){try{a.umount(s)}catch{}e.opfsBackends.delete(t.dbName),c=void 0}if(!c){let n=()=>a.resolveMountConfig({backend:o,handle:i,metadata:`/.metadata.json`}),{resolveWithSidecarRepair:r,repairOpfsMetadataSidecar:l}=await import(`./sidecar-repair-CIHuOk7H.js`).then(e=>e.n);try{let e=await t.withWriteLock(()=>l(i,t.onRepairProgress));e?.changed&&console.warn(`[virtual-fs] repaired metadata sidecar before mount (#2146)`,{dbName:t.dbName,kindFixed:e.kindFixed,sizesFixed:e.sizesFixed,dropped:e.dropped,inosReassigned:e.inosReassigned,nlinksFixed:e.nlinksFixed,selfEntryDropped:e.selfEntryDropped})}catch{}let u=await r(n,()=>t.withWriteLock(()=>l(i,t.onRepairProgress)),e=>console.warn(`[virtual-fs] repaired poisoned metadata sidecar; retrying mount`,{dbName:t.dbName,kindFixed:e.kindFixed,sizesFixed:e.sizesFixed,dropped:e.dropped,nlinksFixed:e.nlinksFixed,selfEntryDropped:e.selfEntryDropped}));try{a.mount(s,u)}catch{}c={backendFs:u,refs:0,sidecarDirty:{paths:new Set,prefixes:new Set}},e.opfsBackends.set(t.dbName,c)}c.refs+=1,t.opfsBackendFs=c.backendFs.index?c.backendFs:null,t.opfsHandle=i,t.mountRoot=s,t.rawLfs=a.promises,t.rawLfsSync=a}static async initMemoryBackend(t,n,r){let i=await import(`./dist-N1MMHRNk.js`).then(e=>e.t);await e.ensureRootMount(i);let a=`/__zenfs__/${n}`,o=e.memoryBackends.get(n);if(o&&r){try{i.umount(a)}catch{}e.memoryBackends.delete(n),o=void 0}o||(o={store:i.InMemory.create({label:n}),refs:0},e.memoryBackends.set(n,o)),o.refs+=1;try{i.mount(a,o.store)}catch{}t.mountRoot=a,t.rawLfs=i.promises,t.rawLfsSync=i,t.opfsBackendFs=null,t.opfsHandle=null}static rootMountReady=null;static memoryBackends=new Map;static opfsBackends=new Map;static async ensureRootMount(t){return e.rootMountReady===null&&(e.rootMountReady=(async()=>{await t.configureSingle({backend:t.InMemory,label:`__vfs_root__`})})()),e.rootMountReady}prefix(e){return this.mountRoot?e===`/`?this.mountRoot:this.mountRoot+e:e}unprefix(e){return!this.mountRoot||!e.startsWith(this.mountRoot)?e:e.slice(this.mountRoot.length)||`/`}makeDeferredLfs(){let e=e=>this.prefix(e),t=e=>this.unprefix(e),n=()=>{if(!this.rawLfs)throw Error(`VirtualFS used before init resolved`);return this.rawLfs};return{readFile:(t,r)=>this._readyResolved?n().readFile(e(t),r):this._ready.then(()=>n().readFile(e(t),r)),writeFile:(t,r,i)=>this._readyResolved?n().writeFile(e(t),r,i):this._ready.then(()=>n().writeFile(e(t),r,i)),readdir:t=>this._readyResolved?n().readdir(e(t)):this._ready.then(()=>n().readdir(e(t))),mkdir:(t,r)=>this._readyResolved?n().mkdir(e(t),r):this._ready.then(()=>n().mkdir(e(t),r)),rmdir:t=>this._readyResolved?n().rmdir(e(t)):this._ready.then(()=>n().rmdir(e(t))),unlink:t=>this._readyResolved?n().unlink(e(t)):this._ready.then(()=>n().unlink(e(t))),rename:(t,r)=>this._readyResolved?n().rename(e(t),e(r)):this._ready.then(()=>n().rename(e(t),e(r))),stat:t=>this._readyResolved?n().stat(e(t)):this._ready.then(()=>n().stat(e(t))),lstat:t=>this._readyResolved?n().lstat(e(t)):this._ready.then(()=>n().lstat(e(t))),symlink:(t,r)=>{let i=t.startsWith(`/`)?e(t):t;return this._readyResolved?n().symlink(i,e(r)):this._ready.then(()=>n().symlink(i,e(r)))},readlink:async r=>(this._readyResolved||await this._ready,t(await n().readlink(e(r)))),truncate:async(t,r)=>{this._readyResolved||await this._ready;let i=n();typeof i.truncate==`function`&&await i.truncate(e(t),r)},realpath:async r=>{this._readyResolved||await this._ready;let i=n();return typeof i.realpath==`function`?t(await i.realpath(e(r))):e(r)}}}makeDeferredLfsSync(){let e=e=>this.prefix(e),t=e=>this.unprefix(e);return{readdirSync:t=>{let n=this.rawLfsSync;return n?.readdirSync?n.readdirSync(e(t)):void 0},statSync:t=>{let n=this.rawLfsSync;return n?.statSync?n.statSync(e(t)):void 0},lstatSync:t=>{let n=this.rawLfsSync;return n?.lstatSync?n.lstatSync(e(t)):void 0},readlinkSync:n=>{let r=this.rawLfsSync;return r?.readlinkSync?t(r.readlinkSync(e(n))):void 0}}}static async seedOpfsMetadataSidecarIfMissing(e){let t=`.metadata.json`;try{await e.getFileHandle(t);return}catch(e){if(e?.name!==`NotFoundError`)throw e}let n=await(await e.getFileHandle(t,{create:!0})).createWritable(),r=JSON.stringify({version:1,maxSize:4294967295,entries:{}});await n.write(r),await n.close()}static async acquireOpfsHandle(e,t){let n=navigator.storage;if(!n?.getDirectory)throw new c(`EINVAL`,`OPFS is not available in this environment`);let r=await n.getDirectory();if(t)try{await r.removeEntry(e,{recursive:!0})}catch{}return r.getDirectoryHandle(e,{create:!0})}static _createSyncForTests(t){return new e(t)}static async create(t){let n=t?.dbName??`browser-fs`,r=t?.wipe===!0,i=t?.backend??G(),a=new e(n,r,i,void 0,t?.onRepairProgress);return await a._ready,r&&await f().catch(()=>{}),a}async flush(){await this.writeOpfsMetadataSidecar()}async writeOpfsMetadataSidecar(){this.backend===`opfs`&&await this.withWriteLock(()=>this.writeOpfsMetadataSidecarUnlocked())}async writeOpfsMetadataSidecarUnlocked(){if(this.backend!==`opfs`)return;let t=this.opfsBackendFs,n=this.opfsHandle;if(!t||!n)return;let r=t.index.toJSON(),i=e.opfsBackends.get(this.dbName)?.sidecarDirty,a=r;if(i){let e=null;try{let t=await n.getFileHandle(`.metadata.json`),r=JSON.parse(await(await t.getFile()).text());r&&typeof r==`object`&&r.entries&&(e=r)}catch{}e&&(await this.auditDirtyKindFlips(r,e,i,n),a=g(e,r,i))}let o=JSON.stringify(h(a)),s=await(await n.getFileHandle(`.metadata.json`,{create:!0})).createWritable();await s.write(o),await s.close(),i&&(i.paths.clear(),i.prefixes.clear())}async auditDirtyKindFlips(e,t,n,r){let i=P(e,t,n.paths,n.prefixes);if(i.length===0)return;let a=_(r),o=this.opfsBackendFs;for(let n of i){let r=await a(n.path).catch(()=>null);if(r!==null&&r.kind!==`missing`&&r.kind===`directory`===n.ownIsDirectory)continue;let i=t.entries?.[n.path];e.entries&&i!==void 0&&(e.entries[n.path]=i);let s=r!==null&&r.kind!==`missing`;s&&(o?.index?.delete(n.path),o?._handles?.delete(n.path)),console.warn(`[virtual-fs] refused to flush in-memory kind flip over sidecar record (#2006)`,{path:n.path,reality:r?.kind??`unverifiable`,evicted:s})}}markSidecarDirty(t,r=`path`){if(this.backend!==`opfs`)return;let a=e.opfsBackends.get(this.dbName)?.sidecarDirty;if(!a)return;let o=i(t);(r===`prefix`?a.prefixes:a.paths).add(o);let{dir:s}=n(o);for(;s!==`/`;)a.paths.add(s),s=n(s).dir}invalidatePaths(e){if(this.backend!==`opfs`||!this.opfsBackendFs)return;let t=this.opfsBackendFs;for(let n of e){let e=i(n);t.index.delete(e),t._handles?.delete(e),this.markSidecarDirty(e)}}async withKindMismatchRetry(e,t){return this.withKindMismatchRetryPaths([e],t)}async withKindMismatchRetryPaths(e,t){try{return await t()}catch(n){let r=n?.code;if(r!==`EISDIR`&&r!==`ENOTDIR`&&r!==`EINVAL`)throw n;for(let n of e)if(await this.reconcileKindMismatch(n).catch(()=>!1))return await t();throw n}}async reconcileKindMismatch(e){if(this.backend!==`opfs`)return!1;let t=this.opfsBackendFs,n=this.opfsHandle;if(!t?.index||!n)return!1;let r=i(e),a=r;try{a=await this.resolveSymlinks(r)}catch{}let o=await _(n)(a),s=j(t.index.get(a)?.mode),c=t._handles?.get(a),l=c?.kind===`directory`?`directory`:c?.kind===`file`?`file`:`absent`,u=M(o,s),d=M(o,l);if(!u&&!d)return!1;if(t.index.delete(a),t._handles?.delete(a),s===`directory`||l===`directory`){let e=`${a}/`;for(let n of[...t.index.keys()])n.startsWith(e)&&t.index.delete(n);if(t._handles)for(let n of[...t._handles.keys()])n.startsWith(e)&&t._handles.delete(n)}return this.markSidecarDirty(a),console.warn(`[virtual-fs] reconciled in-memory kind mismatch (#2006)`,{path:a,reality:o.kind,indexHeld:s,handleHeld:l}),!0}canWrite(e){return!0}setWatcher(e){this.watcher=e}getWatcher(){return this.watcher}async watch(e,t){let n=this.watcher;if(!n)throw new c(`ENOSYS`,`no FsWatcher attached to this VirtualFS`);let r=e.map(e=>n.watch(e,()=>!0,t));return()=>{for(let e of r)e()}}async dispose(){if(this.mountSyncChannel?.close(),this.mountSyncChannel=null,this.watcher?.dispose(),this.watcher=null,this.mountIndex.dispose(),await this.writeOpfsMetadataSidecar(),this.mountRoot){let t=this.backend===`opfs`?e.opfsBackends:e.memoryBackends,n=t.get(this.dbName);if(n&&(--n.refs,n.refs<=0)){t.delete(this.dbName);try{(await import(`./dist-N1MMHRNk.js`).then(e=>e.t)).umount(this.mountRoot)}catch{}}}}readDirSync(e){let t=i(e);if(this.findMount(t))return null;let n=this.lfsSync;if(typeof n.readdirSync!=`function`||typeof n.lstatSync!=`function`)return null;try{let e=n.readdirSync(t),r=[];for(let i of e){let e=t===`/`?`/${i}`:`${t}/${i}`;try{let t=n.lstatSync(e),a=t.isSymbolicLink()?`symlink`:t.isDirectory()?`directory`:`file`;r.push({name:i,type:a})}catch{}}return r}catch{return null}}statSync(e){let t=i(e);if(this.findMount(t))return null;let r=this.lfsSync;if(typeof r.statSync!=`function`||typeof r.lstatSync!=`function`||typeof r.readlinkSync!=`function`)return null;if(t===`/`)try{let e=r.statSync(t);return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs}}catch{return null}let a=t;for(let e=0;e<=10;e++){let e;try{e=r.lstatSync(a)}catch{return null}if(!e.isSymbolicLink())return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs};let t;try{t=r.readlinkSync(a)}catch{return null}a=t.startsWith(`/`)?i(t):i(o(n(a).dir,t))}return null}lstatSync(e){let t=i(e);if(this.findMount(t))return null;let n=this.lfsSync;if(typeof n.lstatSync!=`function`)return null;if(t===`/`)return this.statSync(t);try{let e=n.lstatSync(t);if(e.isSymbolicLink()){let r=n.readlinkSync?n.readlinkSync(t):``;return{type:`symlink`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,isSymlink:!0,symlinkTarget:r}}return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs}}catch{return null}}async mount(e,t,r){let a=i(e);if(this.mountPoints.has(a))throw new c(`EEXIST`,`mount point is already mounted`,a);try{if((await this.lstat(a)).type!==`directory`)throw new c(`ENOTDIR`,`mount point must be a directory`,a);if((await this.readDir(a)).length>0)throw new c(`ENOTEMPTY`,`mount point must be empty to avoid shadowing existing files`,a)}catch(e){if(!(e instanceof c)||e.code!==`ENOENT`)throw e}let{dir:o}=n(a);o!==`/`&&await this.mkdir(o,{recursive:!0});try{await this.lfs.mkdir(a)}catch{}if(this.mountPoints.set(a,t),t.kind===`local`){let e=r?.limits??p(r?.env??{});this.mountIndex.registerMount(a,t.getHandle(),e)}let s=K(t,a);try{this.mountSyncChannel?.postMessage({type:`mount`,path:a,descriptor:s})}catch{}if(this.watcher?.notify([{type:`modify`,path:a,entryType:`directory`}]),t.kind!==`hostfs`)try{let e={targetPath:a,descriptor:s,createdAt:Date.now()},n=t.kind===`local`?t.getHandle():void 0;await l(e,n)}catch{}}async unmount(e){let t=i(e),n=this.mountPoints.get(t);this.mountPoints.delete(t),this.mountIndex.unregisterMount(t);try{this.mountSyncChannel?.postMessage({type:`unmount`,path:t})}catch{}this.watcher?.notify([{type:`modify`,path:t,entryType:`directory`}]),await n?.close();try{await u(t)}catch{}}async reconstructBackendFromDescriptor(e,t){switch(e.kind){case`local`:{let t=await d(e.idbHandleKey);if(!t)throw Error(`no handle stored for ${e.idbHandleKey}`);return s.fromHandle(t,{mountId:e.mountId})}case`hostfs`:{let{HostFsMountBackend:n}=await import(`./backend-hostfs-bQQx-S0W.js`);return new n({targetPath:t,hostPath:e.hostPath,mountId:e.mountId})}case`s3`:{let{S3MountBackend:t,RemoteMountCache:n,makeSignedFetchS3:r}=await import(`./mount-iK3BWJwS.js`).then(e=>e.t),i=new n({mountId:e.mountId,ttlMs:3e4});return new t({source:e.source,profile:e.profile,cache:i,mountId:e.mountId,signedFetch:r(e.profile)})}case`da`:{let{DaMountBackend:t,RemoteMountCache:n,makeSignedFetchDa:r}=await import(`./mount-iK3BWJwS.js`).then(e=>e.t),i=new n({mountId:e.mountId,ttlMs:3e4});return new t({source:e.source,profile:e.profile,cache:i,mountId:e.mountId,signedFetch:r()})}case`aem`:{let{AemMountBackend:t,RemoteMountCache:n,makeSignedFetchDa:r}=await import(`./mount-iK3BWJwS.js`).then(e=>e.t),i=new n({mountId:e.mountId,ttlMs:3e4});return new t({source:e.source,profile:e.profile,cache:i,mountId:e.mountId,signedFetch:r()})}}}listMounts(){let e=[];for(let t of this.mountPoints.keys())this.internalMounts.has(t)||e.push(t);return e}listInternalMounts(){return[...this.internalMounts]}listMountPoints(){let e=[];for(let[t,n]of this.mountPoints)this.internalMounts.has(t)||e.push({path:t,kind:n.kind});return e}async mountInternal(e,t){let r=i(e);if(this.mountPoints.has(r))throw new c(`EEXIST`,`mount point is already mounted`,r);let{dir:a}=n(r);a!==`/`&&await this.mkdir(a,{recursive:!0});try{await this.lfs.mkdir(r)}catch{}this.mountPoints.set(r,t),this.internalMounts.add(r),this.watcher?.notify([{type:`modify`,path:r,entryType:`directory`}])}async unmountInternal(e){let t=i(e);if(!this.internalMounts.has(t))throw new c(`ENOENT`,`not an internal mount point`,t);let n=this.mountPoints.get(t);this.mountPoints.delete(t),this.internalMounts.delete(t),this.watcher?.notify([{type:`modify`,path:t,entryType:`directory`}]),await n?.close()}getMountIndex(){return this.mountIndex}async refreshMount(e,t){let n=i(e),r=this.mountPoints.get(n);if(!r)throw new c(`ENOENT`,`not a mount point`,n);let a=await r.refresh(t);return r.kind===`local`&&await this.mountIndex.refreshMount(n,p(t?.env??{})),this.watcher?.notify([{type:`modify`,path:n,entryType:`directory`}]),a}isPathUnderMount(e){for(let t of this.mountPoints.keys())if(e===t||e.startsWith(t+`/`))return!0;return!1}findMount(e){let t=null;for(let[n,r]of this.mountPoints)(e===n||e.startsWith(n+`/`))&&(!t||n.length>t.mountPath.length)&&(t={mountPath:n,backend:r});return t?e===t.mountPath?{path:t.mountPath,backend:t.backend,relParts:[]}:{path:t.mountPath,backend:t.backend,relParts:e.slice(t.mountPath.length+1).split(`/`).filter(Boolean)}:null}async readFile(e,t){return this.withKindMismatchRetry(e,()=>this.readFileInner(e,t))}async readFileInner(e,t){let n=i(e),r=this.findMount(n);if(r){if(r.relParts.length===0)throw new c(`EISDIR`,`is a directory`,n);let e=r.relParts.join(`/`);try{let n=await r.backend.readFile(e);return(t?.encoding??`utf-8`)===`utf-8`?new TextDecoder(`utf-8`).decode(n):n}catch(e){O(e,n)}}let a=await this.resolveSymlinks(n);try{return(t?.encoding??`utf-8`)===`utf-8`?await this.lfs.readFile(a,{encoding:`utf8`}):await this.lfs.readFile(a)}catch(e){throw A(e,n)}}async writeFile(e,t,n){return this.withKindMismatchRetry(e,()=>this.writeFileInner(e,t,n))}async writeFileInner(e,t,r){let a=i(e),o=this.findMount(a);if(o){if(o.relParts.length===0)throw new c(`EISDIR`,`is a directory`,a);let e=o.relParts.join(`/`),n=!1;try{await this.stat(a),n=!0}catch{}let r=typeof t==`string`?new TextEncoder().encode(t):t instanceof Uint8Array?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):new Uint8Array(t);try{await o.backend.writeFile(e,r)}catch(e){O(e,a)}this.watcher?.notify([{type:n?`modify`:`create`,path:a,entryType:`file`}]),this.mountIndex.notifyWrite(a);return}let s;try{s=await this.resolveSymlinks(a)}catch{s=a}let l=!1;try{await this.lfs.stat(s),l=!0}catch{}let{dir:u}=n(s);await this.withWriteLock(async()=>{this.markSidecarDirty(s),u!==`/`&&await this.mkdirRecursiveUnlocked(u);let e=typeof t==`string`?new TextEncoder().encode(t).byteLength:(t instanceof Uint8Array,t.byteLength);try{await this.lfs.writeFile(s,t)}catch(e){if(u!==`/`&&e instanceof Error&&e.message.includes(`ENOENT`)){await this.mkdirRecursiveUnlocked(u);try{await this.lfs.writeFile(s,t)}catch(e){throw A(e,a)}}else throw A(e,a)}try{await this.lfs.truncate?.(s,e)}catch(e){throw A(e,a)}}),this.watcher?.notify([{type:l?`modify`:`create`,path:s,entryType:`file`}])}async readDir(e){let t=i(e),n=this.findMount(t);return n?this.readDirMounted(t,n):this.readDirLocal(t)}async readDirMounted(e,t){let n=this.mountIndex.getDirectoryEntries(t.path,e);if(n!==void 0){let t=new Map;for(let e of n)t.set(e.name,{name:e.name,type:e.type});return this.addNestedMountEntries(t,e),[...t.values()]}let r=t.relParts.join(`/`)||`/`,i;try{i=await t.backend.readDir(r)}catch(t){O(t,e)}let a=new Map;for(let e of i)a.set(e.name,{name:e.name,type:e.kind===`directory`?`directory`:`file`});return this.addNestedMountEntries(a,e),[...a.values()]}async readDirLocal(e){return this.withKindMismatchRetry(e,()=>this.readDirLocalInner(e))}async readDirLocalInner(e){let t=await this.resolveSymlinks(e);try{let e=await this.lfs.readdir(t),n=[];for(let r of e){let e=await this.statDirEntry(t,r);e&&n.push(e)}return n}catch(t){throw A(t,e)}}async statDirEntry(e,t){let n=e===`/`?`/${t}`:`${e}/${t}`;try{let e=await this.lfs.lstat(n);return e.isSymbolicLink()?{name:t,type:`symlink`}:{name:t,type:e.isDirectory()?`directory`:`file`}}catch{return null}}addNestedMountEntries(e,t){let n=t===`/`?`/`:`${t}/`;for(let r of this.mountPoints.keys()){if(r===t||!r.startsWith(n))continue;let i=r.slice(n.length);!i||i.includes(`/`)||e.has(i)||e.set(i,{name:i,type:`directory`})}}async withWriteLock(t){let n=this.dbName,r,i=new Promise(e=>{r=e}),a=e.writeChains.get(n)??Promise.resolve();e.writeChains.set(n,i),await a;try{let e=globalThis.navigator?.locks;return this.backend!==`opfs`||typeof e?.request!=`function`?await t():await e.request(`slicc-vfs:${n}`,()=>t())}finally{r(),e.writeChains.get(n)===i&&e.writeChains.delete(n)}}async mkdirRecursiveUnlocked(e){let t=e.split(`/`).filter(Boolean),n=[],r=``;for(let e of t){r+=`/`+e;try{await this.lfs.mkdir(r),n.push(r)}catch(e){if(e instanceof Error&&!e.message.includes(`EEXIST`))throw A(e,r);try{let e=await this.lfs.lstat(r);if(!e.isDirectory()&&!e.isSymbolicLink())throw new c(`ENOTDIR`,`not a directory`,r)}catch(e){if(e instanceof c&&e.code===`ENOTDIR`)throw e}}}return n}async mkdir(e,t){let n=i(e);if(n===`/`)return;let r=this.findMount(n);if(r){if(r.relParts.length===0)return;let e=r.relParts.join(`/`),t=await this.exists(n);try{await r.backend.mkdir(e)}catch(e){O(e,n)}t||this.watcher?.notify([{type:`create`,path:n,entryType:`directory`}]);return}if(t?.recursive){let e=await this.withWriteLock(()=>(this.markSidecarDirty(n),this.mkdirRecursiveUnlocked(n)));e.length>0&&this.watcher?.notify(e.map(e=>({type:`create`,path:e,entryType:`directory`})))}else await this.withWriteLock(async()=>{this.markSidecarDirty(n);try{await this.lfs.mkdir(n)}catch(e){throw A(e,n)}}),this.watcher?.notify([{type:`create`,path:n,entryType:`directory`}])}async rm(e,t){return this.withKindMismatchRetry(i(e),()=>this.rmInner(e,t))}async rmInner(e,t){let n=i(e),r=this.findMount(n);if(r){if(r.relParts.length===0)throw new c(`EINVAL`,`cannot remove a mount point — use unmount`,n);let e;try{e=(await this.stat(n)).type}catch{}let i=r.relParts.join(`/`);try{await r.backend.remove(i,{recursive:t?.recursive})}catch(e){O(e,n)}this.watcher?.notify([{type:`delete`,path:n,entryType:e}]),this.mountIndex.notifyDelete(n);return}try{let e=await this.lfs.lstat(n);await this.withWriteLock(async()=>{e.isSymbolicLink()?await this.lfs.unlink(n):e.isDirectory()?t?.recursive?await this.rmRecursiveUnlocked(n):await this.lfs.rmdir(n):await this.lfs.unlink(n),this.markSidecarDirty(n,`prefix`),await this.writeOpfsMetadataSidecarUnlocked()})}catch(e){throw A(e,n)}this.watcher?.notify([{type:`delete`,path:n}])}async rmRecursiveUnlocked(e){let t=await this.lfs.readdir(e);for(let n of t){let t=e===`/`?`/${n}`:`${e}/${n}`,r=await this.lfs.lstat(t);r.isSymbolicLink()?await this.lfs.unlink(t):r.isDirectory()?await this.rmRecursiveUnlocked(t):await this.lfs.unlink(t)}await this.lfs.rmdir(e)}async stat(e){return this.withKindMismatchRetry(e,()=>this.statInner(e))}async statInner(e){let t=i(e),n=this.findMount(t);if(n){if(n.relParts.length===0)try{let e=await this.lfs.stat(t);return{type:`directory`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs}}catch{return{type:`directory`,size:0,mtime:Date.now(),ctime:Date.now()}}let e=n.relParts.join(`/`);try{let t=await n.backend.stat(e);return{type:t.kind===`directory`?`directory`:`file`,size:t.size,mtime:t.mtime,ctime:t.mtime}}catch(e){O(e,t)}}let r=await this.resolveSymlinks(t);try{let e=await this.lfs.stat(r);return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs}}catch(e){throw A(e,t)}}async exists(e){let t=i(e),n=this.findMount(t);if(n){if(n.relParts.length===0)return!0;try{return await this.stat(t),!0}catch{return!1}}try{return await this.stat(t),!0}catch{try{return await this.lfs.lstat(t),!0}catch{return!1}}}async rename(e,t){return this.withKindMismatchRetryPaths([i(e),i(t)],()=>this.renameInner(e,t))}async renameInner(e,t){let n=i(e),r=i(t),a;try{a=(await this.lstat(n)).type}catch{}let o=this.findMount(n);if(o?.backend.rename){let e=this.findMount(r);if(e&&e.backend===o.backend){try{await o.backend.rename(o.relParts.join(`/`),e.relParts.join(`/`))}catch(e){O(e,n)}this.watcher?.notify([{type:`delete`,path:n,entryType:a},{type:`create`,path:r,entryType:a}]),this.mountIndex.notifyRename(n,r);return}}try{await this.withWriteLock(async()=>{this.markSidecarDirty(n,`prefix`),this.markSidecarDirty(r,`prefix`),await this.lfs.rename(n,r),await this.writeOpfsMetadataSidecarUnlocked()})}catch(e){throw A(e,n)}this.watcher?.notify([{type:`delete`,path:n,entryType:a},{type:`create`,path:r,entryType:a}]),this.mountIndex.notifyRename(n,r)}async readTextFile(e){return await this.readFile(e,{encoding:`utf-8`})}async*walk(e,t,n=0){yield*H({mountPoints:this.mountPoints,mountIndex:this.mountIndex,realpath:e=>this.realpath(e),readDir:e=>this.readDir(e),stat:e=>this.stat(e)},e,t,n)}async copyFile(e,t){if((await this.stat(e)).type===`directory`)throw new c(`EISDIR`,`is a directory`,e);let n=await this.readFile(e,{encoding:`binary`});await this.writeFile(t,n)}dirname(e){return n(i(e)).dir}basename(e){return n(i(e)).base}async symlink(e,t){let r=i(t);if(this.findMount(r))throw new c(`EINVAL`,`symlinks not supported on mounted filesystems`,r);let{dir:a}=n(r);await this.withWriteLock(async()=>{a!==`/`&&await this.mkdirRecursiveUnlocked(a);try{await this.lfs.symlink(e,r)}catch(t){if(a!==`/`&&t instanceof Error&&t.message.includes(`ENOENT`)){await this.mkdirRecursiveUnlocked(a);try{await this.lfs.symlink(e,r)}catch(e){throw A(e,r)}}else throw A(t,r)}this.markSidecarDirty(r),await this.writeOpfsMetadataSidecarUnlocked()}),this.watcher?.notify([{type:`create`,path:r,entryType:`symlink`}])}async readlink(e){let t=i(e);try{return await this.lfs.readlink(t)}catch(e){throw A(e,t)}}async lstat(e){let t=i(e);if(this.findMount(t)||t===`/`)return this.stat(t);try{let e=await this.lfs.lstat(t);if(e.isSymbolicLink()){let n=await this.lfs.readlink(t);return{type:`symlink`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,isSymlink:!0,symlinkTarget:n}}return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs}}catch(e){throw A(e,t)}}async realpath(e){return R(this.lfs,e=>this.findMount(e)!==null,e)}resolveSymlinks(e){return z(this.lfs,e=>this.findMount(e)!==null,e)}},J=e({FsError:()=>c,FsWatcher:()=>x,MountIndex:()=>m,RestrictedFS:()=>D,VirtualFS:()=>q,joinPath:()=>o,normalizePath:()=>i,pathSegments:()=>r,resolveVfsBackendFromEnv:()=>G,splitPath:()=>n});export{x as a,w as i,q as n,D as r,J as t};
@@ -0,0 +1,7 @@
1
+ import{n as e}from"./rolldown-runtime-Dd_uD5pT.js";var t=e({GLOBAL_GITCONFIG_PATH:()=>n,readGlobalGitConfigValue:()=>u,removeGitConfigKey:()=>g,writeGlobalGitConfigValue:()=>h});const n=`/workspace/.gitconfig`,r=/^\[(\w+)(?:\s+"([^"]*)")?\]$/,i=/^(\w+)\s*=/,a=/^(\w+)\s*=\s*(.*)$/;function o(e){let t=e.split(`.`),n=t.pop()??``;return{section:t.join(`.`),configKey:n}}function s(e){let t=e.match(r);if(!t)return;let n=t[1].toLowerCase(),i=t[2]??``;return i?`${n}.${i}`:n}function c(e){let t=e.split(`.`);return t.length>1?`[${t[0]} "${t.slice(1).join(`.`)}"]`:`[${e}]`}function l(e,t){return`\t${e} = ${t}`}async function u(e,t){let r;try{r=await e.readTextFile(n)}catch{return}let{section:i,configKey:c}=o(t),l=``;for(let e of r.split(`
2
+ `)){let t=e.trim(),n=s(t);if(n!==void 0){l=n;continue}if(l!==i)continue;let r=t.match(a);if(r&&r[1]===c)return r[2].trim()}}function d(e,t,n,r){let a=``;for(let o=0;o<e.length;o++){let c=e[o].trim(),u=s(c);if(u!==void 0){a=u;continue}if(a!==t)continue;let d=c.match(i);if(d&&d[1]===n)return e[o]=l(n,r),!0}return!1}function f(e,t){for(let n of e)if(s(n.trim())===t)return!0;return!1}function p(e,t,n,r){for(let i=e.length-1;i>=0;i--)if(s(e[i].trim())===t){e.splice(i+1,0,l(n,r));return}}function m(e,t,n,r){let i=c(t),a=l(n,r);return e?e.trimEnd()+`\n${i}\n${a}\n`:`${i}\n${a}\n`}async function h(e,t,r){let i=``;try{i=await e.readTextFile(n)}catch{}let{section:a,configKey:s}=o(t),c=i.split(`
3
+ `);if(d(c,a,s,r)){await e.writeFile(n,c.join(`
4
+ `));return}if(f(c,a)){p(c,a,s,r),await e.writeFile(n,c.join(`
5
+ `));return}await e.writeFile(n,m(i,a,s,r))}function g(e,t){let{section:n,configKey:r}=o(t),a=e.split(`
6
+ `),c=[],l=``;for(let e of a){let t=e.trim(),a=s(t);if(a!==void 0){l=a,c.push(e);continue}if(l===n){let e=t.match(i);if(e&&e[1]===r)continue}c.push(e)}return c.join(`
7
+ `)}export{h as a,g as i,t as n,u as r,n as t};
@@ -0,0 +1,5 @@
1
+ var e=`/workspace/.gitconfig`,t=/^\[(\w+)(?:\s+"([^"]*)")?\]$/,n=/^(\w+)\s*=/,r=/^(\w+)\s*=\s*(.*)$/;function i(e){let t=e.split(`.`),n=t.pop()??``;return{section:t.join(`.`),configKey:n}}function a(e){let n=e.match(t);if(!n)return;let r=n[1].toLowerCase(),i=n[2]??``;return i?`${r}.${i}`:r}function o(e){let t=e.split(`.`);return t.length>1?`[${t[0]} "${t.slice(1).join(`.`)}"]`:`[${e}]`}function s(e,t){return`\t${e} = ${t}`}async function c(t,n){let o;try{o=await t.readTextFile(e)}catch{return}let{section:s,configKey:c}=i(n),l=``;for(let e of o.split(`
2
+ `)){let t=e.trim(),n=a(t);if(n!==void 0){l=n;continue}if(l!==s)continue;let i=t.match(r);if(i&&i[1]===c)return i[2].trim()}}function l(e,t,r,i){let o=``;for(let c=0;c<e.length;c++){let l=e[c].trim(),u=a(l);if(u!==void 0){o=u;continue}if(o!==t)continue;let d=l.match(n);if(d&&d[1]===r)return e[c]=s(r,i),!0}return!1}function u(e,t){for(let n of e)if(a(n.trim())===t)return!0;return!1}function d(e,t,n,r){for(let i=e.length-1;i>=0;i--)if(a(e[i].trim())===t){e.splice(i+1,0,s(n,r));return}}function f(e,t,n,r){let i=o(t),a=s(n,r);return e?e.trimEnd()+`\n${i}\n${a}\n`:`${i}\n${a}\n`}async function p(t,n,r){let a=``;try{a=await t.readTextFile(e)}catch{}let{section:o,configKey:s}=i(n),c=a.split(`
3
+ `);if(l(c,o,s,r)){await t.writeFile(e,c.join(`
4
+ `));return}if(u(c,o)){d(c,o,s,r),await t.writeFile(e,c.join(`
5
+ `));return}await t.writeFile(e,f(a,o,s,r))}export{c as readGlobalGitConfigValue,p as writeGlobalGitConfigValue};
@@ -1,2 +1,2 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/fs-qMMHgiDM.js","assets/rolldown-runtime-Dd_uD5pT.js","assets/preload-helper-Czpn1I53.js","assets/logger-DDBAeTLF.js","assets/tool-ui-DfXu6quJ.js","assets/path-utils-DNJG-zQf.js","assets/types-idfTVsM8.js","assets/virtual-device-paths-9EXC9iPp.js","assets/picker-approval-D89YhXsA.js","assets/html-B_Hg2WOy.js","assets/mount-picker-popup-Bc3ca2Vl.js","assets/logger-BoSvu4mW.js","assets/picker-popup-Bwcnocm6.js","assets/runtime-env-Dlaokqg1.js","assets/runtime-env-CgsZ7LTp.js","assets/runtime-env-E-i2SW1s.js","assets/src-CAWTvdAa.js","assets/mount-table-store-dY2IfQ5S.js"])))=>i.map(i=>d[i]);
2
- import{H as e,S as t,d as n}from"./account-store-BHr78r-q.js";import{t as r}from"./preload-helper-Czpn1I53.js";import"./proxied-fetch-BGeNrvQ4.js";import{r as i,t as a}from"./silent-renew-backoff-t_Cd4Zw7.js";import{r as o}from"./api-endpoint-GRCyib6X.js";import{i as s,t as c}from"./tray-runtime-config-D7cmCcHJ.js";import"./main-DjAHuk3R.js";import{getOAuthPageOrigin as l,resolveOAuthDelegation as u}from"./oauth-service-Uk8UIb05.js";import{t as d}from"./global-db-CbuLl-zx.js";var f={clientId:``,scopes:`repo,read:user,user:email`};function p(){try{let e=localStorage.getItem(s);if(e)return e.replace(/\/$/,``)}catch{}return c}function m(e){return{access_token:e.access_token,token_type:e.token_type,scope:e.scope,refresh_token:e.refresh_token,expires_in:e.expires_in}}async function h(e){let t;try{t=await e.json()}catch{throw Error(`Token exchange failed (HTTP ${e.status}): non-JSON response`)}if(!e.ok&&e.status!==200){let n=t.error_description??t.error??`Token exchange failed (HTTP ${e.status})`;throw Error(n)}if(t.error){let e=t.error_description??t.error;throw Error(e)}return m(t)}async function g(e){let t=`${p()}/oauth/token`;return h(await fetch(t,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:e.provider,code:e.code,redirect_uri:e.redirectUri})}))}async function _(e){let t=`${p()}/oauth/token`;return h(await fetch(t,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:e.provider,refresh_token:e.refreshToken})}))}async function v(e){let t=`${p()}/oauth/revoke`,n=await fetch(t,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:e.provider,access_token:e.accessToken})});if(!(n.status===204||n.ok)){if(n.status===400)try{if((await n.json()).error===`unsupported`)return}catch{}throw Error(`Token revocation failed (HTTP ${n.status})`)}}var y=Object.assign({"/packages/webapp/providers/github-config.json":f})[`/packages/webapp/providers/github-config.json`]??{clientId:``,scopes:`repo,read:user,user:email`},b=null,x=null;function S(e){let{isExtension:t,isConnectMode:n,workerBaseUrl:r,pageOrigin:a,pageHref:o,bridgeApiBaseUrl:s,extensionId:c,nonce:l}=e;if(t)return{redirectUri:`${r}/auth/callback`,state:{source:`extension`,extensionId:c,path:`/github`,nonce:l}};if(e.delegated)return{redirectUri:`${e.runtimeWorkerBaseUrl??r}/auth/callback`,state:{source:`opener`,path:`/auth/callback`,nonce:l}};if(n){let e=a??``;if(/^https?:\/\/(localhost|127\.0\.0\.1):\d+$/.test(e)){let t=parseInt(new URL(o??e).port||`8790`,10);return{redirectUri:`${r}/auth/callback`,state:{source:`local`,port:t,path:`/auth/callback`,nonce:l}}}return{redirectUri:`${r}/auth/callback`,state:{source:`remote`,origin:e,path:`/auth/callback`,nonce:l}}}if(s&&o&&i(o)){let t=null;try{let e=new URL(s);(e.hostname===`localhost`||e.hostname===`127.0.0.1`)&&(t=parseInt(e.port||`5710`,10))}catch{t=null}if(t!==null&&!Number.isNaN(t))return{redirectUri:`${e.runtimeWorkerBaseUrl??r}/auth/callback`,state:{source:`local`,port:t,path:`/auth/callback`,nonce:l}}}return{redirectUri:`${e.runtimeWorkerBaseUrl??a??``}/auth/callback`,state:{port:parseInt(new URL(o??a??`http://localhost:5710`).port||`5710`,10),path:`/auth/callback`,nonce:l}}}async function C(){if(b)return b;if(w){try{let e=await fetch(`${p()}/api/runtime-config`);if(e.ok){let t=await e.json();if(t.oauth?.github)return b=t.oauth.github,b}}catch{}return y.clientId}try{let e=await fetch(`/api/runtime-config`);if(e.ok){let t=await e.json();if(t.oauth?.github)return b=t.oauth.github,t.trayWorkerBaseUrl&&(x=t.trayWorkerBaseUrl),b;if(t.trayWorkerBaseUrl){x=t.trayWorkerBaseUrl;let e=await fetch(`${t.trayWorkerBaseUrl}/api/runtime-config`);if(e.ok){let t=await e.json();if(t.oauth?.github)return b=t.oauth.github,b}}}}catch{}return y.clientId}var w=typeof globalThis<`u`&&typeof globalThis.chrome?.runtime?.id==`string`;function T(){return n().find(e=>e.providerId===`github`)}function E(e){try{return new URL(e).searchParams.get(`code`)}catch{return null}}async function D(e){try{let t=await fetch(`https://api.github.com/user`,{headers:{Authorization:`Bearer ${e}`,Accept:`application/vnd.github+json`}});if(t.ok){let e=await t.json();return{name:e.name||e.login,avatar:e.avatar_url,login:e.login,id:e.id}}}catch(e){console.warn(`[github] Failed to fetch user profile:`,e instanceof Error?e.message:String(e))}return{}}function O(e,t){return`${e}+${t}@users.noreply.github.com`}async function k(e){try{let{VirtualFS:t}=await r(async()=>{let{VirtualFS:e}=await import(`./fs-qMMHgiDM.js`).then(e=>e.t);return{VirtualFS:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17]));await(await t.create({dbName:d})).writeFile(`/workspace/.git/github-token`,e),typeof window<`u`&&window.dispatchEvent(new CustomEvent(`github-token-changed`))}catch(e){console.warn(`[github] Failed to write git token:`,e instanceof Error?e.message:String(e))}}async function A(){try{let{VirtualFS:e}=await r(async()=>{let{VirtualFS:e}=await import(`./fs-qMMHgiDM.js`).then(e=>e.t);return{VirtualFS:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17]));await(await e.create({dbName:d})).rm(`/workspace/.git/github-token`),typeof window<`u`&&window.dispatchEvent(new CustomEvent(`github-token-changed`))}catch{}}async function j(e){if(!(!e.login||e.id===void 0))try{let{VirtualFS:t}=await r(async()=>{let{VirtualFS:e}=await import(`./fs-qMMHgiDM.js`).then(e=>e.t);return{VirtualFS:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17])),{readGlobalGitConfigValue:n,writeGlobalGitConfigValue:i}=await r(async()=>{let{readGlobalGitConfigValue:e,writeGlobalGitConfigValue:t}=await import(`./git-config-DLJIrKjL.js`);return{readGlobalGitConfigValue:e,writeGlobalGitConfigValue:t}},[]),a=await t.create({dbName:d}),o=e.name||e.login,s=O(e.id,e.login);!await n(a,`user.name`)&&o&&await i(a,`user.name`,o),await n(a,`user.email`)||await i(a,`user.email`,s)}catch(e){console.warn(`[github] Failed to seed git identity:`,e instanceof Error?e.message:String(e))}}var M=a();async function N(){try{let n=T();if(!n?.refreshToken)return null;let r=await _({provider:`github`,refreshToken:n.refreshToken});await e({providerId:`github`,accessToken:r.access_token,refreshToken:r.refresh_token,tokenExpiresAt:r.expires_in?Date.now()+r.expires_in*1e3:void 0,userName:n.userName,userAvatar:n.userAvatar,scopes:r.scope??n.scopes});let i=t(`github`)?.maskedValue;return i?await k(i):await A(),r.access_token}catch(e){return console.warn(`[github] Silent renewal failed:`,e instanceof Error?e.message:String(e)),null}}async function P(){let e=T();if(!e?.accessToken)throw Error(`Not logged in to GitHub — please log in first`);if((e.tokenExpiresAt??1/0)-Date.now()>6e4)return e.accessToken;let t=await M.run(()=>N());if(t)return t;let n=T();if((n?.tokenExpiresAt??1/0)-Date.now()>0&&n?.accessToken)return n.accessToken;throw Error(`GitHub session expired — please log in again`)}var F={id:`github`,name:`GitHub`,description:"Sign in with GitHub for git authentication (push/pull/clone) and the `oauth-token github` shell command. Does not expose LLM models — use the GitHub Copilot provider for those.",requiresApiKey:!1,requiresBaseUrl:!1,isOAuth:!0,oauthTokenDomains:[`github.com`,`*.github.com`,`api.github.com`,`raw.githubusercontent.com`],getModelIds:()=>[],onOAuthLogin:async(n,r,i)=>{let a=await C();if(!a)throw Error(`GitHub OAuth not configured — no client ID available`);let s=i?.scopes??y.scopes,c=w?null:await l(),d=!w&&await u(),f=crypto.randomUUID(),m=w?chrome.runtime.id:``,{redirectUri:h,state:_}=S({isExtension:w,isConnectMode:!!globalThis.__slicc_connect_mode,workerBaseUrl:p(),runtimeWorkerBaseUrl:x,pageOrigin:c?.origin??null,pageHref:c?.href??null,bridgeApiBaseUrl:o(),delegated:d,extensionId:m,nonce:f}),v=btoa(JSON.stringify(_)),b=f,T=new URLSearchParams({client_id:a,scope:s,redirect_uri:h});v&&T.set(`state`,v);let O=await n(`https://github.com/login/oauth/authorize?${T}`);if(!O)return;if(b)try{if(new URL(O).searchParams.get(`nonce`)!==b){console.error(`[github] OAuth nonce mismatch — possible CSRF`);return}}catch(e){console.warn(`[github] Nonce check skipped (URL parse failed):`,e instanceof Error?e.message:String(e))}let M=E(O);if(!M){console.error(`[github] Could not extract authorization code from redirect URL`);return}let N=await g({provider:`github`,code:M,redirectUri:h}),P=await D(N.access_token);await e({providerId:`github`,accessToken:N.access_token,refreshToken:N.refresh_token,tokenExpiresAt:N.expires_in?Date.now()+N.expires_in*1e3:void 0,userName:P.name,userAvatar:P.avatar,scopes:N.scope});let F=t(`github`)?.maskedValue;F?await k(F):await A(),await j(P),r()},onSilentRenew:N,getValidAccessToken:P,onOAuthLogout:async()=>{let t=T();t?.accessToken&&await v({provider:`github`,accessToken:t.accessToken}).catch(e=>console.warn(`[github] Token revocation failed:`,e instanceof Error?e.message:String(e))),await A(),await e({providerId:`github`,accessToken:``})},getOAuthLogoutUrl:e=>`https://github.com/logout`};export{O as buildNoreplyEmail,F as config,E as extractCodeFromUrl,P as getValidAccessToken,S as resolveGithubOAuthRedirect,j as syncGitIdentityFromGitHub};
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/fs-CvM7tq2t.js","assets/rolldown-runtime-Dd_uD5pT.js","assets/preload-helper-Czpn1I53.js","assets/logger-DDBAeTLF.js","assets/tool-ui-DfXu6quJ.js","assets/path-utils-DNJG-zQf.js","assets/types-idfTVsM8.js","assets/virtual-device-paths-9EXC9iPp.js","assets/picker-approval-D89YhXsA.js","assets/html-B_Hg2WOy.js","assets/mount-picker-popup-Bc3ca2Vl.js","assets/logger-BoSvu4mW.js","assets/picker-popup-Bwcnocm6.js","assets/runtime-env-Dlaokqg1.js","assets/runtime-env-CgsZ7LTp.js","assets/runtime-env-E-i2SW1s.js","assets/src-CAWTvdAa.js","assets/mount-table-store-dY2IfQ5S.js"])))=>i.map(i=>d[i]);
2
+ import{H as e,S as t,d as n}from"./account-store-CYMEkNNe.js";import{t as r}from"./preload-helper-Czpn1I53.js";import"./proxied-fetch-BGeNrvQ4.js";import{r as i,t as a}from"./silent-renew-backoff-t_Cd4Zw7.js";import{r as o}from"./api-endpoint-GRCyib6X.js";import{i as s,t as c}from"./tray-runtime-config-D7cmCcHJ.js";import"./main-B6Og2ks7.js";import{getOAuthPageOrigin as l,resolveOAuthDelegation as u}from"./oauth-service-Uk8UIb05.js";import{t as d}from"./global-db-CbuLl-zx.js";var f={clientId:``,scopes:`repo,read:user,user:email`};function p(){try{let e=localStorage.getItem(s);if(e)return e.replace(/\/$/,``)}catch{}return c}function m(e){return{access_token:e.access_token,token_type:e.token_type,scope:e.scope,refresh_token:e.refresh_token,expires_in:e.expires_in}}async function h(e){let t;try{t=await e.json()}catch{throw Error(`Token exchange failed (HTTP ${e.status}): non-JSON response`)}if(!e.ok&&e.status!==200){let n=t.error_description??t.error??`Token exchange failed (HTTP ${e.status})`;throw Error(n)}if(t.error){let e=t.error_description??t.error;throw Error(e)}return m(t)}async function g(e){let t=`${p()}/oauth/token`;return h(await fetch(t,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:e.provider,code:e.code,redirect_uri:e.redirectUri})}))}async function _(e){let t=`${p()}/oauth/token`;return h(await fetch(t,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:e.provider,refresh_token:e.refreshToken})}))}async function v(e){let t=`${p()}/oauth/revoke`,n=await fetch(t,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:e.provider,access_token:e.accessToken})});if(!(n.status===204||n.ok)){if(n.status===400)try{if((await n.json()).error===`unsupported`)return}catch{}throw Error(`Token revocation failed (HTTP ${n.status})`)}}var y=Object.assign({"/packages/webapp/providers/github-config.json":f})[`/packages/webapp/providers/github-config.json`]??{clientId:``,scopes:`repo,read:user,user:email`},b=null,x=null;function S(e){let{isExtension:t,isConnectMode:n,workerBaseUrl:r,pageOrigin:a,pageHref:o,bridgeApiBaseUrl:s,extensionId:c,nonce:l}=e;if(t)return{redirectUri:`${r}/auth/callback`,state:{source:`extension`,extensionId:c,path:`/github`,nonce:l}};if(e.delegated)return{redirectUri:`${e.runtimeWorkerBaseUrl??r}/auth/callback`,state:{source:`opener`,path:`/auth/callback`,nonce:l}};if(n){let e=a??``;if(/^https?:\/\/(localhost|127\.0\.0\.1):\d+$/.test(e)){let t=parseInt(new URL(o??e).port||`8790`,10);return{redirectUri:`${r}/auth/callback`,state:{source:`local`,port:t,path:`/auth/callback`,nonce:l}}}return{redirectUri:`${r}/auth/callback`,state:{source:`remote`,origin:e,path:`/auth/callback`,nonce:l}}}if(s&&o&&i(o)){let t=null;try{let e=new URL(s);(e.hostname===`localhost`||e.hostname===`127.0.0.1`)&&(t=parseInt(e.port||`5710`,10))}catch{t=null}if(t!==null&&!Number.isNaN(t))return{redirectUri:`${e.runtimeWorkerBaseUrl??r}/auth/callback`,state:{source:`local`,port:t,path:`/auth/callback`,nonce:l}}}return{redirectUri:`${e.runtimeWorkerBaseUrl??a??``}/auth/callback`,state:{port:parseInt(new URL(o??a??`http://localhost:5710`).port||`5710`,10),path:`/auth/callback`,nonce:l}}}async function C(){if(b)return b;if(w){try{let e=await fetch(`${p()}/api/runtime-config`);if(e.ok){let t=await e.json();if(t.oauth?.github)return b=t.oauth.github,b}}catch{}return y.clientId}try{let e=await fetch(`/api/runtime-config`);if(e.ok){let t=await e.json();if(t.oauth?.github)return b=t.oauth.github,t.trayWorkerBaseUrl&&(x=t.trayWorkerBaseUrl),b;if(t.trayWorkerBaseUrl){x=t.trayWorkerBaseUrl;let e=await fetch(`${t.trayWorkerBaseUrl}/api/runtime-config`);if(e.ok){let t=await e.json();if(t.oauth?.github)return b=t.oauth.github,b}}}}catch{}return y.clientId}var w=typeof globalThis<`u`&&typeof globalThis.chrome?.runtime?.id==`string`;function T(){return n().find(e=>e.providerId===`github`)}function E(e){try{return new URL(e).searchParams.get(`code`)}catch{return null}}async function D(e){try{let t=await fetch(`https://api.github.com/user`,{headers:{Authorization:`Bearer ${e}`,Accept:`application/vnd.github+json`}});if(t.ok){let e=await t.json();return{name:e.name||e.login,avatar:e.avatar_url,login:e.login,id:e.id}}}catch(e){console.warn(`[github] Failed to fetch user profile:`,e instanceof Error?e.message:String(e))}return{}}function O(e,t){return`${e}+${t}@users.noreply.github.com`}async function k(e){try{let{VirtualFS:t}=await r(async()=>{let{VirtualFS:e}=await import(`./fs-CvM7tq2t.js`).then(e=>e.t);return{VirtualFS:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17]));await(await t.create({dbName:d})).writeFile(`/workspace/.git/github-token`,e),typeof window<`u`&&window.dispatchEvent(new CustomEvent(`github-token-changed`))}catch(e){console.warn(`[github] Failed to write git token:`,e instanceof Error?e.message:String(e))}}async function A(){try{let{VirtualFS:e}=await r(async()=>{let{VirtualFS:e}=await import(`./fs-CvM7tq2t.js`).then(e=>e.t);return{VirtualFS:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17]));await(await e.create({dbName:d})).rm(`/workspace/.git/github-token`),typeof window<`u`&&window.dispatchEvent(new CustomEvent(`github-token-changed`))}catch{}}async function j(e){if(!(!e.login||e.id===void 0))try{let{VirtualFS:t}=await r(async()=>{let{VirtualFS:e}=await import(`./fs-CvM7tq2t.js`).then(e=>e.t);return{VirtualFS:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17])),{readGlobalGitConfigValue:n,writeGlobalGitConfigValue:i}=await r(async()=>{let{readGlobalGitConfigValue:e,writeGlobalGitConfigValue:t}=await import(`./git-config-D2u6LGfT.js`);return{readGlobalGitConfigValue:e,writeGlobalGitConfigValue:t}},[]),a=await t.create({dbName:d}),o=e.name||e.login,s=O(e.id,e.login);!await n(a,`user.name`)&&o&&await i(a,`user.name`,o),await n(a,`user.email`)||await i(a,`user.email`,s)}catch(e){console.warn(`[github] Failed to seed git identity:`,e instanceof Error?e.message:String(e))}}var M=a();async function N(){try{let n=T();if(!n?.refreshToken)return null;let r=await _({provider:`github`,refreshToken:n.refreshToken});await e({providerId:`github`,accessToken:r.access_token,refreshToken:r.refresh_token,tokenExpiresAt:r.expires_in?Date.now()+r.expires_in*1e3:void 0,userName:n.userName,userAvatar:n.userAvatar,scopes:r.scope??n.scopes});let i=t(`github`)?.maskedValue;return i?await k(i):await A(),r.access_token}catch(e){return console.warn(`[github] Silent renewal failed:`,e instanceof Error?e.message:String(e)),null}}async function P(){let e=T();if(!e?.accessToken)throw Error(`Not logged in to GitHub — please log in first`);if((e.tokenExpiresAt??1/0)-Date.now()>6e4)return e.accessToken;let t=await M.run(()=>N());if(t)return t;let n=T();if((n?.tokenExpiresAt??1/0)-Date.now()>0&&n?.accessToken)return n.accessToken;throw Error(`GitHub session expired — please log in again`)}var F={id:`github`,name:`GitHub`,description:"Sign in with GitHub for git authentication (push/pull/clone) and the `oauth-token github` shell command. Does not expose LLM models — use the GitHub Copilot provider for those.",requiresApiKey:!1,requiresBaseUrl:!1,isOAuth:!0,oauthTokenDomains:[`github.com`,`*.github.com`,`api.github.com`,`raw.githubusercontent.com`],getModelIds:()=>[],onOAuthLogin:async(n,r,i)=>{let a=await C();if(!a)throw Error(`GitHub OAuth not configured — no client ID available`);let s=i?.scopes??y.scopes,c=w?null:await l(),d=!w&&await u(),f=crypto.randomUUID(),m=w?chrome.runtime.id:``,{redirectUri:h,state:_}=S({isExtension:w,isConnectMode:!!globalThis.__slicc_connect_mode,workerBaseUrl:p(),runtimeWorkerBaseUrl:x,pageOrigin:c?.origin??null,pageHref:c?.href??null,bridgeApiBaseUrl:o(),delegated:d,extensionId:m,nonce:f}),v=btoa(JSON.stringify(_)),b=f,T=new URLSearchParams({client_id:a,scope:s,redirect_uri:h});v&&T.set(`state`,v);let O=await n(`https://github.com/login/oauth/authorize?${T}`);if(!O)return;if(b)try{if(new URL(O).searchParams.get(`nonce`)!==b){console.error(`[github] OAuth nonce mismatch — possible CSRF`);return}}catch(e){console.warn(`[github] Nonce check skipped (URL parse failed):`,e instanceof Error?e.message:String(e))}let M=E(O);if(!M){console.error(`[github] Could not extract authorization code from redirect URL`);return}let N=await g({provider:`github`,code:M,redirectUri:h}),P=await D(N.access_token);await e({providerId:`github`,accessToken:N.access_token,refreshToken:N.refresh_token,tokenExpiresAt:N.expires_in?Date.now()+N.expires_in*1e3:void 0,userName:P.name,userAvatar:P.avatar,scopes:N.scope});let F=t(`github`)?.maskedValue;F?await k(F):await A(),await j(P),r()},onSilentRenew:N,getValidAccessToken:P,onOAuthLogout:async()=>{let t=T();t?.accessToken&&await v({provider:`github`,accessToken:t.accessToken}).catch(e=>console.warn(`[github] Token revocation failed:`,e instanceof Error?e.message:String(e))),await A(),await e({providerId:`github`,accessToken:``})},getOAuthLogoutUrl:e=>`https://github.com/logout`};export{O as buildNoreplyEmail,F as config,E as extractCodeFromUrl,P as getValidAccessToken,S as resolveGithubOAuthRedirect,j as syncGitIdentityFromGitHub};
@@ -1 +1 @@
1
- import"./proxied-fetch-Co-pb0x0.js";import{H as e,S as t,d as n}from"./account-store-DhN2-vXh.js";import{r}from"./api-endpoint-C00IT5T9.js";import{r as i,t as a}from"./tray-runtime-config-CVoPQrT2.js";import{t as o}from"./global-db-DJXlpNui.js";import{r as s,t as c}from"./silent-renew-backoff-C_Iv54ZG.js";import{getOAuthPageOrigin as l,resolveOAuthDelegation as u}from"./oauth-service-CTntqv0R.js";import"./provider-settings-D24NB2-U.js";var d={clientId:``,scopes:`repo,read:user,user:email`};function f(){try{let e=localStorage.getItem(i);if(e)return e.replace(/\/$/,``)}catch{}return a}function p(e){return{access_token:e.access_token,token_type:e.token_type,scope:e.scope,refresh_token:e.refresh_token,expires_in:e.expires_in}}async function m(e){let t;try{t=await e.json()}catch{throw Error(`Token exchange failed (HTTP ${e.status}): non-JSON response`)}if(!e.ok&&e.status!==200){let n=t.error_description??t.error??`Token exchange failed (HTTP ${e.status})`;throw Error(n)}if(t.error){let e=t.error_description??t.error;throw Error(e)}return p(t)}async function h(e){let t=`${f()}/oauth/token`;return m(await fetch(t,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:e.provider,code:e.code,redirect_uri:e.redirectUri})}))}async function g(e){let t=`${f()}/oauth/token`;return m(await fetch(t,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:e.provider,refresh_token:e.refreshToken})}))}async function _(e){let t=`${f()}/oauth/revoke`,n=await fetch(t,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:e.provider,access_token:e.accessToken})});if(!(n.status===204||n.ok)){if(n.status===400)try{if((await n.json()).error===`unsupported`)return}catch{}throw Error(`Token revocation failed (HTTP ${n.status})`)}}const v=Object.assign({"/packages/webapp/providers/github-config.json":d})[`/packages/webapp/providers/github-config.json`]??{clientId:``,scopes:`repo,read:user,user:email`};let y=null,b=null;function x(e){let{isExtension:t,isConnectMode:n,workerBaseUrl:r,pageOrigin:i,pageHref:a,bridgeApiBaseUrl:o,extensionId:c,nonce:l}=e;if(t)return{redirectUri:`${r}/auth/callback`,state:{source:`extension`,extensionId:c,path:`/github`,nonce:l}};if(e.delegated)return{redirectUri:`${e.runtimeWorkerBaseUrl??r}/auth/callback`,state:{source:`opener`,path:`/auth/callback`,nonce:l}};if(n){let e=i??``;if(/^https?:\/\/(localhost|127\.0\.0\.1):\d+$/.test(e)){let t=parseInt(new URL(a??e).port||`8790`,10);return{redirectUri:`${r}/auth/callback`,state:{source:`local`,port:t,path:`/auth/callback`,nonce:l}}}return{redirectUri:`${r}/auth/callback`,state:{source:`remote`,origin:e,path:`/auth/callback`,nonce:l}}}if(o&&a&&s(a)){let t=null;try{let e=new URL(o);(e.hostname===`localhost`||e.hostname===`127.0.0.1`)&&(t=parseInt(e.port||`5710`,10))}catch{t=null}if(t!==null&&!Number.isNaN(t))return{redirectUri:`${e.runtimeWorkerBaseUrl??r}/auth/callback`,state:{source:`local`,port:t,path:`/auth/callback`,nonce:l}}}return{redirectUri:`${e.runtimeWorkerBaseUrl??i??``}/auth/callback`,state:{port:parseInt(new URL(a??i??`http://localhost:5710`).port||`5710`,10),path:`/auth/callback`,nonce:l}}}async function S(){if(y)return y;if(C){try{let e=await fetch(`${f()}/api/runtime-config`);if(e.ok){let t=await e.json();if(t.oauth?.github)return y=t.oauth.github,y}}catch{}return v.clientId}try{let e=await fetch(`/api/runtime-config`);if(e.ok){let t=await e.json();if(t.oauth?.github)return y=t.oauth.github,t.trayWorkerBaseUrl&&(b=t.trayWorkerBaseUrl),y;if(t.trayWorkerBaseUrl){b=t.trayWorkerBaseUrl;let e=await fetch(`${t.trayWorkerBaseUrl}/api/runtime-config`);if(e.ok){let t=await e.json();if(t.oauth?.github)return y=t.oauth.github,y}}}}catch{}return v.clientId}const C=typeof globalThis<`u`&&typeof globalThis.chrome?.runtime?.id==`string`;function w(){return n().find(e=>e.providerId===`github`)}function T(e){try{return new URL(e).searchParams.get(`code`)}catch{return null}}async function E(e){try{let t=await fetch(`https://api.github.com/user`,{headers:{Authorization:`Bearer ${e}`,Accept:`application/vnd.github+json`}});if(t.ok){let e=await t.json();return{name:e.name||e.login,avatar:e.avatar_url,login:e.login,id:e.id}}}catch(e){console.warn(`[github] Failed to fetch user profile:`,e instanceof Error?e.message:String(e))}return{}}function D(e,t){return`${e}+${t}@users.noreply.github.com`}async function O(e){try{let{VirtualFS:t}=await import(`./fs-tsCmhLpU.js`).then(e=>e.t);await(await t.create({dbName:o})).writeFile(`/workspace/.git/github-token`,e),typeof window<`u`&&window.dispatchEvent(new CustomEvent(`github-token-changed`))}catch(e){console.warn(`[github] Failed to write git token:`,e instanceof Error?e.message:String(e))}}async function k(){try{let{VirtualFS:e}=await import(`./fs-tsCmhLpU.js`).then(e=>e.t);await(await e.create({dbName:o})).rm(`/workspace/.git/github-token`),typeof window<`u`&&window.dispatchEvent(new CustomEvent(`github-token-changed`))}catch{}}async function A(e){if(!(!e.login||e.id===void 0))try{let{VirtualFS:t}=await import(`./fs-tsCmhLpU.js`).then(e=>e.t),{readGlobalGitConfigValue:n,writeGlobalGitConfigValue:r}=await import(`./git-config-DA8M5e8O.js`).then(e=>e.n),i=await t.create({dbName:o}),a=e.name||e.login,s=D(e.id,e.login);!await n(i,`user.name`)&&a&&await r(i,`user.name`,a),await n(i,`user.email`)||await r(i,`user.email`,s)}catch(e){console.warn(`[github] Failed to seed git identity:`,e instanceof Error?e.message:String(e))}}const j=c();async function M(){try{let n=w();if(!n?.refreshToken)return null;let r=await g({provider:`github`,refreshToken:n.refreshToken});await e({providerId:`github`,accessToken:r.access_token,refreshToken:r.refresh_token,tokenExpiresAt:r.expires_in?Date.now()+r.expires_in*1e3:void 0,userName:n.userName,userAvatar:n.userAvatar,scopes:r.scope??n.scopes});let i=t(`github`)?.maskedValue;return i?await O(i):await k(),r.access_token}catch(e){return console.warn(`[github] Silent renewal failed:`,e instanceof Error?e.message:String(e)),null}}async function N(){let e=w();if(!e?.accessToken)throw Error(`Not logged in to GitHub — please log in first`);if((e.tokenExpiresAt??1/0)-Date.now()>6e4)return e.accessToken;let t=await j.run(()=>M());if(t)return t;let n=w();if((n?.tokenExpiresAt??1/0)-Date.now()>0&&n?.accessToken)return n.accessToken;throw Error(`GitHub session expired — please log in again`)}const P={id:`github`,name:`GitHub`,description:"Sign in with GitHub for git authentication (push/pull/clone) and the `oauth-token github` shell command. Does not expose LLM models — use the GitHub Copilot provider for those.",requiresApiKey:!1,requiresBaseUrl:!1,isOAuth:!0,oauthTokenDomains:[`github.com`,`*.github.com`,`api.github.com`,`raw.githubusercontent.com`],getModelIds:()=>[],onOAuthLogin:async(n,i,a)=>{let o=await S();if(!o)throw Error(`GitHub OAuth not configured — no client ID available`);let s=a?.scopes??v.scopes,c=C?null:await l(),d=!C&&await u(),p=crypto.randomUUID(),m=C?chrome.runtime.id:``,{redirectUri:g,state:_}=x({isExtension:C,isConnectMode:!!globalThis.__slicc_connect_mode,workerBaseUrl:f(),runtimeWorkerBaseUrl:b,pageOrigin:c?.origin??null,pageHref:c?.href??null,bridgeApiBaseUrl:r(),delegated:d,extensionId:m,nonce:p}),y=btoa(JSON.stringify(_)),w=p,D=new URLSearchParams({client_id:o,scope:s,redirect_uri:g});y&&D.set(`state`,y);let j=await n(`https://github.com/login/oauth/authorize?${D}`);if(!j)return;if(w)try{if(new URL(j).searchParams.get(`nonce`)!==w){console.error(`[github] OAuth nonce mismatch — possible CSRF`);return}}catch(e){console.warn(`[github] Nonce check skipped (URL parse failed):`,e instanceof Error?e.message:String(e))}let M=T(j);if(!M){console.error(`[github] Could not extract authorization code from redirect URL`);return}let N=await h({provider:`github`,code:M,redirectUri:g}),P=await E(N.access_token);await e({providerId:`github`,accessToken:N.access_token,refreshToken:N.refresh_token,tokenExpiresAt:N.expires_in?Date.now()+N.expires_in*1e3:void 0,userName:P.name,userAvatar:P.avatar,scopes:N.scope});let F=t(`github`)?.maskedValue;F?await O(F):await k(),await A(P),i()},onSilentRenew:M,getValidAccessToken:N,onOAuthLogout:async()=>{let t=w();t?.accessToken&&await _({provider:`github`,accessToken:t.accessToken}).catch(e=>console.warn(`[github] Token revocation failed:`,e instanceof Error?e.message:String(e))),await k(),await e({providerId:`github`,accessToken:``})},getOAuthLogoutUrl:e=>`https://github.com/logout`};export{D as buildNoreplyEmail,P as config,T as extractCodeFromUrl,N as getValidAccessToken,x as resolveGithubOAuthRedirect,A as syncGitIdentityFromGitHub};
1
+ import"./proxied-fetch-Co-pb0x0.js";import{H as e,S as t,d as n}from"./account-store-ktNi3pcb.js";import{r}from"./api-endpoint-C00IT5T9.js";import{r as i,t as a}from"./tray-runtime-config-CVoPQrT2.js";import{t as o}from"./global-db-DJXlpNui.js";import{r as s,t as c}from"./silent-renew-backoff-C_Iv54ZG.js";import{getOAuthPageOrigin as l,resolveOAuthDelegation as u}from"./oauth-service-CTntqv0R.js";import"./provider-settings-QhXeD8p1.js";var d={clientId:``,scopes:`repo,read:user,user:email`};function f(){try{let e=localStorage.getItem(i);if(e)return e.replace(/\/$/,``)}catch{}return a}function p(e){return{access_token:e.access_token,token_type:e.token_type,scope:e.scope,refresh_token:e.refresh_token,expires_in:e.expires_in}}async function m(e){let t;try{t=await e.json()}catch{throw Error(`Token exchange failed (HTTP ${e.status}): non-JSON response`)}if(!e.ok&&e.status!==200){let n=t.error_description??t.error??`Token exchange failed (HTTP ${e.status})`;throw Error(n)}if(t.error){let e=t.error_description??t.error;throw Error(e)}return p(t)}async function h(e){let t=`${f()}/oauth/token`;return m(await fetch(t,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:e.provider,code:e.code,redirect_uri:e.redirectUri})}))}async function g(e){let t=`${f()}/oauth/token`;return m(await fetch(t,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:e.provider,refresh_token:e.refreshToken})}))}async function _(e){let t=`${f()}/oauth/revoke`,n=await fetch(t,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:e.provider,access_token:e.accessToken})});if(!(n.status===204||n.ok)){if(n.status===400)try{if((await n.json()).error===`unsupported`)return}catch{}throw Error(`Token revocation failed (HTTP ${n.status})`)}}const v=Object.assign({"/packages/webapp/providers/github-config.json":d})[`/packages/webapp/providers/github-config.json`]??{clientId:``,scopes:`repo,read:user,user:email`};let y=null,b=null;function x(e){let{isExtension:t,isConnectMode:n,workerBaseUrl:r,pageOrigin:i,pageHref:a,bridgeApiBaseUrl:o,extensionId:c,nonce:l}=e;if(t)return{redirectUri:`${r}/auth/callback`,state:{source:`extension`,extensionId:c,path:`/github`,nonce:l}};if(e.delegated)return{redirectUri:`${e.runtimeWorkerBaseUrl??r}/auth/callback`,state:{source:`opener`,path:`/auth/callback`,nonce:l}};if(n){let e=i??``;if(/^https?:\/\/(localhost|127\.0\.0\.1):\d+$/.test(e)){let t=parseInt(new URL(a??e).port||`8790`,10);return{redirectUri:`${r}/auth/callback`,state:{source:`local`,port:t,path:`/auth/callback`,nonce:l}}}return{redirectUri:`${r}/auth/callback`,state:{source:`remote`,origin:e,path:`/auth/callback`,nonce:l}}}if(o&&a&&s(a)){let t=null;try{let e=new URL(o);(e.hostname===`localhost`||e.hostname===`127.0.0.1`)&&(t=parseInt(e.port||`5710`,10))}catch{t=null}if(t!==null&&!Number.isNaN(t))return{redirectUri:`${e.runtimeWorkerBaseUrl??r}/auth/callback`,state:{source:`local`,port:t,path:`/auth/callback`,nonce:l}}}return{redirectUri:`${e.runtimeWorkerBaseUrl??i??``}/auth/callback`,state:{port:parseInt(new URL(a??i??`http://localhost:5710`).port||`5710`,10),path:`/auth/callback`,nonce:l}}}async function S(){if(y)return y;if(C){try{let e=await fetch(`${f()}/api/runtime-config`);if(e.ok){let t=await e.json();if(t.oauth?.github)return y=t.oauth.github,y}}catch{}return v.clientId}try{let e=await fetch(`/api/runtime-config`);if(e.ok){let t=await e.json();if(t.oauth?.github)return y=t.oauth.github,t.trayWorkerBaseUrl&&(b=t.trayWorkerBaseUrl),y;if(t.trayWorkerBaseUrl){b=t.trayWorkerBaseUrl;let e=await fetch(`${t.trayWorkerBaseUrl}/api/runtime-config`);if(e.ok){let t=await e.json();if(t.oauth?.github)return y=t.oauth.github,y}}}}catch{}return v.clientId}const C=typeof globalThis<`u`&&typeof globalThis.chrome?.runtime?.id==`string`;function w(){return n().find(e=>e.providerId===`github`)}function T(e){try{return new URL(e).searchParams.get(`code`)}catch{return null}}async function E(e){try{let t=await fetch(`https://api.github.com/user`,{headers:{Authorization:`Bearer ${e}`,Accept:`application/vnd.github+json`}});if(t.ok){let e=await t.json();return{name:e.name||e.login,avatar:e.avatar_url,login:e.login,id:e.id}}}catch(e){console.warn(`[github] Failed to fetch user profile:`,e instanceof Error?e.message:String(e))}return{}}function D(e,t){return`${e}+${t}@users.noreply.github.com`}async function O(e){try{let{VirtualFS:t}=await import(`./fs-DUneCuZW.js`).then(e=>e.t);await(await t.create({dbName:o})).writeFile(`/workspace/.git/github-token`,e),typeof window<`u`&&window.dispatchEvent(new CustomEvent(`github-token-changed`))}catch(e){console.warn(`[github] Failed to write git token:`,e instanceof Error?e.message:String(e))}}async function k(){try{let{VirtualFS:e}=await import(`./fs-DUneCuZW.js`).then(e=>e.t);await(await e.create({dbName:o})).rm(`/workspace/.git/github-token`),typeof window<`u`&&window.dispatchEvent(new CustomEvent(`github-token-changed`))}catch{}}async function A(e){if(!(!e.login||e.id===void 0))try{let{VirtualFS:t}=await import(`./fs-DUneCuZW.js`).then(e=>e.t),{readGlobalGitConfigValue:n,writeGlobalGitConfigValue:r}=await import(`./git-config-Bdgu8kD2.js`).then(e=>e.n),i=await t.create({dbName:o}),a=e.name||e.login,s=D(e.id,e.login);!await n(i,`user.name`)&&a&&await r(i,`user.name`,a),await n(i,`user.email`)||await r(i,`user.email`,s)}catch(e){console.warn(`[github] Failed to seed git identity:`,e instanceof Error?e.message:String(e))}}const j=c();async function M(){try{let n=w();if(!n?.refreshToken)return null;let r=await g({provider:`github`,refreshToken:n.refreshToken});await e({providerId:`github`,accessToken:r.access_token,refreshToken:r.refresh_token,tokenExpiresAt:r.expires_in?Date.now()+r.expires_in*1e3:void 0,userName:n.userName,userAvatar:n.userAvatar,scopes:r.scope??n.scopes});let i=t(`github`)?.maskedValue;return i?await O(i):await k(),r.access_token}catch(e){return console.warn(`[github] Silent renewal failed:`,e instanceof Error?e.message:String(e)),null}}async function N(){let e=w();if(!e?.accessToken)throw Error(`Not logged in to GitHub — please log in first`);if((e.tokenExpiresAt??1/0)-Date.now()>6e4)return e.accessToken;let t=await j.run(()=>M());if(t)return t;let n=w();if((n?.tokenExpiresAt??1/0)-Date.now()>0&&n?.accessToken)return n.accessToken;throw Error(`GitHub session expired — please log in again`)}const P={id:`github`,name:`GitHub`,description:"Sign in with GitHub for git authentication (push/pull/clone) and the `oauth-token github` shell command. Does not expose LLM models — use the GitHub Copilot provider for those.",requiresApiKey:!1,requiresBaseUrl:!1,isOAuth:!0,oauthTokenDomains:[`github.com`,`*.github.com`,`api.github.com`,`raw.githubusercontent.com`],getModelIds:()=>[],onOAuthLogin:async(n,i,a)=>{let o=await S();if(!o)throw Error(`GitHub OAuth not configured — no client ID available`);let s=a?.scopes??v.scopes,c=C?null:await l(),d=!C&&await u(),p=crypto.randomUUID(),m=C?chrome.runtime.id:``,{redirectUri:g,state:_}=x({isExtension:C,isConnectMode:!!globalThis.__slicc_connect_mode,workerBaseUrl:f(),runtimeWorkerBaseUrl:b,pageOrigin:c?.origin??null,pageHref:c?.href??null,bridgeApiBaseUrl:r(),delegated:d,extensionId:m,nonce:p}),y=btoa(JSON.stringify(_)),w=p,D=new URLSearchParams({client_id:o,scope:s,redirect_uri:g});y&&D.set(`state`,y);let j=await n(`https://github.com/login/oauth/authorize?${D}`);if(!j)return;if(w)try{if(new URL(j).searchParams.get(`nonce`)!==w){console.error(`[github] OAuth nonce mismatch — possible CSRF`);return}}catch(e){console.warn(`[github] Nonce check skipped (URL parse failed):`,e instanceof Error?e.message:String(e))}let M=T(j);if(!M){console.error(`[github] Could not extract authorization code from redirect URL`);return}let N=await h({provider:`github`,code:M,redirectUri:g}),P=await E(N.access_token);await e({providerId:`github`,accessToken:N.access_token,refreshToken:N.refresh_token,tokenExpiresAt:N.expires_in?Date.now()+N.expires_in*1e3:void 0,userName:P.name,userAvatar:P.avatar,scopes:N.scope});let F=t(`github`)?.maskedValue;F?await O(F):await k(),await A(P),i()},onSilentRenew:M,getValidAccessToken:N,onOAuthLogout:async()=>{let t=w();t?.accessToken&&await _({provider:`github`,accessToken:t.accessToken}).catch(e=>console.warn(`[github] Token revocation failed:`,e instanceof Error?e.message:String(e))),await k(),await e({providerId:`github`,accessToken:``})},getOAuthLogoutUrl:e=>`https://github.com/logout`};export{D as buildNoreplyEmail,P as config,T as extractCodeFromUrl,N as getValidAccessToken,x as resolveGithubOAuthRedirect,A as syncGitIdentityFromGitHub};