sliccy 6.110.2 → 6.110.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (144) hide show
  1. package/README.md +1 -1
  2. package/dist/node-server/_cloud_core/src/cone-config/index.d.ts.map +1 -1
  3. package/dist/node-server/_cloud_core/src/cone-config/index.js +9 -6
  4. package/dist/node-server/electron-runtime.d.ts +9 -0
  5. package/dist/node-server/electron-runtime.js +3 -3
  6. package/dist/ui/.vite/manifest.json +173 -165
  7. package/dist/ui/assets/{account-store-Bg1KKHOx.js → account-store-8BBweMEe.js} +3 -3
  8. package/dist/ui/assets/{account-store-8sKKUZ8J.js → account-store-DaG5fzPt.js} +1 -1
  9. package/dist/ui/assets/{adobe-0CWIpyju.js → adobe-ShrE3fLm.js} +1 -1
  10. package/dist/ui/assets/{adobe-ChXsF6gw.js → adobe-lW1zO2xc.js} +2 -2
  11. package/dist/ui/assets/{agent-bridge-B43SVYcu.js → agent-bridge-DnjqW2rF.js} +1 -1
  12. package/dist/ui/assets/{agent-panels-9uCI5yeM.js → agent-panels-BUwuB3TG.js} +1 -1
  13. package/dist/ui/assets/{apply-layout-Bz-0rXhV.js → apply-layout-z0iSraqj.js} +1 -1
  14. package/dist/ui/assets/{apps-C16RztyU.js → apps-BJxy_wtK.js} +1 -1
  15. package/dist/ui/assets/{azure-openai-BCKGDF-y.js → azure-openai-BfsbnpvG.js} +1 -1
  16. package/dist/ui/assets/{azure-openai-DoQszniP.js → azure-openai-CtT9zy2b.js} +1 -1
  17. package/dist/ui/assets/{bsh-watchdog--Df_ThJG.js → bsh-watchdog-COvv_9Ni.js} +1 -1
  18. package/dist/ui/assets/{cdp-BzUC7d2h.js → cdp-D8RM1G3G.js} +1 -1
  19. package/dist/ui/assets/{cerebras-kH_bQsg2.js → cerebras-DPUsdgrQ.js} +1 -1
  20. package/dist/ui/assets/{cerebras-CQwhL4Ig.js → cerebras-b6VkvqMq.js} +1 -1
  21. package/dist/ui/assets/{connect-surface-BMrb-EnN.js → connect-surface-RDU90Juf.js} +1 -1
  22. package/dist/ui/assets/{directed-approval-zeD_orXz.js → directed-approval-DONBhcot.js} +1 -1
  23. package/dist/ui/assets/{follower-navigate-watcher-BoAzVfrf.js → follower-navigate-watcher-DKoozuvB.js} +1 -1
  24. package/dist/ui/assets/fs-CsuRlf5M.js +2 -0
  25. package/dist/ui/assets/{fs-DKRiXKHo.js → fs-DJCrdGnR.js} +1 -1
  26. package/dist/ui/assets/github-CAiprKij.js +1 -0
  27. package/dist/ui/assets/github-DWOc5kg-.js +2 -0
  28. package/dist/ui/assets/{github-copilot-DJf8cE1K.js → github-copilot-Bil4uk_l.js} +1 -1
  29. package/dist/ui/assets/{github-copilot-Xp2l1YxD.js → github-copilot-CJL7AnKr.js} +1 -1
  30. package/dist/ui/assets/{github-install-DRa8AaBY.js → github-install-CndOdb4D.js} +1 -1
  31. package/dist/ui/assets/{github-zip-BpPiUirA.js → github-zip-BY8CZlGS.js} +1 -1
  32. package/dist/ui/assets/intercepted-oauth-B0tP4D7f.js +1 -0
  33. package/dist/ui/assets/{js-realm-worker-D6DSLfXh.js → js-realm-worker-DlEUeX9A.js} +4 -4
  34. package/dist/ui/assets/{kernel-worker-DQDT4Cud.js → kernel-worker-bde26G1-.js} +645 -645
  35. package/dist/ui/assets/{lick-urls-51I5JBZv.js → lick-urls-CLl4eksX.js} +1 -1
  36. package/dist/ui/assets/lick-ws-bridge-BD2lQGbd.js +1 -0
  37. package/dist/ui/assets/{lick-ws-bridge-rxCk9AYw.js → lick-ws-bridge-HrxtV3Ht.js} +1 -1
  38. package/dist/ui/assets/{local-llm-OBHKAcNH.js → local-llm-C62wy8Df.js} +2 -2
  39. package/dist/ui/assets/local-llm-CWREzZ3O.js +2 -0
  40. package/dist/ui/assets/main-Cj0dR__R.js +22 -0
  41. package/dist/ui/assets/main-cherry-DR23QV8d.js +1 -0
  42. package/dist/ui/assets/{mount-BrQpW9eO.js → mount-DOTTHKHC.js} +1 -1
  43. package/dist/ui/assets/{mount-Rb9VVKip.js → mount-DPQd6tzy.js} +2 -2
  44. package/dist/ui/assets/{mount-recovery-Cb-AXW35.js → mount-recovery-VYeNQaYC.js} +1 -1
  45. package/dist/ui/assets/navigation-watcher-DLdGNtAZ.js +1 -0
  46. package/dist/ui/assets/new-session-CSBZYMGL.js +2 -0
  47. package/dist/ui/assets/oauth-bootstrap-DexuY7VO.js +2 -0
  48. package/dist/ui/assets/oauth-service-NaEg6KHx.js +1 -0
  49. package/dist/ui/assets/{oauth-service-CUpgufjo.js → oauth-service-TDESX_tk.js} +1 -1
  50. package/dist/ui/assets/{onboarding-orchestrator-Dmh6rOJl.js → onboarding-orchestrator-D0go0maQ.js} +1 -1
  51. package/dist/ui/assets/{openai-codex-DY_L0KSA.js → openai-codex-CHbj2YKL.js} +1 -1
  52. package/dist/ui/assets/{openai-codex-84EHUcAD.js → openai-codex-CO0FHasF.js} +1 -1
  53. package/dist/ui/assets/{openrouter-z7GGvxCM.js → openrouter-581ltIhi.js} +1 -1
  54. package/dist/ui/assets/{openrouter-meLV8ehE.js → openrouter-mBQeNixz.js} +1 -1
  55. package/dist/ui/assets/{openrouter-oauth-DudFNSW4.js → openrouter-oauth-GybmBe0R.js} +1 -1
  56. package/dist/ui/assets/{openrouter-oauth-CblQ27-K.js → openrouter-oauth-TZF0LEyZ.js} +1 -1
  57. package/dist/ui/assets/{panel-rpc-handlers-DmiAyTiy.js → panel-rpc-handlers-CRRp4c_O.js} +2 -2
  58. package/dist/ui/assets/{panelize-shell-65i9Hq7n.js → panelize-shell-Cqfllxbd.js} +1 -1
  59. package/dist/ui/assets/{provider-BE0mTIGf.js → provider-1riqfMR-.js} +1 -1
  60. package/dist/ui/assets/provider-CSdxYAI8.js +2 -0
  61. package/dist/ui/assets/provider-settings-ZgbgciKR.js +1 -0
  62. package/dist/ui/assets/provider-store-access-D_fJtNHf.js +1 -0
  63. package/dist/ui/assets/provider-store-access-YJf60jWB.js +1 -0
  64. package/dist/ui/assets/{providers-BlPz5ou6.js → providers-BZF0GlsK.js} +1 -1
  65. package/dist/ui/assets/providers-DpEbKMV3.js +2 -0
  66. package/dist/ui/assets/{quick-llm-CcFoANd_.js → quick-llm-Bs6a9ohB.js} +1 -1
  67. package/dist/ui/assets/{recovery-screen-44Uu5Cgy.js → recovery-screen-GaJzi_nj.js} +1 -1
  68. package/dist/ui/assets/{redirect-uri-C_VlH29S.js → redirect-uri-LEkhAfJa.js} +1 -1
  69. package/dist/ui/assets/{remote-terminal-view-vsJYhJKi.js → remote-terminal-view-HlQtiCdZ.js} +1 -1
  70. package/dist/ui/assets/{run-BQu73khp.js → run-BBmtyuxB.js} +1 -1
  71. package/dist/ui/assets/{secret-env-Hwyj0iR1.js → secret-env-CvkpMxjz.js} +1 -1
  72. package/dist/ui/assets/secrets-bridge-client-H8-Z1RVR.js +1 -0
  73. package/dist/ui/assets/{setup-feature-flags-remote-ITlSmr_i.js → setup-feature-flags-remote-CAAIusTL.js} +1 -1
  74. package/dist/ui/assets/sidecar-repair-CEmls84u.js +1 -0
  75. package/dist/ui/assets/{skills-B0o8gPTv.js → skills-C1BCxtxJ.js} +2 -2
  76. package/dist/ui/assets/slicc-version-CE2qd08F.js +1 -0
  77. package/dist/ui/assets/state-Cf1Y6pFo.js +42 -0
  78. package/dist/ui/assets/{store-C3RMRz9d.js → store-C5WIQl6U.js} +1 -1
  79. package/dist/ui/assets/{store-CzQ9Fvfr.js → store-DrDjrRj2.js} +1 -1
  80. package/dist/ui/assets/{sudo-CPH7ANoV.js → sudo-CCTcrBIJ.js} +1 -1
  81. package/dist/ui/assets/{sync-dialog-vSEl3KxP.js → sync-dialog-BRwkEszT.js} +1 -1
  82. package/dist/ui/assets/tool-ui-DCY2mIe9.js +1 -0
  83. package/dist/ui/assets/tray-leader-CHHSfFEB.js +1 -0
  84. package/dist/ui/assets/{tray-leave-runtime-3_wlFPFU.js → tray-leave-runtime-OxVT1X8O.js} +1 -1
  85. package/dist/ui/assets/tray-runtime-config-CjsIUSv2.js +1 -0
  86. package/dist/ui/assets/tray-runtime-config-CluPgaPA.js +1 -0
  87. package/dist/ui/assets/{tray-sidecar-BIcoXTJN.js → tray-sidecar-Bnp-I8VZ.js} +1 -1
  88. package/dist/ui/assets/tray-url-config-Cx0gvYq6.js +1 -0
  89. package/dist/ui/assets/{upgrade-detection-TsOPChOa.js → upgrade-detection-B-ic_s-w.js} +1 -1
  90. package/dist/ui/assets/{voice-reply-O_Z2C0eg.js → voice-reply-vHjs6Lwz.js} +1 -1
  91. package/dist/ui/assets/{wc-attach-DM5yRZRS.js → wc-attach-D1Wbe7BQ.js} +2 -2
  92. package/dist/ui/assets/wc-extension-K69BtExa.js +2 -0
  93. package/dist/ui/assets/{wc-float-label-Bmp3gmHN.js → wc-float-label-BLvU2814.js} +1 -1
  94. package/dist/ui/assets/wc-floatbar-online-WxVLXUuL.js +1 -0
  95. package/dist/ui/assets/wc-follower-MBwg6NpZ.js +17 -0
  96. package/dist/ui/assets/{wc-follower-oauth-D15d_vbh.js → wc-follower-oauth-DL2btuX4.js} +1 -1
  97. package/dist/ui/assets/{wc-live-CiwhsK8i.js → wc-live-D9C2qb2I.js} +6 -6
  98. package/dist/ui/assets/wc-nav-CUf1Z_Tr.js +2 -0
  99. package/dist/ui/assets/{wc-onboarding-DUBWYyMl.js → wc-onboarding-BOIXS806.js} +2 -2
  100. package/dist/ui/assets/{wc-permissions-CCJrTH49.js → wc-permissions-BxpV8lGq.js} +2 -2
  101. package/dist/ui/assets/{wc-placeholder-CPMV2eO3.js → wc-placeholder-CUfZIfzI.js} +3 -3
  102. package/dist/ui/assets/{wc-settings-M8e_JWQh.js → wc-settings-DhhxNWv_.js} +3 -3
  103. package/dist/ui/assets/{wc-shell-WlrdsROD.js → wc-shell-BU2i4AQi.js} +3 -3
  104. package/dist/ui/assets/{wc-shortcut-config-BftmZXGf.js → wc-shortcut-config-CtIiNVQ9.js} +1 -1
  105. package/dist/ui/assets/{wc-sprinkles-DhXJLTUO.js → wc-sprinkles-C9wtNI-h.js} +2 -2
  106. package/dist/ui/assets/wc-transcript-export-By3cf4BN.js +2 -0
  107. package/dist/ui/assets/{wc-tray-BdgbNPhM.js → wc-tray-BLqE4RP_.js} +4 -4
  108. package/dist/ui/assets/welcome-detection-e5PqkJPl.js +1 -0
  109. package/dist/ui/assets/{xai-grok-CVEtAfJK.js → xai-grok-B-Ekm4Mp.js} +1 -1
  110. package/dist/ui/assets/{xai-grok-DH1oX2E5.js → xai-grok-CHr7urYe.js} +1 -1
  111. package/dist/ui/index.html +6 -5
  112. package/dist/ui/packages/webapp/index.html +6 -5
  113. package/package.json +5 -4
  114. package/dist/ui/assets/fs-BsqtoiKD.js +0 -2
  115. package/dist/ui/assets/github-DGUqMidV.js +0 -1
  116. package/dist/ui/assets/github-DqsEulTB.js +0 -2
  117. package/dist/ui/assets/intercepted-oauth-BIKnTjZm.js +0 -1
  118. package/dist/ui/assets/lick-ws-bridge-1UPwiSVX.js +0 -1
  119. package/dist/ui/assets/local-llm-Cjzjpqa1.js +0 -2
  120. package/dist/ui/assets/logger-DQgFbfwx.js +0 -1
  121. package/dist/ui/assets/main-BK-7ArIz.js +0 -22
  122. package/dist/ui/assets/main-cherry-C6fqCnLL.js +0 -1
  123. package/dist/ui/assets/navigation-watcher-DrWMx-B4.js +0 -1
  124. package/dist/ui/assets/new-session-CF4YpiQ9.js +0 -2
  125. package/dist/ui/assets/oauth-bootstrap-YFOy1SIX.js +0 -2
  126. package/dist/ui/assets/oauth-service-DJuzPXsg.js +0 -1
  127. package/dist/ui/assets/provider-BLbTGk-_.js +0 -2
  128. package/dist/ui/assets/provider-settings-Dq-yRgMh.js +0 -1
  129. package/dist/ui/assets/provider-store-access-CJdYrcvf.js +0 -1
  130. package/dist/ui/assets/provider-store-access-NHOQWINx.js +0 -1
  131. package/dist/ui/assets/providers-B3OPYf2o.js +0 -2
  132. package/dist/ui/assets/secrets-bridge-client-CHZomqvU.js +0 -1
  133. package/dist/ui/assets/sidecar-repair-Ddcz9Mvv.js +0 -1
  134. package/dist/ui/assets/slicc-version-BrPYMXS9.js +0 -1
  135. package/dist/ui/assets/state-BSTmV4yO.js +0 -42
  136. package/dist/ui/assets/tray-leader-B_FxjW0d.js +0 -1
  137. package/dist/ui/assets/tray-runtime-config-Bpo7AZhY.js +0 -1
  138. package/dist/ui/assets/tray-runtime-config-Dv3NVv5v.js +0 -1
  139. package/dist/ui/assets/wc-extension-Dg5dOqTK.js +0 -2
  140. package/dist/ui/assets/wc-floatbar-online-B8ug4UwE.js +0 -1
  141. package/dist/ui/assets/wc-follower-G03aUmAn.js +0 -17
  142. package/dist/ui/assets/wc-nav-D8Bi3zRA.js +0 -2
  143. package/dist/ui/assets/wc-transcript-export-DjpmBvLP.js +0 -2
  144. package/dist/ui/assets/welcome-detection-0SaDZUV0.js +0 -1
