sliccy 6.146.2 → 6.147.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 (129) hide show
  1. package/dist/node-server/fetch-proxy-gzip.d.ts +34 -0
  2. package/dist/node-server/fetch-proxy-gzip.js +123 -0
  3. package/dist/node-server/fetch-proxy-headers.js +7 -0
  4. package/dist/node-server/routes/fetch-proxy.js +21 -12
  5. package/dist/ui/.vite/manifest.json +170 -158
  6. package/dist/ui/assets/{SKILL-CkfptFag.js → SKILL-2Mi1pQ3F.js} +30 -4
  7. package/dist/ui/assets/{account-store-BSBnFFPS.js → account-store-6fYzIPsO.js} +1 -1
  8. package/dist/ui/assets/{account-store-BRUCr96D.js → account-store-DSBPuJN7.js} +1 -1
  9. package/dist/ui/assets/{adobe-BePmoDqc.js → adobe--PkbJXyr.js} +1 -1
  10. package/dist/ui/assets/{adobe-D2ONtf9b.js → adobe-_ayrG9lb.js} +1 -1
  11. package/dist/ui/assets/{agent-bridge-DslQDtty.js → agent-bridge-9apk6tdC.js} +1 -1
  12. package/dist/ui/assets/{agent-panels-Ds3CUde9.js → agent-panels-wEXS6Snx.js} +1 -1
  13. package/dist/ui/assets/{apply-layout-CuJIEJ0g.js → apply-layout-xbQW06jD.js} +1 -1
  14. package/dist/ui/assets/{apps-xYbVYVNJ.js → apps-DYcOunQl.js} +1 -1
  15. package/dist/ui/assets/{azure-openai-C9RMKMwt.js → azure-openai-BDaJeYjY.js} +1 -1
  16. package/dist/ui/assets/{azure-openai-DLXgdMoO.js → azure-openai-CPi1_JUV.js} +1 -1
  17. package/dist/ui/assets/{budget-usage-source-DRsm-qIe.js → budget-usage-source-BygBihhd.js} +1 -1
  18. package/dist/ui/assets/{cdp-Bgplxqwh.js → cdp-B164i2yd.js} +1 -1
  19. package/dist/ui/assets/{cerebras-Bw_QvTrp.js → cerebras-CCGSKZIo.js} +1 -1
  20. package/dist/ui/assets/{cerebras-Bc5srro5.js → cerebras-soePCzEI.js} +1 -1
  21. package/dist/ui/assets/{composer-speech-B9r4JYxu.js → composer-speech-CONnJ9a8.js} +1 -1
  22. package/dist/ui/assets/{connect-surface-VgwGEglg.js → connect-surface-B5uadbu6.js} +1 -1
  23. package/dist/ui/assets/{directed-approval--0iRHwbB.js → directed-approval-OYbO_iSN.js} +1 -1
  24. package/dist/ui/assets/es-BR4l6CGS.js +1 -0
  25. package/dist/ui/assets/feature-flags-COdcJUhl.js +1 -0
  26. package/dist/ui/assets/frozen-archive-format-B4efpvB9.js +1 -0
  27. package/dist/ui/assets/frozen-archive-writer-cEYcj5un.js +8 -0
  28. package/dist/ui/assets/{fs-CWmEOkSn.js → fs-BfgEIhY7.js} +1 -1
  29. package/dist/ui/assets/{fs-sNrIPaO_.js → fs-CFSwpfwS.js} +2 -2
  30. package/dist/ui/assets/{github-BL7xlelB.js → github-CMy4oA0P.js} +2 -2
  31. package/dist/ui/assets/{github-copilot-C62fDFcu.js → github-copilot-BUQL8Mqn.js} +1 -1
  32. package/dist/ui/assets/{github-copilot-CtPhNQnK.js → github-copilot-CDj_b6sj.js} +1 -1
  33. package/dist/ui/assets/{github-install-DOMbiICh.js → github-install-fFFxQiCL.js} +1 -1
  34. package/dist/ui/assets/{github-DNtfKMGK.js → github-yoNzFKe_.js} +1 -1
  35. package/dist/ui/assets/{github-zip-BjQhOm6P.js → github-zip-BuTKMi7b.js} +1 -1
  36. package/dist/ui/assets/{hear-C4mXu7ZW.js → hear-CxIOumn9.js} +1 -1
  37. package/dist/ui/assets/{help-DHpBUyiO.js → help-BvFgSl6_.js} +1 -1
  38. package/dist/ui/assets/{js-realm-worker-EoBKAZHX.js → js-realm-worker-NHlCs_Fd.js} +1 -1
  39. package/dist/ui/assets/{kernel-worker-DacBBg8w.js → kernel-worker-sNqm6gqV.js} +644 -644
  40. package/dist/ui/assets/live-session-snapshot-BnA6Mq0G.js +1 -0
  41. package/dist/ui/assets/{local-llm-Cr6CTkbj.js → local-llm-BcAVBZee.js} +1 -1
  42. package/dist/ui/assets/{local-llm-BLnqY8h6.js → local-llm-DB7OUcFy.js} +1 -1
  43. package/dist/ui/assets/{main-cherry-DLuhoDS1.js → main-cherry-C6-AV8cY.js} +1 -1
  44. package/dist/ui/assets/{main-w_xCet4j.js → main-h_6bHCyA.js} +3 -3
  45. package/dist/ui/assets/memory-v2-flag-C1duOEOb.js +1 -0
  46. package/dist/ui/assets/{mount-uOkkZNjk.js → mount-Cd8ExLLy.js} +1 -1
  47. package/dist/ui/assets/{mount-7bYA8pGl.js → mount-DTx-0yit.js} +3 -3
  48. package/dist/ui/assets/{mount-recovery-DgGwhnxS.js → mount-recovery-CGP180NZ.js} +1 -1
  49. package/dist/ui/assets/{new-session-DBtk1rCL.js → new-session-BlinQKKe.js} +2 -2
  50. package/dist/ui/assets/{oauth-bootstrap-DYxjJLsL.js → oauth-bootstrap-COWUwhaQ.js} +2 -2
  51. package/dist/ui/assets/{onboarding-orchestrator-B6T_Ny1B.js → onboarding-orchestrator-BVcVLfMV.js} +1 -1
  52. package/dist/ui/assets/{openai-codex-DkzYl_Av.js → openai-codex-Cvv_6v-i.js} +1 -1
  53. package/dist/ui/assets/{openai-codex-BlCGePv3.js → openai-codex-DG355kmX.js} +1 -1
  54. package/dist/ui/assets/{openrouter-DfxV_kXn.js → openrouter-DN6PN9Wr.js} +1 -1
  55. package/dist/ui/assets/{openrouter-Cj2pVk0X.js → openrouter-Dbic9UcU.js} +1 -1
  56. package/dist/ui/assets/{openrouter-free-BjPH_kdE.js → openrouter-free-Can40S_x.js} +1 -1
  57. package/dist/ui/assets/{openrouter-free-DldbK6sa.js → openrouter-free-DReNzrCj.js} +1 -1
  58. package/dist/ui/assets/{openrouter-oauth-DgDO8d-n.js → openrouter-oauth-ChJf76qL.js} +1 -1
  59. package/dist/ui/assets/{openrouter-oauth-CH1i_4Ro.js → openrouter-oauth-Cr53CrUL.js} +1 -1
  60. package/dist/ui/assets/{panel-rpc-handlers-Ae7e5szM.js → panel-rpc-handlers-4OqnyAmK.js} +2 -2
  61. package/dist/ui/assets/{panelize-shell-9kCQ9OZk.js → panelize-shell-DF9ihI8M.js} +1 -1
  62. package/dist/ui/assets/{provider-BtR7FzYX.js → provider-1VMJDdZZ.js} +2 -2
  63. package/dist/ui/assets/{provider-Cb_dptea.js → provider-C6FaVer7.js} +1 -1
  64. package/dist/ui/assets/provider-settings-BoEydVUb.js +1 -0
  65. package/dist/ui/assets/provider-store-access-BgcRADIe.js +1 -0
  66. package/dist/ui/assets/provider-store-access-CFksaoYa.js +1 -0
  67. package/dist/ui/assets/{providers-CCYUf1lu.js → providers-BySKmZld.js} +2 -2
  68. package/dist/ui/assets/{providers-Bj5Jgeyh.js → providers-CwVqsqpF.js} +1 -1
  69. package/dist/ui/assets/{quick-llm-B8LK4tjq.js → quick-llm-CfwVaiXr.js} +1 -1
  70. package/dist/ui/assets/{recovery-screen-D-eWqkZz.js → recovery-screen-lyTGe0lL.js} +1 -1
  71. package/dist/ui/assets/{run-Clc4oMMw.js → run-BKnRgn-D.js} +2 -2
  72. package/dist/ui/assets/{run-BSItVSs5.js → run-BQh3vxRY.js} +1 -1
  73. package/dist/ui/assets/{run-QTBA9VNJ.js → run-BiqCIix1.js} +1 -1
  74. package/dist/ui/assets/session-command-memory-Bh_U73Lu.js +21 -0
  75. package/dist/ui/assets/session-jsonl-BxhPJRfn.js +3 -0
  76. package/dist/ui/assets/session-jsonl-DAaYGd3T.js +11 -0
  77. package/dist/ui/assets/session-search-index-CYtd-I68.js +3 -0
  78. package/dist/ui/assets/{setup-feature-flags-remote-C0aFgOXn.js → setup-feature-flags-remote-vkoKRY9P.js} +1 -1
  79. package/dist/ui/assets/sidecar-repair-DMTwInFS.js +1 -0
  80. package/dist/ui/assets/{silent-renew-backoff-BXFOEcR4.js → silent-renew-backoff-Cu6ccMA8.js} +1 -1
  81. package/dist/ui/assets/{skills-DH0igvmk.js → skills-CAcGvshD.js} +1 -1
  82. package/dist/ui/assets/slicc-version-DRMK7s55.js +1 -0
  83. package/dist/ui/assets/{snapshot-B23VxS3Z.js → snapshot-BiQjSDr1.js} +1 -1
  84. package/dist/ui/assets/{snapshot-features-EdqS3LYW.js → snapshot-features-jnkdn4FF.js} +1 -1
  85. package/dist/ui/assets/{soundscape-DbhVL1J6.js → soundscape-Q62OViF9.js} +1 -1
  86. package/dist/ui/assets/{speak-Nt2Xatm_.js → speak-BPaRbMbD.js} +1 -1
  87. package/dist/ui/assets/{sprinkle-manager-Gcr6PESp.js → sprinkle-manager-BRWbNbE_.js} +1 -1
  88. package/dist/ui/assets/{sprinkle-renderer-BgznbYny.js → sprinkle-renderer-D52IoNN9.js} +1 -1
  89. package/dist/ui/assets/{state-BiRW-NX3.js → state-Dd7acB-m.js} +1 -1
  90. package/dist/ui/assets/{store-BgpATPUF.js → store-Cwtr3R07.js} +1 -1
  91. package/dist/ui/assets/{store-Sz2R7uqe.js → store-Lwp3bUNr.js} +1 -1
  92. package/dist/ui/assets/{sudo-DcFRMDHW.js → sudo-D46irfhN.js} +1 -1
  93. package/dist/ui/assets/{sync-dialog-CG7oN3ii.js → sync-dialog-DJsA6fkU.js} +1 -1
  94. package/dist/ui/assets/{transformers-env-CAqo4XNv.js → transformers-env-tgTHZJKu.js} +1 -1
  95. package/dist/ui/assets/{tray-sidecar-DH_L8_VL.js → tray-sidecar-D2stckPR.js} +1 -1
  96. package/dist/ui/assets/{upgrade-detection-CIrFLX7C.js → upgrade-detection-BJHuh5PG.js} +1 -1
  97. package/dist/ui/assets/{voice-reply-S9gknH7c.js → voice-reply-BOM0a2lE.js} +1 -1
  98. package/dist/ui/assets/{wc-attach-Dh-J7Xnm.js → wc-attach-DQ2wFLbP.js} +2 -2
  99. package/dist/ui/assets/{wc-extension-DGzZxlv0.js → wc-extension-C0DE4XGb.js} +2 -2
  100. package/dist/ui/assets/{wc-follower-CBYRavvs.js → wc-follower-BaVLZOEY.js} +3 -3
  101. package/dist/ui/assets/{wc-follower-oauth-Dbdj3gVn.js → wc-follower-oauth-DMMj3qmG.js} +1 -1
  102. package/dist/ui/assets/wc-live-Ep7nfskG.js +395 -0
  103. package/dist/ui/assets/{wc-nav-69LMhXN-.js → wc-nav-8TQAWunr.js} +2 -2
  104. package/dist/ui/assets/{wc-onboarding-DeLL7QQz.js → wc-onboarding-7ug9Vb53.js} +2 -2
  105. package/dist/ui/assets/{wc-placeholder-B4z6NazB.js → wc-placeholder-ciXts94w.js} +3 -3
  106. package/dist/ui/assets/{wc-secret-request-CPlXgRlo.js → wc-secret-request-Bg0Z9yTb.js} +1 -1
  107. package/dist/ui/assets/{wc-settings-CFSgQw3j.js → wc-settings-DcEIZKCO.js} +3 -3
  108. package/dist/ui/assets/{wc-shell-CZCKkLJP.js → wc-shell-0IYPmKz5.js} +3 -3
  109. package/dist/ui/assets/{wc-shortcut-config-DO8_9Cf2.js → wc-shortcut-config-D-nERhOf.js} +1 -1
  110. package/dist/ui/assets/{wc-shortcuts-_REWQgA9.js → wc-shortcuts-8X2r2czL.js} +1 -1
  111. package/dist/ui/assets/{wc-sprinkles-Cmtrm7gu.js → wc-sprinkles-_Fa4xEjd.js} +2 -2
  112. package/dist/ui/assets/{wc-transcript-export-C7BaP8YL.js → wc-transcript-export-BTNFe3Rj.js} +2 -2
  113. package/dist/ui/assets/{wc-tray-Juzpc0lo.js → wc-tray-Ng4IYOo7.js} +4 -4
  114. package/dist/ui/assets/welcome-detection-BqZPDl32.js +1 -0
  115. package/dist/ui/assets/{whisper-session-B1zyLwlp.js → whisper-session-iQYr-1HE.js} +2 -2
  116. package/dist/ui/assets/{xai-grok-BkZGmqHN.js → xai-grok-B79MufzJ.js} +1 -1
  117. package/dist/ui/assets/{xai-grok-CYoaZvHZ.js → xai-grok-BkWgoDic.js} +1 -1
  118. package/dist/ui/index.html +3 -3
  119. package/dist/ui/packages/webapp/index.html +3 -3
  120. package/package.json +1 -1
  121. package/dist/ui/assets/frozen-archive-format-CP0rleV0.js +0 -1
  122. package/dist/ui/assets/live-session-snapshot-Dw8Q7uwS.js +0 -8
  123. package/dist/ui/assets/provider-settings-wIUvBGiz.js +0 -1
  124. package/dist/ui/assets/provider-store-access-Dt__oRzP.js +0 -1
  125. package/dist/ui/assets/provider-store-access-pBCuTMk1.js +0 -1
  126. package/dist/ui/assets/sidecar-repair-CODJ1Gjx.js +0 -1
  127. package/dist/ui/assets/slicc-version-Ddu_nmhS.js +0 -1
  128. package/dist/ui/assets/wc-live-DmfNvJns.js +0 -402
  129. package/dist/ui/assets/welcome-detection-B8VXP3l5.js +0 -1
