blink 1.1.21 → 1.1.23
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/cli/{auth-BilZuH-1.js → auth-DbpOUCTO.js} +1 -1
- package/dist/cli/{chat-manager-DfVg04yc.js → chat-manager-GWR_v50X.js} +1 -1
- package/dist/cli/{dev-DRWR8F1H.js → dev-DwwSnzeH.js} +9 -9
- package/dist/cli/index.js +9 -9
- package/dist/cli/{init-BuMKmaaZ.js → init-em410TZP.js} +8 -8
- package/dist/cli/{init-templates-B9PG-9Ei.js → init-templates-By3gx42M.js} +4 -2
- package/dist/cli/login-BDP8JC4X.js +1 -0
- package/dist/cli/{run-DF1dwAY_.js → run-CZZ6WAdr.js} +1 -1
- package/dist/node/react/index.node.cjs +6 -4
- package/dist/node/react/index.node.d.cts +9 -2
- package/dist/node/react/index.node.d.ts +9 -2
- package/dist/node/react/index.node.js +6 -4
- package/package.json +1 -1
- package/dist/cli/login-Bbj133_1.js +0 -1
|
@@ -138,7 +138,7 @@ ${ym}${t.trimStart()}`),n=3+(0,l.stripVTControlCharacters)(t.trimStart()).length
|
|
|
138
138
|
`);process.stdout.write(Ip.cursor.move(-999,e.length-1)),process.stdout.write(Ip.erase.down(e.length))},g=e=>e.replace(/\.+$/,``),_=e=>{let t=(performance.now()-e)/1e3,n=Math.floor(t/60),r=Math.floor(t%60);return n>0?`[${n}m ${r}s]`:`[${r}s]`},v=(u=``)=>{o=!0,i=ip(),s=g(u),l=performance.now(),process.stdout.write(`${X.default.gray(Q)}
|
|
139
139
|
`);let d=0,f=0;p(),a=setInterval(()=>{if(r&&s===c)return;h(),c=s;let n=X.default.magenta(t[d]);if(r)process.stdout.write(`${n} ${s}...`);else if(e===`timer`)process.stdout.write(`${n} ${s} ${_(l)}`);else{let e=`.`.repeat(Math.floor(f)).slice(0,3);process.stdout.write(`${n} ${s}${e}`)}d=d+1<t.length?d+1:0,f=f<t.length?f+.125:0},n)},y=(t=``,n=0)=>{o=!1,clearInterval(a),h();let r=n===0?X.default.green(Hp):n===1?X.default.red(Bp):X.default.red(Vp);s=g(t??s),e===`timer`?process.stdout.write(`${r} ${s} ${_(l)}
|
|
140
140
|
`):process.stdout.write(`${r} ${s}
|
|
141
|
-
`),m(),i()};return{start:v,stop:y,message:(e=``)=>{s=g(e??s)}}},Sm=async(e,t)=>{let n={},r=Object.keys(e);for(let i of r){let r=e[i],a=await r({results:n})?.catch(e=>{throw e});if(typeof t?.onCancel==`function`&&np(a)){n[i]=`canceled`,t.onCancel({results:n});continue}n[i]=a}return n},Cm=async e=>{for(let t of e){if(t.enabled===!1)continue;let e=xm();e.start(t.title);let n=await t.task(e.message);e.stop(n||t.title)}};let wm;function Tm(){try{return o.default.statSync(`/.dockerenv`),!0}catch{return!1}}function Em(){try{return o.default.readFileSync(`/proc/self/cgroup`,`utf8`).includes(`docker`)}catch{return!1}}function Dm(){return wm===void 0&&(wm=Tm()||Em()),wm}let Om;const km=()=>{try{return o.default.statSync(`/run/.containerenv`),!0}catch{return!1}};function Am(){return Om===void 0&&(Om=km()||Dm()),Om}const jm=()=>{if(x.default.platform!==`linux`)return!1;if(S.default.release().toLowerCase().includes(`microsoft`))return!Am();try{return o.default.readFileSync(`/proc/version`,`utf8`).toLowerCase().includes(`microsoft`)?!Am():!1}catch{return!1}};var Mm=x.default.env.__IS_WSL_TEST__?jm:jm();const Nm=(()=>{let e=`/mnt/`,t;return async function(){if(t)return t;let n=`/etc/wsl.conf`,r=!1;try{await E.default.access(n,E.constants.F_OK),r=!0}catch{}if(!r)return e;let i=await E.default.readFile(n,{encoding:`utf8`}),a=/(?<!#.*)root\s*=\s*(?<mountPoint>.*)/g.exec(i);return a?(t=a.groups.mountPoint.trim(),t=t.endsWith(`/`)?t:`${t}/`,t):e}})(),Pm=async()=>`${await Nm()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,Fm=async()=>Mm?Pm():`${x.default.env.SYSTEMROOT||x.default.env.windir||String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;function Im(e,t,n){let r=n=>Object.defineProperty(e,t,{value:n,enumerable:!0,writable:!0});return Object.defineProperty(e,t,{configurable:!0,enumerable:!0,get(){let e=n();return r(e),e},set(e){r(e)}}),e}const Lm=(0,l.promisify)(T.execFile);async function Rm(){if(x.default.platform!==`darwin`)throw Error(`macOS only`);let{stdout:e}=await Lm(`defaults`,[`read`,`com.apple.LaunchServices/com.apple.launchservices.secure`,`LSHandlers`]);return/LSHandlerRoleAll = "(?!-)(?<id>[^"]+?)";\s+?LSHandlerURLScheme = (?:http|https);/.exec(e)?.groups.id??`com.apple.Safari`}const zm=(0,l.promisify)(T.execFile);async function Bm(e,{humanReadableOutput:t=!0,signal:n}={}){if(x.default.platform!==`darwin`)throw Error(`macOS only`);let r=t?[]:[`-ss`],i={};n&&(i.signal=n);let{stdout:a}=await zm(`osascript`,[`-e`,e,r],i);return a.trim()}async function Vm(e){return Bm(`tell application "Finder" to set app_path to application file id "${e}" as string\ntell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`)}const Hm=(0,l.promisify)(T.execFile),Um={AppXq0fevzme2pys62n3e0fbqa7peapykr8v:{name:`Edge`,id:`com.microsoft.edge.old`},MSEdgeDHTML:{name:`Edge`,id:`com.microsoft.edge`},MSEdgeHTM:{name:`Edge`,id:`com.microsoft.edge`},"IE.HTTP":{name:`Internet Explorer`,id:`com.microsoft.ie`},FirefoxURL:{name:`Firefox`,id:`org.mozilla.firefox`},ChromeHTML:{name:`Chrome`,id:`com.google.chrome`},BraveHTML:{name:`Brave`,id:`com.brave.Browser`},BraveBHTML:{name:`Brave Beta`,id:`com.brave.Browser.beta`},BraveSSHTM:{name:`Brave Nightly`,id:`com.brave.Browser.nightly`}};var Wm=class extends Error{};async function Gm(e=Hm){let{stdout:t}=await e(`reg`,[`QUERY`,` HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice`,`/v`,`ProgId`]),n=/ProgId\s*REG_SZ\s*(?<id>\S+)/.exec(t);if(!n)throw new Wm(`Cannot find Windows browser in stdout: ${JSON.stringify(t)}`);let{id:r}=n.groups,i=Um[r];if(!i)throw new Wm(`Unknown browser ID: ${r}`);return i}const Km=(0,l.promisify)(T.execFile),qm=e=>e.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,e=>e.toUpperCase());async function Jm(){if(x.default.platform===`darwin`){let e=await Rm();return{name:await Vm(e),id:e}}if(x.default.platform===`linux`){let{stdout:e}=await Km(`xdg-mime`,[`query`,`default`,`x-scheme-handler/http`]),t=e.trim();return{name:qm(t.replace(/.desktop$/,``).replace(`-`,` `)),id:t}}if(x.default.platform===`win32`)return Gm();throw Error(`Only macOS, Linux, and Windows are supported`)}const Ym=(0,l.promisify)(T.default.execFile),Xm=b.default.dirname((0,s.fileURLToPath)(require(`url`).pathToFileURL(__filename).href)),Zm=b.default.join(Xm,`xdg-open`),{platform:Qm,arch:$m}=x.default;async function eh(){let e=await Fm(),t=String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`,n=a.Buffer.from(t,`utf16le`).toString(`base64`),{stdout:r}=await Ym(e,[`-NoProfile`,`-NonInteractive`,`-ExecutionPolicy`,`Bypass`,`-EncodedCommand`,n],{encoding:`utf8`}),i=r.trim(),o={ChromeHTML:`com.google.chrome`,BraveHTML:`com.brave.Browser`,MSEdgeHTM:`com.microsoft.edge`,FirefoxURL:`org.mozilla.firefox`};return o[i]?{id:o[i]}:{}}const th=async(e,t)=>{let n;for(let r of e)try{return await t(r)}catch(e){n=e}throw n},nh=async e=>{if(e={wait:!1,background:!1,newInstance:!1,allowNonzeroExitCode:!1,...e},Array.isArray(e.app))return th(e.app,t=>nh({...e,app:t}));let{name:t,arguments:n=[]}=e.app??{};if(n=[...n],Array.isArray(t))return th(t,t=>nh({...e,app:{name:t,arguments:n}}));if(t===`browser`||t===`browserPrivate`){let r={"com.google.chrome":`chrome`,"google-chrome.desktop":`chrome`,"com.brave.Browser":`brave`,"org.mozilla.firefox":`firefox`,"firefox.desktop":`firefox`,"com.microsoft.msedge":`edge`,"com.microsoft.edge":`edge`,"com.microsoft.edgemac":`edge`,"microsoft-edge.desktop":`edge`},i={chrome:`--incognito`,brave:`--incognito`,firefox:`--private-window`,edge:`--inPrivate`},a=Mm?await eh():await Jm();if(a.id in r){let o=r[a.id];return t===`browserPrivate`&&n.push(i[o]),nh({...e,app:{name:oh[o],arguments:n}})}throw Error(`${a.name} is not supported as a default browser`)}let r,i=[],o={};if(Qm===`darwin`)r=`open`,e.wait&&i.push(`--wait-apps`),e.background&&i.push(`--background`),e.newInstance&&i.push(`--new`),t&&i.push(`-a`,t);else if(Qm===`win32`||Mm&&!Am()&&!t){r=await Fm(),i.push(`-NoProfile`,`-NonInteractive`,`-ExecutionPolicy`,`Bypass`,`-EncodedCommand`),Mm||(o.windowsVerbatimArguments=!0);let s=[`Start`];e.wait&&s.push(`-Wait`),t?(s.push(`"\`"${t}\`""`),e.target&&n.push(e.target)):e.target&&s.push(`"${e.target}"`),n.length>0&&(n=n.map(e=>`"\`"${e}\`""`),s.push(`-ArgumentList`,n.join(`,`))),e.target=a.Buffer.from(s.join(` `),`utf16le`).toString(`base64`)}else{if(t)r=t;else{let e=!Xm||Xm===`/`,t=!1;try{await E.default.access(Zm,E.constants.X_OK),t=!0}catch{}r=x.default.versions.electron??(Qm===`android`||e||!t)?`xdg-open`:Zm}n.length>0&&i.push(...n),e.wait||(o.stdio=`ignore`,o.detached=!0)}Qm===`darwin`&&n.length>0&&i.push(`--args`,...n),e.target&&i.push(e.target);let s=T.default.spawn(r,i,o);return e.wait?new Promise((t,n)=>{s.once(`error`,n),s.once(`close`,r=>{if(!e.allowNonzeroExitCode&&r>0){n(Error(`Exited with code ${r}`));return}t(s)})}):(s.unref(),s)},rh=(e,t)=>{if(typeof e!=`string`)throw TypeError("Expected a `target`");return nh({...t,target:e})};function ih(e){if(typeof e==`string`||Array.isArray(e))return e;let{[$m]:t}=e;if(!t)throw Error(`${$m} is not supported`);return t}function ah({[Qm]:e},{wsl:t}){if(t&&Mm)return ih(t);if(!e)throw Error(`${Qm} is not supported`);return ih(e)}const oh={};Im(oh,`chrome`,()=>ah({darwin:`google chrome`,win32:`chrome`,linux:[`google-chrome`,`google-chrome-stable`,`chromium`]},{wsl:{ia32:`/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe`,x64:[`/mnt/c/Program Files/Google/Chrome/Application/chrome.exe`,`/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe`]}})),Im(oh,`brave`,()=>ah({darwin:`brave browser`,win32:`brave`,linux:[`brave-browser`,`brave`]},{wsl:{ia32:`/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe`,x64:[`/mnt/c/Program Files/BraveSoftware/Brave-Browser/Application/brave.exe`,`/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe`]}})),Im(oh,`firefox`,()=>ah({darwin:`firefox`,win32:String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,linux:`firefox`},{wsl:`/mnt/c/Program Files/Mozilla Firefox/firefox.exe`})),Im(oh,`edge`,()=>ah({darwin:`microsoft edge`,win32:`msedge`,linux:[`microsoft-edge`,`microsoft-edge-dev`]},{wsl:`/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe`})),Im(oh,`browser`,()=>`browser`),Im(oh,`browserPrivate`,()=>`browserPrivate`);var sh=rh;async function ch(e,t=void 0){try{(await sh(e)).once(`error`,n=>{console.log(mf.yellow(t??`Could not open the browser. Please visit the URL manually: ${e}`))})}catch{console.log(mf.yellow(t??`Could not open the browser. Please visit the URL manually: ${e}`))}}function lh(e){let t=e||fh();if((0,o.existsSync)(t)){let e=(0,o.readFileSync)(t,`utf8`);return JSON.parse(e).token}}function uh(e,t){let n=t||fh();(0,o.existsSync)((0,b.dirname)(n))||(0,o.mkdirSync)((0,b.dirname)(n),{recursive:!0}),(0,o.writeFileSync)(n,JSON.stringify({_:`This is your Blink credentials file. DO NOT SHARE THIS FILE WITH ANYONE!`,token:e}))}function dh(e){let t=e||fh();(0,o.existsSync)(t)&&(0,o.unlinkSync)(t)}function fh(){let e=Dd(`blink`).dataDirs();if(e.length===0)throw Error(`No suitable data directory for Blink storage found!`);return(0,b.join)(e[0],`auth.json`)}function ph(e={}){let{autoCheck:t=!0,onAuthChange:n,onLoginUrl:r,testAuthPath:i}=e,[a,o]=(0,_.useState)(),[s,c]=(0,_.useState)(()=>lh(i)),[l,u]=(0,_.useState)(),d=(0,_.useRef)(n),f=(0,_.useRef)(r);(0,_.useEffect)(()=>{d.current=n,f.current=r},[n,r]);let p=(0,_.useCallback)(async()=>{u(void 0);try{let e=lh(i);if(c(e),!e){o(void 0),d.current?.(void 0);return}let t=new sd({baseURL:`https://blink.so`});t.authToken=e;let n={email:(await t.users.me()).email};o(n),d.current?.(n)}catch(e){o(void 0),u(e instanceof Error?e.message:String(e)),d.current?.(void 0)}},[i]),m=(0,_.useCallback)(async()=>{u(void 0);try{let e=new sd,t=await e.auth.token((e,t)=>{f.current?.(e,t)});e.authToken=t;let n=await e.users.me();uh(t,i),c(t);let r={email:n.email};return o(r),d.current?.(r),r}catch(e){let t=e instanceof Error?e.message:String(e);throw u(t),e}},[i]),h=(0,_.useCallback)(()=>{dh(i),c(void 0),o(void 0),u(void 0),d.current?.(void 0)},[i]);return(0,_.useEffect)(()=>{t&&p()},[t,p]),{user:a,token:s,error:l,login:m,logout:h}}function mh(e){let{directory:t,onBuildStart:r,onBuildSuccess:i,onBuildError:a}=typeof e==`string`?{directory:e}:e,o=(0,_.useMemo)(()=>n.resolveConfig(t),[t]),[s,c]=(0,_.useState)(void 0),[l,u]=(0,_.useState)(void 0),[d,f]=(0,_.useState)(`building`),p=(0,_.useRef)(r),m=(0,_.useRef)(i),h=(0,_.useRef)(a);return(0,_.useEffect)(()=>{p.current=r,m.current=i,h.current=a},[r,i,a]),(0,_.useEffect)(()=>{let e=new AbortController;return o.build({cwd:t,entry:o.entry,outdir:o.outdir,watch:!0,dev:!0,signal:e.signal,onStart:()=>{f(`building`),c(void 0),u(void 0),p.current?.()},onResult:e=>{`error`in e?(c(e.error),f(`error`),h.current?.(e.error)):(u(e),f(`success`),m.current?.(e))}}).catch(e=>{console.log(`error`,e),f(`error`),c(e),h.current?.(e)}),()=>{e.abort()}},[t]),(0,_.useMemo)(()=>({error:s,status:d,result:l,entry:o.entry,outdir:o.outdir}),[s,d,l,o.entry,o.outdir])}function hh(){return/[<>:"/\\|?*\u0000-\u001F]|[. ]$/g}function gh(){return/^(con|prn|aux|nul|com\d|lpt\d)$/i}const _h=100,vh=/^\.+(\\|\/)|^\.+$/,yh=/[. ]+$/,bh=/[\p{Control}\p{Format}\p{Zl}\p{Zp}\uFFF0-\uFFFF]/gu,xh=/[\p{Control}\p{Format}\p{Zl}\p{Zp}\uFFF0-\uFFFF]/u,Sh=e=>e===``,Ch=/([<>:"/\\|?*\u0000-\u001F]){2,}/g,wh=/[\t\n\r\u00A0\u1680\u2000-\u200A\u202F\u205F\u3000]+/g;let Th;function Eh(){return Th??=new Intl.Segmenter(void 0,{granularity:`grapheme`}),Th}function Dh(e,t={}){if(typeof e!=`string`)throw TypeError(`Expected a string`);let n=t.replacement??`!`;if(hh().test(n)||[...n].some(e=>xh.test(e)&&!Sh(e)))throw Error(`Replacement string cannot contain reserved filename characters`);e=e.normalize(`NFC`),e=e.replaceAll(wh,` `),n.length>0&&(e=e.replaceAll(Ch,`$1`)),e=e.replace(yh,``),e=e.replace(vh,n),e=e.replace(hh(),n),e=e.replaceAll(bh,e=>Sh(e)?e:n),e.length===0&&(e=n),e=gh().test(e)?e+n:e;let r=typeof t.maxLength==`number`?t.maxLength:100;if(e.length>r){let t=e.lastIndexOf(`.`);if(t===-1)e=Oh(e,r);else{let n=e.slice(0,t),i=e.slice(t),a=Math.max(0,r-i.length);e=Oh(n,a)+i}}return e}function Oh(e,t){if(e.length<=t)return e;let n=0,r=``;for(let{segment:i}of Eh().segment(e)){let e=n+i.length;if(e>t)break;r+=i,n=e}return r}function kh(e){return`${e}.lock`}function Ah(e){try{return process.kill(e,0),!0}catch(e){return e.code===`EPERM`}}function jh(e,t={}){let n=kh(e),r=process.pid.toString();try{return o.writeFileSync(n,r,{flag:`wx`}),!0}catch(r){if(r.code!==`EEXIST`)throw r;if(t.stale===0)return!1;let i;try{i=parseInt(o.readFileSync(n,`utf8`),10)}catch{return o.unlinkSync(n),jh(e,{...t,stale:0})}if(!Ah(i))try{return o.unlinkSync(n),jh(e,{...t,stale:0})}catch(n){if(n.code===`ENOENT`)return jh(e,{...t,stale:0});throw n}return!1}}async function Mh(e,t={}){let n={stale:!0,retries:0,retryInterval:100,...t},r=b.resolve(e),i=0;for(;i<=n.retries;){if(jh(r,n))return()=>Nh(r);i<n.retries&&await new Promise(e=>setTimeout(e,n.retryInterval)),i++}let a=Error(`Lock file is already being held`);throw a.code=`ELOCKED`,a.file=r,a}function Nh(e){let t=b.resolve(e),n=kh(t);try{if(parseInt(o.readFileSync(n,`utf8`),10)!==process.pid){let e=Error(`Lock is not owned by this process`);throw e.code=`ENOTACQUIRED`,e}o.unlinkSync(n)}catch(e){if(e.code===`ENOENT`){let e=Error(`Lock is not acquired`);throw e.code=`ENOTACQUIRED`,e}throw e}}function Ph(e){let t=b.resolve(e),n=kh(t);try{if(!o.existsSync(n))return{locked:!1};let e=o.readFileSync(n,`utf8`),t=parseInt(e,10);return Ah(t)?{locked:!0,pid:t}:{locked:!1}}catch(e){return e.code,{locked:!1}}}const Fh=e=>{o.mkdirSync(e,{recursive:!0})},Ih=e=>{try{o.fdatasyncSync(e)}catch{}try{o.closeSync(e)}catch{}},Lh=e=>{try{let t=o.openSync(e,`r`);try{o.fsyncSync(t)}finally{o.closeSync(t)}}catch{}},Rh=(e,t)=>{let n=b.dirname(e);Fh(n);let r=b.join(n,`.tmp-`+process.pid+`-`+Math.random().toString(36).slice(2)),i;try{i=o.openSync(r,`w`),o.writeFileSync(i,t,`utf-8`),Ih(i),i=void 0,o.renameSync(r,e),Lh(e),Lh(n)}catch(e){if(i!==void 0)try{o.closeSync(i)}catch{}try{o.rmSync(r,{force:!0})}catch{}throw e}},zh=(e,t)=>{let n=new Map,r,i=e=>{if(o.statSync(e,{throwIfNoEntry:!1}))return JSON.parse(o.readFileSync(e,`utf-8`))},a=(e,t)=>{Rh(e,JSON.stringify(t,null,2))},s=async()=>{if(r)throw Error(`Index is already locked`);let t=b.join(e,`index.json`);Fh(e),o.existsSync(t)||o.writeFileSync(t,JSON.stringify({ids:{}}),`utf-8`);let n=await Mh(t,{stale:!0,retries:5,retryInterval:100});return r=()=>Promise.resolve(n()),()=>{n(),r=void 0}},c=async()=>{let t=b.join(e,`index.json`),n=i(t)??{ids:{}};return n.ids||={},n},l=async t=>{let n=b.join(e,`index.json`);a(n,t)},u=async t=>{let n=(await c()).ids[t];if(n)return b.join(e,n)},d=async t=>{let n=(await c()).ids[t];if(!n)return;let r=b.join(e,n);if(o.statSync(r,{throwIfNoEntry:!1}))return JSON.parse(o.readFileSync(r,`utf-8`))},f=async n=>{let r=n[t],i=String(r),o=Dh(i,{replacement:`_`})+`.json`,u=await s();try{let t=await c();t.ids[i]=o,t.current=i;let r=b.join(e,o);a(r,n),await l(t)}finally{await u()}};return{async get(e){return await d(e)},async list(){if(!o.statSync(e,{throwIfNoEntry:!1}))return[];let t=await c(),n=[];for(let[r,i]of Object.entries(t.ids)){let t=b.join(e,i),a=o.statSync(t,{throwIfNoEntry:!1});if(!a)continue;let s=Ph(t);n.push({key:r,locked:s.locked,pid:s.pid,mtime:a.mtimeMs})}return n.sort((e,t)=>t.mtime-e.mtime),n},async lock(r,i){if(n.has(r))throw Error(`Key "${r}" is already locked in this process`);let a=await u(r);if(!a){let t=Dh(r,{replacement:`_`})+`.json`,n=await s();try{let n=await c();n.ids[r]=t;let i=b.join(e,t);Fh(e),o.writeFileSync(i,JSON.stringify({}),`utf-8`),await l(n),a=i}finally{await n()}}if(i?.force){let e=Ph(a);if(e.locked&&e.pid&&e.pid!==process.pid)try{process.kill(e.pid,`SIGTERM`),await new Promise(e=>setTimeout(e,100))}catch(t){t.code!==`ESRCH`&&console.warn(`Failed to kill process ${e.pid}:`,t.message)}}let p=await Mh(a,{stale:!0,retries:i?.force?10:5,retryInterval:(i?.force,100)});return n.set(r,()=>Promise.resolve(p())),{async get(){let e=await d(r);if(!e)throw Error(`Key ${r} not found`);return e},async set(e){await f(e)},async update(e){let n=await d(r);if(!n||!(t in n))throw Error(`Key ${r} not found`);await f({...n,...e})},async delete(){let t=await s();try{let t=await c(),n=t.ids[r];if(n){delete t.ids[r],t.current===r&&(t.current=void 0),await l(t);let i=b.join(e,n);try{o.rmSync(i,{force:!0}),Lh(e)}catch{}}}finally{await t()}},async release(){try{p()}finally{n.delete(r)}}}},dispose(){n.clear()}}},Bh=(e,t)=>{let n=t?.pollInterval??200,r=t?.debounce??50,i=new Set,a,s,c=new Map,l=new Map,u=b.join(e,`index.json`),d=()=>{try{if(!o.statSync(u,{throwIfNoEntry:!1}))return{ids:{}};let e=o.readFileSync(u,`utf-8`);return{ids:JSON.parse(e).ids??{}}}catch{return{ids:{}}}},f=(e,t,n,r)=>{for(let a of i)try{a({key:e,value:t,locked:n,pid:r})}catch(e){console.error(`Error in onChange callback:`,e)}},p=(t,n,r=!1)=>{let i=b.join(e,n);try{let e=o.statSync(i,{throwIfNoEntry:!1}),a=l.get(n);if(!e){a&&(l.delete(n),f(t,void 0,!1));return}let s=e.mtimeMs,c=a?{locked:a.locked,pid:a.pid}:{locked:!1,pid:void 0};if((r||!a)&&(c=Ph(i)),!a||a.mtime!==s||a.locked!==c.locked||a.pid!==c.pid){let e;e=!a||a.mtime!==s?JSON.parse(o.readFileSync(i,`utf-8`)):a.cachedValue,l.set(n,{mtime:s,key:t,locked:c.locked,pid:c.pid,cachedValue:e}),f(t,e,c.locked,c.pid)}}catch{}},m=()=>{try{let e=d(),t=new Set(Object.keys(e.ids));for(let[t,n]of Object.entries(e.ids))p(t,n,!0);for(let[e,n]of l.entries())t.has(n.key)||(l.delete(e),f(n.key,void 0,!1))}catch{}},h=(e,t,n=!1)=>{let i=c.get(e);i&&clearTimeout(i),c.set(e,setTimeout(()=>{c.delete(e),p(e,t,n)},r))},g=()=>{if(a)return;try{o.mkdirSync(e,{recursive:!0})}catch{}a=o.watch(e,(e,t)=>{if(!t||t.startsWith(`.tmp-`))return;if(t===`index.json`){m();return}if(t.endsWith(`.lock`)){let e=t.replace(`.lock`,``),n=d(),r=Object.keys(n.ids).find(t=>n.ids[t]===e);r&&p(r,e,!0);return}let n=d(),r=Object.keys(n.ids).find(e=>n.ids[e]===t);r&&h(r,t,!1)});let t=()=>{m(),s=setTimeout(t,n)};m(),s=setTimeout(t,n)};return{onChange(e){return i.size===0&&g(),i.add(e),()=>{if(i.delete(e),i.size===0){a&&=(a.close(),void 0),s&&=(clearTimeout(s),void 0);for(let e of c.values())clearTimeout(e);c.clear(),l.clear()}}},dispose(){a&&=(a.close(),void 0),s&&=(clearTimeout(s),void 0);for(let e of c.values())clearTimeout(e);c.clear(),i.clear(),l.clear()}}};async function Vh({id:e,agent:t,messages:n,signal:r,shouldContinueStreaming:i=Hh}){n=[...n];let a=new TransformStream,o=a.writable.getWriter(),s=async()=>{let a;try{let c=await t.chat({messages:n,id:e},{signal:r}),l=(0,m.readUIMessageStream)({message:{id:crypto.randomUUID(),role:`assistant`,parts:[],metadata:{}},stream:c,onError:e=>{e instanceof Error&&e.name===`AbortError`||o.abort(e)}});for await(let e of l)o.write(e),a=e;if(a&&i(a)){n.push(a),await s();return}await o.close()}catch(e){if(e?.name===`AbortError`||r?.aborted)return;await o.abort(e)}finally{await o.close()}};return s().catch(e=>{o.abort(e)}),a.readable}const Hh=e=>{if(e.role!==`assistant`)return!1;let n=e.parts.reduce((e,t,n)=>t.type===`step-start`?n:e,-1),r=e.parts.slice(n+1).filter(m.isToolOrDynamicToolUIPart);return r.length===0||r.some(e=>t.isToolApprovalOutput(e.output)&&e.output.outcome===`pending`)?!1:r.every(e=>e.state.startsWith(`output-`))},Uh=(e,t,n=crypto.randomUUID())=>({created_at:new Date().toISOString(),...e,id:n,metadata:e.metadata,mode:t});function Wh(e){return typeof e==`object`&&e?.__blink_internal!==void 0}var Gh=class{chatId;agent;chatStore;serializeMessage;filterMessages;chat;loading=!1;streamingMessage;status=`idle`;queue=[];abortController;isProcessingQueue=!1;listeners=new Set;watcher;disposed=!1;constructor(e){this.chatId=e.chatId??`00000000-0000-0000-0000-000000000000`,this.chat={id:this.chatId,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[]},this.loading=!0,this.chatStore=zh(e.chatsDirectory,`id`),this.serializeMessage=e.serializeMessage,this.filterMessages=e.filterMessages,this.watcher=Bh(e.chatsDirectory,{pollInterval:1e3,debounce:50}),this.watcher.onChange(e=>{if(e.key!==this.chatId||this.isProcessingQueue)return;if(!e.value){this.chat={id:this.chatId,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[]},this.status=`idle`,this.streamingMessage=void 0,this.notifyListeners();return}if(this.chat.updated_at===e.value?.updated_at)return;let t=e.value,n=e.value?.error?`error`:`idle`;e.locked&&(n=`streaming`);let r=this.chat.updated_at!==t?.updated_at||this.status!==n;this.chat={...t,error:void 0},this.streamingMessage=void 0,this.status=n,r&&this.notifyListeners()}),this.chatStore.get(this.chatId).then(e=>{this.disposed||e&&(this.chat={...e,error:void 0})}).catch(e=>{this.chat.error=e instanceof Error?e.message:String(e)}).finally(()=>{this.loading=!1,this.notifyListeners()})}setAgent(e){this.agent=e}getState(){return{id:this.chatId,key:this.chat?.key,messages:(this.chat?.messages??[]).filter(e=>!Wh(e.metadata)),created_at:this.chat?.created_at,updated_at:this.chat?.updated_at,status:this.status,streamingMessage:this.streamingMessage,error:this.chat?.error,loading:this.loading,queuedMessages:this.queue}}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}async upsertMessages(e,t){let n=!1,r;t?r=t:(r=await this.chatStore.lock(this.chatId),n=!0);try{let t=await r.get();(!t.id||!Array.isArray(t.messages))&&(t={id:this.chatId,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[]});let n=[...t.messages];for(let t of e){let e;if(this.serializeMessage){let n=this.serializeMessage(t);if(n===void 0)return;e=n}else e={...t,created_at:new Date().toISOString(),mode:`run`,metadata:t.metadata,id:t.id??crypto.randomUUID()};let r=n.findIndex(t=>t.id===e.id);r===-1?n.push(e):n.splice(r,1,e)}this.chat={...t,updated_at:new Date().toISOString(),messages:n},await r.set(this.chat),this.notifyListeners()}finally{n&&await r.release()}}async deleteMessages(e){let t;try{t=await this.chatStore.lock(this.chatId);let n=await t.get();this.chat.messages=n.messages.filter(t=>!e.includes(t.id)),this.chat.updated_at=new Date().toISOString(),await t.set(this.chat),this.notifyListeners()}finally{t&&await t.release()}}async sendMessages(e){if(this.chat.error){let e=await this.chatStore.lock(this.chatId);try{this.chat={...await e.get(),error:void 0,updated_at:new Date().toISOString()},await e.set(this.chat)}finally{await e.release()}}if(this.status=`idle`,this.notifyListeners(),this.isProcessingQueue){this.queue.push(...e),this.notifyListeners();return}this.queue=e,this.processQueueOrRun()}async start(){this.chat.error=void 0,this.status=`idle`,this.notifyListeners(),this.processQueueOrRun()}async stop(){this.status=`idle`,this.abortController?.abort(),this.notifyListeners()}async processQueueOrRun(){if(!this.agent){this.chat.error=`The agent is not available. Please wait for the build to succeed.`,this.status=`error`,this.queue=[],this.notifyListeners();return}if(this.isProcessingQueue)return;this.isProcessingQueue=!0,this.chat.error=void 0;let e;try{e=await this.chatStore.lock(this.chatId);let t=!0;for(;this.queue.length>0||t;){t=!1;let n=new AbortController;this.abortController=n;let r=[...this.queue];this.queue=[],this.streamingMessage=void 0,this.status=`streaming`,this.notifyListeners(),r.length>0&&await this.upsertMessages(r,e);let i=this.chat.messages;this.filterMessages&&(i=i.filter(this.filterMessages)),i=i.map(e=>({...e,parts:e.parts.map(e=>!(0,m.isToolOrDynamicToolUIPart)(e)||e.input!==``?e:{...e,input:{}})}));let a=performance.now(),o=await Vh({agent:this.agent,id:this.chatId,signal:n.signal,messages:i}),s=async t=>{let n=t;if(this.serializeMessage){let e=this.serializeMessage(t);if(e===void 0)return;n=e}this.chat.updated_at=new Date().toISOString(),this.chat.messages.push(n),this.streamingMessage=void 0,await e?.set(this.chat)},c=o.getReader();n.signal.addEventListener(`abort`,()=>{c.cancel().catch(()=>{})},{once:!0});let l;try{for(;;){let{done:e,value:t}=await c.read();if(e||n.signal.aborted)break;l||=performance.now()-a,this.streamingMessage&&t.id!==this.streamingMessage.id&&await s(this.streamingMessage);let r={...t,metadata:{...typeof t.metadata==`object`&&t.metadata!==null?t.metadata:{},ttft:l}};this.streamingMessage=this.serializeMessage?this.serializeMessage(r):r,this.notifyListeners()}}finally{c.releaseLock()}this.streamingMessage&&await s(this.streamingMessage)}}catch(e){this.chat.error=e instanceof Error?e.message:String(e)}finally{this.isProcessingQueue=!1,this.streamingMessage=void 0,this.chat.error?this.status=`error`:this.status=`idle`,e&&(this.chat.updated_at=new Date().toISOString(),await e.set(this.chat),await e.release(),this.notifyListeners())}}stopStreaming(){this.abortController?.abort()}clearQueue(){this.queue=[],this.notifyListeners()}async resetChat(){this.abortController?.abort(),this.resetChatState(),this.notifyListeners();let e;try{e=await this.chatStore.lock(this.chatId),await e.delete()}catch{}finally{if(e)try{await e.release()}catch{}}}dispose(){this.disposed=!0,this.watcher.dispose(),this.listeners.clear(),this.abortController?.abort()}resetChatState(){this.chat={id:this.chatId,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[]},this.streamingMessage=void 0,this.status=`idle`,this.queue=[]}notifyListeners(){let e=this.getState();for(let t of this.listeners)t(e)}};function Kh(e){let{chatId:t,agent:n,chatsDirectory:r,serializeMessage:i,filterMessages:a}=e,o=(0,_.useRef)(null),[s,c]=(0,_.useState)({id:t,messages:[],status:`idle`,loading:!0,queuedMessages:[]});(0,_.useEffect)(()=>{o.current&&o.current.dispose();let e=new Gh({chatId:t,chatsDirectory:r,serializeMessage:i,filterMessages:a}),n=e.subscribe(e=>{c(e)});return c(e.getState()),o.current=e,()=>{n(),e.dispose(),o.current=null}},[t,r]),(0,_.useEffect)(()=>{o.current&&o.current.setAgent(n)},[n]);let l=(0,_.useCallback)(async e=>{o.current&&await o.current.sendMessages([e])},[]),u=(0,_.useCallback)(async e=>{o.current&&await o.current.upsertMessages([e])},[]),d=(0,_.useCallback)(()=>{o.current&&o.current.stopStreaming()},[]),f=(0,_.useCallback)(async()=>{o.current&&await o.current.resetChat()},[]),p=(0,_.useCallback)(()=>{o.current&&o.current.clearQueue()},[]),m=(0,_.useCallback)(async e=>{o.current&&await o.current.deleteMessages([e])},[]),h=(0,_.useCallback)(async()=>{o.current&&await o.current.start()},[]);return{...s,sendMessage:l,upsertMessage:u,stopStreaming:d,resetChat:f,clearQueue:p,deleteMessage:m,start:h}}function qh(e){return(0,f.join)(e,`.blink`,`devhook.txt`)}function Jh(e){return(0,p.existsSync)(qh(e))}function Yh(e){let t=qh(e);if((0,p.existsSync)(t))return(0,p.readFileSync)(t,`utf-8`).trim()}function Xh(e){let t=qh(e);if((0,p.mkdirSync)((0,f.dirname)(t),{recursive:!0}),(0,p.existsSync)(t))return(0,p.readFileSync)(t,`utf-8`);let n=crypto.randomUUID();return(0,p.writeFileSync)(t,n),n}const Zh=(e,t)=>e.json({error:t},400),Qh=e=>{let t=e.req.param(`key`);return!t||t===``?{key:t,err:`Key is required`}:t.length>475?{key:t,err:`Key is too long. Max length is 475 characters.`}:{key:t}},$h=()=>new t.Hono,eg=$h().get(`/:key`,async e=>{let{key:t,err:n}=Qh(e);if(n)return Zh(e,n);let r=await e.env.store.get(t);return e.json({value:r},200)}).post(`/:key`,t.validator(`json`,(e,t)=>{let n=e.value;return n?typeof n==`string`?n.length>2e4?Zh(t,`Value is too long. Max length is 20,000 characters.`):{value:n}:Zh(t,`Value must be a string`):Zh(t,`Value is required`)}),async e=>{let{key:t,err:n}=Qh(e);if(n)return Zh(e,n);let{value:r}=e.req.valid(`json`);return await e.env.store.set(t,r),e.body(null,204)}).delete(`/:key`,async e=>{let{key:t,err:n}=Qh(e);return n?Zh(e,n):(await e.env.store.delete(t),e.body(null,204))}).get(`/`,async e=>{let{cursor:t,limit:n,prefix:r}=e.req.query(),{entries:i,cursor:a}=await e.env.store.list(r,{cursor:t?String(t):void 0,limit:n?Number(n):100});return e.json({entries:i,cursor:a})}),tg=e=>{let t=e.req.param(`key`);return t?t.length>475?{key:t,err:`Key is too long. Max length is 475 characters.`}:{key:t}:{key:t,err:`Key is required`}},ng=t.validator(`param`,e=>({id:e.id})),rg=$h().post(`/:key`,async e=>{let{key:t,err:n}=tg(e);return n?Zh(e,n):e.json(await e.env.chat.upsert(t),200)}).get(`/:id`,ng,async e=>{let{id:t}=e.req.valid(`param`);return e.json(await e.env.chat.get(t),200)}).get(`/:id/messages`,ng,async e=>{let{id:t}=e.req.valid(`param`);return e.json(await e.env.chat.getMessages(t),200)}).post(`/:id/sendMessages`,t.validator(`json`,e=>({id:e.id,messages:e.messages,options:e.options})),async e=>{let{id:t,messages:n,options:r}=e.req.valid(`json`);return t?(await e.env.chat.sendMessages(t,n,r),e.body(null,204)):Zh(e,`ID is required`)}).delete(`/:id/messages`,ng,t.validator(`query`,e=>(typeof e.message==`string`&&(e.message=[e.message]),{messages:e.message})),async e=>{let{id:t}=e.req.valid(`param`),{messages:n}=e.req.valid(`query`);return await e.env.chat.deleteMessages(t,n),e.body(null,204)}).post(`/:id/start`,ng,async e=>{let{id:t}=e.req.valid(`param`);return await e.env.chat.start(t),e.body(null,204)}).post(`/:id/stop`,ng,async e=>{let{id:t}=e.req.valid(`param`);return await e.env.chat.stop(t),e.body(null,204)}).delete(`/:id`,ng,async e=>{let{id:t}=e.req.valid(`param`);return await e.env.chat.delete(t),e.body(null,204)}),ig=$h().post(`/v1/traces`,async e=>e.env.otlp?e.env.otlp.traces(e.req.raw):e.body(null,204)),ag=new t.Hono().onError((e,t)=>t.json({error:e instanceof Error?e.message:`Unknown error`},500)).route(`/kv`,eg).route(`/chat`,rg).route(`/otlp`,ig);var og=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;function sg(e){return typeof e==`string`&&og.test(e)}var cg=sg;function lg(e){if(!cg(e))throw TypeError(`Invalid UUID`);let t;return Uint8Array.of((t=parseInt(e.slice(0,8),16))>>>24,t>>>16&255,t>>>8&255,t&255,(t=parseInt(e.slice(9,13),16))>>>8,t&255,(t=parseInt(e.slice(14,18),16))>>>8,t&255,(t=parseInt(e.slice(19,23),16))>>>8,t&255,(t=parseInt(e.slice(24,36),16))/1099511627776&255,t/4294967296&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255)}var ug=lg;const $=[];for(let e=0;e<256;++e)$.push((e+256).toString(16).slice(1));function dg(e,t=0){return($[e[t+0]]+$[e[t+1]]+$[e[t+2]]+$[e[t+3]]+`-`+$[e[t+4]]+$[e[t+5]]+`-`+$[e[t+6]]+$[e[t+7]]+`-`+$[e[t+8]]+$[e[t+9]]+`-`+$[e[t+10]]+$[e[t+11]]+$[e[t+12]]+$[e[t+13]]+$[e[t+14]]+$[e[t+15]]).toLowerCase()}function fg(e){e=unescape(encodeURIComponent(e));let t=new Uint8Array(e.length);for(let n=0;n<e.length;++n)t[n]=e.charCodeAt(n);return t}const pg=`6ba7b810-9dad-11d1-80b4-00c04fd430c8`,mg=`6ba7b811-9dad-11d1-80b4-00c04fd430c8`;function hg(e,t,n,r,i,a){let o=typeof n==`string`?fg(n):n,s=typeof r==`string`?ug(r):r;if(typeof r==`string`&&(r=ug(r)),r?.length!==16)throw TypeError(`Namespace must be array-like (16 iterable integer values, 0-255)`);let c=new Uint8Array(16+o.length);if(c.set(s),c.set(o,s.length),c=t(c),c[6]=c[6]&15|e,c[8]=c[8]&63|128,i){a||=0;for(let e=0;e<16;++e)i[a+e]=c[e];return i}return dg(c)}function gg(e){return Array.isArray(e)?e=Buffer.from(e):typeof e==`string`&&(e=Buffer.from(e,`utf8`)),(0,u.createHash)(`sha1`).update(e).digest()}var _g=gg;function vg(e,t,n,r){return hg(80,_g,e,t,n,r)}vg.DNS=`6ba7b810-9dad-11d1-80b4-00c04fd430c8`,vg.URL=`6ba7b811-9dad-11d1-80b4-00c04fd430c8`;var yg=vg;function bg(e){let n=(0,b.join)(e.dataDirectory,`chats`),r={},i=(0,b.join)(e.dataDirectory,`storage.json`);o.existsSync(i)&&(r=JSON.parse(o.readFileSync(i,`utf-8`)));let a=new Map,s=t=>{let r=a.get(t);return r||(r=new Gh({chatId:t,chatsDirectory:n}),a.set(t,r)),r.setAgent(e.getAgent()),r},c={async upsert(e){let t=yg(JSON.stringify(e),yg.URL),n=s(t).getState(),r=n.messages.length===0&&!n.created_at;return{id:n.id,created:r,createdAt:n.created_at??new Date().toISOString(),key:e}},async get(e){let t=s(e).getState();return{id:t.id,createdAt:t.created_at??new Date().toISOString()}},async getMessages(e){return s(e).getState().messages},async sendMessages(e,t,n){let r=s(e),i=t.map(e=>Uh(e,`run`));if(n?.behavior===`append`){await r.upsertMessages(i);return}if(n?.behavior===`interrupt`){await r.sendMessages(i);return}await r.sendMessages(i)},async deleteMessages(e,t){await s(e).deleteMessages(t)},async start(e){await s(e).start()},async stop(e){await s(e).stop()},async delete(e){await s(e).resetChat()}},l={get(e){return Promise.resolve(r[e])},set(e,t){return r[e]=t,o.writeFileSync(i,JSON.stringify(r),`utf-8`),Promise.resolve()},delete(e){return delete r[e],o.writeFileSync(i,JSON.stringify(r),`utf-8`),Promise.resolve()},list(e,t){let n=Math.min(t?.limit??100,1e3),i=t?.cursor,a=Object.keys(r).filter(t=>t.startsWith(e??``)).sort(),o=0;if(i){let e=a.indexOf(i);e!==-1&&(o=e+1)}let s=a.slice(o,o+n),c=o+n<a.length?s[s.length-1]:void 0;return Promise.resolve({entries:s.map(e=>({key:e})),cursor:c})}},u=(0,d.createServer)(t.createServerAdapter(e=>ag.fetch(e,{chat:c,store:l})));u.listen(e.port??0);let f=zh(n,`id`);return{url:`http://127.0.0.1:${u.address().port}`,chatsDirectory:n,getChatManager:s,listChats:()=>f.list(),dispose:()=>{for(let e of a.values())e.dispose();a.clear(),f.dispose(),u.close()}}}function xg({agent:e,capabilities:n,messages:r}){let[i,a]=(0,_.useState)(void 0),[o,s]=(0,_.useState)(!0),[c,l]=(0,_.useState)(void 0),u=(0,_.useRef)(c);(0,_.useEffect)(()=>{u.current=c},[c]);let[d,f]=(0,_.useState)(()=>t.lastUIOptions(r));(0,_.useEffect)(()=>{f(e=>{let n=t.lastUIOptions(r);return JSON.stringify(n)===JSON.stringify(e)?e:n})},[r]);let[p,m]=(0,_.useState)(void 0),h=(0,_.useCallback)((e,t)=>{if(!u.current)return!1;let n=u.current[e];return n?n.values.some(e=>e.id===t):!1},[]),g=(0,_.useCallback)(e=>{m(t=>{let n={...d,...t,...e};for(let[e,t]of Object.entries(n))h(e,t)||delete n[e];for(let[e,t]of Object.entries(u.current??{}))!n[e]&&t.defaultValue!==void 0&&(n[e]=t.defaultValue);return JSON.stringify(n)===JSON.stringify(t)?t:n})},[d,h]);(0,_.useEffect)(()=>{if(!d&&!c){m(void 0);return}g()},[d,c,g]);let v=(0,_.useRef)(void 0),y=(0,_.useRef)(void 0);(0,_.useEffect)(()=>{e!==y.current&&(y.current=e,l(void 0),m(void 0),a(void 0),s(!0),v.current=void 0)},[e]),(0,_.useEffect)(()=>{if(n&&!n.ui||!e){l(void 0),m(void 0),a(void 0),v.current=void 0;return}let t=p?JSON.stringify(p):``;if(v.current===t){s(!1),a(void 0);return}let r=new AbortController;return s(!0),a(void 0),e.ui(p?{selectedOptions:p}:{},{signal:r.signal}).then(e=>{if(!e){l(void 0);return}r.signal.aborted||(l(t=>JSON.stringify(t)===JSON.stringify(e)?t:e),v.current=t)}).catch(e=>{r.signal.aborted||a(e instanceof Error?e:Error(String(e)))}).finally(()=>{s(!1)}),()=>{r.abort()}},[e,n,p]);let b=(0,_.useCallback)((e,t)=>{g({[e]:t})},[g]);return{schema:c,options:p,setOption:b,loading:o,error:i}}function Sg(e){let t=(0,_.useRef)(e.onRequest);(0,_.useEffect)(()=>{t.current=e.onRequest},[e.onRequest]);let[n,r]=(0,_.useState)(`disconnected`);return(0,_.useEffect)(()=>{if(e.disabled||!e.id){r(`disconnected`);return}let n=!1,i,a,o=!1,s,c=(0,b.join)(e.directory,`.blink`,`devhook`);return(async()=>{try{s=await Mh(c,{stale:!0,retries:0})}catch(e){if(e&&typeof e==`object`&&`code`in e&&e.code===`ELOCKED`){let e=``;try{let t=Ph(c);t.locked&&t.pid&&(e=` (PID: ${t.pid})`)}catch{}console.error(mf.red(`\nError: Another ${mf.bold(`blink dev`)} process is already running in this directory${e}.`)),console.error(mf.red(`Please stop the other process and try again.
|
|
141
|
+
`),m(),i()};return{start:v,stop:y,message:(e=``)=>{s=g(e??s)}}},Sm=async(e,t)=>{let n={},r=Object.keys(e);for(let i of r){let r=e[i],a=await r({results:n})?.catch(e=>{throw e});if(typeof t?.onCancel==`function`&&np(a)){n[i]=`canceled`,t.onCancel({results:n});continue}n[i]=a}return n},Cm=async e=>{for(let t of e){if(t.enabled===!1)continue;let e=xm();e.start(t.title);let n=await t.task(e.message);e.stop(n||t.title)}};let wm;function Tm(){try{return o.default.statSync(`/.dockerenv`),!0}catch{return!1}}function Em(){try{return o.default.readFileSync(`/proc/self/cgroup`,`utf8`).includes(`docker`)}catch{return!1}}function Dm(){return wm===void 0&&(wm=Tm()||Em()),wm}let Om;const km=()=>{try{return o.default.statSync(`/run/.containerenv`),!0}catch{return!1}};function Am(){return Om===void 0&&(Om=km()||Dm()),Om}const jm=()=>{if(x.default.platform!==`linux`)return!1;if(S.default.release().toLowerCase().includes(`microsoft`))return!Am();try{return o.default.readFileSync(`/proc/version`,`utf8`).toLowerCase().includes(`microsoft`)?!Am():!1}catch{return!1}};var Mm=x.default.env.__IS_WSL_TEST__?jm:jm();const Nm=(()=>{let e=`/mnt/`,t;return async function(){if(t)return t;let n=`/etc/wsl.conf`,r=!1;try{await E.default.access(n,E.constants.F_OK),r=!0}catch{}if(!r)return e;let i=await E.default.readFile(n,{encoding:`utf8`}),a=/(?<!#.*)root\s*=\s*(?<mountPoint>.*)/g.exec(i);return a?(t=a.groups.mountPoint.trim(),t=t.endsWith(`/`)?t:`${t}/`,t):e}})(),Pm=async()=>`${await Nm()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,Fm=async()=>Mm?Pm():`${x.default.env.SYSTEMROOT||x.default.env.windir||String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;function Im(e,t,n){let r=n=>Object.defineProperty(e,t,{value:n,enumerable:!0,writable:!0});return Object.defineProperty(e,t,{configurable:!0,enumerable:!0,get(){let e=n();return r(e),e},set(e){r(e)}}),e}const Lm=(0,l.promisify)(T.execFile);async function Rm(){if(x.default.platform!==`darwin`)throw Error(`macOS only`);let{stdout:e}=await Lm(`defaults`,[`read`,`com.apple.LaunchServices/com.apple.launchservices.secure`,`LSHandlers`]);return/LSHandlerRoleAll = "(?!-)(?<id>[^"]+?)";\s+?LSHandlerURLScheme = (?:http|https);/.exec(e)?.groups.id??`com.apple.Safari`}const zm=(0,l.promisify)(T.execFile);async function Bm(e,{humanReadableOutput:t=!0,signal:n}={}){if(x.default.platform!==`darwin`)throw Error(`macOS only`);let r=t?[]:[`-ss`],i={};n&&(i.signal=n);let{stdout:a}=await zm(`osascript`,[`-e`,e,r],i);return a.trim()}async function Vm(e){return Bm(`tell application "Finder" to set app_path to application file id "${e}" as string\ntell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`)}const Hm=(0,l.promisify)(T.execFile),Um={AppXq0fevzme2pys62n3e0fbqa7peapykr8v:{name:`Edge`,id:`com.microsoft.edge.old`},MSEdgeDHTML:{name:`Edge`,id:`com.microsoft.edge`},MSEdgeHTM:{name:`Edge`,id:`com.microsoft.edge`},"IE.HTTP":{name:`Internet Explorer`,id:`com.microsoft.ie`},FirefoxURL:{name:`Firefox`,id:`org.mozilla.firefox`},ChromeHTML:{name:`Chrome`,id:`com.google.chrome`},BraveHTML:{name:`Brave`,id:`com.brave.Browser`},BraveBHTML:{name:`Brave Beta`,id:`com.brave.Browser.beta`},BraveSSHTM:{name:`Brave Nightly`,id:`com.brave.Browser.nightly`}};var Wm=class extends Error{};async function Gm(e=Hm){let{stdout:t}=await e(`reg`,[`QUERY`,` HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice`,`/v`,`ProgId`]),n=/ProgId\s*REG_SZ\s*(?<id>\S+)/.exec(t);if(!n)throw new Wm(`Cannot find Windows browser in stdout: ${JSON.stringify(t)}`);let{id:r}=n.groups,i=Um[r];if(!i)throw new Wm(`Unknown browser ID: ${r}`);return i}const Km=(0,l.promisify)(T.execFile),qm=e=>e.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,e=>e.toUpperCase());async function Jm(){if(x.default.platform===`darwin`){let e=await Rm();return{name:await Vm(e),id:e}}if(x.default.platform===`linux`){let{stdout:e}=await Km(`xdg-mime`,[`query`,`default`,`x-scheme-handler/http`]),t=e.trim();return{name:qm(t.replace(/.desktop$/,``).replace(`-`,` `)),id:t}}if(x.default.platform===`win32`)return Gm();throw Error(`Only macOS, Linux, and Windows are supported`)}const Ym=(0,l.promisify)(T.default.execFile),Xm=b.default.dirname((0,s.fileURLToPath)(require(`url`).pathToFileURL(__filename).href)),Zm=b.default.join(Xm,`xdg-open`),{platform:Qm,arch:$m}=x.default;async function eh(){let e=await Fm(),t=String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`,n=a.Buffer.from(t,`utf16le`).toString(`base64`),{stdout:r}=await Ym(e,[`-NoProfile`,`-NonInteractive`,`-ExecutionPolicy`,`Bypass`,`-EncodedCommand`,n],{encoding:`utf8`}),i=r.trim(),o={ChromeHTML:`com.google.chrome`,BraveHTML:`com.brave.Browser`,MSEdgeHTM:`com.microsoft.edge`,FirefoxURL:`org.mozilla.firefox`};return o[i]?{id:o[i]}:{}}const th=async(e,t)=>{let n;for(let r of e)try{return await t(r)}catch(e){n=e}throw n},nh=async e=>{if(e={wait:!1,background:!1,newInstance:!1,allowNonzeroExitCode:!1,...e},Array.isArray(e.app))return th(e.app,t=>nh({...e,app:t}));let{name:t,arguments:n=[]}=e.app??{};if(n=[...n],Array.isArray(t))return th(t,t=>nh({...e,app:{name:t,arguments:n}}));if(t===`browser`||t===`browserPrivate`){let r={"com.google.chrome":`chrome`,"google-chrome.desktop":`chrome`,"com.brave.Browser":`brave`,"org.mozilla.firefox":`firefox`,"firefox.desktop":`firefox`,"com.microsoft.msedge":`edge`,"com.microsoft.edge":`edge`,"com.microsoft.edgemac":`edge`,"microsoft-edge.desktop":`edge`},i={chrome:`--incognito`,brave:`--incognito`,firefox:`--private-window`,edge:`--inPrivate`},a=Mm?await eh():await Jm();if(a.id in r){let o=r[a.id];return t===`browserPrivate`&&n.push(i[o]),nh({...e,app:{name:oh[o],arguments:n}})}throw Error(`${a.name} is not supported as a default browser`)}let r,i=[],o={};if(Qm===`darwin`)r=`open`,e.wait&&i.push(`--wait-apps`),e.background&&i.push(`--background`),e.newInstance&&i.push(`--new`),t&&i.push(`-a`,t);else if(Qm===`win32`||Mm&&!Am()&&!t){r=await Fm(),i.push(`-NoProfile`,`-NonInteractive`,`-ExecutionPolicy`,`Bypass`,`-EncodedCommand`),Mm||(o.windowsVerbatimArguments=!0);let s=[`Start`];e.wait&&s.push(`-Wait`),t?(s.push(`"\`"${t}\`""`),e.target&&n.push(e.target)):e.target&&s.push(`"${e.target}"`),n.length>0&&(n=n.map(e=>`"\`"${e}\`""`),s.push(`-ArgumentList`,n.join(`,`))),e.target=a.Buffer.from(s.join(` `),`utf16le`).toString(`base64`)}else{if(t)r=t;else{let e=!Xm||Xm===`/`,t=!1;try{await E.default.access(Zm,E.constants.X_OK),t=!0}catch{}r=x.default.versions.electron??(Qm===`android`||e||!t)?`xdg-open`:Zm}n.length>0&&i.push(...n),e.wait||(o.stdio=`ignore`,o.detached=!0)}Qm===`darwin`&&n.length>0&&i.push(`--args`,...n),e.target&&i.push(e.target);let s=T.default.spawn(r,i,o);return e.wait?new Promise((t,n)=>{s.once(`error`,n),s.once(`close`,r=>{if(!e.allowNonzeroExitCode&&r>0){n(Error(`Exited with code ${r}`));return}t(s)})}):(s.unref(),s)},rh=(e,t)=>{if(typeof e!=`string`)throw TypeError("Expected a `target`");return nh({...t,target:e})};function ih(e){if(typeof e==`string`||Array.isArray(e))return e;let{[$m]:t}=e;if(!t)throw Error(`${$m} is not supported`);return t}function ah({[Qm]:e},{wsl:t}){if(t&&Mm)return ih(t);if(!e)throw Error(`${Qm} is not supported`);return ih(e)}const oh={};Im(oh,`chrome`,()=>ah({darwin:`google chrome`,win32:`chrome`,linux:[`google-chrome`,`google-chrome-stable`,`chromium`]},{wsl:{ia32:`/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe`,x64:[`/mnt/c/Program Files/Google/Chrome/Application/chrome.exe`,`/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe`]}})),Im(oh,`brave`,()=>ah({darwin:`brave browser`,win32:`brave`,linux:[`brave-browser`,`brave`]},{wsl:{ia32:`/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe`,x64:[`/mnt/c/Program Files/BraveSoftware/Brave-Browser/Application/brave.exe`,`/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe`]}})),Im(oh,`firefox`,()=>ah({darwin:`firefox`,win32:String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,linux:`firefox`},{wsl:`/mnt/c/Program Files/Mozilla Firefox/firefox.exe`})),Im(oh,`edge`,()=>ah({darwin:`microsoft edge`,win32:`msedge`,linux:[`microsoft-edge`,`microsoft-edge-dev`]},{wsl:`/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe`})),Im(oh,`browser`,()=>`browser`),Im(oh,`browserPrivate`,()=>`browserPrivate`);var sh=rh;async function ch(e,t=void 0){try{(await sh(e)).once(`error`,n=>{console.log(mf.yellow(t??`Could not open the browser. Please visit the URL manually: ${e}`))})}catch{console.log(mf.yellow(t??`Could not open the browser. Please visit the URL manually: ${e}`))}}function lh(e){let t=e||fh();if((0,o.existsSync)(t)){let e=(0,o.readFileSync)(t,`utf8`);return JSON.parse(e).token}}function uh(e,t){let n=t||fh();(0,o.existsSync)((0,b.dirname)(n))||(0,o.mkdirSync)((0,b.dirname)(n),{recursive:!0}),(0,o.writeFileSync)(n,JSON.stringify({_:`This is your Blink credentials file. DO NOT SHARE THIS FILE WITH ANYONE!`,token:e}))}function dh(e){let t=e||fh();(0,o.existsSync)(t)&&(0,o.unlinkSync)(t)}function fh(){let e=Dd(`blink`).dataDirs();if(e.length===0)throw Error(`No suitable data directory for Blink storage found!`);return(0,b.join)(e[0],`auth.json`)}function ph(e={}){let{autoCheck:t=!0,onAuthChange:n,onLoginUrl:r,testAuthPath:i}=e,[a,o]=(0,_.useState)(),[s,c]=(0,_.useState)(()=>lh(i)),[l,u]=(0,_.useState)(),d=(0,_.useRef)(n),f=(0,_.useRef)(r);(0,_.useEffect)(()=>{d.current=n,f.current=r},[n,r]);let p=(0,_.useCallback)(async()=>{u(void 0);try{let e=lh(i);if(c(e),!e){o(void 0),d.current?.(void 0);return}let t=new sd({baseURL:`https://blink.so`});t.authToken=e;let n={email:(await t.users.me()).email};o(n),d.current?.(n)}catch(e){o(void 0),u(e instanceof Error?e.message:String(e)),d.current?.(void 0)}},[i]),m=(0,_.useCallback)(async()=>{u(void 0);try{let e=new sd,t=await e.auth.token((e,t)=>{f.current?.(e,t)});e.authToken=t;let n=await e.users.me();uh(t,i),c(t);let r={email:n.email};return o(r),d.current?.(r),r}catch(e){let t=e instanceof Error?e.message:String(e);throw u(t),e}},[i]),h=(0,_.useCallback)(()=>{dh(i),c(void 0),o(void 0),u(void 0),d.current?.(void 0)},[i]);return(0,_.useEffect)(()=>{t&&p()},[t,p]),{user:a,token:s,error:l,login:m,logout:h}}function mh(e){let{directory:t,onBuildStart:r,onBuildSuccess:i,onBuildError:a}=typeof e==`string`?{directory:e}:e,o=(0,_.useMemo)(()=>n.resolveConfig(t),[t]),[s,c]=(0,_.useState)(void 0),[l,u]=(0,_.useState)(void 0),[d,f]=(0,_.useState)(`building`),p=(0,_.useRef)(r),m=(0,_.useRef)(i),h=(0,_.useRef)(a);return(0,_.useEffect)(()=>{p.current=r,m.current=i,h.current=a},[r,i,a]),(0,_.useEffect)(()=>{let e=new AbortController;return o.build({cwd:t,entry:o.entry,outdir:o.outdir,watch:!0,dev:!0,signal:e.signal,onStart:()=>{f(`building`),c(void 0),u(void 0),p.current?.()},onResult:e=>{`error`in e?(c(e.error),f(`error`),h.current?.(e.error)):(u(e),f(`success`),m.current?.(e))}}).catch(e=>{console.log(`error`,e),f(`error`),c(e),h.current?.(e)}),()=>{e.abort()}},[t]),(0,_.useMemo)(()=>({error:s,status:d,result:l,entry:o.entry,outdir:o.outdir}),[s,d,l,o.entry,o.outdir])}function hh(){return/[<>:"/\\|?*\u0000-\u001F]|[. ]$/g}function gh(){return/^(con|prn|aux|nul|com\d|lpt\d)$/i}const _h=100,vh=/^\.+(\\|\/)|^\.+$/,yh=/[. ]+$/,bh=/[\p{Control}\p{Format}\p{Zl}\p{Zp}\uFFF0-\uFFFF]/gu,xh=/[\p{Control}\p{Format}\p{Zl}\p{Zp}\uFFF0-\uFFFF]/u,Sh=e=>e===``,Ch=/([<>:"/\\|?*\u0000-\u001F]){2,}/g,wh=/[\t\n\r\u00A0\u1680\u2000-\u200A\u202F\u205F\u3000]+/g;let Th;function Eh(){return Th??=new Intl.Segmenter(void 0,{granularity:`grapheme`}),Th}function Dh(e,t={}){if(typeof e!=`string`)throw TypeError(`Expected a string`);let n=t.replacement??`!`;if(hh().test(n)||[...n].some(e=>xh.test(e)&&!Sh(e)))throw Error(`Replacement string cannot contain reserved filename characters`);e=e.normalize(`NFC`),e=e.replaceAll(wh,` `),n.length>0&&(e=e.replaceAll(Ch,`$1`)),e=e.replace(yh,``),e=e.replace(vh,n),e=e.replace(hh(),n),e=e.replaceAll(bh,e=>Sh(e)?e:n),e.length===0&&(e=n),e=gh().test(e)?e+n:e;let r=typeof t.maxLength==`number`?t.maxLength:100;if(e.length>r){let t=e.lastIndexOf(`.`);if(t===-1)e=Oh(e,r);else{let n=e.slice(0,t),i=e.slice(t),a=Math.max(0,r-i.length);e=Oh(n,a)+i}}return e}function Oh(e,t){if(e.length<=t)return e;let n=0,r=``;for(let{segment:i}of Eh().segment(e)){let e=n+i.length;if(e>t)break;r+=i,n=e}return r}function kh(e){return`${e}.lock`}function Ah(e){try{return process.kill(e,0),!0}catch(e){return e.code===`EPERM`}}function jh(e,t={}){let n=kh(e),r=process.pid.toString();try{return o.writeFileSync(n,r,{flag:`wx`}),!0}catch(r){if(r.code!==`EEXIST`)throw r;if(t.stale===0)return!1;let i;try{i=parseInt(o.readFileSync(n,`utf8`),10)}catch{return o.unlinkSync(n),jh(e,{...t,stale:0})}if(!Ah(i))try{return o.unlinkSync(n),jh(e,{...t,stale:0})}catch(n){if(n.code===`ENOENT`)return jh(e,{...t,stale:0});throw n}return!1}}async function Mh(e,t={}){let n={stale:!0,retries:0,retryInterval:100,...t},r=b.resolve(e),i=0;for(;i<=n.retries;){if(jh(r,n))return()=>Nh(r);i<n.retries&&await new Promise(e=>setTimeout(e,n.retryInterval)),i++}let a=Error(`Lock file is already being held`);throw a.code=`ELOCKED`,a.file=r,a}function Nh(e){let t=b.resolve(e),n=kh(t);try{if(parseInt(o.readFileSync(n,`utf8`),10)!==process.pid){let e=Error(`Lock is not owned by this process`);throw e.code=`ENOTACQUIRED`,e}o.unlinkSync(n)}catch(e){if(e.code===`ENOENT`){let e=Error(`Lock is not acquired`);throw e.code=`ENOTACQUIRED`,e}throw e}}function Ph(e){let t=b.resolve(e),n=kh(t);try{if(!o.existsSync(n))return{locked:!1};let e=o.readFileSync(n,`utf8`),t=parseInt(e,10);return Ah(t)?{locked:!0,pid:t}:{locked:!1}}catch(e){return e.code,{locked:!1}}}const Fh=e=>{o.mkdirSync(e,{recursive:!0})},Ih=e=>{try{o.fdatasyncSync(e)}catch{}try{o.closeSync(e)}catch{}},Lh=e=>{try{let t=o.openSync(e,`r`);try{o.fsyncSync(t)}finally{o.closeSync(t)}}catch{}},Rh=(e,t)=>{let n=b.dirname(e);Fh(n);let r=b.join(n,`.tmp-`+process.pid+`-`+Math.random().toString(36).slice(2)),i;try{i=o.openSync(r,`w`),o.writeFileSync(i,t,`utf-8`),Ih(i),i=void 0,o.renameSync(r,e),Lh(e),Lh(n)}catch(e){if(i!==void 0)try{o.closeSync(i)}catch{}try{o.rmSync(r,{force:!0})}catch{}throw e}},zh=(e,t)=>{let n=new Map,r,i=e=>{if(o.statSync(e,{throwIfNoEntry:!1}))return JSON.parse(o.readFileSync(e,`utf-8`))},a=(e,t)=>{Rh(e,JSON.stringify(t,null,2))},s=async()=>{if(r)throw Error(`Index is already locked`);let t=b.join(e,`index.json`);Fh(e),o.existsSync(t)||o.writeFileSync(t,JSON.stringify({ids:{}}),`utf-8`);let n=await Mh(t,{stale:!0,retries:5,retryInterval:100});return r=()=>Promise.resolve(n()),()=>{n(),r=void 0}},c=async()=>{let t=b.join(e,`index.json`),n=i(t)??{ids:{}};return n.ids||={},n},l=async t=>{let n=b.join(e,`index.json`);a(n,t)},u=async t=>{let n=(await c()).ids[t];if(n)return b.join(e,n)},d=async t=>{let n=(await c()).ids[t];if(!n)return;let r=b.join(e,n);if(o.statSync(r,{throwIfNoEntry:!1}))return JSON.parse(o.readFileSync(r,`utf-8`))},f=async n=>{let r=n[t],i=String(r),o=Dh(i,{replacement:`_`})+`.json`,u=await s();try{let t=await c();t.ids[i]=o,t.current=i;let r=b.join(e,o);a(r,n),await l(t)}finally{await u()}};return{async get(e){return await d(e)},async list(){if(!o.statSync(e,{throwIfNoEntry:!1}))return[];let t=await c(),n=[];for(let[r,i]of Object.entries(t.ids)){let t=b.join(e,i),a=o.statSync(t,{throwIfNoEntry:!1});if(!a)continue;let s=Ph(t);n.push({key:r,locked:s.locked,pid:s.pid,mtime:a.mtimeMs})}return n.sort((e,t)=>t.mtime-e.mtime),n},async lock(r,i){if(n.has(r))throw Error(`Key "${r}" is already locked in this process`);let a=await u(r);if(!a){let t=Dh(r,{replacement:`_`})+`.json`,n=await s();try{let n=await c();n.ids[r]=t;let i=b.join(e,t);Fh(e),o.writeFileSync(i,JSON.stringify({}),`utf-8`),await l(n),a=i}finally{await n()}}if(i?.force){let e=Ph(a);if(e.locked&&e.pid&&e.pid!==process.pid)try{process.kill(e.pid,`SIGTERM`),await new Promise(e=>setTimeout(e,100))}catch(t){t.code!==`ESRCH`&&console.warn(`Failed to kill process ${e.pid}:`,t.message)}}let p=await Mh(a,{stale:!0,retries:i?.force?10:5,retryInterval:(i?.force,100)});return n.set(r,()=>Promise.resolve(p())),{async get(){let e=await d(r);if(!e)throw Error(`Key ${r} not found`);return e},async set(e){await f(e)},async update(e){let n=await d(r);if(!n||!(t in n))throw Error(`Key ${r} not found`);await f({...n,...e})},async delete(){let t=await s();try{let t=await c(),n=t.ids[r];if(n){delete t.ids[r],t.current===r&&(t.current=void 0),await l(t);let i=b.join(e,n);try{o.rmSync(i,{force:!0}),Lh(e)}catch{}}}finally{await t()}},async release(){try{p()}finally{n.delete(r)}}}},dispose(){n.clear()}}},Bh=(e,t)=>{let n=t?.pollInterval??200,r=t?.debounce??50,i=new Set,a,s,c=new Map,l=new Map,u=b.join(e,`index.json`),d=()=>{try{if(!o.statSync(u,{throwIfNoEntry:!1}))return{ids:{}};let e=o.readFileSync(u,`utf-8`);return{ids:JSON.parse(e).ids??{}}}catch{return{ids:{}}}},f=(e,t,n,r)=>{for(let a of i)try{a({key:e,value:t,locked:n,pid:r})}catch(e){console.error(`Error in onChange callback:`,e)}},p=(t,n,r=!1)=>{let i=b.join(e,n);try{let e=o.statSync(i,{throwIfNoEntry:!1}),a=l.get(n);if(!e){a&&(l.delete(n),f(t,void 0,!1));return}let s=e.mtimeMs,c=a?{locked:a.locked,pid:a.pid}:{locked:!1,pid:void 0};if((r||!a)&&(c=Ph(i)),!a||a.mtime!==s||a.locked!==c.locked||a.pid!==c.pid){let e;e=!a||a.mtime!==s?JSON.parse(o.readFileSync(i,`utf-8`)):a.cachedValue,l.set(n,{mtime:s,key:t,locked:c.locked,pid:c.pid,cachedValue:e}),f(t,e,c.locked,c.pid)}}catch{}},m=()=>{try{let e=d(),t=new Set(Object.keys(e.ids));for(let[t,n]of Object.entries(e.ids))p(t,n,!0);for(let[e,n]of l.entries())t.has(n.key)||(l.delete(e),f(n.key,void 0,!1))}catch{}},h=(e,t,n=!1)=>{let i=c.get(e);i&&clearTimeout(i),c.set(e,setTimeout(()=>{c.delete(e),p(e,t,n)},r))},g=()=>{if(a)return;try{o.mkdirSync(e,{recursive:!0})}catch{}a=o.watch(e,(e,t)=>{if(!t||t.startsWith(`.tmp-`))return;if(t===`index.json`){m();return}if(t.endsWith(`.lock`)){let e=t.replace(`.lock`,``),n=d(),r=Object.keys(n.ids).find(t=>n.ids[t]===e);r&&p(r,e,!0);return}let n=d(),r=Object.keys(n.ids).find(e=>n.ids[e]===t);r&&h(r,t,!1)});let t=()=>{m(),s=setTimeout(t,n)};m(),s=setTimeout(t,n)};return{onChange(e){return i.size===0&&g(),i.add(e),()=>{if(i.delete(e),i.size===0){a&&=(a.close(),void 0),s&&=(clearTimeout(s),void 0);for(let e of c.values())clearTimeout(e);c.clear(),l.clear()}}},dispose(){a&&=(a.close(),void 0),s&&=(clearTimeout(s),void 0);for(let e of c.values())clearTimeout(e);c.clear(),i.clear(),l.clear()}}};async function Vh({id:e,agent:t,messages:n,signal:r,shouldContinueStreaming:i=Hh}){n=[...n];let a=new TransformStream,o=a.writable.getWriter(),s=async()=>{let a;try{let c=await t.chat({messages:n,id:e},{signal:r}),l=(0,m.readUIMessageStream)({message:{id:crypto.randomUUID(),role:`assistant`,parts:[],metadata:{}},stream:c,onError:e=>{e instanceof Error&&e.name===`AbortError`||o.abort(e)}});for await(let e of l)o.write(e),a=e;if(a&&i(a)){n.push(a),await s();return}await o.close()}catch(e){if(e?.name===`AbortError`||r?.aborted)return;await o.abort(e)}finally{await o.close()}};return s().catch(e=>{o.abort(e)}),a.readable}const Hh=e=>{if(e.role!==`assistant`)return!1;let n=e.parts.reduce((e,t,n)=>t.type===`step-start`?n:e,-1),r=e.parts.slice(n+1).filter(m.isToolOrDynamicToolUIPart);return r.length===0||r.some(e=>t.isToolApprovalOutput(e.output)&&e.output.outcome===`pending`)?!1:r.every(e=>e.state.startsWith(`output-`))},Uh=(e,t,n=crypto.randomUUID())=>({created_at:new Date().toISOString(),...e,id:n,metadata:e.metadata,mode:t});function Wh(e){return typeof e==`object`&&e?.__blink_internal!==void 0}var Gh=class{chatId;agent;chatStore;serializeMessage;filterMessages;onError;chat;loading=!1;streamingMessage;status=`idle`;queue=[];abortController;isProcessingQueue=!1;listeners=new Set;watcher;disposed=!1;constructor(e){this.chatId=e.chatId??`00000000-0000-0000-0000-000000000000`,this.chat={id:this.chatId,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[]},this.loading=!0,this.chatStore=zh(e.chatsDirectory,`id`),this.serializeMessage=e.serializeMessage,this.filterMessages=e.filterMessages,this.onError=e.onError,this.watcher=Bh(e.chatsDirectory,{pollInterval:1e3,debounce:50}),this.watcher.onChange(e=>{if(e.key!==this.chatId||this.isProcessingQueue)return;if(!e.value){this.chat={id:this.chatId,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[]},this.status=`idle`,this.streamingMessage=void 0,this.notifyListeners();return}if(this.chat.updated_at===e.value?.updated_at)return;let t=e.value,n=e.locked?`streaming`:`idle`,r=this.chat.updated_at!==t?.updated_at||this.status!==n;this.chat=t,this.streamingMessage=void 0,this.status=n,r&&this.notifyListeners()}),this.chatStore.get(this.chatId).then(e=>{this.disposed||e&&(this.chat=e)}).catch(e=>{let t=e instanceof Error?e.message:String(e);this.onError?.(t)}).finally(()=>{this.loading=!1,this.notifyListeners()})}setAgent(e){this.agent=e}getState(){return{id:this.chatId,key:this.chat?.key,messages:(this.chat?.messages??[]).filter(e=>!Wh(e.metadata)),created_at:this.chat?.created_at,updated_at:this.chat?.updated_at,status:this.status,streamingMessage:this.streamingMessage,loading:this.loading,queuedMessages:this.queue}}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}async upsertMessages(e,t){let n=!1,r;t?r=t:(r=await this.chatStore.lock(this.chatId),n=!0);try{let t=await r.get();(!t.id||!Array.isArray(t.messages))&&(t={id:this.chatId,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[]});let n=[...t.messages];for(let t of e){let e;if(this.serializeMessage){let n=this.serializeMessage(t);if(n===void 0)return;e=n}else e={...t,created_at:new Date().toISOString(),mode:`run`,metadata:t.metadata,id:t.id??crypto.randomUUID()};let r=n.findIndex(t=>t.id===e.id);r===-1?n.push(e):n.splice(r,1,e)}this.chat={...t,updated_at:new Date().toISOString(),messages:n},await r.set(this.chat),this.notifyListeners()}finally{n&&await r.release()}}async deleteMessages(e){let t;try{t=await this.chatStore.lock(this.chatId);let n=await t.get();this.chat.messages=n.messages.filter(t=>!e.includes(t.id)),this.chat.updated_at=new Date().toISOString(),await t.set(this.chat),this.notifyListeners()}finally{t&&await t.release()}}async sendMessages(e){if(this.status=`idle`,this.notifyListeners(),this.isProcessingQueue){this.queue.push(...e),this.notifyListeners();return}this.queue=e,this.processQueueOrRun()}async start(){this.status=`idle`,this.notifyListeners(),this.processQueueOrRun()}async stop(){this.status=`idle`,this.abortController?.abort(),this.notifyListeners()}async processQueueOrRun(){if(!this.agent){this.onError?.(`The agent is not available. Please wait for the build to succeed.`),this.queue=[];return}if(this.isProcessingQueue)return;this.isProcessingQueue=!0;let e;try{e=await this.chatStore.lock(this.chatId);let t=!0;for(;this.queue.length>0||t;){t=!1;let n=new AbortController;this.abortController=n;let r=[...this.queue];this.queue=[],this.streamingMessage=void 0,this.status=`streaming`,this.notifyListeners(),r.length>0&&await this.upsertMessages(r,e);let i=this.chat.messages;this.filterMessages&&(i=i.filter(this.filterMessages)),i=i.map(e=>({...e,parts:e.parts.map(e=>!(0,m.isToolOrDynamicToolUIPart)(e)||e.input!==``?e:{...e,input:{}})}));let a=performance.now(),o=await Vh({agent:this.agent,id:this.chatId,signal:n.signal,messages:i}),s=async t=>{let n=t;if(this.serializeMessage){let e=this.serializeMessage(t);if(e===void 0)return;n=e}this.chat.updated_at=new Date().toISOString(),this.chat.messages.push(n),this.streamingMessage=void 0,await e?.set(this.chat)},c=o.getReader();n.signal.addEventListener(`abort`,()=>{c.cancel().catch(()=>{})},{once:!0});let l;try{for(;;){let{done:e,value:t}=await c.read();if(e||n.signal.aborted)break;l||=performance.now()-a,this.streamingMessage&&t.id!==this.streamingMessage.id&&await s(this.streamingMessage);let r={...t,metadata:{...typeof t.metadata==`object`&&t.metadata!==null?t.metadata:{},ttft:l}};this.streamingMessage=this.serializeMessage?this.serializeMessage(r):r,this.notifyListeners()}}finally{c.releaseLock()}this.streamingMessage&&await s(this.streamingMessage)}}catch(e){let t=e instanceof Error?e.message:String(e);this.onError?.(t)}finally{this.isProcessingQueue=!1,this.streamingMessage=void 0,this.status=`idle`,e&&(this.chat.updated_at=new Date().toISOString(),await e.set(this.chat),await e.release(),this.notifyListeners())}}stopStreaming(){this.abortController?.abort()}clearQueue(){this.queue=[],this.notifyListeners()}async resetChat(){this.abortController?.abort(),this.resetChatState(),this.notifyListeners();let e;try{e=await this.chatStore.lock(this.chatId),await e.delete()}catch{}finally{if(e)try{await e.release()}catch{}}}dispose(){this.disposed=!0,this.watcher.dispose(),this.listeners.clear(),this.abortController?.abort()}resetChatState(){this.chat={id:this.chatId,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[]},this.streamingMessage=void 0,this.status=`idle`,this.queue=[]}notifyListeners(){let e=this.getState();for(let t of this.listeners)t(e)}};function Kh(e){let{chatId:t,agent:n,chatsDirectory:r,serializeMessage:i,filterMessages:a,onError:o}=e,s=(0,_.useRef)(null),[c,l]=(0,_.useState)({id:t,messages:[],status:`idle`,loading:!0,queuedMessages:[]});(0,_.useEffect)(()=>{s.current&&s.current.dispose();let e=new Gh({chatId:t,chatsDirectory:r,serializeMessage:i,filterMessages:a,onError:o}),n=e.subscribe(e=>{l(e)});return l(e.getState()),s.current=e,()=>{n(),e.dispose(),s.current=null}},[t,r]),(0,_.useEffect)(()=>{s.current&&s.current.setAgent(n)},[n]);let u=(0,_.useCallback)(async e=>{s.current&&await s.current.sendMessages([e])},[]),d=(0,_.useCallback)(async e=>{s.current&&await s.current.upsertMessages([e])},[]),f=(0,_.useCallback)(()=>{s.current&&s.current.stopStreaming()},[]),p=(0,_.useCallback)(async()=>{s.current&&await s.current.resetChat()},[]),m=(0,_.useCallback)(()=>{s.current&&s.current.clearQueue()},[]),h=(0,_.useCallback)(async e=>{s.current&&await s.current.deleteMessages([e])},[]),g=(0,_.useCallback)(async()=>{s.current&&await s.current.start()},[]);return{...c,sendMessage:u,upsertMessage:d,stopStreaming:f,resetChat:p,clearQueue:m,deleteMessage:h,start:g}}function qh(e){return(0,f.join)(e,`.blink`,`devhook.txt`)}function Jh(e){return(0,p.existsSync)(qh(e))}function Yh(e){let t=qh(e);if((0,p.existsSync)(t))return(0,p.readFileSync)(t,`utf-8`).trim()}function Xh(e){let t=qh(e);if((0,p.mkdirSync)((0,f.dirname)(t),{recursive:!0}),(0,p.existsSync)(t))return(0,p.readFileSync)(t,`utf-8`);let n=crypto.randomUUID();return(0,p.writeFileSync)(t,n),n}const Zh=(e,t)=>e.json({error:t},400),Qh=e=>{let t=e.req.param(`key`);return!t||t===``?{key:t,err:`Key is required`}:t.length>475?{key:t,err:`Key is too long. Max length is 475 characters.`}:{key:t}},$h=()=>new t.Hono,eg=$h().get(`/:key`,async e=>{let{key:t,err:n}=Qh(e);if(n)return Zh(e,n);let r=await e.env.store.get(t);return e.json({value:r},200)}).post(`/:key`,t.validator(`json`,(e,t)=>{let n=e.value;return n?typeof n==`string`?n.length>2e4?Zh(t,`Value is too long. Max length is 20,000 characters.`):{value:n}:Zh(t,`Value must be a string`):Zh(t,`Value is required`)}),async e=>{let{key:t,err:n}=Qh(e);if(n)return Zh(e,n);let{value:r}=e.req.valid(`json`);return await e.env.store.set(t,r),e.body(null,204)}).delete(`/:key`,async e=>{let{key:t,err:n}=Qh(e);return n?Zh(e,n):(await e.env.store.delete(t),e.body(null,204))}).get(`/`,async e=>{let{cursor:t,limit:n,prefix:r}=e.req.query(),{entries:i,cursor:a}=await e.env.store.list(r,{cursor:t?String(t):void 0,limit:n?Number(n):100});return e.json({entries:i,cursor:a})}),tg=e=>{let t=e.req.param(`key`);return t?t.length>475?{key:t,err:`Key is too long. Max length is 475 characters.`}:{key:t}:{key:t,err:`Key is required`}},ng=t.validator(`param`,e=>({id:e.id})),rg=$h().post(`/:key`,async e=>{let{key:t,err:n}=tg(e);return n?Zh(e,n):e.json(await e.env.chat.upsert(t),200)}).get(`/:id`,ng,async e=>{let{id:t}=e.req.valid(`param`);return e.json(await e.env.chat.get(t),200)}).get(`/:id/messages`,ng,async e=>{let{id:t}=e.req.valid(`param`);return e.json(await e.env.chat.getMessages(t),200)}).post(`/:id/sendMessages`,t.validator(`json`,e=>({id:e.id,messages:e.messages,options:e.options})),async e=>{let{id:t,messages:n,options:r}=e.req.valid(`json`);return t?(await e.env.chat.sendMessages(t,n,r),e.body(null,204)):Zh(e,`ID is required`)}).delete(`/:id/messages`,ng,t.validator(`query`,e=>(typeof e.message==`string`&&(e.message=[e.message]),{messages:e.message})),async e=>{let{id:t}=e.req.valid(`param`),{messages:n}=e.req.valid(`query`);return await e.env.chat.deleteMessages(t,n),e.body(null,204)}).post(`/:id/start`,ng,async e=>{let{id:t}=e.req.valid(`param`);return await e.env.chat.start(t),e.body(null,204)}).post(`/:id/stop`,ng,async e=>{let{id:t}=e.req.valid(`param`);return await e.env.chat.stop(t),e.body(null,204)}).delete(`/:id`,ng,async e=>{let{id:t}=e.req.valid(`param`);return await e.env.chat.delete(t),e.body(null,204)}),ig=$h().post(`/v1/traces`,async e=>e.env.otlp?e.env.otlp.traces(e.req.raw):e.body(null,204)),ag=new t.Hono().onError((e,t)=>t.json({error:e instanceof Error?e.message:`Unknown error`},500)).route(`/kv`,eg).route(`/chat`,rg).route(`/otlp`,ig);var og=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;function sg(e){return typeof e==`string`&&og.test(e)}var cg=sg;function lg(e){if(!cg(e))throw TypeError(`Invalid UUID`);let t;return Uint8Array.of((t=parseInt(e.slice(0,8),16))>>>24,t>>>16&255,t>>>8&255,t&255,(t=parseInt(e.slice(9,13),16))>>>8,t&255,(t=parseInt(e.slice(14,18),16))>>>8,t&255,(t=parseInt(e.slice(19,23),16))>>>8,t&255,(t=parseInt(e.slice(24,36),16))/1099511627776&255,t/4294967296&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255)}var ug=lg;const $=[];for(let e=0;e<256;++e)$.push((e+256).toString(16).slice(1));function dg(e,t=0){return($[e[t+0]]+$[e[t+1]]+$[e[t+2]]+$[e[t+3]]+`-`+$[e[t+4]]+$[e[t+5]]+`-`+$[e[t+6]]+$[e[t+7]]+`-`+$[e[t+8]]+$[e[t+9]]+`-`+$[e[t+10]]+$[e[t+11]]+$[e[t+12]]+$[e[t+13]]+$[e[t+14]]+$[e[t+15]]).toLowerCase()}function fg(e){e=unescape(encodeURIComponent(e));let t=new Uint8Array(e.length);for(let n=0;n<e.length;++n)t[n]=e.charCodeAt(n);return t}const pg=`6ba7b810-9dad-11d1-80b4-00c04fd430c8`,mg=`6ba7b811-9dad-11d1-80b4-00c04fd430c8`;function hg(e,t,n,r,i,a){let o=typeof n==`string`?fg(n):n,s=typeof r==`string`?ug(r):r;if(typeof r==`string`&&(r=ug(r)),r?.length!==16)throw TypeError(`Namespace must be array-like (16 iterable integer values, 0-255)`);let c=new Uint8Array(16+o.length);if(c.set(s),c.set(o,s.length),c=t(c),c[6]=c[6]&15|e,c[8]=c[8]&63|128,i){a||=0;for(let e=0;e<16;++e)i[a+e]=c[e];return i}return dg(c)}function gg(e){return Array.isArray(e)?e=Buffer.from(e):typeof e==`string`&&(e=Buffer.from(e,`utf8`)),(0,u.createHash)(`sha1`).update(e).digest()}var _g=gg;function vg(e,t,n,r){return hg(80,_g,e,t,n,r)}vg.DNS=`6ba7b810-9dad-11d1-80b4-00c04fd430c8`,vg.URL=`6ba7b811-9dad-11d1-80b4-00c04fd430c8`;var yg=vg;function bg(e){let n=(0,b.join)(e.dataDirectory,`chats`),r={},i=(0,b.join)(e.dataDirectory,`storage.json`);o.existsSync(i)&&(r=JSON.parse(o.readFileSync(i,`utf-8`)));let a=new Map,s=t=>{let r=a.get(t);return r||(r=new Gh({chatId:t,chatsDirectory:n}),a.set(t,r)),r.setAgent(e.getAgent()),r},c={async upsert(e){let t=yg(JSON.stringify(e),yg.URL),n=s(t).getState(),r=n.messages.length===0&&!n.created_at;return{id:n.id,created:r,createdAt:n.created_at??new Date().toISOString(),key:e}},async get(e){let t=s(e).getState();return{id:t.id,createdAt:t.created_at??new Date().toISOString()}},async getMessages(e){return s(e).getState().messages},async sendMessages(e,t,n){let r=s(e),i=t.map(e=>Uh(e,`run`));if(n?.behavior===`append`){await r.upsertMessages(i);return}if(n?.behavior===`interrupt`){await r.sendMessages(i);return}await r.sendMessages(i)},async deleteMessages(e,t){await s(e).deleteMessages(t)},async start(e){await s(e).start()},async stop(e){await s(e).stop()},async delete(e){await s(e).resetChat()}},l={get(e){return Promise.resolve(r[e])},set(e,t){return r[e]=t,o.writeFileSync(i,JSON.stringify(r),`utf-8`),Promise.resolve()},delete(e){return delete r[e],o.writeFileSync(i,JSON.stringify(r),`utf-8`),Promise.resolve()},list(e,t){let n=Math.min(t?.limit??100,1e3),i=t?.cursor,a=Object.keys(r).filter(t=>t.startsWith(e??``)).sort(),o=0;if(i){let e=a.indexOf(i);e!==-1&&(o=e+1)}let s=a.slice(o,o+n),c=o+n<a.length?s[s.length-1]:void 0;return Promise.resolve({entries:s.map(e=>({key:e})),cursor:c})}},u=(0,d.createServer)(t.createServerAdapter(e=>ag.fetch(e,{chat:c,store:l})));u.listen(e.port??0);let f=zh(n,`id`);return{url:`http://127.0.0.1:${u.address().port}`,chatsDirectory:n,getChatManager:s,listChats:()=>f.list(),dispose:()=>{for(let e of a.values())e.dispose();a.clear(),f.dispose(),u.close()}}}function xg({agent:e,capabilities:n,messages:r}){let[i,a]=(0,_.useState)(void 0),[o,s]=(0,_.useState)(!0),[c,l]=(0,_.useState)(void 0),u=(0,_.useRef)(c);(0,_.useEffect)(()=>{u.current=c},[c]);let[d,f]=(0,_.useState)(()=>t.lastUIOptions(r));(0,_.useEffect)(()=>{f(e=>{let n=t.lastUIOptions(r);return JSON.stringify(n)===JSON.stringify(e)?e:n})},[r]);let[p,m]=(0,_.useState)(void 0),h=(0,_.useCallback)((e,t)=>{if(!u.current)return!1;let n=u.current[e];return n?n.values.some(e=>e.id===t):!1},[]),g=(0,_.useCallback)(e=>{m(t=>{let n={...d,...t,...e};for(let[e,t]of Object.entries(n))h(e,t)||delete n[e];for(let[e,t]of Object.entries(u.current??{}))!n[e]&&t.defaultValue!==void 0&&(n[e]=t.defaultValue);return JSON.stringify(n)===JSON.stringify(t)?t:n})},[d,h]);(0,_.useEffect)(()=>{if(!d&&!c){m(void 0);return}g()},[d,c,g]);let v=(0,_.useRef)(void 0),y=(0,_.useRef)(void 0);(0,_.useEffect)(()=>{e!==y.current&&(y.current=e,l(void 0),m(void 0),a(void 0),s(!0),v.current=void 0)},[e]),(0,_.useEffect)(()=>{if(n&&!n.ui||!e){l(void 0),m(void 0),a(void 0),v.current=void 0;return}let t=p?JSON.stringify(p):``;if(v.current===t){s(!1),a(void 0);return}let r=new AbortController;return s(!0),a(void 0),e.ui(p?{selectedOptions:p}:{},{signal:r.signal}).then(e=>{if(!e){l(void 0);return}r.signal.aborted||(l(t=>JSON.stringify(t)===JSON.stringify(e)?t:e),v.current=t)}).catch(e=>{r.signal.aborted||a(e instanceof Error?e:Error(String(e)))}).finally(()=>{s(!1)}),()=>{r.abort()}},[e,n,p]);let b=(0,_.useCallback)((e,t)=>{g({[e]:t})},[g]);return{schema:c,options:p,setOption:b,loading:o,error:i}}function Sg(e){let t=(0,_.useRef)(e.onRequest);(0,_.useEffect)(()=>{t.current=e.onRequest},[e.onRequest]);let[n,r]=(0,_.useState)(`disconnected`);return(0,_.useEffect)(()=>{if(e.disabled||!e.id){r(`disconnected`);return}let n=!1,i,a,o=!1,s,c=(0,b.join)(e.directory,`.blink`,`devhook`);return(async()=>{try{s=await Mh(c,{stale:!0,retries:0})}catch(e){if(e&&typeof e==`object`&&`code`in e&&e.code===`ELOCKED`){let e=``;try{let t=Ph(c);t.locked&&t.pid&&(e=` (PID: ${t.pid})`)}catch{}console.error(mf.red(`\nError: Another ${mf.bold(`blink dev`)} process is already running in this directory${e}.`)),console.error(mf.red(`Please stop the other process and try again.
|
|
142
142
|
`)),process.exit(1)}let t=e&&typeof e==`object`&&`message`in e?String(e.message):String(e);console.warn(mf.yellow(`\nWarning: Failed to acquire devhook lock: ${t}`)),console.warn(mf.yellow(`Continuing without lock. Multiple ${mf.bold(`blink dev`)} processes may conflict with each other.\n`))}let l=()=>{if(!(n||o)){if(o=!0,i){try{i.dispose()}catch{}i=void 0}i=new sd({baseURL:`https://blink.so`}).devhook.listen({id:e.id,onRequest:async e=>t.current(e),onConnect:()=>{o=!1,r(`connected`)},onDisconnect:()=>{o=!1,r(`disconnected`),!n&&!a&&(a=setTimeout(()=>{a=void 0,l()},2e3))},onError:e=>{o=!1,r(`error`),!n&&!a&&(a=setTimeout(()=>{a=void 0,l()},2e3))}})}};l()})(),()=>{if(n=!0,a&&=(clearTimeout(a),void 0),i){try{i.dispose()}catch{}i=void 0}if(s)try{s()}catch(e){console.warn(`Failed to release devhook lock:`,e)}}},[e.disabled,e.directory]),{id:e.id,url:e.id?`https://${e.id}.blink.host`:void 0,status:n}}var Cg=e.__commonJSMin(((e,t)=>{t.exports={name:`dotenv`,version:`17.2.3`,description:`Loads environment variables from .env file`,main:`lib/main.js`,types:`lib/main.d.ts`,exports:{".":{types:`./lib/main.d.ts`,require:`./lib/main.js`,default:`./lib/main.js`},"./config":`./config.js`,"./config.js":`./config.js`,"./lib/env-options":`./lib/env-options.js`,"./lib/env-options.js":`./lib/env-options.js`,"./lib/cli-options":`./lib/cli-options.js`,"./lib/cli-options.js":`./lib/cli-options.js`,"./package.json":`./package.json`},scripts:{"dts-check":`tsc --project tests/types/tsconfig.json`,lint:`standard`,pretest:`npm run lint && npm run dts-check`,test:`tap run tests/**/*.js --allow-empty-coverage --disable-coverage --timeout=60000`,"test:coverage":`tap run tests/**/*.js --show-full-coverage --timeout=60000 --coverage-report=text --coverage-report=lcov`,prerelease:`npm test`,release:`standard-version`},repository:{type:`git`,url:`git://github.com/motdotla/dotenv.git`},homepage:`https://github.com/motdotla/dotenv#readme`,funding:`https://dotenvx.com`,keywords:[`dotenv`,`env`,`.env`,`environment`,`variables`,`config`,`settings`],readmeFilename:`README.md`,license:`BSD-2-Clause`,devDependencies:{"@types/node":`^18.11.3`,decache:`^4.6.2`,sinon:`^14.0.1`,standard:`^17.0.0`,"standard-version":`^9.5.0`,tap:`^19.2.0`,typescript:`^4.8.4`},engines:{node:`>=12`},browser:{fs:!1}}})),wg=e.__commonJSMin(((e,t)=>{let n=require(`fs`),r=require(`path`),i=require(`os`),a=require(`crypto`),o=Cg().version,s=[`🔐 encrypt with Dotenvx: https://dotenvx.com`,`🔐 prevent committing .env to code: https://dotenvx.com/precommit`,`🔐 prevent building .env in docker: https://dotenvx.com/prebuild`,`📡 add observability to secrets: https://dotenvx.com/ops`,`👥 sync secrets across teammates & machines: https://dotenvx.com/ops`,`🗂️ backup and recover secrets: https://dotenvx.com/ops`,`✅ audit secrets and track compliance: https://dotenvx.com/ops`,`🔄 add secrets lifecycle management: https://dotenvx.com/ops`,`🔑 add access controls to secrets: https://dotenvx.com/ops`,"🛠️ run anywhere with `dotenvx run -- yourcommand`",`⚙️ specify custom .env file path with { path: '/custom/path/.env' }`,`⚙️ enable debug logging with { debug: true }`,`⚙️ override existing env vars with { override: true }`,`⚙️ suppress all logs with { quiet: true }`,`⚙️ write to custom object with { processEnv: myObject }`,`⚙️ load multiple .env files with { path: ['.env.local', '.env'] }`];function c(){return s[Math.floor(Math.random()*s.length)]}function l(e){return typeof e==`string`?![`false`,`0`,`no`,`off`,``].includes(e.toLowerCase()):!!e}function u(){return process.stdout.isTTY}function d(e){return u()?`\x1b[2m${e}\x1b[0m`:e}let f=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/gm;function p(e){let t={},n=e.toString();n=n.replace(/\r\n?/gm,`
|
|
143
143
|
`);let r;for(;(r=f.exec(n))!=null;){let e=r[1],n=r[2]||``;n=n.trim();let i=n[0];n=n.replace(/^(['"`])([\s\S]*)\1$/gm,`$2`),i===`"`&&(n=n.replace(/\\n/g,`
|
|
144
144
|
`),n=n.replace(/\\r/g,`\r`)),t[e]=n}return t}function m(e){e||={};let t=b(e);e.path=t;let n=D.configDotenv(e);if(!n.parsed){let e=Error(`MISSING_DATA: Cannot parse ${t} for an unknown reason`);throw e.code=`MISSING_DATA`,e}let r=v(e).split(`,`),i=r.length,a;for(let e=0;e<i;e++)try{let t=r[e].trim(),i=y(n,t);a=D.decrypt(i.ciphertext,i.key);break}catch(t){if(e+1>=i)throw t}return D.parse(a)}function h(e){console.error(`[dotenv@${o}][WARN] ${e}`)}function g(e){console.log(`[dotenv@${o}][DEBUG] ${e}`)}function _(e){console.log(`[dotenv@${o}] ${e}`)}function v(e){return e&&e.DOTENV_KEY&&e.DOTENV_KEY.length>0?e.DOTENV_KEY:process.env.DOTENV_KEY&&process.env.DOTENV_KEY.length>0?process.env.DOTENV_KEY:``}function y(e,t){let n;try{n=new URL(t)}catch(e){if(e.code===`ERR_INVALID_URL`){let e=Error(`INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development`);throw e.code=`INVALID_DOTENV_KEY`,e}throw e}let r=n.password;if(!r){let e=Error(`INVALID_DOTENV_KEY: Missing key part`);throw e.code=`INVALID_DOTENV_KEY`,e}let i=n.searchParams.get(`environment`);if(!i){let e=Error(`INVALID_DOTENV_KEY: Missing environment part`);throw e.code=`INVALID_DOTENV_KEY`,e}let a=`DOTENV_VAULT_${i.toUpperCase()}`,o=e.parsed[a];if(!o){let e=Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${a} in your .env.vault file.`);throw e.code=`NOT_FOUND_DOTENV_ENVIRONMENT`,e}return{ciphertext:o,key:r}}function b(e){let t=null;if(e&&e.path&&e.path.length>0)if(Array.isArray(e.path))for(let r of e.path)n.existsSync(r)&&(t=r.endsWith(`.vault`)?r:`${r}.vault`);else t=e.path.endsWith(`.vault`)?e.path:`${e.path}.vault`;else t=r.resolve(process.cwd(),`.env.vault`);return n.existsSync(t)?t:null}function x(e){return e[0]===`~`?r.join(i.homedir(),e.slice(1)):e}function S(e){let t=l(process.env.DOTENV_CONFIG_DEBUG||e&&e.debug),n=l(process.env.DOTENV_CONFIG_QUIET||e&&e.quiet);(t||!n)&&_(`Loading env from encrypted .env.vault`);let r=D._parseVault(e),i=process.env;return e&&e.processEnv!=null&&(i=e.processEnv),D.populate(i,r,e),{parsed:r}}function C(e){let t=r.resolve(process.cwd(),`.env`),i=`utf8`,a=process.env;e&&e.processEnv!=null&&(a=e.processEnv);let o=l(a.DOTENV_CONFIG_DEBUG||e&&e.debug),s=l(a.DOTENV_CONFIG_QUIET||e&&e.quiet);e&&e.encoding?i=e.encoding:o&&g(`No encoding is specified. UTF-8 is used by default`);let u=[t];if(e&&e.path)if(!Array.isArray(e.path))u=[x(e.path)];else{u=[];for(let t of e.path)u.push(x(t))}let f,p={};for(let t of u)try{let r=D.parse(n.readFileSync(t,{encoding:i}));D.populate(p,r,e)}catch(e){o&&g(`Failed to load ${t} ${e.message}`),f=e}let m=D.populate(a,p,e);if(o=l(a.DOTENV_CONFIG_DEBUG||o),s=l(a.DOTENV_CONFIG_QUIET||s),o||!s){let e=Object.keys(m).length,t=[];for(let e of u)try{let n=r.relative(process.cwd(),e);t.push(n)}catch(t){o&&g(`Failed to load ${e} ${t.message}`),f=t}_(`injecting env (${e}) from ${t.join(`,`)} ${d(`-- tip: ${c()}`)}`)}return f?{parsed:p,error:f}:{parsed:p}}function w(e){if(v(e).length===0)return D.configDotenv(e);let t=b(e);return t?D._configVault(e):(h(`You set DOTENV_KEY but you are missing a .env.vault file at ${t}. Did you forget to build it?`),D.configDotenv(e))}function T(e,t){let n=Buffer.from(t.slice(-64),`hex`),r=Buffer.from(e,`base64`),i=r.subarray(0,12),o=r.subarray(-16);r=r.subarray(12,-16);try{let e=a.createDecipheriv(`aes-256-gcm`,n,i);return e.setAuthTag(o),`${e.update(r)}${e.final()}`}catch(e){let t=e instanceof RangeError,n=e.message===`Invalid key length`,r=e.message===`Unsupported state or unable to authenticate data`;if(t||n){let e=Error(`INVALID_DOTENV_KEY: It must be 64 characters long (or more)`);throw e.code=`INVALID_DOTENV_KEY`,e}else if(r){let e=Error(`DECRYPTION_FAILED: Please check your DOTENV_KEY`);throw e.code=`DECRYPTION_FAILED`,e}else throw e}}function E(e,t,n={}){let r=!!(n&&n.debug),i=!!(n&&n.override),a={};if(typeof t!=`object`){let e=Error(`OBJECT_REQUIRED: Please check the processEnv argument being passed to populate`);throw e.code=`OBJECT_REQUIRED`,e}for(let n of Object.keys(t))Object.prototype.hasOwnProperty.call(e,n)?(i===!0&&(e[n]=t[n],a[n]=t[n]),r&&g(i===!0?`"${n}" is already defined and WAS overwritten`:`"${n}" is already defined and was NOT overwritten`)):(e[n]=t[n],a[n]=t[n]);return a}let D={configDotenv:C,_configVault:S,_parseVault:m,config:w,decrypt:T,parse:p,populate:E};t.exports.configDotenv=D.configDotenv,t.exports._configVault=D._configVault,t.exports._parseVault=D._parseVault,t.exports.config=D.config,t.exports.decrypt=D.decrypt,t.exports.parse=D.parse,t.exports.populate=D.populate,t.exports=D})),Tg=e.__toESM(wg());async function Eg(e,t){let n=e;for(;n!==(0,f.dirname)(n);){let e=(0,f.join)(n,t);try{return await(0,h.stat)(e),e}catch{}n=(0,f.dirname)(n)}}function Dg(e,t=`.env.local`){let[n,r]=(0,_.useState)({});return(0,_.useEffect)(()=>{let n,i=e=>{try{let t=(0,p.readFileSync)(e,`utf-8`),n=(0,Tg.parse)(t);r(n)}catch(e){console.error(`Error reading ${t}:`,e),r({})}};return Eg(e,t).then(e=>{if(!e){r({});return}i(e),n=(0,p.watch)(e,{persistent:!1},()=>{i(e)})}),()=>{n&&n.close()}},[e,t]),n}var Og=class{diff(e,t,n={}){let r;typeof n==`function`?(r=n,n={}):`callback`in n&&(r=n.callback);let i=this.castInput(e,n),a=this.castInput(t,n),o=this.removeEmpty(this.tokenize(i,n)),s=this.removeEmpty(this.tokenize(a,n));return this.diffWithOptionsObj(o,s,n,r)}diffWithOptionsObj(e,t,n,r){let i=e=>{if(e=this.postProcess(e,n),r){setTimeout(function(){r(e)},0);return}else return e},a=t.length,o=e.length,s=1,c=a+o;n.maxEditLength!=null&&(c=Math.min(c,n.maxEditLength));let l=n.timeout??1/0,u=Date.now()+l,d=[{oldPos:-1,lastComponent:void 0}],f=this.extractCommon(d[0],t,e,0,n);if(d[0].oldPos+1>=o&&f+1>=a)return i(this.buildValues(d[0].lastComponent,t,e));let p=-1/0,m=1/0,h=()=>{for(let r=Math.max(p,-s);r<=Math.min(m,s);r+=2){let s,c=d[r-1],l=d[r+1];c&&(d[r-1]=void 0);let u=!1;if(l){let e=l.oldPos-r;u=l&&0<=e&&e<a}let h=c&&c.oldPos+1<o;if(!u&&!h){d[r]=void 0;continue}if(s=!h||u&&c.oldPos<l.oldPos?this.addToPath(l,!0,!1,0,n):this.addToPath(c,!1,!0,1,n),f=this.extractCommon(s,t,e,r,n),s.oldPos+1>=o&&f+1>=a)return i(this.buildValues(s.lastComponent,t,e))||!0;d[r]=s,s.oldPos+1>=o&&(m=Math.min(m,r-1)),f+1>=a&&(p=Math.max(p,r+1))}s++};if(r)(function e(){setTimeout(function(){if(s>c||Date.now()>u)return r(void 0);h()||e()},0)})();else for(;s<=c&&Date.now()<=u;){let e=h();if(e)return e}}addToPath(e,t,n,r,i){let a=e.lastComponent;return a&&!i.oneChangePerToken&&a.added===t&&a.removed===n?{oldPos:e.oldPos+r,lastComponent:{count:a.count+1,added:t,removed:n,previousComponent:a.previousComponent}}:{oldPos:e.oldPos+r,lastComponent:{count:1,added:t,removed:n,previousComponent:a}}}extractCommon(e,t,n,r,i){let a=t.length,o=n.length,s=e.oldPos,c=s-r,l=0;for(;c+1<a&&s+1<o&&this.equals(n[s+1],t[c+1],i);)c++,s++,l++,i.oneChangePerToken&&(e.lastComponent={count:1,previousComponent:e.lastComponent,added:!1,removed:!1});return l&&!i.oneChangePerToken&&(e.lastComponent={count:l,previousComponent:e.lastComponent,added:!1,removed:!1}),e.oldPos=s,c}equals(e,t,n){return n.comparator?n.comparator(e,t):e===t||!!n.ignoreCase&&e.toLowerCase()===t.toLowerCase()}removeEmpty(e){let t=[];for(let n=0;n<e.length;n++)e[n]&&t.push(e[n]);return t}castInput(e,t){return e}tokenize(e,t){return Array.from(e)}join(e){return e.join(``)}postProcess(e,t){return e}get useLongestToken(){return!1}buildValues(e,t,n){let r=[],i;for(;e;)r.push(e),i=e.previousComponent,delete e.previousComponent,e=i;r.reverse();let a=r.length,o=0,s=0,c=0;for(;o<a;o++){let e=r[o];if(e.removed)e.value=this.join(n.slice(c,c+e.count)),c+=e.count;else{if(!e.added&&this.useLongestToken){let r=t.slice(s,s+e.count);r=r.map(function(e,t){let r=n[c+t];return r.length>e.length?r:e}),e.value=this.join(r)}else e.value=this.join(t.slice(s,s+e.count));s+=e.count,e.added||(c+=e.count)}}return r}},kg=class extends Og{};new kg;function Ag(e,t){let n;for(n=0;n<e.length&&n<t.length;n++)if(e[n]!=t[n])return e.slice(0,n);return e.slice(0,n)}function jg(e,t){let n;if(!e||!t||e[e.length-1]!=t[t.length-1])return``;for(n=0;n<e.length&&n<t.length;n++)if(e[e.length-(n+1)]!=t[t.length-(n+1)])return e.slice(-n);return e.slice(-n)}function Mg(e,t,n){if(e.slice(0,t.length)!=t)throw Error(`string ${JSON.stringify(e)} doesn't start with prefix ${JSON.stringify(t)}; this is a bug`);return n+e.slice(t.length)}function Ng(e,t,n){if(!t)return e+n;if(e.slice(-t.length)!=t)throw Error(`string ${JSON.stringify(e)} doesn't end with suffix ${JSON.stringify(t)}; this is a bug`);return e.slice(0,-t.length)+n}function Pg(e,t){return Mg(e,t,``)}function Fg(e,t){return Ng(e,t,``)}function Ig(e,t){return t.slice(0,Lg(e,t))}function Lg(e,t){let n=0;e.length>t.length&&(n=e.length-t.length);let r=t.length;e.length<t.length&&(r=e.length);let i=Array(r),a=0;i[0]=0;for(let e=1;e<r;e++){for(t[e]==t[a]?i[e]=i[a]:i[e]=a;a>0&&t[e]!=t[a];)a=i[a];t[e]==t[a]&&a++}a=0;for(let r=n;r<e.length;r++){for(;a>0&&e[r]!=t[a];)a=i[a];e[r]==t[a]&&a++}return a}function Rg(e){let t;for(t=e.length-1;t>=0&&e[t].match(/\s/);t--);return e.substring(t+1)}function zg(e){let t=e.match(/^\s*/);return t?t[0]:``}const Bg=`a-zA-Z0-9_\\u{C0}-\\u{FF}\\u{D8}-\\u{F6}\\u{F8}-\\u{2C6}\\u{2C8}-\\u{2D7}\\u{2DE}-\\u{2FF}\\u{1E00}-\\u{1EFF}`,Vg=RegExp(`[${Bg}]+|\\s+|[^${Bg}]`,`ug`);var Hg=class extends Og{equals(e,t,n){return n.ignoreCase&&(e=e.toLowerCase(),t=t.toLowerCase()),e.trim()===t.trim()}tokenize(e,t={}){let n;if(t.intlSegmenter){let r=t.intlSegmenter;if(r.resolvedOptions().granularity!=`word`)throw Error(`The segmenter passed must have a granularity of "word"`);n=Array.from(r.segment(e),e=>e.segment)}else n=e.match(Vg)||[];let r=[],i=null;return n.forEach(e=>{/\s/.test(e)?i==null?r.push(e):r.push(r.pop()+e):i!=null&&/\s/.test(i)?r[r.length-1]==i?r.push(r.pop()+e):r.push(i+e):r.push(e),i=e}),r}join(e){return e.map((e,t)=>t==0?e:e.replace(/^\s+/,``)).join(``)}postProcess(e,t){if(!e||t.oneChangePerToken)return e;let n=null,r=null,i=null;return e.forEach(e=>{e.added?r=e:e.removed?i=e:((r||i)&&Ug(n,i,r,e),n=e,r=null,i=null)}),(r||i)&&Ug(n,i,r,null),e}};new Hg;function Ug(e,t,n,r){if(t&&n){let i=zg(t.value),a=Rg(t.value),o=zg(n.value),s=Rg(n.value);if(e){let r=Ag(i,o);e.value=Ng(e.value,o,r),t.value=Pg(t.value,r),n.value=Pg(n.value,r)}if(r){let e=jg(a,s);r.value=Mg(r.value,s,e),t.value=Fg(t.value,e),n.value=Fg(n.value,e)}}else if(n){if(e){let e=zg(n.value);n.value=n.value.substring(e.length)}if(r){let e=zg(r.value);r.value=r.value.substring(e.length)}}else if(e&&r){let n=zg(r.value),i=zg(t.value),a=Rg(t.value),o=Ag(n,i);t.value=Pg(t.value,o);let s=jg(Pg(n,o),a);t.value=Fg(t.value,s),r.value=Mg(r.value,n,s),e.value=Ng(e.value,n,n.slice(0,n.length-s.length))}else if(r){let e=zg(r.value),n=Rg(t.value),i=Ig(n,e);t.value=Fg(t.value,i)}else if(e){let n=Rg(e.value),r=zg(t.value),i=Ig(n,r);t.value=Pg(t.value,i)}}var Wg=class extends Og{tokenize(e){let t=RegExp(`(\\r?\\n)|[${Bg}]+|[^\\S\\n\\r]+|[^${Bg}]`,`ug`);return e.match(t)||[]}};new Wg;var Gg=class extends Og{constructor(){super(...arguments),this.tokenize=Jg}equals(e,t,n){return n.ignoreWhitespace?((!n.newlineIsToken||!e.includes(`
|
|
@@ -468,7 +468,8 @@ import { openai } from "@ai-sdk/openai";
|
|
|
468
468
|
model: anthropic("claude-sonnet-4.5", {
|
|
469
469
|
apiKey: process.env.ANTHROPIC_API_KEY,
|
|
470
470
|
});
|
|
471
|
-
|
|
471
|
+
// Use chat API for OpenAI models - it's more reliable than the responses API
|
|
472
|
+
model: openai.chat("gpt-5", { apiKey: process.env.OPENAI_API_KEY });
|
|
472
473
|
\`\`\`
|
|
473
474
|
|
|
474
475
|
**Note about Edit Mode:** Edit mode (this agent) automatically selects models in this priority:
|
|
@@ -1006,7 +1007,8 @@ import { openai } from "@ai-sdk/openai";
|
|
|
1006
1007
|
model: anthropic("claude-sonnet-4.5", {
|
|
1007
1008
|
apiKey: process.env.ANTHROPIC_API_KEY,
|
|
1008
1009
|
});
|
|
1009
|
-
|
|
1010
|
+
// Use chat API for OpenAI models - it's more reliable than the responses API
|
|
1011
|
+
model: openai.chat("gpt-5", { apiKey: process.env.OPENAI_API_KEY });
|
|
1010
1012
|
\`\`\`
|
|
1011
1013
|
|
|
1012
1014
|
**Note about Edit Mode:** Edit mode (this agent) automatically selects models in this priority:
|
|
@@ -1458,4 +1460,4 @@ Slack:
|
|
|
1458
1460
|
1. *ALWAYS* use the \`typecheck_agent\` tool to check for type errors before making changes. NEVER invoke \`tsc\` directly.
|
|
1459
1461
|
2. Use the \`message_user_agent\` tool to test the agent after you make changes.
|
|
1460
1462
|
</agent_development>
|
|
1461
|
-
`});let v=d_.scratch[`AGENTS.md`];try{v=await(0,h.readFile)((0,f.join)(e.directory,`AGENTS.md`),`utf-8`)}catch{}return _.unshift({role:`system`,content:v}),(0,m.streamText)({model:C_(e.env),messages:_,maxOutputTokens:64e3,tools:p,abortSignal:o,experimental_repairToolCall:({tools:e,toolCall:t})=>{throw Object.keys(e).includes(t.toolName)?Error(`You have this tool, but you used an invalid input.`):Error(`Invalid tool call. Tool "${t.toolName}" is not available to the EDIT AGENT.`)}})}),{agent:n,setUserAgentUrl:e=>{r=e},cleanup:()=>{i&&=(i.close(),void 0)}}}function S_(e){if(e.ANTHROPIC_API_KEY)return gt({apiKey:e.ANTHROPIC_API_KEY}).chat(`claude-sonnet-4-5`);if(e.OPENAI_API_KEY)return Ra({apiKey:e.OPENAI_API_KEY}).chat(`gpt-5`);if(e.AI_GATEWAY_API_KEY)return t.createGatewayProvider({apiKey:e.AI_GATEWAY_API_KEY})(`anthropic/claude-sonnet-4-5`)}function C_(e){let t=S_(e);if(!t)throw Error(`No API key available for edit mode`);return t}function w_(e){let[t,n]=(0,_.useState)(void 0),[r,i]=(0,_.useState)(void 0),[a,o]=(0,_.useState)(!1),s=(0,_.useRef)(void 0);return(0,_.useEffect)(()=>{let t=new AbortController,r=!1;if(i(void 0),n(void 0),!S_(e.env)){o(!0);return}return o(!1),(async()=>{s.current=x_({directory:e.directory,env:e.env,getDevhookUrl:e.getDevhookUrl});let r=await T_(),i=s.current.agent.serve({port:r,host:`127.0.0.1`,apiUrl:e.apiServerUrl});t.signal.addEventListener(`abort`,()=>{try{i.close()}catch{}s.current?.cleanup()});let a=new Hs({baseUrl:`http://127.0.0.1:${r}`});for(;!t.signal.aborted;){try{await a.health();break}catch{}await new Promise(e=>setTimeout(e,100))}if(t.signal.aborted)throw t.signal.reason;n(a)})().catch(e=>{r||i(e instanceof Error?e:Error(String(e)))}),()=>{r=!0,t.abort()}},[e.directory,e.apiServerUrl,e.env,e.getDevhookUrl]),(0,_.useMemo)(()=>({client:t,error:r,missingApiKey:a,setUserAgentUrl:e=>{s.current?.setUserAgentUrl(e)}}),[t,r,a])}async function T_(){let e=(0,d.createServer)();return new Promise((t,n)=>{e.listen(0,()=>{let n=e.address().port;t(n)}).on(`error`,e=>{n(e)})}).finally(()=>{e.close()})}function E_(e){let{directory:n}=e,[r,i]=(0,_.useState)(),[a,o]=(0,_.useState)(!1),[s,c]=(0,_.useState)(`run`),l=(0,_.useRef)(`run`);(0,_.useEffect)(()=>{l.current=s},[s]);let u=(0,_.useCallback)(t=>{c(t),e.onModeChange?.(t),i(void 0)},[e.onModeChange]),d=(0,_.useCallback)(()=>{u(s===`run`?`edit`:`run`)},[s,u]),{error:p,status:h,result:g,entry:v}=mh({directory:n,onBuildStart:e.onBuildStart,onBuildSuccess:e.onBuildSuccess,onBuildError:e.onBuildError}),y=ph({autoCheck:!0,onAuthChange:e.onAuthChange,onLoginUrl:e.onLoginUrl}),b=Dg(n),x=(0,_.useMemo)(()=>{let e=y.token;return e?{...b,BLINK_TOKEN:e}:b},[b,y.token]),S=(0,_.useRef)(void 0);(0,_.useEffect)(()=>{let t=Object.keys(x);if(t.length===S.current||S.current===void 0){S.current=t.length;return}S.current=t.length,e.onEnvLoaded?.(t)},[x,e.onEnvLoaded]);let C=(0,_.useRef)(void 0),w=(0,_.useMemo)(()=>bg({port:0,dataDirectory:(0,f.join)(n,`.blink`),getAgent:()=>C.current}),[n]),{agent:T,logs:E,error:D,capabilities:O}=Us({buildResult:g,env:x,apiServerUrl:w.url}),{client:k,error:A,missingApiKey:j,setUserAgentUrl:M}=w_({directory:n,apiServerUrl:w.url,env:x,getDevhookUrl:(0,_.useCallback)(()=>{let e=Yh(n)??Xh(n);return ne(e),`https://${e}.blink.host`},[n])}),[N,ee]=(0,_.useState)(`00000000-0000-0000-0000-000000000000`);(0,_.useEffect)(()=>{C.current=T},[T]),(0,_.useEffect)(()=>{T&&M(T.baseUrl),(s===`run`&&!T||s===`edit`&&!k)&&w.getChatManager(N)?.stopStreaming()},[T,k,s,N,w,M]);let P=(0,_.useRef)(void 0),F=Kh({chatId:N,agent:s===`run`?T:k,chatsDirectory:w.chatsDirectory,serializeMessage:e=>{let t=e.role===`user`&&P.current?{...typeof e.metadata==`object`&&e.metadata!==null?e.metadata:{},options:P.current}:e.metadata;return typeof t==`object`&&t&&(t.__blink_mode=l.current),{id:e.id??crypto.randomUUID(),created_at:new Date().toISOString(),role:e.role,parts:e.parts,mode:l.current,metadata:t}},filterMessages:e=>l.current===`edit`?!0:!(Wh(e.metadata)||e.mode===`edit`)}),te=(0,_.useRef)(0);(0,_.useEffect)(()=>{if(E.length===te.current)return;let t=te.current;for(let n of E.slice(t))e.onAgentLog?.(n);te.current=E.length},[E,e.onAgentLog,F.upsertMessage]);let[I,L]=(0,_.useState)([]);(0,_.useEffect)(()=>{w.listChats().then(e=>{L(e.map(e=>e.key))})},[w]),(0,_.useEffect)(()=>{N&&!I.includes(N)&&L(e=>[...e,N])},[N,I]);let[R,ne]=(0,_.useState)(()=>Jh(n)?Yh(n):Xh(n)),z=Sg({id:R,directory:n,disabled:!O?.request,onRequest:async t=>{if(!T)throw Error(`No agent`);let n=new URL(t.url),r=new URL(T.baseUrl);r.pathname=n.pathname,r.search=n.search;try{let i=await fetch(r.toString(),{method:t.method,body:t.body,headers:t.headers,redirect:`manual`,signal:t.signal,duplex:`half`});return e.onDevhookRequest?.({method:t.method,path:n.pathname,status:i.status}),i}catch(e){return console.error(`Error sending request to user's agent:`,e),new Response(`Internal server error`,{status:500})}}});(0,_.useEffect)(()=>{z.status!==`connected`||!z.url||e.onDevhookConnected?.(z.url)},[z.status,z.url]);let{schema:re,options:B,error:ie,setOption:ae}=xg({agent:s===`run`?T:k,capabilities:O,messages:F.messages});(0,_.useEffect)(()=>{P.current=B},[B]);let oe=(0,_.useMemo)(()=>{let e=new Map;return D&&s===`run`&&e.set(`agent`,D.message),A&&s===`edit`&&e.set(`editAgent`,`Edit agent error: ${A.message}`),
|
|
1463
|
+
`});let v=d_.scratch[`AGENTS.md`];try{v=await(0,h.readFile)((0,f.join)(e.directory,`AGENTS.md`),`utf-8`)}catch{}return _.unshift({role:`system`,content:v}),(0,m.streamText)({model:C_(e.env),messages:_,maxOutputTokens:64e3,tools:p,abortSignal:o,experimental_repairToolCall:({tools:e,toolCall:t})=>{throw Object.keys(e).includes(t.toolName)?Error(`You have this tool, but you used an invalid input.`):Error(`Invalid tool call. Tool "${t.toolName}" is not available to the EDIT AGENT.`)}})}),{agent:n,setUserAgentUrl:e=>{r=e},cleanup:()=>{i&&=(i.close(),void 0)}}}function S_(e){if(e.ANTHROPIC_API_KEY)return gt({apiKey:e.ANTHROPIC_API_KEY}).chat(`claude-sonnet-4-5`);if(e.OPENAI_API_KEY)return Ra({apiKey:e.OPENAI_API_KEY}).chat(`gpt-5`);if(e.AI_GATEWAY_API_KEY)return t.createGatewayProvider({apiKey:e.AI_GATEWAY_API_KEY})(`anthropic/claude-sonnet-4-5`)}function C_(e){let t=S_(e);if(!t)throw Error(`No API key available for edit mode`);return t}function w_(e){let[t,n]=(0,_.useState)(void 0),[r,i]=(0,_.useState)(void 0),[a,o]=(0,_.useState)(!1),s=(0,_.useRef)(void 0);return(0,_.useEffect)(()=>{let t=new AbortController,r=!1;if(i(void 0),n(void 0),!S_(e.env)){o(!0);return}return o(!1),(async()=>{s.current=x_({directory:e.directory,env:e.env,getDevhookUrl:e.getDevhookUrl});let r=await T_(),i=s.current.agent.serve({port:r,host:`127.0.0.1`,apiUrl:e.apiServerUrl});t.signal.addEventListener(`abort`,()=>{try{i.close()}catch{}s.current?.cleanup()});let a=new Hs({baseUrl:`http://127.0.0.1:${r}`});for(;!t.signal.aborted;){try{await a.health();break}catch{}await new Promise(e=>setTimeout(e,100))}if(t.signal.aborted)throw t.signal.reason;n(a)})().catch(e=>{r||i(e instanceof Error?e:Error(String(e)))}),()=>{r=!0,t.abort()}},[e.directory,e.apiServerUrl,e.env,e.getDevhookUrl]),(0,_.useMemo)(()=>({client:t,error:r,missingApiKey:a,setUserAgentUrl:e=>{s.current?.setUserAgentUrl(e)}}),[t,r,a])}async function T_(){let e=(0,d.createServer)();return new Promise((t,n)=>{e.listen(0,()=>{let n=e.address().port;t(n)}).on(`error`,e=>{n(e)})}).finally(()=>{e.close()})}function E_(e){let{directory:n}=e,[r,i]=(0,_.useState)(),[a,o]=(0,_.useState)(!1),[s,c]=(0,_.useState)(`run`),l=(0,_.useRef)(`run`);(0,_.useEffect)(()=>{l.current=s},[s]);let u=(0,_.useCallback)(t=>{c(t),e.onModeChange?.(t),i(void 0)},[e.onModeChange]),d=(0,_.useCallback)(()=>{u(s===`run`?`edit`:`run`)},[s,u]),{error:p,status:h,result:g,entry:v}=mh({directory:n,onBuildStart:e.onBuildStart,onBuildSuccess:e.onBuildSuccess,onBuildError:e.onBuildError}),y=ph({autoCheck:!0,onAuthChange:e.onAuthChange,onLoginUrl:e.onLoginUrl}),b=Dg(n),x=(0,_.useMemo)(()=>{let e=y.token;return e?{...b,BLINK_TOKEN:e}:b},[b,y.token]),S=(0,_.useRef)(void 0);(0,_.useEffect)(()=>{let t=Object.keys(x);if(t.length===S.current||S.current===void 0){S.current=t.length;return}S.current=t.length,e.onEnvLoaded?.(t)},[x,e.onEnvLoaded]);let C=(0,_.useRef)(void 0),w=(0,_.useMemo)(()=>bg({port:0,dataDirectory:(0,f.join)(n,`.blink`),getAgent:()=>C.current}),[n]),{agent:T,logs:E,error:D,capabilities:O}=Us({buildResult:g,env:x,apiServerUrl:w.url}),{client:k,error:A,missingApiKey:j,setUserAgentUrl:M}=w_({directory:n,apiServerUrl:w.url,env:x,getDevhookUrl:(0,_.useCallback)(()=>{let e=Yh(n)??Xh(n);return ne(e),`https://${e}.blink.host`},[n])}),[N,ee]=(0,_.useState)(`00000000-0000-0000-0000-000000000000`);(0,_.useEffect)(()=>{C.current=T},[T]),(0,_.useEffect)(()=>{T&&M(T.baseUrl),(s===`run`&&!T||s===`edit`&&!k)&&w.getChatManager(N)?.stopStreaming()},[T,k,s,N,w,M]);let P=(0,_.useRef)(void 0),F=Kh({chatId:N,agent:s===`run`?T:k,chatsDirectory:w.chatsDirectory,serializeMessage:e=>{let t=e.role===`user`&&P.current?{...typeof e.metadata==`object`&&e.metadata!==null?e.metadata:{},options:P.current}:e.metadata;return typeof t==`object`&&t&&(t.__blink_mode=l.current),{id:e.id??crypto.randomUUID(),created_at:new Date().toISOString(),role:e.role,parts:e.parts,mode:l.current,metadata:t}},filterMessages:e=>l.current===`edit`?!0:!(Wh(e.metadata)||e.mode===`edit`),onError:t=>{e.onError?.(`${mf.red(`⚙ [Chat Error]`)} ${mf.gray(t)}`)}}),te=(0,_.useRef)(0);(0,_.useEffect)(()=>{if(E.length===te.current)return;let t=te.current;for(let n of E.slice(t))e.onAgentLog?.(n);te.current=E.length},[E,e.onAgentLog,F.upsertMessage]);let[I,L]=(0,_.useState)([]);(0,_.useEffect)(()=>{w.listChats().then(e=>{L(e.map(e=>e.key))})},[w]),(0,_.useEffect)(()=>{N&&!I.includes(N)&&L(e=>[...e,N])},[N,I]);let[R,ne]=(0,_.useState)(()=>Jh(n)?Yh(n):Xh(n)),z=Sg({id:R,directory:n,disabled:!O?.request,onRequest:async t=>{if(!T)throw Error(`No agent`);let n=new URL(t.url),r=new URL(T.baseUrl);r.pathname=n.pathname,r.search=n.search;try{let i=await fetch(r.toString(),{method:t.method,body:t.body,headers:t.headers,redirect:`manual`,signal:t.signal,duplex:`half`});return e.onDevhookRequest?.({method:t.method,path:n.pathname,status:i.status}),i}catch(e){return console.error(`Error sending request to user's agent:`,e),new Response(`Internal server error`,{status:500})}}});(0,_.useEffect)(()=>{z.status!==`connected`||!z.url||e.onDevhookConnected?.(z.url)},[z.status,z.url]);let{schema:re,options:B,error:ie,setOption:ae}=xg({agent:s===`run`?T:k,capabilities:O,messages:F.messages});(0,_.useEffect)(()=>{P.current=B},[B]);let oe=(0,_.useMemo)(()=>{let e=new Map;return D&&s===`run`&&e.set(`agent`,D.message),A&&s===`edit`&&e.set(`editAgent`,`Edit agent error: ${A.message}`),ie&&e.set(`options`,`Options error: ${ie.message}`),e},[D,A,ie,s]),se=(0,_.useRef)(new Map);(0,_.useEffect)(()=>{let t=se.current,n=oe;for(let[r,i]of n.entries())t.get(r)!==i&&e.onError?.(i);for(let e of t.keys())n.has(e);se.current=new Map(n)},[oe,e.onError]);let ce=(0,_.useMemo)(()=>{let e=[...F.messages].reverse().find(e=>!(e.role!==`assistant`||e.metadata&&e.metadata.ephemeral));if(!e||r===e.id)return;let n=e.parts.filter(m.isToolOrDynamicToolUIPart);if(n.length!==0&&n.some(e=>t.isToolApprovalOutput(e.output)&&e.output.outcome===`pending`))return e},[F.messages,r]),V=(0,_.useCallback)(async(e,n)=>{if(!ce)return;n&&e&&o(!0),i(ce.id);let r=F.messages;if(r.length===0)return;let a=r[r.length-1];if(!a||a.role!==`assistant`||!Array.isArray(a.parts))return;let s=a.parts.map(n=>n.output&&t.isToolApprovalOutput(n.output)&&n.output.outcome===`pending`?{...n,output:{...n.output,outcome:e?`approved`:`rejected`}}:n);await F.upsertMessage({...a,parts:s}),await F.start()},[ce,F]);(0,_.useEffect)(()=>{a&&ce&&V(!0)},[a,ce,V]);let le=(0,_.useCallback)(()=>{let e=crypto.randomUUID();ee(e),L(t=>[...t,e]),i(void 0)},[]),ue=(0,_.useCallback)(e=>{ee(e),i(void 0)},[]),de=(0,_.useMemo)(()=>{if(ce)return{message:ce,approve:e=>V(!0,e),reject:()=>V(!1),autoApproveEnabled:a}},[ce,V,a]),fe=(0,_.useMemo)(()=>{let e=F.messages;if(e.length!==0)for(let t=e.length-1;t>=0;t--){let n=e[t];if(!n||n.role!==`assistant`||!n.metadata||typeof n.metadata!=`object`||!(`totalUsage`in n.metadata))continue;let r=n.metadata.totalUsage;if(!(!r||typeof r!=`object`)&&!(!(`inputTokens`in r)||!(`outputTokens`in r)||!(`totalTokens`in r)))return{inputTokens:r.inputTokens,outputTokens:r.outputTokens,totalTokens:r.totalTokens,cachedInputTokens:r.cachedInputTokens}}},[F.messages]),pe=(0,_.useMemo)(()=>{if(F.status!==`streaming`)return!1;if(!F.streamingMessage)return!0;let e=F.streamingMessage.parts.filter(m.isToolOrDynamicToolUIPart);return e.length>0&&e.every(e=>e.state.startsWith(`output-`))},[F.status,F.streamingMessage]);return{mode:s,setMode:u,toggleMode:d,chat:F,chats:I,switchChat:ue,newChat:le,build:{status:h,error:p,entrypoint:v},devhook:{connected:z.status===`connected`,url:z.status===`connected`?z.url:void 0},capabilities:O,options:{schema:re,selected:B,error:ie,setOption:ae},approval:de,tokenUsage:fe,auth:y,server:w,showWaitingPlaceholder:pe,editModeMissingApiKey:j}}exports.useAgent=Us,exports.useAuth=ph,exports.useBundler=mh,exports.useChat=Kh,exports.useDevMode=E_,exports.useDevhook=Sg,exports.useDotenv=Dg,exports.useEditAgent=w_,exports.useOptions=xg;
|
|
@@ -175,7 +175,6 @@ interface StoredChat {
|
|
|
175
175
|
created_at: string;
|
|
176
176
|
updated_at: string;
|
|
177
177
|
messages: StoredMessage[];
|
|
178
|
-
error?: string;
|
|
179
178
|
}
|
|
180
179
|
type StoredMessageMetadata = {
|
|
181
180
|
__blink_internal: true;
|
|
@@ -202,7 +201,6 @@ interface ChatState {
|
|
|
202
201
|
readonly messages: StoredMessage[];
|
|
203
202
|
readonly status: ChatStatus;
|
|
204
203
|
readonly streamingMessage?: StoredMessage;
|
|
205
|
-
readonly error?: string;
|
|
206
204
|
readonly loading: boolean;
|
|
207
205
|
readonly queuedMessages: StoredMessage[];
|
|
208
206
|
}
|
|
@@ -219,6 +217,10 @@ interface ChatManagerOptions {
|
|
|
219
217
|
* Return true to include the message, false to exclude it.
|
|
220
218
|
*/
|
|
221
219
|
readonly filterMessages?: (message: StoredMessage) => boolean;
|
|
220
|
+
/**
|
|
221
|
+
* Optional callback invoked when an error occurs during chat operations.
|
|
222
|
+
*/
|
|
223
|
+
readonly onError?: (error: string) => void;
|
|
222
224
|
}
|
|
223
225
|
type StateListener = (state: ChatState) => void;
|
|
224
226
|
/**
|
|
@@ -231,6 +233,7 @@ declare class ChatManager {
|
|
|
231
233
|
private chatStore;
|
|
232
234
|
private serializeMessage?;
|
|
233
235
|
private filterMessages?;
|
|
236
|
+
private onError?;
|
|
234
237
|
private chat;
|
|
235
238
|
private loading;
|
|
236
239
|
private streamingMessage;
|
|
@@ -301,6 +304,10 @@ interface UseChatOptions {
|
|
|
301
304
|
* Return true to include the message, false to exclude it.
|
|
302
305
|
*/
|
|
303
306
|
readonly filterMessages?: (message: StoredMessage) => boolean;
|
|
307
|
+
/**
|
|
308
|
+
* Optional callback invoked when an error occurs during chat operations.
|
|
309
|
+
*/
|
|
310
|
+
readonly onError?: (error: string) => void;
|
|
304
311
|
}
|
|
305
312
|
interface UseChat extends ChatState {
|
|
306
313
|
readonly sendMessage: (message: StoredMessage) => Promise<void>;
|
|
@@ -175,7 +175,6 @@ interface StoredChat {
|
|
|
175
175
|
created_at: string;
|
|
176
176
|
updated_at: string;
|
|
177
177
|
messages: StoredMessage[];
|
|
178
|
-
error?: string;
|
|
179
178
|
}
|
|
180
179
|
type StoredMessageMetadata = {
|
|
181
180
|
__blink_internal: true;
|
|
@@ -202,7 +201,6 @@ interface ChatState {
|
|
|
202
201
|
readonly messages: StoredMessage[];
|
|
203
202
|
readonly status: ChatStatus;
|
|
204
203
|
readonly streamingMessage?: StoredMessage;
|
|
205
|
-
readonly error?: string;
|
|
206
204
|
readonly loading: boolean;
|
|
207
205
|
readonly queuedMessages: StoredMessage[];
|
|
208
206
|
}
|
|
@@ -219,6 +217,10 @@ interface ChatManagerOptions {
|
|
|
219
217
|
* Return true to include the message, false to exclude it.
|
|
220
218
|
*/
|
|
221
219
|
readonly filterMessages?: (message: StoredMessage) => boolean;
|
|
220
|
+
/**
|
|
221
|
+
* Optional callback invoked when an error occurs during chat operations.
|
|
222
|
+
*/
|
|
223
|
+
readonly onError?: (error: string) => void;
|
|
222
224
|
}
|
|
223
225
|
type StateListener = (state: ChatState) => void;
|
|
224
226
|
/**
|
|
@@ -231,6 +233,7 @@ declare class ChatManager {
|
|
|
231
233
|
private chatStore;
|
|
232
234
|
private serializeMessage?;
|
|
233
235
|
private filterMessages?;
|
|
236
|
+
private onError?;
|
|
234
237
|
private chat;
|
|
235
238
|
private loading;
|
|
236
239
|
private streamingMessage;
|
|
@@ -301,6 +304,10 @@ interface UseChatOptions {
|
|
|
301
304
|
* Return true to include the message, false to exclude it.
|
|
302
305
|
*/
|
|
303
306
|
readonly filterMessages?: (message: StoredMessage) => boolean;
|
|
307
|
+
/**
|
|
308
|
+
* Optional callback invoked when an error occurs during chat operations.
|
|
309
|
+
*/
|
|
310
|
+
readonly onError?: (error: string) => void;
|
|
304
311
|
}
|
|
305
312
|
interface UseChat extends ChatState {
|
|
306
313
|
readonly sendMessage: (message: StoredMessage) => Promise<void>;
|