typebulb 0.24.1 → 0.24.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agents/claude/client.js +257 -256
- package/dist/agents/claude/styles.css +29 -0
- package/dist/agents/pi/client.js +179 -178
- package/dist/agents/pi/matchu-patchu.ts +1 -1
- package/dist/agents/pi/styles.css +29 -0
- package/dist/ai/aiProvider.d.ts.map +1 -1
- package/dist/ai/aiProvider.js +9 -2
- package/dist/ai/aiProvider.js.map +1 -1
- package/dist/ai/aiProviders.d.ts +5 -0
- package/dist/ai/aiProviders.d.ts.map +1 -1
- package/dist/ai/aiProviders.js +10 -2
- package/dist/ai/aiProviders.js.map +1 -1
- package/dist/ai/providers/ollama.js +1 -1
- package/dist/ai/providers/ollama.js.map +1 -1
- package/dist/ai/sseParser.d.ts.map +1 -1
- package/dist/ai/sseParser.js +10 -1
- package/dist/ai/sseParser.js.map +1 -1
- package/dist/dts/fetchDts.d.ts.map +1 -1
- package/dist/dts/fetchDts.js +4 -3
- package/dist/dts/fetchDts.js.map +1 -1
- package/dist/dts/index.d.ts +0 -1
- package/dist/dts/index.d.ts.map +1 -1
- package/dist/dts/index.js +0 -1
- package/dist/dts/index.js.map +1 -1
- package/dist/dts/typescriptProvider.d.ts.map +1 -1
- package/dist/dts/typescriptProvider.js +8 -3
- package/dist/dts/typescriptProvider.js.map +1 -1
- package/dist/format/parse.d.ts.map +1 -1
- package/dist/format/parse.js +4 -2
- package/dist/format/parse.js.map +1 -1
- package/dist/index.js +393 -393
- package/dist/lint/index.d.ts.map +1 -1
- package/dist/lint/index.js +22 -15
- package/dist/lint/index.js.map +1 -1
- package/dist/render.js +30 -29
- package/dist/resolver/cdnClient.d.ts +4 -6
- package/dist/resolver/cdnClient.d.ts.map +1 -1
- package/dist/resolver/cdnClient.js +2 -2
- package/dist/resolver/cdnClient.js.map +1 -1
- package/dist/resolver/index.d.ts +1 -0
- package/dist/resolver/index.d.ts.map +1 -1
- package/dist/resolver/index.js +1 -0
- package/dist/resolver/index.js.map +1 -1
- package/dist/resolver/negativeCacheHelper.d.ts.map +1 -0
- package/dist/{dts → resolver}/negativeCacheHelper.js +5 -12
- package/dist/resolver/negativeCacheHelper.js.map +1 -0
- package/dist/servers.js +31 -31
- package/package.json +1 -1
- package/dist/dts/negativeCacheHelper.d.ts.map +0 -1
- package/dist/dts/negativeCacheHelper.js.map +0 -1
- /package/dist/{dts → resolver}/negativeCacheHelper.d.ts +0 -0
package/dist/index.js
CHANGED
|
@@ -1,159 +1,160 @@
|
|
|
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 wg=Object.create;var Gi=Object.defineProperty;var vg=Object.getOwnPropertyDescriptor;var Sg=Object.getOwnPropertyNames;var kg=Object.getPrototypeOf,xg=Object.prototype.hasOwnProperty;var _n=(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 R=(r,e)=>()=>(r&&(e=r(r=0)),e);var O=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),pl=(r,e)=>{for(var t in e)Gi(r,t,{get:e[t],enumerable:!0})},Eg=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Sg(e))!xg.call(r,s)&&s!==t&&Gi(r,s,{get:()=>e[s],enumerable:!(n=vg(e,s))||n.enumerable});return r};var Ag=(r,e,t)=>(t=r!=null?wg(kg(r)):{},Eg(e||!r||!r.__esModule?Gi(t,"default",{value:r,enumerable:!0}):t,r));function El(r){return $t.find(e=>Mt[e].path===r)}function Tl(r){return!!r?.startsWith("typebulb")}var Mt,$t,Al,Cn=R(()=>{Mt={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"}},$t=["code","css","html","data","infer","insight","config","notes"];Al="typebulb/v1"});function Zi(r){return/[:\n"']/.test(r)||r.startsWith(" ")||r.endsWith(" ")?`"${r.replace(/"/g,'\\"')}"`:r}function eo(r){return r.startsWith('"')&&r.endsWith('"')?r.slice(1,-1).replace(/\\"/g,'"'):r.startsWith("'")&&r.endsWith("'")?r.slice(1,-1):r}var Nn=R(()=>{});function Pe(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=Dg(n);if(!s)return null;let i=new Map,o=[],a=t;for(;t<e.length;){let l=e[t]?.trim()?.match(Pl);if(l){let d=l[1].trim();for(t++;t<e.length&&e[t]?.trim()==="";)t++;let u=e[t]?.match(Ol);if(!u){o.push(`**${d}** has no code fence \u2014 block skipped`);continue}let f=u[1];t++;let p=[];for(;t<e.length&&!e[t]?.match(new RegExp(`^${f}\\s*$`));)p.push(e[t]),t++;let y=t<e.length;t++,o.push(...Mg(d,p,y)),i.set(d,p.join(`
|
|
5
|
+
`)),a=t}else t++}return{frontmatter:s,files:i,warnings:o,bodyEndLine:a}}catch{return null}}function Mg(r,e,t){let n=[];for(let s=0;s<e.length;s++){let i=e[s]?.trim().match(Pl);i&&Lg.has(i[1].trim())&&$g(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 $g(r,e){let t=e+1;for(;t<r.length&&r[t]?.trim()==="";)t++;return!!r[t]?.match(Ol)}function Dg(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=eo(i);break}}return!Tl(e.format)||!e.name?null:e}function Rl(r){return Pe(r)?.warnings??[]}function _l(r){let e=Object.fromEntries($t.map(t=>[t,r.files.get(Mt[t].path)||""]));return{name:r.frontmatter.name,...e}}var Pl,Ol,Lg,Cl=R(()=>{Cn();Nn();Pl=/^\*\*(.+)\*\*$/,Ol=/^(`{3,})(\w*)\s*$/,Lg=new Set($t.map(r=>Mt[r].path))});function Bg(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 Nl(r){let e=$t.filter(t=>r[t]).map(t=>{let{path:n}=Mt[t],s=r[t],i=n.split(".").pop(),o=Bg(s);return`**${n}**
|
|
6
6
|
|
|
7
7
|
${o}${i}
|
|
8
8
|
${s}
|
|
9
|
-
${o}`});return["---",`format: ${
|
|
10
|
-
`)}var
|
|
11
|
-
>/]`,i);if(n&&console.log("[xml-utils] start:",o),o===-1)return;let a=r.slice(o+e.length),c=wr(a,"^[^<]*[ /]>",0),l=c!==-1&&a[c-1]==="/";if(n&&console.log("[xml-utils] selfClosing:",l),l===!1)if(s){let p=0,y=1,m=0;for(;(c=wr(a,"[ /]"+e+">",p))!==-1;){let b=a.substring(p,c+1);if(y+=
|
|
12
|
-
>]`),m+=
|
|
13
|
-
`)}};kr.defaultYaml={explicit:!1,version:"1.2"};kr.defaultTags={"!!":"tag:yaml.org,2002:"};
|
|
14
|
-
`)?
|
|
9
|
+
${o}`});return["---",`format: ${Al}`,`name: ${Zi(r.name)}`,"---","",...e].join(`
|
|
10
|
+
`)}var Il=R(()=>{Cn();Nn()});function Ll(r){if(!r.trim())return{};try{return JSON.parse(r)}catch{return{}}}var Ml=R(()=>{});var $l=R(()=>{});function to(r,e,t){let s=new RegExp(e).exec(r.slice(t));return s?t+s.index:-1}var Dl=R(()=>{});function wr(r,e,t){let s=new RegExp(e).exec(r.slice(t));return s?t+s.index+s[0].length-1:-1}var Bl=R(()=>{});function In(r,e){let t=new RegExp(e,"g"),n=r.match(t);return n?n.length:0}var jl=R(()=>{});function vr(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=to(r,`<${e}[
|
|
11
|
+
>/]`,i);if(n&&console.log("[xml-utils] start:",o),o===-1)return;let a=r.slice(o+e.length),c=wr(a,"^[^<]*[ /]>",0),l=c!==-1&&a[c-1]==="/";if(n&&console.log("[xml-utils] selfClosing:",l),l===!1)if(s){let p=0,y=1,m=0;for(;(c=wr(a,"[ /]"+e+">",p))!==-1;){let b=a.substring(p,c+1);if(y+=In(b,"<"+e+`[
|
|
12
|
+
>]`),m+=In(b,"</"+e+">"),m>=y)break;p=c}}else c=wr(a,"[ /]"+e+">",0);let d=o+e.length+c+1;if(n&&console.log("[xml-utils] end:",d),d===-1)return;let u=r.slice(o,d),f;return l?f=null:f=u.slice(u.indexOf(">")+1,u.lastIndexOf("<")),{inner:f,outer:u,start:o,end:d}}var ro=R(()=>{Dl();Bl();jl()});var no=R(()=>{ro()});var so=R(()=>{no()});var Fl=R(()=>{so()});var ql=R(()=>{});var Ul=R(()=>{$l();ro();no();Fl();so();ql()});var M=O(z=>{"use strict";var io=Symbol.for("yaml.alias"),Jl=Symbol.for("yaml.document"),Ln=Symbol.for("yaml.map"),Kl=Symbol.for("yaml.pair"),oo=Symbol.for("yaml.scalar"),Mn=Symbol.for("yaml.seq"),Oe=Symbol.for("yaml.node.type"),qg=r=>!!r&&typeof r=="object"&&r[Oe]===io,Ug=r=>!!r&&typeof r=="object"&&r[Oe]===Jl,Jg=r=>!!r&&typeof r=="object"&&r[Oe]===Ln,Kg=r=>!!r&&typeof r=="object"&&r[Oe]===Kl,Wl=r=>!!r&&typeof r=="object"&&r[Oe]===oo,Wg=r=>!!r&&typeof r=="object"&&r[Oe]===Mn;function Hl(r){if(r&&typeof r=="object")switch(r[Oe]){case Ln:case Mn:return!0}return!1}function Hg(r){if(r&&typeof r=="object")switch(r[Oe]){case io:case Ln:case oo:case Mn:return!0}return!1}var Vg=r=>(Wl(r)||Hl(r))&&!!r.anchor;z.ALIAS=io;z.DOC=Jl;z.MAP=Ln;z.NODE_TYPE=Oe;z.PAIR=Kl;z.SCALAR=oo;z.SEQ=Mn;z.hasAnchor=Vg;z.isAlias=qg;z.isCollection=Hl;z.isDocument=Ug;z.isMap=Jg;z.isNode=Hg;z.isPair=Kg;z.isScalar=Wl;z.isSeq=Wg});var Sr=O(ao=>{"use strict";var H=M(),re=Symbol("break visit"),Vl=Symbol("skip children"),we=Symbol("remove node");function $n(r,e){let t=Yl(e);H.isDocument(r)?Dt(null,r.contents,t,Object.freeze([r]))===we&&(r.contents=null):Dt(null,r,t,Object.freeze([]))}$n.BREAK=re;$n.SKIP=Vl;$n.REMOVE=we;function Dt(r,e,t,n){let s=Gl(r,e,t,n);if(H.isNode(s)||H.isPair(s))return zl(r,n,s),Dt(r,s,t,n);if(typeof s!="symbol"){if(H.isCollection(e)){n=Object.freeze(n.concat(e));for(let i=0;i<e.items.length;++i){let o=Dt(i,e.items[i],t,n);if(typeof o=="number")i=o-1;else{if(o===re)return re;o===we&&(e.items.splice(i,1),i-=1)}}}else if(H.isPair(e)){n=Object.freeze(n.concat(e));let i=Dt("key",e.key,t,n);if(i===re)return re;i===we&&(e.key=null);let o=Dt("value",e.value,t,n);if(o===re)return re;o===we&&(e.value=null)}}return s}async function Dn(r,e){let t=Yl(e);H.isDocument(r)?await Bt(null,r.contents,t,Object.freeze([r]))===we&&(r.contents=null):await Bt(null,r,t,Object.freeze([]))}Dn.BREAK=re;Dn.SKIP=Vl;Dn.REMOVE=we;async function Bt(r,e,t,n){let s=await Gl(r,e,t,n);if(H.isNode(s)||H.isPair(s))return zl(r,n,s),Bt(r,s,t,n);if(typeof s!="symbol"){if(H.isCollection(e)){n=Object.freeze(n.concat(e));for(let i=0;i<e.items.length;++i){let o=await Bt(i,e.items[i],t,n);if(typeof o=="number")i=o-1;else{if(o===re)return re;o===we&&(e.items.splice(i,1),i-=1)}}}else if(H.isPair(e)){n=Object.freeze(n.concat(e));let i=await Bt("key",e.key,t,n);if(i===re)return re;i===we&&(e.key=null);let o=await Bt("value",e.value,t,n);if(o===re)return re;o===we&&(e.value=null)}}return s}function Yl(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 Gl(r,e,t,n){if(typeof t=="function")return t(r,e,n);if(H.isMap(e))return t.Map?.(r,e,n);if(H.isSeq(e))return t.Seq?.(r,e,n);if(H.isPair(e))return t.Pair?.(r,e,n);if(H.isScalar(e))return t.Scalar?.(r,e,n);if(H.isAlias(e))return t.Alias?.(r,e,n)}function zl(r,e,t){let n=e[e.length-1];if(H.isCollection(n))n.items[r]=t;else if(H.isPair(n))r==="key"?n.key=t:n.value=t;else if(H.isDocument(n))n.contents=t;else{let s=H.isAlias(n)?"alias":"scalar";throw new Error(`Cannot replace node with ${s} parent`)}}ao.visit=$n;ao.visitAsync=Dn});var co=O(Xl=>{"use strict";var Ql=M(),Yg=Sr(),Gg={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},zg=r=>r.replace(/[!,[\]{}]/g,e=>Gg[e]),kr=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+zg(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&&Ql.isNode(e.contents)){let i={};Yg.visit(e.contents,(o,a)=>{Ql.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(`
|
|
13
|
+
`)}};kr.defaultYaml={explicit:!1,version:"1.2"};kr.defaultTags={"!!":"tag:yaml.org,2002:"};Xl.Directives=kr});var Bn=O(xr=>{"use strict";var Zl=M(),Qg=Sr();function Xg(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 eu(r){let e=new Set;return Qg.visit(r,{Value(t,n){n.anchor&&e.add(n.anchor)}}),e}function tu(r,e){for(let t=1;;++t){let n=`${r}${t}`;if(!e.has(n))return n}}function Zg(r,e){let t=[],n=new Map,s=null;return{onAnchor:i=>{t.push(i),s??(s=eu(r));let o=tu(e,s);return s.add(o),o},setAnchors:()=>{for(let i of t){let o=n.get(i);if(typeof o=="object"&&o.anchor&&(Zl.isScalar(o.node)||Zl.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}}xr.anchorIsValid=Xg;xr.anchorNames=eu;xr.createNodeAnchors=Zg;xr.findNewAnchor=tu});var lo=O(ru=>{"use strict";function Er(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=Er(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=Er(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=Er(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=Er(r,n,s,i);o===void 0?delete n[s]:o!==i&&(n[s]=o)}return r.call(e,t,n)}ru.applyReviver=Er});var je=O(su=>{"use strict";var ey=M();function nu(r,e,t){if(Array.isArray(r))return r.map((n,s)=>nu(n,String(s),t));if(r&&typeof r.toJSON=="function"){if(!t||!ey.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}su.toJS=nu});var jn=O(ou=>{"use strict";var ty=lo(),iu=M(),ry=je(),uo=class{constructor(e){Object.defineProperty(this,iu.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(!iu.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=ry.toJS(this,"",o);if(typeof s=="function")for(let{count:c,res:l}of o.anchors.values())s(l,c);return typeof i=="function"?ty.applyReviver(i,{"":a},"",a):a}};ou.NodeBase=uo});var Ar=O(au=>{"use strict";var ny=Bn(),sy=Sr(),jt=M(),iy=jn(),oy=je(),fo=class extends iy.NodeBase{constructor(e){super(jt.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=[],sy.visit(e,{Node:(i,o)=>{(jt.isAlias(o)||jt.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||(oy.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=Fn(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(ny.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 Fn(r,e,t){if(jt.isAlias(e)){let n=e.resolve(r),s=t&&n&&t.get(n);return s?s.count*s.aliasCount:0}else if(jt.isCollection(e)){let n=0;for(let s of e.items){let i=Fn(r,s,t);i>n&&(n=i)}return n}else if(jt.isPair(e)){let n=Fn(r,e.key,t),s=Fn(r,e.value,t);return Math.max(n,s)}return 1}au.Alias=fo});var J=O(po=>{"use strict";var ay=M(),cy=jn(),ly=je(),uy=r=>!r||typeof r!="function"&&typeof r!="object",Fe=class extends cy.NodeBase{constructor(e){super(ay.SCALAR),this.value=e}toJSON(e,t){return t?.keep?this.value:ly.toJS(this.value,e,t)}toString(){return String(this.value)}};Fe.BLOCK_FOLDED="BLOCK_FOLDED";Fe.BLOCK_LITERAL="BLOCK_LITERAL";Fe.PLAIN="PLAIN";Fe.QUOTE_DOUBLE="QUOTE_DOUBLE";Fe.QUOTE_SINGLE="QUOTE_SINGLE";po.Scalar=Fe;po.isScalarValue=uy});var Tr=O(lu=>{"use strict";var fy=Ar(),ot=M(),cu=J(),dy="tag:yaml.org,2002:";function py(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 my(r,e,t){if(ot.isDocument(r)&&(r=r.contents),ot.isNode(r))return r;if(ot.isPair(r)){let u=t.schema[ot.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 fy.Alias(c.anchor);c={anchor:null,node:null},a.set(r,c)}e?.startsWith("!!")&&(e=dy+e.slice(2));let l=py(r,e,o.tags);if(!l){if(r&&typeof r.toJSON=="function"&&(r=r.toJSON()),!r||typeof r!="object"){let u=new cu.Scalar(r);return c&&(c.node=u),u}l=r instanceof Map?o[ot.MAP]:Symbol.iterator in Object(r)?o[ot.SEQ]:o[ot.MAP]}i&&(i(l),delete t.onTagObj);let d=l?.createNode?l.createNode(t.schema,r,t):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(t.schema,r,t):new cu.Scalar(r);return e?d.tag=e:l.default||(d.tag=l.tag),c&&(c.node=d),d}lu.createNode=my});var Un=O(qn=>{"use strict";var hy=Tr(),ve=M(),gy=jn();function mo(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 hy.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 uu=r=>r==null||typeof r=="object"&&!!r[Symbol.iterator]().next().done,ho=class extends gy.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=>ve.isNode(n)||ve.isPair(n)?n.clone(e):n),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(uu(e))this.add(t);else{let[n,...s]=e,i=this.get(n,!0);if(ve.isCollection(i))i.addIn(s,t);else if(i===void 0&&this.schema)this.set(n,mo(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(ve.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&&ve.isScalar(i)?i.value:i:ve.isCollection(i)?i.getIn(s,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!ve.isPair(t))return!1;let n=t.value;return n==null||e&&ve.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 ve.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(ve.isCollection(i))i.setIn(s,t);else if(i===void 0&&this.schema)this.set(n,mo(this.schema,s,t));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${s}`)}}};qn.Collection=ho;qn.collectionFromPath=mo;qn.isEmptyPath=uu});var Pr=O(Jn=>{"use strict";var yy=r=>r.replace(/^(?!$)(?: $)?/gm,"#");function go(r,e){return/^\n+$/.test(r)?r.substring(1):e?r.replace(/^(?! *$)/gm,e):r}var by=(r,e,t)=>r.endsWith(`
|
|
14
|
+
`)?go(t,e):t.includes(`
|
|
15
15
|
`)?`
|
|
16
|
-
`+
|
|
17
|
-
`)t===
|
|
16
|
+
`+go(t,e):(r.endsWith(" ")?"":" ")+t;Jn.indentComment=go;Jn.lineComment=by;Jn.stringifyComment=yy});var du=O(Or=>{"use strict";var wy="flow",yo="block",Kn="quoted";function vy(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=[],d={},u=s-e.length;typeof n=="number"&&(n>s-Math.max(2,i)?l.push(0):u=s-n);let f,p,y=!1,m=-1,b=-1,x=-1;t===yo&&(m=fu(r,m,e.length),m!==-1&&(u=m+c));for(let g;g=r[m+=1];){if(t===Kn&&g==="\\"){switch(b=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(g===`
|
|
17
|
+
`)t===yo&&(m=fu(r,m,e.length)),u=m+e.length+c,f=void 0;else{if(g===" "&&p&&p!==" "&&p!==`
|
|
18
18
|
`&&p!==" "){let w=r[m+1];w&&w!==" "&&w!==`
|
|
19
|
-
`&&w!==" "&&(f=m)}if(m>=u)if(f)l.push(f),u=f+c,f=void 0;else if(t===
|
|
20
|
-
${e}${r.slice(0,k)}`:(t===
|
|
21
|
-
${e}${r.slice(w+1,k)}`)}return
|
|
22
|
-
`);n=e,s=e+1,i=r[s]}return n}Or.FOLD_BLOCK=
|
|
23
|
-
`){if(i-o>n)return!0;if(o=i+1,s-o<=n)return!1}return!0}function Rr(r,e){let t=JSON.stringify(r);if(e.options.doubleQuotedAsJSON)return t;let{implicitKey:n}=e,s=e.options.doubleQuotedMinMultiLineLength,i=e.indent||(
|
|
19
|
+
`&&w!==" "&&(f=m)}if(m>=u)if(f)l.push(f),u=f+c,f=void 0;else if(t===Kn){for(;p===" "||p===" ";)p=g,g=r[m+=1],y=!0;let w=m>x+1?m-2:b-1;if(d[w])return r;l.push(w),d[w]=!0,u=w+c,f=void 0}else y=!0}p=g}if(y&&a&&a(),l.length===0)return r;o&&o();let A=r.slice(0,l[0]);for(let g=0;g<l.length;++g){let w=l[g],k=l[g+1]||r.length;w===0?A=`
|
|
20
|
+
${e}${r.slice(0,k)}`:(t===Kn&&d[w]&&(A+=`${r[w]}\\`),A+=`
|
|
21
|
+
${e}${r.slice(w+1,k)}`)}return A}function fu(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!==`
|
|
22
|
+
`);n=e,s=e+1,i=r[s]}return n}Or.FOLD_BLOCK=yo;Or.FOLD_FLOW=wy;Or.FOLD_QUOTED=Kn;Or.foldFlowLines=vy});var _r=O(pu=>{"use strict";var ue=J(),qe=du(),Hn=(r,e)=>({indentAtStart:e?r.indent.length:r.indentAtStart,lineWidth:r.options.lineWidth,minContentWidth:r.options.minContentWidth}),Vn=r=>/^(%|---|\.\.\.)/m.test(r);function Sy(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]===`
|
|
23
|
+
`){if(i-o>n)return!0;if(o=i+1,s-o<=n)return!1}return!0}function Rr(r,e){let t=JSON.stringify(r);if(e.options.doubleQuotedAsJSON)return t;let{implicitKey:n}=e,s=e.options.doubleQuotedMinMultiLineLength,i=e.indent||(Vn(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 d=t.substr(c+2,4);switch(d){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:d.substr(0,2)==="00"?o+="\\x"+d.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)+`
|
|
24
24
|
|
|
25
25
|
`;t[c+2]==="\\"&&t[c+3]==="n"&&t[c+4]!=='"';)o+=`
|
|
26
|
-
`,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:qe.foldFlowLines(o,i,qe.FOLD_QUOTED,
|
|
27
|
-
`)||/[ \t]\n|\n[ \t]/.test(r))return Rr(r,e);let t=e.indent||(
|
|
28
|
-
${t}`)+"'";return e.implicitKey?n:qe.foldFlowLines(n,t,qe.FOLD_FLOW,
|
|
26
|
+
`,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:qe.foldFlowLines(o,i,qe.FOLD_QUOTED,Hn(e,!1))}function bo(r,e){if(e.options.singleQuote===!1||e.implicitKey&&r.includes(`
|
|
27
|
+
`)||/[ \t]\n|\n[ \t]/.test(r))return Rr(r,e);let t=e.indent||(Vn(r)?" ":""),n="'"+r.replace(/'/g,"''").replace(/\n+/g,`$&
|
|
28
|
+
${t}`)+"'";return e.implicitKey?n:qe.foldFlowLines(n,t,qe.FOLD_FLOW,Hn(e,!1))}function Ft(r,e){let{singleQuote:t}=e.options,n;if(t===!1)n=Rr;else{let s=r.includes('"'),i=r.includes("'");s&&!i?n=bo:i&&!s?n=Rr:n=t?bo:Rr}return n(r,e)}var wo;try{wo=new RegExp(`(^|(?<!
|
|
29
29
|
))
|
|
30
30
|
+(?!
|
|
31
|
-
|$)`,"g")}catch{
|
|
31
|
+
|$)`,"g")}catch{wo=/\n+(?!\n|$)/g}function Wn({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 Ft(t,n);let l=n.indent||(n.forceBlockIndent||Vn(t)?" ":""),d=o==="literal"?!0:o==="folded"||e===ue.Scalar.BLOCK_FOLDED?!1:e===ue.Scalar.BLOCK_LITERAL?!0:!Sy(t,c,l.length);if(!t)return d?`|
|
|
32
32
|
`:`>
|
|
33
33
|
`;let u,f;for(f=t.length;f>0;--f){let k=t[f-1];if(k!==`
|
|
34
34
|
`&&k!==" "&&k!==" ")break}let p=t.substring(f),y=p.indexOf(`
|
|
35
35
|
`);y===-1?u="-":t===p||y!==p.length-1?(u="+",i&&i()):u="",p&&(t=t.slice(0,-p.length),p[p.length-1]===`
|
|
36
|
-
`&&(p=p.slice(0,-1)),p=p.replace(
|
|
37
|
-
`)
|
|
38
|
-
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),
|
|
39
|
-
${l}${
|
|
40
|
-
${l}${
|
|
36
|
+
`&&(p=p.slice(0,-1)),p=p.replace(wo,`$&${l}`));let m=!1,b,x=-1;for(b=0;b<t.length;++b){let k=t[b];if(k===" ")m=!0;else if(k===`
|
|
37
|
+
`)x=b;else break}let A=t.substring(0,x<b?x+1:b);A&&(t=t.substring(A.length),A=A.replace(/\n+/g,`$&${l}`));let w=(m?l?"2":"1":"")+u;if(r&&(w+=" "+a(r.replace(/ ?[\r\n]+/g," ")),s&&s()),!d){let k=t.replace(/\n+/g,`
|
|
38
|
+
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),E=!1,T=Hn(n,!0);o!=="folded"&&e!==ue.Scalar.BLOCK_FOLDED&&(T.onOverflow=()=>{E=!0});let P=qe.foldFlowLines(`${A}${k}${p}`,l,qe.FOLD_BLOCK,T);if(!E)return`>${w}
|
|
39
|
+
${l}${P}`}return t=t.replace(/\n+/g,`$&${l}`),`|${w}
|
|
40
|
+
${l}${A}${t}${p}`}function ky(r,e,t,n){let{type:s,value:i}=r,{actualString:o,implicitKey:a,indent:c,indentStep:l,inFlow:d}=e;if(a&&i.includes(`
|
|
41
41
|
`)||d&&/[[\]{},]/.test(i))return Ft(i,e);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(i))return a||d||!i.includes(`
|
|
42
|
-
`)?Ft(i,e):
|
|
43
|
-
`))return
|
|
44
|
-
${c}`);if(o){let f=m=>m.default&&m.tag!=="tag:yaml.org,2002:str"&&m.test?.test(u),{compat:p,tags:y}=e.doc.schema;if(y.some(f)||p?.some(f))return Ft(i,e)}return a?u:qe.foldFlowLines(u,c,qe.FOLD_FLOW,
|
|
45
|
-
${e.indent}${a}`:a}
|
|
46
|
-
${a}:`):(b=`${b}:`,f&&(b+=Nr.lineComment(b,t.indent,l(f))));let
|
|
47
|
-
`:"",
|
|
48
|
-
${Nr.indentComment(
|
|
49
|
-
`&&g&&(
|
|
50
|
-
|
|
51
|
-
`):
|
|
52
|
-
${t.indent}`}else if(!p&&
|
|
53
|
-
`),
|
|
42
|
+
`)?Ft(i,e):Wn(r,e,t,n);if(!a&&!d&&s!==ue.Scalar.PLAIN&&i.includes(`
|
|
43
|
+
`))return Wn(r,e,t,n);if(Vn(i)){if(c==="")return e.forceBlockIndent=!0,Wn(r,e,t,n);if(a&&c===l)return Ft(i,e)}let u=i.replace(/\n+/g,`$&
|
|
44
|
+
${c}`);if(o){let f=m=>m.default&&m.tag!=="tag:yaml.org,2002:str"&&m.test?.test(u),{compat:p,tags:y}=e.doc.schema;if(y.some(f)||p?.some(f))return Ft(i,e)}return a?u:qe.foldFlowLines(u,c,qe.FOLD_FLOW,Hn(e,!1))}function xy(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!==ue.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(a=ue.Scalar.QUOTE_DOUBLE);let c=d=>{switch(d){case ue.Scalar.BLOCK_FOLDED:case ue.Scalar.BLOCK_LITERAL:return s||i?Ft(o.value,e):Wn(o,e,t,n);case ue.Scalar.QUOTE_DOUBLE:return Rr(o.value,e);case ue.Scalar.QUOTE_SINGLE:return bo(o.value,e);case ue.Scalar.PLAIN:return ky(o,e,t,n);default:return null}},l=c(a);if(l===null){let{defaultKeyType:d,defaultStringType:u}=e.options,f=s&&d||u;if(l=c(f),l===null)throw new Error(`Unsupported default string type ${f}`)}return l}pu.stringifyString=xy});var Cr=O(vo=>{"use strict";var Ey=Bn(),Ue=M(),Ay=Pr(),Ty=_r();function Py(r,e){let t=Object.assign({blockQuote:!0,commentString:Ay.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 Oy(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(Ue.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 Ry(r,e,{anchors:t,doc:n}){if(!n.directives)return"";let s=[],i=(Ue.isScalar(r)||Ue.isCollection(r))&&r.anchor;i&&Ey.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 _y(r,e,t,n){if(Ue.isPair(r))return r.toString(e,t,n);if(Ue.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=Ue.isNode(r)?r:e.doc.createNode(r,{onTagObj:c=>s=c});s??(s=Oy(e.doc.schema.tags,i));let o=Ry(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):Ue.isScalar(i)?Ty.stringifyString(i,e,t,n):i.toString(e,t,n);return o?Ue.isScalar(i)||a[0]==="{"||a[0]==="["?`${o} ${a}`:`${o}
|
|
45
|
+
${e.indent}${a}`:a}vo.createStringifyContext=Py;vo.stringify=_y});var yu=O(gu=>{"use strict";var Re=M(),mu=J(),hu=Cr(),Nr=Pr();function Cy({key:r,value:e},t,n,s){let{allNullValues:i,doc:o,indent:a,indentStep:c,options:{commentString:l,indentSeq:d,simpleKeys:u}}=t,f=Re.isNode(r)&&r.comment||null;if(u){if(f)throw new Error("With simple keys, key nodes cannot have comments");if(Re.isCollection(r)||!Re.isNode(r)&&typeof r=="object"){let T="With simple keys, collection cannot be used as a key value";throw new Error(T)}}let p=!u&&(!r||f&&e==null&&!t.inFlow||Re.isCollection(r)||(Re.isScalar(r)?r.type===mu.Scalar.BLOCK_FOLDED||r.type===mu.Scalar.BLOCK_LITERAL:typeof r=="object"));t=Object.assign({},t,{allNullValues:!1,implicitKey:!p&&(u||!i),indent:a+c});let y=!1,m=!1,b=hu.stringify(r,t,()=>y=!0,()=>m=!0);if(!p&&!t.inFlow&&b.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 y&&n&&n(),b===""?"?":p?`? ${b}`:b}else if(i&&!u||e==null&&p)return b=`? ${b}`,f&&!y?b+=Nr.lineComment(b,t.indent,l(f)):m&&s&&s(),b;y&&(f=null),p?(f&&(b+=Nr.lineComment(b,t.indent,l(f))),b=`? ${b}
|
|
46
|
+
${a}:`):(b=`${b}:`,f&&(b+=Nr.lineComment(b,t.indent,l(f))));let x,A,g;Re.isNode(e)?(x=!!e.spaceBefore,A=e.commentBefore,g=e.comment):(x=!1,A=null,g=null,e&&typeof e=="object"&&(e=o.createNode(e))),t.implicitKey=!1,!p&&!f&&Re.isScalar(e)&&(t.indentAtStart=b.length+1),m=!1,!d&&c.length>=2&&!t.inFlow&&!p&&Re.isSeq(e)&&!e.flow&&!e.tag&&!e.anchor&&(t.indent=t.indent.substring(2));let w=!1,k=hu.stringify(e,t,()=>w=!0,()=>m=!0),E=" ";if(f||x||A){if(E=x?`
|
|
47
|
+
`:"",A){let T=l(A);E+=`
|
|
48
|
+
${Nr.indentComment(T,t.indent)}`}k===""&&!t.inFlow?E===`
|
|
49
|
+
`&&g&&(E=`
|
|
50
|
+
|
|
51
|
+
`):E+=`
|
|
52
|
+
${t.indent}`}else if(!p&&Re.isCollection(e)){let T=k[0],P=k.indexOf(`
|
|
53
|
+
`),D=P!==-1,te=t.inFlow??e.flow??e.items.length===0;if(D||!te){let V=!1;if(D&&(T==="&"||T==="!")){let B=k.indexOf(" ");T==="&"&&B!==-1&&B<P&&k[B+1]==="!"&&(B=k.indexOf(" ",B+1)),(B===-1||P<B)&&(V=!0)}V||(E=`
|
|
54
54
|
${t.indent}`)}}else(k===""||k[0]===`
|
|
55
|
-
`)&&(
|
|
55
|
+
`)&&(E="");return b+=E+k,t.inFlow?w&&n&&n():g&&!w?b+=Nr.lineComment(b,t.indent,l(g)):m&&s&&s(),b}gu.stringifyPair=Cy});var ko=O(So=>{"use strict";var bu=_n("process");function Ny(r,...e){r==="debug"&&console.log(...e)}function Iy(r,e){(r==="debug"||r==="warn")&&(typeof bu.emitWarning=="function"?bu.emitWarning(e):console.warn(e))}So.debug=Ny;So.warn=Iy});var Qn=O(zn=>{"use strict";var Ir=M(),wu=J(),Yn="<<",Gn={identify:r=>r===Yn||typeof r=="symbol"&&r.description===Yn,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new wu.Scalar(Symbol(Yn)),{addToJSMap:vu}),stringify:()=>Yn},Ly=(r,e)=>(Gn.identify(e)||Ir.isScalar(e)&&(!e.type||e.type===wu.Scalar.PLAIN)&&Gn.identify(e.value))&&r?.doc.schema.tags.some(t=>t.tag===Gn.tag&&t.default);function vu(r,e,t){if(t=r&&Ir.isAlias(t)?t.resolve(r.doc):t,Ir.isSeq(t))for(let n of t.items)xo(r,e,n);else if(Array.isArray(t))for(let n of t)xo(r,e,n);else xo(r,e,t)}function xo(r,e,t){let n=r&&Ir.isAlias(t)?t.resolve(r.doc):t;if(!Ir.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}zn.addMergeToJSMap=vu;zn.isMergeKey=Ly;zn.merge=Gn});var Ao=O(xu=>{"use strict";var My=ko(),Su=Qn(),$y=Cr(),ku=M(),Eo=je();function Dy(r,e,{key:t,value:n}){if(ku.isNode(t)&&t.addToJSMap)t.addToJSMap(r,e,n);else if(Su.isMergeKey(r,t))Su.addMergeToJSMap(r,e,n);else{let s=Eo.toJS(t,"",r);if(e instanceof Map)e.set(s,Eo.toJS(n,s,r));else if(e instanceof Set)e.add(s);else{let i=By(t,s,r),o=Eo.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 By(r,e,t){if(e===null)return"";if(typeof e!="object")return String(e);if(ku.isNode(r)&&t?.doc){let n=$y.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)+'..."'),My.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)}xu.addPairToJSMap=Dy});var Je=O(To=>{"use strict";var Eu=Tr(),jy=yu(),Fy=Ao(),Xn=M();function qy(r,e,t){let n=Eu.createNode(r,void 0,t),s=Eu.createNode(e,void 0,t);return new Zn(n,s)}var Zn=class r{constructor(e,t=null){Object.defineProperty(this,Xn.NODE_TYPE,{value:Xn.PAIR}),this.key=e,this.value=t}clone(e){let{key:t,value:n}=this;return Xn.isNode(t)&&(t=t.clone(e)),Xn.isNode(n)&&(n=n.clone(e)),new r(t,n)}toJSON(e,t){let n=t?.mapAsMap?new Map:{};return Fy.addPairToJSMap(t,n,this)}toString(e,t,n){return e?.doc?jy.stringifyPair(this,e,t,n):JSON.stringify(this)}};To.Pair=Zn;To.createPair=qy});var Po=O(Tu=>{"use strict";var at=M(),Au=Cr(),es=Pr();function Uy(r,e,t){return(e.inFlow??r.flow?Ky:Jy)(r,e,t)}function Jy({comment:r,items:e},t,{blockItemPrefix:n,flowChars:s,itemIndent:i,onChompKeep:o,onComment:a}){let{indent:c,options:{commentString:l}}=t,d=Object.assign({},t,{indent:i,type:null}),u=!1,f=[];for(let y=0;y<e.length;++y){let m=e[y],b=null;if(at.isNode(m))!u&&m.spaceBefore&&f.push(""),ts(t,f,m.commentBefore,u),m.comment&&(b=m.comment);else if(at.isPair(m)){let A=at.isNode(m.key)?m.key:null;A&&(!u&&A.spaceBefore&&f.push(""),ts(t,f,A.commentBefore,u))}u=!1;let x=Au.stringify(m,d,()=>b=null,()=>u=!0);b&&(x+=es.lineComment(x,i,l(b))),u&&b&&(u=!1),f.push(n+x)}let p;if(f.length===0)p=s.start+s.end;else{p=f[0];for(let y=1;y<f.length;++y){let m=f[y];p+=m?`
|
|
56
56
|
${c}${m}`:`
|
|
57
57
|
`}}return r?(p+=`
|
|
58
|
-
`+
|
|
59
|
-
`))&&(l=!0),u.push(
|
|
58
|
+
`+es.indentComment(l(r),c),a&&a()):u&&o&&o(),p}function Ky({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,d=0,u=[];for(let y=0;y<r.length;++y){let m=r[y],b=null;if(at.isNode(m))m.spaceBefore&&u.push(""),ts(e,u,m.commentBefore,!1),m.comment&&(b=m.comment);else if(at.isPair(m)){let A=at.isNode(m.key)?m.key:null;A&&(A.spaceBefore&&u.push(""),ts(e,u,A.commentBefore,!1),A.comment&&(l=!0));let g=at.isNode(m.value)?m.value:null;g?(g.comment&&(b=g.comment),g.commentBefore&&(l=!0)):m.value==null&&A?.comment&&(b=A.comment)}b&&(l=!0);let x=Au.stringify(m,c,()=>b=null);y<r.length-1&&(x+=","),b&&(x+=es.lineComment(x,n,a(b))),!l&&(u.length>d||x.includes(`
|
|
59
|
+
`))&&(l=!0),u.push(x),d=u.length}let{start:f,end:p}=t;if(u.length===0)return f+p;if(!l){let y=u.reduce((m,b)=>m+b.length+2,2);l=e.options.lineWidth>0&&y>e.options.lineWidth}if(l){let y=f;for(let m of u)y+=m?`
|
|
60
60
|
${i}${s}${m}`:`
|
|
61
61
|
`;return`${y}
|
|
62
|
-
${s}${p}`}else return`${f}${o}${u.join(" ")}${o}${p}`}function
|
|
63
|
-
`:" ")}return
|
|
62
|
+
${s}${p}`}else return`${f}${o}${u.join(" ")}${o}${p}`}function ts({indent:r,options:{commentString:e}},t,n,s){if(n&&s&&(n=n.replace(/^\n+/,"")),n){let i=es.indentComment(e(n),r);t.push(i.trimStart())}}Tu.stringifyCollection=Uy});var We=O(Ro=>{"use strict";var Wy=Po(),Hy=Ao(),Vy=Un(),Ke=M(),rs=Je(),Yy=J();function Lr(r,e){let t=Ke.isScalar(e)?e.value:e;for(let n of r)if(Ke.isPair(n)&&(n.key===e||n.key===t||Ke.isScalar(n.key)&&n.key.value===t))return n}var Oo=class extends Vy.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(Ke.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(rs.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;Ke.isPair(e)?n=e:!e||typeof e!="object"||!("key"in e)?n=new rs.Pair(e,e?.value):n=new rs.Pair(e.key,e.value);let s=Lr(this.items,n.key),i=this.schema?.sortMapEntries;if(s){if(!t)throw new Error(`Key ${n.key} already set`);Ke.isScalar(s.value)&&Yy.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=Lr(this.items,e);return t?this.items.splice(this.items.indexOf(t),1).length>0:!1}get(e,t){let s=Lr(this.items,e)?.value;return(!t&&Ke.isScalar(s)?s.value:s)??void 0}has(e){return!!Lr(this.items,e)}set(e,t){this.add(new rs.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)Hy.addPairToJSMap(t,s,i);return s}toString(e,t,n){if(!e)return JSON.stringify(this);for(let s of this.items)if(!Ke.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})),Wy.stringifyCollection(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:n,onComment:t})}};Ro.YAMLMap=Oo;Ro.findPair=Lr});var qt=O(Ou=>{"use strict";var Gy=M(),Pu=We(),zy={collection:"map",default:!0,nodeClass:Pu.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(r,e){return Gy.isMap(r)||e("Expected a mapping for this tag"),r},createNode:(r,e,t)=>Pu.YAMLMap.from(r,e,t)};Ou.map=zy});var He=O(Ru=>{"use strict";var Qy=Tr(),Xy=Po(),Zy=Un(),ss=M(),eb=J(),tb=je(),_o=class extends Zy.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(ss.SEQ,e),this.items=[]}add(e){this.items.push(e)}delete(e){let t=ns(e);return typeof t!="number"?!1:this.items.splice(t,1).length>0}get(e,t){let n=ns(e);if(typeof n!="number")return;let s=this.items[n];return!t&&ss.isScalar(s)?s.value:s}has(e){let t=ns(e);return typeof t=="number"&&t<this.items.length}set(e,t){let n=ns(e);if(typeof n!="number")throw new Error(`Expected a valid index, not ${e}.`);let s=this.items[n];ss.isScalar(s)&&eb.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(tb.toJS(i,String(s++),t));return n}toString(e,t,n){return e?Xy.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(Qy.createNode(a,void 0,n))}}return i}};function ns(r){let e=ss.isScalar(r)?r.value:r;return e&&typeof e=="string"&&(e=Number(e)),typeof e=="number"&&Number.isInteger(e)&&e>=0?e:null}Ru.YAMLSeq=_o});var Ut=O(Cu=>{"use strict";var rb=M(),_u=He(),nb={collection:"seq",default:!0,nodeClass:_u.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(r,e){return rb.isSeq(r)||e("Expected a sequence for this tag"),r},createNode:(r,e,t)=>_u.YAMLSeq.from(r,e,t)};Cu.seq=nb});var Mr=O(Nu=>{"use strict";var sb=_r(),ib={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),sb.stringifyString(r,e,t,n)}};Nu.string=ib});var is=O(Mu=>{"use strict";var Iu=J(),Lu={identify:r=>r==null,createNode:()=>new Iu.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new Iu.Scalar(null),stringify:({source:r},e)=>typeof r=="string"&&Lu.test.test(r)?r:e.options.nullStr};Mu.nullTag=Lu});var Co=O(Du=>{"use strict";var ob=J(),$u={identify:r=>typeof r=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:r=>new ob.Scalar(r[0]==="t"||r[0]==="T"),stringify({source:r,value:e},t){if(r&&$u.test.test(r)){let n=r[0]==="t"||r[0]==="T";if(e===n)return r}return e?t.options.trueStr:t.options.falseStr}};Du.boolTag=$u});var Jt=O(Bu=>{"use strict";function ab({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}Bu.stringifyNumber=ab});var Io=O(os=>{"use strict";var cb=J(),No=Jt(),lb={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:No.stringifyNumber},ub={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():No.stringifyNumber(r)}},fb={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 cb.Scalar(parseFloat(r)),t=r.indexOf(".");return t!==-1&&r[r.length-1]==="0"&&(e.minFractionDigits=r.length-t-1),e},stringify:No.stringifyNumber};os.float=fb;os.floatExp=ub;os.floatNaN=lb});var Mo=O(cs=>{"use strict";var ju=Jt(),as=r=>typeof r=="bigint"||Number.isInteger(r),Lo=(r,e,t,{intAsBigInt:n})=>n?BigInt(r):parseInt(r.substring(e),t);function Fu(r,e,t){let{value:n}=r;return as(n)&&n>=0?t+n.toString(e):ju.stringifyNumber(r)}var db={identify:r=>as(r)&&r>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(r,e,t)=>Lo(r,2,8,t),stringify:r=>Fu(r,8,"0o")},pb={identify:as,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(r,e,t)=>Lo(r,0,10,t),stringify:ju.stringifyNumber},mb={identify:r=>as(r)&&r>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(r,e,t)=>Lo(r,2,16,t),stringify:r=>Fu(r,16,"0x")};cs.int=pb;cs.intHex=mb;cs.intOct=db});var Uu=O(qu=>{"use strict";var hb=qt(),gb=is(),yb=Ut(),bb=Mr(),wb=Co(),$o=Io(),Do=Mo(),vb=[hb.map,yb.seq,bb.string,gb.nullTag,wb.boolTag,Do.intOct,Do.int,Do.intHex,$o.floatNaN,$o.floatExp,$o.float];qu.schema=vb});var Wu=O(Ku=>{"use strict";var Sb=J(),kb=qt(),xb=Ut();function Ju(r){return typeof r=="bigint"||Number.isInteger(r)}var ls=({value:r})=>JSON.stringify(r),Eb=[{identify:r=>typeof r=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:r=>r,stringify:ls},{identify:r=>r==null,createNode:()=>new Sb.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:ls},{identify:r=>typeof r=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:r=>r==="true",stringify:ls},{identify:Ju,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})=>Ju(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:ls}],Ab={default:!0,tag:"",test:/^/,resolve(r,e){return e(`Unresolved plain scalar ${JSON.stringify(r)}`),r}},Tb=[kb.map,xb.seq].concat(Eb,Ab);Ku.schema=Tb});var jo=O(Hu=>{"use strict";var $r=_n("buffer"),Bo=J(),Pb=_r(),Ob={identify:r=>r instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(r,e){if(typeof $r.Buffer=="function")return $r.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 $r.Buffer=="function")a=o instanceof $r.Buffer?o.toString("base64"):$r.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=Bo.Scalar.BLOCK_LITERAL),e!==Bo.Scalar.QUOTE_DOUBLE){let c=Math.max(n.options.lineWidth-n.indent.length,n.options.minContentWidth),l=Math.ceil(a.length/c),d=new Array(l);for(let u=0,f=0;u<l;++u,f+=c)d[u]=a.substr(f,c);a=d.join(e===Bo.Scalar.BLOCK_LITERAL?`
|
|
63
|
+
`:" ")}return Pb.stringifyString({comment:r,type:e,value:a},n,s,i)}};Hu.binary=Ob});var ds=O(fs=>{"use strict";var us=M(),Fo=Je(),Rb=J(),_b=He();function Vu(r,e){if(us.isSeq(r))for(let t=0;t<r.items.length;++t){let n=r.items[t];if(!us.isPair(n)){if(us.isMap(n)){n.items.length>1&&e("Each pair must have its own sequence indicator");let s=n.items[0]||new Fo.Pair(new Rb.Scalar(null));if(n.commentBefore&&(s.key.commentBefore=s.key.commentBefore?`${n.commentBefore}
|
|
64
64
|
${s.key.commentBefore}`:n.commentBefore),n.comment){let i=s.value??s.key;i.comment=i.comment?`${n.comment}
|
|
65
|
-
${i.comment}`:n.comment}n=s}r.items[t]=ls.isPair(n)?n:new qo.Pair(n)}}else e("Expected a sequence for this tag");return r}function Vu(r,e,t){let{replacer:n}=t,s=new xb.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(qo.createPair(a,c,t))}return s}var Eb={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Hu,createNode:Vu};us.createPairs=Vu;us.pairs=Eb;us.resolvePairs=Hu});var Ko=P(Jo=>{"use strict";var Yu=L(),Uo=je(),Dr=We(),Ab=He(),Gu=fs(),ct=class r extends Ab.YAMLSeq{constructor(){super(),this.add=Dr.YAMLMap.prototype.add.bind(this),this.delete=Dr.YAMLMap.prototype.delete.bind(this),this.get=Dr.YAMLMap.prototype.get.bind(this),this.has=Dr.YAMLMap.prototype.has.bind(this),this.set=Dr.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(Yu.isPair(s)?(i=Uo.toJS(s.key,"",t),o=Uo.toJS(s.value,i,t)):i=Uo.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=Gu.createPairs(e,t,n),i=new this;return i.items=s.items,i}};ct.tag="tag:yaml.org,2002:omap";var Tb={collection:"seq",identify:r=>r instanceof Map,nodeClass:ct,default:!1,tag:"tag:yaml.org,2002:omap",resolve(r,e){let t=Gu.resolvePairs(r,e),n=[];for(let{key:s}of t.items)Yu.isScalar(s)&&(n.includes(s.value)?e(`Ordered maps must not include duplicate keys: ${s.value}`):n.push(s.value));return Object.assign(new ct,t)},createNode:(r,e,t)=>ct.from(r,e,t)};Jo.YAMLOMap=ct;Jo.omap=Tb});var ef=P(Wo=>{"use strict";var zu=J();function Qu({value:r,source:e},t){return e&&(r?Xu:Zu).test.test(e)?e:r?t.options.trueStr:t.options.falseStr}var Xu={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 zu.Scalar(!0),stringify:Qu},Zu={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 zu.Scalar(!1),stringify:Qu};Wo.falseTag=Zu;Wo.trueTag=Xu});var tf=P(ds=>{"use strict";var Pb=J(),Ho=Jt(),Ob={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:Ho.stringifyNumber},Rb={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():Ho.stringifyNumber(r)}},_b={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 Pb.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:Ho.stringifyNumber};ds.float=_b;ds.floatExp=Rb;ds.floatNaN=Ob});var nf=P(jr=>{"use strict";var rf=Jt(),Br=r=>typeof r=="bigint"||Number.isInteger(r);function ps(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 Vo(r,e,t){let{value:n}=r;if(Br(n)){let s=n.toString(e);return n<0?"-"+t+s.substr(1):t+s}return rf.stringifyNumber(r)}var Cb={identify:Br,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(r,e,t)=>ps(r,2,2,t),stringify:r=>Vo(r,2,"0b")},Nb={identify:Br,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(r,e,t)=>ps(r,1,8,t),stringify:r=>Vo(r,8,"0")},Ib={identify:Br,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(r,e,t)=>ps(r,0,10,t),stringify:rf.stringifyNumber},Lb={identify:Br,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(r,e,t)=>ps(r,2,16,t),stringify:r=>Vo(r,16,"0x")};jr.int=Ib;jr.intBin=Cb;jr.intHex=Lb;jr.intOct=Nb});var Go=P(Yo=>{"use strict";var gs=L(),ms=Je(),hs=We(),lt=class r extends hs.YAMLMap{constructor(e){super(e),this.tag=r.tag}add(e){let t;gs.isPair(e)?t=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?t=new ms.Pair(e.key,null):t=new ms.Pair(e,null),hs.findPair(this.items,t.key)||this.items.push(t)}get(e,t){let n=hs.findPair(this.items,e);return!t&&gs.isPair(n)?gs.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=hs.findPair(this.items,e);n&&!t?this.items.splice(this.items.indexOf(n),1):!n&&t&&this.items.push(new ms.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(ms.createPair(o,null,n));return i}};lt.tag="tag:yaml.org,2002:set";var Mb={collection:"map",identify:r=>r instanceof Set,nodeClass:lt,default:!1,tag:"tag:yaml.org,2002:set",createNode:(r,e,t)=>lt.from(r,e,t),resolve(r,e){if(gs.isMap(r)){if(r.hasAllNullValues(!0))return Object.assign(new lt,r);e("Set items must all have null values")}else e("Expected a mapping for this tag");return r}};Yo.YAMLSet=lt;Yo.set=Mb});var Qo=P(ys=>{"use strict";var $b=Jt();function zo(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 sf(r){let{value:e}=r,t=o=>o;if(typeof e=="bigint")t=o=>BigInt(o);else if(isNaN(e)||!isFinite(e))return $b.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 Db={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})=>zo(r,t),stringify:sf},Bb={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=>zo(r,!1),stringify:sf},of={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(of.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=zo(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$/,"")??""};ys.floatTime=Bb;ys.intTime=Db;ys.timestamp=of});var lf=P(cf=>{"use strict";var jb=qt(),Fb=ss(),qb=Ut(),Ub=Mr(),Jb=Fo(),af=ef(),Xo=tf(),bs=nf(),Kb=zn(),Wb=Ko(),Hb=fs(),Vb=Go(),Zo=Qo(),Yb=[jb.map,qb.seq,Ub.string,Fb.nullTag,af.trueTag,af.falseTag,bs.intBin,bs.intOct,bs.int,bs.intHex,Xo.floatNaN,Xo.floatExp,Xo.float,Jb.binary,Kb.merge,Wb.omap,Hb.pairs,Vb.set,Zo.intTime,Zo.floatTime,Zo.timestamp];cf.schema=Yb});var wf=P(ra=>{"use strict";var pf=qt(),Gb=ss(),mf=Ut(),zb=Mr(),Qb=No(),ea=Lo(),ta=$o(),Xb=qu(),Zb=Ku(),hf=Fo(),Fr=zn(),gf=Ko(),yf=fs(),uf=lf(),bf=Go(),ws=Qo(),ff=new Map([["core",Xb.schema],["failsafe",[pf.map,mf.seq,zb.string]],["json",Zb.schema],["yaml11",uf.schema],["yaml-1.1",uf.schema]]),df={binary:hf.binary,bool:Qb.boolTag,float:ea.float,floatExp:ea.floatExp,floatNaN:ea.floatNaN,floatTime:ws.floatTime,int:ta.int,intHex:ta.intHex,intOct:ta.intOct,intTime:ws.intTime,map:pf.map,merge:Fr.merge,null:Gb.nullTag,omap:gf.omap,pairs:yf.pairs,seq:mf.seq,set:bf.set,timestamp:ws.timestamp},ew={"tag:yaml.org,2002:binary":hf.binary,"tag:yaml.org,2002:merge":Fr.merge,"tag:yaml.org,2002:omap":gf.omap,"tag:yaml.org,2002:pairs":yf.pairs,"tag:yaml.org,2002:set":bf.set,"tag:yaml.org,2002:timestamp":ws.timestamp};function tw(r,e,t){let n=ff.get(e);if(n&&!r)return t&&!n.includes(Fr.merge)?n.concat(Fr.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(Fr.merge)),s.reduce((i,o)=>{let a=typeof o=="string"?df[o]:o;if(!a){let c=JSON.stringify(o),l=Object.keys(df).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},[])}ra.coreKnownTags=ew;ra.getTags=tw});var ia=P(vf=>{"use strict";var na=L(),rw=qt(),nw=Ut(),sw=Mr(),vs=wf(),iw=(r,e)=>r.key<e.key?-1:r.key>e.key?1:0,sa=class r{constructor({compat:e,customTags:t,merge:n,resolveKnownTags:s,schema:i,sortMapEntries:o,toStringDefaults:a}){this.compat=Array.isArray(e)?vs.getTags(e,"compat"):e?vs.getTags(null,e):null,this.name=typeof i=="string"&&i||"core",this.knownTags=s?vs.coreKnownTags:{},this.tags=vs.getTags(t,this.name,n),this.toStringOptions=a??null,Object.defineProperty(this,na.MAP,{value:rw.map}),Object.defineProperty(this,na.SCALAR,{value:sw.string}),Object.defineProperty(this,na.SEQ,{value:nw.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?iw:null}clone(){let e=Object.create(r.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}};vf.Schema=sa});var kf=P(Sf=>{"use strict";var ow=L(),oa=Cr(),qr=Pr();function aw(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=oa.createStringifyContext(r,e),{commentString:i}=s.options;if(r.commentBefore){t.length!==1&&t.unshift("");let c=i(r.commentBefore);t.unshift(qr.indentComment(c,""))}let o=!1,a=null;if(r.contents){if(ow.isNode(r.contents)){if(r.contents.spaceBefore&&n&&t.push(""),r.contents.commentBefore){let d=i(r.contents.commentBefore);t.push(qr.indentComment(d,""))}s.forceBlockIndent=!!r.comment,a=r.contents.comment}let c=a?void 0:()=>o=!0,l=oa.stringify(r.contents,s,()=>a=null,c);a&&(l+=qr.lineComment(l,"",i(a))),(l[0]==="|"||l[0]===">")&&t[t.length-1]==="---"?t[t.length-1]=`--- ${l}`:t.push(l)}else t.push(oa.stringify(r.contents,s));if(r.directives?.docEnd)if(r.comment){let c=i(r.comment);c.includes(`
|
|
65
|
+
${i.comment}`:n.comment}n=s}r.items[t]=us.isPair(n)?n:new Fo.Pair(n)}}else e("Expected a sequence for this tag");return r}function Yu(r,e,t){let{replacer:n}=t,s=new _b.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(Fo.createPair(a,c,t))}return s}var Cb={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Vu,createNode:Yu};fs.createPairs=Yu;fs.pairs=Cb;fs.resolvePairs=Vu});var Jo=O(Uo=>{"use strict";var Gu=M(),qo=je(),Dr=We(),Nb=He(),zu=ds(),ct=class r extends Nb.YAMLSeq{constructor(){super(),this.add=Dr.YAMLMap.prototype.add.bind(this),this.delete=Dr.YAMLMap.prototype.delete.bind(this),this.get=Dr.YAMLMap.prototype.get.bind(this),this.has=Dr.YAMLMap.prototype.has.bind(this),this.set=Dr.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(Gu.isPair(s)?(i=qo.toJS(s.key,"",t),o=qo.toJS(s.value,i,t)):i=qo.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=zu.createPairs(e,t,n),i=new this;return i.items=s.items,i}};ct.tag="tag:yaml.org,2002:omap";var Ib={collection:"seq",identify:r=>r instanceof Map,nodeClass:ct,default:!1,tag:"tag:yaml.org,2002:omap",resolve(r,e){let t=zu.resolvePairs(r,e),n=[];for(let{key:s}of t.items)Gu.isScalar(s)&&(n.includes(s.value)?e(`Ordered maps must not include duplicate keys: ${s.value}`):n.push(s.value));return Object.assign(new ct,t)},createNode:(r,e,t)=>ct.from(r,e,t)};Uo.YAMLOMap=ct;Uo.omap=Ib});var tf=O(Ko=>{"use strict";var Qu=J();function Xu({value:r,source:e},t){return e&&(r?Zu:ef).test.test(e)?e:r?t.options.trueStr:t.options.falseStr}var Zu={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 Qu.Scalar(!0),stringify:Xu},ef={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 Qu.Scalar(!1),stringify:Xu};Ko.falseTag=ef;Ko.trueTag=Zu});var rf=O(ps=>{"use strict";var Lb=J(),Wo=Jt(),Mb={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:Wo.stringifyNumber},$b={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():Wo.stringifyNumber(r)}},Db={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 Lb.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:Wo.stringifyNumber};ps.float=Db;ps.floatExp=$b;ps.floatNaN=Mb});var sf=O(jr=>{"use strict";var nf=Jt(),Br=r=>typeof r=="bigint"||Number.isInteger(r);function ms(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 Ho(r,e,t){let{value:n}=r;if(Br(n)){let s=n.toString(e);return n<0?"-"+t+s.substr(1):t+s}return nf.stringifyNumber(r)}var Bb={identify:Br,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(r,e,t)=>ms(r,2,2,t),stringify:r=>Ho(r,2,"0b")},jb={identify:Br,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(r,e,t)=>ms(r,1,8,t),stringify:r=>Ho(r,8,"0")},Fb={identify:Br,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(r,e,t)=>ms(r,0,10,t),stringify:nf.stringifyNumber},qb={identify:Br,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(r,e,t)=>ms(r,2,16,t),stringify:r=>Ho(r,16,"0x")};jr.int=Fb;jr.intBin=Bb;jr.intHex=qb;jr.intOct=jb});var Yo=O(Vo=>{"use strict";var ys=M(),hs=Je(),gs=We(),lt=class r extends gs.YAMLMap{constructor(e){super(e),this.tag=r.tag}add(e){let t;ys.isPair(e)?t=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?t=new hs.Pair(e.key,null):t=new hs.Pair(e,null),gs.findPair(this.items,t.key)||this.items.push(t)}get(e,t){let n=gs.findPair(this.items,e);return!t&&ys.isPair(n)?ys.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=gs.findPair(this.items,e);n&&!t?this.items.splice(this.items.indexOf(n),1):!n&&t&&this.items.push(new hs.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(hs.createPair(o,null,n));return i}};lt.tag="tag:yaml.org,2002:set";var Ub={collection:"map",identify:r=>r instanceof Set,nodeClass:lt,default:!1,tag:"tag:yaml.org,2002:set",createNode:(r,e,t)=>lt.from(r,e,t),resolve(r,e){if(ys.isMap(r)){if(r.hasAllNullValues(!0))return Object.assign(new lt,r);e("Set items must all have null values")}else e("Expected a mapping for this tag");return r}};Vo.YAMLSet=lt;Vo.set=Ub});var zo=O(bs=>{"use strict";var Jb=Jt();function Go(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 of(r){let{value:e}=r,t=o=>o;if(typeof e=="bigint")t=o=>BigInt(o);else if(isNaN(e)||!isFinite(e))return Jb.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 Kb={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})=>Go(r,t),stringify:of},Wb={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=>Go(r,!1),stringify:of},af={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(af.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=Go(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$/,"")??""};bs.floatTime=Wb;bs.intTime=Kb;bs.timestamp=af});var uf=O(lf=>{"use strict";var Hb=qt(),Vb=is(),Yb=Ut(),Gb=Mr(),zb=jo(),cf=tf(),Qo=rf(),ws=sf(),Qb=Qn(),Xb=Jo(),Zb=ds(),ew=Yo(),Xo=zo(),tw=[Hb.map,Yb.seq,Gb.string,Vb.nullTag,cf.trueTag,cf.falseTag,ws.intBin,ws.intOct,ws.int,ws.intHex,Qo.floatNaN,Qo.floatExp,Qo.float,zb.binary,Qb.merge,Xb.omap,Zb.pairs,ew.set,Xo.intTime,Xo.floatTime,Xo.timestamp];lf.schema=tw});var vf=O(ta=>{"use strict";var mf=qt(),rw=is(),hf=Ut(),nw=Mr(),sw=Co(),Zo=Io(),ea=Mo(),iw=Uu(),ow=Wu(),gf=jo(),Fr=Qn(),yf=Jo(),bf=ds(),ff=uf(),wf=Yo(),vs=zo(),df=new Map([["core",iw.schema],["failsafe",[mf.map,hf.seq,nw.string]],["json",ow.schema],["yaml11",ff.schema],["yaml-1.1",ff.schema]]),pf={binary:gf.binary,bool:sw.boolTag,float:Zo.float,floatExp:Zo.floatExp,floatNaN:Zo.floatNaN,floatTime:vs.floatTime,int:ea.int,intHex:ea.intHex,intOct:ea.intOct,intTime:vs.intTime,map:mf.map,merge:Fr.merge,null:rw.nullTag,omap:yf.omap,pairs:bf.pairs,seq:hf.seq,set:wf.set,timestamp:vs.timestamp},aw={"tag:yaml.org,2002:binary":gf.binary,"tag:yaml.org,2002:merge":Fr.merge,"tag:yaml.org,2002:omap":yf.omap,"tag:yaml.org,2002:pairs":bf.pairs,"tag:yaml.org,2002:set":wf.set,"tag:yaml.org,2002:timestamp":vs.timestamp};function cw(r,e,t){let n=df.get(e);if(n&&!r)return t&&!n.includes(Fr.merge)?n.concat(Fr.merge):n.slice();let s=n;if(!s)if(Array.isArray(r))s=[];else{let i=Array.from(df.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(Fr.merge)),s.reduce((i,o)=>{let a=typeof o=="string"?pf[o]:o;if(!a){let c=JSON.stringify(o),l=Object.keys(pf).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},[])}ta.coreKnownTags=aw;ta.getTags=cw});var sa=O(Sf=>{"use strict";var ra=M(),lw=qt(),uw=Ut(),fw=Mr(),Ss=vf(),dw=(r,e)=>r.key<e.key?-1:r.key>e.key?1:0,na=class r{constructor({compat:e,customTags:t,merge:n,resolveKnownTags:s,schema:i,sortMapEntries:o,toStringDefaults:a}){this.compat=Array.isArray(e)?Ss.getTags(e,"compat"):e?Ss.getTags(null,e):null,this.name=typeof i=="string"&&i||"core",this.knownTags=s?Ss.coreKnownTags:{},this.tags=Ss.getTags(t,this.name,n),this.toStringOptions=a??null,Object.defineProperty(this,ra.MAP,{value:lw.map}),Object.defineProperty(this,ra.SCALAR,{value:fw.string}),Object.defineProperty(this,ra.SEQ,{value:uw.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?dw:null}clone(){let e=Object.create(r.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}};Sf.Schema=na});var xf=O(kf=>{"use strict";var pw=M(),ia=Cr(),qr=Pr();function mw(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=ia.createStringifyContext(r,e),{commentString:i}=s.options;if(r.commentBefore){t.length!==1&&t.unshift("");let c=i(r.commentBefore);t.unshift(qr.indentComment(c,""))}let o=!1,a=null;if(r.contents){if(pw.isNode(r.contents)){if(r.contents.spaceBefore&&n&&t.push(""),r.contents.commentBefore){let d=i(r.contents.commentBefore);t.push(qr.indentComment(d,""))}s.forceBlockIndent=!!r.comment,a=r.contents.comment}let c=a?void 0:()=>o=!0,l=ia.stringify(r.contents,s,()=>a=null,c);a&&(l+=qr.lineComment(l,"",i(a))),(l[0]==="|"||l[0]===">")&&t[t.length-1]==="---"?t[t.length-1]=`--- ${l}`:t.push(l)}else t.push(ia.stringify(r.contents,s));if(r.directives?.docEnd)if(r.comment){let c=i(r.comment);c.includes(`
|
|
66
66
|
`)?(t.push("..."),t.push(qr.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(qr.indentComment(i(c),"")))}return t.join(`
|
|
67
67
|
`)+`
|
|
68
|
-
`}
|
|
68
|
+
`}kf.stringifyDocument=mw});var Ur=O(Ef=>{"use strict";var hw=Ar(),Kt=Un(),oe=M(),gw=Je(),yw=je(),bw=sa(),ww=xf(),oa=Bn(),vw=lo(),Sw=Tr(),aa=co(),ca=class r{constructor(e,t,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,oe.NODE_TYPE,{value:oe.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 aa.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,{[oe.NODE_TYPE]:{value:oe.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=oe.isNode(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){Wt(this.contents)&&this.contents.add(e)}addIn(e,t){Wt(this.contents)&&this.contents.addIn(e,t)}createAlias(e,t){if(!e.anchor){let n=oa.anchorNames(this);e.anchor=!t||n.has(t)?oa.findNewAnchor(t||"a",n):t}return new hw.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 b=A=>typeof A=="number"||A instanceof String||A instanceof Number,x=t.filter(b).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:d}=n??{},{onAnchor:u,setAnchors:f,sourceObjects:p}=oa.createNodeAnchors(this,o||"a"),y={aliasDuplicateObjects:i??!0,keepUndefined:c??!1,onAnchor:u,onTagObj:l,replacer:s,schema:this.schema,sourceObjects:p},m=Sw.createNode(e,d,y);return a&&oe.isCollection(m)&&(m.flow=!0),f(),m}createPair(e,t,n={}){let s=this.createNode(e,null,n),i=this.createNode(t,null,n);return new gw.Pair(s,i)}delete(e){return Wt(this.contents)?this.contents.delete(e):!1}deleteIn(e){return Kt.isEmptyPath(e)?this.contents==null?!1:(this.contents=null,!0):Wt(this.contents)?this.contents.deleteIn(e):!1}get(e,t){return oe.isCollection(this.contents)?this.contents.get(e,t):void 0}getIn(e,t){return Kt.isEmptyPath(e)?!t&&oe.isScalar(this.contents)?this.contents.value:this.contents:oe.isCollection(this.contents)?this.contents.getIn(e,t):void 0}has(e){return oe.isCollection(this.contents)?this.contents.has(e):!1}hasIn(e){return Kt.isEmptyPath(e)?this.contents!==void 0:oe.isCollection(this.contents)?this.contents.hasIn(e):!1}set(e,t){this.contents==null?this.contents=Kt.collectionFromPath(this.schema,[e],t):Wt(this.contents)&&this.contents.set(e,t)}setIn(e,t){Kt.isEmptyPath(e)?this.contents=t:this.contents==null?this.contents=Kt.collectionFromPath(this.schema,Array.from(e),t):Wt(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 aa.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 aa.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 bw.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=yw.toJS(this.contents,t??"",a);if(typeof i=="function")for(let{count:l,res:d}of a.anchors.values())i(d,l);return typeof o=="function"?vw.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 ww.stringifyDocument(this,e)}};function Wt(r){if(oe.isCollection(r))return!0;throw new Error("Expected a YAML collection as document contents")}Ef.Document=ca});var Wr=O(Kr=>{"use strict";var Jr=class extends Error{constructor(e,t,n,s){super(),this.name=e,this.code=n,this.message=s,this.pos=t}},la=class extends Jr{constructor(e,t,n){super("YAMLParseError",e,t,n)}},ua=class extends Jr{constructor(e,t,n){super("YAMLWarning",e,t,n)}},kw=(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
|
|
69
69
|
`),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+=`:
|
|
70
70
|
|
|
71
71
|
${o}
|
|
72
72
|
${l}
|
|
73
|
-
`}};Kr.YAMLError=Jr;Kr.YAMLParseError=
|
|
74
|
-
`))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(
|
|
75
|
-
`+m.comment:a.comment=m.comment);continue}(m.newlineAfterProp||
|
|
76
|
-
`+g.comment:
|
|
77
|
-
`+
|
|
78
|
-
`+
|
|
79
|
-
`+
|
|
80
|
-
`+b.comment:l.comment=b.comment),l.range=[n.offset,m,b.offset]}else l.range=[n.offset,m,m];return l}
|
|
81
|
-
`.repeat(Math.max(1,o.length-1)):"",b=n+s.length;return e.source&&(b+=e.source.length),{value:m,type:i,comment:s.comment,range:[n,b,b]}}let c=e.indent+s.indent,l=e.offset+s.length,d=0;for(let m=0;m<a;++m){let[b,
|
|
82
|
-
`;for(let m=d;m<a;++m){let[b,
|
|
83
|
-
`):b.length>c||
|
|
73
|
+
`}};Kr.YAMLError=Jr;Kr.YAMLParseError=la;Kr.YAMLWarning=ua;Kr.prettifyError=kw});var Hr=O(Af=>{"use strict";function xw(r,{flow:e,indicator:t,next:n,offset:s,onError:i,parentIndent:o,startOnNewline:a}){let c=!1,l=a,d=a,u="",f="",p=!1,y=!1,m=null,b=null,x=null,A=null,g=null,w=null,k=null;for(let P of r)switch(y&&(P.type!=="space"&&P.type!=="newline"&&P.type!=="comma"&&i(P.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),y=!1),m&&(l&&P.type!=="comment"&&P.type!=="newline"&&i(m,"TAB_AS_INDENT","Tabs are not allowed as indentation"),m=null),P.type){case"space":!e&&(t!=="doc-start"||n?.type!=="flow-collection")&&P.source.includes(" ")&&(m=P),d=!0;break;case"comment":{d||i(P,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let D=P.source.substring(1)||" ";u?u+=f+D:u=D,f="",l=!1;break}case"newline":l?u?u+=P.source:(!w||t!=="seq-item-ind")&&(c=!0):f+=P.source,l=!0,p=!0,(b||x)&&(A=P),d=!0;break;case"anchor":b&&i(P,"MULTIPLE_ANCHORS","A node can have at most one anchor"),P.source.endsWith(":")&&i(P.offset+P.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),b=P,k??(k=P.offset),l=!1,d=!1,y=!0;break;case"tag":{x&&i(P,"MULTIPLE_TAGS","A node can have at most one tag"),x=P,k??(k=P.offset),l=!1,d=!1,y=!0;break}case t:(b||x)&&i(P,"BAD_PROP_ORDER",`Anchors and tags must be after the ${P.source} indicator`),w&&i(P,"UNEXPECTED_TOKEN",`Unexpected ${P.source} in ${e??"collection"}`),w=P,l=t==="seq-item-ind"||t==="explicit-key-ind",d=!1;break;case"comma":if(e){g&&i(P,"UNEXPECTED_TOKEN",`Unexpected , in ${e}`),g=P,l=!1,d=!1;break}default:i(P,"UNEXPECTED_TOKEN",`Unexpected ${P.type} token`),l=!1,d=!1}let E=r[r.length-1],T=E?E.offset+E.source.length:s;return y&&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:g,found:w,spaceBefore:c,comment:u,hasNewline:p,anchor:b,tag:x,newlineAfterProp:A,end:T,start:k??T}}Af.resolveProps=xw});var ks=O(Tf=>{"use strict";function fa(r){if(!r)return null;switch(r.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(r.source.includes(`
|
|
74
|
+
`))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(fa(e.key)||fa(e.value))return!0}return!1;default:return!0}}Tf.containsNewline=fa});var da=O(Pf=>{"use strict";var Ew=ks();function Aw(r,e,t){if(e?.type==="flow-collection"){let n=e.end[0];n.indent===r&&(n.source==="]"||n.source==="}")&&Ew.containsNewline(e)&&t(n,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}Pf.flowIndentCheck=Aw});var pa=O(Rf=>{"use strict";var Of=M();function Tw(r,e,t){let{uniqueKeys:n}=r.options;if(n===!1)return!1;let s=typeof n=="function"?n:(i,o)=>i===o||Of.isScalar(i)&&Of.isScalar(o)&&i.value===o.value;return e.some(i=>s(i.key,t))}Rf.mapIncludes=Tw});var Mf=O(Lf=>{"use strict";var _f=Je(),Pw=We(),Cf=Hr(),Ow=ks(),Nf=da(),Rw=pa(),If="All mapping items must start at the same column";function _w({composeNode:r,composeEmptyNode:e},t,n,s,i){let o=i?.nodeClass??Pw.YAMLMap,a=new o(t.schema);t.atRoot&&(t.atRoot=!1);let c=n.offset,l=null;for(let d of n.items){let{start:u,key:f,sep:p,value:y}=d,m=Cf.resolveProps(u,{indicator:"explicit-key-ind",next:f??p?.[0],offset:c,onError:s,parentIndent:n.indent,startOnNewline:!0}),b=!m.found;if(b){if(f&&(f.type==="block-seq"?s(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in f&&f.indent!==n.indent&&s(c,"BAD_INDENT",If)),!m.anchor&&!m.tag&&!p){l=m.end,m.comment&&(a.comment?a.comment+=`
|
|
75
|
+
`+m.comment:a.comment=m.comment);continue}(m.newlineAfterProp||Ow.containsNewline(f))&&s(f??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",If);t.atKey=!0;let x=m.end,A=f?r(t,f,m,s):e(t,x,u,null,m,s);t.schema.compat&&Nf.flowIndentCheck(n.indent,f,s),t.atKey=!1,Rw.mapIncludes(t,a.items,A)&&s(x,"DUPLICATE_KEY","Map keys must be unique");let g=Cf.resolveProps(p??[],{indicator:"map-value-ind",next:y,offset:A.range[2],onError:s,parentIndent:n.indent,startOnNewline:!f||f.type==="block-scalar"});if(c=g.end,g.found){b&&(y?.type==="block-map"&&!g.hasNewline&&s(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),t.options.strict&&m.start<g.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 w=y?r(t,y,g,s):e(t,c,p,null,g,s);t.schema.compat&&Nf.flowIndentCheck(n.indent,y,s),c=w.range[2];let k=new _f.Pair(A,w);t.options.keepSourceTokens&&(k.srcToken=d),a.items.push(k)}else{b&&s(A.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),g.comment&&(A.comment?A.comment+=`
|
|
76
|
+
`+g.comment:A.comment=g.comment);let w=new _f.Pair(A);t.options.keepSourceTokens&&(w.srcToken=d),a.items.push(w)}}return l&&l<c&&s(l,"IMPOSSIBLE","Map comment with trailing content"),a.range=[n.offset,c,l??c],a}Lf.resolveBlockMap=_w});var Df=O($f=>{"use strict";var Cw=He(),Nw=Hr(),Iw=da();function Lw({composeNode:r,composeEmptyNode:e},t,n,s,i){let o=i?.nodeClass??Cw.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:d,value:u}of n.items){let f=Nw.resolveProps(d,{indicator:"seq-item-ind",next:u,offset:c,onError:s,parentIndent:n.indent,startOnNewline:!0});if(!f.found)if(f.anchor||f.tag||u)u?.type==="block-seq"?s(f.end,"BAD_INDENT","All sequence items must start at the same column"):s(c,"MISSING_CHAR","Sequence item without - indicator");else{l=f.end,f.comment&&(a.comment=f.comment);continue}let p=u?r(t,u,f,s):e(t,f.end,d,null,f,s);t.schema.compat&&Iw.flowIndentCheck(n.indent,u,s),c=p.range[2],a.items.push(p)}return a.range=[n.offset,c,l??c],a}$f.resolveBlockSeq=Lw});var Ht=O(Bf=>{"use strict";function Mw(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 d=c.substring(1)||" ";s?s+=o+d:s=d,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}}Bf.resolveEnd=Mw});var Uf=O(qf=>{"use strict";var $w=M(),Dw=Je(),jf=We(),Bw=He(),jw=Ht(),Ff=Hr(),Fw=ks(),qw=pa(),ma="Block collections are not allowed within flow collections",ha=r=>r&&(r.type==="block-map"||r.type==="block-seq");function Uw({composeNode:r,composeEmptyNode:e},t,n,s,i){let o=n.start.source==="{",a=o?"flow map":"flow sequence",c=i?.nodeClass??(o?jf.YAMLMap:Bw.YAMLSeq),l=new c(t.schema);l.flow=!0;let d=t.atRoot;d&&(t.atRoot=!1),t.atKey&&(t.atKey=!1);let u=n.offset+n.start.source.length;for(let b=0;b<n.items.length;++b){let x=n.items[b],{start:A,key:g,sep:w,value:k}=x,E=Ff.resolveProps(A,{flow:a,indicator:"explicit-key-ind",next:g??w?.[0],offset:u,onError:s,parentIndent:n.indent,startOnNewline:!1});if(!E.found){if(!E.anchor&&!E.tag&&!w&&!k){b===0&&E.comma?s(E.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`):b<n.items.length-1&&s(E.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${a}`),E.comment&&(l.comment?l.comment+=`
|
|
77
|
+
`+E.comment:l.comment=E.comment),u=E.end;continue}!o&&t.options.strict&&Fw.containsNewline(g)&&s(g,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(b===0)E.comma&&s(E.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`);else if(E.comma||s(E.start,"MISSING_CHAR",`Missing , between ${a} items`),E.comment){let T="";e:for(let P of A)switch(P.type){case"comma":case"space":break;case"comment":T=P.source.substring(1);break e;default:break e}if(T){let P=l.items[l.items.length-1];$w.isPair(P)&&(P=P.value??P.key),P.comment?P.comment+=`
|
|
78
|
+
`+T:P.comment=T,E.comment=E.comment.substring(T.length+1)}}if(!o&&!w&&!E.found){let T=k?r(t,k,E,s):e(t,E.end,w,null,E,s);l.items.push(T),u=T.range[2],ha(k)&&s(T.range,"BLOCK_IN_FLOW",ma)}else{t.atKey=!0;let T=E.end,P=g?r(t,g,E,s):e(t,T,A,null,E,s);ha(g)&&s(P.range,"BLOCK_IN_FLOW",ma),t.atKey=!1;let D=Ff.resolveProps(w??[],{flow:a,indicator:"map-value-ind",next:k,offset:P.range[2],onError:s,parentIndent:n.indent,startOnNewline:!1});if(D.found){if(!o&&!E.found&&t.options.strict){if(w)for(let B of w){if(B===D.found)break;if(B.type==="newline"){s(B,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}E.start<D.found.offset-1024&&s(D.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else k&&("source"in k&&k.source?.[0]===":"?s(k,"MISSING_CHAR",`Missing space after : in ${a}`):s(D.start,"MISSING_CHAR",`Missing , or : between ${a} items`));let te=k?r(t,k,D,s):D.found?e(t,D.end,w,null,D,s):null;te?ha(k)&&s(te.range,"BLOCK_IN_FLOW",ma):D.comment&&(P.comment?P.comment+=`
|
|
79
|
+
`+D.comment:P.comment=D.comment);let V=new Dw.Pair(P,te);if(t.options.keepSourceTokens&&(V.srcToken=x),o){let B=l;qw.mapIncludes(t,B.items,P)&&s(T,"DUPLICATE_KEY","Map keys must be unique"),B.items.push(V)}else{let B=new jf.YAMLMap(t.schema);B.flow=!0,B.items.push(V);let it=(te??P).range;B.range=[P.range[0],it[1],it[2]],l.items.push(B)}u=te?te.range[2]:D.end}}let f=o?"}":"]",[p,...y]=n.end,m=u;if(p?.source===f)m=p.offset+p.source.length;else{let b=a[0].toUpperCase()+a.substring(1),x=d?`${b} must end with a ${f}`:`${b} in block collection must be sufficiently indented and end with a ${f}`;s(u,d?"MISSING_CHAR":"BAD_INDENT",x),p&&p.source.length!==1&&y.unshift(p)}if(y.length>0){let b=jw.resolveEnd(y,m,t.options.strict,s);b.comment&&(l.comment?l.comment+=`
|
|
80
|
+
`+b.comment:l.comment=b.comment),l.range=[n.offset,m,b.offset]}else l.range=[n.offset,m,m];return l}qf.resolveFlowCollection=Uw});var Kf=O(Jf=>{"use strict";var Jw=M(),Kw=J(),Ww=We(),Hw=He(),Vw=Mf(),Yw=Df(),Gw=Uf();function ga(r,e,t,n,s,i){let o=t.type==="block-map"?Vw.resolveBlockMap(r,e,t,n,i):t.type==="block-seq"?Yw.resolveBlockSeq(r,e,t,n,i):Gw.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 zw(r,e,t,n,s){let i=n.tag,o=i?e.directives.tagName(i.source,f=>s(i,"TAG_RESOLVE_FAILED",f)):null;if(t.type==="block-seq"){let{anchor:f,newlineAfterProp:p}=n,y=f&&i?f.offset>i.offset?f:i:f??i;y&&(!p||p.offset<y.offset)&&s(y,"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===Ww.YAMLMap.tagName&&a==="map"||o===Hw.YAMLSeq.tagName&&a==="seq")return ga(r,e,t,s,o);let c=e.schema.tags.find(f=>f.tag===o&&f.collection===a);if(!c){let f=e.schema.knownTags[o];if(f?.collection===a)e.schema.tags.push(Object.assign({},f,{default:!1})),c=f;else return f?s(i,"BAD_COLLECTION_TYPE",`${f.tag} used for ${a} collection, but expects ${f.collection??"scalar"}`,!0):s(i,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),ga(r,e,t,s,o)}let l=ga(r,e,t,s,o,c),d=c.resolve?.(l,f=>s(i,"TAG_RESOLVE_FAILED",f),e.options)??l,u=Jw.isNode(d)?d:new Kw.Scalar(d);return u.range=l.range,u.tag=o,c?.format&&(u.format=c.format),u}Jf.composeCollection=zw});var ba=O(Wf=>{"use strict";var ya=J();function Qw(r,e,t){let n=e.offset,s=Xw(e,r.options.strict,t);if(!s)return{value:"",type:null,comment:"",range:[n,n,n]};let i=s.mode===">"?ya.Scalar.BLOCK_FOLDED:ya.Scalar.BLOCK_LITERAL,o=e.source?Zw(e.source):[],a=o.length;for(let m=o.length-1;m>=0;--m){let b=o[m][1];if(b===""||b==="\r")a=m;else break}if(a===0){let m=s.chomp==="+"&&o.length>0?`
|
|
81
|
+
`.repeat(Math.max(1,o.length-1)):"",b=n+s.length;return e.source&&(b+=e.source.length),{value:m,type:i,comment:s.comment,range:[n,b,b]}}let c=e.indent+s.indent,l=e.offset+s.length,d=0;for(let m=0;m<a;++m){let[b,x]=o[m];if(x===""||x==="\r")s.indent===0&&b.length>c&&(c=b.length);else{b.length<c&&t(l+b.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),s.indent===0&&(c=b.length),d=m,c===0&&!r.atRoot&&t(l,"BAD_INDENT","Block scalar values in collections must be indented");break}l+=b.length+x.length+1}for(let m=o.length-1;m>=a;--m)o[m][0].length>c&&(a=m+1);let u="",f="",p=!1;for(let m=0;m<d;++m)u+=o[m][0].slice(c)+`
|
|
82
|
+
`;for(let m=d;m<a;++m){let[b,x]=o[m];l+=b.length+x.length+1;let A=x[x.length-1]==="\r";if(A&&(x=x.slice(0,-1)),x&&b.length<c){let w=`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",w),b=""}i===ya.Scalar.BLOCK_LITERAL?(u+=f+b.slice(c)+x,f=`
|
|
83
|
+
`):b.length>c||x[0]===" "?(f===" "?f=`
|
|
84
84
|
`:!p&&f===`
|
|
85
85
|
`&&(f=`
|
|
86
86
|
|
|
87
|
-
`),u+=f+b.slice(c)+
|
|
88
|
-
`,p=!0):
|
|
87
|
+
`),u+=f+b.slice(c)+x,f=`
|
|
88
|
+
`,p=!0):x===""?f===`
|
|
89
89
|
`?u+=`
|
|
90
90
|
`:f=`
|
|
91
|
-
`:(u+=f+
|
|
91
|
+
`:(u+=f+x,f=" ",p=!1)}switch(s.chomp){case"-":break;case"+":for(let m=a;m<o.length;++m)u+=`
|
|
92
92
|
`+o[m][0].slice(c);u[u.length-1]!==`
|
|
93
93
|
`&&(u+=`
|
|
94
94
|
`);break;default:u+=`
|
|
95
|
-
`}let y=n+s.length+e.source.length;return{value:u,type:i,comment:s.comment,range:[n,y,y]}}function
|
|
95
|
+
`}let y=n+s.length+e.source.length;return{value:u,type:i,comment:s.comment,range:[n,y,y]}}function Xw({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 f=1;f<s.length;++f){let p=s[f];if(!a&&(p==="-"||p==="+"))a=p;else{let y=Number(p);!o&&y?o=y:c===-1&&(c=r+f)}}c!==-1&&n(c,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${s}`);let l=!1,d="",u=s.length;for(let f=1;f<e.length;++f){let p=e[f];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,d=p.source.substring(1);break;case"error":n(p,"UNEXPECTED_TOKEN",p.message),u+=p.source.length;break;default:{let y=`Unexpected token in block scalar header: ${p.type}`;n(p,"UNEXPECTED_TOKEN",y);let m=p.source;m&&typeof m=="string"&&(u+=m.length)}}}return{mode:i,indent:o,chomp:a,comment:d,length:u}}function Zw(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}Wf.resolveBlockScalar=Qw});var va=O(Vf=>{"use strict";var wa=J(),ev=Ht();function tv(r,e,t){let{offset:n,type:s,source:i,end:o}=r,a,c,l=(f,p,y)=>t(n+f,p,y);switch(s){case"scalar":a=wa.Scalar.PLAIN,c=rv(i,l);break;case"single-quoted-scalar":a=wa.Scalar.QUOTE_SINGLE,c=nv(i,l);break;case"double-quoted-scalar":a=wa.Scalar.QUOTE_DOUBLE,c=sv(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 d=n+i.length,u=ev.resolveEnd(o,d,e,t);return{value:c,type:a,comment:u.comment,range:[n,d,u.offset]}}function rv(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}`),Hf(r)}function nv(r,e){return(r[r.length-1]!=="'"||r.length===1)&&e(r.length,"MISSING_CHAR","Missing closing 'quote"),Hf(r.slice(1,-1)).replace(/''/g,"'")}function Hf(r){let e,t;try{e=new RegExp(`(.*?)(?<![ ])[ ]*\r?
|
|
96
96
|
`,"sy"),t=new RegExp(`[ ]*(.*?)(?:(?<![ ])[ ]*)?\r?
|
|
97
97
|
`,"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===`
|
|
98
98
|
`?s+=i:i=`
|
|
99
|
-
`:(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
|
|
99
|
+
`:(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 sv(r,e){let t="";for(let n=1;n<r.length-1;++n){let s=r[n];if(!(s==="\r"&&r[n+1]===`
|
|
100
100
|
`))if(s===`
|
|
101
|
-
`){let{fold:i,offset:o}=
|
|
101
|
+
`){let{fold:i,offset:o}=iv(r,n);t+=i,n=o}else if(s==="\\"){let i=r[++n],o=ov[i];if(o)t+=o;else if(i===`
|
|
102
102
|
`)for(i=r[n+1];i===" "||i===" ";)i=r[++n+1];else if(i==="\r"&&r[n+1]===`
|
|
103
|
-
`)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+=
|
|
103
|
+
`)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+=av(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!==`
|
|
104
104
|
`&&!(o==="\r"&&r[n+2]===`
|
|
105
|
-
`)&&(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
|
|
105
|
+
`)&&(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 iv(r,e){let t="",n=r[e+1];for(;(n===" "||n===" "||n===`
|
|
106
106
|
`||n==="\r")&&!(n==="\r"&&r[e+2]!==`
|
|
107
107
|
`);)n===`
|
|
108
108
|
`&&(t+=`
|
|
109
|
-
`),e+=1,n=r[e+1];return t||(t=" "),{fold:t,offset:e}}var
|
|
110
|
-
`,r:"\r",t:" ",v:"\v",N:"\x85",_:"\xA0",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function
|
|
109
|
+
`),e+=1,n=r[e+1];return t||(t=" "),{fold:t,offset:e}}var ov={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
|
|
110
|
+
`,r:"\r",t:" ",v:"\v",N:"\x85",_:"\xA0",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function av(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)}Vf.resolveFlowScalar=tv});var zf=O(Gf=>{"use strict";var ut=M(),Yf=J(),cv=ba(),lv=va();function uv(r,e,t,n){let{value:s,type:i,comment:o,range:a}=e.type==="block-scalar"?cv.resolveBlockScalar(r,e,n):lv.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[ut.SCALAR]:c?l=fv(r.schema,s,c,t,n):e.type==="scalar"?l=dv(r,s,e,n):l=r.schema[ut.SCALAR];let d;try{let u=l.resolve(s,f=>n(t??e,"TAG_RESOLVE_FAILED",f),r.options);d=ut.isScalar(u)?u:new Yf.Scalar(u)}catch(u){let f=u instanceof Error?u.message:String(u);n(t??e,"TAG_RESOLVE_FAILED",f),d=new Yf.Scalar(s)}return d.range=a,d.source=s,i&&(d.type=i),c&&(d.tag=c),l.format&&(d.format=l.format),o&&(d.comment=o),d}function fv(r,e,t,n,s){if(t==="!")return r[ut.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[ut.SCALAR])}function dv({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[ut.SCALAR];if(t.compat){let a=t.compat.find(c=>c.default&&c.test?.test(n))??t[ut.SCALAR];if(o.tag!==a.tag){let c=e.tagString(o.tag),l=e.tagString(a.tag),d=`Value may be parsed as either ${c} or ${l}`;i(s,"TAG_RESOLVE_FAILED",d,!0)}}return o}Gf.composeScalar=uv});var Xf=O(Qf=>{"use strict";function pv(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}Qf.emptyScalarPosition=pv});var td=O(ka=>{"use strict";var mv=Ar(),hv=M(),gv=Kf(),Zf=zf(),yv=Ht(),bv=Xf(),wv={composeNode:ed,composeEmptyNode:Sa};function ed(r,e,t,n){let s=r.atKey,{spaceBefore:i,comment:o,anchor:a,tag:c}=t,l,d=!0;switch(e.type){case"alias":l=vv(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=Zf.composeScalar(r,e,c,n),a&&(l.anchor=a.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":l=gv.composeCollection(wv,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=Sa(r,e.offset,void 0,null,t,n),d=!1}}return a&&l.anchor===""&&n(a,"BAD_ALIAS","Anchor cannot be an empty string"),s&&r.options.stringKeys&&(!hv.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&&d&&(l.srcToken=e),l}function Sa(r,e,t,n,{spaceBefore:s,comment:i,anchor:o,tag:a,end:c},l){let d={type:"scalar",offset:bv.emptyScalarPosition(e,t,n),indent:-1,source:""},u=Zf.composeScalar(r,d,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 vv({options:r},{offset:e,source:t,end:n},s){let i=new mv.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=yv.resolveEnd(n,o,r.strict,s);return i.range=[e,o,a.offset],a.comment&&(i.comment=a.comment),i}ka.composeEmptyNode=Sa;ka.composeNode=ed});var sd=O(nd=>{"use strict";var Sv=Ur(),rd=td(),kv=Ht(),xv=Hr();function Ev(r,e,{offset:t,start:n,value:s,end:i},o){let a=Object.assign({_directives:e},r),c=new Sv.Document(void 0,a),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},d=xv.resolveProps(n,{indicator:"doc-start",next:s??i?.[0],offset:t,onError:o,parentIndent:0,startOnNewline:!0});d.found&&(c.directives.docStart=!0,s&&(s.type==="block-map"||s.type==="block-seq")&&!d.hasNewline&&o(d.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=s?rd.composeNode(l,s,d,o):rd.composeEmptyNode(l,d.end,n,null,d,o);let u=c.contents.range[2],f=kv.resolveEnd(i,u,!1,o);return f.comment&&(c.comment=f.comment),c.range=[t,u,f.offset],c}nd.composeDoc=Ev});var Ea=O(ad=>{"use strict";var Av=_n("process"),Tv=co(),Pv=Ur(),Vr=Wr(),id=M(),Ov=sd(),Rv=Ht();function Yr(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 od(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?`
|
|
111
111
|
|
|
112
112
|
`:`
|
|
113
|
-
`)+(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
|
|
114
|
-
${n}`:n;else if(s||e.directives.docStart||!i)e.commentBefore=n;else if(
|
|
113
|
+
`)+(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 xa=class{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(t,n,s,i)=>{let o=Yr(t);i?this.warnings.push(new Vr.YAMLWarning(o,n,s)):this.errors.push(new Vr.YAMLParseError(o,n,s))},this.directives=new Tv.Directives({version:e.version||"1.2"}),this.options=e}decorate(e,t){let{comment:n,afterEmptyLine:s}=od(this.prelude);if(n){let i=e.contents;if(t)e.comment=e.comment?`${e.comment}
|
|
114
|
+
${n}`:n;else if(s||e.directives.docStart||!i)e.commentBefore=n;else if(id.isCollection(i)&&!i.flow&&i.items.length>0){let o=i.items[0];id.isPair(o)&&(o=o.key);let a=o.commentBefore;o.commentBefore=a?`${n}
|
|
115
115
|
${a}`:n}else{let o=i.commentBefore;i.commentBefore=o?`${n}
|
|
116
|
-
${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:
|
|
117
|
-
${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.push(new Vr.YAMLParseError(Yr(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
|
|
116
|
+
${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:od(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(Av.env.LOG_STREAM&&console.dir(e,{depth:null}),e.type){case"directive":this.directives.add(e.source,(t,n,s)=>{let i=Yr(e);i[0]+=t,this.onError(i,"BAD_DIRECTIVE",n,s)}),this.prelude.push(e.source),this.atDirectives=!0;break;case"document":{let t=Ov.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 Vr.YAMLParseError(Yr(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 Vr.YAMLParseError(Yr(e),"UNEXPECTED_TOKEN",n));break}this.doc.directives.docEnd=!0;let t=Rv.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}
|
|
117
|
+
${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.push(new Vr.YAMLParseError(Yr(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 Pv.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}}};ad.Composer=xa});var ud=O(xs=>{"use strict";var _v=ba(),Cv=va(),Nv=Wr(),cd=_r();function Iv(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 Nv.YAMLParseError([a,a+1],i,o)};switch(r.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return Cv.resolveFlowScalar(r,e,n);case"block-scalar":return _v.resolveBlockScalar({options:{strict:e}},r,n)}}return null}function Lv(r,e){let{implicitKey:t=!1,indent:n,inFlow:s=!1,offset:i=-1,type:o="PLAIN"}=e,a=cd.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:`
|
|
118
118
|
`}];switch(a[0]){case"|":case">":{let l=a.indexOf(`
|
|
119
119
|
`),d=a.substring(0,l),u=a.substring(l+1)+`
|
|
120
|
-
`,f=[{type:"block-scalar-header",offset:i,indent:n,source:d}];return
|
|
121
|
-
`}),{type:"block-scalar",offset:i,indent:n,props:f,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
|
|
120
|
+
`,f=[{type:"block-scalar-header",offset:i,indent:n,source:d}];return ld(f,c)||f.push({type:"newline",offset:-1,indent:n,source:`
|
|
121
|
+
`}),{type:"block-scalar",offset:i,indent:n,props:f,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 Mv(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=cd.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">":$v(r,c);break;case'"':Aa(r,c,"double-quoted-scalar");break;case"'":Aa(r,c,"single-quoted-scalar");break;default:Aa(r,c,"scalar")}}function $v(r,e){let t=e.indexOf(`
|
|
122
122
|
`),n=e.substring(0,t),s=e.substring(t+1)+`
|
|
123
|
-
`;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}];
|
|
124
|
-
`});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
|
|
125
|
-
`};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})}}}
|
|
123
|
+
`;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}];ld(a,"end"in r?r.end:void 0)||a.push({type:"newline",offset:-1,indent:o,source:`
|
|
124
|
+
`});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 ld(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 Aa(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:`
|
|
125
|
+
`};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})}}}xs.createScalarToken=Lv;xs.resolveAsScalar=Iv;xs.setScalarValue=Mv});var dd=O(fd=>{"use strict";var Dv=r=>"type"in r?As(r):Es(r);function As(r){switch(r.type){case"block-scalar":{let e="";for(let t of r.props)e+=As(t);return e+r.source}case"block-map":case"block-seq":{let e="";for(let t of r.items)e+=Es(t);return e}case"flow-collection":{let e=r.start.source;for(let t of r.items)e+=Es(t);for(let t of r.end)e+=t.source;return e}case"document":{let e=Es(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 Es({start:r,key:e,sep:t,value:n}){let s="";for(let i of r)s+=i.source;if(e&&(s+=As(e)),t)for(let i of t)s+=i.source;return n&&(s+=As(n)),s}fd.stringify=Dv});var gd=O(hd=>{"use strict";var Ta=Symbol("break visit"),Bv=Symbol("skip children"),pd=Symbol("remove item");function ft(r,e){"type"in r&&r.type==="document"&&(r={start:r.start,value:r.value}),md(Object.freeze([]),r,e)}ft.BREAK=Ta;ft.SKIP=Bv;ft.REMOVE=pd;ft.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};ft.parentCollection=(r,e)=>{let t=ft.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 md(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=md(Object.freeze(r.concat([[s,o]])),i.items[o],t);if(typeof a=="number")o=a-1;else{if(a===Ta)return Ta;a===pd&&(i.items.splice(o,1),o-=1)}}typeof n=="function"&&s==="key"&&(n=n(e,r))}}return typeof n=="function"?n(e,r):n}hd.visit=ft});var Ts=O(ne=>{"use strict";var Pa=ud(),jv=dd(),Fv=gd(),Oa="\uFEFF",Ra="",_a="",Ca="",qv=r=>!!r&&"items"in r,Uv=r=>!!r&&(r.type==="scalar"||r.type==="single-quoted-scalar"||r.type==="double-quoted-scalar"||r.type==="block-scalar");function Jv(r){switch(r){case Oa:return"<BOM>";case Ra:return"<DOC>";case _a:return"<FLOW_END>";case Ca:return"<SCALAR>";default:return JSON.stringify(r)}}function Kv(r){switch(r){case Oa:return"byte-order-mark";case Ra:return"doc-mode";case _a:return"flow-error-end";case Ca:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
|
|
126
126
|
`:case`\r
|
|
127
|
-
`: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}ne.createScalarToken=
|
|
128
|
-
`:case"\r":case" ":return!0;default:return!1}}var
|
|
129
|
-
\r `),
|
|
127
|
+
`: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}ne.createScalarToken=Pa.createScalarToken;ne.resolveAsScalar=Pa.resolveAsScalar;ne.setScalarValue=Pa.setScalarValue;ne.stringify=jv.stringify;ne.visit=Fv.visit;ne.BOM=Oa;ne.DOCUMENT=Ra;ne.FLOW_END=_a;ne.SCALAR=Ca;ne.isCollection=qv;ne.isScalar=Uv;ne.prettyToken=Jv;ne.tokenType=Kv});var La=O(bd=>{"use strict";var Gr=Ts();function fe(r){switch(r){case void 0:case" ":case`
|
|
128
|
+
`:case"\r":case" ":return!0;default:return!1}}var yd=new Set("0123456789ABCDEFabcdef"),Wv=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),Ps=new Set(",[]{}"),Hv=new Set(` ,[]{}
|
|
129
|
+
\r `),Na=r=>!r||Hv.has(r),Ia=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===`
|
|
130
130
|
`?!0:t==="\r"?this.buffer[e+1]===`
|
|
131
131
|
`:!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===`
|
|
132
132
|
`||!s&&!this.atEnd)return e+n+1}return t===`
|
|
133
|
-
`||n>=this.indentNext||!t&&!this.atEnd?e+n:-1}if(t==="-"||t==="."){let n=this.buffer.substr(e,3);if((n==="---"||n==="...")&&
|
|
134
|
-
`,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]===Gr.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 Gr.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==="...")&&
|
|
133
|
+
`||n>=this.indentNext||!t&&!this.atEnd?e+n:-1}if(t==="-"||t==="."){let n=this.buffer.substr(e,3);if((n==="---"||n==="...")&&fe(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(`
|
|
134
|
+
`,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]===Gr.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 Gr.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==="...")&&fe(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&&!fe(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===":")&&fe(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(Na),"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("..."))&&fe(s[3]))&&!(n===this.indentNext-1&&this.flowLevel===1&&(s[0]==="]"||s[0]==="}")))return this.flowLevel=0,yield Gr.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(Na),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let o=this.charAt(1);if(this.flowKey||fe(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(`
|
|
135
135
|
`,this.pos);if(s!==-1){for(;s!==-1;){let i=this.continueScalar(s+1);if(i===-1)break;s=n.indexOf(`
|
|
136
|
-
`,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=>
|
|
136
|
+
`,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=>fe(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`
|
|
137
137
|
`:e=i,t=0;break;case"\r":{let o=this.buffer[i+1];if(!o&&!this.atEnd)return this.setNext("block-scalar");if(o===`
|
|
138
138
|
`)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(`
|
|
139
139
|
`,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===`
|
|
140
140
|
`;)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===`
|
|
141
|
-
`&&i>=this.pos&&i+1+t>a)e=i;else break}while(!0);return yield Gr.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(
|
|
141
|
+
`&&i>=this.pos&&i+1+t>a)e=i;else break}while(!0);return yield Gr.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(fe(i)||e&&Ps.has(i))break;t=n}else if(fe(s)){let i=this.buffer[n+1];if(s==="\r"&&(i===`
|
|
142
142
|
`?(n+=1,s=`
|
|
143
|
-
`,i=this.buffer[n+1]):t=n),i==="#"||e&&
|
|
144
|
-
`){let o=this.continueScalar(n+1);if(o===-1)break;n=Math.max(n,o-2)}}else{if(e&&
|
|
143
|
+
`,i=this.buffer[n+1]):t=n),i==="#"||e&&Ps.has(i))break;if(s===`
|
|
144
|
+
`){let o=this.continueScalar(n+1);if(o===-1)break;n=Math.max(n,o-2)}}else{if(e&&Ps.has(s))break;t=n}return!s&&!this.atEnd?this.setNext("plain-scalar"):(yield Gr.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(Na))+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators());case"-":case"?":case":":{let e=this.flowLevel>0,t=this.charAt(1);if(fe(t)||e&&Ps.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(;!fe(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(Wv.has(t))t=this.buffer[++e];else if(t==="%"&&yd.has(this.buffer[e+1])&&yd.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===`
|
|
145
145
|
`?yield*this.pushCount(1):e==="\r"&&this.charAt(1)===`
|
|
146
|
-
`?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)}};
|
|
146
|
+
`?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)}};bd.Lexer=Ia});var $a=O(wd=>{"use strict";var Ma=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}}}};wd.LineCounter=Ma});var Ba=O(Ed=>{"use strict";var Vv=_n("process"),vd=Ts(),Yv=La();function Ve(r,e){for(let t=0;t<r.length;++t)if(r[t].type===e)return!0;return!1}function Sd(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 xd(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 Os(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 Vt(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 kd(r){if(r.start.type==="flow-seq-start")for(let e of r.items)e.sep&&!e.value&&!Ve(e.start,"explicit-key-ind")&&!Ve(e.sep,"map-value-ind")&&(e.key&&(e.value=e.key),delete e.key,xd(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 Da=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 Yv.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,Vv.env.LOG_TOKENS&&console.log("|",vd.prettyToken(e)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=e.length;return}let t=vd.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"&&kd(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&&Sd(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":{Sd(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=Os(this.peek(2)),n=Vt(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(`
|
|
147
147
|
`)+1;for(;t!==0;)this.onNewLine(this.offset+t),t=this.source.indexOf(`
|
|
148
|
-
`,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(Ve(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(
|
|
148
|
+
`,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(Ve(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(xd(t.key)&&!Ve(t.sep,"newline")){let o=Vt(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(Ve(t.start,"newline"))Object.assign(t,{key:null,sep:[this.sourceToken]});else{let o=Vt(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]}):Ve(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&&!Ve(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||Ve(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=Os(n),i=Vt(s);kd(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(`
|
|
149
149
|
`)+1;for(;t!==0;)this.onNewLine(this.offset+t),t=this.source.indexOf(`
|
|
150
|
-
`,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=
|
|
151
|
-
`),t=e.trim();if(
|
|
150
|
+
`,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=Os(e),n=Vt(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=Os(e),n=Vt(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())}}};Ed.Parser=Da});var Rd=O(Qr=>{"use strict";var Ad=Ea(),Gv=Ur(),zr=Wr(),zv=ko(),Qv=M(),Xv=$a(),Td=Ba();function Pd(r){let e=r.prettyErrors!==!1;return{lineCounter:r.lineCounter||e&&new Xv.LineCounter||null,prettyErrors:e}}function Zv(r,e={}){let{lineCounter:t,prettyErrors:n}=Pd(e),s=new Td.Parser(t?.addNewLine),i=new Ad.Composer(e),o=Array.from(i.compose(s.parse(r)));if(n&&t)for(let a of o)a.errors.forEach(zr.prettifyError(r,t)),a.warnings.forEach(zr.prettifyError(r,t));return o.length>0?o:Object.assign([],{empty:!0},i.streamInfo())}function Od(r,e={}){let{lineCounter:t,prettyErrors:n}=Pd(e),s=new Td.Parser(t?.addNewLine),i=new Ad.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 zr.YAMLParseError(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return n&&t&&(o.errors.forEach(zr.prettifyError(r,t)),o.warnings.forEach(zr.prettifyError(r,t))),o}function eS(r,e,t){let n;typeof e=="function"?n=e:t===void 0&&e&&typeof e=="object"&&(t=e);let s=Od(r,t);if(!s)return null;if(s.warnings.forEach(i=>zv.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 tS(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 Qv.isDocument(r)&&!n?r.toString(t):new Gv.Document(r,n,t).toString(t)}Qr.parse=eS;Qr.parseAllDocuments=Zv;Qr.parseDocument=Od;Qr.stringify=tS});var Cd=O($=>{"use strict";var rS=Ea(),nS=Ur(),sS=sa(),ja=Wr(),iS=Ar(),Ye=M(),oS=Je(),aS=J(),cS=We(),lS=He(),uS=Ts(),fS=La(),dS=$a(),pS=Ba(),Rs=Rd(),_d=Sr();$.Composer=rS.Composer;$.Document=nS.Document;$.Schema=sS.Schema;$.YAMLError=ja.YAMLError;$.YAMLParseError=ja.YAMLParseError;$.YAMLWarning=ja.YAMLWarning;$.Alias=iS.Alias;$.isAlias=Ye.isAlias;$.isCollection=Ye.isCollection;$.isDocument=Ye.isDocument;$.isMap=Ye.isMap;$.isNode=Ye.isNode;$.isPair=Ye.isPair;$.isScalar=Ye.isScalar;$.isSeq=Ye.isSeq;$.Pair=oS.Pair;$.Scalar=aS.Scalar;$.YAMLMap=cS.YAMLMap;$.YAMLSeq=lS.YAMLSeq;$.CST=uS;$.Lexer=fS.Lexer;$.LineCounter=dS.LineCounter;$.Parser=pS.Parser;$.parse=Rs.parse;$.parseAllDocuments=Rs.parseAllDocuments;$.parseDocument=Rs.parseDocument;$.stringify=Rs.stringify;$.visit=_d.visit;$.visitAsync=_d.visitAsync});function hS(r){try{return JSON.parse(r.trim()),!0}catch{return!1}}function gS(r){let e=r.trim();if(!e.startsWith("<"))return!1;let t=e.match(mS);return t?vr(e,t[1])!==null:!1}function yS(r){let e=r.trim();if(!e.match(/^(---|#|\w+:|-)/)||"[{<".includes(e[0]))return!1;try{let t=Nd.parse(e);return t!==null&&typeof t=="object"}catch{return!1}}function Id(r){return hS(r)||gS(r)||yS(r)}var Nd,mS,Fa=R(()=>{Ul();Nd=Ag(Cd(),1),mS=/<([a-zA-Z_][\w.-]*)/});function bS(r){if(!r?.trim())return[];let e=r.replace(/\r\n/g,`
|
|
151
|
+
`),t=e.trim();if(Id(t))return[{text:t,startLine:1,endLine:e.split(`
|
|
152
152
|
`).length}];let n=e.split(`
|
|
153
153
|
`),s=[],i=0,o=-1,a=0,c=()=>{if(o>=i){let l=n.slice(i,o+1).join(`
|
|
154
|
-
`).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
|
|
155
|
-
`)).map(e=>e.root)}function en(r,e){if(!r)return[];let{target:t,dependencies:n}=e,s=[],i=r.split(`
|
|
156
|
-
`);for(let o=0;o<i.length;o++){let a=i[o],c=o+1;for(let l of
|
|
154
|
+
`).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 Ld(r){return bS(r).map(e=>e.text)}var Md=R(()=>{Fa()});var Xr=R(()=>{Cn();Cl();Il();Ml();Fa();Md();Nn()});function Yt(r){return{..._l(r),server:r.files.get("server.ts")??""}}function _s(r){return!!r.server&&!r.code}var Zr=R(()=>{Xr();Xr()});function kS(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 $d(r){let e=[];for(let s of SS)for(let i of r.matchAll(s)){let o=kS(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(`
|
|
155
|
+
`).length-1}));return n}function Dd(r){return $d(r).map(e=>e.root)}function en(r,e){if(!r)return[];let{target:t,dependencies:n}=e,s=[],i=r.split(`
|
|
156
|
+
`);for(let o=0;o<i.length;o++){let a=i[o],c=o+1;for(let l of vS)l.targets.includes(t)&&l.pattern.test(a)&&s.push({type:l.type,severity:"error",message:AS(l.type,c),lineNumber:c,lineContent:a})}return t==="client"&&n&&s.push(...xS(i,n)),s}function xS(r,e){let t=new Set(Object.keys(e));return $d(r.join(`
|
|
157
|
+
`)).filter(({root:n})=>!t.has(n)).map(({root:n,lineIndex:s})=>({type:"UNDECLARED_IMPORT",severity:"error",message:ES(n,s+1),lineNumber:s+1,lineContent:r[s]}))}function ES(r,e){return`Import "${r}" is not declared in config.json dependencies! Found on line ${e}.
|
|
157
158
|
|
|
158
159
|
**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.
|
|
159
160
|
|
|
@@ -167,7 +168,7 @@ ${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.pus
|
|
|
167
168
|
}
|
|
168
169
|
\`\`\`
|
|
169
170
|
|
|
170
|
-
**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
|
|
171
|
+
**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 AS(r,e){return r==="URL_IMPORT"?`Direct URL imports are not supported! Found on line ${e}.
|
|
171
172
|
|
|
172
173
|
**CRITICAL**: Import packages by name only. Do NOT use CDN URLs:
|
|
173
174
|
|
|
@@ -321,40 +322,40 @@ import { something } from 'module-name'
|
|
|
321
322
|
const something = require('module-name') // NOT SUPPORTED!
|
|
322
323
|
\`\`\`
|
|
323
324
|
|
|
324
|
-
**Fix:** Replace all \`require()\` calls with ES6 \`import\` statements at the top of the file.`}var dt,pt,
|
|
325
|
+
**Fix:** Replace all \`require()\` calls with ES6 \`import\` statements at the top of the file.`}var dt,pt,vS,SS,Cs=R(()=>{dt=["client"],pt=["client","server"],vS=[{type:"DYNAMIC_IMPORT",pattern:/\bimport\s*\(\s*['"`]/,targets:dt},{type:"COMMONJS_REQUIRE",pattern:/\brequire\s*\(\s*['"`]/,targets:pt},{type:"JS_EXTENSION_IMPORT",pattern:/from\s+['"][^'"]*\/[^'"]*\.js['"]/,targets:dt},{type:"URL_IMPORT",pattern:/from\s+['"]https?:\/\//,targets:dt},{type:"VERSION_SPECIFIER_IMPORT",pattern:/from\s+['"][^'"]*@[\d^~]/,targets:dt},{type:"REDUNDANT_TB_DECLARATION",pattern:/declare\s+(const|var|let)\s+tb\b/,targets:pt},{type:"CONST_ENUM",pattern:/\bconst\s+enum\b/,targets:pt},{type:"NAMESPACE_DECLARATION",pattern:/\bnamespace\s+\w+/,targets:pt},{type:"COMMONJS_EXPORT_EQUALS",pattern:/\bexport\s*=/,targets:pt},{type:"COMMONJS_IMPORT_EQUALS",pattern:/\bimport\s+\w+\s*=/,targets:pt},{type:"MODULE_DECLARATION",pattern:/\bmodule\s+\w+\s*\{/,targets:pt},{type:"CSS_FILE_IMPORT",pattern:/(?:from|import)\s+['"][^'"]*\.css['"]/,targets:dt},{type:"NAVIGATION",pattern:/window\.(location\.(reload|assign|replace)\s*\(|open\s*\()/,targets:dt},{type:"NAVIGATION",pattern:/window\.location(\.href)?\s*=[^=]/,targets:dt}],SS=[/\bimport\s+(?:[^'";]*?from\s*)?['"]([^'"]+)['"]/g,/\bexport\s+[^'";]*?from\s*['"]([^'"]+)['"]/g]});var sp=R(()=>{});var me,he,Zt=R(()=>{me=class extends Error{constructor(e,t="unknown",n=!1){super(e),this.code=t,this.retryable=n}},he=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=`
|
|
325
326
|
|
|
326
|
-
`){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
|
|
327
|
-
`)),!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
|
|
327
|
+
`){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 me(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 me(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 Hs,Ya=R(()=>{Zt();Hs=class extends he{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(`
|
|
328
|
+
`)),!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 me(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(`
|
|
328
329
|
|
|
329
|
-
`)}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 er,
|
|
330
|
+
`)}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 er,Vs=R(()=>{Zt();er=class extends he{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 Ys,Ga=R(()=>{Vs();Ys=class extends er{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 Gs,za=R(()=>{Zt();Gs=class extends he{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(`
|
|
330
331
|
|
|
331
|
-
`);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
|
|
332
|
+
`);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 zs,Qa=R(()=>{Zt();zs=class extends he{constructor(){super(...arguments),this.providerName="Gemini",this.defaultBaseUrl="https://generativelanguage.googleapis.com",this.path="/v1beta/models"}getPath(e,t){return`/v1beta/models/${e}:${t?"streamGenerateContent":"generateContent"}${t?"?alt=sse":""}`}buildHeaders(e){return{"Content-Type":"application/json","x-goog-api-key":e}}buildPayload(e,t,n,s){let{system:i,conversationMessages:o}=this.extractSystemMessages(e,`
|
|
332
333
|
`),c={contents:o.map(d=>({role:d.role==="assistant"?"model":"user",parts:[{text:d.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 u={0:0,1:1024,2:8192,3:-1}[l];c.generationConfig={thinkingConfig:u===0?{thinkingBudget:0}:{includeThoughts:!0,thinkingBudget: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(`
|
|
333
|
-
`)[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}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
|
|
334
|
+
`)[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}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 me(`Prompt blocked: ${t}`)}}}});var Qs,Xa=R(()=>{Vs();Qs=class extends er{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 yt(r){let e=GS.get(r);if(!e)throw new Error(`Unsupported protocol: ${r}`);return e}function zS(r,e){return r.replace(/\/+$/,"")+(e.startsWith("/")?e:`/${e}`)}async function Za(r,e){let t=yt(r.protocol),n=t.getPath(r.model,e.stream),s=zS(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 QS(r){return/prompt is too long|context[_ ](length|window)|maximum context|token count exceeds|too many tokens/i.test(r)}async function ln(r,e){let t=yt(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||QS(s))&&(o="context_exceeded"),{code:o,message:s,retryable:i===429||i>=500}}var ip,GS,ec=R(()=>{Ya();Ga();za();Qa();Xa();ip=new Qs,GS=new Map([["openai",new Hs],["openrouter",new Ys],["anthropic",new Gs],["gemini",new zs],["ollama",ip],["openai-compat",ip]])});function op(r){let e=r.indexOf(`\r
|
|
334
335
|
\r
|
|
335
336
|
`),t=r.indexOf(`
|
|
336
337
|
|
|
337
|
-
`);return e!==-1&&(t===-1||e<t)?{pos:e,len:4}:t!==-1?{pos:t,len:2}:{pos:-1,len:0}}function
|
|
338
|
-
`).trim();if(!n)return null;if(n==="[DONE]")return"done";try{return JSON.parse(n)}catch{return null}}async function*
|
|
339
|
-
`)}var nr,ek,tk,
|
|
340
|
-
|
|
341
|
-
`)
|
|
342
|
-
|
|
343
|
-
`).
|
|
344
|
-
`):r==null?"":Se(JSON.stringify(r))}function cx(r){let e=r.trim();return!!e&&Qp.some(t=>t.test(e))}function lx(r){let e=r.trim();return e?Qp.some(t=>{let n=t.exec(e);return!!n&&n.index===0}):!0}function fx(r){return r.replace(ux,"")}function dx(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 rt(r){let e=fx(r).trim();return e?dx(e)??(cx(e)?"":e):""}function Rc(r){return r?.type==="text"&&typeof r.text=="string"?rt(r.text):""}function Cc(r,e){if(typeof r=="string")return $e(r);if(!r||typeof r!="object")return $e(e);let t=r;if(t.type==="text"&&typeof t.file?.numLines=="number")return ge(t.file.numLines,"line");if(t.type==="image"){let n=Gp(t.file?.originalSize);return n?`image (${n})`:"image"}if(t.type==="pdf"){let n=Gp(t.file?.originalSize);return n?`PDF (${n})`:"PDF"}if(t.type==="parts"&&typeof t.file?.count=="number")return ge(t.file.count,"page");if(t.type==="file_unchanged")return"unchanged since last read";if(t.type==="create"&&typeof t.content=="string")return`created, ${ge(t.content.split(`
|
|
345
|
-
`).length,"line")}`;if(t.mode==="content")return ge(t.numLines??0,"line");if(t.mode==="count")return`${ge(t.numMatches??0,"match","matches")} (${ge(t.numFiles??0,"file")})`;if(t.mode==="files_with_matches")return ge(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":$e(t.stdout||t.stderr||"")||"no output":typeof t.code=="number"&&typeof t.codeText=="string"?`${t.code} ${t.codeText}`:typeof t.searchCount=="number"?ge(t.searchCount,"search","searches"):Array.isArray(t.matches)&&typeof t.total_deferred_tools=="number"?ge(t.matches.length,"tool"):Array.isArray(t.newTodos)?ge(t.newTodos.length,"todo"):typeof t.numFiles=="number"?ge(t.numFiles,"file"):$e(e)}function yn(r){return!!r.isSidechain||!!r.isMeta}function px(r){let e;try{e=Zk(r,"r")}catch{return""}try{let n=65536;try{n=rx(r).size}catch{}let s=(l,d)=>{if(d<=0)return"";let u=Buffer.alloc(d),f=ex(e,u,0,d,l);return u.subarray(0,f).toString("utf8")},i=(l,d,u)=>{let f="";for(let p of l.split(`
|
|
338
|
+
`);return e!==-1&&(t===-1||e<t)?{pos:e,len:4}:t!==-1?{pos:t,len:2}:{pos:-1,len:0}}function tc(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(`
|
|
339
|
+
`).trim();if(!n)return null;if(n==="[DONE]")return"done";try{return JSON.parse(n)}catch{return null}}async function*ap(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=tc(s);u!==null&&u!=="done"&&(yield u)}return}t?.(),s+=n.decode(c,{stream:!0});let{pos:l,len:d}=op(s);for(;l!==-1;){let u=s.slice(0,l);s=s.slice(l+d);let f=tc(u);if(f==="done")return;f!==null&&(yield f),{pos:l,len:d}=op(s)}}}finally{i&&e?.removeEventListener("abort",i);try{await r.cancel()}catch{}}}async function bt(r,e){if(!r.body)throw new Error("Response body is missing");let t="";for await(let n of tr(r,e))n.kind==="text"&&(t+=n.text);return t}async function*tr(r,e){let t=e??(r.headers.get("X-Provider-Protocol")||"openai"),n=yt(t);if(!r.body)return;let s=r.body.getReader();for await(let i of ap(s)){let o=n.parseStreamChunk(i);o?.reasoning&&(yield{kind:"reasoning",text:o.reasoning}),o?.text&&(yield{kind:"text",text:o.text})}}var cp=R(()=>{ec()});var rr=R(()=>{sp();Zt();ec();cp();Vs();za();Qa();Ya();Ga();Xa()});function sr(r){return(r.includes("://")?r:`http://${r}`).replace(/\/+$/,"")}function rc(){return fn}async function Ne(){let[r,e]=await Promise.all([up(),rk()]);return[...nk(e),...r]}async function lp(){let r;try{r=await fetch(XS,{signal:AbortSignal.timeout(ek)})}catch(e){return fn=`catalog fetch failed: ${e?.message??e}`,null}if(!r.ok)return fn=`catalog fetch failed: HTTP ${r.status}`,null;try{return await r.json()}catch(e){return fn=`catalog returned an unreadable body: ${e?.message??e}`,null}}async function rk(){if(un&&Date.now()-un.fetchedAt<=ZS)return un.models;let r=await lp()??await lp();return r?(un={models:r,fetchedAt:Date.now()},fn=null,r):un?.models??[]}async function up(){if(Xs&&Date.now()-Xs.fetchedAt<=tk)return Xs.models;let r=sr(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 Xs={models:e,fetchedAt:Date.now()},e}function nk(r){let e=new Set(Object.entries(nr).filter(([,t])=>!!process.env[t]).map(([t])=>t));return r.filter(t=>e.has(t.provider))}function nc(){return Object.values(nr).some(r=>!!process.env[r])}async function Zs(){return nc()||process.env.TB_AI_BASE_URL?!0:(await up()).length>0}function fp(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(`
|
|
340
|
+
`)}var nr,XS,ZS,ek,tk,un,Xs,fn,wt=R(()=>{nr={anthropic:"ANTHROPIC_API_KEY",openai:"OPENAI_API_KEY",gemini:"GOOGLE_API_KEY",openrouter:"OPENROUTER_API_KEY"};XS="https://api.typebulb.com/api/models",ZS=1440*60*1e3,ek=5e3,tk=60*1e3,un=null,Xs=null,fn=null});function vt(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=yt(t)}catch{return`Unknown provider '${t}'.`}if(t==="ollama")return{apiKey:"",baseUrl:`${sr(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=nr[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 St(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 Za(r,{messages:t,stream:!0,effort:n!=null&&n>=0&&n<=3?n:void 0,webSearch:e.webSearch??!0,signal:e.signal})}var ei=R(()=>{rr();wt()});import{realpathSync as ak}from"fs";import{join as oc,resolve as ck}from"path";import{homedir as lk}from"os";function ti(){let r=process.env.TYPEBULB_SERVERS_DIR;return r?oc(r,".."):oc(lk(),".typebulb")}function Le(){return process.env.TYPEBULB_SERVERS_DIR||oc(ti(),"servers")}function Q(r){let e=ck(r),t=e;try{t=ak.native(e)}catch{}return(process.platform==="win32"?t.toLowerCase():t).replace(/\\/g,"/")}function hp(r,e){let t=Q(r),n=Q(e);return t.startsWith(n.endsWith("/")?n:n+"/")?!t.includes("/node_modules/"):!1}var ri=R(()=>{});import{readFileSync as uk,writeFileSync as fk,mkdirSync as dk}from"fs";import{join as pk}from"path";function gp(){return pk(ti(),"trust.json")}function ac(){try{let r=JSON.parse(uk(gp(),"utf8"));return new Set(Array.isArray(r)?r:[])}catch{return new Set}}function mk(r){dk(ti(),{recursive:!0}),fk(gp(),JSON.stringify([...r]))}function kt(r){return ac().has(Q(r))}function ir(r,e){let t=ac(),n=Q(r);(e?t.has(n):!t.has(n))||(e?t.add(n):t.delete(n),mk(t))}function cc(){return[...ac()]}var pn=R(()=>{ri()});function Se(r){return r.length>5e4?r.slice(0,5e4)+`
|
|
341
|
+
\u2026[${r.length-5e4} more characters truncated]`:r}function Me(r){let e=r.replace(hk,"").split(`
|
|
342
|
+
`).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 hk,ni,si=R(()=>{hk=/\u001b\[[0-9;]*m/g;ni=(r,e)=>``});import{existsSync as gk,readdirSync as yk,statSync as bk}from"fs";import{join as wk}from"path";function ii(r){if(!gk(r))return[];let e;try{e=yk(r)}catch{return[]}let t=[];for(let n of e){if(!n.endsWith(".jsonl"))continue;let s=wk(r,n);try{let i=bk(s);i.isFile()&&t.push({sessionId:n.slice(0,-6),file:s,mtime:i.mtimeMs})}catch{}}return t}var lc=R(()=>{});var or,uc=R(()=>{or=class{ensureHarnessSupport(){}}});import{openSync as vk,readSync as Sk,closeSync as kk,statSync as xk,readdirSync as Ek,readFileSync as Ak,existsSync as Tk}from"fs";import{join as hn}from"path";import{homedir as pc}from"os";function Pk(r){return r.replace(/[^a-zA-Z0-9]/g,"-")}function oi(r){let e=r?.type==="image"?r.source:void 0;return e?.type==="base64"&&e.data?ni(e.data,e.media_type):""}function fc(r){return typeof r=="string"?Se(r):Array.isArray(r)?r.map(e=>{if(typeof e=="string")return Se(e);let t=e;return typeof t?.text=="string"?Se(t.text):t?.content!=null?fc(t.content):oi(t)}).join(`
|
|
343
|
+
`):r==null?"":Se(JSON.stringify(r))}function Rk(r){let e=r.trim();return!!e&&vp.some(t=>t.test(e))}function _k(r){let e=r.trim();return e?vp.some(t=>{let n=t.exec(e);return!!n&&n.index===0}):!0}function Nk(r){return r.replace(Ck,"")}function Ik(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 et(r){let e=Nk(r).trim();return e?Ik(e)??(Rk(e)?"":e):""}function dc(r){return r?.type==="text"&&typeof r.text=="string"?et(r.text):""}function mc(r,e){if(typeof r=="string")return Me(r);if(!r||typeof r!="object")return Me(e);let t=r;if(t.type==="text"&&typeof t.file?.numLines=="number")return ye(t.file.numLines,"line");if(t.type==="image"){let n=bp(t.file?.originalSize);return n?`image (${n})`:"image"}if(t.type==="pdf"){let n=bp(t.file?.originalSize);return n?`PDF (${n})`:"PDF"}if(t.type==="parts"&&typeof t.file?.count=="number")return ye(t.file.count,"page");if(t.type==="file_unchanged")return"unchanged since last read";if(t.type==="create"&&typeof t.content=="string")return`created, ${ye(t.content.split(`
|
|
344
|
+
`).length,"line")}`;if(t.mode==="content")return ye(t.numLines??0,"line");if(t.mode==="count")return`${ye(t.numMatches??0,"match","matches")} (${ye(t.numFiles??0,"file")})`;if(t.mode==="files_with_matches")return ye(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":Me(t.stdout||t.stderr||"")||"no output":typeof t.code=="number"&&typeof t.codeText=="string"?`${t.code} ${t.codeText}`:typeof t.searchCount=="number"?ye(t.searchCount,"search","searches"):Array.isArray(t.matches)&&typeof t.total_deferred_tools=="number"?ye(t.matches.length,"tool"):Array.isArray(t.newTodos)?ye(t.newTodos.length,"todo"):typeof t.numFiles=="number"?ye(t.numFiles,"file"):Me(e)}function mn(r){return!!r.isSidechain||!!r.isMeta}function Lk(r){let e;try{e=vk(r,"r")}catch{return""}try{let n=65536;try{n=xk(r).size}catch{}let s=(l,d)=>{if(d<=0)return"";let u=Buffer.alloc(d),f=Sk(e,u,0,d,l);return u.subarray(0,f).toString("utf8")},i=(l,d,u)=>{let f="";for(let p of l.split(`
|
|
346
345
|
`)){if(!p.includes(`"${d}"`))continue;let y;try{y=JSON.parse(p)}catch{continue}let m=y?.[u];y?.type===d&&typeof m=="string"&&m&&(f=m)}return f},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(`
|
|
347
|
-
`)){if(!l.trim())continue;let d;try{d=JSON.parse(l)}catch{continue}if(!d||
|
|
348
|
-
`),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??""),f=!isNaN(u)&&u>=t;n.push({type:"assistant",text:o,thinking:a,tools:c,live:f})}let l=e.message?.usage??e.usage,d=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:d,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()&&
|
|
346
|
+
`)){if(!l.trim())continue;let d;try{d=JSON.parse(l)}catch{continue}if(!d||mn(d)||d.type!=="user")continue;let u=d.message?.content,f="";typeof u=="string"?f=et(u):Array.isArray(u)&&(f=u.map(dc).filter(Boolean).join(" "));let p=f.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{kk(e)}}function Mk(r){let e;try{e=Ek(wp)}catch{return!1}for(let t of e)if(t.endsWith(".json"))try{let n=JSON.parse(Ak(hn(wp,t),"utf8"));if(n?.sessionId!==r)continue;return process.kill(n.pid,0),!0}catch{}return!1}var Ok,yp,vp,Ck,ye,bp,wp,ar,ai=R(()=>{si();lc();uc();Ok=hn(pc(),".claude","projects"),yp=r=>hn(Ok,Pk(r));vp=[/\[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];Ck=/<ide_[a-z_]+>[\s\S]*?<\/ide_[a-z_]+>/gi;ye=(r,e,t=e+"s")=>`${r} ${r===1?e:t}`,bp=r=>typeof r!="number"?"":r<1024?`${r}B`:r<1048576?`${Math.round(r/1024)}KB`:`${(r/1048576).toFixed(1)}MB`;wp=hn(pc(),".claude","sessions");ar=class extends or{displayName="Claude Mirror";detectsSelf(){return process.env.CLAUDECODE==="1"}detectsInstalled(){return Tk(hn(pc(),".claude"))}sessionsDir(e){return yp(e)}listSessionFiles(e){return ii(yp(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(mn(e))return{events:[]};let n=[];if(e.type==="user"){let s=e.message?.content;if(typeof s=="string"){let i=et(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=fc(i.content);n.push({type:"tool_result",id:i.tool_use_id??"",content:o,isError:!!i.is_error,digest:mc(e.toolUseResult,o)})}else{let o=dc(i)||oi(i);o&&n.push({type:"user",text:o})}return{events:n}}if(e.type==="attachment"&&e.attachment?.type==="queued_command"){let s=et(fc(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=>!_k(u)).join(""),a=i.filter(u=>u.type==="thinking").map(u=>u.thinking??"").join(`
|
|
347
|
+
`),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??""),f=!isNaN(u)&&u>=t;n.push({type:"assistant",text:o,thinking:a,tools:c,live:f})}let l=e.message?.usage??e.usage,d=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:d,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()&&et(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 Mk(e)}readPreview(e){return Lk(e)}searchText(e){if(!e||mn(e)||e.type!=="user"&&e.type!=="assistant")return"";let t=e.message?.content,n="";if(typeof t=="string")n=et(t);else if(Array.isArray(t)){let s=t;n=e.type==="user"?s.map(dc).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 Sp}from"child_process";import{readdir as $k,readFile as xp,writeFile as Ep,unlink as hc,mkdir as Dk}from"fs/promises";import{mkdirSync as Ap,writeFileSync as ci,appendFileSync as Bk,readFileSync as gc}from"fs";import*as ce from"path";import{fileURLToPath as jk}from"url";function yc(r){return ce.join(Le(),`${r}.json`)}function yn(r){return ce.join(Le(),`${r}.log`)}function bc(r){return ce.join(Le(),`${r}.wait.json`)}function Tp(r){try{let e=JSON.parse(gc(bc(r),"utf8"));return e.cursors&&typeof e.cursors=="object"?e.cursors:{}}catch{return{}}}function wc(r,e=""){let t=Tp(r)[e];return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}function li(r,e,t=""){try{Ap(Le(),{recursive:!0});let n=Tp(r);n[t]=e,ci(bc(r),JSON.stringify({cursors:n}))}catch{}}function ui(r){let e=yn(r);try{Ap(Le(),{recursive:!0}),ci(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(Bk(e,c),s+=c.length,s>2*kp){let l=gc(e),d=l.subarray(Math.max(0,l.length-kp));ci(e,d),s=d.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 Pp(r){try{ci(yn(r),"")}catch{}}function ke(r,e=0){try{let t=gc(yn(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 vc(r){return`\u2500\u2500 run ${r} \u2500\u2500 ${new Date().toTimeString().slice(0,8)}`}function qk(r){let e=Fk.exec(r);return e?Number(e[1]):void 0}function Op(r,e){let t=r.split(`
|
|
348
|
+
`),n=[];if(t.forEach((o,a)=>{let c=qk(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(`
|
|
349
|
+
`)}function Sc(r){try{return process.kill(r,0),!0}catch(e){return e.code==="EPERM"}}async function Rp(r){await Dk(Le(),{recursive:!0}),await Ep(yc(r.pid),JSON.stringify(r))}async function _p(r,e){let t=yc(r);try{let n=JSON.parse(await xp(t,"utf8"));if(n.denied===e)return;n.denied=e,await Ep(t,JSON.stringify(n))}catch{}}async function gn(r){await hc(yc(r)).catch(()=>{}),await hc(yn(r)).catch(()=>{}),await hc(bc(r)).catch(()=>{})}async function K(r){let e;try{e=await $k(Le())}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 xp(ce.join(Le(),s),"utf8"))}catch{await gn(i);return}o&&typeof o.pid=="number"&&Sc(o.pid)?t.push(o):await gn(i)})),(r?t.filter(s=>s.agent==null&&hp(s.file,r)):t).sort((s,i)=>s.startedAt-i.startedAt)}async function kc(r,e){let t=Q(r);return(await K()).find(n=>n.cwd!=null&&Q(n.cwd)===t&&(e?n.agent===e:n.agent!=null))}async function xt(r){try{process.kill(r,"SIGTERM")}catch{}await gn(r)}function cr(r,e){let t=Q(e);return r.filter(n=>n.agent==null&&n.pid!==process.pid&&Q(n.file)===t)}async function xc(r){let e=cr(await K(),r);for(let t of e)await xt(t.pid);return e}function Jk(r,e,t){(process.platform==="win32"?Sp("cmd",["/c","start","","/b",r,...e],{cwd:t,stdio:"ignore",windowsHide:!0}):Sp(r,e,{cwd:t,detached:!0,stdio:"ignore"})).unref()}function Cp(){return ce.join(ce.dirname(jk(import.meta.url)),"index.js")}function Kk(r,e={}){return{command:process.execPath,args:[Cp(),...e.trust?["--trust"]:[],r,...e.open===!1?["--no-open"]:[]]}}function Wk(r){return{command:process.execPath,args:[Cp(),`agent:${r}`,"--no-open"]}}async function Np(r,e,t,n){let s=await r();if(s)return s;Jk(e.command,e.args,t);let i=Date.now()+2e4;for(;Date.now()<i;){await Uk(150);let o=await r();if(o)return o}throw new Error(`Launched ${n} but it did not register within 20s.`)}async function fi(r,e={}){let t=e.cwd??process.cwd(),n=ce.resolve(t,r);return await xc(n),Np(async()=>cr(await K(),n)[0],Kk(r,e),t,ce.basename(r))}async function Ip(r,e=process.cwd()){return Np(()=>kc(e,r),Wk(r),e,`the ${r} mirror`)}var kp,Fk,Uk,xe=R(()=>{ri();kp=1e6;Fk=/^── run (\d+) ── /;Uk=r=>new Promise(e=>setTimeout(e,r))});function di(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 Ec(r){return(di(r)??"bulb").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"bulb"}var Ac=R(()=>{});import{readdirSync as Hk,readFileSync as Vk,statSync as Yk}from"fs";import{join as Lp,basename as Gk}from"path";function Mp(r,e,t){if(e>8)return t;let n;try{n=Hk(r,{withFileTypes:!0})}catch{return t}for(let s of n)if(s.isDirectory()){if(s.name.startsWith(".")||s.name==="node_modules")continue;Mp(Lp(r,s.name),e+1,t)}else s.isFile()&&s.name.endsWith(".bulb.md")&&t.push(Lp(r,s.name));return t}function pi(r){return Mp(r,0,[]).map(e=>{let t=0;try{t=Yk(e).mtimeMs}catch{}let n,s=!1;try{let i=Vk(e,"utf8");n=di(i.slice(0,1024));let o=Pe(i);s=!!o&&_s(Yt(o))}catch{}return{path:e,name:n??Gk(e).replace(/\.bulb\.md$/,""),mtime:t,serverOnly:s}})}var $p=R(()=>{Xr();Zr();Ac()});function lr(r){if(r.server.trim())return"server-side code (server.ts)";let e=r.code;if(/\btb\s*\.\s*fs\b/.test(e)||e.includes("/__fs"))return"the filesystem";if(/\btb\s*\.\s*ai\b/.test(e)||e.includes("/__ai"))return"AI (your API keys)";if(/\btb\s*\.\s*server\s*\.\s*(?!log\b)\w/.test(e)||e.includes("/__api"))return"server-side code (server.ts)"}var mi=R(()=>{});import{readFile as zk}from"fs/promises";async function Tc(r){try{let e=Pe(await zk(r,"utf-8"));return e?lr(Yt(e)):void 0}catch{return}}var Dp=R(()=>{Zr();mi()});function Pc(r){let e=Pe(r);if(!e)return r;let t=e.files.get("code.tsx");if(!t)return r;let n=Dd(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,d]of e.files){let u=El(l);u&&(c[u]=d)}return c.config=JSON.stringify(i,null,2),Nl(c)}var Bp=R(()=>{Xr();Cs()});import{spawn as jp}from"child_process";import{basename as Qk}from"path";function Xk(){return process.env.TYPEBULB_EDITOR||"code"}function ex(r,e,t){return t==null?[e]:Zk.test(Qk(r))?["-g",`${e}:${t}`]:[`+${t}`,e]}function tx(r,e){let t=Xk();return{command:t,args:ex(t,r,e)}}function Oc(r,e){let{command:t,args:n}=tx(r,e),s=process.platform==="win32"?jp("cmd.exe",["/d","/s","/c",t,...n],{detached:!0,stdio:"ignore",windowsHide:!0}):jp(t,n,{detached:!0,stdio:"ignore"});s.on("error",i=>console.error("[typebulb] editor launch failed:",i?.message??i)),s.unref()}var Zk,Fp=R(()=>{Zk=/^(code|code-insiders|codium|vscodium|cursor|windsurf)(\.cmd|\.exe)?$/i});import{readFileSync as rx,existsSync as nx}from"fs";import*as Et from"path";import{fileURLToPath as sx}from"url";function qp(){let r=Et.dirname(sx(import.meta.url));for(;!nx(Et.join(r,"package.json"));){let e=Et.dirname(r);if(e===r)break;r=e}return r}function At(){return Et.join(qp(),"README.md")}function ur(){return Et.join(qp(),"description.md")}function ix(r){let e=rx(ur(),"utf8").trim().replace(/\s+/g," ");return`---
|
|
349
350
|
name: typebulb
|
|
350
351
|
description: ${JSON.stringify(e)}
|
|
351
352
|
version: ${r}
|
|
352
|
-
---`}function
|
|
353
|
+
---`}function ox(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 Up(r,e){return`${ix(e)}
|
|
353
354
|
|
|
354
|
-
${
|
|
355
|
+
${ox(e)}
|
|
355
356
|
|
|
356
357
|
${r.trim()}
|
|
357
|
-
`}var
|
|
358
|
+
`}var hi=R(()=>{});var fr=R(()=>{xe();$p();Dp();Ac();Bp();Fp();pn();wt();wt();ei();hi()});import{copyFileSync as ax,existsSync as Jp,mkdirSync as Kp,rmSync as cx,writeFileSync as lx}from"fs";import{homedir as ux}from"os";import*as Ee from"path";import{fileURLToPath as fx}from"url";function yx(){return gx.replace('"__TB_DESCRIPTION_PATH__"',JSON.stringify(ur())).replace('"__TB_README_PATH__"',JSON.stringify(At()))}function Wp(){try{if(!Jp(gi()))return}catch{return}try{let r=dx();Kp(Ee.dirname(r),{recursive:!0}),lx(r,yx()),cx(px(),{force:!0})}catch{}try{let r=mx();if(!Jp(r))return;let e=hx();Kp(Ee.dirname(e),{recursive:!0}),ax(r,e)}catch{}}var gi,dx,px,mx,hx,gx,Hp=R(()=>{fr();gi=()=>Ee.join(ux(),".pi","agent"),dx=()=>Ee.join(gi(),"extensions","typebulb.ts"),px=()=>Ee.join(gi(),"extensions","typebulb-wait.ts"),mx=()=>Ee.join(Ee.dirname(fx(import.meta.url)),"agents","pi","matchu-patchu.ts"),hx=()=>Ee.join(gi(),"extensions","matchu-patchu.ts"),gx=String.raw`// Generated by typebulb — do not edit; overwritten on each run.
|
|
358
359
|
import { spawn } from "node:child_process";
|
|
359
360
|
import { existsSync } from "node:fs";
|
|
360
361
|
|
|
@@ -503,28 +504,29 @@ export default function (pi) {
|
|
|
503
504
|
try { pi.on("session_shutdown", () => { for (const c of pending) { try { c.kill(); } catch (e) {} } pending.clear(); }); } catch (e) {}
|
|
504
505
|
} catch (e) { logErr("load", e && e.message); }
|
|
505
506
|
}
|
|
506
|
-
`});function
|
|
507
|
-
`))>=0;){let o=n.slice(0,i);n=n.slice(i+1),o.endsWith("\r")&&(o=o.slice(0,-1)),o&&e(o)}})}var
|
|
508
|
-
`)}catch{}await Promise.race([this.#v,
|
|
509
|
-
`)}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"?
|
|
510
|
-
`)}catch(a){clearTimeout(o),this.#s.delete(n),i(new Error(
|
|
511
|
-
`)};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??
|
|
512
|
-
`),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)
|
|
507
|
+
`});function q(r){return r?.message??String(r)}var G,Tt=R(()=>{G=process.cwd()});import{spawn as Vp}from"child_process";import{StringDecoder as bx}from"string_decoder";function Tx(r,e){let t=new bx("utf8"),n="";r.on("data",s=>{n+=typeof s=="string"?s:t.write(s);let i;for(;(i=n.indexOf(`
|
|
508
|
+
`))>=0;){let o=n.slice(0,i);n=n.slice(i+1),o.endsWith("\r")&&(o=o.slice(0,-1)),o&&e(o)}})}var wx,vx,Yp,Sx,kx,xx,Ex,Ax,yi,bi,Gp,zp=R(()=>{Tt();wx=3e4,vx=5e3,Yp=2e3,Sx=2e3,kx=12e4,xx=8e3,Ex=15e3,Ax=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"]),yi=new Set;process.on("exit",()=>{for(let r of yi)try{r.kill()}catch{}});bi=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)=>Vp(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: ${q(o)}`,this.#b();return}this.#e=i,this.#f=t,yi.add(i),i.stdout&&Tx(i.stdout,o=>this.#T(o)),i.stderr&&i.stderr.on("data",o=>{this.#y=(this.#y+o.toString()).slice(-Sx)}),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"),yi.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(!Ax.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:q(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:q(o)}}return i.success&&!n&&(this.#c=Date.now()+vx),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"})+`
|
|
509
|
+
`)}catch{}await Promise.race([this.#v,Gp(Yp)])}try{e.stdin?.end()}catch{}if(await Promise.race([this.#v,Gp(Yp)]),e.exitCode===null&&!e.killed)if(process.platform==="win32"&&e.pid)try{Vp("taskkill",["/pid",String(e.pid),"/T","/F"],{stdio:"ignore"})}catch{}else try{e.kill("SIGKILL")}catch{}yi.delete(e),this.#r=[],this.#E("pi was shut down")}}#k(e){try{this.#e?.stdin?.write(JSON.stringify(e)+`
|
|
510
|
+
`)}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"?xx:Ex)})}#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)"))},wx);o.unref?.(),this.#s.set(n,{resolve:s,timer:o});try{t.stdin.write(JSON.stringify({id:n,...e})+`
|
|
511
|
+
`)}catch(a){clearTimeout(o),this.#s.delete(n),i(new Error(q(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:[];this.#l={text:s.filter(i=>i?.type==="text").map(i=>i.text??"").join(""),thinking:s.filter(i=>i?.type==="thinking").map(i=>i.thinking??"").join(`
|
|
512
|
+
`)};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??kx),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()}},Gp=r=>new Promise(e=>{setTimeout(e,r).unref?.()})});import{existsSync as Qp,readFileSync as Px,realpathSync as Ox}from"fs";import{join as Pt,dirname as tm,resolve as Rx}from"path";import{homedir as Xp}from"os";function Cx(r,e){let t=Pt(r,".pi");if(_x.some(s=>Qp(Pt(t,s))))return!0;let n=Pt(e,".agents","skills");for(let s=r;;){let i=Pt(s,".agents","skills");if(i!==n&&Qp(i))return!0;let o=tm(s);if(o===s)return!1;s=o}}function Nx(r,e){for(let t=e;;){if(r[t]===!0||r[t]===!1)return!0;let n=tm(t);if(n===t)return!1;t=n}}function rm(r,e){try{let t=e?.agentDir??Pt(Xp(),".pi","agent"),n=Zp(e?.home??process.env.HOME??Xp()),s=Zp(Rx(r));if(!Cx(s,n))return null;let i=em(Pt(t,"settings.json")).defaultProjectTrust;return i==="always"||i==="never"||Nx(em(Pt(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 _x,Zp,em,nm=R(()=>{_x=["settings.json","extensions","skills","prompts","themes","SYSTEM.md","APPEND_SYSTEM.md"],Zp=r=>{try{return Ox(r)}catch{return r}},em=r=>{try{return JSON.parse(Px(r,"utf8"))}catch{return{}}}});import{statSync as Ix,openSync as Lx,readSync as Mx,closeSync as $x,existsSync as Dx}from"fs";import{join as Rc}from"path";import{homedir as im}from"os";function jx(r){return`--${r.replace(/^[/\\]/,"").replace(/[/\\:]/g,"-")}--`}function sm(r){return r.type==="message"?Fx(r.message?.role):r.type==="custom_message"?r.display!==!1:!1}var Bx,Fx,dr,_c=R(()=>{si();lc();uc();Hp();zp();nm();Bx=Rc(im(),".pi","agent","sessions");Fx=r=>r==="user"||r==="assistant"||r==="toolResult"||r==="bashExecution";dr=class extends or{displayName="Pi Mirror";detectsSelf(){return process.env.PI_CODING_AGENT==="true"}detectsInstalled(){return Dx(Rc(im(),".pi","agent"))}ensureHarnessSupport(){Wp()}createDriver(e,t){let n=new bi(e,t),s=rm(e);return s&&n.notice(s,"warning"),n}sessionsDir(e){return Rc(Bx,jx(e))}listSessionFiles(e){return ii(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 sm(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:Me(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(`
|
|
513
|
+
`),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)sm(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=Lx(e,"r")}catch{return""}try{let s=65536;try{s=Ix(e).size}catch{}let i=(u,f)=>{let p=Buffer.alloc(f),y=Mx(t,p,0,f,u);return p.subarray(0,y).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(`
|
|
513
514
|
`))if(p.includes('"session_info"'))try{let y=JSON.parse(p);y?.type==="session_info"&&typeof y.name=="string"&&y.name&&(f=y.name)}catch{}return f},l="";for(let u of o.split(`
|
|
514
|
-
`))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{
|
|
515
|
-
`):""}}});var
|
|
516
|
-
|
|
517
|
-
${r.slice(0,
|
|
518
|
-
`))>=0;){let j=h.partial.slice(0
|
|
519
|
-
`).filter(Boolean).map(async v=>{try{return{f:v,m:(await
|
|
520
|
-
`)){if(!
|
|
521
|
-
`)){let
|
|
522
|
-
`)}function
|
|
515
|
+
`))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{$x(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"?Se(e):Array.isArray(e)?e.map(t=>typeof t?.text=="string"?Se(t.text):t?.type==="image"&&t.data?ni(t.data,t.mimeType):"").filter(Boolean).join(`
|
|
516
|
+
`):""}}});var wi,om=R(()=>{wi=class{#e=new Map;accept(e,t){return this.#e.get(e)===t?!1:(this.#e.set(e,t),!0)}}});function vi(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 Cc=R(()=>{});var Si,ki,am=R(()=>{Si=".typebulb/paste",ki={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 qx,mkdirSync as Ux,writeFileSync as Jx,readFileSync as Kx}from"fs";import{join as xi}from"path";function cm(){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 Yx(r){return r.trim().toLowerCase().replace(/\.[a-z0-9]{1,4}$/,"").replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60)}async function Gx(r){let e=AbortSignal.timeout(Wx);for(let[t,n]of Vx){let s=vt(t,n);if(typeof s!="string"){try{let i=await St(s,{messages:[{role:"user",content:`Reply with ONLY a short kebab-case filename (2-5 words, lowercase, no extension) describing this text:
|
|
517
|
+
|
|
518
|
+
${r.slice(0,Hx)}`}],effort:0,webSearch:!1,signal:e});if(!i.ok)continue;let o=Yx(await bt(i,s.protocol));if(o)return o}catch{}if(e.aborted)return}}}async function lm(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=xi(r,Si);try{Ux(t,{recursive:!0})}catch(a){return{ok:!1,error:q(a)}}let n,s,i;if(e.kind==="image"){if(n=`img-${cm()}`,s=Object.keys(ki).find(a=>ki[a]===e.mime)??"png",i=Buffer.from(e.data,"base64"),!i.length)return{ok:!1,error:"empty image data"}}else n=await Gx(e.data)??`paste-${cm()}`,s="md",i=e.data;let o=`${n}.${s}`;for(let a=2;qx(xi(t,o));a++)o=`${n}-${a}.${s}`;try{Jx(xi(t,o),i)}catch(a){return{ok:!1,error:q(a)}}return{ok:!0,path:`${Si}/${o}`}}function um(r,e){if(!/^[\w-]+(\.[\w-]+)*$/.test(e))return{ok:!1,error:"bad name"};let t=e.slice(e.lastIndexOf(".")+1).toLowerCase(),n=ki[t];if(!n)return{ok:!1,error:"not an image"};try{return{ok:!0,mime:n,base64:Kx(xi(r,Si,e)).toString("base64")}}catch{return{ok:!1,error:"not found"}}}var Wx,Hx,Vx,fm=R(()=>{rr();fr();Tt();am();Wx=4e3,Hx=4e3,Vx=[["openrouter","google/gemini-3.1-flash-lite-preview"],["gemini","gemini-3.1-flash-lite"]]});import{existsSync as dm,openSync as zx,readSync as Qx,closeSync as Xx,statSync as pr,readdirSync as pm,watchFile as Zx,unwatchFile as mm,mkdirSync as e0,writeFileSync as t0,readFileSync as Ei,unlinkSync as r0,rmSync as n0}from"fs";import{stat as s0}from"fs/promises";import{join as Ot}from"path";import{execFile as i0}from"child_process";function l0(r){if(!Number.isInteger(r))return!0;try{return process.kill(r,0),!0}catch(e){return e.code==="EPERM"}}function Ai(r){let e={cwd:G,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:",q(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&&k(h)}}let l=h=>Ot(h,a0),d=(h,S)=>Ot(l(h),`${S}.lock`);function u(h,S){try{let v=d(h,S);if(Date.now()-pr(v).mtimeMs>=hm)return!1;try{let _=parseInt(Ei(v,"utf8").trim(),10);if(_===process.pid||!l0(_))return!1}catch{}return!0}catch{return!1}}function f(h,S){if(S)try{e0(l(h),{recursive:!0}),t0(d(h,S),String(process.pid))}catch(v){console.error("[lock] claim failed:",q(v))}}function p(h){try{n0(Ot(h,".claude-bulb"),{recursive:!0,force:!0})}catch{}}function y(h){let S=l(h);if(!dm(S))return;let v;try{v=pm(S)}catch{return}let _=Date.now();for(let I of v){if(!I.endsWith(".lock"))continue;let L=Ot(S,I);try{let C=pr(L);_-C.mtimeMs>c0&&r0(L)}catch{}}}function m(h){try{return pr(h),!1}catch(S){return S.code==="ENOENT"}}function b(){let h=e;if(h.file&&!m(h.file)){f(h.cwd,h.sessionId);return}let S=x(h);S&&k(S)}function x(h){if(!h.everAttached)return A(h.cwd)??g(h.cwd,()=>!0)}function A(h){let S=l(h);if(!dm(S))return;let v;try{v=pm(S)}catch{return}let _;for(let L of v)if(L.endsWith(".lock"))try{let C=pr(Ot(S,L));if(Date.now()-C.mtimeMs>=hm||parseInt(Ei(Ot(S,L),"utf8").trim(),10)!==process.pid)continue;(!_||C.mtimeMs>_.mtime)&&(_={sessionId:L.slice(0,-5),mtime:C.mtimeMs})}catch{}if(!_)return;let I=r.listSessionFiles(h).find(L=>L.sessionId===_.sessionId);if(!(!I||m(I.file)))return I}function g(h,S){return r.listSessionFiles(h).sort((v,_)=>_.mtime-v.mtime).find(v=>!u(h,v.sessionId)&&S(v))}function w(h,S){let v=e;if(v.file)try{mm(v.file)}catch{}v.file=h,v.sessionId=S,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:S})}function k(h){let S=e;n=void 0,w(h.file,h.sessionId),S.everAttached=!0,f(S.cwd,h.sessionId),T();try{mm(h.file)}catch{}Zx(h.file,{interval:200},()=>T())}function E(){w(void 0,"")}function T(){let h=e;if(!h.file)return;let S;try{S=pr(h.file).size}catch{return}if(S<=h.offset)return;let v;try{v=zx(h.file,"r")}catch{return}try{let j=S-h.offset,ie=Buffer.alloc(j),Y=0;for(;Y<j;){let dl=Qx(v,ie,Y,j-Y,h.offset+Y);if(!dl)break;Y+=dl}h.offset+=Y,h.partial+=ie.subarray(0,Y).toString("utf8")}finally{Xx(v)}let _,I;for(;(I=h.partial.indexOf(`
|
|
519
|
+
`))>=0;){let j=h.partial.slice(0,I);if(h.partial=h.partial.slice(I+1),!j.trim())continue;let ie=r.parseEntry(j);if(!ie)continue;let Y=r.idOf(ie);Y&&(h.entries.set(Y,ie),!r.isSidechain(ie)&&r.isLeafType(ie)&&(_=Y))}if(!_)return;let L=[],C=h.entries.get(_),F=!1;for(;C;){if(L.push(C),r.idOf(C)===h.chainLastId){F=!0;break}let j=r.parentOf(C);C=j?h.entries.get(j):void 0}if(F)for(let j=L.length-2;j>=0;j--)V(L[j]);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 j=new Set(L.map(Y=>r.idOf(Y))),ie=P(h.entries);for(let Y=L.length-1;Y>=0;Y--)V(L[Y]),D(r.idOf(L[Y]),ie,j)}h.chainLastId=_}function P(h){let S=new Map;for(let v of h.values()){let _=r.parentOf(v);if(!_)continue;let I=S.get(_);I?I.push(v):S.set(_,[v])}return S}function D(h,S,v){if(!h)return;let _=S.get(h);if(!_)return;let I=_.filter(j=>!r.isSidechain(j));if(I.length<2)return;let L=I.filter(j=>!v.has(r.idOf(j)));if(!L.length)return;let C=[],F=0;for(let j of L){let ie=te(j,S);C.push(...ie.events),F+=ie.count}F>0&&e.buffer.push({type:"fork",atId:h,count:F,events:C})}function te(h,S){let v=[],_=[h];for(;_.length;){let C=_.pop();if(r.isSidechain(C))continue;v.push(C);let F=S.get(r.idOf(C)??"");if(F)for(let j of F)_.push(j)}v.sort((C,F)=>(Date.parse(r.timestampOf(C)??"")||0)-(Date.parse(r.timestampOf(F)??"")||0));let I=[];for(let C of v)r.isRecoveryNoise(C)||I.push(...r.apply(C,e.sessionStartMs).events);return{count:I.reduce((C,F)=>C+(F.type==="user"||F.type==="assistant"?1:0),0),events:I}}function V(h){try{let{events:S,usage:v,model:_,cost:I}=r.apply(h,e.sessionStartMs);for(let L of S)e.buffer.push(L);S.some(L=>L.type==="assistant")&&s()?.d.clearCompletedDraft(),S.some(L=>L.type==="user")&&s()?.d.clearEcho(),_&&(e.latestModel=_),v&&(e.latest=v),(v||I)&&e.buffer.push({type:"usage",...e.latest,cost:I})}catch(S){console.error("[mirror] skipped malformed entry:",q(S))}}async function B(){return{cwd:e.cwd,pid:process.pid,composer:!!r.createDriver}}let it=new wi;async function Vi(h,S){it.accept(h,S)&&console.log(S)}function tg(){let h=r.sessionAlive(e.sessionId,e.cwd);if(h!==void 0)return h;if(!e.file)return!1;try{return Date.now()-pr(e.file).mtimeMs<1e4}catch{return!1}}function Yi(){return r.chainWorking([...e.entries.values()])&&tg()}function rg(){!r.createDriver||s()||e.latestModel||Yi()||i(e.file)}async function ng(h){let S=e;b(),c(),rg(),a();let v=s();for(let C of t)C!==v&&C.d.dialog;let _=new Set([...t].filter(C=>C.d.streaming&&C.file).map(C=>C.file)),I=_.size?r.listSessionFiles(S.cwd).filter(C=>_.has(C.file)).map(C=>C.sessionId):[],L=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:S.buffer.slice(h),cursor:S.buffer.length,working:!!v?.d.streaming||Yi(),latestModel:S.latestModel,composer:L,busy:I}}async function cl(){b(),c();let h=s();if(h?.d.error&&!h.d.streaming&&(await o(h),h=void 0),!h){if(Yi())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 sg(h,S){if(!r.createDriver)return{ok:!1,error:"not supported"};let v=String(h??"").trim();if(!v)return{ok:!1,error:"empty message"};let _=await cl();return _.ok?_.d.send(v,S):_}async function ig(h,S){let v=s();return v?v.d.respondUi(String(h??""),S??{}):{ok:!1,error:"no dialog pending"}}async function og(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 _=await cl();return _.ok?_.d.rpc(h):_}let v=s();return!v||v.d.error?{ok:!1,error:"not running"}:v.d.rpc(h)}async function ag(){let h=s();if(h)try{await h.d.stop()}catch(S){console.error("[composer] stop:",q(S))}return{ok:!0}}async function cg(){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&&E(),i(void 0),a(),{ok:!0})):{ok:!1,error:"not supported"}}async function lg(){if(!r.createDriver)return[];let h=await new Promise(v=>{i0("git",["ls-files","--cached","--others","--exclude-standard"],{cwd:e.cwd,maxBuffer:64*1024*1024},(_,I)=>v(_?"":I))});return(await Promise.all(h.split(`
|
|
520
|
+
`).filter(Boolean).map(async v=>{try{return{f:v,m:(await s0(Ot(e.cwd,v))).mtimeMs}}catch{return{f:v,m:0}}}))).sort((v,_)=>_.m-v.m).map(v=>v.f)}function ug(){for(let h of[...t])o(h)}async function fg(h){return r.createDriver?lm(e.cwd,h):{ok:!1,error:"not supported"}}async function dg(h){return um(e.cwd,String(h??""))}async function pg(){return r.listSessionFiles(e.cwd).sort((h,S)=>S.mtime-h.mtime).map(({sessionId:h,file:S,mtime:v})=>({sessionId:h,mtime:v,preview:r.readPreview(S)}))}let ll=new Map;function mg(h,S){let v=ll.get(h);if(v&&v.mtime===S)return v.turns;let _=[],I="";try{I=Ei(h,"utf8")}catch{return[]}for(let L of I.split(`
|
|
521
|
+
`)){if(!L.trim())continue;let C=r.parseEntry(L);if(!C)continue;let F=r.searchText(C);F&&_.push({text:F,lower:F.toLowerCase()})}return ll.set(h,{mtime:S,turns:_}),_}async function hg(h){let S=h.toLowerCase(),v=[];for(let{sessionId:_,file:I,mtime:L}of r.listSessionFiles(e.cwd).sort((C,F)=>F.mtime-C.mtime)){let{hitCount:C,snippet:F}=vi(mg(I,L),S);if(C&&(v.push({sessionId:_,mtime:L,preview:r.readPreview(I),hitCount:C,snippet:F}),v.length>=u0))break}return v}let ul=800,fl=new Map;function gg(h,S){let v=fl.get(h);if(v&&v.mtime===S)return v.text;let _="";try{_=Ei(h,"utf8")}catch{return""}let I="";for(let C of _.split(`
|
|
522
|
+
`)){if(!C.trim())continue;let F=r.parseEntry(C);if(F)for(let j of r.apply(F,e.sessionStartMs).events)j.type==="assistant"&&j.text.trim()&&(I=j.text.trim())}let L=I.length>ul?I.slice(0,ul).trimEnd()+"\u2026":I;return fl.set(h,{mtime:S,text:L}),L}async function yg(h){let S=r.listSessionFiles(e.cwd).find(v=>v.sessionId===h);return{text:S?gg(S.file,S.mtime):""}}async function bg(h){let S=e,v=r.listSessionFiles(S.cwd).find(_=>_.sessionId===h);return v?v.file===S.file?{ok:!0}:(k(v),c(),a(),{ok:!0}):{ok:!1,error:"session not found"}}return p(e.cwd),y(e.cwd),b(),{info:B,poll:ng,logEmbedStatus:Vi,listSessions:pg,searchSessions:hg,sessionPeek:yg,attach:bg,composerSend:sg,composerStop:ag,composerNew:cg,composerFiles:lg,composerUiRespond:ig,composerRpc:og,composerPaste:fg,composerPasteRead:dg,shutdownComposer:ug}}var o0,a0,hm,c0,u0,Nc=R(()=>{Tt();om();Cc();fm();o0=".typebulb",a0=`${o0}/locks`,hm=5e3,c0=6e4;u0=50});import{existsSync as Ic,mkdirSync as f0,readFileSync as gm,writeFileSync as d0}from"fs";import{join as mr,isAbsolute as p0}from"path";async function ym(r,e){let t=p0(r)?r:mr(G,r);return Ic(t)?(Oc(t,e),{ok:!0}):{ok:!1,error:"file not found"}}async function bm(r){let e=G,t=Pc(r),n=mr(e,"typebulbs");f0(n,{recursive:!0});let s=Ec(t),i=`${s}.bulb.md`;for(let l=2;Ic(mr(n,i))&&gm(mr(n,i),"utf8")!==t;l++)i=`${s}-${l}.bulb.md`;let o=mr(n,i);Ic(o)||d0(o,t);let a=mr("typebulbs",i),c=await fi(a,{cwd:e,open:!1});return{ok:!0,file:a,pid:c.pid,url:c.url}}async function wm(){return K(G)}async function vm(r){return await xt(r),{ok:!0}}async function Sm(){return pi(G).filter(r=>!r.serverOnly).map(r=>({...r,trusted:kt(r.path)}))}async function km(r){let e=r.toLowerCase(),t=[];for(let n of pi(G).filter(s=>!s.serverOnly).sort((s,i)=>i.mtime-s.mtime)){let s="";try{s=gm(n.path,"utf8")}catch{continue}let i=[];for(let c of s.split(`
|
|
523
|
+
`)){let l=c.replace(/\s+/g," ").trim();l&&i.push({text:l,lower:l.toLowerCase()})}let{hitCount:o,snippet:a}=vi(i,e);o&&t.push({path:n.path,hitCount:o,snippet:a})}return t}async function xm(r,e){let t=G;e!=null&&ir(r,e);let n=await fi(r,{cwd:t,open:!1,trust:e});return{ok:!0,file:n.file,pid:n.pid,url:n.url,trust:!!n.trust}}async function Em(r){return{cap:await Tc(r)}}async function Am(r,e){return ir(r,e),{ok:!0}}async function Tm(r,e){return ke(r,e)}var Lc=R(()=>{fr();Tt();Cc()});import{readFileSync as Dc,writeFileSync as Om,mkdirSync as m0,appendFileSync as Rm,rmSync as Pm}from"fs";import{join as Oi,dirname as h0}from"path";import{createServer as g0}from"http";function tt(r){try{return JSON.parse(Dc(r,"utf8"))}catch{return null}}function Pi(r,e){m0(h0(r),{recursive:!0}),Om(r,JSON.stringify(e,null,2)+`
|
|
524
|
+
`)}function Cm(r,e,t){let n=Oi(r,".gitignore"),s="";try{s=Dc(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(`
|
|
523
525
|
`)?`
|
|
524
|
-
`:"";try{
|
|
526
|
+
`:"";try{Rm(n,a+t+`
|
|
525
527
|
`+o.join(`
|
|
526
528
|
`)+`
|
|
527
|
-
`)}catch(c){console.error("[switcher] .gitignore update failed",
|
|
529
|
+
`)}catch(c){console.error("[switcher] .gitignore update failed",q(c))}}function S0(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?vn="live":s>v0&&(vn="uncached")}function Im(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 k0(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 Lm(r){let e;try{e=JSON.parse(r)}catch{return r}wn=typeof e?.model=="string"?e.model:null,Ae&&(e.model=Ae),_t&&(e.provider=Nm(_t));let t=/haiku/i.test(wn||"");return Sn!=null&&!t&&(e.reasoning={effort:Mc[Sn]}),delete e.thinking,e.output_config&&delete e.output_config.effort,k0(e),JSON.stringify(e)}function x0(){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}
|
|
528
530
|
data: ${JSON.stringify(a)}
|
|
529
531
|
|
|
530
532
|
`}case"content_block_delta":case"content_block_stop":{let c=t.get(a.index);return c==null?null:(a.index=c,`event: ${a.type}
|
|
@@ -532,11 +534,11 @@ data: ${JSON.stringify(a)}
|
|
|
532
534
|
|
|
533
535
|
`)}default:return i}};return i=>{r+=i;let o="",a;for(;(a=r.indexOf(`
|
|
534
536
|
|
|
535
|
-
`))!==-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
|
|
537
|
+
`))!==-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 E0(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 bn(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 A0(r,e,t){if(!Ae){bn(e,400,"invalid_request_error",w0);return}let n=process.env.OPENROUTER_API_KEY;if(!n){bn(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(Bc,{method:"POST",headers:Im(r,n),body:Lm(t),signal:s.signal})}catch(u){bn(e,502,"api_error",`proxy upstream failed: ${q(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,d=a?x0():null;try{for(;;){let{done:u,value:f}=await c.read();if(u)break;if(f)if(d){let p=l.decode(f,{stream:!0});S0(p);let y=d(p);y&&e.write(y)}else e.write(Buffer.from(f))}}catch{}finally{e.writableEnded||e.end()}}async function T0(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(!Ae||!n)return s();try{let i=await fetch(`${Bc}/count_tokens`,{method:"POST",headers:Im(r,n),body:Lm(t)});if(!i.ok)return s();let o=await i.text();e.writeHead(200,{"content-type":"application/json"}),e.end(o)}catch{s()}}function P0(r,e){let t=r.url||"/";if(r.method==="HEAD"){e.writeHead(200),e.end();return}if(r.method!=="POST"){bn(e,404,"not_found_error",t);return}E0(r).then(n=>{if(t.includes("count_tokens"))return T0(r,e,n);if(t.includes("/v1/messages"))return A0(r,e,n);bn(e,404,"not_found_error",t)})}function O0(){return hr&&Rt?Promise.resolve(Rt):new Promise((r,e)=>{let t=g0(P0);t.on("error",e),t.listen(0,"127.0.0.1",()=>{hr=t,Rt=t.address().port,console.log(`[switcher] wire proxy listening on ${Ti(Rt)}`),r(Rt)})})}function R0(){try{hr?.close()}catch{}hr=null,Rt=null}function _0(r,e){let t=Ri(r),n=tt(t),s=n||{};if((!s.env||typeof s.env!="object")&&(s.env={}),s.env.ANTHROPIC_BASE_URL===Ti(e)&&s.env.ANTHROPIC_AUTH_TOKEN)return;let i=_i(r);if(!tt(i)){let a={};for(let c of _m)a[c]=c in s.env?s.env[c]:null;Pi(i,{managedBy:"agent-switcher",fileExisted:n!==null,snapshot:a,active:null})}s.env.ANTHROPIC_BASE_URL=Ti(e),s.env.ANTHROPIC_AUTH_TOKEN=b0,Pi(t,s),Cm(r,[".claude/settings.local.json",".claude/.cc-switcher.json"],"# agent switcher (local Claude Code model override)")}function C0(r,e,t){let n=_i(r),s=tt(n)||{managedBy:"agent-switcher",fileExisted:!1,snapshot:{}};s.active={model:e,provider:t},Pi(n,s)}function Mm(r){let e=Ri(r),t=_i(r),n=tt(t),s=tt(e);if(s?.env){let i=n?.snapshot||{};for(let o of _m){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{Pm(e,{force:!0})}catch{}else Pi(e,s)}try{Pm(t,{force:!0})}catch{}}async function N0(){let r=!!process.env.OPENROUTER_API_KEY,e=[];try{e=(await Ne()).filter(n=>n.provider==="openrouter"&&!jc(n.name)).map(n=>({id:n.name,label:n.friendlyName||n.name}))}catch(n){console.error("[switcher] model list failed",q(n))}let t=e.length?void 0:rc()??void 0;return{hasKey:r,models:e,error:t}}async function I0(){if(hr&&Ae)return{active:!0,managed:!0,model:Ae,port:Rt,provider:_t,routedModel:wn,caching:vn,reasoning:Sn,externalBaseUrl:null};let r=tt(Ri(G))?.env||{};return{active:!1,managed:!1,model:null,port:null,provider:null,routedModel:null,caching:"unknown",reasoning:Sn,externalBaseUrl:r.ANTHROPIC_BASE_URL||null}}async function $m(r,e){let t=await O0();return Ae=r,_t=e,_0(G,t),t}async function L0({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(jc(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 $m(r,Fc[r]??null),wn=null,vn="unknown",C0(G,r,_t)}catch(e){return{ok:!1,error:`failed to start the wire proxy: ${q(e)}`}}return{ok:!0}}async function M0({level:r}){return r!=null&&(!Number.isInteger(r)||r<0||r>=Mc.length)?{ok:!1,error:`reasoning level must be 0\u2013${Mc.length-1} or null`}:(Sn=r,{ok:!0,level:r})}async function $0(){return Mm(G),Ae=null,_t=null,wn=null,vn="unknown",{ok:!0}}async function D0({key:r}){let e=(r||"").trim();if(!e)return{ok:!1,error:"empty key"};let t=G,n=Oi(t,".env"),s="";try{s=Dc(n,"utf8")}catch{}try{if(/^\s*OPENROUTER_API_KEY\s*=/m.test(s))Om(n,s.replace(/^\s*OPENROUTER_API_KEY\s*=.*$/m,`OPENROUTER_API_KEY=${e}`));else{let i=s&&!s.endsWith(`
|
|
536
538
|
`)?`
|
|
537
|
-
`:"";
|
|
538
|
-
`)}}catch(i){return{ok:!1,error:
|
|
539
|
-
`)}catch(o){return{ok:!1,error:`could not write ${r}: ${
|
|
539
|
+
`:"";Rm(n,i+`OPENROUTER_API_KEY=${e}
|
|
540
|
+
`)}}catch(i){return{ok:!1,error:q(i)}}return process.env.OPENROUTER_API_KEY=e,Cm(t,[".env"],"# secrets"),{ok:!0}}function B0(){if(!(!hr&&!Ae)){try{Mm(G)}catch{}R0()}}function j0(r,e){return Dm.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 F0(r){if(Dm.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 q0(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=$c(e?.cache_read_input_tokens)||$c(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 U0({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(jc(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 d=JSON.stringify(a?{...i,provider:Nm(a)}:i),u=await fetch(Bc,{method:"POST",signal:c.signal,headers:s,body:d}),f=await u.json().catch(()=>({}));return{r:u,j:f}}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:j0(a.status,x),restriction:F0(x)}}let l=typeof c?.provider=="string"?c.provider:void 0,d=c?.content?.find?.(x=>x.type==="text")?.text??c?.content?.[0]?.text??"ok",u=$c(c?.usage?.cache_creation_input_tokens),{r:f,j:p}=await o(l),{works:y,read:m,note:b}=q0(f.ok,p?.usage,l);return y===!0&&l&&(Fc[r]=l,Ae===r&&(_t=l)),{ok:!0,callable:!0,status:a.status,ms:Date.now()-t,provider:l,sample:String(d).trim().slice(0,60),cache:{works:y,created:u,read:m,note:b}}}catch(a){let c=q(a);return{ok:!0,callable:!1,ms:Date.now()-t,error:/abort/i.test(c)?"timed out (20s)":c}}}var y0,Bc,b0,w0,_m,v0,Mc,Ri,_i,Ti,jc,hr,Rt,Ae,_t,wn,vn,Sn,Fc,$c,Nm,Dm,Bm=R(()=>{fr();Tt();y0="https://openrouter.ai/api",Bc=`${y0}/v1/messages`,b0="typebulb-proxy-managed",w0="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.",_m=["ANTHROPIC_BASE_URL","ANTHROPIC_AUTH_TOKEN"],v0=5e3,Mc=["low","medium","high"],Ri=r=>Oi(r,".claude","settings.local.json"),_i=r=>Oi(r,".claude",".cc-switcher.json"),Ti=r=>`http://127.0.0.1:${r}`;jc=r=>/^anthropic\//i.test(r)||/claude/i.test(r),hr=null,Rt=null,Ae=null,_t=null,wn=null,vn="unknown",Sn=1,Fc={},$c=r=>typeof r=="number"?r:0,Nm=r=>({order:[r],allow_fallbacks:!1});Dm=/data policy|no endpoints|no allowed providers|privacy|requires.*(training|logging|data)/i;(async function(){try{let e=tt(_i(G)),t=e?.active?.model;if(!t)return;let s=(tt(Ri(G))?.env||{}).ANTHROPIC_BASE_URL||"";if(!/127\.0\.0\.1|localhost/.test(s))return;let i=await $m(t,e.active.provider??Fc[t]??null);console.log(`[switcher] re-adopted override after restart: ${t} via ${Ti(i)}`)}catch(e){console.error("[switcher] boot reconcile failed",q(e))}})()});var Fm={};pl(Fm,{attach:()=>z0,blockToMarkdown:()=>oi,breakout:()=>bm,capText:()=>Se,cleanUserText:()=>et,clearSwitchModel:()=>$0,composerPasteRead:()=>Q0,displayName:()=>J0,firstLineDigest:()=>Me,info:()=>K0,isHiddenTurn:()=>mn,launchBulb:()=>xm,listBreakouts:()=>wm,listBulbFiles:()=>Sm,listSessions:()=>V0,listSwitchModels:()=>N0,logEmbedStatus:()=>H0,openFile:()=>ym,poll:()=>W0,predictTrustOf:()=>Em,probeModel:()=>U0,readBulbLog:()=>Tm,saveOpenRouterKey:()=>D0,searchBulbs:()=>km,searchSessions:()=>Y0,sessionPeek:()=>G0,setBulbTrust:()=>Am,setReasoning:()=>M0,setSwitchModel:()=>L0,shutdownSwitcher:()=>B0,stopBreakout:()=>vm,switchState:()=>I0,toolResultDigest:()=>mc});var jm,J0,K0,W0,H0,V0,Y0,G0,z0,Q0,qm=R(()=>{Nc();ai();Lc();Bm();ai();si();jm=new ar,J0=jm.displayName,{info:K0,poll:W0,logEmbedStatus:H0,listSessions:V0,searchSessions:Y0,sessionPeek:G0,attach:z0,composerPasteRead:Q0}=Ai(jm)});import{readFileSync as X0,writeFileSync as Z0,mkdirSync as eE}from"fs";import{homedir as tE}from"os";import*as Ci from"path";async function Km(){try{let r=await fetch(new URL("/api/tags",Jm()).toString(),{signal:AbortSignal.timeout(rE)});return r.ok?((await r.json()).models??[]).map(t=>t.name).filter(t=>!!t):[]}catch{return[]}}function Wm(r){let e;try{e=X0(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&&!qc(n)}}}catch{}return{json:void 0,unreadable:!0}}function qc(r){let e=r?.providers;return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function nE(r){let e=qc(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 Hm(){let{json:r,unreadable:e}=Wm(Um());return e?{installed:[],configured:null}:{installed:await Km(),configured:nE(r)}}async function Vm(){let r=await Km();return r.length?sE(Um(),r,Jm()):{ok:!1,error:"Ollama is not running (or has no models installed)"}}function sE(r,e,t){let{json:n,unreadable:s}=Wm(r);if(s)return{ok:!1,error:`could not parse ${r} \u2014 edit the ollama provider there yourself`};let i={...n??{},providers:{...qc(n)??{},ollama:{baseUrl:`${t}/v1`,api:"openai-completions",apiKey:"ollama",models:e.map(o=>({id:o}))}}};try{eE(Ci.dirname(r),{recursive:!0}),Z0(r,JSON.stringify(i,null,2)+`
|
|
541
|
+
`)}catch(o){return{ok:!1,error:`could not write ${r}: ${q(o)}`}}return{ok:!0,count:e.length}}var rE,Um,Jm,Ym=R(()=>{Tt();fr();rE=1500,Um=()=>Ci.join(tE(),".pi","agent","models.json"),Jm=()=>sr(process.env.OLLAMA_HOST??"http://localhost:11434")});var zm={};pl(zm,{attach:()=>dE,breakout:()=>bm,composerFiles:()=>gE,composerNew:()=>hE,composerPaste:()=>wE,composerPasteRead:()=>vE,composerRpc:()=>bE,composerSend:()=>pE,composerStop:()=>mE,composerUiRespond:()=>yE,displayName:()=>iE,info:()=>oE,launchBulb:()=>xm,listBreakouts:()=>wm,listBulbFiles:()=>Sm,listSessions:()=>lE,logEmbedStatus:()=>cE,ollamaOffer:()=>Hm,ollamaSync:()=>Vm,openFile:()=>ym,poll:()=>aE,predictTrustOf:()=>Em,readBulbLog:()=>Tm,searchBulbs:()=>km,searchSessions:()=>uE,sessionPeek:()=>fE,setBulbTrust:()=>Am,shutdownComposer:()=>SE,stopBreakout:()=>vm});var Gm,iE,oE,aE,cE,lE,uE,fE,dE,pE,mE,hE,gE,yE,bE,wE,vE,SE,Qm=R(()=>{Nc();_c();Lc();Ym();Gm=new dr,iE=Gm.displayName,{info:oE,poll:aE,logEmbedStatus:cE,listSessions:lE,searchSessions:uE,sessionPeek:fE,attach:dE,composerSend:pE,composerStop:mE,composerNew:hE,composerFiles:gE,composerUiRespond:yE,composerRpc:bE,composerPaste:wE,composerPasteRead:vE,shutdownComposer:SE}=Ai(Gm)});import*as eg from"fs/promises";import*as It from"path";import*as hl from"fs/promises";import{existsSync as Lt,readFileSync as Tg}from"fs";import*as W from"path";import{pathToFileURL as Pg}from"url";import{resolve as Qi}from"resolve.exports";import{init as gl,parse as yl}from"es-module-lexer";function bl(r,e){let t=W.join(r,"package.json");try{return JSON.parse(Tg(t,"utf8"))}catch{throw new Error(`--replace package '${e}' has no readable package.json at ${t}`)}}var zi=["browser","import","default"],ml=["node","import","default"];function wl(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:W.resolve(n)}}async function vl(r){let{name:e,dir:t}=r;if(!Lt(t))throw new Error(`--replace path for '${e}' does not exist: ${t}`);let n=bl(t,e),s=Og(n,e),i=W.resolve(t,s);if(!Lt(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=W.dirname(i),a=`/local/${e}/${W.basename(i)}`,c=Rg(n,t);return await _g(e,i,o),{name:e,dir:t,entryAbs:i,serveDir:o,entryUrl:a,typesAbs:c}}function Og(r,e){if(r.exports!==void 0){let n;try{n=Qi(r,".",{browser:!0,conditions:zi})}catch(i){throw new Error(`--replace package '${e}' "exports" does not resolve a browser entry (conditions: ${zi.join(", ")}): ${i instanceof Error?i.message:i}`)}let s=Xi(n);if(!s)throw new Error(`--replace package '${e}' "exports" did not resolve "." to a single file (conditions: ${zi.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 Rg(r,e){if(r.exports!==void 0)try{let n=Qi(r,".",{conditions:["types"]}),s=Xi(n);if(s){let i=W.resolve(e,s);if(Lt(i))return i}}catch{}let t=r.types??r.typings;if(t){let n=W.resolve(e,t);if(Lt(n))return n}}function Xi(r){if(typeof r=="string")return r;if(Array.isArray(r))return r.find(e=>typeof e=="string")}async function _g(r,e,t){await gl;let n=W.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 hl.readFile(o,"utf8")}catch{continue}let c,l;try{[c,,,l]=yl(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 d of c){if(d.d===-2)continue;let u=d.n;if(u&&!u.startsWith("node:")){if(u.startsWith("./")||u.startsWith("../")||u.startsWith("/")){let f=Cg(o,u,n);f&&!s.has(f)&&i.push(f);continue}throw new Error(`override package must ship self-contained (bundle its dependencies); ${r} externalizes '${u}'`)}}}}function Cg(r,e,t){let n=e.replace(/[?#].*$/,""),s=W.resolve(W.dirname(r),n),i=[s,s+".js",s+".mjs",W.join(s,"index.js"),W.join(s,"index.mjs")];for(let o of i)if(W.normalize(o).startsWith(t)&&Lt(o))return o}function Ng(r,e,t){let n=bl(r,e),s;if(n.exports!==void 0)try{s=Xi(Qi(n,t,{conditions:ml}))}catch(o){throw new Error(`--replace package '${e}' "exports" does not resolve a node entry for '${t}' (conditions: ${ml.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=W.resolve(r,s);if(!Lt(i))throw new Error(`--replace package '${e}' built file not found: ${i} \u2014 did you build it (e.g. \`pnpm run build\`)?`);return Pg(i).href}async function Sl(r,e){await gl;let t;try{[t]=yl(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=Ng(e.dir,e.name,a);n+=r.slice(s,i.s)+c,s=i.e}return n+r.slice(s)}var Ig=5e3;function kl(r){let t={subcommand:"run",file:"",port:3e3,watch:!0,open:!(process.env.TERM_PROGRAM==="vscode"),server:!1,trust:!1,noTrust:!1,follow:!1,clear:!1,help:!1,version:!1,callArgs:[],hasArgsFlag:!1},n=["call","check","predict","logs","wait","stop","trust","untrust","skill","models","send"],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==="--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==="--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=Ig;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=wl(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 xl(){console.log(`
|
|
540
542
|
typebulb - Local bulb runner for Typebulb
|
|
541
543
|
|
|
542
544
|
Usage:
|
|
@@ -665,226 +667,19 @@ Examples:
|
|
|
665
667
|
typebulb my-editor.bulb.md
|
|
666
668
|
typebulb --no-watch --port 8080 my-editor.bulb.md
|
|
667
669
|
typebulb .
|
|
668
|
-
`)}Zr();import*as
|
|
670
|
+
`)}Zr();import*as Ze from"fs/promises";import*as Ie from"path";import{pathToFileURL as ok}from"url";import{transform as wS}from"sucrase";function qa(r,e={}){let t=e.serverOnly?["typescript"]:["typescript","jsx"];try{let{code:n}=wS(r,{transforms:t,jsxRuntime:"automatic",jsxImportSource:e.jsxImportSource||"react",production:!0});return{code:n}}catch(n){return{code:"",error:String(n)}}}Cs();function TS(r){return r.map(e=>`${e.type} (line ${e.lineNumber}): ${e.message.split(`
|
|
669
671
|
`)[0]}`).join(`
|
|
670
|
-
`)}function
|
|
671
|
-
${wS(t)}`)}var Ge="https://esm.sh",tn="https://cdn.jsdelivr.net/npm/",Ja="https://data.jsdelivr.com/v1/package/npm/";function Bd(r){let e=(r||"").replace(/^\/+/,"").replace(/\/+$/,"");return e?e.split("/"):[]}var N=class r{constructor(e,t,n){let s=typeof e=="string"?r.parse(e):e;this.name=s.name,this.version=Gt(t??s.version),this.subpath=Gt(n??s.subpath)}static parse(e){let t=Bd(e||"");if(!t.length)return new r({name:""});if(t[0].startsWith("@")){let s=t[0],[i,o]=jd(t[1]??""),a=Gt(t.slice(2).join("/"));return new r({name:`${s}/${i}`,version:o,subpath:a})}else{let[s,i]=jd(t[0]),o=Gt(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(Ge).host,s=new URL(tn).host;if(t.host===n){let i=Bd(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:Gt(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://")}},Gt=r=>r&&r.length?r:void 0,jd=r=>{let e=r.indexOf("@");return e<0?[r,void 0]:[r.slice(0,e),Gt(r.slice(e+1))]};async function Oe(r){try{return await r()}catch{return}}function mt(r){let e=r||"";return e.startsWith("./")?e.slice(2):e.replace(/^\/+/,"")}function Ka(r){return r.startsWith("./")?r:`./${r}`}var rn=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 N(e):e;return`${tn}${t.name}${t.version?`@${t.version}`:""}/`}file(e,t){return new URL(mt(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(",")),`${Ge}/${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),`${Ge}/${e}`]);return this.pinCache.set(e,{value:s,ts:t}),s}async tryResolveFromUrls(e){for(let t of e){let n=await Oe(()=>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 Oe(()=>this.http.getJson(`${Ja}${encodeURIComponent(e)}`));if(!n?.versions?.length){await this.cache.recordNegative(e);return}await this.cache.clearNegative(e);let s=n.distTags&&Object.keys(n.distTags).length?n.distTags:void 0;return await this.cache.setIndex(e,n.versions,s),n}parseVersionFromUrl(e){let t=N.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 N(`${e}@${t}`)),i=await Oe(()=>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 Fd=r=>r.startsWith("@types/"),nn=r=>Object.keys(r?.peerDependencies||{}).filter(e=>!Fd(e)),Wa=r=>Object.keys(r?.dependencies||{}).filter(e=>!Fd(e)),vS=r=>nn(r).filter(e=>!r?.peerDependenciesMeta?.[e]?.optional),sn=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 vS(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=>nn(i.meta))),n=new Map;for(let i of e)for(let o of Wa(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:nn(i.meta).length>0,isSharedDep:s.has(i.name)}]))}};var on=class{constructor(e,t,n){this.cache=e,this.cdn=t,this.semver=n}async learnExactVersion(e){let t=await Oe(()=>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 Oe(()=>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 Oe(()=>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 N(e),s=n.root(),i=t[s],o=i?await Oe(()=>this.resolveExactForRoot(s,i)):void 0;return{effectivePackage:o?n.withVersion(o).format():e,root:s,range:i,pinned:o}}};import{init as SS,parse as kS}from"es-module-lexer";var zt=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))N.isBare(s[1])&&t.add(s[1])}return Array.from(t)}async extractImports(e){let t=new Set,n=s=>{N.isBare(s)&&t.add(s)};try{await SS;let[s]=kS(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(N.rootOf(u))),i=[...new Set(s.map(N.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 y=s.get(N.rootOf(p));return new N(p).withVersion(y.version).format()},o=new Set([...n.entries()].filter(([,p])=>p.isPeerRoot||p.isSharedDep).map(([p])=>p)),a=new Set(e.filter(p=>p!==N.rootOf(p)).map(N.rootOf)),c=[],l=new Set,d=new Set(e.filter(p=>p===N.rootOf(p))),u=new Set;for(let p of e){let y=N.rootOf(p),m=s.get(y),{isPeerRoot:b,hasPeers:E,isSharedDep:T}=n.get(y),g=a.has(y),w=p!==y,x=!(b||T)&&(g||!E),O=this.singletonDepsOf(m,o),A=w&&d.has(y);A&&u.add(y);let M=A?[...O,y]:O.length?O:void 0;c.push([p,this.cdn.buildEsmUrl(i(p),{bundle:x,external:M})]),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}/`,`${Ge}/${i(p)}/`]));return c}singletonDepsOf(e,t){return[...new Set([...nn(e.meta),...Wa(e.meta)])].filter(n=>t.has(n))}};zt.importPatterns=[/\bimport\s+(?:[^'";]*?from\s*)?['"]([^'"]+)['"]/g,/\bexport\s+[^'";]*?from\s*['"]([^'"]+)['"]/g];import{gt as qd,satisfies as xS,maxSatisfying as Ud,major as ES,valid as AS}from"semver";var Cs=class{cmp(e,t){return e===t?0:qd(e,t)?1:qd(t,e)?-1:0}satisfies(e,t){return!e||!e.trim()?!0:!!xS(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=Ud(e,n,{includePrerelease:!1});if(a)return a}return Ud(e,n,{includePrerelease:!0})??void 0}majorOf(e){return ES(e)}isExactVersion(e){return AS(e)!==null}},ht=new Cs;function Jd(r,e){let t=new rn(r,e),n=new sn(t),s=new on(r,t,ht);return{packageService:new zt(s,t,n),versionResolver:s,cdnClient:t,peerResolver:n}}import*as ip from"fs/promises";import*as de from"path";var Ha=[{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"}],Va=[{name:"dom"},{name:"dom.iterable"},{name:"dom.asynciterable"}];function Ya(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 TS=`
|
|
672
|
-
|
|
673
|
-
* Get raw data chunk from the Data tab.
|
|
674
|
-
* @param index - Chunk index (0-based). Separate chunks with 2 blank lines.
|
|
675
|
-
*/
|
|
676
|
-
data(index: number): string;
|
|
677
|
-
/**
|
|
678
|
-
* Get data chunk parsed as JSON (handles JSON-ish with unquoted keys).
|
|
679
|
-
* @param index - Chunk index (0-based)
|
|
680
|
-
* @throws If chunk is not valid JSON/JSON-ish
|
|
681
|
-
*/
|
|
682
|
-
json<T = unknown>(index: number): T;`,PS=`
|
|
683
|
-
/**
|
|
684
|
-
* Get the insight data produced by the inference layer.
|
|
685
|
-
*
|
|
686
|
-
* Returns the parsed JSON from insight.json, populated by the inference LLM.
|
|
687
|
-
* Use a type parameter to get typed access to the insight data.
|
|
688
|
-
*
|
|
689
|
-
* @returns The parsed insight JSON, or undefined if no insight is available
|
|
690
|
-
*/
|
|
691
|
-
insight<T = unknown>(): T | undefined;`,Kd=`options: {
|
|
692
|
-
messages: Array<{ role: "user" | "assistant"; content: string }>;
|
|
693
|
-
system?: string;
|
|
694
|
-
/** 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. */
|
|
695
|
-
effort?: 0 | 1 | 2 | 3;
|
|
696
|
-
provider?: string;
|
|
697
|
-
model?: string;
|
|
698
|
-
/** Enable/disable web search. Default: on for BYOK, always off for free model. */
|
|
699
|
-
webSearch?: boolean;
|
|
700
|
-
/** Abort the request. On abort the promise rejects / the stream ends. */
|
|
701
|
-
signal?: AbortSignal;
|
|
702
|
-
}`,Wd=`
|
|
703
|
-
/** A single streamed delta from \`tb.ai.stream()\`. Discriminated by \`kind\`. */
|
|
704
|
-
type AiChunk =
|
|
705
|
-
| { kind: "text"; text: string }
|
|
706
|
-
| { kind: "reasoning"; text: string };
|
|
707
|
-
`,Hd=`
|
|
708
|
-
/**
|
|
709
|
-
* General-purpose AI call. \`tb.ai(opts)\` resolves with the full text; \`tb.ai.stream(opts)\`
|
|
710
|
-
* returns an async iterable of {@link AiChunk} deltas you consume with \`for await\`.
|
|
711
|
-
*
|
|
712
|
-
* @returns Promise resolving to { text: string }
|
|
713
|
-
* @throws On rate limit, network error, or provider error
|
|
714
|
-
*/
|
|
715
|
-
ai: {
|
|
716
|
-
(${Kd}): Promise<{ text: string }>;
|
|
717
|
-
/**
|
|
718
|
-
* Streaming counterpart of \`tb.ai()\`. Yields \`{ kind: "text" | "reasoning", text }\` deltas
|
|
719
|
-
* as they arrive; break the loop (or abort \`signal\`) to cancel and stop the upstream.
|
|
720
|
-
*
|
|
721
|
-
* \`kind: "reasoning"\` deltas only arrive when you pass \`effort: 1-3\` AND use a
|
|
722
|
-
* thinking-capable model; otherwise the stream is \`text\`-only.
|
|
723
|
-
*
|
|
724
|
-
* @example
|
|
725
|
-
* let answer = "";
|
|
726
|
-
* for await (const c of tb.ai.stream({ messages })) {
|
|
727
|
-
* if (c.kind === "text") answer += c.text;
|
|
728
|
-
* }
|
|
729
|
-
*/
|
|
730
|
-
stream(${Kd}): AsyncIterable<AiChunk>;
|
|
731
|
-
};`,Vd=`
|
|
732
|
-
/**
|
|
733
|
-
* Returns AI models available to the current user.
|
|
734
|
-
* Models are filtered by the user's configured API keys.
|
|
735
|
-
* If no keys are configured, returns only the courtesy model.
|
|
736
|
-
*/
|
|
737
|
-
models(): Promise<Array<{
|
|
738
|
-
/** Provider protocol: "anthropic", "openai", "gemini", "openrouter" */
|
|
739
|
-
provider: string;
|
|
740
|
-
/** Model identifier, e.g. "claude-sonnet-4-6" */
|
|
741
|
-
name: string;
|
|
742
|
-
/** Human-readable display name, e.g. "Sonnet 4.6" */
|
|
743
|
-
friendlyName: string;
|
|
744
|
-
/** Provider display name, e.g. "Anthropic" */
|
|
745
|
-
providerName: string;
|
|
746
|
-
}>>;
|
|
747
|
-
/**
|
|
748
|
-
* Whether the user's own AI keys back \`tb.ai\`. False means only the
|
|
749
|
-
* quota-limited courtesy model is available (or no AI at all) \u2014 a bulb
|
|
750
|
-
* making many AI calls should check this and show a "use your own keys"
|
|
751
|
-
* notice instead of running.
|
|
752
|
-
*/
|
|
753
|
-
hasOwnKeys(): Promise<boolean>;`,OS="\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;",Yd=`
|
|
754
|
-
/**
|
|
755
|
-
* The mode this bulb is running in.
|
|
756
|
-
*
|
|
757
|
-
* - \`'local'\` \u2014 Running via the typebulb CLI
|
|
758
|
-
* - \`'editor'\` \u2014 Running in the typebulb.com editor
|
|
759
|
-
* - \`'published'\` \u2014 Running as a published/standalone bulb on typebulb.com
|
|
760
|
-
* - \`'embedded'\` \u2014 Running as a bulb embedded inside another bulb (sandboxed,
|
|
761
|
-
* client-only: AI, filesystem, and server RPC are unavailable)
|
|
762
|
-
*/
|
|
763
|
-
mode: 'local' | 'editor' | 'published' | 'embedded';`,RS=`
|
|
764
|
-
/**
|
|
765
|
-
* Local filesystem access (CLI only).
|
|
766
|
-
*
|
|
767
|
-
* Paths are resolved relative to the current working directory (where the CLI
|
|
768
|
-
* was launched), consistent with the .env cascade \u2014 not the bulb file's folder.
|
|
769
|
-
* Throws in editor/published mode.
|
|
770
|
-
*/
|
|
771
|
-
fs: {
|
|
772
|
-
/** Read a file as UTF-8 text. Throws if the file is not valid UTF-8 \u2014 use readBytes for binary. */
|
|
773
|
-
read(path: string): Promise<string>;
|
|
774
|
-
/** Read a file as raw bytes. */
|
|
775
|
-
readBytes(path: string): Promise<Uint8Array>;
|
|
776
|
-
/** Write text or raw bytes to a file. Creates parent directories if needed. */
|
|
777
|
-
write(path: string, content: string | Uint8Array): Promise<boolean>;
|
|
778
|
-
};`,_S=`
|
|
779
|
-
/**
|
|
780
|
-
* Async value inspector for tensor-like objects.
|
|
781
|
-
*
|
|
782
|
-
* Materializes lazy values (like GPU tensors) and logs them with metadata.
|
|
783
|
-
* Handles objects with \`.js()\`, \`.data()\`, \`.array()\`, \`.arraySync()\`, etc.
|
|
784
|
-
*
|
|
785
|
-
* @remarks
|
|
786
|
-
* - Always use \`await\` - materialization may be async (GPU\u2192CPU readback)
|
|
787
|
-
* - Large values are truncated (max 1000 elements)
|
|
788
|
-
* - Promises are logged as \`[Promise]\` (not awaited - could hang)
|
|
789
|
-
*/
|
|
790
|
-
dump(...args: any[]): Promise<void>;
|
|
791
|
-
/**
|
|
792
|
-
* Trigger inference to generate new insight data.
|
|
793
|
-
*
|
|
794
|
-
* Opens a confirmation modal showing the data to be analyzed, then streams
|
|
795
|
-
* the inference result. On success, updates the insight so subsequent
|
|
796
|
-
* \`tb.insight()\` calls return the new value.
|
|
797
|
-
*
|
|
798
|
-
* @param opts - Options for inference
|
|
799
|
-
* @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.
|
|
800
|
-
* @returns Promise that resolves with the parsed insight JSON
|
|
801
|
-
* @throws If inference is already in progress, or on network/parse/rate limit errors
|
|
802
|
-
*/
|
|
803
|
-
infer<T = unknown>(opts?: { data?: string | string[] }): Promise<T>;
|
|
804
|
-
/**
|
|
805
|
-
* Get the current inference state.
|
|
806
|
-
*
|
|
807
|
-
* @returns 'idle' | 'running' | 'complete' | 'error'
|
|
808
|
-
*/
|
|
809
|
-
inferenceState(): 'idle' | 'running' | 'complete' | 'error';
|
|
810
|
-
/**
|
|
811
|
-
* Set a data chunk for the next inference call.
|
|
812
|
-
*
|
|
813
|
-
* Use this to programmatically set data that will be sent when \`tb.infer()\` is called
|
|
814
|
-
* without the \`data\` option.
|
|
815
|
-
*
|
|
816
|
-
* @param index - The chunk index (0-based)
|
|
817
|
-
* @param content - The content for this chunk
|
|
818
|
-
*/
|
|
819
|
-
setData(index: number, content: string): void;
|
|
820
|
-
/**
|
|
821
|
-
* Proxy a CDN URL through the sandbox origin for Web Worker/WASM same-origin loading.
|
|
822
|
-
*
|
|
823
|
-
* In the sandbox, prepends \`/proxy/\` so the URL is served from the same origin.
|
|
824
|
-
* Outside the sandbox (exported HTML, CLI), returns the URL unchanged.
|
|
825
|
-
*
|
|
826
|
-
* @param url - Full HTTPS URL to an allowlisted CDN (esm.sh, unpkg.com, cdn.jsdelivr.net, cdnjs.cloudflare.com)
|
|
827
|
-
* @returns The proxied URL (sandbox) or the original URL (standalone/CLI)
|
|
828
|
-
*/
|
|
829
|
-
proxy(url: string): string;
|
|
830
|
-
/**
|
|
831
|
-
* Copy text to clipboard.
|
|
832
|
-
* Must be called synchronously within a user gesture (click/keydown).
|
|
833
|
-
* @returns true if successful, false otherwise
|
|
834
|
-
*/
|
|
835
|
-
copy(text: string): Promise<boolean>;
|
|
836
|
-
/**
|
|
837
|
-
* Get the canonical URL of this bulb.
|
|
838
|
-
*
|
|
839
|
-
* Returns the parent typebulb.com URL (including path, query, and \`#tb=\` fragment),
|
|
840
|
-
* resolving correctly from inside the cross-origin sandbox iframe.
|
|
841
|
-
* Use this instead of \`location.href\` or \`document.referrer\`.
|
|
842
|
-
*
|
|
843
|
-
* @returns The full canonical URL
|
|
844
|
-
*/
|
|
845
|
-
url(): Promise<string>;`,CS=`
|
|
846
|
-
/**
|
|
847
|
-
* Subscribe to a value pushed from the terminal via \`typebulb send <file> [message]\`.
|
|
848
|
-
*
|
|
849
|
-
* The dual of \`tb.server.log\` (data out): a value sent *in* from the CLI, no \`--trust\` required.
|
|
850
|
-
* Use it to start expensive work on demand instead of on load \u2014 e.g. \`tb.onMessage(() => start())\`
|
|
851
|
-
* \u2014 so hot reloads don't re-trigger it while you edit, and an agent kicks off one run when ready.
|
|
852
|
-
*
|
|
853
|
-
* The message is the JSON-parsed value of what \`send\` was given (or the raw string if it isn't
|
|
854
|
-
* JSON; \`undefined\` for a bare \`typebulb send <file>\`). Returns an unsubscribe function. Inert in
|
|
855
|
-
* an embedded bulb (no sender) \u2014 the handler is registered but never fires.
|
|
856
|
-
*
|
|
857
|
-
* @param handler - Called with each pushed message.
|
|
858
|
-
* @returns An unsubscribe function.
|
|
859
|
-
*/
|
|
860
|
-
onMessage(handler: (message: any) => void): () => void;`,NS="\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>>;",Ga=`${Wd}
|
|
861
|
-
/**
|
|
862
|
-
* Typebulb utilities namespace.
|
|
863
|
-
* Type \`tb.\` to discover available helpers.
|
|
864
|
-
*/
|
|
865
|
-
declare const tb: {${TS}${_S}${PS}${NS}${CS}${Hd}${RS}${Vd}${OS}${Yd}
|
|
866
|
-
};
|
|
867
|
-
`,za=`${Wd}
|
|
868
|
-
/**
|
|
869
|
-
* Typebulb utilities namespace (server-side).
|
|
870
|
-
* Type \`tb.\` to discover available helpers.
|
|
871
|
-
*/
|
|
872
|
-
declare const tb: {${Hd}${Vd}${Yd}
|
|
873
|
-
};
|
|
874
|
-
`;var gt=class{constructor(e){this.store=e}async isNegative(e){let t=await Ns(()=>this.store.get(e));return!!t&&t.until>Date.now()}async recordNegative(e){let n=((await Ns(()=>this.store.get(e)))?.attempts||0)+1;await Ns(()=>this.store.set(e,{until:Date.now()+IS(n),attempts:n}))}async clearNegative(e){await Ns(()=>this.store.delete(e))}};function IS(r){return Math.min(9e5*Math.pow(2,Math.max(0,r-1)),864e5)}async function Ns(r){try{return await r()}catch{return}}import DS from"p-limit";import{resolve as zd}from"resolve.exports";var Re={maxRelativeTypeRefs:500,maxBareDeps:8,maxBareDepth:3,prefetchConcurrency:4,negativeTtlMs:1e4},Is=["index.d.ts","index.d.mts"],Qa=/\.d\.(ts|mts|cts)$/i;function Ls(r){return/\.d\.(ts|mts|cts)(?:[?#].*)?$/i.test(r)||/[?&]dts(?:[&#]|$)/i.test(r)}function Gd(r){return[`${r}.d.ts`,`${r}.d.mts`]}function ze(r){if(!r||r==="./"||r==="/")return[...Is];let e=r.replace(/\.(mjs|cjs|js|mts|cts|ts)$/i,""),t=Gd(e),n=e.endsWith("/")?e:`${e}/`;return t.push(...Gd(`${n}index`)),t}async function Ms(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(LS(a.status)&&s<e)continue;return a}catch{if(s<e)continue;return}finally{clearTimeout(o)}}}function LS(r){return r===408||r===429||r>=500&&r<600}var $s=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)||Ls(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 N({name:e,version:t})),s=await Ms(n);if(!s?.ok)return;let i;try{i=await s.json()}catch{return}if(i)return{pkg:i,baseDir:this.cdnClient.baseDir(new N({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){if(e.kind==="types"){let s=mt(e.path);if(!s||s==="/"||s===".")return this.tryUntilSuccess([...Is],t);if(!Qa.test(s)){let i=await this.tryUntilSuccess(ze(s),t);if(i)return i}return t(s)}let n=ze(e.path);return this.tryUntilSuccess([...Is,...n],t)}toResolutionResult(e){return{kind:Qa.test(e)?"types":"probe",path:e}}resolveExportsPath(e,t){let n=t||".",s=e;try{let i=this.extractPathFromResult(zd(s,n,{conditions:["types"]}));if(i)return i}catch{}try{return this.extractPathFromResult(zd(s,n,{browser:!0,conditions:["import","default","module","browser","node"]}))}catch{return}}async resolve(e){try{let t=N.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 N(i).format(),a=new N({...i,subpath:t.subpath}).format(),c=u=>this.fetchCandidateFrom(s,t.name,u);if(t.subpath){let u=Ka(t.subpath),f=this.resolveExportsPath(n,u);if(f){let y=await this.resolveFromSelected(this.toResolutionResult(f),c);if(y)return{...y,resolvedPkg:a}}let p=await this.tryUntilSuccess(ze(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=mt(n),i=new URL(s,e).toString(),o=await this.tryUrls([i]);return o?{dts:o.dts,url:o.url,resolvedPkg:t}:void 0}};import{gunzipSync as MS}from"fflate";var Ds=class{async fetchAndExtract(e,t){let n=this.getTarballUrl(e,t),s=await Ms(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=MS(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 y=n.slice(i,i+f);t.set(this.normalizeTarPath(l),s.decode(y))}i+=Math.ceil(f/512)*512}}catch{}return t}};var Bs=class{constructor(e,t,n=new Ds){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=ht.majorOf(n),o=e.filter(a=>ht.majorOf(a)===i);if(o.length)return o.sort((a,c)=>ht.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=ze(e);return t!==e&&n.push(`${e}.d.ts`,`${e}/index.d.ts`),n}async fetchFromVersionedRoot(e,t){let n=new N(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 N(t).format():t.name}}}async resolve(e){let t=N.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 js=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(`
|
|
875
|
-
`).filter(s=>{let i=s.trimStart();return!(i.startsWith("*")||i.startsWith("//")||i.startsWith("/*"))}).join(`
|
|
876
|
-
`),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://"))}};var Qd="file:///node_modules",Fs=class{constructor(){this.epoch=0}bumpEpoch(){this.epoch+=1}epochDir(){return`__tsepoch_${this.epoch}`}pathForMain(e){return`${Qd}/${this.epochDir()}/${e}/index.d.ts`}pathFor(e,t){let n=mt(t);return`${Qd}/${this.epochDir()}/${e}/${n}`}};import{LRUCache as $S}from"lru-cache";function Xd(r){let e=new $S({ttl:Re.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 fetch(s,{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 an=class{constructor(e){this.inFlight=new Map,this.scanner=new js,this.cache=e.cache,this.cdnClient=e.cdnClient,this.versionResolver=e.versionResolver,this.packageService=e.packageService,this.fetchDts=Xd(e.cache),this.typescriptProvider=new $s(this.fetchDts,e.cdnClient),this.definitelyTypedProvider=new Bs(e.cdnClient,e.cache),this.virtualFs=new Fs}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 N(n).subpath===new N(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>Re.maxRelativeTypeRefs)))try{let a=new URL(t),c=new URL("./",a);o??(o=this.extractPackageRootUrl(a));let l=this.scanner.collectRelativeTypeRefs(e).slice(0,Re.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=Ls(c)?[c]:ze(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 y=this.toVirtualPath(n,new URL(p.url),s);this.pushFileIfNew(i,y,p.dts),await this.expandRelativeRefs(p.dts,p.url,s,i,o,n);return}}}catch{}}isDifferentPackage(e,t){return e===t?!1:new N(e).name!==new N(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,Re.maxBareDeps).filter(l=>this.isDifferentPackage(l,t));if(!o.length)return;let a=new Set([t]),c=DS(Re.prefetchConcurrency);await Promise.all(o.map(l=>c(()=>this.prefetchBareDepsRecursive(l,n,s,Re.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,Re.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 N(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 N(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 y=f.map(T=>T.content).join(`
|
|
877
|
-
`);await this.prefetchBareDeps(y,l,f,p,s);let m=c.format(),b=e===m?[e]:[e,m],E=b.some(T=>this.ambientlyDeclares(i,T));return E?this.markFileAmbient(f,d):p.push(...b.map(T=>({module:T,path:d}))),{pkg:e,mainPath:d,files:f,shims:p,ambient:E}}};import*as Xe from"fs/promises";import*as Ce from"path";import*as tp from"os";import*as Xa from"fs/promises";import*as Zd from"crypto";function fe(r){return Zd.createHash("sha1").update(r).digest("hex")}async function _e(r){try{return JSON.parse(await Xa.readFile(r,"utf8"))}catch{return}}async function qs(r){try{return await Xa.readFile(r,"utf8")}catch{return}}var ep=1,Qe=Ce.join(tp.homedir(),".typebulb","cache"),cn=Ce.join(Qe,"packages"),ln=Ce.join(Qe,"proxy"),Us=Ce.join(Qe,"dts"),BS=Ce.join(Qe,"emit"),Za;function U(){return Za||(Za=jS()),Za}function Js(r,e){return Ce.join(BS,fe(r),e)}async function jS(){await Xe.mkdir(Qe,{recursive:!0});let r=Ce.join(Qe,"version.json");if((await _e(r))?.version===ep)return;let t=await Xe.readdir(Qe).catch(()=>[]);await Promise.all(t.map(n=>Xe.rm(Ce.join(Qe,n),{recursive:!0,force:!0}))),await Xe.writeFile(r,JSON.stringify({version:ep})+`
|
|
878
|
-
`,"utf8")}import*as Ze from"fs/promises";import*as rp from"path";async function oe(r,e){await Ze.mkdir(rp.dirname(r),{recursive:!0});let t=`${r}.tmp-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;await Ze.writeFile(t,e,"utf8"),await Ze.rename(t,r).catch(async n=>{throw await Ze.rm(t,{force:!0}).catch(()=>{}),n})}var Qt=class{constructor(e){this.filePath=e}mem;loadPromise;load(){return this.mem?Promise.resolve(this.mem):(this.loadPromise||(this.loadPromise=_e(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 oe(this.filePath,JSON.stringify(Object.fromEntries(e)))}};var ec=de.join(cn,"indexes"),np=de.join(cn,"pinned"),FS=de.join(cn,"meta"),qS=de.join(cn,"negative.json"),Ws=class{pinnedMem=new Map;indexMem=new Map;metaMem=new Map;negativeCache=new gt(new Qt(qS));async getPinnedExact(e,t){let n=`${e}@${t}`;if(this.pinnedMem.has(n))return this.pinnedMem.get(n);await U();let s=await qs(de.join(np,fe(n)+".txt"));return this.pinnedMem.set(n,s),s}async setPinnedExact(e,t,n){let s=`${e}@${t}`;this.pinnedMem.set(s,n),await U(),await oe(de.join(np,fe(s)+".txt"),n)}async getIndex(e){if(this.indexMem.has(e))return this.indexMem.get(e);await U();let t=await _e(de.join(ec,Ks(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 U(),await oe(de.join(ec,Ks(e)+".json"),JSON.stringify(s))}async invalidateVersionsCache(e){this.indexMem.delete(e),await ip.rm(de.join(ec,Ks(e)+".json"),{force:!0})}async isNegative(e){return await U(),this.negativeCache.isNegative(e)}async recordNegative(e){await U(),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 U();let s=await _e(sp(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 U(),await oe(sp(e,t),JSON.stringify(o))}};function sp(r,e){return de.join(FS,Ks(r),encodeURIComponent(e)+".json")}function Ks(r){return r.replace(/\//g,"__")}var op={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 US=new Ws,{packageService:Hs,versionResolver:ap,cdnClient:cp,peerResolver:NR}=Jd(US,op);var lp=`
|
|
672
|
+
`)}function Bd(r,e){let t=en(r,{target:"client",dependencies:e}).filter(n=>n.type==="UNDECLARED_IMPORT");if(t.length)throw new Error(`Lint failed:
|
|
673
|
+
${TS(t)}`)}var Ge="https://esm.sh",tn="https://cdn.jsdelivr.net/npm/",Ua="https://data.jsdelivr.com/v1/package/npm/";function jd(r){let e=(r||"").replace(/^\/+/,"").replace(/\/+$/,"");return e?e.split("/"):[]}var N=class r{constructor(e,t,n){let s=typeof e=="string"?r.parse(e):e;this.name=s.name,this.version=Gt(t??s.version),this.subpath=Gt(n??s.subpath)}static parse(e){let t=jd(e||"");if(!t.length)return new r({name:""});if(t[0].startsWith("@")){let s=t[0],[i,o]=Fd(t[1]??""),a=Gt(t.slice(2).join("/"));return new r({name:`${s}/${i}`,version:o,subpath:a})}else{let[s,i]=Fd(t[0]),o=Gt(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(Ge).host,s=new URL(tn).host;if(t.host===n){let i=jd(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:Gt(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://")}},Gt=r=>r&&r.length?r:void 0,Fd=r=>{let e=r.indexOf("@");return e<0?[r,void 0]:[r.slice(0,e),Gt(r.slice(e+1))]};async function se(r){try{return await r()}catch{return}}function mt(r){let e=r||"";return e.startsWith("./")?e.slice(2):e.replace(/^\/+/,"")}function Ja(r){return r.startsWith("./")?r:`./${r}`}var rn=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 N(e):e;return`${tn}${t.name}${t.version?`@${t.version}`:""}/`}file(e,t){return new URL(mt(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(",")),`${Ge}/${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),`${Ge}/${e}`]);return this.pinCache.set(e,{value:s,ts:t}),s}async tryResolveFromUrls(e){for(let t of e){let n=await se(()=>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 se(()=>this.http.getJson(`${Ua}${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=N.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 N(`${e}@${t}`)),i=await se(()=>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 qd=r=>r.startsWith("@types/"),nn=r=>Object.keys(r?.peerDependencies||{}).filter(e=>!qd(e)),Ka=r=>Object.keys(r?.dependencies||{}).filter(e=>!qd(e)),PS=r=>nn(r).filter(e=>!r?.peerDependenciesMeta?.[e]?.optional),sn=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 PS(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=>nn(i.meta))),n=new Map;for(let i of e)for(let o of Ka(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:nn(i.meta).length>0,isSharedDep:s.has(i.name)}]))}};var on=class{constructor(e,t,n){this.cache=e,this.cdn=t,this.semver=n}async learnExactVersion(e){let t=await se(()=>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 se(()=>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 se(()=>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 N(e),s=n.root(),i=t[s],o=i?await se(()=>this.resolveExactForRoot(s,i)):void 0;return{effectivePackage:o?n.withVersion(o).format():e,root:s,range:i,pinned:o}}};import{init as OS,parse as RS}from"es-module-lexer";var zt=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))N.isBare(s[1])&&t.add(s[1])}return Array.from(t)}async extractImports(e){let t=new Set,n=s=>{N.isBare(s)&&t.add(s)};try{await OS;let[s]=RS(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(N.rootOf(u))),i=[...new Set(s.map(N.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 y=s.get(N.rootOf(p));return new N(p).withVersion(y.version).format()},o=new Set([...n.entries()].filter(([,p])=>p.isPeerRoot||p.isSharedDep).map(([p])=>p)),a=new Set(e.filter(p=>p!==N.rootOf(p)).map(N.rootOf)),c=[],l=new Set,d=new Set(e.filter(p=>p===N.rootOf(p))),u=new Set;for(let p of e){let y=N.rootOf(p),m=s.get(y),{isPeerRoot:b,hasPeers:x,isSharedDep:A}=n.get(y),g=a.has(y),w=p!==y,E=!(b||A)&&(g||!x),T=this.singletonDepsOf(m,o),P=w&&d.has(y);P&&u.add(y);let D=P?[...T,y]:T.length?T:void 0;c.push([p,this.cdn.buildEsmUrl(i(p),{bundle:E,external:D})]),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}/`,`${Ge}/${i(p)}/`]));return c}singletonDepsOf(e,t){return[...new Set([...nn(e.meta),...Ka(e.meta)])].filter(n=>t.has(n))}};zt.importPatterns=[/\bimport\s+(?:[^'";]*?from\s*)?['"]([^'"]+)['"]/g,/\bexport\s+[^'";]*?from\s*['"]([^'"]+)['"]/g];import{gt as Ud,satisfies as _S,maxSatisfying as Jd,major as CS,valid as NS}from"semver";var Ns=class{cmp(e,t){return e===t?0:Ud(e,t)?1:Ud(t,e)?-1:0}satisfies(e,t){return!e||!e.trim()?!0:!!_S(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=Jd(e,n,{includePrerelease:!1});if(a)return a}return Jd(e,n,{includePrerelease:!0})??void 0}majorOf(e){return CS(e)}isExactVersion(e){return NS(e)!==null}},ht=new Ns;var gt=class{constructor(e){this.store=e}async isNegative(e){let t=await se(()=>this.store.get(e));return!!t&&t.until>Date.now()}async recordNegative(e){let n=((await se(()=>this.store.get(e)))?.attempts||0)+1;await se(()=>this.store.set(e,{until:Date.now()+IS(n),attempts:n}))}async clearNegative(e){await se(()=>this.store.delete(e))}};function IS(r){return Math.min(9e5*Math.pow(2,Math.max(0,r-1)),864e5)}function Kd(r,e){let t=new rn(r,e),n=new sn(t),s=new on(r,t,ht);return{packageService:new zt(s,t,n),versionResolver:s,cdnClient:t,peerResolver:n}}import*as Qd from"fs/promises";import*as pe from"path";import*as Qe from"fs/promises";import*as Ce from"path";import*as Vd from"os";import*as Wa from"fs/promises";import*as Wd from"crypto";function de(r){return Wd.createHash("sha1").update(r).digest("hex")}async function _e(r){try{return JSON.parse(await Wa.readFile(r,"utf8"))}catch{return}}async function Is(r){try{return await Wa.readFile(r,"utf8")}catch{return}}var Hd=1,ze=Ce.join(Vd.homedir(),".typebulb","cache"),an=Ce.join(ze,"packages"),cn=Ce.join(ze,"proxy"),Ls=Ce.join(ze,"dts"),LS=Ce.join(ze,"emit"),Ha;function U(){return Ha||(Ha=MS()),Ha}function Ms(r,e){return Ce.join(LS,de(r),e)}async function MS(){await Qe.mkdir(ze,{recursive:!0});let r=Ce.join(ze,"version.json");if((await _e(r))?.version===Hd)return;let t=await Qe.readdir(ze).catch(()=>[]);await Promise.all(t.map(n=>Qe.rm(Ce.join(ze,n),{recursive:!0,force:!0}))),await Qe.writeFile(r,JSON.stringify({version:Hd})+`
|
|
674
|
+
`,"utf8")}import*as Xe from"fs/promises";import*as Yd from"path";async function ae(r,e){await Xe.mkdir(Yd.dirname(r),{recursive:!0});let t=`${r}.tmp-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;await Xe.writeFile(t,e,"utf8"),await Xe.rename(t,r).catch(async n=>{throw await Xe.rm(t,{force:!0}).catch(()=>{}),n})}var Qt=class{constructor(e){this.filePath=e}mem;loadPromise;load(){return this.mem?Promise.resolve(this.mem):(this.loadPromise||(this.loadPromise=_e(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 ae(this.filePath,JSON.stringify(Object.fromEntries(e)))}};var Va=pe.join(an,"indexes"),Gd=pe.join(an,"pinned"),$S=pe.join(an,"meta"),DS=pe.join(an,"negative.json"),Ds=class{pinnedMem=new Map;indexMem=new Map;metaMem=new Map;negativeCache=new gt(new Qt(DS));async getPinnedExact(e,t){let n=`${e}@${t}`;if(this.pinnedMem.has(n))return this.pinnedMem.get(n);await U();let s=await Is(pe.join(Gd,de(n)+".txt"));return this.pinnedMem.set(n,s),s}async setPinnedExact(e,t,n){let s=`${e}@${t}`;this.pinnedMem.set(s,n),await U(),await ae(pe.join(Gd,de(s)+".txt"),n)}async getIndex(e){if(this.indexMem.has(e))return this.indexMem.get(e);await U();let t=await _e(pe.join(Va,$s(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 U(),await ae(pe.join(Va,$s(e)+".json"),JSON.stringify(s))}async invalidateVersionsCache(e){this.indexMem.delete(e),await Qd.rm(pe.join(Va,$s(e)+".json"),{force:!0})}async isNegative(e){return await U(),this.negativeCache.isNegative(e)}async recordNegative(e){await U(),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 U();let s=await _e(zd(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 U(),await ae(zd(e,t),JSON.stringify(o))}};function zd(r,e){return pe.join($S,$s(r),encodeURIComponent(e)+".json")}function $s(r){return r.replace(/\//g,"__")}var Xd={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 BS=new Ds,{packageService:Bs,versionResolver:Zd,cdnClient:ep,peerResolver:cR}=Kd(BS,Xd);var tp=`
|
|
879
675
|
(() => {
|
|
880
676
|
// Embedded (bulb-in-a-bulb): runs inside a sandboxed iframe with no parent
|
|
881
677
|
// bridge, so privileged tb.* (AI, fs, server RPC) can't reach a host and would
|
|
882
678
|
// otherwise fail with cryptic CORS/CSP errors. Detect it and fail clearly.
|
|
883
679
|
//
|
|
884
|
-
// The
|
|
885
|
-
//
|
|
886
|
-
//
|
|
887
|
-
// text; absent it, the nested-bulb wording applies.
|
|
680
|
+
// The host injects window.__TB_EMBED_ERR__ to override the text; absent it, the
|
|
681
|
+
// nested-bulb wording applies. (The CLI's untrusted launch is NOT this path \u2014 it's
|
|
682
|
+
// a top-level page, and its \`--trust\` message comes from the server 403.)
|
|
888
683
|
const isEmbedded = window.parent !== window;
|
|
889
684
|
const embedErr = (name) => new Error(
|
|
890
685
|
typeof window.__TB_EMBED_ERR__ === 'function'
|
|
@@ -1185,7 +980,7 @@ declare const tb: {${Hd}${Vd}${Yd}
|
|
|
1185
980
|
|
|
1186
981
|
// Theme accessor - delegates to the head-script engine (window.__tbTheme).
|
|
1187
982
|
// Get: override slot ('dark'|'light'|undefined). Set applies + persists
|
|
1188
|
-
// per-bulb; undefined clears the override.
|
|
983
|
+
// per-bulb; undefined clears the override.
|
|
1189
984
|
get theme() { return window.__tbTheme ? window.__tbTheme.get() : undefined; },
|
|
1190
985
|
set theme(v) { if (window.__tbTheme) window.__tbTheme.set(v); }
|
|
1191
986
|
});
|
|
@@ -1212,11 +1007,11 @@ declare const tb: {${Hd}${Vd}${Yd}
|
|
|
1212
1007
|
};
|
|
1213
1008
|
}
|
|
1214
1009
|
})();
|
|
1215
|
-
`;var Xt=r=>r.replace(/<\/script/gi,"<\\/script");function
|
|
1010
|
+
`;var Xt=r=>r.replace(/<\/script/gi,"<\\/script");function js(r){return r.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}var Fs=` *, *::before, *::after { box-sizing: border-box; }
|
|
1216
1011
|
canvas { max-width: 100%; }
|
|
1217
1012
|
body { margin: 0; display: flow-root; font-family: system-ui, -apple-system, sans-serif; }
|
|
1218
1013
|
html[data-theme="dark"] { color-scheme: dark; }
|
|
1219
|
-
html[data-theme="light"] { color-scheme: light; }`;function
|
|
1014
|
+
html[data-theme="light"] { color-scheme: light; }`;function qs(r,e){return` <script>
|
|
1220
1015
|
(function() {
|
|
1221
1016
|
try {
|
|
1222
1017
|
var KEY = ${Xt(JSON.stringify("tb-theme:"+r))};
|
|
@@ -1236,11 +1031,11 @@ declare const tb: {${Hd}${Vd}${Yd}
|
|
|
1236
1031
|
apply(v);
|
|
1237
1032
|
} else {
|
|
1238
1033
|
try { localStorage.removeItem(KEY); } catch (e) {}
|
|
1239
|
-
apply(os());
|
|
1034
|
+
apply(FORCED || os());
|
|
1240
1035
|
}
|
|
1241
1036
|
};
|
|
1242
1037
|
apply(effective());
|
|
1243
|
-
var onOsChange = function() { if (!stored()) apply(os()); };
|
|
1038
|
+
var onOsChange = function() { if (!stored() && !FORCED) apply(os()); };
|
|
1244
1039
|
mq.addEventListener ? mq.addEventListener('change', onOsChange) : mq.addListener(onOsChange);
|
|
1245
1040
|
window.__tbTheme = { get: stored, set: set, effective: effective };
|
|
1246
1041
|
window.addEventListener('keydown', function(e) {
|
|
@@ -1251,19 +1046,19 @@ declare const tb: {${Hd}${Vd}${Yd}
|
|
|
1251
1046
|
});
|
|
1252
1047
|
} catch (e) {}
|
|
1253
1048
|
})();
|
|
1254
|
-
</script>`}function
|
|
1255
|
-
html, body { height: 100%; }`,f={imports:
|
|
1049
|
+
</script>`}function rp(r){let{name:e,code:t,css:n,html:s,data:i,insight:o,importMap:a,theme:c,embedded:l}=r,d=s.trim()||'<div id="app"></div>',u=l?"":`
|
|
1050
|
+
html, body { height: 100%; }`,f={imports:FS(a.imports)};return`<!DOCTYPE html>
|
|
1256
1051
|
<html>
|
|
1257
1052
|
<head>
|
|
1258
1053
|
<meta charset="utf-8">
|
|
1259
1054
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
1260
|
-
<title>${
|
|
1261
|
-
${
|
|
1055
|
+
<title>${js(e)} - typebulb</title>
|
|
1056
|
+
${qs(e,c)}
|
|
1262
1057
|
<script type="importmap">
|
|
1263
1058
|
${JSON.stringify(f,null,2)}
|
|
1264
1059
|
</script>
|
|
1265
1060
|
<style>
|
|
1266
|
-
${
|
|
1061
|
+
${Fs}${u}
|
|
1267
1062
|
</style>
|
|
1268
1063
|
<style>
|
|
1269
1064
|
${n}
|
|
@@ -1276,17 +1071,17 @@ ${i.length>0?`<script>window.__TB_DATA__ = ${Xt(JSON.stringify(i))};</script>`:"
|
|
|
1276
1071
|
${o?`<script>window.__TB_INSIGHT__ = ${Xt(JSON.stringify(o))};</script>`:""}
|
|
1277
1072
|
|
|
1278
1073
|
<script>
|
|
1279
|
-
${
|
|
1074
|
+
${tp}
|
|
1280
1075
|
</script>
|
|
1281
1076
|
|
|
1282
|
-
${
|
|
1077
|
+
${jS}
|
|
1283
1078
|
|
|
1284
1079
|
<script type="module">
|
|
1285
1080
|
${Xt(t)}
|
|
1286
1081
|
globalThis.__tbEntryRan = true; /* load-failure backstop \u2014 see embedProtocol */
|
|
1287
1082
|
</script>
|
|
1288
1083
|
</body>
|
|
1289
|
-
</html>`}var
|
|
1084
|
+
</html>`}var jS=`<script>
|
|
1290
1085
|
(function () {
|
|
1291
1086
|
var framed = window.parent !== window;
|
|
1292
1087
|
var post = function (m) { try { parent.postMessage(m, '*'); } catch (e) {} }; /* framed only */
|
|
@@ -1382,32 +1177,239 @@ globalThis.__tbEntryRan = true; /* load-failure backstop \u2014 see embedProtoco
|
|
|
1382
1177
|
}
|
|
1383
1178
|
});
|
|
1384
1179
|
})();
|
|
1385
|
-
</script>`;function
|
|
1386
|
-
|
|
1387
|
-
|
|
1388
|
-
|
|
1180
|
+
</script>`;function FS(r){let e={};for(let[t,n]of Object.entries(r))e[t]=n.startsWith("https://")?"/proxy/"+n:n;return e}import*as Js from"fs/promises";import*as Us from"path";import{existsSync as np,readFileSync as qS}from"fs";import{execFile as US}from"child_process";import{promisify as JS}from"util";import{satisfies as KS}from"semver";var WS=JS(US),HS=/^(@[a-z0-9._-]+\/)?[a-z0-9._-]+(@[a-zA-Z0-9.^~*x-]+)?$/i;async function Ks(r,e,t,n){let i=r.map(l=>VS(l,t)).filter(l=>!YS(l,e));if(i.length===0)return;let o=i.filter(l=>!HS.test(l));if(o.length)throw new Error(`Refusing to install npm spec(s) with unsupported characters: ${o.join(", ")}
|
|
1181
|
+
Use a plain name with an exact / caret / tilde range (e.g. three@^0.160.0).`);await Js.mkdir(e,{recursive:!0});let a=Us.join(e,"package.json");np(a)||await Js.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 WS("npm",["install",...c,...i],{cwd:e,shell:!0})}function VS(r,e){if(!e||N.parse(r).version)return r;let t=e[r];return t?`${r}@${t}`:r}function YS(r,e){let{name:t,version:n}=N.parse(r),s=Us.join(e,"node_modules",t);if(!np(s))return!1;if(!n)return!0;try{let i=JSON.parse(qS(Us.join(s,"package.json"),"utf-8")).version;return KS(i,n)}catch{return!1}}function Ws(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(N.rootOf(s))}return[...e]}rr();ei();wt();async function dp(r){let e=vt(r.provider,r.model);if(typeof e=="string")throw new Error(e);let t=await St(e,r);if(!t.ok){let n=await ln(t,e.protocol);throw new Error(n.message)}return{response:t,protocol:e.protocol}}async function sk(r){let{response:e,protocol:t}=await dp(r);return{text:await bt(e,t)}}async function*ik(r){let{response:e,protocol:t}=await dp(r);yield*tr(e,t)}function pp(){let r=Object.assign(sk,{stream:ik});globalThis.tb=Object.freeze({ai:r,models:()=>Ne(),hasOwnKeys:Zs,mode:"local"})}async function mp(r){let t=(await Ze.readdir(r)).find(n=>n.endsWith(".bulb.md"));return t?Ie.join(r,t):null}async function ge(r){let e=await Ze.readFile(r,"utf-8"),t=Pe(e);if(!t)throw new Error("Invalid .bulb.md file format");let n=Yt(t);return{bulb:n,config:Ll(n.config),warnings:Rl(e)}}function sc(r){let e=Ie.basename(r).replace(/\.bulb\.md$/i,"");return Ie.join(Ie.dirname(r),".typebulb",`${e}.server.mjs`)}async function dn(r,e,t,n){let s=qa(r,{serverOnly:!0});if(s.error)throw new Error(`Server compilation error: ${s.error}`);let i=s.code;t&&(i=await Sl(i,t));let o=Ie.join(Ie.dirname(e),".typebulb");await Ze.mkdir(o,{recursive:!0});let a=Ws(i);a.length>0&&await Ks(a,o,n);let c=sc(e);return await Ze.writeFile(c,i,"utf-8"),pp(),await import(`${ok(c).href}?t=${Date.now()}`)}async function ic(r,e,t,n){let{bulb:s,config:i}=await ge(r),o=Ld(s.data);Bd(s.code,i.dependencies??{});let a=qa(s.code,{jsxImportSource:i.ts?.jsxImportSource});a.error&&console.error("Compilation error:",a.error);let{importMap:c}=await Bs.buildImportMap(a.code,i.dependencies??{},n?new Set([n.name]):void 0);n&&(c.imports[n.name]=n.entryUrl);let l=rp({name:s.name,code:a.code,css:s.css,html:s.html,data:o,insight:s.insight,importMap:c,watch:e}),d=null;return s.server&&t&&(d=await dn(s.server,r,n,i.dependencies)),{html:l,bulb:s,serverExports:d}}Zr();pn();ai();_c();var Ni={claude:{adapter:()=>new ar,server:()=>Promise.resolve().then(()=>(qm(),Fm))},pi:{adapter:()=>new dr,server:()=>Promise.resolve().then(()=>(Qm(),zm))}};function Xm(r){return r in Ni}function gr(){return Object.keys(Ni)}function Zm(){return Object.fromEntries(Object.entries(Ni).map(([r,e])=>[r,e.adapter]))}function eh(r){return Ni[r].server()}import*as nt from"path";import{spawn as VE,execSync as YE}from"child_process";import{createRequire as GE}from"module";import{existsSync as zE}from"fs";import*as ee from"fs/promises";import*as X from"path";var Uc=[{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"}],Jc=[{name:"dom"},{name:"dom.iterable"},{name:"dom.asynciterable"}];function Kc(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 kE=`
|
|
1182
|
+
/**
|
|
1183
|
+
* Get raw data chunk from the Data tab.
|
|
1184
|
+
* @param index - Chunk index (0-based). Separate chunks with 2 blank lines.
|
|
1185
|
+
*/
|
|
1186
|
+
data(index: number): string;
|
|
1187
|
+
/**
|
|
1188
|
+
* Get data chunk parsed as JSON (handles JSON-ish with unquoted keys).
|
|
1189
|
+
* @param index - Chunk index (0-based)
|
|
1190
|
+
* @throws If chunk is not valid JSON/JSON-ish
|
|
1191
|
+
*/
|
|
1192
|
+
json<T = unknown>(index: number): T;`,xE=`
|
|
1193
|
+
/**
|
|
1194
|
+
* Get the insight data produced by the inference layer.
|
|
1195
|
+
*
|
|
1196
|
+
* Returns the parsed JSON from insight.json, populated by the inference LLM.
|
|
1197
|
+
* Use a type parameter to get typed access to the insight data.
|
|
1198
|
+
*
|
|
1199
|
+
* @returns The parsed insight JSON, or undefined if no insight is available
|
|
1200
|
+
*/
|
|
1201
|
+
insight<T = unknown>(): T | undefined;`,th=`options: {
|
|
1202
|
+
messages: Array<{ role: "user" | "assistant"; content: string }>;
|
|
1203
|
+
system?: string;
|
|
1204
|
+
/** 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. */
|
|
1205
|
+
effort?: 0 | 1 | 2 | 3;
|
|
1206
|
+
provider?: string;
|
|
1207
|
+
model?: string;
|
|
1208
|
+
/** Enable/disable web search. Default: on for BYOK, always off for free model. */
|
|
1209
|
+
webSearch?: boolean;
|
|
1210
|
+
/** Abort the request. On abort the promise rejects / the stream ends. */
|
|
1211
|
+
signal?: AbortSignal;
|
|
1212
|
+
}`,rh=`
|
|
1213
|
+
/** A single streamed delta from \`tb.ai.stream()\`. Discriminated by \`kind\`. */
|
|
1214
|
+
type AiChunk =
|
|
1215
|
+
| { kind: "text"; text: string }
|
|
1216
|
+
| { kind: "reasoning"; text: string };
|
|
1217
|
+
`,nh=`
|
|
1218
|
+
/**
|
|
1219
|
+
* General-purpose AI call. \`tb.ai(opts)\` resolves with the full text; \`tb.ai.stream(opts)\`
|
|
1220
|
+
* returns an async iterable of {@link AiChunk} deltas you consume with \`for await\`.
|
|
1221
|
+
*
|
|
1222
|
+
* @returns Promise resolving to { text: string }
|
|
1223
|
+
* @throws On rate limit, network error, or provider error
|
|
1224
|
+
*/
|
|
1225
|
+
ai: {
|
|
1226
|
+
(${th}): Promise<{ text: string }>;
|
|
1227
|
+
/**
|
|
1228
|
+
* Streaming counterpart of \`tb.ai()\`. Yields \`{ kind: "text" | "reasoning", text }\` deltas
|
|
1229
|
+
* as they arrive; break the loop (or abort \`signal\`) to cancel and stop the upstream.
|
|
1230
|
+
*
|
|
1231
|
+
* \`kind: "reasoning"\` deltas only arrive when you pass \`effort: 1-3\` AND use a
|
|
1232
|
+
* thinking-capable model; otherwise the stream is \`text\`-only.
|
|
1233
|
+
*
|
|
1234
|
+
* @example
|
|
1235
|
+
* let answer = "";
|
|
1236
|
+
* for await (const c of tb.ai.stream({ messages })) {
|
|
1237
|
+
* if (c.kind === "text") answer += c.text;
|
|
1238
|
+
* }
|
|
1239
|
+
*/
|
|
1240
|
+
stream(${th}): AsyncIterable<AiChunk>;
|
|
1241
|
+
};`,sh=`
|
|
1242
|
+
/**
|
|
1243
|
+
* Returns AI models available to the current user.
|
|
1244
|
+
* Models are filtered by the user's configured API keys.
|
|
1245
|
+
* If no keys are configured, returns only the courtesy model.
|
|
1246
|
+
*/
|
|
1247
|
+
models(): Promise<Array<{
|
|
1248
|
+
/** Provider protocol: "anthropic", "openai", "gemini", "openrouter" */
|
|
1249
|
+
provider: string;
|
|
1250
|
+
/** Model identifier, e.g. "claude-sonnet-4-6" */
|
|
1251
|
+
name: string;
|
|
1252
|
+
/** Human-readable display name, e.g. "Sonnet 4.6" */
|
|
1253
|
+
friendlyName: string;
|
|
1254
|
+
/** Provider display name, e.g. "Anthropic" */
|
|
1255
|
+
providerName: string;
|
|
1256
|
+
}>>;
|
|
1257
|
+
/**
|
|
1258
|
+
* Whether the user's own AI keys back \`tb.ai\`. False means only the
|
|
1259
|
+
* quota-limited courtesy model is available (or no AI at all) \u2014 a bulb
|
|
1260
|
+
* making many AI calls should check this and show a "use your own keys"
|
|
1261
|
+
* notice instead of running.
|
|
1262
|
+
*/
|
|
1263
|
+
hasOwnKeys(): Promise<boolean>;`,EE="\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;",ih=`
|
|
1264
|
+
/**
|
|
1265
|
+
* The mode this bulb is running in.
|
|
1266
|
+
*
|
|
1267
|
+
* - \`'local'\` \u2014 Running via the typebulb CLI
|
|
1268
|
+
* - \`'editor'\` \u2014 Running in the typebulb.com editor
|
|
1269
|
+
* - \`'published'\` \u2014 Running as a published/standalone bulb on typebulb.com
|
|
1270
|
+
* - \`'embedded'\` \u2014 Running as a bulb embedded inside another bulb (sandboxed,
|
|
1271
|
+
* client-only: AI, filesystem, and server RPC are unavailable)
|
|
1272
|
+
*/
|
|
1273
|
+
mode: 'local' | 'editor' | 'published' | 'embedded';`,AE=`
|
|
1274
|
+
/**
|
|
1275
|
+
* Local filesystem access (CLI only).
|
|
1276
|
+
*
|
|
1277
|
+
* Paths are resolved relative to the current working directory (where the CLI
|
|
1278
|
+
* was launched), consistent with the .env cascade \u2014 not the bulb file's folder.
|
|
1279
|
+
* Throws in editor/published mode.
|
|
1280
|
+
*/
|
|
1281
|
+
fs: {
|
|
1282
|
+
/** Read a file as UTF-8 text. Throws if the file is not valid UTF-8 \u2014 use readBytes for binary. */
|
|
1283
|
+
read(path: string): Promise<string>;
|
|
1284
|
+
/** Read a file as raw bytes. */
|
|
1285
|
+
readBytes(path: string): Promise<Uint8Array>;
|
|
1286
|
+
/** Write text or raw bytes to a file. Creates parent directories if needed. */
|
|
1287
|
+
write(path: string, content: string | Uint8Array): Promise<boolean>;
|
|
1288
|
+
};`,TE=`
|
|
1289
|
+
/**
|
|
1290
|
+
* Async value inspector for tensor-like objects.
|
|
1291
|
+
*
|
|
1292
|
+
* Materializes lazy values (like GPU tensors) and logs them with metadata.
|
|
1293
|
+
* Handles objects with \`.js()\`, \`.data()\`, \`.array()\`, \`.arraySync()\`, etc.
|
|
1294
|
+
*
|
|
1295
|
+
* @remarks
|
|
1296
|
+
* - Always use \`await\` - materialization may be async (GPU\u2192CPU readback)
|
|
1297
|
+
* - Large values are truncated (max 1000 elements)
|
|
1298
|
+
* - Promises are logged as \`[Promise]\` (not awaited - could hang)
|
|
1299
|
+
*/
|
|
1300
|
+
dump(...args: any[]): Promise<void>;
|
|
1301
|
+
/**
|
|
1302
|
+
* Trigger inference to generate new insight data.
|
|
1303
|
+
*
|
|
1304
|
+
* Opens a confirmation modal showing the data to be analyzed, then streams
|
|
1305
|
+
* the inference result. On success, updates the insight so subsequent
|
|
1306
|
+
* \`tb.insight()\` calls return the new value.
|
|
1307
|
+
*
|
|
1308
|
+
* @param opts - Options for inference
|
|
1309
|
+
* @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.
|
|
1310
|
+
* @returns Promise that resolves with the parsed insight JSON
|
|
1311
|
+
* @throws If inference is already in progress, or on network/parse/rate limit errors
|
|
1312
|
+
*/
|
|
1313
|
+
infer<T = unknown>(opts?: { data?: string | string[] }): Promise<T>;
|
|
1314
|
+
/**
|
|
1315
|
+
* Get the current inference state.
|
|
1316
|
+
*
|
|
1317
|
+
* @returns 'idle' | 'running' | 'complete' | 'error'
|
|
1318
|
+
*/
|
|
1319
|
+
inferenceState(): 'idle' | 'running' | 'complete' | 'error';
|
|
1320
|
+
/**
|
|
1321
|
+
* Set a data chunk for the next inference call.
|
|
1322
|
+
*
|
|
1323
|
+
* Use this to programmatically set data that will be sent when \`tb.infer()\` is called
|
|
1324
|
+
* without the \`data\` option.
|
|
1325
|
+
*
|
|
1326
|
+
* @param index - The chunk index (0-based)
|
|
1327
|
+
* @param content - The content for this chunk
|
|
1328
|
+
*/
|
|
1329
|
+
setData(index: number, content: string): void;
|
|
1330
|
+
/**
|
|
1331
|
+
* Proxy a CDN URL through the sandbox origin for Web Worker/WASM same-origin loading.
|
|
1332
|
+
*
|
|
1333
|
+
* In the sandbox, prepends \`/proxy/\` so the URL is served from the same origin.
|
|
1334
|
+
* Outside the sandbox (exported HTML, CLI), returns the URL unchanged.
|
|
1335
|
+
*
|
|
1336
|
+
* @param url - Full HTTPS URL to an allowlisted CDN (esm.sh, unpkg.com, cdn.jsdelivr.net, cdnjs.cloudflare.com)
|
|
1337
|
+
* @returns The proxied URL (sandbox) or the original URL (standalone/CLI)
|
|
1338
|
+
*/
|
|
1339
|
+
proxy(url: string): string;
|
|
1340
|
+
/**
|
|
1341
|
+
* Copy text to clipboard.
|
|
1342
|
+
* Must be called synchronously within a user gesture (click/keydown).
|
|
1343
|
+
* @returns true if successful, false otherwise
|
|
1344
|
+
*/
|
|
1345
|
+
copy(text: string): Promise<boolean>;
|
|
1346
|
+
/**
|
|
1347
|
+
* Get the canonical URL of this bulb.
|
|
1348
|
+
*
|
|
1349
|
+
* Returns the parent typebulb.com URL (including path, query, and \`#tb=\` fragment),
|
|
1350
|
+
* resolving correctly from inside the cross-origin sandbox iframe.
|
|
1351
|
+
* Use this instead of \`location.href\` or \`document.referrer\`.
|
|
1352
|
+
*
|
|
1353
|
+
* @returns The full canonical URL
|
|
1354
|
+
*/
|
|
1355
|
+
url(): Promise<string>;`,PE=`
|
|
1356
|
+
/**
|
|
1357
|
+
* Subscribe to a value pushed from the terminal via \`typebulb send <file> [message]\`.
|
|
1358
|
+
*
|
|
1359
|
+
* The dual of \`tb.server.log\` (data out): a value sent *in* from the CLI, no \`--trust\` required.
|
|
1360
|
+
* Use it to start expensive work on demand instead of on load \u2014 e.g. \`tb.onMessage(() => start())\`
|
|
1361
|
+
* \u2014 so hot reloads don't re-trigger it while you edit, and an agent kicks off one run when ready.
|
|
1362
|
+
*
|
|
1363
|
+
* The message is the JSON-parsed value of what \`send\` was given (or the raw string if it isn't
|
|
1364
|
+
* JSON; \`undefined\` for a bare \`typebulb send <file>\`). Returns an unsubscribe function. Inert in
|
|
1365
|
+
* an embedded bulb (no sender) \u2014 the handler is registered but never fires.
|
|
1366
|
+
*
|
|
1367
|
+
* @param handler - Called with each pushed message.
|
|
1368
|
+
* @returns An unsubscribe function.
|
|
1369
|
+
*/
|
|
1370
|
+
onMessage(handler: (message: any) => void): () => void;`,OE="\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>>;",Wc=`${rh}
|
|
1371
|
+
/**
|
|
1372
|
+
* Typebulb utilities namespace.
|
|
1373
|
+
* Type \`tb.\` to discover available helpers.
|
|
1374
|
+
*/
|
|
1375
|
+
declare const tb: {${kE}${TE}${xE}${OE}${PE}${nh}${AE}${sh}${EE}${ih}
|
|
1376
|
+
};
|
|
1377
|
+
`,Hc=`${rh}
|
|
1378
|
+
/**
|
|
1379
|
+
* Typebulb utilities namespace (server-side).
|
|
1380
|
+
* Type \`tb.\` to discover available helpers.
|
|
1381
|
+
*/
|
|
1382
|
+
declare const tb: {${nh}${sh}${ih}
|
|
1383
|
+
};
|
|
1384
|
+
`;import NE from"p-limit";import{resolve as ah}from"resolve.exports";var $e={maxRelativeTypeRefs:500,maxBareDeps:8,maxBareDepth:3,prefetchConcurrency:4,negativeTtlMs:1e4},kn=["index.d.ts","index.d.mts"],Vc=/\.d\.(ts|mts|cts)$/i;function Ii(r){return/\.d\.(ts|mts|cts)(?:[?#].*)?$/i.test(r)||/[?&]dts(?:[&#]|$)/i.test(r)}function oh(r){return[`${r}.d.ts`,`${r}.d.mts`]}function rt(r){if(!r||r==="./"||r==="/")return[...kn];let e=r.replace(/\.(mjs|cjs|js|mts|cts|ts)$/i,""),t=oh(e),n=e.endsWith("/")?e:`${e}/`;return t.push(...oh(`${n}index`)),t}async function yr(r,{retries:e=2,timeoutMs:t=15e3,init:n}={}){for(let s=0;s<=e;s++){let i=new AbortController,o=setTimeout(()=>i.abort(),t);try{let a=await fetch(r,{...n,signal:i.signal});if(RE(a.status)&&s<e)continue;return a}catch{if(s<e)continue;return}finally{clearTimeout(o)}}}function RE(r){return r===408||r===429||r>=500&&r<600}var Li=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)||Ii(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 N({name:e,version:t})),s=await yr(n);if(!s?.ok)return;let i;try{i=await s.json()}catch{return}if(i)return{pkg:i,baseDir:this.cdnClient.baseDir(new N({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=mt(e.path);if(!o||o==="/"||o===".")return this.tryUntilSuccess([...kn],t);if(!Vc.test(o)){let a=await this.tryUntilSuccess(rt(o),t);if(a)return a}return t(o)}let s=rt(e.path),i=n?.subpath?[...s,...kn]:[...kn,...s];return this.tryUntilSuccess(i,t)}toResolutionResult(e){return{kind:Vc.test(e)?"types":"probe",path:e}}resolveExportsPath(e,t){let n=t||".",s=e;try{let i=this.extractPathFromResult(ah(s,n,{conditions:["types"]}));if(i)return i}catch{}try{return this.extractPathFromResult(ah(s,n,{browser:!0,conditions:["import","default","module","browser","node"]}))}catch{return}}async resolve(e){try{let t=N.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 N(i).format(),a=new N({...i,subpath:t.subpath}).format(),c=u=>this.fetchCandidateFrom(s,t.name,u);if(t.subpath){let u=Ja(t.subpath),f=this.resolveExportsPath(n,u);if(f){let y=await this.resolveFromSelected(this.toResolutionResult(f),c,{subpath:!0});if(y)return{...y,resolvedPkg:a}}let p=await this.tryUntilSuccess(rt(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=mt(n),i=new URL(s,e).toString(),o=await this.tryUrls([i]);return o?{dts:o.dts,url:o.url,resolvedPkg:t}:void 0}};import{gunzipSync as _E}from"fflate";var Mi=class{async fetchAndExtract(e,t){let n=this.getTarballUrl(e,t),s=await yr(n,{timeoutMs:3e4});if(!s?.ok)return new Map;let i=new Uint8Array(await s.arrayBuffer());return this.extractDtsFiles(i)}getTarballUrl(e,t){return`https://registry.npmjs.org/${e.replace("/","%2F")}/-/${e.split("/").pop()}-${t}.tgz`}normalizeTarPath(e){let t=e.replace(/^package\//,""),n=t.indexOf("/");return n>0?t.substring(n+1):t}extractDtsFiles(e){let t=new Map;try{let n=_E(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 y=n.slice(i,i+f);t.set(this.normalizeTarPath(l),s.decode(y))}i+=Math.ceil(f/512)*512}}catch{}return t}};var $i=class{constructor(e,t,n=new Mi){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=ht.majorOf(n),o=e.filter(a=>ht.majorOf(a)===i);if(o.length)return o.sort((a,c)=>ht.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=rt(e);return t!==e&&n.push(`${e}.d.ts`,`${e}/index.d.ts`),n}async fetchFromVersionedRoot(e,t){let n=new N(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 N(t).format():t.name}}}async resolve(e){let t=N.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 Di=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(`
|
|
1385
|
+
`).filter(s=>{let i=s.trimStart();return!(i.startsWith("*")||i.startsWith("//")||i.startsWith("/*"))}).join(`
|
|
1386
|
+
`),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://"))}};var ch="file:///node_modules",Bi=class{constructor(){this.epoch=0}bumpEpoch(){this.epoch+=1}epochDir(){return`__tsepoch_${this.epoch}`}pathForMain(e){return`${ch}/${this.epochDir()}/${e}/index.d.ts`}pathFor(e,t){let n=mt(t);return`${ch}/${this.epochDir()}/${e}/${n}`}};import{LRUCache as CE}from"lru-cache";function lh(r){let e=new CE({ttl:$e.negativeTtlMs,max:500}),t=new Map;return async function(s){try{if(await r.isNegative(s)||e.has(s))return;let i=await r.getCachedFile(s);if(i)return{dts:i,url:s};let o=t.get(s);if(o)return o;let a=(async()=>{let c=await yr(s,{init:{cache:"no-store"}});if(!c?.ok){c?.status===404&&(e.set(s,!0),await r.recordNegative(s));return}let l=await c.text(),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 xn=class{constructor(e){this.inFlight=new Map,this.scanner=new Di,this.cache=e.cache,this.cdnClient=e.cdnClient,this.versionResolver=e.versionResolver,this.packageService=e.packageService,this.fetchDts=lh(e.cache),this.typescriptProvider=new Li(this.fetchDts,e.cdnClient),this.definitelyTypedProvider=new $i(e.cdnClient,e.cache),this.virtualFs=new Bi}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 N(n).subpath===new N(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>$e.maxRelativeTypeRefs)))try{let a=new URL(t),c=new URL("./",a);o??(o=this.extractPackageRootUrl(a));let l=this.scanner.collectRelativeTypeRefs(e).slice(0,$e.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=Ii(c)?[c]:rt(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 y=this.toVirtualPath(n,new URL(p.url),s);this.pushFileIfNew(i,y,p.dts),await this.expandRelativeRefs(p.dts,p.url,s,i,o,n);return}}}catch{}}isDifferentPackage(e,t){return e===t?!1:new N(e).name!==new N(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,$e.maxBareDeps).filter(l=>this.isDifferentPackage(l,t));if(!o.length)return;let a=new Set([t]),c=NE($e.prefetchConcurrency);await Promise.all(o.map(l=>c(()=>this.prefetchBareDepsRecursive(l,n,s,$e.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,$e.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 N(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 N(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 y=f.map(A=>A.content).join(`
|
|
1387
|
+
`);await this.prefetchBareDeps(y,l,f,p,s);let m=c.format(),b=e===m?[e]:[e,m],x=b.some(A=>this.ambientlyDeclares(i,A));return x?this.markFileAmbient(f,d):p.push(...b.map(A=>({module:A,path:d}))),{pkg:e,mainPath:d,files:f,shims:p,ambient:x}}};import*as br from"path";var IE=br.join(Ls,"pkg"),LE=br.join(Ls,"files"),ME=br.join(Ls,"negative.json"),Fi=class{pkgMem=new Map;fileMem=new Map;negativeCache=new gt(new Qt(ME));async getCachedDts(e){if(this.pkgMem.has(e))return this.pkgMem.get(e);await U();let t=await _e(uh(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 ji(async()=>{await U(),await ae(uh(e),JSON.stringify(s))})}async getCachedFile(e){if(this.fileMem.has(e))return this.fileMem.get(e);await U();let t=await Is(fh(e));return this.fileMem.set(e,t),t}async setCachedFile(e,t){this.fileMem.set(e,t),await ji(async()=>{await U(),await ae(fh(e),t)})}isNegative(e){return this.negativeCache.isNegative(e)}async recordNegative(e){await ji(async()=>{await U(),await this.negativeCache.recordNegative(e)})}clearNegative(e){return ji(()=>this.negativeCache.clearNegative(e))}};async function ji(r){try{await r()}catch{}}function uh(r){return br.join(IE,de(r)+".json")}function fh(r){return br.join(LE,de(r)+".txt")}var Yc;function $E(){return Yc||(Yc=new xn({cache:new Fi,cdnClient:ep,packageService:Bs,versionResolver:Zd})),Yc}var dh="file:///node_modules/";async function ph(r){let e=Ms(r.emitKey,"typecheck");await U(),await ee.rm(e,{recursive:!0,force:!0}),await ee.mkdir(e,{recursive:!0});let t=FE(r.jsxImportSource,r.dependencies),n=await $E().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=qi(u.path);if(!f||o.has(f))continue;o.add(f);let p=X.join(e,"node_modules",f);await ee.mkdir(X.dirname(p),{recursive:!0}),await ee.writeFile(p,u.content,"utf8")}let a={};for(let d of i)for(let u of d.shims){let f=qi(u.path);f&&(a[u.module]=[`./node_modules/${f}`])}for(let d of i){if(d.ambient)continue;let u=qi(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=qi(u.path);f&&c.add(`node_modules/${f}`)}if(r.local){delete a[r.local.name];let d=await qE(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=DE(r.jsxImportSource,a,[...c]);return await ee.writeFile(X.join(e,"tsconfig.json"),JSON.stringify(l,null,2)+`
|
|
1388
|
+
`,"utf8"),await ee.writeFile(X.join(e,"code.tsx"),r.code,"utf8"),await ee.writeFile(X.join(e,"tb.d.ts"),Wc,"utf8"),{dir:e}}var Gc={target:"es2023",module:"esnext",moduleResolution:"bundler",strict:!0,noEmit:!0,skipLibCheck:!0,esModuleInterop:!0,allowSyntheticDefaultImports:!0,forceConsistentCasingInFileNames:!0};function DE(r,e,t=[]){return{compilerOptions:{...Gc,lib:BE([...Uc,...Jc]),jsx:"react-jsx",jsxImportSource:r??"react",paths:e},include:["code.tsx","tb.d.ts",...t]}}function BE(r){return Kc(r).map(e=>jE(e.name))}function jE(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 FE(r,e){let t=r??("react"in e?"react":void 0);return t?[`${t}/jsx-runtime`,`${t}/jsx-dev-runtime`]:[]}function qi(r){if(!r.startsWith(dh))return;let e=r.slice(dh.length),t=e.indexOf("/");if(!(t<0))return e.slice(t+1)}async function qE(r,e){if(!r.typesAbs)return;let t=X.dirname(r.typesAbs),n=X.join(e,"node_modules",r.name);for(let s of await UE(t)){let i=X.join(n,X.relative(t,s));await ee.mkdir(X.dirname(i),{recursive:!0}),await ee.copyFile(s,i)}return X.basename(r.typesAbs)}async function UE(r){let e=[];async function t(n){let s=await ee.readdir(n,{withFileTypes:!0});for(let i of s){let o=X.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 le from"fs/promises";import*as De from"path";import{existsSync as JE}from"fs";var KE="^22";async function mh(r){let e=Ms(r.emitKey,"typecheck-server");await U(),await le.rm(e,{recursive:!0,force:!0}),await le.mkdir(e,{recursive:!0});let t=De.join(r.bulbDir,".typebulb"),n=Ws(r.server).filter(o=>o!==r.local?.name);await Ks([`@types/node@${KE}`,...n],t,r.dependencies,{ignoreScripts:!0});let s=De.join(t,"node_modules"),i=De.join(e,"node_modules");return await HE(s,i),await le.writeFile(De.join(e,"server.ts"),r.server,"utf8"),await le.writeFile(De.join(e,"tb.d.ts"),Hc,"utf8"),await le.writeFile(De.join(e,"tsconfig.json"),JSON.stringify(WE(r.local),null,2)+`
|
|
1389
|
+
`,"utf8"),{dir:e}}function WE(r){let e={...Gc,lib:["ES2023"],types:["node"]};if(r?.typesAbs){let t=i=>i.replace(/\\/g,"/"),n=t(De.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 HE(r,e){if(!JE(r)){await le.mkdir(e,{recursive:!0});return}await le.rm(e,{recursive:!0,force:!0});let t=process.platform==="win32"?"junction":"dir";await le.symlink(r,e,t)}Cs();async function gh(r,e){let{bulb:t,config:n,warnings:s}=await ge(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=hh(en(t.code,{target:"client",dependencies:n.dependencies??{}}),"client")||i),t.server&&(i=hh(en(t.server,{target:"server"}),"server")||i);let o=ZE([process.cwd(),nt.dirname(r)]);if(!o){let l=nt.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 ph({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 mh({server:t.server,bulbDir:nt.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 QE(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 hh(r,e){for(let t of r)for(let n of t.message.split(`
|
|
1390
|
+
`))console.log(`${e} ${n}`);return r.length>0}function QE(r,e){return new Promise(t=>{let n=VE(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 XE=GE(import.meta.url);function ZE(r){let e=n=>{try{let s=XE.resolve("typescript/package.json",{paths:n}),i=nt.join(nt.dirname(s),"lib","tsc.js");return zE(i)?i:void 0}catch{return}},t=e(r);if(t)return t;try{let n=YE("npm root -g",{encoding:"utf8"}).trim();return e([n])}catch{return}}mi();pn();async function yh(r,e){let{bulb:t}=await ge(r),n=lr(t);if(kt(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.)")}pn();import*as En from"path";async function bh(r,e){if(!r){e||(console.error("Usage: typebulb untrust <file.bulb.md>"),process.exit(1));let n=cc();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=En.resolve(r);t.endsWith(".bulb.md")||(console.error("File must have .bulb.md extension"),process.exit(1)),ir(t,e),console.log(e?`Trusted ${En.basename(t)} \u2014 runs with fs / AI / server.ts (no --trust needed).`:`Untrusted ${En.basename(t)} \u2014 runs Restricted.`),console.log(` ${t}`)}xe();import*as kh from"readline";var An=Zm();function wh(){for(let r of Object.values(An))try{r().ensureHarnessSupport()}catch{}}function Tn(){for(let r of Object.keys(An))try{if(An[r]().detectsSelf())return r}catch{}}function vh(r){let e=gr(),t=new Map(e.filter(i=>An[i]).map(i=>[i,An[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)))}}hi();function zc(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 xh(r){let e=vh(process.cwd());if("ambiguous"in e){let t=await eA(r,e.ambiguous);return t?Sh(r,t):tA(r,e.ambiguous)}return Sh(r,e.name)}async function Sh(r,e){let t,n;try{t=await Ip(e)}catch(d){n=d instanceof Error?d.message:String(d)}let{lit:s,litLink:i,brand:o}=zc(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(ur())}`,` ${s(At())}`],c=t?[" Agent mirror 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(`
|
|
1389
1391
|
`)+`
|
|
1390
|
-
`)}async function
|
|
1392
|
+
`)}async function eA(r,e){if(!process.stdin.isTTY||!process.stdout.isTTY)return;let{lit:t,brand:n}=zc(!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(`
|
|
1391
1393
|
`)+`
|
|
1392
|
-
`);let i=
|
|
1394
|
+
`);let i=kh.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 tA(r,e){let{lit:t,brand:n}=zc(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(`
|
|
1393
1395
|
`)+`
|
|
1394
|
-
`)}import{readFileSync as
|
|
1395
|
-
`)){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
|
|
1396
|
-
`+e)}function
|
|
1396
|
+
`)}import{readFileSync as rA,existsSync as nA}from"fs";import*as Be from"path";function sA(r){return[...r?[`.env.${r}.local`,`.env.${r}`]:[],".env.local",".env"]}function Te(r,e=process.cwd()){let t={},n=[];for(let s of sA(r)){let i;try{i=rA(Be.resolve(e,s),"utf-8")}catch{continue}n.push(s);for(let[o,a]of iA(i))process.env[o]===void 0&&(process.env[o]=a,t[o]=s)}return{mode:r,sources:t,loaded:n}}function*iA(r){for(let e of r.split(`
|
|
1397
|
+
`)){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 oA(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=Be.dirname(e),c=`(mode: ${s??"none"})`,l=t?oA(t):[],d=l.filter(p=>n[p]).map(p=>`${p} \u2190 ${n[p]}`);d.length?console.log(`env: ${d.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=Be.resolve(a)!==Be.resolve(o);if(u)for(let p of[".env.local",".env"])nA(Be.join(a,p))&&console.log(`env: ${Be.join(a,p)} present but not loaded (cwd is ${o})`);let f=l.filter(p=>process.env[p]===void 0);if(f.length){let p=u?` \u2014 try running from ${a}`:"";console.log(`env: server.ts reads ${f.join(", ")} but ${f.length>1?"they are":"it's"} unset${p}`)}}wt();async function Eh(r){Te(r);let e=await Ne();if(e.length>0){console.log(fp(e,process.env.TB_AI_PROVIDER,process.env.TB_AI_MODEL));return}if(!nc()){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(nr))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.")}hi();import*as Ah from"fs/promises";async function Th(r){let e=At(),t;try{t=await Ah.readFile(e,"utf8")}catch{console.error(`Could not read the bundled README (expected at ${e}).`),process.exit(1)}process.stdout.write(Up(t,r))}ri();import*as Ph from"path";xe();function aA(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&&Q(o.cwd)===Q(t));return n&&i.find(o=>o.agent===n)||i[0]}return r.find(i=>Q(i.file)===Q(e))}var Pn=r=>r.agent??Ph.basename(r.file);function Oh(r,e){for(let t of r)e(` ${t.url} pid ${t.pid} ${t.trust?"trusted":"restricted"} ${t.file}`)}function Qc(r,e){if(!r.length){console.log("No running bulb servers.");return}console.log("Running bulb servers:"),Oh(r,t=>console.log(t)),console.log(`
|
|
1398
|
+
`+e)}function Xc(r,e,t,n,s){let i=aA(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>\`):`),Oh(r,o=>console.error(o))):console.error("No bulb servers are running."),process.exit(1)}async function Rh(r,e){if(!r){e.clear&&(console.error("Specify which server to clear: typebulb logs --clear <file|pid>"),process.exit(1)),Qc(await K(process.cwd()),"Run `typebulb logs <file|pid>` to print one server's console.");return}let t=Xc(await K(),r,"logs",process.cwd(),Tn());if(e.clear){Pp(t.pid),console.log(`Cleared log for ${Pn(t)} (pid ${t.pid}).`);return}let n=ke(t.pid),s=n.text;if(e.run!==void 0&&(s=Op(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(`
|
|
1397
1399
|
`);i.length&&i[i.length-1]===""&&i.pop(),s=i.slice(-e.lines).join(`
|
|
1398
1400
|
`)}if(process.stdout.write(s),s&&!s.endsWith(`
|
|
1399
1401
|
`)&&process.stdout.write(`
|
|
1400
|
-
`),e.follow&&e.run===void 0){let i=n.offset,o=setInterval(()=>{let c=
|
|
1401
|
-
`);m=
|
|
1402
|
-
${l}`:"";return g.text(`Forbidden: this capability requires --trust.${
|
|
1403
|
-
${
|
|
1402
|
+
`),e.follow&&e.run===void 0){let i=n.offset,o=setInterval(()=>{let c=ke(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 cA=r=>new Promise(e=>setTimeout(e,r));async function _h(r,e){if(!r){Qc(await K(process.cwd()),"Run `typebulb wait <file|pid>` to block until one logs a new line.");return}let t=Xc(await K(),r,"wait",process.cwd(),Tn()),n=t.agent!=null,i=process.env.TYPEBULB_WAIT_SHIM==="1",o=e.timeoutSec??1800,a=e.match??"",c=ke(t.pid).offset,l=wc(t.pid,a)??(a?wc(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,y,m="",b=0;for(;;){let x=ke(t.pid,d);if(d=x.offset,x.text){m+=x.text;let A=m.split(`
|
|
1403
|
+
`);m=A.pop()??"";for(let g of A)g.trim()&&(e.match&&!g.includes(e.match)||(console.log(g),y??=Date.now()+f,n&&(g.includes("] compile error")||g.includes("] runtime error"))&&(y=Math.min(y,Date.now()+p))))}if(y&&Date.now()>=y)break;if(!i&&!y&&Date.now()>=u){console.error(`timeout: no ${e.match?`line matching '${e.match}'`:"new output"} from ${Pn(t)} within ${o}s`),b=2;break}if(!Sc(t.pid)){y||(console.error(`server ${Pn(t)} (pid ${t.pid}) exited while waiting`),process.exit(3));break}await cA(400)}li(t.pid,d,a),process.exit(b)}async function Ch(r){if(!r){Qc(await K(process.cwd()),"Run `typebulb stop <file|pid>` to stop one.");return}let e=Xc(await K(),r,"stop",process.cwd(),Tn());await xt(e.pid),console.log(`Stopped ${Pn(e)} (pid ${e.pid}, ${e.url}).`)}async function Nh(r){let e=process.cwd(),t=r==="agent"?Tn():void 0,n=r==="global"?await K():r==="bulbs"?await K(e):(await K()).filter(i=>i.agent!=null&&i.cwd!=null&&Q(i.cwd)===Q(e)&&(!t||i.agent===t)),s=r==="global"?"server":r==="agent"?"mirror":"bulb";if(!n.length){console.log(r==="global"?"No running bulb servers.":`No running ${s}s for this project.`);return}await Promise.all(n.map(i=>xt(i.pid))),console.log(`Stopped ${n.length} ${s}${n.length===1?"":"s"}:`);for(let i of n)console.log(` ${i.url} pid ${i.pid} ${Pn(i)}`)}xe();import*as Ih from"path";async function Lh(r,e,t=0){let n=Ih.resolve(r),s=cr(await K(),n)[0];s||(console.error(`No running server for '${r}'. Start it first: npx typebulb ${r}`),process.exit(1));let i=async()=>{let a=await fetch(`${s.url}/__send`,{method:"POST",headers:{"Content-Type":"text/plain"},body:e??""});return a.ok||(console.error(`send failed: HTTP ${a.status} from ${s.url}/__send`),process.exit(1)),(await a.json().catch(()=>({}))).clients??0},o=0;try{let a=Date.now()+t;do{if(o=await i(),o>0||Date.now()>=a)break;await new Promise(c=>setTimeout(c,150))}while(!0)}catch(a){console.error(`send failed: ${a instanceof Error?a.message:String(a)}`),process.exit(1)}o>0?console.log(`Sent to ${o} page${o===1?"":"s"}.`):t>0?console.log(`No page connected after ${t/1e3}s \u2014 is the bulb open?`):console.log("Sent, but no page is connected yet \u2014 open the bulb and retry.")}import*as Fh from"fs/promises";import*as qh from"path";import{EventEmitter as jh}from"events";mi();import EA from"open";rr();import{Hono as mA}from"hono";import{serve as hA}from"@hono/node-server";import{streamSSE as gA}from"hono/streaming";import*as Ct from"fs/promises";import*as be from"path";import*as Zc from"fs/promises";import*as On from"path";var Ui=class{async get(e){let t=de(e),n=On.join(cn,t+".bin"),s=On.join(cn,t+".json");try{let[i,o]=await Promise.all([Zc.readFile(n),Zc.readFile(s,"utf8")]),a=JSON.parse(o);return{body:i,contentType:a.contentType,cacheControl:a.cacheControl}}catch{return}}async set(e,t){await U();let n=de(e),s=On.join(cn,n+".bin"),i=On.join(cn,n+".json"),o={url:e,contentType:t.contentType,cacheControl:t.cacheControl};await Promise.all([ae(s,t.body),ae(i,JSON.stringify(o))])}};xe();wt();ei();rr();import{stream as lA}from"hono/streaming";var uA="X-TB-Stream";function el(r){return r instanceof me?{message:r.message,code:r.code,retryable:r.retryable}:{message:r instanceof Error?r.message:"Unknown error",code:"unknown",retryable:!1}}function tl(r,e){return r.header("Content-Type","application/x-ndjson; charset=utf-8"),r.header("Cache-Control","no-cache"),r.header(uA,"1"),lA(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:el(s)}))}finally{try{await n.return?.()}catch{}}})}var Ji={log:(...r)=>console.log(...r)};function Ki(r,e){let t=r?.[e]??(Object.hasOwn(Ji,e)?Ji[e]:void 0);return typeof t=="function"?t:void 0}function Wi(r){return r.constructor?.name==="AsyncGeneratorFunction"}var fA=/^\/(v\d+\/|stable\/|node\/|gh\/|@[^/]+\/[^@/]+@|[^@/]+@)/,dA=/[?&]target=/,pA=/^\/(?:@[^/]+\/)?[^/@]+\/[^/]+/;function Mh(r,e=""){return fA.test(r)?!0:pA.test(r)&&dA.test(e)}var Dh="127.0.0.1",yA=new Set(["localhost","127.0.0.1","::1"]);function bA(r){if(r)try{return new URL(r.includes("://")?r:`http://${r}`).hostname}catch{return}}function wA(r){let e=bA(r);return!!e&&yA.has(e)}function vA(r,e){if(!e)return!1;try{return new URL(r).host===e}catch{return!1}}function rl(r){return r instanceof Error?r.message:"Unknown error"}async function Bh(r){let{getHtml:e,basePath:t,port:n,reloadEmitter:s,messageEmitter:i,getServerExports:o,localOverride:a,trusted:c=!1,trustHint:l,staticAssets:d}=r,u=new mA;u.use("*",async(g,w)=>{if(!wA(g.req.header("host")))return g.text("Forbidden: untrusted Host",403);await w()}),u.use("*",async(g,w)=>{await w(),g.res.headers.set("Cross-Origin-Opener-Policy","same-origin"),g.res.headers.set("Cross-Origin-Embedder-Policy","credentialless")});let f=["/__fs/*","/__api/*","/__ai"],p=async(g,w)=>{if(!c){let k=new URL(g.req.url).pathname,E=k.startsWith("/__fs")?"the filesystem":k==="/__ai"?"AI (your API keys)":"server-side code (server.ts)";_p(process.pid,E);let T=l?`
|
|
1404
|
+
${l}`:"";return g.text(`Forbidden: this capability requires --trust.${T}`,403)}await w()},y=async(g,w)=>{let k=g.req.header("sec-fetch-site");if(k){if(k!=="same-origin")return g.text(`Forbidden: ${k} request`,403)}else{let E=g.req.header("origin");if(E&&!vA(E,g.req.header("host")))return g.text("Forbidden: cross-origin request",403)}await w()};for(let g of f)u.use(g,p),u.use(g,y);u.use("/__log",y),u.post("/__log",async g=>{try{let{args:w}=await g.req.json();console.log(...w||[])}catch{}return g.json({ok:!0})}),i&&(u.use("/__send",y),u.post("/__send",async g=>{let w="";try{w=await g.req.text()}catch{}let k=i.listenerCount("message");return i.emit("message",w),g.json({clients:k})})),u.get("/",g=>g.html(e())),u.post("/__fs/read",async g=>{try{let{path:w}=await g.req.json(),k=sl(w,t),E=await Ct.readFile(k);return new Response(new Uint8Array(E),{headers:{"Content-Type":"application/octet-stream"}})}catch(w){let k=rl(w);return g.json({error:k},400)}}),u.post("/__fs/write",async g=>{try{let w=g.req.query("path");if(!w)return g.json({error:"Missing path"},400);let k=sl(w,t);return await Ct.mkdir(be.dirname(k),{recursive:!0}),await Ct.writeFile(k,Buffer.from(await g.req.arrayBuffer())),g.json({success:!0})}catch(w){let k=rl(w);return g.json({error:k},400)}}),u.post("/__api/:name",async g=>{try{let w=g.req.param("name"),k=Ki(o?.(),w);if(!k)return g.json({error:`API function '${w}' not found`},404);let{args:E}=await g.req.json();if(Wi(k))return tl(g,k(...E||[]));let T=await k(...E||[]);return g.json({result:T})}catch(w){let k=rl(w);return g.json({error:k},500)}}),u.post("/__ai",async g=>{try{let{messages:w,system:k,effort:E,provider:T,model:P,webSearch:D,stream:te}=await g.req.json();if(!w||!Array.isArray(w)||w.length===0)return g.json({message:"messages array is required",code:"unknown",retryable:!1},400);let V=vt(T,P);if(typeof V=="string")return g.json({message:V,code:"unknown",retryable:!1},400);let B=await St(V,{messages:w,system:k,effort:E,webSearch:D,signal:g.req.raw.signal});if(!B.ok){let Vi=await ln(B,V.protocol);return g.json(Vi,B.status)}if(te)return tl(g,tr(B,V.protocol));let it=await bt(B,V.protocol);return it||console.warn("[tb.ai] Empty response from provider"),g.json({text:it})}catch(w){return g.json(el(w),500)}}),u.get("/__models",async g=>{try{let w=await Ne();return g.json(w)}catch{return g.json([],200)}}),u.get("/__has-own-keys",async g=>{try{return g.json(await Zs())}catch{return g.json(!1,200)}});let m=["esm.sh","unpkg.com","cdn.jsdelivr.net","cdnjs.cloudflare.com"],b=new Ui;u.get("/proxy/*",async g=>{let w=new URL(g.req.url),E=(w.pathname+w.search).slice(7),T=E.lastIndexOf("https://");return T===-1?g.text("Invalid proxy URL",400):x(g,E.slice(T))}),a&&$h(u,`/local/${a.name}/`,a.serveDir),d&&$h(u,d.mount,d.dir);async function x(g,w){let k;try{k=new URL(w)}catch{return g.text("Invalid URL",400)}if(k.protocol!=="https:")return g.text("HTTPS only",400);if(!m.includes(k.hostname))return g.text("Host not allowed",403);let E=await b.get(w);if(E)return new Response(E.body,{status:200,headers:nl(E.contentType,E.cacheControl)});try{let T=await fetch(w,{headers:{Accept:g.req.header("Accept")||"*/*"},redirect:"follow"});if(!T.ok)return g.text(`Upstream ${T.status}`,T.status);let P=T.headers.get("Content-Type")||void 0,D=T.headers.get("Cache-Control")||void 0;if(T.body){let[te,V]=T.body.tee();return(async()=>{try{let B=await new Response(V).arrayBuffer();await b.set(w,{body:Buffer.from(B),contentType:P,cacheControl:D})}catch{}})(),new Response(te,{status:T.status,headers:nl(P,D)})}return new Response(null,{status:T.status,headers:nl(P,D)})}catch(T){return g.text(`Proxy fetch failed: ${T instanceof Error?T.message:T}`,502)}}(s||i)&&u.get("/__reload",g=>gA(g,async w=>{let k=()=>{w.writeSSE({event:"reload",data:""})},E=T=>{w.writeSSE({event:"message",data:JSON.stringify(T)})};for(s?.on("reload",k),i?.on("message",E),w.onAbort(()=>{s?.removeListener("reload",k),i?.removeListener("message",E)});!w.aborted;)await w.sleep(3e4)})),u.notFound(async g=>{if(g.req.method!=="GET")return g.text("Not Found",404);let w=new URL(g.req.url);return Mh(w.pathname,w.search)?x(g,"https://esm.sh"+w.pathname+w.search):g.text("Not Found",404)});let A=hA({fetch:u.fetch,port:n,hostname:Dh});return{port:n,close:()=>A.close()}}function nl(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 $h(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=sl(i,t),a=await Ct.readFile(o);return new Response(a,{headers:{"Content-Type":SA(o)}})}catch{return n.text("Not Found",404)}})}function SA(r){switch(be.extname(r).toLowerCase()){case".js":case".mjs":return"text/javascript";case".wasm":return"application/wasm";case".json":case".map":return"application/json";default:return"application/octet-stream"}}function sl(r,e){let t=be.resolve(e,r),n=be.normalize(e),s=be.normalize(t);if(s!==n&&!s.startsWith(n+be.sep))throw new Error("Path traversal detected - access denied");return t}async function il(r){let e=await import("net");return new Promise(t=>{let n=e.createServer();n.listen(r,Dh,()=>{let s=n.address(),i=typeof s=="object"&&s?s.port:r;n.close(()=>t(i))}),n.on("error",()=>{t(il(r+1))})})}xe();async function Hi(r){let{portPreference:e,makeServerOptions:t,makeEntry:n,displayName:s,stopLog:i}=r,o=await il(e),a=await Bh(t(o)),c=`http://localhost:${o}`;await Rp(n(o,c)),console.log(`
|
|
1405
|
+
${s}`),console.log(` ${c}`),o!==e&&console.log(` (port ${e} was busy)`);let l=[],d=async()=>{console.log(`
|
|
1406
|
+
Shutting down...`),a.close();for(let u of l)try{await u()}catch{}i(),await gn(process.pid),process.exit(0)};return process.on("SIGINT",d),process.on("SIGTERM",d),{port:o,url:c,onCleanup(u){l.push(u)}}}import kA from"chokidar";var xA={persistent:!0,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50}};function Nt(r){let{target:e,onChange:t,events:n="change",debounceMs:s=150}=r,i,o=kA.watch(e,xA),a=()=>{i&&clearTimeout(i),i=setTimeout(t,s)};return n==="all"?o.on("all",a):o.on("change",a),()=>{i&&clearTimeout(i),o.close()}}xe();async function Uh(r,e,t,n){let s=process.cwd(),i=ui(process.pid),o=e.watch?new jh:void 0,a=new jh;a.setMaxListeners(0);let c=Te(e.mode),l=await xc(r);l.length&&console.log(`Replacing the running server for this bulb (pid ${l.map(w=>w.pid).join(", ")})`);let d=1;console.log(vc(d)),console.log(`Loading ${qh.basename(r)}...`);let{html:u,bulb:f,serverExports:p}=await ic(r,e.watch,e.trust,n);st(c,r,f.server);let y=e.trust?void 0:lr(f),{port:m,url:b,onCleanup:x}=await Hi({portPreference:e.port,displayName:f.name,stopLog:i,makeServerOptions:w=>({getHtml:()=>u,basePath:s,port:w,reloadEmitter:o,messageEmitter:a,getServerExports:()=>p,localOverride:n?{name:n.name,serveDir:n.serveDir}:void 0,trusted:e.trust,trustHint:t}),makeEntry:(w,k)=>({pid:process.pid,port:w,url:k,file:r,cwd:process.cwd(),startedAt:Date.now(),trust:e.trust,predicted:y})});e.trust?console.log(" trust: granted (filesystem, AI, server.ts enabled)"):console.log(y?` trust: restricted \u2014 this bulb appears to use ${y}; re-run with --trust to enable it:
|
|
1404
1407
|
${t}
|
|
1405
1408
|
`:` trust: restricted \u2014 re-run with --trust to enable filesystem / AI / server.ts
|
|
1406
1409
|
`),e.watch&&console.log(` Watching for changes...
|
|
1407
|
-
`);let g
|
|
1408
|
-
`),
|
|
1409
|
-
`):await
|
|
1410
|
-
Shutting down...`),b.close(),g?.(),w?.(),o(),await xt(process.pid);let x=hr.join(hr.dirname(r),".typebulb","server.mjs");await Km.rm(x,{force:!0}).catch(()=>{}),process.exit(0)};process.on("SIGINT",k),process.on("SIGTERM",k)}import{readFileSync as jh,copyFileSync as hA,existsSync as gA}from"fs";import*as Z from"path";import{fileURLToPath as yA}from"url";import{EventEmitter as bA}from"events";import Fh from"open";Me();var Gc=r=>`/agents/${r}/client.js`,M0=`
|
|
1410
|
+
`);let A,g;if(e.watch&&o){let w=0,k=Promise.resolve();if(A=Nt({target:r,onChange:()=>{let E=++w;k=k.then(async()=>{if(E===w)try{console.log("Recompiling...");let T=await ic(r,!0,e.trust,n);u=T.html,p=T.serverExports,d++,console.log(vc(d)),o.emit("reload")}catch(T){console.error("Compile error:",T)}})}}),n){let{name:E,serveDir:T}=n;g=Nt({target:T,events:"all",onChange:()=>{console.log(`Local package '${E}' changed. Browser reloading...
|
|
1411
|
+
`),o.emit("reload")}})}}A&&x(A),g&&x(g),x(()=>Fh.rm(sc(r),{force:!0})),e.open&&(l.some(w=>w.port===m)?console.log(` Reusing the open browser tab.
|
|
1412
|
+
`):await EA(b))}import{readFileSync as Kh,copyFileSync as TA,existsSync as PA}from"fs";import*as Z from"path";import{fileURLToPath as OA}from"url";import{EventEmitter as RA}from"events";import Wh from"open";xe();var ol=r=>`/agents/${r}/client.js`,AA=`
|
|
1411
1413
|
(() => {
|
|
1412
1414
|
const api = async (name, ...args) => {
|
|
1413
1415
|
const resp = await fetch('/__api/' + name, {
|
|
@@ -1442,15 +1444,15 @@ Shutting down...`),b.close(),g?.(),w?.(),o(),await xt(process.pid);let x=hr.join
|
|
|
1442
1444
|
es.onerror = () => { es.close(); };
|
|
1443
1445
|
}
|
|
1444
1446
|
})();
|
|
1445
|
-
`;function
|
|
1447
|
+
`;function Jh(r){let{name:e,agent:t,styles:n,mountHtml:s,watch:i,theme:o}=r,a=ol(t);return`<!DOCTYPE html>
|
|
1446
1448
|
<html>
|
|
1447
1449
|
<head>
|
|
1448
1450
|
<meta charset="utf-8">
|
|
1449
1451
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
1450
|
-
<title>${
|
|
1451
|
-
${
|
|
1452
|
+
<title>${js(e)} - typebulb</title>
|
|
1453
|
+
${qs(e,o)}
|
|
1452
1454
|
<style>
|
|
1453
|
-
${
|
|
1455
|
+
${Fs}
|
|
1454
1456
|
</style>
|
|
1455
1457
|
<style>
|
|
1456
1458
|
${n}
|
|
@@ -1462,19 +1464,17 @@ ${s}
|
|
|
1462
1464
|
${i?"<script>window.__TYPEBULB_WATCH__ = true;</script>":""}
|
|
1463
1465
|
|
|
1464
1466
|
<script>
|
|
1465
|
-
${
|
|
1467
|
+
${AA}
|
|
1466
1468
|
</script>
|
|
1467
1469
|
|
|
1468
1470
|
<script type="module" src="${a}"></script>
|
|
1469
1471
|
</body>
|
|
1470
|
-
</html>`}
|
|
1471
|
-
${n.url}`),r.open&&await
|
|
1472
|
-
|
|
1473
|
-
`)
|
|
1474
|
-
`),
|
|
1475
|
-
|
|
1476
|
-
`),
|
|
1477
|
-
`)}
|
|
1478
|
-
`),
|
|
1479
|
-
`),process.exit(1)}function AA(){let r=new vA(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 Wh(r){return new Promise((e,t)=>{process.stdout.write(r,n=>n?t(n):e())})}async function TA(){let r=[];for await(let e of process.stdin)r.push(e);return Buffer.concat(r).toString("utf-8")}var cl="0.24.1";function Yh(r,e){r||(console.error(`This bulb runs server-side Node code (server.ts), which --trust must authorize:
|
|
1480
|
-
${e}`),process.exit(1))}async function PA(){let r=Sl(process.argv.slice(2));if(r.version&&(console.log(`typebulb ${cl}`),process.exit(0)),r.help&&(kl(),process.exit(0)),Em(),r.subcommand==="logs"){await Lm(r.file||void 0,{follow:r.follow,clear:r.clear,run:r.run,lines:r.lines});return}if(r.subcommand==="wait"){await Mm(r.file||void 0,{match:r.match,timeoutSec:r.timeoutSec});return}if(r.subcommand==="stop"){r.stopScope?await Dm(r.stopScope):await $m(r.file||void 0);return}if(r.subcommand==="send"){await jm(r.file,r.sendMessage,r.sendWaitMs??0);return}if(r.subcommand==="skill"){await Cm(cl);return}if(r.subcommand==="models"){await Rm(r.mode);return}if(r.subcommand==="agent"){await(r.agentTarget?qh(r):Om(cl));return}if(r.subcommand==="trust"||r.subcommand==="untrust"){await Mp(r.file||void 0,r.subcommand==="trust");return}let e;if(!r.file||r.file==="."){let l=await kp(process.cwd());l||(console.error("No .bulb.md file found in current directory"),process.exit(1)),e=l}else e=Be.resolve(r.file);await Gh.access(e).then(()=>!0,()=>!1)||(or().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:Be.relative(process.cwd(),e)||Be.basename(e),s=`npx typebulb --trust ${n.includes(" ")?`"${n}"`:n}`;if(r.subcommand==="predict"){await Lp(e,s);return}let i=!r.noTrust&&kt(e);i&&!r.trust&&console.log("trust: granted from memory (run `typebulb untrust` to revoke)"),r.trust=r.noTrust?!1:r.trust||i;let o;try{o=await he(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 wl(r.local)}catch(l){console.error(l instanceof Error?l.message:String(l)),process.exit(1)}console.log(`replace: ${a.name} \u2192 ${Be.relative(process.cwd(),a.dir)||"."}`)}if(r.subcommand==="check"){await Ip(e,a);return}let c=Be.dirname(e);if(r.subcommand==="call"){Yh(r.trust,s),await Hh(e,{fn:r.fn,positional:r.callArgs,argsJson:r.argsJson,hasArgsFlag:r.hasArgsFlag},r.mode,a,c);return}if(o&&o.bulb.server&&(Rs(o.bulb)||r.server)){Yh(r.trust,s),await Jh(e,r.watch,r.mode,a,c);return}await Wm(e,r,s,a,c)}PA().catch(r=>{console.error("Error:",r.message),process.exit(1)});
|
|
1472
|
+
</html>`}async function Hh(r){let e=process.cwd(),t=r.agentTarget;Xm(t)||(console.error(`Unknown agent '${t}'. Known: ${gr().join(", ")}.`),process.exit(1));let n=await kc(e,t);if(n){console.log(`Mirror '${t}' is already running for this project:
|
|
1473
|
+
${n.url}`),r.open&&await Wh(n.url);return}let s=ui(process.pid),i=r.watch?new RA:void 0,o=Te(r.mode),a=await eh(t),c=a.displayName||`${t} mirror`;st(o,Z.join(e,"mirror"));let l=Z.dirname(OA(import.meta.url)),d=Z.join(l,"agents",t),u=Z.join(l,"..","cli","agents"),f=Z.join(d,"styles.css"),p=Z.join(d,"index.html"),y=()=>Jh({name:c,agent:t,styles:Kh(f,"utf8"),mountHtml:Kh(p,"utf8"),watch:r.watch}),{port:m,url:b,onCleanup:x}=await Hi({portPreference:r.port,displayName:c,stopLog:s,makeServerOptions:E=>({getHtml:y,basePath:e,port:E,reloadEmitter:i,getServerExports:()=>a,trusted:!0,staticAssets:{mount:`${Z.posix.dirname(ol(t))}/`,dir:d}}),makeEntry:(E,T)=>({pid:process.pid,port:E,url:T,file:`agent:${t}`,cwd:e,startedAt:Date.now(),trust:!0,agent:t})});r.watch&&console.log(` Watching for changes...
|
|
1474
|
+
`);let A=Z.join(u,t,"client"),g=Z.join(u,"core","client");async function w(){await(await import("esbuild")).build({entryPoints:[Z.join(A,"index.ts")],bundle:!0,platform:"browser",format:"esm",outfile:Z.join(d,"client.js")});for(let T of["styles.css","index.html","typebulb.png","typebulb-inv.png"])TA(Z.join(g,T),Z.join(d,T))}let k;if(r.watch&&i){let E=PA(A),T=!1;k=Nt({target:E?u:d,events:"all",onChange:async()=>{if(!T){T=!0;try{E&&await w(),console.log(`Mirror rebuilt. Browser reloading...
|
|
1475
|
+
`),i.emit("reload")}catch(P){console.error("Mirror rebuild failed:",P instanceof Error?P.message:P)}finally{T=!1}}}})}r.open&&await Wh(b),x(()=>a.shutdownSwitcher?.()),x(()=>a.shutdownComposer?.()),k&&x(k)}import*as Vh from"path";async function Yh(r,e,t,n){let s=Te(t),i=!1,o=async()=>{let{bulb:a,config:c}=await ge(r);i||(st(s,r,a.server),i=!0),await dn(a.server,r,n,c.dependencies)};if(console.log(`Running ${Vh.basename(r)}...`),await o(),e){console.log(`Watching for changes...
|
|
1476
|
+
`);let a=0,c=Promise.resolve();Nt({target:r,onChange:()=>{let l=++a;c=c.then(async()=>{if(l===a)try{console.log("Re-running..."),await o()}catch(d){console.error("Error:",d)}})}})}}import{Console as _A}from"node:console";xe();async function Qh(r,e,t,n){MA();try{let f=cr(await K(),r)[0];f&&(li(f.pid,ke(f.pid).offset),console.error(`note: 'call' boots a fresh server.ts instance; the running server (${f.url}) is not contacted \u2014 state shared with it must live on disk.`))}catch{}let s=Te(t),{bulb:i,config:o}=await ge(r);i.server||Rn("This bulb has no **server.ts** block; nothing to call."),st(s,r,i.server);let a;try{a=await dn(i.server,r,n,o.dependencies)}catch(f){Rn(f instanceof Error?f.message:String(f))}let c=Ki(a,e.fn);if(!c){let f=[...Object.keys(a).filter(p=>typeof a[p]=="function"),...Object.keys(Ji)];Rn(`Function '${e.fn}' not found. Available: ${f.length?f.join(", "):"(none)"}.`)}let l=await CA(e);if(Wi(c)){try{for await(let f of c(...l))await zh(JSON.stringify(f,Xh)+`
|
|
1477
|
+
`)}catch(f){Rn(f instanceof Error?f.stack??f.message:String(f))}return Gh(0)}let d;try{d=await c(...l)}catch(f){Rn(f instanceof Error?f.stack??f.message:String(f))}let u=LA(d);u!==void 0&&await zh(u+`
|
|
1478
|
+
`),Gh(0)}function Gh(r){process.exitCode=r,setTimeout(()=>process.exit(r),2e3).unref?.()}async function CA(r){if(r.hasArgsFlag){let e=r.argsJson??"";return e==="-"&&(e=await $A()),IA(e)}return NA(r.positional)}function NA(r){return r.map(e=>{try{return JSON.parse(e)}catch{return e}})}function IA(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 LA(r){if(r!==void 0)return JSON.stringify(r,Xh,2)}function Xh(r,e){return typeof e=="bigint"?e.toString():e}function Rn(r){process.stderr.write(r+`
|
|
1479
|
+
`),process.exit(1)}function MA(){let r=new _A(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 zh(r){return new Promise((e,t)=>{process.stdout.write(r,n=>n?t(n):e())})}async function $A(){let r=[];for await(let e of process.stdin)r.push(e);return Buffer.concat(r).toString("utf-8")}var al="0.24.3";function Zh(r,e){r||(console.error(`This bulb runs server-side Node code (server.ts), which --trust must authorize:
|
|
1480
|
+
${e}`),process.exit(1))}async function DA(){let r=kl(process.argv.slice(2));if(r.version&&(console.log(`typebulb ${al}`),process.exit(0)),r.help&&(xl(),process.exit(0)),wh(),r.subcommand==="logs"){await Rh(r.file||void 0,{follow:r.follow,clear:r.clear,run:r.run,lines:r.lines});return}if(r.subcommand==="wait"){await _h(r.file||void 0,{match:r.match,timeoutSec:r.timeoutSec});return}if(r.subcommand==="stop"){r.stopScope?await Nh(r.stopScope):await Ch(r.file||void 0);return}if(r.subcommand==="send"){await Lh(r.file,r.sendMessage,r.sendWaitMs??0);return}if(r.subcommand==="skill"){await Th(al);return}if(r.subcommand==="models"){await Eh(r.mode);return}if(r.subcommand==="agent"){await(r.agentTarget?Hh(r):xh(al));return}if(r.subcommand==="trust"||r.subcommand==="untrust"){await bh(r.file||void 0,r.subcommand==="trust");return}let e;if(!r.file||r.file==="."){let c=await mp(process.cwd());c||(console.error("No .bulb.md file found in current directory"),process.exit(1)),e=c}else e=It.resolve(r.file);await eg.access(e).then(()=>!0,()=>!1)||(gr().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:It.relative(process.cwd(),e)||It.basename(e),s=`npx typebulb --trust ${n.includes(" ")?`"${n}"`:n}`;if(r.subcommand==="predict"){await yh(e,s);return}let i=!r.noTrust&&kt(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 ge(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 vl(r.local)}catch(c){console.error(c instanceof Error?c.message:String(c)),process.exit(1)}console.error(`replace: ${a.name} \u2192 ${It.relative(process.cwd(),a.dir)||"."}`)}if(r.subcommand==="check"){await gh(e,a);return}if(r.subcommand==="call"){Zh(r.trust,s),await Qh(e,{fn:r.fn,positional:r.callArgs,argsJson:r.argsJson,hasArgsFlag:r.hasArgsFlag},r.mode,a);return}if(o&&o.bulb.server&&(_s(o.bulb)||r.server)){Zh(r.trust,s),await Yh(e,r.watch,r.mode,a);return}await Uh(e,r,s,a)}DA().catch(r=>{console.error("Error:",r.message),process.exit(1)});
|