sliccy 6.192.0 → 6.193.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (163) hide show
  1. package/dist/ui/.vite/manifest.json +182 -182
  2. package/dist/ui/assets/{MEMORY-CbB3xjAS.js → MEMORY-B9cGngY_.js} +6 -1
  3. package/dist/ui/assets/{SKILL-Be-LbAuP.js → SKILL-CVh4bFFa.js} +1 -1
  4. package/dist/ui/assets/{account-store-Bevys7WL.js → account-store-SimIXg8S.js} +1 -1
  5. package/dist/ui/assets/{account-store-irTFXEHq.js → account-store-b2cIu79O.js} +1 -1
  6. package/dist/ui/assets/adobe-BXH1mZBP.js +1 -0
  7. package/dist/ui/assets/{adobe-CxPY_Nvf.js → adobe-Baxaw9tF.js} +1 -1
  8. package/dist/ui/assets/{agent-panels-CDAHwcGe.js → agent-panels-SuTziiZF.js} +1 -1
  9. package/dist/ui/assets/{almost-bash-shell-headless-B6lKPYip.js → almost-bash-shell-headless-KRKIc_BC.js} +458 -458
  10. package/dist/ui/assets/{apply-layout-BaPTlEmq.js → apply-layout-BMXr012X.js} +1 -1
  11. package/dist/ui/assets/{apps-CWLDElDt.js → apps-ClHDPvz3.js} +1 -1
  12. package/dist/ui/assets/{azure-openai-CAmcCxYK.js → azure-openai-DBM2Ldvh.js} +1 -1
  13. package/dist/ui/assets/{azure-openai-BrEMU1w0.js → azure-openai-DLiuqAAg.js} +1 -1
  14. package/dist/ui/assets/{backend-hostfs-DVOOQmWO.js → backend-hostfs-CMvkeWSE.js} +1 -1
  15. package/dist/ui/assets/{browser-DL3zbJrM.js → browser-Don7GC1D.js} +16 -16
  16. package/dist/ui/assets/{cdp-l5Vq6Mtp.js → cdp-DDirvj-c.js} +1 -1
  17. package/dist/ui/assets/{cerebras-DyJkWRm7.js → cerebras-DuPDmIOB.js} +1 -1
  18. package/dist/ui/assets/{cerebras-COJ_qkGu.js → cerebras-lgyiolIY.js} +1 -1
  19. package/dist/ui/assets/{composer-speech-CYdWOXqF.js → composer-speech-DmZY4JVi.js} +1 -1
  20. package/dist/ui/assets/{connect-surface-DnaS1qCD.js → connect-surface-BOTHMD51.js} +1 -1
  21. package/dist/ui/assets/{cost-command-DC0JwdLM.js → cost-command-MXw_GKzX.js} +1 -1
  22. package/dist/ui/assets/{directed-approval-Bo1zb-ki.js → directed-approval-CerbvC2D.js} +1 -1
  23. package/dist/ui/assets/{emscripten-vfs-hook-DORb16y9.js → emscripten-vfs-hook-BuS59209.js} +1 -1
  24. package/dist/ui/assets/{ensure-speech-assets-DXQUrOok.js → ensure-speech-assets-p_8CXJAD.js} +1 -1
  25. package/dist/ui/assets/{frozen-archive-writer-C_qn0GDJ.js → frozen-archive-writer-CFfTnqU4.js} +2 -2
  26. package/dist/ui/assets/fs-BxDhct-3.js +1 -0
  27. package/dist/ui/assets/fs-C5DLxUuw.js +2 -0
  28. package/dist/ui/assets/{gelatiere-store-D0SzDyoX.js → gelatiere-store-BvgAd5Zk.js} +1 -1
  29. package/dist/ui/assets/{gelatiere-unit-D0eC3q8k.js → gelatiere-unit-s-jBG-uE.js} +1 -1
  30. package/dist/ui/assets/{github-DrXxnqrr.js → github-BXOGqSiK.js} +2 -2
  31. package/dist/ui/assets/{github-CMMdXD7-.js → github-DG9QiZYP.js} +1 -1
  32. package/dist/ui/assets/{github-auth-CVs8hOEW.js → github-auth-CwHehFvz.js} +1 -1
  33. package/dist/ui/assets/{github-copilot-BDW-hvGU.js → github-copilot-DGPlFE5e.js} +1 -1
  34. package/dist/ui/assets/{github-copilot-F_OWE6ig.js → github-copilot-Dt82sOhC.js} +1 -1
  35. package/dist/ui/assets/{github-install-B-rr32FO.js → github-install-jl4FPsHI.js} +1 -1
  36. package/dist/ui/assets/{github-zip-DA_-VtNu.js → github-zip-BAWKMgjN.js} +1 -1
  37. package/dist/ui/assets/{hear-B1QjKHJS.js → hear-TuDMtKj3.js} +1 -1
  38. package/dist/ui/assets/{help-C3q6Ha5a.js → help-BbUskVkl.js} +1 -1
  39. package/dist/ui/assets/{host-command-DTM6_CU_.js → host-command-D8TK1jxM.js} +1 -1
  40. package/dist/ui/assets/installer-08nILdgJ.js +4 -0
  41. package/dist/ui/assets/{js-realm-worker-CIzPgKVU.js → js-realm-worker-UfwUgA6T.js} +14 -14
  42. package/dist/ui/assets/{jsh-executor-8n8-NVRR.js → jsh-executor-DdHf6Js2.js} +2 -2
  43. package/dist/ui/assets/{kernel-worker-YhNfUQ_y.js → kernel-worker-DiHbIWEg.js} +62 -58
  44. package/dist/ui/assets/{lick-ws-bridge-CDPuY-EA.js → lick-ws-bridge-CtPW0aNT.js} +1 -1
  45. package/dist/ui/assets/{lick-ws-bridge-BWmnM4i8.js → lick-ws-bridge-Dglm_RzS.js} +1 -1
  46. package/dist/ui/assets/live-session-curation-BO60iZm7.js +1 -0
  47. package/dist/ui/assets/{live-session-snapshot-CAY9GlTD.js → live-session-snapshot-DSYdvZ1k.js} +1 -1
  48. package/dist/ui/assets/{local-llm-dPetWUMs.js → local-llm-CA-oC8S7.js} +1 -1
  49. package/dist/ui/assets/{local-llm-CsIWLXJ2.js → local-llm-hkLYzSvm.js} +1 -1
  50. package/dist/ui/assets/{main-DUD5pTDH.js → main-BcLR9n_M.js} +3 -3
  51. package/dist/ui/assets/{main-cherry-BoO4BB-J.js → main-cherry-D8lHtydB.js} +1 -1
  52. package/dist/ui/assets/memory-budget-CFfevxz_.js +1 -0
  53. package/dist/ui/assets/{memory-curation-seam-DFftwyHh.js → memory-curation-seam-BJN7RaZ_.js} +1 -1
  54. package/dist/ui/assets/{memory-health-DF6IEFmt.js → memory-health-CmDIs1jS.js} +1 -1
  55. package/dist/ui/assets/memory-write-execute-C6Ys0m3p.js +1 -0
  56. package/dist/ui/assets/{mount-BfPgf0TT.js → mount-3ssq_M3f.js} +1 -1
  57. package/dist/ui/assets/{mount-BsWbgqHU.js → mount-oJcDzYHJ.js} +3 -3
  58. package/dist/ui/assets/{new-session-n4ieWj9Q.js → new-session-DCVrxowi.js} +2 -2
  59. package/dist/ui/assets/{oauth-bootstrap-DEjPbx0S.js → oauth-bootstrap-D1FahnIy.js} +2 -2
  60. package/dist/ui/assets/{onboarding-orchestrator-DTq_WzOT.js → onboarding-orchestrator-UOkZjppy.js} +1 -1
  61. package/dist/ui/assets/{openai-codex-CZFJxrdp.js → openai-codex-B2yw-3yu.js} +1 -1
  62. package/dist/ui/assets/{openai-codex-CRBPHYXu.js → openai-codex-B5_xqxDd.js} +1 -1
  63. package/dist/ui/assets/{openrouter-Bp2hCSj0.js → openrouter-BfigMcxO.js} +1 -1
  64. package/dist/ui/assets/{openrouter-xrK_Q7tb.js → openrouter-BwQeVkB-.js} +1 -1
  65. package/dist/ui/assets/{openrouter-free-B1aHr6YX.js → openrouter-free-B_pyNu1H.js} +1 -1
  66. package/dist/ui/assets/{openrouter-free-Ciud-jQF.js → openrouter-free-Cmp0KK1x.js} +1 -1
  67. package/dist/ui/assets/{openrouter-oauth-BShl7mda.js → openrouter-oauth-CjE2dXpj.js} +1 -1
  68. package/dist/ui/assets/{openrouter-oauth-CBNfp9B7.js → openrouter-oauth-DxX2hvVP.js} +1 -1
  69. package/dist/ui/assets/{opfs-mount-DF1_TQm7.js → opfs-mount-5UoVuxDu.js} +1 -1
  70. package/dist/ui/assets/{panel-rpc-handlers-DYotibPR.js → panel-rpc-handlers-bRzKgfVJ.js} +2 -2
  71. package/dist/ui/assets/{panelize-shell-5hKkbwSl.js → panelize-shell-DAt5CNbQ.js} +1 -1
  72. package/dist/ui/assets/{pi-edit-execution-CcLt8vSI.js → pi-edit-execution-CUuZWLzj.js} +1 -1
  73. package/dist/ui/assets/{provider-BLshPMsZ.js → provider-BCi9Lt4r.js} +2 -2
  74. package/dist/ui/assets/{provider-DqEfigmv.js → provider-aSGF7d4k.js} +1 -1
  75. package/dist/ui/assets/{provider-settings-BuaTQYid.js → provider-settings-DBgiE3eI.js} +1 -1
  76. package/dist/ui/assets/provider-store-access-B-R3ftEl.js +1 -0
  77. package/dist/ui/assets/provider-store-access-DWKXxpFB.js +1 -0
  78. package/dist/ui/assets/{providers-CE4VqQs6.js → providers-CGp8gI0u.js} +2 -2
  79. package/dist/ui/assets/{providers-B3cOXz1H.js → providers-CuHIzVOH.js} +1 -1
  80. package/dist/ui/assets/{quick-llm-D1wGZooG.js → quick-llm-DoBxND6k.js} +1 -1
  81. package/dist/ui/assets/{realm-inprocess-Dcn5yLm3.js → realm-inprocess-CtMTK-aN.js} +11 -11
  82. package/dist/ui/assets/{realm-unhandled-rejections-BU76F0PI.js → realm-unhandled-rejections-Dqt1Gk_j.js} +1 -1
  83. package/dist/ui/assets/{realm-unhandled-rejections-BXxVemlU.js → realm-unhandled-rejections-mGOVnR3q.js} +1 -1
  84. package/dist/ui/assets/{recovery-screen-D6HBp0xj.js → recovery-screen-B5zo1B0l.js} +1 -1
  85. package/dist/ui/assets/{remote-terminal-view-BDO5t9M_.js → remote-terminal-view-DDLUNW_y.js} +2 -2
  86. package/dist/ui/assets/{restore-CdH_ze1C.js → restore-Dd8d_Hgn.js} +1 -1
  87. package/dist/ui/assets/{run-D2pF2y1_.js → run-6f72KPaA.js} +1 -1
  88. package/dist/ui/assets/{run-DNvbqTbo.js → run-Bksq7Mcn.js} +1 -1
  89. package/dist/ui/assets/{run-fHfrubKD.js → run-BtSi8XBr.js} +1 -1
  90. package/dist/ui/assets/{run-B4snw1GL.js → run-DFA1g9kE.js} +2 -2
  91. package/dist/ui/assets/{run-xrVX3llR.js → run-DSsM13ob.js} +1 -1
  92. package/dist/ui/assets/{run-C_6GKpBV.js → run-DaUWBY-8.js} +6 -5
  93. package/dist/ui/assets/{run-CK7bQLZ0.js → run-DthMAupa.js} +2 -2
  94. package/dist/ui/assets/{run-CkKb9UWF.js → run-TkhZNuOx.js} +2 -2
  95. package/dist/ui/assets/{run-DsYsM6Yl.js → run-pvy0ymSy.js} +1 -1
  96. package/dist/ui/assets/{session-command-memory-CGqbKVAE.js → session-command-memory-Bl7bZtJm.js} +2 -2
  97. package/dist/ui/assets/{session-jsonl-CgKvYDUr.js → session-jsonl-Bv4dRBT4.js} +1 -1
  98. package/dist/ui/assets/{session-jsonl-CbNA3lGB.js → session-jsonl-DrVVeoTe.js} +1 -1
  99. package/dist/ui/assets/{session-search-index-CKHuYyZd.js → session-search-index-DGDHOAzl.js} +2 -2
  100. package/dist/ui/assets/{setup-feature-flags-remote-DU_3gSCe.js → setup-feature-flags-remote-CIhV4D0j.js} +1 -1
  101. package/dist/ui/assets/{setup-model-catalog-CQmIQSJ6.js → setup-model-catalog-BVDWM2AV.js} +1 -1
  102. package/dist/ui/assets/{signed-fetch-DEi8arT4.js → signed-fetch-CI9UIEV3.js} +1 -1
  103. package/dist/ui/assets/{silent-renew-backoff-UU1St8tN.js → silent-renew-backoff-BcsYBz66.js} +1 -1
  104. package/dist/ui/assets/slicc-version-BUehjIK3.js +1 -0
  105. package/dist/ui/assets/{snapshot-BPuldVwP.js → snapshot-CuamLfhh.js} +1 -1
  106. package/dist/ui/assets/{snapshot-features-Ddz9jsBd.js → snapshot-features-C5OANvrP.js} +1 -1
  107. package/dist/ui/assets/{soundscape-Uopjnq2I.js → soundscape-BwoAG-sm.js} +1 -1
  108. package/dist/ui/assets/{speak-D_PLnidz.js → speak-DwgV2tTT.js} +1 -1
  109. package/dist/ui/assets/{sprinkle-manager-BpNh9Lri.js → sprinkle-manager-DNJheHds.js} +1 -1
  110. package/dist/ui/assets/{sprinkle-renderer-BljwWT0g.js → sprinkle-renderer-CumxYPMj.js} +1 -1
  111. package/dist/ui/assets/{ssh-DBPFvqmL.js → ssh-B58quV88.js} +1 -1
  112. package/dist/ui/assets/{state-CHrSe9Ro.js → state-D_VYopGz.js} +1 -1
  113. package/dist/ui/assets/{store-BvFCmAq8.js → store-DJqDctgs.js} +1 -1
  114. package/dist/ui/assets/{store-BikzV66S.js → store-Dr9vzNP5.js} +1 -1
  115. package/dist/ui/assets/{sudo-rquT1VWH.js → sudo-BlL3sTXW.js} +1 -1
  116. package/dist/ui/assets/{sudo-fs-C6r_MIIY.js → sudo-fs-CQphjEUf.js} +1 -1
  117. package/dist/ui/assets/{supervisor-MXcG8SU6.js → supervisor-smOiGe-0.js} +1 -1
  118. package/dist/ui/assets/{sync-dialog-zmsfROKR.js → sync-dialog-Dyg2UAEo.js} +1 -1
  119. package/dist/ui/assets/{transformers-env-DVU2J7Xd.js → transformers-env-UAM9w3LM.js} +1 -1
  120. package/dist/ui/assets/{tray-leader-5xt9j15D.js → tray-leader-DK60MjaP.js} +1 -1
  121. package/dist/ui/assets/{tray-leave-runtime-B5LmQl4b.js → tray-leave-runtime-xgABwff8.js} +1 -1
  122. package/dist/ui/assets/{tray-sidecar-pljn-63X.js → tray-sidecar-BASB7cHq.js} +1 -1
  123. package/dist/ui/assets/{upgrade-detection-Ta4nIJJR.js → upgrade-detection-CcWsY0kz.js} +1 -1
  124. package/dist/ui/assets/{upskill-lick-skip-IyN1i0IF.js → upskill-lick-skip-BXEN7tuy.js} +1 -1
  125. package/dist/ui/assets/{voice-reply-aiuvZ8F3.js → voice-reply-DiXcXbUh.js} +1 -1
  126. package/dist/ui/assets/{wc-attach-C1CTfWQ-.js → wc-attach-CY3wKM4q.js} +2 -2
  127. package/dist/ui/assets/{wc-browser-RbezSPht.js → wc-browser-DE6aJENW.js} +1 -1
  128. package/dist/ui/assets/{wc-computers-D4IEEM5M.js → wc-computers-C9GCAa4H.js} +1 -1
  129. package/dist/ui/assets/{wc-detached-CrVlYV_z.js → wc-detached-5v5K5mcQ.js} +1 -1
  130. package/dist/ui/assets/{wc-extension-BW5y8hdg.js → wc-extension-D52mizb7.js} +2 -2
  131. package/dist/ui/assets/{wc-follower-xchSJ13T.js → wc-follower-CJOYr6g8.js} +3 -3
  132. package/dist/ui/assets/{wc-follower-oauth-BArMqE7c.js → wc-follower-oauth-B-6WQQBu.js} +1 -1
  133. package/dist/ui/assets/{wc-gelatiere-CxGkXDNo.js → wc-gelatiere-B2Bep1GD.js} +1 -1
  134. package/dist/ui/assets/{wc-live-DdOUCb1z.js → wc-live-CvDfoeZP.js} +11 -6
  135. package/dist/ui/assets/{wc-nav-C-cqoNl9.js → wc-nav-TcvaUUjk.js} +2 -2
  136. package/dist/ui/assets/{wc-onboarding-CId-wqvG.js → wc-onboarding-CFQJPD-H.js} +2 -2
  137. package/dist/ui/assets/{wc-permissions-lj9xrdU-.js → wc-permissions-BN0L49tc.js} +2 -2
  138. package/dist/ui/assets/{wc-placeholder-bs83QBxc.js → wc-placeholder-C_2WDAIS.js} +3 -3
  139. package/dist/ui/assets/{wc-secret-request-BmVSG3Qe.js → wc-secret-request-Dg-LzTLD.js} +1 -1
  140. package/dist/ui/assets/{wc-settings-CE5aZbkW.js → wc-settings-qv3-GQuG.js} +3 -3
  141. package/dist/ui/assets/{wc-shell-DdSbkIp-.js → wc-shell-B2rVnxeB.js} +5 -5
  142. package/dist/ui/assets/{wc-shortcut-config-C2d66GP8.js → wc-shortcut-config-DxXBHdKj.js} +1 -1
  143. package/dist/ui/assets/{wc-sprinkles-ak7XBDCk.js → wc-sprinkles-RfofsinU.js} +2 -2
  144. package/dist/ui/assets/{wc-transcript-export-DYVbwupj.js → wc-transcript-export-DE4ckv6H.js} +2 -2
  145. package/dist/ui/assets/{wc-tray-CjkC7SwM.js → wc-tray-CBNoNpOV.js} +4 -4
  146. package/dist/ui/assets/welcome-detection-SGZmx8Ya.js +1 -0
  147. package/dist/ui/assets/{whisper-session-DBea3Pzc.js → whisper-session-Cl4_UhwI.js} +2 -2
  148. package/dist/ui/assets/{xai-grok-B-WV19uN.js → xai-grok-CQ-_7nZn.js} +1 -1
  149. package/dist/ui/assets/{xai-grok-CAPZiieq.js → xai-grok-DV6fnUIH.js} +1 -1
  150. package/dist/ui/index.html +3 -3
  151. package/dist/ui/packages/webapp/index.html +3 -3
  152. package/package.json +1 -1
  153. package/dist/ui/assets/adobe-C2Yk0FjU.js +0 -1
  154. package/dist/ui/assets/fs-D5UZBrBX.js +0 -1
  155. package/dist/ui/assets/fs-DouF0VP9.js +0 -2
  156. package/dist/ui/assets/installer-BamTBGiN.js +0 -4
  157. package/dist/ui/assets/live-session-curation-eGH4uyM1.js +0 -1
  158. package/dist/ui/assets/memory-budget-Bcf7Eolo.js +0 -1
  159. package/dist/ui/assets/memory-write-execute-C7SUGCPF.js +0 -1
  160. package/dist/ui/assets/provider-store-access-BABW1Cfu.js +0 -1
  161. package/dist/ui/assets/provider-store-access-C2xFS3NU.js +0 -1
  162. package/dist/ui/assets/slicc-version-D8Zbv4vp.js +0 -1
  163. package/dist/ui/assets/welcome-detection-BAQGL8Ld.js +0 -1
