sliccy 6.40.0 → 6.41.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (109) hide show
  1. package/README.md +1 -1
  2. package/dist/ui/assets/{account-store-BY3aXBTq.js → account-store-BOj83xge.js} +1 -1
  3. package/dist/ui/assets/{account-store-Dt0wuDIn.js → account-store-DZhNh1lP.js} +1 -1
  4. package/dist/ui/assets/{adobe-BGcNp7ud.js → adobe-B44VQ6eM.js} +1 -1
  5. package/dist/ui/assets/{adobe-D0Vk4L9j.js → adobe-CkY4aeYQ.js} +1 -1
  6. package/dist/ui/assets/{apply-layout-7i_CAtSn.js → apply-layout-C5EFkVOb.js} +1 -1
  7. package/dist/ui/assets/{apps-5ql07RBk.js → apps-D6aFuZ__.js} +1 -1
  8. package/dist/ui/assets/{azure-openai-DmSEPug5.js → azure-openai-B28v9Vnf.js} +1 -1
  9. package/dist/ui/assets/{azure-openai-BietzfDv.js → azure-openai-CCkWzmoI.js} +1 -1
  10. package/dist/ui/assets/{backend-local-Btkv66jT.js → backend-local-D7Gqh_i1.js} +1 -1
  11. package/dist/ui/assets/{backend-local-D4WZgy4J.js → backend-local-rrSF0A3j.js} +1 -1
  12. package/dist/ui/assets/{bsh-watchdog-BWoQ4vxy.js → bsh-watchdog-CpQHnQNg.js} +1 -1
  13. package/dist/ui/assets/{cdp-CUhn-e9o.js → cdp-DxpD3C8-.js} +1 -1
  14. package/dist/ui/assets/{cerebras-BXyQxeH5.js → cerebras-5iuoNSQP.js} +1 -1
  15. package/dist/ui/assets/{cerebras-CucwQEOZ.js → cerebras-c3TJ1kI0.js} +1 -1
  16. package/dist/ui/assets/{connect-surface-BcFfYqAg.js → connect-surface-gzLUHoaC.js} +1 -1
  17. package/dist/ui/assets/{dip-DReIJmS8.js → dip-VzeVAaf7.js} +2 -2
  18. package/dist/ui/assets/{fs-1lpjBcH8.js → fs-C2lY2r22.js} +1 -1
  19. package/dist/ui/assets/{fs-zjT7aP3D.js → fs-Dmq-Uipw.js} +2 -2
  20. package/dist/ui/assets/{github-i-WMYM95.js → github-CVDuNHn7.js} +1 -1
  21. package/dist/ui/assets/github-D6Uxzk_I.js +2 -0
  22. package/dist/ui/assets/{github-copilot--DaLg0Yi.js → github-copilot-CCYIsLiU.js} +1 -1
  23. package/dist/ui/assets/{github-copilot-BFx9SGae.js → github-copilot-EOD2wLtx.js} +1 -1
  24. package/dist/ui/assets/{github-install-B_7XU6lL.js → github-install-D1MDzwb-.js} +1 -1
  25. package/dist/ui/assets/{github-zip-DR8Okl6i.js → github-zip-JZM1fZvs.js} +1 -1
  26. package/dist/ui/assets/{kernel-worker-DAtKQ0nE.js → kernel-worker-3-c1T_Ut.js} +635 -632
  27. package/dist/ui/assets/lick-ws-bridge-CFFtf-gn.js +1 -0
  28. package/dist/ui/assets/lick-ws-bridge-DeUbk3le.js +1 -0
  29. package/dist/ui/assets/{local-llm-C10aQlRE.js → local-llm-C817P7no.js} +1 -1
  30. package/dist/ui/assets/{local-llm-Cx0afaWx.js → local-llm-DleKpjrX.js} +1 -1
  31. package/dist/ui/assets/logger-BoSvu4mW.js +1 -0
  32. package/dist/ui/assets/logger-DQgFbfwx.js +1 -0
  33. package/dist/ui/assets/{main-CJl81FT6.js → main-D02Bshqy.js} +3 -3
  34. package/dist/ui/assets/{main-cherry-B3C0ufyv.js → main-cherry-CIOlblhu.js} +1 -1
  35. package/dist/ui/assets/{mount-C3eFehs3.js → mount-C-4-Mnur.js} +1 -1
  36. package/dist/ui/assets/{mount-DB6C8U3-.js → mount-Cws5YfoU.js} +2 -2
  37. package/dist/ui/assets/mount-picker-popup-Bh-wMX4z.js +1 -0
  38. package/dist/ui/assets/{mount-recovery-Ck1JM_Xv.js → mount-recovery-DkHAVPiu.js} +1 -1
  39. package/dist/ui/assets/new-session-d3K2nWav.js +2 -0
  40. package/dist/ui/assets/oauth-bootstrap-MRD7a4SW.js +2 -0
  41. package/dist/ui/assets/{openai-codex-Bd4bYpX3.js → openai-codex-_I5Lsm9r.js} +1 -1
  42. package/dist/ui/assets/{openai-codex-V9JbtyRd.js → openai-codex-k-N5xxJt.js} +1 -1
  43. package/dist/ui/assets/{openrouter-CQgdHpTG.js → openrouter-1FGA9TBR.js} +1 -1
  44. package/dist/ui/assets/{openrouter-D-FzyKnA.js → openrouter-8zyBa8nl.js} +1 -1
  45. package/dist/ui/assets/{openrouter-oauth-Dvvl9Cva.js → openrouter-oauth-A0KBFgc_.js} +1 -1
  46. package/dist/ui/assets/{openrouter-oauth-BdAmWLQG.js → openrouter-oauth-BMleur3U.js} +1 -1
  47. package/dist/ui/assets/{panel-rpc-handlers-C2U2bPzL.js → panel-rpc-handlers-DzYOsxK_.js} +2 -2
  48. package/dist/ui/assets/{picker-approval-CdWaB1mR.js → picker-approval-CXL7T-sh.js} +1 -1
  49. package/dist/ui/assets/{provider-D8qPAyiY.js → provider-B0dbza19.js} +1 -1
  50. package/dist/ui/assets/{provider-CO-efbUO.js → provider-ZRVkoUAT.js} +2 -2
  51. package/dist/ui/assets/{provider-settings-CsNUnYS7.js → provider-settings-B76dsYi_.js} +1 -1
  52. package/dist/ui/assets/{provider-settings-BqgTrNd0.js → provider-settings-YcRcX51v.js} +1 -1
  53. package/dist/ui/assets/provider-store-access-CgBHXCh_.js +1 -0
  54. package/dist/ui/assets/provider-store-access-jt-VuLaS.js +2 -0
  55. package/dist/ui/assets/providers-Byu4I4zs.js +2 -0
  56. package/dist/ui/assets/{providers-C40GgLqQ.js → providers-CMFxANiX.js} +1 -1
  57. package/dist/ui/assets/{quick-llm-3eP55gY-.js → quick-llm-DB8hnmed.js} +1 -1
  58. package/dist/ui/assets/{recovery-screen-DdFC2GOd.js → recovery-screen--1O8eU7g.js} +1 -1
  59. package/dist/ui/assets/{redirect-uri-D3EF2enT.js → redirect-uri-DHGBfMTX.js} +1 -1
  60. package/dist/ui/assets/{remote-terminal-view-2Wk02uVb.js → remote-terminal-view-Q8aeCLeG.js} +1 -1
  61. package/dist/ui/assets/{session-freezer-7CtqVCH5.js → session-freezer-BvaAG9k9.js} +7 -7
  62. package/dist/ui/assets/{setup-feature-flags-remote-BYl7a7uw.js → setup-feature-flags-remote-BRjpfk0R.js} +1 -1
  63. package/dist/ui/assets/{setup-standalone-prelude-_3OVDJrq.js → setup-standalone-prelude-D0i3nMAq.js} +2 -2
  64. package/dist/ui/assets/setup-sudo-B__wUcBH.js +2 -0
  65. package/dist/ui/assets/{skills-C1o--fSs.js → skills-D2uYHYBK.js} +1 -1
  66. package/dist/ui/assets/{store-Bz3wYNXR.js → store-BFReevIV.js} +1 -1
  67. package/dist/ui/assets/{store-Dg0q78qC.js → store-Bxt8NcqL.js} +1 -1
  68. package/dist/ui/assets/{sudo-vcErFxyt.js → sudo-BJ5Pw_5M.js} +1 -1
  69. package/dist/ui/assets/{tab-teleport-CLc1Tuqi.js → tab-teleport-Dhh60nH7.js} +1 -1
  70. package/dist/ui/assets/{teleport-storage-Beud1T6_.js → teleport-storage-CwYntbOB.js} +1 -1
  71. package/dist/ui/assets/tool-ui-C-E235kX.js +1 -0
  72. package/dist/ui/assets/tool-ui-Dq9m-pLC.js +1 -0
  73. package/dist/ui/assets/{upgrade-detection-WFIpSR9L.js → upgrade-detection-CsUicV6H.js} +1 -1
  74. package/dist/ui/assets/{wc-browser-BTGpaihO.js → wc-browser-DdPBkgaJ.js} +1 -1
  75. package/dist/ui/assets/{wc-extension-ExktUfXh.js → wc-extension-yYG4eEP9.js} +2 -2
  76. package/dist/ui/assets/wc-follower-DUFNQfPQ.js +17 -0
  77. package/dist/ui/assets/{wc-live-CxALPjhv.js → wc-live-2R8dyI8p.js} +3 -3
  78. package/dist/ui/assets/wc-nav-BYI4hReW.js +2 -0
  79. package/dist/ui/assets/{wc-onboarding-CTJOFFrA.js → wc-onboarding-jNrGVQ4A.js} +2 -2
  80. package/dist/ui/assets/{wc-permissions-iqdYkwde.js → wc-permissions-Dw-_JpYr.js} +3 -3
  81. package/dist/ui/assets/wc-permissions-providers-BOgM_jqs.js +2 -0
  82. package/dist/ui/assets/{wc-placeholder-B8xuHsKi.js → wc-placeholder-BVsXZIwG.js} +2 -2
  83. package/dist/ui/assets/{wc-settings-BBHQqfPX.js → wc-settings-CEbEFdqB.js} +2 -2
  84. package/dist/ui/assets/{wc-shell-BAh53EB-.js → wc-shell-DQFNkoU5.js} +2 -2
  85. package/dist/ui/assets/{wc-sprinkles-BagZ1zt0.js → wc-sprinkles-BDlwD_fb.js} +2 -2
  86. package/dist/ui/assets/wc-tray--MLF73UI.js +2 -0
  87. package/dist/ui/assets/wc-tray-scoops-T7dGFJhf.js +5 -0
  88. package/dist/ui/assets/{xai-grok-DmTanlk8.js → xai-grok-BWbFBwcw.js} +1 -1
  89. package/dist/ui/assets/{xai-grok-8VzWYOXJ.js → xai-grok-DpQmep92.js} +1 -1
  90. package/dist/ui/index.html +8 -7
  91. package/dist/ui/packages/webapp/index.html +8 -7
  92. package/package.json +1 -1
  93. package/dist/ui/assets/github-BljoTMry.js +0 -2
  94. package/dist/ui/assets/lick-ws-bridge-Cpex5Pe9.js +0 -1
  95. package/dist/ui/assets/lick-ws-bridge-D_e6wRPA.js +0 -1
  96. package/dist/ui/assets/mount-picker-popup-CSSC05JS.js +0 -1
  97. package/dist/ui/assets/new-session-CNFDAwZC.js +0 -2
  98. package/dist/ui/assets/oauth-bootstrap-C0v-Q0DW.js +0 -2
  99. package/dist/ui/assets/provider-store-access-C6cSTLmi.js +0 -1
  100. package/dist/ui/assets/provider-store-access-Dop6FohJ.js +0 -2
  101. package/dist/ui/assets/providers-Bcv36n05.js +0 -2
  102. package/dist/ui/assets/setup-sudo-DhnUoSO-.js +0 -2
  103. package/dist/ui/assets/tool-ui-DfXu6quJ.js +0 -1
  104. package/dist/ui/assets/tool-ui-t6ocn6AG.js +0 -1
  105. package/dist/ui/assets/wc-follower-D6d-q56W.js +0 -17
  106. package/dist/ui/assets/wc-nav-DCCBQZ-C.js +0 -2
  107. package/dist/ui/assets/wc-permissions-providers-DpoCXfAQ.js +0 -2
  108. package/dist/ui/assets/wc-tray-Dsqe3lyy.js +0 -2
  109. package/dist/ui/assets/wc-tray-scoops-Bpcyy0qK.js +0 -5
