typebulb 0.10.4 → 0.10.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -119,8 +119,10 @@ npm install -g typebulb
119
119
  typebulb [file.bulb.md] Run a bulb (defaults to .bulb.md in cwd)
120
120
  typebulb agent:claude Open the agent viewer (a Claude Code session)
121
121
  typebulb agent Start here — how to show a bulb inline or build one locally
122
+ (prints the viewer URL when one is up); always exits 0
122
123
  typebulb skill Print this README as an Agent Skill on stdout
123
124
  typebulb check [file.bulb.md] Type-check a bulb without running it
125
+ typebulb check - Type-check a bulb piped on stdin (validate before embedding)
124
126
  typebulb predict [file] Report the capability a bulb probably needs, without running it
125
127
  typebulb models List AI models for tb.ai, filtered by your .env API keys
126
128
  typebulb logs [file|pid] Print a running bulb's captured console (no arg: list running servers; -f follow, -n N tail)
@@ -226,7 +228,7 @@ A local `.bulb.md` can be re-imported into typebulb.com. If it has a `**server.t
226
228
 
227
229
  The agent viewer currently supports Claude Code only. `npx typebulb agent:claude` gives the user a great scratchpad experience:
228
230
 
229
- * a view over the Claude Code session, where assistant messages containing bulbs render as sandboxed embedded bulbs inline in the conversation, alongside KaTeX math and mermaid diagrams.
231
+ * a view over the Claude Code session, where assistant messages containing bulbs render as sandboxed embedded bulbs inline in the conversation, alongside KaTeX math, mermaid diagrams and svg.
230
232
  * run and stop any bulb in their project.
231
233
  * promote any embedded bulb to a `.bulb.md` file in the `typebulbs/` folder.
232
234
 
@@ -247,6 +249,8 @@ To render a bulb live inline, wrap the **entire** bulb — frontmatter and all b
247
249
 
248
250
  The agent viewer turns that block into a live, sandboxed app, with a *breakout ↗* control that saves it as a `.bulb.md` in the `typebulbs/` folder — editable with hot reload, and sandboxed unless you trust it. Embedded bulbs are client-only — no `server.ts`, no `tb.fs`/`tb.ai`, no storage.
249
251
 
252
+ **Validate before you emit.** An embed is inline text with no file to point `check` at, so type errors otherwise reach the user as a broken embed with no signal to you. Pipe the whole bulb body — frontmatter and all blocks — through `npx typebulb check -`: it type-checks stdin and exits non-zero on errors, giving an embedded bulb the same pre-flight a local `.bulb.md` gets from `typebulb check <file>`.
253
+
250
254
  **Sizing is the viewer's job, not yours.** The agent viewer renders each embed *inline* by default — fit to the conversation column, with height capped so a tall bulb doesn't run away — plus a per-embed toggle to *spread* it to the full transcript width and height. Don't fight the layout from inside the bulb: no need to set a width, reserve height, or guess how much room you'll get.
251
255
 
252
256
  **One layout rule the bulb must get right: vertical space on the root is `padding`, not `margin`.** The embed auto-sizes by reporting `document.body.scrollHeight`, and a vertical margin on the root element *collapses* (a body's first/last child margin escapes through to the viewport) so it isn't captured in that measurement — the host then sizes the frame a margin short and you get a stray scrollbar. The page-style `margin: 32px auto` common on a standalone wrapper is exactly this trap. Keep the horizontal `auto` for centering, but move the vertical part to padding:
@@ -820,6 +820,16 @@ function decodeHtmlEntities(s: string): string {
820
820
  // ```mermaid``` fences render to inline SVG. A parse error falls through to the
821
821
  // default code-block rendering, so an unsupported diagram degrades to readable
822
822
  // source rather than a broken message.
823
+ // A hover-revealed copy pill for a rendered fence. Every fenced block — code, svg, mermaid, an
824
+ // unrecognised language — flows through the fence rule below, and the thing worth copying is always
825
+ // its raw body, so one primitive covers them all. The source rides the button's own data-src
826
+ // (escaped going in; getAttribute auto-unescapes coming out, so multi-line bodies round-trip), which
827
+ // decouples the delegated handler from each block's container structure. `.copyable` is the shared
828
+ // marker the rule stamps on every block so one CSS rule can reveal the pill on hover.
829
+ function copyButton(src: string): string {
830
+ return `<button class="overlay-pill copy-src" type="button" title="Copy source" data-src="${md.utils.escapeHtml(src)}">copy</button>`
831
+ }
832
+
823
833
  const defaultFence: MdRenderRule = md.renderer.rules.fence
824
834
  ?? ((tokens, idx, opts, _env, self) => self.renderToken(tokens, idx, opts))
825
835
  md.renderer.rules.fence = (tokens: MdToken[], idx: number, opts: unknown, env: unknown, self: MdRenderer) => {
@@ -840,7 +850,8 @@ md.renderer.rules.fence = (tokens: MdToken[], idx: number, opts: unknown, env: u
840
850
  // surface is stripped. Lets the agent draw anything (smiley, plot from an
841
851
  // equation) without an iframe, since it's static markup, not executed code.
842
852
  if (lang === 'svg' && live) {
843
- return `<div class="embed svg-embed">${DOMPurify.sanitize(t.content, { USE_PROFILES: { svg: true, svgFilters: true } })}</div>`
853
+ const safe = DOMPurify.sanitize(t.content, { USE_PROFILES: { svg: true, svgFilters: true } })
854
+ return `<div class="embed svg-embed copyable">${safe}${copyButton(t.content)}</div>`
844
855
  }
845
856
  if (lang === 'mermaid' && live) {
846
857
  try {
@@ -861,10 +872,13 @@ md.renderer.rules.fence = (tokens: MdToken[], idx: number, opts: unknown, env: u
861
872
  font: 'system-ui, -apple-system, "Segoe UI", sans-serif',
862
873
  transparent: true,
863
874
  })
864
- return `<div class="mermaid">${svg}</div>`
875
+ return `<div class="mermaid copyable">${svg}${copyButton(t.content)}</div>`
865
876
  } catch { /* fall through to a plain code block */ }
866
877
  }
867
- return defaultFence(tokens, idx, opts, env, self)
878
+ // Every other fence (code, an unrecognised language, or a non-live svg/mermaid in a user turn) is a
879
+ // copyable source block: the default <pre><code> wrapped so it gets the same hover copy pill. The
880
+ // wrapper — not the <pre> — is the `.md` flow child now; see `.code-block` CSS for the rhythm.
881
+ return `<div class="code-block copyable">${defaultFence(tokens, idx, opts, env, self)}${copyButton(t.content)}</div>`
868
882
  }
869
883
 
870
884
  // Author classDef/style colors render as literal fill/stroke/color that override
@@ -926,6 +940,16 @@ function fitSvgEmbeds(root: Element) {
926
940
  // served from the project root, so the browser would GET the path and 404. Links
927
941
  // with a scheme (http, mailto, …) fall through to the default new-tab behavior.
928
942
  function onMarkdownClick(e: Event) {
943
+ // Per-fence copy: the source is on the button's own data-src (see copyButton), so no container walk.
944
+ const copyBtn = (e.target as Element | null)?.closest<HTMLButtonElement>('.copy-src')
945
+ if (copyBtn) {
946
+ e.preventDefault()
947
+ navigator.clipboard?.writeText(copyBtn.dataset.src ?? '')
948
+ copyBtn.classList.add('done')
949
+ copyBtn.textContent = 'copied'
950
+ setTimeout(() => { copyBtn.classList.remove('done'); copyBtn.textContent = 'copy' }, 1200)
951
+ return
952
+ }
929
953
  const anchor = (e.target as Element | null)?.closest('a')
930
954
  if (!anchor) return
931
955
  const href = anchor.getAttribute('href') ?? ''
@@ -3050,6 +3074,19 @@ a.server-port:hover { color: var(--accent); text-decoration: underline; }
3050
3074
  }
3051
3075
  .overlay-pill:hover { color: var(--accent); border-color: var(--accent); }
3052
3076
 
3077
+ /* Per-fence copy pill (code / svg / mermaid) — one reveal rule for every copyable block, since the
3078
+ fence rule stamps `.copyable` on each. The svg/mermaid containers are already position:relative for
3079
+ the chop/breakout; the code-block wrapper needs it for the absolute pill. The pill is positioned
3080
+ (absolute), so it paints over the static fence content regardless of DOM order. */
3081
+ .md .copyable { position: relative; }
3082
+ .md .copyable:hover .copy-src,
3083
+ .md .copy-src:focus-visible { opacity: 1; }
3084
+ .md .copy-src.done { color: var(--accent); border-color: var(--accent); }
3085
+ /* The wrapper carries the code block's vertical rhythm (it, not the <pre>, is the `.md` flow child
3086
+ now, so the first/last-child margin resets land on it); the <pre> sits flush inside. */
3087
+ .md .code-block { margin: .6rem 0; }
3088
+ .md .code-block pre { margin: 0; }
3089
+
3053
3090
  /* Controls (code ⇄ run, then copy, then breakout) — a centered overlay straddling the
3054
3091
  bulb's top edge: clear of the running bulb below, free to overlap the prose above.
3055
3092
  Absolute, so toggling run↔code (which resizes the bulb below) never moves it, and so
@@ -3302,7 +3339,7 @@ a.server-port:hover { color: var(--accent); text-decoration: underline; }
3302
3339
  "beautiful-mermaid": "^1.1.3",
3303
3340
  "dompurify": "^3.2.6",
3304
3341
  "highlight.js": "^11.10.0",
3305
- "typebulb": "^0.10.4"
3342
+ "typebulb": "^0.10.6"
3306
3343
  }
3307
3344
  }
3308
3345
  ```
package/dist/index.js CHANGED
@@ -1,16 +1,18 @@
1
1
  #!/usr/bin/env node
