typebulb 0.32.0 → 0.33.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/agents/pi/matchu-patchu.ts +1 -1
- package/dist/format/config.d.ts +8 -0
- package/dist/format/config.d.ts.map +1 -1
- package/dist/format/config.js +8 -0
- package/dist/format/config.js.map +1 -1
- package/dist/index.js +993 -992
- package/dist/servers.js +102 -102
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,169 +1,169 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __cr } from 'module'; const require = __cr(import.meta.url);
|
|
3
|
-
var
|
|
4
|
-
`),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=
|
|
5
|
-
`)),a=t}else t++}return{frontmatter:s,files:i,warnings:o,bodyEndLine:a}}catch{return null}}function
|
|
3
|
+
var Tb=Object.create;var Wo=Object.defineProperty;var Pb=Object.getOwnPropertyDescriptor;var Ob=Object.getOwnPropertyNames;var Cb=Object.getPrototypeOf,Rb=Object.prototype.hasOwnProperty;var us=(r=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(r,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):r)(function(r){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+r+'" is not supported')});var v=(r,e)=>()=>(r&&(e=r(r=0)),e);var T=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),Fu=(r,e)=>{for(var t in e)Wo(r,t,{get:e[t],enumerable:!0})},_b=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Ob(e))!Rb.call(r,s)&&s!==t&&Wo(r,s,{get:()=>e[s],enumerable:!(n=Pb(e,s))||n.enumerable});return r};var Nb=(r,e,t)=>(t=r!=null?Tb(Cb(r)):{},_b(e||!r||!r.__esModule?Wo(t,"default",{value:r,enumerable:!0}):t,r));import*as Uu from"fs/promises";import{existsSync as rr,readFileSync as Ib}from"fs";import*as Z from"path";import{pathToFileURL as $b}from"url";import{resolve as Vo}from"resolve.exports";import{init as Ju,parse as Ku}from"es-module-lexer";function Hu(r,e){let t=Z.join(r,"package.json");try{return JSON.parse(Ib(t,"utf8"))}catch{throw new Error(`--replace package '${e}' has no readable package.json at ${t}`)}}function Wu(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:Z.resolve(n)}}async function Yu(r){let{name:e,dir:t}=r;if(!rr(t))throw new Error(`--replace path for '${e}' does not exist: ${t}`);let n=Hu(t,e),s=Lb(n,e),i=Z.resolve(t,s);if(!rr(i))throw new Error(`--replace package '${e}' entry not found on disk: ${i} \u2014 did you build it (e.g. \`pnpm run build\`)?`);let o=Z.dirname(i),a=`/local/${e}/${Z.basename(i)}`,c=Mb(n,t);return await Db(e,i,o),{name:e,dir:t,entryAbs:i,serveDir:o,entryUrl:a,typesAbs:c}}function Lb(r,e){if(r.exports!==void 0){let n;try{n=Vo(r,".",{browser:!0,conditions:Yo})}catch(i){throw new Error(`--replace package '${e}' "exports" does not resolve a browser entry (conditions: ${Yo.join(", ")}): ${i instanceof Error?i.message:i}`)}let s=Go(n);if(!s)throw new Error(`--replace package '${e}' "exports" did not resolve "." to a single file (conditions: ${Yo.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 Mb(r,e){if(r.exports!==void 0)try{let n=Vo(r,".",{conditions:["types"]}),s=Go(n);if(s){let i=Z.resolve(e,s);if(rr(i))return i}}catch{}let t=r.types??r.typings;if(t){let n=Z.resolve(e,t);if(rr(n))return n}}function Go(r){if(typeof r=="string")return r;if(Array.isArray(r))return r.find(e=>typeof e=="string")}async function Db(r,e,t){await Ju;let n=Z.normalize(t),s=new Set,i=[e];for(;i.length;){let o=i.shift();if(s.has(o))continue;s.add(o);let a;try{a=await Uu.readFile(o,"utf8")}catch{continue}let c,l;try{[c,,,l]=Ku(a,o)}catch{continue}if(o===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 f of c){if(f.d===-2)continue;let u=f.n;if(u&&!u.startsWith("node:")){if(u.startsWith("./")||u.startsWith("../")||u.startsWith("/")){let d=Bb(o,u,n);d&&!s.has(d)&&i.push(d);continue}throw new Error(`override package must ship self-contained (bundle its dependencies); ${r} externalizes '${u}'`)}}}}function Bb(r,e,t){let n=e.replace(/[?#].*$/,""),s=Z.resolve(Z.dirname(r),n),i=[s,s+".js",s+".mjs",Z.join(s,"index.js"),Z.join(s,"index.mjs")];for(let o of i)if(Z.normalize(o).startsWith(t)&&rr(o))return o}function jb(r,e,t){let n=Hu(r,e),s;if(n.exports!==void 0)try{s=Go(Vo(n,t,{conditions:qu}))}catch(o){throw new Error(`--replace package '${e}' "exports" does not resolve a node entry for '${t}' (conditions: ${qu.join(", ")}): ${o instanceof Error?o.message:o}`)}else t==="."&&(s=n.main??n.module);if(!s)throw new Error(`--replace package '${e}' has no node export for '${t}'.`);let i=Z.resolve(r,s);if(!rr(i))throw new Error(`--replace package '${e}' built file not found: ${i} \u2014 did you build it (e.g. \`pnpm run build\`)?`);return $b(i).href}async function Vu(r,e){await Ju;let t;try{[t]=Ku(r)}catch{return r}let n="",s=0;for(let i of t){if(i.d!==-1)continue;let o=i.n;if(!o||o!==e.name&&!o.startsWith(e.name+"/"))continue;let a=o===e.name?".":"."+o.slice(e.name.length),c=jb(e.dir,e.name,a);n+=r.slice(s,i.s)+c,s=i.e}return n+r.slice(s)}var Yo,qu,ds=v(()=>{Yo=["browser","import","default"],qu=["node","import","default"]});function Qu(r){return tt.find(e=>Ce[e].path===r)}function ed(r){return!!r?.startsWith("typebulb")}var Ce,tt,Zu,fs=v(()=>{Ce={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"}},tt=["code","css","html","data","infer","insight","config","notes"];Zu="typebulb/v1"});function Xo(r){return/[:\n"']/.test(r)||r.startsWith(" ")||r.endsWith(" ")?`"${r.replace(/"/g,'\\"')}"`:r}function Qo(r){return r.startsWith('"')&&r.endsWith('"')?r.slice(1,-1).replace(/\\"/g,'"'):r.startsWith("'")&&r.endsWith("'")?r.slice(1,-1):r}var ps=v(()=>{});function ce(r){try{let e=r.split(`
|
|
4
|
+
`),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=Jb(n);if(!s)return null;let i=new Map,o=[],a=t;for(;t<e.length;){let l=e[t]?.trim()?.match(td);if(l){let f=l[1].trim();for(t++;t<e.length&&e[t]?.trim()==="";)t++;let u=e[t]?.match(ms);if(!u){o.push(`**${f}** has no code fence \u2014 block skipped`);continue}let d=u[1];t++;let p=[],b=Zo(d);for(;t<e.length&&!e[t]?.match(b);)p.push(e[t]),t++;let m=t<e.length;t++,o.push(...qb(f,p,m)),i.set(f,p.join(`
|
|
5
|
+
`)),a=t}else t++}return{frontmatter:s,files:i,warnings:o,bodyEndLine:a}}catch{return null}}function qb(r,e,t){let n=[];for(let s=0;s<e.length;s++){let i=e[s]?.trim().match(td);i&&Fb.has(i[1].trim())&&Ub(e,s)&&n.push(i[1].trim())}return n.length?n.map(s=>`**${r}** block has an unterminated code fence \u2014 it swallowed the **${s}** block.`):t?[]:[`**${r}** block has an unterminated code fence (it runs to the end of the file).`]}function Ub(r,e){let t=e+1;for(;t<r.length&&r[t]?.trim()==="";)t++;return!!r[t]?.match(ms)}function Jb(r){let e={};for(let t of r){let n=t.indexOf(":");if(n===-1)continue;let s=t.slice(0,n).trim(),i=t.slice(n+1).trim();switch(s){case"format":e.format=i;break;case"name":e.name=Qo(i);break}}return!ed(e.format)||!e.name?null:e}function rd(r){return ce(r)?.warnings??[]}function nd(r){let e=Object.fromEntries(tt.map(t=>[t,r.files.get(Ce[t].path)||""]));return{name:r.frontmatter.name,...e}}var td,ms,Fb,Zo,ea=v(()=>{fs();ps();td=/^\*\*(.+)\*\*$/,ms=/^(`{3,})(\w*)\s*$/,Fb=new Set(tt.map(r=>Ce[r].path)),Zo=r=>new RegExp(`^${r}\\s*$`)});function sd(r){let e=r.match(/^`{3,}/gm),t=e?Math.max(...e.map(n=>n.length)):0;return"`".repeat(Math.max(3,t+1))}function id(r,e){let{path:t}=Ce[r],n=t.split(".").pop(),s=sd(e);return`**${t}**
|
|
6
6
|
|
|
7
7
|
${s}${n}
|
|
8
8
|
${e}
|
|
9
|
-
${s}`}function
|
|
10
|
-
`)}function
|
|
11
|
-
`);for(let i=0;i<s.length;i++){if(s[i]?.trim()!==`**${n}**`)continue;let o=i+1;for(;o<s.length&&s[o]?.trim()==="";)o++;let a=s[o]?.match(
|
|
9
|
+
${s}`}function od(r){let e=tt.filter(t=>r[t]).map(t=>id(t,r[t]));return["---",`format: ${Zu}`,`name: ${Xo(r.name)}`,"---","",...e].join(`
|
|
10
|
+
`)}function ta(r,e,t){let{path:n}=Ce[e],s=r.split(`
|
|
11
|
+
`);for(let i=0;i<s.length;i++){if(s[i]?.trim()!==`**${n}**`)continue;let o=i+1;for(;o<s.length&&s[o]?.trim()==="";)o++;let a=s[o]?.match(ms);if(!a)continue;let c=Zo(a[1]),l=o+1;for(;l<s.length&&!s[l]?.match(c);)l++;if(l>=s.length)return r;let f=sd(t),u=f.length>a[1].length?f:a[1];return[...s.slice(0,o),u+a[2],...t.split(`
|
|
12
12
|
`),u,...s.slice(l+1)].join(`
|
|
13
13
|
`)}return`${r.replace(/\s*$/,"")}
|
|
14
14
|
|
|
15
|
-
${
|
|
16
|
-
`}var
|
|
17
|
-
>/]`,i);if(n&&console.log("[xml-utils] start:",o),o===-1)return;let a=r.slice(o+e.length),c=Jr(a,"^[^<]*[ /]>",0),l=c!==-1&&a[c-1]==="/";if(n&&console.log("[xml-utils] selfClosing:",l),l===!1)if(s){let p=0,b=1,m=0;for(;(c=Jr(a,"[ /]"+e+">",p))!==-1;){let g=a.substring(p,c+1);if(b+=
|
|
18
|
-
>]`),m+=
|
|
19
|
-
`)}};Wr.defaultYaml={explicit:!1,version:"1.2"};Wr.defaultTags={"!!":"tag:yaml.org,2002:"};
|
|
20
|
-
`)?
|
|
15
|
+
${id(e,t)}
|
|
16
|
+
`}var ad=v(()=>{fs();ea();ps()});function rt(r){if(!r.trim())return{};try{return JSON.parse(r)}catch{return{}}}function Ur(r){let e=rt(r??"").assets?.trim();if(e){try{let t=new URL(e);if(t.protocol!=="http:"&&t.protocol!=="https:")return}catch{return}return e.endsWith("/")?e:e+"/"}}function Wb(r){return r.replace(/\[([^\]]*)\]\([^)]*\)/g,"$1").replace(/\*\*([^*]+)\*\*/g,"$1").replace(/\*([^*]+)\*/g,"$1").replace(/`([^`]+)`/g,"$1").replace(/^#{1,6}\s+/gm,"")}function na(r){let e=rt(r??"").description?.trim();if(!e)return Hb;let t=Wb(e);return(t.length>200?t.slice(0,197)+"...":t).replace(/\n/g," ")}var Kb,ra,cd,Hb,ld=v(()=>{Kb="https://assets.typebulb.com",ra=(r,e)=>`${Kb}/u/${encodeURIComponent(r)}/${encodeURIComponent(e)}/`,cd=(r,e,t)=>Ur(r)??(e&&t?ra(e,t):void 0),Hb="A Typebulb bulb."});var ud=v(()=>{});function sa(r,e,t){let s=new RegExp(e).exec(r.slice(t));return s?t+s.index:-1}var dd=v(()=>{});function Jr(r,e,t){let s=new RegExp(e).exec(r.slice(t));return s?t+s.index+s[0].length-1:-1}var fd=v(()=>{});function hs(r,e){let t=new RegExp(e,"g"),n=r.match(t);return n?n.length:0}var pd=v(()=>{});function Kr(r,e,t){let n=t&&t.debug||!1,s=!(t&&typeof t.nested===!1),i=t&&t.startIndex||0;n&&console.log("[xml-utils] starting findTagByName with",e," and ",t);let o=sa(r,`<${e}[
|
|
17
|
+
>/]`,i);if(n&&console.log("[xml-utils] start:",o),o===-1)return;let a=r.slice(o+e.length),c=Jr(a,"^[^<]*[ /]>",0),l=c!==-1&&a[c-1]==="/";if(n&&console.log("[xml-utils] selfClosing:",l),l===!1)if(s){let p=0,b=1,m=0;for(;(c=Jr(a,"[ /]"+e+">",p))!==-1;){let g=a.substring(p,c+1);if(b+=hs(g,"<"+e+`[
|
|
18
|
+
>]`),m+=hs(g,"</"+e+">"),m>=b)break;p=c}}else c=Jr(a,"[ /]"+e+">",0);let f=o+e.length+c+1;if(n&&console.log("[xml-utils] end:",f),f===-1)return;let u=r.slice(o,f),d;return l?d=null:d=u.slice(u.indexOf(">")+1,u.lastIndexOf("<")),{inner:d,outer:u,start:o,end:f}}var ia=v(()=>{dd();fd();pd()});var oa=v(()=>{ia()});var aa=v(()=>{oa()});var md=v(()=>{aa()});var hd=v(()=>{});var gd=v(()=>{ud();ia();oa();md();aa();hd()});var F=T(re=>{"use strict";var ca=Symbol.for("yaml.alias"),yd=Symbol.for("yaml.document"),gs=Symbol.for("yaml.map"),bd=Symbol.for("yaml.pair"),la=Symbol.for("yaml.scalar"),ys=Symbol.for("yaml.seq"),Je=Symbol.for("yaml.node.type"),Gb=r=>!!r&&typeof r=="object"&&r[Je]===ca,zb=r=>!!r&&typeof r=="object"&&r[Je]===yd,Xb=r=>!!r&&typeof r=="object"&&r[Je]===gs,Qb=r=>!!r&&typeof r=="object"&&r[Je]===bd,wd=r=>!!r&&typeof r=="object"&&r[Je]===la,Zb=r=>!!r&&typeof r=="object"&&r[Je]===ys;function vd(r){if(r&&typeof r=="object")switch(r[Je]){case gs:case ys:return!0}return!1}function ew(r){if(r&&typeof r=="object")switch(r[Je]){case ca:case gs:case la:case ys:return!0}return!1}var tw=r=>(wd(r)||vd(r))&&!!r.anchor;re.ALIAS=ca;re.DOC=yd;re.MAP=gs;re.NODE_TYPE=Je;re.PAIR=bd;re.SCALAR=la;re.SEQ=ys;re.hasAnchor=tw;re.isAlias=Gb;re.isCollection=vd;re.isDocument=zb;re.isMap=Xb;re.isNode=ew;re.isPair=Qb;re.isScalar=wd;re.isSeq=Zb});var Hr=T(ua=>{"use strict";var ee=F(),le=Symbol("break visit"),Sd=Symbol("skip children"),Re=Symbol("remove node");function bs(r,e){let t=kd(e);ee.isDocument(r)?nr(null,r.contents,t,Object.freeze([r]))===Re&&(r.contents=null):nr(null,r,t,Object.freeze([]))}bs.BREAK=le;bs.SKIP=Sd;bs.REMOVE=Re;function nr(r,e,t,n){let s=xd(r,e,t,n);if(ee.isNode(s)||ee.isPair(s))return Ed(r,n,s),nr(r,s,t,n);if(typeof s!="symbol"){if(ee.isCollection(e)){n=Object.freeze(n.concat(e));for(let i=0;i<e.items.length;++i){let o=nr(i,e.items[i],t,n);if(typeof o=="number")i=o-1;else{if(o===le)return le;o===Re&&(e.items.splice(i,1),i-=1)}}}else if(ee.isPair(e)){n=Object.freeze(n.concat(e));let i=nr("key",e.key,t,n);if(i===le)return le;i===Re&&(e.key=null);let o=nr("value",e.value,t,n);if(o===le)return le;o===Re&&(e.value=null)}}return s}async function ws(r,e){let t=kd(e);ee.isDocument(r)?await sr(null,r.contents,t,Object.freeze([r]))===Re&&(r.contents=null):await sr(null,r,t,Object.freeze([]))}ws.BREAK=le;ws.SKIP=Sd;ws.REMOVE=Re;async function sr(r,e,t,n){let s=await xd(r,e,t,n);if(ee.isNode(s)||ee.isPair(s))return Ed(r,n,s),sr(r,s,t,n);if(typeof s!="symbol"){if(ee.isCollection(e)){n=Object.freeze(n.concat(e));for(let i=0;i<e.items.length;++i){let o=await sr(i,e.items[i],t,n);if(typeof o=="number")i=o-1;else{if(o===le)return le;o===Re&&(e.items.splice(i,1),i-=1)}}}else if(ee.isPair(e)){n=Object.freeze(n.concat(e));let i=await sr("key",e.key,t,n);if(i===le)return le;i===Re&&(e.key=null);let o=await sr("value",e.value,t,n);if(o===le)return le;o===Re&&(e.value=null)}}return s}function kd(r){return typeof r=="object"&&(r.Collection||r.Node||r.Value)?Object.assign({Alias:r.Node,Map:r.Node,Scalar:r.Node,Seq:r.Node},r.Value&&{Map:r.Value,Scalar:r.Value,Seq:r.Value},r.Collection&&{Map:r.Collection,Seq:r.Collection},r):r}function xd(r,e,t,n){if(typeof t=="function")return t(r,e,n);if(ee.isMap(e))return t.Map?.(r,e,n);if(ee.isSeq(e))return t.Seq?.(r,e,n);if(ee.isPair(e))return t.Pair?.(r,e,n);if(ee.isScalar(e))return t.Scalar?.(r,e,n);if(ee.isAlias(e))return t.Alias?.(r,e,n)}function Ed(r,e,t){let n=e[e.length-1];if(ee.isCollection(n))n.items[r]=t;else if(ee.isPair(n))r==="key"?n.key=t:n.value=t;else if(ee.isDocument(n))n.contents=t;else{let s=ee.isAlias(n)?"alias":"scalar";throw new Error(`Cannot replace node with ${s} parent`)}}ua.visit=bs;ua.visitAsync=ws});var da=T(Td=>{"use strict";var Ad=F(),rw=Hr(),nw={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},sw=r=>r.replace(/[!,[\]{}]/g,e=>nw[e]),Wr=class r{constructor(e,t){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},r.defaultYaml,e),this.tags=Object.assign({},r.defaultTags,t)}clone(){let e=new r(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){let e=new r(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:r.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},r.defaultTags);break}return e}add(e,t){this.atNextDocument&&(this.yaml={explicit:r.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},r.defaultTags),this.atNextDocument=!1);let n=e.trim().split(/[ \t]+/),s=n.shift();switch(s){case"%TAG":{if(n.length!==2&&(t(0,"%TAG directive should contain exactly two parts"),n.length<2))return!1;let[i,o]=n;return this.tags[i]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,n.length!==1)return t(0,"%YAML directive should contain exactly one part"),!1;let[i]=n;if(i==="1.1"||i==="1.2")return this.yaml.version=i,!0;{let o=/^\d+\.\d+$/.test(i);return t(6,`Unsupported YAML version ${i}`,o),!1}}default:return t(0,`Unknown directive ${s}`,!0),!1}}tagName(e,t){if(e==="!")return"!";if(e[0]!=="!")return t(`Not a valid tag: ${e}`),null;if(e[1]==="<"){let o=e.slice(2,-1);return o==="!"||o==="!!"?(t(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==">"&&t("Verbatim tags must end with a >"),o)}let[,n,s]=e.match(/^(.*!)([^!]*)$/s);s||t(`The ${e} tag has no suffix`);let i=this.tags[n];if(i)try{return i+decodeURIComponent(s)}catch(o){return t(String(o)),null}return n==="!"?e:(t(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[t,n]of Object.entries(this.tags))if(e.startsWith(n))return t+sw(e.substring(n.length));return e[0]==="!"?e:`!<${e}>`}toString(e){let t=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],n=Object.entries(this.tags),s;if(e&&n.length>0&&Ad.isNode(e.contents)){let i={};rw.visit(e.contents,(o,a)=>{Ad.isNode(a)&&a.tag&&(i[a.tag]=!0)}),s=Object.keys(i)}else s=[];for(let[i,o]of n)i==="!!"&&o==="tag:yaml.org,2002:"||(!e||s.some(a=>a.startsWith(o)))&&t.push(`%TAG ${i} ${o}`);return t.join(`
|
|
19
|
+
`)}};Wr.defaultYaml={explicit:!1,version:"1.2"};Wr.defaultTags={"!!":"tag:yaml.org,2002:"};Td.Directives=Wr});var vs=T(Yr=>{"use strict";var Pd=F(),iw=Hr();function ow(r){if(/[\x00-\x19\s,[\]{}]/.test(r)){let t=`Anchor must not contain whitespace or control characters: ${JSON.stringify(r)}`;throw new Error(t)}return!0}function Od(r){let e=new Set;return iw.visit(r,{Value(t,n){n.anchor&&e.add(n.anchor)}}),e}function Cd(r,e){for(let t=1;;++t){let n=`${r}${t}`;if(!e.has(n))return n}}function aw(r,e){let t=[],n=new Map,s=null;return{onAnchor:i=>{t.push(i),s??(s=Od(r));let o=Cd(e,s);return s.add(o),o},setAnchors:()=>{for(let i of t){let o=n.get(i);if(typeof o=="object"&&o.anchor&&(Pd.isScalar(o.node)||Pd.isCollection(o.node)))o.node.anchor=o.anchor;else{let a=new Error("Failed to resolve repeated object (this should not happen)");throw a.source=i,a}}},sourceObjects:n}}Yr.anchorIsValid=ow;Yr.anchorNames=Od;Yr.createNodeAnchors=aw;Yr.findNewAnchor=Cd});var fa=T(Rd=>{"use strict";function Vr(r,e,t,n){if(n&&typeof n=="object")if(Array.isArray(n))for(let s=0,i=n.length;s<i;++s){let o=n[s],a=Vr(r,n,String(s),o);a===void 0?delete n[s]:a!==o&&(n[s]=a)}else if(n instanceof Map)for(let s of Array.from(n.keys())){let i=n.get(s),o=Vr(r,n,s,i);o===void 0?n.delete(s):o!==i&&n.set(s,o)}else if(n instanceof Set)for(let s of Array.from(n)){let i=Vr(r,n,s,s);i===void 0?n.delete(s):i!==s&&(n.delete(s),n.add(i))}else for(let[s,i]of Object.entries(n)){let o=Vr(r,n,s,i);o===void 0?delete n[s]:o!==i&&(n[s]=o)}return r.call(e,t,n)}Rd.applyReviver=Vr});var nt=T(Nd=>{"use strict";var cw=F();function _d(r,e,t){if(Array.isArray(r))return r.map((n,s)=>_d(n,String(s),t));if(r&&typeof r.toJSON=="function"){if(!t||!cw.hasAnchor(r))return r.toJSON(e,t);let n={aliasCount:0,count:1,res:void 0};t.anchors.set(r,n),t.onCreate=i=>{n.res=i,delete t.onCreate};let s=r.toJSON(e,t);return t.onCreate&&t.onCreate(s),s}return typeof r=="bigint"&&!t?.keep?Number(r):r}Nd.toJS=_d});var Ss=T($d=>{"use strict";var lw=fa(),Id=F(),uw=nt(),pa=class{constructor(e){Object.defineProperty(this,Id.NODE_TYPE,{value:e})}clone(){let e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:t,maxAliasCount:n,onAnchor:s,reviver:i}={}){if(!Id.isDocument(e))throw new TypeError("A document argument is required");let o={anchors:new Map,doc:e,keep:!0,mapAsMap:t===!0,mapKeyWarned:!1,maxAliasCount:typeof n=="number"?n:100},a=uw.toJS(this,"",o);if(typeof s=="function")for(let{count:c,res:l}of o.anchors.values())s(l,c);return typeof i=="function"?lw.applyReviver(i,{"":a},"",a):a}};$d.NodeBase=pa});var Gr=T(Ld=>{"use strict";var dw=vs(),fw=Hr(),ir=F(),pw=Ss(),mw=nt(),ma=class extends pw.NodeBase{constructor(e){super(ir.ALIAS),this.source=e,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(e,t){let n;t?.aliasResolveCache?n=t.aliasResolveCache:(n=[],fw.visit(e,{Node:(i,o)=>{(ir.isAlias(o)||ir.hasAnchor(o))&&n.push(o)}}),t&&(t.aliasResolveCache=n));let s;for(let i of n){if(i===this)break;i.anchor===this.source&&(s=i)}return s}toJSON(e,t){if(!t)return{source:this.source};let{anchors:n,doc:s,maxAliasCount:i}=t,o=this.resolve(s,t);if(!o){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let a=n.get(o);if(a||(mw.toJS(o,null,t),a=n.get(o)),a?.res===void 0){let c="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(c)}if(i>=0&&(a.count+=1,a.aliasCount===0&&(a.aliasCount=ks(s,o,n)),a.count*a.aliasCount>i)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return a.res}toString(e,t,n){let s=`*${this.source}`;if(e){if(dw.anchorIsValid(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){let i=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(i)}if(e.implicitKey)return`${s} `}return s}};function ks(r,e,t){if(ir.isAlias(e)){let n=e.resolve(r),s=t&&n&&t.get(n);return s?s.count*s.aliasCount:0}else if(ir.isCollection(e)){let n=0;for(let s of e.items){let i=ks(r,s,t);i>n&&(n=i)}return n}else if(ir.isPair(e)){let n=ks(r,e.key,t),s=ks(r,e.value,t);return Math.max(n,s)}return 1}Ld.Alias=ma});var X=T(ha=>{"use strict";var hw=F(),gw=Ss(),yw=nt(),bw=r=>!r||typeof r!="function"&&typeof r!="object",st=class extends gw.NodeBase{constructor(e){super(hw.SCALAR),this.value=e}toJSON(e,t){return t?.keep?this.value:yw.toJS(this.value,e,t)}toString(){return String(this.value)}};st.BLOCK_FOLDED="BLOCK_FOLDED";st.BLOCK_LITERAL="BLOCK_LITERAL";st.PLAIN="PLAIN";st.QUOTE_DOUBLE="QUOTE_DOUBLE";st.QUOTE_SINGLE="QUOTE_SINGLE";ha.Scalar=st;ha.isScalarValue=bw});var zr=T(Dd=>{"use strict";var ww=Gr(),Rt=F(),Md=X(),vw="tag:yaml.org,2002:";function Sw(r,e,t){if(e){let n=t.filter(i=>i.tag===e),s=n.find(i=>!i.format)??n[0];if(!s)throw new Error(`Tag ${e} not found`);return s}return t.find(n=>n.identify?.(r)&&!n.format)}function kw(r,e,t){if(Rt.isDocument(r)&&(r=r.contents),Rt.isNode(r))return r;if(Rt.isPair(r)){let u=t.schema[Rt.MAP].createNode?.(t.schema,null,t);return u.items.push(r),u}(r instanceof String||r instanceof Number||r instanceof Boolean||typeof BigInt<"u"&&r instanceof BigInt)&&(r=r.valueOf());let{aliasDuplicateObjects:n,onAnchor:s,onTagObj:i,schema:o,sourceObjects:a}=t,c;if(n&&r&&typeof r=="object"){if(c=a.get(r),c)return c.anchor??(c.anchor=s(r)),new ww.Alias(c.anchor);c={anchor:null,node:null},a.set(r,c)}e?.startsWith("!!")&&(e=vw+e.slice(2));let l=Sw(r,e,o.tags);if(!l){if(r&&typeof r.toJSON=="function"&&(r=r.toJSON()),!r||typeof r!="object"){let u=new Md.Scalar(r);return c&&(c.node=u),u}l=r instanceof Map?o[Rt.MAP]:Symbol.iterator in Object(r)?o[Rt.SEQ]:o[Rt.MAP]}i&&(i(l),delete t.onTagObj);let f=l?.createNode?l.createNode(t.schema,r,t):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(t.schema,r,t):new Md.Scalar(r);return e?f.tag=e:l.default||(f.tag=l.tag),c&&(c.node=f),f}Dd.createNode=kw});var Es=T(xs=>{"use strict";var xw=zr(),_e=F(),Ew=Ss();function ga(r,e,t){let n=t;for(let s=e.length-1;s>=0;--s){let i=e[s];if(typeof i=="number"&&Number.isInteger(i)&&i>=0){let o=[];o[i]=n,n=o}else n=new Map([[i,n]])}return xw.createNode(n,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:r,sourceObjects:new Map})}var Bd=r=>r==null||typeof r=="object"&&!!r[Symbol.iterator]().next().done,ya=class extends Ew.NodeBase{constructor(e,t){super(e),Object.defineProperty(this,"schema",{value:t,configurable:!0,enumerable:!1,writable:!0})}clone(e){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(t.schema=e),t.items=t.items.map(n=>_e.isNode(n)||_e.isPair(n)?n.clone(e):n),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(Bd(e))this.add(t);else{let[n,...s]=e,i=this.get(n,!0);if(_e.isCollection(i))i.addIn(s,t);else if(i===void 0&&this.schema)this.set(n,ga(this.schema,s,t));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${s}`)}}deleteIn(e){let[t,...n]=e;if(n.length===0)return this.delete(t);let s=this.get(t,!0);if(_e.isCollection(s))return s.deleteIn(n);throw new Error(`Expected YAML collection at ${t}. Remaining path: ${n}`)}getIn(e,t){let[n,...s]=e,i=this.get(n,!0);return s.length===0?!t&&_e.isScalar(i)?i.value:i:_e.isCollection(i)?i.getIn(s,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!_e.isPair(t))return!1;let n=t.value;return n==null||e&&_e.isScalar(n)&&n.value==null&&!n.commentBefore&&!n.comment&&!n.tag})}hasIn(e){let[t,...n]=e;if(n.length===0)return this.has(t);let s=this.get(t,!0);return _e.isCollection(s)?s.hasIn(n):!1}setIn(e,t){let[n,...s]=e;if(s.length===0)this.set(n,t);else{let i=this.get(n,!0);if(_e.isCollection(i))i.setIn(s,t);else if(i===void 0&&this.schema)this.set(n,ga(this.schema,s,t));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${s}`)}}};xs.Collection=ya;xs.collectionFromPath=ga;xs.isEmptyPath=Bd});var Xr=T(As=>{"use strict";var Aw=r=>r.replace(/^(?!$)(?: $)?/gm,"#");function ba(r,e){return/^\n+$/.test(r)?r.substring(1):e?r.replace(/^(?! *$)/gm,e):r}var Tw=(r,e,t)=>r.endsWith(`
|
|
20
|
+
`)?ba(t,e):t.includes(`
|
|
21
21
|
`)?`
|
|
22
|
-
`+
|
|
23
|
-
`)t===
|
|
24
|
-
`&&p!==" "){let
|
|
25
|
-
`&&
|
|
26
|
-
${e}${r.slice(0,N)}`:(t===
|
|
27
|
-
${e}${r.slice(
|
|
28
|
-
`);n=e,s=e+1,i=r[s]}return n}Qr.FOLD_BLOCK=
|
|
29
|
-
`){if(i-o>n)return!0;if(o=i+1,s-o<=n)return!1}return!0}function Zr(r,e){let t=JSON.stringify(r);if(e.options.doubleQuotedAsJSON)return t;let{implicitKey:n}=e,s=e.options.doubleQuotedMinMultiLineLength,i=e.indent||(
|
|
22
|
+
`+ba(t,e):(r.endsWith(" ")?"":" ")+t;As.indentComment=ba;As.lineComment=Tw;As.stringifyComment=Aw});var Fd=T(Qr=>{"use strict";var Pw="flow",wa="block",Ts="quoted";function Ow(r,e,t="flow",{indentAtStart:n,lineWidth:s=80,minContentWidth:i=20,onFold:o,onOverflow:a}={}){if(!s||s<0)return r;s<i&&(i=0);let c=Math.max(1+i,1+s-e.length);if(r.length<=c)return r;let l=[],f={},u=s-e.length;typeof n=="number"&&(n>s-Math.max(2,i)?l.push(0):u=s-n);let d,p,b=!1,m=-1,g=-1,x=-1;t===wa&&(m=jd(r,m,e.length),m!==-1&&(u=m+c));for(let P;P=r[m+=1];){if(t===Ts&&P==="\\"){switch(g=m,r[m+1]){case"x":m+=3;break;case"u":m+=5;break;case"U":m+=9;break;default:m+=1}x=m}if(P===`
|
|
23
|
+
`)t===wa&&(m=jd(r,m,e.length)),u=m+e.length+c,d=void 0;else{if(P===" "&&p&&p!==" "&&p!==`
|
|
24
|
+
`&&p!==" "){let _=r[m+1];_&&_!==" "&&_!==`
|
|
25
|
+
`&&_!==" "&&(d=m)}if(m>=u)if(d)l.push(d),u=d+c,d=void 0;else if(t===Ts){for(;p===" "||p===" ";)p=P,P=r[m+=1],b=!0;let _=m>x+1?m-2:g-1;if(f[_])return r;l.push(_),f[_]=!0,u=_+c,d=void 0}else b=!0}p=P}if(b&&a&&a(),l.length===0)return r;o&&o();let A=r.slice(0,l[0]);for(let P=0;P<l.length;++P){let _=l[P],N=l[P+1]||r.length;_===0?A=`
|
|
26
|
+
${e}${r.slice(0,N)}`:(t===Ts&&f[_]&&(A+=`${r[_]}\\`),A+=`
|
|
27
|
+
${e}${r.slice(_+1,N)}`)}return A}function jd(r,e,t){let n=e,s=e+1,i=r[s];for(;i===" "||i===" ";)if(e<s+t)i=r[++e];else{do i=r[++e];while(i&&i!==`
|
|
28
|
+
`);n=e,s=e+1,i=r[s]}return n}Qr.FOLD_BLOCK=wa;Qr.FOLD_FLOW=Pw;Qr.FOLD_QUOTED=Ts;Qr.foldFlowLines=Ow});var en=T(qd=>{"use strict";var ve=X(),it=Fd(),Os=(r,e)=>({indentAtStart:e?r.indent.length:r.indentAtStart,lineWidth:r.options.lineWidth,minContentWidth:r.options.minContentWidth}),Cs=r=>/^(%|---|\.\.\.)/m.test(r);function Cw(r,e,t){if(!e||e<0)return!1;let n=e-t,s=r.length;if(s<=n)return!1;for(let i=0,o=0;i<s;++i)if(r[i]===`
|
|
29
|
+
`){if(i-o>n)return!0;if(o=i+1,s-o<=n)return!1}return!0}function Zr(r,e){let t=JSON.stringify(r);if(e.options.doubleQuotedAsJSON)return t;let{implicitKey:n}=e,s=e.options.doubleQuotedMinMultiLineLength,i=e.indent||(Cs(r)?" ":""),o="",a=0;for(let c=0,l=t[c];l;l=t[++c])if(l===" "&&t[c+1]==="\\"&&t[c+2]==="n"&&(o+=t.slice(a,c)+"\\ ",c+=1,a=c,l="\\"),l==="\\")switch(t[c+1]){case"u":{o+=t.slice(a,c);let f=t.substr(c+2,4);switch(f){case"0000":o+="\\0";break;case"0007":o+="\\a";break;case"000b":o+="\\v";break;case"001b":o+="\\e";break;case"0085":o+="\\N";break;case"00a0":o+="\\_";break;case"2028":o+="\\L";break;case"2029":o+="\\P";break;default:f.substr(0,2)==="00"?o+="\\x"+f.substr(2):o+=t.substr(c,6)}c+=5,a=c+1}break;case"n":if(n||t[c+2]==='"'||t.length<s)c+=1;else{for(o+=t.slice(a,c)+`
|
|
30
30
|
|
|
31
31
|
`;t[c+2]==="\\"&&t[c+3]==="n"&&t[c+4]!=='"';)o+=`
|
|
32
|
-
`,c+=2;o+=i,t[c+2]===" "&&(o+="\\"),c+=1,a=c+1}break;default:c+=1}return o=a?o+t.slice(a):t,n?o:it.foldFlowLines(o,i,it.FOLD_QUOTED,
|
|
33
|
-
`)||/[ \t]\n|\n[ \t]/.test(r))return Zr(r,e);let t=e.indent||(
|
|
34
|
-
${t}`)+"'";return e.implicitKey?n:it.foldFlowLines(n,t,it.FOLD_FLOW,
|
|
32
|
+
`,c+=2;o+=i,t[c+2]===" "&&(o+="\\"),c+=1,a=c+1}break;default:c+=1}return o=a?o+t.slice(a):t,n?o:it.foldFlowLines(o,i,it.FOLD_QUOTED,Os(e,!1))}function va(r,e){if(e.options.singleQuote===!1||e.implicitKey&&r.includes(`
|
|
33
|
+
`)||/[ \t]\n|\n[ \t]/.test(r))return Zr(r,e);let t=e.indent||(Cs(r)?" ":""),n="'"+r.replace(/'/g,"''").replace(/\n+/g,`$&
|
|
34
|
+
${t}`)+"'";return e.implicitKey?n:it.foldFlowLines(n,t,it.FOLD_FLOW,Os(e,!1))}function or(r,e){let{singleQuote:t}=e.options,n;if(t===!1)n=Zr;else{let s=r.includes('"'),i=r.includes("'");s&&!i?n=va:i&&!s?n=Zr:n=t?va:Zr}return n(r,e)}var Sa;try{Sa=new RegExp(`(^|(?<!
|
|
35
35
|
))
|
|
36
36
|
+(?!
|
|
37
|
-
|$)`,"g")}catch{
|
|
37
|
+
|$)`,"g")}catch{Sa=/\n+(?!\n|$)/g}function Ps({comment:r,type:e,value:t},n,s,i){let{blockQuote:o,commentString:a,lineWidth:c}=n.options;if(!o||/\n[\t ]+$/.test(t))return or(t,n);let l=n.indent||(n.forceBlockIndent||Cs(t)?" ":""),f=o==="literal"?!0:o==="folded"||e===ve.Scalar.BLOCK_FOLDED?!1:e===ve.Scalar.BLOCK_LITERAL?!0:!Cw(t,c,l.length);if(!t)return f?`|
|
|
38
38
|
`:`>
|
|
39
|
-
`;let u,
|
|
40
|
-
`&&N!==" "&&N!==" ")break}let p=t.substring(
|
|
39
|
+
`;let u,d;for(d=t.length;d>0;--d){let N=t[d-1];if(N!==`
|
|
40
|
+
`&&N!==" "&&N!==" ")break}let p=t.substring(d),b=p.indexOf(`
|
|
41
41
|
`);b===-1?u="-":t===p||b!==p.length-1?(u="+",i&&i()):u="",p&&(t=t.slice(0,-p.length),p[p.length-1]===`
|
|
42
|
-
`&&(p=p.slice(0,-1)),p=p.replace(
|
|
43
|
-
`)x=g;else break}let A=t.substring(0,x<g?x+1:g);A&&(t=t.substring(A.length),A=A.replace(/\n+/g,`$&${l}`));let
|
|
44
|
-
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),
|
|
45
|
-
${l}${E}`}return t=t.replace(/\n+/g,`$&${l}`),`|${
|
|
46
|
-
${l}${A}${t}${p}`}function
|
|
47
|
-
`)||
|
|
48
|
-
`)?
|
|
49
|
-
`))return
|
|
50
|
-
${c}`);if(o){let
|
|
51
|
-
${e.indent}${a}`:a}
|
|
52
|
-
${a}:`):(g=`${g}:`,
|
|
53
|
-
`:"",A){let
|
|
54
|
-
${rn.indentComment(
|
|
55
|
-
`&&P&&(
|
|
56
|
-
|
|
57
|
-
`):
|
|
58
|
-
${t.indent}`}else if(!p&&
|
|
59
|
-
`),y=E!==-1,
|
|
42
|
+
`&&(p=p.slice(0,-1)),p=p.replace(Sa,`$&${l}`));let m=!1,g,x=-1;for(g=0;g<t.length;++g){let N=t[g];if(N===" ")m=!0;else if(N===`
|
|
43
|
+
`)x=g;else break}let A=t.substring(0,x<g?x+1:g);A&&(t=t.substring(A.length),A=A.replace(/\n+/g,`$&${l}`));let _=(m?l?"2":"1":"")+u;if(r&&(_+=" "+a(r.replace(/ ?[\r\n]+/g," ")),s&&s()),!f){let N=t.replace(/\n+/g,`
|
|
44
|
+
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),C=!1,I=Os(n,!0);o!=="folded"&&e!==ve.Scalar.BLOCK_FOLDED&&(I.onOverflow=()=>{C=!0});let E=it.foldFlowLines(`${A}${N}${p}`,l,it.FOLD_BLOCK,I);if(!C)return`>${_}
|
|
45
|
+
${l}${E}`}return t=t.replace(/\n+/g,`$&${l}`),`|${_}
|
|
46
|
+
${l}${A}${t}${p}`}function Rw(r,e,t,n){let{type:s,value:i}=r,{actualString:o,implicitKey:a,indent:c,indentStep:l,inFlow:f}=e;if(a&&i.includes(`
|
|
47
|
+
`)||f&&/[[\]{},]/.test(i))return or(i,e);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(i))return a||f||!i.includes(`
|
|
48
|
+
`)?or(i,e):Ps(r,e,t,n);if(!a&&!f&&s!==ve.Scalar.PLAIN&&i.includes(`
|
|
49
|
+
`))return Ps(r,e,t,n);if(Cs(i)){if(c==="")return e.forceBlockIndent=!0,Ps(r,e,t,n);if(a&&c===l)return or(i,e)}let u=i.replace(/\n+/g,`$&
|
|
50
|
+
${c}`);if(o){let d=m=>m.default&&m.tag!=="tag:yaml.org,2002:str"&&m.test?.test(u),{compat:p,tags:b}=e.doc.schema;if(b.some(d)||p?.some(d))return or(i,e)}return a?u:it.foldFlowLines(u,c,it.FOLD_FLOW,Os(e,!1))}function _w(r,e,t,n){let{implicitKey:s,inFlow:i}=e,o=typeof r.value=="string"?r:Object.assign({},r,{value:String(r.value)}),{type:a}=r;a!==ve.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(a=ve.Scalar.QUOTE_DOUBLE);let c=f=>{switch(f){case ve.Scalar.BLOCK_FOLDED:case ve.Scalar.BLOCK_LITERAL:return s||i?or(o.value,e):Ps(o,e,t,n);case ve.Scalar.QUOTE_DOUBLE:return Zr(o.value,e);case ve.Scalar.QUOTE_SINGLE:return va(o.value,e);case ve.Scalar.PLAIN:return Rw(o,e,t,n);default:return null}},l=c(a);if(l===null){let{defaultKeyType:f,defaultStringType:u}=e.options,d=s&&f||u;if(l=c(d),l===null)throw new Error(`Unsupported default string type ${d}`)}return l}qd.stringifyString=_w});var tn=T(ka=>{"use strict";var Nw=vs(),ot=F(),Iw=Xr(),$w=en();function Lw(r,e){let t=Object.assign({blockQuote:!0,commentString:Iw.stringifyComment,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trueStr:"true",verifyAliasOrder:!0},r.schema.toStringOptions,e),n;switch(t.collectionStyle){case"block":n=!1;break;case"flow":n=!0;break;default:n=null}return{anchors:new Set,doc:r,flowCollectionPadding:t.flowCollectionPadding?" ":"",indent:"",indentStep:typeof t.indent=="number"?" ".repeat(t.indent):" ",inFlow:n,options:t}}function Mw(r,e){if(e.tag){let s=r.filter(i=>i.tag===e.tag);if(s.length>0)return s.find(i=>i.format===e.format)??s[0]}let t,n;if(ot.isScalar(e)){n=e.value;let s=r.filter(i=>i.identify?.(n));if(s.length>1){let i=s.filter(o=>o.test);i.length>0&&(s=i)}t=s.find(i=>i.format===e.format)??s.find(i=>!i.format)}else n=e,t=r.find(s=>s.nodeClass&&n instanceof s.nodeClass);if(!t){let s=n?.constructor?.name??(n===null?"null":typeof n);throw new Error(`Tag not resolved for ${s} value`)}return t}function Dw(r,e,{anchors:t,doc:n}){if(!n.directives)return"";let s=[],i=(ot.isScalar(r)||ot.isCollection(r))&&r.anchor;i&&Nw.anchorIsValid(i)&&(t.add(i),s.push(`&${i}`));let o=r.tag??(e.default?null:e.tag);return o&&s.push(n.directives.tagString(o)),s.join(" ")}function Bw(r,e,t,n){if(ot.isPair(r))return r.toString(e,t,n);if(ot.isAlias(r)){if(e.doc.directives)return r.toString(e);if(e.resolvedAliases?.has(r))throw new TypeError("Cannot stringify circular structure without alias nodes");e.resolvedAliases?e.resolvedAliases.add(r):e.resolvedAliases=new Set([r]),r=r.resolve(e.doc)}let s,i=ot.isNode(r)?r:e.doc.createNode(r,{onTagObj:c=>s=c});s??(s=Mw(e.doc.schema.tags,i));let o=Dw(i,s,e);o.length>0&&(e.indentAtStart=(e.indentAtStart??0)+o.length+1);let a=typeof s.stringify=="function"?s.stringify(i,e,t,n):ot.isScalar(i)?$w.stringifyString(i,e,t,n):i.toString(e,t,n);return o?ot.isScalar(i)||a[0]==="{"||a[0]==="["?`${o} ${a}`:`${o}
|
|
51
|
+
${e.indent}${a}`:a}ka.createStringifyContext=Lw;ka.stringify=Bw});var Hd=T(Kd=>{"use strict";var Ke=F(),Ud=X(),Jd=tn(),rn=Xr();function jw({key:r,value:e},t,n,s){let{allNullValues:i,doc:o,indent:a,indentStep:c,options:{commentString:l,indentSeq:f,simpleKeys:u}}=t,d=Ke.isNode(r)&&r.comment||null;if(u){if(d)throw new Error("With simple keys, key nodes cannot have comments");if(Ke.isCollection(r)||!Ke.isNode(r)&&typeof r=="object"){let I="With simple keys, collection cannot be used as a key value";throw new Error(I)}}let p=!u&&(!r||d&&e==null&&!t.inFlow||Ke.isCollection(r)||(Ke.isScalar(r)?r.type===Ud.Scalar.BLOCK_FOLDED||r.type===Ud.Scalar.BLOCK_LITERAL:typeof r=="object"));t=Object.assign({},t,{allNullValues:!1,implicitKey:!p&&(u||!i),indent:a+c});let b=!1,m=!1,g=Jd.stringify(r,t,()=>b=!0,()=>m=!0);if(!p&&!t.inFlow&&g.length>1024){if(u)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");p=!0}if(t.inFlow){if(i||e==null)return b&&n&&n(),g===""?"?":p?`? ${g}`:g}else if(i&&!u||e==null&&p)return g=`? ${g}`,d&&!b?g+=rn.lineComment(g,t.indent,l(d)):m&&s&&s(),g;b&&(d=null),p?(d&&(g+=rn.lineComment(g,t.indent,l(d))),g=`? ${g}
|
|
52
|
+
${a}:`):(g=`${g}:`,d&&(g+=rn.lineComment(g,t.indent,l(d))));let x,A,P;Ke.isNode(e)?(x=!!e.spaceBefore,A=e.commentBefore,P=e.comment):(x=!1,A=null,P=null,e&&typeof e=="object"&&(e=o.createNode(e))),t.implicitKey=!1,!p&&!d&&Ke.isScalar(e)&&(t.indentAtStart=g.length+1),m=!1,!f&&c.length>=2&&!t.inFlow&&!p&&Ke.isSeq(e)&&!e.flow&&!e.tag&&!e.anchor&&(t.indent=t.indent.substring(2));let _=!1,N=Jd.stringify(e,t,()=>_=!0,()=>m=!0),C=" ";if(d||x||A){if(C=x?`
|
|
53
|
+
`:"",A){let I=l(A);C+=`
|
|
54
|
+
${rn.indentComment(I,t.indent)}`}N===""&&!t.inFlow?C===`
|
|
55
|
+
`&&P&&(C=`
|
|
56
|
+
|
|
57
|
+
`):C+=`
|
|
58
|
+
${t.indent}`}else if(!p&&Ke.isCollection(e)){let I=N[0],E=N.indexOf(`
|
|
59
|
+
`),y=E!==-1,w=t.inFlow??e.flow??e.items.length===0;if(y||!w){let $=!1;if(y&&(I==="&"||I==="!")){let R=N.indexOf(" ");I==="&"&&R!==-1&&R<E&&N[R+1]==="!"&&(R=N.indexOf(" ",R+1)),(R===-1||E<R)&&($=!0)}$||(C=`
|
|
60
60
|
${t.indent}`)}}else(N===""||N[0]===`
|
|
61
|
-
`)&&(
|
|
61
|
+
`)&&(C="");return g+=C+N,t.inFlow?_&&n&&n():P&&!_?g+=rn.lineComment(g,t.indent,l(P)):m&&s&&s(),g}Kd.stringifyPair=jw});var Ea=T(xa=>{"use strict";var Wd=us("process");function Fw(r,...e){r==="debug"&&console.log(...e)}function qw(r,e){(r==="debug"||r==="warn")&&(typeof Wd.emitWarning=="function"?Wd.emitWarning(e):console.warn(e))}xa.debug=Fw;xa.warn=qw});var Is=T(Ns=>{"use strict";var nn=F(),Yd=X(),Rs="<<",_s={identify:r=>r===Rs||typeof r=="symbol"&&r.description===Rs,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new Yd.Scalar(Symbol(Rs)),{addToJSMap:Vd}),stringify:()=>Rs},Uw=(r,e)=>(_s.identify(e)||nn.isScalar(e)&&(!e.type||e.type===Yd.Scalar.PLAIN)&&_s.identify(e.value))&&r?.doc.schema.tags.some(t=>t.tag===_s.tag&&t.default);function Vd(r,e,t){if(t=r&&nn.isAlias(t)?t.resolve(r.doc):t,nn.isSeq(t))for(let n of t.items)Aa(r,e,n);else if(Array.isArray(t))for(let n of t)Aa(r,e,n);else Aa(r,e,t)}function Aa(r,e,t){let n=r&&nn.isAlias(t)?t.resolve(r.doc):t;if(!nn.isMap(n))throw new Error("Merge sources must be maps or map aliases");let s=n.toJSON(null,r,Map);for(let[i,o]of s)e instanceof Map?e.has(i)||e.set(i,o):e instanceof Set?e.add(i):Object.prototype.hasOwnProperty.call(e,i)||Object.defineProperty(e,i,{value:o,writable:!0,enumerable:!0,configurable:!0});return e}Ns.addMergeToJSMap=Vd;Ns.isMergeKey=Uw;Ns.merge=_s});var Pa=T(Xd=>{"use strict";var Jw=Ea(),Gd=Is(),Kw=tn(),zd=F(),Ta=nt();function Hw(r,e,{key:t,value:n}){if(zd.isNode(t)&&t.addToJSMap)t.addToJSMap(r,e,n);else if(Gd.isMergeKey(r,t))Gd.addMergeToJSMap(r,e,n);else{let s=Ta.toJS(t,"",r);if(e instanceof Map)e.set(s,Ta.toJS(n,s,r));else if(e instanceof Set)e.add(s);else{let i=Ww(t,s,r),o=Ta.toJS(n,i,r);i in e?Object.defineProperty(e,i,{value:o,writable:!0,enumerable:!0,configurable:!0}):e[i]=o}}return e}function Ww(r,e,t){if(e===null)return"";if(typeof e!="object")return String(e);if(zd.isNode(r)&&t?.doc){let n=Kw.createStringifyContext(t.doc,{});n.anchors=new Set;for(let i of t.anchors.keys())n.anchors.add(i.anchor);n.inFlow=!0,n.inStringifyKey=!0;let s=r.toString(n);if(!t.mapKeyWarned){let i=JSON.stringify(s);i.length>40&&(i=i.substring(0,36)+'..."'),Jw.warn(t.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${i}. Set mapAsMap: true to use object keys.`),t.mapKeyWarned=!0}return s}return JSON.stringify(e)}Xd.addPairToJSMap=Hw});var at=T(Oa=>{"use strict";var Qd=zr(),Yw=Hd(),Vw=Pa(),$s=F();function Gw(r,e,t){let n=Qd.createNode(r,void 0,t),s=Qd.createNode(e,void 0,t);return new Ls(n,s)}var Ls=class r{constructor(e,t=null){Object.defineProperty(this,$s.NODE_TYPE,{value:$s.PAIR}),this.key=e,this.value=t}clone(e){let{key:t,value:n}=this;return $s.isNode(t)&&(t=t.clone(e)),$s.isNode(n)&&(n=n.clone(e)),new r(t,n)}toJSON(e,t){let n=t?.mapAsMap?new Map:{};return Vw.addPairToJSMap(t,n,this)}toString(e,t,n){return e?.doc?Yw.stringifyPair(this,e,t,n):JSON.stringify(this)}};Oa.Pair=Ls;Oa.createPair=Gw});var Ca=T(ef=>{"use strict";var _t=F(),Zd=tn(),Ms=Xr();function zw(r,e,t){return(e.inFlow??r.flow?Qw:Xw)(r,e,t)}function Xw({comment:r,items:e},t,{blockItemPrefix:n,flowChars:s,itemIndent:i,onChompKeep:o,onComment:a}){let{indent:c,options:{commentString:l}}=t,f=Object.assign({},t,{indent:i,type:null}),u=!1,d=[];for(let b=0;b<e.length;++b){let m=e[b],g=null;if(_t.isNode(m))!u&&m.spaceBefore&&d.push(""),Ds(t,d,m.commentBefore,u),m.comment&&(g=m.comment);else if(_t.isPair(m)){let A=_t.isNode(m.key)?m.key:null;A&&(!u&&A.spaceBefore&&d.push(""),Ds(t,d,A.commentBefore,u))}u=!1;let x=Zd.stringify(m,f,()=>g=null,()=>u=!0);g&&(x+=Ms.lineComment(x,i,l(g))),u&&g&&(u=!1),d.push(n+x)}let p;if(d.length===0)p=s.start+s.end;else{p=d[0];for(let b=1;b<d.length;++b){let m=d[b];p+=m?`
|
|
62
62
|
${c}${m}`:`
|
|
63
63
|
`}}return r?(p+=`
|
|
64
|
-
|
|
65
|
-
`))&&(l=!0),u.push(x),
|
|
64
|
+
`+Ms.indentComment(l(r),c),a&&a()):u&&o&&o(),p}function Qw({items:r},e,{flowChars:t,itemIndent:n}){let{indent:s,indentStep:i,flowCollectionPadding:o,options:{commentString:a}}=e;n+=i;let c=Object.assign({},e,{indent:n,inFlow:!0,type:null}),l=!1,f=0,u=[];for(let b=0;b<r.length;++b){let m=r[b],g=null;if(_t.isNode(m))m.spaceBefore&&u.push(""),Ds(e,u,m.commentBefore,!1),m.comment&&(g=m.comment);else if(_t.isPair(m)){let A=_t.isNode(m.key)?m.key:null;A&&(A.spaceBefore&&u.push(""),Ds(e,u,A.commentBefore,!1),A.comment&&(l=!0));let P=_t.isNode(m.value)?m.value:null;P?(P.comment&&(g=P.comment),P.commentBefore&&(l=!0)):m.value==null&&A?.comment&&(g=A.comment)}g&&(l=!0);let x=Zd.stringify(m,c,()=>g=null);b<r.length-1&&(x+=","),g&&(x+=Ms.lineComment(x,n,a(g))),!l&&(u.length>f||x.includes(`
|
|
65
|
+
`))&&(l=!0),u.push(x),f=u.length}let{start:d,end:p}=t;if(u.length===0)return d+p;if(!l){let b=u.reduce((m,g)=>m+g.length+2,2);l=e.options.lineWidth>0&&b>e.options.lineWidth}if(l){let b=d;for(let m of u)b+=m?`
|
|
66
66
|
${i}${s}${m}`:`
|
|
67
67
|
`;return`${b}
|
|
68
|
-
${s}${p}`}else return`${
|
|
69
|
-
`:" ")}return
|
|
68
|
+
${s}${p}`}else return`${d}${o}${u.join(" ")}${o}${p}`}function Ds({indent:r,options:{commentString:e}},t,n,s){if(n&&s&&(n=n.replace(/^\n+/,"")),n){let i=Ms.indentComment(e(n),r);t.push(i.trimStart())}}ef.stringifyCollection=zw});var lt=T(_a=>{"use strict";var Zw=Ca(),ev=Pa(),tv=Es(),ct=F(),Bs=at(),rv=X();function sn(r,e){let t=ct.isScalar(e)?e.value:e;for(let n of r)if(ct.isPair(n)&&(n.key===e||n.key===t||ct.isScalar(n.key)&&n.key.value===t))return n}var Ra=class extends tv.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(ct.MAP,e),this.items=[]}static from(e,t,n){let{keepUndefined:s,replacer:i}=n,o=new this(e),a=(c,l)=>{if(typeof i=="function")l=i.call(t,c,l);else if(Array.isArray(i)&&!i.includes(c))return;(l!==void 0||s)&&o.items.push(Bs.createPair(c,l,n))};if(t instanceof Map)for(let[c,l]of t)a(c,l);else if(t&&typeof t=="object")for(let c of Object.keys(t))a(c,t[c]);return typeof e.sortMapEntries=="function"&&o.items.sort(e.sortMapEntries),o}add(e,t){let n;ct.isPair(e)?n=e:!e||typeof e!="object"||!("key"in e)?n=new Bs.Pair(e,e?.value):n=new Bs.Pair(e.key,e.value);let s=sn(this.items,n.key),i=this.schema?.sortMapEntries;if(s){if(!t)throw new Error(`Key ${n.key} already set`);ct.isScalar(s.value)&&rv.isScalarValue(n.value)?s.value.value=n.value:s.value=n.value}else if(i){let o=this.items.findIndex(a=>i(n,a)<0);o===-1?this.items.push(n):this.items.splice(o,0,n)}else this.items.push(n)}delete(e){let t=sn(this.items,e);return t?this.items.splice(this.items.indexOf(t),1).length>0:!1}get(e,t){let s=sn(this.items,e)?.value;return(!t&&ct.isScalar(s)?s.value:s)??void 0}has(e){return!!sn(this.items,e)}set(e,t){this.add(new Bs.Pair(e,t),!0)}toJSON(e,t,n){let s=n?new n:t?.mapAsMap?new Map:{};t?.onCreate&&t.onCreate(s);for(let i of this.items)ev.addPairToJSMap(t,s,i);return s}toString(e,t,n){if(!e)return JSON.stringify(this);for(let s of this.items)if(!ct.isPair(s))throw new Error(`Map items must all be pairs; found ${JSON.stringify(s)} instead`);return!e.allNullValues&&this.hasAllNullValues(!1)&&(e=Object.assign({},e,{allNullValues:!0})),Zw.stringifyCollection(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:n,onComment:t})}};_a.YAMLMap=Ra;_a.findPair=sn});var ar=T(rf=>{"use strict";var nv=F(),tf=lt(),sv={collection:"map",default:!0,nodeClass:tf.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(r,e){return nv.isMap(r)||e("Expected a mapping for this tag"),r},createNode:(r,e,t)=>tf.YAMLMap.from(r,e,t)};rf.map=sv});var ut=T(nf=>{"use strict";var iv=zr(),ov=Ca(),av=Es(),Fs=F(),cv=X(),lv=nt(),Na=class extends av.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(Fs.SEQ,e),this.items=[]}add(e){this.items.push(e)}delete(e){let t=js(e);return typeof t!="number"?!1:this.items.splice(t,1).length>0}get(e,t){let n=js(e);if(typeof n!="number")return;let s=this.items[n];return!t&&Fs.isScalar(s)?s.value:s}has(e){let t=js(e);return typeof t=="number"&&t<this.items.length}set(e,t){let n=js(e);if(typeof n!="number")throw new Error(`Expected a valid index, not ${e}.`);let s=this.items[n];Fs.isScalar(s)&&cv.isScalarValue(t)?s.value=t:this.items[n]=t}toJSON(e,t){let n=[];t?.onCreate&&t.onCreate(n);let s=0;for(let i of this.items)n.push(lv.toJS(i,String(s++),t));return n}toString(e,t,n){return e?ov.stringifyCollection(this,e,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(e.indent||"")+" ",onChompKeep:n,onComment:t}):JSON.stringify(this)}static from(e,t,n){let{replacer:s}=n,i=new this(e);if(t&&Symbol.iterator in Object(t)){let o=0;for(let a of t){if(typeof s=="function"){let c=t instanceof Set?a:String(o++);a=s.call(t,c,a)}i.items.push(iv.createNode(a,void 0,n))}}return i}};function js(r){let e=Fs.isScalar(r)?r.value:r;return e&&typeof e=="string"&&(e=Number(e)),typeof e=="number"&&Number.isInteger(e)&&e>=0?e:null}nf.YAMLSeq=Na});var cr=T(of=>{"use strict";var uv=F(),sf=ut(),dv={collection:"seq",default:!0,nodeClass:sf.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(r,e){return uv.isSeq(r)||e("Expected a sequence for this tag"),r},createNode:(r,e,t)=>sf.YAMLSeq.from(r,e,t)};of.seq=dv});var on=T(af=>{"use strict";var fv=en(),pv={identify:r=>typeof r=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:r=>r,stringify(r,e,t,n){return e=Object.assign({actualString:!0},e),fv.stringifyString(r,e,t,n)}};af.string=pv});var qs=T(uf=>{"use strict";var cf=X(),lf={identify:r=>r==null,createNode:()=>new cf.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new cf.Scalar(null),stringify:({source:r},e)=>typeof r=="string"&&lf.test.test(r)?r:e.options.nullStr};uf.nullTag=lf});var Ia=T(ff=>{"use strict";var mv=X(),df={identify:r=>typeof r=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:r=>new mv.Scalar(r[0]==="t"||r[0]==="T"),stringify({source:r,value:e},t){if(r&&df.test.test(r)){let n=r[0]==="t"||r[0]==="T";if(e===n)return r}return e?t.options.trueStr:t.options.falseStr}};ff.boolTag=df});var lr=T(pf=>{"use strict";function hv({format:r,minFractionDigits:e,tag:t,value:n}){if(typeof n=="bigint")return String(n);let s=typeof n=="number"?n:Number(n);if(!isFinite(s))return isNaN(s)?".nan":s<0?"-.inf":".inf";let i=Object.is(n,-0)?"-0":JSON.stringify(n);if(!r&&e&&(!t||t==="tag:yaml.org,2002:float")&&/^\d/.test(i)){let o=i.indexOf(".");o<0&&(o=i.length,i+=".");let a=e-(i.length-o-1);for(;a-- >0;)i+="0"}return i}pf.stringifyNumber=hv});var La=T(Us=>{"use strict";var gv=X(),$a=lr(),yv={identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:r=>r.slice(-3).toLowerCase()==="nan"?NaN:r[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:$a.stringifyNumber},bv={identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:r=>parseFloat(r),stringify(r){let e=Number(r.value);return isFinite(e)?e.toExponential():$a.stringifyNumber(r)}},wv={identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(r){let e=new gv.Scalar(parseFloat(r)),t=r.indexOf(".");return t!==-1&&r[r.length-1]==="0"&&(e.minFractionDigits=r.length-t-1),e},stringify:$a.stringifyNumber};Us.float=wv;Us.floatExp=bv;Us.floatNaN=yv});var Da=T(Ks=>{"use strict";var mf=lr(),Js=r=>typeof r=="bigint"||Number.isInteger(r),Ma=(r,e,t,{intAsBigInt:n})=>n?BigInt(r):parseInt(r.substring(e),t);function hf(r,e,t){let{value:n}=r;return Js(n)&&n>=0?t+n.toString(e):mf.stringifyNumber(r)}var vv={identify:r=>Js(r)&&r>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(r,e,t)=>Ma(r,2,8,t),stringify:r=>hf(r,8,"0o")},Sv={identify:Js,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(r,e,t)=>Ma(r,0,10,t),stringify:mf.stringifyNumber},kv={identify:r=>Js(r)&&r>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(r,e,t)=>Ma(r,2,16,t),stringify:r=>hf(r,16,"0x")};Ks.int=Sv;Ks.intHex=kv;Ks.intOct=vv});var yf=T(gf=>{"use strict";var xv=ar(),Ev=qs(),Av=cr(),Tv=on(),Pv=Ia(),Ba=La(),ja=Da(),Ov=[xv.map,Av.seq,Tv.string,Ev.nullTag,Pv.boolTag,ja.intOct,ja.int,ja.intHex,Ba.floatNaN,Ba.floatExp,Ba.float];gf.schema=Ov});var vf=T(wf=>{"use strict";var Cv=X(),Rv=ar(),_v=cr();function bf(r){return typeof r=="bigint"||Number.isInteger(r)}var Hs=({value:r})=>JSON.stringify(r),Nv=[{identify:r=>typeof r=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:r=>r,stringify:Hs},{identify:r=>r==null,createNode:()=>new Cv.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:Hs},{identify:r=>typeof r=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:r=>r==="true",stringify:Hs},{identify:bf,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(r,e,{intAsBigInt:t})=>t?BigInt(r):parseInt(r,10),stringify:({value:r})=>bf(r)?r.toString():JSON.stringify(r)},{identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:r=>parseFloat(r),stringify:Hs}],Iv={default:!0,tag:"",test:/^/,resolve(r,e){return e(`Unresolved plain scalar ${JSON.stringify(r)}`),r}},$v=[Rv.map,_v.seq].concat(Nv,Iv);wf.schema=$v});var qa=T(Sf=>{"use strict";var an=us("buffer"),Fa=X(),Lv=en(),Mv={identify:r=>r instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(r,e){if(typeof an.Buffer=="function")return an.Buffer.from(r,"base64");if(typeof atob=="function"){let t=atob(r.replace(/[\n\r]/g,"")),n=new Uint8Array(t.length);for(let s=0;s<t.length;++s)n[s]=t.charCodeAt(s);return n}else return e("This environment does not support reading binary tags; either Buffer or atob is required"),r},stringify({comment:r,type:e,value:t},n,s,i){if(!t)return"";let o=t,a;if(typeof an.Buffer=="function")a=o instanceof an.Buffer?o.toString("base64"):an.Buffer.from(o.buffer).toString("base64");else if(typeof btoa=="function"){let c="";for(let l=0;l<o.length;++l)c+=String.fromCharCode(o[l]);a=btoa(c)}else throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");if(e??(e=Fa.Scalar.BLOCK_LITERAL),e!==Fa.Scalar.QUOTE_DOUBLE){let c=Math.max(n.options.lineWidth-n.indent.length,n.options.minContentWidth),l=Math.ceil(a.length/c),f=new Array(l);for(let u=0,d=0;u<l;++u,d+=c)f[u]=a.substr(d,c);a=f.join(e===Fa.Scalar.BLOCK_LITERAL?`
|
|
69
|
+
`:" ")}return Lv.stringifyString({comment:r,type:e,value:a},n,s,i)}};Sf.binary=Mv});var Vs=T(Ys=>{"use strict";var Ws=F(),Ua=at(),Dv=X(),Bv=ut();function kf(r,e){if(Ws.isSeq(r))for(let t=0;t<r.items.length;++t){let n=r.items[t];if(!Ws.isPair(n)){if(Ws.isMap(n)){n.items.length>1&&e("Each pair must have its own sequence indicator");let s=n.items[0]||new Ua.Pair(new Dv.Scalar(null));if(n.commentBefore&&(s.key.commentBefore=s.key.commentBefore?`${n.commentBefore}
|
|
70
70
|
${s.key.commentBefore}`:n.commentBefore),n.comment){let i=s.value??s.key;i.comment=i.comment?`${n.comment}
|
|
71
|
-
${i.comment}`:n.comment}n=s}r.items[t]=Ks.isPair(n)?n:new Ba.Pair(n)}}else e("Expected a sequence for this tag");return r}function pd(r,e,t){let{replacer:n}=t,s=new Av.YAMLSeq(r);s.tag="tag:yaml.org,2002:pairs";let i=0;if(e&&Symbol.iterator in Object(e))for(let o of e){typeof n=="function"&&(o=n.call(e,String(i++),o));let a,c;if(Array.isArray(o))if(o.length===2)a=o[0],c=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){let l=Object.keys(o);if(l.length===1)a=l[0],c=o[a];else throw new TypeError(`Expected tuple with one key, not ${l.length} keys`)}else a=o;s.items.push(Ba.createPair(a,c,t))}return s}var Tv={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:dd,createNode:pd};Hs.createPairs=pd;Hs.pairs=Tv;Hs.resolvePairs=dd});var qa=T(Fa=>{"use strict";var md=F(),ja=nt(),cn=lt(),Pv=ut(),hd=Ws(),It=class r extends Pv.YAMLSeq{constructor(){super(),this.add=cn.YAMLMap.prototype.add.bind(this),this.delete=cn.YAMLMap.prototype.delete.bind(this),this.get=cn.YAMLMap.prototype.get.bind(this),this.has=cn.YAMLMap.prototype.has.bind(this),this.set=cn.YAMLMap.prototype.set.bind(this),this.tag=r.tag}toJSON(e,t){if(!t)return super.toJSON(e);let n=new Map;t?.onCreate&&t.onCreate(n);for(let s of this.items){let i,o;if(md.isPair(s)?(i=ja.toJS(s.key,"",t),o=ja.toJS(s.value,i,t)):i=ja.toJS(s,"",t),n.has(i))throw new Error("Ordered maps must not include duplicate keys");n.set(i,o)}return n}static from(e,t,n){let s=hd.createPairs(e,t,n),i=new this;return i.items=s.items,i}};It.tag="tag:yaml.org,2002:omap";var Ov={collection:"seq",identify:r=>r instanceof Map,nodeClass:It,default:!1,tag:"tag:yaml.org,2002:omap",resolve(r,e){let t=hd.resolvePairs(r,e),n=[];for(let{key:s}of t.items)md.isScalar(s)&&(n.includes(s.value)?e(`Ordered maps must not include duplicate keys: ${s.value}`):n.push(s.value));return Object.assign(new It,t)},createNode:(r,e,t)=>It.from(r,e,t)};Fa.YAMLOMap=It;Fa.omap=Ov});var vd=T(Ua=>{"use strict";var gd=X();function yd({value:r,source:e},t){return e&&(r?bd:wd).test.test(e)?e:r?t.options.trueStr:t.options.falseStr}var bd={identify:r=>r===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new gd.Scalar(!0),stringify:yd},wd={identify:r=>r===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new gd.Scalar(!1),stringify:yd};Ua.falseTag=wd;Ua.trueTag=bd});var Sd=T(Ys=>{"use strict";var Cv=X(),Ja=ur(),_v={identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:r=>r.slice(-3).toLowerCase()==="nan"?NaN:r[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:Ja.stringifyNumber},Rv={identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:r=>parseFloat(r.replace(/_/g,"")),stringify(r){let e=Number(r.value);return isFinite(e)?e.toExponential():Ja.stringifyNumber(r)}},Nv={identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(r){let e=new Cv.Scalar(parseFloat(r.replace(/_/g,""))),t=r.indexOf(".");if(t!==-1){let n=r.substring(t+1).replace(/_/g,"");n[n.length-1]==="0"&&(e.minFractionDigits=n.length)}return e},stringify:Ja.stringifyNumber};Ys.float=Nv;Ys.floatExp=Rv;Ys.floatNaN=_v});var xd=T(un=>{"use strict";var kd=ur(),ln=r=>typeof r=="bigint"||Number.isInteger(r);function Vs(r,e,t,{intAsBigInt:n}){let s=r[0];if((s==="-"||s==="+")&&(e+=1),r=r.substring(e).replace(/_/g,""),n){switch(t){case 2:r=`0b${r}`;break;case 8:r=`0o${r}`;break;case 16:r=`0x${r}`;break}let o=BigInt(r);return s==="-"?BigInt(-1)*o:o}let i=parseInt(r,t);return s==="-"?-1*i:i}function Ka(r,e,t){let{value:n}=r;if(ln(n)){let s=n.toString(e);return n<0?"-"+t+s.substr(1):t+s}return kd.stringifyNumber(r)}var Iv={identify:ln,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(r,e,t)=>Vs(r,2,2,t),stringify:r=>Ka(r,2,"0b")},$v={identify:ln,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(r,e,t)=>Vs(r,1,8,t),stringify:r=>Ka(r,8,"0")},Lv={identify:ln,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(r,e,t)=>Vs(r,0,10,t),stringify:kd.stringifyNumber},Mv={identify:ln,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(r,e,t)=>Vs(r,2,16,t),stringify:r=>Ka(r,16,"0x")};un.int=Lv;un.intBin=Iv;un.intHex=Mv;un.intOct=$v});var Wa=T(Ha=>{"use strict";var Xs=F(),Gs=at(),zs=lt(),$t=class r extends zs.YAMLMap{constructor(e){super(e),this.tag=r.tag}add(e){let t;Xs.isPair(e)?t=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?t=new Gs.Pair(e.key,null):t=new Gs.Pair(e,null),zs.findPair(this.items,t.key)||this.items.push(t)}get(e,t){let n=zs.findPair(this.items,e);return!t&&Xs.isPair(n)?Xs.isScalar(n.key)?n.key.value:n.key:n}set(e,t){if(typeof t!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof t}`);let n=zs.findPair(this.items,e);n&&!t?this.items.splice(this.items.indexOf(n),1):!n&&t&&this.items.push(new Gs.Pair(e))}toJSON(e,t){return super.toJSON(e,t,Set)}toString(e,t,n){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),t,n);throw new Error("Set items must all have null values")}static from(e,t,n){let{replacer:s}=n,i=new this(e);if(t&&Symbol.iterator in Object(t))for(let o of t)typeof s=="function"&&(o=s.call(t,o,o)),i.items.push(Gs.createPair(o,null,n));return i}};$t.tag="tag:yaml.org,2002:set";var Dv={collection:"map",identify:r=>r instanceof Set,nodeClass:$t,default:!1,tag:"tag:yaml.org,2002:set",createNode:(r,e,t)=>$t.from(r,e,t),resolve(r,e){if(Xs.isMap(r)){if(r.hasAllNullValues(!0))return Object.assign(new $t,r);e("Set items must all have null values")}else e("Expected a mapping for this tag");return r}};Ha.YAMLSet=$t;Ha.set=Dv});var Va=T(Qs=>{"use strict";var Bv=ur();function Ya(r,e){let t=r[0],n=t==="-"||t==="+"?r.substring(1):r,s=o=>e?BigInt(o):Number(o),i=n.replace(/_/g,"").split(":").reduce((o,a)=>o*s(60)+s(a),s(0));return t==="-"?s(-1)*i:i}function Ed(r){let{value:e}=r,t=o=>o;if(typeof e=="bigint")t=o=>BigInt(o);else if(isNaN(e)||!isFinite(e))return Bv.stringifyNumber(r);let n="";e<0&&(n="-",e*=t(-1));let s=t(60),i=[e%s];return e<60?i.unshift(0):(e=(e-i[0])/s,i.unshift(e%s),e>=60&&(e=(e-i[0])/s,i.unshift(e))),n+i.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var jv={identify:r=>typeof r=="bigint"||Number.isInteger(r),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(r,e,{intAsBigInt:t})=>Ya(r,t),stringify:Ed},Fv={identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:r=>Ya(r,!1),stringify:Ed},Ad={identify:r=>r instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(r){let e=r.match(Ad.test);if(!e)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,t,n,s,i,o,a]=e.map(Number),c=e[7]?Number((e[7]+"00").substr(1,3)):0,l=Date.UTC(t,n-1,s,i||0,o||0,a||0,c),d=e[8];if(d&&d!=="Z"){let u=Ya(d,!1);Math.abs(u)<30&&(u*=60),l-=6e4*u}return new Date(l)},stringify:({value:r})=>r?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};Qs.floatTime=Fv;Qs.intTime=jv;Qs.timestamp=Ad});var Od=T(Pd=>{"use strict";var qv=cr(),Uv=js(),Jv=lr(),Kv=on(),Hv=Da(),Td=vd(),Ga=Sd(),Zs=xd(),Wv=Rs(),Yv=qa(),Vv=Ws(),Gv=Wa(),za=Va(),zv=[qv.map,Jv.seq,Kv.string,Uv.nullTag,Td.trueTag,Td.falseTag,Zs.intBin,Zs.intOct,Zs.int,Zs.intHex,Ga.floatNaN,Ga.floatExp,Ga.float,Hv.binary,Wv.merge,Yv.omap,Vv.pairs,Gv.set,za.intTime,za.floatTime,za.timestamp];Pd.schema=zv});var Bd=T(Za=>{"use strict";var Nd=cr(),Xv=js(),Id=lr(),Qv=on(),Zv=Ca(),Xa=Ra(),Qa=Ia(),eS=ad(),tS=ud(),$d=Da(),fn=Rs(),Ld=qa(),Md=Ws(),Cd=Od(),Dd=Wa(),ei=Va(),_d=new Map([["core",eS.schema],["failsafe",[Nd.map,Id.seq,Qv.string]],["json",tS.schema],["yaml11",Cd.schema],["yaml-1.1",Cd.schema]]),Rd={binary:$d.binary,bool:Zv.boolTag,float:Xa.float,floatExp:Xa.floatExp,floatNaN:Xa.floatNaN,floatTime:ei.floatTime,int:Qa.int,intHex:Qa.intHex,intOct:Qa.intOct,intTime:ei.intTime,map:Nd.map,merge:fn.merge,null:Xv.nullTag,omap:Ld.omap,pairs:Md.pairs,seq:Id.seq,set:Dd.set,timestamp:ei.timestamp},rS={"tag:yaml.org,2002:binary":$d.binary,"tag:yaml.org,2002:merge":fn.merge,"tag:yaml.org,2002:omap":Ld.omap,"tag:yaml.org,2002:pairs":Md.pairs,"tag:yaml.org,2002:set":Dd.set,"tag:yaml.org,2002:timestamp":ei.timestamp};function nS(r,e,t){let n=_d.get(e);if(n&&!r)return t&&!n.includes(fn.merge)?n.concat(fn.merge):n.slice();let s=n;if(!s)if(Array.isArray(r))s=[];else{let i=Array.from(_d.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${e}"; use one of ${i} or define customTags array`)}if(Array.isArray(r))for(let i of r)s=s.concat(i);else typeof r=="function"&&(s=r(s.slice()));return t&&(s=s.concat(fn.merge)),s.reduce((i,o)=>{let a=typeof o=="string"?Rd[o]:o;if(!a){let c=JSON.stringify(o),l=Object.keys(Rd).map(d=>JSON.stringify(d)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return i.includes(a)||i.push(a),i},[])}Za.coreKnownTags=rS;Za.getTags=nS});var rc=T(jd=>{"use strict";var ec=F(),sS=cr(),iS=lr(),oS=on(),ti=Bd(),aS=(r,e)=>r.key<e.key?-1:r.key>e.key?1:0,tc=class r{constructor({compat:e,customTags:t,merge:n,resolveKnownTags:s,schema:i,sortMapEntries:o,toStringDefaults:a}){this.compat=Array.isArray(e)?ti.getTags(e,"compat"):e?ti.getTags(null,e):null,this.name=typeof i=="string"&&i||"core",this.knownTags=s?ti.coreKnownTags:{},this.tags=ti.getTags(t,this.name,n),this.toStringOptions=a??null,Object.defineProperty(this,ec.MAP,{value:sS.map}),Object.defineProperty(this,ec.SCALAR,{value:oS.string}),Object.defineProperty(this,ec.SEQ,{value:iS.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?aS:null}clone(){let e=Object.create(r.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}};jd.Schema=tc});var qd=T(Fd=>{"use strict";var cS=F(),nc=tn(),dn=Xr();function lS(r,e){let t=[],n=e.directives===!0;if(e.directives!==!1&&r.directives){let c=r.directives.toString(r);c?(t.push(c),n=!0):r.directives.docStart&&(n=!0)}n&&t.push("---");let s=nc.createStringifyContext(r,e),{commentString:i}=s.options;if(r.commentBefore){t.length!==1&&t.unshift("");let c=i(r.commentBefore);t.unshift(dn.indentComment(c,""))}let o=!1,a=null;if(r.contents){if(cS.isNode(r.contents)){if(r.contents.spaceBefore&&n&&t.push(""),r.contents.commentBefore){let d=i(r.contents.commentBefore);t.push(dn.indentComment(d,""))}s.forceBlockIndent=!!r.comment,a=r.contents.comment}let c=a?void 0:()=>o=!0,l=nc.stringify(r.contents,s,()=>a=null,c);a&&(l+=dn.lineComment(l,"",i(a))),(l[0]==="|"||l[0]===">")&&t[t.length-1]==="---"?t[t.length-1]=`--- ${l}`:t.push(l)}else t.push(nc.stringify(r.contents,s));if(r.directives?.docEnd)if(r.comment){let c=i(r.comment);c.includes(`
|
|
72
|
-
`)?(t.push("..."),t.push(
|
|
71
|
+
${i.comment}`:n.comment}n=s}r.items[t]=Ws.isPair(n)?n:new Ua.Pair(n)}}else e("Expected a sequence for this tag");return r}function xf(r,e,t){let{replacer:n}=t,s=new Bv.YAMLSeq(r);s.tag="tag:yaml.org,2002:pairs";let i=0;if(e&&Symbol.iterator in Object(e))for(let o of e){typeof n=="function"&&(o=n.call(e,String(i++),o));let a,c;if(Array.isArray(o))if(o.length===2)a=o[0],c=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){let l=Object.keys(o);if(l.length===1)a=l[0],c=o[a];else throw new TypeError(`Expected tuple with one key, not ${l.length} keys`)}else a=o;s.items.push(Ua.createPair(a,c,t))}return s}var jv={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:kf,createNode:xf};Ys.createPairs=xf;Ys.pairs=jv;Ys.resolvePairs=kf});var Ha=T(Ka=>{"use strict";var Ef=F(),Ja=nt(),cn=lt(),Fv=ut(),Af=Vs(),Nt=class r extends Fv.YAMLSeq{constructor(){super(),this.add=cn.YAMLMap.prototype.add.bind(this),this.delete=cn.YAMLMap.prototype.delete.bind(this),this.get=cn.YAMLMap.prototype.get.bind(this),this.has=cn.YAMLMap.prototype.has.bind(this),this.set=cn.YAMLMap.prototype.set.bind(this),this.tag=r.tag}toJSON(e,t){if(!t)return super.toJSON(e);let n=new Map;t?.onCreate&&t.onCreate(n);for(let s of this.items){let i,o;if(Ef.isPair(s)?(i=Ja.toJS(s.key,"",t),o=Ja.toJS(s.value,i,t)):i=Ja.toJS(s,"",t),n.has(i))throw new Error("Ordered maps must not include duplicate keys");n.set(i,o)}return n}static from(e,t,n){let s=Af.createPairs(e,t,n),i=new this;return i.items=s.items,i}};Nt.tag="tag:yaml.org,2002:omap";var qv={collection:"seq",identify:r=>r instanceof Map,nodeClass:Nt,default:!1,tag:"tag:yaml.org,2002:omap",resolve(r,e){let t=Af.resolvePairs(r,e),n=[];for(let{key:s}of t.items)Ef.isScalar(s)&&(n.includes(s.value)?e(`Ordered maps must not include duplicate keys: ${s.value}`):n.push(s.value));return Object.assign(new Nt,t)},createNode:(r,e,t)=>Nt.from(r,e,t)};Ka.YAMLOMap=Nt;Ka.omap=qv});var Rf=T(Wa=>{"use strict";var Tf=X();function Pf({value:r,source:e},t){return e&&(r?Of:Cf).test.test(e)?e:r?t.options.trueStr:t.options.falseStr}var Of={identify:r=>r===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new Tf.Scalar(!0),stringify:Pf},Cf={identify:r=>r===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new Tf.Scalar(!1),stringify:Pf};Wa.falseTag=Cf;Wa.trueTag=Of});var _f=T(Gs=>{"use strict";var Uv=X(),Ya=lr(),Jv={identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:r=>r.slice(-3).toLowerCase()==="nan"?NaN:r[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:Ya.stringifyNumber},Kv={identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:r=>parseFloat(r.replace(/_/g,"")),stringify(r){let e=Number(r.value);return isFinite(e)?e.toExponential():Ya.stringifyNumber(r)}},Hv={identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(r){let e=new Uv.Scalar(parseFloat(r.replace(/_/g,""))),t=r.indexOf(".");if(t!==-1){let n=r.substring(t+1).replace(/_/g,"");n[n.length-1]==="0"&&(e.minFractionDigits=n.length)}return e},stringify:Ya.stringifyNumber};Gs.float=Hv;Gs.floatExp=Kv;Gs.floatNaN=Jv});var If=T(un=>{"use strict";var Nf=lr(),ln=r=>typeof r=="bigint"||Number.isInteger(r);function zs(r,e,t,{intAsBigInt:n}){let s=r[0];if((s==="-"||s==="+")&&(e+=1),r=r.substring(e).replace(/_/g,""),n){switch(t){case 2:r=`0b${r}`;break;case 8:r=`0o${r}`;break;case 16:r=`0x${r}`;break}let o=BigInt(r);return s==="-"?BigInt(-1)*o:o}let i=parseInt(r,t);return s==="-"?-1*i:i}function Va(r,e,t){let{value:n}=r;if(ln(n)){let s=n.toString(e);return n<0?"-"+t+s.substr(1):t+s}return Nf.stringifyNumber(r)}var Wv={identify:ln,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(r,e,t)=>zs(r,2,2,t),stringify:r=>Va(r,2,"0b")},Yv={identify:ln,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(r,e,t)=>zs(r,1,8,t),stringify:r=>Va(r,8,"0")},Vv={identify:ln,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(r,e,t)=>zs(r,0,10,t),stringify:Nf.stringifyNumber},Gv={identify:ln,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(r,e,t)=>zs(r,2,16,t),stringify:r=>Va(r,16,"0x")};un.int=Vv;un.intBin=Wv;un.intHex=Gv;un.intOct=Yv});var za=T(Ga=>{"use strict";var Zs=F(),Xs=at(),Qs=lt(),It=class r extends Qs.YAMLMap{constructor(e){super(e),this.tag=r.tag}add(e){let t;Zs.isPair(e)?t=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?t=new Xs.Pair(e.key,null):t=new Xs.Pair(e,null),Qs.findPair(this.items,t.key)||this.items.push(t)}get(e,t){let n=Qs.findPair(this.items,e);return!t&&Zs.isPair(n)?Zs.isScalar(n.key)?n.key.value:n.key:n}set(e,t){if(typeof t!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof t}`);let n=Qs.findPair(this.items,e);n&&!t?this.items.splice(this.items.indexOf(n),1):!n&&t&&this.items.push(new Xs.Pair(e))}toJSON(e,t){return super.toJSON(e,t,Set)}toString(e,t,n){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),t,n);throw new Error("Set items must all have null values")}static from(e,t,n){let{replacer:s}=n,i=new this(e);if(t&&Symbol.iterator in Object(t))for(let o of t)typeof s=="function"&&(o=s.call(t,o,o)),i.items.push(Xs.createPair(o,null,n));return i}};It.tag="tag:yaml.org,2002:set";var zv={collection:"map",identify:r=>r instanceof Set,nodeClass:It,default:!1,tag:"tag:yaml.org,2002:set",createNode:(r,e,t)=>It.from(r,e,t),resolve(r,e){if(Zs.isMap(r)){if(r.hasAllNullValues(!0))return Object.assign(new It,r);e("Set items must all have null values")}else e("Expected a mapping for this tag");return r}};Ga.YAMLSet=It;Ga.set=zv});var Qa=T(ei=>{"use strict";var Xv=lr();function Xa(r,e){let t=r[0],n=t==="-"||t==="+"?r.substring(1):r,s=o=>e?BigInt(o):Number(o),i=n.replace(/_/g,"").split(":").reduce((o,a)=>o*s(60)+s(a),s(0));return t==="-"?s(-1)*i:i}function $f(r){let{value:e}=r,t=o=>o;if(typeof e=="bigint")t=o=>BigInt(o);else if(isNaN(e)||!isFinite(e))return Xv.stringifyNumber(r);let n="";e<0&&(n="-",e*=t(-1));let s=t(60),i=[e%s];return e<60?i.unshift(0):(e=(e-i[0])/s,i.unshift(e%s),e>=60&&(e=(e-i[0])/s,i.unshift(e))),n+i.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var Qv={identify:r=>typeof r=="bigint"||Number.isInteger(r),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(r,e,{intAsBigInt:t})=>Xa(r,t),stringify:$f},Zv={identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:r=>Xa(r,!1),stringify:$f},Lf={identify:r=>r instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(r){let e=r.match(Lf.test);if(!e)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,t,n,s,i,o,a]=e.map(Number),c=e[7]?Number((e[7]+"00").substr(1,3)):0,l=Date.UTC(t,n-1,s,i||0,o||0,a||0,c),f=e[8];if(f&&f!=="Z"){let u=Xa(f,!1);Math.abs(u)<30&&(u*=60),l-=6e4*u}return new Date(l)},stringify:({value:r})=>r?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};ei.floatTime=Zv;ei.intTime=Qv;ei.timestamp=Lf});var Bf=T(Df=>{"use strict";var eS=ar(),tS=qs(),rS=cr(),nS=on(),sS=qa(),Mf=Rf(),Za=_f(),ti=If(),iS=Is(),oS=Ha(),aS=Vs(),cS=za(),ec=Qa(),lS=[eS.map,rS.seq,nS.string,tS.nullTag,Mf.trueTag,Mf.falseTag,ti.intBin,ti.intOct,ti.int,ti.intHex,Za.floatNaN,Za.floatExp,Za.float,sS.binary,iS.merge,oS.omap,aS.pairs,cS.set,ec.intTime,ec.floatTime,ec.timestamp];Df.schema=lS});var Vf=T(nc=>{"use strict";var Uf=ar(),uS=qs(),Jf=cr(),dS=on(),fS=Ia(),tc=La(),rc=Da(),pS=yf(),mS=vf(),Kf=qa(),dn=Is(),Hf=Ha(),Wf=Vs(),jf=Bf(),Yf=za(),ri=Qa(),Ff=new Map([["core",pS.schema],["failsafe",[Uf.map,Jf.seq,dS.string]],["json",mS.schema],["yaml11",jf.schema],["yaml-1.1",jf.schema]]),qf={binary:Kf.binary,bool:fS.boolTag,float:tc.float,floatExp:tc.floatExp,floatNaN:tc.floatNaN,floatTime:ri.floatTime,int:rc.int,intHex:rc.intHex,intOct:rc.intOct,intTime:ri.intTime,map:Uf.map,merge:dn.merge,null:uS.nullTag,omap:Hf.omap,pairs:Wf.pairs,seq:Jf.seq,set:Yf.set,timestamp:ri.timestamp},hS={"tag:yaml.org,2002:binary":Kf.binary,"tag:yaml.org,2002:merge":dn.merge,"tag:yaml.org,2002:omap":Hf.omap,"tag:yaml.org,2002:pairs":Wf.pairs,"tag:yaml.org,2002:set":Yf.set,"tag:yaml.org,2002:timestamp":ri.timestamp};function gS(r,e,t){let n=Ff.get(e);if(n&&!r)return t&&!n.includes(dn.merge)?n.concat(dn.merge):n.slice();let s=n;if(!s)if(Array.isArray(r))s=[];else{let i=Array.from(Ff.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${e}"; use one of ${i} or define customTags array`)}if(Array.isArray(r))for(let i of r)s=s.concat(i);else typeof r=="function"&&(s=r(s.slice()));return t&&(s=s.concat(dn.merge)),s.reduce((i,o)=>{let a=typeof o=="string"?qf[o]:o;if(!a){let c=JSON.stringify(o),l=Object.keys(qf).map(f=>JSON.stringify(f)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return i.includes(a)||i.push(a),i},[])}nc.coreKnownTags=hS;nc.getTags=gS});var oc=T(Gf=>{"use strict";var sc=F(),yS=ar(),bS=cr(),wS=on(),ni=Vf(),vS=(r,e)=>r.key<e.key?-1:r.key>e.key?1:0,ic=class r{constructor({compat:e,customTags:t,merge:n,resolveKnownTags:s,schema:i,sortMapEntries:o,toStringDefaults:a}){this.compat=Array.isArray(e)?ni.getTags(e,"compat"):e?ni.getTags(null,e):null,this.name=typeof i=="string"&&i||"core",this.knownTags=s?ni.coreKnownTags:{},this.tags=ni.getTags(t,this.name,n),this.toStringOptions=a??null,Object.defineProperty(this,sc.MAP,{value:yS.map}),Object.defineProperty(this,sc.SCALAR,{value:wS.string}),Object.defineProperty(this,sc.SEQ,{value:bS.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?vS:null}clone(){let e=Object.create(r.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}};Gf.Schema=ic});var Xf=T(zf=>{"use strict";var SS=F(),ac=tn(),fn=Xr();function kS(r,e){let t=[],n=e.directives===!0;if(e.directives!==!1&&r.directives){let c=r.directives.toString(r);c?(t.push(c),n=!0):r.directives.docStart&&(n=!0)}n&&t.push("---");let s=ac.createStringifyContext(r,e),{commentString:i}=s.options;if(r.commentBefore){t.length!==1&&t.unshift("");let c=i(r.commentBefore);t.unshift(fn.indentComment(c,""))}let o=!1,a=null;if(r.contents){if(SS.isNode(r.contents)){if(r.contents.spaceBefore&&n&&t.push(""),r.contents.commentBefore){let f=i(r.contents.commentBefore);t.push(fn.indentComment(f,""))}s.forceBlockIndent=!!r.comment,a=r.contents.comment}let c=a?void 0:()=>o=!0,l=ac.stringify(r.contents,s,()=>a=null,c);a&&(l+=fn.lineComment(l,"",i(a))),(l[0]==="|"||l[0]===">")&&t[t.length-1]==="---"?t[t.length-1]=`--- ${l}`:t.push(l)}else t.push(ac.stringify(r.contents,s));if(r.directives?.docEnd)if(r.comment){let c=i(r.comment);c.includes(`
|
|
72
|
+
`)?(t.push("..."),t.push(fn.indentComment(c,""))):t.push(`... ${c}`)}else t.push("...");else{let c=r.comment;c&&o&&(c=c.replace(/^\n+/,"")),c&&((!o||a)&&t[t.length-1]!==""&&t.push(""),t.push(fn.indentComment(i(c),"")))}return t.join(`
|
|
73
73
|
`)+`
|
|
74
|
-
`}
|
|
74
|
+
`}zf.stringifyDocument=kS});var pn=T(Qf=>{"use strict";var xS=Gr(),ur=Es(),me=F(),ES=at(),AS=nt(),TS=oc(),PS=Xf(),cc=vs(),OS=fa(),CS=zr(),lc=da(),uc=class r{constructor(e,t,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,me.NODE_TYPE,{value:me.DOC});let s=null;typeof t=="function"||Array.isArray(t)?s=t:n===void 0&&t&&(n=t,t=void 0);let i=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},n);this.options=i;let{version:o}=i;n?._directives?(this.directives=n._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new lc.Directives({version:o}),this.setSchema(o,n),this.contents=e===void 0?null:this.createNode(e,s,n)}clone(){let e=Object.create(r.prototype,{[me.NODE_TYPE]:{value:me.DOC}});return e.commentBefore=this.commentBefore,e.comment=this.comment,e.errors=this.errors.slice(),e.warnings=this.warnings.slice(),e.options=Object.assign({},this.options),this.directives&&(e.directives=this.directives.clone()),e.schema=this.schema.clone(),e.contents=me.isNode(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){dr(this.contents)&&this.contents.add(e)}addIn(e,t){dr(this.contents)&&this.contents.addIn(e,t)}createAlias(e,t){if(!e.anchor){let n=cc.anchorNames(this);e.anchor=!t||n.has(t)?cc.findNewAnchor(t||"a",n):t}return new xS.Alias(e.anchor)}createNode(e,t,n){let s;if(typeof t=="function")e=t.call({"":e},"",e),s=t;else if(Array.isArray(t)){let g=A=>typeof A=="number"||A instanceof String||A instanceof Number,x=t.filter(g).map(String);x.length>0&&(t=t.concat(x)),s=t}else n===void 0&&t&&(n=t,t=void 0);let{aliasDuplicateObjects:i,anchorPrefix:o,flow:a,keepUndefined:c,onTagObj:l,tag:f}=n??{},{onAnchor:u,setAnchors:d,sourceObjects:p}=cc.createNodeAnchors(this,o||"a"),b={aliasDuplicateObjects:i??!0,keepUndefined:c??!1,onAnchor:u,onTagObj:l,replacer:s,schema:this.schema,sourceObjects:p},m=CS.createNode(e,f,b);return a&&me.isCollection(m)&&(m.flow=!0),d(),m}createPair(e,t,n={}){let s=this.createNode(e,null,n),i=this.createNode(t,null,n);return new ES.Pair(s,i)}delete(e){return dr(this.contents)?this.contents.delete(e):!1}deleteIn(e){return ur.isEmptyPath(e)?this.contents==null?!1:(this.contents=null,!0):dr(this.contents)?this.contents.deleteIn(e):!1}get(e,t){return me.isCollection(this.contents)?this.contents.get(e,t):void 0}getIn(e,t){return ur.isEmptyPath(e)?!t&&me.isScalar(this.contents)?this.contents.value:this.contents:me.isCollection(this.contents)?this.contents.getIn(e,t):void 0}has(e){return me.isCollection(this.contents)?this.contents.has(e):!1}hasIn(e){return ur.isEmptyPath(e)?this.contents!==void 0:me.isCollection(this.contents)?this.contents.hasIn(e):!1}set(e,t){this.contents==null?this.contents=ur.collectionFromPath(this.schema,[e],t):dr(this.contents)&&this.contents.set(e,t)}setIn(e,t){ur.isEmptyPath(e)?this.contents=t:this.contents==null?this.contents=ur.collectionFromPath(this.schema,Array.from(e),t):dr(this.contents)&&this.contents.setIn(e,t)}setSchema(e,t={}){typeof e=="number"&&(e=String(e));let n;switch(e){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new lc.Directives({version:"1.1"}),n={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=e:this.directives=new lc.Directives({version:e}),n={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,n=null;break;default:{let s=JSON.stringify(e);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${s}`)}}if(t.schema instanceof Object)this.schema=t.schema;else if(n)this.schema=new TS.Schema(Object.assign(n,t));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:e,jsonArg:t,mapAsMap:n,maxAliasCount:s,onAnchor:i,reviver:o}={}){let a={anchors:new Map,doc:this,keep:!e,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof s=="number"?s:100},c=AS.toJS(this.contents,t??"",a);if(typeof i=="function")for(let{count:l,res:f}of a.anchors.values())i(f,l);return typeof o=="function"?OS.applyReviver(o,{"":c},"",c):c}toJSON(e,t){return this.toJS({json:!0,jsonArg:e,mapAsMap:!1,onAnchor:t})}toString(e={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in e&&(!Number.isInteger(e.indent)||Number(e.indent)<=0)){let t=JSON.stringify(e.indent);throw new Error(`"indent" option must be a positive integer, not ${t}`)}return PS.stringifyDocument(this,e)}};function dr(r){if(me.isCollection(r))return!0;throw new Error("Expected a YAML collection as document contents")}Qf.Document=uc});var gn=T(hn=>{"use strict";var mn=class extends Error{constructor(e,t,n,s){super(),this.name=e,this.code=n,this.message=s,this.pos=t}},dc=class extends mn{constructor(e,t,n){super("YAMLParseError",e,t,n)}},fc=class extends mn{constructor(e,t,n){super("YAMLWarning",e,t,n)}},RS=(r,e)=>t=>{if(t.pos[0]===-1)return;t.linePos=t.pos.map(a=>e.linePos(a));let{line:n,col:s}=t.linePos[0];t.message+=` at line ${n}, column ${s}`;let i=s-1,o=r.substring(e.lineStarts[n-1],e.lineStarts[n]).replace(/[\n\r]+$/,"");if(i>=60&&o.length>80){let a=Math.min(i-39,o.length-79);o="\u2026"+o.substring(a),i-=a-1}if(o.length>80&&(o=o.substring(0,79)+"\u2026"),n>1&&/^ *$/.test(o.substring(0,i))){let a=r.substring(e.lineStarts[n-2],e.lineStarts[n-1]);a.length>80&&(a=a.substring(0,79)+`\u2026
|
|
75
75
|
`),o=a+o}if(/[^ ]/.test(o)){let a=1,c=t.linePos[1];c?.line===n&&c.col>s&&(a=Math.max(1,Math.min(c.col-s,80-i)));let l=" ".repeat(i)+"^".repeat(a);t.message+=`:
|
|
76
76
|
|
|
77
77
|
${o}
|
|
78
78
|
${l}
|
|
79
|
-
`}};hn.YAMLError=mn;hn.YAMLParseError=
|
|
80
|
-
`))return!0;if(r.end){for(let e of r.end)if(e.type==="newline")return!0}return!1;case"flow-collection":for(let e of r.items){for(let t of e.start)if(t.type==="newline")return!0;if(e.sep){for(let t of e.sep)if(t.type==="newline")return!0}if(
|
|
81
|
-
`+m.comment:a.comment=m.comment);continue}(m.newlineAfterProp||
|
|
82
|
-
`+P.comment:A.comment=P.comment);let
|
|
83
|
-
`+
|
|
84
|
-
|
|
85
|
-
`+y.comment:E.comment=y.comment);let
|
|
86
|
-
`+g.comment:l.comment=g.comment),l.range=[n.offset,m,g.offset]}else l.range=[n.offset,m,m];return l}
|
|
87
|
-
`.repeat(Math.max(1,o.length-1)):"",g=n+s.length;return e.source&&(g+=e.source.length),{value:m,type:i,comment:s.comment,range:[n,g,g]}}let c=e.indent+s.indent,l=e.offset+s.length,
|
|
88
|
-
`;for(let m=
|
|
89
|
-
`):g.length>c||x[0]===" "?(
|
|
90
|
-
`:!p&&
|
|
91
|
-
`&&(
|
|
92
|
-
|
|
93
|
-
`),u+=
|
|
94
|
-
`,p=!0):x===""?
|
|
79
|
+
`}};hn.YAMLError=mn;hn.YAMLParseError=dc;hn.YAMLWarning=fc;hn.prettifyError=RS});var yn=T(Zf=>{"use strict";function _S(r,{flow:e,indicator:t,next:n,offset:s,onError:i,parentIndent:o,startOnNewline:a}){let c=!1,l=a,f=a,u="",d="",p=!1,b=!1,m=null,g=null,x=null,A=null,P=null,_=null,N=null;for(let E of r)switch(b&&(E.type!=="space"&&E.type!=="newline"&&E.type!=="comma"&&i(E.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),b=!1),m&&(l&&E.type!=="comment"&&E.type!=="newline"&&i(m,"TAB_AS_INDENT","Tabs are not allowed as indentation"),m=null),E.type){case"space":!e&&(t!=="doc-start"||n?.type!=="flow-collection")&&E.source.includes(" ")&&(m=E),f=!0;break;case"comment":{f||i(E,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let y=E.source.substring(1)||" ";u?u+=d+y:u=y,d="",l=!1;break}case"newline":l?u?u+=E.source:(!_||t!=="seq-item-ind")&&(c=!0):d+=E.source,l=!0,p=!0,(g||x)&&(A=E),f=!0;break;case"anchor":g&&i(E,"MULTIPLE_ANCHORS","A node can have at most one anchor"),E.source.endsWith(":")&&i(E.offset+E.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),g=E,N??(N=E.offset),l=!1,f=!1,b=!0;break;case"tag":{x&&i(E,"MULTIPLE_TAGS","A node can have at most one tag"),x=E,N??(N=E.offset),l=!1,f=!1,b=!0;break}case t:(g||x)&&i(E,"BAD_PROP_ORDER",`Anchors and tags must be after the ${E.source} indicator`),_&&i(E,"UNEXPECTED_TOKEN",`Unexpected ${E.source} in ${e??"collection"}`),_=E,l=t==="seq-item-ind"||t==="explicit-key-ind",f=!1;break;case"comma":if(e){P&&i(E,"UNEXPECTED_TOKEN",`Unexpected , in ${e}`),P=E,l=!1,f=!1;break}default:i(E,"UNEXPECTED_TOKEN",`Unexpected ${E.type} token`),l=!1,f=!1}let C=r[r.length-1],I=C?C.offset+C.source.length:s;return b&&n&&n.type!=="space"&&n.type!=="newline"&&n.type!=="comma"&&(n.type!=="scalar"||n.source!=="")&&i(n.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),m&&(l&&m.indent<=o||n?.type==="block-map"||n?.type==="block-seq")&&i(m,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:P,found:_,spaceBefore:c,comment:u,hasNewline:p,anchor:g,tag:x,newlineAfterProp:A,end:I,start:N??I}}Zf.resolveProps=_S});var si=T(ep=>{"use strict";function pc(r){if(!r)return null;switch(r.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(r.source.includes(`
|
|
80
|
+
`))return!0;if(r.end){for(let e of r.end)if(e.type==="newline")return!0}return!1;case"flow-collection":for(let e of r.items){for(let t of e.start)if(t.type==="newline")return!0;if(e.sep){for(let t of e.sep)if(t.type==="newline")return!0}if(pc(e.key)||pc(e.value))return!0}return!1;default:return!0}}ep.containsNewline=pc});var mc=T(tp=>{"use strict";var NS=si();function IS(r,e,t){if(e?.type==="flow-collection"){let n=e.end[0];n.indent===r&&(n.source==="]"||n.source==="}")&&NS.containsNewline(e)&&t(n,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}tp.flowIndentCheck=IS});var hc=T(np=>{"use strict";var rp=F();function $S(r,e,t){let{uniqueKeys:n}=r.options;if(n===!1)return!1;let s=typeof n=="function"?n:(i,o)=>i===o||rp.isScalar(i)&&rp.isScalar(o)&&i.value===o.value;return e.some(i=>s(i.key,t))}np.mapIncludes=$S});var lp=T(cp=>{"use strict";var sp=at(),LS=lt(),ip=yn(),MS=si(),op=mc(),DS=hc(),ap="All mapping items must start at the same column";function BS({composeNode:r,composeEmptyNode:e},t,n,s,i){let o=i?.nodeClass??LS.YAMLMap,a=new o(t.schema);t.atRoot&&(t.atRoot=!1);let c=n.offset,l=null;for(let f of n.items){let{start:u,key:d,sep:p,value:b}=f,m=ip.resolveProps(u,{indicator:"explicit-key-ind",next:d??p?.[0],offset:c,onError:s,parentIndent:n.indent,startOnNewline:!0}),g=!m.found;if(g){if(d&&(d.type==="block-seq"?s(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in d&&d.indent!==n.indent&&s(c,"BAD_INDENT",ap)),!m.anchor&&!m.tag&&!p){l=m.end,m.comment&&(a.comment?a.comment+=`
|
|
81
|
+
`+m.comment:a.comment=m.comment);continue}(m.newlineAfterProp||MS.containsNewline(d))&&s(d??u[u.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else m.found?.indent!==n.indent&&s(c,"BAD_INDENT",ap);t.atKey=!0;let x=m.end,A=d?r(t,d,m,s):e(t,x,u,null,m,s);t.schema.compat&&op.flowIndentCheck(n.indent,d,s),t.atKey=!1,DS.mapIncludes(t,a.items,A)&&s(x,"DUPLICATE_KEY","Map keys must be unique");let P=ip.resolveProps(p??[],{indicator:"map-value-ind",next:b,offset:A.range[2],onError:s,parentIndent:n.indent,startOnNewline:!d||d.type==="block-scalar"});if(c=P.end,P.found){g&&(b?.type==="block-map"&&!P.hasNewline&&s(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),t.options.strict&&m.start<P.found.offset-1024&&s(A.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let _=b?r(t,b,P,s):e(t,c,p,null,P,s);t.schema.compat&&op.flowIndentCheck(n.indent,b,s),c=_.range[2];let N=new sp.Pair(A,_);t.options.keepSourceTokens&&(N.srcToken=f),a.items.push(N)}else{g&&s(A.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),P.comment&&(A.comment?A.comment+=`
|
|
82
|
+
`+P.comment:A.comment=P.comment);let _=new sp.Pair(A);t.options.keepSourceTokens&&(_.srcToken=f),a.items.push(_)}}return l&&l<c&&s(l,"IMPOSSIBLE","Map comment with trailing content"),a.range=[n.offset,c,l??c],a}cp.resolveBlockMap=BS});var dp=T(up=>{"use strict";var jS=ut(),FS=yn(),qS=mc();function US({composeNode:r,composeEmptyNode:e},t,n,s,i){let o=i?.nodeClass??jS.YAMLSeq,a=new o(t.schema);t.atRoot&&(t.atRoot=!1),t.atKey&&(t.atKey=!1);let c=n.offset,l=null;for(let{start:f,value:u}of n.items){let d=FS.resolveProps(f,{indicator:"seq-item-ind",next:u,offset:c,onError:s,parentIndent:n.indent,startOnNewline:!0});if(!d.found)if(d.anchor||d.tag||u)u?.type==="block-seq"?s(d.end,"BAD_INDENT","All sequence items must start at the same column"):s(c,"MISSING_CHAR","Sequence item without - indicator");else{l=d.end,d.comment&&(a.comment=d.comment);continue}let p=u?r(t,u,d,s):e(t,d.end,f,null,d,s);t.schema.compat&&qS.flowIndentCheck(n.indent,u,s),c=p.range[2],a.items.push(p)}return a.range=[n.offset,c,l??c],a}up.resolveBlockSeq=US});var fr=T(fp=>{"use strict";function JS(r,e,t,n){let s="";if(r){let i=!1,o="";for(let a of r){let{source:c,type:l}=a;switch(l){case"space":i=!0;break;case"comment":{t&&!i&&n(a,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let f=c.substring(1)||" ";s?s+=o+f:s=f,o="";break}case"newline":s&&(o+=c),i=!0;break;default:n(a,"UNEXPECTED_TOKEN",`Unexpected ${l} at node end`)}e+=c.length}}return{comment:s,offset:e}}fp.resolveEnd=JS});var gp=T(hp=>{"use strict";var KS=F(),HS=at(),pp=lt(),WS=ut(),YS=fr(),mp=yn(),VS=si(),GS=hc(),gc="Block collections are not allowed within flow collections",yc=r=>r&&(r.type==="block-map"||r.type==="block-seq");function zS({composeNode:r,composeEmptyNode:e},t,n,s,i){let o=n.start.source==="{",a=o?"flow map":"flow sequence",c=i?.nodeClass??(o?pp.YAMLMap:WS.YAMLSeq),l=new c(t.schema);l.flow=!0;let f=t.atRoot;f&&(t.atRoot=!1),t.atKey&&(t.atKey=!1);let u=n.offset+n.start.source.length;for(let g=0;g<n.items.length;++g){let x=n.items[g],{start:A,key:P,sep:_,value:N}=x,C=mp.resolveProps(A,{flow:a,indicator:"explicit-key-ind",next:P??_?.[0],offset:u,onError:s,parentIndent:n.indent,startOnNewline:!1});if(!C.found){if(!C.anchor&&!C.tag&&!_&&!N){g===0&&C.comma?s(C.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`):g<n.items.length-1&&s(C.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${a}`),C.comment&&(l.comment?l.comment+=`
|
|
83
|
+
`+C.comment:l.comment=C.comment),u=C.end;continue}!o&&t.options.strict&&VS.containsNewline(P)&&s(P,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(g===0)C.comma&&s(C.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`);else if(C.comma||s(C.start,"MISSING_CHAR",`Missing , between ${a} items`),C.comment){let I="";e:for(let E of A)switch(E.type){case"comma":case"space":break;case"comment":I=E.source.substring(1);break e;default:break e}if(I){let E=l.items[l.items.length-1];KS.isPair(E)&&(E=E.value??E.key),E.comment?E.comment+=`
|
|
84
|
+
`+I:E.comment=I,C.comment=C.comment.substring(I.length+1)}}if(!o&&!_&&!C.found){let I=N?r(t,N,C,s):e(t,C.end,_,null,C,s);l.items.push(I),u=I.range[2],yc(N)&&s(I.range,"BLOCK_IN_FLOW",gc)}else{t.atKey=!0;let I=C.end,E=P?r(t,P,C,s):e(t,I,A,null,C,s);yc(P)&&s(E.range,"BLOCK_IN_FLOW",gc),t.atKey=!1;let y=mp.resolveProps(_??[],{flow:a,indicator:"map-value-ind",next:N,offset:E.range[2],onError:s,parentIndent:n.indent,startOnNewline:!1});if(y.found){if(!o&&!C.found&&t.options.strict){if(_)for(let R of _){if(R===y.found)break;if(R.type==="newline"){s(R,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}C.start<y.found.offset-1024&&s(y.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else N&&("source"in N&&N.source?.[0]===":"?s(N,"MISSING_CHAR",`Missing space after : in ${a}`):s(y.start,"MISSING_CHAR",`Missing , or : between ${a} items`));let w=N?r(t,N,y,s):y.found?e(t,y.end,_,null,y,s):null;w?yc(N)&&s(w.range,"BLOCK_IN_FLOW",gc):y.comment&&(E.comment?E.comment+=`
|
|
85
|
+
`+y.comment:E.comment=y.comment);let $=new HS.Pair(E,w);if(t.options.keepSourceTokens&&($.srcToken=x),o){let R=l;GS.mapIncludes(t,R.items,E)&&s(I,"DUPLICATE_KEY","Map keys must be unique"),R.items.push($)}else{let R=new pp.YAMLMap(t.schema);R.flow=!0,R.items.push($);let M=(w??E).range;R.range=[E.range[0],M[1],M[2]],l.items.push(R)}u=w?w.range[2]:y.end}}let d=o?"}":"]",[p,...b]=n.end,m=u;if(p?.source===d)m=p.offset+p.source.length;else{let g=a[0].toUpperCase()+a.substring(1),x=f?`${g} must end with a ${d}`:`${g} in block collection must be sufficiently indented and end with a ${d}`;s(u,f?"MISSING_CHAR":"BAD_INDENT",x),p&&p.source.length!==1&&b.unshift(p)}if(b.length>0){let g=YS.resolveEnd(b,m,t.options.strict,s);g.comment&&(l.comment?l.comment+=`
|
|
86
|
+
`+g.comment:l.comment=g.comment),l.range=[n.offset,m,g.offset]}else l.range=[n.offset,m,m];return l}hp.resolveFlowCollection=zS});var bp=T(yp=>{"use strict";var XS=F(),QS=X(),ZS=lt(),ek=ut(),tk=lp(),rk=dp(),nk=gp();function bc(r,e,t,n,s,i){let o=t.type==="block-map"?tk.resolveBlockMap(r,e,t,n,i):t.type==="block-seq"?rk.resolveBlockSeq(r,e,t,n,i):nk.resolveFlowCollection(r,e,t,n,i),a=o.constructor;return s==="!"||s===a.tagName?(o.tag=a.tagName,o):(s&&(o.tag=s),o)}function sk(r,e,t,n,s){let i=n.tag,o=i?e.directives.tagName(i.source,d=>s(i,"TAG_RESOLVE_FAILED",d)):null;if(t.type==="block-seq"){let{anchor:d,newlineAfterProp:p}=n,b=d&&i?d.offset>i.offset?d:i:d??i;b&&(!p||p.offset<b.offset)&&s(b,"MISSING_CHAR","Missing newline after block sequence props")}let a=t.type==="block-map"?"map":t.type==="block-seq"?"seq":t.start.source==="{"?"map":"seq";if(!i||!o||o==="!"||o===ZS.YAMLMap.tagName&&a==="map"||o===ek.YAMLSeq.tagName&&a==="seq")return bc(r,e,t,s,o);let c=e.schema.tags.find(d=>d.tag===o&&d.collection===a);if(!c){let d=e.schema.knownTags[o];if(d?.collection===a)e.schema.tags.push(Object.assign({},d,{default:!1})),c=d;else return d?s(i,"BAD_COLLECTION_TYPE",`${d.tag} used for ${a} collection, but expects ${d.collection??"scalar"}`,!0):s(i,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),bc(r,e,t,s,o)}let l=bc(r,e,t,s,o,c),f=c.resolve?.(l,d=>s(i,"TAG_RESOLVE_FAILED",d),e.options)??l,u=XS.isNode(f)?f:new QS.Scalar(f);return u.range=l.range,u.tag=o,c?.format&&(u.format=c.format),u}yp.composeCollection=sk});var vc=T(wp=>{"use strict";var wc=X();function ik(r,e,t){let n=e.offset,s=ok(e,r.options.strict,t);if(!s)return{value:"",type:null,comment:"",range:[n,n,n]};let i=s.mode===">"?wc.Scalar.BLOCK_FOLDED:wc.Scalar.BLOCK_LITERAL,o=e.source?ak(e.source):[],a=o.length;for(let m=o.length-1;m>=0;--m){let g=o[m][1];if(g===""||g==="\r")a=m;else break}if(a===0){let m=s.chomp==="+"&&o.length>0?`
|
|
87
|
+
`.repeat(Math.max(1,o.length-1)):"",g=n+s.length;return e.source&&(g+=e.source.length),{value:m,type:i,comment:s.comment,range:[n,g,g]}}let c=e.indent+s.indent,l=e.offset+s.length,f=0;for(let m=0;m<a;++m){let[g,x]=o[m];if(x===""||x==="\r")s.indent===0&&g.length>c&&(c=g.length);else{g.length<c&&t(l+g.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),s.indent===0&&(c=g.length),f=m,c===0&&!r.atRoot&&t(l,"BAD_INDENT","Block scalar values in collections must be indented");break}l+=g.length+x.length+1}for(let m=o.length-1;m>=a;--m)o[m][0].length>c&&(a=m+1);let u="",d="",p=!1;for(let m=0;m<f;++m)u+=o[m][0].slice(c)+`
|
|
88
|
+
`;for(let m=f;m<a;++m){let[g,x]=o[m];l+=g.length+x.length+1;let A=x[x.length-1]==="\r";if(A&&(x=x.slice(0,-1)),x&&g.length<c){let _=`Block scalar lines must not be less indented than their ${s.indent?"explicit indentation indicator":"first line"}`;t(l-x.length-(A?2:1),"BAD_INDENT",_),g=""}i===wc.Scalar.BLOCK_LITERAL?(u+=d+g.slice(c)+x,d=`
|
|
89
|
+
`):g.length>c||x[0]===" "?(d===" "?d=`
|
|
90
|
+
`:!p&&d===`
|
|
91
|
+
`&&(d=`
|
|
92
|
+
|
|
93
|
+
`),u+=d+g.slice(c)+x,d=`
|
|
94
|
+
`,p=!0):x===""?d===`
|
|
95
95
|
`?u+=`
|
|
96
|
-
`:
|
|
97
|
-
`:(u+=
|
|
96
|
+
`:d=`
|
|
97
|
+
`:(u+=d+x,d=" ",p=!1)}switch(s.chomp){case"-":break;case"+":for(let m=a;m<o.length;++m)u+=`
|
|
98
98
|
`+o[m][0].slice(c);u[u.length-1]!==`
|
|
99
99
|
`&&(u+=`
|
|
100
100
|
`);break;default:u+=`
|
|
101
|
-
`}let b=n+s.length+e.source.length;return{value:u,type:i,comment:s.comment,range:[n,b,b]}}function
|
|
101
|
+
`}let b=n+s.length+e.source.length;return{value:u,type:i,comment:s.comment,range:[n,b,b]}}function ok({offset:r,props:e},t,n){if(e[0].type!=="block-scalar-header")return n(e[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:s}=e[0],i=s[0],o=0,a="",c=-1;for(let d=1;d<s.length;++d){let p=s[d];if(!a&&(p==="-"||p==="+"))a=p;else{let b=Number(p);!o&&b?o=b:c===-1&&(c=r+d)}}c!==-1&&n(c,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${s}`);let l=!1,f="",u=s.length;for(let d=1;d<e.length;++d){let p=e[d];switch(p.type){case"space":l=!0;case"newline":u+=p.source.length;break;case"comment":t&&!l&&n(p,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),u+=p.source.length,f=p.source.substring(1);break;case"error":n(p,"UNEXPECTED_TOKEN",p.message),u+=p.source.length;break;default:{let b=`Unexpected token in block scalar header: ${p.type}`;n(p,"UNEXPECTED_TOKEN",b);let m=p.source;m&&typeof m=="string"&&(u+=m.length)}}}return{mode:i,indent:o,chomp:a,comment:f,length:u}}function ak(r){let e=r.split(/\n( *)/),t=e[0],n=t.match(/^( *)/),i=[n?.[1]?[n[1],t.slice(n[1].length)]:["",t]];for(let o=1;o<e.length;o+=2)i.push([e[o],e[o+1]]);return i}wp.resolveBlockScalar=ik});var kc=T(Sp=>{"use strict";var Sc=X(),ck=fr();function lk(r,e,t){let{offset:n,type:s,source:i,end:o}=r,a,c,l=(d,p,b)=>t(n+d,p,b);switch(s){case"scalar":a=Sc.Scalar.PLAIN,c=uk(i,l);break;case"single-quoted-scalar":a=Sc.Scalar.QUOTE_SINGLE,c=dk(i,l);break;case"double-quoted-scalar":a=Sc.Scalar.QUOTE_DOUBLE,c=fk(i,l);break;default:return t(r,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${s}`),{value:"",type:null,comment:"",range:[n,n+i.length,n+i.length]}}let f=n+i.length,u=ck.resolveEnd(o,f,e,t);return{value:c,type:a,comment:u.comment,range:[n,f,u.offset]}}function uk(r,e){let t="";switch(r[0]){case" ":t="a tab character";break;case",":t="flow indicator character ,";break;case"%":t="directive indicator character %";break;case"|":case">":{t=`block scalar indicator ${r[0]}`;break}case"@":case"`":{t=`reserved character ${r[0]}`;break}}return t&&e(0,"BAD_SCALAR_START",`Plain value cannot start with ${t}`),vp(r)}function dk(r,e){return(r[r.length-1]!=="'"||r.length===1)&&e(r.length,"MISSING_CHAR","Missing closing 'quote"),vp(r.slice(1,-1)).replace(/''/g,"'")}function vp(r){let e,t;try{e=new RegExp(`(.*?)(?<![ ])[ ]*\r?
|
|
102
102
|
`,"sy"),t=new RegExp(`[ ]*(.*?)(?:(?<![ ])[ ]*)?\r?
|
|
103
103
|
`,"sy")}catch{e=/(.*?)[ \t]*\r?\n/sy,t=/[ \t]*(.*?)[ \t]*\r?\n/sy}let n=e.exec(r);if(!n)return r;let s=n[1],i=" ",o=e.lastIndex;for(t.lastIndex=o;n=t.exec(r);)n[1]===""?i===`
|
|
104
104
|
`?s+=i:i=`
|
|
105
|
-
`:(s+=i+n[1],i=" "),o=t.lastIndex;let a=/[ \t]*(.*)/sy;return a.lastIndex=o,n=a.exec(r),s+i+(n?.[1]??"")}function
|
|
105
|
+
`:(s+=i+n[1],i=" "),o=t.lastIndex;let a=/[ \t]*(.*)/sy;return a.lastIndex=o,n=a.exec(r),s+i+(n?.[1]??"")}function fk(r,e){let t="";for(let n=1;n<r.length-1;++n){let s=r[n];if(!(s==="\r"&&r[n+1]===`
|
|
106
106
|
`))if(s===`
|
|
107
|
-
`){let{fold:i,offset:o}=
|
|
107
|
+
`){let{fold:i,offset:o}=pk(r,n);t+=i,n=o}else if(s==="\\"){let i=r[++n],o=mk[i];if(o)t+=o;else if(i===`
|
|
108
108
|
`)for(i=r[n+1];i===" "||i===" ";)i=r[++n+1];else if(i==="\r"&&r[n+1]===`
|
|
109
|
-
`)for(i=r[++n+1];i===" "||i===" ";)i=r[++n+1];else if(i==="x"||i==="u"||i==="U"){let a={x:2,u:4,U:8}[i];t+=
|
|
109
|
+
`)for(i=r[++n+1];i===" "||i===" ";)i=r[++n+1];else if(i==="x"||i==="u"||i==="U"){let a={x:2,u:4,U:8}[i];t+=hk(r,n+1,a,e),n+=a}else{let a=r.substr(n-1,2);e(n-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${a}`),t+=a}}else if(s===" "||s===" "){let i=n,o=r[n+1];for(;o===" "||o===" ";)o=r[++n+1];o!==`
|
|
110
110
|
`&&!(o==="\r"&&r[n+2]===`
|
|
111
|
-
`)&&(t+=n>i?r.slice(i,n+1):s)}else t+=s}return(r[r.length-1]!=='"'||r.length===1)&&e(r.length,"MISSING_CHAR",'Missing closing "quote'),t}function
|
|
111
|
+
`)&&(t+=n>i?r.slice(i,n+1):s)}else t+=s}return(r[r.length-1]!=='"'||r.length===1)&&e(r.length,"MISSING_CHAR",'Missing closing "quote'),t}function pk(r,e){let t="",n=r[e+1];for(;(n===" "||n===" "||n===`
|
|
112
112
|
`||n==="\r")&&!(n==="\r"&&r[e+2]!==`
|
|
113
113
|
`);)n===`
|
|
114
114
|
`&&(t+=`
|
|
115
|
-
`),e+=1,n=r[e+1];return t||(t=" "),{fold:t,offset:e}}var
|
|
116
|
-
`,r:"\r",t:" ",v:"\v",N:"\x85",_:"\xA0",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function
|
|
115
|
+
`),e+=1,n=r[e+1];return t||(t=" "),{fold:t,offset:e}}var mk={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
|
|
116
|
+
`,r:"\r",t:" ",v:"\v",N:"\x85",_:"\xA0",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function hk(r,e,t,n){let s=r.substr(e,t),o=s.length===t&&/^[0-9a-fA-F]+$/.test(s)?parseInt(s,16):NaN;if(isNaN(o)){let a=r.substr(e-2,t+2);return n(e-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${a}`),a}return String.fromCodePoint(o)}Sp.resolveFlowScalar=lk});var Ep=T(xp=>{"use strict";var $t=F(),kp=X(),gk=vc(),yk=kc();function bk(r,e,t,n){let{value:s,type:i,comment:o,range:a}=e.type==="block-scalar"?gk.resolveBlockScalar(r,e,n):yk.resolveFlowScalar(e,r.options.strict,n),c=t?r.directives.tagName(t.source,u=>n(t,"TAG_RESOLVE_FAILED",u)):null,l;r.options.stringKeys&&r.atKey?l=r.schema[$t.SCALAR]:c?l=wk(r.schema,s,c,t,n):e.type==="scalar"?l=vk(r,s,e,n):l=r.schema[$t.SCALAR];let f;try{let u=l.resolve(s,d=>n(t??e,"TAG_RESOLVE_FAILED",d),r.options);f=$t.isScalar(u)?u:new kp.Scalar(u)}catch(u){let d=u instanceof Error?u.message:String(u);n(t??e,"TAG_RESOLVE_FAILED",d),f=new kp.Scalar(s)}return f.range=a,f.source=s,i&&(f.type=i),c&&(f.tag=c),l.format&&(f.format=l.format),o&&(f.comment=o),f}function wk(r,e,t,n,s){if(t==="!")return r[$t.SCALAR];let i=[];for(let a of r.tags)if(!a.collection&&a.tag===t)if(a.default&&a.test)i.push(a);else return a;for(let a of i)if(a.test?.test(e))return a;let o=r.knownTags[t];return o&&!o.collection?(r.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(s(n,"TAG_RESOLVE_FAILED",`Unresolved tag: ${t}`,t!=="tag:yaml.org,2002:str"),r[$t.SCALAR])}function vk({atKey:r,directives:e,schema:t},n,s,i){let o=t.tags.find(a=>(a.default===!0||r&&a.default==="key")&&a.test?.test(n))||t[$t.SCALAR];if(t.compat){let a=t.compat.find(c=>c.default&&c.test?.test(n))??t[$t.SCALAR];if(o.tag!==a.tag){let c=e.tagString(o.tag),l=e.tagString(a.tag),f=`Value may be parsed as either ${c} or ${l}`;i(s,"TAG_RESOLVE_FAILED",f,!0)}}return o}xp.composeScalar=bk});var Tp=T(Ap=>{"use strict";function Sk(r,e,t){if(e){t??(t=e.length);for(let n=t-1;n>=0;--n){let s=e[n];switch(s.type){case"space":case"comment":case"newline":r-=s.source.length;continue}for(s=e[++n];s?.type==="space";)r+=s.source.length,s=e[++n];break}}return r}Ap.emptyScalarPosition=Sk});var Cp=T(Ec=>{"use strict";var kk=Gr(),xk=F(),Ek=bp(),Pp=Ep(),Ak=fr(),Tk=Tp(),Pk={composeNode:Op,composeEmptyNode:xc};function Op(r,e,t,n){let s=r.atKey,{spaceBefore:i,comment:o,anchor:a,tag:c}=t,l,f=!0;switch(e.type){case"alias":l=Ok(r,e,n),(a||c)&&n(e,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":l=Pp.composeScalar(r,e,c,n),a&&(l.anchor=a.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":l=Ek.composeCollection(Pk,r,e,t,n),a&&(l.anchor=a.source.substring(1));break;default:{let u=e.type==="error"?e.message:`Unsupported token (type: ${e.type})`;n(e,"UNEXPECTED_TOKEN",u),l=xc(r,e.offset,void 0,null,t,n),f=!1}}return a&&l.anchor===""&&n(a,"BAD_ALIAS","Anchor cannot be an empty string"),s&&r.options.stringKeys&&(!xk.isScalar(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&n(c??e,"NON_STRING_KEY","With stringKeys, all keys must be strings"),i&&(l.spaceBefore=!0),o&&(e.type==="scalar"&&e.source===""?l.comment=o:l.commentBefore=o),r.options.keepSourceTokens&&f&&(l.srcToken=e),l}function xc(r,e,t,n,{spaceBefore:s,comment:i,anchor:o,tag:a,end:c},l){let f={type:"scalar",offset:Tk.emptyScalarPosition(e,t,n),indent:-1,source:""},u=Pp.composeScalar(r,f,a,l);return o&&(u.anchor=o.source.substring(1),u.anchor===""&&l(o,"BAD_ALIAS","Anchor cannot be an empty string")),s&&(u.spaceBefore=!0),i&&(u.comment=i,u.range[2]=c),u}function Ok({options:r},{offset:e,source:t,end:n},s){let i=new kk.Alias(t.substring(1));i.source===""&&s(e,"BAD_ALIAS","Alias cannot be an empty string"),i.source.endsWith(":")&&s(e+t.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let o=e+t.length,a=Ak.resolveEnd(n,o,r.strict,s);return i.range=[e,o,a.offset],a.comment&&(i.comment=a.comment),i}Ec.composeEmptyNode=xc;Ec.composeNode=Op});var Np=T(_p=>{"use strict";var Ck=pn(),Rp=Cp(),Rk=fr(),_k=yn();function Nk(r,e,{offset:t,start:n,value:s,end:i},o){let a=Object.assign({_directives:e},r),c=new Ck.Document(void 0,a),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},f=_k.resolveProps(n,{indicator:"doc-start",next:s??i?.[0],offset:t,onError:o,parentIndent:0,startOnNewline:!0});f.found&&(c.directives.docStart=!0,s&&(s.type==="block-map"||s.type==="block-seq")&&!f.hasNewline&&o(f.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=s?Rp.composeNode(l,s,f,o):Rp.composeEmptyNode(l,f.end,n,null,f,o);let u=c.contents.range[2],d=Rk.resolveEnd(i,u,!1,o);return d.comment&&(c.comment=d.comment),c.range=[t,u,d.offset],c}_p.composeDoc=Nk});var Tc=T(Lp=>{"use strict";var Ik=us("process"),$k=da(),Lk=pn(),bn=gn(),Ip=F(),Mk=Np(),Dk=fr();function wn(r){if(typeof r=="number")return[r,r+1];if(Array.isArray(r))return r.length===2?r:[r[0],r[1]];let{offset:e,source:t}=r;return[e,e+(typeof t=="string"?t.length:1)]}function $p(r){let e="",t=!1,n=!1;for(let s=0;s<r.length;++s){let i=r[s];switch(i[0]){case"#":e+=(e===""?"":n?`
|
|
117
117
|
|
|
118
118
|
`:`
|
|
119
|
-
`)+(i.substring(1)||" "),t=!0,n=!1;break;case"%":r[s+1]?.[0]!=="#"&&(s+=1),t=!1;break;default:t||(n=!0),t=!1}}return{comment:e,afterEmptyLine:n}}var
|
|
120
|
-
${n}`:n;else if(s||e.directives.docStart||!i)e.commentBefore=n;else if(
|
|
119
|
+
`)+(i.substring(1)||" "),t=!0,n=!1;break;case"%":r[s+1]?.[0]!=="#"&&(s+=1),t=!1;break;default:t||(n=!0),t=!1}}return{comment:e,afterEmptyLine:n}}var Ac=class{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(t,n,s,i)=>{let o=wn(t);i?this.warnings.push(new bn.YAMLWarning(o,n,s)):this.errors.push(new bn.YAMLParseError(o,n,s))},this.directives=new $k.Directives({version:e.version||"1.2"}),this.options=e}decorate(e,t){let{comment:n,afterEmptyLine:s}=$p(this.prelude);if(n){let i=e.contents;if(t)e.comment=e.comment?`${e.comment}
|
|
120
|
+
${n}`:n;else if(s||e.directives.docStart||!i)e.commentBefore=n;else if(Ip.isCollection(i)&&!i.flow&&i.items.length>0){let o=i.items[0];Ip.isPair(o)&&(o=o.key);let a=o.commentBefore;o.commentBefore=a?`${n}
|
|
121
121
|
${a}`:n}else{let o=i.commentBefore;i.commentBefore=o?`${n}
|
|
122
|
-
${o}`:n}}t?(Array.prototype.push.apply(e.errors,this.errors),Array.prototype.push.apply(e.warnings,this.warnings)):(e.errors=this.errors,e.warnings=this.warnings),this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment
|
|
123
|
-
${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.push(new bn.YAMLParseError(wn(e),"UNEXPECTED_TOKEN",`Unsupported token ${e.type}`))}}*end(e=!1,t=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(e){let n=Object.assign({_directives:this.directives},this.options),s=new
|
|
122
|
+
${o}`:n}}t?(Array.prototype.push.apply(e.errors,this.errors),Array.prototype.push.apply(e.warnings,this.warnings)):(e.errors=this.errors,e.warnings=this.warnings),this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:$p(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(e,t=!1,n=-1){for(let s of e)yield*this.next(s);yield*this.end(t,n)}*next(e){switch(Ik.env.LOG_STREAM&&console.dir(e,{depth:null}),e.type){case"directive":this.directives.add(e.source,(t,n,s)=>{let i=wn(e);i[0]+=t,this.onError(i,"BAD_DIRECTIVE",n,s)}),this.prelude.push(e.source),this.atDirectives=!0;break;case"document":{let t=Mk.composeDoc(this.options,this.directives,e,this.onError);this.atDirectives&&!t.directives.docStart&&this.onError(e,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(t,!1),this.doc&&(yield this.doc),this.doc=t,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(e.source);break;case"error":{let t=e.source?`${e.message}: ${JSON.stringify(e.source)}`:e.message,n=new bn.YAMLParseError(wn(e),"UNEXPECTED_TOKEN",t);this.atDirectives||!this.doc?this.errors.push(n):this.doc.errors.push(n);break}case"doc-end":{if(!this.doc){let n="Unexpected doc-end without preceding document";this.errors.push(new bn.YAMLParseError(wn(e),"UNEXPECTED_TOKEN",n));break}this.doc.directives.docEnd=!0;let t=Dk.resolveEnd(e.end,e.offset+e.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),t.comment){let n=this.doc.comment;this.doc.comment=n?`${n}
|
|
123
|
+
${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.push(new bn.YAMLParseError(wn(e),"UNEXPECTED_TOKEN",`Unsupported token ${e.type}`))}}*end(e=!1,t=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(e){let n=Object.assign({_directives:this.directives},this.options),s=new Lk.Document(void 0,n);this.atDirectives&&this.onError(t,"MISSING_CHAR","Missing directives-end indicator line"),s.range=[0,t,t],this.decorate(s,!1),yield s}}};Lp.Composer=Ac});var Bp=T(ii=>{"use strict";var Bk=vc(),jk=kc(),Fk=gn(),Mp=en();function qk(r,e=!0,t){if(r){let n=(s,i,o)=>{let a=typeof s=="number"?s:Array.isArray(s)?s[0]:s.offset;if(t)t(a,i,o);else throw new Fk.YAMLParseError([a,a+1],i,o)};switch(r.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return jk.resolveFlowScalar(r,e,n);case"block-scalar":return Bk.resolveBlockScalar({options:{strict:e}},r,n)}}return null}function Uk(r,e){let{implicitKey:t=!1,indent:n,inFlow:s=!1,offset:i=-1,type:o="PLAIN"}=e,a=Mp.stringifyString({type:o,value:r},{implicitKey:t,indent:n>0?" ".repeat(n):"",inFlow:s,options:{blockQuote:!0,lineWidth:-1}}),c=e.end??[{type:"newline",offset:-1,indent:n,source:`
|
|
124
124
|
`}];switch(a[0]){case"|":case">":{let l=a.indexOf(`
|
|
125
|
-
`),
|
|
126
|
-
`,
|
|
127
|
-
`}),{type:"block-scalar",offset:i,indent:n,props:
|
|
125
|
+
`),f=a.substring(0,l),u=a.substring(l+1)+`
|
|
126
|
+
`,d=[{type:"block-scalar-header",offset:i,indent:n,source:f}];return Dp(d,c)||d.push({type:"newline",offset:-1,indent:n,source:`
|
|
127
|
+
`}),{type:"block-scalar",offset:i,indent:n,props:d,source:u}}case'"':return{type:"double-quoted-scalar",offset:i,indent:n,source:a,end:c};case"'":return{type:"single-quoted-scalar",offset:i,indent:n,source:a,end:c};default:return{type:"scalar",offset:i,indent:n,source:a,end:c}}}function Jk(r,e,t={}){let{afterKey:n=!1,implicitKey:s=!1,inFlow:i=!1,type:o}=t,a="indent"in r?r.indent:null;if(n&&typeof a=="number"&&(a+=2),!o)switch(r.type){case"single-quoted-scalar":o="QUOTE_SINGLE";break;case"double-quoted-scalar":o="QUOTE_DOUBLE";break;case"block-scalar":{let l=r.props[0];if(l.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o=l.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:o="PLAIN"}let c=Mp.stringifyString({type:o,value:e},{implicitKey:s||a===null,indent:a!==null&&a>0?" ".repeat(a):"",inFlow:i,options:{blockQuote:!0,lineWidth:-1}});switch(c[0]){case"|":case">":Kk(r,c);break;case'"':Pc(r,c,"double-quoted-scalar");break;case"'":Pc(r,c,"single-quoted-scalar");break;default:Pc(r,c,"scalar")}}function Kk(r,e){let t=e.indexOf(`
|
|
128
128
|
`),n=e.substring(0,t),s=e.substring(t+1)+`
|
|
129
|
-
`;if(r.type==="block-scalar"){let i=r.props[0];if(i.type!=="block-scalar-header")throw new Error("Invalid block scalar header");i.source=n,r.source=s}else{let{offset:i}=r,o="indent"in r?r.indent:-1,a=[{type:"block-scalar-header",offset:i,indent:o,source:n}];
|
|
130
|
-
`});for(let c of Object.keys(r))c!=="type"&&c!=="offset"&&delete r[c];Object.assign(r,{type:"block-scalar",indent:o,props:a,source:s})}}function
|
|
131
|
-
`};delete r.items,Object.assign(r,{type:t,source:e,end:[s]});break}default:{let n="indent"in r?r.indent:-1,s="end"in r&&Array.isArray(r.end)?r.end.filter(i=>i.type==="space"||i.type==="comment"||i.type==="newline"):[];for(let i of Object.keys(r))i!=="type"&&i!=="offset"&&delete r[i];Object.assign(r,{type:t,indent:n,source:e,end:s})}}}
|
|
129
|
+
`;if(r.type==="block-scalar"){let i=r.props[0];if(i.type!=="block-scalar-header")throw new Error("Invalid block scalar header");i.source=n,r.source=s}else{let{offset:i}=r,o="indent"in r?r.indent:-1,a=[{type:"block-scalar-header",offset:i,indent:o,source:n}];Dp(a,"end"in r?r.end:void 0)||a.push({type:"newline",offset:-1,indent:o,source:`
|
|
130
|
+
`});for(let c of Object.keys(r))c!=="type"&&c!=="offset"&&delete r[c];Object.assign(r,{type:"block-scalar",indent:o,props:a,source:s})}}function Dp(r,e){if(e)for(let t of e)switch(t.type){case"space":case"comment":r.push(t);break;case"newline":return r.push(t),!0}return!1}function Pc(r,e,t){switch(r.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":r.type=t,r.source=e;break;case"block-scalar":{let n=r.props.slice(1),s=e.length;r.props[0].type==="block-scalar-header"&&(s-=r.props[0].source.length);for(let i of n)i.offset+=s;delete r.props,Object.assign(r,{type:t,source:e,end:n});break}case"block-map":case"block-seq":{let s={type:"newline",offset:r.offset+e.length,indent:r.indent,source:`
|
|
131
|
+
`};delete r.items,Object.assign(r,{type:t,source:e,end:[s]});break}default:{let n="indent"in r?r.indent:-1,s="end"in r&&Array.isArray(r.end)?r.end.filter(i=>i.type==="space"||i.type==="comment"||i.type==="newline"):[];for(let i of Object.keys(r))i!=="type"&&i!=="offset"&&delete r[i];Object.assign(r,{type:t,indent:n,source:e,end:s})}}}ii.createScalarToken=Uk;ii.resolveAsScalar=qk;ii.setScalarValue=Jk});var Fp=T(jp=>{"use strict";var Hk=r=>"type"in r?ai(r):oi(r);function ai(r){switch(r.type){case"block-scalar":{let e="";for(let t of r.props)e+=ai(t);return e+r.source}case"block-map":case"block-seq":{let e="";for(let t of r.items)e+=oi(t);return e}case"flow-collection":{let e=r.start.source;for(let t of r.items)e+=oi(t);for(let t of r.end)e+=t.source;return e}case"document":{let e=oi(r);if(r.end)for(let t of r.end)e+=t.source;return e}default:{let e=r.source;if("end"in r&&r.end)for(let t of r.end)e+=t.source;return e}}}function oi({start:r,key:e,sep:t,value:n}){let s="";for(let i of r)s+=i.source;if(e&&(s+=ai(e)),t)for(let i of t)s+=i.source;return n&&(s+=ai(n)),s}jp.stringify=Hk});var Kp=T(Jp=>{"use strict";var Oc=Symbol("break visit"),Wk=Symbol("skip children"),qp=Symbol("remove item");function Lt(r,e){"type"in r&&r.type==="document"&&(r={start:r.start,value:r.value}),Up(Object.freeze([]),r,e)}Lt.BREAK=Oc;Lt.SKIP=Wk;Lt.REMOVE=qp;Lt.itemAtPath=(r,e)=>{let t=r;for(let[n,s]of e){let i=t?.[n];if(i&&"items"in i)t=i.items[s];else return}return t};Lt.parentCollection=(r,e)=>{let t=Lt.itemAtPath(r,e.slice(0,-1)),n=e[e.length-1][0],s=t?.[n];if(s&&"items"in s)return s;throw new Error("Parent collection not found")};function Up(r,e,t){let n=t(e,r);if(typeof n=="symbol")return n;for(let s of["key","value"]){let i=e[s];if(i&&"items"in i){for(let o=0;o<i.items.length;++o){let a=Up(Object.freeze(r.concat([[s,o]])),i.items[o],t);if(typeof a=="number")o=a-1;else{if(a===Oc)return Oc;a===qp&&(i.items.splice(o,1),o-=1)}}typeof n=="function"&&s==="key"&&(n=n(e,r))}}return typeof n=="function"?n(e,r):n}Jp.visit=Lt});var ci=T(ue=>{"use strict";var Cc=Bp(),Yk=Fp(),Vk=Kp(),Rc="\uFEFF",_c="",Nc="",Ic="",Gk=r=>!!r&&"items"in r,zk=r=>!!r&&(r.type==="scalar"||r.type==="single-quoted-scalar"||r.type==="double-quoted-scalar"||r.type==="block-scalar");function Xk(r){switch(r){case Rc:return"<BOM>";case _c:return"<DOC>";case Nc:return"<FLOW_END>";case Ic:return"<SCALAR>";default:return JSON.stringify(r)}}function Qk(r){switch(r){case Rc:return"byte-order-mark";case _c:return"doc-mode";case Nc:return"flow-error-end";case Ic:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
|
|
132
132
|
`:case`\r
|
|
133
|
-
`:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(r[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}ue.createScalarToken=
|
|
134
|
-
`:case"\r":case" ":return!0;default:return!1}}var
|
|
135
|
-
\r `)
|
|
133
|
+
`:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(r[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}ue.createScalarToken=Cc.createScalarToken;ue.resolveAsScalar=Cc.resolveAsScalar;ue.setScalarValue=Cc.setScalarValue;ue.stringify=Yk.stringify;ue.visit=Vk.visit;ue.BOM=Rc;ue.DOCUMENT=_c;ue.FLOW_END=Nc;ue.SCALAR=Ic;ue.isCollection=Gk;ue.isScalar=zk;ue.prettyToken=Xk;ue.tokenType=Qk});var Mc=T(Wp=>{"use strict";var vn=ci();function Se(r){switch(r){case void 0:case" ":case`
|
|
134
|
+
`:case"\r":case" ":return!0;default:return!1}}var Hp=new Set("0123456789ABCDEFabcdef"),Zk=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),li=new Set(",[]{}"),ex=new Set(` ,[]{}
|
|
135
|
+
\r `),$c=r=>!r||ex.has(r),Lc=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(e,t=!1){if(e){if(typeof e!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+e:e,this.lineEndPos=null}this.atEnd=!t;let n=this.next??"stream";for(;n&&(t||this.hasChars(1));)n=yield*this.parseNext(n)}atLineEnd(){let e=this.pos,t=this.buffer[e];for(;t===" "||t===" ";)t=this.buffer[++e];return!t||t==="#"||t===`
|
|
136
136
|
`?!0:t==="\r"?this.buffer[e+1]===`
|
|
137
137
|
`:!1}charAt(e){return this.buffer[this.pos+e]}continueScalar(e){let t=this.buffer[e];if(this.indentNext>0){let n=0;for(;t===" ";)t=this.buffer[++n+e];if(t==="\r"){let s=this.buffer[n+e+1];if(s===`
|
|
138
138
|
`||!s&&!this.atEnd)return e+n+1}return t===`
|
|
139
139
|
`||n>=this.indentNext||!t&&!this.atEnd?e+n:-1}if(t==="-"||t==="."){let n=this.buffer.substr(e,3);if((n==="---"||n==="...")&&Se(this.buffer[e+3]))return-1}return e}getLine(){let e=this.lineEndPos;return(typeof e!="number"||e!==-1&&e<this.pos)&&(e=this.buffer.indexOf(`
|
|
140
|
-
`,this.pos),this.lineEndPos=e),e===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[e-1]==="\r"&&(e-=1),this.buffer.substring(this.pos,e))}hasChars(e){return this.pos+e<=this.buffer.length}setNext(e){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=e,null}peek(e){return this.buffer.substr(this.pos,e)}*parseNext(e){switch(e){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let e=this.getLine();if(e===null)return this.setNext("stream");if(e[0]===vn.BOM&&(yield*this.pushCount(1),e=e.substring(1)),e[0]==="%"){let t=e.length,n=e.indexOf("#");for(;n!==-1;){let i=e[n-1];if(i===" "||i===" "){t=n-1;break}else n=e.indexOf("#",n+1)}for(;;){let i=e[t-1];if(i===" "||i===" ")t-=1;else break}let s=(yield*this.pushCount(t))+(yield*this.pushSpaces(!0));return yield*this.pushCount(e.length-s),this.pushNewline(),"stream"}if(this.atLineEnd()){let t=yield*this.pushSpaces(!0);return yield*this.pushCount(e.length-t),yield*this.pushNewline(),"stream"}return yield vn.DOCUMENT,yield*this.parseLineStart()}*parseLineStart(){let e=this.charAt(0);if(!e&&!this.atEnd)return this.setNext("line-start");if(e==="-"||e==="."){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");let t=this.peek(3);if((t==="---"||t==="...")&&Se(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,t==="---"?"doc":"stream"}return this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!Se(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[e,t]=this.peek(2);if(!t&&!this.atEnd)return this.setNext("block-start");if((e==="-"||e==="?"||e===":")&&Se(t)){let n=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=n,yield*this.parseBlockStart()}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let e=this.getLine();if(e===null)return this.setNext("doc");let t=yield*this.pushIndicators();switch(e[t]){case"#":yield*this.pushCount(e.length-t);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(
|
|
140
|
+
`,this.pos),this.lineEndPos=e),e===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[e-1]==="\r"&&(e-=1),this.buffer.substring(this.pos,e))}hasChars(e){return this.pos+e<=this.buffer.length}setNext(e){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=e,null}peek(e){return this.buffer.substr(this.pos,e)}*parseNext(e){switch(e){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let e=this.getLine();if(e===null)return this.setNext("stream");if(e[0]===vn.BOM&&(yield*this.pushCount(1),e=e.substring(1)),e[0]==="%"){let t=e.length,n=e.indexOf("#");for(;n!==-1;){let i=e[n-1];if(i===" "||i===" "){t=n-1;break}else n=e.indexOf("#",n+1)}for(;;){let i=e[t-1];if(i===" "||i===" ")t-=1;else break}let s=(yield*this.pushCount(t))+(yield*this.pushSpaces(!0));return yield*this.pushCount(e.length-s),this.pushNewline(),"stream"}if(this.atLineEnd()){let t=yield*this.pushSpaces(!0);return yield*this.pushCount(e.length-t),yield*this.pushNewline(),"stream"}return yield vn.DOCUMENT,yield*this.parseLineStart()}*parseLineStart(){let e=this.charAt(0);if(!e&&!this.atEnd)return this.setNext("line-start");if(e==="-"||e==="."){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");let t=this.peek(3);if((t==="---"||t==="...")&&Se(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,t==="---"?"doc":"stream"}return this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!Se(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[e,t]=this.peek(2);if(!t&&!this.atEnd)return this.setNext("block-start");if((e==="-"||e==="?"||e===":")&&Se(t)){let n=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=n,yield*this.parseBlockStart()}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let e=this.getLine();if(e===null)return this.setNext("doc");let t=yield*this.pushIndicators();switch(e[t]){case"#":yield*this.pushCount(e.length-t);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil($c),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return t+=yield*this.parseBlockScalarHeader(),t+=yield*this.pushSpaces(!0),yield*this.pushCount(e.length-t),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let e,t,n=-1;do e=yield*this.pushNewline(),e>0?(t=yield*this.pushSpaces(!1),this.indentValue=n=t):t=0,t+=yield*this.pushSpaces(!0);while(e+t>0);let s=this.getLine();if(s===null)return this.setNext("flow");if((n!==-1&&n<this.indentNext&&s[0]!=="#"||n===0&&(s.startsWith("---")||s.startsWith("..."))&&Se(s[3]))&&!(n===this.indentNext-1&&this.flowLevel===1&&(s[0]==="]"||s[0]==="}")))return this.flowLevel=0,yield vn.FLOW_END,yield*this.parseLineStart();let i=0;for(;s[i]===",";)i+=yield*this.pushCount(1),i+=yield*this.pushSpaces(!0),this.flowKey=!1;switch(i+=yield*this.pushIndicators(),s[i]){case void 0:return"flow";case"#":return yield*this.pushCount(s.length-i),"flow";case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel+=1,"flow";case"}":case"]":return yield*this.pushCount(1),this.flowKey=!0,this.flowLevel-=1,this.flowLevel?"flow":"doc";case"*":return yield*this.pushUntil($c),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let o=this.charAt(1);if(this.flowKey||Se(o)||o===",")return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),"flow"}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){let e=this.charAt(0),t=this.buffer.indexOf(e,this.pos+1);if(e==="'")for(;t!==-1&&this.buffer[t+1]==="'";)t=this.buffer.indexOf("'",t+2);else for(;t!==-1;){let i=0;for(;this.buffer[t-1-i]==="\\";)i+=1;if(i%2===0)break;t=this.buffer.indexOf('"',t+1)}let n=this.buffer.substring(0,t),s=n.indexOf(`
|
|
141
141
|
`,this.pos);if(s!==-1){for(;s!==-1;){let i=this.continueScalar(s+1);if(i===-1)break;s=n.indexOf(`
|
|
142
142
|
`,i)}s!==-1&&(t=s-(n[s-1]==="\r"?2:1))}if(t===-1){if(!this.atEnd)return this.setNext("quoted-scalar");t=this.buffer.length}return yield*this.pushToIndex(t+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let e=this.pos;for(;;){let t=this.buffer[++e];if(t==="+")this.blockScalarKeep=!0;else if(t>"0"&&t<="9")this.blockScalarIndent=Number(t)-1;else if(t!=="-")break}return yield*this.pushUntil(t=>Se(t)||t==="#")}*parseBlockScalar(){let e=this.pos-1,t=0,n;e:for(let i=this.pos;n=this.buffer[i];++i)switch(n){case" ":t+=1;break;case`
|
|
143
143
|
`:e=i,t=0;break;case"\r":{let o=this.buffer[i+1];if(!o&&!this.atEnd)return this.setNext("block-scalar");if(o===`
|
|
144
144
|
`)break}default:break e}if(!n&&!this.atEnd)return this.setNext("block-scalar");if(t>=this.indentNext){this.blockScalarIndent===-1?this.indentNext=t:this.indentNext=this.blockScalarIndent+(this.indentNext===0?1:this.indentNext);do{let i=this.continueScalar(e+1);if(i===-1)break;e=this.buffer.indexOf(`
|
|
145
145
|
`,i)}while(e!==-1);if(e===-1){if(!this.atEnd)return this.setNext("block-scalar");e=this.buffer.length}}let s=e+1;for(n=this.buffer[s];n===" ";)n=this.buffer[++s];if(n===" "){for(;n===" "||n===" "||n==="\r"||n===`
|
|
146
146
|
`;)n=this.buffer[++s];e=s-1}else if(!this.blockScalarKeep)do{let i=e-1,o=this.buffer[i];o==="\r"&&(o=this.buffer[--i]);let a=i;for(;o===" ";)o=this.buffer[--i];if(o===`
|
|
147
|
-
`&&i>=this.pos&&i+1+t>a)e=i;else break}while(!0);return yield vn.SCALAR,yield*this.pushToIndex(e+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let e=this.flowLevel>0,t=this.pos-1,n=this.pos-1,s;for(;s=this.buffer[++n];)if(s===":"){let i=this.buffer[n+1];if(Se(i)||e&&
|
|
147
|
+
`&&i>=this.pos&&i+1+t>a)e=i;else break}while(!0);return yield vn.SCALAR,yield*this.pushToIndex(e+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let e=this.flowLevel>0,t=this.pos-1,n=this.pos-1,s;for(;s=this.buffer[++n];)if(s===":"){let i=this.buffer[n+1];if(Se(i)||e&&li.has(i))break;t=n}else if(Se(s)){let i=this.buffer[n+1];if(s==="\r"&&(i===`
|
|
148
148
|
`?(n+=1,s=`
|
|
149
|
-
`,i=this.buffer[n+1]):t=n),i==="#"||e&&
|
|
150
|
-
`){let o=this.continueScalar(n+1);if(o===-1)break;n=Math.max(n,o-2)}}else{if(e&&
|
|
149
|
+
`,i=this.buffer[n+1]):t=n),i==="#"||e&&li.has(i))break;if(s===`
|
|
150
|
+
`){let o=this.continueScalar(n+1);if(o===-1)break;n=Math.max(n,o-2)}}else{if(e&&li.has(s))break;t=n}return!s&&!this.atEnd?this.setNext("plain-scalar"):(yield vn.SCALAR,yield*this.pushToIndex(t+1,!0),e?"flow":"doc")}*pushCount(e){return e>0?(yield this.buffer.substr(this.pos,e),this.pos+=e,e):0}*pushToIndex(e,t){let n=this.buffer.slice(this.pos,e);return n?(yield n,this.pos+=n.length,n.length):(t&&(yield""),0)}*pushIndicators(){switch(this.charAt(0)){case"!":return(yield*this.pushTag())+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators());case"&":return(yield*this.pushUntil($c))+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators());case"-":case"?":case":":{let e=this.flowLevel>0,t=this.charAt(1);if(Se(t)||e&&li.has(t))return e?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,(yield*this.pushCount(1))+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators())}}return 0}*pushTag(){if(this.charAt(1)==="<"){let e=this.pos+2,t=this.buffer[e];for(;!Se(t)&&t!==">";)t=this.buffer[++e];return yield*this.pushToIndex(t===">"?e+1:e,!1)}else{let e=this.pos+1,t=this.buffer[e];for(;t;)if(Zk.has(t))t=this.buffer[++e];else if(t==="%"&&Hp.has(this.buffer[e+1])&&Hp.has(this.buffer[e+2]))t=this.buffer[e+=3];else break;return yield*this.pushToIndex(e,!1)}}*pushNewline(){let e=this.buffer[this.pos];return e===`
|
|
151
151
|
`?yield*this.pushCount(1):e==="\r"&&this.charAt(1)===`
|
|
152
|
-
`?yield*this.pushCount(2):0}*pushSpaces(e){let t=this.pos-1,n;do n=this.buffer[++t];while(n===" "||e&&n===" ");let s=t-this.pos;return s>0&&(yield this.buffer.substr(this.pos,s),this.pos=t),s}*pushUntil(e){let t=this.pos,n=this.buffer[t];for(;!e(n);)n=this.buffer[++t];return yield*this.pushToIndex(t,!1)}};
|
|
152
|
+
`?yield*this.pushCount(2):0}*pushSpaces(e){let t=this.pos-1,n;do n=this.buffer[++t];while(n===" "||e&&n===" ");let s=t-this.pos;return s>0&&(yield this.buffer.substr(this.pos,s),this.pos=t),s}*pushUntil(e){let t=this.pos,n=this.buffer[t];for(;!e(n);)n=this.buffer[++t];return yield*this.pushToIndex(t,!1)}};Wp.Lexer=Lc});var Bc=T(Yp=>{"use strict";var Dc=class{constructor(){this.lineStarts=[],this.addNewLine=e=>this.lineStarts.push(e),this.linePos=e=>{let t=0,n=this.lineStarts.length;for(;t<n;){let i=t+n>>1;this.lineStarts[i]<e?t=i+1:n=i}if(this.lineStarts[t]===e)return{line:t+1,col:1};if(t===0)return{line:0,col:e};let s=this.lineStarts[t-1];return{line:t,col:e-s+1}}}};Yp.LineCounter=Dc});var Fc=T(Qp=>{"use strict";var tx=us("process"),Vp=ci(),rx=Mc();function dt(r,e){for(let t=0;t<r.length;++t)if(r[t].type===e)return!0;return!1}function Gp(r){for(let e=0;e<r.length;++e)switch(r[e].type){case"space":case"comment":case"newline":break;default:return e}return-1}function Xp(r){switch(r?.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"flow-collection":return!0;default:return!1}}function ui(r){switch(r.type){case"document":return r.start;case"block-map":{let e=r.items[r.items.length-1];return e.sep??e.start}case"block-seq":return r.items[r.items.length-1].start;default:return[]}}function pr(r){if(r.length===0)return[];let e=r.length;e:for(;--e>=0;)switch(r[e].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;r[++e]?.type==="space";);return r.splice(e,r.length)}function zp(r){if(r.start.type==="flow-seq-start")for(let e of r.items)e.sep&&!e.value&&!dt(e.start,"explicit-key-ind")&&!dt(e.sep,"map-value-ind")&&(e.key&&(e.value=e.key),delete e.key,Xp(e.value)?e.value.end?Array.prototype.push.apply(e.value.end,e.sep):e.value.end=e.sep:Array.prototype.push.apply(e.start,e.sep),delete e.sep)}var jc=class{constructor(e){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source="",this.type="",this.lexer=new rx.Lexer,this.onNewLine=e}*parse(e,t=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let n of this.lexer.lex(e,t))yield*this.next(n);t||(yield*this.end())}*next(e){if(this.source=e,tx.env.LOG_TOKENS&&console.log("|",Vp.prettyToken(e)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=e.length;return}let t=Vp.tokenType(e);if(t)if(t==="scalar")this.atNewLine=!1,this.atScalar=!0,this.type="scalar";else{switch(this.type=t,yield*this.step(),t){case"newline":this.atNewLine=!0,this.indent=0,this.onNewLine&&this.onNewLine(this.offset+e.length);break;case"space":this.atNewLine&&e[0]===" "&&(this.indent+=e.length);break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":this.atNewLine&&(this.indent+=e.length);break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=!1}this.offset+=e.length}else{let n=`Not a YAML token: ${e}`;yield*this.pop({type:"error",offset:this.offset,message:n,source:e}),this.offset+=e.length}}*end(){for(;this.stack.length>0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let e=this.peek(1);if(this.type==="doc-end"&&e?.type!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!e)return yield*this.stream();switch(e.type){case"document":return yield*this.document(e);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(e);case"block-scalar":return yield*this.blockScalar(e);case"block-map":return yield*this.blockMap(e);case"block-seq":return yield*this.blockSequence(e);case"flow-collection":return yield*this.flowCollection(e);case"doc-end":return yield*this.documentEnd(e)}yield*this.pop()}peek(e){return this.stack[this.stack.length-e]}*pop(e){let t=e??this.stack.pop();if(!t)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield t;else{let n=this.peek(1);switch(t.type==="block-scalar"?t.indent="indent"in n?n.indent:0:t.type==="flow-collection"&&n.type==="document"&&(t.indent=0),t.type==="flow-collection"&&zp(t),n.type){case"document":n.value=t;break;case"block-scalar":n.props.push(t);break;case"block-map":{let s=n.items[n.items.length-1];if(s.value){n.items.push({start:[],key:t,sep:[]}),this.onKeyLine=!0;return}else if(s.sep)s.value=t;else{Object.assign(s,{key:t,sep:[]}),this.onKeyLine=!s.explicitKey;return}break}case"block-seq":{let s=n.items[n.items.length-1];s.value?n.items.push({start:[],value:t}):s.value=t;break}case"flow-collection":{let s=n.items[n.items.length-1];!s||s.value?n.items.push({start:[],key:t,sep:[]}):s.sep?s.value=t:Object.assign(s,{key:t,sep:[]});return}default:yield*this.pop(),yield*this.pop(t)}if((n.type==="document"||n.type==="block-map"||n.type==="block-seq")&&(t.type==="block-map"||t.type==="block-seq")){let s=t.items[t.items.length-1];s&&!s.sep&&!s.value&&s.start.length>0&&Gp(s.start)===-1&&(t.indent===0||s.start.every(i=>i.type!=="comment"||i.indent<t.indent))&&(n.type==="document"?n.end=s.start:n.items.push({start:s.start}),t.items.splice(-1,1))}}}*stream(){switch(this.type){case"directive-line":yield{type:"directive",offset:this.offset,source:this.source};return;case"byte-order-mark":case"space":case"comment":case"newline":yield this.sourceToken;return;case"doc-mode":case"doc-start":{let e={type:"document",offset:this.offset,start:[]};this.type==="doc-start"&&e.start.push(this.sourceToken),this.stack.push(e);return}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(e){if(e.value)return yield*this.lineEnd(e);switch(this.type){case"doc-start":{Gp(e.start)!==-1?(yield*this.pop(),yield*this.step()):e.start.push(this.sourceToken);return}case"anchor":case"tag":case"space":case"comment":case"newline":e.start.push(this.sourceToken);return}let t=this.startBlockValue(e);t?this.stack.push(t):yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(e){if(this.type==="map-value-ind"){let t=ui(this.peek(2)),n=pr(t),s;e.end?(s=e.end,s.push(this.sourceToken),delete e.end):s=[this.sourceToken];let i={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:n,key:e,sep:s}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=i}else yield*this.lineEnd(e)}*blockScalar(e){switch(this.type){case"space":case"comment":case"newline":e.props.push(this.sourceToken);return;case"scalar":if(e.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let t=this.source.indexOf(`
|
|
153
153
|
`)+1;for(;t!==0;)this.onNewLine(this.offset+t),t=this.source.indexOf(`
|
|
154
|
-
`,t)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){let t=e.items[e.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,t.value){let n="end"in t.value?t.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type==="comment"?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else if(t.sep)t.sep.push(this.sourceToken);else{if(this.atIndentedComment(t.start,e.indent)){let s=e.items[e.items.length-2]?.value?.end;if(Array.isArray(s)){Array.prototype.push.apply(s,t.start),s.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return}if(this.indent>=e.indent){let n=!this.onKeyLine&&this.indent===e.indent,s=n&&(t.sep||t.explicitKey)&&this.type!=="seq-item-ind",i=[];if(s&&t.sep&&!t.value){let o=[];for(let a=0;a<t.sep.length;++a){let c=t.sep[a];switch(c.type){case"newline":o.push(a);break;case"space":break;case"comment":c.indent>e.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(i=t.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":s||t.value?(i.push(this.sourceToken),e.items.push({start:i}),this.onKeyLine=!0):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"explicit-key-ind":!t.sep&&!t.explicitKey?(t.start.push(this.sourceToken),t.explicitKey=!0):s||t.value?(i.push(this.sourceToken),e.items.push({start:i,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(t.explicitKey)if(t.sep)if(t.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(
|
|
154
|
+
`,t)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){let t=e.items[e.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,t.value){let n="end"in t.value?t.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type==="comment"?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else if(t.sep)t.sep.push(this.sourceToken);else{if(this.atIndentedComment(t.start,e.indent)){let s=e.items[e.items.length-2]?.value?.end;if(Array.isArray(s)){Array.prototype.push.apply(s,t.start),s.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return}if(this.indent>=e.indent){let n=!this.onKeyLine&&this.indent===e.indent,s=n&&(t.sep||t.explicitKey)&&this.type!=="seq-item-ind",i=[];if(s&&t.sep&&!t.value){let o=[];for(let a=0;a<t.sep.length;++a){let c=t.sep[a];switch(c.type){case"newline":o.push(a);break;case"space":break;case"comment":c.indent>e.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(i=t.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":s||t.value?(i.push(this.sourceToken),e.items.push({start:i}),this.onKeyLine=!0):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"explicit-key-ind":!t.sep&&!t.explicitKey?(t.start.push(this.sourceToken),t.explicitKey=!0):s||t.value?(i.push(this.sourceToken),e.items.push({start:i,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(t.explicitKey)if(t.sep)if(t.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(dt(t.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]});else if(Xp(t.key)&&!dt(t.sep,"newline")){let o=pr(t.start),a=t.key,c=t.sep;c.push(this.sourceToken),delete t.key,delete t.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:a,sep:c}]})}else i.length>0?t.sep=t.sep.concat(i,this.sourceToken):t.sep.push(this.sourceToken);else if(dt(t.start,"newline"))Object.assign(t,{key:null,sep:[this.sourceToken]});else{let o=pr(t.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]})}else t.sep?t.value||s?e.items.push({start:i,key:null,sep:[this.sourceToken]}):dt(t.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let o=this.flowScalar(this.type);s||t.value?(e.items.push({start:i,key:o,sep:[]}),this.onKeyLine=!0):t.sep?this.stack.push(o):(Object.assign(t,{key:o,sep:[]}),this.onKeyLine=!0);return}default:{let o=this.startBlockValue(e);if(o){if(o.type==="block-seq"){if(!t.explicitKey&&t.sep&&!dt(t.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else n&&e.items.push({start:i});this.stack.push(o);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){let t=e.items[e.items.length-1];switch(this.type){case"newline":if(t.value){let n="end"in t.value?t.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type==="comment"?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(t.start,e.indent)){let s=e.items[e.items.length-2]?.value?.end;if(Array.isArray(s)){Array.prototype.push.apply(s,t.start),s.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return;case"anchor":case"tag":if(t.value||this.indent<=e.indent)break;t.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==e.indent)break;t.value||dt(t.start,"seq-item-ind")?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return}if(this.indent>e.indent){let n=this.startBlockValue(e);if(n){this.stack.push(n);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){let t=e.items[e.items.length-1];if(this.type==="flow-error-end"){let n;do yield*this.pop(),n=this.peek(1);while(n?.type==="flow-collection")}else if(e.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!t||t.sep?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return;case"map-value-ind":!t||t.value?e.items.push({start:[],key:null,sep:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!t||t.value?e.items.push({start:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let s=this.flowScalar(this.type);!t||t.value?e.items.push({start:[],key:s,sep:[]}):t.sep?this.stack.push(s):Object.assign(t,{key:s,sep:[]});return}case"flow-map-end":case"flow-seq-end":e.end.push(this.sourceToken);return}let n=this.startBlockValue(e);n?this.stack.push(n):(yield*this.pop(),yield*this.step())}else{let n=this.peek(2);if(n.type==="block-map"&&(this.type==="map-value-ind"&&n.indent===e.indent||this.type==="newline"&&!n.items[n.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&n.type!=="flow-collection"){let s=ui(n),i=pr(s);zp(e);let o=e.end.splice(1,e.end.length);o.push(this.sourceToken);let a={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:i,key:e,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let t=this.source.indexOf(`
|
|
155
155
|
`)+1;for(;t!==0;)this.onNewLine(this.offset+t),t=this.source.indexOf(`
|
|
156
|
-
`,t)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let t=
|
|
157
|
-
`),t=e.trim();if(
|
|
156
|
+
`,t)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let t=ui(e),n=pr(t);return n.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let t=ui(e),n=pr(t);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){return this.type!=="comment"||this.indent<=t?!1:e.every(n=>n.type==="newline"||n.type==="space")}*documentEnd(e){this.type!=="doc-mode"&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};Qp.Parser=jc});var nm=T(kn=>{"use strict";var Zp=Tc(),nx=pn(),Sn=gn(),sx=Ea(),ix=F(),ox=Bc(),em=Fc();function tm(r){let e=r.prettyErrors!==!1;return{lineCounter:r.lineCounter||e&&new ox.LineCounter||null,prettyErrors:e}}function ax(r,e={}){let{lineCounter:t,prettyErrors:n}=tm(e),s=new em.Parser(t?.addNewLine),i=new Zp.Composer(e),o=Array.from(i.compose(s.parse(r)));if(n&&t)for(let a of o)a.errors.forEach(Sn.prettifyError(r,t)),a.warnings.forEach(Sn.prettifyError(r,t));return o.length>0?o:Object.assign([],{empty:!0},i.streamInfo())}function rm(r,e={}){let{lineCounter:t,prettyErrors:n}=tm(e),s=new em.Parser(t?.addNewLine),i=new Zp.Composer(e),o=null;for(let a of i.compose(s.parse(r),!0,r.length))if(!o)o=a;else if(o.options.logLevel!=="silent"){o.errors.push(new Sn.YAMLParseError(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return n&&t&&(o.errors.forEach(Sn.prettifyError(r,t)),o.warnings.forEach(Sn.prettifyError(r,t))),o}function cx(r,e,t){let n;typeof e=="function"?n=e:t===void 0&&e&&typeof e=="object"&&(t=e);let s=rm(r,t);if(!s)return null;if(s.warnings.forEach(i=>sx.warn(s.options.logLevel,i)),s.errors.length>0){if(s.options.logLevel!=="silent")throw s.errors[0];s.errors=[]}return s.toJS(Object.assign({reviver:n},t))}function lx(r,e,t){let n=null;if(typeof e=="function"||Array.isArray(e)?n=e:t===void 0&&e&&(t=e),typeof t=="string"&&(t=t.length),typeof t=="number"){let s=Math.round(t);t=s<1?void 0:s>8?{indent:8}:{indent:s}}if(r===void 0){let{keepUndefined:s}=t??e??{};if(!s)return}return ix.isDocument(r)&&!n?r.toString(t):new nx.Document(r,n,t).toString(t)}kn.parse=cx;kn.parseAllDocuments=ax;kn.parseDocument=rm;kn.stringify=lx});var im=T(q=>{"use strict";var ux=Tc(),dx=pn(),fx=oc(),qc=gn(),px=Gr(),ft=F(),mx=at(),hx=X(),gx=lt(),yx=ut(),bx=ci(),wx=Mc(),vx=Bc(),Sx=Fc(),di=nm(),sm=Hr();q.Composer=ux.Composer;q.Document=dx.Document;q.Schema=fx.Schema;q.YAMLError=qc.YAMLError;q.YAMLParseError=qc.YAMLParseError;q.YAMLWarning=qc.YAMLWarning;q.Alias=px.Alias;q.isAlias=ft.isAlias;q.isCollection=ft.isCollection;q.isDocument=ft.isDocument;q.isMap=ft.isMap;q.isNode=ft.isNode;q.isPair=ft.isPair;q.isScalar=ft.isScalar;q.isSeq=ft.isSeq;q.Pair=mx.Pair;q.Scalar=hx.Scalar;q.YAMLMap=gx.YAMLMap;q.YAMLSeq=yx.YAMLSeq;q.CST=bx;q.Lexer=wx.Lexer;q.LineCounter=vx.LineCounter;q.Parser=Sx.Parser;q.parse=di.parse;q.parseAllDocuments=di.parseAllDocuments;q.parseDocument=di.parseDocument;q.stringify=di.stringify;q.visit=sm.visit;q.visitAsync=sm.visitAsync});function xx(r){try{return JSON.parse(r.trim()),!0}catch{return!1}}function Ex(r){let e=r.trim();if(!e.startsWith("<"))return!1;let t=e.match(kx);return t?Kr(e,t[1])!==null:!1}function Ax(r){let e=r.trim();if(!e.match(/^(---|#|\w+:|-)/)||"[{<".includes(e[0]))return!1;try{let t=om.parse(e);return t!==null&&typeof t=="object"}catch{return!1}}function am(r){return xx(r)||Ex(r)||Ax(r)}var om,kx,Uc=v(()=>{gd();om=Nb(im(),1),kx=/<([a-zA-Z_][\w.-]*)/});function Tx(r){if(!r?.trim())return[];let e=r.replace(/\r\n/g,`
|
|
157
|
+
`),t=e.trim();if(am(t))return[{text:t,startLine:1,endLine:e.split(`
|
|
158
158
|
`).length}];let n=e.split(`
|
|
159
159
|
`),s=[],i=0,o=-1,a=0,c=()=>{if(o>=i){let l=n.slice(i,o+1).join(`
|
|
160
|
-
`).trim();l&&s.push({text:l,startLine:i+1,endLine:o+1})}};for(let l=0;l<n.length;l++)n[l].trim()?(a>=2&&o>=i&&(c(),i=l),a=0,o=l):a++;return c(),s}function
|
|
160
|
+
`).trim();l&&s.push({text:l,startLine:i+1,endLine:o+1})}};for(let l=0;l<n.length;l++)n[l].trim()?(a>=2&&o>=i&&(c(),i=l),a=0,o=l):a++;return c(),s}function fi(r){return Tx(r).map(e=>e.text)}var cm,lm=v(()=>{Uc();cm=`
|
|
161
161
|
|
|
162
162
|
|
|
163
|
-
`});var
|
|
164
|
-
`).length-1}));return n}function
|
|
165
|
-
`);for(let o=0;o<i.length;o++){let a=i[o],c=o+1;for(let l of
|
|
166
|
-
`)).filter(({root:n})=>!t.has(n)).map(({root:n,lineIndex:s})=>({type:"UNDECLARED_IMPORT",severity:"error",message:
|
|
163
|
+
`});var Ne=v(()=>{fs();ea();ad();ld();Uc();lm();ps()});function mr(r){return{...nd(r),server:r.files.get("server.ts")??""}}function pi(r){return!!r.server&&!r.code}var xn=v(()=>{Ne();Ne()});import{transform as Px}from"sucrase";function Jc(r,e={}){let t=e.serverOnly?["typescript"]:["typescript","jsx"];try{let{code:n}=Px(r,{transforms:t,jsxRuntime:"automatic",jsxImportSource:e.jsxImportSource||"react",production:!0});return{code:n}}catch(n){return{code:"",error:String(n)}}}var um=v(()=>{});function Rx(r){if(/^[./]/.test(r)||/^[a-z][a-z0-9+.-]*:/i.test(r))return null;let e=r.split("/");return r.startsWith("@")?e.slice(0,2).join("/"):e[0]}function dm(r){let e=[];for(let s of Cx)for(let i of r.matchAll(s)){let o=Rx(i[1]);o&&e.push({root:o,index:i.index??0})}e.sort((s,i)=>s.index-i.index);let t=new Set,n=[];for(let{root:s,index:i}of e)t.has(s)||(t.add(s),n.push({root:s,lineIndex:r.slice(0,i).split(`
|
|
164
|
+
`).length-1}));return n}function fm(r){return dm(r).map(e=>e.root)}function En(r,e){if(!r)return[];let{target:t,dependencies:n}=e,s=[],i=r.split(`
|
|
165
|
+
`);for(let o=0;o<i.length;o++){let a=i[o],c=o+1;for(let l of Ox)l.targets.includes(t)&&l.pattern.test(a)&&s.push({type:l.type,severity:"error",message:Ix(l.type,c),lineNumber:c,lineContent:a})}return t==="client"&&n&&s.push(..._x(i,n)),s}function _x(r,e){let t=new Set(Object.keys(e));return dm(r.join(`
|
|
166
|
+
`)).filter(({root:n})=>!t.has(n)).map(({root:n,lineIndex:s})=>({type:"UNDECLARED_IMPORT",severity:"error",message:Nx(n,s+1),lineNumber:s+1,lineContent:r[s]}))}function Nx(r,e){return`Import "${r}" is not declared in config.json dependencies! Found on line ${e}.
|
|
167
167
|
|
|
168
168
|
**CRITICAL**: Every bare import in code.tsx must be declared in the **config.json** "dependencies" block. A bulb that imports a package it doesn't declare is incomplete \u2014 it won't type-check, its versions aren't pinned, and it can't be reliably re-run or ported to typebulb.com.
|
|
169
169
|
|
|
@@ -177,7 +177,7 @@ ${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.pus
|
|
|
177
177
|
}
|
|
178
178
|
\`\`\`
|
|
179
179
|
|
|
180
|
-
**Fix:** Add a **config.json** block (or extend the existing one) with a "dependencies" entry for "${r}" \u2014 and for every other bare import in code.tsx. Pin a real version where you can (e.g. "react": "^19.2.7").`}function
|
|
180
|
+
**Fix:** Add a **config.json** block (or extend the existing one) with a "dependencies" entry for "${r}" \u2014 and for every other bare import in code.tsx. Pin a real version where you can (e.g. "react": "^19.2.7").`}function Ix(r,e){return r==="URL_IMPORT"?`Direct URL imports are not supported! Found on line ${e}.
|
|
181
181
|
|
|
182
182
|
**CRITICAL**: Import packages by name only. Do NOT use CDN URLs:
|
|
183
183
|
|
|
@@ -331,11 +331,11 @@ import { something } from 'module-name'
|
|
|
331
331
|
const something = require('module-name') // NOT SUPPORTED!
|
|
332
332
|
\`\`\`
|
|
333
333
|
|
|
334
|
-
**Fix:** Replace all \`require()\` calls with ES6 \`import\` statements at the top of the file.`}var Dt,
|
|
334
|
+
**Fix:** Replace all \`require()\` calls with ES6 \`import\` statements at the top of the file.`}var Mt,Dt,Ox,Cx,mi=v(()=>{Mt=["client"],Dt=["client","server"],Ox=[{type:"DYNAMIC_IMPORT",pattern:/\bimport\s*\(\s*['"`]/,targets:Mt},{type:"COMMONJS_REQUIRE",pattern:/\brequire\s*\(\s*['"`]/,targets:Dt},{type:"JS_EXTENSION_IMPORT",pattern:/from\s+['"][^'"]*\/[^'"]*\.js['"]/,targets:Mt},{type:"URL_IMPORT",pattern:/from\s+['"]https?:\/\//,targets:Mt},{type:"VERSION_SPECIFIER_IMPORT",pattern:/from\s+['"][^'"]*@[\d^~]/,targets:Mt},{type:"REDUNDANT_TB_DECLARATION",pattern:/declare\s+(const|var|let)\s+tb\b/,targets:Dt},{type:"CONST_ENUM",pattern:/\bconst\s+enum\b/,targets:Dt},{type:"NAMESPACE_DECLARATION",pattern:/\bnamespace\s+\w+/,targets:Dt},{type:"COMMONJS_EXPORT_EQUALS",pattern:/\bexport\s*=/,targets:Dt},{type:"COMMONJS_IMPORT_EQUALS",pattern:/\bimport\s+\w+\s*=/,targets:Dt},{type:"MODULE_DECLARATION",pattern:/\bmodule\s+\w+\s*\{/,targets:Dt},{type:"CSS_FILE_IMPORT",pattern:/(?:from|import)\s+['"][^'"]*\.css['"]/,targets:Mt},{type:"NAVIGATION",pattern:/window\.(location\.(reload|assign|replace)\s*\(|open\s*\()/,targets:Mt},{type:"NAVIGATION",pattern:/window\.location(\.href)?\s*=[^=]/,targets:Mt}],Cx=[/\bimport\s+(?:[^'";]*?from\s*)?['"]([^'"]+)['"]/g,/\bexport\s+[^'";]*?from\s*['"]([^'"]+)['"]/g]});function $x(r){return r.map(e=>`${e.type} (line ${e.lineNumber}): ${e.message.split(`
|
|
335
335
|
`)[0]}`).join(`
|
|
336
|
-
`)}function
|
|
337
|
-
${Sx(t)}`)}var sm=S(()=>{di()});var pt,An,Fc,Tn=S(()=>{pt="https://esm.sh",An="https://cdn.jsdelivr.net/npm/",Fc="https://data.jsdelivr.com/v1/package/npm/"});function im(r){let e=(r||"").replace(/^\/+/,"").replace(/\/+$/,"");return e?e.split("/"):[]}var B,gr,om,Pn=S(()=>{Tn();B=class r{constructor(e,t,n){let s=typeof e=="string"?r.parse(e):e;this.name=s.name,this.version=gr(t??s.version),this.subpath=gr(n??s.subpath)}static parse(e){let t=im(e||"");if(!t.length)return new r({name:""});if(t[0].startsWith("@")){let s=t[0],[i,o]=om(t[1]??""),a=gr(t.slice(2).join("/"));return new r({name:`${s}/${i}`,version:o,subpath:a})}else{let[s,i]=om(t[0]),o=gr(t.slice(1).join("/"));return new r({name:s,version:i,subpath:o})}}static fromUrl(e){try{let t=new URL(e),n=new URL(pt).host,s=new URL(An).host;if(t.host===n){let i=im(t.pathname.replace(/^\/v\d+\//,"/"));if(!i.length)return;let o=i[0].startsWith("@")?`${i[0]}/${i[1]??""}`:i[0];return r.parse(o)}if(t.host===s){let i=t.pathname.split("/npm/")[1];if(!i)return;let o=i.split("/")[0]||"";return r.parse(o)}return}catch{return}}format(){let e=this.version?`${this.name}@${this.version}`:this.name;return this.subpath?`${e}/${this.subpath}`:e}root(){return this.name}static rootOf(e){return r.parse(e).name}withVersion(e){return new r({name:this.name,version:gr(e),subpath:this.subpath})}static isBare(e){if(!e||e.startsWith(".")||e.startsWith("/"))return!1;let t=e.toLowerCase();return!t.startsWith("http://")&&!t.startsWith("https://")}},gr=r=>r&&r.length?r:void 0,om=r=>{let e=r.indexOf("@");return e<0?[r,void 0]:[r.slice(0,e),gr(r.slice(e+1))]}});async function fe(r){try{return await r()}catch{return}}var pi=S(()=>{});function jt(r){let e=r||"";return e.startsWith("./")?e.slice(2):e.replace(/^\/+/,"")}function qc(r){return r.startsWith("./")?r:`./${r}`}var On,Uc=S(()=>{Pn();pi();Tn();On=class{constructor(e,t){this.cache=e,this.http=t,this.pinMs=1e4,this.versionsIndexMs=1440*60*1e3,this.metaTtlMs=10080*60*1e3,this.pinCache=new Map}baseDir(e){let t=typeof e=="string"?new B(e):e;return`${An}${t.name}${t.version?`@${t.version}`:""}/`}file(e,t){return new URL(jt(t),this.baseDir(e)).toString()}packageJson(e){return this.file(e,"package.json")}buildEsmUrl(e,t={}){let{target:n="es2022",bundle:s=!1,external:i}=t,o=new URLSearchParams({target:n});return s&&o.append("bundle",""),i?.length&&o.append("external",i.join(",")),`${pt}/${e}?${o.toString()}`}async resolveExactVersion(e){let t=Date.now(),n=this.pinCache.get(e);if(n&&t-n.ts<this.pinMs)return n.value;let s=await this.tryResolveFromUrls([this.buildEsmUrl(e),`${pt}/${e}`]);return this.pinCache.set(e,{value:s,ts:t}),s}async tryResolveFromUrls(e){for(let t of e){let n=await fe(()=>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 fe(()=>this.http.getJson(`${Fc}${encodeURIComponent(e)}`));if(!n?.versions?.length){await this.cache.recordNegative(e);return}await this.cache.clearNegative(e);let s=n.tags&&Object.keys(n.tags).length?n.tags:void 0;return await this.cache.setIndex(e,n.versions,s),{versions:n.versions,distTags:s}}parseVersionFromUrl(e){let t=B.fromUrl(e)?.version;return t&&/\d+\.\d+\.\d+/.test(t)?t:void 0}async fetchPackageMeta(e,t){let n=await this.cache.getMeta(e,t);if(n&&Date.now()-n.updatedAt<this.metaTtlMs){let{dependencies:d,peerDependencies:u,peerDependenciesMeta:f}=n;return{name:e,version:t,dependencies:d,peerDependencies:u,peerDependenciesMeta:f}}let s=this.packageJson(new B(`${e}@${t}`)),i=await fe(()=>this.http.getJson(s));if(!i)return;let o=d=>d&&Object.keys(d).length?d:void 0,a=o(i.dependencies),c=o(i.peerDependencies),l=o(i.peerDependenciesMeta);return await this.cache.setMeta(e,t,a,c,l),{name:e,version:t,dependencies:a,peerDependencies:c,peerDependenciesMeta:l}}}});var am,Cn,Jc,kx,_n,mi=S(()=>{am=r=>r.startsWith("@types/"),Cn=r=>Object.keys(r?.peerDependencies||{}).filter(e=>!am(e)),Jc=r=>Object.keys(r?.dependencies||{}).filter(e=>!am(e)),kx=r=>Cn(r).filter(e=>!r?.peerDependenciesMeta?.[e]?.optional),_n=class{constructor(e){this.cdn=e}async resolve(e,t){let n=await this.fetchMeta(e),{allRoots:s,autoAddedPeers:i}=await this.expandWithPeers(n,t),o=this.computeFlags(s);return{allRoots:s,flags:o,autoAddedPeers:i}}async fetchMeta(e){return Promise.all(e.map(async({name:t,version:n})=>({name:t,version:n,meta:await this.cdn.fetchPackageMeta(t,n)})))}async expandWithPeers(e,t){let n=new Map(e.map(i=>[i.name,i])),s=[];for(let i of e)for(let o of kx(i.meta))!n.has(o)&&!s.some(a=>a.name===o)&&s.push({name:o,requiredBy:i.name});for(let{name:i,requiredBy:o}of s)try{let a=await t(i),c=await this.cdn.fetchPackageMeta(i,a);n.set(i,{name:i,version:a,meta:c})}catch(a){console.warn(`[typebulb] Failed to resolve peer "${i}" for "${o}":`,a)}return{allRoots:[...n.values()],autoAddedPeers:s.filter(i=>n.has(i.name))}}computeFlags(e){let t=new Set(e.flatMap(i=>Cn(i.meta))),n=new Map;for(let i of e)for(let o of Jc(i.meta))n.set(o,(n.get(o)||0)+1);let s=new Set([...n.entries()].filter(([,i])=>i>=2).map(([i])=>i));return new Map(e.map(i=>[i.name,{isPeerRoot:t.has(i.name),hasPeers:Cn(i.meta).length>0,isSharedDep:s.has(i.name)}]))}}});var Rn,Kc=S(()=>{Pn();pi();Rn=class{constructor(e,t,n){this.cache=e,this.cdn=t,this.semver=n}async learnExactVersion(e){let t=await fe(()=>this.cdn.fetchVersionsIndex(e));if(t?.versions?.length){let n=this.semver.selectBestVersion(t.versions,{distTags:t.distTags});if(n)return n}return this.cdn.resolveExactVersion(e)}async resolveExactForRoot(e,t){if(!t)return this.learnExactVersion(e);let n=await this.cache.getPinnedExact(e,t);if(n){if(this.semver.isExactVersion(n))return n;console.debug("[typebulb] cached version for",e,"is not exact (",n,"); re-resolving from registry")}let s=async o=>{if(o&&this.semver.isExactVersion(o))return await this.cache.setPinnedExact(e,t,o),o},i=await fe(()=>this.cdn.fetchVersionsIndex(e));if(i?.versions?.length){let o=this.semver.selectBestVersion(i.versions,{range:t,distTags:i.distTags});if(o){let a=await s(o);if(a)return a}else{console.debug("[typebulb] refreshing version cache for",e,"(",t,"not in cached set \u2014 likely a new release)"),await this.cache.invalidateVersionsCache(e);let a=await fe(()=>this.cdn.fetchVersionsIndex(e));if(a?.versions?.length){let c=await s(this.semver.selectBestVersion(a.versions,{range:t,distTags:a.distTags}));if(c)return c}}}return s(await this.cdn.resolveExactVersion(`${e}@${t}`))}async effectivePackage(e,t){let n=new B(e),s=n.root(),i=t[s],o=i?await fe(()=>this.resolveExactForRoot(s,i)):void 0;return{effectivePackage:o?n.withVersion(o).format():e,root:s,range:i,pinned:o}}}});import{init as xx,parse as Ex}from"es-module-lexer";var yr,Hc=S(()=>{Pn();Tn();mi();yr=class r{constructor(e,t,n){this.version=e,this.cdn=t,this.peer=n}extractImportsSync(e){let t=new Set;for(let n of r.importPatterns){n.lastIndex=0;for(let s of e.matchAll(n))B.isBare(s[1])&&t.add(s[1])}return Array.from(t)}async extractImports(e){let t=new Set,n=s=>{B.isBare(s)&&t.add(s)};try{await xx;let[s]=Ex(e);s.forEach(i=>n(e.slice(i.s,i.e).trim()))}catch{return this.extractImportsSync(e)}return Array.from(t)}async buildImportMap(e,t,n){let s=(await this.extractImports(e)).filter(u=>!n?.has(B.rootOf(u))),i=[...new Set(s.map(B.rootOf))],o=await Promise.all(i.map(async u=>({name:u,version:await this.resolveVersion(u,t)}))),{allRoots:a,flags:c,autoAddedPeers:l}=await this.peer.resolve(o,u=>this.resolveVersion(u,t)),d=this.buildEntries([...s,...l.map(u=>u.name)],a,c);return{importMap:{imports:Object.fromEntries(d)},prefetchUrls:d.map(([,u])=>u)}}async resolveVersion(e,t){let n=t[e],s=await this.version.resolveExactForRoot(e,n);if(!s)throw new Error(`Cannot resolve ${n?`${e}@${n}`:e}: no matching version is published (the package or version may not exist, or the registry was unreachable).`);return s}buildEntries(e,t,n){let s=new Map(t.map(p=>[p.name,p])),i=p=>{let b=s.get(B.rootOf(p));return new B(p).withVersion(b.version).format()},o=new Set([...n.entries()].filter(([,p])=>p.isPeerRoot||p.isSharedDep).map(([p])=>p)),a=new Set(e.filter(p=>p!==B.rootOf(p)).map(B.rootOf)),c=[],l=new Set,d=new Set(e.filter(p=>p===B.rootOf(p))),u=new Set;for(let p of e){let b=B.rootOf(p),m=s.get(b),{isPeerRoot:g,hasPeers:x,isSharedDep:A}=n.get(b),P=a.has(b),R=p!==b,O=!(g||A)&&(P||!x),$=this.singletonDepsOf(m,o),E=R&&d.has(b);E&&u.add(b);let y=E?[...$,b]:$.length?$:void 0;c.push([p,this.cdn.buildEsmUrl(i(p),{bundle:O,external:y})]),l.add(p)}let f=new Set([...o,...u]);for(let p of f)s.has(p)&&(l.has(p)||c.push([p,this.cdn.buildEsmUrl(i(p),{})]),c.push([`${p}/`,`${pt}/${i(p)}/`]));return c}singletonDepsOf(e,t){return[...new Set([...Cn(e.meta),...Jc(e.meta)])].filter(n=>t.has(n))}};yr.importPatterns=[/\bimport\s+(?:[^'";]*?from\s*)?['"]([^'"]+)['"]/g,/\bexport\s+[^'";]*?from\s*['"]([^'"]+)['"]/g]});import{gt as cm,satisfies as Ax,maxSatisfying as lm,major as Tx,valid as Px}from"semver";var hi,Ft,Wc=S(()=>{hi=class{cmp(e,t){return e===t?0:cm(e,t)?1:cm(t,e)?-1:0}satisfies(e,t){return!e||!e.trim()?!0:!!Ax(t,e,{includePrerelease:!0})}selectBestVersion(e,t){if(!e?.length)return;let n=t?.range?.trim()||"*",s=t?.preferStable??!0,i=t?.distTags?.latest;if(i&&e.includes(i)&&this.satisfies(n,i))return i;if(s){let a=lm(e,n,{includePrerelease:!1});if(a)return a}return lm(e,n,{includePrerelease:!0})??void 0}majorOf(e){return Tx(e)}isExactVersion(e){return Px(e)!==null}},Ft=new hi});function Ox(r){return Math.min(9e5*Math.pow(2,Math.max(0,r-1)),864e5)}var qt,um=S(()=>{pi();qt=class{constructor(e){this.store=e}async isNegative(e){let t=await fe(()=>this.store.get(e));return!!t&&t.until>Date.now()}async recordNegative(e){let n=((await fe(()=>this.store.get(e)))?.attempts||0)+1;await fe(()=>this.store.set(e,{until:Date.now()+Ox(n),attempts:n}))}async clearNegative(e){await fe(()=>this.store.delete(e))}}});function fm(r,e){let t=new On(r,e),n=new _n(t),s=new Rn(r,t,Ft);return{packageService:new yr(s,t,n),versionResolver:s,cdnClient:t,peerResolver:n}}var Ke=S(()=>{Uc();mi();Kc();Hc();Wc();Pn();Wc();Tn();Uc();mi();Kc();Hc();um()});import*as Yc from"fs/promises";import*as dm from"crypto";function ke(r){return dm.createHash("sha1").update(r).digest("hex")}async function He(r){try{return JSON.parse(await Yc.readFile(r,"utf8"))}catch{return}}async function gi(r){try{return await Yc.readFile(r,"utf8")}catch{return}}var br=S(()=>{});import*as ht from"fs/promises";import*as We from"path";import*as mm from"os";function G(){return Vc||(Vc=_x()),Vc}function bi(r,e){return We.join(Cx,ke(r),e)}async function _x(){await ht.mkdir(mt,{recursive:!0});let r=We.join(mt,"version.json");if((await He(r))?.version===pm)return;let t=await ht.readdir(mt).catch(()=>[]);await Promise.all(t.map(n=>ht.rm(We.join(mt,n),{recursive:!0,force:!0}))),await ht.writeFile(r,JSON.stringify({version:pm})+`
|
|
338
|
-
`,"utf8")}var
|
|
336
|
+
`)}function pm(r,e){let t=En(r,{target:"client",dependencies:e}).filter(n=>n.type==="UNDECLARED_IMPORT");if(t.length)throw new Error(`Lint failed:
|
|
337
|
+
${$x(t)}`)}var mm=v(()=>{mi()});var pt,An,Kc,Tn=v(()=>{pt="https://esm.sh",An="https://cdn.jsdelivr.net/npm/",Kc="https://data.jsdelivr.com/v1/package/npm/"});function hm(r){let e=(r||"").replace(/^\/+/,"").replace(/\/+$/,"");return e?e.split("/"):[]}var B,hr,gm,Pn=v(()=>{Tn();B=class r{constructor(e,t,n){let s=typeof e=="string"?r.parse(e):e;this.name=s.name,this.version=hr(t??s.version),this.subpath=hr(n??s.subpath)}static parse(e){let t=hm(e||"");if(!t.length)return new r({name:""});if(t[0].startsWith("@")){let s=t[0],[i,o]=gm(t[1]??""),a=hr(t.slice(2).join("/"));return new r({name:`${s}/${i}`,version:o,subpath:a})}else{let[s,i]=gm(t[0]),o=hr(t.slice(1).join("/"));return new r({name:s,version:i,subpath:o})}}static fromUrl(e){try{let t=new URL(e),n=new URL(pt).host,s=new URL(An).host;if(t.host===n){let i=hm(t.pathname.replace(/^\/v\d+\//,"/"));if(!i.length)return;let o=i[0].startsWith("@")?`${i[0]}/${i[1]??""}`:i[0];return r.parse(o)}if(t.host===s){let i=t.pathname.split("/npm/")[1];if(!i)return;let o=i.split("/")[0]||"";return r.parse(o)}return}catch{return}}format(){let e=this.version?`${this.name}@${this.version}`:this.name;return this.subpath?`${e}/${this.subpath}`:e}root(){return this.name}static rootOf(e){return r.parse(e).name}withVersion(e){return new r({name:this.name,version:hr(e),subpath:this.subpath})}static isBare(e){if(!e||e.startsWith(".")||e.startsWith("/"))return!1;let t=e.toLowerCase();return!t.startsWith("http://")&&!t.startsWith("https://")}},hr=r=>r&&r.length?r:void 0,gm=r=>{let e=r.indexOf("@");return e<0?[r,void 0]:[r.slice(0,e),hr(r.slice(e+1))]}});async function de(r){try{return await r()}catch{return}}var hi=v(()=>{});function Bt(r){let e=r||"";return e.startsWith("./")?e.slice(2):e.replace(/^\/+/,"")}function Hc(r){return r.startsWith("./")?r:`./${r}`}var On,Wc=v(()=>{Pn();hi();Tn();On=class{constructor(e,t){this.cache=e,this.http=t,this.pinMs=1e4,this.versionsIndexMs=1440*60*1e3,this.metaTtlMs=10080*60*1e3,this.pinCache=new Map}baseDir(e){let t=typeof e=="string"?new B(e):e;return`${An}${t.name}${t.version?`@${t.version}`:""}/`}file(e,t){return new URL(Bt(t),this.baseDir(e)).toString()}packageJson(e){return this.file(e,"package.json")}buildEsmUrl(e,t={}){let{target:n="es2022",bundle:s=!1,external:i}=t,o=new URLSearchParams({target:n});return s&&o.append("bundle",""),i?.length&&o.append("external",i.join(",")),`${pt}/${e}?${o.toString()}`}async resolveExactVersion(e){let t=Date.now(),n=this.pinCache.get(e);if(n&&t-n.ts<this.pinMs)return n.value;let s=await this.tryResolveFromUrls([this.buildEsmUrl(e),`${pt}/${e}`]);return this.pinCache.set(e,{value:s,ts:t}),s}async tryResolveFromUrls(e){for(let t of e){let n=await de(()=>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 de(()=>this.http.getJson(`${Kc}${encodeURIComponent(e)}`));if(!n?.versions?.length){await this.cache.recordNegative(e);return}await this.cache.clearNegative(e);let s=n.tags&&Object.keys(n.tags).length?n.tags:void 0;return await this.cache.setIndex(e,n.versions,s),{versions:n.versions,distTags:s}}parseVersionFromUrl(e){let t=B.fromUrl(e)?.version;return t&&/\d+\.\d+\.\d+/.test(t)?t:void 0}async fetchPackageMeta(e,t){let n=await this.cache.getMeta(e,t);if(n&&Date.now()-n.updatedAt<this.metaTtlMs){let{dependencies:f,peerDependencies:u,peerDependenciesMeta:d}=n;return{name:e,version:t,dependencies:f,peerDependencies:u,peerDependenciesMeta:d}}let s=this.packageJson(new B(`${e}@${t}`)),i=await de(()=>this.http.getJson(s));if(!i)return;let o=f=>f&&Object.keys(f).length?f:void 0,a=o(i.dependencies),c=o(i.peerDependencies),l=o(i.peerDependenciesMeta);return await this.cache.setMeta(e,t,a,c,l),{name:e,version:t,dependencies:a,peerDependencies:c,peerDependenciesMeta:l}}}});var ym,Cn,Yc,Lx,Rn,gi=v(()=>{ym=r=>r.startsWith("@types/"),Cn=r=>Object.keys(r?.peerDependencies||{}).filter(e=>!ym(e)),Yc=r=>Object.keys(r?.dependencies||{}).filter(e=>!ym(e)),Lx=r=>Cn(r).filter(e=>!r?.peerDependenciesMeta?.[e]?.optional),Rn=class{constructor(e){this.cdn=e}async resolve(e,t){let n=await this.fetchMeta(e),{allRoots:s,autoAddedPeers:i}=await this.expandWithPeers(n,t),o=this.computeFlags(s);return{allRoots:s,flags:o,autoAddedPeers:i}}async fetchMeta(e){return Promise.all(e.map(async({name:t,version:n})=>({name:t,version:n,meta:await this.cdn.fetchPackageMeta(t,n)})))}async expandWithPeers(e,t){let n=new Map(e.map(i=>[i.name,i])),s=[];for(let i of e)for(let o of Lx(i.meta))!n.has(o)&&!s.some(a=>a.name===o)&&s.push({name:o,requiredBy:i.name});for(let{name:i,requiredBy:o}of s)try{let a=await t(i),c=await this.cdn.fetchPackageMeta(i,a);n.set(i,{name:i,version:a,meta:c})}catch(a){console.warn(`[typebulb] Failed to resolve peer "${i}" for "${o}":`,a)}return{allRoots:[...n.values()],autoAddedPeers:s.filter(i=>n.has(i.name))}}computeFlags(e){let t=new Set(e.flatMap(i=>Cn(i.meta))),n=new Map;for(let i of e)for(let o of Yc(i.meta))n.set(o,(n.get(o)||0)+1);let s=new Set([...n.entries()].filter(([,i])=>i>=2).map(([i])=>i));return new Map(e.map(i=>[i.name,{isPeerRoot:t.has(i.name),hasPeers:Cn(i.meta).length>0,isSharedDep:s.has(i.name)}]))}}});var _n,Vc=v(()=>{Pn();hi();_n=class{constructor(e,t,n){this.cache=e,this.cdn=t,this.semver=n}async learnExactVersion(e){let t=await de(()=>this.cdn.fetchVersionsIndex(e));if(t?.versions?.length){let n=this.semver.selectBestVersion(t.versions,{distTags:t.distTags});if(n)return n}return this.cdn.resolveExactVersion(e)}async resolveExactForRoot(e,t){if(!t)return this.learnExactVersion(e);let n=await this.cache.getPinnedExact(e,t);if(n){if(this.semver.isExactVersion(n))return n;console.debug("[typebulb] cached version for",e,"is not exact (",n,"); re-resolving from registry")}let s=async o=>{if(o&&this.semver.isExactVersion(o))return await this.cache.setPinnedExact(e,t,o),o},i=await de(()=>this.cdn.fetchVersionsIndex(e));if(i?.versions?.length){let o=this.semver.selectBestVersion(i.versions,{range:t,distTags:i.distTags});if(o){let a=await s(o);if(a)return a}else{console.debug("[typebulb] refreshing version cache for",e,"(",t,"not in cached set \u2014 likely a new release)"),await this.cache.invalidateVersionsCache(e);let a=await de(()=>this.cdn.fetchVersionsIndex(e));if(a?.versions?.length){let c=await s(this.semver.selectBestVersion(a.versions,{range:t,distTags:a.distTags}));if(c)return c}}}return s(await this.cdn.resolveExactVersion(`${e}@${t}`))}async effectivePackage(e,t){let n=new B(e),s=n.root(),i=t[s],o=i?await de(()=>this.resolveExactForRoot(s,i)):void 0;return{effectivePackage:o?n.withVersion(o).format():e,root:s,range:i,pinned:o}}}});import{init as Mx,parse as Dx}from"es-module-lexer";var gr,Gc=v(()=>{Pn();Tn();gi();gr=class r{constructor(e,t,n){this.version=e,this.cdn=t,this.peer=n}extractImportsSync(e){let t=new Set;for(let n of r.importPatterns){n.lastIndex=0;for(let s of e.matchAll(n))B.isBare(s[1])&&t.add(s[1])}return Array.from(t)}async extractImports(e){let t=new Set,n=s=>{B.isBare(s)&&t.add(s)};try{await Mx;let[s]=Dx(e);s.forEach(i=>n(e.slice(i.s,i.e).trim()))}catch{return this.extractImportsSync(e)}return Array.from(t)}async buildImportMap(e,t,n){let s=(await this.extractImports(e)).filter(u=>!n?.has(B.rootOf(u))),i=[...new Set(s.map(B.rootOf))],o=await Promise.all(i.map(async u=>({name:u,version:await this.resolveVersion(u,t)}))),{allRoots:a,flags:c,autoAddedPeers:l}=await this.peer.resolve(o,u=>this.resolveVersion(u,t)),f=this.buildEntries([...s,...l.map(u=>u.name)],a,c);return{importMap:{imports:Object.fromEntries(f)},prefetchUrls:f.map(([,u])=>u)}}async resolveVersion(e,t){let n=t[e],s=await this.version.resolveExactForRoot(e,n);if(!s)throw new Error(`Cannot resolve ${n?`${e}@${n}`:e}: no matching version is published (the package or version may not exist, or the registry was unreachable).`);return s}buildEntries(e,t,n){let s=new Map(t.map(p=>[p.name,p])),i=p=>{let b=s.get(B.rootOf(p));return new B(p).withVersion(b.version).format()},o=new Set([...n.entries()].filter(([,p])=>p.isPeerRoot||p.isSharedDep).map(([p])=>p)),a=new Set(e.filter(p=>p!==B.rootOf(p)).map(B.rootOf)),c=[],l=new Set,f=new Set(e.filter(p=>p===B.rootOf(p))),u=new Set;for(let p of e){let b=B.rootOf(p),m=s.get(b),{isPeerRoot:g,hasPeers:x,isSharedDep:A}=n.get(b),P=a.has(b),_=p!==b,C=!(g||A)&&(P||!x),I=this.singletonDepsOf(m,o),E=_&&f.has(b);E&&u.add(b);let y=E?[...I,b]:I.length?I:void 0;c.push([p,this.cdn.buildEsmUrl(i(p),{bundle:C,external:y})]),l.add(p)}let d=new Set([...o,...u]);for(let p of d)s.has(p)&&(l.has(p)||c.push([p,this.cdn.buildEsmUrl(i(p),{})]),c.push([`${p}/`,`${pt}/${i(p)}/`]));return c}singletonDepsOf(e,t){return[...new Set([...Cn(e.meta),...Yc(e.meta)])].filter(n=>t.has(n))}};gr.importPatterns=[/\bimport\s+(?:[^'";]*?from\s*)?['"]([^'"]+)['"]/g,/\bexport\s+[^'";]*?from\s*['"]([^'"]+)['"]/g]});import{gt as bm,satisfies as Bx,maxSatisfying as wm,major as jx,valid as Fx}from"semver";var yi,jt,zc=v(()=>{yi=class{cmp(e,t){return e===t?0:bm(e,t)?1:bm(t,e)?-1:0}satisfies(e,t){return!e||!e.trim()?!0:!!Bx(t,e,{includePrerelease:!0})}selectBestVersion(e,t){if(!e?.length)return;let n=t?.range?.trim()||"*",s=t?.preferStable??!0,i=t?.distTags?.latest;if(i&&e.includes(i)&&this.satisfies(n,i))return i;if(s){let a=wm(e,n,{includePrerelease:!1});if(a)return a}return wm(e,n,{includePrerelease:!0})??void 0}majorOf(e){return jx(e)}isExactVersion(e){return Fx(e)!==null}},jt=new yi});function qx(r){return Math.min(9e5*Math.pow(2,Math.max(0,r-1)),864e5)}var Ft,vm=v(()=>{hi();Ft=class{constructor(e){this.store=e}async isNegative(e){let t=await de(()=>this.store.get(e));return!!t&&t.until>Date.now()}async recordNegative(e){let n=((await de(()=>this.store.get(e)))?.attempts||0)+1;await de(()=>this.store.set(e,{until:Date.now()+qx(n),attempts:n}))}async clearNegative(e){await de(()=>this.store.delete(e))}}});function Sm(r,e){let t=new On(r,e),n=new Rn(t),s=new _n(r,t,jt);return{packageService:new gr(s,t,n),versionResolver:s,cdnClient:t,peerResolver:n}}var He=v(()=>{Wc();gi();Vc();Gc();zc();Pn();zc();Tn();Wc();gi();Vc();Gc();vm()});import*as Xc from"fs/promises";import*as km from"crypto";function ke(r){return km.createHash("sha1").update(r).digest("hex")}async function We(r){try{return JSON.parse(await Xc.readFile(r,"utf8"))}catch{return}}async function bi(r){try{return await Xc.readFile(r,"utf8")}catch{return}}var yr=v(()=>{});import*as ht from"fs/promises";import*as Ye from"path";import*as Em from"os";function G(){return Qc||(Qc=Jx()),Qc}function vi(r,e){return Ye.join(Ux,ke(r),e)}async function Jx(){await ht.mkdir(mt,{recursive:!0});let r=Ye.join(mt,"version.json");if((await We(r))?.version===xm)return;let t=await ht.readdir(mt).catch(()=>[]);await Promise.all(t.map(n=>ht.rm(Ye.join(mt,n),{recursive:!0,force:!0}))),await ht.writeFile(r,JSON.stringify({version:xm})+`
|
|
338
|
+
`,"utf8")}var xm,mt,Nn,In,wi,Ux,Qc,br=v(()=>{yr();xm=1,mt=Ye.join(Em.homedir(),".typebulb","cache"),Nn=Ye.join(mt,"packages"),In=Ye.join(mt,"proxy"),wi=Ye.join(mt,"dts"),Ux=Ye.join(mt,"emit")});import*as gt from"fs/promises";import*as Am from"path";async function he(r,e){await gt.mkdir(Am.dirname(r),{recursive:!0});let t=`${r}.tmp-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;await gt.writeFile(t,e,"utf8"),await gt.rename(t,r).catch(async n=>{throw await gt.rm(t,{force:!0}).catch(()=>{}),n})}var $n=v(()=>{});var wr,Zc=v(()=>{$n();yr();wr=class{constructor(e){this.filePath=e}mem;loadPromise;load(){return this.mem?Promise.resolve(this.mem):(this.loadPromise||(this.loadPromise=We(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 he(this.filePath,JSON.stringify(Object.fromEntries(e)))}}});import*as Om from"fs/promises";import*as xe from"path";function Pm(r,e){return xe.join(Kx,Si(r),encodeURIComponent(e)+".json")}function Si(r){return r.replace(/\//g,"__")}var el,Tm,Kx,Hx,ki,Cm=v(()=>{He();br();$n();Zc();yr();el=xe.join(Nn,"indexes"),Tm=xe.join(Nn,"pinned"),Kx=xe.join(Nn,"meta"),Hx=xe.join(Nn,"negative.json"),ki=class{pinnedMem=new Map;indexMem=new Map;metaMem=new Map;negativeCache=new Ft(new wr(Hx));async getPinnedExact(e,t){let n=`${e}@${t}`;if(this.pinnedMem.has(n))return this.pinnedMem.get(n);await G();let s=await bi(xe.join(Tm,ke(n)+".txt"));return this.pinnedMem.set(n,s),s}async setPinnedExact(e,t,n){let s=`${e}@${t}`;this.pinnedMem.set(s,n),await G(),await he(xe.join(Tm,ke(s)+".txt"),n)}async getIndex(e){if(this.indexMem.has(e))return this.indexMem.get(e);await G();let t=await We(xe.join(el,Si(e)+".json"));return this.indexMem.set(e,t),t}async setIndex(e,t,n){let s={versions:t,distTags:n,updatedAt:Date.now()};this.indexMem.set(e,s),await G(),await he(xe.join(el,Si(e)+".json"),JSON.stringify(s))}async invalidateVersionsCache(e){this.indexMem.delete(e),await Om.rm(xe.join(el,Si(e)+".json"),{force:!0})}async isNegative(e){return await G(),this.negativeCache.isNegative(e)}async recordNegative(e){await G(),await this.negativeCache.recordNegative(e)}async clearNegative(e){await this.negativeCache.clearNegative(e)}async getMeta(e,t){let n=`${e}@${t}`;if(this.metaMem.has(n))return this.metaMem.get(n);await G();let s=await We(Pm(e,t));return this.metaMem.set(n,s),s}async setMeta(e,t,n,s,i){let o={dependencies:n,peerDependencies:s,peerDependenciesMeta:i,updatedAt:Date.now()};this.metaMem.set(`${e}@${t}`,o),await G(),await he(Pm(e,t),JSON.stringify(o))}}});var Rm,_m=v(()=>{Rm={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 Wx,xi,Nm,Im,W_,tl=v(()=>{He();Cm();_m();Wx=new ki,{packageService:xi,versionResolver:Nm,cdnClient:Im,peerResolver:W_}=Sm(Wx,Rm)});var $m,Lm=v(()=>{$m=`
|
|
339
339
|
(() => {
|
|
340
340
|
// Embedded (bulb-in-a-bulb): runs inside a sandboxed iframe with no parent
|
|
341
341
|
// bridge, so privileged tb.* (AI, fs, server RPC) can't reach a host and would
|
|
@@ -824,14 +824,14 @@ ${Sx(t)}`)}var sm=S(()=>{di()});var pt,An,Fc,Tn=S(()=>{pt="https://esm.sh",An="h
|
|
|
824
824
|
};
|
|
825
825
|
}
|
|
826
826
|
})();
|
|
827
|
-
`});function
|
|
827
|
+
`});function Ei(r){return r.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function Ti(r,e){return` <script>
|
|
828
828
|
(function() {
|
|
829
829
|
try {
|
|
830
|
-
var KEY = ${
|
|
830
|
+
var KEY = ${qt(JSON.stringify("tb-theme:"+r))};
|
|
831
831
|
var doc = document.documentElement;
|
|
832
832
|
var mq = window.matchMedia('(prefers-color-scheme: dark)');
|
|
833
833
|
var os = function() { return mq.matches ? 'dark' : 'light'; };
|
|
834
|
-
var FORCED = ${
|
|
834
|
+
var FORCED = ${qt(JSON.stringify(e??null))};
|
|
835
835
|
var stored = function() {
|
|
836
836
|
try { var v = localStorage.getItem(KEY); return (v === 'dark' || v === 'light') ? v : undefined; }
|
|
837
837
|
catch (e) { return undefined; }
|
|
@@ -859,23 +859,23 @@ ${Sx(t)}`)}var sm=S(()=>{di()});var pt,An,Fc,Tn=S(()=>{pt="https://esm.sh",An="h
|
|
|
859
859
|
});
|
|
860
860
|
} catch (e) {}
|
|
861
861
|
})();
|
|
862
|
-
</script>`}var
|
|
862
|
+
</script>`}var qt,Ai,rl=v(()=>{qt=r=>r.replace(/<\/script/gi,"<\\/script");Ai=` *, *::before, *::after { box-sizing: border-box; }
|
|
863
863
|
canvas { max-width: 100%; }
|
|
864
864
|
body { margin: 0; display: flow-root; font-family: system-ui, -apple-system, sans-serif; }
|
|
865
865
|
html[data-theme="dark"] { color-scheme: dark; }
|
|
866
|
-
html[data-theme="light"] { color-scheme: light; }`});function
|
|
867
|
-
html, body { height: 100%; }`,p={imports:
|
|
866
|
+
html[data-theme="light"] { color-scheme: light; }`});function Mm(r){let{name:e,code:t,css:n,html:s,data:i,insight:o,importMap:a,theme:c,embedded:l,dir:f}=r,u=s.trim()||'<div id="app"></div>',d=l?"":`
|
|
867
|
+
html, body { height: 100%; }`,p={imports:Vx(a.imports)};return`<!DOCTYPE html>
|
|
868
868
|
<html>
|
|
869
869
|
<head>
|
|
870
870
|
<meta charset="utf-8">
|
|
871
871
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
872
|
-
<title>${
|
|
873
|
-
${
|
|
872
|
+
<title>${Ei(e)} - typebulb</title>
|
|
873
|
+
${Ti(e,c)}
|
|
874
874
|
<script type="importmap">
|
|
875
875
|
${JSON.stringify(p,null,2)}
|
|
876
876
|
</script>
|
|
877
877
|
<style>
|
|
878
|
-
${
|
|
878
|
+
${Ai}${d}
|
|
879
879
|
</style>
|
|
880
880
|
<style>
|
|
881
881
|
${n}
|
|
@@ -884,23 +884,23 @@ ${n}
|
|
|
884
884
|
<body>
|
|
885
885
|
${u}
|
|
886
886
|
|
|
887
|
-
${i.length>0?`<script>window.__TB_DATA__ = ${
|
|
888
|
-
${o?`<script>window.__TB_INSIGHT__ = ${
|
|
889
|
-
${
|
|
887
|
+
${i.length>0?`<script>window.__TB_DATA__ = ${qt(JSON.stringify(i))};</script>`:""}
|
|
888
|
+
${o?`<script>window.__TB_INSIGHT__ = ${qt(JSON.stringify(o))};</script>`:""}
|
|
889
|
+
${f?`<script>window.__TB_DIR__ = ${qt(JSON.stringify(f))};</script>`:""}
|
|
890
890
|
|
|
891
891
|
<script>
|
|
892
|
-
${
|
|
892
|
+
${$m}
|
|
893
893
|
</script>
|
|
894
894
|
|
|
895
|
-
${
|
|
895
|
+
${Yx}
|
|
896
896
|
|
|
897
897
|
<script type="module">
|
|
898
898
|
globalThis.__tbEntryRan = true; /* import graph resolved \u2014 the load-failure backstop's signal (imports hoist above this line) */
|
|
899
899
|
await globalThis.__tbBoot; /* #tb= fragment restore, set by the shim when present (TB-Inference.md) */
|
|
900
|
-
${
|
|
900
|
+
${qt(t)}
|
|
901
901
|
</script>
|
|
902
902
|
</body>
|
|
903
|
-
</html>`}function
|
|
903
|
+
</html>`}function Vx(r){let e={};for(let[t,n]of Object.entries(r))e[t]=n.startsWith("https://")?"/proxy/"+n:n;return e}var Yx,Dm=v(()=>{Lm();rl();Yx=`<script>
|
|
904
904
|
(function () {
|
|
905
905
|
var framed = window.parent !== window;
|
|
906
906
|
var post = function (m) { try { parent.postMessage(m, '*'); } catch (e) {} }; /* framed only */
|
|
@@ -996,22 +996,22 @@ ${Ut(t)}
|
|
|
996
996
|
}
|
|
997
997
|
});
|
|
998
998
|
})();
|
|
999
|
-
</script>`});import*as
|
|
1000
|
-
Use a plain name with an exact / caret / tilde range (e.g. three@^0.160.0).`);await
|
|
999
|
+
</script>`});import*as Oi from"fs/promises";import*as Pi from"path";import{existsSync as Bm,readFileSync as Gx}from"fs";import{execFile as zx}from"child_process";import{promisify as Xx}from"util";import{satisfies as Qx}from"semver";async function Ci(r,e,t,n){let i=r.map(l=>t0(l,t)).filter(l=>!r0(l,e));if(i.length===0)return;let o=i.filter(l=>!e0.test(l));if(o.length)throw new Error(`Refusing to install npm spec(s) with unsupported characters: ${o.join(", ")}
|
|
1000
|
+
Use a plain name with an exact / caret / tilde range (e.g. three@^0.160.0).`);await Oi.mkdir(e,{recursive:!0});let a=Pi.join(e,"package.json");Bm(a)||await Oi.writeFile(a,JSON.stringify({name:"typebulb-server",private:!0})),console.log(` Installing: ${i.join(", ")}`);let c=["--no-audit","--no-fund",...n?.ignoreScripts?["--ignore-scripts"]:[]];await Zx("npm",["install",...c,...i],{cwd:e,shell:!0})}function t0(r,e){if(!e||B.parse(r).version)return r;let t=e[r];return t?`${r}@${t}`:r}function r0(r,e){let{name:t,version:n}=B.parse(r),s=Pi.join(e,"node_modules",t);if(!Bm(s))return!1;if(!n)return!0;try{let i=JSON.parse(Gx(Pi.join(s,"package.json"),"utf-8")).version;return Qx(i,n)}catch{return!1}}function Ri(r){let e=new Set,t=/\bimport\s+(?:[\s\S]*?\s+from\s+)?['"]([^./][^'"]*)['"]/g,n;for(;n=t.exec(r);){let s=n[1];s.includes(":")||e.add(B.rootOf(s))}return[...e]}var Zx,e0,nl=v(()=>{He();Zx=Xx(zx),e0=/^(@[a-z0-9._-]+\/)?[a-z0-9._-]+(@[a-zA-Z0-9.^~*x-]+)?$/i});var jm=v(()=>{});var pe,Ee,vr=v(()=>{pe=class extends Error{constructor(e,t="unknown",n=!1){super(e),this.code=t,this.retryable=n}},Ee=class{getPath(e,t){return this.path}parseError(e,t){return this.parseJsonError(e,t)}parseStreamChunk(e){return this.checkAndThrowError(e),this.parseProviderStreamChunk(e)}extractSystemMessages(e,t=`
|
|
1001
1001
|
|
|
1002
|
-
`){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){if(!e)return{message:`HTTP ${t}`};try{let n=JSON.parse(e);return n.error&&typeof n.error=="object"?{message:n.error.message||`HTTP ${t}`,type:n.error.type}:n.message?{message:n.message}:{message:e}}catch{return{message:e}}}checkAndThrowError(e){if(typeof e!="object"||e===null)return;let t=e;if(t.type==="error"&&"message"in t){let n=t.code||"unknown";throw new pe(t.message,n,!!t.retryable)}if(t.error){let n=t.error,s=typeof n=="object"&&n!==null?String(n.type??n.code??""):"",i=/rate_limit|too_many_requests/i.test(s),o=/overloaded|server_error|unavailable/i.test(s),a=/context_length/i.test(s);throw new pe(this.extractErrorMessage(t.error),i?"rate_limit":a?"context_exceeded":"unknown",i||o)}}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
|
|
1002
|
+
`){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){if(!e)return{message:`HTTP ${t}`};try{let n=JSON.parse(e);return n.error&&typeof n.error=="object"?{message:n.error.message||`HTTP ${t}`,type:n.error.type}:n.message?{message:n.message}:{message:e}}catch{return{message:e}}}checkAndThrowError(e){if(typeof e!="object"||e===null)return;let t=e;if(t.type==="error"&&"message"in t){let n=t.code||"unknown";throw new pe(t.message,n,!!t.retryable)}if(t.error){let n=t.error,s=typeof n=="object"&&n!==null?String(n.type??n.code??""):"",i=/rate_limit|too_many_requests/i.test(s),o=/overloaded|server_error|unavailable/i.test(s),a=/context_length/i.test(s);throw new pe(this.extractErrorMessage(t.error),i?"rate_limit":a?"context_exceeded":"unknown",i||o)}}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 _i,sl=v(()=>{vr();_i=class extends Ee{constructor(){super(...arguments),this.providerName="OpenAI",this.defaultBaseUrl="https://api.openai.com",this.path="/v1/responses",this.effortMap={0:"none",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 i=this.convertMessagesToInput(e),o={model:t,input:i,stream:s};if(n?.webSearch!==!1&&(o.tools=[{type:"web_search"}]),n?.effort!==void 0){let a=this.effortMap[n.effort];o.reasoning=a==="none"?{effort:a}:{effort:a,summary:"auto"}}return o}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(i=>i.text).join(`
|
|
1003
1003
|
`)),!t&&s.type==="message"&&s.content&&(t=s.content.filter(i=>i.type==="output_text").map(i=>i.text).join(""));return{text:t,reasoning:n}}parseProviderStreamChunk(e){if(!this.isResponsesApiEvent(e))return null;switch(e.type){case"response.failed":{let n=e.response?.error,s=n?.message||"Response failed",i=n?.code==="insufficient_quota"||n?.code==="rate_limit_exceeded";throw new pe(s,i?"rate_limit":"unknown",i)}case"response.output_text.delta":return{text:e.delta};case"response.reasoning_summary_text.delta":return{reasoning:e.delta};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(`
|
|
1004
1004
|
|
|
1005
|
-
`)}isResponsesApiEvent(e){return typeof e=="object"&&e!==null&&"type"in e&&typeof e.type=="string"}isResponsesApiResponse(e){return typeof e=="object"&&e!==null&&e.object==="response"}}});var
|
|
1005
|
+
`)}isResponsesApiEvent(e){return typeof e=="object"&&e!==null&&"type"in e&&typeof e.type=="string"}isResponsesApiResponse(e){return typeof e=="object"&&e!==null&&e.object==="response"}}});var Sr,Ni=v(()=>{vr();Sr=class extends Ee{parseNonStreamingResponse(e){if(!this.hasChoices(e))return{text:""};let t=e,n=t.choices[0],s=n?.message,i=s?.content??n?.text??"",o=s?.reasoning??s?.reasoning_content??t.reasoning;return{text:i,reasoning:o}}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,i=n.reasoning||n.reasoning_content||void 0;return!s&&!i?null:{text:s,reasoning:i}}hasChoices(e){return typeof e=="object"&&e!==null&&"choices"in e&&Array.isArray(e.choices)}}});var Ii,il=v(()=>{Ni();Ii=class extends Sr{constructor(){super(...arguments),this.providerName="OpenRouter",this.defaultBaseUrl="https://openrouter.ai",this.path="/api/v1/chat/completions",this.effortMap={0:"none",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 i={model:t,messages:e,stream:s};n?.webSearch===!0&&(i.plugins=[{id:"web"}]);let o=n?.effort;return o!==void 0&&(i.reasoning={effort:this.effortMap[o]}),i}}});var $i,ol=v(()=>{vr();$i=class extends Ee{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:i,conversationMessages:o}=this.extractSystemMessages(e),a={model:t,max_tokens:this.getMaxTokens(t),messages:this.withLastMessageCached(o),stream:s};n?.webSearch!==!1&&(a.tools=[{type:"web_search_20250305",name:"web_search"}]),i&&(a.system=[{type:"text",text:i,cache_control:{type:"ephemeral"}}]);let c=n?.effort;if(c!==void 0){if(this.isModernModel(t))if(c===0)a.output_config={effort:"low"};else{let l={1:"low",2:"medium",3:"high"};a.thinking={type:"adaptive",display:"summarized"},a.output_config={effort:l[c]}}else if(c!==0){let l={1:2048,2:4096,3:8192};a.thinking={type:"enabled",budget_tokens:l[c]}}}return a}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(`
|
|
1006
1006
|
|
|
1007
|
-
`);return{text:t,reasoning:n||void 0}}parseProviderStreamChunk(e){return this.isAnthropicEvent(e)&&e.type==="content_block_delta"?e.delta.type==="text_delta"?{text:e.delta.text||""}:e.delta.type==="thinking_delta"?{reasoning:e.delta.thinking||""}:null: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 typeof e=="object"&&e!==null&&e.type==="message"&&Array.isArray(e.content)}isAnthropicEvent(e){return typeof e=="object"&&e!==null&&"type"in e}isModernModel(e){let t=e.match(/^claude-[a-z]+-(\d+)(?:-(\d+))?/i);if(!t)return!1;let n=+t[1],s=t[2]?+t[2]:0;return n>4||n===4&&s>=6}getMaxTokens(e){return this.isModernModel(e)?64e3:32e3}}});var
|
|
1008
|
-
`),c={contents:o.map(
|
|
1009
|
-
`)[0],type:s.status,code:s.code?.toString()}:n.message?{message:n.message}:{message:e}}catch{return{message:e}}}parseNonStreamingResponse(e){if(this.checkAndThrowError(e),this.checkGeminiError(e),!this.isGeminiResponse(e))return{text:"",status:"failed",error:"Invalid response format"};let t=this.extractParts(e).text||"",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.extractParts(e);return t.text||t.reasoning?t:null}geminiVersion(e){let t=e.match(/^gemini-(\d+(?:\.\d+)?)/);return t?Number(t[1]):null}thinkingLevelFor(e,t){let n=["minimal","low","medium","high"][t];return n==="minimal"&&e<3.5?"low":n}isGeminiResponse(e){return typeof e=="object"&&e!==null&&"candidates"in e&&Array.isArray(e.candidates)}extractParts(e){let t=e.candidates?.[0]?.content?.parts;if(!t)return{};let n="",s="";for(let i of t)i.text&&(i.thought?s+=i.text:n+=i.text);return{text:n||void 0,reasoning:s||void 0}}checkGeminiError(e){if(this.isGeminiResponse(e)&&e.promptFeedback?.blockReason){let t=e.promptFeedback.blockReason;throw new pe(`Prompt blocked: ${t}`)}}}});var
|
|
1007
|
+
`);return{text:t,reasoning:n||void 0}}parseProviderStreamChunk(e){return this.isAnthropicEvent(e)&&e.type==="content_block_delta"?e.delta.type==="text_delta"?{text:e.delta.text||""}:e.delta.type==="thinking_delta"?{reasoning:e.delta.thinking||""}:null: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 typeof e=="object"&&e!==null&&e.type==="message"&&Array.isArray(e.content)}isAnthropicEvent(e){return typeof e=="object"&&e!==null&&"type"in e}isModernModel(e){let t=e.match(/^claude-[a-z]+-(\d+)(?:-(\d+))?/i);if(!t)return!1;let n=+t[1],s=t[2]?+t[2]:0;return n>4||n===4&&s>=6}getMaxTokens(e){return this.isModernModel(e)?64e3:32e3}}});var Li,al=v(()=>{vr();Li=class extends Ee{constructor(){super(...arguments),this.providerName="Gemini",this.defaultBaseUrl="https://generativelanguage.googleapis.com",this.path="/v1beta/models",this.budgetMap={0:0,1:1024,2:8192,3:-1}}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:i,conversationMessages:o}=this.extractSystemMessages(e,`
|
|
1008
|
+
`),c={contents:o.map(f=>({role:f.role==="assistant"?"model":"user",parts:[{text:f.content}]}))};n?.webSearch!==!1&&(c.tools=[{google_search:{}}]),i&&(c.systemInstruction={role:"system",parts:[{text:i}]});let l=n?.effort;if(l!==void 0){let f=this.geminiVersion(t),u=f!==null&&f>=3?{thinkingLevel:this.thinkingLevelFor(f,l)}:{thinkingBudget:this.budgetMap[l]};c.generationConfig={thinkingConfig:l===0?u:{includeThoughts:!0,...u}}}return 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(`
|
|
1009
|
+
`)[0],type:s.status,code:s.code?.toString()}:n.message?{message:n.message}:{message:e}}catch{return{message:e}}}parseNonStreamingResponse(e){if(this.checkAndThrowError(e),this.checkGeminiError(e),!this.isGeminiResponse(e))return{text:"",status:"failed",error:"Invalid response format"};let t=this.extractParts(e).text||"",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.extractParts(e);return t.text||t.reasoning?t:null}geminiVersion(e){let t=e.match(/^gemini-(\d+(?:\.\d+)?)/);return t?Number(t[1]):null}thinkingLevelFor(e,t){let n=["minimal","low","medium","high"][t];return n==="minimal"&&e<3.5?"low":n}isGeminiResponse(e){return typeof e=="object"&&e!==null&&"candidates"in e&&Array.isArray(e.candidates)}extractParts(e){let t=e.candidates?.[0]?.content?.parts;if(!t)return{};let n="",s="";for(let i of t)i.text&&(i.thought?s+=i.text:n+=i.text);return{text:n||void 0,reasoning:s||void 0}}checkGeminiError(e){if(this.isGeminiResponse(e)&&e.promptFeedback?.blockReason){let t=e.promptFeedback.blockReason;throw new pe(`Prompt blocked: ${t}`)}}}});var Mi,cl=v(()=>{Ni();Mi=class extends Sr{constructor(){super(...arguments),this.providerName="Ollama",this.defaultBaseUrl="http://localhost:11434",this.path="/chat/completions"}buildHeaders(e){let t={"Content-Type":"application/json",Accept:"application/json"};return e&&(t.Authorization=`Bearer ${e}`),t}buildPayload(e,t,n,s){return{model:t,messages:e,stream:s}}}});function Ut(r){let e=n0.get(r);if(!e)throw new Error(`Unsupported protocol: ${r}`);return e}function s0(r,e){return r.replace(/\/+$/,"")+(e.startsWith("/")?e:`/${e}`)}async function ll(r,e){let t=Ut(r.protocol),n=t.getPath(r.model,e.stream),s=s0(r.baseUrl,n),i=t.buildHeaders(r.apiKey,e.origin),o=t.buildPayload(e.messages,r.model,{effort:e.effort,webSearch:e.webSearch},e.stream);return e.modifyPayload?.(o),fetch(s,{method:"POST",headers:i,body:JSON.stringify(o),signal:e.signal})}function i0(r){return/prompt is too long|context[_ ](length|window)|maximum context|token count exceeds|too many tokens/i.test(r)}async function kr(r,e){let t=Ut(e),n=await r.text().catch(()=>""),{message:s}=t.parseError(n,r.status),i=r.status,o="unknown";return i===429?o="rate_limit":(i===413||i0(s))&&(o="context_exceeded"),{code:o,message:s,retryable:i===429||i>=500}}var Fm,n0,ul=v(()=>{sl();il();ol();al();cl();Fm=new Mi,n0=new Map([["openai",new _i],["openrouter",new Ii],["anthropic",new $i],["gemini",new Li],["ollama",Fm],["openai-compat",Fm]])});function qm(r){let e=r.indexOf(`\r
|
|
1010
1010
|
\r
|
|
1011
1011
|
`),t=r.indexOf(`
|
|
1012
1012
|
|
|
1013
|
-
`);return e!==-1&&(t===-1||e<t)?{pos:e,len:4}:t!==-1?{pos:t,len:2}:{pos:-1,len:0}}function
|
|
1014
|
-
`).trim();if(!n)return null;if(n==="[DONE]")return"done";try{return JSON.parse(n)}catch{return null}}async function*
|
|
1013
|
+
`);return e!==-1&&(t===-1||e<t)?{pos:e,len:4}:t!==-1?{pos:t,len:2}:{pos:-1,len:0}}function dl(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(`
|
|
1014
|
+
`).trim();if(!n)return null;if(n==="[DONE]")return"done";try{return JSON.parse(n)}catch{return null}}async function*Um(r,e,t){let n=new TextDecoder,s="",i,o=e?new Promise((a,c)=>{e.aborted&&c(new Error("Aborted")),i=()=>c(new Error("Aborted")),e.addEventListener("abort",i,{once:!0})}):null;o?.catch(()=>{});try{for(;;){let{done:a,value:c}=o?await Promise.race([r.read(),o]):await r.read();if(a){if(s.trim()){let u=dl(s);u!==null&&u!=="done"&&(yield u)}return}t?.(),s+=n.decode(c,{stream:!0});let{pos:l,len:f}=qm(s);for(;l!==-1;){let u=s.slice(0,l);s=s.slice(l+f);let d=dl(u);if(d==="done")return;d!==null&&(yield d),{pos:l,len:f}=qm(s)}}}finally{i&&e?.removeEventListener("abort",i);try{await r.cancel()}catch{}}}async function Jt(r,e){if(!r.body)throw new Error("Response body is missing");let t="";for await(let n of Kt(r,e))n.kind==="text"&&(t+=n.text);return t}async function*Kt(r,e){let t=e??(r.headers.get("X-Provider-Protocol")||"openai"),n=Ut(t);if(!r.body)return;let s=r.body.getReader();for await(let i of Um(s)){let o=n.parseStreamChunk(i);o?.reasoning&&(yield{kind:"reasoning",text:o.reasoning}),o?.text&&(yield{kind:"text",text:o.text})}}var Jm=v(()=>{ul()});import{strToU8 as o0,strFromU8 as a0,deflateSync as c0,inflateSync as l0}from"fflate";function pl(r,e){let t=[];if(t.push(`You are a data processor. Follow the instructions to analyze the provided data. Output valid JSON that the code can consume.
|
|
1015
1015
|
|
|
1016
1016
|
---
|
|
1017
1017
|
Instructions:
|
|
@@ -1029,905 +1029,906 @@ ${n}
|
|
|
1029
1029
|
</data>`)}return t.push(`
|
|
1030
1030
|
Output only valid JSON. No explanation, no markdown fences, just the JSON object. Every number must be a JSON literal \u2014 never an expression like 2 * pi; write the computed decimal instead.`),t.join(`
|
|
1031
1031
|
|
|
1032
|
-
`)}function Ln(r){try{return JSON.parse(r)}catch{return null}}function
|
|
1033
|
-
`)}var
|
|
1034
|
-
\u2026[${r.length-5e4} more characters truncated]`:r}function
|
|
1035
|
-
`).map(i=>i.trim()).filter(Boolean),t=e[0];if(!t)return"";let n=t.length>300?t.slice(0,300).trimEnd()+"\u2026":t,s=e.length-1;return s>0?`${n} (+${s} line${s===1?"":"s"})`:n}var
|
|
1036
|
-
`):r==null?"":
|
|
1037
|
-
`).length,"line")}`;if(t.mode==="content")return Te(t.numLines??0,"line");if(t.mode==="count")return`${Te(t.numMatches??0,"match","matches")} (${Te(t.numFiles??0,"file")})`;if(t.mode==="files_with_matches")return Te(t.numFiles??0,"file");if(Array.isArray(t.structuredPatch)){let n=0,s=0;for(let i of t.structuredPatch)for(let o of i?.lines??[])typeof o=="string"&&(o.startsWith("+")?n++:o.startsWith("-")&&s++);return`+${n} \u2212${s}`}return typeof t.stdout=="string"||typeof t.stderr=="string"?t.backgroundTaskId?"running in background":t.interrupted?"interrupted":
|
|
1038
|
-
`)){if(!p.includes(`"${
|
|
1039
|
-
`)){if(!l.trim())continue;let
|
|
1040
|
-
`),c=i.filter(u=>u.type==="tool_use").map(u=>({id:u.id??"",name:u.name??"",input:u.input??{}}));if(o||a||c.length){let u=Date.parse(e.timestamp??""),
|
|
1041
|
-
`),n=[];if(t.forEach((o,a)=>{let c=
|
|
1042
|
-
`)}function
|
|
1032
|
+
`)}function Ln(r){try{return JSON.parse(r)}catch{return null}}function d0(r,e){let t="",n=0,s=!1,i=!1;for(let o=0;o<r.length;o++){let a=r[o];if(i){i=!1;continue}if(a==="\\"){i=!0;continue}a==='"'&&(s?(t+=r.slice(n,o+1),n=o+1):(t+=e(r.slice(n,o))+'"',n=o+1),s=!s)}return t+=s?r.slice(n):e(r.slice(n)),t}function f0(r){let e=d0(r,t=>t.replace(/\bpi\b/g,"3.141592653589793").replace(/\be\b/g,"2.718281828459045").replace(/-?\d[\d.\s+\-*/()]*\d|\(-?\d[\d.\s+\-*/()]*\d\)/g,n=>{if(!/[+\-*/]/.test(n.replace(/^-/,""))||n.length>64||!/^[\d\s.+\-*/()]+$/.test(n))return n;try{let s=Function(`"use strict"; return (${n})`)();return typeof s=="number"&&Number.isFinite(s)?String(s):n}catch{return n}}));return e!==r?e:null}function p0(r,e){let t=0,n=!1,s=!1;for(let i=e;i<r.length;i++){let o=r[i];if(s){s=!1;continue}if(o==="\\"){s=!0;continue}if(o==='"'){n=!n;continue}if(!n){if(o==="{"||o==="[")t++;else if((o==="}"||o==="]")&&(t--,t===0))return i}}return-1}function m0(r){let e=null,t=0;for(;t<r.length;){let n=r[t];if(n==="{"||n==="["){let s=p0(r,t);if(s!==-1){let i=r.slice(t,s+1),o=Ln(i);o!==null&&(e={parsed:o,json:i}),t=s+1;continue}}t++}return e}function ml(r){let e=[],t=r.trim();t.startsWith("```")&&(t=t.replace(/^```(?:json)?\s*\n?/,"").replace(/\n?```\s*$/,""),e.push("markdown fences"));let n=Ln(t);if(n!==null)return{parsed:n,json:t,fixesApplied:e};let s=t.match(/```(?:json)?\s*\n([\s\S]*?)\n?```\s*$/);if(s&&(t=s[1].trim(),e.push("preamble before fenced JSON"),n=Ln(t),n!==null))return{parsed:n,json:t,fixesApplied:e};if(!t.startsWith("{")&&!t.startsWith("[")){let o=t.indexOf("{"),a=t.indexOf("["),c=o>=0&&a>=0?Math.min(o,a):o>=0?o:a;if(c>0&&(t=t.slice(c),e.push("preamble text"),n=Ln(t),n!==null))return{parsed:n,json:t,fixesApplied:e}}for(let[o,a]of u0){let c=a(t);if(c!==null){let l=Ln(c);if(l!==null)return{parsed:l,json:c,fixesApplied:[...e,o]}}}let i=m0(r);return i!==null?{...i,fixesApplied:[...e,"extracted last JSON value"]}:{parsed:null,json:t,fixesApplied:e}}function hl(r){try{let e={i:r.insight,d:r.data},t=JSON.stringify(e),n=c0(o0(t),{level:9}),s=g0(n),i=`${Km}:${s}`;return i.length>h0?"":"#"+fl+i}catch{return""}}function gl(r){try{let e=r.startsWith("#")?r.slice(1):r;if(!e.startsWith(fl))return null;let t=e.slice(fl.length),n=t.indexOf(":");if(n===-1||t.slice(0,n)!==Km)return null;let s=y0(t.slice(n+1)),i=JSON.parse(a0(l0(s)));return!i||typeof i.i>"u"||!Array.isArray(i.d)?null:{insight:i.i,insightJson:JSON.stringify(i.i,null,2),data:i.d}}catch{return null}}function g0(r){let e="";for(let t=0;t<r.length;t+=32768)e+=String.fromCharCode(...r.subarray(t,t+32768));return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function y0(r){let e=r.replace(/-/g,"+").replace(/_/g,"/");for(;e.length%4;)e+="=";let t=atob(e),n=new Uint8Array(t.length);for(let s=0;s<t.length;s++)n[s]=t.charCodeAt(s);return n}var u0,fl,Km,h0,Hm=v(()=>{u0=[["orphan quote",r=>{let e=r.replace(/^[ \t]*"[ \t]*\r?\n/gm,"");return e!==r?e:null}],["trailing }",r=>r.endsWith("}}")?r.slice(0,-1):null],["trailing ]",r=>r.endsWith("]]")?r.slice(0,-1):null],["trailing },",r=>r.endsWith("},")?r.slice(0,-1):null],["trailing ],",r=>r.endsWith("],")?r.slice(0,-1):null],["trailing comma in object",r=>r.match(/,\s*\}$/)?r.replace(/,\s*\}$/,"}"):null],["trailing comma in array",r=>r.match(/,\s*\]$/)?r.replace(/,\s*\]$/,"]"):null],["arithmetic constants",f0]];fl="tb=",Km="1",h0=6e4});var xr=v(()=>{jm();vr();ul();Jm();Hm();Ni();ol();al();sl();il();cl()});function Ar(r){return(r.includes("://")?r:`http://${r}`).replace(/\/+$/,"")}function yl(){return Dn}async function Ve(){let[r,e]=await Promise.all([Ym(),x0()]);return k0([...E0(e),...r],process.env.TB_AI_PROVIDER,process.env.TB_AI_MODEL)}function k0(r,e,t){return!e||!t?r:r.map(n=>n.provider===e&&n.name===t?{...n,default:!0}:n)}async function Wm(){let r;try{r=await fetch(b0,{signal:AbortSignal.timeout(v0)})}catch(e){return Dn=`catalog fetch failed: ${e?.message??e}`,null}if(!r.ok)return Dn=`catalog fetch failed: HTTP ${r.status}`,null;try{return await r.json()}catch(e){return Dn=`catalog returned an unreadable body: ${e?.message??e}`,null}}async function x0(){if(Mn&&Date.now()-Mn.fetchedAt<=w0)return Mn.models;let r=await Wm()??await Wm();return r?(Mn={models:r,fetchedAt:Date.now()},Dn=null,r):Mn?.models??[]}async function Ym(){if(Di&&Date.now()-Di.fetchedAt<=S0)return Di.models;let r=Ar(process.env.OLLAMA_HOST??"http://localhost:11434"),e=[];try{let t=await fetch(new URL("/api/tags",r).toString());t.ok&&(e=((await t.json()).models??[]).map(s=>s.name).filter(s=>!!s).map(s=>({provider:"ollama",name:s,friendlyName:s,providerName:"Ollama"})))}catch{}return Di={models:e,fetchedAt:Date.now()},e}function E0(r){let e=new Set(Object.entries(Er).filter(([,t])=>!!process.env[t]).map(([t])=>t));return r.filter(t=>e.has(t.provider))}function bl(){return Object.values(Er).some(r=>!!process.env[r])}async function Bi(){return bl()||process.env.TB_AI_BASE_URL?!0:(await Ym()).length>0}function Vm(r,e,t){let n=Math.max(...r.map(o=>o.name.length)),s=Math.max(...r.map(o=>o.friendlyName.length)),i=["Models available to tb.ai (filtered by your .env keys):",""];for(let o of r)i.push(` ${o.name.padEnd(n)} ${o.friendlyName.padEnd(s)} (${o.provider})`);return i.push("","Pass an id as the `model` in tb.ai({ provider, model })."),e&&t&&i.push(`Default (from .env): ${e} / ${t}`),i.join(`
|
|
1033
|
+
`)}var Er,b0,w0,v0,S0,Mn,Di,Dn,Ht=v(()=>{Er={anthropic:"ANTHROPIC_API_KEY",openai:"OPENAI_API_KEY",gemini:"GOOGLE_API_KEY",openrouter:"OPENROUTER_API_KEY"};b0="https://api.typebulb.com/api/models",w0=1440*60*1e3,v0=5e3,S0=60*1e3,Mn=null,Di=null,Dn=null});function Ge(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=Ut(t)}catch{return`Unknown provider '${t}'.`}if(t==="ollama")return{apiKey:"",baseUrl:`${Ar(process.env.OLLAMA_HOST??s.defaultBaseUrl)}/v1`,protocol:t,model:n,isFreeModel:!1};if(t==="openai-compat"){let a=process.env.TB_AI_BASE_URL;return a?{apiKey:process.env.TB_AI_API_KEY??"",baseUrl:a,protocol:t,model:n,isFreeModel:!1}:"No base URL for openai-compat. Set TB_AI_BASE_URL (the OpenAI-style base ending in /v1, e.g. http://localhost:1234/v1) in your .env file."}let i=Er[t];if(!i)return`Unknown provider '${t}'.`;let o=process.env[i];return o?{apiKey:o,baseUrl:s.defaultBaseUrl,protocol:t,model:n,isFreeModel:!1}:`No API key for '${t}'. Set ${i} in your .env file.`}function yt(r,e){let t=[...e.system?[{role:"system",content:e.system}]:[],...e.messages.map(s=>({role:s.role,content:s.content}))],n=e.effort;return ll(r,{messages:t,stream:!0,effort:n!=null&&n>=0&&n<=3?n:void 0,webSearch:e.webSearch??!0,signal:e.signal})}var ji=v(()=>{xr();Ht()});import*as Tr from"fs/promises";import*as ze from"path";function Bn(r,e,t=e){let n=ze.resolve(e,r),s=ze.normalize(t),i=ze.normalize(n);if(i!==s&&!i.startsWith(s+ze.sep))throw new Error("Path traversal detected - access denied");return n}async function jn(r,e,t){return Tr.readFile(Bn(r,e,t))}async function Fi(r,e,t,n){let s=Bn(r,t,n);await Tr.mkdir(ze.dirname(s),{recursive:!0}),await Tr.writeFile(s,typeof e=="string"?e:Buffer.from(e))}var wl=v(()=>{});async function Gm(r){let e=Ge(r.provider,r.model);if(typeof e=="string")throw new Error(e);let t=await yt(e,r);if(!t.ok){let n=await kr(t,e.protocol);throw new Error(n.message)}return{response:t,protocol:e.protocol}}async function A0(r){let{response:e,protocol:t}=await Gm(r);return{text:await Jt(e,t)}}async function*T0(r){let{response:e,protocol:t}=await Gm(r);yield*Kt(e,t)}function zm(r,e=process.cwd()){let t=Object.assign(A0,{stream:T0}),n={read:async s=>{let i=await jn(s,r,e);try{return new TextDecoder("utf-8",{fatal:!0}).decode(i)}catch{throw new Error(`File is not valid UTF-8 text: ${s} \u2014 use tb.fs.readBytes() for binary files.`)}},readBytes:async s=>new Uint8Array(await jn(s,r,e)),write:async(s,i)=>(await Fi(s,i,r,e),!0)};globalThis.tb=Object.freeze({ai:t,fs:n,dir:r,models:()=>Ve(),hasOwnKeys:Bi,mode:"local"})}var Xm=v(()=>{xr();ji();Ht();wl()});import*as bt from"fs/promises";import*as se from"path";import{pathToFileURL as P0}from"url";async function Qm(r){let t=(await bt.readdir(r)).find(n=>n.endsWith(".bulb.md"));return t?se.join(r,t):null}function Fn(r,e){let t=se.resolve(r),n=se.join(se.dirname(t),se.basename(t).replace(/\.bulb\.md$/,""));return e?se.join(n,e):n}async function Ae(r){let e=await bt.readFile(r,"utf-8"),t=ce(e);if(!t)throw new Error("Invalid .bulb.md file format");let n=mr(t);return{bulb:n,config:rt(n.config),warnings:rd(e)}}function vl(r){let e=se.basename(r).replace(/\.bulb\.md$/i,"");return se.join(se.dirname(r),".typebulb",`${e}.server.mjs`)}async function qn(r,e,t,n,s){let i=Jc(r,{serverOnly:!0});if(i.error)throw new Error(`Server compilation error: ${i.error}`);let o=i.code;t&&(o=await Vu(o,t));let a=se.join(se.dirname(e),".typebulb");await bt.mkdir(a,{recursive:!0});let c=Ri(o);c.length>0&&await Ci(c,a,n);let l=vl(e);return await bt.writeFile(l,o,"utf-8"),zm(Fn(e,s)),await import(`${P0(l).href}?t=${Date.now()}`)}async function Sl(r,e,t,n,s){let{bulb:i,config:o}=await Ae(r),a=fi(i.data);pm(i.code,o.dependencies??{});let c=Jc(i.code,{jsxImportSource:o.ts?.jsxImportSource});c.error&&console.error("Compilation error:",c.error);let{importMap:l}=await xi.buildImportMap(c.code,o.dependencies??{},n?new Set([n.name]):void 0);n&&(l.imports[n.name]=n.entryUrl);let f=Mm({name:i.name,code:c.code,css:i.css,html:i.html,data:a,insight:i.insight,importMap:l,dir:Fn(r,s),watch:e}),u=null;return i.server&&t&&(u=await qn(i.server,r,n,o.dependencies,s)),{html:f,bulb:i,serverExports:u}}var Pr,wt=v(()=>{xn();um();mm();tl();Dm();nl();ds();Xm();Pr=(r,e)=>se.join(Fn(r,e),"assets")});import{realpathSync as O0}from"fs";import{join as kl,resolve as C0}from"path";import{homedir as R0}from"os";function qi(){let r=process.env.TYPEBULB_SERVERS_DIR;return r?kl(r,".."):kl(R0(),".typebulb")}function Xe(){return process.env.TYPEBULB_SERVERS_DIR||kl(qi(),"servers")}function ne(r){let e=C0(r),t=e;try{t=O0.native(e)}catch{}return(process.platform==="win32"?t.toLowerCase():t).replace(/\\/g,"/")}function Zm(r,e){let t=ne(r),n=ne(e);return t.startsWith(n.endsWith("/")?n:n+"/")?!t.includes("/node_modules/"):!1}var Ui=v(()=>{});import{readFileSync as _0,writeFileSync as N0,mkdirSync as I0}from"fs";import{join as $0}from"path";function eh(){return $0(qi(),"trust.json")}function xl(){try{let r=JSON.parse(_0(eh(),"utf8"));return new Set(Array.isArray(r)?r:[])}catch{return new Set}}function L0(r){I0(qi(),{recursive:!0}),N0(eh(),JSON.stringify([...r]))}function Wt(r){return xl().has(ne(r))}function Or(r,e){let t=xl(),n=ne(r);(e?t.has(n):!t.has(n))||(e?t.add(n):t.delete(n),L0(t))}function El(){return[...xl()]}var Un=v(()=>{Ui()});function Ie(r){return r.length>5e4?r.slice(0,5e4)+`
|
|
1034
|
+
\u2026[${r.length-5e4} more characters truncated]`:r}function Qe(r){let e=r.replace(M0,"").split(`
|
|
1035
|
+
`).map(i=>i.trim()).filter(Boolean),t=e[0];if(!t)return"";let n=t.length>300?t.slice(0,300).trimEnd()+"\u2026":t,s=e.length-1;return s>0?`${n} (+${s} line${s===1?"":"s"})`:n}var M0,Ji,Ki=v(()=>{M0=/\u001b\[[0-9;]*m/g;Ji=(r,e)=>``});import{existsSync as D0,readdirSync as B0,statSync as j0}from"fs";import{join as F0}from"path";function Hi(r){if(!D0(r))return[];let e;try{e=B0(r)}catch{return[]}let t=[];for(let n of e){if(!n.endsWith(".jsonl"))continue;let s=F0(r,n);try{let i=j0(s);i.isFile()&&t.push({sessionId:n.slice(0,-6),file:s,mtime:i.mtimeMs})}catch{}}return t}var Al=v(()=>{});var Cr,Tl=v(()=>{Cr=class{ensureHarnessSupport(){}}});import{openSync as q0,readSync as U0,closeSync as J0,statSync as K0,readdirSync as H0,readFileSync as W0,existsSync as Y0}from"fs";import{join as Kn}from"path";import{homedir as Cl}from"os";function V0(r){return r.replace(/[^a-zA-Z0-9]/g,"-")}function Wi(r){let e=r?.type==="image"?r.source:void 0;return e?.type==="base64"&&e.data?Ji(e.data,e.media_type):""}function Pl(r){return typeof r=="string"?Ie(r):Array.isArray(r)?r.map(e=>{if(typeof e=="string")return Ie(e);let t=e;return typeof t?.text=="string"?Ie(t.text):t?.content!=null?Pl(t.content):Wi(t)}).join(`
|
|
1036
|
+
`):r==null?"":Ie(JSON.stringify(r))}function z0(r){let e=r.trim();return!!e&&sh.some(t=>t.test(e))}function X0(r){let e=r.trim();return e?sh.some(t=>{let n=t.exec(e);return!!n&&n.index===0}):!0}function Z0(r){return r.replace(Q0,"")}function eE(r){let e=/^<command-name>([\s\S]*?)<\/command-name>/.exec(r)?.[1]?.trim();if(!e)return;let t=/<command-args>([\s\S]*?)<\/command-args>/.exec(r)?.[1]?.trim();return t?`${e} ${t}`:e}function vt(r){let e=Z0(r).trim();return e?eE(e)??(z0(e)?"":e):""}function Ol(r){return r?.type==="text"&&typeof r.text=="string"?vt(r.text):""}function Rl(r,e){if(typeof r=="string")return Qe(r);if(!r||typeof r!="object")return Qe(e);let t=r;if(t.type==="text"&&typeof t.file?.numLines=="number")return Te(t.file.numLines,"line");if(t.type==="image"){let n=rh(t.file?.originalSize);return n?`image (${n})`:"image"}if(t.type==="pdf"){let n=rh(t.file?.originalSize);return n?`PDF (${n})`:"PDF"}if(t.type==="parts"&&typeof t.file?.count=="number")return Te(t.file.count,"page");if(t.type==="file_unchanged")return"unchanged since last read";if(t.type==="create"&&typeof t.content=="string")return`created, ${Te(t.content.split(`
|
|
1037
|
+
`).length,"line")}`;if(t.mode==="content")return Te(t.numLines??0,"line");if(t.mode==="count")return`${Te(t.numMatches??0,"match","matches")} (${Te(t.numFiles??0,"file")})`;if(t.mode==="files_with_matches")return Te(t.numFiles??0,"file");if(Array.isArray(t.structuredPatch)){let n=0,s=0;for(let i of t.structuredPatch)for(let o of i?.lines??[])typeof o=="string"&&(o.startsWith("+")?n++:o.startsWith("-")&&s++);return`+${n} \u2212${s}`}return typeof t.stdout=="string"||typeof t.stderr=="string"?t.backgroundTaskId?"running in background":t.interrupted?"interrupted":Qe(t.stdout||t.stderr||"")||"no output":typeof t.code=="number"&&typeof t.codeText=="string"?`${t.code} ${t.codeText}`:typeof t.searchCount=="number"?Te(t.searchCount,"search","searches"):Array.isArray(t.matches)&&typeof t.total_deferred_tools=="number"?Te(t.matches.length,"tool"):Array.isArray(t.newTodos)?Te(t.newTodos.length,"todo"):typeof t.numFiles=="number"?Te(t.numFiles,"file"):Qe(e)}function Jn(r){return!!r.isSidechain||!!r.isMeta}function tE(r){let e;try{e=q0(r,"r")}catch{return""}try{let n=65536;try{n=K0(r).size}catch{}let s=(l,f)=>{if(f<=0)return"";let u=Buffer.alloc(f),d=U0(e,u,0,f,l);return u.subarray(0,d).toString("utf8")},i=(l,f,u)=>{let d="";for(let p of l.split(`
|
|
1038
|
+
`)){if(!p.includes(`"${f}"`))continue;let b;try{b=JSON.parse(p)}catch{continue}let m=b?.[u];b?.type===f&&typeof m=="string"&&m&&(d=m)}return d},o=s(0,Math.min(65536,n)),a=n>65536?s(n-65536,65536):"",c=i(a,"custom-title","customTitle")||i(o,"custom-title","customTitle")||i(a,"ai-title","aiTitle")||i(o,"ai-title","aiTitle");if(c)return c.replace(/\s+/g," ").trim().slice(0,200);for(let l of o.split(`
|
|
1039
|
+
`)){if(!l.trim())continue;let f;try{f=JSON.parse(l)}catch{continue}if(!f||Jn(f)||f.type!=="user")continue;let u=f.message?.content,d="";typeof u=="string"?d=vt(u):Array.isArray(u)&&(d=u.map(Ol).filter(Boolean).join(" "));let p=d.replace(/\s+/g," ").trim();if(p)return(p.replace(/^Continuing from a prior session\. Here is the summary of our work so far:\s*/i,"").trim()||p).slice(0,200)}return""}finally{J0(e)}}function rE(r){let e;try{e=H0(nh)}catch{return!1}for(let t of e)if(t.endsWith(".json"))try{let n=JSON.parse(W0(Kn(nh,t),"utf8"));if(n?.sessionId!==r)continue;return process.kill(n.pid,0),!0}catch{}return!1}var G0,th,sh,Q0,Te,rh,nh,Rr,Yi=v(()=>{Ki();Al();Tl();G0=Kn(Cl(),".claude","projects"),th=r=>Kn(G0,V0(r));sh=[/\[Request interrupted by user\b/i,/\[Tool use was interrupted\]/i,/Claude Code returned an error/i,/\[ede_diagnostic\]/i,/^No response requested\.?$/i,/^<task-notification\b/i,/^<system-reminder\b/i,/^<local-command-stdout\b/i,/^<local-command-stderr\b/i];Q0=/<ide_[a-z_]+>[\s\S]*?<\/ide_[a-z_]+>/gi;Te=(r,e,t=e+"s")=>`${r} ${r===1?e:t}`,rh=r=>typeof r!="number"?"":r<1024?`${r}B`:r<1048576?`${Math.round(r/1024)}KB`:`${(r/1048576).toFixed(1)}MB`;nh=Kn(Cl(),".claude","sessions");Rr=class extends Cr{displayName="Claude Mirror";detectsSelf(){return process.env.CLAUDECODE==="1"}detectsInstalled(){return Y0(Kn(Cl(),".claude"))}sessionsDir(e){return th(e)}listSessionFiles(e){return Hi(th(e))}parseEntry(e){try{return JSON.parse(e)}catch{return null}}idOf(e){return e.uuid}parentOf(e){return e.parentUuid}timestampOf(e){return e.timestamp}isSidechain(e){return!!e.isSidechain}isLeafType(e){return e.type==="user"||e.type==="assistant"}isRecoveryNoise(e){return!!e.isApiErrorMessage}apply(e,t){if(Jn(e))return{events:[]};let n=[];if(e.type==="user"){let s=e.message?.content;if(typeof s=="string"){let i=vt(s);i&&n.push({type:"user",text:i})}else if(Array.isArray(s))for(let i of s)if(i?.type==="tool_result"){let o=Pl(i.content);n.push({type:"tool_result",id:i.tool_use_id??"",content:o,isError:!!i.is_error,digest:Rl(e.toolUseResult,o)})}else{let o=Ol(i)||Wi(i);o&&n.push({type:"user",text:o})}return{events:n}}if(e.type==="attachment"&&e.attachment?.type==="queued_command"){let s=vt(Pl(e.attachment.prompt));return s&&n.push({type:"user",text:s}),{events:n}}if(e.type==="assistant"){let s=e.message?.content,i=Array.isArray(s)?s:[],o=i.filter(u=>u.type==="text").map(u=>u.text??"").filter(u=>!X0(u)).join(""),a=i.filter(u=>u.type==="thinking").map(u=>u.thinking??"").join(`
|
|
1040
|
+
`),c=i.filter(u=>u.type==="tool_use").map(u=>({id:u.id??"",name:u.name??"",input:u.input??{}}));if(o||a||c.length){let u=Date.parse(e.timestamp??""),d=!isNaN(u)&&u>=t;n.push({type:"assistant",text:o,thinking:a,tools:c,live:d})}let l=e.message?.usage??e.usage,f=l&&{in:l.input_tokens??0,out:l.output_tokens??0,cached:l.cache_read_input_tokens??0,cacheCreate:l.cache_creation_input_tokens??0};return{events:n,usage:f,model:e.message?.model}}return{events:n}}chainWorking(e){let t;for(let o of e)(o.type==="user"||o.type==="assistant")&&(t=o);if(!t)return!1;if(t.type==="user"){try{let o=t.message?.content,a=typeof o=="string"?o:Array.isArray(o)?o.filter(l=>l&&l.type==="text").map(l=>l.text??"").join(""):"";if(!(Array.isArray(o)&&o.some(l=>l&&l.type==="tool_result"))&&a.trim()&&vt(a)==="")return!1}catch{}return!0}let s=(Array.isArray(t.message?.content)?t.message.content:[]).filter(o=>o.type==="tool_use").map(o=>o.id);if(s.length===0)return!1;let i=new Set;for(let o of e){let a=o.message?.content;if(Array.isArray(a))for(let c of a)c.type==="tool_result"&&c.tool_use_id&&i.add(c.tool_use_id)}return s.some(o=>o&&!i.has(o))}sessionAlive(e){return rE(e)}readPreview(e){return tE(e)}searchText(e){if(!e||Jn(e)||e.type!=="user"&&e.type!=="assistant")return"";let t=e.message?.content,n="";if(typeof t=="string")n=vt(t);else if(Array.isArray(t)){let s=t;n=e.type==="user"?s.map(Ol).filter(Boolean).join(" "):s.filter(i=>i.type==="text"&&typeof i.text=="string").map(i=>i.text).join(" ")}return n.replace(/\s+/g," ").trim()}}});import{spawn as ih}from"child_process";import{readdir as nE,readFile as ah,writeFile as ch,unlink as _l,mkdir as sE}from"fs/promises";import{mkdirSync as lh,writeFileSync as Vi,appendFileSync as iE,readFileSync as Nl}from"fs";import*as ge from"path";import{fileURLToPath as oE}from"url";function Il(r){return ge.join(Xe(),`${r}.json`)}function Wn(r){return ge.join(Xe(),`${r}.log`)}function $l(r){return ge.join(Xe(),`${r}.wait.json`)}function uh(r){try{let e=JSON.parse(Nl($l(r),"utf8"));return e.cursors&&typeof e.cursors=="object"?e.cursors:{}}catch{return{}}}function Ll(r,e=""){let t=uh(r)[e];return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}function Gi(r,e,t=""){try{lh(Xe(),{recursive:!0});let n=uh(r);n[t]=e,Vi($l(r),JSON.stringify({cursors:n}))}catch{}}function zi(r){let e=Wn(r);try{lh(Xe(),{recursive:!0}),Vi(e,"")}catch{return()=>{}}let t=process.stdout.write.bind(process.stdout),n=process.stderr.write.bind(process.stderr),s=0,i=!1,o=a=>{if(!i)try{let c=typeof a=="string"?Buffer.from(a,"utf8"):Buffer.from(a);if(iE(e,c),s+=c.length,s>2*oh){let l=Nl(e),f=l.subarray(Math.max(0,l.length-oh));Vi(e,f),s=f.length}}catch{i=!0}};return process.stdout.write=((a,...c)=>(o(a),t(a,...c))),process.stderr.write=((a,...c)=>(o(a),n(a,...c))),()=>{process.stdout.write=t,process.stderr.write=n}}function dh(r){try{Vi(Wn(r),"")}catch{}}function $e(r,e=0){try{let t=Nl(Wn(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 Ml(r){return`\u2500\u2500 run ${r} \u2500\u2500 ${new Date().toTimeString().slice(0,8)}`}function cE(r){let e=aE.exec(r);return e?Number(e[1]):void 0}function fh(r,e){let t=r.split(`
|
|
1041
|
+
`),n=[];if(t.forEach((o,a)=>{let c=cE(o);c!==void 0&&n.push({id:c,idx:a})}),!n.length)return e==="latest"?r:"";let s=e==="latest"?n[n.length-1]:n.find(o=>o.id===e);if(!s)return"";let i=n.find(o=>o.idx>s.idx);return t.slice(s.idx,i?i.idx:t.length).join(`
|
|
1042
|
+
`)}function Dl(r){try{return process.kill(r,0),!0}catch(e){return e.code==="EPERM"}}async function ph(r){await sE(Xe(),{recursive:!0}),await ch(Il(r.pid),JSON.stringify(r))}async function mh(r,e){let t=Il(r);try{let n=JSON.parse(await ah(t,"utf8"));if(n.denied===e)return;n.denied=e,await ch(t,JSON.stringify(n))}catch{}}async function Hn(r){await _l(Il(r)).catch(()=>{}),await _l(Wn(r)).catch(()=>{}),await _l($l(r)).catch(()=>{})}async function Q(r){let e;try{e=await nE(Xe())}catch{return[]}let t=[];return await Promise.all(e.map(async s=>{if(!/^\d+\.json$/.test(s))return;let i=parseInt(s,10),o;try{o=JSON.parse(await ah(ge.join(Xe(),s),"utf8"))}catch{await Hn(i);return}o&&typeof o.pid=="number"&&Dl(o.pid)?t.push(o):await Hn(i)})),(r?t.filter(s=>s.agent==null&&Zm(s.file,r)):t).sort((s,i)=>s.startedAt-i.startedAt)}async function Bl(r,e){let t=ne(r);return(await Q()).find(n=>n.cwd!=null&&ne(n.cwd)===t&&(e?n.agent===e:n.agent!=null))}async function Yt(r){try{process.kill(r,"SIGTERM")}catch{}await Hn(r)}function _r(r,e){let t=ne(e);return r.filter(n=>n.agent==null&&n.pid!==process.pid&&ne(n.file)===t)}async function jl(r){let e=_r(await Q(),r);for(let t of e)await Yt(t.pid);return e}function uE(r,e,t){(process.platform==="win32"?ih("cmd",["/c","start","","/b",r,...e],{cwd:t,stdio:"ignore",windowsHide:!0}):ih(r,e,{cwd:t,detached:!0,stdio:"ignore"})).unref()}function hh(){return ge.join(ge.dirname(oE(import.meta.url)),"index.js")}function dE(r,e={}){return{command:process.execPath,args:[hh(),...e.trust?["--trust"]:[],...e.dir?["--dir",e.dir]:[],...e.mode?["--mode",e.mode]:[],r,...e.open===!1?["--no-open"]:[]]}}function fE(r){return{command:process.execPath,args:[hh(),`agent:${r}`,"--no-open"]}}async function gh(r,e,t,n){let s=await r();if(s)return s;uE(e.command,e.args,t);let i=Date.now()+2e4;for(;Date.now()<i;){await lE(150);let o=await r();if(o)return o}throw new Error(`Launched ${n} but it did not register within 20s.`)}async function Xi(r,e={}){let t=e.cwd??process.cwd(),n=ge.resolve(t,r),[s]=await jl(n),i={...e,dir:e.dir??s?.dir,mode:e.mode??s?.mode};return gh(async()=>_r(await Q(),n)[0],dE(r,i),t,ge.basename(r))}async function yh(r,e=process.cwd()){return gh(()=>Bl(e,r),fE(r),e,`the ${r} mirror`)}var oh,aE,lE,Le=v(()=>{Ui();oh=1e6;aE=/^── run (\d+) ── /;lE=r=>new Promise(e=>setTimeout(e,r))});function Qi(r){let e=/^---[^\n]*\n([\s\S]*?)\n---/.exec(r),t=e?/^\s*name:\s*(.+?)\s*$/m.exec(e[1]):null;return t?t[1].replace(/^["']|["']$/g,""):void 0}function Fl(r){return(Qi(r)??"bulb").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"bulb"}var ql=v(()=>{});import{readdirSync as pE,readFileSync as mE,statSync as hE}from"fs";import{join as bh,basename as gE}from"path";function wh(r,e,t){if(e>8)return t;let n;try{n=pE(r,{withFileTypes:!0})}catch{return t}for(let s of n)if(s.isDirectory()){if(s.name.startsWith(".")||s.name==="node_modules")continue;wh(bh(r,s.name),e+1,t)}else s.isFile()&&s.name.endsWith(".bulb.md")&&t.push(bh(r,s.name));return t}function Zi(r){return wh(r,0,[]).map(e=>{let t=0;try{t=hE(e).mtimeMs}catch{}let n,s=!1;try{let i=mE(e,"utf8");n=Qi(i.slice(0,1024));let o=ce(i);s=!!o&&pi(mr(o))}catch{}return{path:e,name:n??gE(e).replace(/\.bulb\.md$/,""),mtime:t,serverOnly:s}})}var vh=v(()=>{Ne();xn();ql()});function Nr(r){if(r.server.trim())return"server-side code (server.ts)";let e=r.code;if(/\btb\s*\.\s*fs\b/.test(e)||e.includes("/__fs"))return"the filesystem";if(/\btb\s*\.\s*ai\b/.test(e)||e.includes("/__ai")||r.infer.trim()||/\btb\s*\.\s*infer\b/.test(e))return"AI (your API keys)";if(/\btb\s*\.\s*server\s*\.\s*(?!log\b)\w/.test(e)||e.includes("/__api"))return"server-side code (server.ts)"}var eo=v(()=>{});import{readFile as yE}from"fs/promises";async function Ul(r){try{let e=ce(await yE(r,"utf-8"));return e?Nr(mr(e)):void 0}catch{return}}var Sh=v(()=>{xn();eo()});function Jl(r){let e=ce(r);if(!e)return r;let t=e.files.get("code.tsx");if(!t)return r;let n=fm(t);if(!n.length)return r;let s=e.files.get("config.json"),i={};if(s)try{let l=JSON.parse(s);l&&typeof l=="object"&&(i=l)}catch{}let o=i.dependencies&&typeof i.dependencies=="object"?{...i.dependencies}:{},a=n.filter(l=>!(l in o));if(!a.length)return r;for(let l of a)o[l]="latest";i.dependencies=o;let c={name:e.frontmatter.name};for(let[l,f]of e.files){let u=Qu(l);u&&(c[u]=f)}return c.config=JSON.stringify(i,null,2),od(c)}var kh=v(()=>{Ne();mi()});import{spawn as xh}from"child_process";import{basename as bE}from"path";function wE(){return process.env.TYPEBULB_EDITOR||"code"}function SE(r,e,t){return t==null?[e]:vE.test(bE(r))?["-g",`${e}:${t}`]:[`+${t}`,e]}function kE(r,e){let t=wE();return{command:t,args:SE(t,r,e)}}function Kl(r,e){let{command:t,args:n}=kE(r,e),s=process.platform==="win32"?xh("cmd.exe",["/d","/s","/c",t,...n],{detached:!0,stdio:"ignore",windowsHide:!0}):xh(t,n,{detached:!0,stdio:"ignore"});s.on("error",i=>console.error("[typebulb] editor launch failed:",i?.message??i)),s.unref()}var vE,Eh=v(()=>{vE=/^(code|code-insiders|codium|vscodium|cursor|windsurf)(\.cmd|\.exe)?$/i});import{readFileSync as xE,existsSync as EE}from"fs";import*as Vt from"path";import{fileURLToPath as AE}from"url";function Ah(){let r=Vt.dirname(AE(import.meta.url));for(;!EE(Vt.join(r,"package.json"));){let e=Vt.dirname(r);if(e===r)break;r=e}return r}function Gt(){return Vt.join(Ah(),"README.md")}function Ir(){return Vt.join(Ah(),"description.md")}function TE(r){let e=xE(Ir(),"utf8").trim().replace(/\s+/g," ");return`---
|
|
1043
1043
|
name: typebulb
|
|
1044
1044
|
description: ${JSON.stringify(e)}
|
|
1045
1045
|
version: ${r}
|
|
1046
|
-
---`}function
|
|
1046
|
+
---`}function PE(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 Th(r,e){return`${TE(e)}
|
|
1047
1047
|
|
|
1048
|
-
${
|
|
1048
|
+
${PE(e)}
|
|
1049
1049
|
|
|
1050
1050
|
${r.trim()}
|
|
1051
|
-
`}var
|
|
1052
|
-
`)){let t=e.trim();if(!t||t.startsWith("#"))continue;let n=t.indexOf("=");if(n===-1)continue;let s=t.slice(0,n).trim(),i=t.slice(n+1).trim();(i.startsWith('"')&&i.endsWith('"')||i.startsWith("'")&&i.endsWith("'"))&&(i=i.slice(1,-1)),yield[s,i]}}function
|
|
1053
|
-
Expected <origin>/u/<user>/<slug>`);let
|
|
1054
|
-
A pull target must be a bulb URL, or a local file at typebulbs/u/<user>/<slug>.bulb.md \u2014 the path is its remote identity.`);return{origin:t,
|
|
1055
|
-
`),n=ce(t(r)),s=ce(t(e));return!n||!s?t(r)===t(e):n.frontmatter.name===s.frontmatter.name&&tt.every(i=>(n.files.get(
|
|
1051
|
+
`}var to=v(()=>{});import{readFileSync as Ph,existsSync as OE}from"fs";import*as Me from"path";function Oh(r){return[...r?[`.env.${r}.local`,`.env.${r}`]:[],".env.local",".env"]}function ye(r,e=process.cwd()){let t={},n=[];for(let s of Oh(r)){let i;try{i=Ph(Me.resolve(e,s),"utf-8")}catch{continue}n.push(s);for(let[o,a]of Ch(i))process.env[o]===void 0&&(process.env[o]=a,t[o]=s)}return{mode:r,sources:t,loaded:n}}function*Ch(r){for(let e of r.split(`
|
|
1052
|
+
`)){let t=e.trim();if(!t||t.startsWith("#"))continue;let n=t.indexOf("=");if(n===-1)continue;let s=t.slice(0,n).trim(),i=t.slice(n+1).trim();(i.startsWith('"')&&i.endsWith('"')||i.startsWith("'")&&i.endsWith("'"))&&(i=i.slice(1,-1)),yield[s,i]}}function ro(r,e=process.cwd()){for(let t of Oh()){let n;try{n=Ph(Me.resolve(e,t),"utf-8")}catch{continue}for(let[s,i]of Ch(n))if(s===r)return i}return process.env[r]}function CE(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 St(r,e,t){let{sources:n,mode:s,loaded:i}=r,o=process.cwd(),a=Me.dirname(e),c=`(mode: ${s??"none"})`,l=t?CE(t):[],f=l.filter(p=>n[p]).map(p=>`${p} \u2190 ${n[p]}`);f.length?console.log(`env: ${f.join(", ")} ${c}`):i.length&&console.log(`env: loaded ${i.join(", ")} ${c}`),s&&!i.some(p=>p===`.env.${s}`||p===`.env.${s}.local`)&&console.log(`env: mode=${s} \u2014 no .env.${s} found; using .env`);let u=Me.resolve(a)!==Me.resolve(o);if(u)for(let p of[".env.local",".env"])OE(Me.join(a,p))&&console.log(`env: ${Me.join(a,p)} present but not loaded (cwd is ${o})`);let d=l.filter(p=>process.env[p]===void 0);if(d.length){let p=u?` \u2014 try running from ${a}`:"";console.log(`env: server.ts reads ${d.join(", ")} but ${d.length>1?"they are":"it's"} unset${p}`)}}var kt=v(()=>{});import*as De from"fs/promises";import*as Pe from"path";function Hl(r){let[e,t,n,s]=r.split(Pe.sep).slice(-4);if(!(e!=="typebulbs"||t!=="u"||!n||!s?.endsWith(".bulb.md")))return{userSlug:n,slug:s.slice(0,-8)}}function Yl(r,e){ye(e);let t=process.env.TYPEBULB_ORIGIN||RE;try{return so(r,process.cwd(),t)}catch(n){console.error(n instanceof Error?n.message:String(n)),process.exit(1)}}function so(r,e,t){if(/^https?:\/\//i.test(r)){let i=new URL(r),o=i.pathname.split("/").filter(Boolean).map(decodeURIComponent),a=o[0]==="api"&&o[1]==="scripts"?o.slice(2):o;if(a[0]!=="u"||!a[1]||!a[2])throw new Error(`Not a bulb URL: ${r}
|
|
1053
|
+
Expected <origin>/u/<user>/<slug>`);let c=a[1],l=a[2].replace(/(\.bulb)?\.md$/,"");return{origin:i.origin,userSlug:c,slug:l,dest:Pe.join(e,no(c,l))}}let n=Pe.resolve(e,r),s=Hl(n);if(!s)throw new Error(`Not a conventional bulb path: ${r}
|
|
1054
|
+
A pull target must be a bulb URL, or a local file at typebulbs/u/<user>/<slug>.bulb.md \u2014 the path is its remote identity.`);return{origin:t,...s,dest:n}}async function io(r,e={}){let t=await fetch(Wl(r),{headers:e.token?{Authorization:`Bearer ${e.token}`}:{},signal:e.timeoutMs?AbortSignal.timeout(e.timeoutMs):void 0});if(!t.ok)return{kind:"http-error",status:t.status};let n=t.headers.get("content-type");if(!n?.includes("text/markdown"))return{kind:"not-markdown",contentType:n};let s=await t.text(),i;try{i=await De.readFile(r.dest,"utf-8")}catch{}if(i!==void 0){if(_E(i,s))return{kind:"up-to-date",dest:r.dest};if(!e.force){let{mtime:a}=await De.stat(r.dest);return{kind:"conflict",dest:r.dest,localMtime:a,remoteLastModified:t.headers.get("last-modified")}}}await De.mkdir(Pe.dirname(r.dest),{recursive:!0}),await De.writeFile(r.dest,s);let o=new Date(t.headers.get("last-modified")??"");return isNaN(o.getTime())||await De.utimes(r.dest,new Date,o),{kind:"written",dest:r.dest,created:i===void 0}}function _E(r,e){let t=i=>i.replace(/\r\n/g,`
|
|
1055
|
+
`),n=ce(t(r)),s=ce(t(e));return!n||!s?t(r)===t(e):n.frontmatter.name===s.frontmatter.name&&tt.every(i=>(n.files.get(Ce[i].path)||"")===(s.files.get(Ce[i].path)||""))}async function Rh(r,e){r||(console.error("Usage: typebulb pull <bulb url | typebulbs/u/<user>/<slug>.bulb.md>"),process.exit(1));let t=Yl(r,e.mode),n=`${t.origin}/u/${t.userSlug}/${t.slug}`,s;try{s=await io(t,{force:e.force,token:process.env.TYPEBULB_TOKEN})}catch(o){console.error(`Could not reach ${t.origin}: ${o instanceof Error?o.message:String(o)}`),process.exitCode=1;return}let i=Pe.relative(process.cwd(),t.dest)||t.dest;switch(s.kind){case"written":console.log(`pulled ${n} \u2192 ${i}${s.created?"":" (overwritten)"}`);return;case"up-to-date":console.log(`up to date: ${i}`);return;case"conflict":console.error(`Refusing to overwrite ${i} \u2014 it differs from ${n}
|
|
1056
1056
|
local file modified ${s.localMtime.toISOString()}
|
|
1057
1057
|
remote last saved ${s.remoteLastModified??"unknown"}
|
|
1058
|
-
Re-run with --force to overwrite the local file.`),process.exitCode=1;return;case"http-error":s.status===404?console.error(`Bulb not found: ${n}`):s.status===401||s.status===403?console.error(`This bulb is private (${s.status}) \u2014 pulling it needs a TYPEBULB_TOKEN for its owner.`):console.error(`Pull failed: ${t.origin} responded ${s.status}`),process.exitCode=1;return;case"not-markdown":console.error(`${n}.md did not return bulb markdown (got ${s.contentType??"no content-type"}) \u2014 is ${t.origin} a typebulb host?`),process.exitCode=1}}var
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1058
|
+
Re-run with --force to overwrite the local file.`),process.exitCode=1;return;case"http-error":s.status===404?console.error(`Bulb not found: ${n}`):s.status===401||s.status===403?console.error(`This bulb is private (${s.status}) \u2014 pulling it needs a TYPEBULB_TOKEN for its owner.`):console.error(`Pull failed: ${t.origin} responded ${s.status}`),process.exitCode=1;return;case"not-markdown":console.error(`${n}.md did not return bulb markdown (got ${s.contentType??"no content-type"}) \u2014 is ${t.origin} a typebulb host?`),process.exitCode=1}}var RE,no,Wl,Yn=v(()=>{kt();Ne();RE="https://typebulb.com",no=(r,e)=>Pe.join("typebulbs","u",r,`${e}.bulb.md`);Wl=r=>`${r.origin}/u/${encodeURIComponent(r.userSlug)}/${encodeURIComponent(r.slug)}.md`});import*as Vl from"fs/promises";import*as Vn from"path";var oo,_h=v(()=>{br();$n();yr();oo=class{async get(e){let t=ke(e),n=Vn.join(In,t+".bin"),s=Vn.join(In,t+".json");try{let[i,o]=await Promise.all([Vl.readFile(n),Vl.readFile(s,"utf8")]),a=JSON.parse(o);return{body:i,contentType:a.contentType,cacheControl:a.cacheControl}}catch{return}}async set(e,t){await G();let n=ke(e),s=Vn.join(In,n+".bin"),i=Vn.join(In,n+".json"),o={url:e,contentType:t.contentType,cacheControl:t.cacheControl};await Promise.all([he(s,t.body),he(i,JSON.stringify(o))])}}});var Nh,Ih=v(()=>{Nh=`
|
|
1059
|
+
const CSS = '\\n' +
|
|
1060
|
+
/* The agent mirror's token set, verbatim (agents/core/client/styles.css) \u2014 one system across CLI
|
|
1061
|
+
chrome: app chrome sits on --panel, content wells paint --veil, grays ride one neutral tint.
|
|
1062
|
+
The lone extension is --accent-contrast (text on a filled accent; the mirror never fills a
|
|
1063
|
+
button, and the dark theme's lighter accent needs dark text). */
|
|
1064
|
+
'.overlay { --fg: rgb(28, 28, 30); --muted: rgb(96, 96, 100); --panel: rgb(242, 242, 242);\\n' +
|
|
1065
|
+
' --border: rgb(221, 221, 221); --accent: rgb(58, 125, 232); --accent-contrast: #fff;\\n' +
|
|
1066
|
+
' --veil: rgba(0, 0, 0, 0.05); --err: rgb(206, 60, 60); }\\n' +
|
|
1067
|
+
'.dark .overlay { --fg: rgb(190, 190, 190); --muted: rgb(150, 150, 150); --panel: rgb(32, 32, 32);\\n' +
|
|
1068
|
+
' --border: rgb(52, 52, 52); --accent: rgb(122, 162, 250); --accent-contrast: #1c1e21;\\n' +
|
|
1069
|
+
' --veil: rgba(255, 255, 255, 0.06); --err: rgb(230, 60, 60); }\\n' +
|
|
1070
|
+
'.overlay { position: fixed; inset: 0; background: rgba(0,0,0,.45); z-index: 2147483000;\\n' +
|
|
1071
|
+
' display: flex; align-items: center; justify-content: center; padding: 16px;\\n' +
|
|
1072
|
+
' font: 14px/1.45 system-ui, sans-serif; color: var(--fg); }\\n' +
|
|
1073
|
+
'.card { background: var(--panel); border-radius: 10px; box-shadow: 0 12px 40px rgba(0,0,0,.35);\\n' +
|
|
1074
|
+
' width: min(560px, 100%); max-height: min(80vh, 640px); display: flex; flex-direction: column; }\\n' +
|
|
1075
|
+
'.head { display: flex; align-items: center; gap: 8px; padding: 14px 16px 10px; }\\n' +
|
|
1076
|
+
'.head h1 { font-size: 18px; font-weight: 600; margin: 0; flex: 1; color: var(--accent); }\\n' +
|
|
1077
|
+
'.x { border: 0; background: none; color: inherit; font-size: 18px; cursor: pointer; opacity: .6; padding: 2px 6px; }\\n' +
|
|
1078
|
+
'.x:hover { opacity: 1; }\\n' +
|
|
1079
|
+
'.body { padding: 0 16px; overflow-y: auto; flex: 1; display: flex; flex-direction: column; gap: 10px; }\\n' +
|
|
1080
|
+
'.model { color: var(--muted); }\\n' +
|
|
1081
|
+
'.model.err { color: var(--err); }\\n' +
|
|
1082
|
+
'label { font-weight: 600; }\\n' +
|
|
1083
|
+
'.tabs { display: flex; gap: 4px; }\\n' +
|
|
1084
|
+
'.tab { font: inherit; padding: 4px 10px; border: 0; border-bottom: 2px solid transparent; border-radius: 0; background: none; color: inherit; cursor: pointer; opacity: .6; }\\n' +
|
|
1085
|
+
'.tab.on { opacity: 1; border-bottom-color: var(--accent); }\\n' +
|
|
1086
|
+
'.tab .cnt { opacity: .6; font-size: 12px; margin-left: 4px; }\\n' +
|
|
1087
|
+
'textarea { width: 100%; box-sizing: border-box; min-height: 160px; max-height: 320px; resize: vertical;\\n' +
|
|
1088
|
+
' font: 13px/1.4 ui-monospace, monospace; padding: 8px; border-radius: 6px;\\n' +
|
|
1089
|
+
' border: 1px solid var(--border); background: var(--veil); color: inherit; }\\n' +
|
|
1090
|
+
'pre.stream { font: 13px/1.4 ui-monospace, monospace; white-space: pre-wrap; word-break: break-word;\\n' +
|
|
1091
|
+
' background: var(--veil); border-radius: 6px; padding: 10px; margin: 0; min-height: 120px; }\\n' +
|
|
1092
|
+
'.error { color: var(--err); white-space: pre-wrap; }\\n' +
|
|
1093
|
+
'.foot { display: flex; gap: 8px; padding: 12px 16px 14px; justify-content: flex-end; align-items: center; }\\n' +
|
|
1094
|
+
'.leftgrp { margin-right: auto; display: flex; gap: 8px; }\\n' +
|
|
1095
|
+
'button { font: inherit; padding: 6px 14px; border-radius: 6px; cursor: pointer;\\n' +
|
|
1096
|
+
' border: 1px solid var(--border); background: transparent; color: inherit; }\\n' +
|
|
1097
|
+
'button.run { background: var(--accent); border-color: var(--accent); color: var(--accent-contrast); }\\n' +
|
|
1098
|
+
'button.run:disabled { opacity: .5; cursor: default; }\\n' +
|
|
1099
|
+
'@keyframes shimmer { 0% { background-position: 200% 0; } 100% { background-position: -200% 0; } }\\n' +
|
|
1100
|
+
'.shimmer { display: inline-block; background-image: linear-gradient(90deg, var(--muted), var(--fg), var(--muted));\\n' +
|
|
1101
|
+
' background-size: 200% 100%; -webkit-background-clip: text; background-clip: text;\\n' +
|
|
1102
|
+
' -webkit-text-fill-color: transparent; color: transparent; animation: shimmer 2s linear infinite; }\\n';
|
|
1065
1103
|
|
|
1066
|
-
|
|
1067
|
-
|
|
1104
|
+
function isDark() {
|
|
1105
|
+
var t = document.documentElement.getAttribute('data-theme');
|
|
1106
|
+
if (t) return t === 'dark';
|
|
1107
|
+
return window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
|
|
1108
|
+
}
|
|
1068
1109
|
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
function resolveBash() {
|
|
1075
|
-
try {
|
|
1076
|
-
if (process.platform !== "win32") return existsSync("/bin/bash") ? "/bin/bash" : null;
|
|
1077
|
-
var dirs = [process.env.ProgramFiles, process.env["ProgramFiles(x86)"]];
|
|
1078
|
-
for (var i = 0; i < dirs.length; i++) {
|
|
1079
|
-
if (dirs[i] && existsSync(dirs[i] + "\\Git\\bin\\bash.exe")) return dirs[i] + "\\Git\\bin\\bash.exe";
|
|
1080
|
-
}
|
|
1081
|
-
return "bash.exe"; // PATH fallback (Cygwin/MSYS2); a spawn miss lands in the "error" handler
|
|
1082
|
-
} catch (e) { return null; }
|
|
1110
|
+
function el(tag, cls, text) {
|
|
1111
|
+
var e = document.createElement(tag);
|
|
1112
|
+
if (cls) e.className = cls;
|
|
1113
|
+
if (text != null) e.textContent = text;
|
|
1114
|
+
return e;
|
|
1083
1115
|
}
|
|
1084
1116
|
|
|
1085
|
-
//
|
|
1086
|
-
//
|
|
1087
|
-
|
|
1088
|
-
|
|
1117
|
+
// Per-chunk label: config dataTitle (comma-delimited) > a #/// comment-header first line > Data N.
|
|
1118
|
+
// The same fallback chain as .com's DataChunkEditor.
|
|
1119
|
+
function chunkLabel(chunk, i, titles) {
|
|
1120
|
+
if (titles[i]) return titles[i];
|
|
1121
|
+
var first = (chunk.split('\\n')[0] || '').trim();
|
|
1122
|
+
if (first.charAt(0) === '#' && first.length > 1 && first.length < 40) return first.replace(/^#+\\s*/, '');
|
|
1123
|
+
if (first.indexOf('//') === 0 && first.length > 2 && first.length < 40) return first.replace(/^\\/\\/\\s*/, '');
|
|
1124
|
+
return 'Data ' + (i + 1);
|
|
1125
|
+
}
|
|
1089
1126
|
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
" Read the authoring skill before writing a bulb:",
|
|
1105
|
-
" • npx typebulb skill — assembles one SKILL.md",
|
|
1106
|
-
" • or, open its parts:",
|
|
1107
|
-
" " + TB_DESCRIPTION_PATH,
|
|
1108
|
-
" " + TB_README_PATH,
|
|
1109
|
-
].join("\n");
|
|
1127
|
+
/**
|
|
1128
|
+
* Open the inference modal. ctx: { data: string[], readStream(resp), onComplete(final),
|
|
1129
|
+
* onError(err), onCancel() }. readStream is the SHIM's NDJSON reader (an async iterable of chunk
|
|
1130
|
+
* values that throws error envelopes as Error with code/retryable) \u2014 passed in so the page has
|
|
1131
|
+
* exactly one copy of the transport decoder. onComplete fires on every successful run (a retry
|
|
1132
|
+
* after an error included); onError on each displayed terminal error; onCancel when the user
|
|
1133
|
+
* closes before any completion.
|
|
1134
|
+
*/
|
|
1135
|
+
export function runInference(ctx) {
|
|
1136
|
+
var host = document.createElement('div');
|
|
1137
|
+
var root = host.attachShadow({ mode: 'closed' });
|
|
1138
|
+
var style = document.createElement('style');
|
|
1139
|
+
style.textContent = CSS;
|
|
1140
|
+
root.appendChild(style);
|
|
1110
1141
|
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
|
|
1142
|
+
var wrap = el('div', isDark() ? 'dark' : '');
|
|
1143
|
+
root.appendChild(wrap);
|
|
1144
|
+
var overlay = el('div', 'overlay');
|
|
1145
|
+
wrap.appendChild(overlay);
|
|
1146
|
+
var card = el('div', 'card');
|
|
1147
|
+
overlay.appendChild(card);
|
|
1114
1148
|
|
|
1115
|
-
|
|
1116
|
-
|
|
1117
|
-
|
|
1118
|
-
|
|
1119
|
-
|
|
1120
|
-
});
|
|
1149
|
+
var completed = false;
|
|
1150
|
+
var canceled = false;
|
|
1151
|
+
var aborter = null;
|
|
1152
|
+
var inferCfg = {};
|
|
1153
|
+
var dataTitles = function () {
|
|
1154
|
+
return String(inferCfg.dataTitle || '').split(',').map(function (s) { return s.trim(); }).filter(Boolean);
|
|
1155
|
+
};
|
|
1121
1156
|
|
|
1122
|
-
|
|
1123
|
-
|
|
1124
|
-
|
|
1125
|
-
|
|
1126
|
-
|
|
1157
|
+
function close(kind) {
|
|
1158
|
+
if (kind === 'cancel') canceled = true;
|
|
1159
|
+
if (aborter) { aborter.abort(); aborter = null; }
|
|
1160
|
+
host.remove();
|
|
1161
|
+
if (kind === 'cancel' && !completed) ctx.onCancel();
|
|
1162
|
+
}
|
|
1163
|
+
overlay.addEventListener('click', function (e) { if (e.target === overlay) close('cancel'); });
|
|
1127
1164
|
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
-
// output, firing the wake before the event while the detached wait delivers to nobody
|
|
1136
|
-
// (field: Toroidal Life, '> /tmp/x.log 2>&1 &'). Strip a trailing "&" so the wait runs
|
|
1137
|
-
// foreground inside the shim's already-backgrounded child.
|
|
1138
|
-
const cmd = String(command).replace(/(?<!&)\s*&\s*$/, "");
|
|
1139
|
-
const bash = resolveBash();
|
|
1140
|
-
const opts = {
|
|
1141
|
-
stdio: ["ignore", "pipe", "pipe"],
|
|
1142
|
-
env: { ...process.env, TYPEBULB_WAIT_SHIM: "1" },
|
|
1143
|
-
};
|
|
1144
|
-
const child = bash ? spawn(bash, ["-c", cmd], opts) : spawn(cmd, { ...opts, shell: true });
|
|
1145
|
-
pending.add(child);
|
|
1146
|
-
let out = "";
|
|
1147
|
-
let errOut = "";
|
|
1148
|
-
if (child.stdout) child.stdout.on("data", (b) => { out += b.toString(); });
|
|
1149
|
-
if (child.stderr) child.stderr.on("data", (b) => { errOut += b.toString(); });
|
|
1150
|
-
child.on("error", (e) => {
|
|
1151
|
-
pending.delete(child);
|
|
1152
|
-
logErr("spawn", e && e.message);
|
|
1153
|
-
// Same class as a failure exit: the subscription never armed, so silence is a deadlock.
|
|
1154
|
-
try { pi.sendUserMessage("typebulb wait FAILED to spawn: " + (e && e.message) + "\nNothing is watching — fix and re-arm the wait.", { deliverAs: "followUp" }); } catch (e2) {}
|
|
1155
|
-
});
|
|
1156
|
-
child.on("exit", (code) => {
|
|
1157
|
-
pending.delete(child);
|
|
1158
|
-
try {
|
|
1159
|
-
const text = out.trim();
|
|
1160
|
-
// Exit 0 with output is a real outcome (embed ok/error, a turn-based move) -> wake the
|
|
1161
|
-
// agent (followUp delivers immediately when idle and queues when streaming — the same call
|
|
1162
|
-
// git-merge-and-resolve.ts makes from agent_end). A late wake is fine; it just reports
|
|
1163
|
-
// something true. Exit 2/3 (no render yet / server gone) surface passively, no turn.
|
|
1164
|
-
// Any OTHER non-zero exit means the subscription itself broke (bad args, no resolvable
|
|
1165
|
-
// mirror): the agent parked on a wake that can never come, so that failure must wake too —
|
|
1166
|
-
// missed wakes are fatal, spurious wakes cheap (TB-Wait.md). null (reap-killed) stays silent.
|
|
1167
|
-
// EXCEPT an embed's clean ok verdict ("[embed <name> vN] ok" — core/client/bulbEmbed.ts):
|
|
1168
|
-
// the user already sees the bulb and the skill orders silence on ok, so a wake would spend
|
|
1169
|
-
// a whole turn saying nothing and render a noise message. Silence IS the ok. Anything else
|
|
1170
|
-
// (an embed error, a turn-based loop event) still wakes; an unrecognized shape wakes too.
|
|
1171
|
-
// Checked PER LINE, not over the whole blob: wait lingers 10s and bursts every matching line
|
|
1172
|
-
// into one payload, and a version-agnostic --match ("[embed <name>") replays v1+v2+... from
|
|
1173
|
-
// log start, so an all-ok payload is routinely multi-line. Suppress iff EVERY line is an ok;
|
|
1174
|
-
// one error line among oks still wakes.
|
|
1175
|
-
var waitLines = text.split("\n").map(function (l) { return l.trim(); }).filter(Boolean);
|
|
1176
|
-
const embedOk = code === 0 && waitLines.length > 0 && waitLines.every(function (l) { return /^\[embed .*\] ok$/.test(l); });
|
|
1177
|
-
if (code === 0 && text && !embedOk) {
|
|
1178
|
-
pi.sendUserMessage("typebulb wait result:\n" + text, { deliverAs: "followUp" });
|
|
1179
|
-
} else if (code === 0 && !text) {
|
|
1180
|
-
// A successful wait always prints its matched line(s), so exit 0 with nothing captured
|
|
1181
|
-
// means the agent redirected stdout (e.g. '> /tmp/x.log 2>&1') — the verdict landed in a
|
|
1182
|
-
// file nobody reads. The line is still in the mirror's log; point the agent there.
|
|
1183
|
-
pi.sendUserMessage("typebulb wait ended (exit 0) but its output was redirected away — read the verdict with: typebulb logs agent\nNext time run the wait plainly: no output redirect, no trailing &.", { deliverAs: "followUp" });
|
|
1184
|
-
} else if (code !== null && code !== 0 && code !== 2 && code !== 3) {
|
|
1185
|
-
var diag = (text + "\n" + errOut.trim()).trim();
|
|
1186
|
-
pi.sendUserMessage("typebulb wait FAILED (exit " + code + ")" + (diag ? ":\n" + diag : " with no output.") + "\nThe wait never armed — nothing is watching. Fix the command and re-arm it.", { deliverAs: "followUp" });
|
|
1187
|
-
} else if (ctx.ui && typeof ctx.ui.notify === "function") {
|
|
1188
|
-
// INVARIANT: this notify must never quote the "[embed <name>" tag verbatim. In a
|
|
1189
|
-
// composer-driven session the mirror's driver echoes extension notifies into the
|
|
1190
|
-
// mirror's own log (driver.ts) — the very log wait watches by substring — so a
|
|
1191
|
-
// verbatim tag re-fires the next same-match wait with a non-ok line: a self-
|
|
1192
|
-
// sustaining wake loop that defeats this suppression (TB-Wait.md). Stripping the
|
|
1193
|
-
// brackets kills the matchable substring while keeping the verdict readable.
|
|
1194
|
-
ctx.ui.notify("typebulb wait: " + (embedOk ? text.replace(/[\[\]]/g, "") : code === 2 ? "timed out, nothing to report" : "ended (code " + code + ")"), "info");
|
|
1195
|
-
}
|
|
1196
|
-
} catch (e) { logErr("exit", e && e.message); }
|
|
1197
|
-
});
|
|
1165
|
+
var head = el('div', 'head');
|
|
1166
|
+
var title = el('h1', '', 'Run AI inference');
|
|
1167
|
+
head.appendChild(title);
|
|
1168
|
+
var x = el('button', 'x', '\\u00d7');
|
|
1169
|
+
x.addEventListener('click', function () { close('cancel'); });
|
|
1170
|
+
head.appendChild(x);
|
|
1171
|
+
card.appendChild(head);
|
|
1198
1172
|
|
|
1199
|
-
|
|
1200
|
-
|
|
1201
|
-
|
|
1202
|
-
|
|
1203
|
-
} catch (e) { logErr("tool_call", e && e.message); return undefined; }
|
|
1204
|
-
});
|
|
1173
|
+
var body = el('div', 'body');
|
|
1174
|
+
card.appendChild(body);
|
|
1175
|
+
var foot = el('div', 'foot');
|
|
1176
|
+
card.appendChild(foot);
|
|
1205
1177
|
|
|
1206
|
-
|
|
1207
|
-
|
|
1208
|
-
|
|
1209
|
-
|
|
1210
|
-
`))>=0;){let o=n.slice(0,i);n=n.slice(i+1),o.endsWith("\r")&&(o=o.slice(0,-1)),o&&e(o)}})}var IE,$E,Ch,LE,ME,DE,BE,jE,ao,co,_h,Rh=S(()=>{Et();IE=3e4,$E=5e3,Ch=2e3,LE=2e3,ME=12e4,DE=8e3,BE=15e3,jE=new Set(["get_state","get_commands","get_available_models","set_model","set_thinking_level","cycle_thinking_level","get_session_stats","compact","set_auto_compaction","get_fork_messages","fork","clone","set_session_name","export_html","bash","abort_bash"]),ao=new Set;process.on("exit",()=>{for(let r of ao)try{r.kill()}catch{}});co=class{#e;#a=!1;#c=0;#i=!1;#l=null;#m=null;#t=null;#n=null;#u=new Map;#r=[];#h=null;#w=null;#g=null;#f;#d;#y="";#A=1;#s=new Map;#v;#b;constructor(e,t,n=(s,i)=>Oh(s,{cwd:i,shell:!0,stdio:["pipe","pipe","pipe"],env:{...process.env,TYPEBULB_MIRROR:"1"}})){if(this.#v=new Promise(o=>{this.#b=o}),t?.includes('"')){this.#d="session path contains a quote \u2014 cannot drive it",this.#b();return}let s=t?`pi --mode rpc --session "${t}"`:"pi --mode rpc",i;try{i=n(s,e)}catch(o){this.#d=`could not start pi: ${J(o)}`,this.#b();return}this.#e=i,this.#f=t,ao.add(i),i.stdout&&FE(i.stdout,o=>this.#T(o)),i.stderr&&i.stderr.on("data",o=>{this.#y=(this.#y+o.toString()).slice(-LE)}),i.on("error",o=>this.#x(`could not start pi: ${o.message}`)),i.on("exit",o=>{this.#e===i&&this.#x(o?`pi exited (code ${o})${this.#y.trim()?`: ${this.#y.trim()}`:""}`:"pi exited"),ao.delete(i),this.#b()}),this.#o({type:"get_state"}).then(o=>{let a=o.data?.sessionFile;typeof a=="string"&&a&&(this.#f=a);let c=o.data?.model;c&&typeof c.id=="string"&&c.id&&(this.#g=c.id)}).catch(()=>{}),this.#S()}get streaming(){return this.#a||Date.now()<this.#c}get draft(){return this.#l}get echo(){return this.#m}get queue(){return this.#h}get stats(){return this.#w}get model(){return this.#g}get sessionFile(){return this.#f}get error(){return this.#d}get status(){if(this.#t)return this.#t;if(this.#n){if(Date.now()<this.#n.until)return{text:this.#n.text,kind:this.#n.kind};this.#n=null}return this.#u.size?{text:[...this.#u.values()].join(" \xB7 "),kind:"info"}:null}get dialog(){let e=Date.now();for(;this.#r.length;){let t=this.#r[0];if(e<t.until)return t.req;this.#r.shift(),t.ownTimeout||this.#k({type:"extension_ui_response",id:t.req.id,cancelled:!0})}return null}notice(e,t){this.#p(e,t)}respondUi(e,t){let n=this.#r.findIndex(o=>o.req.id===e);if(n<0)return{ok:!1,error:"dialog expired or already answered"};let[s]=this.#r.splice(n,1),i={type:"extension_ui_response",id:e};return t.cancelled?i.cancelled=!0:s.req.method==="confirm"?i.confirmed=!!t.confirmed:i.value=t.value??"",this.#k(i),{ok:!0}}async rpc(e){if(!jE.has(e.type))return{ok:!1,error:`command not allowed: ${e.type}`};try{let t=await this.#o(e);if(t.success&&e.type==="set_model"){let n=t.data?.id;typeof n=="string"&&n&&(this.#g=n)}if(t.success&&(e.type==="fork"||e.type==="clone")){try{let s=(await this.#o({type:"get_state"})).data?.sessionFile;typeof s=="string"&&s&&(this.#f=s)}catch{}return{ok:!0,data:{...t.data??{},sessionFile:this.#f}}}return t.success?{ok:!0,data:t.data}:{ok:!1,error:t.error??`pi rejected ${e.type}`}}catch(t){return{ok:!1,error:J(t)}}}async send(e,t){let n=this.streaming,s=n?e.trimStart().startsWith("/")?{type:"prompt",message:e,streamingBehavior:t?.followUp?"followUp":"steer"}:{type:t?.followUp?"follow_up":"steer",message:e}:{type:"prompt",message:e},i;try{i=await this.#o(s)}catch(o){return{ok:!1,error:J(o)}}return i.success&&!n&&(this.#c=Date.now()+$E),i.success&&!n&&!e.trimStart().startsWith("/")&&(this.#m=e),i.success?{ok:!0}:{ok:!1,error:i.error??"pi rejected the message"}}async stop(){if(this.#e)try{await this.#o({type:"abort"})}catch{}}clearCompletedDraft(){this.#i||(this.#l=null)}clearEcho(){this.#m=null}async dispose(){let e=this.#e;if(e){if(this.#e=void 0,this.#a){try{e.stdin?.write(JSON.stringify({type:"abort"})+`
|
|
1211
|
-
`)}catch{}await Promise.race([this.#v,_h(Ch)])}try{e.stdin?.end()}catch{}if(await Promise.race([this.#v,_h(Ch)]),e.exitCode===null&&!e.killed)if(process.platform==="win32"&&e.pid)try{Oh("taskkill",["/pid",String(e.pid),"/T","/F"],{stdio:"ignore"})}catch{}else try{e.kill("SIGKILL")}catch{}ao.delete(e),this.#r=[],this.#E("pi was shut down")}}#k(e){try{this.#e?.stdin?.write(JSON.stringify(e)+`
|
|
1212
|
-
`)}catch{}}#p(e,t){let n=e.length>200?e.slice(0,200)+"\u2026":e;n&&(this.#n={text:n,kind:t,until:Date.now()+(t==="info"?DE:BE)})}#S(){this.#o({type:"get_session_stats"}).then(e=>{if(!e.success||!e.data)return;let t=e.data;this.#w={cost:typeof t.cost=="number"?t.cost:0,contextTokens:typeof t.contextUsage?.tokens=="number"?t.contextUsage.tokens:null,contextPercent:typeof t.contextUsage?.percent=="number"?t.contextUsage.percent:null}}).catch(()=>{})}#o(e){let t=this.#e;if(!t?.stdin?.writable)return Promise.reject(new Error(this.#d??"pi is not running"));let n=`tb-${this.#A++}`;return new Promise((s,i)=>{let o=setTimeout(()=>{this.#s.delete(n),i(new Error("pi did not respond (30s)"))},IE);o.unref?.(),this.#s.set(n,{resolve:s,timer:o});try{t.stdin.write(JSON.stringify({id:n,...e})+`
|
|
1213
|
-
`)}catch(a){clearTimeout(o),this.#s.delete(n),i(new Error(J(a)))}})}#T(e){let t;try{t=JSON.parse(e)}catch{return}switch(t.type){case"response":{let n=t,s=n.id?this.#s.get(n.id):void 0;s&&(this.#s.delete(n.id),clearTimeout(s.timer),s.resolve(n));return}case"agent_start":this.#a=!0,this.#c=0;return;case"agent_end":this.#a=!1,this.#c=0,this.#i=!1,this.#t=null,this.#h=null,this.#S();return;case"message_start":{t.message?.role==="assistant"&&(this.#i=!0,this.#l={text:"",thinking:""});return}case"message_update":{if(!this.#i)return;let n=t.message,s=Array.isArray(n?.content)?n.content:[],i=s[s.length-1];this.#l={text:s.filter(o=>o?.type==="text").map(o=>o.text??"").join(""),thinking:s.filter(o=>o?.type==="thinking").map(o=>o.thinking??"").join(`
|
|
1214
|
-
`),tool:i?.type==="toolCall"?i.name:void 0};return}case"message_end":this.#i=!1;return;case"auto_retry_start":this.#t={text:`retrying after a transient error (attempt ${Number(t.attempt)||1}/${Number(t.maxAttempts)||"?"})\u2026`,kind:"warning"};return;case"auto_retry_end":this.#t=null,t.success===!1&&this.#p(`retries exhausted: ${String(t.finalError??"unknown error")}`,"error");return;case"compaction_start":this.#t={text:"compacting context\u2026",kind:"info"};return;case"compaction_end":{this.#t=null;let n=t.result;typeof t.errorMessage=="string"&&t.errorMessage?this.#p(`compaction failed: ${t.errorMessage}`,"error"):n?.tokensBefore&&this.#p(`compacted: ~${Math.round(n.tokensBefore/1e3)}k \u2192 ~${Math.round((n.estimatedTokensAfter??0)/1e3)}k tokens`,"info"),this.#S();return}case"queue_update":{let n=Array.isArray(t.steering)?t.steering.map(String):[],s=Array.isArray(t.followUp)?t.followUp.map(String):[];this.#h=n.length||s.length?{steering:n,followUp:s}:null;return}case"extension_ui_request":{let n=String(t.method??"");if(n==="select"||n==="confirm"||n==="input"||n==="editor"){let s=typeof t.timeout=="number"&&t.timeout>0?t.timeout:void 0;this.#r.push({req:{id:String(t.id??""),method:n,title:typeof t.title=="string"?t.title:void 0,message:typeof t.message=="string"?t.message:void 0,options:Array.isArray(t.options)?t.options.map(String):void 0,placeholder:typeof t.placeholder=="string"?t.placeholder:void 0,prefill:typeof t.prefill=="string"?t.prefill:void 0},until:Date.now()+(s??ME),ownTimeout:s!==void 0})}else if(n==="notify"){let s=t.notifyType==="warning"?"warning":t.notifyType==="error"?"error":"info";this.#p(String(t.message??""),s),console.log(`[composer] pi extension: ${String(t.message??"")}`)}else if(n==="setStatus"){let s=String(t.statusKey??"");typeof t.statusText=="string"&&t.statusText?this.#u.set(s,t.statusText):this.#u.delete(s)}return}default:return}}#x(e){this.#d=e,this.#a=!1,this.#c=0,this.#i=!1,this.#l=null,this.#m=null,this.#t=null,this.#n=null,this.#u.clear(),this.#r=[],this.#h=null,this.#w=null,this.#g=null,this.#e=void 0,this.#E(e)}#E(e){for(let[,t]of this.#s)clearTimeout(t.timer),t.resolve({type:"response",success:!1,error:e});this.#s.clear()}},_h=r=>new Promise(e=>{setTimeout(e,r).unref?.()})});import{existsSync as Nh,readFileSync as qE,realpathSync as UE}from"fs";import{join as Xt,dirname as Mh,resolve as JE}from"path";import{homedir as Ih}from"os";function HE(r,e){let t=Xt(r,".pi");if(KE.some(s=>Nh(Xt(t,s))))return!0;let n=Xt(e,".agents","skills");for(let s=r;;){let i=Xt(s,".agents","skills");if(i!==n&&Nh(i))return!0;let o=Mh(s);if(o===s)return!1;s=o}}function WE(r,e){for(let t=e;;){if(r[t]===!0||r[t]===!1)return!0;let n=Mh(t);if(n===t)return!1;t=n}}function Dh(r,e){try{let t=e?.agentDir??Xt(Ih(),".pi","agent"),n=$h(e?.home??process.env.HOME??Ih()),s=$h(JE(r));if(!HE(s,n))return null;let i=Lh(Xt(t,"settings.json")).defaultProjectTrust;return i==="always"||i==="never"||WE(Lh(Xt(t,"trust.json")),s)?null:"pi has no trust decision for this project \u2014 running untrusted; run `pi` once in a terminal to grant it"}catch{return null}}var KE,$h,Lh,Bh=S(()=>{KE=["settings.json","extensions","skills","prompts","themes","SYSTEM.md","APPEND_SYSTEM.md"],$h=r=>{try{return UE(r)}catch{return r}},Lh=r=>{try{return JSON.parse(qE(r,"utf8"))}catch{return{}}}});import{statSync as YE,openSync as VE,readSync as GE,closeSync as zE,existsSync as Fh}from"fs";import{join as lo}from"path";import{homedir as Kl}from"os";import{execFile as XE}from"child_process";async function ZE(r){let e=lo(Kl(),".pi","agent","bin",process.platform==="win32"?"fd.exe":"fd");for(let t of["fd","fdfind",...Fh(e)?[e]:[]]){let n=await new Promise(s=>{XE(t,["--base-directory",r,"--type","f","--follow","--hidden","--exclude",".git"],{maxBuffer:67108864},(i,o)=>s(i?null:o))});if(n!==null)return n.split(`
|
|
1215
|
-
`).filter(Boolean).map(s=>s.replace(/\\/g,"/"))}return null}function eA(r){return`--${r.replace(/^[/\\]/,"").replace(/[/\\:]/g,"-")}--`}function jh(r){return r.type==="message"?tA(r.message?.role):r.type==="custom_message"?r.display!==!1:!1}var QE,tA,Lr,Hl=S(()=>{Ui();Sl();kl();Ph();Rh();Bh();QE=lo(Kl(),".pi","agent","sessions");tA=r=>r==="user"||r==="assistant"||r==="toolResult"||r==="bashExecution";Lr=class extends Cr{displayName="Pi Mirror";detectsSelf(){return process.env.PI_CODING_AGENT==="true"}detectsInstalled(){return Fh(lo(Kl(),".pi","agent"))}ensureHarnessSupport(){Th()}createDriver(e,t){let n=new co(e,t),s=Dh(e);return s&&n.notice(s,"warning"),n}walkFiles(e){return ZE(e)}sessionsDir(e){return lo(QE,eA(e))}listSessionFiles(e){return Ji(this.sessionsDir(e))}parseEntry(e){let t;try{t=JSON.parse(e)}catch{return null}return!t||t.type==="session"||!t.id?null:t}idOf(e){return e.id}parentOf(e){return e.parentId??void 0}timestampOf(e){return e.timestamp}isSidechain(e){return!1}isLeafType(e){return jh(e)}isRecoveryNoise(e){return!1}apply(e,t){let n=[];if(e.type==="custom_message"){if(e.display===!1)return{events:n};let i=this.contentText(e.content).trim();return i&&n.push({type:"user",text:i}),{events:n}}if(e.type!=="message"||!e.message)return{events:n};let s=e.message;if(s.role==="user"){let i=this.contentText(s.content).trim();return i&&n.push({type:"user",text:i}),{events:n}}if(s.role==="toolResult"){let i=this.contentText(s.content);return n.push({type:"tool_result",id:s.toolCallId??"",content:i,isError:!!s.isError,digest:Xe(i)}),{events:n}}if(s.role==="bashExecution")return s.command&&!s.excludeFromContext&&n.push({type:"user",text:`$ ${s.command}`}),{events:n};if(s.role==="assistant"){let i=Array.isArray(s.content)?s.content:[],o=i.filter(f=>f.type==="text").map(f=>f.text??"").join(""),a=i.filter(f=>f.type==="thinking").map(f=>f.thinking??"").join(`
|
|
1216
|
-
`),c=i.filter(f=>f.type==="toolCall").map(f=>({id:f.id??"",name:f.name??"",input:f.arguments??{}}));if(o||a||c.length){let f=Date.parse(e.timestamp??""),p=!isNaN(f)&&f>=t;n.push({type:"assistant",text:o,thinking:a,tools:c,live:p})}let l=s.usage,d=l?(l.input??0)+(l.output??0)+(l.cacheRead??0)+(l.cacheWrite??0):0,u=l&&d>0&&s.stopReason!=="aborted"&&s.stopReason!=="error"?{in:l.input??0,out:l.output??0,cached:l.cacheRead??0,cacheCreate:l.cacheWrite??0}:void 0;return{events:n,usage:u,model:s.model,cost:l?.cost?.total}}return{events:n}}chainWorking(e){let t;for(let a of e)jh(a)&&(t=a);if(!t||t.type==="custom_message")return!1;let n=t.message.role;if(n==="user"||n==="toolResult"||n==="bashExecution")return!0;if(n!=="assistant")return!1;let i=(Array.isArray(t.message.content)?t.message.content:[]).filter(a=>a.type==="toolCall").map(a=>a.id);if(!i.length)return!1;let o=new Set;for(let a of e)a.type==="message"&&a.message?.role==="toolResult"&&a.message.toolCallId&&o.add(a.message.toolCallId);return i.some(a=>a&&!o.has(a))}sessionAlive(){}readPreview(e){let t;try{t=VE(e,"r")}catch{return""}try{let s=65536;try{s=YE(e).size}catch{}let i=(u,f)=>{let p=Buffer.alloc(f),b=GE(t,p,0,f,u);return p.subarray(0,b).toString("utf8")},o=i(0,Math.min(65536,s)),a=s>65536?i(s-65536,65536):"",c=u=>{let f="";for(let p of u.split(`
|
|
1217
|
-
`))if(p.includes('"session_info"'))try{let b=JSON.parse(p);b?.type==="session_info"&&typeof b.name=="string"&&b.name&&(f=b.name)}catch{}return f},l="";for(let u of o.split(`
|
|
1218
|
-
`))if(!(l||!u.includes('"type"')))try{let f=JSON.parse(u);f?.type==="message"&&f.message?.role==="user"&&(l=this.contentText(f.message.content).replace(/\s+/g," ").trim())}catch{}let d=c(a)||c(o)||l;return d?d.slice(0,200):""}finally{zE(t)}}searchText(e){if(e?.type!=="message")return"";let t=e.message?.role;if(t!=="user"&&t!=="assistant")return"";let n=e.message?.content,s="";return typeof n=="string"?s=n:Array.isArray(n)&&(s=n.filter(i=>i.type==="text"&&typeof i.text=="string").map(i=>i.text).join(" ")),s.replace(/\s+/g," ").trim()}contentText(e){return typeof e=="string"?Ne(e):Array.isArray(e)?e.map(t=>typeof t?.text=="string"?Ne(t.text):t?.type==="image"&&t.data?qi(t.data,t.mimeType):"").filter(Boolean).join(`
|
|
1219
|
-
`):""}}});var uo,qh=S(()=>{uo=class{#e=new Map;accept(e,t){return this.#e.get(e)===t?!1:(this.#e.set(e,t),!0)}}});import{execFile as rA}from"child_process";import{promisify as nA}from"util";import{readFile as sA}from"fs/promises";import{resolve as Uh,sep as iA}from"path";async function Be(r,e){let{stdout:t}=await oA("git",r,{cwd:e,maxBuffer:67108864});return t}async function Mr(){if(fo)return fo;try{fo=(await Be(["rev-parse","--show-toplevel"],Y)).trim()}catch{}return fo}function aA(r,e){let t=e===" "?r:e;return t==="?"?"U":t}async function Kh(){let r=await Mr();if(!r)return{repo:!1,root:"",files:[]};try{let e=await Be(["status","--porcelain","-z"],r),t=[],n=e.split("\0");for(let s=0;s<n.length;s++){let i=n[s];i.length<4||((i[0]==="R"||i[0]==="C")&&s++,t.push({path:i.slice(3),status:aA(i[0],i[1])}))}try{let s=await Be(["diff","--numstat","HEAD"],r),i=new Map;for(let o of s.split(`
|
|
1220
|
-
`)){let a=/^(\d+)\t(\d+)\t(.+)$/.exec(o);a&&i.set(a[3],{add:+a[1],del:+a[2]})}for(let o of t){let a=i.get(o.path);a&&(o.add=a.add,o.del=a.del)}}catch{}return t.sort((s,i)=>s.path.localeCompare(i.path)),{repo:!0,root:r,files:t}}catch(e){return{repo:!1,root:"",files:[],error:J(e)}}}async function Hh(r){let e=await Mr();if(!e)return{ok:!1,error:"not a git repository"};try{if((await Be(["status","--porcelain","-z","--",r],e)).startsWith("??")){let s=Uh(e,r);if(!s.startsWith(Uh(e)+iA))return{ok:!1,error:"outside repository"};let i=await sA(s);return i.includes(0)?Wl("Binary file (not shown)",!1):Wl(i.toString("utf8"),!0)}let n;try{n=await Be(["diff","--no-color","--unified=999999","HEAD","--",r],e)}catch{n=await Be(["diff","--no-color","--unified=999999","--",r],e)}return Wl(n,!1)}catch(t){return{ok:!1,error:J(t)}}}var oA,Jh,fo,Wl,po=S(()=>{Et();oA=nA(rA),Jh=2e6;Wl=(r,e)=>({ok:!0,text:r.slice(0,Jh),untracked:e,truncated:r.length>Jh})});function mo(r,e){let t=0,n="";for(let s of r){let i=s.lower.indexOf(e);if(!(i<0)&&(t++,!n)){let o=Math.max(0,i-110),a=Math.min(s.text.length,i+e.length+110);n=(o>0?"\u2026":"")+s.text.slice(o,a)+(a<s.text.length?"\u2026":"")}}return{hitCount:t,snippet:n}}var Yl=S(()=>{});var ho,go,Wh=S(()=>{ho=".typebulb/paste",go={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",bmp:"image/bmp"}});import{existsSync as cA,mkdirSync as lA,writeFileSync as uA,readFileSync as fA}from"fs";import{join as yo}from"path";function Yh(){let r=new Date,e=t=>String(t).padStart(2,"0");return`${r.getFullYear()}${e(r.getMonth()+1)}${e(r.getDate())}-${e(r.getHours())}${e(r.getMinutes())}${e(r.getSeconds())}`}function hA(r){return r.trim().toLowerCase().replace(/\.[a-z0-9]{1,4}$/,"").replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60)}async function gA(r){let e=AbortSignal.timeout(dA);for(let[t,n]of mA){let s=Ve(t,n);if(typeof s!="string"){try{let i=await yt(s,{messages:[{role:"user",content:`Reply with ONLY a short kebab-case filename (2-5 words, lowercase, no extension) describing this text:
|
|
1221
|
-
|
|
1222
|
-
${r.slice(0,pA)}`}],effort:0,webSearch:!1,signal:e});if(!i.ok)continue;let o=hA(await Kt(i,s.protocol));if(o)return o}catch{}if(e.aborted)return}}}async function Vh(r,e){if(!e||e.kind!=="image"&&e.kind!=="text")return{ok:!1,error:"bad paste kind"};if(typeof e.data!="string"||!e.data)return{ok:!1,error:"empty paste"};let t=yo(r,ho);try{lA(t,{recursive:!0})}catch(a){return{ok:!1,error:J(a)}}let n,s,i;if(e.kind==="image"){if(n=`img-${Yh()}`,s=Object.keys(go).find(a=>go[a]===e.mime)??"png",i=Buffer.from(e.data,"base64"),!i.length)return{ok:!1,error:"empty image data"}}else n=await gA(e.data)??`paste-${Yh()}`,s="md",i=e.data;let o=`${n}.${s}`;for(let a=2;cA(yo(t,o));a++)o=`${n}-${a}.${s}`;try{uA(yo(t,o),i)}catch(a){return{ok:!1,error:J(a)}}return{ok:!0,path:`${ho}/${o}`}}function Gh(r,e){if(!/^[\w-]+(\.[\w-]+)*$/.test(e))return{ok:!1,error:"bad name"};let t=e.slice(e.lastIndexOf(".")+1).toLowerCase(),n=go[t];if(!n)return{ok:!1,error:"not an image"};try{return{ok:!0,mime:n,base64:fA(yo(r,ho,e)).toString("base64")}}catch{return{ok:!1,error:"not found"}}}var dA,pA,mA,zh=S(()=>{Er();$r();Et();Wh();dA=4e3,pA=4e3,mA=[["openrouter","google/gemini-3.1-flash-lite-preview"],["gemini","gemini-3.1-flash-lite"]]});import{existsSync as Xh,openSync as yA,readSync as bA,closeSync as wA,statSync as Dr,readdirSync as Qh,watchFile as vA,unwatchFile as Zh,mkdirSync as SA,writeFileSync as kA,readFileSync as bo,unlinkSync as xA,rmSync as EA}from"fs";import{stat as AA}from"fs/promises";import{dirname as TA,join as Qt,resolve as eg}from"path";function _A(r){if(!Number.isInteger(r))return!0;try{return process.kill(r,0),!0}catch(e){return e.code==="EPERM"}}function wo(r){let e={cwd:Y,sessionId:"",sessionStartMs:Date.now(),buffer:[],partial:"",offset:0,latest:{in:0,out:0,cached:0,cacheCreate:0},latestModel:null,everAttached:!1,entries:new Map},t=new Set,n;function s(){if(e.file){for(let h of t)if(h.file===e.file)return h;return}return n}function i(h){let w={d:r.createDriver(e.cwd,h),file:h};return t.add(w),e.file||(n=w),w}async function o(h){t.delete(h),n===h&&(n=void 0);try{await h.d.dispose()}catch(w){console.error("[composer] dispose:",J(w))}}function a(){let h=s();for(let w of[...t])w!==h&&(w.d.streaming||w.d.queue||w.d.error||o(w))}function c(){for(let h of t)h.d.sessionFile&&h.file!==h.d.sessionFile&&(h.file=h.d.sessionFile);if(n&&!e.file&&n.file){let h=r.listSessionFiles(e.cwd).find(w=>w.file===n.file);h&&N(h)}}let l=h=>Qt(h,OA),d=(h,w)=>Qt(l(h),`${w}.lock`);function u(h,w){try{let v=d(h,w);if(Date.now()-Dr(v).mtimeMs>=tg)return!1;try{let C=parseInt(bo(v,"utf8").trim(),10);if(C===process.pid||!_A(C))return!1}catch{}return!0}catch{return!1}}function f(h,w){if(w)try{SA(l(h),{recursive:!0}),kA(d(h,w),String(process.pid))}catch(v){console.error("[lock] claim failed:",J(v))}}function p(h){try{EA(Qt(h,".claude-bulb"),{recursive:!0,force:!0})}catch{}}function b(h){let w=l(h);if(!Xh(w))return;let v;try{v=Qh(w)}catch{return}let C=Date.now();for(let D of v){if(!D.endsWith(".lock"))continue;let j=Qt(w,D);try{let L=Dr(j);C-L.mtimeMs>CA&&xA(j)}catch{}}}function m(h){try{return Dr(h),!1}catch(w){return w.code==="ENOENT"}}function g(){let h=e;if(h.file&&!m(h.file)){f(h.cwd,h.sessionId);return}let w=x(h);w&&N(w)}function x(h){if(!h.everAttached)return A(h.cwd)??P(h.cwd,()=>!0)}function A(h){let w=l(h);if(!Xh(w))return;let v;try{v=Qh(w)}catch{return}let C;for(let j of v)if(j.endsWith(".lock"))try{let L=Dr(Qt(w,j));if(Date.now()-L.mtimeMs>=tg||parseInt(bo(Qt(w,j),"utf8").trim(),10)!==process.pid)continue;(!C||L.mtimeMs>C.mtime)&&(C={sessionId:j.slice(0,-5),mtime:L.mtimeMs})}catch{}if(!C)return;let D=r.listSessionFiles(h).find(j=>j.sessionId===C.sessionId);if(!(!D||m(D.file)))return D}function P(h,w){return r.listSessionFiles(h).sort((v,C)=>C.mtime-v.mtime).find(v=>!u(h,v.sessionId)&&w(v))}function R(h,w){let v=e;if(v.file)try{Zh(v.file)}catch{}v.file=h,v.sessionId=w,v.partial="",v.offset=0,v.latest={in:0,out:0,cached:0,cacheCreate:0},v.latestModel=null,v.entries=new Map,v.chainLastId=void 0,v.buffer.push({type:"cleared"}),v.buffer.push({type:"session",sessionId:w})}function N(h){let w=e;n=void 0,R(h.file,h.sessionId),w.everAttached=!0,f(w.cwd,h.sessionId),$();try{Zh(h.file)}catch{}vA(h.file,{interval:200},()=>$())}function O(){R(void 0,"")}function $(){let h=e;if(!h.file)return;let w;try{w=Dr(h.file).size}catch{return}if(w<=h.offset)return;let v;try{v=yA(h.file,"r")}catch{return}try{let U=w-h.offset,de=Buffer.alloc(U),te=0;for(;te<U;){let _u=bA(v,de,te,U-te,h.offset+te);if(!_u)break;te+=_u}h.offset+=te,h.partial+=de.subarray(0,te).toString("utf8")}finally{wA(v)}let C,D;for(;(D=h.partial.indexOf(`
|
|
1223
|
-
`))>=0;){let U=h.partial.slice(0,D);if(h.partial=h.partial.slice(D+1),!U.trim())continue;let de=r.parseEntry(U);if(!de)continue;let te=r.idOf(de);te&&(h.entries.set(te,de),!r.isSidechain(de)&&r.isLeafType(de)&&(C=te))}if(!C)return;let j=[],L=h.entries.get(C),H=!1;for(;L;){if(j.push(L),r.idOf(L)===h.chainLastId){H=!0;break}let U=r.parentOf(L);L=U?h.entries.get(U):void 0}if(H)for(let U=j.length-2;U>=0;U--)I(j[U]);else{h.chainLastId!==void 0&&(h.buffer.push({type:"cleared"}),h.buffer.push({type:"session",sessionId:h.sessionId}),h.latest={in:0,out:0,cached:0,cacheCreate:0});let U=new Set(j.map(te=>r.idOf(te))),de=E(h.entries);for(let te=j.length-1;te>=0;te--)I(j[te]),y(r.idOf(j[te]),de,U)}h.chainLastId=C}function E(h){let w=new Map;for(let v of h.values()){let C=r.parentOf(v);if(!C)continue;let D=w.get(C);D?D.push(v):w.set(C,[v])}return w}function y(h,w,v){if(!h)return;let C=w.get(h);if(!C)return;let D=C.filter(U=>!r.isSidechain(U));if(D.length<2)return;let j=D.filter(U=>!v.has(r.idOf(U)));if(!j.length)return;let L=[],H=0;for(let U of j){let de=k(U,w);L.push(...de.events),H+=de.count}H>0&&e.buffer.push({type:"fork",atId:h,count:H,events:L})}function k(h,w){let v=[],C=[h];for(;C.length;){let L=C.pop();if(r.isSidechain(L))continue;v.push(L);let H=w.get(r.idOf(L)??"");if(H)for(let U of H)C.push(U)}v.sort((L,H)=>(Date.parse(r.timestampOf(L)??"")||0)-(Date.parse(r.timestampOf(H)??"")||0));let D=[];for(let L of v)r.isRecoveryNoise(L)||D.push(...r.apply(L,e.sessionStartMs).events);return{count:D.reduce((L,H)=>L+(H.type==="user"||H.type==="assistant"?1:0),0),events:D}}function I(h){try{let{events:w,usage:v,model:C,cost:D}=r.apply(h,e.sessionStartMs);for(let j of w)e.buffer.push(j);w.some(j=>j.type==="assistant")&&s()?.d.clearCompletedDraft(),w.some(j=>j.type==="user")&&s()?.d.clearEcho(),C&&(e.latestModel=C),v&&(e.latest=v),(v||D)&&e.buffer.push({type:"usage",...e.latest,cost:D})}catch(w){console.error("[mirror] skipped malformed entry:",J(w))}}async function _(){return{cwd:e.cwd,pid:process.pid,composer:!!r.createDriver,elsewhere:await M()}}async function M(){if(r.listSessionFiles(e.cwd).length)return;let h=await Mr();if(!h)return;let w=eg(h).toLowerCase();for(let v=eg(e.cwd);v.toLowerCase()!==w;){let C=TA(v);if(C===v)return;v=C;let D=r.listSessionFiles(v).length;if(D)return{dir:v,count:D}}}M().then(h=>{h&&console.log(`No sessions for ${e.cwd} \u2014 ${h.count} exist for ${h.dir}. Launched from a subfolder? Relaunch from the project root.`)}).catch(()=>{});let W=new uo;async function K(h,w){W.accept(h,w)&&console.log(w)}function Fe(){let h=r.sessionAlive(e.sessionId,e.cwd);if(h!==void 0)return h;if(!e.file)return!1;try{return Date.now()-Dr(e.file).mtimeMs<1e4}catch{return!1}}function z(){return r.chainWorking([...e.entries.values()])&&Fe()}function V(){!r.createDriver||s()||e.latestModel||z()||i(e.file)}async function qe(h){let w=e;g(),c(),V(),a();let v=s();for(let L of t)L!==v&&L.d.dialog;let C=new Set([...t].filter(L=>L.d.streaming&&L.file).map(L=>L.file)),D=C.size?r.listSessionFiles(w.cwd).filter(L=>C.has(L.file)).map(L=>L.sessionId):[],j=r.createDriver?{streaming:!!v?.d.streaming,draft:v?.d.draft??null,echo:v?.d.echo??null,status:v?.d.status??null,dialog:v?.d.dialog??null,queue:v?.d.queue??null,stats:v?.d.stats??null,model:v?.d.model??null,error:v?.d.error}:void 0;return{events:w.buffer.slice(h),cursor:w.buffer.length,working:!!v?.d.streaming||z(),latestModel:w.latestModel,composer:j,busy:D}}async function we(){g(),c();let h=s();if(h?.d.error&&!h.d.streaming&&(await o(h),h=void 0),!h){if(z())return{ok:!1,error:"the agent is mid-turn in a terminal \u2014 watch only"};h=i(e.file)}return{ok:!0,d:h.d}}async function Zy(h,w){if(!r.createDriver)return{ok:!1,error:"not supported"};let v=String(h??"").trim();if(!v)return{ok:!1,error:"empty message"};let C=await we();return C.ok?C.d.send(v,w):C}async function eb(h,w){let v=s();return v?v.d.respondUi(String(h??""),w??{}):{ok:!1,error:"no dialog pending"}}async function tb(h,w){if(!r.createDriver)return{ok:!1,error:"not supported"};if(!h||typeof h.type!="string")return{ok:!1,error:"bad command"};if(w?.spawn){let C=await we();return C.ok?C.d.rpc(h):C}let v=s();return!v||v.d.error?{ok:!1,error:"not running"}:v.d.rpc(h)}async function rb(){let h=s();if(h)try{await h.d.stop()}catch(w){console.error("[composer] stop:",J(w))}return{ok:!0}}async function nb(){return r.createDriver?(c(),!e.file&&n&&!n.d.streaming&&!n.d.error?{ok:!0}:(n?.d.error&&await o(n),n=void 0,e.file&&O(),i(void 0),a(),{ok:!0})):{ok:!1,error:"not supported"}}async function sb(){if(!r.createDriver)return[];let h=await Be(["ls-files","--cached","--others","--exclude-standard"],e.cwd).catch(()=>null),w=h!==null?h.split(`
|
|
1224
|
-
`).filter(Boolean):await r.walkFiles?.(e.cwd)??[];return(await Promise.all(w.map(async C=>{try{return{f:C,m:(await AA(Qt(e.cwd,C))).mtimeMs}}catch{return{f:C,m:0}}}))).sort((C,D)=>D.m-C.m).map(C=>C.f)}function ib(){for(let h of[...t])o(h)}async function ob(h){return r.createDriver?Vh(e.cwd,h):{ok:!1,error:"not supported"}}async function ab(h){return Gh(e.cwd,String(h??""))}async function cb(){return r.listSessionFiles(e.cwd).sort((h,w)=>w.mtime-h.mtime).map(({sessionId:h,file:w,mtime:v})=>({sessionId:h,mtime:v,preview:r.readPreview(w)}))}let Pu=new Map;function lb(h,w){let v=Pu.get(h);if(v&&v.mtime===w)return v.turns;let C=[],D="";try{D=bo(h,"utf8")}catch{return[]}for(let j of D.split(`
|
|
1225
|
-
`)){if(!j.trim())continue;let L=r.parseEntry(j);if(!L)continue;let H=r.searchText(L);H&&C.push({text:H,lower:H.toLowerCase()})}return Pu.set(h,{mtime:w,turns:C}),C}async function ub(h){let w=h.toLowerCase(),v=[];for(let{sessionId:C,file:D,mtime:j}of r.listSessionFiles(e.cwd).sort((L,H)=>H.mtime-L.mtime)){let{hitCount:L,snippet:H}=mo(lb(D,j),w);if(L&&(v.push({sessionId:C,mtime:j,preview:r.readPreview(D),hitCount:L,snippet:H}),v.length>=RA))break}return v}let Ou=800,Cu=new Map;function fb(h,w){let v=Cu.get(h);if(v&&v.mtime===w)return v.text;let C="";try{C=bo(h,"utf8")}catch{return""}let D="";for(let L of C.split(`
|
|
1226
|
-
`)){if(!L.trim())continue;let H=r.parseEntry(L);if(H)for(let U of r.apply(H,e.sessionStartMs).events)U.type==="assistant"&&U.text.trim()&&(D=U.text.trim())}let j=D.length>Ou?D.slice(0,Ou).trimEnd()+"\u2026":D;return Cu.set(h,{mtime:w,text:j}),j}async function db(h){let w=r.listSessionFiles(e.cwd).find(v=>v.sessionId===h);return{text:w?fb(w.file,w.mtime):""}}async function pb(h){let w=e,v=r.listSessionFiles(w.cwd).find(C=>C.sessionId===h);return v?v.file===w.file?{ok:!0}:(N(v),c(),a(),{ok:!0}):{ok:!1,error:"session not found"}}return p(e.cwd),b(e.cwd),g(),{info:_,poll:qe,logEmbedStatus:K,listSessions:cb,searchSessions:ub,sessionPeek:db,attach:pb,composerSend:Zy,composerStop:rb,composerNew:nb,composerFiles:sb,composerUiRespond:eb,composerRpc:tb,composerPaste:ob,composerPasteRead:ab,shutdownComposer:ib}}var PA,OA,tg,CA,RA,Vl=S(()=>{Et();qh();po();Yl();zh();PA=".typebulb",OA=`${PA}/locks`,tg=5e3,CA=6e4;RA=50});import{existsSync as Ql,mkdirSync as NA,readFileSync as rg,writeFileSync as IA}from"fs";import{join as Zt,isAbsolute as $A}from"path";async function ng(r,e){let t=$A(r)?r:Zt(Y,r);return Ql(t)?(Fl(t,e),{ok:!0}):{ok:!1,error:"file not found"}}async function sg(r){let e=Y,t=jl(r),n=Zt(e,"typebulbs");NA(n,{recursive:!0});let s=Ml(t),i=`${s}.bulb.md`;for(let l=2;Ql(Zt(n,i))&&rg(Zt(n,i),"utf8")!==t;l++)i=`${s}-${l}.bulb.md`;let o=Zt(n,i);Ql(o)||IA(o,t);let a=Zt("typebulbs",i),c=await Gi(a,{cwd:e,open:!1});return{ok:!0,file:a,pid:c.pid,url:c.url}}async function ig(){return Q(Y)}async function og(r){return await Vt(r),{ok:!0}}async function ag(){return Xi(Y).filter(r=>!r.serverOnly).map(r=>({...r,trusted:Yt(r.path)}))}async function cg(r){let e=r.toLowerCase(),t=[];for(let n of Xi(Y).filter(s=>!s.serverOnly).sort((s,i)=>i.mtime-s.mtime)){let s="";try{s=rg(n.path,"utf8")}catch{continue}let i=[];for(let c of s.split(`
|
|
1227
|
-
`)){let l=c.replace(/\s+/g," ").trim();l&&i.push({text:l,lower:l.toLowerCase()})}let{hitCount:o,snippet:a}=mo(i,e);o&&t.push({path:n.path,hitCount:o,snippet:a})}return t}async function lg(r,e){let t=Y;e!=null&&Or(r,e);let n=await Gi(r,{cwd:t,open:!1,trust:e});return{ok:!0,file:n.file,pid:n.pid,url:n.url,trust:!!n.trust}}async function ug(r){return{cap:await Bl(r)}}async function fg(r,e){return Or(r,e),{ok:!0}}async function dg(r,e){return Ie(r,e)}async function gg(){return Yn&&Date.now()-Yn.fetchedAt<=MA?Yn.samples:(Gl??=DA().finally(()=>{Gl=null}),Gl)}async function DA(){try{let r=await fetch(`${LA}/api/scripts/u/samples?stubs`,{signal:AbortSignal.timeout(mg)});if(!r.ok)throw new Error(`HTTP ${r.status}`);let e=await r.json(),t=i=>i.order??Number.MAX_SAFE_INTEGER,n=i=>Date.parse(i.createdAt??"")||0,s=e.filter(i=>i.slug!=="welcome").sort((i,o)=>t(i)-t(o)||n(o)-n(i)).map(i=>({slug:i.slug,name:i.name,description:Zo(i.config)}));return Yn={samples:s,fetchedAt:Date.now()},s}catch{return Yn?.samples??[]}}async function yg(r){return Zl.test(r)?vg(pg,"samples",r,!0):{ok:!1,error:"bad slug"}}async function bg(){let r=eu();if(!r)return{bulbs:[]};let e=`${vo()}
|
|
1228
|
-
${r}`;return At?.key===e&&Date.now()-At.fetchedAt<=BA?{user:At.user,bulbs:At.bulbs}:(zl??=jA(e,r).finally(()=>{zl=null}),zl)}async function Xl(r,e,t){let n=await fetch(`${r}${e}`,{headers:t,signal:AbortSignal.timeout(mg)});if(!n.ok)throw new Error(`HTTP ${n.status}`);if(!n.headers.get("content-type")?.includes("json"))throw new Error("not json");return n.json()}async function jA(r,e){let t={Authorization:`Bearer ${e}`};try{let n=vo(),s;try{s=await Xl(n,"/api/me",t)}catch{let a=new URL(n);n=`${a.protocol}//api.${a.host}`,s=await Xl(n,"/api/me",t)}let o=(await Xl(n,"/api/scripts/list",t)).filter(a=>a.userSlug===s.slug&&!a.isTemplate).map(a=>({slug:a.slug,name:a.name,description:Zo(a.config)}));return At={key:r,user:s.slug,bulbs:o,fetchedAt:Date.now()},{user:s.slug,bulbs:o}}catch{return At?.key===r?{user:At.user,bulbs:At.bulbs}:{bulbs:[]}}}async function wg(r,e,t=!1){return!Zl.test(e)||!Zl.test(r)?{ok:!1,error:"bad slug"}:vg(vo(),r,e,t)}async function vg(r,e,t,n){let s=to(e,t);try{let i=await no({origin:r,userSlug:e,slug:t,dest:Zt(Y,s)},{force:n,token:eu(),timeoutMs:hg});return i.kind==="conflict"?{ok:!1,conflict:!0,error:"local file differs from the site copy"}:i.kind==="http-error"?{ok:!1,error:`HTTP ${i.status}`}:i.kind==="not-markdown"?{ok:!1,error:`not a bulb (${i.contentType??"no content-type"})`}:{ok:!0,file:s,upToDate:i.kind==="up-to-date"}}catch(i){return{ok:!1,error:i?.message??String(i)}}}async function Sg(r,e=!1){let t=eu();if(!t)return{ok:!1,error:"no TYPEBULB_TOKEN in .env"};try{let n=ro(r,Y,vo()),s=await io(n,{token:t,force:e,timeoutMs:hg});return s.kind==="conflict"?{ok:!1,conflict:!0,error:s.message}:s.kind==="http-error"?{ok:!1,error:`HTTP ${s.status}: ${s.message}`}:{ok:!0,created:s.created,serverStripped:s.serverStripped}}catch(n){return{ok:!1,error:n?.message??String(n)}}}var LA,pg,MA,mg,hg,Yn,Gl,Zl,BA,At,zl,vo,eu,tu=S(()=>{$r();Et();Yl();Re();LA="https://api.typebulb.com",pg="https://typebulb.com",MA=3600*1e3,mg=5e3,hg=15e3,Yn=null,Gl=null;Zl=/^[a-z0-9][a-z0-9-]*$/,BA=300*1e3,At=null,zl=null,vo=()=>eo("TYPEBULB_ORIGIN",Y)||pg,eu=()=>eo("TYPEBULB_TOKEN",Y)});import{readFileSync as su,writeFileSync as xg,mkdirSync as FA,appendFileSync as Eg,rmSync as kg}from"fs";import{join as xo,dirname as qA}from"path";import{createServer as UA}from"http";function Tt(r){try{return JSON.parse(su(r,"utf8"))}catch{return null}}function ko(r,e){FA(qA(r),{recursive:!0}),xg(r,JSON.stringify(e,null,2)+`
|
|
1229
|
-
`)}function Tg(r,e,t){let n=xo(r,".gitignore"),s="";try{s=su(n,"utf8")}catch{}let i=new Set(s.split(/\r?\n/).map(c=>c.trim())),o=e.filter(c=>!i.has(c));if(!o.length)return;let a=s&&!s.endsWith(`
|
|
1230
|
-
`)?`
|
|
1231
|
-
`:"";try{Eg(n,a+t+`
|
|
1232
|
-
`+o.join(`
|
|
1233
|
-
`)+`
|
|
1234
|
-
`)}catch(c){console.error("[switcher] .gitignore update failed",J(c))}}function YA(r){let e=i=>{let o=i.exec(r);return o?Number(o[1]):0},t=e(/"cache_read_input_tokens":\s*(\d+)/),n=e(/"cache_creation_input_tokens":\s*(\d+)/),s=e(/"input_tokens":\s*(\d+)/);t>0||n>0?zn="live":s>WA&&(zn="uncached")}function Og(r,e){let t={"content-type":"application/json",authorization:`Bearer ${e}`,"anthropic-version":r.headers["anthropic-version"]||"2023-06-01"},n=r.headers["anthropic-beta"];return typeof n=="string"&&(t["anthropic-beta"]=n),t}function VA(r){if(Array.isArray(r?.messages))for(let e of r.messages){if(!Array.isArray(e?.content))continue;let t=e.content.filter(n=>n?.type!=="thinking"&&n?.type!=="redacted_thinking");t.length&&t.length!==e.content.length&&(e.content=t)}}function Cg(r){let e;try{e=JSON.parse(r)}catch{return r}Gn=typeof e?.model=="string"?e.model:null,je&&(e.model=je),tr&&(e.provider=Pg(tr));let t=/haiku/i.test(Gn||"");return Xn!=null&&!t&&(e.reasoning={effort:ru[Xn]}),delete e.thinking,e.output_config&&delete e.output_config.effort,VA(e),JSON.stringify(e)}function GA(){let r="",e=0,t=new Map,n=new Set(["thinking","redacted_thinking"]),s=i=>{let o=/^data: (.*)$/m.exec(i);if(!o)return i;let a;try{a=JSON.parse(o[1])}catch{return i}switch(a.type){case"message_start":return t.clear(),e=0,i;case"content_block_start":{if(n.has(a.content_block?.type))return t.set(a.index,null),null;let c=e++;return t.set(a.index,c),a.index=c,`event: ${a.type}
|
|
1235
|
-
data: ${JSON.stringify(a)}
|
|
1178
|
+
// \u2500\u2500 Confirmation state \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
1179
|
+
var areas = [];
|
|
1180
|
+
function showConfirm() {
|
|
1181
|
+
body.textContent = ''; foot.textContent = ''; areas = [];
|
|
1236
1182
|
|
|
1237
|
-
|
|
1238
|
-
|
|
1239
|
-
|
|
1240
|
-
|
|
1183
|
+
var model = el('div', 'model');
|
|
1184
|
+
model.appendChild(el('span', 'shimmer', 'Resolving model\\u2026'));
|
|
1185
|
+
body.appendChild(model);
|
|
1186
|
+
var cancel = el('button', '', 'Cancel');
|
|
1187
|
+
cancel.addEventListener('click', function () { close('cancel'); });
|
|
1188
|
+
foot.appendChild(cancel);
|
|
1241
1189
|
|
|
1242
|
-
|
|
1243
|
-
|
|
1244
|
-
|
|
1245
|
-
|
|
1246
|
-
|
|
1247
|
-
|
|
1190
|
+
// Build the whole view once the seed arrives (a localhost roundtrip; the shimmer covers it).
|
|
1191
|
+
// Seeding is explicit ctx.data (an arg / setData / a retry's edits) > the bulb's SOURCE
|
|
1192
|
+
// chunks from the server \u2014 never the page's post-run runtime data.
|
|
1193
|
+
fetch('/__infer-info').then(function (r) { return r.json(); })
|
|
1194
|
+
.catch(function () { return {}; })
|
|
1195
|
+
.then(function (info) { buildConfirm(info || {}); });
|
|
1196
|
+
}
|
|
1248
1197
|
|
|
1249
|
-
|
|
1250
|
-
|
|
1251
|
-
|
|
1252
|
-
|
|
1253
|
-
browser, prints its URL and the authoring-skill paths.
|
|
1254
|
-
Always exits 0 (a status report).
|
|
1255
|
-
typebulb agent:{claude|pi} Open a named harness's mirror in the foreground (a browser
|
|
1256
|
-
view of your coding agent's sessions) \u2014 explicit / override.
|
|
1257
|
-
typebulb skill Print this README as an Agent Skill (stdout), for the
|
|
1258
|
-
agent to read and copy into its own skills folder.
|
|
1259
|
-
typebulb call <file> <fn> [\u2026] Invoke one server.ts export headlessly: prints
|
|
1260
|
-
its return as JSON to stdout, logs/errors to
|
|
1261
|
-
stderr. Gated by trust like --server. Args after
|
|
1262
|
-
<fn> are JSON-or-string; --args '<json-array>'
|
|
1263
|
-
(or --args - for stdin) is the escape hatch.
|
|
1264
|
-
typebulb check [file.bulb.md] Type-check a bulb without running it
|
|
1265
|
-
typebulb predict [file] Report the capability a bulb probably needs
|
|
1266
|
-
(fs / AI / server.ts) without running it.
|
|
1267
|
-
typebulb models List AI models for tb.ai, filtered by the API
|
|
1268
|
-
keys in your .env (the exact ids to pass).
|
|
1269
|
-
typebulb logs [file|agent] Print a running bulb server's (or the 'agent' mirror's) console
|
|
1270
|
-
(no arg: list this project's running servers;
|
|
1271
|
-
--run latest|N shows just one hot-reload run;
|
|
1272
|
-
--clear empties it). For agents: fetch
|
|
1273
|
-
tb.server.log / errors of a bulb you launched
|
|
1274
|
-
without watching its terminal.
|
|
1275
|
-
typebulb send <file> [msg] Push a message into a running bulb's page \u2014
|
|
1276
|
-
its tb.onMessage(cb) handlers receive it. The
|
|
1277
|
-
client-side twin of 'call'; msg is JSON-or-
|
|
1278
|
-
string, omit it for a bare trigger. No --trust.
|
|
1279
|
-
With --wait, a handler's non-undefined return
|
|
1280
|
-
prints on stdout (JSON; a bare string raw).
|
|
1281
|
-
msg 'tb:snapshot' instead prints the page's
|
|
1282
|
-
rendered outline (roles, names, visible text).
|
|
1283
|
-
typebulb pull <url|file> Fetch a bulb from typebulb.com into
|
|
1284
|
-
typebulbs/u/<user>/<slug>.bulb.md (a local file
|
|
1285
|
-
at that path re-pulls in place). Unlisted and
|
|
1286
|
-
public bulbs need no login; a differing local
|
|
1287
|
-
file is refused unless --force.
|
|
1288
|
-
typebulb push <file> Upload a typebulbs/u/<user>/<slug>.bulb.md to
|
|
1289
|
-
typebulb.com as you (needs TYPEBULB_TOKEN in
|
|
1290
|
-
.env, minted on the settings page). Refused if
|
|
1291
|
-
the remote changed since your last pull/push,
|
|
1292
|
-
unless --force. A new slug is created unlisted.
|
|
1293
|
-
typebulb wait [file|agent] Block until the target server logs a new line,
|
|
1294
|
-
print it, exit (2: timeout; 3: server died).
|
|
1295
|
-
For agents: run it in the background \u2014 the exit
|
|
1296
|
-
is your wake-up ('wait agent': embed outcomes;
|
|
1297
|
-
'wait <file>': the bulb's own console.log).
|
|
1298
|
-
Resumes where your last wait/call left off, so
|
|
1299
|
-
an event that beats the wait still fires it.
|
|
1300
|
-
typebulb stop [file|pid|agent] Stop a running bulb or mirror (no arg: list this
|
|
1301
|
-
project's running servers; a pid/path/agent stops any).
|
|
1302
|
-
Batch flags: --bulbs (this project's bulbs, the
|
|
1303
|
-
mirror survives), --agent (this project's mirror),
|
|
1304
|
-
--global (every bulb + mirror, all projects).
|
|
1305
|
-
typebulb trust [file] Remember a bulb as Trusted, so a later run grants
|
|
1306
|
-
fs/AI/server.ts without --trust (no arg: list the
|
|
1307
|
-
remembered-trusted bulbs).
|
|
1308
|
-
typebulb untrust <file> Forget a bulb's trust (back to Restricted).
|
|
1198
|
+
function buildConfirm(info) {
|
|
1199
|
+
body.textContent = ''; foot.textContent = ''; areas = [];
|
|
1200
|
+
inferCfg = info.inference || {};
|
|
1201
|
+
if (inferCfg.title) title.textContent = inferCfg.title;
|
|
1309
1202
|
|
|
1310
|
-
|
|
1311
|
-
|
|
1312
|
-
|
|
1313
|
-
|
|
1314
|
-
|
|
1315
|
-
printing it, for a clean run (logs)
|
|
1316
|
-
-n, --lines <n> Print only the last n lines (logs)
|
|
1317
|
-
--match <substring> Only lines containing this literal substring end
|
|
1318
|
-
the wait \u2014 not a regex (wait)
|
|
1319
|
-
--force Overwrite the side the command writes to: a
|
|
1320
|
-
differing local file (pull), or a remote that
|
|
1321
|
-
changed since your last sync (push)
|
|
1322
|
-
--timeout <sec> Give up after this long; exit 2 \u2014 bounds only a
|
|
1323
|
-
manual (foreground) bulb wait, default 1800 (wait)
|
|
1324
|
-
--wait[=ms] For 'send': bound the whole exchange \u2014 retry while
|
|
1325
|
-
no page is connected (a hot reload's gap), then
|
|
1326
|
-
hold for the handlers' replies (default 5000).
|
|
1327
|
-
Use it right after an edit, and for any send
|
|
1328
|
-
whose reply you read.
|
|
1329
|
-
--no-watch Disable hot reload (watch is on by default)
|
|
1330
|
-
-p, --port <port> Use a specific port (default: 3000)
|
|
1331
|
-
--open Force-open the external browser (default off
|
|
1332
|
-
inside VS Code's integrated terminal)
|
|
1333
|
-
--no-open Don't auto-open browser
|
|
1334
|
-
--trust Grant privileged capabilities (filesystem, AI,
|
|
1335
|
-
and server.ts) for this run. Without it a bulb runs
|
|
1336
|
-
Restricted: tb.fs / tb.ai / tb.server are blocked and
|
|
1337
|
-
the page shows the exact --trust command to unlock
|
|
1338
|
-
them. A bulb remembered via 'typebulb trust' runs
|
|
1339
|
-
trusted without this flag.
|
|
1340
|
-
--no-trust Force a Restricted run even if the bulb is
|
|
1341
|
-
remembered-trusted (overrides the trust store).
|
|
1342
|
-
--mode <name> Also load .env.<name> (+ .env.<name>.local) on top
|
|
1343
|
-
of .env / .env.local. Free-form name; loads no mode
|
|
1344
|
-
file by default.
|
|
1345
|
-
--dir <sub> Scope the bulb's dir to a subfolder for this run:
|
|
1346
|
-
tb.dir and relative tb.fs paths land in
|
|
1347
|
-
<bulb-folder>/<sub>. Batch runs without touching
|
|
1348
|
-
the bulb's code (e.g. --dir batch2). Relative
|
|
1349
|
-
subpaths only \u2014 no absolute paths or '..'.
|
|
1350
|
-
--server Run server.ts only, no web server (needs --trust)
|
|
1351
|
-
--args <json-array> For 'call': the whole argument list as one JSON
|
|
1352
|
-
array (strict). '--args -' reads it from stdin,
|
|
1353
|
-
sidestepping shell quoting.
|
|
1354
|
-
--replace <name>=<path> Replace a declared dependency with a local built
|
|
1355
|
-
package folder instead of a CDN (dev only).
|
|
1356
|
-
Applies to both run and check. Watched for
|
|
1357
|
-
rebuilds under --watch; --no-watch freezes it.
|
|
1358
|
-
e.g. --replace tensorgrad=../tensorgrad
|
|
1359
|
-
-V, --version Show version number
|
|
1360
|
-
-h, --help Show this help message
|
|
1203
|
+
var model = el('div', 'model');
|
|
1204
|
+
var runBtn = el('button', 'run', inferCfg.submitTitle || 'Run');
|
|
1205
|
+
if (info.error) { model.textContent = info.error; model.className = 'model err'; runBtn.disabled = true; }
|
|
1206
|
+
else if (info.model) model.textContent = info.model + ' \\u00b7 ' + info.provider;
|
|
1207
|
+
else model.textContent = 'Model info unavailable';
|
|
1361
1208
|
|
|
1362
|
-
|
|
1363
|
-
|
|
1364
|
-
|
|
1365
|
-
|
|
1366
|
-
|
|
1209
|
+
var chunks = ctx.data && ctx.data.length ? ctx.data
|
|
1210
|
+
: (info.data && info.data.length ? info.data : ['']);
|
|
1211
|
+
var titles = dataTitles();
|
|
1212
|
+
// Multi-chunk: .com's shape \u2014 a tab per chunk (label + live char count), one textarea visible.
|
|
1213
|
+
var multi = chunks.length > 1;
|
|
1214
|
+
var tabBtns = [];
|
|
1215
|
+
var counts = [];
|
|
1216
|
+
var strip = multi ? el('div', 'tabs') : null;
|
|
1217
|
+
if (strip) body.appendChild(strip);
|
|
1218
|
+
function formatCount(n) { return n < 10000 ? String(n) : Math.round(n / 1000) + 'K'; }
|
|
1219
|
+
function selectTab(i) {
|
|
1220
|
+
tabBtns.forEach(function (b, j) { b.className = j === i ? 'tab on' : 'tab'; });
|
|
1221
|
+
areas.forEach(function (a, j) { a.style.display = j === i ? '' : 'none'; });
|
|
1222
|
+
}
|
|
1223
|
+
chunks.forEach(function (chunk, i) {
|
|
1224
|
+
if (multi) {
|
|
1225
|
+
var tab = el('button', 'tab');
|
|
1226
|
+
tab.appendChild(el('span', '', chunkLabel(chunk, i, titles)));
|
|
1227
|
+
var cnt = el('span', 'cnt', '(' + formatCount(chunk.length) + ')');
|
|
1228
|
+
counts.push(cnt);
|
|
1229
|
+
tab.appendChild(cnt);
|
|
1230
|
+
tab.addEventListener('click', function () { selectTab(i); });
|
|
1231
|
+
tabBtns.push(tab);
|
|
1232
|
+
strip.appendChild(tab);
|
|
1233
|
+
} else {
|
|
1234
|
+
body.appendChild(el('label', '', titles[0] || 'Data to process'));
|
|
1235
|
+
}
|
|
1236
|
+
var ta = document.createElement('textarea');
|
|
1237
|
+
ta.value = chunk;
|
|
1238
|
+
if (!chunk) ta.placeholder = 'Paste data to process (optional)\\u2026';
|
|
1239
|
+
ta.addEventListener('input', function () {
|
|
1240
|
+
// 2 blank lines IS the chunk separator \u2014 collapse pasted 3+ so text can't silently split (.com parity)
|
|
1241
|
+
var v = ta.value.replace(/\\n{3,}/g, '\\n\\n');
|
|
1242
|
+
if (v !== ta.value) ta.value = v;
|
|
1243
|
+
if (multi) counts[i].textContent = '(' + formatCount(ta.value.length) + ')';
|
|
1244
|
+
});
|
|
1245
|
+
areas.push(ta);
|
|
1246
|
+
body.appendChild(ta);
|
|
1247
|
+
});
|
|
1248
|
+
if (multi) selectTab(0);
|
|
1249
|
+
// The model line reads as a footnote to the action, not a header to the data \u2014 under the
|
|
1250
|
+
// textareas, above the buttons.
|
|
1251
|
+
body.appendChild(model);
|
|
1367
1252
|
|
|
1368
|
-
|
|
1369
|
-
|
|
1370
|
-
|
|
1371
|
-
|
|
1372
|
-
|
|
1373
|
-
|
|
1253
|
+
// Fragment-driven actions (TB-Inference.md): the address bar holds the last completed run, so
|
|
1254
|
+
// both appear exactly when one exists. Copy = share it; Save = promote it to the bulb's source.
|
|
1255
|
+
if (location.hash.indexOf('tb=') !== -1) {
|
|
1256
|
+
var grp = el('div', 'leftgrp');
|
|
1257
|
+
var share = el('button', '', 'Copy share URL');
|
|
1258
|
+
share.title = 'Copies this page URL with the #tb= result fragment \\u2014 paste the fragment onto the published bulb\\u2019s URL to share the last run';
|
|
1259
|
+
share.addEventListener('click', function () {
|
|
1260
|
+
navigator.clipboard.writeText(location.href).then(function () {
|
|
1261
|
+
share.textContent = 'Copied \\u2713';
|
|
1262
|
+
setTimeout(function () { share.textContent = 'Copy share URL'; }, 1500);
|
|
1263
|
+
});
|
|
1264
|
+
});
|
|
1265
|
+
grp.appendChild(share);
|
|
1266
|
+
var save = el('button', '', 'Save to bulb');
|
|
1267
|
+
save.title = 'Write this run\\u2019s data + insight into the .bulb.md as its new defaults';
|
|
1268
|
+
save.addEventListener('click', function () {
|
|
1269
|
+
save.disabled = true;
|
|
1270
|
+
fetch('/__infer-save', {
|
|
1271
|
+
method: 'POST',
|
|
1272
|
+
headers: { 'Content-Type': 'application/json' },
|
|
1273
|
+
body: JSON.stringify({ hash: location.hash })
|
|
1274
|
+
}).then(async function (r) {
|
|
1275
|
+
if (!r.ok) { var t = await r.text(); var err; try { err = JSON.parse(t).message; } catch (e) { err = t; } throw new Error(err || 'Save failed'); }
|
|
1276
|
+
}).then(function () {
|
|
1277
|
+
// The run is source now \u2014 clear the runtime layer. Under watch, the file write is about
|
|
1278
|
+
// to hot-reload the page onto its new defaults anyway.
|
|
1279
|
+
history.replaceState(null, '', location.pathname + location.search);
|
|
1280
|
+
save.textContent = 'Saved \\u2713';
|
|
1281
|
+
}).catch(function (e) {
|
|
1282
|
+
save.textContent = 'Save failed'; save.title = e.message; save.disabled = false;
|
|
1283
|
+
});
|
|
1284
|
+
});
|
|
1285
|
+
grp.appendChild(save);
|
|
1286
|
+
foot.appendChild(grp);
|
|
1287
|
+
}
|
|
1374
1288
|
|
|
1375
|
-
|
|
1376
|
-
|
|
1289
|
+
var cancel = el('button', '', 'Cancel');
|
|
1290
|
+
cancel.addEventListener('click', function () { close('cancel'); });
|
|
1291
|
+
foot.appendChild(cancel);
|
|
1292
|
+
runBtn.addEventListener('click', run);
|
|
1293
|
+
foot.appendChild(runBtn);
|
|
1294
|
+
}
|
|
1377
1295
|
|
|
1378
|
-
|
|
1379
|
-
|
|
1380
|
-
|
|
1381
|
-
|
|
1382
|
-
|
|
1383
|
-
OPENROUTER_API_KEY=sk-or-...
|
|
1384
|
-
Set provider and model (required):
|
|
1385
|
-
TB_AI_PROVIDER=anthropic
|
|
1386
|
-
TB_AI_MODEL=claude-haiku-4-5-20251001
|
|
1387
|
-
Both can be overridden per-call: tb.ai({ provider: "openai", model: "gpt-5.4-mini", ... })
|
|
1388
|
-
Don't guess a model id \u2014 run 'typebulb models' to list the exact ids your keys cover.
|
|
1389
|
-
Optional effort level (1=low, 2=med, 3=high; omit for the model's native default):
|
|
1390
|
-
tb.ai({ ..., effort: 2 })
|
|
1296
|
+
// \u2500\u2500 Streaming / error states \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
1297
|
+
function run() {
|
|
1298
|
+
var data = areas.map(function (a) { return a.value.trim(); }).filter(function (v) { return v !== ''; });
|
|
1299
|
+
ctx.data = data; // a retry's confirm re-seeds from the edited chunks, not the originals
|
|
1300
|
+
body.textContent = ''; foot.textContent = '';
|
|
1391
1301
|
|
|
1392
|
-
|
|
1393
|
-
|
|
1394
|
-
|
|
1395
|
-
|
|
1396
|
-
|
|
1397
|
-
|
|
1398
|
-
|
|
1399
|
-
|
|
1400
|
-
*/
|
|
1401
|
-
data(index: number): string;
|
|
1402
|
-
/**
|
|
1403
|
-
* Get data chunk parsed as JSON (handles JSON-ish with unquoted keys).
|
|
1404
|
-
* @param index - Chunk index (0-based)
|
|
1405
|
-
* @throws If chunk is not valid JSON/JSON-ish
|
|
1406
|
-
*/
|
|
1407
|
-
json<T = unknown>(index: number): T;`,GT=`
|
|
1408
|
-
/**
|
|
1409
|
-
* Get the insight data produced by the inference layer.
|
|
1410
|
-
*
|
|
1411
|
-
* Returns the parsed JSON from insight.json, populated by the inference LLM.
|
|
1412
|
-
* Use a type parameter to get typed access to the insight data.
|
|
1413
|
-
*
|
|
1414
|
-
* @returns The parsed insight JSON, or undefined if no insight is available
|
|
1415
|
-
*/
|
|
1416
|
-
insight<T = unknown>(): T | undefined;`,zg=`options: {
|
|
1417
|
-
messages: Array<{ role: "user" | "assistant"; content: string }>;
|
|
1418
|
-
system?: string;
|
|
1419
|
-
/** Reasoning effort hint: 0=minimal, 1=low, 2=med, 3=high. Mapped to each provider's native mechanism (OpenAI/OpenRouter reasoning effort, Gemini thinking budget, Anthropic adaptive thinking). 0 minimizes reasoning \u2014 a floor, not a guaranteed "off": some models still think a little at 0, and adaptive models already self-skip at 1 (low). Level 1 (low) is the sensible default for most work; reach for 0 only when you truly want minimal deliberation. Omit for the model's own default. */
|
|
1420
|
-
effort?: 0 | 1 | 2 | 3;
|
|
1421
|
-
provider?: string;
|
|
1422
|
-
model?: string;
|
|
1423
|
-
/** Enable/disable web search. Default: on for BYOK, always off for free model. */
|
|
1424
|
-
webSearch?: boolean;
|
|
1425
|
-
/** Abort the request. On abort the promise rejects / the stream ends. */
|
|
1426
|
-
signal?: AbortSignal;
|
|
1427
|
-
}`,Xg=`
|
|
1428
|
-
/** A single streamed delta from \`tb.ai.stream()\`. Discriminated by \`kind\`. */
|
|
1429
|
-
type AiChunk =
|
|
1430
|
-
| { kind: "text"; text: string }
|
|
1431
|
-
| { kind: "reasoning"; text: string };
|
|
1432
|
-
`,Qg=`
|
|
1433
|
-
/**
|
|
1434
|
-
* General-purpose AI call. \`tb.ai(opts)\` resolves with the full text; \`tb.ai.stream(opts)\`
|
|
1435
|
-
* returns an async iterable of {@link AiChunk} deltas you consume with \`for await\`.
|
|
1436
|
-
*
|
|
1437
|
-
* @returns Promise resolving to { text: string }
|
|
1438
|
-
* @throws On rate limit, network error, or provider error
|
|
1439
|
-
*/
|
|
1440
|
-
ai: {
|
|
1441
|
-
(${zg}): Promise<{ text: string }>;
|
|
1442
|
-
/**
|
|
1443
|
-
* Streaming counterpart of \`tb.ai()\`. Yields \`{ kind: "text" | "reasoning", text }\` deltas
|
|
1444
|
-
* as they arrive; break the loop (or abort \`signal\`) to cancel and stop the upstream.
|
|
1445
|
-
*
|
|
1446
|
-
* \`kind: "reasoning"\` deltas only arrive when you pass \`effort: 1-3\` AND use a
|
|
1447
|
-
* thinking-capable model; otherwise the stream is \`text\`-only.
|
|
1448
|
-
*
|
|
1449
|
-
* @example
|
|
1450
|
-
* let answer = "";
|
|
1451
|
-
* for await (const c of tb.ai.stream({ messages })) {
|
|
1452
|
-
* if (c.kind === "text") answer += c.text;
|
|
1453
|
-
* }
|
|
1454
|
-
*/
|
|
1455
|
-
stream(${zg}): AsyncIterable<AiChunk>;
|
|
1456
|
-
};`,Zg=`
|
|
1457
|
-
/**
|
|
1458
|
-
* Returns AI models available to the current user.
|
|
1459
|
-
* Models are filtered by the user's configured API keys.
|
|
1460
|
-
* If no keys are configured, returns only the courtesy model.
|
|
1461
|
-
*/
|
|
1462
|
-
models(): Promise<Array<{
|
|
1463
|
-
/** Provider protocol: "anthropic", "openai", "gemini", "openrouter" */
|
|
1464
|
-
provider: string;
|
|
1465
|
-
/** Model identifier, e.g. "claude-sonnet-4-6" */
|
|
1466
|
-
name: string;
|
|
1467
|
-
/** Human-readable display name, e.g. "Sonnet 4.6" */
|
|
1468
|
-
friendlyName: string;
|
|
1469
|
-
/** Provider display name, e.g. "Anthropic" */
|
|
1470
|
-
providerName: string;
|
|
1471
|
-
/** True on the .env-configured default model (TB_AI_PROVIDER + TB_AI_MODEL); absent otherwise */
|
|
1472
|
-
default?: boolean;
|
|
1473
|
-
}>>;
|
|
1474
|
-
/**
|
|
1475
|
-
* Whether the user's own AI keys back \`tb.ai\`. False means only the
|
|
1476
|
-
* quota-limited courtesy model is available (or no AI at all) \u2014 a bulb
|
|
1477
|
-
* making many AI calls should check this and show a "use your own keys"
|
|
1478
|
-
* notice instead of running.
|
|
1479
|
-
*/
|
|
1480
|
-
hasOwnKeys(): Promise<boolean>;`,zT="\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;",ey=`
|
|
1481
|
-
/**
|
|
1482
|
-
* The mode this bulb is running in.
|
|
1483
|
-
*
|
|
1484
|
-
* - \`'local'\` \u2014 Running via the typebulb CLI
|
|
1485
|
-
* - \`'editor'\` \u2014 Running in the typebulb.com editor
|
|
1486
|
-
* - \`'published'\` \u2014 Running as a published/standalone bulb on typebulb.com
|
|
1487
|
-
* - \`'embedded'\` \u2014 Running as a bulb embedded inside another bulb (sandboxed,
|
|
1488
|
-
* client-only: AI, filesystem, and server RPC are unavailable)
|
|
1489
|
-
*/
|
|
1490
|
-
mode: 'local' | 'editor' | 'published' | 'embedded';`,ty=`
|
|
1491
|
-
/**
|
|
1492
|
-
* Local filesystem access (CLI only).
|
|
1493
|
-
*
|
|
1494
|
-
* Relative paths resolve against the bulb's folder (\`tb.dir\` \u2014
|
|
1495
|
-
* \`<bulb-dir>/<filename-stem>/\`, created on demand), so
|
|
1496
|
-
* \`tb.fs.write('results.json')\` lands beside the bulb. \`../\` reaches sibling
|
|
1497
|
-
* bulbs' folders; everything stays confined to the project (the launch cwd).
|
|
1498
|
-
* Throws in editor/published mode.
|
|
1499
|
-
*/
|
|
1500
|
-
fs: {
|
|
1501
|
-
/** Read a file as UTF-8 text. Throws if the file is not valid UTF-8 \u2014 use readBytes for binary. */
|
|
1502
|
-
read(path: string): Promise<string>;
|
|
1503
|
-
/** Read a file as raw bytes. */
|
|
1504
|
-
readBytes(path: string): Promise<Uint8Array>;
|
|
1505
|
-
/** Write text or raw bytes to a file. Creates parent directories if needed. */
|
|
1506
|
-
write(path: string, content: string | Uint8Array): Promise<boolean>;
|
|
1507
|
-
};`,ry=`
|
|
1508
|
-
/**
|
|
1509
|
-
* The bulb's folder \u2014 absolute path to \`<bulb-dir>/<filename-stem>/\`
|
|
1510
|
-
* (or its subfolder when the run is scoped with \`--dir\`).
|
|
1511
|
-
*
|
|
1512
|
-
* For interop only (handing a path to \`server.ts\` or a spawned tool):
|
|
1513
|
-
* \`tb.fs\` already resolves relative paths against it, so bulb code writing
|
|
1514
|
-
* its own files never needs it. CLI only \u2014 throws in editor/published/embedded mode.
|
|
1515
|
-
*/
|
|
1516
|
-
readonly dir: string;`,XT=`
|
|
1517
|
-
/**
|
|
1518
|
-
* Async value inspector for tensor-like objects.
|
|
1519
|
-
*
|
|
1520
|
-
* Materializes lazy values (like GPU tensors) and logs them with metadata.
|
|
1521
|
-
* Handles objects with \`.js()\`, \`.data()\`, \`.array()\`, \`.arraySync()\`, etc.
|
|
1522
|
-
*
|
|
1523
|
-
* @remarks
|
|
1524
|
-
* - Always use \`await\` - materialization may be async (GPU\u2192CPU readback)
|
|
1525
|
-
* - Large values are truncated (max 1000 elements)
|
|
1526
|
-
* - Promises are logged as \`[Promise]\` (not awaited - could hang)
|
|
1527
|
-
*/
|
|
1528
|
-
dump(...args: any[]): Promise<void>;
|
|
1529
|
-
/**
|
|
1530
|
-
* Trigger inference to generate new insight data.
|
|
1531
|
-
*
|
|
1532
|
-
* Opens a confirmation modal showing the data to be analyzed, then streams
|
|
1533
|
-
* the inference result. On success, updates the insight so subsequent
|
|
1534
|
-
* \`tb.insight()\` calls return the new value.
|
|
1535
|
-
*
|
|
1536
|
-
* @param opts - Options for inference
|
|
1537
|
-
* @param opts.data - Data to pre-populate in the modal (string or array of strings). If omitted, modal opens with empty textarea for user to paste.
|
|
1538
|
-
* @returns Promise that resolves with the parsed insight JSON
|
|
1539
|
-
* @throws If inference is already in progress, or on network/parse/rate limit errors
|
|
1540
|
-
*/
|
|
1541
|
-
infer<T = unknown>(opts?: { data?: string | string[] }): Promise<T>;
|
|
1542
|
-
/**
|
|
1543
|
-
* Get the current inference state.
|
|
1544
|
-
*
|
|
1545
|
-
* @returns 'idle' | 'running' | 'complete' | 'error'
|
|
1546
|
-
*/
|
|
1547
|
-
inferenceState(): 'idle' | 'running' | 'complete' | 'error';
|
|
1548
|
-
/**
|
|
1549
|
-
* Set a data chunk for the next inference call.
|
|
1550
|
-
*
|
|
1551
|
-
* Use this to programmatically set data that will be sent when \`tb.infer()\` is called
|
|
1552
|
-
* without the \`data\` option.
|
|
1553
|
-
*
|
|
1554
|
-
* @param index - The chunk index (0-based)
|
|
1555
|
-
* @param content - The content for this chunk
|
|
1556
|
-
*/
|
|
1557
|
-
setData(index: number, content: string): void;
|
|
1558
|
-
/**
|
|
1559
|
-
* Proxy a CDN URL through the sandbox origin for Web Worker/WASM same-origin loading.
|
|
1560
|
-
*
|
|
1561
|
-
* In the sandbox, prepends \`/proxy/\` so the URL is served from the same origin.
|
|
1562
|
-
* Outside the sandbox (exported HTML, CLI), returns the URL unchanged.
|
|
1563
|
-
*
|
|
1564
|
-
* @param url - Full HTTPS URL to an allowlisted CDN (esm.sh, unpkg.com, cdn.jsdelivr.net, cdnjs.cloudflare.com)
|
|
1565
|
-
* @returns The proxied URL (sandbox) or the original URL (standalone/CLI)
|
|
1566
|
-
*/
|
|
1567
|
-
proxy(url: string): string;
|
|
1568
|
-
/**
|
|
1569
|
-
* Copy text to clipboard.
|
|
1570
|
-
* Must be called synchronously within a user gesture (click/keydown).
|
|
1571
|
-
* @returns true if successful, false otherwise
|
|
1572
|
-
*/
|
|
1573
|
-
copy(text: string): Promise<boolean>;
|
|
1574
|
-
/**
|
|
1575
|
-
* Get the canonical URL of this bulb.
|
|
1576
|
-
*
|
|
1577
|
-
* Returns the parent typebulb.com URL (including path, query, and \`#tb=\` fragment),
|
|
1578
|
-
* resolving correctly from inside the cross-origin sandbox iframe.
|
|
1579
|
-
* Use this instead of \`location.href\` or \`document.referrer\`.
|
|
1580
|
-
*
|
|
1581
|
-
* @returns The full canonical URL
|
|
1582
|
-
*/
|
|
1583
|
-
url(): Promise<string>;`,QT="\n /**\n * Subscribe to a value pushed from the terminal via `typebulb send <file> [message]`.\n *\n * The dual of `tb.server.log` (data out): a value sent *in* from the CLI, no `--trust` required.\n * Use it to start expensive work on demand instead of on load \u2014 e.g. `tb.onMessage(() => start())`\n * \u2014 so hot reloads don't re-trigger it while you edit, and an agent kicks off one run when ready.\n *\n * The message is the JSON-parsed value of what `send` was given (or the raw string if it isn't\n * JSON; `undefined` for a bare `typebulb send <file>`). A non-`undefined` return value (awaited)\n * becomes the reply `send --wait` prints on stdout \u2014 JSON-serializable, at most one handler\n * replying \u2014 the structured read-back for self-tests. Returns an unsubscribe function. Inert in\n * an embedded bulb (no sender) \u2014 the handler is registered but never fires.\n *\n * @param handler - Called with each pushed message; may return a JSON-serializable reply.\n * @returns An unsubscribe function.\n */\n onMessage(handler: (message: any) => unknown): () => void;",ZT="\n /**\n * Server-side function proxy.\n *\n * In the CLI, calls exported functions from the `**server.ts**` section.\n * `tb.server.log(...)` is a built-in that prints to CLI stdout (falls back to console.log on web).\n * User exports override built-ins of the same name.\n *\n * A normal export is awaited for its result (`await tb.server.fn()`). An `async function*`\n * export streams: `for await (const chunk of tb.server.gen())`. The call object supports both;\n * break the `for await` to cancel and tear down the server generator.\n */\n server: Record<string, (...args: any[]) => Promise<any> & AsyncIterable<any>>;",du=`${Xg}
|
|
1584
|
-
/**
|
|
1585
|
-
* Typebulb utilities namespace.
|
|
1586
|
-
* Type \`tb.\` to discover available helpers.
|
|
1587
|
-
*/
|
|
1588
|
-
declare const tb: {${VT}${XT}${GT}${ZT}${QT}${Qg}${ty}${ry}${Zg}${zT}${ey}
|
|
1589
|
-
};
|
|
1590
|
-
`,pu=`${Xg}
|
|
1591
|
-
/**
|
|
1592
|
-
* Typebulb utilities namespace (server-side).
|
|
1593
|
-
* Type \`tb.\` to discover available helpers.
|
|
1594
|
-
*/
|
|
1595
|
-
declare const tb: {${Qg}${ty}${ry}${Zg}${ey}
|
|
1596
|
-
};
|
|
1597
|
-
`;Ke();import nP from"p-limit";Ke();import{resolve as sy}from"resolve.exports";var Ze={maxRelativeTypeRefs:500,maxBareDeps:8,maxBareDepth:3,prefetchConcurrency:4,negativeTtlMs:1e4},Qn=["index.d.ts","index.d.mts"],mu=/\.d\.(ts|mts|cts)$/i;function Oo(r){return/\.d\.(ts|mts|cts)(?:[?#].*)?$/i.test(r)||/[?&]dts(?:[&#]|$)/i.test(r)}function ny(r){return[`${r}.d.ts`,`${r}.d.mts`]}function Pt(r){if(!r||r==="./"||r==="/")return[...Qn];let e=r.replace(/\.(mjs|cjs|js|mts|cts|ts)$/i,""),t=ny(e),n=e.endsWith("/")?e:`${e}/`;return t.push(...ny(`${n}index`)),t}async function Fr(r,{retries:e=2,timeoutMs:t=15e3,init:n}={}){for(let s=0;s<=e;s++){let i=new AbortController,o=setTimeout(()=>i.abort(),t);try{let a=await fetch(r,{...n,signal:i.signal});if(eP(a.status)&&s<e)continue;return a}catch{if(s<e)continue;return}finally{clearTimeout(o)}}}function eP(r){return r===408||r===429||r>=500&&r<600}var Co=class{constructor(e,t){this.fetchDts=e,this.cdnClient=t}async tryUrls(e){for(let t of e){let n=await this.fetchDts(t);if(n&&(this.looksLikeDts(n.dts)||Oo(n.url)))return n}}looksLikeDts(e){return/^\s*export\s*\{\s*\}\s*;?\s*$/m.test(e)?!0:/declare\s+(module|namespace|class|interface|function|const|var|let)/.test(e)||/interface\s+\w+/.test(e)||/type\s+\w+\s*=/.test(e)}async loadPackageAtVersionedRoot(e,t){let n=this.cdnClient.packageJson(new B({name:e,version:t})),s=await Fr(n);if(!s?.ok)return;let i;try{i=await s.json()}catch{return}if(i)return{pkg:i,baseDir:this.cdnClient.baseDir(new B({name:e,version:t??i.version})),version:t}}extractPathFromResult(e){if(typeof e=="string")return e;if(Array.isArray(e))return e.find(t=>typeof t=="string")}async tryUntilSuccess(e,t){for(let n of e){let s=await t(n);if(s)return s}}async resolveFromSelected(e,t,n){if(e.kind==="types"){let o=jt(e.path);if(!o||o==="/"||o===".")return this.tryUntilSuccess([...Qn],t);if(!mu.test(o)){let a=await this.tryUntilSuccess(Pt(o),t);if(a)return a}return t(o)}let s=Pt(e.path),i=n?.subpath?[...s,...Qn]:[...Qn,...s];return this.tryUntilSuccess(i,t)}toResolutionResult(e){return{kind:mu.test(e)?"types":"probe",path:e}}resolveExportsPath(e,t){let n=t||".",s=e;try{let i=this.extractPathFromResult(sy(s,n,{conditions:["types"]}));if(i)return i}catch{}try{return this.extractPathFromResult(sy(s,n,{browser:!0,conditions:["import","default","module","browser","node"]}))}catch{return}}async resolve(e){try{let t=B.parse(e),{pkg:n,baseDir:s}=await this.loadPackageAtVersionedRoot(t.name,t.version)||{};if(!n||!s)return;let i={name:t.name,version:t.version},o=new B(i).format(),a=new B({...i,subpath:t.subpath}).format(),c=u=>this.fetchCandidateFrom(s,t.name,u);if(t.subpath){let u=qc(t.subpath),f=this.resolveExportsPath(n,u);if(f){let b=await this.resolveFromSelected(this.toResolutionResult(f),c,{subpath:!0});if(b)return{...b,resolvedPkg:a}}let p=await this.tryUntilSuccess(Pt(u),c);if(p)return{...p,resolvedPkg:a}}let l=n.types??n.typings;if(l){let u=await this.resolveFromSelected({kind:"types",path:l},c);if(u)return{...u,resolvedPkg:o}}let d=this.resolveExportsPath(n,".");if(d){let u=await this.resolveFromSelected(this.toResolutionResult(d),c);if(u)return{...u,resolvedPkg:o}}return}catch{return}}async fetchCandidateFrom(e,t,n){let s=jt(n),i=new URL(s,e).toString(),o=await this.tryUrls([i]);return o?{dts:o.dts,url:o.url,resolvedPkg:t}:void 0}};Ke();import{gunzipSync as tP}from"fflate";var _o=class{async fetchAndExtract(e,t){let n=this.getTarballUrl(e,t),s=await Fr(n,{timeoutMs:3e4});if(!s?.ok)return new Map;let i=new Uint8Array(await s.arrayBuffer());return this.extractDtsFiles(i)}getTarballUrl(e,t){return`https://registry.npmjs.org/${e.replace("/","%2F")}/-/${e.split("/").pop()}-${t}.tgz`}normalizeTarPath(e){let t=e.replace(/^package\//,""),n=t.indexOf("/");return n>0?t.substring(n+1):t}extractDtsFiles(e){let t=new Map;try{let n=tP(e),s=new TextDecoder("utf-8"),i=0;for(;i<n.length-512;){let o=n.slice(i,i+512);if(o[0]===0)break;let a=o.slice(0,100),c=a.indexOf(0),l=s.decode(a.slice(0,c>0?c:100)).trim(),d=o.slice(124,136),u=s.decode(d).trim().replace(/\0/g,""),f=parseInt(u,8)||0,p=String.fromCharCode(o[156]);if(i+=512,(p==="0"||p==="\0")&&(l.endsWith(".d.ts")||l.endsWith(".d.mts"))){let b=n.slice(i,i+f);t.set(this.normalizeTarPath(l),s.decode(b))}i+=Math.ceil(f/512)*512}}catch{}return t}};var Ro=class{constructor(e,t,n=new _o){this.cdnClient=e,this.cache=t,this.tarballFetcher=n}typesNameCandidates(e){let t=e.startsWith("@")?e.slice(1).replace("/","__"):e;return t.includes(".")?[t,t.split(".").join("-"),t.split(".").join("")]:[t]}selectTypesVersion(e,t,n){try{if(n){let i=Ft.majorOf(n),o=e.filter(a=>Ft.majorOf(a)===i);if(o.length)return o.sort((a,c)=>Ft.cmp(c,a))[0]}let s=t?.latest;return s&&e.includes(s)?s:e[0]}catch{return e[0]}}subpathCandidates(e){let t=e.replace(/\.(mjs|cjs|js|mts|cts|ts)$/i,""),n=Pt(e);return t!==e&&n.push(`${e}.d.ts`,`${e}/index.d.ts`),n}async fetchFromVersionedRoot(e,t){let n=new B(e),s=n.version;if(!s)return;let i;try{i=await this.tarballFetcher.fetchAndExtract(n.name,s)}catch{return}if(!i||i.size===0)return;for(let[a,c]of i.entries()){let l=this.cdnClient.file(e,a);try{await this.cache.setCachedFile(l,c)}catch{}}let o=t.subpath?this.subpathCandidates(t.subpath):["index.d.ts"];for(let a of o){let c=i.get(a);if(c)return{dts:c,url:this.cdnClient.file(e,a),resolvedPkg:t.subpath?new B(t).format():t.name}}}async resolve(e){let t=B.parse(e);if(t.name)for(let n of this.typesNameCandidates(t.name)){let s=`@types/${n}`,i;try{i=await this.cdnClient.fetchVersionsIndex(s)}catch{continue}if(!i?.versions?.length)continue;let o=this.selectTypesVersion(i.versions,i.distTags,t.version),a=await this.fetchFromVersionedRoot(`${s}@${o}`,t);if(a)return a}}};var No=class{collectRelativeTypeRefs(e){return this.collectRefs(e).filter(t=>t.startsWith("./")||t.startsWith("../"))}collectBareModuleRefs(e){return this.collectRefs(e).filter(t=>this.isBare(t))}collectRefs(e){let t=e.split(`
|
|
1598
|
-
`).filter(s=>{let i=s.trimStart();return!(i.startsWith("*")||i.startsWith("//")||i.startsWith("/*"))}).join(`
|
|
1599
|
-
`),n=new Set;for(let s of t.matchAll(/(import|export)\s+[^'"\n]*from\s*['"]([^'"\n]+)['"]/g))n.add(s[2]);for(let s of t.matchAll(/export\s*\*\s*from\s*['"]([^'"\n]+)['"]/g))n.add(s[1]);return Array.from(n)}isBare(e){return!(e.startsWith("./")||e.startsWith("../")||e.startsWith("file:")||e.startsWith("http://")||e.startsWith("https://"))}};Ke();var iy="file:///node_modules",Io=class{constructor(){this.epoch=0}bumpEpoch(){this.epoch+=1}epochDir(){return`__tsepoch_${this.epoch}`}pathForMain(e){return`${iy}/${this.epochDir()}/${e}/index.d.ts`}pathFor(e,t){let n=jt(t);return`${iy}/${this.epochDir()}/${e}/${n}`}};import{LRUCache as rP}from"lru-cache";function oy(r){let e=new rP({ttl:Ze.negativeTtlMs,max:500}),t=new Map;return async function(s){try{if(await r.isNegative(s)||e.has(s))return;let i=await r.getCachedFile(s);if(i)return{dts:i,url:s};let o=t.get(s);if(o)return o;let a=(async()=>{let c=await Fr(s,{init:{cache:"no-store"}});if(!c?.ok){c?.status===404&&(e.set(s,!0),await r.recordNegative(s));return}let l=await c.text(),d=c.url||s;return await r.clearNegative(s),await r.setCachedFile(d,l),{dts:l,url:d}})();return t.set(s,a),await a.finally(()=>t.delete(s))}catch{return}}}var Zn=class{constructor(e){this.inFlight=new Map,this.scanner=new No,this.cache=e.cache,this.cdnClient=e.cdnClient,this.versionResolver=e.versionResolver,this.packageService=e.packageService,this.fetchDts=oy(e.cache),this.typescriptProvider=new Co(this.fetchDts,e.cdnClient),this.definitelyTypedProvider=new Ro(e.cdnClient,e.cache),this.virtualFs=new Io}withInFlight(e,t){let n=this.inFlight.get(e);if(n)return n;let s=t().finally(()=>this.inFlight.delete(e));return this.inFlight.set(e,s),s}invalidate(){this.virtualFs.bumpEpoch(),this.inFlight.clear()}pushFileIfNew(e,t,n){e.some(s=>s.path===t)||e.push({path:t,content:n})}createStubDef(e){let t=this.virtualFs.pathForMain(e);return{pkg:e,mainPath:t,files:[{path:t,content:"export const _shim: any; export default _shim;"}],shims:[{module:e,path:t}]}}async fetchViaProviders(e){for(let t of[this.typescriptProvider,this.definitelyTypedProvider])try{let n=await t.resolve(e);if(n?.dts)return n}catch{}}async fetchRootDts(e,t){let{effectivePackage:n,root:s,pinned:i}=await this.versionResolver.effectivePackage(e,t),o=await this.cache.getCachedDts(n);if(o?.content){let c=o.url??this.cdnClient.file(i?`${s}@${i}`:s,"index.d.ts");return{dts:o.content,url:c,resolvedPkg:n}}let a;try{a=await this.fetchViaProviders(n)}catch{return}if(!(!a?.dts||!a.url)&&new B(n).subpath===new B(a.resolvedPkg||n).subpath){try{await this.cache.setCachedDts(n,a.dts,a.url)}catch{}return a}}extractPackageRootUrl(e){let t=e.pathname.match(/^(.+@[^/]+\/)/);return t?new URL(t[1],e.origin):new URL("./",e)}toVirtualPath(e,t,n){let s=t.pathname.startsWith(e.pathname)?t.pathname.slice(e.pathname.length):`__deps__/${encodeURIComponent(t.toString()).replace(/%/g,"_")}.d.ts`;return this.virtualFs.pathFor(n,s)}computeEntryPath(e,t){if(!e)return{mainPath:this.virtualFs.pathForMain(t),packageRootUrl:void 0};let n=new URL(e),s=this.extractPackageRootUrl(n);return{mainPath:this.toVirtualPath(s,n,t),packageRootUrl:s}}async expandRelativeRefs(e,t,n,s,i=new Set,o){if(!i.has(t)&&(i.add(t),!(i.size>Ze.maxRelativeTypeRefs)))try{let a=new URL(t),c=new URL("./",a);o??(o=this.extractPackageRootUrl(a));let l=this.scanner.collectRelativeTypeRefs(e).slice(0,Ze.maxRelativeTypeRefs);for(let d of l)await this.tryRelativeRef(d,c,o,n,s,i)}catch{}}async tryRelativeRef(e,t,n,s,i,o){try{let a=new URL(e,t),c=a.pathname+a.search,l=Oo(c)?[c]:Pt(c);for(let d of l){let f=new URL(d,a).toString();if(o.has(f))return;let p=await this.fetchDts(f);if(p?.dts){let b=this.toVirtualPath(n,new URL(p.url),s);this.pushFileIfNew(i,b,p.dts),await this.expandRelativeRefs(p.dts,p.url,s,i,o,n);return}}}catch{}}isDifferentPackage(e,t){return e===t?!1:new B(e).name!==new B(t).name}ambientlyDeclares(e,t){if(/^(?:import|export)\b/m.test(e))return!1;for(let n of e.matchAll(/declare\s+module\s+['"]([^'"]+)['"]/g)){let s=n[1];if(s===t||s.endsWith("/*")&&t.startsWith(s.slice(0,-1)))return!0}return!1}markFileAmbient(e,t){let n=e.find(s=>s.path===t);n&&(n.ambient=!0)}async prefetchBareDeps(e,t,n,s,i){try{let o=this.scanner.collectBareModuleRefs(e).slice(0,Ze.maxBareDeps).filter(l=>this.isDifferentPackage(l,t));if(!o.length)return;let a=new Set([t]),c=nP(Ze.prefetchConcurrency);await Promise.all(o.map(l=>c(()=>this.prefetchBareDepsRecursive(l,n,s,Ze.maxBareDepth,a,i).catch(()=>{}))))}catch{}}async prefetchBareDepsRecursive(e,t,n,s,i,o){if(s<=0||i.has(e))return;i.add(e);let a=await this.fetchRootDts(e,o);if(!a?.dts)return;let c=a.resolvedPkg||e,l=this.virtualFs.pathForMain(c);this.pushFileIfNew(t,l,a.dts),this.ambientlyDeclares(a.dts,e)?this.markFileAmbient(t,l):n.push({module:e,path:l}),a.url&&await this.expandRelativeRefs(a.dts,a.url,c,t);let d=this.scanner.collectBareModuleRefs(a.dts).slice(0,Ze.maxBareDeps).filter(u=>!i.has(u));for(let u of d)await this.prefetchBareDepsRecursive(u,t,n,s-1,i,o)}async resolve(e,t,n){let s=await this.packageService.extractImports(e),i=n?[...s,...n]:s;return(await Promise.all(i.map(a=>this.resolveOne(a,t)))).filter(a=>!!a)}async resolveOne(e,t){let{effectivePackage:n}=await this.versionResolver.effectivePackage(e,t);return this.withInFlight(n,async()=>{let s=new B(e),i=await this.fetchRootDts(e,t)??(s.subpath?await this.fetchRootDts(s.name,t):void 0);return i?this.buildDefFromContent(e,i,i.resolvedPkg||e,t):this.createStubDef(e)})}async buildDefFromContent(e,t,n,s){let{dts:i,url:o,resolvedPkg:a}=t,c=new B(a||n),l=c.version?`${c.name}@${c.version}`:c.name,{mainPath:d,packageRootUrl:u}=this.computeEntryPath(o,l),f=[{path:d,content:i}],p=[];o&&await this.expandRelativeRefs(i,o,l,f,void 0,u);let b=f.map(A=>A.content).join(`
|
|
1600
|
-
`);await this.prefetchBareDeps(b,l,f,p,s);let m=c.format(),g=e===m?[e]:[e,m],x=g.some(A=>this.ambientlyDeclares(i,A));return x?this.markFileAmbient(f,d):p.push(...g.map(A=>({module:A,path:d}))),{pkg:e,mainPath:d,files:f,shims:p,ambient:x}}};Xc();Ke();wr();$n();Gc();br();import*as qr from"path";var sP=qr.join(yi,"pkg"),iP=qr.join(yi,"files"),oP=qr.join(yi,"negative.json"),Lo=class{pkgMem=new Map;fileMem=new Map;negativeCache=new qt(new vr(oP));async getCachedDts(e){if(this.pkgMem.has(e))return this.pkgMem.get(e);await G();let t=await He(ay(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 $o(async()=>{await G(),await he(ay(e),JSON.stringify(s))})}async getCachedFile(e){if(this.fileMem.has(e))return this.fileMem.get(e);await G();let t=await gi(cy(e));return this.fileMem.set(e,t),t}async setCachedFile(e,t){this.fileMem.set(e,t),await $o(async()=>{await G(),await he(cy(e),t)})}isNegative(e){return this.negativeCache.isNegative(e)}async recordNegative(e){await $o(async()=>{await G(),await this.negativeCache.recordNegative(e)})}clearNegative(e){return $o(()=>this.negativeCache.clearNegative(e))}};async function $o(r){try{await r()}catch{}}function ay(r){return qr.join(sP,ke(r)+".json")}function cy(r){return qr.join(iP,ke(r)+".txt")}wr();var hu;function aP(){return hu||(hu=new Zn({cache:new Lo,cdnClient:xm,packageService:Si,versionResolver:km})),hu}var ly="file:///node_modules/";async function uy(r){let e=bi(r.emitKey,"typecheck");await G(),await ae.rm(e,{recursive:!0,force:!0}),await ae.mkdir(e,{recursive:!0});let t=fP(r.jsxImportSource,r.dependencies),n=await aP().resolve(r.code,r.dependencies,t),s=r.local?.name,i=s?n.filter(d=>d.pkg!==s):n,o=new Set;for(let d of i)for(let u of d.files){let f=Mo(u.path);if(!f||o.has(f))continue;o.add(f);let p=se.join(e,"node_modules",f);await ae.mkdir(se.dirname(p),{recursive:!0}),await ae.writeFile(p,u.content,"utf8")}let a={};for(let d of i)for(let u of d.shims){let f=Mo(u.path);f&&(a[u.module]=[`./node_modules/${f}`])}for(let d of i){if(d.ambient)continue;let u=Mo(d.mainPath);u&&(a[d.pkg]=[`./node_modules/${u}`])}let c=new Set;for(let d of i)for(let u of d.files){if(!u.ambient)continue;let f=Mo(u.path);f&&c.add(`node_modules/${f}`)}if(r.local){delete a[r.local.name];let d=await dP(r.local,e);d?a[r.local.name]=[`./node_modules/${r.local.name}/${d}`]:console.warn(` local: '${r.local.name}' ships no type defs; check cannot type against it.`)}let l=cP(r.jsxImportSource,a,[...c]);return await ae.writeFile(se.join(e,"tsconfig.json"),JSON.stringify(l,null,2)+`
|
|
1601
|
-
`,"utf8"),await ae.writeFile(se.join(e,"code.tsx"),r.code,"utf8"),await ae.writeFile(se.join(e,"tb.d.ts"),du,"utf8"),{dir:e}}var gu={target:"es2023",module:"esnext",moduleResolution:"bundler",strict:!0,noEmit:!0,skipLibCheck:!0,esModuleInterop:!0,allowSyntheticDefaultImports:!0,forceConsistentCasingInFileNames:!0};function cP(r,e,t=[]){return{compilerOptions:{...gu,lib:lP([...lu,...uu]),jsx:"react-jsx",jsxImportSource:r??"react",paths:e},include:["code.tsx","tb.d.ts",...t]}}function lP(r){return fu(r).map(e=>uP(e.name))}function uP(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 fP(r,e){let t=r??("react"in e?"react":void 0);return t?[`${t}/jsx-runtime`,`${t}/jsx-dev-runtime`]:[]}function Mo(r){if(!r.startsWith(ly))return;let e=r.slice(ly.length),t=e.indexOf("/");if(!(t<0))return e.slice(t+1)}async function dP(r,e){if(!r.typesAbs)return;let t=se.dirname(r.typesAbs),n=se.join(e,"node_modules",r.name);for(let s of await pP(t)){let i=se.join(n,se.relative(t,s));await ae.mkdir(se.dirname(i),{recursive:!0}),await ae.copyFile(s,i)}return se.basename(r.typesAbs)}async function pP(r){let e=[];async function t(n){let s=await ae.readdir(n,{withFileTypes:!0});for(let i of s){let o=se.join(n,i.name);i.isDirectory()?await t(o):/\.d\.ts(\.map)?$/.test(i.name)&&e.push(o)}}return await t(r),e}import*as be from"fs/promises";import*as et from"path";import{existsSync as mP}from"fs";wr();Zc();var hP="^22";async function fy(r){let e=bi(r.emitKey,"typecheck-server");await G(),await be.rm(e,{recursive:!0,force:!0}),await be.mkdir(e,{recursive:!0});let t=et.join(r.bulbDir,".typebulb"),n=Oi(r.server).filter(o=>o!==r.local?.name);await Pi([`@types/node@${hP}`,...n],t,r.dependencies,{ignoreScripts:!0});let s=et.join(t,"node_modules"),i=et.join(e,"node_modules");return await yP(s,i),await be.writeFile(et.join(e,"server.ts"),r.server,"utf8"),await be.writeFile(et.join(e,"tb.d.ts"),pu,"utf8"),await be.writeFile(et.join(e,"tsconfig.json"),JSON.stringify(gP(r.local),null,2)+`
|
|
1602
|
-
`,"utf8"),{dir:e}}function gP(r){let e={...gu,lib:["ES2023"],types:["node"]};if(r?.typesAbs){let t=i=>i.replace(/\\/g,"/"),n=t(et.dirname(r.typesAbs)),s=t(r.typesAbs).replace(/\.d\.ts$/,"");e.paths={[r.name]:[s],[`${r.name}/*`]:[`${n}/*`]}}return{compilerOptions:e,include:["server.ts","tb.d.ts"]}}async function yP(r,e){if(!mP(r)){await be.mkdir(e,{recursive:!0});return}await be.rm(e,{recursive:!0,force:!0});let t=process.platform==="win32"?"junction":"dir";await be.symlink(r,e,t)}di();async function py(r,e){let{bulb:t,config:n,warnings:s}=await Ae(r);!t.code&&!t.server&&(console.error("Bulb has neither **code.tsx** nor **server.ts**; nothing to check."),process.exit(1));let i=!1;for(let l of s)console.log(`structure ${l}`);s.length&&(i=!0),t.code&&(i=dy(En(t.code,{target:"client",dependencies:n.dependencies??{}}),"client")||i),t.server&&(i=dy(En(t.server,{target:"server"}),"server")||i);let o=EP([process.cwd(),Ot.dirname(r)]);if(!o){let l=Ot.relative(process.cwd(),r)||r;console.error("check: TypeScript not found \u2014 install it once, then re-run:"),console.error(" npm i -g typescript"),console.error(` typebulb check ${l}`),process.exit(2)}let a=[];if(t.code){let{dir:l}=await uy({code:t.code,dependencies:n.dependencies??{},jsxImportSource:n.ts?.jsxImportSource,emitKey:r,local:e});a.push({role:"client",dir:l})}if(t.server){let{dir:l}=await fy({server:t.server,bulbDir:Ot.dirname(r),emitKey:r,local:e?{name:e.name,typesAbs:e.typesAbs}:void 0,dependencies:n.dependencies});a.push({role:"server",dir:l})}for(let{role:l,dir:d}of a){let{stdout:u,exitCode:f}=await kP(o,d);for(let p of u.split(/\r?\n/))p.trim()&&console.log(`${l} ${p}`);f!==0&&(i=!0)}i&&process.exit(1);let c=[t.code&&"code.tsx",t.server&&"server.ts"].filter(Boolean).join(", ");console.error(`\u2713 no issues (${c})`)}function dy(r,e){for(let t of r)for(let n of t.message.split(`
|
|
1603
|
-
`))console.log(`${e} ${n}`);return r.length>0}function kP(r,e){return new Promise(t=>{let n=bP(process.execPath,[r,"--noEmit"],{cwd:e}),s="";n.stdout?.on("data",i=>{s+=i.toString()}),n.stderr?.on("data",i=>{s+=i.toString()}),n.on("close",i=>t({stdout:s,exitCode:i??1}))})}var xP=vP(import.meta.url);function EP(r){let e=n=>{try{let s=xP.resolve("typescript/package.json",{paths:n}),i=Ot.join(Ot.dirname(s),"lib","tsc.js");return SP(i)?i:void 0}catch{return}},t=e(r);if(t)return t;try{let n=wP("npm root -g",{encoding:"utf8"}).trim();return e([n])}catch{return}}vt();Qi();qn();async function my(r,e){let{bulb:t}=await Ae(r),n=Nr(t);if(Yt(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.)")}qn();import*as es from"path";async function hy(r,e){if(!r){e||(console.error("Usage: typebulb untrust <file.bulb.md>"),process.exit(1));let n=vl();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=es.resolve(r);t.endsWith(".bulb.md")||(console.error("File must have .bulb.md extension"),process.exit(1)),Or(t,e),console.log(e?`Trusted ${es.basename(t)} \u2014 runs with fs / AI / server.ts (no --trust needed).`:`Untrusted ${es.basename(t)} \u2014 runs Restricted.`),console.log(` ${t}`)}$e();import*as wy from"readline";var ts=Vg();function gy(){for(let r of Object.values(ts))try{r().ensureHarnessSupport()}catch{}}function rs(){for(let r of Object.keys(ts))try{if(ts[r]().detectsSelf())return r}catch{}}function yy(r){let e=jr(),t=new Map(e.filter(i=>ts[i]).map(i=>[i,ts[i]()]));for(let[i,o]of t)if(o.detectsSelf())return{name:i};let n=[...t].filter(([,i])=>i.detectsInstalled()).map(([i])=>i);if(n.length===0)return{name:e[0]};if(n.length===1)return{name:n[0]};let s=i=>t.get(i).listSessionFiles(r).length>0;return{ambiguous:[...n].sort((i,o)=>Number(s(o))-Number(s(i)))}}Zi();function yu(r){let e=t=>n=>r?`\x1B[${t}m${n}\x1B[0m`:n;return{lit:e("38;5;70"),litLink:e("4;38;5;70"),brand:e("38;5;135")}}async function vy(r){let e=yy(process.cwd());if("ambiguous"in e){let t=await AP(r,e.ambiguous);return t?by(r,t):TP(r,e.ambiguous)}return by(r,e.name)}async function by(r,e){let t,n;try{t=await ah(e)}catch(d){n=d instanceof Error?d.message:String(d)}let{lit:s,litLink:i,brand:o}=yu(process.stdout.isTTY===!0),a=[" Read the authoring skill before writing a bulb:",` \u2022 ${s("npx typebulb skill")} \u2014 assembles one SKILL.md`," \u2022 or, open its parts:",` ${s(Ir())}`,` ${s(zt())}`],c=t?[` Agent mirror (${e}) is live\u{1F4A1}`,` ${s("\u25CF")} ${i(t.url)}`," Embedded bulbs render live here."," Agents:",` Reusable app/tool \u2192 write a ${s(".bulb.md")}`," Show something inline \u2192 embed a bulb",e==="pi"?" arm a wait for its render verdict \u2014 run it plainly:":" background a wait for its render verdict:",` \u2022 ${s('typebulb wait agent --match "[embed <name>"')}`,...a," End your reply with the mirror link above"," \u2022 easy to miss the link mid-message"]:[` The mirror did not start (${n})`,` \u25CF Start it manually: ${s(`npx typebulb agent:${e}`)}`," Agents:",...a],l=[` ${o(`typebulb v${r}`)}`,...c,""];process.stdout.write(l.join(`
|
|
1604
|
-
`)+`
|
|
1605
|
-
`)}async function AP(r,e){if(!process.stdin.isTTY||!process.stdout.isTTY)return;let{lit:t,brand:n}=yu(!0),s=[` ${n(`typebulb v${r}`)}`," More than one agent harness is available here.",...e.map((o,a)=>` ${t(String(a+1))}) ${o}`),""];process.stdout.write(s.join(`
|
|
1606
|
-
`)+`
|
|
1607
|
-
`);let i=wy.createInterface({input:process.stdin,output:process.stdout});try{let o=(await new Promise(c=>i.question(" Open which? [1]: ",c))).trim();if(o==="")return e[0];let a=Number(o);return Number.isInteger(a)&&a>=1&&a<=e.length?e[a-1]:e.find(c=>c===o.toLowerCase())}finally{i.close()}}function TP(r,e){let{lit:t,brand:n}=yu(process.stdout.isTTY===!0),s=[` ${n(`typebulb v${r}`)}`," More than one agent harness is available here."," Open the mirror for the one you want:",...e.map(i=>` \u2022 ${t(`npx typebulb agent:${i}`)}`),""];process.stdout.write(s.join(`
|
|
1608
|
-
`)+`
|
|
1609
|
-
`)}xt();Wt();async function Sy(r){ye(r);let e=await Ye();if(e.length>0){console.log(Bm(e,process.env.TB_AI_PROVIDER,process.env.TB_AI_MODEL));return}if(!ml()){console.log("No AI provider keys found in this directory's .env, and no local Ollama server detected."),console.log("Set one of these to use a cloud model with tb.ai:");for(let[t,n]of Object.entries(Ar))console.log(` ${n.padEnd(20)} (${t})`);console.log("\u2026or start Ollama (http://localhost:11434, or set OLLAMA_HOST) for local models. Then re-run `typebulb models`.");return}console.log("Couldn't fetch the model catalog (offline?). tb.ai still works with any valid provider/model id for your keys.")}Zi();import*as ky from"fs/promises";async function xy(r){let e=zt(),t;try{t=await ky.readFile(e,"utf8")}catch{console.error(`Could not read the bundled README (expected at ${e}).`),process.exit(1)}process.stdout.write(gh(t,r))}Fi();import*as Ey from"path";$e();function PP(r,e,t,n){if(/^\d+$/.test(e))return r.find(i=>i.pid===parseInt(e,10));let s=e==="agent"?r.filter(i=>i.agent!=null):r.filter(i=>i.agent===e);if(s.length){if(!t)return s[0];let i=s.filter(o=>o.cwd&&ne(o.cwd)===ne(t));return n&&i.find(o=>o.agent===n)||i[0]}return r.find(i=>ne(i.file)===ne(e))}var ns=r=>r.agent??Ey.basename(r.file);function Ay(r,e){for(let t of r)e(` ${t.url} pid ${t.pid} ${t.trust?"trusted":"restricted"}${t.dir?` --dir ${t.dir}`:""} ${t.file}`)}function bu(r,e){if(!r.length){console.log("No running bulb servers.");return}console.log("Running bulb servers:"),Ay(r,t=>console.log(t)),console.log(`
|
|
1610
|
-
`+e)}function wu(r,e,t,n,s){let i=PP(r,e,n,s);if(i)return i;console.error(`No running server for '${e}'.`),r.length?(console.error(`Running servers (try \`typebulb ${t} <file|pid>\`):`),Ay(r,o=>console.error(o))):console.error("No bulb servers are running."),process.exit(1)}async function Ty(r,e){if(!r){e.clear&&(console.error("Specify which server to clear: typebulb logs --clear <file|pid>"),process.exit(1)),bu(await Q(process.cwd()),"Run `typebulb logs <file|pid>` to print one server's console.");return}let t=wu(await Q(),r,"logs",process.cwd(),rs());if(e.clear){th(t.pid),console.log(`Cleared log for ${ns(t)} (pid ${t.pid}).`);return}let n=Ie(t.pid),s=n.text;if(e.run!==void 0&&(s=rh(s,e.run),!s&&e.run!=="latest"&&console.error(`No output for run ${e.run} (it hasn't started, or was trimmed from the log).`)),e.lines&&e.lines>0){let i=s.split(`
|
|
1611
|
-
`);i.length&&i[i.length-1]===""&&i.pop(),s=i.slice(-e.lines).join(`
|
|
1612
|
-
`)}if(process.stdout.write(s),s&&!s.endsWith(`
|
|
1613
|
-
`)&&process.stdout.write(`
|
|
1614
|
-
`),e.follow&&e.run===void 0){let i=n.offset,o=setInterval(()=>{let c=Ie(t.pid,i);i=c.offset,c.text&&process.stdout.write(c.text)},500),a=()=>{clearInterval(o),process.exit(0)};process.on("SIGINT",a),process.on("SIGTERM",a),await new Promise(()=>{})}}var OP=r=>new Promise(e=>setTimeout(e,r));async function Py(r,e){if(!r){bu(await Q(process.cwd()),"Run `typebulb wait <file|pid>` to block until one logs a new line.");return}let t=wu(await Q(),r,"wait",process.cwd(),rs()),n=t.agent!=null,i=process.env.TYPEBULB_WAIT_SHIM==="1",o=e.timeoutSec??1800,a=e.match??"",c=Ie(t.pid).offset,l=Rl(t.pid,a)??(a?Rl(t.pid):void 0),d=l!==void 0&&l<=c?l:a?0:c,u=Date.now()+o*1e3,f=n?1e4:1e3,p=2e3,b,m="",g=0;for(;;){let x=Ie(t.pid,d);if(d=x.offset,x.text){m+=x.text;let A=m.split(`
|
|
1615
|
-
`);m=A.pop()??"";for(let P of A)P.trim()&&(e.match&&!P.includes(e.match)||(console.log(P),b??=Date.now()+f,n&&(P.includes("] compile error")||P.includes("] runtime error"))&&(b=Math.min(b,Date.now()+p))))}if(b&&Date.now()>=b)break;if(!i&&!b&&Date.now()>=u){console.error(`timeout: no ${e.match?`line matching '${e.match}'`:"new output"} from ${ns(t)} within ${o}s`),g=2;break}if(!Il(t.pid)){b||(console.error(`server ${ns(t)} (pid ${t.pid}) exited while waiting`),process.exit(3));break}await OP(400)}Yi(t.pid,d,a),process.exit(g)}async function Oy(r){if(!r){bu(await Q(process.cwd()),"Run `typebulb stop <file|pid>` to stop one.");return}let e=wu(await Q(),r,"stop",process.cwd(),rs());await Vt(e.pid),console.log(`Stopped ${ns(e)} (pid ${e.pid}, ${e.url}).`)}async function Cy(r){let e=process.cwd(),t=r==="agent"?rs():void 0,n=r==="global"?await Q():r==="bulbs"?await Q(e):(await Q()).filter(i=>i.agent!=null&&i.cwd!=null&&ne(i.cwd)===ne(e)&&(!t||i.agent===t)),s=r==="global"?"server":r==="agent"?"mirror":"bulb";if(!n.length){console.log(r==="global"?"No running bulb servers.":`No running ${s}s for this project.`);return}await Promise.all(n.map(i=>Vt(i.pid))),console.log(`Stopped ${n.length} ${s}${n.length===1?"":"s"}:`);for(let i of n)console.log(` ${i.url} pid ${i.pid} ${ns(i)}`)}$e();import*as _y from"path";async function Ry(r,e,t=0){let n=e!==void 0&&e.startsWith("tb:");n&&t<=0&&(t=Yo);let s=_y.resolve(r),i=Rr(await Q(),s)[0];i||(console.error(`No running server for '${r}'. Start it first: npx typebulb ${r}`),process.exit(1));let o=async f=>{let p=await fetch(`${i.url}/__send${f>0?`?reply=${f}`:""}`,{method:"POST",headers:{"Content-Type":"text/plain"},body:e??""});return p.ok||(console.error(`send failed: HTTP ${p.status} from ${i.url}/__send`),process.exit(1)),await p.json().catch(()=>({}))},a={};try{let f=Date.now()+t;do{if(a=await o(t>0?Math.max(f-Date.now(),1e3):0),(a.clients??0)>0||Date.now()>=f)break;await new Promise(p=>setTimeout(p,150))}while(!0)}catch(f){console.error(`send failed: ${f instanceof Error?f.message:String(f)}`),process.exit(1)}let c=a.clients??0,l=`${c} page${c===1?"":"s"}`;if(c===0){t>0?console.error(`No page connected after ${t/1e3}s \u2014 is the bulb open?`):console.error("Sent, but no page is connected yet \u2014 open the bulb and retry."),n&&process.exit(1);return}console.error(`Sent to ${l}.`);let d=a.results??[],u=a.errors??[];for(let f of u)console.error(`handler error: ${f}`);if(u.length&&process.exit(1),d.length>1&&(console.error(`${d.length} replies from ${l} \u2014 one reply owns stdout: at most one tb.onMessage handler, in one page, may return a value.`),process.exit(1)),d.length===1){let f;try{f=JSON.parse(d[0])}catch{f=void 0}console.log(typeof f=="string"?f:d[0])}else a.timedOut&&(n&&(console.error(`No reply to '${e}' within ${t/1e3}s \u2014 reload the page and retry.`),process.exit(1)),console.error(`(no reply within ${t/1e3}s \u2014 a slow handler's return needs a larger --wait=ms)`))}so();Jl();xt();vt();Re();Qi();import*as _t from"fs/promises";import*as os from"path";import{EventEmitter as jy}from"events";import JP from"open";Er();Re();import{Hono as $P}from"hono";import{serve as LP}from"@hono/node-server";import{streamSSE as MP}from"hono/streaming";import*as xu from"fs/promises";import*as Ly from"path";wr();$n();br();import*as vu from"fs/promises";import*as ss from"path";var Do=class{async get(e){let t=ke(e),n=ss.join(In,t+".bin"),s=ss.join(In,t+".json");try{let[i,o]=await Promise.all([vu.readFile(n),vu.readFile(s,"utf8")]),a=JSON.parse(o);return{body:i,contentType:a.contentType,cacheControl:a.cacheControl}}catch{return}}async set(e,t){await G();let n=ke(e),s=ss.join(In,n+".bin"),i=ss.join(In,n+".json"),o={url:e,contentType:t.contentType,cacheControl:t.cacheControl};await Promise.all([he(s,t.body),he(i,JSON.stringify(o))])}};var Ny=`
|
|
1616
|
-
const CSS = '\\n' +
|
|
1617
|
-
/* The agent mirror's token set, verbatim (agents/core/client/styles.css) \u2014 one system across CLI
|
|
1618
|
-
chrome: app chrome sits on --panel, content wells paint --veil, grays ride one neutral tint.
|
|
1619
|
-
The lone extension is --accent-contrast (text on a filled accent; the mirror never fills a
|
|
1620
|
-
button, and the dark theme's lighter accent needs dark text). */
|
|
1621
|
-
'.overlay { --fg: rgb(28, 28, 30); --muted: rgb(96, 96, 100); --panel: rgb(242, 242, 242);\\n' +
|
|
1622
|
-
' --border: rgb(221, 221, 221); --accent: rgb(58, 125, 232); --accent-contrast: #fff;\\n' +
|
|
1623
|
-
' --veil: rgba(0, 0, 0, 0.05); --err: rgb(206, 60, 60); }\\n' +
|
|
1624
|
-
'.dark .overlay { --fg: rgb(190, 190, 190); --muted: rgb(150, 150, 150); --panel: rgb(32, 32, 32);\\n' +
|
|
1625
|
-
' --border: rgb(52, 52, 52); --accent: rgb(122, 162, 250); --accent-contrast: #1c1e21;\\n' +
|
|
1626
|
-
' --veil: rgba(255, 255, 255, 0.06); --err: rgb(230, 60, 60); }\\n' +
|
|
1627
|
-
'.overlay { position: fixed; inset: 0; background: rgba(0,0,0,.45); z-index: 2147483000;\\n' +
|
|
1628
|
-
' display: flex; align-items: center; justify-content: center; padding: 16px;\\n' +
|
|
1629
|
-
' font: 14px/1.45 system-ui, sans-serif; color: var(--fg); }\\n' +
|
|
1630
|
-
'.card { background: var(--panel); border-radius: 10px; box-shadow: 0 12px 40px rgba(0,0,0,.35);\\n' +
|
|
1631
|
-
' width: min(560px, 100%); max-height: min(80vh, 640px); display: flex; flex-direction: column; }\\n' +
|
|
1632
|
-
'.head { display: flex; align-items: center; gap: 8px; padding: 14px 16px 10px; }\\n' +
|
|
1633
|
-
'.head h1 { font-size: 18px; font-weight: 600; margin: 0; flex: 1; color: var(--accent); }\\n' +
|
|
1634
|
-
'.x { border: 0; background: none; color: inherit; font-size: 18px; cursor: pointer; opacity: .6; padding: 2px 6px; }\\n' +
|
|
1635
|
-
'.x:hover { opacity: 1; }\\n' +
|
|
1636
|
-
'.body { padding: 0 16px; overflow-y: auto; flex: 1; display: flex; flex-direction: column; gap: 10px; }\\n' +
|
|
1637
|
-
'.model { color: var(--muted); }\\n' +
|
|
1638
|
-
'.model.err { color: var(--err); }\\n' +
|
|
1639
|
-
'label { font-weight: 600; }\\n' +
|
|
1640
|
-
'.tabs { display: flex; gap: 4px; }\\n' +
|
|
1641
|
-
'.tab { font: inherit; padding: 4px 10px; border: 0; border-bottom: 2px solid transparent; border-radius: 0; background: none; color: inherit; cursor: pointer; opacity: .6; }\\n' +
|
|
1642
|
-
'.tab.on { opacity: 1; border-bottom-color: var(--accent); }\\n' +
|
|
1643
|
-
'.tab .cnt { opacity: .6; font-size: 12px; margin-left: 4px; }\\n' +
|
|
1644
|
-
'textarea { width: 100%; box-sizing: border-box; min-height: 160px; max-height: 320px; resize: vertical;\\n' +
|
|
1645
|
-
' font: 13px/1.4 ui-monospace, monospace; padding: 8px; border-radius: 6px;\\n' +
|
|
1646
|
-
' border: 1px solid var(--border); background: var(--veil); color: inherit; }\\n' +
|
|
1647
|
-
'pre.stream { font: 13px/1.4 ui-monospace, monospace; white-space: pre-wrap; word-break: break-word;\\n' +
|
|
1648
|
-
' background: var(--veil); border-radius: 6px; padding: 10px; margin: 0; min-height: 120px; }\\n' +
|
|
1649
|
-
'.error { color: var(--err); white-space: pre-wrap; }\\n' +
|
|
1650
|
-
'.foot { display: flex; gap: 8px; padding: 12px 16px 14px; justify-content: flex-end; align-items: center; }\\n' +
|
|
1651
|
-
'.leftgrp { margin-right: auto; display: flex; gap: 8px; }\\n' +
|
|
1652
|
-
'button { font: inherit; padding: 6px 14px; border-radius: 6px; cursor: pointer;\\n' +
|
|
1653
|
-
' border: 1px solid var(--border); background: transparent; color: inherit; }\\n' +
|
|
1654
|
-
'button.run { background: var(--accent); border-color: var(--accent); color: var(--accent-contrast); }\\n' +
|
|
1655
|
-
'button.run:disabled { opacity: .5; cursor: default; }\\n' +
|
|
1656
|
-
'@keyframes shimmer { 0% { background-position: 200% 0; } 100% { background-position: -200% 0; } }\\n' +
|
|
1657
|
-
'.shimmer { display: inline-block; background-image: linear-gradient(90deg, var(--muted), var(--fg), var(--muted));\\n' +
|
|
1658
|
-
' background-size: 200% 100%; -webkit-background-clip: text; background-clip: text;\\n' +
|
|
1659
|
-
' -webkit-text-fill-color: transparent; color: transparent; animation: shimmer 2s linear infinite; }\\n';
|
|
1660
|
-
|
|
1661
|
-
function isDark() {
|
|
1662
|
-
var t = document.documentElement.getAttribute('data-theme');
|
|
1663
|
-
if (t) return t === 'dark';
|
|
1664
|
-
return window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
|
|
1665
|
-
}
|
|
1302
|
+
var pre = el('pre', 'stream', '');
|
|
1303
|
+
var waiting = el('span', 'shimmer', 'Waiting for response\\u2026');
|
|
1304
|
+
pre.appendChild(waiting);
|
|
1305
|
+
var textNode = null;
|
|
1306
|
+
body.appendChild(pre);
|
|
1307
|
+
var cancel = el('button', '', 'Cancel');
|
|
1308
|
+
cancel.addEventListener('click', function () { close('cancel'); });
|
|
1309
|
+
foot.appendChild(cancel);
|
|
1666
1310
|
|
|
1667
|
-
|
|
1668
|
-
|
|
1669
|
-
|
|
1670
|
-
|
|
1671
|
-
|
|
1672
|
-
}
|
|
1311
|
+
aborter = new AbortController();
|
|
1312
|
+
(async function () {
|
|
1313
|
+
var resp = await fetch('/__infer', {
|
|
1314
|
+
method: 'POST',
|
|
1315
|
+
headers: { 'Content-Type': 'application/json' },
|
|
1316
|
+
body: JSON.stringify({ data: data }),
|
|
1317
|
+
signal: aborter.signal
|
|
1318
|
+
});
|
|
1319
|
+
if (resp.headers.get('X-TB-Stream') !== '1') {
|
|
1320
|
+
// Non-stream response: a 403 trust denial (plain text) or a 400/500 JSON error.
|
|
1321
|
+
var text = await resp.text();
|
|
1322
|
+
var err; try { err = JSON.parse(text); } catch (e) { err = { message: text, code: 'unknown', retryable: false }; }
|
|
1323
|
+
var e2 = new Error(err.message || 'Inference failed'); e2.code = err.code; e2.retryable = !!err.retryable;
|
|
1324
|
+
throw e2;
|
|
1325
|
+
}
|
|
1326
|
+
var final = null;
|
|
1327
|
+
for await (var v of ctx.readStream(resp)) {
|
|
1328
|
+
if (v.kind === 'delta') {
|
|
1329
|
+
if (waiting) { waiting.remove(); waiting = null; textNode = document.createTextNode(''); pre.appendChild(textNode); }
|
|
1330
|
+
textNode.appendData(v.text); pre.scrollTop = pre.scrollHeight;
|
|
1331
|
+
}
|
|
1332
|
+
else if (v.kind === 'complete') final = v;
|
|
1333
|
+
}
|
|
1334
|
+
if (!final) { var e3 = new Error('Stream ended without a result'); e3.code = 'network'; e3.retryable = true; throw e3; }
|
|
1335
|
+
completed = true;
|
|
1336
|
+
ctx.onComplete(final);
|
|
1337
|
+
close('complete');
|
|
1338
|
+
})().catch(function (err) {
|
|
1339
|
+
if (canceled) return; // user canceled; close() already ran and the abort rejection is expected
|
|
1340
|
+
showError(err);
|
|
1341
|
+
});
|
|
1342
|
+
}
|
|
1673
1343
|
|
|
1674
|
-
|
|
1675
|
-
|
|
1676
|
-
|
|
1677
|
-
|
|
1678
|
-
var first = (chunk.split('\\n')[0] || '').trim();
|
|
1679
|
-
if (first.charAt(0) === '#' && first.length > 1 && first.length < 40) return first.replace(/^#+\\s*/, '');
|
|
1680
|
-
if (first.indexOf('//') === 0 && first.length > 2 && first.length < 40) return first.replace(/^\\/\\/\\s*/, '');
|
|
1681
|
-
return 'Data ' + (i + 1);
|
|
1682
|
-
}
|
|
1344
|
+
function showError(err) {
|
|
1345
|
+
body.textContent = ''; foot.textContent = '';
|
|
1346
|
+
body.appendChild(el('div', 'error', err.message || 'Inference failed'));
|
|
1347
|
+
ctx.onError({ message: err.message, code: err.code || 'unknown', retryable: !!err.retryable });
|
|
1683
1348
|
|
|
1684
|
-
|
|
1685
|
-
|
|
1686
|
-
|
|
1687
|
-
|
|
1688
|
-
|
|
1689
|
-
|
|
1690
|
-
|
|
1691
|
-
|
|
1692
|
-
|
|
1693
|
-
var host = document.createElement('div');
|
|
1694
|
-
var root = host.attachShadow({ mode: 'closed' });
|
|
1695
|
-
var style = document.createElement('style');
|
|
1696
|
-
style.textContent = CSS;
|
|
1697
|
-
root.appendChild(style);
|
|
1349
|
+
var closeBtn = el('button', '', 'Close');
|
|
1350
|
+
closeBtn.addEventListener('click', function () { close('cancel'); });
|
|
1351
|
+
foot.appendChild(closeBtn);
|
|
1352
|
+
if (err.retryable) {
|
|
1353
|
+
var retry = el('button', 'run', 'Retry');
|
|
1354
|
+
retry.addEventListener('click', showConfirm);
|
|
1355
|
+
foot.appendChild(retry);
|
|
1356
|
+
}
|
|
1357
|
+
}
|
|
1698
1358
|
|
|
1699
|
-
|
|
1700
|
-
|
|
1701
|
-
|
|
1702
|
-
|
|
1703
|
-
|
|
1704
|
-
|
|
1359
|
+
showConfirm();
|
|
1360
|
+
document.body.appendChild(host);
|
|
1361
|
+
}
|
|
1362
|
+
`});import{stream as NE}from"hono/streaming";function Gn(r){return r instanceof pe?{message:r.message,code:r.code,retryable:r.retryable}:{message:r instanceof Error?r.message:"Unknown error",code:"unknown",retryable:!1}}function ao(r,e){return r.header("Content-Type","application/x-ndjson; charset=utf-8"),r.header("Cache-Control","no-cache"),r.header(IE,"1"),NE(r,async t=>{let n=e[Symbol.asyncIterator]();t.onAbort(()=>{n.return?.()});try{for(;;){let{done:s,value:i}=await n.next();if(s)break;await t.writeln(JSON.stringify({type:"chunk",value:i}))}}catch(s){await t.writeln(JSON.stringify({type:"error",error:Gn(s)}))}finally{try{await n.return?.()}catch{}}})}var IE,$h=v(()=>{xr();IE="X-TB-Stream"});function lo(r,e){let t=r?.[e]??(Object.hasOwn(co,e)?co[e]:void 0);return typeof t=="function"?t:void 0}function uo(r){return r.constructor?.name==="AsyncGeneratorFunction"}var co,Gl=v(()=>{co={log:(...r)=>console.log(...r)}});function Lh(r,e=""){return $E.test(r)?!0:ME.test(r)&&LE.test(e)}var $E,LE,ME,Mh=v(()=>{$E=/^\/(v\d+\/|stable\/|node\/|gh\/|@[^/]+\/[^@/]+@|[^@/]+@)/,LE=/[?&]target=/,ME=/^\/(?:@[^/]+\/)?[^/@]+\/[^/]+/});import{Hono as DE}from"hono";import{serve as BE}from"@hono/node-server";import{streamSSE as jE}from"hono/streaming";import*as Ql from"fs/promises";import*as Bh from"path";function qE(r){if(r)try{return new URL(r.includes("://")?r:`http://${r}`).hostname}catch{return}}function UE(r){let e=qE(r);return!!e&&FE.has(e)}function JE(r,e){if(!e)return!1;try{return new URL(r).host===e}catch{return!1}}function zl(r){return r instanceof Error?r.message:"Unknown error"}async function Fh(r){let{getHtml:e,basePath:t,fsBase:n,port:s,reloadEmitter:i,messageEmitter:o,getServerExports:a,getBulbBlocks:c,saveInferenceResult:l,localOverride:f,trusted:u=!1,trustHint:d,staticAssets:p,bulbAssets:b}=r,m=n??t,g=new DE;g.use("*",async(y,w)=>{if(!UE(y.req.header("host")))return y.text("Forbidden: untrusted Host",403);await w()}),g.use("*",async(y,w)=>{await w(),y.res.headers.set("Cross-Origin-Opener-Policy","same-origin"),y.res.headers.set("Cross-Origin-Embedder-Policy","credentialless")});let x=[["/__fs/*","the filesystem"],["/__api/*","server-side code (server.ts)"],["/__ai","AI (your API keys)"],["/__infer","AI (your API keys)"],["/__infer-save","the filesystem"]],A=async(y,w)=>{if(!u){let $=new URL(y.req.url).pathname,R=x.find(([W])=>W.endsWith("/*")?$.startsWith(W.slice(0,-2)):$===W)?.[1]??"server-side code (server.ts)";mh(process.pid,R);let M=d?`
|
|
1363
|
+
${d}`:"";return y.text(`Forbidden: this capability requires --trust.${M}`,403)}await w()},P=async(y,w)=>{let $=y.req.header("sec-fetch-site");if($){if($!=="same-origin")return y.text(`Forbidden: ${$} request`,403)}else{let R=y.req.header("origin");if(R&&!JE(R,y.req.header("host")))return y.text("Forbidden: cross-origin request",403)}await w()};for(let[y]of x)g.use(y,A),g.use(y,P);if(g.use("/__log",P),g.post("/__log",async y=>{try{let{args:w}=await y.req.json();console.log(...w||[])}catch{}return y.json({ok:!0})}),o){let y=0,w=new Map;g.use("/__send",P),g.post("/__send",async $=>{let R="";try{R=await $.req.text()}catch{}let M=Number($.req.query("reply"))||0,W=o.listenerCount("message");if(M<=0||W===0)return o.emit("message",{payload:R}),$.json({clients:W});let K=++y,qe=await new Promise(z=>{let V={expected:W,received:0,results:[],errors:[],finish:we=>{clearTimeout(Ue),w.delete(K),z({results:V.results,errors:V.errors,timedOut:we})}},Ue=setTimeout(()=>V.finish(!0),M);w.set(K,V),o.emit("message",{id:K,payload:R})});return $.json({clients:W,...qe})}),g.use("/__send-reply",P),g.post("/__send-reply",async $=>{try{let{id:R,results:M,errors:W}=await $.req.json(),K=w.get(R);K&&(K.results.push(...M??[]),K.errors.push(...W??[]),++K.received>=K.expected&&K.finish(!1))}catch{}return $.json({ok:!0})})}g.get("/",y=>y.html(e())),g.post("/__fs/read",async y=>{try{let{path:w}=await y.req.json(),$=await jn(w,m,t);return new Response(new Uint8Array($),{headers:{"Content-Type":"application/octet-stream"}})}catch(w){let $=zl(w);return y.json({error:$},400)}}),g.post("/__fs/write",async y=>{try{let w=y.req.query("path");return w?(await Fi(w,new Uint8Array(await y.req.arrayBuffer()),m,t),y.json({success:!0})):y.json({error:"Missing path"},400)}catch(w){let $=zl(w);return y.json({error:$},400)}}),g.post("/__api/:name",async y=>{try{let w=y.req.param("name"),$=lo(a?.(),w);if(!$)return y.json({error:`API function '${w}' not found`},404);let{args:R}=await y.req.json();if(uo($))return ao(y,$(...R||[]));let M=await $(...R||[]);return y.json({result:M})}catch(w){let $=zl(w);return y.json({error:$},500)}}),g.post("/__ai",async y=>{try{let{messages:w,system:$,effort:R,provider:M,model:W,webSearch:K,stream:qe}=await y.req.json();if(!w||!Array.isArray(w)||w.length===0)return y.json({message:"messages array is required",code:"unknown",retryable:!1},400);let z=Ge(M,W);if(typeof z=="string")return y.json({message:z,code:"unknown",retryable:!1},400);let V=await yt(z,{messages:w,system:$,effort:R,webSearch:K,signal:y.req.raw.signal});if(!V.ok){let we=await kr(V,z.protocol);return y.json(we,V.status)}if(qe)return ao(y,Kt(V,z.protocol));let Ue=await Jt(V,z.protocol);return Ue||console.warn("[tb.ai] Empty response from provider"),y.json({text:Ue})}catch(w){return y.json(Gn(w),500)}}),g.post("/__infer",async y=>{try{let{data:w}=await y.req.json().catch(()=>({})),$=c?.();if(!$?.infer.trim())return y.json({message:"This bulb has no infer.md block.",code:"unknown",retryable:!1},400);let R=Ge();if(typeof R=="string")return y.json({message:R,code:"unknown",retryable:!1},400);let M=Array.isArray(w)?w.map(String):[],W=pl($,M),K=await yt(R,{messages:[{role:"user",content:W}],signal:y.req.raw.signal});if(!K.ok){let z=await kr(K,R.protocol);return y.json(z,K.status)}let qe=(async function*(){let z="";for await(let we of Kt(K,R.protocol))we.kind!=="text"||!we.text||(z+=we.text,yield{kind:"delta",text:we.text});let V=ml(z);if(V.parsed===null)throw console.warn(`[tb.infer] output not valid JSON after sanitize; raw output (last 4000 chars):
|
|
1364
|
+
`+z.slice(-4e3)),new pe("LLM output is not valid JSON","parse_error",!0);V.fixesApplied.length&&console.warn("[tb.infer] sanitized output, fixes applied:",V.fixesApplied.join(", "));let Ue={insight:V.parsed,insightJson:V.json,data:M};yield{kind:"complete",...Ue,fixesApplied:V.fixesApplied,hash:hl(Ue)}})();return ao(y,qe)}catch(w){return y.json(Gn(w),500)}});let _=async y=>{let{hash:w}=await y.req.json().catch(()=>({}));return typeof w=="string"?gl(w):null};g.post("/__infer-save",async y=>{try{if(!l)return y.json({message:"Save is not available for this server.",code:"unknown",retryable:!1},400);let w=await _(y);return w?(await l(w.data,w.insightJson),y.json({ok:!0})):y.json({message:"No decodable #tb= fragment to save.",code:"unknown",retryable:!1},400)}catch(w){return y.json(Gn(w),500)}}),g.get("/__infer-info",y=>{let w=c?.(),$=rt(w?.config??"").inference,R=fi(w?.data??""),M=Ge();return typeof M=="string"?y.json({error:M,inference:$,data:R}):y.json({provider:M.protocol,model:M.model,inference:$,data:R})}),g.use("/__infer-decode",P),g.post("/__infer-decode",async y=>y.json(await _(y)??{error:"invalid fragment"})),g.get("/__infer-ui.js",y=>y.body(Nh,200,{"Content-Type":"text/javascript; charset=utf-8"})),g.get("/__models",async y=>{try{let w=await Ve();return y.json(w)}catch{return y.json([],200)}}),g.get("/__has-own-keys",async y=>{try{return y.json(await Bi())}catch{return y.json(!1,200)}});let N=["esm.sh","unpkg.com","cdn.jsdelivr.net","cdnjs.cloudflare.com"],C=new oo;g.get("/proxy/*",async y=>{let w=new URL(y.req.url),R=(w.pathname+w.search).slice(7),M=R.lastIndexOf("https://");return M===-1?y.text("Invalid proxy URL",400):I(y,R.slice(M))}),f&&Dh(g,`/local/${f.name}/`,f.serveDir),p&&Dh(g,p.mount,p.dir),b&&g.get("/assets/*",async y=>{let{pathname:w}=new URL(y.req.url),$=w.slice(8);for(let M of b.dirs){let W;try{W=Bn(decodeURIComponent($),M)}catch{return y.text("Not Found",404)}try{let K=await Ql.readFile(W);return new Response(K,{headers:{"Content-Type":fo(W),"Cache-Control":"no-cache"}})}catch{}}let R=b.getRemoteBase();return R?y.redirect(R+$,302):y.text("Not Found",404)});async function I(y,w){let $;try{$=new URL(w)}catch{return y.text("Invalid URL",400)}if($.protocol!=="https:")return y.text("HTTPS only",400);if(!N.includes($.hostname))return y.text("Host not allowed",403);let R=await C.get(w);if(R)return new Response(R.body,{status:200,headers:Xl(R.contentType,R.cacheControl)});try{let M=await fetch(w,{headers:{Accept:y.req.header("Accept")||"*/*"},redirect:"follow"});if(!M.ok)return y.text(`Upstream ${M.status}`,M.status);let W=M.headers.get("Content-Type")||void 0,K=M.headers.get("Cache-Control")||void 0;if(M.body){let[qe,z]=M.body.tee();return(async()=>{try{let V=await new Response(z).arrayBuffer();await C.set(w,{body:Buffer.from(V),contentType:W,cacheControl:K})}catch{}})(),new Response(qe,{status:M.status,headers:Xl(W,K)})}return new Response(null,{status:M.status,headers:Xl(W,K)})}catch(M){return y.text(`Proxy fetch failed: ${M instanceof Error?M.message:M}`,502)}}(i||o)&&g.get("/__reload",y=>jE(y,async w=>{let $=()=>{w.writeSSE({event:"reload",data:""})},R=M=>{w.writeSSE({event:"message",data:JSON.stringify(M)})};for(i?.on("reload",$),o?.on("message",R),w.onAbort(()=>{i?.removeListener("reload",$),o?.removeListener("message",R)});!w.aborted;)await w.sleep(3e4)})),g.notFound(async y=>{if(y.req.method!=="GET")return y.text("Not Found",404);let w=new URL(y.req.url);return Lh(w.pathname,w.search)?I(y,"https://esm.sh"+w.pathname+w.search):y.text("Not Found",404)});let E=BE({fetch:g.fetch,port:s,hostname:jh});return{port:s,close:()=>E.close()}}function Xl(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 Dh(r,e,t){r.get(`${e}*`,async n=>{let{pathname:s}=new URL(n.req.url);if(!s.startsWith(e))return n.text("Not Found",404);let i=decodeURIComponent(s.slice(e.length));try{let o=Bn(i,t),a=await Ql.readFile(o);return new Response(a,{headers:{"Content-Type":fo(o)}})}catch{return n.text("Not Found",404)}})}function fo(r){switch(Bh.extname(r).toLowerCase()){case".js":case".mjs":return"text/javascript";case".wasm":return"application/wasm";case".json":case".map":return"application/json";case".svg":return"image/svg+xml";case".png":return"image/png";case".jpg":case".jpeg":return"image/jpeg";case".gif":return"image/gif";case".webp":return"image/webp";case".avif":return"image/avif";case".ico":return"image/x-icon";case".mp3":return"audio/mpeg";case".wav":return"audio/wav";case".ogg":return"audio/ogg";case".m4a":return"audio/mp4";case".mp4":return"video/mp4";case".webm":return"video/webm";case".woff2":return"font/woff2";case".ttf":return"font/ttf";case".css":return"text/css";case".txt":return"text/plain; charset=utf-8";default:return"application/octet-stream"}}async function Zl(r){let e=await import("net");return new Promise(t=>{let n=e.createServer();n.listen(r,jh,()=>{let s=n.address(),i=typeof s=="object"&&s?s.port:r;n.close(()=>t(i))}),n.on("error",()=>{t(Zl(r+1))})})}var jh,FE,eu=v(()=>{xr();Ne();_h();Ih();Le();Ht();ji();$h();Gl();wl();Mh();jh="127.0.0.1",FE=new Set(["localhost","127.0.0.1","::1"])});import*as Oe from"fs/promises";import*as Xn from"path";import{createHash as KE}from"crypto";async function HE(r,e){let t=await ru(Pr(r));if(!t.length)return{kind:"none"};let n=await Oe.readFile(r,"utf-8"),s=Ur(ce(n)?.files.get("config.json"));if(!s)return{kind:"no-key",count:t.length};let i=(await Promise.all(t.map(async o=>{let a=s+tu(o);return await WE(a,e?.timeoutMs??1e4)?void 0:{rel:o,url:a}}))).filter(o=>o!==void 0);return i.length?{kind:"missing",missing:i,count:t.length,base:s}:{kind:"verified",count:t.length,base:s}}async function ru(r,e=""){let t=await Oe.readdir(r,{withFileTypes:!0}).catch(()=>[]),n=[];for(let s of t)s.isDirectory()?n.push(...await ru(Xn.join(r,s.name),`${e}${s.name}/`)):s.isFile()&&n.push(e+s.name);return n}async function WE(r,e){try{let t=await fetch(r,{method:"HEAD",signal:AbortSignal.timeout(e)});return t.ok?!0:t.status!==405&&t.status!==501?!1:(await fetch(r,{headers:{Range:"bytes=0-0"},signal:AbortSignal.timeout(e)})).ok}catch{return!1}}async function YE(r,e){let t=e.timeoutMs??3e4,n=qh(r),s={Authorization:`Bearer ${e.token}`},i=Pr(r.dest);if(!await Oe.stat(i).then(p=>p.isDirectory()).catch(()=>!1))return{kind:"skipped"};let o=await ru(i),a;try{let p=await fetch(n,{headers:s,signal:AbortSignal.timeout(t)});if(!p.ok)return{kind:"sync-error",message:`manifest request failed (${p.status}): ${zn(await p.text())}`};a=await p.json()}catch(p){return{kind:"sync-error",message:p instanceof Error?p.message:String(p)}}if(!o.length&&!a.length)return{kind:"skipped"};let c=new Map(a.map(p=>[p.path,p.md5])),l=new Set(o),f=a.map(p=>p.path).filter(p=>!l.has(p)),u=0,d=0;try{await GE(o,4,async p=>{let b=await Oe.readFile(Xn.join(i,...p.split("/")));if(c.get(p)===KE("md5").update(b).digest("hex")){d++;return}let m=await fetch(`${n}/${tu(p)}`,{method:"PUT",body:new Uint8Array(b),headers:{...s,"Content-Type":fo(p)},signal:AbortSignal.timeout(t)});if(!m.ok)throw new Error(`upload of '${p}' refused (${m.status}): ${zn(await m.text())}`);u++})}catch(p){return{kind:"sync-error",message:p instanceof Error?p.message:String(p)}}return{kind:"synced",uploaded:u,unchanged:d,toDelete:f,base:ra(r.userSlug,r.slug)}}async function VE(r,e,t){let n=t.timeoutMs??3e4,s=qh(r),i=[];for(let o of e)try{let a=await fetch(`${s}/${tu(o)}`,{method:"DELETE",headers:{Authorization:`Bearer ${t.token}`},signal:AbortSignal.timeout(n)});if(!a.ok)return{deleted:i,error:`delete of '${o}' refused (${a.status}): ${zn(await a.text())}`};i.push(o)}catch(a){return{deleted:i,error:a instanceof Error?a.message:String(a)}}return{deleted:i}}async function GE(r,e,t){let n=[...r],s=async()=>{for(let i=n.shift();i!==void 0;i=n.shift())await t(i)};await Promise.all(Array.from({length:Math.min(e,r.length)},s))}async function zE(r,e,t){let n=await HE(r.dest);if(n.kind==="missing"){console.error(`assets check against ${n.base}`);for(let s of n.missing)console.error(` MISSING ${s.rel} \u2192 expected at ${s.url}`);if(!t)return console.error(`push refused: ${n.missing.length} of ${n.count} asset(s) not on your host yet. Upload them, or push --force to publish anyway.`),{proceed:!1};console.error(" continuing (--force): the published bulb will 404 on these until they are uploaded.")}if(n.kind==="verified"&&console.log(`assets: verified ${n.count} file(s) against ${n.base}`),n.kind==="no-key"||n.kind==="none"){let s=await YE(r,{token:e});if(s.kind==="sync-error")return console.error(`assets sync failed: ${s.message}
|
|
1365
|
+
push refused: the bulb text was not pushed.`),{proceed:!1};if(s.kind==="synced")return console.log(`assets: ${s.uploaded} uploaded, ${s.unchanged} unchanged \u2192 ${s.base}`),{proceed:!0,toDelete:s.toDelete}}return{proceed:!0}}async function po(r,e){let t=await Oe.readFile(r.dest,"utf-8"),{mtime:n}=await Oe.stat(r.dest),s={Authorization:`Bearer ${e.token}`,"Content-Type":"text/markdown; charset=utf-8"};e.force||(s["If-Unmodified-Since"]=n.toUTCString());let i=await fetch(Wl(r),{method:"PUT",body:t,headers:s,signal:e.timeoutMs?AbortSignal.timeout(e.timeoutMs):void 0}),o=await i.text();if(i.status===409)return{kind:"conflict",message:zn(o)};if(!i.ok)return{kind:"http-error",status:i.status,message:zn(o)};let a=JSON.parse(o);return await Oe.utimes(r.dest,new Date,new Date(a.updatedAt)),{kind:"pushed",created:a.created,serverStripped:a.serverStripped,updatedAt:a.updatedAt}}function zn(r){try{return JSON.parse(r).error||r}catch{return r}}async function Uh(r,e){r||(console.error("Usage: typebulb push <typebulbs/u/<user>/<slug>.bulb.md>"),process.exit(1)),/^https?:\/\//i.test(r)&&(console.error("push takes a local .bulb.md file, not a URL (the path is its remote identity)"),process.exit(1));let t=Yl(r,e.mode),n=process.env.TYPEBULB_TOKEN;n||(console.error("push needs TYPEBULB_TOKEN in your .env \u2014 create one on your typebulb.com settings page."),process.exit(1));let s=`${t.origin}/u/${t.userSlug}/${t.slug}`,i=Xn.relative(process.cwd(),t.dest)||t.dest,o,a;try{let c=await zE(t,n,e.force);if(!c.proceed){process.exitCode=1;return}a=c.toDelete,o=await po(t,{token:n,force:e.force})}catch(c){let l=c instanceof Error?c.message:String(c);console.error(c?.code==="ENOENT"?`File not found: ${i}`:`Could not push to ${t.origin}: ${l}`),process.exitCode=1;return}switch(o.kind){case"pushed":{if(console.log(`pushed ${i} \u2192 ${s}${o.created?" (created, unlisted)":""}`),o.serverStripped&&console.log("note: the server.ts block was stripped on the server copy (CLI-only); your local file is untouched."),a?.length){let c=await VE(t,a,{token:n});for(let l of c.deleted)console.log(` deleted ${l} (no longer in assets/)`);c.error&&console.log(`note: asset cleanup incomplete \u2014 ${c.error}; the next push will retry.`)}return}case"conflict":console.error(`${o.message}
|
|
1366
|
+
pull to see the remote: typebulb pull ${i}
|
|
1367
|
+
or overwrite it: typebulb push ${i} --force`),process.exitCode=1;return;case"http-error":o.status===401?console.error("The server rejected TYPEBULB_TOKEN (401) \u2014 it may be revoked; mint a new one on the settings page."):console.error(`Push failed: ${t.origin} responded ${o.status}${o.message?` \u2014 ${o.message}`:""}`),process.exitCode=1}}var tu,qh,nu=v(()=>{Ne();Yn();wt();eu();tu=r=>r.split("/").map(encodeURIComponent).join("/");qh=r=>`${r.origin}/u/${encodeURIComponent(r.userSlug)}/${encodeURIComponent(r.slug)}/assets`});var $r=v(()=>{Le();vh();Sh();ql();kh();Eh();Un();Ht();Ht();ji();to();Yn();nu();kt()});import{copyFileSync as XE,existsSync as Jh,mkdirSync as Kh,rmSync as QE,writeFileSync as ZE}from"fs";import{homedir as eA}from"os";import*as Be from"path";import{fileURLToPath as tA}from"url";function aA(){return oA.replace('"__TB_DESCRIPTION_PATH__"',JSON.stringify(Ir())).replace('"__TB_README_PATH__"',JSON.stringify(Gt()))}function Hh(){try{if(!Jh(mo()))return}catch{return}try{let r=rA();Kh(Be.dirname(r),{recursive:!0}),ZE(r,aA()),QE(nA(),{force:!0})}catch{}try{let r=sA();if(!Jh(r))return;let e=iA();Kh(Be.dirname(e),{recursive:!0}),XE(r,e)}catch{}}var mo,rA,nA,sA,iA,oA,Wh=v(()=>{$r();mo=()=>Be.join(eA(),".pi","agent"),rA=()=>Be.join(mo(),"extensions","typebulb.ts"),nA=()=>Be.join(mo(),"extensions","typebulb-wait.ts"),sA=()=>Be.join(Be.dirname(tA(import.meta.url)),"agents","pi","matchu-patchu.ts"),iA=()=>Be.join(mo(),"extensions","matchu-patchu.ts"),oA=String.raw`// Generated by typebulb — do not edit; overwritten on each run.
|
|
1368
|
+
import { spawn } from "node:child_process";
|
|
1369
|
+
import { existsSync } from "node:fs";
|
|
1705
1370
|
|
|
1706
|
-
|
|
1707
|
-
var canceled = false;
|
|
1708
|
-
var aborter = null;
|
|
1709
|
-
var inferCfg = {};
|
|
1710
|
-
var dataTitles = function () {
|
|
1711
|
-
return String(inferCfg.dataTitle || '').split(',').map(function (s) { return s.trim(); }).filter(Boolean);
|
|
1712
|
-
};
|
|
1371
|
+
function logErr(...a) { try { console.error("[typebulb]", ...a); } catch (e) {} }
|
|
1713
1372
|
|
|
1714
|
-
|
|
1715
|
-
|
|
1716
|
-
if (aborter) { aborter.abort(); aborter = null; }
|
|
1717
|
-
host.remove();
|
|
1718
|
-
if (kind === 'cancel' && !completed) ctx.onCancel();
|
|
1719
|
-
}
|
|
1720
|
-
overlay.addEventListener('click', function (e) { if (e.target === overlay) close('cancel'); });
|
|
1373
|
+
// Matches "typebulb wait", "npx typebulb wait", "/path/to/typebulb wait", "pnpm exec typebulb wait", etc.
|
|
1374
|
+
function isWaitCommand(command) { return /\btypebulb\s+wait\b/.test(String(command || "")); }
|
|
1721
1375
|
|
|
1722
|
-
|
|
1723
|
-
|
|
1724
|
-
|
|
1725
|
-
|
|
1726
|
-
|
|
1727
|
-
|
|
1728
|
-
|
|
1376
|
+
// pi's bash tool runs every command under Git Bash on Windows (its getShellConfig), so the
|
|
1377
|
+
// intercepted string is POSIX. Re-running it under node's shell:true (cmd.exe on Windows) breaks
|
|
1378
|
+
// that syntax — cmd doesn't split on ";", so a trailing "; echo ..." rides along as extra ARGS to
|
|
1379
|
+
// typebulb wait, which resolves a garbage target and dies code 1 before the event (field: a wait
|
|
1380
|
+
// that resolved the target 'exit: $?'). Resolve bash the way pi does; null → shell:true (POSIX sh).
|
|
1381
|
+
function resolveBash() {
|
|
1382
|
+
try {
|
|
1383
|
+
if (process.platform !== "win32") return existsSync("/bin/bash") ? "/bin/bash" : null;
|
|
1384
|
+
var dirs = [process.env.ProgramFiles, process.env["ProgramFiles(x86)"]];
|
|
1385
|
+
for (var i = 0; i < dirs.length; i++) {
|
|
1386
|
+
if (dirs[i] && existsSync(dirs[i] + "\\Git\\bin\\bash.exe")) return dirs[i] + "\\Git\\bin\\bash.exe";
|
|
1387
|
+
}
|
|
1388
|
+
return "bash.exe"; // PATH fallback (Cygwin/MSYS2); a spawn miss lands in the "error" handler
|
|
1389
|
+
} catch (e) { return null; }
|
|
1390
|
+
}
|
|
1729
1391
|
|
|
1730
|
-
|
|
1731
|
-
|
|
1732
|
-
|
|
1733
|
-
|
|
1392
|
+
// Resolved at shim-write time to this install's absolute skill-part paths (same files
|
|
1393
|
+
// commands/agent.ts prints — readable without a permission prompt, unlike the npx command).
|
|
1394
|
+
var TB_DESCRIPTION_PATH = "__TB_DESCRIPTION_PATH__";
|
|
1395
|
+
var TB_README_PATH = "__TB_README_PATH__";
|
|
1734
1396
|
|
|
1735
|
-
|
|
1736
|
-
|
|
1737
|
-
|
|
1738
|
-
|
|
1397
|
+
// Orientation for a MIRROR-DRIVEN session (TYPEBULB_MIRROR=1 — set only by the mirror's composer
|
|
1398
|
+
// driver). A composer-driven agent never runs "typebulb agent", so the guaranteed-delivery block
|
|
1399
|
+
// that command prints (commands/agent.ts) never reaches it; this re-delivers it via the system
|
|
1400
|
+
// prompt. The wording below is copied from agent.ts, hard-won across many failed interactions —
|
|
1401
|
+
// only the mirror-link lines differ (the user is already IN the mirror). Change it there first.
|
|
1402
|
+
var TB_MIRROR_BLOCK = [
|
|
1403
|
+
"Typebulb: the user is prompting you from the typebulb agent mirror (already open in front of them).",
|
|
1404
|
+
" Embedded bulbs render live in this conversation.",
|
|
1405
|
+
" • do not run npx typebulb agent — the mirror is already running",
|
|
1406
|
+
" • no need to end your reply with a mirror link",
|
|
1407
|
+
" Reusable app/tool → write a .bulb.md",
|
|
1408
|
+
" Show something inline → embed a bulb",
|
|
1409
|
+
" arm a wait for its render verdict — run it plainly:",
|
|
1410
|
+
' • typebulb wait agent --match "[embed <name>"',
|
|
1411
|
+
" Read the authoring skill before writing a bulb:",
|
|
1412
|
+
" • npx typebulb skill — assembles one SKILL.md",
|
|
1413
|
+
" • or, open its parts:",
|
|
1414
|
+
" " + TB_DESCRIPTION_PATH,
|
|
1415
|
+
" " + TB_README_PATH,
|
|
1416
|
+
].join("\n");
|
|
1739
1417
|
|
|
1740
|
-
|
|
1741
|
-
|
|
1742
|
-
|
|
1743
|
-
var cancel = el('button', '', 'Cancel');
|
|
1744
|
-
cancel.addEventListener('click', function () { close('cancel'); });
|
|
1745
|
-
foot.appendChild(cancel);
|
|
1418
|
+
export default function (pi) {
|
|
1419
|
+
try {
|
|
1420
|
+
const pending = new Set();
|
|
1746
1421
|
|
|
1747
|
-
|
|
1748
|
-
|
|
1749
|
-
|
|
1750
|
-
|
|
1751
|
-
|
|
1752
|
-
|
|
1753
|
-
}
|
|
1422
|
+
pi.on("before_agent_start", (event) => {
|
|
1423
|
+
try {
|
|
1424
|
+
if (process.env.TYPEBULB_MIRROR !== "1") return undefined;
|
|
1425
|
+
return { systemPrompt: event.systemPrompt + "\n\n" + TB_MIRROR_BLOCK };
|
|
1426
|
+
} catch (e) { logErr("before_agent_start", e && e.message); return undefined; }
|
|
1427
|
+
});
|
|
1754
1428
|
|
|
1755
|
-
|
|
1756
|
-
|
|
1757
|
-
|
|
1758
|
-
|
|
1429
|
+
pi.on("tool_call", (event, ctx) => {
|
|
1430
|
+
try {
|
|
1431
|
+
if (!event || event.toolName !== "bash") return undefined;
|
|
1432
|
+
const command = event.input && event.input.command;
|
|
1433
|
+
if (!isWaitCommand(command)) return undefined;
|
|
1759
1434
|
|
|
1760
|
-
|
|
1761
|
-
|
|
1762
|
-
|
|
1763
|
-
|
|
1764
|
-
|
|
1435
|
+
// Run the REAL typebulb wait in the background instead of foreground (which would deadlock the
|
|
1436
|
+
// turn). It does the mirror/registry lookup, --match and offsets itself. The marker tells it this
|
|
1437
|
+
// is a shim-backgrounded (non-blocking) wait, so it runs as a pure subscription: no give-up clock,
|
|
1438
|
+
// it waits for the event however long (bounded by the session-shutdown reap below) — an embed's
|
|
1439
|
+
// first paint OR a running bulb's next event line alike.
|
|
1440
|
+
// The agent may self-background ("… &") — the generic-shell reading of "arm it in the
|
|
1441
|
+
// background", but here the SHIM is the backgrounder: bash would exit 0 instantly with empty
|
|
1442
|
+
// output, firing the wake before the event while the detached wait delivers to nobody
|
|
1443
|
+
// (field: Toroidal Life, '> /tmp/x.log 2>&1 &'). Strip a trailing "&" so the wait runs
|
|
1444
|
+
// foreground inside the shim's already-backgrounded child.
|
|
1445
|
+
const cmd = String(command).replace(/(?<!&)\s*&\s*$/, "");
|
|
1446
|
+
const bash = resolveBash();
|
|
1447
|
+
const opts = {
|
|
1448
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
1449
|
+
env: { ...process.env, TYPEBULB_WAIT_SHIM: "1" },
|
|
1450
|
+
};
|
|
1451
|
+
const child = bash ? spawn(bash, ["-c", cmd], opts) : spawn(cmd, { ...opts, shell: true });
|
|
1452
|
+
pending.add(child);
|
|
1453
|
+
let out = "";
|
|
1454
|
+
let errOut = "";
|
|
1455
|
+
if (child.stdout) child.stdout.on("data", (b) => { out += b.toString(); });
|
|
1456
|
+
if (child.stderr) child.stderr.on("data", (b) => { errOut += b.toString(); });
|
|
1457
|
+
child.on("error", (e) => {
|
|
1458
|
+
pending.delete(child);
|
|
1459
|
+
logErr("spawn", e && e.message);
|
|
1460
|
+
// Same class as a failure exit: the subscription never armed, so silence is a deadlock.
|
|
1461
|
+
try { pi.sendUserMessage("typebulb wait FAILED to spawn: " + (e && e.message) + "\nNothing is watching — fix and re-arm the wait.", { deliverAs: "followUp" }); } catch (e2) {}
|
|
1462
|
+
});
|
|
1463
|
+
child.on("exit", (code) => {
|
|
1464
|
+
pending.delete(child);
|
|
1465
|
+
try {
|
|
1466
|
+
const text = out.trim();
|
|
1467
|
+
// Exit 0 with output is a real outcome (embed ok/error, a turn-based move) -> wake the
|
|
1468
|
+
// agent (followUp delivers immediately when idle and queues when streaming — the same call
|
|
1469
|
+
// git-merge-and-resolve.ts makes from agent_end). A late wake is fine; it just reports
|
|
1470
|
+
// something true. Exit 2/3 (no render yet / server gone) surface passively, no turn.
|
|
1471
|
+
// Any OTHER non-zero exit means the subscription itself broke (bad args, no resolvable
|
|
1472
|
+
// mirror): the agent parked on a wake that can never come, so that failure must wake too —
|
|
1473
|
+
// missed wakes are fatal, spurious wakes cheap (TB-Wait.md). null (reap-killed) stays silent.
|
|
1474
|
+
// EXCEPT an embed's clean ok verdict ("[embed <name> vN] ok" — core/client/bulbEmbed.ts):
|
|
1475
|
+
// the user already sees the bulb and the skill orders silence on ok, so a wake would spend
|
|
1476
|
+
// a whole turn saying nothing and render a noise message. Silence IS the ok. Anything else
|
|
1477
|
+
// (an embed error, a turn-based loop event) still wakes; an unrecognized shape wakes too.
|
|
1478
|
+
// Checked PER LINE, not over the whole blob: wait lingers 10s and bursts every matching line
|
|
1479
|
+
// into one payload, and a version-agnostic --match ("[embed <name>") replays v1+v2+... from
|
|
1480
|
+
// log start, so an all-ok payload is routinely multi-line. Suppress iff EVERY line is an ok;
|
|
1481
|
+
// one error line among oks still wakes.
|
|
1482
|
+
var waitLines = text.split("\n").map(function (l) { return l.trim(); }).filter(Boolean);
|
|
1483
|
+
const embedOk = code === 0 && waitLines.length > 0 && waitLines.every(function (l) { return /^\[embed .*\] ok$/.test(l); });
|
|
1484
|
+
if (code === 0 && text && !embedOk) {
|
|
1485
|
+
pi.sendUserMessage("typebulb wait result:\n" + text, { deliverAs: "followUp" });
|
|
1486
|
+
} else if (code === 0 && !text) {
|
|
1487
|
+
// A successful wait always prints its matched line(s), so exit 0 with nothing captured
|
|
1488
|
+
// means the agent redirected stdout (e.g. '> /tmp/x.log 2>&1') — the verdict landed in a
|
|
1489
|
+
// file nobody reads. The line is still in the mirror's log; point the agent there.
|
|
1490
|
+
pi.sendUserMessage("typebulb wait ended (exit 0) but its output was redirected away — read the verdict with: typebulb logs agent\nNext time run the wait plainly: no output redirect, no trailing &.", { deliverAs: "followUp" });
|
|
1491
|
+
} else if (code !== null && code !== 0 && code !== 2 && code !== 3) {
|
|
1492
|
+
var diag = (text + "\n" + errOut.trim()).trim();
|
|
1493
|
+
pi.sendUserMessage("typebulb wait FAILED (exit " + code + ")" + (diag ? ":\n" + diag : " with no output.") + "\nThe wait never armed — nothing is watching. Fix the command and re-arm it.", { deliverAs: "followUp" });
|
|
1494
|
+
} else if (ctx.ui && typeof ctx.ui.notify === "function") {
|
|
1495
|
+
// INVARIANT: this notify must never quote the "[embed <name>" tag verbatim. In a
|
|
1496
|
+
// composer-driven session the mirror's driver echoes extension notifies into the
|
|
1497
|
+
// mirror's own log (driver.ts) — the very log wait watches by substring — so a
|
|
1498
|
+
// verbatim tag re-fires the next same-match wait with a non-ok line: a self-
|
|
1499
|
+
// sustaining wake loop that defeats this suppression (TB-Wait.md). Stripping the
|
|
1500
|
+
// brackets kills the matchable substring while keeping the verdict readable.
|
|
1501
|
+
ctx.ui.notify("typebulb wait: " + (embedOk ? text.replace(/[\[\]]/g, "") : code === 2 ? "timed out, nothing to report" : "ended (code " + code + ")"), "info");
|
|
1502
|
+
}
|
|
1503
|
+
} catch (e) { logErr("exit", e && e.message); }
|
|
1504
|
+
});
|
|
1765
1505
|
|
|
1766
|
-
|
|
1767
|
-
|
|
1768
|
-
|
|
1769
|
-
|
|
1770
|
-
|
|
1771
|
-
var tabBtns = [];
|
|
1772
|
-
var counts = [];
|
|
1773
|
-
var strip = multi ? el('div', 'tabs') : null;
|
|
1774
|
-
if (strip) body.appendChild(strip);
|
|
1775
|
-
function formatCount(n) { return n < 10000 ? String(n) : Math.round(n / 1000) + 'K'; }
|
|
1776
|
-
function selectTab(i) {
|
|
1777
|
-
tabBtns.forEach(function (b, j) { b.className = j === i ? 'tab on' : 'tab'; });
|
|
1778
|
-
areas.forEach(function (a, j) { a.style.display = j === i ? '' : 'none'; });
|
|
1779
|
-
}
|
|
1780
|
-
chunks.forEach(function (chunk, i) {
|
|
1781
|
-
if (multi) {
|
|
1782
|
-
var tab = el('button', 'tab');
|
|
1783
|
-
tab.appendChild(el('span', '', chunkLabel(chunk, i, titles)));
|
|
1784
|
-
var cnt = el('span', 'cnt', '(' + formatCount(chunk.length) + ')');
|
|
1785
|
-
counts.push(cnt);
|
|
1786
|
-
tab.appendChild(cnt);
|
|
1787
|
-
tab.addEventListener('click', function () { selectTab(i); });
|
|
1788
|
-
tabBtns.push(tab);
|
|
1789
|
-
strip.appendChild(tab);
|
|
1790
|
-
} else {
|
|
1791
|
-
body.appendChild(el('label', '', titles[0] || 'Data to process'));
|
|
1792
|
-
}
|
|
1793
|
-
var ta = document.createElement('textarea');
|
|
1794
|
-
ta.value = chunk;
|
|
1795
|
-
if (!chunk) ta.placeholder = 'Paste data to process (optional)\\u2026';
|
|
1796
|
-
ta.addEventListener('input', function () {
|
|
1797
|
-
// 2 blank lines IS the chunk separator \u2014 collapse pasted 3+ so text can't silently split (.com parity)
|
|
1798
|
-
var v = ta.value.replace(/\\n{3,}/g, '\\n\\n');
|
|
1799
|
-
if (v !== ta.value) ta.value = v;
|
|
1800
|
-
if (multi) counts[i].textContent = '(' + formatCount(ta.value.length) + ')';
|
|
1801
|
-
});
|
|
1802
|
-
areas.push(ta);
|
|
1803
|
-
body.appendChild(ta);
|
|
1506
|
+
return {
|
|
1507
|
+
block: true,
|
|
1508
|
+
reason: "Armed in the background. You will be re-invoked automatically with the result when it is ready - do not run this command again; end your turn now and wait for the result.",
|
|
1509
|
+
};
|
|
1510
|
+
} catch (e) { logErr("tool_call", e && e.message); return undefined; }
|
|
1804
1511
|
});
|
|
1805
|
-
if (multi) selectTab(0);
|
|
1806
|
-
// The model line reads as a footnote to the action, not a header to the data \u2014 under the
|
|
1807
|
-
// textareas, above the buttons.
|
|
1808
|
-
body.appendChild(model);
|
|
1809
1512
|
|
|
1810
|
-
|
|
1811
|
-
|
|
1812
|
-
|
|
1813
|
-
|
|
1814
|
-
|
|
1815
|
-
|
|
1816
|
-
|
|
1817
|
-
|
|
1818
|
-
|
|
1819
|
-
|
|
1820
|
-
|
|
1821
|
-
|
|
1822
|
-
|
|
1823
|
-
|
|
1824
|
-
|
|
1825
|
-
|
|
1826
|
-
|
|
1827
|
-
|
|
1828
|
-
|
|
1829
|
-
|
|
1830
|
-
|
|
1831
|
-
|
|
1832
|
-
|
|
1833
|
-
|
|
1834
|
-
|
|
1835
|
-
|
|
1836
|
-
|
|
1837
|
-
|
|
1838
|
-
|
|
1839
|
-
|
|
1840
|
-
});
|
|
1841
|
-
});
|
|
1842
|
-
grp.appendChild(save);
|
|
1843
|
-
foot.appendChild(grp);
|
|
1844
|
-
}
|
|
1513
|
+
try { pi.on("session_shutdown", () => { for (const c of pending) { try { c.kill(); } catch (e) {} } pending.clear(); }); } catch (e) {}
|
|
1514
|
+
} catch (e) { logErr("load", e && e.message); }
|
|
1515
|
+
}
|
|
1516
|
+
`});function J(r){return r?.message??String(r)}var Y,xt=v(()=>{Y=process.cwd()});import{spawn as Yh}from"child_process";import{StringDecoder as cA}from"string_decoder";function gA(r,e){let t=new cA("utf8"),n="";r.on("data",s=>{n+=typeof s=="string"?s:t.write(s);let i;for(;(i=n.indexOf(`
|
|
1517
|
+
`))>=0;){let o=n.slice(0,i);n=n.slice(i+1),o.endsWith("\r")&&(o=o.slice(0,-1)),o&&e(o)}})}var lA,uA,Vh,dA,fA,pA,mA,hA,ho,go,Gh,zh=v(()=>{xt();lA=3e4,uA=5e3,Vh=2e3,dA=2e3,fA=12e4,pA=8e3,mA=15e3,hA=new Set(["get_state","get_commands","get_available_models","set_model","set_thinking_level","cycle_thinking_level","get_session_stats","compact","set_auto_compaction","get_fork_messages","fork","clone","set_session_name","export_html","bash","abort_bash"]),ho=new Set;process.on("exit",()=>{for(let r of ho)try{r.kill()}catch{}});go=class{#e;#a=!1;#c=0;#i=!1;#l=null;#m=null;#t=null;#n=null;#u=new Map;#r=[];#h=null;#w=null;#g=null;#d;#f;#y="";#A=1;#s=new Map;#v;#b;constructor(e,t,n=(s,i)=>Yh(s,{cwd:i,shell:!0,stdio:["pipe","pipe","pipe"],env:{...process.env,TYPEBULB_MIRROR:"1"}})){if(this.#v=new Promise(o=>{this.#b=o}),t?.includes('"')){this.#f="session path contains a quote \u2014 cannot drive it",this.#b();return}let s=t?`pi --mode rpc --session "${t}"`:"pi --mode rpc",i;try{i=n(s,e)}catch(o){this.#f=`could not start pi: ${J(o)}`,this.#b();return}this.#e=i,this.#d=t,ho.add(i),i.stdout&&gA(i.stdout,o=>this.#T(o)),i.stderr&&i.stderr.on("data",o=>{this.#y=(this.#y+o.toString()).slice(-dA)}),i.on("error",o=>this.#x(`could not start pi: ${o.message}`)),i.on("exit",o=>{this.#e===i&&this.#x(o?`pi exited (code ${o})${this.#y.trim()?`: ${this.#y.trim()}`:""}`:"pi exited"),ho.delete(i),this.#b()}),this.#o({type:"get_state"}).then(o=>{let a=o.data?.sessionFile;typeof a=="string"&&a&&(this.#d=a);let c=o.data?.model;c&&typeof c.id=="string"&&c.id&&(this.#g=c.id)}).catch(()=>{}),this.#S()}get streaming(){return this.#a||Date.now()<this.#c}get draft(){return this.#l}get echo(){return this.#m}get queue(){return this.#h}get stats(){return this.#w}get model(){return this.#g}get sessionFile(){return this.#d}get error(){return this.#f}get status(){if(this.#t)return this.#t;if(this.#n){if(Date.now()<this.#n.until)return{text:this.#n.text,kind:this.#n.kind};this.#n=null}return this.#u.size?{text:[...this.#u.values()].join(" \xB7 "),kind:"info"}:null}get dialog(){let e=Date.now();for(;this.#r.length;){let t=this.#r[0];if(e<t.until)return t.req;this.#r.shift(),t.ownTimeout||this.#k({type:"extension_ui_response",id:t.req.id,cancelled:!0})}return null}notice(e,t){this.#p(e,t)}respondUi(e,t){let n=this.#r.findIndex(o=>o.req.id===e);if(n<0)return{ok:!1,error:"dialog expired or already answered"};let[s]=this.#r.splice(n,1),i={type:"extension_ui_response",id:e};return t.cancelled?i.cancelled=!0:s.req.method==="confirm"?i.confirmed=!!t.confirmed:i.value=t.value??"",this.#k(i),{ok:!0}}async rpc(e){if(!hA.has(e.type))return{ok:!1,error:`command not allowed: ${e.type}`};try{let t=await this.#o(e);if(t.success&&e.type==="set_model"){let n=t.data?.id;typeof n=="string"&&n&&(this.#g=n)}if(t.success&&(e.type==="fork"||e.type==="clone")){try{let s=(await this.#o({type:"get_state"})).data?.sessionFile;typeof s=="string"&&s&&(this.#d=s)}catch{}return{ok:!0,data:{...t.data??{},sessionFile:this.#d}}}return t.success?{ok:!0,data:t.data}:{ok:!1,error:t.error??`pi rejected ${e.type}`}}catch(t){return{ok:!1,error:J(t)}}}async send(e,t){let n=this.streaming,s=n?e.trimStart().startsWith("/")?{type:"prompt",message:e,streamingBehavior:t?.followUp?"followUp":"steer"}:{type:t?.followUp?"follow_up":"steer",message:e}:{type:"prompt",message:e},i;try{i=await this.#o(s)}catch(o){return{ok:!1,error:J(o)}}return i.success&&!n&&(this.#c=Date.now()+uA),i.success&&!n&&!e.trimStart().startsWith("/")&&(this.#m=e),i.success?{ok:!0}:{ok:!1,error:i.error??"pi rejected the message"}}async stop(){if(this.#e)try{await this.#o({type:"abort"})}catch{}}clearCompletedDraft(){this.#i||(this.#l=null)}clearEcho(){this.#m=null}async dispose(){let e=this.#e;if(e){if(this.#e=void 0,this.#a){try{e.stdin?.write(JSON.stringify({type:"abort"})+`
|
|
1518
|
+
`)}catch{}await Promise.race([this.#v,Gh(Vh)])}try{e.stdin?.end()}catch{}if(await Promise.race([this.#v,Gh(Vh)]),e.exitCode===null&&!e.killed)if(process.platform==="win32"&&e.pid)try{Yh("taskkill",["/pid",String(e.pid),"/T","/F"],{stdio:"ignore"})}catch{}else try{e.kill("SIGKILL")}catch{}ho.delete(e),this.#r=[],this.#E("pi was shut down")}}#k(e){try{this.#e?.stdin?.write(JSON.stringify(e)+`
|
|
1519
|
+
`)}catch{}}#p(e,t){let n=e.length>200?e.slice(0,200)+"\u2026":e;n&&(this.#n={text:n,kind:t,until:Date.now()+(t==="info"?pA:mA)})}#S(){this.#o({type:"get_session_stats"}).then(e=>{if(!e.success||!e.data)return;let t=e.data;this.#w={cost:typeof t.cost=="number"?t.cost:0,contextTokens:typeof t.contextUsage?.tokens=="number"?t.contextUsage.tokens:null,contextPercent:typeof t.contextUsage?.percent=="number"?t.contextUsage.percent:null}}).catch(()=>{})}#o(e){let t=this.#e;if(!t?.stdin?.writable)return Promise.reject(new Error(this.#f??"pi is not running"));let n=`tb-${this.#A++}`;return new Promise((s,i)=>{let o=setTimeout(()=>{this.#s.delete(n),i(new Error("pi did not respond (30s)"))},lA);o.unref?.(),this.#s.set(n,{resolve:s,timer:o});try{t.stdin.write(JSON.stringify({id:n,...e})+`
|
|
1520
|
+
`)}catch(a){clearTimeout(o),this.#s.delete(n),i(new Error(J(a)))}})}#T(e){let t;try{t=JSON.parse(e)}catch{return}switch(t.type){case"response":{let n=t,s=n.id?this.#s.get(n.id):void 0;s&&(this.#s.delete(n.id),clearTimeout(s.timer),s.resolve(n));return}case"agent_start":this.#a=!0,this.#c=0;return;case"agent_end":this.#a=!1,this.#c=0,this.#i=!1,this.#t=null,this.#h=null,this.#S();return;case"message_start":{t.message?.role==="assistant"&&(this.#i=!0,this.#l={text:"",thinking:""});return}case"message_update":{if(!this.#i)return;let n=t.message,s=Array.isArray(n?.content)?n.content:[],i=s[s.length-1];this.#l={text:s.filter(o=>o?.type==="text").map(o=>o.text??"").join(""),thinking:s.filter(o=>o?.type==="thinking").map(o=>o.thinking??"").join(`
|
|
1521
|
+
`),tool:i?.type==="toolCall"?i.name:void 0};return}case"message_end":this.#i=!1;return;case"auto_retry_start":this.#t={text:`retrying after a transient error (attempt ${Number(t.attempt)||1}/${Number(t.maxAttempts)||"?"})\u2026`,kind:"warning"};return;case"auto_retry_end":this.#t=null,t.success===!1&&this.#p(`retries exhausted: ${String(t.finalError??"unknown error")}`,"error");return;case"compaction_start":this.#t={text:"compacting context\u2026",kind:"info"};return;case"compaction_end":{this.#t=null;let n=t.result;typeof t.errorMessage=="string"&&t.errorMessage?this.#p(`compaction failed: ${t.errorMessage}`,"error"):n?.tokensBefore&&this.#p(`compacted: ~${Math.round(n.tokensBefore/1e3)}k \u2192 ~${Math.round((n.estimatedTokensAfter??0)/1e3)}k tokens`,"info"),this.#S();return}case"queue_update":{let n=Array.isArray(t.steering)?t.steering.map(String):[],s=Array.isArray(t.followUp)?t.followUp.map(String):[];this.#h=n.length||s.length?{steering:n,followUp:s}:null;return}case"extension_ui_request":{let n=String(t.method??"");if(n==="select"||n==="confirm"||n==="input"||n==="editor"){let s=typeof t.timeout=="number"&&t.timeout>0?t.timeout:void 0;this.#r.push({req:{id:String(t.id??""),method:n,title:typeof t.title=="string"?t.title:void 0,message:typeof t.message=="string"?t.message:void 0,options:Array.isArray(t.options)?t.options.map(String):void 0,placeholder:typeof t.placeholder=="string"?t.placeholder:void 0,prefill:typeof t.prefill=="string"?t.prefill:void 0},until:Date.now()+(s??fA),ownTimeout:s!==void 0})}else if(n==="notify"){let s=t.notifyType==="warning"?"warning":t.notifyType==="error"?"error":"info";this.#p(String(t.message??""),s),console.log(`[composer] pi extension: ${String(t.message??"")}`)}else if(n==="setStatus"){let s=String(t.statusKey??"");typeof t.statusText=="string"&&t.statusText?this.#u.set(s,t.statusText):this.#u.delete(s)}return}default:return}}#x(e){this.#f=e,this.#a=!1,this.#c=0,this.#i=!1,this.#l=null,this.#m=null,this.#t=null,this.#n=null,this.#u.clear(),this.#r=[],this.#h=null,this.#w=null,this.#g=null,this.#e=void 0,this.#E(e)}#E(e){for(let[,t]of this.#s)clearTimeout(t.timer),t.resolve({type:"response",success:!1,error:e});this.#s.clear()}},Gh=r=>new Promise(e=>{setTimeout(e,r).unref?.()})});import{existsSync as Xh,readFileSync as yA,realpathSync as bA}from"fs";import{join as zt,dirname as tg,resolve as wA}from"path";import{homedir as Qh}from"os";function SA(r,e){let t=zt(r,".pi");if(vA.some(s=>Xh(zt(t,s))))return!0;let n=zt(e,".agents","skills");for(let s=r;;){let i=zt(s,".agents","skills");if(i!==n&&Xh(i))return!0;let o=tg(s);if(o===s)return!1;s=o}}function kA(r,e){for(let t=e;;){if(r[t]===!0||r[t]===!1)return!0;let n=tg(t);if(n===t)return!1;t=n}}function rg(r,e){try{let t=e?.agentDir??zt(Qh(),".pi","agent"),n=Zh(e?.home??process.env.HOME??Qh()),s=Zh(wA(r));if(!SA(s,n))return null;let i=eg(zt(t,"settings.json")).defaultProjectTrust;return i==="always"||i==="never"||kA(eg(zt(t,"trust.json")),s)?null:"pi has no trust decision for this project \u2014 running untrusted; run `pi` once in a terminal to grant it"}catch{return null}}var vA,Zh,eg,ng=v(()=>{vA=["settings.json","extensions","skills","prompts","themes","SYSTEM.md","APPEND_SYSTEM.md"],Zh=r=>{try{return bA(r)}catch{return r}},eg=r=>{try{return JSON.parse(yA(r,"utf8"))}catch{return{}}}});import{statSync as xA,openSync as EA,readSync as AA,closeSync as TA,existsSync as ig}from"fs";import{join as yo}from"path";import{homedir as su}from"os";import{execFile as PA}from"child_process";async function CA(r){let e=yo(su(),".pi","agent","bin",process.platform==="win32"?"fd.exe":"fd");for(let t of["fd","fdfind",...ig(e)?[e]:[]]){let n=await new Promise(s=>{PA(t,["--base-directory",r,"--type","f","--follow","--hidden","--exclude",".git"],{maxBuffer:67108864},(i,o)=>s(i?null:o))});if(n!==null)return n.split(`
|
|
1522
|
+
`).filter(Boolean).map(s=>s.replace(/\\/g,"/"))}return null}function RA(r){return`--${r.replace(/^[/\\]/,"").replace(/[/\\:]/g,"-")}--`}function sg(r){return r.type==="message"?_A(r.message?.role):r.type==="custom_message"?r.display!==!1:!1}var OA,_A,Lr,iu=v(()=>{Ki();Al();Tl();Wh();zh();ng();OA=yo(su(),".pi","agent","sessions");_A=r=>r==="user"||r==="assistant"||r==="toolResult"||r==="bashExecution";Lr=class extends Cr{displayName="Pi Mirror";detectsSelf(){return process.env.PI_CODING_AGENT==="true"}detectsInstalled(){return ig(yo(su(),".pi","agent"))}ensureHarnessSupport(){Hh()}createDriver(e,t){let n=new go(e,t),s=rg(e);return s&&n.notice(s,"warning"),n}walkFiles(e){return CA(e)}sessionsDir(e){return yo(OA,RA(e))}listSessionFiles(e){return Hi(this.sessionsDir(e))}parseEntry(e){let t;try{t=JSON.parse(e)}catch{return null}return!t||t.type==="session"||!t.id?null:t}idOf(e){return e.id}parentOf(e){return e.parentId??void 0}timestampOf(e){return e.timestamp}isSidechain(e){return!1}isLeafType(e){return sg(e)}isRecoveryNoise(e){return!1}apply(e,t){let n=[];if(e.type==="custom_message"){if(e.display===!1)return{events:n};let i=this.contentText(e.content).trim();return i&&n.push({type:"user",text:i}),{events:n}}if(e.type!=="message"||!e.message)return{events:n};let s=e.message;if(s.role==="user"){let i=this.contentText(s.content).trim();return i&&n.push({type:"user",text:i}),{events:n}}if(s.role==="toolResult"){let i=this.contentText(s.content);return n.push({type:"tool_result",id:s.toolCallId??"",content:i,isError:!!s.isError,digest:Qe(i)}),{events:n}}if(s.role==="bashExecution")return s.command&&!s.excludeFromContext&&n.push({type:"user",text:`$ ${s.command}`}),{events:n};if(s.role==="assistant"){let i=Array.isArray(s.content)?s.content:[],o=i.filter(d=>d.type==="text").map(d=>d.text??"").join(""),a=i.filter(d=>d.type==="thinking").map(d=>d.thinking??"").join(`
|
|
1523
|
+
`),c=i.filter(d=>d.type==="toolCall").map(d=>({id:d.id??"",name:d.name??"",input:d.arguments??{}}));if(o||a||c.length){let d=Date.parse(e.timestamp??""),p=!isNaN(d)&&d>=t;n.push({type:"assistant",text:o,thinking:a,tools:c,live:p})}let l=s.usage,f=l?(l.input??0)+(l.output??0)+(l.cacheRead??0)+(l.cacheWrite??0):0,u=l&&f>0&&s.stopReason!=="aborted"&&s.stopReason!=="error"?{in:l.input??0,out:l.output??0,cached:l.cacheRead??0,cacheCreate:l.cacheWrite??0}:void 0;return{events:n,usage:u,model:s.model,cost:l?.cost?.total}}return{events:n}}chainWorking(e){let t;for(let a of e)sg(a)&&(t=a);if(!t||t.type==="custom_message")return!1;let n=t.message.role;if(n==="user"||n==="toolResult"||n==="bashExecution")return!0;if(n!=="assistant")return!1;let i=(Array.isArray(t.message.content)?t.message.content:[]).filter(a=>a.type==="toolCall").map(a=>a.id);if(!i.length)return!1;let o=new Set;for(let a of e)a.type==="message"&&a.message?.role==="toolResult"&&a.message.toolCallId&&o.add(a.message.toolCallId);return i.some(a=>a&&!o.has(a))}sessionAlive(){}readPreview(e){let t;try{t=EA(e,"r")}catch{return""}try{let s=65536;try{s=xA(e).size}catch{}let i=(u,d)=>{let p=Buffer.alloc(d),b=AA(t,p,0,d,u);return p.subarray(0,b).toString("utf8")},o=i(0,Math.min(65536,s)),a=s>65536?i(s-65536,65536):"",c=u=>{let d="";for(let p of u.split(`
|
|
1524
|
+
`))if(p.includes('"session_info"'))try{let b=JSON.parse(p);b?.type==="session_info"&&typeof b.name=="string"&&b.name&&(d=b.name)}catch{}return d},l="";for(let u of o.split(`
|
|
1525
|
+
`))if(!(l||!u.includes('"type"')))try{let d=JSON.parse(u);d?.type==="message"&&d.message?.role==="user"&&(l=this.contentText(d.message.content).replace(/\s+/g," ").trim())}catch{}let f=c(a)||c(o)||l;return f?f.slice(0,200):""}finally{TA(t)}}searchText(e){if(e?.type!=="message")return"";let t=e.message?.role;if(t!=="user"&&t!=="assistant")return"";let n=e.message?.content,s="";return typeof n=="string"?s=n:Array.isArray(n)&&(s=n.filter(i=>i.type==="text"&&typeof i.text=="string").map(i=>i.text).join(" ")),s.replace(/\s+/g," ").trim()}contentText(e){return typeof e=="string"?Ie(e):Array.isArray(e)?e.map(t=>typeof t?.text=="string"?Ie(t.text):t?.type==="image"&&t.data?Ji(t.data,t.mimeType):"").filter(Boolean).join(`
|
|
1526
|
+
`):""}}});var bo,og=v(()=>{bo=class{#e=new Map;accept(e,t){return this.#e.get(e)===t?!1:(this.#e.set(e,t),!0)}}});import{execFile as NA}from"child_process";import{promisify as IA}from"util";import{readFile as $A}from"fs/promises";import{resolve as ag,sep as LA}from"path";async function je(r,e){let{stdout:t}=await MA("git",r,{cwd:e,maxBuffer:67108864});return t}async function Mr(){if(wo)return wo;try{wo=(await je(["rev-parse","--show-toplevel"],Y)).trim()}catch{}return wo}function DA(r,e){let t=e===" "?r:e;return t==="?"?"U":t}async function lg(){let r=await Mr();if(!r)return{repo:!1,root:"",files:[]};try{let e=await je(["status","--porcelain","-z"],r),t=[],n=e.split("\0");for(let s=0;s<n.length;s++){let i=n[s];i.length<4||((i[0]==="R"||i[0]==="C")&&s++,t.push({path:i.slice(3),status:DA(i[0],i[1])}))}try{let s=await je(["diff","--numstat","HEAD"],r),i=new Map;for(let o of s.split(`
|
|
1527
|
+
`)){let a=/^(\d+)\t(\d+)\t(.+)$/.exec(o);a&&i.set(a[3],{add:+a[1],del:+a[2]})}for(let o of t){let a=i.get(o.path);a&&(o.add=a.add,o.del=a.del)}}catch{}return t.sort((s,i)=>s.path.localeCompare(i.path)),{repo:!0,root:r,files:t}}catch(e){return{repo:!1,root:"",files:[],error:J(e)}}}async function ug(r){let e=await Mr();if(!e)return{ok:!1,error:"not a git repository"};try{if((await je(["status","--porcelain","-z","--",r],e)).startsWith("??")){let s=ag(e,r);if(!s.startsWith(ag(e)+LA))return{ok:!1,error:"outside repository"};let i=await $A(s);return i.includes(0)?ou("Binary file (not shown)",!1):ou(i.toString("utf8"),!0)}let n;try{n=await je(["diff","--no-color","--unified=999999","HEAD","--",r],e)}catch{n=await je(["diff","--no-color","--unified=999999","--",r],e)}return ou(n,!1)}catch(t){return{ok:!1,error:J(t)}}}var MA,cg,wo,ou,vo=v(()=>{xt();MA=IA(NA),cg=2e6;ou=(r,e)=>({ok:!0,text:r.slice(0,cg),untracked:e,truncated:r.length>cg})});function So(r,e){let t=0,n="";for(let s of r){let i=s.lower.indexOf(e);if(!(i<0)&&(t++,!n)){let o=Math.max(0,i-110),a=Math.min(s.text.length,i+e.length+110);n=(o>0?"\u2026":"")+s.text.slice(o,a)+(a<s.text.length?"\u2026":"")}}return{hitCount:t,snippet:n}}var au=v(()=>{});var ko,xo,dg=v(()=>{ko=".typebulb/paste",xo={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",bmp:"image/bmp"}});import{existsSync as BA,mkdirSync as jA,writeFileSync as FA,readFileSync as qA}from"fs";import{join as Eo}from"path";function fg(){let r=new Date,e=t=>String(t).padStart(2,"0");return`${r.getFullYear()}${e(r.getMonth()+1)}${e(r.getDate())}-${e(r.getHours())}${e(r.getMinutes())}${e(r.getSeconds())}`}function HA(r){return r.trim().toLowerCase().replace(/\.[a-z0-9]{1,4}$/,"").replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60)}async function WA(r){let e=AbortSignal.timeout(UA);for(let[t,n]of KA){let s=Ge(t,n);if(typeof s!="string"){try{let i=await yt(s,{messages:[{role:"user",content:`Reply with ONLY a short kebab-case filename (2-5 words, lowercase, no extension) describing this text:
|
|
1528
|
+
|
|
1529
|
+
${r.slice(0,JA)}`}],effort:0,webSearch:!1,signal:e});if(!i.ok)continue;let o=HA(await Jt(i,s.protocol));if(o)return o}catch{}if(e.aborted)return}}}async function pg(r,e){if(!e||e.kind!=="image"&&e.kind!=="text")return{ok:!1,error:"bad paste kind"};if(typeof e.data!="string"||!e.data)return{ok:!1,error:"empty paste"};let t=Eo(r,ko);try{jA(t,{recursive:!0})}catch(a){return{ok:!1,error:J(a)}}let n,s,i;if(e.kind==="image"){if(n=`img-${fg()}`,s=Object.keys(xo).find(a=>xo[a]===e.mime)??"png",i=Buffer.from(e.data,"base64"),!i.length)return{ok:!1,error:"empty image data"}}else n=await WA(e.data)??`paste-${fg()}`,s="md",i=e.data;let o=`${n}.${s}`;for(let a=2;BA(Eo(t,o));a++)o=`${n}-${a}.${s}`;try{FA(Eo(t,o),i)}catch(a){return{ok:!1,error:J(a)}}return{ok:!0,path:`${ko}/${o}`}}function mg(r,e){if(!/^[\w-]+(\.[\w-]+)*$/.test(e))return{ok:!1,error:"bad name"};let t=e.slice(e.lastIndexOf(".")+1).toLowerCase(),n=xo[t];if(!n)return{ok:!1,error:"not an image"};try{return{ok:!0,mime:n,base64:qA(Eo(r,ko,e)).toString("base64")}}catch{return{ok:!1,error:"not found"}}}var UA,JA,KA,hg=v(()=>{xr();$r();xt();dg();UA=4e3,JA=4e3,KA=[["openrouter","google/gemini-3.1-flash-lite-preview"],["gemini","gemini-3.1-flash-lite"]]});import{existsSync as gg,openSync as YA,readSync as VA,closeSync as GA,statSync as Dr,readdirSync as yg,watchFile as zA,unwatchFile as bg,mkdirSync as XA,writeFileSync as QA,readFileSync as Ao,unlinkSync as ZA,rmSync as eT}from"fs";import{stat as tT}from"fs/promises";import{dirname as rT,join as Xt,resolve as wg}from"path";function oT(r){if(!Number.isInteger(r))return!0;try{return process.kill(r,0),!0}catch(e){return e.code==="EPERM"}}function To(r){let e={cwd:Y,sessionId:"",sessionStartMs:Date.now(),buffer:[],partial:"",offset:0,latest:{in:0,out:0,cached:0,cacheCreate:0},latestModel:null,everAttached:!1,entries:new Map},t=new Set,n;function s(){if(e.file){for(let h of t)if(h.file===e.file)return h;return}return n}function i(h){let S={d:r.createDriver(e.cwd,h),file:h};return t.add(S),e.file||(n=S),S}async function o(h){t.delete(h),n===h&&(n=void 0);try{await h.d.dispose()}catch(S){console.error("[composer] dispose:",J(S))}}function a(){let h=s();for(let S of[...t])S!==h&&(S.d.streaming||S.d.queue||S.d.error||o(S))}function c(){for(let h of t)h.d.sessionFile&&h.file!==h.d.sessionFile&&(h.file=h.d.sessionFile);if(n&&!e.file&&n.file){let h=r.listSessionFiles(e.cwd).find(S=>S.file===n.file);h&&N(h)}}let l=h=>Xt(h,sT),f=(h,S)=>Xt(l(h),`${S}.lock`);function u(h,S){try{let k=f(h,S);if(Date.now()-Dr(k).mtimeMs>=vg)return!1;try{let O=parseInt(Ao(k,"utf8").trim(),10);if(O===process.pid||!oT(O))return!1}catch{}return!0}catch{return!1}}function d(h,S){if(S)try{XA(l(h),{recursive:!0}),QA(f(h,S),String(process.pid))}catch(k){console.error("[lock] claim failed:",J(k))}}function p(h){try{eT(Xt(h,".claude-bulb"),{recursive:!0,force:!0})}catch{}}function b(h){let S=l(h);if(!gg(S))return;let k;try{k=yg(S)}catch{return}let O=Date.now();for(let D of k){if(!D.endsWith(".lock"))continue;let j=Xt(S,D);try{let L=Dr(j);O-L.mtimeMs>iT&&ZA(j)}catch{}}}function m(h){try{return Dr(h),!1}catch(S){return S.code==="ENOENT"}}function g(){let h=e;if(h.file&&!m(h.file)){d(h.cwd,h.sessionId);return}let S=x(h);S&&N(S)}function x(h){if(!h.everAttached)return A(h.cwd)??P(h.cwd,()=>!0)}function A(h){let S=l(h);if(!gg(S))return;let k;try{k=yg(S)}catch{return}let O;for(let j of k)if(j.endsWith(".lock"))try{let L=Dr(Xt(S,j));if(Date.now()-L.mtimeMs>=vg||parseInt(Ao(Xt(S,j),"utf8").trim(),10)!==process.pid)continue;(!O||L.mtimeMs>O.mtime)&&(O={sessionId:j.slice(0,-5),mtime:L.mtimeMs})}catch{}if(!O)return;let D=r.listSessionFiles(h).find(j=>j.sessionId===O.sessionId);if(!(!D||m(D.file)))return D}function P(h,S){return r.listSessionFiles(h).sort((k,O)=>O.mtime-k.mtime).find(k=>!u(h,k.sessionId)&&S(k))}function _(h,S){let k=e;if(k.file)try{bg(k.file)}catch{}k.file=h,k.sessionId=S,k.partial="",k.offset=0,k.latest={in:0,out:0,cached:0,cacheCreate:0},k.latestModel=null,k.entries=new Map,k.chainLastId=void 0,k.buffer.push({type:"cleared"}),k.buffer.push({type:"session",sessionId:S})}function N(h){let S=e;n=void 0,_(h.file,h.sessionId),S.everAttached=!0,d(S.cwd,h.sessionId),I();try{bg(h.file)}catch{}zA(h.file,{interval:200},()=>I())}function C(){_(void 0,"")}function I(){let h=e;if(!h.file)return;let S;try{S=Dr(h.file).size}catch{return}if(S<=h.offset)return;let k;try{k=YA(h.file,"r")}catch{return}try{let U=S-h.offset,fe=Buffer.alloc(U),te=0;for(;te<U;){let ju=VA(k,fe,te,U-te,h.offset+te);if(!ju)break;te+=ju}h.offset+=te,h.partial+=fe.subarray(0,te).toString("utf8")}finally{GA(k)}let O,D;for(;(D=h.partial.indexOf(`
|
|
1530
|
+
`))>=0;){let U=h.partial.slice(0,D);if(h.partial=h.partial.slice(D+1),!U.trim())continue;let fe=r.parseEntry(U);if(!fe)continue;let te=r.idOf(fe);te&&(h.entries.set(te,fe),!r.isSidechain(fe)&&r.isLeafType(fe)&&(O=te))}if(!O)return;let j=[],L=h.entries.get(O),H=!1;for(;L;){if(j.push(L),r.idOf(L)===h.chainLastId){H=!0;break}let U=r.parentOf(L);L=U?h.entries.get(U):void 0}if(H)for(let U=j.length-2;U>=0;U--)$(j[U]);else{h.chainLastId!==void 0&&(h.buffer.push({type:"cleared"}),h.buffer.push({type:"session",sessionId:h.sessionId}),h.latest={in:0,out:0,cached:0,cacheCreate:0});let U=new Set(j.map(te=>r.idOf(te))),fe=E(h.entries);for(let te=j.length-1;te>=0;te--)$(j[te]),y(r.idOf(j[te]),fe,U)}h.chainLastId=O}function E(h){let S=new Map;for(let k of h.values()){let O=r.parentOf(k);if(!O)continue;let D=S.get(O);D?D.push(k):S.set(O,[k])}return S}function y(h,S,k){if(!h)return;let O=S.get(h);if(!O)return;let D=O.filter(U=>!r.isSidechain(U));if(D.length<2)return;let j=D.filter(U=>!k.has(r.idOf(U)));if(!j.length)return;let L=[],H=0;for(let U of j){let fe=w(U,S);L.push(...fe.events),H+=fe.count}H>0&&e.buffer.push({type:"fork",atId:h,count:H,events:L})}function w(h,S){let k=[],O=[h];for(;O.length;){let L=O.pop();if(r.isSidechain(L))continue;k.push(L);let H=S.get(r.idOf(L)??"");if(H)for(let U of H)O.push(U)}k.sort((L,H)=>(Date.parse(r.timestampOf(L)??"")||0)-(Date.parse(r.timestampOf(H)??"")||0));let D=[];for(let L of k)r.isRecoveryNoise(L)||D.push(...r.apply(L,e.sessionStartMs).events);return{count:D.reduce((L,H)=>L+(H.type==="user"||H.type==="assistant"?1:0),0),events:D}}function $(h){try{let{events:S,usage:k,model:O,cost:D}=r.apply(h,e.sessionStartMs);for(let j of S)e.buffer.push(j);S.some(j=>j.type==="assistant")&&s()?.d.clearCompletedDraft(),S.some(j=>j.type==="user")&&s()?.d.clearEcho(),O&&(e.latestModel=O),k&&(e.latest=k),(k||D)&&e.buffer.push({type:"usage",...e.latest,cost:D})}catch(S){console.error("[mirror] skipped malformed entry:",J(S))}}async function R(){return{cwd:e.cwd,pid:process.pid,composer:!!r.createDriver,elsewhere:await M()}}async function M(){if(r.listSessionFiles(e.cwd).length)return;let h=await Mr();if(!h)return;let S=wg(h).toLowerCase();for(let k=wg(e.cwd);k.toLowerCase()!==S;){let O=rT(k);if(O===k)return;k=O;let D=r.listSessionFiles(k).length;if(D)return{dir:k,count:D}}}M().then(h=>{h&&console.log(`No sessions for ${e.cwd} \u2014 ${h.count} exist for ${h.dir}. Launched from a subfolder? Relaunch from the project root.`)}).catch(()=>{});let W=new bo;async function K(h,S){W.accept(h,S)&&console.log(S)}function qe(){let h=r.sessionAlive(e.sessionId,e.cwd);if(h!==void 0)return h;if(!e.file)return!1;try{return Date.now()-Dr(e.file).mtimeMs<1e4}catch{return!1}}function z(){return r.chainWorking([...e.entries.values()])&&qe()}function V(){!r.createDriver||s()||e.latestModel||z()||i(e.file)}async function Ue(h){let S=e;g(),c(),V(),a();let k=s();for(let L of t)L!==k&&L.d.dialog;let O=new Set([...t].filter(L=>L.d.streaming&&L.file).map(L=>L.file)),D=O.size?r.listSessionFiles(S.cwd).filter(L=>O.has(L.file)).map(L=>L.sessionId):[],j=r.createDriver?{streaming:!!k?.d.streaming,draft:k?.d.draft??null,echo:k?.d.echo??null,status:k?.d.status??null,dialog:k?.d.dialog??null,queue:k?.d.queue??null,stats:k?.d.stats??null,model:k?.d.model??null,error:k?.d.error}:void 0;return{events:S.buffer.slice(h),cursor:S.buffer.length,working:!!k?.d.streaming||z(),latestModel:S.latestModel,composer:j,busy:D}}async function we(){g(),c();let h=s();if(h?.d.error&&!h.d.streaming&&(await o(h),h=void 0),!h){if(z())return{ok:!1,error:"the agent is mid-turn in a terminal \u2014 watch only"};h=i(e.file)}return{ok:!0,d:h.d}}async function db(h,S){if(!r.createDriver)return{ok:!1,error:"not supported"};let k=String(h??"").trim();if(!k)return{ok:!1,error:"empty message"};let O=await we();return O.ok?O.d.send(k,S):O}async function fb(h,S){let k=s();return k?k.d.respondUi(String(h??""),S??{}):{ok:!1,error:"no dialog pending"}}async function pb(h,S){if(!r.createDriver)return{ok:!1,error:"not supported"};if(!h||typeof h.type!="string")return{ok:!1,error:"bad command"};if(S?.spawn){let O=await we();return O.ok?O.d.rpc(h):O}let k=s();return!k||k.d.error?{ok:!1,error:"not running"}:k.d.rpc(h)}async function mb(){let h=s();if(h)try{await h.d.stop()}catch(S){console.error("[composer] stop:",J(S))}return{ok:!0}}async function hb(){return r.createDriver?(c(),!e.file&&n&&!n.d.streaming&&!n.d.error?{ok:!0}:(n?.d.error&&await o(n),n=void 0,e.file&&C(),i(void 0),a(),{ok:!0})):{ok:!1,error:"not supported"}}async function gb(){if(!r.createDriver)return[];let h=await je(["ls-files","--cached","--others","--exclude-standard"],e.cwd).catch(()=>null),S=h!==null?h.split(`
|
|
1531
|
+
`).filter(Boolean):await r.walkFiles?.(e.cwd)??[];return(await Promise.all(S.map(async O=>{try{return{f:O,m:(await tT(Xt(e.cwd,O))).mtimeMs}}catch{return{f:O,m:0}}}))).sort((O,D)=>D.m-O.m).map(O=>O.f)}function yb(){for(let h of[...t])o(h)}async function bb(h){return r.createDriver?pg(e.cwd,h):{ok:!1,error:"not supported"}}async function wb(h){return mg(e.cwd,String(h??""))}async function vb(){return r.listSessionFiles(e.cwd).sort((h,S)=>S.mtime-h.mtime).map(({sessionId:h,file:S,mtime:k})=>({sessionId:h,mtime:k,preview:r.readPreview(S)}))}let Mu=new Map;function Sb(h,S){let k=Mu.get(h);if(k&&k.mtime===S)return k.turns;let O=[],D="";try{D=Ao(h,"utf8")}catch{return[]}for(let j of D.split(`
|
|
1532
|
+
`)){if(!j.trim())continue;let L=r.parseEntry(j);if(!L)continue;let H=r.searchText(L);H&&O.push({text:H,lower:H.toLowerCase()})}return Mu.set(h,{mtime:S,turns:O}),O}async function kb(h){let S=h.toLowerCase(),k=[];for(let{sessionId:O,file:D,mtime:j}of r.listSessionFiles(e.cwd).sort((L,H)=>H.mtime-L.mtime)){let{hitCount:L,snippet:H}=So(Sb(D,j),S);if(L&&(k.push({sessionId:O,mtime:j,preview:r.readPreview(D),hitCount:L,snippet:H}),k.length>=aT))break}return k}let Du=800,Bu=new Map;function xb(h,S){let k=Bu.get(h);if(k&&k.mtime===S)return k.text;let O="";try{O=Ao(h,"utf8")}catch{return""}let D="";for(let L of O.split(`
|
|
1533
|
+
`)){if(!L.trim())continue;let H=r.parseEntry(L);if(H)for(let U of r.apply(H,e.sessionStartMs).events)U.type==="assistant"&&U.text.trim()&&(D=U.text.trim())}let j=D.length>Du?D.slice(0,Du).trimEnd()+"\u2026":D;return Bu.set(h,{mtime:S,text:j}),j}async function Eb(h){let S=r.listSessionFiles(e.cwd).find(k=>k.sessionId===h);return{text:S?xb(S.file,S.mtime):""}}async function Ab(h){let S=e,k=r.listSessionFiles(S.cwd).find(O=>O.sessionId===h);return k?k.file===S.file?{ok:!0}:(N(k),c(),a(),{ok:!0}):{ok:!1,error:"session not found"}}return p(e.cwd),b(e.cwd),g(),{info:R,poll:Ue,logEmbedStatus:K,listSessions:vb,searchSessions:kb,sessionPeek:Eb,attach:Ab,composerSend:db,composerStop:mb,composerNew:hb,composerFiles:gb,composerUiRespond:fb,composerRpc:pb,composerPaste:bb,composerPasteRead:wb,shutdownComposer:yb}}var nT,sT,vg,iT,aT,cu=v(()=>{xt();og();vo();au();hg();nT=".typebulb",sT=`${nT}/locks`,vg=5e3,iT=6e4;aT=50});import{existsSync as fu,mkdirSync as cT,readFileSync as Sg,writeFileSync as lT}from"fs";import{join as Qt,isAbsolute as uT}from"path";async function kg(r,e){let t=uT(r)?r:Qt(Y,r);return fu(t)?(Kl(t,e),{ok:!0}):{ok:!1,error:"file not found"}}async function xg(r){let e=Y,t=Jl(r),n=Qt(e,"typebulbs");cT(n,{recursive:!0});let s=Fl(t),i=`${s}.bulb.md`;for(let l=2;fu(Qt(n,i))&&Sg(Qt(n,i),"utf8")!==t;l++)i=`${s}-${l}.bulb.md`;let o=Qt(n,i);fu(o)||lT(o,t);let a=Qt("typebulbs",i),c=await Xi(a,{cwd:e,open:!1});return{ok:!0,file:a,pid:c.pid,url:c.url}}async function Eg(){return Q(Y)}async function Ag(r){return await Yt(r),{ok:!0}}async function Tg(){return Zi(Y).filter(r=>!r.serverOnly).map(r=>({...r,trusted:Wt(r.path)}))}async function Pg(r){let e=r.toLowerCase(),t=[];for(let n of Zi(Y).filter(s=>!s.serverOnly).sort((s,i)=>i.mtime-s.mtime)){let s="";try{s=Sg(n.path,"utf8")}catch{continue}let i=[];for(let c of s.split(`
|
|
1534
|
+
`)){let l=c.replace(/\s+/g," ").trim();l&&i.push({text:l,lower:l.toLowerCase()})}let{hitCount:o,snippet:a}=So(i,e);o&&t.push({path:n.path,hitCount:o,snippet:a})}return t}async function Og(r,e){let t=Y;e!=null&&Or(r,e);let n=await Xi(r,{cwd:t,open:!1,trust:e});return{ok:!0,file:n.file,pid:n.pid,url:n.url,trust:!!n.trust}}async function Cg(r){return{cap:await Ul(r)}}async function Rg(r,e){return Or(r,e),{ok:!0}}async function _g(r,e){return $e(r,e)}async function Lg(){return Qn&&Date.now()-Qn.fetchedAt<=fT?Qn.samples:(lu??=pT().finally(()=>{lu=null}),lu)}async function pT(){try{let r=await fetch(`${dT}/api/scripts/u/samples?stubs`,{signal:AbortSignal.timeout(Ig)});if(!r.ok)throw new Error(`HTTP ${r.status}`);let e=await r.json(),t=i=>i.order??Number.MAX_SAFE_INTEGER,n=i=>Date.parse(i.createdAt??"")||0,s=e.filter(i=>i.slug!=="welcome").sort((i,o)=>t(i)-t(o)||n(o)-n(i)).map(i=>({slug:i.slug,name:i.name,description:na(i.config)}));return Qn={samples:s,fetchedAt:Date.now()},s}catch{return Qn?.samples??[]}}async function Mg(r){return pu.test(r)?jg(Ng,"samples",r,!0):{ok:!1,error:"bad slug"}}async function Dg(){let r=mu();if(!r)return{bulbs:[]};let e=`${Po()}
|
|
1535
|
+
${r}`;return Et?.key===e&&Date.now()-Et.fetchedAt<=mT?{user:Et.user,bulbs:Et.bulbs}:(uu??=hT(e,r).finally(()=>{uu=null}),uu)}async function du(r,e,t){let n=await fetch(`${r}${e}`,{headers:t,signal:AbortSignal.timeout(Ig)});if(!n.ok)throw new Error(`HTTP ${n.status}`);if(!n.headers.get("content-type")?.includes("json"))throw new Error("not json");return n.json()}async function hT(r,e){let t={Authorization:`Bearer ${e}`};try{let n=Po(),s;try{s=await du(n,"/api/me",t)}catch{let a=new URL(n);n=`${a.protocol}//api.${a.host}`,s=await du(n,"/api/me",t)}let o=(await du(n,"/api/scripts/list",t)).filter(a=>a.userSlug===s.slug&&!a.isTemplate).map(a=>({slug:a.slug,name:a.name,description:na(a.config)}));return Et={key:r,user:s.slug,bulbs:o,fetchedAt:Date.now()},{user:s.slug,bulbs:o}}catch{return Et?.key===r?{user:Et.user,bulbs:Et.bulbs}:{bulbs:[]}}}async function Bg(r,e,t=!1){return!pu.test(e)||!pu.test(r)?{ok:!1,error:"bad slug"}:jg(Po(),r,e,t)}async function jg(r,e,t,n){let s=no(e,t);try{let i=await io({origin:r,userSlug:e,slug:t,dest:Qt(Y,s)},{force:n,token:mu(),timeoutMs:$g});return i.kind==="conflict"?{ok:!1,conflict:!0,error:"local file differs from the site copy"}:i.kind==="http-error"?{ok:!1,error:`HTTP ${i.status}`}:i.kind==="not-markdown"?{ok:!1,error:`not a bulb (${i.contentType??"no content-type"})`}:{ok:!0,file:s,upToDate:i.kind==="up-to-date"}}catch(i){return{ok:!1,error:i?.message??String(i)}}}async function Fg(r,e=!1){let t=mu();if(!t)return{ok:!1,error:"no TYPEBULB_TOKEN in .env"};try{let n=so(r,Y,Po()),s=await po(n,{token:t,force:e,timeoutMs:$g});return s.kind==="conflict"?{ok:!1,conflict:!0,error:s.message}:s.kind==="http-error"?{ok:!1,error:`HTTP ${s.status}: ${s.message}`}:{ok:!0,created:s.created,serverStripped:s.serverStripped}}catch(n){return{ok:!1,error:n?.message??String(n)}}}var dT,Ng,fT,Ig,$g,Qn,lu,pu,mT,Et,uu,Po,mu,hu=v(()=>{$r();xt();au();Ne();dT="https://api.typebulb.com",Ng="https://typebulb.com",fT=3600*1e3,Ig=5e3,$g=15e3,Qn=null,lu=null;pu=/^[a-z0-9][a-z0-9-]*$/,mT=300*1e3,Et=null,uu=null,Po=()=>ro("TYPEBULB_ORIGIN",Y)||Ng,mu=()=>ro("TYPEBULB_TOKEN",Y)});import{readFileSync as bu,writeFileSync as Ug,mkdirSync as gT,appendFileSync as Jg,rmSync as qg}from"fs";import{join as Ro,dirname as yT}from"path";import{createServer as bT}from"http";function At(r){try{return JSON.parse(bu(r,"utf8"))}catch{return null}}function Co(r,e){gT(yT(r),{recursive:!0}),Ug(r,JSON.stringify(e,null,2)+`
|
|
1536
|
+
`)}function Hg(r,e,t){let n=Ro(r,".gitignore"),s="";try{s=bu(n,"utf8")}catch{}let i=new Set(s.split(/\r?\n/).map(c=>c.trim())),o=e.filter(c=>!i.has(c));if(!o.length)return;let a=s&&!s.endsWith(`
|
|
1537
|
+
`)?`
|
|
1538
|
+
`:"";try{Jg(n,a+t+`
|
|
1539
|
+
`+o.join(`
|
|
1540
|
+
`)+`
|
|
1541
|
+
`)}catch(c){console.error("[switcher] .gitignore update failed",J(c))}}function xT(r){let e=i=>{let o=i.exec(r);return o?Number(o[1]):0},t=e(/"cache_read_input_tokens":\s*(\d+)/),n=e(/"cache_creation_input_tokens":\s*(\d+)/),s=e(/"input_tokens":\s*(\d+)/);t>0||n>0?ts="live":s>kT&&(ts="uncached")}function Yg(r,e){let t={"content-type":"application/json",authorization:`Bearer ${e}`,"anthropic-version":r.headers["anthropic-version"]||"2023-06-01"},n=r.headers["anthropic-beta"];return typeof n=="string"&&(t["anthropic-beta"]=n),t}function ET(r){if(Array.isArray(r?.messages))for(let e of r.messages){if(!Array.isArray(e?.content))continue;let t=e.content.filter(n=>n?.type!=="thinking"&&n?.type!=="redacted_thinking");t.length&&t.length!==e.content.length&&(e.content=t)}}function Vg(r){let e;try{e=JSON.parse(r)}catch{return r}es=typeof e?.model=="string"?e.model:null,Fe&&(e.model=Fe),er&&(e.provider=Wg(er));let t=/haiku/i.test(es||"");return rs!=null&&!t&&(e.reasoning={effort:gu[rs]}),delete e.thinking,e.output_config&&delete e.output_config.effort,ET(e),JSON.stringify(e)}function AT(){let r="",e=0,t=new Map,n=new Set(["thinking","redacted_thinking"]),s=i=>{let o=/^data: (.*)$/m.exec(i);if(!o)return i;let a;try{a=JSON.parse(o[1])}catch{return i}switch(a.type){case"message_start":return t.clear(),e=0,i;case"content_block_start":{if(n.has(a.content_block?.type))return t.set(a.index,null),null;let c=e++;return t.set(a.index,c),a.index=c,`event: ${a.type}
|
|
1542
|
+
data: ${JSON.stringify(a)}
|
|
1845
1543
|
|
|
1846
|
-
|
|
1847
|
-
|
|
1848
|
-
foot.appendChild(cancel);
|
|
1849
|
-
runBtn.addEventListener('click', run);
|
|
1850
|
-
foot.appendChild(runBtn);
|
|
1851
|
-
}
|
|
1544
|
+
`}case"content_block_delta":case"content_block_stop":{let c=t.get(a.index);return c==null?null:(a.index=c,`event: ${a.type}
|
|
1545
|
+
data: ${JSON.stringify(a)}
|
|
1852
1546
|
|
|
1853
|
-
|
|
1854
|
-
function run() {
|
|
1855
|
-
var data = areas.map(function (a) { return a.value.trim(); }).filter(function (v) { return v !== ''; });
|
|
1856
|
-
ctx.data = data; // a retry's confirm re-seeds from the edited chunks, not the originals
|
|
1857
|
-
body.textContent = ''; foot.textContent = '';
|
|
1547
|
+
`)}default:return i}};return i=>{r+=i;let o="",a;for(;(a=r.indexOf(`
|
|
1858
1548
|
|
|
1859
|
-
|
|
1860
|
-
|
|
1861
|
-
|
|
1862
|
-
|
|
1863
|
-
|
|
1864
|
-
|
|
1865
|
-
cancel.addEventListener('click', function () { close('cancel'); });
|
|
1866
|
-
foot.appendChild(cancel);
|
|
1549
|
+
`))!==-1;){let c=r.slice(0,a);if(r=r.slice(a+2),!c.trim())continue;let l=s(c);l!==null&&(o+=l)}return o}}function TT(r){return new Promise(e=>{let t=[];r.on("data",n=>t.push(n)),r.on("end",()=>e(Buffer.concat(t).toString("utf8"))),r.on("error",()=>e(Buffer.concat(t).toString("utf8")))})}function Zn(r,e,t,n){r.writableEnded||(r.writeHead(e,{"content-type":"application/json"}),r.end(JSON.stringify({type:"error",error:{type:t,message:n}})))}async function PT(r,e,t){if(!Fe){Zn(e,400,"invalid_request_error",ST);return}let n=process.env.OPENROUTER_API_KEY;if(!n){Zn(e,401,"authentication_error","OPENROUTER_API_KEY not set in the typebulb proxy");return}let s=new AbortController;e.on("close",()=>{e.writableEnded||s.abort()});let i;try{i=await fetch(wu,{method:"POST",headers:Yg(r,n),body:Vg(t),signal:s.signal})}catch(u){Zn(e,502,"api_error",`proxy upstream failed: ${J(u)}`);return}let o=i.headers.get("content-type")||"application/json";if(e.writeHead(i.status,{"content-type":o}),!i.body){e.end();return}let a=o.includes("event-stream"),c=i.body.getReader(),l=new TextDecoder,f=a?AT():null;try{for(;;){let{done:u,value:d}=await c.read();if(u)break;if(d)if(f){let p=l.decode(d,{stream:!0});xT(p);let b=f(p);b&&e.write(b)}else e.write(Buffer.from(d))}}catch{}finally{e.writableEnded||e.end()}}async function OT(r,e,t){let n=process.env.OPENROUTER_API_KEY,s=()=>{e.writeHead(200,{"content-type":"application/json"}),e.end(JSON.stringify({input_tokens:Math.max(1,Math.ceil(t.length/4))}))};if(!Fe||!n)return s();try{let i=await fetch(`${wu}/count_tokens`,{method:"POST",headers:Yg(r,n),body:Vg(t)});if(!i.ok)return s();let o=await i.text();e.writeHead(200,{"content-type":"application/json"}),e.end(o)}catch{s()}}function CT(r,e){let t=r.url||"/";if(r.method==="HEAD"){e.writeHead(200),e.end();return}if(r.method!=="POST"){Zn(e,404,"not_found_error",t);return}TT(r).then(n=>{if(t.includes("count_tokens"))return OT(r,e,n);if(t.includes("/v1/messages"))return PT(r,e,n);Zn(e,404,"not_found_error",t)})}function RT(){return Br&&Zt?Promise.resolve(Zt):new Promise((r,e)=>{let t=bT(CT);t.on("error",e),t.listen(0,"127.0.0.1",()=>{Br=t,Zt=t.address().port,console.log(`[switcher] wire proxy listening on ${Oo(Zt)}`),r(Zt)})})}function _T(){try{Br?.close()}catch{}Br=null,Zt=null}function NT(r,e){let t=_o(r),n=At(t),s=n||{};if((!s.env||typeof s.env!="object")&&(s.env={}),s.env.ANTHROPIC_BASE_URL===Oo(e)&&s.env.ANTHROPIC_AUTH_TOKEN)return;let i=No(r);if(!At(i)){let a={};for(let c of Kg)a[c]=c in s.env?s.env[c]:null;Co(i,{managedBy:"agent-switcher",fileExisted:n!==null,snapshot:a,active:null})}s.env.ANTHROPIC_BASE_URL=Oo(e),s.env.ANTHROPIC_AUTH_TOKEN=vT,Co(t,s),Hg(r,[".claude/settings.local.json",".claude/.cc-switcher.json"],"# agent switcher (local Claude Code model override)")}function IT(r,e,t){let n=No(r),s=At(n)||{managedBy:"agent-switcher",fileExisted:!1,snapshot:{}};s.active={model:e,provider:t},Co(n,s)}function Gg(r){let e=_o(r),t=No(r),n=At(t),s=At(e);if(s?.env){let i=n?.snapshot||{};for(let o of Kg){let a=i[o];a==null?delete s.env[o]:s.env[o]=a}if(Object.keys(s.env).length===0&&delete s.env,n?.fileExisted===!1&&Object.keys(s).length===0)try{qg(e,{force:!0})}catch{}else Co(e,s)}try{qg(t,{force:!0})}catch{}}async function $T(){let r=!!process.env.OPENROUTER_API_KEY,e=[];try{e=(await Ve()).filter(n=>n.provider==="openrouter"&&!vu(n.name)).map(n=>({id:n.name,label:n.friendlyName||n.name}))}catch(n){console.error("[switcher] model list failed",J(n))}let t=e.length?void 0:yl()??void 0;return{hasKey:r,models:e,error:t}}async function LT(){if(Br&&Fe)return{active:!0,managed:!0,model:Fe,port:Zt,provider:er,routedModel:es,caching:ts,reasoning:rs,externalBaseUrl:null};let r=At(_o(Y))?.env||{};return{active:!1,managed:!1,model:null,port:null,provider:null,routedModel:null,caching:"unknown",reasoning:rs,externalBaseUrl:r.ANTHROPIC_BASE_URL||null}}async function zg(r,e){let t=await RT();return Fe=r,er=e,NT(Y,t),t}async function MT({model:r}){if(!process.env.OPENROUTER_API_KEY)return{ok:!1,error:"OPENROUTER_API_KEY not set \u2014 add a key first"};if(!r)return{ok:!1,error:"no model given"};if(vu(r))return{ok:!1,error:"Refusing to route an Anthropic model through OpenRouter \u2014 that bills full API rate with no caching. Use it on your Anthropic subscription instead."};try{await zg(r,Su[r]??null),es=null,ts="unknown",IT(Y,r,er)}catch(e){return{ok:!1,error:`failed to start the wire proxy: ${J(e)}`}}return{ok:!0}}async function DT({level:r}){return r!=null&&(!Number.isInteger(r)||r<0||r>=gu.length)?{ok:!1,error:`reasoning level must be 0\u2013${gu.length-1} or null`}:(rs=r,{ok:!0,level:r})}async function BT(){return Gg(Y),Fe=null,er=null,es=null,ts="unknown",{ok:!0}}async function jT({key:r}){let e=(r||"").trim();if(!e)return{ok:!1,error:"empty key"};let t=Y,n=Ro(t,".env"),s="";try{s=bu(n,"utf8")}catch{}try{if(/^\s*OPENROUTER_API_KEY\s*=/m.test(s))Ug(n,s.replace(/^\s*OPENROUTER_API_KEY\s*=.*$/m,`OPENROUTER_API_KEY=${e}`));else{let i=s&&!s.endsWith(`
|
|
1550
|
+
`)?`
|
|
1551
|
+
`:"";Jg(n,i+`OPENROUTER_API_KEY=${e}
|
|
1552
|
+
`)}}catch(i){return{ok:!1,error:J(i)}}return process.env.OPENROUTER_API_KEY=e,Hg(t,[".env"],"# secrets"),{ok:!0}}function FT(){if(!(!Br&&!Fe)){try{Gg(Y)}catch{}_T()}}function qT(r,e){return Xg.test(e)?"blocked by your OpenRouter data policy":r===401||r===403||/unauthor|invalid api key|no auth|forbidden/i.test(e)?"auth rejected \u2014 check your OpenRouter key":r===404||/not a valid model|no such model|unknown model|model not found/i.test(e)?"model not found on this route":r===429||/rate limit/i.test(e)?"rate limited":r===402||/insufficient|credit|quota|balance/i.test(e)?"out of credits / quota":e.slice(0,160)}function UT(r){if(Xg.test(r))return"This model's only provider(s) require prompt logging/training, which your OpenRouter account disallows by default. Allow it (or that provider) at openrouter.ai/settings/privacy, then probe again."}function JT(r,e,t){if(!r)return{works:null,read:0,note:t?`couldn't re-test on ${t} \u2014 caching unconfirmed`:"caching unconfirmed"};let n=yu(e?.cache_read_input_tokens)||yu(e?.prompt_tokens_details?.cached_tokens),s=e?.cache_read_input_tokens!==void 0||e?.cache_creation_input_tokens!==void 0||e?.prompt_tokens_details!==void 0;return n>0?{works:!0,read:n,note:`${n} tokens read from cache on the 2nd call`}:s?{works:!1,read:n,note:"no cache reads after a warm call \u2014 every turn re-bills the full context"}:{works:null,read:n,note:"route doesn't report cache usage \u2014 caching almost certainly not honored"}}async function KT({model:r}){let e=process.env.OPENROUTER_API_KEY;if(!e)return{ok:!1,error:"OPENROUTER_API_KEY not set \u2014 add a key first"};if(!r)return{ok:!1,error:"no model given"};if(vu(r))return{ok:!1,error:"Anthropic model \u2014 not offered or probed via OpenRouter"};let t=Date.now(),n=Array(350).fill("Caching probe filler sentence; its only purpose is to exceed the prompt-cache minimum token threshold.").join(" "),s={"content-type":"application/json",authorization:`Bearer ${e}`,"anthropic-version":"2023-06-01"},i={model:r,max_tokens:64,system:[{type:"text",text:n,cache_control:{type:"ephemeral"}}],messages:[{role:"user",content:"Reply with exactly: ok"}]},o=async a=>{let c=new AbortController,l=setTimeout(()=>c.abort(),2e4);try{let f=JSON.stringify(a?{...i,provider:Wg(a)}:i),u=await fetch(wu,{method:"POST",signal:c.signal,headers:s,body:f}),d=await u.json().catch(()=>({}));return{r:u,j:d}}finally{clearTimeout(l)}};try{let{r:a,j:c}=await o();if(!a.ok){let x=c?.error?.message||c?.message||JSON.stringify(c).slice(0,300);return{ok:!0,callable:!1,status:a.status,ms:Date.now()-t,error:qT(a.status,x),restriction:UT(x)}}let l=typeof c?.provider=="string"?c.provider:void 0,f=c?.content?.find?.(x=>x.type==="text")?.text??c?.content?.[0]?.text??"ok",u=yu(c?.usage?.cache_creation_input_tokens),{r:d,j:p}=await o(l),{works:b,read:m,note:g}=JT(d.ok,p?.usage,l);return b===!0&&l&&(Su[r]=l,Fe===r&&(er=l)),{ok:!0,callable:!0,status:a.status,ms:Date.now()-t,provider:l,sample:String(f).trim().slice(0,60),cache:{works:b,created:u,read:m,note:g}}}catch(a){let c=J(a);return{ok:!0,callable:!1,ms:Date.now()-t,error:/abort/i.test(c)?"timed out (20s)":c}}}var wT,wu,vT,ST,Kg,kT,gu,_o,No,Oo,vu,Br,Zt,Fe,er,es,ts,rs,Su,yu,Wg,Xg,Qg=v(()=>{$r();xt();wT="https://openrouter.ai/api",wu=`${wT}/v1/messages`,vT="typebulb-proxy-managed",ST="The typebulb model override was reverted to Anthropic, but this Claude Code session still points at the now-idle proxy. Reload the window (VS Code/Cursor: \u201CDeveloper: Reload Window\u201D) or relaunch `claude` in a terminal to return to your Anthropic subscription.",Kg=["ANTHROPIC_BASE_URL","ANTHROPIC_AUTH_TOKEN"],kT=5e3,gu=["low","medium","high"],_o=r=>Ro(r,".claude","settings.local.json"),No=r=>Ro(r,".claude",".cc-switcher.json"),Oo=r=>`http://127.0.0.1:${r}`;vu=r=>/^anthropic\//i.test(r)||/claude/i.test(r),Br=null,Zt=null,Fe=null,er=null,es=null,ts="unknown",rs=1,Su={},yu=r=>typeof r=="number"?r:0,Wg=r=>({order:[r],allow_fallbacks:!1});Xg=/data policy|no endpoints|no allowed providers|privacy|requires.*(training|logging|data)/i;(async function(){try{let e=At(No(Y)),t=e?.active?.model;if(!t)return;let s=(At(_o(Y))?.env||{}).ANTHROPIC_BASE_URL||"";if(!/127\.0\.0\.1|localhost/.test(s))return;let i=await zg(t,e.active.provider??Su[t]??null);console.log(`[switcher] re-adopted override after restart: ${t} via ${Oo(i)}`)}catch(e){console.error("[switcher] boot reconcile failed",J(e))}})()});var ey={};Fu(ey,{attach:()=>QT,blockToMarkdown:()=>Wi,breakout:()=>xg,capText:()=>Ie,cleanUserText:()=>vt,clearSwitchModel:()=>BT,composerPasteRead:()=>ZT,displayName:()=>HT,downloadSample:()=>Mg,firstLineDigest:()=>Qe,git:()=>je,gitChangedFiles:()=>lg,gitDiff:()=>ug,info:()=>WT,isHiddenTurn:()=>Jn,launchBulb:()=>Og,listBreakouts:()=>Eg,listBulbFiles:()=>Tg,listMyBulbs:()=>Dg,listSamples:()=>Lg,listSessions:()=>GT,listSwitchModels:()=>$T,logEmbedStatus:()=>VT,openFile:()=>kg,poll:()=>YT,predictTrustOf:()=>Cg,probeModel:()=>KT,pullRemoteBulb:()=>Bg,pushLocalBulb:()=>Fg,readBulbLog:()=>_g,repoRoot:()=>Mr,saveOpenRouterKey:()=>jT,searchBulbs:()=>Pg,searchSessions:()=>zT,sessionPeek:()=>XT,setBulbTrust:()=>Rg,setReasoning:()=>DT,setSwitchModel:()=>MT,shutdownSwitcher:()=>FT,stopBreakout:()=>Ag,switchState:()=>LT,toolResultDigest:()=>Rl});var Zg,HT,WT,YT,VT,GT,zT,XT,QT,ZT,ty=v(()=>{cu();Yi();hu();vo();Qg();Yi();Ki();Zg=new Rr,HT=Zg.displayName,{info:WT,poll:YT,logEmbedStatus:VT,listSessions:GT,searchSessions:zT,sessionPeek:XT,attach:QT,composerPasteRead:ZT}=To(Zg)});import{readFileSync as eP,writeFileSync as tP,mkdirSync as rP}from"fs";import{homedir as nP}from"os";import*as Io from"path";async function sy(){try{let r=await fetch(new URL("/api/tags",ny()).toString(),{signal:AbortSignal.timeout(sP)});return r.ok?((await r.json()).models??[]).map(t=>t.name).filter(t=>!!t):[]}catch{return[]}}function iy(r){let e;try{e=eP(r,"utf-8")}catch{return{json:void 0,unreadable:!1}}try{let t=JSON.parse(e);if(t&&typeof t=="object"&&!Array.isArray(t)){let n=t;return{json:n,unreadable:"providers"in n&&!ku(n)}}}catch{}return{json:void 0,unreadable:!0}}function ku(r){let e=r?.providers;return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function iP(r){let e=ku(r);if(!e||!("ollama"in e))return null;let t=e.ollama?.models;return Array.isArray(t)?t.map(n=>n?.id).filter(n=>typeof n=="string"):[]}async function oy(){let{json:r,unreadable:e}=iy(ry());return e?{installed:[],configured:null}:{installed:await sy(),configured:iP(r)}}async function ay(){let r=await sy();return r.length?oP(ry(),r,ny()):{ok:!1,error:"Ollama is not running (or has no models installed)"}}function oP(r,e,t){let{json:n,unreadable:s}=iy(r);if(s)return{ok:!1,error:`could not parse ${r} \u2014 edit the ollama provider there yourself`};let i={...n??{},providers:{...ku(n)??{},ollama:{baseUrl:`${t}/v1`,api:"openai-completions",apiKey:"ollama",models:e.map(o=>({id:o}))}}};try{rP(Io.dirname(r),{recursive:!0}),tP(r,JSON.stringify(i,null,2)+`
|
|
1553
|
+
`)}catch(o){return{ok:!1,error:`could not write ${r}: ${J(o)}`}}return{ok:!0,count:e.length}}var sP,ry,ny,cy=v(()=>{xt();$r();sP=1500,ry=()=>Io.join(nP(),".pi","agent","models.json"),ny=()=>Ar(process.env.OLLAMA_HOST??"http://localhost:11434")});var uy={};Fu(uy,{attach:()=>mP,breakout:()=>xg,composerFiles:()=>bP,composerNew:()=>yP,composerPaste:()=>SP,composerPasteRead:()=>kP,composerRpc:()=>vP,composerSend:()=>hP,composerStop:()=>gP,composerUiRespond:()=>wP,displayName:()=>aP,downloadSample:()=>Mg,git:()=>je,gitChangedFiles:()=>lg,gitDiff:()=>ug,info:()=>cP,launchBulb:()=>Og,listBreakouts:()=>Eg,listBulbFiles:()=>Tg,listMyBulbs:()=>Dg,listSamples:()=>Lg,listSessions:()=>dP,logEmbedStatus:()=>uP,ollamaOffer:()=>oy,ollamaSync:()=>ay,openFile:()=>kg,poll:()=>lP,predictTrustOf:()=>Cg,pullRemoteBulb:()=>Bg,pushLocalBulb:()=>Fg,readBulbLog:()=>_g,repoRoot:()=>Mr,searchBulbs:()=>Pg,searchSessions:()=>fP,sessionPeek:()=>pP,setBulbTrust:()=>Rg,shutdownComposer:()=>xP,stopBreakout:()=>Ag});var ly,aP,cP,lP,uP,dP,fP,pP,mP,hP,gP,yP,bP,wP,vP,SP,kP,xP,dy=v(()=>{cu();iu();hu();vo();cy();ly=new Lr,aP=ly.displayName,{info:cP,poll:lP,logEmbedStatus:uP,listSessions:dP,searchSessions:fP,sessionPeek:pP,attach:mP,composerSend:hP,composerStop:gP,composerNew:yP,composerFiles:bP,composerUiRespond:wP,composerRpc:vP,composerPaste:SP,composerPasteRead:kP,shutdownComposer:xP}=To(ly)});import*as ub from"fs/promises";import*as tr from"path";ds();import*as Gu from"path";var zo=5e3;function zu(r){let t={subcommand:"run",file:"",port:3e3,watch:!0,open:!(process.env.TERM_PROGRAM==="vscode"),server:!1,trust:!1,noTrust:!1,force:!1,follow:!1,clear:!1,help:!1,version:!1,callArgs:[],hasArgsFlag:!1},n=["call","check","predict","logs","wait","stop","trust","untrust","skill","models","send","pull","push"],s=r[0];if(s==="agent"||s?.startsWith("agent:")){t.subcommand="agent";let o=s.indexOf(":");if(o!==-1){let a=s.slice(o+1);a&&(t.agentTarget=a)}r=r.slice(1)}else s&&n.includes(s)&&(t.subcommand=s,r=r.slice(1));let i=[];for(let o=0;o<r.length;o++){let a=r[o];if(a==="--help"||a==="-h")t.help=!0;else if(a==="--version"||a==="-V")t.version=!0;else if(a==="--no-watch")t.watch=!1;else if(a==="--open")t.open=!0;else if(a==="--no-open")t.open=!1;else if(a==="--server")t.server=!0;else if(a==="--trust")t.trust=!0;else if(a==="--no-trust")t.noTrust=!0;else if(a==="--force")t.force=!0;else if(a==="--mode"){let c=r[++o];(!c||c.startsWith("-"))&&(console.error("Missing value for --mode (e.g. --mode staging)"),process.exit(1)),t.mode=c}else if(a==="--dir"){let c=r[++o];(!c||c.startsWith("-"))&&(console.error("Missing value for --dir (a subfolder of the bulb's folder, e.g. --dir batch2)"),process.exit(1));let l=c.replace(/[\\/]+$/,"");(!l||Gu.isAbsolute(l)||l.split(/[\\/]/).some(f=>f===""||f===".."))&&(console.error(`Invalid --dir value: ${c} (a relative subfolder of the bulb's folder \u2014 no absolute paths or '..')`),process.exit(1)),t.dir=l}else if(a==="--follow"||a==="-f")t.follow=!0;else if(a==="--clear")t.clear=!0;else if(a==="--run"){let c=r[++o];if(c==="latest")t.run="latest";else{let l=parseInt(c,10);(isNaN(l)||l<1)&&(console.error(`Invalid --run value: ${c} (a run number, or 'latest')`),process.exit(1)),t.run=l}}else if(a==="--bulbs")t.stopScope="bulbs";else if(a==="--agent")t.stopScope="agent";else if(a==="--global")t.stopScope="global";else if(a==="--match"){let c=r[++o];c===void 0&&(console.error("Missing value for --match (a literal substring new log lines must contain)"),process.exit(1)),t.match=c}else if(a==="--timeout"){let c=parseInt(r[++o],10);(isNaN(c)||c<=0)&&(console.error(`Invalid --timeout value: ${r[o]} (seconds)`),process.exit(1)),t.timeoutSec=c}else if(a==="--wait"||a.startsWith("--wait="))if(a.startsWith("--wait=")){let c=parseInt(a.slice(7),10);(isNaN(c)||c<=0)&&(console.error(`Invalid --wait value: ${a.slice(7)} (milliseconds)`),process.exit(1)),t.sendWaitMs=c}else t.sendWaitMs=zo;else if(a==="--lines"||a==="-n"){let c=parseInt(r[++o],10);(isNaN(c)||c<0)&&(console.error(`Invalid --lines value: ${r[o]}`),process.exit(1)),t.lines=c}else if(a==="--port"||a==="-p"){let c=r[++o],l=parseInt(c,10);isNaN(l)&&(console.error(`Invalid port: ${c}`),process.exit(1)),t.port=l}else if(a==="--replace"||a.startsWith("--replace=")){let c=a.startsWith("--replace=")?a.slice(10):r[++o]??"";try{let l=Wu(c);if(t.local)throw new Error(`--replace can only be used once (got '${t.local.name}' and '${l.name}')`);t.local=l}catch(l){console.error(l instanceof Error?l.message:String(l)),process.exit(1)}}else if(a==="--args"||a.startsWith("--args=")){t.hasArgsFlag=!0;let c=a.startsWith("--args=")?a.slice(7):r[++o];c===void 0&&(console.error("Missing value for --args (a JSON array, or - to read it from stdin)"),process.exit(1)),t.argsJson=c}else if(!a.startsWith("-"))t.subcommand==="call"||t.subcommand==="send"?i.push(a):t.file=a;else{let c=t.subcommand==="call"?" (for a negative or dash-leading argument, use --args '<json-array>')":"";console.error(`Unknown option: ${a}${c}`),process.exit(1)}}return t.subcommand==="call"&&(i.length<2&&(console.error("Usage: typebulb call <file> <fn> [arg\u2026]"),process.exit(1)),t.file=i[0],t.fn=i[1],t.callArgs=i.slice(2)),t.subcommand==="send"&&(i.length<1&&(console.error("Usage: typebulb send <file> [message]"),process.exit(1)),t.file=i[0],t.sendMessage=i[1]),t}function Xu(){console.log(`
|
|
1554
|
+
typebulb - Local bulb runner for Typebulb
|
|
1867
1555
|
|
|
1868
|
-
|
|
1869
|
-
|
|
1870
|
-
|
|
1871
|
-
|
|
1872
|
-
|
|
1873
|
-
|
|
1874
|
-
|
|
1875
|
-
|
|
1876
|
-
|
|
1877
|
-
|
|
1878
|
-
|
|
1879
|
-
|
|
1880
|
-
|
|
1881
|
-
|
|
1882
|
-
|
|
1883
|
-
|
|
1884
|
-
|
|
1885
|
-
|
|
1886
|
-
|
|
1887
|
-
|
|
1888
|
-
|
|
1889
|
-
|
|
1890
|
-
|
|
1891
|
-
|
|
1892
|
-
|
|
1893
|
-
|
|
1894
|
-
|
|
1895
|
-
|
|
1896
|
-
|
|
1897
|
-
|
|
1898
|
-
|
|
1899
|
-
|
|
1556
|
+
Usage:
|
|
1557
|
+
typebulb [file.bulb.md] Run a bulb (defaults to .bulb.md in cwd)
|
|
1558
|
+
typebulb agent An agent's first command \u2014 auto-detects the calling
|
|
1559
|
+
harness, brings up the agent mirror without opening a
|
|
1560
|
+
browser, prints its URL and the authoring-skill paths.
|
|
1561
|
+
Always exits 0 (a status report).
|
|
1562
|
+
typebulb agent:{claude|pi} Open a named harness's mirror in the foreground (a browser
|
|
1563
|
+
view of your coding agent's sessions) \u2014 explicit / override.
|
|
1564
|
+
typebulb skill Print this README as an Agent Skill (stdout), for the
|
|
1565
|
+
agent to read and copy into its own skills folder.
|
|
1566
|
+
typebulb call <file> <fn> [\u2026] Invoke one server.ts export headlessly: prints
|
|
1567
|
+
its return as JSON to stdout, logs/errors to
|
|
1568
|
+
stderr. Gated by trust like --server. Args after
|
|
1569
|
+
<fn> are JSON-or-string; --args '<json-array>'
|
|
1570
|
+
(or --args - for stdin) is the escape hatch.
|
|
1571
|
+
typebulb check [file.bulb.md] Type-check a bulb without running it
|
|
1572
|
+
typebulb predict [file] Report the capability a bulb probably needs
|
|
1573
|
+
(fs / AI / server.ts) without running it.
|
|
1574
|
+
typebulb models List AI models for tb.ai, filtered by the API
|
|
1575
|
+
keys in your .env (the exact ids to pass).
|
|
1576
|
+
typebulb logs [file|agent] Print a running bulb server's (or the 'agent' mirror's) console
|
|
1577
|
+
(no arg: list this project's running servers;
|
|
1578
|
+
--run latest|N shows just one hot-reload run;
|
|
1579
|
+
--clear empties it). For agents: fetch
|
|
1580
|
+
tb.server.log / errors of a bulb you launched
|
|
1581
|
+
without watching its terminal.
|
|
1582
|
+
typebulb send <file> [msg] Push a message into a running bulb's page \u2014
|
|
1583
|
+
its tb.onMessage(cb) handlers receive it. The
|
|
1584
|
+
client-side twin of 'call'; msg is JSON-or-
|
|
1585
|
+
string, omit it for a bare trigger. No --trust.
|
|
1586
|
+
With --wait, a handler's non-undefined return
|
|
1587
|
+
prints on stdout (JSON; a bare string raw).
|
|
1588
|
+
msg 'tb:snapshot' instead prints the page's
|
|
1589
|
+
rendered outline (roles, names, visible text).
|
|
1590
|
+
typebulb pull <url|file> Fetch a bulb from typebulb.com into
|
|
1591
|
+
typebulbs/u/<user>/<slug>.bulb.md (a local file
|
|
1592
|
+
at that path re-pulls in place). Unlisted and
|
|
1593
|
+
public bulbs need no login; a differing local
|
|
1594
|
+
file is refused unless --force.
|
|
1595
|
+
typebulb push <file> Upload a typebulbs/u/<user>/<slug>.bulb.md to
|
|
1596
|
+
typebulb.com as you (needs TYPEBULB_TOKEN in
|
|
1597
|
+
.env, minted on the settings page). Refused if
|
|
1598
|
+
the remote changed since your last pull/push,
|
|
1599
|
+
unless --force. A new slug is created unlisted.
|
|
1600
|
+
typebulb wait [file|agent] Block until the target server logs a new line,
|
|
1601
|
+
print it, exit (2: timeout; 3: server died).
|
|
1602
|
+
For agents: run it in the background \u2014 the exit
|
|
1603
|
+
is your wake-up ('wait agent': embed outcomes;
|
|
1604
|
+
'wait <file>': the bulb's own console.log).
|
|
1605
|
+
Resumes where your last wait/call left off, so
|
|
1606
|
+
an event that beats the wait still fires it.
|
|
1607
|
+
typebulb stop [file|pid|agent] Stop a running bulb or mirror (no arg: list this
|
|
1608
|
+
project's running servers; a pid/path/agent stops any).
|
|
1609
|
+
Batch flags: --bulbs (this project's bulbs, the
|
|
1610
|
+
mirror survives), --agent (this project's mirror),
|
|
1611
|
+
--global (every bulb + mirror, all projects).
|
|
1612
|
+
typebulb trust [file] Remember a bulb as Trusted, so a later run grants
|
|
1613
|
+
fs/AI/server.ts without --trust (no arg: list the
|
|
1614
|
+
remembered-trusted bulbs).
|
|
1615
|
+
typebulb untrust <file> Forget a bulb's trust (back to Restricted).
|
|
1616
|
+
|
|
1617
|
+
Options:
|
|
1618
|
+
-f, --follow Stream new log output until interrupted (logs)
|
|
1619
|
+
--run <latest|N> Show only one hot-reload run's output: 'latest'
|
|
1620
|
+
(the current run) or run number N (logs)
|
|
1621
|
+
--clear Empty the target server's log instead of
|
|
1622
|
+
printing it, for a clean run (logs)
|
|
1623
|
+
-n, --lines <n> Print only the last n lines (logs)
|
|
1624
|
+
--match <substring> Only lines containing this literal substring end
|
|
1625
|
+
the wait \u2014 not a regex (wait)
|
|
1626
|
+
--force Overwrite the side the command writes to: a
|
|
1627
|
+
differing local file (pull), or a remote that
|
|
1628
|
+
changed since your last sync (push)
|
|
1629
|
+
--timeout <sec> Give up after this long; exit 2 \u2014 bounds only a
|
|
1630
|
+
manual (foreground) bulb wait, default 1800 (wait)
|
|
1631
|
+
--wait[=ms] For 'send': bound the whole exchange \u2014 retry while
|
|
1632
|
+
no page is connected (a hot reload's gap), then
|
|
1633
|
+
hold for the handlers' replies (default 5000).
|
|
1634
|
+
Use it right after an edit, and for any send
|
|
1635
|
+
whose reply you read.
|
|
1636
|
+
--no-watch Disable hot reload (watch is on by default)
|
|
1637
|
+
-p, --port <port> Use a specific port (default: 3000)
|
|
1638
|
+
--open Force-open the external browser (default off
|
|
1639
|
+
inside VS Code's integrated terminal)
|
|
1640
|
+
--no-open Don't auto-open browser
|
|
1641
|
+
--trust Grant privileged capabilities (filesystem, AI,
|
|
1642
|
+
and server.ts) for this run. Without it a bulb runs
|
|
1643
|
+
Restricted: tb.fs / tb.ai / tb.server are blocked and
|
|
1644
|
+
the page shows the exact --trust command to unlock
|
|
1645
|
+
them. A bulb remembered via 'typebulb trust' runs
|
|
1646
|
+
trusted without this flag.
|
|
1647
|
+
--no-trust Force a Restricted run even if the bulb is
|
|
1648
|
+
remembered-trusted (overrides the trust store).
|
|
1649
|
+
--mode <name> Also load .env.<name> (+ .env.<name>.local) on top
|
|
1650
|
+
of .env / .env.local. Free-form name; loads no mode
|
|
1651
|
+
file by default.
|
|
1652
|
+
--dir <sub> Scope the bulb's dir to a subfolder for this run:
|
|
1653
|
+
tb.dir and relative tb.fs paths land in
|
|
1654
|
+
<bulb-folder>/<sub>. Batch runs without touching
|
|
1655
|
+
the bulb's code (e.g. --dir batch2). Relative
|
|
1656
|
+
subpaths only \u2014 no absolute paths or '..'.
|
|
1657
|
+
--server Run server.ts only, no web server (needs --trust)
|
|
1658
|
+
--args <json-array> For 'call': the whole argument list as one JSON
|
|
1659
|
+
array (strict). '--args -' reads it from stdin,
|
|
1660
|
+
sidestepping shell quoting.
|
|
1661
|
+
--replace <name>=<path> Replace a declared dependency with a local built
|
|
1662
|
+
package folder instead of a CDN (dev only).
|
|
1663
|
+
Applies to both run and check. Watched for
|
|
1664
|
+
rebuilds under --watch; --no-watch freezes it.
|
|
1665
|
+
e.g. --replace tensorgrad=../tensorgrad
|
|
1666
|
+
-V, --version Show version number
|
|
1667
|
+
-h, --help Show this help message
|
|
1900
1668
|
|
|
1901
|
-
|
|
1902
|
-
|
|
1903
|
-
|
|
1904
|
-
|
|
1669
|
+
Filesystem API:
|
|
1670
|
+
Bulbs can read and write local files via tb.fs:
|
|
1671
|
+
await tb.fs.read('file.txt') // UTF-8 text (throws on non-UTF-8)
|
|
1672
|
+
await tb.fs.readBytes('image.png') // raw bytes (Uint8Array)
|
|
1673
|
+
await tb.fs.write('output.html', content) // text or bytes
|
|
1905
1674
|
|
|
1906
|
-
|
|
1907
|
-
|
|
1908
|
-
|
|
1909
|
-
|
|
1910
|
-
|
|
1911
|
-
|
|
1912
|
-
foot.appendChild(retry);
|
|
1913
|
-
}
|
|
1914
|
-
}
|
|
1675
|
+
Server API:
|
|
1676
|
+
Add a **server.ts** section to run Node.js code server-side.
|
|
1677
|
+
Exported functions become callable from the browser:
|
|
1678
|
+
// in **server.ts**: export async function query(sql) { ... }
|
|
1679
|
+
// in **code.tsx**: const rows = await tb.server.query(sql)
|
|
1680
|
+
.env / .env.local load from the working directory; --mode <name> adds .env.<name>.
|
|
1915
1681
|
|
|
1916
|
-
|
|
1917
|
-
|
|
1918
|
-
|
|
1919
|
-
|
|
1920
|
-
|
|
1921
|
-
|
|
1922
|
-
|
|
1923
|
-
|
|
1682
|
+
Built-in server functions (available without a **server.ts** section):
|
|
1683
|
+
tb.server.log(...) Print to the CLI's stdout
|
|
1684
|
+
|
|
1685
|
+
AI API:
|
|
1686
|
+
Bulbs can call AI providers via tb.ai(). Set API keys in .env:
|
|
1687
|
+
ANTHROPIC_API_KEY=sk-ant-...
|
|
1688
|
+
OPENAI_API_KEY=sk-...
|
|
1689
|
+
GOOGLE_API_KEY=AIza...
|
|
1690
|
+
OPENROUTER_API_KEY=sk-or-...
|
|
1691
|
+
Set provider and model (required):
|
|
1692
|
+
TB_AI_PROVIDER=anthropic
|
|
1693
|
+
TB_AI_MODEL=claude-haiku-4-5-20251001
|
|
1694
|
+
Both can be overridden per-call: tb.ai({ provider: "openai", model: "gpt-5.4-mini", ... })
|
|
1695
|
+
Don't guess a model id \u2014 run 'typebulb models' to list the exact ids your keys cover.
|
|
1696
|
+
Optional effort level (1=low, 2=med, 3=high; omit for the model's native default):
|
|
1697
|
+
tb.ai({ ..., effort: 2 })
|
|
1698
|
+
|
|
1699
|
+
Examples:
|
|
1700
|
+
typebulb my-editor.bulb.md
|
|
1701
|
+
typebulb --no-watch --port 8080 my-editor.bulb.md
|
|
1702
|
+
typebulb .
|
|
1703
|
+
`)}wt();xn();ds();Un();Yi();iu();var $o={claude:{adapter:()=>new Rr,server:()=>Promise.resolve().then(()=>(ty(),ey))},pi:{adapter:()=>new Lr,server:()=>Promise.resolve().then(()=>(dy(),uy))}};function fy(r){return r in $o}function jr(){return Object.keys($o)}function py(){return Object.fromEntries(Object.entries($o).map(([r,e])=>[r,e.adapter]))}function my(r){return $o[r].server()}wt();import*as Pt from"path";import{spawn as VP,execSync as GP}from"child_process";import{createRequire as zP}from"module";import{existsSync as XP}from"fs";import*as ae from"fs/promises";import*as ie from"path";var xu=[{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"}],Eu=[{name:"dom"},{name:"dom.iterable"},{name:"dom.asynciterable"}];function Au(r,e){if(!e)return r.filter(s=>!s.since);let t={"5.0":0,"5.5":1},n=t[e];return r.filter(s=>!s.since||t[s.since]<=n)}var EP=`
|
|
1704
|
+
/**
|
|
1705
|
+
* Get raw data chunk from the Data tab.
|
|
1706
|
+
* @param index - Chunk index (0-based). Separate chunks with 2 blank lines.
|
|
1707
|
+
*/
|
|
1708
|
+
data(index: number): string;
|
|
1709
|
+
/**
|
|
1710
|
+
* Get data chunk parsed as JSON (handles JSON-ish with unquoted keys).
|
|
1711
|
+
* @param index - Chunk index (0-based)
|
|
1712
|
+
* @throws If chunk is not valid JSON/JSON-ish
|
|
1713
|
+
*/
|
|
1714
|
+
json<T = unknown>(index: number): T;`,AP=`
|
|
1715
|
+
/**
|
|
1716
|
+
* Get the insight data produced by the inference layer.
|
|
1717
|
+
*
|
|
1718
|
+
* Returns the parsed JSON from insight.json, populated by the inference LLM.
|
|
1719
|
+
* Use a type parameter to get typed access to the insight data.
|
|
1720
|
+
*
|
|
1721
|
+
* @returns The parsed insight JSON, or undefined if no insight is available
|
|
1722
|
+
*/
|
|
1723
|
+
insight<T = unknown>(): T | undefined;`,hy=`options: {
|
|
1724
|
+
messages: Array<{ role: "user" | "assistant"; content: string }>;
|
|
1725
|
+
system?: string;
|
|
1726
|
+
/** Reasoning effort hint: 0=minimal, 1=low, 2=med, 3=high. Mapped to each provider's native mechanism (OpenAI/OpenRouter reasoning effort, Gemini thinking budget, Anthropic adaptive thinking). 0 minimizes reasoning \u2014 a floor, not a guaranteed "off": some models still think a little at 0, and adaptive models already self-skip at 1 (low). Level 1 (low) is the sensible default for most work; reach for 0 only when you truly want minimal deliberation. Omit for the model's own default. */
|
|
1727
|
+
effort?: 0 | 1 | 2 | 3;
|
|
1728
|
+
provider?: string;
|
|
1729
|
+
model?: string;
|
|
1730
|
+
/** Enable/disable web search. Default: on for BYOK, always off for free model. */
|
|
1731
|
+
webSearch?: boolean;
|
|
1732
|
+
/** Abort the request. On abort the promise rejects / the stream ends. */
|
|
1733
|
+
signal?: AbortSignal;
|
|
1734
|
+
}`,gy=`
|
|
1735
|
+
/** A single streamed delta from \`tb.ai.stream()\`. Discriminated by \`kind\`. */
|
|
1736
|
+
type AiChunk =
|
|
1737
|
+
| { kind: "text"; text: string }
|
|
1738
|
+
| { kind: "reasoning"; text: string };
|
|
1739
|
+
`,yy=`
|
|
1740
|
+
/**
|
|
1741
|
+
* General-purpose AI call. \`tb.ai(opts)\` resolves with the full text; \`tb.ai.stream(opts)\`
|
|
1742
|
+
* returns an async iterable of {@link AiChunk} deltas you consume with \`for await\`.
|
|
1743
|
+
*
|
|
1744
|
+
* @returns Promise resolving to { text: string }
|
|
1745
|
+
* @throws On rate limit, network error, or provider error
|
|
1746
|
+
*/
|
|
1747
|
+
ai: {
|
|
1748
|
+
(${hy}): Promise<{ text: string }>;
|
|
1749
|
+
/**
|
|
1750
|
+
* Streaming counterpart of \`tb.ai()\`. Yields \`{ kind: "text" | "reasoning", text }\` deltas
|
|
1751
|
+
* as they arrive; break the loop (or abort \`signal\`) to cancel and stop the upstream.
|
|
1752
|
+
*
|
|
1753
|
+
* \`kind: "reasoning"\` deltas only arrive when you pass \`effort: 1-3\` AND use a
|
|
1754
|
+
* thinking-capable model; otherwise the stream is \`text\`-only.
|
|
1755
|
+
*
|
|
1756
|
+
* @example
|
|
1757
|
+
* let answer = "";
|
|
1758
|
+
* for await (const c of tb.ai.stream({ messages })) {
|
|
1759
|
+
* if (c.kind === "text") answer += c.text;
|
|
1760
|
+
* }
|
|
1761
|
+
*/
|
|
1762
|
+
stream(${hy}): AsyncIterable<AiChunk>;
|
|
1763
|
+
};`,by=`
|
|
1764
|
+
/**
|
|
1765
|
+
* Returns AI models available to the current user.
|
|
1766
|
+
* Models are filtered by the user's configured API keys.
|
|
1767
|
+
* If no keys are configured, returns only the courtesy model.
|
|
1768
|
+
*/
|
|
1769
|
+
models(): Promise<Array<{
|
|
1770
|
+
/** Provider protocol: "anthropic", "openai", "gemini", "openrouter" */
|
|
1771
|
+
provider: string;
|
|
1772
|
+
/** Model identifier, e.g. "claude-sonnet-4-6" */
|
|
1773
|
+
name: string;
|
|
1774
|
+
/** Human-readable display name, e.g. "Sonnet 4.6" */
|
|
1775
|
+
friendlyName: string;
|
|
1776
|
+
/** Provider display name, e.g. "Anthropic" */
|
|
1777
|
+
providerName: string;
|
|
1778
|
+
/** True on the .env-configured default model (TB_AI_PROVIDER + TB_AI_MODEL); absent otherwise */
|
|
1779
|
+
default?: boolean;
|
|
1780
|
+
}>>;
|
|
1781
|
+
/**
|
|
1782
|
+
* Whether the user's own AI keys back \`tb.ai\`. False means only the
|
|
1783
|
+
* quota-limited courtesy model is available (or no AI at all) \u2014 a bulb
|
|
1784
|
+
* making many AI calls should check this and show a "use your own keys"
|
|
1785
|
+
* notice instead of running.
|
|
1786
|
+
*/
|
|
1787
|
+
hasOwnKeys(): Promise<boolean>;`,TP="\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;",wy=`
|
|
1788
|
+
/**
|
|
1789
|
+
* The mode this bulb is running in.
|
|
1790
|
+
*
|
|
1791
|
+
* - \`'local'\` \u2014 Running via the typebulb CLI
|
|
1792
|
+
* - \`'editor'\` \u2014 Running in the typebulb.com editor
|
|
1793
|
+
* - \`'published'\` \u2014 Running as a published/standalone bulb on typebulb.com
|
|
1794
|
+
* - \`'embedded'\` \u2014 Running as a bulb embedded inside another bulb (sandboxed,
|
|
1795
|
+
* client-only: AI, filesystem, and server RPC are unavailable)
|
|
1796
|
+
*/
|
|
1797
|
+
mode: 'local' | 'editor' | 'published' | 'embedded';`,vy=`
|
|
1798
|
+
/**
|
|
1799
|
+
* Local filesystem access (CLI only).
|
|
1800
|
+
*
|
|
1801
|
+
* Relative paths resolve against the bulb's folder (\`tb.dir\` \u2014
|
|
1802
|
+
* \`<bulb-dir>/<filename-stem>/\`, created on demand), so
|
|
1803
|
+
* \`tb.fs.write('results.json')\` lands beside the bulb. \`../\` reaches sibling
|
|
1804
|
+
* bulbs' folders; everything stays confined to the project (the launch cwd).
|
|
1805
|
+
* Throws in editor/published mode.
|
|
1806
|
+
*/
|
|
1807
|
+
fs: {
|
|
1808
|
+
/** Read a file as UTF-8 text. Throws if the file is not valid UTF-8 \u2014 use readBytes for binary. */
|
|
1809
|
+
read(path: string): Promise<string>;
|
|
1810
|
+
/** Read a file as raw bytes. */
|
|
1811
|
+
readBytes(path: string): Promise<Uint8Array>;
|
|
1812
|
+
/** Write text or raw bytes to a file. Creates parent directories if needed. */
|
|
1813
|
+
write(path: string, content: string | Uint8Array): Promise<boolean>;
|
|
1814
|
+
};`,Sy=`
|
|
1815
|
+
/**
|
|
1816
|
+
* The bulb's folder \u2014 absolute path to \`<bulb-dir>/<filename-stem>/\`
|
|
1817
|
+
* (or its subfolder when the run is scoped with \`--dir\`).
|
|
1818
|
+
*
|
|
1819
|
+
* For interop only (handing a path to \`server.ts\` or a spawned tool):
|
|
1820
|
+
* \`tb.fs\` already resolves relative paths against it, so bulb code writing
|
|
1821
|
+
* its own files never needs it. CLI only \u2014 throws in editor/published/embedded mode.
|
|
1822
|
+
*/
|
|
1823
|
+
readonly dir: string;`,PP=`
|
|
1824
|
+
/**
|
|
1825
|
+
* Async value inspector for tensor-like objects.
|
|
1826
|
+
*
|
|
1827
|
+
* Materializes lazy values (like GPU tensors) and logs them with metadata.
|
|
1828
|
+
* Handles objects with \`.js()\`, \`.data()\`, \`.array()\`, \`.arraySync()\`, etc.
|
|
1829
|
+
*
|
|
1830
|
+
* @remarks
|
|
1831
|
+
* - Always use \`await\` - materialization may be async (GPU\u2192CPU readback)
|
|
1832
|
+
* - Large values are truncated (max 1000 elements)
|
|
1833
|
+
* - Promises are logged as \`[Promise]\` (not awaited - could hang)
|
|
1834
|
+
*/
|
|
1835
|
+
dump(...args: any[]): Promise<void>;
|
|
1836
|
+
/**
|
|
1837
|
+
* Trigger inference to generate new insight data.
|
|
1838
|
+
*
|
|
1839
|
+
* Opens a confirmation modal showing the data to be analyzed, then streams
|
|
1840
|
+
* the inference result. On success, updates the insight so subsequent
|
|
1841
|
+
* \`tb.insight()\` calls return the new value.
|
|
1842
|
+
*
|
|
1843
|
+
* @param opts - Options for inference
|
|
1844
|
+
* @param opts.data - Data to pre-populate in the modal (string or array of strings). If omitted, modal opens with empty textarea for user to paste.
|
|
1845
|
+
* @returns Promise that resolves with the parsed insight JSON
|
|
1846
|
+
* @throws If inference is already in progress, or on network/parse/rate limit errors
|
|
1847
|
+
*/
|
|
1848
|
+
infer<T = unknown>(opts?: { data?: string | string[] }): Promise<T>;
|
|
1849
|
+
/**
|
|
1850
|
+
* Get the current inference state.
|
|
1851
|
+
*
|
|
1852
|
+
* @returns 'idle' | 'running' | 'complete' | 'error'
|
|
1853
|
+
*/
|
|
1854
|
+
inferenceState(): 'idle' | 'running' | 'complete' | 'error';
|
|
1855
|
+
/**
|
|
1856
|
+
* Set a data chunk for the next inference call.
|
|
1857
|
+
*
|
|
1858
|
+
* Use this to programmatically set data that will be sent when \`tb.infer()\` is called
|
|
1859
|
+
* without the \`data\` option.
|
|
1860
|
+
*
|
|
1861
|
+
* @param index - The chunk index (0-based)
|
|
1862
|
+
* @param content - The content for this chunk
|
|
1863
|
+
*/
|
|
1864
|
+
setData(index: number, content: string): void;
|
|
1865
|
+
/**
|
|
1866
|
+
* Proxy a CDN URL through the sandbox origin for Web Worker/WASM same-origin loading.
|
|
1867
|
+
*
|
|
1868
|
+
* In the sandbox, prepends \`/proxy/\` so the URL is served from the same origin.
|
|
1869
|
+
* Outside the sandbox (exported HTML, CLI), returns the URL unchanged.
|
|
1870
|
+
*
|
|
1871
|
+
* @param url - Full HTTPS URL to an allowlisted CDN (esm.sh, unpkg.com, cdn.jsdelivr.net, cdnjs.cloudflare.com)
|
|
1872
|
+
* @returns The proxied URL (sandbox) or the original URL (standalone/CLI)
|
|
1873
|
+
*/
|
|
1874
|
+
proxy(url: string): string;
|
|
1875
|
+
/**
|
|
1876
|
+
* Copy text to clipboard.
|
|
1877
|
+
* Must be called synchronously within a user gesture (click/keydown).
|
|
1878
|
+
* @returns true if successful, false otherwise
|
|
1879
|
+
*/
|
|
1880
|
+
copy(text: string): Promise<boolean>;
|
|
1881
|
+
/**
|
|
1882
|
+
* Get the canonical URL of this bulb.
|
|
1883
|
+
*
|
|
1884
|
+
* Returns the parent typebulb.com URL (including path, query, and \`#tb=\` fragment),
|
|
1885
|
+
* resolving correctly from inside the cross-origin sandbox iframe.
|
|
1886
|
+
* Use this instead of \`location.href\` or \`document.referrer\`.
|
|
1887
|
+
*
|
|
1888
|
+
* @returns The full canonical URL
|
|
1889
|
+
*/
|
|
1890
|
+
url(): Promise<string>;`,OP="\n /**\n * Subscribe to a value pushed from the terminal via `typebulb send <file> [message]`.\n *\n * The dual of `tb.server.log` (data out): a value sent *in* from the CLI, no `--trust` required.\n * Use it to start expensive work on demand instead of on load \u2014 e.g. `tb.onMessage(() => start())`\n * \u2014 so hot reloads don't re-trigger it while you edit, and an agent kicks off one run when ready.\n *\n * The message is the JSON-parsed value of what `send` was given (or the raw string if it isn't\n * JSON; `undefined` for a bare `typebulb send <file>`). A non-`undefined` return value (awaited)\n * becomes the reply `send --wait` prints on stdout \u2014 JSON-serializable, at most one handler\n * replying \u2014 the structured read-back for self-tests. Returns an unsubscribe function. Inert in\n * an embedded bulb (no sender) \u2014 the handler is registered but never fires.\n *\n * @param handler - Called with each pushed message; may return a JSON-serializable reply.\n * @returns An unsubscribe function.\n */\n onMessage(handler: (message: any) => unknown): () => void;",CP="\n /**\n * Server-side function proxy.\n *\n * In the CLI, calls exported functions from the `**server.ts**` section.\n * `tb.server.log(...)` is a built-in that prints to CLI stdout (falls back to console.log on web).\n * User exports override built-ins of the same name.\n *\n * A normal export is awaited for its result (`await tb.server.fn()`). An `async function*`\n * export streams: `for await (const chunk of tb.server.gen())`. The call object supports both;\n * break the `for await` to cancel and tear down the server generator.\n */\n server: Record<string, (...args: any[]) => Promise<any> & AsyncIterable<any>>;",Tu=`${gy}
|
|
1891
|
+
/**
|
|
1892
|
+
* Typebulb utilities namespace.
|
|
1893
|
+
* Type \`tb.\` to discover available helpers.
|
|
1894
|
+
*/
|
|
1895
|
+
declare const tb: {${EP}${PP}${AP}${CP}${OP}${yy}${vy}${Sy}${by}${TP}${wy}
|
|
1896
|
+
};
|
|
1897
|
+
`,Pu=`${gy}
|
|
1898
|
+
/**
|
|
1899
|
+
* Typebulb utilities namespace (server-side).
|
|
1900
|
+
* Type \`tb.\` to discover available helpers.
|
|
1901
|
+
*/
|
|
1902
|
+
declare const tb: {${yy}${vy}${Sy}${by}${wy}
|
|
1903
|
+
};
|
|
1904
|
+
`;He();import IP from"p-limit";He();import{resolve as xy}from"resolve.exports";var Ze={maxRelativeTypeRefs:500,maxBareDeps:8,maxBareDepth:3,prefetchConcurrency:4,negativeTtlMs:1e4},ns=["index.d.ts","index.d.mts"],Ou=/\.d\.(ts|mts|cts)$/i;function Lo(r){return/\.d\.(ts|mts|cts)(?:[?#].*)?$/i.test(r)||/[?&]dts(?:[&#]|$)/i.test(r)}function ky(r){return[`${r}.d.ts`,`${r}.d.mts`]}function Tt(r){if(!r||r==="./"||r==="/")return[...ns];let e=r.replace(/\.(mjs|cjs|js|mts|cts|ts)$/i,""),t=ky(e),n=e.endsWith("/")?e:`${e}/`;return t.push(...ky(`${n}index`)),t}async function Fr(r,{retries:e=2,timeoutMs:t=15e3,init:n}={}){for(let s=0;s<=e;s++){let i=new AbortController,o=setTimeout(()=>i.abort(),t);try{let a=await fetch(r,{...n,signal:i.signal});if(RP(a.status)&&s<e)continue;return a}catch{if(s<e)continue;return}finally{clearTimeout(o)}}}function RP(r){return r===408||r===429||r>=500&&r<600}var Mo=class{constructor(e,t){this.fetchDts=e,this.cdnClient=t}async tryUrls(e){for(let t of e){let n=await this.fetchDts(t);if(n&&(this.looksLikeDts(n.dts)||Lo(n.url)))return n}}looksLikeDts(e){return/^\s*export\s*\{\s*\}\s*;?\s*$/m.test(e)?!0:/declare\s+(module|namespace|class|interface|function|const|var|let)/.test(e)||/interface\s+\w+/.test(e)||/type\s+\w+\s*=/.test(e)}async loadPackageAtVersionedRoot(e,t){let n=this.cdnClient.packageJson(new B({name:e,version:t})),s=await Fr(n);if(!s?.ok)return;let i;try{i=await s.json()}catch{return}if(i)return{pkg:i,baseDir:this.cdnClient.baseDir(new B({name:e,version:t??i.version})),version:t}}extractPathFromResult(e){if(typeof e=="string")return e;if(Array.isArray(e))return e.find(t=>typeof t=="string")}async tryUntilSuccess(e,t){for(let n of e){let s=await t(n);if(s)return s}}async resolveFromSelected(e,t,n){if(e.kind==="types"){let o=Bt(e.path);if(!o||o==="/"||o===".")return this.tryUntilSuccess([...ns],t);if(!Ou.test(o)){let a=await this.tryUntilSuccess(Tt(o),t);if(a)return a}return t(o)}let s=Tt(e.path),i=n?.subpath?[...s,...ns]:[...ns,...s];return this.tryUntilSuccess(i,t)}toResolutionResult(e){return{kind:Ou.test(e)?"types":"probe",path:e}}resolveExportsPath(e,t){let n=t||".",s=e;try{let i=this.extractPathFromResult(xy(s,n,{conditions:["types"]}));if(i)return i}catch{}try{return this.extractPathFromResult(xy(s,n,{browser:!0,conditions:["import","default","module","browser","node"]}))}catch{return}}async resolve(e){try{let t=B.parse(e),{pkg:n,baseDir:s}=await this.loadPackageAtVersionedRoot(t.name,t.version)||{};if(!n||!s)return;let i={name:t.name,version:t.version},o=new B(i).format(),a=new B({...i,subpath:t.subpath}).format(),c=u=>this.fetchCandidateFrom(s,t.name,u);if(t.subpath){let u=Hc(t.subpath),d=this.resolveExportsPath(n,u);if(d){let b=await this.resolveFromSelected(this.toResolutionResult(d),c,{subpath:!0});if(b)return{...b,resolvedPkg:a}}let p=await this.tryUntilSuccess(Tt(u),c);if(p)return{...p,resolvedPkg:a}}let l=n.types??n.typings;if(l){let u=await this.resolveFromSelected({kind:"types",path:l},c);if(u)return{...u,resolvedPkg:o}}let f=this.resolveExportsPath(n,".");if(f){let u=await this.resolveFromSelected(this.toResolutionResult(f),c);if(u)return{...u,resolvedPkg:o}}return}catch{return}}async fetchCandidateFrom(e,t,n){let s=Bt(n),i=new URL(s,e).toString(),o=await this.tryUrls([i]);return o?{dts:o.dts,url:o.url,resolvedPkg:t}:void 0}};He();import{gunzipSync as _P}from"fflate";var Do=class{async fetchAndExtract(e,t){let n=this.getTarballUrl(e,t),s=await Fr(n,{timeoutMs:3e4});if(!s?.ok)return new Map;let i=new Uint8Array(await s.arrayBuffer());return this.extractDtsFiles(i)}getTarballUrl(e,t){return`https://registry.npmjs.org/${e.replace("/","%2F")}/-/${e.split("/").pop()}-${t}.tgz`}normalizeTarPath(e){let t=e.replace(/^package\//,""),n=t.indexOf("/");return n>0?t.substring(n+1):t}extractDtsFiles(e){let t=new Map;try{let n=_P(e),s=new TextDecoder("utf-8"),i=0;for(;i<n.length-512;){let o=n.slice(i,i+512);if(o[0]===0)break;let a=o.slice(0,100),c=a.indexOf(0),l=s.decode(a.slice(0,c>0?c:100)).trim(),f=o.slice(124,136),u=s.decode(f).trim().replace(/\0/g,""),d=parseInt(u,8)||0,p=String.fromCharCode(o[156]);if(i+=512,(p==="0"||p==="\0")&&(l.endsWith(".d.ts")||l.endsWith(".d.mts"))){let b=n.slice(i,i+d);t.set(this.normalizeTarPath(l),s.decode(b))}i+=Math.ceil(d/512)*512}}catch{}return t}};var Bo=class{constructor(e,t,n=new Do){this.cdnClient=e,this.cache=t,this.tarballFetcher=n}typesNameCandidates(e){let t=e.startsWith("@")?e.slice(1).replace("/","__"):e;return t.includes(".")?[t,t.split(".").join("-"),t.split(".").join("")]:[t]}selectTypesVersion(e,t,n){try{if(n){let i=jt.majorOf(n),o=e.filter(a=>jt.majorOf(a)===i);if(o.length)return o.sort((a,c)=>jt.cmp(c,a))[0]}let s=t?.latest;return s&&e.includes(s)?s:e[0]}catch{return e[0]}}subpathCandidates(e){let t=e.replace(/\.(mjs|cjs|js|mts|cts|ts)$/i,""),n=Tt(e);return t!==e&&n.push(`${e}.d.ts`,`${e}/index.d.ts`),n}async fetchFromVersionedRoot(e,t){let n=new B(e),s=n.version;if(!s)return;let i;try{i=await this.tarballFetcher.fetchAndExtract(n.name,s)}catch{return}if(!i||i.size===0)return;for(let[a,c]of i.entries()){let l=this.cdnClient.file(e,a);try{await this.cache.setCachedFile(l,c)}catch{}}let o=t.subpath?this.subpathCandidates(t.subpath):["index.d.ts"];for(let a of o){let c=i.get(a);if(c)return{dts:c,url:this.cdnClient.file(e,a),resolvedPkg:t.subpath?new B(t).format():t.name}}}async resolve(e){let t=B.parse(e);if(t.name)for(let n of this.typesNameCandidates(t.name)){let s=`@types/${n}`,i;try{i=await this.cdnClient.fetchVersionsIndex(s)}catch{continue}if(!i?.versions?.length)continue;let o=this.selectTypesVersion(i.versions,i.distTags,t.version),a=await this.fetchFromVersionedRoot(`${s}@${o}`,t);if(a)return a}}};var jo=class{collectRelativeTypeRefs(e){return this.collectRefs(e).filter(t=>t.startsWith("./")||t.startsWith("../"))}collectBareModuleRefs(e){return this.collectRefs(e).filter(t=>this.isBare(t))}collectRefs(e){let t=e.split(`
|
|
1905
|
+
`).filter(s=>{let i=s.trimStart();return!(i.startsWith("*")||i.startsWith("//")||i.startsWith("/*"))}).join(`
|
|
1906
|
+
`),n=new Set;for(let s of t.matchAll(/(import|export)\s+[^'"\n]*from\s*['"]([^'"\n]+)['"]/g))n.add(s[2]);for(let s of t.matchAll(/export\s*\*\s*from\s*['"]([^'"\n]+)['"]/g))n.add(s[1]);return Array.from(n)}isBare(e){return!(e.startsWith("./")||e.startsWith("../")||e.startsWith("file:")||e.startsWith("http://")||e.startsWith("https://"))}};He();var Ey="file:///node_modules",Fo=class{constructor(){this.epoch=0}bumpEpoch(){this.epoch+=1}epochDir(){return`__tsepoch_${this.epoch}`}pathForMain(e){return`${Ey}/${this.epochDir()}/${e}/index.d.ts`}pathFor(e,t){let n=Bt(t);return`${Ey}/${this.epochDir()}/${e}/${n}`}};import{LRUCache as NP}from"lru-cache";function Ay(r){let e=new NP({ttl:Ze.negativeTtlMs,max:500}),t=new Map;return async function(s){try{if(await r.isNegative(s)||e.has(s))return;let i=await r.getCachedFile(s);if(i)return{dts:i,url:s};let o=t.get(s);if(o)return o;let a=(async()=>{let c=await Fr(s,{init:{cache:"no-store"}});if(!c?.ok){c?.status===404&&(e.set(s,!0),await r.recordNegative(s));return}let l=await c.text(),f=c.url||s;return await r.clearNegative(s),await r.setCachedFile(f,l),{dts:l,url:f}})();return t.set(s,a),await a.finally(()=>t.delete(s))}catch{return}}}var ss=class{constructor(e){this.inFlight=new Map,this.scanner=new jo,this.cache=e.cache,this.cdnClient=e.cdnClient,this.versionResolver=e.versionResolver,this.packageService=e.packageService,this.fetchDts=Ay(e.cache),this.typescriptProvider=new Mo(this.fetchDts,e.cdnClient),this.definitelyTypedProvider=new Bo(e.cdnClient,e.cache),this.virtualFs=new Fo}withInFlight(e,t){let n=this.inFlight.get(e);if(n)return n;let s=t().finally(()=>this.inFlight.delete(e));return this.inFlight.set(e,s),s}invalidate(){this.virtualFs.bumpEpoch(),this.inFlight.clear()}pushFileIfNew(e,t,n){e.some(s=>s.path===t)||e.push({path:t,content:n})}createStubDef(e){let t=this.virtualFs.pathForMain(e);return{pkg:e,mainPath:t,files:[{path:t,content:"export const _shim: any; export default _shim;"}],shims:[{module:e,path:t}]}}async fetchViaProviders(e){for(let t of[this.typescriptProvider,this.definitelyTypedProvider])try{let n=await t.resolve(e);if(n?.dts)return n}catch{}}async fetchRootDts(e,t){let{effectivePackage:n,root:s,pinned:i}=await this.versionResolver.effectivePackage(e,t),o=await this.cache.getCachedDts(n);if(o?.content){let c=o.url??this.cdnClient.file(i?`${s}@${i}`:s,"index.d.ts");return{dts:o.content,url:c,resolvedPkg:n}}let a;try{a=await this.fetchViaProviders(n)}catch{return}if(!(!a?.dts||!a.url)&&new B(n).subpath===new B(a.resolvedPkg||n).subpath){try{await this.cache.setCachedDts(n,a.dts,a.url)}catch{}return a}}extractPackageRootUrl(e){let t=e.pathname.match(/^(.+@[^/]+\/)/);return t?new URL(t[1],e.origin):new URL("./",e)}toVirtualPath(e,t,n){let s=t.pathname.startsWith(e.pathname)?t.pathname.slice(e.pathname.length):`__deps__/${encodeURIComponent(t.toString()).replace(/%/g,"_")}.d.ts`;return this.virtualFs.pathFor(n,s)}computeEntryPath(e,t){if(!e)return{mainPath:this.virtualFs.pathForMain(t),packageRootUrl:void 0};let n=new URL(e),s=this.extractPackageRootUrl(n);return{mainPath:this.toVirtualPath(s,n,t),packageRootUrl:s}}async expandRelativeRefs(e,t,n,s,i=new Set,o){if(!i.has(t)&&(i.add(t),!(i.size>Ze.maxRelativeTypeRefs)))try{let a=new URL(t),c=new URL("./",a);o??(o=this.extractPackageRootUrl(a));let l=this.scanner.collectRelativeTypeRefs(e).slice(0,Ze.maxRelativeTypeRefs);for(let f of l)await this.tryRelativeRef(f,c,o,n,s,i)}catch{}}async tryRelativeRef(e,t,n,s,i,o){try{let a=new URL(e,t),c=a.pathname+a.search,l=Lo(c)?[c]:Tt(c);for(let f of l){let d=new URL(f,a).toString();if(o.has(d))return;let p=await this.fetchDts(d);if(p?.dts){let b=this.toVirtualPath(n,new URL(p.url),s);this.pushFileIfNew(i,b,p.dts),await this.expandRelativeRefs(p.dts,p.url,s,i,o,n);return}}}catch{}}isDifferentPackage(e,t){return e===t?!1:new B(e).name!==new B(t).name}ambientlyDeclares(e,t){if(/^(?:import|export)\b/m.test(e))return!1;for(let n of e.matchAll(/declare\s+module\s+['"]([^'"]+)['"]/g)){let s=n[1];if(s===t||s.endsWith("/*")&&t.startsWith(s.slice(0,-1)))return!0}return!1}markFileAmbient(e,t){let n=e.find(s=>s.path===t);n&&(n.ambient=!0)}async prefetchBareDeps(e,t,n,s,i){try{let o=this.scanner.collectBareModuleRefs(e).slice(0,Ze.maxBareDeps).filter(l=>this.isDifferentPackage(l,t));if(!o.length)return;let a=new Set([t]),c=IP(Ze.prefetchConcurrency);await Promise.all(o.map(l=>c(()=>this.prefetchBareDepsRecursive(l,n,s,Ze.maxBareDepth,a,i).catch(()=>{}))))}catch{}}async prefetchBareDepsRecursive(e,t,n,s,i,o){if(s<=0||i.has(e))return;i.add(e);let a=await this.fetchRootDts(e,o);if(!a?.dts)return;let c=a.resolvedPkg||e,l=this.virtualFs.pathForMain(c);this.pushFileIfNew(t,l,a.dts),this.ambientlyDeclares(a.dts,e)?this.markFileAmbient(t,l):n.push({module:e,path:l}),a.url&&await this.expandRelativeRefs(a.dts,a.url,c,t);let f=this.scanner.collectBareModuleRefs(a.dts).slice(0,Ze.maxBareDeps).filter(u=>!i.has(u));for(let u of f)await this.prefetchBareDepsRecursive(u,t,n,s-1,i,o)}async resolve(e,t,n){let s=await this.packageService.extractImports(e),i=n?[...s,...n]:s;return(await Promise.all(i.map(a=>this.resolveOne(a,t)))).filter(a=>!!a)}async resolveOne(e,t){let{effectivePackage:n}=await this.versionResolver.effectivePackage(e,t);return this.withInFlight(n,async()=>{let s=new B(e),i=await this.fetchRootDts(e,t)??(s.subpath?await this.fetchRootDts(s.name,t):void 0);return i?this.buildDefFromContent(e,i,i.resolvedPkg||e,t):this.createStubDef(e)})}async buildDefFromContent(e,t,n,s){let{dts:i,url:o,resolvedPkg:a}=t,c=new B(a||n),l=c.version?`${c.name}@${c.version}`:c.name,{mainPath:f,packageRootUrl:u}=this.computeEntryPath(o,l),d=[{path:f,content:i}],p=[];o&&await this.expandRelativeRefs(i,o,l,d,void 0,u);let b=d.map(A=>A.content).join(`
|
|
1907
|
+
`);await this.prefetchBareDeps(b,l,d,p,s);let m=c.format(),g=e===m?[e]:[e,m],x=g.some(A=>this.ambientlyDeclares(i,A));return x?this.markFileAmbient(d,f):p.push(...g.map(A=>({module:A,path:f}))),{pkg:e,mainPath:f,files:d,shims:p,ambient:x}}};tl();He();br();$n();Zc();yr();import*as qr from"path";var $P=qr.join(wi,"pkg"),LP=qr.join(wi,"files"),MP=qr.join(wi,"negative.json"),Uo=class{pkgMem=new Map;fileMem=new Map;negativeCache=new Ft(new wr(MP));async getCachedDts(e){if(this.pkgMem.has(e))return this.pkgMem.get(e);await G();let t=await We(Ty(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 qo(async()=>{await G(),await he(Ty(e),JSON.stringify(s))})}async getCachedFile(e){if(this.fileMem.has(e))return this.fileMem.get(e);await G();let t=await bi(Py(e));return this.fileMem.set(e,t),t}async setCachedFile(e,t){this.fileMem.set(e,t),await qo(async()=>{await G(),await he(Py(e),t)})}isNegative(e){return this.negativeCache.isNegative(e)}async recordNegative(e){await qo(async()=>{await G(),await this.negativeCache.recordNegative(e)})}clearNegative(e){return qo(()=>this.negativeCache.clearNegative(e))}};async function qo(r){try{await r()}catch{}}function Ty(r){return qr.join($P,ke(r)+".json")}function Py(r){return qr.join(LP,ke(r)+".txt")}br();var Cu;function DP(){return Cu||(Cu=new ss({cache:new Uo,cdnClient:Im,packageService:xi,versionResolver:Nm})),Cu}var Oy="file:///node_modules/";async function Cy(r){let e=vi(r.emitKey,"typecheck");await G(),await ae.rm(e,{recursive:!0,force:!0}),await ae.mkdir(e,{recursive:!0});let t=qP(r.jsxImportSource,r.dependencies),n=await DP().resolve(r.code,r.dependencies,t),s=r.local?.name,i=s?n.filter(f=>f.pkg!==s):n,o=new Set;for(let f of i)for(let u of f.files){let d=Jo(u.path);if(!d||o.has(d))continue;o.add(d);let p=ie.join(e,"node_modules",d);await ae.mkdir(ie.dirname(p),{recursive:!0}),await ae.writeFile(p,u.content,"utf8")}let a={};for(let f of i)for(let u of f.shims){let d=Jo(u.path);d&&(a[u.module]=[`./node_modules/${d}`])}for(let f of i){if(f.ambient)continue;let u=Jo(f.mainPath);u&&(a[f.pkg]=[`./node_modules/${u}`])}let c=new Set;for(let f of i)for(let u of f.files){if(!u.ambient)continue;let d=Jo(u.path);d&&c.add(`node_modules/${d}`)}if(r.local){delete a[r.local.name];let f=await UP(r.local,e);f?a[r.local.name]=[`./node_modules/${r.local.name}/${f}`]:console.warn(` local: '${r.local.name}' ships no type defs; check cannot type against it.`)}let l=BP(r.jsxImportSource,a,[...c]);return await ae.writeFile(ie.join(e,"tsconfig.json"),JSON.stringify(l,null,2)+`
|
|
1908
|
+
`,"utf8"),await ae.writeFile(ie.join(e,"code.tsx"),r.code,"utf8"),await ae.writeFile(ie.join(e,"tb.d.ts"),Tu,"utf8"),{dir:e}}var Ru={target:"es2023",module:"esnext",moduleResolution:"bundler",strict:!0,noEmit:!0,skipLibCheck:!0,esModuleInterop:!0,allowSyntheticDefaultImports:!0,forceConsistentCasingInFileNames:!0};function BP(r,e,t=[]){return{compilerOptions:{...Ru,lib:jP([...xu,...Eu]),jsx:"react-jsx",jsxImportSource:r??"react",paths:e},include:["code.tsx","tb.d.ts",...t]}}function jP(r){return Au(r).map(e=>FP(e.name))}function FP(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 qP(r,e){let t=r??("react"in e?"react":void 0);return t?[`${t}/jsx-runtime`,`${t}/jsx-dev-runtime`]:[]}function Jo(r){if(!r.startsWith(Oy))return;let e=r.slice(Oy.length),t=e.indexOf("/");if(!(t<0))return e.slice(t+1)}async function UP(r,e){if(!r.typesAbs)return;let t=ie.dirname(r.typesAbs),n=ie.join(e,"node_modules",r.name);for(let s of await JP(t)){let i=ie.join(n,ie.relative(t,s));await ae.mkdir(ie.dirname(i),{recursive:!0}),await ae.copyFile(s,i)}return ie.basename(r.typesAbs)}async function JP(r){let e=[];async function t(n){let s=await ae.readdir(n,{withFileTypes:!0});for(let i of s){let o=ie.join(n,i.name);i.isDirectory()?await t(o):/\.d\.ts(\.map)?$/.test(i.name)&&e.push(o)}}return await t(r),e}import*as be from"fs/promises";import*as et from"path";import{existsSync as KP}from"fs";br();nl();var HP="^22";async function Ry(r){let e=vi(r.emitKey,"typecheck-server");await G(),await be.rm(e,{recursive:!0,force:!0}),await be.mkdir(e,{recursive:!0});let t=et.join(r.bulbDir,".typebulb"),n=Ri(r.server).filter(o=>o!==r.local?.name);await Ci([`@types/node@${HP}`,...n],t,r.dependencies,{ignoreScripts:!0});let s=et.join(t,"node_modules"),i=et.join(e,"node_modules");return await YP(s,i),await be.writeFile(et.join(e,"server.ts"),r.server,"utf8"),await be.writeFile(et.join(e,"tb.d.ts"),Pu,"utf8"),await be.writeFile(et.join(e,"tsconfig.json"),JSON.stringify(WP(r.local),null,2)+`
|
|
1909
|
+
`,"utf8"),{dir:e}}function WP(r){let e={...Ru,lib:["ES2023"],types:["node"]};if(r?.typesAbs){let t=i=>i.replace(/\\/g,"/"),n=t(et.dirname(r.typesAbs)),s=t(r.typesAbs).replace(/\.d\.ts$/,"");e.paths={[r.name]:[s],[`${r.name}/*`]:[`${n}/*`]}}return{compilerOptions:e,include:["server.ts","tb.d.ts"]}}async function YP(r,e){if(!KP(r)){await be.mkdir(e,{recursive:!0});return}await be.rm(e,{recursive:!0,force:!0});let t=process.platform==="win32"?"junction":"dir";await be.symlink(r,e,t)}mi();async function Ny(r,e){let{bulb:t,config:n,warnings:s}=await Ae(r);!t.code&&!t.server&&(console.error("Bulb has neither **code.tsx** nor **server.ts**; nothing to check."),process.exit(1));let i=!1;for(let l of s)console.log(`structure ${l}`);s.length&&(i=!0),t.code&&(i=_y(En(t.code,{target:"client",dependencies:n.dependencies??{}}),"client")||i),t.server&&(i=_y(En(t.server,{target:"server"}),"server")||i);let o=eO([process.cwd(),Pt.dirname(r)]);if(!o){let l=Pt.relative(process.cwd(),r)||r;console.error("check: TypeScript not found \u2014 install it once, then re-run:"),console.error(" npm i -g typescript"),console.error(` typebulb check ${l}`),process.exit(2)}let a=[];if(t.code){let{dir:l}=await Cy({code:t.code,dependencies:n.dependencies??{},jsxImportSource:n.ts?.jsxImportSource,emitKey:r,local:e});a.push({role:"client",dir:l})}if(t.server){let{dir:l}=await Ry({server:t.server,bulbDir:Pt.dirname(r),emitKey:r,local:e?{name:e.name,typesAbs:e.typesAbs}:void 0,dependencies:n.dependencies});a.push({role:"server",dir:l})}for(let{role:l,dir:f}of a){let{stdout:u,exitCode:d}=await QP(o,f);for(let p of u.split(/\r?\n/))p.trim()&&console.log(`${l} ${p}`);d!==0&&(i=!0)}i&&process.exit(1);let c=[t.code&&"code.tsx",t.server&&"server.ts"].filter(Boolean).join(", ");console.error(`\u2713 no issues (${c})`)}function _y(r,e){for(let t of r)for(let n of t.message.split(`
|
|
1910
|
+
`))console.log(`${e} ${n}`);return r.length>0}function QP(r,e){return new Promise(t=>{let n=VP(process.execPath,[r,"--noEmit"],{cwd:e}),s="";n.stdout?.on("data",i=>{s+=i.toString()}),n.stderr?.on("data",i=>{s+=i.toString()}),n.on("close",i=>t({stdout:s,exitCode:i??1}))})}var ZP=zP(import.meta.url);function eO(r){let e=n=>{try{let s=ZP.resolve("typescript/package.json",{paths:n}),i=Pt.join(Pt.dirname(s),"lib","tsc.js");return XP(i)?i:void 0}catch{return}},t=e(r);if(t)return t;try{let n=GP("npm root -g",{encoding:"utf8"}).trim();return e([n])}catch{return}}wt();eo();Un();async function Iy(r,e){let{bulb:t}=await Ae(r),n=Nr(t);if(Wt(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.)")}Un();import*as is from"path";async function $y(r,e){if(!r){e||(console.error("Usage: typebulb untrust <file.bulb.md>"),process.exit(1));let n=El();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=is.resolve(r);t.endsWith(".bulb.md")||(console.error("File must have .bulb.md extension"),process.exit(1)),Or(t,e),console.log(e?`Trusted ${is.basename(t)} \u2014 runs with fs / AI / server.ts (no --trust needed).`:`Untrusted ${is.basename(t)} \u2014 runs Restricted.`),console.log(` ${t}`)}Le();import*as By from"readline";var os=py();function Ly(){for(let r of Object.values(os))try{r().ensureHarnessSupport()}catch{}}function as(){for(let r of Object.keys(os))try{if(os[r]().detectsSelf())return r}catch{}}function My(r){let e=jr(),t=new Map(e.filter(i=>os[i]).map(i=>[i,os[i]()]));for(let[i,o]of t)if(o.detectsSelf())return{name:i};let n=[...t].filter(([,i])=>i.detectsInstalled()).map(([i])=>i);if(n.length===0)return{name:e[0]};if(n.length===1)return{name:n[0]};let s=i=>t.get(i).listSessionFiles(r).length>0;return{ambiguous:[...n].sort((i,o)=>Number(s(o))-Number(s(i)))}}to();function _u(r){let e=t=>n=>r?`\x1B[${t}m${n}\x1B[0m`:n;return{lit:e("38;5;70"),litLink:e("4;38;5;70"),brand:e("38;5;135")}}async function jy(r){let e=My(process.cwd());if("ambiguous"in e){let t=await tO(r,e.ambiguous);return t?Dy(r,t):rO(r,e.ambiguous)}return Dy(r,e.name)}async function Dy(r,e){let t,n;try{t=await yh(e)}catch(f){n=f instanceof Error?f.message:String(f)}let{lit:s,litLink:i,brand:o}=_u(process.stdout.isTTY===!0),a=[" Read the authoring skill before writing a bulb:",` \u2022 ${s("npx typebulb skill")} \u2014 assembles one SKILL.md`," \u2022 or, open its parts:",` ${s(Ir())}`,` ${s(Gt())}`],c=t?[` Agent mirror (${e}) is live\u{1F4A1}`,` ${s("\u25CF")} ${i(t.url)}`," Embedded bulbs render live here."," Agents:",` Reusable app/tool \u2192 write a ${s(".bulb.md")}`," Show something inline \u2192 embed a bulb",e==="pi"?" arm a wait for its render verdict \u2014 run it plainly:":" background a wait for its render verdict:",` \u2022 ${s('typebulb wait agent --match "[embed <name>"')}`,...a," End your reply with the mirror link above"," \u2022 easy to miss the link mid-message"]:[` The mirror did not start (${n})`,` \u25CF Start it manually: ${s(`npx typebulb agent:${e}`)}`," Agents:",...a],l=[` ${o(`typebulb v${r}`)}`,...c,""];process.stdout.write(l.join(`
|
|
1911
|
+
`)+`
|
|
1912
|
+
`)}async function tO(r,e){if(!process.stdin.isTTY||!process.stdout.isTTY)return;let{lit:t,brand:n}=_u(!0),s=[` ${n(`typebulb v${r}`)}`," More than one agent harness is available here.",...e.map((o,a)=>` ${t(String(a+1))}) ${o}`),""];process.stdout.write(s.join(`
|
|
1913
|
+
`)+`
|
|
1914
|
+
`);let i=By.createInterface({input:process.stdin,output:process.stdout});try{let o=(await new Promise(c=>i.question(" Open which? [1]: ",c))).trim();if(o==="")return e[0];let a=Number(o);return Number.isInteger(a)&&a>=1&&a<=e.length?e[a-1]:e.find(c=>c===o.toLowerCase())}finally{i.close()}}function rO(r,e){let{lit:t,brand:n}=_u(process.stdout.isTTY===!0),s=[` ${n(`typebulb v${r}`)}`," More than one agent harness is available here."," Open the mirror for the one you want:",...e.map(i=>` \u2022 ${t(`npx typebulb agent:${i}`)}`),""];process.stdout.write(s.join(`
|
|
1915
|
+
`)+`
|
|
1916
|
+
`)}kt();Ht();async function Fy(r){ye(r);let e=await Ve();if(e.length>0){console.log(Vm(e,process.env.TB_AI_PROVIDER,process.env.TB_AI_MODEL));return}if(!bl()){console.log("No AI provider keys found in this directory's .env, and no local Ollama server detected."),console.log("Set one of these to use a cloud model with tb.ai:");for(let[t,n]of Object.entries(Er))console.log(` ${n.padEnd(20)} (${t})`);console.log("\u2026or start Ollama (http://localhost:11434, or set OLLAMA_HOST) for local models. Then re-run `typebulb models`.");return}console.log("Couldn't fetch the model catalog (offline?). tb.ai still works with any valid provider/model id for your keys.")}to();import*as qy from"fs/promises";async function Uy(r){let e=Gt(),t;try{t=await qy.readFile(e,"utf8")}catch{console.error(`Could not read the bundled README (expected at ${e}).`),process.exit(1)}process.stdout.write(Th(t,r))}Ui();import*as Jy from"path";Le();function nO(r,e,t,n){if(/^\d+$/.test(e))return r.find(i=>i.pid===parseInt(e,10));let s=e==="agent"?r.filter(i=>i.agent!=null):r.filter(i=>i.agent===e);if(s.length){if(!t)return s[0];let i=s.filter(o=>o.cwd&&ne(o.cwd)===ne(t));return n&&i.find(o=>o.agent===n)||i[0]}return r.find(i=>ne(i.file)===ne(e))}var cs=r=>r.agent??Jy.basename(r.file);function Ky(r,e){for(let t of r)e(` ${t.url} pid ${t.pid} ${t.trust?"trusted":"restricted"}${t.dir?` --dir ${t.dir}`:""} ${t.file}`)}function Nu(r,e){if(!r.length){console.log("No running bulb servers.");return}console.log("Running bulb servers:"),Ky(r,t=>console.log(t)),console.log(`
|
|
1917
|
+
`+e)}function Iu(r,e,t,n,s){let i=nO(r,e,n,s);if(i)return i;console.error(`No running server for '${e}'.`),r.length?(console.error(`Running servers (try \`typebulb ${t} <file|pid>\`):`),Ky(r,o=>console.error(o))):console.error("No bulb servers are running."),process.exit(1)}async function Hy(r,e){if(!r){e.clear&&(console.error("Specify which server to clear: typebulb logs --clear <file|pid>"),process.exit(1)),Nu(await Q(process.cwd()),"Run `typebulb logs <file|pid>` to print one server's console.");return}let t=Iu(await Q(),r,"logs",process.cwd(),as());if(e.clear){dh(t.pid),console.log(`Cleared log for ${cs(t)} (pid ${t.pid}).`);return}let n=$e(t.pid),s=n.text;if(e.run!==void 0&&(s=fh(s,e.run),!s&&e.run!=="latest"&&console.error(`No output for run ${e.run} (it hasn't started, or was trimmed from the log).`)),e.lines&&e.lines>0){let i=s.split(`
|
|
1918
|
+
`);i.length&&i[i.length-1]===""&&i.pop(),s=i.slice(-e.lines).join(`
|
|
1919
|
+
`)}if(process.stdout.write(s),s&&!s.endsWith(`
|
|
1920
|
+
`)&&process.stdout.write(`
|
|
1921
|
+
`),e.follow&&e.run===void 0){let i=n.offset,o=setInterval(()=>{let c=$e(t.pid,i);i=c.offset,c.text&&process.stdout.write(c.text)},500),a=()=>{clearInterval(o),process.exit(0)};process.on("SIGINT",a),process.on("SIGTERM",a),await new Promise(()=>{})}}var sO=r=>new Promise(e=>setTimeout(e,r));async function Wy(r,e){if(!r){Nu(await Q(process.cwd()),"Run `typebulb wait <file|pid>` to block until one logs a new line.");return}let t=Iu(await Q(),r,"wait",process.cwd(),as()),n=t.agent!=null,i=process.env.TYPEBULB_WAIT_SHIM==="1",o=e.timeoutSec??1800,a=e.match??"",c=$e(t.pid).offset,l=Ll(t.pid,a)??(a?Ll(t.pid):void 0),f=l!==void 0&&l<=c?l:a?0:c,u=Date.now()+o*1e3,d=n?1e4:1e3,p=2e3,b,m="",g=0;for(;;){let x=$e(t.pid,f);if(f=x.offset,x.text){m+=x.text;let A=m.split(`
|
|
1922
|
+
`);m=A.pop()??"";for(let P of A)P.trim()&&(e.match&&!P.includes(e.match)||(console.log(P),b??=Date.now()+d,n&&(P.includes("] compile error")||P.includes("] runtime error"))&&(b=Math.min(b,Date.now()+p))))}if(b&&Date.now()>=b)break;if(!i&&!b&&Date.now()>=u){console.error(`timeout: no ${e.match?`line matching '${e.match}'`:"new output"} from ${cs(t)} within ${o}s`),g=2;break}if(!Dl(t.pid)){b||(console.error(`server ${cs(t)} (pid ${t.pid}) exited while waiting`),process.exit(3));break}await sO(400)}Gi(t.pid,f,a),process.exit(g)}async function Yy(r){if(!r){Nu(await Q(process.cwd()),"Run `typebulb stop <file|pid>` to stop one.");return}let e=Iu(await Q(),r,"stop",process.cwd(),as());await Yt(e.pid),console.log(`Stopped ${cs(e)} (pid ${e.pid}, ${e.url}).`)}async function Vy(r){let e=process.cwd(),t=r==="agent"?as():void 0,n=r==="global"?await Q():r==="bulbs"?await Q(e):(await Q()).filter(i=>i.agent!=null&&i.cwd!=null&&ne(i.cwd)===ne(e)&&(!t||i.agent===t)),s=r==="global"?"server":r==="agent"?"mirror":"bulb";if(!n.length){console.log(r==="global"?"No running bulb servers.":`No running ${s}s for this project.`);return}await Promise.all(n.map(i=>Yt(i.pid))),console.log(`Stopped ${n.length} ${s}${n.length===1?"":"s"}:`);for(let i of n)console.log(` ${i.url} pid ${i.pid} ${cs(i)}`)}Le();import*as Gy from"path";async function zy(r,e,t=0){let n=e!==void 0&&e.startsWith("tb:");n&&t<=0&&(t=zo);let s=Gy.resolve(r),i=_r(await Q(),s)[0];i||(console.error(`No running server for '${r}'. Start it first: npx typebulb ${r}`),process.exit(1));let o=async d=>{let p=await fetch(`${i.url}/__send${d>0?`?reply=${d}`:""}`,{method:"POST",headers:{"Content-Type":"text/plain"},body:e??""});return p.ok||(console.error(`send failed: HTTP ${p.status} from ${i.url}/__send`),process.exit(1)),await p.json().catch(()=>({}))},a={};try{let d=Date.now()+t;do{if(a=await o(t>0?Math.max(d-Date.now(),1e3):0),(a.clients??0)>0||Date.now()>=d)break;await new Promise(p=>setTimeout(p,150))}while(!0)}catch(d){console.error(`send failed: ${d instanceof Error?d.message:String(d)}`),process.exit(1)}let c=a.clients??0,l=`${c} page${c===1?"":"s"}`;if(c===0){t>0?console.error(`No page connected after ${t/1e3}s \u2014 is the bulb open?`):console.error("Sent, but no page is connected yet \u2014 open the bulb and retry."),n&&process.exit(1);return}console.error(`Sent to ${l}.`);let f=a.results??[],u=a.errors??[];for(let d of u)console.error(`handler error: ${d}`);if(u.length&&process.exit(1),f.length>1&&(console.error(`${f.length} replies from ${l} \u2014 one reply owns stdout: at most one tb.onMessage handler, in one page, may return a value.`),process.exit(1)),f.length===1){let d;try{d=JSON.parse(f[0])}catch{d=void 0}console.log(typeof d=="string"?d:f[0])}else a.timedOut&&(n&&(console.error(`No reply to '${e}' within ${t/1e3}s \u2014 reload the page and retry.`),process.exit(1)),console.error(`(no reply within ${t/1e3}s \u2014 a slow handler's return needs a larger --wait=ms)`))}Yn();nu();kt();wt();Ne();eo();Yn();import*as Ct from"fs/promises";import*as Ho from"path";import{EventEmitter as Xy}from"events";import aO from"open";eu();Le();async function Ko(r){let{portPreference:e,makeServerOptions:t,makeEntry:n,displayName:s,stopLog:i}=r,o=await Zl(e),a=await Fh(t(o)),c=`http://localhost:${o}`;await ph(n(o,c)),console.log(`
|
|
1923
|
+
${s}`),console.log(` ${c}`),o!==e&&console.log(` (port ${e} was busy)`);let l=[],f=async()=>{console.log(`
|
|
1924
|
+
Shutting down...`),a.close();for(let u of l)try{await u()}catch{}i(),await Hn(process.pid),process.exit(0)};return process.on("SIGINT",f),process.on("SIGTERM",f),{port:o,url:c,onCleanup(u){l.push(u)}}}import iO from"chokidar";var oO={persistent:!0,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50}};function Ot(r){let{target:e,onChange:t,events:n="change",debounceMs:s=150}=r,i,o=iO.watch(e,oO);o.on("error",c=>console.warn(`watch: ${c instanceof Error?c.message:c} \u2014 continuing`));let a=()=>{i&&clearTimeout(i),i=setTimeout(t,s)};return n==="all"?o.on("all",a):o.on("change",a),()=>{i&&clearTimeout(i),o.close()}}Le();async function Qy(r,e,t,n){let s=process.cwd(),i=zi(process.pid),o=e.watch?new Xy:void 0,a=new Xy;a.setMaxListeners(0);let c=ye(e.mode),l=await jl(r);l.length&&console.log(`Replacing the running server for this bulb (pid ${l.map(I=>I.pid).join(", ")})`);let f=1;console.log(Ml(f)),console.log(`Loading ${Ho.basename(r)}...`);let{html:u,bulb:d,serverExports:p}=await Sl(r,e.watch,e.trust,n,e.dir);St(c,r,d.server);let b=[...e.dir?[Pr(r,e.dir)]:[],Pr(r)],m=rt(d.config);m.assets&&!Ur(d.config)&&console.warn(` config.json "assets" is not a valid http(s) URL \u2014 ignored: ${m.assets}`);let g=Hl(Ho.resolve(r)),x=e.trust?void 0:Nr(d),{port:A,url:P,onCleanup:_}=await Ko({portPreference:e.port,displayName:d.name,stopLog:i,makeServerOptions:I=>({getHtml:()=>u,basePath:s,fsBase:Fn(r,e.dir),port:I,reloadEmitter:o,messageEmitter:a,getServerExports:()=>p,getBulbBlocks:()=>({infer:d.infer,insight:d.insight,code:d.code,config:d.config,data:d.data}),saveInferenceResult:async(E,y)=>{let w=await Ct.readFile(r,"utf-8");w=ta(w,"data",E.join(cm)),w=ta(w,"insight",y),await Ct.writeFile(r,w)},localOverride:n?{name:n.name,serveDir:n.serveDir}:void 0,bulbAssets:{dirs:b,getRemoteBase:()=>cd(d.config,g?.userSlug,g?.slug)},trusted:e.trust,trustHint:t}),makeEntry:(I,E)=>({pid:process.pid,port:I,url:E,file:r,cwd:process.cwd(),startedAt:Date.now(),trust:e.trust,dir:e.dir,mode:e.mode,predicted:x})});e.trust?console.log(" trust: granted (filesystem, AI, server.ts enabled)"):console.log(x?` trust: restricted \u2014 this bulb appears to use ${x}; re-run with --trust to enable it:
|
|
1924
1925
|
${t}
|
|
1925
1926
|
`:` trust: restricted \u2014 re-run with --trust to enable filesystem / AI / server.ts
|
|
1926
1927
|
`),e.watch&&console.log(` Watching for changes...
|
|
1927
|
-
`);let
|
|
1928
|
-
`),o.emit("reload")}})}for(let
|
|
1929
|
-
`),o.emit("reload")}}))}
|
|
1930
|
-
`):await
|
|
1928
|
+
`);let N,C;if(e.watch&&o){let I=0,E=Promise.resolve();if(N=Ot({target:r,onChange:()=>{let y=++I;E=E.then(async()=>{if(y===I)try{console.log("Recompiling...");let w=await Sl(r,!0,e.trust,n,e.dir);u=w.html,p=w.serverExports,d=w.bulb,f++,console.log(Ml(f)),o.emit("reload")}catch(w){console.error("Compile error:",w)}})}}),n){let{name:y,serveDir:w}=n;C=Ot({target:w,events:"all",onChange:()=>{console.log(`Local package '${y}' changed. Browser reloading...
|
|
1929
|
+
`),o.emit("reload")}})}for(let y of b)await Ct.stat(y).then(w=>w.isDirectory()).catch(()=>!1)&&_(Ot({target:y,events:"all",onChange:()=>{console.log(`Assets changed. Browser reloading...
|
|
1930
|
+
`),o.emit("reload")}}))}N&&_(N),C&&_(C),_(()=>Ct.rm(vl(r),{force:!0})),e.open&&(l.some(I=>I.port===A)?console.log(` Reusing the open browser tab.
|
|
1931
|
+
`):await aO(P))}kt();import{readFileSync as eb,copyFileSync as lO,existsSync as uO}from"fs";import*as oe from"path";import{fileURLToPath as dO}from"url";import{EventEmitter as fO}from"events";import tb from"open";Le();rl();var $u=r=>`/agents/${r}/client.js`,cO=`
|
|
1931
1932
|
(() => {
|
|
1932
1933
|
const api = async (name, ...args) => {
|
|
1933
1934
|
const resp = await fetch('/__api/' + name, {
|
|
@@ -1962,15 +1963,15 @@ Shutting down...`),a.close();for(let u of l)try{await u()}catch{}i(),await Kn(pr
|
|
|
1962
1963
|
es.onerror = () => { es.close(); };
|
|
1963
1964
|
}
|
|
1964
1965
|
})();
|
|
1965
|
-
`;function
|
|
1966
|
+
`;function Zy(r){let{name:e,agent:t,styles:n,mountHtml:s,watch:i,theme:o}=r,a=$u(t);return`<!DOCTYPE html>
|
|
1966
1967
|
<html>
|
|
1967
1968
|
<head>
|
|
1968
1969
|
<meta charset="utf-8">
|
|
1969
1970
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
1970
|
-
<title>${
|
|
1971
|
-
${
|
|
1971
|
+
<title>${Ei(e)} - typebulb</title>
|
|
1972
|
+
${Ti(e,o)}
|
|
1972
1973
|
<style>
|
|
1973
|
-
${
|
|
1974
|
+
${Ai}
|
|
1974
1975
|
</style>
|
|
1975
1976
|
<style>
|
|
1976
1977
|
${n}
|
|
@@ -1982,17 +1983,17 @@ ${s}
|
|
|
1982
1983
|
${i?"<script>window.__TYPEBULB_WATCH__ = true;</script>":""}
|
|
1983
1984
|
|
|
1984
1985
|
<script>
|
|
1985
|
-
${
|
|
1986
|
+
${cO}
|
|
1986
1987
|
</script>
|
|
1987
1988
|
|
|
1988
1989
|
<script type="module" src="${a}"></script>
|
|
1989
1990
|
</body>
|
|
1990
|
-
</html>`}async function
|
|
1991
|
-
${n.url}`),r.open&&await
|
|
1992
|
-
`);let A=
|
|
1993
|
-
`),i.emit("reload")}catch(E){console.error("Mirror rebuild failed:",E instanceof Error?E.message:E)}finally{
|
|
1994
|
-
`);let c=0,l=Promise.resolve();
|
|
1995
|
-
`)}catch(p){
|
|
1996
|
-
`),
|
|
1997
|
-
`),process.exit(1)}function
|
|
1998
|
-
${e}`),process.exit(1))}async function
|
|
1991
|
+
</html>`}async function rb(r){let e=process.cwd(),t=r.agentTarget;fy(t)||(console.error(`Unknown agent '${t}'. Known: ${jr().join(", ")}.`),process.exit(1));let n=await Bl(e,t);if(n){console.log(`Mirror '${t}' is already running for this project:
|
|
1992
|
+
${n.url}`),r.open&&await tb(n.url);return}let s=zi(process.pid),i=r.watch?new fO:void 0,o=ye(r.mode),a=await my(t),c=a.displayName||`${t} mirror`;St(o,oe.join(e,"mirror"));let l=oe.dirname(dO(import.meta.url)),f=oe.join(l,"agents",t),u=oe.join(l,"..","cli","agents"),d=oe.join(f,"styles.css"),p=oe.join(f,"index.html"),b=()=>Zy({name:c,agent:t,styles:eb(d,"utf8"),mountHtml:eb(p,"utf8"),watch:r.watch}),{port:m,url:g,onCleanup:x}=await Ko({portPreference:r.port,displayName:c,stopLog:s,makeServerOptions:C=>({getHtml:b,basePath:e,port:C,reloadEmitter:i,getServerExports:()=>a,trusted:!0,staticAssets:{mount:`${oe.posix.dirname($u(t))}/`,dir:f}}),makeEntry:(C,I)=>({pid:process.pid,port:C,url:I,file:`agent:${t}`,cwd:e,startedAt:Date.now(),trust:!0,agent:t})});r.watch&&console.log(` Watching for changes...
|
|
1993
|
+
`);let A=oe.join(u,t,"client"),P=oe.join(u,"core","client");async function _(){await(await import("esbuild")).build({entryPoints:[oe.join(A,"index.ts")],bundle:!0,platform:"browser",format:"esm",outfile:oe.join(f,"client.js")});for(let I of["styles.css","index.html","typebulb.png","typebulb-inv.png"])lO(oe.join(P,I),oe.join(f,I))}let N;if(r.watch&&i){let C=uO(A),I=!1;N=Ot({target:C?u:f,events:"all",onChange:async()=>{if(!I){I=!0;try{C&&await _(),console.log(`Mirror rebuilt. Browser reloading...
|
|
1994
|
+
`),i.emit("reload")}catch(E){console.error("Mirror rebuild failed:",E instanceof Error?E.message:E)}finally{I=!1}}}})}r.open&&await tb(g),x(()=>a.shutdownSwitcher?.()),x(()=>a.shutdownComposer?.()),N&&x(N)}kt();wt();import*as nb from"path";async function sb(r,e,t,n,s){let i=ye(t),o=!1,a=async()=>{let{bulb:c,config:l}=await Ae(r);o||(St(i,r,c.server),o=!0),await qn(c.server,r,n,l.dependencies,s)};if(console.log(`Running ${nb.basename(r)}...`),await a(),e){console.log(`Watching for changes...
|
|
1995
|
+
`);let c=0,l=Promise.resolve();Ot({target:r,onChange:()=>{let f=++c;l=l.then(async()=>{if(f===c)try{console.log("Re-running..."),await a()}catch(u){console.error("Error:",u)}})}})}}kt();wt();Gl();Le();import{Console as pO}from"node:console";async function ab(r,e,t,n,s){bO();try{let p=_r(await Q(),r)[0];p&&(Gi(p.pid,$e(p.pid).offset),console.error(`note: 'call' boots a fresh server.ts instance; the running server (${p.url}) is not contacted \u2014 state shared with it must live on disk.`))}catch{}let i=ye(t),{bulb:o,config:a}=await Ae(r);o.server||ls("This bulb has no **server.ts** block; nothing to call."),St(i,r,o.server);let c;try{c=await qn(o.server,r,n,a.dependencies,s)}catch(p){ls(p instanceof Error?p.message:String(p))}let l=lo(c,e.fn);if(!l){let p=[...Object.keys(c).filter(b=>typeof c[b]=="function"),...Object.keys(co)];ls(`Function '${e.fn}' not found. Available: ${p.length?p.join(", "):"(none)"}.`)}let f=await mO(e);if(uo(l)){try{for await(let p of l(...f))await ob(JSON.stringify(p,cb)+`
|
|
1996
|
+
`)}catch(p){ls(p instanceof Error?p.stack??p.message:String(p))}return ib(0)}let u;try{u=await l(...f)}catch(p){ls(p instanceof Error?p.stack??p.message:String(p))}let d=yO(u);d!==void 0&&await ob(d+`
|
|
1997
|
+
`),ib(0)}function ib(r){process.exitCode=r,setTimeout(()=>process.exit(r),2e3).unref?.()}async function mO(r){if(r.hasArgsFlag){let e=r.argsJson??"";return e==="-"&&(e=await wO()),gO(e)}return hO(r.positional)}function hO(r){return r.map(e=>{try{return JSON.parse(e)}catch{return e}})}function gO(r){let e;try{e=JSON.parse(r)}catch(t){throw new Error(`--args must be a JSON array: ${t instanceof Error?t.message:String(t)}`)}if(!Array.isArray(e))throw new Error(`--args must be a JSON array, got ${e===null?"null":typeof e}`);return e}function yO(r){if(r!==void 0)return JSON.stringify(r,cb,2)}function cb(r,e){return typeof e=="bigint"?e.toString():e}function ls(r){process.stderr.write(r+`
|
|
1998
|
+
`),process.exit(1)}function bO(){let r=new pO(process.stderr,process.stderr);console.log=r.log.bind(r),console.info=r.info.bind(r),console.debug=r.debug.bind(r),console.dir=r.dir.bind(r)}function ob(r){return new Promise((e,t)=>{process.stdout.write(r,n=>n?t(n):e())})}async function wO(){let r=[];for await(let e of process.stdin)r.push(e);return Buffer.concat(r).toString("utf-8")}var Lu="0.33.0";function lb(r,e){r||(console.error(`This bulb runs server-side Node code (server.ts), which --trust must authorize:
|
|
1999
|
+
${e}`),process.exit(1))}async function vO(){let r=zu(process.argv.slice(2));if(r.version&&(console.log(`typebulb ${Lu}`),process.exit(0)),r.help&&(Xu(),process.exit(0)),Ly(),r.subcommand==="logs"){await Hy(r.file||void 0,{follow:r.follow,clear:r.clear,run:r.run,lines:r.lines});return}if(r.subcommand==="wait"){await Wy(r.file||void 0,{match:r.match,timeoutSec:r.timeoutSec});return}if(r.subcommand==="stop"){r.stopScope?await Vy(r.stopScope):await Yy(r.file||void 0);return}if(r.subcommand==="send"){await zy(r.file,r.sendMessage,r.sendWaitMs??0);return}if(r.subcommand==="skill"){await Uy(Lu);return}if(r.subcommand==="models"){await Fy(r.mode);return}if(r.subcommand==="pull"){await Rh(r.file||void 0,{force:r.force,mode:r.mode});return}if(r.subcommand==="push"){await Uh(r.file||void 0,{force:r.force,mode:r.mode});return}if(r.subcommand==="agent"){await(r.agentTarget?rb(r):jy(Lu));return}if(r.subcommand==="trust"||r.subcommand==="untrust"){await $y(r.file||void 0,r.subcommand==="trust");return}let e;if(!r.file||r.file==="."){let c=await Qm(process.cwd());c||(console.error("No .bulb.md file found in current directory"),process.exit(1)),e=c}else e=tr.resolve(r.file);await ub.access(e).then(()=>!0,()=>!1)||(jr().includes(r.file)&&(console.error(`To open the ${r.file} agent mirror, run: npx typebulb agent:${r.file}`),process.exit(1)),console.error(`File not found: ${e}`),process.exit(1)),e.endsWith(".bulb.md")||(console.error("File must have .bulb.md extension"),process.exit(1));let n=r.file&&r.file!=="."?r.file:tr.relative(process.cwd(),e)||tr.basename(e),s=`npx typebulb --trust ${n.includes(" ")?`"${n}"`:n}`;if(r.subcommand==="predict"){await Iy(e,s);return}let i=!r.noTrust&&Wt(e);i&&!r.trust&&console.error("trust: granted from memory (run `typebulb untrust` to revoke)"),r.trust=r.noTrust?!1:r.trust||i;let o;try{o=await Ae(e)}catch{}let a;if(r.local){o&&!(r.local.name in(o.config.dependencies??{}))&&(console.error(`--replace: '${r.local.name}' is not a dependency in this bulb's config.json; nothing to replace.`),process.exit(1)),o&&r.subcommand!=="call"&&(!o.bulb.code||r.server)&&console.warn("warning: --replace has no effect in server mode (the override is client-only).");try{a=await Yu(r.local)}catch(c){console.error(c instanceof Error?c.message:String(c)),process.exit(1)}console.error(`replace: ${a.name} \u2192 ${tr.relative(process.cwd(),a.dir)||"."}`)}if(r.subcommand==="check"){await Ny(e,a);return}if(r.subcommand==="call"){lb(r.trust,s),await ab(e,{fn:r.fn,positional:r.callArgs,argsJson:r.argsJson,hasArgsFlag:r.hasArgsFlag},r.mode,a,r.dir);return}if(o&&o.bulb.server&&(pi(o.bulb)||r.server)){lb(r.trust,s),await sb(e,r.watch,r.mode,a,r.dir);return}await Qy(e,r,s,a)}vO().catch(r=>{console.error("Error:",r.message),process.exit(1)});
|