@@ -0,0 +1 @@
1
+ import{n as e}from"./wc-onboarding-CFQJPD-H.js";export{e as hasOnboardingFinalLickInHistory};
@@ -1,2 +1,2 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/speak-D_PLnidz.js","assets/preload-helper-Czpn1I53.js","assets/logger-DDBAeTLF.js","assets/runtime-env-Dlaokqg1.js","assets/speech-assets-bridge-CFYafE89.js","assets/transformers-env-DVU2J7Xd.js","assets/wc-shell-DdSbkIp-.js","assets/rolldown-runtime-Dd_uD5pT.js","assets/mime-types-D0xZwlMO.js","assets/base64-ELzoYfwP.js","assets/bridge-protocol-C52CnDIj.js","assets/account-store-Bevys7WL.js","assets/core-Be1yHH6v.js","assets/compat-qQM4gjF_.js","assets/models-BSkXF4T6.js","assets/diagnostics-DN_idNHx.js","assets/provider-env-CTOcDKrQ.js","assets/__vite-browser-external-5eBdwsFd.js","assets/openrouter.models-B-zmcypy.js","assets/libesm-BypnjKEL.js","assets/feature-flags-BftQitIZ.js","assets/proxied-fetch-DiXk_XGs.js","assets/fetch-body-1l9I58Vk.js","assets/api-endpoint-DuEQRZ4g.js","assets/secret-topology-CZv6A9HW.js","assets/float-topology-B0_dG7En.js","assets/secrets-bridge-client-B_CG-HIg.js","assets/port-bridge-client-BiWcfZSc.js","assets/image-markers-q8JQTtid.js","assets/tool-ui-eSQ1g2I1.js","assets/providers-CE4VqQs6.js","assets/panel-rpc-D3EPRnmw.js","assets/bedrock-camp-compat-Bz7u6y4g.js","assets/bedrock-camp-extra-models-IBZyfEdZ.js","assets/claude-model-version-DZmbk9E2.js","assets/telemetry-CKoAhRMv.js","assets/types-D8gIX-W-.js","assets/same-file-identity-DuEcSmPX.js","assets/icons-dEBJiC8z.js","assets/wc-shell-WkeczD9x.css","assets/shared-BDXQKitm.js","assets/transformers.web-BBJR2ai3.js"])))=>i.map(i=>d[i]);
2
- import{t as e}from"./preload-helper-Czpn1I53.js";import{t}from"./logger-DDBAeTLF.js";import{a as n,n as r,o as i,r as a,t as o}from"./transformers-env-DVU2J7Xd.js";var s=t(`speech:whisper`),c=null,l=`idle`,u=null,d=new Set;function f(){return l}function p(){return u}function m(e){return e&&d.add(e),c||=(l=`loading`,g().then(e=>(l=`ready`,h(),e),e=>{throw l=`failed`,c=null,s.error(`whisper load failed`,e),e})),c}function h(){e(async()=>{let{kokoroWarmup:e}=await import(`./speak-D_PLnidz.js`);return{kokoroWarmup:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40])).then(({kokoroWarmup:e})=>e()).catch(e=>s.warn(`kokoro warmup (chained after whisper) failed`,e))}async function g(){let{pipeline:t,env:c}=await e(async()=>{let{pipeline:e,env:t}=await import(`./transformers.web-BBJR2ai3.js`);return{pipeline:e,env:t}},__vite__mapDeps([41,7,1]));r(c),await o(n),await a();let l=i(),f=e=>{if(e?.file){if(e.status===`progress`)l.update(e.file,e.loaded??0,e.total??0);else if(e.status===`done`)l.complete(e.file);else return;u=l.snapshot();for(let e of d)e(u)}},p=async e=>await t(`automatic-speech-recognition`,n,{device:e,dtype:e===`webgpu`?`fp32`:`q8`,progress_callback:f}),m=typeof navigator<`u`&&`gpu`in navigator,h;if(m)try{h=await p(`webgpu`)}catch(e){s.warn(`whisper webgpu init failed; retrying on wasm`,e),h=await p(`wasm`)}else h=await p(`wasm`);return s.info(`whisper ready`,{model:n,device:m?`webgpu`:`wasm`}),{async transcribe(e,t){let n=performance.now(),r=await h(e,{chunk_length_s:30,task:`transcribe`,...t?.language?{language:t.language}:{}}),i=Array.isArray(r)?r.map(e=>e.text??``).join(` `):r.text??``;return s.info(`whisper transcribe`,{elapsedMs:Math.round(performance.now()-n),audioSeconds:Math.round(e.length/160)/100,numThreads:c.backends?.onnx?.wasm?.numThreads,device:m?`webgpu`:`wasm`}),i.trim()}}}var _=16e3;async function v(e){if(typeof AudioContext>`u`||typeof OfflineAudioContext>`u`)throw Error(`audio decoding requires a window/page realm (AudioContext unavailable)`);let t=new AudioContext,n;try{n=await t.decodeAudioData(e.slice(0))}finally{await t.close().catch(()=>{})}let r=Math.max(1,Math.ceil(n.duration*_)),i=new OfflineAudioContext(1,r,_),a=i.createBufferSource();return a.buffer=n,a.connect(i.destination),a.start(),(await i.startRendering()).getChannelData(0).slice(0)}var y=t(`speech:whisper-session`),b=2e3,x=500,S=5e3,C=3e4,w=(e,t,n)=>new Promise((r,i)=>{let a=setTimeout(()=>i(Error(`${n} timed out after ${t}ms`)),t);e.then(e=>{clearTimeout(a),r(e)},e=>{clearTimeout(a),i(e)})});function T(e){return e?.split(`-`)[0]?.toLowerCase()||void 0}async function E(e,t){let n;if(t.stream)n=t.stream;else{if(!navigator.mediaDevices?.getUserMedia)throw Error(`microphone capture unavailable in this realm`);n=await navigator.mediaDevices.getUserMedia({audio:t.deviceId&&t.deviceId!=="default"?{deviceId:{exact:t.deviceId}}:!0})}let r=new MediaRecorder(n),i=[],a=T(t.lang),o=!1,s=!1;r.ondataavailable=e=>{e.data.size>0&&i.push(e.data)};let c=async()=>{if(i.length===0)return``;let t=await v(await new Blob(i,{type:r.mimeType||`audio/webm`}).arrayBuffer());return e.transcribe(t,{language:a})},l=Promise.resolve(``),u=()=>{let e=l.catch(()=>``).then(()=>c());return l=e.catch(()=>``),e},d=setInterval(()=>{o||s||i.length===0||(o=!0,u().then(e=>{!s&&e&&t.onPartial?.(e)}).catch(e=>{y.warn(`partial transcription failed`,e)}).finally(()=>{o=!1}))},b),f=()=>{if(clearInterval(d),r.state!==`inactive`)try{r.stop()}catch{}for(let e of n.getTracks())e.stop()},p=()=>new Promise(e=>{if(r.state===`inactive`){e();return}r.onstop=()=>e();try{r.stop()}catch{e()}});return r.start(x),{async stop(){if(s)return``;s=!0,clearInterval(d);try{await w(p(),S,`recorder flush`);for(let e of n.getTracks())e.stop();return await w(u(),C,`transcription`)}catch(e){for(let e of n.getTracks())e.stop();let r=e instanceof Error?e.message:String(e);return t.onError?.(`transcription failed: ${r}`),``}},cancel(){s||(s=!0,f())}}}export{p as a,m as i,T as n,f as o,v as r,E as t};
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/speak-DwgV2tTT.js","assets/preload-helper-Czpn1I53.js","assets/logger-DDBAeTLF.js","assets/runtime-env-Dlaokqg1.js","assets/speech-assets-bridge-CFYafE89.js","assets/transformers-env-UAM9w3LM.js","assets/wc-shell-B2rVnxeB.js","assets/rolldown-runtime-Dd_uD5pT.js","assets/mime-types-D0xZwlMO.js","assets/base64-ELzoYfwP.js","assets/bridge-protocol-C52CnDIj.js","assets/account-store-SimIXg8S.js","assets/core-Be1yHH6v.js","assets/compat-qQM4gjF_.js","assets/models-BSkXF4T6.js","assets/diagnostics-DN_idNHx.js","assets/provider-env-CTOcDKrQ.js","assets/__vite-browser-external-5eBdwsFd.js","assets/openrouter.models-B-zmcypy.js","assets/libesm-BypnjKEL.js","assets/feature-flags-BftQitIZ.js","assets/proxied-fetch-DiXk_XGs.js","assets/fetch-body-1l9I58Vk.js","assets/api-endpoint-DuEQRZ4g.js","assets/secret-topology-CZv6A9HW.js","assets/float-topology-B0_dG7En.js","assets/secrets-bridge-client-B_CG-HIg.js","assets/port-bridge-client-BiWcfZSc.js","assets/image-markers-q8JQTtid.js","assets/tool-ui-eSQ1g2I1.js","assets/providers-CGp8gI0u.js","assets/panel-rpc-D3EPRnmw.js","assets/bedrock-camp-compat-Bz7u6y4g.js","assets/bedrock-camp-extra-models-IBZyfEdZ.js","assets/claude-model-version-DZmbk9E2.js","assets/telemetry-CKoAhRMv.js","assets/types-D8gIX-W-.js","assets/same-file-identity-DuEcSmPX.js","assets/icons-dEBJiC8z.js","assets/wc-shell-WkeczD9x.css","assets/shared-BDXQKitm.js","assets/transformers.web-BBJR2ai3.js"])))=>i.map(i=>d[i]);
2
+ import{t as e}from"./preload-helper-Czpn1I53.js";import{t}from"./logger-DDBAeTLF.js";import{a as n,n as r,o as i,r as a,t as o}from"./transformers-env-UAM9w3LM.js";var s=t(`speech:whisper`),c=null,l=`idle`,u=null,d=new Set;function f(){return l}function p(){return u}function m(e){return e&&d.add(e),c||=(l=`loading`,g().then(e=>(l=`ready`,h(),e),e=>{throw l=`failed`,c=null,s.error(`whisper load failed`,e),e})),c}function h(){e(async()=>{let{kokoroWarmup:e}=await import(`./speak-DwgV2tTT.js`);return{kokoroWarmup:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40])).then(({kokoroWarmup:e})=>e()).catch(e=>s.warn(`kokoro warmup (chained after whisper) failed`,e))}async function g(){let{pipeline:t,env:c}=await e(async()=>{let{pipeline:e,env:t}=await import(`./transformers.web-BBJR2ai3.js`);return{pipeline:e,env:t}},__vite__mapDeps([41,7,1]));r(c),await o(n),await a();let l=i(),f=e=>{if(e?.file){if(e.status===`progress`)l.update(e.file,e.loaded??0,e.total??0);else if(e.status===`done`)l.complete(e.file);else return;u=l.snapshot();for(let e of d)e(u)}},p=async e=>await t(`automatic-speech-recognition`,n,{device:e,dtype:e===`webgpu`?`fp32`:`q8`,progress_callback:f}),m=typeof navigator<`u`&&`gpu`in navigator,h;if(m)try{h=await p(`webgpu`)}catch(e){s.warn(`whisper webgpu init failed; retrying on wasm`,e),h=await p(`wasm`)}else h=await p(`wasm`);return s.info(`whisper ready`,{model:n,device:m?`webgpu`:`wasm`}),{async transcribe(e,t){let n=performance.now(),r=await h(e,{chunk_length_s:30,task:`transcribe`,...t?.language?{language:t.language}:{}}),i=Array.isArray(r)?r.map(e=>e.text??``).join(` `):r.text??``;return s.info(`whisper transcribe`,{elapsedMs:Math.round(performance.now()-n),audioSeconds:Math.round(e.length/160)/100,numThreads:c.backends?.onnx?.wasm?.numThreads,device:m?`webgpu`:`wasm`}),i.trim()}}}var _=16e3;async function v(e){if(typeof AudioContext>`u`||typeof OfflineAudioContext>`u`)throw Error(`audio decoding requires a window/page realm (AudioContext unavailable)`);let t=new AudioContext,n;try{n=await t.decodeAudioData(e.slice(0))}finally{await t.close().catch(()=>{})}let r=Math.max(1,Math.ceil(n.duration*_)),i=new OfflineAudioContext(1,r,_),a=i.createBufferSource();return a.buffer=n,a.connect(i.destination),a.start(),(await i.startRendering()).getChannelData(0).slice(0)}var y=t(`speech:whisper-session`),b=2e3,x=500,S=5e3,C=3e4,w=(e,t,n)=>new Promise((r,i)=>{let a=setTimeout(()=>i(Error(`${n} timed out after ${t}ms`)),t);e.then(e=>{clearTimeout(a),r(e)},e=>{clearTimeout(a),i(e)})});function T(e){return e?.split(`-`)[0]?.toLowerCase()||void 0}async function E(e,t){let n;if(t.stream)n=t.stream;else{if(!navigator.mediaDevices?.getUserMedia)throw Error(`microphone capture unavailable in this realm`);n=await navigator.mediaDevices.getUserMedia({audio:t.deviceId&&t.deviceId!=="default"?{deviceId:{exact:t.deviceId}}:!0})}let r=new MediaRecorder(n),i=[],a=T(t.lang),o=!1,s=!1;r.ondataavailable=e=>{e.data.size>0&&i.push(e.data)};let c=async()=>{if(i.length===0)return``;let t=await v(await new Blob(i,{type:r.mimeType||`audio/webm`}).arrayBuffer());return e.transcribe(t,{language:a})},l=Promise.resolve(``),u=()=>{let e=l.catch(()=>``).then(()=>c());return l=e.catch(()=>``),e},d=setInterval(()=>{o||s||i.length===0||(o=!0,u().then(e=>{!s&&e&&t.onPartial?.(e)}).catch(e=>{y.warn(`partial transcription failed`,e)}).finally(()=>{o=!1}))},b),f=()=>{if(clearInterval(d),r.state!==`inactive`)try{r.stop()}catch{}for(let e of n.getTracks())e.stop()},p=()=>new Promise(e=>{if(r.state===`inactive`){e();return}r.onstop=()=>e();try{r.stop()}catch{e()}});return r.start(x),{async stop(){if(s)return``;s=!0,clearInterval(d);try{await w(p(),S,`recorder flush`);for(let e of n.getTracks())e.stop();return await w(u(),C,`transcription`)}catch(e){for(let e of n.getTracks())e.stop();let r=e instanceof Error?e.message:String(e);return t.onError?.(`transcription failed: ${r}`),``}},cancel(){s||(s=!0,f())}}}export{p as a,m as i,T as n,f as o,v as r,E as t};
@@ -1 +1 @@
1
- import{_ as e,r as t}from"./account-store-irTFXEHq.js";import{a as n}from"./diagnostics-DN_idNHx.js";import{a as r}from"./compat-uEPf6-XW.js";import{s as i}from"./core-PJsXG3mm.js";import{c as a,i as o,r as s,s as c}from"./legacy-api-aliases-jKEvBgOL.js";import"./provider-settings-BuaTQYid.js";import{n as l,r as u}from"./bridge-token-required-BYgoMwr7.js";import{n as d,r as f,t as p}from"./pkce-hGf_TEnP.js";import{XaiErrorCode as m,XaiOAuthError as h}from"./xai-grok-errors-ByEMMSoz.js";function g(e){return typeof e==`object`&&!!e}function _(e){if(!g(e))return null;let t=g(e.config)?e.config:e,n=t.creditUsagePercent;if(typeof n!=`number`||!Number.isFinite(n))return null;let r=Math.min(1e3,Math.max(0,n)),i=g(t.currentPeriod)?t.currentPeriod:{},a=i.type,o=typeof a==`string`?a.replace(`USAGE_PERIOD_TYPE_`,``).toLowerCase():``,s=i.end??t.billingPeriodEnd,c=typeof s==`string`&&Number.isFinite(Date.parse(s))?s:void 0;return{percent:r,status:`ok`,window:o&&o!==`unspecified`?o:`billing`,...c?{resetsAt:c}:{}}}async function v(e,t,n={}){let r=new AbortController,i=setTimeout(()=>r.abort(),n.timeoutMs??8e3);try{let n=await t(`https://cli-chat-proxy.grok.com/v1/billing?format=credits`,{headers:{Authorization:`Bearer ${e}`},signal:r.signal}),{status:i}=n;if(i===404||i===501)return null;if(!n.ok)throw Error(`xAI Grok usage: ${i===401||i===403?`re-login required`:`failed`} (${i})`);let a=await n.text();if(a.length>65536)return null;try{return _(JSON.parse(a))}catch{return null}}finally{clearTimeout(i)}}const y=`xai-grok`,b=`https://auth.x.ai`,x=`${b}/oauth2/authorize`,S=`${b}/oauth2/token`,C=`b1a00492-073a-47ea-816f-4c329264a828`,w=`http://127.0.0.1:56121/callback`,T=`https://api.x.ai/v1`,E=`grok-4.7`,D=`${y}-openai`;function O(e){if(e.some(e=>e.id===E))return e;let t=e.find(e=>e.id===`grok-4.6`)??e.find(e=>e.api===`openai-responses`)??e[0];return t?[{...t,id:E,name:`Grok 4.7`,api:`openai-responses`,reasoning:!0,input:[`text`,`image`],cost:{input:2,output:6,cacheRead:.5,cacheWrite:0},contextWindow:5e5,maxTokens:5e5,thinkingLevelMap:{off:null,minimal:null,low:`low`,medium:`medium`,high:`high`,xhigh:`xhigh`,max:null}},...e]:e}function k(){return O(i(`xai`))}function A(e){return{id:e.id,name:e.name,api:`openai`,reasoning:e.reasoning,input:e.input,context_window:e.contextWindow,max_tokens:e.maxTokens,compat:e.compat,thinkingLevelMap:e.thinkingLevelMap,cost:e.cost}}function j(e){let t=k(),n=t.find(t=>t.id===e.id);if(!n&&(console.warn(`xAI model "${e.id}" is no longer in the pi-ai catalog; falling back to default "${E}"`),n=t.find(e=>e.id===E),!n))throw Error(`xAI default model "${E}" is not registered by pi-ai`);if(n.api!==`openai-responses`&&n.api!==`openai-completions`)throw Error(`Unsupported pi-ai API "${n.api}" for xAI model "${e.id}"`);return{...e,...n,baseUrl:T}}async function M(e,t){let n=new URLSearchParams({grant_type:`authorization_code`,code:e,redirect_uri:w,client_id:C,code_verifier:t}),r=await fetch(S,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`},body:n});if(!r.ok)throw new h(`xAI token exchange failed: ${r.status} ${await r.text()}`,m.TOKEN_EXCHANGE_FAILED);let i=await r.json();if(!i.access_token)throw new h(`xAI token exchange did not return access_token.`,m.TOKEN_EXCHANGE_INVALID);return i}async function N(e){if(l())return null;try{let t=new URLSearchParams({grant_type:`refresh_token`,refresh_token:e,client_id:C}),n=await fetch(S,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`},body:t});if(!n.ok){let e=await n.text();return u(n.status,e)||console.error(`[xai-grok] refresh failed:`,n.status,e),null}return await n.json()}catch(e){return console.error(`[xai-grok] refresh error:`,e instanceof Error?e.message:String(e)),null}}function P(){return t().find(e=>e.providerId===y)}async function F(){let t=P();if(!t?.accessToken)throw new h("Not signed in to xAI Grok — run /login or `oauth-token xai-grok`",m.AUTH_MISSING,!0);let n=t.tokenExpiresAt??0;if(n&&Date.now()+6e4<n)return t.accessToken;if(t.refreshToken){let n=await N(t.refreshToken);if(n?.access_token)return await e({providerId:y,accessToken:n.access_token,refreshToken:n.refresh_token??t.refreshToken,tokenExpiresAt:Date.now()+(n.expires_in??21600)*1e3,scopes:n.scope??t.scopes}),n.access_token}return t.accessToken}async function I(){if(!P()?.accessToken)throw Error(`xAI Grok budget: not signed in`);return v(await F(),fetch)}function L(e,t){return{type:`error`,reason:`error`,error:{role:`assistant`,content:[],api:D,provider:y,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 R(e,t){return t?{...e??{},"x-grok-conv-id":t}:e}function z(e){console.error(`[xai-grok] Stream error:`,e instanceof Error?e.message:String(e))}async function B(e,t,n,r){try{let i=await F(),a=r.sessionId,c=j(t),l={...r,apiKey:i,headers:R(r.headers,a)},u=c.api===`openai-responses`?o(c,n,l):s(c,n,l);for await(let t of u)e.push(t);e.end()}catch(n){z(n),e.push(L(t,n)),e.end()}}async function V(e,t,n,r){try{let i=await F(),o=r?.sessionId,s=j(t),l={...r,apiKey:i,headers:R(r?.headers,o)},u=s.api===`openai-responses`?a(s,n,l):c(s,n,l);for await(let t of u)e.push(t);e.end()}catch(n){z(n),e.push(L(t,n)),e.end()}}const H=(e,t,r={})=>{let i=n();return B(i,e,t,r).catch(z),i},U=(e,t,r)=>{let i=n();return V(i,e,t,r).catch(z),i},W={id:y,name:`xAI Grok (SuperGrok OAuth)`,description:`Grok via xAI OAuth — uses your SuperGrok subscription, no API key needed. Default model is Grok 4.7.`,requiresApiKey:!1,requiresBaseUrl:!1,isOAuth:!0,defaultModelId:E,oauthTokenDomains:[`api.x.ai`,`*.x.ai`,`auth.x.ai`,`accounts.x.ai`,`cli-chat-proxy.grok.com`],getModelIds:()=>k().map(A),getBudgetUsage:I,onOAuthLoginIntercepted:async(t,n,r)=>{let i=d(),a=await p(i),o=f(),s=f(),c=new URL(x);c.searchParams.set(`response_type`,`code`),c.searchParams.set(`client_id`,C),c.searchParams.set(`redirect_uri`,w),c.searchParams.set(`scope`,r?.scopes??`openid profile email offline_access grok-cli:access api:access`),c.searchParams.set(`code_challenge`,a),c.searchParams.set(`code_challenge_method`,`S256`),c.searchParams.set(`state`,o),c.searchParams.set(`nonce`,s),c.searchParams.set(`plan`,`generic`),c.searchParams.set(`referrer`,`slicc`);let l=await t({authorizeUrl:c.toString(),redirectUriPattern:`http://127.0.0.1:56121/*`,onCapture:`close`});if(!l)throw new h(`xAI OAuth login was cancelled or timed out`,m.CALLBACK_TIMEOUT);let u=new URL(l),g=u.searchParams.get(`code`),_=u.searchParams.get(`state`);if(!g)throw new h(`xAI OAuth redirect did not include a code`,m.CODE_MISSING);if(_!==o)throw new h(`xAI OAuth state mismatch — possible CSRF, aborting`,m.STATE_MISMATCH);let v=await M(g,i);await e({providerId:y,accessToken:v.access_token,refreshToken:v.refresh_token,tokenExpiresAt:Date.now()+(v.expires_in??21600)*1e3,baseUrl:T,scopes:v.scope}),n()},onOAuthLogout:async()=>{await e({providerId:y,accessToken:``})},onSilentRenew:async()=>{let t=P();if(!t?.refreshToken)return null;let n=await N(t.refreshToken);return n?.access_token?(await e({providerId:y,accessToken:n.access_token,refreshToken:n.refresh_token??t.refreshToken,tokenExpiresAt:Date.now()+(n.expires_in??21600)*1e3,scopes:n.scope??t.scopes}),n.access_token):null}};function G(){r({api:D,stream:H,streamSimple:U})}export{m as XaiErrorCode,h as XaiOAuthError,W as config,G as register};
1
+ import{_ as e,r as t}from"./account-store-b2cIu79O.js";import{a as n}from"./diagnostics-DN_idNHx.js";import{a as r}from"./compat-uEPf6-XW.js";import{s as i}from"./core-PJsXG3mm.js";import{c as a,i as o,r as s,s as c}from"./legacy-api-aliases-jKEvBgOL.js";import"./provider-settings-DBgiE3eI.js";import{n as l,r as u}from"./bridge-token-required-BYgoMwr7.js";import{n as d,r as f,t as p}from"./pkce-hGf_TEnP.js";import{XaiErrorCode as m,XaiOAuthError as h}from"./xai-grok-errors-ByEMMSoz.js";function g(e){return typeof e==`object`&&!!e}function _(e){if(!g(e))return null;let t=g(e.config)?e.config:e,n=t.creditUsagePercent;if(typeof n!=`number`||!Number.isFinite(n))return null;let r=Math.min(1e3,Math.max(0,n)),i=g(t.currentPeriod)?t.currentPeriod:{},a=i.type,o=typeof a==`string`?a.replace(`USAGE_PERIOD_TYPE_`,``).toLowerCase():``,s=i.end??t.billingPeriodEnd,c=typeof s==`string`&&Number.isFinite(Date.parse(s))?s:void 0;return{percent:r,status:`ok`,window:o&&o!==`unspecified`?o:`billing`,...c?{resetsAt:c}:{}}}async function v(e,t,n={}){let r=new AbortController,i=setTimeout(()=>r.abort(),n.timeoutMs??8e3);try{let n=await t(`https://cli-chat-proxy.grok.com/v1/billing?format=credits`,{headers:{Authorization:`Bearer ${e}`},signal:r.signal}),{status:i}=n;if(i===404||i===501)return null;if(!n.ok)throw Error(`xAI Grok usage: ${i===401||i===403?`re-login required`:`failed`} (${i})`);let a=await n.text();if(a.length>65536)return null;try{return _(JSON.parse(a))}catch{return null}}finally{clearTimeout(i)}}const y=`xai-grok`,b=`https://auth.x.ai`,x=`${b}/oauth2/authorize`,S=`${b}/oauth2/token`,C=`b1a00492-073a-47ea-816f-4c329264a828`,w=`http://127.0.0.1:56121/callback`,T=`https://api.x.ai/v1`,E=`grok-4.7`,D=`${y}-openai`;function O(e){if(e.some(e=>e.id===E))return e;let t=e.find(e=>e.id===`grok-4.6`)??e.find(e=>e.api===`openai-responses`)??e[0];return t?[{...t,id:E,name:`Grok 4.7`,api:`openai-responses`,reasoning:!0,input:[`text`,`image`],cost:{input:2,output:6,cacheRead:.5,cacheWrite:0},contextWindow:5e5,maxTokens:5e5,thinkingLevelMap:{off:null,minimal:null,low:`low`,medium:`medium`,high:`high`,xhigh:`xhigh`,max:null}},...e]:e}function k(){return O(i(`xai`))}function A(e){return{id:e.id,name:e.name,api:`openai`,reasoning:e.reasoning,input:e.input,context_window:e.contextWindow,max_tokens:e.maxTokens,compat:e.compat,thinkingLevelMap:e.thinkingLevelMap,cost:e.cost}}function j(e){let t=k(),n=t.find(t=>t.id===e.id);if(!n&&(console.warn(`xAI model "${e.id}" is no longer in the pi-ai catalog; falling back to default "${E}"`),n=t.find(e=>e.id===E),!n))throw Error(`xAI default model "${E}" is not registered by pi-ai`);if(n.api!==`openai-responses`&&n.api!==`openai-completions`)throw Error(`Unsupported pi-ai API "${n.api}" for xAI model "${e.id}"`);return{...e,...n,baseUrl:T}}async function M(e,t){let n=new URLSearchParams({grant_type:`authorization_code`,code:e,redirect_uri:w,client_id:C,code_verifier:t}),r=await fetch(S,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`},body:n});if(!r.ok)throw new h(`xAI token exchange failed: ${r.status} ${await r.text()}`,m.TOKEN_EXCHANGE_FAILED);let i=await r.json();if(!i.access_token)throw new h(`xAI token exchange did not return access_token.`,m.TOKEN_EXCHANGE_INVALID);return i}async function N(e){if(l())return null;try{let t=new URLSearchParams({grant_type:`refresh_token`,refresh_token:e,client_id:C}),n=await fetch(S,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`},body:t});if(!n.ok){let e=await n.text();return u(n.status,e)||console.error(`[xai-grok] refresh failed:`,n.status,e),null}return await n.json()}catch(e){return console.error(`[xai-grok] refresh error:`,e instanceof Error?e.message:String(e)),null}}function P(){return t().find(e=>e.providerId===y)}async function F(){let t=P();if(!t?.accessToken)throw new h("Not signed in to xAI Grok — run /login or `oauth-token xai-grok`",m.AUTH_MISSING,!0);let n=t.tokenExpiresAt??0;if(n&&Date.now()+6e4<n)return t.accessToken;if(t.refreshToken){let n=await N(t.refreshToken);if(n?.access_token)return await e({providerId:y,accessToken:n.access_token,refreshToken:n.refresh_token??t.refreshToken,tokenExpiresAt:Date.now()+(n.expires_in??21600)*1e3,scopes:n.scope??t.scopes}),n.access_token}return t.accessToken}async function I(){if(!P()?.accessToken)throw Error(`xAI Grok budget: not signed in`);return v(await F(),fetch)}function L(e,t){return{type:`error`,reason:`error`,error:{role:`assistant`,content:[],api:D,provider:y,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 R(e,t){return t?{...e??{},"x-grok-conv-id":t}:e}function z(e){console.error(`[xai-grok] Stream error:`,e instanceof Error?e.message:String(e))}async function B(e,t,n,r){try{let i=await F(),a=r.sessionId,c=j(t),l={...r,apiKey:i,headers:R(r.headers,a)},u=c.api===`openai-responses`?o(c,n,l):s(c,n,l);for await(let t of u)e.push(t);e.end()}catch(n){z(n),e.push(L(t,n)),e.end()}}async function V(e,t,n,r){try{let i=await F(),o=r?.sessionId,s=j(t),l={...r,apiKey:i,headers:R(r?.headers,o)},u=s.api===`openai-responses`?a(s,n,l):c(s,n,l);for await(let t of u)e.push(t);e.end()}catch(n){z(n),e.push(L(t,n)),e.end()}}const H=(e,t,r={})=>{let i=n();return B(i,e,t,r).catch(z),i},U=(e,t,r)=>{let i=n();return V(i,e,t,r).catch(z),i},W={id:y,name:`xAI Grok (SuperGrok OAuth)`,description:`Grok via xAI OAuth — uses your SuperGrok subscription, no API key needed. Default model is Grok 4.7.`,requiresApiKey:!1,requiresBaseUrl:!1,isOAuth:!0,defaultModelId:E,oauthTokenDomains:[`api.x.ai`,`*.x.ai`,`auth.x.ai`,`accounts.x.ai`,`cli-chat-proxy.grok.com`],getModelIds:()=>k().map(A),getBudgetUsage:I,onOAuthLoginIntercepted:async(t,n,r)=>{let i=d(),a=await p(i),o=f(),s=f(),c=new URL(x);c.searchParams.set(`response_type`,`code`),c.searchParams.set(`client_id`,C),c.searchParams.set(`redirect_uri`,w),c.searchParams.set(`scope`,r?.scopes??`openid profile email offline_access grok-cli:access api:access`),c.searchParams.set(`code_challenge`,a),c.searchParams.set(`code_challenge_method`,`S256`),c.searchParams.set(`state`,o),c.searchParams.set(`nonce`,s),c.searchParams.set(`plan`,`generic`),c.searchParams.set(`referrer`,`slicc`);let l=await t({authorizeUrl:c.toString(),redirectUriPattern:`http://127.0.0.1:56121/*`,onCapture:`close`});if(!l)throw new h(`xAI OAuth login was cancelled or timed out`,m.CALLBACK_TIMEOUT);let u=new URL(l),g=u.searchParams.get(`code`),_=u.searchParams.get(`state`);if(!g)throw new h(`xAI OAuth redirect did not include a code`,m.CODE_MISSING);if(_!==o)throw new h(`xAI OAuth state mismatch — possible CSRF, aborting`,m.STATE_MISMATCH);let v=await M(g,i);await e({providerId:y,accessToken:v.access_token,refreshToken:v.refresh_token,tokenExpiresAt:Date.now()+(v.expires_in??21600)*1e3,baseUrl:T,scopes:v.scope}),n()},onOAuthLogout:async()=>{await e({providerId:y,accessToken:``})},onSilentRenew:async()=>{let t=P();if(!t?.refreshToken)return null;let n=await N(t.refreshToken);return n?.access_token?(await e({providerId:y,accessToken:n.access_token,refreshToken:n.refresh_token??t.refreshToken,tokenExpiresAt:Date.now()+(n.expires_in??21600)*1e3,scopes:n.scope??t.scopes}),n.access_token):null}};function G(){r({api:D,stream:H,streamSimple:U})}export{m as XaiErrorCode,h as XaiOAuthError,W as config,G as register};
@@ -1 +1 @@
1
- import{a as e}from"./core-Be1yHH6v.js";import{a as t}from"./diagnostics-DN_idNHx.js";import{a as n}from"./compat-qQM4gjF_.js";import{c as r,i,r as a,s as o}from"./legacy-api-aliases-DtQJ5I7w.js";import{K as s,f as c}from"./account-store-Bevys7WL.js";import"./main-DUD5pTDH.js";import{n as l,r as u}from"./bridge-token-required-DMk2va9k.js";import{n as d,r as f,t as p}from"./pkce-hGf_TEnP.js";import{XaiErrorCode as m,XaiOAuthError as h}from"./xai-grok-errors-bnlIBeu-.js";var g=`https://cli-chat-proxy.grok.com/v1/billing?format=credits`,_=8e3,v=65536,y=1e3;function b(e){return typeof e==`object`&&!!e}function x(e){if(!b(e))return null;let t=b(e.config)?e.config:e,n=t.creditUsagePercent;if(typeof n!=`number`||!Number.isFinite(n))return null;let r=Math.min(y,Math.max(0,n)),i=b(t.currentPeriod)?t.currentPeriod:{},a=i.type,o=typeof a==`string`?a.replace(`USAGE_PERIOD_TYPE_`,``).toLowerCase():``,s=i.end??t.billingPeriodEnd,c=typeof s==`string`&&Number.isFinite(Date.parse(s))?s:void 0;return{percent:r,status:`ok`,window:o&&o!==`unspecified`?o:`billing`,...c?{resetsAt:c}:{}}}async function S(e,t,n={}){let r=new AbortController,i=setTimeout(()=>r.abort(),n.timeoutMs??_);try{let n=await t(g,{headers:{Authorization:`Bearer ${e}`},signal:r.signal}),{status:i}=n;if(i===404||i===501)return null;if(!n.ok)throw Error(`xAI Grok usage: ${i===401||i===403?`re-login required`:`failed`} (${i})`);let a=await n.text();if(a.length>v)return null;try{return x(JSON.parse(a))}catch{return null}}finally{clearTimeout(i)}}var C=`xai-grok`,w=`https://auth.x.ai`,T=`${w}/oauth2/authorize`,E=`${w}/oauth2/token`,D=`b1a00492-073a-47ea-816f-4c329264a828`,O=`openid profile email offline_access grok-cli:access api:access`,k=`http://127.0.0.1:56121/callback`,A=`http://127.0.0.1:56121/*`,j=`https://api.x.ai/v1`,M=`grok-4.7`,N=`${C}-openai`;function P(e){if(e.some(e=>e.id===M))return e;let t=e.find(e=>e.id===`grok-4.6`)??e.find(e=>e.api===`openai-responses`)??e[0];return t?[{...t,id:M,name:`Grok 4.7`,api:`openai-responses`,reasoning:!0,input:[`text`,`image`],cost:{input:2,output:6,cacheRead:.5,cacheWrite:0},contextWindow:5e5,maxTokens:5e5,thinkingLevelMap:{off:null,minimal:null,low:`low`,medium:`medium`,high:`high`,xhigh:`xhigh`,max:null}},...e]:e}function F(){return P(e(`xai`))}function I(e){return{id:e.id,name:e.name,api:`openai`,reasoning:e.reasoning,input:e.input,context_window:e.contextWindow,max_tokens:e.maxTokens,compat:e.compat,thinkingLevelMap:e.thinkingLevelMap,cost:e.cost}}function L(e){let t=F(),n=t.find(t=>t.id===e.id);if(!n&&(console.warn(`xAI model "${e.id}" is no longer in the pi-ai catalog; falling back to default "${M}"`),n=t.find(e=>e.id===M),!n))throw Error(`xAI default model "${M}" is not registered by pi-ai`);if(n.api!==`openai-responses`&&n.api!==`openai-completions`)throw Error(`Unsupported pi-ai API "${n.api}" for xAI model "${e.id}"`);return{...e,...n,baseUrl:j}}async function R(e,t){let n=new URLSearchParams({grant_type:`authorization_code`,code:e,redirect_uri:k,client_id:D,code_verifier:t}),r=await fetch(E,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`},body:n});if(!r.ok)throw new h(`xAI token exchange failed: ${r.status} ${await r.text()}`,m.TOKEN_EXCHANGE_FAILED);let i=await r.json();if(!i.access_token)throw new h(`xAI token exchange did not return access_token.`,m.TOKEN_EXCHANGE_INVALID);return i}async function z(e){if(l())return null;try{let t=new URLSearchParams({grant_type:`refresh_token`,refresh_token:e,client_id:D}),n=await fetch(E,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`},body:t});if(!n.ok){let e=await n.text();return u(n.status,e)||console.error(`[xai-grok] refresh failed:`,n.status,e),null}return await n.json()}catch(e){return console.error(`[xai-grok] refresh error:`,e instanceof Error?e.message:String(e)),null}}function B(){return c().find(e=>e.providerId===C)}async function V(){let e=B();if(!e?.accessToken)throw new h("Not signed in to xAI Grok — run /login or `oauth-token xai-grok`",m.AUTH_MISSING,!0);let t=e.tokenExpiresAt??0;if(t&&Date.now()+6e4<t)return e.accessToken;if(e.refreshToken){let t=await z(e.refreshToken);if(t?.access_token)return await s({providerId:C,accessToken:t.access_token,refreshToken:t.refresh_token??e.refreshToken,tokenExpiresAt:Date.now()+(t.expires_in??21600)*1e3,scopes:t.scope??e.scopes}),t.access_token}return e.accessToken}async function H(){if(!B()?.accessToken)throw Error(`xAI Grok budget: not signed in`);return S(await V(),fetch)}function U(e,t){return{type:`error`,reason:`error`,error:{role:`assistant`,content:[],api:N,provider:C,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 W(e,t){return t?{...e??{},"x-grok-conv-id":t}:e}function G(e){console.error(`[xai-grok] Stream error:`,e instanceof Error?e.message:String(e))}async function K(e,t,n,r){try{let o=await V(),s=r.sessionId,c=L(t),l={...r,apiKey:o,headers:W(r.headers,s)},u=c.api===`openai-responses`?i(c,n,l):a(c,n,l);for await(let t of u)e.push(t);e.end()}catch(n){G(n),e.push(U(t,n)),e.end()}}async function q(e,t,n,i){try{let a=await V(),s=i?.sessionId,c=L(t),l={...i,apiKey:a,headers:W(i?.headers,s)},u=c.api===`openai-responses`?r(c,n,l):o(c,n,l);for await(let t of u)e.push(t);e.end()}catch(n){G(n),e.push(U(t,n)),e.end()}}var J=(e,n,r={})=>{let i=t();return K(i,e,n,r).catch(G),i},Y=(e,n,r)=>{let i=t();return q(i,e,n,r).catch(G),i},X={id:C,name:`xAI Grok (SuperGrok OAuth)`,description:`Grok via xAI OAuth — uses your SuperGrok subscription, no API key needed. Default model is Grok 4.7.`,requiresApiKey:!1,requiresBaseUrl:!1,isOAuth:!0,defaultModelId:M,oauthTokenDomains:[`api.x.ai`,`*.x.ai`,`auth.x.ai`,`accounts.x.ai`,`cli-chat-proxy.grok.com`],getModelIds:()=>F().map(I),getBudgetUsage:H,onOAuthLoginIntercepted:async(e,t,n)=>{let r=d(),i=await p(r),a=f(),o=f(),c=new URL(T);c.searchParams.set(`response_type`,`code`),c.searchParams.set(`client_id`,D),c.searchParams.set(`redirect_uri`,k),c.searchParams.set(`scope`,n?.scopes??O),c.searchParams.set(`code_challenge`,i),c.searchParams.set(`code_challenge_method`,`S256`),c.searchParams.set(`state`,a),c.searchParams.set(`nonce`,o),c.searchParams.set(`plan`,`generic`),c.searchParams.set(`referrer`,`slicc`);let l=await e({authorizeUrl:c.toString(),redirectUriPattern:A,onCapture:`close`});if(!l)throw new h(`xAI OAuth login was cancelled or timed out`,m.CALLBACK_TIMEOUT);let u=new URL(l),g=u.searchParams.get(`code`),_=u.searchParams.get(`state`);if(!g)throw new h(`xAI OAuth redirect did not include a code`,m.CODE_MISSING);if(_!==a)throw new h(`xAI OAuth state mismatch — possible CSRF, aborting`,m.STATE_MISMATCH);let v=await R(g,r);await s({providerId:C,accessToken:v.access_token,refreshToken:v.refresh_token,tokenExpiresAt:Date.now()+(v.expires_in??21600)*1e3,baseUrl:j,scopes:v.scope}),t()},onOAuthLogout:async()=>{await s({providerId:C,accessToken:``})},onSilentRenew:async()=>{let e=B();if(!e?.refreshToken)return null;let t=await z(e.refreshToken);return t?.access_token?(await s({providerId:C,accessToken:t.access_token,refreshToken:t.refresh_token??e.refreshToken,tokenExpiresAt:Date.now()+(t.expires_in??21600)*1e3,scopes:t.scope??e.scopes}),t.access_token):null}};function Z(){n({api:N,stream:J,streamSimple:Y})}export{m as XaiErrorCode,h as XaiOAuthError,X as config,Z as register};
1
+ import{a as e}from"./core-Be1yHH6v.js";import{a as t}from"./diagnostics-DN_idNHx.js";import{a as n}from"./compat-qQM4gjF_.js";import{c as r,i,r as a,s as o}from"./legacy-api-aliases-DtQJ5I7w.js";import{K as s,f as c}from"./account-store-SimIXg8S.js";import"./main-BcLR9n_M.js";import{n as l,r as u}from"./bridge-token-required-DMk2va9k.js";import{n as d,r as f,t as p}from"./pkce-hGf_TEnP.js";import{XaiErrorCode as m,XaiOAuthError as h}from"./xai-grok-errors-bnlIBeu-.js";var g=`https://cli-chat-proxy.grok.com/v1/billing?format=credits`,_=8e3,v=65536,y=1e3;function b(e){return typeof e==`object`&&!!e}function x(e){if(!b(e))return null;let t=b(e.config)?e.config:e,n=t.creditUsagePercent;if(typeof n!=`number`||!Number.isFinite(n))return null;let r=Math.min(y,Math.max(0,n)),i=b(t.currentPeriod)?t.currentPeriod:{},a=i.type,o=typeof a==`string`?a.replace(`USAGE_PERIOD_TYPE_`,``).toLowerCase():``,s=i.end??t.billingPeriodEnd,c=typeof s==`string`&&Number.isFinite(Date.parse(s))?s:void 0;return{percent:r,status:`ok`,window:o&&o!==`unspecified`?o:`billing`,...c?{resetsAt:c}:{}}}async function S(e,t,n={}){let r=new AbortController,i=setTimeout(()=>r.abort(),n.timeoutMs??_);try{let n=await t(g,{headers:{Authorization:`Bearer ${e}`},signal:r.signal}),{status:i}=n;if(i===404||i===501)return null;if(!n.ok)throw Error(`xAI Grok usage: ${i===401||i===403?`re-login required`:`failed`} (${i})`);let a=await n.text();if(a.length>v)return null;try{return x(JSON.parse(a))}catch{return null}}finally{clearTimeout(i)}}var C=`xai-grok`,w=`https://auth.x.ai`,T=`${w}/oauth2/authorize`,E=`${w}/oauth2/token`,D=`b1a00492-073a-47ea-816f-4c329264a828`,O=`openid profile email offline_access grok-cli:access api:access`,k=`http://127.0.0.1:56121/callback`,A=`http://127.0.0.1:56121/*`,j=`https://api.x.ai/v1`,M=`grok-4.7`,N=`${C}-openai`;function P(e){if(e.some(e=>e.id===M))return e;let t=e.find(e=>e.id===`grok-4.6`)??e.find(e=>e.api===`openai-responses`)??e[0];return t?[{...t,id:M,name:`Grok 4.7`,api:`openai-responses`,reasoning:!0,input:[`text`,`image`],cost:{input:2,output:6,cacheRead:.5,cacheWrite:0},contextWindow:5e5,maxTokens:5e5,thinkingLevelMap:{off:null,minimal:null,low:`low`,medium:`medium`,high:`high`,xhigh:`xhigh`,max:null}},...e]:e}function F(){return P(e(`xai`))}function I(e){return{id:e.id,name:e.name,api:`openai`,reasoning:e.reasoning,input:e.input,context_window:e.contextWindow,max_tokens:e.maxTokens,compat:e.compat,thinkingLevelMap:e.thinkingLevelMap,cost:e.cost}}function L(e){let t=F(),n=t.find(t=>t.id===e.id);if(!n&&(console.warn(`xAI model "${e.id}" is no longer in the pi-ai catalog; falling back to default "${M}"`),n=t.find(e=>e.id===M),!n))throw Error(`xAI default model "${M}" is not registered by pi-ai`);if(n.api!==`openai-responses`&&n.api!==`openai-completions`)throw Error(`Unsupported pi-ai API "${n.api}" for xAI model "${e.id}"`);return{...e,...n,baseUrl:j}}async function R(e,t){let n=new URLSearchParams({grant_type:`authorization_code`,code:e,redirect_uri:k,client_id:D,code_verifier:t}),r=await fetch(E,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`},body:n});if(!r.ok)throw new h(`xAI token exchange failed: ${r.status} ${await r.text()}`,m.TOKEN_EXCHANGE_FAILED);let i=await r.json();if(!i.access_token)throw new h(`xAI token exchange did not return access_token.`,m.TOKEN_EXCHANGE_INVALID);return i}async function z(e){if(l())return null;try{let t=new URLSearchParams({grant_type:`refresh_token`,refresh_token:e,client_id:D}),n=await fetch(E,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`},body:t});if(!n.ok){let e=await n.text();return u(n.status,e)||console.error(`[xai-grok] refresh failed:`,n.status,e),null}return await n.json()}catch(e){return console.error(`[xai-grok] refresh error:`,e instanceof Error?e.message:String(e)),null}}function B(){return c().find(e=>e.providerId===C)}async function V(){let e=B();if(!e?.accessToken)throw new h("Not signed in to xAI Grok — run /login or `oauth-token xai-grok`",m.AUTH_MISSING,!0);let t=e.tokenExpiresAt??0;if(t&&Date.now()+6e4<t)return e.accessToken;if(e.refreshToken){let t=await z(e.refreshToken);if(t?.access_token)return await s({providerId:C,accessToken:t.access_token,refreshToken:t.refresh_token??e.refreshToken,tokenExpiresAt:Date.now()+(t.expires_in??21600)*1e3,scopes:t.scope??e.scopes}),t.access_token}return e.accessToken}async function H(){if(!B()?.accessToken)throw Error(`xAI Grok budget: not signed in`);return S(await V(),fetch)}function U(e,t){return{type:`error`,reason:`error`,error:{role:`assistant`,content:[],api:N,provider:C,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 W(e,t){return t?{...e??{},"x-grok-conv-id":t}:e}function G(e){console.error(`[xai-grok] Stream error:`,e instanceof Error?e.message:String(e))}async function K(e,t,n,r){try{let o=await V(),s=r.sessionId,c=L(t),l={...r,apiKey:o,headers:W(r.headers,s)},u=c.api===`openai-responses`?i(c,n,l):a(c,n,l);for await(let t of u)e.push(t);e.end()}catch(n){G(n),e.push(U(t,n)),e.end()}}async function q(e,t,n,i){try{let a=await V(),s=i?.sessionId,c=L(t),l={...i,apiKey:a,headers:W(i?.headers,s)},u=c.api===`openai-responses`?r(c,n,l):o(c,n,l);for await(let t of u)e.push(t);e.end()}catch(n){G(n),e.push(U(t,n)),e.end()}}var J=(e,n,r={})=>{let i=t();return K(i,e,n,r).catch(G),i},Y=(e,n,r)=>{let i=t();return q(i,e,n,r).catch(G),i},X={id:C,name:`xAI Grok (SuperGrok OAuth)`,description:`Grok via xAI OAuth — uses your SuperGrok subscription, no API key needed. Default model is Grok 4.7.`,requiresApiKey:!1,requiresBaseUrl:!1,isOAuth:!0,defaultModelId:M,oauthTokenDomains:[`api.x.ai`,`*.x.ai`,`auth.x.ai`,`accounts.x.ai`,`cli-chat-proxy.grok.com`],getModelIds:()=>F().map(I),getBudgetUsage:H,onOAuthLoginIntercepted:async(e,t,n)=>{let r=d(),i=await p(r),a=f(),o=f(),c=new URL(T);c.searchParams.set(`response_type`,`code`),c.searchParams.set(`client_id`,D),c.searchParams.set(`redirect_uri`,k),c.searchParams.set(`scope`,n?.scopes??O),c.searchParams.set(`code_challenge`,i),c.searchParams.set(`code_challenge_method`,`S256`),c.searchParams.set(`state`,a),c.searchParams.set(`nonce`,o),c.searchParams.set(`plan`,`generic`),c.searchParams.set(`referrer`,`slicc`);let l=await e({authorizeUrl:c.toString(),redirectUriPattern:A,onCapture:`close`});if(!l)throw new h(`xAI OAuth login was cancelled or timed out`,m.CALLBACK_TIMEOUT);let u=new URL(l),g=u.searchParams.get(`code`),_=u.searchParams.get(`state`);if(!g)throw new h(`xAI OAuth redirect did not include a code`,m.CODE_MISSING);if(_!==a)throw new h(`xAI OAuth state mismatch — possible CSRF, aborting`,m.STATE_MISMATCH);let v=await R(g,r);await s({providerId:C,accessToken:v.access_token,refreshToken:v.refresh_token,tokenExpiresAt:Date.now()+(v.expires_in??21600)*1e3,baseUrl:j,scopes:v.scope}),t()},onOAuthLogout:async()=>{await s({providerId:C,accessToken:``})},onSilentRenew:async()=>{let e=B();if(!e?.refreshToken)return null;let t=await z(e.refreshToken);return t?.access_token?(await s({providerId:C,accessToken:t.access_token,refreshToken:t.refresh_token??e.refreshToken,tokenExpiresAt:Date.now()+(t.expires_in??21600)*1e3,scopes:t.scope??e.scopes}),t.access_token):null}};function Z(){n({api:N,stream:J,streamSimple:Y})}export{m as XaiErrorCode,h as XaiOAuthError,X as config,Z as register};
@@ -5,7 +5,7 @@
5
5
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
6
  <title>slicc</title>
7
7
  <link rel="icon" type="image/png" href="/logos/sliccy-color-1scoops-32x32.png" />
8
- <script type="module" crossorigin src="/assets/main-DUD5pTDH.js"></script>
8
+ <script type="module" crossorigin src="/assets/main-BcLR9n_M.js"></script>
9
9
  <link rel="modulepreload" crossorigin href="/assets/rolldown-runtime-Dd_uD5pT.js">
10
10
  <link rel="modulepreload" crossorigin href="/assets/modulepreload-polyfill-P2Xu9kJm.js">
11
11
  <link rel="modulepreload" crossorigin href="/assets/diagnostics-DN_idNHx.js">
@@ -31,12 +31,12 @@
31
31
  <link rel="modulepreload" crossorigin href="/assets/tool-ui-eSQ1g2I1.js">
32
32
  <link rel="modulepreload" crossorigin href="/assets/core-Be1yHH6v.js">
33
33
  <link rel="modulepreload" crossorigin href="/assets/bridge-protocol-C52CnDIj.js">
34
- <link rel="modulepreload" crossorigin href="/assets/providers-CE4VqQs6.js">
34
+ <link rel="modulepreload" crossorigin href="/assets/providers-CGp8gI0u.js">
35
35
  <link rel="modulepreload" crossorigin href="/assets/panel-rpc-D3EPRnmw.js">
36
36
  <link rel="modulepreload" crossorigin href="/assets/bedrock-camp-compat-Bz7u6y4g.js">
37
37
  <link rel="modulepreload" crossorigin href="/assets/bedrock-camp-extra-models-IBZyfEdZ.js">
38
38
  <link rel="modulepreload" crossorigin href="/assets/claude-model-version-DZmbk9E2.js">
39
- <link rel="modulepreload" crossorigin href="/assets/account-store-Bevys7WL.js">
39
+ <link rel="modulepreload" crossorigin href="/assets/account-store-SimIXg8S.js">
40
40
  <link rel="modulepreload" crossorigin href="/assets/telemetry-CKoAhRMv.js">
41
41
  <link rel="modulepreload" crossorigin href="/assets/tray-follower-status-BAjnN7Ar.js">
42
42
  <link rel="modulepreload" crossorigin href="/assets/clipboard-eqmn97SP.js">
@@ -5,7 +5,7 @@
5
5
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
6
  <title>slicc</title>
7
7
  <link rel="icon" type="image/png" href="/logos/sliccy-color-1scoops-32x32.png" />
8
- <script type="module" crossorigin src="/assets/main-DUD5pTDH.js"></script>
8
+ <script type="module" crossorigin src="/assets/main-BcLR9n_M.js"></script>
9
9
  <link rel="modulepreload" crossorigin href="/assets/rolldown-runtime-Dd_uD5pT.js">
10
10
  <link rel="modulepreload" crossorigin href="/assets/modulepreload-polyfill-P2Xu9kJm.js">
11
11
  <link rel="modulepreload" crossorigin href="/assets/diagnostics-DN_idNHx.js">
@@ -31,12 +31,12 @@
31
31
  <link rel="modulepreload" crossorigin href="/assets/tool-ui-eSQ1g2I1.js">
32
32
  <link rel="modulepreload" crossorigin href="/assets/core-Be1yHH6v.js">
33
33
  <link rel="modulepreload" crossorigin href="/assets/bridge-protocol-C52CnDIj.js">
34
- <link rel="modulepreload" crossorigin href="/assets/providers-CE4VqQs6.js">
34
+ <link rel="modulepreload" crossorigin href="/assets/providers-CGp8gI0u.js">
35
35
  <link rel="modulepreload" crossorigin href="/assets/panel-rpc-D3EPRnmw.js">
36
36
  <link rel="modulepreload" crossorigin href="/assets/bedrock-camp-compat-Bz7u6y4g.js">
37
37
  <link rel="modulepreload" crossorigin href="/assets/bedrock-camp-extra-models-IBZyfEdZ.js">
38
38
  <link rel="modulepreload" crossorigin href="/assets/claude-model-version-DZmbk9E2.js">
39
- <link rel="modulepreload" crossorigin href="/assets/account-store-Bevys7WL.js">
39
+ <link rel="modulepreload" crossorigin href="/assets/account-store-SimIXg8S.js">
40
40
  <link rel="modulepreload" crossorigin href="/assets/telemetry-CKoAhRMv.js">
41
41
  <link rel="modulepreload" crossorigin href="/assets/tray-follower-status-BAjnN7Ar.js">
42
42
  <link rel="modulepreload" crossorigin href="/assets/clipboard-eqmn97SP.js">
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sliccy",
3
- "version": "6.192.0",
3
+ "version": "6.193.0",
4
4
  "description": "Browser-based coding agent with thin CLI server",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
@@ -1 +0,0 @@
1
- import{S as e,_ as t,r as n,s as r}from"./account-store-irTFXEHq.js";import{r as i}from"./panel-rpc-DW7W4w6_.js";import{a}from"./diagnostics-DN_idNHx.js";import{a as o}from"./compat-uEPf6-XW.js";import{c as s,s as c}from"./core-PJsXG3mm.js";import{a as l,r as u,s as d,t as f}from"./legacy-api-aliases-jKEvBgOL.js";import{a as p,i as m,r as h}from"./claude-model-version-ceOteQ2f.js";import{r as g}from"./provider-budget-DbHWq3j6.js";import{n as _}from"./llm-session-id-BZyXP_j2.js";import{v}from"./kernel-worker-YhNfUQ_y.js";import{n as y,t as ee}from"./silent-renew-backoff-Dmz3DJHb.js";import{getOAuthPageOrigin as te}from"./oauth-service-DP3Rx6V_.js";import{n as b}from"./temperature-support-D3pN575q.js";import"./provider-settings-BuaTQYid.js";var ne={proxyEndpoint:`https://adobe-llm-proxy.paolo-moz.workers.dev`,redirectUri:`https://www.sliccy.ai/auth/callback`,extensionRedirectUri:`https://akjjllgokmbgpbdbmafpiefnhidlmbgf.chromiumapp.org/adobe`};function re(e,t){return h(e,t)}function x(e,t,n){return e!==`xhigh`||!t?e:p(t,n)?`xhigh`:m(t,n)?`max`:`high`}function ie(e,t){let n=e?t?.thinkingLevelMap?.[e]:void 0;return x((()=>{if(typeof n==`string`)return n;switch(e){case`minimal`:case`low`:return`low`;case`medium`:return`medium`;case`xhigh`:return`xhigh`;default:return`high`}})(),t?.id,t?.name)}function ae(e,t){return async(n,r)=>{let i=t?await t(n,r)??n:n,a=i.thinking;return a&&a.type===`enabled`&&(i.thinking={type:`adaptive`,...a.display===void 0?{}:{display:a.display}},i.output_config={...i.output_config??{},effort:e}),i}}function S(e,t){if(!re(e.id,e.name))return t;let n=t,r=x(n.effort??ie(n.reasoning,e),e.id,e.name);return{...t,onPayload:ae(r,n.onPayload)}}function oe(e,t){let n={id:e.id,name:e.name??e.id},r=t?.api??e.api,i=t?.context_window??e.context_window,a=t?.max_tokens??e.max_tokens,o=t?.reasoning??e.reasoning,s=t?.input??e.input;r&&(n.api=r),i!==void 0&&(n.context_window=i),a!==void 0&&(n.max_tokens=a),o!==void 0&&(n.reasoning=o),s&&(n.input=s);let c=t?.cost??e.cost;return c&&(n.cost=c),/haiku/i.test(e.id)&&(n.compat={supportsEagerToolInputStreaming:!1}),/sonnet-5\b/i.test(e.id)&&!n.thinkingLevelMap&&(n.thinkingLevelMap={xhigh:`xhigh`}),n}async function se(e,t,n,r={}){let i=typeof AbortController==`function`?new AbortController:null,a=i?setTimeout(()=>i.abort(),r.timeoutMs??8e3):null;try{let a=await n(`${e.replace(/\/$/,``)}/v1/usage`,{headers:{...r.headers,Authorization:`Bearer ${t}`},...i?{signal:i.signal}:{}});if(a.status===404||a.status===501)return null;if(!a.ok)throw Error(`Adobe /v1/usage returned ${a.status}`);return g(await a.json())}finally{a&&clearTimeout(a)}}const C=Object.assign({"/packages/webapp/providers/adobe-config.json":ne})[`/packages/webapp/providers/adobe-config.json`]??{clientId:``,proxyEndpoint:``,scopes:`openid,profile,email`};function w(){let e=r(`adobe`);if(e)return e.replace(/\/$/,``);if(C.proxyEndpoint)return C.proxyEndpoint.replace(/\/$/,``);throw Error(`Adobe proxy endpoint not configured — set it in Settings or adobe-config.json`)}const T=new Map,ce=new Map,le=`slicc-adobe-models`;function E(e){try{localStorage.setItem(le,JSON.stringify(e))}catch{}}async function D(e){try{let t=await fetch(`${e}/v1/config`,{headers:{[W]:`6.192.0`}});return t.ok?await t.json():(console.warn(`[adobe] Proxy /v1/config returned ${t.status}`),null)}catch(e){return console.warn(`[adobe] Failed to fetch proxy config:`,e instanceof Error?e.message:String(e)),null}}async function O(e){let t=T.get(e);if(t)return t;let n=await D(e);return n||=(await new Promise(e=>setTimeout(e,600)),await D(e)),n?(T.set(e,n),n):{}}function k(e){let t=e.clientId||C.clientId;if(!t)throw Error(`Could not determine IMS client ID — proxy /v1/config did not return one and adobe-config.json is empty`);return t}function A(e){return e.scopes||C.scopes}function j(e){return e.imsEnvironment||C.imsEnvironment||`prod`}const M={prod:`https://ims-na1.adobelogin.com`,stg1:`https://ims-na1-stg1.adobelogin.com`};function N(e){return M[e??C.imsEnvironment??`prod`]??M.prod}async function P(){let e;try{e=w()}catch{return{}}return T.get(e)||new Promise(t=>{let n=setTimeout(()=>t({}),5e3),r=e=>{clearTimeout(n),t(e)};O(e).then(r,()=>r({}))})}function F(e){try{let t=e.split(`.`)[1];if(!t)return;let n=t.replace(/-/g,`+`).replace(/_/g,`/`),r=atob(n+`=`.repeat((4-n.length%4)%4)),i=JSON.parse(r);return typeof i.client_id==`string`?i.client_id:void 0}catch{return}}const I=typeof chrome<`u`&&!!chrome?.runtime?.id;function L(){return n().find(e=>e.providerId===`adobe`)}const ue=[`/ims/profile/v1`,`/ims/userinfo/v2`];async function de(e,t){try{let n=await fetch(e,{headers:{Authorization:`Bearer ${t}`}});if(!n.ok){console.warn(`[adobe] Profile fetch ${e} returned ${n.status}`);return}let r=await n.json(),i=r.displayName||r.name||r.email;return i?{name:i,avatar:r.picture||r.avatar_url}:void 0}catch(t){console.warn(`[adobe] Profile fetch ${e} failed:`,t instanceof Error?t.message:String(t));return}}async function fe(e,t){for(let n of ue){let r=await de(`${N(t)}${n}`,e);if(r)return r}return console.warn(`[adobe] No IMS profile endpoint named the user; account will have no display name`),{}}async function pe(){let e=L(),t=e?.accessToken;if(!t)return{status:`unknown`,detail:`no stored token`};let n=await P(),r=F(t)||n.clientId||C.clientId||``;if(!r)return{status:`unknown`,detail:`no IMS client ID available`};let i=N(j(n));try{let n=await fetch(`${i}/ims/validate_token/v1`,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`},body:new URLSearchParams({client_id:r,token:t,type:`access_token`}),signal:AbortSignal.timeout(1e4)});if(!n.ok)return{status:`unknown`,detail:`HTTP ${n.status}${n.statusText?` ${n.statusText}`:``}`};let a=await n.json();return a.valid===!0?{status:`accepted`,userName:e?.userName}:a.valid===!1?{status:`rejected`,detail:`IMS reported the token invalid (${typeof a.reason==`string`?a.reason:`no reason given`})`}:{status:`unknown`,detail:"IMS answered 200 without a boolean `valid` verdict"}}catch(e){return{status:`unknown`,detail:e instanceof Error?e.message:String(e)}}}function R(e){let t=e.indexOf(`#`);if(t<0)return null;let n=new URLSearchParams(e.slice(t+1)),r=n.get(`access_token`);return r?{accessToken:r,expiresIn:parseInt(n.get(`expires_in`)??`86400`,10),scope:n.get(`scope`)??void 0}:null}const z={id:`adobe`,name:`Adobe`,description:`Claude via Adobe — login with your Adobe ID`,requiresApiKey:!1,requiresBaseUrl:!C.proxyEndpoint,baseUrlPlaceholder:`https://your-proxy.example.com`,baseUrlDescription:`Anthropic-compatible proxy endpoint`,isOAuth:!0,defaultModelId:`sonnet`,oauthTokenDomains:[`ims-na1.adobelogin.com`,`ims-na1-stg1.adobelogin.com`,`*.adobelogin.com`,`*.adobe.io`,`firefall.adobe.io`,`admin.hlx.page`,`admin.hlx.live`,`admin.aem.page`,`admin.aem.live`,`api.aem.live`],getBudgetUsage:he,getModelIds:()=>{let e=e=>oe(e,ce.get(e.id));for(let t of Q.values())if(t.length){let n=t.map(t=>e({id:t.id,name:t.name??t.id,reasoning:t.reasoning,input:t.input,cost:t.cost}));return E(n),n}for(let t of T.values())if(t.models?.length)return t.models.map(t=>e(t));try{let e=localStorage.getItem(le);if(e){let t=JSON.parse(e);if(t.length)return t}}catch{}return[{id:`claude-sonnet-4-6`,name:`Claude Sonnet 4.6`}]},onOAuthLogin:async(e,n,r)=>{let i=w(),a=await O(i),o=k(a),s=A(a),c=j(a),l=I?null:await te(),u=I?null:y({pageHref:l.href,pageOrigin:l.origin,configuredRedirectUri:C.redirectUri},()=>crypto.randomUUID()),d=I?C.extensionRedirectUri??`https://${chrome.runtime.id}.chromiumapp.org/`:u.redirectUri,f=u?.oauthState,p=u?.expectedNonce??null,m=new URLSearchParams({client_id:o,scope:s,response_type:`token`,redirect_uri:d});f&&m.set(`state`,f),r?.forceReauth&&m.set(`prompt`,`login`);let h=await e(`${N(c)}/ims/authorize/v2?${m}`);if(!h)return;if(p&&h)try{if(new URL(h).searchParams.get(`nonce`)!==p){console.error(`[adobe] OAuth nonce mismatch — possible CSRF`);return}}catch(e){console.warn(`[adobe] Nonce check skipped (URL parse failed):`,e instanceof Error?e.message:String(e))}let g=R(h);if(!g){console.error(`[adobe] Could not extract token from redirect URL`);return}let _=await fe(g.accessToken,c);await t({providerId:`adobe`,accessToken:g.accessToken,tokenExpiresAt:Date.now()+g.expiresIn*1e3,userName:_.name,userAvatar:_.avatar,scopes:g.scope,baseUrl:C.proxyEndpoint?void 0:i}),v(),await $().catch(e=>console.warn(`[adobe] Failed to fetch models after login:`,e instanceof Error?e.message:String(e))),n()},onOAuthLogout:async()=>{let e=L();if(e?.accessToken)try{let t=await P(),n=F(e.accessToken)||t.clientId||C.clientId,r=j(t);if(n){let t=await fetch(`${N(r)}/ims/revoke`,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`},body:new URLSearchParams({token:e.accessToken,token_type_hint:`access_token`,client_id:n})});t.ok||console.warn(`[adobe] Token revocation returned ${t.status}, token may still be valid server-side`)}}catch(e){console.warn(`[adobe] Failed to revoke token:`,e instanceof Error?e.message:String(e))}await t({providerId:`adobe`,accessToken:``}),v()},onSilentRenew:async()=>L()?.accessToken?U():null,onValidateToken:pe,refreshModels:async e=>{await $(e);let t=z.getModelIds?.();t?.length&&E(t)}};let B=null;const me=ee();async function V(){let e=L();if(!e?.accessToken)throw Error(`Not logged in to Adobe — please log in first`);if((e.tokenExpiresAt??0)-Date.now()>6e4)return e.accessToken;console.log(`[adobe] Token expired or expiring soon, attempting silent renewal...`);let t=await me.run(()=>U());if(t)return t;let n=L();if((n?.tokenExpiresAt??0)-Date.now()>0&&n?.accessToken)return n.accessToken;throw Error(`Adobe session expired — please log in again`)}async function he(){let e;try{e=w()}catch{return null}let t=L();if(!t?.accessToken||H())throw Error(`Adobe budget: not signed in`);return se(e,t.accessToken,fetch,{headers:{"X-Session-Id":_(be)}})}function H(){let e=L();return!e?.tokenExpiresAt||Date.now()>e.tokenExpiresAt-6e4}async function U(){if(typeof window>`u`){let e=i();if(!e)return null;try{let{accessToken:t}=await e.call(`silent-renew`,{providerId:`adobe`},{timeoutMs:13e4});return t}catch(e){return console.warn(`[adobe] worker→page silent-renew bridge failed:`,e instanceof Error?e.message:String(e)),null}}return B===null&&(B=ye().finally(()=>{B=null})),B}function ge(e,t){let n=k(t),r=A(t),i=j(t),a=I?null:y({pageHref:window.location.href,pageOrigin:window.location.origin,configuredRedirectUri:C.redirectUri},()=>crypto.randomUUID()),o=I?C.extensionRedirectUri??`https://${chrome.runtime.id}.chromiumapp.org/`:a.redirectUri,s=a?.oauthState,c=a?.expectedNonce??null,l=new URLSearchParams({client_id:n,scope:r,response_type:`token`,redirect_uri:o,prompt:`none`});return s&&l.set(`state`,s),{authorizeUrl:`${N(i)}/ims/authorize/v2?${l}`,expectedNonce:c,proxyEndpoint:e}}function _e(e,t){if(!t)return!0;try{if(new URL(e).searchParams.get(`nonce`)!==t)return console.error(`[adobe] OAuth nonce mismatch — possible CSRF`),!1}catch(e){console.warn(`[adobe] Nonce check skipped (URL parse failed):`,e instanceof Error?e.message:String(e))}return!0}async function ve(e,n){let r=L();await t({providerId:`adobe`,accessToken:e.accessToken,tokenExpiresAt:Date.now()+e.expiresIn*1e3,userName:r?.userName,userAvatar:r?.userAvatar,scopes:e.scope,baseUrl:C.proxyEndpoint?void 0:n})}async function ye(){try{let e=w(),{authorizeUrl:t,expectedNonce:n}=ge(e,await O(e)),{createOAuthLauncher:r}=await import(`./oauth-service-DP3Rx6V_.js`),i=await r()(t,{interactive:!1});if(!i||!_e(i,n))return null;let a=R(i);return a?(await ve(a,e),console.log(`[adobe] Token renewed silently`),await $().catch(e=>console.warn(`[adobe] Failed to refresh models after silent renewal:`,e instanceof Error?e.message:String(e))),a.accessToken):null}catch(e){return console.warn(`[adobe] Silent renewal error:`,e instanceof Error?e.message:String(e)),null}}const W=`X-Slicc-Version`;function G(e){let t={};if(e.headers)for(let[n,r]of Object.entries(e.headers))n.toLowerCase()!==`x-slicc-version`&&(t[n]=r);return t[W]=`6.192.0`,{...e,headers:t}}const be=`adobe-usage-probe`,K=new Set;function q(e,t){if(e.headers){for(let[t,n]of Object.entries(e.headers))if(t.toLowerCase()===`x-session-id`&&n!=null)return e}return K.has(t)||(K.add(t),console.warn(`[adobe] Missing X-Session-Id from ${t} — using daily fallback. Attach an X-Session-Id header at the call site (see scoop-context.ts streamWithSessionId or docs/pitfalls.md).`)),{...e,headers:{...e.headers??{},"X-Session-Id":_(`adobe-provider-fallback`)}}}function xe(){K.clear()}function J(e,t){return{type:`error`,reason:`error`,error:{role:`assistant`,content:[],api:`adobe-anthropic`,provider:`adobe`,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 Y(e){console.error(`[adobe] Stream error:`,e instanceof Error?e.message:String(e))}const X=(e,t,n={})=>{let r=a();return Se(r,e,t,n).catch(Y),r};async function Se(e,t,n,r){try{let i=await V();if(String(t.api).includes(`openai`)){let a={...t,baseUrl:`${w()}/v1`,api:`openai-completions`,compat:{...t.compat,supportsStore:!1,supportsDeveloperRole:!1}},o=u(a,n,G(q({...r,apiKey:i},`streamAdobe[openai]`)));for await(let t of o)e.push(t)}else{let a={...t,baseUrl:w(),api:`anthropic-messages`},o=f(a,n,G(q(S(t,b(t.id,t.name,{...r,apiKey:i})),`streamAdobe[anthropic]`)));for await(let t of o)e.push(t)}e.end()}catch(n){Y(n),e.push(J(t,n)),e.end()}}const Z=(e,t,n)=>{let r=a();return Ce(r,e,t,n).catch(Y),r};async function Ce(e,t,n,r){try{let i=await V();if(String(t.api).includes(`openai`)){let a={...t,baseUrl:`${w()}/v1`,api:`openai-completions`,compat:{...t.compat,supportsStore:!1,supportsDeveloperRole:!1}},o=d(a,n,G(q({...r,apiKey:i},`streamSimpleAdobe[openai]`)));for await(let t of o)e.push(t)}else{let a={...t,baseUrl:w(),api:`anthropic-messages`},o=l(a,n,G(q(S(t,b(t.id,t.name,{...r,apiKey:i})),`streamSimpleAdobe[anthropic]`)));for await(let t of o)e.push(t)}e.end()}catch(n){Y(n),e.push(J(t,n)),e.end()}}function we(e){let t={id:e.id,name:e.name};return e.api!==void 0&&(t.api=e.api),e.context_window!==void 0&&(t.context_window=e.context_window),e.max_tokens!==void 0&&(t.max_tokens=e.max_tokens),e.reasoning!==void 0&&(t.reasoning=e.reasoning),e.input!==void 0&&(t.input=e.input),t}function Te(){let e=new Map;for(let t of s())try{let n=c(t);for(let t of n)e.set(t.id,t)}catch{}return e}function Ee(t,n,r){let i=`adobe-${t.api===`openai`?`openai`:`anthropic`}`,a=r.get(t.id);if(a)return{...a,provider:`adobe`,api:i};let o=e(t.id,r);return{id:t.id,name:t.name??t.id,provider:`adobe`,api:i,baseUrl:n,contextWindow:2e5,maxTokens:16384,input:[`text`,`image`],cost:o,inputCost:o.input,outputCost:o.output,cacheReadCost:o.cacheRead,cacheWriteCost:o.cacheWrite,reasoning:!0}}function De(e,t){for(let t of e)ce.set(t.id,we(t));let n=Te();return e.map(e=>Ee(e,t,n))}async function Oe(e){try{let t=e??await V(),n=w(),r=await fetch(`${n}/v1/models`,{headers:{Authorization:`Bearer ${t}`,[W]:`6.192.0`}});if(!r.ok)console.warn(`[adobe] Proxy /v1/models returned ${r.status}, falling back to Anthropic models`);else{let e=await r.json();if(e.data?.length)return De(e.data,n)}}catch(e){console.warn(`[adobe] Failed to fetch proxy models:`,e instanceof Error?e.message:String(e))}return null}const Q=new Map;function ke(){return c(`anthropic`).map(e=>({...e,provider:`adobe`,api:`adobe-anthropic`}))}async function $(e){let t=w(),n=Q.get(t);if(n)return n;let r=await Oe(e);return r?(Q.set(t,r),r):ke()}function Ae(){o({api:`adobe-anthropic`,stream:X,streamSimple:Z}),o({api:`adobe-openai`,stream:X,streamSimple:Z})}export{xe as __resetAdobeSessionIdWarningCacheForTests,z as config,R as extractTokenFromUrl,$ as getAdobeModels,V as getValidAccessToken,H as isTokenExpired,Ae as register};
@@ -1 +0,0 @@
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{n as s,t as c}from"./types-D8gIX-W-.js";import{i as l,r as u,t as d}from"./mount-index-CQfmUPuZ.js";import{a as f,i as p,n as m,t as h}from"./mount-table-store-DrF_Ifaz.js";import{n as g,t as _}from"./virtual-device-paths-CS5o4QVz.js";import{t as v}from"./same-file-identity-DuEcSmPX.js";import{a as y,i as b,o as x,r as S}from"./sidecar-repair-BTU4PjlG.js";import{t as C}from"./stat-identity-BaU9yoai.js";function w(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 T(e,t){try{return await e(t)}catch{return t}}async function*E(e,t,n,r=0){let a=i(t);if(w(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 T(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*D(e,t,a===`/`?`/${t.name}`:`${a}/${t.name}`,o,r+1)}async function*D(e,t,n,r,i){if(t.type===`file`){yield n;return}if(t.type===`symlink`){yield*O(e,n,r,i);return}yield*E(e,n,r,i)}async function*O(e,t,n,r){try{let i=await e.stat(t);i.type===`file`?yield t:i.type===`directory`&&(yield*E(e,t,n,r))}catch{}}const k=t(`fs-watcher`);let A=0;function ee(e,t){return t===`/`||e===t||e.startsWith(t+`/`)}var j=class{registrations=new Map;watch(e,t,n){let r=`fsw-${++A}`;return this.registrations.set(r,{id:r,basePath:e,filter:t,callback:n}),k.debug(`Watch registered`,{id:r,basePath:e}),()=>{this.registrations.delete(r),k.debug(`Watch unregistered`,{id:r})}}notify(e){if(e.length!==0)for(let[,t]of this.registrations){let n=e.filter(e=>ee(e.path,t.basePath)&&t.filter(e.path));if(n.length>0)try{t.callback(n)}catch(e){k.error(`Watch callback error`,{id:t.id,error:e instanceof Error?e.message:String(e)})}}}dispose(){this.registrations.clear(),k.debug(`All watchers disposed`)}get size(){return this.registrations.size}};const M=new TextEncoder,N=new TextDecoder(`utf-8`,{fatal:!1});var P=class{entries=new Map;static handles(e){return g(i(e))}has(e){return this.entries.has(i(e))}write(e,t){let n=i(e),r=typeof t==`string`?M.encode(t):new Uint8Array(t),a=Date.now(),o=this.entries.get(n);this.entries.set(n,{bytes:r,mtime:a,ctime:o?.ctime??a})}append(e,t){let n=this.entries.get(i(e))?.bytes??new Uint8Array,r=typeof t==`string`?M.encode(t):t,a=new Uint8Array(n.length+r.length);a.set(n),a.set(r,n.length),this.write(e,a)}read(e,t){let n=this.require(e);return(t?.encoding??`utf-8`)===`utf-8`?N.decode(n.bytes):new Uint8Array(n.bytes)}readText(e){return N.decode(this.require(e).bytes)}stat(e){let t=this.require(e);return{type:`file`,size:t.bytes.length,mtime:t.mtime,ctime:t.ctime}}remove(e){return this.entries.delete(i(e))}require(e){let t=i(e),n=this.entries.get(t);if(!n)throw new c(`ENOENT`,`no such file or directory`,t);return n}};const F={[_]:{stat:()=>({type:`file`,size:0,mtime:0,ctime:0}),read:e=>(e?.encoding??`utf-8`)===`utf-8`?``:new Uint8Array,readText:()=>``,write:()=>{}}},I=[`/tmp/`];var L=class{ephemeralFds=new P;vfs;allowedPrefixes;readOnlyPrefixes;readGrantPatterns=[];writeEnforcement;includeMounts;constructor(e,t,n=[],r=`hard`,a={}){this.vfs=e;let o=e=>{let t=i(e);return t.endsWith(`/`)?t:t+`/`};this.allowedPrefixes=t.map(o),this.readOnlyPrefixes=n.map(o),this.writeEnforcement=r,this.includeMounts=a.includeMounts!==!1}getAllPrefixes(){let e=this.includeMounts?this.vfs.listMounts().map(e=>e.endsWith(`/`)?e:e+`/`):[];return[...this.allowedPrefixes,...this.readOnlyPrefixes,...e,...I]}setReadGrants(e){this.readGrantPatterns=[];for(let t of new Set(e))this.addReadGrant(t)}addReadGrant(e){let t=e.split(`/`),n=[];for(let e=1;e<t.length;e++)n.push(a(t.slice(0,e).join(`/`)||`/`));this.readGrantPatterns.push({pattern:e,regex:a(e),ancestorRegexes:n})}matchesReadGrant(e){return this.readGrantPatterns.some(t=>t.regex.test(e))}leadsToReadGrant(e){return this.readGrantPatterns.some(t=>t.ancestorRegexes.some(t=>t.test(e)))}isAllowed(e){let t=i(e),n=this.getAllPrefixes();return this.matchesReadGrant(t)||this.leadsToReadGrant(t)||n.some(e=>t===e.slice(0,-1)||t.startsWith(e)||t===`/`||e.startsWith(t+`/`))}isAllowedStrict(e){let t=i(e),n=this.getAllPrefixes();return this.matchesReadGrant(t)||n.some(e=>t===e.slice(0,-1)||t.startsWith(e))}isWritable(e){let t=i(e);return[...this.allowedPrefixes,...I].some(e=>t===e.slice(0,-1)||t.startsWith(e))}canWrite(e){return P.handles(e)||this.isWritable(e)}checkWrite(e){if(this.writeEnforcement!==`sudo-delegated`&&!this.isWritable(e))throw new 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 forgetSidecarConsistency(){await this.vfs.forgetSidecarConsistency()}async flush(){await this.vfs.flush()}isPathUnderMount(e){return this.vfs.isPathUnderMount(e)}async readFile(e,t){let n=F[i(e)];if(n)return n.read(t);if(P.handles(e))return this.ephemeralFds.read(e,t);if(!this.isAllowedStrict(e))throw new c(`ENOENT`,`no such file or directory`,i(e));let r=await this.resolveAndCheckRead(e);return this.vfs.readFile(r,t)}async readFileRange(e,t,n){if(!this.isAllowedStrict(e))throw new c(`ENOENT`,`no such file or directory`,i(e));let r=await this.resolveAndCheckRead(e);return this.vfs.readFileRange(r,t,n)}async getNativeFile(e){if(F[i(e)]||P.handles(e)||!this.isAllowedStrict(e))return null;try{let t=await this.resolveAndCheckRead(e);return await this.vfs.getNativeFile(t)}catch{return null}}async readDir(e,t){if(!this.isAllowed(e))return[];let n=e;if(this.isAllowedStrict(e))try{n=await this.resolveAndCheckRead(e)}catch{return[]}let r=await this.vfs.readDir(n,t);if(!this.isAllowedStrict(e)){let t=i(e);return r.filter(e=>{let n=t===`/`?`/${e.name}`:`${t}/${e.name}`;return this.isAllowed(n)})}return r}async stat(e){let t=F[i(e)];if(t)return t.stat();if(P.handles(e))return this.ephemeralFds.stat(e);if(!this.isAllowed(e))throw new 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=F[i(e)];return t?t.stat():P.handles(e)?this.ephemeralFds.has(e)?this.ephemeralFds.stat(e):null:!this.isAllowedStrict(e)||this.scanPathForSymlinks(e,!0)!==!1?null:this.vfs.statSync(e)}lstatSync(e){let t=F[i(e)];return t?t.stat():P.handles(e)?this.ephemeralFds.has(e)?this.ephemeralFds.stat(e):null:!this.isAllowed(e)||this.scanPathForSymlinks(e,!1)!==!1?null:this.vfs.lstatSync(e)}readDirSync(e){if(!this.isAllowed(e)||this.scanPathForSymlinks(e,!0)!==!1)return null;let t=this.vfs.readDirSync(e);if(t===null)return null;if(this.isAllowedStrict(e))return t;let n=i(e);return t.filter(e=>{let t=n===`/`?`/${e.name}`:`${n}/${e.name}`;return this.isAllowed(t)})}async realpath(e){if(P.handles(e)){let t=i(e);if(!this.ephemeralFds.has(t))throw new 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(F[i(e)])return!0;if(P.handles(e))return this.ephemeralFds.has(e);if(!this.isAllowed(e))return!1;if(this.isAllowedStrict(e))try{await this.resolveAndCheckRead(e)}catch{return!1}return this.vfs.exists(e)}async readTextFile(e){let t=F[i(e)];if(t)return t.readText();if(P.handles(e))return this.ephemeralFds.readText(e);if(!this.isAllowedStrict(e))throw new 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=F[i(e)];if(r){r.write(t);return}if(P.handles(e)){this.ephemeralFds.write(e,t);return}return await this.checkContentWrite(e),this.vfs.writeFile(e,t,n)}async appendFile(e,t){let n=F[i(e)];if(n){n.write(t);return}if(P.handles(e)){this.ephemeralFds.append(e,t);return}return await this.checkContentWrite(e),this.vfs.appendFile(e,t)}async chmod(e,t){return this.refuseDescriptorTreeOp(e),await this.checkContentWrite(e),this.vfs.chmod(e,t)}async utimes(e,t,n){return this.refuseDescriptorTreeOp(e),await this.checkContentWrite(e),this.vfs.utimes(e,t,n)}async checkContentWrite(e){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}}refuseDescriptorTreeOp(e){if(P.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(P.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(P.handles(e)){let n=this.ephemeralFds.read(e,{encoding:`binary`});await this.writeFile(t,n);return}if(P.handles(t)){if(!this.isAllowed(e))throw new 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=F[i(e)];if(t)return t.stat();if(P.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(){let e=this.vfs.listMounts();return this.includeMounts?e:e.filter(e=>this.isAllowedStrict(e))}listMountPoints(){let e=this.vfs.listMountPoints();return this.includeMounts?e:e.filter(e=>this.isAllowed(e.path))}getMountIndex(){return this.vfs.getMountIndex()}async refreshMount(e,t){return this.refuseDescriptorTreeOp(e),this.checkWrite(e),this.vfs.refreshMount(e,t)}async dispose(){await this.vfs.dispose()}};function R(e,t){if(e instanceof 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 z=[`ENOENT`,`EEXIST`,`ENOTDIR`,`EISDIR`,`ENOTEMPTY`,`EINVAL`,`EACCES`,`ELOOP`,`EBUSY`,`EFBIG`,`EBADF`,`ENOSYS`,`EOPNOTSUPP`,`EXDEV`,`EIO`];function B(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(z.includes(r)){let n=e instanceof Error?e.message:String(e);return n.startsWith(`${r}: `)&&(n=n.slice(r.length+2),n=n.replace(/, undefined( '[^']*')?$/,``).replace(/ '[^']*'$/,``)),new 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):r.includes(`EOPNOTSUPP`)||r.includes(`ENOTSUP`)?new c(`EOPNOTSUPP`,`operation not supported`,t):r.includes(`EXDEV`)?new c(`EXDEV`,`cross-device link`,t):new c(`EINVAL`,r,t)}function V(e){return e===void 0?`absent`:(e&61440)==16384?`directory`:`file`}function H(e,t){return t===`absent`?!1:e.kind===`missing`||e.kind!==t}function U(e){let t=e?.mode;return typeof t==`number`?t:void 0}function W(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=V(U(r));o!==V(U(i))&&a.push({path:n,ownIsDirectory:o===`directory`})}return a}async function G(e,t){let n=t.split(`/`).filter(Boolean),r=n.pop();if(r===void 0)return null;try{let t=e;for(let e of n)t=await t.getDirectoryHandle(e);return await(await t.getFileHandle(r)).getFile()}catch{return null}}async function K(e,t,n,r){try{return await e.lstat(t)}catch(e){let t=B(e,r);if(t.code===`ENOENT`&&n)return null;throw t}}async function q(e,t,r){let a;try{a=await e.readlink(t)}catch(e){throw B(e,r)}return a.startsWith(`/`)?i(a):i(o(n(t).dir,a))}async function J(e,t,n,r,i,a){let o=t===`/`?`/${n}`:`${t}/${n}`;for(;;){let t=await K(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 q(e,o,i)}}async function Y(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 J(e,o,a[t],t===a.length-1,r,s);o=n.resolved,s=n.hops}return o}async function X(e,t,n){return t(n)?n:Y(e,t,n)}function Z(){try{if(typeof globalThis.navigator?.storage?.getDirectory==`function`)return`opfs`}catch{}return`memory`}function Q(e,t){let n=e.kind===`directory`?`directory`:`file`;return t?{name:e.name,type:n,...e.size===void 0?{}:{size:e.size},...e.lastModified===void 0?{}:{mtime:e.lastModified},...e.ctime===void 0?{}:{ctime:e.ctime},...e.ino===void 0?{}:{ino:e.ino},...e.identity===void 0?{}:{identity:e.identity},...e.dev===void 0?{}:{dev:e.dev},...e.uid===void 0?{}:{uid:e.uid},...e.gid===void 0?{}:{gid:e.gid},...e.mode===void 0?{}:{mode:e.mode}}:{name:e.name,type:n}}function te(e,t){switch(e.kind){case`local`:case`proc`:return{kind:`local`,mountId:e.mountId,idbHandleKey:t};case`hostfs`:return{kind:`hostfs`,mountId:e.mountId,hostPath:e.getHostPath()};default:return{kind:e.kind===`s3`?`s3`:e.kind===`aem`?`aem`:`da`,mountId:e.mountId,source:e.source,profile:e.profile??`default`}}}var $=class e{lfs;lfsSync;rawLfs=null;rawLfsSync=null;_ready;_readyResolved=!1;backend;mountPoints=new Map;opfsBackendFs=null;opfsHandle=null;mountRoot=``;internalMounts=new Set;watcher=null;dbName;mountSyncChannel=null;mountIndex=new d;static writeChains=new Map;onRepairProgress;constructor(t,n,r,i,a,o){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,o):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 opfsInitChains=new Map;static async initOpfsBackend(t,n,r,i){let a=(e.opfsInitChains.get(t.dbName)??Promise.resolve()).catch(()=>{}).then(()=>e.resolveOpfsBackend(t,n,r,i));e.opfsInitChains.set(t.dbName,a);try{await a}finally{e.opfsInitChains.get(t.dbName)===a&&e.opfsInitChains.delete(t.dbName)}}static async resolveOpfsBackend(t,n,r,i){let a=e.opfsBackends.get(t.dbName);if(a&&r)throw new c(`EBUSY`,`Cannot wipe an OPFS backend with live holders`,t.dbName);if(a&&i!==void 0&&a.asyncCache!==i)throw new c(`EBUSY`,`OPFS async cache setting conflicts with the live backend`,t.dbName);let o=n??await e.acquireOpfsHandle(t.dbName,r);await t.withWriteLock(()=>e.seedOpfsMetadataSidecarIfMissing(o));let s=await import(`./dist-SZE428w3.js`);await e.ensureRootMount(s);let l=`/__opfs__/${t.dbName}`,u=e.opfsBackends.get(t.dbName);if(!u){let{resolveOpfsMount:n}=await import(`./opfs-mount-DbDiMdyl.js`),r=await n({handle:o,dbName:t.dbName,asyncCache:i,onRepairProgress:t.onRepairProgress,withWriteLock:e=>t.withWriteLock(e)});try{s.mount(l,r)}catch{}u={backendFs:r,refs:0,asyncCache:i!==!1,sidecarDirty:{paths:new Set,prefixes:new Set}},e.opfsBackends.set(t.dbName,u)}u.refs+=1,t.opfsBackendFs=u.backendFs.index?u.backendFs:null,t.opfsHandle=o,t.mountRoot=l,t.rawLfs=s.promises,t.rawLfsSync=s}static async initMemoryBackend(t,n,r){let i=await import(`./dist-SZE428w3.js`);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)),appendFile:async(t,r)=>{this._readyResolved||await this._ready,await n().appendFile(e(t),r)},chmod:async(t,r)=>{this._readyResolved||await this._ready,await n().chmod(e(t),r)},utimes:async(t,r,i)=>{this._readyResolved||await this._ready,await n().utimes(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(t){let n=`.metadata.json`;try{let r=await t.getFileHandle(n);if(e.isUsableMetadataDocument(await e.readSidecarText(r)))return;console.warn(`[virtual-fs] metadata sidecar is unparseable (torn write?); reseeding an empty index`)}catch(e){if(e?.name!==`NotFoundError`)throw e}let r=await(await t.getFileHandle(n,{create:!0})).createWritable(),i=JSON.stringify({version:1,maxSize:4294967295,entries:{}});await r.write(i),await r.close()}static async readSidecarText(e){let t;for(let n=0;n<3;n++)try{return await(await e.getFile()).text()}catch(e){if(e?.name!==`NotReadableError`)throw e;t=e}throw t}static isUsableMetadataDocument(e){let t;try{t=JSON.parse(e)}catch{return!1}if(!t||typeof t!=`object`)return!1;let n=t.entries;return!!n&&typeof n==`object`}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??Z(),a=new e(n,r,i,void 0,t?.onRepairProgress,t?.opfsAsyncCache);try{await a._ready}catch(e){throw a.mountSyncChannel?.close(),e}return r&&await h().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=y(e,r,i))}let o=JSON.stringify(x(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=W(e,t,n.paths,n.prefixes);if(i.length===0)return;let a=b(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}async forgetSidecarConsistency(){await this.dropSidecarConsistency()}sidecarConsistencyDrop=null;dropSidecarConsistency(){if(this.backend!==`opfs`||!this.opfsHandle)return Promise.resolve();if(!this.sidecarConsistencyDrop){let e=this.opfsHandle;this.sidecarConsistencyDrop=S(e).catch(e=>{throw this.sidecarConsistencyDrop=null,e})}return this.sidecarConsistencyDrop}invalidatePaths(e){if(this.backend!==`opfs`||!this.opfsBackendFs)return;e.length>0&&this.dropSidecarConsistency().catch(()=>void 0);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 b(n)(a),s=V(t.index.get(a)?.mode),c=t._handles?.get(a),l=c?.kind===`directory`?`directory`:c?.kind===`file`?`file`:`absent`,u=H(o,s),d=H(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}localIdentity(e){return C(`zenfs:${this.backend}:${this.dbName}`,e)}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-SZE428w3.js`)).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(a===`symlink`?{name:i,type:a}:{name:i,type:a,size:t.size,mtime:t.mtimeMs,ctime:t.ctimeMs,...t.ino===void 0?{}:{ino:t.ino,identity:this.localIdentity(t.ino),dev:t.dev},...t.uid===void 0?{}:{uid:t.uid},...t.gid===void 0?{}:{gid:t.gid},mode:t.mode})}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,identity:this.localIdentity(e.ino),dev:e.dev,mode:e.mode}}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,identity:this.localIdentity(e.ino),dev:e.dev,mode:e.mode};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,identity:this.localIdentity(e.ino),dev:e.dev,mode:e.mode}}return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,ino:e.ino,identity:this.localIdentity(e.ino),dev:e.dev,mode:e.mode}}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}),await this.dropSidecarConsistency();try{await this.lfs.mkdir(a)}catch{}if(this.mountPoints.set(a,t),t.kind===`local`){let e=r?.limits??u(r?.env??{});this.mountIndex.registerMount(a,t.getHandle(),e)}let s=te(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 f(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 p(t)}catch{}}async reconstructBackendFromDescriptor(e,t){switch(e.kind){case`local`:{let t=await m(e.idbHandleKey);if(!t)throw Error(`no handle stored for ${e.idbHandleKey}`);return l.fromHandle(t,{mountId:e.mountId})}case`hostfs`:{let{HostFsMountBackend:n}=await import(`./backend-hostfs-CMj5JyW-.js`);return new n({targetPath:t,hostPath:e.hostPath,mountId:e.mountId})}case`s3`:{let{S3MountBackend:t,RemoteMountCache:n,makeSignedFetchS3:r}=await import(`./mount-BfPgf0TT.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-BfPgf0TT.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-BfPgf0TT.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}getMountBackend(e){let t=i(e);return this.mountPoints.get(t)??null}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}),await this.dropSidecarConsistency();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,u(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){R(e,n)}}let a=await this.resolveSymlinks(n);try{return(t?.encoding??`utf-8`)===`utf-8`?await this.lfs.readFile(a,{encoding:`utf8`}):await this.lfs.readFile(a)}catch(e){throw B(e,n)}}async readFileRange(e,t,n){let r=i(e);if(!Number.isInteger(t)||!Number.isInteger(n)||t<0||n<t)throw new c(`EINVAL`,`invalid byte range ${t}-${n}`,r);if(t===n)return new Uint8Array;let a=this.findMount(r),o=a?.backend.readFileRange;if(a&&o){if(a.relParts.length===0)throw new c(`EISDIR`,`is a directory`,r);try{return await o.call(a.backend,a.relParts.join(`/`),t,n)}catch(e){R(e,r)}}let s=await this.sliceNativeFile(r,t,n);if(s)return s;let l=await this.readFile(r,{encoding:`binary`});return new Uint8Array(l.subarray(t,Math.min(n,l.byteLength)))}async sliceNativeFile(e,t,n){try{let r=await this.getNativeFile(e);if(!r)return null;let i=r.slice(t,Math.min(n,r.size));return new Uint8Array(await i.arrayBuffer())}catch{return null}}async getNativeFile(e){let t=i(e),n=this.findMount(t);if(n){let e=n.backend.getNativeFile;if(!e||n.relParts.length===0)return null;try{return await e.call(n.backend,n.relParts.join(`/`))}catch{return null}}let r=this.opfsHandle;if(!r)return null;try{return await G(r,await this.resolveSymlinks(t))}catch{return null}}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){R(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()=>{await this.dropSidecarConsistency(),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 B(e,a)}}else throw B(e,a)}try{await this.lfs.truncate?.(s,e)}catch(e){throw B(e,a)}}),this.watcher?.notify([{type:l?`modify`:`create`,path:s,entryType:`file`}])}async appendFile(e,t){let r=i(e);await this.withKindMismatchRetry(r,()=>this.withWriteLock(async()=>{if(this.findMount(r)){await this.appendMounted(r,t);return}await this.dropSidecarConsistency();let e=r,i=!1;try{if(e=await this.resolveSymlinks(r),(await this.lfs.stat(e)).isDirectory())throw new c(`EISDIR`,`is a directory`,r);i=!0}catch(e){let t=B(e,r);if(t.code!==`ENOENT`)throw t}this.markSidecarDirty(e);let{dir:a}=n(e);await this.mkdirRecursiveUnlocked(a);try{await this.lfs.appendFile(e,t)}catch(e){throw B(e,r)}this.watcher?.notify([{type:i?`modify`:`create`,path:e,entryType:`file`}])}))}async appendMounted(e,t){let n=new Uint8Array;try{let t=await this.readFileInner(e,{encoding:`binary`});n=typeof t==`string`?new TextEncoder().encode(t):new Uint8Array(t)}catch(t){let n=B(t,e);if(n.code!==`ENOENT`)throw n}let r=typeof t==`string`?new TextEncoder().encode(t):t,i=new Uint8Array(n.length+r.length);i.set(n),i.set(r,n.length),await this.writeFileInner(e,i)}async chmod(e,t){if(!Number.isInteger(t)||t<0||t>4095)throw new c(`EINVAL`,`invalid file mode`,i(e));await this.changeMetadata(e,e=>this.lfs.chmod(e,t))}async utimes(e,t,n){if(!Number.isFinite(t.getTime())||!Number.isFinite(n.getTime()))throw new c(`EINVAL`,`invalid file time`,i(e));await this.changeMetadata(e,e=>this.lfs.utimes(e,t,n))}async changeMetadata(e,t){let n=i(e);if(this.findMount(n))throw await this.stat(n),new c(`ENOSYS`,`metadata changes are not supported by this mount`,n);await this.withKindMismatchRetry(n,()=>this.withWriteLock(async()=>{await this.dropSidecarConsistency();let e=await this.resolveSymlinks(n);try{let n=await this.lfs.stat(e);this.markSidecarDirty(e),await t(e),await this.writeOpfsMetadataSidecarUnlocked(),this.watcher?.notify([{type:`modify`,path:e,entryType:n.isDirectory()?`directory`:`file`}])}catch(e){throw B(e,n)}}))}async readDir(e,t){let n=i(e),r=this.findMount(n);return r?this.readDirMounted(n,r,t):this.readDirLocal(n)}async readDirMounted(e,t,n){let r=n?.includeStats===!0?void 0:this.mountIndex.getDirectoryEntries(t.path,e);if(r!==void 0){let t=new Map;for(let e of r)t.set(e.name,{name:e.name,type:e.type});return this.addNestedMountEntries(t,e),[...t.values()]}let i=t.relParts.join(`/`)||`/`,a;try{a=await t.backend.readDir(i,n)}catch(t){R(t,e)}let o=new Map,s=t.backend.listingStatsMatchStat===!0;for(let e of a)o.set(e.name,Q(e,s));return this.addNestedMountEntries(o,e),[...o.values()]}async readDirLocal(e){return this.withKindMismatchRetry(e,()=>this.readDirLocalInner(e))}async readDirLocalInner(e){let t=await this.resolveSymlinks(e);try{let e=await this.lfs.readdir(t),n=[];for(let r of e){let e=await this.statDirEntry(t,r);e&&n.push(e)}return n}catch(t){throw B(t,e)}}async statDirEntry(e,t){let n=e===`/`?`/${t}`:`${e}/${t}`;try{let e=await this.lfs.lstat(n);return e.isSymbolicLink()?{name:t,type:`symlink`}:{name:t,type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,...e.ino===void 0?{}:{ino:e.ino,identity:this.localIdentity(e.ino),dev:e.dev},...e.uid===void 0?{}:{uid:e.uid},...e.gid===void 0?{}:{gid:e.gid},mode:e.mode}}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 B(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){R(e,n)}t||this.watcher?.notify([{type:`create`,path:n,entryType:`directory`}]);return}if(t?.recursive){let e=await this.withWriteLock(async()=>(await this.dropSidecarConsistency(),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()=>{await this.dropSidecarConsistency(),this.markSidecarDirty(n);try{await this.lfs.mkdir(n)}catch(e){throw B(e,n)}}),this.watcher?.notify([{type:`create`,path:n,entryType:`directory`}])}async rm(e,t){return this.withKindMismatchRetry(i(e),()=>this.rmInner(e,t))}async rmInner(e,t){let n=i(e),r=this.findMount(n);if(r){if(r.relParts.length===0)throw new 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){R(e,n)}this.watcher?.notify([{type:`delete`,path:n,entryType:e}]),this.mountIndex.notifyDelete(n);return}try{let e=await this.lfs.lstat(n);await this.withWriteLock(async()=>{await this.dropSidecarConsistency(),e.isSymbolicLink()?await this.lfs.unlink(n):e.isDirectory()?t?.recursive?await this.rmRecursiveUnlocked(n):await this.lfs.rmdir(n):await this.lfs.unlink(n),this.markSidecarDirty(n,`prefix`),await this.writeOpfsMetadataSidecarUnlocked()})}catch(e){throw B(e,n)}this.watcher?.notify([{type:`delete`,path:n}])}async rmRecursiveUnlocked(e){let t=await this.lfs.readdir(e);for(let n of t){let t=e===`/`?`/${n}`:`${e}/${n}`,r=await this.lfs.lstat(t);r.isSymbolicLink()?await this.lfs.unlink(t):r.isDirectory()?await this.rmRecursiveUnlocked(t):await this.lfs.unlink(t)}await this.lfs.rmdir(e)}async stat(e){return this.withKindMismatchRetry(e,()=>this.statInner(e))}async statInner(e){let t=i(e),n=this.findMount(t);if(n){if(n.relParts.length===0)try{let e=await this.lfs.stat(t);return{type:`directory`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs}}catch{return{type:`directory`,size:0,mtime:Date.now(),ctime:Date.now()}}let e=n.relParts.join(`/`);try{let t=await n.backend.stat(e);return{type:t.kind===`directory`?`directory`:`file`,size:t.size,mtime:t.mtime,ctime:t.ctime??t.mtime,...t.ino===void 0?{}:{ino:t.ino},...t.identity===void 0?{}:{identity:t.identity},...t.dev===void 0?{}:{dev:t.dev},...t.uid===void 0?{}:{uid:t.uid},...t.gid===void 0?{}:{gid:t.gid},...t.mode===void 0?{}:{mode:t.mode}}}catch(e){R(e,t)}}let r=await this.resolveSymlinks(t);try{let e=await this.lfs.stat(r);return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,ino:e.ino,dev:e.dev,identity:this.localIdentity(e.ino),uid:e.uid,gid:e.gid,mode:e.mode}}catch(e){throw B(e,t)}}async exists(e){let t=i(e),n=this.findMount(t);if(n){if(n.relParts.length===0)return!0;try{return await this.stat(t),!0}catch{return!1}}try{return await this.stat(t),!0}catch{try{return await this.lfs.lstat(t),!0}catch{return!1}}}async rename(e,t){return this.withKindMismatchRetryPaths([i(e),i(t)],()=>this.renameInner(e,t))}async renameInner(e,t){let n=i(e),r=i(t);if(n===r)return;let a;try{a=await this.lstat(n)}catch{}let o=a?.type,s=this.findMount(n);if(s?.backend.rename){let e=this.findMount(r);if(e&&e.backend===s.backend){let t=!1;try{t=(await s.backend.rename(s.relParts.join(`/`),e.relParts.join(`/`)))?.noop===!0}catch(e){R(e,n)}t||(this.watcher?.notify([{type:`delete`,path:n,entryType:o},{type:`create`,path:r,entryType:o}]),this.mountIndex.notifyRename(n,r));return}}if(a)try{let e=await this.lstat(r);if(v(a,e))return}catch{}try{await this.withWriteLock(async()=>{await this.dropSidecarConsistency(),this.markSidecarDirty(n,`prefix`),this.markSidecarDirty(r,`prefix`),await this.lfs.rename(n,r),await this.writeOpfsMetadataSidecarUnlocked()})}catch(e){throw B(e,n)}this.watcher?.notify([{type:`delete`,path:n,entryType:o},{type:`create`,path:r,entryType:o}]),this.mountIndex.notifyRename(n,r)}async readTextFile(e){return await this.readFile(e,{encoding:`utf-8`})}async*walk(e,t,n=0){yield*E({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){let n=await this.stat(e);if(n.type===`directory`)throw new c(`EISDIR`,`is a directory`,e);try{let e=await this.stat(t);if(v(n,e))return}catch{}let r=await this.readFile(e,{encoding:`binary`});await this.writeFile(t,r)}dirname(e){return n(i(e)).dir}basename(e){return n(i(e)).base}resolveSymlinkTargetPath(e,t){return e.startsWith(`/`)?i(e):i(o(n(t).dir,e))}assertSymlinkCreateAllowed(e,t){if(this.findMount(t))throw new c(`EINVAL`,`symlinks not supported on mounted filesystems`,t);let n=this.resolveSymlinkTargetPath(e,t);if(this.findMount(n))throw new c(`EXDEV`,`cannot create a symlink across a mount boundary to '${n}'`,t)}async symlink(e,t){let r=i(t);this.assertSymlinkCreateAllowed(e,r);let{dir:a}=n(r);await this.withWriteLock(async()=>{await this.dropSidecarConsistency(),a!==`/`&&await this.mkdirRecursiveUnlocked(a);try{await this.lfs.symlink(e,r)}catch(t){if(a!==`/`&&t instanceof Error&&t.message.includes(`ENOENT`)){await this.mkdirRecursiveUnlocked(a);try{await this.lfs.symlink(e,r)}catch(e){throw B(e,r)}}else throw B(t,r)}this.markSidecarDirty(r),await this.writeOpfsMetadataSidecarUnlocked()}),this.watcher?.notify([{type:`create`,path:r,entryType:`symlink`}])}async readlink(e){let t=i(e);try{return await this.lfs.readlink(t)}catch(e){throw B(e,t)}}async lstat(e){let t=i(e);if(this.findMount(t)||t===`/`)return this.stat(t);try{let e=await this.lfs.lstat(t);if(e.isSymbolicLink()){let n=await this.lfs.readlink(t);return{type:`symlink`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,isSymlink:!0,symlinkTarget:n,ino:e.ino,dev:e.dev,identity:this.localIdentity(e.ino),uid:e.uid,gid:e.gid,mode:e.mode}}return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,ino:e.ino,dev:e.dev,identity:this.localIdentity(e.ino),uid:e.uid,gid:e.gid,mode:e.mode}}catch(e){throw B(e,t)}}async realpath(e){return Y(this.lfs,e=>this.findMount(e)!==null,e)}resolveSymlinks(e){return X(this.lfs,e=>this.findMount(e)!==null,e)}},ne=e({FsError:()=>c,FsWatcher:()=>j,MountIndex:()=>d,RestrictedFS:()=>L,VirtualFS:()=>$,joinPath:()=>o,normalizePath:()=>i,pathSegments:()=>r,resolveVfsBackendFromEnv:()=>Z,sameFileIdentity:()=>v,splitPath:()=>n,statsFromDirEntry:()=>s});export{j as i,$ as n,L as r,ne as t};
@@ -1,2 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/dist-HBVgABmW.js","assets/rolldown-runtime-Dd_uD5pT.js","assets/buffer-DvhmllZ2.js","assets/opfs-mount-DF1_TQm7.js","assets/backend-hostfs-DVOOQmWO.js","assets/api-endpoint-DuEQRZ4g.js","assets/runtime-env-Dlaokqg1.js","assets/types-D8gIX-W-.js","assets/remote-cache-3KNT1gsp.js","assets/mount-BsWbgqHU.js","assets/preload-helper-Czpn1I53.js","assets/mime-types-D0xZwlMO.js","assets/base64-ELzoYfwP.js","assets/mount-table-store-dY2IfQ5S.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,t as i}from"./types-D8gIX-W-.js";import{a,i as o,n as s,r as c,t as l}from"./path-utils-DNJG-zQf.js";import{r as u,t as d}from"./bounded-walk-BjxKWNqp.js";import{n as ee,t as te}from"./virtual-device-paths-D45tpPP6.js";import{t as f}from"./same-file-identity-DuEcSmPX.js";import{a as ne,i as re,n as ie,t as p}from"./mount-table-store-dY2IfQ5S.js";var m=n(`fs-watcher`),ae=0;function oe(e,t){return t===`/`||e===t||e.startsWith(t+`/`)}var h=class{registrations=new Map;watch(e,t,n){let r=`fsw-${++ae}`;return this.registrations.set(r,{id:r,basePath:e,filter:t,callback:n}),m.debug(`Watch registered`,{id:r,basePath:e}),()=>{this.registrations.delete(r),m.debug(`Watch unregistered`,{id:r})}}notify(e){if(e.length!==0)for(let[,t]of this.registrations){let n=e.filter(e=>oe(e.path,t.basePath)&&t.filter(e.path));if(n.length>0)try{t.callback(n)}catch(e){m.error(`Watch callback error`,{id:t.id,error:e instanceof Error?e.message:String(e)})}}}dispose(){this.registrations.clear(),m.debug(`All watchers disposed`)}get size(){return this.registrations.size}},g=n(`mount-index`),se=400,ce=2e6,le=`SLICC_MOUNT_INDEX_MAX_DEPTH`,ue=`SLICC_MOUNT_INDEX_MAX_ENTRIES`,_=256,v=class extends Error{cause;constructor(e,t){super(e),this.name=`MountIndexAbortError`,this.cause=t}};function de(e){let t=e.map(([e,t])=>`${e}\u0000${t.kind}`).sort(),n=t.length>_?t.slice(0,_):t;return`${t.length}\u0001${n.join(``)}`}async function fe(e,t){let n=e.isSameEntry;if(typeof n!=`function`)return!1;try{return await n.call(e,t)}catch{return!1}}function pe(e,t){return e instanceof Map?e.get(t):e[t]}function me(e){let t=e.trim();if(t===``)return;let n=Number(t);if(!(!Number.isInteger(n)||n<=0))return n}function y(e,t,n){let r=pe(e,t);if(r===void 0||r.trim()===``)return n;let i=me(r);return i===void 0?(g.warn(`Ignoring invalid ${t}; expected a positive integer, using default`,{value:r,fallback:n}),n):i}function b(e){return{maxDepth:y(e,le,se),maxEntries:y(e,ue,ce),skipNoiseDirs:!0}}var x=class{mounts=new Map;listeners=new Set;registerMount(e,t,n=b({})){this.mounts.get(e)?.abortController?.abort();let r=new AbortController,i={handle:t,state:{status:`pending`,indexed:0},files:new Set,directories:new Set,childrenByDirectory:new Map,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(),n.childrenByDirectory.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=n.childrenByDirectory.get(t);if(r)return[...r].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`||this.isSkippedNoisePath(t,e,n,`file`))return;n.files.add(e),this.addPathToChildIndex(n,e,`file`);let r=this.parentPath(e);for(;(r===t||r.startsWith(`${t}/`))&&(n.directories.add(r),this.ensureDirectoryChildren(n,r),r!==t);)this.addPathToChildIndex(n,r,`directory`),r=this.parentPath(r)}notifyDelete(e){let t=this.findMountForPath(e);if(!t)return;let n=this.mounts.get(t);if(n?.state.status!==`ready`||this.isSkippedNoisePath(t,e,n,`unknown`))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);this.removePathFromChildIndex(n,e);for(let t of n.childrenByDirectory.keys())(t===e||t.startsWith(r))&&n.childrenByDirectory.delete(t)}notifyRename(e,t){let n=this.findMountForPath(e);if(!n)return;let r=this.mounts.get(n);if(r?.state.status!==`ready`)return;let i=r.files.has(e)?`file`:r.directories.has(e)?`directory`:`unknown`;if(i===`unknown`||this.isSkippedNoisePath(n,e,r,i))return;if(this.isSkippedNoisePath(n,t,r,i)){this.notifyDelete(e);return}if(i===`file`){r.files.delete(e),r.files.add(t),this.removePathFromChildIndex(r,e),this.addPathToChildIndex(r,t,`file`);return}r.directories.delete(e),r.directories.add(t);let a=e+`/`,o=t+`/`;for(let e of[...r.files])e.startsWith(a)&&(r.files.delete(e),r.files.add(o+e.slice(a.length)));for(let e of[...r.directories])e.startsWith(a)&&(r.directories.delete(e),r.directories.add(o+e.slice(a.length)));this.removePathFromChildIndex(r,e),this.addPathToChildIndex(r,t,`directory`);let s=[...r.childrenByDirectory.entries()].filter(([t])=>t===e||t.startsWith(a));for(let[e]of s)r.childrenByDirectory.delete(e);for(let[n,i]of s){let s=n===e?t:o+n.slice(a.length);r.childrenByDirectory.set(s,i)}}ensureDirectoryChildren(e,t){let n=e.childrenByDirectory.get(t);return n||(n=new Map,e.childrenByDirectory.set(t,n)),n}addPathToChildIndex(e,t,n){let r=t.slice(t.lastIndexOf(`/`)+1);r&&(this.ensureDirectoryChildren(e,this.parentPath(t)).set(r,n),n===`directory`&&this.ensureDirectoryChildren(e,t))}removePathFromChildIndex(e,t){let n=t.slice(t.lastIndexOf(`/`)+1);e.childrenByDirectory.get(this.parentPath(t))?.delete(n)}parentPath(e){let t=e.lastIndexOf(`/`);return t<=0?`/`:e.slice(0,t)}isSkippedNoisePath(e,t,n,r){if(!n.limits.skipNoiseDirs||!t.startsWith(`${e}/`))return!1;let i=t.slice(e.length+1).split(`/`),a=r===`unknown`?n.files.has(t)?`file`:n.directories.has(t)?`directory`:`unknown`:r;for(let e=0;e<i.length;e++){let t=e===i.length-1;if(!(t&&a===`file`)&&!(t&&a===`unknown`&&!d(i[e]))&&d(i[e]))return!0}return!1}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}findMountForPath(e){let t;for(let n of this.mounts.keys())(e===n||e.startsWith(n+`/`))&&(!t||n.length>t.length)&&(t=n);return t}notifyListeners(){for(let e of this.listeners)try{e()}catch{}}async indexMount(e,t,n){t.state={status:`indexing`,indexed:0},this.notifyListeners();try{if(await this.walkHandle(e,t.handle,t,n),n.aborted)return;t.state={status:`ready`,indexed:t.files.size+t.directories.size,total:t.files.size+t.directories.size},t.abortController=null,g.info(`Mount indexed`,{path:e,files:t.files.size,directories:t.directories.size})}catch(r){if(n.aborted)return;let i=r instanceof Error?r.message:String(r),a=r instanceof v?r.cause:`indexing-error`;t.state={status:`error`,indexed:0,error:i,abortCause:a},g.error(`Mount indexing failed`,{path:e,error:i,abortCause:a})}this.notifyListeners()}async walkHandle(e,t,n,r,i=0,a=new Map){if(r.aborted)return;this.enforceWalkBounds(i,n),n.directories.add(e),this.ensureDirectoryChildren(n,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 v(`mount indexing aborted: directory nesting exceeded ${t.limits.maxDepth} levels`,`depth-exceeded`);if(t.directories.size+t.files.size>=t.limits.maxEntries)throw new v(`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 v(`mount indexing aborted: exceeded ${n.limits.maxEntries} entries`,`entries-exceeded`);i.push(e)}return i}async confirmNoCycle(e,t,n,r){let i=de(n),a=r.get(i);if(a){for(let n of a)if(await fe(n.handle,t))throw new v(`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}`;if(s.kind===`file`)n.files.add(t),this.addPathToChildIndex(n,t,`file`),n.state.indexed++;else if(s.kind===`directory`){if(n.limits.skipNoiseDirs&&d(o))continue;this.addPathToChildIndex(n,t,`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)))}}},S=new TextEncoder,C=new TextDecoder(`utf-8`,{fatal:!1}),w=class{entries=new Map;static handles(e){return ee(s(e))}has(e){return this.entries.has(s(e))}write(e,t){let n=s(e),r=typeof t==`string`?S.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})}append(e,t){let n=this.entries.get(s(e))?.bytes??new Uint8Array,r=typeof t==`string`?S.encode(t):t,i=new Uint8Array(n.length+r.length);i.set(n),i.set(r,n.length),this.write(e,i)}read(e,t){let n=this.require(e);return(t?.encoding??`utf-8`)===`utf-8`?C.decode(n.bytes):new Uint8Array(n.bytes)}readText(e){return C.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 i(`ENOENT`,`no such file or directory`,t);return n}},T={[te]:{stat:()=>({type:`file`,size:0,mtime:0,ctime:0}),read:e=>(e?.encoding??`utf-8`)===`utf-8`?``:new Uint8Array,readText:()=>``,write:()=>{}}},E=[`/tmp/`],D=class{ephemeralFds=new w;vfs;allowedPrefixes;readOnlyPrefixes;readGrantPatterns=[];writeEnforcement;includeMounts;constructor(e,t,n=[],r=`hard`,i={}){this.vfs=e;let a=e=>{let t=s(e);return t.endsWith(`/`)?t:t+`/`};this.allowedPrefixes=t.map(a),this.readOnlyPrefixes=n.map(a),this.writeEnforcement=r,this.includeMounts=i.includeMounts!==!1}getAllPrefixes(){let e=this.includeMounts?this.vfs.listMounts().map(e=>e.endsWith(`/`)?e:e+`/`):[];return[...this.allowedPrefixes,...this.readOnlyPrefixes,...e,...E]}setReadGrants(e){this.readGrantPatterns=[];for(let t of new Set(e))this.addReadGrant(t)}addReadGrant(e){let t=e.split(`/`),n=[];for(let e=1;e<t.length;e++)n.push(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,...E].some(e=>t===e.slice(0,-1)||t.startsWith(e))}canWrite(e){return w.handles(e)||this.isWritable(e)}checkWrite(e){if(this.writeEnforcement!==`sudo-delegated`&&!this.isWritable(e))throw new i(`EACCES`,`permission denied`,s(e))}async resolveAndCheckRead(e){try{let t=await this.vfs.realpath(e);if(!this.isAllowedStrict(t))throw new i(`ENOENT`,`no such file or directory`,s(e));return t}catch(t){throw t instanceof i?t:new i(`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 i(`EACCES`,`permission denied`,s(e));return t}catch(t){throw t instanceof i?t:new i(`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 i&&e.code===`EACCES`)throw e;return}let a=r+`/`+n;if(this.isWritable(a))return;let o=s(r)!==s(t);if(!(this.writeEnforcement===`sudo-delegated`&&!o))throw new i(`EACCES`,`permission denied`,s(e))}getUnderlyingFS(){return this.vfs}invalidatePaths(e){this.vfs.invalidatePaths(e)}async forgetSidecarConsistency(){await this.vfs.forgetSidecarConsistency()}async flush(){await this.vfs.flush()}isPathUnderMount(e){return this.vfs.isPathUnderMount(e)}async readFile(e,t){let n=T[s(e)];if(n)return n.read(t);if(w.handles(e))return this.ephemeralFds.read(e,t);if(!this.isAllowedStrict(e))throw new i(`ENOENT`,`no such file or directory`,s(e));let r=await this.resolveAndCheckRead(e);return this.vfs.readFile(r,t)}async readFileRange(e,t,n){if(!this.isAllowedStrict(e))throw new i(`ENOENT`,`no such file or directory`,s(e));let r=await this.resolveAndCheckRead(e);return this.vfs.readFileRange(r,t,n)}async getNativeFile(e){if(T[s(e)]||w.handles(e)||!this.isAllowedStrict(e))return null;try{let t=await this.resolveAndCheckRead(e);return await this.vfs.getNativeFile(t)}catch{return null}}async readDir(e,t){if(!this.isAllowed(e))return[];let n=e;if(this.isAllowedStrict(e))try{n=await this.resolveAndCheckRead(e)}catch{return[]}let r=await this.vfs.readDir(n,t);if(!this.isAllowedStrict(e)){let t=s(e);return r.filter(e=>{let n=t===`/`?`/${e.name}`:`${t}/${e.name}`;return this.isAllowed(n)})}return r}async stat(e){let t=T[s(e)];if(t)return t.stat();if(w.handles(e))return this.ephemeralFds.stat(e);if(!this.isAllowed(e))throw new i(`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=T[s(e)];return t?t.stat():w.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=T[s(e)];return t?t.stat():w.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(w.handles(e)){let t=s(e);if(!this.ephemeralFds.has(t))throw new i(`ENOENT`,`no such file or directory`,t);return t}let t;try{t=await this.vfs.realpath(e)}catch(t){throw t instanceof i?t:new i(`ENOENT`,`no such file or directory`,s(e))}if(!this.isAllowedStrict(t))throw new i(`ENOENT`,`no such file or directory`,s(e));return t}async exists(e){if(T[s(e)])return!0;if(w.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=T[s(e)];if(t)return t.readText();if(w.handles(e))return this.ephemeralFds.readText(e);if(!this.isAllowedStrict(e))throw new i(`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=T[s(e)];if(r){r.write(t);return}if(w.handles(e)){this.ephemeralFds.write(e,t);return}return await this.checkContentWrite(e),this.vfs.writeFile(e,t,n)}async appendFile(e,t){let n=T[s(e)];if(n){n.write(t);return}if(w.handles(e)){this.ephemeralFds.append(e,t);return}return await this.checkContentWrite(e),this.vfs.appendFile(e,t)}async chmod(e,t){return this.refuseDescriptorTreeOp(e),await this.checkContentWrite(e),this.vfs.chmod(e,t)}async utimes(e,t,n){return this.refuseDescriptorTreeOp(e),await this.checkContentWrite(e),this.vfs.utimes(e,t,n)}async checkContentWrite(e){this.checkWrite(e),await this.checkParentRealpathEscape(e);try{(await this.vfs.lstat(e)).type===`symlink`&&await this.resolveAndCheckWrite(e)}catch(e){if(e instanceof i&&e.code===`EACCES`)throw e}}refuseDescriptorTreeOp(e){if(w.handles(e))throw new i(`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(w.handles(e)){if(!this.ephemeralFds.remove(e))throw new i(`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 i&&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(w.handles(e)){let n=this.ephemeralFds.read(e,{encoding:`binary`});await this.writeFile(t,n);return}if(w.handles(t)){if(!this.isAllowed(e))throw new i(`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 i(`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 i&&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 i(`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 i(`ENOENT`,`no such file or directory`,s(e));return t}async lstat(e){let t=T[s(e)];if(t)return t.stat();if(w.handles(e))return this.ephemeralFds.stat(e);if(!this.isAllowed(e))throw new i(`ENOENT`,`no such file or directory`,s(e));let n=s(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 i(`ENOENT`,`no such file or directory`,n)}let c=o===`/`?`/${a}`:`${o}/${a}`;if(!this.isAllowed(c))throw new i(`ENOENT`,`no such file or directory`,n);return this.vfs.lstat(c)}watch(e,t,n){if(!this.isAllowed(e))throw new i(`EACCES`,`permission denied`,s(e));let r=this.vfs.getWatcher();if(!r)throw new i(`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(){let e=this.vfs.listMounts();return this.includeMounts?e:e.filter(e=>this.isAllowedStrict(e))}listMountPoints(){let e=this.vfs.listMountPoints();return this.includeMounts?e:e.filter(e=>this.isAllowed(e.path))}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 O(e,t){if(e instanceof i){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 i(e.code,r,t)}throw e}var he=[`ENOENT`,`EEXIST`,`ENOTDIR`,`EISDIR`,`ENOTEMPTY`,`EINVAL`,`EACCES`,`ELOOP`,`EBUSY`,`EFBIG`,`EBADF`,`ENOSYS`,`EOPNOTSUPP`,`EXDEV`,`EIO`];function k(e,t){if(e instanceof i)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 i(`EIO`,`internal overflow, not storage: ${n} — reload the session`,t)}let n=e?.code;if(typeof n==`string`){let r=n;if(he.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 i(r,n||r,t)}}let r=e instanceof Error?e.message:String(e);return r.includes(`ENOENT`)?new i(`ENOENT`,`no such file or directory`,t):r.includes(`EEXIST`)?new i(`EEXIST`,`file already exists`,t):r.includes(`ENOTDIR`)?new i(`ENOTDIR`,`not a directory`,t):r.includes(`EISDIR`)?new i(`EISDIR`,`is a directory`,t):r.includes(`ENOTEMPTY`)?new i(`ENOTEMPTY`,`directory not empty`,t):r.includes(`ELOOP`)?new i(`ELOOP`,`too many levels of symbolic links`,t):r.includes(`EOPNOTSUPP`)||r.includes(`ENOTSUP`)?new i(`EOPNOTSUPP`,`operation not supported`,t):r.includes(`EXDEV`)?new i(`EXDEV`,`cross-device link`,t):new i(`EINVAL`,r,t)}var ge=61440,_e=16384;function A(e){return e===void 0?`absent`:(e&ge)===_e?`directory`:`file`}function j(e,t){return t===`absent`?!1:e.kind===`missing`||e.kind!==t}function M(e){let t=e?.mode;return typeof t==`number`?t:void 0}function ve(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=A(M(r));o!==A(M(i))&&a.push({path:n,ownIsDirectory:o===`directory`})}return a}var N=512,P=class e{kind=`local`;listingStatsMatchStat=!0;source=void 0;profile=void 0;mountId;handle;dirCacheMax;dirCache=new Map;closed=!1;constructor(e,t){this.handle=e,this.mountId=t.mountId,this.dirCacheMax=t.dirCacheMax??N}static fromHandle(t,n){return new e(t,n)}getHandle(){return this.handle}assertOpen(e){if(this.closed)throw new i(`EBADF`,`mount closed`,e)}splitPath(e){return e.replace(/^\/+/,``).replace(/\/+$/,``).split(`/`).filter(e=>e.length>0)}cacheGet(e){let t=this.dirCache.get(e);if(t!==void 0)return this.dirCache.delete(e),this.dirCache.set(e,t),t}cacheSet(e,t){for(this.dirCache.has(e)&&this.dirCache.delete(e),this.dirCache.set(e,t);this.dirCache.size>this.dirCacheMax;){let e=this.dirCache.keys().next();if(e.done)break;this.dirCache.delete(e.value)}}invalidate(e){if(e===``){this.dirCache.clear();return}let t=`${e}/`;for(let n of[...this.dirCache.keys()])(n===e||n.startsWith(t))&&this.dirCache.delete(n)}getDirCacheSize(){return this.dirCache.size}async resolveDirFrom(e,t,n,r=!0){let i=this.handle,a=``,o=0;if(r)for(let t=e.length;t>0;t--){let n=e.slice(0,t).join(`/`),r=this.cacheGet(n);if(r){i=r,a=n,o=t;break}}let s=a;for(;o<e.length;o++){let r=e[o];try{i=await i.getDirectoryHandle(r,{create:n})}catch(r){if(n&&s!==``)return this.invalidate(s),this.resolveDirFrom(e,t,n,!1);throw this.toFsError(r,t)}a=a===``?r:`${a}/${r}`,this.cacheSet(a,i)}return i}async resolveDir(e,t=!1){return this.resolveDirFrom(this.splitPath(e),e,t)}async resolveParent(e,t){let n=this.splitPath(e);if(n.length===0)throw new i(`EISDIR`,`is a directory`,e);let r=n.pop();return{parent:await this.resolveDirFrom(n,e,t),name:r}}async resolveFile(e,t=!1){let{parent:n,name:r}=await this.resolveParent(e,t);try{return await n.getFileHandle(r,{create:t})}catch(t){throw this.toFsError(t,e)}}toFsError(e,t){if(e instanceof i)return e;if(e instanceof DOMException){if(e.name===`NotFoundError`)return new i(`ENOENT`,`no such file or directory`,t);if(e.name===`TypeMismatchError`)return new i(`ENOTDIR`,`not a directory`,t);if(e.name===`NotAllowedError`)return new i(`EACCES`,`permission denied`,t);if(e.name===`InvalidModificationError`)return new i(`ENOTEMPTY`,`directory not empty`,t)}if(e instanceof Error){if(e.name===`NotFound`||e.name===`NotFoundError`)return new i(`ENOENT`,`no such file or directory`,t);if(e.name===`TypeMismatch`||e.name===`TypeMismatchError`)return new i(`ENOTDIR`,`not a directory`,t);if(e.name===`InvalidModification`||e.name===`InvalidModificationError`)return new i(`ENOTEMPTY`,`directory not empty`,t)}return new i(`EINVAL`,e instanceof Error?e.message:String(e),t)}async readDir(e,t){this.assertOpen(e);let n=await this.resolveDir(e),r=[];for await(let[e,i]of n){if(i.kind!==`file`){r.push({name:e,kind:`directory`});continue}if(!t?.includeStats){r.push({name:e,kind:`file`});continue}let n=await i.getFile();r.push({name:e,kind:`file`,size:n.size,lastModified:n.lastModified})}return r}async readFile(e){this.assertOpen(e);let t=await(await this.resolveFile(e)).getFile();return new Uint8Array(await t.arrayBuffer())}async getNativeFile(e){this.assertOpen(e);try{return await(await this.resolveFile(e)).getFile()}catch{return null}}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){this.assertOpen(e);let t=this.splitPath(e);if(t.length===0)return{kind:`directory`,size:0,mtime:0};let n=t.pop(),r=await this.resolveDirFrom(t,e,!1);try{let e=await(await r.getFileHandle(n)).getFile();return{kind:`file`,size:e.size,mtime:e.lastModified}}catch(t){let n=this.toFsError(t,e);if(n.code!==`ENOENT`&&n.code!==`ENOTDIR`)throw n}try{let e=await r.getDirectoryHandle(n);this.cacheSet(t.length===0?n:`${t.join(`/`)}/${n}`,e)}catch(t){throw this.toFsError(t,e)}return{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 i(`EINVAL`,`cannot remove mount root`,e);let r=n.pop(),a=await this.resolveDirFrom(n,e,!1);try{await a.removeEntry(r,{recursive:t?.recursive??!1})}catch(t){throw this.toFsError(t,e)}this.invalidate(n.length===0?r:`${n.join(`/`)}/${r}`)}async refresh(){return this.assertOpen(`/`),this.dirCache.clear(),{added:[],removed:[],changed:[],unchanged:0,errors:[]}}describe(){return{displayName:this.handle.name}}async close(){this.closed=!0,this.dirCache.clear()}};async function F(e,t){let n=t.split(`/`).filter(Boolean),r=n.pop();if(r===void 0)return null;try{let t=e;for(let e of n)t=await t.getDirectoryHandle(e);return await(await t.getFileHandle(r)).getFile()}catch{return null}}function I(e,t){return e===t||e.startsWith(t===`/`?`/`:`${t}/`)}var ye=`/.metadata.json`,L=`.metadata.consistent.json`,R=`/${L}`;function z(e){return e.entries&&(delete e.entries[ye],delete e.entries[R]),e}function be(e,t,n){let r=t.entries??{},i={...e.entries??{}};`/`in r&&(i[`/`]=r[`/`]);for(let e of n.paths)e in r?i[e]=r[e]:delete i[e];for(let e of n.prefixes){for(let t of Object.keys(i))I(t,e)&&delete i[t];for(let t of Object.keys(r))I(t,e)&&(i[t]=r[t])}let{entries:a,...o}=t;return z({...o,entries:i})}var B=1;async function xe(e,t,n){let r=Math.max(1,Math.trunc(e)||1),i=Array(t.length),a=0,o=async()=>{for(;a<t.length;){let e=a;if(a+=1,e>=t.length)return;i[e]=await n(t[e],e)}},s=[],c=Math.min(r,t.length);for(let e=0;e<c;e+=1)s.push(o());return await Promise.all(s),i}async function V(e){let t=e;if(typeof t.createSyncAccessHandle==`function`)try{let e=await t.createSyncAccessHandle();try{return e.getSize()}finally{try{await e.close()}catch{}}}catch{}return(await e.getFile()).size}async function H(e){let t;for(let n=0;n<3;n+=1)try{return await(await e.getFile()).text()}catch(e){if(e?.name!==`NotReadableError`)throw e;t=e}throw t}function Se(e){if(!e||typeof e!=`object`)return!1;let t=e.entries;return!!t&&typeof t==`object`}async function Ce(e){try{let t=await H(await e.getFileHandle(`.metadata.json`)),n=JSON.parse(t);return Se(n)?{text:t,doc:n}:null}catch{return null}}async function we(e,t){let n=await(await e.getFileHandle(`.metadata.json`,{create:!0})).createWritable();await n.write(t),await n.close()}async function U(e){let t=await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(e)),n=new Uint8Array(t),r=``;for(let e of n)r+=e.toString(16).padStart(2,`0`);return r}async function W(e,t){try{let n=await e.getFileHandle(L),r=JSON.parse(await H(n));if(!r||typeof r!=`object`)return!1;let i=r;return i.v!==B||typeof i.hash!=`string`?!1:i.hash===await U(t)}catch{return!1}}async function Te(e,t){let n={v:B,hash:await U(t)},r=await(await e.getFileHandle(L,{create:!0})).createWritable();await r.write(JSON.stringify(n)),await r.close()}async function Ee(e){try{await e.removeEntry(L)}catch(e){if(e?.name===`NotFoundError`)return;throw e}}async function De(e,t,n){let r=e,i=``,a=0;for(let e=n.length;e>0;--e){let o=n.slice(0,e).join(`/`),s=t.get(o);if(s){r=s,i=o,a=e;break}}for(let e=a;e<n.length;e+=1){let a=n[e];try{r=await r.getDirectoryHandle(a)}catch{return null}i=i?`${i}/${a}`:a,t.set(i,r)}return r}async function Oe(e,t,n,r,i,a){let o=async()=>{try{let n=await e.getDirectoryHandle(t);return i.set(a?`${a}/${t}`:t,n),{kind:`directory`}}catch{return null}},s=async()=>{try{let n=await e.getFileHandle(t);return r?{kind:`file`,size:await V(n)}:{kind:`file`,size:0}}catch{return null}};return n===`directory`?await o()??await s()??{kind:`missing`}:await s()??await o()??{kind:`missing`}}function G(e,t){let n=t?.includeSize!==!1,r=new Map;return async(t,i)=>{let a=t.split(`/`).filter(Boolean),o=await De(e,r,a.slice(0,-1));if(!o)return{kind:`missing`};let s=a[a.length-1];if(s===void 0)return{kind:`directory`};let c=a.slice(0,-1).join(`/`);return Oe(o,s,i,n,r,c)}}async function ke(e){let t=new Map;for await(let[n,r]of e.entries())t.set(n,r);return t}function Ae(e){return e.kind===`directory`?`directory`:e.kind===`file`?`file`:`other`}function je(e){if(typeof e.entries!=`function`)return G(e);let t=new Map,n=(e,n)=>{let r=t.get(n);if(r)return r;let i=ke(e).catch(e=>{throw t.delete(n),e});return t.set(n,i),i};return async t=>{let r=t.split(`/`).filter(Boolean),i=e,a=``;for(let e=0;e<r.length;e+=1){let t=r[e],o=(await n(i,a)).get(t);if(!o)return{kind:`missing`};let s=Ae(o);if(e!==r.length-1){if(s!==`directory`)return{kind:`missing`};i=o,a=`${a}/${t}`;continue}return s===`directory`?{kind:`directory`}:s===`file`?{kind:`file`,size:await V(o)}:{kind:`missing`}}return{kind:`directory`}}}var Me=61440,K=16384,q=32768,Ne=40960;async function Pe(e,t,n,r=16){let i=J(),a=e.entries??{},o=[];for(let[e,t]of Object.entries(a)){let r=Fe(e,t,a,i);r?o.push(r):n?.()}return Ie(o,await xe(r,o,async e=>{n?.();let r=e.fmt===K?`directory`:`file`;return t(e.path,r)}),a,i),Le(a,i),i}function J(){return{kindFixed:[],sizesFixed:0,dropped:0,selfEntryDropped:!1,inosReassigned:0,nlinksFixed:0,changed:!1}}function Fe(e,t,n,r){if(e===`/`||typeof t!=`object`||!t)return null;if(e===`/.metadata.json`||e===R)return delete n[e],e===`/.metadata.json`&&(r.selfEntryDropped=!0),r.changed=!0,null;let i=t,a=(i.mode??0)&Me;return a===Ne?(Y(i,r),null):{path:e,entry:i,fmt:a}}function Ie(e,t,n,r){for(let i=0;i<e.length;i+=1){let a=e[i],o=t[i];if(o.kind===`missing`){delete n[a.path],r.dropped+=1,r.changed=!0;continue}Y(a.entry,r),Re(a.path,a.entry,a.fmt,o,r)}}function Le(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 Y(e,t){e.nlink||(e.nlink=1,t.nlinksFixed+=1,t.changed=!0)}function Re(e,t,n,r,i){if(n===q&&r.kind===`directory`){t.mode=((t.mode??0)&511||493)|K,i.kindFixed.push(`${e} file→dir`),i.changed=!0;return}if(n===K&&r.kind===`file`){t.mode=((t.mode??0)&511||420)|q,t.size=r.size,i.kindFixed.push(`${e} dir→file`),i.changed=!0;return}n===q&&r.kind===`file`&&typeof t.size==`number`&&t.size!==r.size&&(t.size=r.size,i.sizesFixed+=1,i.changed=!0)}async function ze(e,t,n){try{return await e()}catch(r){let i=null;try{i=await t()}catch{}if(!i?.changed)throw r;return n(i),await e()}}async function Be(e,t){let n=await Ce(e);if(!n)return null;if(await W(e,n.text))return J();let r=await Pe(n.doc,je(e),t),i=r.changed?JSON.stringify(n.doc):n.text;r.changed&&await we(e,i);try{await Te(e,i)}catch{}return r}function X(e,t,n=0){if(!(!Number.isSafeInteger(t)||(t??0)<=0||!Number.isSafeInteger(n)||n<0))return JSON.stringify([e,n,t])}async function Ve(e,t,n,r){try{return await e.lstat(t)}catch(e){let t=k(e,r);if(t.code===`ENOENT`&&n)return null;throw t}}async function He(e,t,n){let r;try{r=await e.readlink(t)}catch(e){throw k(e,n)}return r.startsWith(`/`)?s(r):s(l(a(t).dir,r))}async function Ue(e,t,n,r,a,o){let s=t===`/`?`/${n}`:`${t}/${n}`;for(;;){let t=await Ve(e,s,r,a);if(t===null||!t.isSymbolicLink())return{resolved:s,hops:o};if(++o>10)throw new i(`ELOOP`,`too many symbolic links encountered`,a);s=await He(e,s,a)}}async function Z(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 Ue(e,a,i[t],t===i.length-1,r,o);a=n.resolved,o=n.hops}return a}async function We(e,t,n){return t(n)?n:Z(e,t,n)}function Q(){try{if(typeof globalThis.navigator?.storage?.getDirectory==`function`)return`opfs`}catch{}return`memory`}function Ge(e,t){let n=e.kind===`directory`?`directory`:`file`;return t?{name:e.name,type:n,...e.size===void 0?{}:{size:e.size},...e.lastModified===void 0?{}:{mtime:e.lastModified},...e.ctime===void 0?{}:{ctime:e.ctime},...e.ino===void 0?{}:{ino:e.ino},...e.identity===void 0?{}:{identity:e.identity},...e.dev===void 0?{}:{dev:e.dev},...e.uid===void 0?{}:{uid:e.uid},...e.gid===void 0?{}:{gid:e.gid},...e.mode===void 0?{}:{mode:e.mode}}:{name:e.name,type:n}}function Ke(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 x;static writeChains=new Map;onRepairProgress;constructor(t,n,r,i,a,o){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,o):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 opfsInitChains=new Map;static async initOpfsBackend(t,n,r,i){let a=(e.opfsInitChains.get(t.dbName)??Promise.resolve()).catch(()=>{}).then(()=>e.resolveOpfsBackend(t,n,r,i));e.opfsInitChains.set(t.dbName,a);try{await a}finally{e.opfsInitChains.get(t.dbName)===a&&e.opfsInitChains.delete(t.dbName)}}static async resolveOpfsBackend(n,r,a,o){let s=e.opfsBackends.get(n.dbName);if(s&&a)throw new i(`EBUSY`,`Cannot wipe an OPFS backend with live holders`,n.dbName);if(s&&o!==void 0&&s.asyncCache!==o)throw new i(`EBUSY`,`OPFS async cache setting conflicts with the live backend`,n.dbName);let c=r??await e.acquireOpfsHandle(n.dbName,a);await n.withWriteLock(()=>e.seedOpfsMetadataSidecarIfMissing(c));let l=await t(()=>import(`./dist-HBVgABmW.js`),__vite__mapDeps([0,1,2]));await e.ensureRootMount(l);let u=`/__opfs__/${n.dbName}`,d=e.opfsBackends.get(n.dbName);if(!d){let{resolveOpfsMount:r}=await t(async()=>{let{resolveOpfsMount:e}=await import(`./opfs-mount-DF1_TQm7.js`);return{resolveOpfsMount:e}},__vite__mapDeps([3,0,1,2])),i=await r({handle:c,dbName:n.dbName,asyncCache:o,onRepairProgress:n.onRepairProgress,withWriteLock:e=>n.withWriteLock(e)});try{l.mount(u,i)}catch{}d={backendFs:i,refs:0,asyncCache:o!==!1,sidecarDirty:{paths:new Set,prefixes:new Set}},e.opfsBackends.set(n.dbName,d)}d.refs+=1,n.opfsBackendFs=d.backendFs.index?d.backendFs:null,n.opfsHandle=c,n.mountRoot=u,n.rawLfs=l.promises,n.rawLfsSync=l}static async initMemoryBackend(n,r,i){let a=await t(()=>import(`./dist-HBVgABmW.js`),__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)),appendFile:async(t,r)=>{this._readyResolved||await this._ready,await n().appendFile(e(t),r)},chmod:async(t,r)=>{this._readyResolved||await this._ready,await n().chmod(e(t),r)},utimes:async(t,r,i)=>{this._readyResolved||await this._ready,await n().utimes(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(t){let n=`.metadata.json`;try{let r=await t.getFileHandle(n);if(e.isUsableMetadataDocument(await e.readSidecarText(r)))return;console.warn(`[virtual-fs] metadata sidecar is unparseable (torn write?); reseeding an empty index`)}catch(e){if(e?.name!==`NotFoundError`)throw e}let r=await(await t.getFileHandle(n,{create:!0})).createWritable(),i=JSON.stringify({version:1,maxSize:4294967295,entries:{}});await r.write(i),await r.close()}static async readSidecarText(e){let t;for(let n=0;n<3;n++)try{return await(await e.getFile()).text()}catch(e){if(e?.name!==`NotReadableError`)throw e;t=e}throw t}static isUsableMetadataDocument(e){let t;try{t=JSON.parse(e)}catch{return!1}if(!t||typeof t!=`object`)return!1;let n=t.entries;return!!n&&typeof n==`object`}static async acquireOpfsHandle(e,t){let n=navigator.storage;if(!n?.getDirectory)throw new i(`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,t?.opfsAsyncCache);try{await a._ready}catch(e){throw a.mountSyncChannel?.close(),e}return r&&await p().catch(()=>{}),a}async flush(){await this.writeOpfsMetadataSidecar()}async writeOpfsMetadataSidecar(){this.backend===`opfs`&&await this.withWriteLock(()=>this.writeOpfsMetadataSidecarUnlocked())}async writeOpfsMetadataSidecarUnlocked(){if(this.backend!==`opfs`)return;let 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=be(e,r,i))}let o=JSON.stringify(z(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=ve(e,t,n.paths,n.prefixes);if(i.length===0)return;let a=G(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}async forgetSidecarConsistency(){await this.dropSidecarConsistency()}sidecarConsistencyDrop=null;dropSidecarConsistency(){if(this.backend!==`opfs`||!this.opfsHandle)return Promise.resolve();if(!this.sidecarConsistencyDrop){let e=this.opfsHandle;this.sidecarConsistencyDrop=Ee(e).catch(e=>{throw this.sidecarConsistencyDrop=null,e})}return this.sidecarConsistencyDrop}invalidatePaths(e){if(this.backend!==`opfs`||!this.opfsBackendFs)return;e.length>0&&this.dropSidecarConsistency().catch(()=>void 0);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 G(n)(i),o=A(t.index.get(i)?.mode),c=t._handles?.get(i),l=c?.kind===`directory`?`directory`:c?.kind===`file`?`file`:`absent`,u=j(a,o),d=j(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}localIdentity(e){return X(`zenfs:${this.backend}:${this.dbName}`,e)}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 i(`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-HBVgABmW.js`),__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(a===`symlink`?{name:i,type:a}:{name:i,type:a,size:t.size,mtime:t.mtimeMs,ctime:t.ctimeMs,...t.ino===void 0?{}:{ino:t.ino,identity:this.localIdentity(t.ino),dev:t.dev},...t.uid===void 0?{}:{uid:t.uid},...t.gid===void 0?{}:{gid:t.gid},mode:t.mode})}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,identity:this.localIdentity(e.ino),dev:e.dev,mode:e.mode}}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,identity:this.localIdentity(e.ino),dev:e.dev,mode:e.mode};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,identity:this.localIdentity(e.ino),dev:e.dev,mode:e.mode}}return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,ino:e.ino,identity:this.localIdentity(e.ino),dev:e.dev,mode:e.mode}}catch{return null}}async mount(e,t,n){let r=s(e);if(this.mountPoints.has(r))throw new i(`EEXIST`,`mount point is already mounted`,r);try{if((await this.lstat(r)).type!==`directory`)throw new i(`ENOTDIR`,`mount point must be a directory`,r);if((await this.readDir(r)).length>0)throw new i(`ENOTEMPTY`,`mount point must be empty to avoid shadowing existing files`,r)}catch(e){if(!(e instanceof i)||e.code!==`ENOENT`)throw e}let{dir:o}=a(r);o!==`/`&&await this.mkdir(o,{recursive:!0}),await this.dropSidecarConsistency();try{await this.lfs.mkdir(r)}catch{}if(this.mountPoints.set(r,t),t.kind===`local`){let e=n?.limits??b(n?.env??{});this.mountIndex.registerMount(r,t.getHandle(),e)}let c=Ke(t,r);try{this.mountSyncChannel?.postMessage({type:`mount`,path:r,descriptor:c})}catch{}if(this.watcher?.notify([{type:`modify`,path:r,entryType:`directory`}]),t.kind!==`hostfs`)try{let e={targetPath:r,descriptor:c,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 P.fromHandle(t,{mountId:e.mountId})}case`hostfs`:{let{HostFsMountBackend:r}=await t(async()=>{let{HostFsMountBackend:e}=await import(`./backend-hostfs-DVOOQmWO.js`);return{HostFsMountBackend:e}},__vite__mapDeps([4,5,6,7,8]));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-BsWbgqHU.js`);return{S3MountBackend:e,RemoteMountCache:t,makeSignedFetchS3:n}},__vite__mapDeps([9,10,11,12,7,13,1,8])),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-BsWbgqHU.js`);return{DaMountBackend:e,RemoteMountCache:t,makeSignedFetchDa:n}},__vite__mapDeps([9,10,11,12,7,13,1,8])),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-BsWbgqHU.js`);return{AemMountBackend:e,RemoteMountCache:t,makeSignedFetchDa:n}},__vite__mapDeps([9,10,11,12,7,13,1,8])),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}getMountBackend(e){let t=s(e);return this.mountPoints.get(t)??null}async mountInternal(e,t){let n=s(e);if(this.mountPoints.has(n))throw new i(`EEXIST`,`mount point is already mounted`,n);let{dir:r}=a(n);r!==`/`&&await this.mkdir(r,{recursive:!0}),await this.dropSidecarConsistency();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 i(`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 i(`ENOENT`,`not a mount point`,n);let a=await r.refresh(t);return r.kind===`local`&&await this.mountIndex.refreshMount(n,b(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=s(e),r=this.findMount(n);if(r){if(r.relParts.length===0)throw new i(`EISDIR`,`is a directory`,n);let e=r.relParts.join(`/`);try{let n=await r.backend.readFile(e);return(t?.encoding??`utf-8`)===`utf-8`?new TextDecoder(`utf-8`).decode(n):n}catch(e){O(e,n)}}let a=await this.resolveSymlinks(n);try{return(t?.encoding??`utf-8`)===`utf-8`?await this.lfs.readFile(a,{encoding:`utf8`}):await this.lfs.readFile(a)}catch(e){throw k(e,n)}}async readFileRange(e,t,n){let r=s(e);if(!Number.isInteger(t)||!Number.isInteger(n)||t<0||n<t)throw new i(`EINVAL`,`invalid byte range ${t}-${n}`,r);if(t===n)return new Uint8Array;let a=this.findMount(r),o=a?.backend.readFileRange;if(a&&o){if(a.relParts.length===0)throw new i(`EISDIR`,`is a directory`,r);try{return await o.call(a.backend,a.relParts.join(`/`),t,n)}catch(e){O(e,r)}}let c=await this.sliceNativeFile(r,t,n);if(c)return c;let l=await this.readFile(r,{encoding:`binary`});return new Uint8Array(l.subarray(t,Math.min(n,l.byteLength)))}async sliceNativeFile(e,t,n){try{let r=await this.getNativeFile(e);if(!r)return null;let i=r.slice(t,Math.min(n,r.size));return new Uint8Array(await i.arrayBuffer())}catch{return null}}async getNativeFile(e){let t=s(e),n=this.findMount(t);if(n){let e=n.backend.getNativeFile;if(!e||n.relParts.length===0)return null;try{return await e.call(n.backend,n.relParts.join(`/`))}catch{return null}}let r=this.opfsHandle;if(!r)return null;try{return await F(r,await this.resolveSymlinks(t))}catch{return null}}async writeFile(e,t,n){return this.withKindMismatchRetry(e,()=>this.writeFileInner(e,t,n))}async writeFileInner(e,t,n){let r=s(e),o=this.findMount(r);if(o){if(o.relParts.length===0)throw new i(`EISDIR`,`is a directory`,r);let e=o.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 o.backend.writeFile(e,a)}catch(e){O(e,r)}this.watcher?.notify([{type:n?`modify`:`create`,path:r,entryType:`file`}]),this.mountIndex.notifyWrite(r);return}let c;try{c=await this.resolveSymlinks(r)}catch{c=r}let l=!1;try{await this.lfs.stat(c),l=!0}catch{}let{dir:u}=a(c);await this.withWriteLock(async()=>{await this.dropSidecarConsistency(),this.markSidecarDirty(c),u!==`/`&&await this.mkdirRecursiveUnlocked(u);let e=typeof t==`string`?new TextEncoder().encode(t).byteLength:(t instanceof Uint8Array,t.byteLength);try{await this.lfs.writeFile(c,t)}catch(e){if(u!==`/`&&e instanceof Error&&e.message.includes(`ENOENT`)){await this.mkdirRecursiveUnlocked(u);try{await this.lfs.writeFile(c,t)}catch(e){throw k(e,r)}}else throw k(e,r)}try{await this.lfs.truncate?.(c,e)}catch(e){throw k(e,r)}}),this.watcher?.notify([{type:l?`modify`:`create`,path:c,entryType:`file`}])}async appendFile(e,t){let n=s(e);await this.withKindMismatchRetry(n,()=>this.withWriteLock(async()=>{if(this.findMount(n)){await this.appendMounted(n,t);return}await this.dropSidecarConsistency();let e=n,r=!1;try{if(e=await this.resolveSymlinks(n),(await this.lfs.stat(e)).isDirectory())throw new i(`EISDIR`,`is a directory`,n);r=!0}catch(e){let t=k(e,n);if(t.code!==`ENOENT`)throw t}this.markSidecarDirty(e);let{dir:o}=a(e);await this.mkdirRecursiveUnlocked(o);try{await this.lfs.appendFile(e,t)}catch(e){throw k(e,n)}this.watcher?.notify([{type:r?`modify`:`create`,path:e,entryType:`file`}])}))}async appendMounted(e,t){let n=new Uint8Array;try{let t=await this.readFileInner(e,{encoding:`binary`});n=typeof t==`string`?new TextEncoder().encode(t):new Uint8Array(t)}catch(t){let n=k(t,e);if(n.code!==`ENOENT`)throw n}let r=typeof t==`string`?new TextEncoder().encode(t):t,i=new Uint8Array(n.length+r.length);i.set(n),i.set(r,n.length),await this.writeFileInner(e,i)}async chmod(e,t){if(!Number.isInteger(t)||t<0||t>4095)throw new i(`EINVAL`,`invalid file mode`,s(e));await this.changeMetadata(e,e=>this.lfs.chmod(e,t))}async utimes(e,t,n){if(!Number.isFinite(t.getTime())||!Number.isFinite(n.getTime()))throw new i(`EINVAL`,`invalid file time`,s(e));await this.changeMetadata(e,e=>this.lfs.utimes(e,t,n))}async changeMetadata(e,t){let n=s(e);if(this.findMount(n))throw await this.stat(n),new i(`ENOSYS`,`metadata changes are not supported by this mount`,n);await this.withKindMismatchRetry(n,()=>this.withWriteLock(async()=>{await this.dropSidecarConsistency();let e=await this.resolveSymlinks(n);try{let n=await this.lfs.stat(e);this.markSidecarDirty(e),await t(e),await this.writeOpfsMetadataSidecarUnlocked(),this.watcher?.notify([{type:`modify`,path:e,entryType:n.isDirectory()?`directory`:`file`}])}catch(e){throw k(e,n)}}))}async readDir(e,t){let n=s(e),r=this.findMount(n);return r?this.readDirMounted(n,r,t):this.readDirLocal(n)}async readDirMounted(e,t,n){let r=n?.includeStats===!0?void 0:this.mountIndex.getDirectoryEntries(t.path,e);if(r!==void 0){let t=new Map;for(let e of r)t.set(e.name,{name:e.name,type:e.type});return this.addNestedMountEntries(t,e),[...t.values()]}let i=t.relParts.join(`/`)||`/`,a;try{a=await t.backend.readDir(i,n)}catch(t){O(t,e)}let o=new Map,s=t.backend.listingStatsMatchStat===!0;for(let e of a)o.set(e.name,Ge(e,s));return this.addNestedMountEntries(o,e),[...o.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 k(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`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,...e.ino===void 0?{}:{ino:e.ino,identity:this.localIdentity(e.ino),dev:e.dev},...e.uid===void 0?{}:{uid:e.uid},...e.gid===void 0?{}:{gid:e.gid},mode:e.mode}}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 k(e,r);try{let e=await this.lfs.lstat(r);if(!e.isDirectory()&&!e.isSymbolicLink())throw new i(`ENOTDIR`,`not a directory`,r)}catch(e){if(e instanceof i&&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){O(e,n)}t||this.watcher?.notify([{type:`create`,path:n,entryType:`directory`}]);return}if(t?.recursive){let e=await this.withWriteLock(async()=>(await this.dropSidecarConsistency(),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()=>{await this.dropSidecarConsistency(),this.markSidecarDirty(n);try{await this.lfs.mkdir(n)}catch(e){throw k(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 i(`EINVAL`,`cannot remove a mount point — use unmount`,n);let e;try{e=(await this.stat(n)).type}catch{}let a=r.relParts.join(`/`);try{await r.backend.remove(a,{recursive:t?.recursive})}catch(e){O(e,n)}this.watcher?.notify([{type:`delete`,path:n,entryType:e}]),this.mountIndex.notifyDelete(n);return}try{let e=await this.lfs.lstat(n);await this.withWriteLock(async()=>{await this.dropSidecarConsistency(),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 k(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.ctime??t.mtime,...t.ino===void 0?{}:{ino:t.ino},...t.identity===void 0?{}:{identity:t.identity},...t.dev===void 0?{}:{dev:t.dev},...t.uid===void 0?{}:{uid:t.uid},...t.gid===void 0?{}:{gid:t.gid},...t.mode===void 0?{}:{mode:t.mode}}}catch(e){O(e,t)}}let r=await this.resolveSymlinks(t);try{let e=await this.lfs.stat(r);return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,ino:e.ino,dev:e.dev,identity:this.localIdentity(e.ino),uid:e.uid,gid:e.gid,mode:e.mode}}catch(e){throw k(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);if(n===r)return;let i;try{i=await this.lstat(n)}catch{}let a=i?.type,o=this.findMount(n);if(o?.backend.rename){let e=this.findMount(r);if(e&&e.backend===o.backend){let t=!1;try{t=(await o.backend.rename(o.relParts.join(`/`),e.relParts.join(`/`)))?.noop===!0}catch(e){O(e,n)}t||(this.watcher?.notify([{type:`delete`,path:n,entryType:a},{type:`create`,path:r,entryType:a}]),this.mountIndex.notifyRename(n,r));return}}if(i)try{let e=await this.lstat(r);if(f(i,e))return}catch{}try{await this.withWriteLock(async()=>{await this.dropSidecarConsistency(),this.markSidecarDirty(n,`prefix`),this.markSidecarDirty(r,`prefix`),await this.lfs.rename(n,r),await this.writeOpfsMetadataSidecarUnlocked()})}catch(e){throw k(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*u({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){let n=await this.stat(e);if(n.type===`directory`)throw new i(`EISDIR`,`is a directory`,e);try{let e=await this.stat(t);if(f(n,e))return}catch{}let r=await this.readFile(e,{encoding:`binary`});await this.writeFile(t,r)}dirname(e){return a(s(e)).dir}basename(e){return a(s(e)).base}resolveSymlinkTargetPath(e,t){return e.startsWith(`/`)?s(e):s(l(a(t).dir,e))}assertSymlinkCreateAllowed(e,t){if(this.findMount(t))throw new i(`EINVAL`,`symlinks not supported on mounted filesystems`,t);let n=this.resolveSymlinkTargetPath(e,t);if(this.findMount(n))throw new i(`EXDEV`,`cannot create a symlink across a mount boundary to '${n}'`,t)}async symlink(e,t){let n=s(t);this.assertSymlinkCreateAllowed(e,n);let{dir:r}=a(n);await this.withWriteLock(async()=>{await this.dropSidecarConsistency(),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 k(e,n)}}else throw k(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 k(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,dev:e.dev,identity:this.localIdentity(e.ino),uid:e.uid,gid:e.gid,mode:e.mode}}return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,ino:e.ino,dev:e.dev,identity:this.localIdentity(e.ino),uid:e.uid,gid:e.gid,mode:e.mode}}catch(e){throw k(e,t)}}async realpath(e){return Z(this.lfs,e=>this.findMount(e)!==null,e)}resolveSymlinks(e){return We(this.lfs,e=>this.findMount(e)!==null,e)}},qe=e({FsError:()=>i,FsWatcher:()=>h,MountIndex:()=>x,RestrictedFS:()=>D,VirtualFS:()=>$,joinPath:()=>l,normalizePath:()=>s,pathSegments:()=>o,resolveVfsBackendFromEnv:()=>Q,sameFileIdentity:()=>f,splitPath:()=>a,statsFromDirEntry:()=>r});export{i as FsError,h as FsWatcher,x as MountIndex,D as RestrictedFS,$ as VirtualFS,P as a,ze as i,l as joinPath,X as n,s as normalizePath,o as pathSegments,Be as r,Q as resolveVfsBackendFromEnv,f as sameFileIdentity,a as splitPath,r as statsFromDirEntry,qe as t};
@@ -1,4 +0,0 @@
1
- import{t as e}from"./types-D8gIX-W-.js";import"./fs-D5UZBrBX.js";import{n as t,t as n}from"./browser-DuyhpHbR.js";import{A as r,D as i,E as a,M as o,O as s,T as c,j as l,k as u,w as d}from"./shared-2XhBobrM.js";function f(e,...t){return`/${[e,...t].join(`/`).split(`/`).filter(e=>e.length>0).join(`/`)}`}function p(e){let t=JSON.stringify(e);return[`// ${s}`,`const { start } = require('sliccy:exec');`,`const __bin = ${t};`,`const __argv = ['ipx', '--global', __bin, ...process.argv.slice(2)];`,`const __stdin = typeof stdin !== 'undefined' ? stdin : undefined;`,`const __h = start(__argv, __stdin !== undefined ? { stdin: __stdin } : undefined);`,`__h.stdin.end();`,`const __r = await __h.done;`,`if (__r.stdout) process.stdout.write(__r.stdout);`,`if (__r.stderr) process.stderr.write(__r.stderr);`,`process.exit(__r.exitCode);`,``].join(`
2
- `)}var m=class extends Error{binName;path;constructor(e,t){super(`ipk: refusing to overwrite user script at ${t} (bin '${e}')`),this.binName=e,this.path=t,this.name=`GlobalBinCollisionError`}};async function h(e,t){if(t.size!==0){await e.exists(`/shared/bin`)||await e.mkdir(u,{recursive:!0});for(let n of t){if(!n||n.includes(`/`))continue;let t=f(u,`${n}.jsh`);if(await e.exists(t)&&!await g(e,t))throw new m(n,t)}}}async function g(e,t){try{let n=await e.readFile(t);return(typeof n==`string`?n:new TextDecoder().decode(n)).includes(s)}catch{return!1}}async function _(e,t){if(!await e.exists(`/shared/bin`)){if(t.size===0)return;await e.mkdir(u,{recursive:!0})}let n=[];try{n=await e.readDir(u)}catch{n=[]}for(let r of n){if(r.type!==`file`||!r.name.endsWith(`.jsh`))continue;let n=r.name.slice(0,-4);if(t.has(n))continue;let i=f(u,r.name);await g(e,i)&&await e.rm(i)}for(let n of t){if(!n||n.includes(`/`))continue;let t=f(u,`${n}.jsh`);if(await e.exists(t)&&!await g(e,t))throw new m(n,t);await e.writeFile(t,p(n))}}const v={0:`file`,1:`hardLink`,2:`symbolicLink`,3:`characterDevice`,4:`blockDevice`,5:`directory`,6:`fifo`,7:`contiguousFile`,g:`globalExtendedHeader`,x:`extendedHeader`,D:`gnuDirectory`,I:`gnuInodeMetadata`,K:`gnuLongLinkName`,L:`gnuLongFileName`,N:`gnuOldLongFileName`,M:`gnuMultiVolume`,S:`gnuSparseFile`,E:`gnuExtendedSparse`,A:`solarisAcl`,V:`solarisVolumeLabel`,X:`solarisOldExtendedHeader`};function y(e,t){let n=e.buffer||e,r=[],i=0,a,o;for(;i<n.byteLength-512;){let e=x(n,i,100);if(e.length===0)break;if(a){let t=a.path||a.linkpath;t&&(e=t)}let s=x(n,i+100,8).trim(),c=Number.parseInt(x(n,i+108,8)),l=Number.parseInt(x(n,i+116,8)),u=ee(n,i+124,12),d=512+512*Math.trunc(u/512)+(u%512?512:0),f=ee(n,i+136,12),p=x(n,i+156,1)||`0`,m=v[p]||p;switch(m){case`extendedHeader`:case`globalExtendedHeader`:{let e=te(new Uint8Array(n,i+512,u));m===`extendedHeader`?a=e:(a=void 0,o={...o,...e}),i+=d;continue}case`gnuLongFileName`:case`gnuOldLongFileName`:case`gnuLongLinkName`:a={path:x(n,i+512,u)},i+=d;continue}let h=x(n,i+265,32),g=x(n,i+297,32);e=b(e);let _={name:e,type:m,size:u,attrs:{...o,...a,mode:s,uid:c,gid:l,mtime:f,user:h,group:g}};if(a=void 0,t?.filter&&!t.filter(_)){i+=d;continue}if(t?.metaOnly){r.push(_),i+=d;continue}let y=u===0?void 0:new Uint8Array(n,i+512,u);r.push({..._,data:y,get text(){return new TextDecoder().decode(this.data)}}),i+=d}return r}function b(e){let t=e.replace(/\\/g,`/`);t=t.replace(/^[a-zA-Z]:\//,``),t=t.replace(/^\/+/,``);let n=t.startsWith(`./`),r=t.split(`/`),i=[];for(let e of r)e===`..`?i.pop():e!==`.`&&e!==``&&i.push(e);let a=i.join(`/`);return n&&!a.startsWith(`./`)&&(a=`./`+a),e.endsWith(`/`)&&!a.endsWith(`/`)&&(a+=`/`),a}function x(e,t,n){let r=new Uint8Array(e,t,n),i=r.indexOf(0);return new TextDecoder().decode(i===-1?r:r.slice(0,i))}function ee(e,t,n){let r=new Uint8Array(e,t,n),i=``;for(let e=0;e<n;e++)i+=String.fromCodePoint(r[e]);return Number.parseInt(i,8)}function te(e){let t=new TextDecoder().decode(e),n={};for(let e of t.split(`
3
- `)){let t=e.split(` `)[1]?.split(`=`);t&&(n[t[0]]=t[1])}return n}function ne(e,t={}){let n=e.map(e=>{let t=re(e.data);return{...e,data:t,size:t?.length||0}}),r=0;for(let t=0;t<e.length;t++){let e=n[t].data?.length??0;r+=512+512*Math.trunc(e/512),e%512&&(r+=512)}let i=10240*Math.trunc(r/10240);r%10240&&(i+=10240);let a=new ArrayBuffer(i),o=0;for(let e of n){let n=!e.data;S(a,e.name,o,100),S(a,C(e.attrs?.mode??t.attrs?.mode??(n?`775`:`664`),7),o+100,8),S(a,C((e.attrs?.uid??t.attrs?.uid??1e3).toString(8),7),o+108,8),S(a,C((e.attrs?.gid??t.attrs?.gid??1e3).toString(8),7),o+116,8),S(a,C(e.size.toString(8),11),o+124,12);let r=e.attrs?.mtime??t.attrs?.mtime??Date.now();S(a,C(Math.trunc(r/1e3).toString(8),11),o+136,12),S(a,n?`5`:`0`,o+156,1),S(a,`ustar`,o+257,6),S(a,`00`,o+263,2),S(a,e.attrs?.user??t.attrs?.user??``,o+265,32),S(a,e.attrs?.group??t.attrs?.group??``,o+297,32),S(a,` `,o+148,8);let i=new Uint8Array(a,o,512),s=0;for(let e=0;e<512;e++)s+=i[e];if(S(a,s.toString(8),o+148,8),!n){let t=new Uint8Array(a,o+512,e.size);for(let n=0;n<e.size;n++)t[n]=e.data[n];o+=512*Math.trunc(e.size/512),e.size%512&&(o+=512)}o+=512}return new Uint8Array(a)}function S(e,t,n,r){let i=new Uint8Array(e,n,r),a=new TextEncoder().encodeInto(t,i).written;for(let e=a;e<r;e++)i[e]=0}function C(e,t){return String(e).padStart(t,`0`)}function re(e){if(e!=null)return typeof e==`string`?new TextEncoder().encode(e):e instanceof ArrayBuffer?new Uint8Array(e):e}function ie(e){return e.byteOffset===0&&e.byteLength===e.buffer.byteLength?e:new Uint8Array(e)}function w(e){if(!(e instanceof Uint8Array))throw Error(`gunzip: input must be a Uint8Array`);if(e.length<18||e[0]!==31||e[1]!==139)throw Error(`gunzip: input is not a valid gzip stream (bad magic)`);try{return n(e)}catch(e){let t=e instanceof Error?e.message:String(e);throw Error(`gunzip: failed to decompress (${t})`)}}function ae(e){if(!(e instanceof Uint8Array))throw Error(`gzip: input must be a Uint8Array`);try{return t(e)}catch(e){let t=e instanceof Error?e.message:String(e);throw Error(`gzip: failed to compress (${t})`)}}function oe(e){if(!Array.isArray(e))throw Error(`writeTar: entries must be an array`);try{return ne(e.map(e=>({name:e.path,...e.directory?{}:{data:e.bytes},attrs:{mode:(e.mode??(e.directory?493:420)).toString(8),...e.mtime===void 0?{}:{mtime:e.mtime*1e3}}})))}catch(e){let t=e instanceof Error?e.message:String(e);throw Error(`writeTar: failed to create tar archive (${t})`)}}function se(e){return e.startsWith(`package/`)?e.slice(8):e}function T(e,t,n){let r=new Uint8Array(e,t,n),i=r.indexOf(0);return new TextDecoder().decode(i===-1?r:r.subarray(0,i))}function ce(e,t,n){let r=new Uint8Array(e,t,n),i=``;for(let e=0;e<n;e++)i+=String.fromCodePoint(r[e]);return Number.parseInt(i,8)}function le(e,t,n){let r=new TextDecoder().decode(new Uint8Array(e,t,n)),i,a;for(let e of r.split(`
4
- `)){let t=e.split(` `)[1]?.split(`=`);t&&(t[0]===`path`?i=t[1]:t[0]===`linkpath`&&(a=t[1]))}return i||a}function ue(e){let t=e.replace(/\\/g,`/`);t=t.replace(/^[a-zA-Z]:\//,``),t=t.replace(/^\/+/,``);let n=t.startsWith(`./`),r=t.split(`/`),i=[];for(let e of r)e===`..`?i.pop():e!==`.`&&e!==``&&i.push(e);let a=i.join(`/`);return n&&!a.startsWith(`./`)&&(a=`./`+a),e.endsWith(`/`)&&!a.endsWith(`/`)&&(a+=`/`),a}function de(e,t){let n=e.buffer,r=[],i=0,a;for(;i<n.byteLength-512;){let e=T(n,i,100);if(e.length===0)break;let o=ce(n,i+124,12),s=512+512*Math.trunc(o/512)+(o%512?512:0),c=T(n,i+156,1)||`0`;if(c===`x`||c===`g`){a=c===`x`?le(n,i+512,o):void 0,i+=s;continue}if(c===`L`||c===`N`||c===`K`){a=T(n,i+512,o),i+=s;continue}let l;if(a)l=a;else{let t=T(n,i+345,155);l=t.length>0?`${t}/${e}`:e}r.push(t?l:ue(l)),a=void 0,i+=s}return r}function E(e,t={}){if(!(e instanceof Uint8Array))throw Error(`readTar: input must be a Uint8Array`);let n=ie(e),r;try{r=y(n)}catch(e){let t=e instanceof Error?e.message:String(e);throw Error(`readTar: failed to parse tar archive (${t})`)}let i=t.stripNpmPrefix??!0,a=t.includeDirectories??!1,o=de(n,t.preserveRawPaths??!1),s=o.length===r.length;if(t.preserveRawPaths&&!s)throw Error(`readTar: raw path resolution did not align with archive entries`);let c=[];return r.forEach((e,t)=>{let n=e.type===`directory`;if(!n&&e.type!==`file`&&e.type!==`contiguousFile`||n&&!a)return;let r=s?o[t]:e.name,l=Number.parseInt(e.attrs?.mode??``,8);c.push({path:i?se(r):r,bytes:e.data?e.data.slice():new Uint8Array,...n?{directory:!0}:{},...Number.isFinite(l)?{mode:l&511}:{},...typeof e.attrs?.mtime==`number`?{mtime:e.attrs.mtime}:{}})}),c}function D(e){let t=(e??``).trim();if(!t)throw Error(`ipk: package spec is required`);if(t.startsWith(`@`)){let e=t.indexOf(`/`);if(e===-1)throw Error(`ipk: scoped spec '${t}' is missing a name (expected @scope/name)`);let n=t.slice(e+1),r=n.indexOf(`@`),i=t.slice(0,e);return r===-1?{name:`${i}/${n}`,range:``}:{name:`${i}/${n.slice(0,r)}`,range:n.slice(r+1)}}let n=t.indexOf(`@`);return n===-1?{name:t,range:``}:{name:t.slice(0,n),range:t.slice(n+1)}}function O(e,...t){return`/${[e,...t].join(`/`).split(`/`).filter(e=>e.length>0).join(`/`)}`}function k(e,t){if(t.startsWith(`@`)){let[n,r]=t.split(`/`,2);return O(e,n,r)}return O(e,t)}async function A(e,t){await e.mkdir(t,{recursive:!0})}async function j(e,t){await e.exists(t)&&await e.rm(t,{recursive:!0})}function fe(e){return`^${e}`}function M(e,t){let n=e.range.trim();return n===``||n===`*`||n===`latest`||/^[A-Za-z][A-Za-z0-9_-]*$/.test(n)?fe(t):n}async function pe(e,t,n){for(let r of n){if(!r.path)continue;let n=r.path.replace(/\\/g,`/`).replace(/^\/+/,``);if(n.split(`/`).some(e=>e===`..`))throw Error(`installer: refusing to extract entry escaping package root: ${r.path}`);let i=O(t,n),a=i.lastIndexOf(`/`);a>0&&await A(e,i.slice(0,a)),await e.writeFile(i,r.bytes)}}async function N(t,n,r){let i;try{i=await t.readFile(n)}catch(t){if(t instanceof e&&t.code===`ENOENT`)return r;throw t}return JSON.parse(i)}async function P(t,n,r){let i;try{i=await t.readFile(n)}catch(t){if(t instanceof e&&t.code===`ENOENT`)return r;throw t}if(!i?.trim())return r;try{return JSON.parse(i)}catch{return r}}const F=[`dependencies`,`devDependencies`,`optionalDependencies`,`peerDependencies`];function I(e,t){return e!==void 0&&Object.hasOwn(e,t)}function L(e,t,n){return n||I(e.devDependencies,t)?`devDependencies`:I(e.optionalDependencies,t)?`optionalDependencies`:I(e.peerDependencies,t)?`peerDependencies`:`dependencies`}function me(e,t){let n=e[L(e,t,!1)]?.[t];return typeof n==`string`&&n.trim()!==``?n:void 0}function he(e,t){if(e.range.trim()!==``)return e;let n=me(t,e.name);return n===void 0?e:{name:e.name,range:n}}function ge(e,t){let n={dependencies:{...e.dependencies??{}},devDependencies:{...e.devDependencies??{}},optionalDependencies:{...e.optionalDependencies??{}},peerDependencies:{...e.peerDependencies??{}}},r=new Set;for(let e of t){for(let t of F)delete n[t][e.name];n[e.section][e.name]=e.range,r.add(e.section)}let i={...e};for(let t of F)(e[t]!==void 0||r.has(t))&&(i[t]=n[t]);return i}function R(e,t){let n=new Map;return{supplier:async r=>{let i=n.get(r);return i||(i=await c(r,e,{timeoutMs:t}),n.set(r,i),i)},cache:n}}async function _e(e,t,n){let r=[],a=[],o=new Set;for(let s of e){let e;try{e=D(s)}catch(e){a.push({spec:s,error:z(e)});continue}if(n&&(e=he(e,n)),o.has(e.name)){let t=r.findIndex(t=>t.parsed.name===e.name);t>=0&&r.splice(t,1)}try{let n=await t(e.name);i(n,e.range)}catch(e){a.push({spec:s,error:z(e)});continue}r.push({spec:s,parsed:e}),o.add(e.name)}return{directs:r,errors:a}}function z(e){return e instanceof Error?e:Error(String(e))}async function B(e,t,n,r,i){let o=k(t,n.name),s=O(o,`package.json`),c=!1;if(await e.exists(s)&&(await P(e,s,null))?.version===n.version&&(c=!0),!c){let t=E(w(await a(n.resolved,r,{timeoutMs:i})));await j(e,o),await A(e,o);try{await pe(e,o,t)}catch(t){throw await j(e,o),t}}let l=Object.keys(n.dependencies);if(l.length>0){let t=O(o,`node_modules`);await A(e,t);for(let a of l)await B(e,t,n.dependencies[a],r,i)}}async function V(e,t,n,r,i){let a=Object.keys(n.root);if(a.length!==0){await A(e,t);for(let o of a)await B(e,t,n.root[o],r,i)}}function ve(e){if(e.startsWith(`@`)){let t=e.indexOf(`/`);if(t!==-1)return e.slice(t+1)}return e}function H(e,t){return typeof e==`string`?{[ve(t)]:e}:e}function ye(e){return e.replace(/^\.\//,``).replace(/^\/+/,``)}function be(e){return`#!/usr/bin/env node\nrequire(${JSON.stringify(e)});\n`}async function U(e,t){let n=[];return await W(e,t,0,n),n}async function W(e,t,n,r){if(!await e.exists(t))return;let i;try{i=await e.readDir(t)}catch{return}for(let a of i){if(a.type!==`directory`||a.name===`.bin`)continue;if(a.name.startsWith(`@`)){let i=O(t,a.name),o;try{o=await e.readDir(i)}catch{continue}for(let t of o){if(t.type!==`directory`)continue;let o=`${a.name}/${t.name}`;await G(e,O(i,t.name),o,n,r)}continue}let i=a.name;await G(e,O(t,a.name),i,n,r)}}async function G(e,t,n,r,i){let a=await P(e,O(t,`package.json`),null);if(a?.bin!==void 0&&a.bin!==null){let e=H(a.bin,n);for(let[a,o]of Object.entries(e))typeof a==`string`&&a.length!==0&&typeof o==`string`&&o.length!==0&&i.push({binName:a,pkgName:n,installDir:t,binPath:o,depth:r})}await W(e,O(t,`node_modules`),r+1,i)}function K(e){let t=new Map;for(let n of e){let e=t.get(n.binName);if(!e){t.set(n.binName,n);continue}(n.depth<e.depth||n.depth===e.depth&&n.pkgName<e.pkgName)&&t.set(n.binName,n)}return t}function q(e,t,n,r){let i=k(e,t.name);if(t.bin!==void 0&&t.bin!==null){let e=H(t.bin,t.name);for(let[a,o]of Object.entries(e))typeof a==`string`&&a.length!==0&&typeof o==`string`&&o.length!==0&&r.push({binName:a,pkgName:t.name,installDir:i,binPath:o,depth:n})}let a=O(i,`node_modules`);for(let e of Object.values(t.dependencies))q(a,e,n+1,r)}function xe(e,t){let n=[];for(let r of Object.values(e.root))q(t,r,0,n);return n}function J(e,t){return new Set(K(xe(e,t)).keys())}function Se(e,t,n){return`..${t.slice(e.length)}/${ye(n)}`}async function Y(e,t){let n=K(await U(e,t)),r=O(t,`.bin`);if(await e.exists(r)){let t;try{t=await e.readDir(r)}catch{t=[]}for(let i of t)i.type===`file`&&(n.has(i.name)||await e.rm(O(r,i.name)))}if(n.size!==0){await A(e,r);for(let i of n.values()){let n=O(r,i.binName),a=be(Se(t,i.installDir,i.binPath));await e.writeFile(n,a)}}}async function Ce(e,t,n){let r=O(t,`package.json`),i=ge(await N(e,r,{}),n);return await e.writeFile(r,`${JSON.stringify(i,null,2)}\n`),r}async function we(e,t){let{fs:n,fetch:i,cwd:a,timeoutMs:o,global:s=!1,saveDev:c=!1}=t;if(e.length===0)return{results:[],errors:[]};let u=s?l:a,f=await N(n,O(u,`package.json`),{}),{supplier:p}=R(i,o),{directs:m,errors:g}=await _e(e,p,f);if(m.length===0)return{results:[],errors:g};let v={};if(s)for(let e of Q(f))v[e.name]=e.range;for(let e of m)v[e.parsed.name]=e.parsed.range;let y=await d({rootDependencies:v,fetchPackument:p}),b=s?r:O(a,`node_modules`);if(s&&(await $(n,b,new Set(Object.keys(y.root))),await h(n,J(y,b))),await V(n,b,y,i,o),await Y(n,b),s){let e=K(await U(n,b));await _(n,new Set(e.keys()))}let x=await Ce(n,u,m.map(e=>{let t=y.root[e.parsed.name];if(!t)throw Error(`installer: resolved node missing for ${e.parsed.name}`);return{name:e.parsed.name,range:M(e.parsed,t.version),section:L(f,e.parsed.name,c)}}));return{results:m.map(e=>{let t=y.root[e.parsed.name],n=k(b,e.parsed.name);return{ok:!0,name:e.parsed.name,version:t.version,installPath:n,range:M(e.parsed,t.version),manifestPath:x}}),errors:g}}var X=class extends Error{constructor(e){super(`no package.json found at ${e} (run 'ipk install <pkg>' to create one, or add a package.json)`),this.name=`ManifestNotFoundError`}};function Z(e,t){if(!(!t||typeof t!=`object`))for(let[n,r]of Object.entries(t))typeof n==`string`&&typeof r==`string`&&e.set(n,r)}function Te(e){let t=new Map;return Z(t,e.devDependencies),Z(t,e.dependencies),Array.from(t.entries()).map(([e,t])=>({name:e,range:t}))}function Q(e){let t=new Map;return Z(t,e.dependencies),Z(t,e.peerDependencies),Z(t,e.optionalDependencies),Z(t,e.devDependencies),Array.from(t.entries()).map(([e,t])=>({name:e,range:t}))}async function Ee(e){let{fs:t,fetch:n,cwd:r,timeoutMs:a}=e,o=O(r,`package.json`);if(!await t.exists(o))throw new X(o);let s=Te(await N(t,o,{}));if(s.length===0)return{results:[],errors:[],empty:!0};let{supplier:c}=R(n,a),l=[],u=[];for(let e of s)try{let t=await c(e.name);i(t,e.range),l.push(e)}catch(t){u.push({spec:`${e.name}@${e.range}`,error:z(t)})}if(l.length===0)return{results:[],errors:u,empty:!1};let f={};for(let e of l)f[e.name]=e.range;let p=await d({rootDependencies:f,fetchPackument:c}),m=O(r,`node_modules`);return await V(t,m,p,n,a),await Y(t,m),{results:l.map(e=>{let t=p.root[e.name];return t?{ok:!0,name:e.name,version:t.version,installPath:k(m,e.name),range:e.range,manifestPath:o}:null}).filter(e=>e!==null),errors:u,empty:!1}}function De(e,t){return F.some(n=>I(e[n],t))}function Oe(e,t){let n={...e};for(let r of F){let i={...e[r]??{}};for(let e of t)delete i[e];e[r]!==void 0&&(n[r]=i)}return n}async function ke(e,t,n){await e.writeFile(t,`${JSON.stringify(n,null,2)}\n`)}async function $(e,t,n){if(!await e.exists(t))return;let r;try{r=await e.readDir(t)}catch{return}for(let i of r)if(i.name!==`.bin`&&i.type===`directory`){if(i.name.startsWith(`@`)){let r=O(t,i.name),a;try{a=await e.readDir(r)}catch{continue}for(let t of a){if(t.type!==`directory`)continue;let a=`${i.name}/${t.name}`;n.has(a)||await j(e,O(r,t.name))}continue}n.has(i.name)||await j(e,O(t,i.name))}}async function Ae(e,t,n,i){let a=Q(i??await N(e,o,{}));if(a.length===0){await j(e,r),await _(e,new Set);return}let{supplier:s}=R(t,n),c={};for(let e of a)c[e.name]=e.range;let l=await d({rootDependencies:c,fetchPackument:s});await $(e,r,new Set(Object.keys(l.root))),await h(e,J(l,r)),await V(e,r,l,t,n),await Y(e,r);let u=K(await U(e,r));await _(e,new Set(u.keys()))}async function je(e,t){let{fs:n,fetch:r,cwd:i,timeoutMs:a,global:o=!1}=t;if(e.length===0)return{results:[],errors:[]};let s=new Set,c=[];for(let t of e)try{s.add(D(t).name)}catch(e){c.push({spec:t,error:z(e)})}if(s.size===0)return{results:[],errors:c};let u=O(o?l:i,`package.json`);if(!await n.exists(u)){for(let t of e)c.push({spec:t,error:new X(u)});return{results:[],errors:c}}let d=await N(n,u,{}),f=[];for(let e of s)f.push({name:e,removed:De(d,e)});let p=Oe(d,s);try{o?await Ae(n,r,a,p):await Me(n,r,i,a,p)}catch(t){return c.push({spec:e.join(` `),error:z(t)}),{results:f,errors:c}}return await ke(n,u,p),{results:f,errors:c}}async function Me(e,t,n,r,i){let a=O(n,`package.json`),o=Q(i??await N(e,a,{})),s=O(n,`node_modules`);if(o.length===0){await j(e,s);return}let{supplier:c}=R(t,r),l={};for(let e of o)l[e.name]=e.range;let u=await d({rootDependencies:l,fetchPackument:c});await $(e,s,new Set(Object.keys(u.root))),await V(e,s,u,t,r),await Y(e,s)}async function Ne(e){let t=Q(await N(e,o,{})),n=[];for(let i of t){let t=await P(e,O(k(r,i.name),`package.json`),{});n.push({name:i.name,version:typeof t.version==`string`?t.version:`?`,range:i.range})}return n.sort((e,t)=>e.name.localeCompare(t.name)),n}async function Pe(e,t){let n=O(t,`package.json`);if(!await e.exists(n))return[];let r=Q(await N(e,n,{})),i=O(t,`node_modules`),a=[];for(let t of r){let n=await P(e,O(k(i,t.name),`package.json`),{});a.push({name:t.name,version:typeof n.version==`string`?n.version:`?`,range:t.range})}return a.sort((e,t)=>e.name.localeCompare(t.name)),a}export{Pe as a,ae as c,Ne as i,E as l,Ee as n,je as o,we as r,w as s,X as t,oe as u};
@@ -1 +0,0 @@
1
- import{n as e}from"./rolldown-runtime-Dd_uD5pT.js";import{t}from"./logger-LESFN7Hj.js";import{n}from"./feature-flags-ysThCqxC.js";import{t as r}from"./record-ChU1ND2B.js";import{n as i,o as a,r as o,u as s}from"./descriptor-S4Jug1iP.js";import{n as c,t as l}from"./thinking-level-5x0UAu9N.js";import{t as u}from"./types-D8gIX-W-.js";import{a as d,r as f}from"./memory-budget-Bcf7Eolo.js";import{a as ee,g as te,r as p}from"./kernel-worker-YhNfUQ_y.js";import{t as m}from"./MEMORY-CbB3xjAS.js";import{a as ne,i as re,n as h,o as g,r as _,t as ie}from"./instruction-frontmatter-B48EsYtA.js";import{c as v,d as y,n as ae,r as oe,s as b}from"./frozen-archive-writer-C_qn0GDJ.js";function x(e){let t=0;for(let n of e)n.timestamp>t&&(t=n.timestamp);return t}function S(e,t){return t>0?e.filter(e=>e.timestamp>t):[...e]}const C=t(`agentic-memory`),se=e=>[e.memoryPath],ce=e=>[`/sessions/`,`/shared/`,...a(e)],le=`awk.cat.cp.cut.date.diff.du.echo.file.find.grep.head.jq.ls.mkdir.mount.mv.nl.od.printf.readlink.rg.sed.sort.stat.tail.touch.tr.uniq.uname.upskill.wc.xxd`.split(`.`),ue={arrayKeys:new Set([`writablePaths`,`visiblePaths`,`allowedCommands`]),scalarKeys:new Set([`model`,`timeoutSeconds`,`dreamTimeoutSeconds`,`thinkingLevel`])},w=3e4;function T(e){return e===`cone`?`memory-curator`:`memory-curator-${e}`}const E={kind:`curate`,nameFor:T,rivalsFor:e=>[O(e)]},D=`{{TASK}}`;function de(e,t,n){return e.kind===`dream`?`**Consolidation pass** (the nightly dreaming): there is NO new session to mine — skip "Mining the session archive" entirely. Your whole job is to make the existing memory better: consolidated, current, and inside its budget. If the file is missing or empty, reply with one line saying so and stop; never invent memories. The run is hard-stopped after ${n} minutes; a run stopped at that bound lands whatever the memory file holds at that moment (every memory_write leaves a whole, budget-checked file), so consolidate section by section, writing as you go, and finish cleanly when you can.`:`**Curation pass**: mine the archived session at ${t} for what is worth carrying into future sessions, fold it into the memory, and consolidate the whole file in the same pass. Work fast: a pass should finish in well under 10 minutes and is hard-stopped after ${n} minutes — mine the three signals, write, and stop, rather than exploring the archive exhaustively.`}async function fe(e){try{await e.stat(f);return}catch{}try{await e.mkdir(`/etc`,{recursive:!0}),await e.writeFile(f,m),C.info(`Seeded default ${f}`)}catch(e){C.warn(`Failed to seed ${f}`,{error:I(e)})}}function O(e){return e===`cone`?`memory-dreamer`:`memory-dreamer-${e}`}function k(e,t){let n=e.nameFor(t);return A.test(n)?n:e.nameFor(r)}function pe(e,t){let n=A.test(e.nameFor(t))?t:r;return e.rivalsFor?.(n)??[]}const A=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;function me(e,t){return`/scoops/agent-${k(e,t)}`}function he(e){return me(E,e)}const ge=he(r);function _e(e){return s({parentJid:null,folder:e?.folder??`cone`})}function ve(e,t){if(t.root===i.root)return e;if(e===i.memoryPath)return t.memoryPath;if(e===`/workspace/skills`||e.startsWith(`/workspace/skills/`))return e;let n=`${i.root}/`;return e===i.root?t.root:e.startsWith(n)?`${t.root}/${e.slice(n.length)}`:e}function ye(e,t){let n=`${o}/`,r=e=>e.some(e=>n.startsWith(e.endsWith(`/`)?e:`${e}/`)),i=e.map(e=>ve(e,t));return r(e)&&!r(i)&&i.push(n),i}async function be(e){try{if(e.signal?.aborted)return{ok:!1,reason:`aborted`,legacyFallbackSafe:!1};let t=e.instructions??E,n=_e(e.cone),r=me(t,e.cone?.folder??`cone`),i=await xe(e.vfs,n),a=t.kind===`dream`?i.dreamTimeoutSeconds:i.timeoutSeconds,o=F(e.sessionArchivePath);try{await we(e.vfs,n.memoryPath,e.sessionArchivePath)}catch(e){return{ok:!1,reason:`snapshot: ${I(e)}`,legacyFallbackSafe:!0}}let s=t.kind===`dream`?`(no session archive this pass)`:e.sessionArchivePath,c=Math.max(1,Math.round(a/60)),l=de(t,s,c),u=Ee(i,a,De(Oe(i.promptTemplate.includes(D)?i.promptTemplate:`${i.promptTemplate.trimEnd()}\n\n${D}`,{MEMORY_PATH:o,SESSION_ARCHIVE_PATH:s,SESSION_COUNT:String(e.sessionCount),BUDGET_CHARS:String(d(e.sessionCount)),SCRATCH_DIR:r,TODAY:e.today??new Date().toISOString().slice(0,10),TIMEOUT_MINUTES:String(c),TASK:l}),r),e.sessionArchivePath,n,e.cone,t);e.signal&&(u.signal=e.signal);let f=await ke(Promise.resolve().then(()=>e.spawn(u)),a*1e3+w,e.signal);if(f.type===`timeout`)return C.warn(`Agentic memory wait timed out past the in-run bound + grace`,{timeoutSeconds:a,graceMs:w}),{ok:!1,reason:`timeout`,legacyFallbackSafe:!1};if(f.type===`aborted`)return{ok:!1,reason:`aborted`,legacyFallbackSafe:!1};if(f.type===`error`)return{ok:!1,reason:I(f.error),legacyFallbackSafe:!0};if(f.result.exitCode!==0){let e=(f.result.finalText??``).startsWith(te);return{ok:!1,reason:f.result.finalText||`exit-${f.result.exitCode}`,legacyFallbackSafe:!e}}return{ok:!0,report:f.result.finalText}}catch(e){return C.warn(`Agentic memory pass failed`,{error:I(e)}),{ok:!1,reason:I(e),legacyFallbackSafe:!1}}}async function xe(e,t=i){try{let n=await e.readFile(f,{encoding:`utf-8`});return j(typeof n==`string`?n:new TextDecoder().decode(n),t)}catch(e){return C.warn(`Could not load valid ${f}; using built-in default`,{error:I(e)}),j(m,t)}}function j(e,t=i){let n=ne(e,`MEMORY.md`),r=ie(n.frontmatter,ue),a=h(r,`writablePaths`,se(t));if(a.length===0)throw Error(`writablePaths must not be empty`);g(a,`writablePaths`);let o=h(r,`visiblePaths`,ce(t));g(o,`visiblePaths`);let s=_(r.timeoutSeconds,600,1200),c=_(r.dreamTimeoutSeconds,3600,7200,`dreamTimeoutSeconds`),l=re(r.model,`model`);return{writablePaths:a.map(e=>ve(e,t)),visiblePaths:ye(o,t),allowedCommands:[...new Set([...le,...h(r,`allowedCommands`,[])])],...l?{model:l}:{},thinkingLevel:Se(r.thinkingLevel),timeoutSeconds:s,dreamTimeoutSeconds:c,promptTemplate:n.body}}function Se(e){if(e===void 0)return`medium`;if(typeof e!=`string`||!c(e))throw Error(`thinkingLevel must be one of ${l.join(`, `)}`);return e}function M(e){return`/sessions/.curated/${e.slice(e.lastIndexOf(`/`)+1)}`}function N(e){return`/sessions/.curation/${e.slice(e.lastIndexOf(`/`)+1)}`}function P(e){return`${N(e)}/base.md`}function F(e){return`${N(e)}/draft.md`}function Ce(e){return`${N(e)}/status.json`}async function we(e,t,n){let r=``;try{let n=await e.readFile(t,{encoding:`utf-8`});r=typeof n==`string`?n:new TextDecoder().decode(n)}catch{}await e.mkdir(N(n),{recursive:!0}),await e.writeFile(P(n),r),await e.writeFile(F(n),r)}function Te(e,t,n){let r=e.map(e=>e===t?n:e);return r.includes(n)?r:[...r,n]}function Ee(e,t,n,r,i,a,o){let s=e.model===`parent`||e.model===`cone`,c=P(r),l=F(r);return{cwd:i.root,writablePaths:Te(e.writablePaths,i.memoryPath,l),visiblePaths:[...e.visiblePaths,`${N(r)}/`],allowedCommands:e.allowedCommands,prompt:n,thinkingLevel:e.thinkingLevel,persistSession:!0,name:k(o,a?.folder??`cone`),exclusiveWith:pe(o,a?.folder??`cone`),...a?.jid?{parentJid:a.jid}:{},notifyOnComplete:!0,successReceiptPath:M(r),mergeOnSuccess:{targetPath:i.memoryPath,basePath:c,draftPath:l},outcomeReceiptPath:Ce(r),maxWallClockMs:t*1e3,...!s&&e.model?{modelId:e.model}:{}}}function De(e,t){if(t===ge)return e;let n=`\0SCRATCH\0`;return e.replaceAll(t,n).replaceAll(ge,t).replaceAll(n,t)}function Oe(e,t){let n=e;for(let[e,r]of Object.entries(t))n=n.replaceAll(`{{${e}}}`,r);return n}function ke(e,t,n){return new Promise(r=>{let i=!1,a=e=>{i||(i=!0,clearTimeout(s),n?.removeEventListener(`abort`,o),r(e))},o=()=>a({type:`aborted`}),s=setTimeout(()=>a({type:`timeout`}),t);n?.addEventListener(`abort`,o,{once:!0}),e.then(e=>a({type:`result`,result:e}),e=>a({type:`error`,error:e}))})}function I(e){return e instanceof Error?e.message:String(e)}var Ae=e({DEFAULT_DELTA_LIMITS:()=>B,LIVE_DELTA_MAX_CHARS:()=>R,LIVE_DELTA_MAX_MESSAGES:()=>200,advanceCuratedThrough:()=>q,curateLiveSessionDelta:()=>K,liveDeltaArchivePath:()=>W,liveDeltaCurationEnabled:()=>U,scheduleLiveDeltaCuration:()=>je,takeDeltaSlice:()=>G});const L=t(`live-session-curation`),R=8e4,z=`/sessions/.live-deltas`,B={maxMessages:200,maxChars:R},V=new Map,H=new Map;function U(){return n(`memory-v2`)&&n(`agentic-memory`)}function W(e,t,n){return`${z}/${e}-${t}-${n}.md`}function G(e,t=B){if(e.length===0)return[];let n=[],r=0;for(let i of e){let e=Ve(i);if(n.length>=t.maxMessages||n.length>0&&r+e>t.maxChars)break;n.push(i),r+=e}n.length===0&&n.push(e[0]);let i=n[n.length-1].timestamp,a=n.length;for(;a<e.length&&e[a].timestamp===i;)n.push(e[a]),a+=1;return n}function je(e){if(!U())return Promise.resolve({status:`skipped`,reason:`flag-off`});let t=e.cone.folder||`cone`,n={...e.cone,folder:t},r=Be();if(!r)return L.info(`Live delta curation skipped: agent bridge not published`,{cone:t}),Promise.resolve({status:`skipped`,reason:`no-bridge`});let i={...e,cone:n},a=V.get(t);return a?(H.set(t,i),a):J(i,r)}function K(e){let t=e.cone.folder||`cone`,n={...e.cone,folder:t},r={...e,cone:n};if(e.hold===`held`)return Me(r);let i=V.get(t);return i?i.then(()=>K(r)):Y(t,Me(r))}async function q(e,t,n){n>0&&await v(async()=>{let r=await b(Z(e)),i=r.findIndex(e=>e.filename===t);if(i===-1||n<=(r[i].curatedThrough??0))return;let{memoryFailed:a,...o}=r[i],s=r.slice();s[i]={...o,curatedThrough:n},await y(Z(e),s),await Ie(e,`${p}/${t}`,n),await e.flush?.()})}function J(e,t){return Y(e.cone.folder||`cone`,K({vfs:e.vfs,cone:e.cone,spawn:e=>t.spawn(e),enabled:!0,hold:`held`,...e.limits?{limits:e.limits}:{}}))}function Y(e,t){return V.set(e,t),t.then(()=>X(e,t),()=>X(e,t)),t}function X(e,t){if(V.get(e)!==t)return;V.delete(e);let n=H.get(e);if(H.delete(e),!n||!U())return;let r=Be();r&&J(n,r).catch(t=>{L.warn(`Follow-up live delta curation failed to start`,{cone:e,error:Q(t)})})}async function Me(e){if(!(e.enabled??U()))return{status:`skipped`,reason:`flag-off`};let t=e.cone.folder||`cone`,n=e.limits??B,r;try{r=await b(Z(e.vfs))}catch(e){return L.warn(`Live delta curation skipped: sessions index unreadable`,{cone:t,error:Q(e)}),{status:`skipped`,reason:`index-unreadable`}}let i=ae(r,t);if(!i?.sessionId)return{status:`skipped`,reason:`no-archive`};let a=await Le(e.vfs,`${p}/${i.filename}`);if(!a)return{status:`skipped`,reason:`no-archive`};let o=await Ne(e.vfs,i.sessionId,i.filename,a,i.curatedThrough??0,n),s=S(a,o);if(s.length===0)return{status:`skipped`,reason:`caught-up`};let c=G(s,n),l=x(c);if(l<=o)return{status:`skipped`,reason:`caught-up`};let u=W(i.sessionId,o,l);await Pe(e.vfs,{sessionId:i.sessionId,filename:i.filename,title:i.title,frozenAt:i.frozenAt,cone:i.cone,coneLabel:i.coneLabel},c,u);let d=await be({spawn:e.spawn,vfs:e.vfs,sessionArchivePath:u,sessionCount:r.length,...t!==`cone`||e.cone.jid?{cone:e.cone}:{},...e.signal?{signal:e.signal}:{}});return d.ok?(await q(e.vfs,i.filename,l),L.info(`Live delta curated`,{cone:t,filename:i.filename,through:l}),{status:`curated`,curatedThrough:l,filename:i.filename}):(d.reason.startsWith(`agent: name already in use`)||await Fe(e.vfs,i.filename,d.reason),L.warn(`Live delta curation failed`,{cone:t,filename:i.filename,reason:d.reason}),{status:`failed`,reason:d.reason,filename:i.filename})}async function Ne(e,t,n,r,i,a){let o=i;for(let n=0;n<50;n+=1){let n=S(r,o);if(n.length===0)break;let i=x(G(n,a??B));if(i<=o||!await Re(e,W(t,o,i)))break;o=i}return o>i&&await q(e,n,o),o}async function Pe(e,t,n,r){let i={id:t.sessionId,title:t.title,frozenAt:t.frozenAt,createdAt:n[0]?.timestamp??0,updatedAt:x(n),messageCount:n.length,messages:[...n],...t.cone?{cone:t.cone}:{},...t.coneLabel?{coneLabel:t.coneLabel}:{}};await e.mkdir(z,{recursive:!0}),await e.writeFile(r,oe(i))}async function Fe(e,t,n){try{await v(async()=>{let r=await b(Z(e)),i=r.findIndex(e=>e.filename===t);if(i===-1)return;let a=r.slice();a[i]={...r[i],memoryFailed:n.slice(0,300)},await y(Z(e),a),await e.flush?.()})}catch(e){L.warn(`Failed to record live curation failure`,{filename:t,error:Q(e)})}}async function Ie(e,t,n){let r;try{r=await ze(e,t)}catch(e){if($(e))return;throw e}let i=r.match(/^---\n([\s\S]*?)\n---\n/);if(!i)return;let a=`curatedThrough: ${n}`,o=/^curatedThrough:\s*\d+\s*$/m.test(i[1])?i[1].replace(/^curatedThrough:\s*\d+\s*$/m,a):`${i[1]}\n${a}`;o!==i[1]&&await e.writeFile(t,`---\n${o}\n---\n${r.slice(i[0].length)}`)}async function Le(e,t){try{return ee(await ze(e,t)).messages}catch(e){if($(e))return null;throw e}}async function Re(e,t){try{return await e.readFile(M(t),{encoding:`utf-8`}),!0}catch(e){if($(e))return!1;throw e}}async function ze(e,t){let n=await e.readFile(t,{encoding:`utf-8`});return typeof n==`string`?n:new TextDecoder().decode(n)}function Be(){return globalThis.__slicc_agent}function Ve(e){let t=e.toolCalls?JSON.stringify(e.toolCalls).length:0;return e.content.length+t}function Z(e){return e}function Q(e){return e instanceof Error?e.message:String(e)}function $(e){return e instanceof u?e.code===`ENOENT`:typeof e!=`object`||!e||!(`code`in e)?!1:e.code===`ENOENT`}export{O as a,T as i,U as n,be as o,Ae as r,fe as s,K as t};
@@ -1 +0,0 @@
1
- const e=`/etc/MEMORY.md`,t=[`/shared/MEMORY.md`,`/shared/DREAMING.md`];function n(e){return Math.round(4e3+2e3*Math.log2((Number.isFinite(e)&&e>=0?e:0)+2))}const r=[/^\/workspace\/CLAUDE\.md$/,/^\/shared\/CLAUDE\.md$/,/^\/(?:cones|scoops)\/[^/]+\/CLAUDE\.md$/,/^\/sessions\/\.curation\/[^/]+\/draft\.md$/];function i(e){let t=`/${e}`.replace(/\/+/g,`/`).replace(/\/\.(?=\/)/g,``).replace(/\/$/,``);return r.some(e=>e.test(t))}const a=`memory_write`,o=`memory files are budget-guarded — write them with the ${a} tool, which enforces the budget and reports the remaining room`;export{n as a,a as i,o as n,i as o,e as r,t};