typebulb 0.11.4 → 0.11.6

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/index.js CHANGED
@@ -1,12 +1,12 @@
1
1
  #!/usr/bin/env node
2
- var Xs=Object.defineProperty;var M=(r,e)=>()=>(r&&(e=r(r=0)),e);var Qs=(r,e)=>{for(var t in e)Xs(r,t,{get:e[t],enumerable:!0})};function at(r){try{let e=r.split(`
3
- `),t=0;if(e[t]?.trim()!=="---")return null;t++;let n=[];for(;t<e.length&&e[t]?.trim()!=="---";)n.push(e[t]),t++;if(e[t]?.trim()!=="---")return null;t++;let s=ao(n);if(!s)return null;let o=new Map;for(;t<e.length;){let a=e[t]?.trim()?.match(/^\*\*(.+)\*\*$/);if(a){let c=a[1].trim();for(t++;t<e.length&&e[t]?.trim()==="";)t++;let l=e[t]?.match(/^(`{3,})(\w*)\s*$/);if(!l){t++;continue}let d=l[1];t++;let u=[];for(;t<e.length&&!e[t]?.match(new RegExp(`^${d}\\s*$`));)u.push(e[t]),t++;t++,o.set(c,u.join(`
4
- `))}else t++}return{frontmatter:s,files:o}}catch{return null}}function ao(r){let e={};for(let t of r){let n=t.indexOf(":");if(n===-1)continue;let s=t.slice(0,n).trim(),o=t.slice(n+1).trim();switch(s){case"format":e.format=o;break;case"name":e.name=co(o);break}}return!e.format?.startsWith("typebulb")||!e.name?null:e}function co(r){return r.startsWith('"')&&r.endsWith('"')?r.slice(1,-1).replace(/\\"/g,'"'):r.startsWith("'")&&r.endsWith("'")?r.slice(1,-1):r}function ct(r){let e=t=>r.files.get(io[t].path)||"";return{name:r.frontmatter.name,code:e("code"),css:e("css"),html:e("html"),config:e("config"),notes:e("notes"),data:e("data"),infer:e("infer"),insight:e("insight"),server:e("server")}}function lo(r){try{return JSON.parse(r),!0}catch{}return!!(/^\s*<[\s\S]*>/.test(r)||/^---\s*$/m.test(r)||/^\w[\w\s]*:[ \t]/m.test(r))}function Gr(r){let e=r.trim();return e?lo(e)?[e]:r.split(/\n\n\n+/).map(t=>t.trim()).filter(Boolean):[]}function Kr(r){if(!r.trim())return{};try{return JSON.parse(r)}catch{return{}}}var io,Yt=M(()=>{io={code:{path:"code.tsx",language:"typescript"},css:{path:"styles.css",language:"css"},html:{path:"index.html",language:"html"},config:{path:"config.json",language:"json"},notes:{path:"notes.md",language:"markdown"},data:{path:"data.txt",language:"text"},infer:{path:"infer.md",language:"markdown"},insight:{path:"insight.json",language:"json"},server:{path:"server.ts",language:"typescript"}}});import{join as fr,resolve as qo}from"path";import{homedir as Go}from"os";function Tt(){let r=process.env.TYPEBULB_SERVERS_DIR;return r?fr(r,".."):fr(Go(),".typebulb")}function ce(){return process.env.TYPEBULB_SERVERS_DIR||fr(Tt(),"servers")}function D(r){let e=qo(r);return(process.platform==="win32"?e.toLowerCase():e).replace(/\\/g,"/")}function kn(r,e){let t=D(r),n=D(e);return t.startsWith(n.endsWith("/")?n:n+"/")?!t.includes("/node_modules/"):!1}var Ge=M(()=>{});import{readFileSync as Ko,writeFileSync as Yo,mkdirSync as Xo}from"fs";import{join as Qo}from"path";function Tn(){return Qo(Tt(),"trust.json")}function mr(){try{let r=JSON.parse(Ko(Tn(),"utf8"));return new Set(Array.isArray(r)?r:[])}catch{return new Set}}function Zo(r){Xo(Tt(),{recursive:!0}),Yo(Tn(),JSON.stringify([...r]))}function le(r){return mr().has(D(r))}function Se(r,e){let t=mr(),n=D(r);(e?t.has(n):!t.has(n))||(e?t.add(n):t.delete(n),Zo(t))}function hr(){return[...mr()]}var Ke=M(()=>{Ge()});function Re(r){if(r.server.trim())return"server-side code (server.ts)";let e=r.code;if(/\btb\s*\.\s*fs\b/.test(e)||e.includes("/__fs"))return"the filesystem";if(/\btb\s*\.\s*ai\b/.test(e)||e.includes("/__ai"))return"AI (your API keys)";if(/\btb\s*\.\s*server\s*\.\s*(?!log\b)\w/.test(e)||e.includes("/__api"))return"server-side code (server.ts)"}var It=M(()=>{});import{spawn as Nn}from"child_process";import{readdir as yi,readFile as Wn,writeFile as Jn,unlink as Xe,mkdir as bi}from"fs/promises";import{mkdirSync as wi,writeFileSync as Ln,appendFileSync as vi,readFileSync as Hn}from"fs";import*as W from"path";import{fileURLToPath as xi}from"url";function br(r){return W.join(ce(),`${r}.json`)}function Qe(r){return W.join(ce(),`${r}.log`)}function $t(r){let e=Qe(r);try{wi(ce(),{recursive:!0}),Ln(e,"")}catch{return()=>{}}let t=process.stdout.write.bind(process.stdout),n=process.stderr.write.bind(process.stderr),s=0,o=!1,i=a=>{if(!o)try{let c=typeof a=="string"?Buffer.from(a,"utf8"):Buffer.from(a);if(vi(e,c),s+=c.length,s>2*Un){let l=Hn(e),d=l.subarray(Math.max(0,l.length-Un));Ln(e,d),s=d.length}}catch{o=!0}};return process.stdout.write=((a,...c)=>(i(a),t(a,...c))),process.stderr.write=((a,...c)=>(i(a),n(a,...c))),()=>{process.stdout.write=t,process.stderr.write=n}}function ke(r,e=0){try{let t=Hn(Qe(r)),n=e>=0&&e<=t.length?e:0;return{text:t.subarray(n).toString("utf8"),offset:t.length}}catch{return{text:"",offset:0}}}function Si(r){try{return process.kill(r,0),!0}catch(e){return e.code==="EPERM"}}async function Ot(r){await bi(ce(),{recursive:!0}),await Jn(br(r.pid),JSON.stringify(r))}async function Vn(r,e){let t=br(r);try{let n=JSON.parse(await Wn(t,"utf8"));if(n.denied===e)return;n.denied=e,await Jn(t,JSON.stringify(n))}catch{}}async function Ze(r){await Xe(br(r)).catch(()=>{}),await Xe(Qe(r)).catch(()=>{})}async function B(r){let e;try{e=await yi(ce())}catch{return[]}let t=[];return await Promise.all(e.map(async s=>{if(!s.endsWith(".json"))return;let o=W.join(ce(),s),i;try{i=JSON.parse(await Wn(o,"utf8"))}catch{await Xe(o).catch(()=>{});return}i&&typeof i.pid=="number"&&Si(i.pid)?t.push(i):(await Xe(o).catch(()=>{}),i?.pid&&await Xe(Qe(i.pid)).catch(()=>{}))})),(r?t.filter(s=>s.agent==null&&kn(s.file,r)):t).sort((s,o)=>s.startedAt-o.startedAt)}async function Te(r){try{process.kill(r,"SIGTERM")}catch{}await Ze(r)}function Ei(){return W.join(W.dirname(xi(import.meta.url)),"index.js")}function Ri(r,e={}){return{command:process.execPath,args:[Ei(),...e.trust?["--trust"]:[],r,...e.open===!1?["--no-open"]:[]]}}async function Dt(r,e={}){let t=e.cwd??process.cwd(),n=W.resolve(t,r),s=(await B()).find(l=>l.file===n);if(s)return s;let{command:o,args:i}=Ri(r,e);(process.platform==="win32"?Nn("cmd",["/c","start","","/b",o,...i],{cwd:t,stdio:"ignore",windowsHide:!0}):Nn(o,i,{cwd:t,detached:!0,stdio:"ignore"})).unref();let c=Date.now()+2e4;for(;Date.now()<c;){await Pi(150);let l=(await B()).find(d=>d.file===n);if(l)return l}throw new Error(`Launched ${W.basename(r)} but it did not register within 20s.`)}var Un,Pi,de=M(()=>{Ge();Un=1e6;Pi=r=>new Promise(e=>setTimeout(e,r))});function Wt(r){let e=/^---[^\n]*\n([\s\S]*?)\n---/.exec(r),t=e?/^\s*name:\s*(.+?)\s*$/m.exec(e[1]):null;return t?t[1].replace(/^["']|["']$/g,""):void 0}function Ar(r){return(Wt(r)??"bulb").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"bulb"}var Cr=M(()=>{});import{readdirSync as zi,readFileSync as qi,statSync as Gi}from"fs";import{join as ys,basename as Ki}from"path";function bs(r,e,t){if(e>8)return t;let n;try{n=zi(r,{withFileTypes:!0})}catch{return t}for(let s of n)if(s.isDirectory()){if(s.name.startsWith(".")||s.name==="node_modules")continue;bs(ys(r,s.name),e+1,t)}else s.isFile()&&s.name.endsWith(".bulb.md")&&t.push(ys(r,s.name));return t}function Ir(r){return bs(r,0,[]).map(e=>{let t=0;try{t=Gi(e).mtimeMs}catch{}let n;try{n=Wt(qi(e,"utf8").slice(0,1024))}catch{}return{path:e,name:n??Ki(e).replace(/\.bulb\.md$/,""),mtime:t}})}var ws=M(()=>{Cr()});import{readFile as Yi}from"fs/promises";async function $r(r){try{let e=at(await Yi(r,"utf-8"));return e?Re(ct(e)):void 0}catch{return}}var vs=M(()=>{Yt();It()});import{spawn as Xi}from"child_process";import{basename as Qi}from"path";function Zi(){return process.env.TYPEBULB_EDITOR||"code"}function ta(r,e,t){return t==null?[e]:ea.test(Qi(r))?["-g",`${e}:${t}`]:[`+${t}`,e]}function ra(r,e){let t=Zi();return{command:t,args:ta(t,r,e)}}function Or(r,e){let{command:t,args:n}=ra(r,e),s=Xi(t,n,{shell:!0,detached:!0,stdio:"ignore"});s.on("error",o=>console.error("[typebulb] editor launch failed:",o?.message??o)),s.unref()}var ea,xs=M(()=>{ea=/^(code|code-insiders|codium|vscodium|cursor|windsurf)(\.cmd|\.exe)?$/i});var Ss=M(()=>{de();ws();vs();Cr();xs();Ke()});var Jt,Ps=M(()=>{Jt=class{#e=new Map;accept(e,t){return this.#e.get(e)===t?!1:(this.#e.set(e,t),!0)}}});var Js={};Qs(Js,{attach:()=>Aa,breakout:()=>Ia,info:()=>Sa,launchBulb:()=>Ba,listBreakouts:()=>$a,listBulbFiles:()=>Da,listSessions:()=>_a,logEmbedError:()=>Ra,openFile:()=>Ca,poll:()=>Pa,predictTrustOf:()=>Ma,readBulbLog:()=>ja,setBulbTrust:()=>Fa,stopBreakout:()=>Oa});import{existsSync as $e,openSync as _s,readSync as As,closeSync as Cs,statSync as fe,readdirSync as Dr,watchFile as na,unwatchFile as Es,mkdirSync as Is,writeFileSync as $s,readFileSync as Br,unlinkSync as sa,rmSync as oa}from"fs";import{join as k}from"path";import{homedir as ia}from"os";function Os(r){return r?.message??String(r)}function aa(r){return r.replace(/[^a-zA-Z0-9]/g,"-")}function Ds(r){let e=Mr(r);if(!$e(e))return[];let t;try{t=Dr(e)}catch{return[]}let n=[];for(let s of t){if(!s.endsWith(".jsonl"))continue;let o=k(e,s);try{let i=fe(o);i.isFile()&&n.push({sessionId:s.slice(0,-6),file:o,mtime:i.mtimeMs})}catch{}}return n}function Vt(r){return k(r,da)}function Ms(r,e){return k(Vt(r),`${e}.lock`)}function pa(r,e){try{let t=Ms(r,e);if(Date.now()-fe(t).mtimeMs>=Bs)return!1;try{if(parseInt(Br(t,"utf8").trim(),10)===process.pid)return!1}catch{}return!0}catch{return!1}}function Fs(r,e){if(e)try{Is(Vt(r),{recursive:!0}),$s(Ms(r,e),String(process.pid))}catch(t){console.error("[lock] claim failed:",Os(t))}}function fa(r){try{oa(k(r,".claude-bulb"),{recursive:!0,force:!0})}catch{}}function ma(r){let e=Vt(r);if(!$e(e))return;let t;try{t=Dr(e)}catch{return}let n=Date.now();for(let s of t){if(!s.endsWith(".lock"))continue;let o=k(e,s);try{let i=fe(o);n-i.mtimeMs>ua&&sa(o)}catch{}}}function Rs(r){return typeof r=="string"?r:Array.isArray(r)?r.map(e=>typeof e=="string"?e:e?.text??e?.content??JSON.stringify(e)).join(`
5
- `):r==null?"":JSON.stringify(r)}function js(r){try{return fe(r),!1}catch(e){return e.code==="ENOENT"}}function Ns(){let r=C;if(r.file&&!js(r.file)){Fs(r.cwd,r.sessionId);return}let e=ha(r);e&&Ls(e)}function ha(r){if(!r.everAttached)return ga(r.cwd)??ya(r.cwd,()=>!0)}function ga(r){let e=Vt(r);if(!$e(e))return;let t;try{t=Dr(e)}catch{return}let n;for(let o of t)if(o.endsWith(".lock"))try{let i=fe(k(e,o));if(Date.now()-i.mtimeMs>=Bs||parseInt(Br(k(e,o),"utf8").trim(),10)!==process.pid)continue;(!n||i.mtimeMs>n.mtime)&&(n={sessionId:o.slice(0,-5),mtime:i.mtimeMs})}catch{}if(!n)return;let s=k(Mr(r),`${n.sessionId}.jsonl`);if(!js(s))return{sessionId:n.sessionId,file:s,mtime:n.mtime}}function ya(r,e){return Ds(r).sort((t,n)=>n.mtime-t.mtime).find(t=>!pa(r,t.sessionId)&&e(t))}function Ls(r){let e=C;if(e.file)try{Es(e.file)}catch{}e.file=r.file,e.sessionId=r.sessionId,e.everAttached=!0,e.partial="",e.offset=0,e.totals={in:0,out:0,cached:0,cacheCreate:0},e.entries=new Map,e.chainLastUuid=void 0,e.buffer.push({type:"cleared"}),e.buffer.push({type:"session",sessionId:r.sessionId}),Fs(e.cwd,r.sessionId),ks();try{Es(r.file)}catch{}na(r.file,{interval:200},()=>ks())}function ks(){let r=C;if(!r.file)return;let e;try{e=fe(r.file).size}catch{return}if(e<=r.offset)return;let t;try{t=_s(r.file,"r")}catch{return}try{let c=e-r.offset,l=Buffer.alloc(c),d=0;for(;d<c;){let u=As(t,l,d,c-d,r.offset+d);if(!u)break;d+=u}r.offset+=d,r.partial+=l.subarray(0,d).toString("utf8")}finally{Cs(t)}let n,s;for(;(s=r.partial.indexOf(`
6
- `))>=0;){let c=r.partial.slice(0,s);if(r.partial=r.partial.slice(s+1),!c.trim())continue;let l;try{l=JSON.parse(c)}catch{continue}l&&l.uuid&&(r.entries.set(l.uuid,l),l.isSidechain||(n=l.uuid))}if(!n)return;let o=[],i=r.entries.get(n),a=!1;for(;i;){if(o.push(i),i.uuid===r.chainLastUuid){a=!0;break}i=i.parentUuid?r.entries.get(i.parentUuid):void 0}if(a)for(let c=o.length-2;c>=0;c--)Ts(o[c]);else{r.chainLastUuid!==void 0&&(r.buffer.push({type:"cleared"}),r.buffer.push({type:"session",sessionId:r.sessionId}),r.totals={in:0,out:0,cached:0,cacheCreate:0});for(let c=o.length-1;c>=0;c--)Ts(o[c])}r.chainLastUuid=n}function Us(r){let e=r.trim();return!!e&&ba.some(t=>t.test(e))}function va(r){return r.replace(wa,"")}function Ht(r){let e=va(r).trim();return e&&!Us(e)?e:""}function Ws(r){return r?.type==="text"&&typeof r.text=="string"?Ht(r.text):""}function Ts(r){try{xa(r)}catch(e){console.error("[claude-bulb] skipped malformed entry:",Os(e))}}function xa(r){if(r.isSidechain)return;let e=C;if(r.type==="user"){let t=r.message?.content;if(typeof t=="string"){let n=Ht(t);n&&e.buffer.push({type:"user",text:n})}else if(Array.isArray(t))for(let n of t)if(n?.type==="tool_result")e.buffer.push({type:"tool_result",id:n.tool_use_id??"",content:Rs(n.content),isError:!!n.is_error});else{let s=Ws(n);s&&e.buffer.push({type:"user",text:s})}}else if(r.type==="attachment"&&r.attachment?.type==="queued_command"){let t=Ht(Rs(r.attachment.prompt));t&&e.buffer.push({type:"user",text:t})}else if(r.type==="assistant"){let t=r.message?.content,n=Array.isArray(t)?t:[],s=n.filter(c=>c.type==="text").map(c=>c.text??"").filter(c=>!Us(c)).join(""),o=n.filter(c=>c.type==="thinking").map(c=>c.thinking??"").join(`
7
- `),i=n.filter(c=>c.type==="tool_use").map(c=>({id:c.id??"",name:c.name??"",input:c.input??{}}));if(s||o||i.length){let c=Date.parse(r.timestamp??""),l=!isNaN(c)&&c>=e.sessionStartMs;e.buffer.push({type:"assistant",text:s,thinking:o,tools:i,live:l})}let a=r.message?.usage??r.usage;a&&(e.totals.in+=a.input_tokens??0,e.totals.out+=a.output_tokens??0,e.totals.cached+=a.cache_read_input_tokens??0,e.totals.cacheCreate+=a.cache_creation_input_tokens??0,e.buffer.push({type:"usage",...e.totals}))}}async function Sa(){return{cwd:C.cwd,pid:process.pid}}async function Pa(r){let e=C;return Ns(),{events:e.buffer.slice(r),cursor:e.buffer.length,working:ka(e)}}async function Ra(r,e){Ea.accept(r,e)&&console.log(e)}function ka(r){let e;for(let o of r.entries.values())(o.type==="user"||o.type==="assistant")&&(e=o);if(!e)return!1;if(e.type==="user")return!0;let n=(Array.isArray(e.message?.content)?e.message.content:[]).filter(o=>o.type==="tool_use").map(o=>o.id);if(n.length===0)return!1;let s=new Set;for(let o of r.entries.values()){let i=o.message?.content;if(Array.isArray(i))for(let a of i)a.type==="tool_result"&&a.tool_use_id&&s.add(a.tool_use_id)}return n.some(o=>o&&!s.has(o))}function Ta(r){let e;try{e=_s(r,"r")}catch{return""}try{let n=65536;try{n=fe(r).size}catch{}let s=(l,d)=>{if(d<=0)return"";let u=Buffer.alloc(d),f=As(e,u,0,d,l);return u.subarray(0,f).toString("utf8")},o=(l,d,u)=>{let f="";for(let m of l.split(`
2
+ var eo=Object.defineProperty;var M=(r,e)=>()=>(r&&(e=r(r=0)),e);var to=(r,e)=>{for(var t in e)eo(r,t,{get:e[t],enumerable:!0})};function ct(r){try{let e=r.split(`
3
+ `),t=0;if(e[t]?.trim()!=="---")return null;t++;let n=[];for(;t<e.length&&e[t]?.trim()!=="---";)n.push(e[t]),t++;if(e[t]?.trim()!=="---")return null;t++;let s=uo(n);if(!s)return null;let o=new Map;for(;t<e.length;){let a=e[t]?.trim()?.match(/^\*\*(.+)\*\*$/);if(a){let c=a[1].trim();for(t++;t<e.length&&e[t]?.trim()==="";)t++;let l=e[t]?.match(/^(`{3,})(\w*)\s*$/);if(!l){t++;continue}let d=l[1];t++;let u=[];for(;t<e.length&&!e[t]?.match(new RegExp(`^${d}\\s*$`));)u.push(e[t]),t++;t++,o.set(c,u.join(`
4
+ `))}else t++}return{frontmatter:s,files:o}}catch{return null}}function uo(r){let e={};for(let t of r){let n=t.indexOf(":");if(n===-1)continue;let s=t.slice(0,n).trim(),o=t.slice(n+1).trim();switch(s){case"format":e.format=o;break;case"name":e.name=po(o);break}}return!e.format?.startsWith("typebulb")||!e.name?null:e}function po(r){return r.startsWith('"')&&r.endsWith('"')?r.slice(1,-1).replace(/\\"/g,'"'):r.startsWith("'")&&r.endsWith("'")?r.slice(1,-1):r}function lt(r){let e=t=>r.files.get(lo[t].path)||"";return{name:r.frontmatter.name,code:e("code"),css:e("css"),html:e("html"),config:e("config"),notes:e("notes"),data:e("data"),infer:e("infer"),insight:e("insight"),server:e("server")}}function fo(r){try{return JSON.parse(r),!0}catch{}return!!(/^\s*<[\s\S]*>/.test(r)||/^---\s*$/m.test(r)||/^\w[\w\s]*:[ \t]/m.test(r))}function Yr(r){let e=r.trim();return e?fo(e)?[e]:r.split(/\n\n\n+/).map(t=>t.trim()).filter(Boolean):[]}function Xr(r){if(!r.trim())return{};try{return JSON.parse(r)}catch{return{}}}var lo,Xt=M(()=>{lo={code:{path:"code.tsx",language:"typescript"},css:{path:"styles.css",language:"css"},html:{path:"index.html",language:"html"},config:{path:"config.json",language:"json"},notes:{path:"notes.md",language:"markdown"},data:{path:"data.txt",language:"text"},infer:{path:"infer.md",language:"markdown"},insight:{path:"insight.json",language:"json"},server:{path:"server.ts",language:"typescript"}}});import{join as mr,resolve as Yo}from"path";import{homedir as Xo}from"os";function _t(){let r=process.env.TYPEBULB_SERVERS_DIR;return r?mr(r,".."):mr(Xo(),".typebulb")}function ce(){return process.env.TYPEBULB_SERVERS_DIR||mr(_t(),"servers")}function D(r){let e=Yo(r);return(process.platform==="win32"?e.toLowerCase():e).replace(/\\/g,"/")}function _n(r,e){let t=D(r),n=D(e);return t.startsWith(n.endsWith("/")?n:n+"/")?!t.includes("/node_modules/"):!1}var Ke=M(()=>{});import{readFileSync as Qo,writeFileSync as Zo,mkdirSync as ei}from"fs";import{join as ti}from"path";function An(){return ti(_t(),"trust.json")}function hr(){try{let r=JSON.parse(Qo(An(),"utf8"));return new Set(Array.isArray(r)?r:[])}catch{return new Set}}function ri(r){ei(_t(),{recursive:!0}),Zo(An(),JSON.stringify([...r]))}function le(r){return hr().has(D(r))}function Se(r,e){let t=hr(),n=D(r);(e?t.has(n):!t.has(n))||(e?t.add(n):t.delete(n),ri(t))}function gr(){return[...hr()]}var Ye=M(()=>{Ke()});function Re(r){if(r.server.trim())return"server-side code (server.ts)";let e=r.code;if(/\btb\s*\.\s*fs\b/.test(e)||e.includes("/__fs"))return"the filesystem";if(/\btb\s*\.\s*ai\b/.test(e)||e.includes("/__ai"))return"AI (your API keys)";if(/\btb\s*\.\s*server\s*\.\s*(?!log\b)\w/.test(e)||e.includes("/__api"))return"server-side code (server.ts)"}var $t=M(()=>{});import{spawn as Un}from"child_process";import{readdir as vi,readFile as Hn,writeFile as Vn,unlink as Qe,mkdir as xi}from"fs/promises";import{mkdirSync as Si,writeFileSync as Wn,appendFileSync as Pi,readFileSync as zn}from"fs";import*as W from"path";import{fileURLToPath as Ei}from"url";function wr(r){return W.join(ce(),`${r}.json`)}function Ze(r){return W.join(ce(),`${r}.log`)}function Ot(r){let e=Ze(r);try{Si(ce(),{recursive:!0}),Wn(e,"")}catch{return()=>{}}let t=process.stdout.write.bind(process.stdout),n=process.stderr.write.bind(process.stderr),s=0,o=!1,i=a=>{if(!o)try{let c=typeof a=="string"?Buffer.from(a,"utf8"):Buffer.from(a);if(Pi(e,c),s+=c.length,s>2*Jn){let l=zn(e),d=l.subarray(Math.max(0,l.length-Jn));Wn(e,d),s=d.length}}catch{o=!0}};return process.stdout.write=((a,...c)=>(i(a),t(a,...c))),process.stderr.write=((a,...c)=>(i(a),n(a,...c))),()=>{process.stdout.write=t,process.stderr.write=n}}function ke(r,e=0){try{let t=zn(Ze(r)),n=e>=0&&e<=t.length?e:0;return{text:t.subarray(n).toString("utf8"),offset:t.length}}catch{return{text:"",offset:0}}}function Ri(r){try{return process.kill(r,0),!0}catch(e){return e.code==="EPERM"}}async function Dt(r){await xi(ce(),{recursive:!0}),await Vn(wr(r.pid),JSON.stringify(r))}async function qn(r,e){let t=wr(r);try{let n=JSON.parse(await Hn(t,"utf8"));if(n.denied===e)return;n.denied=e,await Vn(t,JSON.stringify(n))}catch{}}async function et(r){await Qe(wr(r)).catch(()=>{}),await Qe(Ze(r)).catch(()=>{})}async function B(r){let e;try{e=await vi(ce())}catch{return[]}let t=[];return await Promise.all(e.map(async s=>{if(!s.endsWith(".json"))return;let o=W.join(ce(),s),i;try{i=JSON.parse(await Hn(o,"utf8"))}catch{await Qe(o).catch(()=>{});return}i&&typeof i.pid=="number"&&Ri(i.pid)?t.push(i):(await Qe(o).catch(()=>{}),i?.pid&&await Qe(Ze(i.pid)).catch(()=>{}))})),(r?t.filter(s=>s.agent==null&&_n(s.file,r)):t).sort((s,o)=>s.startedAt-o.startedAt)}async function Te(r){try{process.kill(r,"SIGTERM")}catch{}await et(r)}function Ti(){return W.join(W.dirname(Ei(import.meta.url)),"index.js")}function _i(r,e={}){return{command:process.execPath,args:[Ti(),...e.trust?["--trust"]:[],r,...e.open===!1?["--no-open"]:[]]}}async function Bt(r,e={}){let t=e.cwd??process.cwd(),n=W.resolve(t,r),s=(await B()).find(l=>l.file===n);if(s)return s;let{command:o,args:i}=_i(r,e);(process.platform==="win32"?Un("cmd",["/c","start","","/b",o,...i],{cwd:t,stdio:"ignore",windowsHide:!0}):Un(o,i,{cwd:t,detached:!0,stdio:"ignore"})).unref();let c=Date.now()+2e4;for(;Date.now()<c;){await ki(150);let l=(await B()).find(d=>d.file===n);if(l)return l}throw new Error(`Launched ${W.basename(r)} but it did not register within 20s.`)}var Jn,ki,de=M(()=>{Ke();Jn=1e6;ki=r=>new Promise(e=>setTimeout(e,r))});function Jt(r){let e=/^---[^\n]*\n([\s\S]*?)\n---/.exec(r),t=e?/^\s*name:\s*(.+?)\s*$/m.exec(e[1]):null;return t?t[1].replace(/^["']|["']$/g,""):void 0}function Ir(r){return(Jt(r)??"bulb").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"bulb"}var $r=M(()=>{});import{readdirSync as Yi,readFileSync as Xi,statSync as Qi}from"fs";import{join as vs,basename as Zi}from"path";function xs(r,e,t){if(e>8)return t;let n;try{n=Yi(r,{withFileTypes:!0})}catch{return t}for(let s of n)if(s.isDirectory()){if(s.name.startsWith(".")||s.name==="node_modules")continue;xs(vs(r,s.name),e+1,t)}else s.isFile()&&s.name.endsWith(".bulb.md")&&t.push(vs(r,s.name));return t}function Or(r){return xs(r,0,[]).map(e=>{let t=0;try{t=Qi(e).mtimeMs}catch{}let n;try{n=Jt(Xi(e,"utf8").slice(0,1024))}catch{}return{path:e,name:n??Zi(e).replace(/\.bulb\.md$/,""),mtime:t}})}var Ss=M(()=>{$r()});import{readFile as ea}from"fs/promises";async function Dr(r){try{let e=ct(await ea(r,"utf-8"));return e?Re(lt(e)):void 0}catch{return}}var Ps=M(()=>{Xt();$t()});import{spawn as ta}from"child_process";import{basename as ra}from"path";function na(){return process.env.TYPEBULB_EDITOR||"code"}function oa(r,e,t){return t==null?[e]:sa.test(ra(r))?["-g",`${e}:${t}`]:[`+${t}`,e]}function ia(r,e){let t=na();return{command:t,args:oa(t,r,e)}}function Br(r,e){let{command:t,args:n}=ia(r,e),s=ta(t,n,{shell:!0,detached:!0,stdio:"ignore"});s.on("error",o=>console.error("[typebulb] editor launch failed:",o?.message??o)),s.unref()}var sa,Es=M(()=>{sa=/^(code|code-insiders|codium|vscodium|cursor|windsurf)(\.cmd|\.exe)?$/i});var Rs=M(()=>{de();Ss();Ps();$r();Es();Ye()});var Ht,ks=M(()=>{Ht=class{#e=new Map;accept(e,t){return this.#e.get(e)===t?!1:(this.#e.set(e,t),!0)}}});var zs={};to(zs,{attach:()=>Oa,breakout:()=>Ba,info:()=>ka,launchBulb:()=>Na,listBreakouts:()=>Ma,listBulbFiles:()=>Fa,listSessions:()=>$a,logEmbedError:()=>Aa,openFile:()=>Da,poll:()=>Ta,predictTrustOf:()=>La,readBulbLog:()=>Wa,setBulbTrust:()=>Ua,stopBreakout:()=>ja});import{existsSync as Oe,openSync as Is,readSync as $s,closeSync as Os,statSync as fe,readdirSync as Mr,watchFile as aa,unwatchFile as Ts,mkdirSync as Ds,writeFileSync as Bs,readFileSync as jr,unlinkSync as ca,rmSync as la}from"fs";import{join as k}from"path";import{homedir as da}from"os";function Ms(r){return r?.message??String(r)}function ua(r){return r.replace(/[^a-zA-Z0-9]/g,"-")}function js(r){let e=Fr(r);if(!Oe(e))return[];let t;try{t=Mr(e)}catch{return[]}let n=[];for(let s of t){if(!s.endsWith(".jsonl"))continue;let o=k(e,s);try{let i=fe(o);i.isFile()&&n.push({sessionId:s.slice(0,-6),file:o,mtime:i.mtimeMs})}catch{}}return n}function zt(r){return k(r,ma)}function Ns(r,e){return k(zt(r),`${e}.lock`)}function ga(r,e){try{let t=Ns(r,e);if(Date.now()-fe(t).mtimeMs>=Fs)return!1;try{if(parseInt(jr(t,"utf8").trim(),10)===process.pid)return!1}catch{}return!0}catch{return!1}}function Ls(r,e){if(e)try{Ds(zt(r),{recursive:!0}),Bs(Ns(r,e),String(process.pid))}catch(t){console.error("[lock] claim failed:",Ms(t))}}function ya(r){try{la(k(r,".claude-bulb"),{recursive:!0,force:!0})}catch{}}function ba(r){let e=zt(r);if(!Oe(e))return;let t;try{t=Mr(e)}catch{return}let n=Date.now();for(let s of t){if(!s.endsWith(".lock"))continue;let o=k(e,s);try{let i=fe(o);n-i.mtimeMs>ha&&ca(o)}catch{}}}function _s(r){return typeof r=="string"?r:Array.isArray(r)?r.map(e=>typeof e=="string"?e:e?.text??e?.content??JSON.stringify(e)).join(`
5
+ `):r==null?"":JSON.stringify(r)}function Us(r){try{return fe(r),!1}catch(e){return e.code==="ENOENT"}}function Ws(){let r=C;if(r.file&&!Us(r.file)){Ls(r.cwd,r.sessionId);return}let e=wa(r);e&&Js(e)}function wa(r){if(!r.everAttached)return va(r.cwd)??xa(r.cwd,()=>!0)}function va(r){let e=zt(r);if(!Oe(e))return;let t;try{t=Mr(e)}catch{return}let n;for(let o of t)if(o.endsWith(".lock"))try{let i=fe(k(e,o));if(Date.now()-i.mtimeMs>=Fs||parseInt(jr(k(e,o),"utf8").trim(),10)!==process.pid)continue;(!n||i.mtimeMs>n.mtime)&&(n={sessionId:o.slice(0,-5),mtime:i.mtimeMs})}catch{}if(!n)return;let s=k(Fr(r),`${n.sessionId}.jsonl`);if(!Us(s))return{sessionId:n.sessionId,file:s,mtime:n.mtime}}function xa(r,e){return js(r).sort((t,n)=>n.mtime-t.mtime).find(t=>!ga(r,t.sessionId)&&e(t))}function Js(r){let e=C;if(e.file)try{Ts(e.file)}catch{}e.file=r.file,e.sessionId=r.sessionId,e.everAttached=!0,e.partial="",e.offset=0,e.totals={in:0,out:0,cached:0,cacheCreate:0},e.entries=new Map,e.chainLastUuid=void 0,e.buffer.push({type:"cleared"}),e.buffer.push({type:"session",sessionId:r.sessionId}),Ls(e.cwd,r.sessionId),As();try{Ts(r.file)}catch{}aa(r.file,{interval:200},()=>As())}function As(){let r=C;if(!r.file)return;let e;try{e=fe(r.file).size}catch{return}if(e<=r.offset)return;let t;try{t=Is(r.file,"r")}catch{return}try{let c=e-r.offset,l=Buffer.alloc(c),d=0;for(;d<c;){let u=$s(t,l,d,c-d,r.offset+d);if(!u)break;d+=u}r.offset+=d,r.partial+=l.subarray(0,d).toString("utf8")}finally{Os(t)}let n,s;for(;(s=r.partial.indexOf(`
6
+ `))>=0;){let c=r.partial.slice(0,s);if(r.partial=r.partial.slice(s+1),!c.trim())continue;let l;try{l=JSON.parse(c)}catch{continue}l&&l.uuid&&(r.entries.set(l.uuid,l),l.isSidechain||(n=l.uuid))}if(!n)return;let o=[],i=r.entries.get(n),a=!1;for(;i;){if(o.push(i),i.uuid===r.chainLastUuid){a=!0;break}i=i.parentUuid?r.entries.get(i.parentUuid):void 0}if(a)for(let c=o.length-2;c>=0;c--)Cs(o[c]);else{r.chainLastUuid!==void 0&&(r.buffer.push({type:"cleared"}),r.buffer.push({type:"session",sessionId:r.sessionId}),r.totals={in:0,out:0,cached:0,cacheCreate:0});for(let c=o.length-1;c>=0;c--)Cs(o[c])}r.chainLastUuid=n}function Hs(r){let e=r.trim();return!!e&&Sa.some(t=>t.test(e))}function Ea(r){return r.replace(Pa,"")}function Vt(r){let e=Ea(r).trim();return e&&!Hs(e)?e:""}function Vs(r){return r?.type==="text"&&typeof r.text=="string"?Vt(r.text):""}function Cs(r){try{Ra(r)}catch(e){console.error("[claude-bulb] skipped malformed entry:",Ms(e))}}function Ra(r){if(r.isSidechain)return;let e=C;if(r.type==="user"){let t=r.message?.content;if(typeof t=="string"){let n=Vt(t);n&&e.buffer.push({type:"user",text:n})}else if(Array.isArray(t))for(let n of t)if(n?.type==="tool_result")e.buffer.push({type:"tool_result",id:n.tool_use_id??"",content:_s(n.content),isError:!!n.is_error});else{let s=Vs(n);s&&e.buffer.push({type:"user",text:s})}}else if(r.type==="attachment"&&r.attachment?.type==="queued_command"){let t=Vt(_s(r.attachment.prompt));t&&e.buffer.push({type:"user",text:t})}else if(r.type==="assistant"){let t=r.message?.content,n=Array.isArray(t)?t:[],s=n.filter(c=>c.type==="text").map(c=>c.text??"").filter(c=>!Hs(c)).join(""),o=n.filter(c=>c.type==="thinking").map(c=>c.thinking??"").join(`
7
+ `),i=n.filter(c=>c.type==="tool_use").map(c=>({id:c.id??"",name:c.name??"",input:c.input??{}}));if(s||o||i.length){let c=Date.parse(r.timestamp??""),l=!isNaN(c)&&c>=e.sessionStartMs;e.buffer.push({type:"assistant",text:s,thinking:o,tools:i,live:l})}let a=r.message?.usage??r.usage;a&&(e.totals.in+=a.input_tokens??0,e.totals.out+=a.output_tokens??0,e.totals.cached+=a.cache_read_input_tokens??0,e.totals.cacheCreate+=a.cache_creation_input_tokens??0,e.buffer.push({type:"usage",...e.totals}))}}async function ka(){return{cwd:C.cwd,pid:process.pid}}async function Ta(r){let e=C;return Ws(),{events:e.buffer.slice(r),cursor:e.buffer.length,working:Ca(e)}}async function Aa(r,e){_a.accept(r,e)&&console.log(e)}function Ca(r){let e;for(let o of r.entries.values())(o.type==="user"||o.type==="assistant")&&(e=o);if(!e)return!1;if(e.type==="user")return!0;let n=(Array.isArray(e.message?.content)?e.message.content:[]).filter(o=>o.type==="tool_use").map(o=>o.id);if(n.length===0)return!1;let s=new Set;for(let o of r.entries.values()){let i=o.message?.content;if(Array.isArray(i))for(let a of i)a.type==="tool_result"&&a.tool_use_id&&s.add(a.tool_use_id)}return n.some(o=>o&&!s.has(o))}function Ia(r){let e;try{e=Is(r,"r")}catch{return""}try{let n=65536;try{n=fe(r).size}catch{}let s=(l,d)=>{if(d<=0)return"";let u=Buffer.alloc(d),f=$s(e,u,0,d,l);return u.subarray(0,f).toString("utf8")},o=(l,d,u)=>{let f="";for(let m of l.split(`
8
8
  `)){if(!m.includes(`"${d}"`))continue;let g;try{g=JSON.parse(m)}catch{continue}let v=g?.[u];g?.type===d&&typeof v=="string"&&v&&(f=v)}return f},i=s(0,Math.min(65536,n)),a=n>65536?s(n-65536,65536):"",c=o(a,"custom-title","customTitle")||o(i,"custom-title","customTitle")||o(a,"ai-title","aiTitle")||o(i,"ai-title","aiTitle");if(c)return c.replace(/\s+/g," ").trim().slice(0,200);for(let l of i.split(`
9
- `)){if(!l.trim())continue;let d;try{d=JSON.parse(l)}catch{continue}if(!d||d.isSidechain||d.type!=="user")continue;let u=d.message?.content,f="";typeof u=="string"?f=Ht(u):Array.isArray(u)&&(f=u.map(Ws).filter(Boolean).join(" "));let m=f.replace(/\s+/g," ").trim();if(m)return(m.replace(/^Continuing from a prior session\. Here is the summary of our work so far:\s*/i,"").trim()||m).slice(0,200)}return""}finally{Cs(e)}}async function _a(){return Ds(C.cwd).sort((r,e)=>e.mtime-r.mtime).map(({sessionId:r,file:e,mtime:t})=>({sessionId:r,mtime:t,preview:Ta(e)}))}async function Aa(r){let e=C,t=k(Mr(e.cwd),`${r}.jsonl`);return $e(t)?t===e.file?{ok:!0}:(Ls({sessionId:r,file:t}),{ok:!0}):{ok:!1,error:"session not found"}}async function Ca(r,e){return Or(r,e),{ok:!0}}async function Ia(r){let e=C.cwd,t=k(e,"typebulbs");Is(t,{recursive:!0});let n=Ar(r),s=`${n}.bulb.md`;for(let c=2;$e(k(t,s))&&Br(k(t,s),"utf8")!==r;c++)s=`${n}-${c}.bulb.md`;let o=k(t,s);$e(o)||$s(o,r);let i=k("typebulbs",s),a=await Dt(i,{cwd:e,open:!0});return{ok:!0,file:i,pid:a.pid,url:a.url}}async function $a(){return B(C.cwd)}async function Oa(r){return await Te(r),{ok:!0}}async function Da(){return Ir(C.cwd).map(r=>({...r,trusted:le(r.path)}))}async function Ba(r,e){let t=C.cwd;e!=null&&Se(r,e);let n=await Dt(r,{cwd:t,open:!0,trust:e});return{ok:!0,file:n.file,pid:n.pid,url:n.url,trust:!!n.trust}}async function Ma(r){return{cap:await $r(r)}}async function Fa(r,e){return Se(r,e),{ok:!0}}async function ja(r,e){return ke(r,e)}var ca,la,Mr,da,Bs,ua,C,ba,wa,Ea,Hs=M(()=>{Ss();Ps();ca=".typebulb",la=k(ia(),".claude","projects"),Mr=r=>k(la,aa(r));da=`${ca}/locks`,Bs=5e3,ua=6e4;C={cwd:process.cwd(),sessionId:"",sessionStartMs:Date.now(),buffer:[],partial:"",offset:0,totals:{in:0,out:0,cached:0,cacheCreate:0},everAttached:!1,entries:new Map};ba=[/\[Request interrupted by user\b/i,/\[Tool use was interrupted\]/i,/Claude Code returned an error/i,/\[ede_diagnostic\]/i,/^No response requested\.?$/i,/^<task-notification\b/i,/^<system-reminder\b/i];wa=/<ide_[a-z_]+>[\s\S]*?<\/ide_[a-z_]+>/gi;Ea=new Jt;fa(C.cwd);ma(C.cwd);Ns()});import*as Ys from"fs/promises";import*as X from"path";import*as Nr from"fs/promises";import{existsSync as he,readFileSync as Zs}from"fs";import*as P from"path";import{pathToFileURL as eo}from"url";import{resolve as Gt}from"resolve.exports";import{init as Lr,parse as Ur}from"es-module-lexer";function Wr(r,e){let t=P.join(r,"package.json");try{return JSON.parse(Zs(t,"utf8"))}catch{throw new Error(`--replace package '${e}' has no readable package.json at ${t}`)}}var qt=["browser","import","default"],jr=["node","import","default"];function Jr(r){let e=r.indexOf("=");if(e===-1)throw new Error(`--replace must be <name>=<path> (got '${r}')`);let t=r.slice(0,e).trim(),n=r.slice(e+1).trim();if(!t)throw new Error(`--replace missing package name (got '${r}')`);if(!n)throw new Error(`--replace missing path for '${t}'`);if(t.startsWith("@"))throw new Error(`--replace does not support scoped names yet; '${t}' is scoped`);return{name:t,dir:P.resolve(n)}}async function Hr(r){let{name:e,dir:t}=r;if(!he(t))throw new Error(`--replace path for '${e}' does not exist: ${t}`);let n=Wr(t,e),s=to(n,e),o=P.resolve(t,s);if(!he(o))throw new Error(`--replace package '${e}' entry not found on disk: ${o} \u2014 did you build it (e.g. \`pnpm run build\`)?`);let i=P.dirname(o),a=`/local/${e}/${P.basename(o)}`,c=ro(n,t);return await no(e,o,i),{name:e,dir:t,entryAbs:o,serveDir:i,entryUrl:a,typesAbs:c}}function to(r,e){if(r.exports!==void 0){let n;try{n=Gt(r,".",{browser:!0,conditions:qt})}catch(o){throw new Error(`--replace package '${e}' "exports" does not resolve a browser entry (conditions: ${qt.join(", ")}): ${o instanceof Error?o.message:o}`)}let s=Kt(n);if(!s)throw new Error(`--replace package '${e}' "exports" did not resolve "." to a single file (conditions: ${qt.join(", ")}); too complex to override.`);return s}let t=r.module??r.main;if(!t)throw new Error(`--replace package '${e}' has no "exports", "module", or "main" entry to resolve.`);return t}function ro(r,e){if(r.exports!==void 0)try{let n=Gt(r,".",{conditions:["types"]}),s=Kt(n);if(s){let o=P.resolve(e,s);if(he(o))return o}}catch{}let t=r.types??r.typings;if(t){let n=P.resolve(e,t);if(he(n))return n}}function Kt(r){if(typeof r=="string")return r;if(Array.isArray(r))return r.find(e=>typeof e=="string")}async function no(r,e,t){await Lr;let n=P.normalize(t),s=new Set,o=[e];for(;o.length;){let i=o.shift();if(s.has(i))continue;s.add(i);let a;try{a=await Nr.readFile(i,"utf8")}catch{continue}let c,l;try{[c,,,l]=Ur(a,i)}catch{continue}if(i===e&&!l)throw new Error(`override package '${r}' entry is not an ES module (no import/export syntax); CommonJS or non-module entries aren't supported (esm.sh would have to transform it).`);for(let d of c){if(d.d===-2)continue;let u=d.n;if(u&&!u.startsWith("node:")){if(u.startsWith("./")||u.startsWith("../")||u.startsWith("/")){let f=so(i,u,n);f&&!s.has(f)&&o.push(f);continue}throw new Error(`override package must ship self-contained (bundle its dependencies); ${r} externalizes '${u}'`)}}}}function so(r,e,t){let n=e.replace(/[?#].*$/,""),s=P.resolve(P.dirname(r),n),o=[s,s+".js",s+".mjs",P.join(s,"index.js"),P.join(s,"index.mjs")];for(let i of o)if(P.normalize(i).startsWith(t)&&he(i))return i}function oo(r,e,t){let n=Wr(r,e),s;if(n.exports!==void 0)try{s=Kt(Gt(n,t,{conditions:jr}))}catch(i){throw new Error(`--replace package '${e}' "exports" does not resolve a node entry for '${t}' (conditions: ${jr.join(", ")}): ${i instanceof Error?i.message:i}`)}else t==="."&&(s=n.main??n.module);if(!s)throw new Error(`--replace package '${e}' has no node export for '${t}'.`);let o=P.resolve(r,s);if(!he(o))throw new Error(`--replace package '${e}' built file not found: ${o} \u2014 did you build it (e.g. \`pnpm run build\`)?`);return eo(o).href}async function Vr(r,e){await Lr;let t;try{[t]=Ur(r)}catch{return r}let n="",s=0;for(let o of t){if(o.d!==-1)continue;let i=o.n;if(!i||i!==e.name&&!i.startsWith(e.name+"/"))continue;let a=i===e.name?".":"."+i.slice(e.name.length),c=oo(e.dir,e.name,a);n+=r.slice(s,o.s)+c,s=o.e}return n+r.slice(s)}function zr(r){let e={subcommand:"run",file:"",port:3e3,watch:!0,open:!0,server:!1,trust:!1,noTrust:!1,follow:!1,all:!1,help:!1,version:!1},t=["check","predict","logs","stop","trust","untrust","skill","models"],n=r[0];if(n==="agent"||n?.startsWith("agent:")){e.subcommand="agent";let s=n.indexOf(":");if(s!==-1){let o=n.slice(s+1);o&&(e.agentTarget=o)}r=r.slice(1)}else n&&t.includes(n)&&(e.subcommand=n,r=r.slice(1));for(let s=0;s<r.length;s++){let o=r[s];if(o==="--help"||o==="-h")e.help=!0;else if(o==="--version"||o==="-V")e.version=!0;else if(o==="--no-watch")e.watch=!1;else if(o==="--no-open")e.open=!1;else if(o==="--server")e.server=!0;else if(o==="--trust")e.trust=!0;else if(o==="--no-trust")e.noTrust=!0;else if(o==="--mode"){let i=r[++s];(!i||i.startsWith("-"))&&(console.error("Missing value for --mode (e.g. --mode staging)"),process.exit(1)),e.mode=i}else if(o==="--follow"||o==="-f")e.follow=!0;else if(o==="--all")e.all=!0;else if(o==="--lines"||o==="-n"){let i=parseInt(r[++s],10);(isNaN(i)||i<0)&&(console.error(`Invalid --lines value: ${r[s]}`),process.exit(1)),e.lines=i}else if(o==="--port"||o==="-p"){let i=r[++s],a=parseInt(i,10);isNaN(a)&&(console.error(`Invalid port: ${i}`),process.exit(1)),e.port=a}else if(o==="--replace"||o.startsWith("--replace=")){let i=o.startsWith("--replace=")?o.slice(10):r[++s]??"";try{let a=Jr(i);if(e.local)throw new Error(`--replace can only be used once (got '${e.local.name}' and '${a.name}')`);e.local=a}catch(a){console.error(a instanceof Error?a.message:String(a)),process.exit(1)}}else o.startsWith("-")||(e.file=o)}return e}function qr(){console.log(`
9
+ `)){if(!l.trim())continue;let d;try{d=JSON.parse(l)}catch{continue}if(!d||d.isSidechain||d.type!=="user")continue;let u=d.message?.content,f="";typeof u=="string"?f=Vt(u):Array.isArray(u)&&(f=u.map(Vs).filter(Boolean).join(" "));let m=f.replace(/\s+/g," ").trim();if(m)return(m.replace(/^Continuing from a prior session\. Here is the summary of our work so far:\s*/i,"").trim()||m).slice(0,200)}return""}finally{Os(e)}}async function $a(){return js(C.cwd).sort((r,e)=>e.mtime-r.mtime).map(({sessionId:r,file:e,mtime:t})=>({sessionId:r,mtime:t,preview:Ia(e)}))}async function Oa(r){let e=C,t=k(Fr(e.cwd),`${r}.jsonl`);return Oe(t)?t===e.file?{ok:!0}:(Js({sessionId:r,file:t}),{ok:!0}):{ok:!1,error:"session not found"}}async function Da(r,e){return Br(r,e),{ok:!0}}async function Ba(r){let e=C.cwd,t=k(e,"typebulbs");Ds(t,{recursive:!0});let n=Ir(r),s=`${n}.bulb.md`;for(let c=2;Oe(k(t,s))&&jr(k(t,s),"utf8")!==r;c++)s=`${n}-${c}.bulb.md`;let o=k(t,s);Oe(o)||Bs(o,r);let i=k("typebulbs",s),a=await Bt(i,{cwd:e,open:!0});return{ok:!0,file:i,pid:a.pid,url:a.url}}async function Ma(){return B(C.cwd)}async function ja(r){return await Te(r),{ok:!0}}async function Fa(){return Or(C.cwd).map(r=>({...r,trusted:le(r.path)}))}async function Na(r,e){let t=C.cwd;e!=null&&Se(r,e);let n=await Bt(r,{cwd:t,open:!0,trust:e});return{ok:!0,file:n.file,pid:n.pid,url:n.url,trust:!!n.trust}}async function La(r){return{cap:await Dr(r)}}async function Ua(r,e){return Se(r,e),{ok:!0}}async function Wa(r,e){return ke(r,e)}var pa,fa,Fr,ma,Fs,ha,C,Sa,Pa,_a,qs=M(()=>{Rs();ks();pa=".typebulb",fa=k(da(),".claude","projects"),Fr=r=>k(fa,ua(r));ma=`${pa}/locks`,Fs=5e3,ha=6e4;C={cwd:process.cwd(),sessionId:"",sessionStartMs:Date.now(),buffer:[],partial:"",offset:0,totals:{in:0,out:0,cached:0,cacheCreate:0},everAttached:!1,entries:new Map};Sa=[/\[Request interrupted by user\b/i,/\[Tool use was interrupted\]/i,/Claude Code returned an error/i,/\[ede_diagnostic\]/i,/^No response requested\.?$/i,/^<task-notification\b/i,/^<system-reminder\b/i];Pa=/<ide_[a-z_]+>[\s\S]*?<\/ide_[a-z_]+>/gi;_a=new Ht;ya(C.cwd);ba(C.cwd);Ws()});import*as Zs from"fs/promises";import*as X from"path";import*as Ur from"fs/promises";import{existsSync as he,readFileSync as ro}from"fs";import*as P from"path";import{pathToFileURL as no}from"url";import{resolve as Kt}from"resolve.exports";import{init as Wr,parse as Jr}from"es-module-lexer";function Hr(r,e){let t=P.join(r,"package.json");try{return JSON.parse(ro(t,"utf8"))}catch{throw new Error(`--replace package '${e}' has no readable package.json at ${t}`)}}var Gt=["browser","import","default"],Lr=["node","import","default"];function Vr(r){let e=r.indexOf("=");if(e===-1)throw new Error(`--replace must be <name>=<path> (got '${r}')`);let t=r.slice(0,e).trim(),n=r.slice(e+1).trim();if(!t)throw new Error(`--replace missing package name (got '${r}')`);if(!n)throw new Error(`--replace missing path for '${t}'`);if(t.startsWith("@"))throw new Error(`--replace does not support scoped names yet; '${t}' is scoped`);return{name:t,dir:P.resolve(n)}}async function zr(r){let{name:e,dir:t}=r;if(!he(t))throw new Error(`--replace path for '${e}' does not exist: ${t}`);let n=Hr(t,e),s=so(n,e),o=P.resolve(t,s);if(!he(o))throw new Error(`--replace package '${e}' entry not found on disk: ${o} \u2014 did you build it (e.g. \`pnpm run build\`)?`);let i=P.dirname(o),a=`/local/${e}/${P.basename(o)}`,c=oo(n,t);return await io(e,o,i),{name:e,dir:t,entryAbs:o,serveDir:i,entryUrl:a,typesAbs:c}}function so(r,e){if(r.exports!==void 0){let n;try{n=Kt(r,".",{browser:!0,conditions:Gt})}catch(o){throw new Error(`--replace package '${e}' "exports" does not resolve a browser entry (conditions: ${Gt.join(", ")}): ${o instanceof Error?o.message:o}`)}let s=Yt(n);if(!s)throw new Error(`--replace package '${e}' "exports" did not resolve "." to a single file (conditions: ${Gt.join(", ")}); too complex to override.`);return s}let t=r.module??r.main;if(!t)throw new Error(`--replace package '${e}' has no "exports", "module", or "main" entry to resolve.`);return t}function oo(r,e){if(r.exports!==void 0)try{let n=Kt(r,".",{conditions:["types"]}),s=Yt(n);if(s){let o=P.resolve(e,s);if(he(o))return o}}catch{}let t=r.types??r.typings;if(t){let n=P.resolve(e,t);if(he(n))return n}}function Yt(r){if(typeof r=="string")return r;if(Array.isArray(r))return r.find(e=>typeof e=="string")}async function io(r,e,t){await Wr;let n=P.normalize(t),s=new Set,o=[e];for(;o.length;){let i=o.shift();if(s.has(i))continue;s.add(i);let a;try{a=await Ur.readFile(i,"utf8")}catch{continue}let c,l;try{[c,,,l]=Jr(a,i)}catch{continue}if(i===e&&!l)throw new Error(`override package '${r}' entry is not an ES module (no import/export syntax); CommonJS or non-module entries aren't supported (esm.sh would have to transform it).`);for(let d of c){if(d.d===-2)continue;let u=d.n;if(u&&!u.startsWith("node:")){if(u.startsWith("./")||u.startsWith("../")||u.startsWith("/")){let f=ao(i,u,n);f&&!s.has(f)&&o.push(f);continue}throw new Error(`override package must ship self-contained (bundle its dependencies); ${r} externalizes '${u}'`)}}}}function ao(r,e,t){let n=e.replace(/[?#].*$/,""),s=P.resolve(P.dirname(r),n),o=[s,s+".js",s+".mjs",P.join(s,"index.js"),P.join(s,"index.mjs")];for(let i of o)if(P.normalize(i).startsWith(t)&&he(i))return i}function co(r,e,t){let n=Hr(r,e),s;if(n.exports!==void 0)try{s=Yt(Kt(n,t,{conditions:Lr}))}catch(i){throw new Error(`--replace package '${e}' "exports" does not resolve a node entry for '${t}' (conditions: ${Lr.join(", ")}): ${i instanceof Error?i.message:i}`)}else t==="."&&(s=n.main??n.module);if(!s)throw new Error(`--replace package '${e}' has no node export for '${t}'.`);let o=P.resolve(r,s);if(!he(o))throw new Error(`--replace package '${e}' built file not found: ${o} \u2014 did you build it (e.g. \`pnpm run build\`)?`);return no(o).href}async function qr(r,e){await Wr;let t;try{[t]=Jr(r)}catch{return r}let n="",s=0;for(let o of t){if(o.d!==-1)continue;let i=o.n;if(!i||i!==e.name&&!i.startsWith(e.name+"/"))continue;let a=i===e.name?".":"."+i.slice(e.name.length),c=co(e.dir,e.name,a);n+=r.slice(s,o.s)+c,s=o.e}return n+r.slice(s)}function Gr(r){let e={subcommand:"run",file:"",port:3e3,watch:!0,open:!0,server:!1,trust:!1,noTrust:!1,follow:!1,all:!1,help:!1,version:!1},t=["check","predict","logs","stop","trust","untrust","skill","models"],n=r[0];if(n==="agent"||n?.startsWith("agent:")){e.subcommand="agent";let s=n.indexOf(":");if(s!==-1){let o=n.slice(s+1);o&&(e.agentTarget=o)}r=r.slice(1)}else n&&t.includes(n)&&(e.subcommand=n,r=r.slice(1));for(let s=0;s<r.length;s++){let o=r[s];if(o==="--help"||o==="-h")e.help=!0;else if(o==="--version"||o==="-V")e.version=!0;else if(o==="--no-watch")e.watch=!1;else if(o==="--no-open")e.open=!1;else if(o==="--server")e.server=!0;else if(o==="--trust")e.trust=!0;else if(o==="--no-trust")e.noTrust=!0;else if(o==="--mode"){let i=r[++s];(!i||i.startsWith("-"))&&(console.error("Missing value for --mode (e.g. --mode staging)"),process.exit(1)),e.mode=i}else if(o==="--follow"||o==="-f")e.follow=!0;else if(o==="--all")e.all=!0;else if(o==="--lines"||o==="-n"){let i=parseInt(r[++s],10);(isNaN(i)||i<0)&&(console.error(`Invalid --lines value: ${r[s]}`),process.exit(1)),e.lines=i}else if(o==="--port"||o==="-p"){let i=r[++s],a=parseInt(i,10);isNaN(a)&&(console.error(`Invalid port: ${i}`),process.exit(1)),e.port=a}else if(o==="--replace"||o.startsWith("--replace=")){let i=o.startsWith("--replace=")?o.slice(10):r[++s]??"";try{let a=Vr(i);if(e.local)throw new Error(`--replace can only be used once (got '${e.local.name}' and '${a.name}')`);e.local=a}catch(a){console.error(a instanceof Error?a.message:String(a)),process.exit(1)}}else o.startsWith("-")||(e.file=o)}return e}function Kr(){console.log(`
10
10
  typebulb - Local bulb runner for Typebulb
11
11
 
12
12
  Usage:
@@ -95,7 +95,7 @@ Examples:
95
95
  typebulb my-editor.bulb.md
96
96
  typebulb --no-watch --port 8080 my-editor.bulb.md
97
97
  typebulb .
98
- `)}Yt();import*as re from"fs/promises";import*as kt from"path";import{pathToFileURL as zo}from"url";import{transform as uo}from"sucrase";function Xt(r,e={}){let t=e.serverOnly?["typescript"]:["typescript","jsx"];try{let{code:n}=uo(r,{transforms:t,jsxRuntime:"automatic",jsxImportSource:e.jsxImportSource||"react",production:!0});return{code:n}}catch(n){return{code:"",error:String(n)}}}var Oe="https://esm.sh",De="https://cdn.jsdelivr.net/npm/",Qt="https://data.jsdelivr.com/v1/package/npm/";function Yr(r){let e=(r||"").replace(/^\/+/,"").replace(/\/+$/,"");return e?e.split("/"):[]}var y=class r{constructor(e,t,n){let s=typeof e=="string"?r.parse(e):e;this.name=s.name,this.version=ge(t??s.version),this.subpath=ge(n??s.subpath)}static parse(e){let t=Yr(e||"");if(!t.length)return new r({name:""});if(t[0].startsWith("@")){let s=t[0],[o,i]=Xr(t[1]??""),a=ge(t.slice(2).join("/"));return new r({name:`${s}/${o}`,version:i,subpath:a})}else{let[s,o]=Xr(t[0]),i=ge(t.slice(1).join("/"));return new r({name:s,version:o,subpath:i})}}static fromUrl(e){try{let t=new URL(e),n=new URL(Oe).host,s=new URL(De).host;if(t.host===n){let o=Yr(t.pathname.replace(/^\/v\d+\//,"/"));if(!o.length)return;let i=o[0].startsWith("@")?`${o[0]}/${o[1]??""}`:o[0];return r.parse(i)}if(t.host===s){let o=t.pathname.split("/npm/")[1];if(!o)return;let i=o.split("/")[0]||"";return r.parse(i)}return}catch{return}}static versionFromUrl(e){return r.fromUrl(e)?.version}format(){let e=this.version?`${this.name}@${this.version}`:this.name;return this.subpath?`${e}/${this.subpath}`:e}root(){return this.name}static rootOf(e){return r.parse(e).name}withVersion(e){return new r({name:this.name,version:ge(e),subpath:this.subpath})}withPreferredVersion(e,t){let n=e||t;return n?this.withVersion(n):this}static isBare(e){if(!e||e.startsWith(".")||e.startsWith("/"))return!1;let t=e.toLowerCase();return!t.startsWith("http://")&&!t.startsWith("https://")}},ge=r=>r&&r.length?r:void 0,Xr=r=>{let e=r.indexOf("@");return e<0?[r,void 0]:[r.slice(0,e),ge(r.slice(e+1))]};async function A(r){try{return await r()}catch{return}}var Be=class{constructor(e,t){this.cache=e,this.http=t,this.esmHost=Oe,this.jsDelivrBase=De,this.jsDelivrMeta=Qt,this.pinMs=1e4,this.versionsIndexMs=1440*60*1e3,this.metaTtlMs=10080*60*1e3,this.pinCache=new Map}normalizeRelative(e){let t=e||"";return t.startsWith("./")?t.slice(2):t.replace(/^\/+/,"")}ensureLeadingDotSlash(e){return e.startsWith("./")?e:`./${e}`}baseDir(e){let t=typeof e=="string"?new y(e):e;return`${this.jsDelivrBase}${t.name}${t.version?`@${t.version}`:""}/`}file(e,t){return new URL(this.normalizeRelative(t),this.baseDir(e)).toString()}packageJson(e){return this.file(e,"package.json")}buildEsmUrl(e,t={}){let{target:n="es2022",bundle:s=!1,external:o}=t,i=new URLSearchParams({target:n});return s&&i.append("bundle",""),o?.length&&i.append("external",o.join(",")),`${this.esmHost}/${e}?${i.toString()}`}async pinEsmUrl(e,t="es2022"){let n=this.buildEsmUrl(e,{target:t}),s=await A(()=>this.http.head(n));return s?.ok?s.url||n:void 0}async resolveExactVersion(e){let t=Date.now(),n=this.pinCache.get(e);if(n&&t-n.ts<this.pinMs)return n.value;let s=await this.tryResolveFromUrls([this.buildEsmUrl(e),`${this.esmHost}/${e}`]);return this.pinCache.set(e,{value:s,ts:t}),s}async tryResolveFromUrls(e){for(let t of e){let n=await A(()=>this.http.head(t)),s=this.parseVersionFromUrl(n?.url||t);if(s)return s}}async fetchVersionsIndex(e){if(await this.cache.isNegative(e))return;let t=await this.cache.getIndex(e);if(t&&Date.now()-t.updatedAt<this.versionsIndexMs)return{versions:t.versions,distTags:t.distTags};let n=await A(()=>this.http.getJson(`${this.jsDelivrMeta}${encodeURIComponent(e)}`));if(!n?.versions?.length){await this.cache.recordNegative(e);return}await this.cache.clearNegative(e);let s=n.distTags&&Object.keys(n.distTags).length?n.distTags:void 0;return await this.cache.setIndex(e,n.versions,s),n}parseVersionFromUrl(e){let t=y.fromUrl(e)?.version;return t&&/\d+\.\d+\.\d+/.test(t)?t:void 0}async fetchPackageMeta(e,t){let n=await this.cache.getMeta(e,t);if(n&&Date.now()-n.updatedAt<this.metaTtlMs){let{dependencies:d,peerDependencies:u,peerDependenciesMeta:f}=n;return{name:e,version:t,dependencies:d,peerDependencies:u,peerDependenciesMeta:f}}let s=this.packageJson(new y(`${e}@${t}`)),o=await A(()=>this.http.getJson(s));if(!o)return;let i=d=>d&&Object.keys(d).length?d:void 0,a=i(o.dependencies),c=i(o.peerDependencies),l=i(o.peerDependenciesMeta);return await this.cache.setMeta(e,t,a,c,l),{name:e,version:t,dependencies:a,peerDependencies:c,peerDependenciesMeta:l}}};var Qr=r=>r.startsWith("@types/"),Me=r=>Object.keys(r?.peerDependencies||{}).filter(e=>!Qr(e)),Zt=r=>Object.keys(r?.dependencies||{}).filter(e=>!Qr(e)),po=r=>Me(r).filter(e=>!r?.peerDependenciesMeta?.[e]?.optional),Fe=class{constructor(e){this.cdn=e}async resolve(e,t){let n=await this.fetchMeta(e),{allRoots:s,autoAddedPeers:o}=await this.expandWithPeers(n,t),i=this.computeFlags(s);return{allRoots:s,flags:i,autoAddedPeers:o}}async fetchMeta(e){return Promise.all(e.map(async({name:t,version:n})=>({name:t,version:n,meta:await this.cdn.fetchPackageMeta(t,n)})))}async expandWithPeers(e,t){let n=new Map(e.map(o=>[o.name,o])),s=[];for(let o of e)for(let i of po(o.meta))!n.has(i)&&!s.some(a=>a.name===i)&&s.push({name:i,requiredBy:o.name});for(let{name:o,requiredBy:i}of s)try{let a=await t(o),c=await this.cdn.fetchPackageMeta(o,a);n.set(o,{name:o,version:a,meta:c})}catch(a){console.warn(`[typebulb] Failed to resolve peer "${o}" for "${i}":`,a)}return{allRoots:[...n.values()],autoAddedPeers:s.filter(o=>n.has(o.name))}}computeFlags(e){let t=new Set(e.flatMap(o=>Me(o.meta))),n=new Map;for(let o of e)for(let i of Zt(o.meta))n.set(i,(n.get(i)||0)+1);let s=new Set([...n.entries()].filter(([,o])=>o>=2).map(([o])=>o));return new Map(e.map(o=>[o.name,{isPeerRoot:t.has(o.name),hasPeers:Me(o.meta).length>0,isSharedDep:s.has(o.name)}]))}};var je=class{constructor(e,t,n){this.cache=e,this.cdn=t,this.semver=n}selectVersionFromIndex(e,t,n){return this.semver.selectBestVersion(e,{range:t,distTags:n})}async learnExactVersion(e){let t=await A(()=>this.cdn.fetchVersionsIndex(e));if(t?.versions?.length){let n=this.semver.selectBestVersion(t.versions,{distTags:t.distTags});if(n)return n}return this.cdn.resolveExactVersion(e)}async resolveExactForRoot(e,t){if(!t)return this.learnExactVersion(e);let n=await this.cache.getPinnedExact(e,t);if(n){if(this.semver.isExactVersion(n))return n;console.debug("[typebulb] cached version for",e,"is not exact (",n,"); re-resolving from registry")}let s=await A(()=>this.cdn.fetchVersionsIndex(e));if(s?.versions?.length){let i=this.selectVersionFromIndex(s.versions,t,s.distTags);if(i){if(this.semver.isExactVersion(i))return await this.cache.setPinnedExact(e,t,i),i}else{console.debug("[typebulb] refreshing version cache for",e,"(",t,"not in cached set \u2014 likely a new release)"),await this.cache.invalidateVersionsCache(e);let a=await A(()=>this.cdn.fetchVersionsIndex(e));if(a?.versions?.length){let c=this.selectVersionFromIndex(a.versions,t,a.distTags);if(c&&this.semver.isExactVersion(c))return await this.cache.setPinnedExact(e,t,c),c}}}let o=await this.cdn.resolveExactVersion(`${e}@${t}`);if(o&&this.semver.isExactVersion(o))return await this.cache.setPinnedExact(e,t,o),o}async effectivePackage(e,t){let n=new y(e),s=n.root(),o=t[s],i=o?await A(()=>this.cache.getPinnedExact(s,o))??await A(()=>this.resolveExactForRoot(s,o)):void 0;return{effectivePackage:i?n.withVersion(i).format():e,root:s,range:o,pinned:i}}};import{init as fo,parse as mo}from"es-module-lexer";var ye=class r{constructor(e,t,n,s){this.version=e,this.cdn=t,this.peer=n,this.cache=s}extractImportsSync(e){let t=new Set;for(let n of r.importPatterns){n.lastIndex=0;for(let s of e.matchAll(n))y.isBare(s[1])&&t.add(s[1])}return Array.from(t)}async extractImports(e){let t=new Set,n=s=>{y.isBare(s)&&t.add(s)};try{await fo;let[s]=mo(e);s.forEach(o=>n(e.slice(o.s,o.e).trim()))}catch{return this.extractImportsSync(e)}return Array.from(t)}async buildImportMap(e,t,n){let s=(await this.extractImports(e)).filter(u=>!n?.has(y.rootOf(u))),o=[...new Set(s.map(y.rootOf))],i=await Promise.all(o.map(async u=>({name:u,version:await this.resolveVersion(u,t)}))),{allRoots:a,flags:c,autoAddedPeers:l}=await this.peer.resolve(i,u=>this.resolveVersion(u,t)),d=this.buildEntries([...s,...l.map(u=>u.name)],a,c,t);return{importMap:{imports:Object.fromEntries(d)},prefetchUrls:d.map(([,u])=>u)}}async resolveVersion(e,t){let n=t[e],s=n?`${e}@${n}`:e,o=await this.version.resolveExactForRoot(e,n);if(!o){let i=await A(()=>this.cdn.pinEsmUrl(s));if(!i)throw new Error(`Cannot resolve ${s}: no matching version is published (the package or version may not exist, or the registry was unreachable).`);o=y.versionFromUrl(i),o&&n&&await A(()=>this.cache.setPinnedExact(e,n,o))}if(!o)throw new Error(`Cannot resolve ${s}: no concrete version found.`);return o}buildEntries(e,t,n,s){let o=new Map(t.map(g=>[g.name,g])),i=g=>{let v=o.get(y.rootOf(g));return new y(g).withPreferredVersion(v.version,s[v.name]).format()},a=new Set([...n.entries()].filter(([,g])=>g.isPeerRoot||g.isSharedDep).map(([g])=>g)),c=new Set(e.filter(g=>g!==y.rootOf(g)).map(y.rootOf)),l=[],d=new Set,u=new Set(e.filter(g=>g===y.rootOf(g))),f=new Set;for(let g of e){let v=y.rootOf(g),$=o.get(v),{isPeerRoot:O,hasPeers:E,isSharedDep:T}=n.get(v),p=c.has(v),h=g!==v,x=!(O||T)&&(p||!E),w=this.singletonDepsOf($,a),V=h&&u.has(v);V&&f.add(v);let se=V?[...w,v]:w.length?w:void 0;l.push([g,this.cdn.buildEsmUrl(i(g),{bundle:x,external:se})]),d.add(g)}let m=new Set([...a,...f]);for(let g of m)o.has(g)&&(d.has(g)||l.push([g,this.cdn.buildEsmUrl(i(g),{})]),l.push([`${g}/`,`${this.cdn.esmHost}/${i(g)}/`]));return l}singletonDepsOf(e,t){return[...new Set([...Me(e.meta),...Zt(e.meta)])].filter(n=>t.has(n))}};ye.importPatterns=[/\bimport\s+(?:[^'";]*?from\s*)?['"]([^'"]+)['"]/g,/\bexport\s+[^'";]*?from\s*['"]([^'"]+)['"]/g];import{gt as Zr,satisfies as ho,maxSatisfying as er,major as go,prerelease as yo,rsort as bo,valid as wo}from"semver";var lt=class{cmp(e,t){return e===t?0:Zr(e,t)?1:Zr(t,e)?-1:0}satisfies(e,t){return!e||!e.trim()?!0:!!ho(t,e,{includePrerelease:!0})}pickMaxSatisfying(e,t){if(!e?.length)return;let n=er(e,t,{includePrerelease:!0});return n===null?void 0:n}pickLatest(e){return e?.length?bo(e)[0]:void 0}selectBestVersion(e,t){if(!e?.length)return;let n=t?.range?.trim()||"*",s=t?.preferStable??!0,o=t?.distTags?.latest;if(o&&e.includes(o)&&this.satisfies(n,o))return o;if(s){let a=er(e,n,{includePrerelease:!1});if(a)return a}return er(e,n,{includePrerelease:!0})??void 0}majorOf(e){return go(e)}isPrerelease(e){return yo(e)!==null}isExactVersion(e){return wo(e)!==null}},oe=new lt;function en(r,e){let t=new Be(r,e),n=new Fe(t),s=new je(r,t,oe);return{packageService:new ye(s,t,n,r),versionResolver:s,cdnClient:t,peerResolver:n}}import*as gn from"fs/promises";import*as U from"path";var tr=[{name:"es5"},{name:"es2015.core"},{name:"es2015.collection"},{name:"es2015.promise"},{name:"es2015.iterable"},{name:"es2015.symbol"},{name:"es2015.symbol.wellknown"},{name:"es2015.generator"},{name:"es2015.proxy"},{name:"es2015.reflect"},{name:"es2016.array.include"},{name:"es2016.intl"},{name:"es2017.object"},{name:"es2017.string"},{name:"es2017.sharedmemory"},{name:"es2017.typedarrays"},{name:"es2017.date"},{name:"es2017.intl"},{name:"es2018.asynciterable"},{name:"es2018.asyncgenerator"},{name:"es2018.promise"},{name:"es2018.regexp"},{name:"es2018.intl"},{name:"es2019.array"},{name:"es2019.object"},{name:"es2019.string"},{name:"es2019.symbol"},{name:"es2019.intl"},{name:"es2020.bigint"},{name:"es2020.promise"},{name:"es2020.string"},{name:"es2020.sharedmemory"},{name:"es2020.date"},{name:"es2020.number"},{name:"es2020.symbol.wellknown"},{name:"es2020.intl"},{name:"es2021.promise"},{name:"es2021.string"},{name:"es2021.weakref"},{name:"es2021.intl"},{name:"es2022.array"},{name:"es2022.object"},{name:"es2022.error"},{name:"es2022.string"},{name:"es2022.regexp"},{name:"es2022.intl"},{name:"es2023.array"},{name:"es2023.collection"},{name:"es2023.intl",since:"5.5"},{name:"es2024.arraybuffer",since:"5.5"},{name:"es2024.collection",since:"5.5"},{name:"es2024.object",since:"5.5"},{name:"es2024.promise",since:"5.5"},{name:"es2024.regexp",since:"5.5"},{name:"es2024.sharedmemory",since:"5.5"},{name:"es2024.string",since:"5.5"},{name:"esnext.array",since:"5.5"},{name:"esnext.collection"},{name:"esnext.decorators"},{name:"esnext.disposable"},{name:"esnext.error",since:"5.5"},{name:"esnext.float16",since:"5.5"},{name:"esnext.iterator",since:"5.5"},{name:"esnext.object"},{name:"esnext.promise"},{name:"esnext.sharedmemory",since:"5.5"},{name:"esnext.intl"}],rr=[{name:"dom"},{name:"dom.iterable"},{name:"dom.asynciterable"}];var tn=`
98
+ `)}Xt();import*as re from"fs/promises";import*as Tt from"path";import{pathToFileURL as Ko}from"url";import{transform as mo}from"sucrase";function Qt(r,e={}){let t=e.serverOnly?["typescript"]:["typescript","jsx"];try{let{code:n}=mo(r,{transforms:t,jsxRuntime:"automatic",jsxImportSource:e.jsxImportSource||"react",production:!0});return{code:n}}catch(n){return{code:"",error:String(n)}}}var De="https://esm.sh",Be="https://cdn.jsdelivr.net/npm/",Zt="https://data.jsdelivr.com/v1/package/npm/";function Qr(r){let e=(r||"").replace(/^\/+/,"").replace(/\/+$/,"");return e?e.split("/"):[]}var y=class r{constructor(e,t,n){let s=typeof e=="string"?r.parse(e):e;this.name=s.name,this.version=ge(t??s.version),this.subpath=ge(n??s.subpath)}static parse(e){let t=Qr(e||"");if(!t.length)return new r({name:""});if(t[0].startsWith("@")){let s=t[0],[o,i]=Zr(t[1]??""),a=ge(t.slice(2).join("/"));return new r({name:`${s}/${o}`,version:i,subpath:a})}else{let[s,o]=Zr(t[0]),i=ge(t.slice(1).join("/"));return new r({name:s,version:o,subpath:i})}}static fromUrl(e){try{let t=new URL(e),n=new URL(De).host,s=new URL(Be).host;if(t.host===n){let o=Qr(t.pathname.replace(/^\/v\d+\//,"/"));if(!o.length)return;let i=o[0].startsWith("@")?`${o[0]}/${o[1]??""}`:o[0];return r.parse(i)}if(t.host===s){let o=t.pathname.split("/npm/")[1];if(!o)return;let i=o.split("/")[0]||"";return r.parse(i)}return}catch{return}}static versionFromUrl(e){return r.fromUrl(e)?.version}format(){let e=this.version?`${this.name}@${this.version}`:this.name;return this.subpath?`${e}/${this.subpath}`:e}root(){return this.name}static rootOf(e){return r.parse(e).name}withVersion(e){return new r({name:this.name,version:ge(e),subpath:this.subpath})}withPreferredVersion(e,t){let n=e||t;return n?this.withVersion(n):this}static isBare(e){if(!e||e.startsWith(".")||e.startsWith("/"))return!1;let t=e.toLowerCase();return!t.startsWith("http://")&&!t.startsWith("https://")}},ge=r=>r&&r.length?r:void 0,Zr=r=>{let e=r.indexOf("@");return e<0?[r,void 0]:[r.slice(0,e),ge(r.slice(e+1))]};async function A(r){try{return await r()}catch{return}}var Me=class{constructor(e,t){this.cache=e,this.http=t,this.esmHost=De,this.jsDelivrBase=Be,this.jsDelivrMeta=Zt,this.pinMs=1e4,this.versionsIndexMs=1440*60*1e3,this.metaTtlMs=10080*60*1e3,this.pinCache=new Map}normalizeRelative(e){let t=e||"";return t.startsWith("./")?t.slice(2):t.replace(/^\/+/,"")}ensureLeadingDotSlash(e){return e.startsWith("./")?e:`./${e}`}baseDir(e){let t=typeof e=="string"?new y(e):e;return`${this.jsDelivrBase}${t.name}${t.version?`@${t.version}`:""}/`}file(e,t){return new URL(this.normalizeRelative(t),this.baseDir(e)).toString()}packageJson(e){return this.file(e,"package.json")}buildEsmUrl(e,t={}){let{target:n="es2022",bundle:s=!1,external:o}=t,i=new URLSearchParams({target:n});return s&&i.append("bundle",""),o?.length&&i.append("external",o.join(",")),`${this.esmHost}/${e}?${i.toString()}`}async pinEsmUrl(e,t="es2022"){let n=this.buildEsmUrl(e,{target:t}),s=await A(()=>this.http.head(n));return s?.ok?s.url||n:void 0}async resolveExactVersion(e){let t=Date.now(),n=this.pinCache.get(e);if(n&&t-n.ts<this.pinMs)return n.value;let s=await this.tryResolveFromUrls([this.buildEsmUrl(e),`${this.esmHost}/${e}`]);return this.pinCache.set(e,{value:s,ts:t}),s}async tryResolveFromUrls(e){for(let t of e){let n=await A(()=>this.http.head(t)),s=this.parseVersionFromUrl(n?.url||t);if(s)return s}}async fetchVersionsIndex(e){if(await this.cache.isNegative(e))return;let t=await this.cache.getIndex(e);if(t&&Date.now()-t.updatedAt<this.versionsIndexMs)return{versions:t.versions,distTags:t.distTags};let n=await A(()=>this.http.getJson(`${this.jsDelivrMeta}${encodeURIComponent(e)}`));if(!n?.versions?.length){await this.cache.recordNegative(e);return}await this.cache.clearNegative(e);let s=n.distTags&&Object.keys(n.distTags).length?n.distTags:void 0;return await this.cache.setIndex(e,n.versions,s),n}parseVersionFromUrl(e){let t=y.fromUrl(e)?.version;return t&&/\d+\.\d+\.\d+/.test(t)?t:void 0}async fetchPackageMeta(e,t){let n=await this.cache.getMeta(e,t);if(n&&Date.now()-n.updatedAt<this.metaTtlMs){let{dependencies:d,peerDependencies:u,peerDependenciesMeta:f}=n;return{name:e,version:t,dependencies:d,peerDependencies:u,peerDependenciesMeta:f}}let s=this.packageJson(new y(`${e}@${t}`)),o=await A(()=>this.http.getJson(s));if(!o)return;let i=d=>d&&Object.keys(d).length?d:void 0,a=i(o.dependencies),c=i(o.peerDependencies),l=i(o.peerDependenciesMeta);return await this.cache.setMeta(e,t,a,c,l),{name:e,version:t,dependencies:a,peerDependencies:c,peerDependenciesMeta:l}}};var en=r=>r.startsWith("@types/"),je=r=>Object.keys(r?.peerDependencies||{}).filter(e=>!en(e)),er=r=>Object.keys(r?.dependencies||{}).filter(e=>!en(e)),ho=r=>je(r).filter(e=>!r?.peerDependenciesMeta?.[e]?.optional),Fe=class{constructor(e){this.cdn=e}async resolve(e,t){let n=await this.fetchMeta(e),{allRoots:s,autoAddedPeers:o}=await this.expandWithPeers(n,t),i=this.computeFlags(s);return{allRoots:s,flags:i,autoAddedPeers:o}}async fetchMeta(e){return Promise.all(e.map(async({name:t,version:n})=>({name:t,version:n,meta:await this.cdn.fetchPackageMeta(t,n)})))}async expandWithPeers(e,t){let n=new Map(e.map(o=>[o.name,o])),s=[];for(let o of e)for(let i of ho(o.meta))!n.has(i)&&!s.some(a=>a.name===i)&&s.push({name:i,requiredBy:o.name});for(let{name:o,requiredBy:i}of s)try{let a=await t(o),c=await this.cdn.fetchPackageMeta(o,a);n.set(o,{name:o,version:a,meta:c})}catch(a){console.warn(`[typebulb] Failed to resolve peer "${o}" for "${i}":`,a)}return{allRoots:[...n.values()],autoAddedPeers:s.filter(o=>n.has(o.name))}}computeFlags(e){let t=new Set(e.flatMap(o=>je(o.meta))),n=new Map;for(let o of e)for(let i of er(o.meta))n.set(i,(n.get(i)||0)+1);let s=new Set([...n.entries()].filter(([,o])=>o>=2).map(([o])=>o));return new Map(e.map(o=>[o.name,{isPeerRoot:t.has(o.name),hasPeers:je(o.meta).length>0,isSharedDep:s.has(o.name)}]))}};var Ne=class{constructor(e,t,n){this.cache=e,this.cdn=t,this.semver=n}selectVersionFromIndex(e,t,n){return this.semver.selectBestVersion(e,{range:t,distTags:n})}async learnExactVersion(e){let t=await A(()=>this.cdn.fetchVersionsIndex(e));if(t?.versions?.length){let n=this.semver.selectBestVersion(t.versions,{distTags:t.distTags});if(n)return n}return this.cdn.resolveExactVersion(e)}async resolveExactForRoot(e,t){if(!t)return this.learnExactVersion(e);let n=await this.cache.getPinnedExact(e,t);if(n){if(this.semver.isExactVersion(n))return n;console.debug("[typebulb] cached version for",e,"is not exact (",n,"); re-resolving from registry")}let s=await A(()=>this.cdn.fetchVersionsIndex(e));if(s?.versions?.length){let i=this.selectVersionFromIndex(s.versions,t,s.distTags);if(i){if(this.semver.isExactVersion(i))return await this.cache.setPinnedExact(e,t,i),i}else{console.debug("[typebulb] refreshing version cache for",e,"(",t,"not in cached set \u2014 likely a new release)"),await this.cache.invalidateVersionsCache(e);let a=await A(()=>this.cdn.fetchVersionsIndex(e));if(a?.versions?.length){let c=this.selectVersionFromIndex(a.versions,t,a.distTags);if(c&&this.semver.isExactVersion(c))return await this.cache.setPinnedExact(e,t,c),c}}}let o=await this.cdn.resolveExactVersion(`${e}@${t}`);if(o&&this.semver.isExactVersion(o))return await this.cache.setPinnedExact(e,t,o),o}async effectivePackage(e,t){let n=new y(e),s=n.root(),o=t[s],i=o?await A(()=>this.cache.getPinnedExact(s,o))??await A(()=>this.resolveExactForRoot(s,o)):void 0;return{effectivePackage:i?n.withVersion(i).format():e,root:s,range:o,pinned:i}}};import{init as go,parse as yo}from"es-module-lexer";var ye=class r{constructor(e,t,n,s){this.version=e,this.cdn=t,this.peer=n,this.cache=s}extractImportsSync(e){let t=new Set;for(let n of r.importPatterns){n.lastIndex=0;for(let s of e.matchAll(n))y.isBare(s[1])&&t.add(s[1])}return Array.from(t)}async extractImports(e){let t=new Set,n=s=>{y.isBare(s)&&t.add(s)};try{await go;let[s]=yo(e);s.forEach(o=>n(e.slice(o.s,o.e).trim()))}catch{return this.extractImportsSync(e)}return Array.from(t)}async buildImportMap(e,t,n){let s=(await this.extractImports(e)).filter(u=>!n?.has(y.rootOf(u))),o=[...new Set(s.map(y.rootOf))],i=await Promise.all(o.map(async u=>({name:u,version:await this.resolveVersion(u,t)}))),{allRoots:a,flags:c,autoAddedPeers:l}=await this.peer.resolve(i,u=>this.resolveVersion(u,t)),d=this.buildEntries([...s,...l.map(u=>u.name)],a,c,t);return{importMap:{imports:Object.fromEntries(d)},prefetchUrls:d.map(([,u])=>u)}}async resolveVersion(e,t){let n=t[e],s=n?`${e}@${n}`:e,o=await this.version.resolveExactForRoot(e,n);if(!o){let i=await A(()=>this.cdn.pinEsmUrl(s));if(!i)throw new Error(`Cannot resolve ${s}: no matching version is published (the package or version may not exist, or the registry was unreachable).`);o=y.versionFromUrl(i),o&&n&&await A(()=>this.cache.setPinnedExact(e,n,o))}if(!o)throw new Error(`Cannot resolve ${s}: no concrete version found.`);return o}buildEntries(e,t,n,s){let o=new Map(t.map(g=>[g.name,g])),i=g=>{let v=o.get(y.rootOf(g));return new y(g).withPreferredVersion(v.version,s[v.name]).format()},a=new Set([...n.entries()].filter(([,g])=>g.isPeerRoot||g.isSharedDep).map(([g])=>g)),c=new Set(e.filter(g=>g!==y.rootOf(g)).map(y.rootOf)),l=[],d=new Set,u=new Set(e.filter(g=>g===y.rootOf(g))),f=new Set;for(let g of e){let v=y.rootOf(g),$=o.get(v),{isPeerRoot:O,hasPeers:E,isSharedDep:T}=n.get(v),p=c.has(v),h=g!==v,x=!(O||T)&&(p||!E),w=this.singletonDepsOf($,a),V=h&&u.has(v);V&&f.add(v);let se=V?[...w,v]:w.length?w:void 0;l.push([g,this.cdn.buildEsmUrl(i(g),{bundle:x,external:se})]),d.add(g)}let m=new Set([...a,...f]);for(let g of m)o.has(g)&&(d.has(g)||l.push([g,this.cdn.buildEsmUrl(i(g),{})]),l.push([`${g}/`,`${this.cdn.esmHost}/${i(g)}/`]));return l}singletonDepsOf(e,t){return[...new Set([...je(e.meta),...er(e.meta)])].filter(n=>t.has(n))}};ye.importPatterns=[/\bimport\s+(?:[^'";]*?from\s*)?['"]([^'"]+)['"]/g,/\bexport\s+[^'";]*?from\s*['"]([^'"]+)['"]/g];import{gt as tn,satisfies as bo,maxSatisfying as tr,major as wo,prerelease as vo,rsort as xo,valid as So}from"semver";var dt=class{cmp(e,t){return e===t?0:tn(e,t)?1:tn(t,e)?-1:0}satisfies(e,t){return!e||!e.trim()?!0:!!bo(t,e,{includePrerelease:!0})}pickMaxSatisfying(e,t){if(!e?.length)return;let n=tr(e,t,{includePrerelease:!0});return n===null?void 0:n}pickLatest(e){return e?.length?xo(e)[0]:void 0}selectBestVersion(e,t){if(!e?.length)return;let n=t?.range?.trim()||"*",s=t?.preferStable??!0,o=t?.distTags?.latest;if(o&&e.includes(o)&&this.satisfies(n,o))return o;if(s){let a=tr(e,n,{includePrerelease:!1});if(a)return a}return tr(e,n,{includePrerelease:!0})??void 0}majorOf(e){return wo(e)}isPrerelease(e){return vo(e)!==null}isExactVersion(e){return So(e)!==null}},oe=new dt;function rn(r,e){let t=new Me(r,e),n=new Fe(t),s=new Ne(r,t,oe);return{packageService:new ye(s,t,n,r),versionResolver:s,cdnClient:t,peerResolver:n}}import*as bn from"fs/promises";import*as U from"path";var rr=[{name:"es5"},{name:"es2015.core"},{name:"es2015.collection"},{name:"es2015.promise"},{name:"es2015.iterable"},{name:"es2015.symbol"},{name:"es2015.symbol.wellknown"},{name:"es2015.generator"},{name:"es2015.proxy"},{name:"es2015.reflect"},{name:"es2016.array.include"},{name:"es2016.intl"},{name:"es2017.object"},{name:"es2017.string"},{name:"es2017.sharedmemory"},{name:"es2017.typedarrays"},{name:"es2017.date"},{name:"es2017.intl"},{name:"es2018.asynciterable"},{name:"es2018.asyncgenerator"},{name:"es2018.promise"},{name:"es2018.regexp"},{name:"es2018.intl"},{name:"es2019.array"},{name:"es2019.object"},{name:"es2019.string"},{name:"es2019.symbol"},{name:"es2019.intl"},{name:"es2020.bigint"},{name:"es2020.promise"},{name:"es2020.string"},{name:"es2020.sharedmemory"},{name:"es2020.date"},{name:"es2020.number"},{name:"es2020.symbol.wellknown"},{name:"es2020.intl"},{name:"es2021.promise"},{name:"es2021.string"},{name:"es2021.weakref"},{name:"es2021.intl"},{name:"es2022.array"},{name:"es2022.object"},{name:"es2022.error"},{name:"es2022.string"},{name:"es2022.regexp"},{name:"es2022.intl"},{name:"es2023.array"},{name:"es2023.collection"},{name:"es2023.intl",since:"5.5"},{name:"es2024.arraybuffer",since:"5.5"},{name:"es2024.collection",since:"5.5"},{name:"es2024.object",since:"5.5"},{name:"es2024.promise",since:"5.5"},{name:"es2024.regexp",since:"5.5"},{name:"es2024.sharedmemory",since:"5.5"},{name:"es2024.string",since:"5.5"},{name:"esnext.array",since:"5.5"},{name:"esnext.collection"},{name:"esnext.decorators"},{name:"esnext.disposable"},{name:"esnext.error",since:"5.5"},{name:"esnext.float16",since:"5.5"},{name:"esnext.iterator",since:"5.5"},{name:"esnext.object"},{name:"esnext.promise"},{name:"esnext.sharedmemory",since:"5.5"},{name:"esnext.intl"}],nr=[{name:"dom"},{name:"dom.iterable"},{name:"dom.asynciterable"}];var nn=`
99
99
  /**
100
100
  * Get raw data chunk from the Data tab.
101
101
  * @param index - Chunk index (0-based). Separate chunks with 2 blank lines.
@@ -106,7 +106,7 @@ Examples:
106
106
  * @param index - Chunk index (0-based)
107
107
  * @throws If chunk is not valid JSON/JSON-ish
108
108
  */
109
- json<T = unknown>(index: number): T;`,rn=`
109
+ json<T = unknown>(index: number): T;`,sn=`
110
110
  /**
111
111
  * Get the insight data produced by the inference layer.
112
112
  *
@@ -115,7 +115,7 @@ Examples:
115
115
  *
116
116
  * @returns The parsed insight JSON, or undefined if no insight is available
117
117
  */
118
- insight<T = unknown>(): T | undefined;`,nn=`
118
+ insight<T = unknown>(): T | undefined;`,on=`
119
119
  /**
120
120
  * General-purpose AI call.
121
121
  *
@@ -132,7 +132,7 @@ Examples:
132
132
  model?: string;
133
133
  /** Enable/disable web search. Default: on for BYOK, always off for free model. */
134
134
  webSearch?: boolean;
135
- }): Promise<{ text: string }>;`,sn=`
135
+ }): Promise<{ text: string }>;`,an=`
136
136
  /**
137
137
  * Returns AI models available to the current user.
138
138
  * Models are filtered by the user's configured API keys.
@@ -147,7 +147,7 @@ Examples:
147
147
  friendlyName: string;
148
148
  /** Provider display name, e.g. "Anthropic" */
149
149
  providerName: string;
150
- }>>;`,vo="\n /**\n * The bulb's theme override (`<html data-theme>`).\n *\n * - Get: the current override \u2014 `'dark'` | `'light'`, or `undefined` when\n * following the OS preference.\n * - Set `'dark'`/`'light'` to force and persist it (per-bulb); set\n * `undefined` to clear the override and follow the OS again.\n *\n * Drives `<html data-theme>`, so render off `html[data-theme=\"\u2026\"]` selectors\n * (or observe the attribute) rather than reading `tb.theme`.\n */\n theme: 'light' | 'dark' | undefined;",on=`
150
+ }>>;`,Po="\n /**\n * The bulb's theme override (`<html data-theme>`).\n *\n * - Get: the current override \u2014 `'dark'` | `'light'`, or `undefined` when\n * following the OS preference.\n * - Set `'dark'`/`'light'` to force and persist it (per-bulb); set\n * `undefined` to clear the override and follow the OS again.\n *\n * Drives `<html data-theme>`, so render off `html[data-theme=\"\u2026\"]` selectors\n * (or observe the attribute) rather than reading `tb.theme`.\n */\n theme: 'light' | 'dark' | undefined;",cn=`
151
151
  /**
152
152
  * The mode this bulb is running in.
153
153
  *
@@ -157,7 +157,7 @@ Examples:
157
157
  * - \`'embedded'\` \u2014 Running as a bulb embedded inside another bulb (sandboxed,
158
158
  * client-only: AI, filesystem, and server RPC are unavailable)
159
159
  */
160
- mode: 'local' | 'editor' | 'published' | 'embedded';`,an=`
160
+ mode: 'local' | 'editor' | 'published' | 'embedded';`,ln=`
161
161
  /**
162
162
  * Local filesystem access (CLI only).
163
163
  *
@@ -171,7 +171,7 @@ Examples:
171
171
  readBytes(path: string): Promise<Uint8Array>;
172
172
  /** Write text or raw bytes to a file. Creates parent directories if needed. */
173
173
  write(path: string, content: string | Uint8Array): Promise<boolean>;
174
- };`,xo=`
174
+ };`,Eo=`
175
175
  /**
176
176
  * Server-side function proxy. The built-in \`log\` prints to CLI stdout
177
177
  * (falls back to console.log on web). On the server side, this object only
@@ -179,7 +179,7 @@ Examples:
179
179
  */
180
180
  server: {
181
181
  log(...args: any[]): Promise<void>;
182
- };`,So=`
182
+ };`,Ro=`
183
183
  /**
184
184
  * Async value inspector for tensor-like objects.
185
185
  *
@@ -246,7 +246,7 @@ Examples:
246
246
  *
247
247
  * @returns The full canonical URL
248
248
  */
249
- url(): Promise<string>;`,Po=`
249
+ url(): Promise<string>;`,ko=`
250
250
  /**
251
251
  * Server-side function proxy.
252
252
  *
@@ -254,23 +254,23 @@ Examples:
254
254
  * \`tb.server.log(...)\` is a built-in that prints to CLI stdout (falls back to console.log on web).
255
255
  * User exports override built-ins of the same name.
256
256
  */
257
- server: Record<string, (...args: any[]) => Promise<any>>;`,nr=`
257
+ server: Record<string, (...args: any[]) => Promise<any>>;`,sr=`
258
258
  /**
259
259
  * Typebulb utilities namespace.
260
260
  * Type \`tb.\` to discover available helpers.
261
261
  */
262
- declare const tb: {${tn}${So}${rn}${Po}${nn}${an}${sn}${vo}${on}
262
+ declare const tb: {${nn}${Ro}${sn}${ko}${on}${ln}${an}${Po}${cn}
263
263
  };
264
- `,sr=`
264
+ `,or=`
265
265
  /**
266
266
  * Typebulb utilities namespace (server-side).
267
267
  * Type \`tb.\` to discover available helpers.
268
268
  */
269
- declare const tb: {${tn}${rn}${nn}${an}${xo}${sn}${on}
269
+ declare const tb: {${nn}${sn}${on}${ln}${Eo}${an}${cn}
270
270
  };
271
- `;var ie=class{constructor(e){this.store=e}async isNegative(e){let t=await dt(()=>this.store.get(e));return!!t&&t.until>Date.now()}async recordNegative(e){let n=((await dt(()=>this.store.get(e)))?.attempts||0)+1;await dt(()=>this.store.set(e,{until:Date.now()+Eo(n),attempts:n}))}async clearNegative(e){await dt(()=>this.store.delete(e))}};function Eo(r){return Math.min(9e5*Math.pow(2,Math.max(0,r-1)),864e5)}async function dt(r){try{return await r()}catch{return}}import Co from"p-limit";import{resolve as cn}from"resolve.exports";var be=class{constructor(e){this.fetchDts=e}fetchDtsText(e){return this.tryUrls([e])}async tryUrls(e){for(let t of e){let n=await this.fetchDts(t);if(n&&(this.looksLikeDts(n.dts)||/\.(d\.ts|d\.mts)(?:[?#].*)?$/i.test(n.url)||/[?&]dts(?:[&#]|$)/i.test(n.url)))return n}}looksLikeDts(e){return/^\s*export\s*\{\s*\}\s*;?\s*$/m.test(e)?!0:/declare\s+(module|namespace|class|interface|function|const|var|let)/.test(e)||/interface\s+\w+/.test(e)||/type\s+\w+\s*=/.test(e)}};var Z={maxRelativeTypeRefs:500,maxBareDeps:8,maxBareDepth:3,prefetchConcurrency:4,negativeTtlMs:1e4},Ne=["index.d.ts","index.d.mts"],Le=/\.d\.(ts|mts)$/i;function or(r){if(Le.test(r))return!0;try{return new URL(r,"file://").search.includes("dts")}catch{return r.includes("?")&&r.includes("dts")}}function ut(r){return[`${r}.d.ts`,`${r}.d.mts`]}async function Ue(r,{retries:e=2,timeoutMs:t=15e3,init:n}={}){for(let s=0;s<=e;s++){let o=new AbortController,i=setTimeout(()=>o.abort(),t);try{let a=await fetch(r,{...n,signal:o.signal});if(Ro(a.status)&&s<e)continue;return a}catch{if(s<e)continue;return}finally{clearTimeout(i)}}}function Ro(r){return r===408||r===429||r>=500&&r<600}var We=class extends be{constructor(e,t){super(e),this.cdnClient=t}async loadPackageAtVersionedRoot(e,t){let n=this.cdnClient.packageJson(new y({name:e,version:t})),s=await Ue(n);if(!s?.ok)return;let o;try{o=await s.json()}catch{return}if(o)return{pkg:o,baseDir:this.cdnClient.baseDir(new y({name:e,version:t??o.version})),version:t}}extractPathFromResult(e){if(typeof e=="string")return e;if(Array.isArray(e))return e.find(t=>typeof t=="string")}async tryUntilSuccess(e,t){for(let n of e){let s=await t(n);if(s)return s}}async resolveFromSelected(e,t){if(e.kind==="types"){let s=this.cdnClient.normalizeRelative(e.path);if(!s||s==="/"||s===".")return this.tryUntilSuccess([...Ne],t);if(!Le.test(s)){let o=await this.tryUntilSuccess(this.declarationCandidatesFor(s),t);if(o)return o}return t(s)}let n=this.declarationCandidatesFor(e.path);return this.tryUntilSuccess([...Ne,...n],t)}toResolutionResult(e){return{kind:Le.test(e)?"types":"probe",path:e}}resolveExportsPath(e,t){let n=t||".",s=e;try{let o=this.extractPathFromResult(cn(s,n,{conditions:["types"]}));if(o)return o}catch{}try{return this.extractPathFromResult(cn(s,n,{browser:!0,conditions:["import","default","module","browser","node"]}))}catch{return}}async resolve(e){try{let t=y.parse(e),{pkg:n,baseDir:s}=await this.loadPackageAtVersionedRoot(t.name,t.version)||{};if(!n||!s)return;let o={name:t.name,version:t.version},i=new y(o).format(),a=new y({...o,subpath:t.subpath}).format(),c=u=>this.fetchCandidateFrom(s,t.name,u);if(t.subpath){let u=this.cdnClient.ensureLeadingDotSlash(t.subpath),f=this.resolveExportsPath(n,u);if(f){let g=await this.resolveFromSelected(this.toResolutionResult(f),c);if(g)return{...g,resolvedPkg:a}}let m=await this.tryUntilSuccess(this.declarationCandidatesFor(u),c);if(m)return{...m,resolvedPkg:a}}let l=n.types??n.typings;if(l){let u=await this.resolveFromSelected({kind:"types",path:l},c);if(u)return{...u,resolvedPkg:i}}let d=this.resolveExportsPath(n,".");if(d){let u=await this.resolveFromSelected(this.toResolutionResult(d),c);if(u)return{...u,resolvedPkg:i}}return}catch{return}}async fetchCandidateFrom(e,t,n){let s=this.cdnClient.normalizeRelative(n),o=new URL(s,e).toString(),i=await this.fetchDtsText(o);return i?{dts:i.dts,url:i.url,resolvedPkg:t}:void 0}declarationCandidatesFor(e){if(!e||e==="./"||e==="/")return[...Ne];let t=e.replace(/\.(mjs|cjs|js|mts|cts|ts)$/i,""),n=ut(t),s=t.endsWith("/")?t:`${t}/`;return n.push(...ut(`${s}index`)),n}};import{gunzipSync as ko}from"fflate";var we=class{async fetchAndExtract(e,t){let n=this.getTarballUrl(e,t),s=await Ue(n,{timeoutMs:3e4});if(!s?.ok)return new Map;let o=new Uint8Array(await s.arrayBuffer());return this.extractDtsFiles(o)}getTarballUrl(e,t){return`https://registry.npmjs.org/${e.replace("/","%2F")}/-/${e.split("/").pop()}-${t}.tgz`}normalizeTarPath(e){let t=e.replace(/^package\//,""),n=t.indexOf("/");return n>0?t.substring(n+1):t}extractDtsFiles(e){let t=new Map;try{let n=ko(e),s=new TextDecoder("utf-8"),o=0;for(;o<n.length-512;){let i=n.slice(o,o+512);if(i[0]===0)break;let a=i.slice(0,100),c=a.indexOf(0),l=s.decode(a.slice(0,c>0?c:100)).trim(),d=i.slice(124,136),u=s.decode(d).trim().replace(/\0/g,""),f=parseInt(u,8)||0,m=String.fromCharCode(i[156]);if(o+=512,(m==="0"||m==="\0")&&(l.endsWith(".d.ts")||l.endsWith(".d.mts"))){let g=n.slice(o,o+f);t.set(this.normalizeTarPath(l),s.decode(g))}o+=Math.ceil(f/512)*512}}catch{}return t}},To=new we;var Je=class extends be{constructor(e,t,n,s=new we){super(e),this.cdnClient=t,this.cache=n,this.tarballFetcher=s}typesNameCandidates(e){let t=e.startsWith("@")?e.slice(1).replace("/","__"):e;return t.includes(".")?[t,t.split(".").join("-"),t.split(".").join("")]:[t]}selectTypesVersion(e,t,n){try{if(n){let o=oe.majorOf(n),i=e.filter(a=>oe.majorOf(a)===o);if(i.length)return i.sort((a,c)=>oe.cmp(c,a))[0]}let s=t?.latest;return s&&e.includes(s)?s:e[0]}catch{return e[0]}}async fetchFromVersionedRoot(e,t){let n=new y(e),s=n.version;if(!s)return;let o;try{o=await this.tarballFetcher.fetchAndExtract(n.name,s)}catch{return}if(!o||o.size===0)return;for(let[a,c]of o.entries()){let l=this.cdnClient.file(e,a);try{await this.cache.setCachedFile(l,c)}catch{}}let i=t.subpath?[t.subpath+".d.ts",t.subpath+"/index.d.ts"]:["index.d.ts"];for(let a of i){let c=o.get(a);if(c)return{dts:c,url:this.cdnClient.file(e,a),resolvedPkg:t.subpath?new y(t).format():t.name}}}async resolve(e){let t=y.parse(e);if(t.name)for(let n of this.typesNameCandidates(t.name)){let s=`@types/${n}`,o;try{o=await this.cdnClient.fetchVersionsIndex(s)}catch{continue}if(!o?.versions?.length)continue;let i=this.selectTypesVersion(o.versions,o.distTags,t.version),a=await this.fetchFromVersionedRoot(`${s}@${i}`,t);if(a)return a}}};var He=class{collectRelativeTypeRefs(e){return this.collectRefs(e).filter(t=>t.startsWith("./")||t.startsWith("../"))}collectBareModuleRefs(e){return this.collectRefs(e).filter(t=>this.isBare(t))}collectRefs(e){let t=new Set,n=(s,o)=>(t.add(s[o]),null);return this.matchAll(e,/(import|export)\s+[^'"\n]*from\s*['"]([^'"\n]+)['"]/,s=>n(s,2)),this.matchAll(e,/export\s*\*\s*from\s*['"]([^'"\n]+)['"]/,s=>n(s,1)),Array.from(t)}matchAll(e,t,n){let s=[];try{let o=new RegExp(t.source,"g"),i;for(;i=o.exec(e);){let a=n(i);a!==null&&s.push(a)}}catch{}return s}isBare(e){return!(e.startsWith("./")||e.startsWith("../")||e.startsWith("file:")||e.startsWith("http://")||e.startsWith("https://"))}};var ln="file:///node_modules",Ve=class{constructor(){this.epoch=0,this.listeners=new Set}getEpoch(){return this.epoch}bumpEpoch(){this.epoch+=1;for(let e of this.listeners)try{e(this.epoch)}catch{}return this.epoch}onEpochChange(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}epochDir(){return`__tsepoch_${this.epoch}`}pathForMain(e){return`${ln}/${this.epochDir()}/${e}/index.d.ts`}pathFor(e,t){let n=_o(t);return`${ln}/${this.epochDir()}/${e}/${n}`}};function _o(r){let e=r||"";return e.startsWith("./")?e.slice(2):e.replace(/^\/+/,"")}import{LRUCache as Ao}from"lru-cache";function ir(r){let e=new Ao({ttl:1e4,max:500}),t=new Map;return async function(s){try{if(await r.isNegative(s))return;let o=e.get(s);if(o&&Date.now()-o<1e4)return;let i=await r.getCachedFile(s);if(i)return{dts:i,url:s};let a=t.get(s);if(a)return a;let c=(async()=>{let l=await fetch(s,{cache:"no-store"});if(!l.ok){l.status===404&&(e.set(s,Date.now()),await r.recordNegative(s));return}let d=await l.text(),u=l.url||s;return await r.clearNegative(s),await r.setCachedFile(u,d),{dts:d,url:u}})();return t.set(s,c),await c.finally(()=>t.delete(s))}catch{return}}}var pt=class{constructor(e){this.inFlight=new Map,this.scanner=new He,this.cache=e.cache,this.cdnClient=e.cdnClient,this.versionResolver=e.versionResolver,this.packageService=e.packageService,this.fetchDts=ir(e.cache),this.typescriptProvider=new We(this.fetchDts,e.cdnClient),this.definitelyTypedProvider=new Je(this.fetchDts,e.cdnClient,e.cache),this.virtualFs=new Ve}withInFlight(e,t){let n=this.inFlight.get(e);if(n)return n;let s=t().finally(()=>this.inFlight.delete(e));return this.inFlight.set(e,s),s}invalidate(){this.virtualFs.bumpEpoch(),this.inFlight.clear()}capArray(e,t){return e.length<=t?e:e.slice(0,t)}pushFileIfNew(e,t,n){e.some(s=>s.path===t)||e.push({path:t,content:n})}createStubDef(e){let t=this.virtualFs.pathForMain(e);return{pkg:e,mainPath:t,files:[{path:t,content:"export const _shim: any; export default _shim;"}],shims:[{module:e,path:t}]}}async trySubpathWithRootFallback(e,t){let n=new y(e);return n.subpath?this.fetchRootDts(n.name,t):void 0}async fetchViaProviders(e){for(let t of[this.typescriptProvider,this.definitelyTypedProvider])try{let n=await t.resolve(e);if(n?.dts)return n}catch{}}subpathsMatch(e,t){return new y(e).subpath===new y(t).subpath}async fetchRootDts(e,t){let{effectivePackage:n,root:s,pinned:o}=await this.versionResolver.effectivePackage(e,t),i=await this.cache.getCachedDts(n);if(i?.content){let c=i.url??this.cdnClient.file(o?`${s}@${o}`:s,"index.d.ts");return{dts:i.content,url:c,resolvedPkg:n}}let a;try{a=await this.fetchViaProviders(n)}catch{return}if(!(!a?.dts||!a.url)){try{await this.cache.setCachedFile(a.url,a.dts)}catch{}if(this.subpathsMatch(n,a.resolvedPkg||n)){try{await this.cache.setCachedDts(n,a.dts,a.url)}catch{}return a}}}extractPackageRootUrl(e){let t=e.pathname.match(/^(.+@[^/]+\/)/);return t?new URL(t[1],e.origin):new URL("./",e)}toVirtualPath(e,t,n){let s=t.pathname.startsWith(e.pathname)?t.pathname.slice(e.pathname.length):`__deps__/${encodeURIComponent(t.toString()).replace(/%/g,"_")}.d.ts`;return this.virtualFs.pathFor(n,s)}computeEntryPath(e,t){if(!e)return{mainPath:this.virtualFs.pathForMain(t),packageRootUrl:void 0};let n=new URL(e),s=this.extractPackageRootUrl(n);return{mainPath:this.toVirtualPath(s,n,t),packageRootUrl:s}}async expandRelativeRefs(e,t,n,s,o=new Set,i){if(!o.has(t)&&(o.add(t),!(o.size>Z.maxRelativeTypeRefs)))try{let a=new URL(t),c=new URL("./",a);i??(i=this.extractPackageRootUrl(a));let l=this.capArray(this.scanner.collectRelativeTypeRefs(e),Z.maxRelativeTypeRefs);for(let d of l)await this.tryRelativeRef(d,c,i,n,s,o)}catch{}}async tryRelativeRef(e,t,n,s,o,i){try{let a=new URL(e,t),c=a.pathname+a.search,l=or(c)?[c]:this.typescriptProvider.declarationCandidatesFor(c);for(let d of l){let f=new URL(d,a).toString();if(i.has(f))return;let m=await this.fetchDts(f);if(m?.dts){let g=this.toVirtualPath(n,new URL(m.url),s);this.pushFileIfNew(o,g,m.dts),await this.expandRelativeRefs(m.dts,m.url,s,o,i,n);return}}}catch{}}isDifferentPackage(e,t){return e===t?!1:new y(e).name!==new y(t).name}ambientlyDeclares(e,t){for(let n of e.matchAll(/declare\s+module\s+['"]([^'"]+)['"]/g)){let s=n[1];if(s===t||s.endsWith("/*")&&t.startsWith(s.slice(0,-1)))return!0}return!1}markFileAmbient(e,t){let n=e.find(s=>s.path===t);n&&(n.ambient=!0)}async prefetchBareDeps(e,t,n,s,o){try{let i=this.capArray(this.scanner.collectBareModuleRefs(e),Z.maxBareDeps).filter(l=>this.isDifferentPackage(l,t));if(!i.length)return;let a=new Set([t]),c=Co(Z.prefetchConcurrency);await Promise.all(i.map(l=>c(()=>this.prefetchBareDepsRecursive(l,n,s,Z.maxBareDepth,a,o).catch(()=>{}))))}catch{}}async prefetchBareDepsRecursive(e,t,n,s,o,i){if(s<=0||o.has(e))return;o.add(e);let a=await this.fetchRootDts(e,i);if(!a?.dts)return;let c=a.resolvedPkg||e,l=this.virtualFs.pathForMain(c);this.pushFileIfNew(t,l,a.dts),this.ambientlyDeclares(a.dts,e)?this.markFileAmbient(t,l):n.push({module:e,path:l}),a.url&&await this.expandRelativeRefs(a.dts,a.url,c,t);let d=this.capArray(this.scanner.collectBareModuleRefs(a.dts),Z.maxBareDeps).filter(u=>!o.has(u));for(let u of d)await this.prefetchBareDepsRecursive(u,t,n,s-1,o,i)}async resolve(e,t,n){let s=await this.packageService.extractImports(e),o=n?[...s,...n]:s;return(await Promise.all(o.map(a=>this.resolveOne(a,t)))).filter(a=>!!a)}async resolveOne(e,t){let{effectivePackage:n}=await this.versionResolver.effectivePackage(e,t);return this.withInFlight(n,async()=>{let s=await this.fetchRootDts(e,t)??await this.trySubpathWithRootFallback(e,t);return s?this.buildDefFromContent(e,s,s.resolvedPkg||e,t):this.createStubDef(e)})}async buildDefFromContent(e,t,n,s){let{dts:o,url:i,resolvedPkg:a}=t,c=new y(a||n),l=c.version?`${c.name}@${c.version}`:c.name,{mainPath:d,packageRootUrl:u}=this.computeEntryPath(i,l),f=[{path:d,content:o}],m=[];i&&await this.expandRelativeRefs(o,i,l,f,void 0,u);let g=f.map(E=>E.content).join(`
272
- `);await this.prefetchBareDeps(g,l,f,m,s);let v=c.format(),$=e===v?[e]:[e,v],O=$.some(E=>this.ambientlyDeclares(o,E));return O?this.markFileAmbient(f,d):m.push(...$.map(E=>({module:E,path:d}))),{pkg:e,mainPath:d,files:f,shims:m,ambient:O}}};function ar(r){return new pt(r)}import*as z from"fs/promises";import*as q from"path";import*as pn from"os";import*as cr from"fs/promises";import*as dn from"crypto";function L(r){return dn.createHash("sha1").update(r).digest("hex")}async function ae(r){try{return JSON.parse(await cr.readFile(r,"utf8"))}catch{return}}async function ft(r){try{return await cr.readFile(r,"utf8")}catch{return}}var un=1,ee=q.join(pn.homedir(),".typebulb","cache"),ze=q.join(ee,"packages"),qe=q.join(ee,"proxy"),mt=q.join(ee,"dts"),Io=q.join(ee,"emit"),lr;function S(){return lr||(lr=$o()),lr}function ht(r,e){return q.join(Io,L(r),e)}async function $o(){await z.mkdir(ee,{recursive:!0});let r=q.join(ee,"version.json");if((await Oo(r))?.version===un)return;let t=await z.readdir(ee).catch(()=>[]);await Promise.all(t.map(n=>z.rm(q.join(ee,n),{recursive:!0,force:!0}))),await z.writeFile(r,JSON.stringify({version:un})+`
273
- `,"utf8")}async function Oo(r){try{let e=await z.readFile(r,"utf8");return JSON.parse(e)}catch{return}}import*as te from"fs/promises";import*as fn from"path";async function F(r,e){await te.mkdir(fn.dirname(r),{recursive:!0});let t=`${r}.tmp-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;await te.writeFile(t,e,"utf8"),await te.rename(t,r).catch(async n=>{throw await te.rm(t,{force:!0}).catch(()=>{}),n})}var ve=class{constructor(e){this.filePath=e}mem;loadPromise;load(){return this.mem?Promise.resolve(this.mem):(this.loadPromise||(this.loadPromise=ae(this.filePath).then(e=>(this.mem=new Map(Object.entries(e??{})),this.mem))),this.loadPromise)}async get(e){return(await this.load()).get(e)}async set(e,t){let n=await this.load();n.set(e,t),await this.persist(n)}async delete(e){let t=await this.load();t.delete(e)&&await this.persist(t)}async persist(e){await F(this.filePath,JSON.stringify(Object.fromEntries(e)))}};var dr=U.join(ze,"indexes"),mn=U.join(ze,"pinned"),Do=U.join(ze,"meta"),Bo=U.join(ze,"negative.json"),xe=Symbol("missing"),yt=class{pinnedMem=new Map;indexMem=new Map;metaMem=new Map;negativeCache=new ie(new ve(Bo));async getPinnedExact(e,t){let n=`${e}@${t}`,s=this.pinnedMem.get(n);if(s!==void 0)return s===xe?void 0:s;await S();let o=await ft(U.join(mn,L(n)+".txt"));return this.pinnedMem.set(n,o??xe),o}async setPinnedExact(e,t,n){let s=`${e}@${t}`;this.pinnedMem.set(s,n),await S(),await F(U.join(mn,L(s)+".txt"),n)}async getIndex(e){let t=this.indexMem.get(e);if(t!==void 0)return t===xe?void 0:t;await S();let n=await ae(U.join(dr,gt(e)+".json"));return this.indexMem.set(e,n??xe),n}async setIndex(e,t,n){let s={versions:t,distTags:n,updatedAt:Date.now()};this.indexMem.set(e,s),await S(),await F(U.join(dr,gt(e)+".json"),JSON.stringify(s))}async invalidateVersionsCache(e){this.indexMem.delete(e),await gn.rm(U.join(dr,gt(e)+".json"),{force:!0})}async isNegative(e){return await S(),this.negativeCache.isNegative(e)}async recordNegative(e){await S(),await this.negativeCache.recordNegative(e)}async clearNegative(e){await this.negativeCache.clearNegative(e)}async getMeta(e,t){let n=`${e}@${t}`,s=this.metaMem.get(n);if(s!==void 0)return s===xe?void 0:s;await S();let o=await ae(hn(e,t));return this.metaMem.set(n,o??xe),o}async setMeta(e,t,n,s,o){let i={dependencies:n,peerDependencies:s,peerDependenciesMeta:o,updatedAt:Date.now()};this.metaMem.set(`${e}@${t}`,i),await S(),await F(hn(e,t),JSON.stringify(i))}};function hn(r,e){return U.join(Do,gt(r),encodeURIComponent(e)+".json")}function gt(r){return r.replace(/\//g,"__")}var yn={async getJson(r){try{let e=await fetch(r,{redirect:"follow"});return e.ok?await e.json():void 0}catch{return}},async head(r){try{let e=await fetch(r,{method:"HEAD",redirect:"follow"});return{ok:e.ok,url:e.url}}catch{return}}};var Mo=new yt,{packageService:bt,versionResolver:bn,cdnClient:wn,peerResolver:Hl}=en(Mo,yn);var vn=`
271
+ `;var ie=class{constructor(e){this.store=e}async isNegative(e){let t=await ut(()=>this.store.get(e));return!!t&&t.until>Date.now()}async recordNegative(e){let n=((await ut(()=>this.store.get(e)))?.attempts||0)+1;await ut(()=>this.store.set(e,{until:Date.now()+To(n),attempts:n}))}async clearNegative(e){await ut(()=>this.store.delete(e))}};function To(r){return Math.min(9e5*Math.pow(2,Math.max(0,r-1)),864e5)}async function ut(r){try{return await r()}catch{return}}import Oo from"p-limit";import{resolve as dn}from"resolve.exports";var be=class{constructor(e){this.fetchDts=e}fetchDtsText(e){return this.tryUrls([e])}async tryUrls(e){for(let t of e){let n=await this.fetchDts(t);if(n&&(this.looksLikeDts(n.dts)||/\.(d\.ts|d\.mts)(?:[?#].*)?$/i.test(n.url)||/[?&]dts(?:[&#]|$)/i.test(n.url)))return n}}looksLikeDts(e){return/^\s*export\s*\{\s*\}\s*;?\s*$/m.test(e)?!0:/declare\s+(module|namespace|class|interface|function|const|var|let)/.test(e)||/interface\s+\w+/.test(e)||/type\s+\w+\s*=/.test(e)}};var Z={maxRelativeTypeRefs:500,maxBareDeps:8,maxBareDepth:3,prefetchConcurrency:4,negativeTtlMs:1e4},Le=["index.d.ts","index.d.mts"],Ue=/\.d\.(ts|mts)$/i;function ir(r){if(Ue.test(r))return!0;try{return new URL(r,"file://").search.includes("dts")}catch{return r.includes("?")&&r.includes("dts")}}function pt(r){return[`${r}.d.ts`,`${r}.d.mts`]}async function We(r,{retries:e=2,timeoutMs:t=15e3,init:n}={}){for(let s=0;s<=e;s++){let o=new AbortController,i=setTimeout(()=>o.abort(),t);try{let a=await fetch(r,{...n,signal:o.signal});if(_o(a.status)&&s<e)continue;return a}catch{if(s<e)continue;return}finally{clearTimeout(i)}}}function _o(r){return r===408||r===429||r>=500&&r<600}var Je=class extends be{constructor(e,t){super(e),this.cdnClient=t}async loadPackageAtVersionedRoot(e,t){let n=this.cdnClient.packageJson(new y({name:e,version:t})),s=await We(n);if(!s?.ok)return;let o;try{o=await s.json()}catch{return}if(o)return{pkg:o,baseDir:this.cdnClient.baseDir(new y({name:e,version:t??o.version})),version:t}}extractPathFromResult(e){if(typeof e=="string")return e;if(Array.isArray(e))return e.find(t=>typeof t=="string")}async tryUntilSuccess(e,t){for(let n of e){let s=await t(n);if(s)return s}}async resolveFromSelected(e,t){if(e.kind==="types"){let s=this.cdnClient.normalizeRelative(e.path);if(!s||s==="/"||s===".")return this.tryUntilSuccess([...Le],t);if(!Ue.test(s)){let o=await this.tryUntilSuccess(this.declarationCandidatesFor(s),t);if(o)return o}return t(s)}let n=this.declarationCandidatesFor(e.path);return this.tryUntilSuccess([...Le,...n],t)}toResolutionResult(e){return{kind:Ue.test(e)?"types":"probe",path:e}}resolveExportsPath(e,t){let n=t||".",s=e;try{let o=this.extractPathFromResult(dn(s,n,{conditions:["types"]}));if(o)return o}catch{}try{return this.extractPathFromResult(dn(s,n,{browser:!0,conditions:["import","default","module","browser","node"]}))}catch{return}}async resolve(e){try{let t=y.parse(e),{pkg:n,baseDir:s}=await this.loadPackageAtVersionedRoot(t.name,t.version)||{};if(!n||!s)return;let o={name:t.name,version:t.version},i=new y(o).format(),a=new y({...o,subpath:t.subpath}).format(),c=u=>this.fetchCandidateFrom(s,t.name,u);if(t.subpath){let u=this.cdnClient.ensureLeadingDotSlash(t.subpath),f=this.resolveExportsPath(n,u);if(f){let g=await this.resolveFromSelected(this.toResolutionResult(f),c);if(g)return{...g,resolvedPkg:a}}let m=await this.tryUntilSuccess(this.declarationCandidatesFor(u),c);if(m)return{...m,resolvedPkg:a}}let l=n.types??n.typings;if(l){let u=await this.resolveFromSelected({kind:"types",path:l},c);if(u)return{...u,resolvedPkg:i}}let d=this.resolveExportsPath(n,".");if(d){let u=await this.resolveFromSelected(this.toResolutionResult(d),c);if(u)return{...u,resolvedPkg:i}}return}catch{return}}async fetchCandidateFrom(e,t,n){let s=this.cdnClient.normalizeRelative(n),o=new URL(s,e).toString(),i=await this.fetchDtsText(o);return i?{dts:i.dts,url:i.url,resolvedPkg:t}:void 0}declarationCandidatesFor(e){if(!e||e==="./"||e==="/")return[...Le];let t=e.replace(/\.(mjs|cjs|js|mts|cts|ts)$/i,""),n=pt(t),s=t.endsWith("/")?t:`${t}/`;return n.push(...pt(`${s}index`)),n}};import{gunzipSync as Ao}from"fflate";var we=class{async fetchAndExtract(e,t){let n=this.getTarballUrl(e,t),s=await We(n,{timeoutMs:3e4});if(!s?.ok)return new Map;let o=new Uint8Array(await s.arrayBuffer());return this.extractDtsFiles(o)}getTarballUrl(e,t){return`https://registry.npmjs.org/${e.replace("/","%2F")}/-/${e.split("/").pop()}-${t}.tgz`}normalizeTarPath(e){let t=e.replace(/^package\//,""),n=t.indexOf("/");return n>0?t.substring(n+1):t}extractDtsFiles(e){let t=new Map;try{let n=Ao(e),s=new TextDecoder("utf-8"),o=0;for(;o<n.length-512;){let i=n.slice(o,o+512);if(i[0]===0)break;let a=i.slice(0,100),c=a.indexOf(0),l=s.decode(a.slice(0,c>0?c:100)).trim(),d=i.slice(124,136),u=s.decode(d).trim().replace(/\0/g,""),f=parseInt(u,8)||0,m=String.fromCharCode(i[156]);if(o+=512,(m==="0"||m==="\0")&&(l.endsWith(".d.ts")||l.endsWith(".d.mts"))){let g=n.slice(o,o+f);t.set(this.normalizeTarPath(l),s.decode(g))}o+=Math.ceil(f/512)*512}}catch{}return t}},Co=new we;var He=class extends be{constructor(e,t,n,s=new we){super(e),this.cdnClient=t,this.cache=n,this.tarballFetcher=s}typesNameCandidates(e){let t=e.startsWith("@")?e.slice(1).replace("/","__"):e;return t.includes(".")?[t,t.split(".").join("-"),t.split(".").join("")]:[t]}selectTypesVersion(e,t,n){try{if(n){let o=oe.majorOf(n),i=e.filter(a=>oe.majorOf(a)===o);if(i.length)return i.sort((a,c)=>oe.cmp(c,a))[0]}let s=t?.latest;return s&&e.includes(s)?s:e[0]}catch{return e[0]}}async fetchFromVersionedRoot(e,t){let n=new y(e),s=n.version;if(!s)return;let o;try{o=await this.tarballFetcher.fetchAndExtract(n.name,s)}catch{return}if(!o||o.size===0)return;for(let[a,c]of o.entries()){let l=this.cdnClient.file(e,a);try{await this.cache.setCachedFile(l,c)}catch{}}let i=t.subpath?[t.subpath+".d.ts",t.subpath+"/index.d.ts"]:["index.d.ts"];for(let a of i){let c=o.get(a);if(c)return{dts:c,url:this.cdnClient.file(e,a),resolvedPkg:t.subpath?new y(t).format():t.name}}}async resolve(e){let t=y.parse(e);if(t.name)for(let n of this.typesNameCandidates(t.name)){let s=`@types/${n}`,o;try{o=await this.cdnClient.fetchVersionsIndex(s)}catch{continue}if(!o?.versions?.length)continue;let i=this.selectTypesVersion(o.versions,o.distTags,t.version),a=await this.fetchFromVersionedRoot(`${s}@${i}`,t);if(a)return a}}};var Ve=class{collectRelativeTypeRefs(e){return this.collectRefs(e).filter(t=>t.startsWith("./")||t.startsWith("../"))}collectBareModuleRefs(e){return this.collectRefs(e).filter(t=>this.isBare(t))}collectRefs(e){let t=new Set,n=(s,o)=>(t.add(s[o]),null);return this.matchAll(e,/(import|export)\s+[^'"\n]*from\s*['"]([^'"\n]+)['"]/,s=>n(s,2)),this.matchAll(e,/export\s*\*\s*from\s*['"]([^'"\n]+)['"]/,s=>n(s,1)),Array.from(t)}matchAll(e,t,n){let s=[];try{let o=new RegExp(t.source,"g"),i;for(;i=o.exec(e);){let a=n(i);a!==null&&s.push(a)}}catch{}return s}isBare(e){return!(e.startsWith("./")||e.startsWith("../")||e.startsWith("file:")||e.startsWith("http://")||e.startsWith("https://"))}};var un="file:///node_modules",ze=class{constructor(){this.epoch=0,this.listeners=new Set}getEpoch(){return this.epoch}bumpEpoch(){this.epoch+=1;for(let e of this.listeners)try{e(this.epoch)}catch{}return this.epoch}onEpochChange(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}epochDir(){return`__tsepoch_${this.epoch}`}pathForMain(e){return`${un}/${this.epochDir()}/${e}/index.d.ts`}pathFor(e,t){let n=Io(t);return`${un}/${this.epochDir()}/${e}/${n}`}};function Io(r){let e=r||"";return e.startsWith("./")?e.slice(2):e.replace(/^\/+/,"")}import{LRUCache as $o}from"lru-cache";function ar(r){let e=new $o({ttl:1e4,max:500}),t=new Map;return async function(s){try{if(await r.isNegative(s))return;let o=e.get(s);if(o&&Date.now()-o<1e4)return;let i=await r.getCachedFile(s);if(i)return{dts:i,url:s};let a=t.get(s);if(a)return a;let c=(async()=>{let l=await fetch(s,{cache:"no-store"});if(!l.ok){l.status===404&&(e.set(s,Date.now()),await r.recordNegative(s));return}let d=await l.text(),u=l.url||s;return await r.clearNegative(s),await r.setCachedFile(u,d),{dts:d,url:u}})();return t.set(s,c),await c.finally(()=>t.delete(s))}catch{return}}}var ft=class{constructor(e){this.inFlight=new Map,this.scanner=new Ve,this.cache=e.cache,this.cdnClient=e.cdnClient,this.versionResolver=e.versionResolver,this.packageService=e.packageService,this.fetchDts=ar(e.cache),this.typescriptProvider=new Je(this.fetchDts,e.cdnClient),this.definitelyTypedProvider=new He(this.fetchDts,e.cdnClient,e.cache),this.virtualFs=new ze}withInFlight(e,t){let n=this.inFlight.get(e);if(n)return n;let s=t().finally(()=>this.inFlight.delete(e));return this.inFlight.set(e,s),s}invalidate(){this.virtualFs.bumpEpoch(),this.inFlight.clear()}capArray(e,t){return e.length<=t?e:e.slice(0,t)}pushFileIfNew(e,t,n){e.some(s=>s.path===t)||e.push({path:t,content:n})}createStubDef(e){let t=this.virtualFs.pathForMain(e);return{pkg:e,mainPath:t,files:[{path:t,content:"export const _shim: any; export default _shim;"}],shims:[{module:e,path:t}]}}async trySubpathWithRootFallback(e,t){let n=new y(e);return n.subpath?this.fetchRootDts(n.name,t):void 0}async fetchViaProviders(e){for(let t of[this.typescriptProvider,this.definitelyTypedProvider])try{let n=await t.resolve(e);if(n?.dts)return n}catch{}}subpathsMatch(e,t){return new y(e).subpath===new y(t).subpath}async fetchRootDts(e,t){let{effectivePackage:n,root:s,pinned:o}=await this.versionResolver.effectivePackage(e,t),i=await this.cache.getCachedDts(n);if(i?.content){let c=i.url??this.cdnClient.file(o?`${s}@${o}`:s,"index.d.ts");return{dts:i.content,url:c,resolvedPkg:n}}let a;try{a=await this.fetchViaProviders(n)}catch{return}if(!(!a?.dts||!a.url)){try{await this.cache.setCachedFile(a.url,a.dts)}catch{}if(this.subpathsMatch(n,a.resolvedPkg||n)){try{await this.cache.setCachedDts(n,a.dts,a.url)}catch{}return a}}}extractPackageRootUrl(e){let t=e.pathname.match(/^(.+@[^/]+\/)/);return t?new URL(t[1],e.origin):new URL("./",e)}toVirtualPath(e,t,n){let s=t.pathname.startsWith(e.pathname)?t.pathname.slice(e.pathname.length):`__deps__/${encodeURIComponent(t.toString()).replace(/%/g,"_")}.d.ts`;return this.virtualFs.pathFor(n,s)}computeEntryPath(e,t){if(!e)return{mainPath:this.virtualFs.pathForMain(t),packageRootUrl:void 0};let n=new URL(e),s=this.extractPackageRootUrl(n);return{mainPath:this.toVirtualPath(s,n,t),packageRootUrl:s}}async expandRelativeRefs(e,t,n,s,o=new Set,i){if(!o.has(t)&&(o.add(t),!(o.size>Z.maxRelativeTypeRefs)))try{let a=new URL(t),c=new URL("./",a);i??(i=this.extractPackageRootUrl(a));let l=this.capArray(this.scanner.collectRelativeTypeRefs(e),Z.maxRelativeTypeRefs);for(let d of l)await this.tryRelativeRef(d,c,i,n,s,o)}catch{}}async tryRelativeRef(e,t,n,s,o,i){try{let a=new URL(e,t),c=a.pathname+a.search,l=ir(c)?[c]:this.typescriptProvider.declarationCandidatesFor(c);for(let d of l){let f=new URL(d,a).toString();if(i.has(f))return;let m=await this.fetchDts(f);if(m?.dts){let g=this.toVirtualPath(n,new URL(m.url),s);this.pushFileIfNew(o,g,m.dts),await this.expandRelativeRefs(m.dts,m.url,s,o,i,n);return}}}catch{}}isDifferentPackage(e,t){return e===t?!1:new y(e).name!==new y(t).name}ambientlyDeclares(e,t){for(let n of e.matchAll(/declare\s+module\s+['"]([^'"]+)['"]/g)){let s=n[1];if(s===t||s.endsWith("/*")&&t.startsWith(s.slice(0,-1)))return!0}return!1}markFileAmbient(e,t){let n=e.find(s=>s.path===t);n&&(n.ambient=!0)}async prefetchBareDeps(e,t,n,s,o){try{let i=this.capArray(this.scanner.collectBareModuleRefs(e),Z.maxBareDeps).filter(l=>this.isDifferentPackage(l,t));if(!i.length)return;let a=new Set([t]),c=Oo(Z.prefetchConcurrency);await Promise.all(i.map(l=>c(()=>this.prefetchBareDepsRecursive(l,n,s,Z.maxBareDepth,a,o).catch(()=>{}))))}catch{}}async prefetchBareDepsRecursive(e,t,n,s,o,i){if(s<=0||o.has(e))return;o.add(e);let a=await this.fetchRootDts(e,i);if(!a?.dts)return;let c=a.resolvedPkg||e,l=this.virtualFs.pathForMain(c);this.pushFileIfNew(t,l,a.dts),this.ambientlyDeclares(a.dts,e)?this.markFileAmbient(t,l):n.push({module:e,path:l}),a.url&&await this.expandRelativeRefs(a.dts,a.url,c,t);let d=this.capArray(this.scanner.collectBareModuleRefs(a.dts),Z.maxBareDeps).filter(u=>!o.has(u));for(let u of d)await this.prefetchBareDepsRecursive(u,t,n,s-1,o,i)}async resolve(e,t,n){let s=await this.packageService.extractImports(e),o=n?[...s,...n]:s;return(await Promise.all(o.map(a=>this.resolveOne(a,t)))).filter(a=>!!a)}async resolveOne(e,t){let{effectivePackage:n}=await this.versionResolver.effectivePackage(e,t);return this.withInFlight(n,async()=>{let s=await this.fetchRootDts(e,t)??await this.trySubpathWithRootFallback(e,t);return s?this.buildDefFromContent(e,s,s.resolvedPkg||e,t):this.createStubDef(e)})}async buildDefFromContent(e,t,n,s){let{dts:o,url:i,resolvedPkg:a}=t,c=new y(a||n),l=c.version?`${c.name}@${c.version}`:c.name,{mainPath:d,packageRootUrl:u}=this.computeEntryPath(i,l),f=[{path:d,content:o}],m=[];i&&await this.expandRelativeRefs(o,i,l,f,void 0,u);let g=f.map(E=>E.content).join(`
272
+ `);await this.prefetchBareDeps(g,l,f,m,s);let v=c.format(),$=e===v?[e]:[e,v],O=$.some(E=>this.ambientlyDeclares(o,E));return O?this.markFileAmbient(f,d):m.push(...$.map(E=>({module:E,path:d}))),{pkg:e,mainPath:d,files:f,shims:m,ambient:O}}};function cr(r){return new ft(r)}import*as z from"fs/promises";import*as q from"path";import*as mn from"os";import*as lr from"fs/promises";import*as pn from"crypto";function L(r){return pn.createHash("sha1").update(r).digest("hex")}async function ae(r){try{return JSON.parse(await lr.readFile(r,"utf8"))}catch{return}}async function mt(r){try{return await lr.readFile(r,"utf8")}catch{return}}var fn=1,ee=q.join(mn.homedir(),".typebulb","cache"),qe=q.join(ee,"packages"),Ge=q.join(ee,"proxy"),ht=q.join(ee,"dts"),Do=q.join(ee,"emit"),dr;function S(){return dr||(dr=Bo()),dr}function gt(r,e){return q.join(Do,L(r),e)}async function Bo(){await z.mkdir(ee,{recursive:!0});let r=q.join(ee,"version.json");if((await Mo(r))?.version===fn)return;let t=await z.readdir(ee).catch(()=>[]);await Promise.all(t.map(n=>z.rm(q.join(ee,n),{recursive:!0,force:!0}))),await z.writeFile(r,JSON.stringify({version:fn})+`
273
+ `,"utf8")}async function Mo(r){try{let e=await z.readFile(r,"utf8");return JSON.parse(e)}catch{return}}import*as te from"fs/promises";import*as hn from"path";async function j(r,e){await te.mkdir(hn.dirname(r),{recursive:!0});let t=`${r}.tmp-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;await te.writeFile(t,e,"utf8"),await te.rename(t,r).catch(async n=>{throw await te.rm(t,{force:!0}).catch(()=>{}),n})}var ve=class{constructor(e){this.filePath=e}mem;loadPromise;load(){return this.mem?Promise.resolve(this.mem):(this.loadPromise||(this.loadPromise=ae(this.filePath).then(e=>(this.mem=new Map(Object.entries(e??{})),this.mem))),this.loadPromise)}async get(e){return(await this.load()).get(e)}async set(e,t){let n=await this.load();n.set(e,t),await this.persist(n)}async delete(e){let t=await this.load();t.delete(e)&&await this.persist(t)}async persist(e){await j(this.filePath,JSON.stringify(Object.fromEntries(e)))}};var ur=U.join(qe,"indexes"),gn=U.join(qe,"pinned"),jo=U.join(qe,"meta"),Fo=U.join(qe,"negative.json"),xe=Symbol("missing"),bt=class{pinnedMem=new Map;indexMem=new Map;metaMem=new Map;negativeCache=new ie(new ve(Fo));async getPinnedExact(e,t){let n=`${e}@${t}`,s=this.pinnedMem.get(n);if(s!==void 0)return s===xe?void 0:s;await S();let o=await mt(U.join(gn,L(n)+".txt"));return this.pinnedMem.set(n,o??xe),o}async setPinnedExact(e,t,n){let s=`${e}@${t}`;this.pinnedMem.set(s,n),await S(),await j(U.join(gn,L(s)+".txt"),n)}async getIndex(e){let t=this.indexMem.get(e);if(t!==void 0)return t===xe?void 0:t;await S();let n=await ae(U.join(ur,yt(e)+".json"));return this.indexMem.set(e,n??xe),n}async setIndex(e,t,n){let s={versions:t,distTags:n,updatedAt:Date.now()};this.indexMem.set(e,s),await S(),await j(U.join(ur,yt(e)+".json"),JSON.stringify(s))}async invalidateVersionsCache(e){this.indexMem.delete(e),await bn.rm(U.join(ur,yt(e)+".json"),{force:!0})}async isNegative(e){return await S(),this.negativeCache.isNegative(e)}async recordNegative(e){await S(),await this.negativeCache.recordNegative(e)}async clearNegative(e){await this.negativeCache.clearNegative(e)}async getMeta(e,t){let n=`${e}@${t}`,s=this.metaMem.get(n);if(s!==void 0)return s===xe?void 0:s;await S();let o=await ae(yn(e,t));return this.metaMem.set(n,o??xe),o}async setMeta(e,t,n,s,o){let i={dependencies:n,peerDependencies:s,peerDependenciesMeta:o,updatedAt:Date.now()};this.metaMem.set(`${e}@${t}`,i),await S(),await j(yn(e,t),JSON.stringify(i))}};function yn(r,e){return U.join(jo,yt(r),encodeURIComponent(e)+".json")}function yt(r){return r.replace(/\//g,"__")}var wn={async getJson(r){try{let e=await fetch(r,{redirect:"follow"});return e.ok?await e.json():void 0}catch{return}},async head(r){try{let e=await fetch(r,{method:"HEAD",redirect:"follow"});return{ok:e.ok,url:e.url}}catch{return}}};var No=new bt,{packageService:wt,versionResolver:vn,cdnClient:xn,peerResolver:Gl}=rn(No,wn);var Sn=`
274
274
  (() => {
275
275
  // Embedded (bulb-in-a-bulb): runs inside a sandboxed iframe with no parent
276
276
  // bridge, so privileged tb.* (AI, fs, server RPC) can't reach a host and would
@@ -480,10 +480,10 @@ declare const tb: {${tn}${rn}${nn}${an}${xo}${sn}${on}
480
480
  };
481
481
  }
482
482
  })();
483
- `;function wt(r){return r.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}var vt=` *, *::before, *::after { box-sizing: border-box; }
483
+ `;function vt(r){return r.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}var xt=` *, *::before, *::after { box-sizing: border-box; }
484
484
  body { margin: 0; display: flow-root; font-family: system-ui, -apple-system, sans-serif; }
485
485
  html[data-theme="dark"] { color-scheme: dark; }
486
- html[data-theme="light"] { color-scheme: light; }`;function xt(r,e){let t=n=>n.replace(/<\/script/gi,"<\\/script");return` <script>
486
+ html[data-theme="light"] { color-scheme: light; }`;function St(r,e){let t=n=>n.replace(/<\/script/gi,"<\\/script");return` <script>
487
487
  (function() {
488
488
  try {
489
489
  var KEY = ${t(JSON.stringify("tb-theme:"+r))};
@@ -518,18 +518,18 @@ declare const tb: {${tn}${rn}${nn}${an}${xo}${sn}${on}
518
518
  });
519
519
  } catch (e) {}
520
520
  })();
521
- </script>`}function xn(r){let{name:e,code:t,css:n,html:s,data:o,insight:i,importMap:a,watch:c,theme:l}=r,d=s.trim()||'<div id="app"></div>',u=m=>m.replace(/<\/script/gi,"<\\/script"),f={imports:jo(a.imports)};return`<!DOCTYPE html>
521
+ </script>`}function Pn(r){let{name:e,code:t,css:n,html:s,data:o,insight:i,importMap:a,watch:c,theme:l}=r,d=s.trim()||'<div id="app"></div>',u=m=>m.replace(/<\/script/gi,"<\\/script"),f={imports:Uo(a.imports)};return`<!DOCTYPE html>
522
522
  <html>
523
523
  <head>
524
524
  <meta charset="utf-8">
525
525
  <meta name="viewport" content="width=device-width, initial-scale=1">
526
- <title>${wt(e)} - typebulb</title>
527
- ${xt(e,l)}
526
+ <title>${vt(e)} - typebulb</title>
527
+ ${St(e,l)}
528
528
  <script type="importmap">
529
529
  ${JSON.stringify(f,null,2)}
530
530
  </script>
531
531
  <style>
532
- ${vt}
532
+ ${xt}
533
533
  </style>
534
534
  <style>
535
535
  ${n}
@@ -543,16 +543,16 @@ ${i?`<script>window.__TB_INSIGHT__ = ${u(JSON.stringify(i))};</script>`:""}
543
543
  ${c?"<script>window.__TYPEBULB_WATCH__ = true;</script>":""}
544
544
 
545
545
  <script>
546
- ${vn}
546
+ ${Sn}
547
547
  </script>
548
548
 
549
- ${Fo}
549
+ ${Lo}
550
550
 
551
551
  <script type="module">
552
552
  ${u(t)}
553
553
  </script>
554
554
  </body>
555
- </html>`}var Fo=`<script>
555
+ </html>`}var Lo=`<script>
556
556
  (function () {
557
557
  if (window.parent === window) return;
558
558
  var de = document.documentElement;
@@ -623,50 +623,50 @@ ${u(t)}
623
623
  }
624
624
  });
625
625
  })();
626
- </script>`;function jo(r){let e={};for(let[t,n]of Object.entries(r))e[t]=n.startsWith("https://")?"/proxy/"+n:n;return e}import*as Pt from"fs/promises";import*as St from"path";import{existsSync as Sn,readFileSync as No}from"fs";import{execFile as Lo}from"child_process";import{promisify as Uo}from"util";import{satisfies as Wo}from"semver";var Jo=Uo(Lo);async function Et(r,e,t){let s=r.map(i=>Ho(i,t)).filter(i=>!Vo(i,e));if(s.length===0)return;await Pt.mkdir(e,{recursive:!0});let o=St.join(e,"package.json");Sn(o)||await Pt.writeFile(o,JSON.stringify({name:"typebulb-server",private:!0})),console.log(` Installing: ${s.join(", ")}`),await Jo("npm",["install","--no-audit","--no-fund",...s],{cwd:e,shell:!0})}function Ho(r,e){if(!e||En(r))return r;let t=e[r];return t?`${r}@${t}`:r}function Vo(r,e){let t=St.join(e,"node_modules",Pn(r));if(!Sn(t))return!1;let n=En(r);if(!n)return!0;try{let s=JSON.parse(No(St.join(t,"package.json"),"utf-8")).version;return Wo(s,n)}catch{return!1}}function Rt(r){let e=new Set,t=/\bimport\s+(?:[\s\S]*?\s+from\s+)?['"]([^./][^'"]*)['"]/g,n;for(;n=t.exec(r);){let s=n[1];if(s.includes(":"))continue;let o=s.startsWith("@")?s.split("/").slice(0,2).join("/"):s.split("/")[0];e.add(o)}return[...e]}function Pn(r){if(r.startsWith("@")){let t=r.indexOf("/");if(t<0)return r;let n=r.indexOf("@",t+1);return n<0?r:r.slice(0,n)}let e=r.indexOf("@");return e<0?r:r.slice(0,e)}function En(r){let e=Pn(r);return r.length>e.length?r.slice(e.length+1):""}async function Rn(r){let t=(await re.readdir(r)).find(n=>n.endsWith(".bulb.md"));return t?kt.join(r,t):null}async function G(r){let e=await re.readFile(r,"utf-8"),t=at(e);if(!t)throw new Error("Invalid .bulb.md file format");let n=ct(t);return{bulb:n,config:Kr(n.config)}}async function ur(r,e,t,n){let s=Xt(r,{serverOnly:!0});if(s.error)throw new Error(`Server compilation error: ${s.error}`);let o=s.code;t&&(o=await Vr(o,t));let i=kt.join(e,".typebulb");await re.mkdir(i,{recursive:!0});let a=Rt(o);a.length>0&&await Et(a,i,n);let c=kt.join(i,"server.mjs");return await re.writeFile(c,o,"utf-8"),await import(`${zo(c).href}?t=${Date.now()}`)}async function pr(r,e,t,n,s){let{bulb:o,config:i}=await G(r),a=Gr(o.data),c=Xt(o.code,{jsxImportSource:i.jsxImportSource});c.error&&console.error("Compilation error:",c.error);let{importMap:l}=await bt.buildImportMap(c.code,i.dependencies??{},n?new Set([n.name]):void 0);n&&(l.imports[n.name]=n.entryUrl);let d=xn({name:o.name,code:c.code,css:o.css,html:o.html,data:a,insight:o.insight,importMap:l,watch:e}),u=null;return o.server&&t&&(u=await ur(o.server,s,n,i.dependencies)),{html:d,bulb:o,serverExports:u}}Ke();import ei from"open";async function Pe(r){await ei(r)}var _n=new Set(["claude"]);function An(r){return _n.has(r)}function gr(){return[..._n]}import*as Bn from"path";import{spawn as hi}from"child_process";import*as _ from"fs/promises";import*as R from"path";import*as Ee from"path";var ti=Ee.join(mt,"pkg"),ri=Ee.join(mt,"files"),ni=Ee.join(mt,"negative.json"),At=class{pkgMem=new Map;fileMem=new Map;negativeCache=new ie(new ve(ni));async getCachedDts(e){if(this.pkgMem.has(e))return this.pkgMem.get(e);await S();let t=await ae(Cn(e));return this.pkgMem.set(e,t),t}async setCachedDts(e,t,n){let s={content:t,url:n};this.pkgMem.set(e,s),await _t(async()=>{await S(),await F(Cn(e),JSON.stringify(s))})}async getCachedFile(e){if(this.fileMem.has(e))return this.fileMem.get(e);await S();let t=await ft(In(e));return this.fileMem.set(e,t),t}async setCachedFile(e,t){this.fileMem.set(e,t),await _t(async()=>{await S(),await F(In(e),t)})}isNegative(e){return this.negativeCache.isNegative(e)}async recordNegative(e){await _t(async()=>{await S(),await this.negativeCache.recordNegative(e)})}clearNegative(e){return _t(()=>this.negativeCache.clearNegative(e))}};async function _t(r){try{await r()}catch{}}function Cn(r){return Ee.join(ti,L(r)+".json")}function In(r){return Ee.join(ri,L(r)+".txt")}var yr;function si(){return yr||(yr=ar({cache:new At,cdnClient:wn,packageService:bt,versionResolver:bn})),yr}var $n="file:///node_modules/";async function On(r){let e=ht(r.emitKey,"typecheck");await S(),await _.rm(e,{recursive:!0,force:!0}),await _.mkdir(e,{recursive:!0});let t=ci(r.jsxImportSource,r.dependencies),n=await si().resolve(r.code,r.dependencies,t),s=r.local?.name,o=s?n.filter(d=>d.pkg!==s):n,i=new Set;for(let d of o)for(let u of d.files){let f=Ct(u.path);if(!f||i.has(f))continue;i.add(f);let m=R.join(e,"node_modules",f);await _.mkdir(R.dirname(m),{recursive:!0}),await _.writeFile(m,u.content,"utf8")}let a={};for(let d of o)for(let u of d.shims){let f=Ct(u.path);f&&(a[u.module]=[`./node_modules/${f}`])}for(let d of o){if(d.ambient)continue;let u=Ct(d.mainPath);u&&(a[d.pkg]=[`./node_modules/${u}`])}let c=new Set;for(let d of o)for(let u of d.files){if(!u.ambient)continue;let f=Ct(u.path);f&&c.add(`node_modules/${f}`)}if(r.local){delete a[r.local.name];let d=await li(r.local,e);d?a[r.local.name]=[`./node_modules/${r.local.name}/${d}`]:console.warn(` local: '${r.local.name}' ships no type defs; check cannot type against it.`)}let l=oi(r.jsxImportSource,a,[...c]);return await _.writeFile(R.join(e,"tsconfig.json"),JSON.stringify(l,null,2)+`
627
- `,"utf8"),await _.writeFile(R.join(e,"code.tsx"),r.code,"utf8"),await _.writeFile(R.join(e,"tb.d.ts"),nr,"utf8"),{dir:e}}function oi(r,e,t=[]){return{compilerOptions:{target:"es2023",module:"esnext",moduleResolution:"bundler",lib:ii([...tr,...rr]),jsx:"react-jsx",jsxImportSource:r??"react",strict:!0,noEmit:!0,skipLibCheck:!0,esModuleInterop:!0,allowSyntheticDefaultImports:!0,forceConsistentCasingInFileNames:!0,baseUrl:".",paths:e},include:["code.tsx","tb.d.ts",...t]}}function ii(r){return r.filter(e=>!e.since).map(e=>ai(e.name))}function ai(r){return r.split(".").map(e=>/^es\d+$/i.test(e)?e.toUpperCase():e==="dom"?"DOM":e==="esnext"?"ESNext":e.charAt(0).toUpperCase()+e.slice(1)).join(".")}function ci(r,e){let t=r??("react"in e?"react":void 0);return t?[`${t}/jsx-runtime`,`${t}/jsx-dev-runtime`]:[]}function Ct(r){if(!r.startsWith($n))return;let e=r.slice($n.length),t=e.indexOf("/");if(!(t<0))return e.slice(t+1)}async function li(r,e){if(!r.typesAbs)return;let t=R.dirname(r.typesAbs),n=R.join(e,"node_modules",r.name);for(let s of await di(t)){let o=R.join(n,R.relative(t,s));await _.mkdir(R.dirname(o),{recursive:!0}),await _.copyFile(s,o)}return R.basename(r.typesAbs)}async function di(r){let e=[];async function t(n){let s=await _.readdir(n,{withFileTypes:!0});for(let o of s){let i=R.join(n,o.name);o.isDirectory()?await t(i):/\.d\.ts(\.map)?$/.test(o.name)&&e.push(i)}}return await t(r),e}import*as j from"fs/promises";import*as K from"path";import{existsSync as ui}from"fs";var pi="^22";async function Dn(r){let e=ht(r.emitKey,"typecheck-server");await S(),await j.rm(e,{recursive:!0,force:!0}),await j.mkdir(e,{recursive:!0});let t=K.join(r.bulbDir,".typebulb"),n=Rt(r.server).filter(i=>i!==r.local?.name);await Et([`@types/node@${pi}`,...n],t,r.dependencies);let s=K.join(t,"node_modules"),o=K.join(e,"node_modules");return await mi(s,o),await j.writeFile(K.join(e,"server.ts"),r.server,"utf8"),await j.writeFile(K.join(e,"tb.d.ts"),sr,"utf8"),await j.writeFile(K.join(e,"tsconfig.json"),JSON.stringify(fi(r.local),null,2)+`
628
- `,"utf8"),{dir:e}}function fi(r){let e={target:"es2023",module:"esnext",moduleResolution:"bundler",lib:["ES2023"],types:["node"],strict:!0,noEmit:!0,skipLibCheck:!0,esModuleInterop:!0,allowSyntheticDefaultImports:!0,forceConsistentCasingInFileNames:!0};if(r?.typesAbs){let t=o=>o.replace(/\\/g,"/"),n=t(K.dirname(r.typesAbs)),s=t(r.typesAbs).replace(/\.d\.ts$/,"");e.baseUrl=".",e.paths={[r.name]:[s],[`${r.name}/*`]:[`${n}/*`]}}return{compilerOptions:e,include:["server.ts","tb.d.ts"]}}async function mi(r,e){if(!ui(r)){await j.mkdir(e,{recursive:!0});return}await j.rm(e,{recursive:!0,force:!0});let t=process.platform==="win32"?"junction":"dir";await j.symlink(r,e,t)}async function Mn(r,e){let{bulb:t,config:n}=await G(r);!t.code&&!t.server&&(console.error("Bulb has neither **code.tsx** nor **server.ts**; nothing to check."),process.exit(1));let s=[];if(t.code){let{dir:i}=await On({code:t.code,dependencies:n.dependencies??{},jsxImportSource:n.jsxImportSource,emitKey:r,local:e});s.push({role:"client",dir:i})}if(t.server){let{dir:i}=await Dn({server:t.server,bulbDir:Bn.dirname(r),emitKey:r,local:e?{name:e.name,typesAbs:e.typesAbs}:void 0,dependencies:n.dependencies});s.push({role:"server",dir:i})}let o=!1;for(let{role:i,dir:a}of s){let{stdout:c,exitCode:l}=await gi(a);for(let d of c.split(/\r?\n/))d.trim()&&console.log(`${i} ${d}`);l!==0&&(o=!0)}o&&process.exit(1)}function gi(r){return new Promise(e=>{let t=hi("npx",["tsc","--noEmit"],{cwd:r,shell:!0}),n="";t.stdout?.on("data",s=>{n+=s.toString()}),t.stderr?.on("data",s=>{n+=s.toString()}),t.on("close",s=>e({stdout:n,exitCode:s??1}))})}It();Ke();async function Fn(r,e){let{bulb:t}=await G(r),n=Re(t);if(le(r)){console.log("remembered-trusted \u2014 runs with filesystem / AI / server.ts automatically (`typebulb untrust` to revoke)."),n&&console.log(` (it uses ${n})`);return}n?(console.log(`This bulb appears to use ${n}; it runs Restricted unless you grant trust:`),console.log(` ${e}`)):console.log("No privileged capability detected \u2014 runs Restricted by default. (A clean scan is a hint, not a guarantee.)")}Ke();import*as Ye from"path";async function jn(r,e){if(!r){e||(console.error("Usage: typebulb untrust <file.bulb.md>"),process.exit(1));let n=hr();if(!n.length){console.log("No bulbs are remembered as trusted.");return}console.log("Trusted bulbs (run with fs/AI/server.ts without --trust):");for(let s of n)console.log(` ${s}`);return}let t=Ye.resolve(r);t.endsWith(".bulb.md")||(console.error("File must have .bulb.md extension"),process.exit(1)),Se(t,e),console.log(e?`Trusted ${Ye.basename(t)} \u2014 runs with fs / AI / server.ts (no --trust needed).`:`Untrusted ${Ye.basename(t)} \u2014 runs Restricted.`),console.log(` ${t}`)}Ge();de();async function wr(r,e){let t=D(r);return(await B()).find(n=>n.cwd!=null&&D(n.cwd)===t&&(e?n.agent===e:n.agent!=null))}async function zn(){let r=await wr(process.cwd()),e=r?.agent,t=e?"output a bulb block; it renders live here":"start the viewer yourself \u2014 `npx typebulb agent:claude --no-open` \u2014 share the localhost link it prints, then output a bulb block",n=[e?`You ran \`typebulb agent\`. Viewer '${e}' is up at ${r?.url}.`:"You ran `typebulb agent`. No viewer is running.",`- To show a bulb inline in this chat: ${t}.`,"- To make a bulb to keep and iterate on: write a .bulb.md and run `npx typebulb my-bulb.bulb.md`.","Working with bulbs? Run `npx typebulb skill` for the full authoring guide \u2014 save it to your skills folder if the user wants bulbs on hand across sessions."];process.stdout.write(n.join(`
629
- `)+`
630
- `)}import{readFileSync as ki,existsSync as Ti}from"fs";import*as Y from"path";function _i(r){return[...r?[`.env.${r}.local`,`.env.${r}`]:[],".env.local",".env"]}function ne(r,e=process.cwd()){let t={},n=[];for(let s of _i(r)){let o;try{o=ki(Y.resolve(e,s),"utf-8")}catch{continue}n.push(s);for(let[i,a]of Ai(o))process.env[i]===void 0&&(process.env[i]=a,t[i]=s)}return{mode:r,sources:t,loaded:n}}function*Ai(r){for(let e of r.split(`
631
- `)){let t=e.trim();if(!t||t.startsWith("#"))continue;let n=t.indexOf("=");if(n===-1)continue;let s=t.slice(0,n).trim(),o=t.slice(n+1).trim();(o.startsWith('"')&&o.endsWith('"')||o.startsWith("'")&&o.endsWith("'"))&&(o=o.slice(1,-1)),yield[s,o]}}function Ci(r){let e=new Set,t=/process\.env\.([A-Za-z_$][\w$]*)|process\.env\[\s*['"]([^'"]+)['"]\s*\]/g;for(let n;n=t.exec(r);)e.add(n[1]??n[2]);return[...e]}function _e(r,e,t){let{sources:n,mode:s,loaded:o}=r,i=process.cwd(),a=Y.dirname(e),c=`(mode: ${s??"none"})`,l=t?Ci(t):[],d=l.filter(m=>n[m]).map(m=>`${m} \u2190 ${n[m]}`);d.length?console.log(`env: ${d.join(", ")} ${c}`):o.length&&console.log(`env: loaded ${o.join(", ")} ${c}`),s&&!o.some(m=>m===`.env.${s}`||m===`.env.${s}.local`)&&console.log(`env: mode=${s} \u2014 no .env.${s} found; using .env`);let u=Y.resolve(a)!==Y.resolve(i);if(u)for(let m of[".env.local",".env"])Ti(Y.join(a,m))&&console.log(`env: ${Y.join(a,m)} present but not loaded (cwd is ${i})`);let f=l.filter(m=>process.env[m]===void 0);if(f.length){let m=u?` \u2014 try running from ${a}`:"";console.log(`env: server.ts reads ${f.join(", ")} but ${f.length>1?"they are":"it's"} unset${m}`)}}var Ce={anthropic:"ANTHROPIC_API_KEY",openai:"OPENAI_API_KEY",gemini:"GOOGLE_API_KEY",openrouter:"OPENROUTER_API_KEY"},Ii="https://api.typebulb.com/api/models",$i=1440*60*1e3,Ae=null;async function Bt(){if(!Ae||Date.now()-Ae.fetchedAt>$i){let r=await fetch(Ii);if(!r.ok)return Ae?qn(Ae.models):[];Ae={models:await r.json(),fetchedAt:Date.now()}}return qn(Ae.models)}function qn(r){let e=new Set(Object.entries(Ce).filter(([,t])=>!!process.env[t]).map(([t])=>t));return r.filter(t=>e.has(t.provider))}function Gn(){return Object.values(Ce).some(r=>!!process.env[r])}function Kn(r,e,t){let n=Math.max(...r.map(i=>i.name.length)),s=Math.max(...r.map(i=>i.friendlyName.length)),o=["Models available to tb.ai (filtered by your .env keys):",""];for(let i of r)o.push(` ${i.name.padEnd(n)} ${i.friendlyName.padEnd(s)} (${i.provider})`);return o.push("","Pass an id as the `model` in tb.ai({ provider, model })."),e&&t&&o.push(`Default (from .env): ${e} / ${t}`),o.join(`
632
- `)}async function Yn(r){if(ne(r),!Gn()){console.log("No AI provider keys found in this directory's .env. Set one of these to use tb.ai:");for(let[t,n]of Object.entries(Ce))console.log(` ${n.padEnd(20)} (${t})`);console.log("Then re-run `typebulb models`.");return}let e=await Bt();if(e.length===0){console.log("Couldn't fetch the model catalog (offline?). tb.ai still works with any valid provider/model id for your keys.");return}console.log(Kn(e,process.env.TB_AI_PROVIDER,process.env.TB_AI_MODEL))}import*as Qn from"fs/promises";import*as Mt from"path";import{fileURLToPath as Bi}from"url";function Oi(r){return`---
626
+ </script>`;function Uo(r){let e={};for(let[t,n]of Object.entries(r))e[t]=n.startsWith("https://")?"/proxy/"+n:n;return e}import*as Et from"fs/promises";import*as Pt from"path";import{existsSync as En,readFileSync as Wo}from"fs";import{execFile as Jo}from"child_process";import{promisify as Ho}from"util";import{satisfies as Vo}from"semver";var zo=Ho(Jo);async function Rt(r,e,t){let s=r.map(i=>qo(i,t)).filter(i=>!Go(i,e));if(s.length===0)return;await Et.mkdir(e,{recursive:!0});let o=Pt.join(e,"package.json");En(o)||await Et.writeFile(o,JSON.stringify({name:"typebulb-server",private:!0})),console.log(` Installing: ${s.join(", ")}`),await zo("npm",["install","--no-audit","--no-fund",...s],{cwd:e,shell:!0})}function qo(r,e){if(!e||kn(r))return r;let t=e[r];return t?`${r}@${t}`:r}function Go(r,e){let t=Pt.join(e,"node_modules",Rn(r));if(!En(t))return!1;let n=kn(r);if(!n)return!0;try{let s=JSON.parse(Wo(Pt.join(t,"package.json"),"utf-8")).version;return Vo(s,n)}catch{return!1}}function kt(r){let e=new Set,t=/\bimport\s+(?:[\s\S]*?\s+from\s+)?['"]([^./][^'"]*)['"]/g,n;for(;n=t.exec(r);){let s=n[1];if(s.includes(":"))continue;let o=s.startsWith("@")?s.split("/").slice(0,2).join("/"):s.split("/")[0];e.add(o)}return[...e]}function Rn(r){if(r.startsWith("@")){let t=r.indexOf("/");if(t<0)return r;let n=r.indexOf("@",t+1);return n<0?r:r.slice(0,n)}let e=r.indexOf("@");return e<0?r:r.slice(0,e)}function kn(r){let e=Rn(r);return r.length>e.length?r.slice(e.length+1):""}async function Tn(r){let t=(await re.readdir(r)).find(n=>n.endsWith(".bulb.md"));return t?Tt.join(r,t):null}async function G(r){let e=await re.readFile(r,"utf-8"),t=ct(e);if(!t)throw new Error("Invalid .bulb.md file format");let n=lt(t);return{bulb:n,config:Xr(n.config)}}async function pr(r,e,t,n){let s=Qt(r,{serverOnly:!0});if(s.error)throw new Error(`Server compilation error: ${s.error}`);let o=s.code;t&&(o=await qr(o,t));let i=Tt.join(e,".typebulb");await re.mkdir(i,{recursive:!0});let a=kt(o);a.length>0&&await Rt(a,i,n);let c=Tt.join(i,"server.mjs");return await re.writeFile(c,o,"utf-8"),await import(`${Ko(c).href}?t=${Date.now()}`)}async function fr(r,e,t,n,s){let{bulb:o,config:i}=await G(r),a=Yr(o.data),c=Qt(o.code,{jsxImportSource:i.jsxImportSource});c.error&&console.error("Compilation error:",c.error);let{importMap:l}=await wt.buildImportMap(c.code,i.dependencies??{},n?new Set([n.name]):void 0);n&&(l.imports[n.name]=n.entryUrl);let d=Pn({name:o.name,code:c.code,css:o.css,html:o.html,data:a,insight:o.insight,importMap:l,watch:e}),u=null;return o.server&&t&&(u=await pr(o.server,s,n,i.dependencies)),{html:d,bulb:o,serverExports:u}}Ye();import ni from"open";async function Pe(r){await ni(r)}var Cn=new Set(["claude"]);function In(r){return Cn.has(r)}function yr(){return[...Cn]}import*as jn from"path";import{spawn as bi}from"child_process";import*as _ from"fs/promises";import*as R from"path";import*as Ee from"path";var si=Ee.join(ht,"pkg"),oi=Ee.join(ht,"files"),ii=Ee.join(ht,"negative.json"),Ct=class{pkgMem=new Map;fileMem=new Map;negativeCache=new ie(new ve(ii));async getCachedDts(e){if(this.pkgMem.has(e))return this.pkgMem.get(e);await S();let t=await ae($n(e));return this.pkgMem.set(e,t),t}async setCachedDts(e,t,n){let s={content:t,url:n};this.pkgMem.set(e,s),await At(async()=>{await S(),await j($n(e),JSON.stringify(s))})}async getCachedFile(e){if(this.fileMem.has(e))return this.fileMem.get(e);await S();let t=await mt(On(e));return this.fileMem.set(e,t),t}async setCachedFile(e,t){this.fileMem.set(e,t),await At(async()=>{await S(),await j(On(e),t)})}isNegative(e){return this.negativeCache.isNegative(e)}async recordNegative(e){await At(async()=>{await S(),await this.negativeCache.recordNegative(e)})}clearNegative(e){return At(()=>this.negativeCache.clearNegative(e))}};async function At(r){try{await r()}catch{}}function $n(r){return Ee.join(si,L(r)+".json")}function On(r){return Ee.join(oi,L(r)+".txt")}var br;function ai(){return br||(br=cr({cache:new Ct,cdnClient:xn,packageService:wt,versionResolver:vn})),br}var Dn="file:///node_modules/";async function Bn(r){let e=gt(r.emitKey,"typecheck");await S(),await _.rm(e,{recursive:!0,force:!0}),await _.mkdir(e,{recursive:!0});let t=ui(r.jsxImportSource,r.dependencies),n=await ai().resolve(r.code,r.dependencies,t),s=r.local?.name,o=s?n.filter(d=>d.pkg!==s):n,i=new Set;for(let d of o)for(let u of d.files){let f=It(u.path);if(!f||i.has(f))continue;i.add(f);let m=R.join(e,"node_modules",f);await _.mkdir(R.dirname(m),{recursive:!0}),await _.writeFile(m,u.content,"utf8")}let a={};for(let d of o)for(let u of d.shims){let f=It(u.path);f&&(a[u.module]=[`./node_modules/${f}`])}for(let d of o){if(d.ambient)continue;let u=It(d.mainPath);u&&(a[d.pkg]=[`./node_modules/${u}`])}let c=new Set;for(let d of o)for(let u of d.files){if(!u.ambient)continue;let f=It(u.path);f&&c.add(`node_modules/${f}`)}if(r.local){delete a[r.local.name];let d=await pi(r.local,e);d?a[r.local.name]=[`./node_modules/${r.local.name}/${d}`]:console.warn(` local: '${r.local.name}' ships no type defs; check cannot type against it.`)}let l=ci(r.jsxImportSource,a,[...c]);return await _.writeFile(R.join(e,"tsconfig.json"),JSON.stringify(l,null,2)+`
627
+ `,"utf8"),await _.writeFile(R.join(e,"code.tsx"),r.code,"utf8"),await _.writeFile(R.join(e,"tb.d.ts"),sr,"utf8"),{dir:e}}function ci(r,e,t=[]){return{compilerOptions:{target:"es2023",module:"esnext",moduleResolution:"bundler",lib:li([...rr,...nr]),jsx:"react-jsx",jsxImportSource:r??"react",strict:!0,noEmit:!0,skipLibCheck:!0,esModuleInterop:!0,allowSyntheticDefaultImports:!0,forceConsistentCasingInFileNames:!0,baseUrl:".",paths:e},include:["code.tsx","tb.d.ts",...t]}}function li(r){return r.filter(e=>!e.since).map(e=>di(e.name))}function di(r){return r.split(".").map(e=>/^es\d+$/i.test(e)?e.toUpperCase():e==="dom"?"DOM":e==="esnext"?"ESNext":e.charAt(0).toUpperCase()+e.slice(1)).join(".")}function ui(r,e){let t=r??("react"in e?"react":void 0);return t?[`${t}/jsx-runtime`,`${t}/jsx-dev-runtime`]:[]}function It(r){if(!r.startsWith(Dn))return;let e=r.slice(Dn.length),t=e.indexOf("/");if(!(t<0))return e.slice(t+1)}async function pi(r,e){if(!r.typesAbs)return;let t=R.dirname(r.typesAbs),n=R.join(e,"node_modules",r.name);for(let s of await fi(t)){let o=R.join(n,R.relative(t,s));await _.mkdir(R.dirname(o),{recursive:!0}),await _.copyFile(s,o)}return R.basename(r.typesAbs)}async function fi(r){let e=[];async function t(n){let s=await _.readdir(n,{withFileTypes:!0});for(let o of s){let i=R.join(n,o.name);o.isDirectory()?await t(i):/\.d\.ts(\.map)?$/.test(o.name)&&e.push(i)}}return await t(r),e}import*as F from"fs/promises";import*as K from"path";import{existsSync as mi}from"fs";var hi="^22";async function Mn(r){let e=gt(r.emitKey,"typecheck-server");await S(),await F.rm(e,{recursive:!0,force:!0}),await F.mkdir(e,{recursive:!0});let t=K.join(r.bulbDir,".typebulb"),n=kt(r.server).filter(i=>i!==r.local?.name);await Rt([`@types/node@${hi}`,...n],t,r.dependencies);let s=K.join(t,"node_modules"),o=K.join(e,"node_modules");return await yi(s,o),await F.writeFile(K.join(e,"server.ts"),r.server,"utf8"),await F.writeFile(K.join(e,"tb.d.ts"),or,"utf8"),await F.writeFile(K.join(e,"tsconfig.json"),JSON.stringify(gi(r.local),null,2)+`
628
+ `,"utf8"),{dir:e}}function gi(r){let e={target:"es2023",module:"esnext",moduleResolution:"bundler",lib:["ES2023"],types:["node"],strict:!0,noEmit:!0,skipLibCheck:!0,esModuleInterop:!0,allowSyntheticDefaultImports:!0,forceConsistentCasingInFileNames:!0};if(r?.typesAbs){let t=o=>o.replace(/\\/g,"/"),n=t(K.dirname(r.typesAbs)),s=t(r.typesAbs).replace(/\.d\.ts$/,"");e.baseUrl=".",e.paths={[r.name]:[s],[`${r.name}/*`]:[`${n}/*`]}}return{compilerOptions:e,include:["server.ts","tb.d.ts"]}}async function yi(r,e){if(!mi(r)){await F.mkdir(e,{recursive:!0});return}await F.rm(e,{recursive:!0,force:!0});let t=process.platform==="win32"?"junction":"dir";await F.symlink(r,e,t)}async function Fn(r,e){let{bulb:t,config:n}=await G(r);!t.code&&!t.server&&(console.error("Bulb has neither **code.tsx** nor **server.ts**; nothing to check."),process.exit(1));let s=[];if(t.code){let{dir:i}=await Bn({code:t.code,dependencies:n.dependencies??{},jsxImportSource:n.jsxImportSource,emitKey:r,local:e});s.push({role:"client",dir:i})}if(t.server){let{dir:i}=await Mn({server:t.server,bulbDir:jn.dirname(r),emitKey:r,local:e?{name:e.name,typesAbs:e.typesAbs}:void 0,dependencies:n.dependencies});s.push({role:"server",dir:i})}let o=!1;for(let{role:i,dir:a}of s){let{stdout:c,exitCode:l}=await wi(a);for(let d of c.split(/\r?\n/))d.trim()&&console.log(`${i} ${d}`);l!==0&&(o=!0)}o&&process.exit(1)}function wi(r){return new Promise(e=>{let t=bi("npx",["tsc","--noEmit"],{cwd:r,shell:!0}),n="";t.stdout?.on("data",s=>{n+=s.toString()}),t.stderr?.on("data",s=>{n+=s.toString()}),t.on("close",s=>e({stdout:n,exitCode:s??1}))})}$t();Ye();async function Nn(r,e){let{bulb:t}=await G(r),n=Re(t);if(le(r)){console.log("remembered-trusted \u2014 runs with filesystem / AI / server.ts automatically (`typebulb untrust` to revoke)."),n&&console.log(` (it uses ${n})`);return}n?(console.log(`This bulb appears to use ${n}; it runs Restricted unless you grant trust:`),console.log(` ${e}`)):console.log("No privileged capability detected \u2014 runs Restricted by default. (A clean scan is a hint, not a guarantee.)")}Ye();import*as Xe from"path";async function Ln(r,e){if(!r){e||(console.error("Usage: typebulb untrust <file.bulb.md>"),process.exit(1));let n=gr();if(!n.length){console.log("No bulbs are remembered as trusted.");return}console.log("Trusted bulbs (run with fs/AI/server.ts without --trust):");for(let s of n)console.log(` ${s}`);return}let t=Xe.resolve(r);t.endsWith(".bulb.md")||(console.error("File must have .bulb.md extension"),process.exit(1)),Se(t,e),console.log(e?`Trusted ${Xe.basename(t)} \u2014 runs with fs / AI / server.ts (no --trust needed).`:`Untrusted ${Xe.basename(t)} \u2014 runs Restricted.`),console.log(` ${t}`)}Ke();de();import{readFileSync as Ai}from"fs";import*as _e from"path";import{fileURLToPath as Ci}from"url";function Gn(){return _e.join(_e.dirname(Ci(import.meta.url)),"..")}function Mt(){return _e.join(Gn(),"README.md")}function vr(){return _e.join(Gn(),"description.md")}function Ii(r){return`---
633
629
  name: typebulb
634
- description: Author and run Typebulb bulbs \u2014 single-file markdown apps (TypeScript/TSX) that run locally via \`npx typebulb\` (full power: filesystem, database, \`server.ts\`, \`tb.ai\`) or render live inline in a Claude Code session through Typebulb's agent viewer (sandboxed, client-only). A bulb can be a visual widget (chart, simulation, diagram, calculator, UI), a full-stack tool with a Node backend, or an AI app that calls models at runtime. Covers the bulb format, the \`tb.*\` API, trust, and the local run/embed workflow. Use when the user wants a bulb, a quick local tool (visual, backend-backed, or AI-powered), or something visual rendered inline in the conversation.
630
+ description: ${Ai(vr(),"utf8").trim().replace(/\s+/g," ")}
635
631
  version: ${r}
636
- ---`}function Di(r){return`> Generated from typebulb v${r}. If \`npx typebulb --version\` reports a newer version, re-run \`npx typebulb skill\` to refresh this file.`}function Xn(r,e){return`${Oi(e)}
632
+ ---`}function $i(r){return`> Generated from typebulb v${r}. If \`npx typebulb --version\` reports a newer version, re-run \`npx typebulb skill\` to refresh this file.`}function Kn(r,e){return`${Ii(e)}
637
633
 
638
- ${Di(e)}
634
+ ${$i(e)}
639
635
 
640
636
  ${r.trim()}
641
- `}async function Zn(r){let e=Mt.join(Mt.dirname(Bi(import.meta.url)),"..","README.md"),t;try{t=await Qn.readFile(e,"utf8")}catch{console.error(`Could not read the bundled README (expected at ${e}).`),process.exit(1)}process.stdout.write(Xn(t,r))}Ge();de();import*as vr from"path";function Mi(r,e,t){if(/^\d+$/.test(e))return r.find(s=>s.pid===parseInt(e,10));let n=r.filter(s=>s.agent===e);return n.length?(t?n.find(o=>o.cwd&&D(o.cwd)===D(t)):void 0)??n[0]:r.find(s=>D(s.file)===D(e))}function es(r,e){for(let t of r)e(` ${t.url} pid ${t.pid} ${t.trust?"trusted":"restricted"} ${t.file}`)}function ts(r,e){if(!r.length){console.log("No running bulb servers.");return}console.log("Running bulb servers:"),es(r,t=>console.log(t)),console.log(`
642
- `+e)}function rs(r,e,t,n){let s=Mi(r,e,n);if(s)return s;console.error(`No running server for '${e}'.`),r.length?(console.error(`Running servers (try \`typebulb ${t} <file|pid>\`):`),es(r,o=>console.error(o))):console.error("No bulb servers are running."),process.exit(1)}async function ns(r,e){if(!r){ts(await B(process.cwd()),"Run `typebulb logs <file|pid>` to print one server's console.");return}let t=rs(await B(),r,"logs",process.cwd()),n=ke(t.pid),s=n.text;if(e.lines&&e.lines>0){let o=s.split(`
637
+ `}async function xr(r,e){let t=D(r);return(await B()).find(n=>n.cwd!=null&&D(n.cwd)===t&&(e?n.agent===e:n.agent!=null))}async function Yn(){let r=await xr(process.cwd()),e=r?.agent,n=[e?`Viewer '${e}' is up at ${r?.url} \u2014 the embedded bulbs render live there.`:"No viewer is running \u2014 to render embedded bulbs live inline, start one with `npx typebulb agent:claude --no-open`; it prints a localhost link that opens the viewer.","","Agents: Read the bulb-authoring skill before writing a bulb \u2014 get it assembled as one SKILL.md with `npx typebulb skill`, or read its parts directly:",` - description: ${vr()}`,` - skill body (the README is the skill): ${Mt()}`];process.stdout.write(n.join(`
638
+ `)+`
639
+ `)}import{readFileSync as Oi,existsSync as Di}from"fs";import*as Y from"path";function Bi(r){return[...r?[`.env.${r}.local`,`.env.${r}`]:[],".env.local",".env"]}function ne(r,e=process.cwd()){let t={},n=[];for(let s of Bi(r)){let o;try{o=Oi(Y.resolve(e,s),"utf-8")}catch{continue}n.push(s);for(let[i,a]of Mi(o))process.env[i]===void 0&&(process.env[i]=a,t[i]=s)}return{mode:r,sources:t,loaded:n}}function*Mi(r){for(let e of r.split(`
640
+ `)){let t=e.trim();if(!t||t.startsWith("#"))continue;let n=t.indexOf("=");if(n===-1)continue;let s=t.slice(0,n).trim(),o=t.slice(n+1).trim();(o.startsWith('"')&&o.endsWith('"')||o.startsWith("'")&&o.endsWith("'"))&&(o=o.slice(1,-1)),yield[s,o]}}function ji(r){let e=new Set,t=/process\.env\.([A-Za-z_$][\w$]*)|process\.env\[\s*['"]([^'"]+)['"]\s*\]/g;for(let n;n=t.exec(r);)e.add(n[1]??n[2]);return[...e]}function Ae(r,e,t){let{sources:n,mode:s,loaded:o}=r,i=process.cwd(),a=Y.dirname(e),c=`(mode: ${s??"none"})`,l=t?ji(t):[],d=l.filter(m=>n[m]).map(m=>`${m} \u2190 ${n[m]}`);d.length?console.log(`env: ${d.join(", ")} ${c}`):o.length&&console.log(`env: loaded ${o.join(", ")} ${c}`),s&&!o.some(m=>m===`.env.${s}`||m===`.env.${s}.local`)&&console.log(`env: mode=${s} \u2014 no .env.${s} found; using .env`);let u=Y.resolve(a)!==Y.resolve(i);if(u)for(let m of[".env.local",".env"])Di(Y.join(a,m))&&console.log(`env: ${Y.join(a,m)} present but not loaded (cwd is ${i})`);let f=l.filter(m=>process.env[m]===void 0);if(f.length){let m=u?` \u2014 try running from ${a}`:"";console.log(`env: server.ts reads ${f.join(", ")} but ${f.length>1?"they are":"it's"} unset${m}`)}}var Ie={anthropic:"ANTHROPIC_API_KEY",openai:"OPENAI_API_KEY",gemini:"GOOGLE_API_KEY",openrouter:"OPENROUTER_API_KEY"},Fi="https://api.typebulb.com/api/models",Ni=1440*60*1e3,Ce=null;async function jt(){if(!Ce||Date.now()-Ce.fetchedAt>Ni){let r=await fetch(Fi);if(!r.ok)return Ce?Xn(Ce.models):[];Ce={models:await r.json(),fetchedAt:Date.now()}}return Xn(Ce.models)}function Xn(r){let e=new Set(Object.entries(Ie).filter(([,t])=>!!process.env[t]).map(([t])=>t));return r.filter(t=>e.has(t.provider))}function Qn(){return Object.values(Ie).some(r=>!!process.env[r])}function Zn(r,e,t){let n=Math.max(...r.map(i=>i.name.length)),s=Math.max(...r.map(i=>i.friendlyName.length)),o=["Models available to tb.ai (filtered by your .env keys):",""];for(let i of r)o.push(` ${i.name.padEnd(n)} ${i.friendlyName.padEnd(s)} (${i.provider})`);return o.push("","Pass an id as the `model` in tb.ai({ provider, model })."),e&&t&&o.push(`Default (from .env): ${e} / ${t}`),o.join(`
641
+ `)}async function es(r){if(ne(r),!Qn()){console.log("No AI provider keys found in this directory's .env. Set one of these to use tb.ai:");for(let[t,n]of Object.entries(Ie))console.log(` ${n.padEnd(20)} (${t})`);console.log("Then re-run `typebulb models`.");return}let e=await jt();if(e.length===0){console.log("Couldn't fetch the model catalog (offline?). tb.ai still works with any valid provider/model id for your keys.");return}console.log(Zn(e,process.env.TB_AI_PROVIDER,process.env.TB_AI_MODEL))}import*as ts from"fs/promises";async function rs(r){let e=Mt(),t;try{t=await ts.readFile(e,"utf8")}catch{console.error(`Could not read the bundled README (expected at ${e}).`),process.exit(1)}process.stdout.write(Kn(t,r))}Ke();de();import*as Sr from"path";function Li(r,e,t){if(/^\d+$/.test(e))return r.find(s=>s.pid===parseInt(e,10));let n=r.filter(s=>s.agent===e);return n.length?(t?n.find(o=>o.cwd&&D(o.cwd)===D(t)):void 0)??n[0]:r.find(s=>D(s.file)===D(e))}function ns(r,e){for(let t of r)e(` ${t.url} pid ${t.pid} ${t.trust?"trusted":"restricted"} ${t.file}`)}function ss(r,e){if(!r.length){console.log("No running bulb servers.");return}console.log("Running bulb servers:"),ns(r,t=>console.log(t)),console.log(`
642
+ `+e)}function os(r,e,t,n){let s=Li(r,e,n);if(s)return s;console.error(`No running server for '${e}'.`),r.length?(console.error(`Running servers (try \`typebulb ${t} <file|pid>\`):`),ns(r,o=>console.error(o))):console.error("No bulb servers are running."),process.exit(1)}async function is(r,e){if(!r){ss(await B(process.cwd()),"Run `typebulb logs <file|pid>` to print one server's console.");return}let t=os(await B(),r,"logs",process.cwd()),n=ke(t.pid),s=n.text;if(e.lines&&e.lines>0){let o=s.split(`
643
643
  `);o.length&&o[o.length-1]===""&&o.pop(),s=o.slice(-e.lines).join(`
644
644
  `)}if(process.stdout.write(s),s&&!s.endsWith(`
645
645
  `)&&process.stdout.write(`
646
- `),e.follow){let o=n.offset,i=setInterval(()=>{let c=ke(t.pid,o);o=c.offset,c.text&&process.stdout.write(c.text)},500),a=()=>{clearInterval(i),process.exit(0)};process.on("SIGINT",a),process.on("SIGTERM",a),await new Promise(()=>{})}}async function ss(r){if(!r){ts(await B(process.cwd()),"Run `typebulb stop <file|pid>` to stop one.");return}let e=rs(await B(),r,"stop",process.cwd());await Te(e.pid),console.log(`Stopped ${e.agent??vr.basename(e.file)} (pid ${e.pid}, ${e.url}).`)}async function os(){let r=await B();if(!r.length){console.log("No running bulb servers.");return}await Promise.all(r.map(e=>Te(e.pid))),console.log(`Stopped ${r.length} server${r.length===1?"":"s"}:`);for(let e of r)console.log(` ${e.url} pid ${e.pid} ${e.agent??vr.basename(e.file)}`)}import*as ms from"fs/promises";import*as Ie from"path";import{EventEmitter as fs}from"events";It();import{Hono as ji}from"hono";import{serve as Ni}from"@hono/node-server";import{streamSSE as Li}from"hono/streaming";import*as pe from"fs/promises";import*as H from"path";var N=class extends Error{constructor(e,t="unknown",n=!1){super(e),this.code=t,this.retryable=n}},J=class{getPath(e,t){return this.path}parseStreamChunk(e){return this.checkAndThrowError(e),this.parseProviderStreamChunk(e)}isReasoningEnabled(e){return e?.reasoning!==void 0&&e.reasoning>0}extractSystemMessages(e,t=`
646
+ `),e.follow){let o=n.offset,i=setInterval(()=>{let c=ke(t.pid,o);o=c.offset,c.text&&process.stdout.write(c.text)},500),a=()=>{clearInterval(i),process.exit(0)};process.on("SIGINT",a),process.on("SIGTERM",a),await new Promise(()=>{})}}async function as(r){if(!r){ss(await B(process.cwd()),"Run `typebulb stop <file|pid>` to stop one.");return}let e=os(await B(),r,"stop",process.cwd());await Te(e.pid),console.log(`Stopped ${e.agent??Sr.basename(e.file)} (pid ${e.pid}, ${e.url}).`)}async function cs(){let r=await B();if(!r.length){console.log("No running bulb servers.");return}await Promise.all(r.map(e=>Te(e.pid))),console.log(`Stopped ${r.length} server${r.length===1?"":"s"}:`);for(let e of r)console.log(` ${e.url} pid ${e.pid} ${e.agent??Sr.basename(e.file)}`)}import*as ys from"fs/promises";import*as $e from"path";import{EventEmitter as gs}from"events";$t();import{Hono as Wi}from"hono";import{serve as Ji}from"@hono/node-server";import{streamSSE as Hi}from"hono/streaming";import*as pe from"fs/promises";import*as H from"path";var N=class extends Error{constructor(e,t="unknown",n=!1){super(e),this.code=t,this.retryable=n}},J=class{getPath(e,t){return this.path}parseStreamChunk(e){return this.checkAndThrowError(e),this.parseProviderStreamChunk(e)}isReasoningEnabled(e){return e?.reasoning!==void 0&&e.reasoning>0}extractSystemMessages(e,t=`
647
647
 
648
- `){let n=e.filter(s=>s.role==="system").map(s=>s.content);return{system:n.length?n.join(t):void 0,conversationMessages:e.filter(s=>s.role!=="system")}}parseJsonError(e,t,n=!1){if(!e)return{message:`HTTP ${t}`};try{let s=JSON.parse(e);if(s.error&&typeof s.error=="object"){let o={message:s.error.message||`HTTP ${t}`,type:s.error.type};return n&&(o.code=s.error.code),o}return s.message?{message:s.message}:{message:e}}catch{return{message:e}}}checkAndThrowError(e){if("type"in e&&e.type==="error"&&"message"in e){let t=e.message,n=e.code||"unknown",s=!!e.retryable;throw new N(t,n,s)}if("error"in e&&e.error){let t=this.extractErrorMessage(e.error);throw new N(t)}}extractErrorMessage(e){if(typeof e=="string")try{let t=JSON.parse(e);return t.error?.message||t.message||e}catch{return e}return typeof e=="object"&&e!==null?e.message||JSON.stringify(e):`${this.providerName} returned an error`}};var et=class extends J{constructor(){super(...arguments),this.providerName="Anthropic",this.defaultBaseUrl="https://api.anthropic.com",this.path="/v1/messages"}buildHeaders(e){return{"x-api-key":e,"anthropic-version":"2023-06-01","Content-Type":"application/json",Accept:"application/json"}}buildPayload(e,t,n,s){let{system:o,conversationMessages:i}=this.extractSystemMessages(e),a={model:t,max_tokens:this.getMaxTokens(t),messages:this.withLastMessageCached(i),stream:s};if(n?.webSearch!==!1&&(a.tools=[{type:"web_search_20250305",name:"web_search"}]),o&&(a.system=[{type:"text",text:o,cache_control:{type:"ephemeral"}}]),this.isReasoningEnabled(n)){let c=n.reasoning;if(this.isModernModel(t)){let l={0:"low",1:"low",2:"medium",3:"high"};a.thinking={type:"adaptive"},a.output_config={effort:l[c]}}else{let l={0:0,1:2048,2:4096,3:8192};a.thinking={type:"enabled",budget_tokens:l[c]}}}return a}parseError(e,t){return this.parseJsonError(e,t)}parseNonStreamingResponse(e){if(!this.isAnthropicResponse(e))return{text:""};let t=e.content.filter(s=>s.type==="text").map(s=>s.text).join(""),n=e.content.filter(s=>s.type==="thinking").map(s=>s.thinking).join(`
648
+ `){let n=e.filter(s=>s.role==="system").map(s=>s.content);return{system:n.length?n.join(t):void 0,conversationMessages:e.filter(s=>s.role!=="system")}}parseJsonError(e,t,n=!1){if(!e)return{message:`HTTP ${t}`};try{let s=JSON.parse(e);if(s.error&&typeof s.error=="object"){let o={message:s.error.message||`HTTP ${t}`,type:s.error.type};return n&&(o.code=s.error.code),o}return s.message?{message:s.message}:{message:e}}catch{return{message:e}}}checkAndThrowError(e){if("type"in e&&e.type==="error"&&"message"in e){let t=e.message,n=e.code||"unknown",s=!!e.retryable;throw new N(t,n,s)}if("error"in e&&e.error){let t=this.extractErrorMessage(e.error);throw new N(t)}}extractErrorMessage(e){if(typeof e=="string")try{let t=JSON.parse(e);return t.error?.message||t.message||e}catch{return e}return typeof e=="object"&&e!==null?e.message||JSON.stringify(e):`${this.providerName} returned an error`}};var tt=class extends J{constructor(){super(...arguments),this.providerName="Anthropic",this.defaultBaseUrl="https://api.anthropic.com",this.path="/v1/messages"}buildHeaders(e){return{"x-api-key":e,"anthropic-version":"2023-06-01","Content-Type":"application/json",Accept:"application/json"}}buildPayload(e,t,n,s){let{system:o,conversationMessages:i}=this.extractSystemMessages(e),a={model:t,max_tokens:this.getMaxTokens(t),messages:this.withLastMessageCached(i),stream:s};if(n?.webSearch!==!1&&(a.tools=[{type:"web_search_20250305",name:"web_search"}]),o&&(a.system=[{type:"text",text:o,cache_control:{type:"ephemeral"}}]),this.isReasoningEnabled(n)){let c=n.reasoning;if(this.isModernModel(t)){let l={0:"low",1:"low",2:"medium",3:"high"};a.thinking={type:"adaptive"},a.output_config={effort:l[c]}}else{let l={0:0,1:2048,2:4096,3:8192};a.thinking={type:"enabled",budget_tokens:l[c]}}}return a}parseError(e,t){return this.parseJsonError(e,t)}parseNonStreamingResponse(e){if(!this.isAnthropicResponse(e))return{text:""};let t=e.content.filter(s=>s.type==="text").map(s=>s.text).join(""),n=e.content.filter(s=>s.type==="thinking").map(s=>s.thinking).join(`
649
649
 
650
- `);return{text:t,reasoning:n||void 0}}parseProviderStreamChunk(e){if(!("type"in e))return null;switch(e.type){case"content_block_delta":return e.delta.type==="text_delta"?{text:e.delta.text||""}:e.delta.type==="thinking_delta"?{reasoning:e.delta.thinking||""}:null;case"message_start":case"content_block_start":case"content_block_stop":case"message_delta":case"message_stop":case"ping":return null;default:return null}}withLastMessageCached(e){let t=e.length-1;return e.map((n,s)=>s===t?{role:n.role,content:[{type:"text",text:n.content,cache_control:{type:"ephemeral"}}]}:n)}isAnthropicResponse(e){return"content"in e&&Array.isArray(e.content)&&"type"in e&&e.type==="message"}isModernModel(e){let t=e.match(/^claude-\w+-(\d+)-(\d+)/);return!!t&&(+t[1]>4||+t[1]==4&&+t[2]>=6)}getMaxTokens(e){return this.isModernModel(e)?64e3:32e3}};var tt=class extends J{constructor(){super(...arguments),this.providerName="OpenAI",this.defaultBaseUrl="https://api.openai.com",this.path="/v1/responses",this.effortMap={0:"minimal",1:"low",2:"medium",3:"high"}}buildHeaders(e){return{Authorization:`Bearer ${e}`,"Content-Type":"application/json",Accept:"application/json"}}buildPayload(e,t,n,s){let o=this.convertMessagesToInput(e),i={model:t,input:o,stream:s};return n?.webSearch!==!1&&(i.tools=[{type:"web_search"}]),this.isReasoningEnabled(n)&&(i.reasoning={effort:this.effortMap[n.reasoning],summary:"auto"}),i}parseError(e,t){return this.parseJsonError(e,t,!0)}parseNonStreamingResponse(e){if(!this.isResponsesApiResponse(e))return{text:""};let t=e.output_text||"",n;if(e.output&&Array.isArray(e.output))for(let s of e.output)s.type==="reasoning"&&s.summary&&(n=s.summary.map(o=>o.text).join(`
650
+ `);return{text:t,reasoning:n||void 0}}parseProviderStreamChunk(e){if(!("type"in e))return null;switch(e.type){case"content_block_delta":return e.delta.type==="text_delta"?{text:e.delta.text||""}:e.delta.type==="thinking_delta"?{reasoning:e.delta.thinking||""}:null;case"message_start":case"content_block_start":case"content_block_stop":case"message_delta":case"message_stop":case"ping":return null;default:return null}}withLastMessageCached(e){let t=e.length-1;return e.map((n,s)=>s===t?{role:n.role,content:[{type:"text",text:n.content,cache_control:{type:"ephemeral"}}]}:n)}isAnthropicResponse(e){return"content"in e&&Array.isArray(e.content)&&"type"in e&&e.type==="message"}isModernModel(e){let t=e.match(/^claude-\w+-(\d+)-(\d+)/);return!!t&&(+t[1]>4||+t[1]==4&&+t[2]>=6)}getMaxTokens(e){return this.isModernModel(e)?64e3:32e3}};var rt=class extends J{constructor(){super(...arguments),this.providerName="OpenAI",this.defaultBaseUrl="https://api.openai.com",this.path="/v1/responses",this.effortMap={0:"minimal",1:"low",2:"medium",3:"high"}}buildHeaders(e){return{Authorization:`Bearer ${e}`,"Content-Type":"application/json",Accept:"application/json"}}buildPayload(e,t,n,s){let o=this.convertMessagesToInput(e),i={model:t,input:o,stream:s};return n?.webSearch!==!1&&(i.tools=[{type:"web_search"}]),this.isReasoningEnabled(n)&&(i.reasoning={effort:this.effortMap[n.reasoning],summary:"auto"}),i}parseError(e,t){return this.parseJsonError(e,t,!0)}parseNonStreamingResponse(e){if(!this.isResponsesApiResponse(e))return{text:""};let t=e.output_text||"",n;if(e.output&&Array.isArray(e.output))for(let s of e.output)s.type==="reasoning"&&s.summary&&(n=s.summary.map(o=>o.text).join(`
651
651
  `)),!t&&s.type==="message"&&s.content&&(t=s.content.filter(o=>o.type==="output_text").map(o=>o.text).join(""));return{text:t,reasoning:n}}parseProviderStreamChunk(e){if(!this.isResponsesApiEvent(e))return null;switch(e.type){case"error":return null;case"response.failed":{let s=e.response?.error,o=s?.message||"Response failed",i=s?.code==="insufficient_quota"||s?.code==="rate_limit_exceeded";throw new N(o,i?"rate_limit":"unknown",i)}case"response.output_text.delta":return{text:e.delta};case"response.reasoning_summary_text.delta":return{reasoning:e.delta};case"response.created":case"response.in_progress":case"response.output_item.added":case"response.output_item.done":case"response.content_part.added":case"response.content_part.done":case"response.output_text.done":case"response.output_text.annotation.added":case"response.reasoning_summary_text.done":case"response.completed":case"response.web_search_call.in_progress":case"response.web_search_call.searching":case"response.web_search_call.completed":return null;default:return null}}convertMessagesToInput(e){return e.map(t=>t.role==="system"?`System: ${t.content}`:t.role==="user"?`User: ${t.content}`:t.role==="assistant"?`Assistant: ${t.content}`:t.content).join(`
652
652
 
653
- `)}isResponsesApiEvent(e){return"type"in e&&typeof e.type=="string"}isResponsesApiResponse(e){return"object"in e&&e.object==="response"}};var rt=class extends J{constructor(){super(...arguments),this.providerName="Gemini",this.defaultBaseUrl="https://generativelanguage.googleapis.com",this.path="/v1beta/models"}getPath(e,t){return`/v1beta/models/${e}:${t?"streamGenerateContent":"generateContent"}${t?"?alt=sse":""}`}buildHeaders(e){return{"Content-Type":"application/json","x-goog-api-key":e}}buildPayload(e,t,n,s){let{system:o,conversationMessages:i}=this.extractSystemMessages(e,`
653
+ `)}isResponsesApiEvent(e){return"type"in e&&typeof e.type=="string"}isResponsesApiResponse(e){return"object"in e&&e.object==="response"}};var nt=class extends J{constructor(){super(...arguments),this.providerName="Gemini",this.defaultBaseUrl="https://generativelanguage.googleapis.com",this.path="/v1beta/models"}getPath(e,t){return`/v1beta/models/${e}:${t?"streamGenerateContent":"generateContent"}${t?"?alt=sse":""}`}buildHeaders(e){return{"Content-Type":"application/json","x-goog-api-key":e}}buildPayload(e,t,n,s){let{system:o,conversationMessages:i}=this.extractSystemMessages(e,`
654
654
  `),c={contents:i.map(l=>({role:l.role==="assistant"?"model":"user",parts:[{text:l.content}]}))};return n?.webSearch!==!1&&(c.tools=[{google_search:{}}]),o&&(c.systemInstruction={role:"system",parts:[{text:o}]}),this.isReasoningEnabled(n)&&(c.generationConfig={temperature:.7+n.reasoning*.1}),c}parseError(e,t){if(!e)return{message:`HTTP ${t}`};try{let n=JSON.parse(e),s=Array.isArray(n)?n[0]?.error:n?.error;return s&&typeof s=="object"?{message:(s.message||`HTTP ${t}`).split(`
655
- `)[0],type:s.status,code:s.code?.toString()}:n.message?{message:n.message}:{message:e}}catch{return{message:e}}}parseNonStreamingResponse(e){if(this.checkGeminiError(e),!this.isGeminiResponse(e))return{text:"",status:"failed",error:"Invalid response format"};let t=this.extractText(e)||"",n=e.candidates?.[0]?.finishReason,s="complete";return n==="MAX_TOKENS"?s="interrupted":(n==="SAFETY"||n==="RECITATION")&&(s="failed"),{text:t,status:s}}parseProviderStreamChunk(e){if(this.checkGeminiError(e),!this.isGeminiResponse(e))return null;let t=this.extractText(e);return t?{text:t}:null}isGeminiResponse(e){return typeof e=="object"&&e!==null&&"candidates"in e&&Array.isArray(e.candidates)}extractText(e){let t=e.candidates?.[0];if(t?.content?.parts)return t.content.parts.map(n=>n.text).filter(Boolean).join("")}checkGeminiError(e){if(typeof e=="object"&&e!==null&&"error"in e){let t=e.error,n;if(typeof t=="string")n=t;else if(typeof t=="object"&&t!==null){let s=t;n=s.message||s.status||"Gemini returned an error"}else n="Gemini returned an error";throw new N(n)}if(this.isGeminiResponse(e)&&e.promptFeedback?.blockReason){let t=e.promptFeedback.blockReason;throw new N(`Prompt blocked: ${t}`)}}};var nt=class extends J{constructor(){super(...arguments),this.providerName="OpenRouter",this.defaultBaseUrl="https://openrouter.ai/api",this.path="/api/v1/chat/completions",this.effortMap={0:"low",1:"low",2:"medium",3:"high"}}buildHeaders(e,t){let n={Authorization:`Bearer ${e}`,"x-api-key":e,"Content-Type":"application/json",Accept:"application/json","X-Title":"Typebulb"};return t&&(n["HTTP-Referer"]=t,n.Referer=t,n.Origin=t),n}buildPayload(e,t,n,s){let o={model:t,messages:e,stream:s};return n?.webSearch===!0&&(o.plugins=[{id:"web"}]),this.isReasoningEnabled(n)&&(o.reasoning={effort:this.effortMap[n.reasoning]}),o}parseError(e,t){return this.parseJsonError(e,t,!0)}parseNonStreamingResponse(e){if(!this.hasChoices(e))return{text:""};let t=e.choices[0],n=t?.message?.content??t?.text??"",s=t?.message?.reasoning??e.reasoning;return{text:n,reasoning:s}}parseProviderStreamChunk(e){if(!this.hasChoices(e))return null;let t=e.choices[0];if(!t)return null;let n=t.delta||t.message;if(!n)return null;let s=n.content||void 0,o=n.reasoning||void 0;return!s&&!o?null:{text:s,reasoning:o}}hasChoices(e){return typeof e=="object"&&e!==null&&"choices"in e&&Array.isArray(e.choices)}};var Fi=new Map([["openai",new tt],["openrouter",new nt],["anthropic",new et],["gemini",new rt]]);function ue(r){let e=Fi.get(r);if(!e)throw new Error(`Unsupported protocol: ${r}`);return e}async function xr(r,e){let t=ue(r.protocol),n=t.getPath(e.model,e.stream),s=new URL(n,r.baseUrl).toString(),o=t.buildHeaders(r.apiKey,e.origin),i=t.buildPayload(e.messages,e.model,{reasoning:e.reasoning,webSearch:e.webSearch},e.stream);return e.modifyPayload?.(i),fetch(s,{method:"POST",headers:o,body:JSON.stringify(i),signal:e.signal})}async function Sr(r,e){let t=ue(e),n=await r.text().catch(()=>""),{message:s}=t.parseError(n,r.status),o=r.status,i="unknown";return o===429?i="rate_limit":o===413&&(i="context_exceeded"),{code:i,message:s,retryable:o===429}}function is(r){let e=r.indexOf(`\r
655
+ `)[0],type:s.status,code:s.code?.toString()}:n.message?{message:n.message}:{message:e}}catch{return{message:e}}}parseNonStreamingResponse(e){if(this.checkGeminiError(e),!this.isGeminiResponse(e))return{text:"",status:"failed",error:"Invalid response format"};let t=this.extractText(e)||"",n=e.candidates?.[0]?.finishReason,s="complete";return n==="MAX_TOKENS"?s="interrupted":(n==="SAFETY"||n==="RECITATION")&&(s="failed"),{text:t,status:s}}parseProviderStreamChunk(e){if(this.checkGeminiError(e),!this.isGeminiResponse(e))return null;let t=this.extractText(e);return t?{text:t}:null}isGeminiResponse(e){return typeof e=="object"&&e!==null&&"candidates"in e&&Array.isArray(e.candidates)}extractText(e){let t=e.candidates?.[0];if(t?.content?.parts)return t.content.parts.map(n=>n.text).filter(Boolean).join("")}checkGeminiError(e){if(typeof e=="object"&&e!==null&&"error"in e){let t=e.error,n;if(typeof t=="string")n=t;else if(typeof t=="object"&&t!==null){let s=t;n=s.message||s.status||"Gemini returned an error"}else n="Gemini returned an error";throw new N(n)}if(this.isGeminiResponse(e)&&e.promptFeedback?.blockReason){let t=e.promptFeedback.blockReason;throw new N(`Prompt blocked: ${t}`)}}};var st=class extends J{constructor(){super(...arguments),this.providerName="OpenRouter",this.defaultBaseUrl="https://openrouter.ai/api",this.path="/api/v1/chat/completions",this.effortMap={0:"low",1:"low",2:"medium",3:"high"}}buildHeaders(e,t){let n={Authorization:`Bearer ${e}`,"x-api-key":e,"Content-Type":"application/json",Accept:"application/json","X-Title":"Typebulb"};return t&&(n["HTTP-Referer"]=t,n.Referer=t,n.Origin=t),n}buildPayload(e,t,n,s){let o={model:t,messages:e,stream:s};return n?.webSearch===!0&&(o.plugins=[{id:"web"}]),this.isReasoningEnabled(n)&&(o.reasoning={effort:this.effortMap[n.reasoning]}),o}parseError(e,t){return this.parseJsonError(e,t,!0)}parseNonStreamingResponse(e){if(!this.hasChoices(e))return{text:""};let t=e.choices[0],n=t?.message?.content??t?.text??"",s=t?.message?.reasoning??e.reasoning;return{text:n,reasoning:s}}parseProviderStreamChunk(e){if(!this.hasChoices(e))return null;let t=e.choices[0];if(!t)return null;let n=t.delta||t.message;if(!n)return null;let s=n.content||void 0,o=n.reasoning||void 0;return!s&&!o?null:{text:s,reasoning:o}}hasChoices(e){return typeof e=="object"&&e!==null&&"choices"in e&&Array.isArray(e.choices)}};var Ui=new Map([["openai",new rt],["openrouter",new st],["anthropic",new tt],["gemini",new nt]]);function ue(r){let e=Ui.get(r);if(!e)throw new Error(`Unsupported protocol: ${r}`);return e}async function Pr(r,e){let t=ue(r.protocol),n=t.getPath(e.model,e.stream),s=new URL(n,r.baseUrl).toString(),o=t.buildHeaders(r.apiKey,e.origin),i=t.buildPayload(e.messages,e.model,{reasoning:e.reasoning,webSearch:e.webSearch},e.stream);return e.modifyPayload?.(i),fetch(s,{method:"POST",headers:o,body:JSON.stringify(i),signal:e.signal})}async function Er(r,e){let t=ue(e),n=await r.text().catch(()=>""),{message:s}=t.parseError(n,r.status),o=r.status,i="unknown";return o===429?i="rate_limit":o===413&&(i="context_exceeded"),{code:i,message:s,retryable:o===429}}function ls(r){let e=r.indexOf(`\r
656
656
  \r
657
657
  `),t=r.indexOf(`
658
658
 
659
- `);return e!==-1&&(t===-1||e<t)?{pos:e,len:4}:t!==-1?{pos:t,len:2}:{pos:-1,len:0}}function Pr(r){let t=r.split(/\r?\n/).filter(s=>s.startsWith("data:"));if(!t.length)return null;let n=t.map(s=>s.replace(/^data:\s?/,"")).join(`
660
- `).trim();if(!n)return null;if(n==="[DONE]")return"done";try{return JSON.parse(n)}catch{return null}}async function as(r,e,t){let n=new TextDecoder,s="",o=!1,i=t?new Promise((a,c)=>{t.aborted&&c(new Error("Aborted")),t.addEventListener("abort",()=>c(new Error("Aborted")),{once:!0})}):null;for(;;){let a=i?await Promise.race([r.read(),i]):await r.read(),{done:c,value:l}=a;if(c){if(s.trim()){let f=Pr(s);f!==null&&f!=="done"&&e(f)}break}o=!0,s+=n.decode(l,{stream:!0});let{pos:d,len:u}=is(s);for(;d!==-1;){let f=s.slice(0,d);s=s.slice(d+u);let m=Pr(f);if(m==="done"){s="";break}m!==null&&e(m),{pos:d,len:u}=is(s)}}return{receivedAnyData:o}}async function Er(r,e){let t=e??(r.headers.get("X-Provider-Protocol")||"openai"),n=ue(t);if(!r.body)throw new Error("Response body is missing");let s=r.body.getReader(),o="";return await as(s,i=>{let a=n.parseStreamChunk(i);a?.text&&(o+=a.text)}),o}import*as Rr from"fs/promises";import*as st from"path";var Ft=class{async get(e){let t=L(e),n=st.join(qe,t+".bin"),s=st.join(qe,t+".json");try{let[o,i]=await Promise.all([Rr.readFile(n),Rr.readFile(s,"utf8")]),a=JSON.parse(i);return{body:o,contentType:a.contentType,cacheControl:a.cacheControl}}catch{return}}async set(e,t){await S();let n=L(e),s=st.join(qe,n+".bin"),o=st.join(qe,n+".json"),i={url:e,contentType:t.contentType,cacheControl:t.cacheControl};await Promise.all([F(s,t.body),F(o,JSON.stringify(i))])}};de();var ds="127.0.0.1",Ui=new Set(["localhost","127.0.0.1","::1"]);function Wi(r){if(r)try{return new URL(r.includes("://")?r:`http://${r}`).hostname}catch{return}}function cs(r){let e=Wi(r);return!!e&&Ui.has(e)}function jt(r){return r instanceof Error?r.message:"Unknown error"}async function Nt(r){let{getHtml:e,basePath:t,port:n,reloadEmitter:s,getServerExports:o,localOverride:i,trusted:a=!1,trustHint:c,staticAssets:l}=r,d=new ji;d.use("*",async(p,h)=>{if(!cs(p.req.header("host")))return p.text("Forbidden: untrusted Host",403);await h()}),d.use("*",async(p,h)=>{await h(),p.res.headers.set("Cross-Origin-Opener-Policy","same-origin"),p.res.headers.set("Cross-Origin-Embedder-Policy","credentialless")});let u=["/__fs/*","/__api/*","/__ai"],f=async(p,h)=>{if(!a){let b=new URL(p.req.url).pathname,x=b.startsWith("/__fs")?"the filesystem":b==="/__ai"?"AI (your API keys)":"server-side code (server.ts)";Vn(process.pid,x);let w=c?`
661
- ${c}`:"";return p.text(`Forbidden: this capability requires --trust.${w}`,403)}await h()},m=async(p,h)=>{let b=p.req.header("sec-fetch-site");if(b){if(b==="cross-site")return p.text("Forbidden: cross-site request",403)}else{let x=p.req.header("origin");if(x&&!cs(x))return p.text("Forbidden: cross-origin request",403)}await h()};for(let p of u)d.use(p,f),d.use(p,m);d.use("/__log",m),d.post("/__log",async p=>{try{let{args:h}=await p.req.json();console.log(...h||[])}catch{}return p.json({ok:!0})}),d.get("/",p=>p.html(e())),d.post("/__fs/read",async p=>{try{let{path:h}=await p.req.json(),b=Tr(h,t),x=await pe.readFile(b);return new Response(new Uint8Array(x),{headers:{"Content-Type":"application/octet-stream"}})}catch(h){let b=jt(h);return p.json({error:b},400)}}),d.post("/__fs/write",async p=>{try{let h=p.req.query("path");if(!h)return p.json({error:"Missing path"},400);let b=Tr(h,t);return await pe.mkdir(H.dirname(b),{recursive:!0}),await pe.writeFile(b,Buffer.from(await p.req.arrayBuffer())),p.json({success:!0})}catch(h){let b=jt(h);return p.json({error:b},400)}});let g={log:console.log};d.post("/__api/:name",async p=>{try{let h=o?.(),b=p.req.param("name"),x=h?.[b]??g[b];if(!x||typeof x!="function")return p.json({error:`API function '${b}' not found`},404);let{args:w}=await p.req.json(),V=await x(...w||[]);return p.json({result:V})}catch(h){let b=jt(h);return p.json({error:b},500)}}),d.post("/__ai",async p=>{try{let{messages:h,system:b,reasoning:x,provider:w,model:V,webSearch:se}=await p.req.json();if(!h||!Array.isArray(h)||h.length===0)return p.json({message:"messages array is required",code:"unknown",retryable:!1},400);let Q=Ji(w,V);if(typeof Q=="string")return p.json({message:Q,code:"unknown",retryable:!1},400);let zt=[...b?[{role:"system",content:b}]:[],...h.map(it=>({role:it.role,content:it.content}))],me=await xr(Q,{model:Q.model,messages:zt,stream:!0,reasoning:x??0,webSearch:se??!0});if(!me.ok){let it=await Sr(me,Q.protocol);return p.json(it,me.status)}let Fr=await Er(me,Q.protocol);return Fr||console.warn("[tb.ai] Empty response from provider"),p.json({text:Fr})}catch(h){if(h instanceof N)return p.json({message:h.message,code:h.code,retryable:h.retryable},500);let b=jt(h);return p.json({message:b,code:"unknown",retryable:!1},500)}}),d.get("/__models",async p=>{try{let h=await Bt();return p.json(h)}catch{return p.json([],200)}});let v=["esm.sh","unpkg.com","cdn.jsdelivr.net","cdnjs.cloudflare.com"],$=new Ft;d.get("/proxy/*",async p=>{let h=new URL(p.req.url),x=(h.pathname+h.search).slice(7),w=x.lastIndexOf("https://");return w===-1?p.text("Invalid proxy URL",400):O(p,x.slice(w))}),i&&ls(d,`/local/${i.name}/`,i.serveDir),l&&ls(d,l.mount,l.dir);async function O(p,h){let b;try{b=new URL(h)}catch{return p.text("Invalid URL",400)}if(b.protocol!=="https:")return p.text("HTTPS only",400);if(!v.includes(b.hostname))return p.text("Host not allowed",403);let x=await $.get(h);if(x)return new Response(x.body,{status:200,headers:kr(x.contentType,x.cacheControl)});try{let w=await fetch(h,{headers:{Accept:p.req.header("Accept")||"*/*"},redirect:"follow"});if(!w.ok)return p.text(`Upstream ${w.status}`,w.status);let V=w.headers.get("Content-Type")||void 0,se=w.headers.get("Cache-Control")||void 0;if(w.body){let[Q,zt]=w.body.tee();return(async()=>{try{let me=await new Response(zt).arrayBuffer();await $.set(h,{body:Buffer.from(me),contentType:V,cacheControl:se})}catch{}})(),new Response(Q,{status:w.status,headers:kr(V,se)})}return new Response(null,{status:w.status,headers:kr(V,se)})}catch(w){return p.text(`Proxy fetch failed: ${w instanceof Error?w.message:w}`,502)}}s&&d.get("/__reload",p=>Li(p,async h=>{let b=()=>{h.writeSSE({event:"reload",data:""})};for(s.on("reload",b),h.onAbort(()=>{s.removeListener("reload",b)});;)await h.sleep(3e4)}));let E=/^\/(v\d+\/|stable\/|node\/|gh\/|@[^/]+\/[^@/]+@|[^@/]+@)/;d.notFound(async p=>{if(p.req.method!=="GET")return p.text("Not Found",404);let h=new URL(p.req.url);return E.test(h.pathname)?O(p,"https://esm.sh"+h.pathname+h.search):p.text("Not Found",404)});let T=Ni({fetch:d.fetch,port:n,hostname:ds});return{port:n,close:()=>T.close()}}function Ji(r,e){let t=r??process.env.TB_AI_PROVIDER,n=e??process.env.TB_AI_MODEL;if(!t)return"No provider specified. Set TB_AI_PROVIDER in your .env file or pass provider in the tb.ai() call.";if(!n)return"No model specified. Set TB_AI_MODEL in your .env file or pass model in the tb.ai() call.";let s;try{s=ue(t)}catch{return`Unknown provider '${t}'.`}let o=Ce[t],i=process.env[o];return i?{apiKey:i,baseUrl:s.defaultBaseUrl,protocol:t,model:n,isFreeModel:!1}:`No API key for '${t}'. Set ${o} in your .env file.`}function kr(r,e){let t=new Headers;return r&&t.set("Content-Type",r),e&&t.set("Cache-Control",e),t.set("Access-Control-Allow-Origin","*"),t.set("Cross-Origin-Resource-Policy","cross-origin"),t}function ls(r,e,t){r.get(`${e}*`,async n=>{let{pathname:s}=new URL(n.req.url);if(!s.startsWith(e))return n.text("Not Found",404);let o=decodeURIComponent(s.slice(e.length));try{let i=Tr(o,t),a=await pe.readFile(i);return new Response(a,{headers:{"Content-Type":Hi(i)}})}catch{return n.text("Not Found",404)}})}function Hi(r){switch(H.extname(r).toLowerCase()){case".js":case".mjs":return"text/javascript";case".wasm":return"application/wasm";case".json":case".map":return"application/json";default:return"application/octet-stream"}}function Tr(r,e){let t=H.resolve(e,r),n=H.normalize(e),s=H.normalize(t);if(s!==n&&!s.startsWith(n+H.sep))throw new Error("Path traversal detected - access denied");return t}async function ot(r){let e=await import("net");return new Promise(t=>{let n=e.createServer();n.listen(r,ds,()=>{let s=n.address(),o=typeof s=="object"&&s?s.port:r;n.close(()=>t(o))}),n.on("error",()=>{t(ot(r+1))})})}import us from"chokidar";var ps={persistent:!0,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50}};function Lt(r){let{bulbPath:e,emitter:t}=r,n=us.watch(e,ps);return n.on("change",()=>{t.emit("reload")}),()=>n.close()}function Ut(r){let{dir:e,onChange:t,debounceMs:n=150}=r,s,o=us.watch(e,ps);return o.on("all",()=>{s&&clearTimeout(s),s=setTimeout(t,n)}),()=>{s&&clearTimeout(s),o.close()}}de();async function hs(r,e,t,n,s){let o=process.cwd(),i=$t(process.pid),a=e.watch?new fs:void 0,c=ne(e.mode);console.log(`Loading ${Ie.basename(r)}...`);let{html:l,bulb:d,serverExports:u}=await pr(r,e.watch,e.trust,n,s);_e(c,r,d.server);let f=await ot(e.port),m=await Nt({getHtml:()=>l,basePath:o,port:f,reloadEmitter:a,getServerExports:()=>u,localOverride:n?{name:n.name,serveDir:n.serveDir}:void 0,trusted:e.trust,trustHint:t}),g=`http://localhost:${f}`,v=e.trust?void 0:Re(d);await Ot({pid:process.pid,port:f,url:g,file:r,cwd:process.cwd(),startedAt:Date.now(),trust:e.trust,predicted:v}),console.log(`
659
+ `);return e!==-1&&(t===-1||e<t)?{pos:e,len:4}:t!==-1?{pos:t,len:2}:{pos:-1,len:0}}function Rr(r){let t=r.split(/\r?\n/).filter(s=>s.startsWith("data:"));if(!t.length)return null;let n=t.map(s=>s.replace(/^data:\s?/,"")).join(`
660
+ `).trim();if(!n)return null;if(n==="[DONE]")return"done";try{return JSON.parse(n)}catch{return null}}async function ds(r,e,t){let n=new TextDecoder,s="",o=!1,i=t?new Promise((a,c)=>{t.aborted&&c(new Error("Aborted")),t.addEventListener("abort",()=>c(new Error("Aborted")),{once:!0})}):null;for(;;){let a=i?await Promise.race([r.read(),i]):await r.read(),{done:c,value:l}=a;if(c){if(s.trim()){let f=Rr(s);f!==null&&f!=="done"&&e(f)}break}o=!0,s+=n.decode(l,{stream:!0});let{pos:d,len:u}=ls(s);for(;d!==-1;){let f=s.slice(0,d);s=s.slice(d+u);let m=Rr(f);if(m==="done"){s="";break}m!==null&&e(m),{pos:d,len:u}=ls(s)}}return{receivedAnyData:o}}async function kr(r,e){let t=e??(r.headers.get("X-Provider-Protocol")||"openai"),n=ue(t);if(!r.body)throw new Error("Response body is missing");let s=r.body.getReader(),o="";return await ds(s,i=>{let a=n.parseStreamChunk(i);a?.text&&(o+=a.text)}),o}import*as Tr from"fs/promises";import*as ot from"path";var Ft=class{async get(e){let t=L(e),n=ot.join(Ge,t+".bin"),s=ot.join(Ge,t+".json");try{let[o,i]=await Promise.all([Tr.readFile(n),Tr.readFile(s,"utf8")]),a=JSON.parse(i);return{body:o,contentType:a.contentType,cacheControl:a.cacheControl}}catch{return}}async set(e,t){await S();let n=L(e),s=ot.join(Ge,n+".bin"),o=ot.join(Ge,n+".json"),i={url:e,contentType:t.contentType,cacheControl:t.cacheControl};await Promise.all([j(s,t.body),j(o,JSON.stringify(i))])}};de();var fs="127.0.0.1",Vi=new Set(["localhost","127.0.0.1","::1"]);function zi(r){if(r)try{return new URL(r.includes("://")?r:`http://${r}`).hostname}catch{return}}function us(r){let e=zi(r);return!!e&&Vi.has(e)}function Nt(r){return r instanceof Error?r.message:"Unknown error"}async function Lt(r){let{getHtml:e,basePath:t,port:n,reloadEmitter:s,getServerExports:o,localOverride:i,trusted:a=!1,trustHint:c,staticAssets:l}=r,d=new Wi;d.use("*",async(p,h)=>{if(!us(p.req.header("host")))return p.text("Forbidden: untrusted Host",403);await h()}),d.use("*",async(p,h)=>{await h(),p.res.headers.set("Cross-Origin-Opener-Policy","same-origin"),p.res.headers.set("Cross-Origin-Embedder-Policy","credentialless")});let u=["/__fs/*","/__api/*","/__ai"],f=async(p,h)=>{if(!a){let b=new URL(p.req.url).pathname,x=b.startsWith("/__fs")?"the filesystem":b==="/__ai"?"AI (your API keys)":"server-side code (server.ts)";qn(process.pid,x);let w=c?`
661
+ ${c}`:"";return p.text(`Forbidden: this capability requires --trust.${w}`,403)}await h()},m=async(p,h)=>{let b=p.req.header("sec-fetch-site");if(b){if(b==="cross-site")return p.text("Forbidden: cross-site request",403)}else{let x=p.req.header("origin");if(x&&!us(x))return p.text("Forbidden: cross-origin request",403)}await h()};for(let p of u)d.use(p,f),d.use(p,m);d.use("/__log",m),d.post("/__log",async p=>{try{let{args:h}=await p.req.json();console.log(...h||[])}catch{}return p.json({ok:!0})}),d.get("/",p=>p.html(e())),d.post("/__fs/read",async p=>{try{let{path:h}=await p.req.json(),b=Ar(h,t),x=await pe.readFile(b);return new Response(new Uint8Array(x),{headers:{"Content-Type":"application/octet-stream"}})}catch(h){let b=Nt(h);return p.json({error:b},400)}}),d.post("/__fs/write",async p=>{try{let h=p.req.query("path");if(!h)return p.json({error:"Missing path"},400);let b=Ar(h,t);return await pe.mkdir(H.dirname(b),{recursive:!0}),await pe.writeFile(b,Buffer.from(await p.req.arrayBuffer())),p.json({success:!0})}catch(h){let b=Nt(h);return p.json({error:b},400)}});let g={log:console.log};d.post("/__api/:name",async p=>{try{let h=o?.(),b=p.req.param("name"),x=h?.[b]??g[b];if(!x||typeof x!="function")return p.json({error:`API function '${b}' not found`},404);let{args:w}=await p.req.json(),V=await x(...w||[]);return p.json({result:V})}catch(h){let b=Nt(h);return p.json({error:b},500)}}),d.post("/__ai",async p=>{try{let{messages:h,system:b,reasoning:x,provider:w,model:V,webSearch:se}=await p.req.json();if(!h||!Array.isArray(h)||h.length===0)return p.json({message:"messages array is required",code:"unknown",retryable:!1},400);let Q=qi(w,V);if(typeof Q=="string")return p.json({message:Q,code:"unknown",retryable:!1},400);let qt=[...b?[{role:"system",content:b}]:[],...h.map(at=>({role:at.role,content:at.content}))],me=await Pr(Q,{model:Q.model,messages:qt,stream:!0,reasoning:x??0,webSearch:se??!0});if(!me.ok){let at=await Er(me,Q.protocol);return p.json(at,me.status)}let Nr=await kr(me,Q.protocol);return Nr||console.warn("[tb.ai] Empty response from provider"),p.json({text:Nr})}catch(h){if(h instanceof N)return p.json({message:h.message,code:h.code,retryable:h.retryable},500);let b=Nt(h);return p.json({message:b,code:"unknown",retryable:!1},500)}}),d.get("/__models",async p=>{try{let h=await jt();return p.json(h)}catch{return p.json([],200)}});let v=["esm.sh","unpkg.com","cdn.jsdelivr.net","cdnjs.cloudflare.com"],$=new Ft;d.get("/proxy/*",async p=>{let h=new URL(p.req.url),x=(h.pathname+h.search).slice(7),w=x.lastIndexOf("https://");return w===-1?p.text("Invalid proxy URL",400):O(p,x.slice(w))}),i&&ps(d,`/local/${i.name}/`,i.serveDir),l&&ps(d,l.mount,l.dir);async function O(p,h){let b;try{b=new URL(h)}catch{return p.text("Invalid URL",400)}if(b.protocol!=="https:")return p.text("HTTPS only",400);if(!v.includes(b.hostname))return p.text("Host not allowed",403);let x=await $.get(h);if(x)return new Response(x.body,{status:200,headers:_r(x.contentType,x.cacheControl)});try{let w=await fetch(h,{headers:{Accept:p.req.header("Accept")||"*/*"},redirect:"follow"});if(!w.ok)return p.text(`Upstream ${w.status}`,w.status);let V=w.headers.get("Content-Type")||void 0,se=w.headers.get("Cache-Control")||void 0;if(w.body){let[Q,qt]=w.body.tee();return(async()=>{try{let me=await new Response(qt).arrayBuffer();await $.set(h,{body:Buffer.from(me),contentType:V,cacheControl:se})}catch{}})(),new Response(Q,{status:w.status,headers:_r(V,se)})}return new Response(null,{status:w.status,headers:_r(V,se)})}catch(w){return p.text(`Proxy fetch failed: ${w instanceof Error?w.message:w}`,502)}}s&&d.get("/__reload",p=>Hi(p,async h=>{let b=()=>{h.writeSSE({event:"reload",data:""})};for(s.on("reload",b),h.onAbort(()=>{s.removeListener("reload",b)});;)await h.sleep(3e4)}));let E=/^\/(v\d+\/|stable\/|node\/|gh\/|@[^/]+\/[^@/]+@|[^@/]+@)/;d.notFound(async p=>{if(p.req.method!=="GET")return p.text("Not Found",404);let h=new URL(p.req.url);return E.test(h.pathname)?O(p,"https://esm.sh"+h.pathname+h.search):p.text("Not Found",404)});let T=Ji({fetch:d.fetch,port:n,hostname:fs});return{port:n,close:()=>T.close()}}function qi(r,e){let t=r??process.env.TB_AI_PROVIDER,n=e??process.env.TB_AI_MODEL;if(!t)return"No provider specified. Set TB_AI_PROVIDER in your .env file or pass provider in the tb.ai() call.";if(!n)return"No model specified. Set TB_AI_MODEL in your .env file or pass model in the tb.ai() call.";let s;try{s=ue(t)}catch{return`Unknown provider '${t}'.`}let o=Ie[t],i=process.env[o];return i?{apiKey:i,baseUrl:s.defaultBaseUrl,protocol:t,model:n,isFreeModel:!1}:`No API key for '${t}'. Set ${o} in your .env file.`}function _r(r,e){let t=new Headers;return r&&t.set("Content-Type",r),e&&t.set("Cache-Control",e),t.set("Access-Control-Allow-Origin","*"),t.set("Cross-Origin-Resource-Policy","cross-origin"),t}function ps(r,e,t){r.get(`${e}*`,async n=>{let{pathname:s}=new URL(n.req.url);if(!s.startsWith(e))return n.text("Not Found",404);let o=decodeURIComponent(s.slice(e.length));try{let i=Ar(o,t),a=await pe.readFile(i);return new Response(a,{headers:{"Content-Type":Gi(i)}})}catch{return n.text("Not Found",404)}})}function Gi(r){switch(H.extname(r).toLowerCase()){case".js":case".mjs":return"text/javascript";case".wasm":return"application/wasm";case".json":case".map":return"application/json";default:return"application/octet-stream"}}function Ar(r,e){let t=H.resolve(e,r),n=H.normalize(e),s=H.normalize(t);if(s!==n&&!s.startsWith(n+H.sep))throw new Error("Path traversal detected - access denied");return t}async function it(r){let e=await import("net");return new Promise(t=>{let n=e.createServer();n.listen(r,fs,()=>{let s=n.address(),o=typeof s=="object"&&s?s.port:r;n.close(()=>t(o))}),n.on("error",()=>{t(it(r+1))})})}import ms from"chokidar";var hs={persistent:!0,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50}};function Ut(r){let{bulbPath:e,emitter:t}=r,n=ms.watch(e,hs);return n.on("change",()=>{t.emit("reload")}),()=>n.close()}function Wt(r){let{dir:e,onChange:t,debounceMs:n=150}=r,s,o=ms.watch(e,hs);return o.on("all",()=>{s&&clearTimeout(s),s=setTimeout(t,n)}),()=>{s&&clearTimeout(s),o.close()}}de();async function bs(r,e,t,n,s){let o=process.cwd(),i=Ot(process.pid),a=e.watch?new gs:void 0,c=ne(e.mode);console.log(`Loading ${$e.basename(r)}...`);let{html:l,bulb:d,serverExports:u}=await fr(r,e.watch,e.trust,n,s);Ae(c,r,d.server);let f=await it(e.port),m=await Lt({getHtml:()=>l,basePath:o,port:f,reloadEmitter:a,getServerExports:()=>u,localOverride:n?{name:n.name,serveDir:n.serveDir}:void 0,trusted:e.trust,trustHint:t}),g=`http://localhost:${f}`,v=e.trust?void 0:Re(d);await Dt({pid:process.pid,port:f,url:g,file:r,cwd:process.cwd(),startedAt:Date.now(),trust:e.trust,predicted:v}),console.log(`
662
662
  ${d.name}`),console.log(` ${g}`),f!==e.port&&console.log(` (port ${e.port} was busy)`),e.trust?console.log(" trust: granted (filesystem, AI, server.ts enabled)"):console.log(v?` trust: sandboxed \u2014 this bulb appears to use ${v}; re-run with --trust to enable it:
663
663
  ${t}
664
664
  `:` trust: sandboxed \u2014 re-run with --trust to enable filesystem / AI / server.ts
665
665
  `),e.watch&&console.log(` Watching for changes...
666
- `);let $,O;if(e.watch&&a){let T=new fs;if(T.on("reload",async()=>{try{console.log("Recompiling...");let p=await pr(r,!0,e.trust,n,s);l=p.html,u=p.serverExports,a.emit("reload"),console.log(`Done. Browser reloading...
667
- `)}catch(p){console.error("Compile error:",p)}}),$=Lt({bulbPath:r,emitter:T}),n){let{name:p,serveDir:h}=n;O=Ut({dir:h,onChange:()=>{console.log(`Local package '${p}' changed. Browser reloading...
666
+ `);let $,O;if(e.watch&&a){let T=new gs;if(T.on("reload",async()=>{try{console.log("Recompiling...");let p=await fr(r,!0,e.trust,n,s);l=p.html,u=p.serverExports,a.emit("reload"),console.log(`Done. Browser reloading...
667
+ `)}catch(p){console.error("Compile error:",p)}}),$=Ut({bulbPath:r,emitter:T}),n){let{name:p,serveDir:h}=n;O=Wt({dir:h,onChange:()=>{console.log(`Local package '${p}' changed. Browser reloading...
668
668
  `),a.emit("reload")}})}}e.open&&await Pe(g);let E=async()=>{console.log(`
669
- Shutting down...`),m.close(),$?.(),O?.(),i(),await Ze(process.pid);let T=Ie.join(Ie.dirname(r),".typebulb","server.mjs");await ms.rm(T,{force:!0}).catch(()=>{}),process.exit(0)};process.on("SIGINT",E),process.on("SIGTERM",E)}import{readFileSync as Vs,copyFileSync as Na,existsSync as La}from"fs";import*as I from"path";import{fileURLToPath as Ua}from"url";import{EventEmitter as Wa}from"events";de();var _r="/agents/claude/client.js",Vi=`
669
+ Shutting down...`),m.close(),$?.(),O?.(),i(),await et(process.pid);let T=$e.join($e.dirname(r),".typebulb","server.mjs");await ys.rm(T,{force:!0}).catch(()=>{}),process.exit(0)};process.on("SIGINT",E),process.on("SIGTERM",E)}import{readFileSync as Gs,copyFileSync as Ja,existsSync as Ha}from"fs";import*as I from"path";import{fileURLToPath as Va}from"url";import{EventEmitter as za}from"events";de();var Cr="/agents/claude/client.js",Ki=`
670
670
  (() => {
671
671
  const api = async (name, ...args) => {
672
672
  const resp = await fetch('/__api/' + name, {
@@ -701,15 +701,15 @@ Shutting down...`),m.close(),$?.(),O?.(),i(),await Ze(process.pid);let T=Ie.join
701
701
  es.onerror = () => { es.close(); };
702
702
  }
703
703
  })();
704
- `;function gs(r){let{name:e,styles:t,mountHtml:n,watch:s,theme:o}=r;return`<!DOCTYPE html>
704
+ `;function ws(r){let{name:e,styles:t,mountHtml:n,watch:s,theme:o}=r;return`<!DOCTYPE html>
705
705
  <html>
706
706
  <head>
707
707
  <meta charset="utf-8">
708
708
  <meta name="viewport" content="width=device-width, initial-scale=1">
709
- <title>${wt(e)} - typebulb</title>
710
- ${xt(e,o)}
709
+ <title>${vt(e)} - typebulb</title>
710
+ ${St(e,o)}
711
711
  <style>
712
- ${vt}
712
+ ${xt}
713
713
  </style>
714
714
  <style>
715
715
  ${t}
@@ -721,16 +721,16 @@ ${n}
721
721
  ${s?"<script>window.__TYPEBULB_WATCH__ = true;</script>":""}
722
722
 
723
723
  <script>
724
- ${Vi}
724
+ ${Ki}
725
725
  </script>
726
726
 
727
- <script type="module" src="${_r}"></script>
727
+ <script type="module" src="${Cr}"></script>
728
728
  </body>
729
- </html>`}async function zs(r){let e=process.cwd(),t=$t(process.pid),n=r.watch?new Wa:void 0,s=ne(r.mode),o=await Promise.resolve().then(()=>(Hs(),Js));_e(s,I.join(e,"viewer"));let i=I.dirname(Ua(import.meta.url)),a=I.join(i,"agents","claude"),c=I.join(i,"..","agents","claude"),l=I.join(a,"styles.css"),d=I.join(a,"index.html"),u=()=>gs({name:"Claude Bulb",styles:Vs(l,"utf8"),mountHtml:Vs(d,"utf8"),watch:r.watch}),f=await ot(r.port),m=await Nt({getHtml:u,basePath:e,port:f,reloadEmitter:n,getServerExports:()=>o,trusted:!0,staticAssets:{mount:`${I.posix.dirname(_r)}/`,dir:a}}),g=`http://localhost:${f}`;await Ot({pid:process.pid,port:f,url:g,file:"agent:claude",cwd:e,startedAt:Date.now(),trust:!0,agent:"claude"}),console.log(`
729
+ </html>`}async function Ks(r){let e=process.cwd(),t=Ot(process.pid),n=r.watch?new za:void 0,s=ne(r.mode),o=await Promise.resolve().then(()=>(qs(),zs));Ae(s,I.join(e,"viewer"));let i=I.dirname(Va(import.meta.url)),a=I.join(i,"agents","claude"),c=I.join(i,"..","agents","claude"),l=I.join(a,"styles.css"),d=I.join(a,"index.html"),u=()=>ws({name:"Claude Bulb",styles:Gs(l,"utf8"),mountHtml:Gs(d,"utf8"),watch:r.watch}),f=await it(r.port),m=await Lt({getHtml:u,basePath:e,port:f,reloadEmitter:n,getServerExports:()=>o,trusted:!0,staticAssets:{mount:`${I.posix.dirname(Cr)}/`,dir:a}}),g=`http://localhost:${f}`;await Dt({pid:process.pid,port:f,url:g,file:"agent:claude",cwd:e,startedAt:Date.now(),trust:!0,agent:"claude"}),console.log(`
730
730
  Claude Bulb`),console.log(` ${g}`),f!==r.port&&console.log(` (port ${r.port} was busy)`),r.watch&&console.log(` Watching for changes...
731
- `);async function v(){await(await import("esbuild")).build({entryPoints:[I.join(c,"client","index.ts")],bundle:!0,platform:"browser",format:"esm",outfile:I.join(a,"client.js")});for(let T of["styles.css","index.html"])Na(I.join(c,T),I.join(a,T))}let $;if(r.watch&&n){let E=La(c),T=!1;$=Ut({dir:E?c:a,onChange:async()=>{if(!T){T=!0;try{E&&await v(),console.log(`Viewer rebuilt. Browser reloading...
731
+ `);async function v(){await(await import("esbuild")).build({entryPoints:[I.join(c,"client","index.ts")],bundle:!0,platform:"browser",format:"esm",outfile:I.join(a,"client.js")});for(let T of["styles.css","index.html"])Ja(I.join(c,T),I.join(a,T))}let $;if(r.watch&&n){let E=Ha(c),T=!1;$=Wt({dir:E?c:a,onChange:async()=>{if(!T){T=!0;try{E&&await v(),console.log(`Viewer rebuilt. Browser reloading...
732
732
  `),n.emit("reload")}catch(p){console.error("Viewer rebuild failed:",p instanceof Error?p.message:p)}finally{T=!1}}}})}r.open&&await Pe(g);let O=async()=>{console.log(`
733
- Shutting down...`),m.close(),$?.(),t(),await Ze(process.pid),process.exit(0)};process.on("SIGINT",O),process.on("SIGTERM",O)}import*as qs from"path";import{EventEmitter as Ja}from"events";async function Gs(r,e,t,n,s){let o=ne(t),i=!1,a=async()=>{let{bulb:c,config:l}=await G(r);i||(_e(o,r,c.server),i=!0),await ur(c.server,s,n,l.dependencies)};if(console.log(`Running ${qs.basename(r)}...`),await a(),e){console.log(`Watching for changes...
734
- `);let c=new Ja;c.on("reload",async()=>{try{console.log("Re-running..."),await a()}catch(l){console.error("Error:",l)}}),Lt({bulbPath:r,emitter:c})}}var Ks="0.11.4";async function Ha(){let r=zr(process.argv.slice(2));if(r.version&&(console.log(`typebulb ${Ks}`),process.exit(0)),r.help&&(qr(),process.exit(0)),r.subcommand==="logs"){await ns(r.file||void 0,{follow:r.follow,lines:r.lines});return}if(r.subcommand==="stop"){r.all?await os():await ss(r.file||void 0);return}if(r.subcommand==="skill"){await Zn(Ks);return}if(r.subcommand==="models"){await Yn(r.mode);return}if(r.subcommand==="agent"){if(!r.agentTarget){await zn();return}An(r.agentTarget)||(console.error(`Unknown agent '${r.agentTarget}'. Known: ${gr().join(", ")}.`),process.exit(1));let l=await wr(process.cwd(),r.agentTarget);if(l){console.log(`Viewer '${r.agentTarget}' is already running for this project:
735
- ${l.url}`),r.open&&await Pe(l.url);return}await zs(r);return}if(r.subcommand==="trust"||r.subcommand==="untrust"){await jn(r.file||void 0,r.subcommand==="trust");return}let e;if(!r.file||r.file==="."){let l=await Rn(process.cwd());l||(console.error("No .bulb.md file found in current directory"),process.exit(1)),e=l}else e=X.resolve(r.file);await Ys.access(e).then(()=>!0,()=>!1)||(gr().includes(r.file)&&(console.error(`To open the ${r.file} agent viewer, run: npx typebulb agent:${r.file}`),process.exit(1)),console.error(`File not found: ${e}`),process.exit(1)),e.endsWith(".bulb.md")||(console.error("File must have .bulb.md extension"),process.exit(1));let n=r.file&&r.file!=="."?r.file:X.relative(process.cwd(),e)||X.basename(e),s=`npx typebulb --trust ${n.includes(" ")?`"${n}"`:n}`;if(r.subcommand==="predict"){await Fn(e,s);return}let o=!r.noTrust&&le(e);o&&!r.trust&&console.log("trust: granted from memory (run `typebulb untrust` to revoke)"),r.trust=r.noTrust?!1:r.trust||o;let i;try{i=await G(e)}catch{}let a;if(r.local){i&&!(r.local.name in(i.config.dependencies??{}))&&(console.error(`--replace: '${r.local.name}' is not a dependency in this bulb's config.json; nothing to replace.`),process.exit(1)),i&&(!i.bulb.code||r.server)&&console.warn("warning: --replace has no effect in server mode (the override is client-only).");try{a=await Hr(r.local)}catch(l){console.error(l instanceof Error?l.message:String(l)),process.exit(1)}console.log(`replace: ${a.name} \u2192 ${X.relative(process.cwd(),a.dir)||"."}`)}if(r.subcommand==="check"){await Mn(e,a);return}let c=X.dirname(e);if(i&&i.bulb.server&&(!i.bulb.code||r.server)){r.trust||(console.error(`This bulb runs server-side Node code (server.ts), which --trust must authorize:
736
- ${s}`),process.exit(1)),await Gs(e,r.watch,r.mode,a,c);return}await hs(e,r,s,a,c)}Ha().catch(r=>{console.error("Error:",r.message),process.exit(1)});
733
+ Shutting down...`),m.close(),$?.(),t(),await et(process.pid),process.exit(0)};process.on("SIGINT",O),process.on("SIGTERM",O)}import*as Ys from"path";import{EventEmitter as qa}from"events";async function Xs(r,e,t,n,s){let o=ne(t),i=!1,a=async()=>{let{bulb:c,config:l}=await G(r);i||(Ae(o,r,c.server),i=!0),await pr(c.server,s,n,l.dependencies)};if(console.log(`Running ${Ys.basename(r)}...`),await a(),e){console.log(`Watching for changes...
734
+ `);let c=new qa;c.on("reload",async()=>{try{console.log("Re-running..."),await a()}catch(l){console.error("Error:",l)}}),Ut({bulbPath:r,emitter:c})}}var Qs="0.11.6";async function Ga(){let r=Gr(process.argv.slice(2));if(r.version&&(console.log(`typebulb ${Qs}`),process.exit(0)),r.help&&(Kr(),process.exit(0)),r.subcommand==="logs"){await is(r.file||void 0,{follow:r.follow,lines:r.lines});return}if(r.subcommand==="stop"){r.all?await cs():await as(r.file||void 0);return}if(r.subcommand==="skill"){await rs(Qs);return}if(r.subcommand==="models"){await es(r.mode);return}if(r.subcommand==="agent"){if(!r.agentTarget){await Yn();return}In(r.agentTarget)||(console.error(`Unknown agent '${r.agentTarget}'. Known: ${yr().join(", ")}.`),process.exit(1));let l=await xr(process.cwd(),r.agentTarget);if(l){console.log(`Viewer '${r.agentTarget}' is already running for this project:
735
+ ${l.url}`),r.open&&await Pe(l.url);return}await Ks(r);return}if(r.subcommand==="trust"||r.subcommand==="untrust"){await Ln(r.file||void 0,r.subcommand==="trust");return}let e;if(!r.file||r.file==="."){let l=await Tn(process.cwd());l||(console.error("No .bulb.md file found in current directory"),process.exit(1)),e=l}else e=X.resolve(r.file);await Zs.access(e).then(()=>!0,()=>!1)||(yr().includes(r.file)&&(console.error(`To open the ${r.file} agent viewer, run: npx typebulb agent:${r.file}`),process.exit(1)),console.error(`File not found: ${e}`),process.exit(1)),e.endsWith(".bulb.md")||(console.error("File must have .bulb.md extension"),process.exit(1));let n=r.file&&r.file!=="."?r.file:X.relative(process.cwd(),e)||X.basename(e),s=`npx typebulb --trust ${n.includes(" ")?`"${n}"`:n}`;if(r.subcommand==="predict"){await Nn(e,s);return}let o=!r.noTrust&&le(e);o&&!r.trust&&console.log("trust: granted from memory (run `typebulb untrust` to revoke)"),r.trust=r.noTrust?!1:r.trust||o;let i;try{i=await G(e)}catch{}let a;if(r.local){i&&!(r.local.name in(i.config.dependencies??{}))&&(console.error(`--replace: '${r.local.name}' is not a dependency in this bulb's config.json; nothing to replace.`),process.exit(1)),i&&(!i.bulb.code||r.server)&&console.warn("warning: --replace has no effect in server mode (the override is client-only).");try{a=await zr(r.local)}catch(l){console.error(l instanceof Error?l.message:String(l)),process.exit(1)}console.log(`replace: ${a.name} \u2192 ${X.relative(process.cwd(),a.dir)||"."}`)}if(r.subcommand==="check"){await Fn(e,a);return}let c=X.dirname(e);if(i&&i.bulb.server&&(!i.bulb.code||r.server)){r.trust||(console.error(`This bulb runs server-side Node code (server.ts), which --trust must authorize:
736
+ ${s}`),process.exit(1)),await Xs(e,r.watch,r.mode,a,c);return}await bs(e,r,s,a,c)}Ga().catch(r=>{console.error("Error:",r.message),process.exit(1)});