@@ -1,4 +1,4 @@
1
- import{t as e}from"./logger-LESFN7Hj.js";import"./logger-DQgFbfwx.js";import{t}from"./esbuild-wasm-Dl3vgXvq.js";const n=e(`bsh-watchdog`),r=`.bsh scripts must be pre-bundled. Install deps via \`ipk add <pkg>\`, then bootstrap esbuild via \`ipk add esbuild-wasm@${t}\` and bundle with \`esbuild --bundle <script>.bsh --outfile=<script>.bundled.bsh\`. Drop the bundled file in place. There is no runtime resolver in the target page.`;var i=class{transport;browserAPI;fs;scriptCatalog;running=!1;executing=new Set;constructor(e){if(!e.transport&&!e.browserAPI)throw Error(`BshWatchdog requires either transport or browserAPI`);if(!e.scriptCatalog)throw Error(`BshWatchdog requires a ScriptCatalog`);this.browserAPI=e.browserAPI,this.transport=e.transport??e.browserAPI.getTransport(),this.fs=e.fs,this.scriptCatalog=e.scriptCatalog}async start(){if(this.running)return;this.running=!0,this.transport.on(`Page.frameNavigated`,this.onFrameNavigated),this.browserAPI&&this.browserAPI.setSessionChangeCallback((e,t)=>{t!==this.transport&&this.setTransport(t)});let e;try{e=(await this.scriptCatalog.getBshEntries()).length}catch(e){n.warn(`BSH watchdog startup discovery failed`,{error:e instanceof Error?e.message:String(e)})}n.info(`BSH watchdog started`,e===void 0?void 0:{scriptCount:e})}stop(){this.running&&(this.running=!1,this.transport.off(`Page.frameNavigated`,this.onFrameNavigated),this.browserAPI&&this.browserAPI.setSessionChangeCallback(void 0),this.executing.clear(),n.info(`BSH watchdog stopped`))}setTransport(e){e!==this.transport&&(this.transport.off(`Page.frameNavigated`,this.onFrameNavigated),this.transport=e,this.running&&this.transport.on(`Page.frameNavigated`,this.onFrameNavigated),n.info(`BSH watchdog transport swapped`))}async discover(){this.scriptCatalog.invalidateBsh(),await this.scriptCatalog.getBshEntries()}async getEntries(){return this.scriptCatalog.getBshEntries()}onFrameNavigated=e=>{let t=e.frame;if(t?.parentId||!t?.url)return;let r=t.url,i=e.sessionId;if(!(!r.startsWith(`http://`)&&!r.startsWith(`https://`))){if(!i){n.warn(`BSH watchdog: no sessionId in Page.frameNavigated params, skipping`,{url:r});return}this.scriptCatalog.findMatchingBshScripts(r).then(e=>{if(e.length!==0)for(let t of e){let e=`${t.path}::${r}`;this.executing.has(e)||(this.executing.add(e),n.info(`BSH watchdog executing script`,{script:t.path,url:r}),this.executeInTargetPage(t.path,r,i).then(()=>{n.info(`BSH script completed`,{script:t.path,url:r})}).catch(e=>{n.error(`BSH script execution error`,{script:t.path,url:r,error:e instanceof Error?e.message:String(e)})}).finally(()=>{this.executing.delete(e)}))}}).catch(e=>{n.error(`BSH discovery failed`,{url:r,error:e instanceof Error?e.message:String(e)})})}};async executeInTargetPage(e,t,i){let a=await this.fs.readFile(e),o=typeof a==`string`?a:new TextDecoder().decode(a),s=`(async () => {
1
+ import{t as e}from"./logger-LESFN7Hj.js";import{t}from"./esbuild-wasm-Dl3vgXvq.js";const n=e(`bsh-watchdog`),r=`.bsh scripts must be pre-bundled. Install deps via \`ipk add <pkg>\`, then bootstrap esbuild via \`ipk add esbuild-wasm@${t}\` and bundle with \`esbuild --bundle <script>.bsh --outfile=<script>.bundled.bsh\`. Drop the bundled file in place. There is no runtime resolver in the target page.`;var i=class{transport;browserAPI;fs;scriptCatalog;running=!1;executing=new Set;constructor(e){if(!e.transport&&!e.browserAPI)throw Error(`BshWatchdog requires either transport or browserAPI`);if(!e.scriptCatalog)throw Error(`BshWatchdog requires a ScriptCatalog`);this.browserAPI=e.browserAPI,this.transport=e.transport??e.browserAPI.getTransport(),this.fs=e.fs,this.scriptCatalog=e.scriptCatalog}async start(){if(this.running)return;this.running=!0,this.transport.on(`Page.frameNavigated`,this.onFrameNavigated),this.browserAPI&&this.browserAPI.setSessionChangeCallback((e,t)=>{t!==this.transport&&this.setTransport(t)});let e;try{e=(await this.scriptCatalog.getBshEntries()).length}catch(e){n.warn(`BSH watchdog startup discovery failed`,{error:e instanceof Error?e.message:String(e)})}n.info(`BSH watchdog started`,e===void 0?void 0:{scriptCount:e})}stop(){this.running&&(this.running=!1,this.transport.off(`Page.frameNavigated`,this.onFrameNavigated),this.browserAPI&&this.browserAPI.setSessionChangeCallback(void 0),this.executing.clear(),n.info(`BSH watchdog stopped`))}setTransport(e){e!==this.transport&&(this.transport.off(`Page.frameNavigated`,this.onFrameNavigated),this.transport=e,this.running&&this.transport.on(`Page.frameNavigated`,this.onFrameNavigated),n.info(`BSH watchdog transport swapped`))}async discover(){this.scriptCatalog.invalidateBsh(),await this.scriptCatalog.getBshEntries()}async getEntries(){return this.scriptCatalog.getBshEntries()}onFrameNavigated=e=>{let t=e.frame;if(t?.parentId||!t?.url)return;let r=t.url,i=e.sessionId;if(!(!r.startsWith(`http://`)&&!r.startsWith(`https://`))){if(!i){n.warn(`BSH watchdog: no sessionId in Page.frameNavigated params, skipping`,{url:r});return}this.scriptCatalog.findMatchingBshScripts(r).then(e=>{if(e.length!==0)for(let t of e){let e=`${t.path}::${r}`;this.executing.has(e)||(this.executing.add(e),n.info(`BSH watchdog executing script`,{script:t.path,url:r}),this.executeInTargetPage(t.path,r,i).then(()=>{n.info(`BSH script completed`,{script:t.path,url:r})}).catch(e=>{n.error(`BSH script execution error`,{script:t.path,url:r,error:e instanceof Error?e.message:String(e)})}).finally(()=>{this.executing.delete(e)}))}}).catch(e=>{n.error(`BSH discovery failed`,{url:r,error:e instanceof Error?e.message:String(e)})})}};async executeInTargetPage(e,t,i){let a=await this.fs.readFile(e),o=typeof a==`string`?a:new TextDecoder().decode(a),s=`(async () => {
2
2
  const __requireSpecifiers = (function() {
3
3
  const re = /require\\s*\\(\\s*['"]([^'"]+)['"]\\s*\\)/g;
4
4
  const code = ${JSON.stringify(o)};
@@ -1,4 +1,4 @@
1
- import{t as e}from"./logger-DDBAeTLF.js";import"./remote-cdp-transport-DeDqT7I4.js";import{n as t,t as n}from"./pending-request-table-Dgn6qYdL.js";import"./logger-BoSvu4mW.js";import"./navigation-watcher-DrWMx-B4.js";var r=e(`cdp`),i=4001,a=class{ws=null;nextId=1;_superseded=!1;pending=new n;listeners=new Map;_state=`disconnected`;get state(){return this._state}get superseded(){return this._superseded}async connect(e){if(this._state!==`disconnected`)throw Error(`Cannot connect: state is ${this._state}`);if(!e?.url)throw Error(`CDPClient.connect() requires a WebSocket URL`);let{url:t,timeout:n=5e3,protocols:i}=e;return this._state=`connecting`,new Promise((e,a)=>{let o=setTimeout(()=>{this.cleanup(),a(Error(`CDP connection timed out after ${n}ms`))},n);try{this.ws=i===void 0?new WebSocket(t):new WebSocket(t,i)}catch(e){clearTimeout(o),this._state=`disconnected`,a(e);return}this.ws.onopen=()=>{clearTimeout(o),this._state=`connected`,this._superseded=!1,r.info(`Connected`,{url:t}),e()},this.ws.onerror=e=>{clearTimeout(o),this._state===`connecting`&&(r.error(`Connection failed`,{url:t}),this.cleanup(),a(Error(`CDP WebSocket connection failed`)))},this.ws.onmessage=e=>{this.handleMessage(e.data)},this.ws.onclose=e=>{this.handleClose(e?.code)}})}disconnect(){this.ws&&(this.ws.onclose=null,this.ws.close()),this._superseded=!1,this.cleanup(),r.info(`Disconnected`)}async send(e,t,n,i=3e4){if(this._state!==`connected`||!this.ws)throw Error(`CDP client is not connected`);let a=this.nextId++,o={id:a,method:e};t&&(o.params=t),n&&(o.sessionId=n),r.debug(`Send`,{method:e,id:a,sessionId:n});let s=this.pending.issue(a,i,`CDP command timed out after ${i}ms: ${e}`);return this.ws.send(JSON.stringify(o)),s}on(e,t){let n=this.listeners.get(e);n||(n=new Set,this.listeners.set(e,n)),n.add(t)}off(e,t){let n=this.listeners.get(e);n&&(n.delete(t),n.size===0&&this.listeners.delete(e))}once(e,n=3e4){return t(t=>(this.on(e,t),()=>this.off(e,t)),n,`Timed out waiting for event: ${e}`)}handleMessage(e){let t;try{t=JSON.parse(e)}catch{return}if(`id`in t&&typeof t.id==`number`){let e=t;r.debug(`Response`,{id:e.id,hasError:!!e.error}),e.error?(r.error(`Command error`,{id:e.id,code:e.error.code,message:e.error.message}),this.pending.reject(e.id,Error(`CDP error: ${e.error.message} (${e.error.code})`))):this.pending.resolve(e.id,e.result??{});return}if(`method`in t){let e=t;r.debug(`Event`,{method:e.method,sessionId:e.sessionId});let n=this.listeners.get(e.method);if(n){let t=e.sessionId?{...e.params,sessionId:e.sessionId}:e.params??{};for(let e of n)try{e(t)}catch{}}}}handleClose(e){let t=e===i;t?(this._superseded=!0,r.warn(`CDP slot superseded by another SLICC tab/window on this instance`,{code:e})):r.error(`Connection closed unexpectedly`,{pendingCommands:this.pending.size});let n=t?`CDP connection superseded by another SLICC tab/window on this instance`:`CDP connection closed`;this.pending.rejectAll(n),this.cleanup()}cleanup(){this.ws=null,this._state=`disconnected`,this.pending.rejectAll(`CDP client disconnected`)}},o=e(`har-recorder`),s=class{recordings=new Map;client;fs;eventCleanup=new Map;constructor(e,t){this.client=e,this.fs=t}async startRecording(e,t,n){let r=`rec-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;await this.client.send(`Network.enable`,{},t),await this.client.send(`Page.enable`,{},t);let i=(await this.client.send(`Runtime.evaluate`,{expression:`location.href`,returnByValue:!0},t)).result?.value??`about:blank`,a={id:r,targetId:e,sessionId:t,filterCode:n,pendingRequests:new Map,entries:[],startTime:Date.now(),currentUrl:i,snapshotCount:0};return this.recordings.set(r,a),this.setupEventListeners(a),await this.ensureDir(`/recordings/${r}`),o.debug(`Started recording`,{recordingId:r,targetId:e,currentUrl:i}),r}setupEventListeners(e){let{sessionId:t,id:n}=e,r=n=>{n.sessionId===t&&this.handleRequestWillBeSent(e,n)},i=n=>{n.sessionId===t&&this.handleResponseReceived(e,n)},a=n=>{n.sessionId===t&&this.handleLoadingFinished(e,n)},s=n=>{n.sessionId===t&&this.handleLoadingFailed(e,n)},c=r=>{if(r.sessionId!==t)return;let i=r.frame;if(!i?.parentId&&i?.url){let t=[...e.entries],r=e.currentUrl;e.currentUrl=i.url,e.entries=[],e.pendingRequests.clear(),this.saveSnapshotWithEntries(e,`navigation`,t,r).catch(e=>{o.error(`Failed to save navigation snapshot`,{recordingId:n,error:e instanceof Error?e.message:String(e)})})}};this.client.on(`Network.requestWillBeSent`,r),this.client.on(`Network.responseReceived`,i),this.client.on(`Network.loadingFinished`,a),this.client.on(`Network.loadingFailed`,s),this.client.on(`Page.frameNavigated`,c),this.eventCleanup.set(n,()=>{this.client.off(`Network.requestWillBeSent`,r),this.client.off(`Network.responseReceived`,i),this.client.off(`Network.loadingFinished`,a),this.client.off(`Network.loadingFailed`,s),this.client.off(`Page.frameNavigated`,c)})}handleRequestWillBeSent(e,t){let n=t.requestId,r=t.request,i=t.timestamp;e.pendingRequests.set(n,{requestId:n,startTime:i*1e3,request:{method:r.method,url:r.url,headers:r.headers,postData:r.postData}})}handleResponseReceived(e,t){let n=t.requestId,r=t.response,i=e.pendingRequests.get(n);i&&(i.response={status:r.status,statusText:r.statusText,headers:r.headers,mimeType:r.mimeType},i.timing=r.timing)}async handleLoadingFinished(e,t){let n=t.requestId,r=t.timestamp,i=e.pendingRequests.get(n);if(!i)return;i.endTime=r*1e3;try{let t=await this.client.send(`Network.getResponseBody`,{requestId:n},e.sessionId);i.responseBody=t.body,i.responseBodyBase64=t.base64Encoded}catch{}let a=this.buildHarEntry(i);a&&e.entries.push(a),e.pendingRequests.delete(n)}handleLoadingFailed(e,t){let n=t.requestId;e.pendingRequests.delete(n)}buildHarEntry(e){if(!e.response)return null;let{request:t,response:n,timing:r,startTime:i,endTime:a,responseBody:o,responseBodyBase64:s}=e,c=a?a-i:0,l=[];try{let e=new URL(t.url);l=Array.from(e.searchParams.entries()).map(([e,t])=>({name:e,value:t}))}catch{}let u=r?(()=>{let e=(e,t)=>{if(e==null||t==null||e<0||t<0)return-1;let n=t-e;return n>=0?n:-1},t=r.dnsStart>=0?r.dnsStart:r.connectStart>=0?r.connectStart:0;return{blocked:t>0?t:-1,dns:e(r.dnsStart,r.dnsEnd),connect:e(r.connectStart,r.connectEnd),ssl:e(r.sslStart,r.sslEnd),send:e(r.sendStart,r.sendEnd),wait:e(r.sendEnd,r.receiveHeadersStart),receive:e(r.receiveHeadersStart,r.receiveHeadersEnd)}})():{blocked:-1,dns:-1,connect:-1,ssl:-1,send:0,wait:c,receive:0},d={size:o?.length??0,mimeType:n.mimeType??`application/octet-stream`};o&&(d.text=o,s&&(d.encoding=`base64`));let f;return t.postData&&(f={mimeType:t.headers[`content-type`]??t.headers[`Content-Type`]??`text/plain`,text:t.postData}),{startedDateTime:new Date(i).toISOString(),time:c,request:{method:t.method,url:t.url,httpVersion:`HTTP/1.1`,cookies:[],headers:Object.entries(t.headers).map(([e,t])=>({name:e,value:t})),queryString:l,postData:f,headersSize:-1,bodySize:t.postData?.length??0},response:{status:n.status,statusText:n.statusText,httpVersion:`HTTP/1.1`,cookies:[],headers:Object.entries(n.headers).map(([e,t])=>({name:e,value:t})),content:d,redirectURL:n.headers.location??n.headers.Location??``,headersSize:-1,bodySize:d.size},cache:{},timings:u}}async saveSnapshot(e,t){return this.saveSnapshotWithEntries(e,t,e.entries,e.currentUrl)}async applyFilter(e,t){return c(e,t)}async saveSnapshotWithEntries(e,t,n,r){if(n.length===0)return o.debug(`No entries to save`,{recordingId:e.id,trigger:t}),null;let i=e.filterCode?await this.applyFilter(n,e.filterCode):n;if(i.length===0)return o.debug(`All entries filtered out`,{recordingId:e.id,trigger:t}),null;e.snapshotCount++;let a=new Date().toISOString().replace(/[:.]/g,`-`),s=this.urlToSlug(r),c=`${e.snapshotCount.toString().padStart(3,`0`)}-${a}-${t}-${s}.har`,l=`/recordings/${e.id}/${c}`,u={log:{version:`1.2`,creator:{name:`SLICC HAR Recorder`,version:`1.0.0`},entries:i}};return await this.fs.writeFile(l,JSON.stringify(u,null,2)),o.debug(`Saved HAR snapshot`,{recordingId:e.id,path:l,entryCount:i.length}),l}urlToSlug(e){try{let t=new URL(e);return`${t.hostname}${t.pathname}`.replace(/[^a-zA-Z0-9]/g,`-`).replace(/-+/g,`-`).replace(/^-|-$/g,``).slice(0,50)||`page`}catch{return`page`}}async stopRecording(e){let t=this.recordings.get(e);if(!t)throw Error(`Recording not found: ${e}`);await this.saveSnapshot(t,`close`);let n=this.eventCleanup.get(e);n&&(n(),this.eventCleanup.delete(e));try{await this.client.send(`Network.disable`,{},t.sessionId)}catch{}this.recordings.delete(e);let r=`/recordings/${e}`;return o.debug(`Stopped recording`,{recordingId:e,snapshotCount:t.snapshotCount}),r}getRecording(e){return this.recordings.get(e)}getRecordingByTarget(e){for(let[t,n]of this.recordings)if(n.targetId===e)return t}async ensureDir(e){await this.fs.mkdir(e,{recursive:!0})}};function c(e,t){try{let n=Function(`entry`,`return (${t})(entry);`),r=[];for(let t of e)try{let e=n(t);if(e===!1)continue;typeof e==`object`&&e?r.push(e):r.push(t)}catch(e){o.error(`Filter function error on entry, keeping it`,{error:e instanceof Error?e.message:String(e)}),r.push(t)}return r}catch(t){return o.error(`Failed to compile filter, returning unfiltered`,{error:t instanceof Error?t.message:String(t)}),e}}var l=`(function() {
1
+ import{t as e}from"./logger-DDBAeTLF.js";import"./remote-cdp-transport-DeDqT7I4.js";import{n as t,t as n}from"./pending-request-table-Dgn6qYdL.js";import"./logger-BoSvu4mW.js";import"./navigation-watcher-DLdGNtAZ.js";var r=e(`cdp`),i=4001,a=class{ws=null;nextId=1;_superseded=!1;pending=new n;listeners=new Map;_state=`disconnected`;get state(){return this._state}get superseded(){return this._superseded}async connect(e){if(this._state!==`disconnected`)throw Error(`Cannot connect: state is ${this._state}`);if(!e?.url)throw Error(`CDPClient.connect() requires a WebSocket URL`);let{url:t,timeout:n=5e3,protocols:i}=e;return this._state=`connecting`,new Promise((e,a)=>{let o=setTimeout(()=>{this.cleanup(),a(Error(`CDP connection timed out after ${n}ms`))},n);try{this.ws=i===void 0?new WebSocket(t):new WebSocket(t,i)}catch(e){clearTimeout(o),this._state=`disconnected`,a(e);return}this.ws.onopen=()=>{clearTimeout(o),this._state=`connected`,this._superseded=!1,r.info(`Connected`,{url:t}),e()},this.ws.onerror=e=>{clearTimeout(o),this._state===`connecting`&&(r.error(`Connection failed`,{url:t}),this.cleanup(),a(Error(`CDP WebSocket connection failed`)))},this.ws.onmessage=e=>{this.handleMessage(e.data)},this.ws.onclose=e=>{this.handleClose(e?.code)}})}disconnect(){this.ws&&(this.ws.onclose=null,this.ws.close()),this._superseded=!1,this.cleanup(),r.info(`Disconnected`)}async send(e,t,n,i=3e4){if(this._state!==`connected`||!this.ws)throw Error(`CDP client is not connected`);let a=this.nextId++,o={id:a,method:e};t&&(o.params=t),n&&(o.sessionId=n),r.debug(`Send`,{method:e,id:a,sessionId:n});let s=this.pending.issue(a,i,`CDP command timed out after ${i}ms: ${e}`);return this.ws.send(JSON.stringify(o)),s}on(e,t){let n=this.listeners.get(e);n||(n=new Set,this.listeners.set(e,n)),n.add(t)}off(e,t){let n=this.listeners.get(e);n&&(n.delete(t),n.size===0&&this.listeners.delete(e))}once(e,n=3e4){return t(t=>(this.on(e,t),()=>this.off(e,t)),n,`Timed out waiting for event: ${e}`)}handleMessage(e){let t;try{t=JSON.parse(e)}catch{return}if(`id`in t&&typeof t.id==`number`){let e=t;r.debug(`Response`,{id:e.id,hasError:!!e.error}),e.error?(r.error(`Command error`,{id:e.id,code:e.error.code,message:e.error.message}),this.pending.reject(e.id,Error(`CDP error: ${e.error.message} (${e.error.code})`))):this.pending.resolve(e.id,e.result??{});return}if(`method`in t){let e=t;r.debug(`Event`,{method:e.method,sessionId:e.sessionId});let n=this.listeners.get(e.method);if(n){let t=e.sessionId?{...e.params,sessionId:e.sessionId}:e.params??{};for(let e of n)try{e(t)}catch{}}}}handleClose(e){let t=e===i;t?(this._superseded=!0,r.warn(`CDP slot superseded by another SLICC tab/window on this instance`,{code:e})):r.error(`Connection closed unexpectedly`,{pendingCommands:this.pending.size});let n=t?`CDP connection superseded by another SLICC tab/window on this instance`:`CDP connection closed`;this.pending.rejectAll(n),this.cleanup()}cleanup(){this.ws=null,this._state=`disconnected`,this.pending.rejectAll(`CDP client disconnected`)}},o=e(`har-recorder`),s=class{recordings=new Map;client;fs;eventCleanup=new Map;constructor(e,t){this.client=e,this.fs=t}async startRecording(e,t,n){let r=`rec-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;await this.client.send(`Network.enable`,{},t),await this.client.send(`Page.enable`,{},t);let i=(await this.client.send(`Runtime.evaluate`,{expression:`location.href`,returnByValue:!0},t)).result?.value??`about:blank`,a={id:r,targetId:e,sessionId:t,filterCode:n,pendingRequests:new Map,entries:[],startTime:Date.now(),currentUrl:i,snapshotCount:0};return this.recordings.set(r,a),this.setupEventListeners(a),await this.ensureDir(`/recordings/${r}`),o.debug(`Started recording`,{recordingId:r,targetId:e,currentUrl:i}),r}setupEventListeners(e){let{sessionId:t,id:n}=e,r=n=>{n.sessionId===t&&this.handleRequestWillBeSent(e,n)},i=n=>{n.sessionId===t&&this.handleResponseReceived(e,n)},a=n=>{n.sessionId===t&&this.handleLoadingFinished(e,n)},s=n=>{n.sessionId===t&&this.handleLoadingFailed(e,n)},c=r=>{if(r.sessionId!==t)return;let i=r.frame;if(!i?.parentId&&i?.url){let t=[...e.entries],r=e.currentUrl;e.currentUrl=i.url,e.entries=[],e.pendingRequests.clear(),this.saveSnapshotWithEntries(e,`navigation`,t,r).catch(e=>{o.error(`Failed to save navigation snapshot`,{recordingId:n,error:e instanceof Error?e.message:String(e)})})}};this.client.on(`Network.requestWillBeSent`,r),this.client.on(`Network.responseReceived`,i),this.client.on(`Network.loadingFinished`,a),this.client.on(`Network.loadingFailed`,s),this.client.on(`Page.frameNavigated`,c),this.eventCleanup.set(n,()=>{this.client.off(`Network.requestWillBeSent`,r),this.client.off(`Network.responseReceived`,i),this.client.off(`Network.loadingFinished`,a),this.client.off(`Network.loadingFailed`,s),this.client.off(`Page.frameNavigated`,c)})}handleRequestWillBeSent(e,t){let n=t.requestId,r=t.request,i=t.timestamp;e.pendingRequests.set(n,{requestId:n,startTime:i*1e3,request:{method:r.method,url:r.url,headers:r.headers,postData:r.postData}})}handleResponseReceived(e,t){let n=t.requestId,r=t.response,i=e.pendingRequests.get(n);i&&(i.response={status:r.status,statusText:r.statusText,headers:r.headers,mimeType:r.mimeType},i.timing=r.timing)}async handleLoadingFinished(e,t){let n=t.requestId,r=t.timestamp,i=e.pendingRequests.get(n);if(!i)return;i.endTime=r*1e3;try{let t=await this.client.send(`Network.getResponseBody`,{requestId:n},e.sessionId);i.responseBody=t.body,i.responseBodyBase64=t.base64Encoded}catch{}let a=this.buildHarEntry(i);a&&e.entries.push(a),e.pendingRequests.delete(n)}handleLoadingFailed(e,t){let n=t.requestId;e.pendingRequests.delete(n)}buildHarEntry(e){if(!e.response)return null;let{request:t,response:n,timing:r,startTime:i,endTime:a,responseBody:o,responseBodyBase64:s}=e,c=a?a-i:0,l=[];try{let e=new URL(t.url);l=Array.from(e.searchParams.entries()).map(([e,t])=>({name:e,value:t}))}catch{}let u=r?(()=>{let e=(e,t)=>{if(e==null||t==null||e<0||t<0)return-1;let n=t-e;return n>=0?n:-1},t=r.dnsStart>=0?r.dnsStart:r.connectStart>=0?r.connectStart:0;return{blocked:t>0?t:-1,dns:e(r.dnsStart,r.dnsEnd),connect:e(r.connectStart,r.connectEnd),ssl:e(r.sslStart,r.sslEnd),send:e(r.sendStart,r.sendEnd),wait:e(r.sendEnd,r.receiveHeadersStart),receive:e(r.receiveHeadersStart,r.receiveHeadersEnd)}})():{blocked:-1,dns:-1,connect:-1,ssl:-1,send:0,wait:c,receive:0},d={size:o?.length??0,mimeType:n.mimeType??`application/octet-stream`};o&&(d.text=o,s&&(d.encoding=`base64`));let f;return t.postData&&(f={mimeType:t.headers[`content-type`]??t.headers[`Content-Type`]??`text/plain`,text:t.postData}),{startedDateTime:new Date(i).toISOString(),time:c,request:{method:t.method,url:t.url,httpVersion:`HTTP/1.1`,cookies:[],headers:Object.entries(t.headers).map(([e,t])=>({name:e,value:t})),queryString:l,postData:f,headersSize:-1,bodySize:t.postData?.length??0},response:{status:n.status,statusText:n.statusText,httpVersion:`HTTP/1.1`,cookies:[],headers:Object.entries(n.headers).map(([e,t])=>({name:e,value:t})),content:d,redirectURL:n.headers.location??n.headers.Location??``,headersSize:-1,bodySize:d.size},cache:{},timings:u}}async saveSnapshot(e,t){return this.saveSnapshotWithEntries(e,t,e.entries,e.currentUrl)}async applyFilter(e,t){return c(e,t)}async saveSnapshotWithEntries(e,t,n,r){if(n.length===0)return o.debug(`No entries to save`,{recordingId:e.id,trigger:t}),null;let i=e.filterCode?await this.applyFilter(n,e.filterCode):n;if(i.length===0)return o.debug(`All entries filtered out`,{recordingId:e.id,trigger:t}),null;e.snapshotCount++;let a=new Date().toISOString().replace(/[:.]/g,`-`),s=this.urlToSlug(r),c=`${e.snapshotCount.toString().padStart(3,`0`)}-${a}-${t}-${s}.har`,l=`/recordings/${e.id}/${c}`,u={log:{version:`1.2`,creator:{name:`SLICC HAR Recorder`,version:`1.0.0`},entries:i}};return await this.fs.writeFile(l,JSON.stringify(u,null,2)),o.debug(`Saved HAR snapshot`,{recordingId:e.id,path:l,entryCount:i.length}),l}urlToSlug(e){try{let t=new URL(e);return`${t.hostname}${t.pathname}`.replace(/[^a-zA-Z0-9]/g,`-`).replace(/-+/g,`-`).replace(/^-|-$/g,``).slice(0,50)||`page`}catch{return`page`}}async stopRecording(e){let t=this.recordings.get(e);if(!t)throw Error(`Recording not found: ${e}`);await this.saveSnapshot(t,`close`);let n=this.eventCleanup.get(e);n&&(n(),this.eventCleanup.delete(e));try{await this.client.send(`Network.disable`,{},t.sessionId)}catch{}this.recordings.delete(e);let r=`/recordings/${e}`;return o.debug(`Stopped recording`,{recordingId:e,snapshotCount:t.snapshotCount}),r}getRecording(e){return this.recordings.get(e)}getRecordingByTarget(e){for(let[t,n]of this.recordings)if(n.targetId===e)return t}async ensureDir(e){await this.fs.mkdir(e,{recursive:!0})}};function c(e,t){try{let n=Function(`entry`,`return (${t})(entry);`),r=[];for(let t of e)try{let e=n(t);if(e===!1)continue;typeof e==`object`&&e?r.push(e):r.push(t)}catch(e){o.error(`Filter function error on entry, keeping it`,{error:e instanceof Error?e.message:String(e)}),r.push(t)}return r}catch(t){return o.error(`Failed to compile filter, returning unfiltered`,{error:t instanceof Error?t.message:String(t)}),e}}var l=`(function() {
2
2
  'use strict';
3
3
 
4
4
  // ===== DOM Utilities =====
@@ -1 +1 @@
1
- import{h as e}from"./account-store-Bg1KKHOx.js";import{a as t}from"./diagnostics-DN_idNHx.js";import{u as n}from"./claude-model-version-C0HLsjny.js";import{r,s as i}from"./legacy-api-aliases-7-tLus57.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()}}}function _(e){console.error(`[cerebras] Stream error:`,e instanceof Error?e.message:String(e))}var v=(e,n,r={})=>{let i=t();return y(i,e,n,r).catch(_),i};async function y(e,t,n,i){try{let a={...t,baseUrl:o,api:s},c=r(a,n,i);for await(let t of c)e.push(t);e.end()}catch(n){_(n),e.push(g(t,n)),e.end()}}var b=(e,n,r)=>{let i=t();return x(i,e,n,r).catch(_),i};async function x(e,t,n,r){try{let a={...t,baseUrl:o,api:s},c=i(a,n,r);for await(let t of c)e.push(t);e.end()}catch(n){_(n),e.push(g(t,n)),e.end()}}var S={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 C(){n({api:c,stream:v,streamSimple:b})}export{S as config,C as register};
1
+ import{h as e}from"./account-store-8BBweMEe.js";import{a as t}from"./diagnostics-DN_idNHx.js";import{u as n}from"./claude-model-version-C0HLsjny.js";import{r,s as i}from"./legacy-api-aliases-7-tLus57.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()}}}function _(e){console.error(`[cerebras] Stream error:`,e instanceof Error?e.message:String(e))}var v=(e,n,r={})=>{let i=t();return y(i,e,n,r).catch(_),i};async function y(e,t,n,i){try{let a={...t,baseUrl:o,api:s},c=r(a,n,i);for await(let t of c)e.push(t);e.end()}catch(n){_(n),e.push(g(t,n)),e.end()}}var b=(e,n,r)=>{let i=t();return x(i,e,n,r).catch(_),i};async function x(e,t,n,r){try{let a={...t,baseUrl:o,api:s},c=i(a,n,r);for await(let t of c)e.push(t);e.end()}catch(n){_(n),e.push(g(t,n)),e.end()}}var S={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 C(){n({api:c,stream:v,streamSimple:b})}export{S as config,C as register};
@@ -1 +1 @@
1
- import{i as e}from"./account-store-8sKKUZ8J.js";import{a as t}from"./diagnostics-DN_idNHx.js";import{a as n}from"./compat-Dujkqs4W.js";import{r,s as i}from"./legacy-api-aliases-PgIrFmtQ.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()}}}function _(e){console.error(`[cerebras] Stream error:`,e instanceof Error?e.message:String(e))}const v=(e,n,r={})=>{let i=t();return y(i,e,n,r).catch(_),i};async function y(e,t,n,i){try{let a={...t,baseUrl:o,api:s},c=r(a,n,i);for await(let t of c)e.push(t);e.end()}catch(n){_(n),e.push(g(t,n)),e.end()}}const b=(e,n,r)=>{let i=t();return x(i,e,n,r).catch(_),i};async function x(e,t,n,r){try{let a={...t,baseUrl:o,api:s},c=i(a,n,r);for await(let t of c)e.push(t);e.end()}catch(n){_(n),e.push(g(t,n)),e.end()}}const S={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 C(){n({api:c,stream:v,streamSimple:b})}export{S as config,C as register};
1
+ import{i as e}from"./account-store-DaG5fzPt.js";import{a as t}from"./diagnostics-DN_idNHx.js";import{a as n}from"./compat-Dujkqs4W.js";import{r,s as i}from"./legacy-api-aliases-PgIrFmtQ.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()}}}function _(e){console.error(`[cerebras] Stream error:`,e instanceof Error?e.message:String(e))}const v=(e,n,r={})=>{let i=t();return y(i,e,n,r).catch(_),i};async function y(e,t,n,i){try{let a={...t,baseUrl:o,api:s},c=r(a,n,i);for await(let t of c)e.push(t);e.end()}catch(n){_(n),e.push(g(t,n)),e.end()}}const b=(e,n,r)=>{let i=t();return x(i,e,n,r).catch(_),i};async function x(e,t,n,r){try{let a={...t,baseUrl:o,api:s},c=i(a,n,r);for await(let t of c)e.push(t);e.end()}catch(n){_(n),e.push(g(t,n)),e.end()}}const S={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 C(){n({api:c,stream:v,streamSimple:b})}export{S as config,C as register};
@@ -1,4 +1,4 @@
1
- import{C as e,I as t,d as n,f as r}from"./account-store-Bg1KKHOx.js";import{n as i}from"./main-BK-7ArIz.js";var a=`slicc_cloud_model_catalog`,o=`adobe`;function s(t){if(t===o)return!1;let n=e(t);return!(n.hidden||n.onOAuthLoginIntercepted)}function c(){try{let e=r().map(e=>({providerId:e.providerId,providerName:e.providerName,models:e.models.map(e=>({id:e.id,name:e.name}))}));localStorage.setItem(a,JSON.stringify(e))}catch{}}async function l(r){for(;r.firstChild;)r.removeChild(r.firstChild);r.className=`connect-surface`;let a=document.createElement(`h1`);a.className=`connect-surface__title`,a.textContent=`Connect providers`,r.appendChild(a);let l=document.createElement(`p`);l.className=`connect-surface__desc`,l.textContent=`Log in or add API keys for the providers your cone should use, then click Done to return to the dashboard.`,r.appendChild(l);let u=document.createElement(`div`);u.className=`connect-surface__accounts`,r.appendChild(u);function d(){for(;u.firstChild;)u.removeChild(u.firstChild);let r=n().filter(e=>e.providerId!==o);if(r.length===0){let e=document.createElement(`div`);e.className=`connect-surface__empty`,e.textContent=`No providers connected yet.`,u.appendChild(e)}else{let n=document.createElement(`div`);n.className=`connect-surface__accounts-list`;for(let i of r){let r=e(i.providerId),a=document.createElement(`div`);a.className=`connect-surface__account-row`;let o=document.createElement(`div`);o.className=`connect-surface__account-info`;let s=document.createElement(`div`);s.className=`connect-surface__account-name`,s.textContent=r.name,o.appendChild(s);let l=document.createElement(`div`);l.className=`connect-surface__account-detail`,l.textContent=i.userName?i.userName:i.accessToken?`Logged in`:i.apiKey?`API key set`:`No credentials`,o.appendChild(l),a.appendChild(o);let u=document.createElement(`button`);u.className=`connect-surface__remove-btn`,u.textContent=`Remove`,u.onclick=async()=>{await t(i.providerId),c(),d()},a.appendChild(u),n.appendChild(a)}u.appendChild(n)}let a=document.createElement(`button`);a.className=`connect-surface__add-btn`,a.textContent=r.length===0?`Add provider`:`Manage providers`,a.onclick=async()=>{await i({startInAddAccount:!0,providerFilter:s})&&(c(),d())},u.appendChild(a)}d(),c();let f=document.createElement(`div`);f.className=`connect-surface__footer`;let p=document.createElement(`button`);if(p.className=`connect-surface__done-btn`,p.textContent=`Done — return to dashboard`,p.onclick=()=>{c(),window.close()},f.appendChild(p),r.appendChild(f),!document.getElementById(`connect-surface-style`)){let e=document.createElement(`style`);e.id=`connect-surface-style`,e.textContent=`
1
+ import{C as e,I as t,d as n,f as r}from"./account-store-8BBweMEe.js";import{n as i}from"./main-Cj0dR__R.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 +1 @@
1
- import{t as e}from"./logger-LESFN7Hj.js";import{t}from"./agent-bridge-B43SVYcu.js";import{T as n}from"./descriptor-Bh6C6cqu.js";const r=e(`directed-approval`);function i(e,t){if(e.kind===`user`)return a(`the user tier is not a directed approval`);if(e.kind===`agent`)return a(`agent approvals are not enqueued to a unit`);let r=e.unitJid;if(!t.scoops.has(r))return a(`the requesting unit is not registered`);let i=t.ownerRootOf(r);if(!i)return a(`no owning cone for the requesting unit`);let o=e.kind===`cone`?i:[...t.scoops.values()].find(t=>t.parentJid===i.jid&&(t.name===e.scoopName||t.folder===e.scoopName));return o?n(o).canResolveApprovals?{ok:!0,requesterJid:r,approver:o}:a(`the named approver cannot resolve approvals`):a(`delegated approver not found under this cone`)}function a(e){return r.warn(`Directed approval failing closed`,{reason:e}),{ok:!1,reason:e}}const o={decision:`deny`};async function s(e,n){let a=e.approver;if(a?.kind===`agent`){let i=globalThis[t];if(!i)return r.warn(`No agent bridge available for an approver agent — denying`),o;let{approverRunnerFor:s}=await import(`./approver-agent-CYHU0chR.js`),c=n.getSharedFs(),l=await s({spawn:e=>i.spawn(e),readSharedFile:async e=>{if(!c)return null;try{let t=await c.readFile(e,{encoding:`utf-8`});return typeof t==`string`?t:null}catch{return null}},findUnit:e=>{let t=n.scoops.get(e);return t?{workspace:n.workspaceFor(t),folder:t.folder}:void 0}})({kind:e.kind===`guest-tool`?`guest-tool`:`guest-message`,requester:e.requester??`an unidentified requester`,detail:e.detail},a.unitJid);return r.info(`Approver agent verdict`,{decision:l.decision,reason:l.reason}),l.decision===`allow`?{decision:`allow`}:o}if(a&&a.kind!==`user`){let t=i(a,n);return t.ok?n.enqueue(t.requesterJid,e,{approver:t.approver}):o}return n.approveAsUser(e)}export{s as runDirectedApproval};
1
+ import{t as e}from"./logger-LESFN7Hj.js";import{t}from"./agent-bridge-DnjqW2rF.js";import{T as n}from"./descriptor-Bh6C6cqu.js";const r=e(`directed-approval`);function i(e,t){if(e.kind===`user`)return a(`the user tier is not a directed approval`);if(e.kind===`agent`)return a(`agent approvals are not enqueued to a unit`);let r=e.unitJid;if(!t.scoops.has(r))return a(`the requesting unit is not registered`);let i=t.ownerRootOf(r);if(!i)return a(`no owning cone for the requesting unit`);let o=e.kind===`cone`?i:[...t.scoops.values()].find(t=>t.parentJid===i.jid&&(t.name===e.scoopName||t.folder===e.scoopName));return o?n(o).canResolveApprovals?{ok:!0,requesterJid:r,approver:o}:a(`the named approver cannot resolve approvals`):a(`delegated approver not found under this cone`)}function a(e){return r.warn(`Directed approval failing closed`,{reason:e}),{ok:!1,reason:e}}const o={decision:`deny`};async function s(e,n){let a=e.approver;if(a?.kind===`agent`){let i=globalThis[t];if(!i)return r.warn(`No agent bridge available for an approver agent — denying`),o;let{approverRunnerFor:s}=await import(`./approver-agent-CYHU0chR.js`),c=n.getSharedFs(),l=await s({spawn:e=>i.spawn(e),readSharedFile:async e=>{if(!c)return null;try{let t=await c.readFile(e,{encoding:`utf-8`});return typeof t==`string`?t:null}catch{return null}},findUnit:e=>{let t=n.scoops.get(e);return t?{workspace:n.workspaceFor(t),folder:t.folder}:void 0}})({kind:e.kind===`guest-tool`?`guest-tool`:`guest-message`,requester:e.requester??`an unidentified requester`,detail:e.detail},a.unitJid);return r.info(`Approver agent verdict`,{decision:l.decision,reason:l.reason}),l.decision===`allow`?{decision:`allow`}:o}if(a&&a.kind!==`user`){let t=i(a,n);return t.ok?n.enqueue(t.requesterJid,e,{approver:t.approver}):o}return n.approveAsUser(e)}export{s as runDirectedApproval};
@@ -1 +1 @@
1
- import{t as e}from"./logger-DDBAeTLF.js";import{t}from"./proxied-fetch-CFWkfPNA.js";import{t as n}from"./navigation-watcher-DrWMx-B4.js";import{t as r}from"./discovery-preference-cJij_YcT.js";var i=e(`follower-navigate-watcher`);function a(e){let n=t();return{onDiscovery:t=>{let n=e();if(!n){i.warn(`discovery lick dropped — no follower sync connected`,{url:t.url});return}n.forwardLick({type:`discovery`,targetScoop:void 0,timestamp:new Date().toISOString(),discoveryOrigin:t.origin,discoveryKind:t.kind,discoveryUrl:t.url,discoverySource:`live-navigation`,body:{origin:t.origin,kind:t.kind,url:t.url,targetId:t.targetId}})},probeFetch:async(e,t)=>{let r=n(e,{method:t?.method??`GET`}),i=t?.signal,a=i?await Promise.race([r,new Promise((e,t)=>{if(i.aborted){t(Error(`aborted`));return}i.addEventListener(`abort`,()=>t(Error(`aborted`)),{once:!0})})]):await r,o=a.headers;return{ok:a.status>=200&&a.status<300,status:a.status,headers:{get(e){return o?o[e.toLowerCase()]??o[e]??null:null}}}},isDiscoveryEnabled:()=>r()}}function o(e,t){let r=new n(e,e=>{let n={url:e.url,verb:e.verb,target:e.target};e.instruction!=null&&(n.instruction=e.instruction),e.branch!=null&&(n.branch=e.branch),e.path!=null&&(n.path=e.path),e.title!=null&&(n.title=e.title);let r=t();if(!r){i.warn(`navigate lick dropped — no follower sync connected`,{url:e.url});return}r.forwardLick({type:`navigate`,navigateUrl:e.url,targetScoop:void 0,timestamp:new Date().toISOString(),body:n})},a(t));return r.start(),()=>void r.stop()}export{o as startFollowerNavigateWatcher};
1
+ import{t as e}from"./logger-DDBAeTLF.js";import{t}from"./proxied-fetch-CFWkfPNA.js";import{t as n}from"./navigation-watcher-DLdGNtAZ.js";import{t as r}from"./discovery-preference-cJij_YcT.js";var i=e(`follower-navigate-watcher`);function a(e){let n=t();return{onDiscovery:t=>{let n=e();if(!n){i.warn(`discovery lick dropped — no follower sync connected`,{url:t.url});return}n.forwardLick({type:`discovery`,targetScoop:void 0,timestamp:new Date().toISOString(),discoveryOrigin:t.origin,discoveryKind:t.kind,discoveryUrl:t.url,discoverySource:`live-navigation`,body:{origin:t.origin,kind:t.kind,url:t.url,targetId:t.targetId}})},probeFetch:async(e,t)=>{let r=n(e,{method:t?.method??`GET`}),i=t?.signal,a=i?await Promise.race([r,new Promise((e,t)=>{if(i.aborted){t(Error(`aborted`));return}i.addEventListener(`abort`,()=>t(Error(`aborted`)),{once:!0})})]):await r,o=a.headers;return{ok:a.status>=200&&a.status<300,status:a.status,headers:{get(e){return o?o[e.toLowerCase()]??o[e]??null:null}}}},isDiscoveryEnabled:()=>r()}}function o(e,t){let r=new n(e,e=>{let n={url:e.url,verb:e.verb,target:e.target};e.instruction!=null&&(n.instruction=e.instruction),e.branch!=null&&(n.branch=e.branch),e.path!=null&&(n.path=e.path),e.title!=null&&(n.title=e.title);let r=t();if(!r){i.warn(`navigate lick dropped — no follower sync connected`,{url:e.url});return}r.forwardLick({type:`navigate`,navigateUrl:e.url,targetScoop:void 0,timestamp:new Date().toISOString(),body:n})},a(t));return r.start(),()=>void r.stop()}export{o as startFollowerNavigateWatcher};
@@ -0,0 +1,2 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/dist-BKQr3WRb.js","assets/rolldown-runtime-Dd_uD5pT.js","assets/safe-buffer-iah92gQe.js","assets/dist-DHO9E-gl.js","assets/backend-hostfs-Com-zF5W.js","assets/api-endpoint-GRCyib6X.js","assets/types-idfTVsM8.js","assets/mount-DPQd6tzy.js","assets/preload-helper-Czpn1I53.js","assets/mime-types-k2E6ulyv.js","assets/base64-DJRlyqZu.js","assets/src-CAWTvdAa.js","assets/runtime-env-Dlaokqg1.js","assets/runtime-env-E-i2SW1s.js","assets/mount-table-store-dY2IfQ5S.js","assets/mount-bridge-client-BJeJ5p60.js","assets/port-bridge-client-Cti-DmEY.js","assets/logger-DDBAeTLF.js","assets/proxied-fetch-CFWkfPNA.js","assets/fetch-body-D2PwksUW.js"])))=>i.map(i=>d[i]);
2
+ import{n as e}from"./rolldown-runtime-Dd_uD5pT.js";import{t}from"./preload-helper-Czpn1I53.js";import{t as n}from"./logger-DDBAeTLF.js";import{n as r,r as i}from"./tool-ui-DfXu6quJ.js";import"./tool-ui-DCY2mIe9.js";import{a,i as o,n as s,r as c,t as l}from"./path-utils-DNJG-zQf.js";import{t as u}from"./types-idfTVsM8.js";import{n as d,t as f}from"./virtual-device-paths-D45tpPP6.js";import{t as ee}from"./picker-approval-D89YhXsA.js";import{i as p,r as te,t as m}from"./mount-picker-popup-C4q1Q3pK.js";import{a as ne,i as re,n as ie,t as ae}from"./mount-table-store-dY2IfQ5S.js";var h=n(`fs-watcher`),oe=0;function se(e,t){return t===`/`||e===t||e.startsWith(t+`/`)}var g=class{registrations=new Map;watch(e,t,n){let r=`fsw-${++oe}`;return this.registrations.set(r,{id:r,basePath:e,filter:t,callback:n}),h.debug(`Watch registered`,{id:r,basePath:e}),()=>{this.registrations.delete(r),h.debug(`Watch unregistered`,{id:r})}}notify(e){if(e.length!==0)for(let[,t]of this.registrations){let n=e.filter(e=>se(e.path,t.basePath)&&t.filter(e.path));if(n.length>0)try{t.callback(n)}catch(e){h.error(`Watch callback error`,{id:t.id,error:e instanceof Error?e.message:String(e)})}}}dispose(){this.registrations.clear(),h.debug(`All watchers disposed`)}get size(){return this.registrations.size}},_=n(`mount-index`),ce=400,v=2e6,y=`SLICC_MOUNT_INDEX_MAX_DEPTH`,le=`SLICC_MOUNT_INDEX_MAX_ENTRIES`,b=256,x=class extends Error{cause;constructor(e,t){super(e),this.name=`MountIndexAbortError`,this.cause=t}};function ue(e){let t=e.map(([e,t])=>`${e}\u0000${t.kind}`).sort(),n=t.length>b?t.slice(0,b):t;return`${t.length}\u0001${n.join(``)}`}async function de(e,t){let n=e.isSameEntry;if(typeof n!=`function`)return!1;try{return await n.call(e,t)}catch{return!1}}function S(e,t){return e instanceof Map?e.get(t):e[t]}function C(e){let t=e.trim();if(t===``)return;let n=Number(t);if(!(!Number.isInteger(n)||n<=0))return n}function w(e,t,n){let r=S(e,t);if(r===void 0||r.trim()===``)return n;let i=C(r);return i===void 0?(_.warn(`Ignoring invalid ${t}; expected a positive integer, using default`,{value:r,fallback:n}),n):i}function T(e){return{maxDepth:w(e,y,ce),maxEntries:w(e,le,v)}}var E=class{mounts=new Map;listeners=new Set;registerMount(e,t,n=T({})){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 x?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 x(`mount indexing aborted: directory nesting exceeded ${t.limits.maxDepth} levels`,`depth-exceeded`);if(t.directories.size+t.files.size>=t.limits.maxEntries)throw new x(`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 x(`mount indexing aborted: exceeded ${n.limits.maxEntries} entries`,`entries-exceeded`);i.push(e)}return i}async confirmNoCycle(e,t,n,r){let i=ue(n),a=r.get(i);if(a){for(let n of a)if(await de(n.handle,t))throw new x(`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)))}}},fe=new TextEncoder,D=new TextDecoder(`utf-8`,{fatal:!1}),O=class{entries=new Map;static handles(e){return d(s(e))}has(e){return this.entries.has(s(e))}write(e,t){let n=s(e),r=typeof t==`string`?fe.encode(t):new Uint8Array(t),i=Date.now(),a=this.entries.get(n);this.entries.set(n,{bytes:r,mtime:i,ctime:a?.ctime??i})}read(e,t){let n=this.require(e);return(t?.encoding??`utf-8`)===`utf-8`?D.decode(n.bytes):new Uint8Array(n.bytes)}readText(e){return D.decode(this.require(e).bytes)}stat(e){let t=this.require(e);return{type:`file`,size:t.bytes.length,mtime:t.mtime,ctime:t.ctime}}remove(e){return this.entries.delete(s(e))}require(e){let t=s(e),n=this.entries.get(t);if(!n)throw new u(`ENOENT`,`no such file or directory`,t);return n}},k={[f]:{stat:()=>({type:`file`,size:0,mtime:0,ctime:0}),read:e=>(e?.encoding??`utf-8`)===`utf-8`?``:new Uint8Array,readText:()=>``,write:()=>{}}},A=[`/tmp/`],j=class{ephemeralFds=new O;vfs;allowedPrefixes;readOnlyPrefixes;readGrantPatterns=[];writeEnforcement;constructor(e,t,n=[],r=`hard`){this.vfs=e;let i=e=>{let t=s(e);return t.endsWith(`/`)?t:t+`/`};this.allowedPrefixes=t.map(i),this.readOnlyPrefixes=n.map(i),this.writeEnforcement=r}getAllPrefixes(){let e=this.vfs.listMounts().map(e=>e.endsWith(`/`)?e:e+`/`);return[...this.allowedPrefixes,...this.readOnlyPrefixes,...e,...A]}setReadGrants(e){this.readGrantPatterns=[];for(let t of new Set(e))this.addReadGrant(t)}addReadGrant(e){let t=e.split(`/`),n=[];for(let e=1;e<t.length;e++)n.push(c(t.slice(0,e).join(`/`)||`/`));this.readGrantPatterns.push({pattern:e,regex:c(e),ancestorRegexes:n})}matchesReadGrant(e){return this.readGrantPatterns.some(t=>t.regex.test(e))}leadsToReadGrant(e){return this.readGrantPatterns.some(t=>t.ancestorRegexes.some(t=>t.test(e)))}isAllowed(e){let t=s(e),n=this.getAllPrefixes();return this.matchesReadGrant(t)||this.leadsToReadGrant(t)||n.some(e=>t===e.slice(0,-1)||t.startsWith(e)||t===`/`||e.startsWith(t+`/`))}isAllowedStrict(e){let t=s(e),n=this.getAllPrefixes();return this.matchesReadGrant(t)||n.some(e=>t===e.slice(0,-1)||t.startsWith(e))}isWritable(e){let t=s(e);return[...this.allowedPrefixes,...A].some(e=>t===e.slice(0,-1)||t.startsWith(e))}canWrite(e){return O.handles(e)||this.isWritable(e)}checkWrite(e){if(this.writeEnforcement!==`sudo-delegated`&&!this.isWritable(e))throw new u(`EACCES`,`permission denied`,s(e))}async resolveAndCheckRead(e){try{let t=await this.vfs.realpath(e);if(!this.isAllowedStrict(t))throw new u(`ENOENT`,`no such file or directory`,s(e));return t}catch(t){throw t instanceof u?t:new u(`ENOENT`,`no such file or directory`,s(e))}}async resolveAndCheckWrite(e){try{let t=await this.vfs.realpath(e);if(!this.isWritable(t)&&!this.isSymlinkEscapeAllowed(t))throw new u(`EACCES`,`permission denied`,s(e));return t}catch(t){throw t instanceof u?t:new u(`EACCES`,`permission denied`,s(e))}}isSymlinkEscapeAllowed(e){return!1}async checkParentRealpathEscape(e){let t=this.vfs.dirname(e),n=this.vfs.basename(e),r;try{r=await this.vfs.realpath(t)}catch(e){if(e instanceof u&&e.code===`EACCES`)throw e;return}let i=r+`/`+n;if(this.isWritable(i))return;let a=s(r)!==s(t);if(!(this.writeEnforcement===`sudo-delegated`&&!a))throw new u(`EACCES`,`permission denied`,s(e))}getUnderlyingFS(){return this.vfs}invalidatePaths(e){this.vfs.invalidatePaths(e)}async flush(){await this.vfs.flush()}isPathUnderMount(e){return this.vfs.isPathUnderMount(e)}async readFile(e,t){let n=k[s(e)];if(n)return n.read(t);if(O.handles(e))return this.ephemeralFds.read(e,t);if(!this.isAllowedStrict(e))throw new u(`ENOENT`,`no such file or directory`,s(e));let r=await this.resolveAndCheckRead(e);return this.vfs.readFile(r,t)}async readDir(e){if(!this.isAllowed(e))return[];let t=e;if(this.isAllowedStrict(e))try{t=await this.resolveAndCheckRead(e)}catch{return[]}let n=await this.vfs.readDir(t);if(!this.isAllowedStrict(e)){let t=s(e);return n.filter(e=>{let n=t===`/`?`/${e.name}`:`${t}/${e.name}`;return this.isAllowed(n)})}return n}async stat(e){let t=k[s(e)];if(t)return t.stat();if(O.handles(e))return this.ephemeralFds.stat(e);if(!this.isAllowed(e))throw new u(`ENOENT`,`no such file or directory`,s(e));if(this.isAllowedStrict(e)){let t=await this.resolveAndCheckRead(e);return this.vfs.stat(t)}return this.vfs.stat(e)}scanPathForSymlinks(e,t){let n=s(e);if(n===`/`)return!1;let r=n.slice(1).split(`/`),i=t?r.length:r.length-1,a=``;for(let e=0;e<i;e++){a=a+`/`+r[e];let t=this.vfs.lstatSync(a);if(t===null)return null;if(t.type===`symlink`)return!0}return!1}statSync(e){let t=k[s(e)];return t?t.stat():O.handles(e)?this.ephemeralFds.has(e)?this.ephemeralFds.stat(e):null:!this.isAllowedStrict(e)||this.scanPathForSymlinks(e,!0)!==!1?null:this.vfs.statSync(e)}lstatSync(e){let t=k[s(e)];return t?t.stat():O.handles(e)?this.ephemeralFds.has(e)?this.ephemeralFds.stat(e):null:!this.isAllowed(e)||this.scanPathForSymlinks(e,!1)!==!1?null:this.vfs.lstatSync(e)}readDirSync(e){if(!this.isAllowed(e)||this.scanPathForSymlinks(e,!0)!==!1)return null;let t=this.vfs.readDirSync(e);if(t===null)return null;if(this.isAllowedStrict(e))return t;let n=s(e);return t.filter(e=>{let t=n===`/`?`/${e.name}`:`${n}/${e.name}`;return this.isAllowed(t)})}async realpath(e){if(O.handles(e)){let t=s(e);if(!this.ephemeralFds.has(t))throw new u(`ENOENT`,`no such file or directory`,t);return t}let t;try{t=await this.vfs.realpath(e)}catch(t){throw t instanceof u?t:new u(`ENOENT`,`no such file or directory`,s(e))}if(!this.isAllowedStrict(t))throw new u(`ENOENT`,`no such file or directory`,s(e));return t}async exists(e){if(k[s(e)])return!0;if(O.handles(e))return this.ephemeralFds.has(e);if(!this.isAllowed(e))return!1;if(this.isAllowedStrict(e))try{await this.resolveAndCheckRead(e)}catch{return!1}return this.vfs.exists(e)}async readTextFile(e){let t=k[s(e)];if(t)return t.readText();if(O.handles(e))return this.ephemeralFds.readText(e);if(!this.isAllowedStrict(e))throw new u(`ENOENT`,`no such file or directory`,s(e));let n=await this.resolveAndCheckRead(e);return this.vfs.readTextFile(n)}async*walk(e){if(!this.isAllowed(e))return;let t=e;if(this.isAllowedStrict(e))try{t=await this.resolveAndCheckRead(e)}catch{return}for await(let e of this.vfs.walk(t))this.isAllowed(e)&&(yield e)}async writeFile(e,t,n){let r=k[s(e)];if(r){r.write(t);return}if(O.handles(e)){this.ephemeralFds.write(e,t);return}this.checkWrite(e),await this.checkParentRealpathEscape(e);try{(await this.vfs.lstat(e)).type===`symlink`&&await this.resolveAndCheckWrite(e)}catch(e){if(e instanceof u&&e.code===`EACCES`)throw e}return this.vfs.writeFile(e,t,n)}refuseDescriptorTreeOp(e){if(O.handles(e))throw new u(`EACCES`,`permission denied`,s(e))}async mkdir(e,t){return this.refuseDescriptorTreeOp(e),this.checkWrite(e),await this.checkParentRealpathEscape(e),this.vfs.mkdir(e,t)}async rm(e,t){if(O.handles(e)){if(!this.ephemeralFds.remove(e))throw new u(`ENOENT`,`no such file or directory`,s(e));return}this.checkWrite(e);try{(await this.vfs.lstat(e)).type===`symlink`||await this.resolveAndCheckWrite(e)}catch(e){if(e instanceof u&&e.code===`EACCES`)throw e}return this.vfs.rm(e,t)}async rename(e,t){return this.refuseDescriptorTreeOp(e),this.refuseDescriptorTreeOp(t),this.checkWrite(e),this.checkWrite(t),await this.resolveAndCheckWrite(e),await this.checkParentRealpathEscape(t),this.vfs.rename(e,t)}async copyFile(e,t){if(O.handles(e)){let n=this.ephemeralFds.read(e,{encoding:`binary`});await this.writeFile(t,n);return}if(O.handles(t)){if(!this.isAllowed(e))throw new u(`ENOENT`,`no such file or directory`,s(e));let n=await this.resolveAndCheckRead(e);this.ephemeralFds.write(t,await this.vfs.readFile(n,{encoding:`binary`}));return}if(!this.isAllowed(e))throw new u(`ENOENT`,`no such file or directory`,s(e));this.checkWrite(t);let n=await this.resolveAndCheckRead(e);await this.checkParentRealpathEscape(t);try{(await this.vfs.lstat(t)).type===`symlink`&&await this.resolveAndCheckWrite(t)}catch(e){if(e instanceof u&&e.code===`EACCES`)throw e}return this.vfs.copyFile(n,t)}async symlink(e,t){return this.refuseDescriptorTreeOp(t),this.checkWrite(t),await this.checkParentRealpathEscape(t),this.vfs.symlink(e,t)}async readlink(e){if(!this.isAllowedStrict(e))throw new u(`ENOENT`,`no such file or directory`,s(e));let t=await this.vfs.readlink(e),n;if(t.startsWith(`/`))n=s(t);else{let r=this.vfs.dirname(e);n=s(r+`/`+t)}if(!this.isAllowedStrict(n))throw new u(`ENOENT`,`no such file or directory`,s(e));return t}async lstat(e){let t=k[s(e)];if(t)return t.stat();if(O.handles(e))return this.ephemeralFds.stat(e);if(!this.isAllowed(e))throw new u(`ENOENT`,`no such file or directory`,s(e));let n=s(e),r=this.vfs.dirname(n),i=this.vfs.basename(n),a;if(r===n)a=r;else try{a=await this.vfs.realpath(r)}catch{throw new u(`ENOENT`,`no such file or directory`,n)}let o=a===`/`?`/${i}`:`${a}/${i}`;if(!this.isAllowed(o))throw new u(`ENOENT`,`no such file or directory`,n);return this.vfs.lstat(o)}watch(e,t,n){if(!this.isAllowed(e))throw new u(`EACCES`,`permission denied`,s(e));let r=this.vfs.getWatcher();if(!r)throw new u(`EINVAL`,`no watcher configured`);return r.watch(s(e),t,n)}dirname(e){return this.vfs.dirname(e)}basename(e){return this.vfs.basename(e)}async mount(e,t,n){return this.refuseDescriptorTreeOp(e),this.checkWrite(e),await this.checkParentRealpathEscape(e),this.vfs.mount(e,t,n)}async unmount(e){return this.refuseDescriptorTreeOp(e),this.checkWrite(e),await this.checkParentRealpathEscape(e),this.vfs.unmount(e)}listMounts(){return this.vfs.listMounts()}getMountIndex(){return this.vfs.getMountIndex()}async refreshMount(e,t){return this.refuseDescriptorTreeOp(e),this.checkWrite(e),this.vfs.refreshMount(e,t)}async dispose(){await this.vfs.dispose()}};function M(e,t){if(e instanceof u){let n=`${e.code}: `,r=e.message;throw r.startsWith(n)&&(r=r.slice(n.length)),e.path&&r.endsWith(` '${e.path}'`)&&(r=r.slice(0,r.length-` '${e.path}'`.length)),new u(e.code,r,t)}throw e}var pe=[`ENOENT`,`EEXIST`,`ENOTDIR`,`EISDIR`,`ENOTEMPTY`,`EINVAL`,`EACCES`,`ELOOP`,`EBUSY`,`EFBIG`,`EBADF`,`ENOSYS`,`EIO`];function N(e,t){if(e instanceof u)return e;{let n=e instanceof Error?e.message:String(e);if(n.includes(`maximum size exceeded`)||n.includes(`call stack size exceeded`))return new u(`EIO`,`internal overflow, not storage: ${n} — reload the session`,t)}let n=e?.code;if(typeof n==`string`){let r=n;if(pe.includes(r)){let n=e instanceof Error?e.message:String(e);return n.startsWith(`${r}: `)&&(n=n.slice(r.length+2),n=n.replace(/, undefined( '[^']*')?$/,``).replace(/ '[^']*'$/,``)),new u(r,n||r,t)}}let r=e instanceof Error?e.message:String(e);return r.includes(`ENOENT`)?new u(`ENOENT`,`no such file or directory`,t):r.includes(`EEXIST`)?new u(`EEXIST`,`file already exists`,t):r.includes(`ENOTDIR`)?new u(`ENOTDIR`,`not a directory`,t):r.includes(`EISDIR`)?new u(`EISDIR`,`is a directory`,t):r.includes(`ENOTEMPTY`)?new u(`ENOTEMPTY`,`directory not empty`,t):r.includes(`ELOOP`)?new u(`ELOOP`,`too many levels of symbolic links`,t):new u(`EINVAL`,r,t)}var me=61440,he=16384;function P(e){return e===void 0?`absent`:(e&me)===he?`directory`:`file`}function F(e,t){return t===`absent`?!1:e.kind===`missing`||e.kind!==t}function I(e){let t=e?.mode;return typeof t==`number`?t:void 0}function L(e,t,n,r=new Set){let i=new Set(n);if(r.size>0){for(let t of Object.keys(e.entries??{}))for(let e of r)if(t===e||t.startsWith(`${e}/`)){i.add(t);break}}let a=[];for(let n of i){let r=e.entries?.[n],i=t.entries?.[n];if(!r||!i)continue;let o=P(I(r));o!==P(I(i))&&a.push({path:n,ownIsDirectory:o===`directory`})}return a}var R=3e5,ge=5e3,z=Symbol(`mount:timeout`),B=Symbol(`mount:no-panel`),V=class e{kind=`local`;source=void 0;profile=void 0;mountId;handle;closed=!1;constructor(e,t){this.handle=e,this.mountId=t.mountId}static fromHandle(t,n){return new e(t,n)}static async create(t){if(t.isScoop())throw Error(`mount: cannot mount local directories from a scoop (no UI). Ask the cone.`);let n;return n=t.toolContext?await e.acquireHandleViaToolUI(t.toolContext,t.targetPath):t.isExtension?await e.acquireHandleViaPopup():await e.acquireHandleViaDirectPicker(),new e(n,{mountId:t.mountId})}static async acquireHandleViaPopup(){try{let e=await te();if(e.cancelled)throw Error(`mount: cancelled`);if(e.error)throw Error(`mount: ${e.error}`);if(e.handleInIdb&&typeof e.idbKey==`string`){let t=await m(e.idbKey);if(!t)throw Error(`mount: no directory handle found in storage`);return await p(t),t}throw Error(`mount: unexpected popup result`)}catch(e){throw Error(`mount: ${e instanceof Error?e.message:String(e)}`)}}static async acquireHandleViaDirectPicker(){if(typeof window>`u`||!(`showDirectoryPicker`in window))throw Error(`mount: local picker requires a user gesture in the panel (unavailable in this runtime). Ask the agent to mount it instead.`);try{return await window.showDirectoryPicker({mode:`readwrite`})}catch(e){throw e instanceof Error&&e.name===`AbortError`?Error(`mount: cancelled`):Error(`mount: ${e instanceof Error?e.message:String(e)}`)}}static async acquireHandleViaToolUI(t,n){let a=i.generateId(),o=!1,s=!1,c=r({id:a,html:ee(`directory`,[],n),onAction:(t,n)=>e.resolveApprovalAction(t,n)},t.onUpdate).catch(e=>{if(o)return z;if(s)return B;throw e}),l,u=new Promise(e=>{l=setTimeout(()=>{o=!0,i.cancel(a,`mount: timed out`),e(z)},R)}),d=new Promise(e=>{i.waitForMount(a,ge).then(()=>{},()=>{o||(s=!0,i.cancel(a,`mount: panel did not render the approval card`),e(B))})}),f=await Promise.race([c,u,d]);if(l&&clearTimeout(l),f===z)throw Error(`mount: timed out after ${Math.round(R/6e4)} minute(s) waiting for user approval`);if(f===B)throw Error(`mount: chat panel did not render the approval card — open the chat panel and retry`);if(!f)throw Error(`mount: tool UI not available`);let p=f;if(p.denied)throw Error(`mount: denied by user`);if(p.cancelled)throw Error(`mount: cancelled`);if(p.error)throw Error(`mount: ${p.error}`);if(!p.handle)throw Error(`mount: no directory selected`);return p.handle}static async resolveApprovalAction(e,t){if(e!==`approve`)return{denied:!0};let n=t;if(n?.handleInIdb&&typeof n.idbKey==`string`)try{let e=await m(n.idbKey);return e?(await p(e),{approved:!0,handle:e}):{error:`No directory handle found in storage`}}catch(e){return{error:e instanceof Error?e.message:String(e)}}if(n?.cancelled)return{cancelled:!0};if(n?.error)return{error:String(n.error)};try{return{approved:!0,handle:await window.showDirectoryPicker({mode:`readwrite`})}}catch(e){return e instanceof Error&&e.name===`AbortError`?{cancelled:!0}:{error:e instanceof Error?e.message:String(e)}}}getHandle(){return this.handle}assertOpen(e){if(this.closed)throw new u(`EBADF`,`mount closed`,e)}splitPath(e){return e.replace(/^\/+/,``).replace(/\/+$/,``).split(`/`).filter(e=>e.length>0)}async resolveDir(e,t=!1){let n=this.splitPath(e),r=this.handle;for(let i of n)try{r=await r.getDirectoryHandle(i,{create:t})}catch(t){throw this.toFsError(t,e)}return r}async resolveFile(e,t=!1){let n=this.splitPath(e);if(n.length===0)throw new u(`EISDIR`,`is a directory`,e);let r=n.pop(),i=this.handle;for(let r of n)try{i=await i.getDirectoryHandle(r,{create:t})}catch(t){throw this.toFsError(t,e)}try{return await i.getFileHandle(r,{create:t})}catch(t){throw this.toFsError(t,e)}}toFsError(e,t){if(e instanceof u)return e;if(e instanceof DOMException){if(e.name===`NotFoundError`)return new u(`ENOENT`,`no such file or directory`,t);if(e.name===`TypeMismatchError`)return new u(`ENOTDIR`,`not a directory`,t);if(e.name===`NotAllowedError`)return new u(`EACCES`,`permission denied`,t);if(e.name===`InvalidModificationError`)return new u(`ENOTEMPTY`,`directory not empty`,t)}if(e instanceof Error){if(e.name===`NotFound`||e.name===`NotFoundError`)return new u(`ENOENT`,`no such file or directory`,t);if(e.name===`TypeMismatch`||e.name===`TypeMismatchError`)return new u(`ENOTDIR`,`not a directory`,t);if(e.name===`InvalidModification`||e.name===`InvalidModificationError`)return new u(`ENOTEMPTY`,`directory not empty`,t)}return new u(`EINVAL`,e instanceof Error?e.message:String(e),t)}async readDir(e){this.assertOpen(e);let t=await this.resolveDir(e),n=[];for await(let[e,r]of t)if(r.kind===`file`){let t=await r.getFile();n.push({name:e,kind:`file`,size:t.size,lastModified:t.lastModified})}else n.push({name:e,kind:`directory`});return n}async readFile(e){this.assertOpen(e);let t=await(await this.resolveFile(e)).getFile();return new Uint8Array(await t.arrayBuffer())}async writeFile(e,t){this.assertOpen(e);let n=await(await this.resolveFile(e,!0)).createWritable();await n.write(t),await n.close()}async stat(e){if(this.assertOpen(e),this.splitPath(e).length===0)return{kind:`directory`,size:0,mtime:0};try{let t=await(await this.resolveFile(e)).getFile();return{kind:`file`,size:t.size,mtime:t.lastModified}}catch{}return await this.resolveDir(e),{kind:`directory`,size:0,mtime:0}}async mkdir(e){this.assertOpen(e),await this.resolveDir(e,!0)}async remove(e,t){this.assertOpen(e);let n=this.splitPath(e);if(n.length===0)throw new u(`EINVAL`,`cannot remove mount root`,e);let r=n.pop(),i=n.join(`/`),a=await this.resolveDir(i||`/`);try{await a.removeEntry(r,{recursive:t?.recursive??!1})}catch(t){throw this.toFsError(t,e)}}async refresh(){return this.assertOpen(`/`),{added:[],removed:[],changed:[],unchanged:0,errors:[]}}describe(){return{displayName:this.handle.name}}async close(){this.closed=!0}};function H(e,t){return e===t||e.startsWith(t===`/`?`/`:`${t}/`)}var _e=`/.metadata.json`;function U(e){return e.entries&&delete e.entries[_e],e}function ve(e,t,n){let r=t.entries??{},i={...e.entries??{}};`/`in r&&(i[`/`]=r[`/`]);for(let e of n.paths)e in r?i[e]=r[e]:delete i[e];for(let e of n.prefixes){for(let t of Object.keys(i))H(t,e)&&delete i[t];for(let t of Object.keys(r))H(t,e)&&(i[t]=r[t])}let{entries:a,...o}=t;return U({...o,entries:i})}var ye=61440,W=16384,G=32768,be=40960;async function K(e,t,n){let r={kindFixed:[],sizesFixed:0,dropped:0,selfEntryDropped:!1,inosReassigned:0,nlinksFixed:0,changed:!1},i=e.entries??{};for(let[e,a]of Object.entries(i)){if(n?.(),e===`/`||typeof a!=`object`||!a)continue;if(e===`/.metadata.json`){delete i[e],r.selfEntryDropped=!0,r.changed=!0;continue}let o=a,s=(o.mode??0)&ye;if(s===be){q(o,r);continue}let c=await t(e);if(c.kind===`missing`){delete i[e],r.dropped+=1,r.changed=!0;continue}q(o,r),Se(e,o,s,c,r)}return xe(i,r),r}function xe(e,t){let n=0;for(let t of Object.values(e)){let e=t;typeof e?.ino==`number`&&(n=Math.max(n,e.ino)),typeof e?.data==`number`&&(n=Math.max(n,e.data))}let r=n+1,i=new Set;for(let[n,a]of Object.entries(e)){if(typeof a!=`object`||!a)continue;let e=a;if(n===`/`){typeof e.ino==`number`&&i.add(e.ino);continue}let o=e.ino;if(typeof o==`number`&&o!==0&&!i.has(o)){i.add(o);continue}e.ino=r,e.data=r+1,i.add(r),r+=2,t.inosReassigned+=1,t.changed=!0}}function q(e,t){e.nlink||(e.nlink=1,t.nlinksFixed+=1,t.changed=!0)}function Se(e,t,n,r,i){if(n===G&&r.kind===`directory`){t.mode=((t.mode??0)&511||493)|W,i.kindFixed.push(`${e} file→dir`),i.changed=!0;return}if(n===W&&r.kind===`file`){t.mode=((t.mode??0)&511||420)|G,t.size=r.size,i.kindFixed.push(`${e} dir→file`),i.changed=!0;return}n===G&&r.kind===`file`&&typeof t.size==`number`&&t.size!==r.size&&(t.size=r.size,i.sizesFixed+=1,i.changed=!0)}function J(e){return async t=>{let n=t.split(`/`).filter(Boolean),r=e;for(let e=0;e<n.length-1;e+=1)try{r=await r.getDirectoryHandle(n[e])}catch{return{kind:`missing`}}let i=n[n.length-1];if(i===void 0)return{kind:`directory`};try{return{kind:`file`,size:(await(await r.getFileHandle(i)).getFile()).size}}catch{}try{return await r.getDirectoryHandle(i),{kind:`directory`}}catch{return{kind:`missing`}}}}async function Ce(e,t,n){try{return await e()}catch(r){let i=null;try{i=await t()}catch{}if(!i?.changed)throw r;return n(i),await e()}}async function we(e,t){let n;try{let t=await e.getFileHandle(`.metadata.json`),r=JSON.parse(await(await t.getFile()).text());if(!r||typeof r!=`object`||!r.entries)return null;n=r}catch{return null}let r=await K(n,J(e),t);if(!r.changed)return r;let i=await(await e.getFileHandle(`.metadata.json`,{create:!0})).createWritable();return await i.write(JSON.stringify(n)),await i.close(),r}async function Te(e,t,n,r){try{return await e.lstat(t)}catch(e){let t=N(e,r);if(t.code===`ENOENT`&&n)return null;throw t}}async function Ee(e,t,n){let r;try{r=await e.readlink(t)}catch(e){throw N(e,n)}return r.startsWith(`/`)?s(r):s(l(a(t).dir,r))}async function De(e,t,n,r,i,a){let o=t===`/`?`/${n}`:`${t}/${n}`;for(;;){let t=await Te(e,o,r,i);if(t===null||!t.isSymbolicLink())return{resolved:o,hops:a};if(++a>10)throw new u(`ELOOP`,`too many symbolic links encountered`,i);o=await Ee(e,o,i)}}async function Y(e,t,n){let r=s(n);if(t(r))return r;let i=r.split(`/`).filter(Boolean),a=`/`,o=0;for(let t=0;t<i.length;t++){let n=await De(e,a,i[t],t===i.length-1,r,o);a=n.resolved,o=n.hops}return a}async function Oe(e,t,n){return t(n)?n:Y(e,t,n)}function ke(e,t,n){return e.size===0||!e.has(n)||!t.isReady(n)?!1:!Array.from(e.keys()).some(e=>e!==n&&e.startsWith(n+`/`))}async function Ae(e,t){try{return await e(t)}catch{return t}}async function*X(e,t,n,r=0){let i=s(t);if(ke(e.mountPoints,e.mountIndex,i)){let t=e.mountIndex.getFiles(i);if(t){for(let e of t)yield e;return}}let a=n??new Set;if(r>64||a.size>=1e5)return;let o=await Ae(t=>e.realpath(t),i);if(a.has(o))return;a.add(o);let c=await e.readDir(i);for(let t of c)yield*Z(e,t,i===`/`?`/${t.name}`:`${i}/${t.name}`,a,r+1)}async function*Z(e,t,n,r,i){if(t.type===`file`){yield n;return}if(t.type===`symlink`){yield*je(e,n,r,i);return}yield*X(e,n,r,i)}async function*je(e,t,n,r){try{let i=await e.stat(t);i.type===`file`?yield t:i.type===`directory`&&(yield*X(e,t,n,r))}catch{}}function Q(){try{if(typeof globalThis.navigator?.storage?.getDirectory==`function`)return`opfs`}catch{}return`memory`}function Me(e,t){switch(e.kind){case`local`:case`proc`:return{kind:`local`,mountId:e.mountId,idbHandleKey:t};case`hostfs`:return{kind:`hostfs`,mountId:e.mountId,hostPath:e.getHostPath()};default:return{kind:e.kind===`s3`?`s3`:e.kind===`aem`?`aem`:`da`,mountId:e.mountId,source:e.source,profile:e.profile??`default`}}}var $=class e{lfs;lfsSync;rawLfs=null;rawLfsSync=null;_ready;_readyResolved=!1;backend;mountPoints=new Map;opfsBackendFs=null;opfsHandle=null;mountRoot=``;internalMounts=new Set;watcher=null;dbName;mountSyncChannel=null;mountIndex=new E;static writeChains=new Map;onRepairProgress;constructor(t,n,r,i,a){if(this.dbName=t,this.onRepairProgress=a,this.backend=r===`opfs`?`opfs`:`memory`,this.lfs=this.makeDeferredLfs(),this.lfsSync=this.makeDeferredLfsSync(),this._ready=this.backend===`opfs`?e.initOpfsBackend(this,i,n===!0):e.initMemoryBackend(this,t,n===!0),this._ready.then(()=>{this._readyResolved=!0},()=>{}),typeof BroadcastChannel<`u`)try{this.mountSyncChannel=new BroadcastChannel(`vfs-mount-sync:${t}`),this.mountSyncChannel.onmessage=e=>{let{type:t,path:n,descriptor:r}=e.data??{};if(t===`mount`&&typeof n==`string`&&r)this.reconstructBackendFromDescriptor(r,n).then(e=>{this.mountPoints.set(n,e),e.kind===`local`&&this.mountIndex.registerMount(n,e.getHandle()),this.watcher?.notify([{type:`modify`,path:n,entryType:`directory`}])}).catch(()=>{});else if(t===`unmount`&&typeof n==`string`){let e=this.mountPoints.get(n);this.mountPoints.delete(n),this.mountIndex.unregisterMount(n),e?.close(),this.watcher?.notify([{type:`modify`,path:n,entryType:`directory`}])}}}catch{}}static async initOpfsBackend(n,r,i){let a=r??await e.acquireOpfsHandle(n.dbName,i);await e.seedOpfsMetadataSidecarIfMissing(a);let[o,{WebAccess:s}]=await Promise.all([t(()=>import(`./dist-BKQr3WRb.js`).then(e=>e.t),__vite__mapDeps([0,1,2])),t(()=>import(`./dist-DHO9E-gl.js`),__vite__mapDeps([3,0,1,2]))]);await e.ensureRootMount(o);let c=`/__opfs__/${n.dbName}`,l=e.opfsBackends.get(n.dbName);if(l&&i){try{o.umount(c)}catch{}e.opfsBackends.delete(n.dbName),l=void 0}if(!l){let r=()=>o.resolveMountConfig({backend:s,handle:a,metadata:`/.metadata.json`}),{resolveWithSidecarRepair:i,repairOpfsMetadataSidecar:u}=await t(async()=>{let{resolveWithSidecarRepair:e,repairOpfsMetadataSidecar:t}=await import(`./sidecar-repair-CEmls84u.js`);return{resolveWithSidecarRepair:e,repairOpfsMetadataSidecar:t}},[]);try{let e=await n.withWriteLock(()=>u(a,n.onRepairProgress));e?.changed&&console.warn(`[virtual-fs] repaired metadata sidecar before mount (#2146)`,{dbName:n.dbName,kindFixed:e.kindFixed,sizesFixed:e.sizesFixed,dropped:e.dropped,inosReassigned:e.inosReassigned,nlinksFixed:e.nlinksFixed,selfEntryDropped:e.selfEntryDropped})}catch{}let d=await i(r,()=>n.withWriteLock(()=>u(a,n.onRepairProgress)),e=>console.warn(`[virtual-fs] repaired poisoned metadata sidecar; retrying mount`,{dbName:n.dbName,kindFixed:e.kindFixed,sizesFixed:e.sizesFixed,dropped:e.dropped,nlinksFixed:e.nlinksFixed,selfEntryDropped:e.selfEntryDropped}));try{o.mount(c,d)}catch{}l={backendFs:d,refs:0,sidecarDirty:{paths:new Set,prefixes:new Set}},e.opfsBackends.set(n.dbName,l)}l.refs+=1,n.opfsBackendFs=l.backendFs.index?l.backendFs:null,n.opfsHandle=a,n.mountRoot=c,n.rawLfs=o.promises,n.rawLfsSync=o}static async initMemoryBackend(n,r,i){let a=await t(()=>import(`./dist-BKQr3WRb.js`).then(e=>e.t),__vite__mapDeps([0,1,2]));await e.ensureRootMount(a);let o=`/__zenfs__/${r}`,s=e.memoryBackends.get(r);if(s&&i){try{a.umount(o)}catch{}e.memoryBackends.delete(r),s=void 0}s||(s={store:a.InMemory.create({label:r}),refs:0},e.memoryBackends.set(r,s)),s.refs+=1;try{a.mount(o,s.store)}catch{}n.mountRoot=o,n.rawLfs=a.promises,n.rawLfsSync=a,n.opfsBackendFs=null,n.opfsHandle=null}static rootMountReady=null;static memoryBackends=new Map;static opfsBackends=new Map;static async ensureRootMount(t){return e.rootMountReady===null&&(e.rootMountReady=(async()=>{await t.configureSingle({backend:t.InMemory,label:`__vfs_root__`})})()),e.rootMountReady}prefix(e){return this.mountRoot?e===`/`?this.mountRoot:this.mountRoot+e:e}unprefix(e){return!this.mountRoot||!e.startsWith(this.mountRoot)?e:e.slice(this.mountRoot.length)||`/`}makeDeferredLfs(){let e=e=>this.prefix(e),t=e=>this.unprefix(e),n=()=>{if(!this.rawLfs)throw Error(`VirtualFS used before init resolved`);return this.rawLfs};return{readFile:(t,r)=>this._readyResolved?n().readFile(e(t),r):this._ready.then(()=>n().readFile(e(t),r)),writeFile:(t,r,i)=>this._readyResolved?n().writeFile(e(t),r,i):this._ready.then(()=>n().writeFile(e(t),r,i)),readdir:t=>this._readyResolved?n().readdir(e(t)):this._ready.then(()=>n().readdir(e(t))),mkdir:(t,r)=>this._readyResolved?n().mkdir(e(t),r):this._ready.then(()=>n().mkdir(e(t),r)),rmdir:t=>this._readyResolved?n().rmdir(e(t)):this._ready.then(()=>n().rmdir(e(t))),unlink:t=>this._readyResolved?n().unlink(e(t)):this._ready.then(()=>n().unlink(e(t))),rename:(t,r)=>this._readyResolved?n().rename(e(t),e(r)):this._ready.then(()=>n().rename(e(t),e(r))),stat:t=>this._readyResolved?n().stat(e(t)):this._ready.then(()=>n().stat(e(t))),lstat:t=>this._readyResolved?n().lstat(e(t)):this._ready.then(()=>n().lstat(e(t))),symlink:(t,r)=>{let i=t.startsWith(`/`)?e(t):t;return this._readyResolved?n().symlink(i,e(r)):this._ready.then(()=>n().symlink(i,e(r)))},readlink:async r=>(this._readyResolved||await this._ready,t(await n().readlink(e(r)))),truncate:async(t,r)=>{this._readyResolved||await this._ready;let i=n();typeof i.truncate==`function`&&await i.truncate(e(t),r)},realpath:async r=>{this._readyResolved||await this._ready;let i=n();return typeof i.realpath==`function`?t(await i.realpath(e(r))):e(r)}}}makeDeferredLfsSync(){let e=e=>this.prefix(e),t=e=>this.unprefix(e);return{readdirSync:t=>{let n=this.rawLfsSync;return n?.readdirSync?n.readdirSync(e(t)):void 0},statSync:t=>{let n=this.rawLfsSync;return n?.statSync?n.statSync(e(t)):void 0},lstatSync:t=>{let n=this.rawLfsSync;return n?.lstatSync?n.lstatSync(e(t)):void 0},readlinkSync:n=>{let r=this.rawLfsSync;return r?.readlinkSync?t(r.readlinkSync(e(n))):void 0}}}static async seedOpfsMetadataSidecarIfMissing(e){let t=`.metadata.json`;try{await e.getFileHandle(t);return}catch(e){if(e?.name!==`NotFoundError`)throw e}let n=await(await e.getFileHandle(t,{create:!0})).createWritable(),r=JSON.stringify({version:1,maxSize:4294967295,entries:{}});await n.write(r),await n.close()}static async acquireOpfsHandle(e,t){let n=navigator.storage;if(!n?.getDirectory)throw new u(`EINVAL`,`OPFS is not available in this environment`);let r=await n.getDirectory();if(t)try{await r.removeEntry(e,{recursive:!0})}catch{}return r.getDirectoryHandle(e,{create:!0})}static _createSyncForTests(t){return new e(t)}static async create(t){let n=t?.dbName??`browser-fs`,r=t?.wipe===!0,i=t?.backend??Q(),a=new e(n,r,i,void 0,t?.onRepairProgress);return await a._ready,r&&await ae().catch(()=>{}),a}async flush(){await this.writeOpfsMetadataSidecar()}async writeOpfsMetadataSidecar(){this.backend===`opfs`&&await this.withWriteLock(()=>this.writeOpfsMetadataSidecarUnlocked())}async writeOpfsMetadataSidecarUnlocked(){if(this.backend!==`opfs`)return;let t=this.opfsBackendFs,n=this.opfsHandle;if(!t||!n)return;let r=t.index.toJSON(),i=e.opfsBackends.get(this.dbName)?.sidecarDirty,a=r;if(i){let e=null;try{let t=await n.getFileHandle(`.metadata.json`),r=JSON.parse(await(await t.getFile()).text());r&&typeof r==`object`&&r.entries&&(e=r)}catch{}e&&(await this.auditDirtyKindFlips(r,e,i,n),a=ve(e,r,i))}let o=JSON.stringify(U(a)),s=await(await n.getFileHandle(`.metadata.json`,{create:!0})).createWritable();await s.write(o),await s.close(),i&&(i.paths.clear(),i.prefixes.clear())}async auditDirtyKindFlips(e,t,n,r){let i=L(e,t,n.paths,n.prefixes);if(i.length===0)return;let a=J(r),o=this.opfsBackendFs;for(let n of i){let r=await a(n.path).catch(()=>null);if(r!==null&&r.kind!==`missing`&&r.kind===`directory`===n.ownIsDirectory)continue;let i=t.entries?.[n.path];e.entries&&i!==void 0&&(e.entries[n.path]=i);let s=r!==null&&r.kind!==`missing`;s&&(o?.index?.delete(n.path),o?._handles?.delete(n.path)),console.warn(`[virtual-fs] refused to flush in-memory kind flip over sidecar record (#2006)`,{path:n.path,reality:r?.kind??`unverifiable`,evicted:s})}}markSidecarDirty(t,n=`path`){if(this.backend!==`opfs`)return;let r=e.opfsBackends.get(this.dbName)?.sidecarDirty;if(!r)return;let i=s(t);(n===`prefix`?r.prefixes:r.paths).add(i);let{dir:o}=a(i);for(;o!==`/`;)r.paths.add(o),o=a(o).dir}invalidatePaths(e){if(this.backend!==`opfs`||!this.opfsBackendFs)return;let t=this.opfsBackendFs;for(let n of e){let e=s(n);t.index.delete(e),t._handles?.delete(e),this.markSidecarDirty(e)}}async withKindMismatchRetry(e,t){return this.withKindMismatchRetryPaths([e],t)}async withKindMismatchRetryPaths(e,t){try{return await t()}catch(n){let r=n?.code;if(r!==`EISDIR`&&r!==`ENOTDIR`&&r!==`EINVAL`)throw n;for(let n of e)if(await this.reconcileKindMismatch(n).catch(()=>!1))return await t();throw n}}async reconcileKindMismatch(e){if(this.backend!==`opfs`)return!1;let t=this.opfsBackendFs,n=this.opfsHandle;if(!t?.index||!n)return!1;let r=s(e),i=r;try{i=await this.resolveSymlinks(r)}catch{}let a=await J(n)(i),o=P(t.index.get(i)?.mode),c=t._handles?.get(i),l=c?.kind===`directory`?`directory`:c?.kind===`file`?`file`:`absent`,u=F(a,o),d=F(a,l);if(!u&&!d)return!1;if(t.index.delete(i),t._handles?.delete(i),o===`directory`||l===`directory`){let e=`${i}/`;for(let n of[...t.index.keys()])n.startsWith(e)&&t.index.delete(n);if(t._handles)for(let n of[...t._handles.keys()])n.startsWith(e)&&t._handles.delete(n)}return this.markSidecarDirty(i),console.warn(`[virtual-fs] reconciled in-memory kind mismatch (#2006)`,{path:i,reality:a.kind,indexHeld:o,handleHeld:l}),!0}canWrite(e){return!0}setWatcher(e){this.watcher=e}getWatcher(){return this.watcher}async watch(e,t){let n=this.watcher;if(!n)throw new u(`ENOSYS`,`no FsWatcher attached to this VirtualFS`);let r=e.map(e=>n.watch(e,()=>!0,t));return()=>{for(let e of r)e()}}async dispose(){if(this.mountSyncChannel?.close(),this.mountSyncChannel=null,this.watcher?.dispose(),this.watcher=null,this.mountIndex.dispose(),await this.writeOpfsMetadataSidecar(),this.mountRoot){let n=this.backend===`opfs`?e.opfsBackends:e.memoryBackends,r=n.get(this.dbName);if(r&&(--r.refs,r.refs<=0)){n.delete(this.dbName);try{(await t(()=>import(`./dist-BKQr3WRb.js`).then(e=>e.t),__vite__mapDeps([0,1,2]))).umount(this.mountRoot)}catch{}}}}readDirSync(e){let t=s(e);if(this.findMount(t))return null;let n=this.lfsSync;if(typeof n.readdirSync!=`function`||typeof n.lstatSync!=`function`)return null;try{let e=n.readdirSync(t),r=[];for(let i of e){let e=t===`/`?`/${i}`:`${t}/${i}`;try{let t=n.lstatSync(e),a=t.isSymbolicLink()?`symlink`:t.isDirectory()?`directory`:`file`;r.push({name:i,type:a})}catch{}}return r}catch{return null}}statSync(e){let t=s(e);if(this.findMount(t))return null;let n=this.lfsSync;if(typeof n.statSync!=`function`||typeof n.lstatSync!=`function`||typeof n.readlinkSync!=`function`)return null;if(t===`/`)try{let e=n.statSync(t);return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,ino:e.ino}}catch{return null}let r=t;for(let e=0;e<=10;e++){let e;try{e=n.lstatSync(r)}catch{return null}if(!e.isSymbolicLink())return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,ino:e.ino};let t;try{t=n.readlinkSync(r)}catch{return null}r=t.startsWith(`/`)?s(t):s(l(a(r).dir,t))}return null}lstatSync(e){let t=s(e);if(this.findMount(t))return null;let n=this.lfsSync;if(typeof n.lstatSync!=`function`)return null;if(t===`/`)return this.statSync(t);try{let e=n.lstatSync(t);if(e.isSymbolicLink()){let r=n.readlinkSync?n.readlinkSync(t):``;return{type:`symlink`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,isSymlink:!0,symlinkTarget:r,ino:e.ino}}return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,ino:e.ino}}catch{return null}}async mount(e,t,n){let r=s(e);if(this.mountPoints.has(r))throw new u(`EEXIST`,`mount point is already mounted`,r);try{if((await this.lstat(r)).type!==`directory`)throw new u(`ENOTDIR`,`mount point must be a directory`,r);if((await this.readDir(r)).length>0)throw new u(`ENOTEMPTY`,`mount point must be empty to avoid shadowing existing files`,r)}catch(e){if(!(e instanceof u)||e.code!==`ENOENT`)throw e}let{dir:i}=a(r);i!==`/`&&await this.mkdir(i,{recursive:!0});try{await this.lfs.mkdir(r)}catch{}if(this.mountPoints.set(r,t),t.kind===`local`){let e=n?.limits??T(n?.env??{});this.mountIndex.registerMount(r,t.getHandle(),e)}let o=Me(t,r);try{this.mountSyncChannel?.postMessage({type:`mount`,path:r,descriptor:o})}catch{}if(this.watcher?.notify([{type:`modify`,path:r,entryType:`directory`}]),t.kind!==`hostfs`)try{let e={targetPath:r,descriptor:o,createdAt:Date.now()},n=t.kind===`local`?t.getHandle():void 0;await ne(e,n)}catch{}}async unmount(e){let t=s(e),n=this.mountPoints.get(t);this.mountPoints.delete(t),this.mountIndex.unregisterMount(t);try{this.mountSyncChannel?.postMessage({type:`unmount`,path:t})}catch{}this.watcher?.notify([{type:`modify`,path:t,entryType:`directory`}]),await n?.close();try{await re(t)}catch{}}async reconstructBackendFromDescriptor(e,n){switch(e.kind){case`local`:{let t=await ie(e.idbHandleKey);if(!t)throw Error(`no handle stored for ${e.idbHandleKey}`);return V.fromHandle(t,{mountId:e.mountId})}case`hostfs`:{let{HostFsMountBackend:r}=await t(async()=>{let{HostFsMountBackend:e}=await import(`./backend-hostfs-Com-zF5W.js`);return{HostFsMountBackend:e}},__vite__mapDeps([4,5,6]));return new r({targetPath:n,hostPath:e.hostPath,mountId:e.mountId})}case`s3`:{let{S3MountBackend:n,RemoteMountCache:r,makeSignedFetchS3:i}=await t(async()=>{let{S3MountBackend:e,RemoteMountCache:t,makeSignedFetchS3:n}=await import(`./mount-DPQd6tzy.js`);return{S3MountBackend:e,RemoteMountCache:t,makeSignedFetchS3:n}},__vite__mapDeps([7,8,9,10,11,12,5,13,6,14,1,15,16,17,18,19])),a=new r({mountId:e.mountId,ttlMs:3e4});return new n({source:e.source,profile:e.profile,cache:a,mountId:e.mountId,signedFetch:i(e.profile)})}case`da`:{let{DaMountBackend:n,RemoteMountCache:r,makeSignedFetchDa:i}=await t(async()=>{let{DaMountBackend:e,RemoteMountCache:t,makeSignedFetchDa:n}=await import(`./mount-DPQd6tzy.js`);return{DaMountBackend:e,RemoteMountCache:t,makeSignedFetchDa:n}},__vite__mapDeps([7,8,9,10,11,12,5,13,6,14,1,15,16,17,18,19])),a=new r({mountId:e.mountId,ttlMs:3e4});return new n({source:e.source,profile:e.profile,cache:a,mountId:e.mountId,signedFetch:i()})}case`aem`:{let{AemMountBackend:n,RemoteMountCache:r,makeSignedFetchDa:i}=await t(async()=>{let{AemMountBackend:e,RemoteMountCache:t,makeSignedFetchDa:n}=await import(`./mount-DPQd6tzy.js`);return{AemMountBackend:e,RemoteMountCache:t,makeSignedFetchDa:n}},__vite__mapDeps([7,8,9,10,11,12,5,13,6,14,1,15,16,17,18,19])),a=new r({mountId:e.mountId,ttlMs:3e4});return new n({source:e.source,profile:e.profile,cache:a,mountId:e.mountId,signedFetch:i()})}}}listMounts(){let e=[];for(let t of this.mountPoints.keys())this.internalMounts.has(t)||e.push(t);return e}listInternalMounts(){return[...this.internalMounts]}listMountPoints(){let e=[];for(let[t,n]of this.mountPoints)this.internalMounts.has(t)||e.push({path:t,kind:n.kind});return e}async mountInternal(e,t){let n=s(e);if(this.mountPoints.has(n))throw new u(`EEXIST`,`mount point is already mounted`,n);let{dir:r}=a(n);r!==`/`&&await this.mkdir(r,{recursive:!0});try{await this.lfs.mkdir(n)}catch{}this.mountPoints.set(n,t),this.internalMounts.add(n),this.watcher?.notify([{type:`modify`,path:n,entryType:`directory`}])}async unmountInternal(e){let t=s(e);if(!this.internalMounts.has(t))throw new u(`ENOENT`,`not an internal mount point`,t);let n=this.mountPoints.get(t);this.mountPoints.delete(t),this.internalMounts.delete(t),this.watcher?.notify([{type:`modify`,path:t,entryType:`directory`}]),await n?.close()}getMountIndex(){return this.mountIndex}async refreshMount(e,t){let n=s(e),r=this.mountPoints.get(n);if(!r)throw new u(`ENOENT`,`not a mount point`,n);let i=await r.refresh(t);return r.kind===`local`&&await this.mountIndex.refreshMount(n,T(t?.env??{})),this.watcher?.notify([{type:`modify`,path:n,entryType:`directory`}]),i}isPathUnderMount(e){for(let t of this.mountPoints.keys())if(e===t||e.startsWith(t+`/`))return!0;return!1}findMount(e){let t=null;for(let[n,r]of this.mountPoints)(e===n||e.startsWith(n+`/`))&&(!t||n.length>t.mountPath.length)&&(t={mountPath:n,backend:r});return t?e===t.mountPath?{path:t.mountPath,backend:t.backend,relParts:[]}:{path:t.mountPath,backend:t.backend,relParts:e.slice(t.mountPath.length+1).split(`/`).filter(Boolean)}:null}async readFile(e,t){return this.withKindMismatchRetry(e,()=>this.readFileInner(e,t))}async readFileInner(e,t){let n=s(e),r=this.findMount(n);if(r){if(r.relParts.length===0)throw new u(`EISDIR`,`is a directory`,n);let e=r.relParts.join(`/`);try{let n=await r.backend.readFile(e);return(t?.encoding??`utf-8`)===`utf-8`?new TextDecoder(`utf-8`).decode(n):n}catch(e){M(e,n)}}let i=await this.resolveSymlinks(n);try{return(t?.encoding??`utf-8`)===`utf-8`?await this.lfs.readFile(i,{encoding:`utf8`}):await this.lfs.readFile(i)}catch(e){throw N(e,n)}}async writeFile(e,t,n){return this.withKindMismatchRetry(e,()=>this.writeFileInner(e,t,n))}async writeFileInner(e,t,n){let r=s(e),i=this.findMount(r);if(i){if(i.relParts.length===0)throw new u(`EISDIR`,`is a directory`,r);let e=i.relParts.join(`/`),n=!1;try{await this.stat(r),n=!0}catch{}let a=typeof t==`string`?new TextEncoder().encode(t):t instanceof Uint8Array?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):new Uint8Array(t);try{await i.backend.writeFile(e,a)}catch(e){M(e,r)}this.watcher?.notify([{type:n?`modify`:`create`,path:r,entryType:`file`}]),this.mountIndex.notifyWrite(r);return}let o;try{o=await this.resolveSymlinks(r)}catch{o=r}let c=!1;try{await this.lfs.stat(o),c=!0}catch{}let{dir:l}=a(o);await this.withWriteLock(async()=>{this.markSidecarDirty(o),l!==`/`&&await this.mkdirRecursiveUnlocked(l);let e=typeof t==`string`?new TextEncoder().encode(t).byteLength:(t instanceof Uint8Array,t.byteLength);try{await this.lfs.writeFile(o,t)}catch(e){if(l!==`/`&&e instanceof Error&&e.message.includes(`ENOENT`)){await this.mkdirRecursiveUnlocked(l);try{await this.lfs.writeFile(o,t)}catch(e){throw N(e,r)}}else throw N(e,r)}try{await this.lfs.truncate?.(o,e)}catch(e){throw N(e,r)}}),this.watcher?.notify([{type:c?`modify`:`create`,path:o,entryType:`file`}])}async readDir(e){let t=s(e),n=this.findMount(t);return n?this.readDirMounted(t,n):this.readDirLocal(t)}async readDirMounted(e,t){let n=this.mountIndex.getDirectoryEntries(t.path,e);if(n!==void 0){let t=new Map;for(let e of n)t.set(e.name,{name:e.name,type:e.type});return this.addNestedMountEntries(t,e),[...t.values()]}let r=t.relParts.join(`/`)||`/`,i;try{i=await t.backend.readDir(r)}catch(t){M(t,e)}let a=new Map;for(let e of i)a.set(e.name,{name:e.name,type:e.kind===`directory`?`directory`:`file`});return this.addNestedMountEntries(a,e),[...a.values()]}async readDirLocal(e){return this.withKindMismatchRetry(e,()=>this.readDirLocalInner(e))}async readDirLocalInner(e){let t=await this.resolveSymlinks(e);try{let e=await this.lfs.readdir(t),n=[];for(let r of e){let e=await this.statDirEntry(t,r);e&&n.push(e)}return n}catch(t){throw N(t,e)}}async statDirEntry(e,t){let n=e===`/`?`/${t}`:`${e}/${t}`;try{let e=await this.lfs.lstat(n);return e.isSymbolicLink()?{name:t,type:`symlink`}:{name:t,type:e.isDirectory()?`directory`:`file`}}catch{return null}}addNestedMountEntries(e,t){let n=t===`/`?`/`:`${t}/`;for(let r of this.mountPoints.keys()){if(r===t||!r.startsWith(n))continue;let i=r.slice(n.length);!i||i.includes(`/`)||e.has(i)||e.set(i,{name:i,type:`directory`})}}async withWriteLock(t){let n=this.dbName,r,i=new Promise(e=>{r=e}),a=e.writeChains.get(n)??Promise.resolve();e.writeChains.set(n,i),await a;try{let e=globalThis.navigator?.locks;return this.backend!==`opfs`||typeof e?.request!=`function`?await t():await e.request(`slicc-vfs:${n}`,()=>t())}finally{r(),e.writeChains.get(n)===i&&e.writeChains.delete(n)}}async mkdirRecursiveUnlocked(e){let t=e.split(`/`).filter(Boolean),n=[],r=``;for(let e of t){r+=`/`+e;try{await this.lfs.mkdir(r),n.push(r)}catch(e){if(e instanceof Error&&!e.message.includes(`EEXIST`))throw N(e,r);try{let e=await this.lfs.lstat(r);if(!e.isDirectory()&&!e.isSymbolicLink())throw new u(`ENOTDIR`,`not a directory`,r)}catch(e){if(e instanceof u&&e.code===`ENOTDIR`)throw e}}}return n}async mkdir(e,t){let n=s(e);if(n===`/`)return;let r=this.findMount(n);if(r){if(r.relParts.length===0)return;let e=r.relParts.join(`/`),t=await this.exists(n);try{await r.backend.mkdir(e)}catch(e){M(e,n)}t||this.watcher?.notify([{type:`create`,path:n,entryType:`directory`}]);return}if(t?.recursive){let e=await this.withWriteLock(()=>(this.markSidecarDirty(n),this.mkdirRecursiveUnlocked(n)));e.length>0&&this.watcher?.notify(e.map(e=>({type:`create`,path:e,entryType:`directory`})))}else await this.withWriteLock(async()=>{this.markSidecarDirty(n);try{await this.lfs.mkdir(n)}catch(e){throw N(e,n)}}),this.watcher?.notify([{type:`create`,path:n,entryType:`directory`}])}async rm(e,t){return this.withKindMismatchRetry(s(e),()=>this.rmInner(e,t))}async rmInner(e,t){let n=s(e),r=this.findMount(n);if(r){if(r.relParts.length===0)throw new u(`EINVAL`,`cannot remove a mount point — use unmount`,n);let e;try{e=(await this.stat(n)).type}catch{}let i=r.relParts.join(`/`);try{await r.backend.remove(i,{recursive:t?.recursive})}catch(e){M(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 N(e,n)}this.watcher?.notify([{type:`delete`,path:n}])}async rmRecursiveUnlocked(e){let t=await this.lfs.readdir(e);for(let n of t){let t=e===`/`?`/${n}`:`${e}/${n}`,r=await this.lfs.lstat(t);r.isSymbolicLink()?await this.lfs.unlink(t):r.isDirectory()?await this.rmRecursiveUnlocked(t):await this.lfs.unlink(t)}await this.lfs.rmdir(e)}async stat(e){return this.withKindMismatchRetry(e,()=>this.statInner(e))}async statInner(e){let t=s(e),n=this.findMount(t);if(n){if(n.relParts.length===0)try{let e=await this.lfs.stat(t);return{type:`directory`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs}}catch{return{type:`directory`,size:0,mtime:Date.now(),ctime:Date.now()}}let e=n.relParts.join(`/`);try{let t=await n.backend.stat(e);return{type:t.kind===`directory`?`directory`:`file`,size:t.size,mtime:t.mtime,ctime:t.mtime}}catch(e){M(e,t)}}let r=await this.resolveSymlinks(t);try{let e=await this.lfs.stat(r);return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,ino:e.ino}}catch(e){throw N(e,t)}}async exists(e){let t=s(e),n=this.findMount(t);if(n){if(n.relParts.length===0)return!0;try{return await this.stat(t),!0}catch{return!1}}try{return await this.stat(t),!0}catch{try{return await this.lfs.lstat(t),!0}catch{return!1}}}async rename(e,t){return this.withKindMismatchRetryPaths([s(e),s(t)],()=>this.renameInner(e,t))}async renameInner(e,t){let n=s(e),r=s(t),i;try{i=(await this.lstat(n)).type}catch{}let a=this.findMount(n);if(a?.backend.rename){let e=this.findMount(r);if(e&&e.backend===a.backend){try{await a.backend.rename(a.relParts.join(`/`),e.relParts.join(`/`))}catch(e){M(e,n)}this.watcher?.notify([{type:`delete`,path:n,entryType:i},{type:`create`,path:r,entryType:i}]),this.mountIndex.notifyRename(n,r);return}}try{await this.withWriteLock(async()=>{this.markSidecarDirty(n,`prefix`),this.markSidecarDirty(r,`prefix`),await this.lfs.rename(n,r),await this.writeOpfsMetadataSidecarUnlocked()})}catch(e){throw N(e,n)}this.watcher?.notify([{type:`delete`,path:n,entryType:i},{type:`create`,path:r,entryType:i}]),this.mountIndex.notifyRename(n,r)}async readTextFile(e){return await this.readFile(e,{encoding:`utf-8`})}async*walk(e,t,n=0){yield*X({mountPoints:this.mountPoints,mountIndex:this.mountIndex,realpath:e=>this.realpath(e),readDir:e=>this.readDir(e),stat:e=>this.stat(e)},e,t,n)}async copyFile(e,t){if((await this.stat(e)).type===`directory`)throw new u(`EISDIR`,`is a directory`,e);let n=await this.readFile(e,{encoding:`binary`});await this.writeFile(t,n)}dirname(e){return a(s(e)).dir}basename(e){return a(s(e)).base}async symlink(e,t){let n=s(t);if(this.findMount(n))throw new u(`EINVAL`,`symlinks not supported on mounted filesystems`,n);let{dir:r}=a(n);await this.withWriteLock(async()=>{r!==`/`&&await this.mkdirRecursiveUnlocked(r);try{await this.lfs.symlink(e,n)}catch(t){if(r!==`/`&&t instanceof Error&&t.message.includes(`ENOENT`)){await this.mkdirRecursiveUnlocked(r);try{await this.lfs.symlink(e,n)}catch(e){throw N(e,n)}}else throw N(t,n)}this.markSidecarDirty(n),await this.writeOpfsMetadataSidecarUnlocked()}),this.watcher?.notify([{type:`create`,path:n,entryType:`symlink`}])}async readlink(e){let t=s(e);try{return await this.lfs.readlink(t)}catch(e){throw N(e,t)}}async lstat(e){let t=s(e);if(this.findMount(t)||t===`/`)return this.stat(t);try{let e=await this.lfs.lstat(t);if(e.isSymbolicLink()){let n=await this.lfs.readlink(t);return{type:`symlink`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,isSymlink:!0,symlinkTarget:n,ino:e.ino}}return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,ino:e.ino}}catch(e){throw N(e,t)}}async realpath(e){return Y(this.lfs,e=>this.findMount(e)!==null,e)}resolveSymlinks(e){return Oe(this.lfs,e=>this.findMount(e)!==null,e)}},Ne=e({FsError:()=>u,FsWatcher:()=>g,MountIndex:()=>E,RestrictedFS:()=>j,VirtualFS:()=>$,joinPath:()=>l,normalizePath:()=>s,pathSegments:()=>o,resolveVfsBackendFromEnv:()=>Q,splitPath:()=>a});export{u as FsError,g as FsWatcher,E as MountIndex,j as RestrictedFS,$ as VirtualFS,Ce as a,K as i,l as joinPath,J as n,s as normalizePath,V as o,o as pathSegments,we as r,Q as resolveVfsBackendFromEnv,a as splitPath,Ne as t};
@@ -1 +1 @@
1
- import{n as e}from"./rolldown-runtime-Dd_uD5pT.js";import{t}from"./logger-LESFN7Hj.js";import{a as n,i as r,n as i,r as a,t as o}from"./path-utils-DNJG-zQf.js";import{t as s}from"./backend-local-_o3dnerJ.js";import{t as c}from"./types-idfTVsM8.js";import{a as l,i as u,n as d,t as f}from"./mount-table-store-DrF_Ifaz.js";import{r as p,t as m}from"./mount-index-CD1UKs2l.js";import{n as h,t as g}from"./virtual-device-paths-CS5o4QVz.js";import{i as _,r as v,t as y}from"./sidecar-repair-CIHuOk7H.js";const b=t(`fs-watcher`);let x=0;function S(e,t){return t===`/`||e===t||e.startsWith(t+`/`)}var C=class{registrations=new Map;watch(e,t,n){let r=`fsw-${++x}`;return this.registrations.set(r,{id:r,basePath:e,filter:t,callback:n}),b.debug(`Watch registered`,{id:r,basePath:e}),()=>{this.registrations.delete(r),b.debug(`Watch unregistered`,{id:r})}}notify(e){if(e.length!==0)for(let[,t]of this.registrations){let n=e.filter(e=>S(e.path,t.basePath)&&t.filter(e.path));if(n.length>0)try{t.callback(n)}catch(e){b.error(`Watch callback error`,{id:t.id,error:e instanceof Error?e.message:String(e)})}}}dispose(){this.registrations.clear(),b.debug(`All watchers disposed`)}get size(){return this.registrations.size}};const w=new TextEncoder,T=new TextDecoder(`utf-8`,{fatal:!1});var E=class{entries=new Map;static handles(e){return h(i(e))}has(e){return this.entries.has(i(e))}write(e,t){let n=i(e),r=typeof t==`string`?w.encode(t):new Uint8Array(t),a=Date.now(),o=this.entries.get(n);this.entries.set(n,{bytes:r,mtime:a,ctime:o?.ctime??a})}read(e,t){let n=this.require(e);return(t?.encoding??`utf-8`)===`utf-8`?T.decode(n.bytes):new Uint8Array(n.bytes)}readText(e){return T.decode(this.require(e).bytes)}stat(e){let t=this.require(e);return{type:`file`,size:t.bytes.length,mtime:t.mtime,ctime:t.ctime}}remove(e){return this.entries.delete(i(e))}require(e){let t=i(e),n=this.entries.get(t);if(!n)throw new c(`ENOENT`,`no such file or directory`,t);return n}};const D={[g]:{stat:()=>({type:`file`,size:0,mtime:0,ctime:0}),read:e=>(e?.encoding??`utf-8`)===`utf-8`?``:new Uint8Array,readText:()=>``,write:()=>{}}},O=[`/tmp/`];var k=class{ephemeralFds=new E;vfs;allowedPrefixes;readOnlyPrefixes;readGrantPatterns=[];writeEnforcement;constructor(e,t,n=[],r=`hard`){this.vfs=e;let a=e=>{let t=i(e);return t.endsWith(`/`)?t:t+`/`};this.allowedPrefixes=t.map(a),this.readOnlyPrefixes=n.map(a),this.writeEnforcement=r}getAllPrefixes(){let e=this.vfs.listMounts().map(e=>e.endsWith(`/`)?e:e+`/`);return[...this.allowedPrefixes,...this.readOnlyPrefixes,...e,...O]}setReadGrants(e){this.readGrantPatterns=[];for(let t of new Set(e))this.addReadGrant(t)}addReadGrant(e){let t=e.split(`/`),n=[];for(let e=1;e<t.length;e++)n.push(a(t.slice(0,e).join(`/`)||`/`));this.readGrantPatterns.push({pattern:e,regex:a(e),ancestorRegexes:n})}matchesReadGrant(e){return this.readGrantPatterns.some(t=>t.regex.test(e))}leadsToReadGrant(e){return this.readGrantPatterns.some(t=>t.ancestorRegexes.some(t=>t.test(e)))}isAllowed(e){let t=i(e),n=this.getAllPrefixes();return this.matchesReadGrant(t)||this.leadsToReadGrant(t)||n.some(e=>t===e.slice(0,-1)||t.startsWith(e)||t===`/`||e.startsWith(t+`/`))}isAllowedStrict(e){let t=i(e),n=this.getAllPrefixes();return this.matchesReadGrant(t)||n.some(e=>t===e.slice(0,-1)||t.startsWith(e))}isWritable(e){let t=i(e);return[...this.allowedPrefixes,...O].some(e=>t===e.slice(0,-1)||t.startsWith(e))}canWrite(e){return E.handles(e)||this.isWritable(e)}checkWrite(e){if(this.writeEnforcement!==`sudo-delegated`&&!this.isWritable(e))throw new c(`EACCES`,`permission denied`,i(e))}async resolveAndCheckRead(e){try{let t=await this.vfs.realpath(e);if(!this.isAllowedStrict(t))throw new c(`ENOENT`,`no such file or directory`,i(e));return t}catch(t){throw t instanceof c?t:new c(`ENOENT`,`no such file or directory`,i(e))}}async resolveAndCheckWrite(e){try{let t=await this.vfs.realpath(e);if(!this.isWritable(t)&&!this.isSymlinkEscapeAllowed(t))throw new c(`EACCES`,`permission denied`,i(e));return t}catch(t){throw t instanceof c?t:new c(`EACCES`,`permission denied`,i(e))}}isSymlinkEscapeAllowed(e){return!1}async checkParentRealpathEscape(e){let t=this.vfs.dirname(e),n=this.vfs.basename(e),r;try{r=await this.vfs.realpath(t)}catch(e){if(e instanceof c&&e.code===`EACCES`)throw e;return}let a=r+`/`+n;if(this.isWritable(a))return;let o=i(r)!==i(t);if(!(this.writeEnforcement===`sudo-delegated`&&!o))throw new c(`EACCES`,`permission denied`,i(e))}getUnderlyingFS(){return this.vfs}invalidatePaths(e){this.vfs.invalidatePaths(e)}async flush(){await this.vfs.flush()}isPathUnderMount(e){return this.vfs.isPathUnderMount(e)}async readFile(e,t){let n=D[i(e)];if(n)return n.read(t);if(E.handles(e))return this.ephemeralFds.read(e,t);if(!this.isAllowedStrict(e))throw new c(`ENOENT`,`no such file or directory`,i(e));let r=await this.resolveAndCheckRead(e);return this.vfs.readFile(r,t)}async readDir(e){if(!this.isAllowed(e))return[];let t=e;if(this.isAllowedStrict(e))try{t=await this.resolveAndCheckRead(e)}catch{return[]}let n=await this.vfs.readDir(t);if(!this.isAllowedStrict(e)){let t=i(e);return n.filter(e=>{let n=t===`/`?`/${e.name}`:`${t}/${e.name}`;return this.isAllowed(n)})}return n}async stat(e){let t=D[i(e)];if(t)return t.stat();if(E.handles(e))return this.ephemeralFds.stat(e);if(!this.isAllowed(e))throw new c(`ENOENT`,`no such file or directory`,i(e));if(this.isAllowedStrict(e)){let t=await this.resolveAndCheckRead(e);return this.vfs.stat(t)}return this.vfs.stat(e)}scanPathForSymlinks(e,t){let n=i(e);if(n===`/`)return!1;let r=n.slice(1).split(`/`),a=t?r.length:r.length-1,o=``;for(let e=0;e<a;e++){o=o+`/`+r[e];let t=this.vfs.lstatSync(o);if(t===null)return null;if(t.type===`symlink`)return!0}return!1}statSync(e){let t=D[i(e)];return t?t.stat():E.handles(e)?this.ephemeralFds.has(e)?this.ephemeralFds.stat(e):null:!this.isAllowedStrict(e)||this.scanPathForSymlinks(e,!0)!==!1?null:this.vfs.statSync(e)}lstatSync(e){let t=D[i(e)];return t?t.stat():E.handles(e)?this.ephemeralFds.has(e)?this.ephemeralFds.stat(e):null:!this.isAllowed(e)||this.scanPathForSymlinks(e,!1)!==!1?null:this.vfs.lstatSync(e)}readDirSync(e){if(!this.isAllowed(e)||this.scanPathForSymlinks(e,!0)!==!1)return null;let t=this.vfs.readDirSync(e);if(t===null)return null;if(this.isAllowedStrict(e))return t;let n=i(e);return t.filter(e=>{let t=n===`/`?`/${e.name}`:`${n}/${e.name}`;return this.isAllowed(t)})}async realpath(e){if(E.handles(e)){let t=i(e);if(!this.ephemeralFds.has(t))throw new c(`ENOENT`,`no such file or directory`,t);return t}let t;try{t=await this.vfs.realpath(e)}catch(t){throw t instanceof c?t:new c(`ENOENT`,`no such file or directory`,i(e))}if(!this.isAllowedStrict(t))throw new c(`ENOENT`,`no such file or directory`,i(e));return t}async exists(e){if(D[i(e)])return!0;if(E.handles(e))return this.ephemeralFds.has(e);if(!this.isAllowed(e))return!1;if(this.isAllowedStrict(e))try{await this.resolveAndCheckRead(e)}catch{return!1}return this.vfs.exists(e)}async readTextFile(e){let t=D[i(e)];if(t)return t.readText();if(E.handles(e))return this.ephemeralFds.readText(e);if(!this.isAllowedStrict(e))throw new c(`ENOENT`,`no such file or directory`,i(e));let n=await this.resolveAndCheckRead(e);return this.vfs.readTextFile(n)}async*walk(e){if(!this.isAllowed(e))return;let t=e;if(this.isAllowedStrict(e))try{t=await this.resolveAndCheckRead(e)}catch{return}for await(let e of this.vfs.walk(t))this.isAllowed(e)&&(yield e)}async writeFile(e,t,n){let r=D[i(e)];if(r){r.write(t);return}if(E.handles(e)){this.ephemeralFds.write(e,t);return}this.checkWrite(e),await this.checkParentRealpathEscape(e);try{(await this.vfs.lstat(e)).type===`symlink`&&await this.resolveAndCheckWrite(e)}catch(e){if(e instanceof c&&e.code===`EACCES`)throw e}return this.vfs.writeFile(e,t,n)}refuseDescriptorTreeOp(e){if(E.handles(e))throw new c(`EACCES`,`permission denied`,i(e))}async mkdir(e,t){return this.refuseDescriptorTreeOp(e),this.checkWrite(e),await this.checkParentRealpathEscape(e),this.vfs.mkdir(e,t)}async rm(e,t){if(E.handles(e)){if(!this.ephemeralFds.remove(e))throw new c(`ENOENT`,`no such file or directory`,i(e));return}this.checkWrite(e);try{(await this.vfs.lstat(e)).type===`symlink`||await this.resolveAndCheckWrite(e)}catch(e){if(e instanceof c&&e.code===`EACCES`)throw e}return this.vfs.rm(e,t)}async rename(e,t){return this.refuseDescriptorTreeOp(e),this.refuseDescriptorTreeOp(t),this.checkWrite(e),this.checkWrite(t),await this.resolveAndCheckWrite(e),await this.checkParentRealpathEscape(t),this.vfs.rename(e,t)}async copyFile(e,t){if(E.handles(e)){let n=this.ephemeralFds.read(e,{encoding:`binary`});await this.writeFile(t,n);return}if(E.handles(t)){if(!this.isAllowed(e))throw new c(`ENOENT`,`no such file or directory`,i(e));let n=await this.resolveAndCheckRead(e);this.ephemeralFds.write(t,await this.vfs.readFile(n,{encoding:`binary`}));return}if(!this.isAllowed(e))throw new c(`ENOENT`,`no such file or directory`,i(e));this.checkWrite(t);let n=await this.resolveAndCheckRead(e);await this.checkParentRealpathEscape(t);try{(await this.vfs.lstat(t)).type===`symlink`&&await this.resolveAndCheckWrite(t)}catch(e){if(e instanceof c&&e.code===`EACCES`)throw e}return this.vfs.copyFile(n,t)}async symlink(e,t){return this.refuseDescriptorTreeOp(t),this.checkWrite(t),await this.checkParentRealpathEscape(t),this.vfs.symlink(e,t)}async readlink(e){if(!this.isAllowedStrict(e))throw new c(`ENOENT`,`no such file or directory`,i(e));let t=await this.vfs.readlink(e),n;if(t.startsWith(`/`))n=i(t);else{let r=this.vfs.dirname(e);n=i(r+`/`+t)}if(!this.isAllowedStrict(n))throw new c(`ENOENT`,`no such file or directory`,i(e));return t}async lstat(e){let t=D[i(e)];if(t)return t.stat();if(E.handles(e))return this.ephemeralFds.stat(e);if(!this.isAllowed(e))throw new c(`ENOENT`,`no such file or directory`,i(e));let n=i(e),r=this.vfs.dirname(n),a=this.vfs.basename(n),o;if(r===n)o=r;else try{o=await this.vfs.realpath(r)}catch{throw new c(`ENOENT`,`no such file or directory`,n)}let s=o===`/`?`/${a}`:`${o}/${a}`;if(!this.isAllowed(s))throw new c(`ENOENT`,`no such file or directory`,n);return this.vfs.lstat(s)}watch(e,t,n){if(!this.isAllowed(e))throw new c(`EACCES`,`permission denied`,i(e));let r=this.vfs.getWatcher();if(!r)throw new c(`EINVAL`,`no watcher configured`);return r.watch(i(e),t,n)}dirname(e){return this.vfs.dirname(e)}basename(e){return this.vfs.basename(e)}async mount(e,t,n){return this.refuseDescriptorTreeOp(e),this.checkWrite(e),await this.checkParentRealpathEscape(e),this.vfs.mount(e,t,n)}async unmount(e){return this.refuseDescriptorTreeOp(e),this.checkWrite(e),await this.checkParentRealpathEscape(e),this.vfs.unmount(e)}listMounts(){return this.vfs.listMounts()}getMountIndex(){return this.vfs.getMountIndex()}async refreshMount(e,t){return this.refuseDescriptorTreeOp(e),this.checkWrite(e),this.vfs.refreshMount(e,t)}async dispose(){await this.vfs.dispose()}};function A(e,t){if(e instanceof c){let n=`${e.code}: `,r=e.message;throw r.startsWith(n)&&(r=r.slice(n.length)),e.path&&r.endsWith(` '${e.path}'`)&&(r=r.slice(0,r.length-` '${e.path}'`.length)),new c(e.code,r,t)}throw e}const j=[`ENOENT`,`EEXIST`,`ENOTDIR`,`EISDIR`,`ENOTEMPTY`,`EINVAL`,`EACCES`,`ELOOP`,`EBUSY`,`EFBIG`,`EBADF`,`ENOSYS`,`EIO`];function M(e,t){if(e instanceof c)return e;{let n=e instanceof Error?e.message:String(e);if(n.includes(`maximum size exceeded`)||n.includes(`call stack size exceeded`))return new c(`EIO`,`internal overflow, not storage: ${n} — reload the session`,t)}let n=e?.code;if(typeof n==`string`){let r=n;if(j.includes(r)){let n=e instanceof Error?e.message:String(e);return n.startsWith(`${r}: `)&&(n=n.slice(r.length+2),n=n.replace(/, undefined( '[^']*')?$/,``).replace(/ '[^']*'$/,``)),new c(r,n||r,t)}}let r=e instanceof Error?e.message:String(e);return r.includes(`ENOENT`)?new c(`ENOENT`,`no such file or directory`,t):r.includes(`EEXIST`)?new c(`EEXIST`,`file already exists`,t):r.includes(`ENOTDIR`)?new c(`ENOTDIR`,`not a directory`,t):r.includes(`EISDIR`)?new c(`EISDIR`,`is a directory`,t):r.includes(`ENOTEMPTY`)?new c(`ENOTEMPTY`,`directory not empty`,t):r.includes(`ELOOP`)?new c(`ELOOP`,`too many levels of symbolic links`,t):new c(`EINVAL`,r,t)}function N(e){return e===void 0?`absent`:(e&61440)==16384?`directory`:`file`}function P(e,t){return t===`absent`?!1:e.kind===`missing`||e.kind!==t}function F(e){let t=e?.mode;return typeof t==`number`?t:void 0}function I(e,t,n,r=new Set){let i=new Set(n);if(r.size>0){for(let t of Object.keys(e.entries??{}))for(let e of r)if(t===e||t.startsWith(`${e}/`)){i.add(t);break}}let a=[];for(let n of i){let r=e.entries?.[n],i=t.entries?.[n];if(!r||!i)continue;let o=N(F(r));o!==N(F(i))&&a.push({path:n,ownIsDirectory:o===`directory`})}return a}async function L(e,t,n,r){try{return await e.lstat(t)}catch(e){let t=M(e,r);if(t.code===`ENOENT`&&n)return null;throw t}}async function R(e,t,r){let a;try{a=await e.readlink(t)}catch(e){throw M(e,r)}return a.startsWith(`/`)?i(a):i(o(n(t).dir,a))}async function z(e,t,n,r,i,a){let o=t===`/`?`/${n}`:`${t}/${n}`;for(;;){let t=await L(e,o,r,i);if(t===null||!t.isSymbolicLink())return{resolved:o,hops:a};if(++a>10)throw new c(`ELOOP`,`too many symbolic links encountered`,i);o=await R(e,o,i)}}async function B(e,t,n){let r=i(n);if(t(r))return r;let a=r.split(`/`).filter(Boolean),o=`/`,s=0;for(let t=0;t<a.length;t++){let n=await z(e,o,a[t],t===a.length-1,r,s);o=n.resolved,s=n.hops}return o}async function V(e,t,n){return t(n)?n:B(e,t,n)}function H(e,t,n){return e.size===0||!e.has(n)||!t.isReady(n)?!1:!Array.from(e.keys()).some(e=>e!==n&&e.startsWith(n+`/`))}async function U(e,t){try{return await e(t)}catch{return t}}async function*W(e,t,n,r=0){let a=i(t);if(H(e.mountPoints,e.mountIndex,a)){let t=e.mountIndex.getFiles(a);if(t){for(let e of t)yield e;return}}let o=n??new Set;if(r>64||o.size>=1e5)return;let s=await U(t=>e.realpath(t),a);if(o.has(s))return;o.add(s);let c=await e.readDir(a);for(let t of c)yield*G(e,t,a===`/`?`/${t.name}`:`${a}/${t.name}`,o,r+1)}async function*G(e,t,n,r,i){if(t.type===`file`){yield n;return}if(t.type===`symlink`){yield*K(e,n,r,i);return}yield*W(e,n,r,i)}async function*K(e,t,n,r){try{let i=await e.stat(t);i.type===`file`?yield t:i.type===`directory`&&(yield*W(e,t,n,r))}catch{}}function q(){try{if(typeof globalThis.navigator?.storage?.getDirectory==`function`)return`opfs`}catch{}return`memory`}function J(e,t){switch(e.kind){case`local`:case`proc`:return{kind:`local`,mountId:e.mountId,idbHandleKey:t};case`hostfs`:return{kind:`hostfs`,mountId:e.mountId,hostPath:e.getHostPath()};default:return{kind:e.kind===`s3`?`s3`:e.kind===`aem`?`aem`:`da`,mountId:e.mountId,source:e.source,profile:e.profile??`default`}}}var Y=class e{lfs;lfsSync;rawLfs=null;rawLfsSync=null;_ready;_readyResolved=!1;backend;mountPoints=new Map;opfsBackendFs=null;opfsHandle=null;mountRoot=``;internalMounts=new Set;watcher=null;dbName;mountSyncChannel=null;mountIndex=new m;static writeChains=new Map;onRepairProgress;constructor(t,n,r,i,a){if(this.dbName=t,this.onRepairProgress=a,this.backend=r===`opfs`?`opfs`:`memory`,this.lfs=this.makeDeferredLfs(),this.lfsSync=this.makeDeferredLfsSync(),this._ready=this.backend===`opfs`?e.initOpfsBackend(this,i,n===!0):e.initMemoryBackend(this,t,n===!0),this._ready.then(()=>{this._readyResolved=!0},()=>{}),typeof BroadcastChannel<`u`)try{this.mountSyncChannel=new BroadcastChannel(`vfs-mount-sync:${t}`),this.mountSyncChannel.onmessage=e=>{let{type:t,path:n,descriptor:r}=e.data??{};if(t===`mount`&&typeof n==`string`&&r)this.reconstructBackendFromDescriptor(r,n).then(e=>{this.mountPoints.set(n,e),e.kind===`local`&&this.mountIndex.registerMount(n,e.getHandle()),this.watcher?.notify([{type:`modify`,path:n,entryType:`directory`}])}).catch(()=>{});else if(t===`unmount`&&typeof n==`string`){let e=this.mountPoints.get(n);this.mountPoints.delete(n),this.mountIndex.unregisterMount(n),e?.close(),this.watcher?.notify([{type:`modify`,path:n,entryType:`directory`}])}}}catch{}}static async initOpfsBackend(t,n,r){let i=n??await e.acquireOpfsHandle(t.dbName,r);await e.seedOpfsMetadataSidecarIfMissing(i);let[a,{WebAccess:o}]=await Promise.all([import(`./dist-CBELmDjr.js`).then(e=>e.t),import(`./dist-iMxkf8fm.js`)]);await e.ensureRootMount(a);let s=`/__opfs__/${t.dbName}`,c=e.opfsBackends.get(t.dbName);if(c&&r){try{a.umount(s)}catch{}e.opfsBackends.delete(t.dbName),c=void 0}if(!c){let n=()=>a.resolveMountConfig({backend:o,handle:i,metadata:`/.metadata.json`}),{resolveWithSidecarRepair:r,repairOpfsMetadataSidecar:l}=await import(`./sidecar-repair-CIHuOk7H.js`).then(e=>e.n);try{let e=await t.withWriteLock(()=>l(i,t.onRepairProgress));e?.changed&&console.warn(`[virtual-fs] repaired metadata sidecar before mount (#2146)`,{dbName:t.dbName,kindFixed:e.kindFixed,sizesFixed:e.sizesFixed,dropped:e.dropped,inosReassigned:e.inosReassigned,nlinksFixed:e.nlinksFixed,selfEntryDropped:e.selfEntryDropped})}catch{}let u=await r(n,()=>t.withWriteLock(()=>l(i,t.onRepairProgress)),e=>console.warn(`[virtual-fs] repaired poisoned metadata sidecar; retrying mount`,{dbName:t.dbName,kindFixed:e.kindFixed,sizesFixed:e.sizesFixed,dropped:e.dropped,nlinksFixed:e.nlinksFixed,selfEntryDropped:e.selfEntryDropped}));try{a.mount(s,u)}catch{}c={backendFs:u,refs:0,sidecarDirty:{paths:new Set,prefixes:new Set}},e.opfsBackends.set(t.dbName,c)}c.refs+=1,t.opfsBackendFs=c.backendFs.index?c.backendFs:null,t.opfsHandle=i,t.mountRoot=s,t.rawLfs=a.promises,t.rawLfsSync=a}static async initMemoryBackend(t,n,r){let i=await import(`./dist-CBELmDjr.js`).then(e=>e.t);await e.ensureRootMount(i);let a=`/__zenfs__/${n}`,o=e.memoryBackends.get(n);if(o&&r){try{i.umount(a)}catch{}e.memoryBackends.delete(n),o=void 0}o||(o={store:i.InMemory.create({label:n}),refs:0},e.memoryBackends.set(n,o)),o.refs+=1;try{i.mount(a,o.store)}catch{}t.mountRoot=a,t.rawLfs=i.promises,t.rawLfsSync=i,t.opfsBackendFs=null,t.opfsHandle=null}static rootMountReady=null;static memoryBackends=new Map;static opfsBackends=new Map;static async ensureRootMount(t){return e.rootMountReady===null&&(e.rootMountReady=(async()=>{await t.configureSingle({backend:t.InMemory,label:`__vfs_root__`})})()),e.rootMountReady}prefix(e){return this.mountRoot?e===`/`?this.mountRoot:this.mountRoot+e:e}unprefix(e){return!this.mountRoot||!e.startsWith(this.mountRoot)?e:e.slice(this.mountRoot.length)||`/`}makeDeferredLfs(){let e=e=>this.prefix(e),t=e=>this.unprefix(e),n=()=>{if(!this.rawLfs)throw Error(`VirtualFS used before init resolved`);return this.rawLfs};return{readFile:(t,r)=>this._readyResolved?n().readFile(e(t),r):this._ready.then(()=>n().readFile(e(t),r)),writeFile:(t,r,i)=>this._readyResolved?n().writeFile(e(t),r,i):this._ready.then(()=>n().writeFile(e(t),r,i)),readdir:t=>this._readyResolved?n().readdir(e(t)):this._ready.then(()=>n().readdir(e(t))),mkdir:(t,r)=>this._readyResolved?n().mkdir(e(t),r):this._ready.then(()=>n().mkdir(e(t),r)),rmdir:t=>this._readyResolved?n().rmdir(e(t)):this._ready.then(()=>n().rmdir(e(t))),unlink:t=>this._readyResolved?n().unlink(e(t)):this._ready.then(()=>n().unlink(e(t))),rename:(t,r)=>this._readyResolved?n().rename(e(t),e(r)):this._ready.then(()=>n().rename(e(t),e(r))),stat:t=>this._readyResolved?n().stat(e(t)):this._ready.then(()=>n().stat(e(t))),lstat:t=>this._readyResolved?n().lstat(e(t)):this._ready.then(()=>n().lstat(e(t))),symlink:(t,r)=>{let i=t.startsWith(`/`)?e(t):t;return this._readyResolved?n().symlink(i,e(r)):this._ready.then(()=>n().symlink(i,e(r)))},readlink:async r=>(this._readyResolved||await this._ready,t(await n().readlink(e(r)))),truncate:async(t,r)=>{this._readyResolved||await this._ready;let i=n();typeof i.truncate==`function`&&await i.truncate(e(t),r)},realpath:async r=>{this._readyResolved||await this._ready;let i=n();return typeof i.realpath==`function`?t(await i.realpath(e(r))):e(r)}}}makeDeferredLfsSync(){let e=e=>this.prefix(e),t=e=>this.unprefix(e);return{readdirSync:t=>{let n=this.rawLfsSync;return n?.readdirSync?n.readdirSync(e(t)):void 0},statSync:t=>{let n=this.rawLfsSync;return n?.statSync?n.statSync(e(t)):void 0},lstatSync:t=>{let n=this.rawLfsSync;return n?.lstatSync?n.lstatSync(e(t)):void 0},readlinkSync:n=>{let r=this.rawLfsSync;return r?.readlinkSync?t(r.readlinkSync(e(n))):void 0}}}static async seedOpfsMetadataSidecarIfMissing(e){let t=`.metadata.json`;try{await e.getFileHandle(t);return}catch(e){if(e?.name!==`NotFoundError`)throw e}let n=await(await e.getFileHandle(t,{create:!0})).createWritable(),r=JSON.stringify({version:1,maxSize:4294967295,entries:{}});await n.write(r),await n.close()}static async acquireOpfsHandle(e,t){let n=navigator.storage;if(!n?.getDirectory)throw new c(`EINVAL`,`OPFS is not available in this environment`);let r=await n.getDirectory();if(t)try{await r.removeEntry(e,{recursive:!0})}catch{}return r.getDirectoryHandle(e,{create:!0})}static _createSyncForTests(t){return new e(t)}static async create(t){let n=t?.dbName??`browser-fs`,r=t?.wipe===!0,i=t?.backend??q(),a=new e(n,r,i,void 0,t?.onRepairProgress);return await a._ready,r&&await f().catch(()=>{}),a}async flush(){await this.writeOpfsMetadataSidecar()}async writeOpfsMetadataSidecar(){this.backend===`opfs`&&await this.withWriteLock(()=>this.writeOpfsMetadataSidecarUnlocked())}async writeOpfsMetadataSidecarUnlocked(){if(this.backend!==`opfs`)return;let t=this.opfsBackendFs,n=this.opfsHandle;if(!t||!n)return;let r=t.index.toJSON(),i=e.opfsBackends.get(this.dbName)?.sidecarDirty,a=r;if(i){let e=null;try{let t=await n.getFileHandle(`.metadata.json`),r=JSON.parse(await(await t.getFile()).text());r&&typeof r==`object`&&r.entries&&(e=r)}catch{}e&&(await this.auditDirtyKindFlips(r,e,i,n),a=v(e,r,i))}let o=JSON.stringify(_(a)),s=await(await n.getFileHandle(`.metadata.json`,{create:!0})).createWritable();await s.write(o),await s.close(),i&&(i.paths.clear(),i.prefixes.clear())}async auditDirtyKindFlips(e,t,n,r){let i=I(e,t,n.paths,n.prefixes);if(i.length===0)return;let a=y(r),o=this.opfsBackendFs;for(let n of i){let r=await a(n.path).catch(()=>null);if(r!==null&&r.kind!==`missing`&&r.kind===`directory`===n.ownIsDirectory)continue;let i=t.entries?.[n.path];e.entries&&i!==void 0&&(e.entries[n.path]=i);let s=r!==null&&r.kind!==`missing`;s&&(o?.index?.delete(n.path),o?._handles?.delete(n.path)),console.warn(`[virtual-fs] refused to flush in-memory kind flip over sidecar record (#2006)`,{path:n.path,reality:r?.kind??`unverifiable`,evicted:s})}}markSidecarDirty(t,r=`path`){if(this.backend!==`opfs`)return;let a=e.opfsBackends.get(this.dbName)?.sidecarDirty;if(!a)return;let o=i(t);(r===`prefix`?a.prefixes:a.paths).add(o);let{dir:s}=n(o);for(;s!==`/`;)a.paths.add(s),s=n(s).dir}invalidatePaths(e){if(this.backend!==`opfs`||!this.opfsBackendFs)return;let t=this.opfsBackendFs;for(let n of e){let e=i(n);t.index.delete(e),t._handles?.delete(e),this.markSidecarDirty(e)}}async withKindMismatchRetry(e,t){return this.withKindMismatchRetryPaths([e],t)}async withKindMismatchRetryPaths(e,t){try{return await t()}catch(n){let r=n?.code;if(r!==`EISDIR`&&r!==`ENOTDIR`&&r!==`EINVAL`)throw n;for(let n of e)if(await this.reconcileKindMismatch(n).catch(()=>!1))return await t();throw n}}async reconcileKindMismatch(e){if(this.backend!==`opfs`)return!1;let t=this.opfsBackendFs,n=this.opfsHandle;if(!t?.index||!n)return!1;let r=i(e),a=r;try{a=await this.resolveSymlinks(r)}catch{}let o=await y(n)(a),s=N(t.index.get(a)?.mode),c=t._handles?.get(a),l=c?.kind===`directory`?`directory`:c?.kind===`file`?`file`:`absent`,u=P(o,s),d=P(o,l);if(!u&&!d)return!1;if(t.index.delete(a),t._handles?.delete(a),s===`directory`||l===`directory`){let e=`${a}/`;for(let n of[...t.index.keys()])n.startsWith(e)&&t.index.delete(n);if(t._handles)for(let n of[...t._handles.keys()])n.startsWith(e)&&t._handles.delete(n)}return this.markSidecarDirty(a),console.warn(`[virtual-fs] reconciled in-memory kind mismatch (#2006)`,{path:a,reality:o.kind,indexHeld:s,handleHeld:l}),!0}canWrite(e){return!0}setWatcher(e){this.watcher=e}getWatcher(){return this.watcher}async watch(e,t){let n=this.watcher;if(!n)throw new c(`ENOSYS`,`no FsWatcher attached to this VirtualFS`);let r=e.map(e=>n.watch(e,()=>!0,t));return()=>{for(let e of r)e()}}async dispose(){if(this.mountSyncChannel?.close(),this.mountSyncChannel=null,this.watcher?.dispose(),this.watcher=null,this.mountIndex.dispose(),await this.writeOpfsMetadataSidecar(),this.mountRoot){let t=this.backend===`opfs`?e.opfsBackends:e.memoryBackends,n=t.get(this.dbName);if(n&&(--n.refs,n.refs<=0)){t.delete(this.dbName);try{(await import(`./dist-CBELmDjr.js`).then(e=>e.t)).umount(this.mountRoot)}catch{}}}}readDirSync(e){let t=i(e);if(this.findMount(t))return null;let n=this.lfsSync;if(typeof n.readdirSync!=`function`||typeof n.lstatSync!=`function`)return null;try{let e=n.readdirSync(t),r=[];for(let i of e){let e=t===`/`?`/${i}`:`${t}/${i}`;try{let t=n.lstatSync(e),a=t.isSymbolicLink()?`symlink`:t.isDirectory()?`directory`:`file`;r.push({name:i,type:a})}catch{}}return r}catch{return null}}statSync(e){let t=i(e);if(this.findMount(t))return null;let r=this.lfsSync;if(typeof r.statSync!=`function`||typeof r.lstatSync!=`function`||typeof r.readlinkSync!=`function`)return null;if(t===`/`)try{let e=r.statSync(t);return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,ino:e.ino}}catch{return null}let a=t;for(let e=0;e<=10;e++){let e;try{e=r.lstatSync(a)}catch{return null}if(!e.isSymbolicLink())return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,ino:e.ino};let t;try{t=r.readlinkSync(a)}catch{return null}a=t.startsWith(`/`)?i(t):i(o(n(a).dir,t))}return null}lstatSync(e){let t=i(e);if(this.findMount(t))return null;let n=this.lfsSync;if(typeof n.lstatSync!=`function`)return null;if(t===`/`)return this.statSync(t);try{let e=n.lstatSync(t);if(e.isSymbolicLink()){let r=n.readlinkSync?n.readlinkSync(t):``;return{type:`symlink`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,isSymlink:!0,symlinkTarget:r,ino:e.ino}}return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,ino:e.ino}}catch{return null}}async mount(e,t,r){let a=i(e);if(this.mountPoints.has(a))throw new c(`EEXIST`,`mount point is already mounted`,a);try{if((await this.lstat(a)).type!==`directory`)throw new c(`ENOTDIR`,`mount point must be a directory`,a);if((await this.readDir(a)).length>0)throw new c(`ENOTEMPTY`,`mount point must be empty to avoid shadowing existing files`,a)}catch(e){if(!(e instanceof c)||e.code!==`ENOENT`)throw e}let{dir:o}=n(a);o!==`/`&&await this.mkdir(o,{recursive:!0});try{await this.lfs.mkdir(a)}catch{}if(this.mountPoints.set(a,t),t.kind===`local`){let e=r?.limits??p(r?.env??{});this.mountIndex.registerMount(a,t.getHandle(),e)}let s=J(t,a);try{this.mountSyncChannel?.postMessage({type:`mount`,path:a,descriptor:s})}catch{}if(this.watcher?.notify([{type:`modify`,path:a,entryType:`directory`}]),t.kind!==`hostfs`)try{let e={targetPath:a,descriptor:s,createdAt:Date.now()},n=t.kind===`local`?t.getHandle():void 0;await l(e,n)}catch{}}async unmount(e){let t=i(e),n=this.mountPoints.get(t);this.mountPoints.delete(t),this.mountIndex.unregisterMount(t);try{this.mountSyncChannel?.postMessage({type:`unmount`,path:t})}catch{}this.watcher?.notify([{type:`modify`,path:t,entryType:`directory`}]),await n?.close();try{await u(t)}catch{}}async reconstructBackendFromDescriptor(e,t){switch(e.kind){case`local`:{let t=await d(e.idbHandleKey);if(!t)throw Error(`no handle stored for ${e.idbHandleKey}`);return s.fromHandle(t,{mountId:e.mountId})}case`hostfs`:{let{HostFsMountBackend:n}=await import(`./backend-hostfs-bQQx-S0W.js`);return new n({targetPath:t,hostPath:e.hostPath,mountId:e.mountId})}case`s3`:{let{S3MountBackend:t,RemoteMountCache:n,makeSignedFetchS3:r}=await import(`./mount-BrQpW9eO.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-BrQpW9eO.js`).then(e=>e.t),i=new n({mountId:e.mountId,ttlMs:3e4});return new t({source:e.source,profile:e.profile,cache:i,mountId:e.mountId,signedFetch:r()})}case`aem`:{let{AemMountBackend:t,RemoteMountCache:n,makeSignedFetchDa:r}=await import(`./mount-BrQpW9eO.js`).then(e=>e.t),i=new n({mountId:e.mountId,ttlMs:3e4});return new t({source:e.source,profile:e.profile,cache:i,mountId:e.mountId,signedFetch:r()})}}}listMounts(){let e=[];for(let t of this.mountPoints.keys())this.internalMounts.has(t)||e.push(t);return e}listInternalMounts(){return[...this.internalMounts]}listMountPoints(){let e=[];for(let[t,n]of this.mountPoints)this.internalMounts.has(t)||e.push({path:t,kind:n.kind});return e}async mountInternal(e,t){let r=i(e);if(this.mountPoints.has(r))throw new c(`EEXIST`,`mount point is already mounted`,r);let{dir:a}=n(r);a!==`/`&&await this.mkdir(a,{recursive:!0});try{await this.lfs.mkdir(r)}catch{}this.mountPoints.set(r,t),this.internalMounts.add(r),this.watcher?.notify([{type:`modify`,path:r,entryType:`directory`}])}async unmountInternal(e){let t=i(e);if(!this.internalMounts.has(t))throw new c(`ENOENT`,`not an internal mount point`,t);let n=this.mountPoints.get(t);this.mountPoints.delete(t),this.internalMounts.delete(t),this.watcher?.notify([{type:`modify`,path:t,entryType:`directory`}]),await n?.close()}getMountIndex(){return this.mountIndex}async refreshMount(e,t){let n=i(e),r=this.mountPoints.get(n);if(!r)throw new c(`ENOENT`,`not a mount point`,n);let a=await r.refresh(t);return r.kind===`local`&&await this.mountIndex.refreshMount(n,p(t?.env??{})),this.watcher?.notify([{type:`modify`,path:n,entryType:`directory`}]),a}isPathUnderMount(e){for(let t of this.mountPoints.keys())if(e===t||e.startsWith(t+`/`))return!0;return!1}findMount(e){let t=null;for(let[n,r]of this.mountPoints)(e===n||e.startsWith(n+`/`))&&(!t||n.length>t.mountPath.length)&&(t={mountPath:n,backend:r});return t?e===t.mountPath?{path:t.mountPath,backend:t.backend,relParts:[]}:{path:t.mountPath,backend:t.backend,relParts:e.slice(t.mountPath.length+1).split(`/`).filter(Boolean)}:null}async readFile(e,t){return this.withKindMismatchRetry(e,()=>this.readFileInner(e,t))}async readFileInner(e,t){let n=i(e),r=this.findMount(n);if(r){if(r.relParts.length===0)throw new c(`EISDIR`,`is a directory`,n);let e=r.relParts.join(`/`);try{let n=await r.backend.readFile(e);return(t?.encoding??`utf-8`)===`utf-8`?new TextDecoder(`utf-8`).decode(n):n}catch(e){A(e,n)}}let a=await this.resolveSymlinks(n);try{return(t?.encoding??`utf-8`)===`utf-8`?await this.lfs.readFile(a,{encoding:`utf8`}):await this.lfs.readFile(a)}catch(e){throw M(e,n)}}async writeFile(e,t,n){return this.withKindMismatchRetry(e,()=>this.writeFileInner(e,t,n))}async writeFileInner(e,t,r){let a=i(e),o=this.findMount(a);if(o){if(o.relParts.length===0)throw new c(`EISDIR`,`is a directory`,a);let e=o.relParts.join(`/`),n=!1;try{await this.stat(a),n=!0}catch{}let r=typeof t==`string`?new TextEncoder().encode(t):t instanceof Uint8Array?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):new Uint8Array(t);try{await o.backend.writeFile(e,r)}catch(e){A(e,a)}this.watcher?.notify([{type:n?`modify`:`create`,path:a,entryType:`file`}]),this.mountIndex.notifyWrite(a);return}let s;try{s=await this.resolveSymlinks(a)}catch{s=a}let l=!1;try{await this.lfs.stat(s),l=!0}catch{}let{dir:u}=n(s);await this.withWriteLock(async()=>{this.markSidecarDirty(s),u!==`/`&&await this.mkdirRecursiveUnlocked(u);let e=typeof t==`string`?new TextEncoder().encode(t).byteLength:(t instanceof Uint8Array,t.byteLength);try{await this.lfs.writeFile(s,t)}catch(e){if(u!==`/`&&e instanceof Error&&e.message.includes(`ENOENT`)){await this.mkdirRecursiveUnlocked(u);try{await this.lfs.writeFile(s,t)}catch(e){throw M(e,a)}}else throw M(e,a)}try{await this.lfs.truncate?.(s,e)}catch(e){throw M(e,a)}}),this.watcher?.notify([{type:l?`modify`:`create`,path:s,entryType:`file`}])}async readDir(e){let t=i(e),n=this.findMount(t);return n?this.readDirMounted(t,n):this.readDirLocal(t)}async readDirMounted(e,t){let n=this.mountIndex.getDirectoryEntries(t.path,e);if(n!==void 0){let t=new Map;for(let e of n)t.set(e.name,{name:e.name,type:e.type});return this.addNestedMountEntries(t,e),[...t.values()]}let r=t.relParts.join(`/`)||`/`,i;try{i=await t.backend.readDir(r)}catch(t){A(t,e)}let a=new Map;for(let e of i)a.set(e.name,{name:e.name,type:e.kind===`directory`?`directory`:`file`});return this.addNestedMountEntries(a,e),[...a.values()]}async readDirLocal(e){return this.withKindMismatchRetry(e,()=>this.readDirLocalInner(e))}async readDirLocalInner(e){let t=await this.resolveSymlinks(e);try{let e=await this.lfs.readdir(t),n=[];for(let r of e){let e=await this.statDirEntry(t,r);e&&n.push(e)}return n}catch(t){throw M(t,e)}}async statDirEntry(e,t){let n=e===`/`?`/${t}`:`${e}/${t}`;try{let e=await this.lfs.lstat(n);return e.isSymbolicLink()?{name:t,type:`symlink`}:{name:t,type:e.isDirectory()?`directory`:`file`}}catch{return null}}addNestedMountEntries(e,t){let n=t===`/`?`/`:`${t}/`;for(let r of this.mountPoints.keys()){if(r===t||!r.startsWith(n))continue;let i=r.slice(n.length);!i||i.includes(`/`)||e.has(i)||e.set(i,{name:i,type:`directory`})}}async withWriteLock(t){let n=this.dbName,r,i=new Promise(e=>{r=e}),a=e.writeChains.get(n)??Promise.resolve();e.writeChains.set(n,i),await a;try{let e=globalThis.navigator?.locks;return this.backend!==`opfs`||typeof e?.request!=`function`?await t():await e.request(`slicc-vfs:${n}`,()=>t())}finally{r(),e.writeChains.get(n)===i&&e.writeChains.delete(n)}}async mkdirRecursiveUnlocked(e){let t=e.split(`/`).filter(Boolean),n=[],r=``;for(let e of t){r+=`/`+e;try{await this.lfs.mkdir(r),n.push(r)}catch(e){if(e instanceof Error&&!e.message.includes(`EEXIST`))throw M(e,r);try{let e=await this.lfs.lstat(r);if(!e.isDirectory()&&!e.isSymbolicLink())throw new c(`ENOTDIR`,`not a directory`,r)}catch(e){if(e instanceof c&&e.code===`ENOTDIR`)throw e}}}return n}async mkdir(e,t){let n=i(e);if(n===`/`)return;let r=this.findMount(n);if(r){if(r.relParts.length===0)return;let e=r.relParts.join(`/`),t=await this.exists(n);try{await r.backend.mkdir(e)}catch(e){A(e,n)}t||this.watcher?.notify([{type:`create`,path:n,entryType:`directory`}]);return}if(t?.recursive){let e=await this.withWriteLock(()=>(this.markSidecarDirty(n),this.mkdirRecursiveUnlocked(n)));e.length>0&&this.watcher?.notify(e.map(e=>({type:`create`,path:e,entryType:`directory`})))}else await this.withWriteLock(async()=>{this.markSidecarDirty(n);try{await this.lfs.mkdir(n)}catch(e){throw M(e,n)}}),this.watcher?.notify([{type:`create`,path:n,entryType:`directory`}])}async rm(e,t){return this.withKindMismatchRetry(i(e),()=>this.rmInner(e,t))}async rmInner(e,t){let n=i(e),r=this.findMount(n);if(r){if(r.relParts.length===0)throw new c(`EINVAL`,`cannot remove a mount point — use unmount`,n);let e;try{e=(await this.stat(n)).type}catch{}let i=r.relParts.join(`/`);try{await r.backend.remove(i,{recursive:t?.recursive})}catch(e){A(e,n)}this.watcher?.notify([{type:`delete`,path:n,entryType:e}]),this.mountIndex.notifyDelete(n);return}try{let e=await this.lfs.lstat(n);await this.withWriteLock(async()=>{e.isSymbolicLink()?await this.lfs.unlink(n):e.isDirectory()?t?.recursive?await this.rmRecursiveUnlocked(n):await this.lfs.rmdir(n):await this.lfs.unlink(n),this.markSidecarDirty(n,`prefix`),await this.writeOpfsMetadataSidecarUnlocked()})}catch(e){throw M(e,n)}this.watcher?.notify([{type:`delete`,path:n}])}async rmRecursiveUnlocked(e){let t=await this.lfs.readdir(e);for(let n of t){let t=e===`/`?`/${n}`:`${e}/${n}`,r=await this.lfs.lstat(t);r.isSymbolicLink()?await this.lfs.unlink(t):r.isDirectory()?await this.rmRecursiveUnlocked(t):await this.lfs.unlink(t)}await this.lfs.rmdir(e)}async stat(e){return this.withKindMismatchRetry(e,()=>this.statInner(e))}async statInner(e){let t=i(e),n=this.findMount(t);if(n){if(n.relParts.length===0)try{let e=await this.lfs.stat(t);return{type:`directory`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs}}catch{return{type:`directory`,size:0,mtime:Date.now(),ctime:Date.now()}}let e=n.relParts.join(`/`);try{let t=await n.backend.stat(e);return{type:t.kind===`directory`?`directory`:`file`,size:t.size,mtime:t.mtime,ctime:t.mtime}}catch(e){A(e,t)}}let r=await this.resolveSymlinks(t);try{let e=await this.lfs.stat(r);return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,ino:e.ino}}catch(e){throw M(e,t)}}async exists(e){let t=i(e),n=this.findMount(t);if(n){if(n.relParts.length===0)return!0;try{return await this.stat(t),!0}catch{return!1}}try{return await this.stat(t),!0}catch{try{return await this.lfs.lstat(t),!0}catch{return!1}}}async rename(e,t){return this.withKindMismatchRetryPaths([i(e),i(t)],()=>this.renameInner(e,t))}async renameInner(e,t){let n=i(e),r=i(t),a;try{a=(await this.lstat(n)).type}catch{}let o=this.findMount(n);if(o?.backend.rename){let e=this.findMount(r);if(e&&e.backend===o.backend){try{await o.backend.rename(o.relParts.join(`/`),e.relParts.join(`/`))}catch(e){A(e,n)}this.watcher?.notify([{type:`delete`,path:n,entryType:a},{type:`create`,path:r,entryType:a}]),this.mountIndex.notifyRename(n,r);return}}try{await this.withWriteLock(async()=>{this.markSidecarDirty(n,`prefix`),this.markSidecarDirty(r,`prefix`),await this.lfs.rename(n,r),await this.writeOpfsMetadataSidecarUnlocked()})}catch(e){throw M(e,n)}this.watcher?.notify([{type:`delete`,path:n,entryType:a},{type:`create`,path:r,entryType:a}]),this.mountIndex.notifyRename(n,r)}async readTextFile(e){return await this.readFile(e,{encoding:`utf-8`})}async*walk(e,t,n=0){yield*W({mountPoints:this.mountPoints,mountIndex:this.mountIndex,realpath:e=>this.realpath(e),readDir:e=>this.readDir(e),stat:e=>this.stat(e)},e,t,n)}async copyFile(e,t){if((await this.stat(e)).type===`directory`)throw new c(`EISDIR`,`is a directory`,e);let n=await this.readFile(e,{encoding:`binary`});await this.writeFile(t,n)}dirname(e){return n(i(e)).dir}basename(e){return n(i(e)).base}async symlink(e,t){let r=i(t);if(this.findMount(r))throw new c(`EINVAL`,`symlinks not supported on mounted filesystems`,r);let{dir:a}=n(r);await this.withWriteLock(async()=>{a!==`/`&&await this.mkdirRecursiveUnlocked(a);try{await this.lfs.symlink(e,r)}catch(t){if(a!==`/`&&t instanceof Error&&t.message.includes(`ENOENT`)){await this.mkdirRecursiveUnlocked(a);try{await this.lfs.symlink(e,r)}catch(e){throw M(e,r)}}else throw M(t,r)}this.markSidecarDirty(r),await this.writeOpfsMetadataSidecarUnlocked()}),this.watcher?.notify([{type:`create`,path:r,entryType:`symlink`}])}async readlink(e){let t=i(e);try{return await this.lfs.readlink(t)}catch(e){throw M(e,t)}}async lstat(e){let t=i(e);if(this.findMount(t)||t===`/`)return this.stat(t);try{let e=await this.lfs.lstat(t);if(e.isSymbolicLink()){let n=await this.lfs.readlink(t);return{type:`symlink`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,isSymlink:!0,symlinkTarget:n,ino:e.ino}}return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,ino:e.ino}}catch(e){throw M(e,t)}}async realpath(e){return B(this.lfs,e=>this.findMount(e)!==null,e)}resolveSymlinks(e){return V(this.lfs,e=>this.findMount(e)!==null,e)}},X=e({FsError:()=>c,FsWatcher:()=>C,MountIndex:()=>m,RestrictedFS:()=>k,VirtualFS:()=>Y,joinPath:()=>o,normalizePath:()=>i,pathSegments:()=>r,resolveVfsBackendFromEnv:()=>q,splitPath:()=>n});export{C as i,Y as n,k as r,X as t};
1
+ import{n as e}from"./rolldown-runtime-Dd_uD5pT.js";import{t}from"./logger-LESFN7Hj.js";import{a as n,i as r,n as i,r as a,t as o}from"./path-utils-DNJG-zQf.js";import{t as s}from"./backend-local-_o3dnerJ.js";import{t as c}from"./types-idfTVsM8.js";import{a as l,i as u,n as d,t as f}from"./mount-table-store-DrF_Ifaz.js";import{r as p,t as m}from"./mount-index-CD1UKs2l.js";import{n as h,t as g}from"./virtual-device-paths-CS5o4QVz.js";import{i as _,r as v,t as y}from"./sidecar-repair-CIHuOk7H.js";const b=t(`fs-watcher`);let x=0;function S(e,t){return t===`/`||e===t||e.startsWith(t+`/`)}var C=class{registrations=new Map;watch(e,t,n){let r=`fsw-${++x}`;return this.registrations.set(r,{id:r,basePath:e,filter:t,callback:n}),b.debug(`Watch registered`,{id:r,basePath:e}),()=>{this.registrations.delete(r),b.debug(`Watch unregistered`,{id:r})}}notify(e){if(e.length!==0)for(let[,t]of this.registrations){let n=e.filter(e=>S(e.path,t.basePath)&&t.filter(e.path));if(n.length>0)try{t.callback(n)}catch(e){b.error(`Watch callback error`,{id:t.id,error:e instanceof Error?e.message:String(e)})}}}dispose(){this.registrations.clear(),b.debug(`All watchers disposed`)}get size(){return this.registrations.size}};const w=new TextEncoder,T=new TextDecoder(`utf-8`,{fatal:!1});var E=class{entries=new Map;static handles(e){return h(i(e))}has(e){return this.entries.has(i(e))}write(e,t){let n=i(e),r=typeof t==`string`?w.encode(t):new Uint8Array(t),a=Date.now(),o=this.entries.get(n);this.entries.set(n,{bytes:r,mtime:a,ctime:o?.ctime??a})}read(e,t){let n=this.require(e);return(t?.encoding??`utf-8`)===`utf-8`?T.decode(n.bytes):new Uint8Array(n.bytes)}readText(e){return T.decode(this.require(e).bytes)}stat(e){let t=this.require(e);return{type:`file`,size:t.bytes.length,mtime:t.mtime,ctime:t.ctime}}remove(e){return this.entries.delete(i(e))}require(e){let t=i(e),n=this.entries.get(t);if(!n)throw new c(`ENOENT`,`no such file or directory`,t);return n}};const D={[g]:{stat:()=>({type:`file`,size:0,mtime:0,ctime:0}),read:e=>(e?.encoding??`utf-8`)===`utf-8`?``:new Uint8Array,readText:()=>``,write:()=>{}}},O=[`/tmp/`];var k=class{ephemeralFds=new E;vfs;allowedPrefixes;readOnlyPrefixes;readGrantPatterns=[];writeEnforcement;constructor(e,t,n=[],r=`hard`){this.vfs=e;let a=e=>{let t=i(e);return t.endsWith(`/`)?t:t+`/`};this.allowedPrefixes=t.map(a),this.readOnlyPrefixes=n.map(a),this.writeEnforcement=r}getAllPrefixes(){let e=this.vfs.listMounts().map(e=>e.endsWith(`/`)?e:e+`/`);return[...this.allowedPrefixes,...this.readOnlyPrefixes,...e,...O]}setReadGrants(e){this.readGrantPatterns=[];for(let t of new Set(e))this.addReadGrant(t)}addReadGrant(e){let t=e.split(`/`),n=[];for(let e=1;e<t.length;e++)n.push(a(t.slice(0,e).join(`/`)||`/`));this.readGrantPatterns.push({pattern:e,regex:a(e),ancestorRegexes:n})}matchesReadGrant(e){return this.readGrantPatterns.some(t=>t.regex.test(e))}leadsToReadGrant(e){return this.readGrantPatterns.some(t=>t.ancestorRegexes.some(t=>t.test(e)))}isAllowed(e){let t=i(e),n=this.getAllPrefixes();return this.matchesReadGrant(t)||this.leadsToReadGrant(t)||n.some(e=>t===e.slice(0,-1)||t.startsWith(e)||t===`/`||e.startsWith(t+`/`))}isAllowedStrict(e){let t=i(e),n=this.getAllPrefixes();return this.matchesReadGrant(t)||n.some(e=>t===e.slice(0,-1)||t.startsWith(e))}isWritable(e){let t=i(e);return[...this.allowedPrefixes,...O].some(e=>t===e.slice(0,-1)||t.startsWith(e))}canWrite(e){return E.handles(e)||this.isWritable(e)}checkWrite(e){if(this.writeEnforcement!==`sudo-delegated`&&!this.isWritable(e))throw new c(`EACCES`,`permission denied`,i(e))}async resolveAndCheckRead(e){try{let t=await this.vfs.realpath(e);if(!this.isAllowedStrict(t))throw new c(`ENOENT`,`no such file or directory`,i(e));return t}catch(t){throw t instanceof c?t:new c(`ENOENT`,`no such file or directory`,i(e))}}async resolveAndCheckWrite(e){try{let t=await this.vfs.realpath(e);if(!this.isWritable(t)&&!this.isSymlinkEscapeAllowed(t))throw new c(`EACCES`,`permission denied`,i(e));return t}catch(t){throw t instanceof c?t:new c(`EACCES`,`permission denied`,i(e))}}isSymlinkEscapeAllowed(e){return!1}async checkParentRealpathEscape(e){let t=this.vfs.dirname(e),n=this.vfs.basename(e),r;try{r=await this.vfs.realpath(t)}catch(e){if(e instanceof c&&e.code===`EACCES`)throw e;return}let a=r+`/`+n;if(this.isWritable(a))return;let o=i(r)!==i(t);if(!(this.writeEnforcement===`sudo-delegated`&&!o))throw new c(`EACCES`,`permission denied`,i(e))}getUnderlyingFS(){return this.vfs}invalidatePaths(e){this.vfs.invalidatePaths(e)}async flush(){await this.vfs.flush()}isPathUnderMount(e){return this.vfs.isPathUnderMount(e)}async readFile(e,t){let n=D[i(e)];if(n)return n.read(t);if(E.handles(e))return this.ephemeralFds.read(e,t);if(!this.isAllowedStrict(e))throw new c(`ENOENT`,`no such file or directory`,i(e));let r=await this.resolveAndCheckRead(e);return this.vfs.readFile(r,t)}async readDir(e){if(!this.isAllowed(e))return[];let t=e;if(this.isAllowedStrict(e))try{t=await this.resolveAndCheckRead(e)}catch{return[]}let n=await this.vfs.readDir(t);if(!this.isAllowedStrict(e)){let t=i(e);return n.filter(e=>{let n=t===`/`?`/${e.name}`:`${t}/${e.name}`;return this.isAllowed(n)})}return n}async stat(e){let t=D[i(e)];if(t)return t.stat();if(E.handles(e))return this.ephemeralFds.stat(e);if(!this.isAllowed(e))throw new c(`ENOENT`,`no such file or directory`,i(e));if(this.isAllowedStrict(e)){let t=await this.resolveAndCheckRead(e);return this.vfs.stat(t)}return this.vfs.stat(e)}scanPathForSymlinks(e,t){let n=i(e);if(n===`/`)return!1;let r=n.slice(1).split(`/`),a=t?r.length:r.length-1,o=``;for(let e=0;e<a;e++){o=o+`/`+r[e];let t=this.vfs.lstatSync(o);if(t===null)return null;if(t.type===`symlink`)return!0}return!1}statSync(e){let t=D[i(e)];return t?t.stat():E.handles(e)?this.ephemeralFds.has(e)?this.ephemeralFds.stat(e):null:!this.isAllowedStrict(e)||this.scanPathForSymlinks(e,!0)!==!1?null:this.vfs.statSync(e)}lstatSync(e){let t=D[i(e)];return t?t.stat():E.handles(e)?this.ephemeralFds.has(e)?this.ephemeralFds.stat(e):null:!this.isAllowed(e)||this.scanPathForSymlinks(e,!1)!==!1?null:this.vfs.lstatSync(e)}readDirSync(e){if(!this.isAllowed(e)||this.scanPathForSymlinks(e,!0)!==!1)return null;let t=this.vfs.readDirSync(e);if(t===null)return null;if(this.isAllowedStrict(e))return t;let n=i(e);return t.filter(e=>{let t=n===`/`?`/${e.name}`:`${n}/${e.name}`;return this.isAllowed(t)})}async realpath(e){if(E.handles(e)){let t=i(e);if(!this.ephemeralFds.has(t))throw new c(`ENOENT`,`no such file or directory`,t);return t}let t;try{t=await this.vfs.realpath(e)}catch(t){throw t instanceof c?t:new c(`ENOENT`,`no such file or directory`,i(e))}if(!this.isAllowedStrict(t))throw new c(`ENOENT`,`no such file or directory`,i(e));return t}async exists(e){if(D[i(e)])return!0;if(E.handles(e))return this.ephemeralFds.has(e);if(!this.isAllowed(e))return!1;if(this.isAllowedStrict(e))try{await this.resolveAndCheckRead(e)}catch{return!1}return this.vfs.exists(e)}async readTextFile(e){let t=D[i(e)];if(t)return t.readText();if(E.handles(e))return this.ephemeralFds.readText(e);if(!this.isAllowedStrict(e))throw new c(`ENOENT`,`no such file or directory`,i(e));let n=await this.resolveAndCheckRead(e);return this.vfs.readTextFile(n)}async*walk(e){if(!this.isAllowed(e))return;let t=e;if(this.isAllowedStrict(e))try{t=await this.resolveAndCheckRead(e)}catch{return}for await(let e of this.vfs.walk(t))this.isAllowed(e)&&(yield e)}async writeFile(e,t,n){let r=D[i(e)];if(r){r.write(t);return}if(E.handles(e)){this.ephemeralFds.write(e,t);return}this.checkWrite(e),await this.checkParentRealpathEscape(e);try{(await this.vfs.lstat(e)).type===`symlink`&&await this.resolveAndCheckWrite(e)}catch(e){if(e instanceof c&&e.code===`EACCES`)throw e}return this.vfs.writeFile(e,t,n)}refuseDescriptorTreeOp(e){if(E.handles(e))throw new c(`EACCES`,`permission denied`,i(e))}async mkdir(e,t){return this.refuseDescriptorTreeOp(e),this.checkWrite(e),await this.checkParentRealpathEscape(e),this.vfs.mkdir(e,t)}async rm(e,t){if(E.handles(e)){if(!this.ephemeralFds.remove(e))throw new c(`ENOENT`,`no such file or directory`,i(e));return}this.checkWrite(e);try{(await this.vfs.lstat(e)).type===`symlink`||await this.resolveAndCheckWrite(e)}catch(e){if(e instanceof c&&e.code===`EACCES`)throw e}return this.vfs.rm(e,t)}async rename(e,t){return this.refuseDescriptorTreeOp(e),this.refuseDescriptorTreeOp(t),this.checkWrite(e),this.checkWrite(t),await this.resolveAndCheckWrite(e),await this.checkParentRealpathEscape(t),this.vfs.rename(e,t)}async copyFile(e,t){if(E.handles(e)){let n=this.ephemeralFds.read(e,{encoding:`binary`});await this.writeFile(t,n);return}if(E.handles(t)){if(!this.isAllowed(e))throw new c(`ENOENT`,`no such file or directory`,i(e));let n=await this.resolveAndCheckRead(e);this.ephemeralFds.write(t,await this.vfs.readFile(n,{encoding:`binary`}));return}if(!this.isAllowed(e))throw new c(`ENOENT`,`no such file or directory`,i(e));this.checkWrite(t);let n=await this.resolveAndCheckRead(e);await this.checkParentRealpathEscape(t);try{(await this.vfs.lstat(t)).type===`symlink`&&await this.resolveAndCheckWrite(t)}catch(e){if(e instanceof c&&e.code===`EACCES`)throw e}return this.vfs.copyFile(n,t)}async symlink(e,t){return this.refuseDescriptorTreeOp(t),this.checkWrite(t),await this.checkParentRealpathEscape(t),this.vfs.symlink(e,t)}async readlink(e){if(!this.isAllowedStrict(e))throw new c(`ENOENT`,`no such file or directory`,i(e));let t=await this.vfs.readlink(e),n;if(t.startsWith(`/`))n=i(t);else{let r=this.vfs.dirname(e);n=i(r+`/`+t)}if(!this.isAllowedStrict(n))throw new c(`ENOENT`,`no such file or directory`,i(e));return t}async lstat(e){let t=D[i(e)];if(t)return t.stat();if(E.handles(e))return this.ephemeralFds.stat(e);if(!this.isAllowed(e))throw new c(`ENOENT`,`no such file or directory`,i(e));let n=i(e),r=this.vfs.dirname(n),a=this.vfs.basename(n),o;if(r===n)o=r;else try{o=await this.vfs.realpath(r)}catch{throw new c(`ENOENT`,`no such file or directory`,n)}let s=o===`/`?`/${a}`:`${o}/${a}`;if(!this.isAllowed(s))throw new c(`ENOENT`,`no such file or directory`,n);return this.vfs.lstat(s)}watch(e,t,n){if(!this.isAllowed(e))throw new c(`EACCES`,`permission denied`,i(e));let r=this.vfs.getWatcher();if(!r)throw new c(`EINVAL`,`no watcher configured`);return r.watch(i(e),t,n)}dirname(e){return this.vfs.dirname(e)}basename(e){return this.vfs.basename(e)}async mount(e,t,n){return this.refuseDescriptorTreeOp(e),this.checkWrite(e),await this.checkParentRealpathEscape(e),this.vfs.mount(e,t,n)}async unmount(e){return this.refuseDescriptorTreeOp(e),this.checkWrite(e),await this.checkParentRealpathEscape(e),this.vfs.unmount(e)}listMounts(){return this.vfs.listMounts()}getMountIndex(){return this.vfs.getMountIndex()}async refreshMount(e,t){return this.refuseDescriptorTreeOp(e),this.checkWrite(e),this.vfs.refreshMount(e,t)}async dispose(){await this.vfs.dispose()}};function A(e,t){if(e instanceof c){let n=`${e.code}: `,r=e.message;throw r.startsWith(n)&&(r=r.slice(n.length)),e.path&&r.endsWith(` '${e.path}'`)&&(r=r.slice(0,r.length-` '${e.path}'`.length)),new c(e.code,r,t)}throw e}const j=[`ENOENT`,`EEXIST`,`ENOTDIR`,`EISDIR`,`ENOTEMPTY`,`EINVAL`,`EACCES`,`ELOOP`,`EBUSY`,`EFBIG`,`EBADF`,`ENOSYS`,`EIO`];function M(e,t){if(e instanceof c)return e;{let n=e instanceof Error?e.message:String(e);if(n.includes(`maximum size exceeded`)||n.includes(`call stack size exceeded`))return new c(`EIO`,`internal overflow, not storage: ${n} — reload the session`,t)}let n=e?.code;if(typeof n==`string`){let r=n;if(j.includes(r)){let n=e instanceof Error?e.message:String(e);return n.startsWith(`${r}: `)&&(n=n.slice(r.length+2),n=n.replace(/, undefined( '[^']*')?$/,``).replace(/ '[^']*'$/,``)),new c(r,n||r,t)}}let r=e instanceof Error?e.message:String(e);return r.includes(`ENOENT`)?new c(`ENOENT`,`no such file or directory`,t):r.includes(`EEXIST`)?new c(`EEXIST`,`file already exists`,t):r.includes(`ENOTDIR`)?new c(`ENOTDIR`,`not a directory`,t):r.includes(`EISDIR`)?new c(`EISDIR`,`is a directory`,t):r.includes(`ENOTEMPTY`)?new c(`ENOTEMPTY`,`directory not empty`,t):r.includes(`ELOOP`)?new c(`ELOOP`,`too many levels of symbolic links`,t):new c(`EINVAL`,r,t)}function N(e){return e===void 0?`absent`:(e&61440)==16384?`directory`:`file`}function P(e,t){return t===`absent`?!1:e.kind===`missing`||e.kind!==t}function F(e){let t=e?.mode;return typeof t==`number`?t:void 0}function I(e,t,n,r=new Set){let i=new Set(n);if(r.size>0){for(let t of Object.keys(e.entries??{}))for(let e of r)if(t===e||t.startsWith(`${e}/`)){i.add(t);break}}let a=[];for(let n of i){let r=e.entries?.[n],i=t.entries?.[n];if(!r||!i)continue;let o=N(F(r));o!==N(F(i))&&a.push({path:n,ownIsDirectory:o===`directory`})}return a}async function L(e,t,n,r){try{return await e.lstat(t)}catch(e){let t=M(e,r);if(t.code===`ENOENT`&&n)return null;throw t}}async function R(e,t,r){let a;try{a=await e.readlink(t)}catch(e){throw M(e,r)}return a.startsWith(`/`)?i(a):i(o(n(t).dir,a))}async function z(e,t,n,r,i,a){let o=t===`/`?`/${n}`:`${t}/${n}`;for(;;){let t=await L(e,o,r,i);if(t===null||!t.isSymbolicLink())return{resolved:o,hops:a};if(++a>10)throw new c(`ELOOP`,`too many symbolic links encountered`,i);o=await R(e,o,i)}}async function B(e,t,n){let r=i(n);if(t(r))return r;let a=r.split(`/`).filter(Boolean),o=`/`,s=0;for(let t=0;t<a.length;t++){let n=await z(e,o,a[t],t===a.length-1,r,s);o=n.resolved,s=n.hops}return o}async function V(e,t,n){return t(n)?n:B(e,t,n)}function H(e,t,n){return e.size===0||!e.has(n)||!t.isReady(n)?!1:!Array.from(e.keys()).some(e=>e!==n&&e.startsWith(n+`/`))}async function U(e,t){try{return await e(t)}catch{return t}}async function*W(e,t,n,r=0){let a=i(t);if(H(e.mountPoints,e.mountIndex,a)){let t=e.mountIndex.getFiles(a);if(t){for(let e of t)yield e;return}}let o=n??new Set;if(r>64||o.size>=1e5)return;let s=await U(t=>e.realpath(t),a);if(o.has(s))return;o.add(s);let c=await e.readDir(a);for(let t of c)yield*G(e,t,a===`/`?`/${t.name}`:`${a}/${t.name}`,o,r+1)}async function*G(e,t,n,r,i){if(t.type===`file`){yield n;return}if(t.type===`symlink`){yield*K(e,n,r,i);return}yield*W(e,n,r,i)}async function*K(e,t,n,r){try{let i=await e.stat(t);i.type===`file`?yield t:i.type===`directory`&&(yield*W(e,t,n,r))}catch{}}function q(){try{if(typeof globalThis.navigator?.storage?.getDirectory==`function`)return`opfs`}catch{}return`memory`}function J(e,t){switch(e.kind){case`local`:case`proc`:return{kind:`local`,mountId:e.mountId,idbHandleKey:t};case`hostfs`:return{kind:`hostfs`,mountId:e.mountId,hostPath:e.getHostPath()};default:return{kind:e.kind===`s3`?`s3`:e.kind===`aem`?`aem`:`da`,mountId:e.mountId,source:e.source,profile:e.profile??`default`}}}var Y=class e{lfs;lfsSync;rawLfs=null;rawLfsSync=null;_ready;_readyResolved=!1;backend;mountPoints=new Map;opfsBackendFs=null;opfsHandle=null;mountRoot=``;internalMounts=new Set;watcher=null;dbName;mountSyncChannel=null;mountIndex=new m;static writeChains=new Map;onRepairProgress;constructor(t,n,r,i,a){if(this.dbName=t,this.onRepairProgress=a,this.backend=r===`opfs`?`opfs`:`memory`,this.lfs=this.makeDeferredLfs(),this.lfsSync=this.makeDeferredLfsSync(),this._ready=this.backend===`opfs`?e.initOpfsBackend(this,i,n===!0):e.initMemoryBackend(this,t,n===!0),this._ready.then(()=>{this._readyResolved=!0},()=>{}),typeof BroadcastChannel<`u`)try{this.mountSyncChannel=new BroadcastChannel(`vfs-mount-sync:${t}`),this.mountSyncChannel.onmessage=e=>{let{type:t,path:n,descriptor:r}=e.data??{};if(t===`mount`&&typeof n==`string`&&r)this.reconstructBackendFromDescriptor(r,n).then(e=>{this.mountPoints.set(n,e),e.kind===`local`&&this.mountIndex.registerMount(n,e.getHandle()),this.watcher?.notify([{type:`modify`,path:n,entryType:`directory`}])}).catch(()=>{});else if(t===`unmount`&&typeof n==`string`){let e=this.mountPoints.get(n);this.mountPoints.delete(n),this.mountIndex.unregisterMount(n),e?.close(),this.watcher?.notify([{type:`modify`,path:n,entryType:`directory`}])}}}catch{}}static async initOpfsBackend(t,n,r){let i=n??await e.acquireOpfsHandle(t.dbName,r);await e.seedOpfsMetadataSidecarIfMissing(i);let[a,{WebAccess:o}]=await Promise.all([import(`./dist-CBELmDjr.js`).then(e=>e.t),import(`./dist-iMxkf8fm.js`)]);await e.ensureRootMount(a);let s=`/__opfs__/${t.dbName}`,c=e.opfsBackends.get(t.dbName);if(c&&r){try{a.umount(s)}catch{}e.opfsBackends.delete(t.dbName),c=void 0}if(!c){let n=()=>a.resolveMountConfig({backend:o,handle:i,metadata:`/.metadata.json`}),{resolveWithSidecarRepair:r,repairOpfsMetadataSidecar:l}=await import(`./sidecar-repair-CIHuOk7H.js`).then(e=>e.n);try{let e=await t.withWriteLock(()=>l(i,t.onRepairProgress));e?.changed&&console.warn(`[virtual-fs] repaired metadata sidecar before mount (#2146)`,{dbName:t.dbName,kindFixed:e.kindFixed,sizesFixed:e.sizesFixed,dropped:e.dropped,inosReassigned:e.inosReassigned,nlinksFixed:e.nlinksFixed,selfEntryDropped:e.selfEntryDropped})}catch{}let u=await r(n,()=>t.withWriteLock(()=>l(i,t.onRepairProgress)),e=>console.warn(`[virtual-fs] repaired poisoned metadata sidecar; retrying mount`,{dbName:t.dbName,kindFixed:e.kindFixed,sizesFixed:e.sizesFixed,dropped:e.dropped,nlinksFixed:e.nlinksFixed,selfEntryDropped:e.selfEntryDropped}));try{a.mount(s,u)}catch{}c={backendFs:u,refs:0,sidecarDirty:{paths:new Set,prefixes:new Set}},e.opfsBackends.set(t.dbName,c)}c.refs+=1,t.opfsBackendFs=c.backendFs.index?c.backendFs:null,t.opfsHandle=i,t.mountRoot=s,t.rawLfs=a.promises,t.rawLfsSync=a}static async initMemoryBackend(t,n,r){let i=await import(`./dist-CBELmDjr.js`).then(e=>e.t);await e.ensureRootMount(i);let a=`/__zenfs__/${n}`,o=e.memoryBackends.get(n);if(o&&r){try{i.umount(a)}catch{}e.memoryBackends.delete(n),o=void 0}o||(o={store:i.InMemory.create({label:n}),refs:0},e.memoryBackends.set(n,o)),o.refs+=1;try{i.mount(a,o.store)}catch{}t.mountRoot=a,t.rawLfs=i.promises,t.rawLfsSync=i,t.opfsBackendFs=null,t.opfsHandle=null}static rootMountReady=null;static memoryBackends=new Map;static opfsBackends=new Map;static async ensureRootMount(t){return e.rootMountReady===null&&(e.rootMountReady=(async()=>{await t.configureSingle({backend:t.InMemory,label:`__vfs_root__`})})()),e.rootMountReady}prefix(e){return this.mountRoot?e===`/`?this.mountRoot:this.mountRoot+e:e}unprefix(e){return!this.mountRoot||!e.startsWith(this.mountRoot)?e:e.slice(this.mountRoot.length)||`/`}makeDeferredLfs(){let e=e=>this.prefix(e),t=e=>this.unprefix(e),n=()=>{if(!this.rawLfs)throw Error(`VirtualFS used before init resolved`);return this.rawLfs};return{readFile:(t,r)=>this._readyResolved?n().readFile(e(t),r):this._ready.then(()=>n().readFile(e(t),r)),writeFile:(t,r,i)=>this._readyResolved?n().writeFile(e(t),r,i):this._ready.then(()=>n().writeFile(e(t),r,i)),readdir:t=>this._readyResolved?n().readdir(e(t)):this._ready.then(()=>n().readdir(e(t))),mkdir:(t,r)=>this._readyResolved?n().mkdir(e(t),r):this._ready.then(()=>n().mkdir(e(t),r)),rmdir:t=>this._readyResolved?n().rmdir(e(t)):this._ready.then(()=>n().rmdir(e(t))),unlink:t=>this._readyResolved?n().unlink(e(t)):this._ready.then(()=>n().unlink(e(t))),rename:(t,r)=>this._readyResolved?n().rename(e(t),e(r)):this._ready.then(()=>n().rename(e(t),e(r))),stat:t=>this._readyResolved?n().stat(e(t)):this._ready.then(()=>n().stat(e(t))),lstat:t=>this._readyResolved?n().lstat(e(t)):this._ready.then(()=>n().lstat(e(t))),symlink:(t,r)=>{let i=t.startsWith(`/`)?e(t):t;return this._readyResolved?n().symlink(i,e(r)):this._ready.then(()=>n().symlink(i,e(r)))},readlink:async r=>(this._readyResolved||await this._ready,t(await n().readlink(e(r)))),truncate:async(t,r)=>{this._readyResolved||await this._ready;let i=n();typeof i.truncate==`function`&&await i.truncate(e(t),r)},realpath:async r=>{this._readyResolved||await this._ready;let i=n();return typeof i.realpath==`function`?t(await i.realpath(e(r))):e(r)}}}makeDeferredLfsSync(){let e=e=>this.prefix(e),t=e=>this.unprefix(e);return{readdirSync:t=>{let n=this.rawLfsSync;return n?.readdirSync?n.readdirSync(e(t)):void 0},statSync:t=>{let n=this.rawLfsSync;return n?.statSync?n.statSync(e(t)):void 0},lstatSync:t=>{let n=this.rawLfsSync;return n?.lstatSync?n.lstatSync(e(t)):void 0},readlinkSync:n=>{let r=this.rawLfsSync;return r?.readlinkSync?t(r.readlinkSync(e(n))):void 0}}}static async seedOpfsMetadataSidecarIfMissing(e){let t=`.metadata.json`;try{await e.getFileHandle(t);return}catch(e){if(e?.name!==`NotFoundError`)throw e}let n=await(await e.getFileHandle(t,{create:!0})).createWritable(),r=JSON.stringify({version:1,maxSize:4294967295,entries:{}});await n.write(r),await n.close()}static async acquireOpfsHandle(e,t){let n=navigator.storage;if(!n?.getDirectory)throw new c(`EINVAL`,`OPFS is not available in this environment`);let r=await n.getDirectory();if(t)try{await r.removeEntry(e,{recursive:!0})}catch{}return r.getDirectoryHandle(e,{create:!0})}static _createSyncForTests(t){return new e(t)}static async create(t){let n=t?.dbName??`browser-fs`,r=t?.wipe===!0,i=t?.backend??q(),a=new e(n,r,i,void 0,t?.onRepairProgress);return await a._ready,r&&await f().catch(()=>{}),a}async flush(){await this.writeOpfsMetadataSidecar()}async writeOpfsMetadataSidecar(){this.backend===`opfs`&&await this.withWriteLock(()=>this.writeOpfsMetadataSidecarUnlocked())}async writeOpfsMetadataSidecarUnlocked(){if(this.backend!==`opfs`)return;let t=this.opfsBackendFs,n=this.opfsHandle;if(!t||!n)return;let r=t.index.toJSON(),i=e.opfsBackends.get(this.dbName)?.sidecarDirty,a=r;if(i){let e=null;try{let t=await n.getFileHandle(`.metadata.json`),r=JSON.parse(await(await t.getFile()).text());r&&typeof r==`object`&&r.entries&&(e=r)}catch{}e&&(await this.auditDirtyKindFlips(r,e,i,n),a=v(e,r,i))}let o=JSON.stringify(_(a)),s=await(await n.getFileHandle(`.metadata.json`,{create:!0})).createWritable();await s.write(o),await s.close(),i&&(i.paths.clear(),i.prefixes.clear())}async auditDirtyKindFlips(e,t,n,r){let i=I(e,t,n.paths,n.prefixes);if(i.length===0)return;let a=y(r),o=this.opfsBackendFs;for(let n of i){let r=await a(n.path).catch(()=>null);if(r!==null&&r.kind!==`missing`&&r.kind===`directory`===n.ownIsDirectory)continue;let i=t.entries?.[n.path];e.entries&&i!==void 0&&(e.entries[n.path]=i);let s=r!==null&&r.kind!==`missing`;s&&(o?.index?.delete(n.path),o?._handles?.delete(n.path)),console.warn(`[virtual-fs] refused to flush in-memory kind flip over sidecar record (#2006)`,{path:n.path,reality:r?.kind??`unverifiable`,evicted:s})}}markSidecarDirty(t,r=`path`){if(this.backend!==`opfs`)return;let a=e.opfsBackends.get(this.dbName)?.sidecarDirty;if(!a)return;let o=i(t);(r===`prefix`?a.prefixes:a.paths).add(o);let{dir:s}=n(o);for(;s!==`/`;)a.paths.add(s),s=n(s).dir}invalidatePaths(e){if(this.backend!==`opfs`||!this.opfsBackendFs)return;let t=this.opfsBackendFs;for(let n of e){let e=i(n);t.index.delete(e),t._handles?.delete(e),this.markSidecarDirty(e)}}async withKindMismatchRetry(e,t){return this.withKindMismatchRetryPaths([e],t)}async withKindMismatchRetryPaths(e,t){try{return await t()}catch(n){let r=n?.code;if(r!==`EISDIR`&&r!==`ENOTDIR`&&r!==`EINVAL`)throw n;for(let n of e)if(await this.reconcileKindMismatch(n).catch(()=>!1))return await t();throw n}}async reconcileKindMismatch(e){if(this.backend!==`opfs`)return!1;let t=this.opfsBackendFs,n=this.opfsHandle;if(!t?.index||!n)return!1;let r=i(e),a=r;try{a=await this.resolveSymlinks(r)}catch{}let o=await y(n)(a),s=N(t.index.get(a)?.mode),c=t._handles?.get(a),l=c?.kind===`directory`?`directory`:c?.kind===`file`?`file`:`absent`,u=P(o,s),d=P(o,l);if(!u&&!d)return!1;if(t.index.delete(a),t._handles?.delete(a),s===`directory`||l===`directory`){let e=`${a}/`;for(let n of[...t.index.keys()])n.startsWith(e)&&t.index.delete(n);if(t._handles)for(let n of[...t._handles.keys()])n.startsWith(e)&&t._handles.delete(n)}return this.markSidecarDirty(a),console.warn(`[virtual-fs] reconciled in-memory kind mismatch (#2006)`,{path:a,reality:o.kind,indexHeld:s,handleHeld:l}),!0}canWrite(e){return!0}setWatcher(e){this.watcher=e}getWatcher(){return this.watcher}async watch(e,t){let n=this.watcher;if(!n)throw new c(`ENOSYS`,`no FsWatcher attached to this VirtualFS`);let r=e.map(e=>n.watch(e,()=>!0,t));return()=>{for(let e of r)e()}}async dispose(){if(this.mountSyncChannel?.close(),this.mountSyncChannel=null,this.watcher?.dispose(),this.watcher=null,this.mountIndex.dispose(),await this.writeOpfsMetadataSidecar(),this.mountRoot){let t=this.backend===`opfs`?e.opfsBackends:e.memoryBackends,n=t.get(this.dbName);if(n&&(--n.refs,n.refs<=0)){t.delete(this.dbName);try{(await import(`./dist-CBELmDjr.js`).then(e=>e.t)).umount(this.mountRoot)}catch{}}}}readDirSync(e){let t=i(e);if(this.findMount(t))return null;let n=this.lfsSync;if(typeof n.readdirSync!=`function`||typeof n.lstatSync!=`function`)return null;try{let e=n.readdirSync(t),r=[];for(let i of e){let e=t===`/`?`/${i}`:`${t}/${i}`;try{let t=n.lstatSync(e),a=t.isSymbolicLink()?`symlink`:t.isDirectory()?`directory`:`file`;r.push({name:i,type:a})}catch{}}return r}catch{return null}}statSync(e){let t=i(e);if(this.findMount(t))return null;let r=this.lfsSync;if(typeof r.statSync!=`function`||typeof r.lstatSync!=`function`||typeof r.readlinkSync!=`function`)return null;if(t===`/`)try{let e=r.statSync(t);return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,ino:e.ino}}catch{return null}let a=t;for(let e=0;e<=10;e++){let e;try{e=r.lstatSync(a)}catch{return null}if(!e.isSymbolicLink())return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,ino:e.ino};let t;try{t=r.readlinkSync(a)}catch{return null}a=t.startsWith(`/`)?i(t):i(o(n(a).dir,t))}return null}lstatSync(e){let t=i(e);if(this.findMount(t))return null;let n=this.lfsSync;if(typeof n.lstatSync!=`function`)return null;if(t===`/`)return this.statSync(t);try{let e=n.lstatSync(t);if(e.isSymbolicLink()){let r=n.readlinkSync?n.readlinkSync(t):``;return{type:`symlink`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,isSymlink:!0,symlinkTarget:r,ino:e.ino}}return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,ino:e.ino}}catch{return null}}async mount(e,t,r){let a=i(e);if(this.mountPoints.has(a))throw new c(`EEXIST`,`mount point is already mounted`,a);try{if((await this.lstat(a)).type!==`directory`)throw new c(`ENOTDIR`,`mount point must be a directory`,a);if((await this.readDir(a)).length>0)throw new c(`ENOTEMPTY`,`mount point must be empty to avoid shadowing existing files`,a)}catch(e){if(!(e instanceof c)||e.code!==`ENOENT`)throw e}let{dir:o}=n(a);o!==`/`&&await this.mkdir(o,{recursive:!0});try{await this.lfs.mkdir(a)}catch{}if(this.mountPoints.set(a,t),t.kind===`local`){let e=r?.limits??p(r?.env??{});this.mountIndex.registerMount(a,t.getHandle(),e)}let s=J(t,a);try{this.mountSyncChannel?.postMessage({type:`mount`,path:a,descriptor:s})}catch{}if(this.watcher?.notify([{type:`modify`,path:a,entryType:`directory`}]),t.kind!==`hostfs`)try{let e={targetPath:a,descriptor:s,createdAt:Date.now()},n=t.kind===`local`?t.getHandle():void 0;await l(e,n)}catch{}}async unmount(e){let t=i(e),n=this.mountPoints.get(t);this.mountPoints.delete(t),this.mountIndex.unregisterMount(t);try{this.mountSyncChannel?.postMessage({type:`unmount`,path:t})}catch{}this.watcher?.notify([{type:`modify`,path:t,entryType:`directory`}]),await n?.close();try{await u(t)}catch{}}async reconstructBackendFromDescriptor(e,t){switch(e.kind){case`local`:{let t=await d(e.idbHandleKey);if(!t)throw Error(`no handle stored for ${e.idbHandleKey}`);return s.fromHandle(t,{mountId:e.mountId})}case`hostfs`:{let{HostFsMountBackend:n}=await import(`./backend-hostfs-bQQx-S0W.js`);return new n({targetPath:t,hostPath:e.hostPath,mountId:e.mountId})}case`s3`:{let{S3MountBackend:t,RemoteMountCache:n,makeSignedFetchS3:r}=await import(`./mount-DOTTHKHC.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-DOTTHKHC.js`).then(e=>e.t),i=new n({mountId:e.mountId,ttlMs:3e4});return new t({source:e.source,profile:e.profile,cache:i,mountId:e.mountId,signedFetch:r()})}case`aem`:{let{AemMountBackend:t,RemoteMountCache:n,makeSignedFetchDa:r}=await import(`./mount-DOTTHKHC.js`).then(e=>e.t),i=new n({mountId:e.mountId,ttlMs:3e4});return new t({source:e.source,profile:e.profile,cache:i,mountId:e.mountId,signedFetch:r()})}}}listMounts(){let e=[];for(let t of this.mountPoints.keys())this.internalMounts.has(t)||e.push(t);return e}listInternalMounts(){return[...this.internalMounts]}listMountPoints(){let e=[];for(let[t,n]of this.mountPoints)this.internalMounts.has(t)||e.push({path:t,kind:n.kind});return e}async mountInternal(e,t){let r=i(e);if(this.mountPoints.has(r))throw new c(`EEXIST`,`mount point is already mounted`,r);let{dir:a}=n(r);a!==`/`&&await this.mkdir(a,{recursive:!0});try{await this.lfs.mkdir(r)}catch{}this.mountPoints.set(r,t),this.internalMounts.add(r),this.watcher?.notify([{type:`modify`,path:r,entryType:`directory`}])}async unmountInternal(e){let t=i(e);if(!this.internalMounts.has(t))throw new c(`ENOENT`,`not an internal mount point`,t);let n=this.mountPoints.get(t);this.mountPoints.delete(t),this.internalMounts.delete(t),this.watcher?.notify([{type:`modify`,path:t,entryType:`directory`}]),await n?.close()}getMountIndex(){return this.mountIndex}async refreshMount(e,t){let n=i(e),r=this.mountPoints.get(n);if(!r)throw new c(`ENOENT`,`not a mount point`,n);let a=await r.refresh(t);return r.kind===`local`&&await this.mountIndex.refreshMount(n,p(t?.env??{})),this.watcher?.notify([{type:`modify`,path:n,entryType:`directory`}]),a}isPathUnderMount(e){for(let t of this.mountPoints.keys())if(e===t||e.startsWith(t+`/`))return!0;return!1}findMount(e){let t=null;for(let[n,r]of this.mountPoints)(e===n||e.startsWith(n+`/`))&&(!t||n.length>t.mountPath.length)&&(t={mountPath:n,backend:r});return t?e===t.mountPath?{path:t.mountPath,backend:t.backend,relParts:[]}:{path:t.mountPath,backend:t.backend,relParts:e.slice(t.mountPath.length+1).split(`/`).filter(Boolean)}:null}async readFile(e,t){return this.withKindMismatchRetry(e,()=>this.readFileInner(e,t))}async readFileInner(e,t){let n=i(e),r=this.findMount(n);if(r){if(r.relParts.length===0)throw new c(`EISDIR`,`is a directory`,n);let e=r.relParts.join(`/`);try{let n=await r.backend.readFile(e);return(t?.encoding??`utf-8`)===`utf-8`?new TextDecoder(`utf-8`).decode(n):n}catch(e){A(e,n)}}let a=await this.resolveSymlinks(n);try{return(t?.encoding??`utf-8`)===`utf-8`?await this.lfs.readFile(a,{encoding:`utf8`}):await this.lfs.readFile(a)}catch(e){throw M(e,n)}}async writeFile(e,t,n){return this.withKindMismatchRetry(e,()=>this.writeFileInner(e,t,n))}async writeFileInner(e,t,r){let a=i(e),o=this.findMount(a);if(o){if(o.relParts.length===0)throw new c(`EISDIR`,`is a directory`,a);let e=o.relParts.join(`/`),n=!1;try{await this.stat(a),n=!0}catch{}let r=typeof t==`string`?new TextEncoder().encode(t):t instanceof Uint8Array?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):new Uint8Array(t);try{await o.backend.writeFile(e,r)}catch(e){A(e,a)}this.watcher?.notify([{type:n?`modify`:`create`,path:a,entryType:`file`}]),this.mountIndex.notifyWrite(a);return}let s;try{s=await this.resolveSymlinks(a)}catch{s=a}let l=!1;try{await this.lfs.stat(s),l=!0}catch{}let{dir:u}=n(s);await this.withWriteLock(async()=>{this.markSidecarDirty(s),u!==`/`&&await this.mkdirRecursiveUnlocked(u);let e=typeof t==`string`?new TextEncoder().encode(t).byteLength:(t instanceof Uint8Array,t.byteLength);try{await this.lfs.writeFile(s,t)}catch(e){if(u!==`/`&&e instanceof Error&&e.message.includes(`ENOENT`)){await this.mkdirRecursiveUnlocked(u);try{await this.lfs.writeFile(s,t)}catch(e){throw M(e,a)}}else throw M(e,a)}try{await this.lfs.truncate?.(s,e)}catch(e){throw M(e,a)}}),this.watcher?.notify([{type:l?`modify`:`create`,path:s,entryType:`file`}])}async readDir(e){let t=i(e),n=this.findMount(t);return n?this.readDirMounted(t,n):this.readDirLocal(t)}async readDirMounted(e,t){let n=this.mountIndex.getDirectoryEntries(t.path,e);if(n!==void 0){let t=new Map;for(let e of n)t.set(e.name,{name:e.name,type:e.type});return this.addNestedMountEntries(t,e),[...t.values()]}let r=t.relParts.join(`/`)||`/`,i;try{i=await t.backend.readDir(r)}catch(t){A(t,e)}let a=new Map;for(let e of i)a.set(e.name,{name:e.name,type:e.kind===`directory`?`directory`:`file`});return this.addNestedMountEntries(a,e),[...a.values()]}async readDirLocal(e){return this.withKindMismatchRetry(e,()=>this.readDirLocalInner(e))}async readDirLocalInner(e){let t=await this.resolveSymlinks(e);try{let e=await this.lfs.readdir(t),n=[];for(let r of e){let e=await this.statDirEntry(t,r);e&&n.push(e)}return n}catch(t){throw M(t,e)}}async statDirEntry(e,t){let n=e===`/`?`/${t}`:`${e}/${t}`;try{let e=await this.lfs.lstat(n);return e.isSymbolicLink()?{name:t,type:`symlink`}:{name:t,type:e.isDirectory()?`directory`:`file`}}catch{return null}}addNestedMountEntries(e,t){let n=t===`/`?`/`:`${t}/`;for(let r of this.mountPoints.keys()){if(r===t||!r.startsWith(n))continue;let i=r.slice(n.length);!i||i.includes(`/`)||e.has(i)||e.set(i,{name:i,type:`directory`})}}async withWriteLock(t){let n=this.dbName,r,i=new Promise(e=>{r=e}),a=e.writeChains.get(n)??Promise.resolve();e.writeChains.set(n,i),await a;try{let e=globalThis.navigator?.locks;return this.backend!==`opfs`||typeof e?.request!=`function`?await t():await e.request(`slicc-vfs:${n}`,()=>t())}finally{r(),e.writeChains.get(n)===i&&e.writeChains.delete(n)}}async mkdirRecursiveUnlocked(e){let t=e.split(`/`).filter(Boolean),n=[],r=``;for(let e of t){r+=`/`+e;try{await this.lfs.mkdir(r),n.push(r)}catch(e){if(e instanceof Error&&!e.message.includes(`EEXIST`))throw M(e,r);try{let e=await this.lfs.lstat(r);if(!e.isDirectory()&&!e.isSymbolicLink())throw new c(`ENOTDIR`,`not a directory`,r)}catch(e){if(e instanceof c&&e.code===`ENOTDIR`)throw e}}}return n}async mkdir(e,t){let n=i(e);if(n===`/`)return;let r=this.findMount(n);if(r){if(r.relParts.length===0)return;let e=r.relParts.join(`/`),t=await this.exists(n);try{await r.backend.mkdir(e)}catch(e){A(e,n)}t||this.watcher?.notify([{type:`create`,path:n,entryType:`directory`}]);return}if(t?.recursive){let e=await this.withWriteLock(()=>(this.markSidecarDirty(n),this.mkdirRecursiveUnlocked(n)));e.length>0&&this.watcher?.notify(e.map(e=>({type:`create`,path:e,entryType:`directory`})))}else await this.withWriteLock(async()=>{this.markSidecarDirty(n);try{await this.lfs.mkdir(n)}catch(e){throw M(e,n)}}),this.watcher?.notify([{type:`create`,path:n,entryType:`directory`}])}async rm(e,t){return this.withKindMismatchRetry(i(e),()=>this.rmInner(e,t))}async rmInner(e,t){let n=i(e),r=this.findMount(n);if(r){if(r.relParts.length===0)throw new c(`EINVAL`,`cannot remove a mount point — use unmount`,n);let e;try{e=(await this.stat(n)).type}catch{}let i=r.relParts.join(`/`);try{await r.backend.remove(i,{recursive:t?.recursive})}catch(e){A(e,n)}this.watcher?.notify([{type:`delete`,path:n,entryType:e}]),this.mountIndex.notifyDelete(n);return}try{let e=await this.lfs.lstat(n);await this.withWriteLock(async()=>{e.isSymbolicLink()?await this.lfs.unlink(n):e.isDirectory()?t?.recursive?await this.rmRecursiveUnlocked(n):await this.lfs.rmdir(n):await this.lfs.unlink(n),this.markSidecarDirty(n,`prefix`),await this.writeOpfsMetadataSidecarUnlocked()})}catch(e){throw M(e,n)}this.watcher?.notify([{type:`delete`,path:n}])}async rmRecursiveUnlocked(e){let t=await this.lfs.readdir(e);for(let n of t){let t=e===`/`?`/${n}`:`${e}/${n}`,r=await this.lfs.lstat(t);r.isSymbolicLink()?await this.lfs.unlink(t):r.isDirectory()?await this.rmRecursiveUnlocked(t):await this.lfs.unlink(t)}await this.lfs.rmdir(e)}async stat(e){return this.withKindMismatchRetry(e,()=>this.statInner(e))}async statInner(e){let t=i(e),n=this.findMount(t);if(n){if(n.relParts.length===0)try{let e=await this.lfs.stat(t);return{type:`directory`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs}}catch{return{type:`directory`,size:0,mtime:Date.now(),ctime:Date.now()}}let e=n.relParts.join(`/`);try{let t=await n.backend.stat(e);return{type:t.kind===`directory`?`directory`:`file`,size:t.size,mtime:t.mtime,ctime:t.mtime}}catch(e){A(e,t)}}let r=await this.resolveSymlinks(t);try{let e=await this.lfs.stat(r);return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,ino:e.ino}}catch(e){throw M(e,t)}}async exists(e){let t=i(e),n=this.findMount(t);if(n){if(n.relParts.length===0)return!0;try{return await this.stat(t),!0}catch{return!1}}try{return await this.stat(t),!0}catch{try{return await this.lfs.lstat(t),!0}catch{return!1}}}async rename(e,t){return this.withKindMismatchRetryPaths([i(e),i(t)],()=>this.renameInner(e,t))}async renameInner(e,t){let n=i(e),r=i(t),a;try{a=(await this.lstat(n)).type}catch{}let o=this.findMount(n);if(o?.backend.rename){let e=this.findMount(r);if(e&&e.backend===o.backend){try{await o.backend.rename(o.relParts.join(`/`),e.relParts.join(`/`))}catch(e){A(e,n)}this.watcher?.notify([{type:`delete`,path:n,entryType:a},{type:`create`,path:r,entryType:a}]),this.mountIndex.notifyRename(n,r);return}}try{await this.withWriteLock(async()=>{this.markSidecarDirty(n,`prefix`),this.markSidecarDirty(r,`prefix`),await this.lfs.rename(n,r),await this.writeOpfsMetadataSidecarUnlocked()})}catch(e){throw M(e,n)}this.watcher?.notify([{type:`delete`,path:n,entryType:a},{type:`create`,path:r,entryType:a}]),this.mountIndex.notifyRename(n,r)}async readTextFile(e){return await this.readFile(e,{encoding:`utf-8`})}async*walk(e,t,n=0){yield*W({mountPoints:this.mountPoints,mountIndex:this.mountIndex,realpath:e=>this.realpath(e),readDir:e=>this.readDir(e),stat:e=>this.stat(e)},e,t,n)}async copyFile(e,t){if((await this.stat(e)).type===`directory`)throw new c(`EISDIR`,`is a directory`,e);let n=await this.readFile(e,{encoding:`binary`});await this.writeFile(t,n)}dirname(e){return n(i(e)).dir}basename(e){return n(i(e)).base}async symlink(e,t){let r=i(t);if(this.findMount(r))throw new c(`EINVAL`,`symlinks not supported on mounted filesystems`,r);let{dir:a}=n(r);await this.withWriteLock(async()=>{a!==`/`&&await this.mkdirRecursiveUnlocked(a);try{await this.lfs.symlink(e,r)}catch(t){if(a!==`/`&&t instanceof Error&&t.message.includes(`ENOENT`)){await this.mkdirRecursiveUnlocked(a);try{await this.lfs.symlink(e,r)}catch(e){throw M(e,r)}}else throw M(t,r)}this.markSidecarDirty(r),await this.writeOpfsMetadataSidecarUnlocked()}),this.watcher?.notify([{type:`create`,path:r,entryType:`symlink`}])}async readlink(e){let t=i(e);try{return await this.lfs.readlink(t)}catch(e){throw M(e,t)}}async lstat(e){let t=i(e);if(this.findMount(t)||t===`/`)return this.stat(t);try{let e=await this.lfs.lstat(t);if(e.isSymbolicLink()){let n=await this.lfs.readlink(t);return{type:`symlink`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,isSymlink:!0,symlinkTarget:n,ino:e.ino}}return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,ino:e.ino}}catch(e){throw M(e,t)}}async realpath(e){return B(this.lfs,e=>this.findMount(e)!==null,e)}resolveSymlinks(e){return V(this.lfs,e=>this.findMount(e)!==null,e)}},X=e({FsError:()=>c,FsWatcher:()=>C,MountIndex:()=>m,RestrictedFS:()=>k,VirtualFS:()=>Y,joinPath:()=>o,normalizePath:()=>i,pathSegments:()=>r,resolveVfsBackendFromEnv:()=>q,splitPath:()=>n});export{C as i,Y as n,k as r,X as t};
@@ -0,0 +1 @@
1
+ import"./proxied-fetch-BduXImRw.js";import{c as e,g as t,n}from"./account-store-DaG5fzPt.js";import{r}from"./api-endpoint-C00IT5T9.js";import{n as i}from"./tray-url-config-Cx0gvYq6.js";import{t as a}from"./tray-runtime-config-CjsIUSv2.js";import{t as o}from"./global-db-DJXlpNui.js";import{r as s,t as c}from"./silent-renew-backoff-C_Iv54ZG.js";import{getOAuthPageOrigin as l,resolveOAuthDelegation as u}from"./oauth-service-TDESX_tk.js";import"./provider-settings-ZgbgciKR.js";var d={clientId:``,scopes:`repo,read:user,user:email`};function f(){try{let e=localStorage.getItem(i);if(e)return e.replace(/\/$/,``)}catch{}return a}function p(e){return{access_token:e.access_token,token_type:e.token_type,scope:e.scope,refresh_token:e.refresh_token,expires_in:e.expires_in}}async function m(e){let t;try{t=await e.json()}catch{throw Error(`Token exchange failed (HTTP ${e.status}): non-JSON response`)}if(!e.ok&&e.status!==200){let n=t.error_description??t.error??`Token exchange failed (HTTP ${e.status})`;throw Error(n)}if(t.error){let e=t.error_description??t.error;throw Error(e)}return p(t)}async function h(e){let t=`${f()}/oauth/token`;return m(await fetch(t,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:e.provider,code:e.code,redirect_uri:e.redirectUri})}))}async function g(e){let t=`${f()}/oauth/token`;return m(await fetch(t,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:e.provider,refresh_token:e.refreshToken})}))}async function _(e){let t=`${f()}/oauth/revoke`,n=await fetch(t,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:e.provider,access_token:e.accessToken})});if(!(n.status===204||n.ok)){if(n.status===400)try{if((await n.json()).error===`unsupported`)return}catch{}throw Error(`Token revocation failed (HTTP ${n.status})`)}}const v=Object.assign({"/packages/webapp/providers/github-config.json":d})[`/packages/webapp/providers/github-config.json`]??{clientId:``,scopes:`repo,read:user,user:email`};let y=null,b=null;function x(e){let{isExtension:t,isConnectMode:n,workerBaseUrl:r,pageOrigin:i,pageHref:a,bridgeApiBaseUrl:o,extensionId:c,nonce:l}=e;if(t)return{redirectUri:`${r}/auth/callback`,state:{source:`extension`,extensionId:c,path:`/github`,nonce:l}};if(e.delegated)return{redirectUri:`${e.runtimeWorkerBaseUrl??r}/auth/callback`,state:{source:`opener`,path:`/auth/callback`,nonce:l}};if(n){let e=i??``;if(/^https?:\/\/(localhost|127\.0\.0\.1):\d+$/.test(e)){let t=parseInt(new URL(a??e).port||`8790`,10);return{redirectUri:`${r}/auth/callback`,state:{source:`local`,port:t,path:`/auth/callback`,nonce:l}}}return{redirectUri:`${r}/auth/callback`,state:{source:`remote`,origin:e,path:`/auth/callback`,nonce:l}}}if(o&&a&&s(a)){let t=null;try{let e=new URL(o);(e.hostname===`localhost`||e.hostname===`127.0.0.1`)&&(t=parseInt(e.port||`5710`,10))}catch{t=null}if(t!==null&&!Number.isNaN(t))return{redirectUri:`${e.runtimeWorkerBaseUrl??r}/auth/callback`,state:{source:`local`,port:t,path:`/auth/callback`,nonce:l}}}return{redirectUri:`${e.runtimeWorkerBaseUrl??i??``}/auth/callback`,state:{port:parseInt(new URL(a??i??`http://localhost:5710`).port||`5710`,10),path:`/auth/callback`,nonce:l}}}async function S(){if(y)return y;if(C){try{let e=await fetch(`${f()}/api/runtime-config`);if(e.ok){let t=await e.json();if(t.oauth?.github)return y=t.oauth.github,y}}catch{}return v.clientId}try{let e=await fetch(`/api/runtime-config`);if(e.ok){let t=await e.json();if(t.oauth?.github)return y=t.oauth.github,t.trayWorkerBaseUrl&&(b=t.trayWorkerBaseUrl),y;if(t.trayWorkerBaseUrl){b=t.trayWorkerBaseUrl;let e=await fetch(`${t.trayWorkerBaseUrl}/api/runtime-config`);if(e.ok){let t=await e.json();if(t.oauth?.github)return y=t.oauth.github,y}}}}catch{}return v.clientId}const C=typeof globalThis<`u`&&typeof globalThis.chrome?.runtime?.id==`string`;function w(){return n().find(e=>e.providerId===`github`)}function T(e){try{return new URL(e).searchParams.get(`code`)}catch{return null}}async function E(e){try{let t=await fetch(`https://api.github.com/user`,{headers:{Authorization:`Bearer ${e}`,Accept:`application/vnd.github+json`}});if(t.ok){let e=await t.json();return{name:e.name||e.login,avatar:e.avatar_url,login:e.login,id:e.id}}}catch(e){console.warn(`[github] Failed to fetch user profile:`,e instanceof Error?e.message:String(e))}return{}}function D(e,t){return`${e}+${t}@users.noreply.github.com`}async function O(e){try{let{VirtualFS:t}=await import(`./fs-DJCrdGnR.js`).then(e=>e.t);await(await t.create({dbName:o})).writeFile(`/workspace/.git/github-token`,e),typeof window<`u`&&window.dispatchEvent(new CustomEvent(`github-token-changed`))}catch(e){console.warn(`[github] Failed to write git token:`,e instanceof Error?e.message:String(e))}}async function k(){try{let{VirtualFS:e}=await import(`./fs-DJCrdGnR.js`).then(e=>e.t);await(await e.create({dbName:o})).rm(`/workspace/.git/github-token`),typeof window<`u`&&window.dispatchEvent(new CustomEvent(`github-token-changed`))}catch{}}async function A(e){if(!(!e.login||e.id===void 0))try{let{VirtualFS:t}=await import(`./fs-DJCrdGnR.js`).then(e=>e.t),{readGlobalGitConfigValue:n,writeGlobalGitConfigValue:r}=await import(`./git-config-Bdgu8kD2.js`).then(e=>e.n),i=await t.create({dbName:o}),a=e.name||e.login,s=D(e.id,e.login);!await n(i,`user.name`)&&a&&await r(i,`user.name`,a),await n(i,`user.email`)||await r(i,`user.email`,s)}catch(e){console.warn(`[github] Failed to seed git identity:`,e instanceof Error?e.message:String(e))}}const j=c();async function M(){try{let n=w();if(!n?.refreshToken)return null;let r=await g({provider:`github`,refreshToken:n.refreshToken});await t({providerId:`github`,accessToken:r.access_token,refreshToken:r.refresh_token,tokenExpiresAt:r.expires_in?Date.now()+r.expires_in*1e3:void 0,userName:n.userName,userAvatar:n.userAvatar,scopes:r.scope??n.scopes});let i=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`)}const P={id:`github`,name:`GitHub`,description:"Sign in with GitHub for git authentication (push/pull/clone) and the `oauth-token github` shell command. Does not expose LLM models — use the GitHub Copilot provider for those.",requiresApiKey:!1,requiresBaseUrl:!1,isOAuth:!0,oauthTokenDomains:[`github.com`,`*.github.com`,`api.github.com`,`raw.githubusercontent.com`],getModelIds:()=>[],onOAuthLogin:async(n,i,a)=>{let o=await S();if(!o)throw Error(`GitHub OAuth not configured — no client ID available`);let s=a?.scopes??v.scopes,c=C?null:await l(),d=!C&&await u(),p=crypto.randomUUID(),m=C?chrome.runtime.id:``,{redirectUri:g,state:_}=x({isExtension:C,isConnectMode:!!globalThis.__slicc_connect_mode,workerBaseUrl:f(),runtimeWorkerBaseUrl:b,pageOrigin:c?.origin??null,pageHref:c?.href??null,bridgeApiBaseUrl:r(),delegated:d,extensionId:m,nonce:p}),y=btoa(JSON.stringify(_)),w=p,D=new URLSearchParams({client_id:o,scope:s,redirect_uri:g});y&&D.set(`state`,y);let j=await n(`https://github.com/login/oauth/authorize?${D}`);if(!j)return;if(w)try{if(new URL(j).searchParams.get(`nonce`)!==w){console.error(`[github] OAuth nonce mismatch — possible CSRF`);return}}catch(e){console.warn(`[github] Nonce check skipped (URL parse failed):`,e instanceof Error?e.message:String(e))}let M=T(j);if(!M){console.error(`[github] Could not extract authorization code from redirect URL`);return}let N=await h({provider:`github`,code:M,redirectUri:g}),P=await E(N.access_token);await t({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),i()},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 t({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};
@@ -0,0 +1,2 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/fs-CsuRlf5M.js","assets/rolldown-runtime-Dd_uD5pT.js","assets/preload-helper-Czpn1I53.js","assets/logger-DDBAeTLF.js","assets/tool-ui-DfXu6quJ.js","assets/tool-ui-DCY2mIe9.js","assets/path-utils-DNJG-zQf.js","assets/types-idfTVsM8.js","assets/virtual-device-paths-D45tpPP6.js","assets/picker-approval-D89YhXsA.js","assets/html-B_Hg2WOy.js","assets/mount-picker-popup-C4q1Q3pK.js","assets/picker-popup-bwFI7R4q.js","assets/runtime-env-Dlaokqg1.js","assets/runtime-env-E-i2SW1s.js","assets/src-CAWTvdAa.js","assets/mount-table-store-dY2IfQ5S.js"])))=>i.map(i=>d[i]);
2
+ import{H as e,S as t,d as n}from"./account-store-8BBweMEe.js";import{t as r}from"./preload-helper-Czpn1I53.js";import"./proxied-fetch-CFWkfPNA.js";import{r as i,t as a}from"./silent-renew-backoff-t_Cd4Zw7.js";import{r as o}from"./api-endpoint-GRCyib6X.js";import{p as s,t as c}from"./tray-runtime-config-CluPgaPA.js";import"./main-Cj0dR__R.js";import{getOAuthPageOrigin as l,resolveOAuthDelegation as u}from"./oauth-service-NaEg6KHx.js";import{t as d}from"./global-db-CbuLl-zx.js";var f={clientId:``,scopes:`repo,read:user,user:email`};function p(){try{let e=localStorage.getItem(s);if(e)return e.replace(/\/$/,``)}catch{}return c}function m(e){return{access_token:e.access_token,token_type:e.token_type,scope:e.scope,refresh_token:e.refresh_token,expires_in:e.expires_in}}async function h(e){let t;try{t=await e.json()}catch{throw Error(`Token exchange failed (HTTP ${e.status}): non-JSON response`)}if(!e.ok&&e.status!==200){let n=t.error_description??t.error??`Token exchange failed (HTTP ${e.status})`;throw Error(n)}if(t.error){let e=t.error_description??t.error;throw Error(e)}return m(t)}async function g(e){let t=`${p()}/oauth/token`;return h(await fetch(t,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:e.provider,code:e.code,redirect_uri:e.redirectUri})}))}async function _(e){let t=`${p()}/oauth/token`;return h(await fetch(t,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:e.provider,refresh_token:e.refreshToken})}))}async function v(e){let t=`${p()}/oauth/revoke`,n=await fetch(t,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:e.provider,access_token:e.accessToken})});if(!(n.status===204||n.ok)){if(n.status===400)try{if((await n.json()).error===`unsupported`)return}catch{}throw Error(`Token revocation failed (HTTP ${n.status})`)}}var y=Object.assign({"/packages/webapp/providers/github-config.json":f})[`/packages/webapp/providers/github-config.json`]??{clientId:``,scopes:`repo,read:user,user:email`},b=null,x=null;function S(e){let{isExtension:t,isConnectMode:n,workerBaseUrl:r,pageOrigin:a,pageHref:o,bridgeApiBaseUrl:s,extensionId:c,nonce:l}=e;if(t)return{redirectUri:`${r}/auth/callback`,state:{source:`extension`,extensionId:c,path:`/github`,nonce:l}};if(e.delegated)return{redirectUri:`${e.runtimeWorkerBaseUrl??r}/auth/callback`,state:{source:`opener`,path:`/auth/callback`,nonce:l}};if(n){let e=a??``;if(/^https?:\/\/(localhost|127\.0\.0\.1):\d+$/.test(e)){let t=parseInt(new URL(o??e).port||`8790`,10);return{redirectUri:`${r}/auth/callback`,state:{source:`local`,port:t,path:`/auth/callback`,nonce:l}}}return{redirectUri:`${r}/auth/callback`,state:{source:`remote`,origin:e,path:`/auth/callback`,nonce:l}}}if(s&&o&&i(o)){let t=null;try{let e=new URL(s);(e.hostname===`localhost`||e.hostname===`127.0.0.1`)&&(t=parseInt(e.port||`5710`,10))}catch{t=null}if(t!==null&&!Number.isNaN(t))return{redirectUri:`${e.runtimeWorkerBaseUrl??r}/auth/callback`,state:{source:`local`,port:t,path:`/auth/callback`,nonce:l}}}return{redirectUri:`${e.runtimeWorkerBaseUrl??a??``}/auth/callback`,state:{port:parseInt(new URL(o??a??`http://localhost:5710`).port||`5710`,10),path:`/auth/callback`,nonce:l}}}async function C(){if(b)return b;if(w){try{let e=await fetch(`${p()}/api/runtime-config`);if(e.ok){let t=await e.json();if(t.oauth?.github)return b=t.oauth.github,b}}catch{}return y.clientId}try{let e=await fetch(`/api/runtime-config`);if(e.ok){let t=await e.json();if(t.oauth?.github)return b=t.oauth.github,t.trayWorkerBaseUrl&&(x=t.trayWorkerBaseUrl),b;if(t.trayWorkerBaseUrl){x=t.trayWorkerBaseUrl;let e=await fetch(`${t.trayWorkerBaseUrl}/api/runtime-config`);if(e.ok){let t=await e.json();if(t.oauth?.github)return b=t.oauth.github,b}}}}catch{}return y.clientId}var w=typeof globalThis<`u`&&typeof globalThis.chrome?.runtime?.id==`string`;function T(){return n().find(e=>e.providerId===`github`)}function E(e){try{return new URL(e).searchParams.get(`code`)}catch{return null}}async function D(e){try{let t=await fetch(`https://api.github.com/user`,{headers:{Authorization:`Bearer ${e}`,Accept:`application/vnd.github+json`}});if(t.ok){let e=await t.json();return{name:e.name||e.login,avatar:e.avatar_url,login:e.login,id:e.id}}}catch(e){console.warn(`[github] Failed to fetch user profile:`,e instanceof Error?e.message:String(e))}return{}}function O(e,t){return`${e}+${t}@users.noreply.github.com`}async function k(e){try{let{VirtualFS:t}=await r(async()=>{let{VirtualFS:e}=await import(`./fs-CsuRlf5M.js`).then(e=>e.t);return{VirtualFS:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]));await(await t.create({dbName:d})).writeFile(`/workspace/.git/github-token`,e),typeof window<`u`&&window.dispatchEvent(new CustomEvent(`github-token-changed`))}catch(e){console.warn(`[github] Failed to write git token:`,e instanceof Error?e.message:String(e))}}async function A(){try{let{VirtualFS:e}=await r(async()=>{let{VirtualFS:e}=await import(`./fs-CsuRlf5M.js`).then(e=>e.t);return{VirtualFS:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]));await(await e.create({dbName:d})).rm(`/workspace/.git/github-token`),typeof window<`u`&&window.dispatchEvent(new CustomEvent(`github-token-changed`))}catch{}}async function j(e){if(!(!e.login||e.id===void 0))try{let{VirtualFS:t}=await r(async()=>{let{VirtualFS:e}=await import(`./fs-CsuRlf5M.js`).then(e=>e.t);return{VirtualFS:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16])),{readGlobalGitConfigValue:n,writeGlobalGitConfigValue:i}=await r(async()=>{let{readGlobalGitConfigValue:e,writeGlobalGitConfigValue:t}=await import(`./git-config-D2u6LGfT.js`);return{readGlobalGitConfigValue:e,writeGlobalGitConfigValue:t}},[]),a=await t.create({dbName:d}),o=e.name||e.login,s=O(e.id,e.login);!await n(a,`user.name`)&&o&&await i(a,`user.name`,o),await n(a,`user.email`)||await i(a,`user.email`,s)}catch(e){console.warn(`[github] Failed to seed git identity:`,e instanceof Error?e.message:String(e))}}var M=a();async function N(){try{let n=T();if(!n?.refreshToken)return null;let r=await _({provider:`github`,refreshToken:n.refreshToken});await e({providerId:`github`,accessToken:r.access_token,refreshToken:r.refresh_token,tokenExpiresAt:r.expires_in?Date.now()+r.expires_in*1e3:void 0,userName:n.userName,userAvatar:n.userAvatar,scopes:r.scope??n.scopes});let i=t(`github`)?.maskedValue;return i?await k(i):await A(),r.access_token}catch(e){return console.warn(`[github] Silent renewal failed:`,e instanceof Error?e.message:String(e)),null}}async function P(){let e=T();if(!e?.accessToken)throw Error(`Not logged in to GitHub — please log in first`);if((e.tokenExpiresAt??1/0)-Date.now()>6e4)return e.accessToken;let t=await M.run(()=>N());if(t)return t;let n=T();if((n?.tokenExpiresAt??1/0)-Date.now()>0&&n?.accessToken)return n.accessToken;throw Error(`GitHub session expired — please log in again`)}var F={id:`github`,name:`GitHub`,description:"Sign in with GitHub for git authentication (push/pull/clone) and the `oauth-token github` shell command. Does not expose LLM models — use the GitHub Copilot provider for those.",requiresApiKey:!1,requiresBaseUrl:!1,isOAuth:!0,oauthTokenDomains:[`github.com`,`*.github.com`,`api.github.com`,`raw.githubusercontent.com`],getModelIds:()=>[],onOAuthLogin:async(n,r,i)=>{let a=await C();if(!a)throw Error(`GitHub OAuth not configured — no client ID available`);let s=i?.scopes??y.scopes,c=w?null:await l(),d=!w&&await u(),f=crypto.randomUUID(),m=w?chrome.runtime.id:``,{redirectUri:h,state:_}=S({isExtension:w,isConnectMode:!!globalThis.__slicc_connect_mode,workerBaseUrl:p(),runtimeWorkerBaseUrl:x,pageOrigin:c?.origin??null,pageHref:c?.href??null,bridgeApiBaseUrl:o(),delegated:d,extensionId:m,nonce:f}),v=btoa(JSON.stringify(_)),b=f,T=new URLSearchParams({client_id:a,scope:s,redirect_uri:h});v&&T.set(`state`,v);let O=await n(`https://github.com/login/oauth/authorize?${T}`);if(!O)return;if(b)try{if(new URL(O).searchParams.get(`nonce`)!==b){console.error(`[github] OAuth nonce mismatch — possible CSRF`);return}}catch(e){console.warn(`[github] Nonce check skipped (URL parse failed):`,e instanceof Error?e.message:String(e))}let M=E(O);if(!M){console.error(`[github] Could not extract authorization code from redirect URL`);return}let N=await g({provider:`github`,code:M,redirectUri:h}),P=await D(N.access_token);await e({providerId:`github`,accessToken:N.access_token,refreshToken:N.refresh_token,tokenExpiresAt:N.expires_in?Date.now()+N.expires_in*1e3:void 0,userName:P.name,userAvatar:P.avatar,scopes:N.scope});let F=t(`github`)?.maskedValue;F?await k(F):await A(),await j(P),r()},onSilentRenew:N,getValidAccessToken:P,onOAuthLogout:async()=>{let t=T();t?.accessToken&&await v({provider:`github`,accessToken:t.accessToken}).catch(e=>console.warn(`[github] Token revocation failed:`,e instanceof Error?e.message:String(e))),await A(),await e({providerId:`github`,accessToken:``})},getOAuthLogoutUrl:e=>`https://github.com/logout`};export{O as buildNoreplyEmail,F as config,E as extractCodeFromUrl,P as getValidAccessToken,S as resolveGithubOAuthRedirect,j as syncGitIdentityFromGitHub};