@@ -1 +1 @@
1
- import{h as e}from"./account-store-BY3aXBTq.js";import{a as t}from"./diagnostics-DN_idNHx.js";import{p as n}from"./bedrock-camp-CFmElpzZ.js";import{r,s as i}from"./legacy-api-aliases-BVP0Ho8x.js";const a=`cerebras`,o=`https://api.cerebras.ai/v1`,s=`openai-completions`,c=`${a}-openai`,l=`slicc-cerebras-models`;let u=[];const d=[{id:`gpt-oss-120b`,name:`GPT OSS 120B`,api:`openai`,reasoning:!0,input:[`text`],context_window:131072,max_tokens:40960},{id:`gemma-4-31b`,name:`Gemma 4 31B`,api:`openai`,reasoning:!1,input:[`text`,`image`],context_window:131072,max_tokens:40960},{id:`zai-glm-4.7`,name:`Z.AI GLM-4.7`,api:`openai`,reasoning:!1,input:[`text`],context_window:131072,max_tokens:40960}];function f(e){try{localStorage.setItem(l,JSON.stringify(e))}catch{}}function p(){try{let e=localStorage.getItem(l);if(!e)return[];let t=JSON.parse(e);return Array.isArray(t)&&t.length>0?t:[]}catch{return[]}}function m(e){let t=e.id??``,n=d.find(e=>e.id===t);return{id:t,name:e.name??n?.name??t,api:`openai`,reasoning:e.capabilities?.reasoning??n?.reasoning??!1,input:e.capabilities?.vision?[`text`,`image`]:n?.input??[`text`],context_window:e.limits?.max_context_length??n?.context_window??8192,max_tokens:e.limits?.max_completion_tokens??n?.max_tokens??4096}}async function h(e){let t=await fetch(`${o}/models`,{headers:{Authorization:`Bearer ${e}`}});if(!t.ok)throw Error(`GET /v1/models → ${t.status} ${t.statusText}`);let n=((await t.json()).data??[]).map(m).filter(e=>e.id.length>0);n.length>0&&(u=n,f(n))}function g(e,t){return{type:`error`,reason:`error`,error:{role:`assistant`,content:[],api:c,provider:a,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:`error`,errorMessage:t instanceof Error?t.message:String(t),timestamp:Date.now()}}}const _=(e,n,i={})=>{let a=t();return(async()=>{try{let t={...e,baseUrl:o,api:s},c=r(t,n,i);for await(let e of c)a.push(e);a.end()}catch(t){console.error(`[cerebras] Stream error:`,t instanceof Error?t.message:String(t)),a.push(g(e,t)),a.end()}})(),a},v=(e,n,r)=>{let a=t();return(async()=>{try{let t={...e,baseUrl:o,api:s},c=i(t,n,r);for await(let e of c)a.push(e);a.end()}catch(t){console.error(`[cerebras] Stream error:`,t instanceof Error?t.message:String(t)),a.push(g(e,t)),a.end()}})(),a},y={id:a,name:`Cerebras`,description:`Ultra-fast inference on Cerebras hardware. Get an API key at cloud.cerebras.ai.`,requiresApiKey:!0,requiresBaseUrl:!1,getModelIds:()=>{if(u.length>0)return u;let e=p();return e.length>0?e:d},refreshModels:async t=>{let n=t??e(a)??``;if(n)try{await h(n)}catch(e){console.warn(`[cerebras] Failed to refresh model list:`,e instanceof Error?e.message:String(e))}}};function b(){n({api:c,stream:_,streamSimple:v})}export{y as config,b as register};
1
+ import{h as e}from"./account-store-BOj83xge.js";import{a as t}from"./diagnostics-DN_idNHx.js";import{p as n}from"./bedrock-camp-CFmElpzZ.js";import{r,s as i}from"./legacy-api-aliases-BVP0Ho8x.js";const a=`cerebras`,o=`https://api.cerebras.ai/v1`,s=`openai-completions`,c=`${a}-openai`,l=`slicc-cerebras-models`;let u=[];const d=[{id:`gpt-oss-120b`,name:`GPT OSS 120B`,api:`openai`,reasoning:!0,input:[`text`],context_window:131072,max_tokens:40960},{id:`gemma-4-31b`,name:`Gemma 4 31B`,api:`openai`,reasoning:!1,input:[`text`,`image`],context_window:131072,max_tokens:40960},{id:`zai-glm-4.7`,name:`Z.AI GLM-4.7`,api:`openai`,reasoning:!1,input:[`text`],context_window:131072,max_tokens:40960}];function f(e){try{localStorage.setItem(l,JSON.stringify(e))}catch{}}function p(){try{let e=localStorage.getItem(l);if(!e)return[];let t=JSON.parse(e);return Array.isArray(t)&&t.length>0?t:[]}catch{return[]}}function m(e){let t=e.id??``,n=d.find(e=>e.id===t);return{id:t,name:e.name??n?.name??t,api:`openai`,reasoning:e.capabilities?.reasoning??n?.reasoning??!1,input:e.capabilities?.vision?[`text`,`image`]:n?.input??[`text`],context_window:e.limits?.max_context_length??n?.context_window??8192,max_tokens:e.limits?.max_completion_tokens??n?.max_tokens??4096}}async function h(e){let t=await fetch(`${o}/models`,{headers:{Authorization:`Bearer ${e}`}});if(!t.ok)throw Error(`GET /v1/models → ${t.status} ${t.statusText}`);let n=((await t.json()).data??[]).map(m).filter(e=>e.id.length>0);n.length>0&&(u=n,f(n))}function g(e,t){return{type:`error`,reason:`error`,error:{role:`assistant`,content:[],api:c,provider:a,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:`error`,errorMessage:t instanceof Error?t.message:String(t),timestamp:Date.now()}}}const _=(e,n,i={})=>{let a=t();return(async()=>{try{let t={...e,baseUrl:o,api:s},c=r(t,n,i);for await(let e of c)a.push(e);a.end()}catch(t){console.error(`[cerebras] Stream error:`,t instanceof Error?t.message:String(t)),a.push(g(e,t)),a.end()}})(),a},v=(e,n,r)=>{let a=t();return(async()=>{try{let t={...e,baseUrl:o,api:s},c=i(t,n,r);for await(let e of c)a.push(e);a.end()}catch(t){console.error(`[cerebras] Stream error:`,t instanceof Error?t.message:String(t)),a.push(g(e,t)),a.end()}})(),a},y={id:a,name:`Cerebras`,description:`Ultra-fast inference on Cerebras hardware. Get an API key at cloud.cerebras.ai.`,requiresApiKey:!0,requiresBaseUrl:!1,getModelIds:()=>{if(u.length>0)return u;let e=p();return e.length>0?e:d},refreshModels:async t=>{let n=t??e(a)??``;if(n)try{await h(n)}catch(e){console.warn(`[cerebras] Failed to refresh model list:`,e instanceof Error?e.message:String(e))}}};function b(){n({api:c,stream:_,streamSimple:v})}export{y as config,b as register};
@@ -1 +1 @@
1
- import{h as e}from"./account-store-Dt0wuDIn.js";import{a as t}from"./diagnostics-DN_idNHx.js";import{a as n}from"./compat-Bn8HnC3L.js";import{r,s as i}from"./legacy-api-aliases-DAkrHYf9.js";var a=`cerebras`,o=`https://api.cerebras.ai/v1`,s=`openai-completions`,c=`${a}-openai`,l=`slicc-cerebras-models`,u=[],d=[{id:`gpt-oss-120b`,name:`GPT OSS 120B`,api:`openai`,reasoning:!0,input:[`text`],context_window:131072,max_tokens:40960},{id:`gemma-4-31b`,name:`Gemma 4 31B`,api:`openai`,reasoning:!1,input:[`text`,`image`],context_window:131072,max_tokens:40960},{id:`zai-glm-4.7`,name:`Z.AI GLM-4.7`,api:`openai`,reasoning:!1,input:[`text`],context_window:131072,max_tokens:40960}];function f(e){try{localStorage.setItem(l,JSON.stringify(e))}catch{}}function p(){try{let e=localStorage.getItem(l);if(!e)return[];let t=JSON.parse(e);return Array.isArray(t)&&t.length>0?t:[]}catch{return[]}}function m(e){let t=e.id??``,n=d.find(e=>e.id===t);return{id:t,name:e.name??n?.name??t,api:`openai`,reasoning:e.capabilities?.reasoning??n?.reasoning??!1,input:e.capabilities?.vision?[`text`,`image`]:n?.input??[`text`],context_window:e.limits?.max_context_length??n?.context_window??8192,max_tokens:e.limits?.max_completion_tokens??n?.max_tokens??4096}}async function h(e){let t=await fetch(`${o}/models`,{headers:{Authorization:`Bearer ${e}`}});if(!t.ok)throw Error(`GET /v1/models → ${t.status} ${t.statusText}`);let n=((await t.json()).data??[]).map(m).filter(e=>e.id.length>0);n.length>0&&(u=n,f(n))}function g(e,t){return{type:`error`,reason:`error`,error:{role:`assistant`,content:[],api:c,provider:a,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:`error`,errorMessage:t instanceof Error?t.message:String(t),timestamp:Date.now()}}}var _=(e,n,i={})=>{let a=t();return(async()=>{try{let t={...e,baseUrl:o,api:s},c=r(t,n,i);for await(let e of c)a.push(e);a.end()}catch(t){console.error(`[cerebras] Stream error:`,t instanceof Error?t.message:String(t)),a.push(g(e,t)),a.end()}})(),a},v=(e,n,r)=>{let a=t();return(async()=>{try{let t={...e,baseUrl:o,api:s},c=i(t,n,r);for await(let e of c)a.push(e);a.end()}catch(t){console.error(`[cerebras] Stream error:`,t instanceof Error?t.message:String(t)),a.push(g(e,t)),a.end()}})(),a},y={id:a,name:`Cerebras`,description:`Ultra-fast inference on Cerebras hardware. Get an API key at cloud.cerebras.ai.`,requiresApiKey:!0,requiresBaseUrl:!1,getModelIds:()=>{if(u.length>0)return u;let e=p();return e.length>0?e:d},refreshModels:async t=>{let n=t??e(a)??``;if(n)try{await h(n)}catch(e){console.warn(`[cerebras] Failed to refresh model list:`,e instanceof Error?e.message:String(e))}}};function b(){n({api:c,stream:_,streamSimple:v})}export{y as config,b as register};
1
+ import{h as e}from"./account-store-DZhNh1lP.js";import{a as t}from"./diagnostics-DN_idNHx.js";import{a as n}from"./compat-Bn8HnC3L.js";import{r,s as i}from"./legacy-api-aliases-DAkrHYf9.js";var a=`cerebras`,o=`https://api.cerebras.ai/v1`,s=`openai-completions`,c=`${a}-openai`,l=`slicc-cerebras-models`,u=[],d=[{id:`gpt-oss-120b`,name:`GPT OSS 120B`,api:`openai`,reasoning:!0,input:[`text`],context_window:131072,max_tokens:40960},{id:`gemma-4-31b`,name:`Gemma 4 31B`,api:`openai`,reasoning:!1,input:[`text`,`image`],context_window:131072,max_tokens:40960},{id:`zai-glm-4.7`,name:`Z.AI GLM-4.7`,api:`openai`,reasoning:!1,input:[`text`],context_window:131072,max_tokens:40960}];function f(e){try{localStorage.setItem(l,JSON.stringify(e))}catch{}}function p(){try{let e=localStorage.getItem(l);if(!e)return[];let t=JSON.parse(e);return Array.isArray(t)&&t.length>0?t:[]}catch{return[]}}function m(e){let t=e.id??``,n=d.find(e=>e.id===t);return{id:t,name:e.name??n?.name??t,api:`openai`,reasoning:e.capabilities?.reasoning??n?.reasoning??!1,input:e.capabilities?.vision?[`text`,`image`]:n?.input??[`text`],context_window:e.limits?.max_context_length??n?.context_window??8192,max_tokens:e.limits?.max_completion_tokens??n?.max_tokens??4096}}async function h(e){let t=await fetch(`${o}/models`,{headers:{Authorization:`Bearer ${e}`}});if(!t.ok)throw Error(`GET /v1/models → ${t.status} ${t.statusText}`);let n=((await t.json()).data??[]).map(m).filter(e=>e.id.length>0);n.length>0&&(u=n,f(n))}function g(e,t){return{type:`error`,reason:`error`,error:{role:`assistant`,content:[],api:c,provider:a,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:`error`,errorMessage:t instanceof Error?t.message:String(t),timestamp:Date.now()}}}var _=(e,n,i={})=>{let a=t();return(async()=>{try{let t={...e,baseUrl:o,api:s},c=r(t,n,i);for await(let e of c)a.push(e);a.end()}catch(t){console.error(`[cerebras] Stream error:`,t instanceof Error?t.message:String(t)),a.push(g(e,t)),a.end()}})(),a},v=(e,n,r)=>{let a=t();return(async()=>{try{let t={...e,baseUrl:o,api:s},c=i(t,n,r);for await(let e of c)a.push(e);a.end()}catch(t){console.error(`[cerebras] Stream error:`,t instanceof Error?t.message:String(t)),a.push(g(e,t)),a.end()}})(),a},y={id:a,name:`Cerebras`,description:`Ultra-fast inference on Cerebras hardware. Get an API key at cloud.cerebras.ai.`,requiresApiKey:!0,requiresBaseUrl:!1,getModelIds:()=>{if(u.length>0)return u;let e=p();return e.length>0?e:d},refreshModels:async t=>{let n=t??e(a)??``;if(n)try{await h(n)}catch(e){console.warn(`[cerebras] Failed to refresh model list:`,e instanceof Error?e.message:String(e))}}};function b(){n({api:c,stream:_,streamSimple:v})}export{y as config,b as register};
@@ -1,4 +1,4 @@
1
- import{C as e,P as t,d as n,f as r}from"./account-store-Dt0wuDIn.js";import{n as i}from"./provider-settings-BqgTrNd0.js";var a=`slicc_cloud_model_catalog`,o=`adobe`;function s(t){if(t===o)return!1;let n=e(t);return!(n.hidden||n.onOAuthLoginIntercepted)}function c(){try{let e=r().map(e=>({providerId:e.providerId,providerName:e.providerName,models:e.models.map(e=>({id:e.id,name:e.name}))}));localStorage.setItem(a,JSON.stringify(e))}catch{}}async function l(r){for(;r.firstChild;)r.removeChild(r.firstChild);r.className=`connect-surface`;let a=document.createElement(`h1`);a.className=`connect-surface__title`,a.textContent=`Connect providers`,r.appendChild(a);let l=document.createElement(`p`);l.className=`connect-surface__desc`,l.textContent=`Log in or add API keys for the providers your cone should use, then click Done to return to the dashboard.`,r.appendChild(l);let u=document.createElement(`div`);u.className=`connect-surface__accounts`,r.appendChild(u);function d(){for(;u.firstChild;)u.removeChild(u.firstChild);let r=n().filter(e=>e.providerId!==o);if(r.length===0){let e=document.createElement(`div`);e.className=`connect-surface__empty`,e.textContent=`No providers connected yet.`,u.appendChild(e)}else{let n=document.createElement(`div`);n.className=`connect-surface__accounts-list`;for(let i of r){let r=e(i.providerId),a=document.createElement(`div`);a.className=`connect-surface__account-row`;let o=document.createElement(`div`);o.className=`connect-surface__account-info`;let s=document.createElement(`div`);s.className=`connect-surface__account-name`,s.textContent=r.name,o.appendChild(s);let l=document.createElement(`div`);l.className=`connect-surface__account-detail`,l.textContent=i.userName?i.userName:i.accessToken?`Logged in`:i.apiKey?`API key set`:`No credentials`,o.appendChild(l),a.appendChild(o);let u=document.createElement(`button`);u.className=`connect-surface__remove-btn`,u.textContent=`Remove`,u.onclick=async()=>{await t(i.providerId),c(),d()},a.appendChild(u),n.appendChild(a)}u.appendChild(n)}let a=document.createElement(`button`);a.className=`connect-surface__add-btn`,a.textContent=r.length===0?`Add provider`:`Manage providers`,a.onclick=async()=>{await i({startInAddAccount:!0,providerFilter:s})&&(c(),d())},u.appendChild(a)}d(),c();let f=document.createElement(`div`);f.className=`connect-surface__footer`;let p=document.createElement(`button`);if(p.className=`connect-surface__done-btn`,p.textContent=`Done — return to dashboard`,p.onclick=()=>{c(),window.close()},f.appendChild(p),r.appendChild(f),!document.getElementById(`connect-surface-style`)){let e=document.createElement(`style`);e.id=`connect-surface-style`,e.textContent=`
1
+ import{C as e,P as t,d as n,f as r}from"./account-store-DZhNh1lP.js";import{n as i}from"./provider-settings-YcRcX51v.js";var a=`slicc_cloud_model_catalog`,o=`adobe`;function s(t){if(t===o)return!1;let n=e(t);return!(n.hidden||n.onOAuthLoginIntercepted)}function c(){try{let e=r().map(e=>({providerId:e.providerId,providerName:e.providerName,models:e.models.map(e=>({id:e.id,name:e.name}))}));localStorage.setItem(a,JSON.stringify(e))}catch{}}async function l(r){for(;r.firstChild;)r.removeChild(r.firstChild);r.className=`connect-surface`;let a=document.createElement(`h1`);a.className=`connect-surface__title`,a.textContent=`Connect providers`,r.appendChild(a);let l=document.createElement(`p`);l.className=`connect-surface__desc`,l.textContent=`Log in or add API keys for the providers your cone should use, then click Done to return to the dashboard.`,r.appendChild(l);let u=document.createElement(`div`);u.className=`connect-surface__accounts`,r.appendChild(u);function d(){for(;u.firstChild;)u.removeChild(u.firstChild);let r=n().filter(e=>e.providerId!==o);if(r.length===0){let e=document.createElement(`div`);e.className=`connect-surface__empty`,e.textContent=`No providers connected yet.`,u.appendChild(e)}else{let n=document.createElement(`div`);n.className=`connect-surface__accounts-list`;for(let i of r){let r=e(i.providerId),a=document.createElement(`div`);a.className=`connect-surface__account-row`;let o=document.createElement(`div`);o.className=`connect-surface__account-info`;let s=document.createElement(`div`);s.className=`connect-surface__account-name`,s.textContent=r.name,o.appendChild(s);let l=document.createElement(`div`);l.className=`connect-surface__account-detail`,l.textContent=i.userName?i.userName:i.accessToken?`Logged in`:i.apiKey?`API key set`:`No credentials`,o.appendChild(l),a.appendChild(o);let u=document.createElement(`button`);u.className=`connect-surface__remove-btn`,u.textContent=`Remove`,u.onclick=async()=>{await t(i.providerId),c(),d()},a.appendChild(u),n.appendChild(a)}u.appendChild(n)}let a=document.createElement(`button`);a.className=`connect-surface__add-btn`,a.textContent=r.length===0?`Add provider`:`Manage providers`,a.onclick=async()=>{await i({startInAddAccount:!0,providerFilter:s})&&(c(),d())},u.appendChild(a)}d(),c();let f=document.createElement(`div`);f.className=`connect-surface__footer`;let p=document.createElement(`button`);if(p.className=`connect-surface__done-btn`,p.textContent=`Done — return to dashboard`,p.onclick=()=>{c(),window.close()},f.appendChild(p),r.appendChild(f),!document.getElementById(`connect-surface-style`)){let e=document.createElement(`style`);e.id=`connect-surface-style`,e.textContent=`
2
2
  .connect-surface {
3
3
  padding: 2rem;
4
4
  max-width: 560px;
@@ -1,4 +1,4 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/mount-picker-popup-CSSC05JS.js","assets/rolldown-runtime-Dd_uD5pT.js","assets/logger-DDBAeTLF.js","assets/picker-popup-BvzmBsGL.js","assets/runtime-env-DH4NDw4t.js","assets/usb-picker-Cl6Cwuv9.js","assets/serial-picker-CUd91lje.js","assets/hid-picker-Bhoh8hxy.js","assets/usb-device-registry-CRsCisej.js","assets/serial-port-registry-B3LG5UIy.js","assets/hid-device-registry-B2R-0rNt.js"])))=>i.map(i=>d[i]);
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/mount-picker-popup-Bh-wMX4z.js","assets/rolldown-runtime-Dd_uD5pT.js","assets/logger-DDBAeTLF.js","assets/logger-BoSvu4mW.js","assets/picker-popup-BvzmBsGL.js","assets/runtime-env-DH4NDw4t.js","assets/usb-picker-Cl6Cwuv9.js","assets/serial-picker-CUd91lje.js","assets/hid-picker-Bhoh8hxy.js","assets/usb-device-registry-CRsCisej.js","assets/serial-port-registry-B3LG5UIy.js","assets/hid-device-registry-B2R-0rNt.js"])))=>i.map(i=>d[i]);
2
2
  import{n as e}from"./rolldown-runtime-Dd_uD5pT.js";import{t}from"./preload-helper-Czpn1I53.js";import{n}from"./runtime-env-DH4NDw4t.js";import{t as r}from"./permissions-surface-registry-CilCRwhh.js";import{n as i,r as a}from"./hid-device-registry-B2R-0rNt.js";import{a as o,i as s}from"./serial-port-registry-B3LG5UIy.js";import{C as c,D as l,E as u,S as d,_ as f,a as ee,g as te,h as p,k as m,l as h,m as ne,n as re,o as g,s as ie,w as ae,x as oe,y as se}from"./usb-operations-Cgk-otz-.js";import{i as ce,r as _}from"./usb-device-registry-CRsCisej.js";import{i as v,n as le,r as y}from"./sprinkle-renderer-CMk2ghMi.js";import{n as ue}from"./sprinkle-bridge-RIIOK3yH.js";import{a as b,n as x,r as S}from"./theme-CXRqxpw6.js";var C=e({broadcastToDips:()=>R,disposeDips:()=>X,handleDipPickerAction:()=>Z,hydrateDips:()=>Y,mountDip:()=>K,setDipExecHandler:()=>he}),w=n();async function T(e,t){if(t?.aborted)throw new DOMException(`aborted`,`AbortError`);let n=await D(e,!0,t);if(t?.aborted)throw new DOMException(`aborted`,`AbortError`);if(n===null)throw Error(`VFS read failed: ${e}`);return typeof n==`string`?n:new TextDecoder().decode(n)}var E=null;function de(){if(E)return E;if(typeof BroadcastChannel>`u`)return null;try{E=new BroadcastChannel(`preview-vfs`)}catch{return null}return E}async function D(e,t,n){let r=de();if(!r)return null;let i=`dip-${Date.now()}-${Math.random().toString(36).slice(2)}`;return new Promise(a=>{let o=!1,s=()=>{r.removeEventListener(`message`,c),n?.removeEventListener(`abort`,l)},c=e=>{if(!o&&e.data?.type===`preview-vfs-response`&&e.data.id===i){if(o=!0,s(),e.data.error){a(null);return}a(e.data.content??null)}},l=()=>{o||(o=!0,s(),a(null))};r.addEventListener(`message`,c),n?.addEventListener(`abort`,l),setTimeout(()=>{o||(o=!0,s(),a(null))},5e3),r.postMessage({type:`preview-vfs-read`,id:i,path:e,asText:t})})}var fe=[`/shared/sprinkles/`,`/workspace/skills/sprinkles/`,`/workspace/sprinkles/`],pe=[`/shared/`,`/workspace/skills/sprinkles/`,`/workspace/sprinkles/`];function me(e){return fe.some(t=>e.startsWith(t))}function O(e){return typeof e!=`string`||!e.startsWith(`/`)||e.includes(`..`)?!1:pe.some(t=>e.startsWith(t))}var k=new WeakSet,A=`,
3
3
  exec: Object.assign(function(cmd) {
4
4
  return _vfsCall('dip-exec', { cmd: cmd }, function(m) { return m.result; });
@@ -230,4 +230,4 @@ ${o?`<script src="/slicc-diff.js"><\/script>`:``}
230
230
  <script src="/lucide-icons.js"><\/script>
231
231
  </head>
232
232
  <body class="sprinkle-inline">${e}</body></html>`}var L=new Set;function R(e){if(typeof e?.type!=`string`||e.type.indexOf(`slicc-`)!==0)throw Error(`broadcastToDips: payload.type must start with 'slicc-'`);for(let t of L)try{t.postMessage(e,`*`)}catch{}}var z;function he(e){z=e}function B(e){return e.length===0?`''`:`'${e.replace(/'/g,`'\\''`)}'`}function ge(e,t){let n=t?.cwd??`.`,r=t?.allowedCommands??`*`,i=[`agent`];return t?.model&&i.push(`--model`,B(t.model)),t?.thinking&&i.push(`--thinking`,B(t.thinking)),t?.readOnly&&i.push(`--read-only`,B(t.readOnly)),i.push(B(n),B(r),B(e)),i.join(` `)}async function V(e){if(!z)return{stdout:``,stderr:`exec: shell bridge not available
233
- `,exitCode:127};try{return await z(e)}catch(e){return{stdout:``,stderr:`exec: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}}async function _e(e,t){let n=await V(ge(e,t));return{stdout:n.stdout||n.stderr,exitCode:n.exitCode}}async function ve(e,t){let n=await ue(V,e,t);if(e===`fetch`){let e=n,t=atob(e.bodyBase64),r=new Uint8Array(t.length);for(let e=0;e<t.length;e++)r[e]=t.charCodeAt(e);return{...e,body:new TextDecoder(`utf-8`).decode(r)}}return n}var H=new WeakMap;function ye(e,t){try{e.postMessage({type:`dip-device-event`,channel:`hid:inputreport`,payload:t},`*`)}catch{}}async function be(e,t){let n=H.get(e);if(n||(n=new Map,H.set(e,n)),n.has(t))return;let r=await d(a(),t,n=>{let r=n.bytes instanceof Uint8Array?n.bytes:new Uint8Array(n.bytes);ye(e,{handle:t,reportId:n.reportId,data:r})});n.set(t,r)}async function xe(e,t){let n=H.get(e);if(!n)return;let r=n.get(t);if(r){n.delete(t);try{await Promise.resolve(r())}catch{}}n.size===0&&H.delete(e)}function U(e){let t=H.get(e);if(t){for(let e of t.values())try{Promise.resolve(e()).catch(()=>{})}catch{}H.delete(e)}}function Se(e){if(e instanceof Uint8Array)return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e)){let t=e;return new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}if(Array.isArray(e))return new Uint8Array(e);throw Error(`expected Uint8Array, ArrayBuffer, or number[]`)}async function Ce(e,t,n){let r=a();switch(t){case`list`:{let e=i();if(!e)throw Error(`WebHID is unavailable in this browser`);return te(r,e)}case`request`:{let e=i();if(!e)throw Error(`WebHID is unavailable in this browser`);return se(r,e,n[0]??[])}case`info`:return p(r,n[0]);case`open`:{let t=n[0];return await f(r,t),await be(e,t),{ok:!0}}case`close`:{let t=n[0];return await xe(e,t),await ne(r,t),{ok:!0}}case`sendReport`:{let e=n[0],t=n[1],i=Se(n[2]),a=i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength);return await oe(r,e,t,a),{ok:!0}}default:throw Error(`hid: unknown op '${t}'`)}}async function we(e,t){let n=o();switch(e){case`list`:{let e=s();if(!e)throw Error(`Web Serial is unavailable in this browser`);return u(n,e)}case`request`:{let e=s();if(!e)throw Error(`Web Serial is unavailable in this browser`);return m(n,e,t[0]??[])}case`info`:return ae(n,t[0]);case`open`:{let e=t[0],r=t[1]??{baudRate:9600};return await l(n,e,r),{ok:!0}}case`close`:return await c(n,t[0]),{ok:!0};default:throw Error(`serial: unknown op '${e}'`)}}async function Te(e,t){let n=ce();switch(e){case`list`:{let e=_();if(!e)throw Error(`WebUSB is unavailable in this browser`);return g(n,e)}case`request`:{let e=_();if(!e)throw Error(`WebUSB is unavailable in this browser`);return h(n,e,t[0]??[])}case`info`:return ee(n,t[0]);case`open`:return await ie(n,t[0]),{ok:!0};case`close`:return await re(n,t[0]),{ok:!0};default:throw Error(`usb: unknown op '${e}'`)}}async function Ee(e,t,n,r){switch(t){case`hid`:return Ce(e,n,r);case`serial`:return we(n,r);case`usb`:return Te(n,r);default:throw Error(`unknown device channel '${t}'`)}}async function W(e,t){if(!e||typeof t.id!=`number`)return!1;let n=n=>{try{e.postMessage({...n,id:t.id},`*`)}catch{}};if(!k.has(e))return n({type:`dip-device-op-response`,error:`device access not allowed for this dip`}),!0;let r=t.channel;if(r!==`hid`&&r!==`serial`&&r!==`usb`)return n({type:`dip-device-op-response`,error:`unknown device channel '${r}'`}),!0;try{n({type:`dip-device-op-response`,result:await Ee(e,r,typeof t.op==`string`?t.op:``,Array.isArray(t.args)?t.args:[])})}catch(e){n({type:`dip-device-op-response`,error:e instanceof Error?e.message:String(e)})}return!0}async function G(e,t){if(!e||typeof t.id!=`number`)return!1;let n=n=>{try{e.postMessage({...n,id:t.id},`*`)}catch{}};if(!k.has(e))return n({type:`${t.type}-response`,error:`exec not allowed for this dip`}),!0;if(t.type===`dip-exec`)return n({type:`dip-exec-response`,result:await V(typeof t.cmd==`string`?t.cmd:``)}),!0;if(t.type===`dip-agent`)return n({type:`dip-agent-response`,result:await _e(typeof t.prompt==`string`?t.prompt:``,t.opts)}),!0;if(t.type===`dip-jsh`){try{n({type:`dip-jsh-response`,result:await ve(typeof t.op==`string`?t.op:``,Array.isArray(t.args)?t.args:[])})}catch(e){n({type:`dip-jsh-response`,error:e instanceof Error?e.message:String(e)})}return!0}return!1}function K(e,t,n,r=!1){let i=I(t,!1,r);if(w)return Me(e,i,n,r);let a=document.createElement(`iframe`);a.setAttribute(`sandbox`,`allow-scripts allow-same-origin`),a.style.cssText=`width:100%;border:none;overflow:hidden;display:block;`,a.srcdoc=i,e.appendChild(a),a.contentWindow&&(S(a.contentWindow),L.add(a.contentWindow),r&&k.add(a.contentWindow)),a.addEventListener(`load`,()=>{S(a.contentWindow),a.contentWindow&&(L.add(a.contentWindow),r&&k.add(a.contentWindow)),y()&&v(a)},{once:!0});let o=e=>{if(e.source!==a.contentWindow)return;let t=e.data;t?.type&&(t.type===`dip-lick`?n(t.action,t.data):t.type===`dip-height`?a.style.height=t.height+`px`:t.type===`dip-open-link`?J(t.url):t.type===`dip-picker-action`?Z(t,n):t.type===`dip-readfile`||t.type===`dip-exists`||t.type===`dip-stat`?q(a.contentWindow,t):t.type===`dip-exec`||t.type===`dip-agent`||t.type===`dip-jsh`?G(a.contentWindow,t):t.type===`dip-device-op`&&W(a.contentWindow,t))};window.addEventListener(`message`,o);let s=null;if(y()&&typeof IntersectionObserver<`u`){let e=!1,t=new IntersectionObserver(n=>{if(n[n.length-1].isIntersecting){if(e){e=!1;return}t.unobserve(a),v(a,()=>{e=!0,t.observe(a)})}});s=t,t.observe(a)}return{dispose(){s?.disconnect(),window.removeEventListener(`message`,o),b(a.contentWindow),a.contentWindow&&(L.delete(a.contentWindow),k.delete(a.contentWindow),U(a.contentWindow)),a.remove()}}}async function q(e,t){if(!e||typeof t.id!=`number`)return!1;let n=typeof t.path==`string`?t.path:``,r=n=>{try{e.postMessage({...n,id:t.id},`*`)}catch{}};if(!k.has(e))return r({type:`${t.type}-response`,error:`VFS access not allowed for this dip`}),!0;if(!O(n))return r({type:`${t.type}-response`,error:`VFS path not allowed: ${n}`}),!0;if(t.type===`dip-readfile`){let e=await D(n,!0);return e===null?(r({type:`dip-readfile-response`,error:`Read failed`}),!0):(r({type:`dip-readfile-response`,content:typeof e==`string`?e:new TextDecoder().decode(e)}),!0)}if(t.type===`dip-exists`)return r({type:`dip-exists-response`,exists:await D(n,!0)!==null}),!0;if(t.type===`dip-stat`){let e=await D(n,!1);return e===null?(r({type:`dip-stat-response`,error:`Stat failed`}),!0):(r({type:`dip-stat-response`,stat:{isFile:!0,isDirectory:!1,size:typeof e==`string`?e.length:e.byteLength,mtimeMs:0}}),!0)}return!1}function J(e){if(!(typeof e!=`string`||!e)&&/^(https?:|mailto:)/i.test(e))try{window.open(e,`_blank`,`noopener,noreferrer`)}catch{}}function Y(e,t){let n=[],r=e.querySelectorAll(`pre > code.language-shtml`);for(let e of r){let r=e.parentElement,i=e.textContent??``,a=document.createElement(`div`);a.className=`msg__dip`,r.replaceWith(a),n.push(K(a,i,t,!1))}let i=e.querySelectorAll(`img[src$=".shtml"]`);for(let e of i){let r=e.getAttribute(`src`);if(!r)continue;let i=document.createElement(`div`);i.className=`msg__dip`,e.alt&&i.setAttribute(`title`,e.alt),e.replaceWith(i);let a=new AbortController,o=null,s=!1;n.push({dispose(){s=!0,a.abort(),o&&=(o.dispose(),null)}});let c=r.startsWith(`/`),l=typeof navigator<`u`&&!!navigator.serviceWorker?.controller,u=c?`/preview${r}`:r,d=async()=>{if(c&&!l)return T(r,a.signal);let e;try{e=await fetch(u,{signal:a.signal})}catch(e){if(e?.name===`AbortError`)throw e;if(c)return T(r,a.signal);throw e}if(e.ok)return e.text();if(c)return T(r,a.signal);throw Error(`HTTP ${e.status}`)},f=c&&me(r);d().then(e=>{s||!i.isConnected||(o=K(i,e,t,f))}).catch(e=>{s||e?.name===`AbortError`||(i.textContent=`Failed to load dip: ${r}`,i.style.cssText=`padding:8px;font-size:12px;color:var(--s2-negative);font-family:var(--s2-font-mono)`)})}return n}function X(e){for(let t of e)try{t.dispose()}catch{}e.length=0}async function Z(e,t){let n=e.data??null,r=Array.isArray(n?.filters)?n.filters:[];if(w){await De(e.picker,e.action,r,t);return}switch(e.picker){case`directory`:await Oe(e.action,t);return;case`usb-device`:await ke(e.action,r,t);return;case`serial-port`:await Ae(e.action,r,t);return;case`hid-device`:await je(e.action,r,t);return;default:t(e.action,e.data);return}}async function De(e,n,r,i){try{switch(e){case`directory`:{let{openMountPickerPopup:e}=await t(async()=>{let{openMountPickerPopup:e}=await import(`./mount-picker-popup-CSSC05JS.js`).then(e=>e.n);return{openMountPickerPopup:e}},__vite__mapDeps([0,1,2,3,4])),r=await e();r.cancelled?i(n,{cancelled:!0}):r.error?i(n,{error:r.error}):r.idbKey?i(n,{handleInIdb:!0,idbKey:r.idbKey,dirName:r.dirName??``}):i(n,{error:`mount picker returned no handle key`});return}case`usb-device`:{let{openUsbPickerPopup:e}=await t(async()=>{let{openUsbPickerPopup:e}=await import(`./usb-picker-Cl6Cwuv9.js`);return{openUsbPickerPopup:e}},__vite__mapDeps([5,3,4])),a=await e(r);`cancelled`in a?i(n,{cancelled:!0}):`error`in a?i(n,{error:a.error}):i(n,{granted:!0,info:a.info});return}case`serial-port`:{let{openSerialPickerPopup:e}=await t(async()=>{let{openSerialPickerPopup:e}=await import(`./serial-picker-CUd91lje.js`);return{openSerialPickerPopup:e}},__vite__mapDeps([6,3,4])),a=await e(r);`cancelled`in a?i(n,{cancelled:!0}):`error`in a?i(n,{error:a.error}):i(n,{granted:!0,info:a.info});return}case`hid-device`:{let{openHidPickerPopup:e}=await t(async()=>{let{openHidPickerPopup:e}=await import(`./hid-picker-Bhoh8hxy.js`);return{openHidPickerPopup:e}},__vite__mapDeps([7,3,4])),a=await e(r);`cancelled`in a?i(n,{cancelled:!0}):`error`in a?i(n,{error:a.error}):i(n,{granted:!0,info:a.info});return}default:i(n,{error:`unknown picker kind: ${e??`(none)`}`});return}}catch(e){i(n,{error:e instanceof Error?e.message:String(e)})}}async function Q(e,t){let n=r();if(!n)return null;let i={current:null},a=t=>{let n=t.detail;n.kind===e&&(i.current=n)};n.addEventListener(`slicc-permission-deny`,a);try{let r=await n.request(e,t);if(r)return{ok:!0,grant:r};let a=i.current;return{ok:!1,reason:a?.reason??`error`,...a?.message?{message:a.message}:{}}}finally{n.removeEventListener(`slicc-permission-deny`,a)}}function $(e,t,n,r){if(t.reason===`cancelled`){r(e,{cancelled:!0});return}if(t.reason===`unavailable`){r(e,{error:n});return}r(e,{error:t.message??`unknown error`})}async function Oe(e,n){let r=await Q(`filesystem`);if(!r){n(e,{error:`File System Access API not available`});return}if(!r.ok){$(e,r,`File System Access API not available`,n);return}let i=r.grant.handle,a=`pendingMount:dip-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`;try{let{storePendingHandle:e}=await t(async()=>{let{storePendingHandle:e}=await import(`./mount-picker-popup-CSSC05JS.js`).then(e=>e.n);return{storePendingHandle:e}},__vite__mapDeps([0,1,2,3,4]));await e(a,i)}catch(t){n(e,{error:`failed to store directory handle: ${t instanceof Error?t.message:String(t)}`});return}n(e,{handleInIdb:!0,idbKey:a,dirName:i.name})}async function ke(e,n,r){let i=await Q(`usb`,{filters:n});if(!i){r(e,{error:`WebUSB is not available`});return}if(!i.ok){$(e,i,`WebUSB is not available`,r);return}let a=i.grant,{getSharedUsbRegistry:o,deviceToInfo:s}=await t(async()=>{let{getSharedUsbRegistry:e,deviceToInfo:t}=await import(`./usb-device-registry-CRsCisej.js`).then(e=>e.a);return{getSharedUsbRegistry:e,deviceToInfo:t}},__vite__mapDeps([8,1])),c=o().register(a.device);r(e,{granted:!0,handle:c,info:s(c,a.device)})}async function Ae(e,n,r){let i=await Q(`serial`,n.length?{filters:n}:void 0);if(!i){r(e,{error:`Web Serial is not available`});return}if(!i.ok){$(e,i,`Web Serial is not available`,r);return}let a=i.grant,o=await t(()=>import(`./serial-port-registry-B3LG5UIy.js`).then(e=>e.o),__vite__mapDeps([9,1])),s=o.getSharedSerialRegistry(),c=s.register(a.port),l=s.get(c);r(e,{granted:!0,handle:c,info:l?o.deviceToInfo(c,l):{handle:c}})}async function je(e,n,r){let i=await Q(`hid`,{filters:n});if(!i){r(e,{error:`WebHID is not available`});return}if(!i.ok){$(e,i,`WebHID is not available`,r);return}let a=i.grant,{getSharedHidRegistry:o,hidDeviceToInfo:s}=await t(async()=>{let{getSharedHidRegistry:e,hidDeviceToInfo:t}=await import(`./hid-device-registry-B2R-0rNt.js`).then(e=>e.a);return{getSharedHidRegistry:e,hidDeviceToInfo:t}},__vite__mapDeps([10,1])),c=o(),l=a.devices.map(e=>{let t=c.register(e);return s(t,e)}),u=l[0];r(e,{granted:!0,handle:u.handle,info:u,devices:l})}function Me(e,t,n,r=!1){let i=document.createElement(`iframe`);i.src=chrome.runtime.getURL(`sprinkle-sandbox.html`),i.style.cssText=`width:100%;border:none;overflow:hidden;display:block;`,e.appendChild(i);let a=e=>{if(e.source!==i.contentWindow)return;let t=e.data;t?.type&&(t.type===`dip-lick`?n(t.action,t.data):t.type===`dip-height`?i.style.height=t.height+`px`:t.type===`dip-open-link`?J(t.url):t.type===`dip-readfile`||t.type===`dip-exists`||t.type===`dip-stat`?q(i.contentWindow,t):t.type===`dip-exec`||t.type===`dip-agent`||t.type===`dip-jsh`?G(i.contentWindow,t):t.type===`dip-device-op`?W(i.contentWindow,t):t.type===`dip-picker-action`&&Z(t,n))};return window.addEventListener(`message`,a),i.addEventListener(`load`,()=>{S(i.contentWindow),i.contentWindow&&(L.add(i.contentWindow),r&&k.add(i.contentWindow)),i.contentWindow?.postMessage({type:`dip-render`,srcdoc:t,isLight:x()},`*`)},{once:!0}),{dispose(){window.removeEventListener(`message`,a),b(i.contentWindow),i.contentWindow&&(L.delete(i.contentWindow),k.delete(i.contentWindow),U(i.contentWindow)),i.remove()}}}export{K as a,Y as i,C as n,X as r,R as t};
233
+ `,exitCode:127};try{return await z(e)}catch(e){return{stdout:``,stderr:`exec: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}}async function _e(e,t){let n=await V(ge(e,t));return{stdout:n.stdout||n.stderr,exitCode:n.exitCode}}async function ve(e,t){let n=await ue(V,e,t);if(e===`fetch`){let e=n,t=atob(e.bodyBase64),r=new Uint8Array(t.length);for(let e=0;e<t.length;e++)r[e]=t.charCodeAt(e);return{...e,body:new TextDecoder(`utf-8`).decode(r)}}return n}var H=new WeakMap;function ye(e,t){try{e.postMessage({type:`dip-device-event`,channel:`hid:inputreport`,payload:t},`*`)}catch{}}async function be(e,t){let n=H.get(e);if(n||(n=new Map,H.set(e,n)),n.has(t))return;let r=await d(a(),t,n=>{let r=n.bytes instanceof Uint8Array?n.bytes:new Uint8Array(n.bytes);ye(e,{handle:t,reportId:n.reportId,data:r})});n.set(t,r)}async function xe(e,t){let n=H.get(e);if(!n)return;let r=n.get(t);if(r){n.delete(t);try{await Promise.resolve(r())}catch{}}n.size===0&&H.delete(e)}function U(e){let t=H.get(e);if(t){for(let e of t.values())try{Promise.resolve(e()).catch(()=>{})}catch{}H.delete(e)}}function Se(e){if(e instanceof Uint8Array)return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e)){let t=e;return new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}if(Array.isArray(e))return new Uint8Array(e);throw Error(`expected Uint8Array, ArrayBuffer, or number[]`)}async function Ce(e,t,n){let r=a();switch(t){case`list`:{let e=i();if(!e)throw Error(`WebHID is unavailable in this browser`);return te(r,e)}case`request`:{let e=i();if(!e)throw Error(`WebHID is unavailable in this browser`);return se(r,e,n[0]??[])}case`info`:return p(r,n[0]);case`open`:{let t=n[0];return await f(r,t),await be(e,t),{ok:!0}}case`close`:{let t=n[0];return await xe(e,t),await ne(r,t),{ok:!0}}case`sendReport`:{let e=n[0],t=n[1],i=Se(n[2]),a=i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength);return await oe(r,e,t,a),{ok:!0}}default:throw Error(`hid: unknown op '${t}'`)}}async function we(e,t){let n=o();switch(e){case`list`:{let e=s();if(!e)throw Error(`Web Serial is unavailable in this browser`);return u(n,e)}case`request`:{let e=s();if(!e)throw Error(`Web Serial is unavailable in this browser`);return m(n,e,t[0]??[])}case`info`:return ae(n,t[0]);case`open`:{let e=t[0],r=t[1]??{baudRate:9600};return await l(n,e,r),{ok:!0}}case`close`:return await c(n,t[0]),{ok:!0};default:throw Error(`serial: unknown op '${e}'`)}}async function Te(e,t){let n=ce();switch(e){case`list`:{let e=_();if(!e)throw Error(`WebUSB is unavailable in this browser`);return g(n,e)}case`request`:{let e=_();if(!e)throw Error(`WebUSB is unavailable in this browser`);return h(n,e,t[0]??[])}case`info`:return ee(n,t[0]);case`open`:return await ie(n,t[0]),{ok:!0};case`close`:return await re(n,t[0]),{ok:!0};default:throw Error(`usb: unknown op '${e}'`)}}async function Ee(e,t,n,r){switch(t){case`hid`:return Ce(e,n,r);case`serial`:return we(n,r);case`usb`:return Te(n,r);default:throw Error(`unknown device channel '${t}'`)}}async function W(e,t){if(!e||typeof t.id!=`number`)return!1;let n=n=>{try{e.postMessage({...n,id:t.id},`*`)}catch{}};if(!k.has(e))return n({type:`dip-device-op-response`,error:`device access not allowed for this dip`}),!0;let r=t.channel;if(r!==`hid`&&r!==`serial`&&r!==`usb`)return n({type:`dip-device-op-response`,error:`unknown device channel '${r}'`}),!0;try{n({type:`dip-device-op-response`,result:await Ee(e,r,typeof t.op==`string`?t.op:``,Array.isArray(t.args)?t.args:[])})}catch(e){n({type:`dip-device-op-response`,error:e instanceof Error?e.message:String(e)})}return!0}async function G(e,t){if(!e||typeof t.id!=`number`)return!1;let n=n=>{try{e.postMessage({...n,id:t.id},`*`)}catch{}};if(!k.has(e))return n({type:`${t.type}-response`,error:`exec not allowed for this dip`}),!0;if(t.type===`dip-exec`)return n({type:`dip-exec-response`,result:await V(typeof t.cmd==`string`?t.cmd:``)}),!0;if(t.type===`dip-agent`)return n({type:`dip-agent-response`,result:await _e(typeof t.prompt==`string`?t.prompt:``,t.opts)}),!0;if(t.type===`dip-jsh`){try{n({type:`dip-jsh-response`,result:await ve(typeof t.op==`string`?t.op:``,Array.isArray(t.args)?t.args:[])})}catch(e){n({type:`dip-jsh-response`,error:e instanceof Error?e.message:String(e)})}return!0}return!1}function K(e,t,n,r=!1){let i=I(t,!1,r);if(w)return Me(e,i,n,r);let a=document.createElement(`iframe`);a.setAttribute(`sandbox`,`allow-scripts allow-same-origin`),a.style.cssText=`width:100%;border:none;overflow:hidden;display:block;`,a.srcdoc=i,e.appendChild(a),a.contentWindow&&(S(a.contentWindow),L.add(a.contentWindow),r&&k.add(a.contentWindow)),a.addEventListener(`load`,()=>{S(a.contentWindow),a.contentWindow&&(L.add(a.contentWindow),r&&k.add(a.contentWindow)),y()&&v(a)},{once:!0});let o=e=>{if(e.source!==a.contentWindow)return;let t=e.data;t?.type&&(t.type===`dip-lick`?n(t.action,t.data):t.type===`dip-height`?a.style.height=t.height+`px`:t.type===`dip-open-link`?J(t.url):t.type===`dip-picker-action`?Z(t,n):t.type===`dip-readfile`||t.type===`dip-exists`||t.type===`dip-stat`?q(a.contentWindow,t):t.type===`dip-exec`||t.type===`dip-agent`||t.type===`dip-jsh`?G(a.contentWindow,t):t.type===`dip-device-op`&&W(a.contentWindow,t))};window.addEventListener(`message`,o);let s=null;if(y()&&typeof IntersectionObserver<`u`){let e=!1,t=new IntersectionObserver(n=>{if(n[n.length-1].isIntersecting){if(e){e=!1;return}t.unobserve(a),v(a,()=>{e=!0,t.observe(a)})}});s=t,t.observe(a)}return{dispose(){s?.disconnect(),window.removeEventListener(`message`,o),b(a.contentWindow),a.contentWindow&&(L.delete(a.contentWindow),k.delete(a.contentWindow),U(a.contentWindow)),a.remove()}}}async function q(e,t){if(!e||typeof t.id!=`number`)return!1;let n=typeof t.path==`string`?t.path:``,r=n=>{try{e.postMessage({...n,id:t.id},`*`)}catch{}};if(!k.has(e))return r({type:`${t.type}-response`,error:`VFS access not allowed for this dip`}),!0;if(!O(n))return r({type:`${t.type}-response`,error:`VFS path not allowed: ${n}`}),!0;if(t.type===`dip-readfile`){let e=await D(n,!0);return e===null?(r({type:`dip-readfile-response`,error:`Read failed`}),!0):(r({type:`dip-readfile-response`,content:typeof e==`string`?e:new TextDecoder().decode(e)}),!0)}if(t.type===`dip-exists`)return r({type:`dip-exists-response`,exists:await D(n,!0)!==null}),!0;if(t.type===`dip-stat`){let e=await D(n,!1);return e===null?(r({type:`dip-stat-response`,error:`Stat failed`}),!0):(r({type:`dip-stat-response`,stat:{isFile:!0,isDirectory:!1,size:typeof e==`string`?e.length:e.byteLength,mtimeMs:0}}),!0)}return!1}function J(e){if(!(typeof e!=`string`||!e)&&/^(https?:|mailto:)/i.test(e))try{window.open(e,`_blank`,`noopener,noreferrer`)}catch{}}function Y(e,t){let n=[],r=e.querySelectorAll(`pre > code.language-shtml`);for(let e of r){let r=e.parentElement,i=e.textContent??``,a=document.createElement(`div`);a.className=`msg__dip`,r.replaceWith(a),n.push(K(a,i,t,!1))}let i=e.querySelectorAll(`img[src$=".shtml"]`);for(let e of i){let r=e.getAttribute(`src`);if(!r)continue;let i=document.createElement(`div`);i.className=`msg__dip`,e.alt&&i.setAttribute(`title`,e.alt),e.replaceWith(i);let a=new AbortController,o=null,s=!1;n.push({dispose(){s=!0,a.abort(),o&&=(o.dispose(),null)}});let c=r.startsWith(`/`),l=typeof navigator<`u`&&!!navigator.serviceWorker?.controller,u=c?`/preview${r}`:r,d=async()=>{if(c&&!l)return T(r,a.signal);let e;try{e=await fetch(u,{signal:a.signal})}catch(e){if(e?.name===`AbortError`)throw e;if(c)return T(r,a.signal);throw e}if(e.ok)return e.text();if(c)return T(r,a.signal);throw Error(`HTTP ${e.status}`)},f=c&&me(r);d().then(e=>{s||!i.isConnected||(o=K(i,e,t,f))}).catch(e=>{s||e?.name===`AbortError`||(i.textContent=`Failed to load dip: ${r}`,i.style.cssText=`padding:8px;font-size:12px;color:var(--s2-negative);font-family:var(--s2-font-mono)`)})}return n}function X(e){for(let t of e)try{t.dispose()}catch{}e.length=0}async function Z(e,t){let n=e.data??null,r=Array.isArray(n?.filters)?n.filters:[];if(w){await De(e.picker,e.action,r,t);return}switch(e.picker){case`directory`:await Oe(e.action,t);return;case`usb-device`:await ke(e.action,r,t);return;case`serial-port`:await Ae(e.action,r,t);return;case`hid-device`:await je(e.action,r,t);return;default:t(e.action,e.data);return}}async function De(e,n,r,i){try{switch(e){case`directory`:{let{openMountPickerPopup:e}=await t(async()=>{let{openMountPickerPopup:e}=await import(`./mount-picker-popup-Bh-wMX4z.js`).then(e=>e.n);return{openMountPickerPopup:e}},__vite__mapDeps([0,1,2,3,4,5])),r=await e();r.cancelled?i(n,{cancelled:!0}):r.error?i(n,{error:r.error}):r.idbKey?i(n,{handleInIdb:!0,idbKey:r.idbKey,dirName:r.dirName??``}):i(n,{error:`mount picker returned no handle key`});return}case`usb-device`:{let{openUsbPickerPopup:e}=await t(async()=>{let{openUsbPickerPopup:e}=await import(`./usb-picker-Cl6Cwuv9.js`);return{openUsbPickerPopup:e}},__vite__mapDeps([6,4,5])),a=await e(r);`cancelled`in a?i(n,{cancelled:!0}):`error`in a?i(n,{error:a.error}):i(n,{granted:!0,info:a.info});return}case`serial-port`:{let{openSerialPickerPopup:e}=await t(async()=>{let{openSerialPickerPopup:e}=await import(`./serial-picker-CUd91lje.js`);return{openSerialPickerPopup:e}},__vite__mapDeps([7,4,5])),a=await e(r);`cancelled`in a?i(n,{cancelled:!0}):`error`in a?i(n,{error:a.error}):i(n,{granted:!0,info:a.info});return}case`hid-device`:{let{openHidPickerPopup:e}=await t(async()=>{let{openHidPickerPopup:e}=await import(`./hid-picker-Bhoh8hxy.js`);return{openHidPickerPopup:e}},__vite__mapDeps([8,4,5])),a=await e(r);`cancelled`in a?i(n,{cancelled:!0}):`error`in a?i(n,{error:a.error}):i(n,{granted:!0,info:a.info});return}default:i(n,{error:`unknown picker kind: ${e??`(none)`}`});return}}catch(e){i(n,{error:e instanceof Error?e.message:String(e)})}}async function Q(e,t){let n=r();if(!n)return null;let i={current:null},a=t=>{let n=t.detail;n.kind===e&&(i.current=n)};n.addEventListener(`slicc-permission-deny`,a);try{let r=await n.request(e,t);if(r)return{ok:!0,grant:r};let a=i.current;return{ok:!1,reason:a?.reason??`error`,...a?.message?{message:a.message}:{}}}finally{n.removeEventListener(`slicc-permission-deny`,a)}}function $(e,t,n,r){if(t.reason===`cancelled`){r(e,{cancelled:!0});return}if(t.reason===`unavailable`){r(e,{error:n});return}r(e,{error:t.message??`unknown error`})}async function Oe(e,n){let r=await Q(`filesystem`);if(!r){n(e,{error:`File System Access API not available`});return}if(!r.ok){$(e,r,`File System Access API not available`,n);return}let i=r.grant.handle,a=`pendingMount:dip-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`;try{let{storePendingHandle:e}=await t(async()=>{let{storePendingHandle:e}=await import(`./mount-picker-popup-Bh-wMX4z.js`).then(e=>e.n);return{storePendingHandle:e}},__vite__mapDeps([0,1,2,3,4,5]));await e(a,i)}catch(t){n(e,{error:`failed to store directory handle: ${t instanceof Error?t.message:String(t)}`});return}n(e,{handleInIdb:!0,idbKey:a,dirName:i.name})}async function ke(e,n,r){let i=await Q(`usb`,{filters:n});if(!i){r(e,{error:`WebUSB is not available`});return}if(!i.ok){$(e,i,`WebUSB is not available`,r);return}let a=i.grant,{getSharedUsbRegistry:o,deviceToInfo:s}=await t(async()=>{let{getSharedUsbRegistry:e,deviceToInfo:t}=await import(`./usb-device-registry-CRsCisej.js`).then(e=>e.a);return{getSharedUsbRegistry:e,deviceToInfo:t}},__vite__mapDeps([9,1])),c=o().register(a.device);r(e,{granted:!0,handle:c,info:s(c,a.device)})}async function Ae(e,n,r){let i=await Q(`serial`,n.length?{filters:n}:void 0);if(!i){r(e,{error:`Web Serial is not available`});return}if(!i.ok){$(e,i,`Web Serial is not available`,r);return}let a=i.grant,o=await t(()=>import(`./serial-port-registry-B3LG5UIy.js`).then(e=>e.o),__vite__mapDeps([10,1])),s=o.getSharedSerialRegistry(),c=s.register(a.port),l=s.get(c);r(e,{granted:!0,handle:c,info:l?o.deviceToInfo(c,l):{handle:c}})}async function je(e,n,r){let i=await Q(`hid`,{filters:n});if(!i){r(e,{error:`WebHID is not available`});return}if(!i.ok){$(e,i,`WebHID is not available`,r);return}let a=i.grant,{getSharedHidRegistry:o,hidDeviceToInfo:s}=await t(async()=>{let{getSharedHidRegistry:e,hidDeviceToInfo:t}=await import(`./hid-device-registry-B2R-0rNt.js`).then(e=>e.a);return{getSharedHidRegistry:e,hidDeviceToInfo:t}},__vite__mapDeps([11,1])),c=o(),l=a.devices.map(e=>{let t=c.register(e);return s(t,e)}),u=l[0];r(e,{granted:!0,handle:u.handle,info:u,devices:l})}function Me(e,t,n,r=!1){let i=document.createElement(`iframe`);i.src=chrome.runtime.getURL(`sprinkle-sandbox.html`),i.style.cssText=`width:100%;border:none;overflow:hidden;display:block;`,e.appendChild(i);let a=e=>{if(e.source!==i.contentWindow)return;let t=e.data;t?.type&&(t.type===`dip-lick`?n(t.action,t.data):t.type===`dip-height`?i.style.height=t.height+`px`:t.type===`dip-open-link`?J(t.url):t.type===`dip-readfile`||t.type===`dip-exists`||t.type===`dip-stat`?q(i.contentWindow,t):t.type===`dip-exec`||t.type===`dip-agent`||t.type===`dip-jsh`?G(i.contentWindow,t):t.type===`dip-device-op`?W(i.contentWindow,t):t.type===`dip-picker-action`&&Z(t,n))};return window.addEventListener(`message`,a),i.addEventListener(`load`,()=>{S(i.contentWindow),i.contentWindow&&(L.add(i.contentWindow),r&&k.add(i.contentWindow)),i.contentWindow?.postMessage({type:`dip-render`,srcdoc:t,isLight:x()},`*`)},{once:!0}),{dispose(){window.removeEventListener(`message`,a),b(i.contentWindow),i.contentWindow&&(L.delete(i.contentWindow),k.delete(i.contentWindow),U(i.contentWindow)),i.remove()}}}export{K as a,Y as i,C as n,X as r,R as t};
@@ -1 +1 @@
1
- import{n as e}from"./rolldown-runtime-Dd_uD5pT.js";import{t}from"./logger-LESFN7Hj.js";import{i as n,n as r,r as i,t as a}from"./path-utils-Rm3AltuN.js";import{t as o}from"./backend-local-D4WZgy4J.js";import{t as s}from"./types-idfTVsM8.js";import{a as c,i as l,n as u,t as d}from"./mount-table-store-DrF_Ifaz.js";const f=t(`fs-watcher`);let p=0;function m(e,t){return t===`/`||e===t||e.startsWith(t+`/`)}var h=class{registrations=new Map;watch(e,t,n){let r=`fsw-${++p}`;return this.registrations.set(r,{id:r,basePath:e,filter:t,callback:n}),f.debug(`Watch registered`,{id:r,basePath:e}),()=>{this.registrations.delete(r),f.debug(`Watch unregistered`,{id:r})}}notify(e){if(e.length!==0)for(let[,t]of this.registrations){let n=e.filter(e=>m(e.path,t.basePath)&&t.filter(e.path));if(n.length>0)try{t.callback(n)}catch(e){f.error(`Watch callback error`,{id:t.id,error:e instanceof Error?e.message:String(e)})}}}dispose(){this.registrations.clear(),f.debug(`All watchers disposed`)}get size(){return this.registrations.size}};const g=t(`mount-index`);var _=class extends Error{cause;constructor(e,t){super(e),this.name=`MountIndexAbortError`,this.cause=t}};function v(e){let t=e.map(([e,t])=>`${e}\u0000${t.kind}`).sort(),n=t.length>256?t.slice(0,256):t;return`${t.length}\u0001${n.join(``)}`}async function y(e,t){let n=e.isSameEntry;if(typeof n!=`function`)return!1;try{return await n.call(e,t)}catch{return!1}}function b(e,t){return e instanceof Map?e.get(t):e[t]}function x(e){let t=e.trim();if(t===``)return;let n=Number(t);if(!(!Number.isInteger(n)||n<=0))return n}function S(e,t,n){let r=b(e,t);if(r===void 0||r.trim()===``)return n;let i=x(r);return i===void 0?(g.warn(`Ignoring invalid ${t}; expected a positive integer, using default`,{value:r,fallback:n}),n):i}function C(e){return{maxDepth:S(e,`SLICC_MOUNT_INDEX_MAX_DEPTH`,400),maxEntries:S(e,`SLICC_MOUNT_INDEX_MAX_ENTRIES`,2e6)}}var w=class{mounts=new Map;listeners=new Set;registerMount(e,t,n=C({})){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,g.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 _?r.cause:`indexing-error`;t.state={status:`error`,indexed:0,error:i,abortCause:a},g.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 _(`mount indexing aborted: directory nesting exceeded ${t.limits.maxDepth} levels`,`depth-exceeded`);if(t.directories.size+t.files.size>=t.limits.maxEntries)throw new _(`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 _(`mount indexing aborted: exceeded ${n.limits.maxEntries} entries`,`entries-exceeded`);i.push(e)}return i}async confirmNoCycle(e,t,n,r){let i=v(n),a=r.get(i);if(a){for(let n of a)if(await y(n.handle,t))throw new _(`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)))}}};const T=`/dev/null`,E=new Set([T]);function D(e){return E.has(e)}const O={[T]:{stat:()=>({type:`file`,size:0,mtime:0,ctime:0}),read:e=>(e?.encoding??`utf-8`)===`utf-8`?``:new Uint8Array,readText:()=>``,write:()=>{}}};var k=class{vfs;allowedPrefixes;readOnlyPrefixes;writeEnforcement;constructor(e,t,n=[],i=`hard`){this.vfs=e;let a=e=>{let t=r(e);return t.endsWith(`/`)?t:t+`/`};this.allowedPrefixes=t.map(a),this.readOnlyPrefixes=n.map(a),this.writeEnforcement=i}getAllPrefixes(){let e=this.vfs.listMounts().map(e=>e.endsWith(`/`)?e:e+`/`);return[...this.allowedPrefixes,...this.readOnlyPrefixes,...e]}isAllowed(e){let t=r(e);return this.getAllPrefixes().some(e=>t===e.slice(0,-1)||t.startsWith(e)||t===`/`||e.startsWith(t+`/`))}isAllowedStrict(e){let t=r(e);return this.getAllPrefixes().some(e=>t===e.slice(0,-1)||t.startsWith(e))}isWritable(e){let t=r(e);return this.allowedPrefixes.some(e=>t===e.slice(0,-1)||t.startsWith(e))}canWrite(e){return this.isWritable(e)}checkWrite(e){if(this.writeEnforcement!==`sudo-delegated`&&!this.isWritable(e))throw new s(`EACCES`,`permission denied`,r(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`,r(e));return t}catch(t){throw t instanceof s?t:new s(`ENOENT`,`no such file or directory`,r(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`,r(e));return t}catch(t){throw t instanceof s?t:new s(`EACCES`,`permission denied`,r(e))}}isSymlinkEscapeAllowed(e){return!1}async checkParentRealpathEscape(e){let t=this.vfs.dirname(e),n=this.vfs.basename(e),i;try{i=await this.vfs.realpath(t)}catch(e){if(e instanceof s&&e.code===`EACCES`)throw e;return}let a=i+`/`+n;if(this.isWritable(a))return;let o=r(i)!==r(t);if(!(this.writeEnforcement===`sudo-delegated`&&!o))throw new s(`EACCES`,`permission denied`,r(e))}getUnderlyingFS(){return this.vfs}invalidatePaths(e){this.vfs.invalidatePaths(e)}isPathUnderMount(e){return this.vfs.isPathUnderMount(e)}async readFile(e,t){let n=O[r(e)];if(n)return n.read(t);if(!this.isAllowedStrict(e))throw new s(`ENOENT`,`no such file or directory`,r(e));let i=await this.resolveAndCheckRead(e);return this.vfs.readFile(i,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=r(e);return n.filter(e=>{let n=t===`/`?`/${e.name}`:`${t}/${e.name}`;return this.isAllowed(n)})}return n}async stat(e){let t=O[r(e)];if(t)return t.stat();if(!this.isAllowed(e))throw new s(`ENOENT`,`no such file or directory`,r(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=r(e);if(n===`/`)return!1;let i=n.slice(1).split(`/`),a=t?i.length:i.length-1,o=``;for(let e=0;e<a;e++){o=o+`/`+i[e];let t=this.vfs.lstatSync(o);if(t===null)return null;if(t.type===`symlink`)return!0}return!1}statSync(e){let t=O[r(e)];return t?t.stat():!this.isAllowedStrict(e)||this.scanPathForSymlinks(e,!0)!==!1?null:this.vfs.statSync(e)}lstatSync(e){let t=O[r(e)];return t?t.stat():!this.isAllowed(e)||this.scanPathForSymlinks(e,!1)!==!1?null:this.vfs.lstatSync(e)}readDirSync(e){if(!this.isAllowed(e)||this.scanPathForSymlinks(e,!0)!==!1)return null;let t=this.vfs.readDirSync(e);if(t===null)return null;if(this.isAllowedStrict(e))return t;let n=r(e);return t.filter(e=>{let t=n===`/`?`/${e.name}`:`${n}/${e.name}`;return this.isAllowed(t)})}async realpath(e){let t;try{t=await this.vfs.realpath(e)}catch(t){throw t instanceof s?t:new s(`ENOENT`,`no such file or directory`,r(e))}if(!this.isAllowedStrict(t))throw new s(`ENOENT`,`no such file or directory`,r(e));return t}async exists(e){if(O[r(e)])return!0;if(!this.isAllowed(e))return!1;if(this.isAllowedStrict(e))try{await this.resolveAndCheckRead(e)}catch{return!1}return this.vfs.exists(e)}async readTextFile(e){let t=O[r(e)];if(t)return t.readText();if(!this.isAllowedStrict(e))throw new s(`ENOENT`,`no such file or directory`,r(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 i=O[r(e)];if(i){i.write(t);return}this.checkWrite(e),await this.checkParentRealpathEscape(e);try{(await this.vfs.lstat(e)).type===`symlink`&&await this.resolveAndCheckWrite(e)}catch(e){if(e instanceof s&&e.code===`EACCES`)throw e}return this.vfs.writeFile(e,t,n)}async mkdir(e,t){return this.checkWrite(e),await this.checkParentRealpathEscape(e),this.vfs.mkdir(e,t)}async rm(e,t){this.checkWrite(e);try{(await this.vfs.lstat(e)).type===`symlink`||await this.resolveAndCheckWrite(e)}catch(e){if(e instanceof s&&e.code===`EACCES`)throw e}return this.vfs.rm(e,t)}async rename(e,t){return this.checkWrite(e),this.checkWrite(t),await this.resolveAndCheckWrite(e),await this.checkParentRealpathEscape(t),this.vfs.rename(e,t)}async copyFile(e,t){if(!this.isAllowed(e))throw new s(`ENOENT`,`no such file or directory`,r(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.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`,r(e));let t=await this.vfs.readlink(e),n;if(t.startsWith(`/`))n=r(t);else{let i=this.vfs.dirname(e);n=r(i+`/`+t)}if(!this.isAllowedStrict(n))throw new s(`ENOENT`,`no such file or directory`,r(e));return t}async lstat(e){let t=O[r(e)];if(t)return t.stat();if(!this.isAllowed(e))throw new s(`ENOENT`,`no such file or directory`,r(e));let n=r(e),i=this.vfs.dirname(n),a=this.vfs.basename(n),o;if(i===n)o=i;else try{o=await this.vfs.realpath(i)}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`,r(e));let i=this.vfs.getWatcher();if(!i)throw new s(`EINVAL`,`no watcher configured`);return i.watch(r(e),t,n)}dirname(e){return this.vfs.dirname(e)}basename(e){return this.vfs.basename(e)}async mount(e,t,n){return this.checkWrite(e),await this.checkParentRealpathEscape(e),this.vfs.mount(e,t,n)}async unmount(e){return this.checkWrite(e),await this.checkParentRealpathEscape(e),this.vfs.unmount(e)}listMounts(){return this.vfs.listMounts()}getMountIndex(){return this.vfs.getMountIndex()}async refreshMount(e,t){return this.checkWrite(e),this.vfs.refreshMount(e,t)}async dispose(){await this.vfs.dispose()}};function 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`,`EIO`];function M(e,t){if(e instanceof s)return e;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 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,t){return e===t||e.startsWith(t===`/`?`/`:`${t}/`)}function P(e,t,n){let r=t.entries??{},i={...e.entries??{}};`/`in r&&(i[`/`]=r[`/`]);for(let e of n.paths)e in r?i[e]=r[e]:delete i[e];for(let e of n.prefixes){for(let t of Object.keys(i))N(t,e)&&delete i[t];for(let t of Object.keys(r))N(t,e)&&(i[t]=r[t])}let{entries:a,...o}=t;return{...o,entries:i}}async function F(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 I(e,t,i){let o;try{o=await e.readlink(t)}catch(e){throw M(e,i)}return o.startsWith(`/`)?r(o):r(a(n(t).dir,o))}async function L(e,t,n,r,i,a){let o=t===`/`?`/${n}`:`${t}/${n}`;for(;;){let t=await F(e,o,r,i);if(t===null||!t.isSymbolicLink())return{resolved:o,hops:a};if(++a>10)throw new s(`ELOOP`,`too many symbolic links encountered`,i);o=await I(e,o,i)}}async function R(e,t,n){let i=r(n);if(t(i))return i;let a=i.split(`/`).filter(Boolean),o=`/`,s=0;for(let t=0;t<a.length;t++){let n=await L(e,o,a[t],t===a.length-1,i,s);o=n.resolved,s=n.hops}return o}async function z(e,t,n){return t(n)?n:R(e,t,n)}function B(e,t,n){return e.size===0||!e.has(n)||!t.isReady(n)?!1:!Array.from(e.keys()).some(e=>e!==n&&e.startsWith(n+`/`))}async function V(e,t){try{return await e(t)}catch{return t}}async function*H(e,t,n,i=0){let a=r(t);if(B(e.mountPoints,e.mountIndex,a)){let t=e.mountIndex.getFiles(a);if(t){for(let e of t)yield e;return}}let o=n??new Set;if(i>64||o.size>=1e5)return;let s=await V(t=>e.realpath(t),a);if(o.has(s))return;o.add(s);let c=await e.readDir(a);for(let t of c)yield*U(e,t,a===`/`?`/${t.name}`:`${a}/${t.name}`,o,i+1)}async function*U(e,t,n,r,i){if(t.type===`file`){yield n;return}if(t.type===`symlink`){yield*W(e,n,r,i);return}yield*H(e,n,r,i)}async function*W(e,t,n,r){try{let i=await e.stat(t);i.type===`file`?yield t:i.type===`directory`&&(yield*H(e,t,n,r))}catch{}}function G(){try{if(typeof globalThis.navigator?.storage?.getDirectory==`function`)return`opfs`}catch{}return`memory`}var K=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 w;static writeChains=new Map;constructor(t,n,r,i){if(this.dbName=t,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).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-4adALD4z.js`).then(e=>e.t),import(`./dist-sUBuiXIF.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-DVW7uarV.js`),u=await r(n,()=>t.withWriteLock(()=>l(i)),e=>console.warn(`[virtual-fs] repaired poisoned metadata sidecar; retrying mount`,{dbName:t.dbName,kindFixed:e.kindFixed,sizesFixed:e.sizesFixed,dropped:e.dropped}));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-4adALD4z.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??G(),a=new e(n,r,i);return await a._ready,r&&await d().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&&(a=P(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())}markSidecarDirty(t,i=`path`){if(this.backend!==`opfs`)return;let a=e.opfsBackends.get(this.dbName)?.sidecarDirty;if(!a)return;let o=r(t);(i===`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=r(n);t.index.delete(e),t._handles?.delete(e),this.markSidecarDirty(e)}}canWrite(e){return!0}setWatcher(e){this.watcher=e}getWatcher(){return this.watcher}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-4adALD4z.js`).then(e=>e.t)).umount(this.mountRoot)}catch{}}}}readDirSync(e){let t=r(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=r(e);if(this.findMount(t))return null;let i=this.lfsSync;if(typeof i.statSync!=`function`||typeof i.lstatSync!=`function`||typeof i.readlinkSync!=`function`)return null;let o=t;for(let e=0;e<=10;e++){let e;try{e=i.lstatSync(o)}catch{return null}if(!e.isSymbolicLink())return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs};let t;try{t=i.readlinkSync(o)}catch{return null}o=t.startsWith(`/`)?r(t):r(a(n(o).dir,t))}return null}lstatSync(e){let t=r(e);if(this.findMount(t))return null;let n=this.lfsSync;if(typeof n.lstatSync!=`function`)return null;try{let e=n.lstatSync(t);if(e.isSymbolicLink()){let r=n.readlinkSync?n.readlinkSync(t):``;return{type:`symlink`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,isSymlink:!0,symlinkTarget:r}}return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs}}catch{return null}}async mount(e,t,i){let a=r(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=C(i?.env??{});this.mountIndex.registerMount(a,t.getHandle(),e)}let l=t.kind===`local`?{kind:`local`,mountId:t.mountId,idbHandleKey:a}:t.kind===`s3`?{kind:`s3`,mountId:t.mountId,source:t.source,profile:t.profile??`default`}:{kind:`da`,mountId:t.mountId,source:t.source,profile:t.profile??`default`};try{this.mountSyncChannel?.postMessage({type:`mount`,path:a,descriptor:l})}catch{}this.watcher?.notify([{type:`modify`,path:a,entryType:`directory`}]);try{let e={targetPath:a,descriptor:l,createdAt:Date.now()},n=t.kind===`local`?t.getHandle():void 0;await c(e,n)}catch{}}async unmount(e){let t=r(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 l(t)}catch{}}async reconstructBackendFromDescriptor(e){switch(e.kind){case`local`:{let t=await u(e.idbHandleKey);if(!t)throw Error(`no handle stored for ${e.idbHandleKey}`);return o.fromHandle(t,{mountId:e.mountId})}case`s3`:{let{S3MountBackend:t,RemoteMountCache:n,makeSignedFetchS3:r}=await import(`./mount-C3eFehs3.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-C3eFehs3.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 i=r(e);if(this.mountPoints.has(i))throw new s(`EEXIST`,`mount point is already mounted`,i);let{dir:a}=n(i);a!==`/`&&await this.mkdir(a,{recursive:!0});try{await this.lfs.mkdir(i)}catch{}this.mountPoints.set(i,t),this.internalMounts.add(i),this.watcher?.notify([{type:`modify`,path:i,entryType:`directory`}])}async unmountInternal(e){let t=r(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=r(e),i=this.mountPoints.get(n);if(!i)throw new s(`ENOENT`,`not a mount point`,n);let a=await i.refresh(t);return i.kind===`local`&&await this.mountIndex.refreshMount(n,C(t?.env??{})),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){let n=r(e),i=this.findMount(n);if(i){if(i.relParts.length===0)throw new s(`EISDIR`,`is a directory`,n);let e=i.relParts.join(`/`);try{let n=await i.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,i){let a=r(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=r(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){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=``;for(let e of t){n+=`/`+e;try{await this.lfs.mkdir(n)}catch(e){if(e instanceof Error&&!e.message.includes(`EEXIST`))throw M(e,n)}}}async mkdir(e,t){let n=r(e);if(n===`/`)return;let i=this.findMount(n);if(i){if(i.relParts.length===0)return;let e=i.relParts.join(`/`),t=await this.exists(n);try{await i.backend.mkdir(e)}catch(e){A(e,n)}t||this.watcher?.notify([{type:`create`,path:n,entryType:`directory`}]);return}t?.recursive?await this.withWriteLock(()=>(this.markSidecarDirty(n),this.mkdirRecursiveUnlocked(n))):(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){let n=r(e),i=this.findMount(n);if(i){if(i.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 r=i.relParts.join(`/`);try{await i.backend.remove(r,{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){let t=r(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 i=await this.resolveSymlinks(t);try{let e=await this.lfs.stat(i);return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs}}catch(e){throw M(e,t)}}async exists(e){let t=r(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){let n=r(e),i=r(t),a;try{a=(await this.lstat(n)).type}catch{}try{await this.withWriteLock(async()=>{this.markSidecarDirty(n,`prefix`),this.markSidecarDirty(i,`prefix`),await this.lfs.rename(n,i),await this.writeOpfsMetadataSidecarUnlocked()})}catch(e){throw M(e,n)}this.watcher?.notify([{type:`delete`,path:n,entryType:a},{type:`create`,path:i,entryType:a}]),this.mountIndex.notifyRename(n,i)}async readTextFile(e){return await this.readFile(e,{encoding:`utf-8`})}async*walk(e,t,n=0){yield*H({mountPoints:this.mountPoints,mountIndex:this.mountIndex,realpath:e=>this.realpath(e),readDir:e=>this.readDir(e),stat:e=>this.stat(e)},e,t,n)}async copyFile(e,t){if((await this.stat(e)).type===`directory`)throw new s(`EISDIR`,`is a directory`,e);let n=await this.readFile(e,{encoding:`binary`});await this.writeFile(t,n)}dirname(e){return n(r(e)).dir}basename(e){return n(r(e)).base}async symlink(e,t){let i=r(t);if(this.findMount(i))throw new s(`EINVAL`,`symlinks not supported on mounted filesystems`,i);let{dir:a}=n(i);await this.withWriteLock(async()=>{a!==`/`&&await this.mkdirRecursiveUnlocked(a);try{await this.lfs.symlink(e,i)}catch(t){if(a!==`/`&&t instanceof Error&&t.message.includes(`ENOENT`)){await this.mkdirRecursiveUnlocked(a);try{await this.lfs.symlink(e,i)}catch(e){throw M(e,i)}}else throw M(t,i)}this.markSidecarDirty(i),await this.writeOpfsMetadataSidecarUnlocked()}),this.watcher?.notify([{type:`create`,path:i,entryType:`symlink`}])}async readlink(e){let t=r(e);try{return await this.lfs.readlink(t)}catch(e){throw M(e,t)}}async lstat(e){let t=r(e);if(this.findMount(t))return this.stat(t);try{let e=await this.lfs.lstat(t);if(e.isSymbolicLink()){let n=await this.lfs.readlink(t);return{type:`symlink`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,isSymlink:!0,symlinkTarget:n}}return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs}}catch(e){throw M(e,t)}}async realpath(e){return R(this.lfs,e=>this.findMount(e)!==null,e)}resolveSymlinks(e){return z(this.lfs,e=>this.findMount(e)!==null,e)}},q=e({FsError:()=>s,FsWatcher:()=>h,MountIndex:()=>w,RestrictedFS:()=>k,VirtualFS:()=>K,joinPath:()=>a,normalizePath:()=>r,pathSegments:()=>i,resolveVfsBackendFromEnv:()=>G,splitPath:()=>n});export{h as a,D as i,K as n,k as r,q as t};
1
+ import{n as e}from"./rolldown-runtime-Dd_uD5pT.js";import{t}from"./logger-LESFN7Hj.js";import{i as n,n as r,r as i,t as a}from"./path-utils-Rm3AltuN.js";import{t as o}from"./backend-local-rrSF0A3j.js";import{t as s}from"./types-idfTVsM8.js";import{a as c,i as l,n as u,t as d}from"./mount-table-store-DrF_Ifaz.js";const f=t(`fs-watcher`);let p=0;function m(e,t){return t===`/`||e===t||e.startsWith(t+`/`)}var h=class{registrations=new Map;watch(e,t,n){let r=`fsw-${++p}`;return this.registrations.set(r,{id:r,basePath:e,filter:t,callback:n}),f.debug(`Watch registered`,{id:r,basePath:e}),()=>{this.registrations.delete(r),f.debug(`Watch unregistered`,{id:r})}}notify(e){if(e.length!==0)for(let[,t]of this.registrations){let n=e.filter(e=>m(e.path,t.basePath)&&t.filter(e.path));if(n.length>0)try{t.callback(n)}catch(e){f.error(`Watch callback error`,{id:t.id,error:e instanceof Error?e.message:String(e)})}}}dispose(){this.registrations.clear(),f.debug(`All watchers disposed`)}get size(){return this.registrations.size}};const g=t(`mount-index`);var _=class extends Error{cause;constructor(e,t){super(e),this.name=`MountIndexAbortError`,this.cause=t}};function v(e){let t=e.map(([e,t])=>`${e}\u0000${t.kind}`).sort(),n=t.length>256?t.slice(0,256):t;return`${t.length}\u0001${n.join(``)}`}async function y(e,t){let n=e.isSameEntry;if(typeof n!=`function`)return!1;try{return await n.call(e,t)}catch{return!1}}function b(e,t){return e instanceof Map?e.get(t):e[t]}function x(e){let t=e.trim();if(t===``)return;let n=Number(t);if(!(!Number.isInteger(n)||n<=0))return n}function S(e,t,n){let r=b(e,t);if(r===void 0||r.trim()===``)return n;let i=x(r);return i===void 0?(g.warn(`Ignoring invalid ${t}; expected a positive integer, using default`,{value:r,fallback:n}),n):i}function C(e){return{maxDepth:S(e,`SLICC_MOUNT_INDEX_MAX_DEPTH`,400),maxEntries:S(e,`SLICC_MOUNT_INDEX_MAX_ENTRIES`,2e6)}}var w=class{mounts=new Map;listeners=new Set;registerMount(e,t,n=C({})){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,g.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 _?r.cause:`indexing-error`;t.state={status:`error`,indexed:0,error:i,abortCause:a},g.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 _(`mount indexing aborted: directory nesting exceeded ${t.limits.maxDepth} levels`,`depth-exceeded`);if(t.directories.size+t.files.size>=t.limits.maxEntries)throw new _(`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 _(`mount indexing aborted: exceeded ${n.limits.maxEntries} entries`,`entries-exceeded`);i.push(e)}return i}async confirmNoCycle(e,t,n,r){let i=v(n),a=r.get(i);if(a){for(let n of a)if(await y(n.handle,t))throw new _(`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)))}}};const T=`/dev/null`,E=new Set([T]);function D(e){return E.has(e)}const O={[T]:{stat:()=>({type:`file`,size:0,mtime:0,ctime:0}),read:e=>(e?.encoding??`utf-8`)===`utf-8`?``:new Uint8Array,readText:()=>``,write:()=>{}}};var k=class{vfs;allowedPrefixes;readOnlyPrefixes;writeEnforcement;constructor(e,t,n=[],i=`hard`){this.vfs=e;let a=e=>{let t=r(e);return t.endsWith(`/`)?t:t+`/`};this.allowedPrefixes=t.map(a),this.readOnlyPrefixes=n.map(a),this.writeEnforcement=i}getAllPrefixes(){let e=this.vfs.listMounts().map(e=>e.endsWith(`/`)?e:e+`/`);return[...this.allowedPrefixes,...this.readOnlyPrefixes,...e]}isAllowed(e){let t=r(e);return this.getAllPrefixes().some(e=>t===e.slice(0,-1)||t.startsWith(e)||t===`/`||e.startsWith(t+`/`))}isAllowedStrict(e){let t=r(e);return this.getAllPrefixes().some(e=>t===e.slice(0,-1)||t.startsWith(e))}isWritable(e){let t=r(e);return this.allowedPrefixes.some(e=>t===e.slice(0,-1)||t.startsWith(e))}canWrite(e){return this.isWritable(e)}checkWrite(e){if(this.writeEnforcement!==`sudo-delegated`&&!this.isWritable(e))throw new s(`EACCES`,`permission denied`,r(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`,r(e));return t}catch(t){throw t instanceof s?t:new s(`ENOENT`,`no such file or directory`,r(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`,r(e));return t}catch(t){throw t instanceof s?t:new s(`EACCES`,`permission denied`,r(e))}}isSymlinkEscapeAllowed(e){return!1}async checkParentRealpathEscape(e){let t=this.vfs.dirname(e),n=this.vfs.basename(e),i;try{i=await this.vfs.realpath(t)}catch(e){if(e instanceof s&&e.code===`EACCES`)throw e;return}let a=i+`/`+n;if(this.isWritable(a))return;let o=r(i)!==r(t);if(!(this.writeEnforcement===`sudo-delegated`&&!o))throw new s(`EACCES`,`permission denied`,r(e))}getUnderlyingFS(){return this.vfs}invalidatePaths(e){this.vfs.invalidatePaths(e)}isPathUnderMount(e){return this.vfs.isPathUnderMount(e)}async readFile(e,t){let n=O[r(e)];if(n)return n.read(t);if(!this.isAllowedStrict(e))throw new s(`ENOENT`,`no such file or directory`,r(e));let i=await this.resolveAndCheckRead(e);return this.vfs.readFile(i,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=r(e);return n.filter(e=>{let n=t===`/`?`/${e.name}`:`${t}/${e.name}`;return this.isAllowed(n)})}return n}async stat(e){let t=O[r(e)];if(t)return t.stat();if(!this.isAllowed(e))throw new s(`ENOENT`,`no such file or directory`,r(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=r(e);if(n===`/`)return!1;let i=n.slice(1).split(`/`),a=t?i.length:i.length-1,o=``;for(let e=0;e<a;e++){o=o+`/`+i[e];let t=this.vfs.lstatSync(o);if(t===null)return null;if(t.type===`symlink`)return!0}return!1}statSync(e){let t=O[r(e)];return t?t.stat():!this.isAllowedStrict(e)||this.scanPathForSymlinks(e,!0)!==!1?null:this.vfs.statSync(e)}lstatSync(e){let t=O[r(e)];return t?t.stat():!this.isAllowed(e)||this.scanPathForSymlinks(e,!1)!==!1?null:this.vfs.lstatSync(e)}readDirSync(e){if(!this.isAllowed(e)||this.scanPathForSymlinks(e,!0)!==!1)return null;let t=this.vfs.readDirSync(e);if(t===null)return null;if(this.isAllowedStrict(e))return t;let n=r(e);return t.filter(e=>{let t=n===`/`?`/${e.name}`:`${n}/${e.name}`;return this.isAllowed(t)})}async realpath(e){let t;try{t=await this.vfs.realpath(e)}catch(t){throw t instanceof s?t:new s(`ENOENT`,`no such file or directory`,r(e))}if(!this.isAllowedStrict(t))throw new s(`ENOENT`,`no such file or directory`,r(e));return t}async exists(e){if(O[r(e)])return!0;if(!this.isAllowed(e))return!1;if(this.isAllowedStrict(e))try{await this.resolveAndCheckRead(e)}catch{return!1}return this.vfs.exists(e)}async readTextFile(e){let t=O[r(e)];if(t)return t.readText();if(!this.isAllowedStrict(e))throw new s(`ENOENT`,`no such file or directory`,r(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 i=O[r(e)];if(i){i.write(t);return}this.checkWrite(e),await this.checkParentRealpathEscape(e);try{(await this.vfs.lstat(e)).type===`symlink`&&await this.resolveAndCheckWrite(e)}catch(e){if(e instanceof s&&e.code===`EACCES`)throw e}return this.vfs.writeFile(e,t,n)}async mkdir(e,t){return this.checkWrite(e),await this.checkParentRealpathEscape(e),this.vfs.mkdir(e,t)}async rm(e,t){this.checkWrite(e);try{(await this.vfs.lstat(e)).type===`symlink`||await this.resolveAndCheckWrite(e)}catch(e){if(e instanceof s&&e.code===`EACCES`)throw e}return this.vfs.rm(e,t)}async rename(e,t){return this.checkWrite(e),this.checkWrite(t),await this.resolveAndCheckWrite(e),await this.checkParentRealpathEscape(t),this.vfs.rename(e,t)}async copyFile(e,t){if(!this.isAllowed(e))throw new s(`ENOENT`,`no such file or directory`,r(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.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`,r(e));let t=await this.vfs.readlink(e),n;if(t.startsWith(`/`))n=r(t);else{let i=this.vfs.dirname(e);n=r(i+`/`+t)}if(!this.isAllowedStrict(n))throw new s(`ENOENT`,`no such file or directory`,r(e));return t}async lstat(e){let t=O[r(e)];if(t)return t.stat();if(!this.isAllowed(e))throw new s(`ENOENT`,`no such file or directory`,r(e));let n=r(e),i=this.vfs.dirname(n),a=this.vfs.basename(n),o;if(i===n)o=i;else try{o=await this.vfs.realpath(i)}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`,r(e));let i=this.vfs.getWatcher();if(!i)throw new s(`EINVAL`,`no watcher configured`);return i.watch(r(e),t,n)}dirname(e){return this.vfs.dirname(e)}basename(e){return this.vfs.basename(e)}async mount(e,t,n){return this.checkWrite(e),await this.checkParentRealpathEscape(e),this.vfs.mount(e,t,n)}async unmount(e){return this.checkWrite(e),await this.checkParentRealpathEscape(e),this.vfs.unmount(e)}listMounts(){return this.vfs.listMounts()}getMountIndex(){return this.vfs.getMountIndex()}async refreshMount(e,t){return this.checkWrite(e),this.vfs.refreshMount(e,t)}async dispose(){await this.vfs.dispose()}};function 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`,`EIO`];function M(e,t){if(e instanceof s)return e;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 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,t){return e===t||e.startsWith(t===`/`?`/`:`${t}/`)}function P(e,t,n){let r=t.entries??{},i={...e.entries??{}};`/`in r&&(i[`/`]=r[`/`]);for(let e of n.paths)e in r?i[e]=r[e]:delete i[e];for(let e of n.prefixes){for(let t of Object.keys(i))N(t,e)&&delete i[t];for(let t of Object.keys(r))N(t,e)&&(i[t]=r[t])}let{entries:a,...o}=t;return{...o,entries:i}}async function F(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 I(e,t,i){let o;try{o=await e.readlink(t)}catch(e){throw M(e,i)}return o.startsWith(`/`)?r(o):r(a(n(t).dir,o))}async function L(e,t,n,r,i,a){let o=t===`/`?`/${n}`:`${t}/${n}`;for(;;){let t=await F(e,o,r,i);if(t===null||!t.isSymbolicLink())return{resolved:o,hops:a};if(++a>10)throw new s(`ELOOP`,`too many symbolic links encountered`,i);o=await I(e,o,i)}}async function R(e,t,n){let i=r(n);if(t(i))return i;let a=i.split(`/`).filter(Boolean),o=`/`,s=0;for(let t=0;t<a.length;t++){let n=await L(e,o,a[t],t===a.length-1,i,s);o=n.resolved,s=n.hops}return o}async function z(e,t,n){return t(n)?n:R(e,t,n)}function B(e,t,n){return e.size===0||!e.has(n)||!t.isReady(n)?!1:!Array.from(e.keys()).some(e=>e!==n&&e.startsWith(n+`/`))}async function V(e,t){try{return await e(t)}catch{return t}}async function*H(e,t,n,i=0){let a=r(t);if(B(e.mountPoints,e.mountIndex,a)){let t=e.mountIndex.getFiles(a);if(t){for(let e of t)yield e;return}}let o=n??new Set;if(i>64||o.size>=1e5)return;let s=await V(t=>e.realpath(t),a);if(o.has(s))return;o.add(s);let c=await e.readDir(a);for(let t of c)yield*U(e,t,a===`/`?`/${t.name}`:`${a}/${t.name}`,o,i+1)}async function*U(e,t,n,r,i){if(t.type===`file`){yield n;return}if(t.type===`symlink`){yield*W(e,n,r,i);return}yield*H(e,n,r,i)}async function*W(e,t,n,r){try{let i=await e.stat(t);i.type===`file`?yield t:i.type===`directory`&&(yield*H(e,t,n,r))}catch{}}function G(){try{if(typeof globalThis.navigator?.storage?.getDirectory==`function`)return`opfs`}catch{}return`memory`}var K=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 w;static writeChains=new Map;constructor(t,n,r,i){if(this.dbName=t,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).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-4adALD4z.js`).then(e=>e.t),import(`./dist-sUBuiXIF.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-DVW7uarV.js`),u=await r(n,()=>t.withWriteLock(()=>l(i)),e=>console.warn(`[virtual-fs] repaired poisoned metadata sidecar; retrying mount`,{dbName:t.dbName,kindFixed:e.kindFixed,sizesFixed:e.sizesFixed,dropped:e.dropped}));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-4adALD4z.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??G(),a=new e(n,r,i);return await a._ready,r&&await d().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&&(a=P(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())}markSidecarDirty(t,i=`path`){if(this.backend!==`opfs`)return;let a=e.opfsBackends.get(this.dbName)?.sidecarDirty;if(!a)return;let o=r(t);(i===`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=r(n);t.index.delete(e),t._handles?.delete(e),this.markSidecarDirty(e)}}canWrite(e){return!0}setWatcher(e){this.watcher=e}getWatcher(){return this.watcher}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-4adALD4z.js`).then(e=>e.t)).umount(this.mountRoot)}catch{}}}}readDirSync(e){let t=r(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=r(e);if(this.findMount(t))return null;let i=this.lfsSync;if(typeof i.statSync!=`function`||typeof i.lstatSync!=`function`||typeof i.readlinkSync!=`function`)return null;let o=t;for(let e=0;e<=10;e++){let e;try{e=i.lstatSync(o)}catch{return null}if(!e.isSymbolicLink())return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs};let t;try{t=i.readlinkSync(o)}catch{return null}o=t.startsWith(`/`)?r(t):r(a(n(o).dir,t))}return null}lstatSync(e){let t=r(e);if(this.findMount(t))return null;let n=this.lfsSync;if(typeof n.lstatSync!=`function`)return null;try{let e=n.lstatSync(t);if(e.isSymbolicLink()){let r=n.readlinkSync?n.readlinkSync(t):``;return{type:`symlink`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,isSymlink:!0,symlinkTarget:r}}return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs}}catch{return null}}async mount(e,t,i){let a=r(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=C(i?.env??{});this.mountIndex.registerMount(a,t.getHandle(),e)}let l=t.kind===`local`?{kind:`local`,mountId:t.mountId,idbHandleKey:a}:t.kind===`s3`?{kind:`s3`,mountId:t.mountId,source:t.source,profile:t.profile??`default`}:{kind:`da`,mountId:t.mountId,source:t.source,profile:t.profile??`default`};try{this.mountSyncChannel?.postMessage({type:`mount`,path:a,descriptor:l})}catch{}this.watcher?.notify([{type:`modify`,path:a,entryType:`directory`}]);try{let e={targetPath:a,descriptor:l,createdAt:Date.now()},n=t.kind===`local`?t.getHandle():void 0;await c(e,n)}catch{}}async unmount(e){let t=r(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 l(t)}catch{}}async reconstructBackendFromDescriptor(e){switch(e.kind){case`local`:{let t=await u(e.idbHandleKey);if(!t)throw Error(`no handle stored for ${e.idbHandleKey}`);return o.fromHandle(t,{mountId:e.mountId})}case`s3`:{let{S3MountBackend:t,RemoteMountCache:n,makeSignedFetchS3:r}=await import(`./mount-C-4-Mnur.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-C-4-Mnur.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 i=r(e);if(this.mountPoints.has(i))throw new s(`EEXIST`,`mount point is already mounted`,i);let{dir:a}=n(i);a!==`/`&&await this.mkdir(a,{recursive:!0});try{await this.lfs.mkdir(i)}catch{}this.mountPoints.set(i,t),this.internalMounts.add(i),this.watcher?.notify([{type:`modify`,path:i,entryType:`directory`}])}async unmountInternal(e){let t=r(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=r(e),i=this.mountPoints.get(n);if(!i)throw new s(`ENOENT`,`not a mount point`,n);let a=await i.refresh(t);return i.kind===`local`&&await this.mountIndex.refreshMount(n,C(t?.env??{})),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){let n=r(e),i=this.findMount(n);if(i){if(i.relParts.length===0)throw new s(`EISDIR`,`is a directory`,n);let e=i.relParts.join(`/`);try{let n=await i.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,i){let a=r(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=r(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){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=``;for(let e of t){n+=`/`+e;try{await this.lfs.mkdir(n)}catch(e){if(e instanceof Error&&!e.message.includes(`EEXIST`))throw M(e,n)}}}async mkdir(e,t){let n=r(e);if(n===`/`)return;let i=this.findMount(n);if(i){if(i.relParts.length===0)return;let e=i.relParts.join(`/`),t=await this.exists(n);try{await i.backend.mkdir(e)}catch(e){A(e,n)}t||this.watcher?.notify([{type:`create`,path:n,entryType:`directory`}]);return}t?.recursive?await this.withWriteLock(()=>(this.markSidecarDirty(n),this.mkdirRecursiveUnlocked(n))):(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){let n=r(e),i=this.findMount(n);if(i){if(i.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 r=i.relParts.join(`/`);try{await i.backend.remove(r,{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){let t=r(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 i=await this.resolveSymlinks(t);try{let e=await this.lfs.stat(i);return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs}}catch(e){throw M(e,t)}}async exists(e){let t=r(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){let n=r(e),i=r(t),a;try{a=(await this.lstat(n)).type}catch{}try{await this.withWriteLock(async()=>{this.markSidecarDirty(n,`prefix`),this.markSidecarDirty(i,`prefix`),await this.lfs.rename(n,i),await this.writeOpfsMetadataSidecarUnlocked()})}catch(e){throw M(e,n)}this.watcher?.notify([{type:`delete`,path:n,entryType:a},{type:`create`,path:i,entryType:a}]),this.mountIndex.notifyRename(n,i)}async readTextFile(e){return await this.readFile(e,{encoding:`utf-8`})}async*walk(e,t,n=0){yield*H({mountPoints:this.mountPoints,mountIndex:this.mountIndex,realpath:e=>this.realpath(e),readDir:e=>this.readDir(e),stat:e=>this.stat(e)},e,t,n)}async copyFile(e,t){if((await this.stat(e)).type===`directory`)throw new s(`EISDIR`,`is a directory`,e);let n=await this.readFile(e,{encoding:`binary`});await this.writeFile(t,n)}dirname(e){return n(r(e)).dir}basename(e){return n(r(e)).base}async symlink(e,t){let i=r(t);if(this.findMount(i))throw new s(`EINVAL`,`symlinks not supported on mounted filesystems`,i);let{dir:a}=n(i);await this.withWriteLock(async()=>{a!==`/`&&await this.mkdirRecursiveUnlocked(a);try{await this.lfs.symlink(e,i)}catch(t){if(a!==`/`&&t instanceof Error&&t.message.includes(`ENOENT`)){await this.mkdirRecursiveUnlocked(a);try{await this.lfs.symlink(e,i)}catch(e){throw M(e,i)}}else throw M(t,i)}this.markSidecarDirty(i),await this.writeOpfsMetadataSidecarUnlocked()}),this.watcher?.notify([{type:`create`,path:i,entryType:`symlink`}])}async readlink(e){let t=r(e);try{return await this.lfs.readlink(t)}catch(e){throw M(e,t)}}async lstat(e){let t=r(e);if(this.findMount(t))return this.stat(t);try{let e=await this.lfs.lstat(t);if(e.isSymbolicLink()){let n=await this.lfs.readlink(t);return{type:`symlink`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,isSymlink:!0,symlinkTarget:n}}return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs}}catch(e){throw M(e,t)}}async realpath(e){return R(this.lfs,e=>this.findMount(e)!==null,e)}resolveSymlinks(e){return z(this.lfs,e=>this.findMount(e)!==null,e)}},q=e({FsError:()=>s,FsWatcher:()=>h,MountIndex:()=>w,RestrictedFS:()=>k,VirtualFS:()=>K,joinPath:()=>a,normalizePath:()=>r,pathSegments:()=>i,resolveVfsBackendFromEnv:()=>G,splitPath:()=>n});export{h as a,D as i,K as n,k as r,q as t};
@@ -1,2 +1,2 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/dist-CoWnU-QN.js","assets/rolldown-runtime-Dd_uD5pT.js","assets/dist-Ca06zVsb.js","assets/mount-DB6C8U3-.js","assets/preload-helper-Czpn1I53.js","assets/mime-types-ugOWOUZ9.js","assets/base64-DpPqYZJF.js","assets/src-CAWTvdAa.js","assets/proxied-fetch-ULPrH97b.js","assets/runtime-env-DH4NDw4t.js","assets/fetch-body-D2PwksUW.js","assets/types-idfTVsM8.js","assets/backend-local-Btkv66jT.js","assets/tool-ui-DfXu6quJ.js","assets/logger-DDBAeTLF.js","assets/picker-approval-CdWaB1mR.js","assets/mount-picker-popup-CSSC05JS.js","assets/picker-popup-BvzmBsGL.js","assets/mount-table-store-dY2IfQ5S.js","assets/mount-bridge-client-DkyfUm3y.js","assets/port-bridge-client-Bg6_jjLD.js"])))=>i.map(i=>d[i]);
2
- import{t as e}from"./preload-helper-Czpn1I53.js";import{t}from"./logger-DDBAeTLF.js";import{i as n,n as r,r as i,t as a}from"./path-utils-Rm3AltuN.js";import{t as o}from"./types-idfTVsM8.js";import{t as s}from"./virtual-device-paths-9EXC9iPp.js";import{t as c}from"./backend-local-Btkv66jT.js";import{a as l,i as u,n as d,t as f}from"./mount-table-store-dY2IfQ5S.js";var p=t(`fs-watcher`),m=0;function h(e,t){return t===`/`||e===t||e.startsWith(t+`/`)}var g=class{registrations=new Map;watch(e,t,n){let r=`fsw-${++m}`;return this.registrations.set(r,{id:r,basePath:e,filter:t,callback:n}),p.debug(`Watch registered`,{id:r,basePath:e}),()=>{this.registrations.delete(r),p.debug(`Watch unregistered`,{id:r})}}notify(e){if(e.length!==0)for(let[,t]of this.registrations){let n=e.filter(e=>h(e.path,t.basePath)&&t.filter(e.path));if(n.length>0)try{t.callback(n)}catch(e){p.error(`Watch callback error`,{id:t.id,error:e instanceof Error?e.message:String(e)})}}}dispose(){this.registrations.clear(),p.debug(`All watchers disposed`)}get size(){return this.registrations.size}},_=t(`mount-index`),v=400,y=2e6,b=`SLICC_MOUNT_INDEX_MAX_DEPTH`,x=`SLICC_MOUNT_INDEX_MAX_ENTRIES`,S=256,C=class extends Error{cause;constructor(e,t){super(e),this.name=`MountIndexAbortError`,this.cause=t}};function w(e){let t=e.map(([e,t])=>`${e}\u0000${t.kind}`).sort(),n=t.length>S?t.slice(0,S):t;return`${t.length}\u0001${n.join(``)}`}async function T(e,t){let n=e.isSameEntry;if(typeof n!=`function`)return!1;try{return await n.call(e,t)}catch{return!1}}function E(e,t){return e instanceof Map?e.get(t):e[t]}function D(e){let t=e.trim();if(t===``)return;let n=Number(t);if(!(!Number.isInteger(n)||n<=0))return n}function O(e,t,n){let r=E(e,t);if(r===void 0||r.trim()===``)return n;let i=D(r);return i===void 0?(_.warn(`Ignoring invalid ${t}; expected a positive integer, using default`,{value:r,fallback:n}),n):i}function k(e){return{maxDepth:O(e,b,v),maxEntries:O(e,x,y)}}var A=class{mounts=new Map;listeners=new Set;registerMount(e,t,n=k({})){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,_.info(`Mount indexed`,{path:e,files:t.files.size,directories:t.directories.size})}catch(r){if(n.aborted)return;let i=r instanceof Error?r.message:String(r),a=r instanceof C?r.cause:`indexing-error`;t.state={status:`error`,indexed:0,error:i,abortCause:a},_.error(`Mount indexing failed`,{path:e,error:i,abortCause:a})}this.notifyListeners()}async walkHandle(e,t,n,r,i=0,a=new Map){if(r.aborted)return;this.enforceWalkBounds(i,n),n.directories.add(e);let o=await this.readChildren(t,r,n);if(r.aborted)return;let s=await this.confirmNoCycle(e,t,o,a),c=this.pushAncestor(a,s,e,t);try{await this.walkChildren(e,o,n,r,i,a)}finally{this.popAncestor(a,s,c)}}enforceWalkBounds(e,t){if(e>t.limits.maxDepth)throw new C(`mount indexing aborted: directory nesting exceeded ${t.limits.maxDepth} levels`,`depth-exceeded`);if(t.directories.size+t.files.size>=t.limits.maxEntries)throw new C(`mount indexing aborted: exceeded ${t.limits.maxEntries} entries`,`entries-exceeded`)}async readChildren(e,t,n){let r=e,i=[];for await(let e of r){if(t.aborted)break;if(n.directories.size+n.files.size+i.length>=n.limits.maxEntries)throw new C(`mount indexing aborted: exceeded ${n.limits.maxEntries} entries`,`entries-exceeded`);i.push(e)}return i}async confirmNoCycle(e,t,n,r){let i=w(n),a=r.get(i);if(a){for(let n of a)if(await T(n.handle,t))throw new C(`mount indexing aborted: self-referential mount cycle detected at ${e} (re-exposes ${n.path})`,`cycle-detected`)}return i}pushAncestor(e,t,n,r){let i=e.get(t);return i||(i=[],e.set(t,i)),i.push({path:n,handle:r,signature:t}),i}popAncestor(e,t,n){n.pop(),n.length===0&&e.delete(t)}async walkChildren(e,t,n,r,i,a){for(let[o,s]of t){if(r.aborted)return;let t=e===`/`?`/${o}`:`${e}/${o}`;s.kind===`file`?(n.files.add(t),n.state.indexed++):s.kind===`directory`&&await this.walkHandle(t,s,n,r,i+1,a),n.state.indexed%500==0&&(this.notifyListeners(),await new Promise(e=>setTimeout(e,0)))}}},j={[s]:{stat:()=>({type:`file`,size:0,mtime:0,ctime:0}),read:e=>(e?.encoding??`utf-8`)===`utf-8`?``:new Uint8Array,readText:()=>``,write:()=>{}}},M=class{vfs;allowedPrefixes;readOnlyPrefixes;writeEnforcement;constructor(e,t,n=[],i=`hard`){this.vfs=e;let a=e=>{let t=r(e);return t.endsWith(`/`)?t:t+`/`};this.allowedPrefixes=t.map(a),this.readOnlyPrefixes=n.map(a),this.writeEnforcement=i}getAllPrefixes(){let e=this.vfs.listMounts().map(e=>e.endsWith(`/`)?e:e+`/`);return[...this.allowedPrefixes,...this.readOnlyPrefixes,...e]}isAllowed(e){let t=r(e);return this.getAllPrefixes().some(e=>t===e.slice(0,-1)||t.startsWith(e)||t===`/`||e.startsWith(t+`/`))}isAllowedStrict(e){let t=r(e);return this.getAllPrefixes().some(e=>t===e.slice(0,-1)||t.startsWith(e))}isWritable(e){let t=r(e);return this.allowedPrefixes.some(e=>t===e.slice(0,-1)||t.startsWith(e))}canWrite(e){return this.isWritable(e)}checkWrite(e){if(this.writeEnforcement!==`sudo-delegated`&&!this.isWritable(e))throw new o(`EACCES`,`permission denied`,r(e))}async resolveAndCheckRead(e){try{let t=await this.vfs.realpath(e);if(!this.isAllowedStrict(t))throw new o(`ENOENT`,`no such file or directory`,r(e));return t}catch(t){throw t instanceof o?t:new o(`ENOENT`,`no such file or directory`,r(e))}}async resolveAndCheckWrite(e){try{let t=await this.vfs.realpath(e);if(!this.isWritable(t)&&!this.isSymlinkEscapeAllowed(t))throw new o(`EACCES`,`permission denied`,r(e));return t}catch(t){throw t instanceof o?t:new o(`EACCES`,`permission denied`,r(e))}}isSymlinkEscapeAllowed(e){return!1}async checkParentRealpathEscape(e){let t=this.vfs.dirname(e),n=this.vfs.basename(e),i;try{i=await this.vfs.realpath(t)}catch(e){if(e instanceof o&&e.code===`EACCES`)throw e;return}let a=i+`/`+n;if(this.isWritable(a))return;let s=r(i)!==r(t);if(!(this.writeEnforcement===`sudo-delegated`&&!s))throw new o(`EACCES`,`permission denied`,r(e))}getUnderlyingFS(){return this.vfs}invalidatePaths(e){this.vfs.invalidatePaths(e)}isPathUnderMount(e){return this.vfs.isPathUnderMount(e)}async readFile(e,t){let n=j[r(e)];if(n)return n.read(t);if(!this.isAllowedStrict(e))throw new o(`ENOENT`,`no such file or directory`,r(e));let i=await this.resolveAndCheckRead(e);return this.vfs.readFile(i,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=r(e);return n.filter(e=>{let n=t===`/`?`/${e.name}`:`${t}/${e.name}`;return this.isAllowed(n)})}return n}async stat(e){let t=j[r(e)];if(t)return t.stat();if(!this.isAllowed(e))throw new o(`ENOENT`,`no such file or directory`,r(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=r(e);if(n===`/`)return!1;let i=n.slice(1).split(`/`),a=t?i.length:i.length-1,o=``;for(let e=0;e<a;e++){o=o+`/`+i[e];let t=this.vfs.lstatSync(o);if(t===null)return null;if(t.type===`symlink`)return!0}return!1}statSync(e){let t=j[r(e)];return t?t.stat():!this.isAllowedStrict(e)||this.scanPathForSymlinks(e,!0)!==!1?null:this.vfs.statSync(e)}lstatSync(e){let t=j[r(e)];return t?t.stat():!this.isAllowed(e)||this.scanPathForSymlinks(e,!1)!==!1?null:this.vfs.lstatSync(e)}readDirSync(e){if(!this.isAllowed(e)||this.scanPathForSymlinks(e,!0)!==!1)return null;let t=this.vfs.readDirSync(e);if(t===null)return null;if(this.isAllowedStrict(e))return t;let n=r(e);return t.filter(e=>{let t=n===`/`?`/${e.name}`:`${n}/${e.name}`;return this.isAllowed(t)})}async realpath(e){let t;try{t=await this.vfs.realpath(e)}catch(t){throw t instanceof o?t:new o(`ENOENT`,`no such file or directory`,r(e))}if(!this.isAllowedStrict(t))throw new o(`ENOENT`,`no such file or directory`,r(e));return t}async exists(e){if(j[r(e)])return!0;if(!this.isAllowed(e))return!1;if(this.isAllowedStrict(e))try{await this.resolveAndCheckRead(e)}catch{return!1}return this.vfs.exists(e)}async readTextFile(e){let t=j[r(e)];if(t)return t.readText();if(!this.isAllowedStrict(e))throw new o(`ENOENT`,`no such file or directory`,r(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 i=j[r(e)];if(i){i.write(t);return}this.checkWrite(e),await this.checkParentRealpathEscape(e);try{(await this.vfs.lstat(e)).type===`symlink`&&await this.resolveAndCheckWrite(e)}catch(e){if(e instanceof o&&e.code===`EACCES`)throw e}return this.vfs.writeFile(e,t,n)}async mkdir(e,t){return this.checkWrite(e),await this.checkParentRealpathEscape(e),this.vfs.mkdir(e,t)}async rm(e,t){this.checkWrite(e);try{(await this.vfs.lstat(e)).type===`symlink`||await this.resolveAndCheckWrite(e)}catch(e){if(e instanceof o&&e.code===`EACCES`)throw e}return this.vfs.rm(e,t)}async rename(e,t){return this.checkWrite(e),this.checkWrite(t),await this.resolveAndCheckWrite(e),await this.checkParentRealpathEscape(t),this.vfs.rename(e,t)}async copyFile(e,t){if(!this.isAllowed(e))throw new o(`ENOENT`,`no such file or directory`,r(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 o&&e.code===`EACCES`)throw e}return this.vfs.copyFile(n,t)}async symlink(e,t){return this.checkWrite(t),await this.checkParentRealpathEscape(t),this.vfs.symlink(e,t)}async readlink(e){if(!this.isAllowedStrict(e))throw new o(`ENOENT`,`no such file or directory`,r(e));let t=await this.vfs.readlink(e),n;if(t.startsWith(`/`))n=r(t);else{let i=this.vfs.dirname(e);n=r(i+`/`+t)}if(!this.isAllowedStrict(n))throw new o(`ENOENT`,`no such file or directory`,r(e));return t}async lstat(e){let t=j[r(e)];if(t)return t.stat();if(!this.isAllowed(e))throw new o(`ENOENT`,`no such file or directory`,r(e));let n=r(e),i=this.vfs.dirname(n),a=this.vfs.basename(n),s;if(i===n)s=i;else try{s=await this.vfs.realpath(i)}catch{throw new o(`ENOENT`,`no such file or directory`,n)}let c=s===`/`?`/${a}`:`${s}/${a}`;if(!this.isAllowed(c))throw new o(`ENOENT`,`no such file or directory`,n);return this.vfs.lstat(c)}watch(e,t,n){if(!this.isAllowed(e))throw new o(`EACCES`,`permission denied`,r(e));let i=this.vfs.getWatcher();if(!i)throw new o(`EINVAL`,`no watcher configured`);return i.watch(r(e),t,n)}dirname(e){return this.vfs.dirname(e)}basename(e){return this.vfs.basename(e)}async mount(e,t,n){return this.checkWrite(e),await this.checkParentRealpathEscape(e),this.vfs.mount(e,t,n)}async unmount(e){return this.checkWrite(e),await this.checkParentRealpathEscape(e),this.vfs.unmount(e)}listMounts(){return this.vfs.listMounts()}getMountIndex(){return this.vfs.getMountIndex()}async refreshMount(e,t){return this.checkWrite(e),this.vfs.refreshMount(e,t)}async dispose(){await this.vfs.dispose()}};function N(e,t){if(e instanceof o){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 o(e.code,r,t)}throw e}var P=[`ENOENT`,`EEXIST`,`ENOTDIR`,`EISDIR`,`ENOTEMPTY`,`EINVAL`,`EACCES`,`ELOOP`,`EBUSY`,`EFBIG`,`EBADF`,`EIO`];function F(e,t){if(e instanceof o)return e;let n=e?.code;if(typeof n==`string`){let r=n;if(P.includes(r)){let n=e instanceof Error?e.message:String(e);return new o(r,n||r,t)}}let r=e instanceof Error?e.message:String(e);return r.includes(`ENOENT`)?new o(`ENOENT`,`no such file or directory`,t):r.includes(`EEXIST`)?new o(`EEXIST`,`file already exists`,t):r.includes(`ENOTDIR`)?new o(`ENOTDIR`,`not a directory`,t):r.includes(`EISDIR`)?new o(`EISDIR`,`is a directory`,t):r.includes(`ENOTEMPTY`)?new o(`ENOTEMPTY`,`directory not empty`,t):r.includes(`ELOOP`)?new o(`ELOOP`,`too many levels of symbolic links`,t):new o(`EINVAL`,r,t)}function I(e,t){return e===t||e.startsWith(t===`/`?`/`:`${t}/`)}function L(e,t,n){let r=t.entries??{},i={...e.entries??{}};`/`in r&&(i[`/`]=r[`/`]);for(let e of n.paths)e in r?i[e]=r[e]:delete i[e];for(let e of n.prefixes){for(let t of Object.keys(i))I(t,e)&&delete i[t];for(let t of Object.keys(r))I(t,e)&&(i[t]=r[t])}let{entries:a,...o}=t;return{...o,entries:i}}async function R(e,t,n,r){try{return await e.lstat(t)}catch(e){let t=F(e,r);if(t.code===`ENOENT`&&n)return null;throw t}}async function z(e,t,i){let o;try{o=await e.readlink(t)}catch(e){throw F(e,i)}return o.startsWith(`/`)?r(o):r(a(n(t).dir,o))}async function B(e,t,n,r,i,a){let s=t===`/`?`/${n}`:`${t}/${n}`;for(;;){let t=await R(e,s,r,i);if(t===null||!t.isSymbolicLink())return{resolved:s,hops:a};if(++a>10)throw new o(`ELOOP`,`too many symbolic links encountered`,i);s=await z(e,s,i)}}async function V(e,t,n){let i=r(n);if(t(i))return i;let a=i.split(`/`).filter(Boolean),o=`/`,s=0;for(let t=0;t<a.length;t++){let n=await B(e,o,a[t],t===a.length-1,i,s);o=n.resolved,s=n.hops}return o}async function H(e,t,n){return t(n)?n:V(e,t,n)}function U(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 W(e,t){try{return await e(t)}catch{return t}}async function*G(e,t,n,i=0){let a=r(t);if(U(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(i>64||o.size>=1e5)return;let s=await W(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*K(e,t,a===`/`?`/${t.name}`:`${a}/${t.name}`,o,i+1)}async function*K(e,t,n,r,i){if(t.type===`file`){yield n;return}if(t.type===`symlink`){yield*q(e,n,r,i);return}yield*G(e,n,r,i)}async function*q(e,t,n,r){try{let i=await e.stat(t);i.type===`file`?yield t:i.type===`directory`&&(yield*G(e,t,n,r))}catch{}}function J(){try{if(typeof globalThis.navigator?.storage?.getDirectory==`function`)return`opfs`}catch{}return`memory`}var Y=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 A;static writeChains=new Map;constructor(e,n,r,i){if(this.dbName=e,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).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-CoWnU-QN.js`).then(e=>e.t),__vite__mapDeps([0,1])),e(()=>import(`./dist-Ca06zVsb.js`),__vite__mapDeps([2,0,1]))]);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-B31h6Aw0.js`);return{resolveWithSidecarRepair:e,repairOpfsMetadataSidecar:t}},[]),d=await i(r,()=>n.withWriteLock(()=>u(a)),e=>console.warn(`[virtual-fs] repaired poisoned metadata sidecar; retrying mount`,{dbName:n.dbName,kindFixed:e.kindFixed,sizesFixed:e.sizesFixed,dropped:e.dropped}));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-CoWnU-QN.js`).then(e=>e.t),__vite__mapDeps([0,1]));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 o(`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??J(),a=new t(n,r,i);return await a._ready,r&&await f().catch(()=>{}),a}async flush(){await this.writeOpfsMetadataSidecar()}async writeOpfsMetadataSidecar(){this.backend===`opfs`&&await this.withWriteLock(()=>this.writeOpfsMetadataSidecarUnlocked())}async writeOpfsMetadataSidecarUnlocked(){if(this.backend!==`opfs`)return;let 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&&(a=L(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())}markSidecarDirty(e,i=`path`){if(this.backend!==`opfs`)return;let a=t.opfsBackends.get(this.dbName)?.sidecarDirty;if(!a)return;let o=r(e);(i===`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=r(n);t.index.delete(e),t._handles?.delete(e),this.markSidecarDirty(e)}}canWrite(e){return!0}setWatcher(e){this.watcher=e}getWatcher(){return this.watcher}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-CoWnU-QN.js`).then(e=>e.t),__vite__mapDeps([0,1]))).umount(this.mountRoot)}catch{}}}}readDirSync(e){let t=r(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=r(e);if(this.findMount(t))return null;let i=this.lfsSync;if(typeof i.statSync!=`function`||typeof i.lstatSync!=`function`||typeof i.readlinkSync!=`function`)return null;let o=t;for(let e=0;e<=10;e++){let e;try{e=i.lstatSync(o)}catch{return null}if(!e.isSymbolicLink())return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs};let t;try{t=i.readlinkSync(o)}catch{return null}o=t.startsWith(`/`)?r(t):r(a(n(o).dir,t))}return null}lstatSync(e){let t=r(e);if(this.findMount(t))return null;let n=this.lfsSync;if(typeof n.lstatSync!=`function`)return null;try{let e=n.lstatSync(t);if(e.isSymbolicLink()){let r=n.readlinkSync?n.readlinkSync(t):``;return{type:`symlink`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,isSymlink:!0,symlinkTarget:r}}return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs}}catch{return null}}async mount(e,t,i){let a=r(e);if(this.mountPoints.has(a))throw new o(`EEXIST`,`mount point is already mounted`,a);try{if((await this.lstat(a)).type!==`directory`)throw new o(`ENOTDIR`,`mount point must be a directory`,a);if((await this.readDir(a)).length>0)throw new o(`ENOTEMPTY`,`mount point must be empty to avoid shadowing existing files`,a)}catch(e){if(!(e instanceof o)||e.code!==`ENOENT`)throw e}let{dir:s}=n(a);s!==`/`&&await this.mkdir(s,{recursive:!0});try{await this.lfs.mkdir(a)}catch{}if(this.mountPoints.set(a,t),t.kind===`local`){let e=k(i?.env??{});this.mountIndex.registerMount(a,t.getHandle(),e)}let c=t.kind===`local`?{kind:`local`,mountId:t.mountId,idbHandleKey:a}:t.kind===`s3`?{kind:`s3`,mountId:t.mountId,source:t.source,profile:t.profile??`default`}:{kind:`da`,mountId:t.mountId,source:t.source,profile:t.profile??`default`};try{this.mountSyncChannel?.postMessage({type:`mount`,path:a,descriptor:c})}catch{}this.watcher?.notify([{type:`modify`,path:a,entryType:`directory`}]);try{let e={targetPath:a,descriptor:c,createdAt:Date.now()},n=t.kind===`local`?t.getHandle():void 0;await l(e,n)}catch{}}async unmount(e){let t=r(e),n=this.mountPoints.get(t);this.mountPoints.delete(t),this.mountIndex.unregisterMount(t);try{this.mountSyncChannel?.postMessage({type:`unmount`,path:t})}catch{}this.watcher?.notify([{type:`modify`,path:t,entryType:`directory`}]),await n?.close();try{await u(t)}catch{}}async reconstructBackendFromDescriptor(t){switch(t.kind){case`local`:{let e=await d(t.idbHandleKey);if(!e)throw Error(`no handle stored for ${t.idbHandleKey}`);return c.fromHandle(e,{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-DB6C8U3-.js`);return{S3MountBackend:e,RemoteMountCache:t,makeSignedFetchS3:n}},__vite__mapDeps([3,4,5,6,7,8,1,9,10,11,12,13,14,15,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-DB6C8U3-.js`);return{DaMountBackend:e,RemoteMountCache:t,makeSignedFetchDa:n}},__vite__mapDeps([3,4,5,6,7,8,1,9,10,11,12,13,14,15,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 i=r(e);if(this.mountPoints.has(i))throw new o(`EEXIST`,`mount point is already mounted`,i);let{dir:a}=n(i);a!==`/`&&await this.mkdir(a,{recursive:!0});try{await this.lfs.mkdir(i)}catch{}this.mountPoints.set(i,t),this.internalMounts.add(i),this.watcher?.notify([{type:`modify`,path:i,entryType:`directory`}])}async unmountInternal(e){let t=r(e);if(!this.internalMounts.has(t))throw new o(`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=r(e),i=this.mountPoints.get(n);if(!i)throw new o(`ENOENT`,`not a mount point`,n);let a=await i.refresh(t);return i.kind===`local`&&await this.mountIndex.refreshMount(n,k(t?.env??{})),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){let n=r(e),i=this.findMount(n);if(i){if(i.relParts.length===0)throw new o(`EISDIR`,`is a directory`,n);let e=i.relParts.join(`/`);try{let n=await i.backend.readFile(e);return(t?.encoding??`utf-8`)===`utf-8`?new TextDecoder(`utf-8`).decode(n):n}catch(e){N(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 F(e,n)}}async writeFile(e,t,i){let a=r(e),s=this.findMount(a);if(s){if(s.relParts.length===0)throw new o(`EISDIR`,`is a directory`,a);let e=s.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 s.backend.writeFile(e,r)}catch(e){N(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 F(e,a)}}else throw F(e,a)}try{await this.lfs.truncate?.(c,e)}catch(e){throw F(e,a)}}),this.watcher?.notify([{type:l?`modify`:`create`,path:c,entryType:`file`}])}async readDir(e){let t=r(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){N(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){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 F(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=``;for(let e of t){n+=`/`+e;try{await this.lfs.mkdir(n)}catch(e){if(e instanceof Error&&!e.message.includes(`EEXIST`))throw F(e,n)}}}async mkdir(e,t){let n=r(e);if(n===`/`)return;let i=this.findMount(n);if(i){if(i.relParts.length===0)return;let e=i.relParts.join(`/`),t=await this.exists(n);try{await i.backend.mkdir(e)}catch(e){N(e,n)}t||this.watcher?.notify([{type:`create`,path:n,entryType:`directory`}]);return}t?.recursive?await this.withWriteLock(()=>(this.markSidecarDirty(n),this.mkdirRecursiveUnlocked(n))):(await this.withWriteLock(async()=>{this.markSidecarDirty(n);try{await this.lfs.mkdir(n)}catch(e){throw F(e,n)}}),this.watcher?.notify([{type:`create`,path:n,entryType:`directory`}]))}async rm(e,t){let n=r(e),i=this.findMount(n);if(i){if(i.relParts.length===0)throw new o(`EINVAL`,`cannot remove a mount point — use unmount`,n);let e;try{e=(await this.stat(n)).type}catch{}let r=i.relParts.join(`/`);try{await i.backend.remove(r,{recursive:t?.recursive})}catch(e){N(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 F(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){let t=r(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){N(e,t)}}let i=await this.resolveSymlinks(t);try{let e=await this.lfs.stat(i);return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs}}catch(e){throw F(e,t)}}async exists(e){let t=r(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){let n=r(e),i=r(t),a;try{a=(await this.lstat(n)).type}catch{}try{await this.withWriteLock(async()=>{this.markSidecarDirty(n,`prefix`),this.markSidecarDirty(i,`prefix`),await this.lfs.rename(n,i),await this.writeOpfsMetadataSidecarUnlocked()})}catch(e){throw F(e,n)}this.watcher?.notify([{type:`delete`,path:n,entryType:a},{type:`create`,path:i,entryType:a}]),this.mountIndex.notifyRename(n,i)}async readTextFile(e){return await this.readFile(e,{encoding:`utf-8`})}async*walk(e,t,n=0){yield*G({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 o(`EISDIR`,`is a directory`,e);let n=await this.readFile(e,{encoding:`binary`});await this.writeFile(t,n)}dirname(e){return n(r(e)).dir}basename(e){return n(r(e)).base}async symlink(e,t){let i=r(t);if(this.findMount(i))throw new o(`EINVAL`,`symlinks not supported on mounted filesystems`,i);let{dir:a}=n(i);await this.withWriteLock(async()=>{a!==`/`&&await this.mkdirRecursiveUnlocked(a);try{await this.lfs.symlink(e,i)}catch(t){if(a!==`/`&&t instanceof Error&&t.message.includes(`ENOENT`)){await this.mkdirRecursiveUnlocked(a);try{await this.lfs.symlink(e,i)}catch(e){throw F(e,i)}}else throw F(t,i)}this.markSidecarDirty(i),await this.writeOpfsMetadataSidecarUnlocked()}),this.watcher?.notify([{type:`create`,path:i,entryType:`symlink`}])}async readlink(e){let t=r(e);try{return await this.lfs.readlink(t)}catch(e){throw F(e,t)}}async lstat(e){let t=r(e);if(this.findMount(t))return this.stat(t);try{let e=await this.lfs.lstat(t);if(e.isSymbolicLink()){let n=await this.lfs.readlink(t);return{type:`symlink`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,isSymlink:!0,symlinkTarget:n}}return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs}}catch(e){throw F(e,t)}}async realpath(e){return V(this.lfs,e=>this.findMount(e)!==null,e)}resolveSymlinks(e){return H(this.lfs,e=>this.findMount(e)!==null,e)}};export{o as FsError,g as FsWatcher,A as MountIndex,M as RestrictedFS,Y as VirtualFS,a as joinPath,r as normalizePath,i as pathSegments,J as resolveVfsBackendFromEnv,n as splitPath};
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/dist-CoWnU-QN.js","assets/rolldown-runtime-Dd_uD5pT.js","assets/dist-Ca06zVsb.js","assets/mount-Cws5YfoU.js","assets/preload-helper-Czpn1I53.js","assets/mime-types-ugOWOUZ9.js","assets/base64-DpPqYZJF.js","assets/src-CAWTvdAa.js","assets/proxied-fetch-ULPrH97b.js","assets/runtime-env-DH4NDw4t.js","assets/fetch-body-D2PwksUW.js","assets/types-idfTVsM8.js","assets/backend-local-D7Gqh_i1.js","assets/tool-ui-C-E235kX.js","assets/logger-DDBAeTLF.js","assets/logger-BoSvu4mW.js","assets/picker-approval-CXL7T-sh.js","assets/mount-picker-popup-Bh-wMX4z.js","assets/picker-popup-BvzmBsGL.js","assets/mount-table-store-dY2IfQ5S.js","assets/mount-bridge-client-DkyfUm3y.js","assets/port-bridge-client-Bg6_jjLD.js"])))=>i.map(i=>d[i]);
2
+ import{t as e}from"./preload-helper-Czpn1I53.js";import{t}from"./logger-DDBAeTLF.js";import{i as n,n as r,r as i,t as a}from"./path-utils-Rm3AltuN.js";import{t as o}from"./types-idfTVsM8.js";import{t as s}from"./virtual-device-paths-9EXC9iPp.js";import{t as c}from"./backend-local-D7Gqh_i1.js";import{a as l,i as u,n as d,t as f}from"./mount-table-store-dY2IfQ5S.js";var p=t(`fs-watcher`),m=0;function h(e,t){return t===`/`||e===t||e.startsWith(t+`/`)}var g=class{registrations=new Map;watch(e,t,n){let r=`fsw-${++m}`;return this.registrations.set(r,{id:r,basePath:e,filter:t,callback:n}),p.debug(`Watch registered`,{id:r,basePath:e}),()=>{this.registrations.delete(r),p.debug(`Watch unregistered`,{id:r})}}notify(e){if(e.length!==0)for(let[,t]of this.registrations){let n=e.filter(e=>h(e.path,t.basePath)&&t.filter(e.path));if(n.length>0)try{t.callback(n)}catch(e){p.error(`Watch callback error`,{id:t.id,error:e instanceof Error?e.message:String(e)})}}}dispose(){this.registrations.clear(),p.debug(`All watchers disposed`)}get size(){return this.registrations.size}},_=t(`mount-index`),v=400,y=2e6,b=`SLICC_MOUNT_INDEX_MAX_DEPTH`,x=`SLICC_MOUNT_INDEX_MAX_ENTRIES`,S=256,C=class extends Error{cause;constructor(e,t){super(e),this.name=`MountIndexAbortError`,this.cause=t}};function w(e){let t=e.map(([e,t])=>`${e}\u0000${t.kind}`).sort(),n=t.length>S?t.slice(0,S):t;return`${t.length}\u0001${n.join(``)}`}async function T(e,t){let n=e.isSameEntry;if(typeof n!=`function`)return!1;try{return await n.call(e,t)}catch{return!1}}function E(e,t){return e instanceof Map?e.get(t):e[t]}function D(e){let t=e.trim();if(t===``)return;let n=Number(t);if(!(!Number.isInteger(n)||n<=0))return n}function O(e,t,n){let r=E(e,t);if(r===void 0||r.trim()===``)return n;let i=D(r);return i===void 0?(_.warn(`Ignoring invalid ${t}; expected a positive integer, using default`,{value:r,fallback:n}),n):i}function k(e){return{maxDepth:O(e,b,v),maxEntries:O(e,x,y)}}var A=class{mounts=new Map;listeners=new Set;registerMount(e,t,n=k({})){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,_.info(`Mount indexed`,{path:e,files:t.files.size,directories:t.directories.size})}catch(r){if(n.aborted)return;let i=r instanceof Error?r.message:String(r),a=r instanceof C?r.cause:`indexing-error`;t.state={status:`error`,indexed:0,error:i,abortCause:a},_.error(`Mount indexing failed`,{path:e,error:i,abortCause:a})}this.notifyListeners()}async walkHandle(e,t,n,r,i=0,a=new Map){if(r.aborted)return;this.enforceWalkBounds(i,n),n.directories.add(e);let o=await this.readChildren(t,r,n);if(r.aborted)return;let s=await this.confirmNoCycle(e,t,o,a),c=this.pushAncestor(a,s,e,t);try{await this.walkChildren(e,o,n,r,i,a)}finally{this.popAncestor(a,s,c)}}enforceWalkBounds(e,t){if(e>t.limits.maxDepth)throw new C(`mount indexing aborted: directory nesting exceeded ${t.limits.maxDepth} levels`,`depth-exceeded`);if(t.directories.size+t.files.size>=t.limits.maxEntries)throw new C(`mount indexing aborted: exceeded ${t.limits.maxEntries} entries`,`entries-exceeded`)}async readChildren(e,t,n){let r=e,i=[];for await(let e of r){if(t.aborted)break;if(n.directories.size+n.files.size+i.length>=n.limits.maxEntries)throw new C(`mount indexing aborted: exceeded ${n.limits.maxEntries} entries`,`entries-exceeded`);i.push(e)}return i}async confirmNoCycle(e,t,n,r){let i=w(n),a=r.get(i);if(a){for(let n of a)if(await T(n.handle,t))throw new C(`mount indexing aborted: self-referential mount cycle detected at ${e} (re-exposes ${n.path})`,`cycle-detected`)}return i}pushAncestor(e,t,n,r){let i=e.get(t);return i||(i=[],e.set(t,i)),i.push({path:n,handle:r,signature:t}),i}popAncestor(e,t,n){n.pop(),n.length===0&&e.delete(t)}async walkChildren(e,t,n,r,i,a){for(let[o,s]of t){if(r.aborted)return;let t=e===`/`?`/${o}`:`${e}/${o}`;s.kind===`file`?(n.files.add(t),n.state.indexed++):s.kind===`directory`&&await this.walkHandle(t,s,n,r,i+1,a),n.state.indexed%500==0&&(this.notifyListeners(),await new Promise(e=>setTimeout(e,0)))}}},j={[s]:{stat:()=>({type:`file`,size:0,mtime:0,ctime:0}),read:e=>(e?.encoding??`utf-8`)===`utf-8`?``:new Uint8Array,readText:()=>``,write:()=>{}}},M=class{vfs;allowedPrefixes;readOnlyPrefixes;writeEnforcement;constructor(e,t,n=[],i=`hard`){this.vfs=e;let a=e=>{let t=r(e);return t.endsWith(`/`)?t:t+`/`};this.allowedPrefixes=t.map(a),this.readOnlyPrefixes=n.map(a),this.writeEnforcement=i}getAllPrefixes(){let e=this.vfs.listMounts().map(e=>e.endsWith(`/`)?e:e+`/`);return[...this.allowedPrefixes,...this.readOnlyPrefixes,...e]}isAllowed(e){let t=r(e);return this.getAllPrefixes().some(e=>t===e.slice(0,-1)||t.startsWith(e)||t===`/`||e.startsWith(t+`/`))}isAllowedStrict(e){let t=r(e);return this.getAllPrefixes().some(e=>t===e.slice(0,-1)||t.startsWith(e))}isWritable(e){let t=r(e);return this.allowedPrefixes.some(e=>t===e.slice(0,-1)||t.startsWith(e))}canWrite(e){return this.isWritable(e)}checkWrite(e){if(this.writeEnforcement!==`sudo-delegated`&&!this.isWritable(e))throw new o(`EACCES`,`permission denied`,r(e))}async resolveAndCheckRead(e){try{let t=await this.vfs.realpath(e);if(!this.isAllowedStrict(t))throw new o(`ENOENT`,`no such file or directory`,r(e));return t}catch(t){throw t instanceof o?t:new o(`ENOENT`,`no such file or directory`,r(e))}}async resolveAndCheckWrite(e){try{let t=await this.vfs.realpath(e);if(!this.isWritable(t)&&!this.isSymlinkEscapeAllowed(t))throw new o(`EACCES`,`permission denied`,r(e));return t}catch(t){throw t instanceof o?t:new o(`EACCES`,`permission denied`,r(e))}}isSymlinkEscapeAllowed(e){return!1}async checkParentRealpathEscape(e){let t=this.vfs.dirname(e),n=this.vfs.basename(e),i;try{i=await this.vfs.realpath(t)}catch(e){if(e instanceof o&&e.code===`EACCES`)throw e;return}let a=i+`/`+n;if(this.isWritable(a))return;let s=r(i)!==r(t);if(!(this.writeEnforcement===`sudo-delegated`&&!s))throw new o(`EACCES`,`permission denied`,r(e))}getUnderlyingFS(){return this.vfs}invalidatePaths(e){this.vfs.invalidatePaths(e)}isPathUnderMount(e){return this.vfs.isPathUnderMount(e)}async readFile(e,t){let n=j[r(e)];if(n)return n.read(t);if(!this.isAllowedStrict(e))throw new o(`ENOENT`,`no such file or directory`,r(e));let i=await this.resolveAndCheckRead(e);return this.vfs.readFile(i,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=r(e);return n.filter(e=>{let n=t===`/`?`/${e.name}`:`${t}/${e.name}`;return this.isAllowed(n)})}return n}async stat(e){let t=j[r(e)];if(t)return t.stat();if(!this.isAllowed(e))throw new o(`ENOENT`,`no such file or directory`,r(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=r(e);if(n===`/`)return!1;let i=n.slice(1).split(`/`),a=t?i.length:i.length-1,o=``;for(let e=0;e<a;e++){o=o+`/`+i[e];let t=this.vfs.lstatSync(o);if(t===null)return null;if(t.type===`symlink`)return!0}return!1}statSync(e){let t=j[r(e)];return t?t.stat():!this.isAllowedStrict(e)||this.scanPathForSymlinks(e,!0)!==!1?null:this.vfs.statSync(e)}lstatSync(e){let t=j[r(e)];return t?t.stat():!this.isAllowed(e)||this.scanPathForSymlinks(e,!1)!==!1?null:this.vfs.lstatSync(e)}readDirSync(e){if(!this.isAllowed(e)||this.scanPathForSymlinks(e,!0)!==!1)return null;let t=this.vfs.readDirSync(e);if(t===null)return null;if(this.isAllowedStrict(e))return t;let n=r(e);return t.filter(e=>{let t=n===`/`?`/${e.name}`:`${n}/${e.name}`;return this.isAllowed(t)})}async realpath(e){let t;try{t=await this.vfs.realpath(e)}catch(t){throw t instanceof o?t:new o(`ENOENT`,`no such file or directory`,r(e))}if(!this.isAllowedStrict(t))throw new o(`ENOENT`,`no such file or directory`,r(e));return t}async exists(e){if(j[r(e)])return!0;if(!this.isAllowed(e))return!1;if(this.isAllowedStrict(e))try{await this.resolveAndCheckRead(e)}catch{return!1}return this.vfs.exists(e)}async readTextFile(e){let t=j[r(e)];if(t)return t.readText();if(!this.isAllowedStrict(e))throw new o(`ENOENT`,`no such file or directory`,r(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 i=j[r(e)];if(i){i.write(t);return}this.checkWrite(e),await this.checkParentRealpathEscape(e);try{(await this.vfs.lstat(e)).type===`symlink`&&await this.resolveAndCheckWrite(e)}catch(e){if(e instanceof o&&e.code===`EACCES`)throw e}return this.vfs.writeFile(e,t,n)}async mkdir(e,t){return this.checkWrite(e),await this.checkParentRealpathEscape(e),this.vfs.mkdir(e,t)}async rm(e,t){this.checkWrite(e);try{(await this.vfs.lstat(e)).type===`symlink`||await this.resolveAndCheckWrite(e)}catch(e){if(e instanceof o&&e.code===`EACCES`)throw e}return this.vfs.rm(e,t)}async rename(e,t){return this.checkWrite(e),this.checkWrite(t),await this.resolveAndCheckWrite(e),await this.checkParentRealpathEscape(t),this.vfs.rename(e,t)}async copyFile(e,t){if(!this.isAllowed(e))throw new o(`ENOENT`,`no such file or directory`,r(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 o&&e.code===`EACCES`)throw e}return this.vfs.copyFile(n,t)}async symlink(e,t){return this.checkWrite(t),await this.checkParentRealpathEscape(t),this.vfs.symlink(e,t)}async readlink(e){if(!this.isAllowedStrict(e))throw new o(`ENOENT`,`no such file or directory`,r(e));let t=await this.vfs.readlink(e),n;if(t.startsWith(`/`))n=r(t);else{let i=this.vfs.dirname(e);n=r(i+`/`+t)}if(!this.isAllowedStrict(n))throw new o(`ENOENT`,`no such file or directory`,r(e));return t}async lstat(e){let t=j[r(e)];if(t)return t.stat();if(!this.isAllowed(e))throw new o(`ENOENT`,`no such file or directory`,r(e));let n=r(e),i=this.vfs.dirname(n),a=this.vfs.basename(n),s;if(i===n)s=i;else try{s=await this.vfs.realpath(i)}catch{throw new o(`ENOENT`,`no such file or directory`,n)}let c=s===`/`?`/${a}`:`${s}/${a}`;if(!this.isAllowed(c))throw new o(`ENOENT`,`no such file or directory`,n);return this.vfs.lstat(c)}watch(e,t,n){if(!this.isAllowed(e))throw new o(`EACCES`,`permission denied`,r(e));let i=this.vfs.getWatcher();if(!i)throw new o(`EINVAL`,`no watcher configured`);return i.watch(r(e),t,n)}dirname(e){return this.vfs.dirname(e)}basename(e){return this.vfs.basename(e)}async mount(e,t,n){return this.checkWrite(e),await this.checkParentRealpathEscape(e),this.vfs.mount(e,t,n)}async unmount(e){return this.checkWrite(e),await this.checkParentRealpathEscape(e),this.vfs.unmount(e)}listMounts(){return this.vfs.listMounts()}getMountIndex(){return this.vfs.getMountIndex()}async refreshMount(e,t){return this.checkWrite(e),this.vfs.refreshMount(e,t)}async dispose(){await this.vfs.dispose()}};function N(e,t){if(e instanceof o){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 o(e.code,r,t)}throw e}var P=[`ENOENT`,`EEXIST`,`ENOTDIR`,`EISDIR`,`ENOTEMPTY`,`EINVAL`,`EACCES`,`ELOOP`,`EBUSY`,`EFBIG`,`EBADF`,`EIO`];function F(e,t){if(e instanceof o)return e;let n=e?.code;if(typeof n==`string`){let r=n;if(P.includes(r)){let n=e instanceof Error?e.message:String(e);return new o(r,n||r,t)}}let r=e instanceof Error?e.message:String(e);return r.includes(`ENOENT`)?new o(`ENOENT`,`no such file or directory`,t):r.includes(`EEXIST`)?new o(`EEXIST`,`file already exists`,t):r.includes(`ENOTDIR`)?new o(`ENOTDIR`,`not a directory`,t):r.includes(`EISDIR`)?new o(`EISDIR`,`is a directory`,t):r.includes(`ENOTEMPTY`)?new o(`ENOTEMPTY`,`directory not empty`,t):r.includes(`ELOOP`)?new o(`ELOOP`,`too many levels of symbolic links`,t):new o(`EINVAL`,r,t)}function I(e,t){return e===t||e.startsWith(t===`/`?`/`:`${t}/`)}function L(e,t,n){let r=t.entries??{},i={...e.entries??{}};`/`in r&&(i[`/`]=r[`/`]);for(let e of n.paths)e in r?i[e]=r[e]:delete i[e];for(let e of n.prefixes){for(let t of Object.keys(i))I(t,e)&&delete i[t];for(let t of Object.keys(r))I(t,e)&&(i[t]=r[t])}let{entries:a,...o}=t;return{...o,entries:i}}async function R(e,t,n,r){try{return await e.lstat(t)}catch(e){let t=F(e,r);if(t.code===`ENOENT`&&n)return null;throw t}}async function z(e,t,i){let o;try{o=await e.readlink(t)}catch(e){throw F(e,i)}return o.startsWith(`/`)?r(o):r(a(n(t).dir,o))}async function B(e,t,n,r,i,a){let s=t===`/`?`/${n}`:`${t}/${n}`;for(;;){let t=await R(e,s,r,i);if(t===null||!t.isSymbolicLink())return{resolved:s,hops:a};if(++a>10)throw new o(`ELOOP`,`too many symbolic links encountered`,i);s=await z(e,s,i)}}async function V(e,t,n){let i=r(n);if(t(i))return i;let a=i.split(`/`).filter(Boolean),o=`/`,s=0;for(let t=0;t<a.length;t++){let n=await B(e,o,a[t],t===a.length-1,i,s);o=n.resolved,s=n.hops}return o}async function H(e,t,n){return t(n)?n:V(e,t,n)}function U(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 W(e,t){try{return await e(t)}catch{return t}}async function*G(e,t,n,i=0){let a=r(t);if(U(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(i>64||o.size>=1e5)return;let s=await W(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*K(e,t,a===`/`?`/${t.name}`:`${a}/${t.name}`,o,i+1)}async function*K(e,t,n,r,i){if(t.type===`file`){yield n;return}if(t.type===`symlink`){yield*q(e,n,r,i);return}yield*G(e,n,r,i)}async function*q(e,t,n,r){try{let i=await e.stat(t);i.type===`file`?yield t:i.type===`directory`&&(yield*G(e,t,n,r))}catch{}}function J(){try{if(typeof globalThis.navigator?.storage?.getDirectory==`function`)return`opfs`}catch{}return`memory`}var Y=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 A;static writeChains=new Map;constructor(e,n,r,i){if(this.dbName=e,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).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-CoWnU-QN.js`).then(e=>e.t),__vite__mapDeps([0,1])),e(()=>import(`./dist-Ca06zVsb.js`),__vite__mapDeps([2,0,1]))]);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-B31h6Aw0.js`);return{resolveWithSidecarRepair:e,repairOpfsMetadataSidecar:t}},[]),d=await i(r,()=>n.withWriteLock(()=>u(a)),e=>console.warn(`[virtual-fs] repaired poisoned metadata sidecar; retrying mount`,{dbName:n.dbName,kindFixed:e.kindFixed,sizesFixed:e.sizesFixed,dropped:e.dropped}));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-CoWnU-QN.js`).then(e=>e.t),__vite__mapDeps([0,1]));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 o(`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??J(),a=new t(n,r,i);return await a._ready,r&&await f().catch(()=>{}),a}async flush(){await this.writeOpfsMetadataSidecar()}async writeOpfsMetadataSidecar(){this.backend===`opfs`&&await this.withWriteLock(()=>this.writeOpfsMetadataSidecarUnlocked())}async writeOpfsMetadataSidecarUnlocked(){if(this.backend!==`opfs`)return;let 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&&(a=L(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())}markSidecarDirty(e,i=`path`){if(this.backend!==`opfs`)return;let a=t.opfsBackends.get(this.dbName)?.sidecarDirty;if(!a)return;let o=r(e);(i===`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=r(n);t.index.delete(e),t._handles?.delete(e),this.markSidecarDirty(e)}}canWrite(e){return!0}setWatcher(e){this.watcher=e}getWatcher(){return this.watcher}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-CoWnU-QN.js`).then(e=>e.t),__vite__mapDeps([0,1]))).umount(this.mountRoot)}catch{}}}}readDirSync(e){let t=r(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=r(e);if(this.findMount(t))return null;let i=this.lfsSync;if(typeof i.statSync!=`function`||typeof i.lstatSync!=`function`||typeof i.readlinkSync!=`function`)return null;let o=t;for(let e=0;e<=10;e++){let e;try{e=i.lstatSync(o)}catch{return null}if(!e.isSymbolicLink())return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs};let t;try{t=i.readlinkSync(o)}catch{return null}o=t.startsWith(`/`)?r(t):r(a(n(o).dir,t))}return null}lstatSync(e){let t=r(e);if(this.findMount(t))return null;let n=this.lfsSync;if(typeof n.lstatSync!=`function`)return null;try{let e=n.lstatSync(t);if(e.isSymbolicLink()){let r=n.readlinkSync?n.readlinkSync(t):``;return{type:`symlink`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,isSymlink:!0,symlinkTarget:r}}return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs}}catch{return null}}async mount(e,t,i){let a=r(e);if(this.mountPoints.has(a))throw new o(`EEXIST`,`mount point is already mounted`,a);try{if((await this.lstat(a)).type!==`directory`)throw new o(`ENOTDIR`,`mount point must be a directory`,a);if((await this.readDir(a)).length>0)throw new o(`ENOTEMPTY`,`mount point must be empty to avoid shadowing existing files`,a)}catch(e){if(!(e instanceof o)||e.code!==`ENOENT`)throw e}let{dir:s}=n(a);s!==`/`&&await this.mkdir(s,{recursive:!0});try{await this.lfs.mkdir(a)}catch{}if(this.mountPoints.set(a,t),t.kind===`local`){let e=k(i?.env??{});this.mountIndex.registerMount(a,t.getHandle(),e)}let c=t.kind===`local`?{kind:`local`,mountId:t.mountId,idbHandleKey:a}:t.kind===`s3`?{kind:`s3`,mountId:t.mountId,source:t.source,profile:t.profile??`default`}:{kind:`da`,mountId:t.mountId,source:t.source,profile:t.profile??`default`};try{this.mountSyncChannel?.postMessage({type:`mount`,path:a,descriptor:c})}catch{}this.watcher?.notify([{type:`modify`,path:a,entryType:`directory`}]);try{let e={targetPath:a,descriptor:c,createdAt:Date.now()},n=t.kind===`local`?t.getHandle():void 0;await l(e,n)}catch{}}async unmount(e){let t=r(e),n=this.mountPoints.get(t);this.mountPoints.delete(t),this.mountIndex.unregisterMount(t);try{this.mountSyncChannel?.postMessage({type:`unmount`,path:t})}catch{}this.watcher?.notify([{type:`modify`,path:t,entryType:`directory`}]),await n?.close();try{await u(t)}catch{}}async reconstructBackendFromDescriptor(t){switch(t.kind){case`local`:{let e=await d(t.idbHandleKey);if(!e)throw Error(`no handle stored for ${t.idbHandleKey}`);return c.fromHandle(e,{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-Cws5YfoU.js`);return{S3MountBackend:e,RemoteMountCache:t,makeSignedFetchS3:n}},__vite__mapDeps([3,4,5,6,7,8,1,9,10,11,12,13,14,15,16,17,18,19,20,21])),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-Cws5YfoU.js`);return{DaMountBackend:e,RemoteMountCache:t,makeSignedFetchDa:n}},__vite__mapDeps([3,4,5,6,7,8,1,9,10,11,12,13,14,15,16,17,18,19,20,21])),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 i=r(e);if(this.mountPoints.has(i))throw new o(`EEXIST`,`mount point is already mounted`,i);let{dir:a}=n(i);a!==`/`&&await this.mkdir(a,{recursive:!0});try{await this.lfs.mkdir(i)}catch{}this.mountPoints.set(i,t),this.internalMounts.add(i),this.watcher?.notify([{type:`modify`,path:i,entryType:`directory`}])}async unmountInternal(e){let t=r(e);if(!this.internalMounts.has(t))throw new o(`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=r(e),i=this.mountPoints.get(n);if(!i)throw new o(`ENOENT`,`not a mount point`,n);let a=await i.refresh(t);return i.kind===`local`&&await this.mountIndex.refreshMount(n,k(t?.env??{})),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){let n=r(e),i=this.findMount(n);if(i){if(i.relParts.length===0)throw new o(`EISDIR`,`is a directory`,n);let e=i.relParts.join(`/`);try{let n=await i.backend.readFile(e);return(t?.encoding??`utf-8`)===`utf-8`?new TextDecoder(`utf-8`).decode(n):n}catch(e){N(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 F(e,n)}}async writeFile(e,t,i){let a=r(e),s=this.findMount(a);if(s){if(s.relParts.length===0)throw new o(`EISDIR`,`is a directory`,a);let e=s.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 s.backend.writeFile(e,r)}catch(e){N(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 F(e,a)}}else throw F(e,a)}try{await this.lfs.truncate?.(c,e)}catch(e){throw F(e,a)}}),this.watcher?.notify([{type:l?`modify`:`create`,path:c,entryType:`file`}])}async readDir(e){let t=r(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){N(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){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 F(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=``;for(let e of t){n+=`/`+e;try{await this.lfs.mkdir(n)}catch(e){if(e instanceof Error&&!e.message.includes(`EEXIST`))throw F(e,n)}}}async mkdir(e,t){let n=r(e);if(n===`/`)return;let i=this.findMount(n);if(i){if(i.relParts.length===0)return;let e=i.relParts.join(`/`),t=await this.exists(n);try{await i.backend.mkdir(e)}catch(e){N(e,n)}t||this.watcher?.notify([{type:`create`,path:n,entryType:`directory`}]);return}t?.recursive?await this.withWriteLock(()=>(this.markSidecarDirty(n),this.mkdirRecursiveUnlocked(n))):(await this.withWriteLock(async()=>{this.markSidecarDirty(n);try{await this.lfs.mkdir(n)}catch(e){throw F(e,n)}}),this.watcher?.notify([{type:`create`,path:n,entryType:`directory`}]))}async rm(e,t){let n=r(e),i=this.findMount(n);if(i){if(i.relParts.length===0)throw new o(`EINVAL`,`cannot remove a mount point — use unmount`,n);let e;try{e=(await this.stat(n)).type}catch{}let r=i.relParts.join(`/`);try{await i.backend.remove(r,{recursive:t?.recursive})}catch(e){N(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 F(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){let t=r(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){N(e,t)}}let i=await this.resolveSymlinks(t);try{let e=await this.lfs.stat(i);return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs}}catch(e){throw F(e,t)}}async exists(e){let t=r(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){let n=r(e),i=r(t),a;try{a=(await this.lstat(n)).type}catch{}try{await this.withWriteLock(async()=>{this.markSidecarDirty(n,`prefix`),this.markSidecarDirty(i,`prefix`),await this.lfs.rename(n,i),await this.writeOpfsMetadataSidecarUnlocked()})}catch(e){throw F(e,n)}this.watcher?.notify([{type:`delete`,path:n,entryType:a},{type:`create`,path:i,entryType:a}]),this.mountIndex.notifyRename(n,i)}async readTextFile(e){return await this.readFile(e,{encoding:`utf-8`})}async*walk(e,t,n=0){yield*G({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 o(`EISDIR`,`is a directory`,e);let n=await this.readFile(e,{encoding:`binary`});await this.writeFile(t,n)}dirname(e){return n(r(e)).dir}basename(e){return n(r(e)).base}async symlink(e,t){let i=r(t);if(this.findMount(i))throw new o(`EINVAL`,`symlinks not supported on mounted filesystems`,i);let{dir:a}=n(i);await this.withWriteLock(async()=>{a!==`/`&&await this.mkdirRecursiveUnlocked(a);try{await this.lfs.symlink(e,i)}catch(t){if(a!==`/`&&t instanceof Error&&t.message.includes(`ENOENT`)){await this.mkdirRecursiveUnlocked(a);try{await this.lfs.symlink(e,i)}catch(e){throw F(e,i)}}else throw F(t,i)}this.markSidecarDirty(i),await this.writeOpfsMetadataSidecarUnlocked()}),this.watcher?.notify([{type:`create`,path:i,entryType:`symlink`}])}async readlink(e){let t=r(e);try{return await this.lfs.readlink(t)}catch(e){throw F(e,t)}}async lstat(e){let t=r(e);if(this.findMount(t))return this.stat(t);try{let e=await this.lfs.lstat(t);if(e.isSymbolicLink()){let n=await this.lfs.readlink(t);return{type:`symlink`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,isSymlink:!0,symlinkTarget:n}}return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs}}catch(e){throw F(e,t)}}async realpath(e){return V(this.lfs,e=>this.findMount(e)!==null,e)}resolveSymlinks(e){return H(this.lfs,e=>this.findMount(e)!==null,e)}};export{o as FsError,g as FsWatcher,A as MountIndex,M as RestrictedFS,Y as VirtualFS,a as joinPath,r as normalizePath,i as pathSegments,J as resolveVfsBackendFromEnv,n as splitPath};
@@ -1 +1 @@
1
- import{S as e,d as t,z as n}from"./account-store-BY3aXBTq.js";import{i as r}from"./proxied-fetch-BML_ivCH.js";import{r as i,t as a}from"./tray-runtime-config-ObNW_fQX.js";import{t as o}from"./global-db-DJXlpNui.js";import{r as s,t as c}from"./silent-renew-backoff-BrAZcbzt.js";import{getOAuthPageOrigin as l,resolveOAuthDelegation as u}from"./oauth-service-a6YE6xTR.js";import"./provider-settings-CsNUnYS7.js";var d={clientId:``,scopes:`repo,read:user,user:email`};function f(){try{let e=localStorage.getItem(i);if(e)return e.replace(/\/$/,``)}catch{}return a}async function p(e){let t;try{t=await e.json()}catch{throw Error(`Token exchange failed (HTTP ${e.status}): non-JSON response`)}if(!e.ok&&e.status!==200){let n=t.error_description??t.error??`Token exchange failed (HTTP ${e.status})`;throw Error(n)}if(t.error){let e=t.error_description??t.error;throw Error(e)}return t}async function m(e){let t=`${f()}/oauth/token`;return p(await fetch(t,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:e.provider,code:e.code,redirect_uri:e.redirectUri})}))}async function h(e){let t=`${f()}/oauth/token`;return p(await fetch(t,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:e.provider,refresh_token:e.refreshToken})}))}async function g(e){let t=`${f()}/oauth/revoke`,n=await fetch(t,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:e.provider,access_token:e.accessToken})});if(!(n.status===204||n.ok)){if(n.status===400)try{if((await n.json()).error===`unsupported`)return}catch{}throw Error(`Token revocation failed (HTTP ${n.status})`)}}const _=Object.assign({"/packages/webapp/providers/github-config.json":d})[`/packages/webapp/providers/github-config.json`]??{clientId:``,scopes:`repo,read:user,user:email`};let v=null,y=null;function b(e){let{isExtension:t,isConnectMode:n,workerBaseUrl:r,pageOrigin:i,pageHref:a,bridgeApiBaseUrl:o,extensionId:c,nonce:l}=e;if(t)return{redirectUri:`${r}/auth/callback`,state:{source:`extension`,extensionId:c,path:`/github`,nonce:l}};if(e.delegated)return{redirectUri:`${e.runtimeWorkerBaseUrl??r}/auth/callback`,state:{source:`opener`,path:`/auth/callback`,nonce:l}};if(n){let e=i??``;if(/^https?:\/\/(localhost|127\.0\.0\.1):\d+$/.test(e)){let t=parseInt(new URL(a??e).port||`8790`,10);return{redirectUri:`${r}/auth/callback`,state:{source:`local`,port:t,path:`/auth/callback`,nonce:l}}}return{redirectUri:`${r}/auth/callback`,state:{source:`remote`,origin:e,path:`/auth/callback`,nonce:l}}}if(o&&a&&s(a)){let t=null;try{let e=new URL(o);(e.hostname===`localhost`||e.hostname===`127.0.0.1`)&&(t=parseInt(e.port||`5710`,10))}catch{t=null}if(t!==null&&!Number.isNaN(t))return{redirectUri:`${e.runtimeWorkerBaseUrl??r}/auth/callback`,state:{source:`local`,port:t,path:`/auth/callback`,nonce:l}}}return{redirectUri:`${e.runtimeWorkerBaseUrl??i??``}/auth/callback`,state:{port:parseInt(new URL(a??i??`http://localhost:5710`).port||`5710`,10),path:`/auth/callback`,nonce:l}}}async function x(){if(v)return v;if(S){try{let e=await fetch(`${f()}/api/runtime-config`);if(e.ok){let t=await e.json();if(t.oauth?.github)return v=t.oauth.github,v}}catch{}return _.clientId}try{let e=await fetch(`/api/runtime-config`);if(e.ok){let t=await e.json();if(t.oauth?.github)return v=t.oauth.github,t.trayWorkerBaseUrl&&(y=t.trayWorkerBaseUrl),v;if(t.trayWorkerBaseUrl){y=t.trayWorkerBaseUrl;let e=await fetch(`${t.trayWorkerBaseUrl}/api/runtime-config`);if(e.ok){let t=await e.json();if(t.oauth?.github)return v=t.oauth.github,v}}}}catch{}return _.clientId}const S=typeof globalThis<`u`&&typeof globalThis.chrome?.runtime?.id==`string`;function C(){return t().find(e=>e.providerId===`github`)}function w(e){try{return new URL(e).searchParams.get(`code`)}catch{return null}}async function T(e){try{let t=await fetch(`https://api.github.com/user`,{headers:{Authorization:`Bearer ${e}`,Accept:`application/vnd.github+json`}});if(t.ok){let e=await t.json();return{name:e.name||e.login,avatar:e.avatar_url,login:e.login,id:e.id}}}catch(e){console.warn(`[github] Failed to fetch user profile:`,e instanceof Error?e.message:String(e))}return{}}function E(e,t){return`${e}+${t}@users.noreply.github.com`}async function D(e){try{let{VirtualFS:t}=await import(`./fs-1lpjBcH8.js`).then(e=>e.t);await(await t.create({dbName:o})).writeFile(`/workspace/.git/github-token`,e),typeof window<`u`&&window.dispatchEvent(new CustomEvent(`github-token-changed`))}catch(e){console.warn(`[github] Failed to write git token:`,e instanceof Error?e.message:String(e))}}async function O(){try{let{VirtualFS:e}=await import(`./fs-1lpjBcH8.js`).then(e=>e.t);await(await e.create({dbName:o})).rm(`/workspace/.git/github-token`),typeof window<`u`&&window.dispatchEvent(new CustomEvent(`github-token-changed`))}catch{}}async function k(e){if(!(!e.login||e.id===void 0))try{let{VirtualFS:t}=await import(`./fs-1lpjBcH8.js`).then(e=>e.t),{readGlobalGitConfigValue:n,writeGlobalGitConfigValue:r}=await import(`./git-config-DA8M5e8O.js`).then(e=>e.n),i=await t.create({dbName:o}),a=e.name||e.login,s=E(e.id,e.login);!await n(i,`user.name`)&&a&&await r(i,`user.name`,a),await n(i,`user.email`)||await r(i,`user.email`,s)}catch(e){console.warn(`[github] Failed to seed git identity:`,e instanceof Error?e.message:String(e))}}const A=c();async function j(){try{let t=C();if(!t?.refreshToken)return null;let r=await h({provider:`github`,refreshToken:t.refreshToken});await n({providerId:`github`,accessToken:r.access_token,refreshToken:r.refresh_token,tokenExpiresAt:r.expires_in?Date.now()+r.expires_in*1e3:void 0,userName:t.userName,userAvatar:t.userAvatar,scopes:r.scope??t.scopes});let i=e(`github`)?.maskedValue;return i?await D(i):await O(),r.access_token}catch(e){return console.warn(`[github] Silent renewal failed:`,e instanceof Error?e.message:String(e)),null}}async function M(){let e=C();if(!e?.accessToken)throw Error(`Not logged in to GitHub — please log in first`);if((e.tokenExpiresAt??1/0)-Date.now()>6e4)return e.accessToken;let t=await A.run(()=>j());if(t)return t;let n=C();if((n?.tokenExpiresAt??1/0)-Date.now()>0&&n?.accessToken)return n.accessToken;throw Error(`GitHub session expired — please log in again`)}const N={id:`github`,name:`GitHub`,description:"Sign in with GitHub for git authentication (push/pull/clone) and the `oauth-token github` shell command. Does not expose LLM models — use the GitHub Copilot provider for those.",requiresApiKey:!1,requiresBaseUrl:!1,isOAuth:!0,oauthTokenDomains:[`github.com`,`*.github.com`,`api.github.com`,`raw.githubusercontent.com`],getModelIds:()=>[],onOAuthLogin:async(t,i,a)=>{let o=await x();if(!o)throw Error(`GitHub OAuth not configured — no client ID available`);let s=a?.scopes??_.scopes,c=S?null:await l(),d=!S&&await u(),p=crypto.randomUUID(),h=S?chrome.runtime.id:``,{redirectUri:g,state:v}=b({isExtension:S,isConnectMode:!!globalThis.__slicc_connect_mode,workerBaseUrl:f(),runtimeWorkerBaseUrl:y,pageOrigin:c?.origin??null,pageHref:c?.href??null,bridgeApiBaseUrl:r(),delegated:d,extensionId:h,nonce:p}),C=btoa(JSON.stringify(v)),E=p,A=new URLSearchParams({client_id:o,scope:s,redirect_uri:g});C&&A.set(`state`,C);let j=await t(`https://github.com/login/oauth/authorize?${A}`);if(!j)return;if(E)try{if(new URL(j).searchParams.get(`nonce`)!==E){console.error(`[github] OAuth nonce mismatch — possible CSRF`);return}}catch(e){console.warn(`[github] Nonce check skipped (URL parse failed):`,e instanceof Error?e.message:String(e))}let M=w(j);if(!M){console.error(`[github] Could not extract authorization code from redirect URL`);return}let N=await m({provider:`github`,code:M,redirectUri:g}),P=await T(N.access_token);await n({providerId:`github`,accessToken:N.access_token,refreshToken:N.refresh_token,tokenExpiresAt:N.expires_in?Date.now()+N.expires_in*1e3:void 0,userName:P.name,userAvatar:P.avatar,scopes:N.scope});let F=e(`github`)?.maskedValue;F?await D(F):await O(),await k(P),i()},onSilentRenew:j,getValidAccessToken:M,onOAuthLogout:async()=>{let e=C();e?.accessToken&&await g({provider:`github`,accessToken:e.accessToken}).catch(e=>console.warn(`[github] Token revocation failed:`,e instanceof Error?e.message:String(e))),await O(),await n({providerId:`github`,accessToken:``})},getOAuthLogoutUrl:e=>`https://github.com/logout`};export{E as buildNoreplyEmail,N as config,w as extractCodeFromUrl,M as getValidAccessToken,b as resolveGithubOAuthRedirect,k as syncGitIdentityFromGitHub};
1
+ import{S as e,d as t,z as n}from"./account-store-BOj83xge.js";import{i as r}from"./proxied-fetch-BML_ivCH.js";import{r as i,t as a}from"./tray-runtime-config-ObNW_fQX.js";import{t as o}from"./global-db-DJXlpNui.js";import{r as s,t as c}from"./silent-renew-backoff-BrAZcbzt.js";import{getOAuthPageOrigin as l,resolveOAuthDelegation as u}from"./oauth-service-a6YE6xTR.js";import"./provider-settings-B76dsYi_.js";var d={clientId:``,scopes:`repo,read:user,user:email`};function f(){try{let e=localStorage.getItem(i);if(e)return e.replace(/\/$/,``)}catch{}return a}async function p(e){let t;try{t=await e.json()}catch{throw Error(`Token exchange failed (HTTP ${e.status}): non-JSON response`)}if(!e.ok&&e.status!==200){let n=t.error_description??t.error??`Token exchange failed (HTTP ${e.status})`;throw Error(n)}if(t.error){let e=t.error_description??t.error;throw Error(e)}return t}async function m(e){let t=`${f()}/oauth/token`;return p(await fetch(t,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:e.provider,code:e.code,redirect_uri:e.redirectUri})}))}async function h(e){let t=`${f()}/oauth/token`;return p(await fetch(t,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:e.provider,refresh_token:e.refreshToken})}))}async function g(e){let t=`${f()}/oauth/revoke`,n=await fetch(t,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:e.provider,access_token:e.accessToken})});if(!(n.status===204||n.ok)){if(n.status===400)try{if((await n.json()).error===`unsupported`)return}catch{}throw Error(`Token revocation failed (HTTP ${n.status})`)}}const _=Object.assign({"/packages/webapp/providers/github-config.json":d})[`/packages/webapp/providers/github-config.json`]??{clientId:``,scopes:`repo,read:user,user:email`};let v=null,y=null;function b(e){let{isExtension:t,isConnectMode:n,workerBaseUrl:r,pageOrigin:i,pageHref:a,bridgeApiBaseUrl:o,extensionId:c,nonce:l}=e;if(t)return{redirectUri:`${r}/auth/callback`,state:{source:`extension`,extensionId:c,path:`/github`,nonce:l}};if(e.delegated)return{redirectUri:`${e.runtimeWorkerBaseUrl??r}/auth/callback`,state:{source:`opener`,path:`/auth/callback`,nonce:l}};if(n){let e=i??``;if(/^https?:\/\/(localhost|127\.0\.0\.1):\d+$/.test(e)){let t=parseInt(new URL(a??e).port||`8790`,10);return{redirectUri:`${r}/auth/callback`,state:{source:`local`,port:t,path:`/auth/callback`,nonce:l}}}return{redirectUri:`${r}/auth/callback`,state:{source:`remote`,origin:e,path:`/auth/callback`,nonce:l}}}if(o&&a&&s(a)){let t=null;try{let e=new URL(o);(e.hostname===`localhost`||e.hostname===`127.0.0.1`)&&(t=parseInt(e.port||`5710`,10))}catch{t=null}if(t!==null&&!Number.isNaN(t))return{redirectUri:`${e.runtimeWorkerBaseUrl??r}/auth/callback`,state:{source:`local`,port:t,path:`/auth/callback`,nonce:l}}}return{redirectUri:`${e.runtimeWorkerBaseUrl??i??``}/auth/callback`,state:{port:parseInt(new URL(a??i??`http://localhost:5710`).port||`5710`,10),path:`/auth/callback`,nonce:l}}}async function x(){if(v)return v;if(S){try{let e=await fetch(`${f()}/api/runtime-config`);if(e.ok){let t=await e.json();if(t.oauth?.github)return v=t.oauth.github,v}}catch{}return _.clientId}try{let e=await fetch(`/api/runtime-config`);if(e.ok){let t=await e.json();if(t.oauth?.github)return v=t.oauth.github,t.trayWorkerBaseUrl&&(y=t.trayWorkerBaseUrl),v;if(t.trayWorkerBaseUrl){y=t.trayWorkerBaseUrl;let e=await fetch(`${t.trayWorkerBaseUrl}/api/runtime-config`);if(e.ok){let t=await e.json();if(t.oauth?.github)return v=t.oauth.github,v}}}}catch{}return _.clientId}const S=typeof globalThis<`u`&&typeof globalThis.chrome?.runtime?.id==`string`;function C(){return t().find(e=>e.providerId===`github`)}function w(e){try{return new URL(e).searchParams.get(`code`)}catch{return null}}async function T(e){try{let t=await fetch(`https://api.github.com/user`,{headers:{Authorization:`Bearer ${e}`,Accept:`application/vnd.github+json`}});if(t.ok){let e=await t.json();return{name:e.name||e.login,avatar:e.avatar_url,login:e.login,id:e.id}}}catch(e){console.warn(`[github] Failed to fetch user profile:`,e instanceof Error?e.message:String(e))}return{}}function E(e,t){return`${e}+${t}@users.noreply.github.com`}async function D(e){try{let{VirtualFS:t}=await import(`./fs-C2lY2r22.js`).then(e=>e.t);await(await t.create({dbName:o})).writeFile(`/workspace/.git/github-token`,e),typeof window<`u`&&window.dispatchEvent(new CustomEvent(`github-token-changed`))}catch(e){console.warn(`[github] Failed to write git token:`,e instanceof Error?e.message:String(e))}}async function O(){try{let{VirtualFS:e}=await import(`./fs-C2lY2r22.js`).then(e=>e.t);await(await e.create({dbName:o})).rm(`/workspace/.git/github-token`),typeof window<`u`&&window.dispatchEvent(new CustomEvent(`github-token-changed`))}catch{}}async function k(e){if(!(!e.login||e.id===void 0))try{let{VirtualFS:t}=await import(`./fs-C2lY2r22.js`).then(e=>e.t),{readGlobalGitConfigValue:n,writeGlobalGitConfigValue:r}=await import(`./git-config-DA8M5e8O.js`).then(e=>e.n),i=await t.create({dbName:o}),a=e.name||e.login,s=E(e.id,e.login);!await n(i,`user.name`)&&a&&await r(i,`user.name`,a),await n(i,`user.email`)||await r(i,`user.email`,s)}catch(e){console.warn(`[github] Failed to seed git identity:`,e instanceof Error?e.message:String(e))}}const A=c();async function j(){try{let t=C();if(!t?.refreshToken)return null;let r=await h({provider:`github`,refreshToken:t.refreshToken});await n({providerId:`github`,accessToken:r.access_token,refreshToken:r.refresh_token,tokenExpiresAt:r.expires_in?Date.now()+r.expires_in*1e3:void 0,userName:t.userName,userAvatar:t.userAvatar,scopes:r.scope??t.scopes});let i=e(`github`)?.maskedValue;return i?await D(i):await O(),r.access_token}catch(e){return console.warn(`[github] Silent renewal failed:`,e instanceof Error?e.message:String(e)),null}}async function M(){let e=C();if(!e?.accessToken)throw Error(`Not logged in to GitHub — please log in first`);if((e.tokenExpiresAt??1/0)-Date.now()>6e4)return e.accessToken;let t=await A.run(()=>j());if(t)return t;let n=C();if((n?.tokenExpiresAt??1/0)-Date.now()>0&&n?.accessToken)return n.accessToken;throw Error(`GitHub session expired — please log in again`)}const N={id:`github`,name:`GitHub`,description:"Sign in with GitHub for git authentication (push/pull/clone) and the `oauth-token github` shell command. Does not expose LLM models — use the GitHub Copilot provider for those.",requiresApiKey:!1,requiresBaseUrl:!1,isOAuth:!0,oauthTokenDomains:[`github.com`,`*.github.com`,`api.github.com`,`raw.githubusercontent.com`],getModelIds:()=>[],onOAuthLogin:async(t,i,a)=>{let o=await x();if(!o)throw Error(`GitHub OAuth not configured — no client ID available`);let s=a?.scopes??_.scopes,c=S?null:await l(),d=!S&&await u(),p=crypto.randomUUID(),h=S?chrome.runtime.id:``,{redirectUri:g,state:v}=b({isExtension:S,isConnectMode:!!globalThis.__slicc_connect_mode,workerBaseUrl:f(),runtimeWorkerBaseUrl:y,pageOrigin:c?.origin??null,pageHref:c?.href??null,bridgeApiBaseUrl:r(),delegated:d,extensionId:h,nonce:p}),C=btoa(JSON.stringify(v)),E=p,A=new URLSearchParams({client_id:o,scope:s,redirect_uri:g});C&&A.set(`state`,C);let j=await t(`https://github.com/login/oauth/authorize?${A}`);if(!j)return;if(E)try{if(new URL(j).searchParams.get(`nonce`)!==E){console.error(`[github] OAuth nonce mismatch — possible CSRF`);return}}catch(e){console.warn(`[github] Nonce check skipped (URL parse failed):`,e instanceof Error?e.message:String(e))}let M=w(j);if(!M){console.error(`[github] Could not extract authorization code from redirect URL`);return}let N=await m({provider:`github`,code:M,redirectUri:g}),P=await T(N.access_token);await n({providerId:`github`,accessToken:N.access_token,refreshToken:N.refresh_token,tokenExpiresAt:N.expires_in?Date.now()+N.expires_in*1e3:void 0,userName:P.name,userAvatar:P.avatar,scopes:N.scope});let F=e(`github`)?.maskedValue;F?await D(F):await O(),await k(P),i()},onSilentRenew:j,getValidAccessToken:M,onOAuthLogout:async()=>{let e=C();e?.accessToken&&await g({provider:`github`,accessToken:e.accessToken}).catch(e=>console.warn(`[github] Token revocation failed:`,e instanceof Error?e.message:String(e))),await O(),await n({providerId:`github`,accessToken:``})},getOAuthLogoutUrl:e=>`https://github.com/logout`};export{E as buildNoreplyEmail,N as config,w as extractCodeFromUrl,M as getValidAccessToken,b as resolveGithubOAuthRedirect,k as syncGitIdentityFromGitHub};
@@ -0,0 +1,2 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/fs-Dmq-Uipw.js","assets/preload-helper-Czpn1I53.js","assets/logger-DDBAeTLF.js","assets/path-utils-Rm3AltuN.js","assets/types-idfTVsM8.js","assets/virtual-device-paths-9EXC9iPp.js","assets/backend-local-D7Gqh_i1.js","assets/tool-ui-C-E235kX.js","assets/logger-BoSvu4mW.js","assets/picker-approval-CXL7T-sh.js","assets/mount-picker-popup-Bh-wMX4z.js","assets/rolldown-runtime-Dd_uD5pT.js","assets/picker-popup-BvzmBsGL.js","assets/runtime-env-DH4NDw4t.js","assets/mount-table-store-dY2IfQ5S.js"])))=>i.map(i=>d[i]);
2
+ import{S as e,d as t,z as n}from"./account-store-DZhNh1lP.js";import{t as r}from"./preload-helper-Czpn1I53.js";import{i}from"./proxied-fetch-ULPrH97b.js";import{i as a,t as o}from"./tray-runtime-config-C82czC62.js";import"./provider-settings-YcRcX51v.js";import{r as s,t as c}from"./silent-renew-backoff-tbYCpSw6.js";import{getOAuthPageOrigin as l,resolveOAuthDelegation as u}from"./oauth-service-Dmnx-pbE.js";import{t as d}from"./global-db-CbuLl-zx.js";var f={clientId:``,scopes:`repo,read:user,user:email`};function p(){try{let e=localStorage.getItem(a);if(e)return e.replace(/\/$/,``)}catch{}return o}async function m(e){let t;try{t=await e.json()}catch{throw Error(`Token exchange failed (HTTP ${e.status}): non-JSON response`)}if(!e.ok&&e.status!==200){let n=t.error_description??t.error??`Token exchange failed (HTTP ${e.status})`;throw Error(n)}if(t.error){let e=t.error_description??t.error;throw Error(e)}return t}async function h(e){let t=`${p()}/oauth/token`;return m(await fetch(t,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:e.provider,code:e.code,redirect_uri:e.redirectUri})}))}async function g(e){let t=`${p()}/oauth/token`;return m(await fetch(t,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:e.provider,refresh_token:e.refreshToken})}))}async function _(e){let t=`${p()}/oauth/revoke`,n=await fetch(t,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:e.provider,access_token:e.accessToken})});if(!(n.status===204||n.ok)){if(n.status===400)try{if((await n.json()).error===`unsupported`)return}catch{}throw Error(`Token revocation failed (HTTP ${n.status})`)}}var v=Object.assign({"/packages/webapp/providers/github-config.json":f})[`/packages/webapp/providers/github-config.json`]??{clientId:``,scopes:`repo,read:user,user:email`},y=null,b=null;function x(e){let{isExtension:t,isConnectMode:n,workerBaseUrl:r,pageOrigin:i,pageHref:a,bridgeApiBaseUrl:o,extensionId:c,nonce:l}=e;if(t)return{redirectUri:`${r}/auth/callback`,state:{source:`extension`,extensionId:c,path:`/github`,nonce:l}};if(e.delegated)return{redirectUri:`${e.runtimeWorkerBaseUrl??r}/auth/callback`,state:{source:`opener`,path:`/auth/callback`,nonce:l}};if(n){let e=i??``;if(/^https?:\/\/(localhost|127\.0\.0\.1):\d+$/.test(e)){let t=parseInt(new URL(a??e).port||`8790`,10);return{redirectUri:`${r}/auth/callback`,state:{source:`local`,port:t,path:`/auth/callback`,nonce:l}}}return{redirectUri:`${r}/auth/callback`,state:{source:`remote`,origin:e,path:`/auth/callback`,nonce:l}}}if(o&&a&&s(a)){let t=null;try{let e=new URL(o);(e.hostname===`localhost`||e.hostname===`127.0.0.1`)&&(t=parseInt(e.port||`5710`,10))}catch{t=null}if(t!==null&&!Number.isNaN(t))return{redirectUri:`${e.runtimeWorkerBaseUrl??r}/auth/callback`,state:{source:`local`,port:t,path:`/auth/callback`,nonce:l}}}return{redirectUri:`${e.runtimeWorkerBaseUrl??i??``}/auth/callback`,state:{port:parseInt(new URL(a??i??`http://localhost:5710`).port||`5710`,10),path:`/auth/callback`,nonce:l}}}async function S(){if(y)return y;if(C){try{let e=await fetch(`${p()}/api/runtime-config`);if(e.ok){let t=await e.json();if(t.oauth?.github)return y=t.oauth.github,y}}catch{}return v.clientId}try{let e=await fetch(`/api/runtime-config`);if(e.ok){let t=await e.json();if(t.oauth?.github)return y=t.oauth.github,t.trayWorkerBaseUrl&&(b=t.trayWorkerBaseUrl),y;if(t.trayWorkerBaseUrl){b=t.trayWorkerBaseUrl;let e=await fetch(`${t.trayWorkerBaseUrl}/api/runtime-config`);if(e.ok){let t=await e.json();if(t.oauth?.github)return y=t.oauth.github,y}}}}catch{}return v.clientId}var C=typeof globalThis<`u`&&typeof globalThis.chrome?.runtime?.id==`string`;function w(){return t().find(e=>e.providerId===`github`)}function T(e){try{return new URL(e).searchParams.get(`code`)}catch{return null}}async function E(e){try{let t=await fetch(`https://api.github.com/user`,{headers:{Authorization:`Bearer ${e}`,Accept:`application/vnd.github+json`}});if(t.ok){let e=await t.json();return{name:e.name||e.login,avatar:e.avatar_url,login:e.login,id:e.id}}}catch(e){console.warn(`[github] Failed to fetch user profile:`,e instanceof Error?e.message:String(e))}return{}}function D(e,t){return`${e}+${t}@users.noreply.github.com`}async function O(e){try{let{VirtualFS:t}=await r(async()=>{let{VirtualFS:e}=await import(`./fs-Dmq-Uipw.js`);return{VirtualFS:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14]));await(await t.create({dbName:d})).writeFile(`/workspace/.git/github-token`,e),typeof window<`u`&&window.dispatchEvent(new CustomEvent(`github-token-changed`))}catch(e){console.warn(`[github] Failed to write git token:`,e instanceof Error?e.message:String(e))}}async function k(){try{let{VirtualFS:e}=await r(async()=>{let{VirtualFS:e}=await import(`./fs-Dmq-Uipw.js`);return{VirtualFS:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14]));await(await e.create({dbName:d})).rm(`/workspace/.git/github-token`),typeof window<`u`&&window.dispatchEvent(new CustomEvent(`github-token-changed`))}catch{}}async function A(e){if(!(!e.login||e.id===void 0))try{let{VirtualFS:t}=await r(async()=>{let{VirtualFS:e}=await import(`./fs-Dmq-Uipw.js`);return{VirtualFS:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14])),{readGlobalGitConfigValue:n,writeGlobalGitConfigValue:i}=await r(async()=>{let{readGlobalGitConfigValue:e,writeGlobalGitConfigValue:t}=await import(`./git-config-DLJIrKjL.js`);return{readGlobalGitConfigValue:e,writeGlobalGitConfigValue:t}},[]),a=await t.create({dbName:d}),o=e.name||e.login,s=D(e.id,e.login);!await n(a,`user.name`)&&o&&await i(a,`user.name`,o),await n(a,`user.email`)||await i(a,`user.email`,s)}catch(e){console.warn(`[github] Failed to seed git identity:`,e instanceof Error?e.message:String(e))}}var j=c();async function M(){try{let t=w();if(!t?.refreshToken)return null;let r=await g({provider:`github`,refreshToken:t.refreshToken});await n({providerId:`github`,accessToken:r.access_token,refreshToken:r.refresh_token,tokenExpiresAt:r.expires_in?Date.now()+r.expires_in*1e3:void 0,userName:t.userName,userAvatar:t.userAvatar,scopes:r.scope??t.scopes});let i=e(`github`)?.maskedValue;return i?await O(i):await k(),r.access_token}catch(e){return console.warn(`[github] Silent renewal failed:`,e instanceof Error?e.message:String(e)),null}}async function N(){let e=w();if(!e?.accessToken)throw Error(`Not logged in to GitHub — please log in first`);if((e.tokenExpiresAt??1/0)-Date.now()>6e4)return e.accessToken;let t=await j.run(()=>M());if(t)return t;let n=w();if((n?.tokenExpiresAt??1/0)-Date.now()>0&&n?.accessToken)return n.accessToken;throw Error(`GitHub session expired — please log in again`)}var P={id:`github`,name:`GitHub`,description:"Sign in with GitHub for git authentication (push/pull/clone) and the `oauth-token github` shell command. Does not expose LLM models — use the GitHub Copilot provider for those.",requiresApiKey:!1,requiresBaseUrl:!1,isOAuth:!0,oauthTokenDomains:[`github.com`,`*.github.com`,`api.github.com`,`raw.githubusercontent.com`],getModelIds:()=>[],onOAuthLogin:async(t,r,a)=>{let o=await S();if(!o)throw Error(`GitHub OAuth not configured — no client ID available`);let s=a?.scopes??v.scopes,c=C?null:await l(),d=!C&&await u(),f=crypto.randomUUID(),m=C?chrome.runtime.id:``,{redirectUri:g,state:_}=x({isExtension:C,isConnectMode:!!globalThis.__slicc_connect_mode,workerBaseUrl:p(),runtimeWorkerBaseUrl:b,pageOrigin:c?.origin??null,pageHref:c?.href??null,bridgeApiBaseUrl:i(),delegated:d,extensionId:m,nonce:f}),y=btoa(JSON.stringify(_)),w=f,D=new URLSearchParams({client_id:o,scope:s,redirect_uri:g});y&&D.set(`state`,y);let j=await t(`https://github.com/login/oauth/authorize?${D}`);if(!j)return;if(w)try{if(new URL(j).searchParams.get(`nonce`)!==w){console.error(`[github] OAuth nonce mismatch — possible CSRF`);return}}catch(e){console.warn(`[github] Nonce check skipped (URL parse failed):`,e instanceof Error?e.message:String(e))}let M=T(j);if(!M){console.error(`[github] Could not extract authorization code from redirect URL`);return}let N=await h({provider:`github`,code:M,redirectUri:g}),P=await E(N.access_token);await n({providerId:`github`,accessToken:N.access_token,refreshToken:N.refresh_token,tokenExpiresAt:N.expires_in?Date.now()+N.expires_in*1e3:void 0,userName:P.name,userAvatar:P.avatar,scopes:N.scope});let F=e(`github`)?.maskedValue;F?await O(F):await k(),await A(P),r()},onSilentRenew:M,getValidAccessToken:N,onOAuthLogout:async()=>{let e=w();e?.accessToken&&await _({provider:`github`,accessToken:e.accessToken}).catch(e=>console.warn(`[github] Token revocation failed:`,e instanceof Error?e.message:String(e))),await k(),await n({providerId:`github`,accessToken:``})},getOAuthLogoutUrl:e=>`https://github.com/logout`};export{D as buildNoreplyEmail,P as config,T as extractCodeFromUrl,N as getValidAccessToken,x as resolveGithubOAuthRedirect,A as syncGitIdentityFromGitHub};