typebulb 0.28.2 → 0.29.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -3
- package/dist/agents/claude/client.js +174 -178
- package/dist/agents/pi/client.js +175 -179
- package/dist/agents/pi/matchu-patchu.ts +116 -53
- package/dist/dts/tbTypings.d.ts +2 -2
- package/dist/dts/tbTypings.d.ts.map +1 -1
- package/dist/dts/tbTypings.js +3 -2
- package/dist/dts/tbTypings.js.map +1 -1
- package/dist/index.js +199 -193
- package/dist/render.js +1 -1
- package/package.json +107 -107
package/dist/index.js
CHANGED
|
@@ -1,32 +1,32 @@
|
|
|
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 Ry=Object.create;var Ao=Object.defineProperty;var Ny=Object.getOwnPropertyDescriptor;var Iy=Object.getOwnPropertyNames;var $y=Object.getPrototypeOf,Ly=Object.prototype.hasOwnProperty;var Vn=(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 A=(r,e)=>()=>(r&&(e=r(r=0)),e);var E=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),su=(r,e)=>{for(var t in e)Ao(r,t,{get:e[t],enumerable:!0})},My=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Iy(e))!Ly.call(r,s)&&s!==t&&Ao(r,s,{get:()=>e[s],enumerable:!(n=Ny(e,s))||n.enumerable});return r};var Dy=(r,e,t)=>(t=r!=null?Ry($y(r)):{},My(e||!r||!r.__esModule?Ao(t,"default",{value:r,enumerable:!0}):t,r));function gu(r){return Ge.find(e=>Pe[e].path===r)}function bu(r){return!!r?.startsWith("typebulb")}var Pe,Ge,yu,Gn=A(()=>{Pe={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"}},Ge=["code","css","html","data","infer","insight","config","notes"];yu="typebulb/v1"});function Co(r){return/[:\n"']/.test(r)||r.startsWith(" ")||r.endsWith(" ")?`"${r.replace(/"/g,'\\"')}"`:r}function _o(r){return r.startsWith('"')&&r.endsWith('"')?r.slice(1,-1).replace(/\\"/g,'"'):r.startsWith("'")&&r.endsWith("'")?r.slice(1,-1):r}var zn=A(()=>{});function de(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=Gy(n);if(!s)return null;let i=new Map,o=[],a=t;for(;t<e.length;){let l=e[t]?.trim()?.match(wu);if(l){let f=l[1].trim();for(t++;t<e.length&&e[t]?.trim()==="";)t++;let u=e[t]?.match(Qn);if(!u){o.push(`**${f}** has no code fence \u2014 block skipped`);continue}let d=u[1];t++;let p=[],y=Ro(d);for(;t<e.length&&!e[t]?.match(y);)p.push(e[t]),t++;let m=t<e.length;t++,o.push(...Yy(f,p,m)),i.set(f,p.join(`
|
|
5
|
+
`)),a=t}else t++}return{frontmatter:s,files:i,warnings:o,bodyEndLine:a}}catch{return null}}function Yy(r,e,t){let n=[];for(let s=0;s<e.length;s++){let i=e[s]?.trim().match(wu);i&&Wy.has(i[1].trim())&&Vy(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 Vy(r,e){let t=e+1;for(;t<r.length&&r[t]?.trim()==="";)t++;return!!r[t]?.match(Qn)}function Gy(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=_o(i);break}}return!bu(e.format)||!e.name?null:e}function vu(r){return de(r)?.warnings??[]}function Su(r){let e=Object.fromEntries(Ge.map(t=>[t,r.files.get(Pe[t].path)||""]));return{name:r.frontmatter.name,...e}}var wu,Qn,Wy,Ro,No=A(()=>{Gn();zn();wu=/^\*\*(.+)\*\*$/,Qn=/^(`{3,})(\w*)\s*$/,Wy=new Set(Ge.map(r=>Pe[r].path)),Ro=r=>new RegExp(`^${r}\\s*$`)});function ku(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 xu(r,e){let{path:t}=Pe[r],n=t.split(".").pop(),s=ku(e);return`**${t}**
|
|
6
6
|
|
|
7
7
|
${s}${n}
|
|
8
8
|
${e}
|
|
9
|
-
${s}`}function
|
|
9
|
+
${s}`}function Eu(r){let e=Ge.filter(t=>r[t]).map(t=>xu(t,r[t]));return["---",`format: ${yu}`,`name: ${Co(r.name)}`,"---","",...e].join(`
|
|
10
10
|
`)}function Io(r,e,t){let{path:n}=Pe[e],s=r.split(`
|
|
11
|
-
`);for(let i=0;i<s.length;i++){if(s[i]?.trim()!==`**${n}**`)continue;let o=i+1;for(;o<s.length&&s[o]?.trim()==="";)o++;let a=s[o]?.match(Qn);if(!a)continue;let c=Ro(a[1]),l=o+1;for(;l<s.length&&!s[l]?.match(c);)l++;if(l>=s.length)return r;let
|
|
11
|
+
`);for(let i=0;i<s.length;i++){if(s[i]?.trim()!==`**${n}**`)continue;let o=i+1;for(;o<s.length&&s[o]?.trim()==="";)o++;let a=s[o]?.match(Qn);if(!a)continue;let c=Ro(a[1]),l=o+1;for(;l<s.length&&!s[l]?.match(c);)l++;if(l>=s.length)return r;let f=ku(t),u=f.length>a[1].length?f:a[1];return[...s.slice(0,o),u+a[2],...t.split(`
|
|
12
12
|
`),u,...s.slice(l+1)].join(`
|
|
13
13
|
`)}return`${r.replace(/\s*$/,"")}
|
|
14
14
|
|
|
15
|
-
${
|
|
16
|
-
`}var
|
|
15
|
+
${xu(e,t)}
|
|
16
|
+
`}var Au=A(()=>{Gn();No();zn()});function Lr(r){if(!r.trim())return{};try{return JSON.parse(r)}catch{return{}}}function Qy(r){return r.replace(/\[([^\]]*)\]\([^)]*\)/g,"$1").replace(/\*\*([^*]+)\*\*/g,"$1").replace(/\*([^*]+)\*/g,"$1").replace(/`([^`]+)`/g,"$1").replace(/^#{1,6}\s+/gm,"")}function $o(r){let e=Lr(r??"").description?.trim();if(!e)return zy;let t=Qy(e);return(t.length>200?t.slice(0,197)+"...":t).replace(/\n/g," ")}var zy,Tu=A(()=>{zy="A Typebulb bulb."});var Pu=A(()=>{});function Lo(r,e,t){let s=new RegExp(e).exec(r.slice(t));return s?t+s.index:-1}var Ou=A(()=>{});function Mr(r,e,t){let s=new RegExp(e).exec(r.slice(t));return s?t+s.index+s[0].length-1:-1}var Cu=A(()=>{});function Xn(r,e){let t=new RegExp(e,"g"),n=r.match(t);return n?n.length:0}var _u=A(()=>{});function Dr(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=Lo(r,`<${e}[
|
|
17
17
|
>/]`,i);if(n&&console.log("[xml-utils] start:",o),o===-1)return;let a=r.slice(o+e.length),c=Mr(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=Mr(a,"[ /]"+e+">",p))!==-1;){let b=a.substring(p,c+1);if(y+=Xn(b,"<"+e+`[
|
|
18
|
-
>]`),m+=Xn(b,"</"+e+">"),m>=y)break;p=c}}else c=Mr(a,"[ /]"+e+">",0);let
|
|
19
|
-
`)}};jr.defaultYaml={explicit:!1,version:"1.2"};jr.defaultTags={"!!":"tag:yaml.org,2002:"};
|
|
18
|
+
>]`),m+=Xn(b,"</"+e+">"),m>=y)break;p=c}}else c=Mr(a,"[ /]"+e+">",0);let f=o+e.length+c+1;if(n&&console.log("[xml-utils] end:",f),f===-1)return;let u=r.slice(o,f),d;return l?d=null:d=u.slice(u.indexOf(">")+1,u.lastIndexOf("<")),{inner:d,outer:u,start:o,end:f}}var Mo=A(()=>{Ou();Cu();_u()});var Do=A(()=>{Mo()});var Bo=A(()=>{Do()});var Ru=A(()=>{Bo()});var Nu=A(()=>{});var Iu=A(()=>{Pu();Mo();Do();Ru();Bo();Nu()});var j=E(Z=>{"use strict";var jo=Symbol.for("yaml.alias"),$u=Symbol.for("yaml.document"),Zn=Symbol.for("yaml.map"),Lu=Symbol.for("yaml.pair"),Fo=Symbol.for("yaml.scalar"),es=Symbol.for("yaml.seq"),De=Symbol.for("yaml.node.type"),eb=r=>!!r&&typeof r=="object"&&r[De]===jo,tb=r=>!!r&&typeof r=="object"&&r[De]===$u,rb=r=>!!r&&typeof r=="object"&&r[De]===Zn,nb=r=>!!r&&typeof r=="object"&&r[De]===Lu,Mu=r=>!!r&&typeof r=="object"&&r[De]===Fo,sb=r=>!!r&&typeof r=="object"&&r[De]===es;function Du(r){if(r&&typeof r=="object")switch(r[De]){case Zn:case es:return!0}return!1}function ib(r){if(r&&typeof r=="object")switch(r[De]){case jo:case Zn:case Fo:case es:return!0}return!1}var ob=r=>(Mu(r)||Du(r))&&!!r.anchor;Z.ALIAS=jo;Z.DOC=$u;Z.MAP=Zn;Z.NODE_TYPE=De;Z.PAIR=Lu;Z.SCALAR=Fo;Z.SEQ=es;Z.hasAnchor=ob;Z.isAlias=eb;Z.isCollection=Du;Z.isDocument=tb;Z.isMap=rb;Z.isNode=ib;Z.isPair=nb;Z.isScalar=Mu;Z.isSeq=sb});var Br=E(qo=>{"use strict";var G=j(),oe=Symbol("break visit"),Bu=Symbol("skip children"),Oe=Symbol("remove node");function ts(r,e){let t=ju(e);G.isDocument(r)?Qt(null,r.contents,t,Object.freeze([r]))===Oe&&(r.contents=null):Qt(null,r,t,Object.freeze([]))}ts.BREAK=oe;ts.SKIP=Bu;ts.REMOVE=Oe;function Qt(r,e,t,n){let s=Fu(r,e,t,n);if(G.isNode(s)||G.isPair(s))return qu(r,n,s),Qt(r,s,t,n);if(typeof s!="symbol"){if(G.isCollection(e)){n=Object.freeze(n.concat(e));for(let i=0;i<e.items.length;++i){let o=Qt(i,e.items[i],t,n);if(typeof o=="number")i=o-1;else{if(o===oe)return oe;o===Oe&&(e.items.splice(i,1),i-=1)}}}else if(G.isPair(e)){n=Object.freeze(n.concat(e));let i=Qt("key",e.key,t,n);if(i===oe)return oe;i===Oe&&(e.key=null);let o=Qt("value",e.value,t,n);if(o===oe)return oe;o===Oe&&(e.value=null)}}return s}async function rs(r,e){let t=ju(e);G.isDocument(r)?await Xt(null,r.contents,t,Object.freeze([r]))===Oe&&(r.contents=null):await Xt(null,r,t,Object.freeze([]))}rs.BREAK=oe;rs.SKIP=Bu;rs.REMOVE=Oe;async function Xt(r,e,t,n){let s=await Fu(r,e,t,n);if(G.isNode(s)||G.isPair(s))return qu(r,n,s),Xt(r,s,t,n);if(typeof s!="symbol"){if(G.isCollection(e)){n=Object.freeze(n.concat(e));for(let i=0;i<e.items.length;++i){let o=await Xt(i,e.items[i],t,n);if(typeof o=="number")i=o-1;else{if(o===oe)return oe;o===Oe&&(e.items.splice(i,1),i-=1)}}}else if(G.isPair(e)){n=Object.freeze(n.concat(e));let i=await Xt("key",e.key,t,n);if(i===oe)return oe;i===Oe&&(e.key=null);let o=await Xt("value",e.value,t,n);if(o===oe)return oe;o===Oe&&(e.value=null)}}return s}function ju(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 Fu(r,e,t,n){if(typeof t=="function")return t(r,e,n);if(G.isMap(e))return t.Map?.(r,e,n);if(G.isSeq(e))return t.Seq?.(r,e,n);if(G.isPair(e))return t.Pair?.(r,e,n);if(G.isScalar(e))return t.Scalar?.(r,e,n);if(G.isAlias(e))return t.Alias?.(r,e,n)}function qu(r,e,t){let n=e[e.length-1];if(G.isCollection(n))n.items[r]=t;else if(G.isPair(n))r==="key"?n.key=t:n.value=t;else if(G.isDocument(n))n.contents=t;else{let s=G.isAlias(n)?"alias":"scalar";throw new Error(`Cannot replace node with ${s} parent`)}}qo.visit=ts;qo.visitAsync=rs});var Uo=E(Ju=>{"use strict";var Uu=j(),ab=Br(),cb={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},lb=r=>r.replace(/[!,[\]{}]/g,e=>cb[e]),jr=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+lb(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&&Uu.isNode(e.contents)){let i={};ab.visit(e.contents,(o,a)=>{Uu.isNode(a)&&a.tag&&(i[a.tag]=!0)}),s=Object.keys(i)}else s=[];for(let[i,o]of n)i==="!!"&&o==="tag:yaml.org,2002:"||(!e||s.some(a=>a.startsWith(o)))&&t.push(`%TAG ${i} ${o}`);return t.join(`
|
|
19
|
+
`)}};jr.defaultYaml={explicit:!1,version:"1.2"};jr.defaultTags={"!!":"tag:yaml.org,2002:"};Ju.Directives=jr});var ns=E(Fr=>{"use strict";var Ku=j(),ub=Br();function fb(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 Hu(r){let e=new Set;return ub.visit(r,{Value(t,n){n.anchor&&e.add(n.anchor)}}),e}function Wu(r,e){for(let t=1;;++t){let n=`${r}${t}`;if(!e.has(n))return n}}function db(r,e){let t=[],n=new Map,s=null;return{onAnchor:i=>{t.push(i),s??(s=Hu(r));let o=Wu(e,s);return s.add(o),o},setAnchors:()=>{for(let i of t){let o=n.get(i);if(typeof o=="object"&&o.anchor&&(Ku.isScalar(o.node)||Ku.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}}Fr.anchorIsValid=fb;Fr.anchorNames=Hu;Fr.createNodeAnchors=db;Fr.findNewAnchor=Wu});var Jo=E(Yu=>{"use strict";function qr(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=qr(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=qr(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=qr(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=qr(r,n,s,i);o===void 0?delete n[s]:o!==i&&(n[s]=o)}return r.call(e,t,n)}Yu.applyReviver=qr});var ze=E(Gu=>{"use strict";var pb=j();function Vu(r,e,t){if(Array.isArray(r))return r.map((n,s)=>Vu(n,String(s),t));if(r&&typeof r.toJSON=="function"){if(!t||!pb.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}Gu.toJS=Vu});var ss=E(Qu=>{"use strict";var mb=Jo(),zu=j(),hb=ze(),Ko=class{constructor(e){Object.defineProperty(this,zu.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(!zu.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=hb.toJS(this,"",o);if(typeof s=="function")for(let{count:c,res:l}of o.anchors.values())s(l,c);return typeof i=="function"?mb.applyReviver(i,{"":a},"",a):a}};Qu.NodeBase=Ko});var Ur=E(Xu=>{"use strict";var gb=ns(),yb=Br(),Zt=j(),bb=ss(),wb=ze(),Ho=class extends bb.NodeBase{constructor(e){super(Zt.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=[],yb.visit(e,{Node:(i,o)=>{(Zt.isAlias(o)||Zt.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||(wb.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=is(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(gb.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 is(r,e,t){if(Zt.isAlias(e)){let n=e.resolve(r),s=t&&n&&t.get(n);return s?s.count*s.aliasCount:0}else if(Zt.isCollection(e)){let n=0;for(let s of e.items){let i=is(r,s,t);i>n&&(n=i)}return n}else if(Zt.isPair(e)){let n=is(r,e.key,t),s=is(r,e.value,t);return Math.max(n,s)}return 1}Xu.Alias=Ho});var W=E(Wo=>{"use strict";var vb=j(),Sb=ss(),kb=ze(),xb=r=>!r||typeof r!="function"&&typeof r!="object",Qe=class extends Sb.NodeBase{constructor(e){super(vb.SCALAR),this.value=e}toJSON(e,t){return t?.keep?this.value:kb.toJS(this.value,e,t)}toString(){return String(this.value)}};Qe.BLOCK_FOLDED="BLOCK_FOLDED";Qe.BLOCK_LITERAL="BLOCK_LITERAL";Qe.PLAIN="PLAIN";Qe.QUOTE_DOUBLE="QUOTE_DOUBLE";Qe.QUOTE_SINGLE="QUOTE_SINGLE";Wo.Scalar=Qe;Wo.isScalarValue=xb});var Jr=E(ef=>{"use strict";var Eb=Ur(),kt=j(),Zu=W(),Ab="tag:yaml.org,2002:";function Tb(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 Pb(r,e,t){if(kt.isDocument(r)&&(r=r.contents),kt.isNode(r))return r;if(kt.isPair(r)){let u=t.schema[kt.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 Eb.Alias(c.anchor);c={anchor:null,node:null},a.set(r,c)}e?.startsWith("!!")&&(e=Ab+e.slice(2));let l=Tb(r,e,o.tags);if(!l){if(r&&typeof r.toJSON=="function"&&(r=r.toJSON()),!r||typeof r!="object"){let u=new Zu.Scalar(r);return c&&(c.node=u),u}l=r instanceof Map?o[kt.MAP]:Symbol.iterator in Object(r)?o[kt.SEQ]:o[kt.MAP]}i&&(i(l),delete t.onTagObj);let f=l?.createNode?l.createNode(t.schema,r,t):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(t.schema,r,t):new Zu.Scalar(r);return e?f.tag=e:l.default||(f.tag=l.tag),c&&(c.node=f),f}ef.createNode=Pb});var as=E(os=>{"use strict";var Ob=Jr(),Ce=j(),Cb=ss();function Yo(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 Ob.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 tf=r=>r==null||typeof r=="object"&&!!r[Symbol.iterator]().next().done,Vo=class extends Cb.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=>Ce.isNode(n)||Ce.isPair(n)?n.clone(e):n),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(tf(e))this.add(t);else{let[n,...s]=e,i=this.get(n,!0);if(Ce.isCollection(i))i.addIn(s,t);else if(i===void 0&&this.schema)this.set(n,Yo(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(Ce.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&&Ce.isScalar(i)?i.value:i:Ce.isCollection(i)?i.getIn(s,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!Ce.isPair(t))return!1;let n=t.value;return n==null||e&&Ce.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 Ce.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(Ce.isCollection(i))i.setIn(s,t);else if(i===void 0&&this.schema)this.set(n,Yo(this.schema,s,t));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${s}`)}}};os.Collection=Vo;os.collectionFromPath=Yo;os.isEmptyPath=tf});var Kr=E(cs=>{"use strict";var _b=r=>r.replace(/^(?!$)(?: $)?/gm,"#");function Go(r,e){return/^\n+$/.test(r)?r.substring(1):e?r.replace(/^(?! *$)/gm,e):r}var Rb=(r,e,t)=>r.endsWith(`
|
|
20
20
|
`)?Go(t,e):t.includes(`
|
|
21
21
|
`)?`
|
|
22
|
-
`+Go(t,e):(r.endsWith(" ")?"":" ")+t;cs.indentComment=Go;cs.lineComment=
|
|
23
|
-
`)t===zo&&(m=
|
|
22
|
+
`+Go(t,e):(r.endsWith(" ")?"":" ")+t;cs.indentComment=Go;cs.lineComment=Rb;cs.stringifyComment=_b});var nf=E(Hr=>{"use strict";var Nb="flow",zo="block",ls="quoted";function Ib(r,e,t="flow",{indentAtStart:n,lineWidth:s=80,minContentWidth:i=20,onFold:o,onOverflow:a}={}){if(!s||s<0)return r;s<i&&(i=0);let c=Math.max(1+i,1+s-e.length);if(r.length<=c)return r;let l=[],f={},u=s-e.length;typeof n=="number"&&(n>s-Math.max(2,i)?l.push(0):u=s-n);let d,p,y=!1,m=-1,b=-1,k=-1;t===zo&&(m=rf(r,m,e.length),m!==-1&&(u=m+c));for(let T;T=r[m+=1];){if(t===ls&&T==="\\"){switch(b=m,r[m+1]){case"x":m+=3;break;case"u":m+=5;break;case"U":m+=9;break;default:m+=1}k=m}if(T===`
|
|
23
|
+
`)t===zo&&(m=rf(r,m,e.length)),u=m+e.length+c,d=void 0;else{if(T===" "&&p&&p!==" "&&p!==`
|
|
24
24
|
`&&p!==" "){let P=r[m+1];P&&P!==" "&&P!==`
|
|
25
|
-
`&&P!==" "&&(
|
|
26
|
-
${e}${r.slice(0,C)}`:(t===ls&&
|
|
27
|
-
${e}${r.slice(P+1,C)}`)}return x}function
|
|
28
|
-
`);n=e,s=e+1,i=r[s]}return n}Hr.FOLD_BLOCK=zo;Hr.FOLD_FLOW=
|
|
29
|
-
`){if(i-o>n)return!0;if(o=i+1,s-o<=n)return!1}return!0}function Wr(r,e){let t=JSON.stringify(r);if(e.options.doubleQuotedAsJSON)return t;let{implicitKey:n}=e,s=e.options.doubleQuotedMinMultiLineLength,i=e.indent||(ds(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
|
|
25
|
+
`&&P!==" "&&(d=m)}if(m>=u)if(d)l.push(d),u=d+c,d=void 0;else if(t===ls){for(;p===" "||p===" ";)p=T,T=r[m+=1],y=!0;let P=m>k+1?m-2:b-1;if(f[P])return r;l.push(P),f[P]=!0,u=P+c,d=void 0}else y=!0}p=T}if(y&&a&&a(),l.length===0)return r;o&&o();let x=r.slice(0,l[0]);for(let T=0;T<l.length;++T){let P=l[T],C=l[T+1]||r.length;P===0?x=`
|
|
26
|
+
${e}${r.slice(0,C)}`:(t===ls&&f[P]&&(x+=`${r[P]}\\`),x+=`
|
|
27
|
+
${e}${r.slice(P+1,C)}`)}return x}function rf(r,e,t){let n=e,s=e+1,i=r[s];for(;i===" "||i===" ";)if(e<s+t)i=r[++e];else{do i=r[++e];while(i&&i!==`
|
|
28
|
+
`);n=e,s=e+1,i=r[s]}return n}Hr.FOLD_BLOCK=zo;Hr.FOLD_FLOW=Nb;Hr.FOLD_QUOTED=ls;Hr.foldFlowLines=Ib});var Yr=E(sf=>{"use strict";var be=W(),Xe=nf(),fs=(r,e)=>({indentAtStart:e?r.indent.length:r.indentAtStart,lineWidth:r.options.lineWidth,minContentWidth:r.options.minContentWidth}),ds=r=>/^(%|---|\.\.\.)/m.test(r);function $b(r,e,t){if(!e||e<0)return!1;let n=e-t,s=r.length;if(s<=n)return!1;for(let i=0,o=0;i<s;++i)if(r[i]===`
|
|
29
|
+
`){if(i-o>n)return!0;if(o=i+1,s-o<=n)return!1}return!0}function Wr(r,e){let t=JSON.stringify(r);if(e.options.doubleQuotedAsJSON)return t;let{implicitKey:n}=e,s=e.options.doubleQuotedMinMultiLineLength,i=e.indent||(ds(r)?" ":""),o="",a=0;for(let c=0,l=t[c];l;l=t[++c])if(l===" "&&t[c+1]==="\\"&&t[c+2]==="n"&&(o+=t.slice(a,c)+"\\ ",c+=1,a=c,l="\\"),l==="\\")switch(t[c+1]){case"u":{o+=t.slice(a,c);let f=t.substr(c+2,4);switch(f){case"0000":o+="\\0";break;case"0007":o+="\\a";break;case"000b":o+="\\v";break;case"001b":o+="\\e";break;case"0085":o+="\\N";break;case"00a0":o+="\\_";break;case"2028":o+="\\L";break;case"2029":o+="\\P";break;default:f.substr(0,2)==="00"?o+="\\x"+f.substr(2):o+=t.substr(c,6)}c+=5,a=c+1}break;case"n":if(n||t[c+2]==='"'||t.length<s)c+=1;else{for(o+=t.slice(a,c)+`
|
|
30
30
|
|
|
31
31
|
`;t[c+2]==="\\"&&t[c+3]==="n"&&t[c+4]!=='"';)o+=`
|
|
32
32
|
`,c+=2;o+=i,t[c+2]===" "&&(o+="\\"),c+=1,a=c+1}break;default:c+=1}return o=a?o+t.slice(a):t,n?o:Xe.foldFlowLines(o,i,Xe.FOLD_QUOTED,fs(e,!1))}function Qo(r,e){if(e.options.singleQuote===!1||e.implicitKey&&r.includes(`
|
|
@@ -34,22 +34,22 @@ ${e}${r.slice(P+1,C)}`)}return x}function tf(r,e,t){let n=e,s=e+1,i=r[s];for(;i=
|
|
|
34
34
|
${t}`)+"'";return e.implicitKey?n:Xe.foldFlowLines(n,t,Xe.FOLD_FLOW,fs(e,!1))}function er(r,e){let{singleQuote:t}=e.options,n;if(t===!1)n=Wr;else{let s=r.includes('"'),i=r.includes("'");s&&!i?n=Qo:i&&!s?n=Wr:n=t?Qo:Wr}return n(r,e)}var Xo;try{Xo=new RegExp(`(^|(?<!
|
|
35
35
|
))
|
|
36
36
|
+(?!
|
|
37
|
-
|$)`,"g")}catch{Xo=/\n+(?!\n|$)/g}function us({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 er(t,n);let l=n.indent||(n.forceBlockIndent||ds(t)?" ":""),
|
|
37
|
+
|$)`,"g")}catch{Xo=/\n+(?!\n|$)/g}function us({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 er(t,n);let l=n.indent||(n.forceBlockIndent||ds(t)?" ":""),f=o==="literal"?!0:o==="folded"||e===be.Scalar.BLOCK_FOLDED?!1:e===be.Scalar.BLOCK_LITERAL?!0:!$b(t,c,l.length);if(!t)return f?`|
|
|
38
38
|
`:`>
|
|
39
|
-
`;let u,
|
|
40
|
-
`&&C!==" "&&C!==" ")break}let p=t.substring(
|
|
39
|
+
`;let u,d;for(d=t.length;d>0;--d){let C=t[d-1];if(C!==`
|
|
40
|
+
`&&C!==" "&&C!==" ")break}let p=t.substring(d),y=p.indexOf(`
|
|
41
41
|
`);y===-1?u="-":t===p||y!==p.length-1?(u="+",i&&i()):u="",p&&(t=t.slice(0,-p.length),p[p.length-1]===`
|
|
42
42
|
`&&(p=p.slice(0,-1)),p=p.replace(Xo,`$&${l}`));let m=!1,b,k=-1;for(b=0;b<t.length;++b){let C=t[b];if(C===" ")m=!0;else if(C===`
|
|
43
|
-
`)k=b;else break}let x=t.substring(0,k<b?k+1:b);x&&(t=t.substring(x.length),x=x.replace(/\n+/g,`$&${l}`));let P=(m?l?"2":"1":"")+u;if(r&&(P+=" "+a(r.replace(/ ?[\r\n]+/g," ")),s&&s()),!
|
|
43
|
+
`)k=b;else break}let x=t.substring(0,k<b?k+1:b);x&&(t=t.substring(x.length),x=x.replace(/\n+/g,`$&${l}`));let P=(m?l?"2":"1":"")+u;if(r&&(P+=" "+a(r.replace(/ ?[\r\n]+/g," ")),s&&s()),!f){let C=t.replace(/\n+/g,`
|
|
44
44
|
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),O=!1,R=fs(n,!0);o!=="folded"&&e!==be.Scalar.BLOCK_FOLDED&&(R.onOverflow=()=>{O=!0});let h=Xe.foldFlowLines(`${x}${C}${p}`,l,Xe.FOLD_BLOCK,R);if(!O)return`>${P}
|
|
45
45
|
${l}${h}`}return t=t.replace(/\n+/g,`$&${l}`),`|${P}
|
|
46
|
-
${l}${x}${t}${p}`}function
|
|
47
|
-
`)||
|
|
48
|
-
`)?er(i,e):us(r,e,t,n);if(!a&&!
|
|
46
|
+
${l}${x}${t}${p}`}function Lb(r,e,t,n){let{type:s,value:i}=r,{actualString:o,implicitKey:a,indent:c,indentStep:l,inFlow:f}=e;if(a&&i.includes(`
|
|
47
|
+
`)||f&&/[[\]{},]/.test(i))return er(i,e);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(i))return a||f||!i.includes(`
|
|
48
|
+
`)?er(i,e):us(r,e,t,n);if(!a&&!f&&s!==be.Scalar.PLAIN&&i.includes(`
|
|
49
49
|
`))return us(r,e,t,n);if(ds(i)){if(c==="")return e.forceBlockIndent=!0,us(r,e,t,n);if(a&&c===l)return er(i,e)}let u=i.replace(/\n+/g,`$&
|
|
50
|
-
${c}`);if(o){let
|
|
51
|
-
${e.indent}${a}`:a}Zo.createStringifyContext=
|
|
52
|
-
${a}:`):(b=`${b}:`,
|
|
50
|
+
${c}`);if(o){let d=m=>m.default&&m.tag!=="tag:yaml.org,2002:str"&&m.test?.test(u),{compat:p,tags:y}=e.doc.schema;if(y.some(d)||p?.some(d))return er(i,e)}return a?u:Xe.foldFlowLines(u,c,Xe.FOLD_FLOW,fs(e,!1))}function Mb(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!==be.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(a=be.Scalar.QUOTE_DOUBLE);let c=f=>{switch(f){case be.Scalar.BLOCK_FOLDED:case be.Scalar.BLOCK_LITERAL:return s||i?er(o.value,e):us(o,e,t,n);case be.Scalar.QUOTE_DOUBLE:return Wr(o.value,e);case be.Scalar.QUOTE_SINGLE:return Qo(o.value,e);case be.Scalar.PLAIN:return Lb(o,e,t,n);default:return null}},l=c(a);if(l===null){let{defaultKeyType:f,defaultStringType:u}=e.options,d=s&&f||u;if(l=c(d),l===null)throw new Error(`Unsupported default string type ${d}`)}return l}sf.stringifyString=Mb});var Vr=E(Zo=>{"use strict";var Db=ns(),Ze=j(),Bb=Kr(),jb=Yr();function Fb(r,e){let t=Object.assign({blockQuote:!0,commentString:Bb.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 qb(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(Ze.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 Ub(r,e,{anchors:t,doc:n}){if(!n.directives)return"";let s=[],i=(Ze.isScalar(r)||Ze.isCollection(r))&&r.anchor;i&&Db.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 Jb(r,e,t,n){if(Ze.isPair(r))return r.toString(e,t,n);if(Ze.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=Ze.isNode(r)?r:e.doc.createNode(r,{onTagObj:c=>s=c});s??(s=qb(e.doc.schema.tags,i));let o=Ub(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):Ze.isScalar(i)?jb.stringifyString(i,e,t,n):i.toString(e,t,n);return o?Ze.isScalar(i)||a[0]==="{"||a[0]==="["?`${o} ${a}`:`${o}
|
|
51
|
+
${e.indent}${a}`:a}Zo.createStringifyContext=Fb;Zo.stringify=Jb});var lf=E(cf=>{"use strict";var Be=j(),of=W(),af=Vr(),Gr=Kr();function Kb({key:r,value:e},t,n,s){let{allNullValues:i,doc:o,indent:a,indentStep:c,options:{commentString:l,indentSeq:f,simpleKeys:u}}=t,d=Be.isNode(r)&&r.comment||null;if(u){if(d)throw new Error("With simple keys, key nodes cannot have comments");if(Be.isCollection(r)||!Be.isNode(r)&&typeof r=="object"){let R="With simple keys, collection cannot be used as a key value";throw new Error(R)}}let p=!u&&(!r||d&&e==null&&!t.inFlow||Be.isCollection(r)||(Be.isScalar(r)?r.type===of.Scalar.BLOCK_FOLDED||r.type===of.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=af.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}`,d&&!y?b+=Gr.lineComment(b,t.indent,l(d)):m&&s&&s(),b;y&&(d=null),p?(d&&(b+=Gr.lineComment(b,t.indent,l(d))),b=`? ${b}
|
|
52
|
+
${a}:`):(b=`${b}:`,d&&(b+=Gr.lineComment(b,t.indent,l(d))));let k,x,T;Be.isNode(e)?(k=!!e.spaceBefore,x=e.commentBefore,T=e.comment):(k=!1,x=null,T=null,e&&typeof e=="object"&&(e=o.createNode(e))),t.implicitKey=!1,!p&&!d&&Be.isScalar(e)&&(t.indentAtStart=b.length+1),m=!1,!f&&c.length>=2&&!t.inFlow&&!p&&Be.isSeq(e)&&!e.flow&&!e.tag&&!e.anchor&&(t.indent=t.indent.substring(2));let P=!1,C=af.stringify(e,t,()=>P=!0,()=>m=!0),O=" ";if(d||k||x){if(O=k?`
|
|
53
53
|
`:"",x){let R=l(x);O+=`
|
|
54
54
|
${Gr.indentComment(R,t.indent)}`}C===""&&!t.inFlow?O===`
|
|
55
55
|
`&&T&&(O=`
|
|
@@ -58,81 +58,81 @@ ${Gr.indentComment(R,t.indent)}`}C===""&&!t.inFlow?O===`
|
|
|
58
58
|
${t.indent}`}else if(!p&&Be.isCollection(e)){let R=C[0],h=C.indexOf(`
|
|
59
59
|
`),S=h!==-1,I=t.inFlow??e.flow??e.items.length===0;if(S||!I){let L=!1;if(S&&(R==="&"||R==="!")){let N=C.indexOf(" ");R==="&"&&N!==-1&&N<h&&C[N+1]==="!"&&(N=C.indexOf(" ",N+1)),(N===-1||h<N)&&(L=!0)}L||(O=`
|
|
60
60
|
${t.indent}`)}}else(C===""||C[0]===`
|
|
61
|
-
`)&&(O="");return b+=O+C,t.inFlow?P&&n&&n():T&&!P?b+=Gr.lineComment(b,t.indent,l(T)):m&&s&&s(),b}
|
|
61
|
+
`)&&(O="");return b+=O+C,t.inFlow?P&&n&&n():T&&!P?b+=Gr.lineComment(b,t.indent,l(T)):m&&s&&s(),b}cf.stringifyPair=Kb});var ta=E(ea=>{"use strict";var uf=Vn("process");function Hb(r,...e){r==="debug"&&console.log(...e)}function Wb(r,e){(r==="debug"||r==="warn")&&(typeof uf.emitWarning=="function"?uf.emitWarning(e):console.warn(e))}ea.debug=Hb;ea.warn=Wb});var gs=E(hs=>{"use strict";var zr=j(),ff=W(),ps="<<",ms={identify:r=>r===ps||typeof r=="symbol"&&r.description===ps,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new ff.Scalar(Symbol(ps)),{addToJSMap:df}),stringify:()=>ps},Yb=(r,e)=>(ms.identify(e)||zr.isScalar(e)&&(!e.type||e.type===ff.Scalar.PLAIN)&&ms.identify(e.value))&&r?.doc.schema.tags.some(t=>t.tag===ms.tag&&t.default);function df(r,e,t){if(t=r&&zr.isAlias(t)?t.resolve(r.doc):t,zr.isSeq(t))for(let n of t.items)ra(r,e,n);else if(Array.isArray(t))for(let n of t)ra(r,e,n);else ra(r,e,t)}function ra(r,e,t){let n=r&&zr.isAlias(t)?t.resolve(r.doc):t;if(!zr.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}hs.addMergeToJSMap=df;hs.isMergeKey=Yb;hs.merge=ms});var sa=E(hf=>{"use strict";var Vb=ta(),pf=gs(),Gb=Vr(),mf=j(),na=ze();function zb(r,e,{key:t,value:n}){if(mf.isNode(t)&&t.addToJSMap)t.addToJSMap(r,e,n);else if(pf.isMergeKey(r,t))pf.addMergeToJSMap(r,e,n);else{let s=na.toJS(t,"",r);if(e instanceof Map)e.set(s,na.toJS(n,s,r));else if(e instanceof Set)e.add(s);else{let i=Qb(t,s,r),o=na.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 Qb(r,e,t){if(e===null)return"";if(typeof e!="object")return String(e);if(mf.isNode(r)&&t?.doc){let n=Gb.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)+'..."'),Vb.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)}hf.addPairToJSMap=zb});var et=E(ia=>{"use strict";var gf=Jr(),Xb=lf(),Zb=sa(),ys=j();function ew(r,e,t){let n=gf.createNode(r,void 0,t),s=gf.createNode(e,void 0,t);return new bs(n,s)}var bs=class r{constructor(e,t=null){Object.defineProperty(this,ys.NODE_TYPE,{value:ys.PAIR}),this.key=e,this.value=t}clone(e){let{key:t,value:n}=this;return ys.isNode(t)&&(t=t.clone(e)),ys.isNode(n)&&(n=n.clone(e)),new r(t,n)}toJSON(e,t){let n=t?.mapAsMap?new Map:{};return Zb.addPairToJSMap(t,n,this)}toString(e,t,n){return e?.doc?Xb.stringifyPair(this,e,t,n):JSON.stringify(this)}};ia.Pair=bs;ia.createPair=ew});var oa=E(bf=>{"use strict";var xt=j(),yf=Vr(),ws=Kr();function tw(r,e,t){return(e.inFlow??r.flow?nw:rw)(r,e,t)}function rw({comment:r,items:e},t,{blockItemPrefix:n,flowChars:s,itemIndent:i,onChompKeep:o,onComment:a}){let{indent:c,options:{commentString:l}}=t,f=Object.assign({},t,{indent:i,type:null}),u=!1,d=[];for(let y=0;y<e.length;++y){let m=e[y],b=null;if(xt.isNode(m))!u&&m.spaceBefore&&d.push(""),vs(t,d,m.commentBefore,u),m.comment&&(b=m.comment);else if(xt.isPair(m)){let x=xt.isNode(m.key)?m.key:null;x&&(!u&&x.spaceBefore&&d.push(""),vs(t,d,x.commentBefore,u))}u=!1;let k=yf.stringify(m,f,()=>b=null,()=>u=!0);b&&(k+=ws.lineComment(k,i,l(b))),u&&b&&(u=!1),d.push(n+k)}let p;if(d.length===0)p=s.start+s.end;else{p=d[0];for(let y=1;y<d.length;++y){let m=d[y];p+=m?`
|
|
62
62
|
${c}${m}`:`
|
|
63
63
|
`}}return r?(p+=`
|
|
64
|
-
`+ws.indentComment(l(r),c),a&&a()):u&&o&&o(),p}function
|
|
65
|
-
`))&&(l=!0),u.push(k),
|
|
64
|
+
`+ws.indentComment(l(r),c),a&&a()):u&&o&&o(),p}function nw({items:r},e,{flowChars:t,itemIndent:n}){let{indent:s,indentStep:i,flowCollectionPadding:o,options:{commentString:a}}=e;n+=i;let c=Object.assign({},e,{indent:n,inFlow:!0,type:null}),l=!1,f=0,u=[];for(let y=0;y<r.length;++y){let m=r[y],b=null;if(xt.isNode(m))m.spaceBefore&&u.push(""),vs(e,u,m.commentBefore,!1),m.comment&&(b=m.comment);else if(xt.isPair(m)){let x=xt.isNode(m.key)?m.key:null;x&&(x.spaceBefore&&u.push(""),vs(e,u,x.commentBefore,!1),x.comment&&(l=!0));let T=xt.isNode(m.value)?m.value:null;T?(T.comment&&(b=T.comment),T.commentBefore&&(l=!0)):m.value==null&&x?.comment&&(b=x.comment)}b&&(l=!0);let k=yf.stringify(m,c,()=>b=null);y<r.length-1&&(k+=","),b&&(k+=ws.lineComment(k,n,a(b))),!l&&(u.length>f||k.includes(`
|
|
65
|
+
`))&&(l=!0),u.push(k),f=u.length}let{start:d,end:p}=t;if(u.length===0)return d+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=d;for(let m of u)y+=m?`
|
|
66
66
|
${i}${s}${m}`:`
|
|
67
67
|
`;return`${y}
|
|
68
|
-
${s}${p}`}else return`${
|
|
69
|
-
`:" ")}return
|
|
68
|
+
${s}${p}`}else return`${d}${o}${u.join(" ")}${o}${p}`}function vs({indent:r,options:{commentString:e}},t,n,s){if(n&&s&&(n=n.replace(/^\n+/,"")),n){let i=ws.indentComment(e(n),r);t.push(i.trimStart())}}bf.stringifyCollection=tw});var rt=E(ca=>{"use strict";var sw=oa(),iw=sa(),ow=as(),tt=j(),Ss=et(),aw=W();function Qr(r,e){let t=tt.isScalar(e)?e.value:e;for(let n of r)if(tt.isPair(n)&&(n.key===e||n.key===t||tt.isScalar(n.key)&&n.key.value===t))return n}var aa=class extends ow.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(tt.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(Ss.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;tt.isPair(e)?n=e:!e||typeof e!="object"||!("key"in e)?n=new Ss.Pair(e,e?.value):n=new Ss.Pair(e.key,e.value);let s=Qr(this.items,n.key),i=this.schema?.sortMapEntries;if(s){if(!t)throw new Error(`Key ${n.key} already set`);tt.isScalar(s.value)&&aw.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=Qr(this.items,e);return t?this.items.splice(this.items.indexOf(t),1).length>0:!1}get(e,t){let s=Qr(this.items,e)?.value;return(!t&&tt.isScalar(s)?s.value:s)??void 0}has(e){return!!Qr(this.items,e)}set(e,t){this.add(new Ss.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)iw.addPairToJSMap(t,s,i);return s}toString(e,t,n){if(!e)return JSON.stringify(this);for(let s of this.items)if(!tt.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})),sw.stringifyCollection(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:n,onComment:t})}};ca.YAMLMap=aa;ca.findPair=Qr});var tr=E(vf=>{"use strict";var cw=j(),wf=rt(),lw={collection:"map",default:!0,nodeClass:wf.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(r,e){return cw.isMap(r)||e("Expected a mapping for this tag"),r},createNode:(r,e,t)=>wf.YAMLMap.from(r,e,t)};vf.map=lw});var nt=E(Sf=>{"use strict";var uw=Jr(),fw=oa(),dw=as(),xs=j(),pw=W(),mw=ze(),la=class extends dw.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(xs.SEQ,e),this.items=[]}add(e){this.items.push(e)}delete(e){let t=ks(e);return typeof t!="number"?!1:this.items.splice(t,1).length>0}get(e,t){let n=ks(e);if(typeof n!="number")return;let s=this.items[n];return!t&&xs.isScalar(s)?s.value:s}has(e){let t=ks(e);return typeof t=="number"&&t<this.items.length}set(e,t){let n=ks(e);if(typeof n!="number")throw new Error(`Expected a valid index, not ${e}.`);let s=this.items[n];xs.isScalar(s)&&pw.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(mw.toJS(i,String(s++),t));return n}toString(e,t,n){return e?fw.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(uw.createNode(a,void 0,n))}}return i}};function ks(r){let e=xs.isScalar(r)?r.value:r;return e&&typeof e=="string"&&(e=Number(e)),typeof e=="number"&&Number.isInteger(e)&&e>=0?e:null}Sf.YAMLSeq=la});var rr=E(xf=>{"use strict";var hw=j(),kf=nt(),gw={collection:"seq",default:!0,nodeClass:kf.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(r,e){return hw.isSeq(r)||e("Expected a sequence for this tag"),r},createNode:(r,e,t)=>kf.YAMLSeq.from(r,e,t)};xf.seq=gw});var Xr=E(Ef=>{"use strict";var yw=Yr(),bw={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),yw.stringifyString(r,e,t,n)}};Ef.string=bw});var Es=E(Pf=>{"use strict";var Af=W(),Tf={identify:r=>r==null,createNode:()=>new Af.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new Af.Scalar(null),stringify:({source:r},e)=>typeof r=="string"&&Tf.test.test(r)?r:e.options.nullStr};Pf.nullTag=Tf});var ua=E(Cf=>{"use strict";var ww=W(),Of={identify:r=>typeof r=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:r=>new ww.Scalar(r[0]==="t"||r[0]==="T"),stringify({source:r,value:e},t){if(r&&Of.test.test(r)){let n=r[0]==="t"||r[0]==="T";if(e===n)return r}return e?t.options.trueStr:t.options.falseStr}};Cf.boolTag=Of});var nr=E(_f=>{"use strict";function vw({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}_f.stringifyNumber=vw});var da=E(As=>{"use strict";var Sw=W(),fa=nr(),kw={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:fa.stringifyNumber},xw={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():fa.stringifyNumber(r)}},Ew={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 Sw.Scalar(parseFloat(r)),t=r.indexOf(".");return t!==-1&&r[r.length-1]==="0"&&(e.minFractionDigits=r.length-t-1),e},stringify:fa.stringifyNumber};As.float=Ew;As.floatExp=xw;As.floatNaN=kw});var ma=E(Ps=>{"use strict";var Rf=nr(),Ts=r=>typeof r=="bigint"||Number.isInteger(r),pa=(r,e,t,{intAsBigInt:n})=>n?BigInt(r):parseInt(r.substring(e),t);function Nf(r,e,t){let{value:n}=r;return Ts(n)&&n>=0?t+n.toString(e):Rf.stringifyNumber(r)}var Aw={identify:r=>Ts(r)&&r>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(r,e,t)=>pa(r,2,8,t),stringify:r=>Nf(r,8,"0o")},Tw={identify:Ts,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(r,e,t)=>pa(r,0,10,t),stringify:Rf.stringifyNumber},Pw={identify:r=>Ts(r)&&r>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(r,e,t)=>pa(r,2,16,t),stringify:r=>Nf(r,16,"0x")};Ps.int=Tw;Ps.intHex=Pw;Ps.intOct=Aw});var $f=E(If=>{"use strict";var Ow=tr(),Cw=Es(),_w=rr(),Rw=Xr(),Nw=ua(),ha=da(),ga=ma(),Iw=[Ow.map,_w.seq,Rw.string,Cw.nullTag,Nw.boolTag,ga.intOct,ga.int,ga.intHex,ha.floatNaN,ha.floatExp,ha.float];If.schema=Iw});var Df=E(Mf=>{"use strict";var $w=W(),Lw=tr(),Mw=rr();function Lf(r){return typeof r=="bigint"||Number.isInteger(r)}var Os=({value:r})=>JSON.stringify(r),Dw=[{identify:r=>typeof r=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:r=>r,stringify:Os},{identify:r=>r==null,createNode:()=>new $w.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:Os},{identify:r=>typeof r=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:r=>r==="true",stringify:Os},{identify:Lf,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})=>Lf(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:Os}],Bw={default:!0,tag:"",test:/^/,resolve(r,e){return e(`Unresolved plain scalar ${JSON.stringify(r)}`),r}},jw=[Lw.map,Mw.seq].concat(Dw,Bw);Mf.schema=jw});var ba=E(Bf=>{"use strict";var Zr=Vn("buffer"),ya=W(),Fw=Yr(),qw={identify:r=>r instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(r,e){if(typeof Zr.Buffer=="function")return Zr.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 Zr.Buffer=="function")a=o instanceof Zr.Buffer?o.toString("base64"):Zr.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=ya.Scalar.BLOCK_LITERAL),e!==ya.Scalar.QUOTE_DOUBLE){let c=Math.max(n.options.lineWidth-n.indent.length,n.options.minContentWidth),l=Math.ceil(a.length/c),f=new Array(l);for(let u=0,d=0;u<l;++u,d+=c)f[u]=a.substr(d,c);a=f.join(e===ya.Scalar.BLOCK_LITERAL?`
|
|
69
|
+
`:" ")}return Fw.stringifyString({comment:r,type:e,value:a},n,s,i)}};Bf.binary=qw});var Rs=E(_s=>{"use strict";var Cs=j(),wa=et(),Uw=W(),Jw=nt();function jf(r,e){if(Cs.isSeq(r))for(let t=0;t<r.items.length;++t){let n=r.items[t];if(!Cs.isPair(n)){if(Cs.isMap(n)){n.items.length>1&&e("Each pair must have its own sequence indicator");let s=n.items[0]||new wa.Pair(new Uw.Scalar(null));if(n.commentBefore&&(s.key.commentBefore=s.key.commentBefore?`${n.commentBefore}
|
|
70
70
|
${s.key.commentBefore}`:n.commentBefore),n.comment){let i=s.value??s.key;i.comment=i.comment?`${n.comment}
|
|
71
|
-
${i.comment}`:n.comment}n=s}r.items[t]=Cs.isPair(n)?n:new wa.Pair(n)}}else e("Expected a sequence for this tag");return r}function jf(r,e,t){let{replacer:n}=t,s=new Uw.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(wa.createPair(a,c,t))}return s}var Jw={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Bf,createNode:jf};_s.createPairs=jf;_s.pairs=Jw;_s.resolvePairs=Bf});var ka=E(Sa=>{"use strict";var Ff=j(),va=ze(),en=rt(),Kw=nt(),qf=Rs(),Et=class r extends Kw.YAMLSeq{constructor(){super(),this.add=en.YAMLMap.prototype.add.bind(this),this.delete=en.YAMLMap.prototype.delete.bind(this),this.get=en.YAMLMap.prototype.get.bind(this),this.has=en.YAMLMap.prototype.has.bind(this),this.set=en.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(Ff.isPair(s)?(i=va.toJS(s.key,"",t),o=va.toJS(s.value,i,t)):i=va.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=qf.createPairs(e,t,n),i=new this;return i.items=s.items,i}};Et.tag="tag:yaml.org,2002:omap";var Hw={collection:"seq",identify:r=>r instanceof Map,nodeClass:Et,default:!1,tag:"tag:yaml.org,2002:omap",resolve(r,e){let t=qf.resolvePairs(r,e),n=[];for(let{key:s}of t.items)Ff.isScalar(s)&&(n.includes(s.value)?e(`Ordered maps must not include duplicate keys: ${s.value}`):n.push(s.value));return Object.assign(new Et,t)},createNode:(r,e,t)=>Et.from(r,e,t)};Sa.YAMLOMap=Et;Sa.omap=Hw});var Wf=E(xa=>{"use strict";var Uf=W();function Jf({value:r,source:e},t){return e&&(r?Kf:Hf).test.test(e)?e:r?t.options.trueStr:t.options.falseStr}var Kf={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 Uf.Scalar(!0),stringify:Jf},Hf={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 Uf.Scalar(!1),stringify:Jf};xa.falseTag=Hf;xa.trueTag=Kf});var Yf=E(Ns=>{"use strict";var Ww=W(),Ea=nr(),Yw={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:Ea.stringifyNumber},Vw={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():Ea.stringifyNumber(r)}},Gw={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 Ww.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:Ea.stringifyNumber};Ns.float=Gw;Ns.floatExp=Vw;Ns.floatNaN=Yw});var Gf=E(rn=>{"use strict";var Vf=nr(),tn=r=>typeof r=="bigint"||Number.isInteger(r);function Is(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 Aa(r,e,t){let{value:n}=r;if(tn(n)){let s=n.toString(e);return n<0?"-"+t+s.substr(1):t+s}return Vf.stringifyNumber(r)}var zw={identify:tn,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(r,e,t)=>Is(r,2,2,t),stringify:r=>Aa(r,2,"0b")},Qw={identify:tn,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(r,e,t)=>Is(r,1,8,t),stringify:r=>Aa(r,8,"0")},Xw={identify:tn,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(r,e,t)=>Is(r,0,10,t),stringify:Vf.stringifyNumber},Zw={identify:tn,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(r,e,t)=>Is(r,2,16,t),stringify:r=>Aa(r,16,"0x")};rn.int=Xw;rn.intBin=zw;rn.intHex=Zw;rn.intOct=Qw});var Pa=E(Ta=>{"use strict";var Ms=j(),$s=et(),Ls=rt(),At=class r extends Ls.YAMLMap{constructor(e){super(e),this.tag=r.tag}add(e){let t;Ms.isPair(e)?t=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?t=new $s.Pair(e.key,null):t=new $s.Pair(e,null),Ls.findPair(this.items,t.key)||this.items.push(t)}get(e,t){let n=Ls.findPair(this.items,e);return!t&&Ms.isPair(n)?Ms.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=Ls.findPair(this.items,e);n&&!t?this.items.splice(this.items.indexOf(n),1):!n&&t&&this.items.push(new $s.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($s.createPair(o,null,n));return i}};At.tag="tag:yaml.org,2002:set";var ev={collection:"map",identify:r=>r instanceof Set,nodeClass:At,default:!1,tag:"tag:yaml.org,2002:set",createNode:(r,e,t)=>At.from(r,e,t),resolve(r,e){if(Ms.isMap(r)){if(r.hasAllNullValues(!0))return Object.assign(new At,r);e("Set items must all have null values")}else e("Expected a mapping for this tag");return r}};Ta.YAMLSet=At;Ta.set=ev});var Ca=E(Ds=>{"use strict";var tv=nr();function Oa(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 zf(r){let{value:e}=r,t=o=>o;if(typeof e=="bigint")t=o=>BigInt(o);else if(isNaN(e)||!isFinite(e))return tv.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 rv={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})=>Oa(r,t),stringify:zf},nv={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=>Oa(r,!1),stringify:zf},Qf={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(Qf.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=Oa(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$/,"")??""};Ds.floatTime=nv;Ds.intTime=rv;Ds.timestamp=Qf});var ed=E(Zf=>{"use strict";var sv=tr(),iv=Es(),ov=rr(),av=Xr(),cv=ba(),Xf=Wf(),_a=Yf(),Bs=Gf(),lv=gs(),uv=ka(),fv=Rs(),dv=Pa(),Ra=Ca(),pv=[sv.map,ov.seq,av.string,iv.nullTag,Xf.trueTag,Xf.falseTag,Bs.intBin,Bs.intOct,Bs.int,Bs.intHex,_a.floatNaN,_a.floatExp,_a.float,cv.binary,lv.merge,uv.omap,fv.pairs,dv.set,Ra.intTime,Ra.floatTime,Ra.timestamp];Zf.schema=pv});var ud=E($a=>{"use strict";var sd=tr(),mv=Es(),id=rr(),hv=Xr(),gv=ua(),Na=da(),Ia=ma(),yv=If(),bv=Mf(),od=ba(),nn=gs(),ad=ka(),cd=Rs(),td=ed(),ld=Pa(),js=Ca(),rd=new Map([["core",yv.schema],["failsafe",[sd.map,id.seq,hv.string]],["json",bv.schema],["yaml11",td.schema],["yaml-1.1",td.schema]]),nd={binary:od.binary,bool:gv.boolTag,float:Na.float,floatExp:Na.floatExp,floatNaN:Na.floatNaN,floatTime:js.floatTime,int:Ia.int,intHex:Ia.intHex,intOct:Ia.intOct,intTime:js.intTime,map:sd.map,merge:nn.merge,null:mv.nullTag,omap:ad.omap,pairs:cd.pairs,seq:id.seq,set:ld.set,timestamp:js.timestamp},wv={"tag:yaml.org,2002:binary":od.binary,"tag:yaml.org,2002:merge":nn.merge,"tag:yaml.org,2002:omap":ad.omap,"tag:yaml.org,2002:pairs":cd.pairs,"tag:yaml.org,2002:set":ld.set,"tag:yaml.org,2002:timestamp":js.timestamp};function vv(r,e,t){let n=rd.get(e);if(n&&!r)return t&&!n.includes(nn.merge)?n.concat(nn.merge):n.slice();let s=n;if(!s)if(Array.isArray(r))s=[];else{let i=Array.from(rd.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(nn.merge)),s.reduce((i,o)=>{let a=typeof o=="string"?nd[o]:o;if(!a){let c=JSON.stringify(o),l=Object.keys(nd).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},[])}$a.coreKnownTags=wv;$a.getTags=vv});var Da=E(fd=>{"use strict";var La=j(),Sv=tr(),kv=rr(),xv=Xr(),Fs=ud(),Ev=(r,e)=>r.key<e.key?-1:r.key>e.key?1:0,Ma=class r{constructor({compat:e,customTags:t,merge:n,resolveKnownTags:s,schema:i,sortMapEntries:o,toStringDefaults:a}){this.compat=Array.isArray(e)?Fs.getTags(e,"compat"):e?Fs.getTags(null,e):null,this.name=typeof i=="string"&&i||"core",this.knownTags=s?Fs.coreKnownTags:{},this.tags=Fs.getTags(t,this.name,n),this.toStringOptions=a??null,Object.defineProperty(this,La.MAP,{value:Sv.map}),Object.defineProperty(this,La.SCALAR,{value:xv.string}),Object.defineProperty(this,La.SEQ,{value:kv.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?Ev:null}clone(){let e=Object.create(r.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}};fd.Schema=Ma});var pd=E(dd=>{"use strict";var Av=j(),Ba=Vr(),sn=Kr();function Tv(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=Ba.createStringifyContext(r,e),{commentString:i}=s.options;if(r.commentBefore){t.length!==1&&t.unshift("");let c=i(r.commentBefore);t.unshift(sn.indentComment(c,""))}let o=!1,a=null;if(r.contents){if(Av.isNode(r.contents)){if(r.contents.spaceBefore&&n&&t.push(""),r.contents.commentBefore){let d=i(r.contents.commentBefore);t.push(sn.indentComment(d,""))}s.forceBlockIndent=!!r.comment,a=r.contents.comment}let c=a?void 0:()=>o=!0,l=Ba.stringify(r.contents,s,()=>a=null,c);a&&(l+=sn.lineComment(l,"",i(a))),(l[0]==="|"||l[0]===">")&&t[t.length-1]==="---"?t[t.length-1]=`--- ${l}`:t.push(l)}else t.push(Ba.stringify(r.contents,s));if(r.directives?.docEnd)if(r.comment){let c=i(r.comment);c.includes(`
|
|
71
|
+
${i.comment}`:n.comment}n=s}r.items[t]=Cs.isPair(n)?n:new wa.Pair(n)}}else e("Expected a sequence for this tag");return r}function Ff(r,e,t){let{replacer:n}=t,s=new Jw.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(wa.createPair(a,c,t))}return s}var Kw={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:jf,createNode:Ff};_s.createPairs=Ff;_s.pairs=Kw;_s.resolvePairs=jf});var ka=E(Sa=>{"use strict";var qf=j(),va=ze(),en=rt(),Hw=nt(),Uf=Rs(),Et=class r extends Hw.YAMLSeq{constructor(){super(),this.add=en.YAMLMap.prototype.add.bind(this),this.delete=en.YAMLMap.prototype.delete.bind(this),this.get=en.YAMLMap.prototype.get.bind(this),this.has=en.YAMLMap.prototype.has.bind(this),this.set=en.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(qf.isPair(s)?(i=va.toJS(s.key,"",t),o=va.toJS(s.value,i,t)):i=va.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=Uf.createPairs(e,t,n),i=new this;return i.items=s.items,i}};Et.tag="tag:yaml.org,2002:omap";var Ww={collection:"seq",identify:r=>r instanceof Map,nodeClass:Et,default:!1,tag:"tag:yaml.org,2002:omap",resolve(r,e){let t=Uf.resolvePairs(r,e),n=[];for(let{key:s}of t.items)qf.isScalar(s)&&(n.includes(s.value)?e(`Ordered maps must not include duplicate keys: ${s.value}`):n.push(s.value));return Object.assign(new Et,t)},createNode:(r,e,t)=>Et.from(r,e,t)};Sa.YAMLOMap=Et;Sa.omap=Ww});var Yf=E(xa=>{"use strict";var Jf=W();function Kf({value:r,source:e},t){return e&&(r?Hf:Wf).test.test(e)?e:r?t.options.trueStr:t.options.falseStr}var Hf={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 Jf.Scalar(!0),stringify:Kf},Wf={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 Jf.Scalar(!1),stringify:Kf};xa.falseTag=Wf;xa.trueTag=Hf});var Vf=E(Ns=>{"use strict";var Yw=W(),Ea=nr(),Vw={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:Ea.stringifyNumber},Gw={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():Ea.stringifyNumber(r)}},zw={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 Yw.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:Ea.stringifyNumber};Ns.float=zw;Ns.floatExp=Gw;Ns.floatNaN=Vw});var zf=E(rn=>{"use strict";var Gf=nr(),tn=r=>typeof r=="bigint"||Number.isInteger(r);function Is(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 Aa(r,e,t){let{value:n}=r;if(tn(n)){let s=n.toString(e);return n<0?"-"+t+s.substr(1):t+s}return Gf.stringifyNumber(r)}var Qw={identify:tn,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(r,e,t)=>Is(r,2,2,t),stringify:r=>Aa(r,2,"0b")},Xw={identify:tn,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(r,e,t)=>Is(r,1,8,t),stringify:r=>Aa(r,8,"0")},Zw={identify:tn,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(r,e,t)=>Is(r,0,10,t),stringify:Gf.stringifyNumber},ev={identify:tn,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(r,e,t)=>Is(r,2,16,t),stringify:r=>Aa(r,16,"0x")};rn.int=Zw;rn.intBin=Qw;rn.intHex=ev;rn.intOct=Xw});var Pa=E(Ta=>{"use strict";var Ms=j(),$s=et(),Ls=rt(),At=class r extends Ls.YAMLMap{constructor(e){super(e),this.tag=r.tag}add(e){let t;Ms.isPair(e)?t=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?t=new $s.Pair(e.key,null):t=new $s.Pair(e,null),Ls.findPair(this.items,t.key)||this.items.push(t)}get(e,t){let n=Ls.findPair(this.items,e);return!t&&Ms.isPair(n)?Ms.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=Ls.findPair(this.items,e);n&&!t?this.items.splice(this.items.indexOf(n),1):!n&&t&&this.items.push(new $s.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($s.createPair(o,null,n));return i}};At.tag="tag:yaml.org,2002:set";var tv={collection:"map",identify:r=>r instanceof Set,nodeClass:At,default:!1,tag:"tag:yaml.org,2002:set",createNode:(r,e,t)=>At.from(r,e,t),resolve(r,e){if(Ms.isMap(r)){if(r.hasAllNullValues(!0))return Object.assign(new At,r);e("Set items must all have null values")}else e("Expected a mapping for this tag");return r}};Ta.YAMLSet=At;Ta.set=tv});var Ca=E(Ds=>{"use strict";var rv=nr();function Oa(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 Qf(r){let{value:e}=r,t=o=>o;if(typeof e=="bigint")t=o=>BigInt(o);else if(isNaN(e)||!isFinite(e))return rv.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 nv={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})=>Oa(r,t),stringify:Qf},sv={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=>Oa(r,!1),stringify:Qf},Xf={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(Xf.test);if(!e)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,t,n,s,i,o,a]=e.map(Number),c=e[7]?Number((e[7]+"00").substr(1,3)):0,l=Date.UTC(t,n-1,s,i||0,o||0,a||0,c),f=e[8];if(f&&f!=="Z"){let u=Oa(f,!1);Math.abs(u)<30&&(u*=60),l-=6e4*u}return new Date(l)},stringify:({value:r})=>r?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};Ds.floatTime=sv;Ds.intTime=nv;Ds.timestamp=Xf});var td=E(ed=>{"use strict";var iv=tr(),ov=Es(),av=rr(),cv=Xr(),lv=ba(),Zf=Yf(),_a=Vf(),Bs=zf(),uv=gs(),fv=ka(),dv=Rs(),pv=Pa(),Ra=Ca(),mv=[iv.map,av.seq,cv.string,ov.nullTag,Zf.trueTag,Zf.falseTag,Bs.intBin,Bs.intOct,Bs.int,Bs.intHex,_a.floatNaN,_a.floatExp,_a.float,lv.binary,uv.merge,fv.omap,dv.pairs,pv.set,Ra.intTime,Ra.floatTime,Ra.timestamp];ed.schema=mv});var fd=E($a=>{"use strict";var id=tr(),hv=Es(),od=rr(),gv=Xr(),yv=ua(),Na=da(),Ia=ma(),bv=$f(),wv=Df(),ad=ba(),nn=gs(),cd=ka(),ld=Rs(),rd=td(),ud=Pa(),js=Ca(),nd=new Map([["core",bv.schema],["failsafe",[id.map,od.seq,gv.string]],["json",wv.schema],["yaml11",rd.schema],["yaml-1.1",rd.schema]]),sd={binary:ad.binary,bool:yv.boolTag,float:Na.float,floatExp:Na.floatExp,floatNaN:Na.floatNaN,floatTime:js.floatTime,int:Ia.int,intHex:Ia.intHex,intOct:Ia.intOct,intTime:js.intTime,map:id.map,merge:nn.merge,null:hv.nullTag,omap:cd.omap,pairs:ld.pairs,seq:od.seq,set:ud.set,timestamp:js.timestamp},vv={"tag:yaml.org,2002:binary":ad.binary,"tag:yaml.org,2002:merge":nn.merge,"tag:yaml.org,2002:omap":cd.omap,"tag:yaml.org,2002:pairs":ld.pairs,"tag:yaml.org,2002:set":ud.set,"tag:yaml.org,2002:timestamp":js.timestamp};function Sv(r,e,t){let n=nd.get(e);if(n&&!r)return t&&!n.includes(nn.merge)?n.concat(nn.merge):n.slice();let s=n;if(!s)if(Array.isArray(r))s=[];else{let i=Array.from(nd.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(nn.merge)),s.reduce((i,o)=>{let a=typeof o=="string"?sd[o]:o;if(!a){let c=JSON.stringify(o),l=Object.keys(sd).map(f=>JSON.stringify(f)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return i.includes(a)||i.push(a),i},[])}$a.coreKnownTags=vv;$a.getTags=Sv});var Da=E(dd=>{"use strict";var La=j(),kv=tr(),xv=rr(),Ev=Xr(),Fs=fd(),Av=(r,e)=>r.key<e.key?-1:r.key>e.key?1:0,Ma=class r{constructor({compat:e,customTags:t,merge:n,resolveKnownTags:s,schema:i,sortMapEntries:o,toStringDefaults:a}){this.compat=Array.isArray(e)?Fs.getTags(e,"compat"):e?Fs.getTags(null,e):null,this.name=typeof i=="string"&&i||"core",this.knownTags=s?Fs.coreKnownTags:{},this.tags=Fs.getTags(t,this.name,n),this.toStringOptions=a??null,Object.defineProperty(this,La.MAP,{value:kv.map}),Object.defineProperty(this,La.SCALAR,{value:Ev.string}),Object.defineProperty(this,La.SEQ,{value:xv.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?Av:null}clone(){let e=Object.create(r.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}};dd.Schema=Ma});var md=E(pd=>{"use strict";var Tv=j(),Ba=Vr(),sn=Kr();function Pv(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=Ba.createStringifyContext(r,e),{commentString:i}=s.options;if(r.commentBefore){t.length!==1&&t.unshift("");let c=i(r.commentBefore);t.unshift(sn.indentComment(c,""))}let o=!1,a=null;if(r.contents){if(Tv.isNode(r.contents)){if(r.contents.spaceBefore&&n&&t.push(""),r.contents.commentBefore){let f=i(r.contents.commentBefore);t.push(sn.indentComment(f,""))}s.forceBlockIndent=!!r.comment,a=r.contents.comment}let c=a?void 0:()=>o=!0,l=Ba.stringify(r.contents,s,()=>a=null,c);a&&(l+=sn.lineComment(l,"",i(a))),(l[0]==="|"||l[0]===">")&&t[t.length-1]==="---"?t[t.length-1]=`--- ${l}`:t.push(l)}else t.push(Ba.stringify(r.contents,s));if(r.directives?.docEnd)if(r.comment){let c=i(r.comment);c.includes(`
|
|
72
72
|
`)?(t.push("..."),t.push(sn.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(sn.indentComment(i(c),"")))}return t.join(`
|
|
73
73
|
`)+`
|
|
74
|
-
`}
|
|
74
|
+
`}pd.stringifyDocument=Pv});var on=E(hd=>{"use strict";var Ov=Ur(),sr=as(),pe=j(),Cv=et(),_v=ze(),Rv=Da(),Nv=md(),ja=ns(),Iv=Jo(),$v=Jr(),Fa=Uo(),qa=class r{constructor(e,t,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,pe.NODE_TYPE,{value:pe.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 Fa.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,{[pe.NODE_TYPE]:{value:pe.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=pe.isNode(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){ir(this.contents)&&this.contents.add(e)}addIn(e,t){ir(this.contents)&&this.contents.addIn(e,t)}createAlias(e,t){if(!e.anchor){let n=ja.anchorNames(this);e.anchor=!t||n.has(t)?ja.findNewAnchor(t||"a",n):t}return new Ov.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=x=>typeof x=="number"||x instanceof String||x instanceof Number,k=t.filter(b).map(String);k.length>0&&(t=t.concat(k)),s=t}else n===void 0&&t&&(n=t,t=void 0);let{aliasDuplicateObjects:i,anchorPrefix:o,flow:a,keepUndefined:c,onTagObj:l,tag:f}=n??{},{onAnchor:u,setAnchors:d,sourceObjects:p}=ja.createNodeAnchors(this,o||"a"),y={aliasDuplicateObjects:i??!0,keepUndefined:c??!1,onAnchor:u,onTagObj:l,replacer:s,schema:this.schema,sourceObjects:p},m=$v.createNode(e,f,y);return a&&pe.isCollection(m)&&(m.flow=!0),d(),m}createPair(e,t,n={}){let s=this.createNode(e,null,n),i=this.createNode(t,null,n);return new Cv.Pair(s,i)}delete(e){return ir(this.contents)?this.contents.delete(e):!1}deleteIn(e){return sr.isEmptyPath(e)?this.contents==null?!1:(this.contents=null,!0):ir(this.contents)?this.contents.deleteIn(e):!1}get(e,t){return pe.isCollection(this.contents)?this.contents.get(e,t):void 0}getIn(e,t){return sr.isEmptyPath(e)?!t&&pe.isScalar(this.contents)?this.contents.value:this.contents:pe.isCollection(this.contents)?this.contents.getIn(e,t):void 0}has(e){return pe.isCollection(this.contents)?this.contents.has(e):!1}hasIn(e){return sr.isEmptyPath(e)?this.contents!==void 0:pe.isCollection(this.contents)?this.contents.hasIn(e):!1}set(e,t){this.contents==null?this.contents=sr.collectionFromPath(this.schema,[e],t):ir(this.contents)&&this.contents.set(e,t)}setIn(e,t){sr.isEmptyPath(e)?this.contents=t:this.contents==null?this.contents=sr.collectionFromPath(this.schema,Array.from(e),t):ir(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 Fa.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 Fa.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 Rv.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=_v.toJS(this.contents,t??"",a);if(typeof i=="function")for(let{count:l,res:f}of a.anchors.values())i(f,l);return typeof o=="function"?Iv.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 Nv.stringifyDocument(this,e)}};function ir(r){if(pe.isCollection(r))return!0;throw new Error("Expected a YAML collection as document contents")}hd.Document=qa});var ln=E(cn=>{"use strict";var an=class extends Error{constructor(e,t,n,s){super(),this.name=e,this.code=n,this.message=s,this.pos=t}},Ua=class extends an{constructor(e,t,n){super("YAMLParseError",e,t,n)}},Ja=class extends an{constructor(e,t,n){super("YAMLWarning",e,t,n)}},Lv=(r,e)=>t=>{if(t.pos[0]===-1)return;t.linePos=t.pos.map(a=>e.linePos(a));let{line:n,col:s}=t.linePos[0];t.message+=` at line ${n}, column ${s}`;let i=s-1,o=r.substring(e.lineStarts[n-1],e.lineStarts[n]).replace(/[\n\r]+$/,"");if(i>=60&&o.length>80){let a=Math.min(i-39,o.length-79);o="\u2026"+o.substring(a),i-=a-1}if(o.length>80&&(o=o.substring(0,79)+"\u2026"),n>1&&/^ *$/.test(o.substring(0,i))){let a=r.substring(e.lineStarts[n-2],e.lineStarts[n-1]);a.length>80&&(a=a.substring(0,79)+`\u2026
|
|
75
75
|
`),o=a+o}if(/[^ ]/.test(o)){let a=1,c=t.linePos[1];c?.line===n&&c.col>s&&(a=Math.max(1,Math.min(c.col-s,80-i)));let l=" ".repeat(i)+"^".repeat(a);t.message+=`:
|
|
76
76
|
|
|
77
77
|
${o}
|
|
78
78
|
${l}
|
|
79
|
-
`}};cn.YAMLError=an;cn.YAMLParseError=Ua;cn.YAMLWarning=Ja;cn.prettifyError
|
|
80
|
-
`))return!0;if(r.end){for(let e of r.end)if(e.type==="newline")return!0}return!1;case"flow-collection":for(let e of r.items){for(let t of e.start)if(t.type==="newline")return!0;if(e.sep){for(let t of e.sep)if(t.type==="newline")return!0}if(Ka(e.key)||Ka(e.value))return!0}return!1;default:return!0}}
|
|
81
|
-
`+m.comment:a.comment=m.comment);continue}(m.newlineAfterProp||
|
|
82
|
-
`+T.comment:x.comment=T.comment);let P=new
|
|
83
|
-
`+O.comment:l.comment=O.comment),u=O.end;continue}!o&&t.options.strict&&
|
|
84
|
-
`+R:h.comment=R,O.comment=O.comment.substring(R.length+1)}}if(!o&&!P&&!O.found){let R=C?r(t,C,O,s):e(t,O.end,P,null,O,s);l.items.push(R),u=R.range[2],Va(C)&&s(R.range,"BLOCK_IN_FLOW",Ya)}else{t.atKey=!0;let R=O.end,h=T?r(t,T,O,s):e(t,R,x,null,O,s);Va(T)&&s(h.range,"BLOCK_IN_FLOW",Ya),t.atKey=!1;let S=
|
|
85
|
-
`+S.comment:h.comment=S.comment);let L=new
|
|
86
|
-
`+b.comment:l.comment=b.comment),l.range=[n.offset,m,b.offset]}else l.range=[n.offset,m,m];return l}
|
|
87
|
-
`.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,
|
|
88
|
-
`;for(let m=
|
|
89
|
-
`):b.length>c||k[0]===" "?(
|
|
90
|
-
`:!p&&
|
|
91
|
-
`&&(
|
|
92
|
-
|
|
93
|
-
`),u+=
|
|
94
|
-
`,p=!0):k===""?
|
|
79
|
+
`}};cn.YAMLError=an;cn.YAMLParseError=Ua;cn.YAMLWarning=Ja;cn.prettifyError=Lv});var un=E(gd=>{"use strict";function Mv(r,{flow:e,indicator:t,next:n,offset:s,onError:i,parentIndent:o,startOnNewline:a}){let c=!1,l=a,f=a,u="",d="",p=!1,y=!1,m=null,b=null,k=null,x=null,T=null,P=null,C=null;for(let h of r)switch(y&&(h.type!=="space"&&h.type!=="newline"&&h.type!=="comma"&&i(h.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),y=!1),m&&(l&&h.type!=="comment"&&h.type!=="newline"&&i(m,"TAB_AS_INDENT","Tabs are not allowed as indentation"),m=null),h.type){case"space":!e&&(t!=="doc-start"||n?.type!=="flow-collection")&&h.source.includes(" ")&&(m=h),f=!0;break;case"comment":{f||i(h,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let S=h.source.substring(1)||" ";u?u+=d+S:u=S,d="",l=!1;break}case"newline":l?u?u+=h.source:(!P||t!=="seq-item-ind")&&(c=!0):d+=h.source,l=!0,p=!0,(b||k)&&(x=h),f=!0;break;case"anchor":b&&i(h,"MULTIPLE_ANCHORS","A node can have at most one anchor"),h.source.endsWith(":")&&i(h.offset+h.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),b=h,C??(C=h.offset),l=!1,f=!1,y=!0;break;case"tag":{k&&i(h,"MULTIPLE_TAGS","A node can have at most one tag"),k=h,C??(C=h.offset),l=!1,f=!1,y=!0;break}case t:(b||k)&&i(h,"BAD_PROP_ORDER",`Anchors and tags must be after the ${h.source} indicator`),P&&i(h,"UNEXPECTED_TOKEN",`Unexpected ${h.source} in ${e??"collection"}`),P=h,l=t==="seq-item-ind"||t==="explicit-key-ind",f=!1;break;case"comma":if(e){T&&i(h,"UNEXPECTED_TOKEN",`Unexpected , in ${e}`),T=h,l=!1,f=!1;break}default:i(h,"UNEXPECTED_TOKEN",`Unexpected ${h.type} token`),l=!1,f=!1}let O=r[r.length-1],R=O?O.offset+O.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:T,found:P,spaceBefore:c,comment:u,hasNewline:p,anchor:b,tag:k,newlineAfterProp:x,end:R,start:C??R}}gd.resolveProps=Mv});var qs=E(yd=>{"use strict";function Ka(r){if(!r)return null;switch(r.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(r.source.includes(`
|
|
80
|
+
`))return!0;if(r.end){for(let e of r.end)if(e.type==="newline")return!0}return!1;case"flow-collection":for(let e of r.items){for(let t of e.start)if(t.type==="newline")return!0;if(e.sep){for(let t of e.sep)if(t.type==="newline")return!0}if(Ka(e.key)||Ka(e.value))return!0}return!1;default:return!0}}yd.containsNewline=Ka});var Ha=E(bd=>{"use strict";var Dv=qs();function Bv(r,e,t){if(e?.type==="flow-collection"){let n=e.end[0];n.indent===r&&(n.source==="]"||n.source==="}")&&Dv.containsNewline(e)&&t(n,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}bd.flowIndentCheck=Bv});var Wa=E(vd=>{"use strict";var wd=j();function jv(r,e,t){let{uniqueKeys:n}=r.options;if(n===!1)return!1;let s=typeof n=="function"?n:(i,o)=>i===o||wd.isScalar(i)&&wd.isScalar(o)&&i.value===o.value;return e.some(i=>s(i.key,t))}vd.mapIncludes=jv});var Td=E(Ad=>{"use strict";var Sd=et(),Fv=rt(),kd=un(),qv=qs(),xd=Ha(),Uv=Wa(),Ed="All mapping items must start at the same column";function Jv({composeNode:r,composeEmptyNode:e},t,n,s,i){let o=i?.nodeClass??Fv.YAMLMap,a=new o(t.schema);t.atRoot&&(t.atRoot=!1);let c=n.offset,l=null;for(let f of n.items){let{start:u,key:d,sep:p,value:y}=f,m=kd.resolveProps(u,{indicator:"explicit-key-ind",next:d??p?.[0],offset:c,onError:s,parentIndent:n.indent,startOnNewline:!0}),b=!m.found;if(b){if(d&&(d.type==="block-seq"?s(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in d&&d.indent!==n.indent&&s(c,"BAD_INDENT",Ed)),!m.anchor&&!m.tag&&!p){l=m.end,m.comment&&(a.comment?a.comment+=`
|
|
81
|
+
`+m.comment:a.comment=m.comment);continue}(m.newlineAfterProp||qv.containsNewline(d))&&s(d??u[u.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else m.found?.indent!==n.indent&&s(c,"BAD_INDENT",Ed);t.atKey=!0;let k=m.end,x=d?r(t,d,m,s):e(t,k,u,null,m,s);t.schema.compat&&xd.flowIndentCheck(n.indent,d,s),t.atKey=!1,Uv.mapIncludes(t,a.items,x)&&s(k,"DUPLICATE_KEY","Map keys must be unique");let T=kd.resolveProps(p??[],{indicator:"map-value-ind",next:y,offset:x.range[2],onError:s,parentIndent:n.indent,startOnNewline:!d||d.type==="block-scalar"});if(c=T.end,T.found){b&&(y?.type==="block-map"&&!T.hasNewline&&s(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),t.options.strict&&m.start<T.found.offset-1024&&s(x.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let P=y?r(t,y,T,s):e(t,c,p,null,T,s);t.schema.compat&&xd.flowIndentCheck(n.indent,y,s),c=P.range[2];let C=new Sd.Pair(x,P);t.options.keepSourceTokens&&(C.srcToken=f),a.items.push(C)}else{b&&s(x.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),T.comment&&(x.comment?x.comment+=`
|
|
82
|
+
`+T.comment:x.comment=T.comment);let P=new Sd.Pair(x);t.options.keepSourceTokens&&(P.srcToken=f),a.items.push(P)}}return l&&l<c&&s(l,"IMPOSSIBLE","Map comment with trailing content"),a.range=[n.offset,c,l??c],a}Ad.resolveBlockMap=Jv});var Od=E(Pd=>{"use strict";var Kv=nt(),Hv=un(),Wv=Ha();function Yv({composeNode:r,composeEmptyNode:e},t,n,s,i){let o=i?.nodeClass??Kv.YAMLSeq,a=new o(t.schema);t.atRoot&&(t.atRoot=!1),t.atKey&&(t.atKey=!1);let c=n.offset,l=null;for(let{start:f,value:u}of n.items){let d=Hv.resolveProps(f,{indicator:"seq-item-ind",next:u,offset:c,onError:s,parentIndent:n.indent,startOnNewline:!0});if(!d.found)if(d.anchor||d.tag||u)u?.type==="block-seq"?s(d.end,"BAD_INDENT","All sequence items must start at the same column"):s(c,"MISSING_CHAR","Sequence item without - indicator");else{l=d.end,d.comment&&(a.comment=d.comment);continue}let p=u?r(t,u,d,s):e(t,d.end,f,null,d,s);t.schema.compat&&Wv.flowIndentCheck(n.indent,u,s),c=p.range[2],a.items.push(p)}return a.range=[n.offset,c,l??c],a}Pd.resolveBlockSeq=Yv});var or=E(Cd=>{"use strict";function Vv(r,e,t,n){let s="";if(r){let i=!1,o="";for(let a of r){let{source:c,type:l}=a;switch(l){case"space":i=!0;break;case"comment":{t&&!i&&n(a,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let f=c.substring(1)||" ";s?s+=o+f:s=f,o="";break}case"newline":s&&(o+=c),i=!0;break;default:n(a,"UNEXPECTED_TOKEN",`Unexpected ${l} at node end`)}e+=c.length}}return{comment:s,offset:e}}Cd.resolveEnd=Vv});var Id=E(Nd=>{"use strict";var Gv=j(),zv=et(),_d=rt(),Qv=nt(),Xv=or(),Rd=un(),Zv=qs(),eS=Wa(),Ya="Block collections are not allowed within flow collections",Va=r=>r&&(r.type==="block-map"||r.type==="block-seq");function tS({composeNode:r,composeEmptyNode:e},t,n,s,i){let o=n.start.source==="{",a=o?"flow map":"flow sequence",c=i?.nodeClass??(o?_d.YAMLMap:Qv.YAMLSeq),l=new c(t.schema);l.flow=!0;let f=t.atRoot;f&&(t.atRoot=!1),t.atKey&&(t.atKey=!1);let u=n.offset+n.start.source.length;for(let b=0;b<n.items.length;++b){let k=n.items[b],{start:x,key:T,sep:P,value:C}=k,O=Rd.resolveProps(x,{flow:a,indicator:"explicit-key-ind",next:T??P?.[0],offset:u,onError:s,parentIndent:n.indent,startOnNewline:!1});if(!O.found){if(!O.anchor&&!O.tag&&!P&&!C){b===0&&O.comma?s(O.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`):b<n.items.length-1&&s(O.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${a}`),O.comment&&(l.comment?l.comment+=`
|
|
83
|
+
`+O.comment:l.comment=O.comment),u=O.end;continue}!o&&t.options.strict&&Zv.containsNewline(T)&&s(T,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(b===0)O.comma&&s(O.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`);else if(O.comma||s(O.start,"MISSING_CHAR",`Missing , between ${a} items`),O.comment){let R="";e:for(let h of x)switch(h.type){case"comma":case"space":break;case"comment":R=h.source.substring(1);break e;default:break e}if(R){let h=l.items[l.items.length-1];Gv.isPair(h)&&(h=h.value??h.key),h.comment?h.comment+=`
|
|
84
|
+
`+R:h.comment=R,O.comment=O.comment.substring(R.length+1)}}if(!o&&!P&&!O.found){let R=C?r(t,C,O,s):e(t,O.end,P,null,O,s);l.items.push(R),u=R.range[2],Va(C)&&s(R.range,"BLOCK_IN_FLOW",Ya)}else{t.atKey=!0;let R=O.end,h=T?r(t,T,O,s):e(t,R,x,null,O,s);Va(T)&&s(h.range,"BLOCK_IN_FLOW",Ya),t.atKey=!1;let S=Rd.resolveProps(P??[],{flow:a,indicator:"map-value-ind",next:C,offset:h.range[2],onError:s,parentIndent:n.indent,startOnNewline:!1});if(S.found){if(!o&&!O.found&&t.options.strict){if(P)for(let N of P){if(N===S.found)break;if(N.type==="newline"){s(N,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}O.start<S.found.offset-1024&&s(S.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else C&&("source"in C&&C.source?.[0]===":"?s(C,"MISSING_CHAR",`Missing space after : in ${a}`):s(S.start,"MISSING_CHAR",`Missing , or : between ${a} items`));let I=C?r(t,C,S,s):S.found?e(t,S.end,P,null,S,s):null;I?Va(C)&&s(I.range,"BLOCK_IN_FLOW",Ya):S.comment&&(h.comment?h.comment+=`
|
|
85
|
+
`+S.comment:h.comment=S.comment);let L=new zv.Pair(h,I);if(t.options.keepSourceTokens&&(L.srcToken=k),o){let N=l;eS.mapIncludes(t,N.items,h)&&s(R,"DUPLICATE_KEY","Map keys must be unique"),N.items.push(L)}else{let N=new _d.YAMLMap(t.schema);N.flow=!0,N.items.push(L);let X=(I??h).range;N.range=[h.range[0],X[1],X[2]],l.items.push(N)}u=I?I.range[2]:S.end}}let d=o?"}":"]",[p,...y]=n.end,m=u;if(p?.source===d)m=p.offset+p.source.length;else{let b=a[0].toUpperCase()+a.substring(1),k=f?`${b} must end with a ${d}`:`${b} in block collection must be sufficiently indented and end with a ${d}`;s(u,f?"MISSING_CHAR":"BAD_INDENT",k),p&&p.source.length!==1&&y.unshift(p)}if(y.length>0){let b=Xv.resolveEnd(y,m,t.options.strict,s);b.comment&&(l.comment?l.comment+=`
|
|
86
|
+
`+b.comment:l.comment=b.comment),l.range=[n.offset,m,b.offset]}else l.range=[n.offset,m,m];return l}Nd.resolveFlowCollection=tS});var Ld=E($d=>{"use strict";var rS=j(),nS=W(),sS=rt(),iS=nt(),oS=Td(),aS=Od(),cS=Id();function Ga(r,e,t,n,s,i){let o=t.type==="block-map"?oS.resolveBlockMap(r,e,t,n,i):t.type==="block-seq"?aS.resolveBlockSeq(r,e,t,n,i):cS.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 lS(r,e,t,n,s){let i=n.tag,o=i?e.directives.tagName(i.source,d=>s(i,"TAG_RESOLVE_FAILED",d)):null;if(t.type==="block-seq"){let{anchor:d,newlineAfterProp:p}=n,y=d&&i?d.offset>i.offset?d:i:d??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===sS.YAMLMap.tagName&&a==="map"||o===iS.YAMLSeq.tagName&&a==="seq")return Ga(r,e,t,s,o);let c=e.schema.tags.find(d=>d.tag===o&&d.collection===a);if(!c){let d=e.schema.knownTags[o];if(d?.collection===a)e.schema.tags.push(Object.assign({},d,{default:!1})),c=d;else return d?s(i,"BAD_COLLECTION_TYPE",`${d.tag} used for ${a} collection, but expects ${d.collection??"scalar"}`,!0):s(i,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),Ga(r,e,t,s,o)}let l=Ga(r,e,t,s,o,c),f=c.resolve?.(l,d=>s(i,"TAG_RESOLVE_FAILED",d),e.options)??l,u=rS.isNode(f)?f:new nS.Scalar(f);return u.range=l.range,u.tag=o,c?.format&&(u.format=c.format),u}$d.composeCollection=lS});var Qa=E(Md=>{"use strict";var za=W();function uS(r,e,t){let n=e.offset,s=fS(e,r.options.strict,t);if(!s)return{value:"",type:null,comment:"",range:[n,n,n]};let i=s.mode===">"?za.Scalar.BLOCK_FOLDED:za.Scalar.BLOCK_LITERAL,o=e.source?dS(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?`
|
|
87
|
+
`.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,f=0;for(let m=0;m<a;++m){let[b,k]=o[m];if(k===""||k==="\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),f=m,c===0&&!r.atRoot&&t(l,"BAD_INDENT","Block scalar values in collections must be indented");break}l+=b.length+k.length+1}for(let m=o.length-1;m>=a;--m)o[m][0].length>c&&(a=m+1);let u="",d="",p=!1;for(let m=0;m<f;++m)u+=o[m][0].slice(c)+`
|
|
88
|
+
`;for(let m=f;m<a;++m){let[b,k]=o[m];l+=b.length+k.length+1;let x=k[k.length-1]==="\r";if(x&&(k=k.slice(0,-1)),k&&b.length<c){let P=`Block scalar lines must not be less indented than their ${s.indent?"explicit indentation indicator":"first line"}`;t(l-k.length-(x?2:1),"BAD_INDENT",P),b=""}i===za.Scalar.BLOCK_LITERAL?(u+=d+b.slice(c)+k,d=`
|
|
89
|
+
`):b.length>c||k[0]===" "?(d===" "?d=`
|
|
90
|
+
`:!p&&d===`
|
|
91
|
+
`&&(d=`
|
|
92
|
+
|
|
93
|
+
`),u+=d+b.slice(c)+k,d=`
|
|
94
|
+
`,p=!0):k===""?d===`
|
|
95
95
|
`?u+=`
|
|
96
|
-
`:
|
|
97
|
-
`:(u+=
|
|
96
|
+
`:d=`
|
|
97
|
+
`:(u+=d+k,d=" ",p=!1)}switch(s.chomp){case"-":break;case"+":for(let m=a;m<o.length;++m)u+=`
|
|
98
98
|
`+o[m][0].slice(c);u[u.length-1]!==`
|
|
99
99
|
`&&(u+=`
|
|
100
100
|
`);break;default:u+=`
|
|
101
|
-
`}let y=n+s.length+e.source.length;return{value:u,type:i,comment:s.comment,range:[n,y,y]}}function
|
|
101
|
+
`}let y=n+s.length+e.source.length;return{value:u,type:i,comment:s.comment,range:[n,y,y]}}function fS({offset:r,props:e},t,n){if(e[0].type!=="block-scalar-header")return n(e[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:s}=e[0],i=s[0],o=0,a="",c=-1;for(let d=1;d<s.length;++d){let p=s[d];if(!a&&(p==="-"||p==="+"))a=p;else{let y=Number(p);!o&&y?o=y:c===-1&&(c=r+d)}}c!==-1&&n(c,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${s}`);let l=!1,f="",u=s.length;for(let d=1;d<e.length;++d){let p=e[d];switch(p.type){case"space":l=!0;case"newline":u+=p.source.length;break;case"comment":t&&!l&&n(p,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),u+=p.source.length,f=p.source.substring(1);break;case"error":n(p,"UNEXPECTED_TOKEN",p.message),u+=p.source.length;break;default:{let 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:f,length:u}}function dS(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}Md.resolveBlockScalar=uS});var Za=E(Bd=>{"use strict";var Xa=W(),pS=or();function mS(r,e,t){let{offset:n,type:s,source:i,end:o}=r,a,c,l=(d,p,y)=>t(n+d,p,y);switch(s){case"scalar":a=Xa.Scalar.PLAIN,c=hS(i,l);break;case"single-quoted-scalar":a=Xa.Scalar.QUOTE_SINGLE,c=gS(i,l);break;case"double-quoted-scalar":a=Xa.Scalar.QUOTE_DOUBLE,c=yS(i,l);break;default:return t(r,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${s}`),{value:"",type:null,comment:"",range:[n,n+i.length,n+i.length]}}let f=n+i.length,u=pS.resolveEnd(o,f,e,t);return{value:c,type:a,comment:u.comment,range:[n,f,u.offset]}}function hS(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}`),Dd(r)}function gS(r,e){return(r[r.length-1]!=="'"||r.length===1)&&e(r.length,"MISSING_CHAR","Missing closing 'quote"),Dd(r.slice(1,-1)).replace(/''/g,"'")}function Dd(r){let e,t;try{e=new RegExp(`(.*?)(?<![ ])[ ]*\r?
|
|
102
102
|
`,"sy"),t=new RegExp(`[ ]*(.*?)(?:(?<![ ])[ ]*)?\r?
|
|
103
103
|
`,"sy")}catch{e=/(.*?)[ \t]*\r?\n/sy,t=/[ \t]*(.*?)[ \t]*\r?\n/sy}let n=e.exec(r);if(!n)return r;let s=n[1],i=" ",o=e.lastIndex;for(t.lastIndex=o;n=t.exec(r);)n[1]===""?i===`
|
|
104
104
|
`?s+=i:i=`
|
|
105
|
-
`:(s+=i+n[1],i=" "),o=t.lastIndex;let a=/[ \t]*(.*)/sy;return a.lastIndex=o,n=a.exec(r),s+i+(n?.[1]??"")}function
|
|
105
|
+
`:(s+=i+n[1],i=" "),o=t.lastIndex;let a=/[ \t]*(.*)/sy;return a.lastIndex=o,n=a.exec(r),s+i+(n?.[1]??"")}function yS(r,e){let t="";for(let n=1;n<r.length-1;++n){let s=r[n];if(!(s==="\r"&&r[n+1]===`
|
|
106
106
|
`))if(s===`
|
|
107
|
-
`){let{fold:i,offset:o}=
|
|
107
|
+
`){let{fold:i,offset:o}=bS(r,n);t+=i,n=o}else if(s==="\\"){let i=r[++n],o=wS[i];if(o)t+=o;else if(i===`
|
|
108
108
|
`)for(i=r[n+1];i===" "||i===" ";)i=r[++n+1];else if(i==="\r"&&r[n+1]===`
|
|
109
|
-
`)for(i=r[++n+1];i===" "||i===" ";)i=r[++n+1];else if(i==="x"||i==="u"||i==="U"){let a={x:2,u:4,U:8}[i];t+=
|
|
109
|
+
`)for(i=r[++n+1];i===" "||i===" ";)i=r[++n+1];else if(i==="x"||i==="u"||i==="U"){let a={x:2,u:4,U:8}[i];t+=vS(r,n+1,a,e),n+=a}else{let a=r.substr(n-1,2);e(n-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${a}`),t+=a}}else if(s===" "||s===" "){let i=n,o=r[n+1];for(;o===" "||o===" ";)o=r[++n+1];o!==`
|
|
110
110
|
`&&!(o==="\r"&&r[n+2]===`
|
|
111
|
-
`)&&(t+=n>i?r.slice(i,n+1):s)}else t+=s}return(r[r.length-1]!=='"'||r.length===1)&&e(r.length,"MISSING_CHAR",'Missing closing "quote'),t}function
|
|
111
|
+
`)&&(t+=n>i?r.slice(i,n+1):s)}else t+=s}return(r[r.length-1]!=='"'||r.length===1)&&e(r.length,"MISSING_CHAR",'Missing closing "quote'),t}function bS(r,e){let t="",n=r[e+1];for(;(n===" "||n===" "||n===`
|
|
112
112
|
`||n==="\r")&&!(n==="\r"&&r[e+2]!==`
|
|
113
113
|
`);)n===`
|
|
114
114
|
`&&(t+=`
|
|
115
|
-
`),e+=1,n=r[e+1];return t||(t=" "),{fold:t,offset:e}}var
|
|
116
|
-
`,r:"\r",t:" ",v:"\v",N:"\x85",_:"\xA0",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function
|
|
115
|
+
`),e+=1,n=r[e+1];return t||(t=" "),{fold:t,offset:e}}var wS={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
|
|
116
|
+
`,r:"\r",t:" ",v:"\v",N:"\x85",_:"\xA0",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function vS(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)}Bd.resolveFlowScalar=mS});var qd=E(Fd=>{"use strict";var Tt=j(),jd=W(),SS=Qa(),kS=Za();function xS(r,e,t,n){let{value:s,type:i,comment:o,range:a}=e.type==="block-scalar"?SS.resolveBlockScalar(r,e,n):kS.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[Tt.SCALAR]:c?l=ES(r.schema,s,c,t,n):e.type==="scalar"?l=AS(r,s,e,n):l=r.schema[Tt.SCALAR];let f;try{let u=l.resolve(s,d=>n(t??e,"TAG_RESOLVE_FAILED",d),r.options);f=Tt.isScalar(u)?u:new jd.Scalar(u)}catch(u){let d=u instanceof Error?u.message:String(u);n(t??e,"TAG_RESOLVE_FAILED",d),f=new jd.Scalar(s)}return f.range=a,f.source=s,i&&(f.type=i),c&&(f.tag=c),l.format&&(f.format=l.format),o&&(f.comment=o),f}function ES(r,e,t,n,s){if(t==="!")return r[Tt.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[Tt.SCALAR])}function AS({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[Tt.SCALAR];if(t.compat){let a=t.compat.find(c=>c.default&&c.test?.test(n))??t[Tt.SCALAR];if(o.tag!==a.tag){let c=e.tagString(o.tag),l=e.tagString(a.tag),f=`Value may be parsed as either ${c} or ${l}`;i(s,"TAG_RESOLVE_FAILED",f,!0)}}return o}Fd.composeScalar=xS});var Jd=E(Ud=>{"use strict";function TS(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}Ud.emptyScalarPosition=TS});var Wd=E(tc=>{"use strict";var PS=Ur(),OS=j(),CS=Ld(),Kd=qd(),_S=or(),RS=Jd(),NS={composeNode:Hd,composeEmptyNode:ec};function Hd(r,e,t,n){let s=r.atKey,{spaceBefore:i,comment:o,anchor:a,tag:c}=t,l,f=!0;switch(e.type){case"alias":l=IS(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=Kd.composeScalar(r,e,c,n),a&&(l.anchor=a.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":l=CS.composeCollection(NS,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=ec(r,e.offset,void 0,null,t,n),f=!1}}return a&&l.anchor===""&&n(a,"BAD_ALIAS","Anchor cannot be an empty string"),s&&r.options.stringKeys&&(!OS.isScalar(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&n(c??e,"NON_STRING_KEY","With stringKeys, all keys must be strings"),i&&(l.spaceBefore=!0),o&&(e.type==="scalar"&&e.source===""?l.comment=o:l.commentBefore=o),r.options.keepSourceTokens&&f&&(l.srcToken=e),l}function ec(r,e,t,n,{spaceBefore:s,comment:i,anchor:o,tag:a,end:c},l){let f={type:"scalar",offset:RS.emptyScalarPosition(e,t,n),indent:-1,source:""},u=Kd.composeScalar(r,f,a,l);return o&&(u.anchor=o.source.substring(1),u.anchor===""&&l(o,"BAD_ALIAS","Anchor cannot be an empty string")),s&&(u.spaceBefore=!0),i&&(u.comment=i,u.range[2]=c),u}function IS({options:r},{offset:e,source:t,end:n},s){let i=new PS.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=_S.resolveEnd(n,o,r.strict,s);return i.range=[e,o,a.offset],a.comment&&(i.comment=a.comment),i}tc.composeEmptyNode=ec;tc.composeNode=Hd});var Gd=E(Vd=>{"use strict";var $S=on(),Yd=Wd(),LS=or(),MS=un();function DS(r,e,{offset:t,start:n,value:s,end:i},o){let a=Object.assign({_directives:e},r),c=new $S.Document(void 0,a),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},f=MS.resolveProps(n,{indicator:"doc-start",next:s??i?.[0],offset:t,onError:o,parentIndent:0,startOnNewline:!0});f.found&&(c.directives.docStart=!0,s&&(s.type==="block-map"||s.type==="block-seq")&&!f.hasNewline&&o(f.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=s?Yd.composeNode(l,s,f,o):Yd.composeEmptyNode(l,f.end,n,null,f,o);let u=c.contents.range[2],d=LS.resolveEnd(i,u,!1,o);return d.comment&&(c.comment=d.comment),c.range=[t,u,d.offset],c}Vd.composeDoc=DS});var nc=E(Xd=>{"use strict";var BS=Vn("process"),jS=Uo(),FS=on(),fn=ln(),zd=j(),qS=Gd(),US=or();function dn(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 Qd(r){let e="",t=!1,n=!1;for(let s=0;s<r.length;++s){let i=r[s];switch(i[0]){case"#":e+=(e===""?"":n?`
|
|
117
117
|
|
|
118
118
|
`:`
|
|
119
|
-
`)+(i.substring(1)||" "),t=!0,n=!1;break;case"%":r[s+1]?.[0]!=="#"&&(s+=1),t=!1;break;default:t||(n=!0),t=!1}}return{comment:e,afterEmptyLine:n}}var rc=class{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(t,n,s,i)=>{let o=dn(t);i?this.warnings.push(new fn.YAMLWarning(o,n,s)):this.errors.push(new fn.YAMLParseError(o,n,s))},this.directives=new
|
|
120
|
-
${n}`:n;else if(s||e.directives.docStart||!i)e.commentBefore=n;else if(
|
|
119
|
+
`)+(i.substring(1)||" "),t=!0,n=!1;break;case"%":r[s+1]?.[0]!=="#"&&(s+=1),t=!1;break;default:t||(n=!0),t=!1}}return{comment:e,afterEmptyLine:n}}var rc=class{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(t,n,s,i)=>{let o=dn(t);i?this.warnings.push(new fn.YAMLWarning(o,n,s)):this.errors.push(new fn.YAMLParseError(o,n,s))},this.directives=new jS.Directives({version:e.version||"1.2"}),this.options=e}decorate(e,t){let{comment:n,afterEmptyLine:s}=Qd(this.prelude);if(n){let i=e.contents;if(t)e.comment=e.comment?`${e.comment}
|
|
120
|
+
${n}`:n;else if(s||e.directives.docStart||!i)e.commentBefore=n;else if(zd.isCollection(i)&&!i.flow&&i.items.length>0){let o=i.items[0];zd.isPair(o)&&(o=o.key);let a=o.commentBefore;o.commentBefore=a?`${n}
|
|
121
121
|
${a}`:n}else{let o=i.commentBefore;i.commentBefore=o?`${n}
|
|
122
|
-
${o}`:n}}t?(Array.prototype.push.apply(e.errors,this.errors),Array.prototype.push.apply(e.warnings,this.warnings)):(e.errors=this.errors,e.warnings=this.warnings),this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:
|
|
123
|
-
${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.push(new fn.YAMLParseError(dn(e),"UNEXPECTED_TOKEN",`Unsupported token ${e.type}`))}}*end(e=!1,t=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(e){let n=Object.assign({_directives:this.directives},this.options),s=new
|
|
122
|
+
${o}`:n}}t?(Array.prototype.push.apply(e.errors,this.errors),Array.prototype.push.apply(e.warnings,this.warnings)):(e.errors=this.errors,e.warnings=this.warnings),this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:Qd(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(BS.env.LOG_STREAM&&console.dir(e,{depth:null}),e.type){case"directive":this.directives.add(e.source,(t,n,s)=>{let i=dn(e);i[0]+=t,this.onError(i,"BAD_DIRECTIVE",n,s)}),this.prelude.push(e.source),this.atDirectives=!0;break;case"document":{let t=qS.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 fn.YAMLParseError(dn(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 fn.YAMLParseError(dn(e),"UNEXPECTED_TOKEN",n));break}this.doc.directives.docEnd=!0;let t=US.resolveEnd(e.end,e.offset+e.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),t.comment){let n=this.doc.comment;this.doc.comment=n?`${n}
|
|
123
|
+
${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.push(new fn.YAMLParseError(dn(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 FS.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}}};Xd.Composer=rc});var tp=E(Us=>{"use strict";var JS=Qa(),KS=Za(),HS=ln(),Zd=Yr();function WS(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 HS.YAMLParseError([a,a+1],i,o)};switch(r.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return KS.resolveFlowScalar(r,e,n);case"block-scalar":return JS.resolveBlockScalar({options:{strict:e}},r,n)}}return null}function YS(r,e){let{implicitKey:t=!1,indent:n,inFlow:s=!1,offset:i=-1,type:o="PLAIN"}=e,a=Zd.stringifyString({type:o,value:r},{implicitKey:t,indent:n>0?" ".repeat(n):"",inFlow:s,options:{blockQuote:!0,lineWidth:-1}}),c=e.end??[{type:"newline",offset:-1,indent:n,source:`
|
|
124
124
|
`}];switch(a[0]){case"|":case">":{let l=a.indexOf(`
|
|
125
|
-
`),
|
|
126
|
-
`,
|
|
127
|
-
`}),{type:"block-scalar",offset:i,indent:n,props:
|
|
125
|
+
`),f=a.substring(0,l),u=a.substring(l+1)+`
|
|
126
|
+
`,d=[{type:"block-scalar-header",offset:i,indent:n,source:f}];return ep(d,c)||d.push({type:"newline",offset:-1,indent:n,source:`
|
|
127
|
+
`}),{type:"block-scalar",offset:i,indent:n,props:d,source:u}}case'"':return{type:"double-quoted-scalar",offset:i,indent:n,source:a,end:c};case"'":return{type:"single-quoted-scalar",offset:i,indent:n,source:a,end:c};default:return{type:"scalar",offset:i,indent:n,source:a,end:c}}}function VS(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=Zd.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">":GS(r,c);break;case'"':sc(r,c,"double-quoted-scalar");break;case"'":sc(r,c,"single-quoted-scalar");break;default:sc(r,c,"scalar")}}function GS(r,e){let t=e.indexOf(`
|
|
128
128
|
`),n=e.substring(0,t),s=e.substring(t+1)+`
|
|
129
|
-
`;if(r.type==="block-scalar"){let i=r.props[0];if(i.type!=="block-scalar-header")throw new Error("Invalid block scalar header");i.source=n,r.source=s}else{let{offset:i}=r,o="indent"in r?r.indent:-1,a=[{type:"block-scalar-header",offset:i,indent:o,source:n}];
|
|
130
|
-
`});for(let c of Object.keys(r))c!=="type"&&c!=="offset"&&delete r[c];Object.assign(r,{type:"block-scalar",indent:o,props:a,source:s})}}function
|
|
131
|
-
`};delete r.items,Object.assign(r,{type:t,source:e,end:[s]});break}default:{let n="indent"in r?r.indent:-1,s="end"in r&&Array.isArray(r.end)?r.end.filter(i=>i.type==="space"||i.type==="comment"||i.type==="newline"):[];for(let i of Object.keys(r))i!=="type"&&i!=="offset"&&delete r[i];Object.assign(r,{type:t,indent:n,source:e,end:s})}}}Us.createScalarToken=
|
|
129
|
+
`;if(r.type==="block-scalar"){let i=r.props[0];if(i.type!=="block-scalar-header")throw new Error("Invalid block scalar header");i.source=n,r.source=s}else{let{offset:i}=r,o="indent"in r?r.indent:-1,a=[{type:"block-scalar-header",offset:i,indent:o,source:n}];ep(a,"end"in r?r.end:void 0)||a.push({type:"newline",offset:-1,indent:o,source:`
|
|
130
|
+
`});for(let c of Object.keys(r))c!=="type"&&c!=="offset"&&delete r[c];Object.assign(r,{type:"block-scalar",indent:o,props:a,source:s})}}function ep(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 sc(r,e,t){switch(r.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":r.type=t,r.source=e;break;case"block-scalar":{let n=r.props.slice(1),s=e.length;r.props[0].type==="block-scalar-header"&&(s-=r.props[0].source.length);for(let i of n)i.offset+=s;delete r.props,Object.assign(r,{type:t,source:e,end:n});break}case"block-map":case"block-seq":{let s={type:"newline",offset:r.offset+e.length,indent:r.indent,source:`
|
|
131
|
+
`};delete r.items,Object.assign(r,{type:t,source:e,end:[s]});break}default:{let n="indent"in r?r.indent:-1,s="end"in r&&Array.isArray(r.end)?r.end.filter(i=>i.type==="space"||i.type==="comment"||i.type==="newline"):[];for(let i of Object.keys(r))i!=="type"&&i!=="offset"&&delete r[i];Object.assign(r,{type:t,indent:n,source:e,end:s})}}}Us.createScalarToken=YS;Us.resolveAsScalar=WS;Us.setScalarValue=VS});var np=E(rp=>{"use strict";var zS=r=>"type"in r?Ks(r):Js(r);function Ks(r){switch(r.type){case"block-scalar":{let e="";for(let t of r.props)e+=Ks(t);return e+r.source}case"block-map":case"block-seq":{let e="";for(let t of r.items)e+=Js(t);return e}case"flow-collection":{let e=r.start.source;for(let t of r.items)e+=Js(t);for(let t of r.end)e+=t.source;return e}case"document":{let e=Js(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 Js({start:r,key:e,sep:t,value:n}){let s="";for(let i of r)s+=i.source;if(e&&(s+=Ks(e)),t)for(let i of t)s+=i.source;return n&&(s+=Ks(n)),s}rp.stringify=zS});var ap=E(op=>{"use strict";var ic=Symbol("break visit"),QS=Symbol("skip children"),sp=Symbol("remove item");function Pt(r,e){"type"in r&&r.type==="document"&&(r={start:r.start,value:r.value}),ip(Object.freeze([]),r,e)}Pt.BREAK=ic;Pt.SKIP=QS;Pt.REMOVE=sp;Pt.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};Pt.parentCollection=(r,e)=>{let t=Pt.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 ip(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=ip(Object.freeze(r.concat([[s,o]])),i.items[o],t);if(typeof a=="number")o=a-1;else{if(a===ic)return ic;a===sp&&(i.items.splice(o,1),o-=1)}}typeof n=="function"&&s==="key"&&(n=n(e,r))}}return typeof n=="function"?n(e,r):n}op.visit=Pt});var Hs=E(ae=>{"use strict";var oc=tp(),XS=np(),ZS=ap(),ac="\uFEFF",cc="",lc="",uc="",ek=r=>!!r&&"items"in r,tk=r=>!!r&&(r.type==="scalar"||r.type==="single-quoted-scalar"||r.type==="double-quoted-scalar"||r.type==="block-scalar");function rk(r){switch(r){case ac:return"<BOM>";case cc:return"<DOC>";case lc:return"<FLOW_END>";case uc:return"<SCALAR>";default:return JSON.stringify(r)}}function nk(r){switch(r){case ac:return"byte-order-mark";case cc:return"doc-mode";case lc:return"flow-error-end";case uc:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
|
|
132
132
|
`:case`\r
|
|
133
|
-
`:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(r[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}
|
|
134
|
-
`:case"\r":case" ":return!0;default:return!1}}var
|
|
135
|
-
\r `),fc=r=>!r||
|
|
133
|
+
`:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(r[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}ae.createScalarToken=oc.createScalarToken;ae.resolveAsScalar=oc.resolveAsScalar;ae.setScalarValue=oc.setScalarValue;ae.stringify=XS.stringify;ae.visit=ZS.visit;ae.BOM=ac;ae.DOCUMENT=cc;ae.FLOW_END=lc;ae.SCALAR=uc;ae.isCollection=ek;ae.isScalar=tk;ae.prettyToken=rk;ae.tokenType=nk});var pc=E(lp=>{"use strict";var pn=Hs();function we(r){switch(r){case void 0:case" ":case`
|
|
134
|
+
`:case"\r":case" ":return!0;default:return!1}}var cp=new Set("0123456789ABCDEFabcdef"),sk=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),Ws=new Set(",[]{}"),ik=new Set(` ,[]{}
|
|
135
|
+
\r `),fc=r=>!r||ik.has(r),dc=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(e,t=!1){if(e){if(typeof e!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+e:e,this.lineEndPos=null}this.atEnd=!t;let n=this.next??"stream";for(;n&&(t||this.hasChars(1));)n=yield*this.parseNext(n)}atLineEnd(){let e=this.pos,t=this.buffer[e];for(;t===" "||t===" ";)t=this.buffer[++e];return!t||t==="#"||t===`
|
|
136
136
|
`?!0:t==="\r"?this.buffer[e+1]===`
|
|
137
137
|
`:!1}charAt(e){return this.buffer[this.pos+e]}continueScalar(e){let t=this.buffer[e];if(this.indentNext>0){let n=0;for(;t===" ";)t=this.buffer[++n+e];if(t==="\r"){let s=this.buffer[n+e+1];if(s===`
|
|
138
138
|
`||!s&&!this.atEnd)return e+n+1}return t===`
|
|
@@ -147,23 +147,23 @@ ${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.pus
|
|
|
147
147
|
`&&i>=this.pos&&i+1+t>a)e=i;else break}while(!0);return yield pn.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(we(i)||e&&Ws.has(i))break;t=n}else if(we(s)){let i=this.buffer[n+1];if(s==="\r"&&(i===`
|
|
148
148
|
`?(n+=1,s=`
|
|
149
149
|
`,i=this.buffer[n+1]):t=n),i==="#"||e&&Ws.has(i))break;if(s===`
|
|
150
|
-
`){let o=this.continueScalar(n+1);if(o===-1)break;n=Math.max(n,o-2)}}else{if(e&&Ws.has(s))break;t=n}return!s&&!this.atEnd?this.setNext("plain-scalar"):(yield pn.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(fc))+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators());case"-":case"?":case":":{let e=this.flowLevel>0,t=this.charAt(1);if(we(t)||e&&Ws.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(;!we(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(
|
|
150
|
+
`){let o=this.continueScalar(n+1);if(o===-1)break;n=Math.max(n,o-2)}}else{if(e&&Ws.has(s))break;t=n}return!s&&!this.atEnd?this.setNext("plain-scalar"):(yield pn.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(fc))+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators());case"-":case"?":case":":{let e=this.flowLevel>0,t=this.charAt(1);if(we(t)||e&&Ws.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(;!we(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(sk.has(t))t=this.buffer[++e];else if(t==="%"&&cp.has(this.buffer[e+1])&&cp.has(this.buffer[e+2]))t=this.buffer[e+=3];else break;return yield*this.pushToIndex(e,!1)}}*pushNewline(){let e=this.buffer[this.pos];return e===`
|
|
151
151
|
`?yield*this.pushCount(1):e==="\r"&&this.charAt(1)===`
|
|
152
|
-
`?yield*this.pushCount(2):0}*pushSpaces(e){let t=this.pos-1,n;do n=this.buffer[++t];while(n===" "||e&&n===" ");let s=t-this.pos;return s>0&&(yield this.buffer.substr(this.pos,s),this.pos=t),s}*pushUntil(e){let t=this.pos,n=this.buffer[t];for(;!e(n);)n=this.buffer[++t];return yield*this.pushToIndex(t,!1)}};
|
|
152
|
+
`?yield*this.pushCount(2):0}*pushSpaces(e){let t=this.pos-1,n;do n=this.buffer[++t];while(n===" "||e&&n===" ");let s=t-this.pos;return s>0&&(yield this.buffer.substr(this.pos,s),this.pos=t),s}*pushUntil(e){let t=this.pos,n=this.buffer[t];for(;!e(n);)n=this.buffer[++t];return yield*this.pushToIndex(t,!1)}};lp.Lexer=dc});var hc=E(up=>{"use strict";var mc=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}}}};up.LineCounter=mc});var yc=E(hp=>{"use strict";var ok=Vn("process"),fp=Hs(),ak=pc();function st(r,e){for(let t=0;t<r.length;++t)if(r[t].type===e)return!0;return!1}function dp(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 mp(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 Ys(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 ar(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 pp(r){if(r.start.type==="flow-seq-start")for(let e of r.items)e.sep&&!e.value&&!st(e.start,"explicit-key-ind")&&!st(e.sep,"map-value-ind")&&(e.key&&(e.value=e.key),delete e.key,mp(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 gc=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 ak.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,ok.env.LOG_TOKENS&&console.log("|",fp.prettyToken(e)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=e.length;return}let t=fp.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"&&pp(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&&dp(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":{dp(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=Ys(this.peek(2)),n=ar(t),s;e.end?(s=e.end,s.push(this.sourceToken),delete e.end):s=[this.sourceToken];let i={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:n,key:e,sep:s}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=i}else yield*this.lineEnd(e)}*blockScalar(e){switch(this.type){case"space":case"comment":case"newline":e.props.push(this.sourceToken);return;case"scalar":if(e.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let t=this.source.indexOf(`
|
|
153
153
|
`)+1;for(;t!==0;)this.onNewLine(this.offset+t),t=this.source.indexOf(`
|
|
154
|
-
`,t)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){let t=e.items[e.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,t.value){let n="end"in t.value?t.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type==="comment"?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else if(t.sep)t.sep.push(this.sourceToken);else{if(this.atIndentedComment(t.start,e.indent)){let s=e.items[e.items.length-2]?.value?.end;if(Array.isArray(s)){Array.prototype.push.apply(s,t.start),s.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return}if(this.indent>=e.indent){let n=!this.onKeyLine&&this.indent===e.indent,s=n&&(t.sep||t.explicitKey)&&this.type!=="seq-item-ind",i=[];if(s&&t.sep&&!t.value){let o=[];for(let a=0;a<t.sep.length;++a){let c=t.sep[a];switch(c.type){case"newline":o.push(a);break;case"space":break;case"comment":c.indent>e.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(i=t.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":s||t.value?(i.push(this.sourceToken),e.items.push({start:i}),this.onKeyLine=!0):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"explicit-key-ind":!t.sep&&!t.explicitKey?(t.start.push(this.sourceToken),t.explicitKey=!0):s||t.value?(i.push(this.sourceToken),e.items.push({start:i,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(t.explicitKey)if(t.sep)if(t.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(st(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(
|
|
154
|
+
`,t)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){let t=e.items[e.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,t.value){let n="end"in t.value?t.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type==="comment"?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else if(t.sep)t.sep.push(this.sourceToken);else{if(this.atIndentedComment(t.start,e.indent)){let s=e.items[e.items.length-2]?.value?.end;if(Array.isArray(s)){Array.prototype.push.apply(s,t.start),s.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return}if(this.indent>=e.indent){let n=!this.onKeyLine&&this.indent===e.indent,s=n&&(t.sep||t.explicitKey)&&this.type!=="seq-item-ind",i=[];if(s&&t.sep&&!t.value){let o=[];for(let a=0;a<t.sep.length;++a){let c=t.sep[a];switch(c.type){case"newline":o.push(a);break;case"space":break;case"comment":c.indent>e.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(i=t.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":s||t.value?(i.push(this.sourceToken),e.items.push({start:i}),this.onKeyLine=!0):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"explicit-key-ind":!t.sep&&!t.explicitKey?(t.start.push(this.sourceToken),t.explicitKey=!0):s||t.value?(i.push(this.sourceToken),e.items.push({start:i,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(t.explicitKey)if(t.sep)if(t.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(st(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(mp(t.key)&&!st(t.sep,"newline")){let o=ar(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(st(t.start,"newline"))Object.assign(t,{key:null,sep:[this.sourceToken]});else{let o=ar(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]}):st(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&&!st(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||st(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=Ys(n),i=ar(s);pp(e);let o=e.end.splice(1,e.end.length);o.push(this.sourceToken);let a={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:i,key:e,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let t=this.source.indexOf(`
|
|
155
155
|
`)+1;for(;t!==0;)this.onNewLine(this.offset+t),t=this.source.indexOf(`
|
|
156
|
-
`,t)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let t=Ys(e),n=ar(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=Ys(e),n=ar(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())}}};
|
|
157
|
-
`),t=e.trim();if(
|
|
156
|
+
`,t)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let t=Ys(e),n=ar(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=Ys(e),n=ar(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())}}};hp.Parser=gc});var vp=E(hn=>{"use strict";var gp=nc(),ck=on(),mn=ln(),lk=ta(),uk=j(),fk=hc(),yp=yc();function bp(r){let e=r.prettyErrors!==!1;return{lineCounter:r.lineCounter||e&&new fk.LineCounter||null,prettyErrors:e}}function dk(r,e={}){let{lineCounter:t,prettyErrors:n}=bp(e),s=new yp.Parser(t?.addNewLine),i=new gp.Composer(e),o=Array.from(i.compose(s.parse(r)));if(n&&t)for(let a of o)a.errors.forEach(mn.prettifyError(r,t)),a.warnings.forEach(mn.prettifyError(r,t));return o.length>0?o:Object.assign([],{empty:!0},i.streamInfo())}function wp(r,e={}){let{lineCounter:t,prettyErrors:n}=bp(e),s=new yp.Parser(t?.addNewLine),i=new gp.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 mn.YAMLParseError(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return n&&t&&(o.errors.forEach(mn.prettifyError(r,t)),o.warnings.forEach(mn.prettifyError(r,t))),o}function pk(r,e,t){let n;typeof e=="function"?n=e:t===void 0&&e&&typeof e=="object"&&(t=e);let s=wp(r,t);if(!s)return null;if(s.warnings.forEach(i=>lk.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 mk(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 uk.isDocument(r)&&!n?r.toString(t):new ck.Document(r,n,t).toString(t)}hn.parse=pk;hn.parseAllDocuments=dk;hn.parseDocument=wp;hn.stringify=mk});var kp=E(F=>{"use strict";var hk=nc(),gk=on(),yk=Da(),bc=ln(),bk=Ur(),it=j(),wk=et(),vk=W(),Sk=rt(),kk=nt(),xk=Hs(),Ek=pc(),Ak=hc(),Tk=yc(),Vs=vp(),Sp=Br();F.Composer=hk.Composer;F.Document=gk.Document;F.Schema=yk.Schema;F.YAMLError=bc.YAMLError;F.YAMLParseError=bc.YAMLParseError;F.YAMLWarning=bc.YAMLWarning;F.Alias=bk.Alias;F.isAlias=it.isAlias;F.isCollection=it.isCollection;F.isDocument=it.isDocument;F.isMap=it.isMap;F.isNode=it.isNode;F.isPair=it.isPair;F.isScalar=it.isScalar;F.isSeq=it.isSeq;F.Pair=wk.Pair;F.Scalar=vk.Scalar;F.YAMLMap=Sk.YAMLMap;F.YAMLSeq=kk.YAMLSeq;F.CST=xk;F.Lexer=Ek.Lexer;F.LineCounter=Ak.LineCounter;F.Parser=Tk.Parser;F.parse=Vs.parse;F.parseAllDocuments=Vs.parseAllDocuments;F.parseDocument=Vs.parseDocument;F.stringify=Vs.stringify;F.visit=Sp.visit;F.visitAsync=Sp.visitAsync});function Ok(r){try{return JSON.parse(r.trim()),!0}catch{return!1}}function Ck(r){let e=r.trim();if(!e.startsWith("<"))return!1;let t=e.match(Pk);return t?Dr(e,t[1])!==null:!1}function _k(r){let e=r.trim();if(!e.match(/^(---|#|\w+:|-)/)||"[{<".includes(e[0]))return!1;try{let t=xp.parse(e);return t!==null&&typeof t=="object"}catch{return!1}}function Ep(r){return Ok(r)||Ck(r)||_k(r)}var xp,Pk,wc=A(()=>{Iu();xp=Dy(kp(),1),Pk=/<([a-zA-Z_][\w.-]*)/});function Rk(r){if(!r?.trim())return[];let e=r.replace(/\r\n/g,`
|
|
157
|
+
`),t=e.trim();if(Ep(t))return[{text:t,startLine:1,endLine:e.split(`
|
|
158
158
|
`).length}];let n=e.split(`
|
|
159
159
|
`),s=[],i=0,o=-1,a=0,c=()=>{if(o>=i){let l=n.slice(i,o+1).join(`
|
|
160
|
-
`).trim();l&&s.push({text:l,startLine:i+1,endLine:o+1})}};for(let l=0;l<n.length;l++)n[l].trim()?(a>=2&&o>=i&&(c(),i=l),a=0,o=l):a++;return c(),s}function Gs(r){return
|
|
160
|
+
`).trim();l&&s.push({text:l,startLine:i+1,endLine:o+1})}};for(let l=0;l<n.length;l++)n[l].trim()?(a>=2&&o>=i&&(c(),i=l),a=0,o=l):a++;return c(),s}function Gs(r){return Rk(r).map(e=>e.text)}var Ap,Tp=A(()=>{wc();Ap=`
|
|
161
161
|
|
|
162
162
|
|
|
163
|
-
`});var je=A(()=>{Gn();No();
|
|
164
|
-
`).length-1}));return n}function
|
|
165
|
-
`);for(let o=0;o<i.length;o++){let a=i[o],c=o+1;for(let l of
|
|
166
|
-
`)).filter(({root:n})=>!t.has(n)).map(({root:n,lineIndex:s})=>({type:"UNDECLARED_IMPORT",severity:"error",message:
|
|
163
|
+
`});var je=A(()=>{Gn();No();Au();Tu();wc();Tp();zn()});function cr(r){return{...Su(r),server:r.files.get("server.ts")??""}}function zs(r){return!!r.server&&!r.code}var gn=A(()=>{je();je()});function Lk(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 Pp(r){let e=[];for(let s of $k)for(let i of r.matchAll(s)){let o=Lk(i[1]);o&&e.push({root:o,index:i.index??0})}e.sort((s,i)=>s.index-i.index);let t=new Set,n=[];for(let{root:s,index:i}of e)t.has(s)||(t.add(s),n.push({root:s,lineIndex:r.slice(0,i).split(`
|
|
164
|
+
`).length-1}));return n}function Op(r){return Pp(r).map(e=>e.root)}function yn(r,e){if(!r)return[];let{target:t,dependencies:n}=e,s=[],i=r.split(`
|
|
165
|
+
`);for(let o=0;o<i.length;o++){let a=i[o],c=o+1;for(let l of Ik)l.targets.includes(t)&&l.pattern.test(a)&&s.push({type:l.type,severity:"error",message:Bk(l.type,c),lineNumber:c,lineContent:a})}return t==="client"&&n&&s.push(...Mk(i,n)),s}function Mk(r,e){let t=new Set(Object.keys(e));return Pp(r.join(`
|
|
166
|
+
`)).filter(({root:n})=>!t.has(n)).map(({root:n,lineIndex:s})=>({type:"UNDECLARED_IMPORT",severity:"error",message:Dk(n,s+1),lineNumber:s+1,lineContent:r[s]}))}function Dk(r,e){return`Import "${r}" is not declared in config.json dependencies! Found on line ${e}.
|
|
167
167
|
|
|
168
168
|
**CRITICAL**: Every bare import in code.tsx must be declared in the **config.json** "dependencies" block. A bulb that imports a package it doesn't declare is incomplete \u2014 it won't type-check, its versions aren't pinned, and it can't be reliably re-run or ported to typebulb.com.
|
|
169
169
|
|
|
@@ -177,7 +177,7 @@ ${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.pus
|
|
|
177
177
|
}
|
|
178
178
|
\`\`\`
|
|
179
179
|
|
|
180
|
-
**Fix:** Add a **config.json** block (or extend the existing one) with a "dependencies" entry for "${r}" \u2014 and for every other bare import in code.tsx. Pin a real version where you can (e.g. "react": "^19.2.7").`}function
|
|
180
|
+
**Fix:** Add a **config.json** block (or extend the existing one) with a "dependencies" entry for "${r}" \u2014 and for every other bare import in code.tsx. Pin a real version where you can (e.g. "react": "^19.2.7").`}function Bk(r,e){return r==="URL_IMPORT"?`Direct URL imports are not supported! Found on line ${e}.
|
|
181
181
|
|
|
182
182
|
**CRITICAL**: Import packages by name only. Do NOT use CDN URLs:
|
|
183
183
|
|
|
@@ -331,7 +331,7 @@ import { something } from 'module-name'
|
|
|
331
331
|
const something = require('module-name') // NOT SUPPORTED!
|
|
332
332
|
\`\`\`
|
|
333
333
|
|
|
334
|
-
**Fix:** Replace all \`require()\` calls with ES6 \`import\` statements at the top of the file.`}var Ot,Ct,
|
|
334
|
+
**Fix:** Replace all \`require()\` calls with ES6 \`import\` statements at the top of the file.`}var Ot,Ct,Ik,$k,Qs=A(()=>{Ot=["client"],Ct=["client","server"],Ik=[{type:"DYNAMIC_IMPORT",pattern:/\bimport\s*\(\s*['"`]/,targets:Ot},{type:"COMMONJS_REQUIRE",pattern:/\brequire\s*\(\s*['"`]/,targets:Ct},{type:"JS_EXTENSION_IMPORT",pattern:/from\s+['"][^'"]*\/[^'"]*\.js['"]/,targets:Ot},{type:"URL_IMPORT",pattern:/from\s+['"]https?:\/\//,targets:Ot},{type:"VERSION_SPECIFIER_IMPORT",pattern:/from\s+['"][^'"]*@[\d^~]/,targets:Ot},{type:"REDUNDANT_TB_DECLARATION",pattern:/declare\s+(const|var|let)\s+tb\b/,targets:Ct},{type:"CONST_ENUM",pattern:/\bconst\s+enum\b/,targets:Ct},{type:"NAMESPACE_DECLARATION",pattern:/\bnamespace\s+\w+/,targets:Ct},{type:"COMMONJS_EXPORT_EQUALS",pattern:/\bexport\s*=/,targets:Ct},{type:"COMMONJS_IMPORT_EQUALS",pattern:/\bimport\s+\w+\s*=/,targets:Ct},{type:"MODULE_DECLARATION",pattern:/\bmodule\s+\w+\s*\{/,targets:Ct},{type:"CSS_FILE_IMPORT",pattern:/(?:from|import)\s+['"][^'"]*\.css['"]/,targets:Ot},{type:"NAVIGATION",pattern:/window\.(location\.(reload|assign|replace)\s*\(|open\s*\()/,targets:Ot},{type:"NAVIGATION",pattern:/window\.location(\.href)?\s*=[^=]/,targets:Ot}],$k=[/\bimport\s+(?:[^'";]*?from\s*)?['"]([^'"]+)['"]/g,/\bexport\s+[^'";]*?from\s*['"]([^'"]+)['"]/g]});var Gp=A(()=>{});var ue,ke,dr=A(()=>{ue=class extends Error{constructor(e,t="unknown",n=!1){super(e),this.code=t,this.retryable=n}},ke=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=`
|
|
335
335
|
|
|
336
336
|
`){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 ue(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 ue(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 di,Pc=A(()=>{dr();di=class extends ke{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(`
|
|
337
337
|
`)),!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 ue(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(`
|
|
@@ -339,13 +339,13 @@ const something = require('module-name') // NOT SUPPORTED!
|
|
|
339
339
|
`)}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 pr,pi=A(()=>{dr();pr=class extends ke{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 mi,Oc=A(()=>{pi();mi=class extends pr{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 hi,Cc=A(()=>{dr();hi=class extends ke{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(`
|
|
340
340
|
|
|
341
341
|
`);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 gi,_c=A(()=>{dr();gi=class extends ke{constructor(){super(...arguments),this.providerName="Gemini",this.defaultBaseUrl="https://generativelanguage.googleapis.com",this.path="/v1beta/models",this.budgetMap={0:0,1:1024,2:8192,3:-1}}getPath(e,t){return`/v1beta/models/${e}:${t?"streamGenerateContent":"generateContent"}${t?"?alt=sse":""}`}buildHeaders(e){return{"Content-Type":"application/json","x-goog-api-key":e}}buildPayload(e,t,n,s){let{system:i,conversationMessages:o}=this.extractSystemMessages(e,`
|
|
342
|
-
`),c={contents:o.map(
|
|
343
|
-
`)[0],type:s.status,code:s.code?.toString()}:n.message?{message:n.message}:{message:e}}catch{return{message:e}}}parseNonStreamingResponse(e){if(this.checkAndThrowError(e),this.checkGeminiError(e),!this.isGeminiResponse(e))return{text:"",status:"failed",error:"Invalid response format"};let t=this.extractParts(e).text||"",n=e.candidates?.[0]?.finishReason,s="complete";return n==="MAX_TOKENS"?s="interrupted":(n==="SAFETY"||n==="RECITATION")&&(s="failed"),{text:t,status:s}}parseProviderStreamChunk(e){if(this.checkGeminiError(e),!this.isGeminiResponse(e))return null;let t=this.extractParts(e);return t.text||t.reasoning?t:null}geminiVersion(e){let t=e.match(/^gemini-(\d+(?:\.\d+)?)/);return t?Number(t[1]):null}thinkingLevelFor(e,t){let n=["minimal","low","medium","high"][t];return n==="minimal"&&e<3.5?"low":n}isGeminiResponse(e){return typeof e=="object"&&e!==null&&"candidates"in e&&Array.isArray(e.candidates)}extractParts(e){let t=e.candidates?.[0]?.content?.parts;if(!t)return{};let n="",s="";for(let i of t)i.text&&(i.thought?s+=i.text:n+=i.text);return{text:n||void 0,reasoning:s||void 0}}checkGeminiError(e){if(this.isGeminiResponse(e)&&e.promptFeedback?.blockReason){let t=e.promptFeedback.blockReason;throw new ue(`Prompt blocked: ${t}`)}}}});var yi,Rc=A(()=>{pi();yi=class extends pr{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 $t(r){let e=
|
|
342
|
+
`),c={contents:o.map(f=>({role:f.role==="assistant"?"model":"user",parts:[{text:f.content}]}))};n?.webSearch!==!1&&(c.tools=[{google_search:{}}]),i&&(c.systemInstruction={role:"system",parts:[{text:i}]});let l=n?.effort;if(l!==void 0){let f=this.geminiVersion(t),u=f!==null&&f>=3?{thinkingLevel:this.thinkingLevelFor(f,l)}:{thinkingBudget:this.budgetMap[l]};c.generationConfig={thinkingConfig:l===0?u:{includeThoughts:!0,...u}}}return c}parseError(e,t){if(!e)return{message:`HTTP ${t}`};try{let n=JSON.parse(e),s=Array.isArray(n)?n[0]?.error:n?.error;return s&&typeof s=="object"?{message:(s.message||`HTTP ${t}`).split(`
|
|
343
|
+
`)[0],type:s.status,code:s.code?.toString()}:n.message?{message:n.message}:{message:e}}catch{return{message:e}}}parseNonStreamingResponse(e){if(this.checkAndThrowError(e),this.checkGeminiError(e),!this.isGeminiResponse(e))return{text:"",status:"failed",error:"Invalid response format"};let t=this.extractParts(e).text||"",n=e.candidates?.[0]?.finishReason,s="complete";return n==="MAX_TOKENS"?s="interrupted":(n==="SAFETY"||n==="RECITATION")&&(s="failed"),{text:t,status:s}}parseProviderStreamChunk(e){if(this.checkGeminiError(e),!this.isGeminiResponse(e))return null;let t=this.extractParts(e);return t.text||t.reasoning?t:null}geminiVersion(e){let t=e.match(/^gemini-(\d+(?:\.\d+)?)/);return t?Number(t[1]):null}thinkingLevelFor(e,t){let n=["minimal","low","medium","high"][t];return n==="minimal"&&e<3.5?"low":n}isGeminiResponse(e){return typeof e=="object"&&e!==null&&"candidates"in e&&Array.isArray(e.candidates)}extractParts(e){let t=e.candidates?.[0]?.content?.parts;if(!t)return{};let n="",s="";for(let i of t)i.text&&(i.thought?s+=i.text:n+=i.text);return{text:n||void 0,reasoning:s||void 0}}checkGeminiError(e){if(this.isGeminiResponse(e)&&e.promptFeedback?.blockReason){let t=e.promptFeedback.blockReason;throw new ue(`Prompt blocked: ${t}`)}}}});var yi,Rc=A(()=>{pi();yi=class extends pr{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 $t(r){let e=cx.get(r);if(!e)throw new Error(`Unsupported protocol: ${r}`);return e}function lx(r,e){return r.replace(/\/+$/,"")+(e.startsWith("/")?e:`/${e}`)}async function Nc(r,e){let t=$t(r.protocol),n=t.getPath(r.model,e.stream),s=lx(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 ux(r){return/prompt is too long|context[_ ](length|window)|maximum context|token count exceeds|too many tokens/i.test(r)}async function mr(r,e){let t=$t(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||ux(s))&&(o="context_exceeded"),{code:o,message:s,retryable:i===429||i>=500}}var zp,cx,Ic=A(()=>{Pc();Oc();Cc();_c();Rc();zp=new yi,cx=new Map([["openai",new di],["openrouter",new mi],["anthropic",new hi],["gemini",new gi],["ollama",zp],["openai-compat",zp]])});function Qp(r){let e=r.indexOf(`\r
|
|
344
344
|
\r
|
|
345
345
|
`),t=r.indexOf(`
|
|
346
346
|
|
|
347
347
|
`);return e!==-1&&(t===-1||e<t)?{pos:e,len:4}:t!==-1?{pos:t,len:2}:{pos:-1,len:0}}function $c(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(`
|
|
348
|
-
`).trim();if(!n)return null;if(n==="[DONE]")return"done";try{return JSON.parse(n)}catch{return null}}async function*
|
|
348
|
+
`).trim();if(!n)return null;if(n==="[DONE]")return"done";try{return JSON.parse(n)}catch{return null}}async function*Xp(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=$c(s);u!==null&&u!=="done"&&(yield u)}return}t?.(),s+=n.decode(c,{stream:!0});let{pos:l,len:f}=Qp(s);for(;l!==-1;){let u=s.slice(0,l);s=s.slice(l+f);let d=$c(u);if(d==="done")return;d!==null&&(yield d),{pos:l,len:f}=Qp(s)}}}finally{i&&e?.removeEventListener("abort",i);try{await r.cancel()}catch{}}}async function Lt(r,e){if(!r.body)throw new Error("Response body is missing");let t="";for await(let n of Mt(r,e))n.kind==="text"&&(t+=n.text);return t}async function*Mt(r,e){let t=e??(r.headers.get("X-Provider-Protocol")||"openai"),n=$t(t);if(!r.body)return;let s=r.body.getReader();for await(let i of Xp(s)){let o=n.parseStreamChunk(i);o?.reasoning&&(yield{kind:"reasoning",text:o.reasoning}),o?.text&&(yield{kind:"text",text:o.text})}}var Zp=A(()=>{Ic()});import{strToU8 as fx,strFromU8 as dx,deflateSync as px,inflateSync as mx}from"fflate";function Mc(r,e){let t=[];if(t.push(`You are a data processor. Follow the instructions to analyze the provided data. Output valid JSON that the code can consume.
|
|
349
349
|
|
|
350
350
|
---
|
|
351
351
|
Instructions:
|
|
@@ -363,35 +363,35 @@ ${n}
|
|
|
363
363
|
</data>`)}return t.push(`
|
|
364
364
|
Output only valid JSON. No explanation, no markdown fences, just the JSON object. Every number must be a JSON literal \u2014 never an expression like 2 * pi; write the computed decimal instead.`),t.join(`
|
|
365
365
|
|
|
366
|
-
`)}function An(r){try{return JSON.parse(r)}catch{return null}}function
|
|
367
|
-
`)}var gr,
|
|
368
|
-
\u2026[${r.length-5e4} more characters truncated]`:r}function He(r){let e=r.replace(
|
|
369
|
-
`).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
|
|
370
|
-
`):r==null?"":_e(JSON.stringify(r))}function
|
|
371
|
-
`).length,"line")}`;if(t.mode==="content")return Ee(t.numLines??0,"line");if(t.mode==="count")return`${Ee(t.numMatches??0,"match","matches")} (${Ee(t.numFiles??0,"file")})`;if(t.mode==="files_with_matches")return Ee(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":He(t.stdout||t.stderr||"")||"no output":typeof t.code=="number"&&typeof t.codeText=="string"?`${t.code} ${t.codeText}`:typeof t.searchCount=="number"?Ee(t.searchCount,"search","searches"):Array.isArray(t.matches)&&typeof t.total_deferred_tools=="number"?Ee(t.matches.length,"tool"):Array.isArray(t.newTodos)?Ee(t.newTodos.length,"todo"):typeof t.numFiles=="number"?Ee(t.numFiles,"file"):He(e)}function _n(r){return!!r.isSidechain||!!r.isMeta}function
|
|
372
|
-
`)){if(!p.includes(`"${
|
|
373
|
-
`)){if(!l.trim())continue;let
|
|
374
|
-
`),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??""),
|
|
375
|
-
`),n=[];if(t.forEach((o,a)=>{let c=
|
|
376
|
-
`)}function il(r){try{return process.kill(r,0),!0}catch(e){return e.code==="EPERM"}}async function
|
|
366
|
+
`)}function An(r){try{return JSON.parse(r)}catch{return null}}function gx(r,e){let t="",n=0,s=!1,i=!1;for(let o=0;o<r.length;o++){let a=r[o];if(i){i=!1;continue}if(a==="\\"){i=!0;continue}a==='"'&&(s?(t+=r.slice(n,o+1),n=o+1):(t+=e(r.slice(n,o))+'"',n=o+1),s=!s)}return t+=s?r.slice(n):e(r.slice(n)),t}function yx(r){let e=gx(r,t=>t.replace(/\bpi\b/g,"3.141592653589793").replace(/\be\b/g,"2.718281828459045").replace(/-?\d[\d.\s+\-*/()]*\d|\(-?\d[\d.\s+\-*/()]*\d\)/g,n=>{if(!/[+\-*/]/.test(n.replace(/^-/,""))||n.length>64||!/^[\d\s.+\-*/()]+$/.test(n))return n;try{let s=Function(`"use strict"; return (${n})`)();return typeof s=="number"&&Number.isFinite(s)?String(s):n}catch{return n}}));return e!==r?e:null}function bx(r,e){let t=0,n=!1,s=!1;for(let i=e;i<r.length;i++){let o=r[i];if(s){s=!1;continue}if(o==="\\"){s=!0;continue}if(o==='"'){n=!n;continue}if(!n){if(o==="{"||o==="[")t++;else if((o==="}"||o==="]")&&(t--,t===0))return i}}return-1}function wx(r){let e=null,t=0;for(;t<r.length;){let n=r[t];if(n==="{"||n==="["){let s=bx(r,t);if(s!==-1){let i=r.slice(t,s+1),o=An(i);o!==null&&(e={parsed:o,json:i}),t=s+1;continue}}t++}return e}function Dc(r){let e=[],t=r.trim();t.startsWith("```")&&(t=t.replace(/^```(?:json)?\s*\n?/,"").replace(/\n?```\s*$/,""),e.push("markdown fences"));let n=An(t);if(n!==null)return{parsed:n,json:t,fixesApplied:e};let s=t.match(/```(?:json)?\s*\n([\s\S]*?)\n?```\s*$/);if(s&&(t=s[1].trim(),e.push("preamble before fenced JSON"),n=An(t),n!==null))return{parsed:n,json:t,fixesApplied:e};if(!t.startsWith("{")&&!t.startsWith("[")){let o=t.indexOf("{"),a=t.indexOf("["),c=o>=0&&a>=0?Math.min(o,a):o>=0?o:a;if(c>0&&(t=t.slice(c),e.push("preamble text"),n=An(t),n!==null))return{parsed:n,json:t,fixesApplied:e}}for(let[o,a]of hx){let c=a(t);if(c!==null){let l=An(c);if(l!==null)return{parsed:l,json:c,fixesApplied:[...e,o]}}}let i=wx(r);return i!==null?{...i,fixesApplied:[...e,"extracted last JSON value"]}:{parsed:null,json:t,fixesApplied:e}}function Bc(r){try{let e={i:r.insight,d:r.data},t=JSON.stringify(e),n=px(fx(t),{level:9}),s=Sx(n),i=`${em}:${s}`;return i.length>vx?"":"#"+Lc+i}catch{return""}}function jc(r){try{let e=r.startsWith("#")?r.slice(1):r;if(!e.startsWith(Lc))return null;let t=e.slice(Lc.length),n=t.indexOf(":");if(n===-1||t.slice(0,n)!==em)return null;let s=kx(t.slice(n+1)),i=JSON.parse(dx(mx(s)));return!i||typeof i.i>"u"||!Array.isArray(i.d)?null:{insight:i.i,insightJson:JSON.stringify(i.i,null,2),data:i.d}}catch{return null}}function Sx(r){let e="";for(let t=0;t<r.length;t+=32768)e+=String.fromCharCode(...r.subarray(t,t+32768));return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function kx(r){let e=r.replace(/-/g,"+").replace(/_/g,"/");for(;e.length%4;)e+="=";let t=atob(e),n=new Uint8Array(t.length);for(let s=0;s<t.length;s++)n[s]=t.charCodeAt(s);return n}var hx,Lc,em,vx,tm=A(()=>{hx=[["orphan quote",r=>{let e=r.replace(/^[ \t]*"[ \t]*\r?\n/gm,"");return e!==r?e:null}],["trailing }",r=>r.endsWith("}}")?r.slice(0,-1):null],["trailing ]",r=>r.endsWith("]]")?r.slice(0,-1):null],["trailing },",r=>r.endsWith("},")?r.slice(0,-1):null],["trailing ],",r=>r.endsWith("],")?r.slice(0,-1):null],["trailing comma in object",r=>r.match(/,\s*\}$/)?r.replace(/,\s*\}$/,"}"):null],["trailing comma in array",r=>r.match(/,\s*\]$/)?r.replace(/,\s*\]$/,"]"):null],["arithmetic constants",yx]];Lc="tb=",em="1",vx=6e4});var hr=A(()=>{Gp();dr();Ic();Zp();tm();pi();Cc();_c();Pc();Oc();Rc()});function yr(r){return(r.includes("://")?r:`http://${r}`).replace(/\/+$/,"")}function Fc(){return Pn}async function Ue(){let[r,e]=await Promise.all([nm(),Px()]);return[...Ox(e),...r]}async function rm(){let r;try{r=await fetch(xx,{signal:AbortSignal.timeout(Ax)})}catch(e){return Pn=`catalog fetch failed: ${e?.message??e}`,null}if(!r.ok)return Pn=`catalog fetch failed: HTTP ${r.status}`,null;try{return await r.json()}catch(e){return Pn=`catalog returned an unreadable body: ${e?.message??e}`,null}}async function Px(){if(Tn&&Date.now()-Tn.fetchedAt<=Ex)return Tn.models;let r=await rm()??await rm();return r?(Tn={models:r,fetchedAt:Date.now()},Pn=null,r):Tn?.models??[]}async function nm(){if(bi&&Date.now()-bi.fetchedAt<=Tx)return bi.models;let r=yr(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 bi={models:e,fetchedAt:Date.now()},e}function Ox(r){let e=new Set(Object.entries(gr).filter(([,t])=>!!process.env[t]).map(([t])=>t));return r.filter(t=>e.has(t.provider))}function qc(){return Object.values(gr).some(r=>!!process.env[r])}async function wi(){return qc()||process.env.TB_AI_BASE_URL?!0:(await nm()).length>0}function sm(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(`
|
|
367
|
+
`)}var gr,xx,Ex,Ax,Tx,Tn,bi,Pn,Dt=A(()=>{gr={anthropic:"ANTHROPIC_API_KEY",openai:"OPENAI_API_KEY",gemini:"GOOGLE_API_KEY",openrouter:"OPENROUTER_API_KEY"};xx="https://api.typebulb.com/api/models",Ex=1440*60*1e3,Ax=5e3,Tx=60*1e3,Tn=null,bi=null,Pn=null});function Je(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=$t(t)}catch{return`Unknown provider '${t}'.`}if(t==="ollama")return{apiKey:"",baseUrl:`${yr(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=gr[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 ut(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 Nc(r,{messages:t,stream:!0,effort:n!=null&&n>=0&&n<=3?n:void 0,webSearch:e.webSearch??!0,signal:e.signal})}var vi=A(()=>{hr();Dt()});import{realpathSync as Nx}from"fs";import{join as Kc,resolve as Ix}from"path";import{homedir as $x}from"os";function ki(){let r=process.env.TYPEBULB_SERVERS_DIR;return r?Kc(r,".."):Kc($x(),".typebulb")}function Ke(){return process.env.TYPEBULB_SERVERS_DIR||Kc(ki(),"servers")}function ee(r){let e=Ix(r),t=e;try{t=Nx.native(e)}catch{}return(process.platform==="win32"?t.toLowerCase():t).replace(/\\/g,"/")}function cm(r,e){let t=ee(r),n=ee(e);return t.startsWith(n.endsWith("/")?n:n+"/")?!t.includes("/node_modules/"):!1}var xi=A(()=>{});import{readFileSync as Lx,writeFileSync as Mx,mkdirSync as Dx}from"fs";import{join as Bx}from"path";function lm(){return Bx(ki(),"trust.json")}function Hc(){try{let r=JSON.parse(Lx(lm(),"utf8"));return new Set(Array.isArray(r)?r:[])}catch{return new Set}}function jx(r){Dx(ki(),{recursive:!0}),Mx(lm(),JSON.stringify([...r]))}function Bt(r){return Hc().has(ee(r))}function br(r,e){let t=Hc(),n=ee(r);(e?t.has(n):!t.has(n))||(e?t.add(n):t.delete(n),jx(t))}function Wc(){return[...Hc()]}var Cn=A(()=>{xi()});function _e(r){return r.length>5e4?r.slice(0,5e4)+`
|
|
368
|
+
\u2026[${r.length-5e4} more characters truncated]`:r}function He(r){let e=r.replace(Fx,"").split(`
|
|
369
|
+
`).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 Fx,Ei,Ai=A(()=>{Fx=/\u001b\[[0-9;]*m/g;Ei=(r,e)=>``});import{existsSync as qx,readdirSync as Ux,statSync as Jx}from"fs";import{join as Kx}from"path";function Ti(r){if(!qx(r))return[];let e;try{e=Ux(r)}catch{return[]}let t=[];for(let n of e){if(!n.endsWith(".jsonl"))continue;let s=Kx(r,n);try{let i=Jx(s);i.isFile()&&t.push({sessionId:n.slice(0,-6),file:s,mtime:i.mtimeMs})}catch{}}return t}var Yc=A(()=>{});var wr,Vc=A(()=>{wr=class{ensureHarnessSupport(){}}});import{openSync as Hx,readSync as Wx,closeSync as Yx,statSync as Vx,readdirSync as Gx,readFileSync as zx,existsSync as Qx}from"fs";import{join as Rn}from"path";import{homedir as Qc}from"os";function Xx(r){return r.replace(/[^a-zA-Z0-9]/g,"-")}function Pi(r){let e=r?.type==="image"?r.source:void 0;return e?.type==="base64"&&e.data?Ei(e.data,e.media_type):""}function Gc(r){return typeof r=="string"?_e(r):Array.isArray(r)?r.map(e=>{if(typeof e=="string")return _e(e);let t=e;return typeof t?.text=="string"?_e(t.text):t?.content!=null?Gc(t.content):Pi(t)}).join(`
|
|
370
|
+
`):r==null?"":_e(JSON.stringify(r))}function e0(r){let e=r.trim();return!!e&&pm.some(t=>t.test(e))}function t0(r){let e=r.trim();return e?pm.some(t=>{let n=t.exec(e);return!!n&&n.index===0}):!0}function n0(r){return r.replace(r0,"")}function s0(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 dt(r){let e=n0(r).trim();return e?s0(e)??(e0(e)?"":e):""}function zc(r){return r?.type==="text"&&typeof r.text=="string"?dt(r.text):""}function Xc(r,e){if(typeof r=="string")return He(r);if(!r||typeof r!="object")return He(e);let t=r;if(t.type==="text"&&typeof t.file?.numLines=="number")return Ee(t.file.numLines,"line");if(t.type==="image"){let n=fm(t.file?.originalSize);return n?`image (${n})`:"image"}if(t.type==="pdf"){let n=fm(t.file?.originalSize);return n?`PDF (${n})`:"PDF"}if(t.type==="parts"&&typeof t.file?.count=="number")return Ee(t.file.count,"page");if(t.type==="file_unchanged")return"unchanged since last read";if(t.type==="create"&&typeof t.content=="string")return`created, ${Ee(t.content.split(`
|
|
371
|
+
`).length,"line")}`;if(t.mode==="content")return Ee(t.numLines??0,"line");if(t.mode==="count")return`${Ee(t.numMatches??0,"match","matches")} (${Ee(t.numFiles??0,"file")})`;if(t.mode==="files_with_matches")return Ee(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":He(t.stdout||t.stderr||"")||"no output":typeof t.code=="number"&&typeof t.codeText=="string"?`${t.code} ${t.codeText}`:typeof t.searchCount=="number"?Ee(t.searchCount,"search","searches"):Array.isArray(t.matches)&&typeof t.total_deferred_tools=="number"?Ee(t.matches.length,"tool"):Array.isArray(t.newTodos)?Ee(t.newTodos.length,"todo"):typeof t.numFiles=="number"?Ee(t.numFiles,"file"):He(e)}function _n(r){return!!r.isSidechain||!!r.isMeta}function i0(r){let e;try{e=Hx(r,"r")}catch{return""}try{let n=65536;try{n=Vx(r).size}catch{}let s=(l,f)=>{if(f<=0)return"";let u=Buffer.alloc(f),d=Wx(e,u,0,f,l);return u.subarray(0,d).toString("utf8")},i=(l,f,u)=>{let d="";for(let p of l.split(`
|
|
372
|
+
`)){if(!p.includes(`"${f}"`))continue;let y;try{y=JSON.parse(p)}catch{continue}let m=y?.[u];y?.type===f&&typeof m=="string"&&m&&(d=m)}return d},o=s(0,Math.min(65536,n)),a=n>65536?s(n-65536,65536):"",c=i(a,"custom-title","customTitle")||i(o,"custom-title","customTitle")||i(a,"ai-title","aiTitle")||i(o,"ai-title","aiTitle");if(c)return c.replace(/\s+/g," ").trim().slice(0,200);for(let l of o.split(`
|
|
373
|
+
`)){if(!l.trim())continue;let f;try{f=JSON.parse(l)}catch{continue}if(!f||_n(f)||f.type!=="user")continue;let u=f.message?.content,d="";typeof u=="string"?d=dt(u):Array.isArray(u)&&(d=u.map(zc).filter(Boolean).join(" "));let p=d.replace(/\s+/g," ").trim();if(p)return(p.replace(/^Continuing from a prior session\. Here is the summary of our work so far:\s*/i,"").trim()||p).slice(0,200)}return""}finally{Yx(e)}}function o0(r){let e;try{e=Gx(dm)}catch{return!1}for(let t of e)if(t.endsWith(".json"))try{let n=JSON.parse(zx(Rn(dm,t),"utf8"));if(n?.sessionId!==r)continue;return process.kill(n.pid,0),!0}catch{}return!1}var Zx,um,pm,r0,Ee,fm,dm,vr,Oi=A(()=>{Ai();Yc();Vc();Zx=Rn(Qc(),".claude","projects"),um=r=>Rn(Zx,Xx(r));pm=[/\[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];r0=/<ide_[a-z_]+>[\s\S]*?<\/ide_[a-z_]+>/gi;Ee=(r,e,t=e+"s")=>`${r} ${r===1?e:t}`,fm=r=>typeof r!="number"?"":r<1024?`${r}B`:r<1048576?`${Math.round(r/1024)}KB`:`${(r/1048576).toFixed(1)}MB`;dm=Rn(Qc(),".claude","sessions");vr=class extends wr{displayName="Claude Mirror";detectsSelf(){return process.env.CLAUDECODE==="1"}detectsInstalled(){return Qx(Rn(Qc(),".claude"))}sessionsDir(e){return um(e)}listSessionFiles(e){return Ti(um(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(_n(e))return{events:[]};let n=[];if(e.type==="user"){let s=e.message?.content;if(typeof s=="string"){let i=dt(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=Gc(i.content);n.push({type:"tool_result",id:i.tool_use_id??"",content:o,isError:!!i.is_error,digest:Xc(e.toolUseResult,o)})}else{let o=zc(i)||Pi(i);o&&n.push({type:"user",text:o})}return{events:n}}if(e.type==="attachment"&&e.attachment?.type==="queued_command"){let s=dt(Gc(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=>!t0(u)).join(""),a=i.filter(u=>u.type==="thinking").map(u=>u.thinking??"").join(`
|
|
374
|
+
`),c=i.filter(u=>u.type==="tool_use").map(u=>({id:u.id??"",name:u.name??"",input:u.input??{}}));if(o||a||c.length){let u=Date.parse(e.timestamp??""),d=!isNaN(u)&&u>=t;n.push({type:"assistant",text:o,thinking:a,tools:c,live:d})}let l=e.message?.usage??e.usage,f=l&&{in:l.input_tokens??0,out:l.output_tokens??0,cached:l.cache_read_input_tokens??0,cacheCreate:l.cache_creation_input_tokens??0};return{events:n,usage:f,model:e.message?.model}}return{events:n}}chainWorking(e){let t;for(let o of e)(o.type==="user"||o.type==="assistant")&&(t=o);if(!t)return!1;if(t.type==="user"){try{let o=t.message?.content,a=typeof o=="string"?o:Array.isArray(o)?o.filter(l=>l&&l.type==="text").map(l=>l.text??"").join(""):"";if(!(Array.isArray(o)&&o.some(l=>l&&l.type==="tool_result"))&&a.trim()&&dt(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 o0(e)}readPreview(e){return i0(e)}searchText(e){if(!e||_n(e)||e.type!=="user"&&e.type!=="assistant")return"";let t=e.message?.content,n="";if(typeof t=="string")n=dt(t);else if(Array.isArray(t)){let s=t;n=e.type==="user"?s.map(zc).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 mm}from"child_process";import{readdir as a0,readFile as gm,writeFile as ym,unlink as Zc,mkdir as c0}from"fs/promises";import{mkdirSync as bm,writeFileSync as Ci,appendFileSync as l0,readFileSync as el}from"fs";import*as he from"path";import{fileURLToPath as u0}from"url";function tl(r){return he.join(Ke(),`${r}.json`)}function In(r){return he.join(Ke(),`${r}.log`)}function rl(r){return he.join(Ke(),`${r}.wait.json`)}function wm(r){try{let e=JSON.parse(el(rl(r),"utf8"));return e.cursors&&typeof e.cursors=="object"?e.cursors:{}}catch{return{}}}function nl(r,e=""){let t=wm(r)[e];return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}function _i(r,e,t=""){try{bm(Ke(),{recursive:!0});let n=wm(r);n[t]=e,Ci(rl(r),JSON.stringify({cursors:n}))}catch{}}function Ri(r){let e=In(r);try{bm(Ke(),{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(l0(e,c),s+=c.length,s>2*hm){let l=el(e),f=l.subarray(Math.max(0,l.length-hm));Ci(e,f),s=f.length}}catch{i=!0}};return process.stdout.write=((a,...c)=>(o(a),t(a,...c))),process.stderr.write=((a,...c)=>(o(a),n(a,...c))),()=>{process.stdout.write=t,process.stderr.write=n}}function vm(r){try{Ci(In(r),"")}catch{}}function Re(r,e=0){try{let t=el(In(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 sl(r){return`\u2500\u2500 run ${r} \u2500\u2500 ${new Date().toTimeString().slice(0,8)}`}function d0(r){let e=f0.exec(r);return e?Number(e[1]):void 0}function Sm(r,e){let t=r.split(`
|
|
375
|
+
`),n=[];if(t.forEach((o,a)=>{let c=d0(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(`
|
|
376
|
+
`)}function il(r){try{return process.kill(r,0),!0}catch(e){return e.code==="EPERM"}}async function km(r){await c0(Ke(),{recursive:!0}),await ym(tl(r.pid),JSON.stringify(r))}async function xm(r,e){let t=tl(r);try{let n=JSON.parse(await gm(t,"utf8"));if(n.denied===e)return;n.denied=e,await ym(t,JSON.stringify(n))}catch{}}async function Nn(r){await Zc(tl(r)).catch(()=>{}),await Zc(In(r)).catch(()=>{}),await Zc(rl(r)).catch(()=>{})}async function Y(r){let e;try{e=await a0(Ke())}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 gm(he.join(Ke(),s),"utf8"))}catch{await Nn(i);return}o&&typeof o.pid=="number"&&il(o.pid)?t.push(o):await Nn(i)})),(r?t.filter(s=>s.agent==null&&cm(s.file,r)):t).sort((s,i)=>s.startedAt-i.startedAt)}async function ol(r,e){let t=ee(r);return(await Y()).find(n=>n.cwd!=null&&ee(n.cwd)===t&&(e?n.agent===e:n.agent!=null))}async function jt(r){try{process.kill(r,"SIGTERM")}catch{}await Nn(r)}function Sr(r,e){let t=ee(e);return r.filter(n=>n.agent==null&&n.pid!==process.pid&&ee(n.file)===t)}async function al(r){let e=Sr(await Y(),r);for(let t of e)await jt(t.pid);return e}function m0(r,e,t){(process.platform==="win32"?mm("cmd",["/c","start","","/b",r,...e],{cwd:t,stdio:"ignore",windowsHide:!0}):mm(r,e,{cwd:t,detached:!0,stdio:"ignore"})).unref()}function Em(){return he.join(he.dirname(u0(import.meta.url)),"index.js")}function h0(r,e={}){return{command:process.execPath,args:[Em(),...e.trust?["--trust"]:[],r,...e.open===!1?["--no-open"]:[]]}}function g0(r){return{command:process.execPath,args:[Em(),`agent:${r}`,"--no-open"]}}async function Am(r,e,t,n){let s=await r();if(s)return s;m0(e.command,e.args,t);let i=Date.now()+2e4;for(;Date.now()<i;){await p0(150);let o=await r();if(o)return o}throw new Error(`Launched ${n} but it did not register within 20s.`)}async function Ni(r,e={}){let t=e.cwd??process.cwd(),n=he.resolve(t,r);return await al(n),Am(async()=>Sr(await Y(),n)[0],h0(r,e),t,he.basename(r))}async function Tm(r,e=process.cwd()){return Am(()=>ol(e,r),g0(r),e,`the ${r} mirror`)}var hm,f0,p0,Ne=A(()=>{xi();hm=1e6;f0=/^── run (\d+) ── /;p0=r=>new Promise(e=>setTimeout(e,r))});function Ii(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 cl(r){return(Ii(r)??"bulb").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"bulb"}var ll=A(()=>{});import{readdirSync as y0,readFileSync as b0,statSync as w0}from"fs";import{join as Pm,basename as v0}from"path";function Om(r,e,t){if(e>8)return t;let n;try{n=y0(r,{withFileTypes:!0})}catch{return t}for(let s of n)if(s.isDirectory()){if(s.name.startsWith(".")||s.name==="node_modules")continue;Om(Pm(r,s.name),e+1,t)}else s.isFile()&&s.name.endsWith(".bulb.md")&&t.push(Pm(r,s.name));return t}function $i(r){return Om(r,0,[]).map(e=>{let t=0;try{t=w0(e).mtimeMs}catch{}let n,s=!1;try{let i=b0(e,"utf8");n=Ii(i.slice(0,1024));let o=de(i);s=!!o&&zs(cr(o))}catch{}return{path:e,name:n??v0(e).replace(/\.bulb\.md$/,""),mtime:t,serverOnly:s}})}var Cm=A(()=>{je();gn();ll()});function kr(r){if(r.server.trim())return"server-side code (server.ts)";let e=r.code;if(/\btb\s*\.\s*fs\b/.test(e)||e.includes("/__fs"))return"the filesystem";if(/\btb\s*\.\s*ai\b/.test(e)||e.includes("/__ai")||r.infer.trim()||/\btb\s*\.\s*infer\b/.test(e))return"AI (your API keys)";if(/\btb\s*\.\s*server\s*\.\s*(?!log\b)\w/.test(e)||e.includes("/__api"))return"server-side code (server.ts)"}var Li=A(()=>{});import{readFile as S0}from"fs/promises";async function ul(r){try{let e=de(await S0(r,"utf-8"));return e?kr(cr(e)):void 0}catch{return}}var _m=A(()=>{gn();Li()});function fl(r){let e=de(r);if(!e)return r;let t=e.files.get("code.tsx");if(!t)return r;let n=Op(t);if(!n.length)return r;let s=e.files.get("config.json"),i={};if(s)try{let l=JSON.parse(s);l&&typeof l=="object"&&(i=l)}catch{}let o=i.dependencies&&typeof i.dependencies=="object"?{...i.dependencies}:{},a=n.filter(l=>!(l in o));if(!a.length)return r;for(let l of a)o[l]="latest";i.dependencies=o;let c={name:e.frontmatter.name};for(let[l,f]of e.files){let u=gu(l);u&&(c[u]=f)}return c.config=JSON.stringify(i,null,2),Eu(c)}var Rm=A(()=>{je();Qs()});import{spawn as Nm}from"child_process";import{basename as k0}from"path";function x0(){return process.env.TYPEBULB_EDITOR||"code"}function A0(r,e,t){return t==null?[e]:E0.test(k0(r))?["-g",`${e}:${t}`]:[`+${t}`,e]}function T0(r,e){let t=x0();return{command:t,args:A0(t,r,e)}}function dl(r,e){let{command:t,args:n}=T0(r,e),s=process.platform==="win32"?Nm("cmd.exe",["/d","/s","/c",t,...n],{detached:!0,stdio:"ignore",windowsHide:!0}):Nm(t,n,{detached:!0,stdio:"ignore"});s.on("error",i=>console.error("[typebulb] editor launch failed:",i?.message??i)),s.unref()}var E0,Im=A(()=>{E0=/^(code|code-insiders|codium|vscodium|cursor|windsurf)(\.cmd|\.exe)?$/i});import{readFileSync as P0,existsSync as O0}from"fs";import*as Ft from"path";import{fileURLToPath as C0}from"url";function $m(){let r=Ft.dirname(C0(import.meta.url));for(;!O0(Ft.join(r,"package.json"));){let e=Ft.dirname(r);if(e===r)break;r=e}return r}function qt(){return Ft.join($m(),"README.md")}function xr(){return Ft.join($m(),"description.md")}function _0(r){let e=P0(xr(),"utf8").trim().replace(/\s+/g," ");return`---
|
|
377
377
|
name: typebulb
|
|
378
378
|
description: ${JSON.stringify(e)}
|
|
379
379
|
version: ${r}
|
|
380
|
-
---`}function
|
|
380
|
+
---`}function R0(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 Lm(r,e){return`${_0(e)}
|
|
381
381
|
|
|
382
|
-
${
|
|
382
|
+
${R0(e)}
|
|
383
383
|
|
|
384
384
|
${r.trim()}
|
|
385
|
-
`}var Mi=A(()=>{});import{readFileSync as
|
|
386
|
-
`)){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 Di(r,e=process.cwd()){for(let t of
|
|
387
|
-
Expected <origin>/u/<user>/<slug>`);let u=
|
|
388
|
-
A pull target must be a bulb URL, or a local file at typebulbs/u/<user>/<slug>.bulb.md \u2014 the path is its remote identity.`);return{origin:t,userSlug:o,slug:a.slice(0,-8),dest:n}}async function Fi(r,e={}){let t=await fetch(pl(r),{headers:e.token?{Authorization:`Bearer ${e.token}`}:{},signal:e.timeoutMs?AbortSignal.timeout(e.timeoutMs):void 0});if(!t.ok)return{kind:"http-error",status:t.status};let n=t.headers.get("content-type");if(!n?.includes("text/markdown"))return{kind:"not-markdown",contentType:n};let s=await t.text(),i;try{i=await $e.readFile(r.dest,"utf-8")}catch{}if(i!==void 0){if(
|
|
389
|
-
`),n=de(t(r)),s=de(t(e));return!n||!s?t(r)===t(e):n.frontmatter.name===s.frontmatter.name&&Ge.every(i=>(n.files.get(Pe[i].path)||"")===(s.files.get(Pe[i].path)||""))}async function
|
|
385
|
+
`}var Mi=A(()=>{});import{readFileSync as Mm,existsSync as N0}from"fs";import*as Ie from"path";function Dm(r){return[...r?[`.env.${r}.local`,`.env.${r}`]:[],".env.local",".env"]}function ge(r,e=process.cwd()){let t={},n=[];for(let s of Dm(r)){let i;try{i=Mm(Ie.resolve(e,s),"utf-8")}catch{continue}n.push(s);for(let[o,a]of Bm(i))process.env[o]===void 0&&(process.env[o]=a,t[o]=s)}return{mode:r,sources:t,loaded:n}}function*Bm(r){for(let e of r.split(`
|
|
386
|
+
`)){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 Di(r,e=process.cwd()){for(let t of Dm()){let n;try{n=Mm(Ie.resolve(e,t),"utf-8")}catch{continue}for(let[s,i]of Bm(n))if(s===r)return i}return process.env[r]}function I0(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 pt(r,e,t){let{sources:n,mode:s,loaded:i}=r,o=process.cwd(),a=Ie.dirname(e),c=`(mode: ${s??"none"})`,l=t?I0(t):[],f=l.filter(p=>n[p]).map(p=>`${p} \u2190 ${n[p]}`);f.length?console.log(`env: ${f.join(", ")} ${c}`):i.length&&console.log(`env: loaded ${i.join(", ")} ${c}`),s&&!i.some(p=>p===`.env.${s}`||p===`.env.${s}.local`)&&console.log(`env: mode=${s} \u2014 no .env.${s} found; using .env`);let u=Ie.resolve(a)!==Ie.resolve(o);if(u)for(let p of[".env.local",".env"])N0(Ie.join(a,p))&&console.log(`env: ${Ie.join(a,p)} present but not loaded (cwd is ${o})`);let d=l.filter(p=>process.env[p]===void 0);if(d.length){let p=u?` \u2014 try running from ${a}`:"";console.log(`env: server.ts reads ${d.join(", ")} but ${d.length>1?"they are":"it's"} unset${p}`)}}var mt=A(()=>{});import*as $e from"fs/promises";import*as Ae from"path";function ml(r,e){ge(e);let t=process.env.TYPEBULB_ORIGIN||$0;try{return ji(r,process.cwd(),t)}catch(n){console.error(n instanceof Error?n.message:String(n)),process.exit(1)}}function ji(r,e,t){if(/^https?:\/\//i.test(r)){let c=new URL(r),l=c.pathname.split("/").filter(Boolean).map(decodeURIComponent),f=l[0]==="api"&&l[1]==="scripts"?l.slice(2):l;if(f[0]!=="u"||!f[1]||!f[2])throw new Error(`Not a bulb URL: ${r}
|
|
387
|
+
Expected <origin>/u/<user>/<slug>`);let u=f[1],d=f[2].replace(/(\.bulb)?\.md$/,"");return{origin:c.origin,userSlug:u,slug:d,dest:Ae.join(e,Bi(u,d))}}let n=Ae.resolve(e,r),[s,i,o,a]=n.split(Ae.sep).slice(-4);if(s!=="typebulbs"||i!=="u"||!o||!a?.endsWith(".bulb.md"))throw new Error(`Not a conventional bulb path: ${r}
|
|
388
|
+
A pull target must be a bulb URL, or a local file at typebulbs/u/<user>/<slug>.bulb.md \u2014 the path is its remote identity.`);return{origin:t,userSlug:o,slug:a.slice(0,-8),dest:n}}async function Fi(r,e={}){let t=await fetch(pl(r),{headers:e.token?{Authorization:`Bearer ${e.token}`}:{},signal:e.timeoutMs?AbortSignal.timeout(e.timeoutMs):void 0});if(!t.ok)return{kind:"http-error",status:t.status};let n=t.headers.get("content-type");if(!n?.includes("text/markdown"))return{kind:"not-markdown",contentType:n};let s=await t.text(),i;try{i=await $e.readFile(r.dest,"utf-8")}catch{}if(i!==void 0){if(L0(i,s))return{kind:"up-to-date",dest:r.dest};if(!e.force){let{mtime:a}=await $e.stat(r.dest);return{kind:"conflict",dest:r.dest,localMtime:a,remoteLastModified:t.headers.get("last-modified")}}}await $e.mkdir(Ae.dirname(r.dest),{recursive:!0}),await $e.writeFile(r.dest,s);let o=new Date(t.headers.get("last-modified")??"");return isNaN(o.getTime())||await $e.utimes(r.dest,new Date,o),{kind:"written",dest:r.dest,created:i===void 0}}function L0(r,e){let t=i=>i.replace(/\r\n/g,`
|
|
389
|
+
`),n=de(t(r)),s=de(t(e));return!n||!s?t(r)===t(e):n.frontmatter.name===s.frontmatter.name&&Ge.every(i=>(n.files.get(Pe[i].path)||"")===(s.files.get(Pe[i].path)||""))}async function jm(r,e){r||(console.error("Usage: typebulb pull <bulb url | typebulbs/u/<user>/<slug>.bulb.md>"),process.exit(1));let t=ml(r,e.mode),n=`${t.origin}/u/${t.userSlug}/${t.slug}`,s;try{s=await Fi(t,{force:e.force,token:process.env.TYPEBULB_TOKEN})}catch(o){console.error(`Could not reach ${t.origin}: ${o instanceof Error?o.message:String(o)}`),process.exitCode=1;return}let i=Ae.relative(process.cwd(),t.dest)||t.dest;switch(s.kind){case"written":console.log(`pulled ${n} \u2192 ${i}${s.created?"":" (overwritten)"}`);return;case"up-to-date":console.log(`up to date: ${i}`);return;case"conflict":console.error(`Refusing to overwrite ${i} \u2014 it differs from ${n}
|
|
390
390
|
local file modified ${s.localMtime.toISOString()}
|
|
391
391
|
remote last saved ${s.remoteLastModified??"unknown"}
|
|
392
|
-
Re-run with --force to overwrite the local file.`),process.exitCode=1;return;case"http-error":s.status===404?console.error(`Bulb not found: ${n}`):s.status===401||s.status===403?console.error(`This bulb is private (${s.status}) \u2014 pulling it needs a TYPEBULB_TOKEN for its owner.`):console.error(`Pull failed: ${t.origin} responded ${s.status}`),process.exitCode=1;return;case"not-markdown":console.error(`${n}.md did not return bulb markdown (got ${s.contentType??"no content-type"}) \u2014 is ${t.origin} a typebulb host?`),process.exitCode=1}}var
|
|
392
|
+
Re-run with --force to overwrite the local file.`),process.exitCode=1;return;case"http-error":s.status===404?console.error(`Bulb not found: ${n}`):s.status===401||s.status===403?console.error(`This bulb is private (${s.status}) \u2014 pulling it needs a TYPEBULB_TOKEN for its owner.`):console.error(`Pull failed: ${t.origin} responded ${s.status}`),process.exitCode=1;return;case"not-markdown":console.error(`${n}.md did not return bulb markdown (got ${s.contentType??"no content-type"}) \u2014 is ${t.origin} a typebulb host?`),process.exitCode=1}}var $0,Bi,pl,qi=A(()=>{mt();je();$0="https://typebulb.com",Bi=(r,e)=>Ae.join("typebulbs","u",r,`${e}.bulb.md`),pl=r=>`${r.origin}/u/${encodeURIComponent(r.userSlug)}/${encodeURIComponent(r.slug)}.md`});import*as Er from"fs/promises";import*as qm from"path";async function Ui(r,e){let t=await Er.readFile(r.dest,"utf-8"),{mtime:n}=await Er.stat(r.dest),s={Authorization:`Bearer ${e.token}`,"Content-Type":"text/markdown; charset=utf-8"};e.force||(s["If-Unmodified-Since"]=n.toUTCString());let i=await fetch(pl(r),{method:"PUT",body:t,headers:s,signal:e.timeoutMs?AbortSignal.timeout(e.timeoutMs):void 0}),o=await i.text();if(i.status===409)return{kind:"conflict",message:Fm(o)};if(!i.ok)return{kind:"http-error",status:i.status,message:Fm(o)};let a=JSON.parse(o);return await Er.utimes(r.dest,new Date,new Date(a.updatedAt)),{kind:"pushed",created:a.created,serverStripped:a.serverStripped,updatedAt:a.updatedAt}}function Fm(r){try{return JSON.parse(r).error||r}catch{return r}}async function Um(r,e){r||(console.error("Usage: typebulb push <typebulbs/u/<user>/<slug>.bulb.md>"),process.exit(1)),/^https?:\/\//i.test(r)&&(console.error("push takes a local .bulb.md file, not a URL (the path is its remote identity)"),process.exit(1));let t=ml(r,e.mode),n=process.env.TYPEBULB_TOKEN;n||(console.error("push needs TYPEBULB_TOKEN in your .env \u2014 create one on your typebulb.com settings page."),process.exit(1));let s=`${t.origin}/u/${t.userSlug}/${t.slug}`,i=qm.relative(process.cwd(),t.dest)||t.dest,o;try{o=await Ui(t,{token:n,force:e.force})}catch(a){let c=a instanceof Error?a.message:String(a);console.error(a?.code==="ENOENT"?`File not found: ${i}`:`Could not push to ${t.origin}: ${c}`),process.exitCode=1;return}switch(o.kind){case"pushed":console.log(`pushed ${i} \u2192 ${s}${o.created?" (created, unlisted)":""}`),o.serverStripped&&console.log("note: the server.ts block was stripped on the server copy (CLI-only); your local file is untouched.");return;case"conflict":console.error(`${o.message}
|
|
393
393
|
pull to see the remote: typebulb pull ${i}
|
|
394
|
-
or overwrite it: typebulb push ${i} --force`),process.exitCode=1;return;case"http-error":o.status===401?console.error("The server rejected TYPEBULB_TOKEN (401) \u2014 it may be revoked; mint a new one on the settings page."):console.error(`Push failed: ${t.origin} responded ${o.status}${o.message?` \u2014 ${o.message}`:""}`),process.exitCode=1}}var hl=A(()=>{qi()});var Ar=A(()=>{Ne();
|
|
394
|
+
or overwrite it: typebulb push ${i} --force`),process.exitCode=1;return;case"http-error":o.status===401?console.error("The server rejected TYPEBULB_TOKEN (401) \u2014 it may be revoked; mint a new one on the settings page."):console.error(`Push failed: ${t.origin} responded ${o.status}${o.message?` \u2014 ${o.message}`:""}`),process.exitCode=1}}var hl=A(()=>{qi()});var Ar=A(()=>{Ne();Cm();_m();ll();Rm();Im();Cn();Dt();Dt();vi();Mi();qi();hl();mt()});import{copyFileSync as M0,existsSync as Jm,mkdirSync as Km,rmSync as D0,writeFileSync as B0}from"fs";import{homedir as j0}from"os";import*as Le from"path";import{fileURLToPath as F0}from"url";function W0(){return H0.replace('"__TB_DESCRIPTION_PATH__"',JSON.stringify(xr())).replace('"__TB_README_PATH__"',JSON.stringify(qt()))}function Hm(){try{if(!Jm(Ji()))return}catch{return}try{let r=q0();Km(Le.dirname(r),{recursive:!0}),B0(r,W0()),D0(U0(),{force:!0})}catch{}try{let r=J0();if(!Jm(r))return;let e=K0();Km(Le.dirname(e),{recursive:!0}),M0(r,e)}catch{}}var Ji,q0,U0,J0,K0,H0,Wm=A(()=>{Ar();Ji=()=>Le.join(j0(),".pi","agent"),q0=()=>Le.join(Ji(),"extensions","typebulb.ts"),U0=()=>Le.join(Ji(),"extensions","typebulb-wait.ts"),J0=()=>Le.join(Le.dirname(F0(import.meta.url)),"agents","pi","matchu-patchu.ts"),K0=()=>Le.join(Ji(),"extensions","matchu-patchu.ts"),H0=String.raw`// Generated by typebulb — do not edit; overwritten on each run.
|
|
395
395
|
import { spawn } from "node:child_process";
|
|
396
396
|
import { existsSync } from "node:fs";
|
|
397
397
|
|
|
@@ -540,31 +540,31 @@ export default function (pi) {
|
|
|
540
540
|
try { pi.on("session_shutdown", () => { for (const c of pending) { try { c.kill(); } catch (e) {} } pending.clear(); }); } catch (e) {}
|
|
541
541
|
} catch (e) { logErr("load", e && e.message); }
|
|
542
542
|
}
|
|
543
|
-
`});function U(r){return r?.message??String(r)}var K,ht=A(()=>{K=process.cwd()});import{spawn as
|
|
544
|
-
`))>=0;){let o=n.slice(0,i);n=n.slice(i+1),o.endsWith("\r")&&(o=o.slice(0,-1)),o&&e(o)}})}var
|
|
545
|
-
`)}catch{}await Promise.race([this.#v,Vm
|
|
546
|
-
`)}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"?
|
|
543
|
+
`});function U(r){return r?.message??String(r)}var K,ht=A(()=>{K=process.cwd()});import{spawn as Ym}from"child_process";import{StringDecoder as Y0}from"string_decoder";function tE(r,e){let t=new Y0("utf8"),n="";r.on("data",s=>{n+=typeof s=="string"?s:t.write(s);let i;for(;(i=n.indexOf(`
|
|
544
|
+
`))>=0;){let o=n.slice(0,i);n=n.slice(i+1),o.endsWith("\r")&&(o=o.slice(0,-1)),o&&e(o)}})}var V0,G0,Vm,z0,Q0,X0,Z0,eE,Ki,Hi,Gm,zm=A(()=>{ht();V0=3e4,G0=5e3,Vm=2e3,z0=2e3,Q0=12e4,X0=8e3,Z0=15e3,eE=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"]),Ki=new Set;process.on("exit",()=>{for(let r of Ki)try{r.kill()}catch{}});Hi=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)=>Ym(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: ${U(o)}`,this.#b();return}this.#e=i,this.#f=t,Ki.add(i),i.stdout&&tE(i.stdout,o=>this.#T(o)),i.stderr&&i.stderr.on("data",o=>{this.#y=(this.#y+o.toString()).slice(-z0)}),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"),Ki.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(!eE.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:U(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:U(o)}}return i.success&&!n&&(this.#c=Date.now()+G0),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"})+`
|
|
545
|
+
`)}catch{}await Promise.race([this.#v,Gm(Vm)])}try{e.stdin?.end()}catch{}if(await Promise.race([this.#v,Gm(Vm)]),e.exitCode===null&&!e.killed)if(process.platform==="win32"&&e.pid)try{Ym("taskkill",["/pid",String(e.pid),"/T","/F"],{stdio:"ignore"})}catch{}else try{e.kill("SIGKILL")}catch{}Ki.delete(e),this.#r=[],this.#E("pi was shut down")}}#k(e){try{this.#e?.stdin?.write(JSON.stringify(e)+`
|
|
546
|
+
`)}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"?X0:Z0)})}#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)"))},V0);o.unref?.(),this.#s.set(n,{resolve:s,timer:o});try{t.stdin.write(JSON.stringify({id:n,...e})+`
|
|
547
547
|
`)}catch(a){clearTimeout(o),this.#s.delete(n),i(new Error(U(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(`
|
|
548
|
-
`)};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??
|
|
549
|
-
`),c=i.filter(
|
|
550
|
-
`))if(p.includes('"session_info"'))try{let y=JSON.parse(p);y?.type==="session_info"&&typeof y.name=="string"&&y.name&&(
|
|
551
|
-
`))if(!(l||!u.includes('"type"')))try{let
|
|
552
|
-
`):""}}});var Wi,
|
|
553
|
-
`)){let a=/^(\d+)\t(\d+)\t(.+)$/.exec(o);a&&i.set(a[3],{add:+a[1],del:+a[2]})}for(let o of t){let a=i.get(o.path);a&&(o.add=a.add,o.del=a.del)}}catch{}return t.sort((s,i)=>s.path.localeCompare(i.path)),{repo:!0,root:r,files:t}}catch(e){return{repo:!1,root:"",files:[],error:U(e)}}}async function
|
|
554
|
-
|
|
555
|
-
${r.slice(0,
|
|
556
|
-
`))>=0;){let q=g.partial.slice(0,M);if(g.partial=g.partial.slice(M+1),!q.trim())continue;let le=r.parseEntry(q);if(!le)continue;let Q=r.idOf(le);Q&&(g.entries.set(Q,le),!r.isSidechain(le)&&r.isLeafType(le)&&(_=Q))}if(!_)return;let B=[],$=g.entries.get(_),J=!1;for(;$;){if(B.push($),r.idOf($)===g.chainLastId){J=!0;break}let q=r.parentOf($);$=q?g.entries.get(q):void 0}if(J)for(let q=B.length-2;q>=0;q--)L(B[q]);else{g.chainLastId!==void 0&&(g.buffer.push({type:"cleared"}),g.buffer.push({type:"session",sessionId:g.sessionId}),g.latest={in:0,out:0,cached:0,cacheCreate:0});let q=new Set(B.map(Q=>r.idOf(Q))),le=h(g.entries);for(let Q=B.length-1;Q>=0;Q--)L(B[Q]),S(r.idOf(B[Q]),le,q)}g.chainLastId=_}function h(g){let v=new Map;for(let w of g.values()){let _=r.parentOf(w);if(!_)continue;let M=v.get(_);M?M.push(w):v.set(_,[w])}return v}function S(g,v,w){if(!g)return;let _=v.get(g);if(!_)return;let M=_.filter(q=>!r.isSidechain(q));if(M.length<2)return;let B=M.filter(q=>!w.has(r.idOf(q)));if(!B.length)return;let $=[],J=0;for(let q of B){let le=I(q,v);$.push(...le.events),J+=le.count}J>0&&e.buffer.push({type:"fork",atId:g,count:J,events:$})}function I(g,v){let w=[],_=[g];for(;_.length;){let $=_.pop();if(r.isSidechain($))continue;w.push($);let J=v.get(r.idOf($)??"");if(J)for(let q of J)_.push(q)}w.sort(($,J)=>(Date.parse(r.timestampOf($)??"")||0)-(Date.parse(r.timestampOf(J)??"")||0));let M=[];for(let $ of w)r.isRecoveryNoise($)||M.push(...r.apply($,e.sessionStartMs).events);return{count:M.reduce(($,J)=>$+(J.type==="user"||J.type==="assistant"?1:0),0),events:M}}function L(g){try{let{events:v,usage:w,model:_,cost:M}=r.apply(g,e.sessionStartMs);for(let B of v)e.buffer.push(B);v.some(B=>B.type==="assistant")&&s()?.d.clearCompletedDraft(),v.some(B=>B.type==="user")&&s()?.d.clearEcho(),_&&(e.latestModel=_),w&&(e.latest=w),(w||M)&&e.buffer.push({type:"usage",...e.latest,cost:M})}catch(v){console.error("[mirror] skipped malformed entry:",U(v))}}async function N(){return{cwd:e.cwd,pid:process.pid,composer:!!r.createDriver,elsewhere:await X()}}async function X(){if(r.listSessionFiles(e.cwd).length)return;let g=await Or();if(!g)return;let v=
|
|
557
|
-
`).filter(Boolean).map(async w=>{try{return{f:w,m:(await
|
|
558
|
-
`)){if(!B.trim())continue;let $=r.parseEntry(B);if(!$)continue;let J=r.searchText($);J&&_.push({text:J,lower:J.toLowerCase()})}return eu.set(g,{mtime:v,turns:_}),_}async function
|
|
559
|
-
`)){if(!$.trim())continue;let J=r.parseEntry($);if(J)for(let q of r.apply(J,e.sessionStartMs).events)q.type==="assistant"&&q.text.trim()&&(M=q.text.trim())}let B=M.length>tu?M.slice(0,tu).trimEnd()+"\u2026":M;return ru.set(g,{mtime:v,text:B}),B}async function
|
|
560
|
-
`)){let l=c.replace(/\s+/g," ").trim();l&&i.push({text:l,lower:l.toLowerCase()})}let{hitCount:o,snippet:a}=Gi(i,e);o&&t.push({path:n.path,hitCount:o,snippet:a})}return t}async function
|
|
561
|
-
${r}`;return gt?.key===e&&Date.now()-gt.fetchedAt<=
|
|
562
|
-
`)}function
|
|
548
|
+
`)};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??Q0),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()}},Gm=r=>new Promise(e=>{setTimeout(e,r).unref?.()})});import{existsSync as Qm,readFileSync as rE,realpathSync as nE}from"fs";import{join as Ut,dirname as th,resolve as sE}from"path";import{homedir as Xm}from"os";function oE(r,e){let t=Ut(r,".pi");if(iE.some(s=>Qm(Ut(t,s))))return!0;let n=Ut(e,".agents","skills");for(let s=r;;){let i=Ut(s,".agents","skills");if(i!==n&&Qm(i))return!0;let o=th(s);if(o===s)return!1;s=o}}function aE(r,e){for(let t=e;;){if(r[t]===!0||r[t]===!1)return!0;let n=th(t);if(n===t)return!1;t=n}}function rh(r,e){try{let t=e?.agentDir??Ut(Xm(),".pi","agent"),n=Zm(e?.home??process.env.HOME??Xm()),s=Zm(sE(r));if(!oE(s,n))return null;let i=eh(Ut(t,"settings.json")).defaultProjectTrust;return i==="always"||i==="never"||aE(eh(Ut(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 iE,Zm,eh,nh=A(()=>{iE=["settings.json","extensions","skills","prompts","themes","SYSTEM.md","APPEND_SYSTEM.md"],Zm=r=>{try{return nE(r)}catch{return r}},eh=r=>{try{return JSON.parse(rE(r,"utf8"))}catch{return{}}}});import{statSync as cE,openSync as lE,readSync as uE,closeSync as fE,existsSync as dE}from"fs";import{join as gl}from"path";import{homedir as ih}from"os";function mE(r){return`--${r.replace(/^[/\\]/,"").replace(/[/\\:]/g,"-")}--`}function sh(r){return r.type==="message"?hE(r.message?.role):r.type==="custom_message"?r.display!==!1:!1}var pE,hE,Tr,yl=A(()=>{Ai();Yc();Vc();Wm();zm();nh();pE=gl(ih(),".pi","agent","sessions");hE=r=>r==="user"||r==="assistant"||r==="toolResult"||r==="bashExecution";Tr=class extends wr{displayName="Pi Mirror";detectsSelf(){return process.env.PI_CODING_AGENT==="true"}detectsInstalled(){return dE(gl(ih(),".pi","agent"))}ensureHarnessSupport(){Hm()}createDriver(e,t){let n=new Hi(e,t),s=rh(e);return s&&n.notice(s,"warning"),n}sessionsDir(e){return gl(pE,mE(e))}listSessionFiles(e){return Ti(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 sh(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:He(i)}),{events:n}}if(s.role==="bashExecution")return s.command&&!s.excludeFromContext&&n.push({type:"user",text:`$ ${s.command}`}),{events:n};if(s.role==="assistant"){let i=Array.isArray(s.content)?s.content:[],o=i.filter(d=>d.type==="text").map(d=>d.text??"").join(""),a=i.filter(d=>d.type==="thinking").map(d=>d.thinking??"").join(`
|
|
549
|
+
`),c=i.filter(d=>d.type==="toolCall").map(d=>({id:d.id??"",name:d.name??"",input:d.arguments??{}}));if(o||a||c.length){let d=Date.parse(e.timestamp??""),p=!isNaN(d)&&d>=t;n.push({type:"assistant",text:o,thinking:a,tools:c,live:p})}let l=s.usage,f=l?(l.input??0)+(l.output??0)+(l.cacheRead??0)+(l.cacheWrite??0):0,u=l&&f>0&&s.stopReason!=="aborted"&&s.stopReason!=="error"?{in:l.input??0,out:l.output??0,cached:l.cacheRead??0,cacheCreate:l.cacheWrite??0}:void 0;return{events:n,usage:u,model:s.model,cost:l?.cost?.total}}return{events:n}}chainWorking(e){let t;for(let a of e)sh(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=lE(e,"r")}catch{return""}try{let s=65536;try{s=cE(e).size}catch{}let i=(u,d)=>{let p=Buffer.alloc(d),y=uE(t,p,0,d,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 d="";for(let p of u.split(`
|
|
550
|
+
`))if(p.includes('"session_info"'))try{let y=JSON.parse(p);y?.type==="session_info"&&typeof y.name=="string"&&y.name&&(d=y.name)}catch{}return d},l="";for(let u of o.split(`
|
|
551
|
+
`))if(!(l||!u.includes('"type"')))try{let d=JSON.parse(u);d?.type==="message"&&d.message?.role==="user"&&(l=this.contentText(d.message.content).replace(/\s+/g," ").trim())}catch{}let f=c(a)||c(o)||l;return f?f.slice(0,200):""}finally{fE(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"?_e(e):Array.isArray(e)?e.map(t=>typeof t?.text=="string"?_e(t.text):t?.type==="image"&&t.data?Ei(t.data,t.mimeType):"").filter(Boolean).join(`
|
|
552
|
+
`):""}}});var Wi,oh=A(()=>{Wi=class{#e=new Map;accept(e,t){return this.#e.get(e)===t?!1:(this.#e.set(e,t),!0)}}});import{execFile as gE}from"child_process";import{promisify as yE}from"util";import{readFile as bE}from"fs/promises";import{resolve as ah,sep as wE}from"path";async function Pr(r,e){let{stdout:t}=await vE("git",r,{cwd:e,maxBuffer:67108864});return t}async function Or(){if(Yi)return Yi;try{Yi=(await Pr(["rev-parse","--show-toplevel"],K)).trim()}catch{}return Yi}function SE(r,e){let t=e===" "?r:e;return t==="?"?"U":t}async function lh(){let r=await Or();if(!r)return{repo:!1,root:"",files:[]};try{let e=await Pr(["status","--porcelain","-z"],r),t=[],n=e.split("\0");for(let s=0;s<n.length;s++){let i=n[s];i.length<4||((i[0]==="R"||i[0]==="C")&&s++,t.push({path:i.slice(3),status:SE(i[0],i[1])}))}try{let s=await Pr(["diff","--numstat","HEAD"],r),i=new Map;for(let o of s.split(`
|
|
553
|
+
`)){let a=/^(\d+)\t(\d+)\t(.+)$/.exec(o);a&&i.set(a[3],{add:+a[1],del:+a[2]})}for(let o of t){let a=i.get(o.path);a&&(o.add=a.add,o.del=a.del)}}catch{}return t.sort((s,i)=>s.path.localeCompare(i.path)),{repo:!0,root:r,files:t}}catch(e){return{repo:!1,root:"",files:[],error:U(e)}}}async function uh(r){let e=await Or();if(!e)return{ok:!1,error:"not a git repository"};try{if((await Pr(["status","--porcelain","-z","--",r],e)).startsWith("??")){let s=ah(e,r);if(!s.startsWith(ah(e)+wE))return{ok:!1,error:"outside repository"};let i=await bE(s);return i.includes(0)?bl("Binary file (not shown)",!1):bl(i.toString("utf8"),!0)}let n;try{n=await Pr(["diff","--no-color","--unified=999999","HEAD","--",r],e)}catch{n=await Pr(["diff","--no-color","--unified=999999","--",r],e)}return bl(n,!1)}catch(t){return{ok:!1,error:U(t)}}}var vE,ch,Yi,bl,Vi=A(()=>{ht();vE=yE(gE),ch=2e6;bl=(r,e)=>({ok:!0,text:r.slice(0,ch),untracked:e,truncated:r.length>ch})});function Gi(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 wl=A(()=>{});var zi,Qi,fh=A(()=>{zi=".typebulb/paste",Qi={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 kE,mkdirSync as xE,writeFileSync as EE,readFileSync as AE}from"fs";import{join as Xi}from"path";function dh(){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 CE(r){return r.trim().toLowerCase().replace(/\.[a-z0-9]{1,4}$/,"").replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60)}async function _E(r){let e=AbortSignal.timeout(TE);for(let[t,n]of OE){let s=Je(t,n);if(typeof s!="string"){try{let i=await ut(s,{messages:[{role:"user",content:`Reply with ONLY a short kebab-case filename (2-5 words, lowercase, no extension) describing this text:
|
|
554
|
+
|
|
555
|
+
${r.slice(0,PE)}`}],effort:0,webSearch:!1,signal:e});if(!i.ok)continue;let o=CE(await Lt(i,s.protocol));if(o)return o}catch{}if(e.aborted)return}}}async function ph(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,zi);try{xE(t,{recursive:!0})}catch(a){return{ok:!1,error:U(a)}}let n,s,i;if(e.kind==="image"){if(n=`img-${dh()}`,s=Object.keys(Qi).find(a=>Qi[a]===e.mime)??"png",i=Buffer.from(e.data,"base64"),!i.length)return{ok:!1,error:"empty image data"}}else n=await _E(e.data)??`paste-${dh()}`,s="md",i=e.data;let o=`${n}.${s}`;for(let a=2;kE(Xi(t,o));a++)o=`${n}-${a}.${s}`;try{EE(Xi(t,o),i)}catch(a){return{ok:!1,error:U(a)}}return{ok:!0,path:`${zi}/${o}`}}function mh(r,e){if(!/^[\w-]+(\.[\w-]+)*$/.test(e))return{ok:!1,error:"bad name"};let t=e.slice(e.lastIndexOf(".")+1).toLowerCase(),n=Qi[t];if(!n)return{ok:!1,error:"not an image"};try{return{ok:!0,mime:n,base64:AE(Xi(r,zi,e)).toString("base64")}}catch{return{ok:!1,error:"not found"}}}var TE,PE,OE,hh=A(()=>{hr();Ar();ht();fh();TE=4e3,PE=4e3,OE=[["openrouter","google/gemini-3.1-flash-lite-preview"],["gemini","gemini-3.1-flash-lite"]]});import{existsSync as gh,openSync as RE,readSync as NE,closeSync as IE,statSync as Cr,readdirSync as yh,watchFile as $E,unwatchFile as bh,mkdirSync as LE,writeFileSync as ME,readFileSync as Zi,unlinkSync as DE,rmSync as BE}from"fs";import{stat as jE}from"fs/promises";import{dirname as FE,join as Jt,resolve as wh}from"path";import{execFile as qE}from"child_process";function HE(r){if(!Number.isInteger(r))return!0;try{return process.kill(r,0),!0}catch(e){return e.code==="EPERM"}}function eo(r){let e={cwd:K,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 g of t)if(g.file===e.file)return g;return}return n}function i(g){let v={d:r.createDriver(e.cwd,g),file:g};return t.add(v),e.file||(n=v),v}async function o(g){t.delete(g),n===g&&(n=void 0);try{await g.d.dispose()}catch(v){console.error("[composer] dispose:",U(v))}}function a(){let g=s();for(let v of[...t])v!==g&&(v.d.streaming||v.d.queue||v.d.error||o(v))}function c(){for(let g of t)g.d.sessionFile&&g.file!==g.d.sessionFile&&(g.file=g.d.sessionFile);if(n&&!e.file&&n.file){let g=r.listSessionFiles(e.cwd).find(v=>v.file===n.file);g&&C(g)}}let l=g=>Jt(g,JE),f=(g,v)=>Jt(l(g),`${v}.lock`);function u(g,v){try{let w=f(g,v);if(Date.now()-Cr(w).mtimeMs>=vh)return!1;try{let _=parseInt(Zi(w,"utf8").trim(),10);if(_===process.pid||!HE(_))return!1}catch{}return!0}catch{return!1}}function d(g,v){if(v)try{LE(l(g),{recursive:!0}),ME(f(g,v),String(process.pid))}catch(w){console.error("[lock] claim failed:",U(w))}}function p(g){try{BE(Jt(g,".claude-bulb"),{recursive:!0,force:!0})}catch{}}function y(g){let v=l(g);if(!gh(v))return;let w;try{w=yh(v)}catch{return}let _=Date.now();for(let M of w){if(!M.endsWith(".lock"))continue;let B=Jt(v,M);try{let $=Cr(B);_-$.mtimeMs>KE&&DE(B)}catch{}}}function m(g){try{return Cr(g),!1}catch(v){return v.code==="ENOENT"}}function b(){let g=e;if(g.file&&!m(g.file)){d(g.cwd,g.sessionId);return}let v=k(g);v&&C(v)}function k(g){if(!g.everAttached)return x(g.cwd)??T(g.cwd,()=>!0)}function x(g){let v=l(g);if(!gh(v))return;let w;try{w=yh(v)}catch{return}let _;for(let B of w)if(B.endsWith(".lock"))try{let $=Cr(Jt(v,B));if(Date.now()-$.mtimeMs>=vh||parseInt(Zi(Jt(v,B),"utf8").trim(),10)!==process.pid)continue;(!_||$.mtimeMs>_.mtime)&&(_={sessionId:B.slice(0,-5),mtime:$.mtimeMs})}catch{}if(!_)return;let M=r.listSessionFiles(g).find(B=>B.sessionId===_.sessionId);if(!(!M||m(M.file)))return M}function T(g,v){return r.listSessionFiles(g).sort((w,_)=>_.mtime-w.mtime).find(w=>!u(g,w.sessionId)&&v(w))}function P(g,v){let w=e;if(w.file)try{bh(w.file)}catch{}w.file=g,w.sessionId=v,w.partial="",w.offset=0,w.latest={in:0,out:0,cached:0,cacheCreate:0},w.latestModel=null,w.entries=new Map,w.chainLastId=void 0,w.buffer.push({type:"cleared"}),w.buffer.push({type:"session",sessionId:v})}function C(g){let v=e;n=void 0,P(g.file,g.sessionId),v.everAttached=!0,d(v.cwd,g.sessionId),R();try{bh(g.file)}catch{}$E(g.file,{interval:200},()=>R())}function O(){P(void 0,"")}function R(){let g=e;if(!g.file)return;let v;try{v=Cr(g.file).size}catch{return}if(v<=g.offset)return;let w;try{w=RE(g.file,"r")}catch{return}try{let q=v-g.offset,le=Buffer.alloc(q),Q=0;for(;Q<q;){let nu=NE(w,le,Q,q-Q,g.offset+Q);if(!nu)break;Q+=nu}g.offset+=Q,g.partial+=le.subarray(0,Q).toString("utf8")}finally{IE(w)}let _,M;for(;(M=g.partial.indexOf(`
|
|
556
|
+
`))>=0;){let q=g.partial.slice(0,M);if(g.partial=g.partial.slice(M+1),!q.trim())continue;let le=r.parseEntry(q);if(!le)continue;let Q=r.idOf(le);Q&&(g.entries.set(Q,le),!r.isSidechain(le)&&r.isLeafType(le)&&(_=Q))}if(!_)return;let B=[],$=g.entries.get(_),J=!1;for(;$;){if(B.push($),r.idOf($)===g.chainLastId){J=!0;break}let q=r.parentOf($);$=q?g.entries.get(q):void 0}if(J)for(let q=B.length-2;q>=0;q--)L(B[q]);else{g.chainLastId!==void 0&&(g.buffer.push({type:"cleared"}),g.buffer.push({type:"session",sessionId:g.sessionId}),g.latest={in:0,out:0,cached:0,cacheCreate:0});let q=new Set(B.map(Q=>r.idOf(Q))),le=h(g.entries);for(let Q=B.length-1;Q>=0;Q--)L(B[Q]),S(r.idOf(B[Q]),le,q)}g.chainLastId=_}function h(g){let v=new Map;for(let w of g.values()){let _=r.parentOf(w);if(!_)continue;let M=v.get(_);M?M.push(w):v.set(_,[w])}return v}function S(g,v,w){if(!g)return;let _=v.get(g);if(!_)return;let M=_.filter(q=>!r.isSidechain(q));if(M.length<2)return;let B=M.filter(q=>!w.has(r.idOf(q)));if(!B.length)return;let $=[],J=0;for(let q of B){let le=I(q,v);$.push(...le.events),J+=le.count}J>0&&e.buffer.push({type:"fork",atId:g,count:J,events:$})}function I(g,v){let w=[],_=[g];for(;_.length;){let $=_.pop();if(r.isSidechain($))continue;w.push($);let J=v.get(r.idOf($)??"");if(J)for(let q of J)_.push(q)}w.sort(($,J)=>(Date.parse(r.timestampOf($)??"")||0)-(Date.parse(r.timestampOf(J)??"")||0));let M=[];for(let $ of w)r.isRecoveryNoise($)||M.push(...r.apply($,e.sessionStartMs).events);return{count:M.reduce(($,J)=>$+(J.type==="user"||J.type==="assistant"?1:0),0),events:M}}function L(g){try{let{events:v,usage:w,model:_,cost:M}=r.apply(g,e.sessionStartMs);for(let B of v)e.buffer.push(B);v.some(B=>B.type==="assistant")&&s()?.d.clearCompletedDraft(),v.some(B=>B.type==="user")&&s()?.d.clearEcho(),_&&(e.latestModel=_),w&&(e.latest=w),(w||M)&&e.buffer.push({type:"usage",...e.latest,cost:M})}catch(v){console.error("[mirror] skipped malformed entry:",U(v))}}async function N(){return{cwd:e.cwd,pid:process.pid,composer:!!r.createDriver,elsewhere:await X()}}async function X(){if(r.listSessionFiles(e.cwd).length)return;let g=await Or();if(!g)return;let v=wh(g).toLowerCase();for(let w=wh(e.cwd);w.toLowerCase()!==v;){let _=FE(w);if(_===w)return;w=_;let M=r.listSessionFiles(w).length;if(M)return{dir:w,count:M}}}X().then(g=>{g&&console.log(`No sessions for ${e.cwd} \u2014 ${g.count} exist for ${g.dir}. Launched from a subfolder? Relaunch from the project root.`)}).catch(()=>{});let fe=new Wi;async function vt(g,v){fe.accept(g,v)&&console.log(v)}function te(){let g=r.sessionAlive(e.sessionId,e.cwd);if(g!==void 0)return g;if(!e.file)return!1;try{return Date.now()-Cr(e.file).mtimeMs<1e4}catch{return!1}}function z(){return r.chainWorking([...e.entries.values()])&&te()}function St(){!r.createDriver||s()||e.latestModel||z()||i(e.file)}async function Ve(g){let v=e;b(),c(),St(),a();let w=s();for(let $ of t)$!==w&&$.d.dialog;let _=new Set([...t].filter($=>$.d.streaming&&$.file).map($=>$.file)),M=_.size?r.listSessionFiles(v.cwd).filter($=>_.has($.file)).map($=>$.sessionId):[],B=r.createDriver?{streaming:!!w?.d.streaming,draft:w?.d.draft??null,echo:w?.d.echo??null,status:w?.d.status??null,dialog:w?.d.dialog??null,queue:w?.d.queue??null,stats:w?.d.stats??null,model:w?.d.model??null,error:w?.d.error}:void 0;return{events:v.buffer.slice(g),cursor:v.buffer.length,working:!!w?.d.streaming||z(),latestModel:v.latestModel,composer:B,busy:M}}async function Zl(){b(),c();let g=s();if(g?.d.error&&!g.d.streaming&&(await o(g),g=void 0),!g){if(z())return{ok:!1,error:"the agent is mid-turn in a terminal \u2014 watch only"};g=i(e.file)}return{ok:!0,d:g.d}}async function gy(g,v){if(!r.createDriver)return{ok:!1,error:"not supported"};let w=String(g??"").trim();if(!w)return{ok:!1,error:"empty message"};let _=await Zl();return _.ok?_.d.send(w,v):_}async function yy(g,v){let w=s();return w?w.d.respondUi(String(g??""),v??{}):{ok:!1,error:"no dialog pending"}}async function by(g,v){if(!r.createDriver)return{ok:!1,error:"not supported"};if(!g||typeof g.type!="string")return{ok:!1,error:"bad command"};if(v?.spawn){let _=await Zl();return _.ok?_.d.rpc(g):_}let w=s();return!w||w.d.error?{ok:!1,error:"not running"}:w.d.rpc(g)}async function wy(){let g=s();if(g)try{await g.d.stop()}catch(v){console.error("[composer] stop:",U(v))}return{ok:!0}}async function vy(){return r.createDriver?(c(),!e.file&&n&&!n.d.streaming&&!n.d.error?{ok:!0}:(n?.d.error&&await o(n),n=void 0,e.file&&O(),i(void 0),a(),{ok:!0})):{ok:!1,error:"not supported"}}async function Sy(){if(!r.createDriver)return[];let g=await new Promise(w=>{qE("git",["ls-files","--cached","--others","--exclude-standard"],{cwd:e.cwd,maxBuffer:64*1024*1024},(_,M)=>w(_?"":M))});return(await Promise.all(g.split(`
|
|
557
|
+
`).filter(Boolean).map(async w=>{try{return{f:w,m:(await jE(Jt(e.cwd,w))).mtimeMs}}catch{return{f:w,m:0}}}))).sort((w,_)=>_.m-w.m).map(w=>w.f)}function ky(){for(let g of[...t])o(g)}async function xy(g){return r.createDriver?ph(e.cwd,g):{ok:!1,error:"not supported"}}async function Ey(g){return mh(e.cwd,String(g??""))}async function Ay(){return r.listSessionFiles(e.cwd).sort((g,v)=>v.mtime-g.mtime).map(({sessionId:g,file:v,mtime:w})=>({sessionId:g,mtime:w,preview:r.readPreview(v)}))}let eu=new Map;function Ty(g,v){let w=eu.get(g);if(w&&w.mtime===v)return w.turns;let _=[],M="";try{M=Zi(g,"utf8")}catch{return[]}for(let B of M.split(`
|
|
558
|
+
`)){if(!B.trim())continue;let $=r.parseEntry(B);if(!$)continue;let J=r.searchText($);J&&_.push({text:J,lower:J.toLowerCase()})}return eu.set(g,{mtime:v,turns:_}),_}async function Py(g){let v=g.toLowerCase(),w=[];for(let{sessionId:_,file:M,mtime:B}of r.listSessionFiles(e.cwd).sort(($,J)=>J.mtime-$.mtime)){let{hitCount:$,snippet:J}=Gi(Ty(M,B),v);if($&&(w.push({sessionId:_,mtime:B,preview:r.readPreview(M),hitCount:$,snippet:J}),w.length>=WE))break}return w}let tu=800,ru=new Map;function Oy(g,v){let w=ru.get(g);if(w&&w.mtime===v)return w.text;let _="";try{_=Zi(g,"utf8")}catch{return""}let M="";for(let $ of _.split(`
|
|
559
|
+
`)){if(!$.trim())continue;let J=r.parseEntry($);if(J)for(let q of r.apply(J,e.sessionStartMs).events)q.type==="assistant"&&q.text.trim()&&(M=q.text.trim())}let B=M.length>tu?M.slice(0,tu).trimEnd()+"\u2026":M;return ru.set(g,{mtime:v,text:B}),B}async function Cy(g){let v=r.listSessionFiles(e.cwd).find(w=>w.sessionId===g);return{text:v?Oy(v.file,v.mtime):""}}async function _y(g){let v=e,w=r.listSessionFiles(v.cwd).find(_=>_.sessionId===g);return w?w.file===v.file?{ok:!0}:(C(w),c(),a(),{ok:!0}):{ok:!1,error:"session not found"}}return p(e.cwd),y(e.cwd),b(),{info:N,poll:Ve,logEmbedStatus:vt,listSessions:Ay,searchSessions:Py,sessionPeek:Cy,attach:_y,composerSend:gy,composerStop:wy,composerNew:vy,composerFiles:Sy,composerUiRespond:yy,composerRpc:by,composerPaste:xy,composerPasteRead:Ey,shutdownComposer:ky}}var UE,JE,vh,KE,WE,vl=A(()=>{ht();oh();Vi();wl();hh();UE=".typebulb",JE=`${UE}/locks`,vh=5e3,KE=6e4;WE=50});import{existsSync as El,mkdirSync as YE,readFileSync as Sh,writeFileSync as VE}from"fs";import{join as Kt,isAbsolute as GE}from"path";async function kh(r,e){let t=GE(r)?r:Kt(K,r);return El(t)?(dl(t,e),{ok:!0}):{ok:!1,error:"file not found"}}async function xh(r){let e=K,t=fl(r),n=Kt(e,"typebulbs");YE(n,{recursive:!0});let s=cl(t),i=`${s}.bulb.md`;for(let l=2;El(Kt(n,i))&&Sh(Kt(n,i),"utf8")!==t;l++)i=`${s}-${l}.bulb.md`;let o=Kt(n,i);El(o)||VE(o,t);let a=Kt("typebulbs",i),c=await Ni(a,{cwd:e,open:!1});return{ok:!0,file:a,pid:c.pid,url:c.url}}async function Eh(){return Y(K)}async function Ah(r){return await jt(r),{ok:!0}}async function Th(){return $i(K).filter(r=>!r.serverOnly).map(r=>({...r,trusted:Bt(r.path)}))}async function Ph(r){let e=r.toLowerCase(),t=[];for(let n of $i(K).filter(s=>!s.serverOnly).sort((s,i)=>i.mtime-s.mtime)){let s="";try{s=Sh(n.path,"utf8")}catch{continue}let i=[];for(let c of s.split(`
|
|
560
|
+
`)){let l=c.replace(/\s+/g," ").trim();l&&i.push({text:l,lower:l.toLowerCase()})}let{hitCount:o,snippet:a}=Gi(i,e);o&&t.push({path:n.path,hitCount:o,snippet:a})}return t}async function Oh(r,e){let t=K;e!=null&&br(r,e);let n=await Ni(r,{cwd:t,open:!1,trust:e});return{ok:!0,file:n.file,pid:n.pid,url:n.url,trust:!!n.trust}}async function Ch(r){return{cap:await ul(r)}}async function _h(r,e){return br(r,e),{ok:!0}}async function Rh(r,e){return Re(r,e)}async function Lh(){return $n&&Date.now()-$n.fetchedAt<=QE?$n.samples:(Sl??=XE().finally(()=>{Sl=null}),Sl)}async function XE(){try{let r=await fetch(`${zE}/api/scripts/u/samples?stubs`,{signal:AbortSignal.timeout(Ih)});if(!r.ok)throw new Error(`HTTP ${r.status}`);let e=await r.json(),t=i=>i.order??Number.MAX_SAFE_INTEGER,n=i=>Date.parse(i.createdAt??"")||0,s=e.filter(i=>i.slug!=="welcome").sort((i,o)=>t(i)-t(o)||n(o)-n(i)).map(i=>({slug:i.slug,name:i.name,description:$o(i.config)}));return $n={samples:s,fetchedAt:Date.now()},s}catch{return $n?.samples??[]}}async function Mh(r){return Al.test(r)?jh(Nh,"samples",r,!0):{ok:!1,error:"bad slug"}}async function Dh(){let r=Tl();if(!r)return{bulbs:[]};let e=`${to()}
|
|
561
|
+
${r}`;return gt?.key===e&&Date.now()-gt.fetchedAt<=ZE?{user:gt.user,bulbs:gt.bulbs}:(kl??=eA(e,r).finally(()=>{kl=null}),kl)}async function xl(r,e,t){let n=await fetch(`${r}${e}`,{headers:t,signal:AbortSignal.timeout(Ih)});if(!n.ok)throw new Error(`HTTP ${n.status}`);if(!n.headers.get("content-type")?.includes("json"))throw new Error("not json");return n.json()}async function eA(r,e){let t={Authorization:`Bearer ${e}`};try{let n=to(),s;try{s=await xl(n,"/api/me",t)}catch{let a=new URL(n);n=`${a.protocol}//api.${a.host}`,s=await xl(n,"/api/me",t)}let o=(await xl(n,"/api/scripts/list",t)).filter(a=>a.userSlug===s.slug&&!a.isTemplate).map(a=>({slug:a.slug,name:a.name,description:$o(a.config)}));return gt={key:r,user:s.slug,bulbs:o,fetchedAt:Date.now()},{user:s.slug,bulbs:o}}catch{return gt?.key===r?{user:gt.user,bulbs:gt.bulbs}:{bulbs:[]}}}async function Bh(r,e,t=!1){return!Al.test(e)||!Al.test(r)?{ok:!1,error:"bad slug"}:jh(to(),r,e,t)}async function jh(r,e,t,n){let s=Bi(e,t);try{let i=await Fi({origin:r,userSlug:e,slug:t,dest:Kt(K,s)},{force:n,token:Tl(),timeoutMs:$h});return i.kind==="conflict"?{ok:!1,conflict:!0,error:"local file differs from the site copy"}:i.kind==="http-error"?{ok:!1,error:`HTTP ${i.status}`}:i.kind==="not-markdown"?{ok:!1,error:`not a bulb (${i.contentType??"no content-type"})`}:{ok:!0,file:s,upToDate:i.kind==="up-to-date"}}catch(i){return{ok:!1,error:i?.message??String(i)}}}async function Fh(r,e=!1){let t=Tl();if(!t)return{ok:!1,error:"no TYPEBULB_TOKEN in .env"};try{let n=ji(r,K,to()),s=await Ui(n,{token:t,force:e,timeoutMs:$h});return s.kind==="conflict"?{ok:!1,conflict:!0,error:s.message}:s.kind==="http-error"?{ok:!1,error:`HTTP ${s.status}: ${s.message}`}:{ok:!0,created:s.created,serverStripped:s.serverStripped}}catch(n){return{ok:!1,error:n?.message??String(n)}}}var zE,Nh,QE,Ih,$h,$n,Sl,Al,ZE,gt,kl,to,Tl,Pl=A(()=>{Ar();ht();wl();je();zE="https://api.typebulb.com",Nh="https://typebulb.com",QE=3600*1e3,Ih=5e3,$h=15e3,$n=null,Sl=null;Al=/^[a-z0-9][a-z0-9-]*$/,ZE=300*1e3,gt=null,kl=null,to=()=>Di("TYPEBULB_ORIGIN",K)||Nh,Tl=()=>Di("TYPEBULB_TOKEN",K)});import{readFileSync as _l,writeFileSync as Uh,mkdirSync as tA,appendFileSync as Jh,rmSync as qh}from"fs";import{join as so,dirname as rA}from"path";import{createServer as nA}from"http";function yt(r){try{return JSON.parse(_l(r,"utf8"))}catch{return null}}function no(r,e){tA(rA(r),{recursive:!0}),Uh(r,JSON.stringify(e,null,2)+`
|
|
562
|
+
`)}function Hh(r,e,t){let n=so(r,".gitignore"),s="";try{s=_l(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(`
|
|
563
563
|
`)?`
|
|
564
|
-
`:"";try{
|
|
564
|
+
`:"";try{Jh(n,a+t+`
|
|
565
565
|
`+o.join(`
|
|
566
566
|
`)+`
|
|
567
|
-
`)}catch(c){console.error("[switcher] .gitignore update failed",U(c))}}function
|
|
567
|
+
`)}catch(c){console.error("[switcher] .gitignore update failed",U(c))}}function cA(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?Dn="live":s>aA&&(Dn="uncached")}function Yh(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 lA(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 Vh(r){let e;try{e=JSON.parse(r)}catch{return r}Mn=typeof e?.model=="string"?e.model:null,Me&&(e.model=Me),Wt&&(e.provider=Wh(Wt));let t=/haiku/i.test(Mn||"");return Bn!=null&&!t&&(e.reasoning={effort:Ol[Bn]}),delete e.thinking,e.output_config&&delete e.output_config.effort,lA(e),JSON.stringify(e)}function uA(){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}
|
|
568
568
|
data: ${JSON.stringify(a)}
|
|
569
569
|
|
|
570
570
|
`}case"content_block_delta":case"content_block_stop":{let c=t.get(a.index);return c==null?null:(a.index=c,`event: ${a.type}
|
|
@@ -572,11 +572,11 @@ data: ${JSON.stringify(a)}
|
|
|
572
572
|
|
|
573
573
|
`)}default:return i}};return i=>{r+=i;let o="",a;for(;(a=r.indexOf(`
|
|
574
574
|
|
|
575
|
-
`))!==-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
|
|
575
|
+
`))!==-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 fA(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 Ln(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 dA(r,e,t){if(!Me){Ln(e,400,"invalid_request_error",oA);return}let n=process.env.OPENROUTER_API_KEY;if(!n){Ln(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(Rl,{method:"POST",headers:Yh(r,n),body:Vh(t),signal:s.signal})}catch(u){Ln(e,502,"api_error",`proxy upstream failed: ${U(u)}`);return}let o=i.headers.get("content-type")||"application/json";if(e.writeHead(i.status,{"content-type":o}),!i.body){e.end();return}let a=o.includes("event-stream"),c=i.body.getReader(),l=new TextDecoder,f=a?uA():null;try{for(;;){let{done:u,value:d}=await c.read();if(u)break;if(d)if(f){let p=l.decode(d,{stream:!0});cA(p);let y=f(p);y&&e.write(y)}else e.write(Buffer.from(d))}}catch{}finally{e.writableEnded||e.end()}}async function pA(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(!Me||!n)return s();try{let i=await fetch(`${Rl}/count_tokens`,{method:"POST",headers:Yh(r,n),body:Vh(t)});if(!i.ok)return s();let o=await i.text();e.writeHead(200,{"content-type":"application/json"}),e.end(o)}catch{s()}}function mA(r,e){let t=r.url||"/";if(r.method==="HEAD"){e.writeHead(200),e.end();return}if(r.method!=="POST"){Ln(e,404,"not_found_error",t);return}fA(r).then(n=>{if(t.includes("count_tokens"))return pA(r,e,n);if(t.includes("/v1/messages"))return dA(r,e,n);Ln(e,404,"not_found_error",t)})}function hA(){return _r&&Ht?Promise.resolve(Ht):new Promise((r,e)=>{let t=nA(mA);t.on("error",e),t.listen(0,"127.0.0.1",()=>{_r=t,Ht=t.address().port,console.log(`[switcher] wire proxy listening on ${ro(Ht)}`),r(Ht)})})}function gA(){try{_r?.close()}catch{}_r=null,Ht=null}function yA(r,e){let t=io(r),n=yt(t),s=n||{};if((!s.env||typeof s.env!="object")&&(s.env={}),s.env.ANTHROPIC_BASE_URL===ro(e)&&s.env.ANTHROPIC_AUTH_TOKEN)return;let i=oo(r);if(!yt(i)){let a={};for(let c of Kh)a[c]=c in s.env?s.env[c]:null;no(i,{managedBy:"agent-switcher",fileExisted:n!==null,snapshot:a,active:null})}s.env.ANTHROPIC_BASE_URL=ro(e),s.env.ANTHROPIC_AUTH_TOKEN=iA,no(t,s),Hh(r,[".claude/settings.local.json",".claude/.cc-switcher.json"],"# agent switcher (local Claude Code model override)")}function bA(r,e,t){let n=oo(r),s=yt(n)||{managedBy:"agent-switcher",fileExisted:!1,snapshot:{}};s.active={model:e,provider:t},no(n,s)}function Gh(r){let e=io(r),t=oo(r),n=yt(t),s=yt(e);if(s?.env){let i=n?.snapshot||{};for(let o of Kh){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{qh(e,{force:!0})}catch{}else no(e,s)}try{qh(t,{force:!0})}catch{}}async function wA(){let r=!!process.env.OPENROUTER_API_KEY,e=[];try{e=(await Ue()).filter(n=>n.provider==="openrouter"&&!Nl(n.name)).map(n=>({id:n.name,label:n.friendlyName||n.name}))}catch(n){console.error("[switcher] model list failed",U(n))}let t=e.length?void 0:Fc()??void 0;return{hasKey:r,models:e,error:t}}async function vA(){if(_r&&Me)return{active:!0,managed:!0,model:Me,port:Ht,provider:Wt,routedModel:Mn,caching:Dn,reasoning:Bn,externalBaseUrl:null};let r=yt(io(K))?.env||{};return{active:!1,managed:!1,model:null,port:null,provider:null,routedModel:null,caching:"unknown",reasoning:Bn,externalBaseUrl:r.ANTHROPIC_BASE_URL||null}}async function zh(r,e){let t=await hA();return Me=r,Wt=e,yA(K,t),t}async function SA({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(Nl(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 zh(r,Il[r]??null),Mn=null,Dn="unknown",bA(K,r,Wt)}catch(e){return{ok:!1,error:`failed to start the wire proxy: ${U(e)}`}}return{ok:!0}}async function kA({level:r}){return r!=null&&(!Number.isInteger(r)||r<0||r>=Ol.length)?{ok:!1,error:`reasoning level must be 0\u2013${Ol.length-1} or null`}:(Bn=r,{ok:!0,level:r})}async function xA(){return Gh(K),Me=null,Wt=null,Mn=null,Dn="unknown",{ok:!0}}async function EA({key:r}){let e=(r||"").trim();if(!e)return{ok:!1,error:"empty key"};let t=K,n=so(t,".env"),s="";try{s=_l(n,"utf8")}catch{}try{if(/^\s*OPENROUTER_API_KEY\s*=/m.test(s))Uh(n,s.replace(/^\s*OPENROUTER_API_KEY\s*=.*$/m,`OPENROUTER_API_KEY=${e}`));else{let i=s&&!s.endsWith(`
|
|
576
576
|
`)?`
|
|
577
|
-
`:"";
|
|
578
|
-
`)}}catch(i){return{ok:!1,error:U(i)}}return process.env.OPENROUTER_API_KEY=e,
|
|
579
|
-
`)}catch(o){return{ok:!1,error:`could not write ${r}: ${U(o)}`}}return{ok:!0,count:e.length}}var
|
|
577
|
+
`:"";Jh(n,i+`OPENROUTER_API_KEY=${e}
|
|
578
|
+
`)}}catch(i){return{ok:!1,error:U(i)}}return process.env.OPENROUTER_API_KEY=e,Hh(t,[".env"],"# secrets"),{ok:!0}}function AA(){if(!(!_r&&!Me)){try{Gh(K)}catch{}gA()}}function TA(r,e){return Qh.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 PA(r){if(Qh.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 OA(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=Cl(e?.cache_read_input_tokens)||Cl(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 CA({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(Nl(r))return{ok:!1,error:"Anthropic model \u2014 not offered or probed via OpenRouter"};let t=Date.now(),n=Array(350).fill("Caching probe filler sentence; its only purpose is to exceed the prompt-cache minimum token threshold.").join(" "),s={"content-type":"application/json",authorization:`Bearer ${e}`,"anthropic-version":"2023-06-01"},i={model:r,max_tokens:64,system:[{type:"text",text:n,cache_control:{type:"ephemeral"}}],messages:[{role:"user",content:"Reply with exactly: ok"}]},o=async a=>{let c=new AbortController,l=setTimeout(()=>c.abort(),2e4);try{let f=JSON.stringify(a?{...i,provider:Wh(a)}:i),u=await fetch(Rl,{method:"POST",signal:c.signal,headers:s,body:f}),d=await u.json().catch(()=>({}));return{r:u,j:d}}finally{clearTimeout(l)}};try{let{r:a,j:c}=await o();if(!a.ok){let k=c?.error?.message||c?.message||JSON.stringify(c).slice(0,300);return{ok:!0,callable:!1,status:a.status,ms:Date.now()-t,error:TA(a.status,k),restriction:PA(k)}}let l=typeof c?.provider=="string"?c.provider:void 0,f=c?.content?.find?.(k=>k.type==="text")?.text??c?.content?.[0]?.text??"ok",u=Cl(c?.usage?.cache_creation_input_tokens),{r:d,j:p}=await o(l),{works:y,read:m,note:b}=OA(d.ok,p?.usage,l);return y===!0&&l&&(Il[r]=l,Me===r&&(Wt=l)),{ok:!0,callable:!0,status:a.status,ms:Date.now()-t,provider:l,sample:String(f).trim().slice(0,60),cache:{works:y,created:u,read:m,note:b}}}catch(a){let c=U(a);return{ok:!0,callable:!1,ms:Date.now()-t,error:/abort/i.test(c)?"timed out (20s)":c}}}var sA,Rl,iA,oA,Kh,aA,Ol,io,oo,ro,Nl,_r,Ht,Me,Wt,Mn,Dn,Bn,Il,Cl,Wh,Qh,Xh=A(()=>{Ar();ht();sA="https://openrouter.ai/api",Rl=`${sA}/v1/messages`,iA="typebulb-proxy-managed",oA="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.",Kh=["ANTHROPIC_BASE_URL","ANTHROPIC_AUTH_TOKEN"],aA=5e3,Ol=["low","medium","high"],io=r=>so(r,".claude","settings.local.json"),oo=r=>so(r,".claude",".cc-switcher.json"),ro=r=>`http://127.0.0.1:${r}`;Nl=r=>/^anthropic\//i.test(r)||/claude/i.test(r),_r=null,Ht=null,Me=null,Wt=null,Mn=null,Dn="unknown",Bn=1,Il={},Cl=r=>typeof r=="number"?r:0,Wh=r=>({order:[r],allow_fallbacks:!1});Qh=/data policy|no endpoints|no allowed providers|privacy|requires.*(training|logging|data)/i;(async function(){try{let e=yt(oo(K)),t=e?.active?.model;if(!t)return;let s=(yt(io(K))?.env||{}).ANTHROPIC_BASE_URL||"";if(!/127\.0\.0\.1|localhost/.test(s))return;let i=await zh(t,e.active.provider??Il[t]??null);console.log(`[switcher] re-adopted override after restart: ${t} via ${ro(i)}`)}catch(e){console.error("[switcher] boot reconcile failed",U(e))}})()});var eg={};su(eg,{attach:()=>DA,blockToMarkdown:()=>Pi,breakout:()=>xh,capText:()=>_e,cleanUserText:()=>dt,clearSwitchModel:()=>xA,composerPasteRead:()=>BA,displayName:()=>_A,downloadSample:()=>Mh,firstLineDigest:()=>He,gitChangedFiles:()=>lh,gitDiff:()=>uh,info:()=>RA,isHiddenTurn:()=>_n,launchBulb:()=>Oh,listBreakouts:()=>Eh,listBulbFiles:()=>Th,listMyBulbs:()=>Dh,listSamples:()=>Lh,listSessions:()=>$A,listSwitchModels:()=>wA,logEmbedStatus:()=>IA,openFile:()=>kh,poll:()=>NA,predictTrustOf:()=>Ch,probeModel:()=>CA,pullRemoteBulb:()=>Bh,pushLocalBulb:()=>Fh,readBulbLog:()=>Rh,repoRoot:()=>Or,saveOpenRouterKey:()=>EA,searchBulbs:()=>Ph,searchSessions:()=>LA,sessionPeek:()=>MA,setBulbTrust:()=>_h,setReasoning:()=>kA,setSwitchModel:()=>SA,shutdownSwitcher:()=>AA,stopBreakout:()=>Ah,switchState:()=>vA,toolResultDigest:()=>Xc});var Zh,_A,RA,NA,IA,$A,LA,MA,DA,BA,tg=A(()=>{vl();Oi();Pl();Vi();Xh();Oi();Ai();Zh=new vr,_A=Zh.displayName,{info:RA,poll:NA,logEmbedStatus:IA,listSessions:$A,searchSessions:LA,sessionPeek:MA,attach:DA,composerPasteRead:BA}=eo(Zh)});import{readFileSync as jA,writeFileSync as FA,mkdirSync as qA}from"fs";import{homedir as UA}from"os";import*as ao from"path";async function sg(){try{let r=await fetch(new URL("/api/tags",ng()).toString(),{signal:AbortSignal.timeout(JA)});return r.ok?((await r.json()).models??[]).map(t=>t.name).filter(t=>!!t):[]}catch{return[]}}function ig(r){let e;try{e=jA(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&&!$l(n)}}}catch{}return{json:void 0,unreadable:!0}}function $l(r){let e=r?.providers;return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function KA(r){let e=$l(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 og(){let{json:r,unreadable:e}=ig(rg());return e?{installed:[],configured:null}:{installed:await sg(),configured:KA(r)}}async function ag(){let r=await sg();return r.length?HA(rg(),r,ng()):{ok:!1,error:"Ollama is not running (or has no models installed)"}}function HA(r,e,t){let{json:n,unreadable:s}=ig(r);if(s)return{ok:!1,error:`could not parse ${r} \u2014 edit the ollama provider there yourself`};let i={...n??{},providers:{...$l(n)??{},ollama:{baseUrl:`${t}/v1`,api:"openai-completions",apiKey:"ollama",models:e.map(o=>({id:o}))}}};try{qA(ao.dirname(r),{recursive:!0}),FA(r,JSON.stringify(i,null,2)+`
|
|
579
|
+
`)}catch(o){return{ok:!1,error:`could not write ${r}: ${U(o)}`}}return{ok:!0,count:e.length}}var JA,rg,ng,cg=A(()=>{ht();Ar();JA=1500,rg=()=>ao.join(UA(),".pi","agent","models.json"),ng=()=>yr(process.env.OLLAMA_HOST??"http://localhost:11434")});var ug={};su(ug,{attach:()=>ZA,breakout:()=>xh,composerFiles:()=>nT,composerNew:()=>rT,composerPaste:()=>oT,composerPasteRead:()=>aT,composerRpc:()=>iT,composerSend:()=>eT,composerStop:()=>tT,composerUiRespond:()=>sT,displayName:()=>WA,downloadSample:()=>Mh,gitChangedFiles:()=>lh,gitDiff:()=>uh,info:()=>YA,launchBulb:()=>Oh,listBreakouts:()=>Eh,listBulbFiles:()=>Th,listMyBulbs:()=>Dh,listSamples:()=>Lh,listSessions:()=>zA,logEmbedStatus:()=>GA,ollamaOffer:()=>og,ollamaSync:()=>ag,openFile:()=>kh,poll:()=>VA,predictTrustOf:()=>Ch,pullRemoteBulb:()=>Bh,pushLocalBulb:()=>Fh,readBulbLog:()=>Rh,repoRoot:()=>Or,searchBulbs:()=>Ph,searchSessions:()=>QA,sessionPeek:()=>XA,setBulbTrust:()=>_h,shutdownComposer:()=>cT,stopBreakout:()=>Ah});var lg,WA,YA,VA,GA,zA,QA,XA,ZA,eT,tT,rT,nT,sT,iT,oT,aT,cT,fg=A(()=>{vl();yl();Pl();Vi();cg();lg=new Tr,WA=lg.displayName,{info:YA,poll:VA,logEmbedStatus:GA,listSessions:zA,searchSessions:QA,sessionPeek:XA,attach:ZA,composerSend:eT,composerStop:tT,composerNew:rT,composerFiles:nT,composerUiRespond:sT,composerRpc:iT,composerPaste:oT,composerPasteRead:aT,shutdownComposer:cT}=eo(lg)});import*as hy from"fs/promises";import*as Gt from"path";import*as pu from"path";import*as ou from"fs/promises";import{existsSync as zt,readFileSync as By}from"fs";import*as V from"path";import{pathToFileURL as jy}from"url";import{resolve as Po}from"resolve.exports";import{init as au,parse as cu}from"es-module-lexer";function lu(r,e){let t=V.join(r,"package.json");try{return JSON.parse(By(t,"utf8"))}catch{throw new Error(`--replace package '${e}' has no readable package.json at ${t}`)}}var To=["browser","import","default"],iu=["node","import","default"];function uu(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:V.resolve(n)}}async function fu(r){let{name:e,dir:t}=r;if(!zt(t))throw new Error(`--replace path for '${e}' does not exist: ${t}`);let n=lu(t,e),s=Fy(n,e),i=V.resolve(t,s);if(!zt(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=V.dirname(i),a=`/local/${e}/${V.basename(i)}`,c=qy(n,t);return await Uy(e,i,o),{name:e,dir:t,entryAbs:i,serveDir:o,entryUrl:a,typesAbs:c}}function Fy(r,e){if(r.exports!==void 0){let n;try{n=Po(r,".",{browser:!0,conditions:To})}catch(i){throw new Error(`--replace package '${e}' "exports" does not resolve a browser entry (conditions: ${To.join(", ")}): ${i instanceof Error?i.message:i}`)}let s=Oo(n);if(!s)throw new Error(`--replace package '${e}' "exports" did not resolve "." to a single file (conditions: ${To.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 qy(r,e){if(r.exports!==void 0)try{let n=Po(r,".",{conditions:["types"]}),s=Oo(n);if(s){let i=V.resolve(e,s);if(zt(i))return i}}catch{}let t=r.types??r.typings;if(t){let n=V.resolve(e,t);if(zt(n))return n}}function Oo(r){if(typeof r=="string")return r;if(Array.isArray(r))return r.find(e=>typeof e=="string")}async function Uy(r,e,t){await au;let n=V.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 ou.readFile(o,"utf8")}catch{continue}let c,l;try{[c,,,l]=cu(a,o)}catch{continue}if(o===e&&!l)throw new Error(`override package '${r}' entry is not an ES module (no import/export syntax); CommonJS or non-module entries aren't supported (esm.sh would have to transform it).`);for(let f of c){if(f.d===-2)continue;let u=f.n;if(u&&!u.startsWith("node:")){if(u.startsWith("./")||u.startsWith("../")||u.startsWith("/")){let d=Jy(o,u,n);d&&!s.has(d)&&i.push(d);continue}throw new Error(`override package must ship self-contained (bundle its dependencies); ${r} externalizes '${u}'`)}}}}function Jy(r,e,t){let n=e.replace(/[?#].*$/,""),s=V.resolve(V.dirname(r),n),i=[s,s+".js",s+".mjs",V.join(s,"index.js"),V.join(s,"index.mjs")];for(let o of i)if(V.normalize(o).startsWith(t)&&zt(o))return o}function Ky(r,e,t){let n=lu(r,e),s;if(n.exports!==void 0)try{s=Oo(Po(n,t,{conditions:iu}))}catch(o){throw new Error(`--replace package '${e}' "exports" does not resolve a node entry for '${t}' (conditions: ${iu.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=V.resolve(r,s);if(!zt(i))throw new Error(`--replace package '${e}' built file not found: ${i} \u2014 did you build it (e.g. \`pnpm run build\`)?`);return jy(i).href}async function du(r,e){await au;let t;try{[t]=cu(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=Ky(e.dir,e.name,a);n+=r.slice(s,i.s)+c,s=i.e}return n+r.slice(s)}var Hy=5e3;function mu(r){let t={subcommand:"run",file:"",port:3e3,watch:!0,open:!(process.env.TERM_PROGRAM==="vscode"),server:!1,trust:!1,noTrust:!1,force:!1,follow:!1,clear:!1,help:!1,version:!1,callArgs:[],hasArgsFlag:!1},n=["call","check","predict","logs","wait","stop","trust","untrust","skill","models","send","pull","push"],s=r[0];if(s==="agent"||s?.startsWith("agent:")){t.subcommand="agent";let o=s.indexOf(":");if(o!==-1){let a=s.slice(o+1);a&&(t.agentTarget=a)}r=r.slice(1)}else s&&n.includes(s)&&(t.subcommand=s,r=r.slice(1));let i=[];for(let o=0;o<r.length;o++){let a=r[o];if(a==="--help"||a==="-h")t.help=!0;else if(a==="--version"||a==="-V")t.version=!0;else if(a==="--no-watch")t.watch=!1;else if(a==="--open")t.open=!0;else if(a==="--no-open")t.open=!1;else if(a==="--server")t.server=!0;else if(a==="--trust")t.trust=!0;else if(a==="--no-trust")t.noTrust=!0;else if(a==="--force")t.force=!0;else if(a==="--mode"){let c=r[++o];(!c||c.startsWith("-"))&&(console.error("Missing value for --mode (e.g. --mode staging)"),process.exit(1)),t.mode=c}else if(a==="--dir"){let c=r[++o];(!c||c.startsWith("-"))&&(console.error("Missing value for --dir (a subfolder of the bulb's folder, e.g. --dir batch2)"),process.exit(1));let l=c.replace(/[\\/]+$/,"");(!l||pu.isAbsolute(l)||l.split(/[\\/]/).some(f=>f===""||f===".."))&&(console.error(`Invalid --dir value: ${c} (a relative subfolder of the bulb's folder \u2014 no absolute paths or '..')`),process.exit(1)),t.dir=l}else if(a==="--follow"||a==="-f")t.follow=!0;else if(a==="--clear")t.clear=!0;else if(a==="--run"){let c=r[++o];if(c==="latest")t.run="latest";else{let l=parseInt(c,10);(isNaN(l)||l<1)&&(console.error(`Invalid --run value: ${c} (a run number, or 'latest')`),process.exit(1)),t.run=l}}else if(a==="--bulbs")t.stopScope="bulbs";else if(a==="--agent")t.stopScope="agent";else if(a==="--global")t.stopScope="global";else if(a==="--match"){let c=r[++o];c===void 0&&(console.error("Missing value for --match (a literal substring new log lines must contain)"),process.exit(1)),t.match=c}else if(a==="--timeout"){let c=parseInt(r[++o],10);(isNaN(c)||c<=0)&&(console.error(`Invalid --timeout value: ${r[o]} (seconds)`),process.exit(1)),t.timeoutSec=c}else if(a==="--wait"||a.startsWith("--wait="))if(a.startsWith("--wait=")){let c=parseInt(a.slice(7),10);(isNaN(c)||c<=0)&&(console.error(`Invalid --wait value: ${a.slice(7)} (milliseconds)`),process.exit(1)),t.sendWaitMs=c}else t.sendWaitMs=Hy;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=uu(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 hu(){console.log(`
|
|
580
580
|
typebulb - Local bulb runner for Typebulb
|
|
581
581
|
|
|
582
582
|
Usage:
|
|
@@ -672,6 +672,11 @@ Options:
|
|
|
672
672
|
--mode <name> Also load .env.<name> (+ .env.<name>.local) on top
|
|
673
673
|
of .env / .env.local. Free-form name; loads no mode
|
|
674
674
|
file by default.
|
|
675
|
+
--dir <sub> Scope the bulb's dir to a subfolder for this run:
|
|
676
|
+
tb.dir and relative tb.fs paths land in
|
|
677
|
+
<bulb-folder>/<sub>. Batch runs without touching
|
|
678
|
+
the bulb's code (e.g. --dir batch2). Relative
|
|
679
|
+
subpaths only \u2014 no absolute paths or '..'.
|
|
675
680
|
--server Run server.ts only, no web server (needs --trust)
|
|
676
681
|
--args <json-array> For 'call': the whole argument list as one JSON
|
|
677
682
|
array (strict). '--args -' reads it from stdin,
|
|
@@ -718,11 +723,11 @@ Examples:
|
|
|
718
723
|
typebulb my-editor.bulb.md
|
|
719
724
|
typebulb --no-watch --port 8080 my-editor.bulb.md
|
|
720
725
|
typebulb .
|
|
721
|
-
`)}gn();import*as ft from"fs/promises";import*as
|
|
726
|
+
`)}gn();import*as ft from"fs/promises";import*as se from"path";import{pathToFileURL as Rx}from"url";import{transform as Nk}from"sucrase";function vc(r,e={}){let t=e.serverOnly?["typescript"]:["typescript","jsx"];try{let{code:n}=Nk(r,{transforms:t,jsxRuntime:"automatic",jsxImportSource:e.jsxImportSource||"react",production:!0});return{code:n}}catch(n){return{code:"",error:String(n)}}}Qs();function jk(r){return r.map(e=>`${e.type} (line ${e.lineNumber}): ${e.message.split(`
|
|
722
727
|
`)[0]}`).join(`
|
|
723
|
-
`)}function
|
|
724
|
-
${Bk(t)}`)}var ot="https://esm.sh",bn="https://cdn.jsdelivr.net/npm/",Sc="https://data.jsdelivr.com/v1/package/npm/";function Cp(r){let e=(r||"").replace(/^\/+/,"").replace(/\/+$/,"");return e?e.split("/"):[]}var D=class r{constructor(e,t,n){let s=typeof e=="string"?r.parse(e):e;this.name=s.name,this.version=lr(t??s.version),this.subpath=lr(n??s.subpath)}static parse(e){let t=Cp(e||"");if(!t.length)return new r({name:""});if(t[0].startsWith("@")){let s=t[0],[i,o]=_p(t[1]??""),a=lr(t.slice(2).join("/"));return new r({name:`${s}/${i}`,version:o,subpath:a})}else{let[s,i]=_p(t[0]),o=lr(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(ot).host,s=new URL(bn).host;if(t.host===n){let i=Cp(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:lr(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://")}},lr=r=>r&&r.length?r:void 0,_p=r=>{let e=r.indexOf("@");return e<0?[r,void 0]:[r.slice(0,e),lr(r.slice(e+1))]};async function ae(r){try{return await r()}catch{return}}function _t(r){let e=r||"";return e.startsWith("./")?e.slice(2):e.replace(/^\/+/,"")}function kc(r){return r.startsWith("./")?r:`./${r}`}var wn=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 D(e):e;return`${bn}${t.name}${t.version?`@${t.version}`:""}/`}file(e,t){return new URL(_t(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(",")),`${ot}/${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),`${ot}/${e}`]);return this.pinCache.set(e,{value:s,ts:t}),s}async tryResolveFromUrls(e){for(let t of e){let n=await ae(()=>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 ae(()=>this.http.getJson(`${Sc}${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=D.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 D(`${e}@${t}`)),i=await ae(()=>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 Rp=r=>r.startsWith("@types/"),vn=r=>Object.keys(r?.peerDependencies||{}).filter(e=>!Rp(e)),xc=r=>Object.keys(r?.dependencies||{}).filter(e=>!Rp(e)),jk=r=>vn(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 jk(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=>vn(i.meta))),n=new Map;for(let i of e)for(let o of xc(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:vn(i.meta).length>0,isSharedDep:s.has(i.name)}]))}};var kn=class{constructor(e,t,n){this.cache=e,this.cdn=t,this.semver=n}async learnExactVersion(e){let t=await ae(()=>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 ae(()=>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 ae(()=>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 D(e),s=n.root(),i=t[s],o=i?await ae(()=>this.resolveExactForRoot(s,i)):void 0;return{effectivePackage:o?n.withVersion(o).format():e,root:s,range:i,pinned:o}}};import{init as Fk,parse as qk}from"es-module-lexer";var ur=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))D.isBare(s[1])&&t.add(s[1])}return Array.from(t)}async extractImports(e){let t=new Set,n=s=>{D.isBare(s)&&t.add(s)};try{await Fk;let[s]=qk(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(D.rootOf(u))),i=[...new Set(s.map(D.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(D.rootOf(p));return new D(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!==D.rootOf(p)).map(D.rootOf)),c=[],l=new Set,d=new Set(e.filter(p=>p===D.rootOf(p))),u=new Set;for(let p of e){let y=D.rootOf(p),m=s.get(y),{isPeerRoot:b,hasPeers:k,isSharedDep:x}=n.get(y),T=a.has(y),P=p!==y,O=!(b||x)&&(T||!k),R=this.singletonDepsOf(m,o),h=P&&d.has(y);h&&u.add(y);let S=h?[...R,y]:R.length?R:void 0;c.push([p,this.cdn.buildEsmUrl(i(p),{bundle:O,external:S})]),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}/`,`${ot}/${i(p)}/`]));return c}singletonDepsOf(e,t){return[...new Set([...vn(e.meta),...xc(e.meta)])].filter(n=>t.has(n))}};ur.importPatterns=[/\bimport\s+(?:[^'";]*?from\s*)?['"]([^'"]+)['"]/g,/\bexport\s+[^'";]*?from\s*['"]([^'"]+)['"]/g];import{gt as Np,satisfies as Uk,maxSatisfying as Ip,major as Jk,valid as Kk}from"semver";var Xs=class{cmp(e,t){return e===t?0:Np(e,t)?1:Np(t,e)?-1:0}satisfies(e,t){return!e||!e.trim()?!0:!!Uk(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=Ip(e,n,{includePrerelease:!1});if(a)return a}return Ip(e,n,{includePrerelease:!0})??void 0}majorOf(e){return Jk(e)}isExactVersion(e){return Kk(e)!==null}},Rt=new Xs;var Nt=class{constructor(e){this.store=e}async isNegative(e){let t=await ae(()=>this.store.get(e));return!!t&&t.until>Date.now()}async recordNegative(e){let n=((await ae(()=>this.store.get(e)))?.attempts||0)+1;await ae(()=>this.store.set(e,{until:Date.now()+Hk(n),attempts:n}))}async clearNegative(e){await ae(()=>this.store.delete(e))}};function Hk(r){return Math.min(9e5*Math.pow(2,Math.max(0,r-1)),864e5)}function $p(r,e){let t=new wn(r,e),n=new Sn(t),s=new kn(r,t,Rt);return{packageService:new ur(s,t,n),versionResolver:s,cdnClient:t,peerResolver:n}}import*as qp from"fs/promises";import*as Se from"path";import*as ct from"fs/promises";import*as qe from"path";import*as Dp from"os";import*as Ec from"fs/promises";import*as Lp from"crypto";function ve(r){return Lp.createHash("sha1").update(r).digest("hex")}async function Fe(r){try{return JSON.parse(await Ec.readFile(r,"utf8"))}catch{return}}async function Zs(r){try{return await Ec.readFile(r,"utf8")}catch{return}}var Mp=1,at=qe.join(Dp.homedir(),".typebulb","cache"),xn=qe.join(at,"packages"),En=qe.join(at,"proxy"),ei=qe.join(at,"dts"),Wk=qe.join(at,"emit"),Ac;function H(){return Ac||(Ac=Yk()),Ac}function ti(r,e){return qe.join(Wk,ve(r),e)}async function Yk(){await ct.mkdir(at,{recursive:!0});let r=qe.join(at,"version.json");if((await Fe(r))?.version===Mp)return;let t=await ct.readdir(at).catch(()=>[]);await Promise.all(t.map(n=>ct.rm(qe.join(at,n),{recursive:!0,force:!0}))),await ct.writeFile(r,JSON.stringify({version:Mp})+`
|
|
725
|
-
`,"utf8")}import*as lt from"fs/promises";import*as
|
|
728
|
+
`)}function Cp(r,e){let t=yn(r,{target:"client",dependencies:e}).filter(n=>n.type==="UNDECLARED_IMPORT");if(t.length)throw new Error(`Lint failed:
|
|
729
|
+
${jk(t)}`)}var ot="https://esm.sh",bn="https://cdn.jsdelivr.net/npm/",Sc="https://data.jsdelivr.com/v1/package/npm/";function _p(r){let e=(r||"").replace(/^\/+/,"").replace(/\/+$/,"");return e?e.split("/"):[]}var D=class r{constructor(e,t,n){let s=typeof e=="string"?r.parse(e):e;this.name=s.name,this.version=lr(t??s.version),this.subpath=lr(n??s.subpath)}static parse(e){let t=_p(e||"");if(!t.length)return new r({name:""});if(t[0].startsWith("@")){let s=t[0],[i,o]=Rp(t[1]??""),a=lr(t.slice(2).join("/"));return new r({name:`${s}/${i}`,version:o,subpath:a})}else{let[s,i]=Rp(t[0]),o=lr(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(ot).host,s=new URL(bn).host;if(t.host===n){let i=_p(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:lr(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://")}},lr=r=>r&&r.length?r:void 0,Rp=r=>{let e=r.indexOf("@");return e<0?[r,void 0]:[r.slice(0,e),lr(r.slice(e+1))]};async function ce(r){try{return await r()}catch{return}}function _t(r){let e=r||"";return e.startsWith("./")?e.slice(2):e.replace(/^\/+/,"")}function kc(r){return r.startsWith("./")?r:`./${r}`}var wn=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 D(e):e;return`${bn}${t.name}${t.version?`@${t.version}`:""}/`}file(e,t){return new URL(_t(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(",")),`${ot}/${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),`${ot}/${e}`]);return this.pinCache.set(e,{value:s,ts:t}),s}async tryResolveFromUrls(e){for(let t of e){let n=await ce(()=>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 ce(()=>this.http.getJson(`${Sc}${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=D.fromUrl(e)?.version;return t&&/\d+\.\d+\.\d+/.test(t)?t:void 0}async fetchPackageMeta(e,t){let n=await this.cache.getMeta(e,t);if(n&&Date.now()-n.updatedAt<this.metaTtlMs){let{dependencies:f,peerDependencies:u,peerDependenciesMeta:d}=n;return{name:e,version:t,dependencies:f,peerDependencies:u,peerDependenciesMeta:d}}let s=this.packageJson(new D(`${e}@${t}`)),i=await ce(()=>this.http.getJson(s));if(!i)return;let o=f=>f&&Object.keys(f).length?f:void 0,a=o(i.dependencies),c=o(i.peerDependencies),l=o(i.peerDependenciesMeta);return await this.cache.setMeta(e,t,a,c,l),{name:e,version:t,dependencies:a,peerDependencies:c,peerDependenciesMeta:l}}};var Np=r=>r.startsWith("@types/"),vn=r=>Object.keys(r?.peerDependencies||{}).filter(e=>!Np(e)),xc=r=>Object.keys(r?.dependencies||{}).filter(e=>!Np(e)),Fk=r=>vn(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 Fk(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=>vn(i.meta))),n=new Map;for(let i of e)for(let o of xc(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:vn(i.meta).length>0,isSharedDep:s.has(i.name)}]))}};var kn=class{constructor(e,t,n){this.cache=e,this.cdn=t,this.semver=n}async learnExactVersion(e){let t=await ce(()=>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 ce(()=>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 ce(()=>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 D(e),s=n.root(),i=t[s],o=i?await ce(()=>this.resolveExactForRoot(s,i)):void 0;return{effectivePackage:o?n.withVersion(o).format():e,root:s,range:i,pinned:o}}};import{init as qk,parse as Uk}from"es-module-lexer";var ur=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))D.isBare(s[1])&&t.add(s[1])}return Array.from(t)}async extractImports(e){let t=new Set,n=s=>{D.isBare(s)&&t.add(s)};try{await qk;let[s]=Uk(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(D.rootOf(u))),i=[...new Set(s.map(D.rootOf))],o=await Promise.all(i.map(async u=>({name:u,version:await this.resolveVersion(u,t)}))),{allRoots:a,flags:c,autoAddedPeers:l}=await this.peer.resolve(o,u=>this.resolveVersion(u,t)),f=this.buildEntries([...s,...l.map(u=>u.name)],a,c);return{importMap:{imports:Object.fromEntries(f)},prefetchUrls:f.map(([,u])=>u)}}async resolveVersion(e,t){let n=t[e],s=await this.version.resolveExactForRoot(e,n);if(!s)throw new Error(`Cannot resolve ${n?`${e}@${n}`:e}: no matching version is published (the package or version may not exist, or the registry was unreachable).`);return s}buildEntries(e,t,n){let s=new Map(t.map(p=>[p.name,p])),i=p=>{let y=s.get(D.rootOf(p));return new D(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!==D.rootOf(p)).map(D.rootOf)),c=[],l=new Set,f=new Set(e.filter(p=>p===D.rootOf(p))),u=new Set;for(let p of e){let y=D.rootOf(p),m=s.get(y),{isPeerRoot:b,hasPeers:k,isSharedDep:x}=n.get(y),T=a.has(y),P=p!==y,O=!(b||x)&&(T||!k),R=this.singletonDepsOf(m,o),h=P&&f.has(y);h&&u.add(y);let S=h?[...R,y]:R.length?R:void 0;c.push([p,this.cdn.buildEsmUrl(i(p),{bundle:O,external:S})]),l.add(p)}let d=new Set([...o,...u]);for(let p of d)s.has(p)&&(l.has(p)||c.push([p,this.cdn.buildEsmUrl(i(p),{})]),c.push([`${p}/`,`${ot}/${i(p)}/`]));return c}singletonDepsOf(e,t){return[...new Set([...vn(e.meta),...xc(e.meta)])].filter(n=>t.has(n))}};ur.importPatterns=[/\bimport\s+(?:[^'";]*?from\s*)?['"]([^'"]+)['"]/g,/\bexport\s+[^'";]*?from\s*['"]([^'"]+)['"]/g];import{gt as Ip,satisfies as Jk,maxSatisfying as $p,major as Kk,valid as Hk}from"semver";var Xs=class{cmp(e,t){return e===t?0:Ip(e,t)?1:Ip(t,e)?-1:0}satisfies(e,t){return!e||!e.trim()?!0:!!Jk(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=$p(e,n,{includePrerelease:!1});if(a)return a}return $p(e,n,{includePrerelease:!0})??void 0}majorOf(e){return Kk(e)}isExactVersion(e){return Hk(e)!==null}},Rt=new Xs;var Nt=class{constructor(e){this.store=e}async isNegative(e){let t=await ce(()=>this.store.get(e));return!!t&&t.until>Date.now()}async recordNegative(e){let n=((await ce(()=>this.store.get(e)))?.attempts||0)+1;await ce(()=>this.store.set(e,{until:Date.now()+Wk(n),attempts:n}))}async clearNegative(e){await ce(()=>this.store.delete(e))}};function Wk(r){return Math.min(9e5*Math.pow(2,Math.max(0,r-1)),864e5)}function Lp(r,e){let t=new wn(r,e),n=new Sn(t),s=new kn(r,t,Rt);return{packageService:new ur(s,t,n),versionResolver:s,cdnClient:t,peerResolver:n}}import*as Up from"fs/promises";import*as Se from"path";import*as ct from"fs/promises";import*as qe from"path";import*as Bp from"os";import*as Ec from"fs/promises";import*as Mp from"crypto";function ve(r){return Mp.createHash("sha1").update(r).digest("hex")}async function Fe(r){try{return JSON.parse(await Ec.readFile(r,"utf8"))}catch{return}}async function Zs(r){try{return await Ec.readFile(r,"utf8")}catch{return}}var Dp=1,at=qe.join(Bp.homedir(),".typebulb","cache"),xn=qe.join(at,"packages"),En=qe.join(at,"proxy"),ei=qe.join(at,"dts"),Yk=qe.join(at,"emit"),Ac;function H(){return Ac||(Ac=Vk()),Ac}function ti(r,e){return qe.join(Yk,ve(r),e)}async function Vk(){await ct.mkdir(at,{recursive:!0});let r=qe.join(at,"version.json");if((await Fe(r))?.version===Dp)return;let t=await ct.readdir(at).catch(()=>[]);await Promise.all(t.map(n=>ct.rm(qe.join(at,n),{recursive:!0,force:!0}))),await ct.writeFile(r,JSON.stringify({version:Dp})+`
|
|
730
|
+
`,"utf8")}import*as lt from"fs/promises";import*as jp from"path";async function me(r,e){await lt.mkdir(jp.dirname(r),{recursive:!0});let t=`${r}.tmp-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;await lt.writeFile(t,e,"utf8"),await lt.rename(t,r).catch(async n=>{throw await lt.rm(t,{force:!0}).catch(()=>{}),n})}var fr=class{constructor(e){this.filePath=e}mem;loadPromise;load(){return this.mem?Promise.resolve(this.mem):(this.loadPromise||(this.loadPromise=Fe(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 me(this.filePath,JSON.stringify(Object.fromEntries(e)))}};var Tc=Se.join(xn,"indexes"),Fp=Se.join(xn,"pinned"),Gk=Se.join(xn,"meta"),zk=Se.join(xn,"negative.json"),ni=class{pinnedMem=new Map;indexMem=new Map;metaMem=new Map;negativeCache=new Nt(new fr(zk));async getPinnedExact(e,t){let n=`${e}@${t}`;if(this.pinnedMem.has(n))return this.pinnedMem.get(n);await H();let s=await Zs(Se.join(Fp,ve(n)+".txt"));return this.pinnedMem.set(n,s),s}async setPinnedExact(e,t,n){let s=`${e}@${t}`;this.pinnedMem.set(s,n),await H(),await me(Se.join(Fp,ve(s)+".txt"),n)}async getIndex(e){if(this.indexMem.has(e))return this.indexMem.get(e);await H();let t=await Fe(Se.join(Tc,ri(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 H(),await me(Se.join(Tc,ri(e)+".json"),JSON.stringify(s))}async invalidateVersionsCache(e){this.indexMem.delete(e),await Up.rm(Se.join(Tc,ri(e)+".json"),{force:!0})}async isNegative(e){return await H(),this.negativeCache.isNegative(e)}async recordNegative(e){await H(),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 H();let s=await Fe(qp(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 H(),await me(qp(e,t),JSON.stringify(o))}};function qp(r,e){return Se.join(Gk,ri(r),encodeURIComponent(e)+".json")}function ri(r){return r.replace(/\//g,"__")}var Jp={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 Qk=new ni,{packageService:si,versionResolver:Kp,cdnClient:Hp,peerResolver:H_}=Lp(Qk,Jp);var Wp=`
|
|
726
731
|
(() => {
|
|
727
732
|
// Embedded (bulb-in-a-bulb): runs inside a sandboxed iframe with no parent
|
|
728
733
|
// bridge, so privileged tb.* (AI, fs, server RPC) can't reach a host and would
|
|
@@ -1082,7 +1087,7 @@ ${Bk(t)}`)}var ot="https://esm.sh",bn="https://cdn.jsdelivr.net/npm/",Sc="https:
|
|
|
1082
1087
|
// Filesystem - local CLI extension
|
|
1083
1088
|
fs,
|
|
1084
1089
|
|
|
1085
|
-
// The bulb's
|
|
1090
|
+
// The bulb's folder, absolute (TB-FS.md) \u2014 for interop (paths handed to server.ts or
|
|
1086
1091
|
// spawned tools); tb.fs itself already resolves relative paths against it. Absent in an
|
|
1087
1092
|
// embed (no filesystem to name), where access throws like tb.fs.
|
|
1088
1093
|
get dir() {
|
|
@@ -1169,8 +1174,8 @@ ${Bk(t)}`)}var ot="https://esm.sh",bn="https://cdn.jsdelivr.net/npm/",Sc="https:
|
|
|
1169
1174
|
});
|
|
1170
1175
|
} catch (e) {}
|
|
1171
1176
|
})();
|
|
1172
|
-
</script>`}function
|
|
1173
|
-
html, body { height: 100%; }`,p={imports:
|
|
1177
|
+
</script>`}function Yp(r){let{name:e,code:t,css:n,html:s,data:i,insight:o,importMap:a,theme:c,embedded:l,dir:f}=r,u=s.trim()||'<div id="app"></div>',d=l?"":`
|
|
1178
|
+
html, body { height: 100%; }`,p={imports:Zk(a.imports)};return`<!DOCTYPE html>
|
|
1174
1179
|
<html>
|
|
1175
1180
|
<head>
|
|
1176
1181
|
<meta charset="utf-8">
|
|
@@ -1181,7 +1186,7 @@ ${ai(e,c)}
|
|
|
1181
1186
|
${JSON.stringify(p,null,2)}
|
|
1182
1187
|
</script>
|
|
1183
1188
|
<style>
|
|
1184
|
-
${oi}${
|
|
1189
|
+
${oi}${d}
|
|
1185
1190
|
</style>
|
|
1186
1191
|
<style>
|
|
1187
1192
|
${n}
|
|
@@ -1192,13 +1197,13 @@ ${u}
|
|
|
1192
1197
|
|
|
1193
1198
|
${i.length>0?`<script>window.__TB_DATA__ = ${It(JSON.stringify(i))};</script>`:""}
|
|
1194
1199
|
${o?`<script>window.__TB_INSIGHT__ = ${It(JSON.stringify(o))};</script>`:""}
|
|
1195
|
-
${
|
|
1200
|
+
${f?`<script>window.__TB_DIR__ = ${It(JSON.stringify(f))};</script>`:""}
|
|
1196
1201
|
|
|
1197
1202
|
<script>
|
|
1198
|
-
${
|
|
1203
|
+
${Wp}
|
|
1199
1204
|
</script>
|
|
1200
1205
|
|
|
1201
|
-
${
|
|
1206
|
+
${Xk}
|
|
1202
1207
|
|
|
1203
1208
|
<script type="module">
|
|
1204
1209
|
globalThis.__tbEntryRan = true; /* import graph resolved \u2014 the load-failure backstop's signal (imports hoist above this line) */
|
|
@@ -1206,7 +1211,7 @@ await globalThis.__tbBoot; /* #tb= fragment restore, set by the shim when presen
|
|
|
1206
1211
|
${It(t)}
|
|
1207
1212
|
</script>
|
|
1208
1213
|
</body>
|
|
1209
|
-
</html>`}var
|
|
1214
|
+
</html>`}var Xk=`<script>
|
|
1210
1215
|
(function () {
|
|
1211
1216
|
var framed = window.parent !== window;
|
|
1212
1217
|
var post = function (m) { try { parent.postMessage(m, '*'); } catch (e) {} }; /* framed only */
|
|
@@ -1302,8 +1307,8 @@ ${It(t)}
|
|
|
1302
1307
|
}
|
|
1303
1308
|
});
|
|
1304
1309
|
})();
|
|
1305
|
-
</script>`;function
|
|
1306
|
-
Use a plain name with an exact / caret / tilde range (e.g. three@^0.160.0).`);await li.mkdir(e,{recursive:!0});let a=ci.join(e,"package.json");
|
|
1310
|
+
</script>`;function Zk(r){let e={};for(let[t,n]of Object.entries(r))e[t]=n.startsWith("https://")?"/proxy/"+n:n;return e}import*as li from"fs/promises";import*as ci from"path";import{existsSync as Vp,readFileSync as ex}from"fs";import{execFile as tx}from"child_process";import{promisify as rx}from"util";import{satisfies as nx}from"semver";var sx=rx(tx),ix=/^(@[a-z0-9._-]+\/)?[a-z0-9._-]+(@[a-zA-Z0-9.^~*x-]+)?$/i;async function ui(r,e,t,n){let i=r.map(l=>ox(l,t)).filter(l=>!ax(l,e));if(i.length===0)return;let o=i.filter(l=>!ix.test(l));if(o.length)throw new Error(`Refusing to install npm spec(s) with unsupported characters: ${o.join(", ")}
|
|
1311
|
+
Use a plain name with an exact / caret / tilde range (e.g. three@^0.160.0).`);await li.mkdir(e,{recursive:!0});let a=ci.join(e,"package.json");Vp(a)||await li.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 sx("npm",["install",...c,...i],{cwd:e,shell:!0})}function ox(r,e){if(!e||D.parse(r).version)return r;let t=e[r];return t?`${r}@${t}`:r}function ax(r,e){let{name:t,version:n}=D.parse(r),s=ci.join(e,"node_modules",t);if(!Vp(s))return!1;if(!n)return!0;try{let i=JSON.parse(ex(ci.join(s,"package.json"),"utf-8")).version;return nx(i,n)}catch{return!1}}function fi(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(D.rootOf(s))}return[...e]}hr();vi();Dt();async function im(r){let e=Je(r.provider,r.model);if(typeof e=="string")throw new Error(e);let t=await ut(e,r);if(!t.ok){let n=await mr(t,e.protocol);throw new Error(n.message)}return{response:t,protocol:e.protocol}}async function Cx(r){let{response:e,protocol:t}=await im(r);return{text:await Lt(e,t)}}async function*_x(r){let{response:e,protocol:t}=await im(r);yield*Mt(e,t)}function om(r){let e=Object.assign(Cx,{stream:_x});globalThis.tb=Object.freeze({ai:e,dir:r,models:()=>Ue(),hasOwnKeys:wi,mode:"local"})}async function am(r){let t=(await ft.readdir(r)).find(n=>n.endsWith(".bulb.md"));return t?se.join(r,t):null}function Si(r,e){let t=se.resolve(r),n=se.join(se.dirname(t),se.basename(t).replace(/\.bulb\.md$/,""));return e?se.join(n,e):n}async function xe(r){let e=await ft.readFile(r,"utf-8"),t=de(e);if(!t)throw new Error("Invalid .bulb.md file format");let n=cr(t);return{bulb:n,config:Lr(n.config),warnings:vu(e)}}function Uc(r){let e=se.basename(r).replace(/\.bulb\.md$/i,"");return se.join(se.dirname(r),".typebulb",`${e}.server.mjs`)}async function On(r,e,t,n,s){let i=vc(r,{serverOnly:!0});if(i.error)throw new Error(`Server compilation error: ${i.error}`);let o=i.code;t&&(o=await du(o,t));let a=se.join(se.dirname(e),".typebulb");await ft.mkdir(a,{recursive:!0});let c=fi(o);c.length>0&&await ui(c,a,n);let l=Uc(e);return await ft.writeFile(l,o,"utf-8"),om(Si(e,s)),await import(`${Rx(l).href}?t=${Date.now()}`)}async function Jc(r,e,t,n,s){let{bulb:i,config:o}=await xe(r),a=Gs(i.data);Cp(i.code,o.dependencies??{});let c=vc(i.code,{jsxImportSource:o.ts?.jsxImportSource});c.error&&console.error("Compilation error:",c.error);let{importMap:l}=await si.buildImportMap(c.code,o.dependencies??{},n?new Set([n.name]):void 0);n&&(l.imports[n.name]=n.entryUrl);let f=Yp({name:i.name,code:c.code,css:i.css,html:i.html,data:a,insight:i.insight,importMap:l,dir:Si(r,s),watch:e}),u=null;return i.server&&t&&(u=await On(i.server,r,n,o.dependencies,s)),{html:f,bulb:i,serverExports:u}}gn();Cn();Oi();yl();var co={claude:{adapter:()=>new vr,server:()=>Promise.resolve().then(()=>(tg(),eg))},pi:{adapter:()=>new Tr,server:()=>Promise.resolve().then(()=>(fg(),ug))}};function dg(r){return r in co}function Rr(){return Object.keys(co)}function pg(){return Object.fromEntries(Object.entries(co).map(([r,e])=>[r,e.adapter]))}function mg(r){return co[r].server()}import*as wt from"path";import{spawn as $T,execSync as LT}from"child_process";import{createRequire as MT}from"module";import{existsSync as DT}from"fs";import*as ie from"fs/promises";import*as re from"path";var Ll=[{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"}],Ml=[{name:"dom"},{name:"dom.iterable"},{name:"dom.asynciterable"}];function Dl(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 lT=`
|
|
1307
1312
|
/**
|
|
1308
1313
|
* Get raw data chunk from the Data tab.
|
|
1309
1314
|
* @param index - Chunk index (0-based). Separate chunks with 2 blank lines.
|
|
@@ -1314,7 +1319,7 @@ ${It(t)}
|
|
|
1314
1319
|
* @param index - Chunk index (0-based)
|
|
1315
1320
|
* @throws If chunk is not valid JSON/JSON-ish
|
|
1316
1321
|
*/
|
|
1317
|
-
json<T = unknown>(index: number): T;`,
|
|
1322
|
+
json<T = unknown>(index: number): T;`,uT=`
|
|
1318
1323
|
/**
|
|
1319
1324
|
* Get the insight data produced by the inference layer.
|
|
1320
1325
|
*
|
|
@@ -1323,7 +1328,7 @@ ${It(t)}
|
|
|
1323
1328
|
*
|
|
1324
1329
|
* @returns The parsed insight JSON, or undefined if no insight is available
|
|
1325
1330
|
*/
|
|
1326
|
-
insight<T = unknown>(): T | undefined;`,
|
|
1331
|
+
insight<T = unknown>(): T | undefined;`,hg=`options: {
|
|
1327
1332
|
messages: Array<{ role: "user" | "assistant"; content: string }>;
|
|
1328
1333
|
system?: string;
|
|
1329
1334
|
/** 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. */
|
|
@@ -1334,12 +1339,12 @@ ${It(t)}
|
|
|
1334
1339
|
webSearch?: boolean;
|
|
1335
1340
|
/** Abort the request. On abort the promise rejects / the stream ends. */
|
|
1336
1341
|
signal?: AbortSignal;
|
|
1337
|
-
}`,
|
|
1342
|
+
}`,gg=`
|
|
1338
1343
|
/** A single streamed delta from \`tb.ai.stream()\`. Discriminated by \`kind\`. */
|
|
1339
1344
|
type AiChunk =
|
|
1340
1345
|
| { kind: "text"; text: string }
|
|
1341
1346
|
| { kind: "reasoning"; text: string };
|
|
1342
|
-
`,
|
|
1347
|
+
`,yg=`
|
|
1343
1348
|
/**
|
|
1344
1349
|
* General-purpose AI call. \`tb.ai(opts)\` resolves with the full text; \`tb.ai.stream(opts)\`
|
|
1345
1350
|
* returns an async iterable of {@link AiChunk} deltas you consume with \`for await\`.
|
|
@@ -1348,7 +1353,7 @@ type AiChunk =
|
|
|
1348
1353
|
* @throws On rate limit, network error, or provider error
|
|
1349
1354
|
*/
|
|
1350
1355
|
ai: {
|
|
1351
|
-
(${
|
|
1356
|
+
(${hg}): Promise<{ text: string }>;
|
|
1352
1357
|
/**
|
|
1353
1358
|
* Streaming counterpart of \`tb.ai()\`. Yields \`{ kind: "text" | "reasoning", text }\` deltas
|
|
1354
1359
|
* as they arrive; break the loop (or abort \`signal\`) to cancel and stop the upstream.
|
|
@@ -1362,8 +1367,8 @@ type AiChunk =
|
|
|
1362
1367
|
* if (c.kind === "text") answer += c.text;
|
|
1363
1368
|
* }
|
|
1364
1369
|
*/
|
|
1365
|
-
stream(${
|
|
1366
|
-
};`,
|
|
1370
|
+
stream(${hg}): AsyncIterable<AiChunk>;
|
|
1371
|
+
};`,bg=`
|
|
1367
1372
|
/**
|
|
1368
1373
|
* Returns AI models available to the current user.
|
|
1369
1374
|
* Models are filtered by the user's configured API keys.
|
|
@@ -1385,7 +1390,7 @@ type AiChunk =
|
|
|
1385
1390
|
* making many AI calls should check this and show a "use your own keys"
|
|
1386
1391
|
* notice instead of running.
|
|
1387
1392
|
*/
|
|
1388
|
-
hasOwnKeys(): Promise<boolean>;`,
|
|
1393
|
+
hasOwnKeys(): Promise<boolean>;`,fT="\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;",wg=`
|
|
1389
1394
|
/**
|
|
1390
1395
|
* The mode this bulb is running in.
|
|
1391
1396
|
*
|
|
@@ -1395,11 +1400,11 @@ type AiChunk =
|
|
|
1395
1400
|
* - \`'embedded'\` \u2014 Running as a bulb embedded inside another bulb (sandboxed,
|
|
1396
1401
|
* client-only: AI, filesystem, and server RPC are unavailable)
|
|
1397
1402
|
*/
|
|
1398
|
-
mode: 'local' | 'editor' | 'published' | 'embedded';`,
|
|
1403
|
+
mode: 'local' | 'editor' | 'published' | 'embedded';`,dT=`
|
|
1399
1404
|
/**
|
|
1400
1405
|
* Local filesystem access (CLI only).
|
|
1401
1406
|
*
|
|
1402
|
-
* Relative paths resolve against the bulb's
|
|
1407
|
+
* Relative paths resolve against the bulb's folder (\`tb.dir\` \u2014
|
|
1403
1408
|
* \`<bulb-dir>/<filename-stem>/\`, created on demand), so
|
|
1404
1409
|
* \`tb.fs.write('results.json')\` lands beside the bulb. \`../\` reaches sibling
|
|
1405
1410
|
* bulbs' folders; everything stays confined to the project (the launch cwd).
|
|
@@ -1412,15 +1417,16 @@ type AiChunk =
|
|
|
1412
1417
|
readBytes(path: string): Promise<Uint8Array>;
|
|
1413
1418
|
/** Write text or raw bytes to a file. Creates parent directories if needed. */
|
|
1414
1419
|
write(path: string, content: string | Uint8Array): Promise<boolean>;
|
|
1415
|
-
};`,
|
|
1420
|
+
};`,vg=`
|
|
1416
1421
|
/**
|
|
1417
|
-
* The bulb's
|
|
1422
|
+
* The bulb's folder \u2014 absolute path to \`<bulb-dir>/<filename-stem>/\`
|
|
1423
|
+
* (or its subfolder when the run is scoped with \`--dir\`).
|
|
1418
1424
|
*
|
|
1419
1425
|
* For interop only (handing a path to \`server.ts\` or a spawned tool):
|
|
1420
1426
|
* \`tb.fs\` already resolves relative paths against it, so bulb code writing
|
|
1421
1427
|
* its own files never needs it. CLI only \u2014 throws in editor/published/embedded mode.
|
|
1422
1428
|
*/
|
|
1423
|
-
readonly dir: string;`,
|
|
1429
|
+
readonly dir: string;`,pT=`
|
|
1424
1430
|
/**
|
|
1425
1431
|
* Async value inspector for tensor-like objects.
|
|
1426
1432
|
*
|
|
@@ -1487,7 +1493,7 @@ type AiChunk =
|
|
|
1487
1493
|
*
|
|
1488
1494
|
* @returns The full canonical URL
|
|
1489
1495
|
*/
|
|
1490
|
-
url(): Promise<string>;`,
|
|
1496
|
+
url(): Promise<string>;`,mT=`
|
|
1491
1497
|
/**
|
|
1492
1498
|
* Subscribe to a value pushed from the terminal via \`typebulb send <file> [message]\`.
|
|
1493
1499
|
*
|
|
@@ -1502,39 +1508,39 @@ type AiChunk =
|
|
|
1502
1508
|
* @param handler - Called with each pushed message.
|
|
1503
1509
|
* @returns An unsubscribe function.
|
|
1504
1510
|
*/
|
|
1505
|
-
onMessage(handler: (message: any) => void): () => void;`,
|
|
1511
|
+
onMessage(handler: (message: any) => void): () => void;`,hT="\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>>;",Bl=`${gg}
|
|
1506
1512
|
/**
|
|
1507
1513
|
* Typebulb utilities namespace.
|
|
1508
1514
|
* Type \`tb.\` to discover available helpers.
|
|
1509
1515
|
*/
|
|
1510
|
-
declare const tb: {${
|
|
1516
|
+
declare const tb: {${lT}${pT}${uT}${hT}${mT}${yg}${dT}${vg}${bg}${fT}${wg}
|
|
1511
1517
|
};
|
|
1512
|
-
`,jl=`${
|
|
1518
|
+
`,jl=`${gg}
|
|
1513
1519
|
/**
|
|
1514
1520
|
* Typebulb utilities namespace (server-side).
|
|
1515
1521
|
* Type \`tb.\` to discover available helpers.
|
|
1516
1522
|
*/
|
|
1517
|
-
declare const tb: {${
|
|
1523
|
+
declare const tb: {${yg}${vg}${bg}${wg}
|
|
1518
1524
|
};
|
|
1519
|
-
`;import
|
|
1525
|
+
`;import wT from"p-limit";import{resolve as kg}from"resolve.exports";var We={maxRelativeTypeRefs:500,maxBareDeps:8,maxBareDepth:3,prefetchConcurrency:4,negativeTtlMs:1e4},jn=["index.d.ts","index.d.mts"],Fl=/\.d\.(ts|mts|cts)$/i;function lo(r){return/\.d\.(ts|mts|cts)(?:[?#].*)?$/i.test(r)||/[?&]dts(?:[&#]|$)/i.test(r)}function Sg(r){return[`${r}.d.ts`,`${r}.d.mts`]}function bt(r){if(!r||r==="./"||r==="/")return[...jn];let e=r.replace(/\.(mjs|cjs|js|mts|cts|ts)$/i,""),t=Sg(e),n=e.endsWith("/")?e:`${e}/`;return t.push(...Sg(`${n}index`)),t}async function Nr(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(gT(a.status)&&s<e)continue;return a}catch{if(s<e)continue;return}finally{clearTimeout(o)}}}function gT(r){return r===408||r===429||r>=500&&r<600}var uo=class{constructor(e,t){this.fetchDts=e,this.cdnClient=t}async tryUrls(e){for(let t of e){let n=await this.fetchDts(t);if(n&&(this.looksLikeDts(n.dts)||lo(n.url)))return n}}looksLikeDts(e){return/^\s*export\s*\{\s*\}\s*;?\s*$/m.test(e)?!0:/declare\s+(module|namespace|class|interface|function|const|var|let)/.test(e)||/interface\s+\w+/.test(e)||/type\s+\w+\s*=/.test(e)}async loadPackageAtVersionedRoot(e,t){let n=this.cdnClient.packageJson(new D({name:e,version:t})),s=await Nr(n);if(!s?.ok)return;let i;try{i=await s.json()}catch{return}if(i)return{pkg:i,baseDir:this.cdnClient.baseDir(new D({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=_t(e.path);if(!o||o==="/"||o===".")return this.tryUntilSuccess([...jn],t);if(!Fl.test(o)){let a=await this.tryUntilSuccess(bt(o),t);if(a)return a}return t(o)}let s=bt(e.path),i=n?.subpath?[...s,...jn]:[...jn,...s];return this.tryUntilSuccess(i,t)}toResolutionResult(e){return{kind:Fl.test(e)?"types":"probe",path:e}}resolveExportsPath(e,t){let n=t||".",s=e;try{let i=this.extractPathFromResult(kg(s,n,{conditions:["types"]}));if(i)return i}catch{}try{return this.extractPathFromResult(kg(s,n,{browser:!0,conditions:["import","default","module","browser","node"]}))}catch{return}}async resolve(e){try{let t=D.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 D(i).format(),a=new D({...i,subpath:t.subpath}).format(),c=u=>this.fetchCandidateFrom(s,t.name,u);if(t.subpath){let u=kc(t.subpath),d=this.resolveExportsPath(n,u);if(d){let y=await this.resolveFromSelected(this.toResolutionResult(d),c,{subpath:!0});if(y)return{...y,resolvedPkg:a}}let p=await this.tryUntilSuccess(bt(u),c);if(p)return{...p,resolvedPkg:a}}let l=n.types??n.typings;if(l){let u=await this.resolveFromSelected({kind:"types",path:l},c);if(u)return{...u,resolvedPkg:o}}let f=this.resolveExportsPath(n,".");if(f){let u=await this.resolveFromSelected(this.toResolutionResult(f),c);if(u)return{...u,resolvedPkg:o}}return}catch{return}}async fetchCandidateFrom(e,t,n){let s=_t(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 yT}from"fflate";var fo=class{async fetchAndExtract(e,t){let n=this.getTarballUrl(e,t),s=await Nr(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=yT(e),s=new TextDecoder("utf-8"),i=0;for(;i<n.length-512;){let o=n.slice(i,i+512);if(o[0]===0)break;let a=o.slice(0,100),c=a.indexOf(0),l=s.decode(a.slice(0,c>0?c:100)).trim(),f=o.slice(124,136),u=s.decode(f).trim().replace(/\0/g,""),d=parseInt(u,8)||0,p=String.fromCharCode(o[156]);if(i+=512,(p==="0"||p==="\0")&&(l.endsWith(".d.ts")||l.endsWith(".d.mts"))){let y=n.slice(i,i+d);t.set(this.normalizeTarPath(l),s.decode(y))}i+=Math.ceil(d/512)*512}}catch{}return t}};var po=class{constructor(e,t,n=new fo){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=Rt.majorOf(n),o=e.filter(a=>Rt.majorOf(a)===i);if(o.length)return o.sort((a,c)=>Rt.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=bt(e);return t!==e&&n.push(`${e}.d.ts`,`${e}/index.d.ts`),n}async fetchFromVersionedRoot(e,t){let n=new D(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 D(t).format():t.name}}}async resolve(e){let t=D.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 mo=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(`
|
|
1520
1526
|
`).filter(s=>{let i=s.trimStart();return!(i.startsWith("*")||i.startsWith("//")||i.startsWith("/*"))}).join(`
|
|
1521
|
-
`),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
|
|
1522
|
-
`);await this.prefetchBareDeps(y,l,
|
|
1523
|
-
`,"utf8"),await
|
|
1524
|
-
`,"utf8"),{dir:e}}function
|
|
1525
|
-
`))console.log(`${e} ${n}`);return r.length>0}function
|
|
1527
|
+
`),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 xg="file:///node_modules",ho=class{constructor(){this.epoch=0}bumpEpoch(){this.epoch+=1}epochDir(){return`__tsepoch_${this.epoch}`}pathForMain(e){return`${xg}/${this.epochDir()}/${e}/index.d.ts`}pathFor(e,t){let n=_t(t);return`${xg}/${this.epochDir()}/${e}/${n}`}};import{LRUCache as bT}from"lru-cache";function Eg(r){let e=new bT({ttl:We.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 Nr(s,{init:{cache:"no-store"}});if(!c?.ok){c?.status===404&&(e.set(s,!0),await r.recordNegative(s));return}let l=await c.text(),f=c.url||s;return await r.clearNegative(s),await r.setCachedFile(f,l),{dts:l,url:f}})();return t.set(s,a),await a.finally(()=>t.delete(s))}catch{return}}}var Fn=class{constructor(e){this.inFlight=new Map,this.scanner=new mo,this.cache=e.cache,this.cdnClient=e.cdnClient,this.versionResolver=e.versionResolver,this.packageService=e.packageService,this.fetchDts=Eg(e.cache),this.typescriptProvider=new uo(this.fetchDts,e.cdnClient),this.definitelyTypedProvider=new po(e.cdnClient,e.cache),this.virtualFs=new ho}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 D(n).subpath===new D(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>We.maxRelativeTypeRefs)))try{let a=new URL(t),c=new URL("./",a);o??(o=this.extractPackageRootUrl(a));let l=this.scanner.collectRelativeTypeRefs(e).slice(0,We.maxRelativeTypeRefs);for(let f of l)await this.tryRelativeRef(f,c,o,n,s,i)}catch{}}async tryRelativeRef(e,t,n,s,i,o){try{let a=new URL(e,t),c=a.pathname+a.search,l=lo(c)?[c]:bt(c);for(let f of l){let d=new URL(f,a).toString();if(o.has(d))return;let p=await this.fetchDts(d);if(p?.dts){let 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 D(e).name!==new D(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,We.maxBareDeps).filter(l=>this.isDifferentPackage(l,t));if(!o.length)return;let a=new Set([t]),c=wT(We.prefetchConcurrency);await Promise.all(o.map(l=>c(()=>this.prefetchBareDepsRecursive(l,n,s,We.maxBareDepth,a,i).catch(()=>{}))))}catch{}}async prefetchBareDepsRecursive(e,t,n,s,i,o){if(s<=0||i.has(e))return;i.add(e);let a=await this.fetchRootDts(e,o);if(!a?.dts)return;let c=a.resolvedPkg||e,l=this.virtualFs.pathForMain(c);this.pushFileIfNew(t,l,a.dts),this.ambientlyDeclares(a.dts,e)?this.markFileAmbient(t,l):n.push({module:e,path:l}),a.url&&await this.expandRelativeRefs(a.dts,a.url,c,t);let f=this.scanner.collectBareModuleRefs(a.dts).slice(0,We.maxBareDeps).filter(u=>!i.has(u));for(let u of f)await this.prefetchBareDepsRecursive(u,t,n,s-1,i,o)}async resolve(e,t,n){let s=await this.packageService.extractImports(e),i=n?[...s,...n]:s;return(await Promise.all(i.map(a=>this.resolveOne(a,t)))).filter(a=>!!a)}async resolveOne(e,t){let{effectivePackage:n}=await this.versionResolver.effectivePackage(e,t);return this.withInFlight(n,async()=>{let s=new D(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 D(a||n),l=c.version?`${c.name}@${c.version}`:c.name,{mainPath:f,packageRootUrl:u}=this.computeEntryPath(o,l),d=[{path:f,content:i}],p=[];o&&await this.expandRelativeRefs(i,o,l,d,void 0,u);let y=d.map(x=>x.content).join(`
|
|
1528
|
+
`);await this.prefetchBareDeps(y,l,d,p,s);let m=c.format(),b=e===m?[e]:[e,m],k=b.some(x=>this.ambientlyDeclares(i,x));return k?this.markFileAmbient(d,f):p.push(...b.map(x=>({module:x,path:f}))),{pkg:e,mainPath:f,files:d,shims:p,ambient:k}}};import*as Ir from"path";var vT=Ir.join(ei,"pkg"),ST=Ir.join(ei,"files"),kT=Ir.join(ei,"negative.json"),yo=class{pkgMem=new Map;fileMem=new Map;negativeCache=new Nt(new fr(kT));async getCachedDts(e){if(this.pkgMem.has(e))return this.pkgMem.get(e);await H();let t=await Fe(Ag(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 go(async()=>{await H(),await me(Ag(e),JSON.stringify(s))})}async getCachedFile(e){if(this.fileMem.has(e))return this.fileMem.get(e);await H();let t=await Zs(Tg(e));return this.fileMem.set(e,t),t}async setCachedFile(e,t){this.fileMem.set(e,t),await go(async()=>{await H(),await me(Tg(e),t)})}isNegative(e){return this.negativeCache.isNegative(e)}async recordNegative(e){await go(async()=>{await H(),await this.negativeCache.recordNegative(e)})}clearNegative(e){return go(()=>this.negativeCache.clearNegative(e))}};async function go(r){try{await r()}catch{}}function Ag(r){return Ir.join(vT,ve(r)+".json")}function Tg(r){return Ir.join(ST,ve(r)+".txt")}var ql;function xT(){return ql||(ql=new Fn({cache:new yo,cdnClient:Hp,packageService:si,versionResolver:Kp})),ql}var Pg="file:///node_modules/";async function Og(r){let e=ti(r.emitKey,"typecheck");await H(),await ie.rm(e,{recursive:!0,force:!0}),await ie.mkdir(e,{recursive:!0});let t=PT(r.jsxImportSource,r.dependencies),n=await xT().resolve(r.code,r.dependencies,t),s=r.local?.name,i=s?n.filter(f=>f.pkg!==s):n,o=new Set;for(let f of i)for(let u of f.files){let d=bo(u.path);if(!d||o.has(d))continue;o.add(d);let p=re.join(e,"node_modules",d);await ie.mkdir(re.dirname(p),{recursive:!0}),await ie.writeFile(p,u.content,"utf8")}let a={};for(let f of i)for(let u of f.shims){let d=bo(u.path);d&&(a[u.module]=[`./node_modules/${d}`])}for(let f of i){if(f.ambient)continue;let u=bo(f.mainPath);u&&(a[f.pkg]=[`./node_modules/${u}`])}let c=new Set;for(let f of i)for(let u of f.files){if(!u.ambient)continue;let d=bo(u.path);d&&c.add(`node_modules/${d}`)}if(r.local){delete a[r.local.name];let f=await OT(r.local,e);f?a[r.local.name]=[`./node_modules/${r.local.name}/${f}`]:console.warn(` local: '${r.local.name}' ships no type defs; check cannot type against it.`)}let l=ET(r.jsxImportSource,a,[...c]);return await ie.writeFile(re.join(e,"tsconfig.json"),JSON.stringify(l,null,2)+`
|
|
1529
|
+
`,"utf8"),await ie.writeFile(re.join(e,"code.tsx"),r.code,"utf8"),await ie.writeFile(re.join(e,"tb.d.ts"),Bl,"utf8"),{dir:e}}var Ul={target:"es2023",module:"esnext",moduleResolution:"bundler",strict:!0,noEmit:!0,skipLibCheck:!0,esModuleInterop:!0,allowSyntheticDefaultImports:!0,forceConsistentCasingInFileNames:!0};function ET(r,e,t=[]){return{compilerOptions:{...Ul,lib:AT([...Ll,...Ml]),jsx:"react-jsx",jsxImportSource:r??"react",paths:e},include:["code.tsx","tb.d.ts",...t]}}function AT(r){return Dl(r).map(e=>TT(e.name))}function TT(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 PT(r,e){let t=r??("react"in e?"react":void 0);return t?[`${t}/jsx-runtime`,`${t}/jsx-dev-runtime`]:[]}function bo(r){if(!r.startsWith(Pg))return;let e=r.slice(Pg.length),t=e.indexOf("/");if(!(t<0))return e.slice(t+1)}async function OT(r,e){if(!r.typesAbs)return;let t=re.dirname(r.typesAbs),n=re.join(e,"node_modules",r.name);for(let s of await CT(t)){let i=re.join(n,re.relative(t,s));await ie.mkdir(re.dirname(i),{recursive:!0}),await ie.copyFile(s,i)}return re.basename(r.typesAbs)}async function CT(r){let e=[];async function t(n){let s=await ie.readdir(n,{withFileTypes:!0});for(let i of s){let o=re.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 ye from"fs/promises";import*as Ye from"path";import{existsSync as _T}from"fs";var RT="^22";async function Cg(r){let e=ti(r.emitKey,"typecheck-server");await H(),await ye.rm(e,{recursive:!0,force:!0}),await ye.mkdir(e,{recursive:!0});let t=Ye.join(r.bulbDir,".typebulb"),n=fi(r.server).filter(o=>o!==r.local?.name);await ui([`@types/node@${RT}`,...n],t,r.dependencies,{ignoreScripts:!0});let s=Ye.join(t,"node_modules"),i=Ye.join(e,"node_modules");return await IT(s,i),await ye.writeFile(Ye.join(e,"server.ts"),r.server,"utf8"),await ye.writeFile(Ye.join(e,"tb.d.ts"),jl,"utf8"),await ye.writeFile(Ye.join(e,"tsconfig.json"),JSON.stringify(NT(r.local),null,2)+`
|
|
1530
|
+
`,"utf8"),{dir:e}}function NT(r){let e={...Ul,lib:["ES2023"],types:["node"]};if(r?.typesAbs){let t=i=>i.replace(/\\/g,"/"),n=t(Ye.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 IT(r,e){if(!_T(r)){await ye.mkdir(e,{recursive:!0});return}await ye.rm(e,{recursive:!0,force:!0});let t=process.platform==="win32"?"junction":"dir";await ye.symlink(r,e,t)}Qs();async function Rg(r,e){let{bulb:t,config:n,warnings:s}=await xe(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=_g(yn(t.code,{target:"client",dependencies:n.dependencies??{}}),"client")||i),t.server&&(i=_g(yn(t.server,{target:"server"}),"server")||i);let o=FT([process.cwd(),wt.dirname(r)]);if(!o){let l=wt.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 Og({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 Cg({server:t.server,bulbDir:wt.dirname(r),emitKey:r,local:e?{name:e.name,typesAbs:e.typesAbs}:void 0,dependencies:n.dependencies});a.push({role:"server",dir:l})}for(let{role:l,dir:f}of a){let{stdout:u,exitCode:d}=await BT(o,f);for(let p of u.split(/\r?\n/))p.trim()&&console.log(`${l} ${p}`);d!==0&&(i=!0)}i&&process.exit(1);let c=[t.code&&"code.tsx",t.server&&"server.ts"].filter(Boolean).join(", ");console.error(`\u2713 no issues (${c})`)}function _g(r,e){for(let t of r)for(let n of t.message.split(`
|
|
1531
|
+
`))console.log(`${e} ${n}`);return r.length>0}function BT(r,e){return new Promise(t=>{let n=$T(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 jT=MT(import.meta.url);function FT(r){let e=n=>{try{let s=jT.resolve("typescript/package.json",{paths:n}),i=wt.join(wt.dirname(s),"lib","tsc.js");return DT(i)?i:void 0}catch{return}},t=e(r);if(t)return t;try{let n=LT("npm root -g",{encoding:"utf8"}).trim();return e([n])}catch{return}}Li();Cn();async function Ng(r,e){let{bulb:t}=await xe(r),n=kr(t);if(Bt(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.)")}Cn();import*as qn from"path";async function Ig(r,e){if(!r){e||(console.error("Usage: typebulb untrust <file.bulb.md>"),process.exit(1));let n=Wc();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=qn.resolve(r);t.endsWith(".bulb.md")||(console.error("File must have .bulb.md extension"),process.exit(1)),br(t,e),console.log(e?`Trusted ${qn.basename(t)} \u2014 runs with fs / AI / server.ts (no --trust needed).`:`Untrusted ${qn.basename(t)} \u2014 runs Restricted.`),console.log(` ${t}`)}Ne();import*as Dg from"readline";var Un=pg();function $g(){for(let r of Object.values(Un))try{r().ensureHarnessSupport()}catch{}}function Jn(){for(let r of Object.keys(Un))try{if(Un[r]().detectsSelf())return r}catch{}}function Lg(r){let e=Rr(),t=new Map(e.filter(i=>Un[i]).map(i=>[i,Un[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)))}}Mi();function Jl(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 Bg(r){let e=Lg(process.cwd());if("ambiguous"in e){let t=await qT(r,e.ambiguous);return t?Mg(r,t):UT(r,e.ambiguous)}return Mg(r,e.name)}async function Mg(r,e){let t,n;try{t=await Tm(e)}catch(f){n=f instanceof Error?f.message:String(f)}let{lit:s,litLink:i,brand:o}=Jl(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(xr())}`,` ${s(qt())}`],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(`
|
|
1526
1532
|
`)+`
|
|
1527
|
-
`)}async function
|
|
1533
|
+
`)}async function qT(r,e){if(!process.stdin.isTTY||!process.stdout.isTTY)return;let{lit:t,brand:n}=Jl(!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(`
|
|
1528
1534
|
`)+`
|
|
1529
|
-
`);let i=
|
|
1535
|
+
`);let i=Dg.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 UT(r,e){let{lit:t,brand:n}=Jl(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(`
|
|
1530
1536
|
`)+`
|
|
1531
|
-
`)}mt();Dt();async function
|
|
1532
|
-
`+e)}function Hl(r,e,t,n,s){let i=
|
|
1537
|
+
`)}mt();Dt();async function jg(r){ge(r);let e=await Ue();if(e.length>0){console.log(sm(e,process.env.TB_AI_PROVIDER,process.env.TB_AI_MODEL));return}if(!qc()){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(gr))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.")}Mi();import*as Fg from"fs/promises";async function qg(r){let e=qt(),t;try{t=await Fg.readFile(e,"utf8")}catch{console.error(`Could not read the bundled README (expected at ${e}).`),process.exit(1)}process.stdout.write(Lm(t,r))}xi();import*as Ug from"path";Ne();function JT(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&&ee(o.cwd)===ee(t));return n&&i.find(o=>o.agent===n)||i[0]}return r.find(i=>ee(i.file)===ee(e))}var Kn=r=>r.agent??Ug.basename(r.file);function Jg(r,e){for(let t of r)e(` ${t.url} pid ${t.pid} ${t.trust?"trusted":"restricted"} ${t.file}`)}function Kl(r,e){if(!r.length){console.log("No running bulb servers.");return}console.log("Running bulb servers:"),Jg(r,t=>console.log(t)),console.log(`
|
|
1538
|
+
`+e)}function Hl(r,e,t,n,s){let i=JT(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>\`):`),Jg(r,o=>console.error(o))):console.error("No bulb servers are running."),process.exit(1)}async function Kg(r,e){if(!r){e.clear&&(console.error("Specify which server to clear: typebulb logs --clear <file|pid>"),process.exit(1)),Kl(await Y(process.cwd()),"Run `typebulb logs <file|pid>` to print one server's console.");return}let t=Hl(await Y(),r,"logs",process.cwd(),Jn());if(e.clear){vm(t.pid),console.log(`Cleared log for ${Kn(t)} (pid ${t.pid}).`);return}let n=Re(t.pid),s=n.text;if(e.run!==void 0&&(s=Sm(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(`
|
|
1533
1539
|
`);i.length&&i[i.length-1]===""&&i.pop(),s=i.slice(-e.lines).join(`
|
|
1534
1540
|
`)}if(process.stdout.write(s),s&&!s.endsWith(`
|
|
1535
1541
|
`)&&process.stdout.write(`
|
|
1536
|
-
`),e.follow&&e.run===void 0){let i=n.offset,o=setInterval(()=>{let c=Re(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
|
|
1537
|
-
`);m=x.pop()??"";for(let T of x)T.trim()&&(e.match&&!T.includes(e.match)||(console.log(T),y??=Date.now()+
|
|
1542
|
+
`),e.follow&&e.run===void 0){let i=n.offset,o=setInterval(()=>{let c=Re(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 KT=r=>new Promise(e=>setTimeout(e,r));async function Hg(r,e){if(!r){Kl(await Y(process.cwd()),"Run `typebulb wait <file|pid>` to block until one logs a new line.");return}let t=Hl(await Y(),r,"wait",process.cwd(),Jn()),n=t.agent!=null,i=process.env.TYPEBULB_WAIT_SHIM==="1",o=e.timeoutSec??1800,a=e.match??"",c=Re(t.pid).offset,l=nl(t.pid,a)??(a?nl(t.pid):void 0),f=l!==void 0&&l<=c?l:a?0:c,u=Date.now()+o*1e3,d=n?1e4:1e3,p=2e3,y,m="",b=0;for(;;){let k=Re(t.pid,f);if(f=k.offset,k.text){m+=k.text;let x=m.split(`
|
|
1543
|
+
`);m=x.pop()??"";for(let T of x)T.trim()&&(e.match&&!T.includes(e.match)||(console.log(T),y??=Date.now()+d,n&&(T.includes("] compile error")||T.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 ${Kn(t)} within ${o}s`),b=2;break}if(!il(t.pid)){y||(console.error(`server ${Kn(t)} (pid ${t.pid}) exited while waiting`),process.exit(3));break}await KT(400)}_i(t.pid,f,a),process.exit(b)}async function Wg(r){if(!r){Kl(await Y(process.cwd()),"Run `typebulb stop <file|pid>` to stop one.");return}let e=Hl(await Y(),r,"stop",process.cwd(),Jn());await jt(e.pid),console.log(`Stopped ${Kn(e)} (pid ${e.pid}, ${e.url}).`)}async function Yg(r){let e=process.cwd(),t=r==="agent"?Jn():void 0,n=r==="global"?await Y():r==="bulbs"?await Y(e):(await Y()).filter(i=>i.agent!=null&&i.cwd!=null&&ee(i.cwd)===ee(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=>jt(i.pid))),console.log(`Stopped ${n.length} ${s}${n.length===1?"":"s"}:`);for(let i of n)console.log(` ${i.url} pid ${i.pid} ${Kn(i)}`)}Ne();import*as Vg from"path";async function Gg(r,e,t=0){let n=Vg.resolve(r),s=Sr(await Y(),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.")}qi();hl();mt();import*as $r from"fs/promises";import*as ry from"path";import{EventEmitter as ty}from"events";je();Li();import oP from"open";hr();je();import{Hono as zT}from"hono";import{serve as QT}from"@hono/node-server";import{streamSSE as XT}from"hono/streaming";import*as Yt from"fs/promises";import*as Te from"path";import*as Wl from"fs/promises";import*as Hn from"path";var wo=class{async get(e){let t=ve(e),n=Hn.join(En,t+".bin"),s=Hn.join(En,t+".json");try{let[i,o]=await Promise.all([Wl.readFile(n),Wl.readFile(s,"utf8")]),a=JSON.parse(o);return{body:i,contentType:a.contentType,cacheControl:a.cacheControl}}catch{return}}async set(e,t){await H();let n=ve(e),s=Hn.join(En,n+".bin"),i=Hn.join(En,n+".json"),o={url:e,contentType:t.contentType,cacheControl:t.cacheControl};await Promise.all([me(s,t.body),me(i,JSON.stringify(o))])}};var zg=`
|
|
1538
1544
|
const CSS = '\\n' +
|
|
1539
1545
|
/* The agent mirror's token set, verbatim (agents/core/client/styles.css) \u2014 one system across CLI
|
|
1540
1546
|
chrome: app chrome sits on --panel, content wells paint --veil, grays ride one neutral tint.
|
|
@@ -1838,17 +1844,17 @@ export function runInference(ctx) {
|
|
|
1838
1844
|
showConfirm();
|
|
1839
1845
|
document.body.appendChild(host);
|
|
1840
1846
|
}
|
|
1841
|
-
`;Ne();Dt();vi();hr();import{stream as
|
|
1842
|
-
${
|
|
1843
|
-
`+te.slice(-4e3)),new ue("LLM output is not valid JSON","parse_error",!0);z.fixesApplied.length&&console.warn("[tb.infer] sanitized output, fixes applied:",z.fixesApplied.join(", "));let St={insight:z.parsed,insightJson:z.json,data:N};yield{kind:"complete",...St,fixesApplied:z.fixesApplied,hash:Bc(St)}})();return vo(h,vt)}catch(S){return h.json(Wn(S),500)}});let T=async h=>{let{hash:S}=await h.req.json().catch(()=>({}));return typeof S=="string"?jc(S):null};m.post("/__infer-save",async h=>{try{if(!l)return h.json({message:"Save is not available for this server.",code:"unknown",retryable:!1},400);let S=await T(h);return S?(await l(S.data,S.insightJson),h.json({ok:!0})):h.json({message:"No decodable #tb= fragment to save.",code:"unknown",retryable:!1},400)}catch(S){return h.json(Wn(S),500)}}),m.get("/__infer-info",h=>{let S=c?.(),I=Lr(S?.config??"").inference,L=Gs(S?.data??""),N=Je();return typeof N=="string"?h.json({error:N,inference:I,data:L}):h.json({provider:N.protocol,model:N.model,inference:I,data:L})}),m.use("/__infer-decode",x),m.post("/__infer-decode",async h=>h.json(await T(h)??{error:"invalid fragment"})),m.get("/__infer-ui.js",h=>h.body(
|
|
1844
|
-
${s}`),console.log(` ${c}`),o!==e&&console.log(` (port ${e} was busy)`);let l=[],
|
|
1845
|
-
Shutting down...`),a.close();for(let u of l)try{await u()}catch{}i(),await Nn(process.pid),process.exit(0)};return process.on("SIGINT",
|
|
1847
|
+
`;Ne();Dt();vi();hr();import{stream as HT}from"hono/streaming";var WT="X-TB-Stream";function Wn(r){return r instanceof ue?{message:r.message,code:r.code,retryable:r.retryable}:{message:r instanceof Error?r.message:"Unknown error",code:"unknown",retryable:!1}}function vo(r,e){return r.header("Content-Type","application/x-ndjson; charset=utf-8"),r.header("Cache-Control","no-cache"),r.header(WT,"1"),HT(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:Wn(s)}))}finally{try{await n.return?.()}catch{}}})}var So={log:(...r)=>console.log(...r)};function ko(r,e){let t=r?.[e]??(Object.hasOwn(So,e)?So[e]:void 0);return typeof t=="function"?t:void 0}function xo(r){return r.constructor?.name==="AsyncGeneratorFunction"}var YT=/^\/(v\d+\/|stable\/|node\/|gh\/|@[^/]+\/[^@/]+@|[^@/]+@)/,VT=/[?&]target=/,GT=/^\/(?:@[^/]+\/)?[^/@]+\/[^/]+/;function Qg(r,e=""){return YT.test(r)?!0:GT.test(r)&&VT.test(e)}var Zg="127.0.0.1",ZT=new Set(["localhost","127.0.0.1","::1"]);function eP(r){if(r)try{return new URL(r.includes("://")?r:`http://${r}`).hostname}catch{return}}function tP(r){let e=eP(r);return!!e&&ZT.has(e)}function rP(r,e){if(!e)return!1;try{return new URL(r).host===e}catch{return!1}}function Yl(r){return r instanceof Error?r.message:"Unknown error"}async function ey(r){let{getHtml:e,basePath:t,fsBase:n,port:s,reloadEmitter:i,messageEmitter:o,getServerExports:a,getBulbBlocks:c,saveInferenceResult:l,localOverride:f,trusted:u=!1,trustHint:d,staticAssets:p}=r,y=n??t,m=new zT;m.use("*",async(h,S)=>{if(!tP(h.req.header("host")))return h.text("Forbidden: untrusted Host",403);await S()}),m.use("*",async(h,S)=>{await S(),h.res.headers.set("Cross-Origin-Opener-Policy","same-origin"),h.res.headers.set("Cross-Origin-Embedder-Policy","credentialless")});let b=[["/__fs/*","the filesystem"],["/__api/*","server-side code (server.ts)"],["/__ai","AI (your API keys)"],["/__infer","AI (your API keys)"],["/__infer-save","the filesystem"]],k=async(h,S)=>{if(!u){let I=new URL(h.req.url).pathname,L=b.find(([X])=>X.endsWith("/*")?I.startsWith(X.slice(0,-2)):I===X)?.[1]??"server-side code (server.ts)";xm(process.pid,L);let N=d?`
|
|
1848
|
+
${d}`:"";return h.text(`Forbidden: this capability requires --trust.${N}`,403)}await S()},x=async(h,S)=>{let I=h.req.header("sec-fetch-site");if(I){if(I!=="same-origin")return h.text(`Forbidden: ${I} request`,403)}else{let L=h.req.header("origin");if(L&&!rP(L,h.req.header("host")))return h.text("Forbidden: cross-origin request",403)}await S()};for(let[h]of b)m.use(h,k),m.use(h,x);m.use("/__log",x),m.post("/__log",async h=>{try{let{args:S}=await h.req.json();console.log(...S||[])}catch{}return h.json({ok:!0})}),o&&(m.use("/__send",x),m.post("/__send",async h=>{let S="";try{S=await h.req.text()}catch{}let I=o.listenerCount("message");return o.emit("message",S),h.json({clients:I})})),m.get("/",h=>h.html(e())),m.post("/__fs/read",async h=>{try{let{path:S}=await h.req.json(),I=Gl(S,y,t),L=await Yt.readFile(I);return new Response(new Uint8Array(L),{headers:{"Content-Type":"application/octet-stream"}})}catch(S){let I=Yl(S);return h.json({error:I},400)}}),m.post("/__fs/write",async h=>{try{let S=h.req.query("path");if(!S)return h.json({error:"Missing path"},400);let I=Gl(S,y,t);return await Yt.mkdir(Te.dirname(I),{recursive:!0}),await Yt.writeFile(I,Buffer.from(await h.req.arrayBuffer())),h.json({success:!0})}catch(S){let I=Yl(S);return h.json({error:I},400)}}),m.post("/__api/:name",async h=>{try{let S=h.req.param("name"),I=ko(a?.(),S);if(!I)return h.json({error:`API function '${S}' not found`},404);let{args:L}=await h.req.json();if(xo(I))return vo(h,I(...L||[]));let N=await I(...L||[]);return h.json({result:N})}catch(S){let I=Yl(S);return h.json({error:I},500)}}),m.post("/__ai",async h=>{try{let{messages:S,system:I,effort:L,provider:N,model:X,webSearch:fe,stream:vt}=await h.req.json();if(!S||!Array.isArray(S)||S.length===0)return h.json({message:"messages array is required",code:"unknown",retryable:!1},400);let te=Je(N,X);if(typeof te=="string")return h.json({message:te,code:"unknown",retryable:!1},400);let z=await ut(te,{messages:S,system:I,effort:L,webSearch:fe,signal:h.req.raw.signal});if(!z.ok){let Ve=await mr(z,te.protocol);return h.json(Ve,z.status)}if(vt)return vo(h,Mt(z,te.protocol));let St=await Lt(z,te.protocol);return St||console.warn("[tb.ai] Empty response from provider"),h.json({text:St})}catch(S){return h.json(Wn(S),500)}}),m.post("/__infer",async h=>{try{let{data:S}=await h.req.json().catch(()=>({})),I=c?.();if(!I?.infer.trim())return h.json({message:"This bulb has no infer.md block.",code:"unknown",retryable:!1},400);let L=Je();if(typeof L=="string")return h.json({message:L,code:"unknown",retryable:!1},400);let N=Array.isArray(S)?S.map(String):[],X=Mc(I,N),fe=await ut(L,{messages:[{role:"user",content:X}],signal:h.req.raw.signal});if(!fe.ok){let te=await mr(fe,L.protocol);return h.json(te,fe.status)}let vt=(async function*(){let te="";for await(let Ve of Mt(fe,L.protocol))Ve.kind!=="text"||!Ve.text||(te+=Ve.text,yield{kind:"delta",text:Ve.text});let z=Dc(te);if(z.parsed===null)throw console.warn(`[tb.infer] output not valid JSON after sanitize; raw output (last 4000 chars):
|
|
1849
|
+
`+te.slice(-4e3)),new ue("LLM output is not valid JSON","parse_error",!0);z.fixesApplied.length&&console.warn("[tb.infer] sanitized output, fixes applied:",z.fixesApplied.join(", "));let St={insight:z.parsed,insightJson:z.json,data:N};yield{kind:"complete",...St,fixesApplied:z.fixesApplied,hash:Bc(St)}})();return vo(h,vt)}catch(S){return h.json(Wn(S),500)}});let T=async h=>{let{hash:S}=await h.req.json().catch(()=>({}));return typeof S=="string"?jc(S):null};m.post("/__infer-save",async h=>{try{if(!l)return h.json({message:"Save is not available for this server.",code:"unknown",retryable:!1},400);let S=await T(h);return S?(await l(S.data,S.insightJson),h.json({ok:!0})):h.json({message:"No decodable #tb= fragment to save.",code:"unknown",retryable:!1},400)}catch(S){return h.json(Wn(S),500)}}),m.get("/__infer-info",h=>{let S=c?.(),I=Lr(S?.config??"").inference,L=Gs(S?.data??""),N=Je();return typeof N=="string"?h.json({error:N,inference:I,data:L}):h.json({provider:N.protocol,model:N.model,inference:I,data:L})}),m.use("/__infer-decode",x),m.post("/__infer-decode",async h=>h.json(await T(h)??{error:"invalid fragment"})),m.get("/__infer-ui.js",h=>h.body(zg,200,{"Content-Type":"text/javascript; charset=utf-8"})),m.get("/__models",async h=>{try{let S=await Ue();return h.json(S)}catch{return h.json([],200)}}),m.get("/__has-own-keys",async h=>{try{return h.json(await wi())}catch{return h.json(!1,200)}});let P=["esm.sh","unpkg.com","cdn.jsdelivr.net","cdnjs.cloudflare.com"],C=new wo;m.get("/proxy/*",async h=>{let S=new URL(h.req.url),L=(S.pathname+S.search).slice(7),N=L.lastIndexOf("https://");return N===-1?h.text("Invalid proxy URL",400):O(h,L.slice(N))}),f&&Xg(m,`/local/${f.name}/`,f.serveDir),p&&Xg(m,p.mount,p.dir);async function O(h,S){let I;try{I=new URL(S)}catch{return h.text("Invalid URL",400)}if(I.protocol!=="https:")return h.text("HTTPS only",400);if(!P.includes(I.hostname))return h.text("Host not allowed",403);let L=await C.get(S);if(L)return new Response(L.body,{status:200,headers:Vl(L.contentType,L.cacheControl)});try{let N=await fetch(S,{headers:{Accept:h.req.header("Accept")||"*/*"},redirect:"follow"});if(!N.ok)return h.text(`Upstream ${N.status}`,N.status);let X=N.headers.get("Content-Type")||void 0,fe=N.headers.get("Cache-Control")||void 0;if(N.body){let[vt,te]=N.body.tee();return(async()=>{try{let z=await new Response(te).arrayBuffer();await C.set(S,{body:Buffer.from(z),contentType:X,cacheControl:fe})}catch{}})(),new Response(vt,{status:N.status,headers:Vl(X,fe)})}return new Response(null,{status:N.status,headers:Vl(X,fe)})}catch(N){return h.text(`Proxy fetch failed: ${N instanceof Error?N.message:N}`,502)}}(i||o)&&m.get("/__reload",h=>XT(h,async S=>{let I=()=>{S.writeSSE({event:"reload",data:""})},L=N=>{S.writeSSE({event:"message",data:JSON.stringify(N)})};for(i?.on("reload",I),o?.on("message",L),S.onAbort(()=>{i?.removeListener("reload",I),o?.removeListener("message",L)});!S.aborted;)await S.sleep(3e4)})),m.notFound(async h=>{if(h.req.method!=="GET")return h.text("Not Found",404);let S=new URL(h.req.url);return Qg(S.pathname,S.search)?O(h,"https://esm.sh"+S.pathname+S.search):h.text("Not Found",404)});let R=QT({fetch:m.fetch,port:s,hostname:Zg});return{port:s,close:()=>R.close()}}function Vl(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 Xg(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=Gl(i,t),a=await Yt.readFile(o);return new Response(a,{headers:{"Content-Type":nP(o)}})}catch{return n.text("Not Found",404)}})}function nP(r){switch(Te.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 Gl(r,e,t=e){let n=Te.resolve(e,r),s=Te.normalize(t),i=Te.normalize(n);if(i!==s&&!i.startsWith(s+Te.sep))throw new Error("Path traversal detected - access denied");return n}async function zl(r){let e=await import("net");return new Promise(t=>{let n=e.createServer();n.listen(r,Zg,()=>{let s=n.address(),i=typeof s=="object"&&s?s.port:r;n.close(()=>t(i))}),n.on("error",()=>{t(zl(r+1))})})}Ne();async function Eo(r){let{portPreference:e,makeServerOptions:t,makeEntry:n,displayName:s,stopLog:i}=r,o=await zl(e),a=await ey(t(o)),c=`http://localhost:${o}`;await km(n(o,c)),console.log(`
|
|
1850
|
+
${s}`),console.log(` ${c}`),o!==e&&console.log(` (port ${e} was busy)`);let l=[],f=async()=>{console.log(`
|
|
1851
|
+
Shutting down...`),a.close();for(let u of l)try{await u()}catch{}i(),await Nn(process.pid),process.exit(0)};return process.on("SIGINT",f),process.on("SIGTERM",f),{port:o,url:c,onCleanup(u){l.push(u)}}}import sP from"chokidar";var iP={persistent:!0,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50}};function Vt(r){let{target:e,onChange:t,events:n="change",debounceMs:s=150}=r,i,o=sP.watch(e,iP),a=()=>{i&&clearTimeout(i),i=setTimeout(t,s)};return n==="all"?o.on("all",a):o.on("change",a),()=>{i&&clearTimeout(i),o.close()}}Ne();async function ny(r,e,t,n){let s=process.cwd(),i=Ri(process.pid),o=e.watch?new ty:void 0,a=new ty;a.setMaxListeners(0);let c=ge(e.mode),l=await al(r);l.length&&console.log(`Replacing the running server for this bulb (pid ${l.map(P=>P.pid).join(", ")})`);let f=1;console.log(sl(f)),console.log(`Loading ${ry.basename(r)}...`);let{html:u,bulb:d,serverExports:p}=await Jc(r,e.watch,e.trust,n,e.dir);pt(c,r,d.server);let y=e.trust?void 0:kr(d),{port:m,url:b,onCleanup:k}=await Eo({portPreference:e.port,displayName:d.name,stopLog:i,makeServerOptions:P=>({getHtml:()=>u,basePath:s,fsBase:Si(r,e.dir),port:P,reloadEmitter:o,messageEmitter:a,getServerExports:()=>p,getBulbBlocks:()=>({infer:d.infer,insight:d.insight,code:d.code,config:d.config,data:d.data}),saveInferenceResult:async(C,O)=>{let R=await $r.readFile(r,"utf-8");R=Io(R,"data",C.join(Ap)),R=Io(R,"insight",O),await $r.writeFile(r,R)},localOverride:n?{name:n.name,serveDir:n.serveDir}:void 0,trusted:e.trust,trustHint:t}),makeEntry:(P,C)=>({pid:process.pid,port:P,url:C,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:
|
|
1846
1852
|
${t}
|
|
1847
1853
|
`:` trust: restricted \u2014 re-run with --trust to enable filesystem / AI / server.ts
|
|
1848
1854
|
`),e.watch&&console.log(` Watching for changes...
|
|
1849
|
-
`);let x,T;if(e.watch&&o){let P=0,C=Promise.resolve();if(x=Vt({target:r,onChange:()=>{let O=++P;C=C.then(async()=>{if(O===P)try{console.log("Recompiling...");let R=await Jc(r,!0,e.trust,n);u=R.html,p=R.serverExports,
|
|
1855
|
+
`);let x,T;if(e.watch&&o){let P=0,C=Promise.resolve();if(x=Vt({target:r,onChange:()=>{let O=++P;C=C.then(async()=>{if(O===P)try{console.log("Recompiling...");let R=await Jc(r,!0,e.trust,n,e.dir);u=R.html,p=R.serverExports,d=R.bulb,f++,console.log(sl(f)),o.emit("reload")}catch(R){console.error("Compile error:",R)}})}}),n){let{name:O,serveDir:R}=n;T=Vt({target:R,events:"all",onChange:()=>{console.log(`Local package '${O}' changed. Browser reloading...
|
|
1850
1856
|
`),o.emit("reload")}})}}x&&k(x),T&&k(T),k(()=>$r.rm(Uc(r),{force:!0})),e.open&&(l.some(P=>P.port===m)?console.log(` Reusing the open browser tab.
|
|
1851
|
-
`):await
|
|
1857
|
+
`):await oP(b))}mt();import{readFileSync as iy,copyFileSync as cP,existsSync as lP}from"fs";import*as ne from"path";import{fileURLToPath as uP}from"url";import{EventEmitter as fP}from"events";import oy from"open";Ne();var Ql=r=>`/agents/${r}/client.js`,aP=`
|
|
1852
1858
|
(() => {
|
|
1853
1859
|
const api = async (name, ...args) => {
|
|
1854
1860
|
const resp = await fetch('/__api/' + name, {
|
|
@@ -1883,7 +1889,7 @@ Shutting down...`),a.close();for(let u of l)try{await u()}catch{}i(),await Nn(pr
|
|
|
1883
1889
|
es.onerror = () => { es.close(); };
|
|
1884
1890
|
}
|
|
1885
1891
|
})();
|
|
1886
|
-
`;function
|
|
1892
|
+
`;function sy(r){let{name:e,agent:t,styles:n,mountHtml:s,watch:i,theme:o}=r,a=Ql(t);return`<!DOCTYPE html>
|
|
1887
1893
|
<html>
|
|
1888
1894
|
<head>
|
|
1889
1895
|
<meta charset="utf-8">
|
|
@@ -1903,17 +1909,17 @@ ${s}
|
|
|
1903
1909
|
${i?"<script>window.__TYPEBULB_WATCH__ = true;</script>":""}
|
|
1904
1910
|
|
|
1905
1911
|
<script>
|
|
1906
|
-
${
|
|
1912
|
+
${aP}
|
|
1907
1913
|
</script>
|
|
1908
1914
|
|
|
1909
1915
|
<script type="module" src="${a}"></script>
|
|
1910
1916
|
</body>
|
|
1911
|
-
</html>`}async function
|
|
1912
|
-
${n.url}`),r.open&&await
|
|
1913
|
-
`);let x=ne.join(u,t,"client"),T=ne.join(u,"core","client");async function P(){await(await import("esbuild")).build({entryPoints:[ne.join(x,"index.ts")],bundle:!0,platform:"browser",format:"esm",outfile:ne.join(
|
|
1914
|
-
`),i.emit("reload")}catch(h){console.error("Mirror rebuild failed:",h instanceof Error?h.message:h)}finally{R=!1}}}})}r.open&&await
|
|
1915
|
-
`);let
|
|
1916
|
-
`)}catch(
|
|
1917
|
-
`),
|
|
1918
|
-
`),process.exit(1)}function
|
|
1919
|
-
${e}`),process.exit(1))}async function
|
|
1917
|
+
</html>`}async function ay(r){let e=process.cwd(),t=r.agentTarget;dg(t)||(console.error(`Unknown agent '${t}'. Known: ${Rr().join(", ")}.`),process.exit(1));let n=await ol(e,t);if(n){console.log(`Mirror '${t}' is already running for this project:
|
|
1918
|
+
${n.url}`),r.open&&await oy(n.url);return}let s=Ri(process.pid),i=r.watch?new fP:void 0,o=ge(r.mode),a=await mg(t),c=a.displayName||`${t} mirror`;pt(o,ne.join(e,"mirror"));let l=ne.dirname(uP(import.meta.url)),f=ne.join(l,"agents",t),u=ne.join(l,"..","cli","agents"),d=ne.join(f,"styles.css"),p=ne.join(f,"index.html"),y=()=>sy({name:c,agent:t,styles:iy(d,"utf8"),mountHtml:iy(p,"utf8"),watch:r.watch}),{port:m,url:b,onCleanup:k}=await Eo({portPreference:r.port,displayName:c,stopLog:s,makeServerOptions:O=>({getHtml:y,basePath:e,port:O,reloadEmitter:i,getServerExports:()=>a,trusted:!0,staticAssets:{mount:`${ne.posix.dirname(Ql(t))}/`,dir:f}}),makeEntry:(O,R)=>({pid:process.pid,port:O,url:R,file:`agent:${t}`,cwd:e,startedAt:Date.now(),trust:!0,agent:t})});r.watch&&console.log(` Watching for changes...
|
|
1919
|
+
`);let x=ne.join(u,t,"client"),T=ne.join(u,"core","client");async function P(){await(await import("esbuild")).build({entryPoints:[ne.join(x,"index.ts")],bundle:!0,platform:"browser",format:"esm",outfile:ne.join(f,"client.js")});for(let R of["styles.css","index.html","typebulb.png","typebulb-inv.png"])cP(ne.join(T,R),ne.join(f,R))}let C;if(r.watch&&i){let O=lP(x),R=!1;C=Vt({target:O?u:f,events:"all",onChange:async()=>{if(!R){R=!0;try{O&&await P(),console.log(`Mirror rebuilt. Browser reloading...
|
|
1920
|
+
`),i.emit("reload")}catch(h){console.error("Mirror rebuild failed:",h instanceof Error?h.message:h)}finally{R=!1}}}})}r.open&&await oy(b),k(()=>a.shutdownSwitcher?.()),k(()=>a.shutdownComposer?.()),C&&k(C)}mt();import*as cy from"path";async function ly(r,e,t,n,s){let i=ge(t),o=!1,a=async()=>{let{bulb:c,config:l}=await xe(r);o||(pt(i,r,c.server),o=!0),await On(c.server,r,n,l.dependencies,s)};if(console.log(`Running ${cy.basename(r)}...`),await a(),e){console.log(`Watching for changes...
|
|
1921
|
+
`);let c=0,l=Promise.resolve();Vt({target:r,onChange:()=>{let f=++c;l=l.then(async()=>{if(f===c)try{console.log("Re-running..."),await a()}catch(u){console.error("Error:",u)}})}})}}mt();import{Console as dP}from"node:console";Ne();async function dy(r,e,t,n,s){yP();try{let p=Sr(await Y(),r)[0];p&&(_i(p.pid,Re(p.pid).offset),console.error(`note: 'call' boots a fresh server.ts instance; the running server (${p.url}) is not contacted \u2014 state shared with it must live on disk.`))}catch{}let i=ge(t),{bulb:o,config:a}=await xe(r);o.server||Yn("This bulb has no **server.ts** block; nothing to call."),pt(i,r,o.server);let c;try{c=await On(o.server,r,n,a.dependencies,s)}catch(p){Yn(p instanceof Error?p.message:String(p))}let l=ko(c,e.fn);if(!l){let p=[...Object.keys(c).filter(y=>typeof c[y]=="function"),...Object.keys(So)];Yn(`Function '${e.fn}' not found. Available: ${p.length?p.join(", "):"(none)"}.`)}let f=await pP(e);if(xo(l)){try{for await(let p of l(...f))await fy(JSON.stringify(p,py)+`
|
|
1922
|
+
`)}catch(p){Yn(p instanceof Error?p.stack??p.message:String(p))}return uy(0)}let u;try{u=await l(...f)}catch(p){Yn(p instanceof Error?p.stack??p.message:String(p))}let d=gP(u);d!==void 0&&await fy(d+`
|
|
1923
|
+
`),uy(0)}function uy(r){process.exitCode=r,setTimeout(()=>process.exit(r),2e3).unref?.()}async function pP(r){if(r.hasArgsFlag){let e=r.argsJson??"";return e==="-"&&(e=await bP()),hP(e)}return mP(r.positional)}function mP(r){return r.map(e=>{try{return JSON.parse(e)}catch{return e}})}function hP(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 gP(r){if(r!==void 0)return JSON.stringify(r,py,2)}function py(r,e){return typeof e=="bigint"?e.toString():e}function Yn(r){process.stderr.write(r+`
|
|
1924
|
+
`),process.exit(1)}function yP(){let r=new dP(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 fy(r){return new Promise((e,t)=>{process.stdout.write(r,n=>n?t(n):e())})}async function bP(){let r=[];for await(let e of process.stdin)r.push(e);return Buffer.concat(r).toString("utf-8")}var Xl="0.29.0";function my(r,e){r||(console.error(`This bulb runs server-side Node code (server.ts), which --trust must authorize:
|
|
1925
|
+
${e}`),process.exit(1))}async function wP(){let r=mu(process.argv.slice(2));if(r.version&&(console.log(`typebulb ${Xl}`),process.exit(0)),r.help&&(hu(),process.exit(0)),$g(),r.subcommand==="logs"){await Kg(r.file||void 0,{follow:r.follow,clear:r.clear,run:r.run,lines:r.lines});return}if(r.subcommand==="wait"){await Hg(r.file||void 0,{match:r.match,timeoutSec:r.timeoutSec});return}if(r.subcommand==="stop"){r.stopScope?await Yg(r.stopScope):await Wg(r.file||void 0);return}if(r.subcommand==="send"){await Gg(r.file,r.sendMessage,r.sendWaitMs??0);return}if(r.subcommand==="skill"){await qg(Xl);return}if(r.subcommand==="models"){await jg(r.mode);return}if(r.subcommand==="pull"){await jm(r.file||void 0,{force:r.force,mode:r.mode});return}if(r.subcommand==="push"){await Um(r.file||void 0,{force:r.force,mode:r.mode});return}if(r.subcommand==="agent"){await(r.agentTarget?ay(r):Bg(Xl));return}if(r.subcommand==="trust"||r.subcommand==="untrust"){await Ig(r.file||void 0,r.subcommand==="trust");return}let e;if(!r.file||r.file==="."){let c=await am(process.cwd());c||(console.error("No .bulb.md file found in current directory"),process.exit(1)),e=c}else e=Gt.resolve(r.file);await hy.access(e).then(()=>!0,()=>!1)||(Rr().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:Gt.relative(process.cwd(),e)||Gt.basename(e),s=`npx typebulb --trust ${n.includes(" ")?`"${n}"`:n}`;if(r.subcommand==="predict"){await Ng(e,s);return}let i=!r.noTrust&&Bt(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 xe(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 fu(r.local)}catch(c){console.error(c instanceof Error?c.message:String(c)),process.exit(1)}console.error(`replace: ${a.name} \u2192 ${Gt.relative(process.cwd(),a.dir)||"."}`)}if(r.subcommand==="check"){await Rg(e,a);return}if(r.subcommand==="call"){my(r.trust,s),await dy(e,{fn:r.fn,positional:r.callArgs,argsJson:r.argsJson,hasArgsFlag:r.hasArgsFlag},r.mode,a,r.dir);return}if(o&&o.bulb.server&&(zs(o.bulb)||r.server)){my(r.trust,s),await ly(e,r.watch,r.mode,a,r.dir);return}await ny(e,r,s,a)}wP().catch(r=>{console.error("Error:",r.message),process.exit(1)});
|