sliccy 5.63.4 → 5.64.1
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/dist/node-server/_cloud_core/tests/e2b-workerd-pin.test.d.ts +2 -0
- package/dist/node-server/_cloud_core/tests/e2b-workerd-pin.test.d.ts.map +1 -0
- package/dist/node-server/_cloud_core/tests/e2b-workerd-pin.test.js +44 -0
- package/dist/node-server/_shared/secrets-pipeline.d.ts +25 -7
- package/dist/node-server/_shared/secrets-pipeline.d.ts.map +1 -1
- package/dist/node-server/_shared/secrets-pipeline.js +35 -8
- package/dist/node-server/_shared/secrets-pipeline.js.map +1 -1
- package/dist/node-server/_shared/tray-sync-protocol.d.ts +3 -0
- package/dist/node-server/_shared/tray-sync-protocol.d.ts.map +1 -1
- package/dist/node-server/_shared/tray-sync-protocol.js.map +1 -1
- package/dist/node-server/routes/fetch-proxy.js +3 -0
- package/dist/node-server/secrets/proxy-manager.d.ts +2 -0
- package/dist/ui/assets/{account-store-BFKOVoJK.js → account-store-CbBigdPI.js} +1 -1
- package/dist/ui/assets/{account-store-B9-adorx.js → account-store-O2BUvC3j.js} +1 -1
- package/dist/ui/assets/{adobe-Cimz7Qad.js → adobe-CTpdS6xa.js} +1 -1
- package/dist/ui/assets/{adobe-DljiV8CX.js → adobe-DKrFjhJ6.js} +1 -1
- package/dist/ui/assets/{apps-EdGaobBt.js → apps-C5Sg_4u2.js} +1 -1
- package/dist/ui/assets/{azure-openai-DZfQfbEN.js → azure-openai-BtESgDTf.js} +1 -1
- package/dist/ui/assets/{azure-openai-B1LGYY5w.js → azure-openai-CHq3fMTF.js} +1 -1
- package/dist/ui/assets/{cerebras-D9rdJuv7.js → cerebras-BtiYKUFA.js} +1 -1
- package/dist/ui/assets/{cerebras-Dd-I5CEf.js → cerebras-t85UJQjn.js} +1 -1
- package/dist/ui/assets/{connect-surface-Dre9TL7S.js → connect-surface-CN-tvori.js} +1 -1
- package/dist/ui/assets/fs-BnRVC9hw.js +1 -0
- package/dist/ui/assets/fs-Cgor0Izu.js +2 -0
- package/dist/ui/assets/{github-CyPb8Ejb.js → github-DVxz4vdw.js} +1 -1
- package/dist/ui/assets/{github-D9N2QXEG.js → github-F8y8IDpa.js} +2 -2
- package/dist/ui/assets/{github-copilot-D1D7dY7b.js → github-copilot-DtscAuev.js} +1 -1
- package/dist/ui/assets/{github-copilot-md_u_Xt0.js → github-copilot-FjY0lxjE.js} +1 -1
- package/dist/ui/assets/{js-realm-worker-vnTP6x9C.js → js-realm-worker-FgXpYXua.js} +7 -7
- package/dist/ui/assets/{kernel-worker-Bg1GG_Na.js → kernel-worker-C1l54cCK.js} +27 -27
- package/dist/ui/assets/leader-session-events-m7I5BMZy.js +1 -0
- package/dist/ui/assets/{lick-ws-bridge-RSsqIMjw.js → lick-ws-bridge-s8xtk-9V.js} +1 -1
- package/dist/ui/assets/{local-llm-C3oGat0H.js → local-llm-C6Uyn1eH.js} +1 -1
- package/dist/ui/assets/{local-llm-BaoGgCFz.js → local-llm-r64sh5vT.js} +1 -1
- package/dist/ui/assets/{main-vzVT7hjL.js → main-BC7cdhzM.js} +3 -3
- package/dist/ui/assets/{mount-CB9LbKIo.js → mount-C7dkJC9k.js} +2 -2
- package/dist/ui/assets/{mount-KPh5FQy2.js → mount-DMo5mtgD.js} +1 -1
- package/dist/ui/assets/{mount-recovery-l9BFFyMp.js → mount-recovery-CmtpPBiM.js} +1 -1
- package/dist/ui/assets/{new-session-CCs-0HLH.js → new-session-DwJBzDuD.js} +2 -2
- package/dist/ui/assets/{oauth-bootstrap-KDRfKJJk.js → oauth-bootstrap-Df6rphhy.js} +2 -2
- package/dist/ui/assets/{openai-codex-G98kDIrK.js → openai-codex-Cfd7h37k.js} +1 -1
- package/dist/ui/assets/{openai-codex-CG1BFVNV.js → openai-codex-uJQvf_Es.js} +1 -1
- package/dist/ui/assets/page-follower-tray-DwTbyxUG.js +5 -0
- package/dist/ui/assets/{panel-rpc-handlers-CtaGdPiZ.js → panel-rpc-handlers--odFdC9Y.js} +2 -2
- package/dist/ui/assets/{provider-1UnA0iTT.js → provider-1yky0PLL.js} +2 -2
- package/dist/ui/assets/{provider-CXZ0Yoon.js → provider-CE6jDRgx.js} +1 -1
- package/dist/ui/assets/{provider-settings-X4c7CFKN.js → provider-settings-BclOQB4V.js} +1 -1
- package/dist/ui/assets/{provider-settings-B1ye5KnA.js → provider-settings-Be9DZHqf.js} +1 -1
- package/dist/ui/assets/{provider-store-access-Bcg6OLsk.js → provider-store-access-CfqFRAcX.js} +2 -2
- package/dist/ui/assets/provider-store-access-DyDHzY1t.js +1 -0
- package/dist/ui/assets/{providers-DmcTo7yV.js → providers-4qAZLHsD.js} +1 -1
- package/dist/ui/assets/{providers-DhwIRhTh.js → providers-CLGEV4xE.js} +2 -2
- package/dist/ui/assets/{quick-llm-C_5W6jkO.js → quick-llm-CNHUhFtm.js} +1 -1
- package/dist/ui/assets/{session-freezer-5VJvody6.js → session-freezer-CfQoJC7N.js} +2 -2
- package/dist/ui/assets/{setup-sudo-hbE3YS_h.js → setup-sudo-Cv0iEi2g.js} +2 -2
- package/dist/ui/assets/{skills-BhOiOEZH.js → skills-CF4YIozr.js} +1 -1
- package/dist/ui/assets/{store-DxxV-bbY.js → store-FJJcjvMM.js} +1 -1
- package/dist/ui/assets/{sudo-DchLnUf3.js → sudo-MQh4Wkfk.js} +1 -1
- package/dist/ui/assets/{upgrade-detection-BW3VRd1P.js → upgrade-detection-C9cmqYPd.js} +1 -1
- package/dist/ui/assets/{wc-extension-C29GXMnK.js → wc-extension-BA2gvu-f.js} +2 -2
- package/dist/ui/assets/{wc-follower-Cw_-1J-M.js → wc-follower-AtjS50fA.js} +3 -3
- package/dist/ui/assets/wc-live-CeKsOHo7.js +8 -0
- package/dist/ui/assets/{wc-nav-GP31iyge.js → wc-nav-5uhNKItB.js} +2 -2
- package/dist/ui/assets/{wc-onboarding-CJqGobRI.js → wc-onboarding-BwMtqWwY.js} +2 -2
- package/dist/ui/assets/{wc-placeholder-CaVn58Qm.js → wc-placeholder-BO99xAKA.js} +2 -2
- package/dist/ui/assets/{wc-settings-D8xvXhKu.js → wc-settings-IukuSp0f.js} +2 -2
- package/dist/ui/assets/{wc-shell-DMnWuIZ-.js → wc-shell-Bd9DGfe5.js} +2 -2
- package/dist/ui/assets/{wc-sprinkles-3sLH601k.js → wc-sprinkles-B-aItcUK.js} +2 -2
- package/dist/ui/assets/wc-tray-BksMaYdO.js +2 -0
- package/dist/ui/assets/{xai-grok-DW_swkku.js → xai-grok-DLYn2N_r.js} +1 -1
- package/dist/ui/assets/{xai-grok-B9IjiF5p.js → xai-grok-DYD1UJ2S.js} +1 -1
- package/dist/ui/index.html +5 -5
- package/dist/ui/packages/webapp/index.html +5 -5
- package/package.json +4 -4
- package/dist/ui/assets/fs-2Bn7XMhr.js +0 -2
- package/dist/ui/assets/fs-Dn5olo3p.js +0 -1
- package/dist/ui/assets/page-follower-tray-DFeLlotx.js +0 -5
- package/dist/ui/assets/provider-store-access-BOUsNLHm.js +0 -1
- package/dist/ui/assets/wc-live-Ddn6PNV5.js +0 -8
- package/dist/ui/assets/wc-tray-BIFpwQo6.js +0 -2
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{i as e,t}from"./rolldown-runtime-aKtaBQYM.js";import{t as n}from"./logger-LESFN7Hj.js";import{n as r,r as i,t as a}from"./panel-rpc-CjFVE0nK.js";import{a as o}from"./providers-
|
|
1
|
+
import{i as e,t}from"./rolldown-runtime-aKtaBQYM.js";import{t as n}from"./logger-LESFN7Hj.js";import{n as r,r as i,t as a}from"./panel-rpc-CjFVE0nK.js";import{a as o}from"./providers-4qAZLHsD.js";import{c as s,d as c,f as l,i as u,l as d,m as f,n as p,o as m,p as h,r as g,s as _,t as v,u as y}from"./proxied-fetch-sbHa3Tte.js";import{r as b,t as x}from"./src-Dk1QVJRd.js";import{D as S,E as C,F as w,I as T,L as E,M as D,N as O,P as k,R as A,T as j,_ as M,h as N,i as P,j as ee,o as te,v as ne}from"./account-store-CbBigdPI.js";import{t as re}from"./runtime-env-byAg9ij-.js";import{n as ie,r as ae,t as oe}from"./fetch-body-DDu_AU5I.js";import{a as se,i as F,n as I,r as ce}from"./transcript-limits-D0M7bLr9.js";import{n as le,o as ue,s as de}from"./tool-ui-t6ocn6AG.js";import{a as fe,i as pe,n as me,o as he,r as L,t as R}from"./backend-local-D4WZgy4J.js";import{t as ge}from"./types-idfTVsM8.js";import{n as _e,t as z}from"./mime-types-D7IV6i7k.js";import{a as ve,i as B,n as ye,r as V}from"./mount-DMo5mtgD.js";import{o as H}from"./mount-table-store-CTrzlrNn.js";import{t as be}from"./remote-cache-D59F5FOx.js";import{r as U,t as xe}from"./mount-recovery-CmtpPBiM.js";import{S as Se,a as W,b as Ce,g as we,h as Te,i as Ee,l as De,m as Oe,n as ke,o as Ae,p as je,t as Me,u as Ne,v as Pe,w as Fe,x as Ie}from"./db-DjAqlQ2I.js";import{a as Le,i as Re,n as ze,r as Be}from"./tray-runtime-config-DlPGhxQs.js";import{a as Ve,i as He,n as Ue,o as We,r as Ge}from"./runtime-mode-M-qJL9jF.js";import{a as Ke,c as qe,d as Je,i as Ye,l as Xe,n as Ze,o as Qe,s as $e,t as et,u as tt}from"./lick-manager-Ct3WOtut.js";import{i as nt,n as rt,t as it}from"./path-utils-DU6QhF_k.js";import{u as at}from"./transform-messages-CVIV-EgO.js";import{l as ot,m as st}from"./bedrock-camp-CvxD6hHk.js";import{t as ct}from"./__vite-browser-external-SwrSgYTf.js";import{a as lt,n as ut,r as dt}from"./fs-BnRVC9hw.js";import{a as ft,c as pt,i as G,n as mt,o as ht,r as gt,s as _t}from"./cost-command-Cpg2Em0Q.js";import{a as vt,c as yt,d as bt,f as xt,i as St,l as Ct,m as wt,n as Tt,o as Et,p as Dt,r as Ot,s as kt,u as At}from"./skills-CF4YIozr.js";import{n as jt,t as Mt}from"./llm-session-id-ZObKEXzb.js";import{a as Nt,c as Pt,d as Ft,f as It,i as Lt,l as Rt,n as zt,o as Bt,r as Vt,s as Ht,t as Ut,u as Wt}from"./installer-BmmE_GGY.js";import{n as Gt,t as Kt}from"./safe-buffer-C0pSmFaz.js";import{t as qt}from"./global-db-DvmmimLY.js";import{a as Jt,i as Yt,r as Xt,t as Zt}from"./git-config-Lj0BT7Oc.js";import{t as Qt}from"./process-manager-B5dz0PkO.js";import{D as $t,O as en,S as tn,_ as nn,a as rn,b as an,c as on,d as sn,f as cn,g as ln,h as un,i as dn,l as fn,m as pn,n as mn,o as hn,p as gn,r as _n,s as vn,t as yn,u as bn,v as xn,x as Sn,y as Cn}from"./shared-CZ95RVhr.js";import{i as wn,r as Tn,t as En}from"./magick-wasm-CdLQkNZO.js";import{a as Dn,i as On,r as kn,t as An}from"./script-catalog-BYXhqRAc.js";import{t as jn}from"./local-llm-C6Uyn1eH.js";import{t as Mn}from"./client-CpLUc-P8.js";const Nn=n(`cdp`);var Pn=class{ws=null;nextId=1;_superseded=!1;pending=new Map;listeners=new Map;_state=`disconnected`;get state(){return this._state}get superseded(){return this._superseded}async connect(e){if(this._state!==`disconnected`)throw Error(`Cannot connect: state is ${this._state}`);if(!e?.url)throw Error(`CDPClient.connect() requires a WebSocket URL`);let{url:t,timeout:n=5e3,protocols:r}=e;return this._state=`connecting`,new Promise((e,i)=>{let a=setTimeout(()=>{this.cleanup(),i(Error(`CDP connection timed out after ${n}ms`))},n);try{this.ws=r===void 0?new WebSocket(t):new WebSocket(t,r)}catch(e){clearTimeout(a),this._state=`disconnected`,i(e);return}this.ws.onopen=()=>{clearTimeout(a),this._state=`connected`,this._superseded=!1,Nn.info(`Connected`,{url:t}),e()},this.ws.onerror=e=>{clearTimeout(a),this._state===`connecting`&&(Nn.error(`Connection failed`,{url:t}),this.cleanup(),i(Error(`CDP WebSocket connection failed`)))},this.ws.onmessage=e=>{this.handleMessage(e.data)},this.ws.onclose=e=>{this.handleClose(e?.code)}})}disconnect(){this.ws&&(this.ws.onclose=null,this.ws.close()),this._superseded=!1,this.cleanup(),Nn.info(`Disconnected`)}async send(e,t,n,r=3e4){if(this._state!==`connected`||!this.ws)throw Error(`CDP client is not connected`);let i=this.nextId++,a={id:i,method:e};return t&&(a.params=t),n&&(a.sessionId=n),Nn.debug(`Send`,{method:e,id:i,sessionId:n}),new Promise((t,n)=>{let o=setTimeout(()=>{this.pending.delete(i),n(Error(`CDP command timed out after ${r}ms: ${e}`))},r);this.pending.set(i,{resolve:e=>{clearTimeout(o),t(e)},reject:e=>{clearTimeout(o),n(e)}}),this.ws.send(JSON.stringify(a))})}on(e,t){let n=this.listeners.get(e);n||(n=new Set,this.listeners.set(e,n)),n.add(t)}off(e,t){let n=this.listeners.get(e);n&&(n.delete(t),n.size===0&&this.listeners.delete(e))}once(e,t=3e4){return new Promise((n,r)=>{let i=setTimeout(()=>{this.off(e,a),r(Error(`Timed out waiting for event: ${e}`))},t),a=t=>{clearTimeout(i),this.off(e,a),n(t)};this.on(e,a)})}handleMessage(e){let t;try{t=JSON.parse(e)}catch{return}if(`id`in t&&typeof t.id==`number`){let e=t;Nn.debug(`Response`,{id:e.id,hasError:!!e.error});let n=this.pending.get(e.id);n&&(this.pending.delete(e.id),e.error?(Nn.error(`Command error`,{id:e.id,code:e.error.code,message:e.error.message}),n.reject(Error(`CDP error: ${e.error.message} (${e.error.code})`))):n.resolve(e.result??{}));return}if(`method`in t){let e=t;Nn.debug(`Event`,{method:e.method,sessionId:e.sessionId});let n=this.listeners.get(e.method);if(n){let t=e.sessionId?{...e.params,sessionId:e.sessionId}:e.params??{};for(let e of n)try{e(t)}catch{}}}}handleClose(e){let t=e===4001;t?(this._superseded=!0,Nn.warn(`CDP slot superseded by another SLICC tab/window on this instance`,{code:e})):Nn.error(`Connection closed unexpectedly`,{pendingCommands:this.pending.size});let n=t?`CDP connection superseded by another SLICC tab/window on this instance`:`CDP connection closed`;for(let[,e]of this.pending)e.reject(Error(n));this.cleanup()}cleanup(){this.ws=null,this._state=`disconnected`,this.pending.clear()}};const Fn=`(function() {
|
|
2
2
|
'use strict';
|
|
3
3
|
|
|
4
4
|
// ===== DOM Utilities =====
|
|
@@ -4850,13 +4850,13 @@ except BaseException:
|
|
|
4850
4850
|
`)?t:`${t}\n`);return}try{e.writeStdout(`${JSON.stringify(t,null,2)}\n`)}catch{e.writeStdout(`${String(t)}\n`)}},warn(n,i){let a=typeof i==`object`&&i&&`prefix`in i?i.prefix:void 0;e.writeStderr(r(a,t(n)))},help(t){throw e.writeStdout(t.endsWith(`
|
|
4851
4851
|
`)?t:`${t}\n`),e.exit(0),Error(`unreachable`)}}}const eC={reset:`\x1B[0m`,green:`\x1B[32m`,red:`\x1B[31m`,yellow:`\x1B[33m`,gray:`\x1B[90m`,bold:`\x1B[1m`,cyan:`\x1B[36m`,dim:`\x1B[2m`};function tC(e){let t=e.isTTY&&!e.noColor,n=e=>n=>t?`${e}${n}${eC.reset}`:String(n);return{enabled:t,green:n(eC.green),red:n(eC.red),yellow:n(eC.yellow),gray:n(eC.gray),bold:n(eC.bold),cyan:n(eC.cyan),dim:n(eC.dim)}}const nC={ms:1,s:1e3,m:6e4,h:36e5,d:864e5,w:6048e5,M:26298e5,y:315576e5};function rC(e){if(typeof e==`number`&&Number.isFinite(e))return Math.trunc(e);if(typeof e!=`string`)throw TypeError(`time.parseDuration: spec must be string or number`);let t=e.trim(),n=/^([0-9]+(?:\.[0-9]+)?)\s*(ms|s|m|h|d|w|M|y)?$/.exec(t);if(!n)throw RangeError(`time.parseDuration: unrecognized spec "${e}"`);let r=Number(n[1]),i=n[2]??`ms`;return Math.trunc(r*nC[i])}function iC(e){return e<10?`0${e}`:String(e)}const aC={parseDuration:rC,ago(e,t=new Date){return new Date(t.getTime()-rC(e))},range(e,t=new Date){let n=new Date(t.getTime());return{start:new Date(n.getTime()-rC(e)),end:n}},future(e,t=new Date){let n=new Date(t.getTime());return{start:n,end:new Date(n.getTime()+rC(e))}},gmailDate(e,t=new Date){let n=new Date(t.getTime()-rC(e));return`${n.getFullYear()}/${iC(n.getMonth()+1)}/${iC(n.getDate())}`}},oC=/\u001b\[[0-9;]*m/g;function sC(e){return e.replace(oC,``)}function cC(e){return sC(e).length}function lC(e,t){let n=String(e??``);return t<=0?``:cC(n)<=t?n:t<=1?n.slice(0,t):`${sC(n).slice(0,t-1)}…`}function uC(e,t){let n=String(e??``),r=cC(n);return r===t?n:r>t?lC(n,t):n+` `.repeat(t-r)}function dC(e,t){if(!e.length)return``;let n=Math.max(...e.map(e=>e.length)),r=[];for(let i=0;i<n;i++)if(t&&t[i]!==void 0)r[i]=t[i];else{let t=0;for(let n of e){let e=i<n.length?String(n[i]??``):``;t=Math.max(t,cC(e))}r[i]=t}return e.map(e=>r.map((t,n)=>uC(n<e.length?String(e[n]??``):``,t)).join(` `).replace(/\s+$/,``)).join(`
|
|
4852
4852
|
`)}function fC(e){return e instanceof Date?e:new Date(e)}function pC(e,t=`short`){let n=fC(e);if(Number.isNaN(n.getTime()))return String(e);if(t===`iso`)return n.toISOString();if(t===`locale`)return new Intl.DateTimeFormat(void 0,{dateStyle:`medium`}).format(n);if(t===`human`){let e=Date.now()-n.getTime(),t=Math.abs(e);if(t<6e4)return e>=0?`just now`:`in a moment`;let r=(t,n)=>e>=0?`${t} ${n}${t===1?``:`s`} ago`:`in ${t} ${n}${t===1?``:`s`}`;return t<36e5?r(Math.round(t/6e4),`minute`):t<864e5?r(Math.round(t/36e5),`hour`):t<26298e5?r(Math.round(t/864e5),`day`):t<315576e5?r(Math.round(t/26298e5),`month`):r(Math.round(t/315576e5),`year`)}return`${n.getFullYear()}-${iC(n.getMonth()+1)}-${iC(n.getDate())}`}const mC={trunc:lC,col:uC,table:dC,date:pC},hC=async(e,t,n)=>{let r=Math.max(1,Math.trunc(e)||1),i=Array(t.length),a=0,o=[],s=async()=>{for(;;){let e=a++;if(e>=t.length)return;i[e]=await n(t[e],e)}};for(let e=0;e<Math.min(r,t.length);e++)o.push(s());return await Promise.all(o),i};function gC(e,t){let n=[];for(let r of e)r===``||r===`.`||(r===`..`?n.length>0&&n[n.length-1]!==`..`?n.pop():t&&n.push(`..`):n.push(r));return n}function _C(e){if(e.length===0)return`.`;let t=e.charCodeAt(0)===47,n=e.charCodeAt(e.length-1)===47,r=gC(e.split(`/`),!t).join(`/`);return r.length===0&&!t&&(r=`.`),r.length>0&&n&&(r+=`/`),(t?`/`:``)+r}function vC(...e){let t=e.filter(e=>typeof e==`string`&&e.length>0).join(`/`);return t.length===0?`.`:_C(t)}function yC(e){if(e.length===0)return`.`;let t=e.charCodeAt(0)===47,n=-1,r=!0;for(let t=e.length-1;t>=1;t--)if(e.charCodeAt(t)===47){if(!r){n=t;break}}else r=!1;return n===-1?t?`/`:`.`:t&&n===1?`//`:e.slice(0,n)}function bC(e,t){let n=0,r=-1,i=!0;for(let t=e.length-1;t>=0;t--)if(e.charCodeAt(t)===47){if(!i){n=t+1;break}}else r===-1&&(i=!1,r=t+1);let a=r===-1?``:e.slice(n,r);return t&&a.endsWith(t)&&a!==t?a.slice(0,a.length-t.length):a}function xC(e){let t=bC(e),n=t.lastIndexOf(`.`);return n<=0?``:t.slice(n)}function SC(...e){let t=``,n=!1;for(let r=e.length-1;r>=0&&!n;r--){let i=e[r];typeof i!=`string`||i.length===0||(t=t.length>0?`${i}/${t}`:i,n=i.charCodeAt(0)===47)}n||(t=t.length>0?`/${t}`:`/`);let r=gC(t.split(`/`),!1).join(`/`);return r.length>0?`/${r}`:`/`}function CC(e,t){let n=SC(e),r=SC(t);if(n===r)return``;let i=n.split(`/`).filter(Boolean),a=r.split(`/`).filter(Boolean),o=0;for(;o<i.length&&o<a.length&&i[o]===a[o];)o++;return[...i.slice(o).map(()=>`..`),...a.slice(o)].join(`/`)}function wC(e){let t=e.charCodeAt(0)===47?`/`:``,n=bC(e),r=xC(e),i=r?n.slice(0,n.length-r.length):n,a=yC(e);return a===`.`&&t===``&&(a=``),{root:t,dir:a,base:n,ext:r,name:i}}function TC(e){let t=e.dir||e.root||``,n=e.base||`${e.name||``}${e.ext||``}`;return t?t===e.root?`${t}${n}`:`${t}/${n}`:n}const EC={sep:`/`,delimiter:`:`,basename:bC,dirname:yC,extname:xC,isAbsolute:e=>e.length>0&&e.charCodeAt(0)===47,join:vC,normalize:_C,resolve:SC,relative:CC,parse:wC,format:TC},DC=65536,OC={md5:gy.md5,sha1:_y.sha1,sha256:vy.sha256};function kC(e,t){let n=globalThis.Buffer;if(!n)throw Error(`crypto.createHash: Buffer is unavailable in this environment`);return t?n.from(e,t):n.from(e)}function AC(e,t){return typeof e==`string`?t===`hex`||t===`base64`||t===`base64url`||t===`latin1`||t===`binary`?new Uint8Array(kC(e,t===`binary`?`latin1`:t)):e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):e}function jC(e){let t=String(e).toLowerCase().replace(`-`,``),n=OC[t];if(!n)throw Error(`Digest method not supported: ${e}`);let r=n.create(),i=!1,a={update(e,t){if(i)throw Error(`Digest already called`);return r.update(AC(e,t)),a},digest(e){i=!0;let t=kC(r.array());return e?t.toString(e):t}};return a}function MC(){let e=globalThis.crypto;if(!e||typeof e.getRandomValues!=`function`)throw Error(`crypto: globalThis.crypto is unavailable in this environment`);return e}function NC(e){return MC().getRandomValues(e)}function PC(e){for(let t=0;t<e.length;t+=DC){let n=Math.min(t+DC,e.length);NC(e.subarray(t,n))}}function FC(e){return e instanceof Uint8Array?e:new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}const IC=Array.from({length:256},(e,t)=>(t+256).toString(16).slice(1));function LC(){let e=MC();if(typeof e.randomUUID==`function`)return e.randomUUID();let t=NC(new Uint8Array(16));return t[6]=t[6]&15|64,t[8]=t[8]&63|128,`${IC[t[0]]}${IC[t[1]]}${IC[t[2]]}${IC[t[3]]}-${IC[t[4]]}${IC[t[5]]}-${IC[t[6]]}${IC[t[7]]}-${IC[t[8]]}${IC[t[9]]}-${IC[t[10]]}${IC[t[11]]}${IC[t[12]]}${IC[t[13]]}${IC[t[14]]}${IC[t[15]]}`}const RC={randomFillSync(e,t=0,n){let r=FC(e),i=t,a=n===void 0?r.length:i+n;return PC(r.subarray(i,a)),e},randomBytes(e){let t=globalThis.Buffer,n=t&&typeof t.allocUnsafe==`function`?t.allocUnsafe(e):new Uint8Array(e);return PC(FC(n)),n},randomUUID:LC,getRandomValues(e){return NC(e)},createHash:jC,get webcrypto(){return MC()},get subtle(){return MC().subtle}};var zC=class extends Error{actual;expected;operator;generatedMessage;code;constructor(e={}){let t=!e.message;super(e.message||`${BC(e.actual)} ${e.operator||`!=`} ${BC(e.expected)}`),this.name=`AssertionError`,this.actual=e.actual,this.expected=e.expected,this.operator=e.operator||``,this.generatedMessage=t,this.code=`ERR_ASSERTION`}};function BC(e){if(typeof e==`string`)return JSON.stringify(e);if(e==null)return String(e);if(typeof e==`object`)try{return JSON.stringify(e)}catch{return String(e)}return String(e)}function VC(e,t){return e instanceof Error?e:typeof e==`string`?new zC({message:e}):t()}function HC(e,t,n,r){if(e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(!WC(e[i],t[i],n,r))return!1;return!0}function UC(e,t,n,r){let i=Object.keys(e);if(i.length!==Object.keys(t).length)return!1;for(let a of i){if(!Object.prototype.hasOwnProperty.call(t,a))return!1;let i=e[a],o=t[a];if(!WC(i,o,n,r))return!1}return!0}function WC(e,t,n,r){if((n?Object.is(e,t):e===t)||!n&&e==t)return!0;if(typeof e!=`object`||typeof t!=`object`||e===null||t===null)return!1;let i=e,a=t;return n&&Object.getPrototypeOf(i)!==Object.getPrototypeOf(a)?!1:r.get(i)===a?!0:(r.set(i,a),Array.isArray(e)===Array.isArray(t)?Array.isArray(e)&&Array.isArray(t)?HC(e,t,n,r):UC(i,a,n,r):!1)}function GC(e,t){try{if(e instanceof t)return!0}catch{}try{return!!t(e)}catch{return!1}}function KC(e,t){for(let[n,r]of Object.entries(t)){let t=e[n];if(r instanceof RegExp){if(typeof t!=`string`||!r.test(t))return!1}else if(t!==r)return!1}return!0}function qC(e,t){if(t===void 0)return!0;if(t instanceof RegExp){let n=e instanceof Error?e.message:String(e);return t.test(n)}return typeof t==`function`?GC(e,t):t&&typeof t==`object`?!e||typeof e!=`object`?!1:KC(e,t):!1}function JC(e){let t=(e,t)=>{if(!e)throw VC(t,()=>new zC({message:`The expression evaluated to a falsy value`,actual:e,expected:!0,operator:`==`}))},n=((e,n)=>t(e,n)),r=(e,t,n)=>{if(!Object.is(e,t))throw VC(n,()=>new zC({actual:e,expected:t,operator:`strictEqual`}))},i=(t,n,i)=>{if(e){r(t,n,i);return}if(t!=n)throw VC(i,()=>new zC({actual:t,expected:n,operator:`==`}))},a=(e,t,n)=>{if(Object.is(e,t))throw VC(n,()=>new zC({actual:e,expected:t,operator:`notStrictEqual`}))},o=(t,n,r)=>{if(e){a(t,n,r);return}if(t==n)throw VC(r,()=>new zC({actual:t,expected:n,operator:`!=`}))},s=(e,t,n)=>{if(!WC(e,t,!0,new WeakMap))throw VC(n,()=>new zC({actual:e,expected:t,operator:`deepStrictEqual`}))},c=(t,n,r)=>{if(e){s(t,n,r);return}if(!WC(t,n,!1,new WeakMap))throw VC(r,()=>new zC({actual:t,expected:n,operator:`deepEqual`}))},l=(e,t,n)=>{if(WC(e,t,!0,new WeakMap))throw VC(n,()=>new zC({actual:e,expected:t,operator:`notDeepStrictEqual`}))};return n.ok=t,n.equal=i,n.notEqual=o,n.strictEqual=r,n.notStrictEqual=a,n.deepEqual=c,n.deepStrictEqual=s,n.notDeepEqual=(t,n,r)=>{if(e){l(t,n,r);return}if(WC(t,n,!1,new WeakMap))throw VC(r,()=>new zC({actual:t,expected:n,operator:`notDeepEqual`}))},n.notDeepStrictEqual=l,n.throws=(e,t,n)=>{let r,i=!1;try{e()}catch(e){r=e,i=!0}if(!i)throw VC(typeof t==`string`?t:n,()=>new zC({message:`Missing expected exception`,operator:`throws`}));if(!(typeof t==`string`||t instanceof Error)&&!qC(r,t))throw VC(n,()=>new zC({message:`Got unwanted exception`,actual:r,operator:`throws`}))},n.doesNotThrow=(e,t)=>{try{e()}catch(e){throw VC(t,()=>new zC({message:`Got unwanted exception`,actual:e,operator:`doesNotThrow`}))}},n.fail=e=>{throw VC(e,()=>new zC({message:`Failed`,operator:`fail`}))},n.AssertionError=zC,n}const YC=JC(!0);YC.strict=YC;const XC=JC(!1);XC.strict=YC;const ZC=Symbol.for(`nodejs.util.inspect.custom`),QC=Symbol.for(`nodejs.util.promisify.custom`);function $C(e){return`'${e.replace(/\\/g,`\\\\`).replace(/'/g,`\\'`).replace(/\n/g,`\\n`)}'`}function ew(e){if(e===null)return`null`;let t=typeof e;if(t===`string`)return $C(e);if(t===`number`)return Object.is(e,-0)?`-0`:String(e);if(t===`bigint`)return`${String(e)}n`;if(t===`boolean`||t===`undefined`)return String(e);if(t===`symbol`)return e.toString();if(t===`function`){let t=e.name;return t?`[Function: ${t}]`:`[Function (anonymous)]`}return null}function tw(e){return e instanceof RegExp?e.toString():e instanceof Date?Number.isNaN(e.getTime())?`Invalid Date`:e.toISOString():e instanceof Error?e.stack||`${e.name}: ${e.message}`:null}function nw(e,t,n){if(Array.isArray(e))return e.length===0?`[]`:`[ ${e.map(e=>rw(e,t+1,n)).join(`, `)} ]`;if(e instanceof Map){let r=[...e].map(([e,r])=>`${rw(e,t+1,n)} => ${rw(r,t+1,n)}`);return`Map(${e.size}) {${r.length?` ${r.join(`, `)} `:``}}`}if(e instanceof Set){let r=[...e].map(e=>rw(e,t+1,n));return`Set(${e.size}) {${r.length?` ${r.join(`, `)} `:``}}`}let r=Object.keys(e),i=e.constructor?e.constructor.name:``,a=i&&i!==`Object`?`${i} `:``;return r.length===0?`${a}{}`:`${a}{ ${r.map(r=>`${/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(r)?r:$C(r)}: ${rw(e[r],t+1,n)}`).join(`, `)} }`}function rw(e,t,n){let r=ew(e);if(r!==null)return r;let i=e,a=tw(i);if(a!==null)return a;let o=i[ZC];if(typeof o==`function`)try{return String(o.call(i,n.maxDepth,n.opts))}catch{}if(n.seen.has(e))return`[Circular *1]`;if(n.maxDepth!==null&&t>n.maxDepth)return Array.isArray(e)?`[Array]`:`[Object]`;n.seen.add(e);try{return nw(i,t,n)}finally{n.seen.delete(e)}}function iw(e,t={}){let n=t.depth===void 0?2:t.depth;return rw(e,0,{seen:new Set,maxDepth:n,opts:t})}function aw(e,t,n,r){if(e===`%%`)return`%`;if(n.i>=t.length)return e;let i=t[n.i];switch(e){case`%s`:return n.i++,typeof i==`string`?i:typeof i==`bigint`?`${String(i)}n`:i==null||typeof i==`number`||typeof i==`boolean`?String(i):iw(i,{depth:r.depth===void 0?2:r.depth});case`%d`:return n.i++,typeof i==`bigint`?`${String(i)}n`:Number.isNaN(Number(i))?`NaN`:String(Number(i));case`%i`:return n.i++,typeof i==`bigint`?`${String(i)}n`:String(Number.parseInt(i,10));case`%f`:return n.i++,String(typeof i==`bigint`?i:Number.parseFloat(i));case`%j`:n.i++;try{return JSON.stringify(i)??`undefined`}catch{return`[Circular]`}case`%o`:return n.i++,iw(i,{depth:4});case`%O`:return n.i++,iw(i,{depth:null});case`%c`:return n.i++,``;default:return e}}function ow(e,...t){let n=t[0];if(typeof n!=`string`)return t.map(e=>typeof e==`string`?e:iw(e)).join(` `);let r={i:1},i=n.replace(/%[sdifjoOc%]/g,n=>aw(n,t,r,e));for(;r.i<t.length;r.i++){let e=t[r.i];i+=` ${typeof e==`string`?e:iw(e)}`}return i}function sw(...e){return ow({},...e)}function cw(e,t){if(e==null)throw TypeError(`The constructor to "inherits" must not be null or undefined`);if(t==null)throw TypeError(`The super constructor to "inherits" must not be null or undefined`);if(t.prototype===void 0)throw TypeError(`The super constructor to "inherits" must have a prototype`);e.super_=t,Object.setPrototypeOf(e.prototype,t.prototype)}function lw(e){if(typeof e!=`function`)throw TypeError(`The "original" argument must be of type function`);let t=e[QC];if(t){if(typeof t!=`function`)throw TypeError(`The [util.promisify.custom] property must be of type function`);return t}function n(...t){return new Promise((n,r)=>{e.call(this,...t,(e,...t)=>{if(e){r(e);return}n(t.length>1?t:t[0])})})}return Object.setPrototypeOf(n,Object.getPrototypeOf(e)),Object.defineProperties(n,Object.getOwnPropertyDescriptors(e)),n}const uw=iw;uw.custom=ZC;const dw=lw;dw.custom=QC;const fw={format:sw,formatWithOptions:ow,inspect:uw,inherits:cw,promisify:dw};function pw(e){return typeof e==`string`?new Uint8Array(kC(e,`utf8`)):ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e)}function mw(e){let t={};return e&&(typeof e.level==`number`&&(t.level=e.level),typeof e.windowBits==`number`&&(t.windowBits=e.windowBits),typeof e.memLevel==`number`&&(t.memLevel=e.memLevel),typeof e.strategy==`number`&&(t.strategy=e.strategy)),t}function hw(e,t,n){return kC(e(pw(t),mw(n)))}function gw(e,t,n,r){let i=typeof n==`function`?n:r,a=typeof n==`function`?void 0:n;if(typeof i!=`function`)throw TypeError(`zlib: callback is required`);let o;try{o=hw(e,t,a)}catch(e){queueMicrotask(()=>i(e instanceof Error?e:Error(String(e))));return}queueMicrotask(()=>i(null,o))}const _w={gzipSync:(e,t)=>hw(GS,e,t),gunzipSync:(e,t)=>hw(YS,e,t),deflateSync:(e,t)=>hw(US,e,t),inflateSync:(e,t)=>hw(YS,e,t),deflateRawSync:(e,t)=>hw(WS,e,t),inflateRawSync:(e,t)=>hw(XS,e,t),gzip:(e,t,n)=>gw(GS,e,t,n),gunzip:(e,t,n)=>gw(YS,e,t,n),deflate:(e,t,n)=>gw(US,e,t,n),inflate:(e,t,n)=>gw(YS,e,t,n),deflateRaw:(e,t,n)=>gw(WS,e,t,n),inflateRaw:(e,t,n)=>gw(XS,e,t,n),constants:{Z_NO_FLUSH:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1}},vw={tmpdir:()=>`/tmp`,homedir:()=>`/home/user`,platform:()=>`linux`,arch:()=>`x64`,EOL:`
|
|
4853
|
-
`,cpus:()=>[{model:`virtual`,speed:0}],hostname:()=>`slicc`,type:()=>`Linux`,release:()=>`0.0.0`};function yw(e){let t=typeof e==`string`?e:e.href;if(!t.startsWith(`file://`))throw TypeError(`fileURLToPath: not a file URL`);let n=t.slice(7);return decodeURIComponent(n)}function bw(e){let t=e.split(`/`).map(e=>encodeURIComponent(e)).join(`/`);return new URL(`file://${t}`)}const xw={URL:globalThis.URL,URLSearchParams:globalThis.URLSearchParams,fileURLToPath:yw,pathToFileURL:bw};var Sw=class{_events=new Map;on(e,t){let n=this._events.get(e);return n?n.push(t):this._events.set(e,[t]),this}addListener(e,t){return this.on(e,t)}off(e,t){let n=this._events.get(e);if(n){let r=n.indexOf(t);r!==-1&&n.splice(r,1),n.length===0&&this._events.delete(e)}return this}removeListener(e,t){return this.off(e,t)}once(e,t){let n=(...r)=>{this.off(e,n),t(...r)};return this.on(e,n)}emit(e,...t){let n=this._events.get(e);if(!n||n.length===0)return!1;for(let e of[...n])e(...t);return!0}removeAllListeners(e){return e===void 0?this._events.clear():this._events.delete(e),this}listenerCount(e){return this._events.get(e)?.length??0}listeners(e){return[...this._events.get(e)??[]]}};const Cw=Object.assign(Sw,{EventEmitter:Sw,default:Sw});var ww=class{_events=new Map;writable=!0;readable=!0;on(e,t){let n=this._events.get(e);return n?n.push(t):this._events.set(e,[t]),this}once(e,t){let n=(...r)=>{this.off(e,n),t(...r)};return this.on(e,n)}off(e,t){let n=this._events.get(e);if(n){let e=n.indexOf(t);e!==-1&&n.splice(e,1)}return this}emit(e,...t){let n=this._events.get(e);if(!n||n.length===0)return!1;for(let e of[...n])e(...t);return!0}pipe(e){return e}removeListener(e,t){return this.off(e,t)}removeAllListeners(){return this._events.clear(),this}},Tw=class extends ww{read(){return null}destroy(){return this}},Ew=class extends ww{write(e,t,n){return n&&queueMicrotask(n),!0}end(e){return e&&queueMicrotask(e),this}destroy(){return this}},Dw=class extends ww{write(e,t,n){return n&&queueMicrotask(n),!0}end(e){return e&&queueMicrotask(e),this}read(){return null}destroy(){return this}};const Ow={Readable:Tw,Writable:Ew,Transform:Dw,PassThrough:class extends Dw{},Stream:ww};let kw=1;function Aw(e){if(typeof e==`string`)return e;if(ArrayBuffer.isView(e)){let t=e;return new TextDecoder().decode(new Uint8Array(t.buffer,t.byteOffset,t.byteLength))}return e==null?``:String(e)}function jw(e,t){return t===void 0||t===`utf8`||t===`utf-8`?e:t===`buffer`||t===null?kC(e):kC(e).toString(t)}function Mw(e,t){if(e.length===0)return jw(``,t);if(typeof e[0]==`string`)return e.join(``);let n=globalThis.Buffer;return n?n.concat(e):e[0]}function Nw(e,t,n){t.length>0&&e.emit(`data`,jw(t,n)),e.readable=!1,e.emit(`end`)}function Pw(e){let t=e=>{typeof e==`function`&&queueMicrotask(e)};return{writable:!0,write(n,r,i){return e.stdin.write(Aw(n)),t(typeof r==`function`?r:i),!0},end(n,r,i){n!==void 0&&typeof n!=`function`&&e.stdin.write(Aw(n)),e.stdin.end(),this.writable=!1,t(typeof n==`function`?n:typeof r==`function`?r:i)}}}var Fw=class extends Sw{stdout;stderr;stdin;pid;exitCode=null;signalCode=null;killed=!1;spawnfile;spawnargs;handle;constructor(e,t,n,r){super(),this.handle=e,this.pid=kw++,this.spawnfile=n,this.spawnargs=r,this.stdout=new Tw,this.stderr=new Tw,this.stdin=Pw(e),e.done.then(e=>this.finish(e,t),e=>this.emit(`error`,e instanceof Error?e:Error(String(e))))}finish(e,t){Nw(this.stdout,e.stdout,t),Nw(this.stderr,e.stderr,t),this.exitCode=e.exitCode;let n=this.killed?null:e.exitCode,r=this.killed?this.signalCode:null;this.emit(`exit`,n,r),this.emit(`close`,n,r)}kill(e=`SIGTERM`){return this.killed=!0,this.signalCode=e,this.handle.kill(e).catch(()=>{}),!0}};function Iw(e){let t=(t,n,r,i,a)=>{let o=e.start(t),s=new Fw(o,r,i,a);return n.input!==void 0&&s.stdin.write(Aw(n.input)),queueMicrotask(()=>o.stdin.end()),s},n=(e,t,n,r)=>{if(typeof r!=`function`)return;let i=[],a=[];e.stdout.on(`data`,e=>i.push(e)),e.stderr.on(`data`,e=>a.push(e)),e.once(`error`,e=>r(e,Mw(i,t),Mw(a,t))),e.once(`close`,(o,s)=>{let c=Mw(i,t),l=Mw(a,t);if(o===0){r(null,c,l);return}r(Object.assign(Error(`Command failed: ${n}\n${Aw(l)}`),{code:o===null?void 0:o,killed:e.killed,signal:s??null,cmd:n}),c,l)})},r=(e,r,i)=>{let a=typeof r==`function`?r:i,o=r&&typeof r==`object`?r:{},s=o.encoding===void 0?`utf8`:o.encoding,c=t(e,o,s,e,[]);return n(c,s,e,a),c},i=(e,r,i,a)=>{let o=[],s={},c;Array.isArray(r)?(o=r,typeof i==`function`?c=i:(s=i??{},c=typeof a==`function`?a:void 0)):typeof r==`function`?c=r:r&&typeof r==`object`&&(s=r,c=typeof i==`function`?i:void 0);let l=s.encoding===void 0?`utf8`:s.encoding,u=[e,...o],d=t(u,s,l,e,o);return n(d,l,u.join(` `),c),d},a=(e,n,r)=>{let i=[],a={};Array.isArray(n)?(i=n,a=r??{}):n&&typeof n==`object`&&(a=n);let o=a.encoding===void 0?`buffer`:a.encoding,s=a.shell?`${e}${i.length?` ${i.join(` `)}`:``}`:[e,...i];return t(s,a,o,e,i)},o=(e,t)=>new Promise((n,i)=>{r(e,t,(e,t,r)=>{if(e){i(Object.assign(e,{stdout:t,stderr:r}));return}n({stdout:t,stderr:r})})}),s=(e,t,n)=>new Promise((r,a)=>{i(e,Array.isArray(t)?t:[],Array.isArray(t)?n:t,(e,t,n)=>{if(e){a(Object.assign(e,{stdout:t,stderr:n}));return}r({stdout:t,stderr:n})})}),c=e=>()=>{throw Error(`child_process.${e} is not available in the browser realm`)},l=(e,t)=>{Object.defineProperty(e,QC,{value:t,enumerable:!1,configurable:!0})};return l(r,o),l(i,s),{exec:r,execFile:i,spawn:a,execSync:c(`execSync`),spawnSync:c(`spawnSync`),execFileSync:c(`execFileSync`),fork:c(`fork`),ChildProcess:Fw}}function Lw(e){let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}var Rw=class{rpc;targetId;selector;index;constructor(e,t,n,r){this.rpc=e,this.targetId=t,this.selector=n,this.index=r}evalOnElement(e){let t=`(() => { const els = document.querySelectorAll(${JSON.stringify(this.selector)}); const el = els[${this.index}]; ${e} })()`;return this.rpc.call(`browser`,`evalAsync`,[this.targetId,t])}async textContent(){return this.evalOnElement(`return el ? el.textContent : null;`)}async getAttribute(e){return this.evalOnElement(`return el ? el.getAttribute(${JSON.stringify(e)}) : null;`)}async isVisible(){return this.evalOnElement(`if (!el) return false; const s = getComputedStyle(el); if (s.display === 'none' || s.visibility === 'hidden' || s.opacity === '0') return false; const r = el.getBoundingClientRect(); return r.width > 0 && r.height > 0;`)}async boundingBox(){return this.evalOnElement(`if (!el) return null; const r = el.getBoundingClientRect(); return { x: r.x, y: r.y, width: r.width, height: r.height };`)}},zw=class{rpc;targetId;onClose;closed=!1;constructor(e,t,n){this.rpc=e,this.targetId=t,this.onClose=n}async goto(e,t){await this.rpc.call(`browser`,`navigateTab`,[this.targetId,e])}async waitForLoadState(e){await this.rpc.call(`browser`,`waitForLoadState`,[this.targetId,e??`load`])}async waitForTimeout(e){await new Promise(t=>setTimeout(t,e))}async evaluate(e,...t){let n=typeof e==`string`?e:`(${e.toString()}).apply(null, JSON.parse(${JSON.stringify(JSON.stringify(t))}))`;return this.rpc.call(`browser`,`evalAsync`,[this.targetId,n])}async screenshot(e){let t={};e?.fullPage!==void 0&&(t.fullPage=e.fullPage);let n=Lw(await this.rpc.call(`browser`,`screenshotTab`,[this.targetId,t]));return e?.path&&await this.rpc.call(`vfs`,`writeFileBinary`,[e.path,n]),n}async $(e){return await this.rpc.call(`browser`,`evalAsync`,[this.targetId,`!!document.querySelector(${JSON.stringify(e)})`])?new Rw(this.rpc,this.targetId,e,0):null}async $$(e){let t=await this.rpc.call(`browser`,`evalAsync`,[this.targetId,`document.querySelectorAll(${JSON.stringify(e)}).length`]),n=[];for(let r=0;r<t;r++)n.push(new Rw(this.rpc,this.targetId,e,r));return n}async $$eval(e,t,...n){if(typeof t==`string`)return this.rpc.call(`browser`,`evalAsync`,[this.targetId,t]);let r=`(${t.toString()}).apply(null, [Array.from(document.querySelectorAll(${JSON.stringify(e)}))].concat(JSON.parse(${JSON.stringify(JSON.stringify(n))})))`;return this.rpc.call(`browser`,`evalAsync`,[this.targetId,r])}async content(){return this.rpc.call(`browser`,`evalAsync`,[this.targetId,`document.documentElement.outerHTML`])}async setViewportSize(e){await this.rpc.call(`browser`,`setViewport`,[this.targetId,e.width,e.height])}async close(){this.closed||(this.closed=!0,await this.rpc.call(`browser`,`closeTab`,[this.targetId]),this.onClose?.())}},Bw=class{rpc;openPages=[];constructor(e){this.rpc=e}async newPage(e){let t=await this.rpc.call(`browser`,`createTab`,[`about:blank`]);e?.viewport&&await this.rpc.call(`browser`,`setViewport`,[t,e.viewport.width,e.viewport.height]);let n=new zw(this.rpc,t,()=>{let e=this.openPages.indexOf(n);e!==-1&&this.openPages.splice(e,1)});return this.openPages.push(n),n}pages(){return[...this.openPages]}async close(){let e=this.openPages.splice(0,this.openPages.length);for(let t of e)await t.close()}},Vw=class{rpc;openPages=[];openContexts=[];constructor(e){this.rpc=e}async newPage(e){let t=await this.rpc.call(`browser`,`createTab`,[`about:blank`]);e?.viewport&&await this.rpc.call(`browser`,`setViewport`,[t,e.viewport.width,e.viewport.height]);let n=new zw(this.rpc,t,()=>{let e=this.openPages.indexOf(n);e!==-1&&this.openPages.splice(e,1)});return this.openPages.push(n),n}async newContext(e){let t=new Bw(this.rpc);return this.openContexts.push(t),t}contexts(){return[...this.openContexts]}async close(){let e=this.openPages.splice(0,this.openPages.length);for(let t of e)await t.close();let t=this.openContexts.splice(0,this.openContexts.length);for(let e of t)await e.close()}};function Hw(e){let t=async t=>new Vw(e),n=async(t,n)=>new Vw(e);return{chromium:{launch:t,connect:n,connectOverCDP:n},firefox:{launch:t,connect:n},webkit:{launch:t,connect:n}}}const Uw=new Set([`bcrypt`,`better-sqlite3`,`canvas`,`cpu-features`,`fsevents`,`leveldown`,`libxmljs`,`libxmljs2`,`node-gyp-build`,`node-sass`,`puppeteer`,`robotjs`,`sass-embedded`,`sharp`,`snappy`,`sqlite3`,`tree-sitter`,`usb`]),Ww={sharp:` Use the built-in 'convert' shell command for image work.`,canvas:` Use the built-in 'convert' / OffscreenCanvas for image work.`,"better-sqlite3":` Use the built-in 'sqlite3' shell command (sql.js WASM).`,sqlite3:` Use the built-in 'sqlite3' shell command (sql.js WASM).`,bcrypt:` Use crypto.subtle.digest() with PBKDF2 / Argon2 in pure JS.`,puppeteer:` Use the built-in browser-automation shell commands.`};function Gw(e,t){let n=Ww[t]??``;return Error(`require('${e}'): '${t}' is a Node native module (C++ bindings) — it cannot run in the browser sandbox.${n}`)}function Kw(e){if(!e)return``;let t=e.lastIndexOf(`/`);return t<0?``:t===0?`/`:e.substring(0,t)}function qw(e){return/^[A-Za-z0-9_\-./:@]+$/.test(e)?e:`'`+e.replace(/'/g,`'\\''`)+`'`}function Jw(e,t){return e===``?t:e===`/`?`/${t}`:`${e}/${t}`}function Yw(e){let t=Kw(e.argv[1]??``),n=Jw(t,`references`),r=Jw(t,`assets`),i=Jw(t,`.config`);async function a(){let t;try{t=await e.fs.exists(i)}catch{return null}if(!t)return null;let n;try{n=await e.fs.readFile(i)}catch{return null}let r=typeof n==`string`?n:String(n);if(!r.trim())return null;let a;try{a=JSON.parse(r)}catch(e){let t=e instanceof Error?e.message:String(e);throw Error(`skill.config(): failed to parse ${i}: ${t}`)}if(a&&typeof a==`object`&&!Array.isArray(a))return a;throw Error(`skill.config(): ${i} must contain a JSON object`)}async function o(t){let n=await a();if(t===void 0)return n;if(typeof t!=`object`||!t||Array.isArray(t))throw TypeError(`skill.config(updates): updates must be a plain object`);let r={...n??{},...t};return await e.fs.writeFile(i,JSON.stringify(r,null,2)+`
|
|
4854
|
-
`),r}async function s(t){if(typeof t!=`string`||!t.trim())throw TypeError(`skill.token(providerId): providerId must be a non-empty string`);let n=`oauth-token ${qw(t)}`,{stdout:r,stderr:i,exitCode:a}=await e.exec(n);if(a!==0){let e=i.trim()||`oauth-token exited with code ${a}`;throw Error(`skill.token('${t}'): ${e}`)}return r.replace(/\r?\n+$/,``)}return Object.freeze({dir:t,refs:n,assets:r,config:o,token:s})}function Xw(e){if(!e||e===`/`)return`/`;e.startsWith(`/`)||(e=`/`+e);let t=e.split(`/`),n=[];for(let e of t)e===``||e===`.`||(e===`..`?n.pop():n.push(e));return`/`+n.join(`/`)}function Zw(e){let t=Xw(e);if(t===`/`)return`/`;let n=t.lastIndexOf(`/`);return n===0?`/`:t.slice(0,n)}function Qw(e){return Object.assign(Error(`ENOENT: no such file or directory, '${e}'`),{code:`ENOENT`})}function $w(e){return Object.assign(Error(`ENOSYNC: file too large for sync access, '${e}' — use async readFile() instead`),{code:`ENOSYNC`})}function eT(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}var tT=class{tree=new Map;initialPaths=new Set;initialContent=new Map;initialIsDirectory=new Map;mkdtempCounter=0;tombstones=new Set;removedDirs=new Set;touched=!1;constructor(e){this.loadSnapshot(e)}loadSnapshot(e){this.tree=new Map,this.tombstones=new Set,this.removedDirs=new Set,this.initialPaths=new Set,this.initialContent=new Map,this.initialIsDirectory=new Map,this.tree.set(`/`,{content:new Uint8Array,isDirectory:!0}),this.initialPaths.add(`/`),this.initialIsDirectory.set(`/`,!0);for(let t of e.entries){let e=Xw(t.path);this.tree.set(e,{content:t.content,isDirectory:t.isDirectory,truncated:t.truncated,size:t.size}),this.initialPaths.add(e),this.initialIsDirectory.set(e,t.isDirectory),t.isDirectory||this.initialContent.set(e,t.content)}for(let t of e.entries){let e=Zw(Xw(t.path));for(;e!==`/`&&!this.tree.has(e);)this.tree.set(e,{content:new Uint8Array,isDirectory:!0}),this.initialPaths.add(e),this.initialIsDirectory.set(e,!0),e=Zw(e)}}wasUsed(){return this.touched}applySnapshot(e){this.loadSnapshot(e)}applySnapshotPreservingMutations(e){let t=this.getMutations();this.loadSnapshot(e);for(let e of t.deleted){if(this.tree.get(e)?.isDirectory){let t=e===`/`?`/`:e+`/`;for(let n of Array.from(this.tree.keys()))n!==e&&n.startsWith(t)&&this.tree.delete(n)}this.tree.delete(e)}for(let e of t.created)this.ensureParentDirs(e.path),this.tree.set(e.path,{content:e.content,isDirectory:e.isDirectory});for(let e of t.modified)this.ensureParentDirs(e.path),this.tree.set(e.path,{content:e.content,isDirectory:!1})}resetBaseline(){this.initialPaths=new Set,this.initialContent=new Map,this.initialIsDirectory=new Map;for(let[e,t]of this.tree.entries())this.initialPaths.add(e),this.initialIsDirectory.set(e,t.isDirectory),t.isDirectory||this.initialContent.set(e,t.content)}ensureParentDirs(e){let t=Zw(e);t!==`/`&&(this.tree.has(t)||this.mkdir(t,!0))}commitWrite(e,t){this.writeFile(e,t);let n=Xw(e);for(this.initialContent.set(n,t);n!==`/`;){let e=this.tree.get(n);e&&(this.initialPaths.add(n),this.initialIsDirectory.set(n,e.isDirectory)),n=Zw(n)}}readFile(e){this.touched=!0;let t=Xw(e),n=this.tree.get(t);if(!n||n.isDirectory)throw Qw(t);if(n.truncated)throw $w(t);return n.content}writeFile(e,t){this.touched=!0;let n=Xw(e);this.ensureParentDirs(n),this.tree.set(n,{content:t,isDirectory:!1}),this.tombstones.delete(n),this.removedDirs.delete(n)}exists(e){this.touched=!0;let t=Xw(e);return this.tree.has(t)}stat(e){this.touched=!0;let t=Xw(e),n=this.tree.get(t);if(!n)throw Qw(t);return{isFile:!n.isDirectory,isDirectory:n.isDirectory,size:n.isDirectory?0:n.size??n.content.byteLength}}readdir(e){this.touched=!0;let t=Xw(e);if(!this.tree.get(t)?.isDirectory)throw Qw(t);let n=t===`/`?`/`:t+`/`,r=new Set;for(let e of this.tree.keys()){if(e===t||e===`/`||!e.startsWith(n))continue;let i=e.slice(n.length).split(`/`)[0];i&&r.add(i)}return Array.from(r)}mkdir(e,t){this.touched=!0;let n=Xw(e);if(this.tree.has(n)){if(this.tree.get(n).isDirectory)return;throw Object.assign(Error(`EEXIST: file already exists, '${n}'`),{code:`EEXIST`})}let r=Zw(n);if(r!==`/`&&!this.tree.has(r)){if(!t)throw Qw(n);this.mkdir(r,!0)}this.tree.set(n,{content:new Uint8Array,isDirectory:!0}),this.tombstones.delete(n),this.removedDirs.delete(n)}rm(e,t){this.touched=!0;let n=Xw(e),r=this.tree.get(n);if(!r)throw Qw(n);if(r.isDirectory){let e=n===`/`?`/`:n+`/`,r=Array.from(this.tree.keys()).filter(t=>t!==n&&t.startsWith(e));if(r.length>0&&!t)throw Object.assign(Error(`ENOTEMPTY: directory not empty, '${n}'`),{code:`ENOTEMPTY`});for(let e of r)this.tree.delete(e),this.tombstones.add(e);t&&this.removedDirs.add(n)}this.tree.delete(n),this.tombstones.add(n)}copyFile(e,t){this.touched=!0;let n=Xw(e),r=this.tree.get(n);if(!r||r.isDirectory)throw Qw(n);if(r.truncated)throw $w(n);let i=Xw(t);this.ensureParentDirs(i),this.tree.set(i,{content:r.content.slice(),isDirectory:!1}),this.tombstones.delete(i),this.removedDirs.delete(i)}rename(e,t){this.touched=!0;let n=Xw(e),r=this.tree.get(n);if(!r)throw Qw(n);let i=Xw(t);if(r.isDirectory){let e=n===`/`?`/`:n+`/`,t=Array.from(this.tree.keys()).filter(t=>t!==n&&t.startsWith(e));this.ensureParentDirs(i),this.tree.set(i,r),this.tree.delete(n);for(let e of t){let t=this.tree.get(e),r=i+e.slice(n.length);this.tree.set(r,t),this.tree.delete(e)}this.tombstones.add(n),this.removedDirs.add(n),this.tombstones.delete(i),this.removedDirs.delete(i);return}this.ensureParentDirs(i),this.tree.set(i,r),this.tree.delete(n),this.tombstones.add(n),this.tombstones.delete(i),this.removedDirs.delete(i)}unlink(e){this.touched=!0;let t=Xw(e),n=this.tree.get(t);if(!n)throw Qw(t);if(n.isDirectory)throw Object.assign(Error(`EISDIR: illegal operation on a directory, unlink '${t}'`),{code:`EISDIR`});this.tree.delete(t),this.tombstones.add(t)}isTombstoned(e){let t=Xw(e);if(this.tombstones.has(t))return!0;for(let e of this.removedDirs)if(t===e||t.startsWith(`${e}/`))return!0;return!1}mkdtemp(e){this.touched=!0;for(let t=0;t<100;t++){let t=`_${String(this.mkdtempCounter).padStart(6,`0`)}`;this.mkdtempCounter++;let n=Xw(e+t);if(!this.tree.has(n))return this.mkdir(n,!0),n}throw Error(`mkdtemp: failed to create unique directory after 100 attempts`)}getMutations(){let e=[],t=[],n=[];for(let[r,i]of this.tree.entries()){if(r===`/`)continue;if(!this.initialPaths.has(r)){e.push({path:r,content:i.content,isDirectory:i.isDirectory});continue}let a=this.initialIsDirectory.get(r);if(a!==void 0&&a!==i.isDirectory){n.push(r),e.push({path:r,content:i.content,isDirectory:i.isDirectory});continue}if(!i.isDirectory){let e=this.initialContent.get(r);e&&!eT(e,i.content)&&t.push({path:r,content:i.content})}}for(let e of this.initialPaths)e!==`/`&&(this.tree.has(e)||n.push(e));return{created:e,modified:t,deleted:n}}};function nT(e){return`slicc-sync-fs-`+e}const rT=`sync-fs-ack`,iT=`sync-fs-res`;function aT(e,t){return Object.assign(Error(`${e}: sync-fs bridge, '${t}'`),{code:e})}function oT(e,t){let n=`/__slicc/fs-sync`+(e.startsWith(`/`)?e:`/${e}`).split(`/`).map(encodeURIComponent).join(`/`);return t?`${n}?op=${t}`:n}function sT(e,t={}){let n=t.timeoutMs??3e4;function r(t,r,i,a){let o=new XMLHttpRequest;try{o.open(t,oT(r,a),!1),o.responseType=`arraybuffer`,o.timeout=n,o.setRequestHeader(`x-slicc-fs-token`,e),i?o.send(new Uint8Array(i)):o.send()}catch{throw aT(`EIO`,r)}return o}function i(e,t){try{let t=new Uint8Array(e.response);return JSON.parse(new TextDecoder().decode(t))}catch{throw aT(`EIO`,t)}}function a(e,t){throw aT(e.getResponseHeader(`x-slicc-fs`)===`1`&&e.getResponseHeader(`x-slicc-fs-errno`)||`EIO`,t)}function o(e){return e.status>=200&&e.status<300&&e.getResponseHeader(`x-slicc-fs`)===`1`}return{readFile(e){let t=r(`GET`,e);if(o(t))return new Uint8Array(t.response);if(t.status>=200&&t.status<300)throw aT(`EIO`,e);a(t,e)},writeFile(e,t){let n=r(`POST`,e,t);if(!o(n)){if(n.status>=200&&n.status<300)throw aT(`EIO`,e);a(n,e)}},stat(e){let t=r(`GET`,e,void 0,`stat`);if(o(t)){let n=i(t,e);if(!n||typeof n.isFile!=`boolean`||typeof n.isDirectory!=`boolean`||typeof n.size!=`number`)throw aT(`EIO`,e);return{isFile:n.isFile,isDirectory:n.isDirectory,size:n.size}}if(t.status>=200&&t.status<300)throw aT(`EIO`,e);a(t,e)},readdir(e){let t=r(`GET`,e,void 0,`readdir`);if(o(t)){let n=i(t,e);if(!Array.isArray(n)||!n.every(e=>typeof e==`string`))throw aT(`EIO`,e);return n}if(t.status>=200&&t.status<300)throw aT(`EIO`,e);a(t,e)},exists(e){let t=r(`GET`,e,void 0,`exists`);if(o(t)){let n=i(t,e);if(typeof n!=`boolean`)throw aT(`EIO`,e);return n}if(t.status>=200&&t.status<300)throw aT(`EIO`,e);a(t,e)}}}function cT(e){if(!e)return``;let t=e.lastIndexOf(`/`);return t<0?``:t===0?`/`:e.substring(0,t)}var lT=class extends Error{code;constructor(e){super(`Process exited with code ${e}`),this.code=e,this.name=`NodeExitError`}};function uT(e){if(typeof e==`string`)return e;if(e==null)return String(e);try{return JSON.stringify(e)}catch{return String(e)}}async function dT(e,t,n){let r;try{r=await e.call(`vfs`,`snapshot`,[t])}catch(e){n?.(e instanceof Error?e.message:String(e)),r={entries:[]}}return new tT(r)}function fT(e,t){if(e.syncFsToken)return e=>t(`[sync-fs] snapshot failed, sync metadata will be incomplete: ${e}\n`)}function pT(e){return e.syncFsToken?sT(e.syncFsToken):void 0}function mT(e){return{usbBridge:oE(e),serialBridge:cE(e),hidBridge:uE(e)}}async function hT(e,t){let n=[],r=[],i=e=>{n.push(typeof e==`string`?e:String(e))},a=e=>{r.push(typeof e==`string`?e:String(e))},o=vT(i,a),{processShim:s,getDidCallProcessExit:c}=yT(e,i,a),l=!!e.env?.NO_COLOR,u=tC({isTTY:!l,noColor:l}),d=$S({writeStdout:i,writeStderr:a,exit:e=>{throw new lT(e)},color:u}),f=new yv(t),p=DT(f,C),m=await dT(f,e.cwd,fT(e,a));Object.assign(p,AT(m,e.cwd,pT(e)));let h=xT(f,m,e.cwd,a),g=wT(h,{cwd:e.cwd}),_=Yw({argv:e.argv,fs:p,exec:h}),v=WT(f),{usbBridge:y,serialBridge:b,hidBridge:x}=mT(f),S=fy({fetch:C});async function C(e,t){let n=e instanceof Request?e.url:e instanceof URL?e.toString():String(e),r=await f.call(`fetch`,`request`,[n,UT(t,e)]),i=r.body.byteLength===0?null:r.body.buffer.slice(r.body.byteOffset,r.body.byteOffset+r.body.byteLength),a=new Response(i,{status:r.status,statusText:r.statusText,headers:r.headers});return Object.defineProperty(a,"url",{value:r.url||n}),a}let w=TT({exec:h,agent:g,skill:_,http:S,browser:v,usb:y,serial:b,hid:x,cli:d,color:u}),T=e.filename,E=cT(T),D=await NT(f,e.code,e.cwd,T),O=IT({graph:D,fsBridge:p,processShim:s,childProcess:Iw(h),nodeConsole:o,sliccyModules:w,shimmedPackages:FT(f)}).require,k={exports:{},filename:e.filename},A=D.entrySource!==void 0,j=D.entrySource??e.code,M=globalThis;M.__slicc_compileWasm=e=>f.call(`wasm`,`compile`,[e]);let N=await HT(j,{process:s,console:o,require:O,module:k,exports:k.exports,fetch:C,__dirname:E,__filename:T},a,A);await gT(f,m,a),c()||await _T(f),delete M.__slicc_compileWasm,f.dispose(),t.postMessage({type:`realm-done`,stdout:n.join(``),stderr:r.join(``),exitCode:N})}async function gT(e,t,n){let r=t.getMutations();if(r.created.length||r.modified.length||r.deleted.length)try{await e.call(`vfs`,`flushWrites`,[r])}catch(e){let t=e instanceof Error?e.message:String(e);n(`[sync-fs] ERROR: flush failed — ${r.created.length+r.modified.length} write(s) + ${r.deleted.length} delete(s) were NOT persisted: ${t}\n`)}}async function _T(e){let t=Date.now()+1e3,n=0;do await new Promise(e=>setTimeout(e,0)),n++;while(e.pendingCount>0&&n<50&&Date.now()<t)}function vT(e,t){return{log:(...t)=>e(`${t.map(uT).join(` `)}
|
|
4855
|
-
`),
|
|
4856
|
-
`),
|
|
4857
|
-
`),
|
|
4858
|
-
`)}}function yT(e,t,n){let r=!!e.env?.NO_COLOR,i=ET(e.stdin??``),a=QS(e.argv),o=!1;return{processShim:{argv:a,env:e.env,cwd:()=>e.cwd,exit:e=>{throw o=!0,new lT(Number.isFinite(e)?Number(e):0)},stdin:i,stdout:{write:t,isTTY:!r},stderr:{write:n,isTTY:!r}},getDidCallProcessExit:()=>o}}function bT(e){return e===`SIGKILL`?137:e===`SIGINT`?130:143}function xT(e,t,n,r){let i=async()=>{if(!t?.wasUsed())return;let n=t.getMutations();(n.created.length||n.modified.length||n.deleted.length)&&await e.call(`vfs`,`flushWrites`,[n]),t.resetBaseline()},a=async(i=!1)=>{if(t?.wasUsed())try{let r=await e.call(`vfs`,`snapshot`,[n]);i?t.applySnapshotPreservingMutations(r):t.applySnapshot(r)}catch(e){let t=e instanceof Error?e.message:String(e);r?.(`[sync-fs] re-snapshot after exec failed: ${t}\n`)}},o=async t=>{await i();try{return await e.call(`exec`,`run`,[t])}finally{await a()}},s=async t=>{await i();try{return await e.call(`exec`,`spawn`,[t])}finally{await a()}},c=1,l=Object.assign(o,{spawn:s,start:(t,n)=>{let r=c++,o=[],s=!1,l=!1,u=!1,d,f,p=new Promise((e,t)=>{d=e,f=t}),m=()=>{if(s||u||l)return;l=!0;let c=o.length>0?o.join(``):n?.stdin,p={};c!==void 0&&(p.stdin=c),n?.stdinKind!==void 0&&(p.stdinKind=n.stdinKind),n?.args!==void 0&&(p.args=n.args),(async()=>{try{if(await i(),u){await a(!0);return}s=!0;let n=await e.call(`exec`,`start`,[r,t,p]);await a(!0),d(n)}catch(e){await a(!0),f(e)}})()};return{kill:t=>s?e.call(`exec`,`kill`,[r,t]):(u=!0,d({stdout:``,stderr:``,exitCode:bT(t)}),Promise.resolve(!0)),stdin:{write:e=>{!s&&!u&&o.push(e)},end:()=>m()},done:p}}});return l.exec=l,l}function ST(e){let t=new TextEncoder().encode(e),n=``;for(let e=0;e<t.length;e++)n+=String.fromCharCode(t[e]);return btoa(n)}function CT(e,t,n){let r=[];t.model&&r.push(`--model`,String(t.model)),t.thinking&&r.push(`--thinking`,String(t.thinking)),t.schema&&r.push(`--schema-b64`,ST(JSON.stringify(t.schema)));let i=t.readOnly===void 0?`/workspace/`:Array.isArray(t.readOnly)?t.readOnly.join(`,`):String(t.readOnly),a=t.cwd===void 0?n||`.`:String(t.cwd),o=t.allowedCommands===void 0?`*`:String(t.allowedCommands);return[`agent`,...r,`--read-only`,i,a,o,String(e)]}function wT(e,t){let n=t.cwd,r=async(t,r)=>{let i=r??{},a=await e.spawn(CT(t,i,n)),o=typeof a.exitCode==`number`?a.exitCode:0;return{finalText:String(a.stdout??``).replace(/\n+$/,``),exitCode:o,stderr:String(a.stderr??``).replace(/\n+$/,``)}},i=(async(e,t)=>{let n=t??{},i=await r(e,n);if(i.exitCode!==0)throw Error(`agent: exited with code ${i.exitCode}${i.stderr?`: ${i.stderr}`:``}`);if(n.schema)try{return JSON.parse(i.finalText)}catch{throw Error(`agent: schema response was not valid JSON (exit ${i.exitCode}): ${i.finalText.slice(0,200)}`)}return i.finalText});return i.spawn=r,i}function TT(e){return{...e,time:aC,fmt:mC,pool:hC}}function ET(e){let t=!1;return{isTTY:!1,read(){return t?null:(t=!0,e)},toString(){return e},[Symbol.asyncIterator](){return{async next(){return t?{value:void 0,done:!0}:(t=!0,{value:e,done:!1})}}}}}function DT(e,t){function n(e){if(e instanceof Uint8Array)return e;if(ArrayBuffer.isView(e)){let t=e;return new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}return e instanceof ArrayBuffer?new Uint8Array(e):new TextEncoder().encode(typeof e==`string`?e:String(e))}async function r(t,n){let r=typeof n==`string`?n:n?.encoding;if(r===null||r===`buffer`){let n=await e.call(`vfs`,`readFileBinary`,[t]),r=globalThis.Buffer;return r?r.from(n instanceof Uint8Array?n:new Uint8Array(n)):n}return e.call(`vfs`,`readFile`,[t])}async function i(t,r){return typeof r==`string`?e.call(`vfs`,`writeFile`,[t,r]):e.call(`vfs`,`writeFileBinary`,[t,n(r)])}async function a(t,r){let i=new Uint8Array;if(await e.call(`vfs`,`exists`,[t])){let n=await e.call(`vfs`,`readFileBinary`,[t]);i=n instanceof Uint8Array?n:new Uint8Array(n)}let a=n(r),o=new Uint8Array(i.byteLength+a.byteLength);o.set(i),o.set(a,i.byteLength),await e.call(`vfs`,`writeFileBinary`,[t,o])}async function o(t,n,r){let i=await e.call(`vfs`,`stat`,[t]);if(i.isFile){let r=await e.call(`vfs`,`readFileBinary`,[t]);await e.call(`vfs`,`writeFileBinary`,[n,r]);return}if(!i.isDirectory||!r?.recursive)throw Error(`cp: '${t}' is a directory (use {recursive: true})`);await c(n);let a=await e.call(`vfs`,`readDir`,[t]);for(let e of a)await o(`${t}/${e}`,`${n}/${e}`,r)}async function s(t,n){if(n?.force&&!await e.call(`vfs`,`exists`,[t]))return!0;if((await e.call(`vfs`,`stat`,[t])).isFile)return e.call(`vfs`,`rm`,[t]);if(!n?.recursive)throw Error(`rm: '${t}' is a directory (use {recursive: true})`);let r=await e.call(`vfs`,`readDir`,[t]);for(let e of r)await s(`${t}/${e}`,n);return e.call(`vfs`,`rm`,[t])}async function c(t){await e.call(`vfs`,`mkdir`,[t])}async function l(t){for(let n=0;n<5;n++){let n=`${t}${Math.random().toString(36).slice(2,10)+Math.random().toString(36).slice(2,6)}`;if(!await e.call(`vfs`,`exists`,[n]))return await e.call(`vfs`,`mkdir`,[n]),n}throw Error(`mkdtemp: failed to create unique directory after 5 attempts`)}async function u(t,n){try{await e.call(`vfs`,`rename`,[t,n])}catch{let r=await e.call(`vfs`,`readFileBinary`,[t]);await e.call(`vfs`,`writeFileBinary`,[n,r]),await e.call(`vfs`,`rm`,[t])}}async function d(t){if(!await e.call(`vfs`,`exists`,[t]))throw Object.assign(Error(`ENOENT: no such file or directory, access '${t}'`),{code:`ENOENT`})}let f={readFile:r,readFileBinary:t=>e.call(`vfs`,`readFileBinary`,[t]),writeFile:i,writeFileBinary:(t,n)=>e.call(`vfs`,`writeFileBinary`,[t,n]),appendFile:a,cp:o,rm:s,readDir:t=>e.call(`vfs`,`readDir`,[t]),readdir:t=>e.call(`vfs`,`readDir`,[t]),exists:t=>e.call(`vfs`,`exists`,[t]),stat:t=>e.call(`vfs`,`stat`,[t]),mkdir:(t,n)=>e.call(`vfs`,`mkdir`,[t]),mkdtemp:l,rename:u,access:d,unlink:t=>e.call(`vfs`,`rm`,[t]),rmdir:t=>e.call(`vfs`,`rm`,[t]),copyFile:async(t,n)=>{let r=await e.call(`vfs`,`readFileBinary`,[t]);await e.call(`vfs`,`writeFileBinary`,[n,r])},fetchToFile:async(n,r)=>{let i=await t(n);if(!i.ok)throw Error(`fetch ${i.status} ${i.statusText}`);let a=new Uint8Array(await i.arrayBuffer());return await e.call(`vfs`,`writeFileBinary`,[r,a]),a.byteLength},promises:null};return f.promises=f,f}function OT(e,t,n=``){return Object.assign(Error(`${e}: sync-fs, ${n?`${n} `:``}'${t}'`),{code:e})}function kT(e){if(typeof e==`string`)return new TextEncoder().encode(e);if(e instanceof Uint8Array)return e;if(ArrayBuffer.isView(e)){let t=e;return new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}return new TextEncoder().encode(String(e))}function AT(e,t,n){function r(e){return Xw(e.startsWith(`/`)?e:t+(t.endsWith(`/`)?``:`/`)+e)}function i(t){try{return e.readFile(t)}catch(r){let i=r?.code;if(n&&!e.isTombstoned(t)&&(i===`ENOENT`||i===`ENOSYNC`))return n.readFile(t);throw r}}function a(t,r){n?(n.writeFile(t,r),e.commitWrite(t,r)):e.writeFile(t,r)}function o(t){if(e.exists(t))return!0;if(!n||e.isTombstoned(t))return!1;try{return n.exists(t)}catch{return!1}}function s(t){try{return e.stat(t)}catch(r){let i=r?.code;if(!n||e.isTombstoned(t)||i!==`ENOENT`)throw r;return n.stat(t)}}function c(t){try{return e.readdir(t)}catch(r){let i=r?.code;if(!n||e.isTombstoned(t)||i!==`ENOENT`)throw r;return n.readdir(t)}}let l=e=>({isFile:()=>e.isFile,isDirectory:()=>e.isDirectory,size:e.size}),u=(e,t)=>e===`/`?`/${t}`:`${e}/${t}`;function d(t,n){if(!s(t).isDirectory){a(n,i(t));return}e.mkdir(n,!0);for(let e of c(t))d(u(t,e),u(n,e))}return{readFileSync(e,t){let n=typeof t==`string`?t:t?.encoding,a=i(r(e));if(n===`utf8`||n===`utf-8`)return new TextDecoder().decode(a);let o=globalThis.Buffer;return o?o.from(a):a},writeFileSync(e,t){a(r(e),kT(t))},appendFileSync(e,t){let n=r(e),o=new Uint8Array;try{o=i(n)}catch(e){if(e?.code!==`ENOENT`)throw e}let s=kT(t),c=new Uint8Array(o.byteLength+s.byteLength);c.set(o),c.set(s,o.byteLength),a(n,c)},truncateSync(e,t=0){let n=r(e),o=i(n),s=new Uint8Array(t);s.set(o.subarray(0,Math.min(t,o.byteLength))),a(n,s)},existsSync(e){return o(r(e))},accessSync(e){let t=r(e);if(!o(t))throw OT(`ENOENT`,t,`access`)},mkdirSync(t,n){e.mkdir(r(t),n?.recursive)},statSync(e){return l(s(r(e)))},lstatSync(e){return l(s(r(e)))},realpathSync(e){let t=r(e);if(!o(t))throw OT(`ENOENT`,t,`realpath`);return t},readdirSync(e){return c(r(e))},rmSync(t,n){let i=r(t);n?.force&&!e.exists(i)||e.rm(i,n?.recursive)},rmdirSync(t,n){let i=r(t);if(o(i)&&!s(i).isDirectory)throw OT(`ENOTDIR`,i,`rmdir`);e.rm(i,n?.recursive)},copyFileSync(e,t){a(r(t),i(r(e)))},cpSync(e,t){d(r(e),r(t))},chmodSync(e){let t=r(e);if(!o(t))throw OT(`ENOENT`,t,`chmod`)},mkdtempSync(t){return e.mkdtemp(r(t))},unlinkSync(t){e.unlink(r(t))},renameSync(t,n){e.rename(r(t),r(n))}}}function jT(e,t){return e?.startsWith(`/`)?cT(e):t}function MT(e){return e.includes(`require`)||e.includes(`import`)}async function NT(e,t,n,r){return MT(t)?e.call(`module`,`buildGraph`,[t,jT(r,n),r]):{files:[],entryMap:{},edges:{},errors:{}}}function PT(e){if(typeof e!=`object`||!e)return;let t=e;if(t.__esModule&&!Object.prototype.hasOwnProperty.call(t,`default`)&&Object.isExtensible(t))try{Object.defineProperty(t,"default",{value:t,enumerable:!1,configurable:!0})}catch{}}function FT(e){return{playwright:Hw(e)}}function IT(e){let{graph:t,fsBridge:n,processShim:r,childProcess:i,nodeConsole:a,sliccyModules:o,shimmedPackages:s={}}=e,c=new Map(t.files.map(e=>[e.path,e.cjsSource])),l=new Map(t.files.map(e=>[e.path,e.kind])),u=new Map,d=e=>{if(typeof e==`string`&&e.startsWith(`sliccy:`))return{hit:!0,value:zT(e,o)};let t=e.startsWith(`node:`)?e.slice(5):e,a=LT(t,n,r,i);if(a.hit)return a;if(Uw.has(t))throw Gw(e,t);if(en.has(t))throw VT(e,t);return t in s?{hit:!0,value:s[t]}:{hit:!1}},f=(e,n)=>{let r=d(n);if(r.hit)return r.value;let i=e?.[n];if(i)return p(i);throw n in t.errors?Error(t.errors[n]):RT(n)};function p(e){let n=u.get(e);if(n)return n.exports;let i=c.get(e);if(i===void 0)throw Error(`Cannot find module '${e}'`);let o={exports:{}};u.set(e,o);let s=n=>f(t.edges[e],n),d=cT(e);return Function(`module`,`exports`,`require`,`__dirname`,`__filename`,`process`,`console`,`Buffer`,`global`,i)(o,o.exports,s,d,e,r,a,globalThis.Buffer,globalThis),l.get(e)===`cjs`&&PT(o.exports),o.exports}return{require:e=>f(t.entryMap,e)}}function LT(e,t,n,r){return e===`fs`||e===`fs/promises`?{hit:!0,value:t}:e===`path`?{hit:!0,value:EC}:e===`crypto`?{hit:!0,value:RC}:e===`child_process`?{hit:!0,value:r}:e===`process`?{hit:!0,value:n}:e===`buffer`?{hit:!0,value:{Buffer:globalThis.Buffer}}:e===`assert`?{hit:!0,value:XC}:e===`assert/strict`?{hit:!0,value:YC}:e===`util`?{hit:!0,value:fw}:e===`events`?{hit:!0,value:Cw}:e===`os`?{hit:!0,value:vw}:e===`stream`?{hit:!0,value:Ow}:e===`url`?{hit:!0,value:xw}:e===`zlib`?{hit:!0,value:_w}:{hit:!1}}function RT(e){if(e.startsWith(`.`)||e.startsWith(`/`)||e.startsWith(`node:`))return Error(`Cannot find module '${e}'`);let t=e.startsWith(`@`)?e.split(`/`).slice(0,2).join(`/`):e.split(`/`)[0];return Error(`Cannot find module '${e}' (run: ipk install ${t})`)}function zT(e,t){let n=e.slice(7);if(n===``)throw Error(`require('sliccy:'): empty sliccy: module name`);if(!Object.prototype.hasOwnProperty.call(t,n))throw Error(`require('${e}'): unknown sliccy: module '${n}'. Known names: ${Object.keys(t).sort().join(`, `)}`);return t[n]}const BT={http:` Use fetch() instead.`,https:` Use fetch() instead.`,crypto:` Use globalThis.crypto (Web Crypto API) instead.`};function VT(e,t){return Error(`require('${e}'): Node built-in '${t}' is not available in the browser environment.${BT[t]||``}`)}async function HT(e,t,n,r){let i=Object.keys(t),a=i.map(e=>t[e]),o=Object.getPrototypeOf(async function(){}).constructor,s=new o(...i,`${r?`"use strict";
|
|
4859
|
-
`:``}${e}`);try{return await s(...a),0}catch(e){return e instanceof lT?e.code:(n(`${e instanceof Error?e.stack??e.message:String(e)}\n`),1)}}function UT(e,t){if(!e&&!(t instanceof Request))return;let n=t instanceof Request?t:null,r=(e?.method??n?.method??`GET`).toUpperCase(),i={};if(e?.headers)if(e.headers instanceof Headers)e.headers.forEach((e,t)=>{i[t]=e});else if(Array.isArray(e.headers))for(let[t,n]of e.headers)i[t]=n;else Object.assign(i,e.headers);else n&&n.headers.forEach((e,t)=>{i[t]=e});let a;return e?.body!==void 0&&e?.body!==null&&e?.body!==``&&(a=typeof e.body==`string`?e.body:String(e.body)),{method:r,headers:i,body:a}}function WT(e){return{findTab:t=>e.call(`browser`,`findTab`,[$T(t)]),ensureTab:(t,n={})=>e.call(`browser`,`ensureTab`,[t,eE(n)]),eval:(t,n)=>e.call(`browser`,`eval`,[GT(t),KT(n,!1)]),evalAsync:(t,n)=>e.call(`browser`,`evalAsync`,[GT(t),KT(n,!0)]),cookie:(t,n)=>e.call(`browser`,`cookie`,[GT(t),n]),localStorage:(t,n)=>e.call(`browser`,`localStorage`,[GT(t),n]),fetch:(t,n,r={})=>QT(n,r).then(n=>e.call(`browser`,`evalAsync`,[GT(t),n])),websocket:tE(e)}}function GT(e){if(typeof e==`string`)return e;if(e&&typeof e==`object`&&typeof e.targetId==`string`)return e.targetId;throw TypeError(`browser: expected a tab handle or targetId string`)}function KT(e,t){if(typeof e==`function`)return`(${e.toString()})()`;if(typeof e==`string`)return e;throw TypeError(`browser.eval/evalAsync: source must be a function or string`)}function qT(e){let t=``,n=32768;for(let r=0;r<e.length;r+=n)t+=String.fromCharCode(...Array.from(e.subarray(r,r+n)));return btoa(t)}async function JT(e){let t=[];for(let[n,r]of e.entries()){if(typeof r==`string`){t.push({name:n,value:r});continue}let e=new Uint8Array(await r.arrayBuffer());t.push({name:n,file:{data:qT(e),filename:typeof r.name==`string`?r.name:`blob`,type:r.type||``}})}return{kind:`formdata`,entries:t}}async function YT(e,t){let n=()=>Object.keys(t).some(e=>e.toLowerCase()===`content-type`);return typeof e==`string`?{body:e}:e instanceof URLSearchParams?(n()||(t[`Content-Type`]=`application/x-www-form-urlencoded;charset=UTF-8`),{body:e.toString()}):e instanceof Blob?{descriptor:{kind:`blob`,data:qT(new Uint8Array(await e.arrayBuffer())),type:e.type||``}}:e instanceof ArrayBuffer?{descriptor:{kind:`bytes`,data:qT(new Uint8Array(e))}}:ArrayBuffer.isView(e)?{descriptor:{kind:`bytes`,data:qT(new Uint8Array(e.buffer,e.byteOffset,e.byteLength))}}:e instanceof FormData?{descriptor:await JT(e)}:(n()||(t[`Content-Type`]=`application/json`),{body:JSON.stringify(e)})}function XT(e){return e?`const __b64 = (s) => { const bin = atob(s); const n = bin.length; const u = new Uint8Array(n); for (let i = 0; i < n; i++) u[i] = bin.charCodeAt(i); return u; };const __body = `+JSON.stringify(e)+`;if (__body.kind === 'bytes') { __init.body = __b64(__body.data); }else if (__body.kind === 'blob') { __init.body = new Blob([__b64(__body.data)], { type: __body.type }); }else if (__body.kind === 'formdata') { const __fd = new FormData(); for (const e of __body.entries) { if (e.file) { __fd.append(e.name, new Blob([__b64(e.file.data)], { type: e.file.type }), e.file.filename); } else { __fd.append(e.name, e.value); } } __init.body = __fd; }`:``}function ZT(e){return`const h = {};r.headers.forEach((v, k) => { h[k] = v; });const ct = r.headers.get('content-type') || '';const __rt = `+JSON.stringify(e??null)+`;const __ctl = ct.toLowerCase();const __binPrefixes = ['image/','audio/','video/','application/octet-stream','application/pdf','application/protobuf','application/x-protobuf','application/wasm','application/zip'];const __isXml = __ctl.indexOf('+xml') !== -1 || __ctl.indexOf('application/xml') === 0 || __ctl.indexOf('text/xml') === 0;const __isBinary = __rt === 'binary' || (__rt !== 'text' && __rt !== 'json' && !__isXml && __binPrefixes.some((p) => __ctl.indexOf(p) === 0));if (__isBinary) {const __u = new Uint8Array(await r.arrayBuffer());let __s = ''; const __cs = 0x8000;for (let __i = 0; __i < __u.length; __i += __cs) { __s += String.fromCharCode.apply(null, __u.subarray(__i, __i + __cs)); }return { ok: r.ok, status: r.status, headers: h, body: btoa(__s), bodyEncoding: 'base64' };}const t = await r.text();let b;const __jsonWanted = __rt === 'json' || (__rt !== 'text' && ct.indexOf('application/json') !== -1);if (__jsonWanted) { if (!t) { b = null; } else { try { b = JSON.parse(t); } catch (e) { b = t; } } }else { b = t; }return { ok: r.ok, status: r.status, headers: h, body: b };`}async function QT(e,t={}){let n={},r=t.headers??{};for(let[e,t]of Object.entries(r))typeof t==`string`&&(n[e]=t);let i=typeof t.method==`string`?t.method:`GET`,a=t.credentials===`same-origin`||t.credentials===`omit`?t.credentials:`include`,o=t.body,{body:s,descriptor:c}=o==null?{}:await YT(o,n),l={method:i,credentials:a,headers:n};s!==void 0&&(l.body=s);for(let e of[`mode`,`cache`,`redirect`,`referrer`,`referrerPolicy`,`integrity`,`keepalive`]){let n=t[e];n!==void 0&&(l[e]=n)}let u=XT(c),d=ZT(t.responseType);return`(async () => {const __init = `+JSON.stringify(l)+`;`+u+`const r = await fetch(`+JSON.stringify(e)+`, __init);`+d+`})()`}function $T(e){let t={};return e.domain!==void 0&&(t.domain=e.domain),e.urlMatch!==void 0&&(t.urlMatch=e.urlMatch instanceof RegExp?e.urlMatch.source:e.urlMatch),t}function eE(e){return e.matchUrl===void 0?{}:{matchUrl:e.matchUrl instanceof RegExp?e.matchUrl.source:e.matchUrl}}function tE(e){function t(t){return{...t,async update(n){let r={};return n.urlMatch!==void 0&&(r.urlMatch=n.urlMatch===null?null:n.urlMatch instanceof RegExp?n.urlMatch.source:n.urlMatch),n.filter!==void 0&&(r.filter=n.filter),e.call(`browser`,`wsUpdate`,[t.id,r])},async close(){return e.call(`browser`,`wsClose`,[t.id])}}}return{on(n,r={}){let i=GT(n),a=r.urlMatch===void 0?void 0:r.urlMatch instanceof RegExp?r.urlMatch.source:r.urlMatch,o,s={filter(e){if(typeof e==`function`||typeof e==`string`)throw TypeError(`browser.websocket: filter must be a declarative JSON object, not a function or string`);return o=e,s},async forward(n){return t(await e.call(`browser`,`wsObserve`,[{targetId:i,urlMatch:a,filter:o,forward:n}]))}};return s},async list(){return e.call(`browser`,`wsList`,[])}}}function nE(e){if(e instanceof Uint8Array)return e;if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);if(e instanceof ArrayBuffer)return new Uint8Array(e);throw TypeError(`expected an ArrayBuffer or typed array`)}function rE(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function iE(e){return e==null?[]:Array.isArray(e)?e:[e]}function aE(e,t){let n=t.handle,r=e=>({status:e.status,data:rE(e.bytes)});return{...t,open:()=>e.call(`usb`,`open`,[n]),close:()=>e.call(`usb`,`close`,[n]),reset:()=>e.call(`usb`,`reset`,[n]),selectConfiguration:t=>e.call(`usb`,`selectConfig`,[n,t]),claimInterface:t=>e.call(`usb`,`claim`,[n,t]),releaseInterface:t=>e.call(`usb`,`release`,[n,t]),controlTransferIn:async(t,i)=>r(await e.call(`usb`,`controlIn`,[n,t,i])),controlTransferOut:(t,r)=>e.call(`usb`,`controlOut`,[n,t,nE(r)]),transferIn:async(t,i)=>r(await e.call(`usb`,`transferIn`,[n,t,i])),transferOut:(t,r)=>e.call(`usb`,`transferOut`,[n,t,nE(r)])}}function oE(e){return{list:async()=>(await e.call(`usb`,`list`,[])).map(t=>aE(e,t)),request:async t=>aE(e,await e.call(`usb`,`request`,[iE(t)]))}}function sE(e,t){let n=t.handle;return{...t,open:t=>e.call(`serial`,`open`,[n,t]),close:()=>e.call(`serial`,`close`,[n]),read:(t={})=>e.call(`serial`,`read`,[n,{maxBytes:t.maxBytes??t.bytes,until:t.until?nE(t.until):void 0,timeoutMs:t.timeoutMs}]),write:t=>e.call(`serial`,`write`,[n,nE(t)]),getSignals:()=>e.call(`serial`,`getSignals`,[n]),setSignals:t=>e.call(`serial`,`setSignals`,[n,t])}}function cE(e){return{list:async()=>(await e.call(`serial`,`list`,[])).map(t=>sE(e,t)),request:async t=>sE(e,await e.call(`serial`,`request`,[iE(t)]))}}function lE(e,t){let n=t.handle,r=new Set,i=new Set,a=!1,o=null,s=e=>{let t=e;if(!t||t.handle!==n)return;let i={reportId:t.reportId,data:rE(t.bytes)};for(let e of[...r])try{e(i)}catch{}},c=()=>{a||(a=!0,o=e.onEvent?e.onEvent(`hid-input-report`,s):null,e.call(`hid`,`subscribeInputReports`,[n]).catch(()=>{a=!1,o?.(),o=null}))},l=()=>{!a||r.size>0||(a=!1,o?.(),o=null,e.call(`hid`,`unsubscribeInputReports`,[n]).catch(()=>{}))};return{...t,open:()=>e.call(`hid`,`open`,[n]),close:()=>e.call(`hid`,`close`,[n]),sendReport:(t,r)=>e.call(`hid`,`sendReport`,[n,t,nE(r)]),sendFeatureReport:(t,r)=>e.call(`hid`,`sendFeatureReport`,[n,t,nE(r)]),receiveFeatureReport:async t=>rE((await e.call(`hid`,`receiveFeatureReport`,[n,t])).bytes),addEventListener(e,t){if(e===`inputreport`)r.add(t),c();else if(e===`disconnect`)i.add(t);else throw TypeError(`hid device: unknown event type '${String(e)}'`)},removeEventListener(e,t){e===`inputreport`?(r.delete(t),l()):e===`disconnect`&&i.delete(t)},onInputReport(e){r.add(e),c()}}}function uE(e){return{list:async()=>(await e.call(`hid`,`list`,[])).map(t=>lE(e,t)),request:async t=>{let n=(await e.call(`hid`,`request`,[iE(t)]))[0];if(!n)throw Error(`No device selected.`);return lE(e,n)}}}function dE(){let e=new Set,t=new Set;return{realmSide:{postMessage:e=>{queueMicrotask(()=>{for(let n of[...t])n({data:e})})},addEventListener:(t,n)=>{e.add(n)},removeEventListener:(t,n)=>{e.delete(n)}},hostSide:{postMessage:t=>{queueMicrotask(()=>{for(let n of[...e])n({data:t})})},addEventListener:(e,n)=>{t.add(n)},removeEventListener:(e,n)=>{t.delete(n)}}}}function fE(){return async({kind:e})=>{if(e!==`js`)throw Error(`createInProcessJsRealmFactory: only kind:js is supported`);let{realmSide:t,hostSide:n}=dE(),r=e=>{if(e.data?.type!==`realm-init`)return;t.removeEventListener(`message`,r);let n=e.data;n.kind===`js`&&hT(n,t).catch(e=>{let n={type:`realm-error`,message:e instanceof Error?e.message:String(e)};t.postMessage(n)})};return t.addEventListener(`message`,r),{controlPort:n,terminate(){t.removeEventListener(`message`,r)}}}}function pE(){return async({kind:e})=>{if(e!==`py`)throw Error(`createInProcessPyRealmFactory: only kind:py is supported`);let{realmSide:t,hostSide:n}=dE(),r=e=>{if(e.data?.type!==`realm-init`)return;t.removeEventListener(`message`,r);let n=e.data;n.kind===`py`&&Av(n,t).catch(e=>{let n={type:`realm-error`,message:e instanceof Error?e.message:String(e)};t.postMessage(n)})};return t.addEventListener(`message`,r),{controlPort:n,terminate(){t.removeEventListener(`message`,r)}}}}const mE=fE(),hE=pE();function gE(){return async({kind:e,ctx:t})=>e===`py`?typeof Worker<`u`?vE():hE({kind:e,ctx:t}):typeof Worker<`u`?_E():mE({kind:e,ctx:t})}function _E(){if(typeof Worker>`u`)throw Error(`realm-factory: Worker is not available in this runtime`);return yE(new Worker(new URL(`/assets/js-realm-worker-vnTP6x9C.js`,``+import.meta.url),{type:`module`}))}function vE(){if(typeof Worker>`u`)throw Error(`realm-factory: Worker is not available in this runtime`);return yE(new Worker(new URL(`/assets/py-realm-worker-VuYxvTG9.js`,``+import.meta.url),{type:`module`}))}function yE(e){let t={postMessage:(t,n)=>n?e.postMessage(t,n):e.postMessage(t),addEventListener:(t,n)=>e.addEventListener(t,n),removeEventListener:(t,n)=>e.removeEventListener(t,n)},n=!1;return{controlPort:t,addEventListener:(t,n,r)=>e.addEventListener(t,n,r),removeEventListener:(t,n)=>e.removeEventListener(t,n),terminate(){if(!n){n=!0;try{e.terminate()}catch{}}}}}function bE(){if(cn())return decodeURIComponent(un(`pyodide/pyodide.mjs`,`../../../../../node_modules/pyodide/`).pathname)}var xE=e(t(((e,t)=>{(e=>{var t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.prototype.hasOwnProperty,a=(e,n)=>{for(var r in n)t(e,r,{get:n[r],enumerable:!0})},o=(e,a,o,s)=>{if(a&&typeof a==`object`||typeof a==`function`)for(let c of r(a))!i.call(e,c)&&c!==o&&t(e,c,{get:()=>a[c],enumerable:!(s=n(a,c))||s.enumerable});return e},s=e=>o(t({},`__esModule`,{value:!0}),e),c=(e,t,n)=>new Promise((r,i)=>{var a=e=>{try{s(n.next(e))}catch(e){i(e)}},o=e=>{try{s(n.throw(e))}catch(e){i(e)}},s=e=>e.done?r(e.value):Promise.resolve(e.value).then(a,o);s((n=n.apply(e,t)).next())}),l={};a(l,{analyzeMetafile:()=>Oe,analyzeMetafileSync:()=>Me,build:()=>we,buildSync:()=>ke,context:()=>Te,default:()=>Be,formatMessages:()=>De,formatMessagesSync:()=>je,initialize:()=>Re,stop:()=>Ne,transform:()=>Ee,transformSync:()=>Ae,version:()=>Ce}),e.exports=s(l);function u(e){let t=e=>{if(e===null)n.write8(0);else if(typeof e==`boolean`)n.write8(1),n.write8(+e);else if(typeof e==`number`)n.write8(2),n.write32(e|0);else if(typeof e==`string`)n.write8(3),n.write(p(e));else if(e instanceof Uint8Array)n.write8(4),n.write(e);else if(e instanceof Array){n.write8(5),n.write32(e.length);for(let n of e)t(n)}else{let r=Object.keys(e);n.write8(6),n.write32(r.length);for(let i of r)n.write(p(i)),t(e[i])}},n=new f;return n.write32(0),n.write32(e.id<<1|!e.isRequest),t(e.value),_(n.buf,n.len-4,0),n.buf.subarray(0,n.len)}function d(e){let t=()=>{switch(n.read8()){case 0:return null;case 1:return!!n.read8();case 2:return n.read32();case 3:return m(n.read());case 4:return n.read();case 5:{let e=n.read32(),r=[];for(let n=0;n<e;n++)r.push(t());return r}case 6:{let e=n.read32(),r={};for(let i=0;i<e;i++)r[m(n.read())]=t();return r}default:throw Error(`Invalid packet`)}},n=new f(e),r=n.read32(),i=(r&1)==0;r>>>=1;let a=t();if(n.ptr!==e.length)throw Error(`Invalid packet`);return{id:r,isRequest:i,value:a}}var f=class{constructor(e=new Uint8Array(1024)){this.buf=e,this.len=0,this.ptr=0}_write(e){if(this.len+e>this.buf.length){let t=new Uint8Array((this.len+e)*2);t.set(this.buf),this.buf=t}return this.len+=e,this.len-e}write8(e){let t=this._write(1);this.buf[t]=e}write32(e){let t=this._write(4);_(this.buf,e,t)}write(e){let t=this._write(4+e.length);_(this.buf,e.length,t),this.buf.set(e,t+4)}_read(e){if(this.ptr+e>this.buf.length)throw Error(`Invalid packet`);return this.ptr+=e,this.ptr-e}read8(){return this.buf[this._read(1)]}read32(){return g(this.buf,this._read(4))}read(){let e=this.read32(),t=new Uint8Array(e),n=this._read(t.length);return t.set(this.buf.subarray(n,n+e)),t}},p,m,h;if(typeof TextEncoder<`u`&&typeof TextDecoder<`u`){let e=new TextEncoder,t=new TextDecoder;p=t=>e.encode(t),m=e=>t.decode(e),h=`new TextEncoder().encode("")`}else if(typeof Buffer<`u`)p=e=>Buffer.from(e),m=e=>{let{buffer:t,byteOffset:n,byteLength:r}=e;return Buffer.from(t,n,r).toString()},h=`Buffer.from("")`;else throw Error(`No UTF-8 codec found`);if(!(p(``)instanceof Uint8Array))throw Error(`Invariant violation: "${h} instanceof Uint8Array" is incorrectly false
|
|
4853
|
+
`,cpus:()=>[{model:`virtual`,speed:0}],hostname:()=>`slicc`,type:()=>`Linux`,release:()=>`0.0.0`};function yw(e){let t=typeof e==`string`?e:e.href;if(!t.startsWith(`file://`))throw TypeError(`fileURLToPath: not a file URL`);let n=t.slice(7);return decodeURIComponent(n)}function bw(e){let t=e.split(`/`).map(e=>encodeURIComponent(e)).join(`/`);return new URL(`file://${t}`)}const xw={URL:globalThis.URL,URLSearchParams:globalThis.URLSearchParams,fileURLToPath:yw,pathToFileURL:bw};var Sw=class{_events=new Map;on(e,t){let n=this._events.get(e);return n?n.push(t):this._events.set(e,[t]),this}addListener(e,t){return this.on(e,t)}off(e,t){let n=this._events.get(e);if(n){let r=n.indexOf(t);r!==-1&&n.splice(r,1),n.length===0&&this._events.delete(e)}return this}removeListener(e,t){return this.off(e,t)}once(e,t){let n=(...r)=>{this.off(e,n),t(...r)};return this.on(e,n)}emit(e,...t){let n=this._events.get(e);if(!n||n.length===0)return!1;for(let e of[...n])e(...t);return!0}removeAllListeners(e){return e===void 0?this._events.clear():this._events.delete(e),this}listenerCount(e){return this._events.get(e)?.length??0}listeners(e){return[...this._events.get(e)??[]]}};const Cw=Object.assign(Sw,{EventEmitter:Sw,default:Sw});var ww=class{_events=new Map;writable=!0;readable=!0;on(e,t){let n=this._events.get(e);return n?n.push(t):this._events.set(e,[t]),this}once(e,t){let n=(...r)=>{this.off(e,n),t(...r)};return this.on(e,n)}off(e,t){let n=this._events.get(e);if(n){let e=n.indexOf(t);e!==-1&&n.splice(e,1)}return this}emit(e,...t){let n=this._events.get(e);if(!n||n.length===0)return!1;for(let e of[...n])e(...t);return!0}pipe(e){return e}removeListener(e,t){return this.off(e,t)}removeAllListeners(){return this._events.clear(),this}},Tw=class extends ww{read(){return null}destroy(){return this}},Ew=class extends ww{write(e,t,n){return n&&queueMicrotask(n),!0}end(e){return e&&queueMicrotask(e),this}destroy(){return this}},Dw=class extends ww{write(e,t,n){return n&&queueMicrotask(n),!0}end(e){return e&&queueMicrotask(e),this}read(){return null}destroy(){return this}};const Ow={Readable:Tw,Writable:Ew,Transform:Dw,PassThrough:class extends Dw{},Stream:ww};let kw=1;function Aw(e){if(typeof e==`string`)return e;if(ArrayBuffer.isView(e)){let t=e;return new TextDecoder().decode(new Uint8Array(t.buffer,t.byteOffset,t.byteLength))}return e==null?``:String(e)}function jw(e,t){return t===void 0||t===`utf8`||t===`utf-8`?e:t===`buffer`||t===null?kC(e):kC(e).toString(t)}function Mw(e,t){if(e.length===0)return jw(``,t);if(typeof e[0]==`string`)return e.join(``);let n=globalThis.Buffer;return n?n.concat(e):e[0]}function Nw(e,t,n){t.length>0&&e.emit(`data`,jw(t,n)),e.readable=!1,e.emit(`end`)}function Pw(e){let t=e=>{typeof e==`function`&&queueMicrotask(e)};return{writable:!0,write(n,r,i){return e.stdin.write(Aw(n)),t(typeof r==`function`?r:i),!0},end(n,r,i){n!==void 0&&typeof n!=`function`&&e.stdin.write(Aw(n)),e.stdin.end(),this.writable=!1,t(typeof n==`function`?n:typeof r==`function`?r:i)}}}var Fw=class extends Sw{stdout;stderr;stdin;pid;exitCode=null;signalCode=null;killed=!1;spawnfile;spawnargs;handle;constructor(e,t,n,r){super(),this.handle=e,this.pid=kw++,this.spawnfile=n,this.spawnargs=r,this.stdout=new Tw,this.stderr=new Tw,this.stdin=Pw(e),e.done.then(e=>this.finish(e,t),e=>this.emit(`error`,e instanceof Error?e:Error(String(e))))}finish(e,t){Nw(this.stdout,e.stdout,t),Nw(this.stderr,e.stderr,t),this.exitCode=e.exitCode;let n=this.killed?null:e.exitCode,r=this.killed?this.signalCode:null;this.emit(`exit`,n,r),this.emit(`close`,n,r)}kill(e=`SIGTERM`){return this.killed=!0,this.signalCode=e,this.handle.kill(e).catch(()=>{}),!0}};function Iw(e){let t=(t,n,r,i,a)=>{let o=e.start(t),s=new Fw(o,r,i,a);return n.input!==void 0&&s.stdin.write(Aw(n.input)),queueMicrotask(()=>o.stdin.end()),s},n=(e,t,n,r)=>{if(typeof r!=`function`)return;let i=[],a=[];e.stdout.on(`data`,e=>i.push(e)),e.stderr.on(`data`,e=>a.push(e)),e.once(`error`,e=>r(e,Mw(i,t),Mw(a,t))),e.once(`close`,(o,s)=>{let c=Mw(i,t),l=Mw(a,t);if(o===0){r(null,c,l);return}r(Object.assign(Error(`Command failed: ${n}\n${Aw(l)}`),{code:o===null?void 0:o,killed:e.killed,signal:s??null,cmd:n}),c,l)})},r=(e,r,i)=>{let a=typeof r==`function`?r:i,o=r&&typeof r==`object`?r:{},s=o.encoding===void 0?`utf8`:o.encoding,c=t(e,o,s,e,[]);return n(c,s,e,a),c},i=(e,r,i,a)=>{let o=[],s={},c;Array.isArray(r)?(o=r,typeof i==`function`?c=i:(s=i??{},c=typeof a==`function`?a:void 0)):typeof r==`function`?c=r:r&&typeof r==`object`&&(s=r,c=typeof i==`function`?i:void 0);let l=s.encoding===void 0?`utf8`:s.encoding,u=[e,...o],d=t(u,s,l,e,o);return n(d,l,u.join(` `),c),d},a=(e,n,r)=>{let i=[],a={};Array.isArray(n)?(i=n,a=r??{}):n&&typeof n==`object`&&(a=n);let o=a.encoding===void 0?`buffer`:a.encoding,s=a.shell?`${e}${i.length?` ${i.join(` `)}`:``}`:[e,...i];return t(s,a,o,e,i)},o=(e,t)=>new Promise((n,i)=>{r(e,t,(e,t,r)=>{if(e){i(Object.assign(e,{stdout:t,stderr:r}));return}n({stdout:t,stderr:r})})}),s=(e,t,n)=>new Promise((r,a)=>{i(e,Array.isArray(t)?t:[],Array.isArray(t)?n:t,(e,t,n)=>{if(e){a(Object.assign(e,{stdout:t,stderr:n}));return}r({stdout:t,stderr:n})})}),c=e=>()=>{throw Error(`child_process.${e} is not available in the browser realm`)},l=(e,t)=>{Object.defineProperty(e,QC,{value:t,enumerable:!1,configurable:!0})};return l(r,o),l(i,s),{exec:r,execFile:i,spawn:a,execSync:c(`execSync`),spawnSync:c(`spawnSync`),execFileSync:c(`execFileSync`),fork:c(`fork`),ChildProcess:Fw}}function Lw(e){let t=new TextEncoder().encode(e),n=``;for(let e=0;e<t.length;e++)n+=String.fromCharCode(t[e]);return btoa(n)}function Rw(e,t,n){let r=[];t.model&&r.push(`--model`,String(t.model)),t.thinking&&r.push(`--thinking`,String(t.thinking)),t.schema&&r.push(`--schema-b64`,Lw(JSON.stringify(t.schema)));let i=t.readOnly===void 0?`/workspace/`:Array.isArray(t.readOnly)?t.readOnly.join(`,`):String(t.readOnly),a=t.cwd===void 0?n||`.`:String(t.cwd),o=t.allowedCommands===void 0?`*`:String(t.allowedCommands);return[`agent`,...r,`--read-only`,i,a,o,String(e)]}function zw(e,t){let n=t.cwd,r=async(t,r)=>{let i=r??{},a=await e.spawn(Rw(t,i,n)),o=typeof a.exitCode==`number`?a.exitCode:0;return{finalText:String(a.stdout??``).replace(/\n+$/,``),exitCode:o,stderr:String(a.stderr??``).replace(/\n+$/,``)}},i=(async(e,t)=>{let n=t??{},i=await r(e,n);if(i.exitCode!==0)throw Error(`agent: exited with code ${i.exitCode}${i.stderr?`: ${i.stderr}`:``}`);if(n.schema)try{return JSON.parse(i.finalText)}catch{throw Error(`agent: schema response was not valid JSON (exit ${i.exitCode}): ${i.finalText.slice(0,200)}`)}return i.finalText});return i.spawn=r,i}function Bw(e){let t=``,n=32768;for(let r=0;r<e.length;r+=n)t+=String.fromCharCode(...Array.from(e.subarray(r,r+n)));return btoa(t)}async function Vw(e){let t=[];for(let[n,r]of e.entries()){if(typeof r==`string`){t.push({name:n,value:r});continue}let e=new Uint8Array(await r.arrayBuffer());t.push({name:n,file:{data:Bw(e),filename:typeof r.name==`string`?r.name:`blob`,type:r.type||``}})}return{kind:`formdata`,entries:t}}async function Hw(e,t){let n=()=>Object.keys(t).some(e=>e.toLowerCase()===`content-type`);return typeof e==`string`?{body:e}:e instanceof URLSearchParams?(n()||(t[`Content-Type`]=`application/x-www-form-urlencoded;charset=UTF-8`),{body:e.toString()}):e instanceof Blob?{descriptor:{kind:`blob`,data:Bw(new Uint8Array(await e.arrayBuffer())),type:e.type||``}}:e instanceof ArrayBuffer?{descriptor:{kind:`bytes`,data:Bw(new Uint8Array(e))}}:ArrayBuffer.isView(e)?{descriptor:{kind:`bytes`,data:Bw(new Uint8Array(e.buffer,e.byteOffset,e.byteLength))}}:e instanceof FormData?{descriptor:await Vw(e)}:(n()||(t[`Content-Type`]=`application/json`),{body:JSON.stringify(e)})}function Uw(e){return e?`const __b64 = (s) => { const bin = atob(s); const n = bin.length; const u = new Uint8Array(n); for (let i = 0; i < n; i++) u[i] = bin.charCodeAt(i); return u; };const __body = `+JSON.stringify(e)+`;if (__body.kind === 'bytes') { __init.body = __b64(__body.data); }else if (__body.kind === 'blob') { __init.body = new Blob([__b64(__body.data)], { type: __body.type }); }else if (__body.kind === 'formdata') { const __fd = new FormData(); for (const e of __body.entries) { if (e.file) { __fd.append(e.name, new Blob([__b64(e.file.data)], { type: e.file.type }), e.file.filename); } else { __fd.append(e.name, e.value); } } __init.body = __fd; }`:``}function Ww(e){return`const h = {};r.headers.forEach((v, k) => { h[k] = v; });const ct = r.headers.get('content-type') || '';const __rt = `+JSON.stringify(e??null)+`;const __ctl = ct.toLowerCase();const __binPrefixes = ['image/','audio/','video/','application/octet-stream','application/pdf','application/protobuf','application/x-protobuf','application/wasm','application/zip'];const __isXml = __ctl.indexOf('+xml') !== -1 || __ctl.indexOf('application/xml') === 0 || __ctl.indexOf('text/xml') === 0;const __isBinary = __rt === 'binary' || (__rt !== 'text' && __rt !== 'json' && !__isXml && __binPrefixes.some((p) => __ctl.indexOf(p) === 0));if (__isBinary) {const __u = new Uint8Array(await r.arrayBuffer());let __s = ''; const __cs = 0x8000;for (let __i = 0; __i < __u.length; __i += __cs) { __s += String.fromCharCode.apply(null, __u.subarray(__i, __i + __cs)); }return { ok: r.ok, status: r.status, headers: h, body: btoa(__s), bodyEncoding: 'base64' };}const t = await r.text();let b;const __jsonWanted = __rt === 'json' || (__rt !== 'text' && ct.indexOf('application/json') !== -1);if (__jsonWanted) { if (!t) { b = null; } else { try { b = JSON.parse(t); } catch (e) { b = t; } } }else { b = t; }return { ok: r.ok, status: r.status, headers: h, body: b };`}async function Gw(e,t={}){let n={},r=t.headers??{};for(let[e,t]of Object.entries(r))typeof t==`string`&&(n[e]=t);let i=typeof t.method==`string`?t.method:`GET`,a=t.credentials===`same-origin`||t.credentials===`omit`?t.credentials:`include`,o=t.body,{body:s,descriptor:c}=o==null?{}:await Hw(o,n),l={method:i,credentials:a,headers:n};s!==void 0&&(l.body=s);for(let e of[`mode`,`cache`,`redirect`,`referrer`,`referrerPolicy`,`integrity`,`keepalive`]){let n=t[e];n!==void 0&&(l[e]=n)}let u=Uw(c),d=Ww(t.responseType);return`(async () => {const __init = `+JSON.stringify(l)+`;`+u+`const r = await fetch(`+JSON.stringify(e)+`, __init);`+d+`})()`}function Kw(e){if(typeof e==`string`)return e;if(e&&typeof e==`object`&&typeof e.targetId==`string`)return e.targetId;throw TypeError(`browser: expected a tab handle or targetId string`)}function qw(e){function t(t){return{...t,async update(n){let r={};return n.urlMatch!==void 0&&(r.urlMatch=n.urlMatch===null?null:n.urlMatch instanceof RegExp?n.urlMatch.source:n.urlMatch),n.filter!==void 0&&(r.filter=n.filter),e.call(`browser`,`wsUpdate`,[t.id,r])},async close(){return e.call(`browser`,`wsClose`,[t.id])}}}return{on(n,r={}){let i=Kw(n),a=r.urlMatch===void 0?void 0:r.urlMatch instanceof RegExp?r.urlMatch.source:r.urlMatch,o,s={filter(e){if(typeof e==`function`||typeof e==`string`)throw TypeError(`browser.websocket: filter must be a declarative JSON object, not a function or string`);return o=e,s},async forward(n){return t(await e.call(`browser`,`wsObserve`,[{targetId:i,urlMatch:a,filter:o,forward:n}]))}};return s},async list(){return e.call(`browser`,`wsList`,[])}}}function Jw(e,t){if(!e&&!(t instanceof Request))return;let n=t instanceof Request?t:null,r=(e?.method??n?.method??`GET`).toUpperCase(),i={};if(e?.headers)if(e.headers instanceof Headers)e.headers.forEach((e,t)=>{i[t]=e});else if(Array.isArray(e.headers))for(let[t,n]of e.headers)i[t]=n;else Object.assign(i,e.headers);else n&&n.headers.forEach((e,t)=>{i[t]=e});let a;return e?.body!==void 0&&e?.body!==null&&e?.body!==``&&(a=typeof e.body==`string`?e.body:String(e.body)),{method:r,headers:i,body:a}}function Yw(e){return{findTab:t=>e.call(`browser`,`findTab`,[Zw(t)]),ensureTab:(t,n={})=>e.call(`browser`,`ensureTab`,[t,Qw(n)]),eval:(t,n)=>e.call(`browser`,`eval`,[Kw(t),Xw(n,!1)]),evalAsync:(t,n)=>e.call(`browser`,`evalAsync`,[Kw(t),Xw(n,!0)]),cookie:(t,n)=>e.call(`browser`,`cookie`,[Kw(t),n]),localStorage:(t,n)=>e.call(`browser`,`localStorage`,[Kw(t),n]),fetch:(t,n,r={})=>Gw(n,r).then(n=>e.call(`browser`,`evalAsync`,[Kw(t),n])),websocket:qw(e)}}function Xw(e,t){if(typeof e==`function`)return`(${e.toString()})()`;if(typeof e==`string`)return e;throw TypeError(`browser.eval/evalAsync: source must be a function or string`)}function Zw(e){let t={};return e.domain!==void 0&&(t.domain=e.domain),e.urlMatch!==void 0&&(t.urlMatch=e.urlMatch instanceof RegExp?e.urlMatch.source:e.urlMatch),t}function Qw(e){return e.matchUrl===void 0?{}:{matchUrl:e.matchUrl instanceof RegExp?e.matchUrl.source:e.matchUrl}}function $w(e){return e===`SIGKILL`?137:e===`SIGINT`?130:143}function eT(e,t,n,r){let i=async()=>{if(!t?.wasUsed())return;let n=t.getMutations();(n.created.length||n.modified.length||n.deleted.length)&&await e.call(`vfs`,`flushWrites`,[n]),t.resetBaseline()},a=async(i=!1)=>{if(t?.wasUsed())try{let r=await e.call(`vfs`,`snapshot`,[n]);i?t.applySnapshotPreservingMutations(r):t.applySnapshot(r)}catch(e){let t=e instanceof Error?e.message:String(e);r?.(`[sync-fs] re-snapshot after exec failed: ${t}\n`)}},o=async t=>{await i();try{return await e.call(`exec`,`run`,[t])}finally{await a()}},s=async t=>{await i();try{return await e.call(`exec`,`spawn`,[t])}finally{await a()}},c=1,l=Object.assign(o,{spawn:s,start:(t,n)=>{let r=c++,o=[],s=!1,l=!1,u=!1,d,f,p=new Promise((e,t)=>{d=e,f=t}),m=()=>{if(s||u||l)return;l=!0;let c=o.length>0?o.join(``):n?.stdin,p={};c!==void 0&&(p.stdin=c),n?.stdinKind!==void 0&&(p.stdinKind=n.stdinKind),n?.args!==void 0&&(p.args=n.args),(async()=>{try{if(await i(),u){await a(!0);return}s=!0;let n=await e.call(`exec`,`start`,[r,t,p]);await a(!0),d(n)}catch(e){await a(!0),f(e)}})()};return{kill:t=>s?e.call(`exec`,`kill`,[r,t]):(u=!0,d({stdout:``,stderr:``,exitCode:$w(t)}),Promise.resolve(!0)),stdin:{write:e=>{!s&&!u&&o.push(e)},end:()=>m()},done:p}}});return l.exec=l,l}function tT(e){if(!e||e===`/`)return`/`;e.startsWith(`/`)||(e=`/`+e);let t=e.split(`/`),n=[];for(let e of t)e===``||e===`.`||(e===`..`?n.pop():n.push(e));return`/`+n.join(`/`)}function nT(e){let t=tT(e);if(t===`/`)return`/`;let n=t.lastIndexOf(`/`);return n===0?`/`:t.slice(0,n)}function rT(e){return Object.assign(Error(`ENOENT: no such file or directory, '${e}'`),{code:`ENOENT`})}function iT(e){return Object.assign(Error(`ENOSYNC: file too large for sync access, '${e}' — use async readFile() instead`),{code:`ENOSYNC`})}function aT(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}var oT=class{tree=new Map;initialPaths=new Set;initialContent=new Map;initialIsDirectory=new Map;mkdtempCounter=0;tombstones=new Set;removedDirs=new Set;touched=!1;constructor(e){this.loadSnapshot(e)}loadSnapshot(e){this.tree=new Map,this.tombstones=new Set,this.removedDirs=new Set,this.initialPaths=new Set,this.initialContent=new Map,this.initialIsDirectory=new Map,this.tree.set(`/`,{content:new Uint8Array,isDirectory:!0}),this.initialPaths.add(`/`),this.initialIsDirectory.set(`/`,!0);for(let t of e.entries){let e=tT(t.path);this.tree.set(e,{content:t.content,isDirectory:t.isDirectory,truncated:t.truncated,size:t.size}),this.initialPaths.add(e),this.initialIsDirectory.set(e,t.isDirectory),t.isDirectory||this.initialContent.set(e,t.content)}for(let t of e.entries){let e=nT(tT(t.path));for(;e!==`/`&&!this.tree.has(e);)this.tree.set(e,{content:new Uint8Array,isDirectory:!0}),this.initialPaths.add(e),this.initialIsDirectory.set(e,!0),e=nT(e)}}wasUsed(){return this.touched}applySnapshot(e){this.loadSnapshot(e)}applySnapshotPreservingMutations(e){let t=this.getMutations();this.loadSnapshot(e);for(let e of t.deleted){if(this.tree.get(e)?.isDirectory){let t=e===`/`?`/`:e+`/`;for(let n of Array.from(this.tree.keys()))n!==e&&n.startsWith(t)&&this.tree.delete(n)}this.tree.delete(e)}for(let e of t.created)this.ensureParentDirs(e.path),this.tree.set(e.path,{content:e.content,isDirectory:e.isDirectory});for(let e of t.modified)this.ensureParentDirs(e.path),this.tree.set(e.path,{content:e.content,isDirectory:!1})}resetBaseline(){this.initialPaths=new Set,this.initialContent=new Map,this.initialIsDirectory=new Map;for(let[e,t]of this.tree.entries())this.initialPaths.add(e),this.initialIsDirectory.set(e,t.isDirectory),t.isDirectory||this.initialContent.set(e,t.content)}ensureParentDirs(e){let t=nT(e);t!==`/`&&(this.tree.has(t)||this.mkdir(t,!0))}commitWrite(e,t){this.writeFile(e,t);let n=tT(e);for(this.initialContent.set(n,t);n!==`/`;){let e=this.tree.get(n);e&&(this.initialPaths.add(n),this.initialIsDirectory.set(n,e.isDirectory)),n=nT(n)}}readFile(e){this.touched=!0;let t=tT(e),n=this.tree.get(t);if(!n||n.isDirectory)throw rT(t);if(n.truncated)throw iT(t);return n.content}writeFile(e,t){this.touched=!0;let n=tT(e);this.ensureParentDirs(n),this.tree.set(n,{content:t,isDirectory:!1}),this.tombstones.delete(n),this.removedDirs.delete(n)}exists(e){this.touched=!0;let t=tT(e);return this.tree.has(t)}stat(e){this.touched=!0;let t=tT(e),n=this.tree.get(t);if(!n)throw rT(t);return{isFile:!n.isDirectory,isDirectory:n.isDirectory,size:n.isDirectory?0:n.size??n.content.byteLength}}readdir(e){this.touched=!0;let t=tT(e);if(!this.tree.get(t)?.isDirectory)throw rT(t);let n=t===`/`?`/`:t+`/`,r=new Set;for(let e of this.tree.keys()){if(e===t||e===`/`||!e.startsWith(n))continue;let i=e.slice(n.length).split(`/`)[0];i&&r.add(i)}return Array.from(r)}mkdir(e,t){this.touched=!0;let n=tT(e);if(this.tree.has(n)){if(this.tree.get(n).isDirectory)return;throw Object.assign(Error(`EEXIST: file already exists, '${n}'`),{code:`EEXIST`})}let r=nT(n);if(r!==`/`&&!this.tree.has(r)){if(!t)throw rT(n);this.mkdir(r,!0)}this.tree.set(n,{content:new Uint8Array,isDirectory:!0}),this.tombstones.delete(n),this.removedDirs.delete(n)}rm(e,t){this.touched=!0;let n=tT(e),r=this.tree.get(n);if(!r)throw rT(n);if(r.isDirectory){let e=n===`/`?`/`:n+`/`,r=Array.from(this.tree.keys()).filter(t=>t!==n&&t.startsWith(e));if(r.length>0&&!t)throw Object.assign(Error(`ENOTEMPTY: directory not empty, '${n}'`),{code:`ENOTEMPTY`});for(let e of r)this.tree.delete(e),this.tombstones.add(e);t&&this.removedDirs.add(n)}this.tree.delete(n),this.tombstones.add(n)}copyFile(e,t){this.touched=!0;let n=tT(e),r=this.tree.get(n);if(!r||r.isDirectory)throw rT(n);if(r.truncated)throw iT(n);let i=tT(t);this.ensureParentDirs(i),this.tree.set(i,{content:r.content.slice(),isDirectory:!1}),this.tombstones.delete(i),this.removedDirs.delete(i)}rename(e,t){this.touched=!0;let n=tT(e),r=this.tree.get(n);if(!r)throw rT(n);let i=tT(t);if(r.isDirectory){let e=n===`/`?`/`:n+`/`,t=Array.from(this.tree.keys()).filter(t=>t!==n&&t.startsWith(e));this.ensureParentDirs(i),this.tree.set(i,r),this.tree.delete(n);for(let e of t){let t=this.tree.get(e),r=i+e.slice(n.length);this.tree.set(r,t),this.tree.delete(e)}this.tombstones.add(n),this.removedDirs.add(n),this.tombstones.delete(i),this.removedDirs.delete(i);return}this.ensureParentDirs(i),this.tree.set(i,r),this.tree.delete(n),this.tombstones.add(n),this.tombstones.delete(i),this.removedDirs.delete(i)}unlink(e){this.touched=!0;let t=tT(e),n=this.tree.get(t);if(!n)throw rT(t);if(n.isDirectory)throw Object.assign(Error(`EISDIR: illegal operation on a directory, unlink '${t}'`),{code:`EISDIR`});this.tree.delete(t),this.tombstones.add(t)}isTombstoned(e){let t=tT(e);if(this.tombstones.has(t))return!0;for(let e of this.removedDirs)if(t===e||t.startsWith(`${e}/`))return!0;return!1}mkdtemp(e){this.touched=!0;for(let t=0;t<100;t++){let t=`_${String(this.mkdtempCounter).padStart(6,`0`)}`;this.mkdtempCounter++;let n=tT(e+t);if(!this.tree.has(n))return this.mkdir(n,!0),n}throw Error(`mkdtemp: failed to create unique directory after 100 attempts`)}getMutations(){let e=[],t=[],n=[];for(let[r,i]of this.tree.entries()){if(r===`/`)continue;if(!this.initialPaths.has(r)){e.push({path:r,content:i.content,isDirectory:i.isDirectory});continue}let a=this.initialIsDirectory.get(r);if(a!==void 0&&a!==i.isDirectory){n.push(r),e.push({path:r,content:i.content,isDirectory:i.isDirectory});continue}if(!i.isDirectory){let e=this.initialContent.get(r);e&&!aT(e,i.content)&&t.push({path:r,content:i.content})}}for(let e of this.initialPaths)e!==`/`&&(this.tree.has(e)||n.push(e));return{created:e,modified:t,deleted:n}}};function sT(e,t){function n(e){if(e instanceof Uint8Array)return e;if(ArrayBuffer.isView(e)){let t=e;return new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}return e instanceof ArrayBuffer?new Uint8Array(e):new TextEncoder().encode(typeof e==`string`?e:String(e))}async function r(t,n){let r=typeof n==`string`?n:n?.encoding;if(r===null||r===`buffer`){let n=await e.call(`vfs`,`readFileBinary`,[t]),r=globalThis.Buffer;return r?r.from(n instanceof Uint8Array?n:new Uint8Array(n)):n}return e.call(`vfs`,`readFile`,[t])}async function i(t,r){return typeof r==`string`?e.call(`vfs`,`writeFile`,[t,r]):e.call(`vfs`,`writeFileBinary`,[t,n(r)])}async function a(t,r){let i=new Uint8Array;if(await e.call(`vfs`,`exists`,[t])){let n=await e.call(`vfs`,`readFileBinary`,[t]);i=n instanceof Uint8Array?n:new Uint8Array(n)}let a=n(r),o=new Uint8Array(i.byteLength+a.byteLength);o.set(i),o.set(a,i.byteLength),await e.call(`vfs`,`writeFileBinary`,[t,o])}async function o(t,n,r){let i=await e.call(`vfs`,`stat`,[t]);if(i.isFile){let r=await e.call(`vfs`,`readFileBinary`,[t]);await e.call(`vfs`,`writeFileBinary`,[n,r]);return}if(!i.isDirectory||!r?.recursive)throw Error(`cp: '${t}' is a directory (use {recursive: true})`);await c(n);let a=await e.call(`vfs`,`readDir`,[t]);for(let e of a)await o(`${t}/${e}`,`${n}/${e}`,r)}async function s(t,n){if(n?.force&&!await e.call(`vfs`,`exists`,[t]))return!0;if((await e.call(`vfs`,`stat`,[t])).isFile)return e.call(`vfs`,`rm`,[t]);if(!n?.recursive)throw Error(`rm: '${t}' is a directory (use {recursive: true})`);let r=await e.call(`vfs`,`readDir`,[t]);for(let e of r)await s(`${t}/${e}`,n);return e.call(`vfs`,`rm`,[t])}async function c(t){await e.call(`vfs`,`mkdir`,[t])}async function l(t){for(let n=0;n<5;n++){let n=`${t}${Math.random().toString(36).slice(2,10)+Math.random().toString(36).slice(2,6)}`;if(!await e.call(`vfs`,`exists`,[n]))return await e.call(`vfs`,`mkdir`,[n]),n}throw Error(`mkdtemp: failed to create unique directory after 5 attempts`)}async function u(t,n){try{await e.call(`vfs`,`rename`,[t,n])}catch{let r=await e.call(`vfs`,`readFileBinary`,[t]);await e.call(`vfs`,`writeFileBinary`,[n,r]),await e.call(`vfs`,`rm`,[t])}}async function d(t){if(!await e.call(`vfs`,`exists`,[t]))throw Object.assign(Error(`ENOENT: no such file or directory, access '${t}'`),{code:`ENOENT`})}let f={readFile:r,readFileBinary:t=>e.call(`vfs`,`readFileBinary`,[t]),writeFile:i,writeFileBinary:(t,n)=>e.call(`vfs`,`writeFileBinary`,[t,n]),appendFile:a,cp:o,rm:s,readDir:t=>e.call(`vfs`,`readDir`,[t]),readdir:t=>e.call(`vfs`,`readDir`,[t]),exists:t=>e.call(`vfs`,`exists`,[t]),stat:t=>e.call(`vfs`,`stat`,[t]),mkdir:(t,n)=>e.call(`vfs`,`mkdir`,[t]),mkdtemp:l,rename:u,access:d,unlink:t=>e.call(`vfs`,`rm`,[t]),rmdir:t=>e.call(`vfs`,`rm`,[t]),copyFile:async(t,n)=>{let r=await e.call(`vfs`,`readFileBinary`,[t]);await e.call(`vfs`,`writeFileBinary`,[n,r])},fetchToFile:async(n,r)=>{let i=await t(n);if(!i.ok)throw Error(`fetch ${i.status} ${i.statusText}`);let a=new Uint8Array(await i.arrayBuffer());return await e.call(`vfs`,`writeFileBinary`,[r,a]),a.byteLength},promises:null};return f.promises=f,f}function cT(e,t,n=``){return Object.assign(Error(`${e}: sync-fs, ${n?`${n} `:``}'${t}'`),{code:e})}function lT(e){if(typeof e==`string`)return new TextEncoder().encode(e);if(e instanceof Uint8Array)return e;if(ArrayBuffer.isView(e)){let t=e;return new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}return new TextEncoder().encode(String(e))}function uT(e,t,n){function r(e){return tT(e.startsWith(`/`)?e:t+(t.endsWith(`/`)?``:`/`)+e)}function i(t){try{return e.readFile(t)}catch(r){let i=r?.code;if(n&&!e.isTombstoned(t)&&(i===`ENOENT`||i===`ENOSYNC`))return n.readFile(t);throw r}}function a(t,r){n?(n.writeFile(t,r),e.commitWrite(t,r)):e.writeFile(t,r)}function o(t){if(e.exists(t))return!0;if(!n||e.isTombstoned(t))return!1;try{return n.exists(t)}catch{return!1}}function s(t){try{return e.stat(t)}catch(r){let i=r?.code;if(!n||e.isTombstoned(t)||i!==`ENOENT`)throw r;return n.stat(t)}}function c(t){try{return e.readdir(t)}catch(r){let i=r?.code;if(!n||e.isTombstoned(t)||i!==`ENOENT`)throw r;return n.readdir(t)}}let l=e=>({isFile:()=>e.isFile,isDirectory:()=>e.isDirectory,size:e.size}),u=(e,t)=>e===`/`?`/${t}`:`${e}/${t}`;function d(t,n){if(!s(t).isDirectory){a(n,i(t));return}e.mkdir(n,!0);for(let e of c(t))d(u(t,e),u(n,e))}return{readFileSync(e,t){let n=typeof t==`string`?t:t?.encoding,a=i(r(e));if(n===`utf8`||n===`utf-8`)return new TextDecoder().decode(a);let o=globalThis.Buffer;return o?o.from(a):a},writeFileSync(e,t){a(r(e),lT(t))},appendFileSync(e,t){let n=r(e),o=new Uint8Array;try{o=i(n)}catch(e){if(e?.code!==`ENOENT`)throw e}let s=lT(t),c=new Uint8Array(o.byteLength+s.byteLength);c.set(o),c.set(s,o.byteLength),a(n,c)},truncateSync(e,t=0){let n=r(e),o=i(n),s=new Uint8Array(t);s.set(o.subarray(0,Math.min(t,o.byteLength))),a(n,s)},existsSync(e){return o(r(e))},accessSync(e){let t=r(e);if(!o(t))throw cT(`ENOENT`,t,`access`)},mkdirSync(t,n){e.mkdir(r(t),n?.recursive)},statSync(e){return l(s(r(e)))},lstatSync(e){return l(s(r(e)))},realpathSync(e){let t=r(e);if(!o(t))throw cT(`ENOENT`,t,`realpath`);return t},readdirSync(e){return c(r(e))},rmSync(t,n){let i=r(t);n?.force&&!e.exists(i)||e.rm(i,n?.recursive)},rmdirSync(t,n){let i=r(t);if(o(i)&&!s(i).isDirectory)throw cT(`ENOTDIR`,i,`rmdir`);e.rm(i,n?.recursive)},copyFileSync(e,t){a(r(t),i(r(e)))},cpSync(e,t){d(r(e),r(t))},chmodSync(e){let t=r(e);if(!o(t))throw cT(`ENOENT`,t,`chmod`)},mkdtempSync(t){return e.mkdtemp(r(t))},unlinkSync(t){e.unlink(r(t))},renameSync(t,n){e.rename(r(t),r(n))}}}function dT(e){if(e instanceof Uint8Array)return e;if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);if(e instanceof ArrayBuffer)return new Uint8Array(e);throw TypeError(`expected an ArrayBuffer or typed array`)}function fT(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function pT(e){return e==null?[]:Array.isArray(e)?e:[e]}function mT(e,t){let n=t.handle,r=new Set,i=new Set,a=!1,o=null,s=e=>{let t=e;if(!t||t.handle!==n)return;let i={reportId:t.reportId,data:fT(t.bytes)};for(let e of[...r])try{e(i)}catch{}},c=()=>{a||(a=!0,o=e.onEvent?e.onEvent(`hid-input-report`,s):null,e.call(`hid`,`subscribeInputReports`,[n]).catch(()=>{a=!1,o?.(),o=null}))},l=()=>{!a||r.size>0||(a=!1,o?.(),o=null,e.call(`hid`,`unsubscribeInputReports`,[n]).catch(()=>{}))};return{...t,open:()=>e.call(`hid`,`open`,[n]),close:()=>e.call(`hid`,`close`,[n]),sendReport:(t,r)=>e.call(`hid`,`sendReport`,[n,t,dT(r)]),sendFeatureReport:(t,r)=>e.call(`hid`,`sendFeatureReport`,[n,t,dT(r)]),receiveFeatureReport:async t=>fT((await e.call(`hid`,`receiveFeatureReport`,[n,t])).bytes),addEventListener(e,t){if(e===`inputreport`)r.add(t),c();else if(e===`disconnect`)i.add(t);else throw TypeError(`hid device: unknown event type '${String(e)}'`)},removeEventListener(e,t){e===`inputreport`?(r.delete(t),l()):e===`disconnect`&&i.delete(t)},onInputReport(e){r.add(e),c()}}}function hT(e){return{list:async()=>(await e.call(`hid`,`list`,[])).map(t=>mT(e,t)),request:async t=>{let n=(await e.call(`hid`,`request`,[pT(t)]))[0];if(!n)throw Error(`No device selected.`);return mT(e,n)}}}function gT(e){let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}var _T=class{rpc;targetId;selector;index;constructor(e,t,n,r){this.rpc=e,this.targetId=t,this.selector=n,this.index=r}evalOnElement(e){let t=`(() => { const els = document.querySelectorAll(${JSON.stringify(this.selector)}); const el = els[${this.index}]; ${e} })()`;return this.rpc.call(`browser`,`evalAsync`,[this.targetId,t])}async textContent(){return this.evalOnElement(`return el ? el.textContent : null;`)}async getAttribute(e){return this.evalOnElement(`return el ? el.getAttribute(${JSON.stringify(e)}) : null;`)}async isVisible(){return this.evalOnElement(`if (!el) return false; const s = getComputedStyle(el); if (s.display === 'none' || s.visibility === 'hidden' || s.opacity === '0') return false; const r = el.getBoundingClientRect(); return r.width > 0 && r.height > 0;`)}async boundingBox(){return this.evalOnElement(`if (!el) return null; const r = el.getBoundingClientRect(); return { x: r.x, y: r.y, width: r.width, height: r.height };`)}},vT=class{rpc;targetId;onClose;closed=!1;constructor(e,t,n){this.rpc=e,this.targetId=t,this.onClose=n}async goto(e,t){await this.rpc.call(`browser`,`navigateTab`,[this.targetId,e])}async waitForLoadState(e){await this.rpc.call(`browser`,`waitForLoadState`,[this.targetId,e??`load`])}async waitForTimeout(e){await new Promise(t=>setTimeout(t,e))}async evaluate(e,...t){let n=typeof e==`string`?e:`(${e.toString()}).apply(null, JSON.parse(${JSON.stringify(JSON.stringify(t))}))`;return this.rpc.call(`browser`,`evalAsync`,[this.targetId,n])}async screenshot(e){let t={};e?.fullPage!==void 0&&(t.fullPage=e.fullPage);let n=gT(await this.rpc.call(`browser`,`screenshotTab`,[this.targetId,t]));return e?.path&&await this.rpc.call(`vfs`,`writeFileBinary`,[e.path,n]),n}async $(e){return await this.rpc.call(`browser`,`evalAsync`,[this.targetId,`!!document.querySelector(${JSON.stringify(e)})`])?new _T(this.rpc,this.targetId,e,0):null}async $$(e){let t=await this.rpc.call(`browser`,`evalAsync`,[this.targetId,`document.querySelectorAll(${JSON.stringify(e)}).length`]),n=[];for(let r=0;r<t;r++)n.push(new _T(this.rpc,this.targetId,e,r));return n}async $$eval(e,t,...n){if(typeof t==`string`)return this.rpc.call(`browser`,`evalAsync`,[this.targetId,t]);let r=`(${t.toString()}).apply(null, [Array.from(document.querySelectorAll(${JSON.stringify(e)}))].concat(JSON.parse(${JSON.stringify(JSON.stringify(n))})))`;return this.rpc.call(`browser`,`evalAsync`,[this.targetId,r])}async content(){return this.rpc.call(`browser`,`evalAsync`,[this.targetId,`document.documentElement.outerHTML`])}async setViewportSize(e){await this.rpc.call(`browser`,`setViewport`,[this.targetId,e.width,e.height])}async close(){this.closed||(this.closed=!0,await this.rpc.call(`browser`,`closeTab`,[this.targetId]),this.onClose?.())}},yT=class{rpc;openPages=[];constructor(e){this.rpc=e}async newPage(e){let t=await this.rpc.call(`browser`,`createTab`,[`about:blank`]);e?.viewport&&await this.rpc.call(`browser`,`setViewport`,[t,e.viewport.width,e.viewport.height]);let n=new vT(this.rpc,t,()=>{let e=this.openPages.indexOf(n);e!==-1&&this.openPages.splice(e,1)});return this.openPages.push(n),n}pages(){return[...this.openPages]}async close(){let e=this.openPages.splice(0,this.openPages.length);for(let t of e)await t.close()}},bT=class{rpc;openPages=[];openContexts=[];constructor(e){this.rpc=e}async newPage(e){let t=await this.rpc.call(`browser`,`createTab`,[`about:blank`]);e?.viewport&&await this.rpc.call(`browser`,`setViewport`,[t,e.viewport.width,e.viewport.height]);let n=new vT(this.rpc,t,()=>{let e=this.openPages.indexOf(n);e!==-1&&this.openPages.splice(e,1)});return this.openPages.push(n),n}async newContext(e){let t=new yT(this.rpc);return this.openContexts.push(t),t}contexts(){return[...this.openContexts]}async close(){let e=this.openPages.splice(0,this.openPages.length);for(let t of e)await t.close();let t=this.openContexts.splice(0,this.openContexts.length);for(let e of t)await e.close()}};function xT(e){let t=async t=>new bT(e),n=async(t,n)=>new bT(e);return{chromium:{launch:t,connect:n,connectOverCDP:n},firefox:{launch:t,connect:n},webkit:{launch:t,connect:n}}}function ST(e){if(!e)return``;let t=e.lastIndexOf(`/`);return t<0?``:t===0?`/`:e.substring(0,t)}var CT=class extends Error{code;constructor(e){super(`Process exited with code ${e}`),this.code=e,this.name=`NodeExitError`}};function wT(e){if(typeof e==`string`)return e;if(e==null)return String(e);try{return JSON.stringify(e)}catch{return String(e)}}function TT(e,t){return{log:(...t)=>e(`${t.map(wT).join(` `)}
|
|
4854
|
+
`),info:(...t)=>e(`${t.map(wT).join(` `)}
|
|
4855
|
+
`),warn:(...e)=>t(`${e.map(wT).join(` `)}
|
|
4856
|
+
`),error:(...e)=>t(`${e.map(wT).join(` `)}
|
|
4857
|
+
`)}}function ET(e,t,n){let r=!!e.env?.NO_COLOR,i=DT(e.stdin??``),a=QS(e.argv),o=!1;return{processShim:{argv:a,env:e.env,cwd:()=>e.cwd,exit:e=>{throw o=!0,new CT(Number.isFinite(e)?Number(e):0)},stdin:i,stdout:{write:t,isTTY:!r},stderr:{write:n,isTTY:!r}},getDidCallProcessExit:()=>o}}function DT(e){let t=!1;return{isTTY:!1,read(){return t?null:(t=!0,e)},toString(){return e},[Symbol.asyncIterator](){return{async next(){return t?{value:void 0,done:!0}:(t=!0,{value:e,done:!1})}}}}}const OT=new Set([`bcrypt`,`better-sqlite3`,`canvas`,`cpu-features`,`fsevents`,`leveldown`,`libxmljs`,`libxmljs2`,`node-gyp-build`,`node-sass`,`puppeteer`,`robotjs`,`sass-embedded`,`sharp`,`snappy`,`sqlite3`,`tree-sitter`,`usb`]),kT={sharp:` Use the built-in 'convert' shell command for image work.`,canvas:` Use the built-in 'convert' / OffscreenCanvas for image work.`,"better-sqlite3":` Use the built-in 'sqlite3' shell command (sql.js WASM).`,sqlite3:` Use the built-in 'sqlite3' shell command (sql.js WASM).`,bcrypt:` Use crypto.subtle.digest() with PBKDF2 / Argon2 in pure JS.`,puppeteer:` Use the built-in browser-automation shell commands.`};function AT(e,t){let n=kT[t]??``;return Error(`require('${e}'): '${t}' is a Node native module (C++ bindings) — it cannot run in the browser sandbox.${n}`)}function jT(e){return{...e,time:aC,fmt:mC,pool:hC}}function MT(e,t){return e?.startsWith(`/`)?ST(e):t}function NT(e){return e.includes(`require`)||e.includes(`import`)}async function PT(e,t,n,r){return NT(t)?e.call(`module`,`buildGraph`,[t,MT(r,n),r]):{files:[],entryMap:{},edges:{},errors:{}}}function FT(e){if(typeof e!=`object`||!e)return;let t=e;if(t.__esModule&&!Object.prototype.hasOwnProperty.call(t,`default`)&&Object.isExtensible(t))try{Object.defineProperty(t,"default",{value:t,enumerable:!1,configurable:!0})}catch{}}function IT(e){return{playwright:xT(e)}}function LT(e){let{graph:t,fsBridge:n,processShim:r,childProcess:i,nodeConsole:a,sliccyModules:o,shimmedPackages:s={}}=e,c=new Map(t.files.map(e=>[e.path,e.cjsSource])),l=new Map(t.files.map(e=>[e.path,e.kind])),u=new Map,d=e=>{if(typeof e==`string`&&e.startsWith(`sliccy:`))return{hit:!0,value:BT(e,o)};let t=e.startsWith(`node:`)?e.slice(5):e,a=RT(t,n,r,i);if(a.hit)return a;if(OT.has(t))throw AT(e,t);if(en.has(t))throw HT(e,t);return t in s?{hit:!0,value:s[t]}:{hit:!1}},f=(e,n)=>{let r=d(n);if(r.hit)return r.value;let i=e?.[n];if(i)return p(i);throw n in t.errors?Error(t.errors[n]):zT(n)};function p(e){let n=u.get(e);if(n)return n.exports;let i=c.get(e);if(i===void 0)throw Error(`Cannot find module '${e}'`);let o={exports:{}};u.set(e,o);let s=n=>f(t.edges[e],n),d=ST(e);return Function(`module`,`exports`,`require`,`__dirname`,`__filename`,`process`,`console`,`Buffer`,`global`,i)(o,o.exports,s,d,e,r,a,globalThis.Buffer,globalThis),l.get(e)===`cjs`&&FT(o.exports),o.exports}return{require:e=>f(t.entryMap,e)}}function RT(e,t,n,r){return e===`fs`||e===`fs/promises`?{hit:!0,value:t}:e===`path`?{hit:!0,value:EC}:e===`crypto`?{hit:!0,value:RC}:e===`child_process`?{hit:!0,value:r}:e===`process`?{hit:!0,value:n}:e===`buffer`?{hit:!0,value:{Buffer:globalThis.Buffer}}:e===`assert`?{hit:!0,value:XC}:e===`assert/strict`?{hit:!0,value:YC}:e===`util`?{hit:!0,value:fw}:e===`events`?{hit:!0,value:Cw}:e===`os`?{hit:!0,value:vw}:e===`stream`?{hit:!0,value:Ow}:e===`url`?{hit:!0,value:xw}:e===`zlib`?{hit:!0,value:_w}:{hit:!1}}function zT(e){if(e.startsWith(`.`)||e.startsWith(`/`)||e.startsWith(`node:`))return Error(`Cannot find module '${e}'`);let t=e.startsWith(`@`)?e.split(`/`).slice(0,2).join(`/`):e.split(`/`)[0];return Error(`Cannot find module '${e}' (run: ipk install ${t})`)}function BT(e,t){let n=e.slice(7);if(n===``)throw Error(`require('sliccy:'): empty sliccy: module name`);if(!Object.prototype.hasOwnProperty.call(t,n))throw Error(`require('${e}'): unknown sliccy: module '${n}'. Known names: ${Object.keys(t).sort().join(`, `)}`);return t[n]}const VT={http:` Use fetch() instead.`,https:` Use fetch() instead.`,crypto:` Use globalThis.crypto (Web Crypto API) instead.`};function HT(e,t){return Error(`require('${e}'): Node built-in '${t}' is not available in the browser environment.${VT[t]||``}`)}async function UT(e,t,n,r){let i=Object.keys(t),a=i.map(e=>t[e]),o=Object.getPrototypeOf(async function(){}).constructor,s=new o(...i,`${r?`"use strict";
|
|
4858
|
+
`:``}${e}`);try{return await s(...a),0}catch(e){return e instanceof CT?e.code:(n(`${e instanceof Error?e.stack??e.message:String(e)}\n`),1)}}function WT(e,t){let n=t.handle;return{...t,open:t=>e.call(`serial`,`open`,[n,t]),close:()=>e.call(`serial`,`close`,[n]),read:(t={})=>e.call(`serial`,`read`,[n,{maxBytes:t.maxBytes??t.bytes,until:t.until?dT(t.until):void 0,timeoutMs:t.timeoutMs}]),write:t=>e.call(`serial`,`write`,[n,dT(t)]),getSignals:()=>e.call(`serial`,`getSignals`,[n]),setSignals:t=>e.call(`serial`,`setSignals`,[n,t])}}function GT(e){return{list:async()=>(await e.call(`serial`,`list`,[])).map(t=>WT(e,t)),request:async t=>WT(e,await e.call(`serial`,`request`,[pT(t)]))}}function KT(e,t){let n=t.handle,r=e=>({status:e.status,data:fT(e.bytes)});return{...t,open:()=>e.call(`usb`,`open`,[n]),close:()=>e.call(`usb`,`close`,[n]),reset:()=>e.call(`usb`,`reset`,[n]),selectConfiguration:t=>e.call(`usb`,`selectConfig`,[n,t]),claimInterface:t=>e.call(`usb`,`claim`,[n,t]),releaseInterface:t=>e.call(`usb`,`release`,[n,t]),controlTransferIn:async(t,i)=>r(await e.call(`usb`,`controlIn`,[n,t,i])),controlTransferOut:(t,r)=>e.call(`usb`,`controlOut`,[n,t,dT(r)]),transferIn:async(t,i)=>r(await e.call(`usb`,`transferIn`,[n,t,i])),transferOut:(t,r)=>e.call(`usb`,`transferOut`,[n,t,dT(r)])}}function qT(e){return{list:async()=>(await e.call(`usb`,`list`,[])).map(t=>KT(e,t)),request:async t=>KT(e,await e.call(`usb`,`request`,[pT(t)]))}}function JT(e){if(!e)return``;let t=e.lastIndexOf(`/`);return t<0?``:t===0?`/`:e.substring(0,t)}function YT(e){return/^[A-Za-z0-9_\-./:@]+$/.test(e)?e:`'`+e.replace(/'/g,`'\\''`)+`'`}function XT(e,t){return e===``?t:e===`/`?`/${t}`:`${e}/${t}`}function ZT(e){let t=JT(e.argv[1]??``),n=XT(t,`references`),r=XT(t,`assets`),i=XT(t,`.config`);async function a(){let t;try{t=await e.fs.exists(i)}catch{return null}if(!t)return null;let n;try{n=await e.fs.readFile(i)}catch{return null}let r=typeof n==`string`?n:String(n);if(!r.trim())return null;let a;try{a=JSON.parse(r)}catch(e){let t=e instanceof Error?e.message:String(e);throw Error(`skill.config(): failed to parse ${i}: ${t}`)}if(a&&typeof a==`object`&&!Array.isArray(a))return a;throw Error(`skill.config(): ${i} must contain a JSON object`)}async function o(t){let n=await a();if(t===void 0)return n;if(typeof t!=`object`||!t||Array.isArray(t))throw TypeError(`skill.config(updates): updates must be a plain object`);let r={...n??{},...t};return await e.fs.writeFile(i,JSON.stringify(r,null,2)+`
|
|
4859
|
+
`),r}async function s(t){if(typeof t!=`string`||!t.trim())throw TypeError(`skill.token(providerId): providerId must be a non-empty string`);let n=`oauth-token ${YT(t)}`,{stdout:r,stderr:i,exitCode:a}=await e.exec(n);if(a!==0){let e=i.trim()||`oauth-token exited with code ${a}`;throw Error(`skill.token('${t}'): ${e}`)}return r.replace(/\r?\n+$/,``)}return Object.freeze({dir:t,refs:n,assets:r,config:o,token:s})}function QT(e){return`slicc-sync-fs-`+e}const $T=`sync-fs-ack`,eE=`sync-fs-res`;function tE(e,t){return Object.assign(Error(`${e}: sync-fs bridge, '${t}'`),{code:e})}function nE(e,t){let n=`/__slicc/fs-sync`+(e.startsWith(`/`)?e:`/${e}`).split(`/`).map(encodeURIComponent).join(`/`);return t?`${n}?op=${t}`:n}function rE(e,t={}){let n=t.timeoutMs??3e4;function r(t,r,i,a){let o=new XMLHttpRequest;try{o.open(t,nE(r,a),!1),o.responseType=`arraybuffer`,o.timeout=n,o.setRequestHeader(`x-slicc-fs-token`,e),i?o.send(new Uint8Array(i)):o.send()}catch{throw tE(`EIO`,r)}return o}function i(e,t){try{let t=new Uint8Array(e.response);return JSON.parse(new TextDecoder().decode(t))}catch{throw tE(`EIO`,t)}}function a(e,t){throw tE(e.getResponseHeader(`x-slicc-fs`)===`1`&&e.getResponseHeader(`x-slicc-fs-errno`)||`EIO`,t)}function o(e){return e.status>=200&&e.status<300&&e.getResponseHeader(`x-slicc-fs`)===`1`}return{readFile(e){let t=r(`GET`,e);if(o(t))return new Uint8Array(t.response);if(t.status>=200&&t.status<300)throw tE(`EIO`,e);a(t,e)},writeFile(e,t){let n=r(`POST`,e,t);if(!o(n)){if(n.status>=200&&n.status<300)throw tE(`EIO`,e);a(n,e)}},stat(e){let t=r(`GET`,e,void 0,`stat`);if(o(t)){let n=i(t,e);if(!n||typeof n.isFile!=`boolean`||typeof n.isDirectory!=`boolean`||typeof n.size!=`number`)throw tE(`EIO`,e);return{isFile:n.isFile,isDirectory:n.isDirectory,size:n.size}}if(t.status>=200&&t.status<300)throw tE(`EIO`,e);a(t,e)},readdir(e){let t=r(`GET`,e,void 0,`readdir`);if(o(t)){let n=i(t,e);if(!Array.isArray(n)||!n.every(e=>typeof e==`string`))throw tE(`EIO`,e);return n}if(t.status>=200&&t.status<300)throw tE(`EIO`,e);a(t,e)},exists(e){let t=r(`GET`,e,void 0,`exists`);if(o(t)){let n=i(t,e);if(typeof n!=`boolean`)throw tE(`EIO`,e);return n}if(t.status>=200&&t.status<300)throw tE(`EIO`,e);a(t,e)}}}async function iE(e,t,n){let r;try{r=await e.call(`vfs`,`snapshot`,[t])}catch(e){n?.(e instanceof Error?e.message:String(e)),r={entries:[]}}return new oT(r)}function aE(e,t){if(e.syncFsToken)return e=>t(`[sync-fs] snapshot failed, sync metadata will be incomplete: ${e}\n`)}function oE(e){return e.syncFsToken?rE(e.syncFsToken):void 0}function sE(e){return{usbBridge:qT(e),serialBridge:GT(e),hidBridge:hT(e)}}async function cE(e,t){let n=[],r=[],i=e=>{n.push(typeof e==`string`?e:String(e))},a=e=>{r.push(typeof e==`string`?e:String(e))},o=TT(i,a),{processShim:s,getDidCallProcessExit:c}=ET(e,i,a),l=!!e.env?.NO_COLOR,u=tC({isTTY:!l,noColor:l}),d=$S({writeStdout:i,writeStderr:a,exit:e=>{throw new CT(e)},color:u}),f=new yv(t),p=sT(f,C),m=await iE(f,e.cwd,aE(e,a));Object.assign(p,uT(m,e.cwd,oE(e)));let h=eT(f,m,e.cwd,a),g=zw(h,{cwd:e.cwd}),_=ZT({argv:e.argv,fs:p,exec:h}),v=Yw(f),{usbBridge:y,serialBridge:b,hidBridge:x}=sE(f),S=fy({fetch:C});async function C(e,t){let n=e instanceof Request?e.url:e instanceof URL?e.toString():String(e),r=await f.call(`fetch`,`request`,[n,Jw(t,e)]),i=r.body.byteLength===0?null:r.body.buffer.slice(r.body.byteOffset,r.body.byteOffset+r.body.byteLength),a=new Response(i,{status:r.status,statusText:r.statusText,headers:r.headers});return Object.defineProperty(a,"url",{value:r.url||n}),a}let w=jT({exec:h,agent:g,skill:_,http:S,browser:v,usb:y,serial:b,hid:x,cli:d,color:u}),T=e.filename,E=ST(T),D=await PT(f,e.code,e.cwd,T),O=LT({graph:D,fsBridge:p,processShim:s,childProcess:Iw(h),nodeConsole:o,sliccyModules:w,shimmedPackages:IT(f)}).require,k={exports:{},filename:e.filename},A=D.entrySource!==void 0,j=D.entrySource??e.code,M=globalThis;M.__slicc_compileWasm=e=>f.call(`wasm`,`compile`,[e]);let N=await UT(j,{process:s,console:o,require:O,module:k,exports:k.exports,fetch:C,__dirname:E,__filename:T},a,A);await lE(f,m,a),c()||await uE(f),delete M.__slicc_compileWasm,f.dispose(),t.postMessage({type:`realm-done`,stdout:n.join(``),stderr:r.join(``),exitCode:N})}async function lE(e,t,n){let r=t.getMutations();if(r.created.length||r.modified.length||r.deleted.length)try{await e.call(`vfs`,`flushWrites`,[r])}catch(e){let t=e instanceof Error?e.message:String(e);n(`[sync-fs] ERROR: flush failed — ${r.created.length+r.modified.length} write(s) + ${r.deleted.length} delete(s) were NOT persisted: ${t}\n`)}}async function uE(e){let t=Date.now()+1e3,n=0;do await new Promise(e=>setTimeout(e,0)),n++;while(e.pendingCount>0&&n<50&&Date.now()<t)}function dE(){let e=new Set,t=new Set;return{realmSide:{postMessage:e=>{queueMicrotask(()=>{for(let n of[...t])n({data:e})})},addEventListener:(t,n)=>{e.add(n)},removeEventListener:(t,n)=>{e.delete(n)}},hostSide:{postMessage:t=>{queueMicrotask(()=>{for(let n of[...e])n({data:t})})},addEventListener:(e,n)=>{t.add(n)},removeEventListener:(e,n)=>{t.delete(n)}}}}function fE(){return async({kind:e})=>{if(e!==`js`)throw Error(`createInProcessJsRealmFactory: only kind:js is supported`);let{realmSide:t,hostSide:n}=dE(),r=e=>{if(e.data?.type!==`realm-init`)return;t.removeEventListener(`message`,r);let n=e.data;n.kind===`js`&&cE(n,t).catch(e=>{let n={type:`realm-error`,message:e instanceof Error?e.message:String(e)};t.postMessage(n)})};return t.addEventListener(`message`,r),{controlPort:n,terminate(){t.removeEventListener(`message`,r)}}}}function pE(){return async({kind:e})=>{if(e!==`py`)throw Error(`createInProcessPyRealmFactory: only kind:py is supported`);let{realmSide:t,hostSide:n}=dE(),r=e=>{if(e.data?.type!==`realm-init`)return;t.removeEventListener(`message`,r);let n=e.data;n.kind===`py`&&Av(n,t).catch(e=>{let n={type:`realm-error`,message:e instanceof Error?e.message:String(e)};t.postMessage(n)})};return t.addEventListener(`message`,r),{controlPort:n,terminate(){t.removeEventListener(`message`,r)}}}}const mE=fE(),hE=pE();function gE(){return async({kind:e,ctx:t})=>e===`py`?typeof Worker<`u`?vE():hE({kind:e,ctx:t}):typeof Worker<`u`?_E():mE({kind:e,ctx:t})}function _E(){if(typeof Worker>`u`)throw Error(`realm-factory: Worker is not available in this runtime`);return yE(new Worker(new URL(`/assets/js-realm-worker-FgXpYXua.js`,``+import.meta.url),{type:`module`}))}function vE(){if(typeof Worker>`u`)throw Error(`realm-factory: Worker is not available in this runtime`);return yE(new Worker(new URL(`/assets/py-realm-worker-VuYxvTG9.js`,``+import.meta.url),{type:`module`}))}function yE(e){let t={postMessage:(t,n)=>n?e.postMessage(t,n):e.postMessage(t),addEventListener:(t,n)=>e.addEventListener(t,n),removeEventListener:(t,n)=>e.removeEventListener(t,n)},n=!1;return{controlPort:t,addEventListener:(t,n,r)=>e.addEventListener(t,n,r),removeEventListener:(t,n)=>e.removeEventListener(t,n),terminate(){if(!n){n=!0;try{e.terminate()}catch{}}}}}function bE(){if(cn())return decodeURIComponent(un(`pyodide/pyodide.mjs`,`../../../../../node_modules/pyodide/`).pathname)}var xE=e(t(((e,t)=>{(e=>{var t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.prototype.hasOwnProperty,a=(e,n)=>{for(var r in n)t(e,r,{get:n[r],enumerable:!0})},o=(e,a,o,s)=>{if(a&&typeof a==`object`||typeof a==`function`)for(let c of r(a))!i.call(e,c)&&c!==o&&t(e,c,{get:()=>a[c],enumerable:!(s=n(a,c))||s.enumerable});return e},s=e=>o(t({},`__esModule`,{value:!0}),e),c=(e,t,n)=>new Promise((r,i)=>{var a=e=>{try{s(n.next(e))}catch(e){i(e)}},o=e=>{try{s(n.throw(e))}catch(e){i(e)}},s=e=>e.done?r(e.value):Promise.resolve(e.value).then(a,o);s((n=n.apply(e,t)).next())}),l={};a(l,{analyzeMetafile:()=>Oe,analyzeMetafileSync:()=>Me,build:()=>we,buildSync:()=>ke,context:()=>Te,default:()=>Be,formatMessages:()=>De,formatMessagesSync:()=>je,initialize:()=>Re,stop:()=>Ne,transform:()=>Ee,transformSync:()=>Ae,version:()=>Ce}),e.exports=s(l);function u(e){let t=e=>{if(e===null)n.write8(0);else if(typeof e==`boolean`)n.write8(1),n.write8(+e);else if(typeof e==`number`)n.write8(2),n.write32(e|0);else if(typeof e==`string`)n.write8(3),n.write(p(e));else if(e instanceof Uint8Array)n.write8(4),n.write(e);else if(e instanceof Array){n.write8(5),n.write32(e.length);for(let n of e)t(n)}else{let r=Object.keys(e);n.write8(6),n.write32(r.length);for(let i of r)n.write(p(i)),t(e[i])}},n=new f;return n.write32(0),n.write32(e.id<<1|!e.isRequest),t(e.value),_(n.buf,n.len-4,0),n.buf.subarray(0,n.len)}function d(e){let t=()=>{switch(n.read8()){case 0:return null;case 1:return!!n.read8();case 2:return n.read32();case 3:return m(n.read());case 4:return n.read();case 5:{let e=n.read32(),r=[];for(let n=0;n<e;n++)r.push(t());return r}case 6:{let e=n.read32(),r={};for(let i=0;i<e;i++)r[m(n.read())]=t();return r}default:throw Error(`Invalid packet`)}},n=new f(e),r=n.read32(),i=(r&1)==0;r>>>=1;let a=t();if(n.ptr!==e.length)throw Error(`Invalid packet`);return{id:r,isRequest:i,value:a}}var f=class{constructor(e=new Uint8Array(1024)){this.buf=e,this.len=0,this.ptr=0}_write(e){if(this.len+e>this.buf.length){let t=new Uint8Array((this.len+e)*2);t.set(this.buf),this.buf=t}return this.len+=e,this.len-e}write8(e){let t=this._write(1);this.buf[t]=e}write32(e){let t=this._write(4);_(this.buf,e,t)}write(e){let t=this._write(4+e.length);_(this.buf,e.length,t),this.buf.set(e,t+4)}_read(e){if(this.ptr+e>this.buf.length)throw Error(`Invalid packet`);return this.ptr+=e,this.ptr-e}read8(){return this.buf[this._read(1)]}read32(){return g(this.buf,this._read(4))}read(){let e=this.read32(),t=new Uint8Array(e),n=this._read(t.length);return t.set(this.buf.subarray(n,n+e)),t}},p,m,h;if(typeof TextEncoder<`u`&&typeof TextDecoder<`u`){let e=new TextEncoder,t=new TextDecoder;p=t=>e.encode(t),m=e=>t.decode(e),h=`new TextEncoder().encode("")`}else if(typeof Buffer<`u`)p=e=>Buffer.from(e),m=e=>{let{buffer:t,byteOffset:n,byteLength:r}=e;return Buffer.from(t,n,r).toString()},h=`Buffer.from("")`;else throw Error(`No UTF-8 codec found`);if(!(p(``)instanceof Uint8Array))throw Error(`Invariant violation: "${h} instanceof Uint8Array" is incorrectly false
|
|
4860
4860
|
|
|
4861
4861
|
This indicates that your JavaScript environment is broken. You cannot use
|
|
4862
4862
|
esbuild in this environment because esbuild relies on this invariant. This
|
|
@@ -5551,7 +5551,7 @@ ${n}:${r}:${i}: ERROR: ${e.pluginName?`[plugin: ${e.pluginName}] `:``}${e.text}`
|
|
|
5551
5551
|
`);return r!=-1&&(console.log(t.substring(0,r)),t=t.substring(r+1)),n.length},write(t,n,r,i,a,o){if(r!==0||i!==n.length||a!==null){o(e());return}o(null,this.writeSync(t,n))},chmod(t,n,r){r(e())},chown(t,n,r,i){i(e())},close(t,n){n(e())},fchmod(t,n,r){r(e())},fchown(t,n,r,i){i(e())},fstat(t,n){n(e())},fsync(e,t){t(null)},ftruncate(t,n,r){r(e())},lchown(t,n,r,i){i(e())},link(t,n,r){r(e())},lstat(t,n){n(e())},mkdir(t,n,r){r(e())},open(t,n,r,i){i(e())},read(t,n,r,i,a,o){o(e())},readdir(t,n){n(e())},readlink(t,n){n(e())},rename(t,n,r){r(e())},rmdir(t,n){n(e())},stat(t,n){n(e())},symlink(t,n,r){r(e())},truncate(t,n,r){r(e())},unlink(t,n){n(e())},utimes(t,n,r,i){i(e())}}}if(r.process||={getuid(){return-1},getgid(){return-1},geteuid(){return-1},getegid(){return-1},getgroups(){throw e()},pid:-1,ppid:-1,umask(){throw e()},cwd(){throw e()},chdir(){throw e()}},r.path||={resolve(...e){return e.join(`/`)}},!r.crypto)throw Error(`globalThis.crypto is not available, polyfill required (crypto.getRandomValues only)`);if(!r.performance)throw Error(`globalThis.performance is not available, polyfill required (performance.now only)`);if(!r.TextEncoder)throw Error(`globalThis.TextEncoder is not available, polyfill required`);if(!r.TextDecoder)throw Error(`globalThis.TextDecoder is not available, polyfill required`);let n=new TextEncoder(`utf-8`),i=new TextDecoder(`utf-8`);r.Go=class{constructor(){this.argv=[`js`],this.env={},this.exit=e=>{e!==0&&console.warn(`exit code:`,e)},this._exitPromise=new Promise(e=>{this._resolveExitPromise=e}),this._pendingEvent=null,this._scheduledTimeouts=new Map,this._nextCallbackTimeoutID=1;let e=(e,t)=>{this.mem.setUint32(e+0,t,!0),this.mem.setUint32(e+4,Math.floor(t/4294967296),!0)},t=e=>this.mem.getUint32(e+0,!0)+this.mem.getInt32(e+4,!0)*4294967296,a=e=>{let t=this.mem.getFloat64(e,!0);if(t===0)return;if(!isNaN(t))return t;let n=this.mem.getUint32(e,!0);return this._values[n]},o=(e,t)=>{let n=2146959360;if(typeof t==`number`&&t!==0){if(isNaN(t)){this.mem.setUint32(e+4,n,!0),this.mem.setUint32(e,0,!0);return}this.mem.setFloat64(e,t,!0);return}if(t===void 0){this.mem.setFloat64(e,0,!0);return}let r=this._ids.get(t);r===void 0&&(r=this._idPool.pop(),r===void 0&&(r=this._values.length),this._values[r]=t,this._goRefCounts[r]=0,this._ids.set(t,r)),this._goRefCounts[r]++;let i=0;switch(typeof t){case`object`:t!==null&&(i=1);break;case`string`:i=2;break;case`symbol`:i=3;break;case`function`:i=4;break}this.mem.setUint32(e+4,n|i,!0),this.mem.setUint32(e,r,!0)},s=e=>{let n=t(e+0),r=t(e+8);return new Uint8Array(this._inst.exports.mem.buffer,n,r)},c=e=>{let n=t(e+0),r=t(e+8),i=Array(r);for(let e=0;e<r;e++)i[e]=a(n+e*8);return i},l=e=>{let n=t(e+0),r=t(e+8);return i.decode(new DataView(this._inst.exports.mem.buffer,n,r))},u=(e,t)=>(this._inst.exports.testExport0(),this._inst.exports.testExport(e,t)),d=Date.now()-performance.now();this.importObject={_gotest:{add:(e,t)=>e+t,callExport:u},gojs:{"runtime.wasmExit":e=>{e>>>=0;let t=this.mem.getInt32(e+8,!0);this.exited=!0,delete this._inst,delete this._values,delete this._goRefCounts,delete this._ids,delete this._idPool,this.exit(t)},"runtime.wasmWrite":e=>{e>>>=0;let n=t(e+8),i=t(e+16),a=this.mem.getInt32(e+24,!0);r.fs.writeSync(n,new Uint8Array(this._inst.exports.mem.buffer,i,a))},"runtime.resetMemoryDataView":e=>{e>>>=0,this.mem=new DataView(this._inst.exports.mem.buffer)},"runtime.nanotime1":t=>{t>>>=0,e(t+8,(d+performance.now())*1e6)},"runtime.walltime":t=>{t>>>=0;let n=new Date().getTime();e(t+8,n/1e3),this.mem.setInt32(t+16,n%1e3*1e6,!0)},"runtime.scheduleTimeoutEvent":e=>{e>>>=0;let n=this._nextCallbackTimeoutID;this._nextCallbackTimeoutID++,this._scheduledTimeouts.set(n,setTimeout(()=>{for(this._resume();this._scheduledTimeouts.has(n);)console.warn(`scheduleTimeoutEvent: missed timeout event`),this._resume()},t(e+8))),this.mem.setInt32(e+16,n,!0)},"runtime.clearTimeoutEvent":e=>{e>>>=0;let t=this.mem.getInt32(e+8,!0);clearTimeout(this._scheduledTimeouts.get(t)),this._scheduledTimeouts.delete(t)},"runtime.getRandomData":e=>{e>>>=0,crypto.getRandomValues(s(e+8))},"syscall/js.finalizeRef":e=>{e>>>=0;let t=this.mem.getUint32(e+8,!0);if(this._goRefCounts[t]--,this._goRefCounts[t]===0){let e=this._values[t];this._values[t]=null,this._ids.delete(e),this._idPool.push(t)}},"syscall/js.stringVal":e=>{e>>>=0,o(e+24,l(e+8))},"syscall/js.valueGet":e=>{e>>>=0;let t=Reflect.get(a(e+8),l(e+16));e=this._inst.exports.getsp()>>>0,o(e+32,t)},"syscall/js.valueSet":e=>{e>>>=0,Reflect.set(a(e+8),l(e+16),a(e+32))},"syscall/js.valueDelete":e=>{e>>>=0,Reflect.deleteProperty(a(e+8),l(e+16))},"syscall/js.valueIndex":e=>{e>>>=0,o(e+24,Reflect.get(a(e+8),t(e+16)))},"syscall/js.valueSetIndex":e=>{e>>>=0,Reflect.set(a(e+8),t(e+16),a(e+24))},"syscall/js.valueCall":e=>{e>>>=0;try{let t=a(e+8),n=Reflect.get(t,l(e+16)),r=c(e+32),i=Reflect.apply(n,t,r);e=this._inst.exports.getsp()>>>0,o(e+56,i),this.mem.setUint8(e+64,1)}catch(t){e=this._inst.exports.getsp()>>>0,o(e+56,t),this.mem.setUint8(e+64,0)}},"syscall/js.valueInvoke":e=>{e>>>=0;try{let t=a(e+8),n=c(e+16),r=Reflect.apply(t,void 0,n);e=this._inst.exports.getsp()>>>0,o(e+40,r),this.mem.setUint8(e+48,1)}catch(t){e=this._inst.exports.getsp()>>>0,o(e+40,t),this.mem.setUint8(e+48,0)}},"syscall/js.valueNew":e=>{e>>>=0;try{let t=a(e+8),n=c(e+16),r=Reflect.construct(t,n);e=this._inst.exports.getsp()>>>0,o(e+40,r),this.mem.setUint8(e+48,1)}catch(t){e=this._inst.exports.getsp()>>>0,o(e+40,t),this.mem.setUint8(e+48,0)}},"syscall/js.valueLength":t=>{t>>>=0,e(t+16,parseInt(a(t+8).length))},"syscall/js.valuePrepareString":t=>{t>>>=0;let r=n.encode(String(a(t+8)));o(t+16,r),e(t+24,r.length)},"syscall/js.valueLoadString":e=>{e>>>=0;let t=a(e+8);s(e+16).set(t)},"syscall/js.valueInstanceOf":e=>{e>>>=0,this.mem.setUint8(e+24,+(a(e+8)instanceof a(e+16)))},"syscall/js.copyBytesToGo":t=>{t>>>=0;let n=s(t+8),r=a(t+32);if(!(r instanceof Uint8Array||r instanceof Uint8ClampedArray)){this.mem.setUint8(t+48,0);return}let i=r.subarray(0,n.length);n.set(i),e(t+40,i.length),this.mem.setUint8(t+48,1)},"syscall/js.copyBytesToJS":t=>{t>>>=0;let n=a(t+8),r=s(t+16);if(!(n instanceof Uint8Array||n instanceof Uint8ClampedArray)){this.mem.setUint8(t+48,0);return}let i=r.subarray(0,n.length);n.set(i),e(t+40,i.length),this.mem.setUint8(t+48,1)},debug:e=>{console.log(e)}}}}run(e){return t(this,null,function*(){if(!(e instanceof WebAssembly.Instance))throw Error(`Go.run: WebAssembly.Instance expected`);this._inst=e,this.mem=new DataView(this._inst.exports.mem.buffer),this._values=[NaN,0,null,!0,!1,r,this],this._goRefCounts=Array(this._values.length).fill(1/0),this._ids=new Map([[0,1],[null,2],[!0,3],[!1,4],[r,5],[this,6]]),this._idPool=[],this.exited=!1;let t=4096,i=e=>{let r=t,i=n.encode(e+`\0`);return new Uint8Array(this.mem.buffer,t,i.length).set(i),t+=i.length,t%8!=0&&(t+=8-t%8),r},a=this.argv.length,o=[];this.argv.forEach(e=>{o.push(i(e))}),o.push(0),Object.keys(this.env).sort().forEach(e=>{o.push(i(`${e}=${this.env[e]}`))}),o.push(0);let s=t;if(o.forEach(e=>{this.mem.setUint32(t,e,!0),this.mem.setUint32(t+4,0,!0),t+=8}),t>=12288)throw Error(`total length of command line and environment variables exceeds limit`);this._inst.exports.run(a,s),this.exited&&this._resolveExitPromise(),yield this._exitPromise})}_resume(){if(this.exited)throw Error(`Go program has already exited`);this._inst.exports.resume(),this.exited&&this._resolveExitPromise()}_makeFuncWrapper(e){let t=this;return function(){let n={id:e,this:this,args:arguments};return t._pendingEvent=n,t._resume(),n.result}}}})(),n=({data:t})=>{let a=new TextDecoder,o=r.fs,s=``;o.writeSync=(t,n)=>{if(t===1)e(n);else if(t===2){s+=a.decode(n);let e=s.split(`
|
|
5552
5552
|
`);e.length>1&&console.log(e.slice(0,-1).join(`
|
|
5553
5553
|
`)),s=e[e.length-1]}else throw Error(`Bad write`);return n.length};let c=[],l,u=0;n=({data:e})=>(e.length>0&&(c.push(e),l&&l()),d),o.read=(e,t,n,r,i,a)=>{if(e!==0||n!==0||r!==t.length||i!==null)throw Error(`Bad read`);if(c.length===0){l=()=>o.read(e,t,n,r,i,a);return}let s=c[0],d=Math.max(0,Math.min(r,s.length-u));t.set(s.subarray(u,u+d),n),u+=d,u===s.length&&(c.shift(),u=0),a(null,d)};let d=new r.Go;return d.argv=[``,`--service=0.28.1`],i(t,d).then(t=>{e(null),d.run(t)},t=>{e(t)}),d};function i(e,n){return t(this,null,function*(){if(e instanceof WebAssembly.Module)return WebAssembly.instantiate(e,n.importObject);let t=yield fetch(e);if(!t.ok)throw Error(`Failed to download ${JSON.stringify(e)}`);if(`instantiateStreaming`in WebAssembly&&/^application\/wasm($|;)/i.test(t.headers.get(`Content-Type`)||``))return(yield WebAssembly.instantiateStreaming(t,n.importObject)).instance;let r=yield t.arrayBuffer();return(yield WebAssembly.instantiate(r,n.importObject)).instance})}return e=>n(e)})(e=>r.onmessage({data:e})),t;r={onmessage:null,postMessage:n=>setTimeout(()=>{try{t=e({data:n})}catch(e){i(e)}}),terminate(){if(t)for(let e of t._scheduledTimeouts.values())clearTimeout(e)}}}let o,s,c=new Promise((e,t)=>{o=e,s=t});r.onmessage=({data:e})=>{r.onmessage=({data:e})=>u(e),e?s(e):o()},r.postMessage(t||new URL(e,location.href).toString());let{readFromStdout:u,service:d}=he({writeToStdin(e){r.postMessage(e)},isSync:!1,hasFS:!1,esbuild:l});yield c,Fe=()=>{r.terminate(),Pe=void 0,Fe=void 0,Ie=void 0},Ie={build:e=>new Promise((t,n)=>{a.then(n),d.buildOrContext({callName:`build`,refs:null,options:e,isTTY:!1,defaultWD:`/`,callback:(e,r)=>e?n(e):t(r)})}),context:e=>new Promise((t,n)=>{a.then(n),d.buildOrContext({callName:`context`,refs:null,options:e,isTTY:!1,defaultWD:`/`,callback:(e,r)=>e?n(e):t(r)})}),transform:(e,t)=>new Promise((n,r)=>{a.then(r),d.transform({callName:`transform`,refs:null,input:e,options:t||{},isTTY:!1,fs:{readFile(e,t){t(Error(`Internal error`),null)},writeFile(e,t){t(null)}},callback:(e,t)=>e?r(e):n(t)})}),formatMessages:(e,t)=>new Promise((n,r)=>{a.then(r),d.formatMessages({callName:`formatMessages`,refs:null,messages:e,options:t,callback:(e,t)=>e?r(e):n(t)})}),analyzeMetafile:(e,t)=>new Promise((n,r)=>{a.then(r),d.analyzeMetafile({callName:`analyzeMetafile`,refs:null,metafile:typeof e==`string`?e:JSON.stringify(e),options:t,callback:(e,t)=>e?r(e):n(t)})})}}),Be=l})(typeof t==`object`?t:{set exports(e){(typeof self<`u`?self:this).esbuild=e}})}))(),1);const SE=xE.version;let CE=null;async function wE(e={}){return CE||=EE(e.onProgress,e.ipk).catch(e=>{throw CE=null,e}),CE}async function TE(e){let t;try{t=await tn(`esbuild-wasm/package.json`,e.fromDir,e.reader)}catch{return null}if(t.type!==`file`)return null;let n=`${nt(t.path).dir}/esbuild.wasm`;if(!await e.reader.exists(n))return null;try{return await e.readBytes(n)}catch{return null}}async function EE(e,t){let n=e??(()=>{});if(cn())return n(`esbuild ready (node service)`),xE;if(!t)throw Error("esbuild-wasm is not available: install via `ipk add esbuild-wasm` or invoke through `ipx esbuild`");let r=await TE(t);if(!r)throw Error("esbuild-wasm is not installed in node_modules: run `ipk add esbuild-wasm` or invoke through `ipx esbuild`");n(`esbuild.wasm loaded from ipk node_modules (${r.byteLength} bytes)`);let i=await wn(r);return await xE.initialize({wasmModule:i,worker:!bn()}),n(`esbuild ready`),xE}function DE(e){let t=e.startsWith(`/`)?e:`/${e}`;return new URL(`file://${t}`).href}function OE(e){return e instanceof Error?e.message:String(e)}function kE(e){return`${(e&&e.length>0?e:`[eval]`).replace(/\.[^./]+$/,``)}.js`}async function AE(e,t,n,r){return(await(await e()).transform(t,{loader:`js`,format:`cjs`,sourcefile:kE(n),supported:{"dynamic-import":!1},define:{"import.meta.url":JSON.stringify(r)}})).code}async function jE(e,t,n,r){return(await(await e()).transform(t,{loader:`js`,format:`cjs`,sourcefile:kE(n),supported:{"dynamic-import":!1},...r?{define:{"import.meta.url":JSON.stringify(r)}}:{}})).code}const ME=/\bimport\s*\.\s*meta\s*\.\s*url\b/g,NE=/\bimport\s*\.\s*meta\b/g;function PE(e,t){let n=JSON.stringify(t);return e.replace(ME,n).replace(NE,`({ url: ${n} })`)}async function FE(e,t,n,r){let i=await e();return i.transpileModule(PE(t,r),{compilerOptions:{module:i.ModuleKind.CommonJS,target:i.ScriptTarget.ES2020,esModuleInterop:!0},fileName:`${n.replace(/\.[^./]+$/,``)}.ts`}).outputText}function IE(e={}){let{ipk:t}=e,n=e.loadEsbuild??(()=>wE(t?{ipk:t}:{})),r=e.loadTypeScript??(()=>fn(t));return async({source:e,path:t,kind:i})=>{if(i!==`esm`||!an(e))return e;let a=DE(t),o;try{return await AE(n,e,t,a)}catch(e){o=e}try{return await FE(r,e,t,a)}catch(e){throw Error(`Failed to transpile ESM module '${t}': ${OE(o)}; typescript fallback: ${OE(e)}`)}}}function LE(e={}){let{ipk:t}=e,n=e.loadEsbuild??(()=>wE(t?{ipk:t}:{})),r=e.loadTypeScript??(()=>fn(t));return async({source:e,filename:t})=>{if(!an(e)&&!Cn(e))return e;let i=typeof t==`string`&&t.startsWith(`/`),a=i?DE(t):void 0,o=i?t:`[eval].js`,s;try{return await jE(n,e,t,a)}catch(e){s=e}try{return await FE(r,e,o,a??``)}catch(e){throw Error(`Failed to transpile entry source: ${OE(s)}; typescript fallback: ${OE(e)}`)}}}function RE(e){if(!e.startsWith(`#!`))return e;let t=e.indexOf(`
|
|
5554
|
-
`);return t===-1?``:e.slice(t+1)}function zE(e){return nt(e).dir}const BE=[`node`,`require`,`default`],VE=[`node`,`import`,`default`],HE=/\brequire\s*\(\s*(['"`])([^'"`\s]+)\1\s*\)/g,UE=/\bimport\s*\(\s*(['"`])([^'"`\s]+)\1\s*\)/g,WE=/(?:^|[;\n}])\s*import\b[\s\S]*?\bfrom\s*(['"])([^'"]+)\1/g,GE=/(?:^|[;\n}])\s*export\b[\s\S]*?\bfrom\s*(['"])([^'"]+)\1/g,KE=/(?:^|[;\n}])\s*import\s*(['"])([^'"]+)\1/g;function qE(e,t,n){let r=t[0].indexOf(n);return r<0?!1:e.startsWith(n,t.index+r)}function JE(e){let t=Sn(e),n=new Map,r=(r,i,a)=>{r.lastIndex=0;let o;for(;(o=r.exec(e))!==null;){if(!qE(t,o,a))continue;let e=o[2];n.get(e)!==`import`&&n.set(e,i)}};return r(HE,`require`,`require`),r(UE,`import`,`import`),r(WE,`import`,`import`),r(GE,`import`,`export`),r(KE,`import`,`import`),[...n].map(([e,t])=>({specifier:e,kind:t}))}async function YE(e,t,n,r){if(n===`json`)return`module.exports = JSON.parse(${JSON.stringify(e)});\n`;let i=RE(e);if(n===`esm`){if(!r)throw Error(`Cannot load ESM module '${t}': no transpile hook configured (run: ipk install esbuild-wasm)`);return await r({source:i,path:t,kind:n})}return i}async function XE(e){let{entrySpecifiers:t,fromDir:n,reader:r,conditions:i,transpile:a}=e,o=e.requireConditions??BE,s=e.importConditions??VE,c=i??o,l=new Map,u=[],d={};async function f(e,t){if(l.has(e))return;let n=await r.readFile(e),i=await YE(n,e,t,a);l.set(e,{path:e,source:n,cjsSource:i,kind:t});let c=zE(e),p={};for(let{specifier:t,kind:i}of JE(n)){let n;try{n=await tn(t,c,r,{conditions:i===`import`?s:o})}catch(t){let n=t instanceof Error?t.message:String(t);throw Error(`While loading '${e}': ${n}`)}n.type===`file`&&(p[t]=n.path,await f(n.path,n.moduleKind))}d[e]=p,u.push(e)}let p={};for(let e of t){let t=await tn(e,n,r,{conditions:c});t.type===`file`&&(p[e]=t.path,await f(t.path,t.moduleKind))}return{files:u.map(e=>{let t=l.get(e);if(!t)throw Error(`module-loader: missing built module for '${e}'`);return t}),entryMap:p,edges:d}}function ZE(e){return!(e.startsWith(`sliccy:`)||e.startsWith(`node:`)||$t.has(e)||Uw.has(e))}async function QE(e){let{entryCode:t,fromDir:n,entryFilename:r,reader:i,transpile:a,transpileEntry:o}=e,s=new Map,c=[],l={},u={},d={};for(let{specifier:e,kind:r}of JE(t))if(ZE(e))try{let t=await XE({entrySpecifiers:[e],fromDir:n,reader:i,transpile:a,conditions:r===`import`?VE:BE,requireConditions:BE,importConditions:VE});for(let e of t.files)s.has(e.path)||(s.set(e.path,e),c.push(e.path));Object.assign(l,t.entryMap);for(let[e,n]of Object.entries(t.edges))u[e]={...u[e]??{},...n}}catch(t){d[e]=t instanceof Error?t.message:String(t)}let f;o&&(an(t)||Cn(t))&&(f=await o({source:t,filename:r??`[eval]`,fromDir:n}));let p={files:c.map(e=>{let t=s.get(e);if(!t)throw Error(`module-loader: missing built module for '${e}'`);return{path:t.path,cjsSource:t.cjsSource,kind:t.kind}}),entryMap:l,edges:u,errors:d};return f!==void 0&&(p.entrySource=f),p}function $E(){return globalThis.navigator?.hid??null}function eD(e){let t=e.collections?.[0];return t?`${t.usagePage??``}:${t.usage??``}`:``}function tD(e,t){return e===t||e.vendorId===t.vendorId&&e.productId===t.productId&&(e.productName??``)===(t.productName??``)&&eD(e)===eD(t)&&!!e.productName}var nD=class{byHandle=new Map;counter=0;register(e){for(let[t,n]of this.byHandle)if(tD(n,e))return this.byHandle.set(t,e),t;let t=`hid${++this.counter}`;return this.byHandle.set(t,e),t}get(e){return this.byHandle.get(e)}remove(e){return this.byHandle.delete(e)}list(){return[...this.byHandle].map(([e,t])=>({handle:e,device:t}))}};let rD=null;function iD(){return rD||=new nD,rD}const aD=4*1024*1024;function oD(e,t){let n=t.collections?.[0];return{handle:e,vendorId:t.vendorId,productId:t.productId,...t.productName?{productName:t.productName}:{},...n?.usagePage===void 0?{}:{usagePage:n.usagePage},...n?.usage===void 0?{}:{usage:n.usage},opened:t.opened}}function sD(e,t){let n=e.get(t);if(!n)throw Error(`unknown hid handle '${t}'`);return n}async function cD(e){e.opened||await e.open()}function lD(e,t){if(e>4194304)throw Error(`${t} exceeds the ${aD}-byte (4 MiB) v1 limit`)}function uD(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)),t}async function dD(e,t){return(await t.getDevices()).map(t=>oD(e.register(t),t))}async function fD(e,t,n){let r=await t.requestDevice({filters:n});if(r.length===0)throw Error(`No device selected.`);return r.map(t=>oD(e.register(t),t))}function pD(e,t){return oD(t,sD(e,t))}async function mD(e,t){await sD(e,t).open()}async function hD(e,t){await sD(e,t).close()}async function gD(e,t,n,r){lD(r.byteLength,`send report payload`);let i=sD(e,t);await cD(i),await i.sendReport(n,r)}async function _D(e,t,n,r){lD(r.byteLength,`send feature report payload`);let i=sD(e,t);await cD(i),await i.sendFeatureReport(n,r)}async function vD(e,t,n){let r=sD(e,t);return await cD(r),{reportId:n,bytes:uD(await r.receiveFeatureReport(n))}}async function yD(e,t,n){let r=sD(e,t);await cD(r);let i=e=>{n({reportId:e.reportId,bytes:uD(e.data)})};return r.addEventListener(`inputreport`,i),()=>r.removeEventListener(`inputreport`,i)}const bD=6e4;function xD(){return pe()}function SD(e){return new Promise(t=>{let n=!1,r=e=>{n||(n=!0,clearTimeout(i),t(e))},i=setTimeout(()=>r({cancelled:!0}),bD);fe(`hid-device`,e??[],void 0,{timeoutMs:bD}).then(e=>{let t=e;t.cancelled?r({cancelled:!0}):typeof t.error==`string`?r({error:t.error}):t.granted&&t.info?r({granted:!0,info:t.info}):r({error:`hid picker returned an unexpected response`})}).catch(e=>{r({error:e instanceof Error?e.message:`Failed to open HID picker`})})})}function CD(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}var wD=class{registry;constructor(e){this.registry=e}hid(){let e=$E();if(!e)throw Error(`WebHID is unavailable in this browser`);return e}list(){return dD(this.registry,this.hid())}async request(e){if(xD()){let t=await SD(e);if(`cancelled`in t)throw Error(`user cancelled the HID picker`);if(`error`in t)throw Error(t.error);let n=await this.reacquireAll(t.info);if(n.length===0)throw Error(`granted device could not be re-acquired`);return n.map(e=>oD(this.registry.register(e),e))}return fD(this.registry,this.hid(),e)}async reacquireAll(e){return(await this.hid().getDevices()).filter(t=>t.vendorId===e.vendorId&&t.productId===e.productId)}info(e){return Promise.resolve(pD(this.registry,e))}open(e){return mD(this.registry,e)}close(e){return hD(this.registry,e)}sendReport(e,t,n){return gD(this.registry,e,t,CD(n))}sendFeatureReport(e,t,n){return _D(this.registry,e,t,CD(n))}async receiveFeatureReport(e,t){let n=await vD(this.registry,e,t);return{reportId:n.reportId,bytes:new Uint8Array(n.bytes)}}async subscribeInputReports(e,t){return yD(this.registry,e,e=>t({reportId:e.reportId,bytes:new Uint8Array(e.bytes)}))}},TD=class e{rpc;constructor(e){this.rpc=e}static REQUEST_TIMEOUT_MS=5*6e4;async list(){return(await this.rpc.call(`hid-list`,void 0)).devices}async request(t){return(await this.rpc.call(`hid-request`,{filters:t},{timeoutMs:e.REQUEST_TIMEOUT_MS})).devices}async info(e){return(await this.rpc.call(`hid-device-info`,{handle:e})).device}async open(e){await this.rpc.call(`hid-open`,{handle:e})}async close(e){await this.rpc.call(`hid-close`,{handle:e})}async sendReport(e,t,n){await this.rpc.call(`hid-send-report`,{handle:e,reportId:t,bytes:CD(n)})}async sendFeatureReport(e,t,n){await this.rpc.call(`hid-send-feature-report`,{handle:e,reportId:t,bytes:CD(n)})}async receiveFeatureReport(e,t){let n=await this.rpc.call(`hid-receive-feature-report`,{handle:e,reportId:t});return{reportId:n.reportId,bytes:new Uint8Array(n.bytes)}}async subscribeInputReports(e,t){let n=this.rpc.onEvent(`hid-input-report`,n=>{let r=n;!r||r.handle!==e||t({reportId:r.reportId,bytes:new Uint8Array(r.bytes)})});try{await this.rpc.call(`hid-subscribe-input-reports`,{handle:e})}catch(e){throw n(),e}return async()=>{n();try{await this.rpc.call(`hid-unsubscribe-input-reports`,{handle:e})}catch{}}}};function ED(e,t){return e&&$E()?new wD(iD()):t?new TD(t):null}function DD(e){return async function(t,n){let r=t instanceof Request?t:null,i=OD(t),a=(n?.method??r?.method??`GET`).toUpperCase(),o=AD(r?.headers,n?.headers),s,c;if(n&&`body`in n&&n.body!==void 0)s=MD(n.body,a),c=n.body;else if(r&&a!==`GET`&&a!==`HEAD`){let e=await r.arrayBuffer();s=e.byteLength===0?void 0:new TextDecoder(`utf-8`).decode(new Uint8Array(e)),c=void 0}else s=void 0,c=void 0;c instanceof URLSearchParams&&o&&!jD(o,`content-type`)&&(o[`Content-Type`]=`application/x-www-form-urlencoded;charset=UTF-8`);let l=await e(i,{method:a,headers:o,body:s}),u=new Headers;for(let[e,t]of Object.entries(l.headers))try{u.set(e,t)}catch{}let d=l.status===204||l.status===205||l.status===304||!l.body||l.body.byteLength===0?null:l.body,f=new Response(d,{status:l.status,statusText:l.statusText,headers:u});try{Object.defineProperty(f,"url",{value:l.url||i,writable:!1,configurable:!0,enumerable:!1})}catch{}return f}}function OD(e){return typeof e==`string`?e:e instanceof URL?e.toString():e.url}function kD(e){if(e){if(e instanceof Headers){let t={};return e.forEach((e,n)=>{t[n]=e}),t}if(Array.isArray(e)){let t={};for(let[n,r]of e)t[n]=r;return t}return{...e}}}function AD(e,t){let n={};e&&e.forEach((e,t)=>{n[t]=e});let r=kD(t);if(r)for(let[e,t]of Object.entries(r))n[e]=t;return n}function jD(e,t){let n=t.toLowerCase();for(let t of Object.keys(e))if(t.toLowerCase()===n)return!0;return!1}function MD(e,t){if(e!=null&&!(t===`GET`||t===`HEAD`)){if(typeof e==`string`)return e;if(e instanceof URLSearchParams)return e.toString();if(e instanceof Uint8Array)return new TextDecoder(`utf-8`).decode(e);if(e instanceof ArrayBuffer)return new TextDecoder(`utf-8`).decode(new Uint8Array(e));if(ArrayBuffer.isView(e)){let t=e;return new TextDecoder(`utf-8`).decode(new Uint8Array(t.buffer,t.byteOffset,t.byteLength))}throw typeof Blob<`u`&&e instanceof Blob?Error(`node fetch shim: Blob request bodies are not supported (use a string, Uint8Array, or URLSearchParams)`):typeof FormData<`u`&&e instanceof FormData?Error(`node fetch shim: FormData request bodies are not supported (post raw application/x-www-form-urlencoded with URLSearchParams instead)`):typeof ReadableStream<`u`&&e instanceof ReadableStream?Error(`node fetch shim: ReadableStream request bodies are not supported (collect into a Uint8Array or string before calling fetch)`):Error(`node fetch shim: unsupported request body type (${Object.prototype.toString.call(e)}); use a string, Uint8Array, ArrayBuffer, or URLSearchParams`)}}function ND(){return globalThis.navigator?.serial??null}var PD=class{byHandle=new Map;counter=0;register(e){for(let[t,n]of this.byHandle)if(n.port===e)return t;let t=`serial${++this.counter}`;return this.byHandle.set(t,{port:e,opened:!1}),t}get(e){return this.byHandle.get(e)}remove(e){return this.byHandle.delete(e)}list(){return[...this.byHandle].map(([e,t])=>({handle:e,entry:t}))}};let FD=null;function ID(){return FD||=new PD,FD}const LD=4*1024*1024;function RD(e,t){let n=t.port.getInfo();return{handle:e,...n.usbVendorId===void 0?{}:{usbVendorId:n.usbVendorId},...n.usbProductId===void 0?{}:{usbProductId:n.usbProductId},opened:t.opened}}function zD(e,t){let n=e.get(t);if(!n)throw Error(`unknown serial handle '${t}'`);return n}function BD(e,t){let n=new Uint8Array(e.length+t.length);return n.set(e),n.set(t,e.length),n}function VD(e,t,n){if(t.length===0)return-1;outer:for(let r=Math.max(0,n);r+t.length<=e.length;r++){for(let n=0;n<t.length;n++)if(e[r+n]!==t[n])continue outer;return r}return-1}async function HD(e,t){return(await t.getPorts()).map(t=>{let n=e.register(t);return RD(n,e.get(n))})}async function UD(e,t,n){let r=await t.requestPort(n.length?{filters:n}:{}),i=e.register(r);return RD(i,e.get(i))}function WD(e,t){return RD(t,zD(e,t))}async function GD(e,t,n){let r=zD(e,t);await r.port.open(n),r.opened=!0}async function KD(e,t){let n=zD(e,t);if(n.reader){try{await n.reader.cancel()}catch{}try{n.reader.releaseLock()}catch{}n.reader=void 0}if(n.pendingRead=void 0,n.leftover=void 0,n.writer){try{n.writer.releaseLock()}catch{}n.writer=void 0}await n.port.close(),n.opened=!1}function qD(e){if(!e.reader){if(!e.port.readable)throw Error(`serial port is not readable (is it open?)`);e.reader=e.port.readable.getReader()}return e.reader}function JD(e){if(!e.writer){if(!e.port.writable)throw Error(`serial port is not writable (is it open?)`);e.writer=e.port.writable.getWriter()}return e.writer}async function YD(e,t,n){let r=zD(e,t),i=Math.min(n.maxBytes??4194304,LD),a=n.until?.length?n.until:void 0,o=n.timeoutMs??1e3,s=Date.now()+Math.max(0,o),c=r.leftover??new Uint8Array;r.leftover=void 0;let l=0,u=()=>{if(a){let e=VD(c,a,Math.max(0,l-(a.length-1)));if(e>=0){let t=e+a.length;return r.leftover=c.slice(t),c.slice(0,t)}}return c.length>=i?(r.leftover=c.slice(i),c.slice(0,i)):null},d=u();if(d)return d;let f=qD(r);for(;Date.now()<s;){let e=s-Date.now(),t=r.pendingRead??f.read();r.pendingRead=t;let n,i=new Promise(t=>{n=setTimeout(()=>t(`__timeout`),e)}),a;try{a=await Promise.race([t,i])}finally{n&&clearTimeout(n)}if(a===`__timeout`)break;if(r.pendingRead=void 0,a.done){r.reader=void 0;break}if(a.value?.length){l=c.length,c=BD(c,a.value);let e=u();if(e)return e}}return c}async function XD(e,t,n){if(n.length>4194304)throw Error(`serial write payload exceeds the ${LD}-byte (4 MiB) v1 limit`);return await JD(zD(e,t)).write(n),n.length}async function ZD(e,t){return zD(e,t).port.getSignals()}async function QD(e,t,n){await zD(e,t).port.setSignals(n)}const $D=6e4;function eO(){return pe()}function tO(e){return new Promise(t=>{let n=!1,r=e=>{n||(n=!0,clearTimeout(i),t(e))},i=setTimeout(()=>r({cancelled:!0}),$D);fe(`serial-port`,e??[],void 0,{timeoutMs:$D}).then(e=>{let t=e;t.cancelled?r({cancelled:!0}):typeof t.error==`string`?r({error:t.error}):t.granted&&t.info?r({granted:!0,info:t.info}):r({error:`serial picker returned an unexpected response`})}).catch(e=>{r({error:e instanceof Error?e.message:`Failed to open serial picker`})})})}function nO(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}var rO=class{registry;constructor(e){this.registry=e}serial(){let e=ND();if(!e)throw Error(`Web Serial is unavailable in this browser`);return e}list(){return HD(this.registry,this.serial())}async request(e){if(eO()){let t=await tO(e);if(`cancelled`in t)throw Error(`user cancelled the serial picker`);if(`error`in t)throw Error(t.error);let n=await this.reacquire(t.info);if(!n)throw Error(`granted port could not be re-acquired`);let r=this.registry.register(n);return RD(r,this.registry.get(r))}return UD(this.registry,this.serial(),e)}async reacquire(e){let t=await this.serial().getPorts(),n=t.filter(t=>{let n=t.getInfo();return!(e.usbVendorId!==void 0&&n.usbVendorId!==e.usbVendorId||e.usbProductId!==void 0&&n.usbProductId!==e.usbProductId)}),r=n.length?n:t,i=this.registry.list().map(e=>e.entry.port);return r.find(e=>!i.includes(e))??r[0]??null}info(e){return Promise.resolve(WD(this.registry,e))}open(e,t){return GD(this.registry,e,t)}close(e){return KD(this.registry,e)}read(e,t){return YD(this.registry,e,t)}write(e,t){return XD(this.registry,e,t)}getSignals(e){return ZD(this.registry,e)}setSignals(e,t){return QD(this.registry,e,t)}},iO=class e{rpc;constructor(e){this.rpc=e}static REQUEST_TIMEOUT_MS=5*6e4;static READ_MARGIN_MS=3e4;async list(){return(await this.rpc.call(`serial-list`,void 0)).devices}async request(t){return(await this.rpc.call(`serial-request`,{filters:t},{timeoutMs:e.REQUEST_TIMEOUT_MS})).device}async info(e){return(await this.rpc.call(`serial-device-info`,{handle:e})).device}async open(e,t){await this.rpc.call(`serial-open`,{handle:e,options:t})}async close(e){await this.rpc.call(`serial-close`,{handle:e})}async read(t,n){let r=(n.timeoutMs??1e3)+e.READ_MARGIN_MS,i=await this.rpc.call(`serial-read`,{handle:t,maxBytes:n.maxBytes,until:n.until?nO(n.until):void 0,timeoutMs:n.timeoutMs},{timeoutMs:r});return new Uint8Array(i.bytes)}async write(e,t){return(await this.rpc.call(`serial-write`,{handle:e,bytes:nO(t)})).bytesWritten}async getSignals(e){return(await this.rpc.call(`serial-get-signals`,{handle:e})).signals}async setSignals(e,t){await this.rpc.call(`serial-set-signals`,{handle:e,signals:t})}};function aO(e,t){return e&&ND()?new rO(ID()):t?new iO(t):null}function oO(){return globalThis.navigator?.usb??null}function sO(e,t){return e===t||e.vendorId===t.vendorId&&e.productId===t.productId&&(e.serialNumber??``)===(t.serialNumber??``)&&!!e.serialNumber}var cO=class{byHandle=new Map;counter=0;register(e){for(let[t,n]of this.byHandle)if(sO(n,e))return this.byHandle.set(t,e),t;let t=`usb${++this.counter}`;return this.byHandle.set(t,e),t}get(e){return this.byHandle.get(e)}remove(e){return this.byHandle.delete(e)}list(){return[...this.byHandle].map(([e,t])=>({handle:e,device:t}))}};let lO=null;function uO(){return lO||=new cO,lO}const dO=4*1024*1024;function fO(e,t){return{handle:e,vendorId:t.vendorId,productId:t.productId,...t.productName?{productName:t.productName}:{},...t.manufacturerName?{manufacturerName:t.manufacturerName}:{},...t.serialNumber?{serialNumber:t.serialNumber}:{},opened:t.opened}}function pO(e,t){let n=e.get(t);if(!n)throw Error(`unknown usb handle '${t}'`);return n}function mO(e,t){if(e>4194304)throw Error(`${t} exceeds the ${dO}-byte (4 MiB) v1 limit`)}function hO(e){return e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength)}async function gO(e,t){return(await t.getDevices()).map(t=>fO(e.register(t),t))}async function _O(e,t,n){let r=await t.requestDevice({filters:n});return fO(e.register(r),r)}function vO(e,t){return fO(t,pO(e,t))}async function yO(e,t){await pO(e,t).open()}async function bO(e,t){await pO(e,t).close()}async function xO(e,t,n){await pO(e,t).selectConfiguration(n)}async function SO(e,t,n){await pO(e,t).claimInterface(n)}async function CO(e,t,n){await pO(e,t).releaseInterface(n)}async function wO(e,t,n,r){mO(r,`control-in length`);let i=await pO(e,t).controlTransferIn(n,r);return{status:i.status??`ok`,bytes:i.data?hO(i.data):new ArrayBuffer(0)}}async function TO(e,t,n,r){mO(r.byteLength,`control-out payload`);let i=await pO(e,t).controlTransferOut(n,r);return{status:i.status??`ok`,bytesWritten:i.bytesWritten}}async function EO(e,t,n,r){mO(r,`transfer-in length`);let i=await pO(e,t).transferIn(n,r);return{status:i.status??`ok`,bytes:i.data?hO(i.data):new ArrayBuffer(0)}}async function DO(e,t,n,r){mO(r.byteLength,`transfer-out payload`);let i=await pO(e,t).transferOut(n,r);return{status:i.status??`ok`,bytesWritten:i.bytesWritten}}async function OO(e,t){await pO(e,t).reset()}const kO=6e4;function AO(){return pe()}function jO(e){return new Promise(t=>{let n=!1,r=e=>{n||(n=!0,clearTimeout(i),t(e))},i=setTimeout(()=>r({cancelled:!0}),kO);fe(`usb-device`,e??[],void 0,{timeoutMs:kO}).then(e=>{let t=e;t.cancelled?r({cancelled:!0}):typeof t.error==`string`?r({error:t.error}):t.granted&&t.info?r({granted:!0,info:t.info}):r({error:`usb picker returned an unexpected response`})}).catch(e=>{r({error:e instanceof Error?e.message:`Failed to open USB picker`})})})}function MO(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}var NO=class{registry;constructor(e){this.registry=e}usb(){let e=oO();if(!e)throw Error(`WebUSB is unavailable in this browser`);return e}list(){return gO(this.registry,this.usb())}async request(e){if(AO()){let t=await jO(e);if(`cancelled`in t)throw Error(`user cancelled the USB picker`);if(`error`in t)throw Error(t.error);let n=await this.reacquire(t.info);if(!n)throw Error(`granted device could not be re-acquired`);return fO(this.registry.register(n),n)}return _O(this.registry,this.usb(),e)}async reacquire(e){return(await this.usb().getDevices()).find(t=>t.vendorId===e.vendorId&&t.productId===e.productId&&(!e.serialNumber||t.serialNumber===e.serialNumber))??null}info(e){return Promise.resolve(vO(this.registry,e))}open(e){return yO(this.registry,e)}close(e){return bO(this.registry,e)}selectConfig(e,t){return xO(this.registry,e,t)}claim(e,t){return SO(this.registry,e,t)}release(e,t){return CO(this.registry,e,t)}async controlIn(e,t,n){let r=await wO(this.registry,e,t,n);return{status:r.status,bytes:new Uint8Array(r.bytes)}}controlOut(e,t,n){return TO(this.registry,e,t,MO(n))}async transferIn(e,t,n){let r=await EO(this.registry,e,t,n);return{status:r.status,bytes:new Uint8Array(r.bytes)}}transferOut(e,t,n){return DO(this.registry,e,t,MO(n))}reset(e){return OO(this.registry,e)}},PO=class e{rpc;constructor(e){this.rpc=e}static REQUEST_TIMEOUT_MS=5*6e4;async list(){return(await this.rpc.call(`usb-list`,void 0)).devices}async request(t){return(await this.rpc.call(`usb-request`,{filters:t},{timeoutMs:e.REQUEST_TIMEOUT_MS})).device}async info(e){return(await this.rpc.call(`usb-device-info`,{handle:e})).device}async open(e){await this.rpc.call(`usb-open`,{handle:e})}async close(e){await this.rpc.call(`usb-close`,{handle:e})}async selectConfig(e,t){await this.rpc.call(`usb-select-configuration`,{handle:e,configurationValue:t})}async claim(e,t){await this.rpc.call(`usb-claim-interface`,{handle:e,interfaceNumber:t})}async release(e,t){await this.rpc.call(`usb-release-interface`,{handle:e,interfaceNumber:t})}async controlIn(e,t,n){let r=await this.rpc.call(`usb-control-transfer-in`,{handle:e,setup:t,length:n});return{status:r.status,bytes:new Uint8Array(r.bytes)}}async controlOut(e,t,n){return this.rpc.call(`usb-control-transfer-out`,{handle:e,setup:t,bytes:MO(n)})}async transferIn(e,t,n){let r=await this.rpc.call(`usb-transfer-in`,{handle:e,endpointNumber:t,length:n});return{status:r.status,bytes:new Uint8Array(r.bytes)}}async transferOut(e,t,n){return this.rpc.call(`usb-transfer-out`,{handle:e,endpointNumber:t,bytes:MO(n)})}async reset(e){await this.rpc.call(`usb-reset`,{handle:e})}};function FO(e,t){return e&&oO()?new NO(uO()):t?new PO(t):null}const IO=new Map;function LO(e){let t=crypto.randomUUID();return IO.set(t,e),t}function RO(e){return IO.get(e)??null}function zO(e){IO.delete(e)}const BO=n(`realm-host`);function VO(e,t,n={}){let r=new Map,i=n.syncFsBridgeEnabled?LO({fs:t.fs,cwd:t.cwd}):void 0,a=!1,o={subscriptions:r,pushEvent:(t,n=[])=>{if(!a)try{e.postMessage(t,n)}catch{}}},s=new Map,c={spawns:s,opts:n},l=r=>{if(r.data?.type!==`realm-rpc-req`)return;let i=r.data;HO(e,i,t,n,o,c)};return e.addEventListener(`message`,l),e.start?.(),{syncFsToken:i,dispose:()=>{if(!a){a=!0,i&&zO(i),e.removeEventListener(`message`,l);for(let{controller:e}of s.values())try{e.signal.aborted||e.abort()}catch{}s.clear();for(let e of r.values())try{Promise.resolve(e()).catch(()=>{})}catch{}r.clear()}}}}async function HO(e,t,n,r,i,a){try{let o=await UO(t,n,r,i,a),s={type:`realm-rpc-res`,id:t.id,result:o},c=Ak(o);e.postMessage(s,c)}catch(n){let r=n instanceof Error?n.message:String(n),i={type:`realm-rpc-res`,id:t.id,error:r};e.postMessage(i)}}async function UO(e,t,n,r,i){switch(e.channel){case`vfs`:return YO(e.op,e.args,t);case`exec`:return ok(e.op,e.args,t,i);case`fetch`:return uk(e.op,e.args,t);case`browser`:return mk(e.op,e.args,WO(n),n);case`usb`:return Dk(e.op,e.args,KO(n));case`serial`:return Ok(e.op,e.args,qO(n));case`hid`:return kk(e.op,e.args,JO(n),r);case`module`:return fk(e.op,e.args,t);case`wasm`:return pk(e.op,e.args,t);default:throw Error(`realm-host: unknown channel '${e.channel}'`)}}function WO(e){if(e.browser)return e.browser;let t=globalThis;if(t.__slicc_browser)return t.__slicc_browser;throw Error(`browser is not available in this runtime`)}function GO(e){if(e.wsSubscribers)return e.wsSubscribers;let t=globalThis;if(t.__slicc_wsSubscribers)return t.__slicc_wsSubscribers;throw Error(`browser.websocket is not available in this runtime`)}function KO(e){if(e.usbBackend)return e.usbBackend;let t=FO(i(),r());if(!t)throw Error(`usb is not available in this runtime`);return t}function qO(e){if(e.serialBackend)return e.serialBackend;let t=aO(i(),r());if(!t)throw Error(`serial is not available in this runtime`);return t}function JO(e){if(e.hidBackend)return e.hidBackend;let t=ED(i(),r());if(!t)throw Error(`hid is not available in this runtime`);return t}async function YO(e,t,n){let r=typeof t[0]==`string`?t[0]:null,i=r===null?null:n.fs.resolvePath(n.cwd,r);switch(e){case`readFile`:return n.fs.readFile(i);case`readFileBinary`:return n.fs.readFileBuffer(i);case`writeFile`:return await n.fs.writeFile(i,t[1]),!0;case`writeFileBinary`:return await n.fs.writeFile(i,t[1]),!0;case`readDir`:return n.fs.readdir(i);case`exists`:return n.fs.exists(i);case`stat`:{let e=await n.fs.stat(i);return{isDirectory:e.isDirectory,isFile:e.isFile,size:e.size}}case`mkdir`:return await n.fs.mkdir(i,{recursive:!0}),!0;case`rm`:return await n.fs.rm(i,{recursive:!0}),!0;case`rename`:{let e=n.fs.resolvePath(n.cwd,t[1]),r=n.fs;if(r.rename)await r.rename(i,e);else{let t=await n.fs.readFileBuffer(i);await n.fs.writeFile(e,t),await n.fs.rm(i,{recursive:!0})}return!0}case`resolvePath`:return n.fs.resolvePath(n.cwd,t[0]);case`invalidatePaths`:{let e=t[0],r=n.fs;return r.invalidatePaths&&r.invalidatePaths(e),!0}case`snapshot`:return nk(n,typeof t[0]==`string`?t[0]:n.cwd);case`flushWrites`:{let e=t[0];return await rk(n,e),!0}default:throw Error(`realm-host: unknown vfs op '${e}'`)}}const XO=10485760;function ZO(e){return e.fileCount>=500||e.totalBytes>=XO}function QO(e){return e.entries.length>=2e4}async function $O(e,t,n,r){r.entries.push({path:t,content:new Uint8Array,isDirectory:!0});let i;try{i=await e.fs.readdir(t)}catch{return}for(let e of i)e!==`node_modules`&&n.push(t===`/`?`/${e}`:`${t}/${e}`)}async function ek(e,t,n,r){if(n>1048576||ZO(r)||r.totalBytes+n>XO){r.entries.push({path:t,content:new Uint8Array,isDirectory:!1,truncated:!0,size:n});return}let i=await e.fs.readFileBuffer(t);r.entries.push({path:t,content:i,isDirectory:!1}),r.fileCount+=1,r.totalBytes+=i.byteLength}async function tk(e,t,n){if(QO(n)||!await e.fs.exists(t))return;let r=[t];for(;r.length>0;){if(QO(n))return;let t=r.pop(),i;try{i=await e.fs.stat(t)}catch{continue}i.isDirectory?await $O(e,t,r,n):i.isFile&&await ek(e,t,i.size,n)}}async function nk(e,t){let n={entries:[],totalBytes:0,fileCount:0};return await tk(e,t,n),t!==`/tmp`&&await tk(e,`/tmp`,n),{entries:n.entries}}async function rk(e,t){for(let n of t.deleted)await e.fs.rm(n,{recursive:!0});for(let n of t.created)n.isDirectory?await e.fs.mkdir(n.path,{recursive:!0}):await e.fs.writeFile(n.path,n.content);for(let n of t.modified)await e.fs.writeFile(n.path,n.content)}const ik=new Set([`SIGINT`,`SIGTERM`,`SIGKILL`,`SIGSTOP`,`SIGCONT`]),ak=new Set([`SIGINT`,`SIGTERM`,`SIGKILL`]);async function ok(e,t,n,r){if(!n.exec)throw Error(`exec is not available in this runtime`);if(e===`run`){let e=t[0],r=await n.exec(e,{cwd:n.cwd});return{stdout:r.stdout,stderr:r.stderr,exitCode:r.exitCode}}if(e===`spawn`){let e=t[0];if(!Array.isArray(e)||e.length===0||!e.every(e=>typeof e==`string`))throw Error(`exec.spawn: argv must be a non-empty string[]`);let[r,...i]=e,a=await n.exec(r,{cwd:n.cwd,args:i});return{stdout:a.stdout,stderr:a.stderr,exitCode:a.exitCode}}if(e===`start`)return ck(t,n,r);if(e===`kill`)return lk(t,r);throw Error(`realm-host: unknown exec op '${e}'`)}function sk(e){if(e.stdin!==void 0&&typeof e.stdin!=`string`)throw Error(`exec.start: stdin must be a string`);if(e.stdinKind!==void 0&&e.stdinKind!==`text`&&e.stdinKind!==`bytes`)throw Error(`exec.start: stdinKind must be 'text' or 'bytes'`);if(e.args!==void 0&&(!Array.isArray(e.args)||!e.args.every(e=>typeof e==`string`)))throw Error(`exec.start: args must be a string[]`)}async function ck(e,t,n){let[r,i,a]=e;if(typeof r!=`number`)throw Error(`exec.start: spawnId must be a number`);if(n.spawns.has(r))throw Error(`exec.start: spawnId ${r} is already in use`);let o,s,c;if(Array.isArray(i)){if(i.length===0||!i.every(e=>typeof e==`string`))throw Error(`exec.start: argv must be a non-empty string[]`);[o,...s]=i,c=i.slice()}else if(typeof i==`string`)o=i,c=[i];else throw Error(`exec.start: command must be a string or a non-empty string[]`);let l=a??{};sk(l);let u=new AbortController,{pm:d,owner:f}=n.opts,p=0;d&&f&&(p=d.spawn({kind:`shell`,argv:c,cwd:t.cwd,owner:f,...n.opts.ppid===void 0?{}:{ppid:n.opts.ppid},adoptAbort:u}).pid),n.spawns.set(r,{controller:u,pid:p});let m;try{let e={cwd:t.cwd,signal:u.signal};return l.stdin!==void 0&&(e.stdin=l.stdin),l.stdinKind!==void 0&&(e.stdinKind=l.stdinKind),s===void 0?l.args!==void 0&&(e.args=l.args):e.args=s,m=await t.exec(o,e),{stdout:m.stdout,stderr:m.stderr,exitCode:m.exitCode}}finally{if(n.spawns.delete(r),d&&p){let e=d.get(p);d.exit(p,e?.terminatedBy?null:m?.exitCode??1)}}}function lk(e,t){let[n,r]=e,i=t.spawns.get(n);if(!i)return!1;let a=typeof r==`string`&&ik.has(r)?r:`SIGTERM`;ak.has(a)&&!i.controller.signal.aborted&&i.controller.abort();let{pm:o}=t.opts;return o&&i.pid?o.signal(i.pid,a):!0}async function uk(e,t,n){if(e!==`request`)throw Error(`realm-host: unknown fetch op '${e}'`);let[r,i]=t,a=await(n.fetch?DD(n.fetch):globalThis.fetch.bind(globalThis))(r,i),o={};a.headers.forEach((e,t)=>{o[t]=e});let s=new Uint8Array(await a.arrayBuffer());return{status:a.status,statusText:a.statusText,headers:o,body:s,url:a.url}}function dk(e){let t=t=>e.fs.resolvePath(e.cwd,t);return{exists:n=>e.fs.exists(t(n)),isDirectory:async n=>{try{return(await e.fs.stat(t(n))).isDirectory}catch{return!1}},readFile:async n=>{let r=await e.fs.readFile(t(n));return typeof r==`string`?r:new TextDecoder().decode(r)}}}async function fk(e,t,n){if(e!==`buildGraph`)throw Error(`realm-host: unknown module op '${e}'`);let r=typeof t[0]==`string`?t[0]:``,i=typeof t[1]==`string`&&t[1]?t[1]:n.cwd,a=typeof t[2]==`string`?t[2]:``,o=dk(n),s={reader:o,readBytes:e=>n.fs.readFileBuffer(e),fromDir:i};return QE({entryCode:r,fromDir:i,entryFilename:a,reader:o,transpile:IE({ipk:s}),transpileEntry:LE({ipk:s})})}async function pk(e,t,n){if(e!==`compile`)throw Error(`realm-host: unknown wasm op '${e}'`);let r=typeof t[0]==`string`?t[0]:null;if(r===null)throw Error(`realm-host: wasm.compile requires a path argument`);return Tn(e=>n.fs.readFileBuffer(e),n.fs.resolvePath(n.cwd,r))}async function mk(e,t,n,r){switch(e){case`findTab`:return _k(n,t[0]??{});case`ensureTab`:{let e=t[0];return vk(n,e,t[1]??{})}case`eval`:{let e=t[0],r=t[1];return yk(n,e,r,!1)}case`evalAsync`:{let e=t[0],r=t[1];return yk(n,e,r,!0)}case`cookie`:{let e=t[0],r=t[1];return Ck(n,e,r)}case`localStorage`:{let e=t[0],r=t[1];return wk(n,e,r)}case`wsObserve`:{let e={...t[0],scoopJid:r.scoopJid};return await GO(r).observe(e)}case`wsUpdate`:{let e=t[0],n=t[1]??{};return GO(r).update(e,n)}case`wsClose`:{let e=t[0];return GO(r).close(e)}case`wsList`:return GO(r).list();case`createTab`:{let e=t[0];return n.createPage(e)}case`closeTab`:{let e=t[0];return n.closePage(e)}case`setViewport`:{let e=t[0],r=t[1],i=t[2];return n.withTab(e,async()=>{await n.sendCDP(`Emulation.setDeviceMetricsOverride`,{width:r,height:i,deviceScaleFactor:1,mobile:!1})})}case`navigateTab`:{let e=t[0],r=t[1];return n.withTab(e,async()=>{await n.navigate(r)})}case`screenshotTab`:{let e=t[0],r=t[1];return n.withTab(e,async()=>(await n.bringToFront(),n.screenshot(r)))}case`waitForLoadState`:{let e=t[0],r=t[1];return Sk(n,e,r)}default:throw Error(`realm-host: unknown browser op '${e}'`)}}function hk(){try{let e=globalThis.localStorage;return e?!!(e.getItem(`slicc.trayWorkerBaseUrl`)||e.getItem(`slicc.trayJoinUrl`)):!1}catch{return!1}}async function gk(e){if(typeof e.listAllTargets!=`function`)return(await e.listPages()).map(e=>({targetId:e.targetId,url:e.url,title:e.title}));let t=(await e.listAllTargets()).map(e=>({targetId:e.targetId,url:e.url,title:e.title})),n=hk()?r():null;if(n)try{let{targets:e}=await n.call(`list-remote-targets`,void 0,{timeoutMs:3e3}),r=new Set(t.map(e=>e.targetId));for(let n of e)r.has(n.targetId)||(r.add(n.targetId),t.push({targetId:n.targetId,url:n.url,title:n.title}))}catch(e){BO.debug(`panel-rpc list-remote-targets failed`,{err:String(e)})}return t}async function _k(e,t){let n=await gk(e);if(t.domain){let e=t.domain.toLowerCase();for(let t of n){let n=Tk(t.url);if(n&&n.toLowerCase()===e)return t}return null}if(t.urlMatch){let e;try{e=new RegExp(t.urlMatch)}catch(e){throw Error(`browser.findTab: invalid urlMatch regex: ${e instanceof Error?e.message:String(e)}`)}for(let t of n)if(e.test(t.url))return t;return null}throw Error("browser.findTab: query requires `domain` or `urlMatch`")}async function vk(e,t,n){let r=await gk(e);if(n.matchUrl){let e;try{e=new RegExp(n.matchUrl)}catch(e){throw Error(`browser.ensureTab: invalid matchUrl regex: ${e instanceof Error?e.message:String(e)}`)}let t=r.find(t=>e.test(t.url));if(t)return t}else{let e=Ek(t);if(e){let t=r.find(t=>Ek(t.url)===e);if(t)return t}}return{targetId:await e.createPage(t),url:t,title:``}}async function yk(e,t,n,r){return e.withTab(t,async()=>bk(await e.evaluate(n,{awaitPromise:r,returnByValue:!0})))}function bk(e){if(typeof e!=`string`)return e;let t=xk(e);if(t===void 0)return e;if(typeof t==`object`&&t)return t;if(typeof t==`string`){let e=t.trim();if(e.length>0&&(e[0]===`{`||e[0]===`[`)){let e=xk(t);if(typeof e==`object`&&e)return e}return t}return e}function xk(e){let t=e.trim();if(t.length===0)return;let n=t[0];if(n===`{`||n===`[`||n===`"`||n===`-`||n>=`0`&&n<=`9`||t===`true`||t===`false`||t===`null`)try{return JSON.parse(t)}catch{return}}async function Sk(e,t,n){if(n===`networkidle`)return e.withTab(t,async()=>{for(let t=0;t<20;t++)if(await new Promise(e=>setTimeout(e,250)),await e.evaluate(`(function(){
|
|
5554
|
+
`);return t===-1?``:e.slice(t+1)}function zE(e){return nt(e).dir}const BE=[`node`,`require`,`default`],VE=[`node`,`import`,`default`],HE=/\brequire\s*\(\s*(['"`])([^'"`\s]+)\1\s*\)/g,UE=/\bimport\s*\(\s*(['"`])([^'"`\s]+)\1\s*\)/g,WE=/(?:^|[;\n}])\s*import\b[\s\S]*?\bfrom\s*(['"])([^'"]+)\1/g,GE=/(?:^|[;\n}])\s*export\b[\s\S]*?\bfrom\s*(['"])([^'"]+)\1/g,KE=/(?:^|[;\n}])\s*import\s*(['"])([^'"]+)\1/g;function qE(e,t,n){let r=t[0].indexOf(n);return r<0?!1:e.startsWith(n,t.index+r)}function JE(e){let t=Sn(e),n=new Map,r=(r,i,a)=>{r.lastIndex=0;let o;for(;(o=r.exec(e))!==null;){if(!qE(t,o,a))continue;let e=o[2];n.get(e)!==`import`&&n.set(e,i)}};return r(HE,`require`,`require`),r(UE,`import`,`import`),r(WE,`import`,`import`),r(GE,`import`,`export`),r(KE,`import`,`import`),[...n].map(([e,t])=>({specifier:e,kind:t}))}async function YE(e,t,n,r){if(n===`json`)return`module.exports = JSON.parse(${JSON.stringify(e)});\n`;let i=RE(e);if(n===`esm`){if(!r)throw Error(`Cannot load ESM module '${t}': no transpile hook configured (run: ipk install esbuild-wasm)`);return await r({source:i,path:t,kind:n})}return i}async function XE(e){let{entrySpecifiers:t,fromDir:n,reader:r,conditions:i,transpile:a}=e,o=e.requireConditions??BE,s=e.importConditions??VE,c=i??o,l=new Map,u=[],d={};async function f(e,t){if(l.has(e))return;let n=await r.readFile(e),i=await YE(n,e,t,a);l.set(e,{path:e,source:n,cjsSource:i,kind:t});let c=zE(e),p={};for(let{specifier:t,kind:i}of JE(n)){let n;try{n=await tn(t,c,r,{conditions:i===`import`?s:o})}catch(t){let n=t instanceof Error?t.message:String(t);throw Error(`While loading '${e}': ${n}`)}n.type===`file`&&(p[t]=n.path,await f(n.path,n.moduleKind))}d[e]=p,u.push(e)}let p={};for(let e of t){let t=await tn(e,n,r,{conditions:c});t.type===`file`&&(p[e]=t.path,await f(t.path,t.moduleKind))}return{files:u.map(e=>{let t=l.get(e);if(!t)throw Error(`module-loader: missing built module for '${e}'`);return t}),entryMap:p,edges:d}}function ZE(e){return!(e.startsWith(`sliccy:`)||e.startsWith(`node:`)||$t.has(e)||OT.has(e))}async function QE(e){let{entryCode:t,fromDir:n,entryFilename:r,reader:i,transpile:a,transpileEntry:o}=e,s=new Map,c=[],l={},u={},d={};for(let{specifier:e,kind:r}of JE(t))if(ZE(e))try{let t=await XE({entrySpecifiers:[e],fromDir:n,reader:i,transpile:a,conditions:r===`import`?VE:BE,requireConditions:BE,importConditions:VE});for(let e of t.files)s.has(e.path)||(s.set(e.path,e),c.push(e.path));Object.assign(l,t.entryMap);for(let[e,n]of Object.entries(t.edges))u[e]={...u[e]??{},...n}}catch(t){d[e]=t instanceof Error?t.message:String(t)}let f;o&&(an(t)||Cn(t))&&(f=await o({source:t,filename:r??`[eval]`,fromDir:n}));let p={files:c.map(e=>{let t=s.get(e);if(!t)throw Error(`module-loader: missing built module for '${e}'`);return{path:t.path,cjsSource:t.cjsSource,kind:t.kind}}),entryMap:l,edges:u,errors:d};return f!==void 0&&(p.entrySource=f),p}function $E(){return globalThis.navigator?.hid??null}function eD(e){let t=e.collections?.[0];return t?`${t.usagePage??``}:${t.usage??``}`:``}function tD(e,t){return e===t||e.vendorId===t.vendorId&&e.productId===t.productId&&(e.productName??``)===(t.productName??``)&&eD(e)===eD(t)&&!!e.productName}var nD=class{byHandle=new Map;counter=0;register(e){for(let[t,n]of this.byHandle)if(tD(n,e))return this.byHandle.set(t,e),t;let t=`hid${++this.counter}`;return this.byHandle.set(t,e),t}get(e){return this.byHandle.get(e)}remove(e){return this.byHandle.delete(e)}list(){return[...this.byHandle].map(([e,t])=>({handle:e,device:t}))}};let rD=null;function iD(){return rD||=new nD,rD}const aD=4*1024*1024;function oD(e,t){let n=t.collections?.[0];return{handle:e,vendorId:t.vendorId,productId:t.productId,...t.productName?{productName:t.productName}:{},...n?.usagePage===void 0?{}:{usagePage:n.usagePage},...n?.usage===void 0?{}:{usage:n.usage},opened:t.opened}}function sD(e,t){let n=e.get(t);if(!n)throw Error(`unknown hid handle '${t}'`);return n}async function cD(e){e.opened||await e.open()}function lD(e,t){if(e>4194304)throw Error(`${t} exceeds the ${aD}-byte (4 MiB) v1 limit`)}function uD(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)),t}async function dD(e,t){return(await t.getDevices()).map(t=>oD(e.register(t),t))}async function fD(e,t,n){let r=await t.requestDevice({filters:n});if(r.length===0)throw Error(`No device selected.`);return r.map(t=>oD(e.register(t),t))}function pD(e,t){return oD(t,sD(e,t))}async function mD(e,t){await sD(e,t).open()}async function hD(e,t){await sD(e,t).close()}async function gD(e,t,n,r){lD(r.byteLength,`send report payload`);let i=sD(e,t);await cD(i),await i.sendReport(n,r)}async function _D(e,t,n,r){lD(r.byteLength,`send feature report payload`);let i=sD(e,t);await cD(i),await i.sendFeatureReport(n,r)}async function vD(e,t,n){let r=sD(e,t);return await cD(r),{reportId:n,bytes:uD(await r.receiveFeatureReport(n))}}async function yD(e,t,n){let r=sD(e,t);await cD(r);let i=e=>{n({reportId:e.reportId,bytes:uD(e.data)})};return r.addEventListener(`inputreport`,i),()=>r.removeEventListener(`inputreport`,i)}const bD=6e4;function xD(){return pe()}function SD(e){return new Promise(t=>{let n=!1,r=e=>{n||(n=!0,clearTimeout(i),t(e))},i=setTimeout(()=>r({cancelled:!0}),bD);fe(`hid-device`,e??[],void 0,{timeoutMs:bD}).then(e=>{let t=e;t.cancelled?r({cancelled:!0}):typeof t.error==`string`?r({error:t.error}):t.granted&&t.info?r({granted:!0,info:t.info}):r({error:`hid picker returned an unexpected response`})}).catch(e=>{r({error:e instanceof Error?e.message:`Failed to open HID picker`})})})}function CD(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}var wD=class{registry;constructor(e){this.registry=e}hid(){let e=$E();if(!e)throw Error(`WebHID is unavailable in this browser`);return e}list(){return dD(this.registry,this.hid())}async request(e){if(xD()){let t=await SD(e);if(`cancelled`in t)throw Error(`user cancelled the HID picker`);if(`error`in t)throw Error(t.error);let n=await this.reacquireAll(t.info);if(n.length===0)throw Error(`granted device could not be re-acquired`);return n.map(e=>oD(this.registry.register(e),e))}return fD(this.registry,this.hid(),e)}async reacquireAll(e){return(await this.hid().getDevices()).filter(t=>t.vendorId===e.vendorId&&t.productId===e.productId)}info(e){return Promise.resolve(pD(this.registry,e))}open(e){return mD(this.registry,e)}close(e){return hD(this.registry,e)}sendReport(e,t,n){return gD(this.registry,e,t,CD(n))}sendFeatureReport(e,t,n){return _D(this.registry,e,t,CD(n))}async receiveFeatureReport(e,t){let n=await vD(this.registry,e,t);return{reportId:n.reportId,bytes:new Uint8Array(n.bytes)}}async subscribeInputReports(e,t){return yD(this.registry,e,e=>t({reportId:e.reportId,bytes:new Uint8Array(e.bytes)}))}},TD=class e{rpc;constructor(e){this.rpc=e}static REQUEST_TIMEOUT_MS=5*6e4;async list(){return(await this.rpc.call(`hid-list`,void 0)).devices}async request(t){return(await this.rpc.call(`hid-request`,{filters:t},{timeoutMs:e.REQUEST_TIMEOUT_MS})).devices}async info(e){return(await this.rpc.call(`hid-device-info`,{handle:e})).device}async open(e){await this.rpc.call(`hid-open`,{handle:e})}async close(e){await this.rpc.call(`hid-close`,{handle:e})}async sendReport(e,t,n){await this.rpc.call(`hid-send-report`,{handle:e,reportId:t,bytes:CD(n)})}async sendFeatureReport(e,t,n){await this.rpc.call(`hid-send-feature-report`,{handle:e,reportId:t,bytes:CD(n)})}async receiveFeatureReport(e,t){let n=await this.rpc.call(`hid-receive-feature-report`,{handle:e,reportId:t});return{reportId:n.reportId,bytes:new Uint8Array(n.bytes)}}async subscribeInputReports(e,t){let n=this.rpc.onEvent(`hid-input-report`,n=>{let r=n;!r||r.handle!==e||t({reportId:r.reportId,bytes:new Uint8Array(r.bytes)})});try{await this.rpc.call(`hid-subscribe-input-reports`,{handle:e})}catch(e){throw n(),e}return async()=>{n();try{await this.rpc.call(`hid-unsubscribe-input-reports`,{handle:e})}catch{}}}};function ED(e,t){return e&&$E()?new wD(iD()):t?new TD(t):null}function DD(e){return async function(t,n){let r=t instanceof Request?t:null,i=OD(t),a=(n?.method??r?.method??`GET`).toUpperCase(),o=AD(r?.headers,n?.headers),s,c;if(n&&`body`in n&&n.body!==void 0)s=MD(n.body,a),c=n.body;else if(r&&a!==`GET`&&a!==`HEAD`){let e=await r.arrayBuffer();s=e.byteLength===0?void 0:new TextDecoder(`utf-8`).decode(new Uint8Array(e)),c=void 0}else s=void 0,c=void 0;c instanceof URLSearchParams&&o&&!jD(o,`content-type`)&&(o[`Content-Type`]=`application/x-www-form-urlencoded;charset=UTF-8`);let l=await e(i,{method:a,headers:o,body:s}),u=new Headers;for(let[e,t]of Object.entries(l.headers))try{u.set(e,t)}catch{}let d=l.status===204||l.status===205||l.status===304||!l.body||l.body.byteLength===0?null:l.body,f=new Response(d,{status:l.status,statusText:l.statusText,headers:u});try{Object.defineProperty(f,"url",{value:l.url||i,writable:!1,configurable:!0,enumerable:!1})}catch{}return f}}function OD(e){return typeof e==`string`?e:e instanceof URL?e.toString():e.url}function kD(e){if(e){if(e instanceof Headers){let t={};return e.forEach((e,n)=>{t[n]=e}),t}if(Array.isArray(e)){let t={};for(let[n,r]of e)t[n]=r;return t}return{...e}}}function AD(e,t){let n={};e&&e.forEach((e,t)=>{n[t]=e});let r=kD(t);if(r)for(let[e,t]of Object.entries(r))n[e]=t;return n}function jD(e,t){let n=t.toLowerCase();for(let t of Object.keys(e))if(t.toLowerCase()===n)return!0;return!1}function MD(e,t){if(e!=null&&!(t===`GET`||t===`HEAD`)){if(typeof e==`string`)return e;if(e instanceof URLSearchParams)return e.toString();if(e instanceof Uint8Array)return new TextDecoder(`utf-8`).decode(e);if(e instanceof ArrayBuffer)return new TextDecoder(`utf-8`).decode(new Uint8Array(e));if(ArrayBuffer.isView(e)){let t=e;return new TextDecoder(`utf-8`).decode(new Uint8Array(t.buffer,t.byteOffset,t.byteLength))}throw typeof Blob<`u`&&e instanceof Blob?Error(`node fetch shim: Blob request bodies are not supported (use a string, Uint8Array, or URLSearchParams)`):typeof FormData<`u`&&e instanceof FormData?Error(`node fetch shim: FormData request bodies are not supported (post raw application/x-www-form-urlencoded with URLSearchParams instead)`):typeof ReadableStream<`u`&&e instanceof ReadableStream?Error(`node fetch shim: ReadableStream request bodies are not supported (collect into a Uint8Array or string before calling fetch)`):Error(`node fetch shim: unsupported request body type (${Object.prototype.toString.call(e)}); use a string, Uint8Array, ArrayBuffer, or URLSearchParams`)}}function ND(){return globalThis.navigator?.serial??null}var PD=class{byHandle=new Map;counter=0;register(e){for(let[t,n]of this.byHandle)if(n.port===e)return t;let t=`serial${++this.counter}`;return this.byHandle.set(t,{port:e,opened:!1}),t}get(e){return this.byHandle.get(e)}remove(e){return this.byHandle.delete(e)}list(){return[...this.byHandle].map(([e,t])=>({handle:e,entry:t}))}};let FD=null;function ID(){return FD||=new PD,FD}const LD=4*1024*1024;function RD(e,t){let n=t.port.getInfo();return{handle:e,...n.usbVendorId===void 0?{}:{usbVendorId:n.usbVendorId},...n.usbProductId===void 0?{}:{usbProductId:n.usbProductId},opened:t.opened}}function zD(e,t){let n=e.get(t);if(!n)throw Error(`unknown serial handle '${t}'`);return n}function BD(e,t){let n=new Uint8Array(e.length+t.length);return n.set(e),n.set(t,e.length),n}function VD(e,t,n){if(t.length===0)return-1;outer:for(let r=Math.max(0,n);r+t.length<=e.length;r++){for(let n=0;n<t.length;n++)if(e[r+n]!==t[n])continue outer;return r}return-1}async function HD(e,t){return(await t.getPorts()).map(t=>{let n=e.register(t);return RD(n,e.get(n))})}async function UD(e,t,n){let r=await t.requestPort(n.length?{filters:n}:{}),i=e.register(r);return RD(i,e.get(i))}function WD(e,t){return RD(t,zD(e,t))}async function GD(e,t,n){let r=zD(e,t);await r.port.open(n),r.opened=!0}async function KD(e,t){let n=zD(e,t);if(n.reader){try{await n.reader.cancel()}catch{}try{n.reader.releaseLock()}catch{}n.reader=void 0}if(n.pendingRead=void 0,n.leftover=void 0,n.writer){try{n.writer.releaseLock()}catch{}n.writer=void 0}await n.port.close(),n.opened=!1}function qD(e){if(!e.reader){if(!e.port.readable)throw Error(`serial port is not readable (is it open?)`);e.reader=e.port.readable.getReader()}return e.reader}function JD(e){if(!e.writer){if(!e.port.writable)throw Error(`serial port is not writable (is it open?)`);e.writer=e.port.writable.getWriter()}return e.writer}async function YD(e,t,n){let r=zD(e,t),i=Math.min(n.maxBytes??4194304,LD),a=n.until?.length?n.until:void 0,o=n.timeoutMs??1e3,s=Date.now()+Math.max(0,o),c=r.leftover??new Uint8Array;r.leftover=void 0;let l=0,u=()=>{if(a){let e=VD(c,a,Math.max(0,l-(a.length-1)));if(e>=0){let t=e+a.length;return r.leftover=c.slice(t),c.slice(0,t)}}return c.length>=i?(r.leftover=c.slice(i),c.slice(0,i)):null},d=u();if(d)return d;let f=qD(r);for(;Date.now()<s;){let e=s-Date.now(),t=r.pendingRead??f.read();r.pendingRead=t;let n,i=new Promise(t=>{n=setTimeout(()=>t(`__timeout`),e)}),a;try{a=await Promise.race([t,i])}finally{n&&clearTimeout(n)}if(a===`__timeout`)break;if(r.pendingRead=void 0,a.done){r.reader=void 0;break}if(a.value?.length){l=c.length,c=BD(c,a.value);let e=u();if(e)return e}}return c}async function XD(e,t,n){if(n.length>4194304)throw Error(`serial write payload exceeds the ${LD}-byte (4 MiB) v1 limit`);return await JD(zD(e,t)).write(n),n.length}async function ZD(e,t){return zD(e,t).port.getSignals()}async function QD(e,t,n){await zD(e,t).port.setSignals(n)}const $D=6e4;function eO(){return pe()}function tO(e){return new Promise(t=>{let n=!1,r=e=>{n||(n=!0,clearTimeout(i),t(e))},i=setTimeout(()=>r({cancelled:!0}),$D);fe(`serial-port`,e??[],void 0,{timeoutMs:$D}).then(e=>{let t=e;t.cancelled?r({cancelled:!0}):typeof t.error==`string`?r({error:t.error}):t.granted&&t.info?r({granted:!0,info:t.info}):r({error:`serial picker returned an unexpected response`})}).catch(e=>{r({error:e instanceof Error?e.message:`Failed to open serial picker`})})})}function nO(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}var rO=class{registry;constructor(e){this.registry=e}serial(){let e=ND();if(!e)throw Error(`Web Serial is unavailable in this browser`);return e}list(){return HD(this.registry,this.serial())}async request(e){if(eO()){let t=await tO(e);if(`cancelled`in t)throw Error(`user cancelled the serial picker`);if(`error`in t)throw Error(t.error);let n=await this.reacquire(t.info);if(!n)throw Error(`granted port could not be re-acquired`);let r=this.registry.register(n);return RD(r,this.registry.get(r))}return UD(this.registry,this.serial(),e)}async reacquire(e){let t=await this.serial().getPorts(),n=t.filter(t=>{let n=t.getInfo();return!(e.usbVendorId!==void 0&&n.usbVendorId!==e.usbVendorId||e.usbProductId!==void 0&&n.usbProductId!==e.usbProductId)}),r=n.length?n:t,i=this.registry.list().map(e=>e.entry.port);return r.find(e=>!i.includes(e))??r[0]??null}info(e){return Promise.resolve(WD(this.registry,e))}open(e,t){return GD(this.registry,e,t)}close(e){return KD(this.registry,e)}read(e,t){return YD(this.registry,e,t)}write(e,t){return XD(this.registry,e,t)}getSignals(e){return ZD(this.registry,e)}setSignals(e,t){return QD(this.registry,e,t)}},iO=class e{rpc;constructor(e){this.rpc=e}static REQUEST_TIMEOUT_MS=5*6e4;static READ_MARGIN_MS=3e4;async list(){return(await this.rpc.call(`serial-list`,void 0)).devices}async request(t){return(await this.rpc.call(`serial-request`,{filters:t},{timeoutMs:e.REQUEST_TIMEOUT_MS})).device}async info(e){return(await this.rpc.call(`serial-device-info`,{handle:e})).device}async open(e,t){await this.rpc.call(`serial-open`,{handle:e,options:t})}async close(e){await this.rpc.call(`serial-close`,{handle:e})}async read(t,n){let r=(n.timeoutMs??1e3)+e.READ_MARGIN_MS,i=await this.rpc.call(`serial-read`,{handle:t,maxBytes:n.maxBytes,until:n.until?nO(n.until):void 0,timeoutMs:n.timeoutMs},{timeoutMs:r});return new Uint8Array(i.bytes)}async write(e,t){return(await this.rpc.call(`serial-write`,{handle:e,bytes:nO(t)})).bytesWritten}async getSignals(e){return(await this.rpc.call(`serial-get-signals`,{handle:e})).signals}async setSignals(e,t){await this.rpc.call(`serial-set-signals`,{handle:e,signals:t})}};function aO(e,t){return e&&ND()?new rO(ID()):t?new iO(t):null}function oO(){return globalThis.navigator?.usb??null}function sO(e,t){return e===t||e.vendorId===t.vendorId&&e.productId===t.productId&&(e.serialNumber??``)===(t.serialNumber??``)&&!!e.serialNumber}var cO=class{byHandle=new Map;counter=0;register(e){for(let[t,n]of this.byHandle)if(sO(n,e))return this.byHandle.set(t,e),t;let t=`usb${++this.counter}`;return this.byHandle.set(t,e),t}get(e){return this.byHandle.get(e)}remove(e){return this.byHandle.delete(e)}list(){return[...this.byHandle].map(([e,t])=>({handle:e,device:t}))}};let lO=null;function uO(){return lO||=new cO,lO}const dO=4*1024*1024;function fO(e,t){return{handle:e,vendorId:t.vendorId,productId:t.productId,...t.productName?{productName:t.productName}:{},...t.manufacturerName?{manufacturerName:t.manufacturerName}:{},...t.serialNumber?{serialNumber:t.serialNumber}:{},opened:t.opened}}function pO(e,t){let n=e.get(t);if(!n)throw Error(`unknown usb handle '${t}'`);return n}function mO(e,t){if(e>4194304)throw Error(`${t} exceeds the ${dO}-byte (4 MiB) v1 limit`)}function hO(e){return e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength)}async function gO(e,t){return(await t.getDevices()).map(t=>fO(e.register(t),t))}async function _O(e,t,n){let r=await t.requestDevice({filters:n});return fO(e.register(r),r)}function vO(e,t){return fO(t,pO(e,t))}async function yO(e,t){await pO(e,t).open()}async function bO(e,t){await pO(e,t).close()}async function xO(e,t,n){await pO(e,t).selectConfiguration(n)}async function SO(e,t,n){await pO(e,t).claimInterface(n)}async function CO(e,t,n){await pO(e,t).releaseInterface(n)}async function wO(e,t,n,r){mO(r,`control-in length`);let i=await pO(e,t).controlTransferIn(n,r);return{status:i.status??`ok`,bytes:i.data?hO(i.data):new ArrayBuffer(0)}}async function TO(e,t,n,r){mO(r.byteLength,`control-out payload`);let i=await pO(e,t).controlTransferOut(n,r);return{status:i.status??`ok`,bytesWritten:i.bytesWritten}}async function EO(e,t,n,r){mO(r,`transfer-in length`);let i=await pO(e,t).transferIn(n,r);return{status:i.status??`ok`,bytes:i.data?hO(i.data):new ArrayBuffer(0)}}async function DO(e,t,n,r){mO(r.byteLength,`transfer-out payload`);let i=await pO(e,t).transferOut(n,r);return{status:i.status??`ok`,bytesWritten:i.bytesWritten}}async function OO(e,t){await pO(e,t).reset()}const kO=6e4;function AO(){return pe()}function jO(e){return new Promise(t=>{let n=!1,r=e=>{n||(n=!0,clearTimeout(i),t(e))},i=setTimeout(()=>r({cancelled:!0}),kO);fe(`usb-device`,e??[],void 0,{timeoutMs:kO}).then(e=>{let t=e;t.cancelled?r({cancelled:!0}):typeof t.error==`string`?r({error:t.error}):t.granted&&t.info?r({granted:!0,info:t.info}):r({error:`usb picker returned an unexpected response`})}).catch(e=>{r({error:e instanceof Error?e.message:`Failed to open USB picker`})})})}function MO(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}var NO=class{registry;constructor(e){this.registry=e}usb(){let e=oO();if(!e)throw Error(`WebUSB is unavailable in this browser`);return e}list(){return gO(this.registry,this.usb())}async request(e){if(AO()){let t=await jO(e);if(`cancelled`in t)throw Error(`user cancelled the USB picker`);if(`error`in t)throw Error(t.error);let n=await this.reacquire(t.info);if(!n)throw Error(`granted device could not be re-acquired`);return fO(this.registry.register(n),n)}return _O(this.registry,this.usb(),e)}async reacquire(e){return(await this.usb().getDevices()).find(t=>t.vendorId===e.vendorId&&t.productId===e.productId&&(!e.serialNumber||t.serialNumber===e.serialNumber))??null}info(e){return Promise.resolve(vO(this.registry,e))}open(e){return yO(this.registry,e)}close(e){return bO(this.registry,e)}selectConfig(e,t){return xO(this.registry,e,t)}claim(e,t){return SO(this.registry,e,t)}release(e,t){return CO(this.registry,e,t)}async controlIn(e,t,n){let r=await wO(this.registry,e,t,n);return{status:r.status,bytes:new Uint8Array(r.bytes)}}controlOut(e,t,n){return TO(this.registry,e,t,MO(n))}async transferIn(e,t,n){let r=await EO(this.registry,e,t,n);return{status:r.status,bytes:new Uint8Array(r.bytes)}}transferOut(e,t,n){return DO(this.registry,e,t,MO(n))}reset(e){return OO(this.registry,e)}},PO=class e{rpc;constructor(e){this.rpc=e}static REQUEST_TIMEOUT_MS=5*6e4;async list(){return(await this.rpc.call(`usb-list`,void 0)).devices}async request(t){return(await this.rpc.call(`usb-request`,{filters:t},{timeoutMs:e.REQUEST_TIMEOUT_MS})).device}async info(e){return(await this.rpc.call(`usb-device-info`,{handle:e})).device}async open(e){await this.rpc.call(`usb-open`,{handle:e})}async close(e){await this.rpc.call(`usb-close`,{handle:e})}async selectConfig(e,t){await this.rpc.call(`usb-select-configuration`,{handle:e,configurationValue:t})}async claim(e,t){await this.rpc.call(`usb-claim-interface`,{handle:e,interfaceNumber:t})}async release(e,t){await this.rpc.call(`usb-release-interface`,{handle:e,interfaceNumber:t})}async controlIn(e,t,n){let r=await this.rpc.call(`usb-control-transfer-in`,{handle:e,setup:t,length:n});return{status:r.status,bytes:new Uint8Array(r.bytes)}}async controlOut(e,t,n){return this.rpc.call(`usb-control-transfer-out`,{handle:e,setup:t,bytes:MO(n)})}async transferIn(e,t,n){let r=await this.rpc.call(`usb-transfer-in`,{handle:e,endpointNumber:t,length:n});return{status:r.status,bytes:new Uint8Array(r.bytes)}}async transferOut(e,t,n){return this.rpc.call(`usb-transfer-out`,{handle:e,endpointNumber:t,bytes:MO(n)})}async reset(e){await this.rpc.call(`usb-reset`,{handle:e})}};function FO(e,t){return e&&oO()?new NO(uO()):t?new PO(t):null}const IO=new Map;function LO(e){let t=crypto.randomUUID();return IO.set(t,e),t}function RO(e){return IO.get(e)??null}function zO(e){IO.delete(e)}const BO=n(`realm-host`);function VO(e,t,n={}){let r=new Map,i=n.syncFsBridgeEnabled?LO({fs:t.fs,cwd:t.cwd}):void 0,a=!1,o={subscriptions:r,pushEvent:(t,n=[])=>{if(!a)try{e.postMessage(t,n)}catch{}}},s=new Map,c={spawns:s,opts:n},l=r=>{if(r.data?.type!==`realm-rpc-req`)return;let i=r.data;HO(e,i,t,n,o,c)};return e.addEventListener(`message`,l),e.start?.(),{syncFsToken:i,dispose:()=>{if(!a){a=!0,i&&zO(i),e.removeEventListener(`message`,l);for(let{controller:e}of s.values())try{e.signal.aborted||e.abort()}catch{}s.clear();for(let e of r.values())try{Promise.resolve(e()).catch(()=>{})}catch{}r.clear()}}}}async function HO(e,t,n,r,i,a){try{let o=await UO(t,n,r,i,a),s={type:`realm-rpc-res`,id:t.id,result:o},c=Ak(o);e.postMessage(s,c)}catch(n){let r=n instanceof Error?n.message:String(n),i={type:`realm-rpc-res`,id:t.id,error:r};e.postMessage(i)}}async function UO(e,t,n,r,i){switch(e.channel){case`vfs`:return YO(e.op,e.args,t);case`exec`:return ok(e.op,e.args,t,i);case`fetch`:return uk(e.op,e.args,t);case`browser`:return mk(e.op,e.args,WO(n),n);case`usb`:return Dk(e.op,e.args,KO(n));case`serial`:return Ok(e.op,e.args,qO(n));case`hid`:return kk(e.op,e.args,JO(n),r);case`module`:return fk(e.op,e.args,t);case`wasm`:return pk(e.op,e.args,t);default:throw Error(`realm-host: unknown channel '${e.channel}'`)}}function WO(e){if(e.browser)return e.browser;let t=globalThis;if(t.__slicc_browser)return t.__slicc_browser;throw Error(`browser is not available in this runtime`)}function GO(e){if(e.wsSubscribers)return e.wsSubscribers;let t=globalThis;if(t.__slicc_wsSubscribers)return t.__slicc_wsSubscribers;throw Error(`browser.websocket is not available in this runtime`)}function KO(e){if(e.usbBackend)return e.usbBackend;let t=FO(i(),r());if(!t)throw Error(`usb is not available in this runtime`);return t}function qO(e){if(e.serialBackend)return e.serialBackend;let t=aO(i(),r());if(!t)throw Error(`serial is not available in this runtime`);return t}function JO(e){if(e.hidBackend)return e.hidBackend;let t=ED(i(),r());if(!t)throw Error(`hid is not available in this runtime`);return t}async function YO(e,t,n){let r=typeof t[0]==`string`?t[0]:null,i=r===null?null:n.fs.resolvePath(n.cwd,r);switch(e){case`readFile`:return n.fs.readFile(i);case`readFileBinary`:return n.fs.readFileBuffer(i);case`writeFile`:return await n.fs.writeFile(i,t[1]),!0;case`writeFileBinary`:return await n.fs.writeFile(i,t[1]),!0;case`readDir`:return n.fs.readdir(i);case`exists`:return n.fs.exists(i);case`stat`:{let e=await n.fs.stat(i);return{isDirectory:e.isDirectory,isFile:e.isFile,size:e.size}}case`mkdir`:return await n.fs.mkdir(i,{recursive:!0}),!0;case`rm`:return await n.fs.rm(i,{recursive:!0}),!0;case`rename`:{let e=n.fs.resolvePath(n.cwd,t[1]),r=n.fs;if(r.rename)await r.rename(i,e);else{let t=await n.fs.readFileBuffer(i);await n.fs.writeFile(e,t),await n.fs.rm(i,{recursive:!0})}return!0}case`resolvePath`:return n.fs.resolvePath(n.cwd,t[0]);case`invalidatePaths`:{let e=t[0],r=n.fs;return r.invalidatePaths&&r.invalidatePaths(e),!0}case`snapshot`:return nk(n,typeof t[0]==`string`?t[0]:n.cwd);case`flushWrites`:{let e=t[0];return await rk(n,e),!0}default:throw Error(`realm-host: unknown vfs op '${e}'`)}}const XO=10485760;function ZO(e){return e.fileCount>=500||e.totalBytes>=XO}function QO(e){return e.entries.length>=2e4}async function $O(e,t,n,r){r.entries.push({path:t,content:new Uint8Array,isDirectory:!0});let i;try{i=await e.fs.readdir(t)}catch{return}for(let e of i)e!==`node_modules`&&n.push(t===`/`?`/${e}`:`${t}/${e}`)}async function ek(e,t,n,r){if(n>1048576||ZO(r)||r.totalBytes+n>XO){r.entries.push({path:t,content:new Uint8Array,isDirectory:!1,truncated:!0,size:n});return}let i=await e.fs.readFileBuffer(t);r.entries.push({path:t,content:i,isDirectory:!1}),r.fileCount+=1,r.totalBytes+=i.byteLength}async function tk(e,t,n){if(QO(n)||!await e.fs.exists(t))return;let r=[t];for(;r.length>0;){if(QO(n))return;let t=r.pop(),i;try{i=await e.fs.stat(t)}catch{continue}i.isDirectory?await $O(e,t,r,n):i.isFile&&await ek(e,t,i.size,n)}}async function nk(e,t){let n={entries:[],totalBytes:0,fileCount:0};return await tk(e,t,n),t!==`/tmp`&&await tk(e,`/tmp`,n),{entries:n.entries}}async function rk(e,t){for(let n of t.deleted)await e.fs.rm(n,{recursive:!0});for(let n of t.created)n.isDirectory?await e.fs.mkdir(n.path,{recursive:!0}):await e.fs.writeFile(n.path,n.content);for(let n of t.modified)await e.fs.writeFile(n.path,n.content)}const ik=new Set([`SIGINT`,`SIGTERM`,`SIGKILL`,`SIGSTOP`,`SIGCONT`]),ak=new Set([`SIGINT`,`SIGTERM`,`SIGKILL`]);async function ok(e,t,n,r){if(!n.exec)throw Error(`exec is not available in this runtime`);if(e===`run`){let e=t[0],r=await n.exec(e,{cwd:n.cwd});return{stdout:r.stdout,stderr:r.stderr,exitCode:r.exitCode}}if(e===`spawn`){let e=t[0];if(!Array.isArray(e)||e.length===0||!e.every(e=>typeof e==`string`))throw Error(`exec.spawn: argv must be a non-empty string[]`);let[r,...i]=e,a=await n.exec(r,{cwd:n.cwd,args:i});return{stdout:a.stdout,stderr:a.stderr,exitCode:a.exitCode}}if(e===`start`)return ck(t,n,r);if(e===`kill`)return lk(t,r);throw Error(`realm-host: unknown exec op '${e}'`)}function sk(e){if(e.stdin!==void 0&&typeof e.stdin!=`string`)throw Error(`exec.start: stdin must be a string`);if(e.stdinKind!==void 0&&e.stdinKind!==`text`&&e.stdinKind!==`bytes`)throw Error(`exec.start: stdinKind must be 'text' or 'bytes'`);if(e.args!==void 0&&(!Array.isArray(e.args)||!e.args.every(e=>typeof e==`string`)))throw Error(`exec.start: args must be a string[]`)}async function ck(e,t,n){let[r,i,a]=e;if(typeof r!=`number`)throw Error(`exec.start: spawnId must be a number`);if(n.spawns.has(r))throw Error(`exec.start: spawnId ${r} is already in use`);let o,s,c;if(Array.isArray(i)){if(i.length===0||!i.every(e=>typeof e==`string`))throw Error(`exec.start: argv must be a non-empty string[]`);[o,...s]=i,c=i.slice()}else if(typeof i==`string`)o=i,c=[i];else throw Error(`exec.start: command must be a string or a non-empty string[]`);let l=a??{};sk(l);let u=new AbortController,{pm:d,owner:f}=n.opts,p=0;d&&f&&(p=d.spawn({kind:`shell`,argv:c,cwd:t.cwd,owner:f,...n.opts.ppid===void 0?{}:{ppid:n.opts.ppid},adoptAbort:u}).pid),n.spawns.set(r,{controller:u,pid:p});let m;try{let e={cwd:t.cwd,signal:u.signal};return l.stdin!==void 0&&(e.stdin=l.stdin),l.stdinKind!==void 0&&(e.stdinKind=l.stdinKind),s===void 0?l.args!==void 0&&(e.args=l.args):e.args=s,m=await t.exec(o,e),{stdout:m.stdout,stderr:m.stderr,exitCode:m.exitCode}}finally{if(n.spawns.delete(r),d&&p){let e=d.get(p);d.exit(p,e?.terminatedBy?null:m?.exitCode??1)}}}function lk(e,t){let[n,r]=e,i=t.spawns.get(n);if(!i)return!1;let a=typeof r==`string`&&ik.has(r)?r:`SIGTERM`;ak.has(a)&&!i.controller.signal.aborted&&i.controller.abort();let{pm:o}=t.opts;return o&&i.pid?o.signal(i.pid,a):!0}async function uk(e,t,n){if(e!==`request`)throw Error(`realm-host: unknown fetch op '${e}'`);let[r,i]=t,a=await(n.fetch?DD(n.fetch):globalThis.fetch.bind(globalThis))(r,i),o={};a.headers.forEach((e,t)=>{o[t]=e});let s=new Uint8Array(await a.arrayBuffer());return{status:a.status,statusText:a.statusText,headers:o,body:s,url:a.url}}function dk(e){let t=t=>e.fs.resolvePath(e.cwd,t);return{exists:n=>e.fs.exists(t(n)),isDirectory:async n=>{try{return(await e.fs.stat(t(n))).isDirectory}catch{return!1}},readFile:async n=>{let r=await e.fs.readFile(t(n));return typeof r==`string`?r:new TextDecoder().decode(r)}}}async function fk(e,t,n){if(e!==`buildGraph`)throw Error(`realm-host: unknown module op '${e}'`);let r=typeof t[0]==`string`?t[0]:``,i=typeof t[1]==`string`&&t[1]?t[1]:n.cwd,a=typeof t[2]==`string`?t[2]:``,o=dk(n),s={reader:o,readBytes:e=>n.fs.readFileBuffer(e),fromDir:i};return QE({entryCode:r,fromDir:i,entryFilename:a,reader:o,transpile:IE({ipk:s}),transpileEntry:LE({ipk:s})})}async function pk(e,t,n){if(e!==`compile`)throw Error(`realm-host: unknown wasm op '${e}'`);let r=typeof t[0]==`string`?t[0]:null;if(r===null)throw Error(`realm-host: wasm.compile requires a path argument`);return Tn(e=>n.fs.readFileBuffer(e),n.fs.resolvePath(n.cwd,r))}async function mk(e,t,n,r){switch(e){case`findTab`:return _k(n,t[0]??{});case`ensureTab`:{let e=t[0];return vk(n,e,t[1]??{})}case`eval`:{let e=t[0],r=t[1];return yk(n,e,r,!1)}case`evalAsync`:{let e=t[0],r=t[1];return yk(n,e,r,!0)}case`cookie`:{let e=t[0],r=t[1];return Ck(n,e,r)}case`localStorage`:{let e=t[0],r=t[1];return wk(n,e,r)}case`wsObserve`:{let e={...t[0],scoopJid:r.scoopJid};return await GO(r).observe(e)}case`wsUpdate`:{let e=t[0],n=t[1]??{};return GO(r).update(e,n)}case`wsClose`:{let e=t[0];return GO(r).close(e)}case`wsList`:return GO(r).list();case`createTab`:{let e=t[0];return n.createPage(e)}case`closeTab`:{let e=t[0];return n.closePage(e)}case`setViewport`:{let e=t[0],r=t[1],i=t[2];return n.withTab(e,async()=>{await n.sendCDP(`Emulation.setDeviceMetricsOverride`,{width:r,height:i,deviceScaleFactor:1,mobile:!1})})}case`navigateTab`:{let e=t[0],r=t[1];return n.withTab(e,async()=>{await n.navigate(r)})}case`screenshotTab`:{let e=t[0],r=t[1];return n.withTab(e,async()=>(await n.bringToFront(),n.screenshot(r)))}case`waitForLoadState`:{let e=t[0],r=t[1];return Sk(n,e,r)}default:throw Error(`realm-host: unknown browser op '${e}'`)}}function hk(){try{let e=globalThis.localStorage;return e?!!(e.getItem(`slicc.trayWorkerBaseUrl`)||e.getItem(`slicc.trayJoinUrl`)):!1}catch{return!1}}async function gk(e){if(typeof e.listAllTargets!=`function`)return(await e.listPages()).map(e=>({targetId:e.targetId,url:e.url,title:e.title}));let t=(await e.listAllTargets()).map(e=>({targetId:e.targetId,url:e.url,title:e.title})),n=hk()?r():null;if(n)try{let{targets:e}=await n.call(`list-remote-targets`,void 0,{timeoutMs:3e3}),r=new Set(t.map(e=>e.targetId));for(let n of e)r.has(n.targetId)||(r.add(n.targetId),t.push({targetId:n.targetId,url:n.url,title:n.title}))}catch(e){BO.debug(`panel-rpc list-remote-targets failed`,{err:String(e)})}return t}async function _k(e,t){let n=await gk(e);if(t.domain){let e=t.domain.toLowerCase();for(let t of n){let n=Tk(t.url);if(n&&n.toLowerCase()===e)return t}return null}if(t.urlMatch){let e;try{e=new RegExp(t.urlMatch)}catch(e){throw Error(`browser.findTab: invalid urlMatch regex: ${e instanceof Error?e.message:String(e)}`)}for(let t of n)if(e.test(t.url))return t;return null}throw Error("browser.findTab: query requires `domain` or `urlMatch`")}async function vk(e,t,n){let r=await gk(e);if(n.matchUrl){let e;try{e=new RegExp(n.matchUrl)}catch(e){throw Error(`browser.ensureTab: invalid matchUrl regex: ${e instanceof Error?e.message:String(e)}`)}let t=r.find(t=>e.test(t.url));if(t)return t}else{let e=Ek(t);if(e){let t=r.find(t=>Ek(t.url)===e);if(t)return t}}return{targetId:await e.createPage(t),url:t,title:``}}async function yk(e,t,n,r){return e.withTab(t,async()=>bk(await e.evaluate(n,{awaitPromise:r,returnByValue:!0})))}function bk(e){if(typeof e!=`string`)return e;let t=xk(e);if(t===void 0)return e;if(typeof t==`object`&&t)return t;if(typeof t==`string`){let e=t.trim();if(e.length>0&&(e[0]===`{`||e[0]===`[`)){let e=xk(t);if(typeof e==`object`&&e)return e}return t}return e}function xk(e){let t=e.trim();if(t.length===0)return;let n=t[0];if(n===`{`||n===`[`||n===`"`||n===`-`||n>=`0`&&n<=`9`||t===`true`||t===`false`||t===`null`)try{return JSON.parse(t)}catch{return}}async function Sk(e,t,n){if(n===`networkidle`)return e.withTab(t,async()=>{for(let t=0;t<20;t++)if(await new Promise(e=>setTimeout(e,250)),await e.evaluate(`(function(){
|
|
5555
5555
|
try {
|
|
5556
5556
|
var entries = performance.getEntriesByType('resource');
|
|
5557
5557
|
var now = performance.now();
|
|
@@ -5646,7 +5646,7 @@ Examples:
|
|
|
5646
5646
|
skill list
|
|
5647
5647
|
skill info bluebubbles
|
|
5648
5648
|
skill read bluebubbles
|
|
5649
|
-
`,stderr:``,exitCode:0};let r=t[0],i=await import(`./skills-
|
|
5649
|
+
`,stderr:``,exitCode:0};let r=t[0],i=await import(`./skills-CF4YIozr.js`).then(e=>e.t);try{switch(r){case`list`:{let t=await i.discoverSkills(e);return t.length===0?{stdout:`No discoverable skills found.\n\n${ZA()}Install skills with: upskill owner/repo --all\n`,stderr:``,exitCode:0}:{stdout:$A(t,`Discoverable skills`),stderr:``,exitCode:0}}case`info`:{let n=t[1];if(!n)return{stdout:``,stderr:`skill: info requires a skill name
|
|
5650
5650
|
`,exitCode:1};let r=await i.getSkillInfo(e,n);return r?{stdout:ej(r),stderr:``,exitCode:0}:{stdout:``,stderr:`skill: "${n}" not found\n`,exitCode:1}}case`read`:{let n=t[1];if(!n)return{stdout:``,stderr:`skill: read requires a skill name
|
|
5651
5651
|
`,exitCode:1};let r=await i.readSkillInstructions(e,n);return r===null?{stdout:``,stderr:`skill: no SKILL.md found for "${n}"\n`,exitCode:1}:{stdout:r+`
|
|
5652
5652
|
`,stderr:``,exitCode:0}}default:return{stdout:``,stderr:`skill: unknown command "${r}"\n`,exitCode:1}}}catch(e){return{stdout:``,stderr:`skill: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}})}async function rj(e,t){let n=`${Kk}/experimental/search?q=${encodeURIComponent(e)}&contentType=skills&page%5Bsize%5D=20`,r;try{r=await t(n,{headers:{Accept:`application/json`}})}catch(e){throw Error(lA(e,n))}if(r.status!==200)throw Error(`Tessl returned HTTP ${r.status}`);let i=ae(r.body);if(!i.data)return[];let a=new Map;for(let e of i.data){if(e.type!==`skill`)continue;let t=e.attributes,n=EA(t.sourceUrl),r=n?`${n.owner}/${n.repo}`:void 0,i=t.scores.aggregate==null?null:Math.round(t.scores.aggregate*100),o=t.sourceUrl||e.id,s=a.get(o);if(s&&s.qualityScore!=null&&i!=null&&s.qualityScore>=i)continue;let c=t.path.replace(/\/SKILL\.md$/i,``),l=c.split(`/`).pop()||t.name,u=n?`upskill ${n.owner}/${n.repo} --path ${c.split(`/`).slice(0,-1).join(`/`)||`.`} --skill ${l}`:`upskill tessl:${t.name}`;a.set(o,{name:t.name,displayName:t.name,summary:t.description||``,source:`tessl`,qualityScore:i,installHint:u,featured:t.featured,sourceRepo:r})}return Array.from(a.values())}async function ij(e,t){let n=`${Kk}/experimental/search?q=${encodeURIComponent(e)}&contentType=skills&page%5Bsize%5D=5`,r;try{r=await t(n,{headers:{Accept:`application/json`}})}catch(e){return{error:`Tessl search failed: ${lA(e,n)}`}}if(r.status!==200)return{error:`Tessl search failed (HTTP ${r.status})`};let i=ae(r.body).data?.find(t=>t.type===`skill`&&t.attributes.name===e);if(!i)return{error:`skill "${e}" not found on Tessl registry`};let a=EA(i.attributes.sourceUrl);if(!a)return{error:`skill "${e}" has no GitHub source URL`};let o=i.attributes.path.replace(/\/SKILL\.md$/i,``);return{owner:a.owner,repo:a.repo,skillPath:o,skillName:e}}const aj=[{label:`Tessl`,host:new URL(Kk).host,fetch:rj},{label:`browse.sh`,host:new URL(qk).host,fetch:UA}];function oj(e){let t=[],n=e.reduce((e,t)=>Math.max(e,t.length),0);for(let r=0;r<n;r++)for(let n of e)r<n.length&&t.push(n[r]);return t}async function sj(e,t,n=1){let r=await Promise.allSettled(aj.map(n=>n.fetch(e,t))),i=r.map(e=>e.status===`fulfilled`?e.value:[]),a=r.every(e=>e.status===`rejected`),o=oj(i),s=``;for(let e=0;e<r.length;e++){let t=r[e];if(t.status===`rejected`){let n=aj[e],r=t.reason instanceof Error?t.reason.message:String(t.reason);s+=`warning: ${n.label} registry unavailable (${n.host}): ${r}\n`}}if(o.length===0){let t=a?`${s}upskill: registries failed to respond\n`:s;return{stdout:`No skills found for "${e}"\n\nTry a different search term or browse the registries at https://tessl.io/registry or https://browse.sh\n`,stderr:t,exitCode:+!!a}}let c=o.length,l=Math.ceil(c/10),u=Math.max(1,Math.min(n,l)),d=(u-1)*10,f=o.slice(d,d+10),p=`Search results for "${e}" (page ${u}/${l}, ${c} total):\n\n`;for(let e of f){let t=e.qualityScore==null?` `:String(e.qualityScore).padStart(3),n=`[${e.source}]`,r=e.sourceRepo?` ${e.sourceRepo}`:``;p+=` ${e.name.padEnd(30)} ${t} ${n.padEnd(10)}${r}\n`,e.summary&&(p+=` ${e.summary}\n`),p+=`
|
|
@@ -5672,7 +5672,7 @@ Examples:
|
|
|
5672
5672
|
`,{stdout:s,stderr:``,exitCode:0}}function mj(e){return!e||e.startsWith(`-`)?{stdout:``,stderr:`upskill: --branch requires a value
|
|
5673
5673
|
`,exitCode:1}:qe(e)?null:{stdout:``,stderr:`upskill: --branch must be a git ref of [A-Za-z0-9._/-]+ with no "..", leading "-"/"/", trailing "/" or ".lock", or shell metacharacters
|
|
5674
5674
|
`,exitCode:1}}function hj(e){let t={selectedSkills:[],listOnly:!1,installAll:!1,force:!1,sourceRef:``},n=0;for(;n<e.length;){let r=e[n];if(r===`--skill`)t.selectedSkills.push(e[++n]);else if(r===`--path`||r===`-p`){let r=e[++n];if(typeof r!=`string`||!Xe(r))return t.earlyReturn={stdout:``,stderr:`upskill: --path must be a repo-relative sub-path of [A-Za-z0-9._/-]+ with no "..", leading "-"/"/", or shell metacharacters
|
|
5675
|
-
`,exitCode:1},t;t.subPath=r}else if(r===`--list`)t.listOnly=!0;else if(r===`--all`)t.installAll=!0;else if(r===`--force`)t.force=!0;else if(r===`--branch`||r===`-b`){let r=mj(e[n+1]);if(r)return t.earlyReturn=r,t;t.branch=e[++n]}else r.startsWith(`-`)||(t.sourceRef=r);n++}return t}async function gj(e){let t=await(await import(`./skills-
|
|
5675
|
+
`,exitCode:1},t;t.subPath=r}else if(r===`--list`)t.listOnly=!0;else if(r===`--all`)t.installAll=!0;else if(r===`--force`)t.force=!0;else if(r===`--branch`||r===`-b`){let r=mj(e[n+1]);if(r)return t.earlyReturn=r,t;t.branch=e[++n]}else r.startsWith(`-`)||(t.sourceRef=r);n++}return t}async function gj(e){let t=await(await import(`./skills-CF4YIozr.js`).then(e=>e.t)).discoverSkills(e);return t.length===0?{stdout:`No discoverable local skills found.\n\n${ZA()}`,stderr:``,exitCode:0}:{stdout:$A(t,`Discoverable local skills`),stderr:``,exitCode:0}}async function _j(e,t,n){if(!t)return{stdout:``,stderr:`upskill: ${e} requires a skill name\n`,exitCode:1};let r=await import(`./skills-CF4YIozr.js`).then(e=>e.t);if(e===`info`){let e=await r.getSkillInfo(n,t);return e?{stdout:ej(e),stderr:``,exitCode:0}:{stdout:``,stderr:`upskill: skill "${t}" not found\n`,exitCode:1}}let i=await r.readSkillInstructions(n,t);return i===null?{stdout:``,stderr:`upskill: no SKILL.md found for "${t}"\n`,exitCode:1}:{stdout:i+`
|
|
5676
5676
|
`,stderr:``,exitCode:0}}async function vj(e,t,n,r,i,a,o){let s=``,c=``,l=0,u=e.length;for(let d=0;d<e.length;d++){let f=e[d],p=await yA(f.path,f.name,r,i,a),m=d+1,h=((Date.now()-o)/1e3).toFixed(1),g=(Date.now()-o)/m,_=m<u?` (~${Math.round((u-m)*g/1e3)}s remaining)`:``;p.ok?(s+=`[${m}/${u}] Installed "${f.name}" from ${t}/${n} (${h}s)${_}\n`,l++):(s+=`[${m}/${u}] Failed "${f.name}": ${p.error}${_}\n`,c+=`upskill: ${p.error}\n`)}return{output:s,errors:c,successCount:l}}async function yj(e,t,n,r,i,a,o,s){let c=``,l=``,u=0,d=e.length;for(let f=0;f<e.length;f++){let p=e[f],m=await OA(t,n,p.path,p.name,i,r,a,void 0,o),h=f+1,g=((Date.now()-s)/1e3).toFixed(1),_=(Date.now()-s)/h,v=h<d?` (~${Math.round((d-h)*_/1e3)}s remaining)`:``;m.exitCode===0?(c+=`[${h}/${d}] Installed "${p.name}" from ${t}/${n} (${g}s)${v}\n`,u++):(c+=`[${h}/${d}] Failed "${p.name}": ${m.stderr.trim()}${v}\n`,l+=m.stderr)}return{output:c,errors:l,successCount:u}}async function bj(e,t,n,r,i,a,o,s){let c=``,l=``,u=0;for(let d of e){let e=await OA(t,n,d.path,d.name,i,r,a,o,s);e.exitCode===0?(c+=e.stdout,u++):l+=e.stderr}return{output:c,errors:l,successCount:u}}function xj(e,t,n){let r=`Available skills in ${t}/${n}:\n\n`;for(let t of e)r+=` ${t.name.padEnd(30)} ${t.path}\n`;return r+=`\nFound ${e.length} skill(s)\n`,r}async function Sj(e,t,n,r){let{owner:i,repo:a}=e,o=t.branch??e.branch,s=t.subPath??e.path,c=await mA(r),l=await DA(i,a,c,s,r,o);if(l.error)return{stdout:``,stderr:`upskill: failed to list skills: ${l.error}\n`,exitCode:1};if(l.skills.length===0)return{stdout:`No skills found in ${i}/${a}${s?`/`+s:``}\n`,stderr:``,exitCode:0};if(t.listOnly)return{stdout:xj(l.skills,i,a)+`\nTo install: upskill ${t.sourceRef} --skill <name>\nTo install all: upskill ${t.sourceRef} --all\n`,stderr:``,exitCode:0};let u=l.skills;if(t.selectedSkills.length>0){u=l.skills.filter(e=>t.selectedSkills.includes(e.name));for(let e of t.selectedSkills)if(!l.skills.find(t=>t.name===e))return{stdout:``,stderr:`upskill: skill "${e}" not found in ${i}/${a}\n`,exitCode:1}}else if(!t.installAll)return{stdout:xj(l.skills,i,a)+`\nTo install specific skills: upskill ${t.sourceRef} --skill <name>\nTo install all: upskill ${t.sourceRef} --all\n`,stderr:``,exitCode:0};let d=u.length,f=Date.now(),p=``,m=``,h=0;if(d>1){let e=await SA(i,a,r,o);if(e.status===`ok`){let r=await vj(u,i,a,CA(e.files),n,t.force,f);({output:p,errors:m,successCount:h}=r)}else{let e=await yj(u,i,a,c,n,t.force,o,f);({output:p,errors:m,successCount:h}=e)}}else({output:p,errors:m,successCount:h}=await bj(u,i,a,c,n,t.force,r,o));let g=((Date.now()-f)/1e3).toFixed(1);return h>0&&(p+=`\nInstalled ${h} skill(s)${d>1?` in ${g}s`:``}\n`,await vA()),{stdout:p,stderr:m,exitCode:+!!m}}function Cj(e,t,n){return G(`upskill`,async(r,i)=>{if(r.length===0||r.includes(`--help`)||r.includes(`-h`))return tj();if(r[0]===`tabs`)return fj(e,t,n,r.includes(`--json`));if(r[0]===`recommendations`)return pj(e,t,r.includes(`--install`));if(r[0]===`list`)return gj(e);if(r[0]===`info`||r[0]===`read`)return _j(r[0],r[1],e);if(r[0]===`search`)return wj(r,t);let a=hj(r);if(a.earlyReturn)return a.earlyReturn;if(!a.sourceRef)return tj();if(a.sourceRef.startsWith(`tessl:`))return Tj(a.sourceRef,a.force,e,t);let o=KA(a.sourceRef);if(o)return XA(o.hostname,o.task,e,t,a.force);let s=kA(a.sourceRef);return s?Sj(s,a,e,t):{stdout:``,stderr:`upskill: unrecognized source "${a.sourceRef}"\n\nExpected: owner/repo, tessl:<name>, or browse:<hostname>/<task>\n`,exitCode:1}})}async function wj(e,t){let n=[...e.slice(1)],r=n.indexOf(`--page`),i=1;r>=0&&(i=parseInt(n[r+1],10)||1,n.splice(r,2));let a=n.join(` `);return a?sj(a,t,i):tj()}async function Tj(e,t,n,r){let i=e.slice(6);if(!i)return{stdout:``,stderr:`upskill: tessl: requires a skill name
|
|
5677
5677
|
`,exitCode:1};let a=await ij(i,r);if(`error`in a)return{stdout:``,stderr:`upskill: ${a.error}\n`,exitCode:1};let o=await mA(r);return OA(a.owner,a.repo,a.skillPath,a.skillName,n,o,t,r)}function Ej(){return{stdout:`usage: afplay [-v volume] [-r rate] <file>
|
|
5678
5678
|
|
|
@@ -6902,7 +6902,7 @@ Common base URLs:
|
|
|
6902
6902
|
llama.cpp http://localhost:8080/v1
|
|
6903
6903
|
vLLM http://localhost:8000/v1
|
|
6904
6904
|
Jan http://localhost:1337/v1
|
|
6905
|
-
`}function PV(){return G(MV,async e=>{if(e.includes(`--help`)||e.includes(`-h`))return{stdout:NV(),stderr:``,exitCode:0};let{getApiKeyForProvider:t,getRawApiKeyForProvider:n,getBaseUrlForProvider:r,addAccount:i}=await import(`./provider-settings-
|
|
6905
|
+
`}function PV(){return G(MV,async e=>{if(e.includes(`--help`)||e.includes(`-h`))return{stdout:NV(),stderr:``,exitCode:0};let{getApiKeyForProvider:t,getRawApiKeyForProvider:n,getBaseUrlForProvider:r,addAccount:i}=await import(`./provider-settings-BclOQB4V.js`),{verifyConnection:a}=await import(`./local-llm-C6Uyn1eH.js`).then(e=>e.n),o=e[0]??`status`;if(o!==`status`&&o!==`discover`)return{stdout:``,stderr:`Unknown subcommand: ${o}. See \`local-llm --help\`.\n`,exitCode:2};let s=r(MV);if(!s)return{stdout:``,stderr:`Local LLM is not configured. Open Settings → Providers → Local LLM and set a base URL.
|
|
6906
6906
|
`,exitCode:1};let c=await a(s,t(MV)??void 0);if(!c.ok){let e=[`✗ Could not reach ${s}`,` runtime: ${c.runtime.kind}${c.runtime.version?` (${c.runtime.version})`:``}`,` error: ${c.error?.message??`unknown`}`];return c.error?.hint&&e.push(` hint: ${c.error.hint}`),{stdout:``,stderr:e.join(`
|
|
6907
6907
|
`)+`
|
|
6908
6908
|
`,exitCode:1}}if(o===`discover`){let e=n(MV)??``;return i(MV,e,s,c.models.join(`, `)),{stdout:[`✓ ${s} (${c.runtime.kind}${c.runtime.version?` ${c.runtime.version}`:``})`,` Saved ${c.models.length} model${c.models.length===1?``:`s`} to Settings:`,...c.models.map(e=>` • ${e}`)].join(`
|
|
@@ -6946,20 +6946,20 @@ authorization-code flow, stores the access token, and retries.
|
|
|
6946
6946
|
On success, the server is persisted to /workspace/.mcp/servers.json and
|
|
6947
6947
|
an alias shim is written to /workspace/.mcp/aliases/<name>.jsh so the
|
|
6948
6948
|
short name resolves on the PATH.
|
|
6949
|
-
`);let n=e.filter(e=>!e.startsWith(`--`));if(n.length<2)return VV(`mcp add: expected <url> <name>`);let[r,i]=n;if(!/^https?:\/\//i.test(r))return VV(`mcp add: invalid URL "${r}" (must start with http:// or https://)`);if(!/^[A-Za-z][A-Za-z0-9_-]*$/.test(i))return VV(`mcp add: invalid name "${i}" (letters, digits, _ and - only; must start with a letter)`);let{getServer:a,setServer:o}=await import(`./store-
|
|
6949
|
+
`);let n=e.filter(e=>!e.startsWith(`--`));if(n.length<2)return VV(`mcp add: expected <url> <name>`);let[r,i]=n;if(!/^https?:\/\//i.test(r))return VV(`mcp add: invalid URL "${r}" (must start with http:// or https://)`);if(!/^[A-Za-z][A-Za-z0-9_-]*$/.test(i))return VV(`mcp add: invalid name "${i}" (letters, digits, _ and - only; must start with a letter)`);let{getServer:a,setServer:o}=await import(`./store-FJJcjvMM.js`).then(e=>e.r);if(await a(i,t.fs))return VV(`mcp add: a server named "${i}" already exists`);let{McpClient:s,McpAuthRequiredError:c}=await import(`./client-CpLUc-P8.js`).then(e=>e.n),l=new s({url:r,fetchImpl:t.fetchImpl}),u;try{await l.initialize()}catch(e){if(!(e instanceof c))throw e;u=await GV(r,i,e.resourceMetadataUrl,t),l=new s({url:r,fetchImpl:t.fetchImpl,getAuthHeader:()=>dH(i)}),await l.initialize()}let d=await l.toolsList(),f=await l.appsList(),p=new Date().toISOString();await o(i,{url:r,tools:d,apps:f,addedAt:p,lastRefreshedAt:p,...u?{auth:u}:{}},t.fs),await _H(i,t);let m=await bH(i,f,t);if(u){let{registerMcpProvider:e}=await import(`./provider-CE6jDRgx.js`);e({name:i,serverUrl:r,auth:u})}return BV([`Added MCP server "${i}" → ${r}`,` tools: ${d.length}, apps: ${f.length} (${m} sprinkle${m===1?``:`s`})`,` alias: ${zV}/${i}.jsh`,u?` auth: oauth (provider mcp:${i})`:` auth: none`].join(`
|
|
6950
6950
|
`)+`
|
|
6951
|
-
`)}async function GV(e,t,n,r){let{discoverAuth:i,dynamicRegister:a,runAuthFlow:o}=await import(`./oauth-Czw-MuuR.js`),{saveOAuthAccount:s}=await import(`./provider-settings-
|
|
6952
|
-
`);let{ensureAllMcpProvidersRegistered:n}=await import(`./provider-
|
|
6951
|
+
`)}async function GV(e,t,n,r){let{discoverAuth:i,dynamicRegister:a,runAuthFlow:o}=await import(`./oauth-Czw-MuuR.js`),{saveOAuthAccount:s}=await import(`./provider-settings-BclOQB4V.js`),c=await mH(r.oauthFetchImpl),l=r.oauthLauncher??await fH(),u=await i(e,n,c);RV.debug(`MCP OAuth discovery succeeded`,{name:t,serverUrl:e,discoveryPath:u.discoveryPath,issuer:u.issuer});let d=await pH(),f=await a(u,d,c),p=u.supportedScopes&&u.supportedScopes.length>0?u.supportedScopes.join(` `):void 0,m=await o({asMetadata:u,clientId:f.clientId,scope:p,redirectUri:d,launcher:l,fetchImpl:c}),h=`mcp:${t}`;return await s({providerId:h,accessToken:m.accessToken,refreshToken:m.refreshToken,tokenExpiresAt:m.expiresAt}),{providerId:h,authorizationServer:u.issuer,clientId:f.clientId,scope:m.scope??p,registrationClientUri:f.registrationClientUri}}async function KV(e,t){if(e.includes(`--help`)||e.includes(`-h`))return BV(`usage: mcp list
|
|
6952
|
+
`);let{ensureAllMcpProvidersRegistered:n}=await import(`./provider-CE6jDRgx.js`);await n();let{listServers:r}=await import(`./store-FJJcjvMM.js`).then(e=>e.r),i=await r(t.fs),a=Object.keys(i).sort();if(a.length===0)return BV("No MCP servers configured. Use `mcp add <url> <name>`.\n");let o=[[`NAME`,`URL`,`AUTH`,`TOOLS`,`APPS`,`ADDED`]];for(let e of a){let t=i[e];o.push([e,t.url,t.auth?`yes`:`no`,String(t.tools?.length??0),String(t.apps?.length??0),t.addedAt?t.addedAt.slice(0,10):`-`])}return BV(qV(o))}function qV(e){let t=e[0].map((t,n)=>e.reduce((e,t)=>Math.max(e,(t[n]??``).length),0));return e.map(e=>e.map((e,n)=>e.padEnd(t[n])).join(` `).trimEnd()).join(`
|
|
6953
6953
|
`)+`
|
|
6954
6954
|
`}async function JV(e,t){if(e[0]===`--help`||e[0]===`-h`)return BV(`usage: mcp search <query>
|
|
6955
6955
|
|
|
6956
6956
|
Case-insensitive substring search across the cached tools of every
|
|
6957
6957
|
registered MCP server. Matches tool name OR description and prints a
|
|
6958
6958
|
table of (server, tool, description, match-field) rows.
|
|
6959
|
-
`);if(e.length===0)return VV(`mcp search: expected <query>`);let n=e[0],r=n.toLowerCase(),{ensureAllMcpProvidersRegistered:i}=await import(`./provider-
|
|
6960
|
-
`);let n=e[0],{ensureMcpProviderRegistered:r,removeMcpProvider:i}=await import(`./provider-
|
|
6959
|
+
`);if(e.length===0)return VV(`mcp search: expected <query>`);let n=e[0],r=n.toLowerCase(),{ensureAllMcpProvidersRegistered:i}=await import(`./provider-CE6jDRgx.js`);await i();let{listServers:a}=await import(`./store-FJJcjvMM.js`).then(e=>e.r),o=await a(t.fs),s=Object.keys(o).sort();if(s.length===0)return BV("No MCP servers configured. Use `mcp add <url> <name>`.\n");let c=[];for(let e of s){let t=o[e].tools??[];for(let n of t){let t=n.description??``,i=n.name.toLowerCase().includes(r),a=t.toLowerCase().includes(r);if(!i&&!a)continue;let o=i&&a?`name+description`:i?`name`:`description`;c.push({server:e,tool:n.name,description:t,match:o})}}if(c.length===0)return BV(`No tools matched "${n}".\n`);c.sort((e,t)=>e.server===t.server?e.tool.localeCompare(t.tool):e.server.localeCompare(t.server));let l=[[`SERVER`,`TOOL`,`DESCRIPTION`,`MATCH`]];for(let e of c)l.push([e.server,e.tool,YV(e.description),e.match]);return BV(qV(l))}function YV(e){if(!e)return``;let t=e.replace(/\s+/g,` `).trim();return t.length<=60?t:t.slice(0,59)+`…`}async function XV(e,t){if(e.length===0||e[0]===`--help`||e[0]===`-h`)return e.length===0?VV(`mcp delete: expected <name>`):BV(`usage: mcp delete <name>
|
|
6960
|
+
`);let n=e[0],{ensureMcpProviderRegistered:r,removeMcpProvider:i}=await import(`./provider-CE6jDRgx.js`);await r(n);let{deleteServer:a}=await import(`./store-FJJcjvMM.js`).then(e=>e.r),o=await a(n,t.fs);await vH(n,t),await yH(n,t);let s=`mcp:${n}`,c=!1;try{let{removeAccount:e,getAccounts:t}=await import(`./provider-settings-BclOQB4V.js`);t().some(e=>e.providerId===s)&&(await e(s),c=!0)}catch(e){RV.warn(`mcp delete: OAuth removal failed`,{providerId:s,error:e instanceof Error?e.message:String(e)})}let l=i(n);return!o&&!c&&!l?VV(`mcp delete: no server, alias, or account found for "${n}"`):BV([`Removed MCP server "${n}"`,` servers.json: ${o?`removed`:`not present`}`,` alias: cleaned`,` sprinkles: cleaned`,` oauth: ${c?`removed`:`not present`}`,` provider: ${l?`unregistered`:`not registered`}`].join(`
|
|
6961
6961
|
`)+`
|
|
6962
|
-
`)}async function ZV(e,t){if(e.length===0||e[0]===`--help`||e[0]===`-h`)return e.length===0?VV(`mcp invoke: expected <name>`):BV(eH());let n=e[0],r=e.slice(1),{ensureMcpProviderRegistered:i}=await import(`./provider-
|
|
6962
|
+
`)}async function ZV(e,t){if(e.length===0||e[0]===`--help`||e[0]===`-h`)return e.length===0?VV(`mcp invoke: expected <name>`):BV(eH());let n=e[0],r=e.slice(1),{ensureMcpProviderRegistered:i}=await import(`./provider-CE6jDRgx.js`);await i(n);let{getServer:a}=await import(`./store-FJJcjvMM.js`).then(e=>e.r),o=await a(n,t.fs);if(!o)return VV(`mcp invoke: unknown server "${n}" (run \`mcp add <url> ${n}\` first)`);let s=o.tools??[];if(r.length===0||r[0]===`--help`||r[0]===`-h`)return BV(tH(n,o,s));let c=r[0],l=s.find(e=>e.name===c);if(!l)return VV(`mcp invoke: unknown tool "${c}" on "${n}" (run \`${n}\` to list tools)`);let{timeoutMs:u,remaining:d,warnings:f}=QV(r.slice(1));if(d.includes(`--help`)||d.includes(`-h`))return BV(nH(n,l));let p=rH(d,l.inputSchema);if(!p.ok)return VV(`mcp invoke: ${p.error}`);let{McpClient:m}=await import(`./client-CpLUc-P8.js`).then(e=>e.n),h=new m({url:o.url,fetchImpl:t.fetchImpl,headers:o.headers,getAuthHeader:o.auth?()=>dH(n):void 0,...u===void 0?{}:{timeoutMs:u}});await h.initialize();let g=sH(await h.toolsCall(c,p.value));return f.length>0&&(g.stderr=f.map(e=>`${e}\n`).join(``)+g.stderr),g}function QV(e){let t=[],n=[],r,i=0;for(;i<e.length;){let a=e[i];if(a.startsWith(`--timeout=`)){let e=$V(a.slice(10));e.ok?r=e.value:n.push(e.error),i+=1;continue}if(a===`--timeout`){let t=e[i+1];if(t===void 0||t.startsWith(`--`)){n.push(`mcp invoke: --timeout requires a value (got ${t===void 0?`nothing`:`"${t}"`}); using default.`),i+=1;continue}let a=$V(t);a.ok?r=a.value:n.push(a.error),i+=2;continue}t.push(a),i+=1}return{timeoutMs:r,remaining:t,warnings:n}}function $V(e){if(!/^-?\d+$/.test(e))return{ok:!1,error:`mcp invoke: invalid --timeout value "${e}" (expected positive integer seconds); using default.`};let t=Number(e);return!Number.isFinite(t)||t<1?{ok:!1,error:`mcp invoke: invalid --timeout value "${e}" (must be >= 1 second); using default.`}:{ok:!0,value:t*1e3}}function eH(){return`usage: mcp invoke <name> [tool] [--timeout <seconds>] [--flag value …]
|
|
6963
6963
|
|
|
6964
6964
|
mcp invoke <name> List tools on <name>.
|
|
6965
6965
|
mcp invoke <name> <tool> --help Show flags for <tool>.
|
|
@@ -6989,7 +6989,7 @@ Arguments are coerced according to the tool's JSON Schema:
|
|
|
6989
6989
|
|
|
6990
6990
|
Re-fetches the tool catalog and \`apps/list\` for <name>. Does NOT refresh
|
|
6991
6991
|
OAuth tokens — for OAuth token refresh use \`mcp auth <name>\`.
|
|
6992
|
-
`);let n=e[0],{ensureMcpProviderRegistered:r}=await import(`./provider-
|
|
6992
|
+
`);let n=e[0],{ensureMcpProviderRegistered:r}=await import(`./provider-CE6jDRgx.js`);await r(n);let{getServer:i,setServer:a}=await import(`./store-FJJcjvMM.js`).then(e=>e.r),o=await i(n,t.fs);if(!o)return VV(`mcp refresh: unknown server "${n}"`);let{McpClient:s,McpAuthRequiredError:c}=await import(`./client-CpLUc-P8.js`).then(e=>e.n),l=new s({url:o.url,fetchImpl:t.fetchImpl,headers:o.headers,getAuthHeader:o.auth?()=>dH(n):void 0});try{await l.initialize()}catch(e){if(e instanceof c)return VV(`mcp refresh: server "${n}" returned 401 — token may have expired. Run \`mcp auth ${n}\` to re-authenticate.`);throw e}let u=await l.toolsList(),d=await l.appsList();await a(n,{...o,sessionId:void 0,tools:u,apps:d,lastRefreshedAt:new Date().toISOString()},t.fs);let f=await bH(n,d,t);return BV(`Refreshed "${n}" — tools: ${u.length}, apps: ${d.length} (${f} sprinkle${f===1?``:`s`})\n`)}async function lH(e,t){if(e.includes(`--help`)||e.includes(`-h`))return BV(`usage: mcp auth <name> [--silent | --interactive]
|
|
6993
6993
|
|
|
6994
6994
|
Re-authenticate an existing MCP server. By default, attempts a silent
|
|
6995
6995
|
token renewal using the persisted refresh_token; if that returns no
|
|
@@ -7001,7 +7001,7 @@ Options:
|
|
|
7001
7001
|
-i, --interactive Skip silent renewal and open the OAuth popup
|
|
7002
7002
|
directly. Use after revoking a refresh token or
|
|
7003
7003
|
when the AS no longer accepts the cached one.
|
|
7004
|
-
`);let n=e.filter(e=>!e.startsWith(`-`));if(n.length===0)return VV(`mcp auth: expected <name>`);let r=n[0],i=e.includes(`--silent`)||e.includes(`-s`),a=e.includes(`--interactive`)||e.includes(`-i`);if(i&&a)return VV(`mcp auth: --silent and --interactive are mutually exclusive`);let{ensureMcpProviderRegistered:o}=await import(`./provider-
|
|
7004
|
+
`);let n=e.filter(e=>!e.startsWith(`-`));if(n.length===0)return VV(`mcp auth: expected <name>`);let r=n[0],i=e.includes(`--silent`)||e.includes(`-s`),a=e.includes(`--interactive`)||e.includes(`-i`);if(i&&a)return VV(`mcp auth: --silent and --interactive are mutually exclusive`);let{ensureMcpProviderRegistered:o}=await import(`./provider-CE6jDRgx.js`),s=await o(r),{getServer:c}=await import(`./store-FJJcjvMM.js`).then(e=>e.r),l=await c(r,t.fs);if(!l)return VV(`mcp auth: unknown server "${r}" (run \`mcp list\` to see configured servers)`);if(!l.auth)return VV(`mcp auth: server "${r}" does not use OAuth`);if(!s)return VV(`mcp auth: failed to register provider for "${r}"`);let u=`mcp:${r}`,{getRegisteredProviderConfig:d}=await import(`./providers-4qAZLHsD.js`).then(e=>e.r),f=d(u);if(!f)return VV(`mcp auth: provider "${u}" is not registered`);if(a)return await uH(r,f,t);if(!f.onSilentRenew)return i?VV(`mcp auth: provider "${u}" does not support silent renewal; retry without --silent`):await uH(r,f,t);let p=null;try{p=await f.onSilentRenew()}catch(e){let t=e instanceof Error?e.message:String(e);if(i)return VV(`mcp auth: silent renewal for "${r}" failed (${t}); retry without --silent to run the interactive flow`);RV.debug(`mcp auth: silent renewal threw, falling back to interactive`,{name:r,error:t})}return p?BV(`Re-authenticated "${r}" via silent renewal (provider ${u})\n`):i?VV(`mcp auth: silent renewal for "${r}" returned no token; retry without --silent to run the interactive flow`):await uH(r,f,t)}async function uH(e,t,n){if(!t.onOAuthLogin)return VV(`mcp auth: provider "${t.id}" does not support interactive OAuth login`);let r=n.oauthLauncher??await fH(),i=!1;return await t.onOAuthLogin(r,()=>{i=!0}),i?BV(`Re-authenticated "${e}" via interactive login (provider ${t.id})\n`):VV(`mcp auth: interactive login for "${e}" did not complete`)}async function dH(e){let t=`mcp:${e}`,{getOAuthAccountInfo:n}=await import(`./provider-settings-BclOQB4V.js`),r=n(t);if(!r)return null;if(r.expired){try{let{getRegisteredProviderConfig:e}=await import(`./providers-4qAZLHsD.js`).then(e=>e.r),n=await e(t)?.onSilentRenew?.();if(n)return`Bearer ${n}`}catch(e){RV.debug(`silent renewal threw`,{providerId:t,error:e instanceof Error?e.message:String(e)})}return null}return`Bearer ${r.token}`}async function fH(){let{createOAuthLauncher:e}=await import(`./oauth-service-CfqjxAd7.js`);return e()}async function pH(){if(re()){let e=chrome;return e.identity?.getRedirectURL?.(`mcp-callback`)??`https://${e.runtime.id}.chromiumapp.org/mcp-callback`}let{getOAuthPageOrigin:e}=await import(`./oauth-service-CfqjxAd7.js`),{origin:t}=await e();return`${t}/auth/callback`}async function mH(e){if(e)return e;let{createProxiedFetch:t}=await import(`./proxied-fetch-sbHa3Tte.js`).then(e=>e.a),n=t();return async(e,t)=>{let r=await n(e,{method:t?.method,headers:t?.headers,body:t?.body}),i=new TextDecoder().decode(r.body);return{ok:r.status>=200&&r.status<300,status:r.status,statusText:r.statusText,text:async()=>i,json:async()=>JSON.parse(i),headers:{get:e=>r.headers[e.toLowerCase()]??null}}}}async function hH(e){if(e)return e;let{VirtualFS:t}=await import(`./fs-BnRVC9hw.js`).then(e=>e.t),{GLOBAL_FS_DB_NAME:n}=await import(`./global-db-DvmmimLY.js`).then(e=>e.n);return await t.create({dbName:n})}function gH(e){return`// MCP alias for "${e}" — forwards args to \`mcp invoke ${e}\`.
|
|
7005
7005
|
// Auto-generated by \`mcp add ${e}\`; do not edit by hand.
|
|
7006
7006
|
const argv = Array.isArray(process.argv) ? process.argv.slice(2) : [];
|
|
7007
7007
|
const escape = (s) => {
|
|
@@ -7015,7 +7015,7 @@ const r = await exec(cmd);
|
|
|
7015
7015
|
if (r.stdout) process.stdout.write(r.stdout);
|
|
7016
7016
|
if (r.stderr) process.stderr.write(r.stderr);
|
|
7017
7017
|
process.exit(r.exitCode || 0);
|
|
7018
|
-
`}async function _H(e,t){let n=await hH(t.fs);await n.mkdir(zV,{recursive:!0}),await n.writeFile(`${zV}/${e}.jsh`,gH(e)),t.scriptCatalog?.invalidateJsh()}async function vH(e,t){let n=await hH(t.fs),r=`${zV}/${e}.jsh`;try{await n.exists(r)&&await n.rm(r)}catch(e){RV.debug(`alias removal failed`,{path:r,error:e instanceof Error?e.message:String(e)})}t.scriptCatalog?.invalidateJsh()}async function yH(e,t){let{removeAppSprinkles:n}=await import(`./apps-
|
|
7018
|
+
`}async function _H(e,t){let n=await hH(t.fs);await n.mkdir(zV,{recursive:!0}),await n.writeFile(`${zV}/${e}.jsh`,gH(e)),t.scriptCatalog?.invalidateJsh()}async function vH(e,t){let n=await hH(t.fs),r=`${zV}/${e}.jsh`;try{await n.exists(r)&&await n.rm(r)}catch(e){RV.debug(`alias removal failed`,{path:r,error:e instanceof Error?e.message:String(e)})}t.scriptCatalog?.invalidateJsh()}async function yH(e,t){let{removeAppSprinkles:n}=await import(`./apps-C5Sg_4u2.js`);await n(e,t.fs)}async function bH(e,t,n){try{let{materializeAppSprinkles:r}=await import(`./apps-C5Sg_4u2.js`);return(await r(e,t,n.fs)).length}catch(t){return RV.warn(`mcp: failed to materialize app sprinkles`,{name:e,error:t instanceof Error?t.message:String(t)}),0}}const xH=`/.cache/artificial-analysis.json`;async function SH(e,t=!1){if(e&&!t)try{let t=await e.readFile(xH),n=JSON.parse(t);if(Date.now()-n.fetchedAt<864e5)return n.models}catch{}let n=null;try{n=localStorage.getItem(`aa_api_key`)}catch{}let r={Accept:`application/json`};n&&(r[`x-api-key`]=n);let i=p(),a;try{a=await i(`https://artificialanalysis.ai/api/v2/data/llms/models`,{method:`GET`,headers:r})}catch{return[]}if(a.status===401||a.status<200||a.status>=300)return[];let o;try{let e=new TextDecoder().decode(a.body);o=JSON.parse(e)}catch{return[]}let s=(Array.isArray(o)?o:o?.data??o?.models??[]).map(e=>({slug:e.slug??``,name:e.name??``,creator_slug:e.model_creator?.slug??``,intelligence_index:e.evaluations?.artificial_analysis_intelligence_index??null,coding_index:e.evaluations?.artificial_analysis_coding_index??null,speed_tps:e.median_output_tokens_per_second??null}));if(e&&s.length>0){let t={fetchedAt:Date.now(),models:s};try{await e.mkdir(`/.cache`,{recursive:!0}),await e.writeFile(xH,JSON.stringify(t))}catch{}}return s}function CH(e){return e.toLowerCase().replace(/\./g,`-`).replace(/-\d{8}$/,``).replace(/-\d{4}$/,``)}function wH(e,t){let n=e.toLowerCase(),r=t.find(e=>e.slug===n);if(r)return r;let i=CH(e),a=t.find(e=>CH(e.slug)===i);if(a)return a;let o=t.filter(e=>n.includes(e.slug)||e.slug.includes(n));if(o.length>0)return o.sort((e,t)=>t.slug.length-e.slug.length),o[0]}function TH(){return`models - list available LLM models
|
|
7019
7019
|
|
|
7020
7020
|
Usage: models [options]
|
|
7021
7021
|
|
|
@@ -7029,7 +7029,7 @@ Options:
|
|
|
7029
7029
|
-h, --help Show this help message
|
|
7030
7030
|
`}function EH(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`.replace(`.0M`,`M`):e>=1e3?`${(e/1e3).toFixed(0)}K`:`${e}`}function DH(e){return`$${e.toFixed(2)}`}const OH=/\b(embedding|embed|tts|whisper|dall-e|image-gen|audio|vision-preview)\b/i;function kH(e){let t=`${e.id} ${e.name??``}`;return!OH.test(t)}function AH(e){let t=e.toLowerCase();t=t.replace(/-\d{8}$/,``),t=t.replace(/-\d{4}$/,``),t=t.replace(/-(preview|latest)$/,``);let n=t.match(/^(claude-(?:opus|sonnet|haiku))/);if(n)return n[1];let r=t.match(/^(gpt-\d+)(?:\.\d+)?(-[a-z][-a-z]*)?$/);if(r)return r[1]+(r[2]??``);let i=t.match(/^gemini-[\d.]+-(.+)$/);if(i)return`gemini-${i[1]}`;let a=t.match(/^gemini-(\d+)-(.+)$/);if(a)return`gemini-${a[2]}`;let o=t.match(/^grok-[\d.]+-([\w-]+)$/);if(o)return`grok-${o[1]}`;if(t.match(/^(grok)-[\d.]+$/))return`grok`;let s=t.match(/^(o\d+(?:-[a-z]+)?)(?:-\d.*)?$/);return s?s[1]:t.replace(/-[\d.]+$/,``)}function jH(e){let t=new Map;for(let n of e){let e=AH(n.id);(!t.has(e)||n.selected)&&t.set(e,n)}return[...t.values()]}function MH(e,t,n,r,i){let a=i?wH(e.id,i):void 0,o={id:e.id,name:e.name,provider:t,cost:e.cost??{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:e.contextWindow??0,maxTokens:e.maxTokens??0,reasoning:!!e.reasoning,input:e.input??[`text`],selected:e.id===n&&t===r};return a?.intelligence_index!=null&&(o.intelligence=a.intelligence_index),a?.coding_index!=null&&(o.codingScore=a.coding_index),a?.speed_tps!=null&&(o.speed=a.speed_tps),o}function NH(e,t,n,r){let i=[];i.push(`Models for "${e}" (${t}):\n`);for(let e of n){let t=e.selected?` ► `:` `,n=e.id.padEnd(30),r=`${DH(e.cost.input)} / ${DH(e.cost.output)}`,a=`${EH(e.contextWindow)} ctx`,o=e.intelligence==null?``:`IQ:${e.intelligence}`,s=e.speed==null?``:`${Math.round(e.speed)} t/s`,c=e.reasoning?`reasoning`:``,l=o||s?`${o.padEnd(6)} ${s.padEnd(8)}`:``;i.push(`${t}${n} ${r.padEnd(16)} ${a.padEnd(10)} ${l} ${c}`)}return i.push(`\n ${n.length} model${n.length===1?``:`s`} available.`),r&&i.push(` Intelligence data: artificialanalysis.ai`),i.join(`
|
|
7031
7031
|
`)+`
|
|
7032
|
-
`}function PH(e){return G(`models`,async t=>{let{getAccounts:n,getAvailableProviders:r,getProviderConfig:i,getProviderModels:a,getSelectedProvider:o,getSelectedModelId:s,resolveCurrentModel:c}=await import(`./provider-settings-
|
|
7032
|
+
`}function PH(e){return G(`models`,async t=>{let{getAccounts:n,getAvailableProviders:r,getProviderConfig:i,getProviderModels:a,getSelectedProvider:o,getSelectedModelId:s,resolveCurrentModel:c}=await import(`./provider-settings-BclOQB4V.js`);if(t.includes(`--help`)||t.includes(`-h`))return{stdout:TH(),stderr:``,exitCode:0};let l=t.includes(`--json`),u=t.includes(`--all`),d=t.includes(`--all-versions`),f=t.includes(`--refresh`),p=t.includes(`--no-benchmarks`),m=t.indexOf(`--provider`),h=m>=0?t[m+1]:void 0,g=o(),_=s(),v=n();if(v.length===0)return{stdout:``,stderr:`No provider accounts configured. Run the provider settings to add one.
|
|
7033
7033
|
`,exitCode:1};let y=c(),b=y.id,x=y.provider,S;p||(S=await SH(e,f),S.length===0&&(S=void 0));let C;if(h){let e=r();if(!e.includes(h))return{stdout:``,stderr:`Unknown provider: ${h}. Available: ${e.join(`, `)}\n`,exitCode:1};C=[h]}else C=u?[...new Set(v.map(e=>e.providerId))]:[g];let w=[],T=[];for(let e of C){let t=a(e).filter(kH);if(t.length===0){if(!u)return{stdout:``,stderr:`No models available for provider ${e}.\n`,exitCode:1};continue}let n=t.map(t=>MH(t,e,b,x,S)).sort((e,t)=>t.cost.input-e.cost.input);if(d||(n=jH(n)),w.push(...n),!l){let t=i(e);T.push(NH(t.name,e,n,!!S))}}if(l)return{stdout:JSON.stringify(w,null,2)+`
|
|
7034
7034
|
`,stderr:``,exitCode:0};!d&&!l&&T.push(`Showing latest versions only. Use --all-versions to see all.
|
|
7035
7035
|
`);let E=`${x}:${b}`,D=`${g}:${_}`;return T.push(E===D?`Currently using: ${E}\n`:`Currently using: ${E} (selected ${D} — resolved to a different model)\n`),{stdout:T.join(`
|
|
@@ -7069,7 +7069,7 @@ Examples:
|
|
|
7069
7069
|
oauth-domain add adobe '*.da.live'
|
|
7070
7070
|
oauth-domain list adobe
|
|
7071
7071
|
oauth-domain remove adobe admin.da.live
|
|
7072
|
-
`}function UH(){return G(`oauth-domain`,async e=>{if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return{stdout:HH(),stderr:``,exitCode:0};let{getExtraOAuthDomains:t,setExtraOAuthDomainsAsync:n,getAllExtraOAuthDomains:r}=await import(`./provider-settings-
|
|
7072
|
+
`}function UH(){return G(`oauth-domain`,async e=>{if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return{stdout:HH(),stderr:``,exitCode:0};let{getExtraOAuthDomains:t,setExtraOAuthDomainsAsync:n,getAllExtraOAuthDomains:r}=await import(`./provider-settings-BclOQB4V.js`),[i,a,o]=e;try{switch(i){case`list`:{if(a){let e=t(a);return e.length===0?{stdout:`(no extra domains configured for ${a})\n`,stderr:``,exitCode:0}:{stdout:e.join(`
|
|
7073
7073
|
`)+`
|
|
7074
7074
|
`,stderr:``,exitCode:0}}let e=r(),n=Object.entries(e).filter(([,e])=>e.length>0);return n.length===0?{stdout:`(no extra OAuth domains configured)
|
|
7075
7075
|
`,stderr:``,exitCode:0}:{stdout:n.map(([e,t])=>`${e}: ${t.join(`, `)}`).join(`
|
|
@@ -7127,11 +7127,11 @@ Examples:
|
|
|
7127
7127
|
--authorize-url 'https://auth.x.ai/oauth2/auth?...' \\
|
|
7128
7128
|
--redirect-pattern 'http://127.0.0.1:56121/*'
|
|
7129
7129
|
curl -H "Authorization: Bearer $(oauth-token github)" https://api.github.com/user
|
|
7130
|
-
`}function GH(){return G(`oauth-token`,async(e,t)=>{let{getOAuthAccountInfo:n,getSelectedProvider:r,getAccounts:i}=await import(`./provider-settings-
|
|
7130
|
+
`}function GH(){return G(`oauth-token`,async(e,t)=>{let{getOAuthAccountInfo:n,getSelectedProvider:r,getAccounts:i}=await import(`./provider-settings-BclOQB4V.js`),{getRegisteredProviderConfig:a,getRegisteredProviderIds:o}=await import(`./providers-4qAZLHsD.js`).then(e=>e.r);if(e.includes(`--help`)||e.includes(`-h`))return{stdout:WH(),stderr:``,exitCode:0};if(e.includes(`--list`))return ZH(i,o,a,n);if(e.includes(`--renew`))return KH(e);if(e.includes(`--from-file`)||e.includes(`--intercept`))return JH(e,t);let s,c=e.indexOf(`--scope`);if(c>=0){if(s=e[c+1]?.trim(),!s||s.startsWith(`-`))return{stdout:``,stderr:`oauth-token: --scope requires a value
|
|
7131
7131
|
`,exitCode:1};e.splice(c,2)}let l,u=e.indexOf(`--provider`);if(u>=0){if(l=e[u+1],!l)return{stdout:``,stderr:`oauth-token: --provider requires a value
|
|
7132
7132
|
`,exitCode:1}}else if(e.length>0)l=e[0];else{let e=r(),t=a(e);if(t?.isOAuth&&(t.onOAuthLogin||t.onOAuthLoginIntercepted))l=e;else if(l=o().find(e=>{let t=a(e);return t?.isOAuth&&(t.onOAuthLogin||t.onOAuthLoginIntercepted)}),!l)return{stdout:``,stderr:`oauth-token: no OAuth providers configured
|
|
7133
7133
|
`,exitCode:1}}let d=a(l);if(!d)return{stdout:``,stderr:`oauth-token: unknown provider "${l}"\n`,exitCode:1};if(!d.isOAuth||!d.onOAuthLogin&&!d.onOAuthLoginIntercepted)return{stdout:``,stderr:`oauth-token: provider "${l}" is not an OAuth provider\n`,exitCode:1};if(!s){let e=n(l);if(e&&!e.expired){let t=e.maskedValue;return t?{stdout:`${t}\n`,stderr:``,exitCode:0}:{stdout:``,stderr:`oauth-token: no masked value for ${l} (try logging in again)\n`,exitCode:1}}}try{if(d.onOAuthLoginIntercepted){let{createInterceptingOAuthLauncherForCurrentRuntime:e}=await import(`./oauth-service-CfqjxAd7.js`),t=await e();if(!t)return{stdout:``,stderr:`oauth-token: provider "${l}" needs the controlled-browser interceptor, but no CDP transport is available in this runtime.\n`,exitCode:1};await d.onOAuthLoginIntercepted(t,()=>{},s?{scopes:s}:void 0)}else if(d.onOAuthLogin){let{createOAuthLauncher:e}=await import(`./oauth-service-CfqjxAd7.js`),t=e();await d.onOAuthLogin(t,()=>{},s?{scopes:s}:void 0)}else return{stdout:``,stderr:`oauth-token: provider "${l}" has no OAuth login hook\n`,exitCode:1};let e=n(l);if(e?.token){let t=e.maskedValue;return t?{stdout:`${t}\n`,stderr:``,exitCode:0}:{stdout:``,stderr:`oauth-token: no masked value for ${l} (try logging in again)\n`,exitCode:1}}return console.error(`[oauth-token] Provider ${l}: login completed but no token was saved`),{stdout:``,stderr:`oauth-token: login completed but no token was saved
|
|
7134
|
-
`,exitCode:1}}catch(e){let t=e instanceof Error?e.message:String(e);return console.error(`[oauth-token] Provider ${l}: login failed:`,t),{stdout:``,stderr:`oauth-token: login failed: ${t}\n`,exitCode:1}}})}async function KH(e){let{getSelectedProvider:t,getOAuthAccountInfo:n}=await import(`./provider-settings-
|
|
7134
|
+
`,exitCode:1}}catch(e){let t=e instanceof Error?e.message:String(e);return console.error(`[oauth-token] Provider ${l}: login failed:`,t),{stdout:``,stderr:`oauth-token: login failed: ${t}\n`,exitCode:1}}})}async function KH(e){let{getSelectedProvider:t,getOAuthAccountInfo:n}=await import(`./provider-settings-BclOQB4V.js`),{getRegisteredProviderConfig:r,getRegisteredProviderIds:i}=await import(`./providers-4qAZLHsD.js`).then(e=>e.r),a=e.filter(e=>!e.startsWith(`-`))[0];if(!a){let e=t();a=r(e)?.onSilentRenew?e:i().find(e=>r(e)?.onSilentRenew)}if(!a)return XH(`oauth-token --renew: no provider supports silent renewal`);let o=r(a);if(!o)return XH(`oauth-token --renew: unknown provider "${a}"`);if(!o.onSilentRenew)return XH(`oauth-token --renew: provider "${a}" has no onSilentRenew hook`);let s=n(a),c=s?.token,l=[`oauth-token --renew ${a}`];l.push(` before: ${qH(s)}`);let u=null,d=null;try{u=await o.onSilentRenew()}catch(e){d=e instanceof Error?e.message:String(e)}if(d)l.push(` silent renewal: ERROR — ${d}`);else if(u){let e=n(a),t=!!(c&&e?.token&&c!==e.token);l.push(` silent renewal: SUCCESS${t?` — token refreshed`:` (token unchanged)`}`),l.push(` after: ${qH(e)}`)}else l.push(` silent renewal: FAILED (onSilentRenew returned null)`),l.push(` → no window should have appeared. Open DevTools console and`),l.push(` look for "[oauth-service] Extension OAuth error" / "[adobe]" to see`),l.push(` the IMS/Chrome reason (e.g. login_required).`);return{stdout:l.join(`
|
|
7135
7135
|
`)+`
|
|
7136
7136
|
`,stderr:``,exitCode:+!u}}function qH(e){if(!e)return`no token`;if(e.expired)return`expired`;if(e.expiresAt){let t=e.expiresAt-Date.now();if(t>0){let e=Math.floor(t/36e5),n=Math.floor(t%36e5/6e4);return e>0?`valid, expires in ${e}h ${n}m`:`valid, expires in ${n}m`}}return`valid`}async function JH(e,t){let{parseInterceptOAuthConfig:n}=await import(`./intercepted-oauth-CaCw-rJ5.js`).then(e=>e.n),{createInterceptingOAuthLauncherForCurrentRuntime:r}=await import(`./oauth-service-CfqjxAd7.js`),i,a=e.indexOf(`--from-file`);if(a>=0){let n=e[a+1];if(!n)return XH(`oauth-token: --from-file requires a path`);try{let e=t.fs.resolvePath(t.cwd,n),r=await t.fs.readFile(e);i=JSON.parse(typeof r==`string`?r:new TextDecoder().decode(r))}catch(e){return XH(`oauth-token: failed to read ${n}: ${e instanceof Error?e.message:String(e)}`)}}else{let t=YH(e,`--authorize-url`),n=YH(e,`--redirect-pattern`);if(!t)return XH(`oauth-token: --authorize-url is required`);if(!n)return XH(`oauth-token: --redirect-pattern is required`);let r=[];for(let t=0;t<e.length;t++){if(e[t]!==`--rewrite`)continue;let n=e[t+1];if(!n)return XH(`oauth-token: --rewrite requires a value`);let i=n.split(`=`);if(i.length<3)return XH(`oauth-token: --rewrite "${n}" must be "<match>=<key>=<value>"`);let[a,o,...s]=i;r.push({match:a,appendParams:{[o]:s.join(`=`)}})}i={authorizeUrl:t,redirectUriPattern:n,onCapture:e.includes(`--leave-tab`)?`leave`:`close`,...r.length>0?{rewrite:r}:{}}}let o=n(i);if(!o.ok)return XH(`oauth-token: invalid intercept config: ${o.error}`);let s=await r();if(!s)return XH(`oauth-token: no CDP transport available in this runtime; --intercept needs the controlled browser.`);let c=await s(o.config);return c?{stdout:`${c}\n`,stderr:``,exitCode:0}:XH(`oauth-token: intercept timed out or was cancelled`)}function YH(e,t){let n=e.indexOf(t);if(n<0)return;let r=e[n+1];if(!(!r||r.startsWith(`--`)))return r}function XH(e){return{stdout:``,stderr:`${e}\n`,exitCode:1}}function ZH(e,t,n,r){let i=t().filter(e=>n(e)?.isOAuth);if(i.length===0)return{stdout:`No OAuth providers configured.
|
|
7137
7137
|
`,stderr:``,exitCode:0};let a=[];for(let e of i){let t=r(e);if(!t)a.push(`${e} (no token)`);else if(t.expired){let n=t.userName?` as ${t.userName}`:``;a.push(`${e} (expired${n})`)}else{let n=[];if(t.userName?n.push(`logged in as ${t.userName}`):n.push(`logged in`),t.expiresAt){let e=t.expiresAt-Date.now();if(e>0){let t=Math.floor(e/36e5),r=Math.floor(e%36e5/6e4);t>0?n.push(`expires in ${t}h`):n.push(`expires in ${r}m`)}}a.push(`${e} (${n.join(`, `)})`)}}return{stdout:a.join(`
|
|
@@ -8755,5 +8755,5 @@ ${t}
|
|
|
8755
8755
|
`)+`
|
|
8756
8756
|
`;case`cmdline`:return`kernel-host\0`;case`cwd`:return`/
|
|
8757
8757
|
`;case`stat`:return`1 (kernel-host) R 0 - 0 -
|
|
8758
|
-
`}}function ZX(e){let t=e instanceof Error?e.message:String(e),n=e?.code;return typeof n==`string`&&/^E[A-Z]+$/.test(n)?{ok:!1,errno:n,message:t}:{ok:!1,errno:`EIO`,message:t}}async function QX(e){let t=RO(e.token);if(!t)return{ok:!1,errno:`EACCES`,message:`sync-fs: unknown or revoked token`};let{fs:n,cwd:r}=t;try{let t=n.resolvePath(r,e.path);switch(e.op){case`read`:return{ok:!0,kind:`bytes`,bytes:await n.readFileBuffer(t)};case`write`:return await n.writeFile(t,e.body??new Uint8Array),{ok:!0,kind:`void`};case`exists`:return{ok:!0,kind:`json`,json:await n.exists(t)};case`stat`:{let e=await n.stat(t);return{ok:!0,kind:`json`,json:{isDirectory:e.isDirectory,isFile:e.isFile,size:e.size}}}case`readdir`:return{ok:!0,kind:`json`,json:await n.readdir(t)};case`mkdir`:return await n.mkdir(t,{recursive:!0}),{ok:!0,kind:`void`};case`rm`:return await n.rm(t,{recursive:!0}),{ok:!0,kind:`void`};case`rename`:{let i=n.resolvePath(r,e.arg2??``),a=n;if(a.rename)await a.rename(t,i);else if(a.mv)await a.mv(t,i);else{let e=await n.readFileBuffer(t);await n.writeFile(i,e),await n.rm(t,{recursive:!0})}return{ok:!0,kind:`void`}}default:return{ok:!1,errno:`EINVAL`,message:`sync-fs: unknown op '${e.op}'`}}}catch(e){return ZX(e)}}function $X(e={}){let t=e.channel===void 0;if(t&&!e.nonce)throw Error(`installSyncFsResponder: a nonce (or a test channel) is required`);let n=e.channel??new BroadcastChannel(
|
|
8759
|
-
`,r=``;try{let t=await i.readFile(e);r=typeof t==`string`?t:new TextDecoder().decode(t)}catch{}await i.writeFile(e,r+n)},log:e=>{a.info?.(`browser.websocket frame`,{payload:e})}}})}}async function lZ(e,t,n){try{let{startLickWsBridge:t}=await import(`./lick-ws-bridge-C_bJMGw6.js`);return t(e,{locationHref:self.location.href,lickWsUrl:n??null}).stop}catch(e){return(t.error?.bind(t)??t.warn.bind(t)??((e,t)=>console.error(`[lick-ws-bridge]`,e,t)))(`Failed to start lick-ws bridge — webhook / crontask / handoff lick delivery is non-functional in this session`,{error:e instanceof Error?e.message:String(e)}),null}}function uZ(e,t,n){let r=e.getTransport();if(r.isExtensionBridge)return n.debug?.(`Skipping NavigationWatcher: extension-bridge transport rejects sessionless Target.* discovery; the service worker observes handoffs via chrome.webRequest`),null;try{let e=new yi(r,e=>{let n={url:e.url,verb:e.verb,target:e.target};e.instruction!=null&&(n.instruction=e.instruction),e.branch!=null&&(n.branch=e.branch),e.path!=null&&(n.path=e.path),e.title!=null&&(n.title=e.title),t.emitEvent({type:`navigate`,navigateUrl:e.url,targetScoop:void 0,timestamp:new Date().toISOString(),body:n})},dZ(t));return e.start(),()=>e.stop()}catch(e){return n.warn(`Failed to start NavigationWatcher`,e),null}}function dZ(e){let t=p();return{onDiscovery:t=>{e.emitEvent({type:`discovery`,targetScoop:void 0,timestamp:new Date().toISOString(),discoveryOrigin:t.origin,discoveryKind:t.kind,discoveryUrl:t.url,body:{origin:t.origin,kind:t.kind,url:t.url,targetId:t.targetId}})},probeFetch:async(e,n)=>{let r=t(e,{method:n?.method??`GET`}),i=n?.signal,a=i?await Promise.race([r,new Promise((e,t)=>{if(i.aborted){t(Error(`aborted`));return}i.addEventListener(`abort`,()=>t(Error(`aborted`)),{once:!0})})]):await r,o=a.headers;return{ok:a.status>=200&&a.status<300,status:a.status,headers:{get(e){return o?o[e.toLowerCase()]??o[e]??null:null}}}},isDiscoveryEnabled:()=>zX()}}function fZ(e,t,n){(async()=>{try{let{getAllMountEntries:r}=await import(`./mount-table-store-CTrzlrNn.js`).then(e=>e.r),{recoverMounts:i}=await import(`./mount-recovery-l9BFFyMp.js`).then(e=>e.n),a=await r();if(a.length===0)return;let{needsRecovery:o}=await i(a,e,n);if(o.length===0)return;t.emitEvent({type:`session-reload`,targetScoop:void 0,timestamp:new Date().toISOString(),body:{reason:`mount-recovery`,mounts:o}})}catch(e){n.warn(`mount recovery failed`,e)}})()}function pZ(e,t){(async()=>{try{let{detectUpgrade:t,recordVersionSeen:n}=await import(`./upgrade-detection-BW3VRd1P.js`),r=await t();if(!r.isUpgrade||r.lastSeen===null)return;e.emitEvent({type:`upgrade`,targetScoop:void 0,timestamp:new Date().toISOString(),upgradeFromVersion:r.lastSeen,upgradeToVersion:r.bundled.version,body:{from:r.lastSeen,to:r.bundled.version,releasedAt:r.bundled.releasedAt}}),await n(r.bundled.version)}catch(e){t.warn(`Upgrade detection failed`,e)}})()}async function mZ(e,t,n){try{let{BshWatchdog:n}=await import(`./bsh-watchdog-cTkGOVHJ.js`),{ScriptCatalog:r}=await import(`./script-catalog-BYXhqRAc.js`).then(e=>e.n),i=new r({jshFs:e,bshFs:e,watcher:e.getWatcher()}),a=new n({browserAPI:t,scriptCatalog:i,fs:e});return a.start(),{bshWatchdogStop:()=>a.stop(),scriptCatalogDispose:()=>i.dispose()}}catch(e){return n.warn(`Failed to start BSH watchdog`,e),{bshWatchdogStop:null,scriptCatalogDispose:null}}}function hZ(){return E()}async function gZ(e){let{container:t,browser:n,bridge:r,callbacks:i,skipConeBootstrap:a=!1}=e,o=e.logger??console,{processManager:s,orchestrator:c,unsubLeader:l,unsubFollower:u,sharedFs:d}=await iZ(t,n,r,i);if(d?Ui(c,d,c.getSessionStore()):o.warn(`AgentBridge not published — orchestrator.getSharedFS() returned null`),d)try{await d.mountInternal(`/proc`,new BX(s))}catch(e){o.warn(`Failed to mount /proc`,e)}let f=await aZ(c,e,o);d&&sZ({orchestrator:c,processManager:s,lickManager:f,sharedFs:d}),globalThis.__slicc_lickManager=f;let{wsBridge:p,wsRegistry:m}=await cZ({browser:n,lickManager:f,orchestrator:c,sharedFs:d,log:o});globalThis.__slicc_wsSubscribers=m;let h=null;hZ()&&(h=await lZ(f,o,e.localLickWsUrl??null));let g=uZ(n,f,o);d&&fZ(d,f,o),a||await oZ(c),d&&pZ(f,o);let _=null,v=null;d&&({bshWatchdogStop:_,scriptCatalogDispose:v}=await mZ(d,n,o));let y=null;d&&e.syncFsChannelNonce&&(y=$X({nonce:e.syncFsChannelNonce}).dispose);let b=!1;return{orchestrator:c,browser:n,bridge:r,lickManager:f,sharedFs:d??null,processManager:s,async dispose(){b||(b=!0,await _Z({unsubLeader:l,unsubFollower:u,bshWatchdogStop:_,scriptCatalogDispose:v,lickWsBridgeStop:h,navigationWatcherStop:g,syncFsResponderDispose:y,sharedFs:d,wsRegistry:m,wsBridge:p,processManager:s,lickManager:f,browser:n,log:o}))}}}async function _Z(e){let{sharedFs:t,wsRegistry:n,wsBridge:r,processManager:i,lickManager:a,browser:o,log:s}=e;if(e.unsubLeader?.(),e.unsubFollower?.(),e.bshWatchdogStop?.(),e.scriptCatalogDispose?.(),e.lickWsBridgeStop?.(),e.syncFsResponderDispose?.(),e.navigationWatcherStop)try{await e.navigationWatcherStop()}catch(e){s.warn(`NavigationWatcher.stop() failed`,e)}if(t)try{await t.unmountInternal(`/proc`)}catch{}try{n.dispose()}catch(e){s.warn(`WsSubscriberRegistry.dispose() failed`,e)}try{r.dispose()}catch(e){s.warn(`CdpWsPageBridge.dispose() failed`,e)}vZ({processManager:i,lickManager:a,browser:o,wsRegistry:n})}function vZ(e){let t=globalThis;t.__slicc_pm===e.processManager&&delete t.__slicc_pm,t.__slicc_lickManager===e.lickManager&&delete t.__slicc_lickManager,e.browser&&t.__slicc_browser===e.browser&&delete t.__slicc_browser,e.wsRegistry&&t.__slicc_wsSubscribers===e.wsRegistry&&delete t.__slicc_wsSubscribers,delete t[vJ]}const yZ=`x-bypass-llm-proxy`;function bZ(e,t,n){return t?(r,i)=>{if(!xZ(r,t,n))return e(r,i);let a=new Headers(i?.headers);return a.has(yZ)||a.set(yZ,`1`),e(r,{...i,headers:a})}:e}function xZ(e,t,n){if(CZ(e,t))return!0;let r=n?.()??null;return r?SZ(e,r,t):!1}function SZ(e,t,n){let r=wZ(e),i,a;try{i=new URL(r,n),a=new URL(t)}catch{return!1}return i.origin===a.origin&&i.pathname.startsWith(`/api/`)}function CZ(e,t){let n=wZ(e);try{return new URL(n,t).origin===t}catch{return!0}}function wZ(e){return typeof e==`string`?e:e instanceof URL?e.href:e.url}function TZ(e,t={}){let n=t.onError??(e=>console.error(`[kernel-worker] boot failed`,e)),r=t.onDuplicate??(()=>console.warn(`[kernel-worker] received duplicate kernel-worker-init; ignoring`)),i=!1;return{handle(t){if(i){r();return}i=!0,e(t).catch(e=>{i=!1,n(e)})},isInitialized(){return i}}}var EZ=class{transport;createShell;log;pm;defaultOwner;sessions=new Map;unsubscribe=null;constructor(e){this.transport=e.transport,this.createShell=e.createShell,this.log=e.logger??console,this.pm=e.processManager??null,this.defaultOwner=e.defaultOwner??{kind:`system`}}start(){return this.unsubscribe||=this.transport.onMessage(e=>{if(!DZ(e)||e.source!==`panel`)return;let t=e.payload;kZ(t)&&this.handleControl(t).catch(e=>{this.log.warn(`[terminal-session-host] handler error`,e)})}),()=>this.dispose()}dispose(){this.unsubscribe?.(),this.unsubscribe=null;for(let[,e]of this.sessions)e.currentProcess&&this.pm?(this.pm.signal(e.currentProcess.pid,`SIGTERM`),this.pm.exit(e.currentProcess.pid,null)):e.currentExec?.abort(),e.shell.dispose?.();this.sessions.clear()}async handleControl(e){switch(e.type){case`terminal-open`:return this.handleOpen(e);case`terminal-close`:return this.handleClose(e);case`terminal-exec`:return this.handleExec(e);case`terminal-signal`:return this.handleSignal(e);case`terminal-stdin`:case`terminal-resize`:return}}async handleOpen(e){if(this.sessions.has(e.sid)){this.emitStatus(e.sid,`error`,`session already open`);return}try{let t=this.createShell(e.sid,{cwd:e.cwd,env:e.env});this.sessions.set(e.sid,{shell:t,currentExec:null,currentProcess:null}),this.emitStatus(e.sid,`opened`)}catch(t){this.emitStatus(e.sid,`error`,t instanceof Error?t.message:String(t))}}async handleClose(e){let t=this.sessions.get(e.sid);t&&(t.currentProcess&&this.pm?(this.pm.signal(t.currentProcess.pid,`SIGTERM`),this.pm.exit(t.currentProcess.pid,null)):t.currentExec?.abort(),t.shell.dispose?.(),this.sessions.delete(e.sid),this.emitStatus(e.sid,`closed`))}emitExit(e,t){this.emit({type:`terminal-exit`,sid:e.sid,execId:e.execId,exitCode:t})}emitStream(e,t,n){this.emit({type:`terminal-output`,sid:e.sid,execId:e.execId,stream:t,data:n})}async handleExec(e){let t=this.sessions.get(e.sid);if(!t){this.emitExit(e,127),this.log.warn(`[terminal-session-host] exec on unknown session`,e.sid);return}if(t.currentExec){this.emitExit(e,130);return}let n=new AbortController;t.currentExec=n;let r=this.pm?this.pm.spawn({kind:`shell`,argv:[e.command],cwd:t.shell.getCwd?.()??void 0,owner:this.defaultOwner,adoptAbort:n}):null;t.currentProcess=r;try{let i=await t.shell.executeCommand(e.command,n.signal,r?.pid);await this.emitExecSuccess(e,i,n,r)}catch(t){this.emitExecError(e,t,n,r)}finally{t.currentExec===n&&(t.currentExec=null,t.currentProcess=null)}}async emitExecSuccess(e,t,n,r){let i=n.signal.aborted?OZ(r?.terminatedBy??`SIGINT`):t.exitCode;n.signal.aborted||(r&&await r.gate.wait(),t.stdout&&this.emitStream(e,`stdout`,t.stdout),t.stderr&&this.emitStream(e,`stderr`,t.stderr)),this.emitExit(e,i),r&&this.pm&&this.pm.exit(r.pid,n.signal.aborted?null:t.exitCode)}emitExecError(e,t,n,r){if(n.signal.aborted){this.emitExit(e,OZ(r?.terminatedBy??`SIGINT`)),r&&this.pm&&this.pm.exit(r.pid,null);return}let i=t instanceof Error?t.message:String(t);this.emitStream(e,`stderr`,`Error: ${i}\n`),this.emitExit(e,1),r&&this.pm&&this.pm.exit(r.pid,1)}async handleSignal(e){let t=this.sessions.get(e.sid);if(!t){this.log.warn(`[terminal-session-host] signal on unknown session`,e.sid);return}(e.signal===`SIGINT`||e.signal===`SIGTERM`||e.signal===`SIGKILL`)&&(t.currentProcess&&this.pm?this.pm.signal(t.currentProcess.pid,e.signal):t.currentExec?.abort())}emit(e){this.transport.send(e)}emitStatus(e,t,n){let r=n?{type:`terminal-status`,sid:e,state:t,error:n}:{type:`terminal-status`,sid:e,state:t};this.emit(r)}};function DZ(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function OZ(e){switch(e){case`SIGINT`:return 130;case`SIGTERM`:return 143;case`SIGKILL`:return 137;case`SIGSTOP`:case`SIGCONT`:return 130}}function kZ(e){if(typeof e!=`object`||!e)return!1;let t=e.type;return t===`terminal-open`||t===`terminal-close`||t===`terminal-exec`||t===`terminal-signal`||t===`terminal-stdin`||t===`terminal-resize`}var AZ=class extends SY{sid;transport;constructor(e,t,n){super(n),this.sid=e,this.transport=t}async renderMediaPreview(e){for(let t of e){let e=``,n=t.bytes,r=8192;for(let t=0;t<n.length;t+=r)e+=String.fromCharCode(...n.subarray(t,t+r));let i={type:`terminal-media-preview`,sid:this.sid,path:t.path,mediaType:t.mimeType,data:btoa(e)};this.transport.send(i)}}};function jZ(e){let{transport:t,fs:n,browser:r,processManager:i,sudoManager:a}=e,o=e.logger??console,s=a?.getShellConfig({transparentGating:!1}),c=new EZ({transport:t,processManager:i,createShell:(e,a)=>new AZ(e,t,{fs:n,cwd:a.cwd,env:a.env,browserAPI:r,processManager:i,processOwner:{kind:`system`},sudo:s}),logger:o});return{host:c,stop:c.start()}}function MZ(e){let t=new NZ(e);return t.start(),{stop:()=>t.dispose()}}var NZ=class{transport;client;writableClient;log;unsubscribe=null;constructor(e){this.transport=e.transport,this.client=e.client,this.writableClient=e.writableClient??null,this.log=e.logger??console}start(){this.unsubscribe||=this.transport.onMessage(e=>{if(!PZ(e)||e.source!==`panel`)return;let t=e.payload;if(FZ(t)){this.handleRequest(t).catch(e=>{this.log.warn(`[vfs-rpc-host] handler unexpectedly threw`,e)});return}if(IZ(t)){this.handleWriteRequest(t).catch(e=>{this.log.warn(`[vfs-rpc-host] write handler unexpectedly threw`,e)});return}})}dispose(){this.unsubscribe?.(),this.unsubscribe=null}async handleRequest(e){switch(e.type){case`vfs-read-dir`:return this.handleReadDir(e);case`vfs-read-file`:return this.handleReadFile(e);case`vfs-stat`:return this.handleStat(e)}}async handleReadDir(e){try{let t=await this.client.readDir(e.path),n={type:`vfs-read-dir-result`,requestId:e.requestId,ok:!0,entries:t};this.transport.send(n)}catch(t){this.emitError(`vfs-read-dir-result`,e.requestId,t,e.path)}}async handleReadFile(e){let t=e.encoding??`utf-8`;try{let n=await this.client.readFile(e.path,{encoding:t});if(t===`binary`){if(!(n instanceof Uint8Array)){this.emitError(`vfs-read-file-result`,e.requestId,new ge(`EIO`,`readFile(binary) did not return Uint8Array`),e.path);return}let t={type:`vfs-read-file-result`,requestId:e.requestId,ok:!0,encoding:`binary`,data:n},r=n.buffer,i=typeof ArrayBuffer<`u`&&r instanceof ArrayBuffer?[r]:void 0;this.transport.send(t,i)}else{if(typeof n!=`string`){this.emitError(`vfs-read-file-result`,e.requestId,new ge(`EIO`,`readFile(utf-8) did not return string`),e.path);return}let t={type:`vfs-read-file-result`,requestId:e.requestId,ok:!0,encoding:`utf-8`,data:n};this.transport.send(t)}}catch(t){this.emitError(`vfs-read-file-result`,e.requestId,t,e.path)}}async handleStat(e){try{let t=await this.client.stat(e.path),n={type:`vfs-stat-result`,requestId:e.requestId,ok:!0,stats:t};this.transport.send(n)}catch(t){this.emitError(`vfs-stat-result`,e.requestId,t,e.path)}}async handleWriteRequest(e){if(!this.writableClient){this.emitWriteError(LZ(e.type),e.requestId,new ge(`EACCES`,`vfs-rpc-host has no writable backend wired`),RZ(e));return}switch(e.type){case`vfs-write-file`:return this.handleWriteFile(e,this.writableClient);case`vfs-mkdir`:return this.handleMkdir(e,this.writableClient);case`vfs-rm`:return this.handleRm(e,this.writableClient);case`vfs-flush`:return this.handleFlush(e,this.writableClient);case`vfs-list-mount-points`:return this.handleListMountPoints(e,this.writableClient)}}async handleWriteFile(e,t){try{if(e.encoding===`binary`){if(!(e.data instanceof Uint8Array)){this.emitWriteError(`vfs-write-file-result`,e.requestId,new ge(`EIO`,`vfs-write-file(binary) data is not Uint8Array`),e.path);return}}else if(typeof e.data!=`string`){this.emitWriteError(`vfs-write-file-result`,e.requestId,new ge(`EIO`,`vfs-write-file(utf-8) data is not string`),e.path);return}let n=e.recursive===void 0?void 0:{recursive:e.recursive};await t.writeFile(e.path,e.data,n);let r={type:`vfs-write-file-result`,requestId:e.requestId,ok:!0};this.transport.send(r)}catch(t){this.emitWriteError(`vfs-write-file-result`,e.requestId,t,e.path)}}async handleMkdir(e,t){try{let n=e.recursive===void 0?void 0:{recursive:e.recursive};await t.mkdir(e.path,n);let r={type:`vfs-mkdir-result`,requestId:e.requestId,ok:!0};this.transport.send(r)}catch(t){this.emitWriteError(`vfs-mkdir-result`,e.requestId,t,e.path)}}async handleRm(e,t){try{let n=e.recursive===void 0?void 0:{recursive:e.recursive};await t.rm(e.path,n);let r={type:`vfs-rm-result`,requestId:e.requestId,ok:!0};this.transport.send(r)}catch(t){this.emitWriteError(`vfs-rm-result`,e.requestId,t,e.path)}}async handleFlush(e,t){try{await t.flush();let n={type:`vfs-flush-result`,requestId:e.requestId,ok:!0};this.transport.send(n)}catch(t){this.emitWriteError(`vfs-flush-result`,e.requestId,t,``)}}async handleListMountPoints(e,t){if(!t.listMountPoints){this.emitWriteError(`vfs-list-mount-points-result`,e.requestId,new ge(`EACCES`,`vfs-rpc-host has no mount-aware backend wired`),``);return}try{let n=await t.listMountPoints(),r={type:`vfs-list-mount-points-result`,requestId:e.requestId,ok:!0,mountPoints:n};this.transport.send(r)}catch(t){this.emitWriteError(`vfs-list-mount-points-result`,e.requestId,t,``)}}emitError(e,t,n,r){let i=zZ(n,r);switch(e){case`vfs-read-dir-result`:{let e={type:`vfs-read-dir-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}case`vfs-read-file-result`:{let e={type:`vfs-read-file-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}case`vfs-stat-result`:{let e={type:`vfs-stat-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}}}emitWriteError(e,t,n,r){let i=zZ(n,r);switch(r===``&&i.path===``&&delete i.path,e){case`vfs-write-file-result`:{let e={type:`vfs-write-file-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}case`vfs-mkdir-result`:{let e={type:`vfs-mkdir-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}case`vfs-rm-result`:{let e={type:`vfs-rm-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}case`vfs-flush-result`:{let e={type:`vfs-flush-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}case`vfs-list-mount-points-result`:{let e={type:`vfs-list-mount-points-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}}}};function PZ(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function FZ(e){if(typeof e!=`object`||!e)return!1;let t=e.type;return t===`vfs-read-dir`||t===`vfs-read-file`||t===`vfs-stat`}function IZ(e){if(typeof e!=`object`||!e)return!1;let t=e.type;return t===`vfs-write-file`||t===`vfs-mkdir`||t===`vfs-rm`||t===`vfs-flush`||t===`vfs-list-mount-points`}function LZ(e){switch(e){case`vfs-write-file`:return`vfs-write-file-result`;case`vfs-mkdir`:return`vfs-mkdir-result`;case`vfs-rm`:return`vfs-rm-result`;case`vfs-flush`:return`vfs-flush-result`;case`vfs-list-mount-points`:return`vfs-list-mount-points-result`}}function RZ(e){return e.type===`vfs-flush`||e.type===`vfs-list-mount-points`?``:e.path}function zZ(e,t){return e instanceof ge?{code:e.code,message:e.message,path:e.path??t}:{code:`EIO`,message:e instanceof Error?e.message:String(e),path:t}}function BZ(){let e=globalThis.fetch;if(!e)return;let t=self?.location?self.location.origin:void 0;globalThis.fetch=bZ(e.bind(globalThis),t,VZ)}function VZ(){let e=u();if(!e)return null;try{return new URL(e).origin}catch{return null}}function HZ(e){let t=new Map(Object.entries(e));Object.defineProperty(globalThis,"localStorage",{value:{get length(){return t.size},key(e){return Array.from(t.keys())[e]??null},getItem(e){return t.has(e)?t.get(e):null},setItem(e,n){t.set(e,n)},removeItem(e){t.delete(e)},clear(){t.clear()}},configurable:!0,writable:!0})}let UZ=null,WZ=null,GZ=null,KZ=null,qZ=null;const JZ=TZ(e=>YZ(e));self.addEventListener(`message`,e=>{e.data?.type===`kernel-worker-init`&&JZ.handle(e.data)});async function YZ(e){Xn(e.instanceId);try{BZ(),d(e.localApiBaseUrl??null),_(e.bridgeToken??null),Nk(e.syncFsBridgeEnabled??!1),s(e.extensionDelegateId??null),HZ(e.localStorageSeed??{}),gr().catch(()=>{}),await o();let t=Or(e.kernelPort),n=new ui(t),i=ui.createCallbacks(n),a=new kr(e.cdpPort);await a.connect();let c=new Bn(a);UZ=await gZ({container:{},browser:c,bridge:n,callbacks:i,logger:console,localLickWsUrl:e.localLickWsUrl??null,syncFsChannelNonce:e.syncFsChannelNonce??null});let{createSprinkleManagerProxyOverChannel:l}=await import(`./sprinkle-bridge-channel-14cdGa6x.js`),u=l({instanceId:e.instanceId});globalThis.__slicc_sprinkleManager=u;let f=UZ.sharedFs?.getWatcher();if(f){let e=[`/workspace`,`/shared`,`/scoops`],t=null,n=new Set;for(let r of e)f.watch(r,e=>e.endsWith(`.shtml`),e=>{for(let t of e){let e=t.path.split(`/`).pop()?.replace(/\.shtml$/,``);e&&n.add(e)}t||=setTimeout(()=>{t=null;for(let e of n)u.reload(e).catch(()=>{});n.clear()},300)})}let{createPanelRpcClient:p}=await import(`./panel-rpc-CjFVE0nK.js`).then(e=>e.i);qZ=p({instanceId:e.instanceId}),globalThis.__slicc_panelRpc=qZ,c.setTrayTargetProvider(Kn(r));let m=await XZ({host:UZ,transport:t,browser:c,instanceId:e.instanceId});m&&(WZ=m.stopTerminalHost,GZ=m.stopVfsRpcHost,KZ=m.stopSpeechAssetsResponder),e.kernelPort.postMessage({type:`kernel-worker-ready`})}catch(e){throw Qn(e),e}}async function XZ(e){let t=e.host.sharedFs;if(!t)return console.warn(`[kernel-worker] shared FS unavailable; terminal sessions will fail to open`),null;let n=jZ({transport:e.transport,fs:t,browser:e.browser,processManager:e.host.processManager,sudoManager:e.host.orchestrator.getSudoManager(),logger:console}),r=MZ({transport:e.transport,client:t,writableClient:t,logger:console}),i=await ZZ(t,e.instanceId);return{stopTerminalHost:n.stop,stopVfsRpcHost:r.stop,stopSpeechAssetsResponder:i}}async function ZZ(e,t){let{installSpeechAssetsResponder:n}=await import(`./speech-assets-bridge-BUDIvdid.js`),{ensureSpeechAssetsStaged:r}=await import(`./ensure-speech-assets-pHHH7zOs.js`),{createProxiedFetch:i}=await import(`./proxied-fetch-sbHa3Tte.js`).then(e=>e.a),a=i();return n({instanceId:t,ensure:t=>r({fs:e,fetch:a},t)})}self.addEventListener(`message`,e=>{e.data?.type===`kernel-worker-shutdown`&&(WZ?.(),WZ=null,GZ?.(),GZ=null,KZ?.(),KZ=null,qZ?.dispose(),qZ=null,UZ?.dispose())});
|
|
8758
|
+
`}}function ZX(e){let t=e instanceof Error?e.message:String(e),n=e?.code;return typeof n==`string`&&/^E[A-Z]+$/.test(n)?{ok:!1,errno:n,message:t}:{ok:!1,errno:`EIO`,message:t}}async function QX(e){let t=RO(e.token);if(!t)return{ok:!1,errno:`EACCES`,message:`sync-fs: unknown or revoked token`};let{fs:n,cwd:r}=t;try{let t=n.resolvePath(r,e.path);switch(e.op){case`read`:return{ok:!0,kind:`bytes`,bytes:await n.readFileBuffer(t)};case`write`:return await n.writeFile(t,e.body??new Uint8Array),{ok:!0,kind:`void`};case`exists`:return{ok:!0,kind:`json`,json:await n.exists(t)};case`stat`:{let e=await n.stat(t);return{ok:!0,kind:`json`,json:{isDirectory:e.isDirectory,isFile:e.isFile,size:e.size}}}case`readdir`:return{ok:!0,kind:`json`,json:await n.readdir(t)};case`mkdir`:return await n.mkdir(t,{recursive:!0}),{ok:!0,kind:`void`};case`rm`:return await n.rm(t,{recursive:!0}),{ok:!0,kind:`void`};case`rename`:{let i=n.resolvePath(r,e.arg2??``),a=n;if(a.rename)await a.rename(t,i);else if(a.mv)await a.mv(t,i);else{let e=await n.readFileBuffer(t);await n.writeFile(i,e),await n.rm(t,{recursive:!0})}return{ok:!0,kind:`void`}}default:return{ok:!1,errno:`EINVAL`,message:`sync-fs: unknown op '${e.op}'`}}}catch(e){return ZX(e)}}function $X(e={}){let t=e.channel===void 0;if(t&&!e.nonce)throw Error(`installSyncFsResponder: a nonce (or a test channel) is required`);let n=e.channel??new BroadcastChannel(QT(e.nonce)),r=e=>n.postMessage(e),i=new Map,a=e=>{let t=e.data;if(t?.type!==`sync-fs-req`||typeof t.id!=`string`)return;let n=t;if(!RO(n.token))return;let a=i.get(n.id);if(a){r({type:$T,id:n.id}),a.result&&r({type:eE,id:n.id,...a.result});return}let o={};i.set(n.id,o),r({type:$T,id:n.id});let s=e=>{o.result=e,o.timer=setTimeout(()=>i.delete(n.id),3e4),r({type:eE,id:n.id,...e})};QX(n).then(s).catch(e=>s({ok:!1,errno:`EIO`,message:e instanceof Error?e.message:String(e)}))};return n.addEventListener(`message`,a),{dispose:()=>{n.removeEventListener(`message`,a);for(let e of i.values())e.timer&&clearTimeout(e.timer);i.clear(),t&&n.close?.()}}}function eZ(e){switch(e.type){case`webhook`:return e.webhookName;case`sprinkle`:return e.sprinkleName;case`fswatch`:return e.fswatchName;case`navigate`:return e.navigateUrl;case`upgrade`:return`${e.upgradeFromVersion??`unknown`}→${e.upgradeToVersion??`unknown`}`;case`session-reload`:return`mount-recovery`;case`workflow`:return e.workflowName??e.workflowRunId??`workflow`;case`preview`:return e.previewOrigin??`preview`;case`discovery`:return e.discoveryUrl??e.discoveryOrigin;default:return e.cronName}}function tZ(e){switch(e.type){case`webhook`:return e.webhookId;case`sprinkle`:return e.sprinkleName;case`fswatch`:return e.fswatchId;case`navigate`:return e.navigateUrl;case`upgrade`:return`upgrade-${e.upgradeToVersion??`unknown`}`;case`session-reload`:return`session-reload-${e.timestamp}`;case`workflow`:return`workflow-${e.workflowRunId??`unknown`}`;case`preview`:return e.previewConnId??`preview-${e.timestamp}`;case`discovery`:return e.discoveryUrl??`discovery-${e.timestamp}`;default:return e.cronId}}function nZ(e,t){if(e.type===`sudo-request`){t.log.debug?.(`sudo-request lick: UI-chip-only path; orchestrator owns delivery`,{lickId:e.lickId});return}rZ(e,t)}function rZ(e,{orchestrator:t,log:n}){e.type===`navigate`?e.lickId=t.registerNavigateLick(e):e.type===`session-reload`?e.lickId=t.registerSessionReloadLick(e):e.type===`upgrade`&&(e.lickId=t.registerUpgradeLick(e));let r=Wr(e);if(r===null){n.debug?.(`dropping lick event with no renderable content`,{type:e.type});return}let i=eZ(e),a=tZ(e),o=e.type,s=t.getScoops(),c;if(c=e.targetScoop?s.find(t=>t.name===e.targetScoop||t.folder===e.targetScoop||t.folder===`${e.targetScoop}-scoop`):s.find(e=>e.isCone),!c){n.warn(`Lick target scoop not found`,e.targetScoop);return}let l={id:`${o}-${a}-${Date.now()}`,chatJid:c.jid,senderId:o,senderName:`${o}:${i}`,content:r.content,timestamp:e.timestamp,fromAssistant:!1,channel:o,...e.lickId?{lickId:e.lickId}:{}};t.handleMessage(l)}async function iZ(e,t,n,r){let i=new Qt,a=new RX(e,{...r,getBrowserAPI:()=>t});a.setProcessManager(i),globalThis.__slicc_pm=i,globalThis.__slicc_browser=t,await n.bind(a,t);let o=We(()=>n.emitTrayRuntimeStatus()),s=Zr(()=>n.emitTrayRuntimeStatus());return await a.init(),await n.seedBuffersFromAgentState(),{processManager:i,orchestrator:a,unsubLeader:o,unsubFollower:s,sharedFs:a.getSharedFS()}}async function aZ(e,t,n){let{registerSessionCostsProvider:r}=await import(`./cost-command-Cpg2Em0Q.js`).then(e=>e.t);r(()=>e.getSessionCosts());let{getLickManager:i}=await import(`./lick-manager-Ct3WOtut.js`).then(e=>e.r),a=i();await a.init(),e.setLickManager(a);let o=t.lickEventHandler??nZ,s={orchestrator:e,lickManager:a,log:n};return a.setEventHandler(e=>o(e,s)),a}async function oZ(e){e.getScoops().some(e=>e.isCone)||await e.registerScoop({jid:`cone_${Date.now()}`,name:`Cone`,folder:`cone`,isCone:!0,type:`cone`,requiresTrigger:!1,assistantLabel:`sliccy`,addedAt:new Date().toISOString()})}function sZ(e){let{orchestrator:t,processManager:n,lickManager:r,sharedFs:i}=e;SJ({sharedFs:i,getConeJid:()=>t.getScoops().find(e=>e.isCone)?.jid,fireLick:e=>r.emitEvent(e),processManager:n,runRealm:(e,t,n)=>zk(e,t,n,void 0,{filename:t[1]}),makeRunId:()=>AJ().slice(10,22),splitResult:(e,t)=>PJ(e,t)})}async function cZ(e){let{browser:t,lickManager:n,orchestrator:r,sharedFs:i,log:a}=e,{CdpWsPageBridge:o}=await import(`./cdp-ws-page-bridge-D_PY6ku1.js`),{WsSubscriberRegistry:s}=await import(`./ws-subscribers-Dzuxa2F7.js`),c=new o({browser:t});return{wsBridge:c,wsRegistry:new s({bridge:c,webhooks:{has:e=>n.getWebhook(e)!==void 0},dispatcher:{webhook:(e,t)=>{n.handleWebhookEvent(e,{},t)},scoop:(e,t)=>{if(!r.getScoops().find(t=>t.jid===e)){a.warn?.(`browser.websocket: scoop sink not found`,{jid:e});return}let n={id:`ws-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,chatJid:e,senderId:`browser.websocket`,senderName:`browser.websocket`,content:typeof t==`string`?t:JSON.stringify(t,null,2),timestamp:new Date().toISOString(),fromAssistant:!1,channel:`browser.websocket`};r.handleMessage(n)},vfs:async(e,t)=>{if(!i)return;let n=(typeof t==`string`?t:JSON.stringify(t))+`
|
|
8759
|
+
`,r=``;try{let t=await i.readFile(e);r=typeof t==`string`?t:new TextDecoder().decode(t)}catch{}await i.writeFile(e,r+n)},log:e=>{a.info?.(`browser.websocket frame`,{payload:e})}}})}}async function lZ(e,t,n){try{let{startLickWsBridge:t}=await import(`./lick-ws-bridge-C_bJMGw6.js`);return t(e,{locationHref:self.location.href,lickWsUrl:n??null}).stop}catch(e){return(t.error?.bind(t)??t.warn.bind(t)??((e,t)=>console.error(`[lick-ws-bridge]`,e,t)))(`Failed to start lick-ws bridge — webhook / crontask / handoff lick delivery is non-functional in this session`,{error:e instanceof Error?e.message:String(e)}),null}}function uZ(e,t,n){let r=e.getTransport();if(r.isExtensionBridge)return n.debug?.(`Skipping NavigationWatcher: extension-bridge transport rejects sessionless Target.* discovery; the service worker observes handoffs via chrome.webRequest`),null;try{let e=new yi(r,e=>{let n={url:e.url,verb:e.verb,target:e.target};e.instruction!=null&&(n.instruction=e.instruction),e.branch!=null&&(n.branch=e.branch),e.path!=null&&(n.path=e.path),e.title!=null&&(n.title=e.title),t.emitEvent({type:`navigate`,navigateUrl:e.url,targetScoop:void 0,timestamp:new Date().toISOString(),body:n})},dZ(t));return e.start(),()=>e.stop()}catch(e){return n.warn(`Failed to start NavigationWatcher`,e),null}}function dZ(e){let t=p();return{onDiscovery:t=>{e.emitEvent({type:`discovery`,targetScoop:void 0,timestamp:new Date().toISOString(),discoveryOrigin:t.origin,discoveryKind:t.kind,discoveryUrl:t.url,body:{origin:t.origin,kind:t.kind,url:t.url,targetId:t.targetId}})},probeFetch:async(e,n)=>{let r=t(e,{method:n?.method??`GET`}),i=n?.signal,a=i?await Promise.race([r,new Promise((e,t)=>{if(i.aborted){t(Error(`aborted`));return}i.addEventListener(`abort`,()=>t(Error(`aborted`)),{once:!0})})]):await r,o=a.headers;return{ok:a.status>=200&&a.status<300,status:a.status,headers:{get(e){return o?o[e.toLowerCase()]??o[e]??null:null}}}},isDiscoveryEnabled:()=>zX()}}function fZ(e,t,n){(async()=>{try{let{getAllMountEntries:r}=await import(`./mount-table-store-CTrzlrNn.js`).then(e=>e.r),{recoverMounts:i}=await import(`./mount-recovery-CmtpPBiM.js`).then(e=>e.n),a=await r();if(a.length===0)return;let{needsRecovery:o}=await i(a,e,n);if(o.length===0)return;t.emitEvent({type:`session-reload`,targetScoop:void 0,timestamp:new Date().toISOString(),body:{reason:`mount-recovery`,mounts:o}})}catch(e){n.warn(`mount recovery failed`,e)}})()}function pZ(e,t){(async()=>{try{let{detectUpgrade:t,recordVersionSeen:n}=await import(`./upgrade-detection-C9cmqYPd.js`),r=await t();if(!r.isUpgrade||r.lastSeen===null)return;e.emitEvent({type:`upgrade`,targetScoop:void 0,timestamp:new Date().toISOString(),upgradeFromVersion:r.lastSeen,upgradeToVersion:r.bundled.version,body:{from:r.lastSeen,to:r.bundled.version,releasedAt:r.bundled.releasedAt}}),await n(r.bundled.version)}catch(e){t.warn(`Upgrade detection failed`,e)}})()}async function mZ(e,t,n){try{let{BshWatchdog:n}=await import(`./bsh-watchdog-cTkGOVHJ.js`),{ScriptCatalog:r}=await import(`./script-catalog-BYXhqRAc.js`).then(e=>e.n),i=new r({jshFs:e,bshFs:e,watcher:e.getWatcher()}),a=new n({browserAPI:t,scriptCatalog:i,fs:e});return a.start(),{bshWatchdogStop:()=>a.stop(),scriptCatalogDispose:()=>i.dispose()}}catch(e){return n.warn(`Failed to start BSH watchdog`,e),{bshWatchdogStop:null,scriptCatalogDispose:null}}}function hZ(){return E()}async function gZ(e){let{container:t,browser:n,bridge:r,callbacks:i,skipConeBootstrap:a=!1}=e,o=e.logger??console,{processManager:s,orchestrator:c,unsubLeader:l,unsubFollower:u,sharedFs:d}=await iZ(t,n,r,i);if(d?Ui(c,d,c.getSessionStore()):o.warn(`AgentBridge not published — orchestrator.getSharedFS() returned null`),d)try{await d.mountInternal(`/proc`,new BX(s))}catch(e){o.warn(`Failed to mount /proc`,e)}let f=await aZ(c,e,o);d&&sZ({orchestrator:c,processManager:s,lickManager:f,sharedFs:d}),globalThis.__slicc_lickManager=f;let{wsBridge:p,wsRegistry:m}=await cZ({browser:n,lickManager:f,orchestrator:c,sharedFs:d,log:o});globalThis.__slicc_wsSubscribers=m;let h=null;hZ()&&(h=await lZ(f,o,e.localLickWsUrl??null));let g=uZ(n,f,o);d&&fZ(d,f,o),a||await oZ(c),d&&pZ(f,o);let _=null,v=null;d&&({bshWatchdogStop:_,scriptCatalogDispose:v}=await mZ(d,n,o));let y=null;d&&e.syncFsChannelNonce&&(y=$X({nonce:e.syncFsChannelNonce}).dispose);let b=!1;return{orchestrator:c,browser:n,bridge:r,lickManager:f,sharedFs:d??null,processManager:s,async dispose(){b||(b=!0,await _Z({unsubLeader:l,unsubFollower:u,bshWatchdogStop:_,scriptCatalogDispose:v,lickWsBridgeStop:h,navigationWatcherStop:g,syncFsResponderDispose:y,sharedFs:d,wsRegistry:m,wsBridge:p,processManager:s,lickManager:f,browser:n,log:o}))}}}async function _Z(e){let{sharedFs:t,wsRegistry:n,wsBridge:r,processManager:i,lickManager:a,browser:o,log:s}=e;if(e.unsubLeader?.(),e.unsubFollower?.(),e.bshWatchdogStop?.(),e.scriptCatalogDispose?.(),e.lickWsBridgeStop?.(),e.syncFsResponderDispose?.(),e.navigationWatcherStop)try{await e.navigationWatcherStop()}catch(e){s.warn(`NavigationWatcher.stop() failed`,e)}if(t)try{await t.unmountInternal(`/proc`)}catch{}try{n.dispose()}catch(e){s.warn(`WsSubscriberRegistry.dispose() failed`,e)}try{r.dispose()}catch(e){s.warn(`CdpWsPageBridge.dispose() failed`,e)}vZ({processManager:i,lickManager:a,browser:o,wsRegistry:n})}function vZ(e){let t=globalThis;t.__slicc_pm===e.processManager&&delete t.__slicc_pm,t.__slicc_lickManager===e.lickManager&&delete t.__slicc_lickManager,e.browser&&t.__slicc_browser===e.browser&&delete t.__slicc_browser,e.wsRegistry&&t.__slicc_wsSubscribers===e.wsRegistry&&delete t.__slicc_wsSubscribers,delete t[vJ]}const yZ=`x-bypass-llm-proxy`;function bZ(e,t,n){return t?(r,i)=>{if(!xZ(r,t,n))return e(r,i);let a=new Headers(i?.headers);return a.has(yZ)||a.set(yZ,`1`),e(r,{...i,headers:a})}:e}function xZ(e,t,n){if(CZ(e,t))return!0;let r=n?.()??null;return r?SZ(e,r,t):!1}function SZ(e,t,n){let r=wZ(e),i,a;try{i=new URL(r,n),a=new URL(t)}catch{return!1}return i.origin===a.origin&&i.pathname.startsWith(`/api/`)}function CZ(e,t){let n=wZ(e);try{return new URL(n,t).origin===t}catch{return!0}}function wZ(e){return typeof e==`string`?e:e instanceof URL?e.href:e.url}function TZ(e,t={}){let n=t.onError??(e=>console.error(`[kernel-worker] boot failed`,e)),r=t.onDuplicate??(()=>console.warn(`[kernel-worker] received duplicate kernel-worker-init; ignoring`)),i=!1;return{handle(t){if(i){r();return}i=!0,e(t).catch(e=>{i=!1,n(e)})},isInitialized(){return i}}}var EZ=class{transport;createShell;log;pm;defaultOwner;sessions=new Map;unsubscribe=null;constructor(e){this.transport=e.transport,this.createShell=e.createShell,this.log=e.logger??console,this.pm=e.processManager??null,this.defaultOwner=e.defaultOwner??{kind:`system`}}start(){return this.unsubscribe||=this.transport.onMessage(e=>{if(!DZ(e)||e.source!==`panel`)return;let t=e.payload;kZ(t)&&this.handleControl(t).catch(e=>{this.log.warn(`[terminal-session-host] handler error`,e)})}),()=>this.dispose()}dispose(){this.unsubscribe?.(),this.unsubscribe=null;for(let[,e]of this.sessions)e.currentProcess&&this.pm?(this.pm.signal(e.currentProcess.pid,`SIGTERM`),this.pm.exit(e.currentProcess.pid,null)):e.currentExec?.abort(),e.shell.dispose?.();this.sessions.clear()}async handleControl(e){switch(e.type){case`terminal-open`:return this.handleOpen(e);case`terminal-close`:return this.handleClose(e);case`terminal-exec`:return this.handleExec(e);case`terminal-signal`:return this.handleSignal(e);case`terminal-stdin`:case`terminal-resize`:return}}async handleOpen(e){if(this.sessions.has(e.sid)){this.emitStatus(e.sid,`error`,`session already open`);return}try{let t=this.createShell(e.sid,{cwd:e.cwd,env:e.env});this.sessions.set(e.sid,{shell:t,currentExec:null,currentProcess:null}),this.emitStatus(e.sid,`opened`)}catch(t){this.emitStatus(e.sid,`error`,t instanceof Error?t.message:String(t))}}async handleClose(e){let t=this.sessions.get(e.sid);t&&(t.currentProcess&&this.pm?(this.pm.signal(t.currentProcess.pid,`SIGTERM`),this.pm.exit(t.currentProcess.pid,null)):t.currentExec?.abort(),t.shell.dispose?.(),this.sessions.delete(e.sid),this.emitStatus(e.sid,`closed`))}emitExit(e,t){this.emit({type:`terminal-exit`,sid:e.sid,execId:e.execId,exitCode:t})}emitStream(e,t,n){this.emit({type:`terminal-output`,sid:e.sid,execId:e.execId,stream:t,data:n})}async handleExec(e){let t=this.sessions.get(e.sid);if(!t){this.emitExit(e,127),this.log.warn(`[terminal-session-host] exec on unknown session`,e.sid);return}if(t.currentExec){this.emitExit(e,130);return}let n=new AbortController;t.currentExec=n;let r=this.pm?this.pm.spawn({kind:`shell`,argv:[e.command],cwd:t.shell.getCwd?.()??void 0,owner:this.defaultOwner,adoptAbort:n}):null;t.currentProcess=r;try{let i=await t.shell.executeCommand(e.command,n.signal,r?.pid);await this.emitExecSuccess(e,i,n,r)}catch(t){this.emitExecError(e,t,n,r)}finally{t.currentExec===n&&(t.currentExec=null,t.currentProcess=null)}}async emitExecSuccess(e,t,n,r){let i=n.signal.aborted?OZ(r?.terminatedBy??`SIGINT`):t.exitCode;n.signal.aborted||(r&&await r.gate.wait(),t.stdout&&this.emitStream(e,`stdout`,t.stdout),t.stderr&&this.emitStream(e,`stderr`,t.stderr)),this.emitExit(e,i),r&&this.pm&&this.pm.exit(r.pid,n.signal.aborted?null:t.exitCode)}emitExecError(e,t,n,r){if(n.signal.aborted){this.emitExit(e,OZ(r?.terminatedBy??`SIGINT`)),r&&this.pm&&this.pm.exit(r.pid,null);return}let i=t instanceof Error?t.message:String(t);this.emitStream(e,`stderr`,`Error: ${i}\n`),this.emitExit(e,1),r&&this.pm&&this.pm.exit(r.pid,1)}async handleSignal(e){let t=this.sessions.get(e.sid);if(!t){this.log.warn(`[terminal-session-host] signal on unknown session`,e.sid);return}(e.signal===`SIGINT`||e.signal===`SIGTERM`||e.signal===`SIGKILL`)&&(t.currentProcess&&this.pm?this.pm.signal(t.currentProcess.pid,e.signal):t.currentExec?.abort())}emit(e){this.transport.send(e)}emitStatus(e,t,n){let r=n?{type:`terminal-status`,sid:e,state:t,error:n}:{type:`terminal-status`,sid:e,state:t};this.emit(r)}};function DZ(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function OZ(e){switch(e){case`SIGINT`:return 130;case`SIGTERM`:return 143;case`SIGKILL`:return 137;case`SIGSTOP`:case`SIGCONT`:return 130}}function kZ(e){if(typeof e!=`object`||!e)return!1;let t=e.type;return t===`terminal-open`||t===`terminal-close`||t===`terminal-exec`||t===`terminal-signal`||t===`terminal-stdin`||t===`terminal-resize`}var AZ=class extends SY{sid;transport;constructor(e,t,n){super(n),this.sid=e,this.transport=t}async renderMediaPreview(e){for(let t of e){let e=``,n=t.bytes,r=8192;for(let t=0;t<n.length;t+=r)e+=String.fromCharCode(...n.subarray(t,t+r));let i={type:`terminal-media-preview`,sid:this.sid,path:t.path,mediaType:t.mimeType,data:btoa(e)};this.transport.send(i)}}};function jZ(e){let{transport:t,fs:n,browser:r,processManager:i,sudoManager:a}=e,o=e.logger??console,s=a?.getShellConfig({transparentGating:!1}),c=new EZ({transport:t,processManager:i,createShell:(e,a)=>new AZ(e,t,{fs:n,cwd:a.cwd,env:a.env,browserAPI:r,processManager:i,processOwner:{kind:`system`},sudo:s}),logger:o});return{host:c,stop:c.start()}}function MZ(e){let t=new NZ(e);return t.start(),{stop:()=>t.dispose()}}var NZ=class{transport;client;writableClient;log;unsubscribe=null;constructor(e){this.transport=e.transport,this.client=e.client,this.writableClient=e.writableClient??null,this.log=e.logger??console}start(){this.unsubscribe||=this.transport.onMessage(e=>{if(!PZ(e)||e.source!==`panel`)return;let t=e.payload;if(FZ(t)){this.handleRequest(t).catch(e=>{this.log.warn(`[vfs-rpc-host] handler unexpectedly threw`,e)});return}if(IZ(t)){this.handleWriteRequest(t).catch(e=>{this.log.warn(`[vfs-rpc-host] write handler unexpectedly threw`,e)});return}})}dispose(){this.unsubscribe?.(),this.unsubscribe=null}async handleRequest(e){switch(e.type){case`vfs-read-dir`:return this.handleReadDir(e);case`vfs-read-file`:return this.handleReadFile(e);case`vfs-stat`:return this.handleStat(e)}}async handleReadDir(e){try{let t=await this.client.readDir(e.path),n={type:`vfs-read-dir-result`,requestId:e.requestId,ok:!0,entries:t};this.transport.send(n)}catch(t){this.emitError(`vfs-read-dir-result`,e.requestId,t,e.path)}}async handleReadFile(e){let t=e.encoding??`utf-8`;try{let n=await this.client.readFile(e.path,{encoding:t});if(t===`binary`){if(!(n instanceof Uint8Array)){this.emitError(`vfs-read-file-result`,e.requestId,new ge(`EIO`,`readFile(binary) did not return Uint8Array`),e.path);return}let t={type:`vfs-read-file-result`,requestId:e.requestId,ok:!0,encoding:`binary`,data:n},r=n.buffer,i=typeof ArrayBuffer<`u`&&r instanceof ArrayBuffer?[r]:void 0;this.transport.send(t,i)}else{if(typeof n!=`string`){this.emitError(`vfs-read-file-result`,e.requestId,new ge(`EIO`,`readFile(utf-8) did not return string`),e.path);return}let t={type:`vfs-read-file-result`,requestId:e.requestId,ok:!0,encoding:`utf-8`,data:n};this.transport.send(t)}}catch(t){this.emitError(`vfs-read-file-result`,e.requestId,t,e.path)}}async handleStat(e){try{let t=await this.client.stat(e.path),n={type:`vfs-stat-result`,requestId:e.requestId,ok:!0,stats:t};this.transport.send(n)}catch(t){this.emitError(`vfs-stat-result`,e.requestId,t,e.path)}}async handleWriteRequest(e){if(!this.writableClient){this.emitWriteError(LZ(e.type),e.requestId,new ge(`EACCES`,`vfs-rpc-host has no writable backend wired`),RZ(e));return}switch(e.type){case`vfs-write-file`:return this.handleWriteFile(e,this.writableClient);case`vfs-mkdir`:return this.handleMkdir(e,this.writableClient);case`vfs-rm`:return this.handleRm(e,this.writableClient);case`vfs-flush`:return this.handleFlush(e,this.writableClient);case`vfs-list-mount-points`:return this.handleListMountPoints(e,this.writableClient)}}async handleWriteFile(e,t){try{if(e.encoding===`binary`){if(!(e.data instanceof Uint8Array)){this.emitWriteError(`vfs-write-file-result`,e.requestId,new ge(`EIO`,`vfs-write-file(binary) data is not Uint8Array`),e.path);return}}else if(typeof e.data!=`string`){this.emitWriteError(`vfs-write-file-result`,e.requestId,new ge(`EIO`,`vfs-write-file(utf-8) data is not string`),e.path);return}let n=e.recursive===void 0?void 0:{recursive:e.recursive};await t.writeFile(e.path,e.data,n);let r={type:`vfs-write-file-result`,requestId:e.requestId,ok:!0};this.transport.send(r)}catch(t){this.emitWriteError(`vfs-write-file-result`,e.requestId,t,e.path)}}async handleMkdir(e,t){try{let n=e.recursive===void 0?void 0:{recursive:e.recursive};await t.mkdir(e.path,n);let r={type:`vfs-mkdir-result`,requestId:e.requestId,ok:!0};this.transport.send(r)}catch(t){this.emitWriteError(`vfs-mkdir-result`,e.requestId,t,e.path)}}async handleRm(e,t){try{let n=e.recursive===void 0?void 0:{recursive:e.recursive};await t.rm(e.path,n);let r={type:`vfs-rm-result`,requestId:e.requestId,ok:!0};this.transport.send(r)}catch(t){this.emitWriteError(`vfs-rm-result`,e.requestId,t,e.path)}}async handleFlush(e,t){try{await t.flush();let n={type:`vfs-flush-result`,requestId:e.requestId,ok:!0};this.transport.send(n)}catch(t){this.emitWriteError(`vfs-flush-result`,e.requestId,t,``)}}async handleListMountPoints(e,t){if(!t.listMountPoints){this.emitWriteError(`vfs-list-mount-points-result`,e.requestId,new ge(`EACCES`,`vfs-rpc-host has no mount-aware backend wired`),``);return}try{let n=await t.listMountPoints(),r={type:`vfs-list-mount-points-result`,requestId:e.requestId,ok:!0,mountPoints:n};this.transport.send(r)}catch(t){this.emitWriteError(`vfs-list-mount-points-result`,e.requestId,t,``)}}emitError(e,t,n,r){let i=zZ(n,r);switch(e){case`vfs-read-dir-result`:{let e={type:`vfs-read-dir-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}case`vfs-read-file-result`:{let e={type:`vfs-read-file-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}case`vfs-stat-result`:{let e={type:`vfs-stat-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}}}emitWriteError(e,t,n,r){let i=zZ(n,r);switch(r===``&&i.path===``&&delete i.path,e){case`vfs-write-file-result`:{let e={type:`vfs-write-file-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}case`vfs-mkdir-result`:{let e={type:`vfs-mkdir-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}case`vfs-rm-result`:{let e={type:`vfs-rm-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}case`vfs-flush-result`:{let e={type:`vfs-flush-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}case`vfs-list-mount-points-result`:{let e={type:`vfs-list-mount-points-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}}}};function PZ(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function FZ(e){if(typeof e!=`object`||!e)return!1;let t=e.type;return t===`vfs-read-dir`||t===`vfs-read-file`||t===`vfs-stat`}function IZ(e){if(typeof e!=`object`||!e)return!1;let t=e.type;return t===`vfs-write-file`||t===`vfs-mkdir`||t===`vfs-rm`||t===`vfs-flush`||t===`vfs-list-mount-points`}function LZ(e){switch(e){case`vfs-write-file`:return`vfs-write-file-result`;case`vfs-mkdir`:return`vfs-mkdir-result`;case`vfs-rm`:return`vfs-rm-result`;case`vfs-flush`:return`vfs-flush-result`;case`vfs-list-mount-points`:return`vfs-list-mount-points-result`}}function RZ(e){return e.type===`vfs-flush`||e.type===`vfs-list-mount-points`?``:e.path}function zZ(e,t){return e instanceof ge?{code:e.code,message:e.message,path:e.path??t}:{code:`EIO`,message:e instanceof Error?e.message:String(e),path:t}}function BZ(){let e=globalThis.fetch;if(!e)return;let t=self?.location?self.location.origin:void 0;globalThis.fetch=bZ(e.bind(globalThis),t,VZ)}function VZ(){let e=u();if(!e)return null;try{return new URL(e).origin}catch{return null}}function HZ(e){let t=new Map(Object.entries(e));Object.defineProperty(globalThis,"localStorage",{value:{get length(){return t.size},key(e){return Array.from(t.keys())[e]??null},getItem(e){return t.has(e)?t.get(e):null},setItem(e,n){t.set(e,n)},removeItem(e){t.delete(e)},clear(){t.clear()}},configurable:!0,writable:!0})}let UZ=null,WZ=null,GZ=null,KZ=null,qZ=null;const JZ=TZ(e=>YZ(e));self.addEventListener(`message`,e=>{e.data?.type===`kernel-worker-init`&&JZ.handle(e.data)});async function YZ(e){Xn(e.instanceId);try{BZ(),d(e.localApiBaseUrl??null),_(e.bridgeToken??null),Nk(e.syncFsBridgeEnabled??!1),s(e.extensionDelegateId??null),HZ(e.localStorageSeed??{}),gr().catch(()=>{}),await o();let t=Or(e.kernelPort),n=new ui(t),i=ui.createCallbacks(n),a=new kr(e.cdpPort);await a.connect();let c=new Bn(a);UZ=await gZ({container:{},browser:c,bridge:n,callbacks:i,logger:console,localLickWsUrl:e.localLickWsUrl??null,syncFsChannelNonce:e.syncFsChannelNonce??null});let{createSprinkleManagerProxyOverChannel:l}=await import(`./sprinkle-bridge-channel-14cdGa6x.js`),u=l({instanceId:e.instanceId});globalThis.__slicc_sprinkleManager=u;let f=UZ.sharedFs?.getWatcher();if(f){let e=[`/workspace`,`/shared`,`/scoops`],t=null,n=new Set;for(let r of e)f.watch(r,e=>e.endsWith(`.shtml`),e=>{for(let t of e){let e=t.path.split(`/`).pop()?.replace(/\.shtml$/,``);e&&n.add(e)}t||=setTimeout(()=>{t=null;for(let e of n)u.reload(e).catch(()=>{});n.clear()},300)})}let{createPanelRpcClient:p}=await import(`./panel-rpc-CjFVE0nK.js`).then(e=>e.i);qZ=p({instanceId:e.instanceId}),globalThis.__slicc_panelRpc=qZ,c.setTrayTargetProvider(Kn(r));let m=await XZ({host:UZ,transport:t,browser:c,instanceId:e.instanceId});m&&(WZ=m.stopTerminalHost,GZ=m.stopVfsRpcHost,KZ=m.stopSpeechAssetsResponder),e.kernelPort.postMessage({type:`kernel-worker-ready`})}catch(e){throw Qn(e),e}}async function XZ(e){let t=e.host.sharedFs;if(!t)return console.warn(`[kernel-worker] shared FS unavailable; terminal sessions will fail to open`),null;let n=jZ({transport:e.transport,fs:t,browser:e.browser,processManager:e.host.processManager,sudoManager:e.host.orchestrator.getSudoManager(),logger:console}),r=MZ({transport:e.transport,client:t,writableClient:t,logger:console}),i=await ZZ(t,e.instanceId);return{stopTerminalHost:n.stop,stopVfsRpcHost:r.stop,stopSpeechAssetsResponder:i}}async function ZZ(e,t){let{installSpeechAssetsResponder:n}=await import(`./speech-assets-bridge-BUDIvdid.js`),{ensureSpeechAssetsStaged:r}=await import(`./ensure-speech-assets-pHHH7zOs.js`),{createProxiedFetch:i}=await import(`./proxied-fetch-sbHa3Tte.js`).then(e=>e.a),a=i();return n({instanceId:t,ensure:t=>r({fs:e,fetch:a},t)})}self.addEventListener(`message`,e=>{e.data?.type===`kernel-worker-shutdown`&&(WZ?.(),WZ=null,GZ?.(),GZ=null,KZ?.(),KZ=null,qZ?.dispose(),qZ=null,UZ?.dispose())});
|