@@ -1,4 +1,4 @@
1
- import{t as e}from"./logger-DDBAeTLF.js";import"./navigation-watcher-BpA1OwJw.js";import"./wc-follower-oauth-Dbdj3gVn.js";import{n as t,t as n}from"./pending-request-table-k-D7ZZsL.js";var r=e(`cdp`);function i(e){return e===4001?`CDP connection superseded by another SLICC tab/window on this instance`:e===4002?`CDP connection reset by proxy (upstream Chrome connection was re-established)`:`CDP connection closed`}var a=class{ws=null;nextId=1;_superseded=!1;pending=new n;listeners=new Map;_state=`disconnected`;stateListeners=new Set;lastNotifiedState=`disconnected`;lastNotifiedReason;get state(){return this._state}onStateChange(e){return this.stateListeners.add(e),()=>{this.stateListeners.delete(e)}}get superseded(){return this._superseded}async connect(e){if(this._state!==`disconnected`)throw Error(`Cannot connect: state is ${this._state}`);if(!e?.url)throw Error(`CDPClient.connect() requires a WebSocket URL`);let{url:t,timeout:n=5e3,protocols:i}=e;return this._state=`connecting`,new Promise((e,a)=>{let o=setTimeout(()=>{this.cleanup(),a(Error(`CDP connection timed out after ${n}ms`))},n);try{this.ws=i===void 0?new WebSocket(t):new WebSocket(t,i)}catch(e){clearTimeout(o),this._state=`disconnected`,a(e);return}this.ws.onopen=()=>{clearTimeout(o),this._state=`connected`,this._superseded=!1,r.info(`Connected`,{url:t}),this.notifyState(`connected`),e()},this.ws.onerror=e=>{clearTimeout(o),this._state===`connecting`&&(r.error(`Connection failed`,{url:t}),this.cleanup(),a(Error(`CDP WebSocket connection failed`)))},this.ws.onmessage=e=>{this.handleMessage(e.data)},this.ws.onclose=e=>{this.handleClose(e?.code)}})}disconnect(){this.ws&&(this.ws.onclose=null,this.ws.close()),this._superseded=!1,this.cleanup(),r.info(`Disconnected`)}async send(e,t,n,i=3e4){if(this._state!==`connected`||!this.ws)throw Error(`CDP client is not connected`);let a=this.nextId++,o={id:a,method:e};t&&(o.params=t),n&&(o.sessionId=n),r.debug(`Send`,{method:e,id:a,sessionId:n});let s=this.pending.issue(a,i,`CDP command timed out after ${i}ms: ${e}`);return this.ws.send(JSON.stringify(o)),s}on(e,t){let n=this.listeners.get(e);n||(n=new Set,this.listeners.set(e,n)),n.add(t)}off(e,t){let n=this.listeners.get(e);n&&(n.delete(t),n.size===0&&this.listeners.delete(e))}once(e,n=3e4){return t(t=>(this.on(e,t),()=>this.off(e,t)),n,`Timed out waiting for event: ${e}`)}handleMessage(e){let t;try{t=JSON.parse(e)}catch{return}if(`id`in t&&typeof t.id==`number`){let e=t;r.debug(`Response`,{id:e.id,hasError:!!e.error}),e.error?(r.error(`Command error`,{id:e.id,code:e.error.code,message:e.error.message}),this.pending.reject(e.id,Error(`CDP error: ${e.error.message} (${e.error.code})`))):this.pending.resolve(e.id,e.result??{});return}if(`method`in t){let e=t;r.debug(`Event`,{method:e.method,sessionId:e.sessionId});let n=this.listeners.get(e.method);if(n){let t=e.sessionId?{...e.params,sessionId:e.sessionId}:e.params??{};for(let e of n)try{e(t)}catch{}}}}handleClose(e){e===4001?(this._superseded=!0,r.warn(`CDP slot superseded by another SLICC tab/window on this instance`,{code:e})):e===4002?r.warn(`CDP proxy reset its upstream Chrome connection — sessions dropped`,{code:e,pendingCommands:this.pending.size}):r.error(`Connection closed unexpectedly`,{pendingCommands:this.pending.size}),this.cleanup(i(e))}cleanup(e=`CDP client disconnected`){this.ws=null,this._state=`disconnected`,this.pending.rejectAll(e),this.notifyState(`disconnected`,e)}notifyState(e,t){if(e!==this.lastNotifiedState||t!==this.lastNotifiedReason){this.lastNotifiedState=e,this.lastNotifiedReason=t;for(let n of this.stateListeners)try{n(e,t)}catch{}}}},o=class extends Error{step;name=`CommandAbortedError`;constructor(e){super(`Browser command aborted while ${e}. A CDP round trip already in flight cannot be cancelled, so it may still have been applied to the page; nothing after it was started.`),this.step=e}};function s(e,t){if(e?.aborted)throw new o(t)}function c(e,t){return e?{signal:e,error:()=>new o(t)}:void 0}function l(e,t,n){return new Promise((r,i)=>{if(t?.aborted){i(new o(n));return}let a=()=>{clearTimeout(s),i(new o(n))},s=setTimeout(()=>{t?.removeEventListener(`abort`,a),r()},e);t?.addEventListener(`abort`,a,{once:!0})})}function u(e,t,n){return t?t.aborted?Promise.reject(new o(n)):new Promise((r,i)=>{let a=()=>i(new o(n));t.addEventListener(`abort`,a,{once:!0}),e.then(()=>{t.removeEventListener(`abort`,a),r()},e=>{t.removeEventListener(`abort`,a),i(e instanceof Error?e:Error(String(e)))})}):e}var d=e(`har-recorder`),f=class{recordings=new Map;client;fs;eventCleanup=new Map;constructor(e,t){this.client=e,this.fs=t}async startRecording(e,t,n,r){let i=`rec-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;s(r,`about to enable Network on tab ${e}`),await this.client.send(`Network.enable`,{},t),s(r,`about to enable Page on tab ${e}`),await this.client.send(`Page.enable`,{},t),s(r,`about to read the URL of tab ${e}`);let a=(await this.client.send(`Runtime.evaluate`,{expression:`location.href`,returnByValue:!0},t)).result?.value??`about:blank`,o={id:i,targetId:e,sessionId:t,filterCode:n,pendingRequests:new Map,entries:[],startTime:Date.now(),currentUrl:a,snapshotCount:0};return this.recordings.set(i,o),this.setupEventListeners(o),await this.ensureDir(`/recordings/${i}`),d.debug(`Started recording`,{recordingId:i,targetId:e,currentUrl:a}),i}setupEventListeners(e){let{sessionId:t,id:n}=e,r=n=>{let r=n;r.sessionId===t&&this.handleRequestWillBeSent(e,r)},i=n=>{let r=n;r.sessionId===t&&this.handleResponseReceived(e,r)},a=r=>{let i=r;i.sessionId===t&&this.handleLoadingFinished(e,i).catch(e=>{d.error(`Failed to process loadingFinished event`,{recordingId:n,requestId:i.requestId,error:e instanceof Error?e.message:String(e)})})},o=n=>{let r=n;r.sessionId===t&&this.handleLoadingFailed(e,r)},s=r=>{let i=r;if(i.sessionId!==t)return;let a=i.frame;if(!a?.parentId&&a?.url){let t=[...e.entries],r=e.currentUrl;e.currentUrl=a.url,e.entries=[],e.pendingRequests.clear(),this.saveSnapshotWithEntries(e,`navigation`,t,r).catch(e=>{d.error(`Failed to save navigation snapshot`,{recordingId:n,error:e instanceof Error?e.message:String(e)})})}};this.client.on(`Network.requestWillBeSent`,r),this.client.on(`Network.responseReceived`,i),this.client.on(`Network.loadingFinished`,a),this.client.on(`Network.loadingFailed`,o),this.client.on(`Page.frameNavigated`,s),this.eventCleanup.set(n,()=>{this.client.off(`Network.requestWillBeSent`,r),this.client.off(`Network.responseReceived`,i),this.client.off(`Network.loadingFinished`,a),this.client.off(`Network.loadingFailed`,o),this.client.off(`Page.frameNavigated`,s)})}handleRequestWillBeSent(e,t){let{requestId:n,request:r,timestamp:i}=t;!n||!r||i==null||e.pendingRequests.set(n,{requestId:n,startTime:i*1e3,request:{method:r.method,url:r.url,headers:r.headers,postData:r.postData}})}handleResponseReceived(e,t){let{requestId:n,response:r}=t;if(!n||!r)return;let i=e.pendingRequests.get(n);i&&(i.response={status:r.status,statusText:r.statusText,headers:r.headers,mimeType:r.mimeType},i.timing=r.timing)}async handleLoadingFinished(e,t){let{requestId:n,timestamp:r}=t;if(!n||r==null)return;let i=e.pendingRequests.get(n);if(!i)return;i.endTime=r*1e3;try{let t=await this.client.send(`Network.getResponseBody`,{requestId:n},e.sessionId);i.responseBody=t.body,i.responseBodyBase64=t.base64Encoded===!0}catch{}let a=this.buildHarEntry(i);a&&e.entries.push(a),e.pendingRequests.delete(n)}handleLoadingFailed(e,t){let{requestId:n}=t;n&&e.pendingRequests.delete(n)}buildHarEntry(e){if(!e.response)return null;let{request:t,response:n,timing:r,startTime:i,endTime:a,responseBody:o,responseBodyBase64:s}=e,c=a?a-i:0,l=[];try{let e=new URL(t.url);l=Array.from(e.searchParams.entries()).map(([e,t])=>({name:e,value:t}))}catch{}let u=r?(()=>{let e=(e,t)=>{if(e==null||t==null||e<0||t<0)return-1;let n=t-e;return n>=0?n:-1},t=r.dnsStart>=0?r.dnsStart:r.connectStart>=0?r.connectStart:0;return{blocked:t>0?t:-1,dns:e(r.dnsStart,r.dnsEnd),connect:e(r.connectStart,r.connectEnd),ssl:e(r.sslStart,r.sslEnd),send:e(r.sendStart,r.sendEnd),wait:e(r.sendEnd,r.receiveHeadersStart),receive:e(r.receiveHeadersStart,r.receiveHeadersEnd)}})():{blocked:-1,dns:-1,connect:-1,ssl:-1,send:0,wait:c,receive:0},d={size:o?.length??0,mimeType:n.mimeType??`application/octet-stream`};o&&(d.text=o,s&&(d.encoding=`base64`));let f;return t.postData&&(f={mimeType:t.headers[`content-type`]??t.headers[`Content-Type`]??`text/plain`,text:t.postData}),{startedDateTime:new Date(i).toISOString(),time:c,request:{method:t.method,url:t.url,httpVersion:`HTTP/1.1`,cookies:[],headers:Object.entries(t.headers).map(([e,t])=>({name:e,value:t})),queryString:l,postData:f,headersSize:-1,bodySize:t.postData?.length??0},response:{status:n.status,statusText:n.statusText,httpVersion:`HTTP/1.1`,cookies:[],headers:Object.entries(n.headers).map(([e,t])=>({name:e,value:t})),content:d,redirectURL:n.headers.location??n.headers.Location??``,headersSize:-1,bodySize:d.size},cache:{},timings:u}}async saveSnapshot(e,t){return this.saveSnapshotWithEntries(e,t,e.entries,e.currentUrl)}async applyFilter(e,t){return p(e,t)}async saveSnapshotWithEntries(e,t,n,r){if(n.length===0)return d.debug(`No entries to save`,{recordingId:e.id,trigger:t}),null;let i=e.filterCode?await this.applyFilter(n,e.filterCode):n;if(i.length===0)return d.debug(`All entries filtered out`,{recordingId:e.id,trigger:t}),null;e.snapshotCount++;let a=new Date().toISOString().replace(/[:.]/g,`-`),o=this.urlToSlug(r),s=`${e.snapshotCount.toString().padStart(3,`0`)}-${a}-${t}-${o}.har`,c=`/recordings/${e.id}/${s}`,l={log:{version:`1.2`,creator:{name:`SLICC HAR Recorder`,version:`1.0.0`},entries:i}};return await this.fs.writeFile(c,JSON.stringify(l,null,2)),d.debug(`Saved HAR snapshot`,{recordingId:e.id,path:c,entryCount:i.length}),c}urlToSlug(e){try{let t=new URL(e);return`${t.hostname}${t.pathname}`.replace(/[^a-zA-Z0-9]/g,`-`).replace(/-+/g,`-`).replace(/^-|-$/g,``).slice(0,50)||`page`}catch{return`page`}}async stopRecording(e){let t=this.recordings.get(e);if(!t)throw Error(`Recording not found: ${e}`);await this.saveSnapshot(t,`close`);let n=this.eventCleanup.get(e);n&&(n(),this.eventCleanup.delete(e));try{await this.client.send(`Network.disable`,{},t.sessionId)}catch{}this.recordings.delete(e);let r=`/recordings/${e}`;return d.debug(`Stopped recording`,{recordingId:e,snapshotCount:t.snapshotCount}),r}getRecording(e){return this.recordings.get(e)}getRecordingByTarget(e){for(let[t,n]of this.recordings)if(n.targetId===e)return t}async ensureDir(e){await this.fs.mkdir(e,{recursive:!0})}};function p(e,t){try{let n=Function(`entry`,`return (${t})(entry);`),r=[];for(let t of e)try{let e=n(t);if(e===!1)continue;typeof e==`object`&&e?r.push(e):r.push(t)}catch(e){d.error(`Filter function error on entry, keeping it`,{error:e instanceof Error?e.message:String(e)}),r.push(t)}return r}catch(t){return d.error(`Failed to compile filter, returning unfiltered`,{error:t instanceof Error?t.message:String(t)}),e}}var m=`(function() {
1
+ import{t as e}from"./logger-DDBAeTLF.js";import"./navigation-watcher-BpA1OwJw.js";import"./wc-follower-oauth-DMMj3qmG.js";import{n as t,t as n}from"./pending-request-table-k-D7ZZsL.js";var r=e(`cdp`);function i(e){return e===4001?`CDP connection superseded by another SLICC tab/window on this instance`:e===4002?`CDP connection reset by proxy (upstream Chrome connection was re-established)`:`CDP connection closed`}var a=class{ws=null;nextId=1;_superseded=!1;pending=new n;listeners=new Map;_state=`disconnected`;stateListeners=new Set;lastNotifiedState=`disconnected`;lastNotifiedReason;get state(){return this._state}onStateChange(e){return this.stateListeners.add(e),()=>{this.stateListeners.delete(e)}}get superseded(){return this._superseded}async connect(e){if(this._state!==`disconnected`)throw Error(`Cannot connect: state is ${this._state}`);if(!e?.url)throw Error(`CDPClient.connect() requires a WebSocket URL`);let{url:t,timeout:n=5e3,protocols:i}=e;return this._state=`connecting`,new Promise((e,a)=>{let o=setTimeout(()=>{this.cleanup(),a(Error(`CDP connection timed out after ${n}ms`))},n);try{this.ws=i===void 0?new WebSocket(t):new WebSocket(t,i)}catch(e){clearTimeout(o),this._state=`disconnected`,a(e);return}this.ws.onopen=()=>{clearTimeout(o),this._state=`connected`,this._superseded=!1,r.info(`Connected`,{url:t}),this.notifyState(`connected`),e()},this.ws.onerror=e=>{clearTimeout(o),this._state===`connecting`&&(r.error(`Connection failed`,{url:t}),this.cleanup(),a(Error(`CDP WebSocket connection failed`)))},this.ws.onmessage=e=>{this.handleMessage(e.data)},this.ws.onclose=e=>{this.handleClose(e?.code)}})}disconnect(){this.ws&&(this.ws.onclose=null,this.ws.close()),this._superseded=!1,this.cleanup(),r.info(`Disconnected`)}async send(e,t,n,i=3e4){if(this._state!==`connected`||!this.ws)throw Error(`CDP client is not connected`);let a=this.nextId++,o={id:a,method:e};t&&(o.params=t),n&&(o.sessionId=n),r.debug(`Send`,{method:e,id:a,sessionId:n});let s=this.pending.issue(a,i,`CDP command timed out after ${i}ms: ${e}`);return this.ws.send(JSON.stringify(o)),s}on(e,t){let n=this.listeners.get(e);n||(n=new Set,this.listeners.set(e,n)),n.add(t)}off(e,t){let n=this.listeners.get(e);n&&(n.delete(t),n.size===0&&this.listeners.delete(e))}once(e,n=3e4){return t(t=>(this.on(e,t),()=>this.off(e,t)),n,`Timed out waiting for event: ${e}`)}handleMessage(e){let t;try{t=JSON.parse(e)}catch{return}if(`id`in t&&typeof t.id==`number`){let e=t;r.debug(`Response`,{id:e.id,hasError:!!e.error}),e.error?(r.error(`Command error`,{id:e.id,code:e.error.code,message:e.error.message}),this.pending.reject(e.id,Error(`CDP error: ${e.error.message} (${e.error.code})`))):this.pending.resolve(e.id,e.result??{});return}if(`method`in t){let e=t;r.debug(`Event`,{method:e.method,sessionId:e.sessionId});let n=this.listeners.get(e.method);if(n){let t=e.sessionId?{...e.params,sessionId:e.sessionId}:e.params??{};for(let e of n)try{e(t)}catch{}}}}handleClose(e){e===4001?(this._superseded=!0,r.warn(`CDP slot superseded by another SLICC tab/window on this instance`,{code:e})):e===4002?r.warn(`CDP proxy reset its upstream Chrome connection — sessions dropped`,{code:e,pendingCommands:this.pending.size}):r.error(`Connection closed unexpectedly`,{pendingCommands:this.pending.size}),this.cleanup(i(e))}cleanup(e=`CDP client disconnected`){this.ws=null,this._state=`disconnected`,this.pending.rejectAll(e),this.notifyState(`disconnected`,e)}notifyState(e,t){if(e!==this.lastNotifiedState||t!==this.lastNotifiedReason){this.lastNotifiedState=e,this.lastNotifiedReason=t;for(let n of this.stateListeners)try{n(e,t)}catch{}}}},o=class extends Error{step;name=`CommandAbortedError`;constructor(e){super(`Browser command aborted while ${e}. A CDP round trip already in flight cannot be cancelled, so it may still have been applied to the page; nothing after it was started.`),this.step=e}};function s(e,t){if(e?.aborted)throw new o(t)}function c(e,t){return e?{signal:e,error:()=>new o(t)}:void 0}function l(e,t,n){return new Promise((r,i)=>{if(t?.aborted){i(new o(n));return}let a=()=>{clearTimeout(s),i(new o(n))},s=setTimeout(()=>{t?.removeEventListener(`abort`,a),r()},e);t?.addEventListener(`abort`,a,{once:!0})})}function u(e,t,n){return t?t.aborted?Promise.reject(new o(n)):new Promise((r,i)=>{let a=()=>i(new o(n));t.addEventListener(`abort`,a,{once:!0}),e.then(()=>{t.removeEventListener(`abort`,a),r()},e=>{t.removeEventListener(`abort`,a),i(e instanceof Error?e:Error(String(e)))})}):e}var d=e(`har-recorder`),f=class{recordings=new Map;client;fs;eventCleanup=new Map;constructor(e,t){this.client=e,this.fs=t}async startRecording(e,t,n,r){let i=`rec-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;s(r,`about to enable Network on tab ${e}`),await this.client.send(`Network.enable`,{},t),s(r,`about to enable Page on tab ${e}`),await this.client.send(`Page.enable`,{},t),s(r,`about to read the URL of tab ${e}`);let a=(await this.client.send(`Runtime.evaluate`,{expression:`location.href`,returnByValue:!0},t)).result?.value??`about:blank`,o={id:i,targetId:e,sessionId:t,filterCode:n,pendingRequests:new Map,entries:[],startTime:Date.now(),currentUrl:a,snapshotCount:0};return this.recordings.set(i,o),this.setupEventListeners(o),await this.ensureDir(`/recordings/${i}`),d.debug(`Started recording`,{recordingId:i,targetId:e,currentUrl:a}),i}setupEventListeners(e){let{sessionId:t,id:n}=e,r=n=>{let r=n;r.sessionId===t&&this.handleRequestWillBeSent(e,r)},i=n=>{let r=n;r.sessionId===t&&this.handleResponseReceived(e,r)},a=r=>{let i=r;i.sessionId===t&&this.handleLoadingFinished(e,i).catch(e=>{d.error(`Failed to process loadingFinished event`,{recordingId:n,requestId:i.requestId,error:e instanceof Error?e.message:String(e)})})},o=n=>{let r=n;r.sessionId===t&&this.handleLoadingFailed(e,r)},s=r=>{let i=r;if(i.sessionId!==t)return;let a=i.frame;if(!a?.parentId&&a?.url){let t=[...e.entries],r=e.currentUrl;e.currentUrl=a.url,e.entries=[],e.pendingRequests.clear(),this.saveSnapshotWithEntries(e,`navigation`,t,r).catch(e=>{d.error(`Failed to save navigation snapshot`,{recordingId:n,error:e instanceof Error?e.message:String(e)})})}};this.client.on(`Network.requestWillBeSent`,r),this.client.on(`Network.responseReceived`,i),this.client.on(`Network.loadingFinished`,a),this.client.on(`Network.loadingFailed`,o),this.client.on(`Page.frameNavigated`,s),this.eventCleanup.set(n,()=>{this.client.off(`Network.requestWillBeSent`,r),this.client.off(`Network.responseReceived`,i),this.client.off(`Network.loadingFinished`,a),this.client.off(`Network.loadingFailed`,o),this.client.off(`Page.frameNavigated`,s)})}handleRequestWillBeSent(e,t){let{requestId:n,request:r,timestamp:i}=t;!n||!r||i==null||e.pendingRequests.set(n,{requestId:n,startTime:i*1e3,request:{method:r.method,url:r.url,headers:r.headers,postData:r.postData}})}handleResponseReceived(e,t){let{requestId:n,response:r}=t;if(!n||!r)return;let i=e.pendingRequests.get(n);i&&(i.response={status:r.status,statusText:r.statusText,headers:r.headers,mimeType:r.mimeType},i.timing=r.timing)}async handleLoadingFinished(e,t){let{requestId:n,timestamp:r}=t;if(!n||r==null)return;let i=e.pendingRequests.get(n);if(!i)return;i.endTime=r*1e3;try{let t=await this.client.send(`Network.getResponseBody`,{requestId:n},e.sessionId);i.responseBody=t.body,i.responseBodyBase64=t.base64Encoded===!0}catch{}let a=this.buildHarEntry(i);a&&e.entries.push(a),e.pendingRequests.delete(n)}handleLoadingFailed(e,t){let{requestId:n}=t;n&&e.pendingRequests.delete(n)}buildHarEntry(e){if(!e.response)return null;let{request:t,response:n,timing:r,startTime:i,endTime:a,responseBody:o,responseBodyBase64:s}=e,c=a?a-i:0,l=[];try{let e=new URL(t.url);l=Array.from(e.searchParams.entries()).map(([e,t])=>({name:e,value:t}))}catch{}let u=r?(()=>{let e=(e,t)=>{if(e==null||t==null||e<0||t<0)return-1;let n=t-e;return n>=0?n:-1},t=r.dnsStart>=0?r.dnsStart:r.connectStart>=0?r.connectStart:0;return{blocked:t>0?t:-1,dns:e(r.dnsStart,r.dnsEnd),connect:e(r.connectStart,r.connectEnd),ssl:e(r.sslStart,r.sslEnd),send:e(r.sendStart,r.sendEnd),wait:e(r.sendEnd,r.receiveHeadersStart),receive:e(r.receiveHeadersStart,r.receiveHeadersEnd)}})():{blocked:-1,dns:-1,connect:-1,ssl:-1,send:0,wait:c,receive:0},d={size:o?.length??0,mimeType:n.mimeType??`application/octet-stream`};o&&(d.text=o,s&&(d.encoding=`base64`));let f;return t.postData&&(f={mimeType:t.headers[`content-type`]??t.headers[`Content-Type`]??`text/plain`,text:t.postData}),{startedDateTime:new Date(i).toISOString(),time:c,request:{method:t.method,url:t.url,httpVersion:`HTTP/1.1`,cookies:[],headers:Object.entries(t.headers).map(([e,t])=>({name:e,value:t})),queryString:l,postData:f,headersSize:-1,bodySize:t.postData?.length??0},response:{status:n.status,statusText:n.statusText,httpVersion:`HTTP/1.1`,cookies:[],headers:Object.entries(n.headers).map(([e,t])=>({name:e,value:t})),content:d,redirectURL:n.headers.location??n.headers.Location??``,headersSize:-1,bodySize:d.size},cache:{},timings:u}}async saveSnapshot(e,t){return this.saveSnapshotWithEntries(e,t,e.entries,e.currentUrl)}async applyFilter(e,t){return p(e,t)}async saveSnapshotWithEntries(e,t,n,r){if(n.length===0)return d.debug(`No entries to save`,{recordingId:e.id,trigger:t}),null;let i=e.filterCode?await this.applyFilter(n,e.filterCode):n;if(i.length===0)return d.debug(`All entries filtered out`,{recordingId:e.id,trigger:t}),null;e.snapshotCount++;let a=new Date().toISOString().replace(/[:.]/g,`-`),o=this.urlToSlug(r),s=`${e.snapshotCount.toString().padStart(3,`0`)}-${a}-${t}-${o}.har`,c=`/recordings/${e.id}/${s}`,l={log:{version:`1.2`,creator:{name:`SLICC HAR Recorder`,version:`1.0.0`},entries:i}};return await this.fs.writeFile(c,JSON.stringify(l,null,2)),d.debug(`Saved HAR snapshot`,{recordingId:e.id,path:c,entryCount:i.length}),c}urlToSlug(e){try{let t=new URL(e);return`${t.hostname}${t.pathname}`.replace(/[^a-zA-Z0-9]/g,`-`).replace(/-+/g,`-`).replace(/^-|-$/g,``).slice(0,50)||`page`}catch{return`page`}}async stopRecording(e){let t=this.recordings.get(e);if(!t)throw Error(`Recording not found: ${e}`);await this.saveSnapshot(t,`close`);let n=this.eventCleanup.get(e);n&&(n(),this.eventCleanup.delete(e));try{await this.client.send(`Network.disable`,{},t.sessionId)}catch{}this.recordings.delete(e);let r=`/recordings/${e}`;return d.debug(`Stopped recording`,{recordingId:e,snapshotCount:t.snapshotCount}),r}getRecording(e){return this.recordings.get(e)}getRecordingByTarget(e){for(let[t,n]of this.recordings)if(n.targetId===e)return t}async ensureDir(e){await this.fs.mkdir(e,{recursive:!0})}};function p(e,t){try{let n=Function(`entry`,`return (${t})(entry);`),r=[];for(let t of e)try{let e=n(t);if(e===!1)continue;typeof e==`object`&&e?r.push(e):r.push(t)}catch(e){d.error(`Filter function error on entry, keeping it`,{error:e instanceof Error?e.message:String(e)}),r.push(t)}return r}catch(t){return d.error(`Failed to compile filter, returning unfiltered`,{error:t instanceof Error?t.message:String(t)}),e}}var m=`(function() {
2
2
  'use strict';
3
3
 
4
4
  // ===== DOM Utilities =====
@@ -1 +1 @@
1
- import{_ as e}from"./account-store-BSBnFFPS.js";import{a as t}from"./diagnostics-DN_idNHx.js";import{d as n}from"./claude-model-version-CSATLzrT.js";import{r,s as i}from"./legacy-api-aliases-bAJ0Klzq.js";var a=`cerebras`,o=`https://api.cerebras.ai/v1`,s=`openai-completions`,c=`${a}-openai`,l=`slicc-cerebras-models`,u=[],d=[{id:`gpt-oss-120b`,name:`GPT OSS 120B`,api:`openai`,reasoning:!0,input:[`text`],context_window:131072,max_tokens:40960},{id:`gemma-4-31b`,name:`Gemma 4 31B`,api:`openai`,reasoning:!1,input:[`text`,`image`],context_window:131072,max_tokens:40960},{id:`zai-glm-4.7`,name:`Z.AI GLM-4.7`,api:`openai`,reasoning:!1,input:[`text`],context_window:131072,max_tokens:40960}];function f(e){try{localStorage.setItem(l,JSON.stringify(e))}catch{}}function p(){try{let e=localStorage.getItem(l);if(!e)return[];let t=JSON.parse(e);return Array.isArray(t)&&t.length>0?t:[]}catch{return[]}}function m(e){let t=e.id??``,n=d.find(e=>e.id===t);return{id:t,name:e.name??n?.name??t,api:`openai`,reasoning:e.capabilities?.reasoning??n?.reasoning??!1,input:e.capabilities?.vision?[`text`,`image`]:n?.input??[`text`],context_window:e.limits?.max_context_length??n?.context_window??8192,max_tokens:e.limits?.max_completion_tokens??n?.max_tokens??4096}}async function h(e){let t=await fetch(`${o}/models`,{headers:{Authorization:`Bearer ${e}`}});if(!t.ok)throw Error(`GET /v1/models → ${t.status} ${t.statusText}`);let n=((await t.json()).data??[]).map(m).filter(e=>e.id.length>0);n.length>0&&(u=n,f(n))}function g(e,t){return{type:`error`,reason:`error`,error:{role:`assistant`,content:[],api:c,provider:a,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:`error`,errorMessage:t instanceof Error?t.message:String(t),timestamp:Date.now()}}}function _(e){console.error(`[cerebras] Stream error:`,e instanceof Error?e.message:String(e))}var v=(e,n,r={})=>{let i=t();return y(i,e,n,r).catch(_),i};async function y(e,t,n,i){try{let a={...t,baseUrl:o,api:s},c=r(a,n,i);for await(let t of c)e.push(t);e.end()}catch(n){_(n),e.push(g(t,n)),e.end()}}var b=(e,n,r)=>{let i=t();return x(i,e,n,r).catch(_),i};async function x(e,t,n,r){try{let a={...t,baseUrl:o,api:s},c=i(a,n,r);for await(let t of c)e.push(t);e.end()}catch(n){_(n),e.push(g(t,n)),e.end()}}var S={id:a,name:`Cerebras`,description:`Ultra-fast inference on Cerebras hardware. Get an API key at cloud.cerebras.ai.`,requiresApiKey:!0,requiresBaseUrl:!1,getModelIds:()=>{if(u.length>0)return u;let e=p();return e.length>0?e:d},refreshModels:async t=>{let n=t??e(a)??``;if(n)try{await h(n)}catch(e){console.warn(`[cerebras] Failed to refresh model list:`,e instanceof Error?e.message:String(e))}}};function C(){n({api:c,stream:v,streamSimple:b})}export{S as config,C as register};
1
+ import{_ as e}from"./account-store-6fYzIPsO.js";import{a as t}from"./diagnostics-DN_idNHx.js";import{d as n}from"./claude-model-version-CSATLzrT.js";import{r,s as i}from"./legacy-api-aliases-bAJ0Klzq.js";var a=`cerebras`,o=`https://api.cerebras.ai/v1`,s=`openai-completions`,c=`${a}-openai`,l=`slicc-cerebras-models`,u=[],d=[{id:`gpt-oss-120b`,name:`GPT OSS 120B`,api:`openai`,reasoning:!0,input:[`text`],context_window:131072,max_tokens:40960},{id:`gemma-4-31b`,name:`Gemma 4 31B`,api:`openai`,reasoning:!1,input:[`text`,`image`],context_window:131072,max_tokens:40960},{id:`zai-glm-4.7`,name:`Z.AI GLM-4.7`,api:`openai`,reasoning:!1,input:[`text`],context_window:131072,max_tokens:40960}];function f(e){try{localStorage.setItem(l,JSON.stringify(e))}catch{}}function p(){try{let e=localStorage.getItem(l);if(!e)return[];let t=JSON.parse(e);return Array.isArray(t)&&t.length>0?t:[]}catch{return[]}}function m(e){let t=e.id??``,n=d.find(e=>e.id===t);return{id:t,name:e.name??n?.name??t,api:`openai`,reasoning:e.capabilities?.reasoning??n?.reasoning??!1,input:e.capabilities?.vision?[`text`,`image`]:n?.input??[`text`],context_window:e.limits?.max_context_length??n?.context_window??8192,max_tokens:e.limits?.max_completion_tokens??n?.max_tokens??4096}}async function h(e){let t=await fetch(`${o}/models`,{headers:{Authorization:`Bearer ${e}`}});if(!t.ok)throw Error(`GET /v1/models → ${t.status} ${t.statusText}`);let n=((await t.json()).data??[]).map(m).filter(e=>e.id.length>0);n.length>0&&(u=n,f(n))}function g(e,t){return{type:`error`,reason:`error`,error:{role:`assistant`,content:[],api:c,provider:a,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:`error`,errorMessage:t instanceof Error?t.message:String(t),timestamp:Date.now()}}}function _(e){console.error(`[cerebras] Stream error:`,e instanceof Error?e.message:String(e))}var v=(e,n,r={})=>{let i=t();return y(i,e,n,r).catch(_),i};async function y(e,t,n,i){try{let a={...t,baseUrl:o,api:s},c=r(a,n,i);for await(let t of c)e.push(t);e.end()}catch(n){_(n),e.push(g(t,n)),e.end()}}var b=(e,n,r)=>{let i=t();return x(i,e,n,r).catch(_),i};async function x(e,t,n,r){try{let a={...t,baseUrl:o,api:s},c=i(a,n,r);for await(let t of c)e.push(t);e.end()}catch(n){_(n),e.push(g(t,n)),e.end()}}var S={id:a,name:`Cerebras`,description:`Ultra-fast inference on Cerebras hardware. Get an API key at cloud.cerebras.ai.`,requiresApiKey:!0,requiresBaseUrl:!1,getModelIds:()=>{if(u.length>0)return u;let e=p();return e.length>0?e:d},refreshModels:async t=>{let n=t??e(a)??``;if(n)try{await h(n)}catch(e){console.warn(`[cerebras] Failed to refresh model list:`,e instanceof Error?e.message:String(e))}}};function C(){n({api:c,stream:v,streamSimple:b})}export{S as config,C as register};
@@ -1 +1 @@
1
- import{a as e}from"./account-store-BRUCr96D.js";import{a as t}from"./diagnostics-DN_idNHx.js";import{a as n}from"./compat-uEPf6-XW.js";import{r,s as i}from"./legacy-api-aliases-jKEvBgOL.js";const a=`cerebras`,o=`https://api.cerebras.ai/v1`,s=`openai-completions`,c=`${a}-openai`,l=`slicc-cerebras-models`;let u=[];const d=[{id:`gpt-oss-120b`,name:`GPT OSS 120B`,api:`openai`,reasoning:!0,input:[`text`],context_window:131072,max_tokens:40960},{id:`gemma-4-31b`,name:`Gemma 4 31B`,api:`openai`,reasoning:!1,input:[`text`,`image`],context_window:131072,max_tokens:40960},{id:`zai-glm-4.7`,name:`Z.AI GLM-4.7`,api:`openai`,reasoning:!1,input:[`text`],context_window:131072,max_tokens:40960}];function f(e){try{localStorage.setItem(l,JSON.stringify(e))}catch{}}function p(){try{let e=localStorage.getItem(l);if(!e)return[];let t=JSON.parse(e);return Array.isArray(t)&&t.length>0?t:[]}catch{return[]}}function m(e){let t=e.id??``,n=d.find(e=>e.id===t);return{id:t,name:e.name??n?.name??t,api:`openai`,reasoning:e.capabilities?.reasoning??n?.reasoning??!1,input:e.capabilities?.vision?[`text`,`image`]:n?.input??[`text`],context_window:e.limits?.max_context_length??n?.context_window??8192,max_tokens:e.limits?.max_completion_tokens??n?.max_tokens??4096}}async function h(e){let t=await fetch(`${o}/models`,{headers:{Authorization:`Bearer ${e}`}});if(!t.ok)throw Error(`GET /v1/models → ${t.status} ${t.statusText}`);let n=((await t.json()).data??[]).map(m).filter(e=>e.id.length>0);n.length>0&&(u=n,f(n))}function g(e,t){return{type:`error`,reason:`error`,error:{role:`assistant`,content:[],api:c,provider:a,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:`error`,errorMessage:t instanceof Error?t.message:String(t),timestamp:Date.now()}}}function _(e){console.error(`[cerebras] Stream error:`,e instanceof Error?e.message:String(e))}const v=(e,n,r={})=>{let i=t();return y(i,e,n,r).catch(_),i};async function y(e,t,n,i){try{let a={...t,baseUrl:o,api:s},c=r(a,n,i);for await(let t of c)e.push(t);e.end()}catch(n){_(n),e.push(g(t,n)),e.end()}}const b=(e,n,r)=>{let i=t();return x(i,e,n,r).catch(_),i};async function x(e,t,n,r){try{let a={...t,baseUrl:o,api:s},c=i(a,n,r);for await(let t of c)e.push(t);e.end()}catch(n){_(n),e.push(g(t,n)),e.end()}}const S={id:a,name:`Cerebras`,description:`Ultra-fast inference on Cerebras hardware. Get an API key at cloud.cerebras.ai.`,requiresApiKey:!0,requiresBaseUrl:!1,getModelIds:()=>{if(u.length>0)return u;let e=p();return e.length>0?e:d},refreshModels:async t=>{let n=t??e(a)??``;if(n)try{await h(n)}catch(e){console.warn(`[cerebras] Failed to refresh model list:`,e instanceof Error?e.message:String(e))}}};function C(){n({api:c,stream:v,streamSimple:b})}export{S as config,C as register};
1
+ import{a as e}from"./account-store-DSBPuJN7.js";import{a as t}from"./diagnostics-DN_idNHx.js";import{a as n}from"./compat-uEPf6-XW.js";import{r,s as i}from"./legacy-api-aliases-jKEvBgOL.js";const a=`cerebras`,o=`https://api.cerebras.ai/v1`,s=`openai-completions`,c=`${a}-openai`,l=`slicc-cerebras-models`;let u=[];const d=[{id:`gpt-oss-120b`,name:`GPT OSS 120B`,api:`openai`,reasoning:!0,input:[`text`],context_window:131072,max_tokens:40960},{id:`gemma-4-31b`,name:`Gemma 4 31B`,api:`openai`,reasoning:!1,input:[`text`,`image`],context_window:131072,max_tokens:40960},{id:`zai-glm-4.7`,name:`Z.AI GLM-4.7`,api:`openai`,reasoning:!1,input:[`text`],context_window:131072,max_tokens:40960}];function f(e){try{localStorage.setItem(l,JSON.stringify(e))}catch{}}function p(){try{let e=localStorage.getItem(l);if(!e)return[];let t=JSON.parse(e);return Array.isArray(t)&&t.length>0?t:[]}catch{return[]}}function m(e){let t=e.id??``,n=d.find(e=>e.id===t);return{id:t,name:e.name??n?.name??t,api:`openai`,reasoning:e.capabilities?.reasoning??n?.reasoning??!1,input:e.capabilities?.vision?[`text`,`image`]:n?.input??[`text`],context_window:e.limits?.max_context_length??n?.context_window??8192,max_tokens:e.limits?.max_completion_tokens??n?.max_tokens??4096}}async function h(e){let t=await fetch(`${o}/models`,{headers:{Authorization:`Bearer ${e}`}});if(!t.ok)throw Error(`GET /v1/models → ${t.status} ${t.statusText}`);let n=((await t.json()).data??[]).map(m).filter(e=>e.id.length>0);n.length>0&&(u=n,f(n))}function g(e,t){return{type:`error`,reason:`error`,error:{role:`assistant`,content:[],api:c,provider:a,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:`error`,errorMessage:t instanceof Error?t.message:String(t),timestamp:Date.now()}}}function _(e){console.error(`[cerebras] Stream error:`,e instanceof Error?e.message:String(e))}const v=(e,n,r={})=>{let i=t();return y(i,e,n,r).catch(_),i};async function y(e,t,n,i){try{let a={...t,baseUrl:o,api:s},c=r(a,n,i);for await(let t of c)e.push(t);e.end()}catch(n){_(n),e.push(g(t,n)),e.end()}}const b=(e,n,r)=>{let i=t();return x(i,e,n,r).catch(_),i};async function x(e,t,n,r){try{let a={...t,baseUrl:o,api:s},c=i(a,n,r);for await(let t of c)e.push(t);e.end()}catch(n){_(n),e.push(g(t,n)),e.end()}}const S={id:a,name:`Cerebras`,description:`Ultra-fast inference on Cerebras hardware. Get an API key at cloud.cerebras.ai.`,requiresApiKey:!0,requiresBaseUrl:!1,getModelIds:()=>{if(u.length>0)return u;let e=p();return e.length>0?e:d},refreshModels:async t=>{let n=t??e(a)??``;if(n)try{await h(n)}catch(e){console.warn(`[cerebras] Failed to refresh model list:`,e instanceof Error?e.message:String(e))}}};function C(){n({api:c,stream:v,streamSimple:b})}export{S as config,C as register};
@@ -1 +1 @@
1
- import{t as e}from"./logger-DDBAeTLF.js";import{q as t}from"./wc-shortcuts-_REWQgA9.js";import{n}from"./runtime-env-Dlaokqg1.js";import{t as r}from"./permissions-surface-registry-CilCRwhh.js";import{t as i}from"./speech-assets-bridge-CFYafE89.js";import{o as a}from"./transformers-env-CAqo4XNv.js";import{i as o,t as s}from"./whisper-session-B1zyLwlp.js";var c=e(`speech:composer`),l=5e3,u=(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)})}),d=class{#e;#t;#n;#r;#i;#a=null;#o=!1;#s={engine:`builtin`,state:`idle`};#c=a();#l=new Set;#u=null;constructor(e={}){this.#e=e.builtin??t(),this.#t=e.loadWhisper??o,this.#n=e.startSession??s,this.#r=e.getPermissionSurface??f,this.#i=e.ensureAssets??v}permission(){return this.#e.permission()}async requestPermission(){let e=this.#r();if(e)try{let t=await e.request(`microphone`);return t?(this.#p(t.stream),!0):!1}catch(e){return c.warn(`permission surface microphone request failed`,e),!1}return this.#e.requestPermission()}microphones(){return this.#e.microphones()}status(){return this.#s}onStatus(e){return this.#l.add(e),e(this.#s),()=>this.#l.delete(e)}warmup(){this.#o||(this.#o=!0,this.#c=a(),this.#_({engine:`builtin`,state:`downloading`}),this.#d().then(e=>{this.#a=e,this.#_({engine:`enhanced`,state:`ready`})},e=>{this.#o=!1,this.#_({engine:`builtin`,state:`unavailable`,message:m(e)}),c.warn(`enhanced speech engine unavailable`,e)}))}async#d(){let e=null;try{await this.#i(e=>this.#h(e))}catch(t){e=t,c.warn(`speech asset staging failed; trying already-present assets`,t)}try{return await this.#t(e=>this.#g(e))}catch(t){throw e??t}}async start(e){let t=this.#a;if(t){let n=null;try{return n=await this.#f(e.deviceId),await this.#n(t,{deviceId:e.deviceId,lang:e.lang,onPartial:e.onPartial,onError:e.onError,stream:n??void 0})}catch(e){if(n)for(let e of n.getTracks())e.stop();c.warn(`whisper session failed to start; falling back to builtin`,e)}}return this.#e.start(e)}async#f(e){let t=e&&e!=="default"?e:void 0,n=this.#m();if(n){if(!t&&p(n))return n;for(let e of n.getTracks())e.stop()}let r=this.#r();if(!r)return null;let i={audio:!t||{deviceId:{exact:t}}},a=await u(r.request(`microphone`,{constraints:i}),l,`microphone capture`);if(!a)throw Error(`microphone permission denied`);return a.stream}#p(e){if(this.#u&&this.#u!==e)for(let e of this.#u.getTracks())e.stop();this.#u=e}#m(){let e=this.#u;return this.#u=null,e}get enhancedReady(){return this.#a!==null}#h(e){if(this.#s.state!==`downloading`)return;(e.bytesTotal!=null||e.bytesLoaded!=null)&&this.#c.update(e.asset,e.bytesLoaded??0,e.bytesTotal??0);let t=this.#c.snapshot();t.total<=0||this.#_({engine:`builtin`,state:`downloading`,download:{loaded:t.loaded,total:t.total,etaSeconds:t.etaSeconds}})}#g(e){this.#s.state===`downloading`&&this.#_({engine:`builtin`,state:`downloading`,download:{loaded:e.loaded,total:e.total,etaSeconds:e.etaSeconds}})}#_(e){this.#s=e;for(let t of this.#l)t(e)}};function f(){let e=r();return e?{async request(t,n){let r=await e.request(t,n);return r?.kind===`microphone`?{kind:`microphone`,stream:r.stream}:null}}:null}function p(e){let t=e.getTracks();return t.length>0&&t.some(e=>e.readyState!==`ended`)}function m(e){return`Enhanced speech unavailable: ${e instanceof Error?e.message:String(e)}`}var h=n,g;function _(e){g=e}function v(e){return h()?Promise.resolve():i({instanceId:g,onProgress:e})}var y=null;function b(){return y??=new d,y}export{b as getComposerSpeech,_ as setComposerSpeechInstanceId};
1
+ import{t as e}from"./logger-DDBAeTLF.js";import{q as t}from"./wc-shortcuts-8X2r2czL.js";import{n}from"./runtime-env-Dlaokqg1.js";import{t as r}from"./permissions-surface-registry-CilCRwhh.js";import{t as i}from"./speech-assets-bridge-CFYafE89.js";import{o as a}from"./transformers-env-tgTHZJKu.js";import{i as o,t as s}from"./whisper-session-iQYr-1HE.js";var c=e(`speech:composer`),l=5e3,u=(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)})}),d=class{#e;#t;#n;#r;#i;#a=null;#o=!1;#s={engine:`builtin`,state:`idle`};#c=a();#l=new Set;#u=null;constructor(e={}){this.#e=e.builtin??t(),this.#t=e.loadWhisper??o,this.#n=e.startSession??s,this.#r=e.getPermissionSurface??f,this.#i=e.ensureAssets??v}permission(){return this.#e.permission()}async requestPermission(){let e=this.#r();if(e)try{let t=await e.request(`microphone`);return t?(this.#p(t.stream),!0):!1}catch(e){return c.warn(`permission surface microphone request failed`,e),!1}return this.#e.requestPermission()}microphones(){return this.#e.microphones()}status(){return this.#s}onStatus(e){return this.#l.add(e),e(this.#s),()=>this.#l.delete(e)}warmup(){this.#o||(this.#o=!0,this.#c=a(),this.#_({engine:`builtin`,state:`downloading`}),this.#d().then(e=>{this.#a=e,this.#_({engine:`enhanced`,state:`ready`})},e=>{this.#o=!1,this.#_({engine:`builtin`,state:`unavailable`,message:m(e)}),c.warn(`enhanced speech engine unavailable`,e)}))}async#d(){let e=null;try{await this.#i(e=>this.#h(e))}catch(t){e=t,c.warn(`speech asset staging failed; trying already-present assets`,t)}try{return await this.#t(e=>this.#g(e))}catch(t){throw e??t}}async start(e){let t=this.#a;if(t){let n=null;try{return n=await this.#f(e.deviceId),await this.#n(t,{deviceId:e.deviceId,lang:e.lang,onPartial:e.onPartial,onError:e.onError,stream:n??void 0})}catch(e){if(n)for(let e of n.getTracks())e.stop();c.warn(`whisper session failed to start; falling back to builtin`,e)}}return this.#e.start(e)}async#f(e){let t=e&&e!=="default"?e:void 0,n=this.#m();if(n){if(!t&&p(n))return n;for(let e of n.getTracks())e.stop()}let r=this.#r();if(!r)return null;let i={audio:!t||{deviceId:{exact:t}}},a=await u(r.request(`microphone`,{constraints:i}),l,`microphone capture`);if(!a)throw Error(`microphone permission denied`);return a.stream}#p(e){if(this.#u&&this.#u!==e)for(let e of this.#u.getTracks())e.stop();this.#u=e}#m(){let e=this.#u;return this.#u=null,e}get enhancedReady(){return this.#a!==null}#h(e){if(this.#s.state!==`downloading`)return;(e.bytesTotal!=null||e.bytesLoaded!=null)&&this.#c.update(e.asset,e.bytesLoaded??0,e.bytesTotal??0);let t=this.#c.snapshot();t.total<=0||this.#_({engine:`builtin`,state:`downloading`,download:{loaded:t.loaded,total:t.total,etaSeconds:t.etaSeconds}})}#g(e){this.#s.state===`downloading`&&this.#_({engine:`builtin`,state:`downloading`,download:{loaded:e.loaded,total:e.total,etaSeconds:e.etaSeconds}})}#_(e){this.#s=e;for(let t of this.#l)t(e)}};function f(){let e=r();return e?{async request(t,n){let r=await e.request(t,n);return r?.kind===`microphone`?{kind:`microphone`,stream:r.stream}:null}}:null}function p(e){let t=e.getTracks();return t.length>0&&t.some(e=>e.readyState!==`ended`)}function m(e){return`Enhanced speech unavailable: ${e instanceof Error?e.message:String(e)}`}var h=n,g;function _(e){g=e}function v(e){return h()?Promise.resolve():i({instanceId:g,onProgress:e})}var y=null;function b(){return y??=new d,y}export{b as getComposerSpeech,_ as setComposerSpeechInstanceId};
@@ -1,4 +1,4 @@
1
- import{T as e,f as t,p as n,z as r}from"./account-store-BSBnFFPS.js";import{n as i}from"./main-w_xCet4j.js";var a=`slicc_cloud_model_catalog`,o=`adobe`;function s(t){if(t===o)return!1;let n=e(t);return!(n.hidden||n.onOAuthLoginIntercepted)}function c(){try{let e=n().map(e=>({providerId:e.providerId,providerName:e.providerName,models:e.models.map(e=>({id:e.id,name:e.name}))}));localStorage.setItem(a,JSON.stringify(e))}catch{}}async function l(n){for(;n.firstChild;)n.removeChild(n.firstChild);n.className=`connect-surface`;let a=document.createElement(`h1`);a.className=`connect-surface__title`,a.textContent=`Connect providers`,n.appendChild(a);let l=document.createElement(`p`);l.className=`connect-surface__desc`,l.textContent=`Log in or add API keys for the providers your cone should use, then click Done to return to the dashboard.`,n.appendChild(l);let u=document.createElement(`div`);u.className=`connect-surface__accounts`,n.appendChild(u);function d(){for(;u.firstChild;)u.removeChild(u.firstChild);let n=t().filter(e=>e.providerId!==o);if(n.length===0){let e=document.createElement(`div`);e.className=`connect-surface__empty`,e.textContent=`No providers connected yet.`,u.appendChild(e)}else{let t=document.createElement(`div`);t.className=`connect-surface__accounts-list`;for(let i of n){let n=e(i.providerId),a=document.createElement(`div`);a.className=`connect-surface__account-row`;let o=document.createElement(`div`);o.className=`connect-surface__account-info`;let s=document.createElement(`div`);s.className=`connect-surface__account-name`,s.textContent=n.name,o.appendChild(s);let l=document.createElement(`div`);l.className=`connect-surface__account-detail`,l.textContent=i.userName?i.userName:i.accessToken?`Logged in`:i.apiKey?`API key set`:`No credentials`,o.appendChild(l),a.appendChild(o);let u=document.createElement(`button`);u.className=`connect-surface__remove-btn`,u.textContent=`Remove`,u.onclick=async()=>{await r(i.providerId),c(),d()},a.appendChild(u),t.appendChild(a)}u.appendChild(t)}let a=document.createElement(`button`);a.className=`connect-surface__add-btn`,a.textContent=n.length===0?`Add provider`:`Manage providers`,a.onclick=async()=>{await i({startInAddAccount:!0,providerFilter:s})&&(c(),d())},u.appendChild(a)}d(),c();let f=document.createElement(`div`);f.className=`connect-surface__footer`;let p=document.createElement(`button`);if(p.className=`connect-surface__done-btn`,p.textContent=`Done — return to dashboard`,p.onclick=()=>{c(),window.close()},f.appendChild(p),n.appendChild(f),!document.getElementById(`connect-surface-style`)){let e=document.createElement(`style`);e.id=`connect-surface-style`,e.textContent=`
1
+ import{T as e,f as t,p as n,z as r}from"./account-store-6fYzIPsO.js";import{n as i}from"./main-h_6bHCyA.js";var a=`slicc_cloud_model_catalog`,o=`adobe`;function s(t){if(t===o)return!1;let n=e(t);return!(n.hidden||n.onOAuthLoginIntercepted)}function c(){try{let e=n().map(e=>({providerId:e.providerId,providerName:e.providerName,models:e.models.map(e=>({id:e.id,name:e.name}))}));localStorage.setItem(a,JSON.stringify(e))}catch{}}async function l(n){for(;n.firstChild;)n.removeChild(n.firstChild);n.className=`connect-surface`;let a=document.createElement(`h1`);a.className=`connect-surface__title`,a.textContent=`Connect providers`,n.appendChild(a);let l=document.createElement(`p`);l.className=`connect-surface__desc`,l.textContent=`Log in or add API keys for the providers your cone should use, then click Done to return to the dashboard.`,n.appendChild(l);let u=document.createElement(`div`);u.className=`connect-surface__accounts`,n.appendChild(u);function d(){for(;u.firstChild;)u.removeChild(u.firstChild);let n=t().filter(e=>e.providerId!==o);if(n.length===0){let e=document.createElement(`div`);e.className=`connect-surface__empty`,e.textContent=`No providers connected yet.`,u.appendChild(e)}else{let t=document.createElement(`div`);t.className=`connect-surface__accounts-list`;for(let i of n){let n=e(i.providerId),a=document.createElement(`div`);a.className=`connect-surface__account-row`;let o=document.createElement(`div`);o.className=`connect-surface__account-info`;let s=document.createElement(`div`);s.className=`connect-surface__account-name`,s.textContent=n.name,o.appendChild(s);let l=document.createElement(`div`);l.className=`connect-surface__account-detail`,l.textContent=i.userName?i.userName:i.accessToken?`Logged in`:i.apiKey?`API key set`:`No credentials`,o.appendChild(l),a.appendChild(o);let u=document.createElement(`button`);u.className=`connect-surface__remove-btn`,u.textContent=`Remove`,u.onclick=async()=>{await r(i.providerId),c(),d()},a.appendChild(u),t.appendChild(a)}u.appendChild(t)}let a=document.createElement(`button`);a.className=`connect-surface__add-btn`,a.textContent=n.length===0?`Add provider`:`Manage providers`,a.onclick=async()=>{await i({startInAddAccount:!0,providerFilter:s})&&(c(),d())},u.appendChild(a)}d(),c();let f=document.createElement(`div`);f.className=`connect-surface__footer`;let p=document.createElement(`button`);if(p.className=`connect-surface__done-btn`,p.textContent=`Done — return to dashboard`,p.onclick=()=>{c(),window.close()},f.appendChild(p),n.appendChild(f),!document.getElementById(`connect-surface-style`)){let e=document.createElement(`style`);e.id=`connect-surface-style`,e.textContent=`
2
2
  .connect-surface {
3
3
  padding: 2rem;
4
4
  max-width: 560px;
@@ -1 +1 @@
1
- import{t as e}from"./logger-LESFN7Hj.js";import{t}from"./agent-bridge-DslQDtty.js";import{S as n}from"./record-YqlVEfh_.js";const r=e(`directed-approval`);function i(e,t){if(e.kind===`user`)return a(`the user tier is not a directed approval`);if(e.kind===`agent`)return a(`agent approvals are not enqueued to a unit`);let r=e.unitJid;if(!t.scoops.has(r))return a(`the requesting unit is not registered`);let i=t.ownerRootOf(r);if(!i)return a(`no owning cone for the requesting unit`);let o=e.kind===`cone`?i:[...t.scoops.values()].find(t=>t.parentJid===i.jid&&(t.name===e.scoopName||t.folder===e.scoopName));return o?n(o).canResolveApprovals?{ok:!0,requesterJid:r,approver:o}:a(`the named approver cannot resolve approvals`):a(`delegated approver not found under this cone`)}function a(e){return r.warn(`Directed approval failing closed`,{reason:e}),{ok:!1,reason:e}}const o={decision:`deny`};async function s(e,n){let a=e.approver;if(a?.kind===`agent`){let i=globalThis[t];if(!i)return r.warn(`No agent bridge available for an approver agent — denying`),o;let{approverRunnerFor:s}=await import(`./approver-agent-O_C8F_lu.js`),c=n.getSharedFs(),l=await s({spawn:e=>i.spawn(e),readSharedFile:async e=>{if(!c)return null;try{let t=await c.readFile(e,{encoding:`utf-8`});return typeof t==`string`?t:null}catch{return null}},findUnit:e=>{let t=n.scoops.get(e);return t?{workspace:n.workspaceFor(t),folder:t.folder}:void 0}})({kind:e.kind===`guest-tool`?`guest-tool`:`guest-message`,requester:e.requester??`an unidentified requester`,detail:e.detail},a.unitJid);return r.info(`Approver agent verdict`,{decision:l.decision,reason:l.reason}),l.decision===`allow`?{decision:`allow`}:o}if(a&&a.kind!==`user`){let t=i(a,n);return t.ok?n.enqueue(t.requesterJid,e,{approver:t.approver}):o}return n.approveAsUser(e)}export{s as runDirectedApproval};
1
+ import{t as e}from"./logger-LESFN7Hj.js";import{t}from"./agent-bridge-9apk6tdC.js";import{S as n}from"./record-YqlVEfh_.js";const r=e(`directed-approval`);function i(e,t){if(e.kind===`user`)return a(`the user tier is not a directed approval`);if(e.kind===`agent`)return a(`agent approvals are not enqueued to a unit`);let r=e.unitJid;if(!t.scoops.has(r))return a(`the requesting unit is not registered`);let i=t.ownerRootOf(r);if(!i)return a(`no owning cone for the requesting unit`);let o=e.kind===`cone`?i:[...t.scoops.values()].find(t=>t.parentJid===i.jid&&(t.name===e.scoopName||t.folder===e.scoopName));return o?n(o).canResolveApprovals?{ok:!0,requesterJid:r,approver:o}:a(`the named approver cannot resolve approvals`):a(`delegated approver not found under this cone`)}function a(e){return r.warn(`Directed approval failing closed`,{reason:e}),{ok:!1,reason:e}}const o={decision:`deny`};async function s(e,n){let a=e.approver;if(a?.kind===`agent`){let i=globalThis[t];if(!i)return r.warn(`No agent bridge available for an approver agent — denying`),o;let{approverRunnerFor:s}=await import(`./approver-agent-O_C8F_lu.js`),c=n.getSharedFs(),l=await s({spawn:e=>i.spawn(e),readSharedFile:async e=>{if(!c)return null;try{let t=await c.readFile(e,{encoding:`utf-8`});return typeof t==`string`?t:null}catch{return null}},findUnit:e=>{let t=n.scoops.get(e);return t?{workspace:n.workspaceFor(t),folder:t.folder}:void 0}})({kind:e.kind===`guest-tool`?`guest-tool`:`guest-message`,requester:e.requester??`an unidentified requester`,detail:e.detail},a.unitJid);return r.info(`Approver agent verdict`,{decision:l.decision,reason:l.reason}),l.decision===`allow`?{decision:`allow`}:o}if(a&&a.kind!==`user`){let t=i(a,n);return t.ok?n.enqueue(t.requesterJid,e,{approver:t.approver}):o}return n.approveAsUser(e)}export{s as runDirectedApproval};
@@ -0,0 +1 @@
1
+ const e=`KEYS`,t=`VALUES`;var n=class{constructor(e,t){let n=e._tree,r=Array.from(n.keys());this.set=e,this._type=t,this._path=r.length>0?[{node:n,keys:r}]:[]}next(){let e=this.dive();return this.backtrack(),e}dive(){if(this._path.length===0)return{done:!0,value:void 0};let{node:e,keys:t}=r(this._path);if(r(t)===``)return{done:!1,value:this.result()};let n=e.get(r(t));return this._path.push({node:n,keys:Array.from(n.keys())}),this.dive()}backtrack(){if(this._path.length===0)return;let e=r(this._path).keys;e.pop(),!(e.length>0)&&(this._path.pop(),this.backtrack())}key(){return this.set._prefix+this._path.map(({keys:e})=>r(e)).filter(e=>e!==``).join(``)}value(){return r(this._path).node.get(``)}result(){switch(this._type){case t:return this.value();case e:return this.key();default:return[this.key(),this.value()]}}[Symbol.iterator](){return this}};const r=e=>e[e.length-1],i=(e,t,n)=>{let r=new Map;if(t===void 0)return r;let i=t.length+1,o=i+n,s=new Uint8Array(o*i).fill(n+1);for(let e=0;e<i;++e)s[e]=e;for(let e=1;e<o;++e)s[e*i]=e;return a(e,t,n,r,s,1,i,``),r},a=(e,t,n,r,i,o,s,c)=>{let l=o*s;key:for(let u of e.keys())if(u===``){let t=i[l-1];t<=n&&r.set(c,[e.get(u),t])}else{let l=o;for(let e=0;e<u.length;++e,++l){let r=u[e],a=s*l,o=a-s,c=i[a],d=Math.max(0,l-n-1),f=Math.min(s-1,l+n);for(let e=d;e<f;++e){let n=r!==t[e],s=i[o+e]+ +n,l=i[o+e+1]+1,u=i[a+e]+1,d=i[a+e+1]=Math.min(s,l,u);d<c&&(c=d)}if(c>n)continue key}a(e.get(u),t,n,r,i,l,s,c+u)}};var o=class r{constructor(e=new Map,t=``){this._size=void 0,this._tree=e,this._prefix=t}atPrefix(e){if(!e.startsWith(this._prefix))throw Error(`Mismatched prefix`);let[t,n]=s(this._tree,e.slice(this._prefix.length));if(t===void 0){let[t,i]=p(n);for(let n of t.keys())if(n!==``&&n.startsWith(i)){let a=new Map;return a.set(n.slice(i.length),t.get(n)),new r(a,e)}}return new r(t,e)}clear(){this._size=void 0,this._tree.clear()}delete(e){return this._size=void 0,u(this._tree,e)}entries(){return new n(this,`ENTRIES`)}forEach(e){for(let[t,n]of this)e(t,n,this)}fuzzyGet(e,t){return i(this._tree,e,t)}get(e){let t=c(this._tree,e);return t===void 0?void 0:t.get(``)}has(e){let t=c(this._tree,e);return t!==void 0&&t.has(``)}keys(){return new n(this,e)}set(e,t){if(typeof e!=`string`)throw Error(`key must be a string`);return this._size=void 0,l(this._tree,e).set(``,t),this}get size(){if(this._size)return this._size;this._size=0;let e=this.entries();for(;!e.next().done;)this._size+=1;return this._size}update(e,t){if(typeof e!=`string`)throw Error(`key must be a string`);this._size=void 0;let n=l(this._tree,e);return n.set(``,t(n.get(``))),this}fetch(e,t){if(typeof e!=`string`)throw Error(`key must be a string`);this._size=void 0;let n=l(this._tree,e),r=n.get(``);return r===void 0&&n.set(``,r=t()),r}values(){return new n(this,t)}[Symbol.iterator](){return this.entries()}static from(e){let t=new r;for(let[n,r]of e)t.set(n,r);return t}static fromObject(e){return r.from(Object.entries(e))}};const s=(e,t,n=[])=>{if(t.length===0||e==null)return[e,n];for(let r of e.keys())if(r!==``&&t.startsWith(r))return n.push([e,r]),s(e.get(r),t.slice(r.length),n);return n.push([e,t]),s(void 0,``,n)},c=(e,t)=>{if(t.length===0||e==null)return e;for(let n of e.keys())if(n!==``&&t.startsWith(n))return c(e.get(n),t.slice(n.length))},l=(e,t)=>{let n=t.length;outer:for(let r=0;e&&r<n;){for(let i of e.keys())if(i!==``&&t[r]===i[0]){let a=Math.min(n-r,i.length),o=1;for(;o<a&&t[r+o]===i[o];)++o;let s=e.get(i);if(o===i.length)e=s;else{let n=new Map;n.set(i.slice(o),s),e.set(t.slice(r,r+o),n),e.delete(i),e=n}r+=o;continue outer}let i=new Map;return e.set(t.slice(r),i),i}return e},u=(e,t)=>{let[n,r]=s(e,t);if(n!==void 0){if(n.delete(``),n.size===0)d(r);else if(n.size===1){let[e,t]=n.entries().next().value;f(r,e,t)}}},d=e=>{if(e.length===0)return;let[t,n]=p(e);if(t.delete(n),t.size===0)d(e.slice(0,-1));else if(t.size===1){let[n,r]=t.entries().next().value;n!==``&&f(e.slice(0,-1),n,r)}},f=(e,t,n)=>{if(e.length===0)return;let[r,i]=p(e);r.set(i+t,n),r.delete(i)},p=e=>e[e.length-1];var m=class e{constructor(e){if(e?.fields==null)throw Error(`MiniSearch: option "fields" must be provided`);let t=e.autoVacuum==null||e.autoVacuum===!0?T:e.autoVacuum;this._options={...b,...e,autoVacuum:t,searchOptions:{...x,...e.searchOptions||{}},autoSuggestOptions:{...S,...e.autoSuggestOptions||{}}},this._index=new o,this._documentCount=0,this._documentIds=new Map,this._idToShortId=new Map,this._fieldIds={},this._fieldLength=new Map,this._avgFieldLength=[],this._nextId=0,this._storedFields=new Map,this._dirtCount=0,this._currentVacuum=null,this._enqueuedVacuum=null,this._enqueuedVacuumConditions=w,this.addFields(this._options.fields)}add(e){let{extractField:t,stringifyField:n,tokenize:r,processTerm:i,fields:a,idField:o}=this._options,s=t(e,o);if(s==null)throw Error(`MiniSearch: document does not have ID field "${o}"`);if(this._idToShortId.has(s))throw Error(`MiniSearch: duplicate ID ${s}`);let c=this.addDocumentId(s);this.saveStoredFields(c,e);for(let o of a){let a=t(e,o);if(a==null)continue;let s=r(n(a,o),o),l=this._fieldIds[o],u=new Set(s).size;this.addFieldLength(c,l,this._documentCount-1,u);for(let e of s){let t=i(e,o);if(Array.isArray(t))for(let e of t)this.addTerm(l,c,e);else t&&this.addTerm(l,c,t)}}}addAll(e){for(let t of e)this.add(t)}addAllAsync(e,t={}){let{chunkSize:n=10}=t,r={chunk:[],promise:Promise.resolve()},{chunk:i,promise:a}=e.reduce(({chunk:e,promise:t},r,i)=>(e.push(r),(i+1)%n===0?{chunk:[],promise:t.then(()=>new Promise(e=>setTimeout(e,0))).then(()=>this.addAll(e))}:{chunk:e,promise:t}),r);return a.then(()=>this.addAll(i))}remove(e){let{tokenize:t,processTerm:n,extractField:r,stringifyField:i,fields:a,idField:o}=this._options,s=r(e,o);if(s==null)throw Error(`MiniSearch: document does not have ID field "${o}"`);let c=this._idToShortId.get(s);if(c==null)throw Error(`MiniSearch: cannot remove document with ID ${s}: it is not in the index`);for(let o of a){let a=r(e,o);if(a==null)continue;let s=t(i(a,o),o),l=this._fieldIds[o],u=new Set(s).size;this.removeFieldLength(c,l,this._documentCount,u);for(let e of s){let t=n(e,o);if(Array.isArray(t))for(let e of t)this.removeTerm(l,c,e);else t&&this.removeTerm(l,c,t)}}this._storedFields.delete(c),this._documentIds.delete(c),this._idToShortId.delete(s),this._fieldLength.delete(c),--this._documentCount}removeAll(e){if(e)for(let t of e)this.remove(t);else if(arguments.length>0)throw Error(`Expected documents to be present. Omit the argument to remove all documents.`);else this._index=new o,this._documentCount=0,this._documentIds=new Map,this._idToShortId=new Map,this._fieldLength=new Map,this._avgFieldLength=[],this._storedFields=new Map,this._nextId=0}discard(e){let t=this._idToShortId.get(e);if(t==null)throw Error(`MiniSearch: cannot discard document with ID ${e}: it is not in the index`);this._idToShortId.delete(e),this._documentIds.delete(t),this._storedFields.delete(t),(this._fieldLength.get(t)||[]).forEach((e,n)=>{this.removeFieldLength(t,n,this._documentCount,e)}),this._fieldLength.delete(t),--this._documentCount,this._dirtCount+=1,this.maybeAutoVacuum()}maybeAutoVacuum(){if(this._options.autoVacuum===!1)return;let{minDirtFactor:e,minDirtCount:t,batchSize:n,batchWait:r}=this._options.autoVacuum;this.conditionalVacuum({batchSize:n,batchWait:r},{minDirtCount:t,minDirtFactor:e})}discardAll(e){let t=this._options.autoVacuum;try{this._options.autoVacuum=!1;for(let t of e)this.discard(t)}finally{this._options.autoVacuum=t}this.maybeAutoVacuum()}replace(e){let{idField:t,extractField:n}=this._options,r=n(e,t);this.discard(r),this.add(e)}vacuum(e={}){return this.conditionalVacuum(e)}conditionalVacuum(e,t){return this._currentVacuum?(this._enqueuedVacuumConditions=this._enqueuedVacuumConditions&&t,this._enqueuedVacuum??=this._currentVacuum.then(()=>{let t=this._enqueuedVacuumConditions;return this._enqueuedVacuumConditions=w,this.performVacuuming(e,t)}),this._enqueuedVacuum):this.vacuumConditionsMet(t)===!1?Promise.resolve():(this._currentVacuum=this.performVacuuming(e),this._currentVacuum)}async performVacuuming(e,t){let n=this._dirtCount;if(this.vacuumConditionsMet(t)){let t=e.batchSize||C.batchSize,r=e.batchWait||C.batchWait,i=1;for(let[e,n]of this._index){for(let[e,t]of n)for(let[r]of t)this._documentIds.has(r)||(t.size<=1?n.delete(e):t.delete(r));this._index.get(e).size===0&&this._index.delete(e),i%t===0&&await new Promise(e=>setTimeout(e,r)),i+=1}this._dirtCount-=n}await null,this._currentVacuum=this._enqueuedVacuum,this._enqueuedVacuum=null}vacuumConditionsMet(e){if(e==null)return!0;let{minDirtCount:t,minDirtFactor:n}=e;return t||=T.minDirtCount,n||=T.minDirtFactor,this.dirtCount>=t&&this.dirtFactor>=n}get isVacuuming(){return this._currentVacuum!=null}get dirtCount(){return this._dirtCount}get dirtFactor(){return this._dirtCount/(1+this._documentCount+this._dirtCount)}has(e){return this._idToShortId.has(e)}getStoredFields(e){let t=this._idToShortId.get(e);if(t!=null)return this._storedFields.get(t)}search(t,n={}){let{searchOptions:r}=this._options,i={...r,...n},a=this.executeQuery(t,n),o=[];for(let[e,{score:t,terms:n,match:r}]of a){let a=n.length||1,s={id:this._documentIds.get(e),score:t*a,terms:Object.keys(r),queryTerms:n,match:r};Object.assign(s,this._storedFields.get(e)),(i.filter==null||i.filter(s))&&o.push(s)}return t===e.wildcard&&i.boostDocument==null||o.sort(O),o}autoSuggest(e,t={}){t={...this._options.autoSuggestOptions,...t};let n=new Map;for(let{score:r,terms:i}of this.search(e,t)){let e=i.join(` `),t=n.get(e);t==null?n.set(e,{score:r,terms:i,count:1}):(t.score+=r,t.count+=1)}let r=[];for(let[e,{score:t,terms:i,count:a}]of n)r.push({suggestion:e,terms:i,score:t/a});return r.sort(O),r}get documentCount(){return this._documentCount}get termCount(){return this._index.size}static loadJSON(e,t){if(t==null)throw Error(`MiniSearch: loadJSON should be given the same options used when serializing the index`);return this.loadJS(JSON.parse(e),t)}static async loadJSONAsync(e,t){if(t==null)throw Error(`MiniSearch: loadJSON should be given the same options used when serializing the index`);return this.loadJSAsync(JSON.parse(e),t)}static getDefault(e){if(b.hasOwnProperty(e))return h(b,e);throw Error(`MiniSearch: unknown option "${e}"`)}static loadJS(e,t){let{index:n,documentIds:r,fieldLength:i,storedFields:a,serializationVersion:o}=e,s=this.instantiateMiniSearch(e,t);s._documentIds=A(r),s._fieldLength=A(i),s._storedFields=A(a);for(let[e,t]of s._documentIds)s._idToShortId.set(t,e);for(let[e,t]of n){let n=new Map;for(let e of Object.keys(t)){let r=t[e];o===1&&(r=r.ds),n.set(parseInt(e,10),A(r))}s._index.set(e,n)}return s}static async loadJSAsync(e,t){let{index:n,documentIds:r,fieldLength:i,storedFields:a,serializationVersion:o}=e,s=this.instantiateMiniSearch(e,t);s._documentIds=await j(r),s._fieldLength=await j(i),s._storedFields=await j(a);for(let[e,t]of s._documentIds)s._idToShortId.set(t,e);let c=0;for(let[e,t]of n){let n=new Map;for(let e of Object.keys(t)){let r=t[e];o===1&&(r=r.ds),n.set(parseInt(e,10),await j(r))}++c%1e3==0&&await M(0),s._index.set(e,n)}return s}static instantiateMiniSearch(t,n){let{documentCount:r,nextId:i,fieldIds:a,averageFieldLength:s,dirtCount:c,serializationVersion:l}=t;if(l!==1&&l!==2)throw Error(`MiniSearch: cannot deserialize an index created with an incompatible version`);let u=new e(n);return u._documentCount=r,u._nextId=i,u._idToShortId=new Map,u._fieldIds=a,u._avgFieldLength=s,u._dirtCount=c||0,u._index=new o,u}executeQuery(t,n={}){if(t===e.wildcard)return this.executeWildcardQuery(n);if(typeof t!=`string`){let e={...n,...t,queries:void 0},r=t.queries.map(t=>this.executeQuery(t,e));return this.combineResults(r,e.combineWith)}let{tokenize:r,processTerm:i,searchOptions:a}=this._options,o={tokenize:r,processTerm:i,...a,...n},{tokenize:s,processTerm:c}=o,l=s(t).flatMap(e=>c(e)).filter(e=>!!e).map(y(o)).map(e=>this.executeQuerySpec(e,o));return this.combineResults(l,o.combineWith)}executeQuerySpec(e,t){let n={...this._options.searchOptions,...t},r=(n.fields||this._options.fields).reduce((e,t)=>({...e,[t]:h(n.boost,t)||1}),{}),{boostDocument:i,weights:a,maxFuzzy:o,bm25:s}=n,{fuzzy:c,prefix:l}={...x.weights,...a},u=this._index.get(e.term),d=this.termResults(e.term,e.term,1,e.termBoost,u,r,i,s),f,p;if(e.prefix&&(f=this._index.atPrefix(e.term)),e.fuzzy){let t=e.fuzzy===!0?.2:e.fuzzy,n=t<1?Math.min(o,Math.round(e.term.length*t)):t;n&&(p=this._index.fuzzyGet(e.term,n))}if(f)for(let[t,n]of f){let a=t.length-e.term.length;if(!a)continue;p?.delete(t);let o=l*t.length/(t.length+.3*a);this.termResults(e.term,t,o,e.termBoost,n,r,i,s,d)}if(p)for(let t of p.keys()){let[n,a]=p.get(t);if(!a)continue;let o=c*t.length/(t.length+a);this.termResults(e.term,t,o,e.termBoost,n,r,i,s,d)}return d}executeWildcardQuery(e){let t=new Map,n={...this._options.searchOptions,...e};for(let[e,r]of this._documentIds){let i=n.boostDocument?n.boostDocument(r,``,this._storedFields.get(e)):1;t.set(e,{score:i,terms:[],match:{}})}return t}combineResults(e,t=`or`){if(e.length===0)return new Map;let n=t.toLowerCase(),r=g[n];if(!r)throw Error(`Invalid combination operator: ${t}`);return e.reduce(r)||new Map}toJSON(){let e=[];for(let[t,n]of this._index){let r={};for(let[e,t]of n)r[e]=Object.fromEntries(t);e.push([t,r])}return{documentCount:this._documentCount,nextId:this._nextId,documentIds:Object.fromEntries(this._documentIds),fieldIds:this._fieldIds,fieldLength:Object.fromEntries(this._fieldLength),averageFieldLength:this._avgFieldLength,storedFields:Object.fromEntries(this._storedFields),dirtCount:this._dirtCount,index:e,serializationVersion:2}}termResults(e,t,n,r,i,a,o,s,c=new Map){if(i==null)return c;for(let l of Object.keys(a)){let u=a[l],d=this._fieldIds[l],f=i.get(d);if(f==null)continue;let p=f.size,m=this._avgFieldLength[d];for(let i of f.keys()){if(!this._documentIds.has(i)){this.removeTerm(d,i,t),--p;continue}let a=o?o(this._documentIds.get(i),t,this._storedFields.get(i)):1;if(!a)continue;let g=f.get(i),_=this._fieldLength.get(i)[d],y=v(g,p,this._documentCount,_,m,s),b=n*r*u*a*y,x=c.get(i);if(x){x.score+=b,E(x.terms,e);let n=h(x.match,t);n?n.push(l):x.match[t]=[l]}else c.set(i,{score:b,terms:[e],match:{[t]:[l]}})}}return c}addTerm(e,t,n){let r=this._index.fetch(n,k),i=r.get(e);if(i==null)i=new Map,i.set(t,1),r.set(e,i);else{let e=i.get(t);i.set(t,(e||0)+1)}}removeTerm(e,t,n){if(!this._index.has(n)){this.warnDocumentChanged(t,e,n);return}let r=this._index.fetch(n,k),i=r.get(e);i==null||i.get(t)==null?this.warnDocumentChanged(t,e,n):i.get(t)<=1?i.size<=1?r.delete(e):i.delete(t):i.set(t,i.get(t)-1),this._index.get(n).size===0&&this._index.delete(n)}warnDocumentChanged(e,t,n){for(let r of Object.keys(this._fieldIds))if(this._fieldIds[r]===t){this._options.logger(`warn`,`MiniSearch: document with ID ${this._documentIds.get(e)} has changed before removal: term "${n}" was not present in field "${r}". Removing a document after it has changed can corrupt the index!`,`version_conflict`);return}}addDocumentId(e){let t=this._nextId;return this._idToShortId.set(e,t),this._documentIds.set(t,e),this._documentCount+=1,this._nextId+=1,t}addFields(e){for(let t=0;t<e.length;t++)this._fieldIds[e[t]]=t}addFieldLength(e,t,n,r){let i=this._fieldLength.get(e);i??this._fieldLength.set(e,i=[]),i[t]=r;let a=(this._avgFieldLength[t]||0)*n+r;this._avgFieldLength[t]=a/(n+1)}removeFieldLength(e,t,n,r){if(n===1){this._avgFieldLength[t]=0;return}let i=this._avgFieldLength[t]*n-r;this._avgFieldLength[t]=i/(n-1)}saveStoredFields(e,t){let{storeFields:n,extractField:r}=this._options;if(n==null||n.length===0)return;let i=this._storedFields.get(e);i??this._storedFields.set(e,i={});for(let e of n){let n=r(t,e);n!==void 0&&(i[e]=n)}}};m.wildcard=Symbol(`*`);const h=(e,t)=>Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0,g={or:(e,t)=>{for(let n of t.keys()){let r=e.get(n);if(r==null)e.set(n,t.get(n));else{let{score:e,terms:i,match:a}=t.get(n);r.score+=e,r.match=Object.assign(r.match,a),D(r.terms,i)}}return e},and:(e,t)=>{let n=new Map;for(let r of t.keys()){let i=e.get(r);if(i==null)continue;let{score:a,terms:o,match:s}=t.get(r);D(i.terms,o),n.set(r,{score:i.score+a,terms:i.terms,match:Object.assign(i.match,s)})}return n},and_not:(e,t)=>{for(let n of t.keys())e.delete(n);return e}},_={k:1.2,b:.7,d:.5},v=(e,t,n,r,i,a)=>{let{k:o,b:s,d:c}=a;return Math.log(1+(n-t+.5)/(t+.5))*(c+e*(o+1)/(e+o*(1-s+s*r/i)))},y=e=>(t,n,r)=>({term:t,fuzzy:typeof e.fuzzy==`function`?e.fuzzy(t,n,r):e.fuzzy||!1,prefix:typeof e.prefix==`function`?e.prefix(t,n,r):e.prefix===!0,termBoost:typeof e.boostTerm==`function`?e.boostTerm(t,n,r):1}),b={idField:`id`,extractField:(e,t)=>e[t],stringifyField:(e,t)=>e.toString(),tokenize:e=>e.split(N),processTerm:e=>e.toLowerCase(),fields:void 0,searchOptions:void 0,storeFields:[],logger:(e,t)=>{typeof(console==null?void 0:console[e])==`function`&&console[e](t)},autoVacuum:!0},x={combineWith:`or`,prefix:!1,fuzzy:!1,maxFuzzy:6,boost:{},weights:{fuzzy:.45,prefix:.375},bm25:_},S={combineWith:`and`,prefix:(e,t,n)=>t===n.length-1},C={batchSize:1e3,batchWait:10},w={minDirtFactor:.1,minDirtCount:20},T={...C,...w},E=(e,t)=>{e.includes(t)||e.push(t)},D=(e,t)=>{for(let n of t)e.includes(n)||e.push(n)},O=({score:e},{score:t})=>t-e,k=()=>new Map,A=e=>{let t=new Map;for(let n of Object.keys(e))t.set(parseInt(n,10),e[n]);return t},j=async e=>{let t=new Map,n=0;for(let r of Object.keys(e))t.set(parseInt(r,10),e[r]),++n%1e3==0&&await M(0);return t},M=e=>new Promise(t=>setTimeout(t,e)),N=/[\n\r\p{Z}\p{P}]+/u;export{m as default};
@@ -0,0 +1 @@
1
+ const e=Object.freeze([Object.freeze({id:`experimental-settings`,label:`Experimental settings`,description:`Show controls for experimental features.`,defaultValue:`on`,floatDefaults:Object.freeze({cherry:`off`}),userToggleable:!1}),Object.freeze({id:`panel-layouts`,label:`Panel layouts`,description:`Arrange the UI as movable, resizable panels instead of the fixed workbench.`,defaultValue:`off`,userToggleable:!0}),Object.freeze({id:`agentic-memory`,label:`Agentic memory`,description:`Curate session memory with a background agent instead of a one-shot extraction call.`,defaultValue:`off`,userToggleable:!0}),Object.freeze({id:`multiple-cones`,label:`Multiple cones`,description:`Add, switch between and remove cones from the freezer rail. Extra cones share the workspace.`,defaultValue:`on`,floatDefaults:Object.freeze({cherry:`off`}),userToggleable:!1}),Object.freeze({id:`compact-on-idle`,label:`Compact on idle`,description:`When a cone has been idle for a while with a large context, summarize its history in the background. The full transcript is kept in /sessions.`,defaultValue:`off`,userToggleable:!0}),Object.freeze({id:`memory-v2`,label:`Memory v2`,description:`Searchable session history and scoop pre-compaction snapshots for agent memory.`,defaultValue:`off`,userToggleable:!0})]);new Map(e.map(e=>[e.id,e]));const t=new Set([`1`,`on`,`true`]);let n=`standalone`,r={},i={};function a(t,n={},r=o()){let a={};for(let o of e){let e=r[o.id];if(typeof e==`string`&&f(o,t)){a[o.id]=e;continue}let s=i[o.id];if(typeof s==`string`&&f(o,t)){a[o.id]=s;continue}let c=n[o.id];a[o.id]=typeof c==`string`?c:d(o,t)}return a}function o(){try{let e=m()?.getItem(`slicc_feature_flags`);return e?p(JSON.parse(e)):{}}catch{return{}}}function s(e,t={}){n=e,r=p(t),i={}}function c(e){return a(n,r)[e]}function l(e){return typeof e==`string`&&t.has(e.trim().toLowerCase())}function u(e){return l(c(e))}function d(e,t){return e.floatDefaults?.[t]??e.defaultValue}function f(e,t){return e.userToggleable&&(e.overridableFloats===void 0||e.overridableFloats.includes(t))}function p(t){if(typeof t!=`object`||!t||Array.isArray(t))return{};let n=t,r={};for(let t of e){let e=n[t.id];typeof e==`string`&&(r[t.id]=e)}return r}function m(){try{let e=globalThis.localStorage;return typeof e?.getItem!=`function`||typeof e.setItem!=`function`?void 0:e}catch{return}}export{u as n,s as t};
@@ -0,0 +1 @@
1
+ import{n as e}from"./rolldown-runtime-Dd_uD5pT.js";var t=e({SESSIONS_DIR:()=>n,SESSIONS_INDEX_PATH:()=>r,parseFrozenArchive:()=>a,readSessionsIndex:()=>i});const n=`/sessions`,r=`/sessions/index.json`;async function i(e){try{let t=await e.readFile(r,{encoding:`utf-8`}),n=typeof t==`string`?t:new TextDecoder().decode(t),i=JSON.parse(n);return Array.isArray(i)?i:[]}catch{return[]}}function a(e){let t=e,n=`Untitled`,r={},i=t.match(/^---\n([\s\S]*?)\n---\n+/);if(i){t=t.slice(i[0].length),Object.assign(r,o(i[1]));let e=i[1].match(/^title:\s*(.+?)\s*$/m);e&&(n=s(e[1]))}let a=t.match(/<!-- slicc:session-data\n([\s\S]*?)\n-->\n*/);if(a){try{let e=a[1].replace(/-- >/g,`-->`),t=JSON.parse(e);if(Array.isArray(t))return{title:n,messages:t,...r}}catch{}t=t.replace(/<!-- slicc:session-data\n[\s\S]*?\n-->\n*/,``)}return r.sidecar?{title:n,messages:[],...r}:(t=t.replace(/^#\s+[^\n]*\n+/,``),{title:n,messages:l(t),...r})}function o(e){let t={},n=c(e,`cost`),r=c(e,`models`);n&&(t.cost=n),r&&(t.models=r);let i=e.match(/^cone:\s*(.+?)\s*$/m)?.[1];i&&(t.cone=i);let a=e.match(/^coneLabel:\s*(.+?)\s*$/m)?.[1];a&&(t.coneLabel=s(a)),/^memorySkipped:\s*true\s*$/m.test(e)&&(t.memorySkipped=!0),/^live:\s*true\s*$/m.test(e)&&(t.live=!0);let o=Number(e.match(/^liveThrough:\s*(\d+)\s*$/m)?.[1]);Number.isFinite(o)&&o>0&&(t.liveThrough=o);let l=Number(e.match(/^compactions:\s*(\d+)\s*$/m)?.[1]);Number.isFinite(l)&&l>0&&(t.compactions=l);let u=e.match(/^id:\s*(\S+)\s*$/m)?.[1];u&&(t.id=u);let d=e.match(/^sidecar:\s*(\S+)\s*$/m)?.[1];return d&&(t.sidecar=d),t}function s(e){let t=e.trim();if(!t.startsWith(`"`))return t;try{let e=JSON.parse(t);if(typeof e==`string`)return e}catch{}return t.replace(/^"|"$/g,``)}function c(e,t){let n=RegExp(`^${t}:\\s*(.+?)\\s*$`,`m`).exec(e)?.[1];if(n)try{return JSON.parse(n)}catch{return}}function l(e){let t=[],n=/^## (User|Assistant)\s*\n/gm,r=[],i;for(;(i=n.exec(e))!==null;)r.push({role:i[1]===`User`?`user`:`assistant`,start:i.index,bodyStart:i.index+i[0].length});for(let n=0;n<r.length;n++){let i=n+1<r.length?r[n+1].start:e.length,a=e.slice(r[n].bodyStart,i).trim();t.push({id:`frozen-${n}`,role:r[n].role,content:a,timestamp:0})}return t}export{i as a,a as i,r as n,t as r,n as t};
@@ -0,0 +1,8 @@
1
+ import{t as e}from"./slugify-BYJ6QVAt.js";import{t}from"./attachments-u2K0aIPI.js";import{t as n}from"./types-Dgm4REV3.js";import{n as r,t as i}from"./frozen-archive-format-B4efpvB9.js";const a=/\uD83C\uDF99\uFE0F?/g,o=/\u25C1[\s\S]*?\u25B7/g;function s(e){return e.replace(o,``).replace(a,``).replace(/[ \t]+$/g,``).trimEnd()}function c(e){let n=``;for(let r of e){let e=r.role===`user`?`User`:`Assistant`,i=r.role===`user`?s(r.content):r.content;if(n+=`## ${e}\n${i}\n\n`,r.attachments?.length&&(n+=`Attachments:\n${r.attachments.map(e=>`- ${t(e)}`).join(`
2
+ `)}\n\n`),r.toolCalls)for(let e of r.toolCalls)n+=`### Tool: ${e.name}\nInput: ${JSON.stringify(e.input,null,2)}\nResult: ${e.result??``}\n\n`}return n}function l(e){return`live-${f(e)}-${d()}.md`}function u(e,t){return e.find(e=>e.live===!0&&(e.cone??`cone`)===t)}function d(){return`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,6)}`}function f(t){return e(t,{maxLen:48,fallback:`session`})}function p(e){let t=e.find(e=>e.role===`user`);if(!t?.content)return`untitled-session`;let n=t.content.trim().replace(/\s+/g,` `);return n.length>60?`${n.slice(0,60)}…`:n||`untitled-session`}function m(e){return e.map(e=>{let t={id:e.id,role:e.role,content:e.content,timestamp:e.timestamp};return e.attachments?.length&&(t.attachments=e.attachments),e.toolCalls?.length&&(t.toolCalls=e.toolCalls.map(e=>({id:e.id,name:e.name,input:e.input,...e.result===void 0?{}:{result:e.result},...e.isError?{isError:e.isError}:{}}))),e.source&&(t.source=e.source),e.channel&&(t.channel=e.channel),e.compaction&&(t.compaction=e.compaction),t})}function h(e){let t=(e.cost?`cost: ${JSON.stringify(e.cost)}\n`:``)+(e.models?`models: ${JSON.stringify(e.models)}\n`:``),n=(e.cone?`cone: ${e.cone}\n`:``)+(e.coneLabel?`coneLabel: ${JSON.stringify(e.coneLabel)}\n`:``)+(e.memorySkipped?`memorySkipped: true
3
+ `:``)+(e.live?`live: true
4
+ `:``)+(e.live&&e.liveThrough?`liveThrough: ${e.liveThrough}\n`:``)+(e.live&&e.compactions?`compactions: ${e.compactions}\n`:``),r=`---\nid: ${e.id}\ntitle: ${JSON.stringify(e.title)}\nfrozenAt: ${e.frozenAt}\ncreatedAt: ${e.createdAt}\nupdatedAt: ${e.updatedAt}\nmessageCount: ${e.messageCount}\n`+t+n+`---
5
+
6
+ `,i=`# ${e.title}\n\n`;return r+`<!-- slicc:session-data
7
+ ${JSON.stringify(m(e.messages)).replace(/-->/g,`-- >`)}
8
+ -->\n\n`+i+c(e.messages)}function g(e){return e===`/sessions`?r:`${e}/index.json`}function _(e){return e===`/sessions`?b:`slicc:sessions-index:${e}`}async function v(e,t=i){try{await e.mkdir(t,{recursive:!0})}catch{}}async function y(e,t=i){try{let n=await e.readFile(g(t),{encoding:`utf-8`}),r=typeof n==`string`?n:new TextDecoder().decode(n),i=JSON.parse(r);return Array.isArray(i)?i:[]}catch(e){if(e instanceof n&&e.code!==`ENOENT`)throw e;return[]}}const b=`slicc:sessions-index`;let x=Promise.resolve();function S(e,t=b){let n=()=>{let n=globalThis.navigator?.locks;return typeof n?.request==`function`?n.request(t,()=>e()):e()},r=x.then(n,n);return x=r.then(()=>void 0,()=>void 0),r}function C(e,t,n=i){return e.writeFile(g(n),JSON.stringify(t,null,2))}async function w(e,t,n=i){await C(e,[t,...(await y(e,n)).filter(e=>e.filename!==t.filename)],n)}export{l as a,_ as c,p as i,w as l,u as n,y as o,h as r,S as s,v as t,C as u};
@@ -1 +1 @@
1
- import{n as e}from"./rolldown-runtime-Dd_uD5pT.js";import{t}from"./logger-LESFN7Hj.js";import{a as n,i as r,n as i,r as a,t as o}from"./path-utils-DNJG-zQf.js";import{n as s,t as c}from"./types-Dgm4REV3.js";import{i as l,r as u,t as d}from"./mount-index-D9w_zMSm.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{i as v,r as y,t as b}from"./sidecar-repair-CIHuOk7H.js";function x(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 S(e,t){try{return await e(t)}catch{return t}}async function*C(e,t,n,r=0){let a=i(t);if(x(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 S(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*w(e,t,a===`/`?`/${t.name}`:`${a}/${t.name}`,o,r+1)}async function*w(e,t,n,r,i){if(t.type===`file`){yield n;return}if(t.type===`symlink`){yield*T(e,n,r,i);return}yield*C(e,n,r,i)}async function*T(e,t,n,r){try{let i=await e.stat(t);i.type===`file`?yield t:i.type===`directory`&&(yield*C(e,t,n,r))}catch{}}const E=t(`fs-watcher`);let D=0;function O(e,t){return t===`/`||e===t||e.startsWith(t+`/`)}var k=class{registrations=new Map;watch(e,t,n){let r=`fsw-${++D}`;return this.registrations.set(r,{id:r,basePath:e,filter:t,callback:n}),E.debug(`Watch registered`,{id:r,basePath:e}),()=>{this.registrations.delete(r),E.debug(`Watch unregistered`,{id:r})}}notify(e){if(e.length!==0)for(let[,t]of this.registrations){let n=e.filter(e=>O(e.path,t.basePath)&&t.filter(e.path));if(n.length>0)try{t.callback(n)}catch(e){E.error(`Watch callback error`,{id:t.id,error:e instanceof Error?e.message:String(e)})}}}dispose(){this.registrations.clear(),E.debug(`All watchers disposed`)}get size(){return this.registrations.size}};const A=new TextEncoder,j=new TextDecoder(`utf-8`,{fatal:!1});var M=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`?A.encode(t):new Uint8Array(t),a=Date.now(),o=this.entries.get(n);this.entries.set(n,{bytes:r,mtime:a,ctime:o?.ctime??a})}read(e,t){let n=this.require(e);return(t?.encoding??`utf-8`)===`utf-8`?j.decode(n.bytes):new Uint8Array(n.bytes)}readText(e){return j.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 N={[_]:{stat:()=>({type:`file`,size:0,mtime:0,ctime:0}),read:e=>(e?.encoding??`utf-8`)===`utf-8`?``:new Uint8Array,readText:()=>``,write:()=>{}}},P=[`/tmp/`];var F=class{ephemeralFds=new M;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,...P]}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,...P].some(e=>t===e.slice(0,-1)||t.startsWith(e))}canWrite(e){return M.handles(e)||this.isWritable(e)}checkWrite(e){if(this.writeEnforcement!==`sudo-delegated`&&!this.isWritable(e))throw new c(`EACCES`,`permission denied`,i(e))}async resolveAndCheckRead(e){try{let t=await this.vfs.realpath(e);if(!this.isAllowedStrict(t))throw new c(`ENOENT`,`no such file or directory`,i(e));return t}catch(t){throw t instanceof c?t:new c(`ENOENT`,`no such file or directory`,i(e))}}async resolveAndCheckWrite(e){try{let t=await this.vfs.realpath(e);if(!this.isWritable(t)&&!this.isSymlinkEscapeAllowed(t))throw new c(`EACCES`,`permission denied`,i(e));return t}catch(t){throw t instanceof c?t:new c(`EACCES`,`permission denied`,i(e))}}isSymlinkEscapeAllowed(e){return!1}async checkParentRealpathEscape(e){let t=this.vfs.dirname(e),n=this.vfs.basename(e),r;try{r=await this.vfs.realpath(t)}catch(e){if(e instanceof c&&e.code===`EACCES`)throw e;return}let a=r+`/`+n;if(this.isWritable(a))return;let o=i(r)!==i(t);if(!(this.writeEnforcement===`sudo-delegated`&&!o))throw new c(`EACCES`,`permission denied`,i(e))}getUnderlyingFS(){return this.vfs}invalidatePaths(e){this.vfs.invalidatePaths(e)}async flush(){await this.vfs.flush()}isPathUnderMount(e){return this.vfs.isPathUnderMount(e)}async readFile(e,t){let n=N[i(e)];if(n)return n.read(t);if(M.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(N[i(e)]||M.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=N[i(e)];if(t)return t.stat();if(M.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=N[i(e)];return t?t.stat():M.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=N[i(e)];return t?t.stat():M.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(M.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(N[i(e)])return!0;if(M.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=N[i(e)];if(t)return t.readText();if(M.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=N[i(e)];if(r){r.write(t);return}if(M.handles(e)){this.ephemeralFds.write(e,t);return}this.checkWrite(e),await this.checkParentRealpathEscape(e);try{(await this.vfs.lstat(e)).type===`symlink`&&await this.resolveAndCheckWrite(e)}catch(e){if(e instanceof c&&e.code===`EACCES`)throw e}return this.vfs.writeFile(e,t,n)}refuseDescriptorTreeOp(e){if(M.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(M.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(M.handles(e)){let n=this.ephemeralFds.read(e,{encoding:`binary`});await this.writeFile(t,n);return}if(M.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=N[i(e)];if(t)return t.stat();if(M.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))}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 I(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 L=[`ENOENT`,`EEXIST`,`ENOTDIR`,`EISDIR`,`ENOTEMPTY`,`EINVAL`,`EACCES`,`ELOOP`,`EBUSY`,`EFBIG`,`EBADF`,`ENOSYS`,`EIO`];function R(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(L.includes(r)){let n=e instanceof Error?e.message:String(e);return n.startsWith(`${r}: `)&&(n=n.slice(r.length+2),n=n.replace(/, undefined( '[^']*')?$/,``).replace(/ '[^']*'$/,``)),new c(r,n||r,t)}}let r=e instanceof Error?e.message:String(e);return r.includes(`ENOENT`)?new c(`ENOENT`,`no such file or directory`,t):r.includes(`EEXIST`)?new c(`EEXIST`,`file already exists`,t):r.includes(`ENOTDIR`)?new c(`ENOTDIR`,`not a directory`,t):r.includes(`EISDIR`)?new c(`EISDIR`,`is a directory`,t):r.includes(`ENOTEMPTY`)?new c(`ENOTEMPTY`,`directory not empty`,t):r.includes(`ELOOP`)?new c(`ELOOP`,`too many levels of symbolic links`,t):new c(`EINVAL`,r,t)}function z(e){return e===void 0?`absent`:(e&61440)==16384?`directory`:`file`}function B(e,t){return t===`absent`?!1:e.kind===`missing`||e.kind!==t}function V(e){let t=e?.mode;return typeof t==`number`?t:void 0}function H(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=z(V(r));o!==z(V(i))&&a.push({path:n,ownIsDirectory:o===`directory`})}return a}async function U(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 W(e,t,n,r){try{return await e.lstat(t)}catch(e){let t=R(e,r);if(t.code===`ENOENT`&&n)return null;throw t}}async function G(e,t,r){let a;try{a=await e.readlink(t)}catch(e){throw R(e,r)}return a.startsWith(`/`)?i(a):i(o(n(t).dir,a))}async function K(e,t,n,r,i,a){let o=t===`/`?`/${n}`:`${t}/${n}`;for(;;){let t=await W(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 G(e,o,i)}}async function q(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 K(e,o,a[t],t===a.length-1,r,s);o=n.resolved,s=n.hops}return o}async function J(e,t,n){return t(n)?n:q(e,t,n)}function Y(){try{if(typeof globalThis.navigator?.storage?.getDirectory==`function`)return`opfs`}catch{}return`memory`}function X(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.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 Z(e,t){switch(e.kind){case`local`:case`proc`:return{kind:`local`,mountId:e.mountId,idbHandleKey:t};case`hostfs`:return{kind:`hostfs`,mountId:e.mountId,hostPath:e.getHostPath()};default:return{kind:e.kind===`s3`?`s3`:e.kind===`aem`?`aem`:`da`,mountId:e.mountId,source:e.source,profile:e.profile??`default`}}}var Q=class e{lfs;lfsSync;rawLfs=null;rawLfsSync=null;_ready;_readyResolved=!1;backend;mountPoints=new Map;opfsBackendFs=null;opfsHandle=null;mountRoot=``;internalMounts=new Set;watcher=null;dbName;mountSyncChannel=null;mountIndex=new d;static writeChains=new Map;onRepairProgress;constructor(t,n,r,i,a){if(this.dbName=t,this.onRepairProgress=a,this.backend=r===`opfs`?`opfs`:`memory`,this.lfs=this.makeDeferredLfs(),this.lfsSync=this.makeDeferredLfsSync(),this._ready=this.backend===`opfs`?e.initOpfsBackend(this,i,n===!0):e.initMemoryBackend(this,t,n===!0),this._ready.then(()=>{this._readyResolved=!0},()=>{}),typeof BroadcastChannel<`u`)try{this.mountSyncChannel=new BroadcastChannel(`vfs-mount-sync:${t}`),this.mountSyncChannel.onmessage=e=>{let{type:t,path:n,descriptor:r}=e.data??{};if(t===`mount`&&typeof n==`string`&&r)this.reconstructBackendFromDescriptor(r,n).then(e=>{this.mountPoints.set(n,e),e.kind===`local`&&this.mountIndex.registerMount(n,e.getHandle()),this.watcher?.notify([{type:`modify`,path:n,entryType:`directory`}])}).catch(()=>{});else if(t===`unmount`&&typeof n==`string`){let e=this.mountPoints.get(n);this.mountPoints.delete(n),this.mountIndex.unregisterMount(n),e?.close(),this.watcher?.notify([{type:`modify`,path:n,entryType:`directory`}])}}}catch{}}static async initOpfsBackend(t,n,r){let i=n??await e.acquireOpfsHandle(t.dbName,r);await t.withWriteLock(()=>e.seedOpfsMetadataSidecarIfMissing(i));let[a,{WebAccess:o}]=await Promise.all([import(`./dist-qS_JJrd_.js`).then(e=>e.t),import(`./dist-I9BhJxsi.js`)]);await e.ensureRootMount(a);let s=`/__opfs__/${t.dbName}`,c=e.opfsBackends.get(t.dbName);if(c&&r){try{a.umount(s)}catch{}e.opfsBackends.delete(t.dbName),c=void 0}if(!c){let n=()=>a.resolveMountConfig({backend:o,handle:i,metadata:`/.metadata.json`}),{resolveWithSidecarRepair:r,repairOpfsMetadataSidecar:l}=await import(`./sidecar-repair-CIHuOk7H.js`).then(e=>e.n);try{let e=await t.withWriteLock(()=>l(i,t.onRepairProgress));e?.changed&&console.warn(`[virtual-fs] repaired metadata sidecar before mount (#2146)`,{dbName:t.dbName,kindFixed:e.kindFixed,sizesFixed:e.sizesFixed,dropped:e.dropped,inosReassigned:e.inosReassigned,nlinksFixed:e.nlinksFixed,selfEntryDropped:e.selfEntryDropped})}catch{}let u=await r(n,()=>t.withWriteLock(()=>l(i,t.onRepairProgress)),e=>console.warn(`[virtual-fs] repaired poisoned metadata sidecar; retrying mount`,{dbName:t.dbName,kindFixed:e.kindFixed,sizesFixed:e.sizesFixed,dropped:e.dropped,nlinksFixed:e.nlinksFixed,selfEntryDropped:e.selfEntryDropped}));try{a.mount(s,u)}catch{}c={backendFs:u,refs:0,sidecarDirty:{paths:new Set,prefixes:new Set}},e.opfsBackends.set(t.dbName,c)}c.refs+=1,t.opfsBackendFs=c.backendFs.index?c.backendFs:null,t.opfsHandle=i,t.mountRoot=s,t.rawLfs=a.promises,t.rawLfsSync=a}static async initMemoryBackend(t,n,r){let i=await import(`./dist-qS_JJrd_.js`).then(e=>e.t);await e.ensureRootMount(i);let a=`/__zenfs__/${n}`,o=e.memoryBackends.get(n);if(o&&r){try{i.umount(a)}catch{}e.memoryBackends.delete(n),o=void 0}o||(o={store:i.InMemory.create({label:n}),refs:0},e.memoryBackends.set(n,o)),o.refs+=1;try{i.mount(a,o.store)}catch{}t.mountRoot=a,t.rawLfs=i.promises,t.rawLfsSync=i,t.opfsBackendFs=null,t.opfsHandle=null}static rootMountReady=null;static memoryBackends=new Map;static opfsBackends=new Map;static async ensureRootMount(t){return e.rootMountReady===null&&(e.rootMountReady=(async()=>{await t.configureSingle({backend:t.InMemory,label:`__vfs_root__`})})()),e.rootMountReady}prefix(e){return this.mountRoot?e===`/`?this.mountRoot:this.mountRoot+e:e}unprefix(e){return!this.mountRoot||!e.startsWith(this.mountRoot)?e:e.slice(this.mountRoot.length)||`/`}makeDeferredLfs(){let e=e=>this.prefix(e),t=e=>this.unprefix(e),n=()=>{if(!this.rawLfs)throw Error(`VirtualFS used before init resolved`);return this.rawLfs};return{readFile:(t,r)=>this._readyResolved?n().readFile(e(t),r):this._ready.then(()=>n().readFile(e(t),r)),writeFile:(t,r,i)=>this._readyResolved?n().writeFile(e(t),r,i):this._ready.then(()=>n().writeFile(e(t),r,i)),readdir:t=>this._readyResolved?n().readdir(e(t)):this._ready.then(()=>n().readdir(e(t))),mkdir:(t,r)=>this._readyResolved?n().mkdir(e(t),r):this._ready.then(()=>n().mkdir(e(t),r)),rmdir:t=>this._readyResolved?n().rmdir(e(t)):this._ready.then(()=>n().rmdir(e(t))),unlink:t=>this._readyResolved?n().unlink(e(t)):this._ready.then(()=>n().unlink(e(t))),rename:(t,r)=>this._readyResolved?n().rename(e(t),e(r)):this._ready.then(()=>n().rename(e(t),e(r))),stat:t=>this._readyResolved?n().stat(e(t)):this._ready.then(()=>n().stat(e(t))),lstat:t=>this._readyResolved?n().lstat(e(t)):this._ready.then(()=>n().lstat(e(t))),symlink:(t,r)=>{let i=t.startsWith(`/`)?e(t):t;return this._readyResolved?n().symlink(i,e(r)):this._ready.then(()=>n().symlink(i,e(r)))},readlink:async r=>(this._readyResolved||await this._ready,t(await n().readlink(e(r)))),truncate:async(t,r)=>{this._readyResolved||await this._ready;let i=n();typeof i.truncate==`function`&&await i.truncate(e(t),r)},realpath:async r=>{this._readyResolved||await this._ready;let i=n();return typeof i.realpath==`function`?t(await i.realpath(e(r))):e(r)}}}makeDeferredLfsSync(){let e=e=>this.prefix(e),t=e=>this.unprefix(e);return{readdirSync:t=>{let n=this.rawLfsSync;return n?.readdirSync?n.readdirSync(e(t)):void 0},statSync:t=>{let n=this.rawLfsSync;return n?.statSync?n.statSync(e(t)):void 0},lstatSync:t=>{let n=this.rawLfsSync;return n?.lstatSync?n.lstatSync(e(t)):void 0},readlinkSync:n=>{let r=this.rawLfsSync;return r?.readlinkSync?t(r.readlinkSync(e(n))):void 0}}}static async seedOpfsMetadataSidecarIfMissing(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??Y(),a=new e(n,r,i,void 0,t?.onRepairProgress);return await a._ready,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(v(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=H(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}invalidatePaths(e){if(this.backend!==`opfs`||!this.opfsBackendFs)return;let t=this.opfsBackendFs;for(let n of e){let e=i(n);t.index.delete(e),t._handles?.delete(e),this.markSidecarDirty(e)}}async withKindMismatchRetry(e,t){return this.withKindMismatchRetryPaths([e],t)}async withKindMismatchRetryPaths(e,t){try{return await t()}catch(n){let r=n?.code;if(r!==`EISDIR`&&r!==`ENOTDIR`&&r!==`EINVAL`)throw n;for(let n of e)if(await this.reconcileKindMismatch(n).catch(()=>!1))return await t();throw n}}async reconcileKindMismatch(e){if(this.backend!==`opfs`)return!1;let t=this.opfsBackendFs,n=this.opfsHandle;if(!t?.index||!n)return!1;let r=i(e),a=r;try{a=await this.resolveSymlinks(r)}catch{}let o=await b(n)(a),s=z(t.index.get(a)?.mode),c=t._handles?.get(a),l=c?.kind===`directory`?`directory`:c?.kind===`file`?`file`:`absent`,u=B(o,s),d=B(o,l);if(!u&&!d)return!1;if(t.index.delete(a),t._handles?.delete(a),s===`directory`||l===`directory`){let e=`${a}/`;for(let n of[...t.index.keys()])n.startsWith(e)&&t.index.delete(n);if(t._handles)for(let n of[...t._handles.keys()])n.startsWith(e)&&t._handles.delete(n)}return this.markSidecarDirty(a),console.warn(`[virtual-fs] reconciled in-memory kind mismatch (#2006)`,{path:a,reality:o.kind,indexHeld:s,handleHeld:l}),!0}canWrite(e){return!0}setWatcher(e){this.watcher=e}getWatcher(){return this.watcher}async watch(e,t){let n=this.watcher;if(!n)throw new c(`ENOSYS`,`no FsWatcher attached to this VirtualFS`);let r=e.map(e=>n.watch(e,()=>!0,t));return()=>{for(let e of r)e()}}async dispose(){if(this.mountSyncChannel?.close(),this.mountSyncChannel=null,this.watcher?.dispose(),this.watcher=null,this.mountIndex.dispose(),await this.writeOpfsMetadataSidecar(),this.mountRoot){let t=this.backend===`opfs`?e.opfsBackends:e.memoryBackends,n=t.get(this.dbName);if(n&&(--n.refs,n.refs<=0)){t.delete(this.dbName);try{(await import(`./dist-qS_JJrd_.js`).then(e=>e.t)).umount(this.mountRoot)}catch{}}}}readDirSync(e){let t=i(e);if(this.findMount(t))return null;let n=this.lfsSync;if(typeof n.readdirSync!=`function`||typeof n.lstatSync!=`function`)return null;try{let e=n.readdirSync(t),r=[];for(let i of e){let e=t===`/`?`/${i}`:`${t}/${i}`;try{let t=n.lstatSync(e),a=t.isSymbolicLink()?`symlink`:t.isDirectory()?`directory`:`file`;r.push(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},...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}}catch{return null}let a=t;for(let e=0;e<=10;e++){let e;try{e=r.lstatSync(a)}catch{return null}if(!e.isSymbolicLink())return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,ino:e.ino};let t;try{t=r.readlinkSync(a)}catch{return null}a=t.startsWith(`/`)?i(t):i(o(n(a).dir,t))}return null}lstatSync(e){let t=i(e);if(this.findMount(t))return null;let n=this.lfsSync;if(typeof n.lstatSync!=`function`)return null;if(t===`/`)return this.statSync(t);try{let e=n.lstatSync(t);if(e.isSymbolicLink()){let r=n.readlinkSync?n.readlinkSync(t):``;return{type:`symlink`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,isSymlink:!0,symlinkTarget:r,ino:e.ino}}return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,ino:e.ino}}catch{return null}}async mount(e,t,r){let a=i(e);if(this.mountPoints.has(a))throw new c(`EEXIST`,`mount point is already mounted`,a);try{if((await this.lstat(a)).type!==`directory`)throw new c(`ENOTDIR`,`mount point must be a directory`,a);if((await this.readDir(a)).length>0)throw new c(`ENOTEMPTY`,`mount point must be empty to avoid shadowing existing files`,a)}catch(e){if(!(e instanceof c)||e.code!==`ENOENT`)throw e}let{dir:o}=n(a);o!==`/`&&await this.mkdir(o,{recursive:!0});try{await this.lfs.mkdir(a)}catch{}if(this.mountPoints.set(a,t),t.kind===`local`){let e=r?.limits??u(r?.env??{});this.mountIndex.registerMount(a,t.getHandle(),e)}let s=Z(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-BxfjZHzO.js`);return new n({targetPath:t,hostPath:e.hostPath,mountId:e.mountId})}case`s3`:{let{S3MountBackend:t,RemoteMountCache:n,makeSignedFetchS3:r}=await import(`./mount-uOkkZNjk.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-uOkkZNjk.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-uOkkZNjk.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});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){I(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 R(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){I(e,r)}}let s=await this.readFile(r,{encoding:`binary`});return new Uint8Array(s.subarray(t,Math.min(n,s.byteLength)))}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 U(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){I(e,a)}this.watcher?.notify([{type:n?`modify`:`create`,path:a,entryType:`file`}]),this.mountIndex.notifyWrite(a);return}let s;try{s=await this.resolveSymlinks(a)}catch{s=a}let l=!1;try{await this.lfs.stat(s),l=!0}catch{}let{dir:u}=n(s);await this.withWriteLock(async()=>{this.markSidecarDirty(s),u!==`/`&&await this.mkdirRecursiveUnlocked(u);let e=typeof t==`string`?new TextEncoder().encode(t).byteLength:(t instanceof Uint8Array,t.byteLength);try{await this.lfs.writeFile(s,t)}catch(e){if(u!==`/`&&e instanceof Error&&e.message.includes(`ENOENT`)){await this.mkdirRecursiveUnlocked(u);try{await this.lfs.writeFile(s,t)}catch(e){throw R(e,a)}}else throw R(e,a)}try{await this.lfs.truncate?.(s,e)}catch(e){throw R(e,a)}}),this.watcher?.notify([{type:l?`modify`:`create`,path:s,entryType:`file`}])}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){I(t,e)}let o=new Map,s=t.backend.listingStatsMatchStat===!0;for(let e of a)o.set(e.name,X(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 R(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},...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 R(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){I(e,n)}t||this.watcher?.notify([{type:`create`,path:n,entryType:`directory`}]);return}if(t?.recursive){let e=await this.withWriteLock(()=>(this.markSidecarDirty(n),this.mkdirRecursiveUnlocked(n)));e.length>0&&this.watcher?.notify(e.map(e=>({type:`create`,path:e,entryType:`directory`})))}else await this.withWriteLock(async()=>{this.markSidecarDirty(n);try{await this.lfs.mkdir(n)}catch(e){throw R(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){I(e,n)}this.watcher?.notify([{type:`delete`,path:n,entryType:e}]),this.mountIndex.notifyDelete(n);return}try{let e=await this.lfs.lstat(n);await this.withWriteLock(async()=>{e.isSymbolicLink()?await this.lfs.unlink(n):e.isDirectory()?t?.recursive?await this.rmRecursiveUnlocked(n):await this.lfs.rmdir(n):await this.lfs.unlink(n),this.markSidecarDirty(n,`prefix`),await this.writeOpfsMetadataSidecarUnlocked()})}catch(e){throw R(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.uid===void 0?{}:{uid:t.uid},...t.gid===void 0?{}:{gid:t.gid},...t.mode===void 0?{}:{mode:t.mode}}}catch(e){I(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,uid:e.uid,gid:e.gid,mode:e.mode}}catch(e){throw R(e,t)}}async exists(e){let t=i(e),n=this.findMount(t);if(n){if(n.relParts.length===0)return!0;try{return await this.stat(t),!0}catch{return!1}}try{return await this.stat(t),!0}catch{try{return await this.lfs.lstat(t),!0}catch{return!1}}}async rename(e,t){return this.withKindMismatchRetryPaths([i(e),i(t)],()=>this.renameInner(e,t))}async renameInner(e,t){let n=i(e),r=i(t),a;try{a=(await this.lstat(n)).type}catch{}let o=this.findMount(n);if(o?.backend.rename){let e=this.findMount(r);if(e&&e.backend===o.backend){try{await o.backend.rename(o.relParts.join(`/`),e.relParts.join(`/`))}catch(e){I(e,n)}this.watcher?.notify([{type:`delete`,path:n,entryType:a},{type:`create`,path:r,entryType:a}]),this.mountIndex.notifyRename(n,r);return}}try{await this.withWriteLock(async()=>{this.markSidecarDirty(n,`prefix`),this.markSidecarDirty(r,`prefix`),await this.lfs.rename(n,r),await this.writeOpfsMetadataSidecarUnlocked()})}catch(e){throw R(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*C({mountPoints:this.mountPoints,mountIndex:this.mountIndex,realpath:e=>this.realpath(e),readDir:e=>this.readDir(e),stat:e=>this.stat(e)},e,t,n)}async copyFile(e,t){if((await this.stat(e)).type===`directory`)throw new c(`EISDIR`,`is a directory`,e);let n=await this.readFile(e,{encoding:`binary`});await this.writeFile(t,n)}dirname(e){return n(i(e)).dir}basename(e){return n(i(e)).base}async symlink(e,t){let r=i(t);if(this.findMount(r))throw new c(`EINVAL`,`symlinks not supported on mounted filesystems`,r);let{dir:a}=n(r);await this.withWriteLock(async()=>{a!==`/`&&await this.mkdirRecursiveUnlocked(a);try{await this.lfs.symlink(e,r)}catch(t){if(a!==`/`&&t instanceof Error&&t.message.includes(`ENOENT`)){await this.mkdirRecursiveUnlocked(a);try{await this.lfs.symlink(e,r)}catch(e){throw R(e,r)}}else throw R(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 R(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,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,uid:e.uid,gid:e.gid,mode:e.mode}}catch(e){throw R(e,t)}}async realpath(e){return q(this.lfs,e=>this.findMount(e)!==null,e)}resolveSymlinks(e){return J(this.lfs,e=>this.findMount(e)!==null,e)}},$=e({FsError:()=>c,FsWatcher:()=>k,MountIndex:()=>d,RestrictedFS:()=>F,VirtualFS:()=>Q,joinPath:()=>o,normalizePath:()=>i,pathSegments:()=>r,resolveVfsBackendFromEnv:()=>Y,splitPath:()=>n,statsFromDirEntry:()=>s});export{k as i,Q as n,F as r,$ as t};
1
+ import{n as e}from"./rolldown-runtime-Dd_uD5pT.js";import{t}from"./logger-LESFN7Hj.js";import{a as n,i as r,n as i,r as a,t as o}from"./path-utils-DNJG-zQf.js";import{n as s,t as c}from"./types-Dgm4REV3.js";import{i as l,r as u,t as d}from"./mount-index-D9w_zMSm.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{i as v,r as y,t as b}from"./sidecar-repair-CIHuOk7H.js";function x(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 S(e,t){try{return await e(t)}catch{return t}}async function*C(e,t,n,r=0){let a=i(t);if(x(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 S(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*w(e,t,a===`/`?`/${t.name}`:`${a}/${t.name}`,o,r+1)}async function*w(e,t,n,r,i){if(t.type===`file`){yield n;return}if(t.type===`symlink`){yield*T(e,n,r,i);return}yield*C(e,n,r,i)}async function*T(e,t,n,r){try{let i=await e.stat(t);i.type===`file`?yield t:i.type===`directory`&&(yield*C(e,t,n,r))}catch{}}const E=t(`fs-watcher`);let D=0;function O(e,t){return t===`/`||e===t||e.startsWith(t+`/`)}var k=class{registrations=new Map;watch(e,t,n){let r=`fsw-${++D}`;return this.registrations.set(r,{id:r,basePath:e,filter:t,callback:n}),E.debug(`Watch registered`,{id:r,basePath:e}),()=>{this.registrations.delete(r),E.debug(`Watch unregistered`,{id:r})}}notify(e){if(e.length!==0)for(let[,t]of this.registrations){let n=e.filter(e=>O(e.path,t.basePath)&&t.filter(e.path));if(n.length>0)try{t.callback(n)}catch(e){E.error(`Watch callback error`,{id:t.id,error:e instanceof Error?e.message:String(e)})}}}dispose(){this.registrations.clear(),E.debug(`All watchers disposed`)}get size(){return this.registrations.size}};const A=new TextEncoder,j=new TextDecoder(`utf-8`,{fatal:!1});var M=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`?A.encode(t):new Uint8Array(t),a=Date.now(),o=this.entries.get(n);this.entries.set(n,{bytes:r,mtime:a,ctime:o?.ctime??a})}read(e,t){let n=this.require(e);return(t?.encoding??`utf-8`)===`utf-8`?j.decode(n.bytes):new Uint8Array(n.bytes)}readText(e){return j.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 N={[_]:{stat:()=>({type:`file`,size:0,mtime:0,ctime:0}),read:e=>(e?.encoding??`utf-8`)===`utf-8`?``:new Uint8Array,readText:()=>``,write:()=>{}}},P=[`/tmp/`];var F=class{ephemeralFds=new M;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,...P]}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,...P].some(e=>t===e.slice(0,-1)||t.startsWith(e))}canWrite(e){return M.handles(e)||this.isWritable(e)}checkWrite(e){if(this.writeEnforcement!==`sudo-delegated`&&!this.isWritable(e))throw new c(`EACCES`,`permission denied`,i(e))}async resolveAndCheckRead(e){try{let t=await this.vfs.realpath(e);if(!this.isAllowedStrict(t))throw new c(`ENOENT`,`no such file or directory`,i(e));return t}catch(t){throw t instanceof c?t:new c(`ENOENT`,`no such file or directory`,i(e))}}async resolveAndCheckWrite(e){try{let t=await this.vfs.realpath(e);if(!this.isWritable(t)&&!this.isSymlinkEscapeAllowed(t))throw new c(`EACCES`,`permission denied`,i(e));return t}catch(t){throw t instanceof c?t:new c(`EACCES`,`permission denied`,i(e))}}isSymlinkEscapeAllowed(e){return!1}async checkParentRealpathEscape(e){let t=this.vfs.dirname(e),n=this.vfs.basename(e),r;try{r=await this.vfs.realpath(t)}catch(e){if(e instanceof c&&e.code===`EACCES`)throw e;return}let a=r+`/`+n;if(this.isWritable(a))return;let o=i(r)!==i(t);if(!(this.writeEnforcement===`sudo-delegated`&&!o))throw new c(`EACCES`,`permission denied`,i(e))}getUnderlyingFS(){return this.vfs}invalidatePaths(e){this.vfs.invalidatePaths(e)}async flush(){await this.vfs.flush()}isPathUnderMount(e){return this.vfs.isPathUnderMount(e)}async readFile(e,t){let n=N[i(e)];if(n)return n.read(t);if(M.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(N[i(e)]||M.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=N[i(e)];if(t)return t.stat();if(M.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=N[i(e)];return t?t.stat():M.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=N[i(e)];return t?t.stat():M.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(M.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(N[i(e)])return!0;if(M.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=N[i(e)];if(t)return t.readText();if(M.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=N[i(e)];if(r){r.write(t);return}if(M.handles(e)){this.ephemeralFds.write(e,t);return}this.checkWrite(e),await this.checkParentRealpathEscape(e);try{(await this.vfs.lstat(e)).type===`symlink`&&await this.resolveAndCheckWrite(e)}catch(e){if(e instanceof c&&e.code===`EACCES`)throw e}return this.vfs.writeFile(e,t,n)}refuseDescriptorTreeOp(e){if(M.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(M.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(M.handles(e)){let n=this.ephemeralFds.read(e,{encoding:`binary`});await this.writeFile(t,n);return}if(M.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=N[i(e)];if(t)return t.stat();if(M.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))}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 I(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 L=[`ENOENT`,`EEXIST`,`ENOTDIR`,`EISDIR`,`ENOTEMPTY`,`EINVAL`,`EACCES`,`ELOOP`,`EBUSY`,`EFBIG`,`EBADF`,`ENOSYS`,`EIO`];function R(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(L.includes(r)){let n=e instanceof Error?e.message:String(e);return n.startsWith(`${r}: `)&&(n=n.slice(r.length+2),n=n.replace(/, undefined( '[^']*')?$/,``).replace(/ '[^']*'$/,``)),new c(r,n||r,t)}}let r=e instanceof Error?e.message:String(e);return r.includes(`ENOENT`)?new c(`ENOENT`,`no such file or directory`,t):r.includes(`EEXIST`)?new c(`EEXIST`,`file already exists`,t):r.includes(`ENOTDIR`)?new c(`ENOTDIR`,`not a directory`,t):r.includes(`EISDIR`)?new c(`EISDIR`,`is a directory`,t):r.includes(`ENOTEMPTY`)?new c(`ENOTEMPTY`,`directory not empty`,t):r.includes(`ELOOP`)?new c(`ELOOP`,`too many levels of symbolic links`,t):new c(`EINVAL`,r,t)}function z(e){return e===void 0?`absent`:(e&61440)==16384?`directory`:`file`}function B(e,t){return t===`absent`?!1:e.kind===`missing`||e.kind!==t}function V(e){let t=e?.mode;return typeof t==`number`?t:void 0}function H(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=z(V(r));o!==z(V(i))&&a.push({path:n,ownIsDirectory:o===`directory`})}return a}async function U(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 W(e,t,n,r){try{return await e.lstat(t)}catch(e){let t=R(e,r);if(t.code===`ENOENT`&&n)return null;throw t}}async function G(e,t,r){let a;try{a=await e.readlink(t)}catch(e){throw R(e,r)}return a.startsWith(`/`)?i(a):i(o(n(t).dir,a))}async function K(e,t,n,r,i,a){let o=t===`/`?`/${n}`:`${t}/${n}`;for(;;){let t=await W(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 G(e,o,i)}}async function q(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 K(e,o,a[t],t===a.length-1,r,s);o=n.resolved,s=n.hops}return o}async function J(e,t,n){return t(n)?n:q(e,t,n)}function Y(){try{if(typeof globalThis.navigator?.storage?.getDirectory==`function`)return`opfs`}catch{}return`memory`}function X(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.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 Z(e,t){switch(e.kind){case`local`:case`proc`:return{kind:`local`,mountId:e.mountId,idbHandleKey:t};case`hostfs`:return{kind:`hostfs`,mountId:e.mountId,hostPath:e.getHostPath()};default:return{kind:e.kind===`s3`?`s3`:e.kind===`aem`?`aem`:`da`,mountId:e.mountId,source:e.source,profile:e.profile??`default`}}}var Q=class e{lfs;lfsSync;rawLfs=null;rawLfsSync=null;_ready;_readyResolved=!1;backend;mountPoints=new Map;opfsBackendFs=null;opfsHandle=null;mountRoot=``;internalMounts=new Set;watcher=null;dbName;mountSyncChannel=null;mountIndex=new d;static writeChains=new Map;onRepairProgress;constructor(t,n,r,i,a){if(this.dbName=t,this.onRepairProgress=a,this.backend=r===`opfs`?`opfs`:`memory`,this.lfs=this.makeDeferredLfs(),this.lfsSync=this.makeDeferredLfsSync(),this._ready=this.backend===`opfs`?e.initOpfsBackend(this,i,n===!0):e.initMemoryBackend(this,t,n===!0),this._ready.then(()=>{this._readyResolved=!0},()=>{}),typeof BroadcastChannel<`u`)try{this.mountSyncChannel=new BroadcastChannel(`vfs-mount-sync:${t}`),this.mountSyncChannel.onmessage=e=>{let{type:t,path:n,descriptor:r}=e.data??{};if(t===`mount`&&typeof n==`string`&&r)this.reconstructBackendFromDescriptor(r,n).then(e=>{this.mountPoints.set(n,e),e.kind===`local`&&this.mountIndex.registerMount(n,e.getHandle()),this.watcher?.notify([{type:`modify`,path:n,entryType:`directory`}])}).catch(()=>{});else if(t===`unmount`&&typeof n==`string`){let e=this.mountPoints.get(n);this.mountPoints.delete(n),this.mountIndex.unregisterMount(n),e?.close(),this.watcher?.notify([{type:`modify`,path:n,entryType:`directory`}])}}}catch{}}static async initOpfsBackend(t,n,r){let i=n??await e.acquireOpfsHandle(t.dbName,r);await t.withWriteLock(()=>e.seedOpfsMetadataSidecarIfMissing(i));let[a,{WebAccess:o}]=await Promise.all([import(`./dist-qS_JJrd_.js`).then(e=>e.t),import(`./dist-I9BhJxsi.js`)]);await e.ensureRootMount(a);let s=`/__opfs__/${t.dbName}`,c=e.opfsBackends.get(t.dbName);if(c&&r){try{a.umount(s)}catch{}e.opfsBackends.delete(t.dbName),c=void 0}if(!c){let n=()=>a.resolveMountConfig({backend:o,handle:i,metadata:`/.metadata.json`}),{resolveWithSidecarRepair:r,repairOpfsMetadataSidecar:l}=await import(`./sidecar-repair-CIHuOk7H.js`).then(e=>e.n);try{let e=await t.withWriteLock(()=>l(i,t.onRepairProgress));e?.changed&&console.warn(`[virtual-fs] repaired metadata sidecar before mount (#2146)`,{dbName:t.dbName,kindFixed:e.kindFixed,sizesFixed:e.sizesFixed,dropped:e.dropped,inosReassigned:e.inosReassigned,nlinksFixed:e.nlinksFixed,selfEntryDropped:e.selfEntryDropped})}catch{}let u=await r(n,()=>t.withWriteLock(()=>l(i,t.onRepairProgress)),e=>console.warn(`[virtual-fs] repaired poisoned metadata sidecar; retrying mount`,{dbName:t.dbName,kindFixed:e.kindFixed,sizesFixed:e.sizesFixed,dropped:e.dropped,nlinksFixed:e.nlinksFixed,selfEntryDropped:e.selfEntryDropped}));try{a.mount(s,u)}catch{}c={backendFs:u,refs:0,sidecarDirty:{paths:new Set,prefixes:new Set}},e.opfsBackends.set(t.dbName,c)}c.refs+=1,t.opfsBackendFs=c.backendFs.index?c.backendFs:null,t.opfsHandle=i,t.mountRoot=s,t.rawLfs=a.promises,t.rawLfsSync=a}static async initMemoryBackend(t,n,r){let i=await import(`./dist-qS_JJrd_.js`).then(e=>e.t);await e.ensureRootMount(i);let a=`/__zenfs__/${n}`,o=e.memoryBackends.get(n);if(o&&r){try{i.umount(a)}catch{}e.memoryBackends.delete(n),o=void 0}o||(o={store:i.InMemory.create({label:n}),refs:0},e.memoryBackends.set(n,o)),o.refs+=1;try{i.mount(a,o.store)}catch{}t.mountRoot=a,t.rawLfs=i.promises,t.rawLfsSync=i,t.opfsBackendFs=null,t.opfsHandle=null}static rootMountReady=null;static memoryBackends=new Map;static opfsBackends=new Map;static async ensureRootMount(t){return e.rootMountReady===null&&(e.rootMountReady=(async()=>{await t.configureSingle({backend:t.InMemory,label:`__vfs_root__`})})()),e.rootMountReady}prefix(e){return this.mountRoot?e===`/`?this.mountRoot:this.mountRoot+e:e}unprefix(e){return!this.mountRoot||!e.startsWith(this.mountRoot)?e:e.slice(this.mountRoot.length)||`/`}makeDeferredLfs(){let e=e=>this.prefix(e),t=e=>this.unprefix(e),n=()=>{if(!this.rawLfs)throw Error(`VirtualFS used before init resolved`);return this.rawLfs};return{readFile:(t,r)=>this._readyResolved?n().readFile(e(t),r):this._ready.then(()=>n().readFile(e(t),r)),writeFile:(t,r,i)=>this._readyResolved?n().writeFile(e(t),r,i):this._ready.then(()=>n().writeFile(e(t),r,i)),readdir:t=>this._readyResolved?n().readdir(e(t)):this._ready.then(()=>n().readdir(e(t))),mkdir:(t,r)=>this._readyResolved?n().mkdir(e(t),r):this._ready.then(()=>n().mkdir(e(t),r)),rmdir:t=>this._readyResolved?n().rmdir(e(t)):this._ready.then(()=>n().rmdir(e(t))),unlink:t=>this._readyResolved?n().unlink(e(t)):this._ready.then(()=>n().unlink(e(t))),rename:(t,r)=>this._readyResolved?n().rename(e(t),e(r)):this._ready.then(()=>n().rename(e(t),e(r))),stat:t=>this._readyResolved?n().stat(e(t)):this._ready.then(()=>n().stat(e(t))),lstat:t=>this._readyResolved?n().lstat(e(t)):this._ready.then(()=>n().lstat(e(t))),symlink:(t,r)=>{let i=t.startsWith(`/`)?e(t):t;return this._readyResolved?n().symlink(i,e(r)):this._ready.then(()=>n().symlink(i,e(r)))},readlink:async r=>(this._readyResolved||await this._ready,t(await n().readlink(e(r)))),truncate:async(t,r)=>{this._readyResolved||await this._ready;let i=n();typeof i.truncate==`function`&&await i.truncate(e(t),r)},realpath:async r=>{this._readyResolved||await this._ready;let i=n();return typeof i.realpath==`function`?t(await i.realpath(e(r))):e(r)}}}makeDeferredLfsSync(){let e=e=>this.prefix(e),t=e=>this.unprefix(e);return{readdirSync:t=>{let n=this.rawLfsSync;return n?.readdirSync?n.readdirSync(e(t)):void 0},statSync:t=>{let n=this.rawLfsSync;return n?.statSync?n.statSync(e(t)):void 0},lstatSync:t=>{let n=this.rawLfsSync;return n?.lstatSync?n.lstatSync(e(t)):void 0},readlinkSync:n=>{let r=this.rawLfsSync;return r?.readlinkSync?t(r.readlinkSync(e(n))):void 0}}}static async seedOpfsMetadataSidecarIfMissing(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??Y(),a=new e(n,r,i,void 0,t?.onRepairProgress);return await a._ready,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(v(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=H(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}invalidatePaths(e){if(this.backend!==`opfs`||!this.opfsBackendFs)return;let t=this.opfsBackendFs;for(let n of e){let e=i(n);t.index.delete(e),t._handles?.delete(e),this.markSidecarDirty(e)}}async withKindMismatchRetry(e,t){return this.withKindMismatchRetryPaths([e],t)}async withKindMismatchRetryPaths(e,t){try{return await t()}catch(n){let r=n?.code;if(r!==`EISDIR`&&r!==`ENOTDIR`&&r!==`EINVAL`)throw n;for(let n of e)if(await this.reconcileKindMismatch(n).catch(()=>!1))return await t();throw n}}async reconcileKindMismatch(e){if(this.backend!==`opfs`)return!1;let t=this.opfsBackendFs,n=this.opfsHandle;if(!t?.index||!n)return!1;let r=i(e),a=r;try{a=await this.resolveSymlinks(r)}catch{}let o=await b(n)(a),s=z(t.index.get(a)?.mode),c=t._handles?.get(a),l=c?.kind===`directory`?`directory`:c?.kind===`file`?`file`:`absent`,u=B(o,s),d=B(o,l);if(!u&&!d)return!1;if(t.index.delete(a),t._handles?.delete(a),s===`directory`||l===`directory`){let e=`${a}/`;for(let n of[...t.index.keys()])n.startsWith(e)&&t.index.delete(n);if(t._handles)for(let n of[...t._handles.keys()])n.startsWith(e)&&t._handles.delete(n)}return this.markSidecarDirty(a),console.warn(`[virtual-fs] reconciled in-memory kind mismatch (#2006)`,{path:a,reality:o.kind,indexHeld:s,handleHeld:l}),!0}canWrite(e){return!0}setWatcher(e){this.watcher=e}getWatcher(){return this.watcher}async watch(e,t){let n=this.watcher;if(!n)throw new c(`ENOSYS`,`no FsWatcher attached to this VirtualFS`);let r=e.map(e=>n.watch(e,()=>!0,t));return()=>{for(let e of r)e()}}async dispose(){if(this.mountSyncChannel?.close(),this.mountSyncChannel=null,this.watcher?.dispose(),this.watcher=null,this.mountIndex.dispose(),await this.writeOpfsMetadataSidecar(),this.mountRoot){let t=this.backend===`opfs`?e.opfsBackends:e.memoryBackends,n=t.get(this.dbName);if(n&&(--n.refs,n.refs<=0)){t.delete(this.dbName);try{(await import(`./dist-qS_JJrd_.js`).then(e=>e.t)).umount(this.mountRoot)}catch{}}}}readDirSync(e){let t=i(e);if(this.findMount(t))return null;let n=this.lfsSync;if(typeof n.readdirSync!=`function`||typeof n.lstatSync!=`function`)return null;try{let e=n.readdirSync(t),r=[];for(let i of e){let e=t===`/`?`/${i}`:`${t}/${i}`;try{let t=n.lstatSync(e),a=t.isSymbolicLink()?`symlink`:t.isDirectory()?`directory`:`file`;r.push(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},...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}}catch{return null}let a=t;for(let e=0;e<=10;e++){let e;try{e=r.lstatSync(a)}catch{return null}if(!e.isSymbolicLink())return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,ino:e.ino};let t;try{t=r.readlinkSync(a)}catch{return null}a=t.startsWith(`/`)?i(t):i(o(n(a).dir,t))}return null}lstatSync(e){let t=i(e);if(this.findMount(t))return null;let n=this.lfsSync;if(typeof n.lstatSync!=`function`)return null;if(t===`/`)return this.statSync(t);try{let e=n.lstatSync(t);if(e.isSymbolicLink()){let r=n.readlinkSync?n.readlinkSync(t):``;return{type:`symlink`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,isSymlink:!0,symlinkTarget:r,ino:e.ino}}return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,ino:e.ino}}catch{return null}}async mount(e,t,r){let a=i(e);if(this.mountPoints.has(a))throw new c(`EEXIST`,`mount point is already mounted`,a);try{if((await this.lstat(a)).type!==`directory`)throw new c(`ENOTDIR`,`mount point must be a directory`,a);if((await this.readDir(a)).length>0)throw new c(`ENOTEMPTY`,`mount point must be empty to avoid shadowing existing files`,a)}catch(e){if(!(e instanceof c)||e.code!==`ENOENT`)throw e}let{dir:o}=n(a);o!==`/`&&await this.mkdir(o,{recursive:!0});try{await this.lfs.mkdir(a)}catch{}if(this.mountPoints.set(a,t),t.kind===`local`){let e=r?.limits??u(r?.env??{});this.mountIndex.registerMount(a,t.getHandle(),e)}let s=Z(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-BxfjZHzO.js`);return new n({targetPath:t,hostPath:e.hostPath,mountId:e.mountId})}case`s3`:{let{S3MountBackend:t,RemoteMountCache:n,makeSignedFetchS3:r}=await import(`./mount-Cd8ExLLy.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-Cd8ExLLy.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-Cd8ExLLy.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});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){I(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 R(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){I(e,r)}}let s=await this.readFile(r,{encoding:`binary`});return new Uint8Array(s.subarray(t,Math.min(n,s.byteLength)))}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 U(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){I(e,a)}this.watcher?.notify([{type:n?`modify`:`create`,path:a,entryType:`file`}]),this.mountIndex.notifyWrite(a);return}let s;try{s=await this.resolveSymlinks(a)}catch{s=a}let l=!1;try{await this.lfs.stat(s),l=!0}catch{}let{dir:u}=n(s);await this.withWriteLock(async()=>{this.markSidecarDirty(s),u!==`/`&&await this.mkdirRecursiveUnlocked(u);let e=typeof t==`string`?new TextEncoder().encode(t).byteLength:(t instanceof Uint8Array,t.byteLength);try{await this.lfs.writeFile(s,t)}catch(e){if(u!==`/`&&e instanceof Error&&e.message.includes(`ENOENT`)){await this.mkdirRecursiveUnlocked(u);try{await this.lfs.writeFile(s,t)}catch(e){throw R(e,a)}}else throw R(e,a)}try{await this.lfs.truncate?.(s,e)}catch(e){throw R(e,a)}}),this.watcher?.notify([{type:l?`modify`:`create`,path:s,entryType:`file`}])}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){I(t,e)}let o=new Map,s=t.backend.listingStatsMatchStat===!0;for(let e of a)o.set(e.name,X(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 R(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},...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 R(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){I(e,n)}t||this.watcher?.notify([{type:`create`,path:n,entryType:`directory`}]);return}if(t?.recursive){let e=await this.withWriteLock(()=>(this.markSidecarDirty(n),this.mkdirRecursiveUnlocked(n)));e.length>0&&this.watcher?.notify(e.map(e=>({type:`create`,path:e,entryType:`directory`})))}else await this.withWriteLock(async()=>{this.markSidecarDirty(n);try{await this.lfs.mkdir(n)}catch(e){throw R(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){I(e,n)}this.watcher?.notify([{type:`delete`,path:n,entryType:e}]),this.mountIndex.notifyDelete(n);return}try{let e=await this.lfs.lstat(n);await this.withWriteLock(async()=>{e.isSymbolicLink()?await this.lfs.unlink(n):e.isDirectory()?t?.recursive?await this.rmRecursiveUnlocked(n):await this.lfs.rmdir(n):await this.lfs.unlink(n),this.markSidecarDirty(n,`prefix`),await this.writeOpfsMetadataSidecarUnlocked()})}catch(e){throw R(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.uid===void 0?{}:{uid:t.uid},...t.gid===void 0?{}:{gid:t.gid},...t.mode===void 0?{}:{mode:t.mode}}}catch(e){I(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,uid:e.uid,gid:e.gid,mode:e.mode}}catch(e){throw R(e,t)}}async exists(e){let t=i(e),n=this.findMount(t);if(n){if(n.relParts.length===0)return!0;try{return await this.stat(t),!0}catch{return!1}}try{return await this.stat(t),!0}catch{try{return await this.lfs.lstat(t),!0}catch{return!1}}}async rename(e,t){return this.withKindMismatchRetryPaths([i(e),i(t)],()=>this.renameInner(e,t))}async renameInner(e,t){let n=i(e),r=i(t),a;try{a=(await this.lstat(n)).type}catch{}let o=this.findMount(n);if(o?.backend.rename){let e=this.findMount(r);if(e&&e.backend===o.backend){try{await o.backend.rename(o.relParts.join(`/`),e.relParts.join(`/`))}catch(e){I(e,n)}this.watcher?.notify([{type:`delete`,path:n,entryType:a},{type:`create`,path:r,entryType:a}]),this.mountIndex.notifyRename(n,r);return}}try{await this.withWriteLock(async()=>{this.markSidecarDirty(n,`prefix`),this.markSidecarDirty(r,`prefix`),await this.lfs.rename(n,r),await this.writeOpfsMetadataSidecarUnlocked()})}catch(e){throw R(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*C({mountPoints:this.mountPoints,mountIndex:this.mountIndex,realpath:e=>this.realpath(e),readDir:e=>this.readDir(e),stat:e=>this.stat(e)},e,t,n)}async copyFile(e,t){if((await this.stat(e)).type===`directory`)throw new c(`EISDIR`,`is a directory`,e);let n=await this.readFile(e,{encoding:`binary`});await this.writeFile(t,n)}dirname(e){return n(i(e)).dir}basename(e){return n(i(e)).base}async symlink(e,t){let r=i(t);if(this.findMount(r))throw new c(`EINVAL`,`symlinks not supported on mounted filesystems`,r);let{dir:a}=n(r);await this.withWriteLock(async()=>{a!==`/`&&await this.mkdirRecursiveUnlocked(a);try{await this.lfs.symlink(e,r)}catch(t){if(a!==`/`&&t instanceof Error&&t.message.includes(`ENOENT`)){await this.mkdirRecursiveUnlocked(a);try{await this.lfs.symlink(e,r)}catch(e){throw R(e,r)}}else throw R(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 R(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,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,uid:e.uid,gid:e.gid,mode:e.mode}}catch(e){throw R(e,t)}}async realpath(e){return q(this.lfs,e=>this.findMount(e)!==null,e)}resolveSymlinks(e){return J(this.lfs,e=>this.findMount(e)!==null,e)}},$=e({FsError:()=>c,FsWatcher:()=>k,MountIndex:()=>d,RestrictedFS:()=>F,VirtualFS:()=>Q,joinPath:()=>o,normalizePath:()=>i,pathSegments:()=>r,resolveVfsBackendFromEnv:()=>Y,splitPath:()=>n,statsFromDirEntry:()=>s});export{k as i,Q as n,F as r,$ as t};