2
- import*as Vn from"fs/promises";import*as q from"path";import*as sr from"fs/promises";import{existsSync as ae,readFileSync as Hn}from"fs";import*as P from"path";import{pathToFileURL as qn}from"url";import{resolve as St}from"resolve.exports";import{init as or,parse as ir}from"es-module-lexer";function ar(r,e){let t=P.join(r,"package.json");try{return JSON.parse(Hn(t,"utf8"))}catch{throw new Error(`--replace package '${e}' has no readable package.json at ${t}`)}}var xt=["browser","import","default"],nr=["node","import","default"];function cr(r){let e=r.indexOf("=");if(e===-1)throw new Error(`--replace must be <name>=<path> (got '${r}')`);let t=r.slice(0,e).trim(),n=r.slice(e+1).trim();if(!t)throw new Error(`--replace missing package name (got '${r}')`);if(!n)throw new Error(`--replace missing path for '${t}'`);if(t.startsWith("@"))throw new Error(`--replace does not support scoped names yet; '${t}' is scoped`);return{name:t,dir:P.resolve(n)}}async function lr(r){let{name:e,dir:t}=r;if(!ae(t))throw new Error(`--replace path for '${e}' does not exist: ${t}`);let n=ar(t,e),s=zn(n,e),o=P.resolve(t,s);if(!ae(o))throw new Error(`--replace package '${e}' entry not found on disk: ${o} \u2014 did you build it (e.g. \`pnpm run build\`)?`);let i=P.dirname(o),a=`/local/${e}/${P.basename(o)}`,c=Gn(n,t);return await Kn(e,o,i),{name:e,dir:t,entryAbs:o,serveDir:i,entryUrl:a,typesAbs:c}}function zn(r,e){if(r.exports!==void 0){let n;try{n=St(r,".",{browser:!0,conditions:xt})}catch(o){throw new Error(`--replace package '${e}' "exports" does not resolve a browser entry (conditions: ${xt.join(", ")}): ${o instanceof Error?o.message:o}`)}let s=Pt(n);if(!s)throw new Error(`--replace package '${e}' "exports" did not resolve "." to a single file (conditions: ${xt.join(", ")}); too complex to override.`);return s}let t=r.module??r.main;if(!t)throw new Error(`--replace package '${e}' has no "exports", "module", or "main" entry to resolve.`);return t}function Gn(r,e){if(r.exports!==void 0)try{let n=St(r,".",{conditions:["types"]}),s=Pt(n);if(s){let o=P.resolve(e,s);if(ae(o))return o}}catch{}let t=r.types??r.typings;if(t){let n=P.resolve(e,t);if(ae(n))return n}}function Pt(r){if(typeof r=="string")return r;if(Array.isArray(r))return r.find(e=>typeof e=="string")}async function Kn(r,e,t){await or;let n=P.normalize(t),s=new Set,o=[e];for(;o.length;){let i=o.shift();if(s.has(i))continue;s.add(i);let a;try{a=await sr.readFile(i,"utf8")}catch{continue}let c,l;try{[c,,,l]=ir(a,i)}catch{continue}if(i===e&&!l)throw new Error(`override package '${r}' entry is not an ES module (no import/export syntax); CommonJS or non-module entries aren't supported (esm.sh would have to transform it).`);for(let p of c){if(p.d===-2)continue;let d=p.n;if(d&&!d.startsWith("node:")){if(d.startsWith("./")||d.startsWith("../")||d.startsWith("/")){let m=Yn(i,d,n);m&&!s.has(m)&&o.push(m);continue}throw new Error(`override package must ship self-contained (bundle its dependencies); ${r} externalizes '${d}'`)}}}}function Yn(r,e,t){let n=e.replace(/[?#].*$/,""),s=P.resolve(P.dirname(r),n),o=[s,s+".js",s+".mjs",P.join(s,"index.js"),P.join(s,"index.mjs")];for(let i of o)if(P.normalize(i).startsWith(t)&&ae(i))return i}function Xn(r,e,t){let n=ar(r,e),s;if(n.exports!==void 0)try{s=Pt(St(n,t,{conditions:nr}))}catch(i){throw new Error(`--replace package '${e}' "exports" does not resolve a node entry for '${t}' (conditions: ${nr.join(", ")}): ${i instanceof Error?i.message:i}`)}else t==="."&&(s=n.main??n.module);if(!s)throw new Error(`--replace package '${e}' has no node export for '${t}'.`);let o=P.resolve(r,s);if(!ae(o))throw new Error(`--replace package '${e}' built file not found: ${o} \u2014 did you build it (e.g. \`pnpm run build\`)?`);return qn(o).href}async function dr(r,e){await or;let t;try{[t]=ir(r)}catch{return r}let n="",s=0;for(let o of t){if(o.d!==-1)continue;let i=o.n;if(!i||i!==e.name&&!i.startsWith(e.name+"/"))continue;let a=i===e.name?".":"."+i.slice(e.name.length),c=Xn(e.dir,e.name,a);n+=r.slice(s,o.s)+c,s=o.e}return n+r.slice(s)}function ur(r){let e={subcommand:"run",file:"",port:3e3,watch:!0,open:!0,server:!1,trust:!1,noTrust:!1,follow:!1,help:!1,version:!1},t=["check","predict","logs","stop","trust","untrust","skill","models"],n=r[0];if(n==="agent"||n?.startsWith("agent:")){e.subcommand="agent";let s=n.indexOf(":");if(s!==-1){let o=n.slice(s+1);o&&(e.agentTarget=o)}r=r.slice(1)}else n&&t.includes(n)&&(e.subcommand=n,r=r.slice(1));for(let s=0;s<r.length;s++){let o=r[s];if(o==="--help"||o==="-h")e.help=!0;else if(o==="--version"||o==="-V")e.version=!0;else if(o==="--no-watch")e.watch=!1;else if(o==="--no-open")e.open=!1;else if(o==="--server")e.server=!0;else if(o==="--trust")e.trust=!0;else if(o==="--no-trust")e.noTrust=!0;else if(o==="--mode"){let i=r[++s];(!i||i.startsWith("-"))&&(console.error("Missing value for --mode (e.g. --mode staging)"),process.exit(1)),e.mode=i}else if(o==="--follow"||o==="-f")e.follow=!0;else if(o==="--lines"||o==="-n"){let i=parseInt(r[++s],10);(isNaN(i)||i<0)&&(console.error(`Invalid --lines value: ${r[s]}`),process.exit(1)),e.lines=i}else if(o==="--port"||o==="-p"){let i=r[++s],a=parseInt(i,10);isNaN(a)&&(console.error(`Invalid port: ${i}`),process.exit(1)),e.port=a}else if(o==="--replace"||o.startsWith("--replace=")){let i=o.startsWith("--replace=")?o.slice(10):r[++s]??"";try{let a=cr(i);if(e.local)throw new Error(`--replace can only be used once (got '${e.local.name}' and '${a.name}')`);e.local=a}catch(a){console.error(a instanceof Error?a.message:String(a)),process.exit(1)}}else o.startsWith("-")||(e.file=o)}return e}function pr(){console.log(`
2
+ import*as zn from"fs/promises";import*as q from"path";import*as ir from"fs/promises";import{existsSync as ae,readFileSync as Gn}from"fs";import*as P from"path";import{pathToFileURL as Kn}from"url";import{resolve as Pt}from"resolve.exports";import{init as ar,parse as cr}from"es-module-lexer";function lr(r,e){let t=P.join(r,"package.json");try{return JSON.parse(Gn(t,"utf8"))}catch{throw new Error(`--replace package '${e}' has no readable package.json at ${t}`)}}var St=["browser","import","default"],or=["node","import","default"];function dr(r){let e=r.indexOf("=");if(e===-1)throw new Error(`--replace must be <name>=<path> (got '${r}')`);let t=r.slice(0,e).trim(),n=r.slice(e+1).trim();if(!t)throw new Error(`--replace missing package name (got '${r}')`);if(!n)throw new Error(`--replace missing path for '${t}'`);if(t.startsWith("@"))throw new Error(`--replace does not support scoped names yet; '${t}' is scoped`);return{name:t,dir:P.resolve(n)}}async function Je(r){let{name:e,dir:t}=r;if(!ae(t))throw new Error(`--replace path for '${e}' does not exist: ${t}`);let n=lr(t,e),s=Yn(n,e),o=P.resolve(t,s);if(!ae(o))throw new Error(`--replace package '${e}' entry not found on disk: ${o} \u2014 did you build it (e.g. \`pnpm run build\`)?`);let i=P.dirname(o),a=`/local/${e}/${P.basename(o)}`,c=Xn(n,t);return await Qn(e,o,i),{name:e,dir:t,entryAbs:o,serveDir:i,entryUrl:a,typesAbs:c}}function Yn(r,e){if(r.exports!==void 0){let n;try{n=Pt(r,".",{browser:!0,conditions:St})}catch(o){throw new Error(`--replace package '${e}' "exports" does not resolve a browser entry (conditions: ${St.join(", ")}): ${o instanceof Error?o.message:o}`)}let s=Rt(n);if(!s)throw new Error(`--replace package '${e}' "exports" did not resolve "." to a single file (conditions: ${St.join(", ")}); too complex to override.`);return s}let t=r.module??r.main;if(!t)throw new Error(`--replace package '${e}' has no "exports", "module", or "main" entry to resolve.`);return t}function Xn(r,e){if(r.exports!==void 0)try{let n=Pt(r,".",{conditions:["types"]}),s=Rt(n);if(s){let o=P.resolve(e,s);if(ae(o))return o}}catch{}let t=r.types??r.typings;if(t){let n=P.resolve(e,t);if(ae(n))return n}}function Rt(r){if(typeof r=="string")return r;if(Array.isArray(r))return r.find(e=>typeof e=="string")}async function Qn(r,e,t){await ar;let n=P.normalize(t),s=new Set,o=[e];for(;o.length;){let i=o.shift();if(s.has(i))continue;s.add(i);let a;try{a=await ir.readFile(i,"utf8")}catch{continue}let c,l;try{[c,,,l]=cr(a,i)}catch{continue}if(i===e&&!l)throw new Error(`override package '${r}' entry is not an ES module (no import/export syntax); CommonJS or non-module entries aren't supported (esm.sh would have to transform it).`);for(let p of c){if(p.d===-2)continue;let d=p.n;if(d&&!d.startsWith("node:")){if(d.startsWith("./")||d.startsWith("../")||d.startsWith("/")){let m=Zn(i,d,n);m&&!s.has(m)&&o.push(m);continue}throw new Error(`override package must ship self-contained (bundle its dependencies); ${r} externalizes '${d}'`)}}}}function Zn(r,e,t){let n=e.replace(/[?#].*$/,""),s=P.resolve(P.dirname(r),n),o=[s,s+".js",s+".mjs",P.join(s,"index.js"),P.join(s,"index.mjs")];for(let i of o)if(P.normalize(i).startsWith(t)&&ae(i))return i}function es(r,e,t){let n=lr(r,e),s;if(n.exports!==void 0)try{s=Rt(Pt(n,t,{conditions:or}))}catch(i){throw new Error(`--replace package '${e}' "exports" does not resolve a node entry for '${t}' (conditions: ${or.join(", ")}): ${i instanceof Error?i.message:i}`)}else t==="."&&(s=n.main??n.module);if(!s)throw new Error(`--replace package '${e}' has no node export for '${t}'.`);let o=P.resolve(r,s);if(!ae(o))throw new Error(`--replace package '${e}' built file not found: ${o} \u2014 did you build it (e.g. \`pnpm run build\`)?`);return Kn(o).href}async function ur(r,e){await ar;let t;try{[t]=cr(r)}catch{return r}let n="",s=0;for(let o of t){if(o.d!==-1)continue;let i=o.n;if(!i||i!==e.name&&!i.startsWith(e.name+"/"))continue;let a=i===e.name?".":"."+i.slice(e.name.length),c=es(e.dir,e.name,a);n+=r.slice(s,o.s)+c,s=o.e}return n+r.slice(s)}function pr(r){let e={subcommand:"run",file:"",port:3e3,watch:!0,open:!0,server:!1,trust:!1,noTrust:!1,follow:!1,help:!1,version:!1},t=["check","predict","logs","stop","trust","untrust","skill","models"],n=r[0];if(n==="agent"||n?.startsWith("agent:")){e.subcommand="agent";let s=n.indexOf(":");if(s!==-1){let o=n.slice(s+1);o&&(e.agentTarget=o)}r=r.slice(1)}else n&&t.includes(n)&&(e.subcommand=n,r=r.slice(1));for(let s=0;s<r.length;s++){let o=r[s];if(o==="--help"||o==="-h")e.help=!0;else if(o==="--version"||o==="-V")e.version=!0;else if(o==="--no-watch")e.watch=!1;else if(o==="--no-open")e.open=!1;else if(o==="--server")e.server=!0;else if(o==="--trust")e.trust=!0;else if(o==="--no-trust")e.noTrust=!0;else if(o==="--mode"){let i=r[++s];(!i||i.startsWith("-"))&&(console.error("Missing value for --mode (e.g. --mode staging)"),process.exit(1)),e.mode=i}else if(o==="--follow"||o==="-f")e.follow=!0;else if(o==="--lines"||o==="-n"){let i=parseInt(r[++s],10);(isNaN(i)||i<0)&&(console.error(`Invalid --lines value: ${r[s]}`),process.exit(1)),e.lines=i}else if(o==="--port"||o==="-p"){let i=r[++s],a=parseInt(i,10);isNaN(a)&&(console.error(`Invalid port: ${i}`),process.exit(1)),e.port=a}else if(o==="--replace"||o.startsWith("--replace=")){let i=o.startsWith("--replace=")?o.slice(10):r[++s]??"";try{let a=dr(i);if(e.local)throw new Error(`--replace can only be used once (got '${e.local.name}' and '${a.name}')`);e.local=a}catch(a){console.error(a instanceof Error?a.message:String(a)),process.exit(1)}}else o==="-"?e.file="-":o.startsWith("-")||(e.file=o)}return e}function fr(){console.log(`
3
3
  typebulb - Local bulb runner for Typebulb
4
4
 
5
5
  Usage:
6
6
  typebulb [file.bulb.md] Run a bulb (defaults to .bulb.md in cwd)
7
7
  typebulb agent Start here \u2014 tells the agent how to show a bulb inline
8
- or build one locally; exit 0 if a viewer is up, else 1.
8
+ or build one locally; prints the viewer URL when one is
9
+ up. Always exits 0 (it's a status report, not a check).
9
10
  typebulb agent:claude Open the agent viewer (a browser view over a Claude
10
11
  Code session; 'agent:<name>' selects which agent).
11
12
  typebulb skill Print this README as an Agent Skill (stdout), for the
12
13
  agent to read and copy into its own skills folder.
13
- typebulb check [file.bulb.md] Type-check a bulb without running it
14
+ typebulb check [file.bulb.md] Type-check a bulb without running it ('-' reads the
15
+ bulb from stdin \u2014 validate an embed before emitting it).
14
16
  typebulb predict [file] Report the capability a bulb probably needs
15
17
  (fs / AI / server.ts) without running it.
16
18
  typebulb models List AI models for tb.ai, filtered by the API
@@ -86,9 +88,9 @@ Examples:
86
88
  typebulb my-editor.bulb.md
87
89
  typebulb --no-watch --port 8080 my-editor.bulb.md
88
90
  typebulb .
89
- `)}import*as X from"fs/promises";import*as nt from"path";import{pathToFileURL as Ns}from"url";var Qn={code:{path:"code.tsx",language:"typescript"},css:{path:"styles.css",language:"css"},html:{path:"index.html",language:"html"},config:{path:"config.json",language:"json"},notes:{path:"notes.md",language:"markdown"},data:{path:"data.txt",language:"text"},infer:{path:"infer.md",language:"markdown"},insight:{path:"insight.json",language:"json"},server:{path:"server.ts",language:"typescript"}};function fr(r){try{let e=r.split(`
90
- `),t=0;if(e[t]?.trim()!=="---")return null;t++;let n=[];for(;t<e.length&&e[t]?.trim()!=="---";)n.push(e[t]),t++;if(e[t]?.trim()!=="---")return null;t++;let s=Zn(n);if(!s)return null;let o=new Map;for(;t<e.length;){let a=e[t]?.trim()?.match(/^\*\*(.+)\*\*$/);if(a){let c=a[1].trim();for(t++;t<e.length&&e[t]?.trim()==="";)t++;let l=e[t]?.match(/^(`{3,})(\w*)\s*$/);if(!l){t++;continue}let p=l[1];t++;let d=[];for(;t<e.length&&!e[t]?.match(new RegExp(`^${p}\\s*$`));)d.push(e[t]),t++;t++,o.set(c,d.join(`
91
- `))}else t++}return{frontmatter:s,files:o}}catch{return null}}function Zn(r){let e={};for(let t of r){let n=t.indexOf(":");if(n===-1)continue;let s=t.slice(0,n).trim(),o=t.slice(n+1).trim();switch(s){case"format":e.format=o;break;case"name":e.name=es(o);break}}return!e.format?.startsWith("typebulb")||!e.name?null:e}function es(r){return r.startsWith('"')&&r.endsWith('"')?r.slice(1,-1).replace(/\\"/g,'"'):r.startsWith("'")&&r.endsWith("'")?r.slice(1,-1):r}function mr(r){let e=t=>r.files.get(Qn[t].path)||"";return{name:r.frontmatter.name,code:e("code"),css:e("css"),html:e("html"),config:e("config"),notes:e("notes"),data:e("data"),infer:e("infer"),insight:e("insight"),server:e("server")}}function ts(r){try{return JSON.parse(r),!0}catch{}return!!(/^\s*<[\s\S]*>/.test(r)||/^---\s*$/m.test(r)||/^\w[\w\s]*:[ \t]/m.test(r))}function hr(r){let e=r.trim();return e?ts(e)?[e]:r.split(/\n\n\n+/).map(t=>t.trim()).filter(Boolean):[]}function gr(r){if(!r.trim())return{};try{return JSON.parse(r)}catch{return{}}}import{transform as rs}from"sucrase";function Rt(r,e={}){let t=e.serverOnly?["typescript"]:["typescript","jsx"];try{let{code:n}=rs(r,{transforms:t,jsxRuntime:"automatic",jsxImportSource:e.jsxImportSource||"react",production:!0});return{code:n}}catch(n){return{code:"",error:String(n)}}}var we="https://esm.sh",xe="https://cdn.jsdelivr.net/npm/",Et="https://data.jsdelivr.com/v1/package/npm/";function br(r){let e=(r||"").replace(/^\/+/,"").replace(/\/+$/,"");return e?e.split("/"):[]}var y=class r{constructor(e,t,n){let s=typeof e=="string"?r.parse(e):e;this.name=s.name,this.version=ce(t??s.version),this.subpath=ce(n??s.subpath)}static parse(e){let t=br(e||"");if(!t.length)return new r({name:""});if(t[0].startsWith("@")){let s=t[0],[o,i]=yr(t[1]??""),a=ce(t.slice(2).join("/"));return new r({name:`${s}/${o}`,version:i,subpath:a})}else{let[s,o]=yr(t[0]),i=ce(t.slice(1).join("/"));return new r({name:s,version:o,subpath:i})}}static fromUrl(e){try{let t=new URL(e),n=new URL(we).host,s=new URL(xe).host;if(t.host===n){let o=br(t.pathname.replace(/^\/v\d+\//,"/"));if(!o.length)return;let i=o[0].startsWith("@")?`${o[0]}/${o[1]??""}`:o[0];return r.parse(i)}if(t.host===s){let o=t.pathname.split("/npm/")[1];if(!o)return;let i=o.split("/")[0]||"";return r.parse(i)}return}catch{return}}static versionFromUrl(e){return r.fromUrl(e)?.version}format(){let e=this.version?`${this.name}@${this.version}`:this.name;return this.subpath?`${e}/${this.subpath}`:e}root(){return this.name}static rootOf(e){return r.parse(e).name}withVersion(e){return new r({name:this.name,version:ce(e),subpath:this.subpath})}withPreferredVersion(e,t){let n=e||t;return n?this.withVersion(n):this}static isBare(e){if(!e||e.startsWith(".")||e.startsWith("/"))return!1;let t=e.toLowerCase();return!t.startsWith("http://")&&!t.startsWith("https://")}},ce=r=>r&&r.length?r:void 0,yr=r=>{let e=r.indexOf("@");return e<0?[r,void 0]:[r.slice(0,e),ce(r.slice(e+1))]};async function k(r){try{return await r()}catch{return}}var Se=class{constructor(e,t){this.cache=e,this.http=t,this.esmHost=we,this.jsDelivrBase=xe,this.jsDelivrMeta=Et,this.pinMs=1e4,this.versionsIndexMs=1440*60*1e3,this.metaTtlMs=10080*60*1e3,this.pinCache=new Map}normalizeRelative(e){let t=e||"";return t.startsWith("./")?t.slice(2):t.replace(/^\/+/,"")}ensureLeadingDotSlash(e){return e.startsWith("./")?e:`./${e}`}baseDir(e){let t=typeof e=="string"?new y(e):e;return`${this.jsDelivrBase}${t.name}${t.version?`@${t.version}`:""}/`}file(e,t){return new URL(this.normalizeRelative(t),this.baseDir(e)).toString()}packageJson(e){return this.file(e,"package.json")}buildEsmUrl(e,t={}){let{target:n="es2022",bundle:s=!1,external:o}=t,i=new URLSearchParams({target:n});return s&&i.append("bundle",""),o?.length&&i.append("external",o.join(",")),`${this.esmHost}/${e}?${i.toString()}`}async pinEsmUrl(e,t="es2022"){let n=this.buildEsmUrl(e,{target:t}),s=await k(()=>this.http.head(n));return s?.ok?s.url||n:void 0}async resolveExactVersion(e){let t=Date.now(),n=this.pinCache.get(e);if(n&&t-n.ts<this.pinMs)return n.value;let s=await this.tryResolveFromUrls([this.buildEsmUrl(e),`${this.esmHost}/${e}`]);return this.pinCache.set(e,{value:s,ts:t}),s}async tryResolveFromUrls(e){for(let t of e){let n=await k(()=>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 k(()=>this.http.getJson(`${this.jsDelivrMeta}${encodeURIComponent(e)}`));if(!n?.versions?.length){await this.cache.recordNegative(e);return}await this.cache.clearNegative(e);let s=n.distTags&&Object.keys(n.distTags).length?n.distTags:void 0;return await this.cache.setIndex(e,n.versions,s),n}parseVersionFromUrl(e){let t=y.fromUrl(e)?.version;return t&&/\d+\.\d+\.\d+/.test(t)?t:void 0}async fetchPackageMeta(e,t){let n=await this.cache.getMeta(e,t);if(n&&Date.now()-n.updatedAt<this.metaTtlMs){let{dependencies:p,peerDependencies:d,peerDependenciesMeta:m}=n;return{name:e,version:t,dependencies:p,peerDependencies:d,peerDependenciesMeta:m}}let s=this.packageJson(new y(`${e}@${t}`)),o=await k(()=>this.http.getJson(s));if(!o)return;let i=p=>p&&Object.keys(p).length?p:void 0,a=i(o.dependencies),c=i(o.peerDependencies),l=i(o.peerDependenciesMeta);return await this.cache.setMeta(e,t,a,c,l),{name:e,version:t,dependencies:a,peerDependencies:c,peerDependenciesMeta:l}}};var vr=r=>r.startsWith("@types/"),Pe=r=>Object.keys(r?.peerDependencies||{}).filter(e=>!vr(e)),kt=r=>Object.keys(r?.dependencies||{}).filter(e=>!vr(e)),ns=r=>Pe(r).filter(e=>!r?.peerDependenciesMeta?.[e]?.optional),Re=class{constructor(e){this.cdn=e}async resolve(e,t){let n=await this.fetchMeta(e),{allRoots:s,autoAddedPeers:o}=await this.expandWithPeers(n,t),i=this.computeFlags(s);return{allRoots:s,flags:i,autoAddedPeers:o}}async fetchMeta(e){return Promise.all(e.map(async({name:t,version:n})=>({name:t,version:n,meta:await this.cdn.fetchPackageMeta(t,n)})))}async expandWithPeers(e,t){let n=new Map(e.map(o=>[o.name,o])),s=[];for(let o of e)for(let i of ns(o.meta))!n.has(i)&&!s.some(a=>a.name===i)&&s.push({name:i,requiredBy:o.name});for(let{name:o,requiredBy:i}of s)try{let a=await t(o),c=await this.cdn.fetchPackageMeta(o,a);n.set(o,{name:o,version:a,meta:c})}catch(a){console.warn(`[typebulb] Failed to resolve peer "${o}" for "${i}":`,a)}return{allRoots:[...n.values()],autoAddedPeers:s.filter(o=>n.has(o.name))}}computeFlags(e){let t=new Set(e.flatMap(o=>Pe(o.meta))),n=new Map;for(let o of e)for(let i of kt(o.meta))n.set(i,(n.get(i)||0)+1);let s=new Set([...n.entries()].filter(([,o])=>o>=2).map(([o])=>o));return new Map(e.map(o=>[o.name,{isPeerRoot:t.has(o.name),hasPeers:Pe(o.meta).length>0,isSharedDep:s.has(o.name)}]))}};var Ee=class{constructor(e,t,n){this.cache=e,this.cdn=t,this.semver=n}selectVersionFromIndex(e,t,n){return this.semver.selectBestVersion(e,{range:t,distTags:n})}async learnExactVersion(e){let t=await k(()=>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.warn("[versionResolver] Rejecting invalid cached version for",e,":",n)}let s=await k(()=>this.cdn.fetchVersionsIndex(e));if(s?.versions?.length){let i=this.selectVersionFromIndex(s.versions,t,s.distTags);if(i){if(this.semver.isExactVersion(i))return await this.cache.setPinnedExact(e,t,i),i}else{console.warn("[versionResolver] Invalidating stale versions cache for",e,"- range",t,"not satisfied"),await this.cache.invalidateVersionsCache(e);let a=await k(()=>this.cdn.fetchVersionsIndex(e));if(a?.versions?.length){let c=this.selectVersionFromIndex(a.versions,t,a.distTags);if(c&&this.semver.isExactVersion(c))return await this.cache.setPinnedExact(e,t,c),c}}}let o=await this.cdn.resolveExactVersion(`${e}@${t}`);if(o&&this.semver.isExactVersion(o))return await this.cache.setPinnedExact(e,t,o),o}async effectivePackage(e,t){let n=new y(e),s=n.root(),o=t[s],i=o?await k(()=>this.cache.getPinnedExact(s,o))??await k(()=>this.resolveExactForRoot(s,o)):void 0;return{effectivePackage:i?n.withVersion(i).format():e,root:s,range:o,pinned:i}}};import{init as ss,parse as os}from"es-module-lexer";var le=class r{constructor(e,t,n,s){this.version=e,this.cdn=t,this.peer=n,this.cache=s}extractImportsSync(e){let t=new Set;for(let n of r.importPatterns){n.lastIndex=0;for(let s of e.matchAll(n))y.isBare(s[1])&&t.add(s[1])}return Array.from(t)}async extractImports(e){let t=new Set,n=s=>{y.isBare(s)&&t.add(s)};try{await ss;let[s]=os(e);s.forEach(o=>n(e.slice(o.s,o.e).trim()))}catch{return this.extractImportsSync(e)}return Array.from(t)}async buildImportMap(e,t,n){let s=(await this.extractImports(e)).filter(d=>!n?.has(y.rootOf(d))),o=[...new Set(s.map(y.rootOf))],i=await Promise.all(o.map(async d=>({name:d,version:await this.resolveVersion(d,t)}))),{allRoots:a,flags:c,autoAddedPeers:l}=await this.peer.resolve(i,d=>this.resolveVersion(d,t)),p=this.buildEntries([...s,...l.map(d=>d.name)],a,c,t);return{importMap:{imports:Object.fromEntries(p)},prefetchUrls:p.map(([,d])=>d)}}async resolveVersion(e,t){let n=t[e],s=n?`${e}@${n}`:e,o=await this.version.resolveExactForRoot(e,n);if(!o){let i=await k(()=>this.cdn.pinEsmUrl(s));if(!i)throw new Error(`Cannot resolve ${s}: no matching version is published (the package or version may not exist, or the registry was unreachable).`);o=y.versionFromUrl(i),o&&n&&await k(()=>this.cache.setPinnedExact(e,n,o))}if(!o)throw new Error(`Cannot resolve ${s}: no concrete version found.`);return o}buildEntries(e,t,n,s){let o=new Map(t.map(g=>[g.name,g])),i=g=>{let S=o.get(y.rootOf(g));return new y(g).withPreferredVersion(S.version,s[S.name]).format()},a=new Set([...n.entries()].filter(([,g])=>g.isPeerRoot||g.isSharedDep).map(([g])=>g)),c=new Set(e.filter(g=>g!==y.rootOf(g)).map(y.rootOf)),l=[],p=new Set,d=new Set(e.filter(g=>g===y.rootOf(g))),m=new Set;for(let g of e){let S=y.rootOf(g),F=o.get(S),{isPeerRoot:L,hasPeers:_,isSharedDep:u}=n.get(S),f=c.has(S),b=g!==S,v=!(L||u)&&(f||!_),T=this.singletonDepsOf(F,a),z=b&&d.has(S);z&&m.add(S);let N=z?[...T,S]:T.length?T:void 0;l.push([g,this.cdn.buildEsmUrl(i(g),{bundle:v,external:N})]),p.add(g)}let h=new Set([...a,...m]);for(let g of h)o.has(g)&&(p.has(g)||l.push([g,this.cdn.buildEsmUrl(i(g),{})]),l.push([`${g}/`,`${this.cdn.esmHost}/${i(g)}/`]));return l}singletonDepsOf(e,t){return[...new Set([...Pe(e.meta),...kt(e.meta)])].filter(n=>t.has(n))}};le.importPatterns=[/\bimport\s+(?:[^'";]*?from\s*)?['"]([^'"]+)['"]/g,/\bexport\s+[^'";]*?from\s*['"]([^'"]+)['"]/g];import{gt as wr,satisfies as is,maxSatisfying as Tt,major as as,prerelease as cs,rsort as ls,valid as ds}from"semver";var Je=class{cmp(e,t){return e===t?0:wr(e,t)?1:wr(t,e)?-1:0}satisfies(e,t){return!e||!e.trim()?!0:!!is(t,e,{includePrerelease:!0})}pickMaxSatisfying(e,t){if(!e?.length)return;let n=Tt(e,t,{includePrerelease:!0});return n===null?void 0:n}pickLatest(e){return e?.length?ls(e)[0]:void 0}selectBestVersion(e,t){if(!e?.length)return;let n=t?.range?.trim()||"*",s=t?.preferStable??!0,o=t?.distTags?.latest;if(o&&e.includes(o)&&this.satisfies(n,o))return o;if(s){let a=Tt(e,n,{includePrerelease:!1});if(a)return a}return Tt(e,n,{includePrerelease:!0})??void 0}majorOf(e){return as(e)}isPrerelease(e){return cs(e)!==null}isExactVersion(e){return ds(e)!==null}},Q=new Je;function xr(r,e){let t=new Se(r,e),n=new Re(t),s=new Ee(r,t,Q);return{packageService:new le(s,t,n,r),versionResolver:s,cdnClient:t,peerResolver:n}}import*as jr from"fs/promises";import*as $ from"path";var _t=[{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"}],Ct=[{name:"dom"},{name:"dom.iterable"},{name:"dom.asynciterable"}];var Sr=`
91
+ `)}import*as X from"fs/promises";import*as st from"path";import{pathToFileURL as Us}from"url";var ts={code:{path:"code.tsx",language:"typescript"},css:{path:"styles.css",language:"css"},html:{path:"index.html",language:"html"},config:{path:"config.json",language:"json"},notes:{path:"notes.md",language:"markdown"},data:{path:"data.txt",language:"text"},infer:{path:"infer.md",language:"markdown"},insight:{path:"insight.json",language:"json"},server:{path:"server.ts",language:"typescript"}};function mr(r){try{let e=r.split(`
92
+ `),t=0;if(e[t]?.trim()!=="---")return null;t++;let n=[];for(;t<e.length&&e[t]?.trim()!=="---";)n.push(e[t]),t++;if(e[t]?.trim()!=="---")return null;t++;let s=rs(n);if(!s)return null;let o=new Map;for(;t<e.length;){let a=e[t]?.trim()?.match(/^\*\*(.+)\*\*$/);if(a){let c=a[1].trim();for(t++;t<e.length&&e[t]?.trim()==="";)t++;let l=e[t]?.match(/^(`{3,})(\w*)\s*$/);if(!l){t++;continue}let p=l[1];t++;let d=[];for(;t<e.length&&!e[t]?.match(new RegExp(`^${p}\\s*$`));)d.push(e[t]),t++;t++,o.set(c,d.join(`
93
+ `))}else t++}return{frontmatter:s,files:o}}catch{return null}}function rs(r){let e={};for(let t of r){let n=t.indexOf(":");if(n===-1)continue;let s=t.slice(0,n).trim(),o=t.slice(n+1).trim();switch(s){case"format":e.format=o;break;case"name":e.name=ns(o);break}}return!e.format?.startsWith("typebulb")||!e.name?null:e}function ns(r){return r.startsWith('"')&&r.endsWith('"')?r.slice(1,-1).replace(/\\"/g,'"'):r.startsWith("'")&&r.endsWith("'")?r.slice(1,-1):r}function hr(r){let e=t=>r.files.get(ts[t].path)||"";return{name:r.frontmatter.name,code:e("code"),css:e("css"),html:e("html"),config:e("config"),notes:e("notes"),data:e("data"),infer:e("infer"),insight:e("insight"),server:e("server")}}function ss(r){try{return JSON.parse(r),!0}catch{}return!!(/^\s*<[\s\S]*>/.test(r)||/^---\s*$/m.test(r)||/^\w[\w\s]*:[ \t]/m.test(r))}function gr(r){let e=r.trim();return e?ss(e)?[e]:r.split(/\n\n\n+/).map(t=>t.trim()).filter(Boolean):[]}function br(r){if(!r.trim())return{};try{return JSON.parse(r)}catch{return{}}}import{transform as os}from"sucrase";function Et(r,e={}){let t=e.serverOnly?["typescript"]:["typescript","jsx"];try{let{code:n}=os(r,{transforms:t,jsxRuntime:"automatic",jsxImportSource:e.jsxImportSource||"react",production:!0});return{code:n}}catch(n){return{code:"",error:String(n)}}}var we="https://esm.sh",xe="https://cdn.jsdelivr.net/npm/",kt="https://data.jsdelivr.com/v1/package/npm/";function yr(r){let e=(r||"").replace(/^\/+/,"").replace(/\/+$/,"");return e?e.split("/"):[]}var y=class r{constructor(e,t,n){let s=typeof e=="string"?r.parse(e):e;this.name=s.name,this.version=ce(t??s.version),this.subpath=ce(n??s.subpath)}static parse(e){let t=yr(e||"");if(!t.length)return new r({name:""});if(t[0].startsWith("@")){let s=t[0],[o,i]=vr(t[1]??""),a=ce(t.slice(2).join("/"));return new r({name:`${s}/${o}`,version:i,subpath:a})}else{let[s,o]=vr(t[0]),i=ce(t.slice(1).join("/"));return new r({name:s,version:o,subpath:i})}}static fromUrl(e){try{let t=new URL(e),n=new URL(we).host,s=new URL(xe).host;if(t.host===n){let o=yr(t.pathname.replace(/^\/v\d+\//,"/"));if(!o.length)return;let i=o[0].startsWith("@")?`${o[0]}/${o[1]??""}`:o[0];return r.parse(i)}if(t.host===s){let o=t.pathname.split("/npm/")[1];if(!o)return;let i=o.split("/")[0]||"";return r.parse(i)}return}catch{return}}static versionFromUrl(e){return r.fromUrl(e)?.version}format(){let e=this.version?`${this.name}@${this.version}`:this.name;return this.subpath?`${e}/${this.subpath}`:e}root(){return this.name}static rootOf(e){return r.parse(e).name}withVersion(e){return new r({name:this.name,version:ce(e),subpath:this.subpath})}withPreferredVersion(e,t){let n=e||t;return n?this.withVersion(n):this}static isBare(e){if(!e||e.startsWith(".")||e.startsWith("/"))return!1;let t=e.toLowerCase();return!t.startsWith("http://")&&!t.startsWith("https://")}},ce=r=>r&&r.length?r:void 0,vr=r=>{let e=r.indexOf("@");return e<0?[r,void 0]:[r.slice(0,e),ce(r.slice(e+1))]};async function k(r){try{return await r()}catch{return}}var Se=class{constructor(e,t){this.cache=e,this.http=t,this.esmHost=we,this.jsDelivrBase=xe,this.jsDelivrMeta=kt,this.pinMs=1e4,this.versionsIndexMs=1440*60*1e3,this.metaTtlMs=10080*60*1e3,this.pinCache=new Map}normalizeRelative(e){let t=e||"";return t.startsWith("./")?t.slice(2):t.replace(/^\/+/,"")}ensureLeadingDotSlash(e){return e.startsWith("./")?e:`./${e}`}baseDir(e){let t=typeof e=="string"?new y(e):e;return`${this.jsDelivrBase}${t.name}${t.version?`@${t.version}`:""}/`}file(e,t){return new URL(this.normalizeRelative(t),this.baseDir(e)).toString()}packageJson(e){return this.file(e,"package.json")}buildEsmUrl(e,t={}){let{target:n="es2022",bundle:s=!1,external:o}=t,i=new URLSearchParams({target:n});return s&&i.append("bundle",""),o?.length&&i.append("external",o.join(",")),`${this.esmHost}/${e}?${i.toString()}`}async pinEsmUrl(e,t="es2022"){let n=this.buildEsmUrl(e,{target:t}),s=await k(()=>this.http.head(n));return s?.ok?s.url||n:void 0}async resolveExactVersion(e){let t=Date.now(),n=this.pinCache.get(e);if(n&&t-n.ts<this.pinMs)return n.value;let s=await this.tryResolveFromUrls([this.buildEsmUrl(e),`${this.esmHost}/${e}`]);return this.pinCache.set(e,{value:s,ts:t}),s}async tryResolveFromUrls(e){for(let t of e){let n=await k(()=>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 k(()=>this.http.getJson(`${this.jsDelivrMeta}${encodeURIComponent(e)}`));if(!n?.versions?.length){await this.cache.recordNegative(e);return}await this.cache.clearNegative(e);let s=n.distTags&&Object.keys(n.distTags).length?n.distTags:void 0;return await this.cache.setIndex(e,n.versions,s),n}parseVersionFromUrl(e){let t=y.fromUrl(e)?.version;return t&&/\d+\.\d+\.\d+/.test(t)?t:void 0}async fetchPackageMeta(e,t){let n=await this.cache.getMeta(e,t);if(n&&Date.now()-n.updatedAt<this.metaTtlMs){let{dependencies:p,peerDependencies:d,peerDependenciesMeta:m}=n;return{name:e,version:t,dependencies:p,peerDependencies:d,peerDependenciesMeta:m}}let s=this.packageJson(new y(`${e}@${t}`)),o=await k(()=>this.http.getJson(s));if(!o)return;let i=p=>p&&Object.keys(p).length?p:void 0,a=i(o.dependencies),c=i(o.peerDependencies),l=i(o.peerDependenciesMeta);return await this.cache.setMeta(e,t,a,c,l),{name:e,version:t,dependencies:a,peerDependencies:c,peerDependenciesMeta:l}}};var wr=r=>r.startsWith("@types/"),Pe=r=>Object.keys(r?.peerDependencies||{}).filter(e=>!wr(e)),Tt=r=>Object.keys(r?.dependencies||{}).filter(e=>!wr(e)),is=r=>Pe(r).filter(e=>!r?.peerDependenciesMeta?.[e]?.optional),Re=class{constructor(e){this.cdn=e}async resolve(e,t){let n=await this.fetchMeta(e),{allRoots:s,autoAddedPeers:o}=await this.expandWithPeers(n,t),i=this.computeFlags(s);return{allRoots:s,flags:i,autoAddedPeers:o}}async fetchMeta(e){return Promise.all(e.map(async({name:t,version:n})=>({name:t,version:n,meta:await this.cdn.fetchPackageMeta(t,n)})))}async expandWithPeers(e,t){let n=new Map(e.map(o=>[o.name,o])),s=[];for(let o of e)for(let i of is(o.meta))!n.has(i)&&!s.some(a=>a.name===i)&&s.push({name:i,requiredBy:o.name});for(let{name:o,requiredBy:i}of s)try{let a=await t(o),c=await this.cdn.fetchPackageMeta(o,a);n.set(o,{name:o,version:a,meta:c})}catch(a){console.warn(`[typebulb] Failed to resolve peer "${o}" for "${i}":`,a)}return{allRoots:[...n.values()],autoAddedPeers:s.filter(o=>n.has(o.name))}}computeFlags(e){let t=new Set(e.flatMap(o=>Pe(o.meta))),n=new Map;for(let o of e)for(let i of Tt(o.meta))n.set(i,(n.get(i)||0)+1);let s=new Set([...n.entries()].filter(([,o])=>o>=2).map(([o])=>o));return new Map(e.map(o=>[o.name,{isPeerRoot:t.has(o.name),hasPeers:Pe(o.meta).length>0,isSharedDep:s.has(o.name)}]))}};var Ee=class{constructor(e,t,n){this.cache=e,this.cdn=t,this.semver=n}selectVersionFromIndex(e,t,n){return this.semver.selectBestVersion(e,{range:t,distTags:n})}async learnExactVersion(e){let t=await k(()=>this.cdn.fetchVersionsIndex(e));if(t?.versions?.length){let n=this.semver.selectBestVersion(t.versions,{distTags:t.distTags});if(n)return n}return this.cdn.resolveExactVersion(e)}async resolveExactForRoot(e,t){if(!t)return this.learnExactVersion(e);let n=await this.cache.getPinnedExact(e,t);if(n){if(this.semver.isExactVersion(n))return n;console.debug("[typebulb] cached version for",e,"is not exact (",n,"); re-resolving from registry")}let s=await k(()=>this.cdn.fetchVersionsIndex(e));if(s?.versions?.length){let i=this.selectVersionFromIndex(s.versions,t,s.distTags);if(i){if(this.semver.isExactVersion(i))return await this.cache.setPinnedExact(e,t,i),i}else{console.debug("[typebulb] refreshing version cache for",e,"(",t,"not in cached set \u2014 likely a new release)"),await this.cache.invalidateVersionsCache(e);let a=await k(()=>this.cdn.fetchVersionsIndex(e));if(a?.versions?.length){let c=this.selectVersionFromIndex(a.versions,t,a.distTags);if(c&&this.semver.isExactVersion(c))return await this.cache.setPinnedExact(e,t,c),c}}}let o=await this.cdn.resolveExactVersion(`${e}@${t}`);if(o&&this.semver.isExactVersion(o))return await this.cache.setPinnedExact(e,t,o),o}async effectivePackage(e,t){let n=new y(e),s=n.root(),o=t[s],i=o?await k(()=>this.cache.getPinnedExact(s,o))??await k(()=>this.resolveExactForRoot(s,o)):void 0;return{effectivePackage:i?n.withVersion(i).format():e,root:s,range:o,pinned:i}}};import{init as as,parse as cs}from"es-module-lexer";var le=class r{constructor(e,t,n,s){this.version=e,this.cdn=t,this.peer=n,this.cache=s}extractImportsSync(e){let t=new Set;for(let n of r.importPatterns){n.lastIndex=0;for(let s of e.matchAll(n))y.isBare(s[1])&&t.add(s[1])}return Array.from(t)}async extractImports(e){let t=new Set,n=s=>{y.isBare(s)&&t.add(s)};try{await as;let[s]=cs(e);s.forEach(o=>n(e.slice(o.s,o.e).trim()))}catch{return this.extractImportsSync(e)}return Array.from(t)}async buildImportMap(e,t,n){let s=(await this.extractImports(e)).filter(d=>!n?.has(y.rootOf(d))),o=[...new Set(s.map(y.rootOf))],i=await Promise.all(o.map(async d=>({name:d,version:await this.resolveVersion(d,t)}))),{allRoots:a,flags:c,autoAddedPeers:l}=await this.peer.resolve(i,d=>this.resolveVersion(d,t)),p=this.buildEntries([...s,...l.map(d=>d.name)],a,c,t);return{importMap:{imports:Object.fromEntries(p)},prefetchUrls:p.map(([,d])=>d)}}async resolveVersion(e,t){let n=t[e],s=n?`${e}@${n}`:e,o=await this.version.resolveExactForRoot(e,n);if(!o){let i=await k(()=>this.cdn.pinEsmUrl(s));if(!i)throw new Error(`Cannot resolve ${s}: no matching version is published (the package or version may not exist, or the registry was unreachable).`);o=y.versionFromUrl(i),o&&n&&await k(()=>this.cache.setPinnedExact(e,n,o))}if(!o)throw new Error(`Cannot resolve ${s}: no concrete version found.`);return o}buildEntries(e,t,n,s){let o=new Map(t.map(g=>[g.name,g])),i=g=>{let S=o.get(y.rootOf(g));return new y(g).withPreferredVersion(S.version,s[S.name]).format()},a=new Set([...n.entries()].filter(([,g])=>g.isPeerRoot||g.isSharedDep).map(([g])=>g)),c=new Set(e.filter(g=>g!==y.rootOf(g)).map(y.rootOf)),l=[],p=new Set,d=new Set(e.filter(g=>g===y.rootOf(g))),m=new Set;for(let g of e){let S=y.rootOf(g),B=o.get(S),{isPeerRoot:N,hasPeers:_,isSharedDep:u}=n.get(S),f=c.has(S),b=g!==S,v=!(N||u)&&(f||!_),T=this.singletonDepsOf(B,a),z=b&&d.has(S);z&&m.add(S);let F=z?[...T,S]:T.length?T:void 0;l.push([g,this.cdn.buildEsmUrl(i(g),{bundle:v,external:F})]),p.add(g)}let h=new Set([...a,...m]);for(let g of h)o.has(g)&&(p.has(g)||l.push([g,this.cdn.buildEsmUrl(i(g),{})]),l.push([`${g}/`,`${this.cdn.esmHost}/${i(g)}/`]));return l}singletonDepsOf(e,t){return[...new Set([...Pe(e.meta),...Tt(e.meta)])].filter(n=>t.has(n))}};le.importPatterns=[/\bimport\s+(?:[^'";]*?from\s*)?['"]([^'"]+)['"]/g,/\bexport\s+[^'";]*?from\s*['"]([^'"]+)['"]/g];import{gt as xr,satisfies as ls,maxSatisfying as _t,major as ds,prerelease as us,rsort as ps,valid as fs}from"semver";var Ve=class{cmp(e,t){return e===t?0:xr(e,t)?1:xr(t,e)?-1:0}satisfies(e,t){return!e||!e.trim()?!0:!!ls(t,e,{includePrerelease:!0})}pickMaxSatisfying(e,t){if(!e?.length)return;let n=_t(e,t,{includePrerelease:!0});return n===null?void 0:n}pickLatest(e){return e?.length?ps(e)[0]:void 0}selectBestVersion(e,t){if(!e?.length)return;let n=t?.range?.trim()||"*",s=t?.preferStable??!0,o=t?.distTags?.latest;if(o&&e.includes(o)&&this.satisfies(n,o))return o;if(s){let a=_t(e,n,{includePrerelease:!1});if(a)return a}return _t(e,n,{includePrerelease:!0})??void 0}majorOf(e){return ds(e)}isPrerelease(e){return us(e)!==null}isExactVersion(e){return fs(e)!==null}},Q=new Ve;function Sr(r,e){let t=new Se(r,e),n=new Re(t),s=new Ee(r,t,Q);return{packageService:new le(s,t,n,r),versionResolver:s,cdnClient:t,peerResolver:n}}import*as Br from"fs/promises";import*as $ from"path";var Ct=[{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"}],Ot=[{name:"dom"},{name:"dom.iterable"},{name:"dom.asynciterable"}];var Pr=`
92
94
  /**
93
95
  * Get raw data chunk from the Data tab.
94
96
  * @param index - Chunk index (0-based). Separate chunks with 2 blank lines.
@@ -99,7 +101,7 @@ Examples:
99
101
  * @param index - Chunk index (0-based)
100
102
  * @throws If chunk is not valid JSON/JSON-ish
101
103
  */
102
- json<T = unknown>(index: number): T;`,Pr=`
104
+ json<T = unknown>(index: number): T;`,Rr=`
103
105
  /**
104
106
  * Get the insight data produced by the inference layer.
105
107
  *
@@ -108,7 +110,7 @@ Examples:
108
110
  *
109
111
  * @returns The parsed insight JSON, or undefined if no insight is available
110
112
  */
111
- insight<T = unknown>(): T | undefined;`,Rr=`
113
+ insight<T = unknown>(): T | undefined;`,Er=`
112
114
  /**
113
115
  * General-purpose AI call.
114
116
  *
@@ -125,7 +127,7 @@ Examples:
125
127
  model?: string;
126
128
  /** Enable/disable web search. Default: on for BYOK, always off for free model. */
127
129
  webSearch?: boolean;
128
- }): Promise<{ text: string }>;`,Er=`
130
+ }): Promise<{ text: string }>;`,kr=`
129
131
  /**
130
132
  * Returns AI models available to the current user.
131
133
  * Models are filtered by the user's configured API keys.
@@ -140,7 +142,7 @@ Examples:
140
142
  friendlyName: string;
141
143
  /** Provider display name, e.g. "Anthropic" */
142
144
  providerName: string;
