sliccy 6.110.12 → 6.110.13

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 (92) hide show
  1. package/dist/ui/.vite/manifest.json +144 -144
  2. package/dist/ui/assets/{account-store-JfqGLwpx.js → account-store-B5g-mrn8.js} +1 -1
  3. package/dist/ui/assets/{account-store-B4f1TkzQ.js → account-store-mFC76tgv.js} +1 -1
  4. package/dist/ui/assets/{adobe-BG0h31bK.js → adobe-BCBLeEqn.js} +1 -1
  5. package/dist/ui/assets/{adobe-Bz4TU9A0.js → adobe-DN_cMZlf.js} +1 -1
  6. package/dist/ui/assets/{agent-bridge-CuRwAl_F.js → agent-bridge-DJ2Gh9VA.js} +1 -1
  7. package/dist/ui/assets/{agent-panels-C-yTo1Cf.js → agent-panels-SjLPDAhx.js} +1 -1
  8. package/dist/ui/assets/{apply-layout-Cwjdhbay.js → apply-layout-DegnOb_8.js} +1 -1
  9. package/dist/ui/assets/{apps-CBx42rH9.js → apps-CeTlBebf.js} +1 -1
  10. package/dist/ui/assets/{azure-openai-CvYv7foL.js → azure-openai-CbsjCnKF.js} +1 -1
  11. package/dist/ui/assets/{azure-openai-IHA9P8r4.js → azure-openai-Co7qiHsD.js} +1 -1
  12. package/dist/ui/assets/{cerebras-zwsRFQcw.js → cerebras-CHy7N-5g.js} +1 -1
  13. package/dist/ui/assets/{cerebras-C-G9dGIN.js → cerebras-CnIp8GQk.js} +1 -1
  14. package/dist/ui/assets/{connect-surface-DfgyQ6M7.js → connect-surface-Hu5fOtLV.js} +1 -1
  15. package/dist/ui/assets/{core-BVWxlTTk.js → core-CGasZgKz.js} +3 -3
  16. package/dist/ui/assets/{directed-approval-DeUsUYBD.js → directed-approval-CRALKPfL.js} +1 -1
  17. package/dist/ui/assets/{fs-DBHB4fgS.js → fs-BhUjB1cK.js} +1 -1
  18. package/dist/ui/assets/{fs-DO7Pn7WW.js → fs-CSRyHRw6.js} +2 -2
  19. package/dist/ui/assets/{github-DthV99LD.js → github-CWYdKkWk.js} +1 -1
  20. package/dist/ui/assets/{github-CXGHIZVB.js → github-CaubYdfd.js} +2 -2
  21. package/dist/ui/assets/{github-copilot-Dsa9eVh5.js → github-copilot-BAWQ9UfS.js} +1 -1
  22. package/dist/ui/assets/{github-copilot-BdjkPAt8.js → github-copilot-Ygk85cjt.js} +1 -1
  23. package/dist/ui/assets/{github-install-Co8RGcCz.js → github-install-C_CLyb3u.js} +1 -1
  24. package/dist/ui/assets/{github-zip-Cp0IybNw.js → github-zip-CKXdHtbK.js} +1 -1
  25. package/dist/ui/assets/{guest-tool-gate-MzqLI9n7.js → guest-tool-gate-DTA3P3jk.js} +1 -1
  26. package/dist/ui/assets/icons-BJsliYCh.js +1 -0
  27. package/dist/ui/assets/{js-realm-worker-C11HEtiw.js → js-realm-worker-B8Mm9E9s.js} +1 -1
  28. package/dist/ui/assets/{kernel-worker-BP7AbN0g.js → kernel-worker-BBWsqNvT.js} +28 -28
  29. package/dist/ui/assets/{local-llm-CWEg0rcm.js → local-llm-CBszF_hu.js} +1 -1
  30. package/dist/ui/assets/{local-llm-MS9lnpet.js → local-llm-DiTdUVxp.js} +1 -1
  31. package/dist/ui/assets/{main-DDf8pkef.js → main-DzWg1TK_.js} +3 -3
  32. package/dist/ui/assets/{mount-BVsAhg7N.js → mount-4B-1d5oh.js} +2 -2
  33. package/dist/ui/assets/{mount-DeYTNAtM.js → mount-CY0WMJLG.js} +1 -1
  34. package/dist/ui/assets/{mount-recovery-C-JrPN0s.js → mount-recovery-DBMLMXSG.js} +1 -1
  35. package/dist/ui/assets/{new-session-B3XnJuqv.js → new-session-jeNmXk7P.js} +2 -2
  36. package/dist/ui/assets/{oauth-bootstrap-Bk9dDOws.js → oauth-bootstrap-8ihF-R_z.js} +2 -2
  37. package/dist/ui/assets/{openai-codex-Cttg7uJd.js → openai-codex-BzNYKmfn.js} +1 -1
  38. package/dist/ui/assets/{openai-codex-rUO7vr1U.js → openai-codex-lPthoW8r.js} +1 -1
  39. package/dist/ui/assets/{openrouter-Ciu6vAC3.js → openrouter-BknXSW5c.js} +1 -1
  40. package/dist/ui/assets/{openrouter-H9gP72-I.js → openrouter-mwt9jwZa.js} +1 -1
  41. package/dist/ui/assets/{openrouter-oauth-D5iIE6cP.js → openrouter-oauth-B65Wk580.js} +1 -1
  42. package/dist/ui/assets/{openrouter-oauth-CH1L0i5l.js → openrouter-oauth-BXgZzA3Q.js} +1 -1
  43. package/dist/ui/assets/{panel-rpc-handlers-Ba_8QBpT.js → panel-rpc-handlers-NEPkzdP3.js} +2 -2
  44. package/dist/ui/assets/{panelize-shell-CRWRRDY-.js → panelize-shell-C8nHDKSj.js} +1 -1
  45. package/dist/ui/assets/{provider-NdjBqWJ5.js → provider-BD2eMVRi.js} +2 -2
  46. package/dist/ui/assets/{provider-DZdn3I7g.js → provider-l9BFMaHE.js} +1 -1
  47. package/dist/ui/assets/{provider-settings-VeKZEiaM.js → provider-settings-8XzaJ7Uj.js} +1 -1
  48. package/dist/ui/assets/{provider-settings-Bzx7Hz1h.js → provider-settings-CsTcfP8K.js} +1 -1
  49. package/dist/ui/assets/provider-store-access-DO9H0PId.js +1 -0
  50. package/dist/ui/assets/{provider-store-access-BmqtHWK-.js → provider-store-access-DdMRpexA.js} +2 -2
  51. package/dist/ui/assets/{providers-BPYoyMTa.js → providers-Bybk43BU.js} +1 -1
  52. package/dist/ui/assets/{providers-BTiNdb0r.js → providers-CGzsfbUR.js} +2 -2
  53. package/dist/ui/assets/{quick-llm-D-0thqIh.js → quick-llm-BjHgHVhH.js} +1 -1
  54. package/dist/ui/assets/{recovery-screen-m5rTUbFa.js → recovery-screen-J3JWTpgF.js} +1 -1
  55. package/dist/ui/assets/{redirect-uri-DC3PdAtX.js → redirect-uri-UNLwkF71.js} +1 -1
  56. package/dist/ui/assets/{run-BQU0xqGp.js → run-BvngdJSx.js} +1 -1
  57. package/dist/ui/assets/{session-freezer-DrAZJ5E8.js → session-freezer-Dp8tR_wX.js} +3 -3
  58. package/dist/ui/assets/{setup-feature-flags-remote-CzuJ2Tg_.js → setup-feature-flags-remote-4vmTEIMx.js} +1 -1
  59. package/dist/ui/assets/{setup-standalone-prelude-Dx27VBt_.js → setup-standalone-prelude-4rQCXLGL.js} +1 -1
  60. package/dist/ui/assets/{setup-sudo-CzZlm0VE.js → setup-sudo-D-pI9Wj_.js} +2 -2
  61. package/dist/ui/assets/{skills-DvboiQ8x.js → skills-DFSM0Mzw.js} +1 -1
  62. package/dist/ui/assets/slicc-version-DamSgLEW.js +1 -0
  63. package/dist/ui/assets/{state-CinEep0w.js → state-Bxe7U2uR.js} +1 -1
  64. package/dist/ui/assets/{store-Bd-S5pB-.js → store-BwjB3mN4.js} +1 -1
  65. package/dist/ui/assets/{store-Dja6bYOS.js → store-DgTQh3uY.js} +1 -1
  66. package/dist/ui/assets/{sudo-DaziFK_O.js → sudo-B1uN4VjQ.js} +1 -1
  67. package/dist/ui/assets/{sync-dialog-ACgl0n-p.js → sync-dialog-Dc1-z8ys.js} +1 -1
  68. package/dist/ui/assets/{upgrade-detection-d83JrIre.js → upgrade-detection-Dm6JI5c7.js} +1 -1
  69. package/dist/ui/assets/{wc-attach-Ddg-AFpA.js → wc-attach-2iyRKvmt.js} +2 -2
  70. package/dist/ui/assets/{wc-extension-DaLJ8MK5.js → wc-extension-DvH_frrB.js} +2 -2
  71. package/dist/ui/assets/{wc-float-label-DFKw-L8x.js → wc-float-label-CPaEzWWM.js} +1 -1
  72. package/dist/ui/assets/{wc-floatbar-online-ClCS1sKy.js → wc-floatbar-online-GqMjLIby.js} +1 -1
  73. package/dist/ui/assets/{wc-follower-CcRLAOwf.js → wc-follower-3cX8fmJu.js} +3 -3
  74. package/dist/ui/assets/{wc-follower-oauth-DN3SywTT.js → wc-follower-oauth-B_i4VloV.js} +1 -1
  75. package/dist/ui/assets/{wc-live-DWITCUer.js → wc-live-M5a3sBeq.js} +4 -4
  76. package/dist/ui/assets/{wc-nav-DCvL8tCQ.js → wc-nav-CHWKuXtU.js} +2 -2
  77. package/dist/ui/assets/{wc-onboarding-CAB4TQKL.js → wc-onboarding-BKIUSDvB.js} +2 -2
  78. package/dist/ui/assets/{wc-placeholder-QhAINQdh.js → wc-placeholder-bZ8QbN6-.js} +2 -2
  79. package/dist/ui/assets/{wc-settings-C9KYDbqg.js → wc-settings-CBxN34VQ.js} +2 -2
  80. package/dist/ui/assets/{wc-shell-BQha7IeK.js → wc-shell-Cdl88M0O.js} +3 -3
  81. package/dist/ui/assets/{wc-shortcut-config-B002nt0y.js → wc-shortcut-config-kW-FDTbf.js} +1 -1
  82. package/dist/ui/assets/{wc-sprinkles-D50_-OOl.js → wc-sprinkles-CZHZhfaV.js} +2 -2
  83. package/dist/ui/assets/{wc-tray-Bj2fhjCA.js → wc-tray-XaKABUZZ.js} +4 -4
  84. package/dist/ui/assets/{xai-grok-bqBopgqi.js → xai-grok-D0_yKThq.js} +1 -1
  85. package/dist/ui/assets/{xai-grok-B__xNVnH.js → xai-grok-ktVvnBiV.js} +1 -1
  86. package/dist/ui/index.html +6 -6
  87. package/dist/ui/lucide-icons.js +180 -179
  88. package/dist/ui/packages/webapp/index.html +6 -6
  89. package/package.json +2 -2
  90. package/dist/ui/assets/icons-ZLR7gmJ4.js +0 -1
  91. package/dist/ui/assets/provider-store-access-Dhsrpl15.js +0 -1
  92. package/dist/ui/assets/slicc-version-DWDKasUe.js +0 -1
@@ -45,7 +45,7 @@ Do NOT continue the conversation. Do NOT answer questions inside the conversatio
45
45
  <conversation>
46
46
  ${e}
47
47
  </conversation>`}async function im(e,t,n,r,i,a,o){let s=await l(e,{systemPrompt:n,messages:[{role:`user`,content:[{type:`text`,text:r}],timestamp:Date.now()}]},{maxTokens:i,apiKey:t,headers:a,signal:o});if(s.stopReason===`error`)throw Error(`Compaction call failed: ${s.errorMessage||`Unknown error`}`);return s.content.filter(e=>e.type===`text`).map(e=>e.text).join(`
