@yuriai/web 0.2.0-beta.7 → 0.2.0-beta.9
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.
- package/README.md +4 -0
- package/dist/assets/{AgentAvatar-CMpCBSy_.js → AgentAvatar-RbwoyGL7.js} +1 -1
- package/dist/assets/{AssistantView-CfyUDUVG.js → AssistantView-CTu_YqYq.js} +3 -3
- package/dist/assets/{DiagramView-CZg5AAli.js → DiagramView-BIhEoeWx.js} +1 -1
- package/dist/assets/{FadeInOnReveal-ANDXEIE7.js → FadeInOnReveal-Dt1nUq5y.js} +1 -1
- package/dist/assets/{GuiPluginSurface-CqqJymvB.js → GuiPluginSurface-68HtzOv6.js} +1 -1
- package/dist/assets/{GuiPluginWindow-B2G2-nAK.js → GuiPluginWindow-CMUyR2_9.js} +1 -1
- package/dist/assets/{Icon-DgrlwLKs.js → Icon-GJTjieJN.js} +1 -1
- package/dist/assets/{ImageLoadingPlaceholder-DdaN0XMj.js → ImageLoadingPlaceholder-C4VZA5iQ.js} +1 -1
- package/dist/assets/{LoadingImage-BJc5SC-0.js → LoadingImage-BZjPXN_m.js} +1 -1
- package/dist/assets/{MarkdownRenderer-DZwskKzl.js → MarkdownRenderer-DnCTLWjR.js} +2 -2
- package/dist/assets/{MarkdownRendererImpl-BQhcJNsK.js → MarkdownRendererImpl-C8HsL6On.js} +1 -1
- package/dist/assets/{MarkstreamRendererImpl-CsURmqQY.js → MarkstreamRendererImpl-B1M5pAJe.js} +1 -1
- package/dist/assets/{MobileDetailNavigation-CH4Oyt33.js → MobileDetailNavigation-BdSsbh04.js} +1 -1
- package/dist/assets/MobileResizableSheet-B8kpq7AR.js +1 -0
- package/dist/assets/{MobileShareBridge-DEDl3YCM.js → MobileShareBridge-r5Q2J_Sc.js} +2 -2
- package/dist/assets/{MobileTabPageHeader-C7Bkm6-_.js → MobileTabPageHeader-BRtaISjE.js} +1 -1
- package/dist/assets/{MultiRunWindow-DI0-Ur1w.js → MultiRunWindow-BPORsCa7.js} +1 -1
- package/dist/assets/{OnboardingScreen-BH__JnO0.js → OnboardingScreen-BssiDW_8.js} +1 -1
- package/dist/assets/{OverlayScrollbar-bByT588g.js → OverlayScrollbar-DWZJpEVx.js} +1 -1
- package/dist/assets/SettingsView-BxRekjws.js +26 -0
- package/dist/assets/{SettingsWindow-BJQyV3do.js → SettingsWindow-BsEMguoj.js} +1 -1
- package/dist/assets/{TerminalView-DRwLYPvJ.js → TerminalView-6hKAHFJ7.js} +1 -1
- package/dist/assets/{ToolOutputDialog-O25CmHgA.js → ToolOutputDialog-CkZORaFS.js} +1 -1
- package/dist/assets/{YuriLogo-Qr_mhaKp.js → YuriLogo-jfvSPXYV.js} +1 -1
- package/dist/assets/{appThemeRegistry-B-rbBHC4.js → appThemeRegistry-DdmE_Iv3.js} +1 -1
- package/dist/assets/{assistant-attachment-cache-DNbxU1Fq.js → assistant-attachment-cache-DWMcn4cE.js} +1 -1
- package/dist/assets/{button-BuhP8T0R.js → button-BgnrCA96.js} +1 -1
- package/dist/assets/{capgoAdapter-BgDvFDUs.js → capgoAdapter-Czek7cOG.js} +1 -1
- package/dist/assets/{collapsible-CwLF0o1c.js → collapsible-gafrZ0Tr.js} +1 -1
- package/dist/assets/desktop-dp2Z0toS.js +1 -0
- package/dist/assets/{desktopHosts-CjH4TGh8.js → desktopHosts-ByGjetLz.js} +1 -1
- package/dist/assets/{desktopRelayRestore-BLJo3sm7.js → desktopRelayRestore-DIO6vl1K.js} +1 -1
- package/dist/assets/{device-BVEAUyle.js → device-Dd4YwDwq.js} +1 -1
- package/dist/assets/{diagram-BIYywJNf.js → diagram-BIjHGw1_.js} +1 -1
- package/dist/assets/{dialog-BUEUatKm.js → dialog-D6jRorvP.js} +1 -1
- package/dist/assets/{dropdown-menu.styles-tzNMk1yW.js → dropdown-menu.styles-BKQriop5.js} +1 -1
- package/dist/assets/{fileMentionTouchSelection-C6ylhQkG.js → fileMentionTouchSelection-BSSggGfQ.js} +1 -1
- package/dist/assets/{fileReferenceActions-DuYvTiGf.js → fileReferenceActions-D625rOTl.js} +1 -1
- package/dist/assets/{gitApi-4JPWt45Y.js → gitApi-BkhGiTtu.js} +1 -1
- package/dist/assets/gui-BCPFcL_m.js +1 -0
- package/dist/assets/host-C6DQGHTV.js +1 -0
- package/dist/assets/{image-loading-CU4V_A1c.js → image-loading-Ctpxfqla.js} +1 -1
- package/dist/assets/{input-BVgNVYou.js → input-CDVEeuDT.js} +1 -1
- package/dist/assets/{insertionBoundaries-BSPv205d.js → insertionBoundaries-8-NDZp_y.js} +1 -1
- package/dist/assets/{main-CETRwACI.js → main-C6Yw42Pk.js} +12 -12
- package/dist/assets/{main-foDhMZ24.js → main-UQKItVb4.js} +2 -2
- package/dist/assets/{markdownHeightCache-BceTKVDK.js → markdownHeightCache-Dv5LnHPc.js} +1 -1
- package/dist/assets/{mcpQueries-AswEbyXP.js → mcpQueries-CyI_Hol5.js} +1 -1
- package/dist/assets/miniChat-tf1jH68G.js +2 -0
- package/dist/assets/mobile-C7dS2AHt.js +2 -0
- package/dist/assets/{mobileBackNavigation-C03Z5phB.js → mobileBackNavigation-Bcg-mihS.js} +1 -1
- package/dist/assets/{multirun-CWGx21Ol.js → multirun-xh4jfDx_.js} +1 -1
- package/dist/assets/native-BMAEg2E6.js +1 -0
- package/dist/assets/{native-config-DC-Ccre6.js → native-config-CKpFI_5o.js} +1 -1
- package/dist/assets/native-errors-06if6eu-.js +1 -0
- package/dist/assets/{persistence-D-W3L37Z.js → persistence-BfjCXjLZ.js} +1 -1
- package/dist/assets/{platform-CQG2KlHW.js → platform-Dcd-lkPn.js} +3 -3
- package/dist/assets/{projectMeta-6Sbr-Iiw.js → projectMeta-QJd1QrkI.js} +1 -1
- package/dist/assets/readiness-C1vgtBOT.js +1 -0
- package/dist/assets/{renderElectronMiniChatApp-CQHm04xq.js → renderElectronMiniChatApp-B84E6SfM.js} +2 -2
- package/dist/assets/{renderMobileApp-D4lOGRzz.js → renderMobileApp-PhdK6y6v.js} +4 -4
- package/dist/assets/{runtime-file-download-BdNCQkDe.js → runtime-file-download-CwP-HoXN.js} +1 -1
- package/dist/assets/{runtime-file-resource-DdAheq3y.js → runtime-file-resource-h3yIw4HU.js} +1 -1
- package/dist/assets/{runtime-file-store-hFlndg-n.js → runtime-file-store-BVRgEtI-.js} +1 -1
- package/dist/assets/runtimeConfig-CJCKi9-y.js +2 -0
- package/dist/assets/runtimeEndpointReset-Dxl8XtfH.js +149 -0
- package/dist/assets/{scheduledTaskNavigation-Cy2nZl_A.js → scheduledTaskNavigation-B7WhY2Fp.js} +1 -1
- package/dist/assets/{sessionChangeSummary-C70M_uHA.js → sessionChangeSummary-CY9vQ5i1.js} +1 -1
- package/dist/assets/{sessionLookup-CCOa3Jeq.js → sessionLookup-D1uJyExH.js} +1 -1
- package/dist/assets/{sortable-tabs-strip-CAkRGa2f.js → sortable-tabs-strip-C4STfRdG.js} +1 -1
- package/dist/assets/{speechSettingsQueries-CIcSgao2.js → speechSettingsQueries-tUWgMwuK.js} +2 -2
- package/dist/assets/src-r07HspQy.css +2 -0
- package/dist/assets/{terminalApi-DY0KJOiK.js → terminalApi-CJx_hK4K.js} +1 -1
- package/dist/assets/{textarea-BLvbQAIG.js → textarea-DI9j9018.js} +1 -1
- package/dist/assets/{tooltip-jf98dFQe.js → tooltip-BHHwyMVd.js} +1 -1
- package/dist/assets/{types-D5ocrnEK.js → types-BmLypFZI.js} +1 -1
- package/dist/assets/{useAppFontEffects-DSR2ev_Q.js → useAppFontEffects-BeFXBNUc.js} +16 -16
- package/dist/assets/{useDesktopWindowControlsLayout-pyawlD_R.js → useDesktopWindowControlsLayout-BkdDy7r3.js} +1 -1
- package/dist/assets/{useEffectiveDirectory-W6wf50T7.js → useEffectiveDirectory-RivT6KwZ.js} +1 -1
- package/dist/assets/{useFontPreferences-CH3iNDUl.js → useFontPreferences-Bwzz0JNf.js} +1 -1
- package/dist/assets/{useMobileNavigationStore-BTF3FUmY.js → useMobileNavigationStore-BQHfCZ55.js} +8 -8
- package/dist/assets/{useWorkerHighlightedLines-Dhr3xUQY.js → useWorkerHighlightedLines-BszN5sdj.js} +1 -1
- package/dist/assets/{vendor-effect-DXlObQuU.js → vendor-effect-DV9F8PTZ.js} +1 -1
- package/dist/assets/vendor-opencode-client-fxfj4IA_.js +12 -0
- package/dist/assets/{vendor-opencode-plugin-BglYYlJt.js → vendor-opencode-plugin-CQ5ogY33.js} +1 -1
- package/dist/assets/{vendor-solid-js-B2FO7pdm.js → vendor-solid-js-Dmt4_-Zk.js} +1 -1
- package/dist/index.html +17 -17
- package/dist/mini-chat.html +17 -17
- package/dist/mobile.html +17 -17
- package/package.json +1 -1
- package/server/index.d.ts +2 -0
- package/server/index.js +8 -1
- package/server/lib/content-search/DOCUMENTATION.md +5 -1
- package/server/lib/content-search/runtime.js +24 -0
- package/server/lib/content-search/runtime.test.js +19 -0
- package/server/lib/opencode/DOCUMENTATION.md +5 -0
- package/server/lib/opencode/gui-plugin-source.js +14 -0
- package/server/lib/opencode/gui-plugin-source.test.js +28 -0
- package/server/lib/opencode/plugin-gui-response.d.ts +7 -0
- package/server/lib/opencode/plugin-gui-response.js +62 -0
- package/server/lib/opencode/plugin-gui-response.test.js +89 -0
- package/server/lib/opencode/proxy.js +32 -0
- package/server/lib/relay/DOCUMENTATION.md +1 -0
- package/server/lib/request-cors.js +2 -2
- package/server/lib/request-cors.test.js +3 -0
- package/server/lib/session-index/DOCUMENTATION.md +4 -0
- package/server/lib/session-index/sync-runtime.js +3 -0
- package/server/lib/session-index/sync-runtime.test.js +18 -0
- package/server/plugin-gui-proxy.test.js +134 -0
- package/dist/assets/MobileResizableSheet-xE71zG4E.js +0 -1
- package/dist/assets/SettingsView-BVmOocRh.js +0 -26
- package/dist/assets/desktop-DpAcrF1h.js +0 -1
- package/dist/assets/gui-B56BgPNQ.js +0 -1
- package/dist/assets/host-Bs4ljApp.js +0 -1
- package/dist/assets/miniChat-Dsodcwqi.js +0 -2
- package/dist/assets/mobile-C4F47gek.js +0 -2
- package/dist/assets/readiness-DWh0yJFu.js +0 -1
- package/dist/assets/runtimeConfig-5btjngJ7.js +0 -2
- package/dist/assets/runtimeEndpointReset-NHpx5wGb.js +0 -149
- package/dist/assets/src-BR-siHj2.css +0 -2
- package/dist/assets/vendor-opencode-client-BcpAhe9I.js +0 -12
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{w as e}from"./runtime-auth-ef9W7A43.js";import{r as t,t as n}from"./runtime-switch-CAZiOV2G.js";import{t as r}from"./runtimeAPIRegistry-C2VogTny.js";var i=[`local`,`remote`,null],a=[`ok`,`not-configured`,`unreachable`,`incompatible`,`wrong-service`,`missing`];function o(e){if(!e||typeof e!=`object`)return{valid:!1};let t=e,n=t.target,r=t.status;if(n!==null&&(typeof n!=`string`||!i.includes(n))||typeof r!=`string`||!a.includes(r))return{valid:!1};if(n===`remote`||n===`local`){if(r===`ok`&&n===`local`)return{valid:!0,outcome:{target:`local`,status:`ok`}};if(r===`ok`&&n===`remote`)return typeof t.hostId!=`string`||typeof t.url!=`string`?{valid:!1}:{valid:!0,outcome:{target:`remote`,status:`ok`,hostId:t.hostId,url:t.url}};if(r===`unreachable`)return n===`local`?{valid:!0,outcome:{target:`local`,status:`unreachable`}}:typeof t.hostId!=`string`||typeof t.url!=`string`?{valid:!1}:{valid:!0,outcome:{target:`remote`,status:`unreachable`,hostId:t.hostId,url:t.url}};if(r===`incompatible`||r===`wrong-service`)return n!==`remote`||typeof t.hostId!=`string`||typeof t.url!=`string`?{valid:!1}:{valid:!0,outcome:{target:`remote`,status:r,hostId:t.hostId,url:t.url}};if(r===`missing`)return n!==`remote`||typeof t.hostId!=`string`?{valid:!1}:{valid:!0,outcome:{target:`remote`,status:`missing`,hostId:t.hostId}}}if(n===null){if(r===`not-configured`)return{valid:!0,outcome:{target:null,status:`not-configured`}};if(r===`missing`)return{valid:!1}}return{valid:!1}}function s(e){if(!e.isDesktopShell)return null;let t=e.bootOutcome;if(!t)return null;if(t.status===`ok`){if(t.target===`local`)return{screen:`main`};if(t.target===`remote`)return{screen:`main`,hostId:t.hostId,url:t.url}}if(t.target===null&&t.status===`not-configured`)return{screen:`chooser`};if(t.target===`local`&&t.status===`unreachable`)return{screen:`recovery`,variant:`local-unavailable`};if(t.target===`remote`){if(t.status===`unreachable`)return{screen:`recovery`,variant:`remote-unreachable`,hostId:t.hostId,url:t.url};if(t.status===`incompatible`)return{screen:`recovery`,variant:`remote-incompatible`,hostId:t.hostId,url:t.url};if(t.status===`wrong-service`)return{screen:`recovery`,variant:`remote-wrong-service`,hostId:t.hostId,url:t.url};if(t.status===`missing`)return{screen:`recovery`,variant:`remote-missing`,hostId:t.hostId}}return null}function c(e){return e.isDesktopShell?e.bootOutcomeKnown?e.bootViewIsMain===!1||e.isInitialized:!1:e.isInitialized}function l(e){return e.isDesktopShell&&!e.isDesktopLocalOriginActive}function u(){if(f()!==`valid`)return null;let e=o(d());return e.valid?e.outcome:null}var d=()=>{if(typeof window>`u`)return;let e=window.__YURI_DESKTOP_BOOT_OUTCOME__;if(e!=null)return e;let t=window.__YURI_DESKTOP_BOOT__;if(t&&typeof t.getOutcome==`function`)try{return t.getOutcome()}catch{return}return e};function f(){if(typeof window>`u`)return`not-injected`;let e=d();return e==null?`not-injected`:o(e).valid?`valid`:`malformed`}var p=()=>typeof window>`u`?null:window.__YURI_ELECTRON__??null,m=()=>typeof window>`u`?null:window.__YURI_DESKTOP__??null,h=()=>p()?.runtime===`electron`,g=()=>h()&&p()?.packaged===!0,_=e=>{if(!h())return null;let t=m()?.getPathForFile?.(e);return typeof t==`string`&&t.trim()?t:null},v=()=>{if(typeof window>`u`)return null;let e=window.__YURI_PLATFORM__;return typeof e==`string`?e:null},ee=()=>{if(!h())return!1;let e=v();return e===`win32`||e===`linux`},y=(e=v())=>e===`linux`?`left`:`right`,b=(e,t=v())=>e===`left`||e===`right`?e:y(t),x=()=>typeof m()?.invoke==`function`,S=()=>h()&&x(),C=()=>h()&&F()?m()?.guiPlugins:void 0,w=()=>h()?m()?.guiPlugins:void 0,T=()=>h()?m()?.viewExport:void 0,E=async(e,t)=>{let n=m();return typeof n?.invoke==`function`?n.invoke(e,t??{}):null},te=async()=>{if(!S()||!F())return null;try{let e=await E(`desktop_get_launch_at_login`);return!e||typeof e.supported!=`boolean`||typeof e.enabled!=`boolean`?null:e}catch(e){return console.warn(`Failed to get launch at login status`,e),null}},ne=async e=>{if(!S()||!F())return null;try{let t=await E(`desktop_set_launch_at_login`,{enabled:e});return!t||typeof t.supported!=`boolean`||typeof t.enabled!=`boolean`?null:t}catch(e){return console.warn(`Failed to set launch at login status`,e),null}},D=async()=>{if(!S()||!F())return null;try{let e=await E(`desktop_get_minimize_to_tray`);return!e||typeof e.supported!=`boolean`||typeof e.enabled!=`boolean`?null:e}catch(e){return console.warn(`Failed to get minimize to tray status`,e),null}},O=async e=>{if(!S()||!F())return null;try{let t=await E(`desktop_set_minimize_to_tray`,{enabled:e});return!t||typeof t.supported!=`boolean`||typeof t.enabled!=`boolean`?null:t}catch(e){return console.warn(`Failed to set minimize to tray status`,e),null}},k=async()=>{if(!S()||!F())return null;try{let e=await E(`desktop_get_keep_awake`);return!e||typeof e.supported!=`boolean`||typeof e.enabled!=`boolean`||typeof e.active!=`boolean`?null:e}catch(e){return console.warn(`Failed to get keep awake status`,e),null}},A=async e=>{if(!S()||!F())return null;try{let t=await E(`desktop_set_keep_awake`,{enabled:e});return!t||typeof t.supported!=`boolean`||typeof t.enabled!=`boolean`||typeof t.active!=`boolean`?null:t}catch(e){return console.warn(`Failed to set keep awake status`,e),null}},j=e=>{let t=e.trim();if(!t)return null;try{return new URL(t).origin}catch{try{return new URL(t.endsWith(`/`)?t:`${t}/`).origin}catch{return null}}},M=e=>{let t=e.trim();if(!t)return null;try{return new URL(t)}catch{try{return new URL(t.endsWith(`/`)?t:`${t}/`)}catch{return null}}},N=e=>e.replace(/^\[|\]$/g,``).toLowerCase(),P=e=>{let t=N(e);return t===`localhost`||t===`127.0.0.1`||t===`::1`},F=()=>{if(typeof window>`u`||!I()||e())return!1;let r=t();if(r.startsWith(`host:`))return!1;if(r===`local`)return!0;let i=typeof window.__YURI_LOCAL_ORIGIN__==`string`?window.__YURI_LOCAL_ORIGIN__:``,a=M(i),o=M(n());if(!o&&a&&u()?.target===`local`)return!0;if(a&&o){if(a.origin===o.origin)return!0;let e=a.port||(a.protocol===`https:`?`443`:`80`),t=o.port||(o.protocol===`https:`?`443`:`80`);return a.protocol===o.protocol&&e===t&&P(a.hostname)&&P(o.hostname)}let s=M(window.location.origin);if(a&&s){if(a.origin===s.origin)return!0;let e=a.port||(a.protocol===`https:`?`443`:`80`),t=s.port||(s.protocol===`https:`?`443`:`80`);return a.protocol===s.protocol&&e===t&&P(a.hostname)&&P(s.hostname)}let c=j(i),l=j(window.location.origin)||window.location.origin;return c&&l&&c===l?!0:!!(s&&P(s.hostname))},I=()=>typeof window>`u`?!1:h(),L=async()=>{if(!I())return!1;try{return await E(`desktop_start_window_drag`),!0}catch{return!1}},R=()=>r()?.runtime?.isVSCode===!0,z=()=>{let e=r()?.runtime?.platform;return e===`web`?!0:e===`desktop`||e===`vscode`?!1:!R()},B=async()=>{if(typeof window<`u`){let e=window.__YURI_HOME__;if(e&&e.length>0)return e}return null},V=async e=>{if(x()&&F())try{let e=await m()?.openDialog?.({directory:!0,multiple:!1,title:`Select Working Directory`});return!e||typeof e!=`string`?{success:!1,error:`Directory selection cancelled`}:{success:!0,path:e}}catch(e){return console.warn(`Failed to request directory access`,e),{success:!1,error:e instanceof Error?e.message:String(e)}}return{success:!0,path:e}},H=e=>typeof e==`object`&&!!e&&!Array.isArray(e),re=async e=>{if(x()&&F())try{let t=await m()?.openDialog?.({directory:!1,multiple:!1,title:`Select File`,returnGrant:!0,...e?.filters?{filters:e.filters}:{},...e?.defaultPath?{defaultPath:e.defaultPath}:{}});if(!t)return{success:!1,error:`File selection cancelled`};if(typeof t==`string`)return{success:!0,path:t};if(!H(t))return{success:!1,error:`File selection cancelled`};let n=typeof t.path==`string`?t.path:``;return n?{success:!0,path:n,outsideFileGrant:typeof t.outsideFileGrant==`string`?t.outsideFileGrant:void 0}:{success:!1,error:`File selection cancelled`}}catch(e){return console.warn(`Failed to request file access`,e),{success:!1,error:e instanceof Error?e.message:String(e)}}return{success:!1,error:`Native file picker not available`}},U=async e=>{let t=typeof e==`string`?e.trim():``;if(!t)return{success:!1,error:`Path is required`};if(!x()||!F())return{success:!1,error:`Native file access not available`};try{let e=await m()?.grantFileAccess?.(t);if(!H(e))return{success:!1,error:`File access was not granted`};let n=typeof e.path==`string`?e.path:``,r=typeof e.outsideFileGrant==`string`?e.outsideFileGrant:``;return!n||!r?{success:!1,error:`File access was not granted`}:{success:!0,path:n,outsideFileGrant:r}}catch(e){return console.warn(`Failed to request existing file access`,e),{success:!1,error:e instanceof Error?e.message:String(e)}}},W=async e=>({success:!0}),G=async e=>({success:!0}),K=async e=>{if(!x())throw Error(`Desktop update checker is unavailable`);let t=await E(`desktop_check_for_updates`,{channelOverride:e});if(!t)throw Error(`Desktop update checker returned no result`);return t},q=async e=>{x()&&await E(`desktop_ota_ready`,{version:e})},J=()=>E(`desktop_get_app_version`),Y=async e=>{let t=m();return typeof t?.listen==`function`?t.listen(`yuri:update-progress`,t=>{let n=t?.payload;if(!n||typeof n!=`object`)return;let r=n;e({event:typeof r.event==`string`?r.event:void 0,data:r.data&&typeof r.data==`object`?r.data:void 0})}):null},X=async e=>{let t=m();return typeof t?.listen==`function`?t.listen(`yuri:update-ready`,t=>{let n=t?.payload;if(!n||typeof n!=`object`)return;let r=n;e({version:typeof r.version==`string`?r.version:null,downloaded:r.downloaded===!0})}):null},ie=async e=>{if(!x())return!1;let t=m(),n=null,r=0,i;try{return typeof e==`function`&&t?.listen&&(n=await t.listen(`yuri:update-progress`,t=>{let n=t?.payload;if(!n||typeof n!=`object`)return;let a=n,o=typeof a.event==`string`?a.event:null,s=a.data&&typeof a.data==`object`?a.data:null;if(o===`Started`){r=0,i=typeof s?.contentLength==`number`?s.contentLength:void 0,e({downloaded:r,total:i});return}if(o===`Progress`){let t=s?.downloaded,n=s?.total;typeof t==`number`&&(r=t),typeof n==`number`&&(i=n),e({downloaded:r,total:i});return}o===`Finished`&&e({downloaded:r,total:i})})),await E(`desktop_download_and_install_update`),!0}catch(e){throw e instanceof Error?e:Error(String(e))}finally{if(n)try{let e=n();e instanceof Promise&&await e}catch{}}},ae=async()=>x()?Z({applyUpdate:!0}):!1,Z=async({applyUpdate:e=!1}={})=>{if(!x())return!1;try{return await E(`desktop_restart`,e?{applyUpdate:!0}:void 0),!0}catch(e){return console.warn(`Failed to restart desktop app`,e),!1}},oe=async()=>{if(!x()||!F())return null;try{let e=await E(`desktop_get_lan_address`);return typeof e==`string`&&e.trim().length>0?e.trim():null}catch(e){return console.warn(`Failed to get desktop LAN address`,e),null}},Q=async(e,t)=>{if(!x()||!F())return!1;let n=e?.trim();if(!n)return!1;try{return await E(`desktop_open_path`,{path:n,app:typeof t==`string`&&t.trim().length>0?t.trim():void 0}),!0}catch(e){return console.warn(`Failed to open path`,e),!1}},$=async e=>{if(!x()||!F())return null;let t=e?.trim();if(!t)return null;try{let e=await E(`desktop_is_binary_path`,{path:t});return typeof e==`boolean`?e:null}catch{return null}},se=async e=>{if(!x()||!F())return!1;let t=e?.trim();if(!t)return!1;try{return await E(`desktop_reveal_path`,{path:t}),!0}catch{return Q(t)}},ce=async(e,t)=>{if(!x()||!F())return null;let n=e?.trim();if(!n)return null;try{let e=await E(`desktop_save_markdown_file`,{defaultFileName:n,content:t});return typeof e==`string`&&e.trim().length>0?e:null}catch(e){return console.warn(`Failed to save markdown file`,e),null}},le=async(e,n,r,i)=>{if(!x()||!i&&!F())return!1;if(i)return t()===`host:${i}`&&(await E(`desktop_open_ssh_in_app`,{projectPath:e,appId:n,hostId:i}),!0);let a=e?.trim(),o=n?.trim(),s=r?.trim();if(!a||!o||!s)return!1;try{return await E(`desktop_open_in_app`,{projectPath:a,appId:o,appName:s}),!0}catch(e){return console.warn(`Failed to open project in app`,e),!1}},ue=async(e,t,n)=>{if(!x()||!F())return!1;let r=e?.trim(),i=t?.trim(),a=n?.trim();if(!r||!i||!a)return!1;try{return await E(`desktop_open_file_in_app`,{filePath:r,appId:i,appName:a}),!0}catch(e){return console.warn(`Failed to open file in app`,e),!1}},de=async(e,t)=>{if(!x())return{apps:[],success:!1,hasCache:!1,isCacheStale:!1};if(v()===`linux`)return{apps:[],success:!0,hasCache:!1,isCacheStale:!1};let n=Array.isArray(e)?e.filter(e=>typeof e==`string`):[];if(n.length===0)return{apps:[],success:!0,hasCache:!1,isCacheStale:!1};try{let e=await E(`desktop_get_installed_apps`,{apps:n,force:t===!0||void 0});if(!e||typeof e!=`object`)return{apps:[],success:!1,hasCache:!1,isCacheStale:!1};let r=e;return r.supported===!1?{apps:[],success:!0,hasCache:!1,isCacheStale:!1}:Array.isArray(r.apps)?{apps:r.apps.filter(e=>e&&typeof e==`object`).map(e=>{let t=e;return{name:typeof t.name==`string`?t.name:``,iconDataUrl:typeof t.iconDataUrl==`string`?t.iconDataUrl:null}}).filter(e=>e.name.length>0),success:!0,hasCache:r.hasCache===!0,isCacheStale:r.isCacheStale===!0}:{apps:[],success:!1,hasCache:!1,isCacheStale:!1}}catch(e){return console.warn(`Failed to fetch installed apps`,e),{apps:[],success:!1,hasCache:!1,isCacheStale:!1}}};export{le as A,ne as B,R as C,q as D,X as E,Z as F,ee as G,W as H,ae as I,u as J,c as K,se as L,U as M,re as N,ue as O,b as P,ce as R,g as S,Y as T,L as U,O as V,G as W,l as X,s as Y,E as _,J as a,I as b,B as c,te as d,D as f,x as g,v as h,de as i,V as j,Q as k,k as l,_ as m,K as n,C as o,T as p,f as q,ie as r,w as s,S as t,oe as u,$ as v,z as w,h as x,F as y,A as z};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{E as e}from"./runtime-auth-ef9W7A43.js";import{
|
|
1
|
+
import{E as e}from"./runtime-auth-ef9W7A43.js";import{_ as t,g as n}from"./desktop-dp2Z0toS.js";var r=e=>typeof e==`object`&&!!e,i=e=>e.trim().toLowerCase()===`authorization`,a=e=>{if(!r(e))return;let t={};for(let[n,r]of Object.entries(e)){let e=n.trim(),a=typeof r==`string`?r.trim():``;!e||!a||/[\r\n:]/.test(e)||/[\r\n]/.test(a)||i(e)||(t[e]=a)}return Object.keys(t).length>0?t:void 0},o=`connect-link`,s=(e,t)=>e.source===`connect-link`||e.relay?!0:t.has(e.id),c=(e,t)=>!!(e&&!e.relay&&t.has(e.id)),l=(e,t)=>!t.has(e.id)&&s(e,t),u=e=>`relay://${e}`,d=e=>{if(!r(e))return null;let t=_(e,`relayUrl`)||_(e,`relay_url`),n=_(e,`serverId`)||_(e,`server_id`),i=e.hostEncPubJwk??e.host_enc_pub_jwk;return!t||!n||!r(i)?null:{relayUrl:t,serverId:n,hostEncPubJwk:i}},f=/^(t|.*(?:token|auth|secret|api).*)$/i,p=e=>{let t=e.trim();if(!t)return null;try{let e=new URL(t);return e.protocol!==`http:`&&e.protocol!==`https:`?null:t.split(`#`)[0]||null}catch{return null}},m=e=>{let t=p(e);if(!t)return null;try{let e=new URL(t);if((e.pathname.replace(/\/+$/,``)||`/`)===`/connect`&&e.searchParams.has(`t`))return{persistedUrl:e.origin,redeemUrl:e.toString(),kind:`tunnel-connect-link`}}catch{return null}return{persistedUrl:t,redeemUrl:null,kind:`normal-host`}},h=e=>{let t=p(e);if(!t)return e;try{let e=new URL(t);(e.username||e.password)&&(e.username=``,e.password=``);let n=Array.from(new Set(Array.from(e.searchParams.keys())));for(let t of n)f.test(t)&&e.searchParams.set(t,`[REDACTED]`);return e.toString()}catch{return t}},g=(e,t)=>{let n=p(e),r=p(t);if(!n||!r)return!1;try{let e=new URL(n),t=new URL(r);if(e.origin!==t.origin||t.search&&e.search!==t.search)return!1;let i=t.pathname.length>1?t.pathname.replace(/\/+$/,``):t.pathname,a=e.pathname.length>1?e.pathname.replace(/\/+$/,``):e.pathname;return i===`/`||a===i||a.startsWith(`${i}/`)}catch{return!1}},_=(e,t)=>{let n=e[t];return typeof n==`string`?n:null},v=(e,t)=>{let n=e[t];return typeof n==`number`&&Number.isFinite(n)?n:null},y=e=>{if(!r(e))return null;let t=_(e,`id`),n=_(e,`label`),i=_(e,`url`),s=_(e,`apiUrl`)||_(e,`api_url`),c=_(e,`clientToken`)||_(e,`client_token`),l=a(e.requestHeaders),u=d(e.relay),f=_(e,`source`)===`connect-link`?o:void 0;return!t||!n||!i&&!u?null:{id:t,label:n,url:i||``,...s?{apiUrl:s}:{},...c?{clientToken:c}:{},...l?{requestHeaders:l}:{},...u?{relay:u}:{},...f?{source:f}:{}}},b=e=>p(e.apiUrl||e.url)||e.apiUrl||e.url,x=()=>n()?(e,n)=>t(e,n):null,S=async()=>{let e=x();if(!e)return{hosts:[],defaultHostId:null,initialHostChoiceCompleted:!1};let t=await e(`desktop_hosts_get`);if(!r(t))return{hosts:[],defaultHostId:null,initialHostChoiceCompleted:!1};let n=t.hosts;return{hosts:Array.isArray(n)?n.map(y).filter(e=>!!e):[],defaultHostId:_(t,`defaultHostId`)||_(t,`default_host_id`)||_(t,`defaultHostID`),initialHostChoiceCompleted:t.initialHostChoiceCompleted===!0||t.initial_host_choice_completed===!0,localOrigin:_(t,`localOrigin`)||_(t,`local_origin`)}},C=async e=>{let t=x();if(!t)return;let n={hosts:e.hosts,defaultHostId:e.defaultHostId,initialHostChoiceCompleted:e.initialHostChoiceCompleted};e.localClientToken!==void 0&&(n.localClientToken=e.localClientToken),await t(`desktop_hosts_set`,{input:n})},w=async e=>{let t=x();if(!t)throw Error(`Desktop host preparation is unavailable`);let n=y(await t(`desktop_host_prepare`,{hostId:e.id}));if(!n||n.id!==e.id)throw Error(`Invalid prepared desktop host`);return n},T=async()=>{let e=x();if(!e)return``;let t=await e(`desktop_local_client_token_get`).catch(()=>null);return typeof t==`string`?t.trim():``},E=async()=>{let e=x();if(!e)return``;let t=await e(`desktop_install_id_get`).catch(()=>null);return typeof t==`string`?t.trim():``},D=8e3,O=async(t,n)=>{let r=e({relayUrl:t.relayUrl,serverId:t.serverId,hostEncPubJwk:t.hostEncPubJwk}),i=Date.now(),a=!1,o;try{let e=await Promise.race([(async()=>{let e=await r.fetch(`/auth/session`,{headers:n?.clientToken?{Authorization:`Bearer ${n.clientToken}`}:{}});return{response:e,payload:e.ok?await e.json().catch(()=>null):null}})(),new Promise(e=>{o=setTimeout(()=>e(null),D)})]),t=e?.response;return t?.status===401||t?.status===403?{status:`auth`,latencyMs:Math.max(0,Date.now()-i)}:t?.ok?e?.payload?.authenticated===!0?(a=n?.keepTunnel===!0,{status:`ok`,latencyMs:Math.max(0,Date.now()-i),...a?{tunnel:r}:{}}):{status:`auth`,latencyMs:Math.max(0,Date.now()-i)}:{status:`unreachable`,latencyMs:0}}catch{return{status:`unreachable`,latencyMs:0}}finally{o!==void 0&&clearTimeout(o),a||r.close()}},k=async(e,t)=>{let n=x();if(!n)return{status:`unreachable`,latencyMs:0};let i=await n(`desktop_host_probe`,{url:e,clientToken:t?.clientToken||void 0,requestHeaders:t?.requestHeaders||void 0,expectedServerId:t?.expectedServerId||void 0});if(!r(i))return{status:`unreachable`,latencyMs:0};let a=i.status;return{status:a===`ok`||a===`auth`||a===`update-recommended`||a===`incompatible`||a===`wrong-service`||a===`unreachable`?a:`unreachable`,latencyMs:v(i,`latencyMs`)??v(i,`latency_ms`)??0}},A=async(e,t)=>{let n=x();n&&await n(`desktop_new_window_at_url`,{url:e,clientToken:t?.clientToken||void 0,requestHeaders:t?.requestHeaders||void 0})},j=async e=>{let t=x();t&&await t(`desktop_new_window_for_host`,{hostId:e})};export{u as _,E as a,j as c,l as d,s as f,h as g,O as h,C as i,w as l,p as m,k as n,T as o,g as p,S as r,A as s,o as t,b as u,m as v,c as y};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{b as e}from"./runtime-auth-ef9W7A43.js";import{l as t,n,r}from"./runtime-switch-CAZiOV2G.js";import{n as i}from"./runtime-fetch-BAN5Gnnp.js";import{
|
|
1
|
+
import{b as e}from"./runtime-auth-ef9W7A43.js";import{l as t,n,r}from"./runtime-switch-CAZiOV2G.js";import{n as i}from"./runtime-fetch-BAN5Gnnp.js";import{x as a}from"./desktop-dp2Z0toS.js";import{h as o,i as s,l as c,m as l,n as u,r as d,u as f}from"./desktopHosts-ByGjetLz.js";var p=e=>e!==`ok`&&e!==`update-recommended`,m=e=>e.id===`local`?`local`:`host:${e.id}`,h=e=>r()===m(e),g=async(n,r)=>{if(!a())return{ok:!1,status:{status:`unreachable`,latencyMs:0},reason:`unsupported`};n=await c(n);let i=l(f(n))||``;if(!i&&!n.relay)return{ok:!1,status:{status:`unreachable`,latencyMs:0},reason:`unreachable`};let s=(r,i)=>{i&&e({relayUrl:r.relayUrl,serverId:r.serverId,hostEncPubJwk:r.hostEncPubJwk},i),t({apiBaseUrl:C(),clientToken:n.clientToken||null,runtimeKey:m(n),relay:r}),T(n.id)},d=e=>{t({apiBaseUrl:e,clientToken:n.clientToken||null,requestHeaders:n.requestHeaders||null,runtimeKey:m(n)})},h={status:`unreachable`,latencyMs:0},g=null,_;if(i){let e=await u(i,{clientToken:n.clientToken||null,requestHeaders:n.requestHeaders||null,expectedServerId:n.relay?.serverId||null}).catch(()=>({status:`unreachable`,latencyMs:0}));h={status:e.status,latencyMs:e.latencyMs},p(e.status)||(g=`direct`)}if(!g&&n.relay){let e=await o(n.relay,{keepTunnel:!0,clientToken:n.clientToken||null}).catch(()=>({status:`unreachable`,latencyMs:0}));e.status===`ok`?(h={status:e.status,latencyMs:e.latencyMs,via:`relay`},g=`relay`,_=`tunnel`in e?e.tunnel:void 0):(!i||e.status===`auth`)&&(h={status:e.status,latencyMs:e.latencyMs})}return g?g===`relay`&&n.relay?(s(n.relay,_),{ok:!0,via:`relay`,status:h}):(d(i),{ok:!0,via:`direct`,status:h}):{ok:!1,status:h,reason:`unreachable`}},_=5e3,v=1500,y=e=>e===`ok`||e===`update-recommended`,b=!1,x=()=>{if(typeof window>`u`)return``;let e=window.__YURI_LOCAL_ORIGIN__;return typeof e==`string`?e.trim():``},S=e=>{if(!e||e===`null`)return!1;try{let t=new URL(e);return(t.protocol===`http:`||t.protocol===`https:`)&&t.origin!==`null`}catch{return!1}},C=()=>{if(typeof window>`u`)return``;let e=window.location.origin;if(S(e))return e;let t=x();return S(t)?t:``},w=async e=>{if(!a()||b)return;let o=`host:${e}`;if(r()!==o)return;let c=n(),f=()=>r()===o&&n()===c;b=!0;try{let n=await d().catch(()=>null);if(!f())return;let r=n?.hosts.find(t=>t.id===e);if(!n||!r?.relay)return;let a=r.apiUrl?l(r.apiUrl):null;if(a&&a.startsWith(`https://`))return;let c=await i(`/api/client-auth/connection/candidates`).catch(()=>null);if(!c?.ok)return;let p=await c.json().catch(()=>null);if(!f()||!p||p.serverId!==r.relay.serverId)return;let m=Array.isArray(p.candidates)?p.candidates:[],h=[];for(let e of m){if(!e||typeof e!=`object`)continue;let t=e;if(t.type!==`lan`||typeof t.url!=`string`)continue;let n=l(t.url);n&&!h.includes(n)&&h.push(n)}if(h.length===0)return;let g=a&&h.includes(a)?a:h[0];if(g!==a&&await s({hosts:n.hosts.map(t=>t.id===e?{...t,apiUrl:g}:t),defaultHostId:n.defaultHostId,initialHostChoiceCompleted:n.initialHostChoiceCompleted}).catch(()=>void 0),!f()||!y((await u(g,{clientToken:r.clientToken||null,requestHeaders:r.requestHeaders||null,expectedServerId:r.relay.serverId}).catch(()=>({status:`unreachable`,latencyMs:0}))).status)||!f())return;t({apiBaseUrl:g,clientToken:r.clientToken||null,requestHeaders:r.requestHeaders||null,runtimeKey:o})}finally{b=!1}},T=e=>{typeof window>`u`||window.setTimeout(()=>{w(e).catch(()=>void 0)},_)},E=async e=>{if(!a())return;let i=r(),o=n(),s=()=>r()===i&&n()===o,c=await d().catch(()=>null);if(!c||!s())return;let p=e||(c.defaultHostId===`local`?null:c.defaultHostId);if(!p)return;let h=c.hosts.find(e=>e.id===p);if(!h?.relay)return;let g=m(h);if(r()===g)return;let _=e=>{t({apiBaseUrl:e,clientToken:h.clientToken||null,requestHeaders:h.requestHeaders||null,runtimeKey:g})},b=()=>{t({apiBaseUrl:C(),clientToken:h.clientToken||null,runtimeKey:g,relay:h.relay??void 0}),T(h.id)},x=h.apiUrl?l(f(h)):null;if(!x){b();return}let S=e=>y(e.status),w=u(x,{clientToken:h.clientToken||null,requestHeaders:h.requestHeaders||null,expectedServerId:h.relay.serverId}).catch(()=>({status:`unreachable`,latencyMs:0})),E=await Promise.race([w,new Promise(e=>setTimeout(()=>e(null),v))]);if(s()){if(E){if(S(E)){_(x);return}b();return}b()}};export{g as i,h as n,m as r,E as t};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/vendor-aparajita-capacitor-secure-storage-xol_6BsB.js","assets/rolldown-runtime-hePW80VL.js"])))=>i.map(i=>d[i]);
|
|
2
|
-
import{r as e}from"./rolldown-runtime-hePW80VL.js";import{
|
|
2
|
+
import{r as e}from"./rolldown-runtime-hePW80VL.js";import{C as t,b as n}from"./desktop-dp2Z0toS.js";import{it as r}from"./vendor-base-ui-CdzJ6My_.js";import{n as i}from"./platform-Dcd-lkPn.js";import"./brand-storage-bootstrap-D4BW3w-M.js";import{n as a}from"./vendor-react-BP2cRVqX.js";import{o}from"./vendor-aparajita-capacitor-secure-storage-xol_6BsB.js";var s=e(r(),1),c=a(),l=.85,u=1.2,d=10/9,f=.9,p=.98,m=p/f,h=`yuri.designPtScale.v8`;function g(e){return!Number.isFinite(e)||e<=0?1:Math.min(u,Math.max(l,e))}function _(e){if(!e)return p;let t=e.density,n=(e.xdpi+e.ydpi)/2;if(!(t>0)||!(n>=50)||n>800)return p;let r=g(n/t/163);return Math.min(p,r*m)}function v(){if(typeof window>`u`)return 1;try{let e=Number.parseFloat(window.localStorage.getItem(`yuri.designPtScale.v8`)??``),t=window.Capacitor?.getPlatform?.();return t===`android`?Math.min(p,g(e)):t===`ios`?d:g(e)}catch{return 1}}function y(e){if(!(typeof window>`u`))try{window.localStorage.setItem(h,String(e))}catch{}}function b(e,t=document.documentElement){let n=g(e);t.style.setProperty(`--dpt`,`${n}px`),t.style.setProperty(`--dpt-n`,String(n))}async function x(){if(typeof document>`u`)return 1;b(v());let{Capacitor:e,registerPlugin:t}=await o(async()=>{let{Capacitor:e,registerPlugin:t}=await import(`./vendor-aparajita-capacitor-secure-storage-xol_6BsB.js`).then(e=>e.i);return{Capacitor:e,registerPlugin:t}},__vite__mapDeps([0,1]));if(!e.isNativePlatform())return b(1),1;if(e.getPlatform()===`ios`)return b(d),y(d),d;if(e.getPlatform()!==`android`)return b(1),1;if(!e.isPluginAvailable(`YuriPhysicalScale`))return b(p),y(p),p;try{let e=_(await t(`YuriPhysicalScale`).getMetrics());return y(e),b(e),e}catch{return b(p),y(p),p}}var S={xs:0,sm:640,md:768,lg:1024,xl:1280,"2xl":1536},C={isMobile:!1,isTablet:!1,isDesktop:!0,deviceType:`desktop`,screenWidth:1024,breakpoint:`lg`,hasTouchInput:!1,hasTouchOnlyPointer:!1},w=()=>typeof window>`u`?!1:new URLSearchParams(window.location.search).get(`surface`)===`desktop`,T=e=>{if(typeof navigator>`u`)return{isExplicitTablet:!1};let t=navigator.userAgent||``,n=navigator.platform||``,r=/iPad/i.test(t)||(/Macintosh|MacIntel/i.test(t)||/MacIntel/i.test(n))&&e>1,i=/Android/i.test(t)&&!/Mobile/i.test(t),a=/Tablet/i.test(t);return{isExplicitTablet:r||i||a}},E=(e,t,n)=>{if(typeof window>`u`)return;let r=document.documentElement,i=t===`mobile`,a=t===`tablet`;r.classList.remove(`device-mobile`,`device-tablet`,`device-desktop`),r.classList.add(t===`mobile`?`device-mobile`:t===`tablet`?`device-tablet`:`device-desktop`),e?(r.classList.add(`desktop-runtime`),r.style.setProperty(`--is-mobile`,`0`),r.style.setProperty(`--device-type`,`desktop`),r.style.setProperty(`--font-scale`,`1`),r.style.setProperty(`--has-coarse-pointer`,`0`),r.style.setProperty(`--has-touch-input`,`0`),r.classList.remove(`mobile-pointer`)):(r.classList.remove(`desktop-runtime`),r.style.setProperty(`--is-mobile`,i?`1`:`0`),r.style.setProperty(`--device-type`,t),r.style.setProperty(`--font-scale`,i?`0.9`:a?`0.95`:`1`),r.style.setProperty(`--has-coarse-pointer`,n?`1`:`0`),r.style.setProperty(`--has-touch-input`,n?`1`:`0`),n?r.classList.add(`mobile-pointer`):r.classList.remove(`mobile-pointer`)),b(e?1:v(),r)};function D(){let e=window.innerWidth,r=typeof window.matchMedia==`function`,a=r?window.matchMedia(`(pointer: coarse)`):null,o=r?window.matchMedia(`(hover: none)`):null,s=a?.matches??!1,c=o?.matches??!1,l=typeof navigator<`u`?navigator.maxTouchPoints??0:0,u=n()||t()||w(),{isExplicitTablet:d}=T(l),f=s||c||l>0,p=s||c,m=e>S.md&&e<=S.lg,h=e<=S.md,g=f&&h,_=f&&!g&&(m||d),v=!f||!_&&e>S.lg,y=`desktop`;u?(g=!1,_=!1,v=!0,y=`desktop`):i()?(g=!0,_=!1,v=!1,y=`mobile`):g?y=`mobile`:_?y=`tablet`:(v=!0,y=`desktop`),E(u,y,f);let b=`xs`;for(let[t,n]of Object.entries(S))e>=n&&(b=t);return{isMobile:g,isTablet:_,isDesktop:v,deviceType:y,screenWidth:e,breakpoint:b,hasTouchInput:f,hasTouchOnlyPointer:p}}var O=(e,t)=>e.isMobile===t.isMobile&&e.isTablet===t.isTablet&&e.isDesktop===t.isDesktop&&e.deviceType===t.deviceType&&e.screenWidth===t.screenWidth&&e.breakpoint===t.breakpoint&&e.hasTouchInput===t.hasTouchInput&&e.hasTouchOnlyPointer===t.hasTouchOnlyPointer,k=new Set,A=null,j,M=null,N=()=>typeof window>`u`?C:(A||=D(),A),P=()=>{for(let e of k)e()},F=()=>{j=void 0;let e=D();A&&O(A,e)||(A=e,P())},I=()=>{typeof window>`u`||j!==void 0||(j=window.requestAnimationFrame(F))},L=(e,t)=>e?typeof e.addEventListener==`function`?(e.addEventListener(`change`,t),()=>e.removeEventListener(`change`,t)):typeof e.addListener==`function`?(e.addListener(t),()=>e.removeListener(t)):()=>{}:()=>{},R=()=>{if(typeof window>`u`)return()=>{};A=D(),window.addEventListener(`resize`,I);let e=typeof window.matchMedia==`function`?window.matchMedia(`(pointer: coarse)`):null,t=typeof window.matchMedia==`function`?window.matchMedia(`(hover: none)`):null,n=L(e,I),r=L(t,I);return()=>{window.removeEventListener(`resize`,I),n(),r(),j!==void 0&&(window.cancelAnimationFrame(j),j=void 0)}},z=e=>typeof window>`u`?()=>{}:(k.add(e),M||=R(),()=>{k.delete(e),k.size===0&&M&&(M(),M=null,A=null)});function B(){if(typeof window>`u`||typeof window<`u`&&n())return!1;let e=document.documentElement,t=e.style.getPropertyValue(`--is-mobile`)||getComputedStyle(e).getPropertyValue(`--is-mobile`);return t===`1`||t===`true`}var V=()=>typeof window>`u`?!1:!!(navigator.standalone===!0||window.matchMedia?.(`(display-mode: standalone)`)?.matches||window.matchMedia?.(`(display-mode: fullscreen)`)?.matches),H=()=>{if(typeof window>`u`||n())return!1;let e=typeof navigator<`u`?navigator.maxTouchPoints??0:0;return V()&&e>0&&window.innerWidth>S.md};function U(){let e=(0,c.c)(2),[t,n]=s.useState(W),r,i;return e[0]===Symbol.for(`react.memo_cache_sentinel`)?(r=()=>{if(typeof window>`u`)return;let e=()=>n(H()),t=window.matchMedia?.(`(display-mode: standalone)`),r=window.matchMedia?.(`(display-mode: fullscreen)`);e(),window.addEventListener(`resize`,e),window.addEventListener(`focus`,e);let i=t=>{t&&(typeof t.addEventListener==`function`?t.addEventListener(`change`,e):typeof t.addListener==`function`&&t.addListener(e))},a=t=>{t&&(typeof t.removeEventListener==`function`?t.removeEventListener(`change`,e):typeof t.removeListener==`function`&&t.removeListener(e))};return i(t),i(r),()=>{window.removeEventListener(`resize`,e),window.removeEventListener(`focus`,e),a(t),a(r)}},i=[],e[0]=r,e[1]=i):(r=e[0],i=e[1]),s.useEffect(r,i),t}function W(){return H()}var G=()=>typeof window>`u`?`portrait`:window.matchMedia?.(`(orientation: landscape)`)?.matches?`landscape`:`portrait`;function K(){let e=(0,c.c)(2),[t,n]=s.useState(G),r,i;return e[0]===Symbol.for(`react.memo_cache_sentinel`)?(r=()=>{if(typeof window>`u`||typeof window.matchMedia!=`function`)return;let e=window.matchMedia(`(orientation: landscape)`),t=()=>n(e.matches?`landscape`:`portrait`);return t(),L(e,t)},i=[],e[0]=r,e[1]=i):(r=e[0],i=e[1]),s.useEffect(r,i),t}function q(){return s.useSyncExternalStore(z,N,J)}function J(){return C}export{U as a,K as i,B as n,x as o,q as r,D as t};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{r as e}from"./rolldown-runtime-hePW80VL.js";import{it as t,rt as n}from"./vendor-base-ui-CdzJ6My_.js";import{r}from"./button-
|
|
1
|
+
import{r as e}from"./rolldown-runtime-hePW80VL.js";import{it as t,rt as n}from"./vendor-base-ui-CdzJ6My_.js";import{r}from"./button-BgnrCA96.js";import{t as i}from"./vendor-react-drawio-Ck9ZKdNN.js";var a=e(t(),1),o=n(),s=`<mxfile><diagram id="new" name="Page-1"><mxGraphModel dx="0" dy="0" grid="1" gridSize="10" guides="1" tooltips="1" connect="1" arrows="1" fold="1" page="1" pageScale="1" pageWidth="827" pageHeight="1169" math="0" shadow="0"><root><mxCell id="0"/><mxCell id="1" parent="0"/></root></mxGraphModel></diagram></mxfile>`;function c(){if(typeof document>`u`)return!1;let e=document.documentElement.getAttribute(`data-theme`);return e===`dark`||!e&&window.matchMedia(`(prefers-color-scheme: dark)`).matches}var l=a.forwardRef(function({xml:e,readOnly:t,className:n,onChange:l},u){let d=a.useRef(e),f=a.useRef(null),p=a.useRef(!1),[m,h]=a.useState(c),g=a.useRef(e),_=a.useRef(e);_.current!==e&&(_.current=e,g.current=e,d.current=e);let v=a.useRef(m);v.current!==m&&(v.current=m,g.current=d.current);let y=a.useRef(null);a.useEffect(()=>{let e=()=>h(c());e();let t=new MutationObserver(e);return t.observe(document.documentElement,{attributes:!0,attributeFilter:[`data-theme`]}),()=>t.disconnect()},[]),a.useEffect(()=>{let e=setTimeout(()=>{y.current?.querySelector(`.diagrams-iframe`)?.focus()},600);return()=>clearTimeout(e)},[]),a.useImperativeHandle(u,()=>({getXml:()=>d.current}));let b=a.useCallback(()=>{!e&&!p.current&&(p.current=!0,setTimeout(()=>{f.current?.template({})},500))},[e]),x=a.useCallback(e=>{d.current=e.xml,l?.(e.xml)},[l]);return(0,o.jsx)(`div`,{ref:y,className:r(`h-full w-full`,n),children:(0,o.jsx)(i,{ref:f,xml:g.current||s,autosave:!0,urlParameters:{ui:t?`simple`:m?`dark`:`kennedy`,spin:!0,libraries:!t,chrome:t,nav:t,layers:t,noSaveBtn:!0,noExitBtn:!0,saveAndExit:!1},onLoad:b,onAutoSave:x},m?`dark`:`light`)})});export{l as t};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{r as e}from"./rolldown-runtime-hePW80VL.js";import{$ as t,J as n,Q as r,X as i,Y as a,Z as o,et as s,it as c,q as l,rt as u}from"./vendor-base-ui-CdzJ6My_.js";import{n as d}from"./vendor-react-BP2cRVqX.js";import{f,r as p}from"./button-
|
|
1
|
+
import{r as e}from"./rolldown-runtime-hePW80VL.js";import{$ as t,J as n,Q as r,X as i,Y as a,Z as o,et as s,it as c,q as l,rt as u}from"./vendor-base-ui-CdzJ6My_.js";import{n as d}from"./vendor-react-BP2cRVqX.js";import{f,r as p}from"./button-BgnrCA96.js";import{n as m}from"./Icon-GJTjieJN.js";var h=d(),g=e(c(),1),_=u(),v=0;function y(e,t){return e&&g.isValidElement(t)?{render:t}:{children:t}}function b(e){let t=(0,h.c)(4),n;t[0]===e?n=t[1]:({...n}=e,t[0]=e,t[1]=n);let r;return t[2]===n?r=t[3]:(r=(0,_.jsx)(a,{...n}),t[2]=n,t[3]=r),r}function x(e){let t=(0,h.c)(10),n,r,i;t[0]===e?(n=t[1],r=t[2],i=t[3]):({asChild:n,children:r,...i}=e,t[0]=e,t[1]=n,t[2]=r,t[3]=i);let a;t[4]!==n||t[5]!==r?(a=y(n,r),t[4]=n,t[5]=r,t[6]=a):a=t[6];let o=a,s;return t[7]!==i||t[8]!==o?(s=(0,_.jsx)(l,{"data-slot":`dialog-trigger`,...i,...o}),t[7]=i,t[8]=o,t[9]=s):s=t[9],s}function S(e){let t=(0,h.c)(4),n;t[0]===e?n=t[1]:({...n}=e,t[0]=e,t[1]=n);let r;return t[2]===n?r=t[3]:(r=(0,_.jsx)(i,{...n}),t[2]=n,t[3]=r),r}var C=g.forwardRef((e,t)=>{let n=(0,h.c)(10),r,i;n[0]===e?(r=n[1],i=n[2]):({className:r,...i}=e,n[0]=e,n[1]=r,n[2]=i);let a;n[3]===Symbol.for(`react.memo_cache_sentinel`)?(a=[],n[3]=a):a=n[3],g.useEffect(A,a);let o=t,c;n[4]===r?c=n[5]:(c=p(`app-region-no-drag fixed inset-0 z-50 bg-black/50 dark:bg-black/75`,`transition-opacity duration-150 ease-out`,`data-[starting-style]:opacity-0 data-[ending-style]:opacity-0`,r),n[4]=r,n[5]=c);let l;return n[6]!==i||n[7]!==o||n[8]!==c?(l=(0,_.jsx)(s,{ref:o,"data-slot":`dialog-overlay`,className:c,...i}),n[6]=i,n[7]=o,n[8]=c,n[9]=l):l=n[9],l});C.displayName=`DialogOverlay`;function w(e){let n=(0,h.c)(29),r,i,a,s,c,l;n[0]===e?(r=n[1],i=n[2],a=n[3],s=n[4],c=n[5],l=n[6]):({className:i,overlayClassName:s,containerClassName:a,children:r,showCloseButton:l,...c}=e,n[0]=e,n[1]=r,n[2]=i,n[3]=a,n[4]=s,n[5]=c,n[6]=l);let u=l===void 0||l,{t:d}=f(),g;n[7]===s?g=n[8]:(g=p(`rounded-none`,s),n[7]=s,n[8]=g);let v;n[9]===g?v=n[10]:(v=(0,_.jsx)(C,{className:g}),n[9]=g,n[10]=v);let y=a??`items-center p-4`,b;n[11]===y?b=n[12]:(b=p(`fixed inset-0 z-50 flex justify-center pointer-events-none`,y),n[11]=y,n[12]=b);let x;n[13]===i?x=n[14]:(x=p(`app-region-no-drag relative pointer-events-auto bg-background text-foreground flex flex-col w-full max-w-lg max-h-full gap-4 rounded-xl border p-6 shadow-none overflow-y-auto pwa-dialog-content origin-center`,`transition-all duration-150 ease-out`,`data-[starting-style]:opacity-0 data-[starting-style]:scale-[0.98]`,`data-[ending-style]:opacity-0 data-[ending-style]:scale-[0.98]`,`data-[nested-dialog-open]:brightness-[0.55] dark:data-[nested-dialog-open]:brightness-[0.4]`,i),n[13]=i,n[14]=x);let w;n[15]!==u||n[16]!==d?(w=u&&(0,_.jsxs)(t,{"data-slot":`dialog-close`,className:`ring-offset-background focus:ring-ring data-[open]:bg-interactive-active data-[open]:text-foreground absolute top-2 right-2 rounded-lg opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none text-muted-foreground hover:text-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4`,children:[(0,_.jsx)(m,{name:`close`}),(0,_.jsx)(`span`,{className:`sr-only`,children:d(`dialog.common.actions.close`)})]}),n[15]=u,n[16]=d,n[17]=w):w=n[17];let T;n[18]!==r||n[19]!==c||n[20]!==x||n[21]!==w?(T=(0,_.jsxs)(o,{"data-slot":`dialog-content`,"data-state-slot":`dialog`,className:x,...c,children:[r,w]}),n[18]=r,n[19]=c,n[20]=x,n[21]=w,n[22]=T):T=n[22];let E;n[23]!==b||n[24]!==T?(E=(0,_.jsx)(`div`,{className:b,children:T}),n[23]=b,n[24]=T,n[25]=E):E=n[25];let D;return n[26]!==v||n[27]!==E?(D=(0,_.jsxs)(S,{children:[v,E]}),n[26]=v,n[27]=E,n[28]=D):D=n[28],D}function T(e){let t=(0,h.c)(8),n,r;t[0]===e?(n=t[1],r=t[2]):({className:n,...r}=e,t[0]=e,t[1]=n,t[2]=r);let i;t[3]===n?i=t[4]:(i=p(`flex flex-col gap-2 text-center sm:text-left`,n),t[3]=n,t[4]=i);let a;return t[5]!==r||t[6]!==i?(a=(0,_.jsx)(`div`,{"data-slot":`dialog-header`,className:i,...r}),t[5]=r,t[6]=i,t[7]=a):a=t[7],a}function E(e){let t=(0,h.c)(8),n,r;t[0]===e?(n=t[1],r=t[2]):({className:n,...r}=e,t[0]=e,t[1]=n,t[2]=r);let i;t[3]===n?i=t[4]:(i=p(`flex flex-col-reverse gap-2 bottom-safe-area sm:flex-row sm:justify-end`,n),t[3]=n,t[4]=i);let a;return t[5]!==r||t[6]!==i?(a=(0,_.jsx)(`div`,{"data-slot":`dialog-footer`,className:i,...r}),t[5]=r,t[6]=i,t[7]=a):a=t[7],a}function D(e){let t=(0,h.c)(8),r,i;t[0]===e?(r=t[1],i=t[2]):({className:r,...i}=e,t[0]=e,t[1]=r,t[2]=i);let a;t[3]===r?a=t[4]:(a=p(`typography-markdown leading-none font-semibold text-foreground`,r),t[3]=r,t[4]=a);let o;return t[5]!==i||t[6]!==a?(o=(0,_.jsx)(n,{"data-slot":`dialog-title`,className:a,...i}),t[5]=i,t[6]=a,t[7]=o):o=t[7],o}function O(e){let t=(0,h.c)(8),n,i;t[0]===e?(n=t[1],i=t[2]):({className:n,...i}=e,t[0]=e,t[1]=n,t[2]=i);let a;t[3]===n?a=t[4]:(a=p(`text-muted-foreground typography-ui-label`,n),t[3]=n,t[4]=a);let o;return t[5]!==i||t[6]!==a?(o=(0,_.jsx)(r,{"data-slot":`dialog-description`,className:a,...i}),t[5]=i,t[6]=a,t[7]=o):o=t[7],o}function k(){v=Math.max(0,v-1),v===0&&document.documentElement.classList.remove(`yuri-dialog-open`)}function A(){return v+=1,document.documentElement.classList.add(`yuri-dialog-open`),k}export{T as a,E as i,w as n,D as o,O as r,x as s,b as t};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{r as e}from"./rolldown-runtime-hePW80VL.js";import{p as t}from"./runtime-auth-ef9W7A43.js";import{c as n,f as r,i}from"./runtime-switch-CAZiOV2G.js";import{n as a}from"./runtime-fetch-BAN5Gnnp.js";import{it as o}from"./vendor-base-ui-CdzJ6My_.js";import{St as s}from"./platform-CQG2KlHW.js";import{n as c}from"./vendor-react-BP2cRVqX.js";import{n as l}from"./vendor-reactuses-core-BpfIZ1tg.js";import{f as u}from"./button-BuhP8T0R.js";var d=`yuri:close-embedded-session-chat`,f=`yuri:embedded-visibility`,p=`yuri:embedded-visibility-request`,m=e=>new URLSearchParams(e).get(`yuriPanel`)===`session-chat`,h=(e,t,n)=>JSON.stringify({sessionID:e,directory:t||``,readOnly:n===!0}),g=(e,t,n,r)=>{if(typeof window>`u`)return``;let i=new URL(window.location.pathname,window.location.origin);return i.searchParams.set(`yuriPanel`,`session-chat`),i.searchParams.set(`surface`,`desktop`),i.searchParams.set(`sessionId`,e),n?i.searchParams.set(`readOnly`,`1`):i.searchParams.delete(`readOnly`),t&&t.trim().length>0?i.searchParams.set(`directory`,t):i.searchParams.delete(`directory`),i.searchParams.set(`themeMode`,r.mode),i.searchParams.set(`lightThemeId`,r.lightThemeId),i.searchParams.set(`darkThemeId`,r.darkThemeId),i.searchParams.set(`themeVariant`,r.currentTheme.metadata.variant===`dark`?`dark`:`light`),i.searchParams.set(`currentTheme`,JSON.stringify(r.currentTheme)),i.hash=``,i.toString()},_=(e,t,n,r,i,a)=>{let o=h(n,r,i),s=e.get(t);if(s?.signature===o)return s.src;let c=g(n,r,i,a);return e.set(t,{signature:o,src:c}),c},v=null,y=()=>{if(v!==null)return v;if(typeof window>`u`)return v=!1,!1;try{return v=new URLSearchParams(window.location.search).get(`yuriPanel`)===`session-chat`,v}catch{return v=!1,!1}},b=()=>{if(!y())return null;try{let e=new URLSearchParams(window.location.search).get(`sessionId`);return e&&e.trim().length>0?e.trim():null}catch{return null}},x=e(o(),1);async function S(e,t){let n=i(),r=await a(`/api/voice/session`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({kind:e}),signal:AbortSignal.any([t,AbortSignal.timeout(2e4)])});if(t.throwIfAborted(),n!==i())throw Error(`Speech runtime changed`);if(r.status===404||r.ok&&r.headers.get(`content-type`)?.includes(`text/html`))return await r.body?.cancel(),null;if(!r.ok)throw await r.body?.cancel(),Error(`Unable to create speech session`);let o=await r.json();if(t.throwIfAborted(),n!==i())throw Error(`Speech runtime changed`);if(o?.transport===`host`)return null;if(o?.transport!==`volcengine-direct`||typeof o.token!=`string`||o.token.length>16384||!/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(o.token)||typeof o.appId!=`string`||!/^[A-Za-z0-9_-]{1,128}$/.test(o.appId)||typeof o.resourceId!=`string`||!/^[A-Za-z0-9._-]{1,128}$/.test(o.resourceId)||!Number.isFinite(o.expiresAt)||o.expiresAt<=Date.now()+5e3||o.expiresAt>Date.now()+36e4||e===`tts`&&(typeof o.voice!=`string`||!/^[A-Za-z0-9_-]{1,200}$/.test(o.voice)||!Number.isFinite(o.speed)||o.speed<.5||o.speed>2||!Number.isFinite(o.pitch)||o.pitch<.5||o.pitch>2||!Number.isFinite(o.volume)||o.volume<0||o.volume>1)||e===`asr`&&o.asrContext!==void 0&&(typeof o.asrContext!=`string`||o.asrContext.length>2e3||/\0/.test(o.asrContext)))throw Error(`Invalid speech session`);return o}function C(e,t){let n=new URL(t===`asr`?`wss://openspeech.bytedance.com/api/v3/sauc/bigmodel_async`:`wss://openspeech.bytedance.com/api/v3/tts/bidirection`);return n.search=new URLSearchParams({api_app_key:e.appId,api_access_key:`Jwt; ${e.token}`,api_resource_id:e.resourceId}).toString(),n.toString()}var w=new TextEncoder,T=new TextDecoder,E=1048576;function D(e,t=!1,n=!1){let r=new Uint8Array(8+e.length);return r.set([17,(t?2:1)<<4|(n?2:0),t?0:16,0]),new DataView(r.buffer).setUint32(4,e.length),r.set(e,8),r}function O(e,t=``,n={}){let r=w.encode(t),i=w.encode(JSON.stringify(n)),a=new Uint8Array(12+i.length+(t?4+r.length:0));a.set([17,20,16,0]);let o=new DataView(a.buffer);o.setInt32(4,e);let s=8;return t&&(o.setUint32(s,r.length),a.set(r,s+4),s+=4+r.length),o.setUint32(s,i.length),a.set(i,s+4),a}async function k(e,t){if(e.byteLength<8||e.byteLength>E)throw Error(`Invalid speech frame size`);let n=new Uint8Array(e),r=new DataView(e),i=n[1]>>4,a=n[1]&15,o=n[2]&15,s=(n[0]&15)*4;if(n[0]>>4!=1||s<4||s>n.length-4)throw Error(`Invalid speech frame`);let c=()=>{if(s+4>n.length)throw Error(`Truncated speech frame`);let e=r.getUint32(s);return s+=4,e};if(i===15)throw Error(`Speech provider failed (code ${c()})`);if(i!==9&&(t!==`tts`||i!==11))throw Error(`Unexpected speech frame`);a&1&&c();let l=0,u=``;if(a&4&&(l=c(),t===`tts`)){let e=c();if(e>256||s+e>n.length)throw Error(`Invalid speech session ID`);u=T.decode(n.subarray(s,s+e)),s+=e}let d=c();if(s+d!==n.length)throw Error(`Truncated speech payload`);let f=n.slice(s);if(o===1){let e=new Blob([f]).stream().pipeThrough(new DecompressionStream(`gzip`)).getReader(),t=[],n=0;try{for(;;){let r=await e.read();if(r.done)break;if(n+=r.value.length,n>E)throw Error(`Speech payload exceeds size limit`);t.push(r.value)}}finally{await e.cancel().catch(()=>void 0),e.releaseLock()}f=new Uint8Array(n);let r=0;for(let e of t)f.set(e,r),r+=e.length}else if(o!==0)throw Error(`Unsupported speech compression`);return{type:i,event:l,sessionId:u,final:!!(a&2),payload:f}}function A(e){let t=JSON.parse(T.decode(e));if(!t||typeof t!=`object`||Array.isArray(t))throw Error(`Invalid speech response`);return t}async function j(e,t){t.throwIfAborted();let n=new WebSocket(e);n.binaryType=`arraybuffer`;let r=[],i=0,a=null,o=null,s=null,c=(e=!0)=>{t.removeEventListener(`abort`,u),n.onmessage=null,n.onclose=null,n.onerror=null,n.onopen=null,e&&(r.length=0,i=0),n.close(),o?.()},l=(e,t=!0)=>{a??=e,s?.(a),c(t)},u=()=>l(new DOMException(`Speech cancelled`,`AbortError`));t.addEventListener(`abort`,u,{once:!0}),n.onmessage=e=>{if(!(e.data instanceof ArrayBuffer)||e.data.byteLength>E){l(Error(`Invalid speech message`));return}if(i+=e.data.byteLength,i>33554432||r.length>=4096){l(Error(`Speech receive buffer exceeded`));return}r.push(e.data),o?.()},n.onerror=()=>l(Error(`Speech connection failed`)),n.onclose=()=>l(Error(`Speech connection ended before completion`),!1);let d=setTimeout(()=>l(Error(`Speech connection timed out`)),1e4);try{await new Promise((e,t)=>{s=t,n.onopen=()=>e()})}finally{clearTimeout(d),s=null}return{send(e){if(t.throwIfAborted(),a)throw a;if(n.readyState!==WebSocket.OPEN||n.bufferedAmount+e.length>E)throw Error(`Speech send buffer exceeded`);n.send(e)},async read(){let e=setTimeout(()=>l(Error(`Speech response timed out`)),6e4);try{for(;!r.length&&!a;)await new Promise(e=>{o=e});if(t.throwIfAborted(),!r.length&&a)throw a;let e=r.shift();return i-=e.byteLength,e}finally{clearTimeout(e),o=null}},close(){a??=new DOMException(`Speech closed`,`AbortError`),c()}}}var M=class{abort;partial;disconnected;socket=null;failure=null;completion=null;text=``;final=!1;finishing=!1;sequence=0;constructor(e,t,n){this.abort=e,this.partial=t,this.disconnected=n}get connected(){return this.socket!==null&&!this.failure&&!this.abort.signal.aborted}async start(e,t){if(t!==`audio/pcm;rate=16000;bits=16`)throw Error(`Direct speech requires 16 kHz PCM16 audio`);let n=await j(C(e,`asr`),this.abort.signal);this.socket=n;try{n.send(D(new TextEncoder().encode(JSON.stringify({user:{uid:`yuri`},audio:{format:`pcm`,codec:`raw`,rate:16e3,bits:16,channel:1},request:{model_name:`bigmodel`,result_type:`full`,enable_itn:!0,enable_punc:!0,enable_nonstream:!0,show_utterances:!0,...e.asrContext?.trim()?{corpus:{context:JSON.stringify({context_type:`dialog_ctx`,context_data:[{text:e.asrContext.trim()}]})}}:{}}}))))}catch(e){throw n.close(),e}this.completion=this.receive().catch(e=>{this.failure=e instanceof Error?e:Error(`Speech recognition failed`),n.close(),!this.abort.signal.aborted&&!this.finishing&&this.disconnected()})}send(e,t){if(!this.connected||this.finishing||this.final||e!==this.sequence)return!1;try{if(t.length>128e3)throw Error(`Speech audio chunk exceeds size limit`);let e=atob(t);if(e.length%2)throw Error(`Invalid PCM audio`);let n=Uint8Array.from(e,e=>e.charCodeAt(0));return this.socket.send(D(n,!0)),this.sequence++,!0}catch{return this.failure=Error(`Unable to send speech audio`),this.socket?.close(),!1}}async finish(e){if(this.failure)throw this.failure;if(!this.socket||e!==this.sequence-1)throw Error(`Incomplete speech audio`);this.finishing=!0,this.socket.send(D(new Uint8Array,!0,!0));let t=setTimeout(()=>{this.failure=Error(`Speech finalization timed out`),this.socket?.close()},3e4);try{if(await this.completion,this.abort.signal.throwIfAborted(),this.failure)throw this.failure;if(!this.final)throw Error(`Incomplete speech recognition`);return{text:this.text}}finally{clearTimeout(t),this.socket.close()}}cancel(){this.abort.abort(),this.socket?.close()}async receive(){for(;;){let e=await k(await this.socket.read(),`asr`);this.abort.signal.throwIfAborted();let t=A(e.payload);if(t.code!==void 0&&![0,1e3,2e7].includes(Number(t.code)))throw Error(`Speech recognition failed`);let n=t.result;if(n!==void 0&&(!n||typeof n!=`object`||Array.isArray(n)))throw Error(`Invalid speech transcript`);if(n&&typeof n==`object`&&`text`in n){if(typeof n.text!=`string`)throw Error(`Invalid speech transcript`);this.text=n.text,e.final||this.partial(this.text)}if(e.final){if(!this.finishing)throw Error(`Speech recognition ended unexpectedly`);this.final=!0;return}}}},N=(e,t,n)=>{let r=Error(e);return r.name=`DictationStreamError`,r.retryable=t,n&&(r.reasonCode=n),r},P=1e4,F=15e3,I=3e4,L=3e4,R=new class{socket=null;connectPromise=null;idleCloseTimer=null;pendingStarts=new Map;pendingFinishes=new Map;connectionListeners=new Set;partialListeners=new Set;activeDictations=0;directStarts=new Map;directSessions=new Map;get isConnected(){if(this.socket?.readyState===WebSocket.OPEN)return!0;for(let e of this.directSessions.values())if(e.connected)return!0;return!1}subscribeConnectionStatus(e){return this.connectionListeners.add(e),()=>{this.connectionListeners.delete(e)}}onPartial(e){return this.partialListeners.add(e),()=>{this.partialListeners.delete(e)}}async ensureConnected(){if(this.socket?.readyState!==WebSocket.OPEN){if(this.connectPromise){await this.connectPromise;return}try{await t()}catch{}this.connectPromise=new Promise((e,t)=>{let n=!1,i;try{let e=r().websocket(`/api/dictation/ws`);i=s(e)}catch(e){this.connectPromise=null,t(e instanceof Error?e:Error(String(e)));return}let a=setTimeout(()=>{if(!n){n=!0,this.connectPromise=null;try{i.close()}catch{}t(Error(`Dictation connection timed out`))}},P);i.onopen=()=>{},i.onmessage=t=>{let r;try{r=JSON.parse(String(t.data))}catch{return}if(!n&&r.type===`ready`){n=!0,clearTimeout(a),this.socket=i,this.connectPromise=null,this.notifyConnection(!0),e();return}this.handleMessage(r)},i.onerror=()=>{window.setTimeout(()=>{n||(n=!0,clearTimeout(a),this.connectPromise=null,t(Error(`Dictation connection failed`)))},250)},i.onclose=e=>{if(!n){n=!0,clearTimeout(a),this.connectPromise=null;let r=e?.reason?`: ${e.reason}`:``;t(Error(`Dictation connection failed${r}`));return}this.socket===i&&(this.socket=null,this.rejectAllPending(Error(`Dictation connection lost`)),this.notifyConnection(!1))}}),await this.connectPromise}}async startDictationStream(e,t){let n=new AbortController;this.directStarts.set(e,n);try{let r=await S(`asr`,n.signal);if(n.signal.throwIfAborted(),r){let i=new M(n,t=>{for(let n of this.partialListeners)n(e,t)},()=>{this.directSessions.delete(e),i.cancel(),this.notifyConnection(!1)});this.directSessions.set(e,i),await i.start(r,t),n.signal.throwIfAborted(),this.notifyConnection(!0);return}await this.ensureConnected(),n.signal.throwIfAborted()}catch(t){throw this.directSessions.get(e)?.cancel(),this.directSessions.delete(e),t}finally{this.directStarts.delete(e)}return this.activeDictations+=1,this.clearIdleCloseTimer(),new Promise((n,r)=>{let i=setTimeout(()=>{this.pendingStarts.delete(e),this.releaseDictation(),r(Error(`Dictation start timed out`))},F);this.pendingStarts.set(e,{resolve:()=>{clearTimeout(i),n()},reject:e=>{clearTimeout(i),this.releaseDictation(),r(e)},timeout:i}),this.send({type:`start`,dictationId:e,format:t})||(clearTimeout(i),this.pendingStarts.delete(e),this.releaseDictation(),r(Error(`Dictation connection lost`)))})}sendDictationStreamChunk(e,t,n){let r=this.directSessions.get(e);return r?r.send(t,n):this.send({type:`chunk`,dictationId:e,seq:t,audio:n})}finishDictationStream(e,t){let n=this.directSessions.get(e);return n?n.finish(t).finally(()=>{n.cancel(),this.directSessions.delete(e)}):new Promise((n,r)=>{let i={resolve:e=>{i.timeout&&clearTimeout(i.timeout),this.releaseDictation(),n(e)},reject:e=>{i.timeout&&clearTimeout(i.timeout),this.releaseDictation(),r(e)},timeout:null};i.timeout=setTimeout(()=>{this.pendingFinishes.delete(e),this.releaseDictation(),r(Error(`Timed out waiting for transcription`))},L),this.pendingFinishes.set(e,i),this.send({type:`finish`,dictationId:e,finalSeq:t})||(this.pendingFinishes.delete(e),i.reject(Error(`Dictation connection lost`)))})}cancelDictationStream(e){this.directStarts.get(e)?.abort(),this.directStarts.delete(e);let t=this.directSessions.get(e);if(t){t.cancel(),this.directSessions.delete(e);return}this.send({type:`cancel`,dictationId:e});let n=this.pendingStarts.get(e);n&&(this.pendingStarts.delete(e),n.reject(Error(`Dictation cancelled`)));let r=this.pendingFinishes.get(e);r&&(this.pendingFinishes.delete(e),r.reject(Error(`Dictation cancelled`))),this.releaseDictation(),this.scheduleIdleCloseIfReady()}handleMessage(e){let t=e.dictationId;if(t)switch(e.type){case`ack`:{let e=this.pendingStarts.get(t);e&&(this.pendingStarts.delete(t),e.resolve());return}case`partial`:for(let n of this.partialListeners)n(t,e.text??``);return;case`finish_accepted`:{let n=this.pendingFinishes.get(t);n&&typeof e.timeoutMs==`number`&&(n.timeout&&clearTimeout(n.timeout),n.timeout=setTimeout(()=>{this.pendingFinishes.delete(t),n.reject(Error(`Timed out waiting for transcription`))},e.timeoutMs+5e3));return}case`final`:{let n=this.pendingFinishes.get(t);n&&(this.pendingFinishes.delete(t),n.resolve({text:e.text??``})),this.scheduleIdleCloseIfReady();return}case`error`:{let n=N(e.error||`Dictation failed`,e.retryable!==!1,e.reasonCode),r=this.pendingStarts.get(t);r&&(this.pendingStarts.delete(t),r.reject(n));let i=this.pendingFinishes.get(t);i&&(this.pendingFinishes.delete(t),i.reject(n)),this.scheduleIdleCloseIfReady();return}}}send(e){if(!this.isConnected||!this.socket)return!1;try{return this.socket.send(JSON.stringify(e)),!0}catch{return!1}}notifyConnection(e){for(let t of this.connectionListeners)t(e)}rejectAllPending(e){for(let[t,n]of this.pendingStarts)this.pendingStarts.delete(t),n.reject(e);for(let[t,n]of this.pendingFinishes)this.pendingFinishes.delete(t),n.reject(e);this.activeDictations=0}releaseDictation(){this.activeDictations=Math.max(0,this.activeDictations-1),this.scheduleIdleCloseIfReady()}scheduleIdleCloseIfReady(){this.activeDictations>0||this.pendingFinishes.size>0||this.pendingStarts.size>0||(this.clearIdleCloseTimer(),this.idleCloseTimer=setTimeout(()=>{if(this.activeDictations===0&&this.pendingFinishes.size===0&&this.pendingStarts.size===0){let e=this.socket;if(this.socket=null,e){try{e.close(1e3,`idle`)}catch{}this.notifyConnection(!1)}}},I))}cancelAllForRuntimeSwitch(){for(let e of this.directStarts.values())e.abort();this.directStarts.clear();for(let e of this.directSessions.values())e.cancel();this.directSessions.clear(),this.clearIdleCloseTimer();let e=this.socket;if(this.socket=null,this.connectPromise=null,this.rejectAllPending(Error(`Runtime changed`)),e){try{e.close(1e3,`runtime switch`)}catch{}this.notifyConnection(!1)}}clearIdleCloseTimer(){this.idleCloseTimer&&=(clearTimeout(this.idleCloseTimer),null)}};typeof window<`u`&&window.addEventListener(`yuri:runtime-endpoint-changed`,()=>{R.cancelAllForRuntimeSwitch()});var z=128,B=`audio/pcm;rate=16000;bits=16`,V=()=>new Promise(e=>setTimeout(e,0)),H=()=>{let e=Math.random().toString(36).slice(2,10);return`dic_${Date.now().toString(16)}${e}`},ee=class{client;format;createDictationId;dictationId=null;sendSeq=0;segments=[];streamReady=!1;flushTimer=null;drainWaiters=[];startGeneration=0;startPromise=null;constructor(e){this.client=e.client,this.format=e.format??B,this.createDictationId=e.createDictationId??H}getDictationId(){return this.dictationId}getFinalSeq(){return this.segments.length-1}hasSegments(){return this.segments.length>0}clearAll(){this.dictationId&&this.client.cancelDictationStream(this.dictationId),this.clearScheduledFlush(),this.dictationId=null,this.sendSeq=0,this.segments=[],this.streamReady=!1,this.startPromise=null,this.startGeneration+=1}resetStreamForReplay(){this.dictationId&&this.client.cancelDictationStream(this.dictationId),this.clearScheduledFlush(),this.dictationId=null,this.sendSeq=0,this.streamReady=!1,this.startPromise=null,this.startGeneration+=1}enqueueSegment(e){if(this.segments.push(e),this.client.isConnected){if(!this.dictationId){this.startPromise||this.restartStream().catch(()=>{});return}this.flush()}}flush(){let e=this.dictationId;if(!this.client.isConnected||!e||!this.streamReady)return 0;let t=0;for(;this.sendSeq<this.segments.length&&t<z;){let n=this.sendSeq,r=this.segments[n];if(!this.client.sendDictationStreamChunk(e,n,r))break;this.sendSeq=n+1,t+=1}return this.hasPendingSegments()?this.scheduleFlush():this.resolveDrainWaiters(),t}async restartStream(){this.startGeneration+=1;let e=this.startGeneration,t=this.createDictationId();this.dictationId=t,this.sendSeq=0,this.streamReady=!1;let n=(async()=>{await this.client.startDictationStream(t,this.format),this.startGeneration===e&&this.dictationId===t&&(this.streamReady=!0,this.flush())})().catch(n=>{throw this.startGeneration===e&&this.dictationId===t&&(this.dictationId=null,this.streamReady=!1),n}).finally(()=>{this.startPromise===n&&(this.startPromise=null)});this.startPromise=n,await n}async finish(e){this.dictationId||await this.restartStream(),this.startPromise&&await this.startPromise;let t=this.dictationId;if(!t||!this.streamReady)throw Error(`Failed to start dictation stream`);return this.flush(),await this.waitForFlushDrain(),{dictationId:t,text:(await this.client.finishDictationStream(t,e)).text}}cancel(){this.resetStreamForReplay()}hasPendingSegments(){return this.sendSeq<this.segments.length}scheduleFlush(){this.flushTimer||=setTimeout(()=>{this.flushTimer=null,this.flush()},0)}clearScheduledFlush(){this.resolveDrainWaiters(),this.flushTimer&&=(clearTimeout(this.flushTimer),null)}async waitForFlushDrain(){for(;this.hasPendingSegments();){if(!this.client.isConnected||!this.dictationId||!this.streamReady)throw Error(`Failed to flush dictation stream`);await new Promise(e=>{this.drainWaiters.push(e)}),await V()}}resolveDrainWaiters(){let e=this.drainWaiters;this.drainWaiters=[];for(let t of e)t()}},U=c(),W=new Set;function G(e){return W.add(e),()=>{W.delete(e)}}function K(){for(let e of W)e();if(typeof window<`u`&&window.speechSynthesis?.cancel(),typeof navigator>`u`)return;let e=navigator.audioSession;if(e)try{e.type=`play-and-record`}catch{}}function te(){if(typeof navigator>`u`)return;let e=navigator.audioSession;if(e)try{e.type!==`playback`&&(e.type=`playback`)}catch{}}var q=16e3,J=q/5,Y=()=>{if(typeof window>`u`)return null;let e=window;return e.AudioContext||e.webkitAudioContext||null},X=e=>{let t=Math.max(-1,Math.min(1,e));return Math.round(t<0?t*32768:t*32767)},ne=(e,t,n)=>{if(e.length===0)return new Int16Array;if(t===n){let t=new Int16Array(e.length);for(let n=0;n<e.length;n++)t[n]=X(e[n]);return t}let r=t/n,i=Math.max(1,Math.round(e.length/r)),a=new Int16Array(i);for(let t=0;t<i;t++){let n=t*r,i=Math.floor(n),o=Math.min(e.length-1,i+1),s=n-i;a[t]=X(e[i]*(1-s)+e[o]*s)}return a},re=(e,t)=>{if(e.length===0)return t;if(t.length===0)return e;let n=new Int16Array(e.length+t.length);return n.set(e,0),n.set(t,e.length),n},Z=e=>{let t=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),n=``;for(let e=0;e<t.length;e++)n+=String.fromCharCode(t[e]);return btoa(n)},Q=()=>({stream:null,context:null,source:null,processor:null,gain:null,pending:new Int16Array,started:!1}),$=e=>{if(e)try{e.disconnect()}catch{}},ie=()=>typeof navigator>`u`||typeof window>`u`||!navigator.mediaDevices||typeof navigator.mediaDevices.getUserMedia!=`function`?!1:Y()!==null;function ae(e){let t=(0,U.c)(16),[n,r]=(0,x.useState)(0),i=(0,x.useRef)(e.onPcmSegment),a=(0,x.useRef)(e.onError),o,s;t[0]!==e.onError||t[1]!==e.onPcmSegment?(o=()=>{i.current=e.onPcmSegment,a.current=e.onError},s=[e.onPcmSegment,e.onError],t[0]=e.onError,t[1]=e.onPcmSegment,t[2]=o,t[3]=s):(o=t[2],s=t[3]),(0,x.useEffect)(o,s);let c;t[4]===Symbol.for(`react.memo_cache_sentinel`)?(c=Q(),t[4]=c):c=t[4];let u=(0,x.useRef)(c),d=(0,x.useRef)(0),f;t[5]===Symbol.for(`react.memo_cache_sentinel`)?(f=async()=>{if(u.current.started)return;if(typeof navigator>`u`||!navigator.mediaDevices||typeof navigator.mediaDevices.getUserMedia!=`function`)throw Error(`Microphone capture is not supported in this environment`);let e=Y();if(!e)throw Error(`AudioContext unavailable`);let t=d.current+=1;K();let n=await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,noiseSuppression:!0,echoCancellation:!0,autoGainControl:!0}});if(t!==d.current){n.getTracks().forEach(ue);return}let a=new e;try{if(a.state===`suspended`&&await a.resume().catch(le),t!==d.current){n.getTracks().forEach(ce),await a.close();return}let e=a.createMediaStreamSource(n),o=a.createScriptProcessor(4096,1,1),s=a.createGain();s.gain.value=0,u.current={stream:n,context:a,source:e,processor:o,gain:s,pending:new Int16Array,started:!0},o.onaudioprocess=e=>{let t=u.current;if(!t.started)return;let n=e.inputBuffer.getChannelData(0),o=0;for(let e=0;e<n.length;e++)o+=n[e]*n[e];let s=Math.sqrt(o/Math.max(1,n.length));r(Math.min(1,Math.max(0,s*2)));let c=ne(n,a.sampleRate,q);for(t.pending=re(t.pending,c);t.pending.length>=J;){let e=t.pending.slice(0,J);t.pending=t.pending.slice(J),i.current(Z(e))}},e.connect(o),o.connect(s),s.connect(a.destination)}catch(e){let t=e;n.getTracks().forEach(se);try{await a.close()}catch{}throw u.current=Q(),t instanceof Error?t:Error(String(t))}},t[5]=f):f=t[5];let p=l(f),m;t[6]===Symbol.for(`react.memo_cache_sentinel`)?(m=async()=>{d.current+=1;let e=u.current;if(e.started=!1,r(0),e.processor)try{e.processor.onaudioprocess=null}catch{}$(e.processor),$(e.source),$(e.gain),e.stream&&e.stream.getTracks().forEach(oe);let t=e.pending;if(e.pending=new Int16Array,t.length>0&&i.current(Z(t)),e.context)try{await e.context.close()}catch{}u.current===e&&(u.current=Q())},t[6]=m):m=t[6];let h=l(m),g,_;t[7]===h?(g=t[8],_=t[9]):(g=()=>()=>{h().catch(e=>{a.current?.(e instanceof Error?e:Error(String(e)))})},_=[h],t[7]=h,t[8]=g,t[9]=_),(0,x.useEffect)(g,_);let v;t[10]===p?v=t[11]:(v=async()=>{try{await p()}catch(e){let t=e,n=t instanceof Error?t:Error(String(t));throw a.current?.(n),n}},t[10]=p,t[11]=v);let y;return t[12]!==h||t[13]!==v||t[14]!==n?(y={start:v,stop:h,volume:n},t[12]=h,t[13]=v,t[14]=n,t[15]=y):y=t[15],y}function oe(e){try{e.stop()}catch{}}function se(e){try{e.stop()}catch{}}function ce(e){return e.stop()}function le(){}function ue(e){return e.stop()}var de=1e3,fe=e=>e instanceof Error?e:Error(String(e));function pe(e={}){let{t}=u(),{onTranscript:r,onError:i,canStart:a}=e,[o,s]=(0,x.useState)(`idle`),[c,d]=(0,x.useState)(!1),[f,p]=(0,x.useState)(``),[m,h]=(0,x.useState)(0),[g,_]=(0,x.useState)(null),[v,y]=(0,x.useState)(null),b=(0,x.useRef)(o);(0,x.useEffect)(()=>{b.current=o},[o]);let S=(0,x.useRef)(``),C=(0,x.useRef)(null),w=(0,x.useRef)({starting:!1,confirming:!1,cancelling:!1}),T=(0,x.useRef)(0),E=(0,x.useRef)(r),D=(0,x.useRef)(i);(0,x.useEffect)(()=>{E.current=r,D.current=i},[r,i]);let O=(0,x.useRef)(null);O.current||=new ee({client:R});let k=l(()=>{C.current&&=(clearInterval(C.current),null)}),A=l(()=>{C.current||=setInterval(()=>{h(e=>e+1)},de)}),j=l(e=>{let n=fe(e),r=n.name===`NotFoundError`||n.name===`DevicesNotFoundError`?Error(t(`chat.dictation.error.microphoneNotFound`),{cause:n}):n;_(r.message);let i=n.reasonCode;y(typeof i==`string`?i:null),D.current?.(r)}),M=l(()=>{_(null),y(null)}),N=l(()=>{O.current?.clearAll(),S.current=``,p(``)}),P=l(t=>e.onPartialTranscript?.(t));(0,x.useEffect)(()=>R.onPartial((e,t)=>{let n=O.current?.getDictationId();!n||e!==n||(S.current=t,p(t),P(t))}),[P]),(0,x.useEffect)(()=>R.subscribeConnectionStatus(e=>{if(!e){b.current===`recording`&&O.current?.resetStreamForReplay();return}if(b.current!==`recording`||O.current?.getDictationId())return;let t=T.current;O.current?.restartStream().catch(e=>{T.current===t&&j(e)})}),[j]);let F=ae({onPcmSegment:e=>{b.current===`recording`&&O.current?.enqueueSegment(e)},onError:e=>{D.current?.(e)}}),I=(0,x.useRef)(F.stop);(0,x.useEffect)(()=>{I.current=F.stop},[F.stop]);let L=l(e=>{h(0),s(`idle`),b.current=`idle`;let t=e.trim();return N(),t?(E.current?.(t),t):null}),z=l(e=>{O.current?.hasSegments()?(s(`failed`),b.current=`failed`):(s(`idle`),b.current=`idle`),j(e)}),B=l(async()=>{let e=w.current;if(e.starting||e.confirming||e.cancelling||b.current!==`idle`||a&&!a())return;e.starting=!0,d(!0);let t=++T.current;M(),p(``),h(0),s(`recording`),b.current=`recording`,N();try{if(await F.start(),T.current!==t||b.current!==`recording`)return;d(!1),A(),await O.current?.restartStream().catch(e=>{T.current===t&&j(e)})}catch(e){if(T.current!==t)return;await F.stop().catch(()=>void 0),k(),s(`idle`),b.current=`idle`,j(e)}finally{T.current===t&&d(!1),e.starting=!1}}),V=l(async()=>{let e=w.current;if(!e.cancelling&&(b.current===`recording`||b.current===`uploading`)){e.cancelling=!0,d(!1),T.current+=1,k(),h(0),M(),s(`idle`),b.current=`idle`;try{O.current?.cancel()}catch{}N();try{await F.stop()}catch{}finally{e.cancelling=!1}}}),H=l(async()=>{let e=w.current;if(e.confirming||b.current!==`recording`)return null;e.confirming=!0,d(!1);let t=++T.current;M(),k();try{if(await F.stop(),T.current!==t)return null;s(`uploading`),b.current=`uploading`;let e=O.current?.getFinalSeq()??-1;if(e<0)return O.current?.cancel(),L(``);let n=await O.current.finish(e);return T.current===t?L(n.text):null}catch(e){return T.current===t&&z(e),null}finally{e.confirming=!1}}),U=l(async()=>{if(b.current!==`failed`||!O.current?.hasSegments())return null;M();let e=++T.current;s(`uploading`),b.current=`uploading`;try{O.current.resetStreamForReplay();let t=O.current.getFinalSeq(),n=await O.current.finish(t);return T.current===e?L(n.text):null}catch(t){return T.current===e&&z(t),null}}),W=l(()=>{if(b.current!==`failed`)return null;let e=S.current.trim();h(0),s(`idle`),b.current=`idle`,M();try{O.current?.cancel()}catch{}return N(),e?(E.current?.(e),e):null}),G=l(()=>{h(0),s(`idle`),b.current=`idle`,M(),N()});return(0,x.useEffect)(()=>n(()=>{b.current===`failed`?(T.current+=1,G()):V()}),[V,G]),(0,x.useEffect)(()=>{if(o!==`recording`||v!==`model_download_in_progress`)return;let e=setInterval(()=>{b.current!==`recording`||O.current?.getDictationId()||O.current?.restartStream().then(()=>{M()}).catch(e=>{j(e)})},3e3);return()=>clearInterval(e)},[o,v,M,j]),(0,x.useEffect)(()=>()=>{T.current+=1,k(),I.current().catch(()=>void 0),O.current?.cancel()},[k]),{status:o,isRecording:o===`recording`,isStarting:c,isProcessing:o===`uploading`,partialTranscript:f,volume:F.volume,duration:m,error:g,errorReason:v,startDictation:B,confirmDictation:H,cancelDictation:V,retryFailedDictation:U,acceptPartialTranscript:W,discardFailedDictation:G}}var me=`app-region-no-drag transition-[opacity,transform] duration-150 ease-out data-[starting-style]:opacity-0 data-[starting-style]:scale-95 data-[ending-style]:opacity-0 data-[ending-style]:scale-95 z-50 max-h-[var(--available-height)] min-w-[8rem] origin-[var(--transform-origin)] overflow-visible rounded-xl p-1 shadow-[inset_0_1px_0_0_rgba(255,255,255,0.8),inset_0_0_0_1px_rgba(0,0,0,0.04),0_0_0_1px_rgba(0,0,0,0.10),0_1px_2px_-0.5px_rgba(0,0,0,0.08),0_4px_8px_-2px_rgba(0,0,0,0.08),0_12px_20px_-4px_rgba(0,0,0,0.08)] dark:shadow-[inset_0_1px_0_0_rgba(255,255,255,0.12),inset_0_0_0_1px_rgba(255,255,255,0.08),0_0_0_1px_rgba(0,0,0,0.36),0_1px_1px_-0.5px_rgba(0,0,0,0.22),0_3px_3px_-1.5px_rgba(0,0,0,0.20),0_6px_6px_-3px_rgba(0,0,0,0.16)]`,he=`data-[highlighted]:bg-interactive-hover hover:bg-interactive-hover active:bg-interactive-active data-[variant=destructive]:text-destructive data-[variant=destructive]:hover:bg-destructive/10 dark:data-[variant=destructive]:hover:bg-destructive/20 data-[variant=destructive]:hover:text-destructive data-[variant=destructive]:*:[svg]:!text-destructive [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-pointer items-center gap-2 rounded-lg px-2 py-1 typography-ui-label outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-3.5`,ge=`data-[highlighted]:bg-interactive-hover hover:bg-interactive-hover active:bg-interactive-active [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-pointer items-center gap-2 rounded-lg px-2 py-1 typography-ui-label outline-hidden select-none data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-3.5`,_e=`bg-border -mx-1 my-0.5 h-px`;export{m as S,f as _,pe as a,_ as b,te as c,j as d,A as f,d as g,C as h,ge as i,G as l,S as m,me as n,ie as o,O as p,_e as r,K as s,he as t,k as u,p as v,y as x,b as y};
|
|
1
|
+
import{r as e}from"./rolldown-runtime-hePW80VL.js";import{p as t}from"./runtime-auth-ef9W7A43.js";import{c as n,f as r,i}from"./runtime-switch-CAZiOV2G.js";import{n as a}from"./runtime-fetch-BAN5Gnnp.js";import{it as o}from"./vendor-base-ui-CdzJ6My_.js";import{St as s}from"./platform-Dcd-lkPn.js";import{n as c}from"./vendor-react-BP2cRVqX.js";import{n as l}from"./vendor-reactuses-core-BpfIZ1tg.js";import{f as u}from"./button-BgnrCA96.js";var d=`yuri:close-embedded-session-chat`,f=`yuri:embedded-visibility`,p=`yuri:embedded-visibility-request`,m=e=>new URLSearchParams(e).get(`yuriPanel`)===`session-chat`,h=(e,t,n)=>JSON.stringify({sessionID:e,directory:t||``,readOnly:n===!0}),g=(e,t,n,r)=>{if(typeof window>`u`)return``;let i=new URL(window.location.pathname,window.location.origin);return i.searchParams.set(`yuriPanel`,`session-chat`),i.searchParams.set(`surface`,`desktop`),i.searchParams.set(`sessionId`,e),n?i.searchParams.set(`readOnly`,`1`):i.searchParams.delete(`readOnly`),t&&t.trim().length>0?i.searchParams.set(`directory`,t):i.searchParams.delete(`directory`),i.searchParams.set(`themeMode`,r.mode),i.searchParams.set(`lightThemeId`,r.lightThemeId),i.searchParams.set(`darkThemeId`,r.darkThemeId),i.searchParams.set(`themeVariant`,r.currentTheme.metadata.variant===`dark`?`dark`:`light`),i.searchParams.set(`currentTheme`,JSON.stringify(r.currentTheme)),i.hash=``,i.toString()},_=(e,t,n,r,i,a)=>{let o=h(n,r,i),s=e.get(t);if(s?.signature===o)return s.src;let c=g(n,r,i,a);return e.set(t,{signature:o,src:c}),c},v=null,y=()=>{if(v!==null)return v;if(typeof window>`u`)return v=!1,!1;try{return v=new URLSearchParams(window.location.search).get(`yuriPanel`)===`session-chat`,v}catch{return v=!1,!1}},b=()=>{if(!y())return null;try{let e=new URLSearchParams(window.location.search).get(`sessionId`);return e&&e.trim().length>0?e.trim():null}catch{return null}},x=e(o(),1);async function S(e,t){let n=i(),r=await a(`/api/voice/session`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({kind:e}),signal:AbortSignal.any([t,AbortSignal.timeout(2e4)])});if(t.throwIfAborted(),n!==i())throw Error(`Speech runtime changed`);if(r.status===404||r.ok&&r.headers.get(`content-type`)?.includes(`text/html`))return await r.body?.cancel(),null;if(!r.ok)throw await r.body?.cancel(),Error(`Unable to create speech session`);let o=await r.json();if(t.throwIfAborted(),n!==i())throw Error(`Speech runtime changed`);if(o?.transport===`host`)return null;if(o?.transport!==`volcengine-direct`||typeof o.token!=`string`||o.token.length>16384||!/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(o.token)||typeof o.appId!=`string`||!/^[A-Za-z0-9_-]{1,128}$/.test(o.appId)||typeof o.resourceId!=`string`||!/^[A-Za-z0-9._-]{1,128}$/.test(o.resourceId)||!Number.isFinite(o.expiresAt)||o.expiresAt<=Date.now()+5e3||o.expiresAt>Date.now()+36e4||e===`tts`&&(typeof o.voice!=`string`||!/^[A-Za-z0-9_-]{1,200}$/.test(o.voice)||!Number.isFinite(o.speed)||o.speed<.5||o.speed>2||!Number.isFinite(o.pitch)||o.pitch<.5||o.pitch>2||!Number.isFinite(o.volume)||o.volume<0||o.volume>1)||e===`asr`&&o.asrContext!==void 0&&(typeof o.asrContext!=`string`||o.asrContext.length>2e3||/\0/.test(o.asrContext)))throw Error(`Invalid speech session`);return o}function C(e,t){let n=new URL(t===`asr`?`wss://openspeech.bytedance.com/api/v3/sauc/bigmodel_async`:`wss://openspeech.bytedance.com/api/v3/tts/bidirection`);return n.search=new URLSearchParams({api_app_key:e.appId,api_access_key:`Jwt; ${e.token}`,api_resource_id:e.resourceId}).toString(),n.toString()}var w=new TextEncoder,T=new TextDecoder,E=1048576;function D(e,t=!1,n=!1){let r=new Uint8Array(8+e.length);return r.set([17,(t?2:1)<<4|(n?2:0),t?0:16,0]),new DataView(r.buffer).setUint32(4,e.length),r.set(e,8),r}function O(e,t=``,n={}){let r=w.encode(t),i=w.encode(JSON.stringify(n)),a=new Uint8Array(12+i.length+(t?4+r.length:0));a.set([17,20,16,0]);let o=new DataView(a.buffer);o.setInt32(4,e);let s=8;return t&&(o.setUint32(s,r.length),a.set(r,s+4),s+=4+r.length),o.setUint32(s,i.length),a.set(i,s+4),a}async function k(e,t){if(e.byteLength<8||e.byteLength>E)throw Error(`Invalid speech frame size`);let n=new Uint8Array(e),r=new DataView(e),i=n[1]>>4,a=n[1]&15,o=n[2]&15,s=(n[0]&15)*4;if(n[0]>>4!=1||s<4||s>n.length-4)throw Error(`Invalid speech frame`);let c=()=>{if(s+4>n.length)throw Error(`Truncated speech frame`);let e=r.getUint32(s);return s+=4,e};if(i===15)throw Error(`Speech provider failed (code ${c()})`);if(i!==9&&(t!==`tts`||i!==11))throw Error(`Unexpected speech frame`);a&1&&c();let l=0,u=``;if(a&4&&(l=c(),t===`tts`)){let e=c();if(e>256||s+e>n.length)throw Error(`Invalid speech session ID`);u=T.decode(n.subarray(s,s+e)),s+=e}let d=c();if(s+d!==n.length)throw Error(`Truncated speech payload`);let f=n.slice(s);if(o===1){let e=new Blob([f]).stream().pipeThrough(new DecompressionStream(`gzip`)).getReader(),t=[],n=0;try{for(;;){let r=await e.read();if(r.done)break;if(n+=r.value.length,n>E)throw Error(`Speech payload exceeds size limit`);t.push(r.value)}}finally{await e.cancel().catch(()=>void 0),e.releaseLock()}f=new Uint8Array(n);let r=0;for(let e of t)f.set(e,r),r+=e.length}else if(o!==0)throw Error(`Unsupported speech compression`);return{type:i,event:l,sessionId:u,final:!!(a&2),payload:f}}function A(e){let t=JSON.parse(T.decode(e));if(!t||typeof t!=`object`||Array.isArray(t))throw Error(`Invalid speech response`);return t}async function j(e,t){t.throwIfAborted();let n=new WebSocket(e);n.binaryType=`arraybuffer`;let r=[],i=0,a=null,o=null,s=null,c=(e=!0)=>{t.removeEventListener(`abort`,u),n.onmessage=null,n.onclose=null,n.onerror=null,n.onopen=null,e&&(r.length=0,i=0),n.close(),o?.()},l=(e,t=!0)=>{a??=e,s?.(a),c(t)},u=()=>l(new DOMException(`Speech cancelled`,`AbortError`));t.addEventListener(`abort`,u,{once:!0}),n.onmessage=e=>{if(!(e.data instanceof ArrayBuffer)||e.data.byteLength>E){l(Error(`Invalid speech message`));return}if(i+=e.data.byteLength,i>33554432||r.length>=4096){l(Error(`Speech receive buffer exceeded`));return}r.push(e.data),o?.()},n.onerror=()=>l(Error(`Speech connection failed`)),n.onclose=()=>l(Error(`Speech connection ended before completion`),!1);let d=setTimeout(()=>l(Error(`Speech connection timed out`)),1e4);try{await new Promise((e,t)=>{s=t,n.onopen=()=>e()})}finally{clearTimeout(d),s=null}return{send(e){if(t.throwIfAborted(),a)throw a;if(n.readyState!==WebSocket.OPEN||n.bufferedAmount+e.length>E)throw Error(`Speech send buffer exceeded`);n.send(e)},async read(){let e=setTimeout(()=>l(Error(`Speech response timed out`)),6e4);try{for(;!r.length&&!a;)await new Promise(e=>{o=e});if(t.throwIfAborted(),!r.length&&a)throw a;let e=r.shift();return i-=e.byteLength,e}finally{clearTimeout(e),o=null}},close(){a??=new DOMException(`Speech closed`,`AbortError`),c()}}}var M=class{abort;partial;disconnected;socket=null;failure=null;completion=null;text=``;final=!1;finishing=!1;sequence=0;constructor(e,t,n){this.abort=e,this.partial=t,this.disconnected=n}get connected(){return this.socket!==null&&!this.failure&&!this.abort.signal.aborted}async start(e,t){if(t!==`audio/pcm;rate=16000;bits=16`)throw Error(`Direct speech requires 16 kHz PCM16 audio`);let n=await j(C(e,`asr`),this.abort.signal);this.socket=n;try{n.send(D(new TextEncoder().encode(JSON.stringify({user:{uid:`yuri`},audio:{format:`pcm`,codec:`raw`,rate:16e3,bits:16,channel:1},request:{model_name:`bigmodel`,result_type:`full`,enable_itn:!0,enable_punc:!0,enable_nonstream:!0,show_utterances:!0,...e.asrContext?.trim()?{corpus:{context:JSON.stringify({context_type:`dialog_ctx`,context_data:[{text:e.asrContext.trim()}]})}}:{}}}))))}catch(e){throw n.close(),e}this.completion=this.receive().catch(e=>{this.failure=e instanceof Error?e:Error(`Speech recognition failed`),n.close(),!this.abort.signal.aborted&&!this.finishing&&this.disconnected()})}send(e,t){if(!this.connected||this.finishing||this.final||e!==this.sequence)return!1;try{if(t.length>128e3)throw Error(`Speech audio chunk exceeds size limit`);let e=atob(t);if(e.length%2)throw Error(`Invalid PCM audio`);let n=Uint8Array.from(e,e=>e.charCodeAt(0));return this.socket.send(D(n,!0)),this.sequence++,!0}catch{return this.failure=Error(`Unable to send speech audio`),this.socket?.close(),!1}}async finish(e){if(this.failure)throw this.failure;if(!this.socket||e!==this.sequence-1)throw Error(`Incomplete speech audio`);this.finishing=!0,this.socket.send(D(new Uint8Array,!0,!0));let t=setTimeout(()=>{this.failure=Error(`Speech finalization timed out`),this.socket?.close()},3e4);try{if(await this.completion,this.abort.signal.throwIfAborted(),this.failure)throw this.failure;if(!this.final)throw Error(`Incomplete speech recognition`);return{text:this.text}}finally{clearTimeout(t),this.socket.close()}}cancel(){this.abort.abort(),this.socket?.close()}async receive(){for(;;){let e=await k(await this.socket.read(),`asr`);this.abort.signal.throwIfAborted();let t=A(e.payload);if(t.code!==void 0&&![0,1e3,2e7].includes(Number(t.code)))throw Error(`Speech recognition failed`);let n=t.result;if(n!==void 0&&(!n||typeof n!=`object`||Array.isArray(n)))throw Error(`Invalid speech transcript`);if(n&&typeof n==`object`&&`text`in n){if(typeof n.text!=`string`)throw Error(`Invalid speech transcript`);this.text=n.text,e.final||this.partial(this.text)}if(e.final){if(!this.finishing)throw Error(`Speech recognition ended unexpectedly`);this.final=!0;return}}}},N=(e,t,n)=>{let r=Error(e);return r.name=`DictationStreamError`,r.retryable=t,n&&(r.reasonCode=n),r},P=1e4,F=15e3,I=3e4,L=3e4,R=new class{socket=null;connectPromise=null;idleCloseTimer=null;pendingStarts=new Map;pendingFinishes=new Map;connectionListeners=new Set;partialListeners=new Set;activeDictations=0;directStarts=new Map;directSessions=new Map;get isConnected(){if(this.socket?.readyState===WebSocket.OPEN)return!0;for(let e of this.directSessions.values())if(e.connected)return!0;return!1}subscribeConnectionStatus(e){return this.connectionListeners.add(e),()=>{this.connectionListeners.delete(e)}}onPartial(e){return this.partialListeners.add(e),()=>{this.partialListeners.delete(e)}}async ensureConnected(){if(this.socket?.readyState!==WebSocket.OPEN){if(this.connectPromise){await this.connectPromise;return}try{await t()}catch{}this.connectPromise=new Promise((e,t)=>{let n=!1,i;try{let e=r().websocket(`/api/dictation/ws`);i=s(e)}catch(e){this.connectPromise=null,t(e instanceof Error?e:Error(String(e)));return}let a=setTimeout(()=>{if(!n){n=!0,this.connectPromise=null;try{i.close()}catch{}t(Error(`Dictation connection timed out`))}},P);i.onopen=()=>{},i.onmessage=t=>{let r;try{r=JSON.parse(String(t.data))}catch{return}if(!n&&r.type===`ready`){n=!0,clearTimeout(a),this.socket=i,this.connectPromise=null,this.notifyConnection(!0),e();return}this.handleMessage(r)},i.onerror=()=>{window.setTimeout(()=>{n||(n=!0,clearTimeout(a),this.connectPromise=null,t(Error(`Dictation connection failed`)))},250)},i.onclose=e=>{if(!n){n=!0,clearTimeout(a),this.connectPromise=null;let r=e?.reason?`: ${e.reason}`:``;t(Error(`Dictation connection failed${r}`));return}this.socket===i&&(this.socket=null,this.rejectAllPending(Error(`Dictation connection lost`)),this.notifyConnection(!1))}}),await this.connectPromise}}async startDictationStream(e,t){let n=new AbortController;this.directStarts.set(e,n);try{let r=await S(`asr`,n.signal);if(n.signal.throwIfAborted(),r){let i=new M(n,t=>{for(let n of this.partialListeners)n(e,t)},()=>{this.directSessions.delete(e),i.cancel(),this.notifyConnection(!1)});this.directSessions.set(e,i),await i.start(r,t),n.signal.throwIfAborted(),this.notifyConnection(!0);return}await this.ensureConnected(),n.signal.throwIfAborted()}catch(t){throw this.directSessions.get(e)?.cancel(),this.directSessions.delete(e),t}finally{this.directStarts.delete(e)}return this.activeDictations+=1,this.clearIdleCloseTimer(),new Promise((n,r)=>{let i=setTimeout(()=>{this.pendingStarts.delete(e),this.releaseDictation(),r(Error(`Dictation start timed out`))},F);this.pendingStarts.set(e,{resolve:()=>{clearTimeout(i),n()},reject:e=>{clearTimeout(i),this.releaseDictation(),r(e)},timeout:i}),this.send({type:`start`,dictationId:e,format:t})||(clearTimeout(i),this.pendingStarts.delete(e),this.releaseDictation(),r(Error(`Dictation connection lost`)))})}sendDictationStreamChunk(e,t,n){let r=this.directSessions.get(e);return r?r.send(t,n):this.send({type:`chunk`,dictationId:e,seq:t,audio:n})}finishDictationStream(e,t){let n=this.directSessions.get(e);return n?n.finish(t).finally(()=>{n.cancel(),this.directSessions.delete(e)}):new Promise((n,r)=>{let i={resolve:e=>{i.timeout&&clearTimeout(i.timeout),this.releaseDictation(),n(e)},reject:e=>{i.timeout&&clearTimeout(i.timeout),this.releaseDictation(),r(e)},timeout:null};i.timeout=setTimeout(()=>{this.pendingFinishes.delete(e),this.releaseDictation(),r(Error(`Timed out waiting for transcription`))},L),this.pendingFinishes.set(e,i),this.send({type:`finish`,dictationId:e,finalSeq:t})||(this.pendingFinishes.delete(e),i.reject(Error(`Dictation connection lost`)))})}cancelDictationStream(e){this.directStarts.get(e)?.abort(),this.directStarts.delete(e);let t=this.directSessions.get(e);if(t){t.cancel(),this.directSessions.delete(e);return}this.send({type:`cancel`,dictationId:e});let n=this.pendingStarts.get(e);n&&(this.pendingStarts.delete(e),n.reject(Error(`Dictation cancelled`)));let r=this.pendingFinishes.get(e);r&&(this.pendingFinishes.delete(e),r.reject(Error(`Dictation cancelled`))),this.releaseDictation(),this.scheduleIdleCloseIfReady()}handleMessage(e){let t=e.dictationId;if(t)switch(e.type){case`ack`:{let e=this.pendingStarts.get(t);e&&(this.pendingStarts.delete(t),e.resolve());return}case`partial`:for(let n of this.partialListeners)n(t,e.text??``);return;case`finish_accepted`:{let n=this.pendingFinishes.get(t);n&&typeof e.timeoutMs==`number`&&(n.timeout&&clearTimeout(n.timeout),n.timeout=setTimeout(()=>{this.pendingFinishes.delete(t),n.reject(Error(`Timed out waiting for transcription`))},e.timeoutMs+5e3));return}case`final`:{let n=this.pendingFinishes.get(t);n&&(this.pendingFinishes.delete(t),n.resolve({text:e.text??``})),this.scheduleIdleCloseIfReady();return}case`error`:{let n=N(e.error||`Dictation failed`,e.retryable!==!1,e.reasonCode),r=this.pendingStarts.get(t);r&&(this.pendingStarts.delete(t),r.reject(n));let i=this.pendingFinishes.get(t);i&&(this.pendingFinishes.delete(t),i.reject(n)),this.scheduleIdleCloseIfReady();return}}}send(e){if(!this.isConnected||!this.socket)return!1;try{return this.socket.send(JSON.stringify(e)),!0}catch{return!1}}notifyConnection(e){for(let t of this.connectionListeners)t(e)}rejectAllPending(e){for(let[t,n]of this.pendingStarts)this.pendingStarts.delete(t),n.reject(e);for(let[t,n]of this.pendingFinishes)this.pendingFinishes.delete(t),n.reject(e);this.activeDictations=0}releaseDictation(){this.activeDictations=Math.max(0,this.activeDictations-1),this.scheduleIdleCloseIfReady()}scheduleIdleCloseIfReady(){this.activeDictations>0||this.pendingFinishes.size>0||this.pendingStarts.size>0||(this.clearIdleCloseTimer(),this.idleCloseTimer=setTimeout(()=>{if(this.activeDictations===0&&this.pendingFinishes.size===0&&this.pendingStarts.size===0){let e=this.socket;if(this.socket=null,e){try{e.close(1e3,`idle`)}catch{}this.notifyConnection(!1)}}},I))}cancelAllForRuntimeSwitch(){for(let e of this.directStarts.values())e.abort();this.directStarts.clear();for(let e of this.directSessions.values())e.cancel();this.directSessions.clear(),this.clearIdleCloseTimer();let e=this.socket;if(this.socket=null,this.connectPromise=null,this.rejectAllPending(Error(`Runtime changed`)),e){try{e.close(1e3,`runtime switch`)}catch{}this.notifyConnection(!1)}}clearIdleCloseTimer(){this.idleCloseTimer&&=(clearTimeout(this.idleCloseTimer),null)}};typeof window<`u`&&window.addEventListener(`yuri:runtime-endpoint-changed`,()=>{R.cancelAllForRuntimeSwitch()});var z=128,B=`audio/pcm;rate=16000;bits=16`,V=()=>new Promise(e=>setTimeout(e,0)),H=()=>{let e=Math.random().toString(36).slice(2,10);return`dic_${Date.now().toString(16)}${e}`},ee=class{client;format;createDictationId;dictationId=null;sendSeq=0;segments=[];streamReady=!1;flushTimer=null;drainWaiters=[];startGeneration=0;startPromise=null;constructor(e){this.client=e.client,this.format=e.format??B,this.createDictationId=e.createDictationId??H}getDictationId(){return this.dictationId}getFinalSeq(){return this.segments.length-1}hasSegments(){return this.segments.length>0}clearAll(){this.dictationId&&this.client.cancelDictationStream(this.dictationId),this.clearScheduledFlush(),this.dictationId=null,this.sendSeq=0,this.segments=[],this.streamReady=!1,this.startPromise=null,this.startGeneration+=1}resetStreamForReplay(){this.dictationId&&this.client.cancelDictationStream(this.dictationId),this.clearScheduledFlush(),this.dictationId=null,this.sendSeq=0,this.streamReady=!1,this.startPromise=null,this.startGeneration+=1}enqueueSegment(e){if(this.segments.push(e),this.client.isConnected){if(!this.dictationId){this.startPromise||this.restartStream().catch(()=>{});return}this.flush()}}flush(){let e=this.dictationId;if(!this.client.isConnected||!e||!this.streamReady)return 0;let t=0;for(;this.sendSeq<this.segments.length&&t<z;){let n=this.sendSeq,r=this.segments[n];if(!this.client.sendDictationStreamChunk(e,n,r))break;this.sendSeq=n+1,t+=1}return this.hasPendingSegments()?this.scheduleFlush():this.resolveDrainWaiters(),t}async restartStream(){this.startGeneration+=1;let e=this.startGeneration,t=this.createDictationId();this.dictationId=t,this.sendSeq=0,this.streamReady=!1;let n=(async()=>{await this.client.startDictationStream(t,this.format),this.startGeneration===e&&this.dictationId===t&&(this.streamReady=!0,this.flush())})().catch(n=>{throw this.startGeneration===e&&this.dictationId===t&&(this.dictationId=null,this.streamReady=!1),n}).finally(()=>{this.startPromise===n&&(this.startPromise=null)});this.startPromise=n,await n}async finish(e){this.dictationId||await this.restartStream(),this.startPromise&&await this.startPromise;let t=this.dictationId;if(!t||!this.streamReady)throw Error(`Failed to start dictation stream`);return this.flush(),await this.waitForFlushDrain(),{dictationId:t,text:(await this.client.finishDictationStream(t,e)).text}}cancel(){this.resetStreamForReplay()}hasPendingSegments(){return this.sendSeq<this.segments.length}scheduleFlush(){this.flushTimer||=setTimeout(()=>{this.flushTimer=null,this.flush()},0)}clearScheduledFlush(){this.resolveDrainWaiters(),this.flushTimer&&=(clearTimeout(this.flushTimer),null)}async waitForFlushDrain(){for(;this.hasPendingSegments();){if(!this.client.isConnected||!this.dictationId||!this.streamReady)throw Error(`Failed to flush dictation stream`);await new Promise(e=>{this.drainWaiters.push(e)}),await V()}}resolveDrainWaiters(){let e=this.drainWaiters;this.drainWaiters=[];for(let t of e)t()}},U=c(),W=new Set;function G(e){return W.add(e),()=>{W.delete(e)}}function K(){for(let e of W)e();if(typeof window<`u`&&window.speechSynthesis?.cancel(),typeof navigator>`u`)return;let e=navigator.audioSession;if(e)try{e.type=`play-and-record`}catch{}}function te(){if(typeof navigator>`u`)return;let e=navigator.audioSession;if(e)try{e.type!==`playback`&&(e.type=`playback`)}catch{}}var q=16e3,J=q/5,Y=()=>{if(typeof window>`u`)return null;let e=window;return e.AudioContext||e.webkitAudioContext||null},X=e=>{let t=Math.max(-1,Math.min(1,e));return Math.round(t<0?t*32768:t*32767)},ne=(e,t,n)=>{if(e.length===0)return new Int16Array;if(t===n){let t=new Int16Array(e.length);for(let n=0;n<e.length;n++)t[n]=X(e[n]);return t}let r=t/n,i=Math.max(1,Math.round(e.length/r)),a=new Int16Array(i);for(let t=0;t<i;t++){let n=t*r,i=Math.floor(n),o=Math.min(e.length-1,i+1),s=n-i;a[t]=X(e[i]*(1-s)+e[o]*s)}return a},re=(e,t)=>{if(e.length===0)return t;if(t.length===0)return e;let n=new Int16Array(e.length+t.length);return n.set(e,0),n.set(t,e.length),n},Z=e=>{let t=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),n=``;for(let e=0;e<t.length;e++)n+=String.fromCharCode(t[e]);return btoa(n)},Q=()=>({stream:null,context:null,source:null,processor:null,gain:null,pending:new Int16Array,started:!1}),$=e=>{if(e)try{e.disconnect()}catch{}},ie=()=>typeof navigator>`u`||typeof window>`u`||!navigator.mediaDevices||typeof navigator.mediaDevices.getUserMedia!=`function`?!1:Y()!==null;function ae(e){let t=(0,U.c)(16),[n,r]=(0,x.useState)(0),i=(0,x.useRef)(e.onPcmSegment),a=(0,x.useRef)(e.onError),o,s;t[0]!==e.onError||t[1]!==e.onPcmSegment?(o=()=>{i.current=e.onPcmSegment,a.current=e.onError},s=[e.onPcmSegment,e.onError],t[0]=e.onError,t[1]=e.onPcmSegment,t[2]=o,t[3]=s):(o=t[2],s=t[3]),(0,x.useEffect)(o,s);let c;t[4]===Symbol.for(`react.memo_cache_sentinel`)?(c=Q(),t[4]=c):c=t[4];let u=(0,x.useRef)(c),d=(0,x.useRef)(0),f;t[5]===Symbol.for(`react.memo_cache_sentinel`)?(f=async()=>{if(u.current.started)return;if(typeof navigator>`u`||!navigator.mediaDevices||typeof navigator.mediaDevices.getUserMedia!=`function`)throw Error(`Microphone capture is not supported in this environment`);let e=Y();if(!e)throw Error(`AudioContext unavailable`);let t=d.current+=1;K();let n=await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,noiseSuppression:!0,echoCancellation:!0,autoGainControl:!0}});if(t!==d.current){n.getTracks().forEach(ue);return}let a=new e;try{if(a.state===`suspended`&&await a.resume().catch(le),t!==d.current){n.getTracks().forEach(ce),await a.close();return}let e=a.createMediaStreamSource(n),o=a.createScriptProcessor(4096,1,1),s=a.createGain();s.gain.value=0,u.current={stream:n,context:a,source:e,processor:o,gain:s,pending:new Int16Array,started:!0},o.onaudioprocess=e=>{let t=u.current;if(!t.started)return;let n=e.inputBuffer.getChannelData(0),o=0;for(let e=0;e<n.length;e++)o+=n[e]*n[e];let s=Math.sqrt(o/Math.max(1,n.length));r(Math.min(1,Math.max(0,s*2)));let c=ne(n,a.sampleRate,q);for(t.pending=re(t.pending,c);t.pending.length>=J;){let e=t.pending.slice(0,J);t.pending=t.pending.slice(J),i.current(Z(e))}},e.connect(o),o.connect(s),s.connect(a.destination)}catch(e){let t=e;n.getTracks().forEach(se);try{await a.close()}catch{}throw u.current=Q(),t instanceof Error?t:Error(String(t))}},t[5]=f):f=t[5];let p=l(f),m;t[6]===Symbol.for(`react.memo_cache_sentinel`)?(m=async()=>{d.current+=1;let e=u.current;if(e.started=!1,r(0),e.processor)try{e.processor.onaudioprocess=null}catch{}$(e.processor),$(e.source),$(e.gain),e.stream&&e.stream.getTracks().forEach(oe);let t=e.pending;if(e.pending=new Int16Array,t.length>0&&i.current(Z(t)),e.context)try{await e.context.close()}catch{}u.current===e&&(u.current=Q())},t[6]=m):m=t[6];let h=l(m),g,_;t[7]===h?(g=t[8],_=t[9]):(g=()=>()=>{h().catch(e=>{a.current?.(e instanceof Error?e:Error(String(e)))})},_=[h],t[7]=h,t[8]=g,t[9]=_),(0,x.useEffect)(g,_);let v;t[10]===p?v=t[11]:(v=async()=>{try{await p()}catch(e){let t=e,n=t instanceof Error?t:Error(String(t));throw a.current?.(n),n}},t[10]=p,t[11]=v);let y;return t[12]!==h||t[13]!==v||t[14]!==n?(y={start:v,stop:h,volume:n},t[12]=h,t[13]=v,t[14]=n,t[15]=y):y=t[15],y}function oe(e){try{e.stop()}catch{}}function se(e){try{e.stop()}catch{}}function ce(e){return e.stop()}function le(){}function ue(e){return e.stop()}var de=1e3,fe=e=>e instanceof Error?e:Error(String(e));function pe(e={}){let{t}=u(),{onTranscript:r,onError:i,canStart:a}=e,[o,s]=(0,x.useState)(`idle`),[c,d]=(0,x.useState)(!1),[f,p]=(0,x.useState)(``),[m,h]=(0,x.useState)(0),[g,_]=(0,x.useState)(null),[v,y]=(0,x.useState)(null),b=(0,x.useRef)(o);(0,x.useEffect)(()=>{b.current=o},[o]);let S=(0,x.useRef)(``),C=(0,x.useRef)(null),w=(0,x.useRef)({starting:!1,confirming:!1,cancelling:!1}),T=(0,x.useRef)(0),E=(0,x.useRef)(r),D=(0,x.useRef)(i);(0,x.useEffect)(()=>{E.current=r,D.current=i},[r,i]);let O=(0,x.useRef)(null);O.current||=new ee({client:R});let k=l(()=>{C.current&&=(clearInterval(C.current),null)}),A=l(()=>{C.current||=setInterval(()=>{h(e=>e+1)},de)}),j=l(e=>{let n=fe(e),r=n.name===`NotFoundError`||n.name===`DevicesNotFoundError`?Error(t(`chat.dictation.error.microphoneNotFound`),{cause:n}):n;_(r.message);let i=n.reasonCode;y(typeof i==`string`?i:null),D.current?.(r)}),M=l(()=>{_(null),y(null)}),N=l(()=>{O.current?.clearAll(),S.current=``,p(``)}),P=l(t=>e.onPartialTranscript?.(t));(0,x.useEffect)(()=>R.onPartial((e,t)=>{let n=O.current?.getDictationId();!n||e!==n||(S.current=t,p(t),P(t))}),[P]),(0,x.useEffect)(()=>R.subscribeConnectionStatus(e=>{if(!e){b.current===`recording`&&O.current?.resetStreamForReplay();return}if(b.current!==`recording`||O.current?.getDictationId())return;let t=T.current;O.current?.restartStream().catch(e=>{T.current===t&&j(e)})}),[j]);let F=ae({onPcmSegment:e=>{b.current===`recording`&&O.current?.enqueueSegment(e)},onError:e=>{D.current?.(e)}}),I=(0,x.useRef)(F.stop);(0,x.useEffect)(()=>{I.current=F.stop},[F.stop]);let L=l(e=>{h(0),s(`idle`),b.current=`idle`;let t=e.trim();return N(),t?(E.current?.(t),t):null}),z=l(e=>{O.current?.hasSegments()?(s(`failed`),b.current=`failed`):(s(`idle`),b.current=`idle`),j(e)}),B=l(async()=>{let e=w.current;if(e.starting||e.confirming||e.cancelling||b.current!==`idle`||a&&!a())return;e.starting=!0,d(!0);let t=++T.current;M(),p(``),h(0),s(`recording`),b.current=`recording`,N();try{if(await F.start(),T.current!==t||b.current!==`recording`)return;d(!1),A(),await O.current?.restartStream().catch(e=>{T.current===t&&j(e)})}catch(e){if(T.current!==t)return;await F.stop().catch(()=>void 0),k(),s(`idle`),b.current=`idle`,j(e)}finally{T.current===t&&d(!1),e.starting=!1}}),V=l(async()=>{let e=w.current;if(!e.cancelling&&(b.current===`recording`||b.current===`uploading`)){e.cancelling=!0,d(!1),T.current+=1,k(),h(0),M(),s(`idle`),b.current=`idle`;try{O.current?.cancel()}catch{}N();try{await F.stop()}catch{}finally{e.cancelling=!1}}}),H=l(async()=>{let e=w.current;if(e.confirming||b.current!==`recording`)return null;e.confirming=!0,d(!1);let t=++T.current;M(),k();try{if(await F.stop(),T.current!==t)return null;s(`uploading`),b.current=`uploading`;let e=O.current?.getFinalSeq()??-1;if(e<0)return O.current?.cancel(),L(``);let n=await O.current.finish(e);return T.current===t?L(n.text):null}catch(e){return T.current===t&&z(e),null}finally{e.confirming=!1}}),U=l(async()=>{if(b.current!==`failed`||!O.current?.hasSegments())return null;M();let e=++T.current;s(`uploading`),b.current=`uploading`;try{O.current.resetStreamForReplay();let t=O.current.getFinalSeq(),n=await O.current.finish(t);return T.current===e?L(n.text):null}catch(t){return T.current===e&&z(t),null}}),W=l(()=>{if(b.current!==`failed`)return null;let e=S.current.trim();h(0),s(`idle`),b.current=`idle`,M();try{O.current?.cancel()}catch{}return N(),e?(E.current?.(e),e):null}),G=l(()=>{h(0),s(`idle`),b.current=`idle`,M(),N()});return(0,x.useEffect)(()=>n(()=>{b.current===`failed`?(T.current+=1,G()):V()}),[V,G]),(0,x.useEffect)(()=>{if(o!==`recording`||v!==`model_download_in_progress`)return;let e=setInterval(()=>{b.current!==`recording`||O.current?.getDictationId()||O.current?.restartStream().then(()=>{M()}).catch(e=>{j(e)})},3e3);return()=>clearInterval(e)},[o,v,M,j]),(0,x.useEffect)(()=>()=>{T.current+=1,k(),I.current().catch(()=>void 0),O.current?.cancel()},[k]),{status:o,isRecording:o===`recording`,isStarting:c,isProcessing:o===`uploading`,partialTranscript:f,volume:F.volume,duration:m,error:g,errorReason:v,startDictation:B,confirmDictation:H,cancelDictation:V,retryFailedDictation:U,acceptPartialTranscript:W,discardFailedDictation:G}}var me=`app-region-no-drag transition-[opacity,transform] duration-150 ease-out data-[starting-style]:opacity-0 data-[starting-style]:scale-95 data-[ending-style]:opacity-0 data-[ending-style]:scale-95 z-50 max-h-[var(--available-height)] min-w-[8rem] origin-[var(--transform-origin)] overflow-visible rounded-xl p-1 shadow-[inset_0_1px_0_0_rgba(255,255,255,0.8),inset_0_0_0_1px_rgba(0,0,0,0.04),0_0_0_1px_rgba(0,0,0,0.10),0_1px_2px_-0.5px_rgba(0,0,0,0.08),0_4px_8px_-2px_rgba(0,0,0,0.08),0_12px_20px_-4px_rgba(0,0,0,0.08)] dark:shadow-[inset_0_1px_0_0_rgba(255,255,255,0.12),inset_0_0_0_1px_rgba(255,255,255,0.08),0_0_0_1px_rgba(0,0,0,0.36),0_1px_1px_-0.5px_rgba(0,0,0,0.22),0_3px_3px_-1.5px_rgba(0,0,0,0.20),0_6px_6px_-3px_rgba(0,0,0,0.16)]`,he=`data-[highlighted]:bg-interactive-hover hover:bg-interactive-hover active:bg-interactive-active data-[variant=destructive]:text-destructive data-[variant=destructive]:hover:bg-destructive/10 dark:data-[variant=destructive]:hover:bg-destructive/20 data-[variant=destructive]:hover:text-destructive data-[variant=destructive]:*:[svg]:!text-destructive [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-pointer items-center gap-2 rounded-lg px-2 py-1 typography-ui-label outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-3.5`,ge=`data-[highlighted]:bg-interactive-hover hover:bg-interactive-hover active:bg-interactive-active [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-pointer items-center gap-2 rounded-lg px-2 py-1 typography-ui-label outline-hidden select-none data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-3.5`,_e=`bg-border -mx-1 my-0.5 h-px`;export{m as S,f as _,pe as a,_ as b,te as c,j as d,A as f,d as g,C as h,ge as i,G as l,S as m,me as n,ie as o,O as p,_e as r,K as s,he as t,k as u,p as v,y as x,b as y};
|
package/dist/assets/{fileMentionTouchSelection-C6ylhQkG.js → fileMentionTouchSelection-BSSggGfQ.js}
RENAMED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{r as e}from"./rolldown-runtime-hePW80VL.js";import{it as t,nt as n,rt as r}from"./vendor-base-ui-CdzJ6My_.js";import{at as i}from"./persistence-
|
|
1
|
+
import{r as e}from"./rolldown-runtime-hePW80VL.js";import{it as t,nt as n,rt as r}from"./vendor-base-ui-CdzJ6My_.js";import{at as i}from"./persistence-BfjCXjLZ.js";import{n as a}from"./vendor-react-BP2cRVqX.js";import{r as o}from"./button-BgnrCA96.js";import{st as s}from"./useMobileNavigationStore-BQHfCZ55.js";import{r as c,t as l}from"./Icon-GJTjieJN.js";import{t as u}from"./vendor-fuzzysort-ukaRp9PC.js";var d=e=>{switch(e.name){case`new`:return`add`;case`init`:return`file`;case`undo`:return`arrow-go-back`;case`redo`:return`arrow-go-forward`;case`timeline`:return`time`;case`compact`:return`scissors`;case`reload`:return`refresh`;case`goal`:return`target`;case`review`:return`search-eye`;case`test`:case`build`:case`run`:return`terminal-box`;default:return e.isBuiltIn?`flashlight`:`command`}},f=()=>`book-open`,p=e=>{if(e.isDirectory)return`folder-3-fill`;switch(e.extension?.toLowerCase()){case`ts`:case`tsx`:case`js`:case`jsx`:case`json`:return`code`;case`md`:case`mdx`:return`file`;case`png`:case`jpg`:case`jpeg`:case`gif`:case`svg`:return`file-image`;default:return`file-pdf`}},m=()=>`ai-agent`,h=()=>`chat-thread`,g=32,_=(e,t)=>{let n=c[e];return typeof n!=`string`||n.length===0?null:`<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="${t}" stroke-width="${l}" stroke-linecap="round" stroke-linejoin="round">${n}</svg>`},v=(e,t)=>{let n=_(e,t);return!n||typeof document>`u`?Promise.resolve(null):new Promise(e=>{let t=new Image;t.decoding=`async`,t.onload=()=>{try{let n=document.createElement(`canvas`);n.width=g,n.height=g;let r=n.getContext(`2d`);if(!r){e(null);return}r.clearRect(0,0,g,g),r.drawImage(t,0,0,g,g);let i=n.toDataURL(`image/png`),a=i.indexOf(`,`);e(a>=0?i.slice(a+1):null)}catch{e(null)}},t.onerror=()=>e(null),t.src=`data:image/svg+xml;charset=utf-8,${encodeURIComponent(n)}`})},y=e(u(),1),b=(e,t)=>e.map(e=>{let n=e.isSkill?t.skill:e.isYuri?`Yuri`:e.isBuiltIn?t.system:e.scope||e.agent||t.command;return{id:e.id,title:`/${e.name}`,subtitle:e.description,badge:n,iconName:d(e)}}),x=({skills:e=[],agents:t,sessions:n,recentFiles:r,pathHits:i,untitledSession:a,sessionBadge:o,skillBadge:s,searchQuery:c=``})=>{let l=[];for(let t of e)l.push({id:`skill:${t.name}-${t.scope}`,title:`@${t.name}`,subtitle:t.description,badge:s??t.scope,iconName:f()});for(let e of t)l.push({id:`agent:${e.name}`,title:`@${e.name}`,subtitle:e.description,iconName:m(),agentName:e.name});let u=c.trim(),d=u?y.default.go(u,l,{keys:[`title`,e=>e.id.startsWith(`skill:`)?e.subtitle??``:``],threshold:.5,limit:10,scoreFn:e=>{let t=e[0],n=(t?.score??0)*(t?.target.startsWith(`@${u}`)?2:1);return n>=.5?1+n:e[1]?.score??0}}).map(e=>e.obj):l.slice();l.length=0;for(let e of r)l.push({id:`recent:${e.path}`,title:e.relativePath||e.name,iconName:p(e)});for(let e of i)l.push({id:`file:${e.path}`,title:e.relativePath||e.name,iconName:p(e)});for(let e of n)l.push({id:`session:${e.id}`,title:e.title||a,badge:o,iconName:h()});return u?[...d,...l].slice(0,10):[...d,...l]},S=(e,t)=>{if(!e.includes(`/`)||t.size===0)return[];let n=RegExp(`(^|\\s)/(${i})?([A-Za-z0-9][A-Za-z0-9_-]*)(?=$|\\s)`,`g`),r=[],a;for(;(a=n.exec(e))!==null;){let e=a[3]??``;if(!t.has(e.toLowerCase()))continue;let n=a[2]??``,i=a.index+(a[1]?.length??0);r.push({start:i,end:i+1+n.length+e.length,name:e,hasSlot:n.length>0})}return r},C=(e,t,n=e.length)=>{let r=S(e,t).filter(e=>!e.hasSlot);if(r.length===0)return null;let a=e,o=n;for(let e=r.length-1;e>=0;--e){let t=r[e].start+1;a=`${a.slice(0,t)}${i}${a.slice(t)}`,o>t&&(o+=i.length)}return a===e?null:{text:a,caret:o}},w=e=>e.startsWith(i)?e.slice(i.length):e,T=e=>{if(e.inputMode===`shell`)return null;let t=e.text,n=Math.max(0,Math.min(e.cursor,t.length));if(t.startsWith(`/`)){let e=t.indexOf(` `),r=t.indexOf(`
|
|
2
2
|
`),i=Math.min(e===-1?t.length:e,r===-1?t.length:r);if(n<=i&&e===-1)return{kind:`slash-command`,query:w(t.substring(1,i)),tokenStart:0,tokenEnd:i}}let r=t.substring(0,n),i=s({value:t,cursorPosition:n,inputSource:e.mentionInputSource??`manual`,insertedText:e.insertedText});return i===null?null:{kind:`mention`,query:i,tokenStart:r.lastIndexOf(`@`),tokenEnd:n}},E=e=>e===`mention`?`@`:`/`,D=(e,t,n)=>{if(n&&n.tokenStart>=0&&n.tokenEnd>=n.tokenStart&&n.tokenEnd<=e.length&&e.startsWith(E(n.kind),n.tokenStart))return{start:n.tokenStart,end:n.tokenEnd};let r=T({text:e,cursor:t});return r?{start:r.tokenStart,end:r.tokenEnd}:null},O=e(t(),1),k=a(),A=e(n(),1),j=`absolute z-[100] min-w-0 w-full bottom-full mb-2 left-0 flex flex-col rounded-xl`,M=`pointer-events-auto absolute z-[100] min-w-0 flex flex-col rounded-xl`;function N(e,t){return o(e?M:j,`yuri-mobile-overlay-surface yuri-mobile-overlay-surface--translucent yuri-composer-autocomplete-surface`,t)}function P(e,t){return e?`yuri-composer-autocomplete-row`:o(`mx-1.5 hover:bg-[color-mix(in_srgb,var(--interactive-selection)_40%,transparent)]`,t&&`bg-[color-mix(in_srgb,var(--interactive-selection)_40%,transparent)]`)}var F=.4,I=e=>{let t=e.gap??8,n=Math.min(e.composerTop-t,e.visibleBottom-t);return{left:e.composerLeft,width:e.composerWidth,bottom:Math.max(0,e.fixedContainingBottom-n),maxHeight:L({popupBottom:n,boundaryTop:e.boundaryTop,viewportHeight:e.viewportHeight,gap:t})}},L=e=>{let t=e.gap??8,n=Math.max(0,e.popupBottom-e.boundaryTop-t),r=e.viewportHeight*F,i=Math.floor(Math.min(n,r));return n>=120?Math.min(n,Math.max(120,i)):i},R=(e,t=0)=>{let n=e.closest(`main`);if(!n)return null;let r=(e.closest(`.mobile-chat-screen__content`)?.parentElement??n.parentElement?.closest(`main`)??n).querySelector(`:scope > .yuri-mobile-detail-navigation`)?.getBoundingClientRect().bottom,i=n.getBoundingClientRect().top;return Math.max(r===void 0?i:Math.max(r,i),t)},z=(e,t)=>{let n=(0,k.c)(5),[r,i]=O.useState(void 0),a;n[0]!==t||n[1]!==e?(a=()=>{if(!t){i(void 0);return}let n=0,r=0,a=()=>{let t=e.current?.parentElement;if(!t)return;let n=t.getBoundingClientRect(),r=window.visualViewport,a=r?.offsetTop??0,o=r?.height??window.innerHeight,s=window.innerHeight,c=a+o,l=R(t,a)??a,u=I({composerTop:n.top,composerLeft:n.left,composerWidth:n.width,fixedContainingBottom:s,visibleBottom:c,boundaryTop:l,viewportHeight:o});i(e=>e&&e.left===u.left&&e.width===u.width&&e.bottom===u.bottom&&e.maxHeight===u.maxHeight?e:u)},o=()=>{a(),n&&window.cancelAnimationFrame(n),r&&window.clearTimeout(r),n=window.requestAnimationFrame(()=>{a(),r=window.setTimeout(a,220)})};return a(),window.addEventListener(`resize`,a),window.addEventListener(`yuri:keyboard-settled`,o),window.addEventListener(`yuri:keyboard-anim`,o),window.visualViewport?.addEventListener(`resize`,a),window.visualViewport?.addEventListener(`scroll`,a),()=>{n&&window.cancelAnimationFrame(n),r&&window.clearTimeout(r),window.removeEventListener(`resize`,a),window.removeEventListener(`yuri:keyboard-settled`,o),window.removeEventListener(`yuri:keyboard-anim`,o),window.visualViewport?.removeEventListener(`resize`,a),window.visualViewport?.removeEventListener(`scroll`,a)}},n[0]=t,n[1]=e,n[2]=a):a=n[2];let o;return n[3]===t?o=n[4]:(o=[t],n[3]=t,n[4]=o),O.useLayoutEffect(a,o),t?r:void 0},B=r(),V=O.forwardRef((e,t)=>{let n=(0,k.c)(24),{isMobile:r,className:i,style:a,children:o}=e,s=O.useRef(null),c=z(s,r),l=typeof document<`u`?document.body:null;if(!r){let e;n[0]===i?e=n[1]:(e=N(!1,i),n[0]=i,n[1]=e);let r;return n[2]!==o||n[3]!==t||n[4]!==a||n[5]!==e?(r=(0,B.jsx)(`div`,{ref:t,className:e,style:a,children:o}),n[2]=o,n[3]=t,n[4]=a,n[5]=e,n[6]=r):r=n[6],r}let u;n[7]===i?u=n[8]:(u=N(!0,i),n[7]=i,n[8]=u);let d;n[9]===c?d=n[10]:(d=c?{left:c.left,width:c.width,bottom:c.bottom,maxHeight:c.maxHeight,overflow:`hidden`}:{visibility:`hidden`},n[9]=c,n[10]=d);let f;n[11]!==a||n[12]!==d?(f={...a,...d},n[11]=a,n[12]=d,n[13]=f):f=n[13];let p;n[14]!==o||n[15]!==t||n[16]!==u||n[17]!==f?(p=(0,B.jsx)(`div`,{className:`pointer-events-none fixed inset-0 z-[100]`,children:(0,B.jsx)(`div`,{ref:t,className:u,style:f,children:o})}),n[14]=o,n[15]=t,n[16]=u,n[17]=f,n[18]=p):p=n[18];let m=p,h;n[19]===Symbol.for(`react.memo_cache_sentinel`)?(h=(0,B.jsx)(`span`,{ref:s,className:`hidden`,"aria-hidden":!0}),n[19]=h):h=n[19];let g;n[20]===m?g=n[21]:(g=l?(0,A.createPortal)(m,l):m,n[20]=m,n[21]=g);let _;return n[22]===g?_=n[23]:(_=(0,B.jsxs)(B.Fragment,{children:[h,g]}),n[22]=g,n[23]=_),_});V.displayName=`ComposerAutocompleteLayer`;var H=()=>{let e=null,t=!1,n=!1;return{pointerDown:(n,r)=>{e={x:n,y:r},t=!1},pointerMove:(n,r)=>{e&&Math.hypot(n-e.x,r-e.y)>6&&(t=!0)},pointerCancel:()=>{e=null,t=!1},pointerUp:r=>{if(!e)return!1;let i=!t;return e=null,t=!1,i?(n=!0,r(),!0):(n=!0,!1)},click:e=>n?(n=!1,!1):(e(),!0)}};export{T as a,x as c,d,D as i,b as l,V as n,C as o,P as r,w as s,H as t,v as u};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{n as e}from"./rolldown-runtime-hePW80VL.js";import{i as t}from"./runtime-switch-CAZiOV2G.js";import{n}from"./runtime-fetch-BAN5Gnnp.js";import{
|
|
1
|
+
import{n as e}from"./rolldown-runtime-hePW80VL.js";import{i as t}from"./runtime-switch-CAZiOV2G.js";import{n}from"./runtime-fetch-BAN5Gnnp.js";import{C as r,b as i,v as a,y as o}from"./desktop-dp2Z0toS.js";import{n as s}from"./useUIStore-NMQx_cnG.js";import{i as c,o as l,t as u}from"./path-utils-jGozTg9d.js";import{c as d,i as f,s as p}from"./toolHelpers-DL452NVK.js";import{a as m,i as h,n as g,o as _,r as ee,t as v}from"./fileReferenceParser-1HHDBUum.js";var y=`data-yuri-block-path-token`,b=`[${y}]`,x=`data-yuri-file-link`,S=`[${x}="true"]`,C=[x,`data-yuri-file-ref`,`data-yuri-file-path`,`data-yuri-file-binary`,`title`,`role`,`tabindex`],w=`data-yuri-block-paths-scanned`,T=`data-yuri-paragraph-paths-scanned`,E=`pre, code, a, script, style, button, [${x}], ${b}`,D=2e5,O=e=>{let t=_(e);return t?h(t.path):!1},te=e=>{let t=e.trim();return!t||t.startsWith(`#`)||t.startsWith(`?`)||t.startsWith(`//`)?!1:/^[A-Za-z]:[\\/]/.test(t)||/^file:/i.test(t)||O(t)&&/:\d+(?:-\d+|:\d+)?$/.test(t)?!0:!/^[A-Za-z][A-Za-z0-9+.-]*:/.test(t)},k=(e,t)=>{let n=0;for(let r of e){let e=n+r.data.length;if(t<=e)return{node:r,offset:Math.max(0,t-n)};n=e}let r=e.at(-1);return r?{node:r,offset:r.data.length}:null},A=e=>{let t=e.querySelectorAll(`pre code`);if(t.length===0)return;let n=e.ownerDocument;if(n)for(let e of Array.from(t)){if(e.getAttribute(w)===`true`)continue;if((e.textContent??``).length>D){e.setAttribute(w,`true`);continue}let t=n.createTreeWalker(e,NodeFilter.SHOW_TEXT),r=[],i=t.nextNode();for(;i;)r.push(i),i=t.nextNode();let a=e.textContent??``;if(!a.includes(`.`)){e.setAttribute(w,`true`);continue}v.lastIndex=0;let o=[],s=v.exec(a);for(;s;){let e=s[0];e&&O(e)&&o.push({start:s.index,end:s.index+e.length,raw:e}),s=v.exec(a)}for(let{start:e,end:t,raw:i}of o.reverse()){let a=k(r,e),o=k(r,t);if(!a||!o)continue;let s=n.createRange();s.setStart(a.node,a.offset),s.setEnd(o.node,o.offset);let c=n.createElement(`span`);c.setAttribute(y,`true`),c.textContent=i,s.deleteContents(),s.insertNode(c)}e.setAttribute(w,`true`)}},j=e=>{let t=e.ownerDocument;if(!t)return;let n=e.querySelectorAll(`p, li, blockquote, h1, h2, h3, h4, h5, h6, td, th`);if(n.length!==0)for(let e of Array.from(n)){if(e.getAttribute(T)===`true`)continue;if(e.closest(E)){e.setAttribute(T,`true`);continue}let n=t.createTreeWalker(e,NodeFilter.SHOW_TEXT,{acceptNode:e=>{let t=e.parentElement;return!t||t.closest(E)?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT}}),r=[],i=n.nextNode();for(;i;)r.push(i),i=n.nextNode();if(r.length===0){e.setAttribute(T,`true`);continue}let a=r.map(e=>e.data).join(``);if(!a.includes(`/`)||!a.includes(`.`)){e.setAttribute(T,`true`);continue}g.lastIndex=0;let o=[],s=g.exec(a);for(;s;){let e=s[0];if(!e){s=g.exec(a);continue}let t=s.index>=2?a.slice(s.index-2,s.index):``;if((s.index>=1?a.charAt(s.index-1):``)===`:`||t===`:/`){s=g.exec(a);continue}O(e)&&o.push({start:s.index,end:s.index+e.length,raw:e}),s=g.exec(a)}for(let{start:e,end:n,raw:i}of o.reverse()){let a=k(r,e),o=k(r,n);if(!a||!o)continue;let s=t.createRange();s.setStart(a.node,a.offset),s.setEnd(o.node,o.offset);let c=t.createElement(`span`);c.setAttribute(y,`true`),c.textContent=i,s.deleteContents(),s.insertNode(c)}e.setAttribute(T,`true`)}},M=e=>{A(e),j(e)},N=(e,t)=>{if(e.getAttribute(`data-yuri-file-link`)!==`true`)return;let n=(e.getAttribute(`data-yuri-file-ref`)||e.textContent||``).trim(),r=(t.textContent||``).trim();if(!(!n||n!==r))for(let n of C){let r=e.getAttribute(n);r===null?t.removeAttribute(n):t.setAttribute(n,r)}},P=e({FILE_REFERENCE_OPEN_TITLE:()=>F,extractPathCandidateFromElement:()=>q,getFileReferenceInfo:()=>Y,getFileReferenceLinkLimit:()=>H,getResolvedReference:()=>J,openFileReference:()=>Q,openFileReferenceFromElement:()=>$,peekFileReferenceInfo:()=>K,probeFileReference:()=>X,resetFileReferenceStatCacheForTests:()=>ce,shouldOfferFileReference:()=>Z}),F=`Open file`,ne=4,re=1e3,ie=200,ae=80,oe=40,I=new Map,L=new Map,R=(e,n)=>JSON.stringify([t(),n,e]),z=0,B=[],V=()=>r()?ie:re,H=()=>r()?oe:ae,U=(e,t)=>{L.set(e,t)},W=()=>{let e=I.keys().next().value;typeof e==`string`&&(I.delete(e),L.delete(e))},G=(e,t)=>{let n=V();for(;I.size>=n;)W();I.set(e,t)},K=(e,t=``)=>{let n=m(e);if(n)return L.get(R(n,t))},q=e=>{if(e.tagName.toLowerCase()===`a`){let t=e.getAttribute(`href`)?.trim();if(t&&O(t))return t}return(e.textContent||``).trim()},J=(e,t)=>{let n=_(e);if(!n||!h(n.path))return null;let r=ee(n.path)?m(n.path):l(t,n.path);return r?{...n,resolvedPath:r}:null},Y=(e,t=``)=>{let r=m(e);if(!r)return Promise.resolve({exists:!1,isBinary:!1});let i=R(r,t),a=I.get(i);if(a)return I.delete(i),I.set(i,a),a;let o=new Promise((e,a)=>{let s=()=>{z+=1,n(`/api/fs/stat?path=${encodeURIComponent(r)}&optional=true`,{method:`GET`,cache:`no-store`,...t?{query:{directory:t}}:{}}).then(async t=>{if(!t.ok)throw Error(`File reference probe failed (${t.status})`);let n=await t.json();if(!n||typeof n.exists!=`boolean`&&n.isFile!==!0)throw Error(`Invalid file reference probe response`);let r={exists:n.exists!==!1,isBinary:n.isBinary===!0};U(i,r),e(r)}).catch(e=>{I.get(i)===o&&(I.delete(i),L.delete(i)),a(e)}).finally(()=>{z=Math.max(0,z-1),B.shift()?.()})};if(z<ne){s();return}B.push(s)});return G(i,o),o},X=(e,t)=>{if(!(i()&&o()&&!c(e,t)))return Y(e,t);let n=m(e);if(!n)return Promise.resolve({exists:!1,isBinary:!1});let r=R(n,t),s=I.get(r);if(s)return I.delete(r),I.set(r,s),s;let l=a(e).then(e=>{let t={exists:!0,isBinary:e===!0};return U(r,t),t});return G(r,l),l},Z=(e,t,n)=>!(!t.exists||n&&t.isBinary&&!d(e)&&!p(e)),se=(e,t)=>e||u(e,t),Q=async(e,t,n)=>{let r=J(e,n.effectiveDirectory);if(!r)return;if(d(r.resolvedPath)&&n.onShowPopup){let e=r.resolvedPath.split(`/`).filter(Boolean).pop()??r.resolvedPath;n.onShowPopup({open:!0,title:e,content:``,metadata:{tool:`image-preview`,filename:e,mime:f(r.resolvedPath)},image:{url:r.resolvedPath,filename:e,mimeType:f(r.resolvedPath)}});return}let i=se(n.effectiveDirectory,r.resolvedPath),a=p(r.resolvedPath);if(n.preferRuntimeEditor&&n.editor&&!a){n.editor.openFile(r.resolvedPath,Number.isFinite(r.line??NaN)?Math.max(1,Math.trunc(r.line)):void 0,Number.isFinite(r.column??NaN)?Math.max(1,Math.trunc(r.column)):void 0);return}let o=s.getState();if(a){o.openContextFile(i,r.resolvedPath,{viewerMode:`preview`});return}if(Number.isFinite(r.line??NaN)){o.openContextFileAtLine(i,r.resolvedPath,Math.max(1,Math.trunc(r.line)),Number.isFinite(r.column??NaN)?Math.max(1,Math.trunc(r.column)):1);return}o.openContextFile(i,r.resolvedPath)},$=async(e,t)=>{await Q(e.getAttribute(`data-yuri-file-ref`)||q(e),e.getAttribute(`data-yuri-file-binary`)===`true`,t)},ce=()=>{I.clear(),L.clear(),z=0,B.length=0};export{J as a,X as c,x as d,S as f,M as g,te as h,H as i,Z as l,O as m,q as n,$ as o,N as p,P as r,K as s,F as t,b as u};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{n as e}from"./rolldown-runtime-hePW80VL.js";import{i as t,n}from"./runtime-switch-CAZiOV2G.js";import{n as r}from"./runtime-fetch-BAN5Gnnp.js";import{t as i}from"./runtimeAPIRegistry-C2VogTny.js";import{$ as a,A as o,C as s,F as c,G as l,J as u,K as d,L as f,M as p,N as m,Nt as ee,O as te,Q as ne,R as re,S as ie,T as ae,X as oe,Y as h,Z as se,_ as ce,at as le,b as ue,c as de,d as fe,gt as pe,h as me,ht as he,it as ge,lt as _e,m as ve,nt as ye,o as be,pt as xe,rt as Se,u as Ce,ut as we,v as Te,vt as Ee,w as De,x as Oe,xt as ke,yt as Ae,z as je}from"./platform-
|
|
1
|
+
import{n as e}from"./rolldown-runtime-hePW80VL.js";import{i as t,n}from"./runtime-switch-CAZiOV2G.js";import{n as r}from"./runtime-fetch-BAN5Gnnp.js";import{t as i}from"./runtimeAPIRegistry-C2VogTny.js";import{$ as a,A as o,C as s,F as c,G as l,J as u,K as d,L as f,M as p,N as m,Nt as ee,O as te,Q as ne,R as re,S as ie,T as ae,X as oe,Y as h,Z as se,_ as ce,at as le,b as ue,c as de,d as fe,gt as pe,h as me,ht as he,it as ge,lt as _e,m as ve,nt as ye,o as be,pt as xe,rt as Se,u as Ce,ut as we,v as Te,vt as Ee,w as De,x as Oe,xt as ke,yt as Ae,z as je}from"./platform-Dcd-lkPn.js";import{d as g,ga as _,l as Me,wa as v}from"./useMobileNavigationStore-BQHfCZ55.js";var Ne=e({COMMIT_DIFF_FILE_LIMIT:()=>30,COMMIT_DIFF_TOTAL_CHAR_LIMIT:()=>j,SESSION_GENERATE_TIMEOUT_MS:()=>M,applyGitStash:()=>K,checkIsGitRepository:()=>x,checkoutCommit:()=>$e,cherryPick:()=>et,collectSelectedFileDiffs:()=>N,countGitStashFiles:()=>W,createBranch:()=>Y,createGitIdentity:()=>Q,createGitWorktree:()=>B,deleteGitIdentity:()=>Je,deleteGitWorktree:()=>V,deleteRemoteBranch:()=>A,discoverGitCredentials:()=>Ye,discoverGitRepositories:()=>S,dropGitStash:()=>J,generateCommitMessage:()=>F,getCommitFileDiff:()=>X,getConflictDetails:()=>$,getGitBranches:()=>k,getGitIdentities:()=>Z,getGitStatus:()=>C,getGitWorktreeBootstrapStatus:()=>R,getGlobalGitIdentity:()=>Xe,git:()=>H,listGitStashes:()=>U,listGitWorktrees:()=>I,merge:()=>Qe,popGitStash:()=>q,previewGitWorktree:()=>z,rebase:()=>Ze,resetToCommit:()=>nt,resolveGitPrimaryRoot:()=>w,resolveGitTopLevel:()=>T,revertCommit:()=>tt,stageGitFile:()=>E,stageGitFiles:()=>D,stashGitChanges:()=>G,unstageGitFile:()=>Pe,unstageGitFiles:()=>O,updateGitIdentity:()=>qe,validateGitWorktree:()=>L}),y=()=>i()?.git??null,b=e=>{let t=e.trim(),n=(t.match(/```(?:json)?\s*([\s\S]*?)```/i)?.[1]??t).trim(),r=[n.indexOf(`{`)].filter(e=>e>=0);for(let e of r)for(let t=n.length;t>e;--t)if(n[t-1]===`}`)try{let r=JSON.parse(n.slice(e,t));if(r&&typeof r==`object`&&!Array.isArray(r))return r}catch{}return null};async function x(e){let t=y();return t?t.checkIsGitRepository(e):de(e)}async function S(e){return De(e)}async function C(e,t){let n=y();return n?n.getGitStatus(e,t):f(e,t)}async function w(e){return(await Se(e)).root}async function T(e){return(await ge(e)).root}async function E(e,t){let n=y();return n?.stageGitFile?n.stageGitFile(e,t):_e(e,t)}async function D(e,t){let n=y();return n?.stageGitFiles?n.stageGitFiles(e,t):we(e,t)}async function Pe(e,t){let n=y();return n?.unstageGitFile?n.unstageGitFile(e,t):he(e,t)}async function O(e,t){let n=y();return n?.unstageGitFiles?n.unstageGitFiles(e,t):pe(e,t)}async function k(e,t){let n=y();if(t?.signal?.throwIfAborted(),n){let r=await n.getGitBranches(e,t);return t?.signal?.throwIfAborted(),r}return p(e,t)}async function A(e,t){let n=y();return n?n.deleteRemoteBranch(e,t):ie(e,t)}var j=12e4,M=9e4,Fe=[`This is an auxiliary structured generation request (git copy).`,`Use the active session context plus the materials below.`,`Answer with the required JSON only.`,`Do not call any tools and do not take any actions.`,`Model and instructions follow the session.generate session contract.`].join(` `),Ie=`Select an active session for generation. session.generate uses that session model contract and does not mutate chat history.`,Le=`No default provider or model configured. Please select a provider and model in settings first.`,Re=`Runtime changed during session.generate`,ze=`session.generate returned empty text`,Be=`session.generate returned invalid structured output`,Ve=e=>{let t=[`Diff budget: included ${e.includedFileCount} of ${e.selectedFileCount} selected files`,`fileLimit=${e.fileLimit}`,`charLimit=${e.charLimit}`,`truncatedByCharLimit=${e.truncatedByCharLimit?`yes`:`no`}`,`omittedFiles=${e.omittedFileCount}`],n=e.omittedFileCount>0||e.truncatedByCharLimit?` Materials are partial under this budget — do not invent diffs for omitted or truncated files; base the message only on provided material.`:` Materials cover the full selected set within the budget.`;return`${t.join(`; `)}.${n}`};async function N(e,t){let n=t.length,r=t.slice(0,30),i=await Promise.all(r.map(async t=>{try{let[n,r]=await Promise.all([m(e,{path:t,staged:!0}).catch(()=>null),m(e,{path:t,staged:!1}).catch(()=>null)]);return[n?.diff,r?.diff].filter(e=>typeof e==`string`&&e.trim().length>0).join(`
|
|
2
2
|
`)||`--- ${t} (no textual diff available)`}catch{return`--- ${t} (diff unavailable)`}})),a=``,o=0,s=!1;for(let e of i){let t=a?`
|
|
3
3
|
|
|
4
4
|
`:``;if(a.length+t.length+e.length>12e4){a+=`
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{c as e,f as t,i as n,n as r,r as i}from"./runtime-switch-CAZiOV2G.js";import{n as a}from"./runtime-fetch-BAN5Gnnp.js";import{L as o}from"./vendor-opencode-client-fxfj4IA_.js";import{t as s}from"./runtime-file-store-BVRgEtI-.js";var c=(e,t)=>JSON.stringify([`gui-code-v1`,`2.2`,e,t]),l=(e,t)=>JSON.stringify([`gui-code`,e,t]),u=e=>typeof e==`string`&&/^[a-f0-9]{64}$/.test(e),d={async read(e,t,n){try{let r=await s.read(c(e,t),n);if(!r)return null;let i=JSON.parse(await r.text());if(!i||typeof i!=`object`||Array.isArray(i))return null;let a=i;return Object.keys(a).length!==2||typeof a.code!=`string`||!a.code||!u(a.token)?null:{code:a.code,token:a.token}}catch{return null}},async write(e,t,n,r){try{await s.write(c(e,t),new Blob([JSON.stringify({code:n.code,token:n.token})],{type:`application/json`}),r,void 0,l(e,t))}catch{}}},f=e=>!!e&&typeof e==`object`&&!Array.isArray(e);function p(s){let c=n(),l=r(),p=i(),m=()=>c===n()&&l===r()&&p===i();return o.make({baseUrl:new URL(t().api(`/`),window.location.href).href,fetch:async(n,r)=>{if(s.aborted||!m())throw new DOMException(`Plugin runtime ended`,`AbortError`);let i=new URL(n instanceof Request?n.url:n.toString()),o=new URL(t().api(`${i.pathname}${i.search}`),window.location.href),c=new Request(o,n instanceof Request?n:r),l={...r,signal:AbortSignal.any([s,c.signal,...r?.signal?[r.signal]:[]])},h=i.searchParams.get(`id`);if((r?.method??c.method).toUpperCase()!==`GET`||i.pathname!==`/api/plugin/gui`||!h)return a(c,l);let g=new AbortController,_=e(()=>{m()||g.abort()}),v=AbortSignal.any([l.signal,g.signal]),y=()=>{if(v.throwIfAborted(),!m())throw new DOMException(`Plugin runtime ended`,`AbortError`)};try{let e=await d.read(p,h,v);y();let t=async e=>{y();let t=new Headers(r?.headers??c.headers);return t.delete(`X-Yuri-Gui-Revision`),t.delete(`If-None-Match`),e&&t.set(`X-Yuri-Gui-Revision`,e),a(c,{...l,signal:v,headers:t,cache:`no-store`})},n=await t(e?.token),i=!!e;if(y(),n.headers.get(`X-Yuri-Gui-Code`)===`cached`&&(!e||n.headers.get(`X-Yuri-Gui-Revision`)!==e.token)&&(await n.body?.cancel(),i=!1,n=await t(),y()),n.status!==200)return n;let o=await n.clone().json();if(y(),!f(o)||!f(o.data)||typeof o.data.code!=`string`||typeof o.data.revision!=`string`||!f(o.data.options))throw Error(`Invalid GUI bundle response`);let s=n.headers.get(`X-Yuri-Gui-Revision`);if(n.headers.get(`X-Yuri-Gui-Code`)===`cached`){if(!i||!e||s!==e.token||o.data.code!==``)throw Error(`Invalid GUI code cache response`);o.data.code=e.code;let t=new Headers(n.headers);t.delete(`content-length`),t.delete(`content-encoding`),n=Response.json(o,{status:200,headers:t})}else u(s)&&o.data.code&&(y(),await d.write(p,h,{code:o.data.code,token:s},v));return y(),n}finally{_()}}})}export{p as createGuiClient};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{A as e,C as t,E as n,F as r,I as i,M as a,P as o,S as s,T as c,_ as l,a as u,b as d,g as f,h as p,i as m,k as h,n as g,o as _,r as v,t as y,x as b}from"./vendor-opencode-client-fxfj4IA_.js";import{i as ee}from"./vendor-tanstack-query-core-BWz0ose6.js";import{n as x,r as te}from"./fileQueries-DbUx7NwP.js";import{o as ne}from"./path-utils-jGozTg9d.js";import{n as re}from"./pathNormalization-ewtPqJWn.js";import{t as S}from"./native-errors-06if6eu-.js";import{i as ie,o as ae}from"./fileReferenceParser-1HHDBUum.js";import{n as oe,t as se}from"./vendor-solid-js-Dmt4_-Zk.js";import{a as ce,c as le,d as C,f as w,h as T,i as ue,l as E,m as D,n as O,o as k,p as de,r as fe,s as pe,t as me,u as he}from"./vendor-opencode-plugin-CQ5ogY33.js";import{Et as A,mt as j,pt as M,y as N}from"./vendor-effect-DV9F8PTZ.js";var P={"@opencode/plugin/gui":k,"@opencode/plugin/gui/main":k,"@opencode/plugin/gui/file":ce,"@opencode/plugin/gui/review":ue,"@opencode/plugin/gui/browser":fe,"@opencode/plugin/rpc":me,"@opencode/schema/rpc":O,"@opencode/client":i,"@opencode/client/effect":g,"@opencode/client/solid":y,effect:N,"solid-js":a,"solid-js/web":oe,"solid-js/store":u},F=new Set(`assert assert/strict async_hooks buffer child_process cluster console constants crypto dgram diagnostics_channel dns dns/promises domain events fs fs/promises http http2 https inspector inspector/promises module net os path path/posix path/win32 perf_hooks process punycode querystring readline readline/promises repl stream stream/consumers stream/promises stream/web string_decoder sys timers timers/promises tls trace_events tty url util util/types v8 vm wasi worker_threads zlib`.split(` `));function I(){let e=new Proxy(function(){},{get:(t,n)=>n===`then`?void 0:n===Symbol.hasInstance?()=>!1:n===Symbol.toPrimitive||n===`toString`?()=>`[main-only module]`:e,apply:()=>e,construct:()=>e,set:()=>!0});return e}function L(e,t){if(e.length>16777216)throw Error(`GUI bundle exceeds 16 MiB`);let n={exports:{}};Function(`require`,`module`,`exports`,e)(e=>{if(Object.hasOwn(P,e))return P[e];if(e===`electron`||e.startsWith(`node:`)||F.has(e))return I();throw Error(`Unsupported GUI shared module: ${e}`)},n,n.exports);let r=n.exports,i=r&&typeof r==`object`&&`default`in r?r.default:r;if(!i||typeof i!=`object`)throw Error(`GUI bundle must default-export Plugin.define`);if((!(`setup`in i)||typeof i.setup!=`function`)&&!(t&&`main`in i&&typeof i.main==`function`))throw new S(`GUI_PLUGIN_UNSUPPORTED`,`This host requires a window setup; main-only plugins are unsupported`);if(`os`in i&&i.os!==void 0){if(!t)throw new S(`GUI_PLUGIN_UNSUPPORTED`,`OS-restricted plugins require the native GUI host`);if(!Array.isArray(i.os)||!i.os.includes(t))throw new S(`GUI_PLUGIN_UNSUPPORTED`,`GUI plugin is unavailable on this OS`)}if(`main`in i&&i.main!==void 0&&typeof i.main!=`function`)throw Error(`Invalid GUI main entry`);if(`stores`in i&&i.stores!==void 0){if(!i.stores||typeof i.stores!=`object`||Array.isArray(i.stores))throw Error(`Invalid GUI stores`);for(let e of Object.values(i.stores))if(!e||typeof e!=`object`||!(`schema`in e)||!A(e.schema)||!(`scope`in e)||![`global`,`session`].includes(String(e.scope))||!(`initial`in e))throw Error(`Invalid GUI store declaration`)}if(`i18n`in i&&i.i18n!==void 0){if(!i.i18n||typeof i.i18n!=`object`||Array.isArray(i.i18n))throw Error(`Invalid GUI locale catalog`);for(let e of Object.values(i.i18n))if(!e||typeof e!=`object`||Array.isArray(e)||Object.values(e).some(e=>typeof e!=`string`))throw Error(`GUI locales must be inline string dictionaries`)}return i}function R(e){let t=e;if(/^file:/i.test(t)){let e=new URL(t);t=`${e.hostname&&e.hostname!==`localhost`?`//${e.hostname}`:``}${decodeURIComponent(e.pathname)}`,/^\/[a-z]:\//i.test(t)&&(t=t.slice(1))}let n=re(t)??``;return n===`.`?``:n}var z=e=>/^(?:\/|[a-z]:\/)/i.test(e),B=()=>{throw Error(`Unsupported GUI file API: tree`)},V=class extends Error{},H=e=>new TextEncoder().encode(e).byteLength,ge=class{files;query;transport;root;api;ended=!1;states=new Map;inflight=new Map;watches=new Map;apiLeases=new Map;registeredOwners=new WeakSet;endedOwners=new WeakSet;leaseCount=0;rerun=new Set;selections=new Map;scrolls=new Map;subscriptions=new Map;constructor(e,t,r,i){this.files=e,this.query=t,this.transport=r,this.root=i,this.root=R(i),this.api={root:this.root,ready:()=>!this.ended,resolve:e=>this.resolve(e),absolute:z,get:e=>{let t=this.track(e,`file`);return this.states.get(t)},missing:e=>{let t=this.track(e,`missing`);return this.states.get(t)?.notFound===!0},sync:(e,t)=>{let r=n();return this.ended||r&&this.endedOwners.has(r)?Promise.resolve():(this.acquireApiLease(e),this.sync(e,t?.force))},unwatch:e=>this.releaseApiLease(n(),this.resolve(e)),exists:async e=>{try{if(this.files.statFile)return(await this.query.fetchQuery(this.statOptions(e))).isFile;let t=this.full(e);return(await this.files.listDirectory(t.slice(0,t.lastIndexOf(`/`)))).entries.some(e=>!e.isDirectory&&R(e.path)===t)}catch{return!1}},search:async(e,t)=>{if(t?.kind===`any`)throw Error(`Unsupported GUI file search: directories`);t?.signal?.throwIfAborted();let n=await this.query.fetchQuery({queryKey:[`gui-plugin-files`,r,this.root,`search`,e,t?.limit],gcTime:3e4,queryFn:async({signal:n})=>(n.throwIfAborted(),this.files.search({directory:this.root,query:e,maxResults:t?.limit??100}))});if(t?.signal?.throwIfAborted(),this.ended)throw new DOMException(`GUI file model was disposed`,`AbortError`);return n.map(e=>this.resolve(e.path))},selection:{get:e=>this.selections.get(this.track(e,`selection`)),set:(e,t)=>{let n=this.resolve(e),r=this.selections.get(n);r===t||r&&t&&r.start===t.start&&r.end===t.end&&r.side===t.side&&r.endSide===t.endSide||(this.selections.set(n,t),this.trim(this.selections,`selection`),this.changed(n,`selection`))}},scroll:{get:e=>this.scrolls.get(this.track(e,`scroll`))??{},set:(e,t)=>{let n=this.resolve(e),r=this.scrolls.get(n),i={...r,...t};(r?.top!==i.top||r?.left!==i.left)&&(this.scrolls.set(n,i),this.trim(this.scrolls,`scroll`),this.changed(n,`scroll`))}},tree:{list:B,state:B,sync:B,expand:B,collapse:B}}}resolve(e){let t=R(e);if(!z(t))return t;if(t===this.root)return``;let n=this.root.endsWith(`/`)?this.root:`${this.root}/`;return t.startsWith(n)?t.slice(n.length):t}full(e){let t=this.resolve(e);return z(t)?t:R(`${this.root}/${t}`)}input(e){return{scopeDirectory:this.root,path:this.full(e),options:{directory:this.root}}}statOptions(e){return{...te(this.files,this.input(e),this.transport),gcTime:3e4}}track(n,r){let i=this.resolve(n),a=c();if(!a||this.ended)return i;let o=`${r}:${i}`,s=this.subscriptions.get(o);s||(s={revision:t(0),listeners:new Set},this.subscriptions.set(o,s));let l=s;return l.listeners.has(a)||(l.listeners.add(a),e(a,()=>h(()=>{l.listeners.delete(a),!l.listeners.size&&this.subscriptions.get(o)===l&&this.subscriptions.delete(o)}))),l.revision[0](),i}changed(e,t){this.ended||this.subscriptions.get(`${t}:${e}`)?.revision[1](e=>e+1)}trim(e,t){for(;e.size>64;){let n=e.keys().next().value;e.delete(n),this.changed(n,t)}}setState(e,t){let n=this.states.get(e);n?.content?.content===t.content?.content&&n?.content?.type===t.content?.type&&(t.content=n?.content),!(n&&n.loaded===t.loaded&&n.loading===t.loading&&n.error===t.error&&n.notFound===t.notFound&&n.content===t.content)&&(this.states.set(e,t),p(()=>{this.changed(e,`file`),n?.notFound===!0!=(t.notFound===!0)&&this.changed(e,`missing`)}))}acquireApiLease(e){let t=n();if(this.ended||t&&this.endedOwners.has(t)||!this.files.statFile)return;let r=this.resolve(e),i=this.apiLeases.get(t);if(i?.has(r))return;if(this.leaseCount>=256)throw Error(`GUI file consumer limit exceeded`);let a=this.watch(r);i||(i=new Map,this.apiLeases.set(t,i)),i.set(r,a),this.leaseCount++,t&&!this.registeredOwners.has(t)&&(this.registeredOwners.add(t),h(()=>{`fn`in t||this.endedOwners.add(t),this.registeredOwners.delete(t);for(let e of[...this.apiLeases.get(t)?.keys()??[]])this.releaseApiLease(t,e)}))}releaseApiLease(e,t){let n=this.apiLeases.get(e),r=n?.get(t);r&&(n.delete(t),this.leaseCount--,n.size||this.apiLeases.delete(e),r())}reserve(e){if(!this.states.has(e)){if(this.states.size>=64){let e=[...this.states.keys()].find(e=>!this.watches.has(e)&&!this.inflight.has(e));if(!e)throw Error(`GUI file cache limit exceeded`);let t=this.states.get(e)?.notFound===!0;this.states.delete(e),p(()=>{this.changed(e,`file`),t&&this.changed(e,`missing`)})}this.states.set(e,{path:e,name:e.split(`/`).at(-1)??e})}}async sync(e,t=!1){if(this.ended)return;let n=this.resolve(e);if(this.inflight.has(n))return t&&this.rerun.add(n),this.inflight.get(n);if(!t&&this.states.get(n)?.loaded&&!this.states.get(n)?.error)return;this.reserve(n);let r=this.states.get(n);this.setState(n,{...r,path:n,name:n.split(`/`).at(-1)??n,loading:!r?.loaded&&!this.watches.get(n)?.failed});let i=(async()=>{try{do{this.rerun.delete(n);let e=this.watches.get(n),r=e?.epoch;try{let i=x(this.files,this.input(n),this.transport),a=await this.query.fetchQuery({...i,gcTime:3e4,staleTime:t?0:3e4,queryFn:async()=>{if(!this.files.readFile)throw Error(`File content reads are unavailable in this runtime`);let e=await this.files.readFile(this.full(n),{directory:this.root});if(e.exists===!1)throw new V(`File does not exist`);let t=e.content;if(H(t)>131072)throw Error(`GUI file preview exceeds 128 KiB`);return t}});if(this.ended)return;if(H(a)>131072)throw Error(`GUI file preview exceeds 128 KiB`);(!e||e.epoch===r&&!e.failed)&&this.setState(n,{path:n,name:n.split(`/`).at(-1)??n,loaded:!0,loading:!1,content:{type:`text`,content:a}})}catch(t){if(this.ended)return;if((!e||e.epoch===r&&!e.failed)&&this.setState(n,{...this.states.get(n),loading:!1,...t instanceof V?{notFound:!0}:{},error:String(t)}),!this.rerun.has(n))throw t}t=!0}while(!this.ended&&this.rerun.has(n))}finally{this.inflight.delete(n),this.rerun.delete(n)}})();return this.inflight.set(n,i),i}watch(e){if(this.ended||!this.files.statFile)return()=>{};let t=this.resolve(e),n=this.watches.get(t);if(!n){if(this.watches.size>=64)throw Error(`GUI file watch limit exceeded`);this.reserve(t),n={count:0,epoch:0,failed:!1,stop:()=>{}};let e=n;this.watches.set(t,e);let r,i=new ee(this.query,{...this.statOptions(t),refetchInterval:2e3,refetchIntervalInBackground:!1}),a=i.subscribe(n=>{if(this.ended||this.watches.get(t)!==e||n.isFetching)return;if(n.isError||n.isSuccess&&!n.data.isFile){e.failed=!0,e.epoch++,this.setState(t,{...this.states.get(t),loading:!1,notFound:n.isSuccess?!0:this.states.get(t)?.notFound,error:n.isError?String(n.error):`File does not exist`});return}if(!n.data||!n.isSuccess)return;let i=`${n.data.size}:${n.data.mtimeMs??``}`,a=e.failed||r!==void 0&&i!==r;e.failed=!1,r=i,a&&(e.epoch++,this.sync(t,!0).catch(()=>{}))});e.stop=()=>{a(),i.destroy()}}n.count++;let r=!0;return()=>{r&&(r=!1,--n.count===0&&this.watches.get(t)===n&&this.stopWatch(t))}}stopWatch(e){this.watches.get(e)?.stop(),this.watches.delete(e)}dispose(){this.ended=!0;for(let e of this.watches.values())e.stop();this.watches.clear(),this.apiLeases.clear(),this.leaseCount=0,this.rerun.clear(),this.states.clear(),this.inflight.clear(),this.selections.clear(),this.scrolls.clear(),this.subscriptions.clear()}},U=256,W=2097152,G=e=>structuredClone(_(e)),_e=class{backend;transport;memory=new Map;resets=new Map;constructor(e,t){this.backend=e,this.transport=t}forPlugin(e,n){let r=(t,n=`global`)=>{if(typeof n==`object`&&`session`in n&&!n.session.location)throw Error(`Unsupported GUI storage: session location is unknown`);let r=n===`global`?n:`session`in n?[n.session.server.id,n.session.id,n.session.location]:[n.server,n.directory];return`yuri.gui-plugin.${JSON.stringify([this.transport,e,r,t])}`},i=e=>{if(n.aborted)throw Error(`GUI plugin has been disposed`);if(e!==void 0)throw Error(`Unsupported GUI storage migration: from`)},a=new Map;return{store:(e,o)=>{i(o.from);let s=r(e,o.scope),c=a.get(s);if(c)return c;if(a.size>=U)throw Error(`GUI plugin store limit exceeded`);let l=M(o.schema),u=j(o.schema),d=l(u(G(o.initial)));if(JSON.stringify(u(d)).length>W)throw Error(`GUI plugin store exceeds 2 MiB`);let f=d,p=this.backend.getItem(s);if(p!==null&&p.length<=W)try{f=l(JSON.parse(p))}catch{f=d}let[m,h]=t(f),g=e=>{i();let t=JSON.stringify(u(G(e)));if(t.length>W)throw Error(`GUI plugin store exceeds 2 MiB`);let n=l(JSON.parse(t));this.backend.setItem(s,t),h(()=>n)},_={get value(){return m()},ready:()=>!0,set:g,update:e=>{let t=G(m());if(e(t)!==void 0)throw Error(`Store update must not return a replacement`);g(t)}},v=()=>h(()=>G(d)),y=this.resets.get(s)??new Set;return y.add(v),this.resets.set(s,y),n.addEventListener(`abort`,()=>{y.delete(v),y.size||this.resets.delete(s),a.clear()},{once:!0}),a.set(s,_),_},memory:(e,t)=>{i();let n=r(e),a=this.memory.get(n);if(a)return[a[0],e=>{i(),a[1](e)}];if(this.memory.size>=U)throw Error(`GUI plugin memory store limit exceeded`);if(JSON.stringify(t.initial).length>W)throw Error(`GUI plugin memory exceeds 2 MiB`);let[o,s]=v(G(t.initial)),c=[o,e=>{i();let t=G(_(o));if(e(t)!==void 0)throw Error(`Memory update must not return a replacement`);if(JSON.stringify(t).length>W)throw Error(`GUI plugin memory exceeds 2 MiB`);s(m(t))}];return this.memory.set(n,[o,e=>{let t=G(_(o));if(e(t)!==void 0)throw Error(`Memory update must not return a replacement`);if(JSON.stringify(t).length>W)throw Error(`GUI plugin memory exceeds 2 MiB`);s(m(t))}]),c},remove:(e,t)=>{i(t?.from);let n=r(e,t?.scope);this.backend.removeItem(n);for(let e of this.resets.get(n)??[])e()}}}dispose(){this.memory.clear(),this.resets.clear()}},ve=`yuri.file-icon`,K=`http://www.w3.org/2000/svg`,ye=new Set([`svg`,`g`,`path`,`rect`,`circle`,`ellipse`,`line`,`polyline`,`polygon`,`defs`,`linearGradient`,`radialGradient`,`stop`,`clipPath`,`mask`,`use`,`title`,`desc`]),q=e=>e.trim().replace(/^\./,``).toLowerCase();function J(e,t){if(typeof e!=`string`)throw Error(`GUI file icon requires SVG text`);let n=t.get(e);if(n)return n;if(e.length>16384)throw Error(`GUI file icon SVG exceeds 16 KiB`);let r=new TextEncoder().encode(e).byteLength;if(r>16384)throw Error(`GUI file icon SVG exceeds 16 KiB`);if(!/^\s*<svg[\s>]/.test(e)||/<!|<\?/.test(e))throw Error(`Invalid GUI file icon SVG`);let i=new DOMParser().parseFromString(e,`image/svg+xml`),a=i.documentElement;if(a?.localName!==`svg`||a.namespaceURI!==K||i.querySelector(`parsererror`))throw Error(`Invalid GUI file icon SVG`);for(let e of[a,...a.querySelectorAll(`*`)]){if(e.namespaceURI!==K||!ye.has(e.localName))throw Error(`Unsupported GUI file icon SVG element`);for(let t of e.attributes){let e=t.name.toLowerCase(),n=t.value.trim();if(e.startsWith(`on`)||e===`style`||e===`xml:base`||n.includes(`\\`)||Array.from(n).some(e=>e.charCodeAt(0)<32)||(e===`href`||e.endsWith(`:href`))&&!/^#[\w.-]+$/.test(n)||/url\s*\(/i.test(n)&&!/^url\(\s*#[\w.-]+\s*\)$/.test(n))throw Error(`Unsupported GUI file icon SVG reference or attribute`)}}let o={source:e,bytes:r,uri:`data:image/svg+xml,${encodeURIComponent(e)}`};return t.set(e,o),o}var be=class{plugins=new Map;index=new Map;listeners=new Set;subscribe=e=>(this.listeners.add(e),()=>{this.listeners.delete(e)});get(e,t){if(t?.isDirectory)return;let n=e.split(/[\\/]/).at(-1)??``,r=t?.extension??(n.includes(`.`)?n.slice(n.lastIndexOf(`.`)+1):``),i=this.index.get(q(r));return t?.themeVariant===`light`?i?.light.uri:i?.dark.uri}replace(e,t){if(t.length>64)throw Error(`GUI file icon per-plugin limit exceeded`);if(!t.length){this.remove(e);return}let n=new Map;for(let t of this.plugins.get(e)??[])for(let e of[t.dark,t.light])n.set(e.source,e);let r=new Set,i=t.map(e=>{if(!e||typeof e!=`object`||!(`id`in e)||typeof e.id!=`string`||!e.id.trim()||e.id.length>128||r.has(e.id))throw Error(`Invalid or duplicate GUI file icon id`);if(r.add(e.id),!(`extensions`in e)||!Array.isArray(e.extensions)||!e.extensions.length||e.extensions.length>64)throw Error(`GUI file icon requires 1–64 extensions`);let t=e.extensions.map(e=>{if(typeof e!=`string`)throw Error(`Invalid GUI file icon extension`);let t=q(e);if(!/^[a-z0-9][a-z0-9_+-]{0,63}$/.test(t))throw Error(`Invalid GUI file icon extension`);return t}),i=J(`svg`in e?e.svg:void 0,n),a=`lightSvg`in e&&e.lightSvg!==void 0?J(e.lightSvg,n):i;return{id:e.id,extensions:[...new Set(t)],dark:i,light:a}}),a=i.length,o=i.reduce((e,t)=>e+t.dark.bytes+t.light.bytes,0);for(let[t,n]of this.plugins)t!==e&&(a+=n.length,o+=n.reduce((e,t)=>e+t.dark.bytes+t.light.bytes,0));if(a>512||o>8388608)throw Error(`GUI file icon total limit exceeded`);this.plugins.set(e,i),this.publish()}remove(e){this.plugins.delete(e)&&this.publish()}dispose(){this.plugins.clear(),this.publish(),this.listeners.clear()}publish(){let e=new Map;for(let t of this.plugins.values())for(let n of t)for(let t of n.extensions)e.set(t,n);let t=e.size!==this.index.size||[...e].some(([e,t])=>{let n=this.index.get(e);return n?.dark.uri!==t.dark.uri||n?.light.uri!==t.light.uri});if(this.index=e,t)for(let e of this.listeners)e()}},Y=e=>e===`yuri.exportPDF`||e===`yuri.exportLongImage`,xe=class{api;probe;clients=new Map;ended=!1;constructor(e){this.api=e}use(e,n){let r=this.clients.get(n),i=r?.get(e);if(i)return i.live;let[a,o]=t(this.api&&!n.aborted&&!this.ended?{status:`pending`}:{status:`inactive`,reason:`disabled`}),s=()=>{o({status:`inactive`,reason:`disabled`}),n.removeEventListener(`abort`,s),this.clients.delete(n)},c={live:T(a),stop:s};if(this.ended||n.aborted||(r||(r=new Map,this.clients.set(n,r)),r.set(e,c),n.addEventListener(`abort`,s,{once:!0}),!this.api))return c.live;let l=this.api;return this.probe??=Promise.resolve().then(()=>l.capabilities()),this.probe.then(t=>{if(this.ended||n.aborted)return;let r=e===`yuri.exportPDF`?`exportPDF`:`exportLongImage`;if(t.version!==1||!t[r]){o({status:`inactive`,reason:`disabled`});return}let i=async(e,t={})=>{if(this.ended||n.aborted||a().status!==`active`)return{status:`cancelled`};let i=AbortSignal.any([n,...t.signal?[t.signal]:[]]);try{return await l[r](e,{...t,signal:i})}catch(e){throw e&&typeof e==`object`&&`code`in e&&e.code===`EXPORT_UNSUPPORTED`&&o({status:`inactive`,reason:`failed`}),e}},s=Object.freeze(e===`yuri.exportPDF`?{version:1,limits:t.limits,exportPDF:i}:{version:1,limits:t.limits,exportLongImage:i});o({status:`active`,generation:1,value:s})}).catch(()=>{!this.ended&&!n.aborted&&o({status:`inactive`,reason:`failed`})}),c.live}dispose(){this.ended=!0;for(let e of this.clients.values())for(let t of e.values())t.stop();this.clients.clear()}},X=e=>{throw new S(`GUI_PLUGIN_UNSUPPORTED`,`Unsupported GUI host API: ${e}`)};function Z(e,t){return new Proxy(t,{get:(t,n)=>n in t?Reflect.get(t,n):X(`${e}.${String(n)}`)})}var Q=e=>Object.freeze(e.map(e=>Object.freeze(e)));function $(e,t){if(e){for(let n of e.owned??[])$(n,t);e.cleanups&&=e.cleanups.map(e=>()=>{try{Promise.resolve(e()).catch(t)}catch(e){t(e)}})}}var Se=class{options;fileIcons=new be;instances=new Map;listeners=new Set;panelMounts=new Set;fileViews=new Map;changes=t(0);views=t(0);session=t();appearance;layouts=new Map;files;storage;ended=!1;contracts=new Map;snapshot=Object.freeze({plugins:Object.freeze([]),commands:Object.freeze([]),panels:Object.freeze([]),settings:Object.freeze([]),menuItems:Object.freeze([]),activePanel:null});screen;viewExports;constructor(e){this.options=e,this.viewExports=new xe(e.viewExport),this.appearance=t({locale:e.locale,mode:e.mode,narrow:e.narrow}),this.storage=new _e(e.storage,e.transport);let n=()=>(this.session[0](),this.files?.api??X(`screen.file without a session`));this.screen=Z(`screen`,{get file(){return n()}})}subscribe=e=>(this.listeners.add(e),()=>{this.listeners.delete(e)});getSnapshot=()=>this.snapshot;changed(){this.changes[1](e=>e+1)}setSession(e){if(this.ended)return;let t=this.session[0]();if(t?.id===e?.id&&t?.directory===e?.directory)return;if(!e)for(let e of[...this.panelMounts])e();this.files?.dispose(),this.files=e?new ge(this.options.files,this.options.queryClient,this.options.transport,e.directory):void 0;let n=Z(`session.server`,{id:this.options.transport,name:this.options.transport,client:this.options.client}),r=e?Object.freeze(Z(`session`,{id:e.id,directory:e.directory,key:`${this.options.transport}\n${e.id}`,tab:e.id,server:n,pending:!1,visit:{},location:{directory:e.directory}})):void 0;this.session[1](r),this.publish()}setAppearance(e){if(this.ended)return;let t=this.appearance[0]();(t.locale!==e.locale||t.mode!==e.mode||t.narrow!==e.narrow)&&this.appearance[1]({...e})}install(r,i,a){let c=this.instances.get(r);if(this.ended||c?.status===`active`&&c.revision===i.revision&&c.native?.active!==!1){a?.dispose();return}c&&(this.instances.delete(r),this.release(c));let u={id:r,native:a,revision:i.revision,controller:new AbortController,status:`active`,cleanups:new Set,contributions:new Set,iconChanges:t(0),commands:[],panels:[],settings:[],menus:[]};this.instances.set(r,u);try{if(r===`yuri`||r.startsWith(`yuri.`))throw Error(`The yuri namespace is reserved to the host`);let t=L(i.code,a?.activation.os);s(r=>{u.dispose=r,u.root=n(),f(()=>l(D.Provider,{value:u.context=this.context(u,t,i.options),get children(){u.owner=n();let e=o(()=>t.setup?.(u.context));if(typeof e==`function`)u.cleanups.add(()=>{Promise.resolve(e()).catch(e=>{u.error=String(e)})});else if(e!==void 0)throw e&&typeof e==`object`&&`then`in e&&Promise.resolve(e).catch(()=>{}),Error(`GUI setup must be synchronous and return only cleanup`);return null}}),e=>this.fail(u,e)),u.controller.signal.aborted||e(u.owner,()=>b(()=>{if(u.iconChanges[0](),!u.controller.signal.aborted)try{let e=[...u.contributions].filter(e=>e.registry===ve).map(e=>e.read()).filter(e=>e!==void 0);this.fileIcons.replace(u.id,e),u.iconError!==void 0&&o(()=>{u.iconError=void 0,this.publish()})}catch(e){o(()=>{this.fileIcons.remove(u.id),u.iconError=e instanceof Error?e.message:String(e),this.publish()})}})),u.controller.signal.aborted||e(u.owner,()=>b(()=>{this.changes[0](),this.session[0](),this.appearance[0]();try{this.derive(u)}catch(e){o(()=>this.fail(u,e))}o(()=>this.publish())}))})}catch(e){this.fail(u,e)}this.changed(),this.publish()}release(e){e.controller.abort(),e.native?.dispose();for(let t of[...e.cleanups])try{t()}catch(t){e.error??=String(t)}e.cleanups.clear(),$(e.root,t=>{e.error??=String(t)});try{e.dispose?.()}catch(t){e.error??=String(t)}e.contributions.clear(),e.commands=[],e.panels=[],e.settings=[],e.menus=[],this.fileIcons.remove(e.id);for(let t of this.contracts.values())t.provider===e&&(t.provider=void 0,t.live[1]({status:`inactive`,reason:e.status===`failed`?`failed`:`disabled`}))}fail(e,t){e.status!==`failed`&&this.instances.get(e.id)===e&&(e.status=`failed`,e.error=t instanceof Error?t.message:String(t),t instanceof S&&(e.errorCode=t.code),this.release(e),this.publish())}uninstall(e){let t=this.instances.get(e);if(t){this.instances.delete(e),this.release(t);for(let t of this.layouts.values())t.open=t.open.filter(t=>!t.startsWith(`${e}:`)),t.active?.startsWith(`${e}:`)&&(t.active=null);this.changed(),this.publish()}}dispose(){this.ended||(this.ended=!0,p(()=>{for(let e of[...this.instances.keys()])this.uninstall(e)}),this.viewExports.dispose(),this.files?.dispose(),this.fileIcons.dispose(),this.storage.dispose(),this.layouts.clear(),this.fileViews.clear(),this.contracts.clear(),this.listeners.clear())}own(e,t){let i=!0,a=()=>{i&&(i=!1,e.cleanups.delete(a),t())};return e.controller.signal.aborted||r(w)?.ended?(a(),a):(e.cleanups.add(a),n()&&h(a),a)}list(e){this.changes[0]();let t=[];for(let n of this.instances.values())if(n.status===`active`){for(let r of n.contributions)if(r.registry===e.id){let e=r.read();e!==void 0&&t.push(e)}}return t}context(e,t,i){let a=this.storage.forPlugin(e.id,e.controller.signal),c=Object.fromEntries(Object.entries(t.stores??{}).map(([e,t])=>[e,t.scope===`global`?a.store(e,{...t,scope:`global`}):n=>a.store(e,{...t,scope:{session:n}})])),l=(e,n)=>{let r=this.appearance[0]().locale;return(t.i18n?.[r]?.[e]??t.i18n?.[r.split(`-`)[0]]?.[e]??t.i18n?.en?.[e]??e).replace(/\{\{(\w+)\}\}/g,(e,t)=>String(n?.[t]??e))},u=Z(`layout`,{narrow:()=>this.appearance[0]().narrow,ready:()=>!!this.session[0](),open:(t,n,r)=>{e.controller.signal.aborted||this.openPanel(t,n,r)},close:(t,n)=>{e.controller.signal.aborted||this.closeFor(t,n)},toggle:(e,t)=>u.state(e,t)===`visible`?u.close(e,t):u.open(e,t),hide:(t,n)=>{if(e.controller.signal.aborted)return;let r=this.layout(n);r.active===t&&r.shown&&(r.shown=!1,this.changed())},state:(e,t)=>{this.changes[0]();let n=this.layout(t);return n.active===e?n.shown?`visible`:`active`:n.open.includes(e)?`open`:`closed`},stored:t=>(this.changes[0](),this.layout(t).open.filter(t=>t.startsWith(`${e.id}:`)).map(t=>t.slice(e.id.length+1))),side:{opened:e=>(this.changes[0](),this.layout(e).shown),toggle:t=>{if(e.controller.signal.aborted)return;let n=this.layout(t);n.shown=!n.shown,this.changed()},menu:()=>this.list(E).filter(e=>e.menu===`session.panel`).sort((e,t)=>(e.order??0)-(t.order??0))},scroll:{get:(e,t)=>(this.changes[0](),this.layout(e).scroll.get(t)),set:(t,n,r)=>{if(e.controller.signal.aborted)return;let i=this.layout(t).scroll;if(!i.has(n)&&i.size>=128)throw Error(`GUI layout scroll limit exceeded`);i.set(n,{...r}),this.changed()}}});return Z(`ctx`,{id:e.id,options:i,signal:e.controller.signal,client:this.options.client,storage:a,stores:c,app:{name:`yuri`,version:e.native?.activation.app.version??``,channel:e.native?.activation.app.packaged?`prod`:`local`,platform:e.native?`desktop`:`web`,packaged:e.native?.activation.app.packaged??!1},desktop:e.native?Z(`desktop`,{os:e.native.activation.os}):void 0,t:l,plural:(e,t,n)=>{let r=`${e}.${new Intl.PluralRules(this.appearance[0]().locale).select(t)}`;return l(r,{...n,count:t})===r?l(`${e}.other`,{...n,count:t}):l(r,{...n,count:t})},add:(t,i)=>{if(e.controller.signal.aborted||r(w)?.ended)return()=>{};if([`server`,`titlebar-item`,`composer-pill`,`slot`,`file.viewer`,`menubar-item`].includes(t.id)&&X(`registry.${t.id}`),e.contributions.size>=256)throw Error(`GUI contribution limit exceeded`);let a=()=>{},c,l=s(e=>{a=e,c=n();let r=()=>typeof i==`function`?i():i,o;if(t.id===`yuri.file-icon`){let e=d(()=>{try{return{ok:!0,value:r()}}catch(e){return{ok:!1,error:e}}});o=()=>{let t=e();if(!t.ok)throw t.error;return t.value}}else o=d(r);if(t.id===`style`){let e=document.createElement(`style`);document.head.append(e),h(()=>e.remove()),b(()=>{let t=o();e.textContent=t===void 0?``:String(t)})}return{registry:t.id,read:o}},n()??e.owner);e.contributions.add(l);let u=()=>{t.id===`yuri.file-icon`&&e.iconChanges[1](e=>e+1)};return o(u),o(()=>this.changed()),this.own(e,()=>{$(c,t=>{e.error??=String(t)}),a(),e.contributions.delete(l),o(u),o(()=>this.changed())})},list:e=>this.list(e),provide:(t,n)=>{if(e.controller.signal.aborted||r(w)?.ended)return()=>{};if(Y(t.id))throw Error(`Export contracts are provided only by the Yuri host`);if(t.kind!==`contract`||!(t.id===e.id||t.id.startsWith(`${e.id}.`)))throw Error(`Contract must belong to the providing plugin`);let i=this.contract(t.id);if(i.provider)throw Error(`Contract already provided: ${t.id}`);return i.provider=e,i.live[1]({status:`active`,value:n,generation:++i.generation}),this.own(e,()=>{i.provider===e&&(i.provider=void 0,i.live[1]({status:`inactive`,reason:e.status===`failed`?`failed`:`disabled`}))})},use:t=>Y(t.id)?t.kind===`contract`?this.viewExports.use(t.id,e.controller.signal):X(`export token must be a Contract`):t.kind===`ipc`&&e.native?e.native.token(t).live:this.contract(t.id,t.kind===`ipc`).live[0],main:t=>{if(!(t.id===e.id||t.id.startsWith(`${e.id}.`)))throw new S(`GUI_PLUGIN_FORBIDDEN`,`IPC must belong to the plugin`);return e.native?e.native.token(t).value:new Proxy({state:()=>void 0},{get:(e,t)=>t===`state`?e.state:t===`on`?()=>{throw new S(`GUI_PLUGIN_UNSUPPORTED`)}:()=>Promise.reject(new S(`GUI_PLUGIN_UNSUPPORTED`))})},sessions:{current:this.session[0],list:()=>{let e=this.session[0]();return e?[e]:[]}},screen:{current:()=>this.session[0]()?this.screen:void 0},layout:u,appearance:{mode:()=>this.appearance[0]().mode,font:()=>getComputedStyle(document.documentElement).getPropertyValue(`--font-mono`).trim()||`monospace`},locale:{locale:()=>this.appearance[0]().locale,direction:()=>/^(ar|fa|he|ur)(-|$)/i.test(this.appearance[0]().locale)?`rtl`:`ltr`},system:{copy:e=>navigator.clipboard.writeText(e),openExternal:e=>{let t=new URL(e);[`https:`,`http:`,`mailto:`].includes(t.protocol)||X(`system.openExternal protocol`),window.open(e,`_blank`,`noopener,noreferrer`)},save:async e=>{let t=URL.createObjectURL(new Blob([e.content],{type:`text/plain`}));try{let n=document.createElement(`a`);return n.href=t,n.download=e.name,n.click(),!0}finally{setTimeout(()=>URL.revokeObjectURL(t),0)}}},commands:{run:t=>e.controller.signal.aborted||!this.command(t)?!1:(this.runCommand(t),!0)},links:{open:t=>!e.controller.signal.aborted&&this.navigateLink(e,t),exists:t=>o(()=>{if(e.controller.signal.aborted)return!1;let n=this.linkHandler(t);try{return Promise.resolve(n?.value.exists?.(t)??!1).catch(()=>!1)}catch{return!1}})}})}contract(e,n=!1){let r=this.contracts.get(e);if(!r){if(this.contracts.size>=256)throw Error(`GUI contract limit exceeded`);let n=t({status:`inactive`,reason:`disabled`});r={live:[T(n[0]),n[1]],generation:0},this.contracts.set(e,r)}return n&&r.provider&&X(`IPC contract collision`),r}derive(e){if(e.status!==`active`)return;let t=[],n=[],r=[],i=[],a=this.session[0]();for(let o of e.contributions){if(o.registry===`yuri.file-icon`)continue;let s=o.read();if(s!==void 0){if(o.registry===pe.id){let n=s;n.enabled!==!1&&t.push({key:`${e.id}.${n.id}`,title:n.title,description:n.description,bind:n.bind,hidden:n.hidden,run:()=>this.invoke(e,()=>n.run())})}else if(o.registry===he.id&&a){let t=s,r=`${e.id}:`,i=this.layout(a).open.filter(e=>e.startsWith(r)).map(e=>e.slice(r.length));for(let r of t.list({session:a,screen:this.screen,open:i}))n.push({plugin:e,panel:t,tab:r})}else if(o.registry===C.id){let e=s;(e.page||e.section)&&X(`SettingsPage host sections`),e.title,r.push(e)}else if(o.registry===E.id){let e=s;e.menu===`session.panel`?(e.title,i.push(e)):X(`MenuItem.${e.menu}`)}}}for(let e of n)e.tab.title;e.commands=t,e.panels=n,e.settings=r,e.menus=i,o(()=>this.views[1](e=>e+1))}publish(){let e=o(this.session[0]),t=e?this.layouts.get(e.key):void 0,n=[...this.instances.values()],r=n.filter(e=>e.status===`active`),i=r.flatMap(e=>e.panels.map(({tab:n})=>{let r=n.file?this.filePath(n.file):void 0;return{key:`${e.id}:${n.id}`,pluginId:e.id,title:n.title,file:r,inline:!!(r&&this.fileViews.has(r)),active:t?.shown===!0&&t.active===`${e.id}:${n.id}`}}));this.snapshot=Object.freeze({plugins:Q(n.map(({id:e,revision:t,status:n,error:r,errorCode:i,iconError:a})=>({id:e,revision:t,status:n,error:r??a,...i?{errorCode:i}:{}}))),commands:Q(r.flatMap(e=>e.commands.filter(e=>!e.hidden))),panels:Q(i),settings:Q(r.flatMap(e=>e.settings.map(t=>({key:`${e.id}:${t.id}`,pluginId:e.id,title:t.title})))),menuItems:Q(r.flatMap(e=>e.menus.map(t=>({key:`${e.id}:${t.id}`,title:t.title,description:t.description,run:()=>{this.invoke(e,()=>t.run())}})))),activePanel:t?.shown&&i.some(e=>e.key===t.active)?t.active:null,sessionKey:e?.key});for(let e of this.listeners)e()}invoke(t,n){if(!t.controller.signal.aborted)try{let r=e(t.owner??null,n);if(r instanceof Promise)return r.catch(e=>this.fail(t,e))}catch(e){this.fail(t,e)}}command(e){return[...this.instances.values()].flatMap(e=>e.commands).find(t=>t.key===e)}runCommand(e){return this.command(e)?.run()}linkHandler(e){let t=[];for(let e of this.instances.values())for(let n of e.contributions)if(n.registry===le.id){let r=n.read();r&&t.push({instance:e,value:r})}for(let n of t.sort((e,t)=>(t.value.priority??0)-(e.value.priority??0)))try{if(n.value.match(e))return n}catch(e){this.fail(n.instance,e)}}navigateLink(e,t){if(this.ended)return!1;let n=ae(t.href);if(!n||!ie(n.path))return this.openLink(t);let r=this.session[0]();if(!r||t.session&&(t.session.key!==r.key||t.session.server.id!==r.server.id))return!1;if(!this.options.focusFile)return this.openLink(t);let i=ne(t.base??r.directory,n.path),a=n.line===void 0?``:`:${n.line}${n.column===void 0?``:`:${n.column}`}`;return this.invoke(e,()=>this.options.focusFile(i+a,r.directory)),!0}openLink(e){if(this.ended)return!1;let t={...e,session:e.session??this.session[0]()},n=this.linkHandler(t);return n?(this.invoke(n.instance,()=>n.value.open(t)),!0):!1}filePath(e,t=this.session[0]()?.directory){let n=R(e);return/^(?:\/|[a-z]:\/)/i.test(n)||!t?n:R(`${t}/${n}`)}registerFileView(e,t){if(this.ended)return()=>{};let n=this.filePath(e,t),r=this.fileViews.get(n)??0;this.fileViews.set(n,r+1),r===0&&(this.changed(),this.publish());let i=!1;return()=>{if(i||this.ended)return;i=!0;let e=(this.fileViews.get(n)??1)-1;if(e){this.fileViews.set(n,e);return}{let e=this.session[0](),t=e&&this.layouts.get(e.key);t?.active&&this.snapshot.panels.some(e=>e.key===t.active&&e.file===n)&&(t.shown=!1),this.fileViews.delete(n)}this.changed(),this.publish()}}filePanel(e,t){let n=this.filePath(e,t);return this.snapshot.panels.find(e=>e.file===n&&e.inline)}panelVisible(e){let t=this.session[0]();if(!t)return!1;let n=this.panel(e)?.tab.file;if(n&&this.fileViews.has(this.filePath(n)))return!0;let r=this.layouts.get(t.key);return!!(r?.shown&&r.active===e)}layout(e){let t=this.layouts.get(e.key);if(!t){if(this.layouts.size>=128)throw Error(`GUI session layout limit exceeded`);t={open:[],active:null,shown:!1,scroll:new Map},this.layouts.set(e.key,t)}return t}openPanel(e,t,n){if(this.ended)return;let r=this.layout(t),i=r.active,a=r.shown,o=r.open.length;if(!r.open.includes(e)){if(r.open.length>=64)throw Error(`GUI panel tab limit exceeded`);r.open=[...r.open,e]}n?.tab!==`append`&&(r.active=e,r.shown=!(this.appearance[0]().narrow&&n?.background)),(i!==r.active||a!==r.shown||o!==r.open.length)&&(this.changed(),this.publish());let s=this.panel(e);t.key===this.session[0]()?.key&&s&&n?.tab!==`append`&&this.invoke(s.plugin,()=>s.panel.focus?.({...this.props(e),restored:!1}))}selectPanel(e){let t=this.session[0]();t&&this.openPanel(e,t)}closeFor(e,t){let n=this.layout(t),r=t.key===this.session[0]()?.key?this.panel(e):void 0;if(!n.open.includes(e)||r?.tab.pinned||r?.tab.closable===!1)return;let i=this.session[0](),a=r&&i?{tab:r.tab,session:i,screen:this.screen}:void 0;n.open=n.open.filter(t=>t!==e),n.active===e&&(n.active=n.open.at(-1)??null),this.changed(),this.publish(),r&&a&&this.invoke(r.plugin,()=>r.panel.close?.(a))}closePanel(e){let t=this.session[0]();t&&this.closeFor(e,t)}hidePanel(){let e=this.session[0]();if(!e)return;let t=this.layout(e);t.shown&&(t.shown=!1,this.changed(),this.publish())}panel(e){return[...this.instances.values()].flatMap(e=>e.panels).find(t=>`${t.plugin.id}:${t.tab.id}`===e)}props(e){let t=this.panel(e)?.tab,n=()=>(this.views[0](),this.panel(e)?.tab??t??X(`panel no longer listed`)),r=()=>this.session[0]()??X(`panel without session`);return{get tab(){return n()},get session(){return r()},screen:this.screen}}mountPanel(e,t){let n=this.panel(e);if(!n)return()=>{};let r=()=>{let t=d(()=>{this.session[0](),this.changes[0](),this.views[0]();let t=this.panel(e)?.tab.file;return t&&this.files&&this.panelVisible(e)?{model:this.files,file:t}:void 0},void 0,{equals:(e,t)=>e?.model===t?.model&&e?.file===t?.file});return b(()=>{let e=t();e&&(h(e.model.watch(e.file)),e.model.sync(e.file).catch(()=>{}))}),o(()=>n.panel.render(this.props(e)))},i=this.mount(n.plugin,t,()=>l(de.Provider,{value:{visible:()=>(this.changes[0](),this.panelVisible(e)),present:()=>(this.changes[0](),this.panelVisible(e)),placement:()=>this.appearance[0]().narrow?`mobile`:`side`,reserve:()=>!1,animate:()=>!1,sidebar:Z(`panel.sidebar`,{}),open:()=>{let e=this.session[0]();return e?n.plugin.context.layout.stored(e):[]}},get children(){return r()}})),a=()=>{this.panelMounts.delete(a),i()};return this.panelMounts.add(a),this.own(n.plugin,a)}mountSettings(e,t){for(let n of this.instances.values()){let r=n.settings.find(t=>`${n.id}:${t.id}`===e);if(r)return this.mount(n,t,()=>r.render({}))}return()=>{}}mount(e,t,r){if(e.controller.signal.aborted)return()=>{};let i=()=>{},a,s=t=>{queueMicrotask(()=>this.fail(e,t))};try{i=se(()=>l(D.Provider,{value:e.context,get children(){return a=n(),f(()=>o(r),s)}}),t)}catch(t){this.fail(e,t)}return this.own(e,()=>{$(a,t=>{e.error??=String(t)}),i(),t.replaceChildren()})}};export{Se as GuiPluginHost};
|