typebulb 0.40.0 → 0.41.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -3
- package/dist/agents/claude/client.js +11 -9
- package/dist/agents/pi/client.js +11 -9
- package/dist/agents/pi/matchu-patchu.ts +1 -1
- package/dist/dts/tbTypings.d.ts +4 -3
- package/dist/dts/tbTypings.d.ts.map +1 -1
- package/dist/dts/tbTypings.js +21 -6
- package/dist/dts/tbTypings.js.map +1 -1
- package/dist/index.js +56 -50
- package/dist/render.js +11 -9
- package/dist/servers.js +12 -10
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -343,7 +343,7 @@ const something = require('module-name') // NOT SUPPORTED!
|
|
|
343
343
|
`)[0]}`).join(`
|
|
344
344
|
`)}function jm(r,e){let t=Nn(r,{target:"client",dependencies:e}).filter(n=>n.type==="UNDECLARED_IMPORT");if(t.length)throw new Error(`Lint failed:
|
|
345
345
|
${g0(t)}`)}var Fm=S(()=>{xi()});var bt,In,ul,$n=S(()=>{bt="https://esm.sh",In="https://cdn.jsdelivr.net/npm/",ul="https://data.jsdelivr.com/v1/package/npm/"});function qm(r){let e=(r||"").replace(/^\/+/,"").replace(/\/+$/,"");return e?e.split("/"):[]}var j,vr,Um,Ln=S(()=>{$n();j=class r{constructor(e,t,n){let s=typeof e=="string"?r.parse(e):e;this.name=s.name,this.version=vr(t??s.version),this.subpath=vr(n??s.subpath)}static parse(e){let t=qm(e||"");if(!t.length)return new r({name:""});if(t[0].startsWith("@")){let s=t[0],[i,o]=Um(t[1]??""),a=vr(t.slice(2).join("/"));return new r({name:`${s}/${i}`,version:o,subpath:a})}else{let[s,i]=Um(t[0]),o=vr(t.slice(1).join("/"));return new r({name:s,version:i,subpath:o})}}static fromUrl(e){try{let t=new URL(e),n=new URL(bt).host,s=new URL(In).host;if(t.host===n){let i=qm(t.pathname.replace(/^\/v\d+\//,"/"));if(!i.length)return;let o=i[0].startsWith("@")?`${i[0]}/${i[1]??""}`:i[0];return r.parse(o)}if(t.host===s){let i=t.pathname.split("/npm/")[1];if(!i)return;let o=i.split("/")[0]||"";return r.parse(o)}return}catch{return}}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:vr(e),subpath:this.subpath})}static isBare(e){if(!e||e.startsWith(".")||e.startsWith("/"))return!1;let t=e.toLowerCase();return!t.startsWith("http://")&&!t.startsWith("https://")}},vr=r=>r&&r.length?r:void 0,Um=r=>{let e=r.indexOf("@");return e<0?[r,void 0]:[r.slice(0,e),vr(r.slice(e+1))]}});async function ge(r){try{return await r()}catch{return}}var Ei=S(()=>{});function Ut(r){let e=r||"";return e.startsWith("./")?e.slice(2):e.replace(/^\/+/,"")}function dl(r){return r.startsWith("./")?r:`./${r}`}var Mn,fl=S(()=>{Ln();Ei();$n();Mn=class{constructor(e,t){this.cache=e,this.http=t,this.pinMs=1e4,this.versionsIndexMs=1440*60*1e3,this.metaTtlMs=10080*60*1e3,this.pinCache=new Map}baseDir(e){let t=typeof e=="string"?new j(e):e;return`${In}${t.name}${t.version?`@${t.version}`:""}/`}file(e,t){return new URL(Ut(t),this.baseDir(e)).toString()}packageJson(e){return this.file(e,"package.json")}buildEsmUrl(e,t={}){let{target:n="es2022",bundle:s=!1,external:i}=t,o=new URLSearchParams({target:n});return s&&o.append("bundle",""),i?.length&&o.append("external",i.join(",")),`${bt}/${e}?${o.toString()}`}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),`${bt}/${e}`]);return this.pinCache.set(e,{value:s,ts:t}),s}async tryResolveFromUrls(e){for(let t of e){let n=await ge(()=>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 ge(()=>this.http.getJson(`${ul}${encodeURIComponent(e)}`));if(!n?.versions?.length){await this.cache.recordNegative(e);return}await this.cache.clearNegative(e);let s=n.tags&&Object.keys(n.tags).length?n.tags:void 0;return await this.cache.setIndex(e,n.versions,s),{versions:n.versions,distTags:s}}parseVersionFromUrl(e){let t=j.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:f,peerDependencies:u,peerDependenciesMeta:d}=n;return{name:e,version:t,dependencies:f,peerDependencies:u,peerDependenciesMeta:d}}let s=this.packageJson(new j(`${e}@${t}`)),i=await ge(()=>this.http.getJson(s));if(!i)return;let o=f=>f&&Object.keys(f).length?f:void 0,a=o(i.dependencies),c=o(i.peerDependencies),l=o(i.peerDependenciesMeta);return await this.cache.setMeta(e,t,a,c,l),{name:e,version:t,dependencies:a,peerDependencies:c,peerDependenciesMeta:l}}}});var Jm,Bn,pl,y0,Dn,Ai=S(()=>{Jm=r=>r.startsWith("@types/"),Bn=r=>Object.keys(r?.peerDependencies||{}).filter(e=>!Jm(e)),pl=r=>Object.keys(r?.dependencies||{}).filter(e=>!Jm(e)),y0=r=>Bn(r).filter(e=>!r?.peerDependenciesMeta?.[e]?.optional),Dn=class{constructor(e){this.cdn=e}async resolve(e,t){let n=await this.fetchMeta(e),{allRoots:s,autoAddedPeers:i}=await this.expandWithPeers(n,t),o=this.computeFlags(s);return{allRoots:s,flags:o,autoAddedPeers:i}}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(i=>[i.name,i])),s=[];for(let i of e)for(let o of y0(i.meta))!n.has(o)&&!s.some(a=>a.name===o)&&s.push({name:o,requiredBy:i.name});for(let{name:i,requiredBy:o}of s)try{let a=await t(i),c=await this.cdn.fetchPackageMeta(i,a);n.set(i,{name:i,version:a,meta:c})}catch(a){console.warn(`[typebulb] Failed to resolve peer "${i}" for "${o}":`,a)}return{allRoots:[...n.values()],autoAddedPeers:s.filter(i=>n.has(i.name))}}computeFlags(e){let t=new Set(e.flatMap(i=>Bn(i.meta))),n=new Map;for(let i of e)for(let o of pl(i.meta))n.set(o,(n.get(o)||0)+1);let s=new Set([...n.entries()].filter(([,i])=>i>=2).map(([i])=>i));return new Map(e.map(i=>[i.name,{isPeerRoot:t.has(i.name),hasPeers:Bn(i.meta).length>0,isSharedDep:s.has(i.name)}]))}}});var jn,ml=S(()=>{Ln();Ei();jn=class{constructor(e,t,n){this.cache=e,this.cdn=t,this.semver=n}async learnExactVersion(e){let t=await ge(()=>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=async o=>{if(o&&this.semver.isExactVersion(o))return await this.cache.setPinnedExact(e,t,o),o},i=await ge(()=>this.cdn.fetchVersionsIndex(e));if(i?.versions?.length){let o=this.semver.selectBestVersion(i.versions,{range:t,distTags:i.distTags});if(o){let a=await s(o);if(a)return a}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 ge(()=>this.cdn.fetchVersionsIndex(e));if(a?.versions?.length){let c=await s(this.semver.selectBestVersion(a.versions,{range:t,distTags:a.distTags}));if(c)return c}}}return s(await this.cdn.resolveExactVersion(`${e}@${t}`))}async effectivePackage(e,t){let n=new j(e),s=n.root(),i=t[s],o=i?await ge(()=>this.resolveExactForRoot(s,i)):void 0;return{effectivePackage:o?n.withVersion(o).format():e,root:s,range:i,pinned:o}}}});import{init as b0,parse as w0}from"es-module-lexer";var Sr,hl=S(()=>{Ln();$n();Ai();Sr=class r{constructor(e,t,n){this.version=e,this.cdn=t,this.peer=n}extractImportsSync(e){let t=new Set;for(let n of r.importPatterns){n.lastIndex=0;for(let s of e.matchAll(n))j.isBare(s[1])&&t.add(s[1])}return Array.from(t)}async extractImports(e){let t=new Set,n=s=>{j.isBare(s)&&t.add(s)};try{await b0;let[s]=w0(e);s.forEach(i=>n(e.slice(i.s,i.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(j.rootOf(u))),i=[...new Set(s.map(j.rootOf))],o=await Promise.all(i.map(async u=>({name:u,version:await this.resolveVersion(u,t)}))),{allRoots:a,flags:c,autoAddedPeers:l}=await this.peer.resolve(o,u=>this.resolveVersion(u,t)),f=this.buildEntries([...s,...l.map(u=>u.name)],a,c);return{importMap:{imports:Object.fromEntries(f)},prefetchUrls:f.map(([,u])=>u)}}async resolveVersion(e,t){let n=t[e],s=await this.version.resolveExactForRoot(e,n);if(!s)throw new Error(`Cannot resolve ${n?`${e}@${n}`:e}: no matching version is published (the package or version may not exist, or the registry was unreachable).`);return s}buildEntries(e,t,n){let s=new Map(t.map(p=>[p.name,p])),i=p=>{let h=s.get(j.rootOf(p));return new j(p).withVersion(h.version).format()},o=new Set([...n.entries()].filter(([,p])=>p.isPeerRoot||p.isSharedDep).map(([p])=>p)),a=new Set(e.filter(p=>p!==j.rootOf(p)).map(j.rootOf)),c=[],l=new Set,f=new Set(e.filter(p=>p===j.rootOf(p))),u=new Set;for(let p of e){let h=j.rootOf(p),m=s.get(h),{isPeerRoot:b,hasPeers:A,isSharedDep:w}=n.get(h),P=a.has(h),C=p!==h,_=!(b||w)&&(P||!A),$=this.singletonDepsOf(m,o),E=C&&f.has(h);E&&u.add(h);let M=E?[...$,h]:$.length?$:void 0;c.push([p,this.cdn.buildEsmUrl(i(p),{bundle:_,external:M})]),l.add(p)}let d=new Set([...o,...u]);for(let p of d)s.has(p)&&(l.has(p)||c.push([p,this.cdn.buildEsmUrl(i(p),{})]),c.push([`${p}/`,`${bt}/${i(p)}/`]));return c}singletonDepsOf(e,t){return[...new Set([...Bn(e.meta),...pl(e.meta)])].filter(n=>t.has(n))}};Sr.importPatterns=[/\bimport\s+(?:[^'";]*?from\s*)?['"]([^'"]+)['"]/g,/\bexport\s+[^'";]*?from\s*['"]([^'"]+)['"]/g]});import{gt as Km,satisfies as v0,maxSatisfying as Hm,major as S0,valid as k0}from"semver";var Ti,Jt,gl=S(()=>{Ti=class{cmp(e,t){return e===t?0:Km(e,t)?1:Km(t,e)?-1:0}satisfies(e,t){return!e||!e.trim()?!0:!!v0(t,e,{includePrerelease:!0})}selectBestVersion(e,t){if(!e?.length)return;let n=t?.range?.trim()||"*",s=t?.preferStable??!0,i=t?.distTags?.latest;if(i&&e.includes(i)&&this.satisfies(n,i))return i;if(s){let a=Hm(e,n,{includePrerelease:!1});if(a)return a}return Hm(e,n,{includePrerelease:!0})??void 0}majorOf(e){return S0(e)}isExactVersion(e){return k0(e)!==null}},Jt=new Ti});function x0(r){return Math.min(9e5*Math.pow(2,Math.max(0,r-1)),864e5)}var Kt,Wm=S(()=>{Ei();Kt=class{constructor(e){this.store=e}async isNegative(e){let t=await ge(()=>this.store.get(e));return!!t&&t.until>Date.now()}async recordNegative(e){let n=((await ge(()=>this.store.get(e)))?.attempts||0)+1;await ge(()=>this.store.set(e,{until:Date.now()+x0(n),attempts:n}))}async clearNegative(e){await ge(()=>this.store.delete(e))}}});function Ym(r,e){let t=new Mn(r,e),n=new Dn(t),s=new jn(r,t,Jt);return{packageService:new Sr(s,t,n),versionResolver:s,cdnClient:t,peerResolver:n}}var Qe=S(()=>{fl();Ai();ml();hl();gl();Ln();gl();$n();fl();Ai();ml();hl();Wm()});import*as yl from"fs/promises";import*as Vm from"crypto";function _e(r){return Vm.createHash("sha1").update(r).digest("hex")}async function Ze(r){try{return JSON.parse(await yl.readFile(r,"utf8"))}catch{return}}async function Pi(r){try{return await yl.readFile(r,"utf8")}catch{return}}var kr=S(()=>{});import*as vt from"fs/promises";import*as et from"path";import*as zm from"os";function Z(){return bl||(bl=A0()),bl}function Ri(r,e){return et.join(E0,_e(r),e)}async function A0(){await vt.mkdir(wt,{recursive:!0});let r=et.join(wt,"version.json");if((await Ze(r))?.version===Gm)return;let t=await vt.readdir(wt).catch(()=>[]);await Promise.all(t.map(n=>vt.rm(et.join(wt,n),{recursive:!0,force:!0}))),await vt.writeFile(r,JSON.stringify({version:Gm})+`
|
|
346
|
-
`,"utf8")}var Gm,wt,Fn,qn,Oi,E0,bl,xr=S(()=>{kr();Gm=1,wt=et.join(zm.homedir(),".typebulb","cache"),Fn=et.join(wt,"packages"),qn=et.join(wt,"proxy"),Oi=et.join(wt,"dts"),E0=et.join(wt,"emit")});import*as St from"fs/promises";import*as Xm from"path";async function xe(r,e){await St.mkdir(Xm.dirname(r),{recursive:!0});let t=`${r}.tmp-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;await St.writeFile(t,e,"utf8"),await St.rename(t,r).catch(async n=>{throw await St.rm(t,{force:!0}).catch(()=>{}),n})}var Un=S(()=>{});var Er,wl=S(()=>{Un();kr();Er=class{constructor(e){this.filePath=e}mem;loadPromise;load(){return this.mem?Promise.resolve(this.mem):(this.loadPromise||(this.loadPromise=Ze(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 xe(this.filePath,JSON.stringify(Object.fromEntries(e)))}}});import*as eh from"fs/promises";import*as Ne from"path";function Zm(r,e){return Ne.join(T0,Ci(r),encodeURIComponent(e)+".json")}function Ci(r){return r.replace(/\//g,"__")}var vl,Qm,T0,P0,_i,th=S(()=>{Qe();xr();Un();wl();kr();vl=Ne.join(Fn,"indexes"),Qm=Ne.join(Fn,"pinned"),T0=Ne.join(Fn,"meta"),P0=Ne.join(Fn,"negative.json"),_i=class{pinnedMem=new Map;indexMem=new Map;metaMem=new Map;negativeCache=new Kt(new Er(P0));async getPinnedExact(e,t){let n=`${e}@${t}`;if(this.pinnedMem.has(n))return this.pinnedMem.get(n);await Z();let s=await Pi(Ne.join(Qm,_e(n)+".txt"));return this.pinnedMem.set(n,s),s}async setPinnedExact(e,t,n){let s=`${e}@${t}`;this.pinnedMem.set(s,n),await Z(),await xe(Ne.join(Qm,_e(s)+".txt"),n)}async getIndex(e){if(this.indexMem.has(e))return this.indexMem.get(e);await Z();let t=await Ze(Ne.join(vl,Ci(e)+".json"));return this.indexMem.set(e,t),t}async setIndex(e,t,n){let s={versions:t,distTags:n,updatedAt:Date.now()};this.indexMem.set(e,s),await Z(),await xe(Ne.join(vl,Ci(e)+".json"),JSON.stringify(s))}async invalidateVersionsCache(e){this.indexMem.delete(e),await eh.rm(Ne.join(vl,Ci(e)+".json"),{force:!0})}async isNegative(e){return await Z(),this.negativeCache.isNegative(e)}async recordNegative(e){await Z(),await this.negativeCache.recordNegative(e)}async clearNegative(e){await this.negativeCache.clearNegative(e)}async getMeta(e,t){let n=`${e}@${t}`;if(this.metaMem.has(n))return this.metaMem.get(n);await Z();let s=await Ze(Zm(e,t));return this.metaMem.set(n,s),s}async setMeta(e,t,n,s,i){let o={dependencies:n,peerDependencies:s,peerDependenciesMeta:i,updatedAt:Date.now()};this.metaMem.set(`${e}@${t}`,o),await Z(),await xe(Zm(e,t),JSON.stringify(o))}}});var rh,nh=S(()=>{rh={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 O0,Ni,sh,ih,
|
|
346
|
+
`,"utf8")}var Gm,wt,Fn,qn,Oi,E0,bl,xr=S(()=>{kr();Gm=1,wt=et.join(zm.homedir(),".typebulb","cache"),Fn=et.join(wt,"packages"),qn=et.join(wt,"proxy"),Oi=et.join(wt,"dts"),E0=et.join(wt,"emit")});import*as St from"fs/promises";import*as Xm from"path";async function xe(r,e){await St.mkdir(Xm.dirname(r),{recursive:!0});let t=`${r}.tmp-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;await St.writeFile(t,e,"utf8"),await St.rename(t,r).catch(async n=>{throw await St.rm(t,{force:!0}).catch(()=>{}),n})}var Un=S(()=>{});var Er,wl=S(()=>{Un();kr();Er=class{constructor(e){this.filePath=e}mem;loadPromise;load(){return this.mem?Promise.resolve(this.mem):(this.loadPromise||(this.loadPromise=Ze(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 xe(this.filePath,JSON.stringify(Object.fromEntries(e)))}}});import*as eh from"fs/promises";import*as Ne from"path";function Zm(r,e){return Ne.join(T0,Ci(r),encodeURIComponent(e)+".json")}function Ci(r){return r.replace(/\//g,"__")}var vl,Qm,T0,P0,_i,th=S(()=>{Qe();xr();Un();wl();kr();vl=Ne.join(Fn,"indexes"),Qm=Ne.join(Fn,"pinned"),T0=Ne.join(Fn,"meta"),P0=Ne.join(Fn,"negative.json"),_i=class{pinnedMem=new Map;indexMem=new Map;metaMem=new Map;negativeCache=new Kt(new Er(P0));async getPinnedExact(e,t){let n=`${e}@${t}`;if(this.pinnedMem.has(n))return this.pinnedMem.get(n);await Z();let s=await Pi(Ne.join(Qm,_e(n)+".txt"));return this.pinnedMem.set(n,s),s}async setPinnedExact(e,t,n){let s=`${e}@${t}`;this.pinnedMem.set(s,n),await Z(),await xe(Ne.join(Qm,_e(s)+".txt"),n)}async getIndex(e){if(this.indexMem.has(e))return this.indexMem.get(e);await Z();let t=await Ze(Ne.join(vl,Ci(e)+".json"));return this.indexMem.set(e,t),t}async setIndex(e,t,n){let s={versions:t,distTags:n,updatedAt:Date.now()};this.indexMem.set(e,s),await Z(),await xe(Ne.join(vl,Ci(e)+".json"),JSON.stringify(s))}async invalidateVersionsCache(e){this.indexMem.delete(e),await eh.rm(Ne.join(vl,Ci(e)+".json"),{force:!0})}async isNegative(e){return await Z(),this.negativeCache.isNegative(e)}async recordNegative(e){await Z(),await this.negativeCache.recordNegative(e)}async clearNegative(e){await this.negativeCache.clearNegative(e)}async getMeta(e,t){let n=`${e}@${t}`;if(this.metaMem.has(n))return this.metaMem.get(n);await Z();let s=await Ze(Zm(e,t));return this.metaMem.set(n,s),s}async setMeta(e,t,n,s,i){let o={dependencies:n,peerDependencies:s,peerDependenciesMeta:i,updatedAt:Date.now()};this.metaMem.set(`${e}@${t}`,o),await Z(),await xe(Zm(e,t),JSON.stringify(o))}}});var rh,nh=S(()=>{rh={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 O0,Ni,sh,ih,GN,Sl=S(()=>{Qe();th();nh();O0=new _i,{packageService:Ni,versionResolver:sh,cdnClient:ih,peerResolver:GN}=Ym(O0,rh)});function Ii(r){return r.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function Li(r,e){return` <script>
|
|
347
347
|
(function() {
|
|
348
348
|
try {
|
|
349
349
|
var KEY = ${Ht(JSON.stringify("tb-theme:"+r))};
|
|
@@ -510,12 +510,12 @@ ${g0(t)}`)}var Fm=S(()=>{xi()});var bt,In,ul,$n=S(()=>{bt="https://esm.sh",In="h
|
|
|
510
510
|
}
|
|
511
511
|
};
|
|
512
512
|
|
|
513
|
-
// Diagnostic logging (tb.
|
|
513
|
+
// Diagnostic logging (tb.log). Routes to the UNGATED /__log endpoint, which only ever
|
|
514
514
|
// runs the server's built-in console.log \u2014 never a user server.ts export \u2014 so it crosses no
|
|
515
515
|
// capability boundary and works even on a Restricted (untrusted) bulb (the FAQ's recommended
|
|
516
516
|
// debugging path). Embedded bulbs have no host, and any transport failure degrades to the page's
|
|
517
517
|
// own console: a diagnostic log must never throw or block.
|
|
518
|
-
const
|
|
518
|
+
const tbLog = async (...args) => {
|
|
519
519
|
if (isEmbedded) { console.log(...args); return; }
|
|
520
520
|
try {
|
|
521
521
|
const resp = await fetch('/__log', {
|
|
@@ -743,17 +743,19 @@ ${g0(t)}`)}var Fm=S(()=>{xi()});var bt,In,ul,$n=S(()=>{bt="https://esm.sh",In="h
|
|
|
743
743
|
return location.origin && location.origin !== 'null' ? location.origin + rel : rel;
|
|
744
744
|
},
|
|
745
745
|
|
|
746
|
+
// The bulb's log channel: prints on the CLI's stdout (\`typebulb logs\` reads it back). Ungated \u2014
|
|
747
|
+
// no server.ts, no trust \u2014 see tbLog above.
|
|
748
|
+
log: (...args) => { void tbLog(...args); },
|
|
749
|
+
|
|
746
750
|
// Server API - call functions from **server.ts**. Returns the hybrid call object: await it for
|
|
747
751
|
// a normal export's result, or for-await it for an async-generator export's stream.
|
|
748
752
|
api: (name, ...args) => serverCall(name, args),
|
|
749
753
|
|
|
750
|
-
// Server proxy - tb.server.fn(...) delegates to serverCall
|
|
751
|
-
//
|
|
752
|
-
//
|
|
754
|
+
// Server proxy - tb.server.fn(...) delegates to serverCall: purely the bulb's own server.ts
|
|
755
|
+
// exports, every one a gated /__api call. (The ungated diagnostic lives at tb.log, so no
|
|
756
|
+
// built-in shadows a user export.)
|
|
753
757
|
server: new Proxy({}, {
|
|
754
|
-
get: (_, name) => name
|
|
755
|
-
? (...args) => serverLog(...args)
|
|
756
|
-
: (...args) => serverCall(name, args)
|
|
758
|
+
get: (_, name) => (...args) => serverCall(name, args)
|
|
757
759
|
}),
|
|
758
760
|
|
|
759
761
|
// Filesystem - local CLI extension
|
|
@@ -768,7 +770,7 @@ ${g0(t)}`)}var Fm=S(()=>{xi()});var bt,In,ul,$n=S(()=>{bt="https://esm.sh",In="h
|
|
|
768
770
|
},
|
|
769
771
|
|
|
770
772
|
// Receive a value pushed from the terminal via \`typebulb send\` (data-in, the dual of the
|
|
771
|
-
// ungated tb.
|
|
773
|
+
// ungated tb.log). Returns an unsubscribe fn. Inert when embedded \u2014 no server, so no
|
|
772
774
|
// sender; the handler is registered but never fires (cf. tb.models returning []). A handler's
|
|
773
775
|
// non-undefined return (awaited) becomes the reply \`send --wait\` prints (TB-Interrogation.md).
|
|
774
776
|
onMessage: (handler) => {
|
|
@@ -1051,7 +1053,7 @@ ${n}
|
|
|
1051
1053
|
Output only valid JSON. No explanation, no markdown fences, just the JSON object. Every number must be a JSON literal \u2014 never an expression like 2 * pi; write the computed decimal instead.`),t.join(`
|
|
1052
1054
|
|
|
1053
1055
|
`)}function Jn(r){try{return JSON.parse(r)}catch{return null}}function z0(r,e){let t="",n=0,s=!1,i=!1;for(let o=0;o<r.length;o++){let a=r[o];if(i){i=!1;continue}if(a==="\\"){i=!0;continue}a==='"'&&(s?(t+=r.slice(n,o+1),n=o+1):(t+=e(r.slice(n,o))+'"',n=o+1),s=!s)}return t+=s?r.slice(n):e(r.slice(n)),t}function X0(r){let e=z0(r,t=>t.replace(/\bpi\b/g,"3.141592653589793").replace(/\be\b/g,"2.718281828459045").replace(/-?\d[\d.\s+\-*/()]*\d|\(-?\d[\d.\s+\-*/()]*\d\)/g,n=>{if(!/[+\-*/]/.test(n.replace(/^-/,""))||n.length>64||!/^[\d\s.+\-*/()]+$/.test(n))return n;try{let s=Function(`"use strict"; return (${n})`)();return typeof s=="number"&&Number.isFinite(s)?String(s):n}catch{return n}}));return e!==r?e:null}function Q0(r,e){let t=0,n=!1,s=!1;for(let i=e;i<r.length;i++){let o=r[i];if(s){s=!1;continue}if(o==="\\"){s=!0;continue}if(o==='"'){n=!n;continue}if(!n){if(o==="{"||o==="[")t++;else if((o==="}"||o==="]")&&(t--,t===0))return i}}return-1}function Z0(r){let e=null,t=0;for(;t<r.length;){let n=r[t];if(n==="{"||n==="["){let s=Q0(r,t);if(s!==-1){let i=r.slice(t,s+1),o=Jn(i);o!==null&&(e={parsed:o,json:i}),t=s+1;continue}}t++}return e}function Il(r){let e=[],t=r.trim();t.startsWith("```")&&(t=t.replace(/^```(?:json)?\s*\n?/,"").replace(/\n?```\s*$/,""),e.push("markdown fences"));let n=Jn(t);if(n!==null)return{parsed:n,json:t,fixesApplied:e};let s=t.match(/```(?:json)?\s*\n([\s\S]*?)\n?```\s*$/);if(s&&(t=s[1].trim(),e.push("preamble before fenced JSON"),n=Jn(t),n!==null))return{parsed:n,json:t,fixesApplied:e};if(!t.startsWith("{")&&!t.startsWith("[")){let o=t.indexOf("{"),a=t.indexOf("["),c=o>=0&&a>=0?Math.min(o,a):o>=0?o:a;if(c>0&&(t=t.slice(c),e.push("preamble text"),n=Jn(t),n!==null))return{parsed:n,json:t,fixesApplied:e}}for(let[o,a]of G0){let c=a(t);if(c!==null){let l=Jn(c);if(l!==null)return{parsed:l,json:c,fixesApplied:[...e,o]}}}let i=Z0(r);return i!==null?{...i,fixesApplied:[...e,"extracted last JSON value"]}:{parsed:null,json:t,fixesApplied:e}}function $l(r){try{let e={i:r.insight,d:r.data},t=JSON.stringify(e),n=Y0(H0(t),{level:9}),s=tE(n),i=`${gh}:${s}`;return i.length>eE?"":"#"+_l+i}catch{return""}}function Ll(r){try{let e=r.startsWith("#")?r.slice(1):r;if(!e.startsWith(_l))return null;let t=e.slice(_l.length),n=t.indexOf(":");if(n===-1||t.slice(0,n)!==gh)return null;let s=rE(t.slice(n+1)),i=JSON.parse(W0(V0(s)));return!i||typeof i.i>"u"||!Array.isArray(i.d)?null:{insight:i.i,insightJson:JSON.stringify(i.i,null,2),data:i.d}}catch{return null}}function tE(r){let e="";for(let t=0;t<r.length;t+=32768)e+=String.fromCharCode(...r.subarray(t,t+32768));return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function rE(r){let e=r.replace(/-/g,"+").replace(/_/g,"/");for(;e.length%4;)e+="=";let t=atob(e),n=new Uint8Array(t.length);for(let s=0;s<t.length;s++)n[s]=t.charCodeAt(s);return n}var G0,_l,gh,eE,yh=S(()=>{G0=[["orphan quote",r=>{let e=r.replace(/^[ \t]*"[ \t]*\r?\n/gm,"");return e!==r?e:null}],["trailing }",r=>r.endsWith("}}")?r.slice(0,-1):null],["trailing ]",r=>r.endsWith("]]")?r.slice(0,-1):null],["trailing },",r=>r.endsWith("},")?r.slice(0,-1):null],["trailing ],",r=>r.endsWith("],")?r.slice(0,-1):null],["trailing comma in object",r=>r.match(/,\s*\}$/)?r.replace(/,\s*\}$/,"}"):null],["trailing comma in array",r=>r.match(/,\s*\]$/)?r.replace(/,\s*\]$/,"]"):null],["arithmetic constants",X0]];_l="tb=",gh="1",eE=6e4});var Or=S(()=>{dh();Ar();Rl();hh();yh();Ji();Al();Tl();xl();El();Pl()});function Cr(r){return(r.includes("://")?r:`http://${r}`).replace(/\/+$/,"")}function Ml(){return Hn}async function tt(){let[r,e]=await Promise.all([wh(),cE()]);return aE([...lE(e),...r],process.env.TB_AI_PROVIDER,process.env.TB_AI_MODEL)}function aE(r,e,t){return!e||!t?r:r.map(n=>n.provider===e&&n.name===t?{...n,default:!0}:n)}async function bh(){let r;try{r=await fetch(nE,{signal:AbortSignal.timeout(iE)})}catch(e){return Hn=`catalog fetch failed: ${e?.message??e}`,null}if(!r.ok)return Hn=`catalog fetch failed: HTTP ${r.status}`,null;try{return await r.json()}catch(e){return Hn=`catalog returned an unreadable body: ${e?.message??e}`,null}}async function cE(){if(Kn&&Date.now()-Kn.fetchedAt<=sE)return Kn.models;let r=await bh()??await bh();return r?(Kn={models:r,fetchedAt:Date.now()},Hn=null,r):Kn?.models??[]}async function wh(){if(Vi&&Date.now()-Vi.fetchedAt<=oE)return Vi.models;let r=Cr(process.env.OLLAMA_HOST??"http://localhost:11434"),e=[];try{let t=await fetch(new URL("/api/tags",r).toString());t.ok&&(e=((await t.json()).models??[]).map(s=>s.name).filter(s=>!!s).map(s=>({provider:"ollama",name:s,friendlyName:s,providerName:"Ollama"})))}catch{}return Vi={models:e,fetchedAt:Date.now()},e}function lE(r){let e=new Set(Object.entries(Rr).filter(([,t])=>!!process.env[t]).map(([t])=>t));return r.filter(t=>e.has(t.provider))}function Bl(){return Object.values(Rr).some(r=>!!process.env[r])}async function Gi(){return Bl()||process.env.TB_AI_BASE_URL?!0:(await wh()).length>0}function vh(r,e,t){let n=Math.max(...r.map(o=>o.name.length)),s=Math.max(...r.map(o=>o.friendlyName.length)),i=["Models available to tb.ai (filtered by your .env keys):",""];for(let o of r)i.push(` ${o.name.padEnd(n)} ${o.friendlyName.padEnd(s)} (${o.provider})`);return i.push("","Pass an id as the `model` in tb.ai({ provider, model })."),e&&t&&i.push(`Default (from .env): ${e} / ${t}`),i.join(`
|
|
1054
|
-
`)}var Rr,nE,sE,iE,oE,Kn,Vi,Hn,Gt=S(()=>{Rr={anthropic:"ANTHROPIC_API_KEY",openai:"OPENAI_API_KEY",gemini:"GOOGLE_API_KEY",openrouter:"OPENROUTER_API_KEY"};nE="https://api.typebulb.com/api/models",sE=1440*60*1e3,iE=5e3,oE=60*1e3,Kn=null,Vi=null,Hn=null});function rt(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=Wt(t)}catch{return`Unknown provider '${t}'.`}if(t==="ollama")return{apiKey:"",baseUrl:`${Cr(process.env.OLLAMA_HOST??s.defaultBaseUrl)}/v1`,protocol:t,model:n,isFreeModel:!1};if(t==="openai-compat"){let a=process.env.TB_AI_BASE_URL;return a?{apiKey:process.env.TB_AI_API_KEY??"",baseUrl:a,protocol:t,model:n,isFreeModel:!1}:"No base URL for openai-compat. Set TB_AI_BASE_URL (the OpenAI-style base ending in /v1, e.g. http://localhost:1234/v1) in your .env file."}let i=Rr[t];if(!i)return`Unknown provider '${t}'.`;let o=process.env[i];return o?{apiKey:o,baseUrl:s.defaultBaseUrl,protocol:t,model:n,isFreeModel:!1}:`No API key for '${t}'. Set ${i} in your .env file.`}function kt(r,e){let t=[...e.system?[{role:"system",content:e.system}]:[],...e.messages.map(s=>({role:s.role,content:s.content}))],n=e.effort;return Ol(r,{messages:t,stream:!0,effort:n!=null&&n>=0&&n<=3?n:void 0,webSearch:e.webSearch??!0,signal:e.signal})}var zi=S(()=>{Or();Gt()});import*as _r from"fs/promises";import*as nt from"path";function Xi(r,e,t=e){let n=nt.resolve(e,r),s=nt.normalize(t),i=nt.normalize(n);if(i!==s&&!i.startsWith(s+nt.sep))throw new Error("Path traversal detected - access denied");return n}async function Wn(r,e,t){return _r.readFile(Xi(r,e,t))}async function Qi(r,e,t,n){let s=Xi(r,t,n);await _r.mkdir(nt.dirname(s),{recursive:!0}),await _r.writeFile(s,typeof e=="string"?e:Buffer.from(e))}var Dl=S(()=>{});async function Sh(r){let e=rt(r.provider,r.model);if(typeof e=="string")throw new Error(e);let t=await kt(e,r);if(!t.ok){let n=await Pr(t,e.protocol);throw new Error(n.message)}return{response:t,protocol:e.protocol}}async function uE(r){let{response:e,protocol:t}=await Sh(r);return{text:await Yt(e,t)}}async function*dE(r){let{response:e,protocol:t}=await Sh(r);yield*Vt(e,t)}function kh(r,e=process.cwd()){let t=Object.assign(uE,{stream:dE}),n={read:async s=>{let i=await Wn(s,r,e);try{return new TextDecoder("utf-8",{fatal:!0}).decode(i)}catch{throw new Error(`File is not valid UTF-8 text: ${s} \u2014 use tb.fs.readBytes() for binary files.`)}},readBytes:async s=>new Uint8Array(await Wn(s,r,e)),write:async(s,i)=>(await Qi(s,i,r,e),!0)};globalThis.tb=Object.freeze({ai:t,fs:n,dir:r,models:()=>tt(),hasOwnKeys:Gi,mode:"local"})}var xh=S(()=>{Or();zi();Gt();Dl()});import*as $e from"fs/promises";import*as se from"path";import{pathToFileURL as fE}from"url";async function Eh(r){let t=(await $e.readdir(r)).find(n=>n.endsWith(".bulb.md"));return t?se.join(r,t):null}function xt(r,e){let t=se.resolve(r),n=se.join(se.dirname(t),se.basename(t).replace(/\.bulb\.md$/,""));return e?se.join(n,"batches",e):n}async function Nr(r,e){let t=xt(r,e);await $e.mkdir(t,{recursive:!0});let n=new Date;await $e.utimes(t,n,n).catch(()=>{})}function Zi(r){let[e,t,n,s]=r.split(se.sep).slice(-4);if(!(e!=="typebulbs"||t!=="u"||!n||!s?.endsWith(".bulb.md")))return{userSlug:n,slug:s.slice(0,-8)}}async function Le(r){let e=await $e.readFile(r,"utf-8"),t=le(e);if(!t)throw new Error("Invalid .bulb.md file format");let n=wr(t);return{bulb:n,config:zr(n.config),warnings:wd(e),starts:t.starts}}function jl(r){let e=se.basename(r).replace(/\.bulb\.md$/i,"");return se.join(se.dirname(r),".typebulb",`${e}.server.mjs`)}async function Yn(r,e,t,n,s){let i=cl(r,{serverOnly:!0});if(i.error)throw new Error(`Server compilation error: ${i.error}`);let o=i.code;t&&(o=await md(o,t));let a=se.join(se.dirname(e),".typebulb");await $e.mkdir(a,{recursive:!0});let c=qi(o);c.length>0&&await Fi(c,a,n);let l=jl(e);return await $e.writeFile(l,o,"utf-8"),kh(xt(e,s)),await import(`${fE(l).href}?t=${Date.now()}`)}async function Fl(r,e,t,n,s){let{bulb:i,config:o,starts:a}=await Le(r),c=Si(i.data);jm(i.code,o.dependencies??{});let l=cl(i.code,{jsxImportSource:o.ts?.jsxImportSource});l.error&&console.error("Compilation error:",l.error);let{importMap:f}=await Ni.buildImportMap(l.code,o.dependencies??{},n?new Set([n.name]):void 0);n&&(f.imports[n.name]=n.entryUrl);let u=ch({name:i.name,code:l.code,css:i.css,html:i.html,data:c,insight:i.insight,importMap:f,dir:xt(r,s),watch:e,source:{file:se.basename(r),codeLine:a.get("code.tsx")??1}}),d=null;return i.server&&t&&(d=await Yn(i.server,r,n,o.dependencies,s)),{html:u,bulb:i,serverExports:d}}var Et,qe=S(()=>{_n();$m();Fm();Sl();lh();kl();ws();xh();Et=(r,e)=>se.join(xt(r,e),"assets")});import{realpathSync as pE}from"fs";import{join as ql,resolve as mE}from"path";import{homedir as hE}from"os";function Ir(){let r=process.env.TYPEBULB_SERVERS_DIR;return r?ql(r,".."):ql(hE(),".typebulb")}function st(){return process.env.TYPEBULB_SERVERS_DIR||ql(Ir(),"servers")}function X(r){let e=mE(r),t=e;try{t=pE.native(e)}catch{}return(process.platform==="win32"?t.toLowerCase():t).replace(/\\/g,"/")}function Ah(r,e){let t=X(r),n=X(e);return t.startsWith(n.endsWith("/")?n:n+"/")?!t.includes("/node_modules/"):!1}var Vn=S(()=>{});import{readFileSync as gE,writeFileSync as yE,mkdirSync as bE}from"fs";import{join as wE}from"path";function Th(){return wE(Ir(),"trust.json")}function Ul(){try{let r=JSON.parse(gE(Th(),"utf8"));return new Set(Array.isArray(r)?r:[])}catch{return new Set}}function vE(r){bE(Ir(),{recursive:!0}),yE(Th(),JSON.stringify([...r]))}function zt(r){return Ul().has(X(r))}function $r(r,e){let t=Ul(),n=X(r);(e?t.has(n):!t.has(n))||(e?t.add(n):t.delete(n),vE(t))}function Jl(){return[...Ul()]}var Gn=S(()=>{Vn()});function Ue(r){return r.length>5e4?r.slice(0,5e4)+`
|
|
1056
|
+
`)}var Rr,nE,sE,iE,oE,Kn,Vi,Hn,Gt=S(()=>{Rr={anthropic:"ANTHROPIC_API_KEY",openai:"OPENAI_API_KEY",gemini:"GOOGLE_API_KEY",openrouter:"OPENROUTER_API_KEY"};nE="https://api.typebulb.com/api/models",sE=1440*60*1e3,iE=5e3,oE=60*1e3,Kn=null,Vi=null,Hn=null});function rt(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=Wt(t)}catch{return`Unknown provider '${t}'.`}if(t==="ollama")return{apiKey:"",baseUrl:`${Cr(process.env.OLLAMA_HOST??s.defaultBaseUrl)}/v1`,protocol:t,model:n,isFreeModel:!1};if(t==="openai-compat"){let a=process.env.TB_AI_BASE_URL;return a?{apiKey:process.env.TB_AI_API_KEY??"",baseUrl:a,protocol:t,model:n,isFreeModel:!1}:"No base URL for openai-compat. Set TB_AI_BASE_URL (the OpenAI-style base ending in /v1, e.g. http://localhost:1234/v1) in your .env file."}let i=Rr[t];if(!i)return`Unknown provider '${t}'.`;let o=process.env[i];return o?{apiKey:o,baseUrl:s.defaultBaseUrl,protocol:t,model:n,isFreeModel:!1}:`No API key for '${t}'. Set ${i} in your .env file.`}function kt(r,e){let t=[...e.system?[{role:"system",content:e.system}]:[],...e.messages.map(s=>({role:s.role,content:s.content}))],n=e.effort;return Ol(r,{messages:t,stream:!0,effort:n!=null&&n>=0&&n<=3?n:void 0,webSearch:e.webSearch??!0,signal:e.signal})}var zi=S(()=>{Or();Gt()});import*as _r from"fs/promises";import*as nt from"path";function Xi(r,e,t=e){let n=nt.resolve(e,r),s=nt.normalize(t),i=nt.normalize(n);if(i!==s&&!i.startsWith(s+nt.sep))throw new Error("Path traversal detected - access denied");return n}async function Wn(r,e,t){return _r.readFile(Xi(r,e,t))}async function Qi(r,e,t,n){let s=Xi(r,t,n);await _r.mkdir(nt.dirname(s),{recursive:!0}),await _r.writeFile(s,typeof e=="string"?e:Buffer.from(e))}var Dl=S(()=>{});async function Sh(r){let e=rt(r.provider,r.model);if(typeof e=="string")throw new Error(e);let t=await kt(e,r);if(!t.ok){let n=await Pr(t,e.protocol);throw new Error(n.message)}return{response:t,protocol:e.protocol}}async function uE(r){let{response:e,protocol:t}=await Sh(r);return{text:await Yt(e,t)}}async function*dE(r){let{response:e,protocol:t}=await Sh(r);yield*Vt(e,t)}function kh(r,e=process.cwd()){let t=Object.assign(uE,{stream:dE}),n={read:async s=>{let i=await Wn(s,r,e);try{return new TextDecoder("utf-8",{fatal:!0}).decode(i)}catch{throw new Error(`File is not valid UTF-8 text: ${s} \u2014 use tb.fs.readBytes() for binary files.`)}},readBytes:async s=>new Uint8Array(await Wn(s,r,e)),write:async(s,i)=>(await Qi(s,i,r,e),!0)};globalThis.tb=Object.freeze({log:(...s)=>{console.log(...s)},ai:t,fs:n,dir:r,models:()=>tt(),hasOwnKeys:Gi,mode:"local"})}var xh=S(()=>{Or();zi();Gt();Dl()});import*as $e from"fs/promises";import*as se from"path";import{pathToFileURL as fE}from"url";async function Eh(r){let t=(await $e.readdir(r)).find(n=>n.endsWith(".bulb.md"));return t?se.join(r,t):null}function xt(r,e){let t=se.resolve(r),n=se.join(se.dirname(t),se.basename(t).replace(/\.bulb\.md$/,""));return e?se.join(n,"batches",e):n}async function Nr(r,e){let t=xt(r,e);await $e.mkdir(t,{recursive:!0});let n=new Date;await $e.utimes(t,n,n).catch(()=>{})}function Zi(r){let[e,t,n,s]=r.split(se.sep).slice(-4);if(!(e!=="typebulbs"||t!=="u"||!n||!s?.endsWith(".bulb.md")))return{userSlug:n,slug:s.slice(0,-8)}}async function Le(r){let e=await $e.readFile(r,"utf-8"),t=le(e);if(!t)throw new Error("Invalid .bulb.md file format");let n=wr(t);return{bulb:n,config:zr(n.config),warnings:wd(e),starts:t.starts}}function jl(r){let e=se.basename(r).replace(/\.bulb\.md$/i,"");return se.join(se.dirname(r),".typebulb",`${e}.server.mjs`)}async function Yn(r,e,t,n,s){let i=cl(r,{serverOnly:!0});if(i.error)throw new Error(`Server compilation error: ${i.error}`);let o=i.code;t&&(o=await md(o,t));let a=se.join(se.dirname(e),".typebulb");await $e.mkdir(a,{recursive:!0});let c=qi(o);c.length>0&&await Fi(c,a,n);let l=jl(e);return await $e.writeFile(l,o,"utf-8"),kh(xt(e,s)),await import(`${fE(l).href}?t=${Date.now()}`)}async function Fl(r,e,t,n,s){let{bulb:i,config:o,starts:a}=await Le(r),c=Si(i.data);jm(i.code,o.dependencies??{});let l=cl(i.code,{jsxImportSource:o.ts?.jsxImportSource});l.error&&console.error("Compilation error:",l.error);let{importMap:f}=await Ni.buildImportMap(l.code,o.dependencies??{},n?new Set([n.name]):void 0);n&&(f.imports[n.name]=n.entryUrl);let u=ch({name:i.name,code:l.code,css:i.css,html:i.html,data:c,insight:i.insight,importMap:f,dir:xt(r,s),watch:e,source:{file:se.basename(r),codeLine:a.get("code.tsx")??1}}),d=null;return i.server&&t&&(d=await Yn(i.server,r,n,o.dependencies,s)),{html:u,bulb:i,serverExports:d}}var Et,qe=S(()=>{_n();$m();Fm();Sl();lh();kl();ws();xh();Et=(r,e)=>se.join(xt(r,e),"assets")});import{realpathSync as pE}from"fs";import{join as ql,resolve as mE}from"path";import{homedir as hE}from"os";function Ir(){let r=process.env.TYPEBULB_SERVERS_DIR;return r?ql(r,".."):ql(hE(),".typebulb")}function st(){return process.env.TYPEBULB_SERVERS_DIR||ql(Ir(),"servers")}function X(r){let e=mE(r),t=e;try{t=pE.native(e)}catch{}return(process.platform==="win32"?t.toLowerCase():t).replace(/\\/g,"/")}function Ah(r,e){let t=X(r),n=X(e);return t.startsWith(n.endsWith("/")?n:n+"/")?!t.includes("/node_modules/"):!1}var Vn=S(()=>{});import{readFileSync as gE,writeFileSync as yE,mkdirSync as bE}from"fs";import{join as wE}from"path";function Th(){return wE(Ir(),"trust.json")}function Ul(){try{let r=JSON.parse(gE(Th(),"utf8"));return new Set(Array.isArray(r)?r:[])}catch{return new Set}}function vE(r){bE(Ir(),{recursive:!0}),yE(Th(),JSON.stringify([...r]))}function zt(r){return Ul().has(X(r))}function $r(r,e){let t=Ul(),n=X(r);(e?t.has(n):!t.has(n))||(e?t.add(n):t.delete(n),vE(t))}function Jl(){return[...Ul()]}var Gn=S(()=>{Vn()});function Ue(r){return r.length>5e4?r.slice(0,5e4)+`
|
|
1055
1057
|
\u2026[${r.length-5e4} more characters truncated]`:r}function it(r){let e=r.replace(SE,"").split(`
|
|
1056
1058
|
`).map(i=>i.trim()).filter(Boolean),t=e[0];if(!t)return"";let n=t.length>300?t.slice(0,300).trimEnd()+"\u2026":t,s=e.length-1;return s>0?`${n} (+${s} line${s===1?"":"s"})`:n}var SE,eo,to=S(()=>{SE=/\u001b\[[0-9;]*m/g;eo=(r,e)=>``});import{existsSync as kE,readdirSync as xE,statSync as EE}from"fs";import{join as AE}from"path";function ro(r){if(!kE(r))return[];let e;try{e=xE(r)}catch{return[]}let t=[];for(let n of e){if(!n.endsWith(".jsonl"))continue;let s=AE(r,n);try{let i=EE(s);i.isFile()&&t.push({sessionId:n.slice(0,-6),file:s,mtime:i.mtimeMs})}catch{}}return t}var Kl=S(()=>{});var Lr,Hl=S(()=>{Lr=class{ensureHarnessSupport(){}}});import{openSync as TE,readSync as PE,closeSync as OE,statSync as RE,readdirSync as CE,readFileSync as _E,existsSync as NE}from"fs";import{join as Xn}from"path";import{homedir as Vl}from"os";function IE(r){return r.replace(/[^a-zA-Z0-9]/g,"-")}function no(r){let e=r?.type==="image"?r.source:void 0;return e?.type==="base64"&&e.data?eo(e.data,e.media_type):""}function Wl(r){return typeof r=="string"?Ue(r):Array.isArray(r)?r.map(e=>{if(typeof e=="string")return Ue(e);let t=e;return typeof t?.text=="string"?Ue(t.text):t?.content!=null?Wl(t.content):no(t)}).join(`
|
|
1057
1059
|
`):r==null?"":Ue(JSON.stringify(r))}function LE(r){let e=r.trim();return!!e&&Ch.some(t=>t.test(e))}function ME(r){let e=r.trim();return e?Ch.some(t=>{let n=t.exec(e);return!!n&&n.index===0}):!0}function DE(r){return r.replace(BE,"")}function jE(r){let e=/^<command-name>([\s\S]*?)<\/command-name>/.exec(r)?.[1]?.trim();if(!e)return;let t=/<command-args>([\s\S]*?)<\/command-args>/.exec(r)?.[1]?.trim();return t?`${e} ${t}`:e}function At(r){let e=DE(r).trim();return e?jE(e)??(LE(e)?"":e):""}function Yl(r){return r?.type==="text"&&typeof r.text=="string"?At(r.text):""}function Gl(r,e){if(typeof r=="string")return it(r);if(!r||typeof r!="object")return it(e);let t=r;if(t.type==="text"&&typeof t.file?.numLines=="number")return Me(t.file.numLines,"line");if(t.type==="image"){let n=Oh(t.file?.originalSize);return n?`image (${n})`:"image"}if(t.type==="pdf"){let n=Oh(t.file?.originalSize);return n?`PDF (${n})`:"PDF"}if(t.type==="parts"&&typeof t.file?.count=="number")return Me(t.file.count,"page");if(t.type==="file_unchanged")return"unchanged since last read";if(t.type==="create"&&typeof t.content=="string")return`created, ${Me(t.content.split(`
|
|
@@ -1060,7 +1062,7 @@ Output only valid JSON. No explanation, no markdown fences, just the JSON object
|
|
|
1060
1062
|
`)){if(!l.trim())continue;let f;try{f=JSON.parse(l)}catch{continue}if(!f||zn(f)||f.type!=="user")continue;let u=f.message?.content,d="";typeof u=="string"?d=At(u):Array.isArray(u)&&(d=u.map(Yl).filter(Boolean).join(" "));let p=d.replace(/\s+/g," ").trim();if(p)return(p.replace(/^Continuing from a prior session\. Here is the summary of our work so far:\s*/i,"").trim()||p).slice(0,200)}return""}finally{OE(e)}}function qE(r){let e;try{e=CE(Rh)}catch{return!1}for(let t of e)if(t.endsWith(".json"))try{let n=JSON.parse(_E(Xn(Rh,t),"utf8"));if(n?.sessionId!==r)continue;return process.kill(n.pid,0),!0}catch{}return!1}var $E,Ph,Ch,BE,Me,Oh,Rh,Mr,so=S(()=>{to();Kl();Hl();$E=Xn(Vl(),".claude","projects"),Ph=r=>Xn($E,IE(r));Ch=[/\[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,/^<local-command-stdout\b/i,/^<local-command-stderr\b/i];BE=/<ide_[a-z_]+>[\s\S]*?<\/ide_[a-z_]+>/gi;Me=(r,e,t=e+"s")=>`${r} ${r===1?e:t}`,Oh=r=>typeof r!="number"?"":r<1024?`${r}B`:r<1048576?`${Math.round(r/1024)}KB`:`${(r/1048576).toFixed(1)}MB`;Rh=Xn(Vl(),".claude","sessions");Mr=class extends Lr{displayName="Claude Mirror";detectsSelf(){return process.env.CLAUDECODE==="1"}detectsInstalled(){return NE(Xn(Vl(),".claude"))}sessionsDir(e){return Ph(e)}listSessionFiles(e){return ro(Ph(e))}parseEntry(e){try{return JSON.parse(e)}catch{return null}}idOf(e){return e.uuid}parentOf(e){return e.parentUuid}timestampOf(e){return e.timestamp}isSidechain(e){return!!e.isSidechain}isLeafType(e){return e.type==="user"||e.type==="assistant"}isRecoveryNoise(e){return!!e.isApiErrorMessage}apply(e,t){if(zn(e))return{events:[]};let n=[];if(e.type==="user"){let s=e.message?.content;if(typeof s=="string"){let i=At(s);i&&n.push({type:"user",text:i})}else if(Array.isArray(s))for(let i of s)if(i?.type==="tool_result"){let o=Wl(i.content);n.push({type:"tool_result",id:i.tool_use_id??"",content:o,isError:!!i.is_error,digest:Gl(e.toolUseResult,o)})}else{let o=Yl(i)||no(i);o&&n.push({type:"user",text:o})}return{events:n}}if(e.type==="attachment"&&e.attachment?.type==="queued_command"){let s=At(Wl(e.attachment.prompt));return s&&n.push({type:"user",text:s}),{events:n}}if(e.type==="assistant"){let s=e.message?.content,i=Array.isArray(s)?s:[],o=i.filter(u=>u.type==="text").map(u=>u.text??"").filter(u=>!ME(u)).join(""),a=i.filter(u=>u.type==="thinking").map(u=>u.thinking??"").join(`
|
|
1061
1063
|
`),c=i.filter(u=>u.type==="tool_use").map(u=>({id:u.id??"",name:u.name??"",input:u.input??{}}));if(o||a||c.length){let u=Date.parse(e.timestamp??""),d=!isNaN(u)&&u>=t;n.push({type:"assistant",text:o,thinking:a,tools:c,live:d})}let l=e.message?.usage??e.usage,f=l&&{in:l.input_tokens??0,out:l.output_tokens??0,cached:l.cache_read_input_tokens??0,cacheCreate:l.cache_creation_input_tokens??0};return{events:n,usage:f,model:e.message?.model}}return{events:n}}chainWorking(e){let t;for(let o of e)(o.type==="user"||o.type==="assistant")&&(t=o);if(!t)return!1;if(t.type==="user"){try{let o=t.message?.content,a=typeof o=="string"?o:Array.isArray(o)?o.filter(l=>l&&l.type==="text").map(l=>l.text??"").join(""):"";if(!(Array.isArray(o)&&o.some(l=>l&&l.type==="tool_result"))&&a.trim()&&At(a)==="")return!1}catch{}return!0}let s=(Array.isArray(t.message?.content)?t.message.content:[]).filter(o=>o.type==="tool_use").map(o=>o.id);if(s.length===0)return!1;let i=new Set;for(let o of e){let a=o.message?.content;if(Array.isArray(a))for(let c of a)c.type==="tool_result"&&c.tool_use_id&&i.add(c.tool_use_id)}return s.some(o=>o&&!i.has(o))}sessionAlive(e){return qE(e)}readPreview(e){return FE(e)}searchText(e){if(!e||zn(e)||e.type!=="user"&&e.type!=="assistant")return"";let t=e.message?.content,n="";if(typeof t=="string")n=At(t);else if(Array.isArray(t)){let s=t;n=e.type==="user"?s.map(Yl).filter(Boolean).join(" "):s.filter(i=>i.type==="text"&&typeof i.text=="string").map(i=>i.text).join(" ")}return n.replace(/\s+/g," ").trim()}}});import{spawn as _h}from"child_process";import{readdir as UE,readFile as Ih,writeFile as $h,unlink as zl,mkdir as JE}from"fs/promises";import{mkdirSync as Lh,writeFileSync as io,appendFileSync as KE,readFileSync as Xl}from"fs";import*as Ee from"path";import{fileURLToPath as HE}from"url";function Ql(r){return Ee.join(st(),`${r}.json`)}function Zn(r){return Ee.join(st(),`${r}.log`)}function Zl(r){return Ee.join(st(),`${r}.wait.json`)}function Mh(r){try{let e=JSON.parse(Xl(Zl(r),"utf8"));return e.cursors&&typeof e.cursors=="object"?e.cursors:{}}catch{return{}}}function eu(r,e=""){let t=Mh(r)[e];return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}function oo(r,e,t=""){try{Lh(st(),{recursive:!0});let n=Mh(r);n[t]=e,io(Zl(r),JSON.stringify({cursors:n}))}catch{}}function ao(r){let e=Zn(r);try{Lh(st(),{recursive:!0}),io(e,"")}catch{return()=>{}}let t=process.stdout.write.bind(process.stdout),n=process.stderr.write.bind(process.stderr),s=0,i=!1,o=a=>{if(!i)try{let c=typeof a=="string"?Buffer.from(a,"utf8"):Buffer.from(a);if(KE(e,c),s+=c.length,s>2*Nh){let l=Xl(e),f=l.subarray(Math.max(0,l.length-Nh));io(e,f),s=f.length}}catch{i=!0}};return process.stdout.write=((a,...c)=>(o(a),t(a,...c))),process.stderr.write=((a,...c)=>(o(a),n(a,...c))),()=>{process.stdout.write=t,process.stderr.write=n}}function Bh(r){try{io(Zn(r),"")}catch{}}function Je(r,e=0){try{let t=Xl(Zn(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 tu(r){return`\u2500\u2500 run ${r} \u2500\u2500 ${new Date().toTimeString().slice(0,8)}`}function YE(r){let e=WE.exec(r);return e?Number(e[1]):void 0}function Dh(r,e){let t=r.split(`
|
|
1062
1064
|
`),n=[];if(t.forEach((o,a)=>{let c=YE(o);c!==void 0&&n.push({id:c,idx:a})}),!n.length)return e==="latest"?r:"";let s=e==="latest"?n[n.length-1]:n.find(o=>o.id===e);if(!s)return"";let i=n.find(o=>o.idx>s.idx);return t.slice(s.idx,i?i.idx:t.length).join(`
|
|
1063
|
-
`)}function ru(r){try{return process.kill(r,0),!0}catch(e){return e.code==="EPERM"}}async function jh(r){await JE(st(),{recursive:!0}),await $h(Ql(r.pid),JSON.stringify(r))}async function Fh(r,e){let t=Ql(r);try{let n=JSON.parse(await Ih(t,"utf8"));if(n.denied===e)return;n.denied=e,await $h(t,JSON.stringify(n))}catch{}}async function Qn(r){await zl(Ql(r)).catch(()=>{}),await zl(Zn(r)).catch(()=>{}),await zl(Zl(r)).catch(()=>{})}async function Q(r){let e;try{e=await UE(st())}catch{return[]}let t=[];return await Promise.all(e.map(async s=>{if(!/^\d+\.json$/.test(s))return;let i=parseInt(s,10),o;try{o=JSON.parse(await Ih(Ee.join(st(),s),"utf8"))}catch{await Qn(i);return}o&&typeof o.pid=="number"&&ru(o.pid)?t.push(o):await Qn(i)})),(r?t.filter(s=>s.agent==null&&Ah(s.file,r)):t).sort((s,i)=>s.startedAt-i.startedAt)}async function nu(r,e){let t=X(r);return(await Q()).find(n=>n.cwd!=null&&X(n.cwd)===t&&(e?n.agent===e:n.agent!=null))}async function Xt(r){try{process.kill(r,"SIGTERM")}catch{}await Qn(r)}function Br(r,e){let t=X(e);return r.filter(n=>n.agent==null&&n.pid!==process.pid&&X(n.file)===t)}async function su(r){let e=Br(await Q(),r);for(let t of e)await Xt(t.pid);return e}function GE(r,e,t){(process.platform==="win32"?_h("cmd",["/c","start","","/b",r,...e],{cwd:t,stdio:"ignore",windowsHide:!0}):_h(r,e,{cwd:t,detached:!0,stdio:"ignore"})).unref()}function qh(){return Ee.join(Ee.dirname(HE(import.meta.url)),"index.js")}function zE(r,e={}){return{command:process.execPath,args:[qh(),...e.trust?["--trust"]:[],...e.batch?["--batch",e.batch]:[],...e.mode?["--mode",e.mode]:[],r,...e.open===!1?["--no-open"]:[]]}}function XE(r){return{command:process.execPath,args:[qh(),`agent:${r}`,"--no-open"]}}async function Uh(r,e,t,n){let s=await r();if(s)return s;GE(e.command,e.args,t);let i=Date.now()+2e4;for(;Date.now()<i;){await VE(150);let o=await r();if(o)return o}throw new Error(`Launched ${n} but it did not register within 20s.`)}async function co(r,e={}){let t=e.cwd??process.cwd(),n=Ee.resolve(t,r),[s]=await su(n),i={...e,batch:e.batch??s?.batch,mode:e.mode??s?.mode};return Uh(async()=>Br(await Q(),n)[0],zE(r,i),t,Ee.basename(r))}async function Jh(r,e=process.cwd()){return Uh(()=>nu(e,r),XE(r),e,`the ${r} mirror`)}var Nh,WE,VE,Be=S(()=>{Vn();Nh=1e6;WE=/^── run (\d+) ── /;VE=r=>new Promise(e=>setTimeout(e,r))});function lo(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 iu(r){return(lo(r)??"bulb").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"bulb"}var ou=S(()=>{});import{readdirSync as Kh,readFileSync as QE,statSync as Hh}from"fs";import{join as uo,basename as ZE}from"path";function Wh(r,e,t){if(e>8)return t;let n;try{n=Kh(r,{withFileTypes:!0})}catch{return t}for(let s of n)if(s.isDirectory()){if(s.name.startsWith(".")||s.name==="node_modules")continue;Wh(uo(r,s.name),e+1,t)}else s.isFile()&&s.name.endsWith(".bulb.md")&&t.push(uo(r,s.name));return t}function au(r){let e=uo(xt(r),"batches"),t;try{t=Kh(e,{withFileTypes:!0})}catch{return[]}return t.filter(n=>n.isDirectory()).map(n=>{let s=0;try{s=Hh(uo(e,n.name)).mtimeMs}catch{}return{name:n.name,mtime:s}}).sort((n,s)=>s.mtime-n.mtime).map(n=>n.name)}function fo(r){return Wh(r,0,[]).map(e=>{let t=0;try{t=Hh(e).mtimeMs}catch{}let n,s=!1;try{let i=QE(e,"utf8");n=lo(i.slice(0,1024));let o=le(i);s=!!o&&ki(wr(o))}catch{}return{path:e,name:n??ZE(e).replace(/\.bulb\.md$/,""),mtime:t,serverOnly:s}})}var Yh=S(()=>{be();_n();ou();qe()});import*as zh from"net";import{mkdir as eA,readFile as tA,writeFile as Xh}from"fs/promises";import{existsSync as rA}from"fs";import{join as Qh}from"path";function tg(){return Qh(Ir(),"blocks")}function cu(r){return Qh(tg(),`${r}.json`)}function mo(r){return new Promise(e=>{let t=zh.createServer();t.once("error",()=>e(!1)),t.listen(r,"127.0.0.1",()=>t.close(()=>e(!0)))})}async function iA(r){for(let e=r;e<65535;e++)if(await mo(e))return e;throw new Error(`No free port found above ${r}`)}async function lu(r){let e=(await Q()).find(n=>n.port===r),t=e?` (pid ${e.pid}, ${e.agent?`agent:${e.agent}`:e.file})`:"";console.error(`port ${r} in use${t}`),process.exit(1)}async function ho(r){try{let e=JSON.parse(await tA(cu(r),"utf8"));return e&&typeof e.cwd=="string"?{cwd:e.cwd,slots:e.slots??{},mirrors:e.mirrors??{}}:void 0}catch{return}}async function go(r,e){await Xh(cu(r),JSON.stringify(e,null,2))}async function oA(r){let e=X(r);try{await eA(tg(),{recursive:!0})}catch{return}let t=[];for(let o=0;o<eg;o++)t.push(Zh+o*Qt);let n=await Promise.all(t.map(async o=>({base:o,block:await ho(o)})));for(let{base:o,block:a}of n)if(a?.cwd===e)return o;let s={cwd:e,slots:{},mirrors:{}};for(let{base:o,block:a}of n){if(!a)try{return await Xh(cu(o),JSON.stringify(s,null,2),{flag:"wx"}),o}catch{if((await ho(o))?.cwd===e)return o;continue}if(!rA(a.cwd))return await go(o,s),o}let i=n.filter(o=>!!o.block).sort((o,a)=>Vh(o.block)-Vh(a.block))[0];if(i)return await go(i.base,s),i.base}function Vh(r){return Object.values(r.slots).reduce((e,t)=>Math.max(e,t.usedAt??0),0)}async function aA(r,e){let t=await ho(r)??{cwd:"",slots:{},mirrors:{}};if(e.kind==="mirror"){let i=t.mirrors[e.agent];if(i!==void 0)return i;let o=Gh(t),a=o.has(0)?sA:0;for(;a>po&&o.has(a);)a--;return t.mirrors[e.agent]=a,await go(r,t),a}let n=X(e.file),s=t.slots[n]?.offset;if(s===void 0){let i=Gh(t);for(s=po;s<Qt&&i.has(s);)s++;if(s>=Qt){let o=Object.entries(t.slots).sort((a,c)=>(a[1].usedAt??0)-(c[1].usedAt??0))[0];s=o?o[1].offset:po,o&&delete t.slots[o[0]]}}return t.slots[n]={offset:s,usedAt:Date.now()},await go(r,t),s}function Gh(r){return new Set([...Object.values(r.mirrors),...Object.values(r.slots).map(e=>e.offset)])}async function cA(r,e){let t=await oA(e);return t===void 0?void 0:t+await aA(t,r)}async function uu(r){let e=X(r);for(let t=0;t<eg;t++){let n=await ho(Zh+t*Qt);if(n?.cwd===e)return s=>n.slots[X(s)]?.usedAt??0}return()=>0}async function yo(r){if(r.explicit!==void 0)return await mo(r.explicit)||await lu(r.explicit),{port:r.explicit};let e=await cA(r.target,r.cwd);if(e!==void 0){let n=e-e%Qt;for(let s=0;s<4;s++){if(await mo(e))return{port:e};await new Promise(i=>setTimeout(i,150))}for(let s=po;s<Qt;s++){let i=n+s;if(i!==e&&await mo(i))return{port:i,note:`(slot ${e} was busy)`}}}return{port:await iA(nA),note:e===void 0?"(no port block available)":"(this project's block was full)"}}var Zh,Qt,eg,nA,po,sA,es=S(()=>{Vn();Be();Zh=20100,Qt=100,eg=19,nA=23e3,po=1,sA=Qt-1});function Dr(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")||r.infer.trim()||/\btb\s*\.\s*infer\b/.test(e))return"AI (your API keys)";if(/\btb\s*\.\s*server\s*\.\s
|
|
1065
|
+
`)}function ru(r){try{return process.kill(r,0),!0}catch(e){return e.code==="EPERM"}}async function jh(r){await JE(st(),{recursive:!0}),await $h(Ql(r.pid),JSON.stringify(r))}async function Fh(r,e){let t=Ql(r);try{let n=JSON.parse(await Ih(t,"utf8"));if(n.denied===e)return;n.denied=e,await $h(t,JSON.stringify(n))}catch{}}async function Qn(r){await zl(Ql(r)).catch(()=>{}),await zl(Zn(r)).catch(()=>{}),await zl(Zl(r)).catch(()=>{})}async function Q(r){let e;try{e=await UE(st())}catch{return[]}let t=[];return await Promise.all(e.map(async s=>{if(!/^\d+\.json$/.test(s))return;let i=parseInt(s,10),o;try{o=JSON.parse(await Ih(Ee.join(st(),s),"utf8"))}catch{await Qn(i);return}o&&typeof o.pid=="number"&&ru(o.pid)?t.push(o):await Qn(i)})),(r?t.filter(s=>s.agent==null&&Ah(s.file,r)):t).sort((s,i)=>s.startedAt-i.startedAt)}async function nu(r,e){let t=X(r);return(await Q()).find(n=>n.cwd!=null&&X(n.cwd)===t&&(e?n.agent===e:n.agent!=null))}async function Xt(r){try{process.kill(r,"SIGTERM")}catch{}await Qn(r)}function Br(r,e){let t=X(e);return r.filter(n=>n.agent==null&&n.pid!==process.pid&&X(n.file)===t)}async function su(r){let e=Br(await Q(),r);for(let t of e)await Xt(t.pid);return e}function GE(r,e,t){(process.platform==="win32"?_h("cmd",["/c","start","","/b",r,...e],{cwd:t,stdio:"ignore",windowsHide:!0}):_h(r,e,{cwd:t,detached:!0,stdio:"ignore"})).unref()}function qh(){return Ee.join(Ee.dirname(HE(import.meta.url)),"index.js")}function zE(r,e={}){return{command:process.execPath,args:[qh(),...e.trust?["--trust"]:[],...e.batch?["--batch",e.batch]:[],...e.mode?["--mode",e.mode]:[],r,...e.open===!1?["--no-open"]:[]]}}function XE(r){return{command:process.execPath,args:[qh(),`agent:${r}`,"--no-open"]}}async function Uh(r,e,t,n){let s=await r();if(s)return s;GE(e.command,e.args,t);let i=Date.now()+2e4;for(;Date.now()<i;){await VE(150);let o=await r();if(o)return o}throw new Error(`Launched ${n} but it did not register within 20s.`)}async function co(r,e={}){let t=e.cwd??process.cwd(),n=Ee.resolve(t,r),[s]=await su(n),i={...e,batch:e.batch??s?.batch,mode:e.mode??s?.mode};return Uh(async()=>Br(await Q(),n)[0],zE(r,i),t,Ee.basename(r))}async function Jh(r,e=process.cwd()){return Uh(()=>nu(e,r),XE(r),e,`the ${r} mirror`)}var Nh,WE,VE,Be=S(()=>{Vn();Nh=1e6;WE=/^── run (\d+) ── /;VE=r=>new Promise(e=>setTimeout(e,r))});function lo(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 iu(r){return(lo(r)??"bulb").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"bulb"}var ou=S(()=>{});import{readdirSync as Kh,readFileSync as QE,statSync as Hh}from"fs";import{join as uo,basename as ZE}from"path";function Wh(r,e,t){if(e>8)return t;let n;try{n=Kh(r,{withFileTypes:!0})}catch{return t}for(let s of n)if(s.isDirectory()){if(s.name.startsWith(".")||s.name==="node_modules")continue;Wh(uo(r,s.name),e+1,t)}else s.isFile()&&s.name.endsWith(".bulb.md")&&t.push(uo(r,s.name));return t}function au(r){let e=uo(xt(r),"batches"),t;try{t=Kh(e,{withFileTypes:!0})}catch{return[]}return t.filter(n=>n.isDirectory()).map(n=>{let s=0;try{s=Hh(uo(e,n.name)).mtimeMs}catch{}return{name:n.name,mtime:s}}).sort((n,s)=>s.mtime-n.mtime).map(n=>n.name)}function fo(r){return Wh(r,0,[]).map(e=>{let t=0;try{t=Hh(e).mtimeMs}catch{}let n,s=!1;try{let i=QE(e,"utf8");n=lo(i.slice(0,1024));let o=le(i);s=!!o&&ki(wr(o))}catch{}return{path:e,name:n??ZE(e).replace(/\.bulb\.md$/,""),mtime:t,serverOnly:s}})}var Yh=S(()=>{be();_n();ou();qe()});import*as zh from"net";import{mkdir as eA,readFile as tA,writeFile as Xh}from"fs/promises";import{existsSync as rA}from"fs";import{join as Qh}from"path";function tg(){return Qh(Ir(),"blocks")}function cu(r){return Qh(tg(),`${r}.json`)}function mo(r){return new Promise(e=>{let t=zh.createServer();t.once("error",()=>e(!1)),t.listen(r,"127.0.0.1",()=>t.close(()=>e(!0)))})}async function iA(r){for(let e=r;e<65535;e++)if(await mo(e))return e;throw new Error(`No free port found above ${r}`)}async function lu(r){let e=(await Q()).find(n=>n.port===r),t=e?` (pid ${e.pid}, ${e.agent?`agent:${e.agent}`:e.file})`:"";console.error(`port ${r} in use${t}`),process.exit(1)}async function ho(r){try{let e=JSON.parse(await tA(cu(r),"utf8"));return e&&typeof e.cwd=="string"?{cwd:e.cwd,slots:e.slots??{},mirrors:e.mirrors??{}}:void 0}catch{return}}async function go(r,e){await Xh(cu(r),JSON.stringify(e,null,2))}async function oA(r){let e=X(r);try{await eA(tg(),{recursive:!0})}catch{return}let t=[];for(let o=0;o<eg;o++)t.push(Zh+o*Qt);let n=await Promise.all(t.map(async o=>({base:o,block:await ho(o)})));for(let{base:o,block:a}of n)if(a?.cwd===e)return o;let s={cwd:e,slots:{},mirrors:{}};for(let{base:o,block:a}of n){if(!a)try{return await Xh(cu(o),JSON.stringify(s,null,2),{flag:"wx"}),o}catch{if((await ho(o))?.cwd===e)return o;continue}if(!rA(a.cwd))return await go(o,s),o}let i=n.filter(o=>!!o.block).sort((o,a)=>Vh(o.block)-Vh(a.block))[0];if(i)return await go(i.base,s),i.base}function Vh(r){return Object.values(r.slots).reduce((e,t)=>Math.max(e,t.usedAt??0),0)}async function aA(r,e){let t=await ho(r)??{cwd:"",slots:{},mirrors:{}};if(e.kind==="mirror"){let i=t.mirrors[e.agent];if(i!==void 0)return i;let o=Gh(t),a=o.has(0)?sA:0;for(;a>po&&o.has(a);)a--;return t.mirrors[e.agent]=a,await go(r,t),a}let n=X(e.file),s=t.slots[n]?.offset;if(s===void 0){let i=Gh(t);for(s=po;s<Qt&&i.has(s);)s++;if(s>=Qt){let o=Object.entries(t.slots).sort((a,c)=>(a[1].usedAt??0)-(c[1].usedAt??0))[0];s=o?o[1].offset:po,o&&delete t.slots[o[0]]}}return t.slots[n]={offset:s,usedAt:Date.now()},await go(r,t),s}function Gh(r){return new Set([...Object.values(r.mirrors),...Object.values(r.slots).map(e=>e.offset)])}async function cA(r,e){let t=await oA(e);return t===void 0?void 0:t+await aA(t,r)}async function uu(r){let e=X(r);for(let t=0;t<eg;t++){let n=await ho(Zh+t*Qt);if(n?.cwd===e)return s=>n.slots[X(s)]?.usedAt??0}return()=>0}async function yo(r){if(r.explicit!==void 0)return await mo(r.explicit)||await lu(r.explicit),{port:r.explicit};let e=await cA(r.target,r.cwd);if(e!==void 0){let n=e-e%Qt;for(let s=0;s<4;s++){if(await mo(e))return{port:e};await new Promise(i=>setTimeout(i,150))}for(let s=po;s<Qt;s++){let i=n+s;if(i!==e&&await mo(i))return{port:i,note:`(slot ${e} was busy)`}}}return{port:await iA(nA),note:e===void 0?"(no port block available)":"(this project's block was full)"}}var Zh,Qt,eg,nA,po,sA,es=S(()=>{Vn();Be();Zh=20100,Qt=100,eg=19,nA=23e3,po=1,sA=Qt-1});function Dr(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")||r.infer.trim()||/\btb\s*\.\s*infer\b/.test(e))return"AI (your API keys)";if(/\btb\s*\.\s*server\s*\.\s*\w/.test(e)||e.includes("/__api"))return"server-side code (server.ts)"}var bo=S(()=>{});import{readFile as lA}from"fs/promises";async function du(r){try{let e=le(await lA(r,"utf-8"));return e?Dr(wr(e)):void 0}catch{return}}var rg=S(()=>{_n();bo()});function fu(r){let e=le(r);if(!e)return r;let t=e.files.get("code.tsx");if(!t)return r;let n=Dm(t);if(!n.length)return r;let s=e.files.get("config.json"),i={};if(s)try{let l=JSON.parse(s);l&&typeof l=="object"&&(i=l)}catch{}let o=i.dependencies&&typeof i.dependencies=="object"?{...i.dependencies}:{},a=n.filter(l=>!(l in o));if(!a.length)return r;for(let l of a)o[l]="latest";i.dependencies=o;let c={name:e.frontmatter.name};for(let[l,f]of e.files){let u=hd(l);u&&(c[u]=f)}return c.config=JSON.stringify(i,null,2),xd(c)}var ng=S(()=>{be();xi()});import{spawn as sg}from"child_process";import{basename as uA}from"path";function dA(){return process.env.TYPEBULB_EDITOR||"code"}function pA(r,e,t){return t==null?[e]:fA.test(uA(r))?["-g",`${e}:${t}`]:[`+${t}`,e]}function mA(r,e){let t=dA();return{command:t,args:pA(t,r,e)}}function pu(r,e){let{command:t,args:n}=mA(r,e),s=process.platform==="win32"?sg("cmd.exe",["/d","/s","/c",t,...n],{detached:!0,stdio:"ignore",windowsHide:!0}):sg(t,n,{detached:!0,stdio:"ignore"});s.on("error",i=>console.error("[typebulb] editor launch failed:",i?.message??i)),s.unref()}var fA,ig=S(()=>{fA=/^(code|code-insiders|codium|vscodium|cursor|windsurf)(\.cmd|\.exe)?$/i});import{readFileSync as hA,existsSync as gA}from"fs";import*as Zt from"path";import{fileURLToPath as yA}from"url";function og(){let r=Zt.dirname(yA(import.meta.url));for(;!gA(Zt.join(r,"package.json"));){let e=Zt.dirname(r);if(e===r)break;r=e}return r}function er(){return Zt.join(og(),"README.md")}function jr(){return Zt.join(og(),"description.md")}function bA(r){let e=hA(jr(),"utf8").trim().replace(/\s+/g," ");return`---
|
|
1064
1066
|
name: typebulb
|
|
1065
1067
|
description: ${JSON.stringify(e)}
|
|
1066
1068
|
version: ${r}
|
|
@@ -1295,7 +1297,7 @@ Usage:
|
|
|
1295
1297
|
(no arg: list this project's running servers;
|
|
1296
1298
|
--run latest|N shows just one hot-reload run;
|
|
1297
1299
|
--clear empties it). For agents: fetch
|
|
1298
|
-
tb.
|
|
1300
|
+
tb.log / errors of a bulb you launched
|
|
1299
1301
|
without watching its terminal.
|
|
1300
1302
|
typebulb send <file> [msg] Push a message into a running bulb's page \u2014
|
|
1301
1303
|
its tb.onMessage(cb) handlers receive it. The
|
|
@@ -1410,7 +1412,7 @@ Server API:
|
|
|
1410
1412
|
.env / .env.local load from the working directory; --mode <name> adds .env.<name>.
|
|
1411
1413
|
|
|
1412
1414
|
Built-in server functions (available without a **server.ts** section):
|
|
1413
|
-
tb.
|
|
1415
|
+
tb.log(...) Print to the CLI's stdout
|
|
1414
1416
|
|
|
1415
1417
|
AI API:
|
|
1416
1418
|
Bulbs can call AI providers via tb.ai(). Set API keys in .env:
|
|
@@ -1430,7 +1432,7 @@ Examples:
|
|
|
1430
1432
|
typebulb my-editor.bulb.md
|
|
1431
1433
|
typebulb --no-watch --port 8080 my-editor.bulb.md
|
|
1432
1434
|
typebulb .
|
|
1433
|
-
`)}qe();_n();ws();Gn();so();Su();var Yo={claude:{adapter:()=>new Mr,server:()=>Promise.resolve().then(()=>(Py(),Ty))},pi:{adapter:()=>new Ur,server:()=>Promise.resolve().then(()=>(By(),My))}};function Dy(r){return r in Yo}function Wr(){return Object.keys(Yo)}function jy(){return Object.fromEntries(Object.entries(Yo).map(([r,e])=>[r,e.adapter]))}function Fy(r){return Yo[r].server()}qe();import*as Ge from"path";import{spawn as
|
|
1435
|
+
`)}qe();_n();ws();Gn();so();Su();var Yo={claude:{adapter:()=>new Mr,server:()=>Promise.resolve().then(()=>(Py(),Ty))},pi:{adapter:()=>new Ur,server:()=>Promise.resolve().then(()=>(By(),My))}};function Dy(r){return r in Yo}function Wr(){return Object.keys(Yo)}function jy(){return Object.fromEntries(Object.entries(Yo).map(([r,e])=>[r,e.adapter]))}function Fy(r){return Yo[r].server()}qe();import*as Ge from"path";import{spawn as OO,execSync as RO}from"child_process";import{createRequire as CO}from"module";import{existsSync as _O}from"fs";import*as fe from"fs/promises";import*as ue from"path";var ju=[{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"}],Fu=[{name:"dom"},{name:"dom.iterable"},{name:"dom.asynciterable"}];function qu(r,e){if(!e)return r.filter(s=>!s.since);let t={"5.0":0,"5.5":1},n=t[e];return r.filter(s=>!s.since||t[s.since]<=n)}var rO=`
|
|
1434
1436
|
/**
|
|
1435
1437
|
* Get raw data chunk from the Data tab.
|
|
1436
1438
|
* @param index - Chunk index (0-based). Separate chunks with 2 blank lines.
|
|
@@ -1608,42 +1610,47 @@ type AiChunk =
|
|
|
1608
1610
|
*
|
|
1609
1611
|
* @returns The full canonical URL
|
|
1610
1612
|
*/
|
|
1611
|
-
url(): Promise<string>;`,oO="\n /**\n * Subscribe to a value pushed from the terminal via `typebulb send <file> [message]`.\n *\n * The dual of `tb.
|
|
1613
|
+
url(): Promise<string>;`,oO="\n /**\n * Subscribe to a value pushed from the terminal via `typebulb send <file> [message]`.\n *\n * The dual of `tb.log` (data out): a value sent *in* from the CLI, no `--trust` required.\n * Use it to start expensive work on demand instead of on load \u2014 e.g. `tb.onMessage(() => start())`\n * \u2014 so hot reloads don't re-trigger it while you edit, and an agent kicks off one run when ready.\n *\n * The message is the JSON-parsed value of what `send` was given (or the raw string if it isn't\n * JSON; `undefined` for a bare `typebulb send <file>`). A non-`undefined` return value (awaited)\n * becomes the reply `send --wait` prints on stdout \u2014 JSON-serializable, at most one handler\n * replying \u2014 the structured read-back for self-tests. Returns an unsubscribe function. Inert in\n * an embedded bulb (no sender) \u2014 the handler is registered but never fires.\n *\n * @param handler - Called with each pushed message; may return a JSON-serializable reply.\n * @returns An unsubscribe function.\n */\n onMessage(handler: (message: any) => unknown): () => void;",aO="\n /**\n * Print to the CLI's stdout \u2014 the bulb's log channel, read back with `typebulb logs <file>`.\n *\n * Ungated: needs no `server.ts` block and no `--trust`, so a Restricted client-only bulb can\n * instrument itself. Args cross to the CLI as JSON; where no CLI serves the page (web, embedded,\n * or a transport failure) it falls back to the browser console. Works in `server.ts` too (same\n * as `console.log` there).\n */\n log(...args: any[]): void;",cO="\n /**\n * Server-side function proxy.\n *\n * In the CLI, calls exported functions from the `**server.ts**` section.\n *\n * A normal export is awaited for its result (`await tb.server.fn()`). An `async function*`\n * export streams: `for await (const chunk of tb.server.gen())`. The call object supports both;\n * break the `for await` to cancel and tear down the server generator.\n */\n server: Record<string, (...args: any[]) => Promise<any> & AsyncIterable<any>>;",Uu=`${Uy}
|
|
1612
1614
|
/**
|
|
1613
1615
|
* Typebulb utilities namespace.
|
|
1614
1616
|
* Type \`tb.\` to discover available helpers.
|
|
1615
1617
|
*/
|
|
1616
|
-
declare const tb: {${rO}${iO}${nO}${aO}${oO}${Jy}${Wy}${Yy}${Ky}${sO}${Hy}
|
|
1618
|
+
declare const tb: {${rO}${iO}${nO}${aO}${cO}${oO}${Jy}${Wy}${Yy}${Ky}${sO}${Hy}
|
|
1617
1619
|
};
|
|
1618
|
-
`,
|
|
1620
|
+
`,lO=`
|
|
1621
|
+
/**
|
|
1622
|
+
* Print to the CLI's stdout \u2014 the same channel as \`console.log\` here (the server's console IS
|
|
1623
|
+
* the bulb's log). One log verb across blocks: page-side \`tb.log\` reaches this same stdout.
|
|
1624
|
+
*/
|
|
1625
|
+
log(...args: any[]): void;`,Ju=`${Uy}
|
|
1619
1626
|
/**
|
|
1620
1627
|
* Typebulb utilities namespace (server-side).
|
|
1621
1628
|
* Type \`tb.\` to discover available helpers.
|
|
1622
1629
|
*/
|
|
1623
|
-
declare const tb: {${Jy}${Wy}${Yy}${Ky}${Hy}
|
|
1630
|
+
declare const tb: {${lO}${Jy}${Wy}${Yy}${Ky}${Hy}
|
|
1624
1631
|
};
|
|
1625
|
-
`;Qe();import
|
|
1632
|
+
`;Qe();import pO from"p-limit";Qe();import{resolve as Gy}from"resolve.exports";var ot={maxRelativeTypeRefs:500,maxBareDeps:8,maxBareDepth:3,prefetchConcurrency:4,negativeTtlMs:1e4},cs=["index.d.ts","index.d.mts"],Ku=/\.d\.(ts|mts|cts)$/i;function Vo(r){return/\.d\.(ts|mts|cts)(?:[?#].*)?$/i.test(r)||/[?&]dts(?:[&#]|$)/i.test(r)}function Vy(r){return[`${r}.d.ts`,`${r}.d.mts`]}function _t(r){if(!r||r==="./"||r==="/")return[...cs];let e=r.replace(/\.(mjs|cjs|js|mts|cts|ts)$/i,""),t=Vy(e),n=e.endsWith("/")?e:`${e}/`;return t.push(...Vy(`${n}index`)),t}async function Yr(r,{retries:e=2,timeoutMs:t=15e3,init:n}={}){for(let s=0;s<=e;s++){let i=new AbortController,o=setTimeout(()=>i.abort(),t);try{let a=await fetch(r,{...n,signal:i.signal});if(uO(a.status)&&s<e)continue;return a}catch{if(s<e)continue;return}finally{clearTimeout(o)}}}function uO(r){return r===408||r===429||r>=500&&r<600}var Go=class{constructor(e,t){this.fetchDts=e,this.cdnClient=t}async tryUrls(e){for(let t of e){let n=await this.fetchDts(t);if(n&&(this.looksLikeDts(n.dts)||Vo(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)}async loadPackageAtVersionedRoot(e,t){let n=this.cdnClient.packageJson(new j({name:e,version:t})),s=await Yr(n);if(!s?.ok)return;let i;try{i=await s.json()}catch{return}if(i)return{pkg:i,baseDir:this.cdnClient.baseDir(new j({name:e,version:t??i.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,n){if(e.kind==="types"){let o=Ut(e.path);if(!o||o==="/"||o===".")return this.tryUntilSuccess([...cs],t);if(!Ku.test(o)){let a=await this.tryUntilSuccess(_t(o),t);if(a)return a}return t(o)}let s=_t(e.path),i=n?.subpath?[...s,...cs]:[...cs,...s];return this.tryUntilSuccess(i,t)}toResolutionResult(e){return{kind:Ku.test(e)?"types":"probe",path:e}}resolveExportsPath(e,t){let n=t||".",s=e;try{let i=this.extractPathFromResult(Gy(s,n,{conditions:["types"]}));if(i)return i}catch{}try{return this.extractPathFromResult(Gy(s,n,{browser:!0,conditions:["import","default","module","browser","node"]}))}catch{return}}async resolve(e){try{let t=j.parse(e),{pkg:n,baseDir:s}=await this.loadPackageAtVersionedRoot(t.name,t.version)||{};if(!n||!s)return;let i={name:t.name,version:t.version},o=new j(i).format(),a=new j({...i,subpath:t.subpath}).format(),c=u=>this.fetchCandidateFrom(s,t.name,u);if(t.subpath){let u=dl(t.subpath),d=this.resolveExportsPath(n,u);if(d){let h=await this.resolveFromSelected(this.toResolutionResult(d),c,{subpath:!0});if(h)return{...h,resolvedPkg:a}}let p=await this.tryUntilSuccess(_t(u),c);if(p)return{...p,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:o}}let f=this.resolveExportsPath(n,".");if(f){let u=await this.resolveFromSelected(this.toResolutionResult(f),c);if(u)return{...u,resolvedPkg:o}}return}catch{return}}async fetchCandidateFrom(e,t,n){let s=Ut(n),i=new URL(s,e).toString(),o=await this.tryUrls([i]);return o?{dts:o.dts,url:o.url,resolvedPkg:t}:void 0}};Qe();import{gunzipSync as dO}from"fflate";var zo=class{async fetchAndExtract(e,t){let n=this.getTarballUrl(e,t),s=await Yr(n,{timeoutMs:3e4});if(!s?.ok)return new Map;let i=new Uint8Array(await s.arrayBuffer());return this.extractDtsFiles(i)}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=dO(e),s=new TextDecoder("utf-8"),i=0;for(;i<n.length-512;){let o=n.slice(i,i+512);if(o[0]===0)break;let a=o.slice(0,100),c=a.indexOf(0),l=s.decode(a.slice(0,c>0?c:100)).trim(),f=o.slice(124,136),u=s.decode(f).trim().replace(/\0/g,""),d=parseInt(u,8)||0,p=String.fromCharCode(o[156]);if(i+=512,(p==="0"||p==="\0")&&(l.endsWith(".d.ts")||l.endsWith(".d.mts"))){let h=n.slice(i,i+d);t.set(this.normalizeTarPath(l),s.decode(h))}i+=Math.ceil(d/512)*512}}catch{}return t}};var Xo=class{constructor(e,t,n=new zo){this.cdnClient=e,this.cache=t,this.tarballFetcher=n}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 i=Jt.majorOf(n),o=e.filter(a=>Jt.majorOf(a)===i);if(o.length)return o.sort((a,c)=>Jt.cmp(c,a))[0]}let s=t?.latest;return s&&e.includes(s)?s:e[0]}catch{return e[0]}}subpathCandidates(e){let t=e.replace(/\.(mjs|cjs|js|mts|cts|ts)$/i,""),n=_t(e);return t!==e&&n.push(`${e}.d.ts`,`${e}/index.d.ts`),n}async fetchFromVersionedRoot(e,t){let n=new j(e),s=n.version;if(!s)return;let i;try{i=await this.tarballFetcher.fetchAndExtract(n.name,s)}catch{return}if(!i||i.size===0)return;for(let[a,c]of i.entries()){let l=this.cdnClient.file(e,a);try{await this.cache.setCachedFile(l,c)}catch{}}let o=t.subpath?this.subpathCandidates(t.subpath):["index.d.ts"];for(let a of o){let c=i.get(a);if(c)return{dts:c,url:this.cdnClient.file(e,a),resolvedPkg:t.subpath?new j(t).format():t.name}}}async resolve(e){let t=j.parse(e);if(t.name)for(let n of this.typesNameCandidates(t.name)){let s=`@types/${n}`,i;try{i=await this.cdnClient.fetchVersionsIndex(s)}catch{continue}if(!i?.versions?.length)continue;let o=this.selectTypesVersion(i.versions,i.distTags,t.version),a=await this.fetchFromVersionedRoot(`${s}@${o}`,t);if(a)return a}}};var Qo=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=e.split(`
|
|
1626
1633
|
`).filter(s=>{let i=s.trimStart();return!(i.startsWith("*")||i.startsWith("//")||i.startsWith("/*"))}).join(`
|
|
1627
|
-
`),n=new Set;for(let s of t.matchAll(/(import|export)\s+[^'"\n]*from\s*['"]([^'"\n]+)['"]/g))n.add(s[2]);for(let s of t.matchAll(/export\s*\*\s*from\s*['"]([^'"\n]+)['"]/g))n.add(s[1]);return Array.from(n)}isBare(e){return!(e.startsWith("./")||e.startsWith("../")||e.startsWith("file:")||e.startsWith("http://")||e.startsWith("https://"))}};Qe();var zy="file:///node_modules",Zo=class{constructor(){this.epoch=0}bumpEpoch(){this.epoch+=1}epochDir(){return`__tsepoch_${this.epoch}`}pathForMain(e){return`${zy}/${this.epochDir()}/${e}/index.d.ts`}pathFor(e,t){let n=Ut(t);return`${zy}/${this.epochDir()}/${e}/${n}`}};import{LRUCache as
|
|
1628
|
-
`);await this.prefetchBareDeps(h,l,d,p,s);let m=c.format(),b=e===m?[e]:[e,m],A=b.some(w=>this.ambientlyDeclares(i,w));return A?this.markFileAmbient(d,f):p.push(...b.map(w=>({module:w,path:f}))),{pkg:e,mainPath:f,files:d,shims:p,ambient:A}}};Sl();Qe();xr();Un();wl();kr();import*as Vr from"path";var
|
|
1629
|
-
`,"utf8"),await fe.writeFile(ue.join(e,"code.tsx"),r.code,"utf8"),await fe.writeFile(ue.join(e,"tb.d.ts"),Uu,"utf8"),{dir:e}}var Wu={target:"es2023",module:"esnext",moduleResolution:"bundler",strict:!0,noEmit:!0,skipLibCheck:!0,esModuleInterop:!0,allowSyntheticDefaultImports:!0,forceConsistentCasingInFileNames:!0};function
|
|
1630
|
-
`,"utf8"),{dir:e}}function
|
|
1631
|
-
`))console.log(`${e} ${n}`);return r.length>0}function
|
|
1634
|
+
`),n=new Set;for(let s of t.matchAll(/(import|export)\s+[^'"\n]*from\s*['"]([^'"\n]+)['"]/g))n.add(s[2]);for(let s of t.matchAll(/export\s*\*\s*from\s*['"]([^'"\n]+)['"]/g))n.add(s[1]);return Array.from(n)}isBare(e){return!(e.startsWith("./")||e.startsWith("../")||e.startsWith("file:")||e.startsWith("http://")||e.startsWith("https://"))}};Qe();var zy="file:///node_modules",Zo=class{constructor(){this.epoch=0}bumpEpoch(){this.epoch+=1}epochDir(){return`__tsepoch_${this.epoch}`}pathForMain(e){return`${zy}/${this.epochDir()}/${e}/index.d.ts`}pathFor(e,t){let n=Ut(t);return`${zy}/${this.epochDir()}/${e}/${n}`}};import{LRUCache as fO}from"lru-cache";function Xy(r){let e=new fO({ttl:ot.negativeTtlMs,max:500}),t=new Map;return async function(s){try{if(await r.isNegative(s)||e.has(s))return;let i=await r.getCachedFile(s);if(i)return{dts:i,url:s};let o=t.get(s);if(o)return o;let a=(async()=>{let c=await Yr(s,{init:{cache:"no-store"}});if(!c?.ok){c?.status===404&&(e.set(s,!0),await r.recordNegative(s));return}let l=await c.text(),f=c.url||s;return await r.clearNegative(s),await r.setCachedFile(f,l),{dts:l,url:f}})();return t.set(s,a),await a.finally(()=>t.delete(s))}catch{return}}}var ls=class{constructor(e){this.inFlight=new Map,this.scanner=new Qo,this.cache=e.cache,this.cdnClient=e.cdnClient,this.versionResolver=e.versionResolver,this.packageService=e.packageService,this.fetchDts=Xy(e.cache),this.typescriptProvider=new Go(this.fetchDts,e.cdnClient),this.definitelyTypedProvider=new Xo(e.cdnClient,e.cache),this.virtualFs=new Zo}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()}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 fetchViaProviders(e){for(let t of[this.typescriptProvider,this.definitelyTypedProvider])try{let n=await t.resolve(e);if(n?.dts)return n}catch{}}async fetchRootDts(e,t){let{effectivePackage:n,root:s,pinned:i}=await this.versionResolver.effectivePackage(e,t),o=await this.cache.getCachedDts(n);if(o?.content){let c=o.url??this.cdnClient.file(i?`${s}@${i}`:s,"index.d.ts");return{dts:o.content,url:c,resolvedPkg:n}}let a;try{a=await this.fetchViaProviders(n)}catch{return}if(!(!a?.dts||!a.url)&&new j(n).subpath===new j(a.resolvedPkg||n).subpath){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,i=new Set,o){if(!i.has(t)&&(i.add(t),!(i.size>ot.maxRelativeTypeRefs)))try{let a=new URL(t),c=new URL("./",a);o??(o=this.extractPackageRootUrl(a));let l=this.scanner.collectRelativeTypeRefs(e).slice(0,ot.maxRelativeTypeRefs);for(let f of l)await this.tryRelativeRef(f,c,o,n,s,i)}catch{}}async tryRelativeRef(e,t,n,s,i,o){try{let a=new URL(e,t),c=a.pathname+a.search,l=Vo(c)?[c]:_t(c);for(let f of l){let d=new URL(f,a).toString();if(o.has(d))return;let p=await this.fetchDts(d);if(p?.dts){let h=this.toVirtualPath(n,new URL(p.url),s);this.pushFileIfNew(i,h,p.dts),await this.expandRelativeRefs(p.dts,p.url,s,i,o,n);return}}}catch{}}isDifferentPackage(e,t){return e===t?!1:new j(e).name!==new j(t).name}ambientlyDeclares(e,t){if(/^(?:import|export)\b/m.test(e))return!1;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,i){try{let o=this.scanner.collectBareModuleRefs(e).slice(0,ot.maxBareDeps).filter(l=>this.isDifferentPackage(l,t));if(!o.length)return;let a=new Set([t]),c=pO(ot.prefetchConcurrency);await Promise.all(o.map(l=>c(()=>this.prefetchBareDepsRecursive(l,n,s,ot.maxBareDepth,a,i).catch(()=>{}))))}catch{}}async prefetchBareDepsRecursive(e,t,n,s,i,o){if(s<=0||i.has(e))return;i.add(e);let a=await this.fetchRootDts(e,o);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 f=this.scanner.collectBareModuleRefs(a.dts).slice(0,ot.maxBareDeps).filter(u=>!i.has(u));for(let u of f)await this.prefetchBareDepsRecursive(u,t,n,s-1,i,o)}async resolve(e,t,n){let s=await this.packageService.extractImports(e),i=n?[...s,...n]:s;return(await Promise.all(i.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=new j(e),i=await this.fetchRootDts(e,t)??(s.subpath?await this.fetchRootDts(s.name,t):void 0);return i?this.buildDefFromContent(e,i,i.resolvedPkg||e,t):this.createStubDef(e)})}async buildDefFromContent(e,t,n,s){let{dts:i,url:o,resolvedPkg:a}=t,c=new j(a||n),l=c.version?`${c.name}@${c.version}`:c.name,{mainPath:f,packageRootUrl:u}=this.computeEntryPath(o,l),d=[{path:f,content:i}],p=[];o&&await this.expandRelativeRefs(i,o,l,d,void 0,u);let h=d.map(w=>w.content).join(`
|
|
1635
|
+
`);await this.prefetchBareDeps(h,l,d,p,s);let m=c.format(),b=e===m?[e]:[e,m],A=b.some(w=>this.ambientlyDeclares(i,w));return A?this.markFileAmbient(d,f):p.push(...b.map(w=>({module:w,path:f}))),{pkg:e,mainPath:f,files:d,shims:p,ambient:A}}};Sl();Qe();xr();Un();wl();kr();import*as Vr from"path";var mO=Vr.join(Oi,"pkg"),hO=Vr.join(Oi,"files"),gO=Vr.join(Oi,"negative.json"),ta=class{pkgMem=new Map;fileMem=new Map;negativeCache=new Kt(new Er(gO));async getCachedDts(e){if(this.pkgMem.has(e))return this.pkgMem.get(e);await Z();let t=await Ze(Qy(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 ea(async()=>{await Z(),await xe(Qy(e),JSON.stringify(s))})}async getCachedFile(e){if(this.fileMem.has(e))return this.fileMem.get(e);await Z();let t=await Pi(Zy(e));return this.fileMem.set(e,t),t}async setCachedFile(e,t){this.fileMem.set(e,t),await ea(async()=>{await Z(),await xe(Zy(e),t)})}isNegative(e){return this.negativeCache.isNegative(e)}async recordNegative(e){await ea(async()=>{await Z(),await this.negativeCache.recordNegative(e)})}clearNegative(e){return ea(()=>this.negativeCache.clearNegative(e))}};async function ea(r){try{await r()}catch{}}function Qy(r){return Vr.join(mO,_e(r)+".json")}function Zy(r){return Vr.join(hO,_e(r)+".txt")}xr();var Hu;function yO(){return Hu||(Hu=new ls({cache:new ta,cdnClient:ih,packageService:Ni,versionResolver:sh})),Hu}var eb="file:///node_modules/";async function tb(r){let e=Ri(r.emitKey,"typecheck");await Z(),await fe.rm(e,{recursive:!0,force:!0}),await fe.mkdir(e,{recursive:!0});let t=SO(r.jsxImportSource,r.dependencies),n=await yO().resolve(r.code,r.dependencies,t),s=r.local?.name,i=s?n.filter(f=>f.pkg!==s):n,o=new Set;for(let f of i)for(let u of f.files){let d=ra(u.path);if(!d||o.has(d))continue;o.add(d);let p=ue.join(e,"node_modules",d);await fe.mkdir(ue.dirname(p),{recursive:!0}),await fe.writeFile(p,u.content,"utf8")}let a={};for(let f of i)for(let u of f.shims){let d=ra(u.path);d&&(a[u.module]=[`./node_modules/${d}`])}for(let f of i){if(f.ambient)continue;let u=ra(f.mainPath);u&&(a[f.pkg]=[`./node_modules/${u}`])}let c=new Set;for(let f of i)for(let u of f.files){if(!u.ambient)continue;let d=ra(u.path);d&&c.add(`node_modules/${d}`)}if(r.local){delete a[r.local.name];let f=await kO(r.local,e);f?a[r.local.name]=[`./node_modules/${r.local.name}/${f}`]:console.warn(` local: '${r.local.name}' ships no type defs; check cannot type against it.`)}let l=bO(r.jsxImportSource,a,[...c]);return await fe.writeFile(ue.join(e,"tsconfig.json"),JSON.stringify(l,null,2)+`
|
|
1636
|
+
`,"utf8"),await fe.writeFile(ue.join(e,"code.tsx"),r.code,"utf8"),await fe.writeFile(ue.join(e,"tb.d.ts"),Uu,"utf8"),{dir:e}}var Wu={target:"es2023",module:"esnext",moduleResolution:"bundler",strict:!0,noEmit:!0,skipLibCheck:!0,esModuleInterop:!0,allowSyntheticDefaultImports:!0,forceConsistentCasingInFileNames:!0};function bO(r,e,t=[]){return{compilerOptions:{...Wu,lib:wO([...ju,...Fu]),jsx:"react-jsx",jsxImportSource:r??"react",paths:e},include:["code.tsx","tb.d.ts",...t]}}function wO(r){return qu(r).map(e=>vO(e.name))}function vO(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 SO(r,e){let t=r??("react"in e?"react":void 0);return t?[`${t}/jsx-runtime`,`${t}/jsx-dev-runtime`]:[]}function ra(r){if(!r.startsWith(eb))return;let e=r.slice(eb.length),t=e.indexOf("/");if(!(t<0))return e.slice(t+1)}async function kO(r,e){if(!r.typesAbs)return;let t=ue.dirname(r.typesAbs),n=ue.join(e,"node_modules",r.name);for(let s of await xO(t)){let i=ue.join(n,ue.relative(t,s));await fe.mkdir(ue.dirname(i),{recursive:!0}),await fe.copyFile(s,i)}return ue.basename(r.typesAbs)}async function xO(r){let e=[];async function t(n){let s=await fe.readdir(n,{withFileTypes:!0});for(let i of s){let o=ue.join(n,i.name);i.isDirectory()?await t(o):/\.d\.ts(\.map)?$/.test(i.name)&&e.push(o)}}return await t(r),e}import*as Pe from"fs/promises";import*as at from"path";import{existsSync as EO}from"fs";xr();kl();var AO="^22";async function rb(r){let e=Ri(r.emitKey,"typecheck-server");await Z(),await Pe.rm(e,{recursive:!0,force:!0}),await Pe.mkdir(e,{recursive:!0});let t=at.join(r.bulbDir,".typebulb"),n=qi(r.server).filter(o=>o!==r.local?.name);await Fi([`@types/node@${AO}`,...n],t,r.dependencies,{ignoreScripts:!0});let s=at.join(t,"node_modules"),i=at.join(e,"node_modules");return await PO(s,i),await Pe.writeFile(at.join(e,"server.ts"),r.server,"utf8"),await Pe.writeFile(at.join(e,"tb.d.ts"),Ju,"utf8"),await Pe.writeFile(at.join(e,"tsconfig.json"),JSON.stringify(TO(r.local),null,2)+`
|
|
1637
|
+
`,"utf8"),{dir:e}}function TO(r){let e={...Wu,lib:["ES2023"],types:["node"]};if(r?.typesAbs){let t=i=>i.replace(/\\/g,"/"),n=t(at.dirname(r.typesAbs)),s=t(r.typesAbs).replace(/\.d\.ts$/,"");e.paths={[r.name]:[s],[`${r.name}/*`]:[`${n}/*`]}}return{compilerOptions:e,include:["server.ts","tb.d.ts"]}}async function PO(r,e){if(!EO(r)){await Pe.mkdir(e,{recursive:!0});return}await Pe.rm(e,{recursive:!0,force:!0});let t=process.platform==="win32"?"junction":"dir";await Pe.symlink(r,e,t)}xi();async function sb(r,e){let{bulb:t,config:n,warnings:s,starts:i}=await Le(r),o=Ge.basename(r),a=d=>i.get(d)??1;!t.code&&!t.server&&(console.error("Bulb has neither **code.tsx** nor **server.ts**; nothing to check."),process.exit(1));let c=!1;for(let d of s)console.log(`structure ${d}`);s.length&&(c=!0),t.code&&(c=nb(Nn(t.code,{target:"client",dependencies:n.dependencies??{},lineOffset:a("code.tsx")}),"client")||c),t.server&&(c=nb(Nn(t.server,{target:"server",lineOffset:a("server.ts")}),"server")||c);let l=LO([process.cwd(),Ge.dirname(r)]);if(!l){let d=Ge.relative(process.cwd(),r)||r;console.error("check: TypeScript not found \u2014 install it once, then re-run:"),console.error(" npm i -g typescript"),console.error(` typebulb check ${d}`),process.exit(2)}let f=[];if(t.code){let{dir:d}=await tb({code:t.code,dependencies:n.dependencies??{},jsxImportSource:n.ts?.jsxImportSource,emitKey:r,local:e});f.push({role:"client",dir:d})}if(t.server){let{dir:d}=await rb({server:t.server,bulbDir:Ge.dirname(r),emitKey:r,local:e?{name:e.name,typesAbs:e.typesAbs}:void 0,dependencies:n.dependencies});f.push({role:"server",dir:d})}for(let{role:d,dir:p}of f){let{stdout:h,exitCode:m}=await IO(l,p);for(let b of h.split(/\r?\n/))b.trim()&&console.log(`${d} ${NO(b,o,a)}`);m!==0&&(c=!0)}c&&process.exit(1);let u=[t.code&&"code.tsx",t.server&&"server.ts"].filter(Boolean).join(", ");console.error(`\u2713 no issues (${u})`)}function nb(r,e){for(let t of r)for(let n of t.message.split(`
|
|
1638
|
+
`))console.log(`${e} ${n}`);return r.length>0}function NO(r,e,t){return r.replace(/\b(code\.tsx|server\.ts)\((\d+),(\d+)\)/g,(n,s,i,o)=>`${e}(${Number(i)+t(s)-1},${o})`)}function IO(r,e){return new Promise(t=>{let n=OO(process.execPath,[r,"--noEmit"],{cwd:e}),s="";n.stdout?.on("data",i=>{s+=i.toString()}),n.stderr?.on("data",i=>{s+=i.toString()}),n.on("close",i=>t({stdout:s,exitCode:i??1}))})}var $O=CO(import.meta.url);function LO(r){let e=n=>{try{let s=$O.resolve("typescript/package.json",{paths:n}),i=Ge.join(Ge.dirname(s),"lib","tsc.js");return _O(i)?i:void 0}catch{return}},t=e(r);if(t)return t;try{let n=RO("npm root -g",{encoding:"utf8"}).trim();return e([n])}catch{return}}qe();bo();Gn();async function ib(r,e){let{bulb:t}=await Le(r),n=Dr(t);if(zt(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.)")}Gn();import*as us from"path";async function ob(r,e){if(!r){e||(console.error("Usage: typebulb untrust <file.bulb.md>"),process.exit(1));let n=Jl();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=us.resolve(r);t.endsWith(".bulb.md")||(console.error("File must have .bulb.md extension"),process.exit(1)),$r(t,e),console.log(e?`Trusted ${us.basename(t)} \u2014 runs with fs / AI / server.ts (no --trust needed).`:`Untrusted ${us.basename(t)} \u2014 runs Restricted.`),console.log(` ${t}`)}Be();import*as ub from"readline";var ds=jy();function ab(){for(let r of Object.values(ds))try{r().ensureHarnessSupport()}catch{}}function fs(){for(let r of Object.keys(ds))try{if(ds[r]().detectsSelf())return r}catch{}}function cb(r){let e=Wr(),t=new Map(e.filter(i=>ds[i]).map(i=>[i,ds[i]()]));for(let[i,o]of t)if(o.detectsSelf())return{name:i};let n=[...t].filter(([,i])=>i.detectsInstalled()).map(([i])=>i);if(n.length===0)return{name:e[0]};if(n.length===1)return{name:n[0]};let s=i=>t.get(i).listSessionFiles(r).length>0;return{ambiguous:[...n].sort((i,o)=>Number(s(o))-Number(s(i)))}}wo();function Yu(r){let e=t=>n=>r?`\x1B[${t}m${n}\x1B[0m`:n;return{lit:e("38;5;70"),litLink:e("4;38;5;70"),brand:e("38;5;135")}}async function db(r){let e=cb(process.cwd());if("ambiguous"in e){let t=await MO(r,e.ambiguous);return t?lb(r,t):BO(r,e.ambiguous)}return lb(r,e.name)}async function lb(r,e){let t,n;try{t=await Jh(e)}catch(f){n=f instanceof Error?f.message:String(f)}let{lit:s,litLink:i,brand:o}=Yu(process.stdout.isTTY===!0),a=[" Read the authoring skill before writing a bulb:",` \u2022 ${s("npx typebulb skill")} \u2014 assembles one SKILL.md`," \u2022 or, open its parts:",` ${s(jr())}`,` ${s(er())}`],c=t?[` Agent mirror (${e}) is live\u{1F4A1}`,` ${s("\u25CF")} ${i(t.url)}`," Embedded bulbs render live here."," Agents:",` Reusable app/tool \u2192 write a ${s(".bulb.md")}`," Show something inline \u2192 embed a bulb",e==="pi"?" arm a wait for its render verdict \u2014 run it plainly:":" background a wait for its render verdict:",` \u2022 ${s('typebulb wait agent --match "[embed <name>"')}`,...a," End your reply with the mirror link above"," \u2022 easy to miss the link mid-message"]:[` The mirror did not start (${n})`,` \u25CF Start it manually: ${s(`npx typebulb agent:${e}`)}`," Agents:",...a],l=[` ${o(`typebulb v${r}`)}`,...c,""];process.stdout.write(l.join(`
|
|
1632
1639
|
`)+`
|
|
1633
|
-
`)}async function
|
|
1640
|
+
`)}async function MO(r,e){if(!process.stdin.isTTY||!process.stdout.isTTY)return;let{lit:t,brand:n}=Yu(!0),s=[` ${n(`typebulb v${r}`)}`," More than one agent harness is available here.",...e.map((o,a)=>` ${t(String(a+1))}) ${o}`),""];process.stdout.write(s.join(`
|
|
1634
1641
|
`)+`
|
|
1635
|
-
`);let i=ub.createInterface({input:process.stdin,output:process.stdout});try{let o=(await new Promise(c=>i.question(" Open which? [1]: ",c))).trim();if(o==="")return e[0];let a=Number(o);return Number.isInteger(a)&&a>=1&&a<=e.length?e[a-1]:e.find(c=>c===o.toLowerCase())}finally{i.close()}}function
|
|
1642
|
+
`);let i=ub.createInterface({input:process.stdin,output:process.stdout});try{let o=(await new Promise(c=>i.question(" Open which? [1]: ",c))).trim();if(o==="")return e[0];let a=Number(o);return Number.isInteger(a)&&a>=1&&a<=e.length?e[a-1]:e.find(c=>c===o.toLowerCase())}finally{i.close()}}function BO(r,e){let{lit:t,brand:n}=Yu(process.stdout.isTTY===!0),s=[` ${n(`typebulb v${r}`)}`," More than one agent harness is available here."," Open the mirror for the one you want:",...e.map(i=>` \u2022 ${t(`npx typebulb agent:${i}`)}`),""];process.stdout.write(s.join(`
|
|
1636
1643
|
`)+`
|
|
1637
|
-
`)}Pt();Gt();async function fb(r){Ae(r);let e=await tt();if(e.length>0){console.log(vh(e,process.env.TB_AI_PROVIDER,process.env.TB_AI_MODEL));return}if(!Bl()){console.log("No AI provider keys found in this directory's .env, and no local Ollama server detected."),console.log("Set one of these to use a cloud model with tb.ai:");for(let[t,n]of Object.entries(Rr))console.log(` ${n.padEnd(20)} (${t})`);console.log("\u2026or start Ollama (http://localhost:11434, or set OLLAMA_HOST) for local models. Then re-run `typebulb models`.");return}console.log("Couldn't fetch the model catalog (offline?). tb.ai still works with any valid provider/model id for your keys.")}wo();import*as pb from"fs/promises";async function mb(r){let e=er(),t;try{t=await pb.readFile(e,"utf8")}catch{console.error(`Could not read the bundled README (expected at ${e}).`),process.exit(1)}process.stdout.write(ag(t,r))}Vn();import*as hb from"path";Be();function
|
|
1638
|
-
`+e)}function Gu(r,e,t,n,s){let i=
|
|
1644
|
+
`)}Pt();Gt();async function fb(r){Ae(r);let e=await tt();if(e.length>0){console.log(vh(e,process.env.TB_AI_PROVIDER,process.env.TB_AI_MODEL));return}if(!Bl()){console.log("No AI provider keys found in this directory's .env, and no local Ollama server detected."),console.log("Set one of these to use a cloud model with tb.ai:");for(let[t,n]of Object.entries(Rr))console.log(` ${n.padEnd(20)} (${t})`);console.log("\u2026or start Ollama (http://localhost:11434, or set OLLAMA_HOST) for local models. Then re-run `typebulb models`.");return}console.log("Couldn't fetch the model catalog (offline?). tb.ai still works with any valid provider/model id for your keys.")}wo();import*as pb from"fs/promises";async function mb(r){let e=er(),t;try{t=await pb.readFile(e,"utf8")}catch{console.error(`Could not read the bundled README (expected at ${e}).`),process.exit(1)}process.stdout.write(ag(t,r))}Vn();import*as hb from"path";Be();function DO(r,e,t,n){if(/^\d+$/.test(e))return r.find(i=>i.pid===parseInt(e,10));let s=e==="agent"?r.filter(i=>i.agent!=null):r.filter(i=>i.agent===e);if(s.length){if(!t)return s[0];let i=s.filter(o=>o.cwd&&X(o.cwd)===X(t));return n&&i.find(o=>o.agent===n)||i[0]}return r.find(i=>X(i.file)===X(e))}var ps=r=>r.agent??hb.basename(r.file);function gb(r,e){for(let t of r)e(` ${t.url} pid ${t.pid} ${t.trust?"trusted":"restricted"}${t.batch?` --batch ${t.batch}`:""} ${t.file}`)}function Vu(r,e){if(!r.length){console.log("No running bulb servers.");return}console.log("Running bulb servers:"),gb(r,t=>console.log(t)),console.log(`
|
|
1645
|
+
`+e)}function Gu(r,e,t,n,s){let i=DO(r,e,n,s);if(i)return i;console.error(`No running server for '${e}'.`),r.length?(console.error(`Running servers (try \`typebulb ${t} <file|pid>\`):`),gb(r,o=>console.error(o))):console.error("No bulb servers are running."),process.exit(1)}async function yb(r,e){if(!r){e.clear&&(console.error("Specify which server to clear: typebulb logs --clear <file|pid>"),process.exit(1)),Vu(await Q(process.cwd()),"Run `typebulb logs <file|pid>` to print one server's console.");return}let t=Gu(await Q(),r,"logs",process.cwd(),fs());if(e.clear){Bh(t.pid),console.log(`Cleared log for ${ps(t)} (pid ${t.pid}).`);return}let n=Je(t.pid),s=n.text;if(e.run!==void 0&&(s=Dh(s,e.run),!s&&e.run!=="latest"&&console.error(`No output for run ${e.run} (it hasn't started, or was trimmed from the log).`)),e.lines&&e.lines>0){let i=s.split(`
|
|
1639
1646
|
`);i.length&&i[i.length-1]===""&&i.pop(),s=i.slice(-e.lines).join(`
|
|
1640
1647
|
`)}if(process.stdout.write(s),s&&!s.endsWith(`
|
|
1641
1648
|
`)&&process.stdout.write(`
|
|
1642
|
-
`),e.follow&&e.run===void 0){let i=n.offset,o=setInterval(()=>{let c=Je(t.pid,i);i=c.offset,c.text&&process.stdout.write(c.text)},500),a=()=>{clearInterval(o),process.exit(0)};process.on("SIGINT",a),process.on("SIGTERM",a),await new Promise(()=>{})}}var
|
|
1643
|
-
`);m=w.pop()??"";for(let P of w)P.trim()&&(e.match&&!P.includes(e.match)||(console.log(P),h??=Date.now()+d,n&&(P.includes("] compile error")||P.includes("] runtime error"))&&(h=Math.min(h,Date.now()+p))))}if(h&&Date.now()>=h)break;if(!i&&!h&&Date.now()>=u){console.error(`timeout: no ${e.match?`line matching '${e.match}'`:"new output"} from ${ps(t)} within ${o}s`),b=2;break}if(!ru(t.pid)){h||(console.error(`server ${ps(t)} (pid ${t.pid}) exited while waiting`),process.exit(3));break}await
|
|
1649
|
+
`),e.follow&&e.run===void 0){let i=n.offset,o=setInterval(()=>{let c=Je(t.pid,i);i=c.offset,c.text&&process.stdout.write(c.text)},500),a=()=>{clearInterval(o),process.exit(0)};process.on("SIGINT",a),process.on("SIGTERM",a),await new Promise(()=>{})}}var jO=r=>new Promise(e=>setTimeout(e,r));async function bb(r,e){if(!r){Vu(await Q(process.cwd()),"Run `typebulb wait <file|pid>` to block until one logs a new line.");return}let t=Gu(await Q(),r,"wait",process.cwd(),fs()),n=t.agent!=null,i=process.env.TYPEBULB_WAIT_SHIM==="1",o=e.timeoutSec??1800,a=e.match??"",c=Je(t.pid).offset,l=eu(t.pid,a)??(a?eu(t.pid):void 0),f=l!==void 0&&l<=c?l:a?0:c,u=Date.now()+o*1e3,d=n?1e4:1e3,p=2e3,h,m="",b=0;for(;;){let A=Je(t.pid,f);if(f=A.offset,A.text){m+=A.text;let w=m.split(`
|
|
1650
|
+
`);m=w.pop()??"";for(let P of w)P.trim()&&(e.match&&!P.includes(e.match)||(console.log(P),h??=Date.now()+d,n&&(P.includes("] compile error")||P.includes("] runtime error"))&&(h=Math.min(h,Date.now()+p))))}if(h&&Date.now()>=h)break;if(!i&&!h&&Date.now()>=u){console.error(`timeout: no ${e.match?`line matching '${e.match}'`:"new output"} from ${ps(t)} within ${o}s`),b=2;break}if(!ru(t.pid)){h||(console.error(`server ${ps(t)} (pid ${t.pid}) exited while waiting`),process.exit(3));break}await jO(400)}oo(t.pid,f,a),process.exit(b)}async function wb(r){if(!r){Vu(await Q(process.cwd()),"Run `typebulb stop <file|pid>` to stop one.");return}let e=Gu(await Q(),r,"stop",process.cwd(),fs());await Xt(e.pid),console.log(`Stopped ${ps(e)} (pid ${e.pid}, ${e.url}).`)}async function vb(r){let e=process.cwd(),t=r==="agent"?fs():void 0,n=r==="global"?await Q():r==="bulbs"?await Q(e):(await Q()).filter(i=>i.agent!=null&&i.cwd!=null&&X(i.cwd)===X(e)&&(!t||i.agent===t)),s=r==="global"?"server":r==="agent"?"mirror":"bulb";if(!n.length){console.log(r==="global"?"No running bulb servers.":`No running ${s}s for this project.`);return}await Promise.all(n.map(i=>Xt(i.pid))),console.log(`Stopped ${n.length} ${s}${n.length===1?"":"s"}:`);for(let i of n)console.log(` ${i.url} pid ${i.pid} ${ps(i)}`)}Be();import*as Sb from"path";import*as kb from"http";function FO(r,e){return new Promise((t,n)=>{let s=new URL(r),i=kb.request({hostname:s.hostname,port:s.port,path:s.pathname+s.search,method:"POST",headers:{"Content-Type":"text/plain","Content-Length":Buffer.byteLength(e)}},o=>{let a="";o.setEncoding("utf8"),o.on("data",c=>{a+=c}),o.on("end",()=>t({status:o.statusCode??0,text:a}))});i.setTimeout(0),i.on("error",n),i.end(e)})}async function xb(r,e,t=0){let n=e!==void 0&&e.startsWith("tb:");n&&t<=0&&(t=al);let s=Sb.resolve(r),i=Br(await Q(),s)[0];i||(console.error(`No running server for '${r}'. Start it first: npx typebulb ${r}`),process.exit(1));let o=async d=>{let p=await FO(`${i.url}/__send${d>0?`?reply=${d}`:""}`,e??"");(p.status<200||p.status>=300)&&(console.error(`send failed: HTTP ${p.status} from ${i.url}/__send`),process.exit(1));try{return JSON.parse(p.text)}catch{return{}}},a={};try{let d=Date.now()+t;do{if(a=await o(t>0?Math.max(d-Date.now(),1e3):0),(a.clients??0)>0||Date.now()>=d)break;await new Promise(p=>setTimeout(p,150))}while(!0)}catch(d){console.error(`send failed: ${d instanceof Error?d.message:String(d)}`),process.exit(1)}let c=a.clients??0,l=`${c} page${c===1?"":"s"}`;if(c===0){let d=a.droppedMsAgo,p=d!==void 0?` \u2014 a page disconnected ${Math.round(d/1e3)}s ago and hasn't reconnected; reload it, or open ${i.url}`:` \u2014 no page has ever connected; open ${i.url}`;t>0?console.error(`No page connected after ${t/1e3}s${p}`):console.error(`Sent, but no page is connected${p}`),n&&process.exit(1);return}console.error(`Sent to ${l}.`);let f=a.results??[],u=a.errors??[];for(let d of u)console.error(`handler error: ${d}`);if(u.length&&process.exit(1),f.length>1&&(console.error(`${f.length} replies from ${l} \u2014 one reply owns stdout: at most one tb.onMessage handler, in one page, may return a value.`),process.exit(1)),f.length===1){let d;try{d=JSON.parse(f[0])}catch{d=void 0}console.log(typeof d=="string"?d:f[0])}else a.timedOut&&(n&&(console.error(`No reply to '${e}' within ${t/1e3}s \u2014 reload the page and retry.`),process.exit(1)),console.error(`(no reply within ${t/1e3}s \u2014 a slow handler's return needs a larger --wait=ms)`))}Ao();wu();be();import*as Eb from"fs/promises";async function Ab(r,e){let t=await Eb.readFile(r,"utf-8"),n=le(t);n||(console.error(`Not a valid bulb: ${r}`),process.exit(1));let s=ae[e].path,i=n.files.get(s);i||(console.error(i===void 0?`No **${s}** block in ${r}`:`The **${s}** block in ${r} is empty`),process.exit(2)),process.stdout.write(i.endsWith(`
|
|
1644
1651
|
`)?i:i+`
|
|
1645
|
-
`)}be();import*as ms from"fs/promises";async function Ob(r,e){let t=await ms.readFile(r,"utf-8"),n=[];for(let{kind:i,source:o}of e){let a;try{a=o==="-"?await
|
|
1646
|
-
`).trimEnd()}function Tb(r,e,t){if(r===e)throw new Error(`the **${t}** block's fence is unterminated; refusing to rewrite inside it`);return r}function Pb(r){console.error(r),process.exit(1)}async function
|
|
1652
|
+
`)}be();import*as ms from"fs/promises";async function Ob(r,e){let t=await ms.readFile(r,"utf-8"),n=[];for(let{kind:i,source:o}of e){let a;try{a=o==="-"?await UO():await ms.readFile(o,"utf-8")}catch(c){Pb(`Cannot read ${i}'s source: ${c instanceof Error?c.message:String(c)}`)}n.push({kind:i,content:Rb(a),label:o==="-"?"stdin":o})}let s;try{s=qO(t,n)}catch(i){Pb(`${r}: ${i instanceof Error?i.message:String(i)}`)}for(let i of s.upToDate)console.log(`${ae[i].path}: already up to date`);if(s.written.length){await ms.writeFile(r,s.text);for(let i of s.written)console.log(i.action==="removed"?`${ae[i.kind].path}: removed (${i.label} is empty)`:`${ae[i.kind].path}: ${i.action} from ${i.label} (${i.chars.toLocaleString()} chars)`)}}function qO(r,e){let t=le(r);if(!t)throw new Error("not a valid bulb");let n=r,s=[],i=[];for(let{kind:o,content:a,label:c}of e){let l=ae[o].path,f=t.files.get(l);if(!a){if(f===void 0){i.push(o);continue}n=Tb(Ad(n,o),n,l),s.push({kind:o,action:"removed",chars:0,label:c});continue}if(f!==void 0&&Rb(f)===a){i.push(o);continue}n=Tb(Gr(n,o,a),n,l),s.push({kind:o,action:f===void 0?"created":"replaced",chars:a.length,label:c})}return{text:n,written:s,upToDate:i}}function Rb(r){return(r.charCodeAt(0)===65279?r.slice(1):r).replace(/\r\n/g,`
|
|
1653
|
+
`).trimEnd()}function Tb(r,e,t){if(r===e)throw new Error(`the **${t}** block's fence is unterminated; refusing to rewrite inside it`);return r}function Pb(r){console.error(r),process.exit(1)}async function UO(){let r=[];for await(let e of process.stdin)r.push(e);return Buffer.concat(r).toString("utf-8")}Pt();qe();be();bo();import*as It from"fs/promises";import*as la from"path";import{EventEmitter as Lb}from"events";import iR from"open";Or();be();import{Hono as VO}from"hono";import{serve as GO}from"@hono/node-server";import{streamSSE as zO}from"hono/streaming";import*as Zu from"fs/promises";xr();Un();kr();import*as zu from"fs/promises";import*as hs from"path";var na=class{async get(e){let t=_e(e),n=hs.join(qn,t+".bin"),s=hs.join(qn,t+".json");try{let[i,o]=await Promise.all([zu.readFile(n),zu.readFile(s,"utf8")]),a=JSON.parse(o);return{body:i,contentType:a.contentType,cacheControl:a.cacheControl}}catch{return}}async set(e,t){await Z();let n=_e(e),s=hs.join(qn,n+".bin"),i=hs.join(qn,n+".json"),o={url:e,contentType:t.contentType,cacheControl:t.cacheControl};await Promise.all([xe(s,t.body),xe(i,JSON.stringify(o))])}};var Cb=`
|
|
1647
1654
|
const CSS = '\\n' +
|
|
1648
1655
|
/* The agent mirror's token set, verbatim (agents/core/client/styles.css) \u2014 one system across CLI
|
|
1649
1656
|
chrome: app chrome sits on --panel, content wells paint --veil, grays ride one neutral tint.
|
|
@@ -1947,18 +1954,18 @@ export function runInference(ctx) {
|
|
|
1947
1954
|
showConfirm();
|
|
1948
1955
|
document.body.appendChild(host);
|
|
1949
1956
|
}
|
|
1950
|
-
`;Be();Gt();zi();Or();import{stream as
|
|
1951
|
-
${d}`:"";return y.text(`Forbidden: this capability requires --trust.${B}`,403)}await x()},R=async(y,x)=>{let N=y.req.header("sec-fetch-site");if(N){if(N!=="same-origin")return y.text(`Forbidden: ${N} request`,403)}else{let L=y.req.header("origin");if(L&&!
|
|
1952
|
-
`+te.slice(-4e3)),new we("LLM output is not valid JSON","parse_error",!0);ie.fixesApplied.length&&console.warn("[tb.infer] sanitized output, fixes applied:",ie.fixesApplied.join(", "));let Se={insight:ie.parsed,insightJson:ie.json,data:B};yield{kind:"complete",...Se,fixesApplied:ie.fixesApplied,hash:$l(Se)}})();return sa(y,pe)}catch(x){return y.json(gs(x),500)}});let $=async y=>{let{hash:x}=await y.req.json().catch(()=>({}));return typeof x=="string"?Ll(x):null};w.post("/__infer-save",async y=>{try{if(!l)return y.json({message:"Save is not available for this server.",code:"unknown",retryable:!1},400);let x=await $(y);return x?(await l(x.data,x.insightJson),y.json({ok:!0})):y.json({message:"No decodable #tb= fragment to save.",code:"unknown",retryable:!1},400)}catch(x){return y.json(gs(x),500)}}),w.get("/__infer-info",y=>{let x=c?.(),N=zr(x?.config??"").inference,L=Si(x?.data??""),B=rt();return typeof B=="string"?y.json({error:B,inference:N,data:L}):y.json({provider:B.protocol,model:B.model,inference:N,data:L})}),w.use("/__infer-decode",R),w.post("/__infer-decode",async y=>y.json(await $(y)??{error:"invalid fragment"})),w.get("/__infer-ui.js",y=>y.body(Cb,200,{"Content-Type":"text/javascript; charset=utf-8"})),w.get("/__models",async y=>{try{let x=await tt();return y.json(x)}catch{return y.json([],200)}}),w.get("/__has-own-keys",async y=>{try{return y.json(await Gi())}catch{return y.json(!1,200)}}),m&&w.get("/__source/*",async y=>{let x=await Zu.readFile(m,"utf-8").catch(()=>{});return x===void 0?y.text("Not Found",404):new Response(x,{headers:{"Content-Type":"text/plain; charset=utf-8"}})});let E=["esm.sh","unpkg.com","cdn.jsdelivr.net","cdnjs.cloudflare.com"],M=new na;w.get("/proxy/*",async y=>{let x=new URL(y.req.url),L=(x.pathname+x.search).slice(7),B=L.lastIndexOf("https://");return B===-1?y.text("Invalid proxy URL",400):H(y,L.slice(B))}),f&&Nb(w,`/local/${f.name}/`,f.serveDir),p&&Nb(w,p.mount,p.dir),h&&w.get("/assets/*",async y=>{let{pathname:x}=new URL(y.req.url),N=x.slice(8),L;try{L=decodeURIComponent(N)}catch{return y.text("Not Found",404)}let B=Rd(L);if(B)return y.text(`${B} is not an asset type: a bulb's code and markup live in the bulb; assets are media and data`,403);try{for(let z of h.dirs){let pe=await $b(L,z,{"Cache-Control":"no-cache"});if(pe)return pe}}catch{return y.text("Not Found",404)}let W=h.remoteBase;return W?y.redirect(W+N,302):y.text("Not Found",404)});async function H(y,x){let N;try{N=new URL(x)}catch{return y.text("Invalid URL",400)}if(N.protocol!=="https:")return y.text("HTTPS only",400);if(!E.includes(N.hostname))return y.text("Host not allowed",403);let L=await M.get(x);if(L)return new Response(L.body,{status:200,headers:Qu(L.contentType,L.cacheControl)});try{let B=await fetch(x,{headers:{Accept:y.req.header("Accept")||"*/*"},redirect:"follow"});if(!B.ok)return y.text(`Upstream ${B.status}`,B.status);let W=B.headers.get("Content-Type")||void 0,z=B.headers.get("Cache-Control")||void 0;if(B.body){let[pe,te]=B.body.tee();return(async()=>{try{let ie=await new Response(te).arrayBuffer();await M.set(x,{body:Buffer.from(ie),contentType:W,cacheControl:z})}catch{}})(),new Response(pe,{status:B.status,headers:Qu(W,z)})}return new Response(null,{status:B.status,headers:Qu(W,z)})}catch(B){return y.text(`Proxy fetch failed: ${B instanceof Error?B.message:B}`,502)}}(i||o)&&w.get("/__reload",y=>
|
|
1957
|
+
`;Be();Gt();zi();Or();import{stream as JO}from"hono/streaming";var KO="X-TB-Stream";function gs(r){return r instanceof we?{message:r.message,code:r.code,retryable:r.retryable}:{message:r instanceof Error?r.message:"Unknown error",code:"unknown",retryable:!1}}function sa(r,e){return r.header("Content-Type","application/x-ndjson; charset=utf-8"),r.header("Cache-Control","no-cache"),r.header(KO,"1"),JO(r,async t=>{let n=e[Symbol.asyncIterator]();t.onAbort(()=>{n.return?.()});try{for(;;){let{done:s,value:i}=await n.next();if(s)break;await t.writeln(JSON.stringify({type:"chunk",value:i}))}}catch(s){await t.writeln(JSON.stringify({type:"error",error:gs(s)}))}finally{try{await n.return?.()}catch{}}})}var ia={log:(...r)=>console.log(...r)};function oa(r,e){let t=r?.[e]??(Object.hasOwn(ia,e)?ia[e]:void 0);return typeof t=="function"?t:void 0}function aa(r){return r.constructor?.name==="AsyncGeneratorFunction"}Dl();var HO=/^\/(v\d+\/|stable\/|node\/|gh\/|@[^/]+\/[^@/]+@|[^@/]+@)/,WO=/[?&]target=/,YO=/^\/(?:@[^/]+\/)?[^/@]+\/[^/]+/;function _b(r,e=""){return HO.test(r)?!0:YO.test(r)&&WO.test(e)}var XO="127.0.0.1",QO=new Set(["localhost","127.0.0.1","::1"]),ZO=0;function eR(r){if(r)try{return new URL(r.includes("://")?r:`http://${r}`).hostname}catch{return}}function tR(r){let e=eR(r);return!!e&&QO.has(e)}function rR(r,e){if(!e)return!1;try{return new URL(r).host===e}catch{return!1}}function Xu(r){return r instanceof Error?r.message:"Unknown error"}async function Ib(r){let{getHtml:e,basePath:t,fsBase:n,port:s,reloadEmitter:i,messageEmitter:o,getServerExports:a,getBulbBlocks:c,saveInferenceResult:l,localOverride:f,trusted:u=!1,trustHint:d,staticAssets:p,bulbAssets:h,sourceFile:m}=r,b=`${process.pid}-${++ZO}-${Date.now()}`,A=n??t,w=new VO;w.use("*",async(y,x)=>{if(!tR(y.req.header("host")))return y.text("Forbidden: untrusted Host",403);await x()}),w.use("*",async(y,x)=>{await x(),y.res.headers.set("Cross-Origin-Opener-Policy","same-origin"),y.res.headers.set("Cross-Origin-Embedder-Policy","credentialless")});let P=[["/__fs/*","the filesystem"],["/__api/*","server-side code (server.ts)"],["/__ai","AI (your API keys)"],["/__infer","AI (your API keys)"],["/__infer-save","the filesystem"]],C=async(y,x)=>{if(!u){let N=new URL(y.req.url).pathname,L=P.find(([W])=>W.endsWith("/*")?N.startsWith(W.slice(0,-2)):N===W)?.[1]??"server-side code (server.ts)";Fh(process.pid,L);let B=d?`
|
|
1958
|
+
${d}`:"";return y.text(`Forbidden: this capability requires --trust.${B}`,403)}await x()},R=async(y,x)=>{let N=y.req.header("sec-fetch-site");if(N){if(N!=="same-origin")return y.text(`Forbidden: ${N} request`,403)}else{let L=y.req.header("origin");if(L&&!rR(L,y.req.header("host")))return y.text("Forbidden: cross-origin request",403)}await x()};for(let[y]of P)w.use(y,C),w.use(y,R);w.use("/__log",R),w.post("/__log",async y=>{try{let{args:x}=await y.req.json();console.log(...x||[])}catch{}return y.json({ok:!0})});let _=0;if(o){let y=0,x=new Map;w.use("/__send",R),w.post("/__send",async N=>{let L="";try{L=await N.req.text()}catch{}let B=Number(N.req.query("reply"))||0,W=o.listenerCount("message"),z=W===0&&_?Date.now()-_:void 0;if(B<=0||W===0)return o.emit("message",{payload:L}),N.json({clients:W,droppedMsAgo:z});let pe=++y,te=await new Promise(ie=>{let Se={expected:W,received:0,results:[],errors:[],finish:ua=>{clearTimeout(De),x.delete(pe),ie({results:Se.results,errors:Se.errors,timedOut:ua})}},De=setTimeout(()=>Se.finish(!0),B);x.set(pe,Se),o.emit("message",{id:pe,payload:L})});return N.json({clients:W,...te})}),w.use("/__send-reply",R),w.post("/__send-reply",async N=>{try{let{id:L,results:B,errors:W}=await N.req.json(),z=x.get(L);z&&(z.results.push(...B??[]),z.errors.push(...W??[]),++z.received>=z.expected&&z.finish(!1))}catch{}return N.json({ok:!0})})}w.get("/",y=>y.html(e())),w.post("/__fs/read",async y=>{try{let{path:x}=await y.req.json(),N=await Wn(x,A,t);return new Response(new Uint8Array(N),{headers:{"Content-Type":"application/octet-stream"}})}catch(x){let N=Xu(x);return y.json({error:N},400)}}),w.post("/__fs/write",async y=>{try{let x=y.req.query("path");return x?(await Qi(x,new Uint8Array(await y.req.arrayBuffer()),A,t),y.json({success:!0})):y.json({error:"Missing path"},400)}catch(x){let N=Xu(x);return y.json({error:N},400)}}),w.post("/__api/:name",async y=>{try{let x=y.req.param("name"),N=oa(a?.(),x);if(!N)return y.json({error:`API function '${x}' not found`},404);let{args:L}=await y.req.json();if(aa(N))return sa(y,N(...L||[]));let B=await N(...L||[]);return y.json({result:B})}catch(x){let N=Xu(x);return y.json({error:N},500)}}),w.post("/__ai",async y=>{try{let{messages:x,system:N,effort:L,provider:B,model:W,webSearch:z,stream:pe}=await y.req.json();if(!x||!Array.isArray(x)||x.length===0)return y.json({message:"messages array is required",code:"unknown",retryable:!1},400);let te=rt(B,W);if(typeof te=="string")return y.json({message:te,code:"unknown",retryable:!1},400);let ie=await kt(te,{messages:x,system:N,effort:L,webSearch:z,signal:y.req.raw.signal});if(!ie.ok){let De=await Pr(ie,te.protocol);return y.json(De,ie.status)}if(pe)return sa(y,Vt(ie,te.protocol));let Se=await Yt(ie,te.protocol);return Se||console.warn("[tb.ai] Empty response from provider"),y.json({text:Se})}catch(x){return y.json(gs(x),500)}}),w.post("/__infer",async y=>{try{let{data:x}=await y.req.json().catch(()=>({})),N=c?.();if(!N?.infer.trim())return y.json({message:"This bulb has no infer.md block.",code:"unknown",retryable:!1},400);let L=rt();if(typeof L=="string")return y.json({message:L,code:"unknown",retryable:!1},400);let B=Array.isArray(x)?x.map(String):[],W=Nl(N,B),z=await kt(L,{messages:[{role:"user",content:W}],signal:y.req.raw.signal});if(!z.ok){let te=await Pr(z,L.protocol);return y.json(te,z.status)}let pe=(async function*(){let te="";for await(let De of Vt(z,L.protocol))De.kind!=="text"||!De.text||(te+=De.text,yield{kind:"delta",text:De.text});let ie=Il(te);if(ie.parsed===null)throw console.warn(`[tb.infer] output not valid JSON after sanitize; raw output (last 4000 chars):
|
|
1959
|
+
`+te.slice(-4e3)),new we("LLM output is not valid JSON","parse_error",!0);ie.fixesApplied.length&&console.warn("[tb.infer] sanitized output, fixes applied:",ie.fixesApplied.join(", "));let Se={insight:ie.parsed,insightJson:ie.json,data:B};yield{kind:"complete",...Se,fixesApplied:ie.fixesApplied,hash:$l(Se)}})();return sa(y,pe)}catch(x){return y.json(gs(x),500)}});let $=async y=>{let{hash:x}=await y.req.json().catch(()=>({}));return typeof x=="string"?Ll(x):null};w.post("/__infer-save",async y=>{try{if(!l)return y.json({message:"Save is not available for this server.",code:"unknown",retryable:!1},400);let x=await $(y);return x?(await l(x.data,x.insightJson),y.json({ok:!0})):y.json({message:"No decodable #tb= fragment to save.",code:"unknown",retryable:!1},400)}catch(x){return y.json(gs(x),500)}}),w.get("/__infer-info",y=>{let x=c?.(),N=zr(x?.config??"").inference,L=Si(x?.data??""),B=rt();return typeof B=="string"?y.json({error:B,inference:N,data:L}):y.json({provider:B.protocol,model:B.model,inference:N,data:L})}),w.use("/__infer-decode",R),w.post("/__infer-decode",async y=>y.json(await $(y)??{error:"invalid fragment"})),w.get("/__infer-ui.js",y=>y.body(Cb,200,{"Content-Type":"text/javascript; charset=utf-8"})),w.get("/__models",async y=>{try{let x=await tt();return y.json(x)}catch{return y.json([],200)}}),w.get("/__has-own-keys",async y=>{try{return y.json(await Gi())}catch{return y.json(!1,200)}}),m&&w.get("/__source/*",async y=>{let x=await Zu.readFile(m,"utf-8").catch(()=>{});return x===void 0?y.text("Not Found",404):new Response(x,{headers:{"Content-Type":"text/plain; charset=utf-8"}})});let E=["esm.sh","unpkg.com","cdn.jsdelivr.net","cdnjs.cloudflare.com"],M=new na;w.get("/proxy/*",async y=>{let x=new URL(y.req.url),L=(x.pathname+x.search).slice(7),B=L.lastIndexOf("https://");return B===-1?y.text("Invalid proxy URL",400):H(y,L.slice(B))}),f&&Nb(w,`/local/${f.name}/`,f.serveDir),p&&Nb(w,p.mount,p.dir),h&&w.get("/assets/*",async y=>{let{pathname:x}=new URL(y.req.url),N=x.slice(8),L;try{L=decodeURIComponent(N)}catch{return y.text("Not Found",404)}let B=Rd(L);if(B)return y.text(`${B} is not an asset type: a bulb's code and markup live in the bulb; assets are media and data`,403);try{for(let z of h.dirs){let pe=await $b(L,z,{"Cache-Control":"no-cache"});if(pe)return pe}}catch{return y.text("Not Found",404)}let W=h.remoteBase;return W?y.redirect(W+N,302):y.text("Not Found",404)});async function H(y,x){let N;try{N=new URL(x)}catch{return y.text("Invalid URL",400)}if(N.protocol!=="https:")return y.text("HTTPS only",400);if(!E.includes(N.hostname))return y.text("Host not allowed",403);let L=await M.get(x);if(L)return new Response(L.body,{status:200,headers:Qu(L.contentType,L.cacheControl)});try{let B=await fetch(x,{headers:{Accept:y.req.header("Accept")||"*/*"},redirect:"follow"});if(!B.ok)return y.text(`Upstream ${B.status}`,B.status);let W=B.headers.get("Content-Type")||void 0,z=B.headers.get("Cache-Control")||void 0;if(B.body){let[pe,te]=B.body.tee();return(async()=>{try{let ie=await new Response(te).arrayBuffer();await M.set(x,{body:Buffer.from(ie),contentType:W,cacheControl:z})}catch{}})(),new Response(pe,{status:B.status,headers:Qu(W,z)})}return new Response(null,{status:B.status,headers:Qu(W,z)})}catch(B){return y.text(`Proxy fetch failed: ${B instanceof Error?B.message:B}`,502)}}(i||o)&&w.get("/__reload",y=>zO(y,async x=>{let N=()=>{x.writeSSE({event:"reload",data:""})},L=B=>{x.writeSSE({event:"message",data:JSON.stringify(B)})};for(i?.on("reload",N),o?.on("message",L),x.onAbort(()=>{i?.removeListener("reload",N),o?.removeListener("message",L),_=Date.now()}),await x.writeSSE({event:"hello",data:b});!x.aborted;)await x.sleep(3e4)})),w.notFound(async y=>{if(y.req.method!=="GET")return y.text("Not Found",404);let x=new URL(y.req.url);return _b(x.pathname,x.search)?H(y,"https://esm.sh"+x.pathname+x.search):y.text("Not Found",404)});let U=GO({fetch:w.fetch,port:s,hostname:XO});return U.listening||await new Promise((y,x)=>{let N=L=>x(L);U.once("error",N),U.once("listening",()=>{U.removeListener("error",N),y()})}),{port:s,close:()=>U.close()}}function Qu(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 Nb(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);try{return await $b(decodeURIComponent(s.slice(e.length)),t)??n.text("Not Found",404)}catch{return n.text("Not Found",404)}})}async function $b(r,e,t={}){let n=Xi(r,e),s=await Zu.readFile(n).catch(()=>{});if(s)return new Response(s,{headers:{"Content-Type":Od(n),...t}})}Be();es();async function ca(r){let{port:e,portNote:t,makeServerOptions:n,makeEntry:s,displayName:i,stopLog:o}=r,a=await Ib(n(e)).catch(async u=>{if(u?.code!=="EADDRINUSE")throw u;return lu(e)}),c=`http://localhost:${e}`;await jh(s(e,c)),console.log(`
|
|
1953
1960
|
${i}`),console.log(` ${c}`),t&&console.log(` ${t}`);let l=[],f=async()=>{console.log(`
|
|
1954
|
-
Shutting down...`),a.close();for(let u of l)try{await u()}catch{}o(),await Qn(process.pid),process.exit(0)};return process.on("SIGINT",f),process.on("SIGTERM",f),{port:e,url:c,onCleanup(u){l.push(u)}}}es();import
|
|
1961
|
+
Shutting down...`),a.close();for(let u of l)try{await u()}catch{}o(),await Qn(process.pid),process.exit(0)};return process.on("SIGINT",f),process.on("SIGTERM",f),{port:e,url:c,onCleanup(u){l.push(u)}}}es();import nR from"chokidar";var sR={persistent:!0,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50}};function Nt(r){let{target:e,onChange:t,events:n="change",debounceMs:s=150}=r,i,o=nR.watch(e,sR);o.on("error",c=>console.warn(`watch: ${c instanceof Error?c.message:c} \u2014 continuing`));let a=()=>{i&&clearTimeout(i),i=setTimeout(t,s)};return n==="all"?o.on("all",a):o.on("change",a),()=>{i&&clearTimeout(i),o.close()}}Be();async function Mb(r,e,t,n){let s=process.cwd(),i=ao(process.pid),o=e.watch?new Lb:void 0,a=new Lb;a.setMaxListeners(0);let c=Ae(e.mode),l=await su(r);l.length&&console.log(`Replacing the running server for this bulb (pid ${l.map(E=>E.pid).join(", ")})`);let{port:f,note:u}=await yo({explicit:e.port,target:{kind:"bulb",file:r},cwd:process.cwd()}),d=1;console.log(tu(d)),e.batch&&await Nr(r,e.batch),console.log(`Loading ${la.basename(r)}...`);let{html:p,bulb:h,serverExports:m}=await Fl(r,e.watch,e.trust,n,e.batch);Tt(c,r,h.server);let b=[...e.batch?[Et(r,e.batch)]:[],Et(r)],A=Zi(la.resolve(r)),w=e.trust?void 0:Dr(h),{port:P,url:C,onCleanup:R}=await ca({port:f,portNote:u,displayName:h.name,stopLog:i,makeServerOptions:E=>({getHtml:()=>p,basePath:s,fsBase:xt(r,e.batch),port:E,reloadEmitter:o,messageEmitter:a,getServerExports:()=>m,getBulbBlocks:()=>({infer:h.infer,insight:h.insight,code:h.code,config:h.config,data:h.data}),saveInferenceResult:async(M,H)=>{let U=await It.readFile(r,"utf-8");U=Gr(U,"data",M.join(Rm)),U=Gr(U,"insight",H),await It.writeFile(r,U)},localOverride:n?{name:n.name,serveDir:n.serveDir}:void 0,bulbAssets:{dirs:b,remoteBase:A&&xs(A.userSlug,A.slug)},sourceFile:r,trusted:e.trust,trustHint:t}),makeEntry:(E,M)=>({pid:process.pid,port:E,url:M,file:r,cwd:process.cwd(),startedAt:Date.now(),trust:e.trust,batch:e.batch,mode:e.mode,predicted:w})});e.trust?console.log(" trust: granted (filesystem, AI, server.ts enabled)"):console.log(w?` trust: restricted \u2014 this bulb appears to use ${w}; re-run with --trust to enable it:
|
|
1955
1962
|
${t}
|
|
1956
1963
|
`:` trust: restricted \u2014 re-run with --trust to enable filesystem / AI / server.ts
|
|
1957
1964
|
`),e.watch&&console.log(` Watching for changes...
|
|
1958
1965
|
`);let _,$;if(e.watch&&o){let E=0,M=Promise.resolve();if(_=Nt({target:r,onChange:()=>{let H=++E;M=M.then(async()=>{if(H===E)try{console.log("Recompiling...");let U=await Fl(r,!0,e.trust,n,e.batch);p=U.html,m=U.serverExports,h=U.bulb,d++,console.log(tu(d)),o.emit("reload")}catch(U){console.error("Compile error:",U)}})}}),n){let{name:H,serveDir:U}=n;$=Nt({target:U,events:"all",onChange:()=>{console.log(`Local package '${H}' changed. Browser reloading...
|
|
1959
1966
|
`),o.emit("reload")}})}for(let H of b)await It.stat(H).then(U=>U.isDirectory()).catch(()=>!1)&&R(Nt({target:H,events:"all",onChange:()=>{console.log(`Assets changed. Browser reloading...
|
|
1960
1967
|
`),o.emit("reload")}}))}_&&R(_),$&&R($),R(()=>It.rm(jl(r),{force:!0})),e.open&&(l.some(E=>E.port===P)?console.log(` Reusing the open browser tab.
|
|
1961
|
-
`):await
|
|
1968
|
+
`):await iR(C))}Pt();import{readFileSync as Db,copyFileSync as aR,existsSync as cR}from"fs";import*as de from"path";import{fileURLToPath as lR}from"url";import{EventEmitter as uR}from"events";import jb from"open";es();Be();Bi();var ed=r=>`/agents/${r}/client.js`,oR=`
|
|
1962
1969
|
(() => {
|
|
1963
1970
|
const api = async (name, ...args) => {
|
|
1964
1971
|
const resp = await fetch('/__api/' + name, {
|
|
@@ -1970,7 +1977,7 @@ Shutting down...`),a.close();for(let u of l)try{await u()}catch{}o(),await Qn(pr
|
|
|
1970
1977
|
if (!resp.ok) throw new Error(data.error || 'API call failed');
|
|
1971
1978
|
return data.result;
|
|
1972
1979
|
};
|
|
1973
|
-
const
|
|
1980
|
+
const tbLog = async (...args) => {
|
|
1974
1981
|
try {
|
|
1975
1982
|
const resp = await fetch('/__log', {
|
|
1976
1983
|
method: 'POST',
|
|
@@ -1981,10 +1988,9 @@ Shutting down...`),a.close();for(let u of l)try{await u()}catch{}o(),await Qn(pr
|
|
|
1981
1988
|
} catch { console.log(...args); }
|
|
1982
1989
|
};
|
|
1983
1990
|
globalThis.tb = Object.freeze({
|
|
1991
|
+
log: (...args) => { void tbLog(...args); },
|
|
1984
1992
|
server: new Proxy({}, {
|
|
1985
|
-
get: (_, name) => name
|
|
1986
|
-
? (...args) => serverLog(...args)
|
|
1987
|
-
: (...args) => api(name, ...args)
|
|
1993
|
+
get: (_, name) => (...args) => api(name, ...args)
|
|
1988
1994
|
})
|
|
1989
1995
|
});
|
|
1990
1996
|
if (window.__TYPEBULB_WATCH__) {
|
|
@@ -2011,17 +2017,17 @@ ${s}
|
|
|
2011
2017
|
${i?"<script>window.__TYPEBULB_WATCH__ = true;</script>":""}
|
|
2012
2018
|
|
|
2013
2019
|
<script>
|
|
2014
|
-
${
|
|
2020
|
+
${oR}
|
|
2015
2021
|
</script>
|
|
2016
2022
|
|
|
2017
2023
|
<script type="module" src="${a}"></script>
|
|
2018
2024
|
</body>
|
|
2019
2025
|
</html>`}async function Fb(r){let e=process.cwd(),t=r.agentTarget;Dy(t)||(console.error(`Unknown agent '${t}'. Known: ${Wr().join(", ")}.`),process.exit(1));let n=await nu(e,t);if(n){console.log(`Mirror '${t}' is already running for this project:
|
|
2020
|
-
${n.url}`),r.open&&await jb(n.url);return}let s=ao(process.pid),i=r.watch?new
|
|
2021
|
-
`);let C=de.join(u,t,"client"),R=de.join(u,"core","client");async function _(){await(await import("esbuild")).build({entryPoints:[de.join(C,"index.ts")],bundle:!0,platform:"browser",format:"esm",outfile:de.join(f,"client.js")});for(let M of["styles.css","index.html","typebulb.png","typebulb-inv.png"])
|
|
2026
|
+
${n.url}`),r.open&&await jb(n.url);return}let s=ao(process.pid),i=r.watch?new uR:void 0,o=Ae(r.mode),a=await Fy(t),c=a.displayName||`${t} mirror`;Tt(o,de.join(e,"mirror"));let l=de.dirname(lR(import.meta.url)),f=de.join(l,"agents",t),u=de.join(l,"..","cli","agents"),d=de.join(f,"styles.css"),p=de.join(f,"index.html"),h=()=>Bb({name:c,agent:t,styles:Db(d,"utf8"),mountHtml:Db(p,"utf8"),watch:r.watch}),{port:m,note:b}=await yo({explicit:r.port,target:{kind:"mirror",agent:t},cwd:e}),{port:A,url:w,onCleanup:P}=await ca({port:m,portNote:b,displayName:c,stopLog:s,makeServerOptions:E=>({getHtml:h,basePath:e,port:E,reloadEmitter:i,getServerExports:()=>a,trusted:!0,staticAssets:{mount:`${de.posix.dirname(ed(t))}/`,dir:f}}),makeEntry:(E,M)=>({pid:process.pid,port:E,url:M,file:`agent:${t}`,cwd:e,startedAt:Date.now(),trust:!0,agent:t})});r.watch&&console.log(` Watching for changes...
|
|
2027
|
+
`);let C=de.join(u,t,"client"),R=de.join(u,"core","client");async function _(){await(await import("esbuild")).build({entryPoints:[de.join(C,"index.ts")],bundle:!0,platform:"browser",format:"esm",outfile:de.join(f,"client.js")});for(let M of["styles.css","index.html","typebulb.png","typebulb-inv.png"])aR(de.join(R,M),de.join(f,M))}let $;if(r.watch&&i){let E=cR(C),M=!1;$=Nt({target:E?u:f,events:"all",onChange:async()=>{if(!M){M=!0;try{E&&await _(),console.log(`Mirror rebuilt. Browser reloading...
|
|
2022
2028
|
`),i.emit("reload")}catch(H){console.error("Mirror rebuild failed:",H instanceof Error?H.message:H)}finally{M=!1}}}})}r.open&&await jb(w),P(()=>a.shutdownSwitcher?.()),P(()=>a.shutdownComposer?.()),$&&P($)}Pt();qe();import*as qb from"path";async function Ub(r,e,t,n,s){let i=Ae(t),o=!1;s&&await Nr(r,s);let a=async()=>{let{bulb:c,config:l}=await Le(r);o||(Tt(i,r,c.server),o=!0),await Yn(c.server,r,n,l.dependencies,s)};if(console.log(`Running ${qb.basename(r)}...`),await a(),e){console.log(`Watching for changes...
|
|
2023
|
-
`);let c=0,l=Promise.resolve();Nt({target:r,onChange:()=>{let f=++c;l=l.then(async()=>{if(f===c)try{console.log("Re-running..."),await a()}catch(u){console.error("Error:",u)}})}})}}Pt();qe();import{Console as
|
|
2024
|
-
`)}catch(p){ys(p instanceof Error?p.stack??p.message:String(p))}return Jb(0)}let u;try{u=await l(...f)}catch(p){ys(p instanceof Error?p.stack??p.message:String(p))}let d=
|
|
2025
|
-
`),Jb(0)}function Jb(r){process.exitCode=r,setTimeout(()=>process.exit(r),2e3).unref?.()}async function
|
|
2026
|
-
`),process.exit(1)}function
|
|
2027
|
-
${e}`),process.exit(1))}async function
|
|
2029
|
+
`);let c=0,l=Promise.resolve();Nt({target:r,onChange:()=>{let f=++c;l=l.then(async()=>{if(f===c)try{console.log("Re-running..."),await a()}catch(u){console.error("Error:",u)}})}})}}Pt();qe();import{Console as dR}from"node:console";Be();async function Hb(r,e,t,n,s){gR();try{let p=Br(await Q(),r)[0];p&&(oo(p.pid,Je(p.pid).offset),console.error(`note: 'call' boots a fresh server.ts instance; the running server (${p.url}) is not contacted \u2014 state shared with it must live on disk.`))}catch{}let i=Ae(t),{bulb:o,config:a}=await Le(r);o.server||ys("This bulb has no **server.ts** block; nothing to call."),Tt(i,r,o.server),s&&await Nr(r,s);let c;try{c=await Yn(o.server,r,n,a.dependencies,s)}catch(p){ys(p instanceof Error?p.message:String(p))}let l=oa(c,e.fn);if(!l){let p=[...Object.keys(c).filter(h=>typeof c[h]=="function"),...Object.keys(ia)];ys(`Function '${e.fn}' not found. Available: ${p.length?p.join(", "):"(none)"}.`)}let f=await fR(e);if(aa(l)){try{for await(let p of l(...f))await Kb(JSON.stringify(p,Wb)+`
|
|
2030
|
+
`)}catch(p){ys(p instanceof Error?p.stack??p.message:String(p))}return Jb(0)}let u;try{u=await l(...f)}catch(p){ys(p instanceof Error?p.stack??p.message:String(p))}let d=hR(u);d!==void 0&&await Kb(d+`
|
|
2031
|
+
`),Jb(0)}function Jb(r){process.exitCode=r,setTimeout(()=>process.exit(r),2e3).unref?.()}async function fR(r){if(r.hasArgsFlag){let e=r.argsJson??"";return e==="-"&&(e=await yR()),mR(e)}return pR(r.positional)}function pR(r){return r.map(e=>{try{return JSON.parse(e)}catch{return e}})}function mR(r){let e;try{e=JSON.parse(r)}catch(t){throw new Error(`--args must be a JSON array: ${t instanceof Error?t.message:String(t)}`)}if(!Array.isArray(e))throw new Error(`--args must be a JSON array, got ${e===null?"null":typeof e}`);return e}function hR(r){if(r!==void 0)return JSON.stringify(r,Wb,2)}function Wb(r,e){return typeof e=="bigint"?e.toString():e}function ys(r){process.stderr.write(r+`
|
|
2032
|
+
`),process.exit(1)}function gR(){let r=new dR(process.stderr,process.stderr);console.log=r.log.bind(r),console.info=r.info.bind(r),console.debug=r.debug.bind(r),console.dir=r.dir.bind(r)}function Kb(r){return new Promise((e,t)=>{process.stdout.write(r,n=>n?t(n):e())})}async function yR(){let r=[];for await(let e of process.stdin)r.push(e);return Buffer.concat(r).toString("utf-8")}var td="0.41.0";function Yb(r,e){r||(console.error(`This bulb runs server-side Node code (server.ts), which --trust must authorize:
|
|
2033
|
+
${e}`),process.exit(1))}async function bR(){let r=Nm(process.argv.slice(2));if(r.version&&(console.log(`typebulb ${td}`),process.exit(0)),r.help&&(Im(),process.exit(0)),ab(),r.subcommand==="logs"){await yb(r.file||void 0,{follow:r.follow,clear:r.clear,run:r.run,lines:r.lines});return}if(r.subcommand==="wait"){await bb(r.file||void 0,{match:r.match,timeoutSec:r.timeoutSec});return}if(r.subcommand==="stop"){r.stopScope?await vb(r.stopScope):await wb(r.file||void 0);return}if(r.subcommand==="send"){await xb(r.file,r.sendMessage,r.sendWaitMs??0);return}if(r.subcommand==="skill"){await mb(td);return}if(r.subcommand==="models"){await fb(r.mode);return}if(r.subcommand==="pull"){await fg(r.file||void 0,{force:r.force,mode:r.mode});return}if(r.subcommand==="push"){await mg(r.file||void 0,{force:r.force,mode:r.mode});return}if(r.subcommand==="agent"){await(r.agentTarget?Fb(r):db(td));return}if(r.subcommand==="trust"||r.subcommand==="untrust"){await ob(r.file||void 0,r.subcommand==="trust");return}let e;if(!r.file||r.file==="."){let c=await Eh(process.cwd());c||(console.error("No .bulb.md file found in current directory"),process.exit(1)),e=c}else e=or.resolve(r.file);if(await Vb.access(e).then(()=>!0,()=>!1)||(Wr().includes(r.file)&&(console.error(`To open the ${r.file} agent mirror, 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)),r.subcommand==="get"){await Ab(e,r.blockKind);return}if(r.subcommand==="put"){await Ob(e,r.blockPairs);return}let n=r.file&&r.file!=="."?r.file:or.relative(process.cwd(),e)||or.basename(e),s=`npx typebulb --trust ${n.includes(" ")?`"${n}"`:n}`;if(r.subcommand==="predict"){await ib(e,s);return}let i=!r.noTrust&&zt(e);i&&!r.trust&&console.error("trust: granted from memory (run `typebulb untrust` to revoke)"),r.trust=r.noTrust?!1:r.trust||i;let o;try{o=await Le(e)}catch{}let a;if(r.local){o&&!(r.local.name in(o.config.dependencies??{}))&&(console.error(`--replace: '${r.local.name}' is not a dependency in this bulb's config.json; nothing to replace.`),process.exit(1)),o&&r.subcommand!=="call"&&(!o.bulb.code||r.server)&&console.warn("warning: --replace has no effect in server mode (the override is client-only).");try{a=await pd(r.local)}catch(c){console.error(c instanceof Error?c.message:String(c)),process.exit(1)}console.error(`replace: ${a.name} \u2192 ${or.relative(process.cwd(),a.dir)||"."}`)}if(r.subcommand==="check"){await sb(e,a);return}if(r.subcommand==="call"){Yb(r.trust,s),await Hb(e,{fn:r.fn,positional:r.callArgs,argsJson:r.argsJson,hasArgsFlag:r.hasArgsFlag},r.mode,a,r.batch);return}if(o&&o.bulb.server&&(ki(o.bulb)||r.server)){Yb(r.trust,s),await Ub(e,r.watch,r.mode,a,r.batch);return}await Mb(e,r,s,a)}bR().catch(r=>{console.error("Error:",r.message),process.exit(1)});
|