48
- `).trim()}function am(e){if(typeof e==`string`)return e.length;if(!Array.isArray(e))return 0;let t=0;for(let n of e){let e=n;if(e.type===`text`&&e.text)t+=e.text.length;else if(e.type===`thinking`&&e.thinking)t+=e.thinking.length;else if(e.type===`toolCall`&&e.arguments!==void 0)try{t+=JSON.stringify(e.arguments).length}catch{}else e.type===`image`&&e.source?.data&&(t+=e.source.data.length)}return t}function om(e,t){let n=Math.max(1,Math.round(e/1024));return`[${t===`assistant`?`Assistant message elided`:`Tool result elided`}: ${n} KB, exceeds half the context window. Re-run with smaller arguments — e.g. open --view --size low.]`}function sm(e){let t=e.role,n=e.content,r=am(n);if(t===`toolResult`)return{...e,content:[{type:`text`,text:om(r,t)}]};let i=(Array.isArray(n)?n.filter(e=>e.type===`toolCall`):[]).map(e=>{let t=0;if(e.arguments!==void 0)try{t=JSON.stringify(e.arguments).length}catch{}return{type:e.type,id:e.id,name:e.name,arguments:{elided:!0,originalBytes:t}}});return{...e,content:[{type:`text`,text:om(r,t)},...i]}}function cm(e,t,n){let r=(t-n)/2,i=0,a=0;return{messages:e.map(e=>{if(Qp(e)<=r)return e;let t=e.role;if(t!==`toolResult`&&t!==`assistant`)return e;let n=e,o=am(n.content);return t===`toolResult`?(i++,a+=o,sm(e)):(Array.isArray(n.content)?n.content:[]).filter(e=>e.type===`toolCall`).length===0?e:(i++,a+=o,sm(e))}),elidedCount:i,elidedBytes:a}}function lm(e,t,n){let r=0,i=0,a=cm(e.map(e=>{let t=mm(e);return t!==e&&(r++,i+=am(e.content)-am(t.content)),t}),t,n);return{messages:a.messages,elidedCount:r+a.elidedCount,elidedBytes:i+a.elidedBytes}}function um(e){let t=0;for(let n of e)t+=Qp(n);return t}function dm(e,t){return e.length!==t.length||e.some((e,n)=>e!==t[n])}function fm(e,t){try{e.onCompactionStateChange?.(t)}catch(e){$.warn(`onCompactionStateChange listener threw`,{error:e instanceof Error?e.message:String(e)})}}function pm(e,t,n,r,i,a){let o=cm(e,n,r),s=o.messages,c=o.elidedCount,l=o.elidedBytes,u=c>0?um(s):t,d=u>n*i;if(d){let e=lm(s,n,r);s=e.messages,c+=e.elidedCount,l+=e.elidedBytes}if(!d&&c===0)return{messages:e,isHopeless:!1,earlyReturn:null};$.warn(`Compaction oversized-message elision`,{totalTokens:t,postSizeTokens:u,contextWindow:n,isHopeless:d,elidedCount:c,elidedBytes:l});let f=Xp(um(s),n,a)?null:gm([],s,n,a);return{messages:s,isHopeless:d,earlyReturn:f}}function mm(e){let t=e.content;if(!Array.isArray(t))return e;let n=!1,r=t.map(e=>{let t=e;return t.type===`image`?(n=!0,{type:`text`,text:`[image elided during compaction: ~${Math.max(1,Math.round((t.source?.data??t.data??``).length/1024))} KB. Re-attach or re-read the image if it is still needed.]`}):e});return n?{...e,content:r}:e}function hm(e){for(let t=e.length-1;t>=0;t--)if($p(e[t],`user`))return t;return-1}function gm(e,t,n,r){let i=hm(t),a=t.map((e,t)=>i!==-1&&t>=i?e:mm(e));if(Xp(um([...e,...a]),n,r))for(let t=0;t<a.length;t++){let i=mm(a[t]);if(i!==a[t]&&(a=[...a.slice(0,t),i,...a.slice(t+1)],!Xp(um([...e,...a]),n,r)))break}return a}function _m(e,t){let n=0,r=e.length;for(let i=e.length-1;i>=0;i--){let a=Qp(e[i]);if(n+a>t&&r<e.length)break;n+=a,r=i}for(;r>0&&$p(e[r],`toolResult`);)r--;return r<=0||r>=e.length?($.warn(`Cannot find valid cut point for compaction`),null):{messagesToSummarize:e.slice(0,r),messagesToKeep:em(e.slice(r))}}async function vm(e,t,n,r){if(!(!e.onMemoryUpdates||e.shouldExtractMemories?.()===!1))try{fm(e,`extracting-memory`);let i=await im(e.model,t,n,`From the conversation above, extract durable memories worth persisting to a global memory file shared across future sessions.
48
+ `).trim()}function am(e){if(typeof e==`string`)return e.length;if(!Array.isArray(e))return 0;let t=0;for(let n of e){let e=n;if(e.type===`text`&&e.text)t+=e.text.length;else if(e.type===`thinking`&&e.thinking)t+=e.thinking.length;else if(e.type===`toolCall`&&e.arguments!==void 0)try{t+=JSON.stringify(e.arguments).length}catch{}else e.type===`image`&&e.source?.data&&(t+=e.source.data.length)}return t}function om(e,t){let n=Math.max(1,Math.round(e/1024));return`[${t===`assistant`?`Assistant message elided`:`Tool result elided`}: ${n} KB, exceeds half the context window. Re-run with smaller arguments — e.g. open --view --size low.]`}function sm(e){let t=e.role,n=e.content,r=am(n);if(t===`toolResult`)return{...e,content:[{type:`text`,text:om(r,t)}]};let i=(Array.isArray(n)?n.filter(e=>e.type===`toolCall`):[]).map(e=>{let t=0;if(e.arguments!==void 0)try{t=JSON.stringify(e.arguments).length}catch{}return{type:e.type,id:e.id,name:e.name,arguments:{elided:!0,originalBytes:t}}});return{...e,content:[{type:`text`,text:om(r,t)},...i]}}function cm(e,t,n){let r=(t-n)/2,i=0,a=0;return{messages:e.map(e=>{if(dm(e)<=r)return e;let t=e.role;if(t!==`toolResult`&&t!==`assistant`)return e;let n=e,o=am(n.content);return t===`toolResult`?(i++,a+=o,sm(e)):(Array.isArray(n.content)?n.content:[]).filter(e=>e.type===`toolCall`).length===0?e:(i++,a+=o,sm(e))}),elidedCount:i,elidedBytes:a}}function lm(e,t,n){let r=0,i=0,a=cm(e.map(e=>{let t=ym(e);return t!==e&&(r++,i+=am(e.content)-am(t.content)),t}),t,n);return{messages:a.messages,elidedCount:r+a.elidedCount,elidedBytes:i+a.elidedBytes}}function um(e){if(!$p(e,`assistant`))return 0;let t=e.content;if(!Array.isArray(t))return 0;let n=0;for(let e of t){let t=e;t.type===`thinking`&&typeof t.thinkingSignature==`string`&&(n+=t.thinkingSignature.length)}return n}function dm(e){return Qp(e)+Math.ceil(um(e)/4)}function fm(e){let t=0;for(let n of e)t+=dm(n);return t}function pm(e){for(let t=e.length-1;t>=0;t--){if(!$p(e[t],`assistant`))continue;let n=e[t];if(n.stopReason===`aborted`||n.stopReason===`error`)continue;let r=n.usage;if(r&&mm(r)>0)return t}return-1}function mm(e){return e.totalTokens||e.input+e.output+e.cacheRead+e.cacheWrite}function hm(e){let t=fm(e),n=pm(e);if(n===-1)return t;let r=mm(e[n].usage);for(let t=n+1;t<e.length;t++)r+=dm(e[t]);return Math.max(t,r)}function gm(e,t){return e.length!==t.length||e.some((e,n)=>e!==t[n])}function _m(e,t){try{e.onCompactionStateChange?.(t)}catch(e){$.warn(`onCompactionStateChange listener threw`,{error:e instanceof Error?e.message:String(e)})}}function vm(e,t,n,r,i,a){let o=cm(e,n,r),s=o.messages,c=o.elidedCount,l=o.elidedBytes,u=c>0?fm(s):t,d=u>n*i;if(d){let e=lm(s,n,r);s=e.messages,c+=e.elidedCount,l+=e.elidedBytes}if(!d&&c===0)return{messages:e,isHopeless:!1,earlyReturn:null};$.warn(`Compaction oversized-message elision`,{totalTokens:t,postSizeTokens:u,contextWindow:n,isHopeless:d,elidedCount:c,elidedBytes:l});let f=Xp(fm(s),n,a)?null:xm([],s,n,a);return{messages:s,isHopeless:d,earlyReturn:f}}function ym(e){let t=e.content;if(!Array.isArray(t))return e;let n=!1,r=t.map(e=>{let t=e;return t.type===`image`?(n=!0,{type:`text`,text:`[image elided during compaction: ~${Math.max(1,Math.round((t.source?.data??t.data??``).length/1024))} KB. Re-attach or re-read the image if it is still needed.]`}):e});return n?{...e,content:r}:e}function bm(e){for(let t=e.length-1;t>=0;t--)if($p(e[t],`user`))return t;return-1}function xm(e,t,n,r){let i=bm(t),a=t.map((e,t)=>i!==-1&&t>=i?e:ym(e));if(Xp(fm([...e,...a]),n,r))for(let t=0;t<a.length;t++){let i=ym(a[t]);if(i!==a[t]&&(a=[...a.slice(0,t),i,...a.slice(t+1)],!Xp(fm([...e,...a]),n,r)))break}return a}function Sm(e,t){let n=0,r=e.length;for(let i=e.length-1;i>=0;i--){let a=dm(e[i]);if(n+a>t&&r<e.length)break;n+=a,r=i}for(;r>0&&$p(e[r],`toolResult`);)r--;return r<=0||r>=e.length?($.warn(`Cannot find valid cut point for compaction`),null):{messagesToSummarize:e.slice(0,r),messagesToKeep:em(e.slice(r))}}async function Cm(e,t,n,r){if(!(!e.onMemoryUpdates||e.shouldExtractMemories?.()===!1))try{_m(e,`extracting-memory`);let i=await im(e.model,t,n,`From the conversation above, extract durable memories worth persisting to a global memory file shared across future sessions.
49
49
 
50
50
  Focus on:
51
51
  - User preferences, working style, opinions stated explicitly.
@@ -61,7 +61,7 @@ DO NOT include:
61
61
  If nothing in the conversation is worth persisting, return exactly the single line:
62
62
  NONE
63
63
 
64
- Otherwise, output ONLY a markdown bullet list (one bullet per memory), no headers, no preamble, no follow-up. Each bullet is one line. Be specific. Prefer one fact per bullet over multi-clause sentences.`,2048,e.headers,r);if(i?.trim()&&i.trim()!==`NONE`)try{await e.onMemoryUpdates(i.trim()),$.info(`Memory extraction applied`,{bulletsLength:i.length})}catch(e){$.warn(`onMemoryUpdates callback threw`,{error:e instanceof Error?e.message:String(e)})}else $.info(`Memory extraction returned no durable memories`)}catch(e){$.warn(`Memory extraction call failed (compaction still applied)`,{error:e instanceof Error?e.message:String(e)})}}async function ym(e,t,n,r,i,a,o,s){try{let c=cm(n,a,i).messages,l=rm(tm(c)),u=Math.floor(.8*i);fm(e,`summarizing`);let d=await im(e.model,t,l,`Produce a structured context checkpoint summary of the conversation above that another LLM can use to continue the work.
64
+ Otherwise, output ONLY a markdown bullet list (one bullet per memory), no headers, no preamble, no follow-up. Each bullet is one line. Be specific. Prefer one fact per bullet over multi-clause sentences.`,2048,e.headers,r);if(i?.trim()&&i.trim()!==`NONE`)try{await e.onMemoryUpdates(i.trim()),$.info(`Memory extraction applied`,{bulletsLength:i.length})}catch(e){$.warn(`onMemoryUpdates callback threw`,{error:e instanceof Error?e.message:String(e)})}else $.info(`Memory extraction returned no durable memories`)}catch(e){$.warn(`Memory extraction call failed (compaction still applied)`,{error:e instanceof Error?e.message:String(e)})}}async function wm(e,t,n,r,i,a,o,s){try{let c=cm(n,a,i).messages,l=rm(tm(c)),u=Math.floor(.8*i);_m(e,`summarizing`);let d=await im(e.model,t,l,`Produce a structured context checkpoint summary of the conversation above that another LLM can use to continue the work.
65
65
 
66
66
  Use this EXACT format:
67
67
 
@@ -92,4 +92,4 @@ Use this EXACT format:
92
92
  - [Any data, examples, or references needed to continue]
93
93
  - [Or "(none)" if not applicable]
94
94
 