143
- }>>;`,us="\n /**\n * The bulb's theme override (`<html data-theme>`).\n *\n * - Get: the current override \u2014 `'dark'` | `'light'`, or `undefined` when\n * following the OS preference.\n * - Set `'dark'`/`'light'` to force and persist it (per-bulb); set\n * `undefined` to clear the override and follow the OS again.\n *\n * Drives `<html data-theme>`, so render off `html[data-theme=\"\u2026\"]` selectors\n * (or observe the attribute) rather than reading `tb.theme`.\n */\n theme: 'light' | 'dark' | undefined;",kr=`
145
+ }>>;`,ms="\n /**\n * The bulb's theme override (`<html data-theme>`).\n *\n * - Get: the current override \u2014 `'dark'` | `'light'`, or `undefined` when\n * following the OS preference.\n * - Set `'dark'`/`'light'` to force and persist it (per-bulb); set\n * `undefined` to clear the override and follow the OS again.\n *\n * Drives `<html data-theme>`, so render off `html[data-theme=\"\u2026\"]` selectors\n * (or observe the attribute) rather than reading `tb.theme`.\n */\n theme: 'light' | 'dark' | undefined;",Tr=`
144
146
  /**
145
147
  * The mode this bulb is running in.
146
148
  *
@@ -150,7 +152,7 @@ Examples:
150
152
  * - \`'embedded'\` \u2014 Running as a bulb embedded inside another bulb (sandboxed,
151
153
  * client-only: AI, filesystem, and server RPC are unavailable)
152
154
  */
153
- mode: 'local' | 'editor' | 'published' | 'embedded';`,Tr=`
155
+ mode: 'local' | 'editor' | 'published' | 'embedded';`,_r=`
154
156
  /**
155
157
  * Local filesystem access (CLI only).
156
158
  *
@@ -164,7 +166,7 @@ Examples:
164
166
  readBytes(path: string): Promise<Uint8Array>;
165
167
  /** Write text or raw bytes to a file. Creates parent directories if needed. */
166
168
  write(path: string, content: string | Uint8Array): Promise<boolean>;
167
- };`,ps=`
169
+ };`,hs=`
168
170
  /**
169
171
  * Server-side function proxy. The built-in \`log\` prints to CLI stdout
170
172
  * (falls back to console.log on web). On the server side, this object only
@@ -172,7 +174,7 @@ Examples:
172
174
  */
173
175
  server: {
174
176
  log(...args: any[]): Promise<void>;
175
- };`,fs=`
177
+ };`,gs=`
176
178
  /**
177
179
  * Async value inspector for tensor-like objects.
178
180
  *
@@ -239,7 +241,7 @@ Examples:
239
241
  *
240
242
  * @returns The full canonical URL
241
243
  */
242
- url(): Promise<string>;`,ms=`
244
+ url(): Promise<string>;`,bs=`
243
245
  /**
244
246
  * Server-side function proxy.
245
247
  *
@@ -252,18 +254,18 @@ Examples:
252
254
  * Typebulb utilities namespace.
253
255
  * Type \`tb.\` to discover available helpers.
254
256
  */
255
- declare const tb: {${Sr}${fs}${Pr}${ms}${Rr}${Tr}${Er}${us}${kr}
257
+ declare const tb: {${Pr}${gs}${Rr}${bs}${Er}${_r}${kr}${ms}${Tr}
256
258
  };
257
259
  `,It=`
258
260
  /**
259
261
  * Typebulb utilities namespace (server-side).
260
262
  * Type \`tb.\` to discover available helpers.
261
263
  */
262
- declare const tb: {${Sr}${Pr}${Rr}${Tr}${ps}${Er}${kr}
264
+ declare const tb: {${Pr}${Rr}${Er}${_r}${hs}${kr}${Tr}
263
265
  };
264
- `;var Z=class{constructor(e){this.store=e}async isNegative(e){let t=await Ve(()=>this.store.get(e));return!!t&&t.until>Date.now()}async recordNegative(e){let n=((await Ve(()=>this.store.get(e)))?.attempts||0)+1;await Ve(()=>this.store.set(e,{until:Date.now()+hs(n),attempts:n}))}async clearNegative(e){await Ve(()=>this.store.delete(e))}};function hs(r){return Math.min(9e5*Math.pow(2,Math.max(0,r-1)),864e5)}async function Ve(r){try{return await r()}catch{return}}import xs from"p-limit";import{resolve as _r}from"resolve.exports";var de=class{constructor(e){this.fetchDts=e}fetchDtsText(e){return this.tryUrls([e])}async tryUrls(e){for(let t of e){let n=await this.fetchDts(t);if(n&&(this.looksLikeDts(n.dts)||/\.(d\.ts|d\.mts)(?:[?#].*)?$/i.test(n.url)||/[?&]dts(?:[&#]|$)/i.test(n.url)))return n}}looksLikeDts(e){return/^\s*export\s*\{\s*\}\s*;?\s*$/m.test(e)?!0:/declare\s+(module|namespace|class|interface|function|const|var|let)/.test(e)||/interface\s+\w+/.test(e)||/type\s+\w+\s*=/.test(e)}};var G={maxRelativeTypeRefs:500,maxBareDeps:8,maxBareDepth:3,prefetchConcurrency:4,negativeTtlMs:1e4},ke=["index.d.ts","index.d.mts"],Te=/\.d\.(ts|mts)$/i;function Ot(r){if(Te.test(r))return!0;try{return new URL(r,"file://").search.includes("dts")}catch{return r.includes("?")&&r.includes("dts")}}function He(r){return[`${r}.d.ts`,`${r}.d.mts`]}async function _e(r,{retries:e=2,timeoutMs:t=15e3,init:n}={}){for(let s=0;s<=e;s++){let o=new AbortController,i=setTimeout(()=>o.abort(),t);try{let a=await fetch(r,{...n,signal:o.signal});if(gs(a.status)&&s<e)continue;return a}catch{if(s<e)continue;return}finally{clearTimeout(i)}}}function gs(r){return r===408||r===429||r>=500&&r<600}var Ce=class extends de{constructor(e,t){super(e),this.cdnClient=t}async loadPackageAtVersionedRoot(e,t){let n=this.cdnClient.packageJson(new y({name:e,version:t})),s=await _e(n);if(!s?.ok)return;let o;try{o=await s.json()}catch{return}if(o)return{pkg:o,baseDir:this.cdnClient.baseDir(new y({name:e,version:t??o.version})),version:t}}extractPathFromResult(e){if(typeof e=="string")return e;if(Array.isArray(e))return e.find(t=>typeof t=="string")}async tryUntilSuccess(e,t){for(let n of e){let s=await t(n);if(s)return s}}async resolveFromSelected(e,t){if(e.kind==="types"){let s=this.cdnClient.normalizeRelative(e.path);if(!s||s==="/"||s===".")return this.tryUntilSuccess([...ke],t);if(!Te.test(s)){let o=await this.tryUntilSuccess(this.declarationCandidatesFor(s),t);if(o)return o}return t(s)}let n=this.declarationCandidatesFor(e.path);return this.tryUntilSuccess([...ke,...n],t)}toResolutionResult(e){return{kind:Te.test(e)?"types":"probe",path:e}}resolveExportsPath(e,t){let n=t||".",s=e;try{let o=this.extractPathFromResult(_r(s,n,{conditions:["types"]}));if(o)return o}catch{}try{return this.extractPathFromResult(_r(s,n,{browser:!0,conditions:["import","default","module","browser","node"]}))}catch{return}}async resolve(e){try{let t=y.parse(e),{pkg:n,baseDir:s}=await this.loadPackageAtVersionedRoot(t.name,t.version)||{};if(!n||!s)return;let o={name:t.name,version:t.version},i=new y(o).format(),a=new y({...o,subpath:t.subpath}).format(),c=d=>this.fetchCandidateFrom(s,t.name,d);if(t.subpath){let d=this.cdnClient.ensureLeadingDotSlash(t.subpath),m=this.resolveExportsPath(n,d);if(m){let g=await this.resolveFromSelected(this.toResolutionResult(m),c);if(g)return{...g,resolvedPkg:a}}let h=await this.tryUntilSuccess(this.declarationCandidatesFor(d),c);if(h)return{...h,resolvedPkg:a}}let l=n.types??n.typings;if(l){let d=await this.resolveFromSelected({kind:"types",path:l},c);if(d)return{...d,resolvedPkg:i}}let p=this.resolveExportsPath(n,".");if(p){let d=await this.resolveFromSelected(this.toResolutionResult(p),c);if(d)return{...d,resolvedPkg:i}}return}catch{return}}async fetchCandidateFrom(e,t,n){let s=this.cdnClient.normalizeRelative(n),o=new URL(s,e).toString(),i=await this.fetchDtsText(o);return i?{dts:i.dts,url:i.url,resolvedPkg:t}:void 0}declarationCandidatesFor(e){if(!e||e==="./"||e==="/")return[...ke];let t=e.replace(/\.(mjs|cjs|js|mts|cts|ts)$/i,""),n=He(t),s=t.endsWith("/")?t:`${t}/`;return n.push(...He(`${s}index`)),n}};import{gunzipSync as bs}from"fflate";var ue=class{async fetchAndExtract(e,t){let n=this.getTarballUrl(e,t),s=await _e(n,{timeoutMs:3e4});if(!s?.ok)return new Map;let o=new Uint8Array(await s.arrayBuffer());return this.extractDtsFiles(o)}getTarballUrl(e,t){return`https://registry.npmjs.org/${e.replace("/","%2F")}/-/${e.split("/").pop()}-${t}.tgz`}normalizeTarPath(e){let t=e.replace(/^package\//,""),n=t.indexOf("/");return n>0?t.substring(n+1):t}extractDtsFiles(e){let t=new Map;try{let n=bs(e),s=new TextDecoder("utf-8"),o=0;for(;o<n.length-512;){let i=n.slice(o,o+512);if(i[0]===0)break;let a=i.slice(0,100),c=a.indexOf(0),l=s.decode(a.slice(0,c>0?c:100)).trim(),p=i.slice(124,136),d=s.decode(p).trim().replace(/\0/g,""),m=parseInt(d,8)||0,h=String.fromCharCode(i[156]);if(o+=512,(h==="0"||h==="\0")&&(l.endsWith(".d.ts")||l.endsWith(".d.mts"))){let g=n.slice(o,o+m);t.set(this.normalizeTarPath(l),s.decode(g))}o+=Math.ceil(m/512)*512}}catch{}return t}},ys=new ue;var Ae=class extends de{constructor(e,t,n,s=new ue){super(e),this.cdnClient=t,this.cache=n,this.tarballFetcher=s}typesNameCandidates(e){let t=e.startsWith("@")?e.slice(1).replace("/","__"):e;return t.includes(".")?[t,t.split(".").join("-"),t.split(".").join("")]:[t]}selectTypesVersion(e,t,n){try{if(n){let o=Q.majorOf(n),i=e.filter(a=>Q.majorOf(a)===o);if(i.length)return i.sort((a,c)=>Q.cmp(c,a))[0]}let s=t?.latest;return s&&e.includes(s)?s:e[0]}catch{return e[0]}}async fetchFromVersionedRoot(e,t){let n=new y(e),s=n.version;if(!s)return;let o;try{o=await this.tarballFetcher.fetchAndExtract(n.name,s)}catch{return}if(!o||o.size===0)return;for(let[a,c]of o.entries()){let l=this.cdnClient.file(e,a);try{await this.cache.setCachedFile(l,c)}catch{}}let i=t.subpath?[t.subpath+".d.ts",t.subpath+"/index.d.ts"]:["index.d.ts"];for(let a of i){let c=o.get(a);if(c)return{dts:c,url:this.cdnClient.file(e,a),resolvedPkg:t.subpath?new y(t).format():t.name}}}async resolve(e){let t=y.parse(e);if(t.name)for(let n of this.typesNameCandidates(t.name)){let s=`@types/${n}`,o;try{o=await this.cdnClient.fetchVersionsIndex(s)}catch{continue}if(!o?.versions?.length)continue;let i=this.selectTypesVersion(o.versions,o.distTags,t.version),a=await this.fetchFromVersionedRoot(`${s}@${i}`,t);if(a)return a}}};var Ie=class{collectRelativeTypeRefs(e){return this.collectRefs(e).filter(t=>t.startsWith("./")||t.startsWith("../"))}collectBareModuleRefs(e){return this.collectRefs(e).filter(t=>this.isBare(t))}collectRefs(e){let t=new Set,n=(s,o)=>(t.add(s[o]),null);return this.matchAll(e,/(import|export)\s+[^'"\n]*from\s*['"]([^'"\n]+)['"]/,s=>n(s,2)),this.matchAll(e,/export\s*\*\s*from\s*['"]([^'"\n]+)['"]/,s=>n(s,1)),Array.from(t)}matchAll(e,t,n){let s=[];try{let o=new RegExp(t.source,"g"),i;for(;i=o.exec(e);){let a=n(i);a!==null&&s.push(a)}}catch{}return s}isBare(e){return!(e.startsWith("./")||e.startsWith("../")||e.startsWith("file:")||e.startsWith("http://")||e.startsWith("https://"))}};var Cr="file:///node_modules",Oe=class{constructor(){this.epoch=0,this.listeners=new Set}getEpoch(){return this.epoch}bumpEpoch(){this.epoch+=1;for(let e of this.listeners)try{e(this.epoch)}catch{}return this.epoch}onEpochChange(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}epochDir(){return`__tsepoch_${this.epoch}`}pathForMain(e){return`${Cr}/${this.epochDir()}/${e}/index.d.ts`}pathFor(e,t){let n=vs(t);return`${Cr}/${this.epochDir()}/${e}/${n}`}};function vs(r){let e=r||"";return e.startsWith("./")?e.slice(2):e.replace(/^\/+/,"")}import{LRUCache as ws}from"lru-cache";function $t(r){let e=new ws({ttl:1e4,max:500}),t=new Map;return async function(s){try{if(await r.isNegative(s))return;let o=e.get(s);if(o&&Date.now()-o<1e4)return;let i=await r.getCachedFile(s);if(i)return{dts:i,url:s};let a=t.get(s);if(a)return a;let c=(async()=>{let l=await fetch(s,{cache:"no-store"});if(!l.ok){l.status===404&&(e.set(s,Date.now()),await r.recordNegative(s));return}let p=await l.text(),d=l.url||s;return await r.clearNegative(s),await r.setCachedFile(d,p),{dts:p,url:d}})();return t.set(s,c),await c.finally(()=>t.delete(s))}catch{return}}}var qe=class{constructor(e){this.inFlight=new Map,this.scanner=new Ie,this.cache=e.cache,this.cdnClient=e.cdnClient,this.versionResolver=e.versionResolver,this.packageService=e.packageService,this.fetchDts=$t(e.cache),this.typescriptProvider=new Ce(this.fetchDts,e.cdnClient),this.definitelyTypedProvider=new Ae(this.fetchDts,e.cdnClient,e.cache),this.virtualFs=new Oe}withInFlight(e,t){let n=this.inFlight.get(e);if(n)return n;let s=t().finally(()=>this.inFlight.delete(e));return this.inFlight.set(e,s),s}invalidate(){this.virtualFs.bumpEpoch(),this.inFlight.clear()}capArray(e,t){return e.length<=t?e:e.slice(0,t)}pushFileIfNew(e,t,n){e.some(s=>s.path===t)||e.push({path:t,content:n})}createStubDef(e){let t=this.virtualFs.pathForMain(e);return{pkg:e,mainPath:t,files:[{path:t,content:"export const _shim: any; export default _shim;"}],shims:[{module:e,path:t}]}}async trySubpathWithRootFallback(e,t){let n=new y(e);return n.subpath?this.fetchRootDts(n.name,t):void 0}async fetchViaProviders(e){for(let t of[this.typescriptProvider,this.definitelyTypedProvider])try{let n=await t.resolve(e);if(n?.dts)return n}catch{}}subpathsMatch(e,t){return new y(e).subpath===new y(t).subpath}async fetchRootDts(e,t){let{effectivePackage:n,root:s,pinned:o}=await this.versionResolver.effectivePackage(e,t),i=await this.cache.getCachedDts(n);if(i?.content){let c=i.url??this.cdnClient.file(o?`${s}@${o}`:s,"index.d.ts");return{dts:i.content,url:c,resolvedPkg:n}}let a;try{a=await this.fetchViaProviders(n)}catch{return}if(!(!a?.dts||!a.url)){try{await this.cache.setCachedFile(a.url,a.dts)}catch{}if(this.subpathsMatch(n,a.resolvedPkg||n)){try{await this.cache.setCachedDts(n,a.dts,a.url)}catch{}return a}}}extractPackageRootUrl(e){let t=e.pathname.match(/^(.+@[^/]+\/)/);return t?new URL(t[1],e.origin):new URL("./",e)}toVirtualPath(e,t,n){let s=t.pathname.startsWith(e.pathname)?t.pathname.slice(e.pathname.length):`__deps__/${encodeURIComponent(t.toString()).replace(/%/g,"_")}.d.ts`;return this.virtualFs.pathFor(n,s)}computeEntryPath(e,t){if(!e)return{mainPath:this.virtualFs.pathForMain(t),packageRootUrl:void 0};let n=new URL(e),s=this.extractPackageRootUrl(n);return{mainPath:this.toVirtualPath(s,n,t),packageRootUrl:s}}async expandRelativeRefs(e,t,n,s,o=new Set,i){if(!o.has(t)&&(o.add(t),!(o.size>G.maxRelativeTypeRefs)))try{let a=new URL(t),c=new URL("./",a);i??(i=this.extractPackageRootUrl(a));let l=this.capArray(this.scanner.collectRelativeTypeRefs(e),G.maxRelativeTypeRefs);for(let p of l)await this.tryRelativeRef(p,c,i,n,s,o)}catch{}}async tryRelativeRef(e,t,n,s,o,i){try{let a=new URL(e,t),c=a.pathname+a.search,l=Ot(c)?[c]:this.typescriptProvider.declarationCandidatesFor(c);for(let p of l){let m=new URL(p,a).toString();if(i.has(m))return;let h=await this.fetchDts(m);if(h?.dts){let g=this.toVirtualPath(n,new URL(h.url),s);this.pushFileIfNew(o,g,h.dts),await this.expandRelativeRefs(h.dts,h.url,s,o,i,n);return}}}catch{}}isDifferentPackage(e,t){return e===t?!1:new y(e).name!==new y(t).name}ambientlyDeclares(e,t){for(let n of e.matchAll(/declare\s+module\s+['"]([^'"]+)['"]/g)){let s=n[1];if(s===t||s.endsWith("/*")&&t.startsWith(s.slice(0,-1)))return!0}return!1}markFileAmbient(e,t){let n=e.find(s=>s.path===t);n&&(n.ambient=!0)}async prefetchBareDeps(e,t,n,s,o){try{let i=this.capArray(this.scanner.collectBareModuleRefs(e),G.maxBareDeps).filter(l=>this.isDifferentPackage(l,t));if(!i.length)return;let a=new Set([t]),c=xs(G.prefetchConcurrency);await Promise.all(i.map(l=>c(()=>this.prefetchBareDepsRecursive(l,n,s,G.maxBareDepth,a,o).catch(()=>{}))))}catch{}}async prefetchBareDepsRecursive(e,t,n,s,o,i){if(s<=0||o.has(e))return;o.add(e);let a=await this.fetchRootDts(e,i);if(!a?.dts)return;let c=a.resolvedPkg||e,l=this.virtualFs.pathForMain(c);this.pushFileIfNew(t,l,a.dts),this.ambientlyDeclares(a.dts,e)?this.markFileAmbient(t,l):n.push({module:e,path:l}),a.url&&await this.expandRelativeRefs(a.dts,a.url,c,t);let p=this.capArray(this.scanner.collectBareModuleRefs(a.dts),G.maxBareDeps).filter(d=>!o.has(d));for(let d of p)await this.prefetchBareDepsRecursive(d,t,n,s-1,o,i)}async resolve(e,t,n){let s=await this.packageService.extractImports(e),o=n?[...s,...n]:s;return(await Promise.all(o.map(a=>this.resolveOne(a,t)))).filter(a=>!!a)}async resolveOne(e,t){let{effectivePackage:n}=await this.versionResolver.effectivePackage(e,t);return this.withInFlight(n,async()=>{let s=await this.fetchRootDts(e,t)??await this.trySubpathWithRootFallback(e,t);return s?this.buildDefFromContent(e,s,s.resolvedPkg||e,t):this.createStubDef(e)})}async buildDefFromContent(e,t,n,s){let{dts:o,url:i,resolvedPkg:a}=t,c=new y(a||n),l=c.version?`${c.name}@${c.version}`:c.name,{mainPath:p,packageRootUrl:d}=this.computeEntryPath(i,l),m=[{path:p,content:o}],h=[];i&&await this.expandRelativeRefs(o,i,l,m,void 0,d);let g=m.map(_=>_.content).join(`
265
- `);await this.prefetchBareDeps(g,l,m,h,s);let S=c.format(),F=e===S?[e]:[e,S],L=F.some(_=>this.ambientlyDeclares(o,_));return L?this.markFileAmbient(m,p):h.push(...F.map(_=>({module:_,path:p}))),{pkg:e,mainPath:p,files:m,shims:h,ambient:L}}};function Dt(r){return new qe(r)}import*as B from"fs/promises";import*as U from"path";import*as Or from"os";import*as Mt from"fs/promises";import*as Ar from"crypto";function O(r){return Ar.createHash("sha1").update(r).digest("hex")}async function ee(r){try{return JSON.parse(await Mt.readFile(r,"utf8"))}catch{return}}async function ze(r){try{return await Mt.readFile(r,"utf8")}catch{return}}var Ir=1,K=U.join(Or.homedir(),".typebulb","cache"),$e=U.join(K,"packages"),De=U.join(K,"proxy"),Ge=U.join(K,"dts"),Ss=U.join(K,"emit"),jt;function x(){return jt||(jt=Ps()),jt}function Ke(r,e){return U.join(Ss,O(r),e)}async function Ps(){await B.mkdir(K,{recursive:!0});let r=U.join(K,"version.json");if((await Rs(r))?.version===Ir)return;let t=await B.readdir(K).catch(()=>[]);await Promise.all(t.map(n=>B.rm(U.join(K,n),{recursive:!0,force:!0}))),await B.writeFile(r,JSON.stringify({version:Ir})+`
266
- `,"utf8")}async function Rs(r){try{let e=await B.readFile(r,"utf8");return JSON.parse(e)}catch{return}}import*as Y from"fs/promises";import*as $r from"path";async function C(r,e){await Y.mkdir($r.dirname(r),{recursive:!0});let t=`${r}.tmp-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;await Y.writeFile(t,e,"utf8"),await Y.rename(t,r).catch(async n=>{throw await Y.rm(t,{force:!0}).catch(()=>{}),n})}var pe=class{constructor(e){this.filePath=e}mem;loadPromise;load(){return this.mem?Promise.resolve(this.mem):(this.loadPromise||(this.loadPromise=ee(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 C(this.filePath,JSON.stringify(Object.fromEntries(e)))}};var Ft=$.join($e,"indexes"),Dr=$.join($e,"pinned"),Es=$.join($e,"meta"),ks=$.join($e,"negative.json"),fe=Symbol("missing"),Xe=class{pinnedMem=new Map;indexMem=new Map;metaMem=new Map;negativeCache=new Z(new pe(ks));async getPinnedExact(e,t){let n=`${e}@${t}`,s=this.pinnedMem.get(n);if(s!==void 0)return s===fe?void 0:s;await x();let o=await ze($.join(Dr,O(n)+".txt"));return this.pinnedMem.set(n,o??fe),o}async setPinnedExact(e,t,n){let s=`${e}@${t}`;this.pinnedMem.set(s,n),await x(),await C($.join(Dr,O(s)+".txt"),n)}async getIndex(e){let t=this.indexMem.get(e);if(t!==void 0)return t===fe?void 0:t;await x();let n=await ee($.join(Ft,Ye(e)+".json"));return this.indexMem.set(e,n??fe),n}async setIndex(e,t,n){let s={versions:t,distTags:n,updatedAt:Date.now()};this.indexMem.set(e,s),await x(),await C($.join(Ft,Ye(e)+".json"),JSON.stringify(s))}async invalidateVersionsCache(e){this.indexMem.delete(e),await jr.rm($.join(Ft,Ye(e)+".json"),{force:!0})}async isNegative(e){return await x(),this.negativeCache.isNegative(e)}async recordNegative(e){await x(),await this.negativeCache.recordNegative(e)}async clearNegative(e){await this.negativeCache.clearNegative(e)}async getMeta(e,t){let n=`${e}@${t}`,s=this.metaMem.get(n);if(s!==void 0)return s===fe?void 0:s;await x();let o=await ee(Mr(e,t));return this.metaMem.set(n,o??fe),o}async setMeta(e,t,n,s,o){let i={dependencies:n,peerDependencies:s,peerDependenciesMeta:o,updatedAt:Date.now()};this.metaMem.set(`${e}@${t}`,i),await x(),await C(Mr(e,t),JSON.stringify(i))}};function Mr(r,e){return $.join(Es,Ye(r),encodeURIComponent(e)+".json")}function Ye(r){return r.replace(/\//g,"__")}var Fr={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 Ts=new Xe,{packageService:Qe,versionResolver:Nr,cdnClient:Br,peerResolver:Ma}=xr(Ts,Fr);var Lr=`
266
+ `;var Z=class{constructor(e){this.store=e}async isNegative(e){let t=await He(()=>this.store.get(e));return!!t&&t.until>Date.now()}async recordNegative(e){let n=((await He(()=>this.store.get(e)))?.attempts||0)+1;await He(()=>this.store.set(e,{until:Date.now()+ys(n),attempts:n}))}async clearNegative(e){await He(()=>this.store.delete(e))}};function ys(r){return Math.min(9e5*Math.pow(2,Math.max(0,r-1)),864e5)}async function He(r){try{return await r()}catch{return}}import Rs from"p-limit";import{resolve as Cr}from"resolve.exports";var de=class{constructor(e){this.fetchDts=e}fetchDtsText(e){return this.tryUrls([e])}async tryUrls(e){for(let t of e){let n=await this.fetchDts(t);if(n&&(this.looksLikeDts(n.dts)||/\.(d\.ts|d\.mts)(?:[?#].*)?$/i.test(n.url)||/[?&]dts(?:[&#]|$)/i.test(n.url)))return n}}looksLikeDts(e){return/^\s*export\s*\{\s*\}\s*;?\s*$/m.test(e)?!0:/declare\s+(module|namespace|class|interface|function|const|var|let)/.test(e)||/interface\s+\w+/.test(e)||/type\s+\w+\s*=/.test(e)}};var G={maxRelativeTypeRefs:500,maxBareDeps:8,maxBareDepth:3,prefetchConcurrency:4,negativeTtlMs:1e4},ke=["index.d.ts","index.d.mts"],Te=/\.d\.(ts|mts)$/i;function $t(r){if(Te.test(r))return!0;try{return new URL(r,"file://").search.includes("dts")}catch{return r.includes("?")&&r.includes("dts")}}function qe(r){return[`${r}.d.ts`,`${r}.d.mts`]}async function _e(r,{retries:e=2,timeoutMs:t=15e3,init:n}={}){for(let s=0;s<=e;s++){let o=new AbortController,i=setTimeout(()=>o.abort(),t);try{let a=await fetch(r,{...n,signal:o.signal});if(vs(a.status)&&s<e)continue;return a}catch{if(s<e)continue;return}finally{clearTimeout(i)}}}function vs(r){return r===408||r===429||r>=500&&r<600}var Ce=class extends de{constructor(e,t){super(e),this.cdnClient=t}async loadPackageAtVersionedRoot(e,t){let n=this.cdnClient.packageJson(new y({name:e,version:t})),s=await _e(n);if(!s?.ok)return;let o;try{o=await s.json()}catch{return}if(o)return{pkg:o,baseDir:this.cdnClient.baseDir(new y({name:e,version:t??o.version})),version:t}}extractPathFromResult(e){if(typeof e=="string")return e;if(Array.isArray(e))return e.find(t=>typeof t=="string")}async tryUntilSuccess(e,t){for(let n of e){let s=await t(n);if(s)return s}}async resolveFromSelected(e,t){if(e.kind==="types"){let s=this.cdnClient.normalizeRelative(e.path);if(!s||s==="/"||s===".")return this.tryUntilSuccess([...ke],t);if(!Te.test(s)){let o=await this.tryUntilSuccess(this.declarationCandidatesFor(s),t);if(o)return o}return t(s)}let n=this.declarationCandidatesFor(e.path);return this.tryUntilSuccess([...ke,...n],t)}toResolutionResult(e){return{kind:Te.test(e)?"types":"probe",path:e}}resolveExportsPath(e,t){let n=t||".",s=e;try{let o=this.extractPathFromResult(Cr(s,n,{conditions:["types"]}));if(o)return o}catch{}try{return this.extractPathFromResult(Cr(s,n,{browser:!0,conditions:["import","default","module","browser","node"]}))}catch{return}}async resolve(e){try{let t=y.parse(e),{pkg:n,baseDir:s}=await this.loadPackageAtVersionedRoot(t.name,t.version)||{};if(!n||!s)return;let o={name:t.name,version:t.version},i=new y(o).format(),a=new y({...o,subpath:t.subpath}).format(),c=d=>this.fetchCandidateFrom(s,t.name,d);if(t.subpath){let d=this.cdnClient.ensureLeadingDotSlash(t.subpath),m=this.resolveExportsPath(n,d);if(m){let g=await this.resolveFromSelected(this.toResolutionResult(m),c);if(g)return{...g,resolvedPkg:a}}let h=await this.tryUntilSuccess(this.declarationCandidatesFor(d),c);if(h)return{...h,resolvedPkg:a}}let l=n.types??n.typings;if(l){let d=await this.resolveFromSelected({kind:"types",path:l},c);if(d)return{...d,resolvedPkg:i}}let p=this.resolveExportsPath(n,".");if(p){let d=await this.resolveFromSelected(this.toResolutionResult(p),c);if(d)return{...d,resolvedPkg:i}}return}catch{return}}async fetchCandidateFrom(e,t,n){let s=this.cdnClient.normalizeRelative(n),o=new URL(s,e).toString(),i=await this.fetchDtsText(o);return i?{dts:i.dts,url:i.url,resolvedPkg:t}:void 0}declarationCandidatesFor(e){if(!e||e==="./"||e==="/")return[...ke];let t=e.replace(/\.(mjs|cjs|js|mts|cts|ts)$/i,""),n=qe(t),s=t.endsWith("/")?t:`${t}/`;return n.push(...qe(`${s}index`)),n}};import{gunzipSync as ws}from"fflate";var ue=class{async fetchAndExtract(e,t){let n=this.getTarballUrl(e,t),s=await _e(n,{timeoutMs:3e4});if(!s?.ok)return new Map;let o=new Uint8Array(await s.arrayBuffer());return this.extractDtsFiles(o)}getTarballUrl(e,t){return`https://registry.npmjs.org/${e.replace("/","%2F")}/-/${e.split("/").pop()}-${t}.tgz`}normalizeTarPath(e){let t=e.replace(/^package\//,""),n=t.indexOf("/");return n>0?t.substring(n+1):t}extractDtsFiles(e){let t=new Map;try{let n=ws(e),s=new TextDecoder("utf-8"),o=0;for(;o<n.length-512;){let i=n.slice(o,o+512);if(i[0]===0)break;let a=i.slice(0,100),c=a.indexOf(0),l=s.decode(a.slice(0,c>0?c:100)).trim(),p=i.slice(124,136),d=s.decode(p).trim().replace(/\0/g,""),m=parseInt(d,8)||0,h=String.fromCharCode(i[156]);if(o+=512,(h==="0"||h==="\0")&&(l.endsWith(".d.ts")||l.endsWith(".d.mts"))){let g=n.slice(o,o+m);t.set(this.normalizeTarPath(l),s.decode(g))}o+=Math.ceil(m/512)*512}}catch{}return t}},xs=new ue;var Oe=class extends de{constructor(e,t,n,s=new ue){super(e),this.cdnClient=t,this.cache=n,this.tarballFetcher=s}typesNameCandidates(e){let t=e.startsWith("@")?e.slice(1).replace("/","__"):e;return t.includes(".")?[t,t.split(".").join("-"),t.split(".").join("")]:[t]}selectTypesVersion(e,t,n){try{if(n){let o=Q.majorOf(n),i=e.filter(a=>Q.majorOf(a)===o);if(i.length)return i.sort((a,c)=>Q.cmp(c,a))[0]}let s=t?.latest;return s&&e.includes(s)?s:e[0]}catch{return e[0]}}async fetchFromVersionedRoot(e,t){let n=new y(e),s=n.version;if(!s)return;let o;try{o=await this.tarballFetcher.fetchAndExtract(n.name,s)}catch{return}if(!o||o.size===0)return;for(let[a,c]of o.entries()){let l=this.cdnClient.file(e,a);try{await this.cache.setCachedFile(l,c)}catch{}}let i=t.subpath?[t.subpath+".d.ts",t.subpath+"/index.d.ts"]:["index.d.ts"];for(let a of i){let c=o.get(a);if(c)return{dts:c,url:this.cdnClient.file(e,a),resolvedPkg:t.subpath?new y(t).format():t.name}}}async resolve(e){let t=y.parse(e);if(t.name)for(let n of this.typesNameCandidates(t.name)){let s=`@types/${n}`,o;try{o=await this.cdnClient.fetchVersionsIndex(s)}catch{continue}if(!o?.versions?.length)continue;let i=this.selectTypesVersion(o.versions,o.distTags,t.version),a=await this.fetchFromVersionedRoot(`${s}@${i}`,t);if(a)return a}}};var Ae=class{collectRelativeTypeRefs(e){return this.collectRefs(e).filter(t=>t.startsWith("./")||t.startsWith("../"))}collectBareModuleRefs(e){return this.collectRefs(e).filter(t=>this.isBare(t))}collectRefs(e){let t=new Set,n=(s,o)=>(t.add(s[o]),null);return this.matchAll(e,/(import|export)\s+[^'"\n]*from\s*['"]([^'"\n]+)['"]/,s=>n(s,2)),this.matchAll(e,/export\s*\*\s*from\s*['"]([^'"\n]+)['"]/,s=>n(s,1)),Array.from(t)}matchAll(e,t,n){let s=[];try{let o=new RegExp(t.source,"g"),i;for(;i=o.exec(e);){let a=n(i);a!==null&&s.push(a)}}catch{}return s}isBare(e){return!(e.startsWith("./")||e.startsWith("../")||e.startsWith("file:")||e.startsWith("http://")||e.startsWith("https://"))}};var Or="file:///node_modules",Ie=class{constructor(){this.epoch=0,this.listeners=new Set}getEpoch(){return this.epoch}bumpEpoch(){this.epoch+=1;for(let e of this.listeners)try{e(this.epoch)}catch{}return this.epoch}onEpochChange(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}epochDir(){return`__tsepoch_${this.epoch}`}pathForMain(e){return`${Or}/${this.epochDir()}/${e}/index.d.ts`}pathFor(e,t){let n=Ss(t);return`${Or}/${this.epochDir()}/${e}/${n}`}};function Ss(r){let e=r||"";return e.startsWith("./")?e.slice(2):e.replace(/^\/+/,"")}import{LRUCache as Ps}from"lru-cache";function Dt(r){let e=new Ps({ttl:1e4,max:500}),t=new Map;return async function(s){try{if(await r.isNegative(s))return;let o=e.get(s);if(o&&Date.now()-o<1e4)return;let i=await r.getCachedFile(s);if(i)return{dts:i,url:s};let a=t.get(s);if(a)return a;let c=(async()=>{let l=await fetch(s,{cache:"no-store"});if(!l.ok){l.status===404&&(e.set(s,Date.now()),await r.recordNegative(s));return}let p=await l.text(),d=l.url||s;return await r.clearNegative(s),await r.setCachedFile(d,p),{dts:p,url:d}})();return t.set(s,c),await c.finally(()=>t.delete(s))}catch{return}}}var ze=class{constructor(e){this.inFlight=new Map,this.scanner=new Ae,this.cache=e.cache,this.cdnClient=e.cdnClient,this.versionResolver=e.versionResolver,this.packageService=e.packageService,this.fetchDts=Dt(e.cache),this.typescriptProvider=new Ce(this.fetchDts,e.cdnClient),this.definitelyTypedProvider=new Oe(this.fetchDts,e.cdnClient,e.cache),this.virtualFs=new Ie}withInFlight(e,t){let n=this.inFlight.get(e);if(n)return n;let s=t().finally(()=>this.inFlight.delete(e));return this.inFlight.set(e,s),s}invalidate(){this.virtualFs.bumpEpoch(),this.inFlight.clear()}capArray(e,t){return e.length<=t?e:e.slice(0,t)}pushFileIfNew(e,t,n){e.some(s=>s.path===t)||e.push({path:t,content:n})}createStubDef(e){let t=this.virtualFs.pathForMain(e);return{pkg:e,mainPath:t,files:[{path:t,content:"export const _shim: any; export default _shim;"}],shims:[{module:e,path:t}]}}async trySubpathWithRootFallback(e,t){let n=new y(e);return n.subpath?this.fetchRootDts(n.name,t):void 0}async fetchViaProviders(e){for(let t of[this.typescriptProvider,this.definitelyTypedProvider])try{let n=await t.resolve(e);if(n?.dts)return n}catch{}}subpathsMatch(e,t){return new y(e).subpath===new y(t).subpath}async fetchRootDts(e,t){let{effectivePackage:n,root:s,pinned:o}=await this.versionResolver.effectivePackage(e,t),i=await this.cache.getCachedDts(n);if(i?.content){let c=i.url??this.cdnClient.file(o?`${s}@${o}`:s,"index.d.ts");return{dts:i.content,url:c,resolvedPkg:n}}let a;try{a=await this.fetchViaProviders(n)}catch{return}if(!(!a?.dts||!a.url)){try{await this.cache.setCachedFile(a.url,a.dts)}catch{}if(this.subpathsMatch(n,a.resolvedPkg||n)){try{await this.cache.setCachedDts(n,a.dts,a.url)}catch{}return a}}}extractPackageRootUrl(e){let t=e.pathname.match(/^(.+@[^/]+\/)/);return t?new URL(t[1],e.origin):new URL("./",e)}toVirtualPath(e,t,n){let s=t.pathname.startsWith(e.pathname)?t.pathname.slice(e.pathname.length):`__deps__/${encodeURIComponent(t.toString()).replace(/%/g,"_")}.d.ts`;return this.virtualFs.pathFor(n,s)}computeEntryPath(e,t){if(!e)return{mainPath:this.virtualFs.pathForMain(t),packageRootUrl:void 0};let n=new URL(e),s=this.extractPackageRootUrl(n);return{mainPath:this.toVirtualPath(s,n,t),packageRootUrl:s}}async expandRelativeRefs(e,t,n,s,o=new Set,i){if(!o.has(t)&&(o.add(t),!(o.size>G.maxRelativeTypeRefs)))try{let a=new URL(t),c=new URL("./",a);i??(i=this.extractPackageRootUrl(a));let l=this.capArray(this.scanner.collectRelativeTypeRefs(e),G.maxRelativeTypeRefs);for(let p of l)await this.tryRelativeRef(p,c,i,n,s,o)}catch{}}async tryRelativeRef(e,t,n,s,o,i){try{let a=new URL(e,t),c=a.pathname+a.search,l=$t(c)?[c]:this.typescriptProvider.declarationCandidatesFor(c);for(let p of l){let m=new URL(p,a).toString();if(i.has(m))return;let h=await this.fetchDts(m);if(h?.dts){let g=this.toVirtualPath(n,new URL(h.url),s);this.pushFileIfNew(o,g,h.dts),await this.expandRelativeRefs(h.dts,h.url,s,o,i,n);return}}}catch{}}isDifferentPackage(e,t){return e===t?!1:new y(e).name!==new y(t).name}ambientlyDeclares(e,t){for(let n of e.matchAll(/declare\s+module\s+['"]([^'"]+)['"]/g)){let s=n[1];if(s===t||s.endsWith("/*")&&t.startsWith(s.slice(0,-1)))return!0}return!1}markFileAmbient(e,t){let n=e.find(s=>s.path===t);n&&(n.ambient=!0)}async prefetchBareDeps(e,t,n,s,o){try{let i=this.capArray(this.scanner.collectBareModuleRefs(e),G.maxBareDeps).filter(l=>this.isDifferentPackage(l,t));if(!i.length)return;let a=new Set([t]),c=Rs(G.prefetchConcurrency);await Promise.all(i.map(l=>c(()=>this.prefetchBareDepsRecursive(l,n,s,G.maxBareDepth,a,o).catch(()=>{}))))}catch{}}async prefetchBareDepsRecursive(e,t,n,s,o,i){if(s<=0||o.has(e))return;o.add(e);let a=await this.fetchRootDts(e,i);if(!a?.dts)return;let c=a.resolvedPkg||e,l=this.virtualFs.pathForMain(c);this.pushFileIfNew(t,l,a.dts),this.ambientlyDeclares(a.dts,e)?this.markFileAmbient(t,l):n.push({module:e,path:l}),a.url&&await this.expandRelativeRefs(a.dts,a.url,c,t);let p=this.capArray(this.scanner.collectBareModuleRefs(a.dts),G.maxBareDeps).filter(d=>!o.has(d));for(let d of p)await this.prefetchBareDepsRecursive(d,t,n,s-1,o,i)}async resolve(e,t,n){let s=await this.packageService.extractImports(e),o=n?[...s,...n]:s;return(await Promise.all(o.map(a=>this.resolveOne(a,t)))).filter(a=>!!a)}async resolveOne(e,t){let{effectivePackage:n}=await this.versionResolver.effectivePackage(e,t);return this.withInFlight(n,async()=>{let s=await this.fetchRootDts(e,t)??await this.trySubpathWithRootFallback(e,t);return s?this.buildDefFromContent(e,s,s.resolvedPkg||e,t):this.createStubDef(e)})}async buildDefFromContent(e,t,n,s){let{dts:o,url:i,resolvedPkg:a}=t,c=new y(a||n),l=c.version?`${c.name}@${c.version}`:c.name,{mainPath:p,packageRootUrl:d}=this.computeEntryPath(i,l),m=[{path:p,content:o}],h=[];i&&await this.expandRelativeRefs(o,i,l,m,void 0,d);let g=m.map(_=>_.content).join(`
267
+ `);await this.prefetchBareDeps(g,l,m,h,s);let S=c.format(),B=e===S?[e]:[e,S],N=B.some(_=>this.ambientlyDeclares(o,_));return N?this.markFileAmbient(m,p):h.push(...B.map(_=>({module:_,path:p}))),{pkg:e,mainPath:p,files:m,shims:h,ambient:N}}};function Mt(r){return new ze(r)}import*as L from"fs/promises";import*as U from"path";import*as $r from"os";import*as jt from"fs/promises";import*as Ar from"crypto";function I(r){return Ar.createHash("sha1").update(r).digest("hex")}async function ee(r){try{return JSON.parse(await jt.readFile(r,"utf8"))}catch{return}}async function Ge(r){try{return await jt.readFile(r,"utf8")}catch{return}}var Ir=1,K=U.join($r.homedir(),".typebulb","cache"),$e=U.join(K,"packages"),De=U.join(K,"proxy"),Ke=U.join(K,"dts"),Es=U.join(K,"emit"),Bt;function x(){return Bt||(Bt=ks()),Bt}function Ye(r,e){return U.join(Es,I(r),e)}async function ks(){await L.mkdir(K,{recursive:!0});let r=U.join(K,"version.json");if((await Ts(r))?.version===Ir)return;let t=await L.readdir(K).catch(()=>[]);await Promise.all(t.map(n=>L.rm(U.join(K,n),{recursive:!0,force:!0}))),await L.writeFile(r,JSON.stringify({version:Ir})+`
268
+ `,"utf8")}async function Ts(r){try{let e=await L.readFile(r,"utf8");return JSON.parse(e)}catch{return}}import*as Y from"fs/promises";import*as Dr from"path";async function C(r,e){await Y.mkdir(Dr.dirname(r),{recursive:!0});let t=`${r}.tmp-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;await Y.writeFile(t,e,"utf8"),await Y.rename(t,r).catch(async n=>{throw await Y.rm(t,{force:!0}).catch(()=>{}),n})}var pe=class{constructor(e){this.filePath=e}mem;loadPromise;load(){return this.mem?Promise.resolve(this.mem):(this.loadPromise||(this.loadPromise=ee(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 C(this.filePath,JSON.stringify(Object.fromEntries(e)))}};var Ft=$.join($e,"indexes"),Mr=$.join($e,"pinned"),_s=$.join($e,"meta"),Cs=$.join($e,"negative.json"),fe=Symbol("missing"),Qe=class{pinnedMem=new Map;indexMem=new Map;metaMem=new Map;negativeCache=new Z(new pe(Cs));async getPinnedExact(e,t){let n=`${e}@${t}`,s=this.pinnedMem.get(n);if(s!==void 0)return s===fe?void 0:s;await x();let o=await Ge($.join(Mr,I(n)+".txt"));return this.pinnedMem.set(n,o??fe),o}async setPinnedExact(e,t,n){let s=`${e}@${t}`;this.pinnedMem.set(s,n),await x(),await C($.join(Mr,I(s)+".txt"),n)}async getIndex(e){let t=this.indexMem.get(e);if(t!==void 0)return t===fe?void 0:t;await x();let n=await ee($.join(Ft,Xe(e)+".json"));return this.indexMem.set(e,n??fe),n}async setIndex(e,t,n){let s={versions:t,distTags:n,updatedAt:Date.now()};this.indexMem.set(e,s),await x(),await C($.join(Ft,Xe(e)+".json"),JSON.stringify(s))}async invalidateVersionsCache(e){this.indexMem.delete(e),await Br.rm($.join(Ft,Xe(e)+".json"),{force:!0})}async isNegative(e){return await x(),this.negativeCache.isNegative(e)}async recordNegative(e){await x(),await this.negativeCache.recordNegative(e)}async clearNegative(e){await this.negativeCache.clearNegative(e)}async getMeta(e,t){let n=`${e}@${t}`,s=this.metaMem.get(n);if(s!==void 0)return s===fe?void 0:s;await x();let o=await ee(jr(e,t));return this.metaMem.set(n,o??fe),o}async setMeta(e,t,n,s,o){let i={dependencies:n,peerDependencies:s,peerDependenciesMeta:o,updatedAt:Date.now()};this.metaMem.set(`${e}@${t}`,i),await x(),await C(jr(e,t),JSON.stringify(i))}};function jr(r,e){return $.join(_s,Xe(r),encodeURIComponent(e)+".json")}function Xe(r){return r.replace(/\//g,"__")}var Fr={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 Os=new Qe,{packageService:Ze,versionResolver:Lr,cdnClient:Nr,peerResolver:La}=Sr(Os,Fr);var Ur=`
267
269
  (() => {
268
270
  // Embedded (bulb-in-a-bulb): runs inside a sandboxed iframe with no parent
269
271
  // bridge, so privileged tb.* (AI, fs, server RPC) can't reach a host and would
@@ -473,12 +475,12 @@ declare const tb: {${Sr}${Pr}${Rr}${Tr}${ps}${Er}${kr}
473
475
  };
474
476
  }
475
477
  })();
476
- `;function Ur(r){let{name:e,code:t,css:n,html:s,data:o,insight:i,importMap:a,watch:c,theme:l}=r,p=s.trim()||'<div id="app"></div>',d=h=>h.replace(/<\/script/gi,"<\\/script"),m={imports:As(a.imports)};return`<!DOCTYPE html>
478
+ `;function Wr(r){let{name:e,code:t,css:n,html:s,data:o,insight:i,importMap:a,watch:c,theme:l}=r,p=s.trim()||'<div id="app"></div>',d=h=>h.replace(/<\/script/gi,"<\\/script"),m={imports:$s(a.imports)};return`<!DOCTYPE html>
477
479
  <html>
478
480
  <head>
479
481
  <meta charset="utf-8">
480
482
  <meta name="viewport" content="width=device-width, initial-scale=1">
481
- <title>${Cs(e)} - typebulb</title>
483
+ <title>${Is(e)} - typebulb</title>
482
484
  <script>
483
485
  // Theme engine. Sets html[data-theme] before stylesheets paint (no flash) and
484
486
  // exposes the tb.theme accessor via window.__tbTheme. The override is persisted
@@ -544,16 +546,16 @@ ${i?`<script>window.__TB_INSIGHT__ = ${d(JSON.stringify(i))};</script>`:""}
544
546
  ${c?"<script>window.__TYPEBULB_WATCH__ = true;</script>":""}
545
547
 
546
548
  <script>
547
- ${Lr}
549
+ ${Ur}
548
550
  </script>
549
551
 
550
- ${_s}
552
+ ${As}
551
553
 
552
554
  <script type="module">
553
555
  ${d(t)}
554
556
  </script>
555
557
  </body>
556
- </html>`}var _s=`<script>
558
+ </html>`}var As=`<script>
557
559
  (function () {
558
560
  if (window.parent === window) return;
559
561
  var de = document.documentElement;
@@ -624,50 +626,50 @@ ${d(t)}
624
626
  }
625
627
  });
626
628
  })();
627
- </script>`;function Cs(r){return r.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function As(r){let e={};for(let[t,n]of Object.entries(r))e[t]=n.startsWith("https://")?"/proxy/"+n:n;return e}import*as et from"fs/promises";import*as Ze from"path";import{existsSync as Wr,readFileSync as Is}from"fs";import{execFile as Os}from"child_process";import{promisify as $s}from"util";import{satisfies as Ds}from"semver";var Ms=$s(Os);async function tt(r,e,t){let s=r.map(i=>js(i,t)).filter(i=>!Fs(i,e));if(s.length===0)return;await et.mkdir(e,{recursive:!0});let o=Ze.join(e,"package.json");Wr(o)||await et.writeFile(o,JSON.stringify({name:"typebulb-server",private:!0})),console.log(` Installing: ${s.join(", ")}`),await Ms("npm",["install","--no-audit","--no-fund",...s],{cwd:e,shell:!0})}function js(r,e){if(!e||Vr(r))return r;let t=e[r];return t?`${r}@${t}`:r}function Fs(r,e){let t=Ze.join(e,"node_modules",Jr(r));if(!Wr(t))return!1;let n=Vr(r);if(!n)return!0;try{let s=JSON.parse(Is(Ze.join(t,"package.json"),"utf-8")).version;return Ds(s,n)}catch{return!1}}function rt(r){let e=new Set,t=/\bimport\s+(?:[\s\S]*?\s+from\s+)?['"]([^./][^'"]*)['"]/g,n;for(;n=t.exec(r);){let s=n[1];if(s.includes(":"))continue;let o=s.startsWith("@")?s.split("/").slice(0,2).join("/"):s.split("/")[0];e.add(o)}return[...e]}function Jr(r){if(r.startsWith("@")){let t=r.indexOf("/");if(t<0)return r;let n=r.indexOf("@",t+1);return n<0?r:r.slice(0,n)}let e=r.indexOf("@");return e<0?r:r.slice(0,e)}function Vr(r){let e=Jr(r);return r.length>e.length?r.slice(e.length+1):""}async function Hr(r){let t=(await X.readdir(r)).find(n=>n.endsWith(".bulb.md"));return t?nt.join(r,t):null}async function W(r){let e=await X.readFile(r,"utf-8"),t=fr(e);if(!t)throw new Error("Invalid .bulb.md file format");let n=mr(t);return{bulb:n,config:gr(n.config)}}async function Nt(r,e,t,n){let s=Rt(r,{serverOnly:!0});if(s.error)throw new Error(`Server compilation error: ${s.error}`);let o=s.code;t&&(o=await dr(o,t));let i=nt.join(e,".typebulb");await X.mkdir(i,{recursive:!0});let a=rt(o);a.length>0&&await tt(a,i,n);let c=nt.join(i,"server.mjs");return await X.writeFile(c,o,"utf-8"),await import(`${Ns(c).href}?t=${Date.now()}`)}async function Bt(r,e,t,n,s){let{bulb:o,config:i}=await W(r),a=hr(o.data),c=Rt(o.code,{jsxImportSource:i.jsxImportSource});c.error&&console.error("Compilation error:",c.error);let{importMap:l}=await Qe.buildImportMap(c.code,i.dependencies??{},n?new Set([n.name]):void 0);n&&(l.imports[n.name]=n.entryUrl);let p=Ur({name:o.name,code:c.code,css:o.css,html:o.html,data:a,insight:o.insight,importMap:l,watch:e}),d=null;return o.server&&t&&(d=await Nt(o.server,s,n,i.dependencies)),{html:p,bulb:o,serverExports:d}}import{readFileSync as Us,writeFileSync as Ws,mkdirSync as Js}from"fs";import{join as Vs}from"path";import{join as Lt,resolve as Bs}from"path";import{homedir as Ls}from"os";function st(){let r=process.env.TYPEBULB_SERVERS_DIR;return r?Lt(r,".."):Lt(Ls(),".typebulb")}function te(){return process.env.TYPEBULB_SERVERS_DIR||Lt(st(),"servers")}function D(r){let e=Bs(r);return(process.platform==="win32"?e.toLowerCase():e).replace(/\\/g,"/")}function qr(r,e){let t=D(r),n=D(e);return t.startsWith(n.endsWith("/")?n:n+"/")?!t.includes("/node_modules/"):!1}function zr(){return Vs(st(),"trust.json")}function Ut(){try{let r=JSON.parse(Us(zr(),"utf8"));return new Set(Array.isArray(r)?r:[])}catch{return new Set}}function Hs(r){Js(st(),{recursive:!0}),Ws(zr(),JSON.stringify([...r]))}function ot(r){return Ut().has(D(r))}function Gr(r,e){let t=Ut(),n=D(r);(e?t.has(n):!t.has(n))||(e?t.add(n):t.delete(n),Hs(t))}function Kr(){return[...Ut()]}import qs from"open";async function it(r){await qs(r)}import*as J from"path";import{fileURLToPath as zs}from"url";var at={claude:{file:"claude.bulb.md",srcEnv:"TYPEBULB_CLAUDE_SRC",viewer:!0}};function me(r){let e=at[r];if(!e)return;let t=e.srcEnv?process.env[e.srcEnv]:void 0;return t?J.resolve(t):J.join(J.dirname(zs(import.meta.url)),"..","bulbs",e.file)}function ct(r){let e=J.basename(r).toLowerCase();for(let[t,n]of Object.entries(at))if(n.viewer&&n.file.toLowerCase()===e)return t}function Wt(){return Object.entries(at).filter(([,r])=>r.viewer).map(([r])=>r)}function Yr(r){let e=J.basename(r).toLowerCase();return Object.values(at).some(t=>t.file.toLowerCase()===e)}import*as rn from"path";import{spawn as co}from"child_process";import*as E from"fs/promises";import*as R from"path";import*as he from"path";var Gs=he.join(Ge,"pkg"),Ks=he.join(Ge,"files"),Ys=he.join(Ge,"negative.json"),dt=class{pkgMem=new Map;fileMem=new Map;negativeCache=new Z(new pe(Ys));async getCachedDts(e){if(this.pkgMem.has(e))return this.pkgMem.get(e);await x();let t=await ee(Xr(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 lt(async()=>{await x(),await C(Xr(e),JSON.stringify(s))})}async getCachedFile(e){if(this.fileMem.has(e))return this.fileMem.get(e);await x();let t=await ze(Qr(e));return this.fileMem.set(e,t),t}async setCachedFile(e,t){this.fileMem.set(e,t),await lt(async()=>{await x(),await C(Qr(e),t)})}isNegative(e){return this.negativeCache.isNegative(e)}async recordNegative(e){await lt(async()=>{await x(),await this.negativeCache.recordNegative(e)})}clearNegative(e){return lt(()=>this.negativeCache.clearNegative(e))}};async function lt(r){try{await r()}catch{}}function Xr(r){return he.join(Gs,O(r)+".json")}function Qr(r){return he.join(Ks,O(r)+".txt")}var Jt;function Xs(){return Jt||(Jt=Dt({cache:new dt,cdnClient:Br,packageService:Qe,versionResolver:Nr})),Jt}var Zr="file:///node_modules/";async function en(r){let e=Ke(r.emitKey,"typecheck");await x(),await E.rm(e,{recursive:!0,force:!0}),await E.mkdir(e,{recursive:!0});let t=to(r.jsxImportSource,r.dependencies),n=await Xs().resolve(r.code,r.dependencies,t),s=r.local?.name,o=s?n.filter(p=>p.pkg!==s):n,i=new Set;for(let p of o)for(let d of p.files){let m=ut(d.path);if(!m||i.has(m))continue;i.add(m);let h=R.join(e,"node_modules",m);await E.mkdir(R.dirname(h),{recursive:!0}),await E.writeFile(h,d.content,"utf8")}let a={};for(let p of o)for(let d of p.shims){let m=ut(d.path);m&&(a[d.module]=[`./node_modules/${m}`])}for(let p of o){if(p.ambient)continue;let d=ut(p.mainPath);d&&(a[p.pkg]=[`./node_modules/${d}`])}let c=new Set;for(let p of o)for(let d of p.files){if(!d.ambient)continue;let m=ut(d.path);m&&c.add(`node_modules/${m}`)}if(r.local){delete a[r.local.name];let p=await ro(r.local,e);p?a[r.local.name]=[`./node_modules/${r.local.name}/${p}`]:console.warn(` local: '${r.local.name}' ships no type defs; check cannot type against it.`)}let l=Qs(r.jsxImportSource,a,[...c]);return await E.writeFile(R.join(e,"tsconfig.json"),JSON.stringify(l,null,2)+`
628
- `,"utf8"),await E.writeFile(R.join(e,"code.tsx"),r.code,"utf8"),await E.writeFile(R.join(e,"tb.d.ts"),At,"utf8"),{dir:e}}function Qs(r,e,t=[]){return{compilerOptions:{target:"es2023",module:"esnext",moduleResolution:"bundler",lib:Zs([..._t,...Ct]),jsx:"react-jsx",jsxImportSource:r??"react",strict:!0,noEmit:!0,skipLibCheck:!0,esModuleInterop:!0,allowSyntheticDefaultImports:!0,forceConsistentCasingInFileNames:!0,baseUrl:".",paths:e},include:["code.tsx","tb.d.ts",...t]}}function Zs(r){return r.filter(e=>!e.since).map(e=>eo(e.name))}function eo(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 to(r,e){let t=r??("react"in e?"react":void 0);return t?[`${t}/jsx-runtime`,`${t}/jsx-dev-runtime`]:[]}function ut(r){if(!r.startsWith(Zr))return;let e=r.slice(Zr.length),t=e.indexOf("/");if(!(t<0))return e.slice(t+1)}async function ro(r,e){if(!r.typesAbs)return;let t=R.dirname(r.typesAbs),n=R.join(e,"node_modules",r.name);for(let s of await no(t)){let o=R.join(n,R.relative(t,s));await E.mkdir(R.dirname(o),{recursive:!0}),await E.copyFile(s,o)}return R.basename(r.typesAbs)}async function no(r){let e=[];async function t(n){let s=await E.readdir(n,{withFileTypes:!0});for(let o of s){let i=R.join(n,o.name);o.isDirectory()?await t(i):/\.d\.ts(\.map)?$/.test(o.name)&&e.push(i)}}return await t(r),e}import*as A from"fs/promises";import*as V from"path";import{existsSync as so}from"fs";var oo="^22";async function tn(r){let e=Ke(r.emitKey,"typecheck-server");await x(),await A.rm(e,{recursive:!0,force:!0}),await A.mkdir(e,{recursive:!0});let t=V.join(r.bulbDir,".typebulb"),n=rt(r.server).filter(i=>i!==r.local?.name);await tt([`@types/node@${oo}`,...n],t,r.dependencies);let s=V.join(t,"node_modules"),o=V.join(e,"node_modules");return await ao(s,o),await A.writeFile(V.join(e,"server.ts"),r.server,"utf8"),await A.writeFile(V.join(e,"tb.d.ts"),It,"utf8"),await A.writeFile(V.join(e,"tsconfig.json"),JSON.stringify(io(r.local),null,2)+`
629
- `,"utf8"),{dir:e}}function io(r){let e={target:"es2023",module:"esnext",moduleResolution:"bundler",lib:["ES2023"],types:["node"],strict:!0,noEmit:!0,skipLibCheck:!0,esModuleInterop:!0,allowSyntheticDefaultImports:!0,forceConsistentCasingInFileNames:!0};if(r?.typesAbs){let t=o=>o.replace(/\\/g,"/"),n=t(V.dirname(r.typesAbs)),s=t(r.typesAbs).replace(/\.d\.ts$/,"");e.baseUrl=".",e.paths={[r.name]:[s],[`${r.name}/*`]:[`${n}/*`]}}return{compilerOptions:e,include:["server.ts","tb.d.ts"]}}async function ao(r,e){if(!so(r)){await A.mkdir(e,{recursive:!0});return}await A.rm(e,{recursive:!0,force:!0});let t=process.platform==="win32"?"junction":"dir";await A.symlink(r,e,t)}async function nn(r,e){let{bulb:t,config:n}=await W(r);!t.code&&!t.server&&(console.error("Bulb has neither **code.tsx** nor **server.ts**; nothing to check."),process.exit(1));let s=[];if(t.code){let{dir:i}=await en({code:t.code,dependencies:n.dependencies??{},jsxImportSource:n.jsxImportSource,emitKey:r,local:e});s.push({role:"client",dir:i})}if(t.server){let{dir:i}=await tn({server:t.server,bulbDir:rn.dirname(r),emitKey:r,local:e?{name:e.name,typesAbs:e.typesAbs}:void 0,dependencies:n.dependencies});s.push({role:"server",dir:i})}let o=!1;for(let{role:i,dir:a}of s){let{stdout:c,exitCode:l}=await lo(a);for(let p of c.split(/\r?\n/))p.trim()&&console.log(`${i} ${p}`);l!==0&&(o=!0)}o&&process.exit(1)}function lo(r){return new Promise(e=>{let t=co("npx",["tsc","--noEmit"],{cwd:r,shell:!0}),n="";t.stdout?.on("data",s=>{n+=s.toString()}),t.stderr?.on("data",s=>{n+=s.toString()}),t.on("close",s=>e({stdout:n,exitCode:s??1}))})}function pt(r){if(r.server.trim())return"server-side code (server.ts)";let e=r.code;if(/\btb\s*\.\s*fs\b/.test(e)||e.includes("/__fs"))return"the filesystem";if(/\btb\s*\.\s*ai\b/.test(e)||e.includes("/__ai"))return"AI (your API keys)";if(/\btb\s*\.\s*server\s*\.\s*(?!log\b)\w/.test(e)||e.includes("/__api"))return"server-side code (server.ts)"}async function sn(r,e){let{bulb:t}=await W(r),n=pt(t);if(ot(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.)")}import*as Me from"path";async function on(r,e){if(!r){e||(console.error("Usage: typebulb untrust <file.bulb.md>"),process.exit(1));let n=Kr();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=Me.resolve(r);t.endsWith(".bulb.md")||(console.error("File must have .bulb.md extension"),process.exit(1)),Gr(t,e),console.log(e?`Trusted ${Me.basename(t)} \u2014 runs with fs / AI / server.ts (no --trust needed).`:`Untrusted ${Me.basename(t)} \u2014 runs Restricted.`),console.log(` ${t}`)}import{readdir as uo,readFile as ln,writeFile as dn,unlink as je,mkdir as po}from"fs/promises";import{mkdirSync as fo,writeFileSync as an,appendFileSync as mo,readFileSync as un}from"fs";import*as re from"path";var cn=1e6;function Vt(r){return re.join(te(),`${r}.json`)}function ft(r){return re.join(te(),`${r}.log`)}function pn(r){let e=ft(r);try{fo(te(),{recursive:!0}),an(e,"")}catch{return()=>{}}let t=process.stdout.write.bind(process.stdout),n=process.stderr.write.bind(process.stderr),s=0,o=!1,i=a=>{if(!o)try{let c=typeof a=="string"?Buffer.from(a,"utf8"):Buffer.from(a);if(mo(e,c),s+=c.length,s>2*cn){let l=un(e),p=l.subarray(Math.max(0,l.length-cn));an(e,p),s=p.length}}catch{o=!0}};return process.stdout.write=((a,...c)=>(i(a),t(a,...c))),process.stderr.write=((a,...c)=>(i(a),n(a,...c))),()=>{process.stdout.write=t,process.stderr.write=n}}function Ht(r,e=0){try{let t=un(ft(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 ho(r){try{return process.kill(r,0),!0}catch(e){return e.code==="EPERM"}}async function fn(r){await po(te(),{recursive:!0}),await dn(Vt(r.pid),JSON.stringify(r))}async function mn(r,e){let t=Vt(r);try{let n=JSON.parse(await ln(t,"utf8"));if(n.denied===e)return;n.denied=e,await dn(t,JSON.stringify(n))}catch{}}async function qt(r){await je(Vt(r)).catch(()=>{}),await je(ft(r)).catch(()=>{})}async function ne(r){let e;try{e=await uo(te())}catch{return[]}let t=[];return await Promise.all(e.map(async s=>{if(!s.endsWith(".json"))return;let o=re.join(te(),s),i;try{i=JSON.parse(await ln(o,"utf8"))}catch{await je(o).catch(()=>{});return}i&&typeof i.pid=="number"&&ho(i.pid)?t.push(i):(await je(o).catch(()=>{}),i?.pid&&await je(ft(i.pid)).catch(()=>{}))})),(r?t.filter(s=>qr(s.file,r)&&!Yr(s.file)):t).sort((s,o)=>s.startedAt-o.startedAt)}async function hn(r){try{process.kill(r,"SIGTERM")}catch{}await qt(r)}async function zt(r,e){let t=D(r);return(await ne()).find(n=>n.cwd!=null&&D(n.cwd)===t&&(e?ct(n.file)===e:ct(n.file)!=null))}async function gn(){let r=await zt(process.cwd()),e=r?ct(r.file):void 0,t=e?"output a bulb block; it renders live here":"start the viewer yourself \u2014 `npx typebulb agent:claude --no-open` \u2014 share the localhost link it prints, then output a bulb block",n=[e?`You ran \`typebulb agent\`. Viewer '${e}' is up.`:"You ran `typebulb agent`. No viewer is running.",`- To show a bulb inline in this chat: ${t}.`,"- To make a bulb to keep and iterate on: write a .bulb.md and run `npx typebulb my-bulb.bulb.md`.","Working with bulbs? Run `npx typebulb skill` for the full authoring guide \u2014 save it to your skills folder if the user wants bulbs on hand across sessions."];process.stdout.write(n.join(`
629
+ </script>`;function Is(r){return r.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function $s(r){let e={};for(let[t,n]of Object.entries(r))e[t]=n.startsWith("https://")?"/proxy/"+n:n;return e}import*as tt from"fs/promises";import*as et from"path";import{existsSync as Jr,readFileSync as Ds}from"fs";import{execFile as Ms}from"child_process";import{promisify as js}from"util";import{satisfies as Bs}from"semver";var Fs=js(Ms);async function rt(r,e,t){let s=r.map(i=>Ls(i,t)).filter(i=>!Ns(i,e));if(s.length===0)return;await tt.mkdir(e,{recursive:!0});let o=et.join(e,"package.json");Jr(o)||await tt.writeFile(o,JSON.stringify({name:"typebulb-server",private:!0})),console.log(` Installing: ${s.join(", ")}`),await Fs("npm",["install","--no-audit","--no-fund",...s],{cwd:e,shell:!0})}function Ls(r,e){if(!e||Hr(r))return r;let t=e[r];return t?`${r}@${t}`:r}function Ns(r,e){let t=et.join(e,"node_modules",Vr(r));if(!Jr(t))return!1;let n=Hr(r);if(!n)return!0;try{let s=JSON.parse(Ds(et.join(t,"package.json"),"utf-8")).version;return Bs(s,n)}catch{return!1}}function nt(r){let e=new Set,t=/\bimport\s+(?:[\s\S]*?\s+from\s+)?['"]([^./][^'"]*)['"]/g,n;for(;n=t.exec(r);){let s=n[1];if(s.includes(":"))continue;let o=s.startsWith("@")?s.split("/").slice(0,2).join("/"):s.split("/")[0];e.add(o)}return[...e]}function Vr(r){if(r.startsWith("@")){let t=r.indexOf("/");if(t<0)return r;let n=r.indexOf("@",t+1);return n<0?r:r.slice(0,n)}let e=r.indexOf("@");return e<0?r:r.slice(0,e)}function Hr(r){let e=Vr(r);return r.length>e.length?r.slice(e.length+1):""}async function qr(r){let t=(await X.readdir(r)).find(n=>n.endsWith(".bulb.md"));return t?st.join(r,t):null}function Lt(r){let e=mr(r);if(!e)throw new Error("Invalid .bulb.md file format");let t=hr(e);return{bulb:t,config:br(t.config)}}async function W(r){return Lt(await X.readFile(r,"utf-8"))}async function Nt(r,e,t,n){let s=Et(r,{serverOnly:!0});if(s.error)throw new Error(`Server compilation error: ${s.error}`);let o=s.code;t&&(o=await ur(o,t));let i=st.join(e,".typebulb");await X.mkdir(i,{recursive:!0});let a=nt(o);a.length>0&&await rt(a,i,n);let c=st.join(i,"server.mjs");return await X.writeFile(c,o,"utf-8"),await import(`${Us(c).href}?t=${Date.now()}`)}async function Ut(r,e,t,n,s){let{bulb:o,config:i}=await W(r),a=gr(o.data),c=Et(o.code,{jsxImportSource:i.jsxImportSource});c.error&&console.error("Compilation error:",c.error);let{importMap:l}=await Ze.buildImportMap(c.code,i.dependencies??{},n?new Set([n.name]):void 0);n&&(l.imports[n.name]=n.entryUrl);let p=Wr({name:o.name,code:c.code,css:o.css,html:o.html,data:a,insight:o.insight,importMap:l,watch:e}),d=null;return o.server&&t&&(d=await Nt(o.server,s,n,i.dependencies)),{html:p,bulb:o,serverExports:d}}import{readFileSync as Vs,writeFileSync as Hs,mkdirSync as qs}from"fs";import{join as zs}from"path";import{join as Wt,resolve as Ws}from"path";import{homedir as Js}from"os";function ot(){let r=process.env.TYPEBULB_SERVERS_DIR;return r?Wt(r,".."):Wt(Js(),".typebulb")}function te(){return process.env.TYPEBULB_SERVERS_DIR||Wt(ot(),"servers")}function D(r){let e=Ws(r);return(process.platform==="win32"?e.toLowerCase():e).replace(/\\/g,"/")}function zr(r,e){let t=D(r),n=D(e);return t.startsWith(n.endsWith("/")?n:n+"/")?!t.includes("/node_modules/"):!1}function Gr(){return zs(ot(),"trust.json")}function Jt(){try{let r=JSON.parse(Vs(Gr(),"utf8"));return new Set(Array.isArray(r)?r:[])}catch{return new Set}}function Gs(r){qs(ot(),{recursive:!0}),Hs(Gr(),JSON.stringify([...r]))}function it(r){return Jt().has(D(r))}function Kr(r,e){let t=Jt(),n=D(r);(e?t.has(n):!t.has(n))||(e?t.add(n):t.delete(n),Gs(t))}function Yr(){return[...Jt()]}import Ks from"open";async function at(r){await Ks(r)}import*as J from"path";import{fileURLToPath as Ys}from"url";var ct={claude:{file:"claude.bulb.md",srcEnv:"TYPEBULB_CLAUDE_SRC",viewer:!0}};function me(r){let e=ct[r];if(!e)return;let t=e.srcEnv?process.env[e.srcEnv]:void 0;return t?J.resolve(t):J.join(J.dirname(Ys(import.meta.url)),"..","bulbs",e.file)}function lt(r){let e=J.basename(r).toLowerCase();for(let[t,n]of Object.entries(ct))if(n.viewer&&n.file.toLowerCase()===e)return t}function Vt(){return Object.entries(ct).filter(([,r])=>r.viewer).map(([r])=>r)}function Xr(r){let e=J.basename(r).toLowerCase();return Object.values(ct).some(t=>t.file.toLowerCase()===e)}import*as nn from"path";import{spawn as po}from"child_process";import*as E from"fs/promises";import*as R from"path";import*as he from"path";var Xs=he.join(Ke,"pkg"),Qs=he.join(Ke,"files"),Zs=he.join(Ke,"negative.json"),ut=class{pkgMem=new Map;fileMem=new Map;negativeCache=new Z(new pe(Zs));async getCachedDts(e){if(this.pkgMem.has(e))return this.pkgMem.get(e);await x();let t=await ee(Qr(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 dt(async()=>{await x(),await C(Qr(e),JSON.stringify(s))})}async getCachedFile(e){if(this.fileMem.has(e))return this.fileMem.get(e);await x();let t=await Ge(Zr(e));return this.fileMem.set(e,t),t}async setCachedFile(e,t){this.fileMem.set(e,t),await dt(async()=>{await x(),await C(Zr(e),t)})}isNegative(e){return this.negativeCache.isNegative(e)}async recordNegative(e){await dt(async()=>{await x(),await this.negativeCache.recordNegative(e)})}clearNegative(e){return dt(()=>this.negativeCache.clearNegative(e))}};async function dt(r){try{await r()}catch{}}function Qr(r){return he.join(Xs,I(r)+".json")}function Zr(r){return he.join(Qs,I(r)+".txt")}var Ht;function eo(){return Ht||(Ht=Mt({cache:new ut,cdnClient:Nr,packageService:Ze,versionResolver:Lr})),Ht}var en="file:///node_modules/";async function tn(r){let e=Ye(r.emitKey,"typecheck");await x(),await E.rm(e,{recursive:!0,force:!0}),await E.mkdir(e,{recursive:!0});let t=so(r.jsxImportSource,r.dependencies),n=await eo().resolve(r.code,r.dependencies,t),s=r.local?.name,o=s?n.filter(p=>p.pkg!==s):n,i=new Set;for(let p of o)for(let d of p.files){let m=pt(d.path);if(!m||i.has(m))continue;i.add(m);let h=R.join(e,"node_modules",m);await E.mkdir(R.dirname(h),{recursive:!0}),await E.writeFile(h,d.content,"utf8")}let a={};for(let p of o)for(let d of p.shims){let m=pt(d.path);m&&(a[d.module]=[`./node_modules/${m}`])}for(let p of o){if(p.ambient)continue;let d=pt(p.mainPath);d&&(a[p.pkg]=[`./node_modules/${d}`])}let c=new Set;for(let p of o)for(let d of p.files){if(!d.ambient)continue;let m=pt(d.path);m&&c.add(`node_modules/${m}`)}if(r.local){delete a[r.local.name];let p=await oo(r.local,e);p?a[r.local.name]=[`./node_modules/${r.local.name}/${p}`]:console.warn(` local: '${r.local.name}' ships no type defs; check cannot type against it.`)}let l=to(r.jsxImportSource,a,[...c]);return await E.writeFile(R.join(e,"tsconfig.json"),JSON.stringify(l,null,2)+`
630
+ `,"utf8"),await E.writeFile(R.join(e,"code.tsx"),r.code,"utf8"),await E.writeFile(R.join(e,"tb.d.ts"),At,"utf8"),{dir:e}}function to(r,e,t=[]){return{compilerOptions:{target:"es2023",module:"esnext",moduleResolution:"bundler",lib:ro([...Ct,...Ot]),jsx:"react-jsx",jsxImportSource:r??"react",strict:!0,noEmit:!0,skipLibCheck:!0,esModuleInterop:!0,allowSyntheticDefaultImports:!0,forceConsistentCasingInFileNames:!0,baseUrl:".",paths:e},include:["code.tsx","tb.d.ts",...t]}}function ro(r){return r.filter(e=>!e.since).map(e=>no(e.name))}function no(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 pt(r){if(!r.startsWith(en))return;let e=r.slice(en.length),t=e.indexOf("/");if(!(t<0))return e.slice(t+1)}async function oo(r,e){if(!r.typesAbs)return;let t=R.dirname(r.typesAbs),n=R.join(e,"node_modules",r.name);for(let s of await io(t)){let o=R.join(n,R.relative(t,s));await E.mkdir(R.dirname(o),{recursive:!0}),await E.copyFile(s,o)}return R.basename(r.typesAbs)}async function io(r){let e=[];async function t(n){let s=await E.readdir(n,{withFileTypes:!0});for(let o of s){let i=R.join(n,o.name);o.isDirectory()?await t(i):/\.d\.ts(\.map)?$/.test(o.name)&&e.push(i)}}return await t(r),e}import*as O from"fs/promises";import*as V from"path";import{existsSync as ao}from"fs";var co="^22";async function rn(r){let e=Ye(r.emitKey,"typecheck-server");await x(),await O.rm(e,{recursive:!0,force:!0}),await O.mkdir(e,{recursive:!0});let t=V.join(r.bulbDir,".typebulb"),n=nt(r.server).filter(i=>i!==r.local?.name);await rt([`@types/node@${co}`,...n],t,r.dependencies);let s=V.join(t,"node_modules"),o=V.join(e,"node_modules");return await uo(s,o),await O.writeFile(V.join(e,"server.ts"),r.server,"utf8"),await O.writeFile(V.join(e,"tb.d.ts"),It,"utf8"),await O.writeFile(V.join(e,"tsconfig.json"),JSON.stringify(lo(r.local),null,2)+`
631
+ `,"utf8"),{dir:e}}function lo(r){let e={target:"es2023",module:"esnext",moduleResolution:"bundler",lib:["ES2023"],types:["node"],strict:!0,noEmit:!0,skipLibCheck:!0,esModuleInterop:!0,allowSyntheticDefaultImports:!0,forceConsistentCasingInFileNames:!0};if(r?.typesAbs){let t=o=>o.replace(/\\/g,"/"),n=t(V.dirname(r.typesAbs)),s=t(r.typesAbs).replace(/\.d\.ts$/,"");e.baseUrl=".",e.paths={[r.name]:[s],[`${r.name}/*`]:[`${n}/*`]}}return{compilerOptions:e,include:["server.ts","tb.d.ts"]}}async function uo(r,e){if(!ao(r)){await O.mkdir(e,{recursive:!0});return}await O.rm(e,{recursive:!0,force:!0});let t=process.platform==="win32"?"junction":"dir";await O.symlink(r,e,t)}async function sn(r,e){await an(await W(r),{emitKey:r,bulbDir:nn.dirname(r),local:e})}async function on(r){let e=await fo(),t,n;try{t=Lt(e),n=r?await Je(r):void 0}catch(s){console.error(s instanceof Error?s.message:String(s)),process.exit(1)}await an(t,{emitKey:"<stdin>",bulbDir:process.cwd(),local:n})}async function an({bulb:r,config:e},{emitKey:t,bulbDir:n,local:s}){!r.code&&!r.server&&(console.error("Bulb has neither **code.tsx** nor **server.ts**; nothing to check."),process.exit(1));let o=[];if(r.code){let{dir:a}=await tn({code:r.code,dependencies:e.dependencies??{},jsxImportSource:e.jsxImportSource,emitKey:t,local:s});o.push({role:"client",dir:a})}if(r.server){let{dir:a}=await rn({server:r.server,bulbDir:n,emitKey:t,local:s?{name:s.name,typesAbs:s.typesAbs}:void 0,dependencies:e.dependencies});o.push({role:"server",dir:a})}let i=!1;for(let{role:a,dir:c}of o){let{stdout:l,exitCode:p}=await mo(c);for(let d of l.split(/\r?\n/))d.trim()&&console.log(`${a} ${d}`);p!==0&&(i=!0)}i&&process.exit(1)}async function fo(){let r=[];for await(let e of process.stdin)r.push(e);return Buffer.concat(r).toString("utf-8")}function mo(r){return new Promise(e=>{let t=po("npx",["tsc","--noEmit"],{cwd:r,shell:!0}),n="";t.stdout?.on("data",s=>{n+=s.toString()}),t.stderr?.on("data",s=>{n+=s.toString()}),t.on("close",s=>e({stdout:n,exitCode:s??1}))})}function ft(r){if(r.server.trim())return"server-side code (server.ts)";let e=r.code;if(/\btb\s*\.\s*fs\b/.test(e)||e.includes("/__fs"))return"the filesystem";if(/\btb\s*\.\s*ai\b/.test(e)||e.includes("/__ai"))return"AI (your API keys)";if(/\btb\s*\.\s*server\s*\.\s*(?!log\b)\w/.test(e)||e.includes("/__api"))return"server-side code (server.ts)"}async function cn(r,e){let{bulb:t}=await W(r),n=ft(t);if(it(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.)")}import*as Me from"path";async function ln(r,e){if(!r){e||(console.error("Usage: typebulb untrust <file.bulb.md>"),process.exit(1));let n=Yr();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=Me.resolve(r);t.endsWith(".bulb.md")||(console.error("File must have .bulb.md extension"),process.exit(1)),Kr(t,e),console.log(e?`Trusted ${Me.basename(t)} \u2014 runs with fs / AI / server.ts (no --trust needed).`:`Untrusted ${Me.basename(t)} \u2014 runs Restricted.`),console.log(` ${t}`)}import{readdir as ho,readFile as pn,writeFile as fn,unlink as je,mkdir as go}from"fs/promises";import{mkdirSync as bo,writeFileSync as dn,appendFileSync as yo,readFileSync as mn}from"fs";import*as re from"path";var un=1e6;function qt(r){return re.join(te(),`${r}.json`)}function mt(r){return re.join(te(),`${r}.log`)}function hn(r){let e=mt(r);try{bo(te(),{recursive:!0}),dn(e,"")}catch{return()=>{}}let t=process.stdout.write.bind(process.stdout),n=process.stderr.write.bind(process.stderr),s=0,o=!1,i=a=>{if(!o)try{let c=typeof a=="string"?Buffer.from(a,"utf8"):Buffer.from(a);if(yo(e,c),s+=c.length,s>2*un){let l=mn(e),p=l.subarray(Math.max(0,l.length-un));dn(e,p),s=p.length}}catch{o=!0}};return process.stdout.write=((a,...c)=>(i(a),t(a,...c))),process.stderr.write=((a,...c)=>(i(a),n(a,...c))),()=>{process.stdout.write=t,process.stderr.write=n}}function zt(r,e=0){try{let t=mn(mt(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 vo(r){try{return process.kill(r,0),!0}catch(e){return e.code==="EPERM"}}async function gn(r){await go(te(),{recursive:!0}),await fn(qt(r.pid),JSON.stringify(r))}async function bn(r,e){let t=qt(r);try{let n=JSON.parse(await pn(t,"utf8"));if(n.denied===e)return;n.denied=e,await fn(t,JSON.stringify(n))}catch{}}async function Gt(r){await je(qt(r)).catch(()=>{}),await je(mt(r)).catch(()=>{})}async function ne(r){let e;try{e=await ho(te())}catch{return[]}let t=[];return await Promise.all(e.map(async s=>{if(!s.endsWith(".json"))return;let o=re.join(te(),s),i;try{i=JSON.parse(await pn(o,"utf8"))}catch{await je(o).catch(()=>{});return}i&&typeof i.pid=="number"&&vo(i.pid)?t.push(i):(await je(o).catch(()=>{}),i?.pid&&await je(mt(i.pid)).catch(()=>{}))})),(r?t.filter(s=>zr(s.file,r)&&!Xr(s.file)):t).sort((s,o)=>s.startedAt-o.startedAt)}async function yn(r){try{process.kill(r,"SIGTERM")}catch{}await Gt(r)}async function Kt(r,e){let t=D(r);return(await ne()).find(n=>n.cwd!=null&&D(n.cwd)===t&&(e?lt(n.file)===e:lt(n.file)!=null))}async function vn(){let r=await Kt(process.cwd()),e=r?lt(r.file):void 0,t=e?"output a bulb block; it renders live here":"start the viewer yourself \u2014 `npx typebulb agent:claude --no-open` \u2014 share the localhost link it prints, then output a bulb block",n=[e?`You ran \`typebulb agent\`. Viewer '${e}' is up at ${r?.url}.`:"You ran `typebulb agent`. No viewer is running.",`- To show a bulb inline in this chat: ${t}.`,"- To make a bulb to keep and iterate on: write a .bulb.md and run `npx typebulb my-bulb.bulb.md`.","Working with bulbs? Run `npx typebulb skill` for the full authoring guide \u2014 save it to your skills folder if the user wants bulbs on hand across sessions."];process.stdout.write(n.join(`
630
632
  `)+`
631
- `),process.exitCode=e?0:1}import{readFileSync as go,existsSync as bo}from"fs";import*as H from"path";function yo(r){return[...r?[`.env.${r}.local`,`.env.${r}`]:[],".env.local",".env"]}function ge(r,e=process.cwd()){let t={},n=[];for(let s of yo(r)){let o;try{o=go(H.resolve(e,s),"utf-8")}catch{continue}n.push(s);for(let[i,a]of vo(o))process.env[i]===void 0&&(process.env[i]=a,t[i]=s)}return{mode:r,sources:t,loaded:n}}function*vo(r){for(let e of r.split(`
632
- `)){let t=e.trim();if(!t||t.startsWith("#"))continue;let n=t.indexOf("=");if(n===-1)continue;let s=t.slice(0,n).trim(),o=t.slice(n+1).trim();(o.startsWith('"')&&o.endsWith('"')||o.startsWith("'")&&o.endsWith("'"))&&(o=o.slice(1,-1)),yield[s,o]}}function wo(r){let e=new Set,t=/process\.env\.([A-Za-z_$][\w$]*)|process\.env\[\s*['"]([^'"]+)['"]\s*\]/g;for(let n;n=t.exec(r);)e.add(n[1]??n[2]);return[...e]}function mt(r,e,t){let{sources:n,mode:s,loaded:o}=r,i=process.cwd(),a=H.dirname(e),c=`(mode: ${s??"none"})`,l=t?wo(t):[],p=l.filter(h=>n[h]).map(h=>`${h} \u2190 ${n[h]}`);p.length?console.log(`env: ${p.join(", ")} ${c}`):o.length&&console.log(`env: loaded ${o.join(", ")} ${c}`),s&&!o.some(h=>h===`.env.${s}`||h===`.env.${s}.local`)&&console.log(`env: mode=${s} \u2014 no .env.${s} found; using .env`);let d=H.resolve(a)!==H.resolve(i);if(d)for(let h of[".env.local",".env"])bo(H.join(a,h))&&console.log(`env: ${H.join(a,h)} present but not loaded (cwd is ${i})`);let m=l.filter(h=>process.env[h]===void 0);if(m.length){let h=d?` \u2014 try running from ${a}`:"";console.log(`env: server.ts reads ${m.join(", ")} but ${m.length>1?"they are":"it's"} unset${h}`)}}var ye={anthropic:"ANTHROPIC_API_KEY",openai:"OPENAI_API_KEY",gemini:"GOOGLE_API_KEY",openrouter:"OPENROUTER_API_KEY"},xo="https://api.typebulb.com/api/models",So=1440*60*1e3,be=null;async function ht(){if(!be||Date.now()-be.fetchedAt>So){let r=await fetch(xo);if(!r.ok)return be?bn(be.models):[];be={models:await r.json(),fetchedAt:Date.now()}}return bn(be.models)}function bn(r){let e=new Set(Object.entries(ye).filter(([,t])=>!!process.env[t]).map(([t])=>t));return r.filter(t=>e.has(t.provider))}function yn(){return Object.values(ye).some(r=>!!process.env[r])}function vn(r,e,t){let n=Math.max(...r.map(i=>i.name.length)),s=Math.max(...r.map(i=>i.friendlyName.length)),o=["Models available to tb.ai (filtered by your .env keys):",""];for(let i of r)o.push(` ${i.name.padEnd(n)} ${i.friendlyName.padEnd(s)} (${i.provider})`);return o.push("","Pass an id as the `model` in tb.ai({ provider, model })."),e&&t&&o.push(`Default (from .env): ${e} / ${t}`),o.join(`
633
- `)}async function wn(r){if(ge(r),!yn()){console.log("No AI provider keys found in this directory's .env. Set one of these to use tb.ai:");for(let[t,n]of Object.entries(ye))console.log(` ${n.padEnd(20)} (${t})`);console.log("Then re-run `typebulb models`.");return}let e=await ht();if(e.length===0){console.log("Couldn't fetch the model catalog (offline?). tb.ai still works with any valid provider/model id for your keys.");return}console.log(vn(e,process.env.TB_AI_PROVIDER,process.env.TB_AI_MODEL))}import*as Sn from"fs/promises";import*as gt from"path";import{fileURLToPath as Eo}from"url";function Po(r){return`---
633
+ `)}import{readFileSync as wo,existsSync as xo}from"fs";import*as H from"path";function So(r){return[...r?[`.env.${r}.local`,`.env.${r}`]:[],".env.local",".env"]}function ge(r,e=process.cwd()){let t={},n=[];for(let s of So(r)){let o;try{o=wo(H.resolve(e,s),"utf-8")}catch{continue}n.push(s);for(let[i,a]of Po(o))process.env[i]===void 0&&(process.env[i]=a,t[i]=s)}return{mode:r,sources:t,loaded:n}}function*Po(r){for(let e of r.split(`
634
+ `)){let t=e.trim();if(!t||t.startsWith("#"))continue;let n=t.indexOf("=");if(n===-1)continue;let s=t.slice(0,n).trim(),o=t.slice(n+1).trim();(o.startsWith('"')&&o.endsWith('"')||o.startsWith("'")&&o.endsWith("'"))&&(o=o.slice(1,-1)),yield[s,o]}}function Ro(r){let e=new Set,t=/process\.env\.([A-Za-z_$][\w$]*)|process\.env\[\s*['"]([^'"]+)['"]\s*\]/g;for(let n;n=t.exec(r);)e.add(n[1]??n[2]);return[...e]}function ht(r,e,t){let{sources:n,mode:s,loaded:o}=r,i=process.cwd(),a=H.dirname(e),c=`(mode: ${s??"none"})`,l=t?Ro(t):[],p=l.filter(h=>n[h]).map(h=>`${h} \u2190 ${n[h]}`);p.length?console.log(`env: ${p.join(", ")} ${c}`):o.length&&console.log(`env: loaded ${o.join(", ")} ${c}`),s&&!o.some(h=>h===`.env.${s}`||h===`.env.${s}.local`)&&console.log(`env: mode=${s} \u2014 no .env.${s} found; using .env`);let d=H.resolve(a)!==H.resolve(i);if(d)for(let h of[".env.local",".env"])xo(H.join(a,h))&&console.log(`env: ${H.join(a,h)} present but not loaded (cwd is ${i})`);let m=l.filter(h=>process.env[h]===void 0);if(m.length){let h=d?` \u2014 try running from ${a}`:"";console.log(`env: server.ts reads ${m.join(", ")} but ${m.length>1?"they are":"it's"} unset${h}`)}}var ye={anthropic:"ANTHROPIC_API_KEY",openai:"OPENAI_API_KEY",gemini:"GOOGLE_API_KEY",openrouter:"OPENROUTER_API_KEY"},Eo="https://api.typebulb.com/api/models",ko=1440*60*1e3,be=null;async function gt(){if(!be||Date.now()-be.fetchedAt>ko){let r=await fetch(Eo);if(!r.ok)return be?wn(be.models):[];be={models:await r.json(),fetchedAt:Date.now()}}return wn(be.models)}function wn(r){let e=new Set(Object.entries(ye).filter(([,t])=>!!process.env[t]).map(([t])=>t));return r.filter(t=>e.has(t.provider))}function xn(){return Object.values(ye).some(r=>!!process.env[r])}function Sn(r,e,t){let n=Math.max(...r.map(i=>i.name.length)),s=Math.max(...r.map(i=>i.friendlyName.length)),o=["Models available to tb.ai (filtered by your .env keys):",""];for(let i of r)o.push(` ${i.name.padEnd(n)} ${i.friendlyName.padEnd(s)} (${i.provider})`);return o.push("","Pass an id as the `model` in tb.ai({ provider, model })."),e&&t&&o.push(`Default (from .env): ${e} / ${t}`),o.join(`
635
+ `)}async function Pn(r){if(ge(r),!xn()){console.log("No AI provider keys found in this directory's .env. Set one of these to use tb.ai:");for(let[t,n]of Object.entries(ye))console.log(` ${n.padEnd(20)} (${t})`);console.log("Then re-run `typebulb models`.");return}let e=await gt();if(e.length===0){console.log("Couldn't fetch the model catalog (offline?). tb.ai still works with any valid provider/model id for your keys.");return}console.log(Sn(e,process.env.TB_AI_PROVIDER,process.env.TB_AI_MODEL))}import*as En from"fs/promises";import*as bt from"path";import{fileURLToPath as Co}from"url";function To(r){return`---
634
636
  name: typebulb
635
637
  description: Author and run Typebulb bulbs \u2014 single-file markdown apps (TypeScript/TSX) that run locally via \`npx typebulb\` (full power: filesystem, database, \`server.ts\`, \`tb.ai\`) or render live inline in a Claude Code session through Typebulb's agent viewer (sandboxed, client-only). A bulb can be a visual widget (chart, simulation, diagram, calculator, UI), a full-stack tool with a Node backend, or an AI app that calls models at runtime. Covers the bulb format, the \`tb.*\` API, trust, and the local run/embed workflow. Use when the user wants a bulb, a quick local tool (visual, backend-backed, or AI-powered), or something visual rendered inline in the conversation.
636
638
  version: ${r}
637
- ---`}function Ro(r){return`> Generated from typebulb v${r}. If \`npx typebulb --version\` reports a newer version, re-run \`npx typebulb skill\` to refresh this file.`}function xn(r,e){return`${Po(e)}
639
+ ---`}function _o(r){return`> Generated from typebulb v${r}. If \`npx typebulb --version\` reports a newer version, re-run \`npx typebulb skill\` to refresh this file.`}function Rn(r,e){return`${To(e)}
638
640
 
639
- ${Ro(e)}
641
+ ${_o(e)}
640
642
 
641
643
  ${r.trim()}
642
- `}async function Pn(r){let e=gt.join(gt.dirname(Eo(import.meta.url)),"..","README.md"),t;try{t=await Sn.readFile(e,"utf8")}catch{console.error(`Could not read the bundled README (expected at ${e}).`),process.exit(1)}process.stdout.write(xn(t,r))}import*as Rn from"path";function ko(r,e){return/^\d+$/.test(e)?r.find(t=>t.pid===parseInt(e,10)):r.find(t=>D(t.file)===D(e))}function En(r,e){for(let t of r)e(` ${t.url} pid ${t.pid} ${t.trust?"trusted":"restricted"} ${t.file}`)}function kn(r,e){if(!r.length){console.log("No running bulb servers.");return}console.log("Running bulb servers:"),En(r,t=>console.log(t)),console.log(`
643
- `+e)}function Tn(r,e,t){let n=ko(r,e);if(n)return n;console.error(`No running server for '${e}'.`),r.length?(console.error(`Running servers (try \`typebulb ${t} <file|pid>\`):`),En(r,s=>console.error(s))):console.error("No bulb servers are running."),process.exit(1)}async function _n(r,e){if(!r){kn(await ne(process.cwd()),"Run `typebulb logs <file|pid>` to print one server's console.");return}let t=Tn(await ne(),me(r)??r,"logs"),n=Ht(t.pid),s=n.text;if(e.lines&&e.lines>0){let o=s.split(`
644
+ `}async function kn(r){let e=bt.join(bt.dirname(Co(import.meta.url)),"..","README.md"),t;try{t=await En.readFile(e,"utf8")}catch{console.error(`Could not read the bundled README (expected at ${e}).`),process.exit(1)}process.stdout.write(Rn(t,r))}import*as Tn from"path";function Oo(r,e){return/^\d+$/.test(e)?r.find(t=>t.pid===parseInt(e,10)):r.find(t=>D(t.file)===D(e))}function _n(r,e){for(let t of r)e(` ${t.url} pid ${t.pid} ${t.trust?"trusted":"restricted"} ${t.file}`)}function Cn(r,e){if(!r.length){console.log("No running bulb servers.");return}console.log("Running bulb servers:"),_n(r,t=>console.log(t)),console.log(`
645
+ `+e)}function On(r,e,t){let n=Oo(r,e);if(n)return n;console.error(`No running server for '${e}'.`),r.length?(console.error(`Running servers (try \`typebulb ${t} <file|pid>\`):`),_n(r,s=>console.error(s))):console.error("No bulb servers are running."),process.exit(1)}async function An(r,e){if(!r){Cn(await ne(process.cwd()),"Run `typebulb logs <file|pid>` to print one server's console.");return}let t=On(await ne(),me(r)??r,"logs"),n=zt(t.pid),s=n.text;if(e.lines&&e.lines>0){let o=s.split(`
644
646
  `);o.length&&o[o.length-1]===""&&o.pop(),s=o.slice(-e.lines).join(`
645
647
  `)}if(process.stdout.write(s),s&&!s.endsWith(`
646
648
  `)&&process.stdout.write(`
647
- `),e.follow){let o=n.offset,i=setInterval(()=>{let c=Ht(t.pid,o);o=c.offset,c.text&&process.stdout.write(c.text)},500),a=()=>{clearInterval(i),process.exit(0)};process.on("SIGINT",a),process.on("SIGTERM",a),await new Promise(()=>{})}}async function Cn(r){if(!r){kn(await ne(process.cwd()),"Run `typebulb stop <file|pid>` to stop one.");return}let e=Tn(await ne(),me(r)??r,"stop");await hn(e.pid),console.log(`Stopped ${Rn.basename(e.file)} (pid ${e.pid}, ${e.url}).`)}import*as Bn from"fs/promises";import*as ve from"path";import{EventEmitter as Nn}from"events";import{Hono as _o}from"hono";import{serve as Co}from"@hono/node-server";import{streamSSE as Ao}from"hono/streaming";import*as oe from"fs/promises";import*as j from"path";var I=class extends Error{constructor(e,t="unknown",n=!1){super(e),this.code=t,this.retryable=n}},M=class{getPath(e,t){return this.path}parseStreamChunk(e){return this.checkAndThrowError(e),this.parseProviderStreamChunk(e)}isReasoningEnabled(e){return e?.reasoning!==void 0&&e.reasoning>0}extractSystemMessages(e,t=`
649
+ `),e.follow){let o=n.offset,i=setInterval(()=>{let c=zt(t.pid,o);o=c.offset,c.text&&process.stdout.write(c.text)},500),a=()=>{clearInterval(i),process.exit(0)};process.on("SIGINT",a),process.on("SIGTERM",a),await new Promise(()=>{})}}async function In(r){if(!r){Cn(await ne(process.cwd()),"Run `typebulb stop <file|pid>` to stop one.");return}let e=On(await ne(),me(r)??r,"stop");await yn(e.pid),console.log(`Stopped ${Tn.basename(e.file)} (pid ${e.pid}, ${e.url}).`)}import*as Wn from"fs/promises";import*as ve from"path";import{EventEmitter as Un}from"events";import{Hono as Io}from"hono";import{serve as $o}from"@hono/node-server";import{streamSSE as Do}from"hono/streaming";import*as oe from"fs/promises";import*as j from"path";var A=class extends Error{constructor(e,t="unknown",n=!1){super(e),this.code=t,this.retryable=n}},M=class{getPath(e,t){return this.path}parseStreamChunk(e){return this.checkAndThrowError(e),this.parseProviderStreamChunk(e)}isReasoningEnabled(e){return e?.reasoning!==void 0&&e.reasoning>0}extractSystemMessages(e,t=`
648
650
 
649
- `){let n=e.filter(s=>s.role==="system").map(s=>s.content);return{system:n.length?n.join(t):void 0,conversationMessages:e.filter(s=>s.role!=="system")}}parseJsonError(e,t,n=!1){if(!e)return{message:`HTTP ${t}`};try{let s=JSON.parse(e);if(s.error&&typeof s.error=="object"){let o={message:s.error.message||`HTTP ${t}`,type:s.error.type};return n&&(o.code=s.error.code),o}return s.message?{message:s.message}:{message:e}}catch{return{message:e}}}checkAndThrowError(e){if("type"in e&&e.type==="error"&&"message"in e){let t=e.message,n=e.code||"unknown",s=!!e.retryable;throw new I(t,n,s)}if("error"in e&&e.error){let t=this.extractErrorMessage(e.error);throw new I(t)}}extractErrorMessage(e){if(typeof e=="string")try{let t=JSON.parse(e);return t.error?.message||t.message||e}catch{return e}return typeof e=="object"&&e!==null?e.message||JSON.stringify(e):`${this.providerName} returned an error`}};var Fe=class extends M{constructor(){super(...arguments),this.providerName="Anthropic",this.defaultBaseUrl="https://api.anthropic.com",this.path="/v1/messages"}buildHeaders(e){return{"x-api-key":e,"anthropic-version":"2023-06-01","Content-Type":"application/json",Accept:"application/json"}}buildPayload(e,t,n,s){let{system:o,conversationMessages:i}=this.extractSystemMessages(e),a={model:t,max_tokens:this.getMaxTokens(t),messages:this.withLastMessageCached(i),stream:s};if(n?.webSearch!==!1&&(a.tools=[{type:"web_search_20250305",name:"web_search"}]),o&&(a.system=[{type:"text",text:o,cache_control:{type:"ephemeral"}}]),this.isReasoningEnabled(n)){let c=n.reasoning;if(this.isModernModel(t)){let l={0:"low",1:"low",2:"medium",3:"high"};a.thinking={type:"adaptive"},a.output_config={effort:l[c]}}else{let l={0:0,1:2048,2:4096,3:8192};a.thinking={type:"enabled",budget_tokens:l[c]}}}return a}parseError(e,t){return this.parseJsonError(e,t)}parseNonStreamingResponse(e){if(!this.isAnthropicResponse(e))return{text:""};let t=e.content.filter(s=>s.type==="text").map(s=>s.text).join(""),n=e.content.filter(s=>s.type==="thinking").map(s=>s.thinking).join(`
651
+ `){let n=e.filter(s=>s.role==="system").map(s=>s.content);return{system:n.length?n.join(t):void 0,conversationMessages:e.filter(s=>s.role!=="system")}}parseJsonError(e,t,n=!1){if(!e)return{message:`HTTP ${t}`};try{let s=JSON.parse(e);if(s.error&&typeof s.error=="object"){let o={message:s.error.message||`HTTP ${t}`,type:s.error.type};return n&&(o.code=s.error.code),o}return s.message?{message:s.message}:{message:e}}catch{return{message:e}}}checkAndThrowError(e){if("type"in e&&e.type==="error"&&"message"in e){let t=e.message,n=e.code||"unknown",s=!!e.retryable;throw new A(t,n,s)}if("error"in e&&e.error){let t=this.extractErrorMessage(e.error);throw new A(t)}}extractErrorMessage(e){if(typeof e=="string")try{let t=JSON.parse(e);return t.error?.message||t.message||e}catch{return e}return typeof e=="object"&&e!==null?e.message||JSON.stringify(e):`${this.providerName} returned an error`}};var Be=class extends M{constructor(){super(...arguments),this.providerName="Anthropic",this.defaultBaseUrl="https://api.anthropic.com",this.path="/v1/messages"}buildHeaders(e){return{"x-api-key":e,"anthropic-version":"2023-06-01","Content-Type":"application/json",Accept:"application/json"}}buildPayload(e,t,n,s){let{system:o,conversationMessages:i}=this.extractSystemMessages(e),a={model:t,max_tokens:this.getMaxTokens(t),messages:this.withLastMessageCached(i),stream:s};if(n?.webSearch!==!1&&(a.tools=[{type:"web_search_20250305",name:"web_search"}]),o&&(a.system=[{type:"text",text:o,cache_control:{type:"ephemeral"}}]),this.isReasoningEnabled(n)){let c=n.reasoning;if(this.isModernModel(t)){let l={0:"low",1:"low",2:"medium",3:"high"};a.thinking={type:"adaptive"},a.output_config={effort:l[c]}}else{let l={0:0,1:2048,2:4096,3:8192};a.thinking={type:"enabled",budget_tokens:l[c]}}}return a}parseError(e,t){return this.parseJsonError(e,t)}parseNonStreamingResponse(e){if(!this.isAnthropicResponse(e))return{text:""};let t=e.content.filter(s=>s.type==="text").map(s=>s.text).join(""),n=e.content.filter(s=>s.type==="thinking").map(s=>s.thinking).join(`
650
652
 
651
- `);return{text:t,reasoning:n||void 0}}parseProviderStreamChunk(e){if(!("type"in e))return null;switch(e.type){case"content_block_delta":return e.delta.type==="text_delta"?{text:e.delta.text||""}:e.delta.type==="thinking_delta"?{reasoning:e.delta.thinking||""}:null;case"message_start":case"content_block_start":case"content_block_stop":case"message_delta":case"message_stop":case"ping":return null;default:return null}}withLastMessageCached(e){let t=e.length-1;return e.map((n,s)=>s===t?{role:n.role,content:[{type:"text",text:n.content,cache_control:{type:"ephemeral"}}]}:n)}isAnthropicResponse(e){return"content"in e&&Array.isArray(e.content)&&"type"in e&&e.type==="message"}isModernModel(e){let t=e.match(/^claude-\w+-(\d+)-(\d+)/);return!!t&&(+t[1]>4||+t[1]==4&&+t[2]>=6)}getMaxTokens(e){return this.isModernModel(e)?64e3:32e3}};var Ne=class extends M{constructor(){super(...arguments),this.providerName="OpenAI",this.defaultBaseUrl="https://api.openai.com",this.path="/v1/responses",this.effortMap={0:"minimal",1:"low",2:"medium",3:"high"}}buildHeaders(e){return{Authorization:`Bearer ${e}`,"Content-Type":"application/json",Accept:"application/json"}}buildPayload(e,t,n,s){let o=this.convertMessagesToInput(e),i={model:t,input:o,stream:s};return n?.webSearch!==!1&&(i.tools=[{type:"web_search"}]),this.isReasoningEnabled(n)&&(i.reasoning={effort:this.effortMap[n.reasoning],summary:"auto"}),i}parseError(e,t){return this.parseJsonError(e,t,!0)}parseNonStreamingResponse(e){if(!this.isResponsesApiResponse(e))return{text:""};let t=e.output_text||"",n;if(e.output&&Array.isArray(e.output))for(let s of e.output)s.type==="reasoning"&&s.summary&&(n=s.summary.map(o=>o.text).join(`
652
- `)),!t&&s.type==="message"&&s.content&&(t=s.content.filter(o=>o.type==="output_text").map(o=>o.text).join(""));return{text:t,reasoning:n}}parseProviderStreamChunk(e){if(!this.isResponsesApiEvent(e))return null;switch(e.type){case"error":return null;case"response.failed":{let s=e.response?.error,o=s?.message||"Response failed",i=s?.code==="insufficient_quota"||s?.code==="rate_limit_exceeded";throw new I(o,i?"rate_limit":"unknown",i)}case"response.output_text.delta":return{text:e.delta};case"response.reasoning_summary_text.delta":return{reasoning:e.delta};case"response.created":case"response.in_progress":case"response.output_item.added":case"response.output_item.done":case"response.content_part.added":case"response.content_part.done":case"response.output_text.done":case"response.output_text.annotation.added":case"response.reasoning_summary_text.done":case"response.completed":case"response.web_search_call.in_progress":case"response.web_search_call.searching":case"response.web_search_call.completed":return null;default:return null}}convertMessagesToInput(e){return e.map(t=>t.role==="system"?`System: ${t.content}`:t.role==="user"?`User: ${t.content}`:t.role==="assistant"?`Assistant: ${t.content}`:t.content).join(`
653
+ `);return{text:t,reasoning:n||void 0}}parseProviderStreamChunk(e){if(!("type"in e))return null;switch(e.type){case"content_block_delta":return e.delta.type==="text_delta"?{text:e.delta.text||""}:e.delta.type==="thinking_delta"?{reasoning:e.delta.thinking||""}:null;case"message_start":case"content_block_start":case"content_block_stop":case"message_delta":case"message_stop":case"ping":return null;default:return null}}withLastMessageCached(e){let t=e.length-1;return e.map((n,s)=>s===t?{role:n.role,content:[{type:"text",text:n.content,cache_control:{type:"ephemeral"}}]}:n)}isAnthropicResponse(e){return"content"in e&&Array.isArray(e.content)&&"type"in e&&e.type==="message"}isModernModel(e){let t=e.match(/^claude-\w+-(\d+)-(\d+)/);return!!t&&(+t[1]>4||+t[1]==4&&+t[2]>=6)}getMaxTokens(e){return this.isModernModel(e)?64e3:32e3}};var Fe=class extends M{constructor(){super(...arguments),this.providerName="OpenAI",this.defaultBaseUrl="https://api.openai.com",this.path="/v1/responses",this.effortMap={0:"minimal",1:"low",2:"medium",3:"high"}}buildHeaders(e){return{Authorization:`Bearer ${e}`,"Content-Type":"application/json",Accept:"application/json"}}buildPayload(e,t,n,s){let o=this.convertMessagesToInput(e),i={model:t,input:o,stream:s};return n?.webSearch!==!1&&(i.tools=[{type:"web_search"}]),this.isReasoningEnabled(n)&&(i.reasoning={effort:this.effortMap[n.reasoning],summary:"auto"}),i}parseError(e,t){return this.parseJsonError(e,t,!0)}parseNonStreamingResponse(e){if(!this.isResponsesApiResponse(e))return{text:""};let t=e.output_text||"",n;if(e.output&&Array.isArray(e.output))for(let s of e.output)s.type==="reasoning"&&s.summary&&(n=s.summary.map(o=>o.text).join(`
654
+ `)),!t&&s.type==="message"&&s.content&&(t=s.content.filter(o=>o.type==="output_text").map(o=>o.text).join(""));return{text:t,reasoning:n}}parseProviderStreamChunk(e){if(!this.isResponsesApiEvent(e))return null;switch(e.type){case"error":return null;case"response.failed":{let s=e.response?.error,o=s?.message||"Response failed",i=s?.code==="insufficient_quota"||s?.code==="rate_limit_exceeded";throw new A(o,i?"rate_limit":"unknown",i)}case"response.output_text.delta":return{text:e.delta};case"response.reasoning_summary_text.delta":return{reasoning:e.delta};case"response.created":case"response.in_progress":case"response.output_item.added":case"response.output_item.done":case"response.content_part.added":case"response.content_part.done":case"response.output_text.done":case"response.output_text.annotation.added":case"response.reasoning_summary_text.done":case"response.completed":case"response.web_search_call.in_progress":case"response.web_search_call.searching":case"response.web_search_call.completed":return null;default:return null}}convertMessagesToInput(e){return e.map(t=>t.role==="system"?`System: ${t.content}`:t.role==="user"?`User: ${t.content}`:t.role==="assistant"?`Assistant: ${t.content}`:t.content).join(`
653
655
 
654
- `)}isResponsesApiEvent(e){return"type"in e&&typeof e.type=="string"}isResponsesApiResponse(e){return"object"in e&&e.object==="response"}};var Be=class extends M{constructor(){super(...arguments),this.providerName="Gemini",this.defaultBaseUrl="https://generativelanguage.googleapis.com",this.path="/v1beta/models"}getPath(e,t){return`/v1beta/models/${e}:${t?"streamGenerateContent":"generateContent"}${t?"?alt=sse":""}`}buildHeaders(e){return{"Content-Type":"application/json","x-goog-api-key":e}}buildPayload(e,t,n,s){let{system:o,conversationMessages:i}=this.extractSystemMessages(e,`
656
+ `)}isResponsesApiEvent(e){return"type"in e&&typeof e.type=="string"}isResponsesApiResponse(e){return"object"in e&&e.object==="response"}};var Le=class extends M{constructor(){super(...arguments),this.providerName="Gemini",this.defaultBaseUrl="https://generativelanguage.googleapis.com",this.path="/v1beta/models"}getPath(e,t){return`/v1beta/models/${e}:${t?"streamGenerateContent":"generateContent"}${t?"?alt=sse":""}`}buildHeaders(e){return{"Content-Type":"application/json","x-goog-api-key":e}}buildPayload(e,t,n,s){let{system:o,conversationMessages:i}=this.extractSystemMessages(e,`
655
657
  `),c={contents:i.map(l=>({role:l.role==="assistant"?"model":"user",parts:[{text:l.content}]}))};return n?.webSearch!==!1&&(c.tools=[{google_search:{}}]),o&&(c.systemInstruction={role:"system",parts:[{text:o}]}),this.isReasoningEnabled(n)&&(c.generationConfig={temperature:.7+n.reasoning*.1}),c}parseError(e,t){if(!e)return{message:`HTTP ${t}`};try{let n=JSON.parse(e),s=Array.isArray(n)?n[0]?.error:n?.error;return s&&typeof s=="object"?{message:(s.message||`HTTP ${t}`).split(`
656
- `)[0],type:s.status,code:s.code?.toString()}:n.message?{message:n.message}:{message:e}}catch{return{message:e}}}parseNonStreamingResponse(e){if(this.checkGeminiError(e),!this.isGeminiResponse(e))return{text:"",status:"failed",error:"Invalid response format"};let t=this.extractText(e)||"",n=e.candidates?.[0]?.finishReason,s="complete";return n==="MAX_TOKENS"?s="interrupted":(n==="SAFETY"||n==="RECITATION")&&(s="failed"),{text:t,status:s}}parseProviderStreamChunk(e){if(this.checkGeminiError(e),!this.isGeminiResponse(e))return null;let t=this.extractText(e);return t?{text:t}:null}isGeminiResponse(e){return typeof e=="object"&&e!==null&&"candidates"in e&&Array.isArray(e.candidates)}extractText(e){let t=e.candidates?.[0];if(t?.content?.parts)return t.content.parts.map(n=>n.text).filter(Boolean).join("")}checkGeminiError(e){if(typeof e=="object"&&e!==null&&"error"in e){let t=e.error,n;if(typeof t=="string")n=t;else if(typeof t=="object"&&t!==null){let s=t;n=s.message||s.status||"Gemini returned an error"}else n="Gemini returned an error";throw new I(n)}if(this.isGeminiResponse(e)&&e.promptFeedback?.blockReason){let t=e.promptFeedback.blockReason;throw new I(`Prompt blocked: ${t}`)}}};var Le=class extends M{constructor(){super(...arguments),this.providerName="OpenRouter",this.defaultBaseUrl="https://openrouter.ai/api",this.path="/api/v1/chat/completions",this.effortMap={0:"low",1:"low",2:"medium",3:"high"}}buildHeaders(e,t){let n={Authorization:`Bearer ${e}`,"x-api-key":e,"Content-Type":"application/json",Accept:"application/json","X-Title":"Typebulb"};return t&&(n["HTTP-Referer"]=t,n.Referer=t,n.Origin=t),n}buildPayload(e,t,n,s){let o={model:t,messages:e,stream:s};return n?.webSearch===!0&&(o.plugins=[{id:"web"}]),this.isReasoningEnabled(n)&&(o.reasoning={effort:this.effortMap[n.reasoning]}),o}parseError(e,t){return this.parseJsonError(e,t,!0)}parseNonStreamingResponse(e){if(!this.hasChoices(e))return{text:""};let t=e.choices[0],n=t?.message?.content??t?.text??"",s=t?.message?.reasoning??e.reasoning;return{text:n,reasoning:s}}parseProviderStreamChunk(e){if(!this.hasChoices(e))return null;let t=e.choices[0];if(!t)return null;let n=t.delta||t.message;if(!n)return null;let s=n.content||void 0,o=n.reasoning||void 0;return!s&&!o?null:{text:s,reasoning:o}}hasChoices(e){return typeof e=="object"&&e!==null&&"choices"in e&&Array.isArray(e.choices)}};var To=new Map([["openai",new Ne],["openrouter",new Le],["anthropic",new Fe],["gemini",new Be]]);function se(r){let e=To.get(r);if(!e)throw new Error(`Unsupported protocol: ${r}`);return e}async function Gt(r,e){let t=se(r.protocol),n=t.getPath(e.model,e.stream),s=new URL(n,r.baseUrl).toString(),o=t.buildHeaders(r.apiKey,e.origin),i=t.buildPayload(e.messages,e.model,{reasoning:e.reasoning,webSearch:e.webSearch},e.stream);return e.modifyPayload?.(i),fetch(s,{method:"POST",headers:o,body:JSON.stringify(i),signal:e.signal})}async function Kt(r,e){let t=se(e),n=await r.text().catch(()=>""),{message:s}=t.parseError(n,r.status),o=r.status,i="unknown";return o===429?i="rate_limit":o===413&&(i="context_exceeded"),{code:i,message:s,retryable:o===429}}function An(r){let e=r.indexOf(`\r
658
+ `)[0],type:s.status,code:s.code?.toString()}:n.message?{message:n.message}:{message:e}}catch{return{message:e}}}parseNonStreamingResponse(e){if(this.checkGeminiError(e),!this.isGeminiResponse(e))return{text:"",status:"failed",error:"Invalid response format"};let t=this.extractText(e)||"",n=e.candidates?.[0]?.finishReason,s="complete";return n==="MAX_TOKENS"?s="interrupted":(n==="SAFETY"||n==="RECITATION")&&(s="failed"),{text:t,status:s}}parseProviderStreamChunk(e){if(this.checkGeminiError(e),!this.isGeminiResponse(e))return null;let t=this.extractText(e);return t?{text:t}:null}isGeminiResponse(e){return typeof e=="object"&&e!==null&&"candidates"in e&&Array.isArray(e.candidates)}extractText(e){let t=e.candidates?.[0];if(t?.content?.parts)return t.content.parts.map(n=>n.text).filter(Boolean).join("")}checkGeminiError(e){if(typeof e=="object"&&e!==null&&"error"in e){let t=e.error,n;if(typeof t=="string")n=t;else if(typeof t=="object"&&t!==null){let s=t;n=s.message||s.status||"Gemini returned an error"}else n="Gemini returned an error";throw new A(n)}if(this.isGeminiResponse(e)&&e.promptFeedback?.blockReason){let t=e.promptFeedback.blockReason;throw new A(`Prompt blocked: ${t}`)}}};var Ne=class extends M{constructor(){super(...arguments),this.providerName="OpenRouter",this.defaultBaseUrl="https://openrouter.ai/api",this.path="/api/v1/chat/completions",this.effortMap={0:"low",1:"low",2:"medium",3:"high"}}buildHeaders(e,t){let n={Authorization:`Bearer ${e}`,"x-api-key":e,"Content-Type":"application/json",Accept:"application/json","X-Title":"Typebulb"};return t&&(n["HTTP-Referer"]=t,n.Referer=t,n.Origin=t),n}buildPayload(e,t,n,s){let o={model:t,messages:e,stream:s};return n?.webSearch===!0&&(o.plugins=[{id:"web"}]),this.isReasoningEnabled(n)&&(o.reasoning={effort:this.effortMap[n.reasoning]}),o}parseError(e,t){return this.parseJsonError(e,t,!0)}parseNonStreamingResponse(e){if(!this.hasChoices(e))return{text:""};let t=e.choices[0],n=t?.message?.content??t?.text??"",s=t?.message?.reasoning??e.reasoning;return{text:n,reasoning:s}}parseProviderStreamChunk(e){if(!this.hasChoices(e))return null;let t=e.choices[0];if(!t)return null;let n=t.delta||t.message;if(!n)return null;let s=n.content||void 0,o=n.reasoning||void 0;return!s&&!o?null:{text:s,reasoning:o}}hasChoices(e){return typeof e=="object"&&e!==null&&"choices"in e&&Array.isArray(e.choices)}};var Ao=new Map([["openai",new Fe],["openrouter",new Ne],["anthropic",new Be],["gemini",new Le]]);function se(r){let e=Ao.get(r);if(!e)throw new Error(`Unsupported protocol: ${r}`);return e}async function Yt(r,e){let t=se(r.protocol),n=t.getPath(e.model,e.stream),s=new URL(n,r.baseUrl).toString(),o=t.buildHeaders(r.apiKey,e.origin),i=t.buildPayload(e.messages,e.model,{reasoning:e.reasoning,webSearch:e.webSearch},e.stream);return e.modifyPayload?.(i),fetch(s,{method:"POST",headers:o,body:JSON.stringify(i),signal:e.signal})}async function Xt(r,e){let t=se(e),n=await r.text().catch(()=>""),{message:s}=t.parseError(n,r.status),o=r.status,i="unknown";return o===429?i="rate_limit":o===413&&(i="context_exceeded"),{code:i,message:s,retryable:o===429}}function $n(r){let e=r.indexOf(`\r
657
659
  \r
658
660
  `),t=r.indexOf(`
659
661
 
660
- `);return e!==-1&&(t===-1||e<t)?{pos:e,len:4}:t!==-1?{pos:t,len:2}:{pos:-1,len:0}}function Yt(r){let t=r.split(/\r?\n/).filter(s=>s.startsWith("data:"));if(!t.length)return null;let n=t.map(s=>s.replace(/^data:\s?/,"")).join(`
661
- `).trim();if(!n)return null;if(n==="[DONE]")return"done";try{return JSON.parse(n)}catch{return null}}async function In(r,e,t){let n=new TextDecoder,s="",o=!1,i=t?new Promise((a,c)=>{t.aborted&&c(new Error("Aborted")),t.addEventListener("abort",()=>c(new Error("Aborted")),{once:!0})}):null;for(;;){let a=i?await Promise.race([r.read(),i]):await r.read(),{done:c,value:l}=a;if(c){if(s.trim()){let m=Yt(s);m!==null&&m!=="done"&&e(m)}break}o=!0,s+=n.decode(l,{stream:!0});let{pos:p,len:d}=An(s);for(;p!==-1;){let m=s.slice(0,p);s=s.slice(p+d);let h=Yt(m);if(h==="done"){s="";break}h!==null&&e(h),{pos:p,len:d}=An(s)}}return{receivedAnyData:o}}async function Xt(r,e){let t=e??(r.headers.get("X-Provider-Protocol")||"openai"),n=se(t);if(!r.body)throw new Error("Response body is missing");let s=r.body.getReader(),o="";return await In(s,i=>{let a=n.parseStreamChunk(i);a?.text&&(o+=a.text)}),o}import*as Qt from"fs/promises";import*as Ue from"path";var bt=class{async get(e){let t=O(e),n=Ue.join(De,t+".bin"),s=Ue.join(De,t+".json");try{let[o,i]=await Promise.all([Qt.readFile(n),Qt.readFile(s,"utf8")]),a=JSON.parse(i);return{body:o,contentType:a.contentType,cacheControl:a.cacheControl}}catch{return}}async set(e,t){await x();let n=O(e),s=Ue.join(De,n+".bin"),o=Ue.join(De,n+".json"),i={url:e,contentType:t.contentType,cacheControl:t.cacheControl};await Promise.all([C(s,t.body),C(o,JSON.stringify(i))])}};var $n="127.0.0.1",Io=new Set(["localhost","127.0.0.1","::1"]);function Oo(r){if(r)try{return new URL(r.includes("://")?r:`http://${r}`).hostname}catch{return}}function On(r){let e=Oo(r);return!!e&&Io.has(e)}function yt(r){return r instanceof Error?r.message:"Unknown error"}async function Dn(r){let{getHtml:e,basePath:t,port:n,reloadEmitter:s,getServerExports:o,localOverride:i,trusted:a=!1,trustHint:c}=r,l=new _o;l.use("*",async(u,f)=>{if(!On(u.req.header("host")))return u.text("Forbidden: untrusted Host",403);await f()}),l.use("*",async(u,f)=>{await f(),u.res.headers.set("Cross-Origin-Opener-Policy","same-origin"),u.res.headers.set("Cross-Origin-Embedder-Policy","credentialless")});let p=["/__fs/*","/__api/*","/__ai"],d=async(u,f)=>{if(!a){let b=new URL(u.req.url).pathname,w=b.startsWith("/__fs")?"the filesystem":b==="/__ai"?"AI (your API keys)":"server-side code (server.ts)";mn(process.pid,w);let v=c?`
662
- ${c}`:"";return u.text(`Forbidden: this capability requires --trust.${v}`,403)}await f()},m=async(u,f)=>{let b=u.req.header("sec-fetch-site");if(b){if(b==="cross-site")return u.text("Forbidden: cross-site request",403)}else{let w=u.req.header("origin");if(w&&!On(w))return u.text("Forbidden: cross-origin request",403)}await f()};for(let u of p)l.use(u,d),l.use(u,m);l.use("/__log",m),l.post("/__log",async u=>{try{let{args:f}=await u.req.json();console.log(...f||[])}catch{}return u.json({ok:!0})}),l.get("/",u=>u.html(e())),l.post("/__fs/read",async u=>{try{let{path:f}=await u.req.json(),b=er(f,t),w=await oe.readFile(b);return new Response(new Uint8Array(w),{headers:{"Content-Type":"application/octet-stream"}})}catch(f){let b=yt(f);return u.json({error:b},400)}}),l.post("/__fs/write",async u=>{try{let f=u.req.query("path");if(!f)return u.json({error:"Missing path"},400);let b=er(f,t);return await oe.mkdir(j.dirname(b),{recursive:!0}),await oe.writeFile(b,Buffer.from(await u.req.arrayBuffer())),u.json({success:!0})}catch(f){let b=yt(f);return u.json({error:b},400)}});let h={log:console.log};l.post("/__api/:name",async u=>{try{let f=o?.(),b=u.req.param("name"),w=f?.[b]??h[b];if(!w||typeof w!="function")return u.json({error:`API function '${b}' not found`},404);let{args:v}=await u.req.json(),T=await w(...v||[]);return u.json({result:T})}catch(f){let b=yt(f);return u.json({error:b},500)}}),l.post("/__ai",async u=>{try{let{messages:f,system:b,reasoning:w,provider:v,model:T,webSearch:z}=await u.req.json();if(!f||!Array.isArray(f)||f.length===0)return u.json({message:"messages array is required",code:"unknown",retryable:!1},400);let N=$o(v,T);if(typeof N=="string")return u.json({message:N,code:"unknown",retryable:!1},400);let wt=[...b?[{role:"system",content:b}]:[],...f.map(We=>({role:We.role,content:We.content}))],ie=await Gt(N,{model:N.model,messages:wt,stream:!0,reasoning:w??0,webSearch:z??!0});if(!ie.ok){let We=await Kt(ie,N.protocol);return u.json(We,ie.status)}let rr=await Xt(ie,N.protocol);return rr||console.warn("[tb.ai] Empty response from provider"),u.json({text:rr})}catch(f){if(f instanceof I)return u.json({message:f.message,code:f.code,retryable:f.retryable},500);let b=yt(f);return u.json({message:b,code:"unknown",retryable:!1},500)}}),l.get("/__models",async u=>{try{let f=await ht();return u.json(f)}catch{return u.json([],200)}});let g=["esm.sh","unpkg.com","cdn.jsdelivr.net","cdnjs.cloudflare.com"],S=new bt;if(l.get("/proxy/*",async u=>{let f=new URL(u.req.url),w=(f.pathname+f.search).slice(7),v=w.lastIndexOf("https://");return v===-1?u.text("Invalid proxy URL",400):F(u,w.slice(v))}),i){let u=`/local/${i.name}/`;l.get("/local/*",async f=>{let{pathname:b}=new URL(f.req.url);if(!b.startsWith(u))return f.text("Not Found",404);let w=decodeURIComponent(b.slice(u.length));try{let v=er(w,i.serveDir),T=await oe.readFile(v);return new Response(T,{headers:{"Content-Type":Do(v)}})}catch{return f.text("Not Found",404)}})}async function F(u,f){let b;try{b=new URL(f)}catch{return u.text("Invalid URL",400)}if(b.protocol!=="https:")return u.text("HTTPS only",400);if(!g.includes(b.hostname))return u.text("Host not allowed",403);let w=await S.get(f);if(w)return new Response(w.body,{status:200,headers:Zt(w.contentType,w.cacheControl)});try{let v=await fetch(f,{headers:{Accept:u.req.header("Accept")||"*/*"},redirect:"follow"});if(!v.ok)return u.text(`Upstream ${v.status}`,v.status);let T=v.headers.get("Content-Type")||void 0,z=v.headers.get("Cache-Control")||void 0;if(v.body){let[N,wt]=v.body.tee();return(async()=>{try{let ie=await new Response(wt).arrayBuffer();await S.set(f,{body:Buffer.from(ie),contentType:T,cacheControl:z})}catch{}})(),new Response(N,{status:v.status,headers:Zt(T,z)})}return new Response(null,{status:v.status,headers:Zt(T,z)})}catch(v){return u.text(`Proxy fetch failed: ${v instanceof Error?v.message:v}`,502)}}s&&l.get("/__reload",u=>Ao(u,async f=>{let b=()=>{f.writeSSE({event:"reload",data:""})};for(s.on("reload",b),f.onAbort(()=>{s.removeListener("reload",b)});;)await f.sleep(3e4)}));let L=/^\/(v\d+\/|stable\/|node\/|gh\/|@[^/]+\/[^@/]+@|[^@/]+@)/;l.notFound(async u=>{if(u.req.method!=="GET")return u.text("Not Found",404);let f=new URL(u.req.url);return L.test(f.pathname)?F(u,"https://esm.sh"+f.pathname+f.search):u.text("Not Found",404)});let _=Co({fetch:l.fetch,port:n,hostname:$n});return{port:n,close:()=>_.close()}}function $o(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=se(t)}catch{return`Unknown provider '${t}'.`}let o=ye[t],i=process.env[o];return i?{apiKey:i,baseUrl:s.defaultBaseUrl,protocol:t,model:n,isFreeModel:!1}:`No API key for '${t}'. Set ${o} in your .env file.`}function Zt(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 Do(r){switch(j.extname(r).toLowerCase()){case".js":case".mjs":return"text/javascript";case".wasm":return"application/wasm";case".json":case".map":return"application/json";default:return"application/octet-stream"}}function er(r,e){let t=j.resolve(e,r),n=j.normalize(e),s=j.normalize(t);if(s!==n&&!s.startsWith(n+j.sep))throw new Error("Path traversal detected - access denied");return t}async function tr(r){let e=await import("net");return new Promise(t=>{let n=e.createServer();n.listen(r,$n,()=>{let s=n.address(),o=typeof s=="object"&&s?s.port:r;n.close(()=>t(o))}),n.on("error",()=>{t(tr(r+1))})})}import Mn from"chokidar";var jn={persistent:!0,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50}};function vt(r){let{bulbPath:e,emitter:t}=r,n=Mn.watch(e,jn);return n.on("change",()=>{t.emit("reload")}),()=>n.close()}function Fn(r){let{dir:e,onChange:t,debounceMs:n=150}=r,s,o=Mn.watch(e,jn);return o.on("all",()=>{s&&clearTimeout(s),s=setTimeout(t,n)}),()=>{s&&clearTimeout(s),o.close()}}async function Ln(r,e,t,n,s){let o=process.cwd(),i=pn(process.pid),a=e.watch?new Nn:void 0,c=ge(e.mode);console.log(`Loading ${ve.basename(r)}...`);let{html:l,bulb:p,serverExports:d}=await Bt(r,e.watch,e.trust,n,s);mt(c,r,p.server);let m=await tr(e.port),h=await Dn({getHtml:()=>l,basePath:o,port:m,reloadEmitter:a,getServerExports:()=>d,localOverride:n?{name:n.name,serveDir:n.serveDir}:void 0,trusted:e.trust,trustHint:t}),g=`http://localhost:${m}`,S=e.trust?void 0:pt(p);await fn({pid:process.pid,port:m,url:g,file:r,cwd:process.cwd(),startedAt:Date.now(),trust:e.trust,predicted:S}),console.log(`
662
+ `);return e!==-1&&(t===-1||e<t)?{pos:e,len:4}:t!==-1?{pos:t,len:2}:{pos:-1,len:0}}function Qt(r){let t=r.split(/\r?\n/).filter(s=>s.startsWith("data:"));if(!t.length)return null;let n=t.map(s=>s.replace(/^data:\s?/,"")).join(`
663
+ `).trim();if(!n)return null;if(n==="[DONE]")return"done";try{return JSON.parse(n)}catch{return null}}async function Dn(r,e,t){let n=new TextDecoder,s="",o=!1,i=t?new Promise((a,c)=>{t.aborted&&c(new Error("Aborted")),t.addEventListener("abort",()=>c(new Error("Aborted")),{once:!0})}):null;for(;;){let a=i?await Promise.race([r.read(),i]):await r.read(),{done:c,value:l}=a;if(c){if(s.trim()){let m=Qt(s);m!==null&&m!=="done"&&e(m)}break}o=!0,s+=n.decode(l,{stream:!0});let{pos:p,len:d}=$n(s);for(;p!==-1;){let m=s.slice(0,p);s=s.slice(p+d);let h=Qt(m);if(h==="done"){s="";break}h!==null&&e(h),{pos:p,len:d}=$n(s)}}return{receivedAnyData:o}}async function Zt(r,e){let t=e??(r.headers.get("X-Provider-Protocol")||"openai"),n=se(t);if(!r.body)throw new Error("Response body is missing");let s=r.body.getReader(),o="";return await Dn(s,i=>{let a=n.parseStreamChunk(i);a?.text&&(o+=a.text)}),o}import*as er from"fs/promises";import*as Ue from"path";var yt=class{async get(e){let t=I(e),n=Ue.join(De,t+".bin"),s=Ue.join(De,t+".json");try{let[o,i]=await Promise.all([er.readFile(n),er.readFile(s,"utf8")]),a=JSON.parse(i);return{body:o,contentType:a.contentType,cacheControl:a.cacheControl}}catch{return}}async set(e,t){await x();let n=I(e),s=Ue.join(De,n+".bin"),o=Ue.join(De,n+".json"),i={url:e,contentType:t.contentType,cacheControl:t.cacheControl};await Promise.all([C(s,t.body),C(o,JSON.stringify(i))])}};var jn="127.0.0.1",Mo=new Set(["localhost","127.0.0.1","::1"]);function jo(r){if(r)try{return new URL(r.includes("://")?r:`http://${r}`).hostname}catch{return}}function Mn(r){let e=jo(r);return!!e&&Mo.has(e)}function vt(r){return r instanceof Error?r.message:"Unknown error"}async function Bn(r){let{getHtml:e,basePath:t,port:n,reloadEmitter:s,getServerExports:o,localOverride:i,trusted:a=!1,trustHint:c}=r,l=new Io;l.use("*",async(u,f)=>{if(!Mn(u.req.header("host")))return u.text("Forbidden: untrusted Host",403);await f()}),l.use("*",async(u,f)=>{await f(),u.res.headers.set("Cross-Origin-Opener-Policy","same-origin"),u.res.headers.set("Cross-Origin-Embedder-Policy","credentialless")});let p=["/__fs/*","/__api/*","/__ai"],d=async(u,f)=>{if(!a){let b=new URL(u.req.url).pathname,w=b.startsWith("/__fs")?"the filesystem":b==="/__ai"?"AI (your API keys)":"server-side code (server.ts)";bn(process.pid,w);let v=c?`
664
+ ${c}`:"";return u.text(`Forbidden: this capability requires --trust.${v}`,403)}await f()},m=async(u,f)=>{let b=u.req.header("sec-fetch-site");if(b){if(b==="cross-site")return u.text("Forbidden: cross-site request",403)}else{let w=u.req.header("origin");if(w&&!Mn(w))return u.text("Forbidden: cross-origin request",403)}await f()};for(let u of p)l.use(u,d),l.use(u,m);l.use("/__log",m),l.post("/__log",async u=>{try{let{args:f}=await u.req.json();console.log(...f||[])}catch{}return u.json({ok:!0})}),l.get("/",u=>u.html(e())),l.post("/__fs/read",async u=>{try{let{path:f}=await u.req.json(),b=rr(f,t),w=await oe.readFile(b);return new Response(new Uint8Array(w),{headers:{"Content-Type":"application/octet-stream"}})}catch(f){let b=vt(f);return u.json({error:b},400)}}),l.post("/__fs/write",async u=>{try{let f=u.req.query("path");if(!f)return u.json({error:"Missing path"},400);let b=rr(f,t);return await oe.mkdir(j.dirname(b),{recursive:!0}),await oe.writeFile(b,Buffer.from(await u.req.arrayBuffer())),u.json({success:!0})}catch(f){let b=vt(f);return u.json({error:b},400)}});let h={log:console.log};l.post("/__api/:name",async u=>{try{let f=o?.(),b=u.req.param("name"),w=f?.[b]??h[b];if(!w||typeof w!="function")return u.json({error:`API function '${b}' not found`},404);let{args:v}=await u.req.json(),T=await w(...v||[]);return u.json({result:T})}catch(f){let b=vt(f);return u.json({error:b},500)}}),l.post("/__ai",async u=>{try{let{messages:f,system:b,reasoning:w,provider:v,model:T,webSearch:z}=await u.req.json();if(!f||!Array.isArray(f)||f.length===0)return u.json({message:"messages array is required",code:"unknown",retryable:!1},400);let F=Bo(v,T);if(typeof F=="string")return u.json({message:F,code:"unknown",retryable:!1},400);let xt=[...b?[{role:"system",content:b}]:[],...f.map(We=>({role:We.role,content:We.content}))],ie=await Yt(F,{model:F.model,messages:xt,stream:!0,reasoning:w??0,webSearch:z??!0});if(!ie.ok){let We=await Xt(ie,F.protocol);return u.json(We,ie.status)}let sr=await Zt(ie,F.protocol);return sr||console.warn("[tb.ai] Empty response from provider"),u.json({text:sr})}catch(f){if(f instanceof A)return u.json({message:f.message,code:f.code,retryable:f.retryable},500);let b=vt(f);return u.json({message:b,code:"unknown",retryable:!1},500)}}),l.get("/__models",async u=>{try{let f=await gt();return u.json(f)}catch{return u.json([],200)}});let g=["esm.sh","unpkg.com","cdn.jsdelivr.net","cdnjs.cloudflare.com"],S=new yt;if(l.get("/proxy/*",async u=>{let f=new URL(u.req.url),w=(f.pathname+f.search).slice(7),v=w.lastIndexOf("https://");return v===-1?u.text("Invalid proxy URL",400):B(u,w.slice(v))}),i){let u=`/local/${i.name}/`;l.get("/local/*",async f=>{let{pathname:b}=new URL(f.req.url);if(!b.startsWith(u))return f.text("Not Found",404);let w=decodeURIComponent(b.slice(u.length));try{let v=rr(w,i.serveDir),T=await oe.readFile(v);return new Response(T,{headers:{"Content-Type":Fo(v)}})}catch{return f.text("Not Found",404)}})}async function B(u,f){let b;try{b=new URL(f)}catch{return u.text("Invalid URL",400)}if(b.protocol!=="https:")return u.text("HTTPS only",400);if(!g.includes(b.hostname))return u.text("Host not allowed",403);let w=await S.get(f);if(w)return new Response(w.body,{status:200,headers:tr(w.contentType,w.cacheControl)});try{let v=await fetch(f,{headers:{Accept:u.req.header("Accept")||"*/*"},redirect:"follow"});if(!v.ok)return u.text(`Upstream ${v.status}`,v.status);let T=v.headers.get("Content-Type")||void 0,z=v.headers.get("Cache-Control")||void 0;if(v.body){let[F,xt]=v.body.tee();return(async()=>{try{let ie=await new Response(xt).arrayBuffer();await S.set(f,{body:Buffer.from(ie),contentType:T,cacheControl:z})}catch{}})(),new Response(F,{status:v.status,headers:tr(T,z)})}return new Response(null,{status:v.status,headers:tr(T,z)})}catch(v){return u.text(`Proxy fetch failed: ${v instanceof Error?v.message:v}`,502)}}s&&l.get("/__reload",u=>Do(u,async f=>{let b=()=>{f.writeSSE({event:"reload",data:""})};for(s.on("reload",b),f.onAbort(()=>{s.removeListener("reload",b)});;)await f.sleep(3e4)}));let N=/^\/(v\d+\/|stable\/|node\/|gh\/|@[^/]+\/[^@/]+@|[^@/]+@)/;l.notFound(async u=>{if(u.req.method!=="GET")return u.text("Not Found",404);let f=new URL(u.req.url);return N.test(f.pathname)?B(u,"https://esm.sh"+f.pathname+f.search):u.text("Not Found",404)});let _=$o({fetch:l.fetch,port:n,hostname:jn});return{port:n,close:()=>_.close()}}function Bo(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=se(t)}catch{return`Unknown provider '${t}'.`}let o=ye[t],i=process.env[o];return i?{apiKey:i,baseUrl:s.defaultBaseUrl,protocol:t,model:n,isFreeModel:!1}:`No API key for '${t}'. Set ${o} in your .env file.`}function tr(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 Fo(r){switch(j.extname(r).toLowerCase()){case".js":case".mjs":return"text/javascript";case".wasm":return"application/wasm";case".json":case".map":return"application/json";default:return"application/octet-stream"}}function rr(r,e){let t=j.resolve(e,r),n=j.normalize(e),s=j.normalize(t);if(s!==n&&!s.startsWith(n+j.sep))throw new Error("Path traversal detected - access denied");return t}async function nr(r){let e=await import("net");return new Promise(t=>{let n=e.createServer();n.listen(r,jn,()=>{let s=n.address(),o=typeof s=="object"&&s?s.port:r;n.close(()=>t(o))}),n.on("error",()=>{t(nr(r+1))})})}import Fn from"chokidar";var Ln={persistent:!0,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50}};function wt(r){let{bulbPath:e,emitter:t}=r,n=Fn.watch(e,Ln);return n.on("change",()=>{t.emit("reload")}),()=>n.close()}function Nn(r){let{dir:e,onChange:t,debounceMs:n=150}=r,s,o=Fn.watch(e,Ln);return o.on("all",()=>{s&&clearTimeout(s),s=setTimeout(t,n)}),()=>{s&&clearTimeout(s),o.close()}}async function Jn(r,e,t,n,s){let o=process.cwd(),i=hn(process.pid),a=e.watch?new Un:void 0,c=ge(e.mode);console.log(`Loading ${ve.basename(r)}...`);let{html:l,bulb:p,serverExports:d}=await Ut(r,e.watch,e.trust,n,s);ht(c,r,p.server);let m=await nr(e.port),h=await Bn({getHtml:()=>l,basePath:o,port:m,reloadEmitter:a,getServerExports:()=>d,localOverride:n?{name:n.name,serveDir:n.serveDir}:void 0,trusted:e.trust,trustHint:t}),g=`http://localhost:${m}`,S=e.trust?void 0:ft(p);await gn({pid:process.pid,port:m,url:g,file:r,cwd:process.cwd(),startedAt:Date.now(),trust:e.trust,predicted:S}),console.log(`
663
665
  ${p.name}`),console.log(` ${g}`),m!==e.port&&console.log(` (port ${e.port} was busy)`),e.trust?console.log(" trust: granted (filesystem, AI, server.ts enabled)"):console.log(S?` trust: sandboxed \u2014 this bulb appears to use ${S}; re-run with --trust to enable it:
664
666
  ${t}
665
667
  `:` trust: sandboxed \u2014 re-run with --trust to enable filesystem / AI / server.ts
666
668
  `),e.watch&&console.log(` Watching for changes...
667
- `);let F,L;if(e.watch&&a){let u=new Nn;if(u.on("reload",async()=>{try{console.log("Recompiling...");let f=await Bt(r,!0,e.trust,n,s);l=f.html,d=f.serverExports,a.emit("reload"),console.log(`Done. Browser reloading...
668
- `)}catch(f){console.error("Compile error:",f)}}),F=vt({bulbPath:r,emitter:u}),n){let{name:f,serveDir:b}=n;L=Fn({dir:b,onChange:()=>{console.log(`Local package '${f}' changed. Browser reloading...
669
- `),a.emit("reload")}})}}e.open&&await it(g);let _=async()=>{console.log(`
670
- Shutting down...`),h.close(),F?.(),L?.(),i(),await qt(process.pid);let u=ve.join(ve.dirname(r),".typebulb","server.mjs");await Bn.rm(u,{force:!0}).catch(()=>{}),process.exit(0)};process.on("SIGINT",_),process.on("SIGTERM",_)}import*as Un from"path";import{EventEmitter as Mo}from"events";async function Wn(r,e,t,n,s){let o=ge(t),i=!1,a=async()=>{let{bulb:c,config:l}=await W(r);i||(mt(o,r,c.server),i=!0),await Nt(c.server,s,n,l.dependencies)};if(console.log(`Running ${Un.basename(r)}...`),await a(),e){console.log(`Watching for changes...
671
- `);let c=new Mo;c.on("reload",async()=>{try{console.log("Re-running..."),await a()}catch(l){console.error("Error:",l)}}),vt({bulbPath:r,emitter:c})}}var Jn="0.10.4";async function jo(){let r=ur(process.argv.slice(2));if(r.version&&(console.log(`typebulb ${Jn}`),process.exit(0)),r.help&&(pr(),process.exit(0)),r.subcommand==="logs"){await _n(r.file||void 0,{follow:r.follow,lines:r.lines});return}if(r.subcommand==="stop"){await Cn(r.file||void 0);return}if(r.subcommand==="skill"){await Pn(Jn);return}if(r.subcommand==="models"){await wn(r.mode);return}if(r.subcommand==="agent"){if(!r.agentTarget){await gn();return}me(r.agentTarget)||(console.error(`Unknown agent '${r.agentTarget}'. Known: ${Wt().join(", ")}.`),process.exit(1));let l=await zt(process.cwd(),r.agentTarget);if(l){console.log(`Viewer '${r.agentTarget}' is already running for this project:
672
- ${l.url}`),r.open&&await it(l.url);return}r.file=r.agentTarget,r.subcommand="run"}if(r.subcommand==="trust"||r.subcommand==="untrust"){await on(r.file||void 0,r.subcommand==="trust");return}let e,t=!1;if(!r.file||r.file==="."){let l=await Hr(process.cwd());l||(console.error("No .bulb.md file found in current directory"),process.exit(1)),e=l}else e=q.resolve(r.file);if(!await Vn.access(e).then(()=>!0,()=>!1)){let l=r.agentTarget?me(r.file):void 0;l?(e=l,t=!0):Wt().includes(r.file)?(console.error(`To open the ${r.file} agent viewer, run: npx typebulb agent:${r.file}`),process.exit(1)):(console.error(`File not found: ${e}`),process.exit(1))}e.endsWith(".bulb.md")||(console.error("File must have .bulb.md extension"),process.exit(1));let s=r.file&&r.file!=="."?r.file:q.relative(process.cwd(),e)||q.basename(e),o=`npx typebulb --trust ${s.includes(" ")?`"${s}"`:s}`;if(r.subcommand==="predict"){await sn(e,o);return}if(t)r.trust=!r.noTrust,r.trust&&console.log("trust: granted (built-in bulb)");else{let l=!r.noTrust&&ot(e);l&&!r.trust&&console.log("trust: granted from memory (run `typebulb untrust` to revoke)"),r.trust=r.noTrust?!1:r.trust||l}let i;try{i=await W(e)}catch{}let a;if(r.local){i&&!(r.local.name in(i.config.dependencies??{}))&&(console.error(`--replace: '${r.local.name}' is not a dependency in this bulb's config.json; nothing to replace.`),process.exit(1)),i&&(!i.bulb.code||r.server)&&console.warn("warning: --replace has no effect in server mode (the override is client-only).");try{a=await lr(r.local)}catch(l){console.error(l instanceof Error?l.message:String(l)),process.exit(1)}console.log(`replace: ${a.name} \u2192 ${q.relative(process.cwd(),a.dir)||"."}`)}if(r.subcommand==="check"){await nn(e,a);return}let c=t?process.cwd():q.dirname(e);if(i&&i.bulb.server&&(!i.bulb.code||r.server)){r.trust||(console.error(`This bulb runs server-side Node code (server.ts), which --trust must authorize:
673
- ${o}`),process.exit(1)),await Wn(e,r.watch,r.mode,a,c);return}await Ln(e,r,o,a,c)}jo().catch(r=>{console.error("Error:",r.message),process.exit(1)});
669
+ `);let B,N;if(e.watch&&a){let u=new Un;if(u.on("reload",async()=>{try{console.log("Recompiling...");let f=await Ut(r,!0,e.trust,n,s);l=f.html,d=f.serverExports,a.emit("reload"),console.log(`Done. Browser reloading...
670
+ `)}catch(f){console.error("Compile error:",f)}}),B=wt({bulbPath:r,emitter:u}),n){let{name:f,serveDir:b}=n;N=Nn({dir:b,onChange:()=>{console.log(`Local package '${f}' changed. Browser reloading...
671
+ `),a.emit("reload")}})}}e.open&&await at(g);let _=async()=>{console.log(`
672
+ Shutting down...`),h.close(),B?.(),N?.(),i(),await Gt(process.pid);let u=ve.join(ve.dirname(r),".typebulb","server.mjs");await Wn.rm(u,{force:!0}).catch(()=>{}),process.exit(0)};process.on("SIGINT",_),process.on("SIGTERM",_)}import*as Vn from"path";import{EventEmitter as Lo}from"events";async function Hn(r,e,t,n,s){let o=ge(t),i=!1,a=async()=>{let{bulb:c,config:l}=await W(r);i||(ht(o,r,c.server),i=!0),await Nt(c.server,s,n,l.dependencies)};if(console.log(`Running ${Vn.basename(r)}...`),await a(),e){console.log(`Watching for changes...
673
+ `);let c=new Lo;c.on("reload",async()=>{try{console.log("Re-running..."),await a()}catch(l){console.error("Error:",l)}}),wt({bulbPath:r,emitter:c})}}var qn="0.10.6";async function No(){let r=pr(process.argv.slice(2));if(r.version&&(console.log(`typebulb ${qn}`),process.exit(0)),r.help&&(fr(),process.exit(0)),r.subcommand==="logs"){await An(r.file||void 0,{follow:r.follow,lines:r.lines});return}if(r.subcommand==="stop"){await In(r.file||void 0);return}if(r.subcommand==="skill"){await kn(qn);return}if(r.subcommand==="models"){await Pn(r.mode);return}if(r.subcommand==="check"&&r.file==="-"){await on(r.local);return}if(r.subcommand==="agent"){if(!r.agentTarget){await vn();return}me(r.agentTarget)||(console.error(`Unknown agent '${r.agentTarget}'. Known: ${Vt().join(", ")}.`),process.exit(1));let l=await Kt(process.cwd(),r.agentTarget);if(l){console.log(`Viewer '${r.agentTarget}' is already running for this project:
674
+ ${l.url}`),r.open&&await at(l.url);return}r.file=r.agentTarget,r.subcommand="run"}if(r.subcommand==="trust"||r.subcommand==="untrust"){await ln(r.file||void 0,r.subcommand==="trust");return}let e,t=!1;if(!r.file||r.file==="."){let l=await qr(process.cwd());l||(console.error("No .bulb.md file found in current directory"),process.exit(1)),e=l}else e=q.resolve(r.file);if(!await zn.access(e).then(()=>!0,()=>!1)){let l=r.agentTarget?me(r.file):void 0;l?(e=l,t=!0):Vt().includes(r.file)?(console.error(`To open the ${r.file} agent viewer, run: npx typebulb agent:${r.file}`),process.exit(1)):(console.error(`File not found: ${e}`),process.exit(1))}e.endsWith(".bulb.md")||(console.error("File must have .bulb.md extension"),process.exit(1));let s=r.file&&r.file!=="."?r.file:q.relative(process.cwd(),e)||q.basename(e),o=`npx typebulb --trust ${s.includes(" ")?`"${s}"`:s}`;if(r.subcommand==="predict"){await cn(e,o);return}if(t)r.trust=!r.noTrust,r.trust&&console.log("trust: granted (built-in bulb)");else{let l=!r.noTrust&&it(e);l&&!r.trust&&console.log("trust: granted from memory (run `typebulb untrust` to revoke)"),r.trust=r.noTrust?!1:r.trust||l}let i;try{i=await W(e)}catch{}let a;if(r.local){i&&!(r.local.name in(i.config.dependencies??{}))&&(console.error(`--replace: '${r.local.name}' is not a dependency in this bulb's config.json; nothing to replace.`),process.exit(1)),i&&(!i.bulb.code||r.server)&&console.warn("warning: --replace has no effect in server mode (the override is client-only).");try{a=await Je(r.local)}catch(l){console.error(l instanceof Error?l.message:String(l)),process.exit(1)}console.log(`replace: ${a.name} \u2192 ${q.relative(process.cwd(),a.dir)||"."}`)}if(r.subcommand==="check"){await sn(e,a);return}let c=t?process.cwd():q.dirname(e);if(i&&i.bulb.server&&(!i.bulb.code||r.server)){r.trust||(console.error(`This bulb runs server-side Node code (server.ts), which --trust must authorize:
675
+ ${o}`),process.exit(1)),await Hn(e,r.watch,r.mode,a,c);return}await Jn(e,r,o,a,c)}No().catch(r=>{console.error("Error:",r.message),process.exit(1)});
package/dist/render.js CHANGED
@@ -495,6 +495,6 @@ ${A(s)}
495
495
  }
496
496
  });
497
497
  })();
498
- <\/script>`;function _m(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function bm(e){let t={};for(let[s,n]of Object.entries(e))t[s]=n.startsWith("https://")?"/proxy/"+n:n;return t}var Ir="https://esm.sh",xr="https://cdn.jsdelivr.net/npm/",si="https://data.jsdelivr.com/v1/package/npm/";function ac(e){let t=(e||"").replace(/^\/+/,"").replace(/\/+$/,"");return t?t.split("/"):[]}var oe=class e{constructor(t,s,n){let i=typeof t=="string"?e.parse(t):t;this.name=i.name,this.version=Nt(s??i.version),this.subpath=Nt(n??i.subpath)}static parse(t){let s=ac(t||"");if(!s.length)return new e({name:""});if(s[0].startsWith("@")){let i=s[0],[a,c]=cc(s[1]??""),p=Nt(s.slice(2).join("/"));return new e({name:`${i}/${a}`,version:c,subpath:p})}else{let[i,a]=cc(s[0]),c=Nt(s.slice(1).join("/"));return new e({name:i,version:a,subpath:c})}}static fromUrl(t){try{let s=new URL(t),n=new URL(Ir).host,i=new URL(xr).host;if(s.host===n){let a=ac(s.pathname.replace(/^\/v\d+\//,"/"));if(!a.length)return;let c=a[0].startsWith("@")?`${a[0]}/${a[1]??""}`:a[0];return e.parse(c)}if(s.host===i){let a=s.pathname.split("/npm/")[1];if(!a)return;let c=a.split("/")[0]||"";return e.parse(c)}return}catch{return}}static versionFromUrl(t){return e.fromUrl(t)?.version}format(){let t=this.version?`${this.name}@${this.version}`:this.name;return this.subpath?`${t}/${this.subpath}`:t}root(){return this.name}static rootOf(t){return e.parse(t).name}withVersion(t){return new e({name:this.name,version:Nt(t),subpath:this.subpath})}withPreferredVersion(t,s){let n=t||s;return n?this.withVersion(n):this}static isBare(t){if(!t||t.startsWith(".")||t.startsWith("/"))return!1;let s=t.toLowerCase();return!s.startsWith("http://")&&!s.startsWith("https://")}},Nt=e=>e&&e.length?e:void 0,cc=e=>{let t=e.indexOf("@");return t<0?[e,void 0]:[e.slice(0,t),Nt(e.slice(t+1))]};async function Ce(e){try{return await e()}catch{return}}var wr=class{constructor(t,s){this.cache=t,this.http=s,this.esmHost=Ir,this.jsDelivrBase=xr,this.jsDelivrMeta=si,this.pinMs=1e4,this.versionsIndexMs=1440*60*1e3,this.metaTtlMs=10080*60*1e3,this.pinCache=new Map}normalizeRelative(t){let s=t||"";return s.startsWith("./")?s.slice(2):s.replace(/^\/+/,"")}ensureLeadingDotSlash(t){return t.startsWith("./")?t:`./${t}`}baseDir(t){let s=typeof t=="string"?new oe(t):t;return`${this.jsDelivrBase}${s.name}${s.version?`@${s.version}`:""}/`}file(t,s){return new URL(this.normalizeRelative(s),this.baseDir(t)).toString()}packageJson(t){return this.file(t,"package.json")}buildEsmUrl(t,s={}){let{target:n="es2022",bundle:i=!1,external:a}=s,c=new URLSearchParams({target:n});return i&&c.append("bundle",""),a?.length&&c.append("external",a.join(",")),`${this.esmHost}/${t}?${c.toString()}`}async pinEsmUrl(t,s="es2022"){let n=this.buildEsmUrl(t,{target:s}),i=await Ce(()=>this.http.head(n));return i?.ok?i.url||n:void 0}async resolveExactVersion(t){let s=Date.now(),n=this.pinCache.get(t);if(n&&s-n.ts<this.pinMs)return n.value;let i=await this.tryResolveFromUrls([this.buildEsmUrl(t),`${this.esmHost}/${t}`]);return this.pinCache.set(t,{value:i,ts:s}),i}async tryResolveFromUrls(t){for(let s of t){let n=await Ce(()=>this.http.head(s)),i=this.parseVersionFromUrl(n?.url||s);if(i)return i}}async fetchVersionsIndex(t){if(await this.cache.isNegative(t))return;let s=await this.cache.getIndex(t);if(s&&Date.now()-s.updatedAt<this.versionsIndexMs)return{versions:s.versions,distTags:s.distTags};let n=await Ce(()=>this.http.getJson(`${this.jsDelivrMeta}${encodeURIComponent(t)}`));if(!n?.versions?.length){await this.cache.recordNegative(t);return}await this.cache.clearNegative(t);let i=n.distTags&&Object.keys(n.distTags).length?n.distTags:void 0;return await this.cache.setIndex(t,n.versions,i),n}parseVersionFromUrl(t){let s=oe.fromUrl(t)?.version;return s&&/\d+\.\d+\.\d+/.test(s)?s:void 0}async fetchPackageMeta(t,s){let n=await this.cache.getMeta(t,s);if(n&&Date.now()-n.updatedAt<this.metaTtlMs){let{dependencies:E,peerDependencies:A,peerDependenciesMeta:x}=n;return{name:t,version:s,dependencies:E,peerDependencies:A,peerDependenciesMeta:x}}let i=this.packageJson(new oe(`${t}@${s}`)),a=await Ce(()=>this.http.getJson(i));if(!a)return;let c=E=>E&&Object.keys(E).length?E:void 0,p=c(a.dependencies),h=c(a.peerDependencies),m=c(a.peerDependenciesMeta);return await this.cache.setMeta(t,s,p,h,m),{name:t,version:s,dependencies:p,peerDependencies:h,peerDependenciesMeta:m}}};var lc=e=>e.startsWith("@types/"),Cr=e=>Object.keys(e?.peerDependencies||{}).filter(t=>!lc(t)),ni=e=>Object.keys(e?.dependencies||{}).filter(t=>!lc(t)),Tm=e=>Cr(e).filter(t=>!e?.peerDependenciesMeta?.[t]?.optional),yr=class{constructor(t){this.cdn=t}async resolve(t,s){let n=await this.fetchMeta(t),{allRoots:i,autoAddedPeers:a}=await this.expandWithPeers(n,s),c=this.computeFlags(i);return{allRoots:i,flags:c,autoAddedPeers:a}}async fetchMeta(t){return Promise.all(t.map(async({name:s,version:n})=>({name:s,version:n,meta:await this.cdn.fetchPackageMeta(s,n)})))}async expandWithPeers(t,s){let n=new Map(t.map(a=>[a.name,a])),i=[];for(let a of t)for(let c of Tm(a.meta))!n.has(c)&&!i.some(p=>p.name===c)&&i.push({name:c,requiredBy:a.name});for(let{name:a,requiredBy:c}of i)try{let p=await s(a),h=await this.cdn.fetchPackageMeta(a,p);n.set(a,{name:a,version:p,meta:h})}catch(p){console.warn(`[typebulb] Failed to resolve peer "${a}" for "${c}":`,p)}return{allRoots:[...n.values()],autoAddedPeers:i.filter(a=>n.has(a.name))}}computeFlags(t){let s=new Set(t.flatMap(a=>Cr(a.meta))),n=new Map;for(let a of t)for(let c of ni(a.meta))n.set(c,(n.get(c)||0)+1);let i=new Set([...n.entries()].filter(([,a])=>a>=2).map(([a])=>a));return new Map(t.map(a=>[a.name,{isPeerRoot:s.has(a.name),hasPeers:Cr(a.meta).length>0,isSharedDep:i.has(a.name)}]))}};var _r=class{constructor(t,s,n){this.cache=t,this.cdn=s,this.semver=n}selectVersionFromIndex(t,s,n){return this.semver.selectBestVersion(t,{range:s,distTags:n})}async learnExactVersion(t){let s=await Ce(()=>this.cdn.fetchVersionsIndex(t));if(s?.versions?.length){let n=this.semver.selectBestVersion(s.versions,{distTags:s.distTags});if(n)return n}return this.cdn.resolveExactVersion(t)}async resolveExactForRoot(t,s){if(!s)return this.learnExactVersion(t);let n=await this.cache.getPinnedExact(t,s);if(n){if(this.semver.isExactVersion(n))return n;console.warn("[versionResolver] Rejecting invalid cached version for",t,":",n)}let i=await Ce(()=>this.cdn.fetchVersionsIndex(t));if(i?.versions?.length){let c=this.selectVersionFromIndex(i.versions,s,i.distTags);if(c){if(this.semver.isExactVersion(c))return await this.cache.setPinnedExact(t,s,c),c}else{console.warn("[versionResolver] Invalidating stale versions cache for",t,"- range",s,"not satisfied"),await this.cache.invalidateVersionsCache(t);let p=await Ce(()=>this.cdn.fetchVersionsIndex(t));if(p?.versions?.length){let h=this.selectVersionFromIndex(p.versions,s,p.distTags);if(h&&this.semver.isExactVersion(h))return await this.cache.setPinnedExact(t,s,h),h}}}let a=await this.cdn.resolveExactVersion(`${t}@${s}`);if(a&&this.semver.isExactVersion(a))return await this.cache.setPinnedExact(t,s,a),a}async effectivePackage(t,s){let n=new oe(t),i=n.root(),a=s[i],c=a?await Ce(()=>this.cache.getPinnedExact(i,a))??await Ce(()=>this.resolveExactForRoot(i,a)):void 0;return{effectivePackage:c?n.withVersion(c).format():t,root:i,range:a,pinned:c}}};var uc;(function(e){e[e.Static=1]="Static",e[e.Dynamic=2]="Dynamic",e[e.ImportMeta=3]="ImportMeta",e[e.StaticSourcePhase=4]="StaticSourcePhase",e[e.DynamicSourcePhase=5]="DynamicSourcePhase",e[e.StaticDeferPhase=6]="StaticDeferPhase",e[e.DynamicDeferPhase=7]="DynamicDeferPhase"})(uc||(uc={}));var Sm=new Uint8Array(new Uint16Array([1]).buffer)[0]===1;function oi(e,t="@"){if(!G)return ii.then((()=>oi(e)));let s=e.length+1,n=(G.__heap_base.value||G.__heap_base)+4*s-G.memory.buffer.byteLength;n>0&&G.memory.grow(Math.ceil(n/65536));let i=G.sa(s-1);if((Sm?Qm:Bm)(e,new Uint16Array(G.memory.buffer,i,s)),!G.parse())throw Object.assign(new Error(`Parse error ${t}:${e.slice(0,G.e()).split(`
498
+ <\/script>`;function _m(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function bm(e){let t={};for(let[s,n]of Object.entries(e))t[s]=n.startsWith("https://")?"/proxy/"+n:n;return t}var Ir="https://esm.sh",xr="https://cdn.jsdelivr.net/npm/",si="https://data.jsdelivr.com/v1/package/npm/";function ac(e){let t=(e||"").replace(/^\/+/,"").replace(/\/+$/,"");return t?t.split("/"):[]}var oe=class e{constructor(t,s,n){let i=typeof t=="string"?e.parse(t):t;this.name=i.name,this.version=Nt(s??i.version),this.subpath=Nt(n??i.subpath)}static parse(t){let s=ac(t||"");if(!s.length)return new e({name:""});if(s[0].startsWith("@")){let i=s[0],[a,c]=cc(s[1]??""),p=Nt(s.slice(2).join("/"));return new e({name:`${i}/${a}`,version:c,subpath:p})}else{let[i,a]=cc(s[0]),c=Nt(s.slice(1).join("/"));return new e({name:i,version:a,subpath:c})}}static fromUrl(t){try{let s=new URL(t),n=new URL(Ir).host,i=new URL(xr).host;if(s.host===n){let a=ac(s.pathname.replace(/^\/v\d+\//,"/"));if(!a.length)return;let c=a[0].startsWith("@")?`${a[0]}/${a[1]??""}`:a[0];return e.parse(c)}if(s.host===i){let a=s.pathname.split("/npm/")[1];if(!a)return;let c=a.split("/")[0]||"";return e.parse(c)}return}catch{return}}static versionFromUrl(t){return e.fromUrl(t)?.version}format(){let t=this.version?`${this.name}@${this.version}`:this.name;return this.subpath?`${t}/${this.subpath}`:t}root(){return this.name}static rootOf(t){return e.parse(t).name}withVersion(t){return new e({name:this.name,version:Nt(t),subpath:this.subpath})}withPreferredVersion(t,s){let n=t||s;return n?this.withVersion(n):this}static isBare(t){if(!t||t.startsWith(".")||t.startsWith("/"))return!1;let s=t.toLowerCase();return!s.startsWith("http://")&&!s.startsWith("https://")}},Nt=e=>e&&e.length?e:void 0,cc=e=>{let t=e.indexOf("@");return t<0?[e,void 0]:[e.slice(0,t),Nt(e.slice(t+1))]};async function Ce(e){try{return await e()}catch{return}}var wr=class{constructor(t,s){this.cache=t,this.http=s,this.esmHost=Ir,this.jsDelivrBase=xr,this.jsDelivrMeta=si,this.pinMs=1e4,this.versionsIndexMs=1440*60*1e3,this.metaTtlMs=10080*60*1e3,this.pinCache=new Map}normalizeRelative(t){let s=t||"";return s.startsWith("./")?s.slice(2):s.replace(/^\/+/,"")}ensureLeadingDotSlash(t){return t.startsWith("./")?t:`./${t}`}baseDir(t){let s=typeof t=="string"?new oe(t):t;return`${this.jsDelivrBase}${s.name}${s.version?`@${s.version}`:""}/`}file(t,s){return new URL(this.normalizeRelative(s),this.baseDir(t)).toString()}packageJson(t){return this.file(t,"package.json")}buildEsmUrl(t,s={}){let{target:n="es2022",bundle:i=!1,external:a}=s,c=new URLSearchParams({target:n});return i&&c.append("bundle",""),a?.length&&c.append("external",a.join(",")),`${this.esmHost}/${t}?${c.toString()}`}async pinEsmUrl(t,s="es2022"){let n=this.buildEsmUrl(t,{target:s}),i=await Ce(()=>this.http.head(n));return i?.ok?i.url||n:void 0}async resolveExactVersion(t){let s=Date.now(),n=this.pinCache.get(t);if(n&&s-n.ts<this.pinMs)return n.value;let i=await this.tryResolveFromUrls([this.buildEsmUrl(t),`${this.esmHost}/${t}`]);return this.pinCache.set(t,{value:i,ts:s}),i}async tryResolveFromUrls(t){for(let s of t){let n=await Ce(()=>this.http.head(s)),i=this.parseVersionFromUrl(n?.url||s);if(i)return i}}async fetchVersionsIndex(t){if(await this.cache.isNegative(t))return;let s=await this.cache.getIndex(t);if(s&&Date.now()-s.updatedAt<this.versionsIndexMs)return{versions:s.versions,distTags:s.distTags};let n=await Ce(()=>this.http.getJson(`${this.jsDelivrMeta}${encodeURIComponent(t)}`));if(!n?.versions?.length){await this.cache.recordNegative(t);return}await this.cache.clearNegative(t);let i=n.distTags&&Object.keys(n.distTags).length?n.distTags:void 0;return await this.cache.setIndex(t,n.versions,i),n}parseVersionFromUrl(t){let s=oe.fromUrl(t)?.version;return s&&/\d+\.\d+\.\d+/.test(s)?s:void 0}async fetchPackageMeta(t,s){let n=await this.cache.getMeta(t,s);if(n&&Date.now()-n.updatedAt<this.metaTtlMs){let{dependencies:E,peerDependencies:A,peerDependenciesMeta:x}=n;return{name:t,version:s,dependencies:E,peerDependencies:A,peerDependenciesMeta:x}}let i=this.packageJson(new oe(`${t}@${s}`)),a=await Ce(()=>this.http.getJson(i));if(!a)return;let c=E=>E&&Object.keys(E).length?E:void 0,p=c(a.dependencies),h=c(a.peerDependencies),m=c(a.peerDependenciesMeta);return await this.cache.setMeta(t,s,p,h,m),{name:t,version:s,dependencies:p,peerDependencies:h,peerDependenciesMeta:m}}};var lc=e=>e.startsWith("@types/"),Cr=e=>Object.keys(e?.peerDependencies||{}).filter(t=>!lc(t)),ni=e=>Object.keys(e?.dependencies||{}).filter(t=>!lc(t)),Tm=e=>Cr(e).filter(t=>!e?.peerDependenciesMeta?.[t]?.optional),yr=class{constructor(t){this.cdn=t}async resolve(t,s){let n=await this.fetchMeta(t),{allRoots:i,autoAddedPeers:a}=await this.expandWithPeers(n,s),c=this.computeFlags(i);return{allRoots:i,flags:c,autoAddedPeers:a}}async fetchMeta(t){return Promise.all(t.map(async({name:s,version:n})=>({name:s,version:n,meta:await this.cdn.fetchPackageMeta(s,n)})))}async expandWithPeers(t,s){let n=new Map(t.map(a=>[a.name,a])),i=[];for(let a of t)for(let c of Tm(a.meta))!n.has(c)&&!i.some(p=>p.name===c)&&i.push({name:c,requiredBy:a.name});for(let{name:a,requiredBy:c}of i)try{let p=await s(a),h=await this.cdn.fetchPackageMeta(a,p);n.set(a,{name:a,version:p,meta:h})}catch(p){console.warn(`[typebulb] Failed to resolve peer "${a}" for "${c}":`,p)}return{allRoots:[...n.values()],autoAddedPeers:i.filter(a=>n.has(a.name))}}computeFlags(t){let s=new Set(t.flatMap(a=>Cr(a.meta))),n=new Map;for(let a of t)for(let c of ni(a.meta))n.set(c,(n.get(c)||0)+1);let i=new Set([...n.entries()].filter(([,a])=>a>=2).map(([a])=>a));return new Map(t.map(a=>[a.name,{isPeerRoot:s.has(a.name),hasPeers:Cr(a.meta).length>0,isSharedDep:i.has(a.name)}]))}};var _r=class{constructor(t,s,n){this.cache=t,this.cdn=s,this.semver=n}selectVersionFromIndex(t,s,n){return this.semver.selectBestVersion(t,{range:s,distTags:n})}async learnExactVersion(t){let s=await Ce(()=>this.cdn.fetchVersionsIndex(t));if(s?.versions?.length){let n=this.semver.selectBestVersion(s.versions,{distTags:s.distTags});if(n)return n}return this.cdn.resolveExactVersion(t)}async resolveExactForRoot(t,s){if(!s)return this.learnExactVersion(t);let n=await this.cache.getPinnedExact(t,s);if(n){if(this.semver.isExactVersion(n))return n;console.debug("[typebulb] cached version for",t,"is not exact (",n,"); re-resolving from registry")}let i=await Ce(()=>this.cdn.fetchVersionsIndex(t));if(i?.versions?.length){let c=this.selectVersionFromIndex(i.versions,s,i.distTags);if(c){if(this.semver.isExactVersion(c))return await this.cache.setPinnedExact(t,s,c),c}else{console.debug("[typebulb] refreshing version cache for",t,"(",s,"not in cached set \u2014 likely a new release)"),await this.cache.invalidateVersionsCache(t);let p=await Ce(()=>this.cdn.fetchVersionsIndex(t));if(p?.versions?.length){let h=this.selectVersionFromIndex(p.versions,s,p.distTags);if(h&&this.semver.isExactVersion(h))return await this.cache.setPinnedExact(t,s,h),h}}}let a=await this.cdn.resolveExactVersion(`${t}@${s}`);if(a&&this.semver.isExactVersion(a))return await this.cache.setPinnedExact(t,s,a),a}async effectivePackage(t,s){let n=new oe(t),i=n.root(),a=s[i],c=a?await Ce(()=>this.cache.getPinnedExact(i,a))??await Ce(()=>this.resolveExactForRoot(i,a)):void 0;return{effectivePackage:c?n.withVersion(c).format():t,root:i,range:a,pinned:c}}};var uc;(function(e){e[e.Static=1]="Static",e[e.Dynamic=2]="Dynamic",e[e.ImportMeta=3]="ImportMeta",e[e.StaticSourcePhase=4]="StaticSourcePhase",e[e.DynamicSourcePhase=5]="DynamicSourcePhase",e[e.StaticDeferPhase=6]="StaticDeferPhase",e[e.DynamicDeferPhase=7]="DynamicDeferPhase"})(uc||(uc={}));var Sm=new Uint8Array(new Uint16Array([1]).buffer)[0]===1;function oi(e,t="@"){if(!G)return ii.then((()=>oi(e)));let s=e.length+1,n=(G.__heap_base.value||G.__heap_base)+4*s-G.memory.buffer.byteLength;n>0&&G.memory.grow(Math.ceil(n/65536));let i=G.sa(s-1);if((Sm?Qm:Bm)(e,new Uint16Array(G.memory.buffer,i,s)),!G.parse())throw Object.assign(new Error(`Parse error ${t}:${e.slice(0,G.e()).split(`
499
499
  `).length}:${G.e()-e.lastIndexOf(`
500
500
  `,G.e()-1)}`),{idx:G.e()});let a=[],c=[];for(;G.ri();){let h=G.is(),m=G.ie(),E=G.it(),A=G.ai(),x=G.id(),I=G.ss(),C=G.se(),F;G.ip()&&(F=p(e.slice(x===-1?h-1:h,x===-1?m+1:m))),a.push({n:F,t:E,s:h,e:m,ss:I,se:C,d:x,a:A})}for(;G.re();){let h=G.es(),m=G.ee(),E=G.els(),A=G.ele(),x=e.slice(h,m),I=x[0],C=E<0?void 0:e.slice(E,A),F=C?C[0]:"";c.push({s:h,e:m,ls:E,le:A,n:I==='"'||I==="'"?p(x):x,ln:F==='"'||F==="'"?p(C):C})}function p(h){try{return(0,eval)(h)}catch{}}return[a,c,!!G.f(),!!G.ms()]}function Bm(e,t){let s=e.length,n=0;for(;n<s;){let i=e.charCodeAt(n);t[n++]=(255&i)<<8|i>>>8}}function Qm(e,t){let s=e.length,n=0;for(;n<s;)t[n]=e.charCodeAt(n++)}var G,vm=()=>{return e="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GzYCHAtBAEEAKAKwCkECajYCsAoCQAJAAkACQEEAECkiAUHhAEYNACABQfcARg0BQQAoArAKIQEMAgtBACgCsAoiAUECakHACEEKEC8NAUEGIQIMAgtBACgCsAoiAS8BAkHpAEcNACABLwEEQfQARw0AQQQhAiABLwEGQegARg0BC0EAIAFBfmo2ArAKDwtBACABIAJBAXRqNgKwCgJAQQEQKUH7AEYNAEEAIAE2ArAKDwtBACgCsAoiACECA0BBACACQQJqNgKwCgJAAkACQEEBECkiAkEiRg0AIAJBJ0cNAUEnEBpBAEEAKAKwCkECajYCsApBARApIQIMAgtBIhAaQQBBACgCsApBAmo2ArAKQQEQKSECDAELIAIQLCECCwJAIAJBOkYNAEEAIAE2ArAKDwtBAEEAKAKwCkECajYCsAoCQEEBECkiAkEiRg0AIAJBJ0YNAEEAIAE2ArAKDwsgAhAaQQBBACgCsApBAmo2ArAKAkACQEEBECkiAkEsRg0AIAJB/QBGDQFBACABNgKwCg8LQQBBACgCsApBAmo2ArAKQQEQKUH9AEYNAEEAKAKwCiECDAELC0EAKALwCSIBIAA2AhAgAUEAKAKwCkECajYCDAttAQJ/AkACQANAAkAgAEH//wNxIgFBd2oiAkEXSw0AQQEgAnRBn4CABHENAgsgAUGgAUYNASAAIQIgARAoDQJBACECQQBBACgCsAoiAEECajYCsAogAC8BAiIADQAMAgsLIAAhAgsgAkH//wNxC6sBAQR/AkACQEEAKAKwCiICLwEAIgNB4QBGDQAgASEEIAAhBQwBC0EAIAJBBGo2ArAKQQEQKSECQQAoArAKIQUCQAJAIAJBIkYNACACQSdGDQAgAhAsGkEAKAKwCiEEDAELIAIQGkEAQQAoArAKQQJqIgQ2ArAKC0EBECkhA0EAKAKwCiECCwJAIAIgBUYNACAFIARBACAAIAAgAUYiAhtBACABIAIbEAILIAMLcgEEf0EAKAKwCiEAQQAoArQKIQECQAJAA0AgAEECaiECIAAgAU8NAQJAAkAgAi8BACIDQaR/ag4CAQQACyACIQAgA0F2ag4EAgEBAgELIABBBGohAAwACwtBACACNgKwChAlQQAPC0EAIAI2ArAKQd0AC0kBA39BACEDAkAgAkUNAAJAA0AgAC0AACIEIAEtAAAiBUcNASABQQFqIQEgAEEBaiEAIAJBf2oiAg0ADAILCyAEIAVrIQMLIAMLC+wBAgBBgAgLzgEAAHgAcABvAHIAdABtAHAAbwByAHQAZgBvAHIAZQB0AGEAbwB1AHIAYwBlAHIAbwBtAHUAbgBjAHQAaQBvAG4AcwBzAGUAcgB0AHYAbwB5AGkAZQBkAGUAbABlAGMAbwBuAHQAaQBuAGkAbgBzAHQAYQBuAHQAeQBiAHIAZQBhAHIAZQB0AHUAcgBkAGUAYgB1AGcAZwBlAGEAdwBhAGkAdABoAHIAdwBoAGkAbABlAGkAZgBjAGEAdABjAGYAaQBuAGEAbABsAGUAbABzAABB0AkLEAEAAAACAAAAAAQAAEA5AAA=",typeof Buffer<"u"?Buffer.from(e,"base64"):Uint8Array.from(atob(e),(t=>t.charCodeAt(0)));var e},ii=WebAssembly.compile(vm()).then(WebAssembly.instantiate).then((({exports:e})=>{G=e}));var Rt=class e{constructor(t,s,n,i){this.version=t,this.cdn=s,this.peer=n,this.cache=i}extractImportsSync(t){let s=new Set;for(let n of e.importPatterns){n.lastIndex=0;for(let i of t.matchAll(n))oe.isBare(i[1])&&s.add(i[1])}return Array.from(s)}async extractImports(t){let s=new Set,n=i=>{oe.isBare(i)&&s.add(i)};try{await ii;let[i]=oi(t);i.forEach(a=>n(t.slice(a.s,a.e).trim()))}catch{return this.extractImportsSync(t)}return Array.from(s)}async buildImportMap(t,s,n){let i=(await this.extractImports(t)).filter(A=>!n?.has(oe.rootOf(A))),a=[...new Set(i.map(oe.rootOf))],c=await Promise.all(a.map(async A=>({name:A,version:await this.resolveVersion(A,s)}))),{allRoots:p,flags:h,autoAddedPeers:m}=await this.peer.resolve(c,A=>this.resolveVersion(A,s)),E=this.buildEntries([...i,...m.map(A=>A.name)],p,h,s);return{importMap:{imports:Object.fromEntries(E)},prefetchUrls:E.map(([,A])=>A)}}async resolveVersion(t,s){let n=s[t],i=n?`${t}@${n}`:t,a=await this.version.resolveExactForRoot(t,n);if(!a){let c=await Ce(()=>this.cdn.pinEsmUrl(i));if(!c)throw new Error(`Cannot resolve ${i}: no matching version is published (the package or version may not exist, or the registry was unreachable).`);a=oe.versionFromUrl(c),a&&n&&await Ce(()=>this.cache.setPinnedExact(t,n,a))}if(!a)throw new Error(`Cannot resolve ${i}: no concrete version found.`);return a}buildEntries(t,s,n,i){let a=new Map(s.map(C=>[C.name,C])),c=C=>{let F=a.get(oe.rootOf(C));return new oe(C).withPreferredVersion(F.version,i[F.name]).format()},p=new Set([...n.entries()].filter(([,C])=>C.isPeerRoot||C.isSharedDep).map(([C])=>C)),h=new Set(t.filter(C=>C!==oe.rootOf(C)).map(oe.rootOf)),m=[],E=new Set,A=new Set(t.filter(C=>C===oe.rootOf(C))),x=new Set;for(let C of t){let F=oe.rootOf(C),S=a.get(F),{isPeerRoot:P,hasPeers:O,isSharedDep:W}=n.get(F),V=h.has(F),Y=C!==F,Ee=!(P||W)&&(V||!O),ie=this.singletonDepsOf(S,p),me=Y&&A.has(F);me&&x.add(F);let Ve=me?[...ie,F]:ie.length?ie:void 0;m.push([C,this.cdn.buildEsmUrl(c(C),{bundle:Ee,external:Ve})]),E.add(C)}let I=new Set([...p,...x]);for(let C of I)a.has(C)&&(E.has(C)||m.push([C,this.cdn.buildEsmUrl(c(C),{})]),m.push([`${C}/`,`${this.cdn.esmHost}/${c(C)}/`]));return m}singletonDepsOf(t,s){return[...new Set([...Cr(t.meta),...ni(t.meta)])].filter(n=>s.has(n))}};Rt.importPatterns=[/\bimport\s+(?:[^'";]*?from\s*)?['"]([^'"]+)['"]/g,/\bexport\s+[^'";]*?from\s*['"]([^'"]+)['"]/g];var ue=Pt(Zl(),1),Ss=class{cmp(t,s){return t===s?0:(0,ue.gt)(t,s)?1:(0,ue.gt)(s,t)?-1:0}satisfies(t,s){return!t||!t.trim()?!0:!!(0,ue.satisfies)(s,t,{includePrerelease:!0})}pickMaxSatisfying(t,s){if(!t?.length)return;let n=(0,ue.maxSatisfying)(t,s,{includePrerelease:!0});return n===null?void 0:n}pickLatest(t){return t?.length?(0,ue.rsort)(t)[0]:void 0}selectBestVersion(t,s){if(!t?.length)return;let n=s?.range?.trim()||"*",i=s?.preferStable??!0,a=s?.distTags?.latest;if(a&&t.includes(a)&&this.satisfies(n,a))return a;if(i){let p=(0,ue.maxSatisfying)(t,n,{includePrerelease:!1});if(p)return p}return(0,ue.maxSatisfying)(t,n,{includePrerelease:!0})??void 0}majorOf(t){return(0,ue.major)(t)}isPrerelease(t){return(0,ue.prerelease)(t)!==null}isExactVersion(t){return(0,ue.valid)(t)!==null}},bi=new Ss;function eu(e,t){let s=new wr(e,t),n=new yr(s),i=new _r(e,s,bi);return{packageService:new Rt(i,s,n,e),versionResolver:i,cdnClient:s,peerResolver:n}}var tu={async getJson(e){try{let t=await fetch(e,{redirect:"follow"});return t.ok?await t.json():void 0}catch{return}},async head(e){try{let t=await fetch(e,{method:"HEAD",redirect:"follow"});return{ok:t.ok,url:t.url}}catch{return}}};function ru(e){let t=/^---[^\n]*\n([\s\S]*?)\n---/.exec(e),s=t?/^\s*name:\s*(.+?)\s*$/m.exec(t[1]):null;return s?s[1].replace(/^["']|["']$/g,""):void 0}function Tg(e){return(ru(e)??"bulb").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"bulb"}function Sg(e){return e.replace(/^---[^\n]*\r?\n[\s\S]*?\r?\n---[^\n]*\r?\n?/,"").replace(/^\r?\n+/,"")}function Bg(){let e=new Map,t=new Map,s=new Set,n=new Map;return{async getPinnedExact(i,a){return e.get(`${i}@${a}`)},async setPinnedExact(i,a,c){e.set(`${i}@${a}`,c)},async getIndex(i){return t.get(i)},async setIndex(i,a,c){t.set(i,{versions:a,distTags:c,updatedAt:Date.now()})},async invalidateVersionsCache(i){t.delete(i)},async isNegative(i){return s.has(i)},async recordNegative(i){s.add(i)},async clearNegative(i){s.delete(i)},async getMeta(i,a){return n.get(`${i}@${a}`)},async setMeta(i,a,c,p,h){n.set(`${i}@${a}`,{dependencies:c,peerDependencies:p,peerDependenciesMeta:h,updatedAt:Date.now()})}}}var{packageService:Qg}=eu(Bg(),tu);async function vg(e,t={}){let s=Si(e);if(!s)return{error:"Not a valid bulb (missing `---` frontmatter or a **code.tsx** block)."};let n=Bi(s);if(n.server.trim())return{error:"Nested bulbs are client-only; a **server.ts** block is not supported."};if(!n.code.trim())return{error:"Bulb has no **code.tsx** to run."};let i=vi(n.config),a=nc(n.code,{jsxImportSource:i.jsxImportSource});if(a.error)return{error:`Compile error: ${a.error}`};let c;try{({importMap:c}=await Qg.buildImportMap(a.code,i.dependencies??{}))}catch(h){return{error:`Dependency resolution failed: ${h instanceof Error?h.message:String(h)}`}}return{html:ic({name:n.name||"bulb",code:a.code,css:n.css,html:n.html,data:Qi(n.data),insight:n.insight,importMap:c,watch:!1,theme:t.theme})}}function Ng(){let e=document.documentElement.getAttribute("data-theme");return e==="dark"||e==="light"?e:void 0}async function Iy(e,t={}){let{html:s,error:n}=await vg(e,{theme:t.theme??Ng()});if(n||!s)throw new Error(n??"Bulb produced no output.");let i=t.initialHeight??320,a=t.maxHeight??1e5,c=document.createElement("iframe");c.setAttribute("sandbox","allow-scripts"),c.style.cssText=`display:block;width:100%;height:${i}px;border:0`,c.srcdoc=s;let p=h=>{if(h.source!==c.contentWindow)return;let m=h.data;!m||m.__typebulbEmbed!==!0||(m.kind==="height"&&typeof m.height=="number"&&Number.isFinite(m.height)?c.style.height=`${Math.min(a,Math.max(0,Math.ceil(m.height)))}px`:m.kind==="error"&&t.onError?.(String(m.message??"error")))};return window.addEventListener("message",p,t.signal?{signal:t.signal}:void 0),c}export{ru as bulbName,Iy as createBulbFrame,vg as renderBulb,Tg as slugifyBulbName,Sg as stripFrontmatter};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "typebulb",
3
- "version": "0.10.4",
3
+ "version": "0.10.6",
4
4
  "description": "Local bulb runner CLI for Typebulb",
5
5
  "license": "MIT",
6
6
  "engines": { "node": ">=18" },