95
- Keep each section concise. Preserve exact file paths, function names, and error messages. Output ONLY the summary, with no preamble or follow-up.`,u,e.headers,s),f={role:`user`,content:[{type:`text`,text:`<context-summary>\n${d}\n</context-summary>`}],timestamp:Date.now()};return $.info(`LLM summarization successful`,{originalMessages:o,compactedMessages:1+r.length,summaryLength:d.length}),await vm(e,t,l,s),fm(e,`idle`),[f,...r]}catch(e){return $.warn(`LLM summarization failed, falling back to naive drop`,{error:e instanceof Error?e.message:String(e)}),null}}function bm(e){let t=e.contextWindow??2e5,n=e.reserveTokens??Yp.reserveTokens,r=e.keepRecentTokens??Yp.keepRecentTokens,i=e.hopelessMultiplier??4,a={enabled:!0,reserveTokens:n,keepRecentTokens:r};return async(o,s,c)=>{if(o.length===0)return o;let l=um(o);if(!c?.force&&!Xp(l,t,a))return o;let u=pm(o,l,t,n,i,a);if(u.earlyReturn)return u.earlyReturn;let d=u.messages,f=u.isHopeless;$.info(`Context compaction triggered`,{totalTokens:l,contextWindow:t,threshold:t-n,messageCount:d.length});let p=_m(d,r);if(!p)return d;let{messagesToSummarize:m,messagesToKeep:h}=p;$.info(`Compaction cut point`,{summarizing:m.length,keeping:h.length});let g=f?void 0:e.getApiKey();if(g){let r=await ym(e,g,m,h,n,t,o.length,s);if(r){let[e,...n]=r;return[e,...gm([e],n,t,a)]}}else f||$.warn(`No API key available for LLM summarization, falling back to naive drop`);fm(e,`fallback`),fm(e,`idle`);let ee={role:`user`,content:[{type:`text`,text:`[Earlier conversation messages were compacted to save context space]`}],timestamp:Date.now()},_=gm([ee],h,t,a);return $.info(`Naive compaction applied`,{originalMessages:o.length,compactedMessages:1+_.length}),[ee,..._]}}function xm(){return a()?`extension-direct`:s()?`extension-delegate`:globalThis.__slicc_connect_mode?`connect`:`node-rest`}function Sm(){return xm()===`node-rest`}const Cm=u({portName:`secrets.crud`,panelRpcOp:`secrets-bridge`,timeoutMs:1e4,onUnavailable:`resolve-undefined`,makeError:e=>Error(e),logNamespace:`secrets-bridge`,toPortMessage:({type:e,payload:t})=>({type:e,...t}),toPanelRpcPayload:({type:e,payload:t})=>({type:e,payload:t})});function wm(e,t){return Cm({type:e,payload:t})}const Tm=n(`secret-scrub`),Em=`[tool output withheld: secret scrub unavailable]`,Dm=async e=>e;function Om(){let e=xm();return e===`extension-direct`?async e=>{if(!e)return e;try{let t=await new Promise(t=>{chrome.runtime.sendMessage({type:`secrets.scrub-tool-result`,text:e},e=>t(e??{}))});return t.error?(Tm.debug(`SW scrub-tool-result returned error`),Em):typeof t.text==`string`?t.text:Em}catch{return Tm.debug(`SW scrub-tool-result failed`),Em}}:e===`extension-delegate`?async e=>{if(!e)return e;try{let t=await wm(`secrets.scrub-tool-result`,{text:e});return t?.error?(Tm.debug(`Bridge scrub-tool-result returned error`),Em):typeof t?.text==`string`?t.text:Em}catch{return Tm.debug(`Bridge scrub-tool-result failed`),Em}}:e===`connect`?Dm:async e=>{if(!e)return e;try{let t=await fetch(o(`/api/secrets/scrub`),{method:`POST`,headers:c({"content-type":`application/json`}),body:JSON.stringify({text:e})});if(!t.ok)return Tm.debug(`Server scrub-tool-result returned non-ok`,{status:t.status}),e;let n=await t.json();return typeof n.text==`string`?n.text:e}catch(t){return Tm.debug(`Server scrub-tool-result failed`,{error:t instanceof Error?t.message:String(t)}),e}}}const km=[];function Am(e){return km.push(e),e}function jm(e){let t=km.lastIndexOf(e);t!==-1&&km.splice(t,1)}function Mm(){return km.length>0?km[km.length-1]:null}const Nm=n(`tool-ui`),Pm=`__mounted`,Fm=new class{pending=new Map;idCounter=0;mounted=new Set;mountWaiters=new Map;generateId(){return`tool-ui-${++this.idCounter}-${Date.now().toString(36)}`}register(e,t,n,r){this.mounted.delete(e),this.pending.set(e,{request:t,resolve:n,reject:r}),Nm.info(`Tool UI registered`,{id:e})}async handleAction(e,t){let n=this.pending.get(e);if(!n){Nm.warn(`Action for unknown tool UI`,{id:e,action:t.action});return}Nm.info(`Tool UI action`,{id:e,action:t.action});try{let e;e=n.request.onAction?await n.request.onAction(t.action,t.data):t,n.resolve(e)}catch(e){n.reject(e instanceof Error?e:Error(String(e)))}finally{this.pending.delete(e),this.clearMountWaiter(e,`tool ui completed`)}}cancel(e,t=`cancelled`){let n=this.pending.get(e);n&&(n.reject(Error(t)),this.pending.delete(e),Nm.info(`Tool UI cancelled`,{id:e,reason:t})),this.clearMountWaiter(e,t),this.mounted.delete(e)}cancelAll(e=`cancelled`){let t=this.pending.size;for(let[t,n]of this.pending)n.reject(Error(e));this.pending.clear();for(let t of[...this.mountWaiters.keys()])this.clearMountWaiter(t,e);this.mounted.clear(),t>0&&Nm.info(`All tool UIs cancelled`,{reason:e,count:t})}isPending(e){return this.pending.has(e)}getPendingIds(){return[...this.pending.keys()]}markMounted(e){this.mounted.add(e);let t=this.mountWaiters.get(e);t&&(clearTimeout(t.timeoutHandle),this.mountWaiters.delete(e),t.resolve())}waitForMount(e,t){return this.mounted.has(e)?Promise.resolve():new Promise((n,r)=>{let i=setTimeout(()=>{this.mountWaiters.delete(e),r(Error(`tool UI ${e} was not mounted by any panel within ${t}ms — check the chat panel`))},t);this.mountWaiters.set(e,{resolve:n,reject:r,timeoutHandle:i})})}clearMountWaiter(e,t){let n=this.mountWaiters.get(e);n&&(clearTimeout(n.timeoutHandle),this.mountWaiters.delete(e),n.reject(Error(t)))}};async function Im(e,t){let n=e.id??Fm.generateId(),r,i,a=new Promise((e,t)=>{r=e,i=t});return Fm.register(n,e,r,i),t?t({content:[{type:`tool_ui`,requestId:n,html:e.html}]}):Nm.warn(`showToolUI called without onUpdate callback — UI may not render`),a.finally(()=>{t&&t({content:[{type:`tool_ui_done`,requestId:n}]})})}async function Lm(e){let t=Mm();return t?Im(e,t.onUpdate):(Nm.warn(`showToolUIFromContext called without execution context`),null)}const Rm=n(`image-processor`),zm=3932160;function Bm(e){let t=e.replace(/[\t\n\f\r ]/g,``),n=t.length%4;return n===2?`${t}==`:n===3?`${t}=`:t}function Vm(e,t){let n=i(Bm(e.slice(0,t)));return new DataView(n.buffer,n.byteOffset,n.byteLength)}function Hm(e,t){return e>0&&t>0?{width:e,height:t}:null}function Um(e){if(e.length<32)return null;let t=Vm(e,32);return Hm(t.getUint32(16,!1),t.getUint32(20,!1))}function Wm(e){if(e.length<16)return null;let t=Vm(e,16);return Hm(t.getUint16(6,!0),t.getUint16(8,!0))}function Gm(e){let t=Vm(e,Math.min(87384,e.length));for(let e=0;e<t.byteLength-8;e++){if(t.getUint8(e)!==255)continue;let n=t.getUint8(e+1);if(n===192||n===194)return Hm(t.getUint16(e+7,!1),t.getUint16(e+5,!1))}return null}function Km(e,t){try{let n=Bm(e);if(t===`image/png`)return Um(n);if(t===`image/gif`)return Wm(n);if(t===`image/jpeg`)return Gm(n)}catch{}return null}async function qm(e){if(!d(e.mimeType))return Rm.warn(`Unsupported image format`,{mimeType:e.mimeType}),{type:`text`,text:`[Image removed: unsupported format "${e.mimeType}". Supported: JPEG, PNG, GIF, WebP]`};let t=e.data.length,n=Km(e.data,e.mimeType);if(!(t>5242880||n!==null&&(n.width>8e3||n.height>8e3)||n!==null&&Math.max(n.width,n.height)>1568))return e;Rm.info(`Image needs processing`,{base64Size:t,dimensions:n?`${n.width}x${n.height}`:`unknown`,reason:t>5242880?`size`:`dimensions`});let a,o;try{let e=await import(`./magick-wasm-266b8ntc.js`).then(e=>e.r);a=e.getMagick,o=e.MIME_TO_MAGICK_FORMAT}catch(e){return Rm.error(`ImageMagick WASM module unavailable`,{error:e instanceof Error?e.message:String(e)}),{type:`text`,text:`[Image removed: resize service unavailable (ImageMagick WASM could not be loaded)]`}}let s;try{s=await a()}catch(e){return Rm.error(`ImageMagick WASM initialization failed`,{error:e instanceof Error?e.message:String(e)}),{type:`text`,text:`[Image removed: resize service unavailable (WASM init failed)]`}}try{let n=i(Bm(e.data)),a={data:null,mime:e.mimeType};if(await s.ImageMagick.read(n,async t=>{let n=t.width,r=t.height,i=Math.max(n,r);if(i>1568){let e=1568/i,a=Math.round(n*e),o=Math.round(r*e);t.resize(a,o),Rm.info(`Resized image`,{from:`${n}x${r}`,to:`${a}x${o}`})}let s=o[e.mimeType]||`JPEG`;t.write(s,e=>{a.data=new Uint8Array(e)}),a.data&&a.data.length>zm&&s!==`JPEG`?(Rm.info(`Still over 5MB, compressing to JPEG q80`),t.quality=80,t.write(`JPEG`,e=>{a.data=new Uint8Array(e)}),a.mime=`image/jpeg`):a.data&&a.data.length>zm&&(Rm.info(`Still over 5MB as JPEG, reducing quality to 60`),t.quality=60,t.write(`JPEG`,e=>{a.data=new Uint8Array(e)}))}),!a.data)return Rm.warn(`ImageMagick produced no output`),{type:`text`,text:`[Image removed: could not be processed (empty output from resize)]`};if(a.data.length>zm)return Rm.warn(`Image still over 5MB after resize+compress`,{size:a.data.length}),{type:`text`,text:`[Image removed: still ${Math.round(a.data.length/1024/1024*10)/10}MB after resize and compression, exceeds 5MB API limit]`};let c=r(a.data);return Rm.info(`Image processed successfully`,{originalBase64:t,newBase64:c.length,mimeType:a.mime}),{type:`image`,data:c,mimeType:a.mime}}catch(n){return Rm.error(`Image data processing failed (corrupt or unreadable)`,{mimeType:e.mimeType,estimatedBytes:t,error:n instanceof Error?n.message:String(n)}),{type:`text`,text:`[Image removed: image data could not be processed (${n instanceof Error?n.message:`corrupt or unreadable`})]`}}}const Jm=n(`tool-adapter`);function Ym(e){let t=[],n=0;for(let r of f(e)){if(r.kind===`inert`||!r.parsed)continue;let i=e.slice(n,r.index);i.trim()&&t.push({type:`text`,text:i.trimEnd()}),t.push({type:`image`,mimeType:r.parsed.mimeType,data:r.parsed.data}),n=r.index+r.marker.length}let r=e.slice(n);return(r.trim()||t.length===0)&&t.push({type:`text`,text:r||e}),t}async function Xm(e){let t=Ym(e),n=[];for(let e of t)e.type===`image`?n.push(await qm(e)):n.push(e);return n}function Zm(e,t,n,r){if(!r)return{tracked:null,effectiveSignal:n};let i=r.processManager.spawn({kind:`tool`,argv:[e.name,...ih(t)],owner:r.owner,ppid:r.getParentPid?.()});n?.aborted?r.processManager.signal(i.pid,`SIGINT`):n&&n.addEventListener(`abort`,()=>r.processManager.signal(i.pid,`SIGINT`),{once:!0});let a=r.processManager.onSignal((e,t)=>{e.pid===i.pid&&t===`SIGKILL`&&r.processManager.exit(i.pid,null)});return{tracked:{record:i,manager:r.processManager,unsubscribeKill:a},effectiveSignal:i.abort.signal}}function Qm(e,t){e&&e.manager.exit(e.record.pid,t)}async function $m(e,t,n){if(!n||typeof e!=`string`||e.length===0)return e;try{return await n.scrubToolResult(e)}catch(n){return Jm.warn(`Tool-result scrub failed, falling back to unscrubbed content`,{tool:t,error:n instanceof Error?n.message:String(n)}),e}}async function eh(e,t){try{return await Xm(e)}catch(n){return Jm.warn(`Image processing failed, falling back to raw content`,{tool:t,error:n instanceof Error?n.message:String(n)}),Ym(e)}}async function th(e,t,n,r){let i=n?.currentGate();if(!i)return!0;if(r?.aborted)return!1;try{return await i.approve(e.name,t)&&r?.aborted!==!0}catch(t){return Jm.warn(`Tool-call gate threw — refusing the call`,{tool:e.name,error:t instanceof Error?t.message:String(t)}),!1}}function nh(e,t,n,r){return{name:e.name,label:e.name,description:e.description,parameters:e.inputSchema,async execute(i,a,o,s){let c;if(s&&(c=Am({onUpdate:s,toolName:e.name,toolCallId:i})),!await th(e,a,r,o))return c&&jm(c),{content:[{type:`text`,text:`${e.name}: not approved (guest-caused turn).`}],details:{isError:!0}};let l=Zm(e,a,o,t);try{let t=await e.execute(a??{},l.effectiveSignal),r=await eh(await $m(t.content,e.name,n),e.name);return Qm(l.tracked,+!!t.isError),{content:r,details:{isError:t.isError}}}catch(e){throw Qm(l.tracked,l.tracked?.record.abort.signal.aborted?null:1),e}finally{c&&jm(c),l.tracked?.unsubscribeKill()}}}}function rh(e,t,n,r){return e.map(e=>nh(e,t,n,r))}function ih(e){if(typeof e!=`object`||!e)return[];let t=e;for(let e of[`command`,`file_path`,`path`,`pattern`,`url`,`key`,`name`,`query`,`message`]){let n=t[e];if(typeof n==`string`&&n.length>0)return[n]}for(let e of Object.values(t))if(typeof e==`string`&&e.length>0)return[e];return[]}export{qt as $,z as A,Te as At,qn as B,xe as Bt,Oi as C,me as Ct,B as D,Ee as Dt,Ni as E,he as Et,$n as F,_e as Ft,Ln as G,ue as Gt,I as H,Fe as Ht,Xn as I,ve as It,rn as J,Mn as K,L,b as Lt,rr as M,je as Mt,nr as N,Me as Nt,Tr as O,Ce as Ot,tr as P,De as Pt,$t as Q,Gn as R,ye as Rt,Pi as S,pe as St,ji as T,x as Tt,Vn as U,ke as Ut,Jn as V,Se as Vt,Rn as W,w as Wt,en as X,nn as Y,N as Z,nf as _,Ne as _t,Lm as a,jt as at,Bi as b,de as bt,Om as c,Tt as ct,xm as d,St as dt,Wt as et,bm as f,mt as ft,cf as g,Ie as gt,ff as h,Le as ht,Im as i,It as it,R as j,we as jt,xr as k,ge as kt,wm as l,Ct as lt,em as m,ct as mt,ih as n,j as nt,Fm as o,At as ot,dm as p,ut as pt,jn as q,Pm as r,zt as rt,Mm as s,Ot as st,rh as t,M as tt,Sm as u,k as ut,Wd as v,Pe as vt,Mi as w,He as wt,zi as x,fe as xt,Ya as y,C as yt,Kn as z,be as zt};
95
+ Keep each section concise. Preserve exact file paths, function names, and error messages. Output ONLY the summary, with no preamble or follow-up.`,u,e.headers,s),f={role:`user`,content:[{type:`text`,text:`<context-summary>\n${d}\n</context-summary>`}],timestamp:Date.now()};return $.info(`LLM summarization successful`,{originalMessages:o,compactedMessages:1+r.length,summaryLength:d.length}),await Cm(e,t,l,s),_m(e,`idle`),[f,...r]}catch(e){return $.warn(`LLM summarization failed, falling back to naive drop`,{error:e instanceof Error?e.message:String(e)}),null}}function Tm(e){let t=e.contextWindow??2e5,n=e.reserveTokens??Yp.reserveTokens,r=e.keepRecentTokens??Yp.keepRecentTokens,i=e.hopelessMultiplier??4,a={enabled:!0,reserveTokens:n,keepRecentTokens:r};return async(o,s,c)=>{if(o.length===0)return o;let l=hm(o);if(!c?.force&&!Xp(l,t,a))return o;let u=vm(o,l,t,n,i,a);if(u.earlyReturn)return u.earlyReturn;let d=u.messages,f=u.isHopeless;$.info(`Context compaction triggered`,{totalTokens:l,contextWindow:t,threshold:t-n,messageCount:d.length});let p=Sm(d,r);if(!p)return d;let{messagesToSummarize:m,messagesToKeep:h}=p;$.info(`Compaction cut point`,{summarizing:m.length,keeping:h.length});let g=f?void 0:e.getApiKey();if(g){let r=await wm(e,g,m,h,n,t,o.length,s);if(r){let[e,...n]=r;return[e,...xm([e],n,t,a)]}}else f||$.warn(`No API key available for LLM summarization, falling back to naive drop`);_m(e,`fallback`),_m(e,`idle`);let ee={role:`user`,content:[{type:`text`,text:`[Earlier conversation messages were compacted to save context space]`}],timestamp:Date.now()},_=xm([ee],h,t,a);return $.info(`Naive compaction applied`,{originalMessages:o.length,compactedMessages:1+_.length}),[ee,..._]}}function Em(){return a()?`extension-direct`:s()?`extension-delegate`:globalThis.__slicc_connect_mode?`connect`:`node-rest`}function Dm(){return Em()===`node-rest`}const Om=u({portName:`secrets.crud`,panelRpcOp:`secrets-bridge`,timeoutMs:1e4,onUnavailable:`resolve-undefined`,makeError:e=>Error(e),logNamespace:`secrets-bridge`,toPortMessage:({type:e,payload:t})=>({type:e,...t}),toPanelRpcPayload:({type:e,payload:t})=>({type:e,payload:t})});function km(e,t){return Om({type:e,payload:t})}const Am=n(`secret-scrub`),jm=`[tool output withheld: secret scrub unavailable]`,Mm=async e=>e;function Nm(){let e=Em();return e===`extension-direct`?async e=>{if(!e)return e;try{let t=await new Promise(t=>{chrome.runtime.sendMessage({type:`secrets.scrub-tool-result`,text:e},e=>t(e??{}))});return t.error?(Am.debug(`SW scrub-tool-result returned error`),jm):typeof t.text==`string`?t.text:jm}catch{return Am.debug(`SW scrub-tool-result failed`),jm}}:e===`extension-delegate`?async e=>{if(!e)return e;try{let t=await km(`secrets.scrub-tool-result`,{text:e});return t?.error?(Am.debug(`Bridge scrub-tool-result returned error`),jm):typeof t?.text==`string`?t.text:jm}catch{return Am.debug(`Bridge scrub-tool-result failed`),jm}}:e===`connect`?Mm:async e=>{if(!e)return e;try{let t=await fetch(o(`/api/secrets/scrub`),{method:`POST`,headers:c({"content-type":`application/json`}),body:JSON.stringify({text:e})});if(!t.ok)return Am.debug(`Server scrub-tool-result returned non-ok`,{status:t.status}),e;let n=await t.json();return typeof n.text==`string`?n.text:e}catch(t){return Am.debug(`Server scrub-tool-result failed`,{error:t instanceof Error?t.message:String(t)}),e}}}const Pm=[];function Fm(e){return Pm.push(e),e}function Im(e){let t=Pm.lastIndexOf(e);t!==-1&&Pm.splice(t,1)}function Lm(){return Pm.length>0?Pm[Pm.length-1]:null}const Rm=n(`tool-ui`),zm=`__mounted`,Bm=new class{pending=new Map;idCounter=0;mounted=new Set;mountWaiters=new Map;generateId(){return`tool-ui-${++this.idCounter}-${Date.now().toString(36)}`}register(e,t,n,r){this.mounted.delete(e),this.pending.set(e,{request:t,resolve:n,reject:r}),Rm.info(`Tool UI registered`,{id:e})}async handleAction(e,t){let n=this.pending.get(e);if(!n){Rm.warn(`Action for unknown tool UI`,{id:e,action:t.action});return}Rm.info(`Tool UI action`,{id:e,action:t.action});try{let e;e=n.request.onAction?await n.request.onAction(t.action,t.data):t,n.resolve(e)}catch(e){n.reject(e instanceof Error?e:Error(String(e)))}finally{this.pending.delete(e),this.clearMountWaiter(e,`tool ui completed`)}}cancel(e,t=`cancelled`){let n=this.pending.get(e);n&&(n.reject(Error(t)),this.pending.delete(e),Rm.info(`Tool UI cancelled`,{id:e,reason:t})),this.clearMountWaiter(e,t),this.mounted.delete(e)}cancelAll(e=`cancelled`){let t=this.pending.size;for(let[t,n]of this.pending)n.reject(Error(e));this.pending.clear();for(let t of[...this.mountWaiters.keys()])this.clearMountWaiter(t,e);this.mounted.clear(),t>0&&Rm.info(`All tool UIs cancelled`,{reason:e,count:t})}isPending(e){return this.pending.has(e)}getPendingIds(){return[...this.pending.keys()]}markMounted(e){this.mounted.add(e);let t=this.mountWaiters.get(e);t&&(clearTimeout(t.timeoutHandle),this.mountWaiters.delete(e),t.resolve())}waitForMount(e,t){return this.mounted.has(e)?Promise.resolve():new Promise((n,r)=>{let i=setTimeout(()=>{this.mountWaiters.delete(e),r(Error(`tool UI ${e} was not mounted by any panel within ${t}ms — check the chat panel`))},t);this.mountWaiters.set(e,{resolve:n,reject:r,timeoutHandle:i})})}clearMountWaiter(e,t){let n=this.mountWaiters.get(e);n&&(clearTimeout(n.timeoutHandle),this.mountWaiters.delete(e),n.reject(Error(t)))}};async function Vm(e,t){let n=e.id??Bm.generateId(),r,i,a=new Promise((e,t)=>{r=e,i=t});return Bm.register(n,e,r,i),t?t({content:[{type:`tool_ui`,requestId:n,html:e.html}]}):Rm.warn(`showToolUI called without onUpdate callback — UI may not render`),a.finally(()=>{t&&t({content:[{type:`tool_ui_done`,requestId:n}]})})}async function Hm(e){let t=Lm();return t?Vm(e,t.onUpdate):(Rm.warn(`showToolUIFromContext called without execution context`),null)}const Um=n(`image-processor`),Wm=3932160;function Gm(e){let t=e.replace(/[\t\n\f\r ]/g,``),n=t.length%4;return n===2?`${t}==`:n===3?`${t}=`:t}function Km(e,t){let n=i(Gm(e.slice(0,t)));return new DataView(n.buffer,n.byteOffset,n.byteLength)}function qm(e,t){return e>0&&t>0?{width:e,height:t}:null}function Jm(e){if(e.length<32)return null;let t=Km(e,32);return qm(t.getUint32(16,!1),t.getUint32(20,!1))}function Ym(e){if(e.length<16)return null;let t=Km(e,16);return qm(t.getUint16(6,!0),t.getUint16(8,!0))}function Xm(e){let t=Km(e,Math.min(87384,e.length));for(let e=0;e<t.byteLength-8;e++){if(t.getUint8(e)!==255)continue;let n=t.getUint8(e+1);if(n===192||n===194)return qm(t.getUint16(e+7,!1),t.getUint16(e+5,!1))}return null}function Zm(e,t){try{let n=Gm(e);if(t===`image/png`)return Jm(n);if(t===`image/gif`)return Ym(n);if(t===`image/jpeg`)return Xm(n)}catch{}return null}async function Qm(e){if(!d(e.mimeType))return Um.warn(`Unsupported image format`,{mimeType:e.mimeType}),{type:`text`,text:`[Image removed: unsupported format "${e.mimeType}". Supported: JPEG, PNG, GIF, WebP]`};let t=e.data.length,n=Zm(e.data,e.mimeType);if(!(t>5242880||n!==null&&(n.width>8e3||n.height>8e3)||n!==null&&Math.max(n.width,n.height)>1568))return e;Um.info(`Image needs processing`,{base64Size:t,dimensions:n?`${n.width}x${n.height}`:`unknown`,reason:t>5242880?`size`:`dimensions`});let a,o;try{let e=await import(`./magick-wasm-266b8ntc.js`).then(e=>e.r);a=e.getMagick,o=e.MIME_TO_MAGICK_FORMAT}catch(e){return Um.error(`ImageMagick WASM module unavailable`,{error:e instanceof Error?e.message:String(e)}),{type:`text`,text:`[Image removed: resize service unavailable (ImageMagick WASM could not be loaded)]`}}let s;try{s=await a()}catch(e){return Um.error(`ImageMagick WASM initialization failed`,{error:e instanceof Error?e.message:String(e)}),{type:`text`,text:`[Image removed: resize service unavailable (WASM init failed)]`}}try{let n=i(Gm(e.data)),a={data:null,mime:e.mimeType};if(await s.ImageMagick.read(n,async t=>{let n=t.width,r=t.height,i=Math.max(n,r);if(i>1568){let e=1568/i,a=Math.round(n*e),o=Math.round(r*e);t.resize(a,o),Um.info(`Resized image`,{from:`${n}x${r}`,to:`${a}x${o}`})}let s=o[e.mimeType]||`JPEG`;t.write(s,e=>{a.data=new Uint8Array(e)}),a.data&&a.data.length>Wm&&s!==`JPEG`?(Um.info(`Still over 5MB, compressing to JPEG q80`),t.quality=80,t.write(`JPEG`,e=>{a.data=new Uint8Array(e)}),a.mime=`image/jpeg`):a.data&&a.data.length>Wm&&(Um.info(`Still over 5MB as JPEG, reducing quality to 60`),t.quality=60,t.write(`JPEG`,e=>{a.data=new Uint8Array(e)}))}),!a.data)return Um.warn(`ImageMagick produced no output`),{type:`text`,text:`[Image removed: could not be processed (empty output from resize)]`};if(a.data.length>Wm)return Um.warn(`Image still over 5MB after resize+compress`,{size:a.data.length}),{type:`text`,text:`[Image removed: still ${Math.round(a.data.length/1024/1024*10)/10}MB after resize and compression, exceeds 5MB API limit]`};let c=r(a.data);return Um.info(`Image processed successfully`,{originalBase64:t,newBase64:c.length,mimeType:a.mime}),{type:`image`,data:c,mimeType:a.mime}}catch(n){return Um.error(`Image data processing failed (corrupt or unreadable)`,{mimeType:e.mimeType,estimatedBytes:t,error:n instanceof Error?n.message:String(n)}),{type:`text`,text:`[Image removed: image data could not be processed (${n instanceof Error?n.message:`corrupt or unreadable`})]`}}}const $m=n(`tool-adapter`);function eh(e){let t=[],n=0;for(let r of f(e)){if(r.kind===`inert`||!r.parsed)continue;let i=e.slice(n,r.index);i.trim()&&t.push({type:`text`,text:i.trimEnd()}),t.push({type:`image`,mimeType:r.parsed.mimeType,data:r.parsed.data}),n=r.index+r.marker.length}let r=e.slice(n);return(r.trim()||t.length===0)&&t.push({type:`text`,text:r||e}),t}async function th(e){let t=eh(e),n=[];for(let e of t)e.type===`image`?n.push(await Qm(e)):n.push(e);return n}function nh(e,t,n,r){if(!r)return{tracked:null,effectiveSignal:n};let i=r.processManager.spawn({kind:`tool`,argv:[e.name,...lh(t)],owner:r.owner,ppid:r.getParentPid?.()});n?.aborted?r.processManager.signal(i.pid,`SIGINT`):n&&n.addEventListener(`abort`,()=>r.processManager.signal(i.pid,`SIGINT`),{once:!0});let a=r.processManager.onSignal((e,t)=>{e.pid===i.pid&&t===`SIGKILL`&&r.processManager.exit(i.pid,null)});return{tracked:{record:i,manager:r.processManager,unsubscribeKill:a},effectiveSignal:i.abort.signal}}function rh(e,t){e&&e.manager.exit(e.record.pid,t)}async function ih(e,t,n){if(!n||typeof e!=`string`||e.length===0)return e;try{return await n.scrubToolResult(e)}catch(n){return $m.warn(`Tool-result scrub failed, falling back to unscrubbed content`,{tool:t,error:n instanceof Error?n.message:String(n)}),e}}async function ah(e,t){try{return await th(e)}catch(n){return $m.warn(`Image processing failed, falling back to raw content`,{tool:t,error:n instanceof Error?n.message:String(n)}),eh(e)}}async function oh(e,t,n,r){let i=n?.currentGate();if(!i)return!0;if(r?.aborted)return!1;try{return await i.approve(e.name,t)&&r?.aborted!==!0}catch(t){return $m.warn(`Tool-call gate threw — refusing the call`,{tool:e.name,error:t instanceof Error?t.message:String(t)}),!1}}function sh(e,t,n,r){return{name:e.name,label:e.name,description:e.description,parameters:e.inputSchema,async execute(i,a,o,s){let c;if(s&&(c=Fm({onUpdate:s,toolName:e.name,toolCallId:i})),!await oh(e,a,r,o))return c&&Im(c),{content:[{type:`text`,text:`${e.name}: not approved (guest-caused turn).`}],details:{isError:!0}};let l=nh(e,a,o,t);try{let t=await e.execute(a??{},l.effectiveSignal),r=await ah(await ih(t.content,e.name,n),e.name);return rh(l.tracked,+!!t.isError),{content:r,details:{isError:t.isError}}}catch(e){throw rh(l.tracked,l.tracked?.record.abort.signal.aborted?null:1),e}finally{c&&Im(c),l.tracked?.unsubscribeKill()}}}}function ch(e,t,n,r){return e.map(e=>sh(e,t,n,r))}function lh(e){if(typeof e!=`object`||!e)return[];let t=e;for(let e of[`command`,`file_path`,`path`,`pattern`,`url`,`key`,`name`,`query`,`message`]){let n=t[e];if(typeof n==`string`&&n.length>0)return[n]}for(let e of Object.values(t))if(typeof e==`string`&&e.length>0)return[e];return[]}export{qt as $,z as A,Te as At,qn as B,xe as Bt,Oi as C,me as Ct,B as D,Ee as Dt,Ni as E,he as Et,$n as F,_e as Ft,Ln as G,ue as Gt,I as H,Fe as Ht,Xn as I,ve as It,rn as J,Mn as K,L,b as Lt,rr as M,je as Mt,nr as N,Me as Nt,Tr as O,Ce as Ot,tr as P,De as Pt,$t as Q,Gn as R,ye as Rt,Pi as S,pe as St,ji as T,x as Tt,Vn as U,ke as Ut,Jn as V,Se as Vt,Rn as W,w as Wt,en as X,nn as Y,N as Z,nf as _,Ne as _t,Hm as a,jt as at,Bi as b,de as bt,Nm as c,Tt as ct,Em as d,St as dt,Wt as et,Tm as f,mt as ft,cf as g,Ie as gt,ff as h,Le as ht,Vm as i,It as it,R as j,we as jt,xr as k,ge as kt,km as l,Ct as lt,em as m,ct as mt,lh as n,j as nt,Bm as o,At as ot,gm as p,ut as pt,jn as q,zm as r,zt as rt,Lm as s,Ot as st,ch as t,M as tt,Dm as u,k as ut,Wd as v,Pe as vt,Mi as w,He as wt,zi as x,fe as xt,Ya as y,C as yt,Kn as z,be as zt};
@@ -1 +1 @@
1
- import{t as e}from"./logger-LESFN7Hj.js";import{t}from"./agent-bridge-CuRwAl_F.js";import{T as n}from"./descriptor-Bh6C6cqu.js";const r=e(`directed-approval`);function i(e,t){if(e.kind===`user`)return a(`the user tier is not a directed approval`);if(e.kind===`agent`)return a(`agent approvals are not enqueued to a unit`);let r=e.unitJid;if(!t.scoops.has(r))return a(`the requesting unit is not registered`);let i=t.ownerRootOf(r);if(!i)return a(`no owning cone for the requesting unit`);let o=e.kind===`cone`?i:[...t.scoops.values()].find(t=>t.parentJid===i.jid&&(t.name===e.scoopName||t.folder===e.scoopName));return o?n(o).canResolveApprovals?{ok:!0,requesterJid:r,approver:o}:a(`the named approver cannot resolve approvals`):a(`delegated approver not found under this cone`)}function a(e){return r.warn(`Directed approval failing closed`,{reason:e}),{ok:!1,reason:e}}const o={decision:`deny`};async function s(e,n){let a=e.approver;if(a?.kind===`agent`){let i=globalThis[t];if(!i)return r.warn(`No agent bridge available for an approver agent — denying`),o;let{approverRunnerFor:s}=await import(`./approver-agent-CYHU0chR.js`),c=n.getSharedFs(),l=await s({spawn:e=>i.spawn(e),readSharedFile:async e=>{if(!c)return null;try{let t=await c.readFile(e,{encoding:`utf-8`});return typeof t==`string`?t:null}catch{return null}},findUnit:e=>{let t=n.scoops.get(e);return t?{workspace:n.workspaceFor(t),folder:t.folder}:void 0}})({kind:e.kind===`guest-tool`?`guest-tool`:`guest-message`,requester:e.requester??`an unidentified requester`,detail:e.detail},a.unitJid);return r.info(`Approver agent verdict`,{decision:l.decision,reason:l.reason}),l.decision===`allow`?{decision:`allow`}:o}if(a&&a.kind!==`user`){let t=i(a,n);return t.ok?n.enqueue(t.requesterJid,e,{approver:t.approver}):o}return n.approveAsUser(e)}export{s as runDirectedApproval};
1
+ import{t as e}from"./logger-LESFN7Hj.js";import{t}from"./agent-bridge-DJ2Gh9VA.js";import{T as n}from"./descriptor-Bh6C6cqu.js";const r=e(`directed-approval`);function i(e,t){if(e.kind===`user`)return a(`the user tier is not a directed approval`);if(e.kind===`agent`)return a(`agent approvals are not enqueued to a unit`);let r=e.unitJid;if(!t.scoops.has(r))return a(`the requesting unit is not registered`);let i=t.ownerRootOf(r);if(!i)return a(`no owning cone for the requesting unit`);let o=e.kind===`cone`?i:[...t.scoops.values()].find(t=>t.parentJid===i.jid&&(t.name===e.scoopName||t.folder===e.scoopName));return o?n(o).canResolveApprovals?{ok:!0,requesterJid:r,approver:o}:a(`the named approver cannot resolve approvals`):a(`delegated approver not found under this cone`)}function a(e){return r.warn(`Directed approval failing closed`,{reason:e}),{ok:!1,reason:e}}const o={decision:`deny`};async function s(e,n){let a=e.approver;if(a?.kind===`agent`){let i=globalThis[t];if(!i)return r.warn(`No agent bridge available for an approver agent — denying`),o;let{approverRunnerFor:s}=await import(`./approver-agent-CYHU0chR.js`),c=n.getSharedFs(),l=await s({spawn:e=>i.spawn(e),readSharedFile:async e=>{if(!c)return null;try{let t=await c.readFile(e,{encoding:`utf-8`});return typeof t==`string`?t:null}catch{return null}},findUnit:e=>{let t=n.scoops.get(e);return t?{workspace:n.workspaceFor(t),folder:t.folder}:void 0}})({kind:e.kind===`guest-tool`?`guest-tool`:`guest-message`,requester:e.requester??`an unidentified requester`,detail:e.detail},a.unitJid);return r.info(`Approver agent verdict`,{decision:l.decision,reason:l.reason}),l.decision===`allow`?{decision:`allow`}:o}if(a&&a.kind!==`user`){let t=i(a,n);return t.ok?n.enqueue(t.requesterJid,e,{approver:t.approver}):o}return n.approveAsUser(e)}export{s as runDirectedApproval};
@@ -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"./types-idfTVsM8.js";import{i as c,r as l,t as u}from"./mount-index-BCzDM4LQ.js";import{a as d,i as f,n as p,t as m}from"./mount-table-store-DrF_Ifaz.js";import{n as h,t as g}from"./virtual-device-paths-CS5o4QVz.js";import{i as _,r as v,t as y}from"./sidecar-repair-CIHuOk7H.js";const b=t(`fs-watcher`);let x=0;function S(e,t){return t===`/`||e===t||e.startsWith(t+`/`)}var C=class{registrations=new Map;watch(e,t,n){let r=`fsw-${++x}`;return this.registrations.set(r,{id:r,basePath:e,filter:t,callback:n}),b.debug(`Watch registered`,{id:r,basePath:e}),()=>{this.registrations.delete(r),b.debug(`Watch unregistered`,{id:r})}}notify(e){if(e.length!==0)for(let[,t]of this.registrations){let n=e.filter(e=>S(e.path,t.basePath)&&t.filter(e.path));if(n.length>0)try{t.callback(n)}catch(e){b.error(`Watch callback error`,{id:t.id,error:e instanceof Error?e.message:String(e)})}}}dispose(){this.registrations.clear(),b.debug(`All watchers disposed`)}get size(){return this.registrations.size}};const w=new TextEncoder,T=new TextDecoder(`utf-8`,{fatal:!1});var E=class{entries=new Map;static handles(e){return h(i(e))}has(e){return this.entries.has(i(e))}write(e,t){let n=i(e),r=typeof t==`string`?w.encode(t):new Uint8Array(t),a=Date.now(),o=this.entries.get(n);this.entries.set(n,{bytes:r,mtime:a,ctime:o?.ctime??a})}read(e,t){let n=this.require(e);return(t?.encoding??`utf-8`)===`utf-8`?T.decode(n.bytes):new Uint8Array(n.bytes)}readText(e){return T.decode(this.require(e).bytes)}stat(e){let t=this.require(e);return{type:`file`,size:t.bytes.length,mtime:t.mtime,ctime:t.ctime}}remove(e){return this.entries.delete(i(e))}require(e){let t=i(e),n=this.entries.get(t);if(!n)throw new s(`ENOENT`,`no such file or directory`,t);return n}};const D={[g]:{stat:()=>({type:`file`,size:0,mtime:0,ctime:0}),read:e=>(e?.encoding??`utf-8`)===`utf-8`?``:new Uint8Array,readText:()=>``,write:()=>{}}},O=[`/tmp/`];var k=class{ephemeralFds=new E;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,...O]}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,...O].some(e=>t===e.slice(0,-1)||t.startsWith(e))}canWrite(e){return E.handles(e)||this.isWritable(e)}checkWrite(e){if(this.writeEnforcement!==`sudo-delegated`&&!this.isWritable(e))throw new s(`EACCES`,`permission denied`,i(e))}async resolveAndCheckRead(e){try{let t=await this.vfs.realpath(e);if(!this.isAllowedStrict(t))throw new s(`ENOENT`,`no such file or directory`,i(e));return t}catch(t){throw t instanceof s?t:new s(`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 s(`EACCES`,`permission denied`,i(e));return t}catch(t){throw t instanceof s?t:new s(`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 s&&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 s(`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=D[i(e)];if(n)return n.read(t);if(E.handles(e))return this.ephemeralFds.read(e,t);if(!this.isAllowedStrict(e))throw new s(`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=D[i(e)];if(t)return t.stat();if(E.handles(e))return this.ephemeralFds.stat(e);if(!this.isAllowed(e))throw new s(`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=D[i(e)];return t?t.stat():E.handles(e)?this.ephemeralFds.has(e)?this.ephemeralFds.stat(e):null:!this.isAllowedStrict(e)||this.scanPathForSymlinks(e,!0)!==!1?null:this.vfs.statSync(e)}lstatSync(e){let t=D[i(e)];return t?t.stat():E.handles(e)?this.ephemeralFds.has(e)?this.ephemeralFds.stat(e):null:!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){if(E.handles(e)){let t=i(e);if(!this.ephemeralFds.has(t))throw new s(`ENOENT`,`no such file or directory`,t);return t}let t;try{t=await this.vfs.realpath(e)}catch(t){throw t instanceof s?t:new s(`ENOENT`,`no such file or directory`,i(e))}if(!this.isAllowedStrict(t))throw new s(`ENOENT`,`no such file or directory`,i(e));return t}async exists(e){if(D[i(e)])return!0;if(E.handles(e))return this.ephemeralFds.has(e);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=D[i(e)];if(t)return t.readText();if(E.handles(e))return this.ephemeralFds.readText(e);if(!this.isAllowedStrict(e))throw new s(`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=D[i(e)];if(r){r.write(t);return}if(E.handles(e)){this.ephemeralFds.write(e,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 s&&e.code===`EACCES`)throw e}return this.vfs.writeFile(e,t,n)}refuseDescriptorTreeOp(e){if(E.handles(e))throw new s(`EACCES`,`permission denied`,i(e))}async mkdir(e,t){return this.refuseDescriptorTreeOp(e),this.checkWrite(e),await this.checkParentRealpathEscape(e),this.vfs.mkdir(e,t)}async rm(e,t){if(E.handles(e)){if(!this.ephemeralFds.remove(e))throw new s(`ENOENT`,`no such file or directory`,i(e));return}this.checkWrite(e);try{(await this.vfs.lstat(e)).type===`symlink`||await this.resolveAndCheckWrite(e)}catch(e){if(e instanceof s&&e.code===`EACCES`)throw e}return this.vfs.rm(e,t)}async rename(e,t){return this.refuseDescriptorTreeOp(e),this.refuseDescriptorTreeOp(t),this.checkWrite(e),this.checkWrite(t),await this.resolveAndCheckWrite(e),await this.checkParentRealpathEscape(t),this.vfs.rename(e,t)}async copyFile(e,t){if(E.handles(e)){let n=this.ephemeralFds.read(e,{encoding:`binary`});await this.writeFile(t,n);return}if(E.handles(t)){if(!this.isAllowed(e))throw new s(`ENOENT`,`no such file or directory`,i(e));let n=await this.resolveAndCheckRead(e);this.ephemeralFds.write(t,await this.vfs.readFile(n,{encoding:`binary`}));return}if(!this.isAllowed(e))throw new s(`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 s&&e.code===`EACCES`)throw e}return this.vfs.copyFile(n,t)}async symlink(e,t){return this.refuseDescriptorTreeOp(t),this.checkWrite(t),await this.checkParentRealpathEscape(t),this.vfs.symlink(e,t)}async readlink(e){if(!this.isAllowedStrict(e))throw new s(`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 s(`ENOENT`,`no such file or directory`,i(e));return t}async lstat(e){let t=D[i(e)];if(t)return t.stat();if(E.handles(e))return this.ephemeralFds.stat(e);if(!this.isAllowed(e))throw new s(`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 s(`ENOENT`,`no such file or directory`,n)}let c=o===`/`?`/${a}`:`${o}/${a}`;if(!this.isAllowed(c))throw new s(`ENOENT`,`no such file or directory`,n);return this.vfs.lstat(c)}watch(e,t,n){if(!this.isAllowed(e))throw new s(`EACCES`,`permission denied`,i(e));let r=this.vfs.getWatcher();if(!r)throw new s(`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.refuseDescriptorTreeOp(e),this.checkWrite(e),await this.checkParentRealpathEscape(e),this.vfs.mount(e,t,n)}async unmount(e){return this.refuseDescriptorTreeOp(e),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.refuseDescriptorTreeOp(e),this.checkWrite(e),this.vfs.refreshMount(e,t)}async dispose(){await this.vfs.dispose()}};function A(e,t){if(e instanceof s){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 s(e.code,r,t)}throw e}const j=[`ENOENT`,`EEXIST`,`ENOTDIR`,`EISDIR`,`ENOTEMPTY`,`EINVAL`,`EACCES`,`ELOOP`,`EBUSY`,`EFBIG`,`EBADF`,`ENOSYS`,`EIO`];function M(e,t){if(e instanceof s)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 s(`EIO`,`internal overflow, not storage: ${n} — reload the session`,t)}let n=e?.code;if(typeof n==`string`){let r=n;if(j.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 s(r,n||r,t)}}let r=e instanceof Error?e.message:String(e);return r.includes(`ENOENT`)?new s(`ENOENT`,`no such file or directory`,t):r.includes(`EEXIST`)?new s(`EEXIST`,`file already exists`,t):r.includes(`ENOTDIR`)?new s(`ENOTDIR`,`not a directory`,t):r.includes(`EISDIR`)?new s(`EISDIR`,`is a directory`,t):r.includes(`ENOTEMPTY`)?new s(`ENOTEMPTY`,`directory not empty`,t):r.includes(`ELOOP`)?new s(`ELOOP`,`too many levels of symbolic links`,t):new s(`EINVAL`,r,t)}function N(e){return e===void 0?`absent`:(e&61440)==16384?`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}async function L(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 R(e,t,r){let a;try{a=await e.readlink(t)}catch(e){throw M(e,r)}return a.startsWith(`/`)?i(a):i(o(n(t).dir,a))}async function z(e,t,n,r,i,a){let o=t===`/`?`/${n}`:`${t}/${n}`;for(;;){let t=await L(e,o,r,i);if(t===null||!t.isSymbolicLink())return{resolved:o,hops:a};if(++a>10)throw new s(`ELOOP`,`too many symbolic links encountered`,i);o=await R(e,o,i)}}async function B(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 z(e,o,a[t],t===a.length-1,r,s);o=n.resolved,s=n.hops}return o}async function V(e,t,n){return t(n)?n:B(e,t,n)}function H(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 U(e,t){try{return await e(t)}catch{return t}}async function*W(e,t,n,r=0){let a=i(t);if(H(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 U(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*G(e,t,a===`/`?`/${t.name}`:`${a}/${t.name}`,o,r+1)}async function*G(e,t,n,r,i){if(t.type===`file`){yield n;return}if(t.type===`symlink`){yield*K(e,n,r,i);return}yield*W(e,n,r,i)}async function*K(e,t,n,r){try{let i=await e.stat(t);i.type===`file`?yield t:i.type===`directory`&&(yield*W(e,t,n,r))}catch{}}function q(){try{if(typeof globalThis.navigator?.storage?.getDirectory==`function`)return`opfs`}catch{}return`memory`}function J(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 Y=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 u;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-CBELmDjr.js`).then(e=>e.t),import(`./dist-iMxkf8fm.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-CBELmDjr.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 s(`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 m().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=v(e,r,i))}let o=JSON.stringify(_(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=y(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 y(n)(a),s=N(t.index.get(a)?.mode),c=t._handles?.get(a),l=c?.kind===`directory`?`directory`:c?.kind===`file`?`file`:`absent`,u=P(o,s),d=P(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 s(`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-CBELmDjr.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,ino:e.ino}}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,ino:e.ino};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,ino:e.ino}}return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,ino:e.ino}}catch{return null}}async mount(e,t,r){let a=i(e);if(this.mountPoints.has(a))throw new s(`EEXIST`,`mount point is already mounted`,a);try{if((await this.lstat(a)).type!==`directory`)throw new s(`ENOTDIR`,`mount point must be a directory`,a);if((await this.readDir(a)).length>0)throw new s(`ENOTEMPTY`,`mount point must be empty to avoid shadowing existing files`,a)}catch(e){if(!(e instanceof s)||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??l(r?.env??{});this.mountIndex.registerMount(a,t.getHandle(),e)}let c=J(t,a);try{this.mountSyncChannel?.postMessage({type:`mount`,path:a,descriptor:c})}catch{}if(this.watcher?.notify([{type:`modify`,path:a,entryType:`directory`}]),t.kind!==`hostfs`)try{let e={targetPath:a,descriptor:c,createdAt:Date.now()},n=t.kind===`local`?t.getHandle():void 0;await d(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 f(t)}catch{}}async reconstructBackendFromDescriptor(e,t){switch(e.kind){case`local`:{let t=await p(e.idbHandleKey);if(!t)throw Error(`no handle stored for ${e.idbHandleKey}`);return c.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-DeYTNAtM.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-DeYTNAtM.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-DeYTNAtM.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 s(`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 s(`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 s(`ENOENT`,`not a mount point`,n);let a=await r.refresh(t);return r.kind===`local`&&await this.mountIndex.refreshMount(n,l(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 s(`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){A(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 M(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 s(`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){A(e,a)}this.watcher?.notify([{type:n?`modify`:`create`,path:a,entryType:`file`}]),this.mountIndex.notifyWrite(a);return}let c;try{c=await this.resolveSymlinks(a)}catch{c=a}let l=!1;try{await this.lfs.stat(c),l=!0}catch{}let{dir:u}=n(c);await this.withWriteLock(async()=>{this.markSidecarDirty(c),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(c,t)}catch(e){if(u!==`/`&&e instanceof Error&&e.message.includes(`ENOENT`)){await this.mkdirRecursiveUnlocked(u);try{await this.lfs.writeFile(c,t)}catch(e){throw M(e,a)}}else throw M(e,a)}try{await this.lfs.truncate?.(c,e)}catch(e){throw M(e,a)}}),this.watcher?.notify([{type:l?`modify`:`create`,path:c,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){A(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 s(`ENOTDIR`,`not a directory`,r)}catch(e){if(e instanceof s&&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){A(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(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 s(`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){A(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=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){A(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,ino:e.ino}}catch(e){throw M(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){A(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 M(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*W({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 s(`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 s(`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 M(e,r)}}else throw M(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 M(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,ino:e.ino}}return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,ino:e.ino}}catch(e){throw M(e,t)}}async realpath(e){return B(this.lfs,e=>this.findMount(e)!==null,e)}resolveSymlinks(e){return V(this.lfs,e=>this.findMount(e)!==null,e)}},X=e({FsError:()=>s,FsWatcher:()=>C,MountIndex:()=>u,RestrictedFS:()=>k,VirtualFS:()=>Y,joinPath:()=>o,normalizePath:()=>i,pathSegments:()=>r,resolveVfsBackendFromEnv:()=>q,splitPath:()=>n});export{C as i,Y as n,k as r,X 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"./types-idfTVsM8.js";import{i as c,r as l,t as u}from"./mount-index-BCzDM4LQ.js";import{a as d,i as f,n as p,t as m}from"./mount-table-store-DrF_Ifaz.js";import{n as h,t as g}from"./virtual-device-paths-CS5o4QVz.js";import{i as _,r as v,t as y}from"./sidecar-repair-CIHuOk7H.js";const b=t(`fs-watcher`);let x=0;function S(e,t){return t===`/`||e===t||e.startsWith(t+`/`)}var C=class{registrations=new Map;watch(e,t,n){let r=`fsw-${++x}`;return this.registrations.set(r,{id:r,basePath:e,filter:t,callback:n}),b.debug(`Watch registered`,{id:r,basePath:e}),()=>{this.registrations.delete(r),b.debug(`Watch unregistered`,{id:r})}}notify(e){if(e.length!==0)for(let[,t]of this.registrations){let n=e.filter(e=>S(e.path,t.basePath)&&t.filter(e.path));if(n.length>0)try{t.callback(n)}catch(e){b.error(`Watch callback error`,{id:t.id,error:e instanceof Error?e.message:String(e)})}}}dispose(){this.registrations.clear(),b.debug(`All watchers disposed`)}get size(){return this.registrations.size}};const w=new TextEncoder,T=new TextDecoder(`utf-8`,{fatal:!1});var E=class{entries=new Map;static handles(e){return h(i(e))}has(e){return this.entries.has(i(e))}write(e,t){let n=i(e),r=typeof t==`string`?w.encode(t):new Uint8Array(t),a=Date.now(),o=this.entries.get(n);this.entries.set(n,{bytes:r,mtime:a,ctime:o?.ctime??a})}read(e,t){let n=this.require(e);return(t?.encoding??`utf-8`)===`utf-8`?T.decode(n.bytes):new Uint8Array(n.bytes)}readText(e){return T.decode(this.require(e).bytes)}stat(e){let t=this.require(e);return{type:`file`,size:t.bytes.length,mtime:t.mtime,ctime:t.ctime}}remove(e){return this.entries.delete(i(e))}require(e){let t=i(e),n=this.entries.get(t);if(!n)throw new s(`ENOENT`,`no such file or directory`,t);return n}};const D={[g]:{stat:()=>({type:`file`,size:0,mtime:0,ctime:0}),read:e=>(e?.encoding??`utf-8`)===`utf-8`?``:new Uint8Array,readText:()=>``,write:()=>{}}},O=[`/tmp/`];var k=class{ephemeralFds=new E;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,...O]}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,...O].some(e=>t===e.slice(0,-1)||t.startsWith(e))}canWrite(e){return E.handles(e)||this.isWritable(e)}checkWrite(e){if(this.writeEnforcement!==`sudo-delegated`&&!this.isWritable(e))throw new s(`EACCES`,`permission denied`,i(e))}async resolveAndCheckRead(e){try{let t=await this.vfs.realpath(e);if(!this.isAllowedStrict(t))throw new s(`ENOENT`,`no such file or directory`,i(e));return t}catch(t){throw t instanceof s?t:new s(`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 s(`EACCES`,`permission denied`,i(e));return t}catch(t){throw t instanceof s?t:new s(`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 s&&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 s(`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=D[i(e)];if(n)return n.read(t);if(E.handles(e))return this.ephemeralFds.read(e,t);if(!this.isAllowedStrict(e))throw new s(`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=D[i(e)];if(t)return t.stat();if(E.handles(e))return this.ephemeralFds.stat(e);if(!this.isAllowed(e))throw new s(`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=D[i(e)];return t?t.stat():E.handles(e)?this.ephemeralFds.has(e)?this.ephemeralFds.stat(e):null:!this.isAllowedStrict(e)||this.scanPathForSymlinks(e,!0)!==!1?null:this.vfs.statSync(e)}lstatSync(e){let t=D[i(e)];return t?t.stat():E.handles(e)?this.ephemeralFds.has(e)?this.ephemeralFds.stat(e):null:!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){if(E.handles(e)){let t=i(e);if(!this.ephemeralFds.has(t))throw new s(`ENOENT`,`no such file or directory`,t);return t}let t;try{t=await this.vfs.realpath(e)}catch(t){throw t instanceof s?t:new s(`ENOENT`,`no such file or directory`,i(e))}if(!this.isAllowedStrict(t))throw new s(`ENOENT`,`no such file or directory`,i(e));return t}async exists(e){if(D[i(e)])return!0;if(E.handles(e))return this.ephemeralFds.has(e);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=D[i(e)];if(t)return t.readText();if(E.handles(e))return this.ephemeralFds.readText(e);if(!this.isAllowedStrict(e))throw new s(`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=D[i(e)];if(r){r.write(t);return}if(E.handles(e)){this.ephemeralFds.write(e,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 s&&e.code===`EACCES`)throw e}return this.vfs.writeFile(e,t,n)}refuseDescriptorTreeOp(e){if(E.handles(e))throw new s(`EACCES`,`permission denied`,i(e))}async mkdir(e,t){return this.refuseDescriptorTreeOp(e),this.checkWrite(e),await this.checkParentRealpathEscape(e),this.vfs.mkdir(e,t)}async rm(e,t){if(E.handles(e)){if(!this.ephemeralFds.remove(e))throw new s(`ENOENT`,`no such file or directory`,i(e));return}this.checkWrite(e);try{(await this.vfs.lstat(e)).type===`symlink`||await this.resolveAndCheckWrite(e)}catch(e){if(e instanceof s&&e.code===`EACCES`)throw e}return this.vfs.rm(e,t)}async rename(e,t){return this.refuseDescriptorTreeOp(e),this.refuseDescriptorTreeOp(t),this.checkWrite(e),this.checkWrite(t),await this.resolveAndCheckWrite(e),await this.checkParentRealpathEscape(t),this.vfs.rename(e,t)}async copyFile(e,t){if(E.handles(e)){let n=this.ephemeralFds.read(e,{encoding:`binary`});await this.writeFile(t,n);return}if(E.handles(t)){if(!this.isAllowed(e))throw new s(`ENOENT`,`no such file or directory`,i(e));let n=await this.resolveAndCheckRead(e);this.ephemeralFds.write(t,await this.vfs.readFile(n,{encoding:`binary`}));return}if(!this.isAllowed(e))throw new s(`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 s&&e.code===`EACCES`)throw e}return this.vfs.copyFile(n,t)}async symlink(e,t){return this.refuseDescriptorTreeOp(t),this.checkWrite(t),await this.checkParentRealpathEscape(t),this.vfs.symlink(e,t)}async readlink(e){if(!this.isAllowedStrict(e))throw new s(`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 s(`ENOENT`,`no such file or directory`,i(e));return t}async lstat(e){let t=D[i(e)];if(t)return t.stat();if(E.handles(e))return this.ephemeralFds.stat(e);if(!this.isAllowed(e))throw new s(`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 s(`ENOENT`,`no such file or directory`,n)}let c=o===`/`?`/${a}`:`${o}/${a}`;if(!this.isAllowed(c))throw new s(`ENOENT`,`no such file or directory`,n);return this.vfs.lstat(c)}watch(e,t,n){if(!this.isAllowed(e))throw new s(`EACCES`,`permission denied`,i(e));let r=this.vfs.getWatcher();if(!r)throw new s(`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.refuseDescriptorTreeOp(e),this.checkWrite(e),await this.checkParentRealpathEscape(e),this.vfs.mount(e,t,n)}async unmount(e){return this.refuseDescriptorTreeOp(e),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.refuseDescriptorTreeOp(e),this.checkWrite(e),this.vfs.refreshMount(e,t)}async dispose(){await this.vfs.dispose()}};function A(e,t){if(e instanceof s){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 s(e.code,r,t)}throw e}const j=[`ENOENT`,`EEXIST`,`ENOTDIR`,`EISDIR`,`ENOTEMPTY`,`EINVAL`,`EACCES`,`ELOOP`,`EBUSY`,`EFBIG`,`EBADF`,`ENOSYS`,`EIO`];function M(e,t){if(e instanceof s)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 s(`EIO`,`internal overflow, not storage: ${n} — reload the session`,t)}let n=e?.code;if(typeof n==`string`){let r=n;if(j.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 s(r,n||r,t)}}let r=e instanceof Error?e.message:String(e);return r.includes(`ENOENT`)?new s(`ENOENT`,`no such file or directory`,t):r.includes(`EEXIST`)?new s(`EEXIST`,`file already exists`,t):r.includes(`ENOTDIR`)?new s(`ENOTDIR`,`not a directory`,t):r.includes(`EISDIR`)?new s(`EISDIR`,`is a directory`,t):r.includes(`ENOTEMPTY`)?new s(`ENOTEMPTY`,`directory not empty`,t):r.includes(`ELOOP`)?new s(`ELOOP`,`too many levels of symbolic links`,t):new s(`EINVAL`,r,t)}function N(e){return e===void 0?`absent`:(e&61440)==16384?`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}async function L(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 R(e,t,r){let a;try{a=await e.readlink(t)}catch(e){throw M(e,r)}return a.startsWith(`/`)?i(a):i(o(n(t).dir,a))}async function z(e,t,n,r,i,a){let o=t===`/`?`/${n}`:`${t}/${n}`;for(;;){let t=await L(e,o,r,i);if(t===null||!t.isSymbolicLink())return{resolved:o,hops:a};if(++a>10)throw new s(`ELOOP`,`too many symbolic links encountered`,i);o=await R(e,o,i)}}async function B(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 z(e,o,a[t],t===a.length-1,r,s);o=n.resolved,s=n.hops}return o}async function V(e,t,n){return t(n)?n:B(e,t,n)}function H(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 U(e,t){try{return await e(t)}catch{return t}}async function*W(e,t,n,r=0){let a=i(t);if(H(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 U(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*G(e,t,a===`/`?`/${t.name}`:`${a}/${t.name}`,o,r+1)}async function*G(e,t,n,r,i){if(t.type===`file`){yield n;return}if(t.type===`symlink`){yield*K(e,n,r,i);return}yield*W(e,n,r,i)}async function*K(e,t,n,r){try{let i=await e.stat(t);i.type===`file`?yield t:i.type===`directory`&&(yield*W(e,t,n,r))}catch{}}function q(){try{if(typeof globalThis.navigator?.storage?.getDirectory==`function`)return`opfs`}catch{}return`memory`}function J(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 Y=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 u;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-CBELmDjr.js`).then(e=>e.t),import(`./dist-iMxkf8fm.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-CBELmDjr.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 s(`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 m().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=v(e,r,i))}let o=JSON.stringify(_(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=y(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 y(n)(a),s=N(t.index.get(a)?.mode),c=t._handles?.get(a),l=c?.kind===`directory`?`directory`:c?.kind===`file`?`file`:`absent`,u=P(o,s),d=P(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 s(`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-CBELmDjr.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,ino:e.ino}}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,ino:e.ino};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,ino:e.ino}}return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,ino:e.ino}}catch{return null}}async mount(e,t,r){let a=i(e);if(this.mountPoints.has(a))throw new s(`EEXIST`,`mount point is already mounted`,a);try{if((await this.lstat(a)).type!==`directory`)throw new s(`ENOTDIR`,`mount point must be a directory`,a);if((await this.readDir(a)).length>0)throw new s(`ENOTEMPTY`,`mount point must be empty to avoid shadowing existing files`,a)}catch(e){if(!(e instanceof s)||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??l(r?.env??{});this.mountIndex.registerMount(a,t.getHandle(),e)}let c=J(t,a);try{this.mountSyncChannel?.postMessage({type:`mount`,path:a,descriptor:c})}catch{}if(this.watcher?.notify([{type:`modify`,path:a,entryType:`directory`}]),t.kind!==`hostfs`)try{let e={targetPath:a,descriptor:c,createdAt:Date.now()},n=t.kind===`local`?t.getHandle():void 0;await d(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 f(t)}catch{}}async reconstructBackendFromDescriptor(e,t){switch(e.kind){case`local`:{let t=await p(e.idbHandleKey);if(!t)throw Error(`no handle stored for ${e.idbHandleKey}`);return c.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-CY0WMJLG.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-CY0WMJLG.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-CY0WMJLG.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 s(`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 s(`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 s(`ENOENT`,`not a mount point`,n);let a=await r.refresh(t);return r.kind===`local`&&await this.mountIndex.refreshMount(n,l(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 s(`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){A(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 M(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 s(`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){A(e,a)}this.watcher?.notify([{type:n?`modify`:`create`,path:a,entryType:`file`}]),this.mountIndex.notifyWrite(a);return}let c;try{c=await this.resolveSymlinks(a)}catch{c=a}let l=!1;try{await this.lfs.stat(c),l=!0}catch{}let{dir:u}=n(c);await this.withWriteLock(async()=>{this.markSidecarDirty(c),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(c,t)}catch(e){if(u!==`/`&&e instanceof Error&&e.message.includes(`ENOENT`)){await this.mkdirRecursiveUnlocked(u);try{await this.lfs.writeFile(c,t)}catch(e){throw M(e,a)}}else throw M(e,a)}try{await this.lfs.truncate?.(c,e)}catch(e){throw M(e,a)}}),this.watcher?.notify([{type:l?`modify`:`create`,path:c,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){A(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 s(`ENOTDIR`,`not a directory`,r)}catch(e){if(e instanceof s&&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){A(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(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 s(`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){A(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=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){A(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,ino:e.ino}}catch(e){throw M(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){A(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 M(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*W({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 s(`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 s(`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 M(e,r)}}else throw M(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 M(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,ino:e.ino}}return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,ino:e.ino}}catch(e){throw M(e,t)}}async realpath(e){return B(this.lfs,e=>this.findMount(e)!==null,e)}resolveSymlinks(e){return V(this.lfs,e=>this.findMount(e)!==null,e)}},X=e({FsError:()=>s,FsWatcher:()=>C,MountIndex:()=>u,RestrictedFS:()=>k,VirtualFS:()=>Y,joinPath:()=>o,normalizePath:()=>i,pathSegments:()=>r,resolveVfsBackendFromEnv:()=>q,splitPath:()=>n});export{C as i,Y as n,k as r,X as t};
@@ -1,2 +1,2 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/dist-BKQr3WRb.js","assets/rolldown-runtime-Dd_uD5pT.js","assets/safe-buffer-iah92gQe.js","assets/dist-DHO9E-gl.js","assets/sidecar-repair-431vRT2V.js","assets/backend-hostfs-Com-zF5W.js","assets/api-endpoint-GRCyib6X.js","assets/types-idfTVsM8.js","assets/mount-BVsAhg7N.js","assets/preload-helper-Czpn1I53.js","assets/mime-types-k2E6ulyv.js","assets/base64-DJRlyqZu.js","assets/src-CAWTvdAa.js","assets/runtime-env-Dlaokqg1.js","assets/runtime-env-E-i2SW1s.js","assets/mount-table-store-dY2IfQ5S.js","assets/mount-bridge-client-BJeJ5p60.js","assets/port-bridge-client-Cti-DmEY.js","assets/logger-DDBAeTLF.js","assets/proxied-fetch-CFWkfPNA.js","assets/fetch-body-D2PwksUW.js"])))=>i.map(i=>d[i]);
2
- import{t as e}from"./preload-helper-Czpn1I53.js";import{t}from"./logger-DDBAeTLF.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"./types-idfTVsM8.js";import{n as c,t as l}from"./virtual-device-paths-D45tpPP6.js";import{a as u,i as d,n as f,t as p}from"./mount-table-store-dY2IfQ5S.js";import{i as ee,r as te,t as m}from"./sidecar-repair-431vRT2V.js";var h=t(`fs-watcher`),g=0;function _(e,t){return t===`/`||e===t||e.startsWith(t+`/`)}var v=class{registrations=new Map;watch(e,t,n){let r=`fsw-${++g}`;return this.registrations.set(r,{id:r,basePath:e,filter:t,callback:n}),h.debug(`Watch registered`,{id:r,basePath:e}),()=>{this.registrations.delete(r),h.debug(`Watch unregistered`,{id:r})}}notify(e){if(e.length!==0)for(let[,t]of this.registrations){let n=e.filter(e=>_(e.path,t.basePath)&&t.filter(e.path));if(n.length>0)try{t.callback(n)}catch(e){h.error(`Watch callback error`,{id:t.id,error:e instanceof Error?e.message:String(e)})}}}dispose(){this.registrations.clear(),h.debug(`All watchers disposed`)}get size(){return this.registrations.size}},y=t(`mount-index`),ne=400,b=2e6,x=`SLICC_MOUNT_INDEX_MAX_DEPTH`,S=`SLICC_MOUNT_INDEX_MAX_ENTRIES`,C=256,w=class extends Error{cause;constructor(e,t){super(e),this.name=`MountIndexAbortError`,this.cause=t}};function T(e){let t=e.map(([e,t])=>`${e}\u0000${t.kind}`).sort(),n=t.length>C?t.slice(0,C):t;return`${t.length}\u0001${n.join(``)}`}async function E(e,t){let n=e.isSameEntry;if(typeof n!=`function`)return!1;try{return await n.call(e,t)}catch{return!1}}function D(e,t){return e instanceof Map?e.get(t):e[t]}function O(e){let t=e.trim();if(t===``)return;let n=Number(t);if(!(!Number.isInteger(n)||n<=0))return n}function k(e,t,n){let r=D(e,t);if(r===void 0||r.trim()===``)return n;let i=O(r);return i===void 0?(y.warn(`Ignoring invalid ${t}; expected a positive integer, using default`,{value:r,fallback:n}),n):i}function A(e){return{maxDepth:k(e,x,ne),maxEntries:k(e,S,b)}}var j=class{mounts=new Map;listeners=new Set;registerMount(e,t,n=A({})){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,y.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 w?r.cause:`indexing-error`;t.state={status:`error`,indexed:0,error:i,abortCause:a},y.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 w(`mount indexing aborted: directory nesting exceeded ${t.limits.maxDepth} levels`,`depth-exceeded`);if(t.directories.size+t.files.size>=t.limits.maxEntries)throw new w(`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 w(`mount indexing aborted: exceeded ${n.limits.maxEntries} entries`,`entries-exceeded`);i.push(e)}return i}async confirmNoCycle(e,t,n,r){let i=T(n),a=r.get(i);if(a){for(let n of a)if(await E(n.handle,t))throw new w(`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)))}}},M=new TextEncoder,N=new TextDecoder(`utf-8`,{fatal:!1}),P=class{entries=new Map;static handles(e){return c(i(e))}has(e){return this.entries.has(i(e))}write(e,t){let n=i(e),r=typeof t==`string`?M.encode(t):new Uint8Array(t),a=Date.now(),o=this.entries.get(n);this.entries.set(n,{bytes:r,mtime:a,ctime:o?.ctime??a})}read(e,t){let n=this.require(e);return(t?.encoding??`utf-8`)===`utf-8`?N.decode(n.bytes):new Uint8Array(n.bytes)}readText(e){return N.decode(this.require(e).bytes)}stat(e){let t=this.require(e);return{type:`file`,size:t.bytes.length,mtime:t.mtime,ctime:t.ctime}}remove(e){return this.entries.delete(i(e))}require(e){let t=i(e),n=this.entries.get(t);if(!n)throw new s(`ENOENT`,`no such file or directory`,t);return n}},F={[l]:{stat:()=>({type:`file`,size:0,mtime:0,ctime:0}),read:e=>(e?.encoding??`utf-8`)===`utf-8`?``:new Uint8Array,readText:()=>``,write:()=>{}}},I=[`/tmp/`],L=class{ephemeralFds=new P;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,...I]}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,...I].some(e=>t===e.slice(0,-1)||t.startsWith(e))}canWrite(e){return P.handles(e)||this.isWritable(e)}checkWrite(e){if(this.writeEnforcement!==`sudo-delegated`&&!this.isWritable(e))throw new s(`EACCES`,`permission denied`,i(e))}async resolveAndCheckRead(e){try{let t=await this.vfs.realpath(e);if(!this.isAllowedStrict(t))throw new s(`ENOENT`,`no such file or directory`,i(e));return t}catch(t){throw t instanceof s?t:new s(`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 s(`EACCES`,`permission denied`,i(e));return t}catch(t){throw t instanceof s?t:new s(`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 s&&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 s(`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=F[i(e)];if(n)return n.read(t);if(P.handles(e))return this.ephemeralFds.read(e,t);if(!this.isAllowedStrict(e))throw new s(`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=F[i(e)];if(t)return t.stat();if(P.handles(e))return this.ephemeralFds.stat(e);if(!this.isAllowed(e))throw new s(`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=F[i(e)];return t?t.stat():P.handles(e)?this.ephemeralFds.has(e)?this.ephemeralFds.stat(e):null:!this.isAllowedStrict(e)||this.scanPathForSymlinks(e,!0)!==!1?null:this.vfs.statSync(e)}lstatSync(e){let t=F[i(e)];return t?t.stat():P.handles(e)?this.ephemeralFds.has(e)?this.ephemeralFds.stat(e):null:!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){if(P.handles(e)){let t=i(e);if(!this.ephemeralFds.has(t))throw new s(`ENOENT`,`no such file or directory`,t);return t}let t;try{t=await this.vfs.realpath(e)}catch(t){throw t instanceof s?t:new s(`ENOENT`,`no such file or directory`,i(e))}if(!this.isAllowedStrict(t))throw new s(`ENOENT`,`no such file or directory`,i(e));return t}async exists(e){if(F[i(e)])return!0;if(P.handles(e))return this.ephemeralFds.has(e);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=F[i(e)];if(t)return t.readText();if(P.handles(e))return this.ephemeralFds.readText(e);if(!this.isAllowedStrict(e))throw new s(`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=F[i(e)];if(r){r.write(t);return}if(P.handles(e)){this.ephemeralFds.write(e,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 s&&e.code===`EACCES`)throw e}return this.vfs.writeFile(e,t,n)}refuseDescriptorTreeOp(e){if(P.handles(e))throw new s(`EACCES`,`permission denied`,i(e))}async mkdir(e,t){return this.refuseDescriptorTreeOp(e),this.checkWrite(e),await this.checkParentRealpathEscape(e),this.vfs.mkdir(e,t)}async rm(e,t){if(P.handles(e)){if(!this.ephemeralFds.remove(e))throw new s(`ENOENT`,`no such file or directory`,i(e));return}this.checkWrite(e);try{(await this.vfs.lstat(e)).type===`symlink`||await this.resolveAndCheckWrite(e)}catch(e){if(e instanceof s&&e.code===`EACCES`)throw e}return this.vfs.rm(e,t)}async rename(e,t){return this.refuseDescriptorTreeOp(e),this.refuseDescriptorTreeOp(t),this.checkWrite(e),this.checkWrite(t),await this.resolveAndCheckWrite(e),await this.checkParentRealpathEscape(t),this.vfs.rename(e,t)}async copyFile(e,t){if(P.handles(e)){let n=this.ephemeralFds.read(e,{encoding:`binary`});await this.writeFile(t,n);return}if(P.handles(t)){if(!this.isAllowed(e))throw new s(`ENOENT`,`no such file or directory`,i(e));let n=await this.resolveAndCheckRead(e);this.ephemeralFds.write(t,await this.vfs.readFile(n,{encoding:`binary`}));return}if(!this.isAllowed(e))throw new s(`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 s&&e.code===`EACCES`)throw e}return this.vfs.copyFile(n,t)}async symlink(e,t){return this.refuseDescriptorTreeOp(t),this.checkWrite(t),await this.checkParentRealpathEscape(t),this.vfs.symlink(e,t)}async readlink(e){if(!this.isAllowedStrict(e))throw new s(`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 s(`ENOENT`,`no such file or directory`,i(e));return t}async lstat(e){let t=F[i(e)];if(t)return t.stat();if(P.handles(e))return this.ephemeralFds.stat(e);if(!this.isAllowed(e))throw new s(`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 s(`ENOENT`,`no such file or directory`,n)}let c=o===`/`?`/${a}`:`${o}/${a}`;if(!this.isAllowed(c))throw new s(`ENOENT`,`no such file or directory`,n);return this.vfs.lstat(c)}watch(e,t,n){if(!this.isAllowed(e))throw new s(`EACCES`,`permission denied`,i(e));let r=this.vfs.getWatcher();if(!r)throw new s(`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.refuseDescriptorTreeOp(e),this.checkWrite(e),await this.checkParentRealpathEscape(e),this.vfs.mount(e,t,n)}async unmount(e){return this.refuseDescriptorTreeOp(e),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.refuseDescriptorTreeOp(e),this.checkWrite(e),this.vfs.refreshMount(e,t)}async dispose(){await this.vfs.dispose()}};function R(e,t){if(e instanceof s){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 s(e.code,r,t)}throw e}var z=[`ENOENT`,`EEXIST`,`ENOTDIR`,`EISDIR`,`ENOTEMPTY`,`EINVAL`,`EACCES`,`ELOOP`,`EBUSY`,`EFBIG`,`EBADF`,`ENOSYS`,`EIO`];function B(e,t){if(e instanceof s)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 s(`EIO`,`internal overflow, not storage: ${n} — reload the session`,t)}let n=e?.code;if(typeof n==`string`){let r=n;if(z.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 s(r,n||r,t)}}let r=e instanceof Error?e.message:String(e);return r.includes(`ENOENT`)?new s(`ENOENT`,`no such file or directory`,t):r.includes(`EEXIST`)?new s(`EEXIST`,`file already exists`,t):r.includes(`ENOTDIR`)?new s(`ENOTDIR`,`not a directory`,t):r.includes(`EISDIR`)?new s(`EISDIR`,`is a directory`,t):r.includes(`ENOTEMPTY`)?new s(`ENOTEMPTY`,`directory not empty`,t):r.includes(`ELOOP`)?new s(`ELOOP`,`too many levels of symbolic links`,t):new s(`EINVAL`,r,t)}var V=61440,H=16384;function U(e){return e===void 0?`absent`:(e&V)===H?`directory`:`file`}function W(e,t){return t===`absent`?!1:e.kind===`missing`||e.kind!==t}function G(e){let t=e?.mode;return typeof t==`number`?t:void 0}function K(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=U(G(r));o!==U(G(i))&&a.push({path:n,ownIsDirectory:o===`directory`})}return a}var q=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)}getHandle(){return this.handle}assertOpen(e){if(this.closed)throw new s(`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 s(`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 s)return e;if(e instanceof DOMException){if(e.name===`NotFoundError`)return new s(`ENOENT`,`no such file or directory`,t);if(e.name===`TypeMismatchError`)return new s(`ENOTDIR`,`not a directory`,t);if(e.name===`NotAllowedError`)return new s(`EACCES`,`permission denied`,t);if(e.name===`InvalidModificationError`)return new s(`ENOTEMPTY`,`directory not empty`,t)}if(e instanceof Error){if(e.name===`NotFound`||e.name===`NotFoundError`)return new s(`ENOENT`,`no such file or directory`,t);if(e.name===`TypeMismatch`||e.name===`TypeMismatchError`)return new s(`ENOTDIR`,`not a directory`,t);if(e.name===`InvalidModification`||e.name===`InvalidModificationError`)return new s(`ENOTEMPTY`,`directory not empty`,t)}return new s(`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 s(`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}};async function J(e,t,n,r){try{return await e.lstat(t)}catch(e){let t=B(e,r);if(t.code===`ENOENT`&&n)return null;throw t}}async function Y(e,t,r){let a;try{a=await e.readlink(t)}catch(e){throw B(e,r)}return a.startsWith(`/`)?i(a):i(o(n(t).dir,a))}async function X(e,t,n,r,i,a){let o=t===`/`?`/${n}`:`${t}/${n}`;for(;;){let t=await J(e,o,r,i);if(t===null||!t.isSymbolicLink())return{resolved:o,hops:a};if(++a>10)throw new s(`ELOOP`,`too many symbolic links encountered`,i);o=await Y(e,o,i)}}async function Z(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 X(e,o,a[t],t===a.length-1,r,s);o=n.resolved,s=n.hops}return o}async function re(e,t,n){return t(n)?n:Z(e,t,n)}function ie(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 ae(e,t){try{return await e(t)}catch{return t}}async function*Q(e,t,n,r=0){let a=i(t);if(ie(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 ae(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*oe(e,t,a===`/`?`/${t.name}`:`${a}/${t.name}`,o,r+1)}async function*oe(e,t,n,r,i){if(t.type===`file`){yield n;return}if(t.type===`symlink`){yield*se(e,n,r,i);return}yield*Q(e,n,r,i)}async function*se(e,t,n,r){try{let i=await e.stat(t);i.type===`file`?yield t:i.type===`directory`&&(yield*Q(e,t,n,r))}catch{}}function $(){try{if(typeof globalThis.navigator?.storage?.getDirectory==`function`)return`opfs`}catch{}return`memory`}function ce(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 le=class t{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 j;static writeChains=new Map;onRepairProgress;constructor(e,n,r,i,a){if(this.dbName=e,this.onRepairProgress=a,this.backend=r===`opfs`?`opfs`:`memory`,this.lfs=this.makeDeferredLfs(),this.lfsSync=this.makeDeferredLfsSync(),this._ready=this.backend===`opfs`?t.initOpfsBackend(this,i,n===!0):t.initMemoryBackend(this,e,n===!0),this._ready.then(()=>{this._readyResolved=!0},()=>{}),typeof BroadcastChannel<`u`)try{this.mountSyncChannel=new BroadcastChannel(`vfs-mount-sync:${e}`),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 t.acquireOpfsHandle(n.dbName,i);await t.seedOpfsMetadataSidecarIfMissing(a);let[o,{WebAccess:s}]=await Promise.all([e(()=>import(`./dist-BKQr3WRb.js`).then(e=>e.t),__vite__mapDeps([0,1,2])),e(()=>import(`./dist-DHO9E-gl.js`),__vite__mapDeps([3,0,1,2]))]);await t.ensureRootMount(o);let c=`/__opfs__/${n.dbName}`,l=t.opfsBackends.get(n.dbName);if(l&&i){try{o.umount(c)}catch{}t.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 e(async()=>{let{resolveWithSidecarRepair:e,repairOpfsMetadataSidecar:t}=await import(`./sidecar-repair-431vRT2V.js`).then(e=>e.n);return{resolveWithSidecarRepair:e,repairOpfsMetadataSidecar:t}},__vite__mapDeps([4,1]));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}},t.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 e(()=>import(`./dist-BKQr3WRb.js`).then(e=>e.t),__vite__mapDeps([0,1,2]));await t.ensureRootMount(a);let o=`/__zenfs__/${r}`,s=t.memoryBackends.get(r);if(s&&i){try{a.umount(o)}catch{}t.memoryBackends.delete(r),s=void 0}s||(s={store:a.InMemory.create({label:r}),refs:0},t.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(e){return t.rootMountReady===null&&(t.rootMountReady=(async()=>{await e.configureSingle({backend:e.InMemory,label:`__vfs_root__`})})()),t.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 s(`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(e){return new t(e)}static async create(e){let n=e?.dbName??`browser-fs`,r=e?.wipe===!0,i=e?.backend??$(),a=new t(n,r,i,void 0,e?.onRepairProgress);return await a._ready,r&&await p().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 e=this.opfsBackendFs,n=this.opfsHandle;if(!e||!n)return;let r=e.index.toJSON(),i=t.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=te(e,r,i))}let o=JSON.stringify(ee(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=K(e,t,n.paths,n.prefixes);if(i.length===0)return;let a=m(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(e,r=`path`){if(this.backend!==`opfs`)return;let a=t.opfsBackends.get(this.dbName)?.sidecarDirty;if(!a)return;let o=i(e);(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 m(n)(a),s=U(t.index.get(a)?.mode),c=t._handles?.get(a),l=c?.kind===`directory`?`directory`:c?.kind===`file`?`file`:`absent`,u=W(o,s),d=W(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 s(`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`?t.opfsBackends:t.memoryBackends,r=n.get(this.dbName);if(r&&(--r.refs,r.refs<=0)){n.delete(this.dbName);try{(await e(()=>import(`./dist-BKQr3WRb.js`).then(e=>e.t),__vite__mapDeps([0,1,2]))).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,ino:e.ino}}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,ino:e.ino};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,ino:e.ino}}return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,ino:e.ino}}catch{return null}}async mount(e,t,r){let a=i(e);if(this.mountPoints.has(a))throw new s(`EEXIST`,`mount point is already mounted`,a);try{if((await this.lstat(a)).type!==`directory`)throw new s(`ENOTDIR`,`mount point must be a directory`,a);if((await this.readDir(a)).length>0)throw new s(`ENOTEMPTY`,`mount point must be empty to avoid shadowing existing files`,a)}catch(e){if(!(e instanceof s)||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??A(r?.env??{});this.mountIndex.registerMount(a,t.getHandle(),e)}let c=ce(t,a);try{this.mountSyncChannel?.postMessage({type:`mount`,path:a,descriptor:c})}catch{}if(this.watcher?.notify([{type:`modify`,path:a,entryType:`directory`}]),t.kind!==`hostfs`)try{let e={targetPath:a,descriptor:c,createdAt:Date.now()},n=t.kind===`local`?t.getHandle():void 0;await u(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 d(t)}catch{}}async reconstructBackendFromDescriptor(t,n){switch(t.kind){case`local`:{let e=await f(t.idbHandleKey);if(!e)throw Error(`no handle stored for ${t.idbHandleKey}`);return q.fromHandle(e,{mountId:t.mountId})}case`hostfs`:{let{HostFsMountBackend:r}=await e(async()=>{let{HostFsMountBackend:e}=await import(`./backend-hostfs-Com-zF5W.js`);return{HostFsMountBackend:e}},__vite__mapDeps([5,6,7]));return new r({targetPath:n,hostPath:t.hostPath,mountId:t.mountId})}case`s3`:{let{S3MountBackend:n,RemoteMountCache:r,makeSignedFetchS3:i}=await e(async()=>{let{S3MountBackend:e,RemoteMountCache:t,makeSignedFetchS3:n}=await import(`./mount-BVsAhg7N.js`);return{S3MountBackend:e,RemoteMountCache:t,makeSignedFetchS3:n}},__vite__mapDeps([8,9,10,11,12,13,6,14,7,15,1,16,17,18,19,20])),a=new r({mountId:t.mountId,ttlMs:3e4});return new n({source:t.source,profile:t.profile,cache:a,mountId:t.mountId,signedFetch:i(t.profile)})}case`da`:{let{DaMountBackend:n,RemoteMountCache:r,makeSignedFetchDa:i}=await e(async()=>{let{DaMountBackend:e,RemoteMountCache:t,makeSignedFetchDa:n}=await import(`./mount-BVsAhg7N.js`);return{DaMountBackend:e,RemoteMountCache:t,makeSignedFetchDa:n}},__vite__mapDeps([8,9,10,11,12,13,6,14,7,15,1,16,17,18,19,20])),a=new r({mountId:t.mountId,ttlMs:3e4});return new n({source:t.source,profile:t.profile,cache:a,mountId:t.mountId,signedFetch:i()})}case`aem`:{let{AemMountBackend:n,RemoteMountCache:r,makeSignedFetchDa:i}=await e(async()=>{let{AemMountBackend:e,RemoteMountCache:t,makeSignedFetchDa:n}=await import(`./mount-BVsAhg7N.js`);return{AemMountBackend:e,RemoteMountCache:t,makeSignedFetchDa:n}},__vite__mapDeps([8,9,10,11,12,13,6,14,7,15,1,16,17,18,19,20])),a=new r({mountId:t.mountId,ttlMs:3e4});return new n({source:t.source,profile:t.profile,cache:a,mountId:t.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 r=i(e);if(this.mountPoints.has(r))throw new s(`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 s(`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 s(`ENOENT`,`not a mount point`,n);let a=await r.refresh(t);return r.kind===`local`&&await this.mountIndex.refreshMount(n,A(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 s(`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){R(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 B(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 s(`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){R(e,a)}this.watcher?.notify([{type:n?`modify`:`create`,path:a,entryType:`file`}]),this.mountIndex.notifyWrite(a);return}let c;try{c=await this.resolveSymlinks(a)}catch{c=a}let l=!1;try{await this.lfs.stat(c),l=!0}catch{}let{dir:u}=n(c);await this.withWriteLock(async()=>{this.markSidecarDirty(c),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(c,t)}catch(e){if(u!==`/`&&e instanceof Error&&e.message.includes(`ENOENT`)){await this.mkdirRecursiveUnlocked(u);try{await this.lfs.writeFile(c,t)}catch(e){throw B(e,a)}}else throw B(e,a)}try{await this.lfs.truncate?.(c,e)}catch(e){throw B(e,a)}}),this.watcher?.notify([{type:l?`modify`:`create`,path:c,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){R(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 B(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(e){let n=this.dbName,r,i=new Promise(e=>{r=e}),a=t.writeChains.get(n)??Promise.resolve();t.writeChains.set(n,i),await a;try{let t=globalThis.navigator?.locks;return this.backend!==`opfs`||typeof t?.request!=`function`?await e():await t.request(`slicc-vfs:${n}`,()=>e())}finally{r(),t.writeChains.get(n)===i&&t.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 B(e,r);try{let e=await this.lfs.lstat(r);if(!e.isDirectory()&&!e.isSymbolicLink())throw new s(`ENOTDIR`,`not a directory`,r)}catch(e){if(e instanceof s&&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){R(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 B(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 s(`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){R(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 B(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){R(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,ino:e.ino}}catch(e){throw B(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){R(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 B(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*Q({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 s(`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 s(`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 B(e,r)}}else throw B(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 B(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,ino:e.ino}}return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,ino:e.ino}}catch(e){throw B(e,t)}}async realpath(e){return Z(this.lfs,e=>this.findMount(e)!==null,e)}resolveSymlinks(e){return re(this.lfs,e=>this.findMount(e)!==null,e)}};export{s as FsError,v as FsWatcher,j as MountIndex,L as RestrictedFS,le as VirtualFS,o as joinPath,i as normalizePath,r as pathSegments,$ as resolveVfsBackendFromEnv,n as splitPath,q as t};
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/dist-BKQr3WRb.js","assets/rolldown-runtime-Dd_uD5pT.js","assets/safe-buffer-iah92gQe.js","assets/dist-DHO9E-gl.js","assets/sidecar-repair-431vRT2V.js","assets/backend-hostfs-Com-zF5W.js","assets/api-endpoint-GRCyib6X.js","assets/types-idfTVsM8.js","assets/mount-4B-1d5oh.js","assets/preload-helper-Czpn1I53.js","assets/mime-types-k2E6ulyv.js","assets/base64-DJRlyqZu.js","assets/src-CAWTvdAa.js","assets/runtime-env-Dlaokqg1.js","assets/runtime-env-E-i2SW1s.js","assets/mount-table-store-dY2IfQ5S.js","assets/mount-bridge-client-BJeJ5p60.js","assets/port-bridge-client-Cti-DmEY.js","assets/logger-DDBAeTLF.js","assets/proxied-fetch-CFWkfPNA.js","assets/fetch-body-D2PwksUW.js"])))=>i.map(i=>d[i]);
2
+ import{t as e}from"./preload-helper-Czpn1I53.js";import{t}from"./logger-DDBAeTLF.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"./types-idfTVsM8.js";import{n as c,t as l}from"./virtual-device-paths-D45tpPP6.js";import{a as u,i as d,n as f,t as p}from"./mount-table-store-dY2IfQ5S.js";import{i as ee,r as te,t as m}from"./sidecar-repair-431vRT2V.js";var h=t(`fs-watcher`),g=0;function _(e,t){return t===`/`||e===t||e.startsWith(t+`/`)}var v=class{registrations=new Map;watch(e,t,n){let r=`fsw-${++g}`;return this.registrations.set(r,{id:r,basePath:e,filter:t,callback:n}),h.debug(`Watch registered`,{id:r,basePath:e}),()=>{this.registrations.delete(r),h.debug(`Watch unregistered`,{id:r})}}notify(e){if(e.length!==0)for(let[,t]of this.registrations){let n=e.filter(e=>_(e.path,t.basePath)&&t.filter(e.path));if(n.length>0)try{t.callback(n)}catch(e){h.error(`Watch callback error`,{id:t.id,error:e instanceof Error?e.message:String(e)})}}}dispose(){this.registrations.clear(),h.debug(`All watchers disposed`)}get size(){return this.registrations.size}},y=t(`mount-index`),ne=400,b=2e6,x=`SLICC_MOUNT_INDEX_MAX_DEPTH`,S=`SLICC_MOUNT_INDEX_MAX_ENTRIES`,C=256,w=class extends Error{cause;constructor(e,t){super(e),this.name=`MountIndexAbortError`,this.cause=t}};function T(e){let t=e.map(([e,t])=>`${e}\u0000${t.kind}`).sort(),n=t.length>C?t.slice(0,C):t;return`${t.length}\u0001${n.join(``)}`}async function E(e,t){let n=e.isSameEntry;if(typeof n!=`function`)return!1;try{return await n.call(e,t)}catch{return!1}}function D(e,t){return e instanceof Map?e.get(t):e[t]}function O(e){let t=e.trim();if(t===``)return;let n=Number(t);if(!(!Number.isInteger(n)||n<=0))return n}function k(e,t,n){let r=D(e,t);if(r===void 0||r.trim()===``)return n;let i=O(r);return i===void 0?(y.warn(`Ignoring invalid ${t}; expected a positive integer, using default`,{value:r,fallback:n}),n):i}function A(e){return{maxDepth:k(e,x,ne),maxEntries:k(e,S,b)}}var j=class{mounts=new Map;listeners=new Set;registerMount(e,t,n=A({})){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,y.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 w?r.cause:`indexing-error`;t.state={status:`error`,indexed:0,error:i,abortCause:a},y.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 w(`mount indexing aborted: directory nesting exceeded ${t.limits.maxDepth} levels`,`depth-exceeded`);if(t.directories.size+t.files.size>=t.limits.maxEntries)throw new w(`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 w(`mount indexing aborted: exceeded ${n.limits.maxEntries} entries`,`entries-exceeded`);i.push(e)}return i}async confirmNoCycle(e,t,n,r){let i=T(n),a=r.get(i);if(a){for(let n of a)if(await E(n.handle,t))throw new w(`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)))}}},M=new TextEncoder,N=new TextDecoder(`utf-8`,{fatal:!1}),P=class{entries=new Map;static handles(e){return c(i(e))}has(e){return this.entries.has(i(e))}write(e,t){let n=i(e),r=typeof t==`string`?M.encode(t):new Uint8Array(t),a=Date.now(),o=this.entries.get(n);this.entries.set(n,{bytes:r,mtime:a,ctime:o?.ctime??a})}read(e,t){let n=this.require(e);return(t?.encoding??`utf-8`)===`utf-8`?N.decode(n.bytes):new Uint8Array(n.bytes)}readText(e){return N.decode(this.require(e).bytes)}stat(e){let t=this.require(e);return{type:`file`,size:t.bytes.length,mtime:t.mtime,ctime:t.ctime}}remove(e){return this.entries.delete(i(e))}require(e){let t=i(e),n=this.entries.get(t);if(!n)throw new s(`ENOENT`,`no such file or directory`,t);return n}},F={[l]:{stat:()=>({type:`file`,size:0,mtime:0,ctime:0}),read:e=>(e?.encoding??`utf-8`)===`utf-8`?``:new Uint8Array,readText:()=>``,write:()=>{}}},I=[`/tmp/`],L=class{ephemeralFds=new P;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,...I]}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,...I].some(e=>t===e.slice(0,-1)||t.startsWith(e))}canWrite(e){return P.handles(e)||this.isWritable(e)}checkWrite(e){if(this.writeEnforcement!==`sudo-delegated`&&!this.isWritable(e))throw new s(`EACCES`,`permission denied`,i(e))}async resolveAndCheckRead(e){try{let t=await this.vfs.realpath(e);if(!this.isAllowedStrict(t))throw new s(`ENOENT`,`no such file or directory`,i(e));return t}catch(t){throw t instanceof s?t:new s(`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 s(`EACCES`,`permission denied`,i(e));return t}catch(t){throw t instanceof s?t:new s(`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 s&&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 s(`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=F[i(e)];if(n)return n.read(t);if(P.handles(e))return this.ephemeralFds.read(e,t);if(!this.isAllowedStrict(e))throw new s(`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=F[i(e)];if(t)return t.stat();if(P.handles(e))return this.ephemeralFds.stat(e);if(!this.isAllowed(e))throw new s(`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=F[i(e)];return t?t.stat():P.handles(e)?this.ephemeralFds.has(e)?this.ephemeralFds.stat(e):null:!this.isAllowedStrict(e)||this.scanPathForSymlinks(e,!0)!==!1?null:this.vfs.statSync(e)}lstatSync(e){let t=F[i(e)];return t?t.stat():P.handles(e)?this.ephemeralFds.has(e)?this.ephemeralFds.stat(e):null:!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){if(P.handles(e)){let t=i(e);if(!this.ephemeralFds.has(t))throw new s(`ENOENT`,`no such file or directory`,t);return t}let t;try{t=await this.vfs.realpath(e)}catch(t){throw t instanceof s?t:new s(`ENOENT`,`no such file or directory`,i(e))}if(!this.isAllowedStrict(t))throw new s(`ENOENT`,`no such file or directory`,i(e));return t}async exists(e){if(F[i(e)])return!0;if(P.handles(e))return this.ephemeralFds.has(e);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=F[i(e)];if(t)return t.readText();if(P.handles(e))return this.ephemeralFds.readText(e);if(!this.isAllowedStrict(e))throw new s(`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=F[i(e)];if(r){r.write(t);return}if(P.handles(e)){this.ephemeralFds.write(e,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 s&&e.code===`EACCES`)throw e}return this.vfs.writeFile(e,t,n)}refuseDescriptorTreeOp(e){if(P.handles(e))throw new s(`EACCES`,`permission denied`,i(e))}async mkdir(e,t){return this.refuseDescriptorTreeOp(e),this.checkWrite(e),await this.checkParentRealpathEscape(e),this.vfs.mkdir(e,t)}async rm(e,t){if(P.handles(e)){if(!this.ephemeralFds.remove(e))throw new s(`ENOENT`,`no such file or directory`,i(e));return}this.checkWrite(e);try{(await this.vfs.lstat(e)).type===`symlink`||await this.resolveAndCheckWrite(e)}catch(e){if(e instanceof s&&e.code===`EACCES`)throw e}return this.vfs.rm(e,t)}async rename(e,t){return this.refuseDescriptorTreeOp(e),this.refuseDescriptorTreeOp(t),this.checkWrite(e),this.checkWrite(t),await this.resolveAndCheckWrite(e),await this.checkParentRealpathEscape(t),this.vfs.rename(e,t)}async copyFile(e,t){if(P.handles(e)){let n=this.ephemeralFds.read(e,{encoding:`binary`});await this.writeFile(t,n);return}if(P.handles(t)){if(!this.isAllowed(e))throw new s(`ENOENT`,`no such file or directory`,i(e));let n=await this.resolveAndCheckRead(e);this.ephemeralFds.write(t,await this.vfs.readFile(n,{encoding:`binary`}));return}if(!this.isAllowed(e))throw new s(`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 s&&e.code===`EACCES`)throw e}return this.vfs.copyFile(n,t)}async symlink(e,t){return this.refuseDescriptorTreeOp(t),this.checkWrite(t),await this.checkParentRealpathEscape(t),this.vfs.symlink(e,t)}async readlink(e){if(!this.isAllowedStrict(e))throw new s(`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 s(`ENOENT`,`no such file or directory`,i(e));return t}async lstat(e){let t=F[i(e)];if(t)return t.stat();if(P.handles(e))return this.ephemeralFds.stat(e);if(!this.isAllowed(e))throw new s(`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 s(`ENOENT`,`no such file or directory`,n)}let c=o===`/`?`/${a}`:`${o}/${a}`;if(!this.isAllowed(c))throw new s(`ENOENT`,`no such file or directory`,n);return this.vfs.lstat(c)}watch(e,t,n){if(!this.isAllowed(e))throw new s(`EACCES`,`permission denied`,i(e));let r=this.vfs.getWatcher();if(!r)throw new s(`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.refuseDescriptorTreeOp(e),this.checkWrite(e),await this.checkParentRealpathEscape(e),this.vfs.mount(e,t,n)}async unmount(e){return this.refuseDescriptorTreeOp(e),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.refuseDescriptorTreeOp(e),this.checkWrite(e),this.vfs.refreshMount(e,t)}async dispose(){await this.vfs.dispose()}};function R(e,t){if(e instanceof s){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 s(e.code,r,t)}throw e}var z=[`ENOENT`,`EEXIST`,`ENOTDIR`,`EISDIR`,`ENOTEMPTY`,`EINVAL`,`EACCES`,`ELOOP`,`EBUSY`,`EFBIG`,`EBADF`,`ENOSYS`,`EIO`];function B(e,t){if(e instanceof s)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 s(`EIO`,`internal overflow, not storage: ${n} — reload the session`,t)}let n=e?.code;if(typeof n==`string`){let r=n;if(z.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 s(r,n||r,t)}}let r=e instanceof Error?e.message:String(e);return r.includes(`ENOENT`)?new s(`ENOENT`,`no such file or directory`,t):r.includes(`EEXIST`)?new s(`EEXIST`,`file already exists`,t):r.includes(`ENOTDIR`)?new s(`ENOTDIR`,`not a directory`,t):r.includes(`EISDIR`)?new s(`EISDIR`,`is a directory`,t):r.includes(`ENOTEMPTY`)?new s(`ENOTEMPTY`,`directory not empty`,t):r.includes(`ELOOP`)?new s(`ELOOP`,`too many levels of symbolic links`,t):new s(`EINVAL`,r,t)}var V=61440,H=16384;function U(e){return e===void 0?`absent`:(e&V)===H?`directory`:`file`}function W(e,t){return t===`absent`?!1:e.kind===`missing`||e.kind!==t}function G(e){let t=e?.mode;return typeof t==`number`?t:void 0}function K(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=U(G(r));o!==U(G(i))&&a.push({path:n,ownIsDirectory:o===`directory`})}return a}var q=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)}getHandle(){return this.handle}assertOpen(e){if(this.closed)throw new s(`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 s(`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 s)return e;if(e instanceof DOMException){if(e.name===`NotFoundError`)return new s(`ENOENT`,`no such file or directory`,t);if(e.name===`TypeMismatchError`)return new s(`ENOTDIR`,`not a directory`,t);if(e.name===`NotAllowedError`)return new s(`EACCES`,`permission denied`,t);if(e.name===`InvalidModificationError`)return new s(`ENOTEMPTY`,`directory not empty`,t)}if(e instanceof Error){if(e.name===`NotFound`||e.name===`NotFoundError`)return new s(`ENOENT`,`no such file or directory`,t);if(e.name===`TypeMismatch`||e.name===`TypeMismatchError`)return new s(`ENOTDIR`,`not a directory`,t);if(e.name===`InvalidModification`||e.name===`InvalidModificationError`)return new s(`ENOTEMPTY`,`directory not empty`,t)}return new s(`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 s(`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}};async function J(e,t,n,r){try{return await e.lstat(t)}catch(e){let t=B(e,r);if(t.code===`ENOENT`&&n)return null;throw t}}async function Y(e,t,r){let a;try{a=await e.readlink(t)}catch(e){throw B(e,r)}return a.startsWith(`/`)?i(a):i(o(n(t).dir,a))}async function X(e,t,n,r,i,a){let o=t===`/`?`/${n}`:`${t}/${n}`;for(;;){let t=await J(e,o,r,i);if(t===null||!t.isSymbolicLink())return{resolved:o,hops:a};if(++a>10)throw new s(`ELOOP`,`too many symbolic links encountered`,i);o=await Y(e,o,i)}}async function Z(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 X(e,o,a[t],t===a.length-1,r,s);o=n.resolved,s=n.hops}return o}async function re(e,t,n){return t(n)?n:Z(e,t,n)}function ie(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 ae(e,t){try{return await e(t)}catch{return t}}async function*Q(e,t,n,r=0){let a=i(t);if(ie(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 ae(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*oe(e,t,a===`/`?`/${t.name}`:`${a}/${t.name}`,o,r+1)}async function*oe(e,t,n,r,i){if(t.type===`file`){yield n;return}if(t.type===`symlink`){yield*se(e,n,r,i);return}yield*Q(e,n,r,i)}async function*se(e,t,n,r){try{let i=await e.stat(t);i.type===`file`?yield t:i.type===`directory`&&(yield*Q(e,t,n,r))}catch{}}function $(){try{if(typeof globalThis.navigator?.storage?.getDirectory==`function`)return`opfs`}catch{}return`memory`}function ce(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 le=class t{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 j;static writeChains=new Map;onRepairProgress;constructor(e,n,r,i,a){if(this.dbName=e,this.onRepairProgress=a,this.backend=r===`opfs`?`opfs`:`memory`,this.lfs=this.makeDeferredLfs(),this.lfsSync=this.makeDeferredLfsSync(),this._ready=this.backend===`opfs`?t.initOpfsBackend(this,i,n===!0):t.initMemoryBackend(this,e,n===!0),this._ready.then(()=>{this._readyResolved=!0},()=>{}),typeof BroadcastChannel<`u`)try{this.mountSyncChannel=new BroadcastChannel(`vfs-mount-sync:${e}`),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 t.acquireOpfsHandle(n.dbName,i);await t.seedOpfsMetadataSidecarIfMissing(a);let[o,{WebAccess:s}]=await Promise.all([e(()=>import(`./dist-BKQr3WRb.js`).then(e=>e.t),__vite__mapDeps([0,1,2])),e(()=>import(`./dist-DHO9E-gl.js`),__vite__mapDeps([3,0,1,2]))]);await t.ensureRootMount(o);let c=`/__opfs__/${n.dbName}`,l=t.opfsBackends.get(n.dbName);if(l&&i){try{o.umount(c)}catch{}t.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 e(async()=>{let{resolveWithSidecarRepair:e,repairOpfsMetadataSidecar:t}=await import(`./sidecar-repair-431vRT2V.js`).then(e=>e.n);return{resolveWithSidecarRepair:e,repairOpfsMetadataSidecar:t}},__vite__mapDeps([4,1]));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}},t.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 e(()=>import(`./dist-BKQr3WRb.js`).then(e=>e.t),__vite__mapDeps([0,1,2]));await t.ensureRootMount(a);let o=`/__zenfs__/${r}`,s=t.memoryBackends.get(r);if(s&&i){try{a.umount(o)}catch{}t.memoryBackends.delete(r),s=void 0}s||(s={store:a.InMemory.create({label:r}),refs:0},t.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(e){return t.rootMountReady===null&&(t.rootMountReady=(async()=>{await e.configureSingle({backend:e.InMemory,label:`__vfs_root__`})})()),t.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 s(`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(e){return new t(e)}static async create(e){let n=e?.dbName??`browser-fs`,r=e?.wipe===!0,i=e?.backend??$(),a=new t(n,r,i,void 0,e?.onRepairProgress);return await a._ready,r&&await p().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 e=this.opfsBackendFs,n=this.opfsHandle;if(!e||!n)return;let r=e.index.toJSON(),i=t.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=te(e,r,i))}let o=JSON.stringify(ee(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=K(e,t,n.paths,n.prefixes);if(i.length===0)return;let a=m(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(e,r=`path`){if(this.backend!==`opfs`)return;let a=t.opfsBackends.get(this.dbName)?.sidecarDirty;if(!a)return;let o=i(e);(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 m(n)(a),s=U(t.index.get(a)?.mode),c=t._handles?.get(a),l=c?.kind===`directory`?`directory`:c?.kind===`file`?`file`:`absent`,u=W(o,s),d=W(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 s(`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`?t.opfsBackends:t.memoryBackends,r=n.get(this.dbName);if(r&&(--r.refs,r.refs<=0)){n.delete(this.dbName);try{(await e(()=>import(`./dist-BKQr3WRb.js`).then(e=>e.t),__vite__mapDeps([0,1,2]))).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,ino:e.ino}}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,ino:e.ino};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,ino:e.ino}}return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,ino:e.ino}}catch{return null}}async mount(e,t,r){let a=i(e);if(this.mountPoints.has(a))throw new s(`EEXIST`,`mount point is already mounted`,a);try{if((await this.lstat(a)).type!==`directory`)throw new s(`ENOTDIR`,`mount point must be a directory`,a);if((await this.readDir(a)).length>0)throw new s(`ENOTEMPTY`,`mount point must be empty to avoid shadowing existing files`,a)}catch(e){if(!(e instanceof s)||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??A(r?.env??{});this.mountIndex.registerMount(a,t.getHandle(),e)}let c=ce(t,a);try{this.mountSyncChannel?.postMessage({type:`mount`,path:a,descriptor:c})}catch{}if(this.watcher?.notify([{type:`modify`,path:a,entryType:`directory`}]),t.kind!==`hostfs`)try{let e={targetPath:a,descriptor:c,createdAt:Date.now()},n=t.kind===`local`?t.getHandle():void 0;await u(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 d(t)}catch{}}async reconstructBackendFromDescriptor(t,n){switch(t.kind){case`local`:{let e=await f(t.idbHandleKey);if(!e)throw Error(`no handle stored for ${t.idbHandleKey}`);return q.fromHandle(e,{mountId:t.mountId})}case`hostfs`:{let{HostFsMountBackend:r}=await e(async()=>{let{HostFsMountBackend:e}=await import(`./backend-hostfs-Com-zF5W.js`);return{HostFsMountBackend:e}},__vite__mapDeps([5,6,7]));return new r({targetPath:n,hostPath:t.hostPath,mountId:t.mountId})}case`s3`:{let{S3MountBackend:n,RemoteMountCache:r,makeSignedFetchS3:i}=await e(async()=>{let{S3MountBackend:e,RemoteMountCache:t,makeSignedFetchS3:n}=await import(`./mount-4B-1d5oh.js`);return{S3MountBackend:e,RemoteMountCache:t,makeSignedFetchS3:n}},__vite__mapDeps([8,9,10,11,12,13,6,14,7,15,1,16,17,18,19,20])),a=new r({mountId:t.mountId,ttlMs:3e4});return new n({source:t.source,profile:t.profile,cache:a,mountId:t.mountId,signedFetch:i(t.profile)})}case`da`:{let{DaMountBackend:n,RemoteMountCache:r,makeSignedFetchDa:i}=await e(async()=>{let{DaMountBackend:e,RemoteMountCache:t,makeSignedFetchDa:n}=await import(`./mount-4B-1d5oh.js`);return{DaMountBackend:e,RemoteMountCache:t,makeSignedFetchDa:n}},__vite__mapDeps([8,9,10,11,12,13,6,14,7,15,1,16,17,18,19,20])),a=new r({mountId:t.mountId,ttlMs:3e4});return new n({source:t.source,profile:t.profile,cache:a,mountId:t.mountId,signedFetch:i()})}case`aem`:{let{AemMountBackend:n,RemoteMountCache:r,makeSignedFetchDa:i}=await e(async()=>{let{AemMountBackend:e,RemoteMountCache:t,makeSignedFetchDa:n}=await import(`./mount-4B-1d5oh.js`);return{AemMountBackend:e,RemoteMountCache:t,makeSignedFetchDa:n}},__vite__mapDeps([8,9,10,11,12,13,6,14,7,15,1,16,17,18,19,20])),a=new r({mountId:t.mountId,ttlMs:3e4});return new n({source:t.source,profile:t.profile,cache:a,mountId:t.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 r=i(e);if(this.mountPoints.has(r))throw new s(`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 s(`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 s(`ENOENT`,`not a mount point`,n);let a=await r.refresh(t);return r.kind===`local`&&await this.mountIndex.refreshMount(n,A(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 s(`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){R(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 B(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 s(`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){R(e,a)}this.watcher?.notify([{type:n?`modify`:`create`,path:a,entryType:`file`}]),this.mountIndex.notifyWrite(a);return}let c;try{c=await this.resolveSymlinks(a)}catch{c=a}let l=!1;try{await this.lfs.stat(c),l=!0}catch{}let{dir:u}=n(c);await this.withWriteLock(async()=>{this.markSidecarDirty(c),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(c,t)}catch(e){if(u!==`/`&&e instanceof Error&&e.message.includes(`ENOENT`)){await this.mkdirRecursiveUnlocked(u);try{await this.lfs.writeFile(c,t)}catch(e){throw B(e,a)}}else throw B(e,a)}try{await this.lfs.truncate?.(c,e)}catch(e){throw B(e,a)}}),this.watcher?.notify([{type:l?`modify`:`create`,path:c,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){R(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 B(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(e){let n=this.dbName,r,i=new Promise(e=>{r=e}),a=t.writeChains.get(n)??Promise.resolve();t.writeChains.set(n,i),await a;try{let t=globalThis.navigator?.locks;return this.backend!==`opfs`||typeof t?.request!=`function`?await e():await t.request(`slicc-vfs:${n}`,()=>e())}finally{r(),t.writeChains.get(n)===i&&t.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 B(e,r);try{let e=await this.lfs.lstat(r);if(!e.isDirectory()&&!e.isSymbolicLink())throw new s(`ENOTDIR`,`not a directory`,r)}catch(e){if(e instanceof s&&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){R(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 B(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 s(`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){R(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 B(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){R(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,ino:e.ino}}catch(e){throw B(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){R(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 B(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*Q({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 s(`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 s(`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 B(e,r)}}else throw B(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 B(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,ino:e.ino}}return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,ino:e.ino}}catch(e){throw B(e,t)}}async realpath(e){return Z(this.lfs,e=>this.findMount(e)!==null,e)}resolveSymlinks(e){return re(this.lfs,e=>this.findMount(e)!==null,e)}};export{s as FsError,v as FsWatcher,j as MountIndex,L as RestrictedFS,le as VirtualFS,o as joinPath,i as normalizePath,r as pathSegments,$ as resolveVfsBackendFromEnv,n as splitPath,q as t};